• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

IJHack / QtPass / 44098727190

17 Nov 2026 02:01PM UTC coverage: 96.408% (+0.04%) from 96.369%
44098727190

push

github

web-flow
Users dialog: name folders below it could not read; FAQ entry (#2250)

From the #2248 review: the note on folders below with their own
recipients left out folders the walk could not read, which may hold a
list of their own. They are now named too, as unknown.

FAQ: "I removed someone, but they can still read some passwords" covers
folders below with their own list (and how to find copies made by
earlier versions), hidden folders, which QtPass does not re-encrypt, and
copies elsewhere that no re-encryption takes back.

Signed-off-by: Anne Jan Brouwer <brouwer@annejan.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

24 of 25 new or added lines in 1 file covered. (96.0%)

3 existing lines in 1 file now uncovered.

8990 of 9325 relevant lines covered (96.41%)

757.47 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

98.21
/src/usersdialog.cpp
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 "qtpasssettings.h"
12
#include "ui_usersdialog.h"
13
#include "util.h"
14
#include "windowstatestore.h"
15
#include <QApplication>
16
#include <QDateTime>
17
#include <QDialogButtonBox>
18
#include <QDir>
19
#include <QFileInfo>
20
#include <QFont>
21
#include <QHash>
22
#include <QKeyEvent>
23
#include <QLabel>
24
#include <QLineEdit>
25
#include <QListWidget>
26
#include <QMessageBox>
27
#include <QPalette>
28
#include <QPushButton>
29
#include <QRegularExpression>
30
#include <QSet>
31
#include <QSignalBlocker>
32
#include <QWidget>
33
#include <algorithm>
34
#include <utility>
35

36
#include "qtpasslogging.h"
37
UsersDialog::UsersDialog(Pass *pass, const AppSettings &s, QString dir,
44 ✔
38
                         QWidget *parent)
44 ✔
39
    : UsersDialog(pass, s, std::move(dir), Preselect::FromList, parent) {}
88 ✔
40

41
UsersDialog::UsersDialog(Pass *pass, const AppSettings &s, QString dir,
47 ✔
42
                         Preselect preselect, QWidget *parent)
47 ✔
43
    : QDialog(parent), ui(new Ui::UsersDialog), m_pass(pass),
47 ✔
44
      m_passStore(s.passStore), m_gpgExe(s.gpgExecutable),
45
      m_dir(std::move(dir)), m_preselect(preselect) {
94 ✔
46
  Q_ASSERT(pass);
47
  ui->setupUi(this);
47 ✔
48

49
  restoreDialogState();
47 ✔
50
  if (!loadGpgKeys()) {
47 ✔
51
    connect(ui->buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
1 ✔
52
    return;
1 ✔
53
  }
54

55
  loadRecipients();
46 ✔
56
  showNestedLists();
46 ✔
57
  populateList();
46 ✔
58

59
  connectSignals();
46 ✔
60
}
×
61

62
void UsersDialog::connectSignals() {
46 ✔
63
  connect(ui->buttonBox, &QDialogButtonBox::accepted, this,
46 ✔
64
          &UsersDialog::accept);
46 ✔
65
  connect(ui->buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
46 ✔
66
  connect(ui->listWidget, &QListWidget::itemChanged, this,
46 ✔
67
          &UsersDialog::itemChange);
92 ✔
68
  // importKeyButton is wired via Qt's automatic on_<name>_<signal> mechanism
69
  // already triggered by setupUi().
70

71
  ui->lineEdit->setClearButtonEnabled(true);
46 ✔
72
}
46 ✔
73

74
void UsersDialog::restoreDialogState() {
47 ✔
75
  WindowStateStore::attach(*this, QStringLiteral("usersDialog"));
94 ✔
76
}
47 ✔
77

78
auto UsersDialog::loadGpgKeys() -> bool {
48 ✔
79
  QList<UserInfo> users = m_pass->listKeys();
48 ✔
80
  if (users.isEmpty()) {
48 ✔
81
    QMessageBox::critical(parentWidget(), tr("Keylist missing"),
3 ✔
82
                          tr("Could not fetch list of available GPG keys"));
×
83
    reject();
1 ✔
84
    return false;
85
  }
86

87
  markSecretKeys(users);
47 ✔
88

89
  m_userList = users;
90
  return true;
47 ✔
91
}
92

93
void UsersDialog::markSecretKeys(QList<UserInfo> &users) {
47 ✔
94
  QList<UserInfo> secret_keys = m_pass->listKeys("", true);
94 ✔
95
  QSet<QString> secretKeyIds;
96
  for (const UserInfo &sec : secret_keys) {
52 ✔
97
    secretKeyIds.insert(sec.key_id);
5 ✔
98
  }
99
  for (auto &user : users) {
141 ✔
100
    if (secretKeyIds.contains(user.key_id)) {
94 ✔
101
      user.have_secret = true;
5 ✔
102
    }
103
  }
104
}
47 ✔
105

106
void UsersDialog::showRecipientWarning(const QString &text,
10 ✔
107
                                       const QString &name) {
108
  // Plain text before the text is set: it can quote the store's recipient
109
  // list, which as rich text could make Qt load a file (<img src=...>).
110
  auto *banner = new QLabel(this);
10 ✔
111
  banner->setTextFormat(Qt::PlainText);
10 ✔
112
  banner->setText(text);
10 ✔
113
  banner->setObjectName(name);
10 ✔
114
  banner->setWordWrap(true);
10 ✔
115
  // Palette, not a stylesheet colour, so it reads on dark themes too; red as
116
  // ProcessOutputPanel paints error lines.
117
  QFont bold = banner->font();
10 ✔
118
  bold.setBold(true);
119
  banner->setFont(bold);
10 ✔
120
  QPalette palette = banner->palette();
10 ✔
121
  palette.setColor(QPalette::WindowText, QColor(Qt::red));
10 ✔
122
  banner->setPalette(palette);
10 ✔
123
  banner->setContentsMargins(4, 4, 4, 4);
10 ✔
124
  ui->verticalLayout->insertWidget(1, banner);
10 ✔
125
}
10 ✔
126

127
void UsersDialog::showNestedLists() {
46 ✔
128
  // The walk re-encryption takes: hidden folders and links are not entered.
129
  const QString dir = QDir::cleanPath(m_dir);
46 ✔
130
  if (!QFileInfo(dir).isDir()) {
46 ✔
131
    return;
132
  }
133
  QStringList unlisted;
46 ✔
134
  const QStringList lists = Util::regularFilesUnder(
138 ✔
135
      dir, {QStringLiteral(".gpg-id")}, nullptr, true, &unlisted);
92 ✔
136
  const auto relative = [&dir](const QString &folder) {
4 ✔
137
    return QDir::toNativeSeparators(QDir(dir).relativeFilePath(folder));
8 ✔
138
  };
46 ✔
139
  QStringList nested;
46 ✔
140
  for (const QString &list : lists) {
77 ✔
141
    const QString folder = QFileInfo(list).path();
31 ✔
142
    if (QDir::cleanPath(folder) != dir) {
62 ✔
143
      nested << relative(folder);
6 ✔
144
    }
145
  }
146
  QStringList unread;
46 ✔
147
  for (const QString &folder : std::as_const(unlisted)) {
47 ✔
148
    unread << relative(folder);
2 ✔
149
  }
150
  constexpr qsizetype kMaxNamed = 5;
151
  const auto named = [](const QStringList &folders) {
3 ✔
152
    QString names = folders.mid(0, kMaxNamed).join(QStringLiteral(", "));
6 ✔
153
    if (folders.size() > kMaxNamed) {
3 ✔
NEW
154
      names += QStringLiteral(", …");
×
155
    }
156
    return names;
3 ✔
157
  };
158
  QStringList text;
46 ✔
159
  if (!nested.isEmpty()) {
46 ✔
160
    //: %1 lists folders, such as "work, work/bank". Shown when changing the
161
    //: recipients of a folder that has folders with their own list below it.
162
    text << tr("%n folder(s) below this one have their own recipients, which "
2 ✔
163
               "saving here does not change: %1",
164
               nullptr, static_cast<int>(nested.size()))
165
                .arg(named(nested));
4 ✔
166
  }
167
  if (!unread.isEmpty()) {
46 ✔
168
    //: %1 lists folders, such as "work, work/bank", that QtPass has no
169
    //: permission to read.
170
    text << tr("%n folder(s) below this one could not be read, so whether "
1 ✔
171
               "they have their own recipients is unknown: %1",
172
               nullptr, static_cast<int>(unread.size()))
173
                .arg(named(unread));
2 ✔
174
  }
175
  if (!text.isEmpty()) {
46 ✔
176
    showRecipientWarning(text.join(QLatin1Char('\n')),
6 ✔
177
                         QStringLiteral("nestedListsWarning"));
3 ✔
178
  }
179
}
180

181
namespace {
182

183
/// A key ID as written anywhere: without a 0x prefix, upper case.
184
auto normalisedKeyId(const QString &id) -> QString {
86 ✔
185
  const QString trimmed = id.trimmed();
186
  return (trimmed.startsWith(QLatin1String("0x"), Qt::CaseInsensitive)
86 ✔
187
              ? trimmed.mid(2)
172 ✔
188
              : trimmed)
189
      .toUpper();
86 ✔
190
}
191

192
/// Whether @p recipient, as a .gpg-id lists it, names @p key the way gpg's
193
/// -r resolves it: a key ID in any length gpg accepts (the key carries its
194
/// fingerprint, the list may carry a long or short ID, a suffix of it, or
195
/// the fingerprint; eight characters is the shortest), or else a name,
196
/// matched case-insensitively as a substring of the UID after gpg's
197
/// "=", "<...>", "@" and "*" markers.
198
auto answersTo(const UserInfo &key, const QString &recipient) -> bool {
48 ✔
199
  static const QRegularExpression hexId(
200
      QStringLiteral("^(0x)?[0-9A-Fa-f]{8,}$"));
51 ✔
201
  if (hexId.match(recipient.trimmed()).hasMatch()) {
96 ✔
202
    const QString id = normalisedKeyId(recipient);
43 ✔
203
    const QString keyId = normalisedKeyId(key.key_id);
43 ✔
204
    return keyId.endsWith(id) || (keyId.size() >= 8 && id.endsWith(keyId));
43 ✔
205
  }
206
  QString term = recipient.trimmed();
207
  if (term.startsWith(u'=') || term.startsWith(u'@') || term.startsWith(u'*')) {
5 ✔
208
    term.remove(0, 1);
×
209
  } else if (term.startsWith(u'<') && term.endsWith(u'>')) {
5 ✔
210
    term = term.mid(1, term.size() - 2);
2 ✔
211
  }
212
  return !term.isEmpty() && key.name.contains(term, Qt::CaseInsensitive);
5 ✔
213
}
214

215
} // namespace
216

217
void UsersDialog::selectRecipients(const QStringList &recipients) {
25 ✔
218
  // Each per-line gpg lookup is a blocking call on the dialog's way up, so a
219
  // store with many keys missing from the keyring (a fresh clone, a team
220
  // store) is capped at this many across both the fallback below and the
221
  // missing-key check; the rest resolve by the batched call or stay unchecked.
222
  constexpr int kMaxLookups = 10;
223
  int lookups = 0;
224
  // Remembers the per-line lookups the fallback already ran, so the
225
  // missing-key loop below reuses them instead of asking gpg a second time.
226
  QHash<QString, bool> perLineHasKey;
25 ✔
227

228
  // One gpg call resolves every recipient, by key ID or by email/UID.
229
  QList<UserInfo> resolved = m_pass->listKeys(recipients);
50 ✔
230
  if (resolved.isEmpty() && recipients.size() > 1) {
25 ✔
231
    // One line gpg cannot read as a key search ("0x", a fingerprint one
232
    // digit short) aborts that whole call with exit code 2, so nothing is
233
    // listed for the other lines, whose keys are in the keyring all the same.
234
    // Asked for one by one they still resolve; only the unreadable line is
235
    // reported missing by the loop below, as an unknown key already is.
236
    for (const QString &recipient : recipients) {
25 ✔
237
      if (lookups++ >= kMaxLookups) {
22 ✔
238
        break;
239
      }
240
      const QList<UserInfo> keys = m_pass->listKeys(recipient);
21 ✔
241
      perLineHasKey.insert(recipient, !keys.isEmpty());
21 ✔
242
      resolved += keys;
243
    }
244
  }
245
  for (UserInfo &user : m_userList) {
75 ✔
246
    if (std::any_of(resolved.cbegin(), resolved.cend(),
50 ✔
247
                    [&user](const UserInfo &key) {
248
                      return key.key_id == user.key_id;
63 ✔
249
                    })) {
250
      user.enabled = true;
36 ✔
251
    }
252
  }
253
  // Only what gpg itself cannot find is reported missing. The fallback's
254
  // per-line answer, when it has one, is gpg's own verdict for that line and
255
  // decides it outright. Otherwise the heuristic match is a fast path (a
256
  // secondary UID or a subkey ID resolves in gpg without showing in what it
257
  // lists), and a per-line gpg call settles anything it does not catch. Taking
258
  // the cached answer first also keeps a genuinely unreadable line ("0x")
259
  // reported missing even when a resolved key's UID happens to contain it, so
260
  // the heuristic answersTo() would otherwise match.
261
  for (const QString &recipient : recipients) {
82 ✔
262
    bool found = false;
263
    const auto cached = perLineHasKey.constFind(recipient);
57 ✔
264
    if (cached != perLineHasKey.constEnd()) {
265
      found = cached.value();
21 ✔
266
    } else {
267
      found = std::any_of(resolved.cbegin(), resolved.cend(),
36 ✔
268
                          [&recipient](const UserInfo &key) {
269
                            return answersTo(key, recipient);
48 ✔
270
                          });
271
      if (!found && lookups++ < kMaxLookups) {
36 ✔
272
        found = !m_pass->listKeys(recipient).isEmpty();
8 ✔
273
      }
274
    }
275
    if (!found) {
57 ✔
276
      UserInfo missing;
26 ✔
277
      missing.enabled = true;
26 ✔
278
      missing.key_id = recipient;
26 ✔
279
      missing.name = " ?? " + tr("Key not found in keyring");
52 ✔
280
      m_userList.append(missing);
281
    }
26 ✔
282
  }
283
}
25 ✔
284

285
void UsersDialog::loadRecipients() {
46 ✔
286
  // A store that had no list when it was chosen (a new profile): a list
287
  // that appeared since is nobody's choice, and was read under the active
288
  // backend's signing policy, not the new profile's.
289
  if (m_preselect == Preselect::Nothing) {
46 ✔
290
    return;
3 ✔
291
  }
292
  // Through the backend: with a signing key only a verified list may be
293
  // preselected, since OK signs whatever is selected.
294
  const Pass::RecipientsForEditing loaded =
295
      m_pass->recipientsForEditing(m_dir, m_passStore);
43 ✔
296
  if (!loaded.warning.isEmpty()) {
43 ✔
297
    showRecipientWarning(loaded.warning);
14 ✔
298
  }
299
  // A folder without .gpg-id (new store, new profile) has no recipients yet;
300
  // listKeys() with no filter would return the whole keyring, preselected.
301
  if (loaded.state != Pass::RecipientsForEditing::State::Rejected &&
43 ✔
302
      !loaded.recipients.isEmpty()) {
303
    selectRecipients(loaded.recipients);
25 ✔
304
  }
305
}
306

307
UsersDialog::~UsersDialog() = default;
94 ✔
308

309
void UsersDialog::accept() {
9 ✔
310
  if (!hasSelection()) {
9 ✔
311
    // Nothing to encrypt to: an empty .gpg-id would make every insert fail
312
    // and the wizard never offers this dialog again once the file exists.
313
    return;
314
  }
315
  if (m_initOnAccept) {
7 ✔
316
    m_pass->Init(m_dir, m_userList);
8 ✔
317
  }
318

319
  QDialog::accept();
7 ✔
320
}
321

322
auto UsersDialog::hasSelection() const -> bool {
139 ✔
323
  return std::any_of(m_userList.cbegin(), m_userList.cend(),
324
                     [](const UserInfo &user) { return user.enabled; });
211 ✔
325
}
326

327
void UsersDialog::updateOkButton() {
127 ✔
328
  if (auto *ok = ui->buttonBox->button(QDialogButtonBox::Ok)) {
127 ✔
329
    ok->setEnabled(hasSelection());
127 ✔
330
  }
331
}
127 ✔
332

333
void UsersDialog::keyPressEvent(QKeyEvent *event) {
1 ✔
334
  switch (event->key()) {
1 ✔
335
  case Qt::Key_Escape:
1 ✔
336
    ui->lineEdit->clear();
1 ✔
337
    break;
1 ✔
338
  default:
339
    break;
340
  }
341
}
1 ✔
342

343
void UsersDialog::itemChange(QListWidgetItem *item) {
137 ✔
344
  if (!item) {
137 ✔
345
    return;
80 ✔
346
  }
347
  bool ok = false;
137 ✔
348
  const int index = item->data(Qt::UserRole).toInt(&ok);
137 ✔
349
  if (!ok) {
137 ✔
350
    qCWarning(lcQtPass)
158 ✔
351
        << "UsersDialog::itemChange: invalid user index data for item";
79 ✔
352
    return;
79 ✔
353
  }
354
  if (index < 0 || index >= m_userList.size()) {
58 ✔
355
    qCWarning(lcQtPass) << "UsersDialog::itemChange: user index out of range:"
2 ✔
356
                        << index << "valid range is [0,"
1 ✔
357
                        << (m_userList.size() - 1) << "]";
1 ✔
358
    return;
1 ✔
359
  }
360
  m_userList[index].enabled = item->checkState() == Qt::Checked;
57 ✔
361
  updateOkButton();
57 ✔
362
}
363

364
void UsersDialog::populateList(const QString &filter) {
70 ✔
365
  // Invalidate cached datetime so expiry checks use fresh current time
366
  m_cachedDateTimeValid = false;
70 ✔
367

368
  QString patternString = "*" + filter + "*";
70 ✔
369
  if (m_cachedPatternString != patternString) {
70 ✔
370
    // A user ID is not a path: "*" and "?" must match a "/" as well, or a
371
    // key named "ACME A/S" or "(dev/ops)" drops out of the search and stays
372
    // ticked unseen while the listed rows are unticked.
373
    QRegularExpression re(
374
        QRegularExpression::wildcardToRegularExpression(
120 ✔
375
            patternString, QRegularExpression::NonPathWildcardConversion),
376
        QRegularExpression::CaseInsensitiveOption);
60 ✔
377
    if (re.isValid()) {
60 ✔
378
      m_cachedNameFilter = re;
60 ✔
379
      m_cachedPatternString = patternString;
60 ✔
380
    }
381
  }
60 ✔
382
  const QRegularExpression &nameFilter = m_cachedNameFilter;
70 ✔
383
  ui->listWidget->clear();
70 ✔
384

385
  for (int i = 0; i < m_userList.size(); ++i) {
251 ✔
386
    const auto &user = m_userList.at(i);
387
    if (!passesFilter(user, filter, nameFilter)) {
181 ✔
388
      continue;
26 ✔
389
    }
390

391
    auto *item = new QListWidgetItem(buildUserText(user), ui->listWidget);
155 ✔
392
    applyUserStyling(item, user);
155 ✔
393
    item->setCheckState(user.enabled ? Qt::Checked : Qt::Unchecked);
225 ✔
394
    item->setData(Qt::UserRole, QVariant::fromValue(i));
155 ✔
395
    ui->listWidget->addItem(item);
155 ✔
396
  }
397
  updateOkButton();
70 ✔
398
}
70 ✔
399

400
bool UsersDialog::passesFilter(const UserInfo &user, const QString &filter,
181 ✔
401
                               const QRegularExpression &nameFilter) const {
402
  if (!filter.isEmpty() && !nameFilter.match(user.name).hasMatch()) {
194 ✔
403
    return false;
404
  }
405
  // A ticked key is one the folder is encrypted to: it is shown whatever
406
  // its state, or an expired or missing recipient stays in .gpg-id unseen and
407
  // cannot be unticked. "Show unusable keys" is about keys to add.
408
  if (user.enabled || ui->checkBox->isChecked()) {
168 ✔
409
    return true;
94 ✔
410
  }
411
  return user.isValid() && !isUserExpired(user);
66 ✔
412
}
413

414
auto UsersDialog::isUserExpired(const UserInfo &user) const -> bool {
221 ✔
415
  if (!m_cachedDateTimeValid) {
221 ✔
416
    m_cachedCurrentDateTime = QDateTime::currentDateTime();
68 ✔
417
    m_cachedDateTimeValid = true;
68 ✔
418
  }
419
  // gpg marks a key it already judged expired with validity 'e'.
420
  return user.validity == 'e' ||
440 ✔
421
         (user.expiry.isValid() && m_cachedCurrentDateTime > user.expiry);
228 ✔
422
}
423

424
QString UsersDialog::buildUserText(const UserInfo &user) const {
155 ✔
425
  QString text = user.name + "\n" + user.key_id;
155 ✔
426
  if (user.created.isValid()) {
155 ✔
427
    text += " " + tr("created") + " " +
256 ✔
428
            QLocale::system().toString(user.created, QLocale::ShortFormat);
384 ✔
429
  }
430
  if (user.expiry.isValid()) {
155 ✔
431
    text += " " + tr("expires") + " " +
12 ✔
432
            QLocale::system().toString(user.expiry, QLocale::ShortFormat);
18 ✔
433
  }
434
  return text;
155 ✔
435
}
436

437
void UsersDialog::applyUserStyling(QListWidgetItem *item,
155 ✔
438
                                   const UserInfo &user) const {
439
  const QString originalText = item->text();
155 ✔
440
  // Status badge first: an own key can be expired too, and then the marker
441
  // matters more than the "you can decrypt with this" colour.
442
  bool badged = true;
443
  // Expired before invalid: gpg gives an expired key validity 'e', which is
444
  // not a valid one, and "expired" says what to do about it.
445
  if (isUserExpired(user)) {
155 ✔
446
    // A lone dark-red foreground is unreadable on dark themes, and gpg
447
    // refuses to encrypt to expired keys anyway.
448
    item->setBackground(Qt::darkRed);
6 ✔
449
    item->setForeground(Qt::white);
6 ✔
450
    item->setText(tr("[EXPIRED] ") + originalText);
12 ✔
451
  } else if (!user.isValid()) {
452
    item->setBackground(Qt::darkRed);
30 ✔
453
    item->setForeground(Qt::white);
30 ✔
454
    item->setText(tr("[INVALID] ") + originalText);
60 ✔
455
  } else if (!user.fullyValid()) {
119 ✔
456
    item->setBackground(Qt::darkYellow);
7 ✔
457
    item->setForeground(Qt::white);
7 ✔
458
    item->setText(tr("[PARTIAL] ") + originalText);
14 ✔
459
  } else {
460
    item->setText(originalText);
112 ✔
461
    badged = false;
462
  }
463
  if (user.have_secret) {
155 ✔
464
    if (!badged) {
7 ✔
465
      item->setForeground(QApplication::palette().color(QPalette::Link));
14 ✔
466
    }
467
    QFont font = item->font();
7 ✔
468
    font.setBold(true);
469
    item->setFont(font);
7 ✔
470
  }
7 ✔
471
}
155 ✔
472

473
void UsersDialog::on_lineEdit_textChanged(const QString &filter) {
13 ✔
474
  populateList(filter);
13 ✔
475
}
13 ✔
476

477
void UsersDialog::on_checkBox_clicked() { populateList(ui->lineEdit->text()); }
20 ✔
478

479
void UsersDialog::selectImportedKey(const QString &importedKey) {
1 ✔
480
  // Suffixes shorter than 16 characters would give false positives.
481
  const auto sameKey = [&importedKey](const QString &keyId) {
2 ✔
482
    return (keyId.length() >= 16 &&
2 ✔
483
            importedKey.endsWith(keyId, Qt::CaseInsensitive)) ||
3 ✔
484
           (importedKey.length() >= 16 &&
2 ✔
485
            keyId.endsWith(importedKey, Qt::CaseInsensitive));
1 ✔
486
  };
1 ✔
487
  // The stored key_id, not the item text.
488
  for (int i = 0; i < ui->listWidget->count(); ++i) {
2 ✔
489
    QListWidgetItem *item = ui->listWidget->item(i);
2 ✔
490
    bool ok = false;
2 ✔
491
    const int idx = item != nullptr ? item->data(Qt::UserRole).toInt(&ok) : -1;
2 ✔
492
    if (ok && idx >= 0 && idx < m_userList.size() &&
4 ✔
493
        !m_userList[idx].key_id.isEmpty() && sameKey(m_userList[idx].key_id)) {
4 ✔
494
      ui->listWidget->setCurrentItem(item);
1 ✔
495
      return;
1 ✔
496
    }
497
  }
498
}
499

500
void UsersDialog::on_importKeyButton_clicked() {
2 ✔
501
  ImportKeyDialog dialog(m_gpgExe, this);
2 ✔
502
  if (dialog.exec() != QDialog::Accepted) {
2 ✔
503
    return;
504
  }
505

506
  // Non-empty after Accepted, but an empty id would make the endsWith()
507
  // below match the first listed key.
508
  const QString importedKey = dialog.importedKeyId();
1 ✔
509
  if (importedKey.isEmpty()) {
1 ✔
510
    return;
511
  }
512

513
  // loadGpgKeys() rebuilds the key list from the keyring and drops every tick.
514
  // Remember which recipients were selected (the .gpg-id list and the user's
515
  // own ticks, including any "key not found" rows) and re-apply them after, so
516
  // importing a key does not silently remove the other recipients.
517
  QStringList selected;
1 ✔
518
  for (const UserInfo &user : std::as_const(m_userList)) {
2 ✔
519
    if (user.enabled) {
1 ✔
520
      selected.append(user.key_id);
1 ✔
521
    }
522
  }
523

524
  if (!loadGpgKeys()) {
1 ✔
525
    return;
526
  }
527

528
  // Re-apply the remembered selection. Most saved identifiers are a key ID that
529
  // is in the rebuilt list, so match those exactly first (no gpg lookup). An
530
  // identifier that does not match a row is one that was listed as "key not
531
  // found" - a short ID or email that gpg could not resolve, or whose key has
532
  // just been imported and now shows under its fingerprint. Hand those to
533
  // selectRecipients(), which resolves each against the refreshed keyring,
534
  // ticks the matching row, and re-adds a "key not found" row for any that
535
  // still does not resolve.
536
  QStringList unresolved;
1 ✔
537
  for (const QString &keyId : std::as_const(selected)) {
2 ✔
538
    bool matched = false;
539
    for (UserInfo &user : m_userList) {
3 ✔
540
      if (user.key_id == keyId) {
2 ✔
541
        user.enabled = true;
1 ✔
542
        matched = true;
543
      }
544
    }
545
    if (!matched) {
1 ✔
546
      unresolved.append(keyId);
547
    }
548
  }
549
  if (!unresolved.isEmpty()) {
1 ✔
550
    selectRecipients(unresolved);
×
551
  }
552

553
  // Clear the filter so the just-imported key is visible. setText("") still
554
  // emits textChanged once, so don't double-populate.
555
  {
556
    const QSignalBlocker blocker(ui->lineEdit);
1 ✔
557
    ui->lineEdit->clear();
1 ✔
558
  }
1 ✔
559
  populateList(QString());
1 ✔
560

561
  selectImportedKey(importedKey);
1 ✔
562
}
2 ✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc