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

IJHack / QtPass / 43634506205

14 Nov 2026 07:53PM UTC coverage: 96.295% (+0.04%) from 96.26%
43634506205

push

github

web-flow
Search: open the entry named exactly as typed, and filter before opening (#2170)

* Search: open the entry named exactly as typed, and filter before opening

Enter in the search box opened the first entry the filter left, folders
sorted first, so "bank" opened team/bank. selectFirstFile() now prefers
the entry named exactly as the search text (exactMatch(), through the
filter, files only), for the highlight and for Enter alike.

Enter pressed within the 350 ms search delay acted on the tree as the
previous text had filtered it. on_lineEdit_returnPressed() now runs a
pending search first.

qtpass(1) says search text from the command line, or handed to a running
QtPass, filters the tree and opens an exact match. At first start the text
was only typed in, so nothing opened; from a second instance Enter was
pressed before the filter ran, opening whatever came first. Both now go
through applySearchText(): filter at once, open only an entry named
exactly so. Right after the window is shown the tree is still loading its
folders, so when the entry exists on disk but is not in the tree yet, it
is opened as soon as its folder has loaded (for at most 5 s, and not if
the text changed meanwhile).

Tests enterInTheSearchBoxPrefersTheEntryNamedAsTyped,
enterInsideTheSearchDelayUsesTheTypedText and
messageFromAnotherInstanceOpensOnlyAnExactMatch; the second-instance test
now requires the named entry. Each of the four changes, removed in turn,
fails a test. Findings L8EWSWX3 and ROR8PEWK.

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

* Search: keep spaces in names, leave content search, cancel a waiting open

Review follow-ups on the exact-match search:

- The command-line search is queued after the configuration loop: a
  wizard's nested event loop ran it before any store was set.
- An entry named " bank" is matched as named; spaces around the text
  are dropped only when no entry is named with them.
-... (continued)

57 of 59 new or added lines in 1 file covered. (96.61%)

8498 of 8825 relevant lines covered (96.29%)

487.59 hits per line

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

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

11
#include "qtpasslogging.h"
12

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

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

74
  m_qtPass = new QtPass(this);
147 ✔
75
  restoreWindow();
147 ✔
76
  connectBackends();
147 ✔
77

78
  new QShortcut(QKeySequence(QKeySequence::StandardKey::Copy), this, this,
147 ✔
79
                &MainWindow::copyPasswordFromTreeview);
147 ✔
80

81
  m_tree = new StoreTree(ui->treeView, this);
147 ✔
82
  m_tree->setStore(QtPassSettings::getPassStore(Util::findPasswordStore()));
147 ✔
83
  m_tree->setPass(QtPassSettings::getPass());
147 ✔
84
  connect(ui->treeView, &QWidget::customContextMenuRequested, this,
147 ✔
85
          &MainWindow::showContextMenu);
147 ✔
86
  connect(ui->treeView, &DeselectableTreeView::emptyClicked, this,
147 ✔
87
          &MainWindow::deselect);
147 ✔
88

89
  initTextBrowser();
147 ✔
90

91
  updateProfileBox();
147 ✔
92

93
  initDisplayPanel();
147 ✔
94

95
  QtPassSettings::getPass()->updateEnv();
147 ✔
96

97
  // Install the search-box key filter once, not on every setUiElementsEnabled
98
  // call.
99
  ui->lineEdit->installEventFilter(this);
147 ✔
100
  // Both live in Breeze's "tools area" and get its header palette; see the
101
  // PaletteChange branch in eventFilter().
102
  ui->toolBar->installEventFilter(this);
147 ✔
103
  menuBar()->installEventFilter(this);
147 ✔
104

105
  initTimers();
147 ✔
106

107
  initToolBarButtons();
147 ✔
108
  initStatusBar();
147 ✔
109
  initProcessOutput();
147 ✔
110

111
  ui->lineEdit->setClearButtonEnabled(true);
147 ✔
112
  updateGrepButtonVisibility();
147 ✔
113

114
  setUiElementsEnabled(true);
147 ✔
115

116
  // No QApplication::quit() here: before exec() it is a documented no-op.
117
  // main() checks initSucceeded() and exits before show() instead.
118
  m_qtPass->init();
147 ✔
119
  // OK is not gated on Util::configIsValid(): an accepted configuration can
120
  // still lack a .gpg-id, so ask again; only a cancel ends the loop.
121
  while (!Util::configIsValid(QtPassSettings::load())) {
148 ✔
122
    if (!config()) {
2 ✔
123
      return;
124
    }
125
  }
126
  m_freshStart = false;
146 ✔
127
  m_initSucceeded = true;
146 ✔
128

129
  // Searched as qtpass(1) promises, once the window and its tree are up:
130
  // filtered at once and an entry named exactly so opened. Setting the
131
  // text here left it to the search timer, which only highlights. Queued
132
  // only now: from before the configuration loop, a wizard's nested event
133
  // loop ran it while no store was set yet.
134
  if (!searchText.isEmpty()) {
146 ✔
135
    QTimer::singleShot(0, this,
NEW
136
                       [this, searchText] { applySearchText(searchText); });
×
137
  }
138

139
  // Initial focus is set in showEvent(): a 10 ms QTimer here could fire
140
  // before the window was realised (queued ActivationChange, nested exec() in
141
  // init()) and selectAll() segfaulted inside Qt (#1187, #1188).
142
}
×
143

144
void MainWindow::connectBackends() {
147 ✔
145
  connect(m_qtPass, &QtPass::outputReady, this,
147 ✔
146
          [this](const QString &html) { flashText(html, false, true); });
178 ✔
147
  connect(m_qtPass, &QtPass::operationFinished, this,
147 ✔
148
          [this]() { setUiElementsEnabled(true); });
179 ✔
149
  connect(m_qtPass, &QtPass::statusMessage, this,
147 ✔
150
          &MainWindow::showStatusMessage);
147 ✔
151
  connect(m_qtPass, &QtPass::pushRequested, this, &MainWindow::onPush);
147 ✔
152
  connect(m_qtPass, &QtPass::entryInserted, this,
147 ✔
153
          [this]() { on_treeView_clicked(getCurrentTreeViewIndex()); });
148 ✔
154
  connect(&m_qtPass->clipboard(), &ClipboardManager::statusMessage, this,
147 ✔
155
          [this](const QString &message) { showStatusMessage(message); });
157 ✔
156
  // Both backends: the active one can change through the configuration
157
  // dialog without a restart.
158
  connectPassSignals(QtPassSettings::getRealPass());
147 ✔
159
  connectPassSignals(QtPassSettings::getImitatePass());
147 ✔
160
  ImitatePass *ipass = QtPassSettings::getImitatePass();
147 ✔
161
  connect(ipass, &ImitatePass::startReencryptPath, this,
147 ✔
162
          &MainWindow::startReencryptPath);
147 ✔
163
  connect(ipass, &ImitatePass::reencryptProgress, this,
147 ✔
164
          &MainWindow::reencryptProgress);
147 ✔
165
  connect(ipass, &ImitatePass::endReencryptPath, this,
147 ✔
166
          &MainWindow::endReencryptPath);
147 ✔
167
}
147 ✔
168

169
void MainWindow::initTextBrowser() {
147 ✔
170
  {
171
    const AppSettings s = QtPassSettings::load();
147 ✔
172
    if (s.useMonospace) {
147 ✔
173
      QFont monospace("Monospace");
1 ✔
174
      monospace.setStyleHint(QFont::Monospace);
1 ✔
175
      ui->textBrowser->setFont(monospace);
1 ✔
176
    }
1 ✔
177
    if (s.noLineWrapping) {
147 ✔
178
      ui->textBrowser->setLineWrapMode(QTextBrowser::NoWrap);
1 ✔
179
    }
180
    clearPanelTimer.setInterval(MS_PER_SECOND * s.autoclearPanelSeconds);
147 ✔
181
  }
147 ✔
182
  ui->textBrowser->setOpenExternalLinks(true);
147 ✔
183
  ui->textBrowser->setContextMenuPolicy(Qt::CustomContextMenu);
147 ✔
184
  connect(ui->textBrowser, &QWidget::customContextMenuRequested, this,
147 ✔
185
          &MainWindow::showBrowserContextMenu);
147 ✔
186
}
147 ✔
187

188
void MainWindow::initDisplayPanel() {
147 ✔
189
  m_displayPanel = new PasswordDisplayPanel(
147 ✔
190
      ui->gridLayout, ui->verticalLayoutPassword, this, this);
147 ✔
191
  connect(m_displayPanel, &PasswordDisplayPanel::copyRequested,
147 ✔
192
          &m_qtPass->clipboard(), &ClipboardManager::copyText);
147 ✔
193
  connect(m_displayPanel, &PasswordDisplayPanel::textCopied,
147 ✔
194
          &m_qtPass->clipboard(), &ClipboardManager::trackCopied);
147 ✔
195
  connect(ui->textBrowser, &SecretTextBrowser::copied, &m_qtPass->clipboard(),
147 ✔
196
          &ClipboardManager::trackCopied);
147 ✔
197
  connect(m_displayPanel, &PasswordDisplayPanel::qrRequested, m_qtPass,
147 ✔
198
          &QtPass::showTextAsQRCode);
147 ✔
199
  // Double-click on what is shown edits it, as in the tree.
200
  connect(m_displayPanel, &PasswordDisplayPanel::editRequested, this, [this] {
147 ✔
201
    if (ui->actionEdit->isEnabled()) {
3 ✔
202
      onEdit();
2 ✔
203
    }
204
  });
3 ✔
205
}
147 ✔
206

207
void MainWindow::initTimers() {
147 ✔
208
  clearPanelTimer.setSingleShot(true);
147 ✔
209
  connect(&clearPanelTimer, &QTimer::timeout, this, [this]() { clearPanel(); });
149 ✔
210

211
  searchTimer.setInterval(350);
147 ✔
212
  searchTimer.setSingleShot(true);
147 ✔
213

214
  connect(&searchTimer, &QTimer::timeout, this, &MainWindow::onTimeoutSearch);
147 ✔
215

216
  // Safety net: if a backend operation disables the UI but never signals
217
  // completion, re-enable after a timeout so the window can't get stuck.
218
  m_uiWatchdog.setSingleShot(true);
147 ✔
219
  m_uiWatchdog.setInterval(UiWatchdogMs);
147 ✔
220
  connect(&m_uiWatchdog, &QTimer::timeout, this, [this]() {
147 ✔
221
    showStatusMessage(tr("Operation timed out; re-enabling interface."));
×
222
    // Drop any in-flight OTP request so a late finishedShow cannot be mistaken
223
    // for the answer to it.
224
    cancelOtpRequest();
×
225
    setUiElementsEnabled(true);
×
226
  });
×
227
}
147 ✔
228

229
void MainWindow::initProcessOutput() {
147 ✔
230
  m_processOutput = new ProcessOutputPanel(this);
147 ✔
231
  addDockWidget(Qt::BottomDockWidgetArea, m_processOutput);
147 ✔
232
  // After addDockWidget so our preference wins over any cached state
233
  // QMainWindow applies; restoreWindow() already processed the saved layout.
234
  m_processOutput->setVisible(QtPassSettings::isShowProcessOutput());
147 ✔
235
  // From the setting, not isVisible(): the window is not shown yet, so no
236
  // child of it reports visible.
237
  ui->actionShowProcessOutput->setChecked(
147 ✔
238
      QtPassSettings::isShowProcessOutput());
147 ✔
239
  connect(ui->actionShowProcessOutput, &QAction::toggled, this,
147 ✔
240
          [this](bool show) {
147 ✔
241
            m_processOutput->setVisible(show);
2 ✔
242
            AppSettings s = QtPassSettings::load();
2 ✔
243
            if (s.showProcessOutput != show) {
2 ✔
244
              s.showProcessOutput = show;
2 ✔
245
              QtPassSettings::save(s);
2 ✔
246
            }
247
          });
2 ✔
248

249
  connect(QtPassSettings::getPass(), &Pass::finishedAnyWithPid, this,
147 ✔
250
          [this](const QString &out, const QString &err, Enums::PROCESS pid) {
147 ✔
251
            // Never route potentially-secret output through the panel:
252
            // PASS_SHOW goes to the text browser (cleared on a timer when
253
            // "Autoclear panel" is set),
254
            // PASS_GREP would return password-file lines (#252; it is no
255
            // longer started, the check stays), and PASS_INSERT
256
            // is excluded defensively in case a future path uses --echo.
257
            if (ProcessOutputPanel::isSensitiveProcess(pid)) {
5 ✔
258
              return;
259
            }
260
            if (!out.isEmpty()) {
4 ✔
261
              onProcessOutput(out, false, pid);
1 ✔
262
            }
263
            if (!err.isEmpty()) {
4 ✔
264
              onProcessOutput(err, true, pid);
3 ✔
265
            }
266
          });
267
}
147 ✔
268

269
MainWindow::~MainWindow() {
290 ✔
270
  // Quit from the tray menu or a SIGTERM never delivers closeEvent(); the
271
  // window still knows its last geometry here.
272
  saveWindowState();
147 ✔
273
  delete m_qtPass;
147 ✔
274
}
437 ✔
275

