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

IJHack / QtPass / 46376622100

30 Nov 2026 07:48AM UTC coverage: 94.369% (-0.1%) from 94.493%
46376622100

push

github

web-flow
The store tree follows changes without Qt's quadratic watch (#2409)

QFileSystemModel watched the store and, for every changed file, found its
row by a linear search, so a pull that rewrote N entries of one folder froze
the window for on the order of N² comparisons (about half a minute for
20000 entries). Scan finding ANT-2026-OJ33F28Z.

The tree's model no longer watches (DontWatchForChanges). StoreTree watches
the folders the shown model has listed with its own QFileSystemWatcher and,
once they have been quiet for 300 ms, builds a fresh model in the
background, listing the store root and every folder listed before, and
swaps it in with the expanded folders, the current entry and the scroll
position kept. Building a fresh model is linear; the worst stall for 20000
entries went from about 23 s to under a second.

Around the swap:
- one build at a time; a change during a build runs one more after it;
- a folder listed while a build runs is listed in the fresh model too;
- the swap waits up to 3 s; listings still under way finish in the shown
  model, after which a search is applied again;
- a folder expanded later is watched then; a store shown again gets a
  fresh model;
- a current entry the swap cannot show is reported (currentEntryLost); an
  open tree menu closes on it rather than acting on the store root, and a
  current entry that still exists comes back once it shows, unless the
  user picked another one meanwhile.

MainWindow's pending-open logic follows StoreTree::directoryLoaded instead
of the model's signal.

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

145 of 152 new or added lines in 2 files covered. (95.39%)

15 existing lines in 1 file now uncovered.

11313 of 11988 relevant lines covered (94.37%)

23974.39 hits per line

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

94.35
/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 <array>
69
#include <utility>
70

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

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

97
  m_qtPass = new QtPass(this);
204 ✔
98
  restoreWindow();
204 ✔
99
  connectBackends();
204 ✔
100

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

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

118
  initTextBrowser();
204 ✔
119

120
  updateProfileBox();
204 ✔
121

122
  initDisplayPanel();
204 ✔
123

124
  QtPassSettings::getPass()->updateEnv();
204 ✔
125

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

134
  initTimers();
204 ✔
135

136
  initToolBarButtons();
204 ✔
137
  initStatusBar();
204 ✔
138
  initProcessOutput();
204 ✔
139

140
  ui->lineEdit->setClearButtonEnabled(true);
204 ✔
141
  updateGrepButtonVisibility();
204 ✔
142

143
  setUiElementsEnabled(true);
204 ✔
144

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

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

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

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

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

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

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

277
  searchTimer.setInterval(350);
204 ✔
278
  searchTimer.setSingleShot(true);
204 ✔
279

280
  connect(&searchTimer, &QTimer::timeout, this, &MainWindow::onTimeoutSearch);
204 ✔
281

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

691
  applyTextBrowserSettings();
4 ✔
692
  applyWindowFlagsSettings();
4 ✔
693

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1022
  applyWindowFlagsSettings();
