QtPass Developer documentation
QtPass test coverage
Current view: top level - src/usersdialog.cpp (source / functions) Coverage Total Hit
Test: QtPass Lines: 96.5 % 428 413
Test Date: 2026-12-03 23:34:20 Functions: 100.0 % 45 45
Branches: 82.1 % 391 321

             Branch data     Line data    Source code
       1                 :             : // SPDX-FileCopyrightText: 2015 Anne Jan Brouwer
       2                 :             : // SPDX-License-Identifier: GPL-3.0-or-later
       3                 :             : /**
       4                 :             :  * @file
       5                 :             :  * @brief Implements UsersDialog; selectRecipients() matches the `.gpg-id`
       6                 :             :  * lines against the keyring and lists the ones no key answers to.
       7                 :             :  */
       8                 :             : #include "usersdialog.h"
       9                 :             : #include "importkeydialog.h"
      10                 :             : #include "pass.h"
      11                 :             : #include "plainmessagebox.h"
      12                 :             : #include "qtpasssettings.h"
      13                 :             : #include "ui_usersdialog.h"
      14                 :             : #include "util.h"
      15                 :             : #include "windowstatestore.h"
      16                 :             : #include <QApplication>
      17                 :             : #include <QDateTime>
      18                 :             : #include <QDialogButtonBox>
      19                 :             : #include <QDir>
      20                 :             : #include <QFileInfo>
      21                 :             : #include <QFont>
      22                 :             : #include <QHash>
      23                 :             : #include <QKeyEvent>
      24                 :             : #include <QLabel>
      25                 :             : #include <QLineEdit>
      26                 :             : #include <QListWidget>
      27                 :             : #include <QMessageBox>
      28                 :             : #include <QPalette>
      29                 :             : #include <QPushButton>
      30                 :             : #include <QRegularExpression>
      31                 :             : #include <QScrollArea>
      32                 :             : #include <QSet>
      33                 :             : #include <QSignalBlocker>
      34                 :             : #include <QWidget>
      35                 :             : #include <algorithm>
      36                 :             : #include <iterator>
      37                 :             : #include <utility>
      38                 :             : 
      39                 :             : #include "qtpasslogging.h"
      40                 :          67 : UsersDialog::UsersDialog(Pass *pass, const AppSettings &s, QString dir,
      41                 :          67 :                          QWidget *parent)
      42                 :         134 :     : UsersDialog(pass, s, std::move(dir), Preselect::FromList, parent) {}
      43                 :             : 
      44                 :          71 : UsersDialog::UsersDialog(Pass *pass, const AppSettings &s, QString dir,
      45                 :          71 :                          Preselect preselect, QWidget *parent)
      46                 :          71 :     : QDialog(parent), ui(new Ui::UsersDialog), m_pass(pass),
      47                 :             :       m_passStore(s.passStore), m_gpgExe(s.gpgExecutable),
      48                 :         142 :       m_dir(std::move(dir)), m_preselect(preselect) {
      49                 :             :   Q_ASSERT(pass);
      50                 :          71 :   ui->setupUi(this);
      51                 :             : 
      52                 :          71 :   restoreDialogState();
      53      [ +  +  + ]:          71 :   if (!loadGpgKeys()) {
      54                 :           1 :     connect(ui->buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
      55                 :           1 :     return;
      56                 :             :   }
      57                 :             : 
      58                 :          70 :   loadRecipients();
      59                 :          70 :   showNestedLists();
      60                 :          70 :   populateList();
      61                 :             : 
      62                 :          70 :   connectSignals();
      63                 :           0 : }
      64                 :             : 
      65                 :          70 : void UsersDialog::connectSignals() {
      66                 :          70 :   connect(ui->buttonBox, &QDialogButtonBox::accepted, this,
      67                 :          70 :           &UsersDialog::accept);
      68                 :          70 :   connect(ui->buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
      69                 :          70 :   connect(ui->listWidget, &QListWidget::itemChanged, this,
      70                 :         140 :           &UsersDialog::itemChange);
      71                 :             :   // importKeyButton is wired via Qt's automatic on_<name>_<signal> mechanism
      72                 :             :   // already triggered by setupUi().
      73                 :             : 
      74                 :          70 :   ui->lineEdit->setClearButtonEnabled(true);
      75                 :          70 : }
      76                 :             : 
      77                 :          71 : void UsersDialog::restoreDialogState() {
      78                 :         142 :   WindowStateStore::attach(*this, QStringLiteral("usersDialog"));
      79                 :          71 : }
      80                 :             : 
      81                 :          73 : auto UsersDialog::loadGpgKeys() -> bool {
      82                 :          73 :   QList<UserInfo> users = m_pass->listKeys();
      83         [ +  + ]:          73 :   if (users.isEmpty()) {
      84                 :           3 :     QMessageBox::critical(parentWidget(), tr("Keylist missing"),
      85                 :           0 :                           tr("Could not fetch list of available GPG keys"));
      86                 :           1 :     reject();
      87                 :             :     return false;
      88                 :             :   }
      89                 :             : 
      90                 :          72 :   markSecretKeys(users);
      91                 :             : 
      92                 :             :   m_userList = std::move(users);
      93                 :          72 :   return true;
      94                 :             : }
      95                 :             : 
      96                 :          72 : void UsersDialog::markSecretKeys(QList<UserInfo> &users) {
      97                 :         144 :   QList<UserInfo> secret_keys = m_pass->listKeys("", true);
      98                 :             :   QSet<QString> secretKeyIds;
      99         [ +  + ]:          79 :   for (const UserInfo &sec : std::as_const(secret_keys)) {
     100                 :           7 :     secretKeyIds.insert(sec.key_id);
     101                 :             :   }
     102      [ +  +  + ]:         211 :   for (auto &user : users) {
     103         [ +  + ]:         139 :     if (secretKeyIds.contains(user.key_id)) {
     104                 :           7 :       user.have_secret = true;
     105                 :             :     }
     106                 :             :   }
     107                 :          72 : }
     108                 :             : 
     109                 :          14 : void UsersDialog::showRecipientWarning(const QString &text,
     110                 :             :                                        const QString &name) {
     111                 :             :   // Plain text before the text is set: it can quote the store's recipient
     112                 :             :   // list, which as rich text could make Qt load a file (<img src=...>).
     113                 :          14 :   auto *banner = new QLabel(this);
     114                 :          14 :   banner->setTextFormat(Qt::PlainText);
     115                 :             :   // And with nothing in it that changes how the rest reads: a folder name
     116                 :             :   // with a bidi override mirrored the warning after it.
     117                 :          14 :   banner->setText(Util::displayable(text));
     118                 :          14 :   banner->setObjectName(name);
     119                 :          14 :   banner->setWordWrap(true);
     120                 :             :   // Palette, not a stylesheet colour, so it reads on dark themes too; red as
     121                 :             :   // ProcessOutputPanel paints error lines.
     122                 :          14 :   QFont bold = banner->font();
     123                 :             :   bold.setBold(true);
     124                 :          14 :   banner->setFont(bold);
     125                 :          14 :   QPalette palette = banner->palette();
     126                 :          14 :   palette.setColor(QPalette::WindowText, QColor(Qt::red));
     127                 :          14 :   banner->setPalette(palette);
     128                 :          14 :   banner->setContentsMargins(4, 4, 4, 4);
     129                 :             :   // In a scroll area of a few lines: the text quotes folder paths a
     130                 :             :   // co-writer chose, and a word-wrapped label is as wide as its longest
     131                 :             :   // run without a space and as tall as its lines. Unscrolled it sized the
     132                 :             :   // dialog to tens of thousands of pixels; a scroll area asks for at most
     133                 :             :   // a bounded size, and all of the text can still be read.
     134                 :          14 :   auto *area = new QScrollArea(this);
     135                 :          14 :   area->setWidget(banner);
     136                 :          14 :   area->setWidgetResizable(true);
     137                 :          14 :   area->setFrameShape(QFrame::NoFrame);
     138                 :          14 :   area->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
     139                 :          14 :   area->setMaximumHeight(banner->fontMetrics().lineSpacing() * 8 + 8);
     140                 :          14 :   ui->verticalLayout->insertWidget(1, area);
     141                 :          14 : }
     142                 :             : 
     143                 :          70 : void UsersDialog::showNestedLists() {
     144                 :             :   // The walk re-encryption takes: hidden folders and links are not entered.
     145                 :          70 :   const QString dir = QDir::cleanPath(m_dir);
     146   [ +  +  -  + ]:          70 :   if (!QFileInfo(dir).isDir()) {
     147                 :             :     return;
     148                 :             :   }
     149                 :          70 :   QStringList unlisted;
     150                 :         210 :   const QStringList lists = Util::regularFilesUnder(
     151                 :         140 :       dir, {QStringLiteral(".gpg-id")}, nullptr, true, &unlisted);
     152                 :          10 :   const auto relative = [&dir](const QString &folder) {
     153                 :          20 :     return QDir::toNativeSeparators(QDir(dir).relativeFilePath(folder));
     154                 :          70 :   };
     155                 :          70 :   QStringList nested;
     156         [ +  + ]:         129 :   for (const QString &list : lists) {
     157                 :          59 :     const QString folder = QFileInfo(list).path();
     158      [ +  +  + ]:         118 :     if (QDir::cleanPath(folder) != dir) {
     159                 :          18 :       nested << relative(folder);
     160                 :             :     }
     161                 :             :   }
     162                 :          70 :   QStringList unread;
     163         [ +  + ]:          71 :   for (const QString &folder : std::as_const(unlisted)) {
     164                 :           2 :     unread << relative(folder);
     165                 :             :   }
     166                 :             :   constexpr qsizetype kMaxNamed = 5;
     167                 :           5 :   const auto named = [](const QStringList &folders) {
     168                 :          10 :     QString names = folders.mid(0, kMaxNamed).join(QStringLiteral(", "));
     169         [ -  + ]:           5 :     if (folders.size() > kMaxNamed) {
     170                 :           0 :       names += QStringLiteral(", …");
     171                 :             :     }
     172                 :           5 :     return names;
     173                 :             :   };
     174                 :          70 :   QStringList text;
     175         [ +  + ]:          70 :   if (!nested.isEmpty()) {
     176                 :             :     //: %1 lists folders, such as "work, work/bank". Shown when changing the
     177                 :             :     //: recipients of a folder that has folders with their own list below it.
     178                 :           4 :     text << tr("%n folder(s) below this one have their own recipients, which "
     179                 :             :                "saving here does not change: %1",
     180                 :             :                nullptr, static_cast<int>(nested.size()))
     181                 :           8 :                 .arg(named(nested));
     182                 :             :   }
     183         [ +  + ]:          70 :   if (!unread.isEmpty()) {
     184                 :             :     //: %1 lists folders, such as "work, work/bank", that QtPass could not
     185                 :             :     //: read: no permission, or a name in them that is not valid UTF-8.
     186                 :           1 :     text << tr("%n folder(s) below this one could not be read, so whether "
     187                 :             :                "they have their own recipients is unknown: %1",
     188                 :             :                nullptr, static_cast<int>(unread.size()))
     189                 :           2 :                 .arg(named(unread));
     190                 :             :   }
     191         [ +  + ]:          70 :   if (!text.isEmpty()) {
     192                 :          10 :     showRecipientWarning(text.join(QLatin1Char('\n')),
     193                 :           5 :                          QStringLiteral("nestedListsWarning"));
     194                 :             :   }
     195                 :             : }
     196                 :             : 
     197                 :             : namespace {
     198                 :             : 
     199                 :             : /// A key ID as written anywhere: without a 0x prefix, upper case.
     200                 :         436 : auto normalisedKeyId(const QString &id) -> QString {
     201                 :             :   const QString trimmed = id.trimmed();
     202                 :         436 :   return (trimmed.startsWith(QLatin1String("0x"), Qt::CaseInsensitive)
     203      [ -  +  - ]:         872 :               ? trimmed.mid(2)
     204                 :             :               : trimmed)
     205                 :         436 :       .toUpper();
     206                 :             : }
     207                 :             : 
     208                 :             : /// Whether two hex identifiers name the same key. v4 key IDs are fingerprint
     209                 :             : /// suffixes; v5/v6 key IDs are the first 16 digits, with the short ID in the
     210                 :             : /// following eight. Do not accept a v5/v6 fingerprint's tail as its key ID.
     211                 :         218 : auto keyIdsMatch(const QString &first, const QString &second) -> bool {
     212                 :         225 :   static const QRegularExpression hexId(QStringLiteral("^[0-9A-F]{8,}$"));
     213                 :         218 :   const QString a = normalisedKeyId(first);
     214                 :         218 :   const QString b = normalisedKeyId(second);
     215   [ +  +  +  -  :         436 :   if (!hexId.match(a).hasMatch() || !hexId.match(b).hasMatch()) {
          +  +  +  -  -  
                +  -  - ]
     216                 :             :     return false;
     217                 :             :   }
     218         [ +  + ]:         218 :   if (a.size() == 64) {
     219   [ -  +  +  +  :          16 :     return b == a || (b.size() == 16 && a.startsWith(b)) ||
             +  +  +  +  
                      + ]
     220                 :          19 :            (b.size() == 8 && a.mid(8, 8) == b);
     221                 :             :   }
     222         [ -  + ]:         202 :   if (b.size() == 64) {
     223   [ #  #  #  #  :           0 :     return a == b || (a.size() == 16 && b.startsWith(a)) ||
             #  #  #  #  
                      # ]
     224                 :           0 :            (a.size() == 8 && b.mid(8, 8) == a);
     225                 :             :   }
     226   [ +  +  +  +  :         202 :   return a.endsWith(b) || b.endsWith(a);
                   +  + ]
     227                 :             : }
     228                 :             : 
     229                 :             : /// The hex identifier a .gpg-id line names, without "0x" and a trailing
     230                 :             : /// "!", when the line is one in the lengths gpg reads as a key ID or
     231                 :             : /// fingerprint (8, 16, 40 or 64 digits); empty otherwise.
     232                 :       18360 : auto keyIdOfLine(const QString &recipient) -> QString {
     233                 :             :   static const QRegularExpression hexLine(
     234   [ +  +  +  -  :       18366 :       QStringLiteral("^(?:0[xX])?([0-9A-Fa-f]+)!?$"));
                      + ]
     235                 :       18360 :   const QRegularExpressionMatch match = hexLine.match(recipient.trimmed());
     236      [ +  +  + ]:       18360 :   if (!match.hasMatch()) {
     237                 :       18053 :     return {};
     238                 :             :   }
     239                 :         307 :   const QString digits = match.captured(1);
     240                 :             :   const qsizetype size = digits.size();
     241         [ +  - ]:         307 :   return size == 8 || size == 16 || size == 40 || size == 64 ? digits
     242                 :           0 :                                                              : QString();
     243                 :       18360 : }
     244                 :             : 
     245                 :             : /// The text a .gpg-id line searches the user IDs for, after gpg's "=",
     246                 :             : /// "<...>", "@" and "*" markers; empty when the line is not one of those
     247                 :             : /// forms or a plain name.
     248                 :       18038 : auto nameTermOfLine(const QString &recipient) -> QString {
     249                 :             :   const QString line = recipient.trimmed();
     250         [ -  + ]:       18038 :   if (line.isEmpty()) {
     251                 :           0 :     return {};
     252                 :             :   }
     253                 :             :   // A leading 0x, digits only, or groups of four digits split by spaces (a
     254                 :             :   // fingerprint as gpg prints it) is a key ID gpg reads in its own way
     255                 :             :   // (keyIdOfLine() takes the lengths it accepts); ".", "+", "#", "&", "^",
     256                 :             :   // "/", "[" and ":" start search modes this dialog does not model.
     257                 :           1 :   static const QRegularExpression hexish(QStringLiteral(
     258   [ +  +  +  -  :       18040 :       "^(?:0[xX]|[0-9A-Fa-f]+!?$|[0-9A-Fa-f]{4}(?:\\s+[0-9A-Fa-f]{4})+!?$)"));
                      + ]
     259   [ +  +  +  +  :       36076 :   if (hexish.match(line).hasMatch() ||
                   +  + ]
     260   [ +  +  +  +  :       36071 :       QStringLiteral(".+#&^/[:!\\").contains(line.front())) {
                   -  - ]
     261                 :          17 :     return {};
     262                 :             :   }
     263                 :             :   QString term = line;
     264      [ +  +  + ]:       18021 :   if (term.startsWith(u'<')) {
     265      [ +  -  + ]:           2 :     if (!term.endsWith(u'>')) {
     266                 :           0 :       return {};
     267                 :             :     }
     268                 :           4 :     term = term.mid(1, term.size() - 2);
     269   [ +  +  -  +  :       36038 :   } else if (term.startsWith(u'=') || term.startsWith(u'@') ||
             +  -  +  - ]
     270                 :       36038 :              term.startsWith(u'*')) {
     271                 :           0 :     term.remove(0, 1);
     272                 :             :   }
     273                 :             :   return term;
     274                 :             : }
     275                 :             : 
     276                 :             : /// Whether answersTo() can judge @p recipient on its own: a key ID or
     277                 :             : /// fingerprint in a length gpg reads as one, or a name. For those every key
     278                 :             : /// gpg resolves the line to is one answersTo() matches, given the key's full
     279                 :             : /// listing, so a line that matches no listed key names no key in the
     280                 :             : /// keyring. Any other form (a fingerprint written with spaces or between
     281                 :             : /// colons, a keygrip, "*" alone) needs gpg's own answer.
     282                 :        6119 : auto judgedLocally(const QString &recipient) -> bool {
     283   [ +  +  +  +  :       12145 :   return !keyIdOfLine(recipient).isEmpty() ||
                      + ]
     284      [ +  -  - ]:       12145 :          !nameTermOfLine(recipient).isEmpty();
     285                 :             : }
     286                 :             : 
     287                 :             : /// Whether @p recipient, a .gpg-id line judgedLocally() accepts, names
     288                 :             : /// @p key the way gpg's -r resolves it: a key ID or fingerprint of the key
     289                 :             : /// or of one of its subkeys (v4 key IDs are a fingerprint's tail, v5/v6 ones
     290                 :             : /// its head), or else a name, matched case-insensitively as a substring of
     291                 :             : /// any of its user IDs. That is as loose as gpg's substring search and
     292                 :             : /// looser than its exact ("="), mailbox ("<...>") and domain ("@") ones, so
     293                 :             : /// it may claim a key gpg would not, but never misses one gpg finds.
     294                 :       12155 : auto answersTo(const UserInfo &key, const QString &recipient) -> bool {
     295                 :       12155 :   const QString keyId = keyIdOfLine(recipient);
     296         [ +  + ]:       12155 :   if (!keyId.isEmpty()) {
     297      [ +  +  + ]:         143 :     return keyIdsMatch(key.key_id, keyId) ||
     298         [ +  + ]:         103 :            std::any_of(key.subkeys.cbegin(), key.subkeys.cend(),
     299                 :             :                        [&keyId](const QString &subkey) {
     300                 :          69 :                          return keyIdsMatch(subkey, keyId);
     301                 :             :                        });
     302                 :             :   }
     303                 :       12012 :   const QString term = nameTermOfLine(recipient);
     304         [ -  + ]:       12012 :   if (term.isEmpty()) {
     305                 :             :     return false;
     306                 :             :   }
     307                 :       24022 :   const auto holds = [&term](const QString &uid) {
     308                 :       24022 :     return uid.contains(term, Qt::CaseInsensitive);
     309                 :       12012 :   };
     310      [ +  +  + ]:       12012 :   return holds(key.name) ||
     311                 :       12009 :          std::any_of(key.uids.cbegin(), key.uids.cend(), holds);
     312                 :             : }
     313                 :             : 
     314                 :             : /// @p listed with each line once, in first-seen order: a line listed twice
     315                 :             : /// is one recipient, and one row.
     316                 :          47 : auto uniqueLines(const QStringList &listed) -> QStringList {
     317                 :          47 :   QStringList lines;
     318                 :             :   QSet<QString> seen;
     319         [ +  + ]:        6179 :   for (const QString &line : listed) {
     320         [ +  + ]:        6132 :     if (!seen.contains(line)) {
     321                 :        6131 :       seen.insert(line);
     322                 :             :       lines.append(line);
     323                 :             :     }
     324                 :             :   }
     325                 :          47 :   return lines;
     326                 :             : }
     327                 :             : 
     328                 :             : } // namespace
     329                 :             : 
     330                 :          47 : void UsersDialog::selectRecipients(const QStringList &listed) {
     331                 :          47 :   QStringList recipients = uniqueLines(listed);
     332                 :             : 
     333                 :             :   // OK saves what is ticked, so the ticks are the keys gpg's -r reaches for
     334                 :             :   // the list, found by a throwaway encryption. A keyring search would also
     335                 :             :   // find keys that only resemble a recipient: a user ID containing its
     336                 :             :   // address, a subkey bound to its key, which whoever made the key decides.
     337                 :             :   // Every reached key must have a row, or OK would drop it.
     338      [ +  +  + ]:          47 :   if (!setAsideHeldTwice(&recipients)) {
     339                 :             :     return;
     340                 :             :   }
     341                 :             :   const std::optional<QStringList> reached =
     342                 :          46 :       m_pass->encryptionReaches(recipients);
     343   [ +  +  +  +  :          46 :   if (reached && !reached->isEmpty() && tickReached(*reached, recipients)) {
                +  -  + ]
     344                 :             :     return;
     345                 :             :   }
     346                 :             :   // gpg refused the list as a whole: one line it cannot encrypt to (a
     347                 :             :   // key gone, expired or revoked), as in a list edited after someone
     348                 :             :   // left. Each line on its own, so the others still tick only what they
     349                 :             :   // reach, and a line gpg cannot encrypt to is kept as written. Address
     350                 :             :   // and name lines first, where look-alike keys come from: a key ID or
     351                 :             :   // fingerprint reaches the same key by probe or search. A line past the
     352                 :             :   // few probed is kept as written too, so OK writes it back and adds no
     353                 :             :   // key; only a line whose probe names no one goes to the search below.
     354   [ +  +  +  +  :          42 :   if (!reached && !probeEachLine(&recipients)) {
                      + ]
     355                 :             :     return;
     356                 :             :   }
     357                 :             :   // What a probe could not settle: gpg encrypted but did not say whom, or
     358                 :             :   // reached a key without a row. The keyring search below, as before.
     359                 :          39 :   searchKeyring(recipients);
     360                 :             : }
     361                 :             : 
     362                 :          23 : void UsersDialog::keepAsWritten(const QString &line, const QString &why) {
     363                 :          23 :   UserInfo kept;
     364                 :          23 :   kept.key_id = line;
     365                 :          23 :   kept.enabled = true;
     366                 :          23 :   kept.name = " ?? " + why;
     367                 :          23 :   m_userList.append(kept);
     368                 :          23 : }
     369                 :             : 
     370                 :             : // Ticks the rows @p ids (what a probe of @p lines reached) belong to;
     371                 :             : // false, ticking nothing, when one has no row. A long key ID is a line
     372                 :             : // answersTo() judges as gpg does: the key's or one of its subkeys'. An
     373                 :             : // ID on more than one row is a subkey bound to several keys, where the
     374                 :             : // probe cannot tell which key gpg chose: only a line naming a reached
     375                 :             : // key's own primary key ticks its row, and any other line is kept as
     376                 :             : // written, so OK neither adds the key that shares the subkey nor drops
     377                 :             : // the recipient the line meant. Ticks are only added: after a key import
     378                 :             : // the rows ticked before stay.
     379                 :           6 : auto UsersDialog::tickReached(const QStringList &ids, const QStringList &lines)
     380                 :             :     -> bool {
     381                 :             :   bool shared = false;
     382                 :             :   QSet<int> reachedRows;
     383         [ +  + ]:          12 :   for (const QString &id : ids) {
     384                 :           6 :     QList<int> rows;
     385         [ +  + ]:          18 :     for (int row = 0; row < m_userList.size(); ++row) {
     386      [ +  +  + ]:          12 :       if (answersTo(m_userList.at(row), id)) {
     387                 :             :         rows << row;
     388                 :             :       }
     389                 :             :     }
     390         [ -  + ]:           6 :     if (rows.isEmpty()) {
     391                 :             :       return false;
     392                 :             :     }
     393   [ +  -  +  + ]:           6 :     shared = shared || rows.size() > 1;
     394         [ +  + ]:          14 :     for (const int row : std::as_const(rows)) {
     395                 :           8 :       reachedRows.insert(row);
     396                 :             :     }
     397                 :             :   }
     398         [ +  + ]:           6 :   if (!shared) {
     399                 :           4 :     for (const int row : std::as_const(reachedRows)) {
     400                 :           4 :       m_userList[row].enabled = true;
     401                 :             :     }
     402                 :           4 :     return true;
     403                 :             :   }
     404         [ +  + ]:           4 :   for (const QString &line : lines) {
     405                 :           2 :     const QString keyId = keyIdOfLine(line);
     406                 :             :     bool ticked = false;
     407         [ +  + ]:           2 :     if (!keyId.isEmpty()) {
     408                 :           2 :       for (const int row : std::as_const(reachedRows)) {
     409      [ +  +  + ]:           2 :         if (keyIdsMatch(m_userList.at(row).key_id, keyId)) {
     410                 :           1 :           m_userList[row].enabled = true;
     411                 :             :           ticked = true;
     412                 :             :         }
     413                 :             :       }
     414                 :             :     }
     415         [ -  + ]:           1 :     if (!ticked) {
     416                 :           2 :       keepAsWritten(line, tr("Matches more than one key; kept as written"));
     417                 :             :     }
     418                 :             :   }
     419                 :             :   return true;
     420                 :             : }
     421                 :             : 
     422                 :             : // A key ID or fingerprint that two key blocks hold (someone bound another
     423                 :             : // person's key to their own as a subkey) may encrypt to either: kept as
     424                 :             : // written and named, and not looked up, which would tick the other key.
     425                 :             : // A keyring that cannot be listed leaves every line untold: all kept as
     426                 :             : // written, nothing probed.
     427                 :          47 : auto UsersDialog::setAsideHeldTwice(QStringList *recipients) -> bool {
     428                 :             :   if (const std::optional<QHash<QString, QStringList>> held =
     429                 :          47 :           m_pass->keyLinesHeldTwice(*recipients);
     430         [ +  - ]:          47 :       !held || !held->isEmpty()) {
     431                 :           2 :     showRecipientWarning(Pass::describeKeyLinesHeldTwice(held),
     432                 :           1 :                          QStringLiteral("heldTwiceWarning"));
     433                 :           1 :     QStringList rest;
     434         [ +  + ]:           2 :     for (const QString &line : std::as_const(*recipients)) {
     435         [ -  + ]:           1 :       if (!held) {
     436                 :           0 :         keepAsWritten(line, tr("Keys could not be checked; kept as written"));
     437         [ +  - ]:           1 :       } else if (held->contains(line)) {
     438                 :           2 :         keepAsWritten(line, tr("Held by more than one key; kept as written"));
     439                 :             :       } else {
     440                 :             :         rest << line;
     441                 :             :       }
     442                 :             :     }
     443         [ +  - ]:           1 :     if (rest.isEmpty()) {
     444                 :             :       return false;
     445                 :             :     }
     446                 :             :     *recipients = std::move(rest);
     447                 :             :   }
     448                 :          46 :   return true;
     449                 :             : }
     450                 :             : 
     451                 :           7 : auto UsersDialog::probeEachLine(QStringList *recipients) -> bool {
     452                 :           7 :   QStringList order;
     453                 :           7 :   std::copy_if(recipients->cbegin(), recipients->cend(),
     454                 :             :                std::back_inserter(order),
     455                 :          42 :                [](const QString &line) { return keyIdOfLine(line).isEmpty(); });
     456                 :           7 :   std::copy_if(
     457                 :             :       recipients->cbegin(), recipients->cend(), std::back_inserter(order),
     458                 :          42 :       [](const QString &line) { return !keyIdOfLine(line).isEmpty(); });
     459                 :             :   constexpr int kMaxLineProbes = 10;
     460                 :           7 :   QStringList unsure;
     461                 :             :   int probes = 0;
     462         [ +  + ]:          49 :   for (const QString &line : std::as_const(order)) {
     463         [ +  + ]:          42 :     if (probes++ >= kMaxLineProbes) {
     464                 :           8 :       keepAsWritten(line, tr("Not checked; kept as written"));
     465                 :           8 :       continue;
     466                 :             :     }
     467                 :             :     // A one-line list: the probe that failed was this line's own.
     468                 :             :     const std::optional<QStringList> one =
     469         [ +  + ]:          34 :         recipients->size() == 1 ? std::nullopt
     470                 :         100 :                                 : m_pass->encryptionReaches({line});
     471         [ +  + ]:          34 :     if (!one) {
     472                 :          26 :       keepAsWritten(line, tr("Key not found in keyring, or not usable"));
     473   [ +  +  +  +  :          27 :     } else if (one->isEmpty() || !tickReached(*one, {line})) {
          -  +  +  +  +  
             +  +  -  - ]
     474                 :             :       unsure << line;
     475                 :             :     }
     476                 :             :   }
     477         [ +  + ]:           7 :   if (unsure.isEmpty()) {
     478                 :             :     return false;
     479                 :             :   }
     480                 :             :   *recipients = std::move(unsure);
     481                 :           4 :   return true;
     482                 :             : }
     483                 :             : 
     484                 :          39 : void UsersDialog::searchKeyring(const QStringList &recipients) {
     485                 :             :   // One gpg call resolves every recipient, by key ID or by email/UID.
     486                 :          78 :   QList<UserInfo> resolved = m_pass->listKeys(recipients);
     487   [ +  +  +  + ]:          39 :   if (resolved.isEmpty() && recipients.size() > 1) {
     488                 :             :     // One line gpg cannot read as a key search ("0x", a fingerprint one
     489                 :             :     // digit short) aborts that whole call with exit code 2, so nothing is
     490                 :             :     // listed for the other lines, whose keys are in the keyring all the same.
     491                 :             :     // Every form judgedLocally() accepts gpg reads, so ask again for those;
     492                 :             :     // the rest get a call of their own below.
     493                 :           2 :     QStringList readable;
     494                 :           2 :     std::copy_if(recipients.cbegin(), recipients.cend(),
     495                 :             :                  std::back_inserter(readable), judgedLocally);
     496   [ +  -  +  - ]:           2 :     if (!readable.isEmpty() && readable.size() < recipients.size()) {
     497                 :           4 :       resolved = m_pass->listKeys(std::move(readable));
     498                 :             :     }
     499                 :             :   }
     500                 :             : 
     501                 :             :   // A line answersTo() cannot judge gets gpg's own verdict, one blocking
     502                 :             :   // call each on the dialog's way up. Only unusual forms need it, so a few
     503                 :             :   // are asked; past that a line is listed unticked as not looked up, so it
     504                 :             :   // does not stay in the list unseen (a member could otherwise hide behind
     505                 :             :   // it a key the user unticks).
     506                 :             :   constexpr int kMaxLookups = 10;
     507                 :             :   int lookups = 0;
     508                 :          39 :   QHash<QString, bool> perLineHasKey;
     509                 :             :   QSet<QString> notLookedUp;
     510         [ +  + ]:        6142 :   for (const QString &recipient : std::as_const(recipients)) {
     511      [ +  +  + ]:        6103 :     if (judgedLocally(recipient)) {
     512                 :        6089 :       continue;
     513                 :             :     }
     514         [ +  + ]:          15 :     if (lookups++ >= kMaxLookups) {
     515                 :           1 :       notLookedUp.insert(recipient);
     516                 :           1 :       continue;
     517                 :             :     }
     518                 :          14 :     const QList<UserInfo> keys = m_pass->listKeys(recipient);
     519         [ +  + ]:          14 :     perLineHasKey.insert(recipient, !keys.isEmpty());
     520                 :             :     resolved += keys;
     521                 :             :   }
     522                 :             : 
     523   [ +  +  +  + ]:         122 :   for (UserInfo &user : m_userList) {
     524         [ +  + ]:          83 :     if (std::any_of(resolved.cbegin(), resolved.cend(),
     525                 :             :                     [&user](const UserInfo &key) {
     526         [ +  + ]:          96 :                       return key.key_id == user.key_id;
     527                 :             :                     })) {
     528                 :          51 :       user.enabled = true;
     529                 :             :     }
     530                 :             :   }
     531                 :             :   // Only what gpg itself cannot find is reported missing. A per-line answer
     532                 :             :   // is gpg's own verdict for that line and decides it outright; that also
     533                 :             :   // keeps a genuinely unreadable line ("0x") reported missing. Any other
     534                 :             :   // line is missing when no key gpg resolved answers to it: the full listing
     535                 :             :   // carries every user ID and subkey, so nothing is left for gpg to add.
     536         [ +  + ]:        6142 :   for (const QString &recipient : std::as_const(recipients)) {
     537                 :        6103 :     UserInfo missing;
     538                 :        6103 :     missing.key_id = recipient;
     539         [ +  + ]:        6103 :     if (notLookedUp.contains(recipient)) {
     540                 :           1 :       missing.name = " ?? " + tr("Not looked up in keyring");
     541                 :           1 :       m_notLookedUp.insert(recipient);
     542                 :             :       m_userList.append(missing);
     543                 :             :       continue;
     544                 :             :     }
     545                 :        6102 :     const auto cached = perLineHasKey.constFind(recipient);
     546                 :             :     const bool found = cached != perLineHasKey.constEnd()
     547                 :          14 :                            ? cached.value()
     548                 :        6088 :                            : std::any_of(resolved.cbegin(), resolved.cend(),
     549                 :             :                                          [&recipient](const UserInfo &key) {
     550                 :       12143 :                                            return answersTo(key, recipient);
     551                 :        6088 :                                          });
     552         [ +  + ]:        6102 :     if (!found) {
     553                 :        6057 :       missing.enabled = true;
     554                 :       12114 :       missing.name = " ?? " + tr("Key not found in keyring");
     555                 :             :       m_userList.append(missing);
     556                 :             :     }
     557                 :        6103 :   }
     558                 :          78 : }
     559                 :             : 
     560                 :          70 : void UsersDialog::loadRecipients() {
     561                 :             :   // A store that had no list when it was chosen (a new profile): a list
     562                 :             :   // that appeared since is nobody's choice, and was read under the active
     563                 :             :   // backend's signing policy, not the new profile's.
     564         [ +  + ]:          70 :   if (m_preselect == Preselect::Nothing) {
     565                 :           4 :     return;
     566                 :             :   }
     567                 :             :   // Through the backend: with a signing key only a verified list may be
     568                 :             :   // preselected, since OK signs whatever is selected.
     569                 :             :   const Pass::RecipientsForEditing loaded =
     570                 :          66 :       m_pass->recipientsForEditing(m_dir, m_passStore);
     571                 :          66 :   m_listRead = true;
     572                 :          66 :   m_readState = static_cast<int>(loaded.state);
     573                 :             :   m_readRecipients = loaded.recipients;
     574         [ +  + ]:          66 :   if (!loaded.warning.isEmpty()) {
     575                 :          16 :     showRecipientWarning(loaded.warning);
     576                 :             :   }
     577                 :             :   // A folder without .gpg-id (new store, new profile) has no recipients yet;
     578                 :             :   // listKeys() with no filter would return the whole keyring, preselected.
     579   [ +  +  +  + ]:          66 :   if (loaded.state != Pass::RecipientsForEditing::State::Rejected &&
     580                 :             :       !loaded.recipients.isEmpty()) {
     581                 :          47 :     selectRecipients(loaded.recipients);
     582                 :             :   }
     583                 :             : }
     584                 :             : 
     585                 :         142 : UsersDialog::~UsersDialog() = default;
     586                 :             : 
     587                 :          10 : auto UsersDialog::listChangedSinceRead() const -> bool {
     588                 :             :   const Pass::RecipientsForEditing now =
     589                 :          10 :       m_pass->recipientsForEditing(m_dir, m_passStore);
     590   [ +  -  +  + ]:          10 :   return static_cast<int>(now.state) != m_readState ||
     591         [ +  + ]:          10 :          now.recipients != m_readRecipients;
     592                 :             : }
     593                 :             : 
     594                 :          14 : void UsersDialog::accept() {
     595         [ +  + ]:          14 :   if (!hasSelection()) {
     596                 :             :     // Nothing to encrypt to: an empty .gpg-id would make every insert fail
     597                 :             :     // and the wizard never offers this dialog again once the file exists.
     598                 :             :     return;
     599                 :             :   }
     600                 :             :   // OK writes the whole selection, ticked from the list as it was read. A
     601                 :             :   // newer list that arrived meanwhile (a pull the watchdog let run on under
     602                 :             :   // the dialog, a sync) would be overwritten by the old one plus the user's
     603                 :             :   // change: someone just removed came back, signed as the next generation.
     604   [ +  +  +  + ]:          12 :   if (m_listRead && listChangedSinceRead()) {
     605                 :           2 :     QMessageBox::warning(
     606                 :           1 :         this, tr("Recipients not changed"),
     607                 :           1 :         tr("The recipient list of this folder changed while this dialog was "
     608                 :             :            "open, for example through an update from Git. OK would have "
     609                 :             :            "written the old list back. Close this dialog and open it again "
     610                 :             :            "to see the new list."));
     611                 :           1 :     return;
     612                 :             :   }
     613         [ +  + ]:          11 :   if (m_initOnAccept) {
     614                 :             :     // The pass backend re-encrypts every entry itself: asked first when one
     615                 :             :     // would gain a reader it does not have.
     616      [ +  +  + ]:          16 :     if (!PlainMessageBox::confirmPassRun(this, m_passStore, [this] {
     617                 :           8 :           return m_pass->entriesInitWouldWiden(m_dir, m_userList);
     618                 :             :         })) {
     619                 :             :       return;
     620                 :             :     }
     621         [ +  - ]:           7 :     if (m_listRead) {
     622                 :             :       // Compared again by the backend at the last point before it writes:
     623                 :             :       // a pull in a terminal can still land between here and there.
     624                 :           7 :       Pass::RecipientsForEditing read;
     625                 :           7 :       read.state = static_cast<Pass::RecipientsForEditing::State>(m_readState);
     626                 :             :       read.recipients = m_readRecipients;
     627                 :             :       // Refused there (changed after all, or another operation runs): the
     628                 :             :       // dialog stays open with the selection, as the message asks to save
     629                 :             :       // again.
     630      [ +  +  + ]:           7 :       if (!m_pass->initIfUnchanged(m_dir, m_userList, m_dir, m_passStore,
     631                 :             :                                    read)) {
     632                 :             :         return;
     633                 :             :       }
     634                 :             :     } else {
     635                 :           0 :       m_pass->Init(m_dir, m_userList);
     636                 :             :     }
     637                 :             :   }
     638                 :             : 
     639                 :           9 :   QDialog::accept();
     640                 :             : }
     641                 :             : 
     642                 :         132 : auto UsersDialog::hasSelection() const -> bool {
     643                 :             :   return std::any_of(m_userList.cbegin(), m_userList.cend(),
     644         [ +  + ]:         198 :                      [](const UserInfo &user) { return user.enabled; });
     645                 :             : }
     646                 :             : 
     647                 :         115 : void UsersDialog::updateOkButton() {
     648         [ +  - ]:         115 :   if (auto *ok = ui->buttonBox->button(QDialogButtonBox::Ok)) {
     649                 :         115 :     ok->setEnabled(hasSelection());
     650                 :             :   }
     651                 :         115 : }
     652                 :             : 
     653                 :           1 : void UsersDialog::keyPressEvent(QKeyEvent *event) {
     654         [ +  - ]:           1 :   switch (event->key()) {
     655                 :           1 :   case Qt::Key_Escape:
     656                 :           1 :     ui->lineEdit->clear();
     657                 :           1 :     break;
     658                 :             :   default:
     659                 :             :     break;
     660                 :             :   }
     661                 :           1 : }
     662                 :             : 
     663                 :          21 : void UsersDialog::itemChange(QListWidgetItem *item) {
     664         [ +  - ]:          21 :   if (!item) {
     665                 :           1 :     return;
     666                 :             :   }
     667                 :          21 :   bool ok = false;
     668                 :          21 :   const int index = item->data(Qt::UserRole).toInt(&ok);
     669         [ -  + ]:          21 :   if (!ok) {
     670                 :           0 :     qCWarning(lcQtPass)
     671                 :           0 :         << "UsersDialog::itemChange: invalid user index data for item";
     672                 :           0 :     return;
     673                 :             :   }
     674   [ +  -  +  + ]:          21 :   if (index < 0 || index >= m_userList.size()) {
     675                 :           2 :     qCWarning(lcQtPass) << "UsersDialog::itemChange: user index out of range:"
     676                 :           1 :                         << index << "valid range is [0,"
     677                 :           1 :                         << (m_userList.size() - 1) << "]";
     678                 :           1 :     return;
     679                 :             :   }
     680                 :          20 :   m_userList[index].enabled = item->checkState() == Qt::Checked;
     681                 :          20 :   updateOkButton();
     682                 :             : }
     683                 :             : 
     684                 :          95 : void UsersDialog::populateList(const QString &filter) {
     685                 :             :   // Invalidate cached datetime so expiry checks use fresh current time
     686                 :          95 :   m_cachedDateTimeValid = false;
     687                 :             : 
     688                 :          95 :   QString patternString = "*" + filter + "*";
     689         [ +  + ]:          95 :   if (m_cachedPatternString != patternString) {
     690                 :             :     // A user ID is not a path: "*" and "?" must match a "/" as well, or a
     691                 :             :     // key named "ACME A/S" or "(dev/ops)" drops out of the search and stays
     692                 :             :     // ticked unseen while the listed rows are unticked.
     693                 :             :     QRegularExpression re(
     694                 :         172 :         QRegularExpression::wildcardToRegularExpression(
     695                 :             :             patternString, QRegularExpression::NonPathWildcardConversion),
     696         [ +  + ]:          86 :         QRegularExpression::CaseInsensitiveOption);
     697      [ +  +  - ]:          86 :     if (re.isValid()) {
     698                 :          86 :       m_cachedNameFilter = re;
     699                 :             :       m_cachedPatternString = std::move(patternString);
     700                 :             :     }
     701                 :          86 :   }
     702                 :          95 :   const QRegularExpression &nameFilter = m_cachedNameFilter;
     703                 :             :   // Sorted once at the end: with sorting on, each badge and tick below
     704                 :             :   // re-sorted every row added so far, and a .gpg-id of thousands of
     705                 :             :   // unknown recipients kept the dialog from opening for minutes.
     706                 :          95 :   ui->listWidget->setSortingEnabled(false);
     707                 :          95 :   ui->listWidget->clear();
     708                 :             : 
     709         [ +  + ]:        6375 :   for (int i = 0; i < m_userList.size(); ++i) {
     710                 :             :     const auto &user = m_userList.at(i);
     711      [ +  +  + ]:        6280 :     if (!passesFilter(user, filter, nameFilter)) {
     712                 :          27 :       continue;
     713                 :             :     }
     714                 :             : 
     715                 :             :     // Built outside the list and added whole: an item made with the list as
     716                 :             :     // its parent is in it at once, and each setter below then reports a
     717                 :             :     // change for a row that has no user index yet.
     718                 :        6253 :     auto *item = new QListWidgetItem(buildUserText(user));
     719                 :        6253 :     applyUserStyling(item, user);
     720      [ +  +  + ]:        6348 :     item->setCheckState(user.enabled ? Qt::Checked : Qt::Unchecked);
     721                 :        6253 :     item->setData(Qt::UserRole, QVariant::fromValue(i));
     722                 :        6253 :     ui->listWidget->addItem(item);
     723                 :             :   }
     724                 :             :   // setSortingEnabled() only sets the flag; sortItems() sorts.
     725                 :          95 :   ui->listWidget->sortItems();
     726                 :          95 :   ui->listWidget->setSortingEnabled(true);
     727                 :          95 :   updateOkButton();
     728                 :          95 : }
     729                 :             : 
     730                 :        6280 : bool UsersDialog::passesFilter(const UserInfo &user, const QString &filter,
     731                 :             :                                const QRegularExpression &nameFilter) const {
     732   [ +  +  +  +  :        6294 :   if (!filter.isEmpty() && !nameFilter.match(user.name).hasMatch()) {
                +  +  + ]
     733                 :             :     return false;
     734                 :             :   }
     735                 :             :   // A ticked key is one the folder is encrypted to: it is shown whatever
     736                 :             :   // its state, or an expired or missing recipient stays in .gpg-id unseen and
     737                 :             :   // cannot be unticked. "Show unusable keys" is about keys to add. A line
     738                 :             :   // listed unticked without a lookup is shown too: OK would drop it unseen.
     739   [ +  +  +  +  :        6266 :   if (user.enabled || ui->checkBox->isChecked() ||
                   +  + ]
     740         [ +  + ]:          99 :       m_notLookedUp.contains(user.key_id)) {
     741                 :        6168 :     return true;
     742                 :             :   }
     743         [ +  + ]:          90 :   return user.isValid() && !isUserExpired(user);
     744                 :             : }
     745                 :             : 
     746                 :        6343 : auto UsersDialog::isUserExpired(const UserInfo &user) const -> bool {
     747         [ +  + ]:        6343 :   if (!m_cachedDateTimeValid) {
     748                 :          92 :     m_cachedCurrentDateTime = QDateTime::currentDateTime();
     749                 :          92 :     m_cachedDateTimeValid = true;
     750                 :             :   }
     751                 :             :   // gpg marks a key it already judged expired with validity 'e'.
     752   [ +  +  +  + ]:       12684 :   return user.validity == 'e' ||
     753         [ -  + ]:        6350 :          (user.expiry.isValid() && m_cachedCurrentDateTime > user.expiry);
     754                 :             : }
     755                 :             : 
     756                 :             : namespace {
     757                 :             : /**
     758                 :             :  * @brief Text cut to a length a list row can draw at once.
     759                 :             :  *
     760                 :             :  * A .gpg-id line no key answers to is shown as written, up to the 1 MiB the
     761                 :             :  * list may hold: Qt elided such a row on every paint in time quadratic in
     762                 :             :  * its tabs and script changes, and the dialog hung for minutes. No user ID
     763                 :             :  * or key ID is this long.
     764                 :             :  * @param text A user ID or key ID.
     765                 :             :  * @return The text, or its first 256 characters followed by an ellipsis;
     766                 :             :  *         a surrogate pair is never split.
     767                 :             :  */
     768                 :       12506 : auto shortened(const QString &text) -> QString {
     769                 :             :   constexpr qsizetype kMaxShown = 256;
     770         [ +  + ]:       12506 :   if (text.size() <= kMaxShown) {
     771                 :             :     return text;
     772                 :             :   }
     773                 :             :   qsizetype cut = kMaxShown;
     774         [ +  - ]:           1 :   if (text.at(cut - 1).isHighSurrogate()) {
     775                 :             :     --cut;
     776                 :             :   }
     777                 :           2 :   return text.left(cut) + QChar(0x2026);
     778                 :             : }
     779                 :             : } // namespace
     780                 :             : 
     781                 :        6253 : QString UsersDialog::buildUserText(const UserInfo &user) const {
     782                 :             :   // One line for the user ID: a line separator in it (gpg escapes only
     783                 :             :   // ASCII) drew a line that looked like the key's fingerprint.
     784                 :             :   // The key ID too: a recipient no key answers to is the .gpg-id line as
     785                 :             :   // written, which may hold the same separators.
     786                 :       12506 :   QString text = Util::displayable(shortened(user.name), false) + "\n" +
     787                 :       12506 :                  Util::displayable(shortened(user.key_id), false);
     788      [ +  +  + ]:        6253 :   if (user.created.isValid()) {
     789                 :         342 :     text += " " + tr("created") + " " +
     790                 :         513 :             QLocale::system().toString(user.created, QLocale::ShortFormat);
     791                 :             :   }
     792      [ +  +  + ]:        6253 :   if (user.expiry.isValid()) {
     793                 :          12 :     text += " " + tr("expires") + " " +
     794                 :          18 :             QLocale::system().toString(user.expiry, QLocale::ShortFormat);
     795                 :             :   }
     796                 :        6253 :   return text;
     797                 :             : }
     798                 :             : 
     799                 :        6253 : void UsersDialog::applyUserStyling(QListWidgetItem *item,
     800                 :             :                                    const UserInfo &user) const {
     801                 :        6253 :   const QString originalText = item->text();
     802                 :             :   // Status badge first: an own key can be expired too, and then the marker
     803                 :             :   // matters more than the "you can decrypt with this" colour.
     804                 :             :   bool badged = true;
     805                 :             :   // Expired before invalid: gpg gives an expired key validity 'e', which is
     806                 :             :   // not a valid one, and "expired" says what to do about it.
     807      [ +  +  + ]:        6253 :   if (isUserExpired(user)) {
     808                 :             :     // A lone dark-red foreground is unreadable on dark themes, and gpg
     809                 :             :     // refuses to encrypt to expired keys anyway.
     810                 :           6 :     item->setBackground(Qt::darkRed);
     811                 :           6 :     item->setForeground(Qt::white);
     812                 :          12 :     item->setText(tr("[EXPIRED] ") + originalText);
     813                 :             :   } else if (!user.isValid()) {
     814                 :        6085 :     item->setBackground(Qt::darkRed);
     815                 :        6085 :     item->setForeground(Qt::white);
     816                 :       12170 :     item->setText(tr("[INVALID] ") + originalText);
     817         [ +  + ]:         162 :   } else if (!user.fullyValid()) {
     818                 :           7 :     item->setBackground(Qt::darkYellow);
     819                 :           7 :     item->setForeground(Qt::white);
     820                 :          14 :     item->setText(tr("[PARTIAL] ") + originalText);
     821                 :             :   } else {
     822                 :         155 :     item->setText(originalText);
     823                 :             :     badged = false;
     824                 :             :   }
     825         [ +  + ]:        6253 :   if (user.have_secret) {
     826         [ +  - ]:           9 :     if (!badged) {
     827                 :          18 :       item->setForeground(QApplication::palette().color(QPalette::Link));
     828                 :             :     }
     829                 :           9 :     QFont font = item->font();
     830                 :             :     font.setBold(true);
     831                 :           9 :     item->setFont(font);
     832                 :           9 :   }
     833                 :        6253 : }
     834                 :             : 
     835                 :          14 : void UsersDialog::on_lineEdit_textChanged(const QString &filter) {
     836                 :          14 :   populateList(filter);
     837                 :          14 : }
     838                 :             : 
     839                 :          18 : void UsersDialog::on_checkBox_clicked() { populateList(ui->lineEdit->text()); }
     840                 :             : 
     841                 :           2 : void UsersDialog::selectImportedKey(const QString &importedKey) {
     842                 :             :   // The stored key_id, not the item text.
     843         [ +  - ]:           4 :   for (int i = 0; i < ui->listWidget->count(); ++i) {
     844                 :           4 :     QListWidgetItem *item = ui->listWidget->item(i);
     845                 :           4 :     bool ok = false;
     846   [ +  -  +  +  :           4 :     const int idx = item != nullptr ? item->data(Qt::UserRole).toInt(&ok) : -1;
                   -  - ]
     847   [ +  -  +  -  :           8 :     if (ok && idx >= 0 && idx < m_userList.size() &&
                   +  - ]
     848   [ +  -  +  + ]:           8 :         !m_userList[idx].key_id.isEmpty() &&
     849                 :           4 :         keyIdsMatch(m_userList[idx].key_id, importedKey)) {
     850                 :           2 :       ui->listWidget->setCurrentItem(item);
     851                 :           2 :       return;
     852                 :             :     }
     853                 :             :   }
     854                 :             : }
     855                 :             : 
     856                 :           3 : void UsersDialog::on_importKeyButton_clicked() {
     857                 :           3 :   ImportKeyDialog dialog(m_gpgExe, this);
     858      [ +  +  + ]:           3 :   if (dialog.exec() != QDialog::Accepted) {
     859                 :             :     return;
     860                 :             :   }
     861                 :             : 
     862                 :             :   // Non-empty after Accepted, but an empty id would make the endsWith()
     863                 :             :   // below match the first listed key.
     864                 :           2 :   const QString importedKey = dialog.importedKeyId();
     865         [ +  - ]:           2 :   if (importedKey.isEmpty()) {
     866                 :             :     return;
     867                 :             :   }
     868                 :             : 
     869                 :             :   // loadGpgKeys() rebuilds the key list from the keyring and drops every tick.
     870                 :             :   // Remember which recipients were selected (the .gpg-id list and the user's
     871                 :             :   // own ticks, including any "key not found" rows) and re-apply them after, so
     872                 :             :   // importing a key does not silently remove the other recipients.
     873                 :           2 :   QStringList selected;
     874         [ +  + ]:           4 :   for (const UserInfo &user : std::as_const(m_userList)) {
     875         [ +  - ]:           2 :     if (user.enabled) {
     876                 :           2 :       selected.append(user.key_id);
     877                 :             :     }
     878                 :             :   }
     879                 :             : 
     880      [ +  -  + ]:           2 :   if (!loadGpgKeys()) {
     881                 :             :     return;
     882                 :             :   }
     883                 :             : 
     884                 :             :   // Re-apply the remembered selection. Most saved identifiers are a key ID that
     885                 :             :   // is in the rebuilt list, so match those exactly first (no gpg lookup). An
     886                 :             :   // identifier that does not match a row is one that was listed as "key not
     887                 :             :   // found" - a short ID or email that gpg could not resolve, or whose key has
     888                 :             :   // just been imported and now shows under its fingerprint. Hand those to
     889                 :             :   // selectRecipients(), which resolves each against the refreshed keyring,
     890                 :             :   // ticks the matching row, and re-adds a "key not found" row for any that
     891                 :             :   // still does not resolve.
     892                 :           2 :   QStringList unresolved;
     893         [ +  + ]:           4 :   for (const QString &keyId : std::as_const(selected)) {
     894                 :             :     bool matched = false;
     895   [ +  +  +  + ]:           6 :     for (UserInfo &user : m_userList) {
     896         [ +  + ]:           4 :       if (user.key_id == keyId) {
     897                 :           2 :         user.enabled = true;
     898                 :             :         matched = true;
     899                 :             :       }
     900                 :             :     }
     901         [ -  + ]:           2 :     if (!matched) {
     902                 :             :       unresolved.append(keyId);
     903                 :             :     }
     904                 :             :   }
     905         [ -  + ]:           2 :   if (!unresolved.isEmpty()) {
     906                 :           0 :     selectRecipients(unresolved);
     907                 :             :   }
     908                 :             : 
     909                 :             :   // Clear the filter so the just-imported key is visible. setText("") still
     910                 :             :   // emits textChanged once, so don't double-populate.
     911                 :             :   {
     912                 :           2 :     const QSignalBlocker blocker(ui->lineEdit);
     913                 :           2 :     ui->lineEdit->clear();
     914                 :           2 :   }
     915                 :           2 :   populateList(QString());
     916                 :             : 
     917                 :           2 :   selectImportedKey(importedKey);
     918                 :           3 : }
        

Generated by: LCOV version 2.0-1