276
// The signals of one backend that the window answers itself.
277
void MainWindow::connectPassSignals(Pass *pass) {
294 ✔
278
  // A failed decrypt never emits finishedShow; drop the pending OTP/copy
279
  // request so a later decrypt of the same entry is not taken as its answer.
280
  connect(pass, &Pass::processErrorExit, this, &MainWindow::onOperationError);
294 ✔
281
  connect(pass, &Pass::critical, this, &MainWindow::critical);
294 ✔
282
  connect(pass, &Pass::startingExecuteWrapper, this,
294 ✔
283
          &MainWindow::executeWrapperStarted);
294 ✔
284
  // The profile box comes back when the queue is done, also after the
285
  // watchdog released the rest of the interface early.
286
  connect(pass, &Pass::idle, this, &MainWindow::updateProfileBoxEnabled);
294 ✔
287
  connect(pass, &Pass::statusMsg, this, &MainWindow::showStatusMessage);
294 ✔
288
  connect(pass, &Pass::finishedShow, this, &MainWindow::passShowHandler);
294 ✔
289
  // Both check the file against their own pending request and ignore the
290
  // rest, so they can stay connected for good.
291
  connect(pass, &Pass::finishedShow, this, &MainWindow::otpFromFileToClipboard);
294 ✔
292
  connect(pass, &Pass::finishedShow, this,
294 ✔
293
          &MainWindow::passwordFromFileToClipboard);
294 ✔
294
  connect(pass, &Pass::finishedGrep, this, &MainWindow::onGrepFinished);
294 ✔
295
}
294 ✔
296

297
// Idempotent; called from closeEvent() and the destructor.
298
void MainWindow::saveWindowState() {
149 ✔
299
  QtPassSettings::setGeometry(saveGeometry());
149 ✔
300
  QtPassSettings::setSavestate(saveState());
149 ✔
301
}
149 ✔
302

303
void MainWindow::focusInput() {
53 ✔
304
  // findChild() rather than ui->lineEdit: on a fresh-config first launch
305
  // config() calls setWindowFlags(), which rebuilds the native window, and
306
  // under Qt 6.11 the QLineEdit was destroyed while ui->lineEdit kept its old
307
  // address (SIGSEGV in QWidget::testAttribute). findChild() returns null.
308
  if (!isVisible()) {
53 ✔
309
    return;
310
  }
311
  auto *lineEdit = findChild<QLineEdit *>(QStringLiteral("lineEdit"));
53 ✔
312
  if (lineEdit == nullptr || !lineEdit->isVisible()) {
53 ✔
313
    return;
314
  }
315
  lineEdit->selectAll();
53 ✔
316
  lineEdit->setFocus();
53 ✔
317
  // Only once focus has landed: set in showEvent(), an early return above
318
  // would consume the one-shot and never retry.
319
  m_firstShowCompleted = true;
53 ✔
320
}
321

322
auto MainWindow::event(QEvent *event) -> bool {
6,541 ✔
323
  if (event->type() == QEvent::ApplicationPaletteChange) {
6,541 ✔
324
    m_themeSwitched = true;
11 ✔
325
    // Breeze may re-stamp the bars before this arrives (Plasma 6 does):
326
    // their PaletteChange then found no switch yet, so check them now too.
327
    QTimer::singleShot(0, this, &MainWindow::dropStaleToolsAreaPalettes);
11 ✔
328
  }
329
  return QMainWindow::event(event);
6,541 ✔
330
}
331

332
void MainWindow::changeEvent(QEvent *event) {
197 ✔
333
  QWidget::changeEvent(event);
197 ✔
334
  if (event->type() == QEvent::PaletteChange && m_displayPanel != nullptr) {
197 ✔
335
    // Desktop switched light/dark. Top-level widgets get PaletteChange
336
    // (ApplicationPaletteChange goes to QApplication); stylesheets with
337
    // baked-in palette colours must be re-derived by hand.
338
    m_displayPanel->refreshPalette();
10 ✔
339
  }
340
  if (event->type() == QEvent::ActivationChange && isActiveWindow() &&
197 ✔
341
      isVisible()) {
342
    // Defer a tick so the activation dispatch chain unwinds first: calling
343
    // focusInput() inline has segfaulted on half-rebuilt ui state.
344
    QMetaObject::invokeMethod(this, &MainWindow::focusInput,
30 ✔
345
                              Qt::QueuedConnection);
346
  }
347
}
197 ✔
348

349
void MainWindow::showEvent(QShowEvent *event) {
32 ✔
350
  QMainWindow::showEvent(event);
32 ✔
351
  if (m_firstShowCompleted) {
32 ✔
352
    return;
353
  }
354
  // Queued so the platform map and pending rebuilds (setWindowFlags on the
355
  // wizard path) settle first. focusInput() sets the latch only on success,
356
  // so a failed lookup retries on the next show.
357
  QMetaObject::invokeMethod(this, &MainWindow::focusInput,
30 ✔
358
                            Qt::QueuedConnection);
359
}
360

361
void MainWindow::initToolBarButtons() {
147 ✔
362
  connect(ui->actionAddPassword, &QAction::triggered, this,
147 ✔
363
          &MainWindow::addPassword);
147 ✔
364
  connect(ui->actionAddFolder, &QAction::triggered, this,
147 ✔
365
          &MainWindow::addFolder);
147 ✔
366
  connect(ui->actionEdit, &QAction::triggered, this, &MainWindow::onEdit);
147 ✔
367
  connect(ui->actionDelete, &QAction::triggered, this, &MainWindow::onDelete);
147 ✔
368
  connect(ui->actionPush, &QAction::triggered, this, &MainWindow::onPush);
147 ✔
369
  connect(ui->actionUpdate, &QAction::triggered, this, &MainWindow::onUpdate);
147 ✔
370
  connect(ui->actionUsers, &QAction::triggered, this, &MainWindow::onUsers);
147 ✔
371
  connect(ui->actionConfig, &QAction::triggered, this, &MainWindow::onConfig);
147 ✔
372
  connect(ui->actionOtp, &QAction::triggered, this, &MainWindow::onOtp);
147 ✔
373

374
  // Menu-only. Quit ends the application, tray icon or not, as in KeePassXC,
375
  // Telegram and the KDE, GNOME and macOS guidelines (#1788). Close is
376
  // close(), a hide when "hide on close" is set, like the X button and Alt+F4.
377
  connect(ui->actionQuit, &QAction::triggered, qApp, &QApplication::quit);
147 ✔
378
  connect(ui->actionClose, &QAction::triggered, this, &MainWindow::close);
147 ✔
379
#ifdef Q_OS_MACOS
380
  // The menu bar is the system's up there; nothing to hide.
381
  ui->actionShowMenuBar->setVisible(false);
382
#else
383
  // The action lives in the menu it hides, so it has to be on the window as
384
  // well for Ctrl+M to keep working while the bar is gone.
385
  addAction(ui->actionShowMenuBar);
147 ✔
386
  ui->actionShowMenuBar->setChecked(QtPassSettings::load().showMenuBar);
147 ✔
387
  menuBar()->setVisible(ui->actionShowMenuBar->isChecked());
147 ✔
388
  connect(ui->actionShowMenuBar, &QAction::toggled, this, [this](bool show) {
147 ✔
389
    menuBar()->setVisible(show);
5 ✔
390
    AppSettings s = QtPassSettings::load();
5 ✔
391
    s.showMenuBar = show;
5 ✔
392
    QtPassSettings::save(s);
5 ✔
393
  });
5 ✔
394
  new MenuBarPeek(this, ui->actionShowMenuBar);
147 ✔
395
#endif
396
  connect(ui->actionFaq, &QAction::triggered, this, [] {
148 ✔
397
    QDesktopServices::openUrl(QUrl(QStringLiteral("https://qtpass.org/faq")));
2 ✔
398
  });
1 ✔
399
  connect(ui->actionAbout, &QAction::triggered, this, &MainWindow::showAbout);
147 ✔
400
  connect(ui->actionAboutQt, &QAction::triggered, qApp, &QApplication::aboutQt);
147 ✔
401

402
  ui->actionAddPassword->setIcon(
147 ✔
403
      QIcon::fromTheme("document-new", QIcon(":/icons/document-new.svg")));
588 ✔
404
  ui->actionAddFolder->setIcon(
147 ✔
405
      QIcon::fromTheme("folder-new", QIcon(":/icons/folder-new.svg")));
588 ✔
406
  ui->actionEdit->setIcon(QIcon::fromTheme(
147 ✔
407
      "document-properties", QIcon(":/icons/document-properties.svg")));
441 ✔
408
  ui->actionDelete->setIcon(
147 ✔
409
      QIcon::fromTheme("edit-delete", QIcon(":/icons/edit-delete.svg")));
588 ✔
410
  ui->actionPush->setIcon(
147 ✔
411
      QIcon::fromTheme("go-up", QIcon(":/icons/go-top.svg")));
588 ✔
412
  ui->actionUpdate->setIcon(
147 ✔
413
      QIcon::fromTheme("go-down", QIcon(":/icons/go-bottom.svg")));
588 ✔
414
  ui->actionUsers->setIcon(QIcon::fromTheme(
147 ✔
415
      "x-office-address-book", QIcon(":/icons/x-office-address-book.svg")));
441 ✔
416
  ui->actionConfig->setIcon(QIcon::fromTheme(
147 ✔
417
      "applications-system", QIcon(":/icons/applications-system.svg")));
294 ✔
418
}
147 ✔
419

420
void MainWindow::initStatusBar() {
147 ✔
421
  ui->statusBar->showMessage(tr("Welcome to QtPass %1").arg(VERSION), 2000);
294 ✔
422

423
  QPixmap logo = QPixmap::fromImage(QImage(":/artwork/icon.svg"))
294 ✔
424
                     .scaledToHeight(statusBar()->height());
147 ✔
425
  auto *logoApp = new QLabel(statusBar());
147 ✔
426
  logoApp->setPixmap(logo);
147 ✔
427
  statusBar()->addPermanentWidget(logoApp);
147 ✔
428
}
147 ✔
429

430
auto MainWindow::getCurrentTreeViewIndex() -> QModelIndex {
1 ✔
431
  return ui->treeView->currentIndex();
1 ✔
432
}
433

434
void MainWindow::flashText(const QString &text, const bool isError,
57 ✔
435
                           const bool isHtml) {
436
  if (isError) {
57 ✔
437
    ui->textBrowser->setTextColor(Qt::red);
7 ✔
438
  } else {
439
    // setText() re-applies the current char format, red after an error, to
440
    // the whole document. Clear the foreground rather than pin a palette
441
    // colour, so text follows runtime light/dark switches (#946).
442
    QTextCharFormat format = ui->textBrowser->currentCharFormat();
50 ✔
443
    format.clearForeground();
444
    ui->textBrowser->setCurrentCharFormat(format);
50 ✔
445
  }
446

447
  if (isHtml) {
57 ✔
448
    QString _text = text;
449
    if (!ui->textBrowser->toPlainText().isEmpty()) {
96 ✔
450
      _text = ui->textBrowser->toHtml() + _text;
30 ✔
451
    }
452
    ui->textBrowser->setHtml(_text);
48 ✔
453
  } else {
454
    ui->textBrowser->setText(text);
9 ✔
455
  }
456
}
57 ✔
457

458
void MainWindow::applyTextBrowserSettings() {
3 ✔
459
  const AppSettings s = QtPassSettings::load();
3 ✔
460
  if (s.useMonospace) {
3 ✔
461
    QFont monospace("Monospace");
1 ✔
462
    monospace.setStyleHint(QFont::Monospace);
1 ✔
463
    ui->textBrowser->setFont(monospace);
1 ✔
464
  } else {
1 ✔
465
    ui->textBrowser->setFont(QFont());
2 ✔
466
  }
467

468
  if (s.noLineWrapping) {
3 ✔
469
    ui->textBrowser->setLineWrapMode(QTextBrowser::NoWrap);
1 ✔
470
  } else {
471
    ui->textBrowser->setLineWrapMode(QTextBrowser::WidgetWidth);
2 ✔
472
  }
473
}
3 ✔
474

475
void MainWindow::applyWindowFlagsSettings() {
159 ✔
476
  const bool wantOnTop = QtPassSettings::isAlwaysOnTop();
159 ✔
477
  const Qt::WindowFlags flags = windowFlags();
478
  if (flags.testFlag(Qt::WindowStaysOnTopHint) == wantOnTop) {
159 ✔
479
    // setWindowFlags() rebuilds the native window, the teardown that left
480
    // ui->lineEdit dangling (see focusInput()); skip it when nothing changes.
481
    return;
482
  }
483
  // Toggle just this hint; resetting to Qt::Window discarded every other flag.
484
  const bool wasVisible = isVisible();
485
  setWindowFlags(wantOnTop ? (flags | Qt::WindowStaysOnTopHint)
4 ✔
486
                           : (flags & ~Qt::WindowStaysOnTopHint));
487
  // setWindowFlags() hides a shown window; a window that was not shown yet
488
  // (first-run wizard from the constructor) is left to its normal show.
489
  if (wasVisible) {
2 ✔
490
    show();
2 ✔
491
  }
492
}
493

