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

IJHack / QtPass / 46622089878

01 Dec 2026 09:59AM UTC coverage: 94.512% (+0.004%) from 94.508%
46622089878

Pull #2432

github

web-flow
Merge ef558cc58 into 11c8c2071
Pull Request #2432: Close a tree menu once another entry is current

38 of 39 new or added lines in 1 file covered. (97.44%)

50 existing lines in 1 file now uncovered.

11436 of 12100 relevant lines covered (94.51%)

23928.22 hits per line

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

95.59
/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 ✔
UNCOV
85
             : label;
×
86
}
87

88
MainWindow::MainWindow(const QString &searchText, QWidget *parent)
205 ✔
89
    : QMainWindow(parent), ui(new Ui::MainWindow) {
205 ✔
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);
205 ✔
96

97
  m_qtPass = new QtPass(this);
205 ✔
98
  restoreWindow();
205 ✔
99
  connectBackends();
205 ✔
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);
205 ✔
106
  for (const QKeySequence &keys : copyKeys) {
615 ✔
107
    new QShortcut(keys, this, this, &MainWindow::copySelectionOrPassword);
410 ✔
108
  }
109

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

118
  initTextBrowser();
205 ✔
119

120
  updateProfileBox();
205 ✔
121

122
  initDisplayPanel();
205 ✔
123

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

126
  // Install the search-box key filter once, not on every setUiElementsEnabled
127
  // call.
128
  ui->lineEdit->installEventFilter(this);
205 ✔
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);
205 ✔
132
  menuBar()->installEventFilter(this);
205 ✔
133

134
  initTimers();
205 ✔
135

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

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

143
  setUiElementsEnabled(true);
205 ✔
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();
205 ✔
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())) {
206 ✔
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);
204 ✔
159
  m_freshStart = false;
204 ✔
160
  m_initSucceeded = true;
204 ✔
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()) {
204 ✔
168
    QTimer::singleShot(0, this,
UNCOV
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).
UNCOV
175
}
×
176

177
void MainWindow::connectBackends() {
205 ✔
178
  connect(m_qtPass, &QtPass::outputReady, this,
205 ✔
179
          [this](const QString &html) { flashText(html, false, true); });
250 ✔
180
  connect(m_qtPass, &QtPass::operationFinished, this,
205 ✔
181
          [this]() { setUiElementsEnabled(true); });
275 ✔
182
  connect(m_qtPass, &QtPass::statusMessage, this,
205 ✔
183
          &MainWindow::showStatusMessage);
205 ✔
184
  connect(m_qtPass, &QtPass::pushRequested, this, &MainWindow::onAutoPush);
205 ✔
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]() {
205 ✔
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,
205 ✔
212
          [this](const QString &message) { showStatusMessage(message); });
228 ✔
213
  // Both backends: the active one can change through the configuration
214
  // dialog without a restart.
215
  connectPassSignals(QtPassSettings::getRealPass());
205 ✔
216
  connectPassSignals(QtPassSettings::getImitatePass());
205 ✔
217
  ImitatePass *ipass = QtPassSettings::getImitatePass();
205 ✔
218
  connect(ipass, &ImitatePass::startReencryptPath, this,
205 ✔
219
          &MainWindow::startReencryptPath);
205 ✔
220
  connect(ipass, &ImitatePass::reencryptProgress, this,
205 ✔
221
          &MainWindow::reencryptProgress);
205 ✔
222
  connect(ipass, &ImitatePass::endReencryptPath, this,
205 ✔
223
          &MainWindow::endReencryptPath);
205 ✔
224
  connect(ipass, &ImitatePass::unexpectedRecipients, this,
205 ✔
225
          &MainWindow::askReencryptUnexpected);
205 ✔
226
}
205 ✔
227

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

248
void MainWindow::initDisplayPanel() {
205 ✔
249
  m_displayPanel = new PasswordDisplayPanel(
205 ✔
250
      ui->gridLayout, ui->verticalLayoutPassword, this, this);
205 ✔
251
  connect(m_displayPanel, &PasswordDisplayPanel::copyRequested,
205 ✔
252
          &m_qtPass->clipboard(), &ClipboardManager::copyText);
205 ✔
253
  connect(m_displayPanel, &PasswordDisplayPanel::textCopied,
205 ✔
254
          &m_qtPass->clipboard(), &ClipboardManager::trackCopied);
205 ✔
255
  connect(ui->textBrowser, &SecretTextBrowser::copied, &m_qtPass->clipboard(),
205 ✔
256
          &ClipboardManager::trackCopied);
205 ✔
257
  connect(m_displayPanel, &PasswordDisplayPanel::qrRequested, m_qtPass,
205 ✔
258
          &QtPass::showTextAsQRCode);
205 ✔
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] {
205 ✔
263
    if (ui->actionEdit->isEnabled() && !m_panelEntry.isEmpty()) {
4 ✔
264
      editPassword(m_panelEntry);
3 ✔
265
    }
266
  });
4 ✔
267
}
205 ✔
268

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

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

280
  connect(&searchTimer, &QTimer::timeout, this, &MainWindow::onTimeoutSearch);
205 ✔
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);
205 ✔
285
  m_uiWatchdog.setInterval(UiWatchdogMs);
205 ✔
286
  connect(&m_uiWatchdog, &QTimer::timeout, this, [this]() {
205 ✔
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
}
205 ✔
303

304
void MainWindow::initProcessOutput() {
205 ✔
305
  m_processOutput = new ProcessOutputPanel(this);
205 ✔
306
  addDockWidget(Qt::BottomDockWidgetArea, m_processOutput);
205 ✔
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());
205 ✔
310
  // From the setting, not isVisible(): the window is not shown yet, so no
311
  // child of it reports visible.
312
  ui->actionShowProcessOutput->setChecked(
205 ✔
313
      QtPassSettings::isShowProcessOutput());
205 ✔
314
  connect(ui->actionShowProcessOutput, &QAction::toggled, this,
205 ✔
315
          [this](bool show) {
205 ✔
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,
205 ✔
325
          [this](const QString &out, const QString &err, Enums::PROCESS pid) {
205 ✔
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
}
205 ✔
343

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

351
// The signals of one backend that the window answers itself.
352
void MainWindow::connectPassSignals(Pass *pass) {
410 ✔
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);
410 ✔
356
  connect(pass, &Pass::critical, this, &MainWindow::critical);
410 ✔
357
  connect(pass, &Pass::startingExecuteWrapper, this,
410 ✔
358
          &MainWindow::executeWrapperStarted);
410 ✔
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);
410 ✔
362
  // The button names what it stops, also once the queue moved on.
363
  connect(pass, &Pass::startingExecuteWrapper, this, [this, pass]() {
410 ✔
364
    if (m_stopButton != nullptr && !m_stopButton->isHidden()) {
76 ✔
365
      m_stopButton->setToolTip(tr("Stop %1, which is still running")
4 ✔
366
                                   .arg(runLabel(pass->runningProcess())));
6 ✔
367
    }
368
  });
76 ✔
369
  // Nothing left to stop.
370
  connect(pass, &Pass::idle, this, [this]() {
410 ✔
371
    if (m_stopButton != nullptr) {
50 ✔
372
      m_stopButton->hide();
50 ✔
373
    }
374
  });
50 ✔
375
  connect(pass, &Pass::statusMsg, this, &MainWindow::showStatusMessage);
410 ✔
376
  connect(pass, &Pass::finishedShow, this, &MainWindow::passShowHandler);
410 ✔
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);
410 ✔
380
  connect(pass, &Pass::finishedShow, this,
410 ✔
381
          &MainWindow::passwordFromFileToClipboard);
410 ✔
382
  connect(pass, &Pass::finishedGrep, this, &MainWindow::onGrepFinished);
410 ✔
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]() {
410 ✔
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
}
410 ✔
402

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

