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

IJHack / QtPass / 43637362390

14 Nov 2026 08:24PM UTC coverage: 96.257% (-0.04%) from 96.295%
43637362390

push

github

web-flow
Search: on a case-insensitive file system, match the entry as stored (#2172)

* tests: stage waits through the tree's proxy; case-insensitive exact match

- The staged-wait helpers look entries up through the tree's proxy, as
  exactMatch() does, instead of in the source model alone, which kept a
  name-filtered entry indexable on macOS.
- exactMatchFollowsACaseInsensitiveFileSystem: where the file system
  ignores case, "Bank" should open bank.gpg, not the first match.

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

* Search: on a case-insensitive file system, match the entry as stored

Where the file system ignores case, "Bank.gpg" exists while the file is
bank.gpg. The exact match then asked the tree for Bank.gpg, and on macOS
QFileSystemModel::index() added that spelling as a second, phantom entry
and selected it. exactMatchPath() now spells each part of the path as
stored on disk, so "Bank" selects bank.gpg. The macOS job showed the new
test failing without this.

The staged-wait test helpers walk the tree's rows instead of calling
index(path), which made a name-filtered entry visible again on macOS.
The tests skip at once where the open still does not wait, instead of
polling for 5 s first.

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

---------

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

14 of 18 new or added lines in 1 file covered. (77.78%)

8512 of 8843 relevant lines covered (96.26%)

487.46 hits per line

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

97.47
/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)
148 ✔
66
    : QMainWindow(parent), ui(new Ui::MainWindow) {
148 ✔
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);
148 ✔
73

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

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

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

89
  initTextBrowser();
148 ✔
90

91
  updateProfileBox();
148 ✔
92

93
  initDisplayPanel();
148 ✔
94

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

97
  // Install the search-box key filter once, not on every setUiElementsEnabled
98
  // call.
99
  ui->lineEdit->installEventFilter(this);
148 ✔
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);
148 ✔
103
  menuBar()->installEventFilter(this);
148 ✔
104

105
  initTimers();
148 ✔
106

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

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

114
  setUiElementsEnabled(true);
148 ✔
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();
148 ✔
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())) {
149 ✔
122
    if (!config()) {
2 ✔
123
      return;
124
    }
125
  }
126
  m_freshStart = false;
147 ✔
127
  m_initSucceeded = true;