494
auto MainWindow::config() -> bool {
5 ✔
495
  if (m_freshStart) {
5 ✔
496
    // No usable configuration yet: the wizard finds the programs, the key
497
    // and the store, and creates the store when it has to.
498
    FirstRunWizard wizard(this);
2 ✔
499
    if (wizard.exec() != QDialog::Accepted) {
2 ✔
500
      return false;
501
    }
502
  } else {
2 ✔
503
    ConfigDialog d(this);
3 ✔
504
    d.setModal(true);
3 ✔
505
    if (d.exec() != QDialog::Accepted) {
3 ✔
506
      return false;
507
    }
508
  }
3 ✔
509

510
  applyTextBrowserSettings();
3 ✔
511
  applyWindowFlagsSettings();
3 ✔
512

513
  updateProfileBox();
3 ✔
514
  const AppSettings s = QtPassSettings::load();
3 ✔
515
  // An open still waiting for the tree was asked of the old view; once
516
  // re-rooted, it would find that name in the new store. A profile switch
517
  // ends it by clearing the search text.
518
  delete m_pendingOpen;
3 ✔
519
  m_tree->setStore(s.passStore);
3 ✔
520
  deselect();
3 ✔
521
  ui->treeView->setCurrentIndex(QModelIndex());
3 ✔
522

523
  Pass *activePass = QtPassSettings::getPass();
3 ✔
524
  activePass->updateEnv();
3 ✔
525
  m_tree->setPass(activePass);
3 ✔
526
  clearPanelTimer.setInterval(MS_PER_SECOND * s.autoclearPanelSeconds);
3 ✔
527
  m_qtPass->clipboard().setAutoclearTimer();
3 ✔
528

529
  updateGitButtonVisibility();
3 ✔
530
  updateOtpButtonVisibility();
3 ✔
531
  updateGrepButtonVisibility();
3 ✔
532
  updateProcessOutputVisibility();
3 ✔
533
#ifndef Q_OS_MACOS
534
  // The action's toggled handler shows or hides the bar (and saves again).
535
  ui->actionShowMenuBar->setChecked(s.showMenuBar);
3 ✔
536
#endif
537
  if (s.useTrayIcon && m_tray == nullptr) {
3 ✔
538
    initTrayIcon();
1 ✔
539
  } else if (!s.useTrayIcon && m_tray != nullptr) {
2 ✔
540
    destroyTrayIcon();
×
541
  }
542

543
  // Stay fresh-start while the configuration is unusable, so the
544
  // constructor's loop re-runs the wizard. The re-prompt lives there:
545
  // recursing here never reported a cancel back to the caller.
546
  if (Util::configIsValid(s)) {
3 ✔
547
    m_freshStart = false;
3 ✔
548
  }
549
  return true;
550
}
3 ✔
551

552
void MainWindow::onUpdate(bool block) {
2 ✔
553
  ui->statusBar->showMessage(tr("Updating password-store"), 2000);
2 ✔
554
  if (block) {
2 ✔
555
    QtPassSettings::getPass()->GitPull_b();
1 ✔
556
  } else {
557
    QtPassSettings::getPass()->GitPull();
1 ✔
558
  }
559
}
2 ✔
560

561
void MainWindow::onPush() {
1 ✔
562
  if (QtPassSettings::isUseGit()) {
1 ✔
563
    ui->statusBar->showMessage(tr("Updating password-store"), 2000);
1 ✔
564
    QtPassSettings::getPass()->GitPush();
1 ✔
565
  }
566
}
1 ✔
567

568
auto MainWindow::getFile(const QModelIndex &index, bool forPass) -> QString {
45 ✔
569
  return m_tree->fileFor(index, forPass);
45 ✔
570
}
571

572
void MainWindow::on_treeView_clicked(const QModelIndex &index) {
21 ✔
573
  bool cleared = ui->treeView->currentIndex().flags() == Qt::NoItemFlags;
21 ✔
574
  QString file = getFile(index, true);
21 ✔
575
  ui->passwordName->setText(file);
21 ✔
576
  if (!file.isEmpty() && !cleared) {
21 ✔
577
    // Remember what the panel is about to show, so onOtp() can tell whether the
578
    // code it can see belongs to the entry that is currently selected.
579
    m_shownFile = file;
20 ✔
580
    QtPassSettings::getPass()->Show(file);
40 ✔
581
  } else {
582
    m_shownFile.clear();
1 ✔
583
    clearPanel(false);
1 ✔
584
    ui->actionEdit->setEnabled(false);
1 ✔
585
    ui->actionDelete->setEnabled(true);
1 ✔
586
  }
587
}
21 ✔
588

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

592
  if (fileOrFolder.isFile()) {
4 ✔
593
    editPassword(getFile(index, true));
6 ✔
594
  }
595
}
4 ✔
596

597
void MainWindow::deselect() {
14 ✔
598
  m_shownFile.clear();
14 ✔
599
  cancelOtpRequest();
14 ✔
600
  m_qtPass->clipboard().clear();
14 ✔
601
  ui->treeView->clearSelection();
14 ✔
602
  ui->actionEdit->setEnabled(false);
14 ✔
603
  ui->actionDelete->setEnabled(false);
14 ✔
604
  ui->passwordName->setText("");
14 ✔
605
  clearPanel(false);
14 ✔
606
}
14 ✔
607

608
void MainWindow::executeWrapperStarted() {
40 ✔
609
  m_displayPanel->clear();
40 ✔
610
  ui->textBrowser->clear();
40 ✔
611
  setUiElementsEnabled(false);
40 ✔
612
  clearPanelTimer.stop();
40 ✔
613
  if (QtPassSettings::isShowProcessOutput()) {
40 ✔
614
    m_processOutput->setVisible(true);
35 ✔
615
  }
616
}
40 ✔
617

618
void MainWindow::passShowHandler(const QString &p_output, const QString &file) {
24 ✔
619
  // Only the entry we most recently asked to show may repaint the panel; a
620
  // slower decrypt of an entry the user has since left is dropped, and so is
621
  // one that arrives after the selection was cleared (deselect, a profile
622
  // switch): nothing is asked to be shown then.
623
  if (!file.isEmpty() && file != m_shownFile) {
24 ✔
624
    // A newer show is pending and releases the interface when it lands;
625
    // with none (the selection was cleared) nothing else would until the
626
    // watchdog. setUiElementsEnabled() keeps a re-encryption's lock.
627
    if (m_shownFile.isEmpty()) {
8 ✔
628
      setUiElementsEnabled(true);
7 ✔
629
    }
630
    return;
8 ✔
631
  }
632
  const AppSettings s = QtPassSettings::load();
16 ✔
633
  // What a template marks secret, in the settings or the store's
634
  // .templates; read per entry shown, so an edit there counts at once.
635
  if (s.hidePassword) {
16 ✔
636
    m_displayPanel->setMarkedSecrets(
2 ✔
637
        TemplateIO::secretFieldsIn(s.passTemplate) +
4 ✔
638
        TemplateIO::readSecretFields(s.passStore));
6 ✔
639
  }
640
  QStringList templ =
641
      s.useTemplate ? TemplateIO::fieldsIn(s.passTemplate) : QStringList();
16 ✔
642
  bool allFields = s.useTemplate && s.templateAllFields;
16 ✔
643
  // A secret the panel hides is a field even when the template doesn't list
644
  // it: left in the text below the fields, it would show in plain view.
645
  FileContent fileContent = FileContent::parse(
646
      p_output, templ, allFields, [this, &s](const QString &name) {
16 ✔
647
        return m_displayPanel->isSecret(name, s);
7 ✔
648
      });
16 ✔
649
  QString output = p_output;
650
  // Display variant: empty when the password line is itself an otpauth URI, so
651
  // the shared secret is neither rendered nor copied to the clipboard.
652
  QString password = fileContent.getPasswordForDisplay();
16 ✔
653

654
  // Skipped for an OTP request: the user asked for a code, and two
655
  // OleSetClipboard calls in one turn can leave the Windows clipboard empty.
656
  if (m_otpRequestFile.isEmpty() || m_otpRequestFile != file) {
16 ✔
657
    m_qtPass->clipboard().copyIfAlways(password, p_output);
14 ✔
658
  }
659

660
  m_displayPanel->clear();
16 ✔
661

662
  if (s.hideContent) {
16 ✔
663
    output = "***" + tr("Content hidden") + "***";
4 ✔
664
  } else if (s.displayAsIs) {
14 ✔
665
    // As it is, but not a block per line of millions.
666
    output = FileContent::boundedForDisplay(p_output);
×
667
  } else {
668
    m_displayPanel->displayFields(password, fileContent.getNamedValues(), s,
28 ✔
669
                                  s.useOtp ? fileContent.getOtpUri()
14 ✔
670
                                           : QString());
671
    output = fileContent.getRemainingDataForDisplay();
28 ✔
672
  }
673

674
  if (s.useAutoclearPanel) {
16 ✔
675
    clearPanelTimer.start();
2 ✔
676
  }
677

678
  flashText(QtPass::formatOutput(output), false, true);
32 ✔
679
  setUiElementsEnabled(true);
16 ✔
680
}
32 ✔
681

682
void MainWindow::otpFromFileToClipboard(const QString &p_output,
20 ✔
683
                                        const QString &file) {
684
  // Permanently connected: only the decrypt of the entry onOtp() asked for
685
  // is ours, everything else belongs to a tree click or a Ctrl+C.
686
  if (m_otpRequestFile.isEmpty() || file != m_otpRequestFile) {
20 ✔
687
    return;
17 ✔
688
  }
689
  m_otpRequestFile.clear();
5 ✔
690

691
  if (p_output.isEmpty()) {
5 ✔
692
    // Distinguish "could not read the entry" from "entry has no OTP".
693
    flashText(tr("Could not decrypt this password entry"), true);
1 ✔
694
    setUiElementsEnabled(true);
1 ✔
695
    return;
1 ✔
696
  }
697

698
  // passShowHandler ran first for this finishedShow; if it rendered the OTP
699
  // row, reuse its code (as onOtp()'s fast path does). Otherwise parse:
700
  // hideContent, displayAsIs or no OTP field.
701
  const QString shown = m_displayPanel->currentOtpCode();
4 ✔
702
  if (!shown.isEmpty()) {
4 ✔
703
    m_qtPass->clipboard().copyText(shown);
1 ✔
704
    showStatusMessage(tr("OTP code copied to clipboard"));
1 ✔
705
    setUiElementsEnabled(true);
1 ✔
706
    return;
707
  }
708

709
  const AppSettings s = QtPassSettings::load();
3 ✔
710
  // Parse with the same template settings passShowHandler uses, so an OTP
711
  // field is recognised identically in both paths.
712
  const QStringList templ =
713
      s.useTemplate ? TemplateIO::fieldsIn(s.passTemplate) : QStringList();
3 ✔
714
  const bool allFields = s.useTemplate && s.templateAllFields;
3 ✔
715
  const FileContent fileContent =
716
      FileContent::parse(p_output, templ, allFields);
3 ✔
717

718
  const std::optional<Totp::Settings> settings =
719
      Totp::parse(fileContent.getOtpUri());
6 ✔
720
  if (settings.has_value()) {
3 ✔
721
    m_qtPass->clipboard().copyText(Totp::generateNow(*settings));
4 ✔
722
    showStatusMessage(tr("OTP code copied to clipboard"));
4 ✔
723
  } else {
724
    flashText(tr("No OTP code found in this password entry"), true);
2 ✔
725
  }
726
  setUiElementsEnabled(true);
3 ✔
727
}
6 ✔
728

729
void MainWindow::clearPanel(bool notify) {
48 ✔
730
  m_displayPanel->clear();
48 ✔
731
  const bool grepWasVisible = ui->grepResultsList->isVisible();
48 ✔
732
  ui->grepResultsList->clear();
48 ✔
733
  if (grepWasVisible) {
48 ✔
734
    ui->grepResultsList->setVisible(false);
2 ✔
735
    ui->treeView->setVisible(true);
2 ✔
736
    if (m_grep.inGrepMode()) {
2 ✔
737
      m_grep.clearGrepMode();
738
      ui->grepButton->blockSignals(true);
2 ✔
739
      ui->grepButton->setChecked(false);
2 ✔
740
      ui->grepButton->blockSignals(false);
2 ✔
741
      ui->lineEdit->blockSignals(true);
2 ✔
742
      ui->lineEdit->clear();
2 ✔
743
      ui->lineEdit->blockSignals(false);
2 ✔
744
      ui->lineEdit->setPlaceholderText(tr("Search password"));
4 ✔
745
    }
746
  }
747
  if (notify) {
48 ✔
748
    QString output = "***" + tr("Password and content hidden") + "***";
4 ✔
749
    ui->textBrowser->setHtml(output);
2 ✔
750
  } else {
751
    ui->textBrowser->setHtml("");
92 ✔
752
  }
753
}
48 ✔
754

