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

IJHack / QtPass / 46165298070

28 Nov 2026 04:27PM UTC coverage: 94.471% (+0.03%) from 94.442%
46165298070

push

github

web-flow
Refuse a recipient key that another key also holds (#2383)

gpg resolves a .gpg-id fingerprint or key ID among primary keys and
subkeys, and anyone can bind another person's public key to their own
as a subkey. After the user imported such an update of a colleague's
key, every entry saved or re-encrypted for the person the line names
was encrypted to the colleague instead, silently, with no access to
the store needed.

Pass::keyLinesHeldTwice() lists the keyring once, in the store's
environment, and finds every key ID or fingerprint line (grouped with
spaces too) that more than one key block holds. Such a line is
refused, naming both keys:

- native backend: Insert(), Init() and each folder of a re-encryption
  run;
- pass backend: insert, init and move/copy, right before pass runs and
  including every folder's own list below that pass re-encrypts to;
- the Users dialog keeps such a line as written, with a warning, and
  does not probe or search it;
- "Export my public key" refuses, and exports in the store's keyring.

A gpg that starts but cannot list its keyring refuses too; one that
does not start fails as before. Each check runs after the existing
refusals. Lost convenience: such a folder cannot be saved to until the
key that claims someone else's is deleted.

Tests: the listing parser (fingerprints, key IDs, "!", grouped lines,
v5 naming); ImitatePass refuses Insert() and re-encryption with nothing
encrypted, and a keyring that cannot be listed; RealPass refuses insert
and an init with a child list held twice (also past a decoy x.gpg
folder); the Users dialog keeps the line; export refuses. Each guard
was reverted once and its test failed.

Scan finding ANT-2026-ZQIJE21W.

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

164 of 170 new or added lines in 6 files covered. (96.47%)

10764 of 11394 relevant lines covered (94.47%)

24513.83 hits per line

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

95.25
/src/mainwindow.cpp
1
// SPDX-FileCopyrightText: 2014 Anne Jan Brouwer
2
// SPDX-License-Identifier: GPL-3.0-or-later
3
/**
4
 * @file
5
 * @brief Implements MainWindow; the backend signal wiring lives in
6
 *        connectBackends() and connectPassSignals(), the decrypted-entry
7
 *        rendering in passShowHandler().
8
 */
9
#include "mainwindow.h"
10

11
#include "qtpasslogging.h"
12

13
#include "configdialog.h"
14
#include "enums.h"
15
#include "executor.h"
16
#include "exportpublickeydialog.h"
17
#include "filecontent.h"
18
#include "firstrunwizard.h"
19
#include "menubarpeek.h"
20
#include "nativegrep.h"
21
#include "passworddialog.h"
22
#include "passworddisplaypanel.h"
23
#include "pathvalidator.h"
24
#include "plainmessagebox.h"
25
#include "processoutputpanel.h"
26
#include "qpushbuttonasqrcode.h"
27
#include "qpushbuttonshowpassword.h"
28
#include "qpushbuttonwithclipboard.h"
29
#include "qtpass.h"
30
#include "qtpasssettings.h"
31
#include "templateio.h"
32
#include "totp.h"
33
#include "trayicon.h"
34
#include "ui_mainwindow.h"
35
#include "usersdialog.h"
36
#include "util.h"
37
#include "windowstatestore.h"
38
#include <QApplication>
39
#include <QCloseEvent>
40
#include <QDate>
41
#include <QDesktopServices>
42
#include <QDialog>
43
#include <QDockWidget>
44
#include <QFileInfo>
45
#include <QFileSystemModel>
46
#include <QHBoxLayout>
47
#include <QInputDialog>
48
#include <QLabel>
49
#include <QLineEdit>
50
#include <QMenu>
51
#include <QMenuBar>
52
#include <QMessageBox>
53
#include <QProgressDialog>
54
#include <QPushButton>
55
#include <QScrollBar>
56
#include <QShortcut>
57
#include <QTextBlock>
58
#include <QTextCharFormat>
59
#include <QTextCursor>
60
#include <QTextDocument>
61
#include <QTextEdit>
62
#include <QTextStream>
63
#include <QTimer>
64
#include <QTreeWidget>
65
#include <QUrl>
66
#include <algorithm>
67
#include <array>
68
#include <utility>
69

70
MainWindow::MainWindow(const QString &searchText, QWidget *parent)
200 ✔
71
    : QMainWindow(parent), ui(new Ui::MainWindow) {
200 ✔
72
#ifdef __APPLE__
73
  // extra treatment for mac os
74
  // see https://doc.qt.io/qt-6/qkeysequence.html#qt_set_sequence_auto_mnemonic
75
  qt_set_sequence_auto_mnemonic(true);
76
#endif
77
  ui->setupUi(this);
200 ✔
78

79
  m_qtPass = new QtPass(this);
200 ✔
80
  restoreWindow();
200 ✔
81
  connectBackends();
200 ✔
82

83
  // Every Copy binding, not only the first (Ctrl+C): Ctrl+Insert and F16
84
  // otherwise reached the views' own copy, which put decrypted text on the
85
  // clipboard bare, without the secret hint or the autoclear.
86
  const QList<QKeySequence> copyKeys =
87
      QKeySequence::keyBindings(QKeySequence::StandardKey::Copy);
200 ✔
88
  for (const QKeySequence &keys : copyKeys) {
600 ✔
89
    new QShortcut(keys, this, this, &MainWindow::copySelectionOrPassword);
400 ✔
90
  }
91

92
  m_tree = new StoreTree(ui->treeView, this);
200 ✔
93
  m_tree->setStore(QtPassSettings::getPassStore(Util::findPasswordStore()));
200 ✔
94
  m_tree->setPass(QtPassSettings::getPass());
200 ✔
95
  connect(ui->treeView, &QWidget::customContextMenuRequested, this,
200 ✔
96
          &MainWindow::showContextMenu);
200 ✔
97
  connect(ui->treeView, &DeselectableTreeView::emptyClicked, this,
200 ✔
98
          &MainWindow::deselect);
200 ✔
99

100
  initTextBrowser();
200 ✔
101

102
  updateProfileBox();
200 ✔
103

104
  initDisplayPanel();
200 ✔
105

106
  QtPassSettings::getPass()->updateEnv();
200 ✔
107

108
  // Install the search-box key filter once, not on every setUiElementsEnabled
109
  // call.
110
  ui->lineEdit->installEventFilter(this);
200 ✔
111
  // Both live in Breeze's "tools area" and get its header palette; see the
112
  // PaletteChange branch in eventFilter().
113
  ui->toolBar->installEventFilter(this);
200 ✔
114
  menuBar()->installEventFilter(this);
200 ✔
115

116
  initTimers();
200 ✔
117

118
  initToolBarButtons();
200 ✔
119
  initStatusBar();
200 ✔
120
  initProcessOutput();
200 ✔
121

122
  ui->lineEdit->setClearButtonEnabled(true);
200 ✔
123
  updateGrepButtonVisibility();
200 ✔
124

125
  setUiElementsEnabled(true);
200 ✔
126

127
  // No QApplication::quit() here: before exec() it is a documented no-op.
128
  // main() checks initSucceeded() and exits before show() instead.
129
  m_qtPass->init();
200 ✔
130
  // OK is not gated on Util::configIsValid(): an accepted configuration can
131
  // still lack a .gpg-id, so ask again; only a cancel ends the loop.
132
  while (!Util::configIsValid(QtPassSettings::load())) {
201 ✔
133
    if (!config()) {
2 ✔
134
      return;
135
    }
136
  }
137
  // Set up, with or without the wizard (a fresh install can find a store
138
  // that already works): a later run of the wizard keeps the saved backend
139
  // and Git choices. A cancelled first run returned above and keeps it.
140
  QtPassSettings::getInstance()->remove(SettingsConstants::firstRunPending);
199 ✔
141
  m_freshStart = false;
199 ✔
142
  m_initSucceeded = true;
199 ✔
143

144
  // Searched as qtpass(1) promises, once the window and its tree are up:
145
  // filtered at once and an entry named exactly so opened. Setting the
146
  // text here left it to the search timer, which only highlights. Queued
147
  // only now: from before the configuration loop, a wizard's nested event
148
  // loop ran it while no store was set yet.
149
  if (!searchText.isEmpty()) {
199 ✔
150
    QTimer::singleShot(0, this,
151
                       [this, searchText] { applySearchText(searchText); });
×
152
  }
153

154
  // Initial focus is set in showEvent(): a 10 ms QTimer here could fire
155
  // before the window was realised (queued ActivationChange, nested exec() in
156
  // init()) and selectAll() segfaulted inside Qt (#1187, #1188).
157
}
×
158

159
void MainWindow::connectBackends() {
200 ✔
160
  connect(m_qtPass, &QtPass::outputReady, this,
200 ✔
161
          [this](const QString &html) { flashText(html, false, true); });
241 ✔
162
  connect(m_qtPass, &QtPass::operationFinished, this,
200 ✔
163
          [this]() { setUiElementsEnabled(true); });
263 ✔
164
  connect(m_qtPass, &QtPass::statusMessage, this,
200 ✔
165
          &MainWindow::showStatusMessage);
200 ✔
166
  connect(m_qtPass, &QtPass::pushRequested, this, &MainWindow::onAutoPush);
200 ✔
167
  // With automatic push, the push is queued first and the refresh would start
168
  // as soon as it ends, emptying the browser before a failed push's error was
169
  // painted. So the refresh waits for the push (see connectPassSignals()). It
170
  // claims the panel now, as its decrypt would: whatever drops a pending
171
  // decrypt (another entry, a search, Escape, Edit, an error) drops it too.
172
  connect(m_qtPass, &QtPass::entryInserted, this, [this]() {
200 ✔
173
    const QModelIndex index = getCurrentTreeViewIndex();
11 ✔
174
    const QString file = getFile(index, true);
11 ✔
175
    Pass *pass = QtPassSettings::getPass();
11 ✔
176
    // Only the entry the save wrote is shown again, when it is the selected
177
    // one. After Add, or a save that reports once another row is selected,
178
    // the selected row is another entry: showing it decrypted it once more
179
    // and, with "Always copy", put its password on the clipboard.
180
    if (const QString saved = pass->reportedInsert();
11 ✔
181
        !saved.isEmpty() &&
14 ✔
182
        QDir::cleanPath(saved) != QDir::cleanPath(getFile(index, false))) {
20 ✔
183
      return;
184
    }
185
    if (!file.isEmpty() && pass->isPushing()) {
20 ✔
186
      m_refreshAfterPush = file;
8 ✔
187
      m_refreshAfterPushOwner = pass;
8 ✔
188
      m_shownFile = file;
8 ✔
189
      return;
8 ✔
190
    }
191
    on_treeView_clicked(index);
2 ✔
192
  });
193
  connect(&m_qtPass->clipboard(), &ClipboardManager::statusMessage, this,
200 ✔
194
          [this](const QString &message) { showStatusMessage(message); });
223 ✔
195
  // Both backends: the active one can change through the configuration
196
  // dialog without a restart.
197
  connectPassSignals(QtPassSettings::getRealPass());
200 ✔
198
  connectPassSignals(QtPassSettings::getImitatePass());
200 ✔
199
  ImitatePass *ipass = QtPassSettings::getImitatePass();
200 ✔
200
  connect(ipass, &ImitatePass::startReencryptPath, this,
200 ✔
201
          &MainWindow::startReencryptPath);
200 ✔
202
  connect(ipass, &ImitatePass::reencryptProgress, this,
200 ✔
203
          &MainWindow::reencryptProgress);
200 ✔
204
  connect(ipass, &ImitatePass::endReencryptPath, this,
200 ✔
205
          &MainWindow::endReencryptPath);
200 ✔
206
  connect(ipass, &ImitatePass::unexpectedRecipients, this,
200 ✔
207
          &MainWindow::askReencryptUnexpected);
200 ✔
208
}
200 ✔
209

210
void MainWindow::initTextBrowser() {
200 ✔
211
  {
212
    const AppSettings s = QtPassSettings::load();
200 ✔
213
    if (s.useMonospace) {
200 ✔
214
      QFont monospace("Monospace");
1 ✔
215
      monospace.setStyleHint(QFont::Monospace);
1 ✔
216
      ui->textBrowser->setFont(monospace);
1 ✔
217
    }
1 ✔
218
    if (s.noLineWrapping) {
200 ✔
219
      ui->textBrowser->setLineWrapMode(QTextBrowser::NoWrap);
1 ✔
220
    }
221
    clearPanelTimer.setInterval(MS_PER_SECOND * s.autoclearPanelSeconds);
200 ✔
222
    clearResultsTimer.setInterval(clearPanelTimer.interval());
200 ✔
223
  }
200 ✔
224
  ui->textBrowser->setOpenExternalLinks(true);
200 ✔
225
  ui->textBrowser->setContextMenuPolicy(Qt::CustomContextMenu);
200 ✔
226
  connect(ui->textBrowser, &QWidget::customContextMenuRequested, this,
200 ✔
227
          &MainWindow::showBrowserContextMenu);
200 ✔
228
}
200 ✔
229

230
void MainWindow::initDisplayPanel() {
200 ✔
231
  m_displayPanel = new PasswordDisplayPanel(
200 ✔
232
      ui->gridLayout, ui->verticalLayoutPassword, this, this);
200 ✔
233
  connect(m_displayPanel, &PasswordDisplayPanel::copyRequested,
200 ✔
234
          &m_qtPass->clipboard(), &ClipboardManager::copyText);
200 ✔
235
  connect(m_displayPanel, &PasswordDisplayPanel::textCopied,
200 ✔
236
          &m_qtPass->clipboard(), &ClipboardManager::trackCopied);
200 ✔
237
  connect(ui->textBrowser, &SecretTextBrowser::copied, &m_qtPass->clipboard(),
200 ✔
238
          &ClipboardManager::trackCopied);
200 ✔
239
  connect(m_displayPanel, &PasswordDisplayPanel::qrRequested, m_qtPass,
200 ✔
240
          &QtPass::showTextAsQRCode);
200 ✔
241
  // Double-click on what is shown edits it, as in the tree.
242
  // The entry whose rows were double-clicked, not the tree's current row:
243
  // arrow keys and a right-click move that row without repainting the panel.
244
  connect(m_displayPanel, &PasswordDisplayPanel::editRequested, this, [this] {
200 ✔
245
    if (ui->actionEdit->isEnabled() && !m_panelEntry.isEmpty()) {
4 ✔
246
      editPassword(m_panelEntry);
3 ✔
247
    }
248
  });
4 ✔
249
}
200 ✔
250

251
void MainWindow::initTimers() {
200 ✔
252
  clearPanelTimer.setSingleShot(true);
200 ✔
253
  connect(&clearPanelTimer, &QTimer::timeout, this,
200 ✔
254
          [this]() { clearShownEntry(true); });
202 ✔
255
  clearResultsTimer.setSingleShot(true);
200 ✔
256
  connect(&clearResultsTimer, &QTimer::timeout, this,
200 ✔
257
          &MainWindow::clearContentResults);
200 ✔
258

259
  searchTimer.setInterval(350);
200 ✔
260
  searchTimer.setSingleShot(true);
200 ✔
261

262
  connect(&searchTimer, &QTimer::timeout, this, &MainWindow::onTimeoutSearch);
200 ✔
263

264
  // Safety net: if a backend operation disables the UI but never signals
265
  // completion, re-enable after a timeout so the window can't get stuck.
266
  m_uiWatchdog.setSingleShot(true);
200 ✔
267
  m_uiWatchdog.setInterval(UiWatchdogMs);
200 ✔
268
  connect(&m_uiWatchdog, &QTimer::timeout, this, [this]() {
200 ✔
269
    showStatusMessage(tr("Operation timed out; re-enabling interface."));
×
270
    // Drop any in-flight OTP request so a late finishedShow cannot be mistaken
271
    // for the answer to it.
272
    cancelOtpRequest();
×
273
    setUiElementsEnabled(true);
×
274
  });
×
275
}
200 ✔
276

277
void MainWindow::initProcessOutput() {
200 ✔
278
  m_processOutput = new ProcessOutputPanel(this);
200 ✔
279
  addDockWidget(Qt::BottomDockWidgetArea, m_processOutput);
200 ✔
280
  // After addDockWidget so our preference wins over any cached state
281
  // QMainWindow applies; restoreWindow() already processed the saved layout.
282
  m_processOutput->setVisible(QtPassSettings::isShowProcessOutput());
200 ✔
283
  // From the setting, not isVisible(): the window is not shown yet, so no
284
  // child of it reports visible.
285
  ui->actionShowProcessOutput->setChecked(
200 ✔
286
      QtPassSettings::isShowProcessOutput());
200 ✔
287
  connect(ui->actionShowProcessOutput, &QAction::toggled, this,
200 ✔
288
          [this](bool show) {
200 ✔
289
            m_processOutput->setVisible(show);
2 ✔
290
            AppSettings s = QtPassSettings::load();
2 ✔
291
            if (s.showProcessOutput != show) {
2 ✔
292
              s.showProcessOutput = show;
2 ✔
293
              QtPassSettings::save(s);
2 ✔
294
            }
295
          });
2 ✔
296

297
  connect(QtPassSettings::getPass(), &Pass::finishedAnyWithPid, this,
200 ✔
298
          [this](const QString &out, const QString &err, Enums::PROCESS pid) {
200 ✔
299
            // Never route potentially-secret output through the panel:
300
            // PASS_SHOW goes to the text browser (cleared on a timer when
301
            // "Autoclear panel" is set),
302
            // PASS_GREP would return password-file lines (#252; it is no
303
            // longer started, the check stays), and PASS_INSERT
304
            // is excluded defensively in case a future path uses --echo.
305
            if (ProcessOutputPanel::isSensitiveProcess(pid)) {
14 ✔
306
              return;
307
            }
308
            if (!out.isEmpty()) {
13 ✔
309
              onProcessOutput(out, false, pid);
1 ✔
310
            }
311
            if (!err.isEmpty()) {
13 ✔
312
              onProcessOutput(err, true, pid);
4 ✔
313
            }
314
          });
315
}
200 ✔
316

317
MainWindow::~MainWindow() {
396 ✔
318
  // Quit from the tray menu or a SIGTERM never delivers closeEvent(); the
319
  // window still knows its last geometry here.
320
  saveWindowState();
200 ✔
321
  delete m_qtPass;
200 ✔
322
}
596 ✔
323

324
// The signals of one backend that the window answers itself.
325
void MainWindow::connectPassSignals(Pass *pass) {
400 ✔
326
  // A failed decrypt never emits finishedShow; drop the pending OTP/copy
327
  // request so a later decrypt of the same entry is not taken as its answer.
328
  connect(pass, &Pass::processErrorExit, this, &MainWindow::onOperationError);
400 ✔
329
  connect(pass, &Pass::critical, this, &MainWindow::critical);
400 ✔
330
  connect(pass, &Pass::startingExecuteWrapper, this,
400 ✔
331
          &MainWindow::executeWrapperStarted);
400 ✔
332
  // The profile box comes back when the queue is done, also after the
333
  // watchdog released the rest of the interface early.
334
  connect(pass, &Pass::idle, this, &MainWindow::updateProfileBoxEnabled);
400 ✔
335
  connect(pass, &Pass::statusMsg, this, &MainWindow::showStatusMessage);
400 ✔
336
  connect(pass, &Pass::finishedShow, this, &MainWindow::passShowHandler);
400 ✔
337
  // Both check the file against their own pending request and ignore the
338
  // rest, so they can stay connected for good.
339
  connect(pass, &Pass::finishedShow, this, &MainWindow::otpFromFileToClipboard);
400 ✔
340
  connect(pass, &Pass::finishedShow, this,
400 ✔
341
          &MainWindow::passwordFromFileToClipboard);
400 ✔
342
  connect(pass, &Pass::finishedGrep, this, &MainWindow::onGrepFinished);
400 ✔
343
  // The refresh a save left waiting runs once the last push went through,
344
  // by name as it was queued before (the save's rewrite of the file may have
345
  // replaced its row in the tree), and only while the entry still holds the
346
  // panel and nothing else is queued: queued work would run first, and the
347
  // refresh would empty the browser of its error. A failed push dropped it
348
  // (onOperationError()).
349
  connect(pass, &Pass::finishedGitPush, this, [this, pass]() {
400 ✔
350
    if (m_refreshAfterPush.isEmpty() || m_refreshAfterPushOwner != pass ||
31 ✔
351
        pass->isPushing()) {
9 ✔
352
      return;
5 ✔
353
    }
354
    const QString file = std::exchange(m_refreshAfterPush, QString());
7 ✔
355
    m_refreshAfterPushOwner = nullptr;
7 ✔
356
    if (file == m_shownFile && pass->isIdle()) {
7 ✔
357
      ui->passwordName->setText(Util::shownName(file));
4 ✔
358
      pass->Show(file);
8 ✔
359
    }
360
  });
361
}
400 ✔
362

363
// Idempotent; called from closeEvent() and the destructor.
364
void MainWindow::saveWindowState() {
204 ✔
365
  QtPassSettings::setGeometry(saveGeometry());
204 ✔
366
  QtPassSettings::setSavestate(saveState());
204 ✔
367
}
204 ✔
368

369
void MainWindow::focusInput() {
76 ✔
370
  // findChild() rather than ui->lineEdit: on a fresh-config first launch
371
  // config() calls setWindowFlags(), which rebuilds the native window, and
372
  // under Qt 6.11 the QLineEdit was destroyed while ui->lineEdit kept its old
373
  // address (SIGSEGV in QWidget::testAttribute). findChild() returns null.
374
  if (!isVisible()) {
76 ✔
375
    return;
376
  }
377
  auto *lineEdit = findChild<QLineEdit *>(QStringLiteral("lineEdit"));
76 ✔
378
  if (lineEdit == nullptr || !lineEdit->isVisible()) {
76 ✔
379
    return;
380
  }
381
  lineEdit->selectAll();
76 ✔
382
  lineEdit->setFocus();
76 ✔
383
  // Only once focus has landed: set in showEvent(), an early return above
384
  // would consume the one-shot and never retry.
385
  m_firstShowCompleted = true;
76 ✔
386
}
387

388
auto MainWindow::event(QEvent *event) -> bool {
9,208 ✔
389
  if (event->type() == QEvent::ApplicationPaletteChange) {
9,208 ✔
390
    m_themeSwitched = true;
11 ✔
391
    // Breeze may re-stamp the bars before this arrives (Plasma 6 does):
392
    // their PaletteChange then found no switch yet, so check them now too.
393
    QTimer::singleShot(0, this, &MainWindow::dropStaleToolsAreaPalettes);
11 ✔
394
  }
395
  return QMainWindow::event(event);
9,208 ✔
396
}
397

398
void MainWindow::changeEvent(QEvent *event) {
266 ✔
399
  QWidget::changeEvent(event);
266 ✔
400
  if (event->type() == QEvent::PaletteChange && m_displayPanel != nullptr) {
266 ✔
401
    // Desktop switched light/dark. Top-level widgets get PaletteChange
402
    // (ApplicationPaletteChange goes to QApplication); stylesheets with
403
    // baked-in palette colours must be re-derived by hand.
404
    m_displayPanel->refreshPalette();
10 ✔
405
  }
406
  if (event->type() == QEvent::ActivationChange && isActiveWindow() &&
266 ✔
407
      isVisible()) {
408
    // Defer a tick so the activation dispatch chain unwinds first: calling
409
    // focusInput() inline has segfaulted on half-rebuilt ui state.
410
    QMetaObject::invokeMethod(this, &MainWindow::focusInput,
44 ✔
411
                              Qt::QueuedConnection);
412
  }
413
}
266 ✔
414

415
void MainWindow::showEvent(QShowEvent *event) {
46 ✔
416
  QMainWindow::showEvent(event);
46 ✔
417
  if (m_firstShowCompleted) {
46 ✔
418
    return;
419
  }
420
  // Queued so the platform map and pending rebuilds (setWindowFlags on the
421
  // wizard path) settle first. focusInput() sets the latch only on success,
422
  // so a failed lookup retries on the next show.
423
  QMetaObject::invokeMethod(this, &MainWindow::focusInput,
44 ✔
424
                            Qt::QueuedConnection);
425
}
426

427
void MainWindow::initToolBarButtons() {
200 ✔
428
  connect(ui->actionAddPassword, &QAction::triggered, this,
200 ✔
429
          &MainWindow::addPassword);
200 ✔
430
  connect(ui->actionAddFolder, &QAction::triggered, this,
200 ✔
431
          &MainWindow::addFolder);
200 ✔
432
  connect(ui->actionEdit, &QAction::triggered, this, &MainWindow::onEdit);
200 ✔
433
  connect(ui->actionDelete, &QAction::triggered, this, &MainWindow::onDelete);
200 ✔
434
  connect(ui->actionPush, &QAction::triggered, this, &MainWindow::onPush);
200 ✔
435
  connect(ui->actionUpdate, &QAction::triggered, this, &MainWindow::onUpdate);
200 ✔
436
  connect(ui->actionUsers, &QAction::triggered, this, &MainWindow::onUsers);
200 ✔
437
  connect(ui->actionConfig, &QAction::triggered, this, &MainWindow::onConfig);
200 ✔
438
  connect(ui->actionOtp, &QAction::triggered, this, &MainWindow::onOtp);
200 ✔
439

440
  // Menu-only. Quit ends the application, tray icon or not, as in KeePassXC,
441
  // Telegram and the KDE, GNOME and macOS guidelines (#1788). Close is
442
  // close(), a hide when "hide on close" is set, like the X button and Alt+F4.
443
  connect(ui->actionQuit, &QAction::triggered, qApp, &QApplication::quit);
200 ✔
444
  connect(ui->actionClose, &QAction::triggered, this, &MainWindow::close);
200 ✔
445
#ifdef Q_OS_MACOS
446
  // The menu bar is the system's up there; nothing to hide.
447
  ui->actionShowMenuBar->setVisible(false);
448
#else
449
  // The action lives in the menu it hides, so it has to be on the window as
450
  // well for Ctrl+M to keep working while the bar is gone.
451
  addAction(ui->actionShowMenuBar);
200 ✔
452
  ui->actionShowMenuBar->setChecked(QtPassSettings::load().showMenuBar);
200 ✔
453
  menuBar()->setVisible(ui->actionShowMenuBar->isChecked());
200 ✔
454
  connect(ui->actionShowMenuBar, &QAction::toggled, this, [this](bool show) {
200 ✔
455
    menuBar()->setVisible(show);
5 ✔
456
    AppSettings s = QtPassSettings::load();
5 ✔
457
    s.showMenuBar = show;
5 ✔
458
    QtPassSettings::save(s);
5 ✔
459
  });
5 ✔
460
  new MenuBarPeek(this, ui->actionShowMenuBar);
200 ✔
461
#endif
462
  connect(ui->actionFaq, &QAction::triggered, this, [] {
201 ✔
463
    QDesktopServices::openUrl(QUrl(QStringLiteral("https://qtpass.org/faq")));
2 ✔
464
  });
1 ✔
465
  connect(ui->actionAbout, &QAction::triggered, this, &MainWindow::showAbout);
200 ✔
466
  connect(ui->actionAboutQt, &QAction::triggered, qApp, &QApplication::aboutQt);
200 ✔
467

468
  ui->actionAddPassword->setIcon(
200 ✔
469
      QIcon::fromTheme("document-new", QIcon(":/icons/document-new.svg")));
800 ✔
470
  ui->actionAddFolder->setIcon(
200 ✔
471
      QIcon::fromTheme("folder-new", QIcon(":/icons/folder-new.svg")));
800 ✔
472
  ui->actionEdit->setIcon(QIcon::fromTheme(
200 ✔
473
      "document-properties", QIcon(":/icons/document-properties.svg")));
600 ✔
474
  ui->actionDelete->setIcon(
200 ✔
475
      QIcon::fromTheme("edit-delete", QIcon(":/icons/edit-delete.svg")));
800 ✔
476
  ui->actionPush->setIcon(
200 ✔
477
      QIcon::fromTheme("go-up", QIcon(":/icons/go-top.svg")));
800 ✔
478
  ui->actionUpdate->setIcon(
200 ✔
479
      QIcon::fromTheme("go-down", QIcon(":/icons/go-bottom.svg")));
800 ✔
480
  ui->actionUsers->setIcon(QIcon::fromTheme(
200 ✔
481
      "x-office-address-book", QIcon(":/icons/x-office-address-book.svg")));
600 ✔
482
  ui->actionConfig->setIcon(QIcon::fromTheme(
200 ✔
483
      "applications-system", QIcon(":/icons/applications-system.svg")));
400 ✔
484
}
200 ✔
485

486
void MainWindow::initStatusBar() {
200 ✔
487
  ui->statusBar->showMessage(tr("Welcome to QtPass %1").arg(VERSION), 2000);
400 ✔
488

489
  QPixmap logo = QPixmap::fromImage(QImage(":/artwork/icon.svg"))
400 ✔
490
                     .scaledToHeight(statusBar()->height());
200 ✔
491
  auto *logoApp = new QLabel(statusBar());
200 ✔
492
  logoApp->setPixmap(logo);
200 ✔
493
  statusBar()->addPermanentWidget(logoApp);
200 ✔
494
}
200 ✔
495

496
auto MainWindow::getCurrentTreeViewIndex() -> QModelIndex {
11 ✔
497
  return ui->treeView->currentIndex();
11 ✔
498
}
499

500
void MainWindow::flashText(const QString &text, const bool isError,
298 ✔
501
                           const bool isHtml) {
502
  // setText() applies the current char format to the whole message. Start
503
  // from an empty one: inherited from a cursor on a linkified URL it carried
504
  // the anchor, and the message became a link to that address. No colour
505
  // but red for an error, so text follows runtime light/dark switches (#946).
506
  QTextCursor cursor = ui->textBrowser->textCursor();
298 ✔
507
  cursor.clearSelection();
298 ✔
508
  ui->textBrowser->setTextCursor(cursor);
298 ✔
509
  QTextCharFormat format;
298 ✔
510
  if (isError) {
298 ✔
511
    format.setForeground(QColor(Qt::red));
11 ✔
512
  }
513
  ui->textBrowser->setCurrentCharFormat(format);
298 ✔
514

515
  // Wrapped at word boundaries, a run of hundreds of thousands of letters
516
  // took Qt seconds to minutes; anywhere, it is linear. Anywhere while the
517
  // text goes in, then word wrap back unless what is shown has such a run:
518
  // markup (a link's "<a href") splits a run in the source, not on screen.
519
  ui->textBrowser->setWordWrapMode(QTextOption::WrapAnywhere);
298 ✔
520
  if (isHtml) {
298 ✔
521
    QString _text = text;
522
    // What was shown before this message: the part the cap may remove.
523
    // The message itself is never cut, so an entry shown through here
524
    // (passShowHandler()) stays whole however long it is.
525
    int older = 0;
279 ✔
526
    if (!ui->textBrowser->toPlainText().isEmpty()) {
558 ✔
527
      older = ui->textBrowser->document()->characterCount() - 1;
223 ✔
528
      _text = ui->textBrowser->toHtml() + _text;
446 ✔
529
    }
530
    ui->textBrowser->setHtml(_text);
279 ✔
531
    // Only the latest output: from the front, up to the start of the first
532
    // paragraph that ends the excess, within what was shown before (a
533
    // message that starts a paragraph starts one past it, after the
534
    // separator).
535
    QTextDocument *doc = ui->textBrowser->document();
279 ✔
536
    int cut = qMin(doc->characterCount() - kMaxFlashCharacters, older);
279 ✔
537
    if (cut > 0) {
279 ✔
538
      const QTextBlock block = doc->findBlock(cut);
140 ✔
539
      if (block.isValid() && cut > block.position() && block.next().isValid() &&
140 ✔
540
          block.next().position() <= older + 1) {
140 ✔
541
        cut = block.next().position();
140 ✔
542
      }
543
      QTextCursor trim(doc);
140 ✔
544
      trim.setPosition(cut, QTextCursor::KeepAnchor);
140 ✔
545
      trim.removeSelectedText();
140 ✔
546
    }
140 ✔
547
  } else {
548
    ui->textBrowser->setText(text);
19 ✔
549
  }
550
  // The raw text: toPlainText() turns a no-break space into a plain one.
551
  if (!Util::hasLongUnbrokenRun(ui->textBrowser->document()->toRawText())) {
596 ✔
552
    ui->textBrowser->setWordWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
292 ✔
553
  }
554
}
298 ✔
555

556
void MainWindow::applyTextBrowserSettings() {
5 ✔
557
  const AppSettings s = QtPassSettings::load();
5 ✔
558
  if (s.useMonospace) {
5 ✔
559
    QFont monospace("Monospace");
1 ✔
560
    monospace.setStyleHint(QFont::Monospace);
1 ✔
561
    ui->textBrowser->setFont(monospace);
1 ✔
562
  } else {
1 ✔
563
    ui->textBrowser->setFont(QFont());
4 ✔
564
  }
565

566
  if (s.noLineWrapping) {
5 ✔
567
    ui->textBrowser->setLineWrapMode(QTextBrowser::NoWrap);
1 ✔
568
  } else {
569
    ui->textBrowser->setLineWrapMode(QTextBrowser::WidgetWidth);
4 ✔
570
  }
571
}
5 ✔
572

573
void MainWindow::applyWindowFlagsSettings() {
216 ✔
574
  const bool wantOnTop = QtPassSettings::isAlwaysOnTop();
216 ✔
575
  const Qt::WindowFlags flags = windowFlags();
576
  if (flags.testFlag(Qt::WindowStaysOnTopHint) == wantOnTop) {
216 ✔
577
    // setWindowFlags() rebuilds the native window, the teardown that left
578
    // ui->lineEdit dangling (see focusInput()); skip it when nothing changes.
579
    return;
580
  }
581
  // Toggle just this hint; resetting to Qt::Window discarded every other flag.
582
  const bool wasVisible = isVisible();
583
  setWindowFlags(wantOnTop ? (flags | Qt::WindowStaysOnTopHint)
4 ✔
584
                           : (flags & ~Qt::WindowStaysOnTopHint));
585
  // setWindowFlags() hides a shown window; a window that was not shown yet
586
  // (first-run wizard from the constructor) is left to its normal show.
587
  if (wasVisible) {
2 ✔
588
    show();
2 ✔
589
  }
590
}
591

592
auto MainWindow::config() -> bool {
8 ✔
593
  if (m_freshStart) {
8 ✔
594
    // No usable configuration yet: the wizard finds the programs, the key
595
    // and the store, and creates the store when it has to.
596
    FirstRunWizard wizard(this);
2 ✔
597
    if (wizard.exec() != QDialog::Accepted) {
2 ✔
598
      return false;
599
    }
600
  } else {
2 ✔
601
    ConfigDialog d(this);
6 ✔
602
    d.setModal(true);
6 ✔
603
    if (d.exec() != QDialog::Accepted) {
6 ✔
604
      return false;
605
    }
606
  }
6 ✔
607

608
  applyTextBrowserSettings();
5 ✔
609
  applyWindowFlagsSettings();
5 ✔
610

611
  updateProfileBox();
5 ✔
612
  const AppSettings s = QtPassSettings::load();
5 ✔
613
  // An open still waiting for the tree was asked of the old view; once
614
  // re-rooted, it would find that name in the new store. A profile switch
615
  // ends it by clearing the search text.
616
  delete m_pendingOpen;
5 ✔
617
  // A content search still running searched the old store, and its matches
618
  // would be listed for this one: onGrepFinished() cannot tell. Cancelled,
619
  // and content-search results on screen go with it (clearPanel()).
620
  cancelContentSearch();
5 ✔
621
  if (m_grep.cancelSearch()) {
622
    QApplication::restoreOverrideCursor();
1 ✔
623
  }
624
  clearPanel(false);
5 ✔
625
  m_tree->setStore(s.passStore);
5 ✔
626
  deselect();
5 ✔
627
  ui->treeView->setCurrentIndex(QModelIndex());
5 ✔
628

629
  Pass *activePass = QtPassSettings::getPass();
5 ✔
630
  activePass->updateEnv();
5 ✔
631
  m_tree->setPass(activePass);
5 ✔
632
  clearPanelTimer.setInterval(MS_PER_SECOND * s.autoclearPanelSeconds);
5 ✔
633
  clearResultsTimer.setInterval(clearPanelTimer.interval());
5 ✔
634
  m_qtPass->clipboard().setAutoclearTimer();
5 ✔
635

636
  updateGitButtonVisibility();
5 ✔
637
  updateOtpButtonVisibility();
5 ✔
638
  updateGrepButtonVisibility();
5 ✔
639
  updateProcessOutputVisibility();
5 ✔
640
#ifndef Q_OS_MACOS
641
  // The action's toggled handler shows or hides the bar (and saves again).
642
  ui->actionShowMenuBar->setChecked(s.showMenuBar);
5 ✔
643
#endif
644
  if (s.useTrayIcon && m_tray == nullptr) {
5 ✔
645
    initTrayIcon();
1 ✔
646
  } else if (!s.useTrayIcon && m_tray != nullptr) {
4 ✔
647
    destroyTrayIcon();
×
648
  }
649

650
  // Stay fresh-start while the configuration is unusable, so the
651
  // constructor's loop re-runs the wizard. The re-prompt lives there:
652
  // recursing here never reported a cancel back to the caller.
653
  if (Util::configIsValid(s)) {
5 ✔
654
    m_freshStart = false;
5 ✔
655
  }
656
  return true;
657
}
5 ✔
658

659
void MainWindow::onUpdate(bool block) {
2 ✔
660
  ui->statusBar->showMessage(tr("Updating password-store"), 2000);
2 ✔
661
  if (block) {
2 ✔
662
    QtPassSettings::getPass()->GitPull_b(Pass::kBlockingPullMs);
1 ✔
663
  } else {
664
    QtPassSettings::getPass()->GitPull();
1 ✔
665
  }
666
}
2 ✔
667

668
void MainWindow::onPush() {
1 ✔
669
  if (QtPassSettings::isUseGit()) {
1 ✔
670
    ui->statusBar->showMessage(tr("Updating password-store"), 2000);
1 ✔
671
    QtPassSettings::getPass()->GitPush();
1 ✔
672
  }
673
}
1 ✔
674

675
void MainWindow::onAutoPush() {
8 ✔
676
  if (QtPassSettings::isUseGit()) {
8 ✔
677
    ui->statusBar->showMessage(tr("Updating password-store"), 2000);
8 ✔
678
    QtPassSettings::getPass()->GitPushAutomatic();
8 ✔
679
  }
680
}
8 ✔
681

682
auto MainWindow::getFile(const QModelIndex &index, bool forPass) -> QString {
68 ✔
683
  return m_tree->fileFor(index, forPass);
68 ✔
684
}
685

686
void MainWindow::on_treeView_clicked(const QModelIndex &index) {
27 ✔
687
  bool cleared = ui->treeView->currentIndex().flags() == Qt::NoItemFlags;
27 ✔
688
  QString file = getFile(index, true);
27 ✔
689
  ui->passwordName->setText(Util::shownName(file));
54 ✔
690
  if (!file.isEmpty() && !cleared) {
27 ✔
691
    // Remember what the panel is about to show, so onOtp() can tell whether the
692
    // code it can see belongs to the entry that is currently selected.
693
    m_shownFile = file;
26 ✔
694
    QtPassSettings::getPass()->Show(file);
52 ✔
695
  } else {
696
    m_shownFile.clear();
1 ✔
697
    clearPanel(false);
1 ✔
698
    ui->actionEdit->setEnabled(false);
1 ✔
699
    ui->actionDelete->setEnabled(true);
1 ✔
700
  }
701
}
27 ✔
702

703
void MainWindow::on_treeView_doubleClicked(const QModelIndex &index) {
4 ✔
704
  QFileInfo fileOrFolder = m_tree->fileInfo(ui->treeView->currentIndex());
4 ✔
705

706
  if (fileOrFolder.isFile()) {
4 ✔
707
    editPassword(getFile(index, true));
6 ✔
708
  }
709
}
4 ✔
710

711
void MainWindow::deselect() {
19 ✔
712
  m_shownFile.clear();
19 ✔
713
  cancelOtpRequest();
19 ✔
714
  m_qtPass->clipboard().clear();
19 ✔
715
  ui->treeView->clearSelection();
19 ✔
716
  // The current index too: clearSelection() keeps it, and whatever asks for
717
  // the "current" folder (Users, Add password, Add folder) took the hidden
718
  // entry it was left on, such as the first hit of a search just emptied.
719
  ui->treeView->setCurrentIndex(QModelIndex());
19 ✔
720
  ui->actionEdit->setEnabled(false);
19 ✔
721
  ui->actionDelete->setEnabled(false);
19 ✔
722
  ui->passwordName->setText("");
19 ✔
723
  clearPanel(false);
19 ✔
724
}
19 ✔
725

726
void MainWindow::executeWrapperStarted() {
71 ✔
727
  m_displayPanel->clear();
71 ✔
728
  m_panelEntry.clear();
71 ✔
729
  ui->textBrowser->clear();
71 ✔
730
  setUiElementsEnabled(false);
71 ✔
731
  clearPanelTimer.stop();
71 ✔
732
  if (QtPassSettings::isShowProcessOutput()) {
71 ✔
733
    m_processOutput->setVisible(true);
66 ✔
734
  }
735
}
71 ✔
736

737
void MainWindow::passShowHandler(const QString &p_output, const QString &file) {
43 ✔
738
  // Only the entry we most recently asked to show may repaint the panel; a
739
  // slower decrypt of an entry the user has since left is dropped, and so is
740
  // one that arrives after the selection was cleared (deselect, a profile
741
  // switch): nothing is asked to be shown then.
742
  if (!file.isEmpty() && file != m_shownFile) {
43 ✔
743
    // A newer show is pending and releases the interface when it lands;
744
    // with none (the selection was cleared) nothing else would until the
745
    // watchdog. setUiElementsEnabled() keeps a re-encryption's lock.
746
    if (m_shownFile.isEmpty()) {
11 ✔
747
      setUiElementsEnabled(true);
8 ✔
748
    }
749
    return;
11 ✔
750
  }
751
  const AppSettings s = QtPassSettings::load();
32 ✔
752
  refreshMarkedSecrets(s);
32 ✔
753
  QStringList templ =
754
      s.useTemplate ? TemplateIO::fieldsIn(s.passTemplate) : QStringList();
32 ✔
755
  bool allFields = s.useTemplate && s.templateAllFields;
32 ✔
756
  // A secret the panel hides is a field even when the template doesn't list
757
  // it: left in the text below the fields, it would show in plain view.
758
  FileContent fileContent = FileContent::parse(
759
      p_output, templ, allFields, [this, &s](const QString &name) {
32 ✔
760
        return m_displayPanel->isSecret(name, s);
19 ✔
761
      });
32 ✔
762
  QString output = p_output;
763
  // Display variant: empty when the password line is itself an otpauth URI, so
764
  // the shared secret is neither rendered nor copied to the clipboard.
765
  QString password = fileContent.getPasswordForDisplay();
32 ✔
766

767
  // Skipped for an OTP request: the user asked for a code, and two
768
  // OleSetClipboard calls in one turn can leave the Windows clipboard empty.
769
  if (m_otpRequestFile.isEmpty() || m_otpRequestFile != file) {
32 ✔
770
    m_qtPass->clipboard().copyIfAlways(password, p_output);
30 ✔
771
  }
772

773
  m_displayPanel->clear();
32 ✔
774
  m_panelEntry.clear();
32 ✔
775

776
  if (s.hideContent) {
32 ✔
777
    output = "***" + tr("Content hidden") + "***";
4 ✔
778
  } else if (s.displayAsIs) {
30 ✔
779
    // As it is, but not a block per line of millions.
780
    output = FileContent::boundedForDisplay(p_output);
4 ✔
781
  } else {
782
    m_panelEntry = file;
28 ✔
783
    m_displayPanel->displayFields(password, fileContent.getNamedValues(), s,
56 ✔
784
                                  s.useOtp ? fileContent.getOtpUri()
28 ✔
785
                                           : QString());
786
    output = fileContent.getRemainingDataForDisplay();
56 ✔
787
  }
788

789
  if (s.useAutoclearPanel) {
32 ✔
790
    clearPanelTimer.start();
3 ✔
791
  }
792

793
  // Shown as it is, the text holds the password and every secret field: no
794
  // links in it, or a click on a URL-shaped one handed it to the browser.
795
  flashText(QtPass::formatOutput(output, QString(), QString(),
64 ✔
796
                                 !s.displayAsIs || s.hideContent),
32 ✔
797
            false, true);
798
  setUiElementsEnabled(true);
32 ✔
799
}
64 ✔
800

801
void MainWindow::otpFromFileToClipboard(const QString &p_output,
32 ✔
802
                                        const QString &file) {
803
  // Permanently connected: only the decrypt of the entry onOtp() asked for
804
  // is ours, everything else belongs to a tree click or a Ctrl+C.
805
  if (m_otpRequestFile.isEmpty() || file != m_otpRequestFile) {
32 ✔
806
    return;
28 ✔
807
  }
808
  m_otpRequestFile.clear();
6 ✔
809

810
  if (p_output.isEmpty()) {
6 ✔
811
    // Distinguish "could not read the entry" from "entry has no OTP".
812
    flashText(tr("Could not decrypt this password entry"), true);
1 ✔
813
    setUiElementsEnabled(true);
1 ✔
814
    return;
1 ✔
815
  }
816

817
  // passShowHandler ran first for this finishedShow; if it rendered the OTP
818
  // row, reuse its code (as onOtp()'s fast path does). Otherwise parse:
819
  // hideContent, displayAsIs or no OTP field.
820
  const QString shown = m_displayPanel->currentOtpCode();
5 ✔
821
  if (!shown.isEmpty()) {
5 ✔
822
    m_qtPass->clipboard().copyText(shown);
1 ✔
823
    showStatusMessage(tr("OTP code copied to clipboard"));
1 ✔
824
    setUiElementsEnabled(true);
1 ✔
825
    return;
826
  }
827

828
  const AppSettings s = QtPassSettings::load();
4 ✔
829
  // Parse with the same template settings passShowHandler uses, so an OTP
830
  // field is recognised identically in both paths.
831
  const QStringList templ =
832
      s.useTemplate ? TemplateIO::fieldsIn(s.passTemplate) : QStringList();
4 ✔
833
  const bool allFields = s.useTemplate && s.templateAllFields;
4 ✔
834
  const FileContent fileContent =
835
      FileContent::parse(p_output, templ, allFields);
4 ✔
836

837
  Totp::Refusal why = Totp::Refusal::None;
4 ✔
838
  const std::optional<Totp::Settings> settings =
839
      Totp::parse(fileContent.getOtpUri(), &why);
8 ✔
840
  if (settings.has_value()) {
4 ✔
841
    m_qtPass->clipboard().copyText(Totp::generateNow(*settings));
4 ✔
842
    showStatusMessage(tr("OTP code copied to clipboard"));
4 ✔
843
  } else {
844
    // Why, when there is a configuration that gives no code.
845
    const QString reason = Totp::describe(why);
2 ✔
846
    flashText(reason.isEmpty() ? tr("No OTP code found in this password entry")
6 ✔
847
                               : reason,
848
              true);
849
  }
850
  setUiElementsEnabled(true);
4 ✔
851
}
8 ✔
852

853
void MainWindow::clearPanel(bool notify) {
65 ✔
854
  clearShownEntry(notify);
65 ✔
855
  clearContentResults();
65 ✔
856
}
65 ✔
857

858
void MainWindow::clearShownEntry(bool notify) {
67 ✔
859
  m_displayPanel->clear();
67 ✔
860
  m_panelEntry.clear();
67 ✔
861
  // A QR code of the password is the password on screen as much as the
862
  // panel is; it is a popup of its own, not part of the panel.
863
  m_qtPass->closeQRCode();
67 ✔
864
  if (notify) {
67 ✔
865
    QString output = "***" + tr("Password and content hidden") + "***";
4 ✔
866
    ui->textBrowser->setHtml(output);
2 ✔
867
  } else {
868
    ui->textBrowser->setHtml("");
130 ✔
869
  }
870
}
67 ✔
871

872
void MainWindow::clearContentResults() {
68 ✔
873
  clearResultsTimer.stop();
68 ✔
874
  const bool grepWasVisible = ui->grepResultsList->isVisible();
68 ✔
875
  ui->grepResultsList->clear();
68 ✔
876
  if (grepWasVisible) {
68 ✔
877
    showContentResults(false);
7 ✔
878
    if (m_grep.inGrepMode()) {
7 ✔
879
      // Left as the button leaves it: a search still running would otherwise
880
      // hand its partial matches to a content search entered meanwhile.
881
      cancelContentSearch();
7 ✔
882
      if (m_grep.leaveGrepMode()) {
883
        QApplication::restoreOverrideCursor();
2 ✔
884
      }
885
      ui->grepButton->blockSignals(true);
7 ✔
886
      ui->grepButton->setChecked(false);
7 ✔
887
      ui->grepButton->blockSignals(false);
7 ✔
888
      ui->lineEdit->blockSignals(true);
7 ✔
889
      ui->lineEdit->clear();
7 ✔
890
      ui->lineEdit->blockSignals(false);
7 ✔
891
      ui->lineEdit->setPlaceholderText(tr("Search password"));
14 ✔
892
    }
893
  }
894
}
68 ✔
895

896
void MainWindow::setUiElementsEnabled(bool state) {
450 ✔
897
  // A running re-encryption owns the UI state: the progress dialog's Cancel is
898
  // the user's escape hatch and endReencryptPath() releases the interface, so
899
  // neither an unrelated completion nor the watchdog may re-enable it early.
900
  if (state && m_reencryptRunning) {
450 ✔
901
    m_uiWatchdog.stop();
1 ✔
902
    return;
1 ✔
903
  }
904
  // Arm the watchdog while the UI is disabled; disarm once re-enabled.
905
  if (state) {
906
    m_uiWatchdog.stop();
354 ✔
907
  } else {
908
    m_uiWatchdog.start();
95 ✔
909
  }
910
  ui->treeView->setEnabled(state);
449 ✔
911
  ui->lineEdit->setEnabled(state);
449 ✔
912
  ui->actionAddPassword->setEnabled(state);
449 ✔
913
  ui->actionAddFolder->setEnabled(state);
449 ✔
914
  ui->actionUsers->setEnabled(state);
449 ✔
915
  ui->actionConfig->setEnabled(state);
449 ✔
916
  m_uiEnabled = state;
449 ✔
917
  updateProfileBoxEnabled();
449 ✔
918
  const bool uiEnabled = state;
919
  // is a file selected, and in sight (content search results hide the tree)?
920
  state &= ui->treeView->currentIndex().isValid() && !ui->treeView->isHidden();
901 ✔
921
  ui->actionDelete->setEnabled(state);
449 ✔
922
  ui->actionEdit->setEnabled(state);
449 ✔
923
  updateGitButtonVisibility(uiEnabled);
449 ✔
924
  // `state` is now "UI enabled AND a file is selected", which is exactly when
925
  // generating an OTP makes sense.
926
  updateOtpButtonVisibility(state);
449 ✔
927
}
928

929
void MainWindow::restoreWindow() {
211 ✔
930
  // saveGeometry() covers position, size, maximized state and screen;
931
  // anything applied on top discards it. Centre only when nothing was saved.
932
  const QByteArray geometry = QtPassSettings::getGeometry();
422 ✔
933
  if (geometry.isEmpty() || !restoreGeometry(geometry)) {
211 ✔
934
    WindowStateStore::centreOnCursorScreen(*this);
4 ✔
935
  }
936
  restoreState(QtPassSettings::getSavestate(saveState()));
211 ✔
937
  const AppSettings s = QtPassSettings::load();
211 ✔
938

939
  applyWindowFlagsSettings();
211 ✔
940

941
  if (s.useTrayIcon && m_tray == nullptr) {
211 ✔
942
    initTrayIcon();
2 ✔
943
    // Minimized to the tray only when there is one: without a system tray
944
    // initTrayIcon() gave up, and a hidden window could not be brought back.
945
    if (s.startMinimized && m_tray != nullptr) {
2 ✔
946
      // since we are still in constructor, can't directly hide
947
      QTimer::singleShot(10, this, &MainWindow::hide);
×
948
    }
949
  } else if (!s.useTrayIcon && m_tray != nullptr) {
209 ✔
950
    destroyTrayIcon();
×
951
  }
952
}
422 ✔
953

954
void MainWindow::onConfig() {
3 ✔
955
  // No Settings while anything of the store runs or waits, as with the
956
  // profile box (#2071): the store, backend and programs chosen there apply
957
  // to what is still queued, so a pending `pass init` re-encrypted the store
958
  // just picked for the recipients chosen for the other. Asked of the
959
  // backends: the watchdog releases the interface while a slow gpg or git
960
  // still runs.
961
  if (!QtPassSettings::backendsIdle()) {
3 ✔
962
    critical(tr("Settings not opened"),
2 ✔
963
             tr("A gpg, Git or pass command is still running or waiting. "
1 ✔
964
                "Open the settings again once it has finished. If it does "
965
                "not finish, answer or cancel the PIN or password prompt it "
966
                "waits for, or restart QtPass. A restart forgets which "
967
                "folders still need re-encrypting: re-encrypt any folder "
968
                "whose re-encryption did not finish, or that you moved "
969
                "entries into, before anything is pushed."));
970
    return;
1 ✔
971
  }
972
  config();
2 ✔
973
}
974

975
void MainWindow::showAbout() {
1 ✔
976
  QMessageBox::about(
1 ✔
977
      this, tr("About QtPass"),
1 ✔
978
      tr("<h3>QtPass %1</h3>"
1 ✔
979
         "<p>A multi-platform GUI for <a "
980
         "href=\"https://www.passwordstore.org/\">"
981
         "pass</a>, the standard Unix password manager.</p>"
982
         "<p><a href=\"https://qtpass.org/\">qtpass.org</a> &middot; "
983
         "<a href=\"https://github.com/IJHack/QtPass\">Source and "
984
         "issues</a></p>"
985
         "<p>Copyright &copy; 2014&ndash;%2 IJhack. Licensed under the "
986
         "<a href=\"https://www.gnu.org/licenses/gpl-3.0.html\">GNU GPL "
987
         "version 3</a> or later.</p>")
988
          .arg(QStringLiteral(VERSION),
2 ✔
989
               QString::number(QDate::currentDate().year())));
2 ✔
990
}
1 ✔
991

992
void MainWindow::on_lineEdit_textChanged(const QString &arg1) {
50 ✔
993
  if (m_grep.inGrepMode())
50 ✔
994
    return;
995
  ui->statusBar->showMessage(tr("Looking for: %1").arg(arg1), 1000);
74 ✔
996
  ui->treeView->expandAll();
37 ✔
997
  // Drop any decrypt still pending for the entry that was shown: otherwise it
998
  // keeps its right to the panel and, with "Always copy", the clipboard, and
999
  // when it lands late it shows that entry's password under the new heading.
1000
  m_shownFile.clear();
37 ✔
1001
  cancelOtpRequest();
37 ✔
1002
  clearPanel(false);
37 ✔
1003
  ui->passwordName->setText("");
74 ✔
1004
  ui->actionEdit->setEnabled(false);
37 ✔
1005
  ui->actionDelete->setEnabled(false);
37 ✔
1006
  searchTimer.start();
37 ✔
1007
}
1008

1009
void MainWindow::onTimeoutSearch() {
41 ✔
1010
  // The tree matches slash-separated paths: on Windows, team\bank typed is
1011
  // team/bank, as exactMatchPath() reads it too.
1012
  QString query = QDir::fromNativeSeparators(ui->lineEdit->text());
82 ✔
1013

1014
  if (query.isEmpty()) {
41 ✔
1015
    ui->treeView->collapseAll();
2 ✔
1016
    deselect();
2 ✔
1017
  }
1018

1019
  // The words are matched literally, in order, with anything in between:
1020
  // "work vpn" finds work/acme/vpn.
1021
  m_tree->setFilter(StoreModel::wordsFilter(query));
41 ✔
1022

1023
  if (m_tree->proxy().rowCount() > 0 && !query.isEmpty()) {
41 ✔
1024
    selectFirstFile();
29 ✔
1025
  } else {
1026
    ui->actionEdit->setEnabled(false);
12 ✔
1027
    ui->actionDelete->setEnabled(false);
12 ✔
1028
  }
1029
}
41 ✔
1030

1031
void MainWindow::on_lineEdit_returnPressed() {
17 ✔
1032
  qCDebug(lcQtPass) << "on_lineEdit_returnPressed"
17 ✔
1033
                    << m_tree->proxy().rowCount();
×
1034

1035
  if (m_grep.inGrepMode()) {
17 ✔
1036
    const QString query = ui->lineEdit->text();
12 ✔
1037
    if (!query.isEmpty()) {
12 ✔
1038
      ui->grepResultsList->clear();
9 ✔
1039
      ui->statusBar->showMessage(tr("Searching…"));
18 ✔
1040
      if (m_grep.beginSearch()) {
1041
        QApplication::setOverrideCursor(Qt::WaitCursor);
9 ✔
1042
      }
1043
      QtPassSettings::getPass()->Grep(query, ui->grepCaseButton->isChecked());
18 ✔
1044
    } else {
1045
      cancelContentSearch();
3 ✔
1046
      if (m_grep.cancelSearch()) {
1047
        QApplication::restoreOverrideCursor();
2 ✔
1048
      }
1049
      ui->grepResultsList->clear();
3 ✔
1050
      showContentResults(false);
3 ✔
1051
    }
1052
    return;
1053
  }
1054

1055
  // Return within the search delay acts on the text as typed, not on the
1056
  // tree as the previous text filtered it.
1057
  if (searchTimer.isActive()) {
5 ✔
1058
    searchTimer.stop();
5 ✔
1059
    onTimeoutSearch();
5 ✔
1060
  }
1061
  if (m_tree->proxy().rowCount() > 0) {
5 ✔
1062
    selectFirstFile();
5 ✔
1063
    on_treeView_clicked(ui->treeView->currentIndex());
5 ✔
1064
  }
1065
}
1066

1067
void MainWindow::on_grepButton_toggled(bool checked) {
35 ✔
1068
  const AppSettings s = QtPassSettings::load();
35 ✔
1069
  if (checked) {
35 ✔
1070
    m_grep.enterGrepMode();
1071
    ui->lineEdit->setPlaceholderText(tr("Search content (regex)"));
44 ✔
1072
    // Both backends search through NativeGrep (QRegularExpression), so one
1073
    // dialect: PCRE.
1074
    ui->lineEdit->setToolTip(
22 ✔
1075
        tr("Content search uses Perl-compatible regular expressions (PCRE)."));
22 ✔
1076
    ui->lineEdit->clear();
22 ✔
1077
    searchTimer.stop();
22 ✔
1078
    m_tree->setFilter(QRegularExpression());
22 ✔
1079
    ui->grepResultsList->setVisible(false);
22 ✔
1080
    // Keep treeView visible until results arrive
1081
  } else {
1082
    cancelContentSearch();
13 ✔
1083
    if (m_grep.leaveGrepMode()) {
1084
      QApplication::restoreOverrideCursor();
2 ✔
1085
    }
1086
    searchTimer.stop();
13 ✔
1087
    ui->lineEdit->blockSignals(true);
13 ✔
1088
    ui->lineEdit->clear();
13 ✔
1089
    ui->lineEdit->blockSignals(false);
13 ✔
1090
    ui->lineEdit->setPlaceholderText(tr("Search password"));
26 ✔
1091
    ui->lineEdit->setToolTip(QString());
26 ✔
1092
    ui->grepResultsList->clear();
13 ✔
1093
    showContentResults(false);
13 ✔
1094
    m_tree->setFilter(QRegularExpression());
13 ✔
1095
  }
1096
}
35 ✔
1097

1098
void MainWindow::refreshMarkedSecrets(const AppSettings &s) {
42 ✔
1099
  if (s.hidePassword) {
42 ✔
1100
    m_displayPanel->setMarkedSecrets(
4 ✔
1101
        TemplateIO::secretFieldsIn(s.passTemplate) +
8 ✔
1102
        TemplateIO::readSecretFields(s.passStore));
12 ✔
1103
  }
1104
}
42 ✔
1105

1106
auto MainWindow::grepLineForDisplay(const QString &line,
43 ✔
1107
                                    const AppSettings &s) const -> QString {
1108
  const QString hidden =
1109
      QStringLiteral("***") + tr("hidden") + QStringLiteral("***");
86 ✔
1110
  if (NativeGrep::isOtpMarker(line)) {
43 ✔
1111
    return tr("One-time password secret: %1").arg(hidden);
2 ✔
1112
  }
1113
  // The panel's own rules: the password and a field it would put behind
1114
  // the eye button keep their value out of the list too.
1115
  if (NativeGrep::isPasswordMatch(line)) {
1116
    return m_displayPanel->hides(QObject::tr("Password"), s)
52 ✔
1117
               ? tr("Password: %1").arg(hidden)
52 ✔
1118
               : NativeGrep::passwordMatchText(line);
26 ✔
1119
  }
1120
  if (const qsizetype colon = line.indexOf(QLatin1Char(':')); colon > 0) {
15 ✔
1121
    if (m_displayPanel->hides(line.left(colon).trimmed(), s)) {
39 ✔
1122
      return line.left(colon + 1) + QLatin1Char(' ') + hidden;
4 ✔
1123
    }
1124
  }
1125
  return line;
1126
}
1127

1128
void MainWindow::onGrepFinished(
21 ✔
1129
    const QList<QPair<QString, QStringList>> &results) {
1130
  // Both backends stay connected, each with its own search: a search the
1131
  // other backend was still running when Settings switched backends is not
1132
  // this one, whatever the controller's state, and searched another store.
1133
  // Dropped before it can end (or be taken for) the current search.
1134
  if (const QObject *from = sender();
21 ✔
1135
      from != nullptr && from != QtPassSettings::getPass()) {
21 ✔
1136
    return;
11 ✔
1137
  }
1138
  const GrepSearchController::FinishOutcome outcome = m_grep.finishSearch();
1139
  if (outcome.restoreCursor) {
20 ✔
1140
    QApplication::restoreOverrideCursor();
2 ✔
1141
  }
1142
  // Re-enable the UI before the discard check so a cancelled search can never
1143
  // leave controls disabled.
1144
  setUiElementsEnabled(true);
20 ✔
1145
  if (outcome.discard) {
20 ✔
1146
    return;
1147
  }
1148
  if (!m_grep.inGrepMode())
12 ✔
1149
    return;
1150
  ui->grepResultsList->clear();
12 ✔
1151
  if (results.isEmpty()) {
12 ✔
1152
    ui->statusBar->showMessage(tr("No matches found."), 3000);
2 ✔
1153
    showContentResults(false);
2 ✔
1154
    return;
2 ✔
1155
  }
1156
  const AppSettings s = QtPassSettings::load();
10 ✔
1157
  const bool hideContent = s.hideContent;
10 ✔
1158
  refreshMarkedSecrets(s);
10 ✔
1159
  int totalLines = 0;
1160
  int entries = 0;
1161
  bool stopped = false;
1162
  for (const auto &pair : results) {
43 ✔
1163
    if (NativeGrep::isStoppedMarker(pair)) {
33 ✔
1164
      stopped = true;
1165
      continue;
×
1166
    }
1167
    ++entries;
33 ✔
1168
    auto *entryItem = new QTreeWidgetItem(ui->grepResultsList);
33 ✔
1169
    entryItem->setText(0, pair.first);
33 ✔
1170
    entryItem->setData(0, Qt::UserRole, pair.first);
33 ✔
1171
    for (const QString &line : pair.second) {
76 ✔
1172
      auto *lineItem = new QTreeWidgetItem(entryItem);
43 ✔
1173
      // The marker is no content: shown as it is with hidden content too,
1174
      // and not counted as a match.
1175
      if (NativeGrep::isMoreMarker(line)) {
43 ✔
1176
        lineItem->setText(0, tr("… more matches in this entry"));
×
1177
      } else {
1178
        lineItem->setText(0, hideContent ? "***" + tr("Content hidden") + "***"
86 ✔
1179
                                         : grepLineForDisplay(line, s));
1180
        ++totalLines;
43 ✔
1181
      }
1182
      lineItem->setData(0, Qt::UserRole, pair.first);
43 ✔
1183
    }
1184
  }
1185
  ui->grepResultsList->expandAll();
10 ✔
1186
  showContentResults(true);
10 ✔
1187
  if (stopped) {
10 ✔
1188
    // The search stopped there; more entries may match.
1189
    ui->statusBar->showMessage(
×
1190
        tr("Showing the first %n match(es); search for something narrower "
×
1191
           "to see the rest.",
1192
           nullptr, totalLines),
1193
        10000);
1194
  } else {
1195
    ui->statusBar->showMessage(tr("Found %n match(es)", nullptr, totalLines) +
30 ✔
1196
                                   " " +
10 ✔
1197
                                   tr("in %n entr(ies).", nullptr, entries),
20 ✔
1198
                               3000);
1199
  }
1200
  // The results' own deadline: restarting the entry's timer here gave an
1201
  // entry still on the panel a second period, and an operation that stops
1202
  // the entry's timer left the results up with none.
1203
  if (s.useAutoclearPanel)
10 ✔
1204
    clearResultsTimer.start();
3 ✔
1205
}
10 ✔
1206

1207
void MainWindow::on_grepResultsList_itemClicked(QTreeWidgetItem *item,
2 ✔
1208
                                                int /*column*/) {
1209
  const AppSettings s = QtPassSettings::load();
2 ✔
1210
  const QString entry = item->data(0, Qt::UserRole).toString();
2 ✔
1211
  if (entry.isEmpty())
2 ✔
1212
    return;
1213
  const QString fullPath =
1214
      QDir::cleanPath(Util::joinPath(s.passStore, entry + ".gpg"));
2 ✔
1215
  // Persistent: setCurrentIndex() runs the selection handlers, which can
1216
  // change the model before the click is handled.
1217
  const QPersistentModelIndex proxyIndex(m_tree->indexFor(fullPath));
2 ✔
1218
  if (!proxyIndex.isValid())
2 ✔
1219
    return;
1220
  ui->treeView->setCurrentIndex(proxyIndex);
2 ✔
1221
  if (!proxyIndex.isValid())
2 ✔
1222
    return;
1223
  on_treeView_clicked(proxyIndex);
2 ✔
1224
  if (s.hideContent || s.useAutoclearPanel)
2 ✔
1225
    ui->grepResultsList->clear();
1 ✔
1226
  showContentResults(false);
2 ✔
1227
  ui->treeView->scrollTo(proxyIndex);
2 ✔
1228
  ui->treeView->setFocus();
2 ✔
1229
}
4 ✔
1230

1231
void MainWindow::showContentResults(bool shown) {
37 ✔
1232
  ui->grepResultsList->setVisible(shown);
37 ✔
1233
  ui->treeView->setVisible(!shown);
37 ✔
1234
  if (shown) {
37 ✔
1235
    // The tree's current entry is out of sight: Delete, Edit and OTP would
1236
    // act on it, not on a result. Opening a result shows the tree again.
1237
    ui->actionDelete->setEnabled(false);
10 ✔
1238
    ui->actionEdit->setEnabled(false);
10 ✔
1239
    updateOtpButtonVisibility(false);
10 ✔
1240
  } else if (ui->treeView->selectionModel()->hasSelection()) {
27 ✔
1241
    // Only for an entry still selected: with nothing selected there is no
1242
    // entry for Edit and Delete to act on.
1243
    setUiElementsEnabled(m_uiEnabled);
8 ✔
1244
  }
1245
}
37 ✔
1246

1247
void MainWindow::cancelContentSearch() {
28 ✔
1248
  QtPassSettings::getRealPass()->CancelGrep();
28 ✔
1249
  QtPassSettings::getImitatePass()->CancelGrep();
28 ✔
1250
}
28 ✔
1251

1252
void MainWindow::selectFirstFile() {
34 ✔
1253
  // The entry named exactly as typed wins: with folders sorted first, the
1254
  // depth-first walk found team/bank before bank.
1255
  QModelIndex index = exactMatch();
34 ✔
1256
  if (!index.isValid()) {
1257
    index = firstFile(m_tree->rootIndex());
17 ✔
1258
  }
1259
  ui->treeView->setCurrentIndex(index);
34 ✔
1260
}
34 ✔
1261

1262
namespace {
1263
/**
1264
 * @brief @p path with each part below @p store spelled as stored on disk.
1265
 *
1266
 * Where the file system ignores case, "Bank.gpg" exists while the file is
1267
 * bank.gpg, and the tree knows the entry only by that spelling.
1268
 * @param store The store folder.
1269
 * @param path An existing file in the store.
1270
 * @return @p path itself when every part is spelled as stored, otherwise
1271
 *         the path with the stored spelling.
1272
 */
1273
auto spelledAsStored(const QString &store, const QString &path) -> QString {
33 ✔
1274
  const QStringList parts = QDir(store).relativeFilePath(path).split(
66 ✔
1275
      QLatin1Char('/'), Qt::SkipEmptyParts);
33 ✔
1276
  QDir dir(store);
33 ✔
1277
  bool respelled = false;
1278
  for (int i = 0; i < parts.size(); ++i) {
36 ✔
1279
    const bool leaf = i == parts.size() - 1;
36 ✔
1280
    const QStringList names =
1281
        dir.entryList((leaf ? QDir::Files : QDir::Dirs) | QDir::Hidden |
36 ✔
1282
                      QDir::NoDotAndDotDot);
39 ✔
1283
    QString name = parts.at(i);
1284
    if (!names.contains(name)) {
36 ✔
1285
      const auto stored = std::find_if(
×
1286
          names.cbegin(), names.cend(), [&name](const QString &candidate) {
1287
            return candidate.compare(name, Qt::CaseInsensitive) == 0;
×
1288
          });
1289
      if (stored == names.cend()) {
×
1290
        return path;
1291
      }
1292
      name = *stored;
×
1293
      respelled = true;
1294
    }
1295
    if (leaf) {
36 ✔
1296
      return respelled ? QDir::cleanPath(Util::joinPath(dir.path(), name))
66 ✔
1297
                       : path;
×
1298
    }
1299
    if (!dir.cd(name)) {
3 ✔
1300
      return path;
1301
    }
1302
  }
1303
  return path;
1304
}
33 ✔
1305
} // namespace
1306

1307
auto MainWindow::exactMatchPath() -> QString {
52 ✔
1308
  const QString text = QDir::fromNativeSeparators(ui->lineEdit->text());
104 ✔
1309
  const QString store = QtPassSettings::getPassStore();
104 ✔
1310
  // A name may begin or end with a space: " bank" is that entry, not bank.
1311
  // Only when no entry is named so are spaces around the text dropped.
1312
  for (const QString &typed : {text, text.trimmed()}) {
196 ✔
1313
    if (typed.isEmpty()) {
73 ✔
1314
      continue;
×
1315
    }
1316
    const QString path =
1317
        QDir::cleanPath(Util::joinPath(store, typed + QStringLiteral(".gpg")));
146 ✔
1318
    if (PathValidator::isPathInStore(store, path) && QFileInfo(path).isFile()) {
73 ✔
1319
      return spelledAsStored(store, path);
33 ✔
1320
    }
1321
  }
156 ✔
1322
  return {};
19 ✔
1323
}
1324

1325
auto MainWindow::exactMatch() -> QModelIndex {
48 ✔
1326
  const QString path = exactMatchPath();
48 ✔
1327
  if (path.isEmpty()) {
48 ✔
1328
    return {};
18 ✔
1329
  }
1330
  // indexFor() maps through the filter: a row the filter hides is no match.
1331
  const QModelIndex index = m_tree->indexFor(path);
30 ✔
1332
  if (!index.isValid() || !m_tree->fileInfo(index).isFile()) {
53 ✔
1333
    return {};
7 ✔
1334
  }
1335
  return index;
23 ✔
1336
}
1337

1338
void MainWindow::applySearchText(const QString &text) {
9 ✔
1339
  // A name search: content search, left on, kept its results over the tree
1340
  // and ignored the text.
1341
  if (ui->grepButton->isChecked()) {
9 ✔
1342
    ui->grepButton->setChecked(false);
1 ✔
1343
  }
1344
  delete m_pendingOpen;
9 ✔
1345
  ui->lineEdit->setText(text);
9 ✔
1346
  // Filter now, not after the search delay: the timer would leave the tree
1347
  // as the previous text filtered it.
1348
  searchTimer.stop();
9 ✔
1349
  onTimeoutSearch();
9 ✔
1350
  if (const QModelIndex exact = exactMatch(); exact.isValid()) {
9 ✔
1351
    openExactMatch(exact);
5 ✔
1352
    return;
5 ✔
1353
  }
1354
  // The tree loads folders in the background: at start, or right after the
1355
  // window is shown again, an entry that exists may not be in it yet. Try
1356
  // again as folders finish loading, for a few seconds, unless the search
1357
  // text changes meanwhile: any change ends the wait, even one typed back to
1358
  // this text, which is a new search that has not asked to open anything.
1359
  if (exactMatchPath().isEmpty()) {
8 ✔
1360
    return;
1361
  }
1362
  auto *pending = new QObject(this);
3 ✔
1363
  m_pendingOpen = pending;
1364
  QTimer::singleShot(5000, pending, &QObject::deleteLater);
3 ✔
1365
  // Disconnected at once: with deleteLater() alone, a folder that finished
1366
  // loading before the deletion still ran the open, or ran it twice.
1367
  const auto stop = [this, pending] {
2 ✔
1368
    disconnect(&m_tree->fileSystem(), nullptr, pending, nullptr);
2 ✔
1369
    disconnect(ui->lineEdit, nullptr, pending, nullptr);
2 ✔
1370
    pending->deleteLater();
2 ✔
1371
  };
5 ✔
1372
  connect(ui->lineEdit, &QLineEdit::textChanged, pending, stop);
3 ✔
1373
  connect(&m_tree->fileSystem(), &QFileSystemModel::directoryLoaded, pending,
3 ✔
1374
          [this, stop](const QString &) {
6 ✔
1375
            searchTimer.stop();
5 ✔
1376
            onTimeoutSearch();
5 ✔
1377
            if (const QModelIndex exact = exactMatch(); exact.isValid()) {
5 ✔
1378
              stop();
1 ✔
1379
              openExactMatch(exact);
1 ✔
1380
            }
1381
          });
5 ✔
1382
}
1383

1384
void MainWindow::openExactMatch(const QModelIndex &index) {
6 ✔
1385
  // Made current here, not left to the filter pass before: the tree may have
1386
  // moved its current row since, and with none on_treeView_clicked() only
1387
  // names the entry without decrypting it.
1388
  ui->treeView->setCurrentIndex(index);
6 ✔
1389
  on_treeView_clicked(index);
6 ✔
1390
}
6 ✔
1391

1392
auto MainWindow::firstFile(QModelIndex parentIndex) -> QModelIndex {
26 ✔
1393
  StoreModel &proxy = m_tree->proxy();
26 ✔
1394
  int numRows = proxy.rowCount(parentIndex);
26 ✔
1395
  for (int row = 0; row < numRows; ++row) {
33 ✔
1396
    QModelIndex index = proxy.index(row, 0, parentIndex);
24 ✔
1397
    if (m_tree->fileInfo(index).isFile()) {
24 ✔
1398
      return index;
17 ✔
1399
    }
1400
    if (proxy.hasChildren(index)) {
14 ✔
1401
      QModelIndex childFile = firstFile(index);
9 ✔
1402
      if (childFile.isValid())
1403
        return childFile;
7 ✔
1404
    }
1405
  }
1406
  return QModelIndex();
9 ✔
1407
}
1408

1409
// Guards the input dialogs (create, move, rename) against names like
1410
// "../../etc/passwd" or absolute paths escaping the store root.
1411
auto MainWindow::confirmPathInStore(const QString &candidate) -> bool {
11 ✔
1412
  if (PathValidator::isPathInStore(QtPassSettings::getPassStore(), candidate)) {
22 ✔
1413
    return true;
1414
  }
1415
  QMessageBox::warning(this, tr("Invalid name"),
9 ✔
1416
                       tr("That name would resolve outside the password "
3 ✔
1417
                          "store. Please choose a different name."));
1418
  return false;
3 ✔
1419
}
1420

1421
void MainWindow::setPassword(const QString &file, bool isNew) {
8 ✔
1422
  const AppSettings s = QtPassSettings::load();
8 ✔
1423
  PasswordDialog d(QtPassSettings::getPass(), s, file, isNew, this);
8 ✔
1424
  // A copy out of the editor is autocleared like one from the display.
1425
  connect(&d, &PasswordDialog::copied, &m_qtPass->clipboard(),
8 ✔
1426
          &ClipboardManager::trackCopied);
8 ✔
1427

1428
  if (isNew) {
8 ✔
1429
    const QString storePath = s.passStore;
1430
    QString folder = m_tree->currentDir(false);
2 ✔
1431
    if (folder.isEmpty()) {
2 ✔
1432
      folder = storePath;
×
1433
    }
1434
    // A tree folder that is, or lies behind, a symbolic link is not part of the
1435
    // store (Users and re-encryption refuse it the same way). Adding here would
1436
    // silently fall back to the store root and encrypt the new entry to the
1437
    // root's recipients - which a co-writer who planted the link, and is on the
1438
    // root list but not the real folder's, can then read. Refuse instead.
1439
    if (refuseLinkedFolder(folder)) {
2 ✔
1440
      return;
1441
    }
1442
    // Folders to pick from, the tree's current one preselected. Real folders
1443
    // only: a linked or junctioned one would write the entry outside the store.
1444
    QStringList folders{QString()};
2 ✔
1445
    const QStringList found = Util::directoriesUnder(storePath);
1 ✔
1446
    for (const QString &path : found) {
18 ✔
1447
      const QString rel = QDir(storePath).relativeFilePath(path);
17 ✔
1448
      if (!rel.startsWith(u'.') && !rel.contains(QStringLiteral("/."))) {
51 ✔
1449
        folders << rel;
1450
      }
1451
    }
1452
    std::sort(folders.begin() + 1, folders.end());
1 ✔
1453
    d.setNewEntryLocation(storePath, folders,
1 ✔
1454
                          QDir(storePath).relativeFilePath(folder));
2 ✔
1455
    QHash<QString, QStringList> templates =
1456
        TemplateIO::readTemplates(storePath);
1 ✔
1457
    if (!templates.isEmpty()) {
1458
      QString defaultTemplate =
1459
          TemplateIO::getFolderTemplate(folder, storePath);
1 ✔
1460
      d.setAvailableTemplates(templates, defaultTemplate);
1 ✔
1461
    }
1462
  }
1 ✔
1463

1464
  if (!d.exec()) {
7 ✔
1465
    ui->treeView->setFocus();
6 ✔
1466
  }
1467
}
8 ✔
1468

1469
void MainWindow::addPassword() { setPassword(QString()); }
4 ✔
1470

1471
auto MainWindow::confirmDeletion(const QString &file, bool isDir) -> bool {
8 ✔
1472
  const QString path = QDir::separator() + file;
8 ✔
1473
  // As the platform writes paths: backslashes only on Windows, never a mix.
1474
  // On one line: a name from the store may hold a line feed (Unix allows
1475
  // one), which drew lines of its own into the question.
1476
  const QString shown =
1477
      Util::displayable(QDir::toNativeSeparators(path), false);
8 ✔
1478
  if (!isDir) {
8 ✔
1479
    return PlainMessageBox::askYes(
2 ✔
1480
        this, tr("Delete password?"),
2 ✔
1481
        tr("Are you sure you want to delete %1?").arg(shown));
4 ✔
1482
  }
1483
  // Whole sentences, not a question stitched from pieces: a verb-final
1484
  // language cannot put the rest of the question after the path.
1485
  // Plain text, as every box quoting the store: the path is a name other
1486
  // writers control, and as rich text "a  b" would also show as "a b".
1487
  QString question =
1488
      tr("Are you sure you want to delete %1 and the whole content?")
×
1489
          .arg(shown);
6 ✔
1490
  // A link, junction or special file inside is as unexpected as a stray
1491
  // plain file: the walker leaves them out of content and reports them.
1492
  QStringList skipped;
6 ✔
1493
  QStringList unlisted;
6 ✔
1494
  const QString root = m_tree->fileSystem().rootPath();
6 ✔
1495
  const QStringList content = Util::regularFilesUnder(
18 ✔
1496
      root + path, {QStringLiteral("*")}, &skipped, false, &unlisted);
18 ✔
1497
  const bool unexpected =
1498
      !skipped.isEmpty() ||
6 ✔
1499
      std::any_of(content.cbegin(), content.cend(), [](const QString &entry) {
6 ✔
1500
        return QFileInfo(entry).suffix() != QLatin1String("gpg");
8 ✔
1501
      });
1502
  if (unexpected) {
1503
    question += QStringLiteral("\n\n") +
1 ✔
1504
                tr("Attention: there are unexpected files in the given "
1 ✔
1505
                   "folder, check them before continuing.");
1 ✔
1506
  }
1507
  // A folder the walk cannot read is not empty but unknown: whatever it
1508
  // holds goes too, or stays behind when the removal cannot list it.
1509
  if (unlisted.size() == 1) {
6 ✔
1510
    //: %1 is a folder in the password store, such as /Work/bank.
1511
    const QString one =
1512
        tr("%1 could not be read, so what it holds is unknown.")
1 ✔
1513
            .arg(Util::displayable(
1 ✔
1514
                QDir::toNativeSeparators(
1 ✔
1515
                    QDir::separator() +
1 ✔
1516
                    QDir(root).relativeFilePath(unlisted.first())),
2 ✔
1517
                false));
3 ✔
1518
    question += QStringLiteral("\n\n") + one;
2 ✔
1519
  } else if (unlisted.size() > 1) {
5 ✔
1520
    //: Only shown for two or more folders; one folder is named instead.
1521
    const QString many =
1522
        tr("%n folder(s) in it could not be read, so what they hold "
1523
           "is unknown.",
1524
           nullptr, static_cast<int>(unlisted.size()));
1 ✔
1525
    question += QStringLiteral("\n\n") + many;
2 ✔
1526
  }
1527
  return PlainMessageBox::askYes(this, tr("Delete folder?"), question);
12 ✔
1528
}
1529

1530
auto MainWindow::confirmLinkRemoval(const QString &file) -> bool {
1 ✔
1531
  // Only the link goes (ImitatePass::Remove unlinks it); nothing behind it
1532
  // is looked at or mentioned.
1533
  return PlainMessageBox::askYes(
1 ✔
1534
      this, tr("Delete link?"),
1 ✔
1535
      tr("%1 is a symbolic link or junction. Remove the link? What it "
1 ✔
1536
         "points to is left alone.")
1537
          .arg(Util::displayable(QDir::separator() + file, false)));
2 ✔
1538
}
1539

1540
void MainWindow::onDelete() {
13 ✔
1541
  const QModelIndex currentIndex = ui->treeView->currentIndex();
13 ✔
1542
  // While content search results hide the tree, its current entry is not
1543
  // what the user looks at (the Delete key comes here directly).
1544
  if (!currentIndex.isValid() || ui->treeView->isHidden()) {
11 ✔
1545
    // Otherwise the whole password directory would be deleted (#556).
1546
    return;
10 ✔
1547
  }
1548

1549
  const bool isDir = !m_tree->fileInfo(currentIndex).isFile();
9 ✔
1550
  const QString file =
1551
      isDir ? m_tree->currentDir(true) : getFile(currentIndex, true);
9 ✔
1552
  const QString folder =
1553
      m_tree->fileSystem().rootPath() + QDir::separator() + file;
9 ✔
1554
  const bool linkedFolder = isDir && Util::isLinkedFolder(folder);
9 ✔
1555

1556
  if (!linkedFolder && refuseLinkedFolder(folder)) {
8 ✔
1557
    // Behind a link: deleting would reach outside the store.
1558
    return;
1559
  }
1560
  const bool confirmed =
1561
      linkedFolder ? confirmLinkRemoval(file) : confirmDeletion(file, isDir);
9 ✔
1562
  if (!confirmed) {
9 ✔
1563
    return;
1564
  }
1565
  QtPassSettings::getPass()->Remove(file, isDir);
6 ✔
1566
}
1567

1568
void MainWindow::cancelOtpRequest() {
91 ✔
1569
  m_otpRequestFile.clear();
91 ✔
1570
  m_copyRequestFile.clear();
91 ✔
1571
}
91 ✔
1572

1573
void MainWindow::onOperationError() {
34 ✔
1574
  cancelOtpRequest();
34 ✔
1575
  // executeWrapperStarted() emptied the panel and the browser when the
1576
  // operation started (a refusal says so too); what is left to forget is
1577
  // which entry the panel was about to show.
1578
  m_shownFile.clear();
34 ✔
1579
  // A save's refresh waiting for its push is dropped: it would clear the
1580
  // push's error (or whatever failed before it) from the browser.
1581
  m_refreshAfterPush.clear();
34 ✔
1582
  m_refreshAfterPushOwner = nullptr;
1583
}
34 ✔
1584

1585
// Derives the code in-process from one decrypt, so it works with either
1586
// backend on every platform; otpFromFileToClipboard() finishes the job.
1587
void MainWindow::onOtp() {
12 ✔
1588
  if (ui->treeView->isHidden()) {
12 ✔
1589
    return;
4 ✔
1590
  }
1591
  QString file = getFile(ui->treeView->currentIndex(), true);
11 ✔
1592
  if (file.isEmpty()) {
11 ✔
1593
    flashText(tr("No password selected for OTP generation"), true);
1 ✔
1594
    return;
1 ✔
1595
  }
1596
  if (!QtPassSettings::isUseOtp()) {
10 ✔
1597
    // Normally unreachable (the action is hidden), but never fail silently.
1598
    flashText(tr("No OTP code found in this password entry"), true);
1 ✔
1599
    return;
1 ✔
1600
  }
1601

1602
  // Fast path: the panel shows a live code, so no decrypt, and one clipboard
1603
  // write (two setMimeData calls in one turn can empty the Windows
1604
  // clipboard). Only for *this* entry: arrow keys and right-click move
1605
  // currentIndex without QTreeView::clicked, so the code may be another's.
1606
  const QString shown =
1607
      (m_shownFile == file) ? m_displayPanel->currentOtpCode() : QString();
9 ✔
1608
  if (!shown.isEmpty()) {
9 ✔
1609
    m_qtPass->clipboard().copyText(shown);
1 ✔
1610
    showStatusMessage(tr("OTP code copied to clipboard"));
2 ✔
1611
    return;
1612
  }
1613

1614
  // Fallback: decrypt once. The request file keeps passShowHandler from
1615
  // copying the password and tells otpFromFileToClipboard its answer.
1616
  m_otpRequestFile = file;
8 ✔
1617
  setUiElementsEnabled(false);
8 ✔
1618
  // Keep the marker in step so a second request takes the fast path; safe as
1619
  // executeWrapperStarted() clears the panel, so a failed decrypt shows none.
1620
  m_shownFile = file;
8 ✔
1621
  QtPassSettings::getPass()->Show(file);
16 ✔
1622
}
1623

1624
void MainWindow::onEdit() {
1 ✔
1625
  if (ui->treeView->isHidden()) {
1 ✔
1626
    return;
1 ✔
1627
  }
1628
  QString file = getFile(ui->treeView->currentIndex(), true);
×
1629
  editPassword(file);
×
1630
}
1631

1632
void MainWindow::onUsers() {
2 ✔
1633
  const QString dir = m_tree->currentDir(false);
2 ✔
1634
  if (refuseLinkedFolder(dir)) {
2 ✔
1635
    return;
1636
  }
1637

1638
  UsersDialog d(QtPassSettings::getPass(), QtPassSettings::load(), dir, this);
1 ✔
1639
  if (!d.exec()) {
1 ✔
1640
    ui->treeView->setFocus();
1 ✔
1641
  }
1642
}
1 ✔
1643

1644
void MainWindow::messageAvailable(const QString &message) {
10 ✔
1645
  show();
10 ✔
1646
  raise();
10 ✔
1647
  if (message.isEmpty()) {
10 ✔
1648
    focusInput();
1 ✔
1649
  } else {
1650
    ui->treeView->expandAll();
9 ✔
1651
    applySearchText(message);
9 ✔
1652
  }
1653
}
10 ✔
1654

1655
void MainWindow::updateProfileBox() {
209 ✔
1656
  const Profiles profiles = QtPassSettings::getProfiles();
209 ✔
1657
  bool activeGone = false;
1658

1659
  if (profiles.isEmpty()) {
7 ✔
1660
    ui->profileWidget->hide();
202 ✔
1661
  } else {
1662
    ui->profileWidget->show();
7 ✔
1663
    // A refill is no choice of the user's: clearing and adding items moves
1664
    // the current text, which would otherwise switch profiles.
1665
    const QSignalBlocker quiet(ui->profileBox);
7 ✔
1666
    ui->profileBox->clear();
7 ✔
1667
    for (auto i = profiles.cbegin(); i != profiles.cend(); ++i) {
19 ✔
1668
      if (!i.key().isEmpty()) {
12 ✔
1669
        ui->profileBox->addItem(i.key());
12 ✔
1670
      }
1671
    }
1672
    ui->profileBox->model()->sort(0);
7 ✔
1673
    int index = ui->profileBox->findText(QtPassSettings::getProfile());
14 ✔
1674
    if (index != -1) { //  -1 for not found
7 ✔
1675
      ui->profileBox->setCurrentIndex(index);
6 ✔
1676
    } else if (ui->profileBox->count() > 0) {
1 ✔
1677
      // The active profile is gone (removed in Settings): the box shows the
1678
      // first one, and the settings and backend must follow it, or the
1679
      // removed profile's store stays in use behind it.
1680
      ui->profileBox->setCurrentIndex(0);
1 ✔
1681
      activeGone = true;
1682
    }
1683
  }
7 ✔
1684
  if (activeGone) {
7 ✔
1685
    on_profileBox_currentTextChanged(ui->profileBox->currentText());
2 ✔
1686
  }
1687
  updateProfileBoxEnabled();
209 ✔
1688
}
209 ✔
1689

1690
void MainWindow::updateProfileBoxEnabled() {
703 ✔
1691
  // No profile switch while anything of the store runs or waits: the
1692
  // backend's store and environment would change under it, and what is
1693
  // still queued (a push after a save, say) would finish for the other
1694
  // profile (#2071). Asked of the backend, not only of the interface: the
1695
  // watchdog releases the interface while a slow gpg or git still runs.
1696
  // Every backend: one kept from before a switch of backend may still
1697
  // run what was queued on it.
1698
  ui->profileBox->setEnabled(m_uiEnabled && ui->profileBox->count() > 1 &&
1,408 ✔
1699
                             QtPassSettings::backendsIdle());
14 ✔
1700
}
703 ✔
1701

1702
void MainWindow::on_profileBox_currentTextChanged(const QString &name) {
6 ✔
1703
  if (m_freshStart || name == QtPassSettings::getProfile()) {
18 ✔
1704
    return;
1 ✔
1705
  }
1706
  // The box is disabled while anything runs; should a change come through
1707
  // anyway, the active profile stays and the box says so again.
1708
  if (!m_uiEnabled || !QtPassSettings::backendsIdle()) {
5 ✔
1709
    const QSignalBlocker quiet(ui->profileBox);
×
1710
    ui->profileBox->setCurrentText(QtPassSettings::getProfile());
×
1711
    return;
1712
  }
×
1713
  // A content search runs outside the queue: leaving grep mode cancels it,
1714
  // so its results for the old store are dropped, not shown for the new.
1715
  if (m_grep.inGrepMode()) {
5 ✔
1716
    ui->grepButton->setChecked(false);
1 ✔
1717
  }
1718

1719
  ui->lineEdit->clear();
5 ✔
1720

1721
  const Profile prof = QtPassSettings::getProfiles().value(name);
10 ✔
1722
  AppSettings s = QtPassSettings::load();
5 ✔
1723
  s.activeProfile = name;
5 ✔
1724
  s.passStore = prof.path;
5 ✔
1725
  s.passSigningKey = prof.signingKey;
5 ✔
1726
  // A profile without its own Git flags keeps the global values.
1727
  s.useGit = prof.useGit.value_or(s.useGit);
5 ✔
1728
  s.autoPush = prof.autoPush.value_or(s.autoPush);
5 ✔
1729
  s.autoPull = prof.autoPull.value_or(s.autoPull);
5 ✔
1730
  QtPassSettings::save(s);
5 ✔
1731
  ui->statusBar->showMessage(tr("Profile changed to %1").arg(name), 2000);
10 ✔
1732

1733
  QtPassSettings::getPass()->updateEnv();
5 ✔
1734

1735
  m_tree->setStore(QtPassSettings::getPassStore());
10 ✔
1736
  deselect();
5 ✔
1737
  ui->treeView->setCurrentIndex(QModelIndex());
5 ✔
1738
}
5 ✔
1739

1740
void MainWindow::initTrayIcon() {
3 ✔
1741
  m_tray = new TrayIcon(this);
3 ✔
1742
  if (!m_tray->getIsAllocated()) {
3 ✔
1743
    destroyTrayIcon();
3 ✔
1744
    return;
3 ✔
1745
  }
1746
#ifndef Q_OS_MACOS
1747
  m_tray->addToggle(ui->actionShowMenuBar);
×
1748
#endif
1749
}
1750

1751
void MainWindow::destroyTrayIcon() {
3 ✔
1752
  delete m_tray;
3 ✔
1753
  m_tray = nullptr;
3 ✔
1754
}
3 ✔
1755

1756
void MainWindow::closeEvent(QCloseEvent *event) {
4 ✔
1757
  // Save in both branches: a tray user only ever hides the window, and
1758
  // used to quit through the tray menu with nothing ever written.
1759
  saveWindowState();
4 ✔
1760
  // Only with a tray icon to come back from: without one (none asked for, or
1761
  // no system tray in this session) a hidden QtPass ran on invisibly, with the
1762
  // last entry in its window and the password on the clipboard.
1763
  if (QtPassSettings::isHideOnClose() && m_tray != nullptr) {
8 ✔
1764
    this->hide();
×
1765
    event->ignore();
1766
  } else {
1767
    m_qtPass->clipboard().clear();
4 ✔
1768
    event->accept();
1769
    // A visible QSystemTrayIcon keeps the application alive, so
1770
    // quitOnLastWindowClosed never fires; quit explicitly.
1771
    QApplication::quit();
4 ✔
1772
  }
1773
}
4 ✔
1774

1775
auto MainWindow::eventFilter(QObject *obj, QEvent *event) -> bool {
8,389 ✔
1776
  if ((obj == ui->toolBar || obj == menuBar()) &&
8,389 ✔
1777
      event->type() == QEvent::PaletteChange) {
1778
    // Breeze gives these bars a "header" palette and, after a runtime
1779
    // light/dark switch, stamps the previous theme's colours back from a
1780
    // cached kdeglobals, hiding the toolbar icons. Deferred so we never
1781
    // re-enter the style while it is still applying its palette.
1782
    QTimer::singleShot(0, this, &MainWindow::dropStaleToolsAreaPalettes);
36 ✔
1783
  }
1784
  if (obj == ui->lineEdit && event->type() == QEvent::KeyPress) {
8,389 ✔
1785
    auto *key = dynamic_cast<QKeyEvent *>(event);
5 ✔
1786
    if (key != nullptr && key->key() == Qt::Key_Down) {
5 ✔
1787
      // Into whichever list is in sight: the tree, or content search results.
1788
      // Focus makes the list's first item current.
1789
      if (ui->treeView->isHidden()) {
2 ✔
1790
        ui->grepResultsList->setFocus();
1 ✔
1791
      } else {
1792
        ui->treeView->setFocus();
1 ✔
1793
      }
1794
    }
1795
    // Return ends at the search box: QLineEdit emits returnPressed() and
1796
    // leaves the key unaccepted, so keyPressEvent() would open the tree's
1797
    // current entry as well. In content search that is an entry nobody
1798
    // asked for; by name, the first hit a second time.
1799
    if (key != nullptr &&
5 ✔
1800
        (key->key() == Qt::Key_Return || key->key() == Qt::Key_Enter)) {
2 ✔
1801
      ui->lineEdit->event(event);
3 ✔
1802
      event->accept();
1803
      return true;
3 ✔
1804
    }
1805
  }
1806
  return QObject::eventFilter(obj, event);
8,386 ✔
1807
}
1808

1809
// Only once the application palette changed (see m_themeSwitched): a bar
1810
// whose active Window lightness is far from the application's shows the
1811
// other theme.
1812
void MainWindow::dropStaleToolsAreaPalettes() {
31 ✔
1813
  if (!m_themeSwitched) {
31 ✔
1814
    return;
1815
  }
1816
  constexpr int kStaleToolsAreaLightness = 64;
1817
  // The active group on both sides: a bar's palette() reads the inactive
1818
  // group while another window has focus (the settings app, during a theme
1819
  // switch), and Breeze gives the header set different inactive colours.
1820
  const int appLightness = QApplication::palette()
54 ✔
1821
                               .color(QPalette::Active, QPalette::Window)
1822
                               .lightness();
27 ✔
1823
  for (QWidget *bar : {static_cast<QWidget *>(ui->toolBar),
108 ✔
1824
                       static_cast<QWidget *>(menuBar())}) {
81 ✔
1825
    if (!bar->testAttribute(Qt::WA_SetPalette)) {
54 ✔
1826
      continue;
48 ✔
1827
    }
1828
    const int barLightness =
1829
        bar->palette().color(QPalette::Active, QPalette::Window).lightness();
12 ✔
1830
    if (qAbs(barLightness - appLightness) <= kStaleToolsAreaLightness) {
6 ✔
1831
      continue;
2 ✔
1832
    }
1833
    bar->setPalette(QPalette());
4 ✔
1834
    // Both bars are transparent and the style paints the tools area from the
1835
    // stale palette, so fill our own. Window, not their Button role, which is
1836
    // not the window colour in either theme.
1837
    bar->setBackgroundRole(QPalette::Window);
4 ✔
1838
    bar->setAutoFillBackground(true);
4 ✔
1839
  }
1840
}
1841

1842
void MainWindow::keyPressEvent(QKeyEvent *event) {
25 ✔
1843
  switch (event->key()) {
25 ✔
1844
  case Qt::Key_Delete:
2 ✔
1845
    onDelete();
2 ✔
1846
    break;
2 ✔
1847
  case Qt::Key_Return:
2 ✔
1848
  case Qt::Key_Enter:
1849
    // While content search results hide the tree, its current entry is not
1850
    // what the user looks at: Return on a result opens that result.
1851
    if (ui->treeView->isHidden()) {
2 ✔
1852
      QTreeWidgetItem *result = ui->grepResultsList->currentItem();
1 ✔
1853
      if (result != nullptr && ui->grepResultsList->hasFocus()) {
1 ✔
1854
        on_grepResultsList_itemClicked(result, 0);
1 ✔
1855
      }
1856
      break;
1857
    }
1858
    if (m_tree->proxy().rowCount() > 0) {
1 ✔
1859
      on_treeView_clicked(ui->treeView->currentIndex());
1 ✔
1860
    }
1861
    break;
1862
  case Qt::Key_Escape:
3 ✔
1863
    ui->lineEdit->clear();
3 ✔
1864
    break;
3 ✔
1865
  default:
1866
    break;
1867
  }
1868
}
25 ✔
1869

1870
void MainWindow::addShareMenu(QMenu &contextMenu, const AppSettings &s) {
10 ✔
1871
  const QString dirPath = QDir::cleanPath(m_tree->currentDir(false));
10 ✔
1872
  auto *shareMenu = new QMenu(tr("Share"), &contextMenu);
10 ✔
1873
  contextMenu.addMenu(shareMenu);
10 ✔
1874

1875
  const QString gpgIdPath = Pass::getGpgIdPath(dirPath, s.passStore);
10 ✔
1876
  const bool gpgIdExists = !gpgIdPath.isEmpty() && QFile(gpgIdPath).exists();
10 ✔
1877
  const QString exePath = s.usePass ? s.passExecutable : s.gpgExecutable;
10 ✔
1878
  const bool gpgAvailable =
1879
      !exePath.isEmpty() &&
20 ✔
1880
      (Executor::parseWslCommand(exePath) || QFile(exePath).exists());
20 ✔
1881

1882
  QAction *reencrypt = shareMenu->addAction(tr("Re-encrypt all passwords"));
10 ✔
1883
  reencrypt->setEnabled(gpgIdExists && gpgAvailable);
10 ✔
1884
  connect(reencrypt, &QAction::triggered, this,
10 ✔
1885
          [this, dirPath]() { reencryptPath(dirPath); });
34 ✔
1886

1887
  QAction *exportKey = shareMenu->addAction(tr("Export my public key..."));
10 ✔
1888
  exportKey->setEnabled(gpgAvailable);
10 ✔
1889
  connect(exportKey, &QAction::triggered, this, &MainWindow::exportPublicKey);
10 ✔
1890

1891
  QAction *addRecipientAction = shareMenu->addAction(tr("Add recipient..."));
10 ✔
1892
  addRecipientAction->setEnabled(gpgIdExists && gpgAvailable);
10 ✔
1893
  connect(addRecipientAction, &QAction::triggered, this,
10 ✔
1894
          [this, dirPath]() { addRecipient(dirPath); });
32 ✔
1895

1896
  QAction *shareHelp = shareMenu->addAction(tr("What is this?"));
10 ✔
1897
  connect(shareHelp, &QAction::triggered, this, &MainWindow::showShareHelp);
10 ✔
1898
}
10 ✔
1899

1900
void MainWindow::showContextMenu(const QPoint &pos) {
12 ✔
1901
  const AppSettings s = QtPassSettings::load();
12 ✔
1902
  const QModelIndex index = ui->treeView->indexAt(pos);
12 ✔
1903
  const bool selected = index.isValid();
1904
  if (!selected) {
1905
    ui->treeView->clearSelection();
1 ✔
1906
    ui->actionDelete->setEnabled(false);
1 ✔
1907
    ui->actionEdit->setEnabled(false);
1 ✔
1908
  }
1909
  ui->treeView->setCurrentIndex(index);
12 ✔
1910
  const QPoint globalPos = ui->treeView->viewport()->mapToGlobal(pos);
12 ✔
1911
  const QFileInfo fileOrFolder = m_tree->fileInfo(ui->treeView->currentIndex());
12 ✔
1912
  const bool isDir = fileOrFolder.isDir();
12 ✔
1913

1914
  QMenu contextMenu;
12 ✔
1915
  if (!selected || isDir) {
12 ✔
1916
    const std::array<std::pair<QString, void (MainWindow::*)()>, 4> onFolder{{
1917
        {tr("Open folder with file manager"), &MainWindow::openFolder},
11 ✔
1918
        {tr("Add folder"), &MainWindow::addFolder},
11 ✔
1919
        {tr("Add password"), &MainWindow::addPassword},
11 ✔
1920
        {tr("Users"), &MainWindow::onUsers},
11 ✔
1921
    }};
×
1922
    for (const auto &[text, slot] : onFolder) {
55 ✔
1923
      connect(contextMenu.addAction(text), &QAction::triggered, this, slot);
44 ✔
1924
    }
1925
  } else if (fileOrFolder.isFile()) {
1 ✔
1926
    connect(contextMenu.addAction(tr("Edit")), &QAction::triggered, this,
1 ✔
1927
            &MainWindow::onEdit);
2 ✔
1928
  }
1929
  if (selected) {
12 ✔
1930
    contextMenu.addSeparator();
11 ✔
1931
    if (isDir) {
11 ✔
1932
      connect(contextMenu.addAction(tr("Rename folder")), &QAction::triggered,
10 ✔
1933
              this, &MainWindow::renameFolder);
20 ✔
1934
    } else if (fileOrFolder.isFile()) {
1 ✔
1935
      connect(contextMenu.addAction(tr("Rename password")), &QAction::triggered,
1 ✔
1936
              this, &MainWindow::renamePassword);
2 ✔
1937
    }
1938
    connect(contextMenu.addAction(tr("Delete")), &QAction::triggered, this,
11 ✔
1939
            &MainWindow::onDelete);
11 ✔
1940
    if (isDir) {
11 ✔
1941
      addShareMenu(contextMenu, s);
10 ✔
1942
    }
1943
  }
1944
  contextMenu.exec(globalPos);
12 ✔
1945
}
12 ✔
1946

1947
auto MainWindow::browserContextMenu(const QPoint &pos) -> QMenu * {
3 ✔
1948
  // createStandardContextMenu() takes document coordinates, anchorAt() and
1949
  // the menu's place viewport ones: scrolled, the menu checked the text
1950
  // above the link and left "Copy Link Location" disabled.
1951
  // Right to left, the horizontal offset counts from the other end.
1952
  const QScrollBar *across = ui->textBrowser->horizontalScrollBar();
3 ✔
1953
  const int dx = ui->textBrowser->isRightToLeft()
3 ✔
1954
                     ? across->maximum() - across->value()
3 ✔
1955
                     : across->value();
3 ✔
1956
  const QPoint documentPos =
1957
      pos + QPoint(dx, ui->textBrowser->verticalScrollBar()->value());
3 ✔
1958
  QMenu *contextMenu = ui->textBrowser->createStandardContextMenu(documentPos);
3 ✔
1959
  // Reparent from textBrowser: a browser stylesheet cascades to the child
1960
  // QMenu and breaks its opaque native background.
1961
  contextMenu->setParent(this, contextMenu->windowFlags());
3 ✔
1962
  if (auto *copyLink =
3 ✔
1963
          contextMenu->findChild<QAction *>(QStringLiteral("link-copy"))) {
3 ✔
1964
    const QString link = ui->textBrowser->anchorAt(pos);
3 ✔
1965
    disconnect(copyLink, &QAction::triggered, nullptr, nullptr);
3 ✔
1966
    connect(copyLink, &QAction::triggered, this, [this, link] {
10 ✔
1967
      if (!link.isEmpty()) {
1 ✔
1968
        m_qtPass->clipboard().copyText(link);
1 ✔
1969
      }
1970
    });
1 ✔
1971
  }
1972
  return contextMenu;
3 ✔
1973
}
1974

1975
void MainWindow::showBrowserContextMenu(const QPoint &pos) {
1 ✔
1976
  QMenu *contextMenu = browserContextMenu(pos);
1 ✔
1977
  contextMenu->exec(ui->textBrowser->viewport()->mapToGlobal(pos));
1 ✔
1978
  delete contextMenu;
1 ✔
1979
}
1 ✔
1980

1981
void MainWindow::openFolder() {
1 ✔
1982
  QString dir = m_tree->currentDir(false);
1 ✔
1983

1984
  QString path = QDir::toNativeSeparators(dir);
1 ✔
1985
  QDesktopServices::openUrl(QUrl::fromLocalFile(path));
1 ✔
1986
}
1 ✔
1987

1988
void MainWindow::addFolder() {
7 ✔
1989
  const AppSettings s = QtPassSettings::load();
7 ✔
1990
  bool ok;
1991
  QString dir = m_tree->currentDir(false);
7 ✔
1992
  QString newdir = QInputDialog::getText(
1993
      this, tr("New folder"),
7 ✔
1994
      tr("New folder: \n(Will be placed in %1 )")
7 ✔
1995
          .arg(Util::shownName(s.passStore + m_tree->currentDir(true))),
14 ✔
1996
      QLineEdit::Normal, "", &ok);
14 ✔
1997
  if (!ok || newdir.isEmpty()) {
7 ✔
1998
    return;
1999
  }
2000
  // Checked and created as one and the same path: the check resolves ".."
2001
  // lexically, the system after following links, so "link/../x" would pass
2002
  // as the store's x and be made beside the link's target.
2003
  newdir = QDir::cleanPath(newdir.prepend(dir));
6 ✔
2004
  if (!confirmPathInStore(newdir)) {
6 ✔
2005
    return;
2006
  }
2007
  // Behind a link the folder would be made outside the store, as Users,
2008
  // Re-encrypt and Delete already refuse.
2009
  if (refuseLinkedFolder(newdir)) {
5 ✔
2010
    return;
2011
  }
2012
  // The tree, like `pass ls`, hides names that start with a dot.
2013
  const QStringList parts =
2014
      QDir(s.passStore).relativeFilePath(newdir).split(u'/');
4 ✔
2015
  if (std::any_of(parts.cbegin(), parts.cend(), [](const QString &part) {
8 ✔
2016
        return part != u'.' && part.startsWith(u'.');
4 ✔
2017
      })) {
2018
    PlainMessageBox::warning(this, tr("Hidden folder"),
2 ✔
2019
                             tr("A folder that starts with a dot would be "
1 ✔
2020
                                "hidden from the list: %1")
2021
                                 .arg(newdir));
2 ✔
2022
    return;
1 ✔
2023
  }
2024
  // Exists already: an error, as QDir::mkdir() made it before.
2025
  if (QFileInfo::exists(newdir) || !Util::mkpathForStore(newdir)) {
3 ✔
2026
    PlainMessageBox::warning(this, tr("Error"),
2 ✔
2027
                             tr("Failed to create folder: %1").arg(newdir));
2 ✔
2028
    return;
1 ✔
2029
  }
2030
  // No .gpg-id of its own: the folder uses its parent's recipients, as with
2031
  // pass, until Users gives it a list. A copy of the parent's list (#1688)
2032
  // kept every recipient later removed above it, and its entries stayed
2033
  // readable by them.
2034
}
7 ✔
2035

2036
void MainWindow::renameFolder() {
4 ✔
2037
  bool ok;
2038
  QString srcDir = QDir::cleanPath(m_tree->currentDir(false));
4 ✔
2039
  QString srcDirName = QDir(srcDir).dirName();
4 ✔
2040
  QString newName =
2041
      QInputDialog::getText(this, tr("Rename folder"), tr("Rename folder to: "),
4 ✔
2042
                            QLineEdit::Normal, srcDirName, &ok);
8 ✔
2043
  if (!ok || newName.isEmpty()) {
4 ✔
2044
    return;
2045
  }
2046
  QString destDir = srcDir;
2047
  destDir.replace(srcDir.lastIndexOf(srcDirName), srcDirName.length(), newName);
3 ✔
2048
  if (!confirmPathInStore(destDir)) {
3 ✔
2049
    return;
2050
  }
2051
  QtPassSettings::getPass()->Move(srcDir, destDir, false);
6 ✔
2052
}
2053

2054
void MainWindow::editPassword(const QString &file) {
6 ✔
2055
  if (!file.isEmpty()) {
6 ✔
2056
    const AppSettings s = QtPassSettings::load();
6 ✔
2057
    if (s.useGit && s.autoPull) {
6 ✔
2058
      onUpdate(true);
1 ✔
2059
    }
2060
    // The dialog decrypts the entry itself to fill its fields. That decrypt
2061
    // lands on the same finishedShow the panel uses, so drop the panel's claim
2062
    // to it: otherwise passShowHandler() repaints and, with "Always copy",
2063
    // puts the entry's old password on the clipboard - replacing whatever the
2064
    // user copied to paste into the dialog.
2065
    m_shownFile.clear();
6 ✔
2066
    setPassword(file, false);
6 ✔
2067
  }
6 ✔
2068
}
6 ✔
2069

2070
void MainWindow::renamePassword() {
2 ✔
2071
  bool ok;
2072
  QString file = getFile(ui->treeView->currentIndex(), false);
2 ✔
2073
  QString filePath = QFileInfo(file).path();
2 ✔
2074
  QString fileName = QFileInfo(file).fileName();
2 ✔
2075
  if (fileName.endsWith(".gpg", Qt::CaseInsensitive)) {
4 ✔
2076
    fileName.chop(4);
2 ✔
2077
  }
2078

2079
  QString newName =
2080
      QInputDialog::getText(this, tr("Rename file"), tr("Rename file to: "),
2 ✔
2081
                            QLineEdit::Normal, fileName, &ok);
4 ✔
2082
  if (!ok || newName.isEmpty()) {
2 ✔
2083
    return;
2084
  }
2085
  QString newFile = Util::joinPath(filePath, newName);
2 ✔
2086
  if (!confirmPathInStore(newFile)) {
2 ✔
2087
    return;
2088
  }
2089
  QtPassSettings::getPass()->Move(file, newFile, false);
3 ✔
2090
}
2091

2092
void MainWindow::copySelectionOrPassword() {
5 ✔
2093
  QWidget *focus = QApplication::focusWidget();
5 ✔
2094
  // The widget's own copy: a SecretTextBrowser marks what it copies as
2095
  // secret for clipboard managers, as the context menu's Copy does.
2096
  if (auto *text = qobject_cast<QTextEdit *>(focus);
5 ✔
2097
      text != nullptr && text->textCursor().hasSelection()) {
5 ✔
2098
    text->copy();
1 ✔
2099
    return;
1 ✔
2100
  }
2101
  // Through the clipboard manager, as a copy button would: the label may be
2102
  // the OTP code, which gets the secret hint and the autoclear.
2103
  if (auto *label = qobject_cast<QLabel *>(focus);
2104
      label != nullptr && label->hasSelectedText()) {
4 ✔
2105
    m_qtPass->clipboard().copyText(label->selectedText());
1 ✔
2106
    return;
1 ✔
2107
  }
2108
  // A line of the content search results is decrypted text: through the
2109
  // clipboard manager too, for the secret hint and the autoclear.
2110
  if (focus == ui->grepResultsList) {
3 ✔
2111
    if (const QTreeWidgetItem *item = ui->grepResultsList->currentItem();
3 ✔
2112
        item != nullptr && !item->text(0).isEmpty()) {
6 ✔
2113
      m_qtPass->clipboard().copyText(item->text(0));
6 ✔
2114
    }
2115
    return;
3 ✔
2116
  }
2117
  copyPasswordFromTreeview();
×
2118
}
2119

2120
void MainWindow::copyPasswordFromTreeview() {
9 ✔
2121
  // While content search results hide the tree, its current entry is not
2122
  // what the user looks at: no decrypt, as for Edit and OTP.
2123
  if (ui->treeView->isHidden()) {
9 ✔
2124
    return;
×
2125
  }
2126
  QFileInfo fileOrFolder = m_tree->fileInfo(ui->treeView->currentIndex());
9 ✔
2127

2128
  if (fileOrFolder.isFile()) {
9 ✔
2129
    QString file = getFile(ui->treeView->currentIndex(), true);
9 ✔
2130
    // The newest Ctrl+C wins: finishedShow names its file, so the decrypt of
2131
    // an earlier request is simply not this one's.
2132
    m_copyRequestFile = file;
9 ✔
2133
    // This Show repaints the panel as well; see onOtp().
2134
    m_shownFile = file;
9 ✔
2135
    QtPassSettings::getPass()->Show(file);
18 ✔
2136
  }
2137
}
9 ✔
2138

2139
void MainWindow::passwordFromFileToClipboard(const QString &text,
33 ✔
2140
                                             const QString &file) {
2141
  if (m_copyRequestFile.isEmpty() || file != m_copyRequestFile) {
33 ✔
2142
    return;
28 ✔
2143
  }
2144
  m_copyRequestFile.clear();
8 ✔
2145
  // The first line, without a list of every line (an entry can expand into
2146
  // millions of them), and without the "\r" of a CRLF line end, as the
2147
  // password row and "Always copy" have it.
2148
  const QString first = FileContent::passwordLine(text);
8 ✔
2149
  // A `pass otp insert` entry's first line is the otpauth:// URI carrying the
2150
  // TOTP seed, and an OTP field holding a seed there is the same; copying it
2151
  // would leak 2FA material. Matches the display path
2152
  // (FileContent::getPasswordForDisplay / PasswordDisplayPanel).
2153
  if (FileContent::isOtpPasswordLine(first)) {
8 ✔
2154
    flashText(tr("This entry holds an OTP secret, not a password"), true);
6 ✔
2155
    return;
2156
  }
2157
  m_qtPass->clipboard().copyText(first);
5 ✔
2158
}
2159

2160
void MainWindow::showStatusMessage(const QString &msg, int timeout) {
34 ✔
2161
  ui->statusBar->showMessage(msg, timeout);
34 ✔
2162
}
34 ✔
2163

2164
void MainWindow::reencryptPath(const QString &dir) {
4 ✔
2165
  QDir checkDir(dir);
4 ✔
2166
  if (!checkDir.exists()) {
4 ✔
2167
    PlainMessageBox::critical(this, tr("Error"),
2 ✔
2168
                              tr("Directory does not exist: %1").arg(dir));
2 ✔
2169
    return;
1 ✔
2170
  }
2171
  if (refuseLinkedFolder(dir)) {
3 ✔
2172
    return;
2173
  }
2174

2175
  const bool yes = PlainMessageBox::askYes(
3 ✔
2176
      this, tr("Re-encrypt passwords"),
3 ✔
2177
      tr("Re-encrypt all passwords in %1?\n\n"
3 ✔
2178
         "This will re-encrypt ALL password files in this folder "
2179
         "using the current recipients defined in .gpg-id.\n\n"
2180
         "This may rewrite many files and cannot be undone easily.\n\n"
2181
         "Continue?")
2182
          // On one line: a name with line feeds pushed the warning out of
2183
          // the box, which shows 40 lines at most.
2184
          .arg(Util::displayable(QDir(dir).dirName(), false)));
6 ✔
2185

2186
  if (!yes)
3 ✔
2187
    return;
2188

2189
  // Disable now; the asynchronous startReencryptPath signal re-runs this
2190
  // harmlessly.
2191
  startReencryptPath();
1 ✔
2192

2193
  // Under the current profile's settings: with the pass backend active, the
2194
  // native one is not re-initialised on a profile switch.
2195
  QtPassSettings::getImitatePass()->reencryptPath(
2 ✔
2196
      QDir::cleanPath(QDir(dir).absolutePath()), QtPassSettings::load());
2 ✔
2197
}
4 ✔
2198

2199
// Idempotent: reencryptPath() calls it before ImitatePass emits the signal.
2200
void MainWindow::startReencryptPath() {
7 ✔
2201
  m_reencryptRunning = true;
7 ✔
2202
  setUiElementsEnabled(false);
7 ✔
2203
  // The worker always ends with endReencryptPath(), and Cancel is available
2204
  // throughout, so the generic watchdog is not needed for this operation.
2205
  m_uiWatchdog.stop();
7 ✔
2206
  ui->treeView->setDisabled(true);
7 ✔
2207
  if (m_reencryptProgress)
7 ✔
2208
    return;
2209
  auto *progress = new QProgressDialog(tr("Re-encrypting passwords..."),
5 ✔
2210
                                       tr("Cancel"), 0, 0, this);
10 ✔
2211
  progress->setWindowTitle(tr("Re-encrypt passwords"));
5 ✔
2212
  progress->setWindowModality(Qt::WindowModal);
5 ✔
2213
  progress->setAutoClose(false);
5 ✔
2214
  progress->setAutoReset(false);
5 ✔
2215
  progress->setMinimumDuration(0);
5 ✔
2216
  connect(progress, &QProgressDialog::canceled, this, [this]() {
5 ✔
2217
    QtPassSettings::getImitatePass()->cancelReencryptPath();
1 ✔
2218
    showStatusMessage(tr("Cancelling re-encryption"), 5000);
1 ✔
2219
  });
1 ✔
2220
  m_reencryptProgress = progress;
2221
  progress->show();
5 ✔
2222
}
2223

2224
void MainWindow::reencryptProgress(int current, int total) {
7 ✔
2225
  if (!m_reencryptProgress || m_inProgressUpdate)
7 ✔
2226
    return;
2227
  QProgressDialog *progress = m_reencryptProgress;
2228
  progress->setMaximum(total);
6 ✔
2229
  progress->setLabelText(
6 ✔
2230
      tr("Re-encrypting passwords: %1 of %2").arg(current).arg(total));
6 ✔
2231
  // On a modal dialog setValue() runs processEvents(), which can deliver
2232
  // endReencryptPath(), even inside a nested event loop that would delete a
2233
  // deleteLater()ed dialog under setValue()'s feet: keep this last, and
2234
  // delete the dialog only after it returns.
2235
  m_inProgressUpdate = true;
6 ✔
2236
  progress->setValue(current);
6 ✔
2237
  m_inProgressUpdate = false;
6 ✔
2238
  if (m_progressToDelete) {
6 ✔
2239
    m_progressToDelete->deleteLater();
2 ✔
2240
    m_progressToDelete = nullptr;
2241
  }
2242
}
2243

2244
void MainWindow::endReencryptPath() {
5 ✔
2245
  m_reencryptRunning = false;
5 ✔
2246
  if (m_reencryptProgress) {
5 ✔
2247
    m_reencryptProgress->hide();
5 ✔
2248
    if (m_inProgressUpdate) {
5 ✔
2249
      m_progressToDelete = m_reencryptProgress;
2250
    } else {
2251
      m_reencryptProgress->deleteLater();
3 ✔
2252
    }
2253
    m_reencryptProgress = nullptr;
2254
  }
2255
  setUiElementsEnabled(true);
5 ✔
2256
}
5 ✔
2257

2258
void MainWindow::askReencryptUnexpected(const QString &dir,
×
2259
                                        const QStringList &files,
2260
                                        const QStringList &details) {
2261
  const AppSettings s = QtPassSettings::load();
×
2262
  const QDir store(s.passStore);
×
2263
  // Sorted by name, so each folder's entries stand together; who would gain
2264
  // each one beside it, as the names alone are the writer's choosing.
2265
  QList<std::pair<QString, QString>> rows;
×
2266
  for (qsizetype i = 0; i < files.size(); ++i) {
×
2267
    rows.append({Util::displayable(store.relativeFilePath(files.at(i)), false),
×
2268
                 details.value(i)});
×
2269
  }
2270
  std::sort(rows.begin(), rows.end());
×
2271
  constexpr int kListed = 15;
2272
  QStringList lines;
×
2273
  for (qsizetype i = 0; i < rows.size() && i < kListed; ++i) {
×
2274
    lines << rows.at(i).first + QStringLiteral(": ") + rows.at(i).second;
×
2275
  }
2276
  if (rows.size() > kListed) {
×
2277
    lines << tr("... and %n more", nullptr,
×
2278
                static_cast<int>(rows.size() - kListed));
×
2279
  }
2280
  const int n = static_cast<int>(files.size());
×
2281
  const bool yes = PlainMessageBox::askYes(
×
2282
      this, tr("Re-encrypt these too?"),
×
2283
      tr("%n entry(s) here would become readable by people on this "
×
2284
         "folder's list who cannot read them now, and whom you did not just "
2285
         "add, so they were left as they are. Someone who can read this "
2286
         "folder may have copied them in from a folder they cannot read.",
2287
         nullptr, n) +
×
2288
          QStringLiteral("\n\n") + lines.join(QLatin1Char('\n')) +
×
2289
          QStringLiteral("\n\n") +
×
2290
          tr("Re-encrypt them for this folder's recipients? If not, they "
×
2291
             "stay readable only by whoever they are encrypted to now."));
×
2292
  if (!yes) {
×
2293
    return;
2294
  }
2295
  startReencryptPath();
×
2296
  QtPassSettings::getImitatePass()->reencryptAlso(dir, files, s);
×
2297
}
×
2298

2299
void MainWindow::exportPublicKey() {
4 ✔
2300
  const AppSettings s = QtPassSettings::load();
4 ✔
2301
  const QString identity = s.passSigningKey;
2302
  if (identity.isEmpty()) {
4 ✔
2303
    QMessageBox::information(
2 ✔
2304
        this, tr("Export public key"),
1 ✔
2305
        tr("<h3>Export your public key</h3>"
×
2306
           "<p>No signing key is configured. Set one in QtPass Settings "
2307
           "&gt; GPG keys, or run this in a terminal:</p>"
2308
           "<pre>gpg --armor --export --output my_key.asc &lt;your-key-id"
2309
           "&gt;</pre>"
2310
           "<p>Then send the file to your teammates.</p>"));
2311
    return;
1 ✔
2312
  }
2313
  QString gpgExe = s.gpgExecutable;
2314
  if (gpgExe.isEmpty()) {
3 ✔
2315
    gpgExe = QStringLiteral("gpg");
×
2316
  }
2317
  const QStringList keys = identity.split(' ', Qt::SkipEmptyParts);
3 ✔
2318
  // gpg --export takes every key block that holds the ID: another key that
2319
  // holds yours as a subkey would go out to your teammates as yours.
2320
  if (Pass *pass = QtPassSettings::getPass(); pass != nullptr) {
3 ✔
2321
    if (const std::optional<QHash<QString, QStringList>> held =
2322
            pass->keyLinesHeldTwice(keys);
3 ✔
2323
        !held || !held->isEmpty()) {
3 ✔
2324
      PlainMessageBox::warning(
1 ✔
2325
          this, tr("Export public key"),
1 ✔
2326
          tr("Your key cannot be exported on its own:\n\n%1")
1 ✔
2327
              .arg(Pass::describeKeyLinesHeldTwice(held)));
2 ✔
2328
      return;
2329
    }
2330
  }
2331
  QString stdOut;
2 ✔
2332
  QString stdErr;
2 ✔
2333
  // In the store's environment, the keyring the check above read.
2334
  Pass *pass = QtPassSettings::getPass();
2 ✔
2335
  int exitCode =
2336
      pass != nullptr
2337
          ? pass->exportPublicKeys(gpgExe, keys, &stdOut, &stdErr)
2 ✔
NEW
2338
          : Executor::executeBlocking(gpgExe,
×
NEW
2339
                                      QStringList{QStringLiteral("--armor"),
×
2340
                                                  QStringLiteral("--export")} +
2 ✔
NEW
2341
                                          keys,
×
2342
                                      &stdOut, &stdErr);
2343
  if (exitCode != 0 || stdOut.isEmpty()) {
2 ✔
2344
    PlainMessageBox::warning(this, tr("Export public key"),
2 ✔
2345
                             tr("Could not export public key for %1.\n\n%2")
1 ✔
2346
                                 .arg(identity, stdErr.isEmpty()
2 ✔
2347
                                                    ? tr("No output from gpg.")
2 ✔
2348
                                                    : stdErr));
2349
    return;
2350
  }
2351
  ExportPublicKeyDialog dialog(identity, stdOut, this);
1 ✔
2352
  dialog.exec();
1 ✔
2353
}
5 ✔
2354

2355
// UsersDialog only ticks keys already in the keyring; importing a foreign
2356
// key still has to happen via gpg (or QtPass settings) first.
2357
void MainWindow::addRecipient(const QString &dir) {
2 ✔
2358
  if (refuseLinkedFolder(dir)) {
2 ✔
2359
    return;
1 ✔
2360
  }
2361
  UsersDialog d(QtPassSettings::getPass(), QtPassSettings::load(), dir, this);
1 ✔
2362
  d.exec();
1 ✔
2363
}
1 ✔
2364

2365
// A tree-picked folder that is, or lies behind, a symlink or junction is not
2366
// a folder of the store. The store root itself may be a link (a synced
2367
// folder); that is configuration, not a tree pick.
2368
auto MainWindow::refuseLinkedFolder(const QString &dir) -> bool {
22 ✔
2369
  if (!Util::isUnderLink(dir, QtPassSettings::load().passStore)) {
22 ✔
2370
    return false;
2371
  }
2372
  PlainMessageBox::critical(
4 ✔
2373
      this, tr("Not a folder of the store"),
4 ✔
2374
      tr("%1 is, or lies behind, a symbolic link or junction. What that "
4 ✔
2375
         "points to is not part of the password store and is left alone.")
2376
          .arg(QDir::toNativeSeparators(QDir::cleanPath(dir))));
8 ✔
2377
  return true;
4 ✔
2378
}
2379

2380
void MainWindow::showShareHelp() {
1 ✔
2381
  QMessageBox::information(
2 ✔
2382
      this, tr("Sharing passwords with GPG"),
1 ✔
2383
      tr("<h3>Sharing passwords with GPG</h3>"
1 ✔
2384
         "<p>To share passwords with other users:</p>"
2385
         "<ol>"
2386
         "<li><b>Export your public key</b> and send it to teammates</li>"
2387
         "<li><b>Import teammates' public keys</b> into your GPG keyring</li>"
2388
         "<li><b>Re-encrypt passwords</b> so all recipients can decrypt "
2389
         "them</li>"
2390
         "</ol>"
2391
         "<p>Only people who have a matching secret key can decrypt the "
2392
         "passwords.</p>"
2393
         "<p><b>Tip:</b> Use the same GPG key for all shared folders.</p>"
2394
         "<p>See the FAQ for more details.</p>"));
2395
}
1 ✔
2396

2397
void MainWindow::updateGitButtonVisibility(bool uiEnabled) {
454 ✔
2398
  const AppSettings s = QtPassSettings::load();
454 ✔
2399
  // Without Git there is nothing to push or pull, ever: the buttons go, not
2400
  // grey out. While an operation runs they stay and are disabled.
2401
  const bool usable =
2402
      s.useGit && !(s.gitExecutable.isEmpty() && s.passExecutable.isEmpty());
454 ✔
2403
  ui->actionPush->setVisible(usable);
454 ✔
2404
  ui->actionUpdate->setVisible(usable);
454 ✔
2405
  // The separator in front of them would otherwise sit next to the next one.
2406
  const QList<QAction *> actions = ui->toolBar->actions();
454 ✔
2407
  const qsizetype at = actions.indexOf(ui->actionPush);
454 ✔
2408
  if (at > 0 && actions.at(at - 1)->isSeparator()) {
454 ✔
2409
    actions.at(at - 1)->setVisible(usable);
454 ✔
2410
  }
2411
  enableGitButtons(usable && uiEnabled);
454 ✔
2412
}
454 ✔
2413

2414
void MainWindow::updateOtpButtonVisibility(bool uiEnabled) {
464 ✔
2415
  // No platform gating: codes are generated in-process. Visible but disabled
2416
  // when OTP is off: the panel never shows an OTP field (a secret), so hiding
2417
  // this too would leave no trace of the feature. Honour uiEnabled, or the
2418
  // user can stack Show calls while a decrypt is in flight.
2419
  ui->actionOtp->setVisible(true);
464 ✔
2420
  ui->actionOtp->setEnabled(QtPassSettings::isUseOtp() && uiEnabled);
572 ✔
2421
}
464 ✔
2422

2423
void MainWindow::updateGrepButtonVisibility() {
205 ✔
2424
  const bool enabled = QtPassSettings::isUseGrepSearch();
205 ✔
2425
  ui->grepButton->setVisible(enabled);
205 ✔
2426
  ui->grepCaseButton->setVisible(enabled);
205 ✔
2427
  if (!enabled && m_grep.inGrepMode()) {
205 ✔
2428
    ui->grepButton->setChecked(false);
1 ✔
2429
  }
2430
}
205 ✔
2431

2432
void MainWindow::enableGitButtons(const bool &state) {
454 ✔
2433
  ui->actionPush->setEnabled(state);
454 ✔
2434
  ui->actionUpdate->setEnabled(state);
454 ✔
2435
}
454 ✔
2436

2437
void MainWindow::critical(const QString &title, const QString &msg) {
4 ✔
2438
  // Pass's messages quote store paths; see PlainMessageBox.
2439
  PlainMessageBox::critical(this, title, msg);
4 ✔
2440
}
4 ✔
2441

2442
void MainWindow::onProcessOutput(const QString &output, bool isError,
7 ✔
2443
                                 Enums::PROCESS pid) {
2444
  if (!QtPassSettings::isShowProcessOutput()) {
7 ✔
2445
    return;
2446
  }
2447
  m_processOutput->append(output, isError,
6 ✔
2448
                          ProcessOutputPanel::processName(pid));
12 ✔
2449
}
2450

2451
void MainWindow::updateProcessOutputVisibility() {
5 ✔
2452
  // The action's toggled handler shows or hides the dock.
2453
  ui->actionShowProcessOutput->setChecked(
5 ✔
2454
      QtPassSettings::isShowProcessOutput());
5 ✔
2455
  m_processOutput->setVisible(QtPassSettings::isShowProcessOutput());
5 ✔
2456
}
5 ✔
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