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

IJHack / QtPass / 46634848759

01 Dec 2026 11:16AM UTC coverage: 94.516% (+0.008%) from 94.508%
46634848759

push

github

web-flow
Tree menu actions run on the entry the menu was opened on (#2432)

Fixes #2431.

On macOS the file system model removes a deleted folder's row itself and
makes the next row current. The reload after it finds that entry again,
so currentEntryLost never comes: a menu opened on the removed folder
stayed open, and its Delete or Rename acted on the neighbouring entry.

- MainWindow::showContextMenu: every action that reads the current entry
  first calls backOnMenuEntry(), which makes the entry the menu was
  opened on current again. When that entry is gone from disk or no
  longer listed, the action does not run and the status bar says so.
  A dangling link still counts as an entry.
- Tests: aTreeMenuActsOnTheEntryItWasOpenedOn and
  aTreeMenuDoesNothingOnceItsEntryIsGone.
- aTreeMenuClosesWhenItsFolderIsGone ends its wait once another entry is
  current, the macOS outcome it failed on after 30 s.

A first version closed the menu on currentChanged; on macOS that closed
it right after it opened, so it was replaced (review by nogeenhenk).

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

30 of 31 new or added lines in 1 file covered. (96.77%)

11443 of 12107 relevant lines covered (94.52%)

23926.19 hits per line

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

95.61
/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 "processinfo.h"
26
#include "processoutputpanel.h"
27
#include "qpushbuttonasqrcode.h"
28
#include "qpushbuttonshowpassword.h"
29
#include "qpushbuttonwithclipboard.h"
30
#include "qtpass.h"
31
#include "qtpasssettings.h"
32
#include "templateio.h"
33
#include "totp.h"
34
#include "trayicon.h"
35
#include "ui_mainwindow.h"
36
#include "usersdialog.h"
37
#include "util.h"
38
#include "windowstatestore.h"
39
#include <QApplication>
40
#include <QCloseEvent>
41
#include <QDate>
42
#include <QDesktopServices>
43
#include <QDialog>
44
#include <QDockWidget>
45
#include <QFileInfo>
46
#include <QFileSystemModel>
47
#include <QHBoxLayout>
48
#include <QInputDialog>
49
#include <QLabel>
50
#include <QLineEdit>
51
#include <QMenu>
52
#include <QMenuBar>
53
#include <QMessageBox>
54
#include <QProgressDialog>
55
#include <QPushButton>
56
#include <QScrollBar>
57
#include <QShortcut>
58
#include <QTextBlock>
59
#include <QTextCharFormat>
60
#include <QTextCursor>
61
#include <QTextDocument>
62
#include <QTextEdit>
63
#include <QTextStream>
64
#include <QTimer>
65
#include <QTreeWidget>
66
#include <QUrl>
67
#include <algorithm>
68
#include <utility>
69

70
/**
71
 * @brief What the Stop button calls a run.
72
 * @param pid The kind of command that runs.
73
 * @return Its command line label ("git pull", "pass init"); "a decrypt" for
74
 *         a decrypt, whose label the output panel leaves empty; "a command"
75
 *         when the kind is unknown.
76
 */
77
static auto runLabel(Enums::PROCESS pid) -> QString {
14 ✔
78
  if (pid == Enums::PASS_SHOW) {
14 ✔
79
    return QCoreApplication::translate("MainWindow", "a decrypt");
4 ✔
80
  }
81
  const QString label = Enums::processLabel(pid);
10 ✔
82
  return label.isEmpty()
83
             ? QCoreApplication::translate("MainWindow", "a command")
10 ✔
84
             : label;
×
85
}
86

87
MainWindow::MainWindow(const QString &searchText, QWidget *parent)
206 ✔
88
    : QMainWindow(parent), ui(new Ui::MainWindow) {
206 ✔
89
#ifdef __APPLE__
90
  // extra treatment for mac os
91
  // see https://doc.qt.io/qt-6/qkeysequence.html#qt_set_sequence_auto_mnemonic
92
  qt_set_sequence_auto_mnemonic(true);
93
#endif
94
  ui->setupUi(this);
206 ✔
95

96
  m_qtPass = new QtPass(this);
206 ✔
97
  restoreWindow();
206 ✔
98
  connectBackends();
206 ✔
99

100
  // Every Copy binding, not only the first (Ctrl+C): Ctrl+Insert and F16
101
  // otherwise reached the views' own copy, which put decrypted text on the
102
  // clipboard bare, without the secret hint or the autoclear.
103
  const QList<QKeySequence> copyKeys =
104
      QKeySequence::keyBindings(QKeySequence::StandardKey::Copy);
206 ✔
105
  for (const QKeySequence &keys : copyKeys) {
618 ✔
106
    new QShortcut(keys, this, this, &MainWindow::copySelectionOrPassword);
412 ✔
107
  }
108

109
  m_tree = new StoreTree(ui->treeView, this);
206 ✔
110
  m_tree->setStore(QtPassSettings::getPassStore(Util::findPasswordStore()));
206 ✔
111
  m_tree->setPass(QtPassSettings::getPass());
206 ✔
112
  connect(ui->treeView, &QWidget::customContextMenuRequested, this,
206 ✔
113
          &MainWindow::showContextMenu);
206 ✔
114
  connect(ui->treeView, &DeselectableTreeView::emptyClicked, this,
206 ✔
115
          &MainWindow::deselect);
206 ✔
116

117
  initTextBrowser();
206 ✔
118

119
  updateProfileBox();
206 ✔
120

121
  initDisplayPanel();
206 ✔
122

123
  QtPassSettings::getPass()->updateEnv();
206 ✔
124

125
  // Install the search-box key filter once, not on every setUiElementsEnabled
126
  // call.
127
  ui->lineEdit->installEventFilter(this);
206 ✔
128
  // Both live in Breeze's "tools area" and get its header palette; see the
129
  // PaletteChange branch in eventFilter().
130
  ui->toolBar->installEventFilter(this);
206 ✔
131
  menuBar()->installEventFilter(this);
206 ✔
132

133
  initTimers();
206 ✔
134

135
  initToolBarButtons();
206 ✔
136
  initStatusBar();
206 ✔
137
  initProcessOutput();
206 ✔
138

139
  ui->lineEdit->setClearButtonEnabled(true);
206 ✔
140
  updateGrepButtonVisibility();
206 ✔
141

142
  setUiElementsEnabled(true);
206 ✔
143

144
  // No QApplication::quit() here: before exec() it is a documented no-op.
145
  // main() checks initSucceeded() and exits before show() instead.
146
  m_qtPass->init();
206 ✔
147
  // OK is not gated on Util::configIsValid(): an accepted configuration can
148
  // still lack a .gpg-id, so ask again; only a cancel ends the loop.
149
  while (!Util::configIsValid(QtPassSettings::load())) {
207 ✔
150
    if (!config()) {
2 ✔
151
      return;
152
    }
153
  }
154
  // Set up, with or without the wizard (a fresh install can find a store
155
  // that already works): a later run of the wizard keeps the saved backend
156
  // and Git choices. A cancelled first run returned above and keeps it.
157
  QtPassSettings::getInstance()->remove(SettingsConstants::firstRunPending);
205 ✔
158
  m_freshStart = false;
205 ✔
159
  m_initSucceeded = true;
205 ✔
160

161
  // Searched as qtpass(1) promises, once the window and its tree are up:
162
  // filtered at once and an entry named exactly so opened. Setting the
163
  // text here left it to the search timer, which only highlights. Queued
164
  // only now: from before the configuration loop, a wizard's nested event
165
  // loop ran it while no store was set yet.
166
  if (!searchText.isEmpty()) {
205 ✔
167
    QTimer::singleShot(0, this,
168
                       [this, searchText] { applySearchText(searchText); });
×
169
  }
170

171
  // Initial focus is set in showEvent(): a 10 ms QTimer here could fire
172
  // before the window was realised (queued ActivationChange, nested exec() in
173
  // init()) and selectAll() segfaulted inside Qt (#1187, #1188).
174
}
×
175

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

227
void MainWindow::initTextBrowser() {
206 ✔
228
  {
229
    const AppSettings s = QtPassSettings::load();
206 ✔
230
    if (s.useMonospace) {
206 ✔
231
      QFont monospace("Monospace");
1 ✔
232
      monospace.setStyleHint(QFont::Monospace);
1 ✔
233
      ui->textBrowser->setFont(monospace);
1 ✔
234
    }
1 ✔
235
    if (s.noLineWrapping) {
206 ✔
236
      ui->textBrowser->setLineWrapMode(QTextBrowser::NoWrap);
1 ✔
237
    }
238
    clearPanelTimer.setInterval(MS_PER_SECOND * s.autoclearPanelSeconds);
206 ✔
239
    clearResultsTimer.setInterval(clearPanelTimer.interval());
206 ✔
240
  }
206 ✔
241
  ui->textBrowser->setOpenExternalLinks(true);
206 ✔
242
  ui->textBrowser->setContextMenuPolicy(Qt::CustomContextMenu);
206 ✔
243
  connect(ui->textBrowser, &QWidget::customContextMenuRequested, this,
206 ✔
244
          &MainWindow::showBrowserContextMenu);
206 ✔
245
}
206 ✔
246

247
void MainWindow::initDisplayPanel() {
206 ✔
248
  m_displayPanel = new PasswordDisplayPanel(
206 ✔
249
      ui->gridLayout, ui->verticalLayoutPassword, this, this);
206 ✔
250
  connect(m_displayPanel, &PasswordDisplayPanel::copyRequested,
206 ✔
251
          &m_qtPass->clipboard(), &ClipboardManager::copyText);
206 ✔
252
  connect(m_displayPanel, &PasswordDisplayPanel::textCopied,
206 ✔
253
          &m_qtPass->clipboard(), &ClipboardManager::trackCopied);
206 ✔
254
  connect(ui->textBrowser, &SecretTextBrowser::copied, &m_qtPass->clipboard(),
206 ✔
255
          &ClipboardManager::trackCopied);
206 ✔
256
  connect(m_displayPanel, &PasswordDisplayPanel::qrRequested, m_qtPass,
206 ✔
257
          &QtPass::showTextAsQRCode);
206 ✔
258
  // Double-click on what is shown edits it, as in the tree.
259
  // The entry whose rows were double-clicked, not the tree's current row:
260
  // arrow keys and a right-click move that row without repainting the panel.
261
  connect(m_displayPanel, &PasswordDisplayPanel::editRequested, this, [this] {
206 ✔
262
    if (ui->actionEdit->isEnabled() && !m_panelEntry.isEmpty()) {
4 ✔
263
      editPassword(m_panelEntry);
3 ✔
264
    }
265
  });
4 ✔
266
}
206 ✔
267

268
void MainWindow::initTimers() {
206 ✔
269
  clearPanelTimer.setSingleShot(true);
206 ✔
270
  connect(&clearPanelTimer, &QTimer::timeout, this,
206 ✔
271
          [this]() { clearShownEntry(true); });
208 ✔
272
  clearResultsTimer.setSingleShot(true);
206 ✔
273
  connect(&clearResultsTimer, &QTimer::timeout, this,
206 ✔
274
          &MainWindow::clearContentResults);
206 ✔
275

276
  searchTimer.setInterval(350);
206 ✔
277
  searchTimer.setSingleShot(true);
206 ✔
278

279
  connect(&searchTimer, &QTimer::timeout, this, &MainWindow::onTimeoutSearch);
206 ✔
280

281
  // Safety net: if a backend operation disables the UI but never signals
282
  // completion, re-enable after a timeout so the window can't get stuck.
283
  m_uiWatchdog.setSingleShot(true);
206 ✔
284
  m_uiWatchdog.setInterval(UiWatchdogMs);
206 ✔
285
  connect(&m_uiWatchdog, &QTimer::timeout, this, [this]() {
206 ✔
286
    showStatusMessage(tr("Operation timed out; re-enabling interface."));
6 ✔
287
    // What still runs can be stopped: a store entry built to keep gpg busy
288
    // holds up everything queued behind it. No timer stops it by itself, as
289
    // a decrypt may be waiting for a passphrase.
290
    if (Pass *pass = QtPassSettings::getPass();
6 ✔
291
        pass != nullptr && !pass->isIdle()) {
6 ✔
292
      m_stopButton->setToolTip(tr("Stop %1, which is still running")
12 ✔
293
                                   .arg(runLabel(pass->runningProcess())));
18 ✔
294
      m_stopButton->show();
6 ✔
295
    }
296
    // Drop any in-flight OTP request so a late finishedShow cannot be mistaken
297
    // for the answer to it.
298
    cancelOtpRequest();
6 ✔
299
    setUiElementsEnabled(true);
6 ✔
300
  });
6 ✔
301
}
206 ✔
302

303
void MainWindow::initProcessOutput() {
206 ✔
304
  m_processOutput = new ProcessOutputPanel(this);
206 ✔
305
  addDockWidget(Qt::BottomDockWidgetArea, m_processOutput);
206 ✔
306
  // After addDockWidget so our preference wins over any cached state
307
  // QMainWindow applies; restoreWindow() already processed the saved layout.
308
  m_processOutput->setVisible(QtPassSettings::isShowProcessOutput());
206 ✔
309
  // From the setting, not isVisible(): the window is not shown yet, so no
310
  // child of it reports visible.
311
  ui->actionShowProcessOutput->setChecked(
206 ✔
312
      QtPassSettings::isShowProcessOutput());
206 ✔
313
  connect(ui->actionShowProcessOutput, &QAction::toggled, this,
206 ✔
314
          [this](bool show) {
206 ✔
315
            m_processOutput->setVisible(show);
2 ✔
316
            AppSettings s = QtPassSettings::load();
2 ✔
317
            if (s.showProcessOutput != show) {
2 ✔
318
              s.showProcessOutput = show;
2 ✔
319
              QtPassSettings::save(s);
2 ✔
320
            }
321
          });
2 ✔
322

323
  connect(QtPassSettings::getPass(), &Pass::finishedAnyWithPid, this,
206 ✔
324
          [this](const QString &out, const QString &err, Enums::PROCESS pid) {
206 ✔
325
            // Never route potentially-secret output through the panel:
326
            // PASS_SHOW goes to the text browser (cleared on a timer when
327
            // "Autoclear panel" is set),
328
            // PASS_GREP would return password-file lines (#252; it is no
329
            // longer started, the check stays), and PASS_INSERT
330
            // is excluded defensively in case a future path uses --echo.
331
            if (ProcessOutputPanel::isSensitiveProcess(pid)) {
17 ✔
332
              return;
333
            }
334
            if (!out.isEmpty()) {
16 ✔
335
              onProcessOutput(out, false, pid);
1 ✔
336
            }
337
            if (!err.isEmpty()) {
16 ✔
338
              onProcessOutput(err, true, pid);
4 ✔
339
            }
340
          });
341
}
206 ✔
342

343
MainWindow::~MainWindow() {
408 ✔
344
  // Quit from the tray menu or a SIGTERM never delivers closeEvent(); the
345
  // window still knows its last geometry here.
346
  saveWindowState();
206 ✔
347
  delete m_qtPass;
206 ✔
348
}
614 ✔
349

350
// The signals of one backend that the window answers itself.
351
void MainWindow::connectPassSignals(Pass *pass) {
412 ✔
352
  // A failed decrypt never emits finishedShow; drop the pending OTP/copy
353
  // request so a later decrypt of the same entry is not taken as its answer.
354
  connect(pass, &Pass::processErrorExit, this, &MainWindow::onOperationError);
412 ✔
355
  connect(pass, &Pass::critical, this, &MainWindow::critical);
412 ✔
356
  connect(pass, &Pass::startingExecuteWrapper, this,
412 ✔
357
          &MainWindow::executeWrapperStarted);
412 ✔
358
  // The profile box comes back when the queue is done, also after the
359
  // watchdog released the rest of the interface early.
360
  connect(pass, &Pass::idle, this, &MainWindow::updateProfileBoxEnabled);
412 ✔
361
  // The button names what it stops, also once the queue moved on.
362
  connect(pass, &Pass::startingExecuteWrapper, this, [this, pass]() {
412 ✔
363
    if (m_stopButton != nullptr && !m_stopButton->isHidden()) {
76 ✔
364
      m_stopButton->setToolTip(tr("Stop %1, which is still running")
4 ✔
365
                                   .arg(runLabel(pass->runningProcess())));
6 ✔
366
    }
367
  });
76 ✔
368
  // Nothing left to stop.
369
  connect(pass, &Pass::idle, this, [this]() {
412 ✔
370
    if (m_stopButton != nullptr) {
50 ✔
371
      m_stopButton->hide();
50 ✔
372
    }
373
  });
50 ✔
374
  connect(pass, &Pass::statusMsg, this, &MainWindow::showStatusMessage);
412 ✔
375
  connect(pass, &Pass::finishedShow, this, &MainWindow::passShowHandler);
412 ✔
376
  // Both check the file against their own pending request and ignore the
377
  // rest, so they can stay connected for good.
378
  connect(pass, &Pass::finishedShow, this, &MainWindow::otpFromFileToClipboard);
412 ✔
379
  connect(pass, &Pass::finishedShow, this,
412 ✔
380
          &MainWindow::passwordFromFileToClipboard);
412 ✔
381
  connect(pass, &Pass::finishedGrep, this, &MainWindow::onGrepFinished);
412 ✔
382
  // The refresh a save left waiting runs once the last push went through,
383
  // by name as it was queued before (the save's rewrite of the file may have
384
  // replaced its row in the tree), and only while the entry still holds the
385
  // panel and nothing else is queued: queued work would run first, and the
386
  // refresh would empty the browser of its error. A failed push dropped it
387
  // (onOperationError()).
388
  connect(pass, &Pass::finishedGitPush, this, [this, pass]() {
412 ✔
389
    if (m_refreshAfterPush.isEmpty() || m_refreshAfterPushOwner != pass ||
31 ✔
390
        pass->isPushing()) {
9 ✔
391
      return;
5 ✔
392
    }
393
    const QString file = std::exchange(m_refreshAfterPush, QString());
7 ✔
394
    m_refreshAfterPushOwner = nullptr;
7 ✔
395
    if (file == m_shownFile && pass->isIdle()) {
7 ✔
396
      ui->passwordName->setText(Util::shownName(file));
4 ✔
397
      pass->Show(file);
8 ✔
398
    }
399
  });
400
}
412 ✔
401

402
// Idempotent; called from closeEvent() and the destructor.
403
void MainWindow::saveWindowState() {
210 ✔
404
  QtPassSettings::setGeometry(saveGeometry());
210 ✔
405
  QtPassSettings::setSavestate(saveState());
210 ✔
406
}
210 ✔
407

408
void MainWindow::focusInput() {
82 ✔
409
  // findChild() rather than ui->lineEdit: on a fresh-config first launch
410
  // config() calls setWindowFlags(), which rebuilds the native window, and
411
  // under Qt 6.11 the QLineEdit was destroyed while ui->lineEdit kept its old
412
  // address (SIGSEGV in QWidget::testAttribute). findChild() returns null.
413
  if (!isVisible()) {
82 ✔
414
    return;
415
  }
416
  auto *lineEdit = findChild<QLineEdit *>(QStringLiteral("lineEdit"));
82 ✔
417
  if (lineEdit == nullptr || !lineEdit->isVisible()) {
82 ✔
418
    return;
419
  }
420
  lineEdit->selectAll();
82 ✔
421
  lineEdit->setFocus();
82 ✔
422
  // Only once focus has landed: set in showEvent(), an early return above
423
  // would consume the one-shot and never retry.
424
  m_firstShowCompleted = true;
82 ✔
425
}
426

427
auto MainWindow::event(QEvent *event) -> bool {
9,579 ✔
428
  if (event->type() == QEvent::ApplicationPaletteChange) {
9,579 ✔
429
    m_themeSwitched = true;
11 ✔
430
    // Breeze may re-stamp the bars before this arrives (Plasma 6 does):
431
    // their PaletteChange then found no switch yet, so check them now too.
432
    QTimer::singleShot(0, this, &MainWindow::dropStaleToolsAreaPalettes);
11 ✔
433
  }
434
  return QMainWindow::event(event);
9,579 ✔
435
}
436

437
void MainWindow::changeEvent(QEvent *event) {
276 ✔
438
  QWidget::changeEvent(event);
276 ✔
439
  if (event->type() == QEvent::PaletteChange && m_displayPanel != nullptr) {
276 ✔
440
    // Desktop switched light/dark. Top-level widgets get PaletteChange
441
    // (ApplicationPaletteChange goes to QApplication); stylesheets with
442
    // baked-in palette colours must be re-derived by hand.
443
    m_displayPanel->refreshPalette();
10 ✔
444
  }
445
  if (event->type() == QEvent::ActivationChange && isActiveWindow() &&
276 ✔
446
      isVisible()) {
447
    // Defer a tick so the activation dispatch chain unwinds first: calling
448
    // focusInput() inline has segfaulted on half-rebuilt ui state.
449
    QMetaObject::invokeMethod(this, &MainWindow::focusInput,
47 ✔
450
                              Qt::QueuedConnection);
451
  }
452
}
276 ✔
453

454
void MainWindow::showEvent(QShowEvent *event) {
49 ✔
455
  QMainWindow::showEvent(event);
49 ✔
456
  if (m_firstShowCompleted) {
49 ✔
457
    return;
458
  }
459
  // Queued so the platform map and pending rebuilds (setWindowFlags on the
460
  // wizard path) settle first. focusInput() sets the latch only on success,
461
  // so a failed lookup retries on the next show.
462
  QMetaObject::invokeMethod(this, &MainWindow::focusInput,
47 ✔
463
                            Qt::QueuedConnection);
464
}
465

466
void MainWindow::initToolBarButtons() {
206 ✔
467
  connect(ui->actionAddPassword, &QAction::triggered, this,
206 ✔
468
          &MainWindow::addPassword);
206 ✔
469
  connect(ui->actionAddFolder, &QAction::triggered, this,
206 ✔
470
          &MainWindow::addFolder);
206 ✔
471
  connect(ui->actionEdit, &QAction::triggered, this, &MainWindow::onEdit);
206 ✔
472
  connect(ui->actionDelete, &QAction::triggered, this, &MainWindow::onDelete);
206 ✔
473
  connect(ui->actionPush, &QAction::triggered, this, &MainWindow::onPush);
206 ✔
474
  connect(ui->actionUpdate, &QAction::triggered, this, &MainWindow::onUpdate);
206 ✔
475
  connect(ui->actionUsers, &QAction::triggered, this, &MainWindow::onUsers);
206 ✔
476
  connect(ui->actionConfig, &QAction::triggered, this, &MainWindow::onConfig);
206 ✔
477
  connect(ui->actionOtp, &QAction::triggered, this, &MainWindow::onOtp);
206 ✔
478

479
  // Menu-only. Quit ends the application, tray icon or not, as in KeePassXC,
480
  // Telegram and the KDE, GNOME and macOS guidelines (#1788). Close is
481
  // close(), a hide when "hide on close" is set, like the X button and Alt+F4.
482
  connect(ui->actionQuit, &QAction::triggered, qApp, &QApplication::quit);
206 ✔
483
  connect(ui->actionClose, &QAction::triggered, this, &MainWindow::close);
206 ✔
484
#ifdef Q_OS_MACOS
485
  // The menu bar is the system's up there; nothing to hide.
486
  ui->actionShowMenuBar->setVisible(false);
487
#else
488
  // The action lives in the menu it hides, so it has to be on the window as
489
  // well for Ctrl+M to keep working while the bar is gone.
490
  addAction(ui->actionShowMenuBar);
206 ✔
491
  ui->actionShowMenuBar->setChecked(QtPassSettings::load().showMenuBar);
206 ✔
492
  menuBar()->setVisible(ui->actionShowMenuBar->isChecked());
206 ✔
493
  connect(ui->actionShowMenuBar, &QAction::toggled, this, [this](bool show) {
206 ✔
494
    menuBar()->setVisible(show);
5 ✔
495
    AppSettings s = QtPassSettings::load();
5 ✔
496
    s.showMenuBar = show;
5 ✔
497
    QtPassSettings::save(s);
5 ✔
498
  });
5 ✔
499
  new MenuBarPeek(this, ui->actionShowMenuBar);
206 ✔
500
#endif
501
  connect(ui->actionFaq, &QAction::triggered, this, [] {
207 ✔
502
    QDesktopServices::openUrl(QUrl(QStringLiteral("https://qtpass.org/faq")));
2 ✔
503
  });
1 ✔
504
  connect(ui->actionAbout, &QAction::triggered, this, &MainWindow::showAbout);
206 ✔
505
  connect(ui->actionAboutQt, &QAction::triggered, qApp, &QApplication::aboutQt);
206 ✔
506

507
  ui->actionAddPassword->setIcon(
206 ✔
508
      QIcon::fromTheme("document-new", QIcon(":/icons/document-new.svg")));
824 ✔
509
  ui->actionAddFolder->setIcon(
206 ✔
510
      QIcon::fromTheme("folder-new", QIcon(":/icons/folder-new.svg")));
824 ✔
511
  ui->actionEdit->setIcon(QIcon::fromTheme(
206 ✔
512
      "document-properties", QIcon(":/icons/document-properties.svg")));
618 ✔
513
  ui->actionDelete->setIcon(
206 ✔
514
      QIcon::fromTheme("edit-delete", QIcon(":/icons/edit-delete.svg")));
824 ✔
515
  ui->actionPush->setIcon(
206 ✔
516
      QIcon::fromTheme("go-up", QIcon(":/icons/go-top.svg")));
824 ✔
517
  ui->actionUpdate->setIcon(
206 ✔
518
      QIcon::fromTheme("go-down", QIcon(":/icons/go-bottom.svg")));
824 ✔
519
  ui->actionUsers->setIcon(QIcon::fromTheme(
206 ✔
520
      "x-office-address-book", QIcon(":/icons/x-office-address-book.svg")));
618 ✔
521
  ui->actionConfig->setIcon(QIcon::fromTheme(
206 ✔
522
      "applications-system", QIcon(":/icons/applications-system.svg")));
412 ✔
523
}
206 ✔
524

525
void MainWindow::initStatusBar() {
206 ✔
526
  ui->statusBar->showMessage(tr("Welcome to QtPass %1").arg(VERSION), 2000);
412 ✔
527

528
  QPixmap logo = QPixmap::fromImage(QImage(":/artwork/icon.svg"))
412 ✔
529
                     .scaledToHeight(statusBar()->height());
206 ✔
530
  auto *logoApp = new QLabel(statusBar());
206 ✔
531
  logoApp->setPixmap(logo);
206 ✔
532
  m_stopButton = new QPushButton(tr("Stop"), statusBar());
412 ✔
533
  m_stopButton->setObjectName(QStringLiteral("stopButton"));
412 ✔
534
  m_stopButton->setToolTip(
206 ✔
535
      tr("Stop the gpg, git or pass run that is still going"));
206 ✔
536
  m_stopButton->hide();
206 ✔
537
  connect(m_stopButton, &QPushButton::clicked, this, [this]() {
206 ✔
538
    Pass *pass = QtPassSettings::getPass();
6 ✔
539
    if (pass == nullptr || pass->isIdle()) {
6 ✔
540
      m_stopButton->hide();
×
541
      return;
2 ✔
542
    }
543
    const Enums::PROCESS pid = pass->runningProcess();
544
    const quint64 run = pass->runningSerial();
545
    const QString label = runLabel(pid);
6 ✔
546
    // A decrypt or a search changes nothing. Anything else may be half done
547
    // when stopped: some entries re-encrypted and others not, a Git step cut
548
    // off with its lock left behind.
549
    const bool writes = pid != Enums::PASS_SHOW && pid != Enums::PASS_GREP;
6 ✔
550
    if (writes) {
6 ✔
551
      const auto answer = QMessageBox::question(
8 ✔
552
          this, tr("Stop %1?").arg(label),
8 ✔
553
          tr("%1 has not finished. Stopping it can leave its change half "
4 ✔
554
             "done: some entries re-encrypted and others not, or a Git step "
555
             "cut off, after which Git may refuse to run until "
556
             ".git/index.lock is removed.\n\nStop it anyway?")
557
              .arg(label),
8 ✔
558
          QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
559
      // The queue may have moved on while the question was open: stop
560
      // nothing but what was asked about.
561
      if (answer != QMessageBox::Yes || pass->runningSerial() != run) {
7 ✔
562
        return;
563
      }
564
    }
565
    m_stopButton->hide();
4 ✔
566
    if (pass->stopRunning()) {
4 ✔
567
      showStatusMessage(
4 ✔
568
          writes ? tr("Stopped %1 before it finished; the store may be "
12 ✔
569
                      "partly changed.")
570
                       .arg(label)
571
                 : tr("Stopped %1.").arg(label));
6 ✔
572
    }
573
  });
574
  statusBar()->addPermanentWidget(m_stopButton);
206 ✔
575
  statusBar()->addPermanentWidget(logoApp);
206 ✔
576
}
206 ✔
577

578
auto MainWindow::getCurrentTreeViewIndex() -> QModelIndex {
11 ✔
579
  return ui->treeView->currentIndex();
11 ✔
580
}
581

582
void MainWindow::flashText(const QString &text, const bool isError,
303 ✔
583
                           const bool isHtml) {
584
  // setText() applies the current char format to the whole message. Start
585
  // from an empty one: inherited from a cursor on a linkified URL it carried
586
  // the anchor, and the message became a link to that address. No colour
587
  // but red for an error, so text follows runtime light/dark switches (#946).
588
  QTextCursor cursor = ui->textBrowser->textCursor();
303 ✔
589
  cursor.clearSelection();
303 ✔
590
  ui->textBrowser->setTextCursor(cursor);
303 ✔
591
  QTextCharFormat format;
303 ✔
592
  if (isError) {
303 ✔
593
    format.setForeground(QColor(Qt::red));
11 ✔
594
  }
595
  ui->textBrowser->setCurrentCharFormat(format);
303 ✔
596

597
  // Wrapped at word boundaries, a run of hundreds of thousands of letters
598
  // took Qt seconds to minutes; anywhere, it is linear. Anywhere while the
599
  // text goes in, then word wrap back unless what is shown has such a run:
600
  // markup (a link's "<a href") splits a run in the source, not on screen.
601
  ui->textBrowser->setWordWrapMode(QTextOption::WrapAnywhere);
303 ✔
602
  if (isHtml) {
303 ✔
603
    QString _text = text;
604
    // What was shown before this message: the part the cap may remove.
605
    // The message itself is never cut, so an entry shown through here
606
    // (passShowHandler()) stays whole however long it is.
607
    int older = 0;
284 ✔
608
    if (!ui->textBrowser->toPlainText().isEmpty()) {
568 ✔
609
      older = ui->textBrowser->document()->characterCount() - 1;
224 ✔
610
      _text = ui->textBrowser->toHtml() + _text;
448 ✔
611
    }
612
    ui->textBrowser->setHtml(_text);
284 ✔
613
    // Only the latest output: from the front, up to the start of the first
614
    // paragraph that ends the excess, within what was shown before (a
615
    // message that starts a paragraph starts one past it, after the
616
    // separator).
617
    QTextDocument *doc = ui->textBrowser->document();
284 ✔
618
    int cut = qMin(doc->characterCount() - kMaxFlashCharacters, older);
284 ✔
619
    if (cut > 0) {
284 ✔
620
      const QTextBlock block = doc->findBlock(cut);
140 ✔
621
      if (block.isValid() && cut > block.position() && block.next().isValid() &&
140 ✔
622
          block.next().position() <= older + 1) {
140 ✔
623
        cut = block.next().position();
140 ✔
624
      }
625
      QTextCursor trim(doc);
140 ✔
626
      trim.setPosition(cut, QTextCursor::KeepAnchor);
140 ✔
627
      trim.removeSelectedText();
140 ✔
628
    }
140 ✔
629
  } else {
630
    ui->textBrowser->setText(text);
19 ✔
631
  }
632
  // The raw text: toPlainText() turns a no-break space into a plain one.
633
  if (!Util::hasLongUnbrokenRun(ui->textBrowser->document()->toRawText())) {
606 ✔
634
    ui->textBrowser->setWordWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
297 ✔
635
  }
636
}
303 ✔
637

638
void MainWindow::applyTextBrowserSettings() {
5 ✔
639
  const AppSettings s = QtPassSettings::load();
5 ✔
640
  if (s.useMonospace) {
5 ✔
641
    QFont monospace("Monospace");
1 ✔
642
    monospace.setStyleHint(QFont::Monospace);
1 ✔
643
    ui->textBrowser->setFont(monospace);
1 ✔
644
  } else {
1 ✔
645
    ui->textBrowser->setFont(QFont());
4 ✔
646
  }
647

648
  if (s.noLineWrapping) {
5 ✔
649
    ui->textBrowser->setLineWrapMode(QTextBrowser::NoWrap);
1 ✔
650
  } else {
651
    ui->textBrowser->setLineWrapMode(QTextBrowser::WidgetWidth);
4 ✔
652
  }
653
}
5 ✔
654

655
void MainWindow::applyWindowFlagsSettings() {
222 ✔
656
  const bool wantOnTop = QtPassSettings::isAlwaysOnTop();
222 ✔
657
  const Qt::WindowFlags flags = windowFlags();
658
  if (flags.testFlag(Qt::WindowStaysOnTopHint) == wantOnTop) {
222 ✔
659
    // setWindowFlags() rebuilds the native window, the teardown that left
660
    // ui->lineEdit dangling (see focusInput()); skip it when nothing changes.
661
    return;
662
  }
663
  // Toggle just this hint; resetting to Qt::Window discarded every other flag.
664
  const bool wasVisible = isVisible();
665
  setWindowFlags(wantOnTop ? (flags | Qt::WindowStaysOnTopHint)
4 ✔
666
                           : (flags & ~Qt::WindowStaysOnTopHint));
667
  // setWindowFlags() hides a shown window; a window that was not shown yet
668
  // (first-run wizard from the constructor) is left to its normal show.
669
  if (wasVisible) {
2 ✔
670
    show();
2 ✔
671
  }
672
}
673

674
auto MainWindow::config() -> bool {
8 ✔
675
  if (m_freshStart) {
8 ✔
676
    // No usable configuration yet: the wizard finds the programs, the key
677
    // and the store, and creates the store when it has to.
678
    FirstRunWizard wizard(this);
2 ✔
679
    if (wizard.exec() != QDialog::Accepted) {
2 ✔
680
      return false;
681
    }
682
  } else {
2 ✔
683
    ConfigDialog d(this);
6 ✔
684
    d.setModal(true);
6 ✔
685
    if (d.exec() != QDialog::Accepted) {
6 ✔
686
      return false;
687
    }
688
  }
6 ✔
689

690
  applyTextBrowserSettings();
5 ✔
691
  applyWindowFlagsSettings();
5 ✔
692

693
  updateProfileBox();
5 ✔
694
  const AppSettings s = QtPassSettings::load();
5 ✔
695
  // An open still waiting for the tree was asked of the old view; once
696
  // re-rooted, it would find that name in the new store. A profile switch
697
  // ends it by clearing the search text.
698
  delete m_pendingOpen;
5 ✔
699
  // A content search still running searched the old store, and its matches
700
  // would be listed for this one: onGrepFinished() cannot tell. Cancelled,
701
  // and content-search results on screen go with it (clearPanel()).
702
  cancelContentSearch();
5 ✔
703
  if (m_grep.cancelSearch()) {
704
    QApplication::restoreOverrideCursor();
1 ✔
705
  }
706
  clearPanel(false);
5 ✔
707
  m_tree->setStore(s.passStore);
5 ✔
708
  deselect();
5 ✔
709
  ui->treeView->setCurrentIndex(QModelIndex());
5 ✔
710

711
  Pass *activePass = QtPassSettings::getPass();
5 ✔
712
  activePass->updateEnv();
5 ✔
713
  m_tree->setPass(activePass);
5 ✔
714
  clearPanelTimer.setInterval(MS_PER_SECOND * s.autoclearPanelSeconds);
5 ✔
715
  clearResultsTimer.setInterval(clearPanelTimer.interval());
5 ✔
716
  m_qtPass->clipboard().setAutoclearTimer();
5 ✔
717

718
  updateGitButtonVisibility();
5 ✔
719
  updateOtpButtonVisibility();
5 ✔
720
  updateGrepButtonVisibility();
5 ✔
721
  updateProcessOutputVisibility();
5 ✔
722
#ifndef Q_OS_MACOS
723
  // The action's toggled handler shows or hides the bar (and saves again).
724
  ui->actionShowMenuBar->setChecked(s.showMenuBar);
5 ✔
725
#endif
726
  if (s.useTrayIcon && m_tray == nullptr) {
5 ✔
727
    initTrayIcon();
1 ✔
728
  } else if (!s.useTrayIcon && m_tray != nullptr) {
4 ✔
729
    destroyTrayIcon();
×
730
  }
731

732
  // Stay fresh-start while the configuration is unusable, so the
733
  // constructor's loop re-runs the wizard. The re-prompt lives there:
734
  // recursing here never reported a cancel back to the caller.
735
  if (Util::configIsValid(s)) {
5 ✔
736
    m_freshStart = false;
5 ✔
737
  }
738
  return true;
739
}
5 ✔
740

741
void MainWindow::onUpdate(bool block) {
2 ✔
742
  ui->statusBar->showMessage(tr("Updating password-store"), 2000);
2 ✔
743
  if (block) {
2 ✔
744
    QtPassSettings::getPass()->GitPull_b(Pass::kBlockingPullMs);
1 ✔
745
  } else {
746
    QtPassSettings::getPass()->GitPull();
1 ✔
747
  }
748
}
2 ✔
749

750
void MainWindow::onPush() {
1 ✔
751
  if (QtPassSettings::isUseGit()) {
1 ✔
752
    ui->statusBar->showMessage(tr("Updating password-store"), 2000);
1 ✔
753
    QtPassSettings::getPass()->GitPush();
1 ✔
754
  }
755
}
1 ✔
756

757
void MainWindow::onAutoPush() {
8 ✔
758
  if (QtPassSettings::isUseGit()) {
8 ✔
759
    ui->statusBar->showMessage(tr("Updating password-store"), 2000);
8 ✔
760
    QtPassSettings::getPass()->GitPushAutomatic();
8 ✔
761
  }
762
}
8 ✔
763

764
auto MainWindow::getFile(const QModelIndex &index, bool forPass) -> QString {
68 ✔
765
  return m_tree->fileFor(index, forPass);
68 ✔
766
}
767

768
void MainWindow::on_treeView_clicked(const QModelIndex &index) {
27 ✔
769
  bool cleared = ui->treeView->currentIndex().flags() == Qt::NoItemFlags;
27 ✔
770
  QString file = getFile(index, true);
27 ✔
771
  ui->passwordName->setText(Util::shownName(file));
54 ✔
772
  if (!file.isEmpty() && !cleared) {
27 ✔
773
    // Remember what the panel is about to show, so onOtp() can tell whether the
774
    // code it can see belongs to the entry that is currently selected.
775
    m_shownFile = file;
26 ✔
776
    QtPassSettings::getPass()->Show(file);
52 ✔
777
  } else {
778
    m_shownFile.clear();
1 ✔
779
    clearPanel(false);
1 ✔
780
    ui->actionEdit->setEnabled(false);
1 ✔
781
    ui->actionDelete->setEnabled(true);
1 ✔
782
  }
783
}
27 ✔
784

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

788
  if (fileOrFolder.isFile()) {
4 ✔
789
    editPassword(getFile(index, true));
6 ✔
790
  }
791
}
4 ✔
792

793
void MainWindow::deselect() {
21 ✔
794
  m_shownFile.clear();
21 ✔
795
  cancelOtpRequest();
21 ✔
796
  m_qtPass->clipboard().clear();
21 ✔
797
  ui->treeView->clearSelection();
21 ✔
798
  // The current index too: clearSelection() keeps it, and whatever asks for
799
  // the "current" folder (Users, Add password, Add folder) took the hidden
800
  // entry it was left on, such as the first hit of a search just emptied.
801
  ui->treeView->setCurrentIndex(QModelIndex());
21 ✔
802
  ui->actionEdit->setEnabled(false);
21 ✔
803
  ui->actionDelete->setEnabled(false);
21 ✔
804
  ui->passwordName->setText("");
21 ✔
805
  clearPanel(false);
21 ✔
806
}
21 ✔
807

808
void MainWindow::executeWrapperStarted() {
78 ✔
809
  m_displayPanel->clear();
78 ✔
810
  m_panelEntry.clear();
78 ✔
811
  ui->textBrowser->clear();
78 ✔
812
  setUiElementsEnabled(false);
78 ✔
813
  clearPanelTimer.stop();
78 ✔
814
  if (QtPassSettings::isShowProcessOutput()) {
78 ✔
815
    m_processOutput->setVisible(true);
73 ✔
816
  }
817
}
78 ✔
818

819
void MainWindow::passShowHandler(const QString &p_output, const QString &file) {
42 ✔
820
  // Only the entry we most recently asked to show may repaint the panel; a
821
  // slower decrypt of an entry the user has since left is dropped, and so is
822
  // one that arrives after the selection was cleared (deselect, a profile
823
  // switch): nothing is asked to be shown then.
824
  if (!file.isEmpty() && file != m_shownFile) {
42 ✔
825
    // A newer show is pending and releases the interface when it lands;
826
    // with none (the selection was cleared) nothing else would until the
827
    // watchdog. setUiElementsEnabled() keeps a re-encryption's lock.
828
    if (m_shownFile.isEmpty()) {
10 ✔
829
      setUiElementsEnabled(true);
8 ✔
830
    }
831
    return;
10 ✔
832
  }
833
  const AppSettings s = QtPassSettings::load();
32 ✔
834
  refreshMarkedSecrets(s);
32 ✔
835
  QStringList templ =
836
      s.useTemplate ? TemplateIO::fieldsIn(s.passTemplate) : QStringList();
32 ✔
837
  bool allFields = s.useTemplate && s.templateAllFields;
32 ✔
838
  // A secret the panel hides is a field even when the template doesn't list
839
  // it: left in the text below the fields, it would show in plain view.
840
  FileContent fileContent = FileContent::parse(
841
      p_output, templ, allFields, [this, &s](const QString &name) {
32 ✔
842
        return m_displayPanel->isSecret(name, s);
19 ✔
843
      });
32 ✔
844
  QString output = p_output;
845
  // Display variant: empty when the password line is itself an otpauth URI, so
846
  // the shared secret is neither rendered nor copied to the clipboard.
847
  QString password = fileContent.getPasswordForDisplay();
32 ✔
848

849
  // Skipped for an OTP request: the user asked for a code, and two
850
  // OleSetClipboard calls in one turn can leave the Windows clipboard empty.
851
  if (m_otpRequestFile.isEmpty() || m_otpRequestFile != file) {
32 ✔
852
    m_qtPass->clipboard().copyIfAlways(password, p_output);
30 ✔
853
  }
854

855
  m_displayPanel->clear();
32 ✔
856
  m_panelEntry.clear();
32 ✔
857

858
  if (s.hideContent) {
32 ✔
859
    output = "***" + tr("Content hidden") + "***";
4 ✔
860
  } else if (s.displayAsIs) {
30 ✔
861
    // As it is, but not a block per line of millions.
862
    output = FileContent::boundedForDisplay(p_output);
4 ✔
863
  } else {
864
    m_panelEntry = file;
28 ✔
865
    m_displayPanel->displayFields(password, fileContent.getNamedValues(), s,
56 ✔
866
                                  s.useOtp ? fileContent.getOtpUri()
28 ✔
867
                                           : QString());
868
    output = fileContent.getRemainingDataForDisplay();
56 ✔
869
  }
870

871
  if (s.useAutoclearPanel) {
32 ✔
872
    clearPanelTimer.start();
3 ✔
873
  }
874

875
  // Shown as it is, the text holds the password and every secret field: no
876
  // links in it, or a click on a URL-shaped one handed it to the browser.
877
  flashText(QtPass::formatOutput(output, QString(), QString(),
64 ✔
878
                                 !s.displayAsIs || s.hideContent),
32 ✔
879
            false, true);
880
  setUiElementsEnabled(true);
32 ✔
881
}
64 ✔
882

883
void MainWindow::otpFromFileToClipboard(const QString &p_output,
31 ✔
884
                                        const QString &file) {
885
  // Permanently connected: only the decrypt of the entry onOtp() asked for
886
  // is ours, everything else belongs to a tree click or a Ctrl+C.
887
  if (m_otpRequestFile.isEmpty() || file != m_otpRequestFile) {
31 ✔
888
    return;
27 ✔
889
  }
890
  m_otpRequestFile.clear();
6 ✔
891

892
  if (p_output.isEmpty()) {
6 ✔
893
    // Distinguish "could not read the entry" from "entry has no OTP".
894
    flashText(tr("Could not decrypt this password entry"), true);
1 ✔
895
    setUiElementsEnabled(true);
1 ✔
896
    return;
1 ✔
897
  }
898

899
  // passShowHandler ran first for this finishedShow; if it rendered the OTP
900
  // row, reuse its code (as onOtp()'s fast path does). Otherwise parse:
901
  // hideContent, displayAsIs or no OTP field.
902
  const QString shown = m_displayPanel->currentOtpCode();
5 ✔
903
  if (!shown.isEmpty()) {
5 ✔
904
    m_qtPass->clipboard().copyText(shown);
1 ✔
905
    showStatusMessage(tr("OTP code copied to clipboard"));
1 ✔
906
    setUiElementsEnabled(true);
1 ✔
907
    return;
908
  }
909

910
  const AppSettings s = QtPassSettings::load();
4 ✔
911
  // Parse with the same template settings passShowHandler uses, so an OTP
912
  // field is recognised identically in both paths.
913
  const QStringList templ =
914
      s.useTemplate ? TemplateIO::fieldsIn(s.passTemplate) : QStringList();
4 ✔
915
  const bool allFields = s.useTemplate && s.templateAllFields;
4 ✔
916
  const FileContent fileContent =
917
      FileContent::parse(p_output, templ, allFields);
4 ✔
918

919
  Totp::Refusal why = Totp::Refusal::None;
4 ✔
920
  const std::optional<Totp::Settings> settings =
921
      Totp::parse(fileContent.getOtpUri(), &why);
8 ✔
922
  if (settings.has_value()) {
4 ✔
923
    m_qtPass->clipboard().copyText(Totp::generateNow(*settings));
4 ✔
924
    showStatusMessage(tr("OTP code copied to clipboard"));
4 ✔
925
  } else {
926
    // Why, when there is a configuration that gives no code.
927
    const QString reason = Totp::describe(why);
2 ✔
928
    flashText(reason.isEmpty() ? tr("No OTP code found in this password entry")
6 ✔
929
                               : reason,
930
              true);
931
  }
932
  setUiElementsEnabled(true);
4 ✔
933
}
8 ✔
934

935
void MainWindow::clearPanel(bool notify) {
67 ✔
936
  clearShownEntry(notify);
67 ✔
937
  clearContentResults();
67 ✔
938
}
67 ✔
939

940
void MainWindow::clearShownEntry(bool notify) {
69 ✔
941
  m_displayPanel->clear();
69 ✔
942
  m_panelEntry.clear();
69 ✔
943
  // A QR code of the password is the password on screen as much as the
944
  // panel is; it is a popup of its own, not part of the panel.
945
  m_qtPass->closeQRCode();
69 ✔
946
  if (notify) {
69 ✔
947
    QString output = "***" + tr("Password and content hidden") + "***";
4 ✔
948
    ui->textBrowser->setHtml(output);
2 ✔
949
  } else {
950
    ui->textBrowser->setHtml("");
134 ✔
951
  }
952
}
69 ✔
953

954
void MainWindow::clearContentResults() {
70 ✔
955
  clearResultsTimer.stop();
70 ✔
956
  const bool grepWasVisible = ui->grepResultsList->isVisible();
70 ✔
957
  ui->grepResultsList->clear();
70 ✔
958
  if (grepWasVisible) {
70 ✔
959
    showContentResults(false);
7 ✔
960
    if (m_grep.inGrepMode()) {
7 ✔
961
      // Left as the button leaves it: a search still running would otherwise
962
      // hand its partial matches to a content search entered meanwhile.
963
      cancelContentSearch();
7 ✔
964
      if (m_grep.leaveGrepMode()) {
965
        QApplication::restoreOverrideCursor();
2 ✔
966
      }
967
      ui->grepButton->blockSignals(true);
7 ✔
968
      ui->grepButton->setChecked(false);
7 ✔
969
      ui->grepButton->blockSignals(false);
7 ✔
970
      ui->lineEdit->blockSignals(true);
7 ✔
971
      ui->lineEdit->clear();
7 ✔
972
      ui->lineEdit->blockSignals(false);
7 ✔
973
      ui->lineEdit->setPlaceholderText(tr("Search password"));
14 ✔
974
    }
975
  }
976
}
70 ✔
977

978
void MainWindow::setUiElementsEnabled(bool state) {
477 ✔
979
  // A running re-encryption owns the UI state: the progress dialog's Cancel is
980
  // the user's escape hatch and endReencryptPath() releases the interface, so
981
  // neither an unrelated completion nor the watchdog may re-enable it early.
982
  if (state && m_reencryptRunning) {
477 ✔
983
    m_uiWatchdog.stop();
1 ✔
984
    return;
1 ✔
985
  }
986
  // Arm the watchdog while the UI is disabled; disarm once re-enabled.
987
  if (state) {
988
    m_uiWatchdog.stop();
374 ✔
989
  } else {
990
    m_uiWatchdog.start();
102 ✔
991
  }
992
  ui->treeView->setEnabled(state);
476 ✔
993
  ui->lineEdit->setEnabled(state);
476 ✔
994
  ui->actionAddPassword->setEnabled(state);
476 ✔
995
  ui->actionAddFolder->setEnabled(state);
476 ✔
996
  ui->actionUsers->setEnabled(state);
476 ✔
997
  ui->actionConfig->setEnabled(state);
476 ✔
998
  m_uiEnabled = state;
476 ✔
999
  updateProfileBoxEnabled();
476 ✔
1000
  const bool uiEnabled = state;
1001
  // is a file selected, and in sight (content search results hide the tree)?
1002
  state &= ui->treeView->currentIndex().isValid() && !ui->treeView->isHidden();
955 ✔
1003
  ui->actionDelete->setEnabled(state);
476 ✔
1004
  ui->actionEdit->setEnabled(state);
476 ✔
1005
  updateGitButtonVisibility(uiEnabled);
476 ✔
1006
  // `state` is now "UI enabled AND a file is selected", which is exactly when
1007
  // generating an OTP makes sense.
1008
  updateOtpButtonVisibility(state);
476 ✔
1009
}
1010

1011
void MainWindow::restoreWindow() {
217 ✔
1012
  // saveGeometry() covers position, size, maximized state and screen;
1013
  // anything applied on top discards it. Centre only when nothing was saved.
1014
  const QByteArray geometry = QtPassSettings::getGeometry();
434 ✔
1015
  if (geometry.isEmpty() || !restoreGeometry(geometry)) {
217 ✔
1016
    WindowStateStore::centreOnCursorScreen(*this);
4 ✔
1017
  }
1018
  restoreState(QtPassSettings::getSavestate(saveState()));
217 ✔
1019
  const AppSettings s = QtPassSettings::load();
217 ✔
1020

1021
  applyWindowFlagsSettings();
217 ✔
1022

1023
  if (s.useTrayIcon && m_tray == nullptr) {
217 ✔
1024
    initTrayIcon();
2 ✔
1025
    // Minimized to the tray only when there is one: without a system tray
1026
    // initTrayIcon() gave up, and a hidden window could not be brought back.
1027
    if (s.startMinimized && m_tray != nullptr) {
2 ✔
1028
      // since we are still in constructor, can't directly hide
1029
      QTimer::singleShot(10, this, &MainWindow::hide);
×
1030
    }
1031
  } else if (!s.useTrayIcon && m_tray != nullptr) {
215 ✔
1032
    destroyTrayIcon();
×
1033
  }
1034
}
434 ✔
1035

1036
void MainWindow::onConfig() {
3 ✔
1037
  // No Settings while anything of the store runs or waits, as with the
1038
  // profile box (#2071): the store, backend and programs chosen there apply
1039
  // to what is still queued, so a pending `pass init` re-encrypted the store
1040
  // just picked for the recipients chosen for the other. Asked of the
1041
  // backends: the watchdog releases the interface while a slow gpg or git
1042
  // still runs.
1043
  if (!QtPassSettings::backendsIdle()) {
3 ✔
1044
    critical(tr("Settings not opened"),
2 ✔
1045
             tr("A gpg, Git or pass command is still running or waiting. "
1 ✔
1046
                "Open the settings again once it has finished. If it does "
1047
                "not finish, answer or cancel the PIN or password prompt it "
1048
                "waits for, or restart QtPass. A restart forgets which "
1049
                "folders still need re-encrypting: re-encrypt any folder "
1050
                "whose re-encryption did not finish, or that you moved "
1051
                "entries into, before anything is pushed."));
1052
    return;
1 ✔
1053
  }
1054
  config();
2 ✔
1055
}
1056

1057
void MainWindow::showAbout() {
1 ✔
1058
  QMessageBox::about(
1 ✔
1059
      this, tr("About QtPass"),
1 ✔
1060
      tr("<h3>QtPass %1</h3>"
1 ✔
1061
         "<p>A multi-platform GUI for <a "
1062
         "href=\"https://www.passwordstore.org/\">"
1063
         "pass</a>, the standard Unix password manager.</p>"
1064
         "<p><a href=\"https://qtpass.org/\">qtpass.org</a> &middot; "
1065
         "<a href=\"https://github.com/IJHack/QtPass\">Source and "
1066
         "issues</a></p>"
1067
         "<p>Copyright &copy; 2014&ndash;%2 IJhack. Licensed under the "
1068
         "<a href=\"https://www.gnu.org/licenses/gpl-3.0.html\">GNU GPL "
1069
         "version 3</a> or later.</p>")
1070
          .arg(QStringLiteral(VERSION),
2 ✔
1071
               QString::number(QDate::currentDate().year())));
2 ✔
1072
}
1 ✔
1073

1074
void MainWindow::on_lineEdit_textChanged(const QString &arg1) {
50 ✔
1075
  if (m_grep.inGrepMode())
50 ✔
1076
    return;
1077
  ui->statusBar->showMessage(tr("Looking for: %1").arg(arg1), 1000);
74 ✔
1078
  ui->treeView->expandAll();
37 ✔
1079
  // Drop any decrypt still pending for the entry that was shown: otherwise it
1080
  // keeps its right to the panel and, with "Always copy", the clipboard, and
1081
  // when it lands late it shows that entry's password under the new heading.
1082
  m_shownFile.clear();
37 ✔
1083
  cancelOtpRequest();
37 ✔
1084
  clearPanel(false);
37 ✔
1085
  ui->passwordName->setText("");
74 ✔
1086
  ui->actionEdit->setEnabled(false);
37 ✔
1087
  ui->actionDelete->setEnabled(false);
37 ✔
1088
  searchTimer.start();
37 ✔
1089
}
1090

1091
void MainWindow::onTimeoutSearch() {
42 ✔
1092
  // The tree matches slash-separated paths: on Windows, team\bank typed is
1093
  // team/bank, as exactMatchPath() reads it too.
1094
  QString query = QDir::fromNativeSeparators(ui->lineEdit->text());
84 ✔
1095

1096
  if (query.isEmpty()) {
42 ✔
1097
    ui->treeView->collapseAll();
2 ✔
1098
    deselect();
2 ✔
1099
  }
1100

1101
  // The words are matched literally, in order, with anything in between:
1102
  // "work vpn" finds work/acme/vpn.
1103
  m_tree->setFilter(StoreModel::wordsFilter(query));
42 ✔
1104

1105
  if (m_tree->proxy().rowCount() > 0 && !query.isEmpty()) {
42 ✔
1106
    selectFirstFile();
29 ✔
1107
  } else {
1108
    ui->actionEdit->setEnabled(false);
13 ✔
1109
    ui->actionDelete->setEnabled(false);
13 ✔
1110
  }
1111
}
42 ✔
1112

1113
void MainWindow::on_lineEdit_returnPressed() {
17 ✔
1114
  qCDebug(lcQtPass) << "on_lineEdit_returnPressed"
17 ✔
1115
                    << m_tree->proxy().rowCount();
×
1116

1117
  if (m_grep.inGrepMode()) {
17 ✔
1118
    const QString query = ui->lineEdit->text();
12 ✔
1119
    if (!query.isEmpty()) {
12 ✔
1120
      ui->grepResultsList->clear();
9 ✔
1121
      ui->statusBar->showMessage(tr("Searching…"));
18 ✔
1122
      if (m_grep.beginSearch()) {
1123
        QApplication::setOverrideCursor(Qt::WaitCursor);
9 ✔
1124
      }
1125
      QtPassSettings::getPass()->Grep(query, ui->grepCaseButton->isChecked());
18 ✔
1126
    } else {
1127
      cancelContentSearch();
3 ✔
1128
      if (m_grep.cancelSearch()) {
1129
        QApplication::restoreOverrideCursor();
2 ✔
1130
      }
1131
      ui->grepResultsList->clear();
3 ✔
1132
      showContentResults(false);
3 ✔
1133
    }
1134
    return;
1135
  }
1136

1137
  // Return within the search delay acts on the text as typed, not on the
1138
  // tree as the previous text filtered it.
1139
  if (searchTimer.isActive()) {
5 ✔
1140
    searchTimer.stop();
5 ✔
1141
    onTimeoutSearch();
5 ✔
1142
  }
1143
  if (m_tree->proxy().rowCount() > 0) {
5 ✔
1144
    selectFirstFile();
5 ✔
1145
    on_treeView_clicked(ui->treeView->currentIndex());
5 ✔
1146
  }
1147
}
1148

1149
void MainWindow::on_grepButton_toggled(bool checked) {
35 ✔
1150
  const AppSettings s = QtPassSettings::load();
35 ✔
1151
  if (checked) {
35 ✔
1152
    m_grep.enterGrepMode();
1153
    ui->lineEdit->setPlaceholderText(tr("Search content (regex)"));
44 ✔
1154
    // Both backends search through NativeGrep (QRegularExpression), so one
1155
    // dialect: PCRE.
1156
    ui->lineEdit->setToolTip(
22 ✔
1157
        tr("Content search uses Perl-compatible regular expressions (PCRE)."));
22 ✔
1158
    ui->lineEdit->clear();
22 ✔
1159
    searchTimer.stop();
22 ✔
1160
    m_tree->setFilter(QRegularExpression());
22 ✔
1161
    ui->grepResultsList->setVisible(false);
22 ✔
1162
    // Keep treeView visible until results arrive
1163
  } else {
1164
    cancelContentSearch();
13 ✔
1165
    if (m_grep.leaveGrepMode()) {
1166
      QApplication::restoreOverrideCursor();
2 ✔
1167
    }
1168
    searchTimer.stop();
13 ✔
1169
    ui->lineEdit->blockSignals(true);
13 ✔
1170
    ui->lineEdit->clear();
13 ✔
1171
    ui->lineEdit->blockSignals(false);
13 ✔
1172
    ui->lineEdit->setPlaceholderText(tr("Search password"));
26 ✔
1173
    ui->lineEdit->setToolTip(QString());
26 ✔
1174
    ui->grepResultsList->clear();
13 ✔
1175
    showContentResults(false);
13 ✔
1176
    m_tree->setFilter(QRegularExpression());
13 ✔
1177
  }
1178
}
35 ✔
1179

1180
void MainWindow::refreshMarkedSecrets(const AppSettings &s) {
42 ✔
1181
  if (s.hidePassword) {
42 ✔
1182
    m_displayPanel->setMarkedSecrets(
4 ✔
1183
        TemplateIO::secretFieldsIn(s.passTemplate) +
8 ✔
1184
        TemplateIO::readSecretFields(s.passStore));
12 ✔
1185
  }
1186
}
42 ✔
1187

1188
auto MainWindow::grepLineForDisplay(const QString &line,
43 ✔
1189
                                    const AppSettings &s) const -> QString {
1190
  const QString hidden =
1191
      QStringLiteral("***") + tr("hidden") + QStringLiteral("***");
86 ✔
1192
  if (NativeGrep::isOtpMarker(line)) {
43 ✔
1193
    return tr("One-time password secret: %1").arg(hidden);
2 ✔
1194
  }
1195
  // The panel's own rules: the password and a field it would put behind
1196
  // the eye button keep their value out of the list too.
1197
  if (NativeGrep::isPasswordMatch(line)) {
1198
    return m_displayPanel->hides(QObject::tr("Password"), s)
52 ✔
1199
               ? tr("Password: %1").arg(hidden)
52 ✔
1200
               : NativeGrep::passwordMatchText(line);
26 ✔
1201
  }
1202
  if (const qsizetype colon = line.indexOf(QLatin1Char(':')); colon > 0) {
15 ✔
1203
    if (m_displayPanel->hides(line.left(colon).trimmed(), s)) {
39 ✔
1204
      return line.left(colon + 1) + QLatin1Char(' ') + hidden;
4 ✔
1205
    }
1206
  }
1207
  return line;
1208
}
1209

1210
void MainWindow::onGrepFinished(
21 ✔
1211
    const QList<QPair<QString, QStringList>> &results) {
1212
  // Both backends stay connected, each with its own search: a search the
1213
  // other backend was still running when Settings switched backends is not
1214
  // this one, whatever the controller's state, and searched another store.
1215
  // Dropped before it can end (or be taken for) the current search.
1216
  if (const QObject *from = sender();
21 ✔
1217
      from != nullptr && from != QtPassSettings::getPass()) {
21 ✔
1218
    return;
11 ✔
1219
  }
1220
  const GrepSearchController::FinishOutcome outcome = m_grep.finishSearch();
1221
  if (outcome.restoreCursor) {
20 ✔
1222
    QApplication::restoreOverrideCursor();
2 ✔
1223
  }
1224
  // Re-enable the UI before the discard check so a cancelled search can never
1225
  // leave controls disabled.
1226
  setUiElementsEnabled(true);
20 ✔
1227
  if (outcome.discard) {
20 ✔
1228
    return;
1229
  }
1230
  if (!m_grep.inGrepMode())
12 ✔
1231
    return;
1232
  ui->grepResultsList->clear();
12 ✔
1233
  if (results.isEmpty()) {
12 ✔
1234
    ui->statusBar->showMessage(tr("No matches found."), 3000);
2 ✔
1235
    showContentResults(false);
2 ✔
1236
    return;
2 ✔
1237
  }
1238
  const AppSettings s = QtPassSettings::load();
10 ✔
1239
  const bool hideContent = s.hideContent;
10 ✔
1240
  refreshMarkedSecrets(s);
10 ✔
1241
  int totalLines = 0;
1242
  int entries = 0;
1243
  bool stopped = false;
1244
  for (const auto &pair : results) {
43 ✔
1245
    if (NativeGrep::isStoppedMarker(pair)) {
33 ✔
1246
      stopped = true;
1247
      continue;
×
1248
    }
1249
    ++entries;
33 ✔
1250
    auto *entryItem = new QTreeWidgetItem(ui->grepResultsList);
33 ✔
1251
    entryItem->setText(0, pair.first);
33 ✔
1252
    entryItem->setData(0, Qt::UserRole, pair.first);
33 ✔
1253
    for (const QString &line : pair.second) {
76 ✔
1254
      auto *lineItem = new QTreeWidgetItem(entryItem);
43 ✔
1255
      // The marker is no content: shown as it is with hidden content too,
1256
      // and not counted as a match.
1257
      if (NativeGrep::isMoreMarker(line)) {
43 ✔
1258
        lineItem->setText(0, tr("… more matches in this entry"));
×
1259
      } else {
1260
        lineItem->setText(0, hideContent ? "***" + tr("Content hidden") + "***"
86 ✔
1261
                                         : grepLineForDisplay(line, s));
1262
        ++totalLines;
43 ✔
1263
      }
1264
      lineItem->setData(0, Qt::UserRole, pair.first);
43 ✔
1265
    }
1266
  }
1267
  ui->grepResultsList->expandAll();
10 ✔
1268
  showContentResults(true);
10 ✔
1269
  if (stopped) {
10 ✔
1270
    // The search stopped there; more entries may match.
1271
    ui->statusBar->showMessage(
×
1272
        tr("Showing the first %n match(es); search for something narrower "
×
1273
           "to see the rest.",
1274
           nullptr, totalLines),
1275
        10000);
1276
  } else {
1277
    ui->statusBar->showMessage(tr("Found %n match(es)", nullptr, totalLines) +
30 ✔
1278
                                   " " +
10 ✔
1279
                                   tr("in %n entr(ies).", nullptr, entries),
20 ✔
1280
                               3000);
1281
  }
1282
  // The results' own deadline: restarting the entry's timer here gave an
1283
  // entry still on the panel a second period, and an operation that stops
1284
  // the entry's timer left the results up with none.
1285
  if (s.useAutoclearPanel)
10 ✔
1286
    clearResultsTimer.start();
3 ✔
1287
}
10 ✔
1288

1289
void MainWindow::on_grepResultsList_itemClicked(QTreeWidgetItem *item,
2 ✔
1290
                                                int /*column*/) {
1291
  const AppSettings s = QtPassSettings::load();
2 ✔
1292
  const QString entry = item->data(0, Qt::UserRole).toString();
2 ✔
1293
  if (entry.isEmpty())
2 ✔
1294
    return;
1295
  const QString fullPath =
1296
      QDir::cleanPath(Util::joinPath(s.passStore, entry + ".gpg"));
2 ✔
1297
  // Persistent: setCurrentIndex() runs the selection handlers, which can
1298
  // change the model before the click is handled.
1299
  const QPersistentModelIndex proxyIndex(m_tree->indexFor(fullPath));
2 ✔
1300
  if (!proxyIndex.isValid())
2 ✔
1301
    return;
1302
  ui->treeView->setCurrentIndex(proxyIndex);
2 ✔
1303
  if (!proxyIndex.isValid())
2 ✔
1304
    return;
1305
  on_treeView_clicked(proxyIndex);
2 ✔
1306
  if (s.hideContent || s.useAutoclearPanel)
2 ✔
1307
    ui->grepResultsList->clear();
1 ✔
1308
  showContentResults(false);
2 ✔
1309
  ui->treeView->scrollTo(proxyIndex);
2 ✔
1310
  ui->treeView->setFocus();
2 ✔
1311
}
4 ✔
1312

1313
void MainWindow::showContentResults(bool shown) {
37 ✔
1314
  ui->grepResultsList->setVisible(shown);
37 ✔
1315
  ui->treeView->setVisible(!shown);
37 ✔
1316
  if (shown) {
37 ✔
1317
    // The tree's current entry is out of sight: Delete, Edit and OTP would
1318
    // act on it, not on a result. Opening a result shows the tree again.
1319
    ui->actionDelete->setEnabled(false);
10 ✔
1320
    ui->actionEdit->setEnabled(false);
10 ✔
1321
    updateOtpButtonVisibility(false);
10 ✔
1322
  } else if (ui->treeView->selectionModel()->hasSelection()) {
27 ✔
1323
    // Only for an entry still selected: with nothing selected there is no
1324
    // entry for Edit and Delete to act on.
1325
    setUiElementsEnabled(m_uiEnabled);
8 ✔
1326
  }
1327
}
37 ✔
1328

1329
void MainWindow::cancelContentSearch() {
28 ✔
1330
  QtPassSettings::getRealPass()->CancelGrep();
28 ✔
1331
  QtPassSettings::getImitatePass()->CancelGrep();
28 ✔
1332
}
28 ✔
1333

1334
void MainWindow::selectFirstFile() {
34 ✔
1335
  // The entry named exactly as typed wins: with folders sorted first, the
1336
  // depth-first walk found team/bank before bank.
1337
  QModelIndex index = exactMatch();
34 ✔
1338
  if (!index.isValid()) {
1339
    index = firstFile(m_tree->rootIndex());
17 ✔
1340
  }
1341
  ui->treeView->setCurrentIndex(index);
34 ✔
1342
}
34 ✔
1343

1344
namespace {
1345
/**
1346
 * @brief @p path with each part below @p store spelled as stored on disk.
1347
 *
1348
 * Where the file system ignores case, "Bank.gpg" exists while the file is
1349
 * bank.gpg, and the tree knows the entry only by that spelling.
1350
 * @param store The store folder.
1351
 * @param path An existing file in the store.
1352
 * @return @p path itself when every part is spelled as stored, otherwise
1353
 *         the path with the stored spelling.
1354
 */
1355
auto spelledAsStored(const QString &store, const QString &path) -> QString {
33 ✔
1356
  const QStringList parts = QDir(store).relativeFilePath(path).split(
66 ✔
1357
      QLatin1Char('/'), Qt::SkipEmptyParts);
33 ✔
1358
  QDir dir(store);
33 ✔
1359
  bool respelled = false;
1360
  for (int i = 0; i < parts.size(); ++i) {
36 ✔
1361
    const bool leaf = i == parts.size() - 1;
36 ✔
1362
    const QStringList names =
1363
        dir.entryList((leaf ? QDir::Files : QDir::Dirs) | QDir::Hidden |
36 ✔
1364
                      QDir::NoDotAndDotDot);
39 ✔
1365
    QString name = parts.at(i);
1366
    if (!names.contains(name)) {
36 ✔
1367
      const auto stored = std::find_if(
×
1368
          names.cbegin(), names.cend(), [&name](const QString &candidate) {
1369
            return candidate.compare(name, Qt::CaseInsensitive) == 0;
×
1370
          });
1371
      if (stored == names.cend()) {
×
1372
        return path;
1373
      }
1374
      name = *stored;
×
1375
      respelled = true;
1376
    }
1377
    if (leaf) {
36 ✔
1378
      return respelled ? QDir::cleanPath(Util::joinPath(dir.path(), name))
66 ✔
1379
                       : path;
×
1380
    }
1381
    if (!dir.cd(name)) {
3 ✔
1382
      return path;
1383
    }
1384
  }
1385
  return path;
1386
}
33 ✔
1387
} // namespace
1388

1389
auto MainWindow::exactMatchPath() -> QString {
52 ✔
1390
  const QString text = QDir::fromNativeSeparators(ui->lineEdit->text());
104 ✔
1391
  const QString store = QtPassSettings::getPassStore();
104 ✔
1392
  // A name may begin or end with a space: " bank" is that entry, not bank.
1393
  // Only when no entry is named so are spaces around the text dropped.
1394
  for (const QString &typed : {text, text.trimmed()}) {
196 ✔
1395
    if (typed.isEmpty()) {
73 ✔
1396
      continue;
×
1397
    }
1398
    const QString path =
1399
        QDir::cleanPath(Util::joinPath(store, typed + QStringLiteral(".gpg")));
146 ✔
1400
    if (PathValidator::isPathInStore(store, path) && QFileInfo(path).isFile()) {
73 ✔
1401
      return spelledAsStored(store, path);
33 ✔
1402
    }
1403
  }
156 ✔
1404
  return {};
19 ✔
1405
}
1406

1407
auto MainWindow::exactMatch() -> QModelIndex {
48 ✔
1408
  const QString path = exactMatchPath();
48 ✔
1409
  if (path.isEmpty()) {
48 ✔
1410
    return {};
18 ✔
1411
  }
1412
  // indexFor() maps through the filter: a row the filter hides is no match.
1413
  const QModelIndex index = m_tree->indexFor(path);
30 ✔
1414
  if (!index.isValid() || !m_tree->fileInfo(index).isFile()) {
53 ✔
1415
    return {};
7 ✔
1416
  }
1417
  return index;
23 ✔
1418
}
1419

1420
void MainWindow::applySearchText(const QString &text) {
9 ✔
1421
  // A name search: content search, left on, kept its results over the tree
1422
  // and ignored the text.
1423
  if (ui->grepButton->isChecked()) {
9 ✔
1424
    ui->grepButton->setChecked(false);
1 ✔
1425
  }
1426
  delete m_pendingOpen;
9 ✔
1427
  ui->lineEdit->setText(text);
9 ✔
1428
  // Filter now, not after the search delay: the timer would leave the tree
1429
  // as the previous text filtered it.
1430
  searchTimer.stop();
9 ✔
1431
  onTimeoutSearch();
9 ✔
1432
  if (const QModelIndex exact = exactMatch(); exact.isValid()) {
9 ✔
1433
    openExactMatch(exact);
5 ✔
1434
    return;
5 ✔
1435
  }
1436
  // The tree loads folders in the background: at start, or right after the
1437
  // window is shown again, an entry that exists may not be in it yet. Try
1438
  // again as folders finish loading, for a few seconds, unless the search
1439
  // text changes meanwhile: any change ends the wait, even one typed back to
1440
  // this text, which is a new search that has not asked to open anything.
1441
  if (exactMatchPath().isEmpty()) {
8 ✔
1442
    return;
1443
  }
1444
  auto *pending = new QObject(this);
3 ✔
1445
  m_pendingOpen = pending;
1446
  QTimer::singleShot(5000, pending, &QObject::deleteLater);
3 ✔
1447
  // Disconnected at once: with deleteLater() alone, a folder that finished
1448
  // loading before the deletion still ran the open, or ran it twice.
1449
  const auto stop = [this, pending] {
2 ✔
1450
    disconnect(m_tree, nullptr, pending, nullptr);
2 ✔
1451
    disconnect(ui->lineEdit, nullptr, pending, nullptr);
2 ✔
1452
    pending->deleteLater();
2 ✔
1453
  };
5 ✔
1454
  connect(ui->lineEdit, &QLineEdit::textChanged, pending, stop);
3 ✔
1455
  connect(m_tree, &StoreTree::directoryLoaded, pending,
3 ✔
1456
          [this, stop](const QString &) {
6 ✔
1457
            searchTimer.stop();
5 ✔
1458
            onTimeoutSearch();
5 ✔
1459
            if (const QModelIndex exact = exactMatch(); exact.isValid()) {
5 ✔
1460
              stop();
1 ✔
1461
              openExactMatch(exact);
1 ✔
1462
            }
1463
          });
5 ✔
1464
}
1465

1466
void MainWindow::openExactMatch(const QModelIndex &index) {
6 ✔
1467
  // Made current here, not left to the filter pass before: the tree may have
1468
  // moved its current row since, and with none on_treeView_clicked() only
1469
  // names the entry without decrypting it.
1470
  ui->treeView->setCurrentIndex(index);
6 ✔
1471
  on_treeView_clicked(index);
6 ✔
1472
}
6 ✔
1473

1474
auto MainWindow::firstFile(QModelIndex parentIndex) -> QModelIndex {
24 ✔
1475
  StoreModel &proxy = m_tree->proxy();
24 ✔
1476
  int numRows = proxy.rowCount(parentIndex);
24 ✔
1477
  for (int row = 0; row < numRows; ++row) {
32 ✔
1478
    QModelIndex index = proxy.index(row, 0, parentIndex);
22 ✔
1479
    if (m_tree->fileInfo(index).isFile()) {
22 ✔
1480
      return index;
14 ✔
1481
    }
1482
    if (proxy.hasChildren(index)) {
13 ✔
1483
      QModelIndex childFile = firstFile(index);
7 ✔
1484
      if (childFile.isValid())
1485
        return childFile;
5 ✔
1486
    }
1487
  }
1488
  return QModelIndex();
10 ✔
1489
}
1490

1491
// Guards the input dialogs (create, move, rename) against names like
1492
// "../../etc/passwd" or absolute paths escaping the store root.
1493
auto MainWindow::confirmPathInStore(const QString &candidate) -> bool {
11 ✔
1494
  if (PathValidator::isPathInStore(QtPassSettings::getPassStore(), candidate)) {
22 ✔
1495
    return true;
1496
  }
1497
  QMessageBox::warning(this, tr("Invalid name"),
9 ✔
1498
                       tr("That name would resolve outside the password "
3 ✔
1499
                          "store. Please choose a different name."));
1500
  return false;
3 ✔
1501
}
1502

1503
void MainWindow::setPassword(const QString &file, bool isNew) {
8 ✔
1504
  const AppSettings s = QtPassSettings::load();
8 ✔
1505
  PasswordDialog d(QtPassSettings::getPass(), s, file, isNew, this);
8 ✔
1506
  // A copy out of the editor is autocleared like one from the display.
1507
  connect(&d, &PasswordDialog::copied, &m_qtPass->clipboard(),
8 ✔
1508
          &ClipboardManager::trackCopied);
8 ✔
1509

1510
  if (isNew) {
8 ✔
1511
    const QString storePath = s.passStore;
1512
    QString folder = m_tree->currentDir(false);
2 ✔
1513
    if (folder.isEmpty()) {
2 ✔
1514
      folder = storePath;
×
1515
    }
1516
    // A tree folder that is, or lies behind, a symbolic link is not part of the
1517
    // store (Users and re-encryption refuse it the same way). Adding here would
1518
    // silently fall back to the store root and encrypt the new entry to the
1519
    // root's recipients - which a co-writer who planted the link, and is on the
1520
    // root list but not the real folder's, can then read. Refuse instead.
1521
    if (refuseLinkedFolder(folder)) {
2 ✔
1522
      return;
1523
    }
1524
    // Folders to pick from, the tree's current one preselected. Real folders
1525
    // only: a linked or junctioned one would write the entry outside the store.
1526
    QStringList folders{QString()};
2 ✔
1527
    const QStringList found = Util::directoriesUnder(storePath);
1 ✔
1528
    for (const QString &path : found) {
19 ✔
1529
      const QString rel = QDir(storePath).relativeFilePath(path);
18 ✔
1530
      if (!rel.startsWith(u'.') && !rel.contains(QStringLiteral("/."))) {
54 ✔
1531
        folders << rel;
1532
      }
1533
    }
1534
    std::sort(folders.begin() + 1, folders.end());
1 ✔
1535
    d.setNewEntryLocation(storePath, folders,
1 ✔
1536
                          QDir(storePath).relativeFilePath(folder));
2 ✔
1537
    QHash<QString, QStringList> templates =
1538
        TemplateIO::readTemplates(storePath);
1 ✔
1539
    if (!templates.isEmpty()) {
1540
      QString defaultTemplate =
1541
          TemplateIO::getFolderTemplate(folder, storePath);
1 ✔
1542
      d.setAvailableTemplates(templates, defaultTemplate);
1 ✔
1543
    }
1544
  }
1 ✔
1545

1546
  if (!d.exec()) {
7 ✔
1547
    ui->treeView->setFocus();
6 ✔
1548
  }
1549
}
8 ✔
1550

1551
void MainWindow::addPassword() { setPassword(QString()); }
4 ✔
1552

1553
auto MainWindow::confirmDeletion(const QString &file, bool isDir) -> bool {
9 ✔
1554
  const QString path = QDir::separator() + file;
9 ✔
1555
  // As the platform writes paths: backslashes only on Windows, never a mix.
1556
  // On one line: a name from the store may hold a line feed (Unix allows
1557
  // one), which drew lines of its own into the question.
1558
  const QString shown =
1559
      Util::displayable(QDir::toNativeSeparators(path), false);
9 ✔
1560
  if (!isDir) {
9 ✔
1561
    return PlainMessageBox::askYes(
2 ✔
1562
        this, tr("Delete password?"),
2 ✔
1563
        tr("Are you sure you want to delete %1?").arg(shown));
4 ✔
1564
  }
1565
  // Whole sentences, not a question stitched from pieces: a verb-final
1566
  // language cannot put the rest of the question after the path.
1567
  // Plain text, as every box quoting the store: the path is a name other
1568
  // writers control, and as rich text "a  b" would also show as "a b".
1569
  QString question =
1570
      tr("Are you sure you want to delete %1 and the whole content?")
×
1571
          .arg(shown);
7 ✔
1572
  // A link, junction or special file inside is as unexpected as a stray
1573
  // plain file: the walker leaves them out of content and reports them.
1574
  QStringList skipped;
7 ✔
1575
  QStringList unlisted;
7 ✔
1576
  const QString root = m_tree->fileSystem().rootPath();
7 ✔
1577
  const QStringList content = Util::regularFilesUnder(
21 ✔
1578
      root + path, {QStringLiteral("*")}, &skipped, false, &unlisted);
21 ✔
1579
  const bool unexpected =
1580
      !skipped.isEmpty() ||
7 ✔
1581
      std::any_of(content.cbegin(), content.cend(), [](const QString &entry) {
7 ✔
1582
        return QFileInfo(entry).suffix() != QLatin1String("gpg");
10 ✔
1583
      });
1584
  if (unexpected) {
1585
    question += QStringLiteral("\n\n") +
1 ✔
1586
                tr("Attention: there are unexpected files in the given "
1 ✔
1587
                   "folder, check them before continuing.");
1 ✔
1588
  }
1589
  // A folder the walk cannot read is not empty but unknown: whatever it
1590
  // holds goes too, or stays behind when the removal cannot list it.
1591
  if (unlisted.size() == 1) {
7 ✔
1592
    //: %1 is a folder in the password store, such as /Work/bank.
1593
    const QString one =
1594
        tr("%1 could not be read, so what it holds is unknown.")
1 ✔
1595
            .arg(Util::displayable(
1 ✔
1596
                QDir::toNativeSeparators(
1 ✔
1597
                    QDir::separator() +
1 ✔
1598
                    QDir(root).relativeFilePath(unlisted.first())),
2 ✔
1599
                false));
3 ✔
1600
    question += QStringLiteral("\n\n") + one;
2 ✔
1601
  } else if (unlisted.size() > 1) {
6 ✔
1602
    //: Only shown for two or more folders; one folder is named instead.
1603
    const QString many =
1604
        tr("%n folder(s) in it could not be read, so what they hold "
1605
           "is unknown.",
1606
           nullptr, static_cast<int>(unlisted.size()));
1 ✔
1607
    question += QStringLiteral("\n\n") + many;
2 ✔
1608
  }
1609
  return PlainMessageBox::askYes(this, tr("Delete folder?"), question);
14 ✔
1610
}
1611

1612
auto MainWindow::confirmLinkRemoval(const QString &file) -> bool {
1 ✔
1613
  // Only the link goes (ImitatePass::Remove unlinks it); nothing behind it
1614
  // is looked at or mentioned.
1615
  return PlainMessageBox::askYes(
1 ✔
1616
      this, tr("Delete link?"),
1 ✔
1617
      tr("%1 is a symbolic link or junction. Remove the link? What it "
1 ✔
1618
         "points to is left alone.")
1619
          .arg(Util::displayable(QDir::separator() + file, false)));
2 ✔
1620
}
1621

1622
void MainWindow::onDelete() {
14 ✔
1623
  const QModelIndex currentIndex = ui->treeView->currentIndex();
14 ✔
1624
  // While content search results hide the tree, its current entry is not
1625
  // what the user looks at (the Delete key comes here directly).
1626
  if (!currentIndex.isValid() || ui->treeView->isHidden()) {
12 ✔
1627
    // Otherwise the whole password directory would be deleted (#556).
1628
    return;
11 ✔
1629
  }
1630

1631
  const bool isDir = !m_tree->fileInfo(currentIndex).isFile();
10 ✔
1632
  const QString file =
1633
      isDir ? m_tree->currentDir(true) : getFile(currentIndex, true);
10 ✔
1634
  const QString folder =
1635
      m_tree->fileSystem().rootPath() + QDir::separator() + file;
10 ✔
1636
  const bool linkedFolder = isDir && Util::isLinkedFolder(folder);
10 ✔
1637

1638
  if (!linkedFolder && refuseLinkedFolder(folder)) {
9 ✔
1639
    // Behind a link: deleting would reach outside the store.
1640
    return;
1641
  }
1642
  const bool confirmed =
1643
      linkedFolder ? confirmLinkRemoval(file) : confirmDeletion(file, isDir);
10 ✔
1644
  if (!confirmed) {
10 ✔
1645
    return;
1646
  }
1647
  QtPassSettings::getPass()->Remove(file, isDir);
6 ✔
1648
}
1649

1650
void MainWindow::cancelOtpRequest() {
104 ✔
1651
  m_otpRequestFile.clear();
104 ✔
1652
  m_copyRequestFile.clear();
104 ✔
1653
}
104 ✔
1654

1655
void MainWindow::onOperationError() {
39 ✔
1656
  cancelOtpRequest();
39 ✔
1657
  // executeWrapperStarted() emptied the panel and the browser when the
1658
  // operation started (a refusal says so too); what is left to forget is
1659
  // which entry the panel was about to show.
1660
  m_shownFile.clear();
39 ✔
1661
  // A save's refresh waiting for its push is dropped: it would clear the
1662
  // push's error (or whatever failed before it) from the browser.
1663
  m_refreshAfterPush.clear();
39 ✔
1664
  m_refreshAfterPushOwner = nullptr;
1665
}
39 ✔
1666

1667
// Derives the code in-process from one decrypt, so it works with either
1668
// backend on every platform; otpFromFileToClipboard() finishes the job.
1669
void MainWindow::onOtp() {
12 ✔
1670
  if (ui->treeView->isHidden()) {
12 ✔
1671
    return;
4 ✔
1672
  }
1673
  QString file = getFile(ui->treeView->currentIndex(), true);
11 ✔
1674
  if (file.isEmpty()) {
11 ✔
1675
    flashText(tr("No password selected for OTP generation"), true);
1 ✔
1676
    return;
1 ✔
1677
  }
1678
  if (!QtPassSettings::isUseOtp()) {
10 ✔
1679
    // Normally unreachable (the action is hidden), but never fail silently.
1680
    flashText(tr("No OTP code found in this password entry"), true);
1 ✔
1681
    return;
1 ✔
1682
  }
1683

1684
  // Fast path: the panel shows a live code, so no decrypt, and one clipboard
1685
  // write (two setMimeData calls in one turn can empty the Windows
1686
  // clipboard). Only for *this* entry: arrow keys and right-click move
1687
  // currentIndex without QTreeView::clicked, so the code may be another's.
1688
  const QString shown =
1689
      (m_shownFile == file) ? m_displayPanel->currentOtpCode() : QString();
9 ✔
1690
  if (!shown.isEmpty()) {
9 ✔
1691
    m_qtPass->clipboard().copyText(shown);
1 ✔
1692
    showStatusMessage(tr("OTP code copied to clipboard"));
2 ✔
1693
    return;
1694
  }
1695

1696
  // Fallback: decrypt once. The request file keeps passShowHandler from
1697
  // copying the password and tells otpFromFileToClipboard its answer.
1698
  m_otpRequestFile = file;
8 ✔
1699
  setUiElementsEnabled(false);
8 ✔
1700
  // Keep the marker in step so a second request takes the fast path; safe as
1701
  // executeWrapperStarted() clears the panel, so a failed decrypt shows none.
1702
  m_shownFile = file;
8 ✔
1703
  QtPassSettings::getPass()->Show(file);
16 ✔
1704
}
1705

1706
void MainWindow::onEdit() {
1 ✔
1707
  if (ui->treeView->isHidden()) {
1 ✔
1708
    return;
1 ✔
1709
  }
1710
  QString file = getFile(ui->treeView->currentIndex(), true);
×
1711
  editPassword(file);
×
1712
}
1713

1714
void MainWindow::onUsers() {
2 ✔
1715
  const QString dir = m_tree->currentDir(false);
2 ✔
1716
  if (refuseLinkedFolder(dir)) {
2 ✔
1717
    return;
1718
  }
1719

1720
  UsersDialog d(QtPassSettings::getPass(), QtPassSettings::load(), dir, this);
1 ✔
1721
  if (!d.exec()) {
1 ✔
1722
    ui->treeView->setFocus();
1 ✔
1723
  }
1724
}
1 ✔
1725

1726
void MainWindow::messageAvailable(const QString &message) {
10 ✔
1727
  show();
10 ✔
1728
  raise();
10 ✔
1729
  if (message.isEmpty()) {
10 ✔
1730
    focusInput();
1 ✔
1731
  } else {
1732
    ui->treeView->expandAll();
9 ✔
1733
    applySearchText(message);
9 ✔
1734
  }
1735
}
10 ✔
1736

1737
void MainWindow::updateProfileBox() {
215 ✔
1738
  const Profiles profiles = QtPassSettings::getProfiles();
215 ✔
1739
  bool activeGone = false;
1740

1741
  if (profiles.isEmpty()) {
8 ✔
1742
    ui->profileWidget->hide();
207 ✔
1743
  } else {
1744
    ui->profileWidget->show();
8 ✔
1745
    // A refill is no choice of the user's: clearing and adding items moves
1746
    // the current text, which would otherwise switch profiles.
1747
    const QSignalBlocker quiet(ui->profileBox);
8 ✔
1748
    ui->profileBox->clear();
8 ✔
1749
    for (auto i = profiles.cbegin(); i != profiles.cend(); ++i) {
22 ✔
1750
      if (!i.key().isEmpty()) {
14 ✔
1751
        ui->profileBox->addItem(i.key());
14 ✔
1752
      }
1753
    }
1754
    ui->profileBox->model()->sort(0);
8 ✔
1755
    int index = ui->profileBox->findText(QtPassSettings::getProfile());
16 ✔
1756
    if (index != -1) { //  -1 for not found
8 ✔
1757
      ui->profileBox->setCurrentIndex(index);
7 ✔
1758
    } else if (ui->profileBox->count() > 0) {
1 ✔
1759
      // The active profile is gone (removed in Settings): the box shows the
1760
      // first one, and the settings and backend must follow it, or the
1761
      // removed profile's store stays in use behind it.
1762
      ui->profileBox->setCurrentIndex(0);
1 ✔
1763
      activeGone = true;
1764
    }
1765
  }
8 ✔
1766
  if (activeGone) {
8 ✔
1767
    on_profileBox_currentTextChanged(ui->profileBox->currentText());
2 ✔
1768
  }
1769
  updateProfileBoxEnabled();
215 ✔
1770
}
215 ✔
1771

1772
void MainWindow::updateProfileBoxEnabled() {
741 ✔
1773
  // No profile switch while anything of the store runs or waits: the
1774
  // backend's store and environment would change under it, and what is
1775
  // still queued (a push after a save, say) would finish for the other
1776
  // profile (#2071). Asked of the backend, not only of the interface: the
1777
  // watchdog releases the interface while a slow gpg or git still runs.
1778
  // Every backend: one kept from before a switch of backend may still
1779
  // run what was queued on it.
1780
  ui->profileBox->setEnabled(m_uiEnabled && ui->profileBox->count() > 1 &&
1,484 ✔
1781
                             QtPassSettings::backendsIdle());
16 ✔
1782
}
741 ✔
1783

1784
void MainWindow::on_profileBox_currentTextChanged(const QString &name) {
8 ✔
1785
  if (m_freshStart || name == QtPassSettings::getProfile()) {
24 ✔
1786
    return;
1 ✔
1787
  }
1788
  // The box is disabled while anything runs; should a change come through
1789
  // anyway, the active profile stays and the box says so again.
1790
  if (!m_uiEnabled || !QtPassSettings::backendsIdle()) {
7 ✔
1791
    const QSignalBlocker quiet(ui->profileBox);
×
1792
    ui->profileBox->setCurrentText(QtPassSettings::getProfile());
×
1793
    return;
1794
  }
×
1795
  // A content search runs outside the queue: leaving grep mode cancels it,
1796
  // so its results for the old store are dropped, not shown for the new.
1797
  if (m_grep.inGrepMode()) {
7 ✔
1798
    ui->grepButton->setChecked(false);
1 ✔
1799
  }
1800

1801
  ui->lineEdit->clear();
7 ✔
1802

1803
  const Profile prof = QtPassSettings::getProfiles().value(name);
14 ✔
1804
  AppSettings s = QtPassSettings::load();
7 ✔
1805
  s.activeProfile = name;
7 ✔
1806
  s.passStore = prof.path;
7 ✔
1807
  s.passSigningKey = prof.signingKey;
7 ✔
1808
  // The profile's own Git flags are not written over the Git page's: every
1809
  // profile without flags of its own falls back to those.
1810
  // QtPassSettings::loadEffective() applies them while the profile is active.
1811
  QtPassSettings::save(s);
7 ✔
1812
  ui->statusBar->showMessage(tr("Profile changed to %1").arg(name), 2000);
14 ✔
1813

1814
  QtPassSettings::getPass()->updateEnv();
7 ✔
1815

1816
  m_tree->setStore(QtPassSettings::getPassStore());
14 ✔
1817
  deselect();
7 ✔
1818
  ui->treeView->setCurrentIndex(QModelIndex());
7 ✔
1819
}
7 ✔
1820

1821
void MainWindow::initTrayIcon() {
3 ✔
1822
  m_tray = new TrayIcon(this);
3 ✔
1823
  if (!m_tray->getIsAllocated()) {
3 ✔
1824
    destroyTrayIcon();
3 ✔
1825
    return;
3 ✔
1826
  }
1827
#ifndef Q_OS_MACOS
1828
  m_tray->addToggle(ui->actionShowMenuBar);
×
1829
#endif
1830
}
1831

1832
void MainWindow::destroyTrayIcon() {
3 ✔
1833
  delete m_tray;
3 ✔
1834
  m_tray = nullptr;
3 ✔
1835
}
3 ✔
1836

1837
void MainWindow::closeEvent(QCloseEvent *event) {
4 ✔
1838
  // Save in both branches: a tray user only ever hides the window, and
1839
  // used to quit through the tray menu with nothing ever written.
1840
  saveWindowState();
4 ✔
1841
  // Only with a tray icon to come back from: without one (none asked for, or
1842
  // no system tray in this session) a hidden QtPass ran on invisibly, with the
1843
  // last entry in its window and the password on the clipboard.
1844
  if (QtPassSettings::isHideOnClose() && m_tray != nullptr) {
8 ✔
1845
    this->hide();
×
1846
    event->ignore();
1847
  } else {
1848
    m_qtPass->clipboard().clear();
4 ✔
1849
    event->accept();
1850
    // A visible QSystemTrayIcon keeps the application alive, so
1851
    // quitOnLastWindowClosed never fires; quit explicitly.
1852
    QApplication::quit();
4 ✔
1853
  }
1854
}
4 ✔
1855

1856
auto MainWindow::eventFilter(QObject *obj, QEvent *event) -> bool {
8,762 ✔
1857
  if ((obj == ui->toolBar || obj == menuBar()) &&
8,762 ✔
1858
      event->type() == QEvent::PaletteChange) {
1859
    // Breeze gives these bars a "header" palette and, after a runtime
1860
    // light/dark switch, stamps the previous theme's colours back from a
1861
    // cached kdeglobals, hiding the toolbar icons. Deferred so we never
1862
    // re-enter the style while it is still applying its palette.
1863
    QTimer::singleShot(0, this, &MainWindow::dropStaleToolsAreaPalettes);
36 ✔
1864
  }
1865
  if (obj == ui->lineEdit && event->type() == QEvent::KeyPress) {
8,762 ✔
1866
    auto *key = dynamic_cast<QKeyEvent *>(event);
5 ✔
1867
    if (key != nullptr && key->key() == Qt::Key_Down) {
5 ✔
1868
      // Into whichever list is in sight: the tree, or content search results.
1869
      // Focus makes the list's first item current.
1870
      if (ui->treeView->isHidden()) {
2 ✔
1871
        ui->grepResultsList->setFocus();
1 ✔
1872
      } else {
1873
        ui->treeView->setFocus();
1 ✔
1874
      }
1875
    }
1876
    // Return ends at the search box: QLineEdit emits returnPressed() and
1877
    // leaves the key unaccepted, so keyPressEvent() would open the tree's
1878
    // current entry as well. In content search that is an entry nobody
1879
    // asked for; by name, the first hit a second time.
1880
    if (key != nullptr &&
5 ✔
1881
        (key->key() == Qt::Key_Return || key->key() == Qt::Key_Enter)) {
2 ✔
1882
      ui->lineEdit->event(event);
3 ✔
1883
      event->accept();
1884
      return true;
3 ✔
1885
    }
1886
  }
1887
  return QObject::eventFilter(obj, event);
8,759 ✔
1888
}
1889

1890
// Only once the application palette changed (see m_themeSwitched): a bar
1891
// whose active Window lightness is far from the application's shows the
1892
// other theme.
1893
void MainWindow::dropStaleToolsAreaPalettes() {
31 ✔
1894
  if (!m_themeSwitched) {
31 ✔
1895
    return;
1896
  }
1897
  constexpr int kStaleToolsAreaLightness = 64;
1898
  // The active group on both sides: a bar's palette() reads the inactive
1899
  // group while another window has focus (the settings app, during a theme
1900
  // switch), and Breeze gives the header set different inactive colours.
1901
  const int appLightness = QApplication::palette()
54 ✔
1902
                               .color(QPalette::Active, QPalette::Window)
1903
                               .lightness();
27 ✔
1904
  for (QWidget *bar : {static_cast<QWidget *>(ui->toolBar),
108 ✔
1905
                       static_cast<QWidget *>(menuBar())}) {
81 ✔
1906
    if (!bar->testAttribute(Qt::WA_SetPalette)) {
54 ✔
1907
      continue;
48 ✔
1908
    }
1909
    const int barLightness =
1910
        bar->palette().color(QPalette::Active, QPalette::Window).lightness();
12 ✔
1911
    if (qAbs(barLightness - appLightness) <= kStaleToolsAreaLightness) {
6 ✔
1912
      continue;
2 ✔
1913
    }
1914
    bar->setPalette(QPalette());
4 ✔
1915
    // Both bars are transparent and the style paints the tools area from the
1916
    // stale palette, so fill our own. Window, not their Button role, which is
1917
    // not the window colour in either theme.
1918
    bar->setBackgroundRole(QPalette::Window);
4 ✔
1919
    bar->setAutoFillBackground(true);
4 ✔
1920
  }
1921
}
1922

1923
void MainWindow::keyPressEvent(QKeyEvent *event) {
25 ✔
1924
  switch (event->key()) {
25 ✔
1925
  case Qt::Key_Delete:
2 ✔
1926
    onDelete();
2 ✔
1927
    break;
2 ✔
1928
  case Qt::Key_Return:
2 ✔
1929
  case Qt::Key_Enter:
1930
    // While content search results hide the tree, its current entry is not
1931
    // what the user looks at: Return on a result opens that result.
1932
    if (ui->treeView->isHidden()) {
2 ✔
1933
      QTreeWidgetItem *result = ui->grepResultsList->currentItem();
1 ✔
1934
      if (result != nullptr && ui->grepResultsList->hasFocus()) {
1 ✔
1935
        on_grepResultsList_itemClicked(result, 0);
1 ✔
1936
      }
1937
      break;
1938
    }
1939
    if (m_tree->proxy().rowCount() > 0) {
1 ✔
1940
      on_treeView_clicked(ui->treeView->currentIndex());
1 ✔
1941
    }
1942
    break;
1943
  case Qt::Key_Escape:
3 ✔
1944
    ui->lineEdit->clear();
3 ✔
1945
    break;
3 ✔
1946
  default:
1947
    break;
1948
  }
1949
}
25 ✔
1950

1951
void MainWindow::addShareMenu(QMenu &contextMenu, const AppSettings &s) {
14 ✔
1952
  const QString dirPath = QDir::cleanPath(m_tree->currentDir(false));
14 ✔
1953
  auto *shareMenu = new QMenu(tr("Share"), &contextMenu);
14 ✔
1954
  contextMenu.addMenu(shareMenu);
14 ✔
1955

1956
  const QString gpgIdPath = Pass::getGpgIdPath(dirPath, s.passStore);
14 ✔
1957
  const bool gpgIdExists = !gpgIdPath.isEmpty() && QFile(gpgIdPath).exists();
14 ✔
1958
  const QString exePath = s.usePass ? s.passExecutable : s.gpgExecutable;
14 ✔
1959
  const bool gpgAvailable =
1960
      !exePath.isEmpty() &&
28 ✔
1961
      (Executor::parseWslCommand(exePath) || QFile(exePath).exists());
28 ✔
1962

1963
  QAction *reencrypt = shareMenu->addAction(tr("Re-encrypt all passwords"));
14 ✔
1964
  reencrypt->setEnabled(gpgIdExists && gpgAvailable);
14 ✔
1965
  connect(reencrypt, &QAction::triggered, this,
14 ✔
1966
          [this, dirPath]() { reencryptPath(dirPath); });
46 ✔
1967

1968
  QAction *exportKey = shareMenu->addAction(tr("Export my public key..."));
14 ✔
1969
  exportKey->setEnabled(gpgAvailable);
14 ✔
1970
  connect(exportKey, &QAction::triggered, this, &MainWindow::exportPublicKey);
14 ✔
1971

1972
  QAction *addRecipientAction = shareMenu->addAction(tr("Add recipient..."));
14 ✔
1973
  addRecipientAction->setEnabled(gpgIdExists && gpgAvailable);
14 ✔
1974
  connect(addRecipientAction, &QAction::triggered, this,
14 ✔
1975
          [this, dirPath]() { addRecipient(dirPath); });
44 ✔
1976

1977
  QAction *shareHelp = shareMenu->addAction(tr("What is this?"));
14 ✔
1978
  connect(shareHelp, &QAction::triggered, this, &MainWindow::showShareHelp);
14 ✔
1979
}
14 ✔
1980

1981
auto MainWindow::backOnMenuEntry(const QString &openedOn) -> bool {
4 ✔
1982
  const QModelIndex current = ui->treeView->currentIndex();
4 ✔
1983
  if (openedOn.isEmpty()) {
4 ✔
1984
    // Opened beside the entries: for the store itself.
1985
    if (current.isValid()) {
NEW
1986
      ui->treeView->setCurrentIndex(QModelIndex());
×
1987
    }
1988
    return true;
1 ✔
1989
  }
1990
  // Gone, also while the tree still lists it: the reload comes later. A
1991
  // link that leads nowhere is still an entry.
1992
  const QFileInfo entry(openedOn);
3 ✔
1993
  const bool there = entry.exists() || entry.isSymLink();
3 ✔
1994
  if (there && current.isValid() &&
3 ✔
1995
      m_tree->fileInfo(current).absoluteFilePath() == openedOn) {
4 ✔
1996
    return true;
1997
  }
1998
  // Asked only about a path that exists: the file system model on macOS
1999
  // lists a path again once it is asked for one that is gone.
2000
  const QModelIndex shown = there ? m_tree->indexFor(openedOn) : QModelIndex();
3 ✔
2001
  if (!shown.isValid()) {
2002
    showStatusMessage(
2 ✔
2003
        tr("%1 is no longer in the list.").arg(Util::shownName(openedOn)));
4 ✔
2004
    return false;
2 ✔
2005
  }
2006
  ui->treeView->setCurrentIndex(shown);
1 ✔
2007
  return true;
2008
}
3 ✔
2009

2010
void MainWindow::showContextMenu(const QPoint &pos) {
16 ✔
2011
  const AppSettings s = QtPassSettings::load();
16 ✔
2012
  const QModelIndex index = ui->treeView->indexAt(pos);
16 ✔
2013
  const bool selected = index.isValid();
2014
  if (!selected) {
2015
    ui->treeView->clearSelection();
1 ✔
2016
    ui->actionDelete->setEnabled(false);
1 ✔
2017
    ui->actionEdit->setEnabled(false);
1 ✔
2018
  }
2019
  ui->treeView->setCurrentIndex(index);
16 ✔
2020
  const QPoint globalPos = ui->treeView->viewport()->mapToGlobal(pos);
16 ✔
2021
  const QFileInfo fileOrFolder = m_tree->fileInfo(ui->treeView->currentIndex());
16 ✔
2022
  const bool isDir = fileOrFolder.isDir();
16 ✔
2023

2024
  QMenu contextMenu;
16 ✔
2025
  // The actions read the current entry when picked, and that may be another
2026
  // one by then: a row removed in place by the file system model (its own
2027
  // watcher, on macOS) hands the current index to a neighbour, and the
2028
  // reload after it finds that one again. Delete would then remove the
2029
  // neighbour. So each action first goes back to the entry the menu was
2030
  // opened on, and does nothing when that is gone.
2031
  const QString openedOn =
2032
      selected ? fileOrFolder.absoluteFilePath() : QString();
16 ✔
2033
  const auto add = [this, &contextMenu, openedOn](const QString &text,
16 ✔
2034
                                                  void (MainWindow::*slot)()) {
2035
    connect(contextMenu.addAction(text), &QAction::triggered, this,
91 ✔
2036
            [this, openedOn, slot]() {
182 ✔
2037
              if (backOnMenuEntry(openedOn)) {
4 ✔
2038
                (this->*slot)();
2 ✔
2039
              }
2040
            });
4 ✔
2041
  };
107 ✔
2042
  if (!selected || isDir) {
16 ✔
2043
    add(tr("Open folder with file manager"), &MainWindow::openFolder);
15 ✔
2044
    add(tr("Add folder"), &MainWindow::addFolder);
15 ✔
2045
    add(tr("Add password"), &MainWindow::addPassword);
15 ✔
2046
    add(tr("Users"), &MainWindow::onUsers);
30 ✔
2047
  } else if (fileOrFolder.isFile()) {
1 ✔
2048
    add(tr("Edit"), &MainWindow::onEdit);
2 ✔
2049
  }
2050
  if (selected) {
16 ✔
2051
    contextMenu.addSeparator();
15 ✔
2052
    if (isDir) {
15 ✔
2053
      add(tr("Rename folder"), &MainWindow::renameFolder);
28 ✔
2054
    } else if (fileOrFolder.isFile()) {
1 ✔
2055
      add(tr("Rename password"), &MainWindow::renamePassword);
2 ✔
2056
    }
2057
    add(tr("Delete"), &MainWindow::onDelete);
15 ✔
2058
    if (isDir) {
15 ✔
2059
      addShareMenu(contextMenu, s);
14 ✔
2060
    }
2061
  }
2062
  // With the current entry gone and nothing else current, the menu has
2063
  // nothing left to act on.
2064
  connect(m_tree, &StoreTree::currentEntryLost, &contextMenu, &QMenu::close);
16 ✔
2065
  contextMenu.exec(globalPos);
16 ✔
2066
}
16 ✔
2067

2068
auto MainWindow::browserContextMenu(const QPoint &pos) -> QMenu * {
3 ✔
2069
  // createStandardContextMenu() takes document coordinates, anchorAt() and
2070
  // the menu's place viewport ones: scrolled, the menu checked the text
2071
  // above the link and left "Copy Link Location" disabled.
2072
  // Right to left, the horizontal offset counts from the other end.
2073
  const QScrollBar *across = ui->textBrowser->horizontalScrollBar();
3 ✔
2074
  const int dx = ui->textBrowser->isRightToLeft()
3 ✔
2075
                     ? across->maximum() - across->value()
3 ✔
2076
                     : across->value();
3 ✔
2077
  const QPoint documentPos =
2078
      pos + QPoint(dx, ui->textBrowser->verticalScrollBar()->value());
3 ✔
2079
  QMenu *contextMenu = ui->textBrowser->createStandardContextMenu(documentPos);
3 ✔
2080
  // Reparent from textBrowser: a browser stylesheet cascades to the child
2081
  // QMenu and breaks its opaque native background.
2082
  contextMenu->setParent(this, contextMenu->windowFlags());
3 ✔
2083
  if (auto *copyLink =
3 ✔
2084
          contextMenu->findChild<QAction *>(QStringLiteral("link-copy"))) {
3 ✔
2085
    const QString link = ui->textBrowser->anchorAt(pos);
3 ✔
2086
    disconnect(copyLink, &QAction::triggered, nullptr, nullptr);
3 ✔
2087
    connect(copyLink, &QAction::triggered, this, [this, link] {
10 ✔
2088
      if (!link.isEmpty()) {
1 ✔
2089
        m_qtPass->clipboard().copyText(link);
1 ✔
2090
      }
2091
    });
1 ✔
2092
  }
2093
  return contextMenu;
3 ✔
2094
}
2095

2096
void MainWindow::showBrowserContextMenu(const QPoint &pos) {
1 ✔
2097
  QMenu *contextMenu = browserContextMenu(pos);
1 ✔
2098
  contextMenu->exec(ui->textBrowser->viewport()->mapToGlobal(pos));
1 ✔
2099
  delete contextMenu;
1 ✔
2100
}
1 ✔
2101

2102
void MainWindow::openFolder() {
1 ✔
2103
  QString dir = m_tree->currentDir(false);
1 ✔
2104

2105
  QString path = QDir::toNativeSeparators(dir);
1 ✔
2106
  QDesktopServices::openUrl(QUrl::fromLocalFile(path));
1 ✔
2107
}
1 ✔
2108

2109
void MainWindow::addFolder() {
7 ✔
2110
  const AppSettings s = QtPassSettings::load();
7 ✔
2111
  bool ok;
2112
  QString dir = m_tree->currentDir(false);
7 ✔
2113
  QString newdir = QInputDialog::getText(
2114
      this, tr("New folder"),
7 ✔
2115
      tr("New folder: \n(Will be placed in %1 )")
7 ✔
2116
          .arg(Util::shownName(s.passStore + m_tree->currentDir(true))),
14 ✔
2117
      QLineEdit::Normal, "", &ok);
14 ✔
2118
  if (!ok || newdir.isEmpty()) {
7 ✔
2119
    return;
2120
  }
2121
  // Checked and created as one and the same path: the check resolves ".."
2122
  // lexically, the system after following links, so "link/../x" would pass
2123
  // as the store's x and be made beside the link's target.
2124
  newdir = QDir::cleanPath(newdir.prepend(dir));
6 ✔
2125
  if (!confirmPathInStore(newdir)) {
6 ✔
2126
    return;
2127
  }
2128
  // Behind a link the folder would be made outside the store, as Users,
2129
  // Re-encrypt and Delete already refuse.
2130
  if (refuseLinkedFolder(newdir)) {
5 ✔
2131
    return;
2132
  }
2133
  // The tree, like `pass ls`, hides names that start with a dot.
2134
  const QStringList parts =
2135
      QDir(s.passStore).relativeFilePath(newdir).split(u'/');
4 ✔
2136
  if (std::any_of(parts.cbegin(), parts.cend(), [](const QString &part) {
8 ✔
2137
        return part != u'.' && part.startsWith(u'.');
4 ✔
2138
      })) {
2139
    PlainMessageBox::warning(this, tr("Hidden folder"),
2 ✔
2140
                             tr("A folder that starts with a dot would be "
1 ✔
2141
                                "hidden from the list: %1")
2142
                                 .arg(newdir));
2 ✔
2143
    return;
1 ✔
2144
  }
2145
  // Exists already: an error, as QDir::mkdir() made it before.
2146
  if (QFileInfo::exists(newdir) || !Util::mkpathForStore(newdir)) {
3 ✔
2147
    PlainMessageBox::warning(this, tr("Error"),
2 ✔
2148
                             tr("Failed to create folder: %1").arg(newdir));
2 ✔
2149
    return;
1 ✔
2150
  }
2151
  // No .gpg-id of its own: the folder uses its parent's recipients, as with
2152
  // pass, until Users gives it a list. A copy of the parent's list (#1688)
2153
  // kept every recipient later removed above it, and its entries stayed
2154
  // readable by them.
2155
}
7 ✔
2156

2157
void MainWindow::renameFolder() {
4 ✔
2158
  bool ok;
2159
  QString srcDir = QDir::cleanPath(m_tree->currentDir(false));
4 ✔
2160
  QString srcDirName = QDir(srcDir).dirName();
4 ✔
2161
  QString newName =
2162
      QInputDialog::getText(this, tr("Rename folder"), tr("Rename folder to: "),
4 ✔
2163
                            QLineEdit::Normal, srcDirName, &ok);
8 ✔
2164
  if (!ok || newName.isEmpty()) {
4 ✔
2165
    return;
2166
  }
2167
  QString destDir = srcDir;
2168
  destDir.replace(srcDir.lastIndexOf(srcDirName), srcDirName.length(), newName);
3 ✔
2169
  if (!confirmPathInStore(destDir)) {
3 ✔
2170
    return;
2171
  }
2172
  if (!PlainMessageBox::confirmPassRun(
2 ✔
2173
          this, QtPassSettings::getPassStore(), [&srcDir, &destDir] {
4 ✔
2174
            return QtPassSettings::getPass()->entriesMoveWouldWiden(srcDir,
2 ✔
2175
                                                                    destDir);
2 ✔
2176
          })) {
2177
    return;
2178
  }
2179
  QtPassSettings::getPass()->Move(srcDir, destDir, false);
6 ✔
2180
}
2181

2182
void MainWindow::editPassword(const QString &file) {
6 ✔
2183
  if (!file.isEmpty()) {
6 ✔
2184
    const AppSettings s = QtPassSettings::loadEffective();
6 ✔
2185
    if (s.useGit && s.autoPull) {
6 ✔
2186
      onUpdate(true);
1 ✔
2187
    }
2188
    // The dialog decrypts the entry itself to fill its fields. That decrypt
2189
    // lands on the same finishedShow the panel uses, so drop the panel's claim
2190
    // to it: otherwise passShowHandler() repaints and, with "Always copy",
2191
    // puts the entry's old password on the clipboard - replacing whatever the
2192
    // user copied to paste into the dialog.
2193
    m_shownFile.clear();
6 ✔
2194
    setPassword(file, false);
6 ✔
2195
  }
6 ✔
2196
}
6 ✔
2197

2198
void MainWindow::renamePassword() {
2 ✔
2199
  bool ok;
2200
  QString file = getFile(ui->treeView->currentIndex(), false);
2 ✔
2201
  QString filePath = QFileInfo(file).path();
2 ✔
2202
  QString fileName = QFileInfo(file).fileName();
2 ✔
2203
  if (fileName.endsWith(".gpg", Qt::CaseInsensitive)) {
4 ✔
2204
    fileName.chop(4);
2 ✔
2205
  }
2206

2207
  QString newName =
2208
      QInputDialog::getText(this, tr("Rename file"), tr("Rename file to: "),
2 ✔
2209
                            QLineEdit::Normal, fileName, &ok);
4 ✔
2210
  if (!ok || newName.isEmpty()) {
2 ✔
2211
    return;
2212
  }
2213
  QString newFile = Util::joinPath(filePath, newName);
2 ✔
2214
  if (!confirmPathInStore(newFile)) {
2 ✔
2215
    return;
2216
  }
2217
  if (!PlainMessageBox::confirmPassRun(
1 ✔
2218
          this, QtPassSettings::getPassStore(), [&file, &newFile] {
2 ✔
2219
            return QtPassSettings::getPass()->entriesMoveWouldWiden(file,
1 ✔
2220
                                                                    newFile);
1 ✔
2221
          })) {
2222
    return;
2223
  }
2224
  QtPassSettings::getPass()->Move(file, newFile, false);
3 ✔
2225
}
2226

2227
void MainWindow::copySelectionOrPassword() {
5 ✔
2228
  QWidget *focus = QApplication::focusWidget();
5 ✔
2229
  // The widget's own copy: a SecretTextBrowser marks what it copies as
2230
  // secret for clipboard managers, as the context menu's Copy does.
2231
  if (auto *text = qobject_cast<QTextEdit *>(focus);
5 ✔
2232
      text != nullptr && text->textCursor().hasSelection()) {
5 ✔
2233
    text->copy();
1 ✔
2234
    return;
1 ✔
2235
  }
2236
  // Through the clipboard manager, as a copy button would: the label may be
2237
  // the OTP code, which gets the secret hint and the autoclear.
2238
  if (auto *label = qobject_cast<QLabel *>(focus);
2239
      label != nullptr && label->hasSelectedText()) {
4 ✔
2240
    m_qtPass->clipboard().copyText(label->selectedText());
1 ✔
2241
    return;
1 ✔
2242
  }
2243
  // A line of the content search results is decrypted text: through the
2244
  // clipboard manager too, for the secret hint and the autoclear.
2245
  if (focus == ui->grepResultsList) {
3 ✔
2246
    if (const QTreeWidgetItem *item = ui->grepResultsList->currentItem();
3 ✔
2247
        item != nullptr && !item->text(0).isEmpty()) {
6 ✔
2248
      m_qtPass->clipboard().copyText(item->text(0));
6 ✔
2249
    }
2250
    return;
3 ✔
2251
  }
2252
  copyPasswordFromTreeview();
×
2253
}
2254

2255
void MainWindow::copyPasswordFromTreeview() {
9 ✔
2256
  // While content search results hide the tree, its current entry is not
2257
  // what the user looks at: no decrypt, as for Edit and OTP.
2258
  if (ui->treeView->isHidden()) {
9 ✔
2259
    return;
×
2260
  }
2261
  QFileInfo fileOrFolder = m_tree->fileInfo(ui->treeView->currentIndex());
9 ✔
2262

2263
  if (fileOrFolder.isFile()) {
9 ✔
2264
    QString file = getFile(ui->treeView->currentIndex(), true);
9 ✔
2265
    // The newest Ctrl+C wins: finishedShow names its file, so the decrypt of
2266
    // an earlier request is simply not this one's.
2267
    m_copyRequestFile = file;
9 ✔
2268
    // This Show repaints the panel as well; see onOtp().
2269
    m_shownFile = file;
9 ✔
2270
    QtPassSettings::getPass()->Show(file);
18 ✔
2271
  }
2272
}
9 ✔
2273

2274
void MainWindow::passwordFromFileToClipboard(const QString &text,
32 ✔
2275
                                             const QString &file) {
2276
  if (m_copyRequestFile.isEmpty() || file != m_copyRequestFile) {
32 ✔
2277
    return;
27 ✔
2278
  }
2279
  m_copyRequestFile.clear();
8 ✔
2280
  // The first line, without a list of every line (an entry can expand into
2281
  // millions of them), and without the "\r" of a CRLF line end, as the
2282
  // password row and "Always copy" have it.
2283
  const QString first = FileContent::passwordLine(text);
8 ✔
2284
  // A `pass otp insert` entry's first line is the otpauth:// URI carrying the
2285
  // TOTP seed, and an OTP field holding a seed there is the same; copying it
2286
  // would leak 2FA material. Matches the display path
2287
  // (FileContent::getPasswordForDisplay / PasswordDisplayPanel).
2288
  if (FileContent::isOtpPasswordLine(first)) {
8 ✔
2289
    flashText(tr("This entry holds an OTP secret, not a password"), true);
6 ✔
2290
    return;
2291
  }
2292
  m_qtPass->clipboard().copyText(first);
5 ✔
2293
}
2294

2295
void MainWindow::showStatusMessage(const QString &msg, int timeout) {
46 ✔
2296
  ui->statusBar->showMessage(msg, timeout);
46 ✔
2297
}
46 ✔
2298

2299
void MainWindow::reencryptPath(const QString &dir) {
4 ✔
2300
  QDir checkDir(dir);
4 ✔
2301
  if (!checkDir.exists()) {
4 ✔
2302
    PlainMessageBox::critical(this, tr("Error"),
2 ✔
2303
                              tr("Directory does not exist: %1").arg(dir));
2 ✔
2304
    return;
1 ✔
2305
  }
2306
  if (refuseLinkedFolder(dir)) {
3 ✔
2307
    return;
2308
  }
2309

2310
  const bool yes = PlainMessageBox::askYes(
3 ✔
2311
      this, tr("Re-encrypt passwords"),
3 ✔
2312
      tr("Re-encrypt all passwords in %1?\n\n"
3 ✔
2313
         "This will re-encrypt ALL password files in this folder "
2314
         "using the current recipients defined in .gpg-id.\n\n"
2315
         "This may rewrite many files and cannot be undone easily.\n\n"
2316
         "Continue?")
2317
          // On one line: a name with line feeds pushed the warning out of
2318
          // the box, which shows 40 lines at most.
2319
          .arg(Util::displayable(QDir(dir).dirName(), false)));
6 ✔
2320

2321
  if (!yes)
3 ✔
2322
    return;
2323

2324
  // Disable now; the asynchronous startReencryptPath signal re-runs this
2325
  // harmlessly.
2326
  startReencryptPath();
1 ✔
2327

2328
  // Under the current profile's settings: with the pass backend active, the
2329
  // native one is not re-initialised on a profile switch.
2330
  QtPassSettings::getImitatePass()->reencryptPath(
2 ✔
2331
      QDir::cleanPath(QDir(dir).absolutePath()), QtPassSettings::load());
2 ✔
2332
}
4 ✔
2333

2334
// Idempotent: reencryptPath() calls it before ImitatePass emits the signal.
2335
void MainWindow::startReencryptPath() {
7 ✔
2336
  m_reencryptRunning = true;
7 ✔
2337
  setUiElementsEnabled(false);
7 ✔
2338
  // The worker always ends with endReencryptPath(), and Cancel is available
2339
  // throughout, so the generic watchdog is not needed for this operation.
2340
  m_uiWatchdog.stop();
7 ✔
2341
  ui->treeView->setDisabled(true);
7 ✔
2342
  if (m_reencryptProgress)
7 ✔
2343
    return;
2344
  auto *progress = new QProgressDialog(tr("Re-encrypting passwords..."),
5 ✔
2345
                                       tr("Cancel"), 0, 0, this);
10 ✔
2346
  progress->setWindowTitle(tr("Re-encrypt passwords"));
5 ✔
2347
  progress->setWindowModality(Qt::WindowModal);
5 ✔
2348
  progress->setAutoClose(false);
5 ✔
2349
  progress->setAutoReset(false);
5 ✔
2350
  progress->setMinimumDuration(0);
5 ✔
2351
  connect(progress, &QProgressDialog::canceled, this, [this]() {
5 ✔
2352
    QtPassSettings::getImitatePass()->cancelReencryptPath();
1 ✔
2353
    showStatusMessage(tr("Cancelling re-encryption"), 5000);
1 ✔
2354
  });
1 ✔
2355
  m_reencryptProgress = progress;
2356
  progress->show();
5 ✔
2357
}
2358

2359
void MainWindow::reencryptProgress(int current, int total) {
7 ✔
2360
  if (!m_reencryptProgress || m_inProgressUpdate)
7 ✔
2361
    return;
2362
  QProgressDialog *progress = m_reencryptProgress;
2363
  progress->setMaximum(total);
6 ✔
2364
  progress->setLabelText(
6 ✔
2365
      tr("Re-encrypting passwords: %1 of %2").arg(current).arg(total));
6 ✔
2366
  // On a modal dialog setValue() runs processEvents(), which can deliver
2367
  // endReencryptPath(), even inside a nested event loop that would delete a
2368
  // deleteLater()ed dialog under setValue()'s feet: keep this last, and
2369
  // delete the dialog only after it returns.
2370
  m_inProgressUpdate = true;
6 ✔
2371
  progress->setValue(current);
6 ✔
2372
  m_inProgressUpdate = false;
6 ✔
2373
  if (m_progressToDelete) {
6 ✔
2374
    m_progressToDelete->deleteLater();
2 ✔
2375
    m_progressToDelete = nullptr;
2376
  }
2377
}
2378

2379
void MainWindow::endReencryptPath() {
5 ✔
2380
  m_reencryptRunning = false;
5 ✔
2381
  if (m_reencryptProgress) {
5 ✔
2382
    m_reencryptProgress->hide();
5 ✔
2383
    if (m_inProgressUpdate) {
5 ✔
2384
      m_progressToDelete = m_reencryptProgress;
2385
    } else {
2386
      m_reencryptProgress->deleteLater();
3 ✔
2387
    }
2388
    m_reencryptProgress = nullptr;
2389
  }
2390
  setUiElementsEnabled(true);
5 ✔
2391
}
5 ✔
2392

2393
void MainWindow::askReencryptUnexpected(const QString &dir,
×
2394
                                        const QStringList &files,
2395
                                        const QStringList &details) {
2396
  const AppSettings s = QtPassSettings::load();
×
2397
  const QDir store(s.passStore);
×
2398
  // Sorted by name, so each folder's entries stand together; who would gain
2399
  // each one beside it, as the names alone are the writer's choosing.
2400
  QList<std::pair<QString, QString>> rows;
×
2401
  for (qsizetype i = 0; i < files.size(); ++i) {
×
2402
    rows.append({Util::displayable(store.relativeFilePath(files.at(i)), false),
×
2403
                 details.value(i)});
×
2404
  }
2405
  std::sort(rows.begin(), rows.end());
×
2406
  constexpr int kListed = 15;
2407
  QStringList lines;
×
2408
  for (qsizetype i = 0; i < rows.size() && i < kListed; ++i) {
×
2409
    lines << rows.at(i).first + QStringLiteral(": ") + rows.at(i).second;
×
2410
  }
2411
  if (rows.size() > kListed) {
×
2412
    lines << tr("... and %n more", nullptr,
×
2413
                static_cast<int>(rows.size() - kListed));
×
2414
  }
2415
  const int n = static_cast<int>(files.size());
×
2416
  const bool yes = PlainMessageBox::askYes(
×
2417
      this, tr("Re-encrypt these too?"),
×
2418
      tr("%n entry(s) here would become readable by people on this "
×
2419
         "folder's list who cannot read them now, and whom you did not just "
2420
         "add, so they were left as they are. Someone who can read this "
2421
         "folder may have copied them in from a folder they cannot read.",
2422
         nullptr, n) +
×
2423
          QStringLiteral("\n\n") + lines.join(QLatin1Char('\n')) +
×
2424
          QStringLiteral("\n\n") +
×
2425
          tr("Re-encrypt them for this folder's recipients? If not, they "
×
2426
             "stay readable only by whoever they are encrypted to now."));
×
2427
  if (!yes) {
×
2428
    return;
2429
  }
2430
  startReencryptPath();
×
2431
  QtPassSettings::getImitatePass()->reencryptAlso(dir, files, s);
×
2432
}
×
2433

2434
void MainWindow::exportPublicKey() {
4 ✔
2435
  const AppSettings s = QtPassSettings::load();
4 ✔
2436
  const QString identity = s.passSigningKey;
2437
  if (identity.isEmpty()) {
4 ✔
2438
    QMessageBox::information(
2 ✔
2439
        this, tr("Export public key"),
1 ✔
2440
        tr("<h3>Export your public key</h3>"
×
2441
           "<p>No signing key is configured. Set one in QtPass Settings "
2442
           "&gt; GPG keys, or run this in a terminal:</p>"
2443
           "<pre>gpg --armor --export --output my_key.asc &lt;your-key-id"
2444
           "&gt;</pre>"
2445
           "<p>Then send the file to your teammates.</p>"));
2446
    return;
1 ✔
2447
  }
2448
  QString gpgExe = s.gpgExecutable;
2449
  if (gpgExe.isEmpty()) {
3 ✔
2450
    gpgExe = QStringLiteral("gpg");
×
2451
  }
2452
  const QStringList keys = identity.split(' ', Qt::SkipEmptyParts);
3 ✔
2453
  // gpg --export takes every key block that holds the ID: another key that
2454
  // holds yours as a subkey would go out to your teammates as yours.
2455
  if (Pass *pass = QtPassSettings::getPass(); pass != nullptr) {
3 ✔
2456
    if (const std::optional<QHash<QString, QStringList>> held =
2457
            pass->keyLinesHeldTwice(keys);
3 ✔
2458
        !held || !held->isEmpty()) {
3 ✔
2459
      PlainMessageBox::warning(
1 ✔
2460
          this, tr("Export public key"),
1 ✔
2461
          tr("Your key cannot be exported on its own:\n\n%1")
1 ✔
2462
              .arg(Pass::describeKeyLinesHeldTwice(held)));
2 ✔
2463
      return;
2464
    }
2465
  }
2466
  QString stdOut;
2 ✔
2467
  QString stdErr;
2 ✔
2468
  // In the store's environment, the keyring the check above read.
2469
  Pass *pass = QtPassSettings::getPass();
2 ✔
2470
  int exitCode =
2471
      pass != nullptr
2472
          ? pass->exportPublicKeys(gpgExe, keys, &stdOut, &stdErr)
2 ✔
2473
          : Executor::executeBlocking(gpgExe,
×
2474
                                      QStringList{QStringLiteral("--armor"),
×
2475
                                                  QStringLiteral("--export")} +
2 ✔
2476
                                          keys,
×
2477
                                      &stdOut, &stdErr);
2478
  if (exitCode != 0 || stdOut.isEmpty()) {
2 ✔
2479
    PlainMessageBox::warning(this, tr("Export public key"),
2 ✔
2480
                             tr("Could not export public key for %1.\n\n%2")
1 ✔
2481
                                 .arg(identity, stdErr.isEmpty()
2 ✔
2482
                                                    ? tr("No output from gpg.")
2 ✔
2483
                                                    : stdErr));
2484
    return;
2485
  }
2486
  ExportPublicKeyDialog dialog(identity, stdOut, this);
1 ✔
2487
  dialog.exec();
1 ✔
2488
}
5 ✔
2489

2490
// UsersDialog only ticks keys already in the keyring; importing a foreign
2491
// key still has to happen via gpg (or QtPass settings) first.
2492
void MainWindow::addRecipient(const QString &dir) {
2 ✔
2493
  if (refuseLinkedFolder(dir)) {
2 ✔
2494
    return;
1 ✔
2495
  }
2496
  UsersDialog d(QtPassSettings::getPass(), QtPassSettings::load(), dir, this);
1 ✔
2497
  d.exec();
1 ✔
2498
}
1 ✔
2499

2500
// A tree-picked folder that is, or lies behind, a symlink or junction is not
2501
// a folder of the store. The store root itself may be a link (a synced
2502
// folder); that is configuration, not a tree pick.
2503
auto MainWindow::refuseLinkedFolder(const QString &dir) -> bool {
23 ✔
2504
  if (!Util::isUnderLink(dir, QtPassSettings::load().passStore)) {
23 ✔
2505
    return false;
2506
  }
2507
  PlainMessageBox::critical(
4 ✔
2508
      this, tr("Not a folder of the store"),
4 ✔
2509
      tr("%1 is, or lies behind, a symbolic link or junction. What that "
4 ✔
2510
         "points to is not part of the password store and is left alone.")
2511
          .arg(QDir::toNativeSeparators(QDir::cleanPath(dir))));
8 ✔
2512
  return true;
4 ✔
2513
}
2514

2515
void MainWindow::showShareHelp() {
1 ✔
2516
  QMessageBox::information(
2 ✔
2517
      this, tr("Sharing passwords with GPG"),
1 ✔
2518
      tr("<h3>Sharing passwords with GPG</h3>"
1 ✔
2519
         "<p>To share passwords with other users:</p>"
2520
         "<ol>"
2521
         "<li><b>Export your public key</b> and send it to teammates</li>"
2522
         "<li><b>Import teammates' public keys</b> into your GPG keyring</li>"
2523
         "<li><b>Re-encrypt passwords</b> so all recipients can decrypt "
2524
         "them</li>"
2525
         "</ol>"
2526
         "<p>Only people who have a matching secret key can decrypt the "
2527
         "passwords.</p>"
2528
         "<p><b>Tip:</b> Use the same GPG key for all shared folders.</p>"
2529
         "<p>See the FAQ for more details.</p>"));
2530
}
1 ✔
2531

2532
void MainWindow::updateGitButtonVisibility(bool uiEnabled) {
481 ✔
2533
  const AppSettings s = QtPassSettings::loadEffective();
481 ✔
2534
  // Without Git there is nothing to push or pull, ever: the buttons go, not
2535
  // grey out. While an operation runs they stay and are disabled.
2536
  const bool usable =
2537
      s.useGit && !(s.gitExecutable.isEmpty() && s.passExecutable.isEmpty());
481 ✔
2538
  ui->actionPush->setVisible(usable);
481 ✔
2539
  ui->actionUpdate->setVisible(usable);
481 ✔
2540
  // The separator in front of them would otherwise sit next to the next one.
2541
  const QList<QAction *> actions = ui->toolBar->actions();
481 ✔
2542
  const qsizetype at = actions.indexOf(ui->actionPush);
481 ✔
2543
  if (at > 0 && actions.at(at - 1)->isSeparator()) {
481 ✔
2544
    actions.at(at - 1)->setVisible(usable);
481 ✔
2545
  }
2546
  enableGitButtons(usable && uiEnabled);
481 ✔
2547
}
481 ✔
2548

2549
void MainWindow::updateOtpButtonVisibility(bool uiEnabled) {
491 ✔
2550
  // No platform gating: codes are generated in-process. Visible but disabled
2551
  // when OTP is off: the panel never shows an OTP field (a secret), so hiding
2552
  // this too would leave no trace of the feature. Honour uiEnabled, or the
2553
  // user can stack Show calls while a decrypt is in flight.
2554
  ui->actionOtp->setVisible(true);
491 ✔
2555
  ui->actionOtp->setEnabled(QtPassSettings::isUseOtp() && uiEnabled);
599 ✔
2556
}
491 ✔
2557

2558
void MainWindow::updateGrepButtonVisibility() {
211 ✔
2559
  const bool enabled = QtPassSettings::isUseGrepSearch();
211 ✔
2560
  ui->grepButton->setVisible(enabled);
211 ✔
2561
  ui->grepCaseButton->setVisible(enabled);
211 ✔
2562
  if (!enabled && m_grep.inGrepMode()) {
211 ✔
2563
    ui->grepButton->setChecked(false);
1 ✔
2564
  }
2565
}
211 ✔
2566

2567
void MainWindow::enableGitButtons(const bool &state) {
481 ✔
2568
  ui->actionPush->setEnabled(state);
481 ✔
2569
  ui->actionUpdate->setEnabled(state);
481 ✔
2570
}
481 ✔
2571

2572
void MainWindow::critical(const QString &title, const QString &msg) {
4 ✔
2573
  // Pass's messages quote store paths; see PlainMessageBox.
2574
  PlainMessageBox::critical(this, title, msg);
4 ✔
2575
}
4 ✔
2576

2577
void MainWindow::onProcessOutput(const QString &output, bool isError,
7 ✔
2578
                                 Enums::PROCESS pid) {
2579
  if (!QtPassSettings::isShowProcessOutput()) {
7 ✔
2580
    return;
2581
  }
2582
  m_processOutput->append(output, isError,
6 ✔
2583
                          ProcessOutputPanel::processName(pid));
12 ✔
2584
}
2585

2586
void MainWindow::updateProcessOutputVisibility() {
5 ✔
2587
  // The action's toggled handler shows or hides the dock.
2588
  ui->actionShowProcessOutput->setChecked(
5 ✔
2589
      QtPassSettings::isShowProcessOutput());
5 ✔
2590
  m_processOutput->setVisible(QtPassSettings::isShowProcessOutput());
5 ✔
2591
}
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