755
void MainWindow::setUiElementsEnabled(bool state) {
287 ✔
756
  // A running re-encryption owns the UI state: the progress dialog's Cancel is
757
  // the user's escape hatch and endReencryptPath() releases the interface, so
758
  // neither an unrelated completion nor the watchdog may re-enable it early.
759
  if (state && m_reencryptRunning) {
287 ✔
760
    m_uiWatchdog.stop();
1 ✔
761
    return;
1 ✔
762
  }
763
  // Arm the watchdog while the UI is disabled; disarm once re-enabled.
764
  if (state) {
765
    m_uiWatchdog.stop();
226 ✔
766
  } else {
767
    m_uiWatchdog.start();
60 ✔
768
  }
769
  ui->treeView->setEnabled(state);
286 ✔
770
  ui->lineEdit->setEnabled(state);
286 ✔
771
  ui->actionAddPassword->setEnabled(state);
286 ✔
772
  ui->actionAddFolder->setEnabled(state);
286 ✔
773
  ui->actionUsers->setEnabled(state);
286 ✔
774
  ui->actionConfig->setEnabled(state);
286 ✔
775
  m_uiEnabled = state;
286 ✔
776
  updateProfileBoxEnabled();
286 ✔
777
  const bool uiEnabled = state;
778
  // is a file selected?
779
  state &= ui->treeView->currentIndex().isValid();
572 ✔
780
  ui->actionDelete->setEnabled(state);
286 ✔
781
  ui->actionEdit->setEnabled(state);
286 ✔
782
  updateGitButtonVisibility(uiEnabled);
286 ✔
783
  // `state` is now "UI enabled AND a file is selected", which is exactly when
784
  // generating an OTP makes sense.
785
  updateOtpButtonVisibility(state);
286 ✔
786
}
787

788
void MainWindow::restoreWindow() {
156 ✔
789
  // saveGeometry() covers position, size, maximized state and screen;
790
  // anything applied on top discards it. Centre only when nothing was saved.
791
  const QByteArray geometry = QtPassSettings::getGeometry();
312 ✔
792
  if (geometry.isEmpty() || !restoreGeometry(geometry)) {
156 ✔
793
    WindowStateStore::centreOnCursorScreen(*this);
4 ✔
794
  }
795
  restoreState(QtPassSettings::getSavestate(saveState()));
156 ✔
796
  const AppSettings s = QtPassSettings::load();
156 ✔
797

798
  applyWindowFlagsSettings();
156 ✔
799

800
  if (s.useTrayIcon && m_tray == nullptr) {
156 ✔
801
    initTrayIcon();
1 ✔
802
    if (s.startMinimized) {
1 ✔
803
      // since we are still in constructor, can't directly hide
804
      QTimer::singleShot(10, this, &MainWindow::hide);
2 ✔
805
    }
806
  } else if (!s.useTrayIcon && m_tray != nullptr) {
155 ✔
807
    destroyTrayIcon();
×
808
  }
809
}
312 ✔
810

811
void MainWindow::onConfig() { config(); }
1 ✔
812

813
void MainWindow::showAbout() {
1 ✔
814
  QMessageBox::about(
1 ✔
815
      this, tr("About QtPass"),
1 ✔
816
      tr("<h3>QtPass %1</h3>"
1 ✔
817
         "<p>A multi-platform GUI for <a "
818
         "href=\"https://www.passwordstore.org/\">"
819
         "pass</a>, the standard Unix password manager.</p>"
820
         "<p><a href=\"https://qtpass.org/\">qtpass.org</a> &middot; "
821
         "<a href=\"https://github.com/IJHack/QtPass\">Source and "
822
         "issues</a></p>"
823
         "<p>Copyright &copy; 2014&ndash;%2 IJhack. Licensed under the "
824
         "<a href=\"https://www.gnu.org/licenses/gpl-3.0.html\">GNU GPL "
825
         "version 3</a> or later.</p>")
826
          .arg(QStringLiteral(VERSION),
2 ✔
827
               QString::number(QDate::currentDate().year())));
2 ✔
828
}
1 ✔
829

830
void MainWindow::on_lineEdit_textChanged(const QString &arg1) {
36 ✔
831
  if (m_grep.inGrepMode())
36 ✔
832
    return;
833
  ui->statusBar->showMessage(tr("Looking for: %1").arg(arg1), 1000);
62 ✔
834
  ui->treeView->expandAll();
31 ✔
835
  // Drop any decrypt still pending for the entry that was shown: otherwise it
836
  // keeps its right to the panel and, with "Always copy", the clipboard, and
837
  // when it lands late it shows that entry's password under the new heading.
838
  m_shownFile.clear();
31 ✔
839
  cancelOtpRequest();
31 ✔
840
  clearPanel(false);
31 ✔
841
  ui->passwordName->setText("");
62 ✔
842
  ui->actionEdit->setEnabled(false);
31 ✔
843
  ui->actionDelete->setEnabled(false);
31 ✔
844
  searchTimer.start();
31 ✔
845
}
846

847
void MainWindow::onTimeoutSearch() {
37 ✔
848
  // The tree matches slash-separated paths: on Windows, team\bank typed is
849
  // team/bank, as exactMatchPath() reads it too.
850
  QString query = QDir::fromNativeSeparators(ui->lineEdit->text());
74 ✔
851

852
  if (query.isEmpty()) {
37 ✔
853
    ui->treeView->collapseAll();
1 ✔
854
    deselect();
1 ✔
855
  }
856

857
  // The words are matched literally, in order, with anything in between:
858
  // "work vpn" finds work/acme/vpn. Regular expressions belong to the
859
  // content search; here a typed "[" or "(" must not switch filtering off.
860
  QStringList words;
37 ✔
861
  for (const QString &word :
862
       query.split(QLatin1Char(' '), Qt::SkipEmptyParts)) {
111 ✔
863
    words << QRegularExpression::escape(word);
37 ✔
864
  }
865
  QRegularExpression regExp(words.join(QStringLiteral(".*")),
74 ✔
866
                            QRegularExpression::CaseInsensitiveOption);
37 ✔
867
  m_tree->setFilter(regExp);
37 ✔
868

869
  if (m_tree->proxy().rowCount() > 0 && !query.isEmpty()) {
37 ✔
870
    selectFirstFile();
26 ✔
871
  } else {
872
    ui->actionEdit->setEnabled(false);
11 ✔
873
    ui->actionDelete->setEnabled(false);
11 ✔
874
  }
875
}
74 ✔
876

877
void MainWindow::on_lineEdit_returnPressed() {
8 ✔
878
  qCDebug(lcQtPass) << "on_lineEdit_returnPressed"
8 ✔
879
                    << m_tree->proxy().rowCount();
×
880

881
  if (m_grep.inGrepMode()) {
8 ✔
882
    const QString query = ui->lineEdit->text();
4 ✔
883
    if (!query.isEmpty()) {
4 ✔
884
      ui->grepResultsList->clear();
3 ✔
885
      ui->statusBar->showMessage(tr("Searching…"));
6 ✔
886
      if (m_grep.beginSearch()) {
887
        QApplication::setOverrideCursor(Qt::WaitCursor);
3 ✔
888
      }
889
      QtPassSettings::getPass()->Grep(query, ui->grepCaseButton->isChecked());
6 ✔
890
    } else {
891
      if (m_grep.cancelSearch()) {
892
        QApplication::restoreOverrideCursor();
1 ✔
893
      }
894
      ui->grepResultsList->clear();
1 ✔
895
      ui->grepResultsList->setVisible(false);
1 ✔
896
      ui->treeView->setVisible(true);
1 ✔
897
    }
898
    return;
899
  }
900

901
  // Return within the search delay acts on the text as typed, not on the
902
  // tree as the previous text filtered it.
903
  if (searchTimer.isActive()) {
4 ✔
904
    searchTimer.stop();
4 ✔
905
    onTimeoutSearch();
4 ✔
906
  }
907
  if (m_tree->proxy().rowCount() > 0) {
4 ✔
908
    selectFirstFile();
4 ✔
909
    on_treeView_clicked(ui->treeView->currentIndex());
4 ✔
910
  }
911
}
912

913
void MainWindow::on_grepButton_toggled(bool checked) {
14 ✔
914
  const AppSettings s = QtPassSettings::load();
14 ✔
915
  if (checked) {
14 ✔
916
    m_grep.enterGrepMode();
917
    ui->lineEdit->setPlaceholderText(tr("Search content (regex)"));
16 ✔
918
    // Both backends search through NativeGrep (QRegularExpression), so one
919
    // dialect: PCRE.
920
    ui->lineEdit->setToolTip(
8 ✔
921
        tr("Content search uses Perl-compatible regular expressions (PCRE)."));
8 ✔
922
    ui->lineEdit->clear();
8 ✔
923
    searchTimer.stop();
8 ✔
924
    m_tree->setFilter(QRegularExpression());
8 ✔
925
    ui->grepResultsList->setVisible(false);
8 ✔
926
    // Keep treeView visible until results arrive
927
  } else {
928
    if (m_grep.leaveGrepMode()) {
929
      QApplication::restoreOverrideCursor();
1 ✔
930
    }
931
    searchTimer.stop();
6 ✔
932
    ui->lineEdit->blockSignals(true);
6 ✔
933
    ui->lineEdit->clear();
6 ✔
934
    ui->lineEdit->blockSignals(false);
6 ✔
935
    ui->lineEdit->setPlaceholderText(tr("Search password"));
12 ✔
936
    ui->lineEdit->setToolTip(QString());
12 ✔
937
    ui->grepResultsList->clear();
6 ✔
938
    ui->grepResultsList->setVisible(false);
6 ✔
939
    ui->treeView->setVisible(true);
6 ✔
940
    m_tree->setFilter(QRegularExpression());
6 ✔
941
  }
942
}
14 ✔
943

944
void MainWindow::onGrepFinished(
6 ✔
945
    const QList<QPair<QString, QStringList>> &results) {
946
  const GrepSearchController::FinishOutcome outcome = m_grep.finishSearch();
947
  if (outcome.restoreCursor) {
6 ✔
948
    QApplication::restoreOverrideCursor();
1 ✔
949
  }
950
  // Re-enable the UI before the discard check so a cancelled search can never
951
  // leave controls disabled.
952
  setUiElementsEnabled(true);
6 ✔
953
  if (outcome.discard) {
6 ✔
954
    return;
3 ✔
955
  }
956
  if (!m_grep.inGrepMode())
4 ✔
957
    return;
958
  ui->grepResultsList->clear();
4 ✔
959
  if (results.isEmpty()) {
4 ✔
960
    ui->statusBar->showMessage(tr("No matches found."), 3000);
2 ✔
961
    ui->grepResultsList->setVisible(false);
1 ✔
962
    ui->treeView->setVisible(true);
1 ✔
963
    return;
1 ✔
964
  }
965
  const AppSettings s = QtPassSettings::load();
3 ✔
966
  const bool hideContent = s.hideContent;
3 ✔
967
  int totalLines = 0;
968
  int entries = 0;
969
  bool stopped = false;
970
  for (const auto &pair : results) {
24 ✔
971
    if (NativeGrep::isStoppedMarker(pair)) {
21 ✔
972
      stopped = true;
973
      continue;
×
974
    }
975
    ++entries;
21 ✔
976
    auto *entryItem = new QTreeWidgetItem(ui->grepResultsList);
21 ✔
977
    entryItem->setText(0, pair.first);
21 ✔
978
    entryItem->setData(0, Qt::UserRole, pair.first);
21 ✔
979
    for (const QString &line : pair.second) {
42 ✔
980
      auto *lineItem = new QTreeWidgetItem(entryItem);
21 ✔
981
      // The marker is no content: shown as it is with hidden content too,
982
      // and not counted as a match.
983
      if (NativeGrep::isMoreMarker(line)) {
21 ✔
984
        lineItem->setText(0, tr("… more matches in this entry"));
×
985
      } else {
986
        lineItem->setText(0, hideContent ? "***" + tr("Content hidden") + "***"
63 ✔
987
                                         : line);
988
        ++totalLines;
21 ✔
989
      }
990
      lineItem->setData(0, Qt::UserRole, pair.first);
21 ✔
991
    }
992
  }
993
  ui->grepResultsList->expandAll();
3 ✔
994
  ui->treeView->setVisible(false);
3 ✔
995
  ui->grepResultsList->setVisible(true);
3 ✔
996
  if (stopped) {
3 ✔
997
    // The search stopped there; more entries may match.
998
    ui->statusBar->showMessage(
×
999
        tr("Showing the first %n match(es); search for something narrower "
×
1000
           "to see the rest.",
1001
           nullptr, totalLines),
1002
        10000);
1003
  } else {
1004
    ui->statusBar->showMessage(tr("Found %n match(es)", nullptr, totalLines) +
9 ✔
1005
                                   " " +
3 ✔
1006
                                   tr("in %n entr(ies).", nullptr, entries),
6 ✔
1007
                               3000);
1008
  }
1009
  if (s.useAutoclearPanel)
3 ✔
1010
    clearPanelTimer.start();
1 ✔
1011
}
3 ✔
1012

1013
void MainWindow::on_grepResultsList_itemClicked(QTreeWidgetItem *item,
1 ✔
1014
                                                int /*column*/) {
1015
  const AppSettings s = QtPassSettings::load();
1 ✔
1016
  const QString entry = item->data(0, Qt::UserRole).toString();
1 ✔
1017
  if (entry.isEmpty())
1 ✔
1018
    return;
1019
  const QString fullPath =
1020
      QDir::cleanPath(QDir(s.passStore).filePath(entry + ".gpg"));
2 ✔
1021
  const QModelIndex proxyIndex = m_tree->indexFor(fullPath);
1 ✔
1022
  if (!proxyIndex.isValid())
1023
    return;
1024
  ui->treeView->setCurrentIndex(proxyIndex);
1 ✔
1025
  on_treeView_clicked(proxyIndex);
1 ✔
1026
  if (s.hideContent || s.useAutoclearPanel)
1 ✔
1027
    ui->grepResultsList->clear();
1 ✔
1028
  ui->grepResultsList->setVisible(false);
1 ✔
1029
  ui->treeView->setVisible(true);
1 ✔
1030
  ui->treeView->scrollTo(proxyIndex);
1 ✔
1031
  ui->treeView->setFocus();
1 ✔
1032
}
1 ✔
1033