215 ✔
1023

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1982
void MainWindow::showContextMenu(const QPoint &pos) {
13 ✔
1983
  const AppSettings s = QtPassSettings::load();
13 ✔
1984
  const QModelIndex index = ui->treeView->indexAt(pos);
13 ✔
1985
  const bool selected = index.isValid();
1986
  if (!selected) {
1987
    ui->treeView->clearSelection();
1 ✔
1988
    ui->actionDelete->setEnabled(false);
1 ✔
1989
    ui->actionEdit->setEnabled(false);
1 ✔
1990
  }
1991
  ui->treeView->setCurrentIndex(index);
13 ✔
1992
  const QPoint globalPos = ui->treeView->viewport()->mapToGlobal(pos);
13 ✔
1993
  const QFileInfo fileOrFolder = m_tree->fileInfo(ui->treeView->currentIndex());
13 ✔
1994
  const bool isDir = fileOrFolder.isDir();
13 ✔
1995

1996
  QMenu contextMenu;
13 ✔
1997
  if (!selected || isDir) {
13 ✔
1998
    const std::array<std::pair<QString, void (MainWindow::*)()>, 4> onFolder{{
1999
        {tr("Open folder with file manager"), &MainWindow::openFolder},
12 ✔
2000
        {tr("Add folder"), &MainWindow::addFolder},
12 ✔
2001
        {tr("Add password"), &MainWindow::addPassword},
12 ✔
2002
        {tr("Users"), &MainWindow::onUsers},
12 ✔
2003
    }};
×
2004
    for (const auto &[text, slot] : onFolder) {
60 ✔
2005
      connect(contextMenu.addAction(text), &QAction::triggered, this, slot);
48 ✔
2006
    }
2007
  } else if (fileOrFolder.isFile()) {
1 ✔
2008
    connect(contextMenu.addAction(tr("Edit")), &QAction::triggered, this,
1 ✔
2009
            &MainWindow::onEdit);
2 ✔
2010
  }
2011
  if (selected) {
13 ✔
2012
    contextMenu.addSeparator();
12 ✔
2013
    if (isDir) {
12 ✔
2014
      connect(contextMenu.addAction(tr("Rename folder")), &QAction::triggered,
11 ✔
2015
              this, &MainWindow::renameFolder);
22 ✔
2016
    } else if (fileOrFolder.isFile()) {
1 ✔
2017
      connect(contextMenu.addAction(tr("Rename password")), &QAction::triggered,
1 ✔
2018
              this, &MainWindow::renamePassword);
2 ✔
2019
    }
2020
    connect(contextMenu.addAction(tr("Delete")), &QAction::triggered, this,
12 ✔
2021
            &MainWindow::onDelete);
12 ✔
2022
    if (isDir) {
12 ✔
2023
      addShareMenu(contextMenu, s);
11 ✔
2024
    }
2025
  }
2026
  // Its actions read the current entry when picked: once that is gone they
2027
  // would act on the store root instead.
2028
  connect(m_tree, &StoreTree::currentEntryLost, &contextMenu, &QMenu::close);
13 ✔
2029
  contextMenu.exec(globalPos);
13 ✔
2030
}
13 ✔
2031

2032
auto MainWindow::browserContextMenu(const QPoint &pos) -> QMenu * {
3 ✔
2033
  // createStandardContextMenu() takes document coordinates, anchorAt() and
2034
  // the menu's place viewport ones: scrolled, the menu checked the text
2035
  // above the link and left "Copy Link Location" disabled.
2036
  // Right to left, the horizontal offset counts from the other end.
2037
  const QScrollBar *across = ui->textBrowser->horizontalScrollBar();
3 ✔
2038
  const int dx = ui->textBrowser->isRightToLeft()
3 ✔
2039
                     ? across->maximum() - across->value()
3 ✔
2040
                     : across->value();
3 ✔
2041
  const QPoint documentPos =
2042
      pos + QPoint(dx, ui->textBrowser->verticalScrollBar()->value());
3 ✔
2043
  QMenu *contextMenu = ui->textBrowser->createStandardContextMenu(documentPos);
3 ✔
2044
  // Reparent from textBrowser: a browser stylesheet cascades to the child
2045
  // QMenu and breaks its opaque native background.
2046
  contextMenu->setParent(this, contextMenu->windowFlags());
3 ✔
2047
  if (auto *copyLink =
3 ✔
2048
          contextMenu->findChild<QAction *>(QStringLiteral("link-copy"))) {
3 ✔
2049
    const QString link = ui->textBrowser->anchorAt(pos);
3 ✔
2050
    disconnect(copyLink, &QAction::triggered, nullptr, nullptr);
3 ✔
2051
    connect(copyLink, &QAction::triggered, this, [this, link] {
10 ✔
2052
      if (!link.isEmpty()) {
1 ✔
2053
        m_qtPass->clipboard().copyText(link);
1 ✔
2054
      }
2055
    });
1 ✔
2056
  }
2057
  return contextMenu;
3 ✔
2058
}
2059

2060
void MainWindow::showBrowserContextMenu(const QPoint &pos) {
1 ✔
2061
  QMenu *contextMenu = browserContextMenu(pos);
1 ✔
2062
  contextMenu->exec(ui->textBrowser->viewport()->mapToGlobal(pos));
1 ✔
2063
  delete contextMenu;
1 ✔
2064
}
1 ✔
2065

2066
void MainWindow::openFolder() {
1 ✔
2067
  QString dir = m_tree->currentDir(false);
1 ✔
2068

2069
  QString path = QDir::toNativeSeparators(dir);
1 ✔
2070
  QDesktopServices::openUrl(QUrl::fromLocalFile(path));
1 ✔
2071
}
1 ✔
2072

