diff --git a/src/filter/filteractions/filteractionwidget.cpp b/src/filter/filteractions/filteractionwidget.cpp index d7648a9..049b682 100644 --- a/src/filter/filteractions/filteractionwidget.cpp +++ b/src/filter/filteractions/filteractionwidget.cpp @@ -1,439 +1,438 @@ /* Copyright (c) 2010 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com Copyright (c) 2010 Andras Mantia This program 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 2 of the License, or (at your option) any later version. This program 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 this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "filteractionwidget.h" #include "mailcommon_debug.h" #include "filter/filteractions/filteraction.h" #include "filter/filteractions/filteractiondict.h" #include "filter/filtermanager.h" #include "filter/mailfilter.h" #include #include #include #include #include #include using namespace MailCommon; //============================================================================= // // class FilterActionWidget // //============================================================================= class Q_DECL_HIDDEN FilterActionWidget::Private { public: Private(FilterActionWidget *qq) : q(qq) , mComboBox(nullptr) , mAdd(nullptr) , mRemove(nullptr) , mLayout(nullptr) { } ~Private() { qDeleteAll(mActionList); mActionList.clear(); } void setFilterAction(QWidget *widget = nullptr); void slotFilterTypeChanged(int index); void slotAddWidget(); void slotRemoveWidget(); FilterActionWidget *q; QList mActionList; KComboBox *mComboBox = nullptr; QPushButton *mAdd = nullptr; QPushButton *mRemove = nullptr; QGridLayout *mLayout = nullptr; }; void FilterActionWidget::Private::setFilterAction(QWidget *widget) { if (mLayout->itemAtPosition(1, 2)) { delete mLayout->itemAtPosition(1, 2)->widget(); } if (widget) { mLayout->addWidget(widget, 1, 2); } else { mLayout->addWidget(new QLabel(i18n("Please select an action."), q), 1, 2); } } void FilterActionWidget::Private::slotAddWidget() { Q_EMIT q->addFilterWidget(q); Q_EMIT q->filterModified(); } void FilterActionWidget::Private::slotRemoveWidget() { Q_EMIT q->removeFilterWidget(q); Q_EMIT q->filterModified(); } void FilterActionWidget::Private::slotFilterTypeChanged(int index) { setFilterAction(index < mActionList.count() ? mActionList.at(index)->createParamWidget(q) : nullptr); } FilterActionWidget::FilterActionWidget(QWidget *parent) : QWidget(parent) , d(new Private(this)) { QHBoxLayout *mainLayout = new QHBoxLayout; mainLayout->setMargin(0); setLayout(mainLayout); QWidget *widget = new QWidget(this); mainLayout->addWidget(widget); d->mLayout = new QGridLayout(widget); d->mLayout->setContentsMargins(0, 0, 0, 0); d->mComboBox = new PimCommon::MinimumComboBox(widget); d->mComboBox->setEditable(false); Q_ASSERT(d->mComboBox); d->mLayout->addWidget(d->mComboBox, 1, 1); d->mAdd = new QPushButton(widget); d->mAdd->setIcon(QIcon::fromTheme(QStringLiteral("list-add"))); d->mAdd->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); d->mRemove = new QPushButton(widget); d->mRemove->setIcon(QIcon::fromTheme(QStringLiteral("list-remove"))); d->mRemove->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); mainLayout->setSpacing(4); int index; QList list = MailCommon::FilterManager::filterActionDict()->list(); QList::const_iterator it; QList::const_iterator end(list.constEnd()); for (index = 0, it = list.constBegin(); it != end; ++it, ++index) { //create an instance: FilterAction *action = (*it)->create(); // append to the list of actions: d->mActionList.append(action); // add (i18n-ized) name to combo box d->mComboBox->addItem((*it)->label, (*it)->name); // Register the FilterAction modification signal connect(action, &FilterAction::filterActionModified, this, &FilterActionWidget::filterModified); } // widget for the case where no action is selected. d->mComboBox->addItem(QStringLiteral(" ")); d->mComboBox->setCurrentIndex(index); // don't show scroll bars. d->mComboBox->setMaxCount(d->mComboBox->count()); // layout management: // o the combo box is not to be made larger than it's sizeHint(), // the parameter widget should grow instead. // o the whole widget takes all space horizontally, but is fixed vertically. d->mComboBox->adjustSize(); d->mComboBox->setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed)); setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed)); updateGeometry(); // redirect focus to the filter action combo box setFocusProxy(d->mComboBox); // now connect the combo box and the widget stack connect(d->mComboBox, SIGNAL(activated(int)), this, SLOT(slotFilterTypeChanged(int))); connect(d->mComboBox, QOverload::of(&KComboBox::activated), this, &FilterActionWidget::filterModified); connect(d->mAdd, SIGNAL(clicked()), this, SLOT(slotAddWidget())); connect(d->mRemove, SIGNAL(clicked()), this, SLOT(slotRemoveWidget())); d->setFilterAction(); d->mLayout->addWidget(d->mAdd, 1, 3); d->mLayout->addWidget(d->mRemove, 1, 4); } FilterActionWidget::~FilterActionWidget() { delete d; } void FilterActionWidget::updateAddRemoveButton(bool addButtonEnabled, bool removeButtonEnabled) { d->mAdd->setEnabled(addButtonEnabled); d->mRemove->setEnabled(removeButtonEnabled); } void FilterActionWidget::setAction(const FilterAction *action) { bool found = false; const int count = d->mComboBox->count() - 1; // last entry is the empty one const QString name = action ? action->name() : QString(); // find the index of typeOf(action) in mComboBox // and clear the other widgets on the way. for (int i = 0; i < count; ++i) { if (action && d->mComboBox->itemData(i) == name) { d->setFilterAction(d->mActionList.at(i)->createParamWidget(this)); //...set the parameter widget to the settings // of aAction... action->setParamWidgetValue(d->mLayout->itemAtPosition(1, 2)->widget()); //...and show the correct entry of // the combo box d->mComboBox->setCurrentIndex(i); // (mm) also raise the widget, but doesn't found = true; } } if (found) { return; } // not found, so set the empty widget d->setFilterAction(); d->mComboBox->setCurrentIndex(count); // last item } FilterAction *FilterActionWidget::action() const { // look up the action description via the label // returned by KComboBox::currentText()... FilterActionDesc *description = MailCommon::FilterManager::filterActionDict()->value(d->mComboBox->itemData(d->mComboBox->currentIndex()).toString()); if (description) { // ...create an instance... FilterAction *action = description->create(); if (action) { // ...and apply the setting of the parameter widget. action->applyParamWidgetValue(d->mLayout->itemAtPosition(1, 2)->widget()); return action; } } return nullptr; } //============================================================================= // // class FilterActionWidgetLister (the filter action editor) // //============================================================================= class FilterActionWidgetLister::Private { public: Private(FilterActionWidgetLister *qq) : q(qq) - , mActionList(nullptr) { } void regenerateActionListFromWidgets(); FilterActionWidgetLister *q; - QList *mActionList; + QList *mActionList = nullptr; }; void FilterActionWidgetLister::Private::regenerateActionListFromWidgets() { if (!mActionList) { return; } mActionList->clear(); foreach (const QWidget *widget, q->widgets()) { FilterAction *action = qobject_cast(widget)->action(); if (action) { mActionList->append(action); } } q->updateAddRemoveButton(); } FilterActionWidgetLister:: FilterActionWidgetLister(QWidget *parent) : KWidgetLister(false, 1, MailFilter::filterActionsMaximumSize(), parent) , d(new Private(this)) { } FilterActionWidgetLister::~FilterActionWidgetLister() { delete d; } void FilterActionWidgetLister::setActionList(QList *list) { Q_ASSERT(list); if (d->mActionList && d->mActionList != list) { d->regenerateActionListFromWidgets(); } d->mActionList = list; static_cast(parent())->setEnabled(true); if (!widgets().isEmpty()) { // move this below next 'if'? widgets().constFirst()->blockSignals(true); } if (list->isEmpty()) { slotClear(); connectWidget(widgets().constFirst(), nullptr); widgets().constFirst()->blockSignals(false); return; } int superfluousItems = (int)d->mActionList->count() - widgetsMaximum(); if (superfluousItems > 0) { qCDebug(MAILCOMMON_LOG) << "FilterActionWidgetLister: Clipping action list to" << widgetsMaximum() << "items!"; for (; superfluousItems; superfluousItems--) { d->mActionList->removeLast(); } } // set the right number of widgets setNumberOfShownWidgetsTo(d->mActionList->count()); // load the actions into the widgets QList widgetList = widgets(); QList::const_iterator aEnd(d->mActionList->constEnd()); QList::ConstIterator wIt = widgetList.constBegin(); QList::ConstIterator wEnd = widgetList.constEnd(); for (QList::const_iterator aIt = d->mActionList->constBegin(); (aIt != aEnd && wIt != wEnd); ++aIt, ++wIt) { connectWidget((*wIt), (*aIt)); } widgets().constFirst()->blockSignals(false); updateAddRemoveButton(); } void FilterActionWidgetLister::connectWidget(QWidget *widget, FilterAction *filterAction) { FilterActionWidget *w = qobject_cast(widget); if (filterAction) { w->setAction(filterAction); } connect(w, &FilterActionWidget::filterModified, this, &FilterActionWidgetLister::filterModified, Qt::UniqueConnection); reconnectWidget(w); } void FilterActionWidgetLister::slotAddWidget(QWidget *w) { addWidgetAfterThisWidget(w); updateAddRemoveButton(); } void FilterActionWidgetLister::slotRemoveWidget(QWidget *w) { removeWidget(w); updateAddRemoveButton(); } void FilterActionWidgetLister::updateAddRemoveButton() { QList widgetList = widgets(); const int numberOfWidget(widgetList.count()); bool addButtonEnabled = false; bool removeButtonEnabled = false; if (numberOfWidget <= widgetsMinimum()) { addButtonEnabled = true; removeButtonEnabled = false; } else if (numberOfWidget >= widgetsMaximum()) { addButtonEnabled = false; removeButtonEnabled = true; } else { addButtonEnabled = true; removeButtonEnabled = true; } QList::ConstIterator wIt = widgetList.constBegin(); QList::ConstIterator wEnd = widgetList.constEnd(); for (; wIt != wEnd; ++wIt) { FilterActionWidget *w = qobject_cast(*wIt); w->updateAddRemoveButton(addButtonEnabled, removeButtonEnabled); } } void FilterActionWidgetLister::updateActionList() { d->regenerateActionListFromWidgets(); } void FilterActionWidgetLister::reset() { if (d->mActionList) { d->regenerateActionListFromWidgets(); } d->mActionList = nullptr; slotClear(); static_cast(parent())->setEnabled(false); } void FilterActionWidgetLister::reconnectWidget(FilterActionWidget *w) { connect(w, &FilterActionWidget::addFilterWidget, this, &FilterActionWidgetLister::slotAddWidget, Qt::UniqueConnection); connect(w, &FilterActionWidget::removeFilterWidget, this, &FilterActionWidgetLister::slotRemoveWidget, Qt::UniqueConnection); } QWidget *FilterActionWidgetLister::createWidget(QWidget *parent) { FilterActionWidget *w = new FilterActionWidget(parent); reconnectWidget(w); return w; } void FilterActionWidgetLister::clearWidget(QWidget *widget) { if (widget) { FilterActionWidget *w = static_cast(widget); w->setAction(nullptr); w->disconnect(this); reconnectWidget(w); updateAddRemoveButton(); } } #include "moc_filteractionwidget.cpp" diff --git a/src/filter/filtermanager.cpp b/src/filter/filtermanager.cpp index acdba46..ce5ddde 100644 --- a/src/filter/filtermanager.cpp +++ b/src/filter/filtermanager.cpp @@ -1,350 +1,350 @@ /* Copyright (C) 2011 Tobias Koenig This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "filtermanager.h" #include "mailcommon_debug.h" #include "filteractions/filteraction.h" #include "filteractions/filteractiondict.h" #include "filterimporterexporter.h" #include "mailfilteragentinterface.h" #include #include #include #include #include #include #include namespace MailCommon { class Q_DECL_HIDDEN FilterManager::Private { public: Private(FilterManager *qq) : q(qq) , mMailFilterAgentInterface(nullptr) , mMonitor(new Akonadi::Monitor) , mInitialized(false) { const auto service = Akonadi::ServerManager::agentServiceName(Akonadi::ServerManager::Agent, QStringLiteral("akonadi_mailfilter_agent")); mMailFilterAgentInterface = new org::freedesktop::Akonadi::MailFilterAgent(service, QStringLiteral("/MailFilterAgent"), QDBusConnection::sessionBus(), q); } void readConfig(); void writeConfig(bool withSync = true) const; void clear(); QMap mTagList; static FilterManager *mInstance; static FilterActionDict *mFilterActionDict; FilterManager *q; OrgFreedesktopAkonadiMailFilterAgentInterface *mMailFilterAgentInterface = nullptr; QList mFilters; - Akonadi::Monitor *mMonitor; - bool mInitialized; + Akonadi::Monitor *mMonitor = nullptr; + bool mInitialized = false; }; void FilterManager::Private::readConfig() { KSharedConfig::Ptr config = KSharedConfig::openConfig( Akonadi::ServerManager::addNamespace(QStringLiteral("akonadi_mailfilter_agent")) + QStringLiteral("rc")); clear(); QStringList emptyFilters; mFilters = FilterImporterExporter::readFiltersFromConfig(config, emptyFilters); Q_EMIT q->filtersChanged(); } void FilterManager::Private::writeConfig(bool withSync) const { KSharedConfig::Ptr config = KSharedConfig::openConfig( Akonadi::ServerManager::addNamespace(QStringLiteral("akonadi_mailfilter_agent")) + QStringLiteral("rc")); // Now, write out the new stuff: FilterImporterExporter::writeFiltersToConfig(mFilters, config); KConfigGroup group = config->group("General"); if (withSync) { group.sync(); } } void FilterManager::Private::clear() { qDeleteAll(mFilters); mFilters.clear(); } } using namespace MailCommon; FilterManager *FilterManager::Private::mInstance = nullptr; FilterActionDict *FilterManager::Private::mFilterActionDict = nullptr; FilterManager *FilterManager::instance() { if (!FilterManager::Private::mInstance) { FilterManager::Private::mInstance = new FilterManager; } return FilterManager::Private::mInstance; } FilterActionDict *FilterManager::filterActionDict() { if (!FilterManager::Private::mFilterActionDict) { FilterManager::Private::mFilterActionDict = new FilterActionDict; } return FilterManager::Private::mFilterActionDict; } FilterManager::FilterManager() : d(new Private(this)) { updateTagList(); d->mMonitor->setTypeMonitored(Akonadi::Monitor::Tags); d->mMonitor->tagFetchScope().fetchAttribute(); connect(d->mMonitor, &Akonadi::Monitor::tagAdded, this, &FilterManager::slotTagAdded); connect(d->mMonitor, &Akonadi::Monitor::tagRemoved, this, &FilterManager::slotTagRemoved); connect(d->mMonitor, &Akonadi::Monitor::tagChanged, this, &FilterManager::slotTagChanged); qDBusRegisterMetaType >(); Akonadi::ServerManager::State state = Akonadi::ServerManager::self()->state(); if (state == Akonadi::ServerManager::Running) { QTimer::singleShot(0, this, &FilterManager::slotReadConfig); } else { connect(Akonadi::ServerManager::self(), &Akonadi::ServerManager::stateChanged, this, &FilterManager::slotServerStateChanged); } } FilterManager::~FilterManager() { cleanup(); } void FilterManager::cleanup() { d->clear(); } void FilterManager::slotServerStateChanged(Akonadi::ServerManager::State state) { if (state == Akonadi::ServerManager::Running) { d->readConfig(); disconnect(Akonadi::ServerManager::self(), SIGNAL(stateChanged(Akonadi::ServerManager::State))); } } void FilterManager::updateTagList() { Akonadi::TagFetchJob *fetchJob = new Akonadi::TagFetchJob(this); fetchJob->fetchScope().fetchAttribute(); connect(fetchJob, &Akonadi::TagFetchJob::result, this, &FilterManager::slotFinishedTagListing); } bool FilterManager::initialized() const { return d->mInitialized; } void FilterManager::slotReadConfig() { d->readConfig(); d->mInitialized = true; Q_EMIT loadingFiltersDone(); } void FilterManager::slotFinishedTagListing(KJob *job) { if (job->error()) { qCWarning(MAILCOMMON_LOG) << "failed to retrieve tags " << job->errorString(); } Akonadi::TagFetchJob *fetchJob = static_cast(job); const Akonadi::Tag::List lstTags = fetchJob->tags(); for (const Akonadi::Tag &tag : lstTags) { d->mTagList.insert(tag.url(), tag.name()); } Q_EMIT tagListingFinished(); } void FilterManager::slotTagAdded(const Akonadi::Tag &tag) { d->mTagList.insert(tag.url(), tag.name()); Q_EMIT tagListingFinished(); } void FilterManager::slotTagChanged(const Akonadi::Tag &tag) { if (d->mTagList.contains(tag.url())) { d->mTagList.insert(tag.url(), tag.name()); } Q_EMIT tagListingFinished(); } void FilterManager::slotTagRemoved(const Akonadi::Tag &tag) { d->mTagList.remove(tag.url()); Q_EMIT tagListingFinished(); } QMap FilterManager::tagList() const { return d->mTagList; } bool FilterManager::isValid() const { return d->mMailFilterAgentInterface->isValid(); } QString FilterManager::createUniqueFilterName(const QString &name) const { return d->mMailFilterAgentInterface->createUniqueName(name); } void FilterManager::showFilterLogDialog(qlonglong windowId) { d->mMailFilterAgentInterface->showFilterLogDialog(windowId); } void FilterManager::filter(const Akonadi::Item &item, const QString &identifier, const QString &resourceId) const { d->mMailFilterAgentInterface->filter(item.id(), identifier, resourceId); } void FilterManager::filter(const Akonadi::Item &item, FilterSet set, bool account, const QString &resourceId) const { d->mMailFilterAgentInterface->filterItem(item.id(), static_cast(set), account ? resourceId : QString()); } void FilterManager::filter(const Akonadi::Collection &collection, MailCommon::FilterManager::FilterSet set) const { filter(Akonadi::Collection::List{ collection }, set); } void FilterManager::filter(const Akonadi::Collection::List &collections, FilterManager::FilterSet set) const { QList colIds; colIds.reserve(collections.size()); for (const auto col : collections) { colIds << col.id(); } d->mMailFilterAgentInterface->filterCollections(colIds, static_cast(set)); } void FilterManager::filter(const Akonadi::Collection &collection, const QStringList &listFilters) const { filter(Akonadi::Collection::List{ collection }, listFilters); } void FilterManager::filter(const Akonadi::Collection::List &collections, const QStringList &listFilters) const { QList colIds; colIds.reserve(collections.size()); for (const auto col : collections) { colIds << col.id(); } d->mMailFilterAgentInterface->applySpecificFiltersOnCollections(colIds, listFilters); } void FilterManager::filter(const Akonadi::Item::List &messages, FilterManager::FilterSet set) const { QList itemIds; itemIds.reserve(messages.size()); for (const Akonadi::Item &item : messages) { itemIds << item.id(); } d->mMailFilterAgentInterface->filterItems(itemIds, static_cast(set)); } void FilterManager::filter(const Akonadi::Item::List &messages, SearchRule::RequiredPart requiredPart, const QStringList &listFilters) const { QList itemIds; itemIds.reserve(messages.size()); for (const Akonadi::Item &item : messages) { itemIds << item.id(); } d->mMailFilterAgentInterface->applySpecificFilters(itemIds, static_cast(requiredPart), listFilters); } void FilterManager::setFilters(const QList &filters) { beginUpdate(); d->clear(); d->mFilters = filters; endUpdate(); } QList FilterManager::filters() const { return d->mFilters; } void FilterManager::appendFilters(const QList &filters, bool replaceIfNameExists) { beginUpdate(); if (replaceIfNameExists) { for (const MailCommon::MailFilter *newFilter : filters) { int numberOfFilters = d->mFilters.count(); for (int i = 0; i < numberOfFilters; ++i) { MailCommon::MailFilter *filter = d->mFilters.at(i); if (newFilter->name() == filter->name()) { d->mFilters.removeAll(filter); i = 0; numberOfFilters = d->mFilters.count(); } } } } d->mFilters += filters; endUpdate(); } void FilterManager::removeFilter(MailCommon::MailFilter *filter) { beginUpdate(); d->mFilters.removeAll(filter); endUpdate(); } void FilterManager::beginUpdate() { } void FilterManager::endUpdate() { d->writeConfig(true); d->mMailFilterAgentInterface->reload(); Q_EMIT filtersChanged(); } diff --git a/src/folder/foldertreeview.cpp b/src/folder/foldertreeview.cpp index 7472882..dc54039 100644 --- a/src/folder/foldertreeview.cpp +++ b/src/folder/foldertreeview.cpp @@ -1,710 +1,710 @@ /* Copyright (c) 2009-2017 Montel Laurent This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation. This program 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 this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "foldertreeview.h" #include "util/mailutil_p.h" #include "kernel/mailkernel.h" #include #include #include #include #include #include #include #include #include #include using namespace MailCommon; FolderTreeView::FolderTreeView(QWidget *parent, bool showUnreadCount) : Akonadi::EntityTreeView(parent) , mbDisableContextMenuAndExtraColumn(false) , mbDisableSaveConfig(false) { init(showUnreadCount); } FolderTreeView::FolderTreeView(KXMLGUIClient *xmlGuiClient, QWidget *parent, bool showUnreadCount) : Akonadi::EntityTreeView(xmlGuiClient, parent) , mbDisableContextMenuAndExtraColumn(false) , mbDisableSaveConfig(false) { init(showUnreadCount); } FolderTreeView::~FolderTreeView() { } void FolderTreeView::disableSaveConfig() { mbDisableSaveConfig = true; } void FolderTreeView::setTooltipsPolicy(FolderTreeWidget::ToolTipDisplayPolicy policy) { if (mToolTipDisplayPolicy == policy) { return; } mToolTipDisplayPolicy = policy; Q_EMIT changeTooltipsPolicy(mToolTipDisplayPolicy); writeConfig(); } void FolderTreeView::disableContextMenuAndExtraColumn() { mbDisableContextMenuAndExtraColumn = true; const int nbColumn = header()->count(); for (int i = 1; i < nbColumn; ++i) { setColumnHidden(i, true); } } void FolderTreeView::init(bool showUnreadCount) { setIconSize(QSize(22, 22)); setUniformRowHeights(true); mSortingPolicy = FolderTreeWidget::SortByCurrentColumn; mToolTipDisplayPolicy = FolderTreeWidget::DisplayAlways; header()->setContextMenuPolicy(Qt::CustomContextMenu); connect(header(), &QWidget::customContextMenuRequested, this, &FolderTreeView::slotHeaderContextMenuRequested); mCollectionStatisticsDelegate = new Akonadi::CollectionStatisticsDelegate(this); mCollectionStatisticsDelegate->setProgressAnimationEnabled(true); setItemDelegate(mCollectionStatisticsDelegate); mCollectionStatisticsDelegate->setUnreadCountShown( showUnreadCount && !header()->isSectionHidden(1)); } void FolderTreeView::showStatisticAnimation(bool anim) { mCollectionStatisticsDelegate->setProgressAnimationEnabled(anim); } void FolderTreeView::writeConfig() { if (mbDisableSaveConfig) { return; } KConfigGroup myGroup(KernelIf->config(), "MainFolderView"); myGroup.writeEntry("IconSize", iconSize().width()); myGroup.writeEntry("ToolTipDisplayPolicy", (int)mToolTipDisplayPolicy); myGroup.writeEntry("SortingPolicy", (int)mSortingPolicy); } void FolderTreeView::readConfig() { KConfigGroup myGroup(KernelIf->config(), "MainFolderView"); int iIconSize = myGroup.readEntry("IconSize", iconSize().width()); if (iIconSize < 16 || iIconSize > 32) { iIconSize = 22; } setIconSize(QSize(iIconSize, iIconSize)); mToolTipDisplayPolicy = static_cast( myGroup.readEntry("ToolTipDisplayPolicy", static_cast(FolderTreeWidget::DisplayAlways))); Q_EMIT changeTooltipsPolicy(mToolTipDisplayPolicy); setSortingPolicy( (FolderTreeWidget::SortingPolicy)myGroup.readEntry( "SortingPolicy", (int)FolderTreeWidget::SortByCurrentColumn), false); } void FolderTreeView::slotHeaderContextMenuRequested(const QPoint &pnt) { if (mbDisableContextMenuAndExtraColumn) { readConfig(); return; } // the menu for the columns QMenu menu; - QAction *act; + QAction *act = nullptr; menu.addSection(i18n("View Columns")); const int nbColumn = header()->count(); for (int i = 1; i < nbColumn; ++i) { act = menu.addAction(model()->headerData(i, Qt::Horizontal).toString()); act->setCheckable(true); act->setChecked(!header()->isSectionHidden(i)); act->setData(QVariant(i)); connect(act, &QAction::triggered, this, &FolderTreeView::slotHeaderContextMenuChangeHeader); } menu.addSection(i18n("Icon Size")); static const int icon_sizes[] = { 16, 22, 32 /*, 48, 64, 128 */ }; QActionGroup *grp = new QActionGroup(&menu); const int nbElement((int)(sizeof(icon_sizes) / sizeof(int))); for (int i = 0; i < nbElement; ++i) { act = menu.addAction(QStringLiteral("%1x%2").arg(icon_sizes[ i ]).arg(icon_sizes[ i ])); act->setCheckable(true); grp->addAction(act); if (iconSize().width() == icon_sizes[ i ]) { act->setChecked(true); } act->setData(QVariant(icon_sizes[ i ])); connect(act, &QAction::triggered, this, &FolderTreeView::slotHeaderContextMenuChangeIconSize); } menu.addSection(i18n("Display Tooltips")); grp = new QActionGroup(&menu); act = menu.addAction(i18nc("@action:inmenu Always display tooltips", "Always")); act->setCheckable(true); grp->addAction(act); act->setChecked(mToolTipDisplayPolicy == FolderTreeWidget::DisplayAlways); act->setData(QVariant((int)FolderTreeWidget::DisplayAlways)); connect(act, &QAction::triggered, this, &FolderTreeView::slotHeaderContextMenuChangeToolTipDisplayPolicy); act = menu.addAction(i18nc("@action:inmenu Never display tooltips.", "Never")); act->setCheckable(true); grp->addAction(act); act->setChecked(mToolTipDisplayPolicy == FolderTreeWidget::DisplayNever); act->setData(QVariant((int)FolderTreeWidget::DisplayNever)); connect(act, &QAction::triggered, this, &FolderTreeView::slotHeaderContextMenuChangeToolTipDisplayPolicy); menu.addSection(i18nc("@action:inmenu", "Sort Items")); grp = new QActionGroup(&menu); act = menu.addAction(i18nc("@action:inmenu", "Automatically, by Current Column")); act->setCheckable(true); grp->addAction(act); act->setChecked(mSortingPolicy == FolderTreeWidget::SortByCurrentColumn); act->setData(QVariant((int)FolderTreeWidget::SortByCurrentColumn)); connect(act, &QAction::triggered, this, &FolderTreeView::slotHeaderContextMenuChangeSortingPolicy); act = menu.addAction(i18nc("@action:inmenu", "Manually, by Drag And Drop")); act->setCheckable(true); grp->addAction(act); act->setChecked(mSortingPolicy == FolderTreeWidget::SortByDragAndDropKey); act->setData(QVariant((int)FolderTreeWidget::SortByDragAndDropKey)); connect(act, &QAction::triggered, this, &FolderTreeView::slotHeaderContextMenuChangeSortingPolicy); menu.exec(header()->mapToGlobal(pnt)); } void FolderTreeView::slotHeaderContextMenuChangeSortingPolicy(bool) { QAction *act = qobject_cast< QAction * >(sender()); if (!act) { return; } QVariant data = act->data(); bool ok; int policy = data.toInt(&ok); if (!ok) { return; } setSortingPolicy((FolderTreeWidget::SortingPolicy)policy, true); } void FolderTreeView::setSortingPolicy(FolderTreeWidget::SortingPolicy policy, bool writeInConfig) { if (mSortingPolicy == policy) { return; } mSortingPolicy = policy; switch (mSortingPolicy) { case FolderTreeWidget::SortByCurrentColumn: header()->setSectionsClickable(true); header()->setSortIndicatorShown(true); setSortingEnabled(true); Q_EMIT manualSortingChanged(false); break; case FolderTreeWidget::SortByDragAndDropKey: header()->setSectionsClickable(false); header()->setSortIndicatorShown(false); setSortingEnabled(false); // hack for qutie bug: this call shouldn't be here at all Q_EMIT manualSortingChanged(true); break; default: // should never happen break; } if (writeInConfig) { writeConfig(); } } void FolderTreeView::slotHeaderContextMenuChangeToolTipDisplayPolicy(bool) { QAction *act = qobject_cast< QAction * >(sender()); if (!act) { return; } QVariant data = act->data(); bool ok; const int id = data.toInt(&ok); if (!ok) { return; } Q_EMIT changeTooltipsPolicy((FolderTreeWidget::ToolTipDisplayPolicy)id); } void FolderTreeView::slotHeaderContextMenuChangeHeader(bool) { QAction *act = qobject_cast< QAction * >(sender()); if (!act) { return; } QVariant data = act->data(); bool ok; const int id = data.toInt(&ok); if (!ok) { return; } if (id > header()->count()) { return; } if (id == 1) { mCollectionStatisticsDelegate->setUnreadCountShown(!act->isChecked()); } setColumnHidden(id, !act->isChecked()); } void FolderTreeView::slotHeaderContextMenuChangeIconSize(bool) { QAction *act = qobject_cast< QAction * >(sender()); if (!act) { return; } QVariant data = act->data(); bool ok; const int size = data.toInt(&ok); if (!ok) { return; } const QSize newIconSize(QSize(size, size)); if (newIconSize == iconSize()) { return; } setIconSize(newIconSize); writeConfig(); } void FolderTreeView::setCurrentModelIndex(const QModelIndex &index) { if (index.isValid()) { clearSelection(); scrollTo(index); selectionModel()->setCurrentIndex(index, QItemSelectionModel::Rows); } } void FolderTreeView::selectModelIndex(const QModelIndex &index) { if (index.isValid()) { scrollTo(index); selectionModel()->select( index, QItemSelectionModel::Rows | QItemSelectionModel::Select |QItemSelectionModel::Current | QItemSelectionModel::Clear); } } void FolderTreeView::slotSelectFocusFolder() { const QModelIndex index = currentIndex(); if (index.isValid()) { setCurrentIndex(index); } } void FolderTreeView::slotFocusNextFolder() { const QModelIndex nextFolder = selectNextFolder(currentIndex()); if (nextFolder.isValid()) { expand(nextFolder); setCurrentModelIndex(nextFolder); } } QModelIndex FolderTreeView::selectNextFolder(const QModelIndex ¤t) { QModelIndex below; if (current.isValid()) { model()->fetchMore(current); if (model()->hasChildren(current)) { expand(current); below = indexBelow(current); } else if (current.row() < model()->rowCount(model()->parent(current)) - 1) { below = model()->index(current.row() + 1, current.column(), model()->parent(current)); } else { below = indexBelow(current); } } return below; } void FolderTreeView::slotFocusPrevFolder() { const QModelIndex current = currentIndex(); if (current.isValid()) { QModelIndex above = indexAbove(current); setCurrentModelIndex(above); } } void FolderTreeView::slotFocusFirstFolder() { const QModelIndex first = moveCursor(QAbstractItemView::MoveHome, nullptr); if (first.isValid()) { setCurrentModelIndex(first); } } void FolderTreeView::slotFocusLastFolder() { const QModelIndex last = moveCursor(QAbstractItemView::MoveEnd, nullptr); if (last.isValid()) { setCurrentModelIndex(last); } } void FolderTreeView::selectNextUnreadFolder(bool confirm) { // find next unread collection starting from current position if (!trySelectNextUnreadFolder(currentIndex(), ForwardSearch, confirm)) { // if there is none, jump to the last collection and try again trySelectNextUnreadFolder(model()->index(0, 0), ForwardSearch, confirm); } } // helper method to find last item in the model tree static QModelIndex lastChildOf(QAbstractItemModel *model, const QModelIndex ¤t) { if (model->rowCount(current) == 0) { return current; } return lastChildOf(model, model->index(model->rowCount(current) - 1, 0, current)); } void FolderTreeView::selectPrevUnreadFolder(bool confirm) { // find next unread collection starting from current position if (!trySelectNextUnreadFolder(currentIndex(), BackwardSearch, confirm)) { // if there is none, jump to top and try again const QModelIndex index = lastChildOf(model(), QModelIndex()); trySelectNextUnreadFolder(index, BackwardSearch, confirm); } } bool FolderTreeView::trySelectNextUnreadFolder(const QModelIndex ¤t, SearchDirection direction, bool confirm) { QModelIndex index = current; while (true) { index = nextUnreadCollection(index, direction); if (!index.isValid()) { return false; } const Akonadi::Collection collection = index.data(Akonadi::EntityTreeModel::CollectionRole).value(); if (collection == Kernel::self()->trashCollectionFolder() || collection == Kernel::self()->outboxCollectionFolder()) { continue; } if (ignoreUnreadFolder(collection, confirm)) { continue; } if (allowedToEnterFolder(collection, confirm)) { expand(index); setCurrentIndex(index); selectModelIndex(index); return true; } else { return false; } } return false; } bool FolderTreeView::ignoreUnreadFolder(const Akonadi::Collection &collection, bool confirm) const { if (!confirm) { return false; } // Skip drafts, sent mail and templates as well, when reading mail with the // space bar - but not when changing into the next folder with unread mail // via ctrl+ or ctrl- so we do this only if (confirm == true), which means // we are doing readOn. return collection == Kernel::self()->draftsCollectionFolder() || collection == Kernel::self()->templatesCollectionFolder() || collection == Kernel::self()->sentCollectionFolder(); } bool FolderTreeView::allowedToEnterFolder(const Akonadi::Collection &collection, bool confirm) const { if (!confirm) { return true; } // warn user that going to next folder - but keep track of // whether he wishes to be notified again in "AskNextFolder" // parameter (kept in the config file for kmail) const int result = KMessageBox::questionYesNo( const_cast(this), i18n("Go to the next unread message in folder %1?", collection.name()), i18n("Go to Next Unread Message"), KGuiItem(i18n("Go To")), KGuiItem(i18n("Do Not Go To")), // defaults QStringLiteral(":kmail_AskNextFolder"), nullptr); return result == KMessageBox::Yes; } bool FolderTreeView::isUnreadFolder(const QModelIndex ¤t, QModelIndex &index, FolderTreeView::Move move, bool confirm) { if (current.isValid()) { if (move == FolderTreeView::Next) { index = selectNextFolder(current); } else if (move == FolderTreeView::Previous) { index = indexAbove(current); } if (index.isValid()) { const Akonadi::Collection collection = index.model()->data( current, Akonadi::EntityTreeModel::CollectionRole).value(); if (collection.isValid()) { if (collection.statistics().unreadCount() > 0) { if (!confirm) { selectModelIndex(current); return true; } else { // Skip drafts, sent mail and templates as well, when reading mail with the // space bar - but not when changing into the next folder with unread mail // via ctrl+ or ctrl- so we do this only if (confirm == true), which means // we are doing readOn. if (collection == Kernel::self()->draftsCollectionFolder() || collection == Kernel::self()->templatesCollectionFolder() || collection == Kernel::self()->sentCollectionFolder()) { return false; } // warn user that going to next folder - but keep track of // whether he wishes to be notified again in "AskNextFolder" // parameter (kept in the config file for kmail) if (KMessageBox::questionYesNo( this, i18n("Go to the next unread message in folder %1?", collection.name()), i18n("Go to Next Unread Message"), KGuiItem(i18n("Go To")), KGuiItem(i18n("Do Not Go To")), // defaults QStringLiteral(":kmail_AskNextFolder"), nullptr) == KMessageBox::No) { return true; // assume selected (do not continue looping) } selectModelIndex(current); return true; } } } } } return false; } Akonadi::Collection FolderTreeView::currentFolder() const { const QModelIndex current = currentIndex(); if (current.isValid()) { const Akonadi::Collection collection = current.model()->data( current, Akonadi::EntityTreeModel::CollectionRole).value(); return collection; } return Akonadi::Collection(); } void FolderTreeView::mousePressEvent(QMouseEvent *e) { const bool buttonPressedIsMiddle = (e->button() == Qt::MidButton); Q_EMIT newTabRequested(buttonPressedIsMiddle); EntityTreeView::mousePressEvent(e); } void FolderTreeView::restoreHeaderState(const QByteArray &data) { if (data.isEmpty()) { const int nbColumn = header()->count(); for (int i = 1; i < nbColumn; ++i) { setColumnHidden(i, true); } } else { header()->restoreState(data); } mCollectionStatisticsDelegate->setUnreadCountShown(header()->isSectionHidden(1)); } void FolderTreeView::updatePalette() { mCollectionStatisticsDelegate->updatePalette(); } void FolderTreeView::keyboardSearch(const QString &) { // Disable keyboardSearch: it interfers with filtering in the // FolderSelectionDialog. We don't want it in KMail main window // either because KMail has one-letter keyboard shortcuts. } QModelIndex FolderTreeView::indexBelow(const QModelIndex ¤t) const { // if we have children, return first child if (model()->rowCount(current) > 0) { return model()->index(0, 0, current); } // if we have siblings, return next sibling const QModelIndex parent = model()->parent(current); const QModelIndex sibling = model()->index(current.row() + 1, 0, parent); if (sibling.isValid()) { // found valid sibling return sibling; } if (!parent.isValid()) { // our parent is the tree root and we have no siblings return QModelIndex(); // we reached the bottom of the tree } // We are the last child, the next index to check is our uncle, parent's first sibling const QModelIndex parentsSibling = parent.sibling(parent.row() + 1, 0); if (parentsSibling.isValid()) { return parentsSibling; } // iterate over our parents back to root until we find a parent with a valid sibling QModelIndex currentParent = parent; QModelIndex grandParent = model()->parent(currentParent); while (currentParent.isValid()) { // check if the parent has children except from us if (model()->rowCount(grandParent) > currentParent.row() + 1) { const auto index = indexBelow(model()->index(currentParent.row() + 1, 0, grandParent)); if (index.isValid()) { return index; } } currentParent = grandParent; grandParent = model()->parent(currentParent); } return QModelIndex(); // nothing found -> end of tree } QModelIndex FolderTreeView::lastChild(const QModelIndex ¤t) const { if (model()->rowCount(current) == 0) { return current; } return lastChild(model()->index(model()->rowCount(current) - 1, 0, current)); } QModelIndex FolderTreeView::indexAbove(const QModelIndex ¤t) const { const QModelIndex parent = model()->parent(current); if (current.row() == 0) { // we have no previous siblings -> our parent is the next item above us return parent; } // find previous sibling const QModelIndex previousSibling = model()->index(current.row() - 1, 0, parent); // the item above us is the last child (or grandchild, or grandgrandchild... etc) // of our previous sibling return lastChild(previousSibling); } QModelIndex FolderTreeView::nextUnreadCollection(const QModelIndex ¤t, SearchDirection direction) const { QModelIndex index = current; while (true) { if (direction == ForwardSearch) { index = indexBelow(index); } else if (direction == BackwardSearch) { index = indexAbove(index); } if (!index.isValid()) { // reach end or top of the model return QModelIndex(); } // check if the index is a collection const auto collection = index.data(Akonadi::EntityTreeModel::CollectionRole).value(); if (collection.isValid()) { // check if it is unread if (collection.statistics().unreadCount() > 0) { if (!MailCommon::Util::ignoreNewMailInFolder(collection)) { return index; // we found the next unread collection } } } } return QModelIndex(); // no unread collection found } diff --git a/src/folder/foldertreeview.h b/src/folder/foldertreeview.h index 066202e..7f0c504 100644 --- a/src/folder/foldertreeview.h +++ b/src/folder/foldertreeview.h @@ -1,129 +1,129 @@ /* Copyright (c) 2009-2017 Montel Laurent This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation. This program 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 this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef MAILCOMMON_FOLDERTREEVIEW_H #define MAILCOMMON_FOLDERTREEVIEW_H #include "mailcommon_export.h" #include "foldertreewidget.h" #include "mailcommon/mailutil.h" #include #include class QMouseEvent; namespace Akonadi { class CollectionStatisticsDelegate; } namespace MailCommon { /** * This is an enhanced EntityTreeView specially suited for the folders in KMail's * main folder widget. */ class MAILCOMMON_EXPORT FolderTreeView : public Akonadi::EntityTreeView { Q_OBJECT public: explicit FolderTreeView(QWidget *parent = nullptr, bool showUnreadCount = true); explicit FolderTreeView(KXMLGUIClient *xmlGuiClient, QWidget *parent = nullptr, bool showUnreadCount = true); virtual ~FolderTreeView(); void selectNextUnreadFolder(bool confirm = false); void selectPrevUnreadFolder(bool confirm = false); void showStatisticAnimation(bool anim); void disableContextMenuAndExtraColumn(); void setTooltipsPolicy(FolderTreeWidget::ToolTipDisplayPolicy); void restoreHeaderState(const QByteArray &data); Akonadi::Collection currentFolder() const; void disableSaveConfig(); void readConfig(); void updatePalette(); void keyboardSearch(const QString &) override; protected: enum Move { Next = 0, Previous = 1 }; void init(bool showUnreadCount); void selectModelIndex(const QModelIndex &); void setCurrentModelIndex(const QModelIndex &); QModelIndex selectNextFolder(const QModelIndex ¤t); bool isUnreadFolder(const QModelIndex ¤t, QModelIndex &nextIndex, FolderTreeView::Move move, bool confirm); void writeConfig(); void setSortingPolicy(FolderTreeWidget::SortingPolicy policy, bool writeInConfig = false); void mousePressEvent(QMouseEvent *e) override; public Q_SLOTS: void slotFocusNextFolder(); void slotFocusPrevFolder(); void slotSelectFocusFolder(); void slotFocusFirstFolder(); void slotFocusLastFolder(); protected Q_SLOTS: void slotHeaderContextMenuRequested(const QPoint &); void slotHeaderContextMenuChangeIconSize(bool); void slotHeaderContextMenuChangeHeader(bool); void slotHeaderContextMenuChangeToolTipDisplayPolicy(bool); void slotHeaderContextMenuChangeSortingPolicy(bool); Q_SIGNALS: void changeTooltipsPolicy(FolderTreeWidget::ToolTipDisplayPolicy); void manualSortingChanged(bool actif); void newTabRequested(bool); private: enum SearchDirection { ForwardSearch, BackwardSearch }; QModelIndex indexAbove(const QModelIndex ¤t) const; QModelIndex indexBelow(const QModelIndex ¤t) const; QModelIndex lastChild(const QModelIndex ¤t) const; QModelIndex nextUnreadCollection(const QModelIndex ¤t, SearchDirection direction) const; bool ignoreUnreadFolder(const Akonadi::Collection &, bool) const; bool allowedToEnterFolder(const Akonadi::Collection &, bool) const; bool trySelectNextUnreadFolder(const QModelIndex &, SearchDirection, bool); FolderTreeWidget::ToolTipDisplayPolicy mToolTipDisplayPolicy; FolderTreeWidget::SortingPolicy mSortingPolicy; - Akonadi::CollectionStatisticsDelegate *mCollectionStatisticsDelegate; - bool mbDisableContextMenuAndExtraColumn; - bool mbDisableSaveConfig; + Akonadi::CollectionStatisticsDelegate *mCollectionStatisticsDelegate = nullptr; + bool mbDisableContextMenuAndExtraColumn = false; + bool mbDisableSaveConfig = false; }; } #endif diff --git a/src/job/jobscheduler.h b/src/job/jobscheduler.h index e68e945..a0cd68c 100644 --- a/src/job/jobscheduler.h +++ b/src/job/jobscheduler.h @@ -1,152 +1,152 @@ /* * Copyright (c) 2004 David Faure * * This program 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; version 2 of the License * * This program 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 this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * In addition, as a special exception, the copyright holders give * permission to link the code of this program with any edition of * the Qt library by Trolltech AS, Norway (or with modified versions * of Qt that use the same license as Qt), and distribute linked * combinations including the two. You must obey the GNU General * Public License in all respects for all of the code used other than * Qt. If you modify this file, you may extend this exception to * your version of the file, but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from * your version. */ #ifndef MAILCOMMON_JOBSCHEDULER_H #define MAILCOMMON_JOBSCHEDULER_H #include "mailcommon_export.h" #include #include #include "folderjob.h" #include // If this define is set, JobScheduler will show debug output, and related kmkernel timers will be shortened // This is for debugging purposes only, don't commit with it. //#define DEBUG_SCHEDULER namespace MailCommon { class FolderJob; class ScheduledJob; /** * A scheduled task is some information about a folder job that should be run later. * As long as it's not running, it's called a "task", i.e. something that needs to be done. * Tasks are held in the JobScheduler. */ class MAILCOMMON_EXPORT ScheduledTask { public: /// Create a scheduled task for a given folder /// If @p immediate is true, the scheduler will run this task as soon /// as possible (but won't interrupt a currently running job for it) ScheduledTask(const Akonadi::Collection &folder, bool immediate); virtual ~ScheduledTask(); /// Run this task, i.e. create a job for it. /// Important: the job's execute() method must either call open() on the /// folder or storage immediately, or abort (deleting itself). /// Usually, that job should also be cancellable. /// Otherwise (if the open() is delayed) an unrelated open() could happen first /// and mess things up. /// If for some reason (e.g. folder deleted) nothing should be done, return 0. virtual ScheduledJob *run() = 0; /// An identifier for the type of task (a bit like QListViewItem::rtti) /// This allows to automatically prevent two identical tasks from being scheduled /// for the same folder. To circumvent this feature and make every task /// unique, return 0 here. virtual int taskTypeId() const = 0; /// The folder which this task is about, 0 if it was deleted meanwhile. Akonadi::Collection folder() const { return mCurrentFolder; } bool isImmediate() const { return mImmediate; } private: Akonadi::Collection mCurrentFolder; bool mImmediate; }; /** * The unique JobScheduler instance (owned by kmkernel) implements "background processing" * of folder operations (like expiration and compaction). Tasks (things to be done) * are registered with the JobScheduler, and it will execute them one at a time, * separated with a 1-minute timer. The jobs themselves should use timers to avoid * using too much CPU for too long. Tasks for opened folders are not executed until * the folder is closed. */ class MAILCOMMON_EXPORT JobScheduler : public QObject { Q_OBJECT public: explicit JobScheduler(QObject *parent); ~JobScheduler(); /// Register a task to be done for a given folder /// The ownership of the task is transferred to the JobScheduler void registerTask(ScheduledTask *task); // D-Bus calls, called from KMKernel void pause(); void resume(); private: /// Called by a timer to run the next job void slotRunNextJob(); /// Called when the current job terminates void slotJobFinished(); void restartTimer(); void interruptCurrentTask(); void runTaskNow(ScheduledTask *task); typedef QList TaskList; void removeTask(TaskList::Iterator &it); private: TaskList mTaskList; // FIFO of tasks to be run QTimer mTimer; int mPendingImmediateTasks; /// Information about the currently running job, if any - ScheduledTask *mCurrentTask; - ScheduledJob *mCurrentJob; + ScheduledTask *mCurrentTask = nullptr; + ScheduledJob *mCurrentJob = nullptr; }; /** * Base class for scheduled jobs */ class MAILCOMMON_EXPORT ScheduledJob : public FolderJob { public: ScheduledJob(const Akonadi::Collection &folder, bool immediate); ~ScheduledJob(); protected: bool mImmediate; }; } #endif diff --git a/src/mdn/sendmdnhandler.cpp b/src/mdn/sendmdnhandler.cpp index 06fa2cd..38d097c 100644 --- a/src/mdn/sendmdnhandler.cpp +++ b/src/mdn/sendmdnhandler.cpp @@ -1,141 +1,141 @@ /* Copyright (C) 2010 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.net, Author Tobias Koenig This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "sendmdnhandler.h" #include "mailcommon/mailinterfaces.h" #include "kernel/mailkernel.h" #include "util/mailutil.h" #include "filter/mdnadvicedialog.h" #include "mailcommon_debug.h" #include #include #include #include #include #include #include #include #include using namespace MailCommon; class Q_DECL_HIDDEN SendMdnHandler::Private { public: Private(SendMdnHandler *qq, IKernel *kernel) : q(qq) , mKernel(kernel) { } void handleMessages(); SendMdnHandler *q; - IKernel *mKernel; + IKernel *mKernel = nullptr; QQueue mItemQueue; QTimer mTimer; }; void SendMdnHandler::Private::handleMessages() { while (!mItemQueue.isEmpty()) { Akonadi::Item item = mItemQueue.dequeue(); #if 0 // should we send an MDN? if (MessageViewer::MessageViewerSettings::notSendWhenEncrypted() && message()->encryptionState() != KMMsgNotEncrypted && message()->encryptionState() != KMMsgEncryptionStateUnknown) { return; } #else qCDebug(MAILCOMMON_LOG) << "AKONADI PORT: Disabled code in " << Q_FUNC_INFO; #endif const Akonadi::Collection collection = item.parentCollection(); if (collection.isValid() && (CommonKernel->folderIsSentMailFolder(collection) || CommonKernel->folderIsTrash(collection) || CommonKernel->folderIsDraftOrOutbox(collection) || CommonKernel->folderIsTemplates(collection))) { continue; } const KMime::Message::Ptr message = MessageComposer::Util::message(item); if (!message) { continue; } const QPair mdnSend = MDNAdviceHelper::instance()->checkAndSetMDNInfo(item, KMime::MDN::Displayed); if (mdnSend.first) { const int quote = MessageViewer::MessageViewerSettings::self()->quoteMessage(); MessageComposer::MessageFactoryNG factory(message, Akonadi::Item().id()); factory.setIdentityManager(mKernel->identityManager()); factory.setFolderIdentity(MailCommon::Util::folderIdentity(item)); const KMime::Message::Ptr mdn = factory.createMDN(KMime::MDN::ManualAction, KMime::MDN::Displayed, mdnSend.second, quote); if (mdn) { if (!mKernel->msgSender()->send(mdn)) { qCDebug(MAILCOMMON_LOG) << "Sending failed."; } } } } } SendMdnHandler::SendMdnHandler(IKernel *kernel, QObject *parent) : QObject(parent) , d(new Private(this, kernel)) { d->mTimer.setSingleShot(true); connect(&d->mTimer, SIGNAL(timeout()), this, SLOT(handleMessages())); } SendMdnHandler::~SendMdnHandler() { delete d; } void SendMdnHandler::setItem(const Akonadi::Item &item) { if (item.hasFlag(Akonadi::MessageFlags::Seen)) { return; } d->mTimer.stop(); d->mItemQueue.enqueue(item); if (MessageViewer::MessageViewerSettings::self()->delayedMarkAsRead() && MessageViewer::MessageViewerSettings::self()->delayedMarkTime() != 0) { d->mTimer.start(MessageViewer::MessageViewerSettings::self()->delayedMarkTime() * 1000); return; } d->handleMessages(); } #include "moc_sendmdnhandler.cpp" diff --git a/src/search/searchpatternedit.h b/src/search/searchpatternedit.h index e414db8..0988799 100644 --- a/src/search/searchpatternedit.h +++ b/src/search/searchpatternedit.h @@ -1,312 +1,312 @@ /* Author: Marc Mutz This program 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 2 of the License, or (at your option) any later version. This program 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 this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef MAILCOMMON_SEARCHPATTERNEDIT_H #define MAILCOMMON_SEARCHPATTERNEDIT_H #include "mailcommon_export.h" #include "searchpattern.h" #include #include #include class KComboBox; class QPushButton; class QAbstractButton; class QRadioButton; class QStackedWidget; namespace MailCommon { class SearchPatternEdit; /** * This widget is intended to be used in the filter configuration as * well as in the message search dialogs. It consists of a frame, * inside which there are placed two radio buttons entitled "Match * {all,any} of the following", followed by a vertical stack of * MailCommon::SearchRuleWidgets (initially two) and two buttons to add * and remove, resp., additional KMSearchWidget 's. * * To set the widget according to a given KMSearchPattern, use * setSearchPattern; to initialize it (e.g. for a new, virgin * rule), use setSearchPattern with a 0 argument. The widget * operates directly on a shallow(!) copy of the search rule. So * while you actually don't really need searchPattern, because * you can always store a pointer to the current pattern yourself, * you must not modify the currently-worked-on pattern yourself while * this widget holds a reference to it. The only exceptions are: * * @li If you edit a derived class, you can change aspects of the * class that don't interfere with the KMSearchPattern part. An * example is KMFilter, whose actions you can still edit while the * KMSearchPattern part of it is being acted upon by this widget. * * @li You can change the name of the pattern, but only using (this * widget's) setName. You cannot change the pattern's name * directly, although this widget in itself doesn't let the user * change it. This is because it auto-names the pattern to * "<$field>:$contents" iff the pattern begins with "<". * * @short A widget which allows editing a set of MailCommon::SearchRule's. * @author Marc Mutz */ class SearchRuleWidgetLister; class MAILCOMMON_EXPORT SearchPatternEdit : public QWidget { Q_OBJECT public: enum SearchPatternEditOption { None = 0, HeadersOnly = 1, NotShowAbsoluteDate = 2, MatchAllMessages = 4, NotShowSize = 8, NotShowDate = 16, NotShowTags = 32 }; Q_DECLARE_FLAGS(SearchPatternEditOptions, SearchPatternEditOption) enum SearchModeType { StandardMode = 0, BalooMode = 1 }; /** * Constructor. The parent parameter is passed to the underlying * QGroupBox, as usual. */ explicit SearchPatternEdit( QWidget *parent = nullptr, SearchPatternEditOptions options = (SearchPatternEditOptions)(None), SearchModeType modeType = StandardMode); ~SearchPatternEdit(); void setPatternEditOptions(SearchPatternEdit::SearchPatternEditOptions options); /** * Sets the search pattern. Rules are inserted regardless of the * return value of each rules' MailCommon::SearchRule::isEmpty. * This widget makes a shallow copy of @p aPattern and operates * directly on it. */ void setSearchPattern(MailCommon::SearchPattern *aPattern); /** * Updates the search pattern according to the current widget values. */ void updateSearchPattern(); public Q_SLOTS: /** * Called when the widget should let go of the currently referenced * filter and disable itself. */ void reset(); Q_SIGNALS: /** * This signal is emitted whenever the name of the processed * search pattern may have changed. */ void maybeNameChanged(); /** * This signal is emitted wherenever the search pattern changes in some way. */ void patternChanged(); void returnPressed(); private Q_SLOTS: void slotRadioClicked(QAbstractButton *aRBtn); void slotAutoNameHack(); void slotRuleAdded(QWidget *widget); private: void initLayout(SearchPatternEditOptions options, SearchModeType modeType); MailCommon::SearchPattern *mPattern = nullptr; QRadioButton *mAllRBtn = nullptr; QRadioButton *mAnyRBtn = nullptr; QRadioButton *mAllMessageRBtn = nullptr; SearchRuleWidgetLister *mRuleLister = nullptr; }; /** * A widget to edit a single MailCommon::SearchRule. * It consists of an editable KComboBox for the field, * a read-only KComboBox for the function and * a QLineEdit for the content or the pattern (in case of regexps). * It manages the i18n itself, so field name should be in it's english form. * * To use, you essentially give it the reference to a MailCommon::SearchRule and * it does the rest. It will never delete the rule itself, as it assumes * that something outside of it manages this. * * @short A widget to edit a single MailCommon::SearchRule. * @author Marc Mutz */ class SearchRuleWidget : public QWidget { Q_OBJECT public: /** * Constructor. You can give a MailCommon::SearchRule as parameter, * which will be used to initialize the widget. */ explicit SearchRuleWidget(QWidget *parent = nullptr, MailCommon::SearchRule::Ptr aRule = MailCommon::SearchRule::Ptr(), SearchPatternEdit::SearchPatternEditOptions options = (SearchPatternEdit::SearchPatternEditOptions)(SearchPatternEdit::None), SearchPatternEdit::SearchModeType modeType = SearchPatternEdit::StandardMode); enum { Message, Body, AnyHeader, Recipients, Size, AgeInDays, Status, Tag, Subject, From, To, CC, ReplyTo, Organization, Date }; /** * Sets the rule. The rule is accepted regardless of the return * value of MailCommon::SearchRule::isEmpty. This widget makes a shallow * copy of @p aRule and operates directly on it. If @p aRule is 0, * resets itself, taks user input, but does essentially nothing. * If you pass 0, you should probably disable it. */ void setRule(MailCommon::SearchRule::Ptr aRule); /** * Returns a reference to the currently-worked-on MailCommon::SearchRule. */ MailCommon::SearchRule::Ptr rule() const; /** * Resets the rule currently worked on and updates the widget accordingly. */ void reset(); static int ruleFieldToId(const QString &i18nVal); void updateAddRemoveButton(bool addButtonEnabled, bool removeButtonEnabled); void setPatternEditOptions(MailCommon::SearchPatternEdit::SearchPatternEditOptions options); public Q_SLOTS: void slotFunctionChanged(); void slotValueChanged(); void slotReturnPressed(); Q_SIGNALS: /** * This signal is emitted whenever the user alters the field. * The pseudo-headers <...> are returned in their i18n form, but * stored in their English form in the rule. */ void fieldChanged(const QString &); /** * This signal is emitted whenever the user alters the contents/value * of the rule. */ void contentsChanged(const QString &); void returnPressed(); void addWidget(QWidget *); void removeWidget(QWidget *); protected: /** * Used internally to translate i18n-ized pseudo-headers back to English. */ static QByteArray ruleFieldToEnglish(const QString &i18nVal); /** * Used internally to find the corresponding index into the field * ComboBox. Returns the index if found or -1 if the search failed, */ int indexOfRuleField(const QByteArray &aName) const; protected Q_SLOTS: void slotRuleFieldChanged(const QString &); void slotAddWidget(); void slotRemoveWidget(); private: void initWidget(SearchPatternEdit::SearchModeType modeType); void initFieldList(MailCommon::SearchPatternEdit::SearchPatternEditOptions options); QStringList mFilterFieldList; KComboBox *mRuleField = nullptr; QStackedWidget *mFunctionStack = nullptr; QStackedWidget *mValueStack = nullptr; QPushButton *mAdd = nullptr; QPushButton *mRemove = nullptr; }; class SearchRuleWidgetLister : public KPIM::KWidgetLister { Q_OBJECT friend class SearchPatternEdit; public: explicit SearchRuleWidgetLister(QWidget *parent = nullptr, SearchPatternEdit::SearchPatternEditOptions opt = (SearchPatternEdit::SearchPatternEditOptions)(SearchPatternEdit::None), SearchPatternEdit::SearchModeType modeType = SearchPatternEdit::StandardMode); virtual ~SearchRuleWidgetLister(); void setRuleList(QList *aList); void setPatternEditOptions(SearchPatternEdit::SearchPatternEditOptions options); public Q_SLOTS: void reset(); void slotAddWidget(QWidget *); void slotRemoveWidget(QWidget *); protected: void clearWidget(QWidget *aWidget) override; QWidget *createWidget(QWidget *parent) override; private: void reconnectWidget(SearchRuleWidget *w); void updateAddRemoveButton(); void regenerateRuleListFromWidgets(); - QList *mRuleList; + QList *mRuleList = nullptr; SearchPatternEdit::SearchPatternEditOptions mOptions; SearchPatternEdit::SearchModeType mTypeMode; }; } #endif