409
void MainWindow::focusInput() {
80 ✔
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()) {
80 ✔
415
    return;
416
  }
417
  auto *lineEdit = findChild<QLineEdit *>(QStringLiteral("lineEdit"));
80 ✔
418
  if (lineEdit == nullptr || !lineEdit->isVisible()) {
80 ✔
419
    return;
420
  }
421
  lineEdit->selectAll();
80 ✔
422
  lineEdit->setFocus();
80 ✔
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;
80 ✔
426
}
427

428
auto MainWindow::event(QEvent *event) -> bool {
9,491 ✔
429
  if (event->type() == QEvent::ApplicationPaletteChange) {
9,491 ✔
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,491 ✔
436
}
437

438
void MainWindow::changeEvent(QEvent *event) {
273 ✔
439
  QWidget::changeEvent(event);
273 ✔
440
  if (event->type() == QEvent::PaletteChange && m_displayPanel != nullptr) {
273 ✔
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() &&
273 ✔
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,
46 ✔
451
                              Qt::QueuedConnection);
452
  }
453
}
273 ✔
454

455
void MainWindow::showEvent(QShowEvent *event) {
48 ✔
456
  QMainWindow::showEvent(event);
48 ✔
457
  if (m_firstShowCompleted) {
48 ✔
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,
46 ✔
464
                            Qt::QueuedConnection);
465
}
466

467
void MainWindow::initToolBarButtons() {
205 ✔
468
  connect(ui->actionAddPassword, &QAction::triggered, this,
205 ✔
469
          &MainWindow::addPassword);
205 ✔
470
  connect(ui->actionAddFolder, &QAction::triggered, this,
205 ✔
471
          &MainWindow::addFolder);
205 ✔
472
  connect(ui->actionEdit, &QAction::triggered, this, &MainWindow::onEdit);
205 ✔
473
  connect(ui->actionDelete, &QAction::triggered, this, &MainWindow::onDelete);
205 ✔
474
  connect(ui->actionPush, &QAction::triggered, this, &MainWindow::onPush);
205 ✔
475
  connect(ui->actionUpdate, &QAction::triggered, this, &MainWindow::onUpdate);
205 ✔
476
  connect(ui->actionUsers, &QAction::triggered, this, &MainWindow::onUsers);
205 ✔
477
  connect(ui->actionConfig, &QAction::triggered, this, &MainWindow::onConfig);
205 ✔
478
  connect(ui->actionOtp, &QAction::triggered, this, &MainWindow::onOtp);
205 ✔
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);
205 ✔
484
  connect(ui->actionClose, &QAction::triggered, this, &MainWindow::close);
205 ✔
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);
205 ✔
492
  ui->actionShowMenuBar->setChecked(QtPassSettings::load().showMenuBar);
205 ✔
493
  menuBar()->setVisible(ui->actionShowMenuBar->isChecked());
205 ✔
494
  connect(ui->actionShowMenuBar, &QAction::toggled, this, [this](bool show) {
205 ✔
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);
205 ✔
501
#endif
502
  connect(ui->actionFaq, &QAction::triggered, this, [] {
206 ✔
503
    QDesktopServices::openUrl(QUrl(QStringLiteral("https://qtpass.org/faq")));
2 ✔
504
  });
1 ✔
505
  connect(ui->actionAbout, &QAction::triggered, this, &MainWindow::showAbout);
205 ✔
506
  connect(ui->actionAboutQt, &QAction::triggered, qApp, &QApplication::aboutQt);
205 ✔
507

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

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

529
  QPixmap logo = QPixmap::fromImage(QImage(":/artwork/icon.svg"))
410 ✔
530
                     .scaledToHeight(statusBar()->height());
205 ✔
531
  auto *logoApp = new QLabel(statusBar());
205 ✔
532
  logoApp->setPixmap(logo);
205 ✔
533
  m_stopButton = new QPushButton(tr("Stop"), statusBar());
410 ✔
534
  m_stopButton->setObjectName(QStringLiteral("stopButton"));
410 ✔
535
  m_stopButton->setToolTip(
205 ✔
536
      tr("Stop the gpg, git or pass run that is still going"));
205 ✔
537
  m_stopButton->hide();
205 ✔
538
  connect(m_stopButton, &QPushButton::clicked, this, [this]() {
205 ✔
539
    Pass *pass = QtPassSettings::getPass();
6 ✔
540
    if (pass == nullptr || pass->isIdle()) {
6 ✔
UNCOV
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);
205 ✔
576
  statusBar()->addPermanentWidget(logoApp);
205 ✔
577
}
205 ✔
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,
302 ✔
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();
302 ✔
590
  cursor.clearSelection();
302 ✔
591
  ui->textBrowser->setTextCursor(cursor);
302 ✔
592
  QTextCharFormat format;
302 ✔
593
  if (isError) {
302 ✔
594
    format.setForeground(QColor(Qt::red));
11 ✔
595
  }
596
  ui->textBrowser->setCurrentCharFormat(format);
302 ✔
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);
302 ✔
603
  if (isHtml) {
302 ✔
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;
283 ✔
609
    if (!ui->textBrowser->toPlainText().isEmpty()) {
566 ✔
610
      older = ui->textBrowser->document()->characterCount() - 1;
223 ✔
611
      _text = ui->textBrowser->toHtml() + _text;
446 ✔
612
    }
613
    ui->textBrowser->setHtml(_text);
283 ✔
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();
283 ✔
619
    int cut = qMin(doc->characterCount() - kMaxFlashCharacters, older);
283 ✔
620
    if (cut > 0) {
283 ✔
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())) {
604 ✔
635
    ui->textBrowser->setWordWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
296 ✔
636
  }
637
}
302 ✔
638