1034
void MainWindow::selectFirstFile() {
30 ✔
1035
  // The entry named exactly as typed wins: with folders sorted first, the
1036
  // depth-first walk found team/bank before bank.
1037
  QModelIndex index = exactMatch();
30 ✔
1038
  if (!index.isValid()) {
1039
    index = firstFile(m_tree->rootIndex());
15 ✔
1040
  }
1041
  ui->treeView->setCurrentIndex(index);
30 ✔
1042
}
30 ✔
1043

1044
auto MainWindow::exactMatchPath() -> QString {
48 ✔
1045
  const QString text = QDir::fromNativeSeparators(ui->lineEdit->text());
96 ✔
1046
  const QString store = QtPassSettings::getPassStore();
96 ✔
1047
  // A name may begin or end with a space: " bank" is that entry, not bank.
1048
  // Only when no entry is named so are spaces around the text dropped.
1049
  for (const QString &typed : {text, text.trimmed()}) {
180 ✔
1050
    if (typed.isEmpty()) {
67 ✔
NEW
1051
      continue;
×
1052
    }
1053
    const QString path =
1054
        QDir::cleanPath(QDir(store).filePath(typed + QStringLiteral(".gpg")));
134 ✔
1055
    if (PathValidator::isPathInStore(store, path) && QFileInfo(path).isFile()) {
67 ✔
1056
      return path;
1057
    }
1058
  }
144 ✔
1059
  return {};
17 ✔
1060
}
1061

1062
auto MainWindow::exactMatch() -> QModelIndex {
44 ✔
1063
  const QString path = exactMatchPath();
44 ✔
1064
  if (path.isEmpty()) {
44 ✔
1065
    return {};
16 ✔
1066
  }
1067
  // indexFor() maps through the filter: a row the filter hides is no match.
1068
  const QModelIndex index = m_tree->indexFor(path);
28 ✔
1069
  if (!index.isValid() || !m_tree->fileInfo(index).isFile()) {
49 ✔
1070
    return {};
7 ✔
1071
  }
1072
  return index;
21 ✔
1073
}
1074

1075
void MainWindow::applySearchText(const QString &text) {
9 ✔
1076
  // A name search: content search, left on, kept its results over the tree
1077
  // and ignored the text.
1078
  if (ui->grepButton->isChecked()) {
9 ✔
1079
    ui->grepButton->setChecked(false);
1 ✔
1080
  }
1081
  delete m_pendingOpen;
9 ✔
1082
  ui->lineEdit->setText(text);
9 ✔
1083
  // Filter now, not after the search delay: the timer would leave the tree
1084
  // as the previous text filtered it.
1085
  searchTimer.stop();
9 ✔
1086
  onTimeoutSearch();
9 ✔
1087
  if (const QModelIndex exact = exactMatch(); exact.isValid()) {
9 ✔
1088
    openExactMatch(exact);
5 ✔
1089
    return;
5 ✔
1090
  }
1091
  // The tree loads folders in the background: at start, or right after the
1092
  // window is shown again, an entry that exists may not be in it yet. Try
1093
  // again as folders finish loading, for a few seconds, unless the search
1094
  // text changes meanwhile: any change ends the wait, even one typed back to
1095
  // this text, which is a new search that has not asked to open anything.
1096
  if (exactMatchPath().isEmpty()) {
8 ✔
1097
    return;
1098
  }
1099
  auto *pending = new QObject(this);
3 ✔
1100
  m_pendingOpen = pending;
1101
  QTimer::singleShot(5000, pending, &QObject::deleteLater);
3 ✔
1102
  // Disconnected at once: with deleteLater() alone, a folder that finished
1103
  // loading before the deletion still ran the open, or ran it twice.
1104
  const auto stop = [this, pending] {
2 ✔
1105
    disconnect(&m_tree->fileSystem(), nullptr, pending, nullptr);
2 ✔
1106
    disconnect(ui->lineEdit, nullptr, pending, nullptr);
2 ✔
1107
    pending->deleteLater();
2 ✔
1108
  };
5 ✔
1109
  connect(ui->lineEdit, &QLineEdit::textChanged, pending, stop);
3 ✔
1110
  connect(&m_tree->fileSystem(), &QFileSystemModel::directoryLoaded, pending,
3 ✔
1111
          [this, stop](const QString &) {
6 ✔
1112
            searchTimer.stop();
5 ✔
1113
            onTimeoutSearch();
5 ✔
1114
            if (const QModelIndex exact = exactMatch(); exact.isValid()) {
5 ✔
1115
              stop();
1 ✔
1116
              openExactMatch(exact);
1 ✔
1117
            }
1118
          });
5 ✔
1119
}
1120

1121
void MainWindow::openExactMatch(const QModelIndex &index) {
6 ✔
1122
  // Made current here, not left to the filter pass before: the tree may have
1123
  // moved its current row since, and with none on_treeView_clicked() only
1124
  // names the entry without decrypting it.
1125
  ui->treeView->setCurrentIndex(index);
6 ✔
1126
  on_treeView_clicked(index);
6 ✔
1127
}
6 ✔
1128

1129
auto MainWindow::firstFile(QModelIndex parentIndex) -> QModelIndex {
23 ✔
1130
  StoreModel &proxy = m_tree->proxy();
23 ✔
1131
  int numRows = proxy.rowCount(parentIndex);
23 ✔
1132
  for (int row = 0; row < numRows; ++row) {
30 ✔
1133
    QModelIndex index = proxy.index(row, 0, parentIndex);
20 ✔
1134
    if (m_tree->fileInfo(index).isFile()) {
20 ✔
1135
      return index;
13 ✔
1136
    }
1137
    if (proxy.hasChildren(index)) {
12 ✔
1138
      QModelIndex childFile = firstFile(index);
8 ✔
1139
      if (childFile.isValid())
1140
        return childFile;
5 ✔
1141
    }
1142
  }
1143
  return QModelIndex();
10 ✔
1144
}
1145

1146
// Guards the input dialogs (create, move, rename) against names like
1147
// "../../etc/passwd" or absolute paths escaping the store root.
1148
auto MainWindow::confirmPathInStore(const QString &candidate) -> bool {
11 ✔
1149
  if (PathValidator::isPathInStore(QtPassSettings::getPassStore(), candidate)) {
22 ✔
1150
    return true;
1151
  }
1152
  QMessageBox::warning(this, tr("Invalid name"),
9 ✔
1153
                       tr("That name would resolve outside the password "
3 ✔
1154
                          "store. Please choose a different name."));
1155
  return false;
3 ✔
1156
}
1157

1158
void MainWindow::setPassword(const QString &file, bool isNew) {
6 ✔
1159
  const AppSettings s = QtPassSettings::load();
6 ✔
1160
  PasswordDialog d(QtPassSettings::getPass(), s, file, isNew, this);
6 ✔
1161
  // A copy out of the editor is autocleared like one from the display.
1162
  connect(&d, &PasswordDialog::copied, &m_qtPass->clipboard(),
6 ✔
1163
          &ClipboardManager::trackCopied);
6 ✔
1164

1165
  if (isNew) {
6 ✔
1166
    const QString storePath = s.passStore;
1167
    QString folder = m_tree->currentDir(false);
1 ✔
1168
    if (folder.isEmpty()) {
1 ✔
1169
      folder = storePath;
×
1170
    }
1171
    // Folders to pick from, the tree's current one preselected. Real folders
1172
    // only: a linked or junctioned one would write the entry outside the store.
1173
    QStringList folders{QString()};
2 ✔
1174
    const QStringList found = Util::directoriesUnder(storePath);
1 ✔
1175
    for (const QString &path : found) {
16 ✔
1176
      const QString rel = QDir(storePath).relativeFilePath(path);
15 ✔
1177
      if (!rel.startsWith(u'.') && !rel.contains(QStringLiteral("/."))) {
45 ✔
1178
        folders << rel;
1179
      }
1180
    }
1181
    std::sort(folders.begin() + 1, folders.end());
1 ✔
1182
    d.setNewEntryLocation(storePath, folders,
1 ✔
1183
                          QDir(storePath).relativeFilePath(folder));
2 ✔
1184
    QHash<QString, QStringList> templates =
1185
        TemplateIO::readTemplates(storePath);
1 ✔
1186
    if (!templates.isEmpty()) {
1187
      QString defaultTemplate =
1188
          TemplateIO::getFolderTemplate(folder, storePath);
1 ✔
1189
      d.setAvailableTemplates(templates, defaultTemplate);
1 ✔
1190
    }
1191
  }
1 ✔
1192

1193
  if (!d.exec()) {
6 ✔
1194
    ui->treeView->setFocus();
5 ✔
1195
  }
1196
}
6 ✔
1197

1198
void MainWindow::addPassword() { setPassword(QString()); }
2 ✔
1199

1200
auto MainWindow::confirmDeletion(const QString &file, bool isDir) -> bool {
4 ✔
1201
  const QString path = QDir::separator() + file;
4 ✔
1202
  if (!isDir) {
4 ✔
1203
    return PlainMessageBox::askYes(
2 ✔
1204
        this, tr("Delete password?"),
2 ✔
1205
        tr("Are you sure you want to delete %1?").arg(path));
4 ✔
1206
  }
1207
  // Whole sentences, not a question stitched from pieces: a verb-final
1208
  // language cannot put the rest of the question after the path.
1209
  // Plain text, as every box quoting the store: the path is a name other
1210
  // writers control, and as rich text "a  b" would also show as "a b".
1211
  QString question =
1212
      tr("Are you sure you want to delete %1 and the whole content?").arg(path);
2 ✔
1213
  // A link, junction or special file inside is as unexpected as a stray
1214
  // plain file: the walker leaves them out of content and reports them.
1215
  QStringList skipped;
2 ✔
1216
  const QStringList content = Util::regularFilesUnder(
6 ✔
1217
      m_tree->fileSystem().rootPath() + path, {QStringLiteral("*")}, &skipped);
6 ✔
1218
  const bool unexpected =
1219
      !skipped.isEmpty() ||
2 ✔
1220
      std::any_of(content.cbegin(), content.cend(), [](const QString &entry) {
2 ✔
1221
        return QFileInfo(entry).suffix() != QLatin1String("gpg");
4 ✔
1222
      });
1223
  if (unexpected) {
1224
    question += QStringLiteral("\n\n") +
1 ✔
1225
                tr("Attention: there are unexpected files in the given "
1 ✔
1226
                   "folder, check them before continuing.");
1 ✔
1227
  }
1228
  return PlainMessageBox::askYes(this, tr("Delete folder?"), question);
4 ✔
1229
}
1230

1231
auto MainWindow::confirmLinkRemoval(const QString &file) -> bool {
1 ✔
1232
  // Only the link goes (ImitatePass::Remove unlinks it); nothing behind it
1233
  // is looked at or mentioned.
1234
  return PlainMessageBox::askYes(
1 ✔
1235
      this, tr("Delete link?"),
1 ✔
1236
      tr("%1 is a symbolic link or junction. Remove the link? What it "
1 ✔
1237
         "points to is left alone.")
1238
          .arg(QDir::separator() + file));
2 ✔
1239
}
1240

1241
void MainWindow::onDelete() {
8 ✔
1242
  const QModelIndex currentIndex = ui->treeView->currentIndex();
8 ✔
1243
  if (!currentIndex.isValid()) {
1244
    // Otherwise the whole password directory would be deleted (#556).
1245
    return;
5 ✔
1246
  }
1247

1248
  const bool isDir = !m_tree->fileInfo(currentIndex).isFile();
6 ✔
1249
  const QString file =
1250
      isDir ? m_tree->currentDir(true) : getFile(currentIndex, true);
6 ✔
1251
  const QString folder =
1252
      m_tree->fileSystem().rootPath() + QDir::separator() + file;
6 ✔
1253
  const bool linkedFolder = isDir && Util::isLinkedFolder(folder);
6 ✔
1254

1255
  if (!linkedFolder && refuseLinkedFolder(folder)) {
5 ✔
1256
    // Behind a link: deleting would reach outside the store.
1257
    return;
1258
  }
1259
  const bool confirmed =
1260
      linkedFolder ? confirmLinkRemoval(file) : confirmDeletion(file, isDir);
5 ✔
1261
  if (!confirmed) {
5 ✔
1262
    return;
1263
  }
1264
  QtPassSettings::getPass()->Remove(file, isDir);
6 ✔
1265
}
1266

1267
void MainWindow::cancelOtpRequest() {
72 ✔
1268
  m_otpRequestFile.clear();
72 ✔
1269
  m_copyRequestFile.clear();
72 ✔
1270
}
72 ✔
1271

1272
void MainWindow::onOperationError() {
26 ✔
1273
  cancelOtpRequest();
26 ✔
1274
  // executeWrapperStarted() emptied the panel and the browser when the
1275
  // operation started (a refusal says so too); what is left to forget is
1276
  // which entry the panel was about to show.
1277
  m_shownFile.clear();
26 ✔
1278
}
26 ✔
1279

1280
// Derives the code in-process from one decrypt, so it works with either
1281
// backend on every platform; otpFromFileToClipboard() finishes the job.
1282
void MainWindow::onOtp() {
10 ✔
1283
  QString file = getFile(ui->treeView->currentIndex(), true);
10 ✔
1284
  if (file.isEmpty()) {
10 ✔
1285
    flashText(tr("No password selected for OTP generation"), true);
1 ✔
1286
    return;
1 ✔
1287
  }
1288
  if (!QtPassSettings::isUseOtp()) {
9 ✔
1289
    // Normally unreachable (the action is hidden), but never fail silently.
1290
    flashText(tr("No OTP code found in this password entry"), true);
1 ✔
1291
    return;
1 ✔
1292
  }
1293

1294
  // Fast path: the panel shows a live code, so no decrypt, and one clipboard
1295
  // write (two setMimeData calls in one turn can empty the Windows
1296
  // clipboard). Only for *this* entry: arrow keys and right-click move
1297
  // currentIndex without QTreeView::clicked, so the code may be another's.
1298
  const QString shown =
1299
      (m_shownFile == file) ? m_displayPanel->currentOtpCode() : QString();
8 ✔
1300
  if (!shown.isEmpty()) {
8 ✔
1301
    m_qtPass->clipboard().copyText(shown);
1 ✔
1302
    showStatusMessage(tr("OTP code copied to clipboard"));
2 ✔
1303
    return;
1304
  }
1305

1306
  // Fallback: decrypt once. The request file keeps passShowHandler from
1307
  // copying the password and tells otpFromFileToClipboard its answer.
1308
  m_otpRequestFile = file;
7 ✔
1309
  setUiElementsEnabled(false);
7 ✔
1310
  // Keep the marker in step so a second request takes the fast path; safe as
1311
  // executeWrapperStarted() clears the panel, so a failed decrypt shows none.
1312
  m_shownFile = file;
7 ✔
1313
  QtPassSettings::getPass()->Show(file);
14 ✔
1314
}
1315

1316
void MainWindow::onEdit() {
2 ✔
1317
  QString file = getFile(ui->treeView->currentIndex(), true);
2 ✔
1318
  editPassword(file);
2 ✔
1319
}
2 ✔
1320

1321
void MainWindow::onUsers() {
2 ✔
1322
  const QString dir = m_tree->currentDir(false);
2 ✔
1323
  if (refuseLinkedFolder(dir)) {
2 ✔
1324
    return;
1325
  }
1326

1327
  UsersDialog d(QtPassSettings::getPass(), QtPassSettings::load(), dir, this);
1 ✔
1328
  if (!d.exec()) {
1 ✔
1329
    ui->treeView->setFocus();
1 ✔
1330
  }
1331
}
1 ✔
1332

1333
void MainWindow::messageAvailable(const QString &message) {
10 ✔
1334
  show();
10 ✔
1335
  raise();
10 ✔
1336
  if (message.isEmpty()) {
10 ✔
1337
    focusInput();
1 ✔
1338
  } else {
1339
    ui->treeView->expandAll();
9 ✔
1340
    applySearchText(message);
9 ✔
1341
  }
1342
}
10 ✔
1343

1344
void MainWindow::updateProfileBox() {
154 ✔
1345
  const Profiles profiles = QtPassSettings::getProfiles();
154 ✔
1346
  bool activeGone = false;
1347

1348
  if (profiles.isEmpty()) {
7 ✔
1349
    ui->profileWidget->hide();
147 ✔
1350
  } else {
1351
    ui->profileWidget->show();
7 ✔
1352
    // A refill is no choice of the user's: clearing and adding items moves
1353
    // the current text, which would otherwise switch profiles.
1354
    const QSignalBlocker quiet(ui->profileBox);
7 ✔
1355
    ui->profileBox->clear();
7 ✔
1356
    for (auto i = profiles.cbegin(); i != profiles.cend(); ++i) {
19 ✔
1357
      if (!i.key().isEmpty()) {
12 ✔
1358
        ui->profileBox->addItem(i.key());
12 ✔
1359
      }
1360
    }
1361
    ui->profileBox->model()->sort(0);
7 ✔
1362
    int index = ui->profileBox->findText(QtPassSettings::getProfile());
14 ✔
1363
    if (index != -1) { //  -1 for not found
7 ✔
1364
      ui->profileBox->setCurrentIndex(index);
6 ✔
1365
    } else if (ui->profileBox->count() > 0) {
1 ✔
1366
      // The active profile is gone (removed in Settings): the box shows the
1367
      // first one, and the settings and backend must follow it, or the
1368
      // removed profile's store stays in use behind it.
1369
      ui->profileBox->setCurrentIndex(0);
1 ✔
1370
      activeGone = true;
1371
    }
1372
  }
7 ✔
1373
  if (activeGone) {
7 ✔
1374
    on_profileBox_currentTextChanged(ui->profileBox->currentText());
2 ✔
1375
  }
1376
  updateProfileBoxEnabled();
154 ✔
1377
}
154 ✔
1378

1379
void MainWindow::updateProfileBoxEnabled() {
468 ✔
1380
  // No profile switch while anything of the store runs or waits: the
1381
  // backend's store and environment would change under it, and what is
1382
  // still queued (a push after a save, say) would finish for the other
1383
  // profile (#2071). Asked of the backend, not only of the interface: the
1384
  // watchdog releases the interface while a slow gpg or git still runs.
1385
  // Every backend: one kept from before a switch of backend may still
1386
  // run what was queued on it.
1387
  ui->profileBox->setEnabled(m_uiEnabled && ui->profileBox->count() > 1 &&
937 ✔
1388
                             QtPassSettings::backendsIdle());
11 ✔
1389
}
468 ✔
1390

1391
void MainWindow::on_profileBox_currentTextChanged(const QString &name) {
6 ✔
1392
  if (m_freshStart || name == QtPassSettings::getProfile()) {
18 ✔
1393
    return;
1 ✔
1394
  }
1395
  // The box is disabled while anything runs; should a change come through
1396
  // anyway, the active profile stays and the box says so again.
1397
  if (!m_uiEnabled || !QtPassSettings::backendsIdle()) {
5 ✔
1398
    const QSignalBlocker quiet(ui->profileBox);
×
1399
    ui->profileBox->setCurrentText(QtPassSettings::getProfile());
×
1400
    return;
1401
  }
×
1402
  // A content search runs outside the queue: leaving grep mode cancels it,
1403
  // so its results for the old store are dropped, not shown for the new.
1404
  if (m_grep.inGrepMode()) {
5 ✔
1405
    ui->grepButton->setChecked(false);
1 ✔
1406
  }
1407

1408
  ui->lineEdit->clear();
5 ✔
1409

1410
  const Profile prof = QtPassSettings::getProfiles().value(name);
10 ✔
1411
  AppSettings s = QtPassSettings::load();
5 ✔
1412
  s.activeProfile = name;
5 ✔
1413
  s.passStore = prof.path;
5 ✔
1414
  s.passSigningKey = prof.signingKey;
5 ✔
1415
  // A profile without its own Git flags keeps the global values.
1416
  s.useGit = prof.useGit.value_or(s.useGit);
5 ✔
1417
  s.autoPush = prof.autoPush.value_or(s.autoPush);
5 ✔
1418
  s.autoPull = prof.autoPull.value_or(s.autoPull);
5 ✔
1419
  QtPassSettings::save(s);
5 ✔
1420
  ui->statusBar->showMessage(tr("Profile changed to %1").arg(name), 2000);
10 ✔
1421

1422
  QtPassSettings::getPass()->updateEnv();
5 ✔
1423

1424
  m_tree->setStore(QtPassSettings::getPassStore());
10 ✔
1425
  deselect();
5 ✔
1426
  ui->treeView->setCurrentIndex(QModelIndex());
5 ✔
1427
}
5 ✔
1428

1429
void MainWindow::initTrayIcon() {
2 ✔
1430
  m_tray = new TrayIcon(this);
2 ✔
1431
  if (!m_tray->getIsAllocated()) {
2 ✔
1432
    destroyTrayIcon();
2 ✔
1433
    return;
2 ✔
1434
  }
1435
#ifndef Q_OS_MACOS
1436
  m_tray->addToggle(ui->actionShowMenuBar);
×
1437
#endif
1438
}
1439

1440
void MainWindow::destroyTrayIcon() {
2 ✔
1441
  delete m_tray;
2 ✔
1442
  m_tray = nullptr;
2 ✔
1443
}
2 ✔
1444

1445
void MainWindow::closeEvent(QCloseEvent *event) {
2 ✔
1446
  // Save in both branches: a tray user only ever hides the window, and
1447
  // used to quit through the tray menu with nothing ever written.
1448
  saveWindowState();
2 ✔
1449
  if (QtPassSettings::isHideOnClose()) {
2 ✔
1450
    this->hide();
2 ✔
1451
    event->ignore();
1452
  } else {
1453
    m_qtPass->clipboard().clear();
×
1454
    event->accept();
1455
    // A visible QSystemTrayIcon keeps the application alive, so
1456
    // quitOnLastWindowClosed never fires; quit explicitly.
1457
    QApplication::quit();
×
1458
  }
1459
}
2 ✔
1460

1461
auto MainWindow::eventFilter(QObject *obj, QEvent *event) -> bool {
5,884 ✔
1462
  if ((obj == ui->toolBar || obj == menuBar()) &&
5,884 ✔
1463
      event->type() == QEvent::PaletteChange) {
1464
    // Breeze gives these bars a "header" palette and, after a runtime
1465
    // light/dark switch, stamps the previous theme's colours back from a
1466
    // cached kdeglobals, hiding the toolbar icons. Deferred so we never
1467
    // re-enter the style while it is still applying its palette.
1468
    QTimer::singleShot(0, this, &MainWindow::dropStaleToolsAreaPalettes);
36 ✔
1469
  }
1470
  if (obj == ui->lineEdit && event->type() == QEvent::KeyPress) {
5,884 ✔
1471
    auto *key = dynamic_cast<QKeyEvent *>(event);
1 ✔
1472
    if (key != nullptr && key->key() == Qt::Key_Down) {
1 ✔
1473
      ui->treeView->setFocus();
1 ✔
1474
    }
1475
  }
1476
  return QObject::eventFilter(obj, event);
5,884 ✔
1477
}
1478

1479
// Only once the application palette changed (see m_themeSwitched): a bar
1480
// whose active Window lightness is far from the application's shows the
1481
// other theme.
1482
void MainWindow::dropStaleToolsAreaPalettes() {
31 ✔
1483
  if (!m_themeSwitched) {
31 ✔
1484
    return;
1485
  }
1486
  constexpr int kStaleToolsAreaLightness = 64;
1487
  // The active group on both sides: a bar's palette() reads the inactive
1488
  // group while another window has focus (the settings app, during a theme
1489
  // switch), and Breeze gives the header set different inactive colours.
1490
  const int appLightness = QApplication::palette()
54 ✔
1491
                               .color(QPalette::Active, QPalette::Window)
1492
                               .lightness();
27 ✔
1493
  for (QWidget *bar : {static_cast<QWidget *>(ui->toolBar),
108 ✔
1494
                       static_cast<QWidget *>(menuBar())}) {
81 ✔
1495
    if (!bar->testAttribute(Qt::WA_SetPalette)) {
54 ✔
1496
      continue;
48 ✔
1497
    }
1498
    const int barLightness =
1499
        bar->palette().color(QPalette::Active, QPalette::Window).lightness();
12 ✔
1500
    if (qAbs(barLightness - appLightness) <= kStaleToolsAreaLightness) {
6 ✔
1501
      continue;
2 ✔
1502
    }
1503
    bar->setPalette(QPalette());
4 ✔
1504
    // Both bars are transparent and the style paints the tools area from the
1505
    // stale palette, so fill our own. Window, not their Button role, which is
1506
    // not the window colour in either theme.
1507
    bar->setBackgroundRole(QPalette::Window);
4 ✔
1508
    bar->setAutoFillBackground(true);
4 ✔
1509
  }
1510
}
1511

1512
void MainWindow::keyPressEvent(QKeyEvent *event) {
18 ✔
1513
  switch (event->key()) {
18 ✔
1514
  case Qt::Key_Delete:
1 ✔
1515
    onDelete();
1 ✔
1516
    break;
1 ✔
1517
  case Qt::Key_Return:
1 ✔
1518
  case Qt::Key_Enter:
1519
    if (m_tree->proxy().rowCount() > 0) {
1 ✔
1520
      on_treeView_clicked(ui->treeView->currentIndex());
1 ✔
1521
    }
1522
    break;
1523
  case Qt::Key_Escape:
3 ✔
1524
    ui->lineEdit->clear();
3 ✔
1525
    break;
3 ✔
1526
  default:
1527
    break;
1528
  }
1529
}
18 ✔
1530