2073
void MainWindow::addFolder() {
7 ✔
2074
  const AppSettings s = QtPassSettings::load();
7 ✔
2075
  bool ok;
2076
  QString dir = m_tree->currentDir(false);
7 ✔
2077
  QString newdir = QInputDialog::getText(
2078
      this, tr("New folder"),
7 ✔
2079
      tr("New folder: \n(Will be placed in %1 )")
7 ✔
2080
          .arg(Util::shownName(s.passStore + m_tree->currentDir(true))),
14 ✔
2081
      QLineEdit::Normal, "", &ok);
14 ✔
2082
  if (!ok || newdir.isEmpty()) {
7 ✔
2083
    return;
2084
  }
2085
  // Checked and created as one and the same path: the check resolves ".."
2086
  // lexically, the system after following links, so "link/../x" would pass
2087
  // as the store's x and be made beside the link's target.
2088
  newdir = QDir::cleanPath(newdir.prepend(dir));
6 ✔
2089
  if (!confirmPathInStore(newdir)) {
6 ✔
2090
    return;
2091
  }
2092
  // Behind a link the folder would be made outside the store, as Users,
2093
  // Re-encrypt and Delete already refuse.
2094
  if (refuseLinkedFolder(newdir)) {
5 ✔
2095
    return;
2096
  }
2097
  // The tree, like `pass ls`, hides names that start with a dot.
2098
  const QStringList parts =
2099
      QDir(s.passStore).relativeFilePath(newdir).split(u'/');
4 ✔
2100
  if (std::any_of(parts.cbegin(), parts.cend(), [](const QString &part) {
8 ✔
2101
        return part != u'.' && part.startsWith(u'.');
4 ✔
2102
      })) {
2103
    PlainMessageBox::warning(this, tr("Hidden folder"),
2 ✔
2104
                             tr("A folder that starts with a dot would be "
1 ✔
2105
                                "hidden from the list: %1")
2106
                                 .arg(newdir));
2 ✔
2107
    return;
1 ✔
2108
  }
2109
  // Exists already: an error, as QDir::mkdir() made it before.
2110
  if (QFileInfo::exists(newdir) || !Util::mkpathForStore(newdir)) {
3 ✔
2111
    PlainMessageBox::warning(this, tr("Error"),
2 ✔
2112
                             tr("Failed to create folder: %1").arg(newdir));
2 ✔
2113
    return;
1 ✔
2114
  }
2115
  // No .gpg-id of its own: the folder uses its parent's recipients, as with
2116
  // pass, until Users gives it a list. A copy of the parent's list (#1688)
2117
  // kept every recipient later removed above it, and its entries stayed
2118
  // readable by them.
2119
}
7 ✔
2120

2121
void MainWindow::renameFolder() {
4 ✔
2122
  bool ok;
2123
  QString srcDir = QDir::cleanPath(m_tree->currentDir(false));
4 ✔
2124
  QString srcDirName = QDir(srcDir).dirName();
4 ✔
2125
  QString newName =
2126
      QInputDialog::getText(this, tr("Rename folder"), tr("Rename folder to: "),
4 ✔
2127
                            QLineEdit::Normal, srcDirName, &ok);
8 ✔
2128
  if (!ok || newName.isEmpty()) {
4 ✔
2129
    return;
2130
  }
2131
  QString destDir = srcDir;
2132
  destDir.replace(srcDir.lastIndexOf(srcDirName), srcDirName.length(), newName);
3 ✔
2133
  if (!confirmPathInStore(destDir)) {
3 ✔
2134
    return;
2135
  }
2136
  if (!PlainMessageBox::confirmPassRun(
2 ✔
2137
          this, QtPassSettings::getPassStore(), [&srcDir, &destDir] {
4 ✔
2138
            return QtPassSettings::getPass()->entriesMoveWouldWiden(srcDir,
2 ✔
2139
                                                                    destDir);
2 ✔
2140
          })) {
2141
    return;
2142
  }
2143
  QtPassSettings::getPass()->Move(srcDir, destDir, false);
6 ✔
2144
}
2145

2146
void MainWindow::editPassword(const QString &file) {
6 ✔
2147
  if (!file.isEmpty()) {
6 ✔
2148
    const AppSettings s = QtPassSettings::loadEffective();
6 ✔
2149
    if (s.useGit && s.autoPull) {
6 ✔
2150
      onUpdate(true);
1 ✔
2151
    }
2152
    // The dialog decrypts the entry itself to fill its fields. That decrypt
2153
    // lands on the same finishedShow the panel uses, so drop the panel's claim
2154
    // to it: otherwise passShowHandler() repaints and, with "Always copy",
2155
    // puts the entry's old password on the clipboard - replacing whatever the
2156
    // user copied to paste into the dialog.
2157
    m_shownFile.clear();
6 ✔
2158
    setPassword(file, false);
6 ✔
2159
  }
6 ✔
2160
}
6 ✔
2161

2162
void MainWindow::renamePassword() {
2 ✔
2163
  bool ok;
2164
  QString file = getFile(ui->treeView->currentIndex(), false);
2 ✔
2165
  QString filePath = QFileInfo(file).path();
2 ✔
2166
  QString fileName = QFileInfo(file).fileName();
2 ✔
2167
  if (fileName.endsWith(".gpg", Qt::CaseInsensitive)) {
4 ✔
2168
    fileName.chop(4);
2 ✔
2169
  }
2170

2171
  QString newName =
2172
      QInputDialog::getText(this, tr("Rename file"), tr("Rename file to: "),
2 ✔
2173
                            QLineEdit::Normal, fileName, &ok);
4 ✔
2174
  if (!ok || newName.isEmpty()) {
2 ✔
2175
    return;
2176
  }
2177
  QString newFile = Util::joinPath(filePath, newName);
2 ✔
2178
  if (!confirmPathInStore(newFile)) {
2 ✔
2179
    return;
2180
  }
2181
  if (!PlainMessageBox::confirmPassRun(
1 ✔
2182
          this, QtPassSettings::getPassStore(), [&file, &newFile] {
2 ✔
2183
            return QtPassSettings::getPass()->entriesMoveWouldWiden(file,
1 ✔
2184
                                                                    newFile);
1 ✔
2185
          })) {
2186
    return;
2187
  }
2188
  QtPassSettings::getPass()->Move(file, newFile, false);
3 ✔
2189
}
2190

2191
void MainWindow::copySelectionOrPassword() {
5 ✔
2192
  QWidget *focus = QApplication::focusWidget();
5 ✔
2193
  // The widget's own copy: a SecretTextBrowser marks what it copies as
2194
  // secret for clipboard managers, as the context menu's Copy does.
2195
  if (auto *text = qobject_cast<QTextEdit *>(focus);
5 ✔
2196
      text != nullptr && text->textCursor().hasSelection()) {
5 ✔
2197
    text->copy();
1 ✔
2198
    return;
1 ✔
2199
  }
2200
  // Through the clipboard manager, as a copy button would: the label may be
2201
  // the OTP code, which gets the secret hint and the autoclear.
2202
  if (auto *label = qobject_cast<QLabel *>(focus);
2203
      label != nullptr && label->hasSelectedText()) {
4 ✔
2204
    m_qtPass->clipboard().copyText(label->selectedText());
1 ✔
2205
    return;
1 ✔
2206
  }
2207
  // A line of the content search results is decrypted text: through the
2208
  // clipboard manager too, for the secret hint and the autoclear.
2209
  if (focus == ui->grepResultsList) {
3 ✔
2210
    if (const QTreeWidgetItem *item = ui->grepResultsList->currentItem();
3 ✔
2211
        item != nullptr && !item->text(0).isEmpty()) {
6 ✔
2212
      m_qtPass->clipboard().copyText(item->text(0));
6 ✔
2213
    }
2214
    return;
3 ✔
2215
  }
2216
  copyPasswordFromTreeview();
×
2217
}
2218

2219
void MainWindow::copyPasswordFromTreeview() {
9 ✔
2220
  // While content search results hide the tree, its current entry is not
2221
  // what the user looks at: no decrypt, as for Edit and OTP.
2222
  if (ui->treeView->isHidden()) {
9 ✔
2223
    return;
×
2224
  }
2225
  QFileInfo fileOrFolder = m_tree->fileInfo(ui->treeView->currentIndex());
9 ✔
2226

2227
  if (fileOrFolder.isFile()) {
9 ✔
2228
    QString file = getFile(ui->treeView->currentIndex(), true);
9 ✔
2229
    // The newest Ctrl+C wins: finishedShow names its file, so the decrypt of
2230
    // an earlier request is simply not this one's.
2231
    m_copyRequestFile = file;
9 ✔
2232
    // This Show repaints the panel as well; see onOtp().
2233
    m_shownFile = file;
9 ✔
2234
    QtPassSettings::getPass()->Show(file);
18 ✔
2235
  }
2236
}
9 ✔
2237

2238
void MainWindow::passwordFromFileToClipboard(const QString &text,
33 ✔
2239
                                             const QString &file) {
2240
  if (m_copyRequestFile.isEmpty() || file != m_copyRequestFile) {
33 ✔
2241
    return;
28 ✔
2242
  }
2243
  m_copyRequestFile.clear();
8 ✔
2244
  // The first line, without a list of every line (an entry can expand into
2245
  // millions of them), and without the "\r" of a CRLF line end, as the
2246
  // password row and "Always copy" have it.
2247
  const QString first = FileContent::passwordLine(text);
8 ✔
2248
  // A `pass otp insert` entry's first line is the otpauth:// URI carrying the
2249
  // TOTP seed, and an OTP field holding a seed there is the same; copying it
2250
  // would leak 2FA material. Matches the display path
2251
  // (FileContent::getPasswordForDisplay / PasswordDisplayPanel).
2252
  if (FileContent::isOtpPasswordLine(first)) {
8 ✔
2253
    flashText(tr("This entry holds an OTP secret, not a password"), true);
6 ✔
2254
    return;
2255
  }
2256
  m_qtPass->clipboard().copyText(first);
5 ✔
2257
}
2258

2259
void MainWindow::showStatusMessage(const QString &msg, int timeout) {
44 ✔
2260
  ui->statusBar->showMessage(msg, timeout);
44 ✔
2261
}
44 ✔
2262

2263
void MainWindow::reencryptPath(const QString &dir) {
4 ✔
2264
  QDir checkDir(dir);
4 ✔
2265
  if (!checkDir.exists()) {
4 ✔
2266
    PlainMessageBox::critical(this, tr("Error"),
2 ✔
2267
                              tr("Directory does not exist: %1").arg(dir));
2 ✔
2268
    return;
1 ✔
2269
  }
2270
  if (refuseLinkedFolder(dir)) {
3 ✔
2271
    return;
2272
  }
2273

2274
  const bool yes = PlainMessageBox::askYes(
3 ✔
2275
      this, tr("Re-encrypt passwords"),
3 ✔
2276
      tr("Re-encrypt all passwords in %1?\n\n"
3 ✔
2277
         "This will re-encrypt ALL password files in this folder "
2278
         "using the current recipients defined in .gpg-id.\n\n"
2279
         "This may rewrite many files and cannot be undone easily.\n\n"
2280
         "Continue?")
2281
          // On one line: a name with line feeds pushed the warning out of
2282
          // the box, which shows 40 lines at most.
2283
          .arg(Util::displayable(QDir(dir).dirName(), false)));
6 ✔
2284

2285
  if (!yes)
3 ✔
2286
    return;
2287

2288
  // Disable now; the asynchronous startReencryptPath signal re-runs this
2289
  // harmlessly.
2290
  startReencryptPath();
1 ✔
2291

2292
  // Under the current profile's settings: with the pass backend active, the
2293
  // native one is not re-initialised on a profile switch.
2294
  QtPassSettings::getImitatePass()->reencryptPath(
2 ✔
2295
      QDir::cleanPath(QDir(dir).absolutePath()), QtPassSettings::load());
2 ✔
2296
}
4 ✔
2297

2298
// Idempotent: reencryptPath() calls it before ImitatePass emits the signal.
2299
void MainWindow::startReencryptPath() {
7 ✔
2300
  m_reencryptRunning = true;
7 ✔
2301
  setUiElementsEnabled(false);
7 ✔
2302
  // The worker always ends with endReencryptPath(), and Cancel is available
2303
  // throughout, so the generic watchdog is not needed for this operation.
2304
  m_uiWatchdog.stop();
7 ✔
2305
  ui->treeView->setDisabled(true);
7 ✔
2306
  if (m_reencryptProgress)
7 ✔
2307
    return;
2308
  auto *progress = new QProgressDialog(tr("Re-encrypting passwords..."),
5 ✔
2309
                                       tr("Cancel"), 0, 0, this);
10 ✔
2310
  progress->setWindowTitle(tr("Re-encrypt passwords"));
5 ✔
2311
  progress->setWindowModality(Qt::WindowModal);
5 ✔
2312
  progress->setAutoClose(false);
5 ✔
2313
  progress->setAutoReset(false);
5 ✔
2314
  progress->setMinimumDuration(0);
5 ✔
2315
  connect(progress, &QProgressDialog::canceled, this, [this]() {
5 ✔
2316
    QtPassSettings::getImitatePass()->cancelReencryptPath();
1 ✔
2317
    showStatusMessage(tr("Cancelling re-encryption"), 5000);
1 ✔
2318
  });
1 ✔
2319
  m_reencryptProgress = progress;
2320
  progress->show();
5 ✔
2321
}
2322

2323
void MainWindow::reencryptProgress(int current, int total) {
7 ✔
2324
  if (!m_reencryptProgress || m_inProgressUpdate)
7 ✔
2325
    return;
2326
  QProgressDialog *progress = m_reencryptProgress;
2327
  progress->setMaximum(total);
6 ✔
2328
  progress->setLabelText(
6 ✔
2329
      tr("Re-encrypting passwords: %1 of %2").arg(current).arg(total));
6 ✔
2330
  // On a modal dialog setValue() runs processEvents(), which can deliver
2331
  // endReencryptPath(), even inside a nested event loop that would delete a
2332
  // deleteLater()ed dialog under setValue()'s feet: keep this last, and
2333
  // delete the dialog only after it returns.
2334
  m_inProgressUpdate = true;
6 ✔
2335
  progress->setValue(current);
6 ✔
2336
  m_inProgressUpdate = false;
6 ✔
2337
  if (m_progressToDelete) {
6 ✔
2338
    m_progressToDelete->deleteLater();
2 ✔
2339
    m_progressToDelete = nullptr;
2340
  }
2341
}
2342

2343
void MainWindow::endReencryptPath() {
5 ✔
2344
  m_reencryptRunning = false;
5 ✔
2345
  if (m_reencryptProgress) {
5 ✔
2346
    m_reencryptProgress->hide();
5 ✔
2347
    if (m_inProgressUpdate) {
5 ✔
2348
      m_progressToDelete = m_reencryptProgress;
2349
    } else {
2350
      m_reencryptProgress->deleteLater();
3 ✔
2351
    }
2352
    m_reencryptProgress = nullptr;
2353
  }
2354
  setUiElementsEnabled(true);
5 ✔
2355
}
5 ✔
2356

2357
void MainWindow::askReencryptUnexpected(const QString &dir,
×
2358
                                        const QStringList &files,
2359
                                        const QStringList &details) {
2360
  const AppSettings s = QtPassSettings::load();
×
2361
  const QDir store(s.passStore);
×
2362
  // Sorted by name, so each folder's entries stand together; who would gain
2363
  // each one beside it, as the names alone are the writer's choosing.
2364
  QList<std::pair<QString, QString>> rows;
×
2365
  for (qsizetype i = 0; i < files.size(); ++i) {
×
2366
    rows.append({Util::displayable(store.relativeFilePath(files.at(i)), false),
×
2367
                 details.value(i)});
×
2368
  }
2369
  std::sort(rows.begin(), rows.end());
×
2370
  constexpr int kListed = 15;
2371
  QStringList lines;
×
2372
  for (qsizetype i = 0; i < rows.size() && i < kListed; ++i) {
×
2373
    lines << rows.at(i).first + QStringLiteral(": ") + rows.at(i).second;
×
2374
  }
2375
  if (rows.size() > kListed) {
×
2376
    lines << tr("... and %n more", nullptr,
×
2377
                static_cast<int>(rows.size() - kListed));
×
2378
  }
2379
  const int n = static_cast<int>(files.size());
×
2380
  const bool yes = PlainMessageBox::askYes(
×
2381
      this, tr("Re-encrypt these too?"),
×
2382
      tr("%n entry(s) here would become readable by people on this "
×
2383
         "folder's list who cannot read them now, and whom you did not just "
2384
         "add, so they were left as they are. Someone who can read this "
2385
         "folder may have copied them in from a folder they cannot read.",
2386
         nullptr, n) +
×
2387
          QStringLiteral("\n\n") + lines.join(QLatin1Char('\n')) +
×
2388
          QStringLiteral("\n\n") +
×
2389
          tr("Re-encrypt them for this folder's recipients? If not, they "
×
2390
             "stay readable only by whoever they are encrypted to now."));
×
2391
  if (!yes) {
×
2392
    return;
2393
  }
2394
  startReencryptPath();
×
2395
  QtPassSettings::getImitatePass()->reencryptAlso(dir, files, s);
×
2396
}
×
2397

