Reformated using astyle, added some astyle scripts.

This commit is contained in:
Martin Rotter 2017-07-21 06:53:23 +02:00
parent 14473722b0
commit 208284e80d
304 changed files with 34084 additions and 34464 deletions

26
.astylerc Executable file
View File

@ -0,0 +1,26 @@
--style=java
--indent=spaces=2
--indent-classes
--indent-namespaces
--indent-switches
--indent-labels
--indent-preproc-define
--indent-col1-comments
--max-continuation-indent=100
--break-blocks=all
--unpad-paren
--delete-empty-lines
--pad-oper
--pad-comma
--pad-header
--align-pointer=type
--align-reference=type
--break-closing-braces
--break-one-line-headers
--add-braces
--convert-tabs
--close-templates
--max-code-length=200
--lineend=linux
-t -p
-M60Ucv

64
astyle-format-all.sh Executable file
View File

@ -0,0 +1,64 @@
#!/bin/bash
#
# This file is part of RSS Guard.
#
# Copyright (C) 2011-2017 by Martin Rotter <rotter.martinos@gmail.com>
# Copyright (C) 2010-2014 by David Rosca <nowrep@gmail.com>
#
# RSS Guard is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# RSS Guard is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with RSS Guard. If not, see <http:#www.gnu.org/licenses/>.
function usage {
echo "Usage: $0 \"root-directory\"..."
exit 1
}
if [ $# -eq 0 ]; then
usage
fi
ASTYLE_CMD="astyle"
ASTYLE_RC=".astylerc"
# Check all args.
for dir in "$@"; do
if [ ! -d "${dir}" ]; then
echo "\"${dir}\" is not a directory..."
usage
fi
done
# Run the thing.
for dir in "$@"; do
pushd "${dir}"
if [ ! -r "$ASTYLE_RC" ]; then
echo "No $ASTYLE_RC in pwd \"$PWD\"..."
continue
fi
for f in $(find . \
-name '*.c' \
-o -name '*.cc' \
-o -name '*.cpp' \
-o -name '*.h' \
-o -name '*.hh' \
-o -name '*.hpp'); do
"${ASTYLE_CMD}" --options="$ASTYLE_RC" "${f}"
done
# Remove backup files.
find . -name "*.orig" | xargs --no-run-if-empty rm -v
popd
done

View File

@ -27,7 +27,7 @@
#include <QString> #include <QString>
FeedDownloader::FeedDownloader(QObject *parent) FeedDownloader::FeedDownloader(QObject* parent)
: QObject(parent), m_feeds(QList<Feed*>()), m_mutex(new QMutex()), m_threadPool(new QThreadPool(this)), : QObject(parent), m_feeds(QList<Feed*>()), m_mutex(new QMutex()), m_threadPool(new QThreadPool(this)),
m_results(FeedDownloadResults()), m_feedsUpdated(0), m_results(FeedDownloadResults()), m_feedsUpdated(0),
m_feedsUpdating(0), m_feedsOriginalCount(0) { m_feedsUpdating(0), m_feedsOriginalCount(0) {
@ -39,7 +39,6 @@ FeedDownloader::~FeedDownloader() {
m_mutex->tryLock(); m_mutex->tryLock();
m_mutex->unlock(); m_mutex->unlock();
delete m_mutex; delete m_mutex;
qDebug("Destroying FeedDownloader instance."); qDebug("Destroying FeedDownloader instance.");
} }
@ -50,11 +49,13 @@ bool FeedDownloader::isUpdateRunning() const {
void FeedDownloader::updateAvailableFeeds() { void FeedDownloader::updateAvailableFeeds() {
while (!m_feeds.isEmpty()) { while (!m_feeds.isEmpty()) {
connect(m_feeds.first(), &Feed::messagesObtained, this, &FeedDownloader::oneFeedUpdateFinished, connect(m_feeds.first(), &Feed::messagesObtained, this, &FeedDownloader::oneFeedUpdateFinished,
(Qt::ConnectionType) (Qt::UniqueConnection | Qt::AutoConnection)); (Qt::ConnectionType)(Qt::UniqueConnection | Qt::AutoConnection));
if (m_threadPool->tryStart(m_feeds.first())) { if (m_threadPool->tryStart(m_feeds.first())) {
m_feeds.removeFirst(); m_feeds.removeFirst();
m_feedsUpdating++; m_feedsUpdating++;
} }
else { else {
// We want to start update of some feeds but all working threads are occupied. // We want to start update of some feeds but all working threads are occupied.
break; break;
@ -62,21 +63,20 @@ void FeedDownloader::updateAvailableFeeds() {
} }
} }
void FeedDownloader::updateFeeds(const QList<Feed*> &feeds) { void FeedDownloader::updateFeeds(const QList<Feed*>& feeds) {
QMutexLocker locker(m_mutex); QMutexLocker locker(m_mutex);
if (feeds.isEmpty()) { if (feeds.isEmpty()) {
qDebug("No feeds to update in worker thread, aborting update."); qDebug("No feeds to update in worker thread, aborting update.");
finalizeUpdate(); finalizeUpdate();
} }
else { else {
qDebug().nospace() << "Starting feed updates from worker in thread: \'" << QThread::currentThreadId() << "\'."; qDebug().nospace() << "Starting feed updates from worker in thread: \'" << QThread::currentThreadId() << "\'.";
m_feeds = feeds; m_feeds = feeds;
m_feedsOriginalCount = m_feeds.size(); m_feedsOriginalCount = m_feeds.size();
m_results.clear(); m_results.clear();
m_feedsUpdated = m_feedsUpdating = 0; m_feedsUpdated = m_feedsUpdating = 0;
// Job starts now. // Job starts now.
emit updateStarted(); emit updateStarted();
updateAvailableFeeds(); updateAvailableFeeds();
@ -88,24 +88,18 @@ void FeedDownloader::stopRunningUpdate() {
m_feeds.clear(); m_feeds.clear();
} }
void FeedDownloader::oneFeedUpdateFinished(const QList<Message> &messages, bool error_during_obtaining) { void FeedDownloader::oneFeedUpdateFinished(const QList<Message>& messages, bool error_during_obtaining) {
QMutexLocker locker(m_mutex); QMutexLocker locker(m_mutex);
m_feedsUpdated++; m_feedsUpdated++;
m_feedsUpdating--; m_feedsUpdating--;
Feed* feed = qobject_cast<Feed*>(sender());
Feed *feed = qobject_cast<Feed*>(sender());
disconnect(feed, &Feed::messagesObtained, this, &FeedDownloader::oneFeedUpdateFinished); disconnect(feed, &Feed::messagesObtained, this, &FeedDownloader::oneFeedUpdateFinished);
// Now, we check if there are any feeds we would like to update too. // Now, we check if there are any feeds we would like to update too.
updateAvailableFeeds(); updateAvailableFeeds();
// Now make sure, that messages are actually stored to SQL in a locked state. // Now make sure, that messages are actually stored to SQL in a locked state.
qDebug().nospace() << "Saving messages of feed " qDebug().nospace() << "Saving messages of feed "
<< feed->id() << " in thread: \'" << feed->id() << " in thread: \'"
<< QThread::currentThreadId() << "\'."; << QThread::currentThreadId() << "\'.";
int updated_messages = feed->updateMessages(messages, error_during_obtaining); int updated_messages = feed->updateMessages(messages, error_during_obtaining);
/* /*
@ -115,7 +109,7 @@ void FeedDownloader::oneFeedUpdateFinished(const QList<Message> &messages, bool
*/ */
if (updated_messages > 0) { if (updated_messages > 0) {
m_results.appendUpdatedFeed(QPair<QString,int>(feed->title(), updated_messages)); m_results.appendUpdatedFeed(QPair<QString, int>(feed->title(), updated_messages));
} }
qDebug("Made progress in feed updates, total feeds count %d/%d (id of feed is %d).", m_feedsUpdated, m_feedsOriginalCount, feed->id()); qDebug("Made progress in feed updates, total feeds count %d/%d (id of feed is %d).", m_feedsUpdated, m_feedsOriginalCount, feed->id());
@ -128,9 +122,7 @@ void FeedDownloader::oneFeedUpdateFinished(const QList<Message> &messages, bool
void FeedDownloader::finalizeUpdate() { void FeedDownloader::finalizeUpdate() {
qDebug().nospace() << "Finished feed updates in thread: \'" << QThread::currentThreadId() << "\'."; qDebug().nospace() << "Finished feed updates in thread: \'" << QThread::currentThreadId() << "\'.";
m_results.sort(); m_results.sort();
// Update of feeds has finished. // Update of feeds has finished.
// NOTE: This means that now "update lock" can be unlocked // NOTE: This means that now "update lock" can be unlocked
// and feeds can be added/edited/deleted and application // and feeds can be added/edited/deleted and application
@ -138,7 +130,7 @@ void FeedDownloader::finalizeUpdate() {
emit updateFinished(m_results); emit updateFinished(m_results);
} }
FeedDownloadResults::FeedDownloadResults() : m_updatedFeeds(QList<QPair<QString,int> >()) { FeedDownloadResults::FeedDownloadResults() : m_updatedFeeds(QList<QPair<QString, int>>()) {
} }
QString FeedDownloadResults::overview(int how_many_feeds) const { QString FeedDownloadResults::overview(int how_many_feeds) const {
@ -157,7 +149,7 @@ QString FeedDownloadResults::overview(int how_many_feeds) const {
return res_str; return res_str;
} }
void FeedDownloadResults::appendUpdatedFeed(const QPair<QString,int> &feed) { void FeedDownloadResults::appendUpdatedFeed(const QPair<QString, int>& feed) {
m_updatedFeeds.append(feed); m_updatedFeeds.append(feed);
} }
@ -165,7 +157,7 @@ void FeedDownloadResults::sort() {
qSort(m_updatedFeeds.begin(), m_updatedFeeds.end(), FeedDownloadResults::lessThan); qSort(m_updatedFeeds.begin(), m_updatedFeeds.end(), FeedDownloadResults::lessThan);
} }
bool FeedDownloadResults::lessThan(const QPair<QString, int> &lhs, const QPair<QString, int> &rhs) { bool FeedDownloadResults::lessThan(const QPair<QString, int>& lhs, const QPair<QString, int>& rhs) {
return lhs.second > rhs.second; return lhs.second > rhs.second;
} }
@ -173,6 +165,6 @@ void FeedDownloadResults::clear() {
m_updatedFeeds.clear(); m_updatedFeeds.clear();
} }
QList<QPair<QString,int> > FeedDownloadResults::updatedFeeds() const { QList<QPair<QString, int>> FeedDownloadResults::updatedFeeds() const {
return m_updatedFeeds; return m_updatedFeeds;
} }

View File

@ -34,18 +34,18 @@ class FeedDownloadResults {
public: public:
explicit FeedDownloadResults(); explicit FeedDownloadResults();
QList<QPair<QString,int> > updatedFeeds() const; QList<QPair<QString, int>> updatedFeeds() const;
QString overview(int how_many_feeds) const; QString overview(int how_many_feeds) const;
void appendUpdatedFeed(const QPair<QString,int> &feed); void appendUpdatedFeed(const QPair<QString, int>& feed);
void sort(); void sort();
void clear(); void clear();
static bool lessThan(const QPair<QString,int> &lhs, const QPair<QString,int> &rhs); static bool lessThan(const QPair<QString, int>& lhs, const QPair<QString, int>& rhs);
private: private:
// QString represents title if the feed, int represents count of newly downloaded messages. // QString represents title if the feed, int represents count of newly downloaded messages.
QList<QPair<QString,int> > m_updatedFeeds; QList<QPair<QString, int>> m_updatedFeeds;
}; };
// This class offers means to "update" feeds and "special" categories. // This class offers means to "update" feeds and "special" categories.
@ -55,7 +55,7 @@ class FeedDownloader : public QObject {
public: public:
// Constructors and destructors. // Constructors and destructors.
explicit FeedDownloader(QObject *parent = 0); explicit FeedDownloader(QObject* parent = 0);
virtual ~FeedDownloader(); virtual ~FeedDownloader();
bool isUpdateRunning() const; bool isUpdateRunning() const;
@ -65,13 +65,13 @@ class FeedDownloader : public QObject {
// New messages are downloaded for each feed and they // New messages are downloaded for each feed and they
// are stored persistently in the database. // are stored persistently in the database.
// Appropriate signals are emitted. // Appropriate signals are emitted.
void updateFeeds(const QList<Feed*> &feeds); void updateFeeds(const QList<Feed*>& feeds);
// Stops running update. // Stops running update.
void stopRunningUpdate(); void stopRunningUpdate();
private slots: private slots:
void oneFeedUpdateFinished(const QList<Message> &messages, bool error_during_obtaining); void oneFeedUpdateFinished(const QList<Message>& messages, bool error_during_obtaining);
signals: signals:
// Emitted if feed updates started. // Emitted if feed updates started.
@ -85,15 +85,15 @@ class FeedDownloader : public QObject {
// "Current" number indicates count of processed feeds // "Current" number indicates count of processed feeds
// and "total" number indicates total number of feeds // and "total" number indicates total number of feeds
// which were in the initial queue. // which were in the initial queue.
void updateProgress(const Feed *feed, int current, int total); void updateProgress(const Feed* feed, int current, int total);
private: private:
void updateAvailableFeeds(); void updateAvailableFeeds();
void finalizeUpdate(); void finalizeUpdate();
QList<Feed*> m_feeds; QList<Feed*> m_feeds;
QMutex *m_mutex; QMutex* m_mutex;
QThreadPool *m_threadPool; QThreadPool* m_threadPool;
FeedDownloadResults m_results; FeedDownloadResults m_results;
int m_feedsUpdated; int m_feedsUpdated;

View File

@ -38,44 +38,38 @@
#include <algorithm> #include <algorithm>
FeedsModel::FeedsModel(QObject *parent) : QAbstractItemModel(parent) { FeedsModel::FeedsModel(QObject* parent) : QAbstractItemModel(parent) {
setObjectName(QSL("FeedsModel")); setObjectName(QSL("FeedsModel"));
// Create root item. // Create root item.
m_rootItem = new RootItem(); m_rootItem = new RootItem();
//: 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")));
// Setup icons. // Setup icons.
m_countsIcon = qApp->icons()->fromTheme(QSL("mail-mark-unread")); m_countsIcon = qApp->icons()->fromTheme(QSL("mail-mark-unread"));
//: Title text in the feed list header. //: Title text in the feed list header.
m_headerData << tr("Title"); m_headerData << tr("Title");
m_tooltipData << /*: Feed list header "titles" column tooltip.*/ tr("Titles of feeds/categories.") << 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."); /*: Feed list header "counts" column tooltip.*/ tr("Counts of unread/all mesages.");
} }
FeedsModel::~FeedsModel() { FeedsModel::~FeedsModel() {
qDebug("Destroying FeedsModel instance."); qDebug("Destroying FeedsModel instance.");
// Delete all model items. // Delete all model items.
delete m_rootItem; delete m_rootItem;
} }
QMimeData *FeedsModel::mimeData(const QModelIndexList &indexes) const { QMimeData* FeedsModel::mimeData(const QModelIndexList& indexes) const {
QMimeData *mime_data = new QMimeData(); QMimeData* mime_data = new QMimeData();
QByteArray encoded_data; QByteArray encoded_data;
QDataStream stream(&encoded_data, QIODevice::WriteOnly); QDataStream stream(&encoded_data, QIODevice::WriteOnly);
foreach (const QModelIndex &index, indexes) { foreach (const QModelIndex& index, indexes) {
if (index.column() != 0) { if (index.column() != 0) {
continue; continue;
} }
RootItem *item_for_index = itemForIndex(index); RootItem* item_for_index = itemForIndex(index);
if (item_for_index->kind() != RootItemKind::Root) { if (item_for_index->kind() != RootItemKind::Root) {
stream << (quintptr) item_for_index; stream << (quintptr) item_for_index;
@ -90,13 +84,14 @@ 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, 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(row)
Q_UNUSED(column) Q_UNUSED(column)
if (action == Qt::IgnoreAction) { if (action == Qt::IgnoreAction) {
return true; return true;
} }
else if (action != Qt::MoveAction) { else if (action != Qt::MoveAction) {
return false; return false;
} }
@ -106,18 +101,18 @@ bool FeedsModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int
if (dragged_items_data.isEmpty()) { if (dragged_items_data.isEmpty()) {
return false; return false;
} }
else { else {
QDataStream stream(&dragged_items_data, QIODevice::ReadOnly); QDataStream stream(&dragged_items_data, QIODevice::ReadOnly);
while (!stream.atEnd()) { while (!stream.atEnd()) {
quintptr pointer_to_item; quintptr pointer_to_item;
stream >> 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.
RootItem *dragged_item = (RootItem*) pointer_to_item; RootItem* dragged_item = (RootItem*) pointer_to_item;
RootItem *target_item = itemForIndex(parent); RootItem* target_item = itemForIndex(parent);
ServiceRoot *dragged_item_root = dragged_item->getParentServiceRoot(); ServiceRoot* dragged_item_root = dragged_item->getParentServiceRoot();
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.");
@ -131,7 +126,6 @@ bool FeedsModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int
QSystemTrayIcon::Warning, QSystemTrayIcon::Warning,
qApp->mainFormWidget(), qApp->mainFormWidget(),
true); true);
qDebug("Dragged item cannot be dragged into different account. Cancelling drag-drop action."); qDebug("Dragged item cannot be dragged into different account. Cancelling drag-drop action.");
return false; return false;
} }
@ -153,11 +147,10 @@ Qt::DropActions FeedsModel::supportedDropActions() const {
return Qt::MoveAction; return Qt::MoveAction;
} }
Qt::ItemFlags FeedsModel::flags(const QModelIndex &index) const { Qt::ItemFlags FeedsModel::flags(const QModelIndex& index) const {
Qt::ItemFlags base_flags = QAbstractItemModel::flags(index); Qt::ItemFlags base_flags = QAbstractItemModel::flags(index);
const RootItem *item_for_index = itemForIndex(index); const RootItem* item_for_index = itemForIndex(index);
Qt::ItemFlags additional_flags = item_for_index->additionalFlags(); Qt::ItemFlags additional_flags = item_for_index->additionalFlags();
return base_flags | additional_flags; return base_flags | additional_flags;
} }
@ -171,6 +164,7 @@ QVariant FeedsModel::headerData(int section, Qt::Orientation orientation, int ro
if (section == FDS_MODEL_TITLE_INDEX) { if (section == FDS_MODEL_TITLE_INDEX) {
return m_headerData.at(FDS_MODEL_TITLE_INDEX); return m_headerData.at(FDS_MODEL_TITLE_INDEX);
} }
else { else {
return QVariant(); return QVariant();
} }
@ -182,6 +176,7 @@ QVariant FeedsModel::headerData(int section, Qt::Orientation orientation, int ro
if (section == FDS_MODEL_COUNTS_INDEX) { if (section == FDS_MODEL_COUNTS_INDEX) {
return m_countsIcon; return m_countsIcon;
} }
else { else {
return QVariant(); return QVariant();
} }
@ -191,42 +186,45 @@ QVariant FeedsModel::headerData(int section, Qt::Orientation orientation, int ro
} }
} }
QModelIndex FeedsModel::index(int row, int column, const QModelIndex &parent) const { QModelIndex FeedsModel::index(int row, int column, const QModelIndex& parent) const {
if (!hasIndex(row, column, parent)) { if (!hasIndex(row, column, parent)) {
return QModelIndex(); return QModelIndex();
} }
RootItem *parent_item = itemForIndex(parent); RootItem* parent_item = itemForIndex(parent);
RootItem *child_item = parent_item->child(row); RootItem* child_item = parent_item->child(row);
if (child_item) { if (child_item) {
return createIndex(row, column, child_item); return createIndex(row, column, child_item);
} }
else { else {
return QModelIndex(); return QModelIndex();
} }
} }
QModelIndex FeedsModel::parent(const QModelIndex &child) const { QModelIndex FeedsModel::parent(const QModelIndex& child) const {
if (!child.isValid()) { if (!child.isValid()) {
return QModelIndex(); return QModelIndex();
} }
RootItem *child_item = itemForIndex(child); RootItem* child_item = itemForIndex(child);
RootItem *parent_item = child_item->parent(); RootItem* parent_item = child_item->parent();
if (parent_item == m_rootItem) { if (parent_item == m_rootItem) {
return QModelIndex(); return QModelIndex();
} }
else { else {
return createIndex(parent_item->row(), 0, parent_item); return createIndex(parent_item->row(), 0, parent_item);
} }
} }
int FeedsModel::rowCount(const QModelIndex &parent) const { int FeedsModel::rowCount(const QModelIndex& parent) const {
if (parent.column() > 0) { if (parent.column() > 0) {
return 0; return 0;
} }
else { else {
return itemForIndex(parent)->childCount(); return itemForIndex(parent)->childCount();
} }
@ -246,38 +244,34 @@ void FeedsModel::reloadCountsOfWholeModel() {
notifyWithCounts(); notifyWithCounts();
} }
void FeedsModel::removeItem(const QModelIndex &index) { void FeedsModel::removeItem(const QModelIndex& index) {
if (index.isValid()) { if (index.isValid()) {
RootItem *deleting_item = itemForIndex(index); RootItem* deleting_item = itemForIndex(index);
QModelIndex parent_index = index.parent(); QModelIndex parent_index = index.parent();
RootItem *parent_item = deleting_item->parent(); RootItem* parent_item = deleting_item->parent();
beginRemoveRows(parent_index, index.row(), index.row()); beginRemoveRows(parent_index, index.row(), index.row());
parent_item->removeChild(deleting_item); parent_item->removeChild(deleting_item);
endRemoveRows(); endRemoveRows();
deleting_item->deleteLater(); deleting_item->deleteLater();
notifyWithCounts(); notifyWithCounts();
} }
} }
void FeedsModel::removeItem(RootItem *deleting_item) { void FeedsModel::removeItem(RootItem* deleting_item) {
if (deleting_item != nullptr) { if (deleting_item != nullptr) {
QModelIndex index = indexForItem(deleting_item); QModelIndex index = indexForItem(deleting_item);
QModelIndex parent_index = index.parent(); QModelIndex parent_index = index.parent();
RootItem *parent_item = deleting_item->parent(); RootItem* parent_item = deleting_item->parent();
beginRemoveRows(parent_index, index.row(), index.row()); beginRemoveRows(parent_index, index.row(), index.row());
parent_item->removeChild(deleting_item); parent_item->removeChild(deleting_item);
endRemoveRows(); endRemoveRows();
deleting_item->deleteLater(); deleting_item->deleteLater();
notifyWithCounts(); notifyWithCounts();
} }
} }
void FeedsModel::reassignNodeToNewParent(RootItem *original_node, RootItem *new_parent) { void FeedsModel::reassignNodeToNewParent(RootItem* original_node, RootItem* new_parent) {
RootItem *original_parent = original_node->parent(); RootItem* original_parent = original_node->parent();
if (original_parent != new_parent) { if (original_parent != new_parent) {
if (original_parent != nullptr) { if (original_parent != nullptr) {
@ -292,7 +286,6 @@ void FeedsModel::reassignNodeToNewParent(RootItem *original_node, RootItem *new_
} }
int new_index_of_item = new_parent->childCount(); int new_index_of_item = new_parent->childCount();
// ... and insert it under the new parent. // ... and insert it under the new parent.
beginInsertRows(indexForItem(new_parent), new_index_of_item, new_index_of_item); beginInsertRows(indexForItem(new_parent), new_index_of_item, new_index_of_item);
new_parent->appendChild(original_node); new_parent->appendChild(original_node);
@ -303,7 +296,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;
foreach (RootItem *root, m_rootItem->childItems()) { foreach (RootItem* root, m_rootItem->childItems()) {
if (root->kind() == RootItemKind::ServiceRoot) { if (root->kind() == RootItemKind::ServiceRoot) {
roots.append(root->toServiceRoot()); roots.append(root->toServiceRoot());
} }
@ -312,8 +305,8 @@ QList<ServiceRoot*> FeedsModel::serviceRoots() const {
return roots; return roots;
} }
bool FeedsModel::containsServiceRootFromEntryPoint(const ServiceEntryPoint *point) const { bool FeedsModel::containsServiceRootFromEntryPoint(const ServiceEntryPoint* point) const {
foreach (const ServiceRoot *root, serviceRoots()) { foreach (const ServiceRoot* root, serviceRoots()) {
if (root->code() == point->code()) { if (root->code() == point->code()) {
return true; return true;
} }
@ -322,9 +315,9 @@ bool FeedsModel::containsServiceRootFromEntryPoint(const ServiceEntryPoint *poin
return false; return false;
} }
StandardServiceRoot *FeedsModel::standardServiceRoot() const { StandardServiceRoot* FeedsModel::standardServiceRoot() const {
foreach (ServiceRoot *root, serviceRoots()) { foreach (ServiceRoot* root, serviceRoots()) {
StandardServiceRoot *std_service_root; StandardServiceRoot* std_service_root;
if ((std_service_root = dynamic_cast<StandardServiceRoot*>(root)) != nullptr) { if ((std_service_root = dynamic_cast<StandardServiceRoot*>(root)) != nullptr) {
return std_service_root; return std_service_root;
@ -337,7 +330,7 @@ StandardServiceRoot *FeedsModel::standardServiceRoot() const {
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;
foreach (Feed *feed, m_rootItem->getSubTreeFeeds()) { foreach (Feed* feed, m_rootItem->getSubTreeFeeds()) {
switch (feed->autoUpdateType()) { switch (feed->autoUpdateType()) {
case Feed::DontAutoUpdate: case Feed::DontAutoUpdate:
// Do not auto-update this feed ever. // Do not auto-update this feed ever.
@ -360,6 +353,7 @@ QList<Feed*> FeedsModel::feedsForScheduledUpdate(bool auto_update_now) {
feeds_for_update.append(feed); feeds_for_update.append(feed);
feed->setAutoUpdateRemainingInterval(feed->autoUpdateInitialInterval()); feed->setAutoUpdateRemainingInterval(feed->autoUpdateInitialInterval());
} }
else { else {
// Interval did not pass, set new decremented interval and do NOT // Interval did not pass, set new decremented interval and do NOT
// include this feed in the output list. // include this feed in the output list.
@ -373,26 +367,26 @@ QList<Feed*> FeedsModel::feedsForScheduledUpdate(bool auto_update_now) {
return feeds_for_update; return feeds_for_update;
} }
QList<Message> FeedsModel::messagesForItem(RootItem *item) const { QList<Message> FeedsModel::messagesForItem(RootItem* item) const {
return item->undeletedMessages(); return item->undeletedMessages();
} }
int FeedsModel::columnCount(const QModelIndex &parent) const { int FeedsModel::columnCount(const QModelIndex& parent) const {
Q_UNUSED(parent) Q_UNUSED(parent)
return FEEDS_VIEW_COLUMN_COUNT; return FEEDS_VIEW_COLUMN_COUNT;
} }
RootItem *FeedsModel::itemForIndex(const QModelIndex &index) const { RootItem* FeedsModel::itemForIndex(const QModelIndex& index) const {
if (index.isValid() && index.model() == this) { if (index.isValid() && index.model() == this) {
return static_cast<RootItem*>(index.internalPointer()); return static_cast<RootItem*>(index.internalPointer());
} }
else { else {
return m_rootItem; return m_rootItem;
} }
} }
QModelIndex FeedsModel::indexForItem(const RootItem *item) const { QModelIndex FeedsModel::indexForItem(const RootItem* item) const {
if (item == nullptr || item->kind() == RootItemKind::Root) { if (item == nullptr || item->kind() == RootItemKind::Root) {
// Root item lies on invalid index. // Root item lies on invalid index.
return QModelIndex(); return QModelIndex();
@ -410,7 +404,7 @@ QModelIndex FeedsModel::indexForItem(const RootItem *item) const {
// We go through the stack and create our target index. // We go through the stack and create our target index.
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)), 0, target_index); target_index = index(parent_item->parent()->childItems().indexOf(const_cast<RootItem* const>(parent_item)), 0, target_index);
} }
@ -418,7 +412,7 @@ QModelIndex FeedsModel::indexForItem(const RootItem *item) const {
} }
bool FeedsModel::hasAnyFeedNewMessages() const { bool FeedsModel::hasAnyFeedNewMessages() const {
foreach (const Feed *feed, m_rootItem->getSubTreeFeeds()) { foreach (const Feed* feed, m_rootItem->getSubTreeFeeds()) {
if (feed->status() == Feed::NewMessages) { if (feed->status() == Feed::NewMessages) {
return true; return true;
} }
@ -427,7 +421,7 @@ bool FeedsModel::hasAnyFeedNewMessages() const {
return false; return false;
} }
RootItem *FeedsModel::rootItem() const { RootItem* FeedsModel::rootItem() const {
return m_rootItem; return m_rootItem;
} }
@ -437,16 +431,14 @@ void FeedsModel::reloadChangedLayout(QModelIndexList list) {
if (indx.isValid()) { if (indx.isValid()) {
QModelIndex indx_parent = indx.parent(); QModelIndex indx_parent = indx.parent();
// Underlying data are changed. // Underlying data are changed.
emit dataChanged(index(indx.row(), 0, indx_parent), index(indx.row(), FDS_MODEL_COUNTS_INDEX, indx_parent)); emit dataChanged(index(indx.row(), 0, indx_parent), index(indx.row(), FDS_MODEL_COUNTS_INDEX, indx_parent));
list.append(indx_parent); list.append(indx_parent);
} }
} }
} }
void FeedsModel::reloadChangedItem(RootItem *item) { void FeedsModel::reloadChangedItem(RootItem* item) {
QModelIndex index_item = indexForItem(item); QModelIndex index_item = indexForItem(item);
reloadChangedLayout(QModelIndexList() << index_item); reloadChangedLayout(QModelIndexList() << index_item);
} }
@ -455,15 +447,16 @@ void FeedsModel::notifyWithCounts() {
emit messageCountsChanged(countOfUnreadMessages(), hasAnyFeedNewMessages()); emit messageCountsChanged(countOfUnreadMessages(), hasAnyFeedNewMessages());
} }
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) {
qDebug("There is request to reload feed model for more than %d items, reloading model fully.", RELOAD_MODEL_BORDER_NUM); qDebug("There is request to reload feed model for more than %d items, reloading model fully.", RELOAD_MODEL_BORDER_NUM);
reloadWholeLayout(); reloadWholeLayout();
} }
else { else {
qDebug("There is request to reload feed model, reloading the %d items individually.", items.size()); qDebug("There is request to reload feed model, reloading the %d items individually.", items.size());
foreach (RootItem *item, items) { foreach (RootItem* item, items) {
reloadChangedItem(item); reloadChangedItem(item);
} }
} }
@ -476,13 +469,11 @@ void FeedsModel::reloadWholeLayout() {
emit layoutChanged(); emit layoutChanged();
} }
bool FeedsModel::addServiceAccount(ServiceRoot *root, bool freshly_activated) { bool FeedsModel::addServiceAccount(ServiceRoot* root, bool freshly_activated) {
int new_row_index = m_rootItem->childCount(); int new_row_index = m_rootItem->childCount();
beginInsertRows(indexForItem(m_rootItem), new_row_index, new_row_index); beginInsertRows(indexForItem(m_rootItem), new_row_index, new_row_index);
m_rootItem->appendChild(root); m_rootItem->appendChild(root);
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);
@ -490,7 +481,6 @@ bool FeedsModel::addServiceAccount(ServiceRoot *root, bool freshly_activated) {
connect(root, &ServiceRoot::reloadMessageListRequested, this, &FeedsModel::reloadMessageListRequested); connect(root, &ServiceRoot::reloadMessageListRequested, this, &FeedsModel::reloadMessageListRequested);
connect(root, &ServiceRoot::itemExpandRequested, this, &FeedsModel::itemExpandRequested); connect(root, &ServiceRoot::itemExpandRequested, this, &FeedsModel::itemExpandRequested);
connect(root, &ServiceRoot::itemExpandStateSaveRequested, this, &FeedsModel::itemExpandStateSaveRequested); connect(root, &ServiceRoot::itemExpandStateSaveRequested, this, &FeedsModel::itemExpandStateSaveRequested);
root->start(freshly_activated); root->start(freshly_activated);
return true; return true;
} }
@ -498,8 +488,8 @@ bool FeedsModel::addServiceAccount(ServiceRoot *root, bool freshly_activated) {
bool FeedsModel::restoreAllBins() { bool FeedsModel::restoreAllBins() {
bool result = true; bool result = true;
foreach (ServiceRoot *root, serviceRoots()) { foreach (ServiceRoot* root, serviceRoots()) {
RecycleBin *bin_of_root = root->recycleBin(); RecycleBin* bin_of_root = root->recycleBin();
if (bin_of_root != nullptr) { if (bin_of_root != nullptr) {
result &= bin_of_root->restore(); result &= bin_of_root->restore();
@ -512,8 +502,8 @@ bool FeedsModel::restoreAllBins() {
bool FeedsModel::emptyAllBins() { bool FeedsModel::emptyAllBins() {
bool result = true; bool result = true;
foreach (ServiceRoot *root, serviceRoots()) { foreach (ServiceRoot* root, serviceRoots()) {
RecycleBin *bin_of_root = root->recycleBin(); RecycleBin* bin_of_root = root->recycleBin();
if (bin_of_root != nullptr) { if (bin_of_root != nullptr) {
result &= bin_of_root->empty(); result &= bin_of_root->empty();
@ -525,30 +515,30 @@ bool FeedsModel::emptyAllBins() {
void FeedsModel::loadActivatedServiceAccounts() { void FeedsModel::loadActivatedServiceAccounts() {
// Iterate all globally available feed "service plugins". // Iterate all globally available feed "service plugins".
foreach (const ServiceEntryPoint *entry_point, qApp->feedReader()->feedServices()) { foreach (const ServiceEntryPoint* entry_point, qApp->feedReader()->feedServices()) {
// Load all stored root nodes from the entry point and add those to the model. // Load all stored root nodes from the entry point and add those to the model.
QList<ServiceRoot*> roots = entry_point->initializeSubtree(); QList<ServiceRoot*> roots = entry_point->initializeSubtree();
foreach (ServiceRoot *root, roots) { foreach (ServiceRoot* root, roots) {
addServiceAccount(root, false); addServiceAccount(root, false);
} }
} }
} }
void FeedsModel::stopServiceAccounts() { void FeedsModel::stopServiceAccounts() {
foreach (ServiceRoot *account, serviceRoots()) { foreach (ServiceRoot* account, serviceRoots()) {
account->stop(); account->stop();
} }
} }
QList<Feed*> FeedsModel::feedsForIndex(const QModelIndex &index) const { QList<Feed*> FeedsModel::feedsForIndex(const QModelIndex& index) const {
return itemForIndex(index)->getSubTreeFeeds(); return itemForIndex(index)->getSubTreeFeeds();
} }
bool FeedsModel::markItemRead(RootItem *item, RootItem::ReadStatus read) { bool FeedsModel::markItemRead(RootItem* item, RootItem::ReadStatus read) {
return item->markAsReadUnread(read); return item->markAsReadUnread(read);
} }
bool FeedsModel::markItemCleared(RootItem *item, bool clean_read_only) { bool FeedsModel::markItemCleared(RootItem* item, bool clean_read_only) {
return item->cleanMessages(clean_read_only); return item->cleanMessages(clean_read_only);
} }

View File

@ -34,28 +34,28 @@ class FeedsModel : public QAbstractItemModel {
public: public:
// Constructors and destructors. // Constructors and destructors.
explicit FeedsModel(QObject *parent = 0); explicit FeedsModel(QObject* parent = 0);
virtual ~FeedsModel(); virtual ~FeedsModel();
// Model implementation. // Model implementation.
inline QVariant data(const QModelIndex &index, int role) const { inline QVariant data(const QModelIndex& index, int role) const {
// Return data according to item. // Return data according to item.
return itemForIndex(index)->data(index.column(), role); return itemForIndex(index)->data(index.column(), role);
} }
// Drag & drop. // Drag & drop.
QMimeData *mimeData(const QModelIndexList &indexes) const; QMimeData* mimeData(const QModelIndexList& indexes) const;
QStringList mimeTypes() const; QStringList mimeTypes() const;
bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent); bool dropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, const QModelIndex& parent);
Qt::DropActions supportedDropActions() const; Qt::DropActions supportedDropActions() const;
Qt::ItemFlags flags(const QModelIndex &index) const; Qt::ItemFlags flags(const QModelIndex& index) const;
// Other subclassed methods. // Other subclassed methods.
QVariant headerData(int section, Qt::Orientation orientation, int role) const; QVariant headerData(int section, Qt::Orientation orientation, int role) const;
QModelIndex index(int row, int column, const QModelIndex &parent) const; QModelIndex index(int row, int column, const QModelIndex& parent) const;
QModelIndex parent(const QModelIndex &child) const; QModelIndex parent(const QModelIndex& child) const;
int columnCount(const QModelIndex &parent) const; int columnCount(const QModelIndex& parent) const;
int rowCount(const QModelIndex &parent) const; int rowCount(const QModelIndex& parent) const;
// Returns counts of ALL/UNREAD (non-deleted) messages for the model. // Returns counts of ALL/UNREAD (non-deleted) messages for the model.
int countOfAllMessages() const; int countOfAllMessages() const;
@ -67,10 +67,10 @@ class FeedsModel : public QAbstractItemModel {
QList<ServiceRoot*> serviceRoots() const; QList<ServiceRoot*> serviceRoots() const;
// Determines if there is any account activated from given entry point. // Determines if there is any account activated from given entry point.
bool containsServiceRootFromEntryPoint(const ServiceEntryPoint *point) const; bool containsServiceRootFromEntryPoint(const ServiceEntryPoint* point) const;
// Direct and the only global accessor to standard service root. // Direct and the only global accessor to standard service root.
StandardServiceRoot *standardServiceRoot() const; StandardServiceRoot* standardServiceRoot() const;
// Returns the list of feeds which should be updated // Returns the list of feeds which should be updated
// according to auto-update schedule. // according to auto-update schedule.
@ -84,26 +84,26 @@ class FeedsModel : public QAbstractItemModel {
// Returns (undeleted) messages for given feeds. // Returns (undeleted) messages for given feeds.
// This is usually used for displaying whole feeds // This is usually used for displaying whole feeds
// in "newspaper" mode. // in "newspaper" mode.
QList<Message> messagesForItem(RootItem *item) const; QList<Message> messagesForItem(RootItem* item) const;
// Returns ALL RECURSIVE CHILD feeds contained within single index. // Returns ALL RECURSIVE CHILD feeds contained within single index.
QList<Feed*> feedsForIndex(const QModelIndex &index) const; QList<Feed*> feedsForIndex(const QModelIndex& index) const;
// Returns feed/category which lies at the specified index or // Returns feed/category which lies at the specified index or
// root item if index is invalid. // root item if index is invalid.
RootItem *itemForIndex(const QModelIndex &index) const; RootItem* itemForIndex(const QModelIndex& index) const;
// Returns source QModelIndex on which lies given item. // Returns source QModelIndex on which lies given item.
// NOTE: This goes through all available indexes and // NOTE: This goes through all available indexes and
// checks their bound items manually, there is no // checks their bound items manually, there is no
// other way to to this. // other way to to this.
QModelIndex indexForItem(const RootItem *item) const; QModelIndex indexForItem(const RootItem* item) const;
// Determines if any feed has any new messages. // Determines if any feed has any new messages.
bool hasAnyFeedNewMessages() const; bool hasAnyFeedNewMessages() const;
// Access to root item. // Access to root item.
RootItem *rootItem() const; RootItem* rootItem() const;
public slots: public slots:
// Loads feed/categories from the database. // Loads feed/categories from the database.
@ -117,23 +117,23 @@ class FeedsModel : public QAbstractItemModel {
// Checks if new parent node is different from one used by original node. // Checks if new parent node is different from one used by original node.
// If it is, then it reassigns original_node to new parent. // If it is, then it reassigns original_node to new parent.
void reassignNodeToNewParent(RootItem *original_node, RootItem *new_parent); void reassignNodeToNewParent(RootItem* original_node, RootItem* new_parent);
// Adds given service root account. // Adds given service root account.
bool addServiceAccount(ServiceRoot *root, bool freshly_activated); bool addServiceAccount(ServiceRoot* root, bool freshly_activated);
// Removes item with given index. // Removes item with given index.
// NOTE: Also deletes item from memory. // NOTE: Also deletes item from memory.
void removeItem(const QModelIndex &index); void removeItem(const QModelIndex& index);
void removeItem(RootItem *deleting_item); void removeItem(RootItem* deleting_item);
// Recycle bins operations. // Recycle bins operations.
bool restoreAllBins(); bool restoreAllBins();
bool emptyAllBins(); bool emptyAllBins();
// Feeds operations. // Feeds operations.
bool markItemRead(RootItem *item, RootItem::ReadStatus read); bool markItemRead(RootItem* item, RootItem::ReadStatus read);
bool markItemCleared(RootItem *item, bool clean_read_only); bool markItemCleared(RootItem* item, bool clean_read_only);
// Signals that properties (probably counts) // Signals that properties (probably counts)
// of ALL items have changed. // of ALL items have changed.
@ -145,14 +145,14 @@ class FeedsModel : public QAbstractItemModel {
void reloadChangedLayout(QModelIndexList list); void reloadChangedLayout(QModelIndexList list);
// Invalidates data under index for the item. // Invalidates data under index for the item.
void reloadChangedItem(RootItem *item); void reloadChangedItem(RootItem* item);
// Notifies other components about messages // Notifies other components about messages
// counts. // counts.
void notifyWithCounts(); void notifyWithCounts();
private slots: private slots:
void onItemDataChanged(const QList<RootItem*> &items); void onItemDataChanged(const QList<RootItem*>& items);
signals: signals:
// Emitted if counts of messages are changed. // Emitted if counts of messages are changed.
@ -163,17 +163,17 @@ class FeedsModel : public QAbstractItemModel {
// Emitted if any item requested that its expand states should be explicitly saved. // Emitted if any item requested that its expand states should be explicitly saved.
// NOTE: Normally expand states are saved when application quits. // NOTE: Normally expand states are saved when application quits.
void itemExpandStateSaveRequested(RootItem *subtree_root); void itemExpandStateSaveRequested(RootItem* subtree_root);
// Emitted when there is a need of reloading of displayed messages. // Emitted when there is a need of reloading of displayed messages.
void reloadMessageListRequested(bool mark_selected_messages_read); void reloadMessageListRequested(bool mark_selected_messages_read);
// There was some drag/drop operation, notify view about this. // There was some drag/drop operation, notify view about this.
// NOTE: View will probably expand dropped index. // NOTE: View will probably expand dropped index.
void requireItemValidationAfterDragDrop(const QModelIndex &source_index); void requireItemValidationAfterDragDrop(const QModelIndex& source_index);
private: private:
RootItem *m_rootItem; RootItem* m_rootItem;
QList<QString> m_headerData; QList<QString> m_headerData;
QList<QString> m_tooltipData; QList<QString> m_tooltipData;
QIcon m_countsIcon; QIcon m_countsIcon;

View File

@ -25,9 +25,9 @@
#include <QTimer> #include <QTimer>
FeedsProxyModel::FeedsProxyModel(FeedsModel *source_model, QObject *parent) FeedsProxyModel::FeedsProxyModel(FeedsModel* source_model, QObject* parent)
: QSortFilterProxyModel(parent), m_sourceModel(source_model), m_selectedItem(nullptr), : QSortFilterProxyModel(parent), m_sourceModel(source_model), m_selectedItem(nullptr),
m_showUnreadOnly(false), m_hiddenIndices(QList<QPair<int,QModelIndex> >()) { m_showUnreadOnly(false), m_hiddenIndices(QList<QPair<int, QModelIndex>>()) {
setObjectName(QSL("FeedsProxyModel")); setObjectName(QSL("FeedsProxyModel"));
setSortRole(Qt::EditRole); setSortRole(Qt::EditRole);
setSortCaseSensitivity(Qt::CaseInsensitive); setSortCaseSensitivity(Qt::CaseInsensitive);
@ -42,7 +42,7 @@ FeedsProxyModel::~FeedsProxyModel() {
qDebug("Destroying FeedsProxyModel instance"); qDebug("Destroying FeedsProxyModel instance");
} }
QModelIndexList FeedsProxyModel::match(const QModelIndex &start, int role, const QVariant &value, int hits, Qt::MatchFlags flags) const { QModelIndexList FeedsProxyModel::match(const QModelIndex& start, int role, const QVariant& value, int hits, Qt::MatchFlags flags) const {
QModelIndexList result; QModelIndexList result;
const uint match_type = flags & 0x0F; const uint match_type = flags & 0x0F;
const Qt::CaseSensitivity cs = Qt::CaseInsensitive; const Qt::CaseSensitivity cs = Qt::CaseInsensitive;
@ -71,6 +71,7 @@ QModelIndexList FeedsProxyModel::match(const QModelIndex &start, int role, const
result.append(idx); result.append(idx);
} }
} }
// QString based matching. // QString based matching.
else { else {
if (entered_text.isEmpty()) { if (entered_text.isEmpty()) {
@ -84,30 +85,35 @@ QModelIndexList FeedsProxyModel::match(const QModelIndex &start, int role, const
if (QRegExp(entered_text, cs).exactMatch(item_text)) { if (QRegExp(entered_text, cs).exactMatch(item_text)) {
result.append(idx); result.append(idx);
} }
break; break;
case Qt::MatchWildcard: case Qt::MatchWildcard:
if (QRegExp(entered_text, cs, QRegExp::Wildcard).exactMatch(item_text)) { if (QRegExp(entered_text, cs, QRegExp::Wildcard).exactMatch(item_text)) {
result.append(idx); result.append(idx);
} }
break; break;
case Qt::MatchStartsWith: case Qt::MatchStartsWith:
if (item_text.startsWith(entered_text, cs)) { if (item_text.startsWith(entered_text, cs)) {
result.append(idx); result.append(idx);
} }
break; break;
case Qt::MatchEndsWith: case Qt::MatchEndsWith:
if (item_text.endsWith(entered_text, cs)) { if (item_text.endsWith(entered_text, cs)) {
result.append(idx); result.append(idx);
} }
break; break;
case Qt::MatchFixedString: case Qt::MatchFixedString:
if (item_text.compare(entered_text, cs) == 0) { if (item_text.compare(entered_text, cs) == 0) {
result.append(idx); result.append(idx);
} }
break; break;
case Qt::MatchContains: case Qt::MatchContains:
@ -115,6 +121,7 @@ QModelIndexList FeedsProxyModel::match(const QModelIndex &start, int role, const
if (item_text.contains(entered_text, cs)) { if (item_text.contains(entered_text, cs)) {
result.append(idx); result.append(idx);
} }
break; break;
} }
} }
@ -131,11 +138,11 @@ QModelIndexList FeedsProxyModel::match(const QModelIndex &start, int role, const
return result; return result;
} }
bool FeedsProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { bool FeedsProxyModel::lessThan(const QModelIndex& left, const QModelIndex& right) const {
if (left.isValid() && right.isValid()) { if (left.isValid() && right.isValid()) {
// Make necessary castings. // Make necessary castings.
const RootItem *left_item = m_sourceModel->itemForIndex(left); const RootItem* left_item = m_sourceModel->itemForIndex(left);
const RootItem *right_item = m_sourceModel->itemForIndex(right); const RootItem* right_item = m_sourceModel->itemForIndex(right);
// NOTE: Here we want to accomplish that ALL // NOTE: Here we want to accomplish that ALL
// categories are queued one after another and all // categories are queued one after another and all
@ -149,23 +156,28 @@ bool FeedsProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right
// User wants to sort according to counts. // User wants to sort according to counts.
return left_item->countOfUnreadMessages() < right_item->countOfUnreadMessages(); return left_item->countOfUnreadMessages() < right_item->countOfUnreadMessages();
} }
else { else {
// In other cases, sort by title. // In other cases, sort by title.
return QString::localeAwareCompare(left_item->title(), right_item->title()) < 0; return QString::localeAwareCompare(left_item->title(), right_item->title()) < 0;
} }
} }
else if (left_item->kind() == RootItemKind::Bin) { else if (left_item->kind() == RootItemKind::Bin) {
// Left item is recycle bin. Make sure it is "biggest" item if we have selected ascending order. // Left item is recycle bin. Make sure it is "biggest" item if we have selected ascending order.
return sortOrder() == Qt::DescendingOrder; return sortOrder() == Qt::DescendingOrder;
} }
else if (right_item->kind() == RootItemKind::Bin) { else if (right_item->kind() == RootItemKind::Bin) {
// Right item is recycle bin. Make sure it is "smallest" item if we have selected descending order. // Right item is recycle bin. Make sure it is "smallest" item if we have selected descending order.
return sortOrder() == Qt::AscendingOrder; return sortOrder() == Qt::AscendingOrder;
} }
else if (left_item->kind() == RootItemKind::Feed) { else if (left_item->kind() == RootItemKind::Feed) {
// Left item is feed, right item is category. // Left item is feed, right item is category.
return false; return false;
} }
else { else {
// Left item is category, right item is feed. // Left item is category, right item is feed.
// NOTE: Category is in fact "more" than feed but we consider it to be "less" because it should be "placed" // NOTE: Category is in fact "more" than feed but we consider it to be "less" because it should be "placed"
@ -174,29 +186,29 @@ bool FeedsProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right
return true; return true;
} }
} }
else { else {
return false; return false;
} }
} }
bool FeedsProxyModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const { bool FeedsProxyModel::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const {
bool should_show = filterAcceptsRowInternal(source_row, source_parent); bool should_show = filterAcceptsRowInternal(source_row, source_parent);
if (should_show && m_hiddenIndices.contains(QPair<int,QModelIndex>(source_row, source_parent))) { if (should_show && m_hiddenIndices.contains(QPair<int, QModelIndex>(source_row, source_parent))) {
const_cast<FeedsProxyModel*>(this)->m_hiddenIndices.removeAll(QPair<int,QModelIndex>(source_row, source_parent)); const_cast<FeedsProxyModel*>(this)->m_hiddenIndices.removeAll(QPair<int, QModelIndex>(source_row, source_parent));
// Load status. // Load status.
emit expandAfterFilterIn(m_sourceModel->index(source_row, 0, source_parent)); emit expandAfterFilterIn(m_sourceModel->index(source_row, 0, source_parent));
} }
if (!should_show) { if (!should_show) {
const_cast<FeedsProxyModel*>(this)->m_hiddenIndices.append(QPair<int,QModelIndex>(source_row, source_parent)); const_cast<FeedsProxyModel*>(this)->m_hiddenIndices.append(QPair<int, QModelIndex>(source_row, source_parent));
} }
return should_show; return should_show;
} }
bool FeedsProxyModel::filterAcceptsRowInternal(int source_row, const QModelIndex &source_parent) const { bool FeedsProxyModel::filterAcceptsRowInternal(int source_row, const QModelIndex& source_parent) const {
if (!m_showUnreadOnly) { if (!m_showUnreadOnly) {
return QSortFilterProxyModel::filterAcceptsRow(source_row, source_parent); return QSortFilterProxyModel::filterAcceptsRow(source_row, source_parent);
} }
@ -207,16 +219,18 @@ bool FeedsProxyModel::filterAcceptsRowInternal(int source_row, const QModelIndex
return false; return false;
} }
const RootItem *item = m_sourceModel->itemForIndex(idx); const RootItem* item = m_sourceModel->itemForIndex(idx);
if (item->kind() == RootItemKind::Bin || item->kind() == RootItemKind::ServiceRoot) { if (item->kind() == RootItemKind::Bin || item->kind() == RootItemKind::ServiceRoot) {
// Recycle bin is always displayed. // Recycle bin is always displayed.
return true; return true;
} }
else if (item->isParentOf(m_selectedItem)/* || item->isChildOf(m_selectedItem)*/ || m_selectedItem == item) { else if (item->isParentOf(m_selectedItem)/* || item->isChildOf(m_selectedItem)*/ || m_selectedItem == item) {
// Currently selected item and all its parents and children must be displayed. // Currently selected item and all its parents and children must be displayed.
return true; return true;
} }
else { else {
// NOTE: If item has < 0 of unread message it may mean, that the count // NOTE: If item has < 0 of unread message it may mean, that the count
// of unread messages is not (yet) known, display that item too. // of unread messages is not (yet) known, display that item too.
@ -224,11 +238,11 @@ bool FeedsProxyModel::filterAcceptsRowInternal(int source_row, const QModelIndex
} }
} }
const RootItem *FeedsProxyModel::selectedItem() const { const RootItem* FeedsProxyModel::selectedItem() const {
return m_selectedItem; return m_selectedItem;
} }
void FeedsProxyModel::setSelectedItem(const RootItem *selected_item) { void FeedsProxyModel::setSelectedItem(const RootItem* selected_item) {
m_selectedItem = selected_item; m_selectedItem = selected_item;
} }
@ -249,10 +263,10 @@ void FeedsProxyModel::setShowUnreadOnly(bool show_unread_only) {
qApp->settings()->setValue(GROUP(Feeds), Feeds::ShowOnlyUnreadFeeds, show_unread_only); qApp->settings()->setValue(GROUP(Feeds), Feeds::ShowOnlyUnreadFeeds, show_unread_only);
} }
QModelIndexList FeedsProxyModel::mapListToSource(const QModelIndexList &indexes) const { QModelIndexList FeedsProxyModel::mapListToSource(const QModelIndexList& indexes) const {
QModelIndexList source_indexes; QModelIndexList source_indexes;
foreach (const QModelIndex &index, indexes) { foreach (const QModelIndex& index, indexes) {
source_indexes << mapToSource(index); source_indexes << mapToSource(index);
} }

View File

@ -29,21 +29,21 @@ class FeedsProxyModel : public QSortFilterProxyModel {
public: public:
// Constructors and destructors. // Constructors and destructors.
explicit FeedsProxyModel(FeedsModel *source_model, QObject *parent = 0); explicit FeedsProxyModel(FeedsModel* source_model, QObject* parent = 0);
virtual ~FeedsProxyModel(); virtual ~FeedsProxyModel();
// Returns index list of items which "match" given value. // Returns index list of items which "match" given value.
// Used for finding items according to entered title text. // Used for finding items according to entered title text.
QModelIndexList match(const QModelIndex &start, int role, const QVariant &value, int hits, Qt::MatchFlags flags) const; QModelIndexList match(const QModelIndex& start, int role, const QVariant& value, int hits, Qt::MatchFlags flags) const;
// Maps list of indexes. // Maps list of indexes.
QModelIndexList mapListToSource(const QModelIndexList &indexes) const; QModelIndexList mapListToSource(const QModelIndexList& indexes) const;
bool showUnreadOnly() const; bool showUnreadOnly() const;
void setShowUnreadOnly(bool show_unread_only); void setShowUnreadOnly(bool show_unread_only);
const RootItem *selectedItem() const; const RootItem* selectedItem() const;
void setSelectedItem(const RootItem *selected_item); void setSelectedItem(const RootItem* selected_item);
public slots: public slots:
void invalidateReadFeedsFilter(bool set_new_value = false, bool show_unread_only = false); void invalidateReadFeedsFilter(bool set_new_value = false, bool show_unread_only = false);
@ -56,15 +56,15 @@ class FeedsProxyModel : public QSortFilterProxyModel {
private: private:
// Compares two rows of data. // Compares two rows of data.
bool lessThan(const QModelIndex &left, const QModelIndex &right) const; bool lessThan(const QModelIndex& left, const QModelIndex& right) const;
bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const; bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const;
bool filterAcceptsRowInternal(int source_row, const QModelIndex &source_parent) const; bool filterAcceptsRowInternal(int source_row, const QModelIndex& source_parent) const;
// Source model pointer. // Source model pointer.
FeedsModel *m_sourceModel; FeedsModel* m_sourceModel;
const RootItem *m_selectedItem; const RootItem* m_selectedItem;
bool m_showUnreadOnly; bool m_showUnreadOnly;
QList<QPair<int,QModelIndex> > m_hiddenIndices; QList<QPair<int, QModelIndex>> m_hiddenIndices;
}; };
#endif // FEEDSPROXYMODEL_H #endif // FEEDSPROXYMODEL_H

View File

@ -22,21 +22,21 @@
#include <QVariant> #include <QVariant>
Enclosure::Enclosure(const QString &url, const QString &mime) : m_url(url), m_mimeType(mime) { Enclosure::Enclosure(const QString& url, const QString& mime) : m_url(url), m_mimeType(mime) {
} }
QList<Enclosure> Enclosures::decodeEnclosuresFromString(const QString &enclosures_data) { QList<Enclosure> Enclosures::decodeEnclosuresFromString(const QString& enclosures_data) {
QList<Enclosure> enclosures; QList<Enclosure> enclosures;
foreach (const QString &single_enclosure, enclosures_data.split(ENCLOSURES_OUTER_SEPARATOR, QString::SkipEmptyParts)) { foreach (const QString& single_enclosure, enclosures_data.split(ENCLOSURES_OUTER_SEPARATOR, QString::SkipEmptyParts)) {
Enclosure enclosure; Enclosure enclosure;
if (single_enclosure.contains(ECNLOSURES_INNER_SEPARATOR)) { if (single_enclosure.contains(ECNLOSURES_INNER_SEPARATOR)) {
QStringList mime_url = single_enclosure.split(ECNLOSURES_INNER_SEPARATOR); QStringList mime_url = single_enclosure.split(ECNLOSURES_INNER_SEPARATOR);
enclosure.m_mimeType = QByteArray::fromBase64(mime_url.at(0).toLocal8Bit()); enclosure.m_mimeType = QByteArray::fromBase64(mime_url.at(0).toLocal8Bit());
enclosure.m_url = QByteArray::fromBase64(mime_url.at(1).toLocal8Bit()); enclosure.m_url = QByteArray::fromBase64(mime_url.at(1).toLocal8Bit());
} }
else { else {
enclosure.m_url = QByteArray::fromBase64(single_enclosure.toLocal8Bit()); enclosure.m_url = QByteArray::fromBase64(single_enclosure.toLocal8Bit());
} }
@ -47,13 +47,14 @@ QList<Enclosure> Enclosures::decodeEnclosuresFromString(const QString &enclosure
return enclosures; return enclosures;
} }
QString Enclosures::encodeEnclosuresToString(const QList<Enclosure> &enclosures) { QString Enclosures::encodeEnclosuresToString(const QList<Enclosure>& enclosures) {
QStringList enclosures_str; QStringList enclosures_str;
foreach (const Enclosure &enclosure, enclosures) { foreach (const Enclosure& enclosure, enclosures) {
if (enclosure.m_mimeType.isEmpty()) { if (enclosure.m_mimeType.isEmpty()) {
enclosures_str.append(enclosure.m_url.toLocal8Bit().toBase64()); enclosures_str.append(enclosure.m_url.toLocal8Bit().toBase64());
} }
else { else {
enclosures_str.append(QString(enclosure.m_mimeType.toLocal8Bit().toBase64()) + enclosures_str.append(QString(enclosure.m_mimeType.toLocal8Bit().toBase64()) +
ECNLOSURES_INNER_SEPARATOR + ECNLOSURES_INNER_SEPARATOR +
@ -71,7 +72,7 @@ Message::Message() {
m_isRead = m_isImportant = false; m_isRead = m_isImportant = false;
} }
Message Message::fromSqlRecord(const QSqlRecord &record, bool *result) { Message Message::fromSqlRecord(const QSqlRecord& record, bool* result) {
if (record.count() != MSG_DB_CUSTOM_HASH_INDEX + 1) { if (record.count() != MSG_DB_CUSTOM_HASH_INDEX + 1) {
if (result != nullptr) { if (result != nullptr) {
*result = false; *result = false;
@ -80,7 +81,6 @@ Message Message::fromSqlRecord(const QSqlRecord &record, bool *result) {
} }
Message message; Message message;
message.m_id = record.value(MSG_DB_ID_INDEX).toInt(); message.m_id = record.value(MSG_DB_ID_INDEX).toInt();
message.m_isRead = record.value(MSG_DB_READ_INDEX).toBool(); message.m_isRead = record.value(MSG_DB_READ_INDEX).toBool();
message.m_isImportant = record.value(MSG_DB_IMPORTANT_INDEX).toBool(); message.m_isImportant = record.value(MSG_DB_IMPORTANT_INDEX).toBool();
@ -107,6 +107,6 @@ uint qHash(Message key, uint seed) {
return (key.m_accountId * 10000) + key.m_id; return (key.m_accountId * 10000) + key.m_id;
} }
uint qHash(const Message &key) { uint qHash(const Message& key) {
return (key.m_accountId * 10000) + key.m_id; return (key.m_accountId * 10000) + key.m_id;
} }

View File

@ -28,7 +28,7 @@
// Represents single enclosure. // Represents single enclosure.
struct Enclosure { struct Enclosure {
public: public:
explicit Enclosure(const QString &url = QString(), const QString &mime = QString()); explicit Enclosure(const QString& url = QString(), const QString& mime = QString());
QString m_url; QString m_url;
QString m_mimeType; QString m_mimeType;
@ -37,8 +37,8 @@ struct Enclosure {
// Represents single enclosure. // Represents single enclosure.
class Enclosures { class Enclosures {
public: public:
static QList<Enclosure> decodeEnclosuresFromString(const QString &enclosures_data); static QList<Enclosure> decodeEnclosuresFromString(const QString& enclosures_data);
static QString encodeEnclosuresToString(const QList<Enclosure> &enclosures); static QString encodeEnclosuresToString(const QList<Enclosure>& enclosures);
}; };
// Represents single message. // Represents single message.
@ -48,7 +48,7 @@ class Message {
// Creates Message from given record, which contains // Creates Message from given record, which contains
// row from query SELECT * FROM Messages WHERE ....; // row from query SELECT * FROM Messages WHERE ....;
static Message fromSqlRecord(const QSqlRecord &record, bool *result = nullptr); static Message fromSqlRecord(const QSqlRecord& record, bool* result = nullptr);
QString m_title; QString m_title;
QString m_url; QString m_url;
@ -70,16 +70,16 @@ class Message {
// from the feed, otherwise is false // from the feed, otherwise is false
bool m_createdFromFeed; bool m_createdFromFeed;
friend inline bool operator==(const Message &lhs, const Message &rhs) { friend inline bool operator==(const Message& lhs, const Message& rhs) {
return lhs.m_accountId == rhs.m_accountId && lhs.m_id == rhs.m_id; return lhs.m_accountId == rhs.m_accountId && lhs.m_id == rhs.m_id;
} }
friend inline bool operator!=(const Message &lhs, const Message &rhs) { friend inline bool operator!=(const Message& lhs, const Message& rhs) {
return !(lhs == rhs); return !(lhs == rhs);
} }
}; };
uint qHash(Message key, uint seed); uint qHash(Message key, uint seed);
uint qHash(const Message &key); uint qHash(const Message& key);
#endif // MESSAGE_H #endif // MESSAGE_H

View File

@ -30,14 +30,13 @@
#include <QSqlField> #include <QSqlField>
MessagesModel::MessagesModel(QObject *parent) MessagesModel::MessagesModel(QObject* parent)
: QSqlQueryModel(parent), MessagesModelSqlLayer(), : QSqlQueryModel(parent), MessagesModelSqlLayer(),
m_cache(new MessagesModelCache(this)), m_messageHighlighter(NoHighlighting), m_customDateFormat(QString()) { m_cache(new MessagesModelCache(this)), m_messageHighlighter(NoHighlighting), m_customDateFormat(QString()) {
setupFonts(); setupFonts();
setupIcons(); setupIcons();
setupHeaderData(); setupHeaderData();
updateDateFormat(); updateDateFormat();
loadMessages(nullptr); loadMessages(nullptr);
} }
@ -60,9 +59,8 @@ void MessagesModel::repopulate() {
} }
} }
bool MessagesModel::setData(const QModelIndex &index, const QVariant &value, int role) { bool MessagesModel::setData(const QModelIndex& index, const QVariant& value, int role) {
Q_UNUSED(role) Q_UNUSED(role)
m_cache->setData(index, value, record(index.row())); m_cache->setData(index, value, record(index.row()));
return true; return true;
} }
@ -72,19 +70,19 @@ void MessagesModel::setupFonts() {
m_normalFont = Application::font("MessagesView"); m_normalFont = Application::font("MessagesView");
m_boldFont = m_normalFont; m_boldFont = m_normalFont;
m_boldFont.setBold(true); m_boldFont.setBold(true);
m_normalStrikedFont = m_normalFont; m_normalStrikedFont = m_normalFont;
m_boldStrikedFont = m_boldFont; m_boldStrikedFont = m_boldFont;
m_normalStrikedFont.setStrikeOut(true); m_normalStrikedFont.setStrikeOut(true);
m_boldStrikedFont.setStrikeOut(true); m_boldStrikedFont.setStrikeOut(true);
} }
void MessagesModel::loadMessages(RootItem *item) { void MessagesModel::loadMessages(RootItem* item) {
m_selectedItem = item; m_selectedItem = item;
if (item == nullptr) { if (item == nullptr) {
setFilter(QSL(DEFAULT_SQL_MESSAGES_FILTER)); setFilter(QSL(DEFAULT_SQL_MESSAGES_FILTER));
} }
else { else {
if (!item->getParentServiceRoot()->loadMessagesForItem(item, this)) { if (!item->getParentServiceRoot()->loadMessagesForItem(item, this)) {
setFilter(QSL("true != true")); setFilter(QSL("true != true"));
@ -132,7 +130,7 @@ RootItem::Importance MessagesModel::messageImportance(int row_index) const {
return (RootItem::Importance) data(row_index, MSG_DB_IMPORTANT_INDEX, Qt::EditRole).toInt(); return (RootItem::Importance) data(row_index, MSG_DB_IMPORTANT_INDEX, Qt::EditRole).toInt();
} }
RootItem *MessagesModel::loadedItem() const { RootItem* MessagesModel::loadedItem() const {
return m_selectedItem; return m_selectedItem;
} }
@ -140,6 +138,7 @@ void MessagesModel::updateDateFormat() {
if (qApp->settings()->value(GROUP(Messages), SETTING(Messages::UseCustomDate)).toBool()) { if (qApp->settings()->value(GROUP(Messages), SETTING(Messages::UseCustomDate)).toBool()) {
m_customDateFormat = qApp->settings()->value(GROUP(Messages), SETTING(Messages::CustomDateFormat)).toString(); m_customDateFormat = qApp->settings()->value(GROUP(Messages), SETTING(Messages::CustomDateFormat)).toString();
} }
else { else {
m_customDateFormat = QString(); m_customDateFormat = QString();
} }
@ -171,7 +170,6 @@ void MessagesModel::setupHeaderData() {
/*: Tooltip for custom ID of message.*/ tr("Custom ID") << /*: Tooltip for custom ID of message.*/ tr("Custom ID") <<
/*: Tooltip for custom hash string of message.*/ tr("Custom hash") << /*: Tooltip for custom hash string of message.*/ tr("Custom hash") <<
/*: Tooltip for custom ID of feed of message.*/ tr("Feed ID");; /*: Tooltip for custom ID of feed of message.*/ tr("Feed ID");;
m_tooltipData << tr("Id of the message.") << tr("Is message read?") << m_tooltipData << tr("Id of the message.") << tr("Is message read?") <<
tr("Is message deleted?") << tr("Is message important?") << tr("Is message deleted?") << tr("Is message important?") <<
tr("Id of feed which this message belongs to.") << tr("Id of feed which this message belongs to.") <<
@ -182,9 +180,8 @@ void MessagesModel::setupHeaderData() {
tr("Custom hash of the message.") << tr("Custom ID of feed of the message."); tr("Custom hash of the message.") << tr("Custom ID of feed of the message.");
} }
Qt::ItemFlags MessagesModel::flags(const QModelIndex &index) const { Qt::ItemFlags MessagesModel::flags(const QModelIndex& index) const {
Q_UNUSED(index) Q_UNUSED(index)
return Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemNeverHasChildren; return Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemNeverHasChildren;
} }
@ -192,7 +189,7 @@ QVariant MessagesModel::data(int row, int column, int role) const {
return data(index(row, column), role); return data(index(row, column), role);
} }
QVariant MessagesModel::data(const QModelIndex &idx, int role) const { QVariant MessagesModel::data(const QModelIndex& idx, int role) const {
// This message is not in cache, return real data from live query. // This message is not in cache, return real data from live query.
switch (role) { switch (role) {
// Human readable data for viewing. // Human readable data for viewing.
@ -205,18 +202,21 @@ QVariant MessagesModel::data(const QModelIndex &idx, int role) const {
if (m_customDateFormat.isEmpty()) { if (m_customDateFormat.isEmpty()) {
return dt.toString(Qt::DefaultLocaleShortDate); return dt.toString(Qt::DefaultLocaleShortDate);
} }
else { else {
return dt.toString(m_customDateFormat); return dt.toString(m_customDateFormat);
} }
} }
else if (index_column == MSG_DB_AUTHOR_INDEX) { else if (index_column == MSG_DB_AUTHOR_INDEX) {
const QString author_name = QSqlQueryModel::data(idx, role).toString(); const QString author_name = QSqlQueryModel::data(idx, role).toString();
return author_name.isEmpty() ? QSL("-") : author_name; return author_name.isEmpty() ? QSL("-") : author_name;
} }
else if (index_column != MSG_DB_IMPORTANT_INDEX && index_column != MSG_DB_READ_INDEX) { else if (index_column != MSG_DB_IMPORTANT_INDEX && index_column != MSG_DB_READ_INDEX) {
return QSqlQueryModel::data(idx, role); return QSqlQueryModel::data(idx, role);
} }
else { else {
return QVariant(); return QVariant();
} }
@ -228,7 +228,6 @@ QVariant MessagesModel::data(const QModelIndex &idx, int role) const {
case Qt::FontRole: { case Qt::FontRole: {
QModelIndex idx_read = index(idx.row(), MSG_DB_READ_INDEX); QModelIndex idx_read = index(idx.row(), MSG_DB_READ_INDEX);
QVariant data_read = data(idx_read, Qt::EditRole); QVariant data_read = data(idx_read, Qt::EditRole);
const bool is_bin = qobject_cast<RecycleBin*>(loadedItem()) != nullptr; const bool is_bin = qobject_cast<RecycleBin*>(loadedItem()) != nullptr;
bool is_deleted; bool is_deleted;
@ -236,6 +235,7 @@ QVariant MessagesModel::data(const QModelIndex &idx, int role) const {
QModelIndex idx_del = index(idx.row(), MSG_DB_PDELETED_INDEX); QModelIndex idx_del = index(idx.row(), MSG_DB_PDELETED_INDEX);
is_deleted = data(idx_del, Qt::EditRole).toBool(); is_deleted = data(idx_del, Qt::EditRole).toBool();
} }
else { else {
QModelIndex idx_del = index(idx.row(), MSG_DB_DELETED_INDEX); QModelIndex idx_del = index(idx.row(), MSG_DB_DELETED_INDEX);
is_deleted = data(idx_del, Qt::EditRole).toBool(); is_deleted = data(idx_del, Qt::EditRole).toBool();
@ -246,6 +246,7 @@ QVariant MessagesModel::data(const QModelIndex &idx, int role) const {
if (data_read.toBool()) { if (data_read.toBool()) {
return striked ? m_normalStrikedFont : m_normalFont; return striked ? m_normalStrikedFont : m_normalFont;
} }
else { else {
return striked ? m_boldStrikedFont : m_boldFont; return striked ? m_boldStrikedFont : m_boldFont;
} }
@ -256,14 +257,12 @@ QVariant MessagesModel::data(const QModelIndex &idx, int role) const {
case HighlightImportant: { case HighlightImportant: {
QModelIndex idx_important = index(idx.row(), MSG_DB_IMPORTANT_INDEX); QModelIndex idx_important = index(idx.row(), MSG_DB_IMPORTANT_INDEX);
QVariant dta = m_cache->containsData(idx_important.row()) ? m_cache->data(idx_important) : QSqlQueryModel::data(idx_important); QVariant dta = m_cache->containsData(idx_important.row()) ? m_cache->data(idx_important) : QSqlQueryModel::data(idx_important);
return dta.toInt() == 1 ? QColor(Qt::blue) : QVariant(); return dta.toInt() == 1 ? QColor(Qt::blue) : QVariant();
} }
case HighlightUnread: { case HighlightUnread: {
QModelIndex idx_read = index(idx.row(), MSG_DB_READ_INDEX); QModelIndex idx_read = index(idx.row(), MSG_DB_READ_INDEX);
QVariant dta = m_cache->containsData(idx_read.row()) ? m_cache->data(idx_read) : QSqlQueryModel::data(idx_read); QVariant dta = m_cache->containsData(idx_read.row()) ? m_cache->data(idx_read) : QSqlQueryModel::data(idx_read);
return dta.toInt() == 0 ? QColor(Qt::blue) : QVariant(); return dta.toInt() == 0 ? QColor(Qt::blue) : QVariant();
} }
@ -278,15 +277,15 @@ QVariant MessagesModel::data(const QModelIndex &idx, int role) const {
if (index_column == MSG_DB_READ_INDEX) { if (index_column == MSG_DB_READ_INDEX) {
QModelIndex idx_read = index(idx.row(), MSG_DB_READ_INDEX); QModelIndex idx_read = index(idx.row(), MSG_DB_READ_INDEX);
QVariant dta = m_cache->containsData(idx_read.row()) ? m_cache->data(idx_read) : QSqlQueryModel::data(idx_read); QVariant dta = m_cache->containsData(idx_read.row()) ? m_cache->data(idx_read) : QSqlQueryModel::data(idx_read);
return dta.toInt() == 1 ? m_readIcon : m_unreadIcon; return dta.toInt() == 1 ? m_readIcon : m_unreadIcon;
} }
else if (index_column == MSG_DB_IMPORTANT_INDEX) { else if (index_column == MSG_DB_IMPORTANT_INDEX) {
QModelIndex idx_important = index(idx.row(), MSG_DB_IMPORTANT_INDEX); QModelIndex idx_important = index(idx.row(), MSG_DB_IMPORTANT_INDEX);
QVariant dta = m_cache->containsData(idx_important.row()) ? m_cache->data(idx_important) : QSqlQueryModel::data(idx_important); QVariant dta = m_cache->containsData(idx_important.row()) ? m_cache->data(idx_important) : QSqlQueryModel::data(idx_important);
return dta.toInt() == 1 ? m_favoriteIcon : QVariant(); return dta.toInt() == 1 ? m_favoriteIcon : QVariant();
} }
else { else {
return QVariant(); return QVariant();
} }
@ -323,6 +322,7 @@ bool MessagesModel::setMessageRead(int row_index, RootItem::ReadStatus read) {
if (DatabaseQueries::markMessagesReadUnread(m_db, QStringList() << QString::number(message.m_id), read)) { if (DatabaseQueries::markMessagesReadUnread(m_db, QStringList() << QString::number(message.m_id), read)) {
return m_selectedItem->getParentServiceRoot()->onAfterSetMessagesRead(m_selectedItem, QList<Message>() << message, read); return m_selectedItem->getParentServiceRoot()->onAfterSetMessagesRead(m_selectedItem, QList<Message>() << message, read);
} }
else { else {
return false; return false;
} }
@ -352,10 +352,10 @@ bool MessagesModel::switchMessageImportance(int row_index) {
const RootItem::Importance next_importance = current_importance == RootItem::Important ? const RootItem::Importance next_importance = current_importance == RootItem::Important ?
RootItem::NotImportant : RootItem::Important; RootItem::NotImportant : RootItem::Important;
const Message message = messageAt(row_index); const Message message = messageAt(row_index);
const QPair<Message,RootItem::Importance> pair(message, next_importance); const QPair<Message, RootItem::Importance> pair(message, next_importance);
if (!m_selectedItem->getParentServiceRoot()->onBeforeSwitchMessageImportance(m_selectedItem, if (!m_selectedItem->getParentServiceRoot()->onBeforeSwitchMessageImportance(m_selectedItem,
QList<QPair<Message,RootItem::Importance> >() << pair)) { QList<QPair<Message, RootItem::Importance>>() << pair)) {
return false; return false;
} }
@ -371,29 +371,27 @@ bool MessagesModel::switchMessageImportance(int row_index) {
// Commit changes. // Commit changes.
if (DatabaseQueries::markMessageImportant(m_db, message.m_id, next_importance)) { if (DatabaseQueries::markMessageImportant(m_db, message.m_id, next_importance)) {
emit dataChanged(index(row_index, 0), index(row_index, MSG_DB_FEED_CUSTOM_ID_INDEX), QVector<int>() << Qt::FontRole); emit dataChanged(index(row_index, 0), index(row_index, MSG_DB_FEED_CUSTOM_ID_INDEX), QVector<int>() << Qt::FontRole);
return m_selectedItem->getParentServiceRoot()->onAfterSwitchMessageImportance(m_selectedItem, return m_selectedItem->getParentServiceRoot()->onAfterSwitchMessageImportance(m_selectedItem,
QList<QPair<Message,RootItem::Importance> >() << pair); QList<QPair<Message, RootItem::Importance>>() << pair);
} }
else { else {
return false; return false;
} }
} }
bool MessagesModel::switchBatchMessageImportance(const QModelIndexList &messages) { bool MessagesModel::switchBatchMessageImportance(const QModelIndexList& messages) {
QStringList message_ids; QStringList message_ids;
QList<QPair<Message,RootItem::Importance> > message_states; QList<QPair<Message, RootItem::Importance>> message_states;
// Obtain IDs of all desired messages. // Obtain IDs of all desired messages.
foreach (const QModelIndex &message, messages) { foreach (const QModelIndex& message, messages) {
const Message msg = messageAt(message.row()); const Message msg = messageAt(message.row());
RootItem::Importance message_importance = messageImportance((message.row())); RootItem::Importance message_importance = messageImportance((message.row()));
message_states.append(QPair<Message, RootItem::Importance>(msg, message_importance == RootItem::Important ?
message_states.append(QPair<Message,RootItem::Importance>(msg, message_importance == RootItem::Important ?
RootItem::NotImportant : RootItem::NotImportant :
RootItem::Important)); RootItem::Important));
message_ids.append(QString::number(msg.m_id)); message_ids.append(QString::number(msg.m_id));
QModelIndex idx_msg_imp = index(message.row(), MSG_DB_IMPORTANT_INDEX); QModelIndex idx_msg_imp = index(message.row(), MSG_DB_IMPORTANT_INDEX);
setData(idx_msg_imp, message_importance == RootItem::Important ? setData(idx_msg_imp, message_importance == RootItem::Important ?
(int) RootItem::NotImportant : (int) RootItem::NotImportant :
@ -409,25 +407,26 @@ bool MessagesModel::switchBatchMessageImportance(const QModelIndexList &messages
if (DatabaseQueries::switchMessagesImportance(m_db, message_ids)) { if (DatabaseQueries::switchMessagesImportance(m_db, message_ids)) {
return m_selectedItem->getParentServiceRoot()->onAfterSwitchMessageImportance(m_selectedItem, message_states); return m_selectedItem->getParentServiceRoot()->onAfterSwitchMessageImportance(m_selectedItem, message_states);
} }
else { else {
return false; return false;
} }
} }
bool MessagesModel::setBatchMessagesDeleted(const QModelIndexList &messages) { bool MessagesModel::setBatchMessagesDeleted(const QModelIndexList& messages) {
QStringList message_ids; QStringList message_ids;
QList<Message> msgs; QList<Message> msgs;
// Obtain IDs of all desired messages. // Obtain IDs of all desired messages.
foreach (const QModelIndex &message, messages) { foreach (const QModelIndex& message, messages) {
const Message msg = messageAt(message.row()); const Message msg = messageAt(message.row());
msgs.append(msg); msgs.append(msg);
message_ids.append(QString::number(msg.m_id)); message_ids.append(QString::number(msg.m_id));
if (qobject_cast<RecycleBin*>(m_selectedItem) != nullptr) { if (qobject_cast<RecycleBin*>(m_selectedItem) != nullptr) {
setData(index(message.row(), MSG_DB_PDELETED_INDEX), 1); setData(index(message.row(), MSG_DB_PDELETED_INDEX), 1);
} }
else { else {
setData(index(message.row(), MSG_DB_DELETED_INDEX), 1); setData(index(message.row(), MSG_DB_DELETED_INDEX), 1);
} }
@ -444,6 +443,7 @@ bool MessagesModel::setBatchMessagesDeleted(const QModelIndexList &messages) {
if (m_selectedItem->kind() != RootItemKind::Bin) { if (m_selectedItem->kind() != RootItemKind::Bin) {
deleted = DatabaseQueries::deleteOrRestoreMessagesToFromBin(m_db, message_ids, true); deleted = DatabaseQueries::deleteOrRestoreMessagesToFromBin(m_db, message_ids, true);
} }
else { else {
deleted = DatabaseQueries::permanentlyDeleteMessages(m_db, message_ids); deleted = DatabaseQueries::permanentlyDeleteMessages(m_db, message_ids);
} }
@ -451,22 +451,21 @@ bool MessagesModel::setBatchMessagesDeleted(const QModelIndexList &messages) {
if (deleted) { if (deleted) {
return m_selectedItem->getParentServiceRoot()->onAfterMessagesDelete(m_selectedItem, msgs); return m_selectedItem->getParentServiceRoot()->onAfterMessagesDelete(m_selectedItem, msgs);
} }
else { else {
return false; return false;
} }
} }
bool MessagesModel::setBatchMessagesRead(const QModelIndexList &messages, RootItem::ReadStatus read) { bool MessagesModel::setBatchMessagesRead(const QModelIndexList& messages, RootItem::ReadStatus read) {
QStringList message_ids; QStringList message_ids;
QList<Message> msgs; QList<Message> msgs;
// Obtain IDs of all desired messages. // Obtain IDs of all desired messages.
foreach (const QModelIndex &message, messages) { foreach (const QModelIndex& message, messages) {
Message msg = messageAt(message.row()); Message msg = messageAt(message.row());
msgs.append(msg); msgs.append(msg);
message_ids.append(QString::number(msg.m_id)); message_ids.append(QString::number(msg.m_id));
setData(index(message.row(), MSG_DB_READ_INDEX), (int) read); setData(index(message.row(), MSG_DB_READ_INDEX), (int) read);
} }
@ -479,22 +478,21 @@ bool MessagesModel::setBatchMessagesRead(const QModelIndexList &messages, RootIt
if (DatabaseQueries::markMessagesReadUnread(m_db, message_ids, read)) { if (DatabaseQueries::markMessagesReadUnread(m_db, message_ids, read)) {
return m_selectedItem->getParentServiceRoot()->onAfterSetMessagesRead(m_selectedItem, msgs, read); return m_selectedItem->getParentServiceRoot()->onAfterSetMessagesRead(m_selectedItem, msgs, read);
} }
else { else {
return false; return false;
} }
} }
bool MessagesModel::setBatchMessagesRestored(const QModelIndexList &messages) { bool MessagesModel::setBatchMessagesRestored(const QModelIndexList& messages) {
QStringList message_ids; QStringList message_ids;
QList<Message> msgs; QList<Message> msgs;
// Obtain IDs of all desired messages. // Obtain IDs of all desired messages.
foreach (const QModelIndex &message, messages) { foreach (const QModelIndex& message, messages) {
const Message msg = messageAt(message.row()); const Message msg = messageAt(message.row());
msgs.append(msg); msgs.append(msg);
message_ids.append(QString::number(msg.m_id)); message_ids.append(QString::number(msg.m_id));
setData(index(message.row(), MSG_DB_PDELETED_INDEX), 0); setData(index(message.row(), MSG_DB_PDELETED_INDEX), 0);
setData(index(message.row(), MSG_DB_DELETED_INDEX), 0); setData(index(message.row(), MSG_DB_DELETED_INDEX), 0);
} }
@ -508,6 +506,7 @@ bool MessagesModel::setBatchMessagesRestored(const QModelIndexList &messages) {
if (DatabaseQueries::deleteOrRestoreMessagesToFromBin(m_db, message_ids, false)) { if (DatabaseQueries::deleteOrRestoreMessagesToFromBin(m_db, message_ids, false)) {
return m_selectedItem->getParentServiceRoot()->onAfterMessagesRestoredFromBin(m_selectedItem, msgs); return m_selectedItem->getParentServiceRoot()->onAfterMessagesRestoredFromBin(m_selectedItem, msgs);
} }
else { else {
return false; return false;
} }
@ -518,11 +517,13 @@ QVariant MessagesModel::headerData(int section, Qt::Orientation orientation, int
switch (role) { switch (role) {
case Qt::DisplayRole: case Qt::DisplayRole:
// Display textual headers for all columns except "read" and // Display textual headers for all columns except "read" and
// "important" columns. // "important" columns.
if (section != MSG_DB_READ_INDEX && section != MSG_DB_IMPORTANT_INDEX) { if (section != MSG_DB_READ_INDEX && section != MSG_DB_IMPORTANT_INDEX) {
return m_headerData.at(section); return m_headerData.at(section);
} }
else { else {
return QVariant(); return QVariant();
} }

View File

@ -44,7 +44,7 @@ class MessagesModel : public QSqlQueryModel, public MessagesModelSqlLayer {
}; };
// Constructors and destructors. // Constructors and destructors.
explicit MessagesModel(QObject *parent = 0); explicit MessagesModel(QObject* parent = 0);
virtual ~MessagesModel(); virtual ~MessagesModel();
// Fetches ALL available data to the model. // Fetches ALL available data to the model.
@ -52,18 +52,18 @@ class MessagesModel : public QSqlQueryModel, public MessagesModelSqlLayer {
void repopulate(); void repopulate();
// Model implementation. // Model implementation.
bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole); bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole);
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const;
QVariant data(int row, int column, int role = Qt::DisplayRole) const; QVariant data(int row, int column, int role = Qt::DisplayRole) const;
QVariant headerData(int section, Qt::Orientation orientation, int role) const; QVariant headerData(int section, Qt::Orientation orientation, int role) const;
Qt::ItemFlags flags(const QModelIndex &index) const; Qt::ItemFlags flags(const QModelIndex& index) const;
// Returns message at given index. // Returns message at given index.
Message messageAt(int row_index) const; Message messageAt(int row_index) const;
int messageId(int row_index) const; int messageId(int row_index) const;
RootItem::Importance messageImportance(int row_index) const; RootItem::Importance messageImportance(int row_index) const;
RootItem *loadedItem() const; RootItem* loadedItem() const;
void updateDateFormat(); void updateDateFormat();
void reloadWholeLayout(); void reloadWholeLayout();
@ -72,16 +72,16 @@ class MessagesModel : public QSqlQueryModel, public MessagesModelSqlLayer {
bool setMessageRead(int row_index, RootItem::ReadStatus read); bool setMessageRead(int row_index, RootItem::ReadStatus read);
// BATCH messages manipulators. // BATCH messages manipulators.
bool switchBatchMessageImportance(const QModelIndexList &messages); bool switchBatchMessageImportance(const QModelIndexList& messages);
bool setBatchMessagesDeleted(const QModelIndexList &messages); bool setBatchMessagesDeleted(const QModelIndexList& messages);
bool setBatchMessagesRead(const QModelIndexList &messages, RootItem::ReadStatus read); bool setBatchMessagesRead(const QModelIndexList& messages, RootItem::ReadStatus read);
bool setBatchMessagesRestored(const QModelIndexList &messages); bool setBatchMessagesRestored(const QModelIndexList& messages);
// Highlights messages. // Highlights messages.
void highlightMessages(MessageHighlighter highlight); void highlightMessages(MessageHighlighter highlight);
// Loads messages of given feeds. // Loads messages of given feeds.
void loadMessages(RootItem *item); void loadMessages(RootItem* item);
public slots: public slots:
// NOTE: These methods DO NOT actually change data in the DB, just in the model. // NOTE: These methods DO NOT actually change data in the DB, just in the model.
@ -94,11 +94,11 @@ class MessagesModel : public QSqlQueryModel, public MessagesModelSqlLayer {
void setupFonts(); void setupFonts();
void setupIcons(); void setupIcons();
MessagesModelCache *m_cache; MessagesModelCache* m_cache;
MessageHighlighter m_messageHighlighter; MessageHighlighter m_messageHighlighter;
QString m_customDateFormat; QString m_customDateFormat;
RootItem *m_selectedItem; RootItem* m_selectedItem;
QList<QString> m_headerData; QList<QString> m_headerData;
QList<QString> m_tooltipData; QList<QString> m_tooltipData;

View File

@ -20,13 +20,13 @@
#include "miscellaneous/textfactory.h" #include "miscellaneous/textfactory.h"
MessagesModelCache::MessagesModelCache(QObject *parent) : QObject(parent), m_msgCache(QHash<int,QSqlRecord>()) { MessagesModelCache::MessagesModelCache(QObject* parent) : QObject(parent), m_msgCache(QHash<int, QSqlRecord>()) {
} }
MessagesModelCache::~MessagesModelCache() { MessagesModelCache::~MessagesModelCache() {
} }
void MessagesModelCache::setData(const QModelIndex &index, const QVariant &value, const QSqlRecord &record) { void MessagesModelCache::setData(const QModelIndex& index, const QVariant& value, const QSqlRecord& record) {
if (!m_msgCache.contains(index.row())) { if (!m_msgCache.contains(index.row())) {
m_msgCache[index.row()] = record; m_msgCache[index.row()] = record;
} }
@ -34,6 +34,6 @@ void MessagesModelCache::setData(const QModelIndex &index, const QVariant &value
m_msgCache[index.row()].setValue(index.column(), value); m_msgCache[index.row()].setValue(index.column(), value);
} }
QVariant MessagesModelCache::data(const QModelIndex &idx) { QVariant MessagesModelCache::data(const QModelIndex& idx) {
return m_msgCache[idx.row()].value(idx.column()); return m_msgCache[idx.row()].value(idx.column());
} }

View File

@ -30,7 +30,7 @@ class MessagesModelCache : public QObject {
Q_OBJECT Q_OBJECT
public: public:
explicit MessagesModelCache(QObject *parent = nullptr); explicit MessagesModelCache(QObject* parent = nullptr);
virtual ~MessagesModelCache(); virtual ~MessagesModelCache();
inline bool containsData(int row_idx) const { inline bool containsData(int row_idx) const {
@ -45,11 +45,11 @@ class MessagesModelCache : public QObject {
m_msgCache.clear(); m_msgCache.clear();
} }
void setData(const QModelIndex &index, const QVariant &value, const QSqlRecord &record); void setData(const QModelIndex& index, const QVariant& value, const QSqlRecord& record);
QVariant data(const QModelIndex &idx); QVariant data(const QModelIndex& idx);
private: private:
QHash<int,QSqlRecord> m_msgCache; QHash<int, QSqlRecord> m_msgCache;
}; };
#endif // MESSAGESMODELCACHE_H #endif // MESSAGESMODELCACHE_H

View File

@ -22,10 +22,9 @@
MessagesModelSqlLayer::MessagesModelSqlLayer() MessagesModelSqlLayer::MessagesModelSqlLayer()
: m_filter(QSL(DEFAULT_SQL_MESSAGES_FILTER)), m_fieldNames(QMap<int,QString>()), : m_filter(QSL(DEFAULT_SQL_MESSAGES_FILTER)), m_fieldNames(QMap<int, QString>()),
m_sortColumns(QList<int>()), m_sortOrders(QList<Qt::SortOrder>()){ m_sortColumns(QList<int>()), m_sortOrders(QList<Qt::SortOrder>()) {
m_db = qApp->database()->connection(QSL("MessagesModel"), DatabaseFactory::FromSettings); m_db = qApp->database()->connection(QSL("MessagesModel"), DatabaseFactory::FromSettings);
m_fieldNames[MSG_DB_ID_INDEX] = "Messages.id"; m_fieldNames[MSG_DB_ID_INDEX] = "Messages.id";
m_fieldNames[MSG_DB_READ_INDEX] = "Messages.is_read"; m_fieldNames[MSG_DB_READ_INDEX] = "Messages.is_read";
m_fieldNames[MSG_DB_DELETED_INDEX] = "Messages.is_deleted"; m_fieldNames[MSG_DB_DELETED_INDEX] = "Messages.is_deleted";
@ -65,6 +64,7 @@ void MessagesModelSqlLayer::addSortState(int column, Qt::SortOrder order) {
m_sortColumns.append(column); m_sortColumns.append(column);
m_sortOrders.append(order); m_sortOrders.append(order);
} }
else { else {
m_sortColumns.prepend(column); m_sortColumns.prepend(column);
m_sortOrders.prepend(order); m_sortOrders.prepend(order);
@ -73,7 +73,7 @@ void MessagesModelSqlLayer::addSortState(int column, Qt::SortOrder order) {
qDebug("Added sort state, select statement is now:\n'%s'", qPrintable(selectStatement())); qDebug("Added sort state, select statement is now:\n'%s'", qPrintable(selectStatement()));
} }
void MessagesModelSqlLayer::setFilter(const QString &filter) { void MessagesModelSqlLayer::setFilter(const QString& filter) {
m_filter = filter; m_filter = filter;
} }
@ -91,12 +91,12 @@ QString MessagesModelSqlLayer::orderByClause() const {
if (m_sortColumns.isEmpty()) { if (m_sortColumns.isEmpty()) {
return QString(); return QString();
} }
else { else {
QStringList sorts; QStringList sorts;
for (int i = 0; i < m_sortColumns.size(); i++) { for (int i = 0; i < m_sortColumns.size(); i++) {
QString field_name(m_fieldNames[m_sortColumns[i]]); QString field_name(m_fieldNames[m_sortColumns[i]]);
sorts.append(field_name + (m_sortOrders[i] == Qt::AscendingOrder ? QSL(" ASC") : QSL(" DESC"))); sorts.append(field_name + (m_sortOrders[i] == Qt::AscendingOrder ? QSL(" ASC") : QSL(" DESC")));
} }

View File

@ -33,7 +33,7 @@ class MessagesModelSqlLayer {
void addSortState(int column, Qt::SortOrder order); void addSortState(int column, Qt::SortOrder order);
// Sets SQL WHERE clause, without "WHERE" keyword. // Sets SQL WHERE clause, without "WHERE" keyword.
void setFilter(const QString &filter); void setFilter(const QString& filter);
protected: protected:
QString orderByClause() const; QString orderByClause() const;
@ -48,7 +48,7 @@ class MessagesModelSqlLayer {
// NOTE: These two lists contain data for multicolumn sorting. // NOTE: These two lists contain data for multicolumn sorting.
// They are always same length. Most important sort column/order // They are always same length. Most important sort column/order
// are located at the start of lists; // are located at the start of lists;
QMap<int,QString> m_fieldNames; QMap<int, QString> m_fieldNames;
QList<int> m_sortColumns; QList<int> m_sortColumns;
QList<Qt::SortOrder> m_sortOrders; QList<Qt::SortOrder> m_sortOrders;
}; };

View File

@ -20,9 +20,8 @@
#include "core/messagesmodel.h" #include "core/messagesmodel.h"
MessagesProxyModel::MessagesProxyModel(MessagesModel *source_model, QObject *parent) MessagesProxyModel::MessagesProxyModel(MessagesModel* source_model, QObject* parent)
: QSortFilterProxyModel(parent), m_sourceModel(source_model) { : QSortFilterProxyModel(parent), m_sourceModel(source_model) {
setObjectName(QSL("MessagesProxyModel")); setObjectName(QSL("MessagesProxyModel"));
setSortRole(Qt::EditRole); setSortRole(Qt::EditRole);
setSortCaseSensitivity(Qt::CaseInsensitive); setSortCaseSensitivity(Qt::CaseInsensitive);
@ -60,6 +59,7 @@ QModelIndex MessagesProxyModel::getNextUnreadItemIndex(int default_row, int max_
// We found unread message, mark it. // We found unread message, mark it.
return proxy_index; return proxy_index;
} }
else { else {
default_row++; default_row++;
} }
@ -68,22 +68,22 @@ QModelIndex MessagesProxyModel::getNextUnreadItemIndex(int default_row, int max_
return QModelIndex(); return QModelIndex();
} }
bool MessagesProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { bool MessagesProxyModel::lessThan(const QModelIndex& left, const QModelIndex& right) const {
Q_UNUSED(left) Q_UNUSED(left)
Q_UNUSED(right) Q_UNUSED(right)
// NOTE: Comparisons are done by SQL servers itself, not client-side. // NOTE: Comparisons are done by SQL servers itself, not client-side.
return false; return false;
} }
QModelIndexList MessagesProxyModel::mapListFromSource(const QModelIndexList &indexes, bool deep) const { QModelIndexList MessagesProxyModel::mapListFromSource(const QModelIndexList& indexes, bool deep) const {
QModelIndexList mapped_indexes; QModelIndexList mapped_indexes;
foreach (const QModelIndex &index, indexes) { foreach (const QModelIndex& index, indexes) {
if (deep) { if (deep) {
// Construct new source index. // Construct new source index.
mapped_indexes << mapFromSource(m_sourceModel->index(index.row(), index.column())); mapped_indexes << mapFromSource(m_sourceModel->index(index.row(), index.column()));
} }
else { else {
mapped_indexes << mapFromSource(index); mapped_indexes << mapFromSource(index);
} }
@ -92,8 +92,8 @@ QModelIndexList MessagesProxyModel::mapListFromSource(const QModelIndexList &ind
return mapped_indexes; return mapped_indexes;
} }
QModelIndexList MessagesProxyModel::match(const QModelIndex &start, int role, QModelIndexList MessagesProxyModel::match(const QModelIndex& start, int role,
const QVariant &entered_value, int hits, Qt::MatchFlags flags) const { const QVariant& entered_value, int hits, Qt::MatchFlags flags) const {
QModelIndexList result; QModelIndexList result;
const uint match_type = flags & 0x0F; const uint match_type = flags & 0x0F;
const Qt::CaseSensitivity case_sensitivity = Qt::CaseInsensitive; const Qt::CaseSensitivity case_sensitivity = Qt::CaseInsensitive;
@ -119,6 +119,7 @@ QModelIndexList MessagesProxyModel::match(const QModelIndex &start, int role,
result.append(idx); result.append(idx);
} }
} }
// QString based matching. // QString based matching.
else { else {
if (entered_text.isEmpty()) { if (entered_text.isEmpty()) {
@ -132,30 +133,35 @@ QModelIndexList MessagesProxyModel::match(const QModelIndex &start, int role,
if (QRegExp(entered_text, case_sensitivity).exactMatch(item_text)) { if (QRegExp(entered_text, case_sensitivity).exactMatch(item_text)) {
result.append(idx); result.append(idx);
} }
break; break;
case Qt::MatchWildcard: case Qt::MatchWildcard:
if (QRegExp(entered_text, case_sensitivity, QRegExp::Wildcard).exactMatch(item_text)) { if (QRegExp(entered_text, case_sensitivity, QRegExp::Wildcard).exactMatch(item_text)) {
result.append(idx); result.append(idx);
} }
break; break;
case Qt::MatchStartsWith: case Qt::MatchStartsWith:
if (item_text.startsWith(entered_text, case_sensitivity)) { if (item_text.startsWith(entered_text, case_sensitivity)) {
result.append(idx); result.append(idx);
} }
break; break;
case Qt::MatchEndsWith: case Qt::MatchEndsWith:
if (item_text.endsWith(entered_text, case_sensitivity)) { if (item_text.endsWith(entered_text, case_sensitivity)) {
result.append(idx); result.append(idx);
} }
break; break;
case Qt::MatchFixedString: case Qt::MatchFixedString:
if (item_text.compare(entered_text, case_sensitivity) == 0) { if (item_text.compare(entered_text, case_sensitivity) == 0) {
result.append(idx); result.append(idx);
} }
break; break;
case Qt::MatchContains: case Qt::MatchContains:
@ -163,6 +169,7 @@ QModelIndexList MessagesProxyModel::match(const QModelIndex &start, int role,
if (item_text.contains(entered_text, case_sensitivity)) { if (item_text.contains(entered_text, case_sensitivity)) {
result.append(idx); result.append(idx);
} }
break; break;
} }
} }
@ -182,10 +189,10 @@ void MessagesProxyModel::sort(int column, Qt::SortOrder order) {
Q_UNUSED(order) Q_UNUSED(order)
} }
QModelIndexList MessagesProxyModel::mapListToSource(const QModelIndexList &indexes) const { QModelIndexList MessagesProxyModel::mapListToSource(const QModelIndexList& indexes) const {
QModelIndexList source_indexes; QModelIndexList source_indexes;
foreach (const QModelIndex &index, indexes) { foreach (const QModelIndex& index, indexes) {
source_indexes << mapToSource(index); source_indexes << mapToSource(index);
} }

View File

@ -28,17 +28,17 @@ class MessagesProxyModel : public QSortFilterProxyModel {
public: public:
// Constructors and destructors. // Constructors and destructors.
explicit MessagesProxyModel(MessagesModel *source_model, QObject *parent = 0); explicit MessagesProxyModel(MessagesModel* source_model, QObject* parent = 0);
virtual ~MessagesProxyModel(); virtual ~MessagesProxyModel();
QModelIndex getNextPreviousUnreadItemIndex(int default_row); QModelIndex getNextPreviousUnreadItemIndex(int default_row);
// Maps list of indexes. // Maps list of indexes.
QModelIndexList mapListToSource(const QModelIndexList &indexes) const; QModelIndexList mapListToSource(const QModelIndexList& indexes) const;
QModelIndexList mapListFromSource(const QModelIndexList &indexes, bool deep = false) const; QModelIndexList mapListFromSource(const QModelIndexList& indexes, bool deep = false) const;
// Fix for matching indexes with respect to specifics of the message model. // Fix for matching indexes with respect to specifics of the message model.
QModelIndexList match(const QModelIndex &start, int role, const QVariant &entered_value, int hits, Qt::MatchFlags flags) const; QModelIndexList match(const QModelIndex& start, int role, const QVariant& entered_value, int hits, Qt::MatchFlags flags) const;
// Performs sort of items. // Performs sort of items.
void sort(int column, Qt::SortOrder order = Qt::AscendingOrder); void sort(int column, Qt::SortOrder order = Qt::AscendingOrder);
@ -47,10 +47,10 @@ class MessagesProxyModel : public QSortFilterProxyModel {
QModelIndex getNextUnreadItemIndex(int default_row, int max_row) const; QModelIndex getNextUnreadItemIndex(int default_row, int max_row) const;
// Compares two rows of data. // Compares two rows of data.
bool lessThan(const QModelIndex &left, const QModelIndex &right) const; bool lessThan(const QModelIndex& left, const QModelIndex& right) const;
// Source model pointer. // Source model pointer.
MessagesModel *m_sourceModel; MessagesModel* m_sourceModel;
}; };
#endif // MESSAGESPROXYMODEL_H #endif // MESSAGESPROXYMODEL_H

View File

@ -27,18 +27,18 @@
DynamicShortcuts::DynamicShortcuts() { DynamicShortcuts::DynamicShortcuts() {
} }
void DynamicShortcuts::save(const QList<QAction*> &actions) { void DynamicShortcuts::save(const QList<QAction*>& actions) {
Settings *settings = qApp->settings(); Settings* settings = qApp->settings();
foreach (const QAction *action, actions) { foreach (const QAction* action, actions) {
settings->setValue(GROUP(Keyboard), action->objectName(), action->shortcut().toString(QKeySequence::PortableText)); settings->setValue(GROUP(Keyboard), action->objectName(), action->shortcut().toString(QKeySequence::PortableText));
} }
} }
void DynamicShortcuts::load(const QList<QAction *> &actions) { void DynamicShortcuts::load(const QList<QAction*>& actions) {
Settings *settings = qApp->settings(); Settings* settings = qApp->settings();
foreach (QAction *action, actions) { foreach (QAction* action, actions) {
QString shortcut_for_action = settings->value(GROUP(Keyboard), QString shortcut_for_action = settings->value(GROUP(Keyboard),
action->objectName(), action->objectName(),
action->shortcut().toString(QKeySequence::PortableText)).toString(); action->shortcut().toString(QKeySequence::PortableText)).toString();

View File

@ -27,11 +27,11 @@ class DynamicShortcuts {
public: public:
// Checks the application settings and then initializes shortcut of // Checks the application settings and then initializes shortcut of
// each action from actions from the settings. // each action from actions from the settings.
static void load(const QList<QAction*> &actions); static void load(const QList<QAction*>& actions);
// Stores shortcut of each action from actions into the application // Stores shortcut of each action from actions into the application
// settings. // settings.
static void save(const QList<QAction*> &actions); static void save(const QList<QAction*>& actions);
private: private:
// Constructor. // Constructor.

View File

@ -26,11 +26,10 @@
#include <QLabel> #include <QLabel>
DynamicShortcutsWidget::DynamicShortcutsWidget(QWidget *parent) : QWidget(parent) { DynamicShortcutsWidget::DynamicShortcutsWidget(QWidget* parent) : QWidget(parent) {
// Create layout for this control and set is as active. // Create layout for this control and set is as active.
m_layout = new QGridLayout(this); m_layout = new QGridLayout(this);
m_layout->setMargin(0); m_layout->setMargin(0);
setLayout(m_layout); setLayout(m_layout);
} }
@ -42,13 +41,14 @@ bool DynamicShortcutsWidget::areShortcutsUnique() const {
QList<QKeySequence> all_shortcuts; QList<QKeySequence> all_shortcuts;
// Obtain all shortcuts. // Obtain all shortcuts.
foreach (const ActionBinding &binding, m_actionBindings) { foreach (const ActionBinding& binding, m_actionBindings) {
const QKeySequence new_shortcut = binding.second->shortcut(); const QKeySequence new_shortcut = binding.second->shortcut();
if (!new_shortcut.isEmpty() && all_shortcuts.contains(new_shortcut)) { if (!new_shortcut.isEmpty() && all_shortcuts.contains(new_shortcut)) {
// Problem, two identical non-empty shortcuts found. // Problem, two identical non-empty shortcuts found.
return false; return false;
} }
else { else {
all_shortcuts.append(binding.second->shortcut()); all_shortcuts.append(binding.second->shortcut());
} }
@ -58,7 +58,7 @@ bool DynamicShortcutsWidget::areShortcutsUnique() const {
} }
void DynamicShortcutsWidget::updateShortcuts() { void DynamicShortcutsWidget::updateShortcuts() {
foreach (const ActionBinding &binding, m_actionBindings) { foreach (const ActionBinding& binding, m_actionBindings) {
binding.first->setShortcut(binding.second->shortcut()); binding.first->setShortcut(binding.second->shortcut());
} }
} }
@ -66,7 +66,6 @@ void DynamicShortcutsWidget::updateShortcuts() {
void DynamicShortcutsWidget::populate(QList<QAction*> actions) { void DynamicShortcutsWidget::populate(QList<QAction*> actions) {
m_actionBindings.clear(); m_actionBindings.clear();
qSort(actions.begin(), actions.end(), DynamicShortcutsWidget::lessThan); qSort(actions.begin(), actions.end(), DynamicShortcutsWidget::lessThan);
int row_id = 0; int row_id = 0;
// FIXME: Maybe separate actions into "categories". Each category will start with label. // FIXME: Maybe separate actions into "categories". Each category will start with label.
@ -76,35 +75,28 @@ void DynamicShortcutsWidget::populate(QList<QAction*> actions) {
// This will be setup in FormMain::allActions(). // This will be setup in FormMain::allActions().
// Then here I will process actions into categories. // Then here I will process actions into categories.
foreach (QAction *action, actions) { foreach (QAction* action, actions) {
// Create shortcut catcher for this action and set default shortcut. // Create shortcut catcher for this action and set default shortcut.
ShortcutCatcher *catcher = new ShortcutCatcher(this); ShortcutCatcher* catcher = new ShortcutCatcher(this);
catcher->setDefaultShortcut(action->shortcut()); catcher->setDefaultShortcut(action->shortcut());
// Store information for re-initialization of shortcuts // Store information for re-initialization of shortcuts
// of actions when widget gets "confirmed". // of actions when widget gets "confirmed".
QPair<QAction*,ShortcutCatcher*> new_binding; QPair<QAction*, ShortcutCatcher*> new_binding;
new_binding.first = action; new_binding.first = action;
new_binding.second = catcher; new_binding.second = catcher;
m_actionBindings << new_binding; m_actionBindings << new_binding;
// Add new catcher to our control. // Add new catcher to our control.
QLabel *action_label = new QLabel(this); QLabel* action_label = new QLabel(this);
action_label->setText(action->text().remove(QSL("&"))); action_label->setText(action->text().remove(QSL("&")));
action_label->setToolTip(action->toolTip()); action_label->setToolTip(action->toolTip());
action_label->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Preferred); action_label->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Preferred);
QLabel* action_icon = new QLabel(this);
QLabel *action_icon = new QLabel(this);
action_icon->setPixmap(action->icon().pixmap(ICON_SIZE_SETTINGS, ICON_SIZE_SETTINGS)); action_icon->setPixmap(action->icon().pixmap(ICON_SIZE_SETTINGS, ICON_SIZE_SETTINGS));
action_icon->setToolTip(action->toolTip()); action_icon->setToolTip(action->toolTip());
m_layout->addWidget(action_icon, row_id, 0); m_layout->addWidget(action_icon, row_id, 0);
m_layout->addWidget(action_label, row_id, 1); m_layout->addWidget(action_label, row_id, 1);
m_layout->addWidget(catcher, row_id, 2); m_layout->addWidget(catcher, row_id, 2);
row_id++; row_id++;
connect(catcher, &ShortcutCatcher::shortcutChanged, this, &DynamicShortcutsWidget::setupChanged); connect(catcher, &ShortcutCatcher::shortcutChanged, this, &DynamicShortcutsWidget::setupChanged);
} }
@ -113,6 +105,6 @@ void DynamicShortcutsWidget::populate(QList<QAction*> actions) {
m_layout->setColumnStretch(1, 1); m_layout->setColumnStretch(1, 1);
} }
bool DynamicShortcutsWidget::lessThan(QAction *lhs, QAction *rhs) { bool DynamicShortcutsWidget::lessThan(QAction* lhs, QAction* rhs) {
return QString::localeAwareCompare(lhs->text().replace(QL1S("&"), QString()), rhs->text().replace(QL1S("&"), QString())) < 0; return QString::localeAwareCompare(lhs->text().replace(QL1S("&"), QString()), rhs->text().replace(QL1S("&"), QString())) < 0;
} }

View File

@ -31,7 +31,7 @@ class DynamicShortcutsWidget : public QWidget {
public: public:
// Constructors and destructors. // Constructors and destructors.
explicit DynamicShortcutsWidget(QWidget *parent = 0); explicit DynamicShortcutsWidget(QWidget* parent = 0);
virtual ~DynamicShortcutsWidget(); virtual ~DynamicShortcutsWidget();
// Updates shortcuts of all actions according to changes. // Updates shortcuts of all actions according to changes.
@ -54,10 +54,10 @@ class DynamicShortcutsWidget : public QWidget {
void setupChanged(); void setupChanged();
private: private:
static bool lessThan(QAction *lhs, QAction *rhs); static bool lessThan(QAction* lhs, QAction* rhs);
private: private:
QGridLayout *m_layout; QGridLayout* m_layout;
QList<ActionBinding> m_actionBindings; QList<ActionBinding> m_actionBindings;
}; };

View File

@ -50,7 +50,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <QKeyEvent> #include <QKeyEvent>
ShortcutButton::ShortcutButton(ShortcutCatcher *catcher, QWidget *parent) ShortcutButton::ShortcutButton(ShortcutCatcher* catcher, QWidget* parent)
: QPushButton(parent), m_catcher(catcher) { : QPushButton(parent), m_catcher(catcher) {
setMinimumWidth(100); setMinimumWidth(100);
} }
@ -58,7 +58,7 @@ ShortcutButton::ShortcutButton(ShortcutCatcher *catcher, QWidget *parent)
ShortcutButton::~ShortcutButton() { ShortcutButton::~ShortcutButton() {
} }
void ShortcutButton::keyPressEvent(QKeyEvent *event) { void ShortcutButton::keyPressEvent(QKeyEvent* event) {
int pressed_key = event->key(); int pressed_key = event->key();
if (pressed_key == -1) { if (pressed_key == -1) {
@ -79,7 +79,7 @@ void ShortcutButton::keyPressEvent(QKeyEvent *event) {
event->accept(); event->accept();
m_catcher->m_modifierKeys = new_modifiers; m_catcher->m_modifierKeys = new_modifiers;
switch(pressed_key) { switch (pressed_key) {
case Qt::Key_AltGr: case Qt::Key_AltGr:
return; return;
@ -93,11 +93,13 @@ void ShortcutButton::keyPressEvent(QKeyEvent *event) {
break; break;
default: default:
// We now have a valid key press. // We now have a valid key press.
if (pressed_key) { if (pressed_key) {
if ((pressed_key == Qt::Key_Backtab) && (m_catcher->m_modifierKeys & Qt::SHIFT)) { if ((pressed_key == Qt::Key_Backtab) && (m_catcher->m_modifierKeys & Qt::SHIFT)) {
pressed_key = Qt::Key_Tab | m_catcher->m_modifierKeys; pressed_key = Qt::Key_Tab | m_catcher->m_modifierKeys;
} }
else { else {
pressed_key |= m_catcher->m_modifierKeys; pressed_key |= m_catcher->m_modifierKeys;
} }
@ -119,8 +121,8 @@ void ShortcutButton::keyPressEvent(QKeyEvent *event) {
} }
} }
void ShortcutButton::keyReleaseEvent(QKeyEvent *event) { void ShortcutButton::keyReleaseEvent(QKeyEvent* event) {
if (event->key() == -1){ if (event->key() == -1) {
return; return;
} }
@ -130,7 +132,6 @@ void ShortcutButton::keyReleaseEvent(QKeyEvent *event) {
} }
event->accept(); event->accept();
const Qt::KeyboardModifiers new_modifiers = event->modifiers() & const Qt::KeyboardModifiers new_modifiers = event->modifiers() &
(Qt::SHIFT | Qt::CTRL | Qt::ALT | Qt::META); (Qt::SHIFT | Qt::CTRL | Qt::ALT | Qt::META);

View File

@ -56,15 +56,15 @@ class ShortcutButton : public QPushButton {
public: public:
// Constructors and destructors. // Constructors and destructors.
explicit ShortcutButton(ShortcutCatcher *catcher, QWidget *parent = 0); explicit ShortcutButton(ShortcutCatcher* catcher, QWidget* parent = 0);
virtual ~ShortcutButton(); virtual ~ShortcutButton();
protected: protected:
void keyPressEvent(QKeyEvent *event); void keyPressEvent(QKeyEvent* event);
void keyReleaseEvent(QKeyEvent *event); void keyReleaseEvent(QKeyEvent* event);
private: private:
ShortcutCatcher *m_catcher; ShortcutCatcher* m_catcher;
}; };
#endif // SHORTCUTBUTTON_H #endif // SHORTCUTBUTTON_H

View File

@ -52,40 +52,34 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <QHBoxLayout> #include <QHBoxLayout>
ShortcutCatcher::ShortcutCatcher(QWidget *parent) ShortcutCatcher::ShortcutCatcher(QWidget* parent)
: QWidget(parent) { : QWidget(parent) {
// Setup layout of the control // Setup layout of the control
m_layout = new QHBoxLayout(this); m_layout = new QHBoxLayout(this);
m_layout->setMargin(0); m_layout->setMargin(0);
m_layout->setSpacing(1); m_layout->setSpacing(1);
// Create reset button. // Create reset button.
m_btnReset = new PlainToolButton(this); m_btnReset = new PlainToolButton(this);
m_btnReset->setIcon(qApp->icons()->fromTheme(QSL("document-revert"))); m_btnReset->setIcon(qApp->icons()->fromTheme(QSL("document-revert")));
m_btnReset->setFocusPolicy(Qt::NoFocus); m_btnReset->setFocusPolicy(Qt::NoFocus);
m_btnReset->setToolTip(tr("Reset to original shortcut.")); m_btnReset->setToolTip(tr("Reset to original shortcut."));
// Create clear button. // Create clear button.
m_btnClear = new PlainToolButton(this); m_btnClear = new PlainToolButton(this);
m_btnClear->setIcon(qApp->icons()->fromTheme(QSL("list-remove"))); m_btnClear->setIcon(qApp->icons()->fromTheme(QSL("list-remove")));
m_btnClear->setFocusPolicy(Qt::NoFocus); m_btnClear->setFocusPolicy(Qt::NoFocus);
m_btnClear->setToolTip(tr("Clear current shortcut.")); m_btnClear->setToolTip(tr("Clear current shortcut."));
// Clear main shortcut catching button. // Clear main shortcut catching button.
m_btnChange = new ShortcutButton(this); m_btnChange = new ShortcutButton(this);
m_btnChange->setFocusPolicy(Qt::StrongFocus); m_btnChange->setFocusPolicy(Qt::StrongFocus);
m_btnChange->setToolTip(tr("Click and hit new shortcut.")); m_btnChange->setToolTip(tr("Click and hit new shortcut."));
// Add both buttons to the layout. // Add both buttons to the layout.
m_layout->addWidget(m_btnChange); m_layout->addWidget(m_btnChange);
m_layout->addWidget(m_btnReset); m_layout->addWidget(m_btnReset);
m_layout->addWidget(m_btnClear); m_layout->addWidget(m_btnClear);
// Establish needed connections. // Establish needed connections.
connect(m_btnReset, &QToolButton::clicked, this, &ShortcutCatcher::resetShortcut); connect(m_btnReset, &QToolButton::clicked, this, &ShortcutCatcher::resetShortcut);
connect(m_btnClear, &QToolButton::clicked, this, &ShortcutCatcher::clearShortcut); connect(m_btnClear, &QToolButton::clicked, this, &ShortcutCatcher::clearShortcut);
connect(m_btnChange, &QToolButton::clicked, this, &ShortcutCatcher::startRecording); connect(m_btnChange, &QToolButton::clicked, this, &ShortcutCatcher::startRecording);
// Prepare initial state of the control. // Prepare initial state of the control.
updateDisplayShortcut(); updateDisplayShortcut();
} }
@ -104,7 +98,6 @@ void ShortcutCatcher::startRecording() {
m_isRecording = true; m_isRecording = true;
m_btnChange->setDown(true); m_btnChange->setDown(true);
m_btnChange->grabKeyboard(); m_btnChange->grabKeyboard();
updateDisplayShortcut(); updateDisplayShortcut();
} }
@ -112,9 +105,7 @@ void ShortcutCatcher::doneRecording() {
m_isRecording = false; m_isRecording = false;
m_btnChange->releaseKeyboard(); m_btnChange->releaseKeyboard();
m_btnChange->setDown(false); m_btnChange->setDown(false);
updateDisplayShortcut(); updateDisplayShortcut();
emit shortcutChanged(m_currentSequence); emit shortcutChanged(m_currentSequence);
} }
@ -133,15 +124,19 @@ void ShortcutCatcher::updateDisplayShortcut() {
if (!str.isEmpty()) { if (!str.isEmpty()) {
str.append(QSL(",")); str.append(QSL(","));
} }
if (m_modifierKeys & Qt::META) { if (m_modifierKeys & Qt::META) {
str += QL1S("Meta + "); str += QL1S("Meta + ");
} }
if (m_modifierKeys & Qt::CTRL) { if (m_modifierKeys & Qt::CTRL) {
str += QL1S("Ctrl + "); str += QL1S("Ctrl + ");
} }
if (m_modifierKeys & Qt::ALT) { if (m_modifierKeys & Qt::ALT) {
str += QL1S("Alt + "); str += QL1S("Alt + ");
} }
if (m_modifierKeys & Qt::SHIFT) { if (m_modifierKeys & Qt::SHIFT) {
str += QL1S("Shift + "); str += QL1S("Shift + ");
} }
@ -155,12 +150,12 @@ QKeySequence ShortcutCatcher::shortcut() const {
return m_currentSequence; return m_currentSequence;
} }
void ShortcutCatcher::setDefaultShortcut(const QKeySequence &key) { void ShortcutCatcher::setDefaultShortcut(const QKeySequence& key) {
m_defaultSequence = key; m_defaultSequence = key;
setShortcut(key); setShortcut(key);
} }
void ShortcutCatcher::setShortcut(const QKeySequence &key) { void ShortcutCatcher::setShortcut(const QKeySequence& key) {
m_currentSequence = key; m_currentSequence = key;
doneRecording(); doneRecording();
} }

View File

@ -60,15 +60,15 @@ class ShortcutCatcher : public QWidget {
public: public:
// Constructors and destructors. // Constructors and destructors.
explicit ShortcutCatcher(QWidget *parent = 0); explicit ShortcutCatcher(QWidget* parent = 0);
virtual ~ShortcutCatcher(); virtual ~ShortcutCatcher();
void controlModifierlessTimout(); void controlModifierlessTimout();
void updateDisplayShortcut(); void updateDisplayShortcut();
QKeySequence shortcut() const; QKeySequence shortcut() const;
void setDefaultShortcut(const QKeySequence &key); void setDefaultShortcut(const QKeySequence& key);
void setShortcut(const QKeySequence &key); void setShortcut(const QKeySequence& key);
public slots: public slots:
void resetShortcut(); void resetShortcut();
@ -79,13 +79,13 @@ class ShortcutCatcher : public QWidget {
void doneRecording(); void doneRecording();
signals: signals:
void shortcutChanged(const QKeySequence &seguence); void shortcutChanged(const QKeySequence& seguence);
private: private:
QToolButton *m_btnReset; QToolButton* m_btnReset;
QToolButton *m_btnClear; QToolButton* m_btnClear;
ShortcutButton *m_btnChange; ShortcutButton* m_btnChange;
QHBoxLayout *m_layout; QHBoxLayout* m_layout;
QKeySequence m_currentSequence; QKeySequence m_currentSequence;
QKeySequence m_defaultSequence; QKeySequence m_defaultSequence;

View File

@ -18,7 +18,7 @@
#include "exceptions/applicationexception.h" #include "exceptions/applicationexception.h"
ApplicationException::ApplicationException(const QString &message) : m_message(message) { ApplicationException::ApplicationException(const QString& message) : m_message(message) {
} }
ApplicationException::~ApplicationException() { ApplicationException::~ApplicationException() {

View File

@ -23,7 +23,7 @@
class ApplicationException { class ApplicationException {
public: public:
explicit ApplicationException(const QString &message = QString()); explicit ApplicationException(const QString& message = QString());
virtual ~ApplicationException(); virtual ~ApplicationException();
QString message() const; QString message() const;

View File

@ -18,7 +18,7 @@
#include "exceptions/ioexception.h" #include "exceptions/ioexception.h"
IOException::IOException(const QString &message) : ApplicationException(message) { IOException::IOException(const QString& message) : ApplicationException(message) {
} }
IOException::~IOException() { IOException::~IOException() {

View File

@ -23,7 +23,7 @@
class IOException : public ApplicationException { class IOException : public ApplicationException {
public: public:
explicit IOException(const QString &message = QString()); explicit IOException(const QString& message = QString());
virtual ~IOException(); virtual ~IOException();
}; };

View File

@ -20,18 +20,18 @@
#include <QKeyEvent> #include <QKeyEvent>
BaseLineEdit::BaseLineEdit(QWidget *parent) : QLineEdit(parent) { BaseLineEdit::BaseLineEdit(QWidget* parent) : QLineEdit(parent) {
} }
BaseLineEdit::~BaseLineEdit() { BaseLineEdit::~BaseLineEdit() {
} }
void BaseLineEdit::submit(const QString &text) { void BaseLineEdit::submit(const QString& text) {
setText(text); setText(text);
emit submitted(text); emit submitted(text);
} }
void BaseLineEdit::keyPressEvent(QKeyEvent *event) { void BaseLineEdit::keyPressEvent(QKeyEvent* event) {
if (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return) { if (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return) {
emit submitted(text()); emit submitted(text());
event->accept(); event->accept();

View File

@ -26,18 +26,18 @@ class BaseLineEdit : public QLineEdit {
public: public:
// Constructors and destructors. // Constructors and destructors.
explicit BaseLineEdit(QWidget *parent = 0); explicit BaseLineEdit(QWidget* parent = 0);
virtual ~BaseLineEdit(); virtual ~BaseLineEdit();
public slots: public slots:
void submit(const QString &text); void submit(const QString& text);
protected: protected:
void keyPressEvent(QKeyEvent *event); void keyPressEvent(QKeyEvent* event);
signals: signals:
// Emitted if user hits ENTER button. // Emitted if user hits ENTER button.
void submitted(const QString &text); void submitted(const QString& text);
}; };
#endif // BASELINEEDIT_H #endif // BASELINEEDIT_H

View File

@ -24,7 +24,7 @@
#include <QWidgetAction> #include <QWidgetAction>
BaseToolBar::BaseToolBar(const QString &title, QWidget *parent) : QToolBar(title, parent) { BaseToolBar::BaseToolBar(const QString& title, QWidget* parent) : QToolBar(title, parent) {
// Update right margin of filter textbox. // Update right margin of filter textbox.
QMargins margins = contentsMargins(); QMargins margins = contentsMargins();
margins.setRight(margins.right() + FILTER_RIGHT_MARGIN); margins.setRight(margins.right() + FILTER_RIGHT_MARGIN);
@ -39,8 +39,8 @@ void BaseBar::loadSavedActions() {
loadSpecificActions(getSpecificActions(savedActions())); loadSpecificActions(getSpecificActions(savedActions()));
} }
QAction *BaseBar::findMatchingAction(const QString &action, const QList<QAction*> &actions) const { QAction* BaseBar::findMatchingAction(const QString& action, const QList<QAction*>& actions) const {
foreach (QAction *act, actions) { foreach (QAction* act, actions) {
if (act->objectName() == action) { if (act->objectName() == action) {
return act; return act;
} }

View File

@ -32,7 +32,7 @@ class BaseBar {
// Sets new "actions" to the toolbar and perhaps saves the toolbar // Sets new "actions" to the toolbar and perhaps saves the toolbar
// state into the settings. // state into the settings.
virtual void saveChangeableActions(const QStringList &actions) = 0; virtual void saveChangeableActions(const QStringList& actions) = 0;
// Returns list of default actions. // Returns list of default actions.
virtual QStringList defaultActions() const = 0; virtual QStringList defaultActions() const = 0;
@ -41,11 +41,11 @@ class BaseBar {
// Loads the toolbar state from settings. // Loads the toolbar state from settings.
virtual void loadSavedActions(); virtual void loadSavedActions();
virtual QList<QAction*> getSpecificActions(const QStringList &actions) = 0; virtual QList<QAction*> getSpecificActions(const QStringList& actions) = 0;
virtual void loadSpecificActions(const QList<QAction*> &actions) = 0; virtual void loadSpecificActions(const QList<QAction*>& actions) = 0;
protected: protected:
QAction *findMatchingAction(const QString &action, const QList<QAction *> &actions) const; QAction* findMatchingAction(const QString& action, const QList<QAction*>& actions) const;
}; };
class BaseToolBar : public QToolBar, public BaseBar { class BaseToolBar : public QToolBar, public BaseBar {
@ -53,7 +53,7 @@ class BaseToolBar : public QToolBar, public BaseBar {
public: public:
// Constructors and destructors. // Constructors and destructors.
explicit BaseToolBar(const QString &title, QWidget *parent = 0); explicit BaseToolBar(const QString& title, QWidget* parent = 0);
virtual ~BaseToolBar(); virtual ~BaseToolBar();
}; };

View File

@ -32,7 +32,7 @@ QString ClickableLabel::themeIcon() const {
return m_themeIcon; return m_themeIcon;
} }
void ClickableLabel::setThemeIcon(const QString &name) { void ClickableLabel::setThemeIcon(const QString& name) {
m_themeIcon = name; m_themeIcon = name;
updateIcon(); updateIcon();
} }
@ -41,14 +41,13 @@ QIcon ClickableLabel::fallbackIcon() const {
return m_fallbackIcon; return m_fallbackIcon;
} }
void ClickableLabel::setFallbackIcon(const QIcon &fallbackIcon) { void ClickableLabel::setFallbackIcon(const QIcon& fallbackIcon) {
m_fallbackIcon = fallbackIcon; m_fallbackIcon = fallbackIcon;
updateIcon(); updateIcon();
} }
void ClickableLabel::updateIcon() { void ClickableLabel::updateIcon() {
if (!m_themeIcon.isEmpty()) { if (!m_themeIcon.isEmpty()) {
const QIcon icon = qApp->icons()->fromTheme(m_themeIcon); const QIcon icon = qApp->icons()->fromTheme(m_themeIcon);
if (!icon.isNull()) { if (!icon.isNull()) {
@ -62,7 +61,7 @@ void ClickableLabel::updateIcon() {
} }
} }
void ClickableLabel::resizeEvent(QResizeEvent *ev) { void ClickableLabel::resizeEvent(QResizeEvent* ev) {
QLabel::resizeEvent(ev); QLabel::resizeEvent(ev);
updateIcon(); updateIcon();
} }
@ -72,13 +71,16 @@ void ClickableLabel::mouseReleaseEvent(QMouseEvent* ev) {
if (ev->modifiers() == Qt::ControlModifier) { if (ev->modifiers() == Qt::ControlModifier) {
emit middleClicked(ev->globalPos()); emit middleClicked(ev->globalPos());
} }
else { else {
emit clicked(ev->globalPos()); emit clicked(ev->globalPos());
} }
} }
else if (ev->button() == Qt::MiddleButton && rect().contains(ev->pos())) { else if (ev->button() == Qt::MiddleButton && rect().contains(ev->pos())) {
emit middleClicked(ev->globalPos()); emit middleClicked(ev->globalPos());
} }
else { else {
QLabel::mouseReleaseEvent(ev); QLabel::mouseReleaseEvent(ev);
} }

View File

@ -25,7 +25,7 @@
class QMouseEvent; class QMouseEvent;
class ClickableLabel : public QLabel{ class ClickableLabel : public QLabel {
Q_OBJECT Q_OBJECT
Q_PROPERTY(QSize fixedsize READ size WRITE setFixedSize) Q_PROPERTY(QSize fixedsize READ size WRITE setFixedSize)
Q_PROPERTY(int fixedwidth READ width WRITE setFixedWidth) Q_PROPERTY(int fixedwidth READ width WRITE setFixedWidth)
@ -34,13 +34,13 @@ class ClickableLabel : public QLabel{
Q_PROPERTY(QIcon fallbackIcon READ fallbackIcon WRITE setFallbackIcon) Q_PROPERTY(QIcon fallbackIcon READ fallbackIcon WRITE setFallbackIcon)
public: public:
explicit ClickableLabel(QWidget *parent = 0); explicit ClickableLabel(QWidget* parent = 0);
QString themeIcon() const; QString themeIcon() const;
void setThemeIcon(const QString &name); void setThemeIcon(const QString& name);
QIcon fallbackIcon() const; QIcon fallbackIcon() const;
void setFallbackIcon(const QIcon &fallbackIcon); void setFallbackIcon(const QIcon& fallbackIcon);
signals: signals:
void clicked(QPoint); void clicked(QPoint);
@ -49,7 +49,7 @@ class ClickableLabel : public QLabel{
private: private:
void updateIcon(); void updateIcon();
void resizeEvent(QResizeEvent *ev); void resizeEvent(QResizeEvent* ev);
void mouseReleaseEvent(QMouseEvent* ev); void mouseReleaseEvent(QMouseEvent* ev);
QString m_themeIcon; QString m_themeIcon;

View File

@ -21,7 +21,7 @@
#include <QPainter> #include <QPainter>
ColorLabel::ColorLabel(QWidget *parent) : QLabel(parent), m_color(QColor()) { ColorLabel::ColorLabel(QWidget* parent) : QLabel(parent), m_color(QColor()) {
setFixedWidth(20); setFixedWidth(20);
} }
@ -32,12 +32,11 @@ QColor ColorLabel::color() const {
return m_color; return m_color;
} }
void ColorLabel::setColor(const QColor &color) { void ColorLabel::setColor(const QColor& color) {
m_color = color; m_color = color;
repaint(); repaint();
} }
void ColorLabel::paintEvent(QPaintEvent *event) { void ColorLabel::paintEvent(QPaintEvent* event) {
QPainter(this).fillRect(event->rect(), m_color); QPainter(this).fillRect(event->rect(), m_color);
} }

View File

@ -25,14 +25,14 @@ class ColorLabel : public QLabel {
Q_OBJECT Q_OBJECT
public: public:
explicit ColorLabel(QWidget *parent = 0); explicit ColorLabel(QWidget* parent = 0);
virtual ~ColorLabel(); virtual ~ColorLabel();
QColor color() const; QColor color() const;
void setColor(const QColor &color); void setColor(const QColor& color);
protected: protected:
void paintEvent(QPaintEvent *event); void paintEvent(QPaintEvent* event);
private: private:
QColor m_color; QColor m_color;

View File

@ -22,14 +22,12 @@
#include <QHBoxLayout> #include <QHBoxLayout>
ComboBoxWithStatus::ComboBoxWithStatus(QWidget *parent) ComboBoxWithStatus::ComboBoxWithStatus(QWidget* parent)
: WidgetWithStatus(parent) { : WidgetWithStatus(parent) {
m_wdgInput = new QComboBox(this); m_wdgInput = new QComboBox(this);
// Set correct size for the tool button. // Set correct size for the tool button.
const int txt_input_height = m_wdgInput->sizeHint().height(); const int txt_input_height = m_wdgInput->sizeHint().height();
m_btnStatus->setFixedSize(txt_input_height, txt_input_height); m_btnStatus->setFixedSize(txt_input_height, txt_input_height);
// Compose the layout. // Compose the layout.
m_layout->addWidget(m_wdgInput); m_layout->addWidget(m_wdgInput);
m_layout->addWidget(m_btnStatus); m_layout->addWidget(m_btnStatus);

View File

@ -28,10 +28,10 @@ class ComboBoxWithStatus : public WidgetWithStatus {
public: public:
// Constructors and destructors. // Constructors and destructors.
explicit ComboBoxWithStatus(QWidget *parent = 0); explicit ComboBoxWithStatus(QWidget* parent = 0);
virtual ~ComboBoxWithStatus(); virtual ~ComboBoxWithStatus();
inline QComboBox *comboBox() const { inline QComboBox* comboBox() const {
return static_cast<QComboBox*>(m_wdgInput); return static_cast<QComboBox*>(m_wdgInput);
} }
}; };

View File

@ -25,21 +25,16 @@
#include <QTextStream> #include <QTextStream>
FormAbout::FormAbout(QWidget *parent) : QDialog(parent), m_ui(new Ui::FormAbout()) { FormAbout::FormAbout(QWidget* parent) : QDialog(parent), m_ui(new Ui::FormAbout()) {
m_ui->setupUi(this); m_ui->setupUi(this);
// Set flags and attributes. // Set flags and attributes.
setWindowFlags(Qt::MSWindowsFixedSizeDialogHint | Qt::Dialog | Qt::WindowSystemMenuHint); setWindowFlags(Qt::MSWindowsFixedSizeDialogHint | Qt::Dialog | Qt::WindowSystemMenuHint);
setWindowIcon(qApp->icons()->fromTheme(QSL("help-about"))); setWindowIcon(qApp->icons()->fromTheme(QSL("help-about")));
//: About RSS Guard dialog title. //: About RSS Guard dialog title.
setWindowTitle(tr("About %1").arg(APP_NAME)); setWindowTitle(tr("About %1").arg(APP_NAME));
m_ui->m_lblIcon->setPixmap(QPixmap(APP_ICON_PATH)); m_ui->m_lblIcon->setPixmap(QPixmap(APP_ICON_PATH));
// Load information from embedded text files. // Load information from embedded text files.
loadLicenseAndInformation(); loadLicenseAndInformation();
// Load additional paths information. // Load additional paths information.
loadSettingsAndPaths(); loadSettingsAndPaths();
} }
@ -52,6 +47,7 @@ void FormAbout::loadSettingsAndPaths() {
if (qApp->settings()->type() == SettingsProperties::Portable) { if (qApp->settings()->type() == SettingsProperties::Portable) {
m_ui->m_txtPathsSettingsType->setText(tr("FULLY portable")); m_ui->m_txtPathsSettingsType->setText(tr("FULLY portable"));
} }
else { else {
m_ui->m_txtPathsSettingsType->setText(tr("NOT portable")); m_ui->m_txtPathsSettingsType->setText(tr("NOT portable"));
} }
@ -65,34 +61,39 @@ void FormAbout::loadSettingsAndPaths() {
void FormAbout::loadLicenseAndInformation() { void FormAbout::loadLicenseAndInformation() {
QFile file; QFile file;
file.setFileName(APP_INFO_PATH + QL1S("/COPYING_GNU_GPL_HTML")); file.setFileName(APP_INFO_PATH + QL1S("/COPYING_GNU_GPL_HTML"));
if (file.open(QIODevice::ReadOnly | QIODevice::Text)) { if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
m_ui->m_txtLicenseGnu->setText(QString::fromUtf8(file.readAll())); m_ui->m_txtLicenseGnu->setText(QString::fromUtf8(file.readAll()));
} }
else { else {
m_ui->m_txtLicenseGnu->setText(tr("License not found.")); m_ui->m_txtLicenseGnu->setText(tr("License not found."));
} }
file.close();
file.close();
file.setFileName(APP_INFO_PATH + QL1S("/COPYING_BSD")); file.setFileName(APP_INFO_PATH + QL1S("/COPYING_BSD"));
if (file.open(QIODevice::ReadOnly | QIODevice::Text)) { if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
m_ui->m_txtLicenseBsd->setText(QString::fromUtf8(file.readAll())); m_ui->m_txtLicenseBsd->setText(QString::fromUtf8(file.readAll()));
} }
else { else {
m_ui->m_txtLicenseBsd->setText(tr("License not found.")); m_ui->m_txtLicenseBsd->setText(tr("License not found."));
} }
file.close();
file.close();
file.setFileName(APP_INFO_PATH + QL1S("/CHANGELOG")); file.setFileName(APP_INFO_PATH + QL1S("/CHANGELOG"));
if (file.open(QIODevice::ReadOnly | QIODevice::Text)) { if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
m_ui->m_txtChangelog->setText(QString::fromUtf8(file.readAll())); m_ui->m_txtChangelog->setText(QString::fromUtf8(file.readAll()));
} }
else { else {
m_ui->m_txtChangelog->setText(tr("Changelog not found.")); m_ui->m_txtChangelog->setText(tr("Changelog not found."));
} }
file.close();
file.close();
// Set other informative texts. // Set other informative texts.
m_ui->m_lblDesc->setText(tr("<b>%8</b><br>" m_ui->m_lblDesc->setText(tr("<b>%8</b><br>"
"<b>Version:</b> %1 (built on %2/%3)<br>" "<b>Version:</b> %1 (built on %2/%3)<br>"
@ -107,7 +108,6 @@ void FormAbout::loadLicenseAndInformation() {
qVersion(), qVersion(),
QT_VERSION_STR, QT_VERSION_STR,
APP_NAME)); APP_NAME));
m_ui->m_txtInfo->setText(tr("<body>%5 is a (very) tiny feed reader." m_ui->m_txtInfo->setText(tr("<body>%5 is a (very) tiny feed reader."
"<br><br>This software is distributed under the terms of GNU General Public License, version 3." "<br><br>This software is distributed under the terms of GNU General Public License, version 3."
"<br><br>Contacts:" "<br><br>Contacts:"

View File

@ -30,7 +30,7 @@ class FormAbout : public QDialog {
public: public:
// Constructors and destructors. // Constructors and destructors.
explicit FormAbout(QWidget *parent); explicit FormAbout(QWidget* parent);
virtual ~FormAbout(); virtual ~FormAbout();
private: private:

View File

@ -26,14 +26,12 @@
#include <QDialogButtonBox> #include <QDialogButtonBox>
FormAddAccount::FormAddAccount(const QList<ServiceEntryPoint*> &entry_points, FeedsModel *model, QWidget *parent) FormAddAccount::FormAddAccount(const QList<ServiceEntryPoint*>& entry_points, FeedsModel* model, QWidget* parent)
: QDialog(parent), m_ui(new Ui::FormAddAccount), m_model(model), m_entryPoints(entry_points) { : QDialog(parent), m_ui(new Ui::FormAddAccount), m_model(model), m_entryPoints(entry_points) {
m_ui->setupUi(this); m_ui->setupUi(this);
// Set flags and attributes. // Set flags and attributes.
setWindowFlags(Qt::MSWindowsFixedSizeDialogHint | Qt::Dialog | Qt::WindowSystemMenuHint); setWindowFlags(Qt::MSWindowsFixedSizeDialogHint | Qt::Dialog | Qt::WindowSystemMenuHint);
setWindowIcon(qApp->icons()->fromTheme(QSL("document-new"))); setWindowIcon(qApp->icons()->fromTheme(QSL("document-new")));
connect(m_ui->m_listEntryPoints, &QListWidget::itemDoubleClicked, this, &FormAddAccount::addSelectedAccount); connect(m_ui->m_listEntryPoints, &QListWidget::itemDoubleClicked, this, &FormAddAccount::addSelectedAccount);
connect(m_ui->m_buttonBox, &QDialogButtonBox::accepted, this, &FormAddAccount::addSelectedAccount); connect(m_ui->m_buttonBox, &QDialogButtonBox::accepted, this, &FormAddAccount::addSelectedAccount);
connect(m_ui->m_listEntryPoints, &QListWidget::itemSelectionChanged, this, &FormAddAccount::displayActiveEntryPointDetails); connect(m_ui->m_listEntryPoints, &QListWidget::itemSelectionChanged, this, &FormAddAccount::displayActiveEntryPointDetails);
@ -46,34 +44,33 @@ FormAddAccount::~FormAddAccount() {
void FormAddAccount::addSelectedAccount() { void FormAddAccount::addSelectedAccount() {
accept(); accept();
ServiceEntryPoint* point = selectedEntryPoint();
ServiceEntryPoint *point = selectedEntryPoint(); ServiceRoot* new_root = point->createNewRoot();
ServiceRoot *new_root = point->createNewRoot();
if (new_root != nullptr) { if (new_root != nullptr) {
m_model->addServiceAccount(new_root, true); m_model->addServiceAccount(new_root, true);
} }
else { else {
qCritical("Cannot create new account."); qCritical("Cannot create new account.");
} }
} }
void FormAddAccount::displayActiveEntryPointDetails() { void FormAddAccount::displayActiveEntryPointDetails() {
const ServiceEntryPoint *point = selectedEntryPoint(); const ServiceEntryPoint* point = selectedEntryPoint();
m_ui->m_txtAuthor->setText(point->author()); m_ui->m_txtAuthor->setText(point->author());
m_ui->m_txtDescription->setText(point->description()); m_ui->m_txtDescription->setText(point->description());
m_ui->m_txtName->setText(point->name()); m_ui->m_txtName->setText(point->name());
m_ui->m_txtVersion->setText(point->version()); m_ui->m_txtVersion->setText(point->version());
} }
ServiceEntryPoint *FormAddAccount::selectedEntryPoint() const { ServiceEntryPoint* FormAddAccount::selectedEntryPoint() const {
return m_entryPoints.at(m_ui->m_listEntryPoints->currentRow()); return m_entryPoints.at(m_ui->m_listEntryPoints->currentRow());
} }
void FormAddAccount::loadEntryPoints() { void FormAddAccount::loadEntryPoints() {
foreach (const ServiceEntryPoint *entry_point, m_entryPoints) { foreach (const ServiceEntryPoint* entry_point, m_entryPoints) {
QListWidgetItem *item = new QListWidgetItem(entry_point->icon(), entry_point->name(), m_ui->m_listEntryPoints); QListWidgetItem* item = new QListWidgetItem(entry_point->icon(), entry_point->name(), m_ui->m_listEntryPoints);
if (entry_point->isSingleInstanceService() && m_model->containsServiceRootFromEntryPoint(entry_point)) { if (entry_point->isSingleInstanceService() && m_model->containsServiceRootFromEntryPoint(entry_point)) {
// Oops, this item cannot be added, it is single instance and is already added. // Oops, this item cannot be added, it is single instance and is already added.

View File

@ -30,7 +30,7 @@ class FormAddAccount : public QDialog {
Q_OBJECT Q_OBJECT
public: public:
explicit FormAddAccount(const QList<ServiceEntryPoint*> &entry_points, FeedsModel *model, QWidget *parent = 0); explicit FormAddAccount(const QList<ServiceEntryPoint*>& entry_points, FeedsModel* model, QWidget* parent = 0);
virtual ~FormAddAccount(); virtual ~FormAddAccount();
private slots: private slots:
@ -38,11 +38,11 @@ class FormAddAccount : public QDialog {
void displayActiveEntryPointDetails(); void displayActiveEntryPointDetails();
private: private:
ServiceEntryPoint *selectedEntryPoint() const; ServiceEntryPoint* selectedEntryPoint() const;
void loadEntryPoints(); void loadEntryPoints();
QScopedPointer<Ui::FormAddAccount> m_ui; QScopedPointer<Ui::FormAddAccount> m_ui;
FeedsModel *m_model; FeedsModel* m_model;
QList<ServiceEntryPoint*> m_entryPoints; QList<ServiceEntryPoint*> m_entryPoints;
}; };

View File

@ -28,20 +28,17 @@
#include <QDateTime> #include <QDateTime>
FormBackupDatabaseSettings::FormBackupDatabaseSettings(QWidget *parent) : QDialog(parent), m_ui(new Ui::FormBackupDatabaseSettings) { FormBackupDatabaseSettings::FormBackupDatabaseSettings(QWidget* parent) : QDialog(parent), m_ui(new Ui::FormBackupDatabaseSettings) {
m_ui->setupUi(this); m_ui->setupUi(this);
m_ui->m_txtBackupName->lineEdit()->setPlaceholderText(tr("Common name for backup files")); m_ui->m_txtBackupName->lineEdit()->setPlaceholderText(tr("Common name for backup files"));
setWindowIcon(qApp->icons()->fromTheme(QSL("document-export"))); setWindowIcon(qApp->icons()->fromTheme(QSL("document-export")));
setWindowFlags(Qt::MSWindowsFixedSizeDialogHint | Qt::Dialog | Qt::WindowSystemMenuHint); setWindowFlags(Qt::MSWindowsFixedSizeDialogHint | Qt::Dialog | Qt::WindowSystemMenuHint);
connect(m_ui->m_checkBackupDatabase, &QCheckBox::toggled, this, &FormBackupDatabaseSettings::checkOkButton); connect(m_ui->m_checkBackupDatabase, &QCheckBox::toggled, this, &FormBackupDatabaseSettings::checkOkButton);
connect(m_ui->m_checkBackupSettings, &QCheckBox::toggled, this, &FormBackupDatabaseSettings::checkOkButton); connect(m_ui->m_checkBackupSettings, &QCheckBox::toggled, this, &FormBackupDatabaseSettings::checkOkButton);
connect(m_ui->m_buttonBox->button(QDialogButtonBox::Ok), &QPushButton::clicked, this, &FormBackupDatabaseSettings::performBackup); connect(m_ui->m_buttonBox->button(QDialogButtonBox::Ok), &QPushButton::clicked, this, &FormBackupDatabaseSettings::performBackup);
connect(m_ui->m_txtBackupName->lineEdit(), &BaseLineEdit::textChanged, this, &FormBackupDatabaseSettings::checkBackupNames); connect(m_ui->m_txtBackupName->lineEdit(), &BaseLineEdit::textChanged, this, &FormBackupDatabaseSettings::checkBackupNames);
connect(m_ui->m_txtBackupName->lineEdit(), &BaseLineEdit::textChanged, this, &FormBackupDatabaseSettings::checkOkButton); connect(m_ui->m_txtBackupName->lineEdit(), &BaseLineEdit::textChanged, this, &FormBackupDatabaseSettings::checkOkButton);
connect(m_ui->m_btnSelectFolder, &QPushButton::clicked, this, &FormBackupDatabaseSettings::selectFolderInitial); connect(m_ui->m_btnSelectFolder, &QPushButton::clicked, this, &FormBackupDatabaseSettings::selectFolderInitial);
selectFolder(qApp->getDocumentsFolderPath()); selectFolder(qApp->getDocumentsFolderPath());
m_ui->m_txtBackupName->lineEdit()->setText(QString(APP_LOW_NAME) + QL1S("_") + QDateTime::currentDateTime().toString(QSL("yyyyMMddHHmm"))); m_ui->m_txtBackupName->lineEdit()->setText(QString(APP_LOW_NAME) + QL1S("_") + QDateTime::currentDateTime().toString(QSL("yyyyMMddHHmm")));
m_ui->m_lblResult->setStatus(WidgetWithStatus::Warning, tr("No operation executed yet."), tr("No operation executed yet.")); m_ui->m_lblResult->setStatus(WidgetWithStatus::Warning, tr("No operation executed yet."), tr("No operation executed yet."));
@ -64,7 +61,8 @@ void FormBackupDatabaseSettings::performBackup() {
tr("Backup was created successfully and stored in target directory."), tr("Backup was created successfully and stored in target directory."),
tr("Backup was created successfully.")); tr("Backup was created successfully."));
} }
catch (const ApplicationException &ex) {
catch (const ApplicationException& ex) {
m_ui->m_lblResult->setStatus(WidgetWithStatus::Error, ex.message(), tr("Backup failed.")); m_ui->m_lblResult->setStatus(WidgetWithStatus::Error, ex.message(), tr("Backup failed."));
} }
} }
@ -84,10 +82,11 @@ void FormBackupDatabaseSettings::selectFolder(QString path) {
} }
} }
void FormBackupDatabaseSettings::checkBackupNames(const QString &name) { void FormBackupDatabaseSettings::checkBackupNames(const QString& name) {
if (name.simplified().isEmpty()) { if (name.simplified().isEmpty()) {
m_ui->m_txtBackupName->setStatus(WidgetWithStatus::Error, tr("Backup name cannot be empty.")); m_ui->m_txtBackupName->setStatus(WidgetWithStatus::Error, tr("Backup name cannot be empty."));
} }
else { else {
m_ui->m_txtBackupName->setStatus(WidgetWithStatus::Ok, tr("Backup name looks okay.")); m_ui->m_txtBackupName->setStatus(WidgetWithStatus::Ok, tr("Backup name looks okay."));
} }

View File

@ -28,7 +28,7 @@ class FormBackupDatabaseSettings : public QDialog {
public: public:
// Constructors and destructors // Constructors and destructors
explicit FormBackupDatabaseSettings(QWidget *parent = 0); explicit FormBackupDatabaseSettings(QWidget* parent = 0);
virtual ~FormBackupDatabaseSettings(); virtual ~FormBackupDatabaseSettings();
@ -36,7 +36,7 @@ class FormBackupDatabaseSettings : public QDialog {
void performBackup(); void performBackup();
void selectFolderInitial(); void selectFolderInitial();
void selectFolder(QString path = QString()); void selectFolder(QString path = QString());
void checkBackupNames(const QString &name); void checkBackupNames(const QString& name);
void checkOkButton(); void checkOkButton();
private: private:

View File

@ -26,13 +26,11 @@
#include <QPushButton> #include <QPushButton>
FormDatabaseCleanup::FormDatabaseCleanup(QWidget *parent) : QDialog(parent), m_ui(new Ui::FormDatabaseCleanup), m_cleaner(nullptr) { FormDatabaseCleanup::FormDatabaseCleanup(QWidget* parent) : QDialog(parent), m_ui(new Ui::FormDatabaseCleanup), m_cleaner(nullptr) {
m_ui->setupUi(this); m_ui->setupUi(this);
// Set flags and attributes. // Set flags and attributes.
setWindowFlags(Qt::MSWindowsFixedSizeDialogHint | Qt::Dialog | Qt::WindowSystemMenuHint | Qt::WindowTitleHint); setWindowFlags(Qt::MSWindowsFixedSizeDialogHint | Qt::Dialog | Qt::WindowSystemMenuHint | Qt::WindowTitleHint);
setWindowIcon(qApp->icons()->fromTheme(QSL("edit-clear"))); setWindowIcon(qApp->icons()->fromTheme(QSL("edit-clear")));
connect(m_ui->m_spinDays, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &FormDatabaseCleanup::updateDaysSuffix); connect(m_ui->m_spinDays, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &FormDatabaseCleanup::updateDaysSuffix);
m_ui->m_spinDays->setValue(DEFAULT_DAYS_TO_DELETE_MSG); m_ui->m_spinDays->setValue(DEFAULT_DAYS_TO_DELETE_MSG);
m_ui->m_lblResult->setStatus(WidgetWithStatus::Information, tr("I am ready."), tr("I am ready.")); m_ui->m_lblResult->setStatus(WidgetWithStatus::Information, tr("I am ready."), tr("I am ready."));
@ -43,34 +41,35 @@ FormDatabaseCleanup::~FormDatabaseCleanup() {
qDebug("Destroying FormDatabaseCleanup instance."); qDebug("Destroying FormDatabaseCleanup instance.");
} }
void FormDatabaseCleanup::setCleaner(DatabaseCleaner *cleaner) { void FormDatabaseCleanup::setCleaner(DatabaseCleaner* cleaner) {
if (m_cleaner != nullptr) { if (m_cleaner != nullptr) {
disconnect(this, 0, m_cleaner, 0); disconnect(this, 0, m_cleaner, 0);
disconnect(m_cleaner, 0, this, 0); disconnect(m_cleaner, 0, this, 0);
} }
m_cleaner = cleaner; m_cleaner = cleaner;
connect(m_ui->m_btnBox->button(QDialogButtonBox::Ok), &QPushButton::clicked, this, &FormDatabaseCleanup::startPurging); connect(m_ui->m_btnBox->button(QDialogButtonBox::Ok), &QPushButton::clicked, this, &FormDatabaseCleanup::startPurging);
connect(this, &FormDatabaseCleanup::purgeRequested, m_cleaner, &DatabaseCleaner::purgeDatabaseData); connect(this, &FormDatabaseCleanup::purgeRequested, m_cleaner, &DatabaseCleaner::purgeDatabaseData);
connect(m_cleaner, &DatabaseCleaner::purgeStarted, this, &FormDatabaseCleanup::onPurgeStarted); connect(m_cleaner, &DatabaseCleaner::purgeStarted, this, &FormDatabaseCleanup::onPurgeStarted);
connect(m_cleaner, &DatabaseCleaner::purgeProgress, this, &FormDatabaseCleanup::onPurgeProgress); connect(m_cleaner, &DatabaseCleaner::purgeProgress, this, &FormDatabaseCleanup::onPurgeProgress);
connect(m_cleaner, &DatabaseCleaner::purgeFinished, this,&FormDatabaseCleanup::onPurgeFinished); connect(m_cleaner, &DatabaseCleaner::purgeFinished, this, &FormDatabaseCleanup::onPurgeFinished);
} }
void FormDatabaseCleanup::closeEvent(QCloseEvent *event) { void FormDatabaseCleanup::closeEvent(QCloseEvent* event) {
if (m_ui->m_progressBar->isEnabled()) { if (m_ui->m_progressBar->isEnabled()) {
event->ignore(); event->ignore();
} }
else { else {
QDialog::closeEvent(event); QDialog::closeEvent(event);
} }
} }
void FormDatabaseCleanup::keyPressEvent(QKeyEvent *event) { void FormDatabaseCleanup::keyPressEvent(QKeyEvent* event) {
if (m_ui->m_progressBar->isEnabled()) { if (m_ui->m_progressBar->isEnabled()) {
event->ignore(); event->ignore();
} }
else { else {
QDialog::keyPressEvent(event); QDialog::keyPressEvent(event);
} }
@ -82,14 +81,12 @@ void FormDatabaseCleanup::updateDaysSuffix(int number) {
void FormDatabaseCleanup::startPurging() { void FormDatabaseCleanup::startPurging() {
CleanerOrders orders; CleanerOrders orders;
orders.m_removeRecycleBin = m_ui->m_checkRemoveRecycleBin->isChecked(); orders.m_removeRecycleBin = m_ui->m_checkRemoveRecycleBin->isChecked();
orders.m_removeOldMessages = m_ui->m_checkRemoveOldMessages->isChecked(); orders.m_removeOldMessages = m_ui->m_checkRemoveOldMessages->isChecked();
orders.m_barrierForRemovingOldMessagesInDays = m_ui->m_spinDays->value(); orders.m_barrierForRemovingOldMessagesInDays = m_ui->m_spinDays->value();
orders.m_removeReadMessages = m_ui->m_checkRemoveReadMessages->isChecked(); orders.m_removeReadMessages = m_ui->m_checkRemoveReadMessages->isChecked();
orders.m_shrinkDatabase = m_ui->m_checkShrink->isEnabled() && m_ui->m_checkShrink->isChecked(); orders.m_shrinkDatabase = m_ui->m_checkShrink->isEnabled() && m_ui->m_checkShrink->isChecked();
orders.m_removeStarredMessages = m_ui->m_checkRemoveStarredMessages->isChecked(); orders.m_removeStarredMessages = m_ui->m_checkRemoveStarredMessages->isChecked();
emit purgeRequested(orders); emit purgeRequested(orders);
} }
@ -100,7 +97,7 @@ void FormDatabaseCleanup::onPurgeStarted() {
m_ui->m_lblResult->setStatus(WidgetWithStatus::Information, tr("Database cleanup is running."), tr("Database cleanup is running.")); m_ui->m_lblResult->setStatus(WidgetWithStatus::Information, tr("Database cleanup is running."), tr("Database cleanup is running."));
} }
void FormDatabaseCleanup::onPurgeProgress(int progress, const QString &description) { void FormDatabaseCleanup::onPurgeProgress(int progress, const QString& description) {
m_ui->m_progressBar->setValue(progress); m_ui->m_progressBar->setValue(progress);
m_ui->m_lblResult->setStatus(WidgetWithStatus::Information, description, description); m_ui->m_lblResult->setStatus(WidgetWithStatus::Information, description, description);
} }
@ -113,6 +110,7 @@ void FormDatabaseCleanup::onPurgeFinished(bool finished) {
if (finished) { if (finished) {
m_ui->m_lblResult->setStatus(WidgetWithStatus::Ok, tr("Database cleanup is completed."), tr("Database cleanup is completed.")); m_ui->m_lblResult->setStatus(WidgetWithStatus::Ok, tr("Database cleanup is completed."), tr("Database cleanup is completed."));
} }
else { else {
m_ui->m_lblResult->setStatus(WidgetWithStatus::Error, tr("Database cleanup failed."), tr("Database cleanup failed.")); m_ui->m_lblResult->setStatus(WidgetWithStatus::Error, tr("Database cleanup failed."), tr("Database cleanup failed."));
} }
@ -123,10 +121,8 @@ void FormDatabaseCleanup::onPurgeFinished(bool finished) {
void FormDatabaseCleanup::loadDatabaseInfo() { void FormDatabaseCleanup::loadDatabaseInfo() {
qint64 file_size = qApp->database()->getDatabaseFileSize(); qint64 file_size = qApp->database()->getDatabaseFileSize();
qint64 data_size = qApp->database()->getDatabaseDataSize(); qint64 data_size = qApp->database()->getDatabaseDataSize();
QString file_size_str = file_size > 0 ? QString::number(file_size / 1000000.0) + QL1S(" MB") : tr("unknown"); QString file_size_str = file_size > 0 ? QString::number(file_size / 1000000.0) + QL1S(" MB") : tr("unknown");
QString data_size_str = data_size > 0 ? QString::number(data_size / 1000000.0) + QL1S(" MB") : tr("unknown"); QString data_size_str = data_size > 0 ? QString::number(data_size / 1000000.0) + QL1S(" MB") : tr("unknown");
m_ui->m_txtFileSize->setText(tr("file: %1, data: %2").arg(file_size_str, data_size_str)); m_ui->m_txtFileSize->setText(tr("file: %1, data: %2").arg(file_size_str, data_size_str));
m_ui->m_txtDatabaseType->setText(qApp->database()->humanDriverName(qApp->database()->activeDatabaseDriver())); m_ui->m_txtDatabaseType->setText(qApp->database()->humanDriverName(qApp->database()->activeDatabaseDriver()));
m_ui->m_checkShrink->setEnabled(qApp->database()->activeDatabaseDriver() == DatabaseFactory::SQLITE || m_ui->m_checkShrink->setEnabled(qApp->database()->activeDatabaseDriver() == DatabaseFactory::SQLITE ||

View File

@ -30,31 +30,31 @@ class FormDatabaseCleanup : public QDialog {
public: public:
// Constructors. // Constructors.
explicit FormDatabaseCleanup(QWidget *parent = 0); explicit FormDatabaseCleanup(QWidget* parent = 0);
virtual ~FormDatabaseCleanup(); virtual ~FormDatabaseCleanup();
void setCleaner(DatabaseCleaner *cleaner); void setCleaner(DatabaseCleaner* cleaner);
protected: protected:
void closeEvent(QCloseEvent *event); void closeEvent(QCloseEvent* event);
void keyPressEvent(QKeyEvent *event); void keyPressEvent(QKeyEvent* event);
private slots: private slots:
void updateDaysSuffix(int number); void updateDaysSuffix(int number);
void startPurging(); void startPurging();
void onPurgeStarted(); void onPurgeStarted();
void onPurgeProgress(int progress, const QString &description); void onPurgeProgress(int progress, const QString& description);
void onPurgeFinished(bool finished); void onPurgeFinished(bool finished);
signals: signals:
void purgeRequested(const CleanerOrders &which_data); void purgeRequested(const CleanerOrders& which_data);
private: private:
void loadDatabaseInfo(); void loadDatabaseInfo();
private: private:
QScopedPointer<Ui::FormDatabaseCleanup> m_ui; QScopedPointer<Ui::FormDatabaseCleanup> m_ui;
DatabaseCleaner *m_cleaner; DatabaseCleaner* m_cleaner;
}; };
#endif // FORMDATABASECLEANUP_H #endif // FORMDATABASECLEANUP_H

View File

@ -60,50 +60,38 @@
#endif #endif
FormMain::FormMain(QWidget *parent, Qt::WindowFlags f) FormMain::FormMain(QWidget* parent, Qt::WindowFlags f)
: QMainWindow(parent, f), m_ui(new Ui::FormMain) { : QMainWindow(parent, f), m_ui(new Ui::FormMain) {
m_ui->setupUi(this); m_ui->setupUi(this);
#if defined(USE_WEBENGINE) #if defined(USE_WEBENGINE)
m_adblockIcon = new AdBlockIcon(this); m_adblockIcon = new AdBlockIcon(this);
m_adblockIconAction = m_adblockIcon->menuAction(); m_adblockIconAction = m_adblockIcon->menuAction();
m_adblockIconAction->setObjectName(QSL("m_adblockIconAction")); m_adblockIconAction->setObjectName(QSL("m_adblockIconAction"));
m_ui->m_menuTools->addAction(m_adblockIconAction); m_ui->m_menuTools->addAction(m_adblockIconAction);
#endif #endif
qApp->setMainForm(this); qApp->setMainForm(this);
// Add these actions to the list of actions of the main window. // Add these actions to the list of actions of the main window.
// This allows to use actions via shortcuts // This allows to use actions via shortcuts
// even if main menu is not visible. // even if main menu is not visible.
addActions(allActions()); addActions(allActions());
#if defined(USE_WEBENGINE) #if defined(USE_WEBENGINE)
addAction(m_adblockIconAction); addAction(m_adblockIconAction);
#endif #endif
m_statusBar = new StatusBar(this); m_statusBar = new StatusBar(this);
setStatusBar(m_statusBar); setStatusBar(m_statusBar);
// Prepare main window and tabs. // Prepare main window and tabs.
prepareMenus(); prepareMenus();
// Prepare tabs. // Prepare tabs.
//m_ui->m_tabWidget->initializeTabs(); //m_ui->m_tabWidget->initializeTabs();
tabWidget()->feedMessageViewer()->feedsToolBar()->loadSavedActions(); tabWidget()->feedMessageViewer()->feedsToolBar()->loadSavedActions();
tabWidget()->feedMessageViewer()->messagesToolBar()->loadSavedActions(); tabWidget()->feedMessageViewer()->messagesToolBar()->loadSavedActions();
// Establish connections. // Establish connections.
createConnections(); createConnections();
updateMessageButtonsAvailability(); updateMessageButtonsAvailability();
updateFeedButtonsAvailability(); updateFeedButtonsAvailability();
// Setup some appearance of the window. // Setup some appearance of the window.
setupIcons(); setupIcons();
loadSize(); loadSize();
m_statusBar->loadSavedActions(); m_statusBar->loadSavedActions();
} }
@ -111,15 +99,15 @@ FormMain::~FormMain() {
qDebug("Destroying FormMain instance."); qDebug("Destroying FormMain instance.");
} }
QMenu *FormMain::trayMenu() const { QMenu* FormMain::trayMenu() const {
return m_trayMenu; return m_trayMenu;
} }
TabWidget *FormMain::tabWidget() const { TabWidget* FormMain::tabWidget() const {
return m_ui->m_tabWidget; return m_ui->m_tabWidget;
} }
StatusBar *FormMain::statusBar() const { StatusBar* FormMain::statusBar() const {
return m_statusBar; return m_statusBar;
} }
@ -128,12 +116,11 @@ void FormMain::showDbCleanupAssistant() {
QScopedPointer<FormDatabaseCleanup> form_pointer(new FormDatabaseCleanup(this)); QScopedPointer<FormDatabaseCleanup> form_pointer(new FormDatabaseCleanup(this));
form_pointer.data()->setCleaner(qApp->feedReader()->databaseCleaner()); form_pointer.data()->setCleaner(qApp->feedReader()->databaseCleaner());
form_pointer.data()->exec(); form_pointer.data()->exec();
qApp->feedUpdateLock()->unlock(); qApp->feedUpdateLock()->unlock();
tabWidget()->feedMessageViewer()->messagesView()->reloadSelections(); tabWidget()->feedMessageViewer()->messagesView()->reloadSelections();
qApp->feedReader()->feedsModel()->reloadCountsOfWholeModel(); qApp->feedReader()->feedsModel()->reloadCountsOfWholeModel();
} }
else { else {
qApp->showGuiMessage(tr("Cannot cleanup database"), qApp->showGuiMessage(tr("Cannot cleanup database"),
tr("Cannot cleanup database, because another critical action is running."), tr("Cannot cleanup database, because another critical action is running."),
@ -143,7 +130,6 @@ void FormMain::showDbCleanupAssistant() {
QList<QAction*> FormMain::allActions() const { QList<QAction*> FormMain::allActions() const {
QList<QAction*> actions; QList<QAction*> actions;
// Add basic actions. // Add basic actions.
actions << m_ui->m_actionSettings; actions << m_ui->m_actionSettings;
actions << m_ui->m_actionDownloadManager; actions << m_ui->m_actionDownloadManager;
@ -164,7 +150,6 @@ QList<QAction*> FormMain::allActions() const {
actions << m_ui->m_actionSwitchListHeaders; actions << m_ui->m_actionSwitchListHeaders;
actions << m_ui->m_actionSwitchStatusBar; actions << m_ui->m_actionSwitchStatusBar;
actions << m_ui->m_actionSwitchMessageListOrientation; actions << m_ui->m_actionSwitchMessageListOrientation;
// Add feeds/messages actions. // Add feeds/messages actions.
actions << m_ui->m_actionOpenSelectedSourceArticlesExternally; actions << m_ui->m_actionOpenSelectedSourceArticlesExternally;
actions << m_ui->m_actionOpenSelectedMessagesInternally; actions << m_ui->m_actionOpenSelectedMessagesInternally;
@ -196,15 +181,12 @@ QList<QAction*> FormMain::allActions() const {
actions << m_ui->m_actionSelectPreviousMessage; actions << m_ui->m_actionSelectPreviousMessage;
actions << m_ui->m_actionSelectNextUnreadMessage; actions << m_ui->m_actionSelectNextUnreadMessage;
actions << m_ui->m_actionExpandCollapseItem; actions << m_ui->m_actionExpandCollapseItem;
#if defined(USE_WEBENGINE) #if defined(USE_WEBENGINE)
actions << m_ui->m_actionTabNewWebBrowser; actions << m_ui->m_actionTabNewWebBrowser;
actions << m_adblockIconAction; actions << m_adblockIconAction;
#endif #endif
actions << m_ui->m_actionTabsCloseAll; actions << m_ui->m_actionTabsCloseAll;
actions << m_ui->m_actionTabsCloseAllExceptCurrent; actions << m_ui->m_actionTabsCloseAllExceptCurrent;
return actions; return actions;
} }
@ -216,7 +198,6 @@ void FormMain::prepareMenus() {
#else #else
m_trayMenu = new QMenu(QSL(APP_NAME), this); m_trayMenu = new QMenu(QSL(APP_NAME), this);
#endif #endif
// Add needed items to the menu. // Add needed items to the menu.
m_trayMenu->addAction(m_ui->m_actionSwitchMainWindow); m_trayMenu->addAction(m_ui->m_actionSwitchMainWindow);
m_trayMenu->addSeparator(); m_trayMenu->addSeparator();
@ -225,7 +206,6 @@ void FormMain::prepareMenus() {
m_trayMenu->addSeparator(); m_trayMenu->addSeparator();
m_trayMenu->addAction(m_ui->m_actionSettings); m_trayMenu->addAction(m_ui->m_actionSettings);
m_trayMenu->addAction(m_ui->m_actionQuit); m_trayMenu->addAction(m_ui->m_actionQuit);
qDebug("Creating tray icon menu."); qDebug("Creating tray icon menu.");
} }
@ -233,7 +213,6 @@ void FormMain::prepareMenus() {
m_ui->m_menuWebBrowserTabs->removeAction(m_ui->m_actionTabNewWebBrowser); m_ui->m_menuWebBrowserTabs->removeAction(m_ui->m_actionTabNewWebBrowser);
m_ui->m_menuWebBrowserTabs->setTitle(tr("Tabs")); m_ui->m_menuWebBrowserTabs->setTitle(tr("Tabs"));
#endif #endif
#if defined(Q_OS_MAC) #if defined(Q_OS_MAC)
m_ui->m_actionSwitchMainMenu->setVisible(false); m_ui->m_actionSwitchMainMenu->setVisible(false);
m_ui->m_actionFullscreen->setVisible(false); m_ui->m_actionFullscreen->setVisible(false);
@ -245,10 +224,12 @@ void FormMain::switchFullscreenMode() {
qApp->settings()->setValue(GROUP(GUI), GUI::IsMainWindowMaximizedBeforeFullscreen, isMaximized()); qApp->settings()->setValue(GROUP(GUI), GUI::IsMainWindowMaximizedBeforeFullscreen, isMaximized());
showFullScreen(); showFullScreen();
} }
else { else {
if (qApp->settings()->value(GROUP(GUI), SETTING(GUI::IsMainWindowMaximizedBeforeFullscreen)).toBool()) { if (qApp->settings()->value(GROUP(GUI), SETTING(GUI::IsMainWindowMaximizedBeforeFullscreen)).toBool()) {
setWindowState((windowState() & ~Qt::WindowFullScreen) | Qt::WindowMaximized); setWindowState((windowState() & ~Qt::WindowFullScreen) | Qt::WindowMaximized);
} }
else { else {
showNormal(); showNormal();
} }
@ -259,15 +240,14 @@ void FormMain::updateAddItemMenu() {
// NOTE: Clear here deletes items from memory but only those OWNED by the menu. // NOTE: Clear here deletes items from memory but only those OWNED by the menu.
m_ui->m_menuAddItem->clear(); m_ui->m_menuAddItem->clear();
foreach (ServiceRoot *activated_root, qApp->feedReader()->feedsModel()->serviceRoots()) { foreach (ServiceRoot* activated_root, qApp->feedReader()->feedsModel()->serviceRoots()) {
QMenu *root_menu = new QMenu(activated_root->title(), m_ui->m_menuAddItem); QMenu* root_menu = new QMenu(activated_root->title(), m_ui->m_menuAddItem);
root_menu->setIcon(activated_root->icon()); root_menu->setIcon(activated_root->icon());
root_menu->setToolTip(activated_root->description()); root_menu->setToolTip(activated_root->description());
QList<QAction*> specific_root_actions = activated_root->addItemMenu(); QList<QAction*> specific_root_actions = activated_root->addItemMenu();
if (activated_root->supportsCategoryAdding()) { if (activated_root->supportsCategoryAdding()) {
QAction *action_new_category = new QAction(qApp->icons()->fromTheme(QSL("folder")), QAction* action_new_category = new QAction(qApp->icons()->fromTheme(QSL("folder")),
tr("Add new category"), tr("Add new category"),
m_ui->m_menuAddItem); m_ui->m_menuAddItem);
root_menu->addAction(action_new_category); root_menu->addAction(action_new_category);
@ -275,7 +255,7 @@ void FormMain::updateAddItemMenu() {
} }
if (activated_root->supportsFeedAdding()) { if (activated_root->supportsFeedAdding()) {
QAction *action_new_feed = new QAction(qApp->icons()->fromTheme(QSL("application-rss+xml")), QAction* action_new_feed = new QAction(qApp->icons()->fromTheme(QSL("application-rss+xml")),
tr("Add new feed"), tr("Add new feed"),
m_ui->m_menuAddItem); m_ui->m_menuAddItem);
root_menu->addAction(action_new_feed); root_menu->addAction(action_new_feed);
@ -299,6 +279,7 @@ void FormMain::updateAddItemMenu() {
m_ui->m_menuAddItem->addAction(m_ui->m_actionAddCategoryIntoSelectedAccount); m_ui->m_menuAddItem->addAction(m_ui->m_actionAddCategoryIntoSelectedAccount);
m_ui->m_menuAddItem->addAction(m_ui->m_actionAddFeedIntoSelectedAccount); m_ui->m_menuAddItem->addAction(m_ui->m_actionAddFeedIntoSelectedAccount);
} }
else { else {
m_ui->m_menuAddItem->addAction(m_ui->m_actionNoActions); m_ui->m_menuAddItem->addAction(m_ui->m_actionNoActions);
} }
@ -307,28 +288,29 @@ void FormMain::updateAddItemMenu() {
void FormMain::updateRecycleBinMenu() { void FormMain::updateRecycleBinMenu() {
m_ui->m_menuRecycleBin->clear(); m_ui->m_menuRecycleBin->clear();
foreach (const ServiceRoot *activated_root, qApp->feedReader()->feedsModel()->serviceRoots()) { foreach (const ServiceRoot* activated_root, qApp->feedReader()->feedsModel()->serviceRoots()) {
QMenu *root_menu = new QMenu(activated_root->title(), m_ui->m_menuRecycleBin); QMenu* root_menu = new QMenu(activated_root->title(), m_ui->m_menuRecycleBin);
root_menu->setIcon(activated_root->icon()); root_menu->setIcon(activated_root->icon());
root_menu->setToolTip(activated_root->description()); root_menu->setToolTip(activated_root->description());
RecycleBin* bin = activated_root->recycleBin();
RecycleBin *bin = activated_root->recycleBin();
QList<QAction*> context_menu; QList<QAction*> context_menu;
if (bin == nullptr) { if (bin == nullptr) {
QAction *no_action = new QAction(qApp->icons()->fromTheme(QSL("dialog-error")), QAction* no_action = new QAction(qApp->icons()->fromTheme(QSL("dialog-error")),
tr("No recycle bin"), tr("No recycle bin"),
m_ui->m_menuRecycleBin); m_ui->m_menuRecycleBin);
no_action->setEnabled(false); no_action->setEnabled(false);
root_menu->addAction(no_action); root_menu->addAction(no_action);
} }
else if ((context_menu = bin->contextMenu()).isEmpty()) { else if ((context_menu = bin->contextMenu()).isEmpty()) {
QAction *no_action = new QAction(qApp->icons()->fromTheme(QSL("dialog-error")), QAction* no_action = new QAction(qApp->icons()->fromTheme(QSL("dialog-error")),
tr("No actions possible"), tr("No actions possible"),
m_ui->m_menuRecycleBin); m_ui->m_menuRecycleBin);
no_action->setEnabled(false); no_action->setEnabled(false);
root_menu->addAction(no_action); root_menu->addAction(no_action);
} }
else { else {
root_menu->addActions(context_menu); root_menu->addActions(context_menu);
} }
@ -347,20 +329,20 @@ void FormMain::updateRecycleBinMenu() {
void FormMain::updateAccountsMenu() { void FormMain::updateAccountsMenu() {
m_ui->m_menuAccounts->clear(); m_ui->m_menuAccounts->clear();
foreach (ServiceRoot *activated_root, qApp->feedReader()->feedsModel()->serviceRoots()) { foreach (ServiceRoot* activated_root, qApp->feedReader()->feedsModel()->serviceRoots()) {
QMenu *root_menu = new QMenu(activated_root->title(), m_ui->m_menuAccounts); QMenu* root_menu = new QMenu(activated_root->title(), m_ui->m_menuAccounts);
root_menu->setIcon(activated_root->icon()); root_menu->setIcon(activated_root->icon());
root_menu->setToolTip(activated_root->description()); root_menu->setToolTip(activated_root->description());
QList<QAction*> root_actions = activated_root->serviceMenu(); QList<QAction*> root_actions = activated_root->serviceMenu();
if (root_actions.isEmpty()) { if (root_actions.isEmpty()) {
QAction *no_action = new QAction(qApp->icons()->fromTheme(QSL("dialog-error")), QAction* no_action = new QAction(qApp->icons()->fromTheme(QSL("dialog-error")),
tr("No possible actions"), tr("No possible actions"),
m_ui->m_menuAccounts); m_ui->m_menuAccounts);
no_action->setEnabled(false); no_action->setEnabled(false);
root_menu->addAction(no_action); root_menu->addAction(no_action);
} }
else { else {
root_menu->addActions(root_actions); root_menu->addActions(root_actions);
} }
@ -377,9 +359,8 @@ void FormMain::updateAccountsMenu() {
m_ui->m_menuAccounts->addAction(m_ui->m_actionServiceDelete); m_ui->m_menuAccounts->addAction(m_ui->m_actionServiceDelete);
} }
void FormMain::onFeedUpdatesFinished(const FeedDownloadResults &results) { void FormMain::onFeedUpdatesFinished(const FeedDownloadResults& results) {
Q_UNUSED(results) Q_UNUSED(results)
statusBar()->clearProgressFeeds(); statusBar()->clearProgressFeeds();
tabWidget()->feedMessageViewer()->messagesView()->reloadSelections(); tabWidget()->feedMessageViewer()->messagesView()->reloadSelections();
} }
@ -389,7 +370,7 @@ void FormMain::onFeedUpdatesStarted() {
statusBar()->showProgressFeeds(0, tr("Feed update started")); statusBar()->showProgressFeeds(0, tr("Feed update started"));
} }
void FormMain::onFeedUpdatesProgress(const Feed *feed, int current, int total) { void FormMain::onFeedUpdatesProgress(const Feed* feed, int current, int total) {
statusBar()->showProgressFeeds((current * 100.0) / total, statusBar()->showProgressFeeds((current * 100.0) / total,
//: Text display in status bar when particular feed is updated. //: Text display in status bar when particular feed is updated.
tr("Updated feed '%1'").arg(feed->title())); tr("Updated feed '%1'").arg(feed->title()));
@ -398,8 +379,8 @@ void FormMain::onFeedUpdatesProgress(const Feed *feed, int current, int total) {
void FormMain::updateMessageButtonsAvailability() { void FormMain::updateMessageButtonsAvailability() {
const bool one_message_selected = tabWidget()->feedMessageViewer()->messagesView()->selectionModel()->selectedRows().size() == 1; const bool one_message_selected = tabWidget()->feedMessageViewer()->messagesView()->selectionModel()->selectedRows().size() == 1;
const bool atleast_one_message_selected = !tabWidget()->feedMessageViewer()->messagesView()->selectionModel()->selectedRows().isEmpty(); const bool atleast_one_message_selected = !tabWidget()->feedMessageViewer()->messagesView()->selectionModel()->selectedRows().isEmpty();
const bool bin_loaded = tabWidget()->feedMessageViewer()->messagesView()->sourceModel()->loadedItem() != nullptr && tabWidget()->feedMessageViewer()->messagesView()->sourceModel()->loadedItem()->kind() == RootItemKind::Bin; const bool bin_loaded = tabWidget()->feedMessageViewer()->messagesView()->sourceModel()->loadedItem() != nullptr
&& tabWidget()->feedMessageViewer()->messagesView()->sourceModel()->loadedItem()->kind() == RootItemKind::Bin;
m_ui->m_actionDeleteSelectedMessages->setEnabled(atleast_one_message_selected); m_ui->m_actionDeleteSelectedMessages->setEnabled(atleast_one_message_selected);
m_ui->m_actionRestoreSelectedMessages->setEnabled(atleast_one_message_selected && bin_loaded); m_ui->m_actionRestoreSelectedMessages->setEnabled(atleast_one_message_selected && bin_loaded);
m_ui->m_actionMarkSelectedMessagesAsRead->setEnabled(atleast_one_message_selected); m_ui->m_actionMarkSelectedMessagesAsRead->setEnabled(atleast_one_message_selected);
@ -413,12 +394,11 @@ void FormMain::updateMessageButtonsAvailability() {
void FormMain::updateFeedButtonsAvailability() { void FormMain::updateFeedButtonsAvailability() {
const bool is_update_running = qApp->feedReader()->isFeedUpdateRunning(); const bool is_update_running = qApp->feedReader()->isFeedUpdateRunning();
const bool critical_action_running = qApp->feedUpdateLock()->isLocked(); const bool critical_action_running = qApp->feedUpdateLock()->isLocked();
const RootItem *selected_item = tabWidget()->feedMessageViewer()->feedsView()->selectedItem(); const RootItem* selected_item = tabWidget()->feedMessageViewer()->feedsView()->selectedItem();
const bool anything_selected = selected_item != nullptr; const bool anything_selected = selected_item != nullptr;
const bool feed_selected = anything_selected && selected_item->kind() == RootItemKind::Feed; const bool feed_selected = anything_selected && selected_item->kind() == RootItemKind::Feed;
const bool category_selected = anything_selected && selected_item->kind() == RootItemKind::Category; const bool category_selected = anything_selected && selected_item->kind() == RootItemKind::Category;
const bool service_selected = anything_selected && selected_item->kind() == RootItemKind::ServiceRoot; const bool service_selected = anything_selected && selected_item->kind() == RootItemKind::ServiceRoot;
m_ui->m_actionStopRunningItemsUpdate->setEnabled(is_update_running); m_ui->m_actionStopRunningItemsUpdate->setEnabled(is_update_running);
m_ui->m_actionBackupDatabaseSettings->setEnabled(!critical_action_running); m_ui->m_actionBackupDatabaseSettings->setEnabled(!critical_action_running);
m_ui->m_actionCleanupDatabase->setEnabled(!critical_action_running); m_ui->m_actionCleanupDatabase->setEnabled(!critical_action_running);
@ -431,12 +411,10 @@ void FormMain::updateFeedButtonsAvailability() {
m_ui->m_actionUpdateSelectedItems->setEnabled(!critical_action_running && (feed_selected || category_selected || service_selected)); m_ui->m_actionUpdateSelectedItems->setEnabled(!critical_action_running && (feed_selected || category_selected || service_selected));
m_ui->m_actionViewSelectedItemsNewspaperMode->setEnabled(anything_selected); m_ui->m_actionViewSelectedItemsNewspaperMode->setEnabled(anything_selected);
m_ui->m_actionExpandCollapseItem->setEnabled(anything_selected); m_ui->m_actionExpandCollapseItem->setEnabled(anything_selected);
m_ui->m_actionServiceDelete->setEnabled(service_selected); m_ui->m_actionServiceDelete->setEnabled(service_selected);
m_ui->m_actionServiceEdit->setEnabled(service_selected); m_ui->m_actionServiceEdit->setEnabled(service_selected);
m_ui->m_actionAddFeedIntoSelectedAccount->setEnabled(anything_selected); m_ui->m_actionAddFeedIntoSelectedAccount->setEnabled(anything_selected);
m_ui->m_actionAddCategoryIntoSelectedAccount->setEnabled(anything_selected); m_ui->m_actionAddCategoryIntoSelectedAccount->setEnabled(anything_selected);
m_ui->m_menuAddItem->setEnabled(!critical_action_running); m_ui->m_menuAddItem->setEnabled(!critical_action_running);
m_ui->m_menuAccounts->setEnabled(!critical_action_running); m_ui->m_menuAccounts->setEnabled(!critical_action_running);
m_ui->m_menuRecycleBin->setEnabled(!critical_action_running); m_ui->m_menuRecycleBin->setEnabled(!critical_action_running);
@ -447,11 +425,13 @@ void FormMain::switchVisibility(bool force_hide) {
if (SystemTrayIcon::isSystemTrayActivated()) { if (SystemTrayIcon::isSystemTrayActivated()) {
hide(); hide();
} }
else { else {
// Window gets minimized in single-window mode. // Window gets minimized in single-window mode.
showMinimized(); showMinimized();
} }
} }
else { else {
display(); display();
} }
@ -460,19 +440,16 @@ void FormMain::switchVisibility(bool force_hide) {
void FormMain::display() { void FormMain::display() {
// Make sure window is not minimized. // Make sure window is not minimized.
setWindowState(windowState() & ~Qt::WindowMinimized); setWindowState(windowState() & ~Qt::WindowMinimized);
// Display the window and make sure it is raised on top. // Display the window and make sure it is raised on top.
show(); show();
activateWindow(); activateWindow();
raise(); raise();
// Raise alert event. Check the documentation for more info on this. // Raise alert event. Check the documentation for more info on this.
Application::alert(this); Application::alert(this);
} }
void FormMain::setupIcons() { void FormMain::setupIcons() {
IconFactory *icon_theme_factory = qApp->icons(); IconFactory* icon_theme_factory = qApp->icons();
// Setup icons of this main window. // Setup icons of this main window.
m_ui->m_actionDownloadManager->setIcon(icon_theme_factory->fromTheme(QSL("emblem-downloads"))); m_ui->m_actionDownloadManager->setIcon(icon_theme_factory->fromTheme(QSL("emblem-downloads")));
m_ui->m_actionSettings->setIcon(icon_theme_factory->fromTheme(QSL("document-properties"))); m_ui->m_actionSettings->setIcon(icon_theme_factory->fromTheme(QSL("document-properties")));
@ -486,7 +463,6 @@ void FormMain::setupIcons() {
m_ui->m_actionRestoreDatabaseSettings->setIcon(icon_theme_factory->fromTheme(QSL("document-import"))); m_ui->m_actionRestoreDatabaseSettings->setIcon(icon_theme_factory->fromTheme(QSL("document-import")));
m_ui->m_actionDonate->setIcon(icon_theme_factory->fromTheme(QSL("applications-office"))); m_ui->m_actionDonate->setIcon(icon_theme_factory->fromTheme(QSL("applications-office")));
m_ui->m_actionDisplayWiki->setIcon(icon_theme_factory->fromTheme(QSL("applications-science"))); m_ui->m_actionDisplayWiki->setIcon(icon_theme_factory->fromTheme(QSL("applications-science")));
// View. // View.
m_ui->m_actionSwitchMainWindow->setIcon(icon_theme_factory->fromTheme(QSL("window-close"))); m_ui->m_actionSwitchMainWindow->setIcon(icon_theme_factory->fromTheme(QSL("window-close")));
m_ui->m_actionFullscreen->setIcon(icon_theme_factory->fromTheme(QSL("view-fullscreen"))); m_ui->m_actionFullscreen->setIcon(icon_theme_factory->fromTheme(QSL("view-fullscreen")));
@ -497,7 +473,6 @@ void FormMain::setupIcons() {
m_ui->m_actionSwitchStatusBar->setIcon(icon_theme_factory->fromTheme(QSL("dialog-information"))); m_ui->m_actionSwitchStatusBar->setIcon(icon_theme_factory->fromTheme(QSL("dialog-information")));
m_ui->m_actionSwitchMessageListOrientation->setIcon(icon_theme_factory->fromTheme(QSL("view-restore"))); m_ui->m_actionSwitchMessageListOrientation->setIcon(icon_theme_factory->fromTheme(QSL("view-restore")));
m_ui->m_menuShowHide->setIcon(icon_theme_factory->fromTheme(QSL("view-restore"))); m_ui->m_menuShowHide->setIcon(icon_theme_factory->fromTheme(QSL("view-restore")));
// Feeds/messages. // Feeds/messages.
m_ui->m_menuAddItem->setIcon(icon_theme_factory->fromTheme(QSL("list-add"))); m_ui->m_menuAddItem->setIcon(icon_theme_factory->fromTheme(QSL("list-add")));
m_ui->m_actionStopRunningItemsUpdate->setIcon(icon_theme_factory->fromTheme(QSL("process-stop"))); m_ui->m_actionStopRunningItemsUpdate->setIcon(icon_theme_factory->fromTheme(QSL("process-stop")));
@ -533,27 +508,23 @@ void FormMain::setupIcons() {
m_ui->m_actionServiceDelete->setIcon(icon_theme_factory->fromTheme(QSL("list-remove"))); m_ui->m_actionServiceDelete->setIcon(icon_theme_factory->fromTheme(QSL("list-remove")));
m_ui->m_actionAddFeedIntoSelectedAccount->setIcon(icon_theme_factory->fromTheme(QSL("application-rss+xml"))); m_ui->m_actionAddFeedIntoSelectedAccount->setIcon(icon_theme_factory->fromTheme(QSL("application-rss+xml")));
m_ui->m_actionAddCategoryIntoSelectedAccount->setIcon(icon_theme_factory->fromTheme(QSL("folder"))); m_ui->m_actionAddCategoryIntoSelectedAccount->setIcon(icon_theme_factory->fromTheme(QSL("folder")));
// Tabs & web browser. // Tabs & web browser.
m_ui->m_actionTabNewWebBrowser->setIcon(icon_theme_factory->fromTheme(QSL("tab-new"))); m_ui->m_actionTabNewWebBrowser->setIcon(icon_theme_factory->fromTheme(QSL("tab-new")));
m_ui->m_actionTabsCloseAll->setIcon(icon_theme_factory->fromTheme(QSL("window-close"))); m_ui->m_actionTabsCloseAll->setIcon(icon_theme_factory->fromTheme(QSL("window-close")));
m_ui->m_actionTabsCloseAllExceptCurrent->setIcon(icon_theme_factory->fromTheme(QSL("window-close"))); m_ui->m_actionTabsCloseAllExceptCurrent->setIcon(icon_theme_factory->fromTheme(QSL("window-close")));
// Setup icons on TabWidget too. // Setup icons on TabWidget too.
m_ui->m_tabWidget->setupIcons(); m_ui->m_tabWidget->setupIcons();
} }
void FormMain::loadSize() { void FormMain::loadSize() {
const QRect screen = qApp->desktop()->screenGeometry(); const QRect screen = qApp->desktop()->screenGeometry();
const Settings *settings = qApp->settings(); const Settings* settings = qApp->settings();
// Reload main window size & position. // Reload main window size & position.
resize(settings->value(GROUP(GUI), GUI::MainWindowInitialSize, size()).toSize()); resize(settings->value(GROUP(GUI), GUI::MainWindowInitialSize, size()).toSize());
move(settings->value(GROUP(GUI), GUI::MainWindowInitialPosition, screen.center() - rect().center()).toPoint()); move(settings->value(GROUP(GUI), GUI::MainWindowInitialPosition, screen.center() - rect().center()).toPoint());
if (settings->value(GROUP(GUI), SETTING(GUI::MainWindowStartsMaximized)).toBool()) { if (settings->value(GROUP(GUI), SETTING(GUI::MainWindowStartsMaximized)).toBool()) {
setWindowState(windowState() | Qt::WindowMaximized); setWindowState(windowState() | Qt::WindowMaximized);
// We process events so that window is really maximized fast. // We process events so that window is really maximized fast.
qApp->processEvents(); qApp->processEvents();
} }
@ -566,36 +537,31 @@ void FormMain::loadSize() {
// Hide the main menu if user wants it. // Hide the main menu if user wants it.
m_ui->m_actionSwitchMainMenu->setChecked(settings->value(GROUP(GUI), SETTING(GUI::MainMenuVisible)).toBool()); m_ui->m_actionSwitchMainMenu->setChecked(settings->value(GROUP(GUI), SETTING(GUI::MainMenuVisible)).toBool());
// Adjust dimensions of "feeds & messages" widget. // Adjust dimensions of "feeds & messages" widget.
m_ui->m_tabWidget->feedMessageViewer()->loadSize(); m_ui->m_tabWidget->feedMessageViewer()->loadSize();
m_ui->m_actionSwitchToolBars->setChecked(settings->value(GROUP(GUI), SETTING(GUI::ToolbarsVisible)).toBool()); m_ui->m_actionSwitchToolBars->setChecked(settings->value(GROUP(GUI), SETTING(GUI::ToolbarsVisible)).toBool());
m_ui->m_actionSwitchListHeaders->setChecked(settings->value(GROUP(GUI), SETTING(GUI::ListHeadersVisible)).toBool()); m_ui->m_actionSwitchListHeaders->setChecked(settings->value(GROUP(GUI), SETTING(GUI::ListHeadersVisible)).toBool());
m_ui->m_actionSwitchStatusBar->setChecked(settings->value(GROUP(GUI), SETTING(GUI::StatusBarVisible)).toBool()); m_ui->m_actionSwitchStatusBar->setChecked(settings->value(GROUP(GUI), SETTING(GUI::StatusBarVisible)).toBool());
// Make sure that only unread feeds are shown if user has that feature set on. // Make sure that only unread feeds are shown if user has that feature set on.
m_ui->m_actionShowOnlyUnreadItems->setChecked(settings->value(GROUP(Feeds), SETTING(Feeds::ShowOnlyUnreadFeeds)).toBool()); m_ui->m_actionShowOnlyUnreadItems->setChecked(settings->value(GROUP(Feeds), SETTING(Feeds::ShowOnlyUnreadFeeds)).toBool());
} }
void FormMain::saveSize() { void FormMain::saveSize() {
Settings *settings = qApp->settings(); Settings* settings = qApp->settings();
bool is_fullscreen = isFullScreen(); bool is_fullscreen = isFullScreen();
bool is_maximized = false; bool is_maximized = false;
if (is_fullscreen) { if (is_fullscreen) {
m_ui->m_actionFullscreen->setChecked(false); m_ui->m_actionFullscreen->setChecked(false);
// We (process events to really) un-fullscreen, so that we can determine if window is really maximized. // We (process events to really) un-fullscreen, so that we can determine if window is really maximized.
qApp->processEvents(); qApp->processEvents();
} }
if (isMaximized()) { if (isMaximized()) {
is_maximized = true; is_maximized = true;
// Window is maximized, we store that fact to settings and unmaximize. // Window is maximized, we store that fact to settings and unmaximize.
qApp->settings()->setValue(GROUP(GUI), GUI::IsMainWindowMaximizedBeforeFullscreen, isMaximized()); qApp->settings()->setValue(GROUP(GUI), GUI::IsMainWindowMaximizedBeforeFullscreen, isMaximized());
setWindowState((windowState() & ~Qt::WindowMaximized) | Qt::WindowActive); setWindowState((windowState() & ~Qt::WindowMaximized) | Qt::WindowActive);
// We process events to really have window un-maximized. // We process events to really have window un-maximized.
qApp->processEvents(); qApp->processEvents();
} }
@ -606,7 +572,6 @@ void FormMain::saveSize() {
settings->setValue(GROUP(GUI), GUI::MainWindowStartsMaximized, is_maximized); settings->setValue(GROUP(GUI), GUI::MainWindowStartsMaximized, is_maximized);
settings->setValue(GROUP(GUI), GUI::MainWindowStartsFullscreen, is_fullscreen); settings->setValue(GROUP(GUI), GUI::MainWindowStartsFullscreen, is_fullscreen);
settings->setValue(GROUP(GUI), GUI::StatusBarVisible, m_ui->m_actionSwitchStatusBar->isChecked()); settings->setValue(GROUP(GUI), GUI::StatusBarVisible, m_ui->m_actionSwitchStatusBar->isChecked());
m_ui->m_tabWidget->feedMessageViewer()->saveSize(); m_ui->m_tabWidget->feedMessageViewer()->saveSize();
} }
@ -615,53 +580,43 @@ void FormMain::createConnections() {
connect(m_ui->m_menuAddItem, &QMenu::aboutToShow, this, &FormMain::updateAddItemMenu); connect(m_ui->m_menuAddItem, &QMenu::aboutToShow, this, &FormMain::updateAddItemMenu);
connect(m_ui->m_menuRecycleBin, &QMenu::aboutToShow, this, &FormMain::updateRecycleBinMenu); connect(m_ui->m_menuRecycleBin, &QMenu::aboutToShow, this, &FormMain::updateRecycleBinMenu);
connect(m_ui->m_menuAccounts, &QMenu::aboutToShow, this, &FormMain::updateAccountsMenu); connect(m_ui->m_menuAccounts, &QMenu::aboutToShow, this, &FormMain::updateAccountsMenu);
connect(m_ui->m_actionServiceDelete, &QAction::triggered, m_ui->m_actionDeleteSelectedItem, &QAction::triggered); connect(m_ui->m_actionServiceDelete, &QAction::triggered, m_ui->m_actionDeleteSelectedItem, &QAction::triggered);
connect(m_ui->m_actionServiceEdit, &QAction::triggered, m_ui->m_actionEditSelectedItem, &QAction::triggered); connect(m_ui->m_actionServiceEdit, &QAction::triggered, m_ui->m_actionEditSelectedItem, &QAction::triggered);
// Menu "File" connections. // Menu "File" connections.
connect(m_ui->m_actionBackupDatabaseSettings, &QAction::triggered, this, &FormMain::backupDatabaseSettings); connect(m_ui->m_actionBackupDatabaseSettings, &QAction::triggered, this, &FormMain::backupDatabaseSettings);
connect(m_ui->m_actionRestoreDatabaseSettings, &QAction::triggered, this, &FormMain::restoreDatabaseSettings); connect(m_ui->m_actionRestoreDatabaseSettings, &QAction::triggered, this, &FormMain::restoreDatabaseSettings);
connect(m_ui->m_actionQuit, &QAction::triggered, qApp, &Application::quit); connect(m_ui->m_actionQuit, &QAction::triggered, qApp, &Application::quit);
connect(m_ui->m_actionServiceAdd, &QAction::triggered, this, &FormMain::showAddAccountDialog); connect(m_ui->m_actionServiceAdd, &QAction::triggered, this, &FormMain::showAddAccountDialog);
connect(m_ui->m_actionRestart, &QAction::triggered, qApp, &Application::restart); connect(m_ui->m_actionRestart, &QAction::triggered, qApp, &Application::restart);
// Menu "View" connections. // Menu "View" connections.
connect(m_ui->m_actionFullscreen, &QAction::toggled, this, &FormMain::switchFullscreenMode); connect(m_ui->m_actionFullscreen, &QAction::toggled, this, &FormMain::switchFullscreenMode);
connect(m_ui->m_actionSwitchMainMenu, &QAction::toggled, m_ui->m_menuBar, &QMenuBar::setVisible); connect(m_ui->m_actionSwitchMainMenu, &QAction::toggled, m_ui->m_menuBar, &QMenuBar::setVisible);
connect(m_ui->m_actionSwitchMainWindow, &QAction::triggered, this, &FormMain::switchVisibility); connect(m_ui->m_actionSwitchMainWindow, &QAction::triggered, this, &FormMain::switchVisibility);
connect(m_ui->m_actionSwitchStatusBar, &QAction::toggled, statusBar(), &StatusBar::setVisible); connect(m_ui->m_actionSwitchStatusBar, &QAction::toggled, statusBar(), &StatusBar::setVisible);
// Menu "Tools" connections. // Menu "Tools" connections.
connect(m_ui->m_actionSettings, &QAction::triggered, this, &FormMain::showSettings); connect(m_ui->m_actionSettings, &QAction::triggered, this, &FormMain::showSettings);
connect(m_ui->m_actionDownloadManager, &QAction::triggered, m_ui->m_tabWidget, &TabWidget::showDownloadManager); connect(m_ui->m_actionDownloadManager, &QAction::triggered, m_ui->m_tabWidget, &TabWidget::showDownloadManager);
connect(m_ui->m_actionCleanupDatabase, &QAction::triggered, this, &FormMain::showDbCleanupAssistant); connect(m_ui->m_actionCleanupDatabase, &QAction::triggered, this, &FormMain::showDbCleanupAssistant);
// Menu "Help" connections. // Menu "Help" connections.
connect(m_ui->m_actionAboutGuard, &QAction::triggered, this, &FormMain::showAbout); connect(m_ui->m_actionAboutGuard, &QAction::triggered, this, &FormMain::showAbout);
connect(m_ui->m_actionCheckForUpdates, &QAction::triggered, this, &FormMain::showUpdates); connect(m_ui->m_actionCheckForUpdates, &QAction::triggered, this, &FormMain::showUpdates);
connect(m_ui->m_actionReportBug, &QAction::triggered, this, &FormMain::reportABug); connect(m_ui->m_actionReportBug, &QAction::triggered, this, &FormMain::reportABug);
connect(m_ui->m_actionDonate, &QAction::triggered, this, &FormMain::donate); connect(m_ui->m_actionDonate, &QAction::triggered, this, &FormMain::donate);
connect(m_ui->m_actionDisplayWiki, &QAction::triggered, this, &FormMain::showWiki); connect(m_ui->m_actionDisplayWiki, &QAction::triggered, this, &FormMain::showWiki);
// Tab widget connections. // Tab widget connections.
connect(m_ui->m_actionTabsCloseAllExceptCurrent, &QAction::triggered, m_ui->m_tabWidget, &TabWidget::closeAllTabsExceptCurrent); connect(m_ui->m_actionTabsCloseAllExceptCurrent, &QAction::triggered, m_ui->m_tabWidget, &TabWidget::closeAllTabsExceptCurrent);
connect(m_ui->m_actionTabsCloseAll, &QAction::triggered, m_ui->m_tabWidget, &TabWidget::closeAllTabs); connect(m_ui->m_actionTabsCloseAll, &QAction::triggered, m_ui->m_tabWidget, &TabWidget::closeAllTabs);
connect(m_ui->m_actionTabNewWebBrowser, &QAction::triggered, m_ui->m_tabWidget, &TabWidget::addEmptyBrowser); connect(m_ui->m_actionTabNewWebBrowser, &QAction::triggered, m_ui->m_tabWidget, &TabWidget::addEmptyBrowser);
connect(tabWidget()->feedMessageViewer()->feedsView(), &FeedsView::itemSelected, this, &FormMain::updateFeedButtonsAvailability); connect(tabWidget()->feedMessageViewer()->feedsView(), &FeedsView::itemSelected, this, &FormMain::updateFeedButtonsAvailability);
connect(qApp->feedUpdateLock(), &Mutex::locked, this, &FormMain::updateFeedButtonsAvailability); connect(qApp->feedUpdateLock(), &Mutex::locked, this, &FormMain::updateFeedButtonsAvailability);
connect(qApp->feedUpdateLock(), &Mutex::unlocked, this, &FormMain::updateFeedButtonsAvailability); connect(qApp->feedUpdateLock(), &Mutex::unlocked, this, &FormMain::updateFeedButtonsAvailability);
connect(tabWidget()->feedMessageViewer()->messagesView(), &MessagesView::currentMessageRemoved, connect(tabWidget()->feedMessageViewer()->messagesView(), &MessagesView::currentMessageRemoved,
this, &FormMain::updateMessageButtonsAvailability); this, &FormMain::updateMessageButtonsAvailability);
connect(tabWidget()->feedMessageViewer()->messagesView(), &MessagesView::currentMessageChanged, connect(tabWidget()->feedMessageViewer()->messagesView(), &MessagesView::currentMessageChanged,
this, &FormMain::updateMessageButtonsAvailability); this, &FormMain::updateMessageButtonsAvailability);
connect(qApp->feedReader(), &FeedReader::feedUpdatesStarted, this, &FormMain::onFeedUpdatesStarted); connect(qApp->feedReader(), &FeedReader::feedUpdatesStarted, this, &FormMain::onFeedUpdatesStarted);
connect(qApp->feedReader(), &FeedReader::feedUpdatesProgress, this, &FormMain::onFeedUpdatesProgress); connect(qApp->feedReader(), &FeedReader::feedUpdatesProgress, this, &FormMain::onFeedUpdatesProgress);
connect(qApp->feedReader(), &FeedReader::feedUpdatesFinished, this, &FormMain::onFeedUpdatesFinished); connect(qApp->feedReader(), &FeedReader::feedUpdatesFinished, this, &FormMain::onFeedUpdatesFinished);
// Toolbar forwardings. // Toolbar forwardings.
connect(m_ui->m_actionAddFeedIntoSelectedAccount, &QAction::triggered, connect(m_ui->m_actionAddFeedIntoSelectedAccount, &QAction::triggered,
tabWidget()->feedMessageViewer()->feedsView(), &FeedsView::addFeedIntoSelectedAccount); tabWidget()->feedMessageViewer()->feedsView(), &FeedsView::addFeedIntoSelectedAccount);
@ -747,7 +702,7 @@ void FormMain::restoreDatabaseSettings() {
} }
} }
void FormMain::changeEvent(QEvent *event) { void FormMain::changeEvent(QEvent* event) {
switch (event->type()) { switch (event->type()) {
case QEvent::WindowStateChange: { case QEvent::WindowStateChange: {
if (windowState() & Qt::WindowMinimized && if (windowState() & Qt::WindowMinimized &&

View File

@ -38,17 +38,17 @@ class FormMain : public QMainWindow {
public: public:
// Constructors and destructors. // Constructors and destructors.
explicit FormMain(QWidget *parent = 0, Qt::WindowFlags f = 0); explicit FormMain(QWidget* parent = 0, Qt::WindowFlags f = 0);
virtual ~FormMain(); virtual ~FormMain();
// Returns menu for the tray icon. // Returns menu for the tray icon.
QMenu *trayMenu() const; QMenu* trayMenu() const;
// Returns global tab widget. // Returns global tab widget.
TabWidget *tabWidget() const; TabWidget* tabWidget() const;
// Access to statusbar. // Access to statusbar.
StatusBar *statusBar() const; StatusBar* statusBar() const;
// Returns list of all globally available actions. // Returns list of all globally available actions.
// NOTE: This is used for setting dynamic shortcuts // NOTE: This is used for setting dynamic shortcuts
@ -60,7 +60,7 @@ class FormMain : public QMainWindow {
void saveSize(); void saveSize();
#if defined(USE_WEBENGINE) #if defined(USE_WEBENGINE)
AdBlockIcon *adblockIcon() const { AdBlockIcon* adblockIcon() const {
return m_adblockIcon; return m_adblockIcon;
} }
#endif #endif
@ -84,8 +84,8 @@ class FormMain : public QMainWindow {
void updateFeedButtonsAvailability(); void updateFeedButtonsAvailability();
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);
// Displays various dialogs. // Displays various dialogs.
void backupDatabaseSettings(); void backupDatabaseSettings();
@ -101,7 +101,7 @@ class FormMain : public QMainWindow {
private: private:
// Event handler reimplementations. // Event handler reimplementations.
void changeEvent(QEvent *event); void changeEvent(QEvent* event);
// Creates all needed menus and sets them up. // Creates all needed menus and sets them up.
void prepareMenus(); void prepareMenus();
@ -113,13 +113,13 @@ class FormMain : public QMainWindow {
void setupIcons(); void setupIcons();
#if defined(USE_WEBENGINE) #if defined(USE_WEBENGINE)
AdBlockIcon *m_adblockIcon; AdBlockIcon* m_adblockIcon;
QAction *m_adblockIconAction; QAction* m_adblockIconAction;
#endif #endif
QScopedPointer<Ui::FormMain> m_ui; QScopedPointer<Ui::FormMain> m_ui;
QMenu *m_trayMenu; QMenu* m_trayMenu;
StatusBar *m_statusBar; StatusBar* m_statusBar;
}; };
#endif // FORMMAIN_H #endif // FORMMAIN_H

View File

@ -25,17 +25,14 @@
#include "QFileDialog" #include "QFileDialog"
FormRestoreDatabaseSettings::FormRestoreDatabaseSettings(QWidget *parent) FormRestoreDatabaseSettings::FormRestoreDatabaseSettings(QWidget* parent)
: QDialog(parent), m_ui(new Ui::FormRestoreDatabaseSettings), m_shouldRestart(false) { : QDialog(parent), m_ui(new Ui::FormRestoreDatabaseSettings), m_shouldRestart(false) {
m_ui->setupUi(this); m_ui->setupUi(this);
m_btnRestart = m_ui->m_buttonBox->addButton(tr("Restart"), QDialogButtonBox::ActionRole); m_btnRestart = m_ui->m_buttonBox->addButton(tr("Restart"), QDialogButtonBox::ActionRole);
m_ui->m_lblResult->setStatus(WidgetWithStatus::Warning, tr("No operation executed yet."), tr("No operation executed yet.")); m_ui->m_lblResult->setStatus(WidgetWithStatus::Warning, tr("No operation executed yet."), tr("No operation executed yet."));
setWindowIcon(qApp->icons()->fromTheme(QSL("document-import"))); setWindowIcon(qApp->icons()->fromTheme(QSL("document-import")));
setWindowFlags(Qt::MSWindowsFixedSizeDialogHint | Qt::Dialog | Qt::WindowSystemMenuHint); setWindowFlags(Qt::MSWindowsFixedSizeDialogHint | Qt::Dialog | Qt::WindowSystemMenuHint);
connect(m_btnRestart, &QPushButton::clicked, this, [ = ]() {
connect(m_btnRestart, &QPushButton::clicked, this, [=]() {
m_shouldRestart = true; m_shouldRestart = true;
close(); close();
}); });
@ -43,7 +40,6 @@ FormRestoreDatabaseSettings::FormRestoreDatabaseSettings(QWidget *parent)
connect(m_ui->m_groupDatabase, SIGNAL(toggled(bool)), this, SLOT(checkOkButton())); connect(m_ui->m_groupDatabase, SIGNAL(toggled(bool)), this, SLOT(checkOkButton()));
connect(m_ui->m_groupSettings, SIGNAL(toggled(bool)), this, SLOT(checkOkButton())); connect(m_ui->m_groupSettings, SIGNAL(toggled(bool)), this, SLOT(checkOkButton()));
connect(m_ui->m_buttonBox->button(QDialogButtonBox::Ok), SIGNAL(clicked()), this, SLOT(performRestoration())); connect(m_ui->m_buttonBox->button(QDialogButtonBox::Ok), SIGNAL(clicked()), this, SLOT(performRestoration()));
selectFolder(qApp->getDocumentsFolderPath()); selectFolder(qApp->getDocumentsFolderPath());
} }
@ -67,7 +63,8 @@ void FormRestoreDatabaseSettings::performRestoration() {
m_ui->m_lblResult->setStatus(WidgetWithStatus::Ok, tr("Restoration was initiated. Restart to proceed."), m_ui->m_lblResult->setStatus(WidgetWithStatus::Ok, tr("Restoration was initiated. Restart to proceed."),
tr("You need to restart application for restoration process to finish.")); tr("You need to restart application for restoration process to finish."));
} }
catch (const ApplicationException &ex) {
catch (const ApplicationException& ex) {
m_ui->m_lblResult->setStatus(WidgetWithStatus::Error, ex.message(), m_ui->m_lblResult->setStatus(WidgetWithStatus::Error, ex.message(),
tr("Database and/or settings were not copied to restoration directory successully.")); tr("Database and/or settings were not copied to restoration directory successully."));
} }
@ -95,33 +92,33 @@ void FormRestoreDatabaseSettings::selectFolder(QString folder) {
m_ui->m_lblSelectFolder->setStatus(WidgetWithStatus::Ok, QDir::toNativeSeparators(folder), m_ui->m_lblSelectFolder->setStatus(WidgetWithStatus::Ok, QDir::toNativeSeparators(folder),
tr("Good source directory is specified.")); tr("Good source directory is specified."));
} }
else { else {
return; return;
} }
const QDir selected_folder(folder); const QDir selected_folder(folder);
const QFileInfoList available_databases = selected_folder.entryInfoList(QStringList() const QFileInfoList available_databases = selected_folder.entryInfoList(QStringList()
<< QString("*") + BACKUP_SUFFIX_DATABASE , << QString("*") + BACKUP_SUFFIX_DATABASE,
QDir::Files | QDir::NoDotAndDotDot | QDir::Readable | QDir::Files | QDir::NoDotAndDotDot | QDir::Readable |
QDir::CaseSensitive | QDir::NoSymLinks, QDir::CaseSensitive | QDir::NoSymLinks,
QDir::Name); QDir::Name);
const QFileInfoList available_settings = selected_folder.entryInfoList(QStringList() const QFileInfoList available_settings = selected_folder.entryInfoList(QStringList()
<< QString("*") + BACKUP_SUFFIX_SETTINGS , << QString("*") + BACKUP_SUFFIX_SETTINGS,
QDir::Files | QDir::NoDotAndDotDot | QDir::Readable | QDir::Files | QDir::NoDotAndDotDot | QDir::Readable |
QDir::CaseSensitive | QDir::NoSymLinks, QDir::CaseSensitive | QDir::NoSymLinks,
QDir::Name); QDir::Name);
m_ui->m_listDatabase->clear(); m_ui->m_listDatabase->clear();
m_ui->m_listSettings->clear(); m_ui->m_listSettings->clear();
foreach (const QFileInfo &database_file, available_databases) { foreach (const QFileInfo& database_file, available_databases) {
QListWidgetItem *database_item = new QListWidgetItem(database_file.fileName(), m_ui->m_listDatabase); QListWidgetItem* database_item = new QListWidgetItem(database_file.fileName(), m_ui->m_listDatabase);
database_item->setData(Qt::UserRole, database_file.absoluteFilePath()); database_item->setData(Qt::UserRole, database_file.absoluteFilePath());
database_item->setToolTip(QDir::toNativeSeparators(database_file.absoluteFilePath())); database_item->setToolTip(QDir::toNativeSeparators(database_file.absoluteFilePath()));
} }
foreach (const QFileInfo &settings_file, available_settings) { foreach (const QFileInfo& settings_file, available_settings) {
QListWidgetItem *settings_item = new QListWidgetItem(settings_file.fileName(), m_ui->m_listSettings); QListWidgetItem* settings_item = new QListWidgetItem(settings_file.fileName(), m_ui->m_listSettings);
settings_item->setData(Qt::UserRole, settings_file.absoluteFilePath()); settings_item->setData(Qt::UserRole, settings_file.absoluteFilePath());
settings_item->setToolTip(QDir::toNativeSeparators(settings_file.absoluteFilePath())); settings_item->setToolTip(QDir::toNativeSeparators(settings_file.absoluteFilePath()));
} }

View File

@ -28,7 +28,7 @@ class FormRestoreDatabaseSettings : public QDialog {
public: public:
// Constructors and destructors. // Constructors and destructors.
explicit FormRestoreDatabaseSettings(QWidget *parent = 0); explicit FormRestoreDatabaseSettings(QWidget* parent = 0);
virtual ~FormRestoreDatabaseSettings(); virtual ~FormRestoreDatabaseSettings();
bool shouldRestart() const { bool shouldRestart() const {
@ -43,7 +43,7 @@ class FormRestoreDatabaseSettings : public QDialog {
private: private:
QScopedPointer<Ui::FormRestoreDatabaseSettings> m_ui; QScopedPointer<Ui::FormRestoreDatabaseSettings> m_ui;
QPushButton *m_btnRestart; QPushButton* m_btnRestart;
bool m_shouldRestart; bool m_shouldRestart;
}; };

View File

@ -33,21 +33,17 @@
#include "gui/settings/settingsshortcuts.h" #include "gui/settings/settingsshortcuts.h"
FormSettings::FormSettings(QWidget *parent) : QDialog(parent), m_panels(QList<SettingsPanel*>()), m_ui(new Ui::FormSettings), m_settings(qApp->settings()) { FormSettings::FormSettings(QWidget* parent) : QDialog(parent), m_panels(QList<SettingsPanel*>()), m_ui(new Ui::FormSettings), m_settings(qApp->settings()) {
m_ui->setupUi(this); m_ui->setupUi(this);
// Set flags and attributes. // Set flags and attributes.
setWindowFlags(Qt::MSWindowsFixedSizeDialogHint | Qt::Dialog | Qt::WindowSystemMenuHint | Qt::WindowTitleHint); setWindowFlags(Qt::MSWindowsFixedSizeDialogHint | Qt::Dialog | Qt::WindowSystemMenuHint | Qt::WindowTitleHint);
setWindowIcon(qApp->icons()->fromTheme(QSL("emblem-system"))); setWindowIcon(qApp->icons()->fromTheme(QSL("emblem-system")));
m_btnApply = m_ui->m_buttonBox->button(QDialogButtonBox::Apply); m_btnApply = m_ui->m_buttonBox->button(QDialogButtonBox::Apply);
m_btnApply->setEnabled(false); m_btnApply->setEnabled(false);
// Establish needed connections. // Establish needed connections.
connect(m_ui->m_buttonBox, &QDialogButtonBox::accepted, this, &FormSettings::saveSettings); connect(m_ui->m_buttonBox, &QDialogButtonBox::accepted, this, &FormSettings::saveSettings);
connect(m_ui->m_buttonBox, &QDialogButtonBox::rejected, this, &FormSettings::cancelSettings); connect(m_ui->m_buttonBox, &QDialogButtonBox::rejected, this, &FormSettings::cancelSettings);
connect(m_btnApply, &QPushButton::clicked, this, &FormSettings::applySettings); connect(m_btnApply, &QPushButton::clicked, this, &FormSettings::applySettings);
addSettingsPanel(new SettingsGeneral(m_settings, this)); addSettingsPanel(new SettingsGeneral(m_settings, this));
addSettingsPanel(new SettingsDatabase(m_settings, this)); addSettingsPanel(new SettingsDatabase(m_settings, this));
addSettingsPanel(new SettingsGui(m_settings, this)); addSettingsPanel(new SettingsGui(m_settings, this));
@ -56,7 +52,6 @@ FormSettings::FormSettings(QWidget *parent) : QDialog(parent), m_panels(QList<Se
addSettingsPanel(new SettingsBrowserMail(m_settings, this)); addSettingsPanel(new SettingsBrowserMail(m_settings, this));
addSettingsPanel(new SettingsDownloads(m_settings, this)); addSettingsPanel(new SettingsDownloads(m_settings, this));
addSettingsPanel(new SettingsFeedsMessages(m_settings, this)); addSettingsPanel(new SettingsFeedsMessages(m_settings, this));
m_ui->m_listSettings->setCurrentRow(0); m_ui->m_listSettings->setCurrentRow(0);
} }
@ -72,10 +67,9 @@ void FormSettings::saveSettings() {
void FormSettings::applySettings() { void FormSettings::applySettings() {
// Save all settings. // Save all settings.
m_settings->checkSettings(); m_settings->checkSettings();
QStringList panels_for_restart; QStringList panels_for_restart;
foreach (SettingsPanel *panel, m_panels) { foreach (SettingsPanel* panel, m_panels) {
if (panel->isDirty()) { if (panel->isDirty()) {
panel->saveSettings(); panel->saveSettings();
} }
@ -88,7 +82,6 @@ void FormSettings::applySettings() {
if (!panels_for_restart.isEmpty()) { if (!panels_for_restart.isEmpty()) {
const QStringList changed_settings_description = panels_for_restart.replaceInStrings(QRegExp(QSL("^")), QString::fromUtf8("")); const QStringList changed_settings_description = panels_for_restart.replaceInStrings(QRegExp(QSL("^")), QString::fromUtf8(""));
const QMessageBox::StandardButton clicked_button = MessageBox::show(this, const QMessageBox::StandardButton clicked_button = MessageBox::show(this,
QMessageBox::Question, QMessageBox::Question,
tr("Critical settings were changed"), tr("Critical settings were changed"),
@ -109,7 +102,7 @@ void FormSettings::applySettings() {
void FormSettings::cancelSettings() { void FormSettings::cancelSettings() {
QStringList changed_panels; QStringList changed_panels;
foreach (SettingsPanel *panel, m_panels) { foreach (SettingsPanel* panel, m_panels) {
if (panel->isDirty()) { if (panel->isDirty()) {
changed_panels.append(panel->title().toLower()); changed_panels.append(panel->title().toLower());
} }
@ -118,6 +111,7 @@ void FormSettings::cancelSettings() {
if (changed_panels.isEmpty()) { if (changed_panels.isEmpty()) {
reject(); reject();
} }
else { else {
const QStringList changed_settings_description = changed_panels.replaceInStrings(QRegExp(QSL("^")), QString::fromUtf8("")); const QStringList changed_settings_description = changed_panels.replaceInStrings(QRegExp(QSL("^")), QString::fromUtf8(""));
@ -134,12 +128,11 @@ void FormSettings::cancelSettings() {
} }
} }
void FormSettings::addSettingsPanel(SettingsPanel *panel) { void FormSettings::addSettingsPanel(SettingsPanel* panel) {
m_ui->m_listSettings->addItem(panel->title()); m_ui->m_listSettings->addItem(panel->title());
m_panels.append(panel); m_panels.append(panel);
m_ui->m_stackedSettings->addWidget(panel); m_ui->m_stackedSettings->addWidget(panel);
panel->loadSettings(); panel->loadSettings();
connect(panel, &SettingsPanel::settingsChanged, [this]() { connect(panel, &SettingsPanel::settingsChanged, [this]() {
m_btnApply->setEnabled(true); m_btnApply->setEnabled(true);
}); });

View File

@ -31,7 +31,7 @@ class FormSettings : public QDialog {
public: public:
// Constructors and destructors. // Constructors and destructors.
explicit FormSettings(QWidget *parent = 0); explicit FormSettings(QWidget* parent = 0);
virtual ~FormSettings(); virtual ~FormSettings();
private slots: private slots:
@ -41,12 +41,12 @@ class FormSettings : public QDialog {
void cancelSettings(); void cancelSettings();
private: private:
void addSettingsPanel(SettingsPanel *panel); void addSettingsPanel(SettingsPanel* panel);
QList<SettingsPanel*> m_panels; QList<SettingsPanel*> m_panels;
QScopedPointer<Ui::FormSettings> m_ui; QScopedPointer<Ui::FormSettings> m_ui;
QPushButton *m_btnApply; QPushButton* m_btnApply;
Settings *m_settings; Settings* m_settings;
}; };
#endif // FORMSETTINGS_H #endif // FORMSETTINGS_H

View File

@ -33,12 +33,11 @@
#endif #endif
FormUpdate::FormUpdate(QWidget *parent) FormUpdate::FormUpdate(QWidget* parent)
: QDialog(parent), m_downloader(nullptr), m_readyToInstall(false), m_ui(new Ui::FormUpdate), m_lastDownloadedBytes(0) { : QDialog(parent), m_downloader(nullptr), m_readyToInstall(false), m_ui(new Ui::FormUpdate), m_lastDownloadedBytes(0) {
m_ui->setupUi(this); m_ui->setupUi(this);
m_ui->m_lblCurrentRelease->setText(APP_VERSION); m_ui->m_lblCurrentRelease->setText(APP_VERSION);
m_ui->m_tabInfo->removeTab(1); m_ui->m_tabInfo->removeTab(1);
// Set flags and attributes. // Set flags and attributes.
setWindowFlags(Qt::MSWindowsFixedSizeDialogHint | Qt::Dialog | Qt::WindowSystemMenuHint | Qt::WindowTitleHint); setWindowFlags(Qt::MSWindowsFixedSizeDialogHint | Qt::Dialog | Qt::WindowSystemMenuHint | Qt::WindowTitleHint);
setWindowIcon(qApp->icons()->fromTheme(QSL("help-about"))); setWindowIcon(qApp->icons()->fromTheme(QSL("help-about")));
@ -47,6 +46,7 @@ FormUpdate::FormUpdate(QWidget *parent)
m_btnUpdate = m_ui->m_buttonBox->addButton(tr("Download selected update"), QDialogButtonBox::ActionRole); m_btnUpdate = m_ui->m_buttonBox->addButton(tr("Download selected update"), QDialogButtonBox::ActionRole);
m_btnUpdate->setToolTip(tr("Download new installation files.")); m_btnUpdate->setToolTip(tr("Download new installation files."));
} }
else { else {
m_btnUpdate = m_ui->m_buttonBox->addButton(tr("Go to application website"), QDialogButtonBox::ActionRole); m_btnUpdate = m_ui->m_buttonBox->addButton(tr("Go to application website"), QDialogButtonBox::ActionRole);
m_btnUpdate->setToolTip(tr("Go to application website to get update packages manually.")); m_btnUpdate->setToolTip(tr("Go to application website to get update packages manually."));
@ -74,7 +74,6 @@ void FormUpdate::checkForUpdates() {
if (update.second != QNetworkReply::NoError) { if (update.second != QNetworkReply::NoError) {
m_updateInfo = UpdateInfo(); m_updateInfo = UpdateInfo();
m_ui->m_tabInfo->setEnabled(false); m_ui->m_tabInfo->setEnabled(false);
//: Unknown release. //: Unknown release.
m_ui->m_lblAvailableRelease->setText(tr("unknown")); m_ui->m_lblAvailableRelease->setText(tr("unknown"));
m_ui->m_txtChanges->clear(); m_ui->m_txtChanges->clear();
@ -82,9 +81,9 @@ void FormUpdate::checkForUpdates() {
tr("Error: '%1'.").arg(NetworkFactory::networkErrorText(update.second)), tr("Error: '%1'.").arg(NetworkFactory::networkErrorText(update.second)),
tr("List with updates was not\ndownloaded successfully.")); tr("List with updates was not\ndownloaded successfully."));
} }
else { else {
const bool self_update_supported = isSelfUpdateSupported(); const bool self_update_supported = isSelfUpdateSupported();
m_updateInfo = update.first.at(0); m_updateInfo = update.first.at(0);
m_ui->m_tabInfo->setEnabled(true); m_ui->m_tabInfo->setEnabled(true);
m_ui->m_lblAvailableRelease->setText(m_updateInfo.m_availableVersion); m_ui->m_lblAvailableRelease->setText(m_updateInfo.m_availableVersion);
@ -100,6 +99,7 @@ void FormUpdate::checkForUpdates() {
loadAvailableFiles(); loadAvailableFiles();
} }
} }
else { else {
m_ui->m_lblStatus->setStatus(WidgetWithStatus::Warning, m_ui->m_lblStatus->setStatus(WidgetWithStatus::Warning,
tr("No new release available."), tr("No new release available."),
@ -119,12 +119,11 @@ void FormUpdate::updateProgress(qint64 bytes_received, qint64 bytes_total) {
2)), 2)),
tr("Downloading update...")); tr("Downloading update..."));
m_ui->m_lblStatus->repaint(); m_ui->m_lblStatus->repaint();
m_lastDownloadedBytes = bytes_received; m_lastDownloadedBytes = bytes_received;
} }
} }
void FormUpdate::saveUpdateFile(const QByteArray &file_contents) { void FormUpdate::saveUpdateFile(const QByteArray& file_contents) {
const QString url_file = m_ui->m_listFiles->currentItem()->data(Qt::UserRole).toString(); const QString url_file = m_ui->m_listFiles->currentItem()->data(Qt::UserRole).toString();
const QString temp_directory = qApp->getTempFolderPath(); const QString temp_directory = qApp->getTempFolderPath();
@ -135,21 +134,20 @@ void FormUpdate::saveUpdateFile(const QByteArray &file_contents) {
if (output_file.open(QIODevice::WriteOnly | QIODevice::Truncate)) { if (output_file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
qDebug("Storing update file to temporary location '%s'.", qDebug("Storing update file to temporary location '%s'.",
qPrintable(QDir::toNativeSeparators(output_file.fileName()))); qPrintable(QDir::toNativeSeparators(output_file.fileName())));
output_file.write(file_contents); output_file.write(file_contents);
output_file.flush(); output_file.flush();
output_file.close(); output_file.close();
qDebug("Update file contents was successfuly saved."); qDebug("Update file contents was successfuly saved.");
m_updateFilePath = output_file.fileName(); m_updateFilePath = output_file.fileName();
m_readyToInstall = true; m_readyToInstall = true;
} }
else { else {
qDebug("Cannot save downloaded update file because target temporary file '%s' cannot be " qDebug("Cannot save downloaded update file because target temporary file '%s' cannot be "
"opened for writing.", qPrintable(output_file_name)); "opened for writing.", qPrintable(output_file_name));
} }
} }
else { else {
qDebug("Cannot save downloaded update file because no TEMP directory is available."); qDebug("Cannot save downloaded update file because no TEMP directory is available.");
} }
@ -158,8 +156,8 @@ void FormUpdate::saveUpdateFile(const QByteArray &file_contents) {
void FormUpdate::loadAvailableFiles() { void FormUpdate::loadAvailableFiles() {
m_ui->m_listFiles->clear(); m_ui->m_listFiles->clear();
foreach (const UpdateUrl &url, m_updateInfo.m_urls) { foreach (const UpdateUrl& url, m_updateInfo.m_urls) {
QListWidgetItem *item = new QListWidgetItem(url.m_name + tr(" (size ") + url.m_size + QSL(")")); QListWidgetItem* item = new QListWidgetItem(url.m_name + tr(" (size ") + url.m_size + QSL(")"));
item->setData(Qt::UserRole, url.m_fileUrl); item->setData(Qt::UserRole, url.m_fileUrl);
item->setToolTip(url.m_fileUrl); item->setToolTip(url.m_fileUrl);
m_ui->m_listFiles->addItem(item); m_ui->m_listFiles->addItem(item);
@ -168,6 +166,7 @@ void FormUpdate::loadAvailableFiles() {
if (m_ui->m_listFiles->count() > 0) { if (m_ui->m_listFiles->count() > 0) {
m_ui->m_listFiles->setCurrentRow(0); m_ui->m_listFiles->setCurrentRow(0);
} }
else { else {
m_btnUpdate->setEnabled(false); m_btnUpdate->setEnabled(false);
} }
@ -202,6 +201,7 @@ void FormUpdate::startUpdate() {
url_file = m_ui->m_listFiles->currentItem()->data(Qt::UserRole).toString(); url_file = m_ui->m_listFiles->currentItem()->data(Qt::UserRole).toString();
m_ui->m_listFiles->setEnabled(false); m_ui->m_listFiles->setEnabled(false);
} }
else { else {
url_file = APP_URL; url_file = APP_URL;
} }
@ -209,7 +209,6 @@ void FormUpdate::startUpdate() {
if (m_readyToInstall) { if (m_readyToInstall) {
close(); close();
qDebug("Preparing to launch external installer '%s'.", qPrintable(QDir::toNativeSeparators(m_updateFilePath))); qDebug("Preparing to launch external installer '%s'.", qPrintable(QDir::toNativeSeparators(m_updateFilePath)));
#if defined(Q_OS_WIN) #if defined(Q_OS_WIN)
HINSTANCE exec_result = ShellExecute(nullptr, HINSTANCE exec_result = ShellExecute(nullptr,
nullptr, nullptr,
@ -220,24 +219,24 @@ void FormUpdate::startUpdate() {
if (((int)exec_result) <= 32) { if (((int)exec_result) <= 32) {
qDebug("External updater was not launched due to error."); qDebug("External updater was not launched due to error.");
qApp->showGuiMessage(tr("Cannot update application"), qApp->showGuiMessage(tr("Cannot update application"),
tr("Cannot launch external updater. Update application manually."), tr("Cannot launch external updater. Update application manually."),
QSystemTrayIcon::Warning, this); QSystemTrayIcon::Warning, this);
} }
else { else {
qApp->quit(); qApp->quit();
} }
#endif #endif
} }
else if (update_for_this_system) { else if (update_for_this_system) {
// Nothing is downloaded yet, but update for this system // Nothing is downloaded yet, but update for this system
// is available and self-update feature is present. // is available and self-update feature is present.
if (m_downloader == nullptr) { if (m_downloader == nullptr) {
// Initialie downloader. // Initialie downloader.
m_downloader = new Downloader(this); m_downloader = new Downloader(this);
connect(m_downloader, &Downloader::progress, this, &FormUpdate::updateProgress); connect(m_downloader, &Downloader::progress, this, &FormUpdate::updateProgress);
connect(m_downloader, &Downloader::completed, this, &FormUpdate::updateCompleted); connect(m_downloader, &Downloader::completed, this, &FormUpdate::updateCompleted);
updateProgress(0, 100); updateProgress(0, 100);
@ -247,6 +246,7 @@ void FormUpdate::startUpdate() {
m_btnUpdate->setEnabled(false); m_btnUpdate->setEnabled(false);
m_downloader->downloadFile(url_file); m_downloader->downloadFile(url_file);
} }
else { else {
// Self-update and package are not available. // Self-update and package are not available.
if (!WebFactory::instance()->openUrlInExternalBrowser(url_file)) { if (!WebFactory::instance()->openUrlInExternalBrowser(url_file)) {

View File

@ -35,7 +35,7 @@ class FormUpdate : public QDialog {
public: public:
// Constructors and destructors. // Constructors and destructors.
explicit FormUpdate(QWidget *parent = 0); explicit FormUpdate(QWidget* parent = 0);
virtual ~FormUpdate(); virtual ~FormUpdate();
// Returns true if application can self-update // Returns true if application can self-update
@ -49,17 +49,17 @@ class FormUpdate : public QDialog {
void updateProgress(qint64 bytes_received, qint64 bytes_total); void updateProgress(qint64 bytes_received, qint64 bytes_total);
void updateCompleted(QNetworkReply::NetworkError status, QByteArray contents); void updateCompleted(QNetworkReply::NetworkError status, QByteArray contents);
void saveUpdateFile(const QByteArray &file_contents); void saveUpdateFile(const QByteArray& file_contents);
private: private:
void loadAvailableFiles(); void loadAvailableFiles();
Downloader *m_downloader; Downloader* m_downloader;
bool m_readyToInstall; bool m_readyToInstall;
QString m_updateFilePath; QString m_updateFilePath;
QScopedPointer<Ui::FormUpdate> m_ui; QScopedPointer<Ui::FormUpdate> m_ui;
UpdateInfo m_updateInfo; UpdateInfo m_updateInfo;
QPushButton *m_btnUpdate; QPushButton* m_btnUpdate;
qint64 m_lastDownloadedBytes; qint64 m_lastDownloadedBytes;
}; };

View File

@ -30,7 +30,7 @@
#include <QVariant> #include <QVariant>
DiscoverFeedsButton::DiscoverFeedsButton(QWidget *parent) : QToolButton(parent), m_addresses(QStringList()) { DiscoverFeedsButton::DiscoverFeedsButton(QWidget* parent) : QToolButton(parent), m_addresses(QStringList()) {
setEnabled(false); setEnabled(false);
setIcon(qApp->icons()->fromTheme(QSL("application-rss+xml"))); setIcon(qApp->icons()->fromTheme(QSL("application-rss+xml")));
setPopupMode(QToolButton::InstantPopup); setPopupMode(QToolButton::InstantPopup);
@ -43,7 +43,7 @@ void DiscoverFeedsButton::clearFeedAddresses() {
setFeedAddresses(QStringList()); setFeedAddresses(QStringList());
} }
void DiscoverFeedsButton::setFeedAddresses(const QStringList &addresses) { void DiscoverFeedsButton::setFeedAddresses(const QStringList& addresses) {
setEnabled(!addresses.isEmpty()); setEnabled(!addresses.isEmpty());
setToolTip(addresses.isEmpty() ? setToolTip(addresses.isEmpty() ?
tr("This website does not contain any feeds.") : tr("This website does not contain any feeds.") :
@ -60,13 +60,14 @@ void DiscoverFeedsButton::setFeedAddresses(const QStringList &addresses) {
m_addresses = addresses; m_addresses = addresses;
} }
void DiscoverFeedsButton::linkTriggered(QAction *action) { void DiscoverFeedsButton::linkTriggered(QAction* action) {
const QString url = action->property("url").toString(); const QString url = action->property("url").toString();
ServiceRoot *root = static_cast<ServiceRoot*>(action->property("root").value<void*>()); ServiceRoot* root = static_cast<ServiceRoot*>(action->property("root").value<void*>());
if (root->supportsFeedAdding()) { if (root->supportsFeedAdding()) {
root->addNewFeed(url); root->addNewFeed(url);
} }
else { else {
qApp->showGuiMessage(tr("Not supported"), qApp->showGuiMessage(tr("Not supported"),
tr("Given account does not support adding feeds."), tr("Given account does not support adding feeds."),
@ -78,13 +79,12 @@ void DiscoverFeedsButton::linkTriggered(QAction *action) {
void DiscoverFeedsButton::fillMenu() { void DiscoverFeedsButton::fillMenu() {
menu()->clear(); menu()->clear();
foreach (const ServiceRoot *root, qApp->feedReader()->feedsModel()->serviceRoots()) { foreach (const ServiceRoot* root, qApp->feedReader()->feedsModel()->serviceRoots()) {
QMenu *root_menu = menu()->addMenu(root->icon(), root->title()); QMenu* root_menu = menu()->addMenu(root->icon(), root->title());
foreach (const QString &url, m_addresses) { foreach (const QString& url, m_addresses) {
if (root->supportsFeedAdding()) { if (root->supportsFeedAdding()) {
QAction *url_action = root_menu->addAction(root->icon(), url); QAction* url_action = root_menu->addAction(root->icon(), url);
url_action->setProperty("url", url); url_action->setProperty("url", url);
url_action->setProperty("root", QVariant::fromValue((void*) root)); url_action->setProperty("root", QVariant::fromValue((void*) root));
} }

View File

@ -26,16 +26,16 @@ class DiscoverFeedsButton : public QToolButton {
public: public:
// Constructors. // Constructors.
explicit DiscoverFeedsButton(QWidget *parent = 0); explicit DiscoverFeedsButton(QWidget* parent = 0);
virtual ~DiscoverFeedsButton(); virtual ~DiscoverFeedsButton();
// Feed addresses manipulators. // Feed addresses manipulators.
void clearFeedAddresses(); void clearFeedAddresses();
void setFeedAddresses(const QStringList &addresses); void setFeedAddresses(const QStringList& addresses);
private slots: private slots:
// User chose any of addresses. // User chose any of addresses.
void linkTriggered(QAction *action); void linkTriggered(QAction* action);
void fillMenu(); void fillMenu();
private: private:

View File

@ -20,14 +20,15 @@
#include <QKeyEvent> #include <QKeyEvent>
EditTableView::EditTableView(QWidget *parent) : QTableView(parent) { EditTableView::EditTableView(QWidget* parent) : QTableView(parent) {
} }
void EditTableView::keyPressEvent(QKeyEvent *event) { void EditTableView::keyPressEvent(QKeyEvent* event) {
if (model() && event->key() == Qt::Key_Delete) { if (model() && event->key() == Qt::Key_Delete) {
removeSelected(); removeSelected();
event->accept(); event->accept();
} }
else { else {
QAbstractItemView::keyPressEvent(event); QAbstractItemView::keyPressEvent(event);
} }

View File

@ -25,14 +25,14 @@ class EditTableView : public QTableView {
Q_OBJECT Q_OBJECT
public: public:
explicit EditTableView(QWidget *parent = 0); explicit EditTableView(QWidget* parent = 0);
public slots: public slots:
void removeSelected(); void removeSelected();
void removeAll(); void removeAll();
private: private:
void keyPressEvent(QKeyEvent *event); void keyPressEvent(QKeyEvent* event);
}; };
#endif // EDITTABLEVIEW_H #endif // EDITTABLEVIEW_H

View File

@ -63,7 +63,7 @@
#include <QPointer> #include <QPointer>
FeedMessageViewer::FeedMessageViewer(QWidget *parent) FeedMessageViewer::FeedMessageViewer(QWidget* parent)
: TabContent(parent), : TabContent(parent),
m_toolBarsEnabled(true), m_toolBarsEnabled(true),
m_listHeadersEnabled(true), m_listHeadersEnabled(true),
@ -87,50 +87,44 @@ FeedMessageViewer::~FeedMessageViewer() {
} }
#if defined(USE_WEBENGINE) #if defined(USE_WEBENGINE)
WebBrowser *FeedMessageViewer::webBrowser() const { WebBrowser* FeedMessageViewer::webBrowser() const {
return m_messagesBrowser; return m_messagesBrowser;
} }
#endif #endif
FeedsView *FeedMessageViewer::feedsView() const { FeedsView* FeedMessageViewer::feedsView() const {
return m_feedsView; return m_feedsView;
} }
MessagesView *FeedMessageViewer::messagesView() const { MessagesView* FeedMessageViewer::messagesView() const {
return m_messagesView; return m_messagesView;
} }
MessagesToolBar *FeedMessageViewer::messagesToolBar() const { MessagesToolBar* FeedMessageViewer::messagesToolBar() const {
return m_toolBarMessages; return m_toolBarMessages;
} }
FeedsToolBar *FeedMessageViewer::feedsToolBar() const { FeedsToolBar* FeedMessageViewer::feedsToolBar() const {
return m_toolBarFeeds; return m_toolBarFeeds;
} }
void FeedMessageViewer::saveSize() { void FeedMessageViewer::saveSize() {
Settings *settings = qApp->settings(); Settings* settings = qApp->settings();
m_feedsView->saveAllExpandStates(); m_feedsView->saveAllExpandStates();
// Store offsets of splitters. // Store offsets of splitters.
settings->setValue(GROUP(GUI), GUI::SplitterFeeds, QString(m_feedSplitter->saveState().toBase64())); settings->setValue(GROUP(GUI), GUI::SplitterFeeds, QString(m_feedSplitter->saveState().toBase64()));
settings->setValue(GROUP(GUI), GUI::SplitterMessages, QString(m_messageSplitter->saveState().toBase64())); settings->setValue(GROUP(GUI), GUI::SplitterMessages, QString(m_messageSplitter->saveState().toBase64()));
settings->setValue(GROUP(GUI), GUI::MessageViewState, QString(m_messagesView->header()->saveState().toBase64())); settings->setValue(GROUP(GUI), GUI::MessageViewState, QString(m_messagesView->header()->saveState().toBase64()));
// Store "visibility" of toolbars and list headers. // Store "visibility" of toolbars and list headers.
settings->setValue(GROUP(GUI), GUI::ToolbarsVisible, m_toolBarsEnabled); settings->setValue(GROUP(GUI), GUI::ToolbarsVisible, m_toolBarsEnabled);
settings->setValue(GROUP(GUI), GUI::ListHeadersVisible, m_listHeadersEnabled); settings->setValue(GROUP(GUI), GUI::ListHeadersVisible, m_listHeadersEnabled);
} }
void FeedMessageViewer::loadSize() { void FeedMessageViewer::loadSize() {
const Settings *settings = qApp->settings(); const Settings* settings = qApp->settings();
// Restore offsets of splitters. // Restore offsets of splitters.
m_feedSplitter->restoreState(QByteArray::fromBase64(settings->value(GROUP(GUI), SETTING(GUI::SplitterFeeds)).toString().toLocal8Bit())); m_feedSplitter->restoreState(QByteArray::fromBase64(settings->value(GROUP(GUI), SETTING(GUI::SplitterFeeds)).toString().toLocal8Bit()));
m_messageSplitter->restoreState(QByteArray::fromBase64(settings->value(GROUP(GUI), SETTING(GUI::SplitterMessages)).toString().toLocal8Bit())); m_messageSplitter->restoreState(QByteArray::fromBase64(settings->value(GROUP(GUI), SETTING(GUI::SplitterMessages)).toString().toLocal8Bit()));
m_messagesView->header()->restoreState(QByteArray::fromBase64(settings->value(GROUP(GUI), SETTING(GUI::MessageViewState)).toString().toLocal8Bit())); m_messagesView->header()->restoreState(QByteArray::fromBase64(settings->value(GROUP(GUI), SETTING(GUI::MessageViewState)).toString().toLocal8Bit()));
} }
@ -150,6 +144,7 @@ void FeedMessageViewer::switchMessageSplitterOrientation() {
if (m_messageSplitter->orientation() == Qt::Vertical) { if (m_messageSplitter->orientation() == Qt::Vertical) {
m_messageSplitter->setOrientation(Qt::Horizontal); m_messageSplitter->setOrientation(Qt::Horizontal);
} }
else { else {
m_messageSplitter->setOrientation(Qt::Vertical); m_messageSplitter->setOrientation(Qt::Vertical);
} }
@ -168,22 +163,24 @@ void FeedMessageViewer::setListHeadersEnabled(bool enable) {
} }
void FeedMessageViewer::switchFeedComponentVisibility() { void FeedMessageViewer::switchFeedComponentVisibility() {
QAction *sen = qobject_cast<QAction*>(sender()); QAction* sen = qobject_cast<QAction*>(sender());
if (sen != nullptr) { if (sen != nullptr) {
m_feedsWidget->setVisible(sen->isChecked()); m_feedsWidget->setVisible(sen->isChecked());
} }
else { else {
m_feedsWidget->setVisible(!m_feedsWidget->isVisible()); m_feedsWidget->setVisible(!m_feedsWidget->isVisible());
} }
} }
void FeedMessageViewer::toggleShowOnlyUnreadFeeds() { void FeedMessageViewer::toggleShowOnlyUnreadFeeds() {
const QAction *origin = qobject_cast<QAction*>(sender()); const QAction* origin = qobject_cast<QAction*>(sender());
if (origin == nullptr) { if (origin == nullptr) {
m_feedsView->model()->invalidateReadFeedsFilter(true, false); m_feedsView->model()->invalidateReadFeedsFilter(true, false);
} }
else { else {
m_feedsView->model()->invalidateReadFeedsFilter(true, origin->isChecked()); m_feedsView->model()->invalidateReadFeedsFilter(true, origin->isChecked());
} }
@ -193,7 +190,6 @@ void FeedMessageViewer::createConnections() {
// Filtering & searching. // Filtering & searching.
connect(m_toolBarMessages, &MessagesToolBar::messageSearchPatternChanged, m_messagesView, &MessagesView::searchMessages); connect(m_toolBarMessages, &MessagesToolBar::messageSearchPatternChanged, m_messagesView, &MessagesView::searchMessages);
connect(m_toolBarMessages, &MessagesToolBar::messageFilterChanged, m_messagesView, &MessagesView::filterMessages); connect(m_toolBarMessages, &MessagesToolBar::messageFilterChanged, m_messagesView, &MessagesView::filterMessages);
#if defined(USE_WEBENGINE) #if defined(USE_WEBENGINE)
connect(m_messagesView, &MessagesView::currentMessageRemoved, m_messagesBrowser, &WebBrowser::clear); connect(m_messagesView, &MessagesView::currentMessageRemoved, m_messagesBrowser, &WebBrowser::clear);
connect(m_messagesView, &MessagesView::currentMessageChanged, m_messagesBrowser, &WebBrowser::loadMessage); connect(m_messagesView, &MessagesView::currentMessageChanged, m_messagesBrowser, &WebBrowser::loadMessage);
@ -209,10 +205,8 @@ void FeedMessageViewer::createConnections() {
connect(m_messagesBrowser, &MessagePreviewer::markMessageImportant, connect(m_messagesBrowser, &MessagePreviewer::markMessageImportant,
m_messagesView->sourceModel(), &MessagesModel::setMessageImportantById); m_messagesView->sourceModel(), &MessagesModel::setMessageImportantById);
#endif #endif
// If user selects feeds, load their messages. // If user selects feeds, load their messages.
connect(m_feedsView, &FeedsView::itemSelected, m_messagesView, &MessagesView::loadItem); connect(m_feedsView, &FeedsView::itemSelected, m_messagesView, &MessagesView::loadItem);
// State of many messages is changed, then we need // State of many messages is changed, then we need
// to reload selections. // to reload selections.
connect(m_feedsView->sourceModel(), &FeedsModel::reloadMessageListRequested, connect(m_feedsView->sourceModel(), &FeedsModel::reloadMessageListRequested,
@ -224,16 +218,12 @@ void FeedMessageViewer::initialize() {
m_toolBarFeeds->setFloatable(false); m_toolBarFeeds->setFloatable(false);
m_toolBarFeeds->setMovable(false); m_toolBarFeeds->setMovable(false);
m_toolBarFeeds->setAllowedAreas(Qt::TopToolBarArea); m_toolBarFeeds->setAllowedAreas(Qt::TopToolBarArea);
m_toolBarMessages->setFloatable(false); m_toolBarMessages->setFloatable(false);
m_toolBarMessages->setMovable(false); m_toolBarMessages->setMovable(false);
m_toolBarMessages->setAllowedAreas(Qt::TopToolBarArea); m_toolBarMessages->setAllowedAreas(Qt::TopToolBarArea);
m_toolBarFeeds->loadSavedActions(); m_toolBarFeeds->loadSavedActions();
m_toolBarMessages->loadSavedActions(); m_toolBarMessages->loadSavedActions();
m_messagesBrowser->clear(); m_messagesBrowser->clear();
// Now refresh visual setup. // Now refresh visual setup.
refreshVisualProperties(); refreshVisualProperties();
} }
@ -243,12 +233,10 @@ void FeedMessageViewer::initializeViews() {
m_messagesWidget = new QWidget(this); m_messagesWidget = new QWidget(this);
m_feedSplitter = new QSplitter(Qt::Horizontal, this); m_feedSplitter = new QSplitter(Qt::Horizontal, this);
m_messageSplitter = new QSplitter(Qt::Vertical, this); m_messageSplitter = new QSplitter(Qt::Vertical, this);
// Instantiate needed components. // Instantiate needed components.
QVBoxLayout *central_layout = new QVBoxLayout(this); QVBoxLayout* central_layout = new QVBoxLayout(this);
QVBoxLayout *feed_layout = new QVBoxLayout(m_feedsWidget); QVBoxLayout* feed_layout = new QVBoxLayout(m_feedsWidget);
QVBoxLayout *message_layout = new QVBoxLayout(m_messagesWidget); QVBoxLayout* message_layout = new QVBoxLayout(m_messagesWidget);
// Set layout properties. // Set layout properties.
central_layout->setMargin(0); central_layout->setMargin(0);
central_layout->setSpacing(0); central_layout->setSpacing(0);
@ -256,11 +244,9 @@ void FeedMessageViewer::initializeViews() {
feed_layout->setSpacing(0); feed_layout->setSpacing(0);
message_layout->setMargin(0); message_layout->setMargin(0);
message_layout->setSpacing(0); message_layout->setSpacing(0);
// Set views. // Set views.
m_feedsView->setFrameStyle(QFrame::NoFrame); m_feedsView->setFrameStyle(QFrame::NoFrame);
m_messagesView->setFrameStyle(QFrame::NoFrame); m_messagesView->setFrameStyle(QFrame::NoFrame);
// Setup message splitter. // Setup message splitter.
m_messageSplitter->setObjectName(QSL("MessageSplitter")); m_messageSplitter->setObjectName(QSL("MessageSplitter"));
m_messageSplitter->setHandleWidth(1); m_messageSplitter->setHandleWidth(1);
@ -268,25 +254,20 @@ void FeedMessageViewer::initializeViews() {
m_messageSplitter->setChildrenCollapsible(false); m_messageSplitter->setChildrenCollapsible(false);
m_messageSplitter->addWidget(m_messagesView); m_messageSplitter->addWidget(m_messagesView);
m_messageSplitter->addWidget(m_messagesBrowser); m_messageSplitter->addWidget(m_messagesBrowser);
// Assemble message-related components to single widget. // Assemble message-related components to single widget.
message_layout->addWidget(m_toolBarMessages); message_layout->addWidget(m_toolBarMessages);
message_layout->addWidget(m_messageSplitter); message_layout->addWidget(m_messageSplitter);
// Assemble feed-related components to another widget. // Assemble feed-related components to another widget.
feed_layout->addWidget(m_toolBarFeeds); feed_layout->addWidget(m_toolBarFeeds);
feed_layout->addWidget(m_feedsView); feed_layout->addWidget(m_feedsView);
// Assembler everything together. // Assembler everything together.
m_feedSplitter->setHandleWidth(1); m_feedSplitter->setHandleWidth(1);
m_feedSplitter->setOpaqueResize(false); m_feedSplitter->setOpaqueResize(false);
m_feedSplitter->setChildrenCollapsible(false); m_feedSplitter->setChildrenCollapsible(false);
m_feedSplitter->addWidget(m_feedsWidget); m_feedSplitter->addWidget(m_feedsWidget);
m_feedSplitter->addWidget(m_messagesWidget); m_feedSplitter->addWidget(m_messagesWidget);
// Add toolbar and main feeds/messages widget to main layout. // Add toolbar and main feeds/messages widget to main layout.
central_layout->addWidget(m_feedSplitter); central_layout->addWidget(m_feedSplitter);
setTabOrder(m_feedsView, m_messagesView); setTabOrder(m_feedsView, m_messagesView);
setTabOrder(m_messagesView, m_toolBarFeeds); setTabOrder(m_messagesView, m_toolBarFeeds);
setTabOrder(m_toolBarFeeds, m_toolBarMessages); setTabOrder(m_toolBarFeeds, m_toolBarMessages);
@ -296,7 +277,6 @@ void FeedMessageViewer::initializeViews() {
void FeedMessageViewer::refreshVisualProperties() { void FeedMessageViewer::refreshVisualProperties() {
const Qt::ToolButtonStyle button_style = static_cast<Qt::ToolButtonStyle>(qApp->settings()->value(GROUP(GUI), const Qt::ToolButtonStyle button_style = static_cast<Qt::ToolButtonStyle>(qApp->settings()->value(GROUP(GUI),
SETTING(GUI::ToolbarStyle)).toInt()); SETTING(GUI::ToolbarStyle)).toInt());
m_toolBarFeeds->setToolButtonStyle(button_style); m_toolBarFeeds->setToolButtonStyle(button_style);
m_toolBarMessages->setToolButtonStyle(button_style); m_toolBarMessages->setToolButtonStyle(button_style);
} }

View File

@ -45,17 +45,17 @@ class FeedMessageViewer : public TabContent {
public: public:
// Constructors and destructors. // Constructors and destructors.
explicit FeedMessageViewer(QWidget *parent = 0); explicit FeedMessageViewer(QWidget* parent = 0);
virtual ~FeedMessageViewer(); virtual ~FeedMessageViewer();
#if defined(USE_WEBENGINE) #if defined(USE_WEBENGINE)
WebBrowser *webBrowser() const; WebBrowser* webBrowser() const;
#endif #endif
FeedsView *feedsView() const; FeedsView* feedsView() const;
MessagesView *messagesView() const; MessagesView* messagesView() const;
MessagesToolBar *messagesToolBar() const; MessagesToolBar* messagesToolBar() const;
FeedsToolBar *feedsToolBar() const; FeedsToolBar* feedsToolBar() const;
bool areToolBarsEnabled() const; bool areToolBarsEnabled() const;
bool areListHeadersEnabled() const; bool areListHeadersEnabled() const;
@ -99,21 +99,21 @@ class FeedMessageViewer : public TabContent {
private: private:
bool m_toolBarsEnabled; bool m_toolBarsEnabled;
bool m_listHeadersEnabled; bool m_listHeadersEnabled;
FeedsToolBar *m_toolBarFeeds; FeedsToolBar* m_toolBarFeeds;
MessagesToolBar *m_toolBarMessages; MessagesToolBar* m_toolBarMessages;
QSplitter *m_feedSplitter; QSplitter* m_feedSplitter;
QSplitter *m_messageSplitter; QSplitter* m_messageSplitter;
MessagesView *m_messagesView; MessagesView* m_messagesView;
FeedsView *m_feedsView; FeedsView* m_feedsView;
QWidget *m_feedsWidget; QWidget* m_feedsWidget;
QWidget *m_messagesWidget; QWidget* m_messagesWidget;
#if defined(USE_WEBENGINE) #if defined(USE_WEBENGINE)
WebBrowser *m_messagesBrowser; WebBrowser* m_messagesBrowser;
#else #else
MessagePreviewer *m_messagesBrowser; MessagePreviewer* m_messagesBrowser;
#endif #endif
}; };

View File

@ -24,7 +24,7 @@
#include <QWidgetAction> #include <QWidgetAction>
FeedsToolBar::FeedsToolBar(const QString &title, QWidget *parent) : BaseToolBar(title, parent) { FeedsToolBar::FeedsToolBar(const QString& title, QWidget* parent) : BaseToolBar(title, parent) {
// Update right margin of filter textbox. // Update right margin of filter textbox.
QMargins margins = contentsMargins(); QMargins margins = contentsMargins();
margins.setRight(margins.right() + FILTER_RIGHT_MARGIN); margins.setRight(margins.right() + FILTER_RIGHT_MARGIN);
@ -42,42 +42,40 @@ QList<QAction*> FeedsToolBar::changeableActions() const {
return actions(); return actions();
} }
void FeedsToolBar::saveChangeableActions(const QStringList &actions) { void FeedsToolBar::saveChangeableActions(const QStringList& actions) {
qApp->settings()->setValue(GROUP(GUI), GUI::FeedsToolbarActions, actions.join(QSL(","))); qApp->settings()->setValue(GROUP(GUI), GUI::FeedsToolbarActions, actions.join(QSL(",")));
loadSpecificActions(getSpecificActions(actions)); loadSpecificActions(getSpecificActions(actions));
} }
QList<QAction*> FeedsToolBar::getSpecificActions(const QStringList &actions) { QList<QAction*> FeedsToolBar::getSpecificActions(const QStringList& actions) {
QList<QAction*> available_actions = availableActions(); QList<QAction*> available_actions = availableActions();
QList<QAction*> spec_actions; QList<QAction*> spec_actions;
// Iterate action names and add respectable actions into the toolbar. // Iterate action names and add respectable actions into the toolbar.
foreach (const QString &action_name, actions) { foreach (const QString& action_name, actions) {
QAction *matching_action = findMatchingAction(action_name, available_actions); QAction* matching_action = findMatchingAction(action_name, available_actions);
if (matching_action != nullptr) { if (matching_action != nullptr) {
// Add existing standard action. // Add existing standard action.
spec_actions.append(matching_action); spec_actions.append(matching_action);
} }
else if (action_name == SEPARATOR_ACTION_NAME) { else if (action_name == SEPARATOR_ACTION_NAME) {
// Add new separator. // Add new separator.
QAction *act = new QAction(this); QAction* act = new QAction(this);
act->setSeparator(true); act->setSeparator(true);
spec_actions.append(act); spec_actions.append(act);
} }
else if (action_name == SPACER_ACTION_NAME) { else if (action_name == SPACER_ACTION_NAME) {
// Add new spacer. // Add new spacer.
QWidget *spacer = new QWidget(this); QWidget* spacer = new QWidget(this);
spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
QWidgetAction* action = new QWidgetAction(this);
QWidgetAction *action = new QWidgetAction(this);
action->setDefaultWidget(spacer); action->setDefaultWidget(spacer);
action->setIcon(qApp->icons()->fromTheme(QSL("system-search"))); action->setIcon(qApp->icons()->fromTheme(QSL("system-search")));
action->setProperty("type", SPACER_ACTION_NAME); action->setProperty("type", SPACER_ACTION_NAME);
action->setProperty("name", tr("Toolbar spacer")); action->setProperty("name", tr("Toolbar spacer"));
spec_actions.append(action); spec_actions.append(action);
} }
} }
@ -85,10 +83,10 @@ QList<QAction*> FeedsToolBar::getSpecificActions(const QStringList &actions) {
return spec_actions; return spec_actions;
} }
void FeedsToolBar::loadSpecificActions(const QList<QAction*> &actions) { void FeedsToolBar::loadSpecificActions(const QList<QAction*>& actions) {
clear(); clear();
foreach (QAction *act, actions) { foreach (QAction* act, actions) {
addAction(act); addAction(act);
} }
} }
@ -101,5 +99,4 @@ QStringList FeedsToolBar::defaultActions() const {
QStringList FeedsToolBar::savedActions() const { QStringList FeedsToolBar::savedActions() const {
return qApp->settings()->value(GROUP(GUI), SETTING(GUI::FeedsToolbarActions)).toString().split(',', return qApp->settings()->value(GROUP(GUI), SETTING(GUI::FeedsToolbarActions)).toString().split(',',
QString::SkipEmptyParts); QString::SkipEmptyParts);
} }

View File

@ -26,15 +26,15 @@ class FeedsToolBar : public BaseToolBar {
public: public:
// Constructors and destructors. // Constructors and destructors.
explicit FeedsToolBar(const QString &title, QWidget *parent = 0); explicit FeedsToolBar(const QString& title, QWidget* parent = 0);
virtual ~FeedsToolBar(); virtual ~FeedsToolBar();
QList<QAction*> availableActions() const; QList<QAction*> availableActions() const;
QList<QAction*> changeableActions() const; QList<QAction*> changeableActions() const;
void saveChangeableActions(const QStringList &actions); void saveChangeableActions(const QStringList& actions);
QList<QAction*> getSpecificActions(const QStringList &actions); QList<QAction*> getSpecificActions(const QStringList& actions);
void loadSpecificActions(const QList<QAction*> &actions); void loadSpecificActions(const QList<QAction*>& actions);
QStringList defaultActions() const; QStringList defaultActions() const;
QStringList savedActions() const; QStringList savedActions() const;

View File

@ -42,25 +42,22 @@
#include <QTimer> #include <QTimer>
FeedsView::FeedsView(QWidget *parent) FeedsView::FeedsView(QWidget* parent)
: QTreeView(parent), : QTreeView(parent),
m_contextMenuCategories(nullptr), m_contextMenuCategories(nullptr),
m_contextMenuFeeds(nullptr), m_contextMenuFeeds(nullptr),
m_contextMenuEmptySpace(nullptr), m_contextMenuEmptySpace(nullptr),
m_contextMenuOtherItems(nullptr) { m_contextMenuOtherItems(nullptr) {
setObjectName(QSL("FeedsView")); setObjectName(QSL("FeedsView"));
// Allocate models. // Allocate models.
m_sourceModel = qApp->feedReader()->feedsModel(); m_sourceModel = qApp->feedReader()->feedsModel();
m_proxyModel = qApp->feedReader()->feedsProxyModel(); m_proxyModel = qApp->feedReader()->feedsProxyModel();
// Connections. // Connections.
connect(m_sourceModel, &FeedsModel::requireItemValidationAfterDragDrop, this, &FeedsView::validateItemAfterDragDrop); connect(m_sourceModel, &FeedsModel::requireItemValidationAfterDragDrop, this, &FeedsView::validateItemAfterDragDrop);
connect(m_sourceModel, &FeedsModel::itemExpandRequested, this, &FeedsView::onItemExpandRequested); connect(m_sourceModel, &FeedsModel::itemExpandRequested, this, &FeedsView::onItemExpandRequested);
connect(m_sourceModel, &FeedsModel::itemExpandStateSaveRequested, this, &FeedsView::onItemExpandStateSaveRequested); connect(m_sourceModel, &FeedsModel::itemExpandStateSaveRequested, this, &FeedsView::onItemExpandStateSaveRequested);
connect(header(), &QHeaderView::sortIndicatorChanged, this, &FeedsView::saveSortState); connect(header(), &QHeaderView::sortIndicatorChanged, this, &FeedsView::saveSortState);
connect(m_proxyModel, &FeedsProxyModel::expandAfterFilterIn, this, &FeedsView::expandItemDelayed); connect(m_proxyModel, &FeedsProxyModel::expandAfterFilterIn, this, &FeedsView::expandItemDelayed);
setModel(m_proxyModel); setModel(m_proxyModel);
setupAppearance(); setupAppearance();
} }
@ -81,24 +78,26 @@ QList<Feed*> FeedsView::selectedFeeds() const {
if (current_index.isValid()) { if (current_index.isValid()) {
return m_sourceModel->feedsForIndex(m_proxyModel->mapToSource(current_index)); return m_sourceModel->feedsForIndex(m_proxyModel->mapToSource(current_index));
} }
else { else {
return QList<Feed*>(); return QList<Feed*>();
} }
} }
RootItem *FeedsView::selectedItem() const { RootItem* FeedsView::selectedItem() const {
const QModelIndexList selected_rows = selectionModel()->selectedRows(); const QModelIndexList selected_rows = selectionModel()->selectedRows();
if (selected_rows.isEmpty()) { if (selected_rows.isEmpty()) {
return nullptr; return nullptr;
} }
else { else {
RootItem *selected_item = m_sourceModel->itemForIndex(m_proxyModel->mapToSource(selected_rows.at(0))); RootItem* selected_item = m_sourceModel->itemForIndex(m_proxyModel->mapToSource(selected_rows.at(0)));
return selected_item == m_sourceModel->rootItem() ? nullptr : selected_item; return selected_item == m_sourceModel->rootItem() ? nullptr : selected_item;
} }
} }
void FeedsView::onItemExpandStateSaveRequested(RootItem *item) { void FeedsView::onItemExpandStateSaveRequested(RootItem* item) {
saveExpandStates(item); saveExpandStates(item);
} }
@ -106,17 +105,15 @@ void FeedsView::saveAllExpandStates() {
saveExpandStates(sourceModel()->rootItem()); saveExpandStates(sourceModel()->rootItem());
} }
void FeedsView::saveExpandStates(RootItem *item) { void FeedsView::saveExpandStates(RootItem* item) {
Settings *settings = qApp->settings(); Settings* settings = qApp->settings();
QList<RootItem*> items = item->getSubTree(RootItemKind::Category | RootItemKind::ServiceRoot); QList<RootItem*> items = item->getSubTree(RootItemKind::Category | RootItemKind::ServiceRoot);
// Iterate all categories and save their expand statuses. // Iterate all categories and save their expand statuses.
foreach (const RootItem *item, items) { foreach (const RootItem* item, items) {
const QString setting_name = item->hashCode(); const QString setting_name = item->hashCode();
QModelIndex source_index = sourceModel()->indexForItem(item); QModelIndex source_index = sourceModel()->indexForItem(item);
QModelIndex visible_index = model()->mapFromSource(source_index); QModelIndex visible_index = model()->mapFromSource(source_index);
settings->setValue(GROUP(CategoriesExpandStates), settings->setValue(GROUP(CategoriesExpandStates),
setting_name, setting_name,
isExpanded(visible_index)); isExpanded(visible_index));
@ -124,15 +121,13 @@ void FeedsView::saveExpandStates(RootItem *item) {
} }
void FeedsView::loadAllExpandStates() { void FeedsView::loadAllExpandStates() {
const Settings *settings = qApp->settings(); const Settings* settings = qApp->settings();
QList<RootItem*> expandable_items; QList<RootItem*> expandable_items;
expandable_items.append(sourceModel()->rootItem()->getSubTree(RootItemKind::Category | RootItemKind::ServiceRoot)); expandable_items.append(sourceModel()->rootItem()->getSubTree(RootItemKind::Category | RootItemKind::ServiceRoot));
// Iterate all categories and save their expand statuses. // Iterate all categories and save their expand statuses.
foreach (const RootItem *item, expandable_items) { foreach (const RootItem* item, expandable_items) {
const QString setting_name = item->hashCode(); const QString setting_name = item->hashCode();
setExpanded(model()->mapFromSource(sourceModel()->indexForItem(item)), setExpanded(model()->mapFromSource(sourceModel()->indexForItem(item)),
settings->value(GROUP(CategoriesExpandStates), setting_name, item->childCount() > 0).toBool()); settings->value(GROUP(CategoriesExpandStates), setting_name, item->childCount() > 0).toBool());
} }
@ -148,20 +143,22 @@ void FeedsView::sortByColumn(int column, Qt::SortOrder order) {
if (column == old_column && order == old_order) { if (column == old_column && order == old_order) {
m_proxyModel->sort(column, order); m_proxyModel->sort(column, order);
} }
else { else {
QTreeView::sortByColumn(column, order); QTreeView::sortByColumn(column, order);
} }
} }
void FeedsView::addFeedIntoSelectedAccount() { void FeedsView::addFeedIntoSelectedAccount() {
const RootItem *selected = selectedItem(); const RootItem* selected = selectedItem();
if (selected != nullptr) { if (selected != nullptr) {
ServiceRoot *root = selected->getParentServiceRoot(); ServiceRoot* root = selected->getParentServiceRoot();
if (root->supportsFeedAdding()) { if (root->supportsFeedAdding()) {
root->addNewFeed(); root->addNewFeed();
} }
else { else {
qApp->showGuiMessage(tr("Not supported"), qApp->showGuiMessage(tr("Not supported"),
tr("Selected account does not support adding of new feeds."), tr("Selected account does not support adding of new feeds."),
@ -172,14 +169,15 @@ void FeedsView::addFeedIntoSelectedAccount() {
} }
void FeedsView::addCategoryIntoSelectedAccount() { void FeedsView::addCategoryIntoSelectedAccount() {
const RootItem *selected = selectedItem(); const RootItem* selected = selectedItem();
if (selected != nullptr) { if (selected != nullptr) {
ServiceRoot *root = selected->getParentServiceRoot(); ServiceRoot* root = selected->getParentServiceRoot();
if (root->supportsCategoryAdding()) { if (root->supportsCategoryAdding()) {
root->addNewCategory(); root->addNewCategory();
} }
else { else {
qApp->showGuiMessage(tr("Not supported"), qApp->showGuiMessage(tr("Not supported"),
tr("Selected account does not support adding of new categories."), tr("Selected account does not support adding of new categories."),
@ -229,6 +227,7 @@ void FeedsView::editSelectedItem() {
if (selectedItem()->canBeEdited()) { if (selectedItem()->canBeEdited()) {
selectedItem()->editViaGui(); selectedItem()->editViaGui();
} }
else { else {
qApp->showGuiMessage(tr("Cannot edit item"), qApp->showGuiMessage(tr("Cannot edit item"),
tr("Selected item cannot be edited, this is not (yet?) supported."), tr("Selected item cannot be edited, this is not (yet?) supported."),
@ -249,7 +248,6 @@ void FeedsView::deleteSelectedItem() {
qApp->showGuiMessage(tr("Cannot delete item"), qApp->showGuiMessage(tr("Cannot delete item"),
tr("Selected item cannot be deleted because another critical operation is ongoing."), tr("Selected item cannot be deleted because another critical operation is ongoing."),
QSystemTrayIcon::Warning, qApp->mainFormWidget(), true); QSystemTrayIcon::Warning, qApp->mainFormWidget(), true);
// Thus, cannot delete and quit the method. // Thus, cannot delete and quit the method.
return; return;
} }
@ -260,7 +258,7 @@ void FeedsView::deleteSelectedItem() {
return; return;
} }
RootItem *selected_item = selectedItem(); RootItem* selected_item = selectedItem();
if (selected_item != nullptr) { if (selected_item != nullptr) {
if (selected_item->canBeDeleted()) { if (selected_item->canBeDeleted()) {
@ -285,6 +283,7 @@ void FeedsView::deleteSelectedItem() {
true); true);
} }
} }
else { else {
qApp->showGuiMessage(tr("Cannot delete \"%1\"").arg(selected_item->title()), qApp->showGuiMessage(tr("Cannot delete \"%1\"").arg(selected_item->title()),
tr("This item cannot be deleted, because it does not support it\nor this functionality is not implemented yet."), tr("This item cannot be deleted, because it does not support it\nor this functionality is not implemented yet."),
@ -319,7 +318,7 @@ void FeedsView::markAllItemsRead() {
} }
void FeedsView::openSelectedItemsInNewspaperMode() { void FeedsView::openSelectedItemsInNewspaperMode() {
RootItem *selected_item = selectedItem(); RootItem* selected_item = selectedItem();
const QList<Message> messages = m_sourceModel->messagesForItem(selected_item); const QList<Message> messages = m_sourceModel->messagesForItem(selected_item);
if (!messages.isEmpty()) { if (!messages.isEmpty()) {
@ -328,13 +327,13 @@ void FeedsView::openSelectedItemsInNewspaperMode() {
} }
void FeedsView::selectNextItem() { void FeedsView::selectNextItem() {
const QModelIndex &curr_idx = currentIndex(); const QModelIndex& curr_idx = currentIndex();
if (m_proxyModel->hasChildren(curr_idx) && !isExpanded(curr_idx)) { if (m_proxyModel->hasChildren(curr_idx) && !isExpanded(curr_idx)) {
expand(curr_idx); expand(curr_idx);
} }
const QModelIndex &index_next = moveCursor(QAbstractItemView::MoveDown, Qt::NoModifier); const QModelIndex& index_next = moveCursor(QAbstractItemView::MoveDown, Qt::NoModifier);
if (index_next.isValid()) { if (index_next.isValid()) {
setCurrentIndex(index_next); setCurrentIndex(index_next);
@ -343,13 +342,13 @@ void FeedsView::selectNextItem() {
} }
void FeedsView::selectPreviousItem() { void FeedsView::selectPreviousItem() {
const QModelIndex &curr_idx = currentIndex(); const QModelIndex& curr_idx = currentIndex();
if (m_proxyModel->hasChildren(curr_idx) && !isExpanded(curr_idx)) { if (m_proxyModel->hasChildren(curr_idx) && !isExpanded(curr_idx)) {
expand(curr_idx); expand(curr_idx);
} }
const QModelIndex &index_previous = moveCursor(QAbstractItemView::MoveUp, Qt::NoModifier); const QModelIndex& index_previous = moveCursor(QAbstractItemView::MoveUp, Qt::NoModifier);
if (index_previous.isValid()) { if (index_previous.isValid()) {
setCurrentIndex(index_previous); setCurrentIndex(index_previous);
@ -361,23 +360,23 @@ void FeedsView::switchVisibility() {
setVisible(!isVisible()); setVisible(!isVisible());
} }
void FeedsView::expandItemDelayed(const QModelIndex &idx) { void FeedsView::expandItemDelayed(const QModelIndex& idx) {
QTimer::singleShot(100, this, [=] { QTimer::singleShot(100, this, [ = ] {
// TODO: Z nastavení. // TODO: Z nastavení.
setExpanded(m_proxyModel->mapFromSource(idx), true); setExpanded(m_proxyModel->mapFromSource(idx), true);
}); });
} }
QMenu *FeedsView::initializeContextMenuCategories(RootItem *clicked_item) { QMenu* FeedsView::initializeContextMenuCategories(RootItem* clicked_item) {
if (m_contextMenuCategories == nullptr) { if (m_contextMenuCategories == nullptr) {
m_contextMenuCategories = new QMenu(tr("Context menu for categories"), this); m_contextMenuCategories = new QMenu(tr("Context menu for categories"), this);
} }
else { else {
m_contextMenuCategories->clear(); m_contextMenuCategories->clear();
} }
QList<QAction*> specific_actions = clicked_item->contextMenu(); QList<QAction*> specific_actions = clicked_item->contextMenu();
m_contextMenuCategories->addActions(QList<QAction*>() << m_contextMenuCategories->addActions(QList<QAction*>() <<
qApp->mainForm()->m_ui->m_actionUpdateSelectedItems << qApp->mainForm()->m_ui->m_actionUpdateSelectedItems <<
qApp->mainForm()->m_ui->m_actionEditSelectedItem << qApp->mainForm()->m_ui->m_actionEditSelectedItem <<
@ -394,16 +393,16 @@ QMenu *FeedsView::initializeContextMenuCategories(RootItem *clicked_item) {
return m_contextMenuCategories; return m_contextMenuCategories;
} }
QMenu *FeedsView::initializeContextMenuFeeds(RootItem *clicked_item) { QMenu* FeedsView::initializeContextMenuFeeds(RootItem* clicked_item) {
if (m_contextMenuFeeds == nullptr) { if (m_contextMenuFeeds == nullptr) {
m_contextMenuFeeds = new QMenu(tr("Context menu for categories"), this); m_contextMenuFeeds = new QMenu(tr("Context menu for categories"), this);
} }
else { else {
m_contextMenuFeeds->clear(); m_contextMenuFeeds->clear();
} }
QList<QAction*> specific_actions = clicked_item->contextMenu(); QList<QAction*> specific_actions = clicked_item->contextMenu();
m_contextMenuFeeds->addActions(QList<QAction*>() << m_contextMenuFeeds->addActions(QList<QAction*>() <<
qApp->mainForm()->m_ui->m_actionUpdateSelectedItems << qApp->mainForm()->m_ui->m_actionUpdateSelectedItems <<
qApp->mainForm()->m_ui->m_actionEditSelectedItem << qApp->mainForm()->m_ui->m_actionEditSelectedItem <<
@ -420,7 +419,7 @@ QMenu *FeedsView::initializeContextMenuFeeds(RootItem *clicked_item) {
return m_contextMenuFeeds; return m_contextMenuFeeds;
} }
QMenu *FeedsView::initializeContextMenuEmptySpace() { QMenu* FeedsView::initializeContextMenuEmptySpace() {
if (m_contextMenuEmptySpace == nullptr) { if (m_contextMenuEmptySpace == nullptr) {
m_contextMenuEmptySpace = new QMenu(tr("Context menu for empty space"), this); m_contextMenuEmptySpace = new QMenu(tr("Context menu for empty space"), this);
m_contextMenuEmptySpace->addAction(qApp->mainForm()->m_ui->m_actionUpdateAllItems); m_contextMenuEmptySpace->addAction(qApp->mainForm()->m_ui->m_actionUpdateAllItems);
@ -430,10 +429,11 @@ QMenu *FeedsView::initializeContextMenuEmptySpace() {
return m_contextMenuEmptySpace; return m_contextMenuEmptySpace;
} }
QMenu *FeedsView::initializeContextMenuOtherItem(RootItem *clicked_item) { QMenu* FeedsView::initializeContextMenuOtherItem(RootItem* clicked_item) {
if (m_contextMenuOtherItems == nullptr) { if (m_contextMenuOtherItems == nullptr) {
m_contextMenuOtherItems = new QMenu(tr("Context menu for other items"), this); m_contextMenuOtherItems = new QMenu(tr("Context menu for other items"), this);
} }
else { else {
m_contextMenuOtherItems->clear(); m_contextMenuOtherItems->clear();
} }
@ -444,6 +444,7 @@ QMenu *FeedsView::initializeContextMenuOtherItem(RootItem *clicked_item) {
m_contextMenuOtherItems->addSeparator(); m_contextMenuOtherItems->addSeparator();
m_contextMenuOtherItems->addActions(specific_actions); m_contextMenuOtherItems->addActions(specific_actions);
} }
else { else {
m_contextMenuOtherItems->addAction(qApp->mainForm()->m_ui->m_actionNoActions); m_contextMenuOtherItems->addAction(qApp->mainForm()->m_ui->m_actionNoActions);
} }
@ -455,7 +456,6 @@ void FeedsView::setupAppearance() {
// Setup column resize strategies. // Setup column resize strategies.
header()->setSectionResizeMode(FDS_MODEL_TITLE_INDEX, QHeaderView::Stretch); header()->setSectionResizeMode(FDS_MODEL_TITLE_INDEX, QHeaderView::Stretch);
header()->setSectionResizeMode(FDS_MODEL_COUNTS_INDEX, QHeaderView::ResizeToContents); header()->setSectionResizeMode(FDS_MODEL_COUNTS_INDEX, QHeaderView::ResizeToContents);
setUniformRowHeights(true); setUniformRowHeights(true);
setAnimated(true); setAnimated(true);
setSortingEnabled(true); setSortingEnabled(true);
@ -475,16 +475,15 @@ void FeedsView::setupAppearance() {
header()->setSortIndicatorShown(false); header()->setSortIndicatorShown(false);
} }
void FeedsView::selectionChanged(const QItemSelection &selected, const QItemSelection &deselected) { void FeedsView::selectionChanged(const QItemSelection& selected, const QItemSelection& deselected) {
RootItem *selected_item = selectedItem(); RootItem* selected_item = selectedItem();
m_proxyModel->setSelectedItem(selected_item); m_proxyModel->setSelectedItem(selected_item);
QTreeView::selectionChanged(selected, deselected); QTreeView::selectionChanged(selected, deselected);
emit itemSelected(selected_item); emit itemSelected(selected_item);
m_proxyModel->invalidateReadFeedsFilter(); m_proxyModel->invalidateReadFeedsFilter();
} }
void FeedsView::keyPressEvent(QKeyEvent *event) { void FeedsView::keyPressEvent(QKeyEvent* event) {
QTreeView::keyPressEvent(event); QTreeView::keyPressEvent(event);
if (event->key() == Qt::Key_Delete) { if (event->key() == Qt::Key_Delete) {
@ -492,36 +491,39 @@ void FeedsView::keyPressEvent(QKeyEvent *event) {
} }
} }
void FeedsView::contextMenuEvent(QContextMenuEvent *event) { void FeedsView::contextMenuEvent(QContextMenuEvent* event) {
const QModelIndex clicked_index = indexAt(event->pos()); const QModelIndex clicked_index = indexAt(event->pos());
if (clicked_index.isValid()) { if (clicked_index.isValid()) {
const QModelIndex mapped_index = model()->mapToSource(clicked_index); const QModelIndex mapped_index = model()->mapToSource(clicked_index);
RootItem *clicked_item = sourceModel()->itemForIndex(mapped_index); RootItem* clicked_item = sourceModel()->itemForIndex(mapped_index);
if (clicked_item->kind() == RootItemKind::Category) { if (clicked_item->kind() == RootItemKind::Category) {
// Display context menu for categories. // Display context menu for categories.
initializeContextMenuCategories(clicked_item)->exec(event->globalPos()); initializeContextMenuCategories(clicked_item)->exec(event->globalPos());
} }
else if (clicked_item->kind() == RootItemKind::Feed) { else if (clicked_item->kind() == RootItemKind::Feed) {
// Display context menu for feeds. // Display context menu for feeds.
initializeContextMenuFeeds(clicked_item)->exec(event->globalPos()); initializeContextMenuFeeds(clicked_item)->exec(event->globalPos());
} }
else { else {
initializeContextMenuOtherItem(clicked_item)->exec(event->globalPos()); initializeContextMenuOtherItem(clicked_item)->exec(event->globalPos());
} }
} }
else { else {
// Display menu for empty space. // Display menu for empty space.
initializeContextMenuEmptySpace()->exec(event->globalPos()); initializeContextMenuEmptySpace()->exec(event->globalPos());
} }
} }
void FeedsView::mouseDoubleClickEvent(QMouseEvent *event) { void FeedsView::mouseDoubleClickEvent(QMouseEvent* event) {
QModelIndex idx = indexAt(event->pos()); QModelIndex idx = indexAt(event->pos());
if (idx.isValid()) { if (idx.isValid()) {
RootItem *item = m_sourceModel->itemForIndex(m_proxyModel->mapToSource(idx)); RootItem* item = m_sourceModel->itemForIndex(m_proxyModel->mapToSource(idx));
if (item->kind() == RootItemKind::Feed || item->kind() == RootItemKind::Bin) { if (item->kind() == RootItemKind::Feed || item->kind() == RootItemKind::Bin) {
const QList<Message> messages = m_sourceModel->messagesForItem(item); const QList<Message> messages = m_sourceModel->messagesForItem(item);
@ -540,7 +542,7 @@ void FeedsView::saveSortState(int column, Qt::SortOrder order) {
qApp->settings()->setValue(GROUP(GUI), GUI::DefaultSortOrderFeeds, order); qApp->settings()->setValue(GROUP(GUI), GUI::DefaultSortOrderFeeds, order);
} }
void FeedsView::validateItemAfterDragDrop(const QModelIndex &source_index) { void FeedsView::validateItemAfterDragDrop(const QModelIndex& source_index) {
const QModelIndex mapped = m_proxyModel->mapFromSource(source_index); const QModelIndex mapped = m_proxyModel->mapFromSource(source_index);
if (mapped.isValid()) { if (mapped.isValid()) {
@ -549,11 +551,10 @@ void FeedsView::validateItemAfterDragDrop(const QModelIndex &source_index) {
} }
} }
void FeedsView::onItemExpandRequested(const QList<RootItem*> &items, bool exp) { void FeedsView::onItemExpandRequested(const QList<RootItem*>& items, bool exp) {
foreach (const RootItem *item, items) { foreach (const RootItem* item, items) {
QModelIndex source_index = m_sourceModel->indexForItem(item); QModelIndex source_index = m_sourceModel->indexForItem(item);
QModelIndex proxy_index = m_proxyModel->mapFromSource(source_index); QModelIndex proxy_index = m_proxyModel->mapFromSource(source_index);
//setExpanded(proxy_index, !exp); //setExpanded(proxy_index, !exp);
setExpanded(proxy_index, exp); setExpanded(proxy_index, exp);
} }

View File

@ -34,15 +34,15 @@ class FeedsView : public QTreeView {
public: public:
// Constructors and destructors. // Constructors and destructors.
explicit FeedsView(QWidget *parent = 0); explicit FeedsView(QWidget* parent = 0);
virtual ~FeedsView(); virtual ~FeedsView();
// Fundamental accessors. // Fundamental accessors.
inline FeedsProxyModel *model() const { inline FeedsProxyModel* model() const {
return m_proxyModel; return m_proxyModel;
} }
inline FeedsModel *sourceModel() const { inline FeedsModel* sourceModel() const {
return m_sourceModel; return m_sourceModel;
} }
@ -54,7 +54,7 @@ class FeedsView : public QTreeView {
// Returns pointers to selected feed/category if they are really // Returns pointers to selected feed/category if they are really
// selected. // selected.
RootItem *selectedItem() const; RootItem* selectedItem() const;
// Saves/loads expand states of all nodes (feeds/categories) of the list to/from settings. // Saves/loads expand states of all nodes (feeds/categories) of the list to/from settings.
void saveAllExpandStates(); void saveAllExpandStates();
@ -95,52 +95,52 @@ class FeedsView : public QTreeView {
signals: signals:
// Emitted if user selects new feeds. // Emitted if user selects new feeds.
void itemSelected(RootItem *item); void itemSelected(RootItem* item);
// Requests opening of given messages in newspaper mode. // Requests opening of given messages in newspaper mode.
void openMessagesInNewspaperView(RootItem *root, const QList<Message> &messages); void openMessagesInNewspaperView(RootItem* root, const QList<Message>& messages);
protected: protected:
// Handle selections. // Handle selections.
void selectionChanged(const QItemSelection &selected, const QItemSelection &deselected); void selectionChanged(const QItemSelection& selected, const QItemSelection& deselected);
// React on "Del" key. // React on "Del" key.
void keyPressEvent(QKeyEvent *event); void keyPressEvent(QKeyEvent* event);
// Show custom context menu. // Show custom context menu.
void contextMenuEvent(QContextMenuEvent *event); void contextMenuEvent(QContextMenuEvent* event);
void mouseDoubleClickEvent(QMouseEvent *event); void mouseDoubleClickEvent(QMouseEvent* event);
private slots: private slots:
void expandItemDelayed(const QModelIndex &idx); void expandItemDelayed(const QModelIndex& idx);
void markSelectedItemReadStatus(RootItem::ReadStatus read); void markSelectedItemReadStatus(RootItem::ReadStatus read);
void markAllItemsReadStatus(RootItem::ReadStatus read); void markAllItemsReadStatus(RootItem::ReadStatus read);
void saveSortState(int column, Qt::SortOrder order); void saveSortState(int column, Qt::SortOrder order);
void validateItemAfterDragDrop(const QModelIndex &source_index); void validateItemAfterDragDrop(const QModelIndex& source_index);
void onItemExpandRequested(const QList<RootItem*> &items, bool exp); void onItemExpandRequested(const QList<RootItem*>& items, bool exp);
void onItemExpandStateSaveRequested(RootItem *item); void onItemExpandStateSaveRequested(RootItem* item);
private: private:
// Initializes context menus. // Initializes context menus.
QMenu *initializeContextMenuCategories(RootItem *clicked_item); QMenu* initializeContextMenuCategories(RootItem* clicked_item);
QMenu *initializeContextMenuFeeds(RootItem *clicked_item); QMenu* initializeContextMenuFeeds(RootItem* clicked_item);
QMenu *initializeContextMenuEmptySpace(); QMenu* initializeContextMenuEmptySpace();
QMenu *initializeContextMenuOtherItem(RootItem *clicked_item); QMenu* initializeContextMenuOtherItem(RootItem* clicked_item);
// Sets up appearance of this widget. // Sets up appearance of this widget.
void setupAppearance(); void setupAppearance();
void saveExpandStates(RootItem *item); void saveExpandStates(RootItem* item);
QMenu *m_contextMenuCategories; QMenu* m_contextMenuCategories;
QMenu *m_contextMenuFeeds; QMenu* m_contextMenuFeeds;
QMenu *m_contextMenuEmptySpace; QMenu* m_contextMenuEmptySpace;
QMenu *m_contextMenuOtherItems; QMenu* m_contextMenuOtherItems;
FeedsModel *m_sourceModel; FeedsModel* m_sourceModel;
FeedsProxyModel *m_proxyModel; FeedsProxyModel* m_proxyModel;
}; };
#endif // FEEDSVIEW_H #endif // FEEDSVIEW_H

View File

@ -22,12 +22,13 @@
#include <QLabel> #include <QLabel>
void GuiUtilities::setLabelAsNotice(QLabel *label, bool is_warning) { void GuiUtilities::setLabelAsNotice(QLabel* label, bool is_warning) {
label->setMargin(6); label->setMargin(6);
if (is_warning) { if (is_warning) {
label->setStyleSheet(QSL("font-weight: bold; font-style: italic; color: red")); label->setStyleSheet(QSL("font-weight: bold; font-style: italic; color: red"));
} }
else { else {
label->setStyleSheet(QSL("font-style: italic;")); label->setStyleSheet(QSL("font-style: italic;"));
} }

View File

@ -23,7 +23,7 @@ class QLabel;
class GuiUtilities { class GuiUtilities {
public: public:
static void setLabelAsNotice(QLabel *label, bool is_warning); static void setLabelAsNotice(QLabel* label, bool is_warning);
private: private:
explicit GuiUtilities(); explicit GuiUtilities();

View File

@ -22,14 +22,12 @@
#include <QHBoxLayout> #include <QHBoxLayout>
LabelWithStatus::LabelWithStatus(QWidget *parent) LabelWithStatus::LabelWithStatus(QWidget* parent)
: WidgetWithStatus(parent) { : WidgetWithStatus(parent) {
m_wdgInput = new QLabel(this); m_wdgInput = new QLabel(this);
// Set correct size for the tool button. // Set correct size for the tool button.
int label_height = m_wdgInput->sizeHint().height(); int label_height = m_wdgInput->sizeHint().height();
m_btnStatus->setFixedSize(label_height, label_height); m_btnStatus->setFixedSize(label_height, label_height);
// Compose the layout. // Compose the layout.
m_layout->addWidget(m_wdgInput); m_layout->addWidget(m_wdgInput);
m_layout->addWidget(m_btnStatus); m_layout->addWidget(m_btnStatus);
@ -39,8 +37,8 @@ LabelWithStatus::~LabelWithStatus() {
} }
void LabelWithStatus::setStatus(WidgetWithStatus::StatusType status, void LabelWithStatus::setStatus(WidgetWithStatus::StatusType status,
const QString &label_text, const QString& label_text,
const QString &status_text) { const QString& status_text) {
WidgetWithStatus::setStatus(status, status_text); WidgetWithStatus::setStatus(status, status_text);
label()->setText(label_text); label()->setText(label_text);
} }

View File

@ -28,13 +28,13 @@ class LabelWithStatus : public WidgetWithStatus {
public: public:
// Constructors and destructors. // Constructors and destructors.
explicit LabelWithStatus(QWidget *parent = 0); explicit LabelWithStatus(QWidget* parent = 0);
virtual ~LabelWithStatus(); virtual ~LabelWithStatus();
void setStatus(StatusType status, const QString &label_text, const QString &status_text); void setStatus(StatusType status, const QString& label_text, const QString& status_text);
// Access to label. // Access to label.
inline QLabel *label() const { inline QLabel* label() const {
return static_cast<QLabel*>(m_wdgInput); return static_cast<QLabel*>(m_wdgInput);
} }
}; };

View File

@ -23,16 +23,13 @@
#include <QHBoxLayout> #include <QHBoxLayout>
LineEditWithStatus::LineEditWithStatus(QWidget *parent) LineEditWithStatus::LineEditWithStatus(QWidget* parent)
: WidgetWithStatus(parent) { : WidgetWithStatus(parent) {
m_wdgInput = new BaseLineEdit(this); m_wdgInput = new BaseLineEdit(this);
setFocusProxy(m_wdgInput); setFocusProxy(m_wdgInput);
// Set correct size for the tool button. // Set correct size for the tool button.
const int txt_input_height = m_wdgInput->sizeHint().height(); const int txt_input_height = m_wdgInput->sizeHint().height();
m_btnStatus->setFixedSize(txt_input_height, txt_input_height); m_btnStatus->setFixedSize(txt_input_height, txt_input_height);
// Compose the layout. // Compose the layout.
m_layout->addWidget(m_wdgInput); m_layout->addWidget(m_wdgInput);
m_layout->addWidget(m_btnStatus); m_layout->addWidget(m_btnStatus);

View File

@ -28,11 +28,11 @@ class LineEditWithStatus : public WidgetWithStatus {
public: public:
// Constructors and destructors. // Constructors and destructors.
explicit LineEditWithStatus(QWidget *parent = 0); explicit LineEditWithStatus(QWidget* parent = 0);
virtual ~LineEditWithStatus(); virtual ~LineEditWithStatus();
// Access to line edit. // Access to line edit.
inline BaseLineEdit *lineEdit() const { inline BaseLineEdit* lineEdit() const {
return static_cast<BaseLineEdit*>(m_wdgInput); return static_cast<BaseLineEdit*>(m_wdgInput);
} }
}; };

View File

@ -22,7 +22,7 @@
#include <QMouseEvent> #include <QMouseEvent>
LocationLineEdit::LocationLineEdit(QWidget *parent) LocationLineEdit::LocationLineEdit(QWidget* parent)
: BaseLineEdit(parent), m_mouseSelectsAllText(true), m_googleSuggest(new GoogleSuggest(this)) { : BaseLineEdit(parent), m_mouseSelectsAllText(true), m_googleSuggest(new GoogleSuggest(this)) {
setPlaceholderText(tr("Website address goes here")); setPlaceholderText(tr("Website address goes here"));
connect(this, &LocationLineEdit::submitted, m_googleSuggest, &GoogleSuggest::preventSuggest); connect(this, &LocationLineEdit::submitted, m_googleSuggest, &GoogleSuggest::preventSuggest);
@ -31,22 +31,21 @@ LocationLineEdit::LocationLineEdit(QWidget *parent)
LocationLineEdit::~LocationLineEdit() { LocationLineEdit::~LocationLineEdit() {
} }
void LocationLineEdit::focusOutEvent(QFocusEvent *event) { void LocationLineEdit::focusOutEvent(QFocusEvent* event) {
BaseLineEdit::focusOutEvent(event); BaseLineEdit::focusOutEvent(event);
// User now left text box, when he enters it again and clicks, // User now left text box, when he enters it again and clicks,
// then all text should be selected. // then all text should be selected.
m_mouseSelectsAllText = true; m_mouseSelectsAllText = true;
} }
void LocationLineEdit::mousePressEvent(QMouseEvent *event) { void LocationLineEdit::mousePressEvent(QMouseEvent* event) {
if (m_mouseSelectsAllText) { if (m_mouseSelectsAllText) {
event->ignore(); event->ignore();
selectAll(); selectAll();
// User clicked and all text was selected. // User clicked and all text was selected.
m_mouseSelectsAllText = false; m_mouseSelectsAllText = false;
} }
else { else {
BaseLineEdit::mousePressEvent(event); BaseLineEdit::mousePressEvent(event);
} }

View File

@ -29,16 +29,16 @@ class LocationLineEdit : public BaseLineEdit {
public: public:
// Constructors and destructors. // Constructors and destructors.
explicit LocationLineEdit(QWidget *parent = 0); explicit LocationLineEdit(QWidget* parent = 0);
virtual ~LocationLineEdit(); virtual ~LocationLineEdit();
protected: protected:
void focusOutEvent(QFocusEvent *event); void focusOutEvent(QFocusEvent* event);
void mousePressEvent(QMouseEvent *event); void mousePressEvent(QMouseEvent* event);
private: private:
bool m_mouseSelectsAllText; bool m_mouseSelectsAllText;
GoogleSuggest *m_googleSuggest; GoogleSuggest* m_googleSuggest;
}; };
#endif // LOCATIONLINEEDIT_H #endif // LOCATIONLINEEDIT_H

View File

@ -28,7 +28,7 @@
#include <QCheckBox> #include <QCheckBox>
MessageBox::MessageBox(QWidget *parent) : QMessageBox(parent) { MessageBox::MessageBox(QWidget* parent) : QMessageBox(parent) {
} }
MessageBox::~MessageBox() { MessageBox::~MessageBox() {
@ -37,21 +37,18 @@ MessageBox::~MessageBox() {
void MessageBox::setIcon(QMessageBox::Icon icon) { void MessageBox::setIcon(QMessageBox::Icon icon) {
// Determine correct status icon size. // Determine correct status icon size.
const int icon_size = qApp->style()->pixelMetric(QStyle::PM_MessageBoxIconSize, 0, this); const int icon_size = qApp->style()->pixelMetric(QStyle::PM_MessageBoxIconSize, 0, this);
// Setup status icon. // Setup status icon.
setIconPixmap(iconForStatus(icon).pixmap(icon_size, icon_size)); setIconPixmap(iconForStatus(icon).pixmap(icon_size, icon_size));
} }
void MessageBox::setCheckBox(QMessageBox *msg_box, const QString &text, bool *data) { void MessageBox::setCheckBox(QMessageBox* msg_box, const QString& text, bool* data) {
// Add "don't show this again checkbox. // Add "don't show this again checkbox.
QCheckBox *check_box = new QCheckBox(msg_box); QCheckBox* check_box = new QCheckBox(msg_box);
check_box->setChecked(*data); check_box->setChecked(*data);
check_box->setText(text); check_box->setText(text);
connect(check_box, &QCheckBox::toggled, [=](bool checked) { connect(check_box, &QCheckBox::toggled, [ = ](bool checked) {
*data = checked; *data = checked;
}); });
msg_box->setCheckBox(check_box); msg_box->setCheckBox(check_box);
} }
@ -75,18 +72,17 @@ QIcon MessageBox::iconForStatus(QMessageBox::Icon status) {
} }
} }
QMessageBox::StandardButton MessageBox::show(QWidget *parent, QMessageBox::StandardButton MessageBox::show(QWidget* parent,
QMessageBox::Icon icon, QMessageBox::Icon icon,
const QString &title, const QString& title,
const QString &text, const QString& text,
const QString &informative_text, const QString& informative_text,
const QString &detailed_text, const QString& detailed_text,
QMessageBox::StandardButtons buttons, QMessageBox::StandardButtons buttons,
QMessageBox::StandardButton default_button, QMessageBox::StandardButton default_button,
bool *dont_show_again) { bool* dont_show_again) {
// Create and find needed components. // Create and find needed components.
MessageBox msg_box(parent); MessageBox msg_box(parent);
// Initialize message box properties. // Initialize message box properties.
msg_box.setWindowTitle(title); msg_box.setWindowTitle(title);
msg_box.setText(text); msg_box.setText(text);
@ -104,6 +100,7 @@ QMessageBox::StandardButton MessageBox::show(QWidget *parent,
if (msg_box.exec() == -1) { if (msg_box.exec() == -1) {
return QMessageBox::Cancel; return QMessageBox::Cancel;
} }
else { else {
return msg_box.standardButton(msg_box.clickedButton()); return msg_box.standardButton(msg_box.clickedButton());
} }

View File

@ -27,24 +27,24 @@ class MessageBox : public QMessageBox {
public: public:
// Constructors and destructors. // Constructors and destructors.
explicit MessageBox(QWidget *parent = 0); explicit MessageBox(QWidget* parent = 0);
virtual ~MessageBox(); virtual ~MessageBox();
// Custom icon setting. // Custom icon setting.
void setIcon(Icon icon); void setIcon(Icon icon);
static void setCheckBox(QMessageBox *msg_box, const QString &text, bool *data); static void setCheckBox(QMessageBox* msg_box, const QString& text, bool* data);
// Displays custom message box. // Displays custom message box.
static QMessageBox::StandardButton show(QWidget *parent, static QMessageBox::StandardButton show(QWidget* parent,
QMessageBox::Icon icon, QMessageBox::Icon icon,
const QString &title, const QString& title,
const QString &text, const QString& text,
const QString &informative_text = QString(), const QString& informative_text = QString(),
const QString &detailed_text = QString(), const QString& detailed_text = QString(),
QMessageBox::StandardButtons buttons = QMessageBox::Ok, QMessageBox::StandardButtons buttons = QMessageBox::Ok,
QMessageBox::StandardButton default_button = QMessageBox::Ok, QMessageBox::StandardButton default_button = QMessageBox::Ok,
bool *dont_show_again = nullptr); bool* dont_show_again = nullptr);
static QIcon iconForStatus(QMessageBox::Icon status); static QIcon iconForStatus(QMessageBox::Icon status);
}; };

View File

@ -30,7 +30,7 @@
void MessagePreviewer::createConnections() { void MessagePreviewer::createConnections() {
connect(m_ui->m_txtMessage, &QTextBrowser::anchorClicked, [=](const QUrl &url) { connect(m_ui->m_txtMessage, &QTextBrowser::anchorClicked, [ = ](const QUrl & url) {
if (!url.isEmpty()) { if (!url.isEmpty()) {
bool open_externally_now = qApp->settings()->value(GROUP(Browser), bool open_externally_now = qApp->settings()->value(GROUP(Browser),
SETTING(Browser::OpenLinksInExternalBrowserRightAway)).toBool(); SETTING(Browser::OpenLinksInExternalBrowserRightAway)).toBool();
@ -38,20 +38,18 @@ void MessagePreviewer::createConnections() {
if (open_externally_now) { if (open_externally_now) {
WebFactory::instance()->openUrlInExternalBrowser(url.toString()); WebFactory::instance()->openUrlInExternalBrowser(url.toString());
} }
else { else {
// User clicked some URL. Open it in external browser or download? // User clicked some URL. Open it in external browser or download?
MessageBox box(qApp->mainForm()); MessageBox box(qApp->mainForm());
box.setText(tr("You clicked some link. You can download the link contents or open it in external web browser.")); box.setText(tr("You clicked some link. You can download the link contents or open it in external web browser."));
box.setInformativeText(tr("What action do you want to take?")); box.setInformativeText(tr("What action do you want to take?"));
box.setDetailedText(url.toString()); box.setDetailedText(url.toString());
QAbstractButton *btn_open = box.addButton(tr("Open in external browser"), QMessageBox::ActionRole); QAbstractButton* btn_open = box.addButton(tr("Open in external browser"), QMessageBox::ActionRole);
QAbstractButton *btn_download = box.addButton(tr("Download"), QMessageBox::ActionRole); QAbstractButton* btn_download = box.addButton(tr("Download"), QMessageBox::ActionRole);
QAbstractButton *btn_cancel = box.addButton(QMessageBox::Cancel); QAbstractButton* btn_cancel = box.addButton(QMessageBox::Cancel);
bool always; bool always;
MessageBox::setCheckBox(&box, tr("Always open links in external browser."), &always); MessageBox::setCheckBox(&box, tr("Always open links in external browser."), &always);
box.setDefaultButton(QMessageBox::Cancel); box.setDefaultButton(QMessageBox::Cancel);
box.exec(); box.exec();
@ -63,6 +61,7 @@ void MessagePreviewer::createConnections() {
if (box.clickedButton() == btn_open) { if (box.clickedButton() == btn_open) {
WebFactory::instance()->openUrlInExternalBrowser(url.toString()); WebFactory::instance()->openUrlInExternalBrowser(url.toString());
} }
else if (box.clickedButton() == btn_download) { else if (box.clickedButton() == btn_download) {
qApp->downloadManager()->download(url); qApp->downloadManager()->download(url);
} }
@ -72,6 +71,7 @@ void MessagePreviewer::createConnections() {
btn_cancel->deleteLater(); btn_cancel->deleteLater();
} }
} }
else { else {
MessageBox::show(qApp->mainForm(), QMessageBox::Warning, tr("Incorrect link"), MessageBox::show(qApp->mainForm(), QMessageBox::Warning, tr("Incorrect link"),
tr("Selected hyperlink is invalid.")); tr("Selected hyperlink is invalid."));
@ -91,25 +91,21 @@ void MessagePreviewer::createConnections() {
&MessagePreviewer::switchMessageImportance); &MessagePreviewer::switchMessageImportance);
connect(m_ui->m_txtMessage, connect(m_ui->m_txtMessage,
static_cast<void (QTextBrowser::*)(const QString&)>(&QTextBrowser::highlighted), static_cast<void (QTextBrowser::*)(const QString&)>(&QTextBrowser::highlighted),
[=](const QString &text) { [ = ](const QString & text) {
Q_UNUSED(text) Q_UNUSED(text)
QToolTip::showText(QCursor::pos(), tr("Click this link to download it or open it with external browser."), this); QToolTip::showText(QCursor::pos(), tr("Click this link to download it or open it with external browser."), this);
}); });
} }
MessagePreviewer::MessagePreviewer(QWidget *parent) : QWidget(parent), MessagePreviewer::MessagePreviewer(QWidget* parent) : QWidget(parent),
m_ui(new Ui::MessagePreviewer), m_pictures(QStringList()) { m_ui(new Ui::MessagePreviewer), m_pictures(QStringList()) {
m_ui->setupUi(this); m_ui->setupUi(this);
m_ui->m_txtMessage->viewport()->setAutoFillBackground(true); m_ui->m_txtMessage->viewport()->setAutoFillBackground(true);
m_toolBar = new QToolBar(this); m_toolBar = new QToolBar(this);
m_toolBar->setOrientation(Qt::Vertical); m_toolBar->setOrientation(Qt::Vertical);
m_ui->m_layout->addWidget(m_toolBar, 0, 0, -1, 1); m_ui->m_layout->addWidget(m_toolBar, 0, 0, -1, 1);
createConnections(); createConnections();
m_actionSwitchImportance->setCheckable(true); m_actionSwitchImportance->setCheckable(true);
reloadFontSettings(); reloadFontSettings();
clear(); clear();
} }
@ -118,12 +114,10 @@ MessagePreviewer::~MessagePreviewer() {
} }
void MessagePreviewer::reloadFontSettings() { void MessagePreviewer::reloadFontSettings() {
const Settings *settings = qApp->settings(); const Settings* settings = qApp->settings();
QFont fon; QFont fon;
fon.fromString(settings->value(GROUP(Messages), fon.fromString(settings->value(GROUP(Messages),
SETTING(Messages::PreviewerFontStandard)).toString()); SETTING(Messages::PreviewerFontStandard)).toString());
m_ui->m_txtMessage->setFont(fon); m_ui->m_txtMessage->setFont(fon);
} }
@ -137,17 +131,15 @@ void MessagePreviewer::hideToolbar() {
m_toolBar->setVisible(false); m_toolBar->setVisible(false);
} }
void MessagePreviewer::loadMessage(const Message &message, RootItem *root) { void MessagePreviewer::loadMessage(const Message& message, RootItem* root) {
m_message = message; m_message = message;
m_root = root; m_root = root;
if (!m_root.isNull()) { if (!m_root.isNull()) {
m_actionSwitchImportance->setChecked(m_message.m_isImportant); m_actionSwitchImportance->setChecked(m_message.m_isImportant);
m_ui->m_txtMessage->setHtml(prepareHtmlForMessage(m_message)); m_ui->m_txtMessage->setHtml(prepareHtmlForMessage(m_message));
updateButtons(); updateButtons();
show(); show();
m_ui->m_txtMessage->verticalScrollBar()->triggerAction(QScrollBar::SliderToMinimum); m_ui->m_txtMessage->verticalScrollBar()->triggerAction(QScrollBar::SliderToMinimum);
} }
} }
@ -172,7 +164,6 @@ void MessagePreviewer::markMessageAsReadUnread(RootItem::ReadStatus read) {
QList<Message>() << m_message, QList<Message>() << m_message,
read); read);
m_message.m_isRead = read == RootItem::Read; m_message.m_isRead = read == RootItem::Read;
emit markMessageRead(m_message.m_id, read); emit markMessageRead(m_message.m_id, read);
updateButtons(); updateButtons();
} }
@ -188,13 +179,11 @@ void MessagePreviewer::switchMessageImportance(bool checked) {
RootItem::Important))) { RootItem::Important))) {
DatabaseQueries::switchMessagesImportance(qApp->database()->connection(objectName(), DatabaseFactory::FromSettings), DatabaseQueries::switchMessagesImportance(qApp->database()->connection(objectName(), DatabaseFactory::FromSettings),
QStringList() << QString::number(m_message.m_id)); QStringList() << QString::number(m_message.m_id));
m_root->getParentServiceRoot()->onAfterSwitchMessageImportance(m_root.data(), m_root->getParentServiceRoot()->onAfterSwitchMessageImportance(m_root.data(),
QList<ImportanceChange>() << ImportanceChange(m_message, QList<ImportanceChange>() << ImportanceChange(m_message,
m_message.m_isImportant ? m_message.m_isImportant ?
RootItem::NotImportant : RootItem::NotImportant :
RootItem::Important)); RootItem::Important));
emit markMessageImportant(m_message.m_id, checked ? RootItem::Important : RootItem::NotImportant); emit markMessageImportant(m_message.m_id, checked ? RootItem::Important : RootItem::NotImportant);
m_message.m_isImportant = checked; m_message.m_isImportant = checked;
} }
@ -206,29 +195,25 @@ void MessagePreviewer::updateButtons() {
m_actionMarkUnread->setEnabled(m_message.m_isRead); m_actionMarkUnread->setEnabled(m_message.m_isRead);
} }
QString MessagePreviewer::prepareHtmlForMessage(const Message &message) { QString MessagePreviewer::prepareHtmlForMessage(const Message& message) {
QString html = QString("<h2 align=\"center\">%1</h2>").arg(message.m_title); QString html = QString("<h2 align=\"center\">%1</h2>").arg(message.m_title);
html += QString("[url] <a href=\"%1\">%1</a><br/>").arg(message.m_url); html += QString("[url] <a href=\"%1\">%1</a><br/>").arg(message.m_url);
foreach (const Enclosure &enc, message.m_enclosures) { foreach (const Enclosure& enc, message.m_enclosures) {
html += QString("[%2] <a href=\"%1\">%1</a><br/>").arg(enc.m_url, enc.m_mimeType); html += QString("[%2] <a href=\"%1\">%1</a><br/>").arg(enc.m_url, enc.m_mimeType);
} }
int offset = 0; int offset = 0;
QRegExp imgTagRegex("\\<img[^\\>]*src\\s*=\\s*\"([^\"]*)\"[^\\>]*\\>", Qt::CaseInsensitive); QRegExp imgTagRegex("\\<img[^\\>]*src\\s*=\\s*\"([^\"]*)\"[^\\>]*\\>", Qt::CaseInsensitive);
imgTagRegex.setMinimal(true); imgTagRegex.setMinimal(true);
while( (offset = imgTagRegex.indexIn(message.m_contents, offset)) != -1){ while ((offset = imgTagRegex.indexIn(message.m_contents, offset)) != -1) {
m_pictures.append(imgTagRegex.cap(1)); m_pictures.append(imgTagRegex.cap(1));
offset += imgTagRegex.matchedLength(); offset += imgTagRegex.matchedLength();
html += QString("[%2] <a href=\"%1\">%1</a><br/>").arg(imgTagRegex.cap(1), tr("image")); html += QString("[%2] <a href=\"%1\">%1</a><br/>").arg(imgTagRegex.cap(1), tr("image"));
} }
html += "<br/>"; html += "<br/>";
html += message.m_contents; html += message.m_contents;
return html; return html;
} }

View File

@ -38,7 +38,7 @@ class MessagePreviewer : public QWidget {
Q_OBJECT Q_OBJECT
public: public:
explicit MessagePreviewer(QWidget *parent = 0); explicit MessagePreviewer(QWidget* parent = 0);
virtual ~MessagePreviewer(); virtual ~MessagePreviewer();
void reloadFontSettings(); void reloadFontSettings();
@ -46,7 +46,7 @@ class MessagePreviewer : public QWidget {
public slots: public slots:
void clear(); void clear();
void hideToolbar(); void hideToolbar();
void loadMessage(const Message &message, RootItem *root); void loadMessage(const Message& message, RootItem* root);
private slots: private slots:
void markMessageAsRead(); void markMessageAsRead();
@ -62,17 +62,17 @@ class MessagePreviewer : public QWidget {
private: private:
void createConnections(); void createConnections();
void updateButtons(); void updateButtons();
QString prepareHtmlForMessage(const Message &message); QString prepareHtmlForMessage(const Message& message);
QToolBar *m_toolBar; QToolBar* m_toolBar;
QScopedPointer<Ui::MessagePreviewer> m_ui; QScopedPointer<Ui::MessagePreviewer> m_ui;
Message m_message; Message m_message;
QStringList m_pictures; QStringList m_pictures;
QPointer<RootItem> m_root; QPointer<RootItem> m_root;
QAction *m_actionMarkRead; QAction* m_actionMarkRead;
QAction *m_actionMarkUnread; QAction* m_actionMarkUnread;
QAction *m_actionSwitchImportance; QAction* m_actionSwitchImportance;
}; };
#endif // MESSAGEPREVIEWER_H #endif // MESSAGEPREVIEWER_H

View File

@ -18,7 +18,7 @@
#include "gui/messagessearchlineedit.h" #include "gui/messagessearchlineedit.h"
MessagesSearchLineEdit::MessagesSearchLineEdit(QWidget *parent) : BaseLineEdit(parent) { MessagesSearchLineEdit::MessagesSearchLineEdit(QWidget* parent) : BaseLineEdit(parent) {
} }
MessagesSearchLineEdit::~MessagesSearchLineEdit() { MessagesSearchLineEdit::~MessagesSearchLineEdit() {

View File

@ -28,7 +28,7 @@ class MessagesSearchLineEdit : public BaseLineEdit {
public: public:
// Constructors and destructors. // Constructors and destructors.
explicit MessagesSearchLineEdit(QWidget *parent = 0); explicit MessagesSearchLineEdit(QWidget* parent = 0);
virtual ~MessagesSearchLineEdit(); virtual ~MessagesSearchLineEdit();
}; };

View File

@ -28,7 +28,7 @@
#include <QMenu> #include <QMenu>
MessagesToolBar::MessagesToolBar(const QString &title, QWidget *parent) MessagesToolBar::MessagesToolBar(const QString& title, QWidget* parent)
: BaseToolBar(title, parent) { : BaseToolBar(title, parent) {
initializeSearchBox(); initializeSearchBox();
initializeHighlighter(); initializeHighlighter();
@ -39,10 +39,8 @@ MessagesToolBar::~MessagesToolBar() {
QList<QAction*> MessagesToolBar::availableActions() const { QList<QAction*> MessagesToolBar::availableActions() const {
QList<QAction*> available_actions = qApp->userActions(); QList<QAction*> available_actions = qApp->userActions();
available_actions.append(m_actionSearchMessages); available_actions.append(m_actionSearchMessages);
available_actions.append(m_actionMessageHighlighter); available_actions.append(m_actionMessageHighlighter);
return available_actions; return available_actions;
} }
@ -60,45 +58,45 @@ void MessagesToolBar::saveChangeableActions(const QStringList& actions) {
} }
} }
QList<QAction*> MessagesToolBar::getSpecificActions(const QStringList &actions) { QList<QAction*> MessagesToolBar::getSpecificActions(const QStringList& actions) {
QList<QAction*> available_actions = availableActions(); QList<QAction*> available_actions = availableActions();
QList<QAction*> spec_actions; QList<QAction*> spec_actions;
// Iterate action names and add respectable actions into the toolbar. // Iterate action names and add respectable actions into the toolbar.
foreach (const QString &action_name, actions) { foreach (const QString& action_name, actions) {
QAction *matching_action = findMatchingAction(action_name, available_actions); QAction* matching_action = findMatchingAction(action_name, available_actions);
if (matching_action != nullptr) { if (matching_action != nullptr) {
// Add existing standard action. // Add existing standard action.
spec_actions.append(matching_action); spec_actions.append(matching_action);
} }
else if (action_name == SEPARATOR_ACTION_NAME) { else if (action_name == SEPARATOR_ACTION_NAME) {
// Add new separator. // Add new separator.
QAction *act = new QAction(this); QAction* act = new QAction(this);
act->setSeparator(true); act->setSeparator(true);
spec_actions.append(act); spec_actions.append(act);
} }
else if (action_name == SEACRH_MESSAGES_ACTION_NAME) { else if (action_name == SEACRH_MESSAGES_ACTION_NAME) {
// Add search box. // Add search box.
spec_actions.append(m_actionSearchMessages); spec_actions.append(m_actionSearchMessages);
} }
else if (action_name == HIGHLIGHTER_ACTION_NAME) { else if (action_name == HIGHLIGHTER_ACTION_NAME) {
// Add filter button. // Add filter button.
spec_actions.append(m_actionMessageHighlighter); spec_actions.append(m_actionMessageHighlighter);
} }
else if (action_name == SPACER_ACTION_NAME) { else if (action_name == SPACER_ACTION_NAME) {
// Add new spacer. // Add new spacer.
QWidget *spacer = new QWidget(this); QWidget* spacer = new QWidget(this);
spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
QWidgetAction* action = new QWidgetAction(this);
QWidgetAction *action = new QWidgetAction(this);
action->setDefaultWidget(spacer); action->setDefaultWidget(spacer);
action->setIcon(qApp->icons()->fromTheme(QSL("go-jump"))); action->setIcon(qApp->icons()->fromTheme(QSL("go-jump")));
action->setProperty("type", SPACER_ACTION_NAME); action->setProperty("type", SPACER_ACTION_NAME);
action->setProperty("name", tr("Toolbar spacer")); action->setProperty("name", tr("Toolbar spacer"));
spec_actions.append(action); spec_actions.append(action);
} }
} }
@ -106,18 +104,17 @@ QList<QAction*> MessagesToolBar::getSpecificActions(const QStringList &actions)
return spec_actions; return spec_actions;
} }
void MessagesToolBar::loadSpecificActions(const QList<QAction*> &actions) { void MessagesToolBar::loadSpecificActions(const QList<QAction*>& actions) {
clear(); clear();
foreach (QAction *act, actions) { foreach (QAction* act, actions) {
addAction(act); addAction(act);
} }
} }
void MessagesToolBar::handleMessageHighlighterChange(QAction *action) { void MessagesToolBar::handleMessageHighlighterChange(QAction* action) {
m_btnMessageHighlighter->setIcon(action->icon()); m_btnMessageHighlighter->setIcon(action->icon());
m_btnMessageHighlighter->setToolTip(action->text()); m_btnMessageHighlighter->setToolTip(action->text());
emit messageFilterChanged(action->data().value<MessagesModel::MessageHighlighter>()); emit messageFilterChanged(action->data().value<MessagesModel::MessageHighlighter>());
} }
@ -125,14 +122,12 @@ void MessagesToolBar::initializeSearchBox() {
m_txtSearchMessages = new MessagesSearchLineEdit(this); m_txtSearchMessages = new MessagesSearchLineEdit(this);
m_txtSearchMessages->setFixedWidth(FILTER_WIDTH); m_txtSearchMessages->setFixedWidth(FILTER_WIDTH);
m_txtSearchMessages->setPlaceholderText(tr("Search messages")); m_txtSearchMessages->setPlaceholderText(tr("Search messages"));
// Setup wrapping action for search box. // Setup wrapping action for search box.
m_actionSearchMessages = new QWidgetAction(this); m_actionSearchMessages = new QWidgetAction(this);
m_actionSearchMessages->setDefaultWidget(m_txtSearchMessages); m_actionSearchMessages->setDefaultWidget(m_txtSearchMessages);
m_actionSearchMessages->setIcon(qApp->icons()->fromTheme(QSL("system-search"))); m_actionSearchMessages->setIcon(qApp->icons()->fromTheme(QSL("system-search")));
m_actionSearchMessages->setProperty("type", SEACRH_MESSAGES_ACTION_NAME); m_actionSearchMessages->setProperty("type", SEACRH_MESSAGES_ACTION_NAME);
m_actionSearchMessages->setProperty("name", tr("Message search box")); m_actionSearchMessages->setProperty("name", tr("Message search box"));
connect(m_txtSearchMessages, &MessagesSearchLineEdit::textChanged, this, &MessagesToolBar::messageSearchPatternChanged); connect(m_txtSearchMessages, &MessagesSearchLineEdit::textChanged, this, &MessagesToolBar::messageSearchPatternChanged);
} }
@ -144,19 +139,16 @@ void MessagesToolBar::initializeHighlighter() {
tr("Highlight unread messages"))->setData(QVariant::fromValue(MessagesModel::HighlightUnread)); tr("Highlight unread messages"))->setData(QVariant::fromValue(MessagesModel::HighlightUnread));
m_menuMessageHighlighter->addAction(qApp->icons()->fromTheme(QSL("mail-mark-important")), m_menuMessageHighlighter->addAction(qApp->icons()->fromTheme(QSL("mail-mark-important")),
tr("Highlight important messages"))->setData(QVariant::fromValue(MessagesModel::HighlightImportant)); tr("Highlight important messages"))->setData(QVariant::fromValue(MessagesModel::HighlightImportant));
m_btnMessageHighlighter = new QToolButton(this); m_btnMessageHighlighter = new QToolButton(this);
m_btnMessageHighlighter->setToolTip(tr("Display all messages")); m_btnMessageHighlighter->setToolTip(tr("Display all messages"));
m_btnMessageHighlighter->setMenu(m_menuMessageHighlighter); m_btnMessageHighlighter->setMenu(m_menuMessageHighlighter);
m_btnMessageHighlighter->setPopupMode(QToolButton::MenuButtonPopup); m_btnMessageHighlighter->setPopupMode(QToolButton::MenuButtonPopup);
m_btnMessageHighlighter->setIcon(qApp->icons()->fromTheme(QSL("mail-mark-read"))); m_btnMessageHighlighter->setIcon(qApp->icons()->fromTheme(QSL("mail-mark-read")));
m_actionMessageHighlighter = new QWidgetAction(this); m_actionMessageHighlighter = new QWidgetAction(this);
m_actionMessageHighlighter->setDefaultWidget(m_btnMessageHighlighter); m_actionMessageHighlighter->setDefaultWidget(m_btnMessageHighlighter);
m_actionMessageHighlighter->setIcon(m_btnMessageHighlighter->icon()); m_actionMessageHighlighter->setIcon(m_btnMessageHighlighter->icon());
m_actionMessageHighlighter->setProperty("type", HIGHLIGHTER_ACTION_NAME); m_actionMessageHighlighter->setProperty("type", HIGHLIGHTER_ACTION_NAME);
m_actionMessageHighlighter->setProperty("name", tr("Message highlighter")); m_actionMessageHighlighter->setProperty("name", tr("Message highlighter"));
connect(m_menuMessageHighlighter, SIGNAL(triggered(QAction*)), connect(m_menuMessageHighlighter, SIGNAL(triggered(QAction*)),
this, SLOT(handleMessageHighlighterChange(QAction*))); this, SLOT(handleMessageHighlighterChange(QAction*)));
} }

View File

@ -33,50 +33,50 @@ class MessagesToolBar : public BaseToolBar {
public: public:
// Constructors and destructors. // Constructors and destructors.
explicit MessagesToolBar(const QString &title, QWidget *parent = 0); explicit MessagesToolBar(const QString& title, QWidget* parent = 0);
virtual ~MessagesToolBar(); virtual ~MessagesToolBar();
// External access to search line edit. // External access to search line edit.
inline MessagesSearchLineEdit *searchLineEdit() { inline MessagesSearchLineEdit* searchLineEdit() {
return m_txtSearchMessages; return m_txtSearchMessages;
} }
// Implementation of BaseToolBar interface. // Implementation of BaseToolBar interface.
QList<QAction*> availableActions() const; QList<QAction*> availableActions() const;
QList<QAction*> changeableActions() const; QList<QAction*> changeableActions() const;
void saveChangeableActions(const QStringList &actions); void saveChangeableActions(const QStringList& actions);
// Loads actions as specified by external actions list. // Loads actions as specified by external actions list.
// NOTE: This is used primarily for reloading actions // NOTE: This is used primarily for reloading actions
// when they are changed from settings. // when they are changed from settings.
void loadSpecificActions(const QList<QAction*> &actions); void loadSpecificActions(const QList<QAction*>& actions);
QList<QAction*> getSpecificActions(const QStringList &actions); QList<QAction*> getSpecificActions(const QStringList& actions);
QStringList defaultActions() const; QStringList defaultActions() const;
QStringList savedActions() const; QStringList savedActions() const;
signals: signals:
void messageSearchPatternChanged(const QString &pattern); void messageSearchPatternChanged(const QString& pattern);
// Emitted if message filter is changed. // Emitted if message filter is changed.
void messageFilterChanged(MessagesModel::MessageHighlighter filter); void messageFilterChanged(MessagesModel::MessageHighlighter filter);
private slots: private slots:
// Called when highlighter gets changed. // Called when highlighter gets changed.
void handleMessageHighlighterChange(QAction *action); void handleMessageHighlighterChange(QAction* action);
private: private:
void initializeSearchBox(); void initializeSearchBox();
void initializeHighlighter(); void initializeHighlighter();
private: private:
QWidgetAction *m_actionMessageHighlighter; QWidgetAction* m_actionMessageHighlighter;
QToolButton *m_btnMessageHighlighter; QToolButton* m_btnMessageHighlighter;
QMenu *m_menuMessageHighlighter; QMenu* m_menuMessageHighlighter;
QWidgetAction *m_actionSearchMessages; QWidgetAction* m_actionSearchMessages;
MessagesSearchLineEdit *m_txtSearchMessages; MessagesSearchLineEdit* m_txtSearchMessages;
}; };
#endif // NEWSTOOLBAR_H #endif // NEWSTOOLBAR_H

View File

@ -34,18 +34,16 @@
#include <QMenu> #include <QMenu>
MessagesView::MessagesView(QWidget *parent) MessagesView::MessagesView(QWidget* parent)
: QTreeView(parent), m_contextMenu(nullptr), m_columnsAdjusted(false) { : QTreeView(parent), m_contextMenu(nullptr), m_columnsAdjusted(false) {
m_sourceModel = qApp->feedReader()->messagesModel(); m_sourceModel = qApp->feedReader()->messagesModel();
m_proxyModel = qApp->feedReader()->messagesProxyModel(); m_proxyModel = qApp->feedReader()->messagesProxyModel();
// Forward count changes to the view. // Forward count changes to the view.
createConnections(); createConnections();
setModel(m_proxyModel); setModel(m_proxyModel);
setupAppearance(); setupAppearance();
header()->setContextMenuPolicy(Qt::CustomContextMenu); header()->setContextMenuPolicy(Qt::CustomContextMenu);
connect(header(), &QHeaderView::customContextMenuRequested, [=](const QPoint &point) { connect(header(), &QHeaderView::customContextMenuRequested, [ = ](const QPoint & point) {
TreeViewColumnsMenu mm(header()); TreeViewColumnsMenu mm(header());
mm.exec(header()->mapToGlobal(point)); mm.exec(header()->mapToGlobal(point));
}); });
@ -74,13 +72,12 @@ void MessagesView::sort(int column, Qt::SortOrder order, bool repopulate_data, b
void MessagesView::createConnections() { void MessagesView::createConnections() {
connect(this, &MessagesView::doubleClicked, this, &MessagesView::openSelectedSourceMessagesExternally); connect(this, &MessagesView::doubleClicked, this, &MessagesView::openSelectedSourceMessagesExternally);
// Adjust columns when layout gets changed. // Adjust columns when layout gets changed.
connect(header(), &QHeaderView::geometriesChanged, this, &MessagesView::adjustColumns); connect(header(), &QHeaderView::geometriesChanged, this, &MessagesView::adjustColumns);
connect(header(), &QHeaderView::sortIndicatorChanged, this, &MessagesView::onSortIndicatorChanged); connect(header(), &QHeaderView::sortIndicatorChanged, this, &MessagesView::onSortIndicatorChanged);
} }
void MessagesView::keyboardSearch(const QString &search) { void MessagesView::keyboardSearch(const QString& search) {
// WARNING: This is quite hacky way how to force selection of next item even // WARNING: This is quite hacky way how to force selection of next item even
// with extended selection enabled. // with extended selection enabled.
setSelectionMode(QAbstractItemView::SingleSelection); setSelectionMode(QAbstractItemView::SingleSelection);
@ -90,13 +87,11 @@ void MessagesView::keyboardSearch(const QString &search) {
void MessagesView::reloadSelections() { void MessagesView::reloadSelections() {
const QDateTime dt1 = QDateTime::currentDateTime(); const QDateTime dt1 = QDateTime::currentDateTime();
QModelIndex current_index = selectionModel()->currentIndex(); QModelIndex current_index = selectionModel()->currentIndex();
const QModelIndex mapped_current_index = m_proxyModel->mapToSource(current_index); const QModelIndex mapped_current_index = m_proxyModel->mapToSource(current_index);
const Message selected_message = m_sourceModel->messageAt(mapped_current_index.row()); const Message selected_message = m_sourceModel->messageAt(mapped_current_index.row());
const int col = header()->sortIndicatorSection(); const int col = header()->sortIndicatorSection();
const Qt::SortOrder ord = header()->sortIndicatorOrder(); const Qt::SortOrder ord = header()->sortIndicatorOrder();
// Reload the model now. // Reload the model now.
sort(col, ord, true, false, false); sort(col, ord, true, false, false);
@ -105,6 +100,7 @@ void MessagesView::reloadSelections() {
if (m_proxyModel->rowCount() == 0) { if (m_proxyModel->rowCount() == 0) {
current_index = QModelIndex(); current_index = QModelIndex();
} }
else { else {
for (int i = 0; i < m_proxyModel->rowCount(); i++) { for (int i = 0; i < m_proxyModel->rowCount(); i++) {
QModelIndex msg_idx = m_proxyModel->index(i, MSG_DB_TITLE_INDEX); QModelIndex msg_idx = m_proxyModel->index(i, MSG_DB_TITLE_INDEX);
@ -127,6 +123,7 @@ void MessagesView::reloadSelections() {
setCurrentIndex(current_index); setCurrentIndex(current_index);
reselectIndexes(QModelIndexList() << current_index); reselectIndexes(QModelIndexList() << current_index);
} }
else { else {
// Messages were probably removed from the model, nothing can // Messages were probably removed from the model, nothing can
// be selected and no message can be displayed. // be selected and no message can be displayed.
@ -134,7 +131,6 @@ void MessagesView::reloadSelections() {
} }
const QDateTime dt2 = QDateTime::currentDateTime(); const QDateTime dt2 = QDateTime::currentDateTime();
qDebug("Reloading of msg selections took %lld miliseconds.", dt1.msecsTo(dt2)); qDebug("Reloading of msg selections took %lld miliseconds.", dt1.msecsTo(dt2));
} }
@ -151,7 +147,6 @@ void MessagesView::setupAppearance() {
setAllColumnsShowFocus(false); setAllColumnsShowFocus(false);
setSelectionMode(QAbstractItemView::ExtendedSelection); setSelectionMode(QAbstractItemView::ExtendedSelection);
setItemDelegate(new StyledItemDelegateWithoutFocus(this)); setItemDelegate(new StyledItemDelegateWithoutFocus(this));
header()->setDefaultSectionSize(MESSAGES_VIEW_DEFAULT_COL); header()->setDefaultSectionSize(MESSAGES_VIEW_DEFAULT_COL);
header()->setMinimumSectionSize(MESSAGES_VIEW_MINIMUM_COL); header()->setMinimumSectionSize(MESSAGES_VIEW_MINIMUM_COL);
header()->setCascadingSectionResizes(false); header()->setCascadingSectionResizes(false);
@ -159,7 +154,7 @@ void MessagesView::setupAppearance() {
header()->setSortIndicatorShown(true); header()->setSortIndicatorShown(true);
} }
void MessagesView::keyPressEvent(QKeyEvent *event) { void MessagesView::keyPressEvent(QKeyEvent* event) {
QTreeView::keyPressEvent(event); QTreeView::keyPressEvent(event);
if (event->key() == Qt::Key_Delete) { if (event->key() == Qt::Key_Delete) {
@ -167,17 +162,17 @@ void MessagesView::keyPressEvent(QKeyEvent *event) {
} }
} }
void MessagesView::contextMenuEvent(QContextMenuEvent *event) { void MessagesView::contextMenuEvent(QContextMenuEvent* event) {
const QModelIndex clicked_index = indexAt(event->pos()); const QModelIndex clicked_index = indexAt(event->pos());
if (!clicked_index.isValid()) { if (!clicked_index.isValid()) {
TreeViewColumnsMenu menu(header()); TreeViewColumnsMenu menu(header());
menu.exec(event->globalPos()); menu.exec(event->globalPos());
} }
else { else {
// Context menu is not initialized, initialize. // Context menu is not initialized, initialize.
initializeContextMenu(); initializeContextMenu();
m_contextMenu->exec(event->globalPos()); m_contextMenu->exec(event->globalPos());
} }
} }
@ -202,7 +197,7 @@ void MessagesView::initializeContextMenu() {
} }
} }
void MessagesView::mousePressEvent(QMouseEvent *event) { void MessagesView::mousePressEvent(QMouseEvent* event) {
QTreeView::mousePressEvent(event); QTreeView::mousePressEvent(event);
switch (event->button()) { switch (event->button()) {
@ -238,7 +233,6 @@ void MessagesView::mousePressEvent(QMouseEvent *event) {
} }
} }
break; break;
} }
@ -247,25 +241,23 @@ void MessagesView::mousePressEvent(QMouseEvent *event) {
} }
} }
void MessagesView::selectionChanged(const QItemSelection &selected, const QItemSelection &deselected) { void MessagesView::selectionChanged(const QItemSelection& selected, const QItemSelection& deselected) {
const QModelIndexList selected_rows = selectionModel()->selectedRows(); const QModelIndexList selected_rows = selectionModel()->selectedRows();
const QModelIndex current_index = currentIndex(); const QModelIndex current_index = currentIndex();
const QModelIndex mapped_current_index = m_proxyModel->mapToSource(current_index); const QModelIndex mapped_current_index = m_proxyModel->mapToSource(current_index);
qDebug("Current row changed - row [%d,%d] source [%d, %d].", qDebug("Current row changed - row [%d,%d] source [%d, %d].",
current_index.row(), current_index.column(), current_index.row(), current_index.column(),
mapped_current_index.row(), mapped_current_index.column()); mapped_current_index.row(), mapped_current_index.column());
if (mapped_current_index.isValid() && selected_rows.count() > 0) { if (mapped_current_index.isValid() && selected_rows.count() > 0) {
Message message = m_sourceModel->messageAt(m_proxyModel->mapToSource(current_index).row()); Message message = m_sourceModel->messageAt(m_proxyModel->mapToSource(current_index).row());
// Set this message as read only if current item // Set this message as read only if current item
// wasn't changed by "mark selected messages unread" action. // wasn't changed by "mark selected messages unread" action.
m_sourceModel->setMessageRead(mapped_current_index.row(), RootItem::Read); m_sourceModel->setMessageRead(mapped_current_index.row(), RootItem::Read);
message.m_isRead = true; message.m_isRead = true;
emit currentMessageChanged(message, m_sourceModel->loadedItem()); emit currentMessageChanged(message, m_sourceModel->loadedItem());
} }
else { else {
emit currentMessageRemoved(); emit currentMessageRemoved();
} }
@ -277,14 +269,12 @@ void MessagesView::selectionChanged(const QItemSelection &selected, const QItemS
QTreeView::selectionChanged(selected, deselected); QTreeView::selectionChanged(selected, deselected);
} }
void MessagesView::loadItem(RootItem *item) { void MessagesView::loadItem(RootItem* item) {
const int col = header()->sortIndicatorSection(); const int col = header()->sortIndicatorSection();
const Qt::SortOrder ord = header()->sortIndicatorOrder(); const Qt::SortOrder ord = header()->sortIndicatorOrder();
scrollToTop(); scrollToTop();
sort(col, ord, false, true, false); sort(col, ord, false, true, false);
m_sourceModel->loadMessages(item); m_sourceModel->loadMessages(item);
// Messages are loaded, make sure that previously // Messages are loaded, make sure that previously
// active message is not shown in browser. // active message is not shown in browser.
// BUG: Qt 5 is probably bugged here. Selections // BUG: Qt 5 is probably bugged here. Selections
@ -293,7 +283,7 @@ void MessagesView::loadItem(RootItem *item) {
} }
void MessagesView::openSelectedSourceMessagesExternally() { void MessagesView::openSelectedSourceMessagesExternally() {
foreach (const QModelIndex &index, selectionModel()->selectedRows()) { foreach (const QModelIndex& index, selectionModel()->selectedRows()) {
const QString link = m_sourceModel->messageAt(m_proxyModel->mapToSource(index).row()).m_url; const QString link = m_sourceModel->messageAt(m_proxyModel->mapToSource(index).row()).m_url;
if (!WebFactory::instance()->openUrlInExternalBrowser(link)) { if (!WebFactory::instance()->openUrlInExternalBrowser(link)) {
@ -313,7 +303,7 @@ void MessagesView::openSelectedSourceMessagesExternally() {
void MessagesView::openSelectedMessagesInternally() { void MessagesView::openSelectedMessagesInternally() {
QList<Message> messages; QList<Message> messages;
foreach (const QModelIndex &index, selectionModel()->selectedRows()) { foreach (const QModelIndex& index, selectionModel()->selectedRows()) {
messages << m_sourceModel->messageAt(m_proxyModel->mapToSource(index).row()); messages << m_sourceModel->messageAt(m_proxyModel->mapToSource(index).row());
} }
@ -352,13 +342,13 @@ void MessagesView::setSelectedMessagesReadStatus(RootItem::ReadStatus read) {
QModelIndexList selected_indexes = selectionModel()->selectedRows(); QModelIndexList selected_indexes = selectionModel()->selectedRows();
const QModelIndexList mapped_indexes = m_proxyModel->mapListToSource(selected_indexes); const QModelIndexList mapped_indexes = m_proxyModel->mapListToSource(selected_indexes);
m_sourceModel->setBatchMessagesRead(mapped_indexes, read); m_sourceModel->setBatchMessagesRead(mapped_indexes, read);
current_index = m_proxyModel->index(current_index.row(), current_index.column()); current_index = m_proxyModel->index(current_index.row(), current_index.column());
if (current_index.isValid()) { if (current_index.isValid()) {
emit currentMessageChanged(m_sourceModel->messageAt(m_proxyModel->mapToSource(current_index).row()), m_sourceModel->loadedItem()); emit currentMessageChanged(m_sourceModel->messageAt(m_proxyModel->mapToSource(current_index).row()), m_sourceModel->loadedItem());
} }
else { else {
emit currentMessageRemoved(); emit currentMessageRemoved();
} }
@ -373,7 +363,6 @@ void MessagesView::deleteSelectedMessages() {
const QModelIndexList selected_indexes = selectionModel()->selectedRows(); const QModelIndexList selected_indexes = selectionModel()->selectedRows();
const QModelIndexList mapped_indexes = m_proxyModel->mapListToSource(selected_indexes); const QModelIndexList mapped_indexes = m_proxyModel->mapListToSource(selected_indexes);
m_sourceModel->setBatchMessagesDeleted(mapped_indexes); m_sourceModel->setBatchMessagesDeleted(mapped_indexes);
current_index = moveCursor(QAbstractItemView::MoveDown, Qt::NoModifier); current_index = moveCursor(QAbstractItemView::MoveDown, Qt::NoModifier);
@ -381,6 +370,7 @@ void MessagesView::deleteSelectedMessages() {
setCurrentIndex(current_index); setCurrentIndex(current_index);
emit currentMessageChanged(m_sourceModel->messageAt(m_proxyModel->mapToSource(current_index).row()), m_sourceModel->loadedItem()); emit currentMessageChanged(m_sourceModel->messageAt(m_proxyModel->mapToSource(current_index).row()), m_sourceModel->loadedItem());
} }
else { else {
emit currentMessageRemoved(); emit currentMessageRemoved();
} }
@ -395,14 +385,13 @@ void MessagesView::restoreSelectedMessages() {
const QModelIndexList selected_indexes = selectionModel()->selectedRows(); const QModelIndexList selected_indexes = selectionModel()->selectedRows();
const QModelIndexList mapped_indexes = m_proxyModel->mapListToSource(selected_indexes); const QModelIndexList mapped_indexes = m_proxyModel->mapListToSource(selected_indexes);
m_sourceModel->setBatchMessagesRestored(mapped_indexes); m_sourceModel->setBatchMessagesRestored(mapped_indexes);
current_index = m_proxyModel->index(current_index.row(), current_index.column()); current_index = m_proxyModel->index(current_index.row(), current_index.column());
if (current_index.isValid()) { if (current_index.isValid()) {
emit currentMessageChanged(m_sourceModel->messageAt(m_proxyModel->mapToSource(current_index).row()), m_sourceModel->loadedItem()); emit currentMessageChanged(m_sourceModel->messageAt(m_proxyModel->mapToSource(current_index).row()), m_sourceModel->loadedItem());
} }
else { else {
emit currentMessageRemoved(); emit currentMessageRemoved();
} }
@ -417,13 +406,13 @@ void MessagesView::switchSelectedMessagesImportance() {
QModelIndexList selected_indexes = selectionModel()->selectedRows(); QModelIndexList selected_indexes = selectionModel()->selectedRows();
const QModelIndexList mapped_indexes = m_proxyModel->mapListToSource(selected_indexes); const QModelIndexList mapped_indexes = m_proxyModel->mapListToSource(selected_indexes);
m_sourceModel->switchBatchMessageImportance(mapped_indexes); m_sourceModel->switchBatchMessageImportance(mapped_indexes);
current_index = m_proxyModel->index(current_index.row(), current_index.column()); current_index = m_proxyModel->index(current_index.row(), current_index.column());
if (current_index.isValid()) { if (current_index.isValid()) {
emit currentMessageChanged(m_sourceModel->messageAt(m_proxyModel->mapToSource(current_index).row()), m_sourceModel->loadedItem()); emit currentMessageChanged(m_sourceModel->messageAt(m_proxyModel->mapToSource(current_index).row()), m_sourceModel->loadedItem());
} }
else { else {
// Messages were probably removed from the model, nothing can // Messages were probably removed from the model, nothing can
// be selected and no message can be displayed. // be selected and no message can be displayed.
@ -431,11 +420,11 @@ void MessagesView::switchSelectedMessagesImportance() {
} }
} }
void MessagesView::reselectIndexes(const QModelIndexList &indexes) { void MessagesView::reselectIndexes(const QModelIndexList& indexes) {
if (indexes.size() < RESELECT_MESSAGE_THRESSHOLD) { if (indexes.size() < RESELECT_MESSAGE_THRESSHOLD) {
QItemSelection selection; QItemSelection selection;
foreach (const QModelIndex &index, indexes) { foreach (const QModelIndex& index, indexes) {
selection.merge(QItemSelection(index, index), QItemSelectionModel::Select); selection.merge(QItemSelection(index, index), QItemSelectionModel::Select);
} }
@ -465,7 +454,6 @@ void MessagesView::selectPreviousItem() {
void MessagesView::selectNextUnreadItem() { void MessagesView::selectNextUnreadItem() {
// FIXME: Use this to solve #112. // FIXME: Use this to solve #112.
const QModelIndexList selected_rows = selectionModel()->selectedRows(); const QModelIndexList selected_rows = selectionModel()->selectedRows();
int active_row; int active_row;
@ -473,6 +461,7 @@ void MessagesView::selectNextUnreadItem() {
// Okay, something is selected, start from it. // Okay, something is selected, start from it.
active_row = selected_rows.at(0).row(); active_row = selected_rows.at(0).row();
} }
else { else {
active_row = 0; active_row = 0;
} }
@ -487,12 +476,13 @@ void MessagesView::selectNextUnreadItem() {
} }
} }
void MessagesView::searchMessages(const QString &pattern) { void MessagesView::searchMessages(const QString& pattern) {
m_proxyModel->setFilterRegExp(pattern); m_proxyModel->setFilterRegExp(pattern);
if (selectionModel()->selectedRows().size() == 0) { if (selectionModel()->selectedRows().size() == 0) {
emit currentMessageRemoved(); emit currentMessageRemoved();
} }
else { else {
// Scroll to selected message, it could become scrolled out due to filter change. // Scroll to selected message, it could become scrolled out due to filter change.
scrollTo(selectionModel()->selectedRows().at(0)); scrollTo(selectionModel()->selectedRows().at(0));
@ -506,7 +496,6 @@ void MessagesView::filterMessages(MessagesModel::MessageHighlighter filter) {
void MessagesView::adjustColumns() { void MessagesView::adjustColumns() {
if (header()->count() > 0 && !m_columnsAdjusted) { if (header()->count() > 0 && !m_columnsAdjusted) {
m_columnsAdjusted = true; m_columnsAdjusted = true;
// Setup column resize strategies. // Setup column resize strategies.
header()->setSectionResizeMode(MSG_DB_ID_INDEX, QHeaderView::Interactive); header()->setSectionResizeMode(MSG_DB_ID_INDEX, QHeaderView::Interactive);
header()->setSectionResizeMode(MSG_DB_READ_INDEX, QHeaderView::ResizeToContents); header()->setSectionResizeMode(MSG_DB_READ_INDEX, QHeaderView::ResizeToContents);
@ -519,10 +508,8 @@ void MessagesView::adjustColumns() {
header()->setSectionResizeMode(MSG_DB_DCREATED_INDEX, QHeaderView::Interactive); header()->setSectionResizeMode(MSG_DB_DCREATED_INDEX, QHeaderView::Interactive);
header()->setSectionResizeMode(MSG_DB_CONTENTS_INDEX, QHeaderView::Interactive); header()->setSectionResizeMode(MSG_DB_CONTENTS_INDEX, QHeaderView::Interactive);
header()->setSectionResizeMode(MSG_DB_PDELETED_INDEX, QHeaderView::Interactive); header()->setSectionResizeMode(MSG_DB_PDELETED_INDEX, QHeaderView::Interactive);
//header()->resizeSection(MSG_DB_READ_INDEX, MESSAGES_VIEW_MINIMUM_COL); //header()->resizeSection(MSG_DB_READ_INDEX, MESSAGES_VIEW_MINIMUM_COL);
//header()->resizeSection(MSG_DB_IMPORTANT_INDEX, MESSAGES_VIEW_MINIMUM_COL); //header()->resizeSection(MSG_DB_IMPORTANT_INDEX, MESSAGES_VIEW_MINIMUM_COL);
// Hide columns. // Hide columns.
hideColumn(MSG_DB_ID_INDEX); hideColumn(MSG_DB_ID_INDEX);
hideColumn(MSG_DB_DELETED_INDEX); hideColumn(MSG_DB_DELETED_INDEX);
@ -534,7 +521,6 @@ void MessagesView::adjustColumns() {
hideColumn(MSG_DB_CUSTOM_ID_INDEX); hideColumn(MSG_DB_CUSTOM_ID_INDEX);
hideColumn(MSG_DB_CUSTOM_HASH_INDEX); hideColumn(MSG_DB_CUSTOM_HASH_INDEX);
hideColumn(MSG_DB_FEED_CUSTOM_ID_INDEX); hideColumn(MSG_DB_FEED_CUSTOM_ID_INDEX);
qDebug("Adjusting column resize modes for MessagesView."); qDebug("Adjusting column resize modes for MessagesView.");
} }
} }

View File

@ -33,27 +33,27 @@ class MessagesView : public QTreeView {
public: public:
// Constructors and destructors. // Constructors and destructors.
explicit MessagesView(QWidget *parent = 0); explicit MessagesView(QWidget* parent = 0);
virtual ~MessagesView(); virtual ~MessagesView();
// Model accessors. // Model accessors.
inline MessagesProxyModel *model() const { inline MessagesProxyModel* model() const {
return m_proxyModel; return m_proxyModel;
} }
inline MessagesModel *sourceModel() const { inline MessagesModel* sourceModel() const {
return m_sourceModel; return m_sourceModel;
} }
public slots: public slots:
void keyboardSearch(const QString &search); void keyboardSearch(const QString& search);
// Called after data got changed externally // Called after data got changed externally
// and it needs to be reloaded to the view. // and it needs to be reloaded to the view.
void reloadSelections(); void reloadSelections();
// Loads un-deleted messages from selected feeds. // Loads un-deleted messages from selected feeds.
void loadItem(RootItem *item); void loadItem(RootItem* item);
// Message manipulators. // Message manipulators.
void openSelectedSourceMessagesExternally(); void openSelectedSourceMessagesExternally();
@ -73,12 +73,12 @@ class MessagesView : public QTreeView {
void selectNextUnreadItem(); void selectNextUnreadItem();
// Searchs the visible message according to given pattern. // Searchs the visible message according to given pattern.
void searchMessages(const QString &pattern); void searchMessages(const QString& pattern);
void filterMessages(MessagesModel::MessageHighlighter filter); void filterMessages(MessagesModel::MessageHighlighter filter);
private slots: private slots:
// Marks given indexes as selected. // Marks given indexes as selected.
void reselectIndexes(const QModelIndexList &indexes); void reselectIndexes(const QModelIndexList& indexes);
// Changes resize mode for all columns. // Changes resize mode for all columns.
void adjustColumns(); void adjustColumns();
@ -88,12 +88,12 @@ class MessagesView : public QTreeView {
signals: signals:
// Link/message openers. // Link/message openers.
void openLinkNewTab(const QString &link); void openLinkNewTab(const QString& link);
void openLinkMiniBrowser(const QString &link); void openLinkMiniBrowser(const QString& link);
void openMessagesInNewspaperView(RootItem *root, const QList<Message> &messages); void openMessagesInNewspaperView(RootItem* root, const QList<Message>& messages);
// Notify others about message selections. // Notify others about message selections.
void currentMessageChanged(const Message &message, RootItem *root); void currentMessageChanged(const Message& message, RootItem* root);
void currentMessageRemoved(); void currentMessageRemoved();
private: private:
@ -109,15 +109,15 @@ class MessagesView : public QTreeView {
void setupAppearance(); void setupAppearance();
// Event reimplementations. // Event reimplementations.
void contextMenuEvent(QContextMenuEvent *event); void contextMenuEvent(QContextMenuEvent* event);
void mousePressEvent(QMouseEvent *event); void mousePressEvent(QMouseEvent* event);
void keyPressEvent(QKeyEvent *event); void keyPressEvent(QKeyEvent* event);
void selectionChanged(const QItemSelection &selected, const QItemSelection &deselected); void selectionChanged(const QItemSelection& selected, const QItemSelection& deselected);
QMenu *m_contextMenu; QMenu* m_contextMenu;
MessagesProxyModel *m_proxyModel; MessagesProxyModel* m_proxyModel;
MessagesModel *m_sourceModel; MessagesModel* m_sourceModel;
bool m_columnsAdjusted; bool m_columnsAdjusted;
}; };

View File

@ -22,13 +22,13 @@
#include "network-web/networkfactory.h" #include "network-web/networkfactory.h"
MessageTextBrowser::MessageTextBrowser(QWidget *parent) : QTextBrowser(parent) { MessageTextBrowser::MessageTextBrowser(QWidget* parent) : QTextBrowser(parent) {
} }
MessageTextBrowser::~MessageTextBrowser() { MessageTextBrowser::~MessageTextBrowser() {
} }
QVariant MessageTextBrowser::loadResource(int type, const QUrl &name) { QVariant MessageTextBrowser::loadResource(int type, const QUrl& name) {
Q_UNUSED(name) Q_UNUSED(name)
switch (type) { switch (type) {
@ -45,7 +45,7 @@ QVariant MessageTextBrowser::loadResource(int type, const QUrl &name) {
} }
} }
void MessageTextBrowser::wheelEvent(QWheelEvent *e) { void MessageTextBrowser::wheelEvent(QWheelEvent* e) {
QTextBrowser::wheelEvent(e); QTextBrowser::wheelEvent(e);
qApp->settings()->setValue(GROUP(Messages), Messages::PreviewerFontStandard, font().toString()); qApp->settings()->setValue(GROUP(Messages), Messages::PreviewerFontStandard, font().toString());
} }

View File

@ -25,13 +25,13 @@ class MessageTextBrowser : public QTextBrowser {
Q_OBJECT Q_OBJECT
public: public:
explicit MessageTextBrowser(QWidget *parent = 0); explicit MessageTextBrowser(QWidget* parent = 0);
virtual ~MessageTextBrowser(); virtual ~MessageTextBrowser();
QVariant loadResource(int type, const QUrl &name); QVariant loadResource(int type, const QUrl& name);
protected: protected:
void wheelEvent(QWheelEvent *e); void wheelEvent(QWheelEvent* e);
private: private:
QPixmap m_imagePlaceholder; QPixmap m_imagePlaceholder;

View File

@ -24,7 +24,7 @@
#include <QScrollBar> #include <QScrollBar>
NewspaperPreviewer::NewspaperPreviewer(RootItem *root, QList<Message> messages, QWidget *parent) NewspaperPreviewer::NewspaperPreviewer(RootItem* root, QList<Message> messages, QWidget* parent)
: TabContent(parent), m_ui(new Ui::NewspaperPreviewer), m_root(root), m_messages(messages) { : TabContent(parent), m_ui(new Ui::NewspaperPreviewer), m_root(root), m_messages(messages) {
m_ui->setupUi(this); m_ui->setupUi(this);
connect(m_ui->m_btnShowMoreMessages, &QPushButton::clicked, this, &NewspaperPreviewer::showMoreMessages); connect(m_ui->m_btnShowMoreMessages, &QPushButton::clicked, this, &NewspaperPreviewer::showMoreMessages);
@ -40,11 +40,9 @@ void NewspaperPreviewer::showMoreMessages() {
for (int i = 0; i < 10 && !m_messages.isEmpty(); i++) { for (int i = 0; i < 10 && !m_messages.isEmpty(); i++) {
Message msg = m_messages.takeFirst(); Message msg = m_messages.takeFirst();
MessagePreviewer *prev = new MessagePreviewer(this); MessagePreviewer* prev = new MessagePreviewer(this);
QMargins margins = prev->layout()->contentsMargins(); QMargins margins = prev->layout()->contentsMargins();
connect(prev, &MessagePreviewer::requestMessageListReload, this, &NewspaperPreviewer::requestMessageListReload); connect(prev, &MessagePreviewer::requestMessageListReload, this, &NewspaperPreviewer::requestMessageListReload);
margins.setRight(0); margins.setRight(0);
prev->layout()->setContentsMargins(margins); prev->layout()->setContentsMargins(margins);
prev->setFixedHeight(300); prev->setFixedHeight(300);
@ -56,6 +54,7 @@ void NewspaperPreviewer::showMoreMessages() {
m_ui->m_btnShowMoreMessages->setEnabled(!m_messages.isEmpty()); m_ui->m_btnShowMoreMessages->setEnabled(!m_messages.isEmpty());
m_ui->scrollArea->verticalScrollBar()->setValue(current_scroll); m_ui->scrollArea->verticalScrollBar()->setValue(current_scroll);
} }
else { else {
qApp->showGuiMessage(tr("Cannot show more messages"), qApp->showGuiMessage(tr("Cannot show more messages"),
tr("Cannot show more messages because parent feed was removed."), tr("Cannot show more messages because parent feed was removed."),

View File

@ -40,7 +40,7 @@ class NewspaperPreviewer : public TabContent {
Q_OBJECT Q_OBJECT
public: public:
explicit NewspaperPreviewer(RootItem *root, QList<Message> messages, QWidget *parent = 0); explicit NewspaperPreviewer(RootItem* root, QList<Message> messages, QWidget* parent = 0);
virtual ~NewspaperPreviewer(); virtual ~NewspaperPreviewer();
private slots: private slots:

View File

@ -25,18 +25,16 @@
#include <QAction> #include <QAction>
PlainToolButton::PlainToolButton(QWidget *parent) : QToolButton(parent), m_padding(0) { PlainToolButton::PlainToolButton(QWidget* parent) : QToolButton(parent), m_padding(0) {
} }
PlainToolButton::~PlainToolButton() { PlainToolButton::~PlainToolButton() {
} }
void PlainToolButton::paintEvent(QPaintEvent *e) { void PlainToolButton::paintEvent(QPaintEvent* e) {
Q_UNUSED(e) Q_UNUSED(e)
QPainter p(this); QPainter p(this);
QRect rect(QPoint(0, 0), size()); QRect rect(QPoint(0, 0), size());
// Set padding. // Set padding.
rect.adjust(m_padding, m_padding, -m_padding, -m_padding); rect.adjust(m_padding, m_padding, -m_padding, -m_padding);
@ -45,6 +43,7 @@ void PlainToolButton::paintEvent(QPaintEvent *e) {
p.setOpacity(0.7); p.setOpacity(0.7);
} }
} }
else { else {
p.setOpacity(0.3); p.setOpacity(0.3);
} }
@ -66,7 +65,7 @@ void PlainToolButton::setChecked(bool checked) {
repaint(); repaint();
} }
void PlainToolButton::reactOnActionChange(QAction *action) { void PlainToolButton::reactOnActionChange(QAction* action) {
if (action != nullptr) { if (action != nullptr) {
setEnabled(action->isEnabled()); setEnabled(action->isEnabled());
setCheckable(action->isCheckable()); setCheckable(action->isCheckable());

View File

@ -26,7 +26,7 @@ class PlainToolButton : public QToolButton {
public: public:
// Contructors and destructors. // Contructors and destructors.
explicit PlainToolButton(QWidget *parent = 0); explicit PlainToolButton(QWidget* parent = 0);
virtual ~PlainToolButton(); virtual ~PlainToolButton();
// Padding changers. // Padding changers.
@ -35,12 +35,12 @@ class PlainToolButton : public QToolButton {
public slots: public slots:
void setChecked(bool checked); void setChecked(bool checked);
void reactOnActionChange(QAction *action); void reactOnActionChange(QAction* action);
void reactOnSenderActionChange(); void reactOnSenderActionChange();
protected: protected:
// Custom look. // Custom look.
void paintEvent(QPaintEvent *e); void paintEvent(QPaintEvent* e);
private: private:
int m_padding; int m_padding;

View File

@ -26,20 +26,17 @@
#include <QFileDialog> #include <QFileDialog>
SettingsBrowserMail::SettingsBrowserMail(Settings *settings, QWidget *parent) SettingsBrowserMail::SettingsBrowserMail(Settings* settings, QWidget* parent)
: SettingsPanel(settings, parent), m_ui(new Ui::SettingsBrowserMail) { : SettingsPanel(settings, parent), m_ui(new Ui::SettingsBrowserMail) {
m_ui->setupUi(this); m_ui->setupUi(this);
GuiUtilities::setLabelAsNotice(m_ui->label, false); GuiUtilities::setLabelAsNotice(m_ui->label, false);
GuiUtilities::setLabelAsNotice(m_ui->m_lblExternalEmailInfo, false); GuiUtilities::setLabelAsNotice(m_ui->m_lblExternalEmailInfo, false);
GuiUtilities::setLabelAsNotice(m_ui->m_lblProxyInfo, false); GuiUtilities::setLabelAsNotice(m_ui->m_lblProxyInfo, false);
#if defined(USE_WEBENGINE) #if defined(USE_WEBENGINE)
m_ui->m_checkOpenLinksInExternal->setVisible(false); m_ui->m_checkOpenLinksInExternal->setVisible(false);
#else #else
connect(m_ui->m_checkOpenLinksInExternal, &QCheckBox::stateChanged, this, &SettingsBrowserMail::dirtifySettings); connect(m_ui->m_checkOpenLinksInExternal, &QCheckBox::stateChanged, this, &SettingsBrowserMail::dirtifySettings);
#endif #endif
connect(m_ui->m_cmbProxyType, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &SettingsBrowserMail::dirtifySettings); connect(m_ui->m_cmbProxyType, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &SettingsBrowserMail::dirtifySettings);
connect(m_ui->m_txtProxyHost, &QLineEdit::textChanged, this, &SettingsBrowserMail::dirtifySettings); connect(m_ui->m_txtProxyHost, &QLineEdit::textChanged, this, &SettingsBrowserMail::dirtifySettings);
connect(m_ui->m_txtProxyPassword, &QLineEdit::textChanged, this, &SettingsBrowserMail::dirtifySettings); connect(m_ui->m_txtProxyPassword, &QLineEdit::textChanged, this, &SettingsBrowserMail::dirtifySettings);
@ -51,7 +48,6 @@ SettingsBrowserMail::SettingsBrowserMail(Settings *settings, QWidget *parent)
connect(m_ui->m_txtExternalBrowserExecutable, &QLineEdit::textChanged, this, &SettingsBrowserMail::dirtifySettings); connect(m_ui->m_txtExternalBrowserExecutable, &QLineEdit::textChanged, this, &SettingsBrowserMail::dirtifySettings);
connect(m_ui->m_txtExternalEmailArguments, &QLineEdit::textChanged, this, &SettingsBrowserMail::dirtifySettings); connect(m_ui->m_txtExternalEmailArguments, &QLineEdit::textChanged, this, &SettingsBrowserMail::dirtifySettings);
connect(m_ui->m_txtExternalEmailExecutable, &QLineEdit::textChanged, this, &SettingsBrowserMail::dirtifySettings); connect(m_ui->m_txtExternalEmailExecutable, &QLineEdit::textChanged, this, &SettingsBrowserMail::dirtifySettings);
connect(m_ui->m_cmbProxyType, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &SettingsBrowserMail::onProxyTypeChanged); connect(m_ui->m_cmbProxyType, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &SettingsBrowserMail::onProxyTypeChanged);
connect(m_ui->m_checkShowPassword, &QCheckBox::stateChanged, this, &SettingsBrowserMail::displayProxyPassword); connect(m_ui->m_checkShowPassword, &QCheckBox::stateChanged, this, &SettingsBrowserMail::displayProxyPassword);
connect(m_ui->m_cmbExternalBrowserPreset, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &SettingsBrowserMail::changeDefaultBrowserArguments); connect(m_ui->m_cmbExternalBrowserPreset, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &SettingsBrowserMail::changeDefaultBrowserArguments);
@ -75,11 +71,11 @@ void SettingsBrowserMail::selectBrowserExecutable() {
tr("Select web browser executable"), tr("Select web browser executable"),
qApp->getHomeFolderPath(), qApp->getHomeFolderPath(),
//: File filter for external browser selection dialog. //: File filter for external browser selection dialog.
#if defined(Q_OS_LINUX) #if defined(Q_OS_LINUX)
tr("Executables (*)") tr("Executables (*)")
#else #else
tr("Executables (*.*)") tr("Executables (*.*)")
#endif #endif
); );
if (!executable_file.isEmpty()) { if (!executable_file.isEmpty()) {
@ -91,6 +87,7 @@ void SettingsBrowserMail::displayProxyPassword(int state) {
if (state == Qt::Checked) { if (state == Qt::Checked) {
m_ui->m_txtProxyPassword->setEchoMode(QLineEdit::Normal); m_ui->m_txtProxyPassword->setEchoMode(QLineEdit::Normal);
} }
else { else {
m_ui->m_txtProxyPassword->setEchoMode(QLineEdit::PasswordEchoOnEdit); m_ui->m_txtProxyPassword->setEchoMode(QLineEdit::PasswordEchoOnEdit);
} }
@ -99,7 +96,6 @@ void SettingsBrowserMail::displayProxyPassword(int state) {
void SettingsBrowserMail::onProxyTypeChanged(int index) { void SettingsBrowserMail::onProxyTypeChanged(int index) {
const QNetworkProxy::ProxyType selected_type = static_cast<QNetworkProxy::ProxyType>(m_ui->m_cmbProxyType->itemData(index).toInt()); const QNetworkProxy::ProxyType selected_type = static_cast<QNetworkProxy::ProxyType>(m_ui->m_cmbProxyType->itemData(index).toInt());
const bool is_proxy_selected = selected_type != QNetworkProxy::NoProxy && selected_type != QNetworkProxy::DefaultProxy; const bool is_proxy_selected = selected_type != QNetworkProxy::NoProxy && selected_type != QNetworkProxy::DefaultProxy;
m_ui->m_txtProxyHost->setEnabled(is_proxy_selected); m_ui->m_txtProxyHost->setEnabled(is_proxy_selected);
m_ui->m_txtProxyPassword->setEnabled(is_proxy_selected); m_ui->m_txtProxyPassword->setEnabled(is_proxy_selected);
m_ui->m_txtProxyUsername->setEnabled(is_proxy_selected); m_ui->m_txtProxyUsername->setEnabled(is_proxy_selected);
@ -123,11 +119,11 @@ void SettingsBrowserMail::selectEmailExecutable() {
tr("Select e-mail executable"), tr("Select e-mail executable"),
qApp->getHomeFolderPath(), qApp->getHomeFolderPath(),
//: File filter for external e-mail selection dialog. //: File filter for external e-mail selection dialog.
#if defined(Q_OS_LINUX) #if defined(Q_OS_LINUX)
tr("Executables (*)") tr("Executables (*)")
#else #else
tr("Executables (*.*)") tr("Executables (*.*)")
#endif #endif
); );
if (!executable_file.isEmpty()) { if (!executable_file.isEmpty()) {
@ -137,66 +133,53 @@ void SettingsBrowserMail::selectEmailExecutable() {
void SettingsBrowserMail::loadSettings() { void SettingsBrowserMail::loadSettings() {
onBeginLoadSettings(); onBeginLoadSettings();
#if !defined(USE_WEBENGINE) #if !defined(USE_WEBENGINE)
m_ui->m_checkOpenLinksInExternal->setChecked(settings()->value(GROUP(Browser), m_ui->m_checkOpenLinksInExternal->setChecked(settings()->value(GROUP(Browser),
SETTING(Browser::OpenLinksInExternalBrowserRightAway)).toBool()); SETTING(Browser::OpenLinksInExternalBrowserRightAway)).toBool());
#endif #endif
// Load settings of web browser GUI. // Load settings of web browser GUI.
m_ui->m_cmbExternalBrowserPreset->addItem(tr("Opera 12 or older"), QSL("-nosession %1")); m_ui->m_cmbExternalBrowserPreset->addItem(tr("Opera 12 or older"), QSL("-nosession %1"));
m_ui->m_txtExternalBrowserExecutable->setText(settings()->value(GROUP(Browser), SETTING(Browser::CustomExternalBrowserExecutable)).toString()); m_ui->m_txtExternalBrowserExecutable->setText(settings()->value(GROUP(Browser), SETTING(Browser::CustomExternalBrowserExecutable)).toString());
m_ui->m_txtExternalBrowserArguments->setText(settings()->value(GROUP(Browser), SETTING(Browser::CustomExternalBrowserArguments)).toString()); m_ui->m_txtExternalBrowserArguments->setText(settings()->value(GROUP(Browser), SETTING(Browser::CustomExternalBrowserArguments)).toString());
m_ui->m_grpCustomExternalBrowser->setChecked(settings()->value(GROUP(Browser), SETTING(Browser::CustomExternalBrowserEnabled)).toBool()); m_ui->m_grpCustomExternalBrowser->setChecked(settings()->value(GROUP(Browser), SETTING(Browser::CustomExternalBrowserEnabled)).toBool());
// Load settings of e-mail. // Load settings of e-mail.
m_ui->m_cmbExternalEmailPreset->addItem(tr("Mozilla Thunderbird"), QSL("-compose \"subject='%1',body='%2'\"")); m_ui->m_cmbExternalEmailPreset->addItem(tr("Mozilla Thunderbird"), QSL("-compose \"subject='%1',body='%2'\""));
m_ui->m_txtExternalEmailExecutable->setText(settings()->value(GROUP(Browser), SETTING(Browser::CustomExternalEmailExecutable)).toString()); m_ui->m_txtExternalEmailExecutable->setText(settings()->value(GROUP(Browser), SETTING(Browser::CustomExternalEmailExecutable)).toString());
m_ui->m_txtExternalEmailArguments->setText(settings()->value(GROUP(Browser), SETTING(Browser::CustomExternalEmailArguments)).toString()); m_ui->m_txtExternalEmailArguments->setText(settings()->value(GROUP(Browser), SETTING(Browser::CustomExternalEmailArguments)).toString());
m_ui->m_grpCustomExternalEmail->setChecked(settings()->value(GROUP(Browser), SETTING(Browser::CustomExternalEmailEnabled)).toBool()); m_ui->m_grpCustomExternalEmail->setChecked(settings()->value(GROUP(Browser), SETTING(Browser::CustomExternalEmailEnabled)).toBool());
m_ui->m_cmbProxyType->addItem(tr("No proxy"), QNetworkProxy::NoProxy); m_ui->m_cmbProxyType->addItem(tr("No proxy"), QNetworkProxy::NoProxy);
m_ui->m_cmbProxyType->addItem(tr("System proxy"), QNetworkProxy::DefaultProxy); m_ui->m_cmbProxyType->addItem(tr("System proxy"), QNetworkProxy::DefaultProxy);
m_ui->m_cmbProxyType->addItem(tr("Socks5"), QNetworkProxy::Socks5Proxy); m_ui->m_cmbProxyType->addItem(tr("Socks5"), QNetworkProxy::Socks5Proxy);
m_ui->m_cmbProxyType->addItem(tr("Http"), QNetworkProxy::HttpProxy); m_ui->m_cmbProxyType->addItem(tr("Http"), QNetworkProxy::HttpProxy);
// Load the settings. // Load the settings.
QNetworkProxy::ProxyType selected_proxy_type = static_cast<QNetworkProxy::ProxyType>(settings()->value(GROUP(Proxy), SETTING(Proxy::Type)).toInt()); QNetworkProxy::ProxyType selected_proxy_type = static_cast<QNetworkProxy::ProxyType>(settings()->value(GROUP(Proxy), SETTING(Proxy::Type)).toInt());
m_ui->m_cmbProxyType->setCurrentIndex(m_ui->m_cmbProxyType->findData(selected_proxy_type)); m_ui->m_cmbProxyType->setCurrentIndex(m_ui->m_cmbProxyType->findData(selected_proxy_type));
m_ui->m_txtProxyHost->setText(settings()->value(GROUP(Proxy), SETTING(Proxy::Host)).toString()); m_ui->m_txtProxyHost->setText(settings()->value(GROUP(Proxy), SETTING(Proxy::Host)).toString());
m_ui->m_txtProxyUsername->setText(settings()->value(GROUP(Proxy), SETTING(Proxy::Username)).toString()); m_ui->m_txtProxyUsername->setText(settings()->value(GROUP(Proxy), SETTING(Proxy::Username)).toString());
m_ui->m_txtProxyPassword->setText(TextFactory::decrypt(settings()->value(GROUP(Proxy), SETTING(Proxy::Password)).toString())); m_ui->m_txtProxyPassword->setText(TextFactory::decrypt(settings()->value(GROUP(Proxy), SETTING(Proxy::Password)).toString()));
m_ui->m_spinProxyPort->setValue(settings()->value(GROUP(Proxy), SETTING(Proxy::Port)).toInt()); m_ui->m_spinProxyPort->setValue(settings()->value(GROUP(Proxy), SETTING(Proxy::Port)).toInt());
onEndLoadSettings(); onEndLoadSettings();
} }
void SettingsBrowserMail::saveSettings() { void SettingsBrowserMail::saveSettings() {
onBeginSaveSettings(); onBeginSaveSettings();
#if !defined(USE_WEBENGINE) #if !defined(USE_WEBENGINE)
settings()->setValue(GROUP(Browser), Browser::OpenLinksInExternalBrowserRightAway, m_ui->m_checkOpenLinksInExternal->isChecked()); settings()->setValue(GROUP(Browser), Browser::OpenLinksInExternalBrowserRightAway, m_ui->m_checkOpenLinksInExternal->isChecked());
#endif #endif
// Save settings of GUI of web browser. // Save settings of GUI of web browser.
settings()->setValue(GROUP(Browser), Browser::CustomExternalBrowserEnabled, m_ui->m_grpCustomExternalBrowser->isChecked()); settings()->setValue(GROUP(Browser), Browser::CustomExternalBrowserEnabled, m_ui->m_grpCustomExternalBrowser->isChecked());
settings()->setValue(GROUP(Browser), Browser::CustomExternalBrowserExecutable, m_ui->m_txtExternalBrowserExecutable->text()); settings()->setValue(GROUP(Browser), Browser::CustomExternalBrowserExecutable, m_ui->m_txtExternalBrowserExecutable->text());
settings()->setValue(GROUP(Browser), Browser::CustomExternalBrowserArguments, m_ui->m_txtExternalBrowserArguments->text()); settings()->setValue(GROUP(Browser), Browser::CustomExternalBrowserArguments, m_ui->m_txtExternalBrowserArguments->text());
// Save settings of e-mail. // Save settings of e-mail.
settings()->setValue(GROUP(Browser), Browser::CustomExternalEmailExecutable, m_ui->m_txtExternalEmailExecutable->text()); settings()->setValue(GROUP(Browser), Browser::CustomExternalEmailExecutable, m_ui->m_txtExternalEmailExecutable->text());
settings()->setValue(GROUP(Browser), Browser::CustomExternalEmailArguments, m_ui->m_txtExternalEmailArguments->text()); settings()->setValue(GROUP(Browser), Browser::CustomExternalEmailArguments, m_ui->m_txtExternalEmailArguments->text());
settings()->setValue(GROUP(Browser), Browser::CustomExternalEmailEnabled, m_ui->m_grpCustomExternalEmail->isChecked()); settings()->setValue(GROUP(Browser), Browser::CustomExternalEmailEnabled, m_ui->m_grpCustomExternalEmail->isChecked());
settings()->setValue(GROUP(Proxy), Proxy::Type, m_ui->m_cmbProxyType->itemData(m_ui->m_cmbProxyType->currentIndex())); settings()->setValue(GROUP(Proxy), Proxy::Type, m_ui->m_cmbProxyType->itemData(m_ui->m_cmbProxyType->currentIndex()));
settings()->setValue(GROUP(Proxy), Proxy::Host, m_ui->m_txtProxyHost->text()); settings()->setValue(GROUP(Proxy), Proxy::Host, m_ui->m_txtProxyHost->text());
settings()->setValue(GROUP(Proxy), Proxy::Username, m_ui->m_txtProxyUsername->text()); settings()->setValue(GROUP(Proxy), Proxy::Username, m_ui->m_txtProxyUsername->text());
settings()->setValue(GROUP(Proxy), Proxy::Password, TextFactory::encrypt(m_ui->m_txtProxyPassword->text())); settings()->setValue(GROUP(Proxy), Proxy::Password, TextFactory::encrypt(m_ui->m_txtProxyPassword->text()));
settings()->setValue(GROUP(Proxy), Proxy::Port, m_ui->m_spinProxyPort->value()); settings()->setValue(GROUP(Proxy), Proxy::Port, m_ui->m_spinProxyPort->value());
// Reload settings for all network access managers. // Reload settings for all network access managers.
SilentNetworkAccessManager::instance()->loadSettings(); SilentNetworkAccessManager::instance()->loadSettings();
onEndSaveSettings(); onEndSaveSettings();
} }

View File

@ -27,7 +27,7 @@ class SettingsBrowserMail : public SettingsPanel {
Q_OBJECT Q_OBJECT
public: public:
explicit SettingsBrowserMail(Settings *settings, QWidget *parent = 0); explicit SettingsBrowserMail(Settings* settings, QWidget* parent = 0);
virtual ~SettingsBrowserMail(); virtual ~SettingsBrowserMail();
inline QString title() const { inline QString title() const {
@ -46,7 +46,7 @@ class SettingsBrowserMail : public SettingsPanel {
void onProxyTypeChanged(int index); void onProxyTypeChanged(int index);
private: private:
Ui::SettingsBrowserMail *m_ui; Ui::SettingsBrowserMail* m_ui;
}; };
#endif // SETTINGSBROWSERMAIL_H #endif // SETTINGSBROWSERMAIL_H

View File

@ -24,14 +24,12 @@
#include "gui/guiutilities.h" #include "gui/guiutilities.h"
SettingsDatabase::SettingsDatabase(Settings *settings, QWidget *parent) SettingsDatabase::SettingsDatabase(Settings* settings, QWidget* parent)
: SettingsPanel(settings, parent), m_ui(new Ui::SettingsDatabase) { : SettingsPanel(settings, parent), m_ui(new Ui::SettingsDatabase) {
m_ui->setupUi(this); m_ui->setupUi(this);
GuiUtilities::setLabelAsNotice(m_ui->m_lblDataStorageWarning, true); GuiUtilities::setLabelAsNotice(m_ui->m_lblDataStorageWarning, true);
GuiUtilities::setLabelAsNotice(m_ui->m_lblMysqlInfo, false); GuiUtilities::setLabelAsNotice(m_ui->m_lblMysqlInfo, false);
GuiUtilities::setLabelAsNotice(m_ui->m_lblSqliteInMemoryWarnings, true); GuiUtilities::setLabelAsNotice(m_ui->m_lblSqliteInMemoryWarnings, true);
connect(m_ui->m_cmbDatabaseDriver, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &SettingsDatabase::dirtifySettings); connect(m_ui->m_cmbDatabaseDriver, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &SettingsDatabase::dirtifySettings);
connect(m_ui->m_checkSqliteUseInMemoryDatabase, &QCheckBox::toggled, this, &SettingsDatabase::dirtifySettings); connect(m_ui->m_checkSqliteUseInMemoryDatabase, &QCheckBox::toggled, this, &SettingsDatabase::dirtifySettings);
connect(m_ui->m_txtMysqlDatabase->lineEdit(), &QLineEdit::textChanged, this, &SettingsDatabase::dirtifySettings); connect(m_ui->m_txtMysqlDatabase->lineEdit(), &QLineEdit::textChanged, this, &SettingsDatabase::dirtifySettings);
@ -40,7 +38,6 @@ SettingsDatabase::SettingsDatabase(Settings *settings, QWidget *parent)
connect(m_ui->m_checkUseTransactions, &QCheckBox::toggled, this, &SettingsDatabase::dirtifySettings); connect(m_ui->m_checkUseTransactions, &QCheckBox::toggled, this, &SettingsDatabase::dirtifySettings);
connect(m_ui->m_txtMysqlUsername->lineEdit(), &QLineEdit::textChanged, this, &SettingsDatabase::dirtifySettings); connect(m_ui->m_txtMysqlUsername->lineEdit(), &QLineEdit::textChanged, this, &SettingsDatabase::dirtifySettings);
connect(m_ui->m_spinMysqlPort, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &SettingsDatabase::dirtifySettings); connect(m_ui->m_spinMysqlPort, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &SettingsDatabase::dirtifySettings);
connect(m_ui->m_cmbDatabaseDriver, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &SettingsDatabase::selectSqlBackend); connect(m_ui->m_cmbDatabaseDriver, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &SettingsDatabase::selectSqlBackend);
connect(m_ui->m_checkMysqlShowPassword, &QCheckBox::toggled, this, &SettingsDatabase::switchMysqlPasswordVisiblity); connect(m_ui->m_checkMysqlShowPassword, &QCheckBox::toggled, this, &SettingsDatabase::switchMysqlPasswordVisiblity);
connect(m_ui->m_txtMysqlUsername->lineEdit(), &BaseLineEdit::textChanged, this, &SettingsDatabase::onMysqlUsernameChanged); connect(m_ui->m_txtMysqlUsername->lineEdit(), &BaseLineEdit::textChanged, this, &SettingsDatabase::onMysqlUsernameChanged);
@ -48,7 +45,6 @@ SettingsDatabase::SettingsDatabase(Settings *settings, QWidget *parent)
connect(m_ui->m_txtMysqlPassword->lineEdit(), &BaseLineEdit::textChanged, this, &SettingsDatabase::onMysqlPasswordChanged); connect(m_ui->m_txtMysqlPassword->lineEdit(), &BaseLineEdit::textChanged, this, &SettingsDatabase::onMysqlPasswordChanged);
connect(m_ui->m_txtMysqlDatabase->lineEdit(), &BaseLineEdit::textChanged, this, &SettingsDatabase::onMysqlDatabaseChanged); connect(m_ui->m_txtMysqlDatabase->lineEdit(), &BaseLineEdit::textChanged, this, &SettingsDatabase::onMysqlDatabaseChanged);
connect(m_ui->m_btnMysqlTestSetup, &QPushButton::clicked, this, &SettingsDatabase::mysqlTestConnection); connect(m_ui->m_btnMysqlTestSetup, &QPushButton::clicked, this, &SettingsDatabase::mysqlTestConnection);
connect(m_ui->m_cmbDatabaseDriver, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &SettingsDatabase::requireRestart); connect(m_ui->m_cmbDatabaseDriver, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &SettingsDatabase::requireRestart);
connect(m_ui->m_checkSqliteUseInMemoryDatabase, &QCheckBox::toggled, this, &SettingsDatabase::requireRestart); connect(m_ui->m_checkSqliteUseInMemoryDatabase, &QCheckBox::toggled, this, &SettingsDatabase::requireRestart);
connect(m_ui->m_spinMysqlPort, &QSpinBox::editingFinished, this, &SettingsDatabase::requireRestart); connect(m_ui->m_spinMysqlPort, &QSpinBox::editingFinished, this, &SettingsDatabase::requireRestart);
@ -69,7 +65,6 @@ void SettingsDatabase::mysqlTestConnection() {
m_ui->m_txtMysqlPassword->lineEdit()->text()); m_ui->m_txtMysqlPassword->lineEdit()->text());
const QString interpretation = qApp->database()->mysqlInterpretErrorCode(error_code); const QString interpretation = qApp->database()->mysqlInterpretErrorCode(error_code);
switch (error_code) { switch (error_code) {
case DatabaseFactory::MySQLOk: case DatabaseFactory::MySQLOk:
case DatabaseFactory::MySQLUnknownDatabase: case DatabaseFactory::MySQLUnknownDatabase:
@ -82,37 +77,41 @@ void SettingsDatabase::mysqlTestConnection() {
} }
} }
void SettingsDatabase::onMysqlHostnameChanged(const QString &new_hostname) { void SettingsDatabase::onMysqlHostnameChanged(const QString& new_hostname) {
if (new_hostname.isEmpty()) { if (new_hostname.isEmpty()) {
m_ui->m_txtMysqlHostname->setStatus(LineEditWithStatus::Warning, tr("Hostname is empty.")); m_ui->m_txtMysqlHostname->setStatus(LineEditWithStatus::Warning, tr("Hostname is empty."));
} }
else { else {
m_ui->m_txtMysqlHostname->setStatus(LineEditWithStatus::Ok, tr("Hostname looks ok.")); m_ui->m_txtMysqlHostname->setStatus(LineEditWithStatus::Ok, tr("Hostname looks ok."));
} }
} }
void SettingsDatabase::onMysqlUsernameChanged(const QString &new_username) { void SettingsDatabase::onMysqlUsernameChanged(const QString& new_username) {
if (new_username.isEmpty()) { if (new_username.isEmpty()) {
m_ui->m_txtMysqlUsername->setStatus(LineEditWithStatus::Warning, tr("Username is empty.")); m_ui->m_txtMysqlUsername->setStatus(LineEditWithStatus::Warning, tr("Username is empty."));
} }
else { else {
m_ui->m_txtMysqlUsername->setStatus(LineEditWithStatus::Ok, tr("Username looks ok.")); m_ui->m_txtMysqlUsername->setStatus(LineEditWithStatus::Ok, tr("Username looks ok."));
} }
} }
void SettingsDatabase::onMysqlPasswordChanged(const QString &new_password) { void SettingsDatabase::onMysqlPasswordChanged(const QString& new_password) {
if (new_password.isEmpty()) { if (new_password.isEmpty()) {
m_ui->m_txtMysqlPassword->setStatus(LineEditWithStatus::Warning, tr("Password is empty.")); m_ui->m_txtMysqlPassword->setStatus(LineEditWithStatus::Warning, tr("Password is empty."));
} }
else { else {
m_ui->m_txtMysqlPassword->setStatus(LineEditWithStatus::Ok, tr("Password looks ok.")); m_ui->m_txtMysqlPassword->setStatus(LineEditWithStatus::Ok, tr("Password looks ok."));
} }
} }
void SettingsDatabase::onMysqlDatabaseChanged(const QString &new_database) { void SettingsDatabase::onMysqlDatabaseChanged(const QString& new_database) {
if (new_database.isEmpty()) { if (new_database.isEmpty()) {
m_ui->m_txtMysqlDatabase->setStatus(LineEditWithStatus::Warning, tr("Working database is empty.")); m_ui->m_txtMysqlDatabase->setStatus(LineEditWithStatus::Warning, tr("Working database is empty."));
} }
else { else {
m_ui->m_txtMysqlDatabase->setStatus(LineEditWithStatus::Ok, tr("Working database is ok.")); m_ui->m_txtMysqlDatabase->setStatus(LineEditWithStatus::Ok, tr("Working database is ok."));
} }
@ -124,9 +123,11 @@ void SettingsDatabase::selectSqlBackend(int index) {
if (selected_db_driver == APP_DB_SQLITE_DRIVER) { if (selected_db_driver == APP_DB_SQLITE_DRIVER) {
m_ui->m_stackedDatabaseDriver->setCurrentIndex(0); m_ui->m_stackedDatabaseDriver->setCurrentIndex(0);
} }
else if (selected_db_driver == APP_DB_MYSQL_DRIVER) { else if (selected_db_driver == APP_DB_MYSQL_DRIVER) {
m_ui->m_stackedDatabaseDriver->setCurrentIndex(1); m_ui->m_stackedDatabaseDriver->setCurrentIndex(1);
} }
else { else {
qWarning("GUI for given database driver '%s' is not available.", qPrintable(selected_db_driver)); qWarning("GUI for given database driver '%s' is not available.", qPrintable(selected_db_driver));
} }
@ -138,13 +139,10 @@ void SettingsDatabase::switchMysqlPasswordVisiblity(bool visible) {
void SettingsDatabase::loadSettings() { void SettingsDatabase::loadSettings() {
onBeginLoadSettings(); onBeginLoadSettings();
m_ui->m_checkUseTransactions->setChecked(qApp->settings()->value(GROUP(Database), SETTING(Database::UseTransactions)).toBool()); m_ui->m_checkUseTransactions->setChecked(qApp->settings()->value(GROUP(Database), SETTING(Database::UseTransactions)).toBool());
m_ui->m_lblMysqlTestResult->setStatus(WidgetWithStatus::Information, tr("No connection test triggered so far."), tr("You did not executed any connection test yet.")); m_ui->m_lblMysqlTestResult->setStatus(WidgetWithStatus::Information, tr("No connection test triggered so far."), tr("You did not executed any connection test yet."));
// Load SQLite. // Load SQLite.
m_ui->m_cmbDatabaseDriver->addItem(qApp->database()->humanDriverName(DatabaseFactory::SQLITE), APP_DB_SQLITE_DRIVER); m_ui->m_cmbDatabaseDriver->addItem(qApp->database()->humanDriverName(DatabaseFactory::SQLITE), APP_DB_SQLITE_DRIVER);
// Load in-memory database status. // Load in-memory database status.
m_ui->m_checkSqliteUseInMemoryDatabase->setChecked(settings()->value(GROUP(Database), SETTING(Database::UseInMemory)).toBool()); m_ui->m_checkSqliteUseInMemoryDatabase->setChecked(settings()->value(GROUP(Database), SETTING(Database::UseInMemory)).toBool());
@ -153,22 +151,18 @@ void SettingsDatabase::loadSettings() {
onMysqlUsernameChanged(QString()); onMysqlUsernameChanged(QString());
onMysqlPasswordChanged(QString()); onMysqlPasswordChanged(QString());
onMysqlDatabaseChanged(QString()); onMysqlDatabaseChanged(QString());
// Load MySQL. // Load MySQL.
m_ui->m_cmbDatabaseDriver->addItem(qApp->database()->humanDriverName(DatabaseFactory::MYSQL), APP_DB_MYSQL_DRIVER); m_ui->m_cmbDatabaseDriver->addItem(qApp->database()->humanDriverName(DatabaseFactory::MYSQL), APP_DB_MYSQL_DRIVER);
// Setup placeholders. // Setup placeholders.
m_ui->m_txtMysqlHostname->lineEdit()->setPlaceholderText(tr("Hostname of your MySQL server")); m_ui->m_txtMysqlHostname->lineEdit()->setPlaceholderText(tr("Hostname of your MySQL server"));
m_ui->m_txtMysqlUsername->lineEdit()->setPlaceholderText(tr("Username to login with")); m_ui->m_txtMysqlUsername->lineEdit()->setPlaceholderText(tr("Username to login with"));
m_ui->m_txtMysqlPassword->lineEdit()->setPlaceholderText(tr("Password for your username")); m_ui->m_txtMysqlPassword->lineEdit()->setPlaceholderText(tr("Password for your username"));
m_ui->m_txtMysqlDatabase->lineEdit()->setPlaceholderText(tr("Working database which you have full access to.")); m_ui->m_txtMysqlDatabase->lineEdit()->setPlaceholderText(tr("Working database which you have full access to."));
m_ui->m_txtMysqlHostname->lineEdit()->setText(settings()->value(GROUP(Database), SETTING(Database::MySQLHostname)).toString()); m_ui->m_txtMysqlHostname->lineEdit()->setText(settings()->value(GROUP(Database), SETTING(Database::MySQLHostname)).toString());
m_ui->m_txtMysqlUsername->lineEdit()->setText(settings()->value(GROUP(Database), SETTING(Database::MySQLUsername)).toString()); m_ui->m_txtMysqlUsername->lineEdit()->setText(settings()->value(GROUP(Database), SETTING(Database::MySQLUsername)).toString());
m_ui->m_txtMysqlPassword->lineEdit()->setText(TextFactory::decrypt(settings()->value(GROUP(Database), SETTING(Database::MySQLPassword)).toString())); m_ui->m_txtMysqlPassword->lineEdit()->setText(TextFactory::decrypt(settings()->value(GROUP(Database), SETTING(Database::MySQLPassword)).toString()));
m_ui->m_txtMysqlDatabase->lineEdit()->setText(settings()->value(GROUP(Database), SETTING(Database::MySQLDatabase)).toString()); m_ui->m_txtMysqlDatabase->lineEdit()->setText(settings()->value(GROUP(Database), SETTING(Database::MySQLDatabase)).toString());
m_ui->m_spinMysqlPort->setValue(settings()->value(GROUP(Database), SETTING(Database::MySQLPort)).toInt()); m_ui->m_spinMysqlPort->setValue(settings()->value(GROUP(Database), SETTING(Database::MySQLPort)).toInt());
m_ui->m_checkMysqlShowPassword->setChecked(false); m_ui->m_checkMysqlShowPassword->setChecked(false);
} }
@ -183,17 +177,13 @@ void SettingsDatabase::loadSettings() {
void SettingsDatabase::saveSettings() { void SettingsDatabase::saveSettings() {
onBeginSaveSettings(); onBeginSaveSettings();
// Setup in-memory database status. // Setup in-memory database status.
const bool original_inmemory = settings()->value(GROUP(Database), SETTING(Database::UseInMemory)).toBool(); const bool original_inmemory = settings()->value(GROUP(Database), SETTING(Database::UseInMemory)).toBool();
const bool new_inmemory = m_ui->m_checkSqliteUseInMemoryDatabase->isChecked(); const bool new_inmemory = m_ui->m_checkSqliteUseInMemoryDatabase->isChecked();
qApp->settings()->setValue(GROUP(Database), Database::UseTransactions, m_ui->m_checkUseTransactions->isChecked()); qApp->settings()->setValue(GROUP(Database), Database::UseTransactions, m_ui->m_checkUseTransactions->isChecked());
// Save data storage settings. // Save data storage settings.
QString original_db_driver = settings()->value(GROUP(Database), SETTING(Database::ActiveDriver)).toString(); QString original_db_driver = settings()->value(GROUP(Database), SETTING(Database::ActiveDriver)).toString();
QString selected_db_driver = m_ui->m_cmbDatabaseDriver->itemData(m_ui->m_cmbDatabaseDriver->currentIndex()).toString(); QString selected_db_driver = m_ui->m_cmbDatabaseDriver->itemData(m_ui->m_cmbDatabaseDriver->currentIndex()).toString();
// Save SQLite. // Save SQLite.
settings()->setValue(GROUP(Database), Database::UseInMemory, new_inmemory); settings()->setValue(GROUP(Database), Database::UseInMemory, new_inmemory);

View File

@ -27,7 +27,7 @@ class SettingsDatabase : public SettingsPanel {
Q_OBJECT Q_OBJECT
public: public:
explicit SettingsDatabase(Settings *settings, QWidget *parent = 0); explicit SettingsDatabase(Settings* settings, QWidget* parent = 0);
virtual ~SettingsDatabase(); virtual ~SettingsDatabase();
inline QString title() const { inline QString title() const {
@ -39,14 +39,14 @@ class SettingsDatabase : public SettingsPanel {
private: private:
void mysqlTestConnection(); void mysqlTestConnection();
void onMysqlHostnameChanged(const QString &new_hostname); void onMysqlHostnameChanged(const QString& new_hostname);
void onMysqlUsernameChanged(const QString &new_username); void onMysqlUsernameChanged(const QString& new_username);
void onMysqlPasswordChanged(const QString &new_password); void onMysqlPasswordChanged(const QString& new_password);
void onMysqlDatabaseChanged(const QString &new_database); void onMysqlDatabaseChanged(const QString& new_database);
void selectSqlBackend(int index); void selectSqlBackend(int index);
void switchMysqlPasswordVisiblity(bool visible); void switchMysqlPasswordVisiblity(bool visible);
Ui::SettingsDatabase *m_ui; Ui::SettingsDatabase* m_ui;
}; };
#endif // SETTINGSDATABASE_H #endif // SETTINGSDATABASE_H

View File

@ -24,14 +24,12 @@
#include <QFileDialog> #include <QFileDialog>
SettingsDownloads::SettingsDownloads(Settings *settings, QWidget *parent) SettingsDownloads::SettingsDownloads(Settings* settings, QWidget* parent)
: SettingsPanel(settings, parent), m_ui(new Ui::SettingsDownloads) { : SettingsPanel(settings, parent), m_ui(new Ui::SettingsDownloads) {
m_ui->setupUi(this); m_ui->setupUi(this);
connect(m_ui->m_checkOpenManagerWhenDownloadStarts, &QCheckBox::toggled, this, &SettingsDownloads::dirtifySettings); connect(m_ui->m_checkOpenManagerWhenDownloadStarts, &QCheckBox::toggled, this, &SettingsDownloads::dirtifySettings);
connect(m_ui->m_txtDownloadsTargetDirectory, &QLineEdit::textChanged, this, &SettingsDownloads::dirtifySettings); connect(m_ui->m_txtDownloadsTargetDirectory, &QLineEdit::textChanged, this, &SettingsDownloads::dirtifySettings);
connect(m_ui->m_rbDownloadsAskEachFile, &QRadioButton::toggled, this, &SettingsDownloads::dirtifySettings); connect(m_ui->m_rbDownloadsAskEachFile, &QRadioButton::toggled, this, &SettingsDownloads::dirtifySettings);
connect(m_ui->m_btnDownloadsTargetDirectory, &QPushButton::clicked, this, &SettingsDownloads::selectDownloadsDirectory); connect(m_ui->m_btnDownloadsTargetDirectory, &QPushButton::clicked, this, &SettingsDownloads::selectDownloadsDirectory);
} }
@ -52,24 +50,20 @@ void SettingsDownloads::selectDownloadsDirectory() {
void SettingsDownloads::loadSettings() { void SettingsDownloads::loadSettings() {
onBeginLoadSettings(); onBeginLoadSettings();
m_ui->m_checkOpenManagerWhenDownloadStarts->setChecked(settings()->value(GROUP(Downloads), m_ui->m_checkOpenManagerWhenDownloadStarts->setChecked(settings()->value(GROUP(Downloads),
SETTING(Downloads::ShowDownloadsWhenNewDownloadStarts)).toBool()); SETTING(Downloads::ShowDownloadsWhenNewDownloadStarts)).toBool());
m_ui->m_txtDownloadsTargetDirectory->setText(QDir::toNativeSeparators(settings()->value(GROUP(Downloads), m_ui->m_txtDownloadsTargetDirectory->setText(QDir::toNativeSeparators(settings()->value(GROUP(Downloads),
SETTING(Downloads::TargetDirectory)).toString())); SETTING(Downloads::TargetDirectory)).toString()));
m_ui->m_rbDownloadsAskEachFile->setChecked(settings()->value(GROUP(Downloads), m_ui->m_rbDownloadsAskEachFile->setChecked(settings()->value(GROUP(Downloads),
SETTING(Downloads::AlwaysPromptForFilename)).toBool()); SETTING(Downloads::AlwaysPromptForFilename)).toBool());
onEndLoadSettings(); onEndLoadSettings();
} }
void SettingsDownloads::saveSettings() { void SettingsDownloads::saveSettings() {
onBeginSaveSettings(); onBeginSaveSettings();
settings()->setValue(GROUP(Downloads), Downloads::ShowDownloadsWhenNewDownloadStarts, m_ui->m_checkOpenManagerWhenDownloadStarts->isChecked()); settings()->setValue(GROUP(Downloads), Downloads::ShowDownloadsWhenNewDownloadStarts, m_ui->m_checkOpenManagerWhenDownloadStarts->isChecked());
settings()->setValue(GROUP(Downloads), Downloads::TargetDirectory, m_ui->m_txtDownloadsTargetDirectory->text()); settings()->setValue(GROUP(Downloads), Downloads::TargetDirectory, m_ui->m_txtDownloadsTargetDirectory->text());
settings()->setValue(GROUP(Downloads), Downloads::AlwaysPromptForFilename, m_ui->m_rbDownloadsAskEachFile->isChecked()); settings()->setValue(GROUP(Downloads), Downloads::AlwaysPromptForFilename, m_ui->m_rbDownloadsAskEachFile->isChecked());
qApp->downloadManager()->setDownloadDirectory(m_ui->m_txtDownloadsTargetDirectory->text()); qApp->downloadManager()->setDownloadDirectory(m_ui->m_txtDownloadsTargetDirectory->text());
onEndSaveSettings(); onEndSaveSettings();
} }

View File

@ -27,7 +27,7 @@ class SettingsDownloads : public SettingsPanel {
Q_OBJECT Q_OBJECT
public: public:
explicit SettingsDownloads(Settings *settings, QWidget *parent = 0); explicit SettingsDownloads(Settings* settings, QWidget* parent = 0);
virtual ~SettingsDownloads(); virtual ~SettingsDownloads();
inline QString title() const { inline QString title() const {
@ -41,7 +41,7 @@ class SettingsDownloads : public SettingsPanel {
void selectDownloadsDirectory(); void selectDownloadsDirectory();
private: private:
Ui::SettingsDownloads *m_ui; Ui::SettingsDownloads* m_ui;
}; };
#endif // SETTINGSDOWNLOADS_H #endif // SETTINGSDOWNLOADS_H

View File

@ -30,13 +30,11 @@
#include <QFontDialog> #include <QFontDialog>
SettingsFeedsMessages::SettingsFeedsMessages(Settings *settings, QWidget *parent) SettingsFeedsMessages::SettingsFeedsMessages(Settings* settings, QWidget* parent)
: SettingsPanel(settings, parent), m_ui(new Ui::SettingsFeedsMessages){ : SettingsPanel(settings, parent), m_ui(new Ui::SettingsFeedsMessages) {
m_ui->setupUi(this); m_ui->setupUi(this);
initializeMessageDateFormats(); initializeMessageDateFormats();
GuiUtilities::setLabelAsNotice(m_ui->label_9, false); GuiUtilities::setLabelAsNotice(m_ui->label_9, false);
connect(m_ui->m_checkAutoUpdateNotification, &QCheckBox::toggled, this, &SettingsFeedsMessages::dirtifySettings); connect(m_ui->m_checkAutoUpdateNotification, &QCheckBox::toggled, this, &SettingsFeedsMessages::dirtifySettings);
connect(m_ui->m_checkAutoUpdate, &QCheckBox::toggled, this, &SettingsFeedsMessages::dirtifySettings); connect(m_ui->m_checkAutoUpdate, &QCheckBox::toggled, this, &SettingsFeedsMessages::dirtifySettings);
connect(m_ui->m_checkKeppMessagesInTheMiddle, &QCheckBox::toggled, this, &SettingsFeedsMessages::dirtifySettings); connect(m_ui->m_checkKeppMessagesInTheMiddle, &QCheckBox::toggled, this, &SettingsFeedsMessages::dirtifySettings);
@ -52,7 +50,6 @@ SettingsFeedsMessages::SettingsFeedsMessages(Settings *settings, QWidget *parent
connect(m_ui->m_cmbMessagesDateTimeFormat, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &SettingsFeedsMessages::dirtifySettings); connect(m_ui->m_cmbMessagesDateTimeFormat, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &SettingsFeedsMessages::dirtifySettings);
connect(m_ui->m_cmbCountsFeedList, &QComboBox::currentTextChanged, this, &SettingsFeedsMessages::dirtifySettings); connect(m_ui->m_cmbCountsFeedList, &QComboBox::currentTextChanged, this, &SettingsFeedsMessages::dirtifySettings);
connect(m_ui->m_cmbCountsFeedList, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &SettingsFeedsMessages::dirtifySettings); connect(m_ui->m_cmbCountsFeedList, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &SettingsFeedsMessages::dirtifySettings);
connect(m_ui->m_btnChangeMessagesFont, &QPushButton::clicked, this, &SettingsFeedsMessages::changeMessagesFont); connect(m_ui->m_btnChangeMessagesFont, &QPushButton::clicked, this, &SettingsFeedsMessages::changeMessagesFont);
if (!m_ui->m_spinFeedUpdateTimeout->suffix().startsWith(' ')) { if (!m_ui->m_spinFeedUpdateTimeout->suffix().startsWith(' ')) {
@ -65,13 +62,14 @@ SettingsFeedsMessages::~SettingsFeedsMessages() {
} }
void SettingsFeedsMessages::initializeMessageDateFormats() { void SettingsFeedsMessages::initializeMessageDateFormats() {
QStringList best_formats; best_formats << QSL("d/M/yyyy hh:mm:ss") << QSL("ddd, d. M. yy hh:mm:ss") << QStringList best_formats;
best_formats << QSL("d/M/yyyy hh:mm:ss") << QSL("ddd, d. M. yy hh:mm:ss") <<
QSL("yyyy-MM-dd HH:mm:ss.z") << QSL("yyyy-MM-ddThh:mm:ss") << QSL("yyyy-MM-dd HH:mm:ss.z") << QSL("yyyy-MM-ddThh:mm:ss") <<
QSL("MMM d yyyy hh:mm:ss");; QSL("MMM d yyyy hh:mm:ss");;
const QLocale current_locale = qApp->localization()->loadedLocale(); const QLocale current_locale = qApp->localization()->loadedLocale();
const QDateTime current_dt = QDateTime::currentDateTime(); const QDateTime current_dt = QDateTime::currentDateTime();
foreach (const QString &format, best_formats) { foreach (const QString& format, best_formats) {
m_ui->m_cmbMessagesDateTimeFormat->addItem(current_locale.toString(current_dt, format), format); m_ui->m_cmbMessagesDateTimeFormat->addItem(current_locale.toString(current_dt, format), format);
} }
} }
@ -90,7 +88,6 @@ void SettingsFeedsMessages::changeMessagesFont() {
void SettingsFeedsMessages::loadSettings() { void SettingsFeedsMessages::loadSettings() {
onBeginLoadSettings(); onBeginLoadSettings();
m_ui->m_checkAutoUpdateNotification->setChecked(settings()->value(GROUP(Feeds), SETTING(Feeds::EnableAutoUpdateNotification)).toBool()); m_ui->m_checkAutoUpdateNotification->setChecked(settings()->value(GROUP(Feeds), SETTING(Feeds::EnableAutoUpdateNotification)).toBool());
m_ui->m_checkKeppMessagesInTheMiddle->setChecked(settings()->value(GROUP(Messages), SETTING(Messages::KeepCursorInCenter)).toBool()); m_ui->m_checkKeppMessagesInTheMiddle->setChecked(settings()->value(GROUP(Messages), SETTING(Messages::KeepCursorInCenter)).toBool());
m_ui->m_checkRemoveReadMessagesOnExit->setChecked(settings()->value(GROUP(Messages), SETTING(Messages::ClearReadOnExit)).toBool()); m_ui->m_checkRemoveReadMessagesOnExit->setChecked(settings()->value(GROUP(Messages), SETTING(Messages::ClearReadOnExit)).toBool());
@ -101,9 +98,7 @@ void SettingsFeedsMessages::loadSettings() {
m_ui->m_cmbCountsFeedList->addItems(QStringList() << "(%unread)" << "[%unread]" << "%unread/%all" << "%unread-%all" << "[%unread|%all]"); m_ui->m_cmbCountsFeedList->addItems(QStringList() << "(%unread)" << "[%unread]" << "%unread/%all" << "%unread-%all" << "[%unread|%all]");
m_ui->m_cmbCountsFeedList->setEditText(settings()->value(GROUP(Feeds), SETTING(Feeds::CountFormat)).toString()); m_ui->m_cmbCountsFeedList->setEditText(settings()->value(GROUP(Feeds), SETTING(Feeds::CountFormat)).toString());
m_ui->m_spinHeightImageAttachments->setValue(settings()->value(GROUP(Messages), SETTING(Messages::MessageHeadImageHeight)).toInt()); m_ui->m_spinHeightImageAttachments->setValue(settings()->value(GROUP(Messages), SETTING(Messages::MessageHeadImageHeight)).toInt());
initializeMessageDateFormats(); initializeMessageDateFormats();
m_ui->m_checkMessagesDateTimeFormat->setChecked(settings()->value(GROUP(Messages), SETTING(Messages::UseCustomDate)).toBool()); m_ui->m_checkMessagesDateTimeFormat->setChecked(settings()->value(GROUP(Messages), SETTING(Messages::UseCustomDate)).toBool());
const int index_format = m_ui->m_cmbMessagesDateTimeFormat->findData(settings()->value(GROUP(Messages), SETTING(Messages::CustomDateFormat)).toString()); const int index_format = m_ui->m_cmbMessagesDateTimeFormat->findData(settings()->value(GROUP(Messages), SETTING(Messages::CustomDateFormat)).toString());
@ -116,13 +111,11 @@ void SettingsFeedsMessages::loadSettings() {
fon.fromString(settings()->value(GROUP(Messages), fon.fromString(settings()->value(GROUP(Messages),
SETTING(Messages::PreviewerFontStandard)).toString()); SETTING(Messages::PreviewerFontStandard)).toString());
m_ui->m_lblMessagesFont->setFont(fon); m_ui->m_lblMessagesFont->setFont(fon);
onEndLoadSettings(); onEndLoadSettings();
} }
void SettingsFeedsMessages::saveSettings() { void SettingsFeedsMessages::saveSettings() {
onBeginSaveSettings(); onBeginSaveSettings();
settings()->setValue(GROUP(Feeds), Feeds::EnableAutoUpdateNotification, m_ui->m_checkAutoUpdateNotification->isChecked()); settings()->setValue(GROUP(Feeds), Feeds::EnableAutoUpdateNotification, m_ui->m_checkAutoUpdateNotification->isChecked());
settings()->setValue(GROUP(Messages), Messages::KeepCursorInCenter, m_ui->m_checkKeppMessagesInTheMiddle->isChecked()); settings()->setValue(GROUP(Messages), Messages::KeepCursorInCenter, m_ui->m_checkKeppMessagesInTheMiddle->isChecked());
settings()->setValue(GROUP(Messages), Messages::ClearReadOnExit, m_ui->m_checkRemoveReadMessagesOnExit->isChecked()); settings()->setValue(GROUP(Messages), Messages::ClearReadOnExit, m_ui->m_checkRemoveReadMessagesOnExit->isChecked());
@ -135,16 +128,12 @@ void SettingsFeedsMessages::saveSettings() {
settings()->setValue(GROUP(Messages), Messages::MessageHeadImageHeight, m_ui->m_spinHeightImageAttachments->value()); settings()->setValue(GROUP(Messages), Messages::MessageHeadImageHeight, m_ui->m_spinHeightImageAttachments->value());
settings()->setValue(GROUP(Messages), Messages::CustomDateFormat, settings()->setValue(GROUP(Messages), Messages::CustomDateFormat,
m_ui->m_cmbMessagesDateTimeFormat->itemData(m_ui->m_cmbMessagesDateTimeFormat->currentIndex()).toString()); m_ui->m_cmbMessagesDateTimeFormat->itemData(m_ui->m_cmbMessagesDateTimeFormat->currentIndex()).toString());
// Save fonts. // Save fonts.
settings()->setValue(GROUP(Messages), Messages::PreviewerFontStandard, m_ui->m_lblMessagesFont->font().toString()); settings()->setValue(GROUP(Messages), Messages::PreviewerFontStandard, m_ui->m_lblMessagesFont->font().toString());
qApp->mainForm()->tabWidget()->feedMessageViewer()->loadMessageViewerFonts(); qApp->mainForm()->tabWidget()->feedMessageViewer()->loadMessageViewerFonts();
qApp->feedReader()->updateAutoUpdateStatus(); qApp->feedReader()->updateAutoUpdateStatus();
qApp->feedReader()->feedsModel()->reloadWholeLayout(); qApp->feedReader()->feedsModel()->reloadWholeLayout();
qApp->feedReader()->messagesModel()->updateDateFormat(); qApp->feedReader()->messagesModel()->updateDateFormat();
qApp->feedReader()->messagesModel()->reloadWholeLayout(); qApp->feedReader()->messagesModel()->reloadWholeLayout();
onEndSaveSettings(); onEndSaveSettings();
} }

View File

@ -27,7 +27,7 @@ class SettingsFeedsMessages : public SettingsPanel {
Q_OBJECT Q_OBJECT
public: public:
explicit SettingsFeedsMessages(Settings *settings, QWidget *parent = 0); explicit SettingsFeedsMessages(Settings* settings, QWidget* parent = 0);
virtual ~SettingsFeedsMessages(); virtual ~SettingsFeedsMessages();
inline QString title() const { inline QString title() const {
@ -43,7 +43,7 @@ class SettingsFeedsMessages : public SettingsPanel {
private: private:
void initializeMessageDateFormats(); void initializeMessageDateFormats();
Ui::SettingsFeedsMessages *m_ui; Ui::SettingsFeedsMessages* m_ui;
}; };
#endif // SETTINGSFEEDSMESSAGES_H #endif // SETTINGSFEEDSMESSAGES_H

View File

@ -21,11 +21,10 @@
#include "miscellaneous/application.h" #include "miscellaneous/application.h"
SettingsGeneral::SettingsGeneral(Settings *settings, QWidget *parent) SettingsGeneral::SettingsGeneral(Settings* settings, QWidget* parent)
: SettingsPanel(settings, parent), m_ui(new Ui::SettingsGeneral) { : SettingsPanel(settings, parent), m_ui(new Ui::SettingsGeneral) {
m_ui->setupUi(this); m_ui->setupUi(this);
m_ui->m_checkAutostart->setText(m_ui->m_checkAutostart->text().arg(APP_NAME)); m_ui->m_checkAutostart->setText(m_ui->m_checkAutostart->text().arg(APP_NAME));
connect(m_ui->m_checkAutostart, &QCheckBox::stateChanged, this, &SettingsGeneral::dirtifySettings); connect(m_ui->m_checkAutostart, &QCheckBox::stateChanged, this, &SettingsGeneral::dirtifySettings);
connect(m_ui->m_checkForUpdatesOnStart, &QCheckBox::stateChanged, this, &SettingsGeneral::dirtifySettings); connect(m_ui->m_checkForUpdatesOnStart, &QCheckBox::stateChanged, this, &SettingsGeneral::dirtifySettings);
connect(m_ui->m_checkRemoveTrolltechJunk, &QCheckBox::stateChanged, this, &SettingsGeneral::dirtifySettings); connect(m_ui->m_checkRemoveTrolltechJunk, &QCheckBox::stateChanged, this, &SettingsGeneral::dirtifySettings);
@ -37,9 +36,7 @@ SettingsGeneral::~SettingsGeneral() {
void SettingsGeneral::loadSettings() { void SettingsGeneral::loadSettings() {
onBeginLoadSettings(); onBeginLoadSettings();
m_ui->m_checkForUpdatesOnStart->setChecked(settings()->value(GROUP(General), SETTING(General::UpdateOnStartup)).toBool()); m_ui->m_checkForUpdatesOnStart->setChecked(settings()->value(GROUP(General), SETTING(General::UpdateOnStartup)).toBool());
// Load auto-start status. // Load auto-start status.
const SystemFactory::AutoStartStatus autostart_status = qApp->system()->getAutoStartStatus(); const SystemFactory::AutoStartStatus autostart_status = qApp->system()->getAutoStartStatus();
@ -64,7 +61,6 @@ void SettingsGeneral::loadSettings() {
#else #else
m_ui->m_checkRemoveTrolltechJunk->setVisible(false); m_ui->m_checkRemoveTrolltechJunk->setVisible(false);
#endif #endif
onEndLoadSettings(); onEndLoadSettings();
} }
@ -75,12 +71,12 @@ void SettingsGeneral::saveSettings() {
if (m_ui->m_checkAutostart->isChecked()) { if (m_ui->m_checkAutostart->isChecked()) {
qApp->system()->setAutoStartStatus(SystemFactory::Enabled); qApp->system()->setAutoStartStatus(SystemFactory::Enabled);
} }
else { else {
qApp->system()->setAutoStartStatus(SystemFactory::Disabled); qApp->system()->setAutoStartStatus(SystemFactory::Disabled);
} }
settings()->setValue(GROUP(General), General::UpdateOnStartup, m_ui->m_checkForUpdatesOnStart->isChecked()); settings()->setValue(GROUP(General), General::UpdateOnStartup, m_ui->m_checkForUpdatesOnStart->isChecked());
settings()->setValue(GROUP(General), General::RemoveTrolltechJunk, m_ui->m_checkRemoveTrolltechJunk->isChecked()); settings()->setValue(GROUP(General), General::RemoveTrolltechJunk, m_ui->m_checkRemoveTrolltechJunk->isChecked());
onEndSaveSettings(); onEndSaveSettings();
} }

View File

@ -27,7 +27,7 @@ class SettingsGeneral : public SettingsPanel {
Q_OBJECT Q_OBJECT
public: public:
explicit SettingsGeneral(Settings *settings, QWidget *parent = 0); explicit SettingsGeneral(Settings* settings, QWidget* parent = 0);
virtual ~SettingsGeneral(); virtual ~SettingsGeneral();
inline QString title() const { inline QString title() const {
@ -38,7 +38,7 @@ class SettingsGeneral : public SettingsPanel {
void saveSettings(); void saveSettings();
private: private:
Ui::SettingsGeneral *m_ui; Ui::SettingsGeneral* m_ui;
}; };
#endif // SETTINGSGENERAL_H #endif // SETTINGSGENERAL_H

Some files were not shown because too many files have changed in this diff Show More