639
void MainWindow::applyTextBrowserSettings() {
5 ✔
640
  const AppSettings s = QtPassSettings::load();
5 ✔
641
  if (s.useMonospace) {
5 ✔
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());
4 ✔
647
  }
648

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

656
void MainWindow::applyWindowFlagsSettings() {
221 ✔
657
  const bool wantOnTop = QtPassSettings::isAlwaysOnTop();
221 ✔
658
  const Qt::WindowFlags flags = windowFlags();
659
  if (flags.testFlag(Qt::WindowStaysOnTopHint) == wantOnTop) {
221 ✔
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 {
8 ✔
676
  if (m_freshStart) {
8 ✔
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);
6 ✔
685
    d.setModal(true);
6 ✔
686
    if (d.exec() != QDialog::Accepted) {
6 ✔
687
      return false;
688
    }
689
  }
6 ✔
690

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

694
  updateProfileBox();
5 ✔
695
  const AppSettings s = QtPassSettings::load();
5 ✔
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;
5 ✔
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();
5 ✔
704
  if (m_grep.cancelSearch()) {
705
    QApplication::restoreOverrideCursor();
1 ✔
706
  }
707
  clearPanel(false);
5 ✔
708
  m_tree->setStore(s.passStore);
5 ✔
709
  deselect();
5 ✔
710
  ui->treeView->setCurrentIndex(QModelIndex());
5 ✔
711

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

719
  updateGitButtonVisibility();
5 ✔
720
  updateOtpButtonVisibility();
5 ✔
721
  updateGrepButtonVisibility();
5 ✔
722
  updateProcessOutputVisibility();
5 ✔
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);
5 ✔
726
#endif
727
  if (s.useTrayIcon && m_tray == nullptr) {
5 ✔
728
    initTrayIcon();
1 ✔
729
  } else if (!s.useTrayIcon && m_tray != nullptr) {
4 ✔
UNCOV
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)) {
5 ✔
737
    m_freshStart = false;
5 ✔
738
  }
739
  return true;
740
}
5 ✔
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 {
68 ✔
766
  return m_tree->fileFor(index, forPass);
68 ✔
767
}
768

769
void MainWindow::on_treeView_clicked(const QModelIndex &index) {
27 ✔
770
  bool cleared = ui->treeView->currentIndex().flags() == Qt::NoItemFlags;
27 ✔
771
  QString file = getFile(index, true);
27 ✔
772
  ui->passwordName->setText(Util::shownName(file));
54 ✔
773
  if (!file.isEmpty() && !cleared) {
27 ✔
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;
26 ✔
777
    QtPassSettings::getPass()->Show(file);
52 ✔
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
}
27 ✔
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() {
21 ✔
795
  m_shownFile.clear();
21 ✔
796
  cancelOtpRequest();
21 ✔
797
  m_qtPass->clipboard().clear();
21 ✔
798
  ui->treeView->clearSelection();
21 ✔
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());
21 ✔
803
  ui->actionEdit->setEnabled(false);
21 ✔
804
  ui->actionDelete->setEnabled(false);
21 ✔
805
  ui->passwordName->setText("");
21 ✔
806
  clearPanel(false);
21 ✔
807
}
21 ✔
808

809
void MainWindow::executeWrapperStarted() {
78 ✔
810
  m_displayPanel->clear();
78 ✔
811
  m_panelEntry.clear();
78 ✔
812
  ui->textBrowser->clear();
78 ✔
813
  setUiElementsEnabled(false);
78 ✔
814
  clearPanelTimer.stop();
78 ✔
815
  if (QtPassSettings::isShowProcessOutput()) {
78 ✔
816
    m_processOutput->setVisible(true);
73 ✔
817
  }
818
}
78 ✔
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) {
67 ✔
937
  clearShownEntry(notify);
67 ✔
938
  clearContentResults();
67 ✔
939
}
67 ✔
940

941
void MainWindow::clearShownEntry(bool notify) {
69 ✔
942
  m_displayPanel->clear();
69 ✔
943
  m_panelEntry.clear();
69 ✔
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();
69 ✔
947
  if (notify) {
69 ✔
948
    QString output = "***" + tr("Password and content hidden") + "***";
4 ✔
949
    ui->textBrowser->setHtml(output);
2 ✔
950
  } else {
951
    ui->textBrowser->setHtml("");
134 ✔
952
  }
953
}
69 ✔
954

955
void MainWindow::clearContentResults() {
70 ✔
956
  clearResultsTimer.stop();
70 ✔
957
  const bool grepWasVisible = ui->grepResultsList->isVisible();
70 ✔
958
  ui->grepResultsList->clear();
70 ✔
959
  if (grepWasVisible) {
70 ✔
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
}
70 ✔
978

979
void MainWindow::setUiElementsEnabled(bool state) {
475 ✔
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) {
475 ✔
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();
102 ✔
992
  }
993
  ui->treeView->setEnabled(state);
474 ✔
994
  ui->lineEdit->setEnabled(state);
474 ✔
995
  ui->actionAddPassword->setEnabled(state);
474 ✔
996
  ui->actionAddFolder->setEnabled(state);
474 ✔
997
  ui->actionUsers->setEnabled(state);
474 ✔
998
  ui->actionConfig->setEnabled(state);
474 ✔
999
  m_uiEnabled = state;
474 ✔
1000
  updateProfileBoxEnabled();
474 ✔
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();
951 ✔
1004
  ui->actionDelete->setEnabled(state);
474 ✔
1005
  ui->actionEdit->setEnabled(state);
474 ✔
1006
  updateGitButtonVisibility(uiEnabled);
474 ✔
1007
  // `state` is now "UI enabled AND a file is selected", which is exactly when
1008
  // generating an OTP makes sense.
1009
  updateOtpButtonVisibility(state);
474 ✔
1010
}
1011

1012
void MainWindow::restoreWindow() {
216 ✔
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();
432 ✔
1016
  if (geometry.isEmpty() || !restoreGeometry(geometry)) {
216 ✔
1017
    WindowStateStore::centreOnCursorScreen(*this);
4 ✔
1018
  }
1019
  restoreState(QtPassSettings::getSavestate(saveState()));
216 ✔
1020
  const AppSettings s = QtPassSettings::load();
216 ✔
1021

1022
  applyWindowFlagsSettings();
216 ✔
1023

1024
  if (s.useTrayIcon && m_tray == nullptr) {
216 ✔
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
UNCOV
1030
      QTimer::singleShot(10, this, &MainWindow::hide);
×
1031
    }
1032
  } else if (!s.useTrayIcon && m_tray != nullptr) {
214 ✔
UNCOV
1033
    destroyTrayIcon();
×
1034
  }