2398
void MainWindow::exportPublicKey() {
4 ✔
2399
  const AppSettings s = QtPassSettings::load();
4 ✔
2400
  const QString identity = s.passSigningKey;
2401
  if (identity.isEmpty()) {
4 ✔
2402
    QMessageBox::information(
2 ✔
2403
        this, tr("Export public key"),
1 ✔
2404
        tr("<h3>Export your public key</h3>"
×
2405
           "<p>No signing key is configured. Set one in QtPass Settings "
2406
           "&gt; GPG keys, or run this in a terminal:</p>"
2407
           "<pre>gpg --armor --export --output my_key.asc &lt;your-key-id"
2408
           "&gt;</pre>"
2409
           "<p>Then send the file to your teammates.</p>"));
2410
    return;
1 ✔
2411
  }
2412
  QString gpgExe = s.gpgExecutable;
2413
  if (gpgExe.isEmpty()) {
3 ✔
2414
    gpgExe = QStringLiteral("gpg");
×
2415
  }
2416
  const QStringList keys = identity.split(' ', Qt::SkipEmptyParts);
3 ✔
2417
  // gpg --export takes every key block that holds the ID: another key that
2418
  // holds yours as a subkey would go out to your teammates as yours.
2419
  if (Pass *pass = QtPassSettings::getPass(); pass != nullptr) {
3 ✔
2420
    if (const std::optional<QHash<QString, QStringList>> held =
2421
            pass->keyLinesHeldTwice(keys);
3 ✔
2422
        !held || !held->isEmpty()) {
3 ✔
2423
      PlainMessageBox::warning(
1 ✔
2424
          this, tr("Export public key"),
1 ✔
2425
          tr("Your key cannot be exported on its own:\n\n%1")
1 ✔
2426
              .arg(Pass::describeKeyLinesHeldTwice(held)));
2 ✔
2427
      return;
2428
    }
2429
  }
2430
  QString stdOut;
2 ✔
2431
  QString stdErr;
2 ✔
2432
  // In the store's environment, the keyring the check above read.
2433
  Pass *pass = QtPassSettings::getPass();
2 ✔
2434
  int exitCode =
2435
      pass != nullptr
2436
          ? pass->exportPublicKeys(gpgExe, keys, &stdOut, &stdErr)
2 ✔
2437
          : Executor::executeBlocking(gpgExe,
×
2438
                                      QStringList{QStringLiteral("--armor"),
×
2439
                                                  QStringLiteral("--export")} +
2 ✔
2440
                                          keys,
×
2441
                                      &stdOut, &stdErr);
2442
  if (exitCode != 0 || stdOut.isEmpty()) {
2 ✔
2443
    PlainMessageBox::warning(this, tr("Export public key"),
2 ✔
2444
                             tr("Could not export public key for %1.\n\n%2")
1 ✔
2445
                                 .arg(identity, stdErr.isEmpty()
2 ✔
2446
                                                    ? tr("No output from gpg.")
2 ✔
2447
                                                    : stdErr));
2448
    return;
2449
  }
2450
  ExportPublicKeyDialog dialog(identity, stdOut, this);
1 ✔
2451
  dialog.exec();
1 ✔
2452
}
5 ✔
2453

2454
// UsersDialog only ticks keys already in the keyring; importing a foreign
2455
// key still has to happen via gpg (or QtPass settings) first.
2456
void MainWindow::addRecipient(const QString &dir) {
2 ✔
2457
  if (refuseLinkedFolder(dir)) {
2 ✔
2458
    return;
1 ✔
2459
  }
2460
  UsersDialog d(QtPassSettings::getPass(), QtPassSettings::load(), dir, this);
1 ✔
2461
  d.exec();
1 ✔
2462
}
1 ✔
2463

2464
// A tree-picked folder that is, or lies behind, a symlink or junction is not
2465
// a folder of the store. The store root itself may be a link (a synced
2466
// folder); that is configuration, not a tree pick.
2467
auto MainWindow::refuseLinkedFolder(const QString &dir) -> bool {
22 ✔
2468
  if (!Util::isUnderLink(dir, QtPassSettings::load().passStore)) {
22 ✔
2469
    return false;
2470
  }
2471
  PlainMessageBox::critical(
4 ✔
2472
      this, tr("Not a folder of the store"),
4 ✔
2473
      tr("%1 is, or lies behind, a symbolic link or junction. What that "
4 ✔
2474
         "points to is not part of the password store and is left alone.")
2475
          .arg(QDir::toNativeSeparators(QDir::cleanPath(dir))));
8 ✔
2476
  return true;
4 ✔
2477
}
2478

2479
void MainWindow::showShareHelp() {
1 ✔
2480
  QMessageBox::information(
2 ✔
2481
      this, tr("Sharing passwords with GPG"),
1 ✔
2482
      tr("<h3>Sharing passwords with GPG</h3>"
1 ✔
2483
         "<p>To share passwords with other users:</p>"
2484
         "<ol>"
2485
         "<li><b>Export your public key</b> and send it to teammates</li>"
2486
         "<li><b>Import teammates' public keys</b> into your GPG keyring</li>"
2487
         "<li><b>Re-encrypt passwords</b> so all recipients can decrypt "
2488
         "them</li>"
2489
         "</ol>"
2490
         "<p>Only people who have a matching secret key can decrypt the "
2491
         "passwords.</p>"
2492
         "<p><b>Tip:</b> Use the same GPG key for all shared folders.</p>"
2493
         "<p>See the FAQ for more details.</p>"));
2494
}
1 ✔
2495

2496
void MainWindow::updateGitButtonVisibility(bool uiEnabled) {
479 ✔
2497
  const AppSettings s = QtPassSettings::loadEffective();
479 ✔
2498
  // Without Git there is nothing to push or pull, ever: the buttons go, not
2499
  // grey out. While an operation runs they stay and are disabled.
2500
  const bool usable =
2501
      s.useGit && !(s.gitExecutable.isEmpty() && s.passExecutable.isEmpty());
479 ✔
2502
  ui->actionPush->setVisible(usable);
479 ✔
2503
  ui->actionUpdate->setVisible(usable);
479 ✔
2504
  // The separator in front of them would otherwise sit next to the next one.
2505
  const QList<QAction *> actions = ui->toolBar->actions();
479 ✔
2506
  const qsizetype at = actions.indexOf(ui->actionPush);
479 ✔
2507
  if (at > 0 && actions.at(at - 1)->isSeparator()) {
479 ✔
2508
    actions.at(at - 1)->setVisible(usable);
479 ✔
2509
  }
2510
  enableGitButtons(usable && uiEnabled);
479 ✔
2511
}
479 ✔
2512

2513
void MainWindow::updateOtpButtonVisibility(bool uiEnabled) {
489 ✔
2514
  // No platform gating: codes are generated in-process. Visible but disabled
2515
  // when OTP is off: the panel never shows an OTP field (a secret), so hiding
2516
  // this too would leave no trace of the feature. Honour uiEnabled, or the
2517
  // user can stack Show calls while a decrypt is in flight.
2518
  ui->actionOtp->setVisible(true);
489 ✔
2519
  ui->actionOtp->setEnabled(QtPassSettings::isUseOtp() && uiEnabled);
597 ✔
2520
}
489 ✔
2521

2522
void MainWindow::updateGrepButtonVisibility() {
208 ✔
2523
  const bool enabled = QtPassSettings::isUseGrepSearch();
208 ✔
2524
  ui->grepButton->setVisible(enabled);
208 ✔
2525
  ui->grepCaseButton->setVisible(enabled);
208 ✔
2526
  if (!enabled && m_grep.inGrepMode()) {
208 ✔
2527
    ui->grepButton->setChecked(false);
1 ✔
2528
  }
2529
}
208 ✔
2530

2531
void MainWindow::enableGitButtons(const bool &state) {
479 ✔
2532
  ui->actionPush->setEnabled(state);
479 ✔
2533
  ui->actionUpdate->setEnabled(state);
479 ✔
2534
}
479 ✔
2535

2536
void MainWindow::critical(const QString &title, const QString &msg) {
4 ✔
2537
  // Pass's messages quote store paths; see PlainMessageBox.
2538
  PlainMessageBox::critical(this, title, msg);
4 ✔
2539
}
4 ✔
2540

2541
void MainWindow::onProcessOutput(const QString &output, bool isError,
7 ✔
2542
                                 Enums::PROCESS pid) {
2543
  if (!QtPassSettings::isShowProcessOutput()) {
7 ✔
2544
    return;
2545
  }
2546
  m_processOutput->append(output, isError,
6 ✔
2547
                          ProcessOutputPanel::processName(pid));
12 ✔
2548
}
2549

2550
void MainWindow::updateProcessOutputVisibility() {
4 ✔
2551
  // The action's toggled handler shows or hides the dock.
2552
  ui->actionShowProcessOutput->setChecked(
4 ✔
2553
      QtPassSettings::isShowProcessOutput());
4 ✔
2554
  m_processOutput->setVisible(QtPassSettings::isShowProcessOutput());
4 ✔
2555
}
4 ✔
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