7#include <config-libkleo.h>
9#include "useridselectioncombo.h"
11#include "progressbar.h"
13#include <libkleo/defaultkeyfilter.h>
14#include <libkleo/dn.h>
15#include <libkleo/formatting.h>
16#include <libkleo/keycache.h>
17#include <libkleo/keyfiltermanager.h>
18#include <libkleo/keyhelpers.h>
19#include <libkleo/keylist.h>
20#include <libkleo/keylistmodel.h>
21#include <libkleo/keylistsortfilterproxymodel.h>
22#include <libkleo/useridproxymodel.h>
24#include <kleo_ui_debug.h>
26#include <KLocalizedString>
30#include <QSortFilterProxyModel>
34#include <gpgme++/key.h>
39Q_DECLARE_METATYPE(GpgME::Key)
43class SortFilterProxyModel :
public KeyListSortFilterProxyModel
48 using KeyListSortFilterProxyModel::KeyListSortFilterProxyModel;
50 void setAlwaysAcceptedKey(
const QString &fingerprint)
52 if (fingerprint == mFingerprint) {
55 mFingerprint = fingerprint;
60 bool filterAcceptsRow(
int source_row,
const QModelIndex &source_parent)
const override
62 if (!mFingerprint.isEmpty()) {
63 const QModelIndex index = sourceModel()->index(source_row, 0, source_parent);
64 const auto fingerprint = sourceModel()->
data(index, KeyList::FingerprintRole).toString();
65 if (fingerprint == mFingerprint) {
70 return KeyListSortFilterProxyModel::filterAcceptsRow(source_row, source_parent);
77static QString formatUserID(
const GpgME::UserID &userID)
82 if (userID.parent().protocol() == GpgME::OpenPGP) {
87 name = dn[QStringLiteral(
"CN")];
88 email = dn[QStringLiteral(
"EMAIL")];
90 name =
Kleo::DN(userID.parent().userID(0).id())[QStringLiteral(
"CN")];
93 return email.
isEmpty() ? name : name.isEmpty() ? email :
i18nc(
"Name <email>",
"%1 <%2>", name, email);
101 SortAndFormatCertificatesProxyModel(KeyUsage::Flags usageFlags, QObject *parent =
nullptr)
102 : QSortFilterProxyModel{parent}
103 , mIconProvider{usageFlags}
108 bool lessThan(
const QModelIndex &left,
const QModelIndex &right)
const override
110 const auto leftUserId = sourceModel()->data(left, KeyList::UserIDRole).value<GpgME::UserID>();
111 const auto rightUserId = sourceModel()->data(right, KeyList::UserIDRole).value<GpgME::UserID>();
112 if (leftUserId.isNull()) {
115 if (rightUserId.isNull()) {
118 const auto leftNameAndEmail = formatUserID(leftUserId);
119 const auto rightNameAndEmail = formatUserID(rightUserId);
125 if (leftUserId.validity() != rightUserId.validity()) {
126 return leftUserId.validity() > rightUserId.validity();
131 for (
const GpgME::Subkey &s : leftUserId.parent().subkeys()) {
135 if (s.creationTime() > leftTime) {
136 leftTime = s.creationTime();
139 time_t rightTime = 0;
140 for (
const GpgME::Subkey &s : rightUserId.parent().subkeys()) {
144 if (s.creationTime() > rightTime) {
145 rightTime = s.creationTime();
148 if (rightTime != leftTime) {
149 return leftTime > rightTime;
153 return strcmp(leftUserId.parent().primaryFingerprint(), rightUserId.parent().primaryFingerprint()) < 0;
157 QVariant data(
const QModelIndex &index,
int role)
const override
164 Q_ASSERT(!userId.isNull());
165 if (userId.isNull()) {
172 return Formatting::summaryLine(userId);
175 using namespace Kleo::Formatting;
176 return Kleo::Formatting::toolTip(userId, Validity | Issuer | Subject | Fingerprint | ExpiryDates | UserIDs);
179 return mIconProvider.icon(userId.parent());
182 return KeyFilterManager::instance()->font(userId.parent(), QFont());
190 Formatting::IconProvider mIconProvider;
206 CustomItemsProxyModel(QObject *parent =
nullptr)
207 : QSortFilterProxyModel(parent)
211 ~CustomItemsProxyModel()
override
213 qDeleteAll(mFrontItems);
214 qDeleteAll(mBackItems);
217 bool isCustomItem(
const int row)
const
222 void prependItem(
const QIcon &icon,
const QString &text,
const QVariant &data,
const QString &toolTip)
224 beginInsertRows(QModelIndex(), 0, 0);
225 mFrontItems.push_front(
new CustomItem{icon, text, data, toolTip});
229 void appendItem(
const QIcon &icon,
const QString &text,
const QVariant &data,
const QString &toolTip)
231 beginInsertRows(QModelIndex(), rowCount(), rowCount());
232 mBackItems.push_back(
new CustomItem{icon, text, data, toolTip});
236 void removeCustomItem(
const QVariant &data)
238 for (
int i = 0; i < mFrontItems.count(); ++i) {
239 if (mFrontItems[i]->data == data) {
240 beginRemoveRows(QModelIndex(), i, i);
241 delete mFrontItems.takeAt(i);
246 for (
int i = 0; i < mBackItems.count(); ++i) {
247 if (mBackItems[i]->data == data) {
249 beginRemoveRows(QModelIndex(), index, index);
250 delete mBackItems.takeAt(i);
257 int rowCount(
const QModelIndex &parent = QModelIndex())
const override
262 int columnCount(
const QModelIndex &parent = QModelIndex())
const override
271 QModelIndex mapToSource(
const QModelIndex &index)
const override
276 if (!isCustomItem(index.
row())) {
277 const int sourceRow = index.
row() - mFrontItems.count();
283 QModelIndex mapFromSource(
const QModelIndex &source_index)
const override
289 QModelIndex index(
int row,
int column,
const QModelIndex &parent = QModelIndex())
const override
291 if (row < 0 || row >= rowCount()) {
294 if (row < mFrontItems.count()) {
295 return createIndex(row, column, mFrontItems[row]);
310 QModelIndex parent(
const QModelIndex &)
const override
316 QVariant data(
const QModelIndex &index,
int role)
const override
322 if (isCustomItem(index.
row())) {
323 Q_ASSERT(!mFrontItems.isEmpty() || !mBackItems.isEmpty());
331 case KeyList::UserIDRole:
344 QList<CustomItem *> mFrontItems;
345 QList<CustomItem *> mBackItems;
352class UserIDSelectionComboPrivate
355 UserIDSelectionComboPrivate(UserIDSelectionCombo *parent,
bool secretOnly_, KeyUsage::Flags usage)
357 , secretOnly{secretOnly_}
378 bool selectPerfectIdMatch()
const
380 if (mPerfectMatchMbox.isEmpty()) {
384 for (
int i = 0; i < proxyModel->rowCount(); ++i) {
385 const auto idx = proxyModel->index(i, 0, QModelIndex());
386 const auto userID = idx.data(KeyList::UserIDRole).value<GpgME::UserID>();
387 if (userID.isNull()) {
392 combo->setCurrentIndex(i);
401 void updateWithDefaultKey()
403 GpgME::Protocol filterProto = GpgME::UnknownProtocol;
405 const auto filter =
dynamic_cast<const DefaultKeyFilter *
>(sortFilterProxy->keyFilter().
get());
406 if (filter &&
filter->isOpenPGP() == DefaultKeyFilter::Set) {
407 filterProto = GpgME::OpenPGP;
408 }
else if (filter &&
filter->isOpenPGP() == DefaultKeyFilter::NotSet) {
409 filterProto = GpgME::CMS;
412 QString defaultKey = defaultKeys.value(filterProto);
415 defaultKey = defaultKeys.value(GpgME::UnknownProtocol);
418 if (filterProto == GpgME::UnknownProtocol) {
419 sortFilterProxy->setAlwaysAcceptedKey(defaultKey);
421 const auto key = KeyCache::instance()->findByFingerprint(defaultKey.
toLatin1().
constData());
422 if (!key.isNull() && key.protocol() == filterProto) {
423 sortFilterProxy->setAlwaysAcceptedKey(defaultKey);
425 sortFilterProxy->setAlwaysAcceptedKey({});
428 q->setCurrentKey(defaultKey);
431 void storeCurrentSelectionBeforeModelChange()
433 userIDBeforeModelChange = q->currentUserID();
434 customItemBeforeModelChange = combo->currentData();
437 void restoreCurrentSelectionAfterModelChange()
439 if (!userIDBeforeModelChange.isNull()) {
440 q->setCurrentUserID(userIDBeforeModelChange);
441 }
else if (customItemBeforeModelChange.isValid()) {
442 const auto index = combo->findData(customItemBeforeModelChange);
444 combo->setCurrentIndex(index);
446 updateWithDefaultKey();
451 Kleo::AbstractKeyListModel *model =
nullptr;
452 UserIDProxyModel *userIdProxy =
nullptr;
453 SortFilterProxyModel *sortFilterProxy =
nullptr;
454 SortAndFormatCertificatesProxyModel *sortAndFormatProxy =
nullptr;
455 CustomItemsProxyModel *proxyModel =
nullptr;
456 QComboBox *combo =
nullptr;
457 QToolButton *button =
nullptr;
458 std::shared_ptr<Kleo::KeyCache> cache;
459 QMap<GpgME::Protocol, QString> defaultKeys;
460 bool wasEnabled =
false;
461 bool useWasEnabled =
false;
462 bool secretOnly =
false;
463 bool initialKeyListingDone =
false;
464 QString mPerfectMatchMbox;
465 GpgME::UserID userIDBeforeModelChange;
466 QVariant customItemBeforeModelChange;
467 KeyUsage::Flags usageFlags;
470 UserIDSelectionCombo *
const q;
477UserIDSelectionCombo::UserIDSelectionCombo(
QWidget *parent)
478 : UserIDSelectionCombo(true, KeyUsage::
None, parent)
482UserIDSelectionCombo::UserIDSelectionCombo(
bool secretOnly,
QWidget *parent)
483 : UserIDSelectionCombo(secretOnly, KeyUsage::
None, parent)
487UserIDSelectionCombo::UserIDSelectionCombo(KeyUsage::Flags usage,
QWidget *parent)
488 : UserIDSelectionCombo{false, usage, parent}
492UserIDSelectionCombo::UserIDSelectionCombo(KeyUsage::Flag usage,
QWidget *parent)
493 : UserIDSelectionCombo{false, usage, parent}
497UserIDSelectionCombo::UserIDSelectionCombo(
bool secretOnly, KeyUsage::Flags usage,
QWidget *parent)
499 , d(new UserIDSelectionComboPrivate(this, secretOnly, usage))
503 setAccessibleDescription(QStringLiteral(
" "));
504 d->model = Kleo::AbstractKeyListModel::createFlatKeyListModel(
this);
506 d->userIdProxy =
new UserIDProxyModel(
this);
507 d->userIdProxy->setSourceModel(d->model);
509 d->sortFilterProxy =
new SortFilterProxyModel(
this);
510 d->sortFilterProxy->setSourceModel(d->userIdProxy);
512 d->sortAndFormatProxy =
new SortAndFormatCertificatesProxyModel{usage,
this};
513 d->sortAndFormatProxy->setSourceModel(d->sortFilterProxy);
515 d->sortAndFormatProxy->sort(0);
517 d->proxyModel =
new CustomItemsProxyModel{
this};
518 d->proxyModel->setSourceModel(d->sortAndFormatProxy);
521 layout->setContentsMargins({});
524 layout->addWidget(d->combo);
528 d->button->setToolTip(
i18nc(
"@info:tooltip",
"Show certificate list"));
529 d->button->setAccessibleName(
i18n(
"Show certificate list"));
530 layout->addWidget(d->button);
534 d->combo->setModel(d->proxyModel);
536 if (row >= 0 && row < d->proxyModel->rowCount()) {
537 if (d->proxyModel->isCustomItem(row)) {
538 Q_EMIT customItemSelected(d->combo->currentData(Qt::UserRole));
540 Q_EMIT currentKeyChanged(currentKey());
545 d->cache = Kleo::KeyCache::mutableInstance();
548 d->storeCurrentSelectionBeforeModelChange();
551 d->restoreCurrentSelectionAfterModelChange();
554 d->storeCurrentSelectionBeforeModelChange();
557 d->restoreCurrentSelectionAfterModelChange();
560 d->storeCurrentSelectionBeforeModelChange();
563 d->restoreCurrentSelectionAfterModelChange();
569UserIDSelectionCombo::~UserIDSelectionCombo() =
default;
571void UserIDSelectionCombo::init()
573 connect(d->cache.get(), &Kleo::KeyCache::keyListingDone,
this, [
this]() {
576 if (!d->initialKeyListingDone) {
577 d->model->useKeyCache(true, d->secretOnly ? KeyList::SecretKeysOnly : KeyList::AllKeys);
579 d->proxyModel->removeCustomItem(QStringLiteral(
"-libkleo-loading-keys"));
589 if (d->useWasEnabled) {
590 setEnabled(d->wasEnabled);
591 d->useWasEnabled = false;
593 Q_EMIT keyListingFinished();
596 connect(
this, &UserIDSelectionCombo::keyListingFinished,
this, [
this]() {
597 if (!d->initialKeyListingDone) {
598 d->updateWithDefaultKey();
599 d->initialKeyListingDone =
true;
603 if (!d->cache->initialized()) {
606 d->model->useKeyCache(
true, d->secretOnly ? KeyList::SecretKeysOnly : KeyList::AllKeys);
607 Q_EMIT keyListingFinished();
611 setToolTip(d->combo->currentData(Qt::ToolTipRole).toString());
615void UserIDSelectionCombo::setKeyFilter(
const std::shared_ptr<const KeyFilter> &kf)
617 d->sortFilterProxy->setKeyFilter(kf);
618 d->updateWithDefaultKey();
621std::shared_ptr<const KeyFilter> UserIDSelectionCombo::keyFilter()
const
623 return d->sortFilterProxy->keyFilter();
626void UserIDSelectionCombo::setIdFilter(
const QString &
id)
628 d->sortFilterProxy->setFilterRegularExpression(
id);
629 d->mPerfectMatchMbox = id;
630 d->updateWithDefaultKey();
633QString UserIDSelectionCombo::idFilter()
const
635 return d->sortFilterProxy->filterRegularExpression().pattern();
638GpgME::Key Kleo::UserIDSelectionCombo::currentKey()
const
640 return d->combo->currentData(KeyList::KeyRole).value<GpgME::Key>();
643void Kleo::UserIDSelectionCombo::setCurrentKey(
const GpgME::Key &key)
647 d->combo->setCurrentIndex(idx);
648 }
else if (!d->selectPerfectIdMatch()) {
649 d->updateWithDefaultKey();
654void Kleo::UserIDSelectionCombo::setCurrentKey(
const QString &fingerprint)
656 const auto cur = currentKey();
657 if (!cur.isNull() && !fingerprint.
isEmpty() && fingerprint == QLatin1StringView(cur.primaryFingerprint())) {
660 Q_EMIT currentKeyChanged(cur);
663 const int idx = d->combo->findData(fingerprint, KeyList::FingerprintRole,
Qt::MatchExactly);
665 d->combo->setCurrentIndex(idx);
666 }
else if (!d->selectPerfectIdMatch()) {
667 d->combo->setCurrentIndex(0);
672GpgME::UserID Kleo::UserIDSelectionCombo::currentUserID()
const
674 return d->combo->currentData(KeyList::UserIDRole).value<GpgME::UserID>();
677void Kleo::UserIDSelectionCombo::setCurrentUserID(
const GpgME::UserID &userID)
679 for (
auto i = 0; i < d->combo->count(); i++) {
680 const auto &other = d->combo->itemData(i, KeyList::UserIDRole).value<GpgME::UserID>();
681 if (!qstrcmp(userID.id(), other.id()) && !qstrcmp(userID.parent().primaryFingerprint(), other.parent().primaryFingerprint())) {
682 d->combo->setCurrentIndex(i);
687 if (!d->selectPerfectIdMatch()) {
688 d->updateWithDefaultKey();
693void UserIDSelectionCombo::refreshKeys()
696 d->useWasEnabled =
true;
699 prependCustomItem(QIcon(),
i18n(
"Loading keys ..."), QStringLiteral(
"-libkleo-loading-keys"));
700 d->combo->setCurrentIndex(0);
702 d->cache->startKeyListing();
705void UserIDSelectionCombo::appendCustomItem(
const QIcon &icon,
const QString &text,
const QVariant &data,
const QString &toolTip)
707 d->proxyModel->appendItem(icon, text, data,
toolTip);
710void UserIDSelectionCombo::appendCustomItem(
const QIcon &icon,
const QString &text,
const QVariant &data)
712 appendCustomItem(icon, text, data, QString());
715void UserIDSelectionCombo::prependCustomItem(
const QIcon &icon,
const QString &text,
const QVariant &data,
const QString &toolTip)
717 d->proxyModel->prependItem(icon, text, data,
toolTip);
720void UserIDSelectionCombo::prependCustomItem(
const QIcon &icon,
const QString &text,
const QVariant &data)
722 prependCustomItem(icon, text, data, QString());
725void UserIDSelectionCombo::removeCustomItem(
const QVariant &data)
727 d->proxyModel->removeCustomItem(data);
730void Kleo::UserIDSelectionCombo::setDefaultKey(
const QString &fingerprint, GpgME::Protocol proto)
732 d->defaultKeys.insert(proto, fingerprint);
733 d->updateWithDefaultKey();
736void Kleo::UserIDSelectionCombo::setDefaultKey(
const QString &fingerprint)
738 setDefaultKey(fingerprint, GpgME::UnknownProtocol);
741QString Kleo::UserIDSelectionCombo::defaultKey(GpgME::Protocol proto)
const
743 return d->defaultKeys.value(proto);
746QString Kleo::UserIDSelectionCombo::defaultKey()
const
748 return defaultKey(GpgME::UnknownProtocol);
751QComboBox *Kleo::UserIDSelectionCombo::combo()
const
756int Kleo::UserIDSelectionCombo::findUserId(
const GpgME::UserID &userId)
const
758 for (
int i = 0; i < combo()->model()->rowCount(); i++) {
759 if (Kleo::userIDsAreEqual(userId, combo()->model()->index(i, 0).data(KeyList::UserIDRole).value<GpgME::UserID>())) {
766#include "useridselectioncombo.moc"
768#include "moc_useridselectioncombo.cpp"
QString i18nc(const char *context, const char *text, const TYPE &arg...)
QString i18n(const char *text, const TYPE &arg...)
KIOCORE_EXPORT TransferJob * get(const QUrl &url, LoadType reload=NoReload, JobFlags flags=DefaultFlags)
void modelAboutToBeReset()
void rowsAboutToBeInserted(const QModelIndex &parent, int start, int end)
void rowsAboutToBeRemoved(const QModelIndex &parent, int first, int last)
void rowsInserted(const QModelIndex &parent, int first, int last)
void rowsRemoved(const QModelIndex &parent, int first, int last)
const char * constData() const const
void currentIndexChanged(int index)
QIcon fromTheme(const QString &name)
void * internalPointer() const const
bool isValid() const const
bool blockSignals(bool block)
QMetaObject::Connection connect(const QObject *sender, PointerToMemberFunction signal, Functor functor)
virtual QVariant data(const QModelIndex &index, int role) const const override
virtual QModelIndex index(int row, int column, const QModelIndex &parent) const const override
virtual QModelIndex mapFromSource(const QModelIndex &sourceIndex) const const override
virtual QModelIndex mapToSource(const QModelIndex &proxyIndex) const const override
virtual int rowCount(const QModelIndex &parent) const const override
QString fromLatin1(QByteArrayView str)
QString fromStdString(const std::string &str)
QString fromUtf8(QByteArrayView str)
bool isEmpty() const const
int localeAwareCompare(QStringView s1, QStringView s2)
QByteArray toLatin1() const const
QFuture< void > filter(QThreadPool *pool, Sequence &sequence, KeepFunctor &&filterFunction)
QFuture< ArgsType< Signal > > connect(Sender *sender, Signal signal)