diff --git a/src/conf/cryptooperationsconfigwidget.cpp b/src/conf/cryptooperationsconfigwidget.cpp index 38bce2e88..6067e4e89 100644 --- a/src/conf/cryptooperationsconfigwidget.cpp +++ b/src/conf/cryptooperationsconfigwidget.cpp @@ -1,385 +1,385 @@ /* cryptooperationsconfigwidget.cpp This file is part of kleopatra, the KDE key manager SPDX-FileCopyrightText: 2010 Klarälvdalens Datakonsult AB 2016 by Bundesamt für Sicherheit in der Informationstechnik SPDX-FileContributor: Intevation GmbH SPDX-License-Identifier: GPL-2.0-or-later */ #include #include "cryptooperationsconfigwidget.h" #include "kleopatra_debug.h" #include "emailoperationspreferences.h" #include "fileoperationspreferences.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace Kleo; using namespace Kleo::Config; CryptoOperationsConfigWidget::CryptoOperationsConfigWidget(QWidget *p, Qt::WindowFlags f) : QWidget(p, f), mApplyBtn(nullptr) { setupGui(); } static void resetDefaults() { auto config = QGpgME::cryptoConfig(); if (!config) { qCWarning(KLEOPATRA_LOG) << "Failed to obtain config"; return; } const QStringList componentList = config->componentList(); for (const auto &compName: componentList) { auto comp = config->component(compName); if (!comp) { qCWarning(KLEOPATRA_LOG) << "Failed to find component:" << comp; return; } const QStringList groupList = comp->groupList(); for (const auto &grpName: groupList) { auto grp = comp->group(grpName); if (!grp) { qCWarning(KLEOPATRA_LOG) << "Failed to find group:" << grp << "in component:" << compName; return; } const QStringList entries = grp->entryList(); for (const auto &entryName: entries) { auto entry = grp->entry(entryName); if (!entry) { qCWarning(KLEOPATRA_LOG) << "Failed to find entry:" << entry << "in group:"<< grp << "in component:" << compName; return; } entry->resetToDefault(); } } } config->sync(true); return; } void CryptoOperationsConfigWidget::applyProfile(const QString &profile) { if (profile.isEmpty()) { return; } qCDebug(KLEOPATRA_LOG) << "Applying profile " << profile; if (profile == i18n("default")) { if (KMessageBox::warningYesNo( this, i18n("This means that every configuration option of the GnuPG System will be reset to its default."), i18n("Apply profile"), KStandardGuiItem::apply(), KStandardGuiItem::no()) != KMessageBox::Yes) { return; } resetDefaults(); KeyFilterManager::instance()->reload(); return; } mApplyBtn->setEnabled(false); QDir datadir(QString::fromLocal8Bit(GpgME::dirInfo("datadir")) + QStringLiteral("/../doc/gnupg/examples")); const auto path = datadir.filePath(profile + QStringLiteral(".prf")); auto gpgconf = new QProcess; const auto ei = GpgME::engineInfo(GpgME::GpgConfEngine); Q_ASSERT (ei.fileName()); gpgconf->setProgram(QFile::decodeName(ei.fileName())); gpgconf->setProcessChannelMode(QProcess::MergedChannels); gpgconf->setArguments(QStringList() << QStringLiteral("--runtime") << QStringLiteral("--apply-profile") << path); qDebug() << "Starting" << ei.fileName() << "with args" << gpgconf->arguments(); connect(gpgconf, static_cast(&QProcess::finished), this, [this, gpgconf, profile] () { mApplyBtn->setEnabled(true); if (gpgconf->exitStatus() != QProcess::NormalExit) { KMessageBox::error(this, QStringLiteral("
%1
").arg(QString::fromLocal8Bit(gpgconf->readAll()))); delete gpgconf; return; } delete gpgconf; KMessageBox::information(this, i18nc("%1 is the name of the profile", "The configuration profile \"%1\" was applied.", profile), i18n("GnuPG Profile - Kleopatra")); auto config = QGpgME::cryptoConfig(); if (config) { config->clear(); } KeyFilterManager::instance()->reload(); }); gpgconf->start(); } // Get a list of available profile files and add a configuration // group if there are any. void CryptoOperationsConfigWidget::setupProfileGui(QBoxLayout *layout) { qCDebug(KLEOPATRA_LOG) << "Engine version "; if (GpgME::engineInfo(GpgME::GpgEngine).engineVersion() < "2.1.20" || !layout) { // Profile support is new in 2.1.20 qCDebug(KLEOPATRA_LOG) << "Engine version false"; return; } QDir datadir(QString::fromLocal8Bit(GpgME::dirInfo("datadir")) + QStringLiteral("/../doc/gnupg/examples")); if (!datadir.exists()) { qCDebug(KLEOPATRA_LOG) << "Failed to find gnupg's example profile directory" << datadir.path(); return; } const auto profiles = datadir.entryInfoList(QStringList() << QStringLiteral("*.prf"), QDir::Readable | QDir::Files, QDir::Name); if (profiles.isEmpty()) { qCDebug(KLEOPATRA_LOG) << "Failed to find any profiles in: " << datadir.path(); return; } auto genGrp = new QGroupBox(i18nc("@title", "General Operations")); auto profLayout = new QHBoxLayout; genGrp->setLayout(profLayout); layout->addWidget(genGrp); auto profLabel = new QLabel(i18n("Activate GnuPG Profile:")); profLabel->setToolTip(i18n("A profile consists of various settings that can apply to multiple components of the GnuPG system.")); auto combo = new QComboBox; profLabel->setBuddy(combo); // Add an empty Item to avoid the impression that this GUI element // shows the currently selected profile. combo->addItem(QString()); // We don't translate "default" here because the other profile names are // also not translated as they are taken directly from file. combo->addItem(i18n("default")); for (const auto &profile: profiles) { combo->addItem(profile.baseName()); } mApplyBtn = new QPushButton(i18n("Apply")); mApplyBtn->setEnabled(false); profLayout->addWidget(profLabel); profLayout->addWidget(combo); profLayout->addWidget(mApplyBtn); profLayout->addStretch(1); connect(mApplyBtn, &QPushButton::clicked, this, [this, combo] () { applyProfile(combo->currentText()); }); - connect(combo, QOverload::of(&QComboBox::currentTextChanged), this, [this] (const QString &text) { + connect(combo, qOverload(&QComboBox::currentTextChanged), this, [this] (const QString &text) { mApplyBtn->setEnabled(!text.isEmpty()); }); } void CryptoOperationsConfigWidget::setupGui() { auto baseLay = new QVBoxLayout(this); baseLay->setContentsMargins(0, 0, 0, 0); auto mailGrp = new QGroupBox(i18n("EMail Operations")); auto mailGrpLayout = new QVBoxLayout; mQuickSignCB = new QCheckBox(i18n("Don't confirm signing certificate if there is only one valid certificate for the identity")); mQuickEncryptCB = new QCheckBox(i18n("Don't confirm encryption certificates if there is exactly one valid certificate for each recipient")); mailGrpLayout->addWidget(mQuickSignCB); mailGrpLayout->addWidget(mQuickEncryptCB); mailGrp->setLayout(mailGrpLayout); baseLay->addWidget(mailGrp); auto fileGrp = new QGroupBox(i18n("File Operations")); auto fileGrpLay = new QVBoxLayout; mPGPFileExtCB = new QCheckBox(i18n(R"(Create OpenPGP encrypted files with ".pgp" file extensions instead of ".gpg")")); mASCIIArmorCB = new QCheckBox(i18n("Create signed or encrypted files as text files.")); mASCIIArmorCB->setToolTip(i18nc("@info", "Set this option to encode encrypted or signed files as base64 encoded text. " "So that they can be opened with an editor or sent in a mail body. " "This will increase file size by one third.")); mAutoDecryptVerifyCB = new QCheckBox(i18n("Automatically start operation based on input detection for decrypt/verify.")); mTmpDirCB = new QCheckBox(i18n("Create temporary decrypted files in the folder of the encrypted file.")); mTmpDirCB->setToolTip(i18nc("@info", "Set this option to avoid using the users temporary directory.")); fileGrpLay->addWidget(mPGPFileExtCB); fileGrpLay->addWidget(mAutoDecryptVerifyCB); fileGrpLay->addWidget(mASCIIArmorCB); fileGrpLay->addWidget(mTmpDirCB); auto comboLay = new QGridLayout; auto chkLabel = new QLabel(i18n("Checksum program to use when creating checksum files:")); comboLay->addWidget(chkLabel, 0, 0); mChecksumDefinitionCB = new QComboBox; comboLay->addWidget(mChecksumDefinitionCB, 0, 1); auto archLabel = new QLabel(i18n("Archive command to use when archiving files:")); comboLay->addWidget(archLabel, 1, 0); mArchiveDefinitionCB = new QComboBox; comboLay->addWidget(mArchiveDefinitionCB, 1, 1); fileGrpLay->addLayout(comboLay); fileGrp->setLayout(fileGrpLay); baseLay->addWidget(fileGrp); setupProfileGui(baseLay); baseLay->addStretch(1); if (!GpgME::hasFeature(0, GpgME::BinaryAndFineGrainedIdentify)) { /* Auto handling requires a working identify in GpgME. * so that classify in kleoaptra can correctly detect the input.*/ mAutoDecryptVerifyCB->setVisible(false); } connect(mQuickSignCB, &QCheckBox::toggled, this, &CryptoOperationsConfigWidget::changed); connect(mQuickEncryptCB, &QCheckBox::toggled, this, &CryptoOperationsConfigWidget::changed); connect(mChecksumDefinitionCB, static_cast(&QComboBox::currentIndexChanged), this, &CryptoOperationsConfigWidget::changed); connect(mArchiveDefinitionCB, static_cast(&QComboBox::currentIndexChanged), this, &CryptoOperationsConfigWidget::changed); connect(mPGPFileExtCB, &QCheckBox::toggled, this, &CryptoOperationsConfigWidget::changed); connect(mAutoDecryptVerifyCB, &QCheckBox::toggled, this, &CryptoOperationsConfigWidget::changed); connect(mASCIIArmorCB, &QCheckBox::toggled, this, &CryptoOperationsConfigWidget::changed); connect(mTmpDirCB, &QCheckBox::toggled, this, &CryptoOperationsConfigWidget::changed); } CryptoOperationsConfigWidget::~CryptoOperationsConfigWidget() {} void CryptoOperationsConfigWidget::defaults() { EMailOperationsPreferences emailPrefs; emailPrefs.setDefaults(); mQuickSignCB->setChecked(emailPrefs.quickSignEMail()); mQuickEncryptCB->setChecked(emailPrefs.quickEncryptEMail()); FileOperationsPreferences filePrefs; filePrefs.setDefaults(); mPGPFileExtCB->setChecked(filePrefs.usePGPFileExt()); mAutoDecryptVerifyCB->setChecked(filePrefs.autoDecryptVerify()); if (mChecksumDefinitionCB->count()) { mChecksumDefinitionCB->setCurrentIndex(0); } if (mArchiveDefinitionCB->count()) { mArchiveDefinitionCB->setCurrentIndex(0); } } Q_DECLARE_METATYPE(std::shared_ptr) void CryptoOperationsConfigWidget::load() { const EMailOperationsPreferences emailPrefs; mQuickSignCB ->setChecked(emailPrefs.quickSignEMail()); mQuickEncryptCB->setChecked(emailPrefs.quickEncryptEMail()); const FileOperationsPreferences filePrefs; mPGPFileExtCB->setChecked(filePrefs.usePGPFileExt()); mAutoDecryptVerifyCB->setChecked(filePrefs.autoDecryptVerify()); mASCIIArmorCB->setChecked(filePrefs.addASCIIArmor()); mTmpDirCB->setChecked(filePrefs.dontUseTmpDir()); const std::vector< std::shared_ptr > cds = ChecksumDefinition::getChecksumDefinitions(); const std::shared_ptr default_cd = ChecksumDefinition::getDefaultChecksumDefinition(cds); mChecksumDefinitionCB->clear(); mArchiveDefinitionCB->clear(); for (const std::shared_ptr &cd : cds) { mChecksumDefinitionCB->addItem(cd->label(), QVariant::fromValue(cd)); if (cd == default_cd) { mChecksumDefinitionCB->setCurrentIndex(mChecksumDefinitionCB->count() - 1); } } const QString ad_default_id = filePrefs.archiveCommand(); // This is a weird hack but because we are a KCM we can't link // against ArchiveDefinition which pulls in loads of other classes. // So we do the parsing which archive definitions exist here ourself. if (KSharedConfigPtr config = KSharedConfig::openConfig(QStringLiteral("libkleopatrarc"))) { const QStringList groups = config->groupList().filter(QRegularExpression(QStringLiteral("^Archive Definition #"))); for (const QString &group : groups) { const KConfigGroup cGroup(config, group); const QString id = cGroup.readEntryUntranslated(QStringLiteral("id")); const QString name = cGroup.readEntry("Name"); mArchiveDefinitionCB->addItem(name, QVariant(id)); if (id == ad_default_id) { mArchiveDefinitionCB->setCurrentIndex(mArchiveDefinitionCB->count() - 1); } } } } void CryptoOperationsConfigWidget::save() { EMailOperationsPreferences emailPrefs; emailPrefs.setQuickSignEMail(mQuickSignCB ->isChecked()); emailPrefs.setQuickEncryptEMail(mQuickEncryptCB->isChecked()); emailPrefs.save(); FileOperationsPreferences filePrefs; filePrefs.setUsePGPFileExt(mPGPFileExtCB->isChecked()); filePrefs.setAutoDecryptVerify(mAutoDecryptVerifyCB->isChecked()); filePrefs.setAddASCIIArmor(mASCIIArmorCB->isChecked()); filePrefs.setDontUseTmpDir(mTmpDirCB->isChecked()); const int idx = mChecksumDefinitionCB->currentIndex(); if (idx >= 0) { const auto cd = qvariant_cast< std::shared_ptr >(mChecksumDefinitionCB->itemData(idx)); ChecksumDefinition::setDefaultChecksumDefinition(cd); } const int aidx = mArchiveDefinitionCB->currentIndex(); if (aidx >= 0) { const QString id = mArchiveDefinitionCB->itemData(aidx).toString(); filePrefs.setArchiveCommand(id); } filePrefs.save(); } diff --git a/src/crypto/gui/certificatelineedit.cpp b/src/crypto/gui/certificatelineedit.cpp index 0564454dc..01225a592 100644 --- a/src/crypto/gui/certificatelineedit.cpp +++ b/src/crypto/gui/certificatelineedit.cpp @@ -1,329 +1,329 @@ /* crypto/gui/certificatelineedit.cpp This file is part of Kleopatra, the KDE keymanager SPDX-FileCopyrightText: 2016 Bundesamt für Sicherheit in der Informationstechnik SPDX-FileContributor: Intevation GmbH SPDX-FileCopyrightText: 2021 g10 Code GmbH SPDX-FileContributor: Ingo Klöcker SPDX-License-Identifier: GPL-2.0-or-later */ #include "certificatelineedit.h" #include #include #include #include #include "kleopatra_debug.h" #include #include #include #include #include #include #include #include #include #include using namespace Kleo; using namespace GpgME; Q_DECLARE_METATYPE(GpgME::Key) Q_DECLARE_METATYPE(KeyGroup) static QStringList s_lookedUpKeys; namespace { class ProxyModel : public KeyListSortFilterProxyModel { Q_OBJECT public: ProxyModel(QObject *parent = nullptr) : KeyListSortFilterProxyModel(parent) { } QVariant data(const QModelIndex &index, int role) const override { if (!index.isValid()) { return QVariant(); } switch (role) { case Qt::DecorationRole: { const auto key = KeyListSortFilterProxyModel::data(index, KeyList::KeyRole).value(); if (!key.isNull()) { return Kleo::Formatting::iconForUid(key.userID(0)); } const auto group = KeyListSortFilterProxyModel::data(index, KeyList::GroupRole).value(); if (!group.isNull()) { return QIcon::fromTheme(QStringLiteral("group")); } Q_ASSERT(!key.isNull() || !group.isNull()); return QVariant(); } default: return KeyListSortFilterProxyModel::data(index, role); } } }; } // namespace CertificateLineEdit::CertificateLineEdit(AbstractKeyListModel *model, QWidget *parent, KeyFilter *filter) : QLineEdit(parent), mFilterModel(new KeyListSortFilterProxyModel(this)), mCompleterFilterModel(new ProxyModel(this)), mCompleter(new QCompleter(this)), mFilter(std::shared_ptr(filter)), mLineAction(new QAction(this)) { setPlaceholderText(i18n("Please enter a name or email address...")); setClearButtonEnabled(true); addAction(mLineAction, QLineEdit::LeadingPosition); mCompleterFilterModel->setKeyFilter(mFilter); mCompleterFilterModel->setSourceModel(model); mCompleter->setModel(mCompleterFilterModel); mCompleter->setCompletionColumn(KeyList::Summary); mCompleter->setFilterMode(Qt::MatchContains); mCompleter->setCaseSensitivity(Qt::CaseInsensitive); setCompleter(mCompleter); mFilterModel->setSourceModel(model); mFilterModel->setFilterKeyColumn(KeyList::Summary); if (filter) { mFilterModel->setKeyFilter(mFilter); } connect(KeyCache::instance().get(), &Kleo::KeyCache::keyListingDone, this, &CertificateLineEdit::updateKey); connect(KeyCache::instance().get(), &Kleo::KeyCache::groupUpdated, this, [this] (const KeyGroup &group) { if (!mGroup.isNull() && mGroup.source() == group.source() && mGroup.id() == group.id()) { QSignalBlocker blocky(this); setText(Formatting::summaryLine(group)); // queue the update to ensure that the model has been updated QMetaObject::invokeMethod(this, &CertificateLineEdit::updateKey, Qt::QueuedConnection); } }); connect(KeyCache::instance().get(), &Kleo::KeyCache::groupRemoved, this, [this] (const KeyGroup &group) { if (!mGroup.isNull() && mGroup.source() == group.source() && mGroup.id() == group.id()) { mGroup = KeyGroup(); QSignalBlocker blocky(this); clear(); // queue the update to ensure that the model has been updated QMetaObject::invokeMethod(this, &CertificateLineEdit::updateKey, Qt::QueuedConnection); } }); connect(this, &QLineEdit::editingFinished, this, [this] () { // queue the call of editFinished() to ensure that QCompleter::activated is handled first QMetaObject::invokeMethod(this, &CertificateLineEdit::editFinished, Qt::QueuedConnection); }); connect(this, &QLineEdit::textChanged, this, &CertificateLineEdit::editChanged); connect(mLineAction, &QAction::triggered, this, &CertificateLineEdit::dialogRequested); - connect(mCompleter, QOverload::of(&QCompleter::activated), + connect(mCompleter, qOverload(&QCompleter::activated), this, [this] (const QModelIndex &index) { Key key = mCompleter->completionModel()->data(index, KeyList::KeyRole).value(); auto group = mCompleter->completionModel()->data(index, KeyList::GroupRole).value(); if (!key.isNull()) { setKey(key); } else if (!group.isNull()) { setGroup(group); } else { qCDebug(KLEOPATRA_LOG) << "Activated item is neither key nor group"; } }); updateKey(); /* Take ownership of the model to prevent double deletion when the * filter models are deleted */ model->setParent(parent ? parent : this); } void CertificateLineEdit::editChanged() { updateKey(); if (!mEditStarted) { Q_EMIT editingStarted(); mEditStarted = true; } mEditFinished = false; } void CertificateLineEdit::editFinished() { mEditStarted = false; mEditFinished = true; updateKey(); checkLocate(); } void CertificateLineEdit::checkLocate() { if (!key().isNull() || !group().isNull()) { // Already have a key or group return; } // Only check once per mailbox const auto mailText = text(); if (s_lookedUpKeys.contains(mailText)) { return; } s_lookedUpKeys << mailText; qCDebug(KLEOPATRA_LOG) << "Lookup job for" << mailText; QGpgME::KeyForMailboxJob *job = QGpgME::openpgp()->keyForMailboxJob(); job->start(mailText); } void CertificateLineEdit::updateKey() { static const _detail::ByFingerprint keysHaveSameFingerprint; const auto mailText = text(); auto newKey = Key(); auto newGroup = KeyGroup(); if (mailText.isEmpty()) { mLineAction->setIcon(QIcon::fromTheme(QStringLiteral("resource-group-new"))); mLineAction->setToolTip(i18n("Open selection dialog.")); } else { mFilterModel->setFilterFixedString(mailText); if (mFilterModel->rowCount() > 1) { // keep current key or group if they still match if (!mKey.isNull()) { for (int row = 0; row < mFilterModel->rowCount(); ++row) { const QModelIndex index = mFilterModel->index(row, 0); Key key = mFilterModel->key(index); if (!key.isNull() && keysHaveSameFingerprint(key, mKey)) { newKey = mKey; break; } } } else if (!mGroup.isNull()) { newGroup = mGroup; for (int row = 0; row < mFilterModel->rowCount(); ++row) { const QModelIndex index = mFilterModel->index(row, 0); KeyGroup group = mFilterModel->group(index); if (!group.isNull() && group.source() == mGroup.source() && group.id() == mGroup.id()) { newGroup = mGroup; break; } } } if (newKey.isNull() && newGroup.isNull()) { if (mEditFinished) { mLineAction->setIcon(QIcon::fromTheme(QStringLiteral("question"))); mLineAction->setToolTip(i18n("Multiple certificates")); } else { mLineAction->setIcon(QIcon::fromTheme(QStringLiteral("resource-group-new"))); mLineAction->setToolTip(i18n("Open selection dialog.")); } } } else if (mFilterModel->rowCount() == 1) { const auto index = mFilterModel->index(0, 0); newKey = mFilterModel->data(index, KeyList::KeyRole).value(); newGroup = mFilterModel->data(index, KeyList::GroupRole).value(); Q_ASSERT(!newKey.isNull() || !newGroup.isNull()); if (newKey.isNull() && newGroup.isNull()) { mLineAction->setIcon(QIcon::fromTheme(QStringLiteral("emblem-error"))); mLineAction->setToolTip(i18n("No matching certificates found.
Click here to import a certificate.")); } } else { mLineAction->setIcon(QIcon::fromTheme(QStringLiteral("emblem-error"))); mLineAction->setToolTip(i18n("No matching certificates found.
Click here to import a certificate.")); } } mKey = newKey; mGroup = newGroup; if (!mKey.isNull()) { /* FIXME: This needs to be solved by a multiple UID supporting model */ mLineAction->setIcon(Formatting::iconForUid(mKey.userID(0))); mLineAction->setToolTip(Formatting::validity(mKey.userID(0)) + QLatin1String("
") + i18n("Click for details.")); setToolTip(Formatting::toolTip(mKey, Formatting::ToolTipOption::AllOptions)); } else if (!mGroup.isNull()) { mLineAction->setIcon(Formatting::validityIcon(mGroup)); mLineAction->setToolTip(Formatting::validity(mGroup) + QLatin1String("
") + i18n("Click for details.")); setToolTip(Formatting::toolTip(mGroup, Formatting::ToolTipOption::AllOptions)); } else { setToolTip(QString()); } Q_EMIT keyChanged(); if (mailText.isEmpty()) { Q_EMIT wantsRemoval(this); } } Key CertificateLineEdit::key() const { if (isEnabled()) { return mKey; } else { return Key(); } } KeyGroup CertificateLineEdit::group() const { if (isEnabled()) { return mGroup; } else { return KeyGroup(); } } void CertificateLineEdit::setKey(const Key &key) { mKey = key; mGroup = KeyGroup(); QSignalBlocker blocky(this); qCDebug(KLEOPATRA_LOG) << "Setting Key. " << Formatting::summaryLine(key); setText(Formatting::summaryLine(key)); updateKey(); } void CertificateLineEdit::setGroup(const KeyGroup &group) { mGroup = group; mKey = Key(); QSignalBlocker blocky(this); const QString summary = Formatting::summaryLine(group); qCDebug(KLEOPATRA_LOG) << "Setting KeyGroup. " << summary; setText(summary); updateKey(); } bool CertificateLineEdit::isEmpty() const { return text().isEmpty(); } void CertificateLineEdit::setKeyFilter(const std::shared_ptr &filter) { mFilter = filter; mFilterModel->setKeyFilter(filter); mCompleterFilterModel->setKeyFilter(mFilter); updateKey(); } #include "certificatelineedit.moc" diff --git a/src/dialogs/expirydialog.cpp b/src/dialogs/expirydialog.cpp index d8146715c..77167dd0d 100644 --- a/src/dialogs/expirydialog.cpp +++ b/src/dialogs/expirydialog.cpp @@ -1,328 +1,328 @@ /* -*- mode: c++; c-basic-offset:4 -*- dialogs/expirydialog.cpp This file is part of Kleopatra, the KDE keymanager SPDX-FileCopyrightText: 2008 Klarälvdalens Datakonsult AB SPDX-FileCopyrightText: 2021 g10 Code GmbH SPDX-FileContributor: Ingo Klöcker SPDX-License-Identifier: GPL-2.0-or-later */ #include #include "expirydialog.h" #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace Kleo; using namespace Kleo::Dialogs; namespace { enum Period { Days, Weeks, Months, Years, NumPeriods }; static QDate date_by_amount_and_unit(int inAmount, int inUnit) { const QDate current = QDate::currentDate(); switch (inUnit) { case Days: return current.addDays(inAmount); case Weeks: return current.addDays(7 * inAmount); case Months: return current.addMonths(inAmount); case Years: return current.addYears(inAmount); default: Q_ASSERT(!"Should not reach here"); } return QDate(); } // these calculations should be precise enough for the forseeable future... static const double DAYS_IN_GREGORIAN_YEAR = 365.2425; static int monthsBetween(const QDate &d1, const QDate &d2) { const int days = d1.daysTo(d2); return qRound(days / DAYS_IN_GREGORIAN_YEAR * 12); } static int yearsBetween(const QDate &d1, const QDate &d2) { const int days = d1.daysTo(d2); return qRound(days / DAYS_IN_GREGORIAN_YEAR); } auto radioButtonSize(const QRadioButton *radioButton) { QStyleOptionButton opt; return radioButton->style()->sizeFromContents(QStyle::CT_RadioButton, &opt, QSize(), radioButton); } } class ExpiryDialog::Private { friend class ::Kleo::Dialogs::ExpiryDialog; ExpiryDialog *const q; public: explicit Private(Mode mode, ExpiryDialog *qq) : q{qq} , mode{mode} , inUnit{Days} , ui{mode, q} { connect(ui.inSB, &QSpinBox::valueChanged, q, [this] () { slotInAmountChanged(); }); - connect(ui.inCB, QOverload::of(&QComboBox::currentIndexChanged), + connect(ui.inCB, qOverload(&QComboBox::currentIndexChanged), q, [this] () { slotInUnitChanged(); }); connect(ui.onCW, &QCalendarWidget::selectionChanged, q, [this] () { slotOnDateChanged(); }); connect(ui.onCW, &QCalendarWidget::currentPageChanged, q, [this] (int year, int month) { // We select the same day in the month when // a page is switched. auto date = ui.onCW->selectedDate(); if (!date.setDate(year, month, date.day())) { date.setDate(year, month, 1); } ui.onCW->setSelectedDate(date); }); Q_ASSERT(ui.inCB->currentIndex() == inUnit); } private: void slotInAmountChanged(); void slotInUnitChanged(); void slotOnDateChanged(); private: QDate inDate() const; int inAmountByDate(const QDate &date) const; private: ExpiryDialog::Mode mode; int inUnit; struct UI { QRadioButton *neverRB; QRadioButton *inRB; QSpinBox *inSB; QComboBox *inCB; QRadioButton *onRB; QCalendarWidget *onCW; QCheckBox *updateSubkeysCheckBox; explicit UI(Mode mode, Dialogs::ExpiryDialog *qq) { auto mainLayout = new QVBoxLayout{qq}; auto mainWidget = new QWidget{qq}; auto vboxLayout = new QVBoxLayout{mainWidget}; vboxLayout->setContentsMargins(0, 0, 0, 0); { auto label = new QLabel{qq}; label->setText(mode == Mode::UpdateIndividualSubkey ? i18n("Please select when to expire this subkey:") : i18n("Please select when to expire this certificate:")); vboxLayout->addWidget(label); } neverRB = new QRadioButton(i18n("Ne&ver"), mainWidget); neverRB->setChecked(false); vboxLayout->addWidget(neverRB); { auto hboxLayout = new QHBoxLayout; inRB = new QRadioButton{i18n("In"), mainWidget}; inRB->setChecked(false); hboxLayout->addWidget(inRB); inSB = new QSpinBox{mainWidget}; inSB->setEnabled(false); inSB->setAlignment(Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter); inSB->setMinimum(1); hboxLayout->addWidget(inSB); inCB = new QComboBox{mainWidget}; inCB->addItem(i18n("Days")); inCB->addItem(i18n("Weeks")); inCB->addItem(i18n("Months")); inCB->addItem(i18n("Years")); Q_ASSERT(inCB->count() == NumPeriods); inCB->setEnabled(false); hboxLayout->addWidget(inCB); hboxLayout->addStretch(1); vboxLayout->addLayout(hboxLayout); } onRB = new QRadioButton{i18n("On this da&y:"), mainWidget}; onRB->setChecked(true); vboxLayout->addWidget(onRB); { auto hboxLayout = new QHBoxLayout; hboxLayout->addSpacing(radioButtonSize(onRB).width()); onCW = new QCalendarWidget{mainWidget}; onCW->setGridVisible(true); onCW->setMinimumDate(QDate::currentDate().addDays(1)); hboxLayout->addWidget(onCW); hboxLayout->addStretch(1); vboxLayout->addLayout(hboxLayout); } { updateSubkeysCheckBox = new QCheckBox{i18n("Also update the expiry of the subkeys"), qq}; #ifdef QGPGME_SUPPORTS_CHANGING_EXPIRATION_OF_COMPLETE_KEY updateSubkeysCheckBox->setVisible(mode == Mode::UpdateCertificateWithSubkeys); #else updateSubkeysCheckBox->setVisible(false); #endif vboxLayout->addWidget(updateSubkeysCheckBox); } vboxLayout->addStretch(1); mainLayout->addWidget(mainWidget); auto buttonBox = new QDialogButtonBox{QDialogButtonBox::Ok | QDialogButtonBox::Cancel, qq}; auto okButton = buttonBox->button(QDialogButtonBox::Ok); KGuiItem::assign(okButton, KStandardGuiItem::ok()); okButton->setDefault(true); okButton->setShortcut(Qt::CTRL | Qt::Key_Return); KGuiItem::assign(buttonBox->button(QDialogButtonBox::Cancel), KStandardGuiItem::cancel()); qq->connect(buttonBox, &QDialogButtonBox::accepted, qq, &QDialog::accept); qq->connect(buttonBox, &QDialogButtonBox::rejected, qq, &QDialog::reject); mainLayout->addWidget(buttonBox); connect(onRB, &QRadioButton::toggled, onCW, &QWidget::setEnabled); connect(inRB, &QRadioButton::toggled, inCB, &QWidget::setEnabled); connect(inRB, &QRadioButton::toggled, inSB, &QWidget::setEnabled); } } ui; }; void ExpiryDialog::Private::slotInUnitChanged() { const int oldInAmount = ui.inSB->value(); const QDate targetDate = date_by_amount_and_unit(oldInAmount, inUnit); inUnit = ui.inCB->currentIndex(); if (targetDate.isValid()) { ui.inSB->setValue(inAmountByDate(targetDate)); } else { slotInAmountChanged(); } } void ExpiryDialog::Private::slotInAmountChanged() { // Only modify onCW when onCW is slave: if (ui.inRB->isChecked()) { ui.onCW->setSelectedDate(inDate()); } } void ExpiryDialog::Private::slotOnDateChanged() { // Only modify inSB/inCB when onCW is master: if (ui.onRB->isChecked()) { ui.inSB->setValue(inAmountByDate(ui.onCW->selectedDate())); } } QDate ExpiryDialog::Private::inDate() const { return date_by_amount_and_unit(ui.inSB->value(), ui.inCB->currentIndex()); } int ExpiryDialog::Private::inAmountByDate(const QDate &selected) const { const QDate current = QDate::currentDate(); switch (ui.inCB->currentIndex()) { case Days: return current.daysTo(selected); case Weeks: return qRound(current.daysTo(selected) / 7.0); case Months: return monthsBetween(current, selected); case Years: return yearsBetween(current, selected); }; Q_ASSERT(!"Should not reach here"); return -1; } ExpiryDialog::ExpiryDialog(Mode mode, QWidget *p) : QDialog{p} , d{new Private{mode, this}} { setWindowTitle(i18nc("@title:window", "Change Expiry")); } ExpiryDialog::~ExpiryDialog() = default; void ExpiryDialog::setDateOfExpiry(const QDate &date) { const QDate current = QDate::currentDate(); if (date.isValid()) { d->ui.onRB->setChecked(true); d->ui.onCW->setSelectedDate(qMax(date, current)); } else { d->ui.neverRB->setChecked(true); d->ui.onCW->setSelectedDate(current); d->ui.inSB->setValue(0); } } QDate ExpiryDialog::dateOfExpiry() const { return d->ui.inRB->isChecked() ? d->inDate() : d->ui.onRB->isChecked() ? d->ui.onCW->selectedDate() : QDate{}; } void ExpiryDialog::setUpdateExpirationOfAllSubkeys(bool update) { d->ui.updateSubkeysCheckBox->setChecked(update); } bool ExpiryDialog::updateExpirationOfAllSubkeys() const { return d->ui.updateSubkeysCheckBox->isChecked(); } #include "moc_expirydialog.cpp"