147 ✔
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()) {
147 ✔
135
    QTimer::singleShot(0, this,
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() {
148 ✔
145
  connect(m_qtPass, &QtPass::outputReady, this,
148 ✔
146
          [this](const QString &html) { flashText(html, false, true); });
178 ✔
147
  connect(m_qtPass, &QtPass::operationFinished, this,
148 ✔
148
          [this]() { setUiElementsEnabled(true); });
179 ✔
149
  connect(m_qtPass, &QtPass::statusMessage, this,
148 ✔
150
          &MainWindow::showStatusMessage);
148 ✔
151
  connect(m_qtPass, &QtPass::pushRequested, this, &MainWindow::onPush);
148 ✔
152
  connect(m_qtPass, &QtPass::entryInserted, this,
148 ✔
153
          [this]() { on_treeView_clicked(getCurrentTreeViewIndex()); });
149 ✔
154
  connect(&m_qtPass->clipboard(), &ClipboardManager::statusMessage, this,
148 ✔
155
          [this](const QString &message) { showStatusMessage(message); });
158 ✔
156
  // Both backends: the active one can change through the configuration
157
  // dialog without a restart.
158
  connectPassSignals(QtPassSettings::getRealPass());
148 ✔
159
  connectPassSignals(QtPassSettings::getImitatePass());
148 ✔
160
  ImitatePass *ipass = QtPassSettings::getImitatePass();
148 ✔
161
  connect(ipass, &ImitatePass::startReencryptPath, this,
148 ✔
162
          &MainWindow::startReencryptPath);
148 ✔
163
  connect(ipass, &ImitatePass::reencryptProgress, this,
148 ✔
164
          &MainWindow::reencryptProgress);
148 ✔
165
  connect(ipass, &ImitatePass::endReencryptPath, this,
148 ✔
166
          &MainWindow::endReencryptPath);
148 ✔
167
}
148 ✔
168

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

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

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

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

214
  connect(&searchTimer, &QTimer::timeout, this, &MainWindow::onTimeoutSearch);
148 ✔
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);
148 ✔
219
  m_uiWatchdog.setInterval(UiWatchdogMs);
148 ✔
220
  connect(&m_uiWatchdog, &QTimer::timeout, this, [this]() {
148 ✔
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
}
148 ✔
228

229
void MainWindow::initProcessOutput() {
148 ✔
230
  m_processOutput = new ProcessOutputPanel(this);
148 ✔
231
  addDockWidget(Qt::BottomDockWidgetArea, m_processOutput);
148 ✔
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());
148 ✔
235
  // From the setting, not isVisible(): the window is not shown yet, so no
236
  // child of it reports visible.
237
  ui->actionShowProcessOutput->setChecked(
148 ✔
238
      QtPassSettings::isShowProcessOutput());
148 ✔
239
  connect(ui->actionShowProcessOutput, &QAction::toggled, this,
148 ✔
240
          [this](bool show) {
148 ✔
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,
148 ✔
250
          [this](const QString &out, const QString &err, Enums::PROCESS pid) {
148 ✔
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
}
148 ✔
268

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

276
// The signals of one backend that the window answers itself.
277
void MainWindow::connectPassSignals(Pass *pass) {
296 ✔
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);
296 ✔
281
  connect(pass, &Pass::critical, this, &MainWindow::critical);
296 ✔
282
  connect(pass, &Pass::startingExecuteWrapper, this,
296 ✔
283
          &MainWindow::executeWrapperStarted);
296 ✔
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);
296 ✔
287
  connect(pass, &Pass::statusMsg, this, &MainWindow::showStatusMessage);
296 ✔
288
  connect(pass, &Pass::finishedShow, this, &MainWindow::passShowHandler);
296 ✔
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);
296 ✔
292
  connect(pass, &Pass::finishedShow, this,
296 ✔
293
          &MainWindow::passwordFromFileToClipboard);
296 ✔
294
  connect(pass, &Pass::finishedGrep, this, &MainWindow::onGrepFinished);
296 ✔
295
}
296 ✔
296

297
// Idempotent; called from closeEvent() and the destructor.
298
void MainWindow::saveWindowState() {
150 ✔
299
  QtPassSettings::setGeometry(saveGeometry());
150 ✔
300
  QtPassSettings::setSavestate(saveState());
150 ✔
301
}
150 ✔
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,575 ✔
323
  if (event->type() == QEvent::ApplicationPaletteChange) {
6,575 ✔
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,575 ✔
330
}
331

332
void MainWindow::changeEvent(QEvent *event) {
198 ✔
333
  QWidget::changeEvent(event);
198 ✔
334
  if (event->type() == QEvent::PaletteChange && m_displayPanel != nullptr) {
198 ✔
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() &&
198 ✔
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
}
198 ✔
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() {
148 ✔
362
  connect(ui->actionAddPassword, &QAction::triggered, this,
148 ✔
363
          &MainWindow::addPassword);
148 ✔
364
  connect(ui->actionAddFolder, &QAction::triggered, this,
148 ✔
365
          &MainWindow::addFolder);
148 ✔
366
  connect(ui->actionEdit, &QAction::triggered, this, &MainWindow::onEdit);
148 ✔
367
  connect(ui->actionDelete, &QAction::triggered, this, &MainWindow::onDelete);
148 ✔
368
  connect(ui->actionPush, &QAction::triggered, this, &MainWindow::onPush);
148 ✔
369
  connect(ui->actionUpdate, &QAction::triggered, this, &MainWindow::onUpdate);
148 ✔
370
  connect(ui->actionUsers, &QAction::triggered, this, &MainWindow::onUsers);
148 ✔
371
  connect(ui->actionConfig, &QAction::triggered, this, &MainWindow::onConfig);
148 ✔
372
  connect(ui->actionOtp, &QAction::triggered, this, &MainWindow::onOtp);
148 ✔
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);
148 ✔
378
  connect(ui->actionClose, &QAction::triggered, this, &MainWindow::close);
148 ✔
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);
148 ✔
386
  ui->actionShowMenuBar->setChecked(QtPassSettings::load().showMenuBar);
148 ✔
387
  menuBar()->setVisible(ui->actionShowMenuBar->isChecked());
148 ✔
388
  connect(ui->actionShowMenuBar, &QAction::toggled, this, [this](bool show) {
148 ✔
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);
148 ✔
395
#endif
396
  connect(ui->actionFaq, &QAction::triggered, this, [] {
149 ✔
397
    QDesktopServices::openUrl(QUrl(QStringLiteral("https://qtpass.org/faq")));
2 ✔
398
  });
1 ✔
399
  connect(ui->actionAbout, &QAction::triggered, this, &MainWindow::showAbout);
148 ✔
400
  connect(ui->actionAboutQt, &QAction::triggered, qApp, &QApplication::aboutQt);
148 ✔
401

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

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

423
  QPixmap logo = QPixmap::fromImage(QImage(":/artwork/icon.svg"))
296 ✔
424
                     .scaledToHeight(statusBar()->height());
148 ✔
425
  auto *logoApp = new QLabel(statusBar());
148 ✔
426
  logoApp->setPixmap(logo);
148 ✔
427
  statusBar()->addPermanentWidget(logoApp);
148 ✔
428
}
148 ✔
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,
56 ✔
435
                           const bool isHtml) {
436
  if (isError) {
56 ✔
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();
49 ✔
443
    format.clearForeground();
444
    ui->textBrowser->setCurrentCharFormat(format);
49 ✔
445
  }
446

447
  if (isHtml) {
56 ✔
448
    QString _text = text;
449
    if (!ui->textBrowser->toPlainText().isEmpty()) {
94 ✔
450
      _text = ui->textBrowser->toHtml() + _text;
28 ✔
451
    }
452
    ui->textBrowser->setHtml(_text);
47 ✔
453
  } else {
454
    ui->textBrowser->setText(text);
9 ✔
455
  }
456
}
56 ✔
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() {
160 ✔
476
  const bool wantOnTop = QtPassSettings::isAlwaysOnTop();
160 ✔
477
  const Qt::WindowFlags flags = windowFlags();
478
  if (flags.testFlag(Qt::WindowStaysOnTopHint) == wantOnTop) {
160 ✔
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) {
25 ✔
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) {
25 ✔
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()) {
9 ✔
628
      setUiElementsEnabled(true);
7 ✔
629
    }
630
    return;
9 ✔
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,
21 ✔
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) {
21 ✔
687
    return;
18 ✔
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() {
157 ✔
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();
314 ✔
792
  if (geometry.isEmpty() || !restoreGeometry(geometry)) {
157 ✔
793
    WindowStateStore::centreOnCursorScreen(*this);
4 ✔
794
  }
795
  restoreState(QtPassSettings::getSavestate(saveState()));
157 ✔
796
  const AppSettings s = QtPassSettings::load();
157 ✔
797

798
  applyWindowFlagsSettings();
157 ✔
799

800
  if (s.useTrayIcon && m_tray == nullptr) {
157 ✔
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) {
156 ✔
807
    destroyTrayIcon();
×
808
  }
809
}
314 ✔
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
namespace {
1045
/**
1046
 * @brief @p path with each part below @p store spelled as stored on disk.
1047
 *
1048
 * Where the file system ignores case, "Bank.gpg" exists while the file is
1049
 * bank.gpg, and the tree knows the entry only by that spelling.
1050
 * @param store The store folder.
1051
 * @param path An existing file in the store.
1052
 * @return @p path itself when every part is spelled as stored, otherwise
1053
 *         the path with the stored spelling.
1054
 */
1055
auto spelledAsStored(const QString &store, const QString &path) -> QString {
31 ✔
1056
  const QStringList parts = QDir(store).relativeFilePath(path).split(
62 ✔
1057
      QLatin1Char('/'), Qt::SkipEmptyParts);
31 ✔
1058
  QDir dir(store);
31 ✔
1059
  bool respelled = false;
1060
  for (int i = 0; i < parts.size(); ++i) {
34 ✔
1061
    const bool leaf = i == parts.size() - 1;
34 ✔
1062
    const QStringList names =
1063
        dir.entryList((leaf ? QDir::Files : QDir::Dirs) | QDir::Hidden |
34 ✔
1064
                      QDir::NoDotAndDotDot);
37 ✔
1065
    QString name = parts.at(i);
1066
    if (!names.contains(name)) {
34 ✔
NEW
1067
      const auto stored = std::find_if(
×
1068
          names.cbegin(), names.cend(), [&name](const QString &candidate) {
NEW
1069
            return candidate.compare(name, Qt::CaseInsensitive) == 0;
×
1070
          });
NEW
1071
      if (stored == names.cend()) {
×
1072
        return path;
1073
      }
NEW
1074
      name = *stored;
×
1075
      respelled = true;
1076
    }
1077
    if (leaf) {
34 ✔
1078
      return respelled ? QDir::cleanPath(dir.filePath(name)) : path;
62 ✔
1079
    }
1080
    if (!dir.cd(name)) {
3 ✔
1081
      return path;
1082
    }
1083
  }
1084
  return path;
1085
}
31 ✔
1086
} // namespace
1087

1088
auto MainWindow::exactMatchPath() -> QString {
48 ✔
1089
  const QString text = QDir::fromNativeSeparators(ui->lineEdit->text());
96 ✔
1090
  const QString store = QtPassSettings::getPassStore();
96 ✔
1091
  // A name may begin or end with a space: " bank" is that entry, not bank.
1092
  // Only when no entry is named so are spaces around the text dropped.
1093
  for (const QString &typed : {text, text.trimmed()}) {
180 ✔
1094
    if (typed.isEmpty()) {
67 ✔
1095
      continue;
×
1096
    }
1097
    const QString path =
1098
        QDir::cleanPath(QDir(store).filePath(typed + QStringLiteral(".gpg")));
134 ✔
1099
    if (PathValidator::isPathInStore(store, path) && QFileInfo(path).isFile()) {
67 ✔
1100
      return spelledAsStored(store, path);
31 ✔
1101
    }
1102
  }
144 ✔
1103
  return {};
17 ✔
1104
}
1105

1106
auto MainWindow::exactMatch() -> QModelIndex {
44 ✔
1107
  const QString path = exactMatchPath();
44 ✔
1108
  if (path.isEmpty()) {
44 ✔
1109
    return {};
16 ✔
1110
  }
1111
  // indexFor() maps through the filter: a row the filter hides is no match.
1112
  const QModelIndex index = m_tree->indexFor(path);
28 ✔
1113
  if (!index.isValid() || !m_tree->fileInfo(index).isFile()) {
49 ✔
1114
    return {};
7 ✔
1115
  }
1116
  return index;
21 ✔
1117
}
1118

1119
void MainWindow::applySearchText(const QString &text) {
9 ✔
1120
  // A name search: content search, left on, kept its results over the tree
1121
  // and ignored the text.
1122
  if (ui->grepButton->isChecked()) {
9 ✔
1123
    ui->grepButton->setChecked(false);
1 ✔
1124
  }
1125
  delete m_pendingOpen;
9 ✔
1126
  ui->lineEdit->setText(text);
9 ✔
1127
  // Filter now, not after the search delay: the timer would leave the tree
1128
  // as the previous text filtered it.
1129
  searchTimer.stop();
9 ✔
1130
  onTimeoutSearch();
9 ✔
1131
  if (const QModelIndex exact = exactMatch(); exact.isValid()) {
9 ✔
1132
    openExactMatch(exact);
5 ✔
1133
    return;
5 ✔
1134
  }
1135
  // The tree loads folders in the background: at start, or right after the
1136
  // window is shown again, an entry that exists may not be in it yet. Try
1137
  // again as folders finish loading, for a few seconds, unless the search
1138
  // text changes meanwhile: any change ends the wait, even one typed back to
1139
  // this text, which is a new search that has not asked to open anything.
1140
  if (exactMatchPath().isEmpty()) {
8 ✔
1141
    return;
1142
  }
1143
  auto *pending = new QObject(this);
3 ✔
1144
  m_pendingOpen = pending;
1145
  QTimer::singleShot(5000, pending, &QObject::deleteLater);
3 ✔
1146
  // Disconnected at once: with deleteLater() alone, a folder that finished
1147
  // loading before the deletion still ran the open, or ran it twice.
1148
  const auto stop = [this, pending] {
2 ✔
1149
    disconnect(&m_tree->fileSystem(), nullptr, pending, nullptr);
2 ✔
1150
    disconnect(ui->lineEdit, nullptr, pending, nullptr);
2 ✔
1151
    pending->deleteLater();
2 ✔
1152
  };
5 ✔
1153
  connect(ui->lineEdit, &QLineEdit::textChanged, pending, stop);
3 ✔
1154
  connect(&m_tree->fileSystem(), &QFileSystemModel::directoryLoaded, pending,
3 ✔
1155
          [this, stop](const QString &) {
6 ✔
1156
            searchTimer.stop();
5 ✔
1157
            onTimeoutSearch();
5 ✔
1158
            if (const QModelIndex exact = exactMatch(); exact.isValid()) {
5 ✔
1159
              stop();
1 ✔
1160
              openExactMatch(exact);
1 ✔
1161
            }
1162
          });
5 ✔
1163
}
1164

1165
void MainWindow::openExactMatch(const QModelIndex &index) {
6 ✔
1166
  // Made current here, not left to the filter pass before: the tree may have
1167
  // moved its current row since, and with none on_treeView_clicked() only
1168
  // names the entry without decrypting it.
1169
  ui->treeView->setCurrentIndex(index);
6 ✔
1170
  on_treeView_clicked(index);
6 ✔
1171
}
6 ✔
1172

1173
auto MainWindow::firstFile(QModelIndex parentIndex) -> QModelIndex {
23 ✔
1174
  StoreModel &proxy = m_tree->proxy();
23 ✔
1175
  int numRows = proxy.rowCount(parentIndex);
23 ✔
1176
  for (int row = 0; row < numRows; ++row) {
30 ✔
1177
    QModelIndex index = proxy.index(row, 0, parentIndex);
20 ✔
1178
    if (m_tree->fileInfo(index).isFile()) {
20 ✔
1179
      return index;
13 ✔
1180
    }
1181
    if (proxy.hasChildren(index)) {
12 ✔
1182
      QModelIndex childFile = firstFile(index);
8 ✔
1183
      if (childFile.isValid())
1184
        return childFile;
5 ✔
1185
    }
1186
  }
1187
  return QModelIndex();
10 ✔
1188
}
1189

1190
// Guards the input dialogs (create, move, rename) against names like
1191
// "../../etc/passwd" or absolute paths escaping the store root.
1192
auto MainWindow::confirmPathInStore(const QString &candidate) -> bool {
11 ✔
1193
  if (PathValidator::isPathInStore(QtPassSettings::getPassStore(), candidate)) {
22 ✔
1194
    return true;
1195
  }
1196
  QMessageBox::warning(this, tr("Invalid name"),
9 ✔
1197
                       tr("That name would resolve outside the password "
3 ✔
1198
                          "store. Please choose a different name."));
1199
  return false;
3 ✔
1200
}
1201

1202
void MainWindow::setPassword(const QString &file, bool isNew) {
6 ✔
1203
  const AppSettings s = QtPassSettings::load();
6 ✔
1204
  PasswordDialog d(QtPassSettings::getPass(), s, file, isNew, this);
6 ✔
1205
  // A copy out of the editor is autocleared like one from the display.
1206
  connect(&d, &PasswordDialog::copied, &m_qtPass->clipboard(),
6 ✔
1207
          &ClipboardManager::trackCopied);
6 ✔
1208

1209
  if (isNew) {
6 ✔
1210
    const QString storePath = s.passStore;
1211
    QString folder = m_tree->currentDir(false);
1 ✔
1212
    if (folder.isEmpty()) {
1 ✔
1213
      folder = storePath;
×
1214
    }
1215
    // Folders to pick from, the tree's current one preselected. Real folders
1216
    // only: a linked or junctioned one would write the entry outside the store.
1217
    QStringList folders{QString()};
2 ✔
1218
    const QStringList found = Util::directoriesUnder(storePath);
1 ✔
1219
    for (const QString &path : found) {
16 ✔
1220
      const QString rel = QDir(storePath).relativeFilePath(path);
15 ✔
1221
      if (!rel.startsWith(u'.') && !rel.contains(QStringLiteral("/."))) {
45 ✔
1222
        folders << rel;
1223
      }
1224
    }
1225
    std::sort(folders.begin() + 1, folders.end());
1 ✔
1226
    d.setNewEntryLocation(storePath, folders,
1 ✔
1227
                          QDir(storePath).relativeFilePath(folder));
2 ✔
1228
    QHash<QString, QStringList> templates =
1229
        TemplateIO::readTemplates(storePath);
1 ✔
1230
    if (!templates.isEmpty()) {
1231
      QString defaultTemplate =
1232
          TemplateIO::getFolderTemplate(folder, storePath);
1 ✔
1233
      d.setAvailableTemplates(templates, defaultTemplate);
1 ✔
1234
    }
1235
  }
1 ✔
1236

1237
  if (!d.exec()) {
6 ✔
1238
    ui->treeView->setFocus();
5 ✔
1239
  }
1240
}
6 ✔
1241

1242
void MainWindow::addPassword() { setPassword(QString()); }
2 ✔
1243

1244
auto MainWindow::confirmDeletion(const QString &file, bool isDir) -> bool {
4 ✔
1245
  const QString path = QDir::separator() + file;
4 ✔
1246
  if (!isDir) {
4 ✔
1247
    return PlainMessageBox::askYes(
2 ✔
1248
        this, tr("Delete password?"),
2 ✔
1249
        tr("Are you sure you want to delete %1?").arg(path));
4 ✔
1250
  }
1251
  // Whole sentences, not a question stitched from pieces: a verb-final
1252
  // language cannot put the rest of the question after the path.
1253
  // Plain text, as every box quoting the store: the path is a name other
1254
  // writers control, and as rich text "a  b" would also show as "a b".
1255
  QString question =
1256
      tr("Are you sure you want to delete %1 and the whole content?").arg(path);
2 ✔
1257
  // A link, junction or special file inside is as unexpected as a stray
1258
  // plain file: the walker leaves them out of content and reports them.
1259
  QStringList skipped;
2 ✔
1260
  const QStringList content = Util::regularFilesUnder(
6 ✔
1261
      m_tree->fileSystem().rootPath() + path, {QStringLiteral("*")}, &skipped);
6 ✔
1262
  const bool unexpected =
1263
      !skipped.isEmpty() ||
2 ✔
1264
      std::any_of(content.cbegin(), content.cend(), [](const QString &entry) {
2 ✔
1265
        return QFileInfo(entry).suffix() != QLatin1String("gpg");
4 ✔
1266
      });
1267
  if (unexpected) {
1268
    question += QStringLiteral("\n\n") +
1 ✔
1269
                tr("Attention: there are unexpected files in the given "
1 ✔
1270
                   "folder, check them before continuing.");
1 ✔
1271
  }
1272
  return PlainMessageBox::askYes(this, tr("Delete folder?"), question);
4 ✔
1273
}
1274

1275
auto MainWindow::confirmLinkRemoval(const QString &file) -> bool {
1 ✔
1276
  // Only the link goes (ImitatePass::Remove unlinks it); nothing behind it
1277
  // is looked at or mentioned.
1278
  return PlainMessageBox::askYes(
1 ✔
1279
      this, tr("Delete link?"),
1 ✔
1280
      tr("%1 is a symbolic link or junction. Remove the link? What it "
1 ✔
1281
         "points to is left alone.")
1282
          .arg(QDir::separator() + file));
2 ✔
1283
}
1284

1285
void MainWindow::onDelete() {
8 ✔
1286
  const QModelIndex currentIndex = ui->treeView->currentIndex();
8 ✔
1287
  if (!currentIndex.isValid()) {
1288
    // Otherwise the whole password directory would be deleted (#556).
1289
    return;
5 ✔
1290
  }
1291

1292
  const bool isDir = !m_tree->fileInfo(currentIndex).isFile();
6 ✔
1293
  const QString file =
1294
      isDir ? m_tree->currentDir(true) : getFile(currentIndex, true);
6 ✔
1295
  const QString folder =
1296
      m_tree->fileSystem().rootPath() + QDir::separator() + file;
6 ✔
1297
  const bool linkedFolder = isDir && Util::isLinkedFolder(folder);
6 ✔
1298

1299
  if (!linkedFolder && refuseLinkedFolder(folder)) {
5 ✔
1300
    // Behind a link: deleting would reach outside the store.
1301
    return;
1302
  }
1303
  const bool confirmed =
1304
      linkedFolder ? confirmLinkRemoval(file) : confirmDeletion(file, isDir);
5 ✔
1305
  if (!confirmed) {
5 ✔
1306
    return;
1307
  }
1308
  QtPassSettings::getPass()->Remove(file, isDir);
6 ✔
1309
}
1310

1311
void MainWindow::cancelOtpRequest() {
71 ✔
1312
  m_otpRequestFile.clear();
71 ✔
1313
  m_copyRequestFile.clear();
71 ✔
1314
}
71 ✔
1315

1316
void MainWindow::onOperationError() {
25 ✔
1317
  cancelOtpRequest();
25 ✔
1318
  // executeWrapperStarted() emptied the panel and the browser when the
1319
  // operation started (a refusal says so too); what is left to forget is
1320
  // which entry the panel was about to show.
1321
  m_shownFile.clear();
25 ✔
1322
}
25 ✔
1323

1324
// Derives the code in-process from one decrypt, so it works with either
1325
// backend on every platform; otpFromFileToClipboard() finishes the job.
1326
void MainWindow::onOtp() {
10 ✔
1327
  QString file = getFile(ui->treeView->currentIndex(), true);
10 ✔
1328
  if (file.isEmpty()) {
10 ✔
1329
    flashText(tr("No password selected for OTP generation"), true);
1 ✔
1330
    return;
1 ✔
1331
  }
1332
  if (!QtPassSettings::isUseOtp()) {
9 ✔
1333
    // Normally unreachable (the action is hidden), but never fail silently.
1334
    flashText(tr("No OTP code found in this password entry"), true);
1 ✔
1335
    return;
1 ✔
1336
  }
1337

1338
  // Fast path: the panel shows a live code, so no decrypt, and one clipboard
1339
  // write (two setMimeData calls in one turn can empty the Windows
1340
  // clipboard). Only for *this* entry: arrow keys and right-click move
1341
  // currentIndex without QTreeView::clicked, so the code may be another's.
1342
  const QString shown =
1343
      (m_shownFile == file) ? m_displayPanel->currentOtpCode() : QString();
8 ✔
1344
  if (!shown.isEmpty()) {
8 ✔
1345
    m_qtPass->clipboard().copyText(shown);
1 ✔
1346
    showStatusMessage(tr("OTP code copied to clipboard"));
2 ✔
1347
    return;
1348
  }
1349

1350
  // Fallback: decrypt once. The request file keeps passShowHandler from
1351
  // copying the password and tells otpFromFileToClipboard its answer.
1352
  m_otpRequestFile = file;
7 ✔
1353
  setUiElementsEnabled(false);
7 ✔
1354
  // Keep the marker in step so a second request takes the fast path; safe as
1355
  // executeWrapperStarted() clears the panel, so a failed decrypt shows none.
1356
  m_shownFile = file;
7 ✔
1357
  QtPassSettings::getPass()->Show(file);
14 ✔
1358
}
1359

1360
void MainWindow::onEdit() {
2 ✔
1361
  QString file = getFile(ui->treeView->currentIndex(), true);
2 ✔
1362
  editPassword(file);
2 ✔
1363
}
2 ✔
1364

1365
void MainWindow::onUsers() {
2 ✔
1366
  const QString dir = m_tree->currentDir(false);
2 ✔
1367
  if (refuseLinkedFolder(dir)) {
2 ✔
1368
    return;
1369
  }
1370

1371
  UsersDialog d(QtPassSettings::getPass(), QtPassSettings::load(), dir, this);
1 ✔
1372
  if (!d.exec()) {
1 ✔
1373
    ui->treeView->setFocus();
1 ✔
1374
  }
1375
}
1 ✔
1376

1377
void MainWindow::messageAvailable(const QString &message) {
10 ✔
1378
  show();
10 ✔
1379
  raise();
10 ✔
1380
  if (message.isEmpty()) {
10 ✔
1381
    focusInput();
1 ✔
1382
  } else {
1383
    ui->treeView->expandAll();
9 ✔
1384
    applySearchText(message);
9 ✔
1385
  }
1386
}
10 ✔
1387

1388
void MainWindow::updateProfileBox() {
155 ✔
1389
  const Profiles profiles = QtPassSettings::getProfiles();
155 ✔
1390
  bool activeGone = false;
1391

1392
  if (profiles.isEmpty()) {
7 ✔
1393
    ui->profileWidget->hide();
148 ✔
1394
  } else {
1395
    ui->profileWidget->show();
7 ✔
1396
    // A refill is no choice of the user's: clearing and adding items moves
1397
    // the current text, which would otherwise switch profiles.
1398
    const QSignalBlocker quiet(ui->profileBox);
7 ✔
1399
    ui->profileBox->clear();
7 ✔
1400
    for (auto i = profiles.cbegin(); i != profiles.cend(); ++i) {
19 ✔
1401
      if (!i.key().isEmpty()) {
12 ✔
1402
        ui->profileBox->addItem(i.key());
12 ✔
1403
      }
1404
    }
1405
    ui->profileBox->model()->sort(0);
7 ✔
1406
    int index = ui->profileBox->findText(QtPassSettings::getProfile());
14 ✔
1407
    if (index != -1) { //  -1 for not found
7 ✔
1408
      ui->profileBox->setCurrentIndex(index);
6 ✔
1409
    } else if (ui->profileBox->count() > 0) {
1 ✔
1410
      // The active profile is gone (removed in Settings): the box shows the
1411
      // first one, and the settings and backend must follow it, or the
1412
      // removed profile's store stays in use behind it.
1413
      ui->profileBox->setCurrentIndex(0);
1 ✔
1414
      activeGone = true;
1415
    }
1416
  }
7 ✔
1417
  if (activeGone) {
7 ✔
1418
    on_profileBox_currentTextChanged(ui->profileBox->currentText());
2 ✔
1419
  }
1420
  updateProfileBoxEnabled();
155 ✔
1421
}
155 ✔
1422

1423
void MainWindow::updateProfileBoxEnabled() {
469 ✔
1424
  // No profile switch while anything of the store runs or waits: the
1425
  // backend's store and environment would change under it, and what is
1426
  // still queued (a push after a save, say) would finish for the other
1427
  // profile (#2071). Asked of the backend, not only of the interface: the
1428
  // watchdog releases the interface while a slow gpg or git still runs.
1429
  // Every backend: one kept from before a switch of backend may still
1430
  // run what was queued on it.
1431
  ui->profileBox->setEnabled(m_uiEnabled && ui->profileBox->count() > 1 &&
939 ✔
1432
                             QtPassSettings::backendsIdle());
11 ✔
1433
}
469 ✔
1434

1435
void MainWindow::on_profileBox_currentTextChanged(const QString &name) {
6 ✔
1436
  if (m_freshStart || name == QtPassSettings::getProfile()) {
18 ✔
1437
    return;
1 ✔
1438
  }
1439
  // The box is disabled while anything runs; should a change come through
1440
  // anyway, the active profile stays and the box says so again.
1441
  if (!m_uiEnabled || !QtPassSettings::backendsIdle()) {
5 ✔
1442
    const QSignalBlocker quiet(ui->profileBox);
×
1443
    ui->profileBox->setCurrentText(QtPassSettings::getProfile());
×
1444
    return;
1445
  }
×
1446
  // A content search runs outside the queue: leaving grep mode cancels it,
1447
  // so its results for the old store are dropped, not shown for the new.
1448
  if (m_grep.inGrepMode()) {
5 ✔
1449
    ui->grepButton->setChecked(false);
1 ✔
1450
  }
1451

1452
  ui->lineEdit->clear();
5 ✔
1453

1454
  const Profile prof = QtPassSettings::getProfiles().value(name);
10 ✔
1455
  AppSettings s = QtPassSettings::load();
5 ✔
1456
  s.activeProfile = name;
5 ✔
1457
  s.passStore = prof.path;
5 ✔
1458
  s.passSigningKey = prof.signingKey;
5 ✔
1459
  // A profile without its own Git flags keeps the global values.
1460
  s.useGit = prof.useGit.value_or(s.useGit);
5 ✔
1461
  s.autoPush = prof.autoPush.value_or(s.autoPush);
5 ✔
1462
  s.autoPull = prof.autoPull.value_or(s.autoPull);
5 ✔
1463
  QtPassSettings::save(s);
5 ✔
1464
  ui->statusBar->showMessage(tr("Profile changed to %1").arg(name), 2000);
10 ✔
1465

1466
  QtPassSettings::getPass()->updateEnv();
5 ✔
1467

1468
  m_tree->setStore(QtPassSettings::getPassStore());
10 ✔
1469
  deselect();
5 ✔
1470
  ui->treeView->setCurrentIndex(QModelIndex());
5 ✔
1471
}
5 ✔
1472

1473
void MainWindow::initTrayIcon() {
2 ✔
1474
  m_tray = new TrayIcon(this);
2 ✔
1475
  if (!m_tray->getIsAllocated()) {
2 ✔
1476
    destroyTrayIcon();
2 ✔
1477
    return;
2 ✔
1478
  }
1479
#ifndef Q_OS_MACOS
1480
  m_tray->addToggle(ui->actionShowMenuBar);
×
1481
#endif
1482
}
1483

1484
void MainWindow::destroyTrayIcon() {
2 ✔
1485
  delete m_tray;
2 ✔
1486
  m_tray = nullptr;
2 ✔
1487
}
2 ✔
1488

1489
void MainWindow::closeEvent(QCloseEvent *event) {
2 ✔
1490
  // Save in both branches: a tray user only ever hides the window, and
1491
  // used to quit through the tray menu with nothing ever written.
1492
  saveWindowState();
2 ✔
1493
  if (QtPassSettings::isHideOnClose()) {
2 ✔
1494
    this->hide();
2 ✔
1495
    event->ignore();
1496
  } else {
1497
    m_qtPass->clipboard().clear();
×
1498
    event->accept();
1499
    // A visible QSystemTrayIcon keeps the application alive, so
1500
    // quitOnLastWindowClosed never fires; quit explicitly.
1501
    QApplication::quit();
×
1502
  }
1503
}
2 ✔
1504

1505
auto MainWindow::eventFilter(QObject *obj, QEvent *event) -> bool {
5,904 ✔
1506
  if ((obj == ui->toolBar || obj == menuBar()) &&
5,904 ✔
1507
      event->type() == QEvent::PaletteChange) {
1508
    // Breeze gives these bars a "header" palette and, after a runtime
1509
    // light/dark switch, stamps the previous theme's colours back from a
1510
    // cached kdeglobals, hiding the toolbar icons. Deferred so we never
1511
    // re-enter the style while it is still applying its palette.
1512
    QTimer::singleShot(0, this, &MainWindow::dropStaleToolsAreaPalettes);
36 ✔
1513
  }
1514
  if (obj == ui->lineEdit && event->type() == QEvent::KeyPress) {
5,904 ✔
1515
    auto *key = dynamic_cast<QKeyEvent *>(event);
1 ✔
1516
    if (key != nullptr && key->key() == Qt::Key_Down) {
1 ✔
1517
      ui->treeView->setFocus();
1 ✔
1518
    }
1519
  }
1520
  return QObject::eventFilter(obj, event);
5,904 ✔
1521
}
1522

1523
// Only once the application palette changed (see m_themeSwitched): a bar
1524
// whose active Window lightness is far from the application's shows the
1525
// other theme.
1526
void MainWindow::dropStaleToolsAreaPalettes() {
31 ✔
1527
  if (!m_themeSwitched) {
31 ✔
1528
    return;
1529
  }
1530
  constexpr int kStaleToolsAreaLightness = 64;
1531
  // The active group on both sides: a bar's palette() reads the inactive
1532
  // group while another window has focus (the settings app, during a theme
1533
  // switch), and Breeze gives the header set different inactive colours.
1534
  const int appLightness = QApplication::palette()
54 ✔
1535
                               .color(QPalette::Active, QPalette::Window)
1536
                               .lightness();
27 ✔
1537
  for (QWidget *bar : {static_cast<QWidget *>(ui->toolBar),
108 ✔
1538
                       static_cast<QWidget *>(menuBar())}) {
81 ✔
1539
    if (!bar->testAttribute(Qt::WA_SetPalette)) {
54 ✔
1540
      continue;
48 ✔
1541
    }
1542
    const int barLightness =
1543
        bar->palette().color(QPalette::Active, QPalette::Window).lightness();
12 ✔
1544
    if (qAbs(barLightness - appLightness) <= kStaleToolsAreaLightness) {
6 ✔
1545
      continue;
2 ✔
1546
    }
1547
    bar->setPalette(QPalette());
4 ✔
1548
    // Both bars are transparent and the style paints the tools area from the
1549
    // stale palette, so fill our own. Window, not their Button role, which is
1550
    // not the window colour in either theme.
1551
    bar->setBackgroundRole(QPalette::Window);
4 ✔
1552
    bar->setAutoFillBackground(true);
4 ✔
1553
  }
1554
}
1555

1556
void MainWindow::keyPressEvent(QKeyEvent *event) {
18 ✔
1557
  switch (event->key()) {
18 ✔
1558
  case Qt::Key_Delete:
1 ✔
1559
    onDelete();
1 ✔
1560
    break;
1 ✔
1561
  case Qt::Key_Return:
1 ✔
1562
  case Qt::Key_Enter:
1563
    if (m_tree->proxy().rowCount() > 0) {
1 ✔
1564
      on_treeView_clicked(ui->treeView->currentIndex());
1 ✔
1565
    }
1566
    break;
1567
  case Qt::Key_Escape:
3 ✔
1568
    ui->lineEdit->clear();
3 ✔
1569
    break;
3 ✔
1570
  default:
1571
    break;
1572
  }
1573
}
18 ✔
1574

1575
void MainWindow::addShareMenu(QMenu &contextMenu, const AppSettings &s) {
9 ✔
1576
  const QString dirPath = QDir::cleanPath(m_tree->currentDir(false));
9 ✔
1577
  auto *shareMenu = new QMenu(tr("Share"), &contextMenu);
9 ✔
1578
  contextMenu.addMenu(shareMenu);
9 ✔
1579

1580
  const QString gpgIdPath = Pass::getGpgIdPath(dirPath, s.passStore);
9 ✔
1581
  const bool gpgIdExists = !gpgIdPath.isEmpty() && QFile(gpgIdPath).exists();
9 ✔
1582
  const QString exePath = s.usePass ? s.passExecutable : s.gpgExecutable;
9 ✔
1583
  const bool gpgAvailable =
1584
      !exePath.isEmpty() &&
18 ✔
1585
      (Executor::parseWslCommand(exePath) || QFile(exePath).exists());
18 ✔
1586

1587
  QAction *reencrypt = shareMenu->addAction(tr("Re-encrypt all passwords"));
9 ✔
1588
  reencrypt->setEnabled(gpgIdExists && gpgAvailable);
9 ✔
1589
  connect(reencrypt, &QAction::triggered, this,
9 ✔
1590
          [this, dirPath]() { reencryptPath(dirPath); });
30 ✔
1591

1592
  QAction *exportKey = shareMenu->addAction(tr("Export my public key..."));
9 ✔
1593
  exportKey->setEnabled(gpgAvailable);
9 ✔
1594
  connect(exportKey, &QAction::triggered, this, &MainWindow::exportPublicKey);
9 ✔
1595

1596
  QAction *addRecipientAction = shareMenu->addAction(tr("Add recipient..."));
9 ✔
1597
  addRecipientAction->setEnabled(gpgIdExists && gpgAvailable);
9 ✔
1598
  connect(addRecipientAction, &QAction::triggered, this,
9 ✔
1599
          [this, dirPath]() { addRecipient(dirPath); });
29 ✔
1600

1601
  QAction *shareHelp = shareMenu->addAction(tr("What is this?"));
9 ✔
1602
  connect(shareHelp, &QAction::triggered, this, &MainWindow::showShareHelp);
9 ✔
1603
}
9 ✔
1604

1605
void MainWindow::showContextMenu(const QPoint &pos) {
11 ✔
1606
  const AppSettings s = QtPassSettings::load();
11 ✔
1607
  const QModelIndex index = ui->treeView->indexAt(pos);
11 ✔
1608
  const bool selected = index.isValid();
1609
  if (!selected) {
1610
    ui->treeView->clearSelection();
1 ✔
1611
    ui->actionDelete->setEnabled(false);
1 ✔
1612
    ui->actionEdit->setEnabled(false);
1 ✔
1613
  }
1614
  ui->treeView->setCurrentIndex(index);
11 ✔
1615
  const QPoint globalPos = ui->treeView->viewport()->mapToGlobal(pos);
11 ✔
1616
  const QFileInfo fileOrFolder = m_tree->fileInfo(ui->treeView->currentIndex());
11 ✔
1617
  const bool isDir = fileOrFolder.isDir();
11 ✔
1618

1619
  QMenu contextMenu;
11 ✔
1620
  if (!selected || isDir) {
11 ✔
1621
    const std::array<std::pair<QString, void (MainWindow::*)()>, 4> onFolder{{
1622
        {tr("Open folder with file manager"), &MainWindow::openFolder},
10 ✔
1623
        {tr("Add folder"), &MainWindow::addFolder},
10 ✔
1624
        {tr("Add password"), &MainWindow::addPassword},
10 ✔
1625
        {tr("Users"), &MainWindow::onUsers},
10 ✔
1626
    }};
×
1627
    for (const auto &[text, slot] : onFolder) {
50 ✔
1628
      connect(contextMenu.addAction(text), &QAction::triggered, this, slot);
40 ✔
1629
    }
1630
  } else if (fileOrFolder.isFile()) {
1 ✔
1631
    connect(contextMenu.addAction(tr("Edit")), &QAction::triggered, this,
1 ✔
1632
            &MainWindow::onEdit);
2 ✔
1633
  }
1634
  if (selected) {
11 ✔
1635
    contextMenu.addSeparator();
10 ✔
1636
    if (isDir) {
10 ✔
1637
      connect(contextMenu.addAction(tr("Rename folder")), &QAction::triggered,
9 ✔
1638
              this, &MainWindow::renameFolder);
18 ✔
1639
    } else if (fileOrFolder.isFile()) {
1 ✔
1640
      connect(contextMenu.addAction(tr("Rename password")), &QAction::triggered,
1 ✔
1641
              this, &MainWindow::renamePassword);
2 ✔
1642
    }
1643
    connect(contextMenu.addAction(tr("Delete")), &QAction::triggered, this,
10 ✔
1644
            &MainWindow::onDelete);
10 ✔
1645
    if (isDir) {
10 ✔
1646
      addShareMenu(contextMenu, s);
9 ✔
1647
    }
1648
  }
1649
  contextMenu.exec(globalPos);
11 ✔
1650
}
11 ✔
1651

1652
void MainWindow::showBrowserContextMenu(const QPoint &pos) {
1 ✔
1653
  QMenu *contextMenu = ui->textBrowser->createStandardContextMenu(pos);
1 ✔
1654
  // Reparent from textBrowser: a browser stylesheet cascades to the child
1655
  // QMenu and breaks its opaque native background.
1656
  contextMenu->setParent(this, contextMenu->windowFlags());
1 ✔
1657
  QPoint globalPos = ui->textBrowser->viewport()->mapToGlobal(pos);
1 ✔
1658

1659
  contextMenu->exec(globalPos);
1 ✔
1660
  delete contextMenu;
1 ✔
1661
}
1 ✔
1662

1663
void MainWindow::openFolder() {
1 ✔
1664
  QString dir = m_tree->currentDir(false);
1 ✔
1665

1666
  QString path = QDir::toNativeSeparators(dir);
1 ✔
1667
  QDesktopServices::openUrl(QUrl::fromLocalFile(path));
1 ✔
1668
}
1 ✔
1669

1670
void MainWindow::addFolder() {
8 ✔
1671
  const AppSettings s = QtPassSettings::load();
8 ✔
1672
  bool ok;
1673
  QString dir = m_tree->currentDir(false);
8 ✔
1674
  QString newdir =
1675
      QInputDialog::getText(this, tr("New folder"),
8 ✔
1676
                            tr("New folder: \n(Will be placed in %1 )")
8 ✔
1677
                                .arg(s.passStore + m_tree->currentDir(true)),
16 ✔
1678
                            QLineEdit::Normal, "", &ok);
16 ✔
1679
  if (!ok || newdir.isEmpty()) {
8 ✔
1680
    return;
1681
  }
1682
  // Checked and created as one and the same path: the check resolves ".."
1683
  // lexically, the system after following links, so "link/../x" would pass
1684
  // as the store's x and be made beside the link's target.
1685
  newdir = QDir::cleanPath(newdir.prepend(dir));
7 ✔
1686
  if (!confirmPathInStore(newdir)) {
7 ✔
1687
    return;
1688
  }
1689
  // Behind a link the folder would be made outside the store, as Users,
1690
  // Re-encrypt and Delete already refuse.
1691
  if (refuseLinkedFolder(newdir)) {
6 ✔
1692
    return;
1693
  }
1694
  // The tree, like `pass ls`, hides names that start with a dot.
1695
  const QStringList parts =
1696
      QDir(s.passStore).relativeFilePath(newdir).split(u'/');
5 ✔
1697
  if (std::any_of(parts.cbegin(), parts.cend(), [](const QString &part) {
10 ✔
1698
        return part != u'.' && part.startsWith(u'.');
5 ✔
1699
      })) {
1700
    PlainMessageBox::warning(this, tr("Hidden folder"),
2 ✔
1701
                             tr("A folder that starts with a dot would be "
1 ✔
1702
                                "hidden from the list: %1")
1703
                                 .arg(newdir));
2 ✔
1704
    return;
1 ✔
1705
  }
1706
  // Exists already: an error, as QDir::mkdir() made it before.
1707
  if (QFileInfo::exists(newdir) || !Util::mkpathForStore(newdir)) {
4 ✔
1708
    PlainMessageBox::warning(this, tr("Error"),
2 ✔
1709
                             tr("Failed to create folder: %1").arg(newdir));
2 ✔
1710
    return;
1 ✔
1711
  }
1712
  // With a signing key, ImitatePass::loadVerifiedRecipients and pass
1713
  // (PASSWORD_STORE_SIGNING_KEY) refuse a .gpg-id without .gpg-id.sig, and
1714
  // signing needs a passphrase just to make a folder. So it inherits the
1715
  // parent's signed list; UsersDialog (Init) gives it its own.
1716
  const bool signingConfigured = !s.passSigningKey.trimmed().isEmpty();
3 ✔
1717
  if (s.addGPGId && !signingConfigured) {
3 ✔
1718
    // Seed from the parent's recipients in effect, not from `enabled` keys:
1719
    // that flag is only set in UsersDialog, so it left a zero-byte .gpg-id
1720
    // shadowing the parent's recipients (#1682).
1721
    if (!Pass::seedGpgIdFile(newdir, s.passStore)) {
3 ✔
1722
      PlainMessageBox::warning(
1 ✔
1723
          this, tr("Error"),
1 ✔
1724
          tr("Failed to create .gpg-id file in: %1").arg(newdir));
2 ✔
1725
      return;
1 ✔
1726
    }
1727
  }
1728
}
8 ✔
1729

1730
void MainWindow::renameFolder() {
3 ✔
1731
  bool ok;
1732
  QString srcDir = QDir::cleanPath(m_tree->currentDir(false));
3 ✔
1733
  QString srcDirName = QDir(srcDir).dirName();
3 ✔
1734
  QString newName =
1735
      QInputDialog::getText(this, tr("Rename folder"), tr("Rename folder to: "),
3 ✔
1736
                            QLineEdit::Normal, srcDirName, &ok);
6 ✔
1737
  if (!ok || newName.isEmpty()) {
3 ✔
1738
    return;
1739
  }
1740
  QString destDir = srcDir;
1741
  destDir.replace(srcDir.lastIndexOf(srcDirName), srcDirName.length(), newName);
2 ✔
1742
  if (!confirmPathInStore(destDir)) {
2 ✔
1743
    return;
1744
  }
1745
  QtPassSettings::getPass()->Move(srcDir, destDir, false);
3 ✔
1746
}
1747

1748
void MainWindow::editPassword(const QString &file) {
5 ✔
1749
  if (!file.isEmpty()) {
5 ✔
1750
    const AppSettings s = QtPassSettings::load();
5 ✔
1751
    if (s.useGit && s.autoPull) {
5 ✔
1752
      onUpdate(true);
1 ✔
1753
    }
1754
    // The dialog decrypts the entry itself to fill its fields. That decrypt
1755
    // lands on the same finishedShow the panel uses, so drop the panel's claim
1756
    // to it: otherwise passShowHandler() repaints and, with "Always copy",
1757
    // puts the entry's old password on the clipboard - replacing whatever the
1758
    // user copied to paste into the dialog.
1759
    m_shownFile.clear();
5 ✔
1760
    setPassword(file, false);
5 ✔
1761
  }
5 ✔
1762
}
5 ✔
1763

1764
void MainWindow::renamePassword() {
2 ✔
1765
  bool ok;
1766
  QString file = getFile(ui->treeView->currentIndex(), false);
2 ✔
1767
  QString filePath = QFileInfo(file).path();
2 ✔
1768
  QString fileName = QFileInfo(file).fileName();
2 ✔
1769
  if (fileName.endsWith(".gpg", Qt::CaseInsensitive)) {
4 ✔
1770
    fileName.chop(4);
2 ✔
1771
  }
1772

1773
  QString newName =
1774
      QInputDialog::getText(this, tr("Rename file"), tr("Rename file to: "),
2 ✔
1775
                            QLineEdit::Normal, fileName, &ok);
4 ✔
1776
  if (!ok || newName.isEmpty()) {
2 ✔
1777
    return;
1778
  }
1779
  QString newFile = QDir(filePath).filePath(newName);
2 ✔
1780
  if (!confirmPathInStore(newFile)) {
2 ✔
1781
    return;
1782
  }
1783
  QtPassSettings::getPass()->Move(file, newFile, false);
3 ✔
1784
}
1785

1786
void MainWindow::copyPasswordFromTreeview() {
4 ✔
1787
  QFileInfo fileOrFolder = m_tree->fileInfo(ui->treeView->currentIndex());
4 ✔
1788

1789
  if (fileOrFolder.isFile()) {
4 ✔
1790
    QString file = getFile(ui->treeView->currentIndex(), true);
4 ✔
1791
    // The newest Ctrl+C wins: finishedShow names its file, so the decrypt of
1792
    // an earlier request is simply not this one's.
1793
    m_copyRequestFile = file;
4 ✔
1794
    // This Show repaints the panel as well; see onOtp().
1795
    m_shownFile = file;
4 ✔
1796
    QtPassSettings::getPass()->Show(file);
8 ✔
1797
  }
1798
}
4 ✔
1799

1800
void MainWindow::passwordFromFileToClipboard(const QString &text,
18 ✔
1801
                                             const QString &file) {
1802
  if (m_copyRequestFile.isEmpty() || file != m_copyRequestFile) {
18 ✔
1803
    return;
16 ✔
1804
  }
1805
  m_copyRequestFile.clear();
3 ✔
1806
  // The first line, without a list of every line (an entry can expand into
1807
  // millions of them); left(-1) is the whole text when there is no newline.
1808
  const QString first = text.left(text.indexOf(QLatin1Char('\n')));
3 ✔
1809
  // A `pass otp insert` entry's first line is the otpauth:// URI carrying the
1810
  // TOTP seed; copying it would leak 2FA material. Matches the display path
1811
  // (FileContent::getPasswordForDisplay / PasswordDisplayPanel).
1812
  if (FileContent::isOtpUriValue(first)) {
3 ✔
1813
    flashText(tr("This entry holds an OTP secret, not a password"), true);
2 ✔
1814
    return;
1815
  }
1816
  m_qtPass->clipboard().copyText(first);
2 ✔
1817
}
1818

1819
void MainWindow::showStatusMessage(const QString &msg, int timeout) {
21 ✔
1820
  ui->statusBar->showMessage(msg, timeout);
21 ✔
1821
}
21 ✔
1822

1823
void MainWindow::reencryptPath(const QString &dir) {
3 ✔
1824
  QDir checkDir(dir);
3 ✔
1825
  if (!checkDir.exists()) {
3 ✔
1826
    PlainMessageBox::critical(this, tr("Error"),
2 ✔
1827
                              tr("Directory does not exist: %1").arg(dir));
2 ✔
1828
    return;
1 ✔
1829
  }
1830
  if (refuseLinkedFolder(dir)) {
2 ✔
1831
    return;
1832
  }
1833

1834
  const bool yes = PlainMessageBox::askYes(
2 ✔
1835
      this, tr("Re-encrypt passwords"),
2 ✔
1836
      tr("Re-encrypt all passwords in %1?\n\n"
2 ✔
1837
         "This will re-encrypt ALL password files in this folder "
1838
         "using the current recipients defined in .gpg-id.\n\n"
1839
         "This may rewrite many files and cannot be undone easily.\n\n"
1840
         "Continue?")
1841
          .arg(QDir(dir).dirName()));
4 ✔
1842

1843
  if (!yes)
2 ✔
1844
    return;
1845

1846
  // Disable now; the asynchronous startReencryptPath signal re-runs this
1847
  // harmlessly.
1848
  startReencryptPath();
1 ✔
1849

1850
  // Under the current profile's settings: with the pass backend active, the
1851
  // native one is not re-initialised on a profile switch.
1852
  QtPassSettings::getImitatePass()->reencryptPath(
2 ✔
1853
      QDir::cleanPath(QDir(dir).absolutePath()), QtPassSettings::load());
2 ✔
1854
}
3 ✔
1855

1856
// Idempotent: reencryptPath() calls it before ImitatePass emits the signal.
1857
void MainWindow::startReencryptPath() {
6 ✔
1858
  m_reencryptRunning = true;
6 ✔
1859
  setUiElementsEnabled(false);
6 ✔
1860
  // The worker always ends with endReencryptPath(), and Cancel is available
1861
  // throughout, so the generic watchdog is not needed for this operation.
1862
  m_uiWatchdog.stop();
6 ✔
1863
  ui->treeView->setDisabled(true);
6 ✔
1864
  if (m_reencryptProgress)
6 ✔
1865
    return;
1866
  auto *progress = new QProgressDialog(tr("Re-encrypting passwords..."),
4 ✔
1867
                                       tr("Cancel"), 0, 0, this);
8 ✔
1868
  progress->setWindowTitle(tr("Re-encrypt passwords"));
4 ✔
1869
  progress->setWindowModality(Qt::WindowModal);
4 ✔
1870
  progress->setAutoClose(false);
4 ✔
1871
  progress->setAutoReset(false);
4 ✔
1872
  progress->setMinimumDuration(0);
4 ✔
1873
  connect(progress, &QProgressDialog::canceled, this, [this]() {
4 ✔
1874
    QtPassSettings::getImitatePass()->cancelReencryptPath();
1 ✔
1875
    showStatusMessage(tr("Cancelling re-encryption"), 5000);
1 ✔
1876
  });
1 ✔
1877
  m_reencryptProgress = progress;
1878
  progress->show();
4 ✔
1879
}
1880

1881
void MainWindow::reencryptProgress(int current, int total) {
5 ✔
1882
  if (!m_reencryptProgress)
5 ✔
1883
    return;
1884
  m_reencryptProgress->setMaximum(total);
4 ✔
1885
  m_reencryptProgress->setLabelText(
4 ✔
1886
      tr("Re-encrypting passwords: %1 of %2").arg(current).arg(total));
8 ✔
1887
  // On a modal dialog setValue() runs processEvents(), which can deliver
1888
  // endReencryptPath() and reset m_reencryptProgress: keep this last.
1889
  m_reencryptProgress->setValue(current);
4 ✔
1890
}
1891

1892
void MainWindow::endReencryptPath() {
4 ✔
1893
  m_reencryptRunning = false;
4 ✔
1894
  if (m_reencryptProgress) {
4 ✔
1895
    m_reencryptProgress->hide();
4 ✔
1896
    m_reencryptProgress->deleteLater();
4 ✔
1897
    m_reencryptProgress = nullptr;
1898
  }
1899
  setUiElementsEnabled(true);
4 ✔
1900
}
4 ✔
1901

1902
void MainWindow::exportPublicKey() {
3 ✔
1903
  const AppSettings s = QtPassSettings::load();
3 ✔
1904
  const QString identity = s.passSigningKey;
1905
  if (identity.isEmpty()) {
3 ✔
1906
    QMessageBox::information(
2 ✔
1907
        this, tr("Export public key"),
1 ✔
1908
        tr("<h3>Export your public key</h3>"
×
1909
           "<p>No signing key is configured. Set one in QtPass Settings "
1910
           "&gt; GPG keys, or run this in a terminal:</p>"
1911
           "<pre>gpg --armor --export --output my_key.asc &lt;your-key-id"
1912
           "&gt;</pre>"
1913
           "<p>Then send the file to your teammates.</p>"));
1914
    return;
1 ✔
1915
  }
1916
  QString gpgExe = s.gpgExecutable;
1917
  if (gpgExe.isEmpty()) {
2 ✔
1918
    gpgExe = QStringLiteral("gpg");
×
1919
  }
1920
  QStringList args = {"--armor", "--export"};
10 ✔
1921
  args.append(identity.split(' ', Qt::SkipEmptyParts));
2 ✔
1922
  QString stdOut;
2 ✔
1923
  QString stdErr;
2 ✔
1924
  int exitCode = Executor::executeBlocking(gpgExe, args, &stdOut, &stdErr);
2 ✔
1925
  if (exitCode != 0 || stdOut.isEmpty()) {
2 ✔
1926
    PlainMessageBox::warning(this, tr("Export public key"),
2 ✔
1927
                             tr("Could not export public key for %1.\n\n%2")
1 ✔
1928
                                 .arg(identity, stdErr.isEmpty()
2 ✔
1929
                                                    ? tr("No output from gpg.")
2 ✔
1930
                                                    : stdErr));
1931
    return;
1932
  }
1933
  ExportPublicKeyDialog dialog(identity, stdOut, this);
1 ✔
1934
  dialog.exec();
1 ✔
1935
}
4 ✔
1936

1937
// UsersDialog only ticks keys already in the keyring; importing a foreign
1938
// key still has to happen via gpg (or QtPass settings) first.
1939
void MainWindow::addRecipient(const QString &dir) {
2 ✔
1940
  if (refuseLinkedFolder(dir)) {
2 ✔
1941
    return;
1 ✔
1942
  }
1943
  UsersDialog d(QtPassSettings::getPass(), QtPassSettings::load(), dir, this);
1 ✔
1944
  d.exec();
1 ✔
1945
}
1 ✔
1946

1947
// A tree-picked folder that is, or lies behind, a symlink or junction is not
1948
// a folder of the store. The store root itself may be a link (a synced
1949
// folder); that is configuration, not a tree pick.
1950
auto MainWindow::refuseLinkedFolder(const QString &dir) -> bool {
17 ✔
1951
  if (!Util::isUnderLink(dir, QtPassSettings::load().passStore)) {
17 ✔
1952
    return false;
1953
  }
1954
  PlainMessageBox::critical(
4 ✔
1955
      this, tr("Not a folder of the store"),
4 ✔
1956
      tr("%1 is, or lies behind, a symbolic link or junction. What that "
4 ✔
1957
         "points to is not part of the password store and is left alone.")
1958
          .arg(QDir::toNativeSeparators(QDir::cleanPath(dir))));
8 ✔
1959
  return true;
4 ✔
1960
}
1961

1962
void MainWindow::showShareHelp() {
1 ✔
1963
  QMessageBox::information(
2 ✔
1964
      this, tr("Sharing passwords with GPG"),
1 ✔
1965
      tr("<h3>Sharing passwords with GPG</h3>"
1 ✔
1966
         "<p>To share passwords with other users:</p>"
1967
         "<ol>"
1968
         "<li><b>Export your public key</b> and send it to teammates</li>"
1969
         "<li><b>Import teammates' public keys</b> into your GPG keyring</li>"
1970
         "<li><b>Re-encrypt passwords</b> so all recipients can decrypt "
1971
         "them</li>"
1972
         "</ol>"
1973
         "<p>Only people who have a matching secret key can decrypt the "
1974
         "passwords.</p>"
1975
         "<p><b>Tip:</b> Use the same GPG key for all shared folders.</p>"
1976
         "<p>See the FAQ for more details.</p>"));
1977
}
1 ✔
1978

1979
void MainWindow::updateGitButtonVisibility(bool uiEnabled) {
289 ✔
1980
  const AppSettings s = QtPassSettings::load();
289 ✔
1981
  // Without Git there is nothing to push or pull, ever: the buttons go, not
1982
  // grey out. While an operation runs they stay and are disabled.
1983
  const bool usable =
1984
      s.useGit && !(s.gitExecutable.isEmpty() && s.passExecutable.isEmpty());
289 ✔
1985
  ui->actionPush->setVisible(usable);
289 ✔
1986
  ui->actionUpdate->setVisible(usable);
289 ✔
1987
  // The separator in front of them would otherwise sit next to the next one.
1988
  const QList<QAction *> actions = ui->toolBar->actions();
289 ✔
1989
  const qsizetype at = actions.indexOf(ui->actionPush);
289 ✔
1990
  if (at > 0 && actions.at(at - 1)->isSeparator()) {
289 ✔
1991
    actions.at(at - 1)->setVisible(usable);
289 ✔
1992
  }
1993
  enableGitButtons(usable && uiEnabled);
289 ✔
1994
}
289 ✔
1995

1996
void MainWindow::updateOtpButtonVisibility(bool uiEnabled) {
289 ✔
1997
  // No platform gating: codes are generated in-process. Visible but disabled
1998
  // when OTP is off: the panel never shows an OTP field (a secret), so hiding
1999
  // this too would leave no trace of the feature. Honour uiEnabled, or the
2000
  // user can stack Show calls while a decrypt is in flight.
2001
  ui->actionOtp->setVisible(true);
289 ✔
2002
  ui->actionOtp->setEnabled(QtPassSettings::isUseOtp() && uiEnabled);
302 ✔
2003
}
289 ✔
2004

2005
void MainWindow::updateGrepButtonVisibility() {
151 ✔
2006
  const bool enabled = QtPassSettings::isUseGrepSearch();
151 ✔
2007
  ui->grepButton->setVisible(enabled);
151 ✔
2008
  ui->grepCaseButton->setVisible(enabled);
151 ✔
2009
  if (!enabled && m_grep.inGrepMode()) {
151 ✔
2010
    ui->grepButton->setChecked(false);
1 ✔
2011
  }
2012
}
151 ✔
2013

2014
void MainWindow::enableGitButtons(const bool &state) {
289 ✔
2015
  ui->actionPush->setEnabled(state);
289 ✔
2016
  ui->actionUpdate->setEnabled(state);
289 ✔
2017
}
289 ✔
2018

2019
void MainWindow::critical(const QString &title, const QString &msg) {
3 ✔
2020
  // Pass's messages quote store paths; see PlainMessageBox.
2021
  PlainMessageBox::critical(this, title, msg);
3 ✔
2022
}
3 ✔
2023

2024
void MainWindow::onProcessOutput(const QString &output, bool isError,
6 ✔
2025
                                 Enums::PROCESS pid) {
2026
  if (!QtPassSettings::isShowProcessOutput()) {
6 ✔
2027
    return;
2028
  }
2029
  m_processOutput->append(output, isError,
5 ✔
2030
                          ProcessOutputPanel::processName(pid));
10 ✔
2031
}
2032

2033
void MainWindow::updateProcessOutputVisibility() {
3 ✔
2034
  // The action's toggled handler shows or hides the dock.
2035
  ui->actionShowProcessOutput->setChecked(
3 ✔
2036
      QtPassSettings::isShowProcessOutput());
3 ✔
2037
  m_processOutput->setVisible(QtPassSettings::isShowProcessOutput());
3 ✔
2038
}
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