1531
void MainWindow::addShareMenu(QMenu &contextMenu, const AppSettings &s) {
9 ✔
1532
  const QString dirPath = QDir::cleanPath(m_tree->currentDir(false));
9 ✔
1533
  auto *shareMenu = new QMenu(tr("Share"), &contextMenu);
9 ✔
1534
  contextMenu.addMenu(shareMenu);
9 ✔
1535

1536
  const QString gpgIdPath = Pass::getGpgIdPath(dirPath, s.passStore);
9 ✔
1537
  const bool gpgIdExists = !gpgIdPath.isEmpty() && QFile(gpgIdPath).exists();
9 ✔
1538
  const QString exePath = s.usePass ? s.passExecutable : s.gpgExecutable;
9 ✔
1539
  const bool gpgAvailable =
1540
      !exePath.isEmpty() &&
18 ✔
1541
      (Executor::parseWslCommand(exePath) || QFile(exePath).exists());
18 ✔
1542

1543
  QAction *reencrypt = shareMenu->addAction(tr("Re-encrypt all passwords"));
9 ✔
1544
  reencrypt->setEnabled(gpgIdExists && gpgAvailable);
9 ✔
1545
  connect(reencrypt, &QAction::triggered, this,
9 ✔
1546
          [this, dirPath]() { reencryptPath(dirPath); });
30 ✔
1547

1548
  QAction *exportKey = shareMenu->addAction(tr("Export my public key..."));
9 ✔
1549
  exportKey->setEnabled(gpgAvailable);
9 ✔
1550
  connect(exportKey, &QAction::triggered, this, &MainWindow::exportPublicKey);
9 ✔
1551

1552
  QAction *addRecipientAction = shareMenu->addAction(tr("Add recipient..."));
9 ✔
1553
  addRecipientAction->setEnabled(gpgIdExists && gpgAvailable);
9 ✔
1554
  connect(addRecipientAction, &QAction::triggered, this,
9 ✔
1555
          [this, dirPath]() { addRecipient(dirPath); });
29 ✔
1556

1557
  QAction *shareHelp = shareMenu->addAction(tr("What is this?"));
9 ✔
1558
  connect(shareHelp, &QAction::triggered, this, &MainWindow::showShareHelp);
9 ✔
1559
}
9 ✔
1560

1561
void MainWindow::showContextMenu(const QPoint &pos) {
11 ✔
1562
  const AppSettings s = QtPassSettings::load();
11 ✔
1563
  const QModelIndex index = ui->treeView->indexAt(pos);
11 ✔
1564
  const bool selected = index.isValid();
1565
  if (!selected) {
1566
    ui->treeView->clearSelection();
1 ✔
1567
    ui->actionDelete->setEnabled(false);
1 ✔
1568
    ui->actionEdit->setEnabled(false);
1 ✔
1569
  }
1570
  ui->treeView->setCurrentIndex(index);
11 ✔
1571
  const QPoint globalPos = ui->treeView->viewport()->mapToGlobal(pos);
11 ✔
1572
  const QFileInfo fileOrFolder = m_tree->fileInfo(ui->treeView->currentIndex());
11 ✔
1573
  const bool isDir = fileOrFolder.isDir();
11 ✔
1574

1575
  QMenu contextMenu;
11 ✔
1576
  if (!selected || isDir) {
11 ✔
1577
    const std::array<std::pair<QString, void (MainWindow::*)()>, 4> onFolder{{
1578
        {tr("Open folder with file manager"), &MainWindow::openFolder},
10 ✔
1579
        {tr("Add folder"), &MainWindow::addFolder},
10 ✔
1580
        {tr("Add password"), &MainWindow::addPassword},
10 ✔
1581
        {tr("Users"), &MainWindow::onUsers},
10 ✔
1582
    }};
×
1583
    for (const auto &[text, slot] : onFolder) {
50 ✔
1584
      connect(contextMenu.addAction(text), &QAction::triggered, this, slot);
40 ✔
1585
    }
1586
  } else if (fileOrFolder.isFile()) {
1 ✔
1587
    connect(contextMenu.addAction(tr("Edit")), &QAction::triggered, this,
1 ✔
1588
            &MainWindow::onEdit);
2 ✔
1589
  }
1590
  if (selected) {
11 ✔
1591
    contextMenu.addSeparator();
10 ✔
1592
    if (isDir) {
10 ✔
1593
      connect(contextMenu.addAction(tr("Rename folder")), &QAction::triggered,
9 ✔
1594
              this, &MainWindow::renameFolder);
18 ✔
1595
    } else if (fileOrFolder.isFile()) {
1 ✔
1596
      connect(contextMenu.addAction(tr("Rename password")), &QAction::triggered,
1 ✔
1597
              this, &MainWindow::renamePassword);
2 ✔
1598
    }
1599
    connect(contextMenu.addAction(tr("Delete")), &QAction::triggered, this,
10 ✔
1600
            &MainWindow::onDelete);
10 ✔
1601
    if (isDir) {
10 ✔
1602
      addShareMenu(contextMenu, s);
9 ✔
1603
    }
1604
  }
1605
  contextMenu.exec(globalPos);
11 ✔
1606
}
11 ✔
1607

1608
void MainWindow::showBrowserContextMenu(const QPoint &pos) {
1 ✔
1609
  QMenu *contextMenu = ui->textBrowser->createStandardContextMenu(pos);
1 ✔
1610
  // Reparent from textBrowser: a browser stylesheet cascades to the child
1611
  // QMenu and breaks its opaque native background.
1612
  contextMenu->setParent(this, contextMenu->windowFlags());
1 ✔
1613
  QPoint globalPos = ui->textBrowser->viewport()->mapToGlobal(pos);
1 ✔
1614

1615
  contextMenu->exec(globalPos);
1 ✔
1616
  delete contextMenu;
1 ✔
1617
}
1 ✔
1618

1619
void MainWindow::openFolder() {
1 ✔
1620
  QString dir = m_tree->currentDir(false);
1 ✔
1621

1622
  QString path = QDir::toNativeSeparators(dir);
1 ✔
1623
  QDesktopServices::openUrl(QUrl::fromLocalFile(path));
1 ✔
1624
}
1 ✔
1625

1626
void MainWindow::addFolder() {
8 ✔
1627
  const AppSettings s = QtPassSettings::load();
8 ✔
1628
  bool ok;
1629
  QString dir = m_tree->currentDir(false);
8 ✔
1630
  QString newdir =
1631
      QInputDialog::getText(this, tr("New folder"),
8 ✔
1632
                            tr("New folder: \n(Will be placed in %1 )")
8 ✔
1633
                                .arg(s.passStore + m_tree->currentDir(true)),
16 ✔
1634
                            QLineEdit::Normal, "", &ok);
16 ✔
1635
  if (!ok || newdir.isEmpty()) {
8 ✔
1636
    return;
1637
  }
1638
  // Checked and created as one and the same path: the check resolves ".."
1639
  // lexically, the system after following links, so "link/../x" would pass
1640
  // as the store's x and be made beside the link's target.
1641
  newdir = QDir::cleanPath(newdir.prepend(dir));
7 ✔
1642
  if (!confirmPathInStore(newdir)) {
7 ✔
1643
    return;
1644
  }
1645
  // Behind a link the folder would be made outside the store, as Users,
1646
  // Re-encrypt and Delete already refuse.
1647
  if (refuseLinkedFolder(newdir)) {
6 ✔
1648
    return;
1649
  }
1650
  // The tree, like `pass ls`, hides names that start with a dot.
1651
  const QStringList parts =
1652
      QDir(s.passStore).relativeFilePath(newdir).split(u'/');
5 ✔
1653
  if (std::any_of(parts.cbegin(), parts.cend(), [](const QString &part) {
10 ✔
1654
        return part != u'.' && part.startsWith(u'.');
5 ✔
1655
      })) {
1656
    PlainMessageBox::warning(this, tr("Hidden folder"),
2 ✔
1657
                             tr("A folder that starts with a dot would be "
1 ✔
1658
                                "hidden from the list: %1")
1659
                                 .arg(newdir));
2 ✔
1660
    return;
1 ✔
1661
  }
1662
  // Exists already: an error, as QDir::mkdir() made it before.
1663
  if (QFileInfo::exists(newdir) || !Util::mkpathForStore(newdir)) {
4 ✔
1664
    PlainMessageBox::warning(this, tr("Error"),
2 ✔
1665
                             tr("Failed to create folder: %1").arg(newdir));
2 ✔
1666
    return;
1 ✔
1667
  }
1668
  // With a signing key, ImitatePass::loadVerifiedRecipients and pass
1669
  // (PASSWORD_STORE_SIGNING_KEY) refuse a .gpg-id without .gpg-id.sig, and
1670
  // signing needs a passphrase just to make a folder. So it inherits the
1671
  // parent's signed list; UsersDialog (Init) gives it its own.
1672
  const bool signingConfigured = !s.passSigningKey.trimmed().isEmpty();
3 ✔
1673
  if (s.addGPGId && !signingConfigured) {
3 ✔
1674
    // Seed from the parent's recipients in effect, not from `enabled` keys:
1675
    // that flag is only set in UsersDialog, so it left a zero-byte .gpg-id
1676
    // shadowing the parent's recipients (#1682).
1677
    if (!Pass::seedGpgIdFile(newdir, s.passStore)) {
3 ✔
1678
      PlainMessageBox::warning(
1 ✔
1679
          this, tr("Error"),
1 ✔
1680
          tr("Failed to create .gpg-id file in: %1").arg(newdir));
2 ✔
1681
      return;
1 ✔
1682
    }
1683
  }
1684
}
8 ✔
1685

1686
void MainWindow::renameFolder() {
3 ✔
1687
  bool ok;
1688
  QString srcDir = QDir::cleanPath(m_tree->currentDir(false));
3 ✔
1689
  QString srcDirName = QDir(srcDir).dirName();
3 ✔
1690
  QString newName =
1691
      QInputDialog::getText(this, tr("Rename folder"), tr("Rename folder to: "),
3 ✔
1692
                            QLineEdit::Normal, srcDirName, &ok);
6 ✔
1693
  if (!ok || newName.isEmpty()) {
3 ✔
1694
    return;
1695
  }
1696
  QString destDir = srcDir;
1697
  destDir.replace(srcDir.lastIndexOf(srcDirName), srcDirName.length(), newName);
2 ✔
1698
  if (!confirmPathInStore(destDir)) {
2 ✔
1699
    return;
1700
  }
1701
  QtPassSettings::getPass()->Move(srcDir, destDir, false);
3 ✔
1702
}
1703

1704
void MainWindow::editPassword(const QString &file) {
5 ✔
1705
  if (!file.isEmpty()) {
5 ✔
1706
    const AppSettings s = QtPassSettings::load();
5 ✔
1707
    if (s.useGit && s.autoPull) {
5 ✔
1708
      onUpdate(true);
1 ✔
1709
    }
1710
    // The dialog decrypts the entry itself to fill its fields. That decrypt
1711
    // lands on the same finishedShow the panel uses, so drop the panel's claim
1712
    // to it: otherwise passShowHandler() repaints and, with "Always copy",
1713
    // puts the entry's old password on the clipboard - replacing whatever the
1714
    // user copied to paste into the dialog.
1715
    m_shownFile.clear();
5 ✔
1716
    setPassword(file, false);
5 ✔
1717
  }
5 ✔
1718
}
5 ✔
1719

1720
void MainWindow::renamePassword() {
2 ✔
1721
  bool ok;
1722
  QString file = getFile(ui->treeView->currentIndex(), false);
2 ✔
1723
  QString filePath = QFileInfo(file).path();
2 ✔
1724
  QString fileName = QFileInfo(file).fileName();
2 ✔
1725
  if (fileName.endsWith(".gpg", Qt::CaseInsensitive)) {
4 ✔
1726
    fileName.chop(4);
2 ✔
1727
  }
1728

1729
  QString newName =
1730
      QInputDialog::getText(this, tr("Rename file"), tr("Rename file to: "),
2 ✔
1731
                            QLineEdit::Normal, fileName, &ok);
4 ✔
1732
  if (!ok || newName.isEmpty()) {
2 ✔
1733
    return;
1734
  }
1735
  QString newFile = QDir(filePath).filePath(newName);
2 ✔
1736
  if (!confirmPathInStore(newFile)) {
2 ✔
1737
    return;
1738
  }
1739
  QtPassSettings::getPass()->Move(file, newFile, false);
3 ✔
1740
}
1741

1742
void MainWindow::copyPasswordFromTreeview() {
4 ✔
1743
  QFileInfo fileOrFolder = m_tree->fileInfo(ui->treeView->currentIndex());
4 ✔
1744

1745
  if (fileOrFolder.isFile()) {
4 ✔
1746
    QString file = getFile(ui->treeView->currentIndex(), true);
4 ✔
1747
    // The newest Ctrl+C wins: finishedShow names its file, so the decrypt of
1748
    // an earlier request is simply not this one's.
1749
    m_copyRequestFile = file;
4 ✔
1750
    // This Show repaints the panel as well; see onOtp().
1751
    m_shownFile = file;
4 ✔
1752
    QtPassSettings::getPass()->Show(file);
8 ✔
1753
  }
1754
}
4 ✔
1755