1035
}
432 ✔
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) {
50 ✔
1076
  if (m_grep.inGrepMode())
50 ✔
1077
    return;
1078
  ui->statusBar->showMessage(tr("Looking for: %1").arg(arg1), 1000);
74 ✔
1079
  ui->treeView->expandAll();
37 ✔
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();
37 ✔
1084
  cancelOtpRequest();
37 ✔
1085
  clearPanel(false);
37 ✔
1086
  ui->passwordName->setText("");
74 ✔
1087
  ui->actionEdit->setEnabled(false);
37 ✔
1088
  ui->actionDelete->setEnabled(false);
37 ✔
1089
  searchTimer.start();
37 ✔
1090
}
1091

1092
void MainWindow::onTimeoutSearch() {
41 ✔
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());
82 ✔
1096

1097
  if (query.isEmpty()) {
41 ✔
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));
41 ✔
1105

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

1114
void MainWindow::on_lineEdit_returnPressed() {
17 ✔
1115
  qCDebug(lcQtPass) << "on_lineEdit_returnPressed"
17 ✔
UNCOV
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;
UNCOV
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 ✔
UNCOV
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(
×
UNCOV
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() {
28 ✔
1331
  QtPassSettings::getRealPass()->CancelGrep();
28 ✔
1332
  QtPassSettings::getImitatePass()->CancelGrep();
28 ✔
1333
}
28 ✔
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());
16 ✔
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 {
33 ✔
1357
  const QStringList parts = QDir(store).relativeFilePath(path).split(
66 ✔
1358
      QLatin1Char('/'), Qt::SkipEmptyParts);
33 ✔
1359
  QDir dir(store);
33 ✔
1360
  bool respelled = false;
1361
  for (int i = 0; i < parts.size(); ++i) {
36 ✔
1362
    const bool leaf = i == parts.size() - 1;
36 ✔
1363
    const QStringList names =
1364
        dir.entryList((leaf ? QDir::Files : QDir::Dirs) | QDir::Hidden |
36 ✔
1365
                      QDir::NoDotAndDotDot);
39 ✔
1366
    QString name = parts.at(i);
1367
    if (!names.contains(name)) {
36 ✔
UNCOV
1368
      const auto stored = std::find_if(
×
1369
          names.cbegin(), names.cend(), [&name](const QString &candidate) {
UNCOV
1370
            return candidate.compare(name, Qt::CaseInsensitive) == 0;
×
1371
          });
UNCOV
1372
      if (stored == names.cend()) {
×
1373
        return path;
1374
      }
UNCOV
1375
      name = *stored;
×
1376
      respelled = true;
1377
    }
1378
    if (leaf) {
36 ✔
1379
      return respelled ? QDir::cleanPath(Util::joinPath(dir.path(), name))
66 ✔
UNCOV
1380
                       : path;
×
1381
    }
1382
    if (!dir.cd(name)) {
3 ✔
1383
      return path;
1384
    }
1385
  }
1386
  return path;
1387
}
33 ✔
1388
} // namespace
1389

1390
auto MainWindow::exactMatchPath() -> QString {
51 ✔
1391
  const QString text = QDir::fromNativeSeparators(ui->lineEdit->text());
102 ✔
1392
  const QString store = QtPassSettings::getPassStore();
102 ✔
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()}) {
191 ✔
1396
    if (typed.isEmpty()) {
71 ✔
UNCOV
1397
      continue;
×
1398
    }
1399
    const QString path =
1400
        QDir::cleanPath(Util::joinPath(store, typed + QStringLiteral(".gpg")));
142 ✔
1401
    if (PathValidator::isPathInStore(store, path) && QFileInfo(path).isFile()) {
71 ✔
1402
      return spelledAsStored(store, path);
33 ✔
1403
    }
1404
  }
153 ✔
1405
  return {};
18 ✔
1406
}
1407

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

1421
void MainWindow::applySearchText(const QString &text) {
9 ✔
1422
  // A name search: content search, left on, kept its results over the tree
1423
  // and ignored the text.
1424
  if (ui->grepButton->isChecked()) {
9 ✔
1425
    ui->grepButton->setChecked(false);
1 ✔
1426
  }
1427
  delete m_pendingOpen;
9 ✔
1428
  ui->lineEdit->setText(text);
9 ✔
1429
  // Filter now, not after the search delay: the timer would leave the tree
1430
  // as the previous text filtered it.
1431
  searchTimer.stop();
9 ✔
1432
  onTimeoutSearch();
9 ✔
1433
  if (const QModelIndex exact = exactMatch(); exact.isValid()) {
9 ✔
1434
    openExactMatch(exact);
5 ✔
1435
    return;
5 ✔
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()) {
8 ✔
1443
    return;
1444
  }
1445
  auto *pending = new QObject(this);
3 ✔
1446
  m_pendingOpen = pending;
1447
  QTimer::singleShot(5000, pending, &QObject::deleteLater);
3 ✔
1448
  // Disconnected at once: with deleteLater() alone, a folder that finished
1449
  // loading before the deletion still ran the open, or ran it twice.
1450
  const auto stop = [this, pending] {
2 ✔
1451
    disconnect(m_tree, nullptr, pending, nullptr);
2 ✔
1452
    disconnect(ui->lineEdit, nullptr, pending, nullptr);
2 ✔
1453
    pending->deleteLater();
2 ✔
1454
  };
5 ✔
1455
  connect(ui->lineEdit, &QLineEdit::textChanged, pending, stop);
3 ✔
1456
  connect(m_tree, &StoreTree::directoryLoaded, pending,
3 ✔
1457
          [this, stop](const QString &) {
6 ✔
1458
            searchTimer.stop();
5 ✔
1459
            onTimeoutSearch();
5 ✔
1460
            if (const QModelIndex exact = exactMatch(); exact.isValid()) {
5 ✔
1461
              stop();
1 ✔
1462
              openExactMatch(exact);
1 ✔
1463
            }
1464
          });
5 ✔
1465
}
1466

1467
void MainWindow::openExactMatch(const QModelIndex &index) {
6 ✔
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);
6 ✔
1472
  on_treeView_clicked(index);
6 ✔
1473
}
6 ✔
1474

