diff --git a/src/crypto/gui/signencryptemailconflictdialog.cpp b/src/crypto/gui/signencryptemailconflictdialog.cpp index a91a27e14..1c6132d3f 100644 --- a/src/crypto/gui/signencryptemailconflictdialog.cpp +++ b/src/crypto/gui/signencryptemailconflictdialog.cpp @@ -1,649 +1,642 @@ /* -*- mode: c++; c-basic-offset:4 -*- crypto/gui/signencryptemailconflictdialog.cpp This file is part of Kleopatra, the KDE keymanager SPDX-FileCopyrightText: 2009 Klarälvdalens Datakonsult AB SPDX-License-Identifier: GPL-2.0-or-later */ #include #include "signencryptemailconflictdialog.h" #include #include #include "dialogs/certificateselectiondialog.h" #include "certificateselectionline.h" #include #include "utils/gui-helper.h" #include "utils/kleo_assert.h" #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::Crypto; using namespace Kleo::Crypto::Gui; using namespace Kleo::Dialogs; using namespace GpgME; Q_DECLARE_METATYPE(GpgME::Key) Q_DECLARE_METATYPE(GpgME::UserID) static CertificateSelectionDialog * create_certificate_selection_dialog(QWidget *parent, Protocol proto) { auto const dlg = new CertificateSelectionDialog(parent); dlg->setOptions(proto == OpenPGP ? CertificateSelectionDialog::OpenPGPFormat : proto == CMS ? CertificateSelectionDialog::CMSFormat : CertificateSelectionDialog::AnyFormat); return dlg; } static CertificateSelectionDialog * create_encryption_certificate_selection_dialog(QWidget *parent, Protocol proto, const QString &mailbox) { CertificateSelectionDialog *const dlg = create_certificate_selection_dialog(parent, proto); dlg->setCustomLabelText(i18n("Please select an encryption certificate for recipient \"%1\"", mailbox)); dlg->setOptions(CertificateSelectionDialog::SingleSelection | CertificateSelectionDialog::EncryptOnly | dlg->options()); return dlg; } static CertificateSelectionDialog * create_signing_certificate_selection_dialog(QWidget *parent, Protocol proto, const QString &mailbox) { CertificateSelectionDialog *const dlg = create_certificate_selection_dialog(parent, proto); dlg->setCustomLabelText(i18n("Please select a signing certificate for sender \"%1\"", mailbox)); dlg->setOptions(CertificateSelectionDialog::SingleSelection | CertificateSelectionDialog::SignOnly | CertificateSelectionDialog::SecretKeys | dlg->options()); return dlg; } static QString make_top_label_conflict_text(bool sign, bool enc) { return sign && enc ? i18n("Kleopatra cannot unambiguously determine matching certificates " "for all recipients/senders of the message.\n" "Please select the correct certificates for each recipient:") : sign ? i18n("Kleopatra cannot unambiguously determine matching certificates " "for the sender of the message.\n" "Please select the correct certificates for the sender:") : enc ? i18n("Kleopatra cannot unambiguously determine matching certificates " "for all recipients of the message.\n" "Please select the correct certificates for each recipient:") : /* else */ (kleo_assert_fail(sign || enc), QString()); } static QString make_top_label_quickmode_text(bool sign, bool enc) { return enc ? i18n("Please verify that correct certificates have been selected for each recipient:") : sign ? i18n("Please verify that the correct certificate has been selected for the sender:") : /*else*/ (kleo_assert_fail(sign || enc), QString()); } class SignEncryptEMailConflictDialog::Private { friend class ::Kleo::Crypto::Gui::SignEncryptEMailConflictDialog; SignEncryptEMailConflictDialog *const q; public: explicit Private(SignEncryptEMailConflictDialog *qq) : q(qq), senders(), recipients(), sign(true), encrypt(true), presetProtocol(UnknownProtocol), ui(q) { } private: void updateTopLabelText() { ui.conflictTopLB.setText(make_top_label_conflict_text(sign, encrypt)); ui.quickModeTopLB.setText(make_top_label_quickmode_text(sign, encrypt)); } void showHideWidgets() { const Protocol proto = q->selectedProtocol(); const bool quickMode = q->isQuickMode(); const bool needProtocolSelection = presetProtocol == UnknownProtocol; const bool needShowAllRecipientsCB = quickMode ? false : needProtocolSelection ? needShowAllRecipients(OpenPGP) || needShowAllRecipients(CMS) : /* else */ needShowAllRecipients(proto) ; ui.showAllRecipientsCB.setVisible(needShowAllRecipientsCB); ui.pgpRB.setVisible(needProtocolSelection); ui.cmsRB.setVisible(needProtocolSelection); const bool showAll = !needShowAllRecipientsCB || ui.showAllRecipientsCB.isChecked(); bool first; first = true; for (const CertificateSelectionLine &line : std::as_const(ui.signers)) { line.showHide(proto, first, showAll, sign); } ui.selectSigningCertificatesGB.setVisible(sign && (showAll || !first)); first = true; for (const CertificateSelectionLine &line : std::as_const(ui.recipients)) { line.showHide(proto, first, showAll, encrypt); } ui.selectEncryptionCertificatesGB.setVisible(encrypt && (showAll || !first)); } bool needShowAllRecipients(Protocol proto) const { if (sign) { if (const unsigned int num = std::count_if(ui.signers.cbegin(), ui.signers.cend(), [proto](const CertificateSelectionLine &l) { return l.wasInitiallyAmbiguous(proto); })) { if (num != ui.signers.size()) { return true; } } } if (encrypt) { if (const unsigned int num = std::count_if(ui.recipients.cbegin(), ui.recipients.cend(), [proto](const CertificateSelectionLine &l) { return l.wasInitiallyAmbiguous(proto); })) { if (num != ui.recipients.size()) { return true; } } } return false; } void createSendersAndRecipients() { ui.clearSendersAndRecipients(); ui.addSelectSigningCertificatesGB(); for (const Sender &s : std::as_const(senders)) { addSigner(s); } ui.addSelectEncryptionCertificatesGB(); for (const Sender &s : std::as_const(senders)) { addRecipient(s); } for (const Recipient &r : std::as_const(recipients)) { addRecipient(r); } } void addSigner(const Sender &s) { ui.addSigner(s.mailbox().prettyAddress(), s.signingCertificateCandidates(OpenPGP), s.isSigningAmbiguous(OpenPGP), s.signingCertificateCandidates(CMS), s.isSigningAmbiguous(CMS), q); } void addRecipient(const Sender &s) { ui.addRecipient(s.mailbox().prettyAddress(), s.encryptToSelfCertificateCandidates(OpenPGP), s.isEncryptionAmbiguous(OpenPGP), s.encryptToSelfCertificateCandidates(CMS), s.isEncryptionAmbiguous(CMS), q); } void addRecipient(const Recipient &r) { ui.addRecipient(r.mailbox().prettyAddress(), r.encryptionCertificateCandidates(OpenPGP), r.isEncryptionAmbiguous(OpenPGP), r.encryptionCertificateCandidates(CMS), r.isEncryptionAmbiguous(CMS), q); } bool isComplete(Protocol proto) const; private: void updateComplianceStatus() { if (!DeVSCompliance::isCompliant()) { return; } if (q->selectedProtocol() == UnknownProtocol || (q->resolvedSigningKeys().empty() && q->resolvedEncryptionKeys().empty())) { return; } // Handle compliance bool de_vs = true; for (const auto &key: q->resolvedSigningKeys()) { if (!key.isDeVs() || keyValidity(key) < GpgME::UserID::Validity::Full) { de_vs = false; break; } } if (de_vs) { for (const auto &key: q->resolvedEncryptionKeys()) { if (!key.isDeVs() || keyValidity(key) < GpgME::UserID::Validity::Full) { de_vs = false; break; } } } auto btn = ui.buttonBox.button(QDialogButtonBox::Ok); - btn->setIcon(QIcon::fromTheme(de_vs - ? QStringLiteral("security-high") - : QStringLiteral("security-medium"))); - if (!SystemInfo::isHighContrastModeActive()) { - btn->setStyleSheet(QStringLiteral("QPushButton { background-color: %1; }").arg(de_vs - ? KColorScheme(QPalette::Active, KColorScheme::View).background(KColorScheme::PositiveBackground).color().name() - : KColorScheme(QPalette::Active, KColorScheme::View).background(KColorScheme::NegativeBackground).color().name())); - } + DeVSCompliance::decorate(btn, de_vs); ui.complianceLB.setText(de_vs ? i18nc("%1 is a placeholder for the name of a compliance mode. E.g. NATO RESTRICTED compliant or VS-NfD compliant", "%1 communication possible.", DeVSCompliance::name(true)) : i18nc("%1 is a placeholder for the name of a compliance mode. E.g. NATO RESTRICTED compliant or VS-NfD compliant", "%1 communication not possible.", DeVSCompliance::name(true))); ui.complianceLB.setVisible(true); } void updateDialogStatus() { ui.setOkButtonEnabled(q->isComplete()); updateComplianceStatus(); } void slotCompleteChanged() { updateDialogStatus(); } void slotShowAllRecipientsToggled(bool) { showHideWidgets(); } void slotProtocolChanged() { showHideWidgets(); updateDialogStatus(); } void slotCertificateSelectionDialogRequested() { const QObject *const s = q->sender(); const Protocol proto = q->selectedProtocol(); QPointer dlg; for (const CertificateSelectionLine &l : std::as_const(ui.signers)) if (s == l.toolButton()) { dlg = create_signing_certificate_selection_dialog(q, proto, l.mailboxText()); if (dlg->exec()) { l.addAndSelectCertificate(dlg->selectedCertificate()); } // ### switch to key.protocol(), in case proto == UnknownProtocol break; } for (const CertificateSelectionLine &l : std::as_const(ui.recipients)) if (s == l.toolButton()) { dlg = create_encryption_certificate_selection_dialog(q, proto, l.mailboxText()); if (dlg->exec()) { l.addAndSelectCertificate(dlg->selectedCertificate()); } // ### switch to key.protocol(), in case proto == UnknownProtocol break; } #ifndef Q_OS_WIN // This leads to a crash on Windows. We don't really // leak memory here anyway because the destruction of the // dialog happens when the parent (q) is destroyed anyway. delete dlg; #endif } private: std::vector senders; std::vector recipients; bool sign : 1; bool encrypt : 1; Protocol presetProtocol; private: struct Ui { QLabel conflictTopLB, quickModeTopLB; QCheckBox showAllRecipientsCB; QRadioButton pgpRB, cmsRB; QGroupBox selectSigningCertificatesGB; QGroupBox selectEncryptionCertificatesGB; QCheckBox quickModeCB; QDialogButtonBox buttonBox; QVBoxLayout vlay; QHBoxLayout hlay; QHBoxLayout hlay2; QGridLayout glay; std::vector signers, recipients; QLabel complianceLB; void setOkButtonEnabled(bool enable) { return buttonBox.button(QDialogButtonBox::Ok)->setEnabled(enable); } explicit Ui(SignEncryptEMailConflictDialog *q) : conflictTopLB(make_top_label_conflict_text(true, true), q), quickModeTopLB(make_top_label_quickmode_text(true, true), q), showAllRecipientsCB(i18n("Show all recipients"), q), pgpRB(i18n("OpenPGP"), q), cmsRB(i18n("S/MIME"), q), selectSigningCertificatesGB(i18n("Select Signing Certificate"), q), selectEncryptionCertificatesGB(i18n("Select Encryption Certificate"), q), quickModeCB(i18n("Only show this dialog in case of conflicts (experimental)"), q), buttonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, q), vlay(q), hlay(), glay(), signers(), recipients() { KDAB_SET_OBJECT_NAME(conflictTopLB); KDAB_SET_OBJECT_NAME(quickModeTopLB); KDAB_SET_OBJECT_NAME(showAllRecipientsCB); KDAB_SET_OBJECT_NAME(pgpRB); KDAB_SET_OBJECT_NAME(cmsRB); KDAB_SET_OBJECT_NAME(selectSigningCertificatesGB); KDAB_SET_OBJECT_NAME(selectEncryptionCertificatesGB); KDAB_SET_OBJECT_NAME(quickModeCB); KDAB_SET_OBJECT_NAME(buttonBox); KDAB_SET_OBJECT_NAME(hlay); KDAB_SET_OBJECT_NAME(glay); KDAB_SET_OBJECT_NAME(vlay); q->setWindowTitle(i18nc("@title:window", "Select Certificates for Message")); conflictTopLB.hide(); selectSigningCertificatesGB.setFlat(true); selectEncryptionCertificatesGB.setFlat(true); selectSigningCertificatesGB.setAlignment(Qt::AlignCenter); selectEncryptionCertificatesGB.setAlignment(Qt::AlignCenter); glay.setColumnStretch(2, 1); glay.setColumnStretch(3, 1); vlay.setSizeConstraint(QLayout::SetMinimumSize); vlay.addWidget(&conflictTopLB); vlay.addWidget(&quickModeTopLB); hlay.addWidget(&showAllRecipientsCB); hlay.addStretch(1); hlay.addWidget(&pgpRB); hlay.addWidget(&cmsRB); vlay.addLayout(&hlay); addSelectSigningCertificatesGB(); addSelectEncryptionCertificatesGB(); vlay.addLayout(&glay); vlay.addStretch(1); complianceLB.setVisible(false); hlay2.addStretch(1); hlay2.addWidget(&complianceLB, 0, Qt::AlignRight); hlay2.addWidget(&buttonBox, 0, Qt::AlignRight); vlay.addWidget(&quickModeCB, 0, Qt::AlignRight); vlay.addLayout(&hlay2); connect(&buttonBox, &QDialogButtonBox::accepted, q, &SignEncryptEMailConflictDialog::accept); connect(&buttonBox, &QDialogButtonBox::rejected, q, &SignEncryptEMailConflictDialog::reject); connect(&showAllRecipientsCB, SIGNAL(toggled(bool)), q, SLOT(slotShowAllRecipientsToggled(bool))); connect(&pgpRB, SIGNAL(toggled(bool)), q, SLOT(slotProtocolChanged())); connect(&cmsRB, SIGNAL(toggled(bool)), q, SLOT(slotProtocolChanged())); } void clearSendersAndRecipients() { std::vector sig, enc; sig.swap(signers); enc.swap(recipients); std::for_each(sig.begin(), sig.end(), std::mem_fn(&CertificateSelectionLine::kill)); std::for_each(enc.begin(), enc.end(), std::mem_fn(&CertificateSelectionLine::kill)); glay.removeWidget(&selectSigningCertificatesGB); glay.removeWidget(&selectEncryptionCertificatesGB); } void addSelectSigningCertificatesGB() { glay.addWidget(&selectSigningCertificatesGB, glay.rowCount(), 0, 1, CertificateSelectionLine::NumColumns); } void addSelectEncryptionCertificatesGB() { glay.addWidget(&selectEncryptionCertificatesGB, glay.rowCount(), 0, 1, CertificateSelectionLine::NumColumns); } void addSigner(const QString &mailbox, const std::vector &pgp, bool pgpAmbiguous, const std::vector &cms, bool cmsAmbiguous, QWidget *q) { CertificateSelectionLine line(i18n("From:"), mailbox, pgp, pgpAmbiguous, cms, cmsAmbiguous, q, glay); signers.push_back(line); } void addRecipient(const QString &mailbox, const std::vector &pgp, bool pgpAmbiguous, const std::vector &cms, bool cmsAmbiguous, QWidget *q) { CertificateSelectionLine line(i18n("To:"), mailbox, pgp, pgpAmbiguous, cms, cmsAmbiguous, q, glay); recipients.push_back(line); } } ui; }; SignEncryptEMailConflictDialog::SignEncryptEMailConflictDialog(QWidget *parent) : QDialog(parent), d(new Private(this)) { } SignEncryptEMailConflictDialog::~SignEncryptEMailConflictDialog() {} void SignEncryptEMailConflictDialog::setPresetProtocol(Protocol p) { if (p == d->presetProtocol) { return; } const QSignalBlocker pgpBlocker(d->ui.pgpRB); const QSignalBlocker cmsBlocker(d->ui.cmsRB); really_check(d->ui.pgpRB, p == OpenPGP); really_check(d->ui.cmsRB, p == CMS); d->presetProtocol = p; d->showHideWidgets(); d->updateDialogStatus(); } Protocol SignEncryptEMailConflictDialog::selectedProtocol() const { if (d->presetProtocol != UnknownProtocol) { return d->presetProtocol; } if (d->ui.pgpRB.isChecked()) { return OpenPGP; } if (d->ui.cmsRB.isChecked()) { return CMS; } return UnknownProtocol; } void SignEncryptEMailConflictDialog::setSubject(const QString &subject) { setWindowTitle(i18nc("@title:window", "Select Certificates for Message \"%1\"", subject)); } void SignEncryptEMailConflictDialog::setSign(bool sign) { if (sign == d->sign) { return; } d->sign = sign; d->updateTopLabelText(); d->showHideWidgets(); d->updateDialogStatus(); } void SignEncryptEMailConflictDialog::setEncrypt(bool encrypt) { if (encrypt == d->encrypt) { return; } d->encrypt = encrypt; d->updateTopLabelText(); d->showHideWidgets(); d->updateDialogStatus(); } void SignEncryptEMailConflictDialog::setSenders(const std::vector &senders) { if (senders == d->senders) { return; } d->senders = senders; d->createSendersAndRecipients(); d->showHideWidgets(); d->updateDialogStatus(); } void SignEncryptEMailConflictDialog::setRecipients(const std::vector &recipients) { if (d->recipients == recipients) { return; } d->recipients = recipients; d->createSendersAndRecipients(); d->showHideWidgets(); d->updateDialogStatus(); } void SignEncryptEMailConflictDialog::pickProtocol() { if (selectedProtocol() != UnknownProtocol) { return; // already picked } const bool pgp = d->isComplete(OpenPGP); const bool cms = d->isComplete(CMS); if (pgp && !cms) { d->ui.pgpRB.setChecked(true); } else if (cms && !pgp) { d->ui.cmsRB.setChecked(true); } } bool SignEncryptEMailConflictDialog::isComplete() const { const Protocol proto = selectedProtocol(); return proto != UnknownProtocol && d->isComplete(proto); } bool SignEncryptEMailConflictDialog::Private::isComplete(Protocol proto) const { return (!sign || std::none_of(ui.signers.cbegin(), ui.signers.cend(), [proto](const CertificateSelectionLine &l) { return l.isStillAmbiguous(proto); })) && (!encrypt || std::none_of(ui.recipients.cbegin(), ui.recipients.cend(), [proto](const CertificateSelectionLine &l) { return l.isStillAmbiguous(proto); })); } static std::vector get_keys(const std::vector &lines, Protocol proto) { if (proto == UnknownProtocol) { return std::vector(); } Q_ASSERT(proto == OpenPGP || proto == CMS); std::vector keys; keys.reserve(lines.size()); std::transform(lines.cbegin(), lines.cend(), std::back_inserter(keys), [proto](const CertificateSelectionLine &l) { return l.key(proto); }); return keys; } std::vector SignEncryptEMailConflictDialog::resolvedSigningKeys() const { return d->sign ? get_keys(d->ui.signers, selectedProtocol()) : std::vector(); } std::vector SignEncryptEMailConflictDialog::resolvedEncryptionKeys() const { return d->encrypt ? get_keys(d->ui.recipients, selectedProtocol()) : std::vector(); } void SignEncryptEMailConflictDialog::setQuickMode(bool on) { d->ui.quickModeCB.setChecked(on); } bool SignEncryptEMailConflictDialog::isQuickMode() const { return d->ui.quickModeCB.isChecked(); } void SignEncryptEMailConflictDialog::setConflict(bool conflict) { d->ui.conflictTopLB.setVisible(conflict); d->ui.quickModeTopLB.setVisible(!conflict); } #include "moc_signencryptemailconflictdialog.cpp" diff --git a/src/crypto/gui/signencryptfileswizard.cpp b/src/crypto/gui/signencryptfileswizard.cpp index a503604f6..600b72908 100644 --- a/src/crypto/gui/signencryptfileswizard.cpp +++ b/src/crypto/gui/signencryptfileswizard.cpp @@ -1,693 +1,687 @@ /* crypto/gui/signencryptfileswizard.cpp This file is part of Kleopatra, the KDE keymanager SPDX-FileCopyrightText: 2009 Klarälvdalens Datakonsult AB SPDX-FileCopyrightText: 2016 Bundesamt für Sicherheit in der Informationstechnik SPDX-FileContributor: Intevation GmbH SPDX-License-Identifier: GPL-2.0-or-later */ #include #include "signencryptfileswizard.h" #include "signencryptwidget.h" #include "newresultpage.h" #include #include #include #include #include #include #include #include #include #include "kleopatra_debug.h" #include #include #include #include #include #include #include #include #include #include #include #include +#include #include #include #include using namespace GpgME; using namespace Kleo; using namespace Kleo::Crypto::Gui; enum Page { SigEncPageId, ResultPageId, NumPages }; class FileNameRequesterWithIcon : public QWidget { Q_OBJECT public: explicit FileNameRequesterWithIcon(QDir::Filters filter, QWidget *parent = nullptr) : QWidget(parent) { auto layout = new QHBoxLayout{this}; layout->setContentsMargins(0, 0, 0, 0); mIconLabel = new QLabel{this}; mRequester = new FileNameRequester{filter, this}; mRequester->setExistingOnly(false); layout->addWidget(mIconLabel); layout->addWidget(mRequester); setFocusPolicy(mRequester->focusPolicy()); setFocusProxy(mRequester); connect(mRequester, &FileNameRequester::fileNameChanged, this, &FileNameRequesterWithIcon::fileNameChanged); } void setIcon(const QIcon &icon) { mIconLabel->setPixmap(icon.pixmap(32, 32)); } void setFileName(const QString &name) { mRequester->setFileName(name); } QString fileName() const { return mRequester->fileName(); } void setNameFilter(const QString &nameFilter) { mRequester->setNameFilter(nameFilter); } QString nameFilter() const { return mRequester->nameFilter(); } FileNameRequester *requester() { return mRequester; } Q_SIGNALS: void fileNameChanged(const QString &filename); protected: bool event(QEvent *e) override { if (e->type() == QEvent::ToolTipChange) { mRequester->setToolTip(toolTip()); } return QWidget::event(e); } private: QLabel *mIconLabel; FileNameRequester *mRequester; }; class SigEncPage: public QWizardPage { Q_OBJECT public: explicit SigEncPage(QWidget *parent = nullptr) : QWizardPage(parent), mParent((SignEncryptFilesWizard *) parent), mWidget(new SignEncryptWidget), mOutLayout(new QVBoxLayout), mOutputLabel{nullptr}, mArchive(false), mUseOutputDir(false), mSingleFile{true} { setTitle(i18nc("@title", "Sign / Encrypt Files")); auto vLay = new QVBoxLayout(this); vLay->setContentsMargins(0, 0, 0, 0); if (!Settings{}.cmsEnabled()) { mWidget->setProtocol(GpgME::OpenPGP); } mWidget->setSignAsText(i18nc("@option:check on SignEncryptPage", "&Sign as:")); mWidget->setEncryptForMeText(i18nc("@option:check on SignEncryptPage", "Encrypt for &me:")); mWidget->setEncryptForOthersText(i18nc("@option:check on SignEncryptPage", "Encrypt for &others:")); mWidget->setEncryptWithPasswordText(i18nc("@option:check on SignEncryptPage", "Encrypt with &password. Anyone you share the password with can read the data.")); vLay->addWidget(mWidget); connect(mWidget, &SignEncryptWidget::operationChanged, this, &SigEncPage::updateCommitButton); connect(mWidget, &SignEncryptWidget::keysChanged, this, &SigEncPage::updateFileWidgets); auto outputGrp = new QGroupBox(i18nc("@title:group", "Output")); outputGrp->setLayout(mOutLayout); mPlaceholderWidget = new QLabel(i18n("Please select an action.")); mOutLayout->addWidget(mPlaceholderWidget); mOutputLabel = new QLabel(i18nc("@label on SignEncryptPage", "Output &files/folder:")); mOutLayout->addWidget(mOutputLabel); createRequesters(mOutLayout); mUseOutputDirChk = new QCheckBox(i18nc("@option:check on SignEncryptPage", "Encrypt / Sign &each file separately.")); mUseOutputDirChk->setToolTip(i18nc("@info:tooltip", "Keep each file separate instead of creating an archive for all.")); mOutLayout->addWidget(mUseOutputDirChk); connect (mUseOutputDirChk, &QCheckBox::toggled, this, [this] (bool state) { mUseOutputDir = state; mArchive = !mUseOutputDir && !mSingleFile; updateFileWidgets(); }); vLay->addWidget(outputGrp); auto messageWidget = new KMessageWidget; messageWidget->setMessageType(KMessageWidget::Error); messageWidget->setIcon(style()->standardIcon(QStyle::SP_MessageBoxCritical, nullptr, this)); messageWidget->setText(i18n("Signing and encrypting files is not possible.")); messageWidget->setToolTip(xi18nc("@info %1 is a placeholder for the name of a compliance mode. E.g. NATO RESTRICTED compliant or VS-NfD compliant", "You cannot use Kleopatra for signing or encrypting files " "because the GnuPG system used by Kleopatra is not %1.", DeVSCompliance::name(true))); messageWidget->setCloseButtonVisible(false); messageWidget->setVisible(DeVSCompliance::isActive() && !DeVSCompliance::isCompliant()); vLay->addWidget(messageWidget); setMinimumHeight(300); } void setEncryptionPreset(bool value) { mWidget->setEncryptionChecked(value); } void setSigningPreset(bool value) { mWidget->setSigningChecked(value); } bool isComplete() const override { if (DeVSCompliance::isActive() && !DeVSCompliance::isCompliant()) { return false; } return mWidget->isComplete(); } int nextId() const override { return ResultPageId; } void initializePage() override { setCommitPage(true); updateCommitButton(mWidget->currentOp()); } void setArchiveForced(bool archive) { mArchive = archive; setArchiveMutable(!archive); } void setArchiveMutable(bool archive) { mUseOutputDirChk->setVisible(archive); if (archive) { const KConfigGroup archCfg(KSharedConfig::openConfig(), "SignEncryptFilesWizard"); mUseOutputDirChk->setChecked(archCfg.readEntry("LastUseOutputDir", false)); } else { mUseOutputDirChk->setChecked(false); } } void setSingleFile(bool singleFile) { mSingleFile = singleFile; mArchive = !mUseOutputDir && !mSingleFile; } bool validatePage() override { if (DeVSCompliance::isActive() && !DeVSCompliance::isCompliant()) { KMessageBox::sorry(topLevelWidget(), xi18nc("@info %1 is a placeholder for the name of a compliance mode. E.g. NATO RESTRICTED compliant or VS-NfD compliant", "Sorry! You cannot use Kleopatra for signing or encrypting files " "because the GnuPG system used by Kleopatra is not %1.", DeVSCompliance::name(true))); return false; } bool sign = !mWidget->signKey().isNull(); bool encrypt = !mWidget->selfKey().isNull() || !mWidget->recipients().empty(); if (!mWidget->validate()) { return false; } mWidget->saveOwnKeys(); if (mUseOutputDirChk->isVisible()) { KConfigGroup archCfg(KSharedConfig::openConfig(), "SignEncryptFilesWizard"); archCfg.writeEntry("LastUseOutputDir", mUseOutputDir); } if (sign && !encrypt && mArchive) { return KMessageBox::warningContinueCancel(this, xi18nc("@info", "Archiving in combination with sign-only currently requires what are known as opaque signatures - " "unlike detached ones, these embed the content in the signature." "This format is rather unusual. You might want to archive the files separately, " "and then sign the archive as one file with Kleopatra." "Future versions of Kleopatra are expected to also support detached signatures in this case."), i18nc("@title:window", "Unusual Signature Warning"), KStandardGuiItem::cont(), KStandardGuiItem::cancel(), QStringLiteral("signencryptfileswizard-archive+sign-only-warning")) == KMessageBox::Continue; } else if (sign && !encrypt) { return true; } if (!mWidget->selfKey().isNull() || mWidget->encryptSymmetric()) { return true; } const auto recipientKeys = recipients(); const bool hasSecret = std::any_of(std::begin(recipientKeys), std::end(recipientKeys), [](const auto &k) { return k.hasSecret(); }); if (!hasSecret) { if (KMessageBox::warningContinueCancel(this, xi18nc("@info", "None of the recipients you are encrypting to seems to be your own." "This means that you will not be able to decrypt the data anymore, once encrypted." "Do you want to continue, or cancel to change the recipient selection?"), i18nc("@title:window", "Encrypt-To-Self Warning"), KStandardGuiItem::cont(), KStandardGuiItem::cancel(), QStringLiteral("warn-encrypt-to-non-self"), KMessageBox::Notify | KMessageBox::Dangerous) == KMessageBox::Cancel) { return false; } } return true; } std::vector recipients() const { return mWidget->recipients(); } /* In the future we might find a usecase for multiple * signers */ std::vector signers() const { const Key k = mWidget->signKey(); if (!k.isNull()) { return {k}; } return {}; } private: struct RequesterInfo { SignEncryptFilesWizard::KindNames id; QString icon; QString toolTip; QString accessibleName; QString nameFilterBinary; QString nameFilterAscii; }; void createRequesters(QBoxLayout *lay) { static const std::array requestersInfo = {{ { SignEncryptFilesWizard::SignatureCMS, QStringLiteral("document-sign"), i18nc("@info:tooltip", "This is the filename of the S/MIME signature."), i18nc("Lineedit accessible name", "S/MIME signature file"), i18nc("Name filter binary", "S/MIME Signatures (*.p7s)"), i18nc("Name filter ASCII", "S/MIME Signatures (*.p7s *.pem)"), }, { SignEncryptFilesWizard::SignaturePGP, QStringLiteral("document-sign"), i18nc("@info:tooltip", "This is the filename of the detached OpenPGP signature."), i18nc("Lineedit accessible name", "OpenPGP signature file"), i18nc("Name filter binary", "OpenPGP Signatures (*.sig *.pgp)"), i18nc("Name filter ASCII", "OpenPGP Signatures (*.asc *.sig)"), }, { SignEncryptFilesWizard::CombinedPGP, QStringLiteral("document-edit-sign-encrypt"), i18nc("@info:tooltip", "This is the filename of the OpenPGP-signed and encrypted file."), i18nc("Lineedit accessible name", "OpenPGP signed and encrypted file"), i18nc("Name filter binary", "OpenPGP Files (*.gpg *.pgp)"), i18nc("Name filter ASCII", "OpenPGP Files (*.asc)"), }, { SignEncryptFilesWizard::EncryptedPGP, QStringLiteral("document-encrypt"), i18nc("@info:tooltip", "This is the filename of the OpenPGP encrypted file."), i18nc("Lineedit accessible name", "OpenPGP encrypted file"), i18nc("Name filter binary", "OpenPGP Files (*.gpg *.pgp)"), i18nc("Name filter ASCII", "OpenPGP Files (*.asc)"), }, { SignEncryptFilesWizard::EncryptedCMS, QStringLiteral("document-encrypt"), i18nc("@info:tooltip", "This is the filename of the S/MIME encrypted file."), i18nc("Lineedit accessible name", "S/MIME encrypted file"), i18nc("Name filter binary", "S/MIME Files (*.p7m)"), i18nc("Name filter ASCII", "S/MIME Files (*.p7m *.pem)"), }, { SignEncryptFilesWizard::Directory, QStringLiteral("folder"), i18nc("@info:tooltip", "The resulting files are written to this directory."), i18nc("Lineedit accessible name", "Output directory"), {}, {}, }, }}; if (!mRequesters.empty()) { return; } const bool isAscii = FileOperationsPreferences().addASCIIArmor(); for (const auto &requester : requestersInfo) { const auto id = requester.id; auto requesterWithIcon = new FileNameRequesterWithIcon{id == SignEncryptFilesWizard::Directory ? QDir::Dirs : QDir::Files, this}; requesterWithIcon->setIcon(QIcon::fromTheme(requester.icon)); requesterWithIcon->setToolTip(requester.toolTip); requesterWithIcon->requester()->setAccessibleNameOfLineEdit(requester.accessibleName); requesterWithIcon->setNameFilter(isAscii ? requester.nameFilterAscii : requester.nameFilterBinary); lay->addWidget(requesterWithIcon); connect(requesterWithIcon, &FileNameRequesterWithIcon::fileNameChanged, this, [this, id](const QString &newName) { mOutNames[id] = newName; }); mRequesters.insert(id, requesterWithIcon); } } public: void setOutputNames(const QMap &names) { Q_ASSERT(mOutNames.isEmpty()); for (auto it = std::begin(names); it != std::end(names); ++it) { mRequesters.value(it.key())->setFileName(it.value()); } mOutNames = names; updateFileWidgets(); } QMap outputNames() const { if (!mUseOutputDir) { auto ret = mOutNames; ret.remove(SignEncryptFilesWizard::Directory); return ret; } return mOutNames; } bool encryptSymmetric() const { return mWidget->encryptSymmetric(); } private Q_SLOTS: void updateCommitButton(const QString &label) { if (mParent->currentPage() != this) { return; } - auto btn = mParent->button(QWizard::CommitButton); + auto btn = qobject_cast(mParent->button(QWizard::CommitButton)); if (!label.isEmpty()) { mParent->setButtonText(QWizard::CommitButton, label); if (DeVSCompliance::isActive()) { const bool de_vs = DeVSCompliance::isCompliant() && mWidget->isDeVsAndValid(); - btn->setIcon(QIcon::fromTheme(de_vs - ? QStringLiteral("security-high") - : QStringLiteral("security-medium"))); - if (!SystemInfo::isHighContrastModeActive()) { - btn->setStyleSheet(QStringLiteral("QPushButton { background-color: %1; }").arg(de_vs - ? KColorScheme(QPalette::Active, KColorScheme::View).background(KColorScheme::PositiveBackground).color().name() - : KColorScheme(QPalette::Active, KColorScheme::View).background(KColorScheme::NegativeBackground).color().name())); - } + DeVSCompliance::decorate(btn, de_vs); mParent->setLabelText(de_vs ? i18nc("%1 is a placeholder for the name of a compliance mode. E.g. NATO RESTRICTED compliant or VS-NfD compliant", "%1 communication possible.", DeVSCompliance::name(true)) : i18nc("%1 is a placeholder for the name of a compliance mode. E.g. NATO RESTRICTED compliant or VS-NfD compliant", "%1 communication not possible.", DeVSCompliance::name(true))); } } else { mParent->setButtonText(QWizard::CommitButton, i18n("Next")); btn->setIcon(QIcon()); btn->setStyleSheet(QString()); } Q_EMIT completeChanged(); } void updateFileWidgets() { if (mRequesters.isEmpty()) { return; } const std::vector recipients = mWidget->recipients(); const Key sigKey = mWidget->signKey(); const bool pgp = mWidget->encryptSymmetric() || std::any_of(std::cbegin(recipients), std::cend(recipients), [](const auto &k) { return k.protocol() == Protocol::OpenPGP; }); const bool cms = std::any_of(std::cbegin(recipients), std::cend(recipients), [](const auto &k) { return k.protocol() == Protocol::CMS; }); mOutLayout->setEnabled(false); if (cms || pgp || !sigKey.isNull()) { mPlaceholderWidget->setVisible(false); mOutputLabel->setVisible(true); mRequesters[SignEncryptFilesWizard::SignatureCMS]->setVisible(!mUseOutputDir && sigKey.protocol() == Protocol::CMS); mRequesters[SignEncryptFilesWizard::EncryptedCMS]->setVisible(!mUseOutputDir && cms); mRequesters[SignEncryptFilesWizard::CombinedPGP]->setVisible(!mUseOutputDir && sigKey.protocol() == Protocol::OpenPGP && pgp); mRequesters[SignEncryptFilesWizard::EncryptedPGP]->setVisible(!mUseOutputDir && sigKey.protocol() != Protocol::OpenPGP && pgp); mRequesters[SignEncryptFilesWizard::SignaturePGP]->setVisible(!mUseOutputDir && sigKey.protocol() == Protocol::OpenPGP && !pgp); mRequesters[SignEncryptFilesWizard::Directory]->setVisible(mUseOutputDir); auto firstNotHidden = std::find_if(std::cbegin(mRequesters), std::cend(mRequesters), [](auto w) { return !w->isHidden(); }); mOutputLabel->setBuddy(*firstNotHidden); } else { mPlaceholderWidget->setVisible(true); mOutputLabel->setVisible(false); std::for_each(std::cbegin(mRequesters), std::cend(mRequesters), [](auto w) { w->setVisible(false); }); mOutputLabel->setBuddy(nullptr); } mOutLayout->setEnabled(true); } private: SignEncryptFilesWizard *mParent; SignEncryptWidget *mWidget; QMap mOutNames; QMap mRequesters; QVBoxLayout *mOutLayout; QWidget *mPlaceholderWidget; QCheckBox *mUseOutputDirChk; QLabel *mOutputLabel; bool mArchive; bool mUseOutputDir; bool mSingleFile; }; class ResultPage : public NewResultPage { Q_OBJECT public: explicit ResultPage(QWidget *parent = nullptr) : NewResultPage(parent), mParent((SignEncryptFilesWizard *) parent) { setTitle(i18nc("@title", "Results")); setSubTitle(i18nc("@title", "Status and progress of the crypto operations is shown here.")); } void initializePage() override { mParent->setLabelText(QString()); } private: SignEncryptFilesWizard *mParent; }; SignEncryptFilesWizard::SignEncryptFilesWizard(QWidget *parent, Qt::WindowFlags f) : QWizard(parent, f) { readConfig(); const bool de_vs = DeVSCompliance::isActive(); #ifdef Q_OS_WIN // Enforce modern style to avoid vista style ugliness. setWizardStyle(QWizard::ModernStyle); #endif mSigEncPage = new SigEncPage(this); mResultPage = new ResultPage(this); connect(this, &QWizard::currentIdChanged, this, &SignEncryptFilesWizard::slotCurrentIdChanged); setPage(SigEncPageId, mSigEncPage); setPage(ResultPageId, mResultPage); setOptions(QWizard::IndependentPages | (de_vs ? QWizard::HaveCustomButton1 : QWizard::WizardOption(0)) | QWizard::NoBackButtonOnLastPage | QWizard::NoBackButtonOnStartPage); if (de_vs) { /* We use a custom button to display a label next to the buttons. */ auto btn = button(QWizard::CustomButton1); /* We style the button so that it looks and acts like a label. */ btn->setStyleSheet(QStringLiteral("border: none")); btn->setFocusPolicy(Qt::NoFocus); } } void SignEncryptFilesWizard::setLabelText(const QString &label) { button(QWizard::CommitButton)->setToolTip(label); setButtonText(QWizard::CustomButton1, label); } void SignEncryptFilesWizard::slotCurrentIdChanged(int id) { if (id == ResultPageId) { Q_EMIT operationPrepared(); } } SignEncryptFilesWizard::~SignEncryptFilesWizard() { qCDebug(KLEOPATRA_LOG); writeConfig(); } void SignEncryptFilesWizard::setSigningPreset(bool preset) { mSigEncPage->setSigningPreset(preset); } void SignEncryptFilesWizard::setSigningUserMutable(bool mut) { if (mut == mSigningUserMutable) { return; } mSigningUserMutable = mut; } void SignEncryptFilesWizard::setEncryptionPreset(bool preset) { mSigEncPage->setEncryptionPreset(preset); } void SignEncryptFilesWizard::setEncryptionUserMutable(bool mut) { if (mut == mEncryptionUserMutable) { return; } mEncryptionUserMutable = mut; } void SignEncryptFilesWizard::setArchiveForced(bool archive) { mSigEncPage->setArchiveForced(archive); } void SignEncryptFilesWizard::setArchiveMutable(bool archive) { mSigEncPage->setArchiveMutable(archive); } void SignEncryptFilesWizard::setSingleFile(bool singleFile) { mSigEncPage->setSingleFile(singleFile); } std::vector SignEncryptFilesWizard::resolvedRecipients() const { return mSigEncPage->recipients(); } std::vector SignEncryptFilesWizard::resolvedSigners() const { return mSigEncPage->signers(); } void SignEncryptFilesWizard::setTaskCollection(const std::shared_ptr &coll) { mResultPage->setTaskCollection(coll); } void SignEncryptFilesWizard::setOutputNames(const QMap &map) const { mSigEncPage->setOutputNames(map); } QMap SignEncryptFilesWizard::outputNames() const { return mSigEncPage->outputNames(); } bool SignEncryptFilesWizard::encryptSymmetric() const { return mSigEncPage->encryptSymmetric(); } void SignEncryptFilesWizard::readConfig() { winId(); // ensure there's a window created // set default window size windowHandle()->resize(640, 480); // restore size from config file KConfigGroup cfgGroup(KSharedConfig::openConfig(), "SignEncryptFilesWizard"); KWindowConfig::restoreWindowSize(windowHandle(), cfgGroup); // NOTICE: QWindow::setGeometry() does NOT impact the backing QWidget geometry even if the platform // window was created -> QTBUG-40584. We therefore copy the size here. // TODO: remove once this was resolved in QWidget QPA resize(windowHandle()->size()); } void SignEncryptFilesWizard::writeConfig() { KConfigGroup cfgGroup(KSharedConfig::openConfig(), "SignEncryptFilesWizard"); KWindowConfig::saveWindowSize(windowHandle(), cfgGroup); cfgGroup.sync(); } #include "signencryptfileswizard.moc" diff --git a/src/view/padwidget.cpp b/src/view/padwidget.cpp index 0cebade54..8caddc0b0 100644 --- a/src/view/padwidget.cpp +++ b/src/view/padwidget.cpp @@ -1,547 +1,540 @@ /* -*- mode: c++; c-basic-offset:4 -*- padwidget.cpp This file is part of Kleopatra, the KDE keymanager SPDX-FileCopyrightText: 2018 Intevation GmbH SPDX-License-Identifier: GPL-2.0-or-later */ #include "padwidget.h" #include "kleopatra_debug.h" #include #include #include #include #include #include #include #include "crypto/gui/signencryptwidget.h" #include "crypto/gui/resultitemwidget.h" #include "crypto/signencrypttask.h" #include "crypto/decryptverifytask.h" #include #include "utils/input.h" #include "utils/output.h" #include "commands/importcertificatefromdatacommand.h" #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::Crypto; using namespace Kleo::Crypto::Gui; static GpgME::Protocol getProtocol(const std::shared_ptr &result) { const auto dvResult = dynamic_cast(result.get()); if (dvResult) { for (const auto &key: KeyCache::instance()->findRecipients(dvResult->decryptionResult())) { return key.protocol(); } for (const auto &key: KeyCache::instance()->findSigners(dvResult->verificationResult())) { return key.protocol(); } } return GpgME::UnknownProtocol; } class PadWidget::Private { friend class ::Kleo::PadWidget; public: Private(PadWidget *qq): q(qq), mEdit(new QTextEdit), mCryptBtn(new QPushButton(QIcon::fromTheme(QStringLiteral("document-edit-sign-encrypt")), i18n("Sign / Encrypt Notepad"))), mDecryptBtn(new QPushButton(QIcon::fromTheme(QStringLiteral("document-edit-decrypt-verify")), i18n("Decrypt / Verify Notepad"))), mRevertBtn(new QPushButton(QIcon::fromTheme(QStringLiteral("edit-undo")), i18n("Revert"))), mMessageWidget{new KMessageWidget}, mAdditionalInfoLabel(new QLabel), mSigEncWidget(new SignEncryptWidget(nullptr, true)), mProgressBar(new QProgressBar), mProgressLabel(new QLabel), mLastResultWidget(nullptr), mPGPRB(nullptr), mCMSRB(nullptr), mImportProto(GpgME::UnknownProtocol) { auto vLay = new QVBoxLayout(q); auto btnLay = new QHBoxLayout; vLay->addLayout(btnLay); btnLay->addWidget(mCryptBtn); btnLay->addWidget(mDecryptBtn); btnLay->addWidget(mRevertBtn); mRevertBtn->setVisible(false); btnLay->addWidget(mAdditionalInfoLabel); btnLay->addStretch(-1); mMessageWidget->setMessageType(KMessageWidget::Warning); mMessageWidget->setIcon(q->style()->standardIcon(QStyle::SP_MessageBoxWarning, nullptr, q)); mMessageWidget->setText(i18n("Signing and encryption is not possible.")); mMessageWidget->setToolTip(xi18nc("@info %1 is a placeholder for the name of a compliance mode. E.g. NATO RESTRICTED compliant or VS-NfD compliant", "You cannot use Kleopatra for signing or encryption " "because the GnuPG system used by Kleopatra is not %1.", DeVSCompliance::name(true))); mMessageWidget->setCloseButtonVisible(false); mMessageWidget->setVisible(false); vLay->addWidget(mMessageWidget); mProgressBar->setRange(0, 0); mProgressBar->setVisible(false); mProgressLabel->setVisible(false); auto progLay = new QHBoxLayout; progLay->addWidget(mProgressLabel); progLay->addWidget(mProgressBar); mStatusLay = new QVBoxLayout; mStatusLay->addLayout(progLay); vLay->addLayout(mStatusLay, 0); auto tabWidget = new QTabWidget; vLay->addWidget(tabWidget, 1); tabWidget->addTab(mEdit, QIcon::fromTheme(QStringLiteral("edittext")), i18n("Notepad")); // The recipients area auto recipientsWidget = new QWidget; auto recipientsVLay = new QVBoxLayout(recipientsWidget); auto protocolSelectionLay = new QHBoxLayout; bool pgpOnly = KeyCache::instance()->pgpOnly(); if (!pgpOnly) { recipientsVLay->addLayout(protocolSelectionLay); } protocolSelectionLay->addWidget(new QLabel(i18n("

Protocol:

"))); protocolSelectionLay->addStretch(-1); // Once S/MIME is supported add radio for S/MIME here. recipientsVLay->addWidget(mSigEncWidget); tabWidget->addTab(recipientsWidget, QIcon::fromTheme(QStringLiteral("contact-new-symbolic")), i18n("Recipients")); mEdit->setPlaceholderText(i18n("Enter a message to encrypt or decrypt...")); auto fixedFont = QFont(QStringLiteral("Monospace")); fixedFont.setStyleHint(QFont::TypeWriter); // This does not work well // QFontDatabase::systemFont(QFontDatabase::FixedFont); mEdit->setFont(fixedFont); mEdit->setAcceptRichText(false); mEdit->setMinimumWidth(QFontMetrics(fixedFont).averageCharWidth() * 70); if (KeyCache::instance()->pgpOnly() || !Settings{}.cmsEnabled()) { mSigEncWidget->setProtocol(GpgME::OpenPGP); } else { auto grp = new QButtonGroup(q); auto mPGPRB = new QRadioButton(i18n("OpenPGP")); auto mCMSRB = new QRadioButton(i18n("S/MIME")); grp->addButton(mPGPRB); grp->addButton(mCMSRB); KConfigGroup config(KSharedConfig::openConfig(), "Notepad"); if (config.readEntry("wasCMS", false)) { mCMSRB->setChecked(true); mSigEncWidget->setProtocol(GpgME::CMS); } else { mPGPRB->setChecked(true); mSigEncWidget->setProtocol(GpgME::OpenPGP); } protocolSelectionLay->addWidget(mPGPRB); protocolSelectionLay->addWidget(mCMSRB); connect(mPGPRB, &QRadioButton::toggled, q, [this] (bool value) { if (value) { mSigEncWidget->setProtocol(GpgME::OpenPGP); } }); connect(mCMSRB, &QRadioButton::toggled, q, [this] (bool value) { if (value) { mSigEncWidget->setProtocol(GpgME::CMS); } }); } updateCommitButton(); connect(mEdit, &QTextEdit::textChanged, q, [this] () { updateCommitButton(); }); connect(mCryptBtn, &QPushButton::clicked, q, [this] () { if (mImportProto != GpgME::UnknownProtocol) { doImport(); } else { doEncryptSign(); } }); connect(mSigEncWidget, &SignEncryptWidget::operationChanged, q, [this] (const QString &) { updateCommitButton(); }); connect(mDecryptBtn, &QPushButton::clicked, q, [this] () { doDecryptVerify(); }); connect(mRevertBtn, &QPushButton::clicked, q, [this] () { revert(); }); } void revert() { mEdit->setPlainText(QString::fromUtf8(mInputData)); mRevertBtn->setVisible(false); } void updateRecipientsFromResult(const Kleo::Crypto::DecryptVerifyResult &result) { const auto decResult = result.decryptionResult(); for (const auto &recipient: decResult.recipients()) { if (!recipient.keyID()) { continue; } GpgME::Key key; if (strlen(recipient.keyID()) < 16) { key = KeyCache::instance()->findByShortKeyID(recipient.keyID()); } else { key = KeyCache::instance()->findByKeyIDOrFingerprint(recipient.keyID()); } if (key.isNull()) { std::vector subids; subids.push_back(std::string(recipient.keyID())); for (const auto &subkey: KeyCache::instance()->findSubkeysByKeyID(subids)) { key = subkey.parent(); break; } } if (key.isNull()) { qCDebug(KLEOPATRA_LOG) << "Unknown key" << recipient.keyID(); mSigEncWidget->addUnknownRecipient(recipient.keyID()); continue; } bool keyFound = false; for (const auto &existingKey: mSigEncWidget->recipients()) { if (existingKey.primaryFingerprint() && key.primaryFingerprint() && !strcmp (existingKey.primaryFingerprint(), key.primaryFingerprint())) { keyFound = true; break; } } if (!keyFound) { mSigEncWidget->addRecipient(key); } } } void cryptDone(const std::shared_ptr &result) { updateCommitButton(); mProgressBar->setVisible(false); mProgressLabel->setVisible(false); mLastResultWidget = new ResultItemWidget(result); mLastResultWidget->showCloseButton(true); mStatusLay->addWidget(mLastResultWidget); connect(mLastResultWidget, &ResultItemWidget::closeButtonClicked, q, [this] () { removeLastResultItem(); }); // Check result protocol if (mPGPRB) { auto proto = getProtocol(result); if (proto == GpgME::UnknownProtocol) { proto = mPGPRB->isChecked() ? GpgME::OpenPGP : GpgME::CMS; } else if (proto == GpgME::OpenPGP) { mPGPRB->setChecked(true); } else if (proto == GpgME::CMS) { mCMSRB->setChecked(true); } KConfigGroup config(KSharedConfig::openConfig(), "Notepad"); config.writeEntry("wasCMS", proto == GpgME::CMS); } if (result->errorCode()) { if (!result->errorString().isEmpty()) { KMessageBox::error(q, result->errorString(), i18nc("@title", "Error in crypto action")); } return; } mEdit->setPlainText(QString::fromUtf8(mOutputData)); mOutputData.clear(); mRevertBtn->setVisible(true); mDecryptBtn->setEnabled(true); const auto decryptVerifyResult = dynamic_cast(result.get()); if (decryptVerifyResult) { updateRecipientsFromResult(*decryptVerifyResult); } } void doDecryptVerify() { doCryptoCommon(); mSigEncWidget->clearAddedRecipients(); mProgressLabel->setText(i18n("Decrypt / Verify") + QStringLiteral("...")); auto input = Input::createFromByteArray(&mInputData, i18n("Notepad")); auto output = Output::createFromByteArray(&mOutputData, i18n("Notepad")); AbstractDecryptVerifyTask *task; auto classification = input->classification(); if (classification & Class::OpaqueSignature || classification & Class::ClearsignedMessage) { auto verifyTask = new VerifyOpaqueTask(); verifyTask->setInput(input); verifyTask->setOutput(output); task = verifyTask; } else { auto decTask = new DecryptVerifyTask(); decTask->setInput(input); decTask->setOutput(output); task = decTask; } try { task->autodetectProtocolFromInput(); } catch (const Kleo::Exception &e) { KMessageBox::error(q, e.message(), i18nc("@title", "Error in crypto action")); updateCommitButton(); mProgressBar->setVisible(false); mProgressLabel->setVisible(false); return; } connect (task, &Task::result, q, [this, task] (const std::shared_ptr &result) { qCDebug(KLEOPATRA_LOG) << "Decrypt / Verify done. Err:" << result->errorCode(); task->deleteLater(); cryptDone(result); }); task->start(); } void removeLastResultItem() { if (mLastResultWidget) { mStatusLay->removeWidget(mLastResultWidget); delete mLastResultWidget; mLastResultWidget = nullptr; } } void doCryptoCommon() { mCryptBtn->setEnabled(false); mDecryptBtn->setEnabled(false); mProgressBar->setVisible(true); mProgressLabel->setVisible(true); mInputData = mEdit->toPlainText().toUtf8(); removeLastResultItem(); } void doEncryptSign() { if (DeVSCompliance::isActive() && !DeVSCompliance::isCompliant()) { KMessageBox::sorry(q->topLevelWidget(), xi18nc("@info %1 is a placeholder for the name of a compliance mode. E.g. NATO RESTRICTED compliant or VS-NfD compliant", "Sorry! You cannot use Kleopatra for signing or encryption " "because the GnuPG system used by Kleopatra is not %1.", DeVSCompliance::name(true))); return; } doCryptoCommon(); mProgressLabel->setText(mSigEncWidget->currentOp() + QStringLiteral("...")); auto input = Input::createFromByteArray(&mInputData, i18n("Notepad")); auto output = Output::createFromByteArray(&mOutputData, i18n("Notepad")); auto task = new SignEncryptTask(); task->setInput(input); task->setOutput(output); const auto sigKey = mSigEncWidget->signKey(); const std::vector recipients = mSigEncWidget->recipients(); const bool encrypt = mSigEncWidget->encryptSymmetric() || !recipients.empty(); const bool sign = !sigKey.isNull(); if (sign) { task->setSign(true); std::vector signVector; signVector.push_back(sigKey); task->setSigners(signVector); } else { task->setSign(false); } task->setEncrypt(encrypt); task->setRecipients(recipients); task->setEncryptSymmetric(mSigEncWidget->encryptSymmetric()); task->setAsciiArmor(true); if (sign && !encrypt && sigKey.protocol() == GpgME::OpenPGP) { task->setClearsign(true); } connect (task, &Task::result, q, [this, task] (const std::shared_ptr &result) { qCDebug(KLEOPATRA_LOG) << "Encrypt / Sign done. Err:" << result->errorCode(); task->deleteLater(); cryptDone(result); }); task->start(); } void doImport() { doCryptoCommon(); mProgressLabel->setText(i18n("Importing...")); auto cmd = new Kleo::ImportCertificateFromDataCommand(mInputData, mImportProto); connect(cmd, &Kleo::ImportCertificatesCommand::finished, q, [this] () { mCryptBtn->setEnabled(true); mDecryptBtn->setEnabled(true); mProgressBar->setVisible(false); mProgressLabel->setVisible(false); updateCommitButton(); mRevertBtn->setVisible(true); mEdit->setPlainText(QString()); }); cmd->start(); } void checkImportProtocol() { QGpgME::QByteArrayDataProvider dp(mEdit->toPlainText().toUtf8()); GpgME::Data data(&dp); auto type = data.type(); if (type == GpgME::Data::PGPKey) { mImportProto = GpgME::OpenPGP; } else if (type == GpgME::Data::X509Cert || type == GpgME::Data::PKCS12) { mImportProto = GpgME::CMS; } else { mImportProto = GpgME::UnknownProtocol; } } void updateCommitButton() { mAdditionalInfoLabel->setVisible(false); checkImportProtocol(); if (mImportProto != GpgME::UnknownProtocol) { mCryptBtn->setText(i18nc("1 is an operation to apply to the notepad. " "Like Sign/Encrypt or just Encrypt.", "%1 Notepad", i18n("Import"))); mCryptBtn->setEnabled(true); return; } if (!mSigEncWidget->currentOp().isEmpty()) { mCryptBtn->setEnabled(true); mCryptBtn->setText(i18nc("1 is an operation to apply to the notepad. " "Like Sign/Encrypt or just Encrypt.", "%1 Notepad", mSigEncWidget->currentOp())); } else { mCryptBtn->setText(i18n("Sign / Encrypt Notepad")); mCryptBtn->setEnabled(false); } if (DeVSCompliance::isActive()) { const bool de_vs = DeVSCompliance::isCompliant() && mSigEncWidget->isDeVsAndValid(); - mCryptBtn->setIcon(QIcon::fromTheme(de_vs - ? QStringLiteral("security-high") - : QStringLiteral("security-medium"))); - if (!SystemInfo::isHighContrastModeActive()) { - mCryptBtn->setStyleSheet(QStringLiteral("QPushButton { background-color: %1; }").arg(de_vs - ? KColorScheme(QPalette::Active, KColorScheme::View).background(KColorScheme::PositiveBackground).color().name() - : KColorScheme(QPalette::Active, KColorScheme::View).background(KColorScheme::NegativeBackground).color().name())); - } + DeVSCompliance::decorate(mCryptBtn, de_vs); mAdditionalInfoLabel->setText(de_vs ? i18nc("%1 is a placeholder for the name of a compliance mode. E.g. NATO RESTRICTED compliant or VS-NfD compliant", "%1 communication possible.", DeVSCompliance::name(true)) : i18nc("%1 is a placeholder for the name of a compliance mode. E.g. NATO RESTRICTED compliant or VS-NfD compliant", "%1 communication not possible.", DeVSCompliance::name(true))); mAdditionalInfoLabel->setVisible(true); if (!DeVSCompliance::isCompliant()) { mCryptBtn->setEnabled(false); } mMessageWidget->setVisible(!DeVSCompliance::isCompliant()); } } private: PadWidget *const q; QTextEdit *mEdit; QPushButton *mCryptBtn; QPushButton *mDecryptBtn; QPushButton *mRevertBtn; KMessageWidget *mMessageWidget; QLabel *mAdditionalInfoLabel; QByteArray mInputData; QByteArray mOutputData; SignEncryptWidget *mSigEncWidget; QProgressBar *mProgressBar; QLabel *mProgressLabel; QVBoxLayout *mStatusLay; ResultItemWidget *mLastResultWidget; QList mAutoAddedKeys; QRadioButton *mPGPRB; QRadioButton *mCMSRB; GpgME::Protocol mImportProto; }; PadWidget::PadWidget(QWidget *parent): QWidget(parent), d(new Private(this)) { } void PadWidget::focusFirstChild(Qt::FocusReason reason) { d->mEdit->setFocus(reason); }