1756
void MainWindow::passwordFromFileToClipboard(const QString &text,
17 ✔
1757
                                             const QString &file) {
1758
  if (m_copyRequestFile.isEmpty() || file != m_copyRequestFile) {
17 ✔
1759
    return;
15 ✔
1760
  }
1761
  m_copyRequestFile.clear();
3 ✔
1762
  // The first line, without a list of every line (an entry can expand into
1763
  // millions of them); left(-1) is the whole text when there is no newline.
1764
  const QString first = text.left(text.indexOf(QLatin1Char('\n')));
3 ✔
1765
  // A `pass otp insert` entry's first line is the otpauth:// URI carrying the
1766
  // TOTP seed; copying it would leak 2FA material. Matches the display path
1767
  // (FileContent::getPasswordForDisplay / PasswordDisplayPanel).
1768
  if (FileContent::isOtpUriValue(first)) {
3 ✔
1769
    flashText(tr("This entry holds an OTP secret, not a password"), true);
2 ✔
1770
    return;
1771
  }
1772
  m_qtPass->clipboard().copyText(first);
2 ✔
1773
}
1774

1775
void MainWindow::showStatusMessage(const QString &msg, int timeout) {
21 ✔
1776
  ui->statusBar->showMessage(msg, timeout);
21 ✔
1777
}
21 ✔
1778

1779
void MainWindow::reencryptPath(const QString &dir) {
3 ✔
1780
  QDir checkDir(dir);
3 ✔
1781
  if (!checkDir.exists()) {
3 ✔
1782
    PlainMessageBox::critical(this, tr("Error"),
2 ✔
1783
                              tr("Directory does not exist: %1").arg(dir));
2 ✔
1784
    return;
1 ✔
1785
  }
1786
  if (refuseLinkedFolder(dir)) {
2 ✔
1787
    return;
1788
  }
1789

1790
  const bool yes = PlainMessageBox::askYes(
2 ✔
1791
      this, tr("Re-encrypt passwords"),
2 ✔
1792
      tr("Re-encrypt all passwords in %1?\n\n"
2 ✔
1793
         "This will re-encrypt ALL password files in this folder "
1794
         "using the current recipients defined in .gpg-id.\n\n"
1795
         "This may rewrite many files and cannot be undone easily.\n\n"
1796
         "Continue?")
1797
          .arg(QDir(dir).dirName()));
4 ✔
1798

1799
  if (!yes)
2 ✔
1800
    return;
1801

1802
  // Disable now; the asynchronous startReencryptPath signal re-runs this
1803
  // harmlessly.
1804
  startReencryptPath();
1 ✔
1805

1806
  // Under the current profile's settings: with the pass backend active, the
1807
  // native one is not re-initialised on a profile switch.
1808
  QtPassSettings::getImitatePass()->reencryptPath(
2 ✔
1809
      QDir::cleanPath(QDir(dir).absolutePath()), QtPassSettings::load());
2 ✔
1810
}
3 ✔
1811

1812
// Idempotent: reencryptPath() calls it before ImitatePass emits the signal.
1813
void MainWindow::startReencryptPath() {
6 ✔
1814
  m_reencryptRunning = true;
6 ✔
1815
  setUiElementsEnabled(false);
6 ✔
1816
  // The worker always ends with endReencryptPath(), and Cancel is available
1817
  // throughout, so the generic watchdog is not needed for this operation.
1818
  m_uiWatchdog.stop();
6 ✔
1819
  ui->treeView->setDisabled(true);
6 ✔
1820
  if (m_reencryptProgress)
6 ✔
1821
    return;
1822
  auto *progress = new QProgressDialog(tr("Re-encrypting passwords..."),
4 ✔
1823
                                       tr("Cancel"), 0, 0, this);
8 ✔
1824
  progress->setWindowTitle(tr("Re-encrypt passwords"));
4 ✔
1825
  progress->setWindowModality(Qt::WindowModal);
4 ✔
1826
  progress->setAutoClose(false);
4 ✔
1827
  progress->setAutoReset(false);
4 ✔
1828
  progress->setMinimumDuration(0);
4 ✔
1829
  connect(progress, &QProgressDialog::canceled, this, [this]() {
4 ✔
1830
    QtPassSettings::getImitatePass()->cancelReencryptPath();
1 ✔
1831
    showStatusMessage(tr("Cancelling re-encryption"), 5000);
1 ✔
1832
  });
1 ✔
1833
  m_reencryptProgress = progress;
1834
  progress->show();
4 ✔
1835
}
1836

1837
void MainWindow::reencryptProgress(int current, int total) {
5 ✔
1838
  if (!m_reencryptProgress)
5 ✔
1839
    return;
1840
  m_reencryptProgress->setMaximum(total);
4 ✔
1841
  m_reencryptProgress->setLabelText(
4 ✔
1842
      tr("Re-encrypting passwords: %1 of %2").arg(current).arg(total));
8 ✔
1843
  // On a modal dialog setValue() runs processEvents(), which can deliver
1844
  // endReencryptPath() and reset m_reencryptProgress: keep this last.
1845
  m_reencryptProgress->setValue(current);
4 ✔
1846
}
1847

1848
void MainWindow::endReencryptPath() {
4 ✔
1849
  m_reencryptRunning = false;
4 ✔
1850
  if (m_reencryptProgress) {
4 ✔
1851
    m_reencryptProgress->hide();
4 ✔
1852
    m_reencryptProgress->deleteLater();
4 ✔
1853
    m_reencryptProgress = nullptr;
1854
  }
1855
  setUiElementsEnabled(true);
4 ✔
1856
}
4 ✔
1857

1858
void MainWindow::exportPublicKey() {
3 ✔
1859
  const AppSettings s = QtPassSettings::load();
3 ✔
1860
  const QString identity = s.passSigningKey;
1861
  if (identity.isEmpty()) {
3 ✔
1862
    QMessageBox::information(
2 ✔
1863
        this, tr("Export public key"),
1 ✔
1864
        tr("<h3>Export your public key</h3>"
×
1865
           "<p>No signing key is configured. Set one in QtPass Settings "
1866
           "&gt; GPG keys, or run this in a terminal:</p>"
1867
           "<pre>gpg --armor --export --output my_key.asc &lt;your-key-id"
1868
           "&gt;</pre>"
1869
           "<p>Then send the file to your teammates.</p>"));
1870
    return;
1 ✔
1871
  }
1872
  QString gpgExe = s.gpgExecutable;
1873
  if (gpgExe.isEmpty()) {
2 ✔
1874
    gpgExe = QStringLiteral("gpg");
×
1875
  }
1876
  QStringList args = {"--armor", "--export"};
10 ✔
1877
  args.append(identity.split(' ', Qt::SkipEmptyParts));
2 ✔
1878
  QString stdOut;
2 ✔
1879
  QString stdErr;
2 ✔
1880
  int exitCode = Executor::executeBlocking(gpgExe, args, &stdOut, &stdErr);
2 ✔
1881
  if (exitCode != 0 || stdOut.isEmpty()) {
2 ✔
1882
    PlainMessageBox::warning(this, tr("Export public key"),
2 ✔
1883
                             tr("Could not export public key for %1.\n\n%2")
1 ✔
1884
                                 .arg(identity, stdErr.isEmpty()
2 ✔
1885
                                                    ? tr("No output from gpg.")
2 ✔
1886
                                                    : stdErr));
1887
    return;
1888
  }
1889
  ExportPublicKeyDialog dialog(identity, stdOut, this);
1 ✔
1890
  dialog.exec();
1 ✔
1891
}
4 ✔
1892

1893
// UsersDialog only ticks keys already in the keyring; importing a foreign
1894
// key still has to happen via gpg (or QtPass settings) first.
1895
void MainWindow::addRecipient(const QString &dir) {
2 ✔
1896
  if (refuseLinkedFolder(dir)) {
2 ✔
1897
    return;
1 ✔
1898
  }
1899
  UsersDialog d(QtPassSettings::getPass(), QtPassSettings::load(), dir, this);
1 ✔
1900
  d.exec();
1 ✔
1901
}
1 ✔
1902

1903
// A tree-picked folder that is, or lies behind, a symlink or junction is not
1904
// a folder of the store. The store root itself may be a link (a synced
1905
// folder); that is configuration, not a tree pick.
1906
auto MainWindow::refuseLinkedFolder(const QString &dir) -> bool {
17 ✔
1907
  if (!Util::isUnderLink(dir, QtPassSettings::load().passStore)) {
17 ✔
1908
    return false;
1909
  }
1910
  PlainMessageBox::critical(
4 ✔
1911
      this, tr("Not a folder of the store"),
4 ✔
1912
      tr("%1 is, or lies behind, a symbolic link or junction. What that "
4 ✔
1913
         "points to is not part of the password store and is left alone.")
1914
          .arg(QDir::toNativeSeparators(QDir::cleanPath(dir))));
8 ✔
1915
  return true;
4 ✔
1916
}
1917

1918
void MainWindow::showShareHelp() {
1 ✔
1919
  QMessageBox::information(
2 ✔
1920
      this, tr("Sharing passwords with GPG"),
1 ✔
1921
      tr("<h3>Sharing passwords with GPG</h3>"
1 ✔
1922
         "<p>To share passwords with other users:</p>"
1923
         "<ol>"
1924
         "<li><b>Export your public key</b> and send it to teammates</li>"
1925
         "<li><b>Import teammates' public keys</b> into your GPG keyring</li>"
1926
         "<li><b>Re-encrypt passwords</b> so all recipients can decrypt "
1927
         "them</li>"
1928
         "</ol>"
1929
         "<p>Only people who have a matching secret key can decrypt the "
1930
         "passwords.</p>"
1931
         "<p><b>Tip:</b> Use the same GPG key for all shared folders.</p>"
1932
         "<p>See the FAQ for more details.</p>"));
1933
}
1 ✔
1934

1935
void MainWindow::updateGitButtonVisibility(bool uiEnabled) {
289 ✔
1936
  const AppSettings s = QtPassSettings::load();
289 ✔
1937
  // Without Git there is nothing to push or pull, ever: the buttons go, not
1938
  // grey out. While an operation runs they stay and are disabled.
1939
  const bool usable =
1940
      s.useGit && !(s.gitExecutable.isEmpty() && s.passExecutable.isEmpty());
289 ✔
1941
  ui->actionPush->setVisible(usable);
289 ✔
1942
  ui->actionUpdate->setVisible(usable);
289 ✔
1943
  // The separator in front of them would otherwise sit next to the next one.
1944
  const QList<QAction *> actions = ui->toolBar->actions();
289 ✔
1945
  const qsizetype at = actions.indexOf(ui->actionPush);
289 ✔
1946
  if (at > 0 && actions.at(at - 1)->isSeparator()) {
289 ✔
1947
    actions.at(at - 1)->setVisible(usable);
289 ✔
1948
  }
1949
  enableGitButtons(usable && uiEnabled);
289 ✔
1950
}
289 ✔
1951

1952
void MainWindow::updateOtpButtonVisibility(bool uiEnabled) {
289 ✔
1953
  // No platform gating: codes are generated in-process. Visible but disabled
1954
  // when OTP is off: the panel never shows an OTP field (a secret), so hiding
1955
  // this too would leave no trace of the feature. Honour uiEnabled, or the
1956
  // user can stack Show calls while a decrypt is in flight.
1957
  ui->actionOtp->setVisible(true);
289 ✔
1958
  ui->actionOtp->setEnabled(QtPassSettings::isUseOtp() && uiEnabled);
302 ✔
1959
}
289 ✔
1960

1961
void MainWindow::updateGrepButtonVisibility() {
150 ✔
1962
  const bool enabled = QtPassSettings::isUseGrepSearch();
150 ✔
1963
  ui->grepButton->setVisible(enabled);
150 ✔
1964
  ui->grepCaseButton->setVisible(enabled);
150 ✔
1965
  if (!enabled && m_grep.inGrepMode()) {
150 ✔
1966
    ui->grepButton->setChecked(false);
1 ✔
1967
  }
1968
}
150 ✔
1969

1970
void MainWindow::enableGitButtons(const bool &state) {
289 ✔
1971
  ui->actionPush->setEnabled(state);
289 ✔
1972
  ui->actionUpdate->setEnabled(state);
289 ✔
1973
}
289 ✔
1974

1975
void MainWindow::critical(const QString &title, const QString &msg) {
3 ✔
1976
  // Pass's messages quote store paths; see PlainMessageBox.
1977
  PlainMessageBox::critical(this, title, msg);
3 ✔
1978
}
3 ✔
1979

1980
void MainWindow::onProcessOutput(const QString &output, bool isError,
6 ✔
1981
                                 Enums::PROCESS pid) {
1982
  if (!QtPassSettings::isShowProcessOutput()) {
6 ✔
1983
    return;
1984
  }
1985
  m_processOutput->append(output, isError,
5 ✔
1986
                          ProcessOutputPanel::processName(pid));
10 ✔
1987
}
1988

1989
void MainWindow::updateProcessOutputVisibility() {
3 ✔
1990
  // The action's toggled handler shows or hides the dock.
1991
  ui->actionShowProcessOutput->setChecked(
3 ✔
1992
      QtPassSettings::isShowProcessOutput());
3 ✔
1993
  m_processOutput->setVisible(QtPassSettings::isShowProcessOutput());
3 ✔
1994
}
3 ✔
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