1475
auto MainWindow::firstFile(QModelIndex parentIndex) -> QModelIndex {
23 ✔
1476
  StoreModel &proxy = m_tree->proxy();
23 ✔
1477
  int numRows = proxy.rowCount(parentIndex);
23 ✔
1478
  for (int row = 0; row < numRows; ++row) {
30 ✔
1479
    QModelIndex index = proxy.index(row, 0, parentIndex);
21 ✔
1480
    if (m_tree->fileInfo(index).isFile()) {
21 ✔
1481
      return index;
14 ✔
1482
    }
1483
    if (proxy.hasChildren(index)) {
12 ✔
1484
      QModelIndex childFile = firstFile(index);
7 ✔
1485
      if (childFile.isValid())
1486
        return childFile;
5 ✔
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 ✔
UNCOV
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) {
19 ✔
1530
      const QString rel = QDir(storePath).relativeFilePath(path);
18 ✔
1531
      if (!rel.startsWith(u'.') && !rel.contains(QStringLiteral("/."))) {
54 ✔
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 =
UNCOV
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() {
103 ✔
1652
  m_otpRequestFile.clear();
103 ✔
1653
  m_copyRequestFile.clear();
103 ✔
1654
}
103 ✔
1655

1656
void MainWindow::onOperationError() {
38 ✔
1657
  cancelOtpRequest();
38 ✔
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();
38 ✔
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();
38 ✔
1665
  m_refreshAfterPushOwner = nullptr;
1666
}
38 ✔
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);
×
UNCOV
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) {
10 ✔
1728
  show();
10 ✔
1729
  raise();
10 ✔
1730
  if (message.isEmpty()) {
10 ✔
1731
    focusInput();
1 ✔
1732
  } else {
1733
    ui->treeView->expandAll();
9 ✔
1734
    applySearchText(message);
9 ✔
1735
  }
1736
}
10 ✔
1737

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

1742
  if (profiles.isEmpty()) {
8 ✔
1743
    ui->profileWidget->hide();
206 ✔
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();
214 ✔
1771
}
214 ✔
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);
×
UNCOV
1793
    ui->profileBox->setCurrentText(QtPassSettings::getProfile());
×
1794
    return;
UNCOV
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
UNCOV
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 ✔
UNCOV
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,683 ✔
1858
  if ((obj == ui->toolBar || obj == menuBar()) &&
8,683 ✔
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,683 ✔
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,680 ✔
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) {
12 ✔
1953
  const QString dirPath = QDir::cleanPath(m_tree->currentDir(false));
12 ✔
1954
  auto *shareMenu = new QMenu(tr("Share"), &contextMenu);
12 ✔
1955
  contextMenu.addMenu(shareMenu);
12 ✔
1956

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

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

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

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

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

1982
void MainWindow::showContextMenu(const QPoint &pos) {
14 ✔
1983
  const AppSettings s = QtPassSettings::load();
14 ✔
1984
  const QModelIndex index = ui->treeView->indexAt(pos);
14 ✔
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);
14 ✔
1992
  const QPoint globalPos = ui->treeView->viewport()->mapToGlobal(pos);
14 ✔
1993
  const QFileInfo fileOrFolder = m_tree->fileInfo(ui->treeView->currentIndex());
14 ✔
1994
  const bool isDir = fileOrFolder.isDir();
14 ✔
1995

1996
  QMenu contextMenu;
14 ✔
1997
  if (!selected || isDir) {
14 ✔
1998
    const std::array<std::pair<QString, void (MainWindow::*)()>, 4> onFolder{{
1999
        {tr("Open folder with file manager"), &MainWindow::openFolder},
13 ✔
2000
        {tr("Add folder"), &MainWindow::addFolder},
13 ✔
2001
        {tr("Add password"), &MainWindow::addPassword},
13 ✔
2002
        {tr("Users"), &MainWindow::onUsers},
13 ✔
NEW
2003
    }};
×
2004
    for (const auto &[text, slot] : onFolder) {
65 ✔
2005
      connect(contextMenu.addAction(text), &QAction::triggered, this, slot);
52 ✔
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) {
14 ✔
2012
    contextMenu.addSeparator();
13 ✔
2013
    if (isDir) {
13 ✔
2014
      connect(contextMenu.addAction(tr("Rename folder")), &QAction::triggered,
12 ✔
2015
              this, &MainWindow::renameFolder);
24 ✔
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,
13 ✔
2021
            &MainWindow::onDelete);
13 ✔
2022
    if (isDir) {
13 ✔
2023
      addShareMenu(contextMenu, s);
12 ✔
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);
14 ✔
2029
  // Nor may they act on another entry. A row removed in place by the file
2030
  // system model (its own watcher, on macOS) hands the current index to a
2031
  // neighbour, and the reload after it finds that one again: Delete would
2032
  // then remove the neighbour.
2033
  const auto pathOf = [this](const QModelIndex &at) {
15 ✔
2034
    return at.isValid() ? m_tree->fileInfo(at).absoluteFilePath() : QString();
15 ✔
2035
  };
14 ✔
2036
  const QString openedOn = pathOf(ui->treeView->currentIndex());
14 ✔
2037
  connect(ui->treeView->selectionModel(), &QItemSelectionModel::currentChanged,
14 ✔
2038
          &contextMenu,
2039
          [&contextMenu, pathOf, openedOn](const QModelIndex &now) {
28 ✔
2040
            if (pathOf(now) != openedOn) {
2 ✔
2041
              contextMenu.close();
1 ✔
2042
            }
2043
          });
1 ✔
2044
  contextMenu.exec(globalPos);
14 ✔
2045
}
14 ✔
2046

2047
auto MainWindow::browserContextMenu(const QPoint &pos) -> QMenu * {
3 ✔
2048
  // createStandardContextMenu() takes document coordinates, anchorAt() and
2049
  // the menu's place viewport ones: scrolled, the menu checked the text
2050
  // above the link and left "Copy Link Location" disabled.
2051
  // Right to left, the horizontal offset counts from the other end.
2052
  const QScrollBar *across = ui->textBrowser->horizontalScrollBar();
3 ✔
2053
  const int dx = ui->textBrowser->isRightToLeft()
3 ✔
2054
                     ? across->maximum() - across->value()
3 ✔
2055
                     : across->value();
3 ✔
2056
  const QPoint documentPos =
2057
      pos + QPoint(dx, ui->textBrowser->verticalScrollBar()->value());
3 ✔
2058
  QMenu *contextMenu = ui->textBrowser->createStandardContextMenu(documentPos);
3 ✔
2059
  // Reparent from textBrowser: a browser stylesheet cascades to the child
2060
  // QMenu and breaks its opaque native background.
2061
  contextMenu->setParent(this, contextMenu->windowFlags());
3 ✔
2062
  if (auto *copyLink =
3 ✔
2063
          contextMenu->findChild<QAction *>(QStringLiteral("link-copy"))) {
3 ✔
2064
    const QString link = ui->textBrowser->anchorAt(pos);
3 ✔
2065
    disconnect(copyLink, &QAction::triggered, nullptr, nullptr);
3 ✔
2066
    connect(copyLink, &QAction::triggered, this, [this, link] {
10 ✔
2067
      if (!link.isEmpty()) {
1 ✔
2068
        m_qtPass->clipboard().copyText(link);
1 ✔
2069
      }
2070
    });
1 ✔
2071
  }
2072
  return contextMenu;
3 ✔
2073
}
2074

2075
void MainWindow::showBrowserContextMenu(const QPoint &pos) {
1 ✔
2076
  QMenu *contextMenu = browserContextMenu(pos);
1 ✔
2077
  contextMenu->exec(ui->textBrowser->viewport()->mapToGlobal(pos));
1 ✔
2078
  delete contextMenu;
1 ✔
2079
}
1 ✔
2080

2081
void MainWindow::openFolder() {
1 ✔
2082
  QString dir = m_tree->currentDir(false);
1 ✔
2083

2084
  QString path = QDir::toNativeSeparators(dir);
1 ✔
2085
  QDesktopServices::openUrl(QUrl::fromLocalFile(path));
1 ✔
2086
}
1 ✔
2087

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

2136
void MainWindow::renameFolder() {
4 ✔
2137
  bool ok;
2138
  QString srcDir = QDir::cleanPath(m_tree->currentDir(false));
4 ✔
2139
  QString srcDirName = QDir(srcDir).dirName();
4 ✔
2140
  QString newName =
2141
      QInputDialog::getText(this, tr("Rename folder"), tr("Rename folder to: "),
4 ✔
2142
                            QLineEdit::Normal, srcDirName, &ok);
8 ✔
2143
  if (!ok || newName.isEmpty()) {
4 ✔
2144
    return;
2145
  }
2146
  QString destDir = srcDir;
2147
  destDir.replace(srcDir.lastIndexOf(srcDirName), srcDirName.length(), newName);
3 ✔
2148
  if (!confirmPathInStore(destDir)) {
3 ✔
2149
    return;
2150
  }
2151
  if (!PlainMessageBox::confirmPassRun(
2 ✔
2152
          this, QtPassSettings::getPassStore(), [&srcDir, &destDir] {
4 ✔
2153
            return QtPassSettings::getPass()->entriesMoveWouldWiden(srcDir,
2 ✔
2154
                                                                    destDir);
2 ✔
2155
          })) {
2156
    return;
2157
  }
2158
  QtPassSettings::getPass()->Move(srcDir, destDir, false);
6 ✔
2159
}
2160

2161
void MainWindow::editPassword(const QString &file) {
6 ✔
2162
  if (!file.isEmpty()) {
6 ✔
2163
    const AppSettings s = QtPassSettings::loadEffective();
6 ✔
2164
    if (s.useGit && s.autoPull) {
6 ✔
2165
      onUpdate(true);
1 ✔
2166
    }
2167
    // The dialog decrypts the entry itself to fill its fields. That decrypt
2168
    // lands on the same finishedShow the panel uses, so drop the panel's claim
2169
    // to it: otherwise passShowHandler() repaints and, with "Always copy",
2170
    // puts the entry's old password on the clipboard - replacing whatever the
2171
    // user copied to paste into the dialog.
2172
    m_shownFile.clear();
6 ✔
2173
    setPassword(file, false);
6 ✔
2174
  }
6 ✔
2175
}
6 ✔
2176

2177
void MainWindow::renamePassword() {
2 ✔
2178
  bool ok;
2179
  QString file = getFile(ui->treeView->currentIndex(), false);
2 ✔
2180
  QString filePath = QFileInfo(file).path();
2 ✔
2181
  QString fileName = QFileInfo(file).fileName();
2 ✔
2182
  if (fileName.endsWith(".gpg", Qt::CaseInsensitive)) {
4 ✔
2183
    fileName.chop(4);
2 ✔
2184
  }
2185

2186
  QString newName =
2187
      QInputDialog::getText(this, tr("Rename file"), tr("Rename file to: "),
2 ✔
2188
                            QLineEdit::Normal, fileName, &ok);
4 ✔
2189
  if (!ok || newName.isEmpty()) {
2 ✔
2190
    return;
2191
  }
2192
  QString newFile = Util::joinPath(filePath, newName);
2 ✔
2193
  if (!confirmPathInStore(newFile)) {
2 ✔
2194
    return;
2195
  }
2196
  if (!PlainMessageBox::confirmPassRun(
1 ✔
2197
          this, QtPassSettings::getPassStore(), [&file, &newFile] {
2 ✔
2198
            return QtPassSettings::getPass()->entriesMoveWouldWiden(file,
1 ✔
2199
                                                                    newFile);
1 ✔
2200
          })) {
2201
    return;
2202
  }
2203
  QtPassSettings::getPass()->Move(file, newFile, false);
3 ✔
2204
}
2205

2206
void MainWindow::copySelectionOrPassword() {
5 ✔
2207
  QWidget *focus = QApplication::focusWidget();
5 ✔
2208
  // The widget's own copy: a SecretTextBrowser marks what it copies as
2209
  // secret for clipboard managers, as the context menu's Copy does.
2210
  if (auto *text = qobject_cast<QTextEdit *>(focus);
5 ✔
2211
      text != nullptr && text->textCursor().hasSelection()) {
5 ✔
2212
    text->copy();
1 ✔
2213
    return;
1 ✔
2214
  }
2215
  // Through the clipboard manager, as a copy button would: the label may be
2216
  // the OTP code, which gets the secret hint and the autoclear.
2217
  if (auto *label = qobject_cast<QLabel *>(focus);
2218
      label != nullptr && label->hasSelectedText()) {
4 ✔
2219
    m_qtPass->clipboard().copyText(label->selectedText());
1 ✔
2220
    return;
1 ✔
2221
  }
2222
  // A line of the content search results is decrypted text: through the
2223
  // clipboard manager too, for the secret hint and the autoclear.
2224
  if (focus == ui->grepResultsList) {
3 ✔
2225
    if (const QTreeWidgetItem *item = ui->grepResultsList->currentItem();
3 ✔
2226
        item != nullptr && !item->text(0).isEmpty()) {
6 ✔
2227
      m_qtPass->clipboard().copyText(item->text(0));
6 ✔
2228
    }
2229
    return;
3 ✔
2230
  }
UNCOV
2231
  copyPasswordFromTreeview();
×
2232
}
2233

2234
void MainWindow::copyPasswordFromTreeview() {
9 ✔
2235
  // While content search results hide the tree, its current entry is not
2236
  // what the user looks at: no decrypt, as for Edit and OTP.
2237
  if (ui->treeView->isHidden()) {
9 ✔
UNCOV
2238
    return;
×
2239
  }
2240
  QFileInfo fileOrFolder = m_tree->fileInfo(ui->treeView->currentIndex());
9 ✔
2241

2242
  if (fileOrFolder.isFile()) {
9 ✔
2243
    QString file = getFile(ui->treeView->currentIndex(), true);
9 ✔
2244
    // The newest Ctrl+C wins: finishedShow names its file, so the decrypt of
2245
    // an earlier request is simply not this one's.
2246
    m_copyRequestFile = file;
9 ✔
2247
    // This Show repaints the panel as well; see onOtp().
2248
    m_shownFile = file;
9 ✔
2249
    QtPassSettings::getPass()->Show(file);
18 ✔
2250
  }
2251
}
9 ✔
2252

2253
void MainWindow::passwordFromFileToClipboard(const QString &text,
33 ✔
2254
                                             const QString &file) {
2255
  if (m_copyRequestFile.isEmpty() || file != m_copyRequestFile) {
33 ✔
2256
    return;
28 ✔
2257
  }
2258
  m_copyRequestFile.clear();
8 ✔
2259
  // The first line, without a list of every line (an entry can expand into
2260
  // millions of them), and without the "\r" of a CRLF line end, as the
2261
  // password row and "Always copy" have it.
2262
  const QString first = FileContent::passwordLine(text);
8 ✔
2263
  // A `pass otp insert` entry's first line is the otpauth:// URI carrying the
2264
  // TOTP seed, and an OTP field holding a seed there is the same; copying it
2265
  // would leak 2FA material. Matches the display path
2266
  // (FileContent::getPasswordForDisplay / PasswordDisplayPanel).
2267
  if (FileContent::isOtpPasswordLine(first)) {
8 ✔
2268
    flashText(tr("This entry holds an OTP secret, not a password"), true);
6 ✔
2269
    return;
2270
  }
2271
  m_qtPass->clipboard().copyText(first);
5 ✔
2272
}
2273

2274
void MainWindow::showStatusMessage(const QString &msg, int timeout) {
44 ✔
2275
  ui->statusBar->showMessage(msg, timeout);
44 ✔
2276
}
44 ✔
2277

2278
void MainWindow::reencryptPath(const QString &dir) {
4 ✔
2279
  QDir checkDir(dir);
4 ✔
2280
  if (!checkDir.exists()) {
4 ✔
2281
    PlainMessageBox::critical(this, tr("Error"),
2 ✔
2282
                              tr("Directory does not exist: %1").arg(dir));
2 ✔
2283
    return;
1 ✔
2284
  }
2285
  if (refuseLinkedFolder(dir)) {
3 ✔
2286
    return;
2287
  }
2288

2289
  const bool yes = PlainMessageBox::askYes(
3 ✔
2290
      this, tr("Re-encrypt passwords"),
3 ✔
2291
      tr("Re-encrypt all passwords in %1?\n\n"
3 ✔
2292
         "This will re-encrypt ALL password files in this folder "
2293
         "using the current recipients defined in .gpg-id.\n\n"
2294
         "This may rewrite many files and cannot be undone easily.\n\n"
2295
         "Continue?")
2296
          // On one line: a name with line feeds pushed the warning out of
2297
          // the box, which shows 40 lines at most.
2298
          .arg(Util::displayable(QDir(dir).dirName(), false)));
6 ✔
2299

2300
  if (!yes)
3 ✔
2301
    return;
2302

2303
  // Disable now; the asynchronous startReencryptPath signal re-runs this
2304
  // harmlessly.
2305
  startReencryptPath();
1 ✔
2306

2307
  // Under the current profile's settings: with the pass backend active, the
2308
  // native one is not re-initialised on a profile switch.
2309
  QtPassSettings::getImitatePass()->reencryptPath(
2 ✔
2310
      QDir::cleanPath(QDir(dir).absolutePath()), QtPassSettings::load());
2 ✔
2311
}
4 ✔
2312

2313
// Idempotent: reencryptPath() calls it before ImitatePass emits the signal.
2314
void MainWindow::startReencryptPath() {
7 ✔
2315
  m_reencryptRunning = true;
7 ✔
2316
  setUiElementsEnabled(false);
7 ✔
2317
  // The worker always ends with endReencryptPath(), and Cancel is available
2318
  // throughout, so the generic watchdog is not needed for this operation.
2319
  m_uiWatchdog.stop();
7 ✔
2320
  ui->treeView->setDisabled(true);
7 ✔
2321
  if (m_reencryptProgress)
7 ✔
2322
    return;
2323
  auto *progress = new QProgressDialog(tr("Re-encrypting passwords..."),
5 ✔
2324
                                       tr("Cancel"), 0, 0, this);
10 ✔
2325
  progress->setWindowTitle(tr("Re-encrypt passwords"));
5 ✔
2326
  progress->setWindowModality(Qt::WindowModal);
5 ✔
2327
  progress->setAutoClose(false);
5 ✔
2328
  progress->setAutoReset(false);
5 ✔
2329
  progress->setMinimumDuration(0);
5 ✔
2330
  connect(progress, &QProgressDialog::canceled, this, [this]() {
5 ✔
2331
    QtPassSettings::getImitatePass()->cancelReencryptPath();
1 ✔
2332
    showStatusMessage(tr("Cancelling re-encryption"), 5000);
1 ✔
2333
  });
1 ✔
2334
  m_reencryptProgress = progress;
2335
  progress->show();
5 ✔
2336
}
2337

2338
void MainWindow::reencryptProgress(int current, int total) {
7 ✔
2339
  if (!m_reencryptProgress || m_inProgressUpdate)
7 ✔
2340
    return;
2341
  QProgressDialog *progress = m_reencryptProgress;
2342
  progress->setMaximum(total);
6 ✔
2343
  progress->setLabelText(
6 ✔
2344
      tr("Re-encrypting passwords: %1 of %2").arg(current).arg(total));
6 ✔
2345
  // On a modal dialog setValue() runs processEvents(), which can deliver
2346
  // endReencryptPath(), even inside a nested event loop that would delete a
2347
  // deleteLater()ed dialog under setValue()'s feet: keep this last, and
2348
  // delete the dialog only after it returns.
2349
  m_inProgressUpdate = true;
6 ✔
2350
  progress->setValue(current);
6 ✔
2351
  m_inProgressUpdate = false;
6 ✔
2352
  if (m_progressToDelete) {
6 ✔
2353
    m_progressToDelete->deleteLater();
2 ✔
2354
    m_progressToDelete = nullptr;
2355
  }
2356
}
2357

2358
void MainWindow::endReencryptPath() {
5 ✔
2359
  m_reencryptRunning = false;
5 ✔
2360
  if (m_reencryptProgress) {
5 ✔
2361
    m_reencryptProgress->hide();
5 ✔
2362
    if (m_inProgressUpdate) {
5 ✔
2363
      m_progressToDelete = m_reencryptProgress;
2364
    } else {
2365
      m_reencryptProgress->deleteLater();
3 ✔
2366
    }
2367
    m_reencryptProgress = nullptr;
2368
  }
2369
  setUiElementsEnabled(true);
5 ✔
2370
}
5 ✔
2371

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

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

2469
// UsersDialog only ticks keys already in the keyring; importing a foreign
2470
// key still has to happen via gpg (or QtPass settings) first.
2471
void MainWindow::addRecipient(const QString &dir) {
2 ✔
2472
  if (refuseLinkedFolder(dir)) {
2 ✔
2473
    return;
1 ✔
2474
  }
2475
  UsersDialog d(QtPassSettings::getPass(), QtPassSettings::load(), dir, this);
1 ✔
2476
  d.exec();
1 ✔
2477
}
1 ✔
2478

2479
// A tree-picked folder that is, or lies behind, a symlink or junction is not
2480
// a folder of the store. The store root itself may be a link (a synced
2481
// folder); that is configuration, not a tree pick.
2482
auto MainWindow::refuseLinkedFolder(const QString &dir) -> bool {
22 ✔
2483
  if (!Util::isUnderLink(dir, QtPassSettings::load().passStore)) {
22 ✔
2484
    return false;
2485
  }
2486
  PlainMessageBox::critical(
4 ✔
2487
      this, tr("Not a folder of the store"),
4 ✔
2488
      tr("%1 is, or lies behind, a symbolic link or junction. What that "
4 ✔
2489
         "points to is not part of the password store and is left alone.")
2490
          .arg(QDir::toNativeSeparators(QDir::cleanPath(dir))));
8 ✔
2491
  return true;
4 ✔
2492
}
2493

2494
void MainWindow::showShareHelp() {
1 ✔
2495
  QMessageBox::information(
2 ✔
2496
      this, tr("Sharing passwords with GPG"),
1 ✔
2497
      tr("<h3>Sharing passwords with GPG</h3>"
1 ✔
2498
         "<p>To share passwords with other users:</p>"
2499
         "<ol>"
2500
         "<li><b>Export your public key</b> and send it to teammates</li>"
2501
         "<li><b>Import teammates' public keys</b> into your GPG keyring</li>"
2502
         "<li><b>Re-encrypt passwords</b> so all recipients can decrypt "
2503
         "them</li>"
2504
         "</ol>"
2505
         "<p>Only people who have a matching secret key can decrypt the "
2506
         "passwords.</p>"
2507
         "<p><b>Tip:</b> Use the same GPG key for all shared folders.</p>"
2508
         "<p>See the FAQ for more details.</p>"));
2509
}
1 ✔
2510

2511
void MainWindow::updateGitButtonVisibility(bool uiEnabled) {
479 ✔
2512
  const AppSettings s = QtPassSettings::loadEffective();
479 ✔
2513
  // Without Git there is nothing to push or pull, ever: the buttons go, not
2514
  // grey out. While an operation runs they stay and are disabled.
2515
  const bool usable =
2516
      s.useGit && !(s.gitExecutable.isEmpty() && s.passExecutable.isEmpty());
479 ✔
2517
  ui->actionPush->setVisible(usable);
479 ✔
2518
  ui->actionUpdate->setVisible(usable);
479 ✔
2519
  // The separator in front of them would otherwise sit next to the next one.
2520
  const QList<QAction *> actions = ui->toolBar->actions();
479 ✔
2521
  const qsizetype at = actions.indexOf(ui->actionPush);
479 ✔
2522
  if (at > 0 && actions.at(at - 1)->isSeparator()) {
479 ✔
2523
    actions.at(at - 1)->setVisible(usable);
479 ✔
2524
  }
2525
  enableGitButtons(usable && uiEnabled);
479 ✔
2526
}
479 ✔
2527

2528
void MainWindow::updateOtpButtonVisibility(bool uiEnabled) {
489 ✔
2529
  // No platform gating: codes are generated in-process. Visible but disabled
2530
  // when OTP is off: the panel never shows an OTP field (a secret), so hiding
2531
  // this too would leave no trace of the feature. Honour uiEnabled, or the
2532
  // user can stack Show calls while a decrypt is in flight.
2533
  ui->actionOtp->setVisible(true);
489 ✔
2534
  ui->actionOtp->setEnabled(QtPassSettings::isUseOtp() && uiEnabled);
597 ✔
2535
}
489 ✔
2536

2537
void MainWindow::updateGrepButtonVisibility() {
210 ✔
2538
  const bool enabled = QtPassSettings::isUseGrepSearch();
210 ✔
2539
  ui->grepButton->setVisible(enabled);
210 ✔
2540
  ui->grepCaseButton->setVisible(enabled);
210 ✔
2541
  if (!enabled && m_grep.inGrepMode()) {
210 ✔
2542
    ui->grepButton->setChecked(false);
1 ✔
2543
  }
2544
}
210 ✔
2545

2546
void MainWindow::enableGitButtons(const bool &state) {
479 ✔
2547
  ui->actionPush->setEnabled(state);
479 ✔
2548
  ui->actionUpdate->setEnabled(state);
479 ✔
2549
}
479 ✔
2550

2551
void MainWindow::critical(const QString &title, const QString &msg) {
4 ✔
2552
  // Pass's messages quote store paths; see PlainMessageBox.
2553
  PlainMessageBox::critical(this, title, msg);
4 ✔
2554
}
4 ✔
2555

2556
void MainWindow::onProcessOutput(const QString &output, bool isError,
7 ✔
2557
                                 Enums::PROCESS pid) {
2558
  if (!QtPassSettings::isShowProcessOutput()) {
7 ✔
2559
    return;
2560
  }
2561
  m_processOutput->append(output, isError,
6 ✔
2562
                          ProcessOutputPanel::processName(pid));
12 ✔
2563
}
2564

2565
void MainWindow::updateProcessOutputVisibility() {
5 ✔
2566
  // The action's toggled handler shows or hides the dock.
2567
  ui->actionShowProcessOutput->setChecked(
5 ✔
2568
      QtPassSettings::isShowProcessOutput());
5 ✔
2569
  m_processOutput->setVisible(QtPassSettings::isShowProcessOutput());
5 ✔
2570
}
5 ✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc