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

IJHack / QtPass / 43719269064

15 Nov 2026 01:29PM UTC coverage: 71.217% (+2.3%) from 68.908%
43719269064

push

github

web-flow
[1.8] Backport display, search and settings fixes (#2178, #2179, #2180, #2181, #2185) (#2187)

* 1.8: show and copy entry text with its whitespace as stored (ported from #2178)

showInTextBrowser() and the linked branch of the field rows wrap their HTML in white-space: pre-wrap, so two spaces, indentation and tabs are shown and copied as stored (#210, broken again since 1.4.0). A CRLF is one line end and a lone CR stays a space. Util::boundSpaceRuns() cuts runs of white space to 1000 first: with white space kept, Qt's line layout never finishes a wrapped line of 65536 spaces.

Finding TY6WZYFI.

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

* 1.8: key generation refuses a passphrase with a blank at either end (ported from #2179)

gpg's batch reader cuts spaces and tabs off a Passphrase: value, so such a passphrase protected the key without them and was then refused as typed. done() refuses it via KeygenDialog::isBatchPassphrase() (ASCII white space only; a no-break space is kept by gpg and accepted).

Finding 424Q5OQ6.

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

* 1.8: refuse a slash in a profile name (ported from #2181)

QSettings reads / (and \\ on Windows) in a key as a group separator, so "Work/Client" was saved a group too deep and read back as a profile "Work" without folder or signing key. validate() marks such a name and keeps OK off.

Finding VI12APUH.

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

* 1.8: hide on close and start minimized only into a tray icon (ported from #2185)

Without a tray icon (none asked for, or no system tray in the session) closing the window hid it while QtPass ran on invisibly, with the last entry in it and the password on the clipboard. closeEvent() and restoreWindow() hide only when m_tray exists.

Finding SWZB47G8.

... (continued)

56 of 57 new or added lines in 6 files covered. (98.25%)

1 existing line in 1 file now uncovered.

5535 of 7772 relevant lines covered (71.22%)

133.33 hits per line

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

52.04
/src/mainwindow.cpp
1
// SPDX-FileCopyrightText: 2014 Anne Jan Brouwer
2
// SPDX-License-Identifier: GPL-3.0-or-later
3
#include "mainwindow.h"
4

5
#ifdef QT_DEBUG
6
#include "debughelper.h"
7
#endif
8

9
#include "configdialog.h"
10
#include "enums.h"
11
#include "executor.h"
12
#include "exportpublickeydialog.h"
13
#include "filecontent.h"
14
#include "passworddialog.h"
15
#include "passworddisplaypanel.h"
16
#include "pathvalidator.h"
17
#include "qpushbuttonasqrcode.h"
18
#include "qpushbuttonshowpassword.h"
19
#include "qpushbuttonwithclipboard.h"
20
#include "qtcompat.h"
21
#include "qtpass.h"
22
#include "qtpasssettings.h"
23
#include "templateio.h"
24
#include "totp.h"
25
#include "trayicon.h"
26
#include "ui_mainwindow.h"
27
#include "usersdialog.h"
28
#include "util.h"
29
#include <QApplication>
30
#include <QCloseEvent>
31
#include <QDesktopServices>
32
#include <QDialog>
33
#include <QDirIterator>
34
#include <QDockWidget>
35
#include <QFileInfo>
36
#include <QHBoxLayout>
37
#include <QInputDialog>
38
#include <QLabel>
39
#include <QLineEdit>
40
#include <QMenu>
41
#include <QMessageBox>
42
#include <QPushButton>
43
#include <QScrollBar>
44
#include <QShortcut>
45
#include <QTextCursor>
46
#include <QTextEdit>
47
#include <QTimer>
48
#include <QToolButton>
49
#include <QTreeWidget>
50
#include <QUrl>
51
#include <utility>
52

53
/**
54
 * @brief MainWindow::MainWindow handles all of the main functionality and also
55
 * the main window.
56
 * @param searchText for searching from cli
57
 * @param parent pointer
58
 */
59
MainWindow::MainWindow(const QString &searchText, QWidget *parent)
32 ✔
60
    : QMainWindow(parent), ui(new Ui::MainWindow) {
32 ✔
61
#ifdef __APPLE__
62
  // extra treatment for mac os
63
  // see http://doc.qt.io/qt-5/qkeysequence.html#qt_set_sequence_auto_mnemonic
64
  qt_set_sequence_auto_mnemonic(true);
65
#endif
66
  ui->setupUi(this);
32 ✔
67

68
  m_qtPass = new QtPass(this);
32 ✔
69

70
  // register shortcut ctrl/cmd + Q to close the main window
71
  new QShortcut(QKeySequence(Qt::CTRL | Qt::Key_Q), this, SLOT(close()));
32 ✔
72
  // register shortcut ctrl/cmd + C to copy the currently selected password
73
  new QShortcut(QKeySequence(QKeySequence::StandardKey::Copy), this,
64 ✔
74
                SLOT(copyPasswordFromTreeview()));
64 ✔
75

76
  model.setNameFilters(QStringList() << "*.gpg");
96 ✔
77
  model.setNameFilterDisables(false);
32 ✔
78

79
  /*
80
   * I added this to solve Windows bug but now on GNU/Linux the main folder,
81
   * if hidden, disappear
82
   *
83
   * model.setFilter(QDir::NoDot);
84
   */
85

86
  QString passStore = QtPassSettings::getPassStore(Util::findPasswordStore());
32 ✔
87

88
  QModelIndex rootDir = model.setRootPath(passStore);
32 ✔
89
  model.fetchMore(rootDir);
32 ✔
90

91
  proxyModel.setModelAndStore(&model, passStore);
32 ✔
92
  proxyModel.setPass(QtPassSettings::getPass());
32 ✔
93
  selectionModel.reset(new QItemSelectionModel(&proxyModel));
32 ✔
94

95
  ui->treeView->setModel(&proxyModel);
32 ✔
96
  ui->treeView->setRootIndex(proxyModel.mapFromSource(rootDir));
32 ✔
97
  ui->treeView->setColumnHidden(1, true);
32 ✔
98
  ui->treeView->setColumnHidden(2, true);
32 ✔
99
  ui->treeView->setColumnHidden(3, true);
32 ✔
100
  ui->treeView->setHeaderHidden(true);
32 ✔
101
  ui->treeView->setIndentation(15);
32 ✔
102
  ui->treeView->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
32 ✔
103
  ui->treeView->setContextMenuPolicy(Qt::CustomContextMenu);
32 ✔
104
  ui->treeView->header()->setSectionResizeMode(0, QHeaderView::Stretch);
32 ✔
105
  ui->treeView->sortByColumn(0, Qt::AscendingOrder);
32 ✔
106
  connect(ui->treeView, &QWidget::customContextMenuRequested, this,
32 ✔
107
          &MainWindow::showContextMenu);
32 ✔
108
  connect(ui->treeView, &DeselectableTreeView::emptyClicked, this,
32 ✔
109
          &MainWindow::deselect);
32 ✔
110

111
  {
112
    const AppSettings s = QtPassSettings::load();
32 ✔
113
    if (s.useMonospace) {
32 ✔
114
      QFont monospace("Monospace");
×
115
      monospace.setStyleHint(QFont::Monospace);
×
116
      ui->textBrowser->setFont(monospace);
×
117
    }
×
118
    if (s.noLineWrapping) {
32 ✔
119
      ui->textBrowser->setLineWrapMode(QTextBrowser::NoWrap);
×
120
    }
121
    clearPanelTimer.setInterval(MS_PER_SECOND * s.autoclearPanelSeconds);
32 ✔
122
  }
32 ✔
123
  ui->textBrowser->setOpenExternalLinks(true);
32 ✔
124
  ui->textBrowser->setContextMenuPolicy(Qt::CustomContextMenu);
32 ✔
125
  connect(ui->textBrowser, &QWidget::customContextMenuRequested, this,
32 ✔
126
          &MainWindow::showBrowserContextMenu);
32 ✔
127

128
  updateProfileBox();
32 ✔
129

130
  m_displayPanel = new PasswordDisplayPanel(
32 ✔
131
      ui->gridLayout, ui->verticalLayoutPassword, this, this);
32 ✔
132
  connect(m_displayPanel, &PasswordDisplayPanel::copyRequested, m_qtPass,
32 ✔
133
          &QtPass::copyTextToClipboard);
32 ✔
134
  connect(m_displayPanel, &PasswordDisplayPanel::textCopied, m_qtPass,
32 ✔
135
          &QtPass::trackCopied);
32 ✔
136
  connect(ui->textBrowser, &SecretTextBrowser::copied, m_qtPass,
32 ✔
137
          &QtPass::trackCopied);
32 ✔
138
  connect(m_displayPanel, &PasswordDisplayPanel::qrRequested, m_qtPass,
32 ✔
139
          &QtPass::showTextAsQRCode);
32 ✔
140

141
  QtPassSettings::getPass()->updateEnv();
32 ✔
142
  clearPanelTimer.setSingleShot(true);
32 ✔
143
  connect(&clearPanelTimer, &QTimer::timeout, this, [this]() { clearPanel(); });
32 ✔
144

145
  searchTimer.setInterval(350);
32 ✔
146
  searchTimer.setSingleShot(true);
32 ✔
147

148
  connect(&searchTimer, &QTimer::timeout, this, &MainWindow::onTimeoutSearch);
32 ✔
149

150
  // Install the search-box key filter once, not on every setUiElementsEnabled
151
  // call.
152
  ui->lineEdit->installEventFilter(this);
32 ✔
153
  ui->toolBar->installEventFilter(this);
32 ✔
154

155
  // Safety net: if a backend operation disables the UI but never signals
156
  // completion, re-enable after a timeout so the window can't get stuck.
157
  m_uiWatchdog.setSingleShot(true);
32 ✔
158
  m_uiWatchdog.setInterval(UiWatchdogMs);
32 ✔
159
  connect(&m_uiWatchdog, &QTimer::timeout, this, [this]() {
32 ✔
160
    showStatusMessage(tr("Operation timed out; re-enabling interface."));
×
161
    // Drop any in-flight OTP request so a late finishedShow cannot be mistaken
162
    // for the answer to it.
163
    cancelOtpRequest();
×
164
    setUiElementsEnabled(true);
×
165
  });
×
166

167
  initToolBarButtons();
32 ✔
168
  initStatusBar();
32 ✔
169
  initProcessOutputPanel();
32 ✔
170

171
  connect(QtPassSettings::getPass(), &Pass::finishedAnyWithPid, this,
32 ✔
172
          [this](const QString &out, const QString &err, Enums::PROCESS pid) {
64 ✔
173
            // Never route potentially-secret output through the panel:
174
            // - PASS_SHOW / PASS_OTP_GENERATE go via dedicated signals to
175
            //   the main text browser (which clears on a timer).
176
            // - PASS_GREP returns lines from password files; #252 must
177
            //   not leak those into a long-lived panel.
178
            // - PASS_INSERT's stdin is the password; stdout normally
179
            //   carries gpg/git progress only, but exclude defensively
180
            //   in case a future code path uses --echo or similar.
181
            if (isSensitiveProcess(pid)) {
×
182
              return;
183
            }
184
            if (!out.isEmpty()) {
×
185
              onProcessOutput(out, false, pid);
×
186
            }
187
            if (!err.isEmpty()) {
×
188
              onProcessOutput(err, true, pid);
×
189
            }
190
          });
191

192
  ui->lineEdit->setClearButtonEnabled(true);
32 ✔
193
  updateGrepButtonVisibility();
32 ✔
194

195
  setUiElementsEnabled(true);
32 ✔
196

197
  ui->lineEdit->setText(searchText);
32 ✔
198

199
  // Record whether startup configuration succeeded instead of calling
200
  // QApplication::quit() here: quit() before the event loop runs (exec() is
201
  // still ahead in main()) is a documented no-op, so a cancelled first-run
202
  // wizard used to leave the half-configured window showing anyway. main()
203
  // consults initSucceeded() and exits before show() when this is false.
204
  m_initSucceeded = m_qtPass->init();
32 ✔
205
  if (!m_initSucceeded) {
32 ✔
206
    return;
207
  }
208

209
  // Initial focus is handled in showEvent() once the window is actually
210
  // mapped. Scheduling it here via a 10 ms QTimer was racy: if the timer
211
  // fires while the window has not yet been realised — e.g. an
212
  // ActivationChange queued by main()'s `activateWindow()` call before
213
  // `show()`, or a nested QDialog::exec() inside init() — the
214
  // QLineEdit's internal text engine hasn't been wired up and
215
  // selectAll() segfaults inside Qt (see #1187, #1188).
216
}
×
217

218
MainWindow::~MainWindow() { delete m_qtPass; }
124 ✔
219

220
/**
221
 * @brief MainWindow::focusInput selects any text (if applicable) in the search
222
 * box and sets focus to it. Allows for easy searching, called at application
223
 * start and when receiving empty message in MainWindow::messageAvailable when
224
 * compiled with SINGLE_APP=1 (default).
225
 */
226
void MainWindow::focusInput() {
19 ✔
227
  // Resolve the QLineEdit through the live widget tree rather than the
228
  // cached `ui->lineEdit` pointer.
229
  //
230
  // On a fresh-config first launch the constructor calls
231
  // `m_qtPass->init()` → `MainWindow::config()`, and `config()`'s
232
  // `applyWindowFlagsSettings()` does `setWindowFlags(...)` + `show()`
233
  // on the main window. `setWindowFlags` on a top-level widget rebuilds
234
  // the native window via `setParent(nullptr, flags)`; under Qt 6.11
235
  // we observed the QLineEdit attached to the centralWidget gets
236
  // destroyed in that rebuild while `ui->lineEdit` still holds its old
237
  // address — leading to a SIGSEGV inside `QWidget::testAttribute`
238
  // (called from `QLineEdit::isVisible` / `selectAll`). `findChild<>()`
239
  // walks the current hierarchy and returns null cleanly when the
240
  // widget is gone, so `focusInput` becomes a safe no-op instead of a
241
  // use-after-free.
242
  if (!isVisible()) {
19 ✔
243
    return;
244
  }
245
  auto *lineEdit = findChild<QLineEdit *>(QStringLiteral("lineEdit"));
19 ✔
246
  if (lineEdit == nullptr || !lineEdit->isVisible()) {
19 ✔
247
    return;
248
  }
249
  lineEdit->selectAll();
19 ✔
250
  lineEdit->setFocus();
19 ✔
251
  // Only mark the first-show focus pulse as done once it's actually
252
  // landed; setting it eagerly in showEvent() would consume the
253
  // one-shot if focusInput returned early (mid-rebuild widget state)
254
  // and we'd never retry.
255
  m_firstShowCompleted = true;
19 ✔
256
}
257

258
/**
259
 * @brief MainWindow::changeEvent sets focus to the search box on activation
260
 * and re-derives palette-dependent styling on a theme change.
261
 * @param event
262
 */
263
void MainWindow::changeEvent(QEvent *event) {
50 ✔
264
  QWidget::changeEvent(event);
50 ✔
265
  if (event->type() == QEvent::PaletteChange && m_displayPanel != nullptr) {
50 ✔
266
    // Desktop switched light/dark (e.g. KDE day/night). Top-level widgets
267
    // receive PaletteChange for that (ApplicationPaletteChange goes to the
268
    // QApplication object). Styling that bakes palette colours into
269
    // stylesheets must be re-derived by hand.
270
    m_displayPanel->refreshPalette();
5 ✔
271
  }
272
  if (event->type() == QEvent::ActivationChange && isActiveWindow() &&
50 ✔
273
      isVisible()) {
274
    // Defer one event-loop tick so the synchronous activation dispatch
275
    // chain (`QApplicationPrivate::setActiveWindow` → `notify_helper`)
276
    // unwinds before we touch widget state — calling `focusInput()`
277
    // inline from this stack has segfaulted in past iterations because
278
    // mid-rebuild ui state isn't fully wired up yet.
279
    QMetaObject::invokeMethod(this, &MainWindow::focusInput,
10 ✔
280
                              Qt::QueuedConnection);
281
  }
282
}
50 ✔
283

284
/**
285
 * @brief First-show hook: run the initial focusInput() pulse once the
286
 *        window is actually mapped. The widget's internal data is fully
287
 *        initialised by this point, so QLineEdit::selectAll() is safe.
288
 * @param event Show event passed to the base class.
289
 */
290
void MainWindow::showEvent(QShowEvent *event) {
11 ✔
291
  QMainWindow::showEvent(event);
11 ✔
292
  if (m_firstShowCompleted) {
11 ✔
293
    return;
294
  }
295
  // Queue the focus pulse for the next event-loop tick so the platform
296
  // map round-trip and any pending widget rebuilds (e.g. setWindowFlags
297
  // from the config wizard path) settle before we look up the line
298
  // edit. The `m_firstShowCompleted` latch is set inside focusInput()
299
  // *after* it actually focuses, so a transient failed lookup just
300
  // re-queues on the next show rather than silently dropping.
301
  QMetaObject::invokeMethod(this, &MainWindow::focusInput,
10 ✔
302
                            Qt::QueuedConnection);
303
}
304

305
/**
306
 * @brief MainWindow::initToolBarButtons init main ToolBar and connect actions
307
 */
308
void MainWindow::initToolBarButtons() {
32 ✔
309
  connect(ui->actionAddPassword, &QAction::triggered, this,
32 ✔
310
          &MainWindow::addPassword);
32 ✔
311
  connect(ui->actionAddFolder, &QAction::triggered, this,
32 ✔
312
          &MainWindow::addFolder);
32 ✔
313
  connect(ui->actionEdit, &QAction::triggered, this, &MainWindow::onEdit);
32 ✔
314
  connect(ui->actionDelete, &QAction::triggered, this, &MainWindow::onDelete);
32 ✔
315
  connect(ui->actionPush, &QAction::triggered, this, &MainWindow::onPush);
32 ✔
316
  connect(ui->actionUpdate, &QAction::triggered, this, &MainWindow::onUpdate);
32 ✔
317
  connect(ui->actionUsers, &QAction::triggered, this, &MainWindow::onUsers);
32 ✔
318
  connect(ui->actionConfig, &QAction::triggered, this, &MainWindow::onConfig);
32 ✔
319
  connect(ui->actionOtp, &QAction::triggered, this, &MainWindow::onOtp);
32 ✔
320

321
  ui->actionAddPassword->setIcon(
32 ✔
322
      QIcon::fromTheme("document-new", QIcon(":/icons/document-new.svg")));
128 ✔
323
  ui->actionAddFolder->setIcon(
32 ✔
324
      QIcon::fromTheme("folder-new", QIcon(":/icons/folder-new.svg")));
128 ✔
325
  ui->actionEdit->setIcon(QIcon::fromTheme(
32 ✔
326
      "document-properties", QIcon(":/icons/document-properties.svg")));
96 ✔
327
  ui->actionDelete->setIcon(
32 ✔
328
      QIcon::fromTheme("edit-delete", QIcon(":/icons/edit-delete.svg")));
128 ✔
329
  ui->actionPush->setIcon(
32 ✔
330
      QIcon::fromTheme("go-up", QIcon(":/icons/go-top.svg")));
128 ✔
331
  ui->actionUpdate->setIcon(
32 ✔
332
      QIcon::fromTheme("go-down", QIcon(":/icons/go-bottom.svg")));
128 ✔
333
  ui->actionUsers->setIcon(QIcon::fromTheme(
32 ✔
334
      "x-office-address-book", QIcon(":/icons/x-office-address-book.svg")));
96 ✔
335
  ui->actionConfig->setIcon(QIcon::fromTheme(
32 ✔
336
      "applications-system", QIcon(":/icons/applications-system.svg")));
64 ✔
337
}
32 ✔
338

339
/**
340
 * @brief MainWindow::initStatusBar init statusBar with default message and logo
341
 */
342
void MainWindow::initStatusBar() {
32 ✔
343
  ui->statusBar->showMessage(tr("Welcome to QtPass %1").arg(VERSION), 2000);
64 ✔
344

345
  QPixmap logo = QPixmap::fromImage(QImage(":/artwork/icon.svg"))
64 ✔
346
                     .scaledToHeight(statusBar()->height());
32 ✔
347
  auto *logoApp = new QLabel(statusBar());
32 ✔
348
  logoApp->setPixmap(logo);
32 ✔
349
  statusBar()->addPermanentWidget(logoApp);
32 ✔
350
}
32 ✔
351

352
/**
353
 * @brief Build the process-output panel as a bottom QDockWidget.
354
 *
355
 * The panel is constructed programmatically rather than declared in
356
 * mainwindow.ui: uic only places QMainWindow's top-level children into
357
 * the centralWidget / statusBar / menuBar / toolBars / dock-widget
358
 * slots, and the previous home (statusBar()->addPermanentWidget()) made
359
 * an 80–150 px tall QTextEdit sit inside what is otherwise a thin
360
 * status row. A QDockWidget at the bottom dock area is the conventional
361
 * place for an IDE-style output console, and it gives users
362
 * detach/move for free.
363
 */
364
void MainWindow::initProcessOutputPanel() {
32 ✔
365
  m_processOutputWidget = new QWidget;
32 ✔
366
  m_processOutputWidget->setObjectName(QStringLiteral("processOutputWidget"));
64 ✔
367
  auto *outputLayout = new QHBoxLayout(m_processOutputWidget);
32 ✔
368
  outputLayout->setObjectName(QStringLiteral("processOutputLayout"));
64 ✔
369
  outputLayout->setContentsMargins(0, 0, 0, 0);
32 ✔
370
  m_clearOutputButton = new QToolButton(m_processOutputWidget);
32 ✔
371
  m_clearOutputButton->setObjectName(QStringLiteral("clearOutputButton"));
64 ✔
372
  m_clearOutputButton->setText(tr("Clear"));
32 ✔
373
  m_clearOutputButton->setToolTip(tr("Clear output"));
32 ✔
374
  outputLayout->addWidget(m_clearOutputButton);
32 ✔
375
  m_processOutputEdit = new QTextEdit(m_processOutputWidget);
32 ✔
376
  m_processOutputEdit->setObjectName(QStringLiteral("processOutputEdit"));
64 ✔
377
  m_processOutputEdit->setReadOnly(true);
32 ✔
378
  m_processOutputEdit->setAcceptRichText(false);
32 ✔
379
  outputLayout->addWidget(m_processOutputEdit);
32 ✔
380

381
  m_processOutputDock = new QDockWidget(tr("Process Output"), this);
32 ✔
382
  m_processOutputDock->setObjectName(QStringLiteral("processOutputDock"));
64 ✔
383
  m_processOutputDock->setFeatures(QDockWidget::DockWidgetMovable |
32 ✔
384
                                   QDockWidget::DockWidgetFloatable);
385
  m_processOutputDock->setAllowedAreas(Qt::BottomDockWidgetArea |
32 ✔
386
                                       Qt::TopDockWidgetArea);
387
  m_processOutputDock->setWidget(m_processOutputWidget);
32 ✔
388
  addDockWidget(Qt::BottomDockWidgetArea, m_processOutputDock);
32 ✔
389
  // setVisible after addDockWidget so our explicit preference wins
390
  // even if QMainWindow applies any cached state when the dock is
391
  // attached. restoreWindow() runs before this method (it's called
392
  // from the QtPass ctor, which is constructed at the top of the
393
  // MainWindow ctor), so the saved layout has already been processed
394
  // by the time we get here.
395
  m_processOutputDock->setVisible(QtPassSettings::isShowProcessOutput());
32 ✔
396

397
  connect(m_clearOutputButton, &QToolButton::clicked, this,
32 ✔
398
          &MainWindow::on_clearOutputButton_clicked);
32 ✔
399

400
  // Hysteresis: while the user is actively dragging the slider, don't
401
  // touch m_autoScroll on every tick — a brief overshoot at maximum
402
  // would silently re-arm auto-scroll without an explicit release. Only
403
  // commit on slider release. Wheel/keyboard scroll never sets
404
  // isSliderDown(), so they still update immediately.
405
  connect(m_processOutputEdit->verticalScrollBar(), &QScrollBar::valueChanged,
32 ✔
406
          this, [this]() {
32 ✔
407
            auto *sb = m_processOutputEdit->verticalScrollBar();
×
408
            if (sb->isSliderDown())
×
409
              return;
410
            m_autoScroll = sb->value() >= sb->maximum();
×
411
          });
412
  connect(m_processOutputEdit->verticalScrollBar(), &QScrollBar::sliderReleased,
32 ✔
413
          this, [this]() {
32 ✔
414
            auto *sb = m_processOutputEdit->verticalScrollBar();
×
415
            m_autoScroll = sb->value() >= sb->maximum();
×
416
          });
×
417
}
32 ✔
418

419
auto MainWindow::getCurrentTreeViewIndex() -> QModelIndex {
1 ✔
420
  return ui->treeView->currentIndex();
1 ✔
421
}
422

423
void MainWindow::cleanKeygenDialog() {
1 ✔
424
  if (m_keyGenDialog != nullptr) {
1 ✔
425
    m_keyGenDialog->close();
×
426
  }
427
  m_keyGenDialog = nullptr;
428
}
1 ✔
429

430
/**
431
 * @brief Displays the given text in the main window text browser, optionally
432
 * marking it as an error and/or rendering it as HTML.
433
 * @example
434
 * MainWindow window;
435
 * window.flashText("Operation completed.", false, false);
436
 *
437
 * @param const QString &text - The text content to display.
438
 * @param const bool isError - If true, sets the text color to red before
439
 * displaying the text.
440
 * @param const bool isHtml - If true, treats the text as HTML and appends it to
441
 * the existing HTML content.
442
 * @return void - No return value.
443
 */
444
void MainWindow::flashText(const QString &text, const bool isError,
16 ✔
445
                           const bool isHtml) {
446
  if (isError) {
16 ✔
447
    ui->textBrowser->setTextColor(Qt::red);
2 ✔
448
  }
449

450
  if (isHtml) {
16 ✔
451
    QString _text = text;
452
    if (!ui->textBrowser->toPlainText().isEmpty()) {
26 ✔
453
      _text = ui->textBrowser->toHtml() + _text;
4 ✔
454
    }
455
    ui->textBrowser->setHtml(_text);
13 ✔
456
  } else {
457
    ui->textBrowser->setText(text);
3 ✔
458
  }
459
}
16 ✔
460

461
/**
462
 * @brief MainWindow::config pops up the configuration screen and handles all
463
 * inter-window communication
464
 */
465
void MainWindow::applyTextBrowserSettings() {
3 ✔
466
  const AppSettings s = QtPassSettings::load();
3 ✔
467
  if (s.useMonospace) {
3 ✔
468
    QFont monospace("Monospace");
×
469
    monospace.setStyleHint(QFont::Monospace);
×
470
    ui->textBrowser->setFont(monospace);
×
471
  } else {
×
472
    ui->textBrowser->setFont(QFont());
3 ✔
473
  }
474

475
  if (s.noLineWrapping) {
3 ✔
476
    ui->textBrowser->setLineWrapMode(QTextBrowser::NoWrap);
×
477
  } else {
478
    ui->textBrowser->setLineWrapMode(QTextBrowser::WidgetWidth);
3 ✔
479
  }
480
}
3 ✔
481

482
void MainWindow::applyWindowFlagsSettings() {
3 ✔
483
  if (QtPassSettings::isAlwaysOnTop()) {
3 ✔
484
    Qt::WindowFlags flags = windowFlags();
485
    this->setWindowFlags(flags | Qt::WindowStaysOnTopHint);
×
486
  } else {
487
    this->setWindowFlags(Qt::Window);
3 ✔
488
  }
489
  this->show();
3 ✔
490
}
3 ✔
491

492
/**
493
 * @brief Opens and processes the application configuration dialog, then applies
494
 * any accepted settings.
495
 * @example
496
 * if (!config()) {
497
 *   // the user cancelled
498
 * }
499
 *
500
 * @return bool - True when the dialog was accepted, false when it was
501
 * cancelled. An accepted dialog can still leave the configuration invalid
502
 * (the OK button is not gated on Util::configIsValid()); QtPass::init() keeps
503
 * asking until the configuration is usable or this returns false.
504
 */
505
auto MainWindow::config() -> bool {
4 ✔
506
  QScopedPointer<ConfigDialog> d(new ConfigDialog(this));
4 ✔
507
  d->setModal(true);
4 ✔
508
  // Automatically default to pass if it's available
509
  if (m_qtPass->isFreshStart() &&
4 ✔
510
      QFile(QtPassSettings::getPassExecutable()).exists()) {
12 ✔
511
    QtPassSettings::setUsePass(true);
×
512
  }
513

514
  if (m_qtPass->isFreshStart()) {
4 ✔
515
    d->wizard(); // run initial setup wizard for first-time configuration
4 ✔
516
  }
517
  if (d->exec() != QDialog::Accepted) {
4 ✔
518
    return false;
519
  }
520

521
  applyTextBrowserSettings();
3 ✔
522
  applyWindowFlagsSettings();
3 ✔
523

524
  updateProfileBox();
3 ✔
525
  const AppSettings s = QtPassSettings::load();
3 ✔
526
  proxyModel.setStore(s.passStore);
3 ✔
527
  ui->treeView->setRootIndex(proxyModel.rootIndexFor(s.passStore));
3 ✔
528
  deselect();
3 ✔
529
  ui->treeView->setCurrentIndex(QModelIndex());
3 ✔
530

531
  Pass *activePass = QtPassSettings::getPass();
3 ✔
532
  activePass->updateEnv();
3 ✔
533
  proxyModel.setPass(activePass);
3 ✔
534
  clearPanelTimer.setInterval(MS_PER_SECOND * s.autoclearPanelSeconds);
3 ✔
535
  m_qtPass->setClipboardTimer();
3 ✔
536

537
  updateGitButtonVisibility();
3 ✔
538
  updateOtpButtonVisibility();
3 ✔
539
  updateGrepButtonVisibility();
3 ✔
540
  updateProcessOutputVisibility();
3 ✔
541
  if (s.useTrayIcon && m_tray == nullptr) {
3 ✔
542
    initTrayIcon();
×
543
  } else if (!s.useTrayIcon && m_tray != nullptr) {
3 ✔
544
    destroyTrayIcon();
×
545
  }
546

547
  // Leave the fresh-start state in place while the accepted configuration is
548
  // still unusable (for example the user declined to create the store), so
549
  // the next attempt from QtPass::init() runs the first-run wizard again
550
  // instead of showing the bare dialog. The re-prompt itself lives in init():
551
  // recursing here re-ran the dialog on this stack frame and never reported
552
  // a cancel back to the caller.
553
  if (Util::configIsValid(s)) {
3 ✔
554
    m_qtPass->setFreshStart(false);
1 ✔
555
  }
556
  return true;
557
}
4 ✔
558

559
/**
560
 * @brief MainWindow::onUpdate do a git pull
561
 */
562
void MainWindow::onUpdate(bool block) {
×
563
  ui->statusBar->showMessage(tr("Updating password-store"), 2000);
×
564
  if (block) {
×
565
    QtPassSettings::getPass()->GitPull_b();
×
566
  } else {
567
    QtPassSettings::getPass()->GitPull();
×
568
  }
569
}
×
570

571
/**
572
 * @brief MainWindow::onPush do a git push
573
 */
574
void MainWindow::onPush() {
×
575
  if (QtPassSettings::isUseGit()) {
×
576
    ui->statusBar->showMessage(tr("Updating password-store"), 2000);
×
577
    QtPassSettings::getPass()->GitPush();
×
578
  }
579
}
×
580

581
/**
582
 * @brief MainWindow::getFile get the selected file path
583
 * @param index
584
 * @param forPass returns relative path without '.gpg' extension
585
 * @return path
586
 * @return
587
 */
588
auto MainWindow::getFile(const QModelIndex &index, bool forPass) -> QString {
5 ✔
589
  if (!index.isValid() ||
5 ✔
590
      !model.fileInfo(proxyModel.mapToSource(index)).isFile()) {
10 ✔
591
    return {};
×
592
  }
593
  QString filePath = model.filePath(proxyModel.mapToSource(index));
5 ✔
594
  if (forPass) {
5 ✔
595
    filePath = QDir(QtPassSettings::getPassStore()).relativeFilePath(filePath);
15 ✔
596
    filePath.replace(Util::endsWithGpg(), "");
10 ✔
597
  }
598
  return filePath;
599
}
600

601
/**
602
 * @brief MainWindow::on_treeView_clicked read the selected password file
603
 * @param index
604
 */
605
void MainWindow::on_treeView_clicked(const QModelIndex &index) {
4 ✔
606
  bool cleared = ui->treeView->currentIndex().flags() == Qt::NoItemFlags;
4 ✔
607
  m_currentDir = Util::getDir(ui->treeView->currentIndex(), false, model,
8 ✔
608
                              proxyModel, QtPassSettings::getPassStore());
8 ✔
609
  QString file = getFile(index, true);
4 ✔
610
  ui->passwordName->setText(file);
4 ✔
611
  if (!file.isEmpty() && !cleared) {
4 ✔
612
    // Remember what the panel is about to show, so onOtp() can tell whether the
613
    // code it can see belongs to the entry that is currently selected.
614
    m_shownFile = file;
4 ✔
615
    QtPassSettings::getPass()->Show(file);
8 ✔
616
  } else {
617
    m_shownFile.clear();
×
618
    clearPanel(false);
×
619
    ui->actionEdit->setEnabled(false);
×
620
    ui->actionDelete->setEnabled(true);
×
621
  }
622
}
4 ✔
623

624
/**
625
 * @brief MainWindow::on_treeView_doubleClicked when doubleclicked on
626
 * TreeViewItem, open the edit Window
627
 * @param index
628
 */
629
void MainWindow::on_treeView_doubleClicked(const QModelIndex &index) {
1 ✔
630
  QFileInfo fileOrFolder =
631
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
1 ✔
632

633
  if (fileOrFolder.isFile()) {
1 ✔
634
    editPassword(getFile(index, true));
2 ✔
635
  }
636
}
1 ✔
637

638
/**
639
 * @brief MainWindow::deselect clear the selection, password and copy buffer
640
 */
641
void MainWindow::deselect() {
4 ✔
642
  m_currentDir = "";
4 ✔
643
  m_shownFile.clear();
4 ✔
644
  cancelOtpRequest();
4 ✔
645
  m_qtPass->clearClipboard();
4 ✔
646
  ui->treeView->clearSelection();
4 ✔
647
  ui->actionEdit->setEnabled(false);
4 ✔
648
  ui->actionDelete->setEnabled(false);
4 ✔
649
  ui->passwordName->setText("");
4 ✔
650
  clearPanel(false);
4 ✔
651
}
4 ✔
652

653
void MainWindow::executeWrapperStarted() {
7 ✔
654
  m_displayPanel->clear();
7 ✔
655
  ui->textBrowser->clear();
7 ✔
656
  setUiElementsEnabled(false);
7 ✔
657
  clearPanelTimer.stop();
7 ✔
658
  if (QtPassSettings::isShowProcessOutput()) {
7 ✔
659
    m_processOutputDock->setVisible(true);
2 ✔
660
  }
661
}
7 ✔
662

663
/**
664
 * @brief Handles displaying parsed password entry content in the main window.
665
 * @example
666
 * void result = MainWindow::passShowHandler(p_output);
667
 * // Updates the UI with parsed fields and emits
668
 * passShowHandlerFinished(output)
669
 *
670
 * @param p_output - The raw output text containing the password entry data.
671
 * @return void - This function does not return a value.
672
 */
673
void MainWindow::passShowHandler(const QString &p_output) {
5 ✔
674
  const AppSettings s = QtPassSettings::load();
5 ✔
675
  QStringList templ =
676
      s.useTemplate ? s.passTemplate.split("\n") : QStringList();
5 ✔
677
  bool allFields = s.useTemplate && s.templateAllFields;
5 ✔
678
  FileContent fileContent = FileContent::parse(p_output, templ, allFields);
5 ✔
679
  QString output = p_output;
680
  // Display variant: empty when the password line is itself an otpauth URI, so
681
  // the shared secret is neither rendered nor copied to the clipboard.
682
  QString password = fileContent.getPasswordForDisplay();
5 ✔
683

684
  // set clipped text
685
  //
686
  // Skipped for an OTP request: the user asked for a one-time code, not the
687
  // password, and writing both in one event-loop turn can leave the Windows
688
  // clipboard empty (two OleSetClipboard calls back to back).
689
  if (!m_otpRequestPending) {
5 ✔
690
    m_qtPass->setClippedText(password, p_output);
5 ✔
691
  }
692

693
  // first clear the current view:
694
  m_displayPanel->clear();
5 ✔
695

696
  // show what is needed:
697
  if (s.hideContent) {
5 ✔
698
    output = "***" + tr("Content hidden") + "***";
×
699
  } else if (!s.displayAsIs) {
5 ✔
700
    m_displayPanel->displayFields(password, fileContent.getNamedValues(), s,
8 ✔
701
                                  s.useOtp ? fileContent.getOtpUri()
4 ✔
702
                                           : QString());
703
    output = fileContent.getRemainingDataForDisplay();
8 ✔
704
  }
705

706
  if (s.useAutoclearPanel) {
5 ✔
707
    clearPanelTimer.start();
×
708
  }
709

710
  emit passShowHandlerFinished(output);
5 ✔
711
  setUiElementsEnabled(true);
5 ✔
712
}
10 ✔
713

714
/**
715
 * @brief Generates a one-time password from a decrypted entry and copies it.
716
 *
717
 * Connected as a one-shot to Pass::finishedShow by onOtp(). passShowHandler is
718
 * connected first, so by the time this runs the panel has already been
719
 * repainted and the UI re-enabled.
720
 *
721
 * @param p_output - The decrypted entry content.
722
 * @return void - This function does not return a value.
723
 */
724
void MainWindow::otpFromFileToClipboard(const QString &p_output) {
×
725
  disconnectSingleShot(QtPassSettings::getPass(), &Pass::finishedShow, this,
×
726
                       &MainWindow::otpFromFileToClipboard);
727
  // A failed decrypt never fires finishedShow, and Qt::SingleShotConnection
728
  // only self-disconnects when it does fire, so a connection armed by an
729
  // earlier failed request can still be live here. Ignore it rather than
730
  // hijacking an unrelated entry's decrypted content.
731
  if (!m_otpRequestPending) {
×
732
    return;
×
733
  }
734
  // finishedShow carries no request identity, so make sure this decrypt is the
735
  // one we asked for and not a tree click that happened to land first.
736
  if (m_otpRequestFile != getFile(ui->treeView->currentIndex(), true)) {
×
737
    cancelOtpRequest();
×
738
    setUiElementsEnabled(true);
×
739
    return;
×
740
  }
741
  m_otpRequestPending = false;
×
742
  m_otpRequestFile.clear();
×
743

744
  if (p_output.isEmpty()) {
×
745
    // Distinguish "could not read the entry" from "entry has no OTP".
746
    flashText(tr("Could not decrypt this password entry"), true);
×
747
    setUiElementsEnabled(true);
×
748
    return;
×
749
  }
750

751
  // passShowHandler is connected first, so it has already repainted the panel
752
  // for this same finishedShow. When it rendered the OTP row the current code
753
  // is derived and cached, so reuse it instead of re-loading settings and
754
  // re-parsing p_output (mirrors onOtp()'s fast path). Falls through to a fresh
755
  // parse when no OTP row is shown (hideContent / displayAsIs / no OTP field).
756
  const QString shown = m_displayPanel->currentOtpCode();
×
757
  if (!shown.isEmpty()) {
×
758
    m_qtPass->copyTextToClipboard(shown);
×
759
    showStatusMessage(tr("OTP code copied to clipboard"));
×
760
    setUiElementsEnabled(true);
×
761
    return;
762
  }
763

764
  const AppSettings s = QtPassSettings::load();
×
765
  // Parse with the same template settings passShowHandler uses, so an OTP
766
  // field is recognised identically in both paths.
767
  const QStringList templ =
768
      s.useTemplate ? s.passTemplate.split("\n") : QStringList();
×
769
  const bool allFields = s.useTemplate && s.templateAllFields;
×
770
  const FileContent fileContent =
771
      FileContent::parse(p_output, templ, allFields);
×
772

773
  const std::optional<Totp::Settings> settings =
774
      Totp::parse(fileContent.getOtpUri());
×
775
  if (settings.has_value()) {
×
776
    m_qtPass->copyTextToClipboard(Totp::generateNow(*settings));
×
777
    showStatusMessage(tr("OTP code copied to clipboard"));
×
778
  } else {
779
    flashText(tr("No OTP code found in this password entry"), true);
×
780
  }
781
  setUiElementsEnabled(true);
×
782
}
×
783

784
/**
785
 * @brief MainWindow::clearPanel hide the information from shoulder surfers
786
 */
787
void MainWindow::clearPanel(bool notify) {
5 ✔
788
  m_displayPanel->clear();
5 ✔
789
  const bool grepWasVisible = ui->grepResultsList->isVisible();
5 ✔
790
  ui->grepResultsList->clear();
5 ✔
791
  if (grepWasVisible) {
5 ✔
792
    ui->grepResultsList->setVisible(false);
×
793
    ui->treeView->setVisible(true);
×
794
    if (m_grep.inGrepMode()) {
×
795
      m_grep.clearGrepMode();
796
      ui->grepButton->blockSignals(true);
×
797
      ui->grepButton->setChecked(false);
×
798
      ui->grepButton->blockSignals(false);
×
799
      ui->lineEdit->blockSignals(true);
×
800
      ui->lineEdit->clear();
×
801
      ui->lineEdit->blockSignals(false);
×
802
      ui->lineEdit->setPlaceholderText(tr("Search Password"));
×
803
    }
804
  }
805
  if (notify) {
5 ✔
806
    QString output = "***" + tr("Password and Content hidden") + "***";
×
807
    ui->textBrowser->setHtml(output);
×
808
  } else {
809
    ui->textBrowser->setHtml("");
10 ✔
810
  }
811
}
5 ✔
812

813
/**
814
 * @brief MainWindow::setUiElementsEnabled enable or disable the relevant UI
815
 * elements
816
 * @param state
817
 */
818
void MainWindow::setUiElementsEnabled(bool state) {
58 ✔
819
  // Arm the watchdog while the UI is disabled; disarm once re-enabled.
820
  if (state) {
58 ✔
821
    m_uiWatchdog.stop();
49 ✔
822
  } else {
823
    m_uiWatchdog.start();
9 ✔
824
  }
825
  ui->treeView->setEnabled(state);
58 ✔
826
  ui->lineEdit->setEnabled(state);
58 ✔
827
  ui->actionAddPassword->setEnabled(state);
58 ✔
828
  ui->actionAddFolder->setEnabled(state);
58 ✔
829
  ui->actionUsers->setEnabled(state);
58 ✔
830
  ui->actionConfig->setEnabled(state);
58 ✔
831
  // is a file selected?
832
  state &= ui->treeView->currentIndex().isValid();
116 ✔
833
  ui->actionDelete->setEnabled(state);
58 ✔
834
  ui->actionEdit->setEnabled(state);
58 ✔
835
  updateGitButtonVisibility();
58 ✔
836
  // `state` is now "UI enabled AND a file is selected", which is exactly when
837
  // generating an OTP makes sense.
838
  updateOtpButtonVisibility(state);
58 ✔
839
}
58 ✔
840

841
/**
842
 * @brief Restores the main window geometry, state, position, size, and
843
 * tray/icon settings from saved application settings.
844
 * @example
845
 * MainWindow window;
846
 * window.restoreWindow();
847
 *
848
 * @return void - This function does not return a value.
849
 */
850
void MainWindow::restoreWindow() {
35 ✔
851
  QByteArray geometry = QtPassSettings::getGeometry(saveGeometry());
35 ✔
852
  restoreGeometry(geometry);
35 ✔
853
  QByteArray savestate = QtPassSettings::getSavestate(saveState());
35 ✔
854
  restoreState(savestate);
35 ✔
855
  QPoint position = QtPassSettings::getPos(pos());
35 ✔
856
  move(position);
35 ✔
857
  QSize newSize = QtPassSettings::getSize(size());
35 ✔
858
  resize(newSize);
35 ✔
859
  const AppSettings s = QtPassSettings::load();
35 ✔
860
  if (s.maximized) {
35 ✔
861
    showMaximized();
×
862
  }
863

864
  if (s.alwaysOnTop) {
35 ✔
865
    Qt::WindowFlags flags = windowFlags();
866
    setWindowFlags(flags | Qt::WindowStaysOnTopHint);
×
867
    show();
×
868
  }
869

870
  if (s.useTrayIcon && m_tray == nullptr) {
35 ✔
871
    initTrayIcon();
2 ✔
872
    // Minimized to the tray only when there is one: without a system tray
873
    // initTrayIcon() gave up, and a hidden window could not be brought back.
874
    if (s.startMinimized && m_tray != nullptr) {
2 ✔
875
      // since we are still in constructor, can't directly hide
876
      QTimer::singleShot(10, this, SLOT(hide()));
×
877
    }
878
  } else if (!s.useTrayIcon && m_tray != nullptr) {
33 ✔
879
    destroyTrayIcon();
×
880
  }
881
}
70 ✔
882

883
/**
884
 * @brief MainWindow::on_configButton_clicked run Mainwindow::config
885
 */
886
void MainWindow::onConfig() { config(); }
×
887

888
/**
889
 * @brief Executes when the string in the search box changes, collapses the
890
 * TreeView
891
 * @param arg1
892
 */
893
void MainWindow::on_lineEdit_textChanged(const QString &arg1) {
3 ✔
894
  if (m_grep.inGrepMode())
3 ✔
895
    return;
896
  ui->statusBar->showMessage(tr("Looking for: %1").arg(arg1), 1000);
2 ✔
897
  ui->treeView->expandAll();
1 ✔
898
  clearPanel(false);
1 ✔
899
  ui->passwordName->setText("");
2 ✔
900
  ui->actionEdit->setEnabled(false);
1 ✔
901
  ui->actionDelete->setEnabled(false);
1 ✔
902
  searchTimer.start();
1 ✔
903
}
904

905
/**
906
 * @brief MainWindow::onTimeoutSearch Fired when search is finished or too much
907
 * time from two keypresses is elapsed
908
 */
909
void MainWindow::onTimeoutSearch() {
1 ✔
910
  QString query = ui->lineEdit->text();
1 ✔
911

912
  if (query.isEmpty()) {
1 ✔
913
    ui->treeView->collapseAll();
×
914
    deselect();
×
915
  }
916

917
  query.replace(QStringLiteral(" "), ".*");
2 ✔
918
  QRegularExpression regExp(query, QRegularExpression::CaseInsensitiveOption);
1 ✔
919
  if (!regExp.isValid())
1 ✔
920
    return;
921
  proxyModel.setFilterRegularExpression(regExp);
1 ✔
922
  ui->treeView->setRootIndex(
1 ✔
923
      proxyModel.rootIndexFor(QtPassSettings::getPassStore()));
2 ✔
924

925
  if (proxyModel.rowCount() > 0 && !query.isEmpty()) {
1 ✔
926
    selectFirstFile();
1 ✔
927
  } else {
928
    ui->actionEdit->setEnabled(false);
×
929
    ui->actionDelete->setEnabled(false);
×
930
  }
931
}
1 ✔
932

933
/**
934
 * @brief MainWindow::on_lineEdit_returnPressed get searching
935
 *
936
 * Select the first possible file in the tree
937
 */
938
void MainWindow::on_lineEdit_returnPressed() {
3 ✔
939
#ifdef QT_DEBUG
940
  dbg() << "on_lineEdit_returnPressed" << proxyModel.rowCount();
941
#endif
942

943
  if (m_grep.inGrepMode()) {
3 ✔
944
    const QString query = ui->lineEdit->text();
2 ✔
945
    if (!query.isEmpty()) {
2 ✔
946
      ui->grepResultsList->clear();
1 ✔
947
      ui->statusBar->showMessage(tr("Searching…"));
2 ✔
948
      if (m_grep.beginSearch()) {
949
        QApplication::setOverrideCursor(Qt::WaitCursor);
1 ✔
950
      }
951
      QtPassSettings::getPass()->Grep(query, ui->grepCaseButton->isChecked());
2 ✔
952
    } else {
953
      if (m_grep.cancelSearch()) {
954
        QApplication::restoreOverrideCursor();
×
955
      }
956
      ui->grepResultsList->clear();
1 ✔
957
      ui->grepResultsList->setVisible(false);
1 ✔
958
      ui->treeView->setVisible(true);
1 ✔
959
    }
960
    return;
961
  }
962

963
  if (proxyModel.rowCount() > 0) {
1 ✔
964
    selectFirstFile();
1 ✔
965
    on_treeView_clicked(ui->treeView->currentIndex());
1 ✔
966
  }
967
}
968

969
/**
970
 * @brief Toggle grep (content search) mode.
971
 */
972
void MainWindow::on_grepButton_toggled(bool checked) {
3 ✔
973
  const AppSettings s = QtPassSettings::load();
3 ✔
974
  if (checked) {
3 ✔
975
    m_grep.enterGrepMode();
976
    ui->lineEdit->setPlaceholderText(tr("Search content (regex)"));
4 ✔
977
    // The regex dialect depends on the backend (see Pass::Grep): the pass
978
    // backend uses POSIX BRE via `pass grep`, the native backend uses PCRE.
979
    ui->lineEdit->setToolTip(
2 ✔
980
        s.usePass
2 ✔
981
            ? tr("Content search uses POSIX basic regular expressions "
4 ✔
982
                 "(pass grep).")
983
            : tr("Content search uses Perl-compatible regular expressions "
984
                 "(PCRE)."));
985
    ui->lineEdit->clear();
2 ✔
986
    searchTimer.stop();
2 ✔
987
    proxyModel.setFilterRegularExpression(QRegularExpression());
2 ✔
988
    ui->treeView->setRootIndex(proxyModel.rootIndexFor(s.passStore));
2 ✔
989
    ui->grepResultsList->setVisible(false);
2 ✔
990
    // Keep treeView visible until results arrive
991
  } else {
992
    if (m_grep.leaveGrepMode()) {
993
      QApplication::restoreOverrideCursor();
×
994
    }
995
    searchTimer.stop();
1 ✔
996
    ui->lineEdit->blockSignals(true);
1 ✔
997
    ui->lineEdit->clear();
1 ✔
998
    ui->lineEdit->blockSignals(false);
1 ✔
999
    ui->lineEdit->setPlaceholderText(tr("Search Password"));
2 ✔
1000
    ui->lineEdit->setToolTip(QString());
2 ✔
1001
    ui->grepResultsList->clear();
1 ✔
1002
    ui->grepResultsList->setVisible(false);
1 ✔
1003
    ui->treeView->setVisible(true);
1 ✔
1004
    proxyModel.setFilterRegularExpression(QRegularExpression());
1 ✔
1005
    ui->treeView->setRootIndex(proxyModel.rootIndexFor(s.passStore));
1 ✔
1006
  }
1007
}
3 ✔
1008

1009
/**
1010
 * @brief Display grep results in grepResultsList.
1011
 */
1012
void MainWindow::onGrepFinished(
1 ✔
1013
    const QList<QPair<QString, QStringList>> &results) {
1014
  const GrepSearchController::FinishOutcome outcome = m_grep.finishSearch();
1015
  if (outcome.restoreCursor) {
1 ✔
1016
    QApplication::restoreOverrideCursor();
1 ✔
1017
  }
1018
  // Re-enable the UI before the discard check so a cancelled search can never
1019
  // leave controls disabled.
1020
  setUiElementsEnabled(true);
1 ✔
1021
  if (outcome.discard) {
1 ✔
1022
    return;
1 ✔
1023
  }
1024
  if (!m_grep.inGrepMode())
1 ✔
1025
    return;
1026
  ui->grepResultsList->clear();
1 ✔
1027
  if (results.isEmpty()) {
1 ✔
1028
    ui->statusBar->showMessage(tr("No matches found."), 3000);
2 ✔
1029
    ui->grepResultsList->setVisible(false);
1 ✔
1030
    ui->treeView->setVisible(true);
1 ✔
1031
    return;
1 ✔
1032
  }
1033
  const AppSettings s = QtPassSettings::load();
×
1034
  const bool hideContent = s.hideContent;
×
1035
  int totalLines = 0;
1036
  for (const auto &pair : results) {
×
1037
    auto *entryItem = new QTreeWidgetItem(ui->grepResultsList);
×
1038
    entryItem->setText(0, pair.first);
×
1039
    entryItem->setData(0, Qt::UserRole, pair.first);
×
1040
    for (const QString &line : pair.second) {
×
1041
      auto *lineItem = new QTreeWidgetItem(entryItem);
×
1042
      lineItem->setText(0, hideContent ? "***" + tr("Content hidden") + "***"
×
1043
                                       : line);
1044
      lineItem->setData(0, Qt::UserRole, pair.first);
×
1045
      ++totalLines;
×
1046
    }
1047
  }
1048
  ui->grepResultsList->expandAll();
×
1049
  ui->treeView->setVisible(false);
×
1050
  ui->grepResultsList->setVisible(true);
×
1051
  ui->statusBar->showMessage(
×
1052
      tr("Found %n match(es)", nullptr, totalLines) + " " +
×
1053
          tr("in %n entr(ies).", nullptr, static_cast<int>(results.size())),
×
1054
      3000);
1055
  if (s.useAutoclearPanel)
×
1056
    clearPanelTimer.start();
×
1057
}
×
1058

1059
/**
1060
 * @brief Navigate to the password entry when a grep result is clicked.
1061
 */
1062
void MainWindow::on_grepResultsList_itemClicked(QTreeWidgetItem *item,
1 ✔
1063
                                                int /*column*/) {
1064
  const AppSettings s = QtPassSettings::load();
1 ✔
1065
  const QString entry = item->data(0, Qt::UserRole).toString();
1 ✔
1066
  if (entry.isEmpty())
1 ✔
1067
    return;
1068
  const QString fullPath =
1069
      QDir::cleanPath(QDir(s.passStore).filePath(entry + ".gpg"));
2 ✔
1070
  QModelIndex srcIndex = model.index(fullPath);
1 ✔
1071
  if (!srcIndex.isValid())
1072
    return;
1073
  QModelIndex proxyIndex = proxyModel.mapFromSource(srcIndex);
1 ✔
1074
  if (!proxyIndex.isValid())
1075
    return;
1076
  ui->treeView->setCurrentIndex(proxyIndex);
1 ✔
1077
  on_treeView_clicked(proxyIndex);
1 ✔
1078
  if (s.hideContent || s.useAutoclearPanel)
1 ✔
1079
    ui->grepResultsList->clear();
×
1080
  ui->grepResultsList->setVisible(false);
1 ✔
1081
  ui->treeView->setVisible(true);
1 ✔
1082
  ui->treeView->scrollTo(proxyIndex);
1 ✔
1083
  ui->treeView->setFocus();
1 ✔
1084
}
1 ✔
1085

1086
/**
1087
 * @brief MainWindow::selectFirstFile select the first possible file in the
1088
 * tree
1089
 */
1090
void MainWindow::selectFirstFile() {
2 ✔
1091
  QModelIndex index = proxyModel.rootIndexFor(QtPassSettings::getPassStore());
4 ✔
1092
  index = firstFile(index);
2 ✔
1093
  ui->treeView->setCurrentIndex(index);
2 ✔
1094
}
2 ✔
1095

1096
/**
1097
 * @brief MainWindow::firstFile return location of first possible file
1098
 * @param parentIndex
1099
 * @return QModelIndex
1100
 */
1101
auto MainWindow::firstFile(QModelIndex parentIndex) -> QModelIndex {
2 ✔
1102
  int numRows = proxyModel.rowCount(parentIndex);
2 ✔
1103
  for (int row = 0; row < numRows; ++row) {
2 ✔
1104
    QModelIndex index = proxyModel.index(row, 0, parentIndex);
2 ✔
1105
    if (model.fileInfo(proxyModel.mapToSource(index)).isFile()) {
2 ✔
1106
      return index;
2 ✔
1107
    }
1108
    if (proxyModel.hasChildren(index)) {
×
1109
      QModelIndex childFile = firstFile(index);
×
1110
      if (childFile.isValid())
1111
        return childFile;
×
1112
    }
1113
  }
1114
  return QModelIndex();
×
1115
}
1116

1117
/**
1118
 * @brief MainWindow::confirmPathInStore reject paths that resolve outside
1119
 * the password store and warn the user.
1120
 *
1121
 * Used before file/folder creation, move, and rename to stop user-typed
1122
 * names like "../../etc/passwd" or absolute paths from escaping the
1123
 * configured store root via the input dialogs.
1124
 *
1125
 * @param candidate Absolute candidate path to validate.
1126
 * @return true if the path is inside the password store; false otherwise (a
1127
 * warning dialog is shown in that case).
1128
 */
1129
auto MainWindow::confirmPathInStore(const QString &candidate) -> bool {
×
1130
  if (PathValidator::isPathInStore(QtPassSettings::getPassStore(), candidate)) {
×
1131
    return true;
1132
  }
1133
  QMessageBox::warning(this, tr("Invalid name"),
×
1134
                       tr("That name would resolve outside the password "
×
1135
                          "store. Please choose a different name."));
1136
  return false;
×
1137
}
1138

1139
/**
1140
 * @brief MainWindow::setPassword open passworddialog
1141
 * @param file which pgp file
1142
 * @param isNew insert (not update)
1143
 */
1144
void MainWindow::setPassword(const QString &file, bool isNew) {
1 ✔
1145
  const AppSettings s = QtPassSettings::load();
1 ✔
1146
  PasswordDialog d(QtPassSettings::getPass(), s, file, isNew, this);
1 ✔
1147

1148
  if (isNew) {
1 ✔
1149
    const QString storePath = s.passStore;
1150
    QString folder = Util::getDir(ui->treeView->currentIndex(), false, model,
×
1151
                                  proxyModel, s.passStore);
×
1152
    if (folder.isEmpty()) {
×
1153
      folder = storePath;
×
1154
    }
1155
    QHash<QString, QStringList> templates =
1156
        TemplateIO::readTemplates(storePath);
×
1157
    if (!templates.isEmpty()) {
1158
      QString defaultTemplate =
1159
          TemplateIO::getFolderTemplate(folder, storePath);
×
1160
      d.setAvailableTemplates(templates, defaultTemplate);
×
1161
      new QShortcut(QKeySequence(Qt::CTRL | Qt::Key_T), &d,
×
1162
                    [&d]() { d.cycleTemplate(); });
×
1163
    }
1164
  }
×
1165

1166
  if (!d.exec()) {
1 ✔
1167
    ui->treeView->setFocus();
×
1168
  }
1169
}
1 ✔
1170

1171
/**
1172
 * @brief MainWindow::addPassword add a new password by showing a
1173
 * number of dialogs.
1174
 */
1175
void MainWindow::addPassword() {
×
1176
  const QString passStore = QtPassSettings::load().passStore;
×
1177
  bool ok;
1178
  QString dir = Util::getDir(ui->treeView->currentIndex(), true, model,
×
1179
                             proxyModel, passStore);
×
1180
  QString file = QInputDialog::getText(
1181
      this, tr("New file"),
×
1182
      tr("New password file: \n(Will be placed in %1 )")
×
1183
          .arg(passStore + Util::getDir(ui->treeView->currentIndex(), true,
×
1184
                                        model, proxyModel, passStore)),
×
1185
      QLineEdit::Normal, "", &ok);
×
1186
  if (!ok || file.isEmpty()) {
×
1187
    return;
1188
  }
1189
  file = dir + file;
×
1190
  if (!confirmPathInStore(passStore + file)) {
×
1191
    return;
1192
  }
1193
  setPassword(file);
×
1194
}
1195

1196
/**
1197
 * @brief MainWindow::onDelete remove password, if you are
1198
 * sure.
1199
 */
1200
void MainWindow::onDelete() {
×
1201
  QModelIndex currentIndex = ui->treeView->currentIndex();
×
1202
  if (!currentIndex.isValid()) {
1203
    // This fixes https://github.com/IJHack/QtPass/issues/556
1204
    // Otherwise the entire password directory would be deleted if
1205
    // nothing is selected in the tree view.
1206
    return;
×
1207
  }
1208

1209
  QFileInfo fileOrFolder =
1210
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
1211
  QString file = "";
×
1212
  bool isDir = false;
1213

1214
  if (fileOrFolder.isFile()) {
×
1215
    file = getFile(ui->treeView->currentIndex(), true);
×
1216
  } else {
1217
    file = Util::getDir(ui->treeView->currentIndex(), true, model, proxyModel,
×
1218
                        QtPassSettings::getPassStore());
×
1219
    isDir = true;
1220
  }
1221

1222
  QString dirMessage = tr(" and the whole content?");
1223
  if (isDir) {
×
1224
    QDirIterator it(model.rootPath() + QDir::separator() + file,
×
1225
                    QDirIterator::Subdirectories);
×
1226
    bool okDir = true;
1227
    while (it.hasNext() && okDir) {
×
1228
      it.next();
×
1229
      if (QFileInfo(it.filePath()).isFile()) {
×
1230
        if (QFileInfo(it.filePath()).suffix() != "gpg") {
×
1231
          okDir = false;
1232
          dirMessage = tr(" and the whole content? <br><strong>Attention: "
×
1233
                          "there are unexpected files in the given folder, "
1234
                          "check them before continue.</strong>");
1235
        }
1236
      }
1237
    }
1238
  }
×
1239

1240
  if (QMessageBox::question(
×
1241
          this, isDir ? tr("Delete folder?") : tr("Delete password?"),
×
1242
          tr("Are you sure you want to delete %1%2?")
×
1243
              .arg(QDir::separator() + file, isDir ? dirMessage : "?"),
×
1244
          QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) {
1245
    return;
1246
  }
1247

1248
  QtPassSettings::getPass()->Remove(file, isDir);
×
1249
}
×
1250

1251
/**
1252
 * @brief MainWindow::cancelOtpRequest abandon an in-flight OTP request.
1253
 *
1254
 * Connected to Pass::processErrorExit, and called from deselect(). A failed
1255
 * decrypt never emits finishedShow, and the error handler re-enables the UI —
1256
 * which stops the watchdog that was the only other thing clearing the flag.
1257
 * Left set, it permanently suppressed passShowHandler's copy-on-select and let
1258
 * the still-armed one-shot claim the next unrelated decrypt.
1259
 *
1260
 * The same failed decrypt would otherwise leave m_passwordCopyPending stuck
1261
 * (its only other reset is passwordFromFileToClipboard, which never runs when
1262
 * finishedShow is not emitted), permanently blocking Ctrl+C, so clear it here
1263
 * too. Unlike otpFromFileToClipboard, that slot has no pending-flag guard, so
1264
 * its single-shot connection must be torn down here as well — otherwise a
1265
 * connection left armed by the failed decrypt would claim the next unrelated
1266
 * finishedShow and copy the wrong entry to the clipboard. disconnectSingleShot
1267
 * is a no-op on Qt 6 (the never-fired connection persists until it emits), so
1268
 * disconnect unconditionally.
1269
 */
1270
void MainWindow::cancelOtpRequest() {
6 ✔
1271
  m_otpRequestPending = false;
6 ✔
1272
  m_otpRequestFile.clear();
6 ✔
1273
  disconnect(QtPassSettings::getPass(), &Pass::finishedShow, this,
6 ✔
1274
             &MainWindow::passwordFromFileToClipboard);
1275
  m_passwordCopyPending = false;
6 ✔
1276
}
6 ✔
1277

1278
/**
1279
 * @brief MainWindow::onOtp generate the selected entry's OTP code and copy it.
1280
 *
1281
 * Decrypts the entry once and derives the code in-process, so this works with
1282
 * either backend and on every platform. The code itself is produced by
1283
 * otpFromFileToClipboard once Pass::finishedShow arrives.
1284
 */
1285
void MainWindow::onOtp() {
×
1286
  QString file = getFile(ui->treeView->currentIndex(), true);
×
1287
  if (file.isEmpty()) {
×
1288
    flashText(tr("No password selected for OTP generation"), true);
×
1289
    return;
×
1290
  }
1291
  if (!QtPassSettings::isUseOtp()) {
×
1292
    // Normally unreachable (the action is hidden), but never fail silently.
1293
    flashText(tr("No OTP code found in this password entry"), true);
×
1294
    return;
×
1295
  }
1296

1297
  // Fast path: the panel already shows a live code for the selected entry, so
1298
  // there is nothing to decrypt. This also keeps the clipboard write single —
1299
  // going through Show() would let passShowHandler copy the password first, and
1300
  // two QClipboard::setMimeData calls in one event-loop turn can leave the
1301
  // Windows clipboard empty.
1302
  //
1303
  // Only when the panel is showing *this* entry: arrow-key navigation and
1304
  // right-clicking move the tree's currentIndex without emitting
1305
  // QTreeView::clicked, so the visible code can belong to a different account.
1306
  const QString shown =
1307
      (m_shownFile == file) ? m_displayPanel->currentOtpCode() : QString();
×
1308
  if (!shown.isEmpty()) {
×
1309
    m_qtPass->copyTextToClipboard(shown);
×
1310
    showStatusMessage(tr("OTP code copied to clipboard"));
×
1311
    return;
1312
  }
1313

1314
  // Fallback: no OTP row on screen, so decrypt once. The flag stops
1315
  // passShowHandler putting the password on the clipboard for a request that
1316
  // only asked for a code.
1317
  m_otpRequestPending = true;
×
1318
  m_otpRequestFile = file;
×
1319
  setUiElementsEnabled(false);
×
1320
  connectSingleShot(QtPassSettings::getPass(), &Pass::finishedShow, this,
×
1321
                    &MainWindow::otpFromFileToClipboard);
1322
  // passShowHandler repaints the panel for this Show too, so keep the marker in
1323
  // step or a second request would decrypt again instead of taking the fast
1324
  // path. Safe to set now: executeWrapperStarted() clears the panel on every
1325
  // command, so a failed decrypt leaves currentOtpCode() empty.
1326
  m_shownFile = file;
×
1327
  QtPassSettings::getPass()->Show(file);
×
1328
}
1329

1330
/**
1331
 * @brief MainWindow::onEdit try and edit (selected) password.
1332
 */
1333
void MainWindow::onEdit() {
×
1334
  QString file = getFile(ui->treeView->currentIndex(), true);
×
1335
  editPassword(file);
×
1336
}
×
1337

1338
/**
1339
 * @brief MainWindow::userDialog see MainWindow::onUsers()
1340
 * @param dir folder to edit users for.
1341
 */
1342
void MainWindow::userDialog(const QString &dir) {
×
1343
  if (!dir.isEmpty()) {
×
1344
    m_currentDir = dir;
×
1345
  }
1346
  onUsers();
×
1347
}
×
1348

1349
/**
1350
 * @brief MainWindow::onUsers edit users for the current
1351
 * folder,
1352
 * gets lists and opens UserDialog.
1353
 */
1354
void MainWindow::onUsers() {
×
1355
  QString dir = m_currentDir.isEmpty()
1356
                    ? Util::getDir(ui->treeView->currentIndex(), false, model,
×
1357
                                   proxyModel, QtPassSettings::getPassStore())
×
1358
                    : m_currentDir;
×
1359

1360
  UsersDialog d(QtPassSettings::getPass(), QtPassSettings::load(), dir, this);
×
1361
  if (!d.exec()) {
×
1362
    ui->treeView->setFocus();
×
1363
  }
1364
}
×
1365

1366
/**
1367
 * @brief MainWindow::messageAvailable we have some text/message/search to do.
1368
 * @param message
1369
 */
1370
void MainWindow::messageAvailable(const QString &message) {
×
1371
  show();
×
1372
  raise();
×
1373
  if (message.isEmpty()) {
×
1374
    focusInput();
×
1375
  } else {
1376
    ui->treeView->expandAll();
×
1377
    ui->lineEdit->setText(message);
×
1378
    on_lineEdit_returnPressed();
×
1379
  }
1380
}
×
1381

1382
/**
1383
 * @brief MainWindow::generateKeyPair internal gpg keypair generator . .
1384
 * @param batch
1385
 * @param keygenWindow
1386
 */
1387
void MainWindow::generateKeyPair(const QString &batch, QDialog *keygenWindow) {
×
1388
  m_keyGenDialog = keygenWindow;
1389
  emit generateGPGKeyPair(batch);
×
1390
}
×
1391

1392
/**
1393
 * @brief MainWindow::updateProfileBox update the list of profiles, optionally
1394
 * select a more appropriate one to view too
1395
 */
1396
void MainWindow::updateProfileBox() {
35 ✔
1397
  QHash<QString, QHash<QString, QString>> profiles =
1398
      QtPassSettings::getProfiles();
35 ✔
1399

1400
  if (profiles.isEmpty()) {
1401
    ui->profileWidget->hide();
35 ✔
1402
  } else {
1403
    ui->profileWidget->show();
×
1404
    ui->profileBox->setEnabled(profiles.size() > 1);
×
1405
    ui->profileBox->clear();
×
1406
    QHashIterator<QString, QHash<QString, QString>> i(profiles);
×
1407
    while (i.hasNext()) {
×
1408
      i.next();
1409
      if (!i.key().isEmpty()) {
×
1410
        ui->profileBox->addItem(i.key());
×
1411
      }
1412
    }
1413
    ui->profileBox->model()->sort(0);
×
1414
  }
1415
  int index = ui->profileBox->findText(QtPassSettings::getProfile());
70 ✔
1416
  if (index != -1) { //  -1 for not found
35 ✔
1417
    ui->profileBox->setCurrentIndex(index);
×
1418
  }
1419
}
35 ✔
1420

1421
/**
1422
 * @brief MainWindow::on_profileBox_currentIndexChanged make sure we show the
1423
 * correct "profile"
1424
 * @param name
1425
 */
1426
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
1427
void MainWindow::on_profileBox_currentIndexChanged(const QString &name) {
1428
#else
1429
/**
1430
 * @brief Handles changes to the selected profile in the profile combo box.
1431
 * @details Ignores the event during a fresh start or when the selected profile
1432
 * matches the current profile. Otherwise, it clears the password field, updates
1433
 * the active profile and related settings, refreshes the environment, and
1434
 * resets the tree view and action states to reflect the newly selected profile.
1435
 *
1436
 * @param name - The newly selected profile name.
1437
 * @return void - This function does not return a value.
1438
 *
1439
 */
1440
void MainWindow::on_profileBox_currentTextChanged(const QString &name) {
×
1441
#endif
1442
  if (m_qtPass->isFreshStart() || name == QtPassSettings::getProfile()) {
×
1443
    return;
×
1444
  }
1445

1446
  ui->lineEdit->clear();
×
1447

1448
  const QHash<QString, QString> prof =
1449
      QtPassSettings::getProfiles().value(name);
×
1450
  AppSettings s = QtPassSettings::load();
×
1451
  s.activeProfile = name;
×
1452
  s.passStore = prof.value("path");
×
1453
  s.passSigningKey = prof.value("signingKey");
×
1454
  // Per-profile git flags (#1140) were stored but never applied; a profile
1455
  // without them keeps the global values.
1456
  const auto flag = [&prof](const char *key, bool current) {
×
1457
    const QString value = prof.value(QLatin1String(key));
×
1458
    return value.isEmpty() ? current : value == QLatin1String("true");
×
1459
  };
×
1460
  s.useGit = flag("useGit", s.useGit);
×
1461
  s.autoPush = flag("autoPush", s.autoPush);
×
1462
  s.autoPull = flag("autoPull", s.autoPull);
×
1463
  QtPassSettings::save(s);
×
1464
  ui->statusBar->showMessage(tr("Profile changed to %1").arg(name), 2000);
×
1465

1466
  QtPassSettings::getPass()->updateEnv();
×
1467

1468
  const QString passStore = QtPassSettings::getPassStore();
×
1469
  proxyModel.setStore(passStore);
×
1470
  ui->treeView->setRootIndex(proxyModel.rootIndexFor(passStore));
×
1471
  deselect();
×
1472
  ui->treeView->setCurrentIndex(QModelIndex());
×
1473
}
×
1474

1475
/**
1476
 * @brief MainWindow::initTrayIcon show a nice tray icon on systems that
1477
 * support
1478
 * it
1479
 */
1480
void MainWindow::initTrayIcon() {
2 ✔
1481
  m_tray = new TrayIcon(this);
2 ✔
1482
  if (!m_tray->getIsAllocated()) {
2 ✔
1483
    destroyTrayIcon();
2 ✔
1484
  }
1485
}
2 ✔
1486

1487
/**
1488
 * @brief MainWindow::destroyTrayIcon remove that pesky tray icon
1489
 */
1490
void MainWindow::destroyTrayIcon() {
2 ✔
1491
  delete m_tray;
2 ✔
1492
  m_tray = nullptr;
2 ✔
1493
}
2 ✔
1494

1495
/**
1496
 * @brief MainWindow::closeEvent hide or quit
1497
 * @param event
1498
 */
1499
void MainWindow::closeEvent(QCloseEvent *event) {
2 ✔
1500
  // Only with a tray icon to come back from: without one (none asked for, or
1501
  // no system tray in this session) a hidden QtPass ran on invisibly, with the
1502
  // last entry in its window and the password on the clipboard.
1503
  if (QtPassSettings::isHideOnClose() && m_tray != nullptr) {
4 ✔
UNCOV
1504
    this->hide();
×
1505
    event->ignore();
1506
  } else {
1507
    m_qtPass->clearClipboard();
2 ✔
1508

1509
    QtPassSettings::setGeometry(saveGeometry());
2 ✔
1510
    QtPassSettings::setSavestate(saveState());
2 ✔
1511
    QtPassSettings::setMaximized(isMaximized());
2 ✔
1512
    if (!isMaximized()) {
2 ✔
1513
      QtPassSettings::setPos(pos());
2 ✔
1514
      QtPassSettings::setSize(size());
2 ✔
1515
    }
1516
    event->accept();
1517
    // A visible QSystemTrayIcon keeps the application alive after the last
1518
    // window closes, so quitOnLastWindowClosed never fires and the window
1519
    // merely vanishes into the tray. Quit explicitly so closing the window
1520
    // actually exits when "hide on close" is disabled.
1521
    QApplication::quit();
2 ✔
1522
  }
1523
}
2 ✔
1524

1525
/**
1526
 * @brief MainWindow::eventFilter filter out some events and focus the
1527
 * treeview
1528
 * @param obj
1529
 * @param event
1530
 * @return
1531
 */
1532
auto MainWindow::eventFilter(QObject *obj, QEvent *event) -> bool {
1,276 ✔
1533
  if (obj == ui->toolBar && event->type() == QEvent::PaletteChange) {
1,276 ✔
1534
    // KDE's Breeze style gives top toolbars a "header" palette of its own.
1535
    // After a runtime light/dark switch it recomputes that palette from a
1536
    // cached kdeglobals and stamps the previous theme's colours back on, so
1537
    // the toolbar stays dark on a light window (or vice versa) with matching
1538
    // invisible icons. A legitimate header tint is close to the window
1539
    // colour; a stale theme is not. When the two disagree, drop the imposed
1540
    // palette so the toolbar follows the application palette again. Deferred
1541
    // so we never re-enter the style while it is still applying its palette.
1542
    QTimer::singleShot(0, this, &MainWindow::dropStaleToolBarPalette);
6 ✔
1543
  }
1544
  if (obj == ui->lineEdit && event->type() == QEvent::KeyPress) {
1,276 ✔
1545
    auto *key = dynamic_cast<QKeyEvent *>(event);
3 ✔
1546
    if (key != nullptr && key->key() == Qt::Key_Down) {
3 ✔
1547
      ui->treeView->setFocus();
×
1548
    }
1549
    // Return ends at the search box: QLineEdit emits returnPressed() and
1550
    // leaves the key unaccepted, so keyPressEvent() would open the tree's
1551
    // current entry as well. In content search that is an entry nobody
1552
    // asked for; by name, the first hit a second time.
1553
    if (key != nullptr &&
3 ✔
NEW
1554
        (key->key() == Qt::Key_Return || key->key() == Qt::Key_Enter)) {
×
1555
      ui->lineEdit->event(event);
3 ✔
1556
      event->accept();
1557
      return true;
3 ✔
1558
    }
1559
  }
1560
  return QObject::eventFilter(obj, event);
1,273 ✔
1561
}
1562

1563
/**
1564
 * @brief Reset the toolbar palette when a style left it in the wrong theme.
1565
 *
1566
 * Compares the lightness of the toolbar's Window colour with the application
1567
 * palette; a difference above kStaleToolBarLightness means the toolbar shows
1568
 * the other theme. See the PaletteChange branch in eventFilter().
1569
 */
1570
void MainWindow::dropStaleToolBarPalette() {
3 ✔
1571
  if (!ui->toolBar->testAttribute(Qt::WA_SetPalette)) {
3 ✔
1572
    return;
1573
  }
1574
  constexpr int kStaleToolBarLightness = 64;
1575
  const int barLightness =
1576
      ui->toolBar->palette().color(QPalette::Window).lightness();
4 ✔
1577
  const int appLightness =
1578
      QApplication::palette().color(QPalette::Window).lightness();
4 ✔
1579
  if (qAbs(barLightness - appLightness) > kStaleToolBarLightness) {
2 ✔
1580
    ui->toolBar->setPalette(QPalette());
1 ✔
1581
    // The style also paints the tools-area background on the main window
1582
    // from the same stale palette, and the toolbar is transparent by default;
1583
    // paint our own background so the reset is actually visible.
1584
    ui->toolBar->setAutoFillBackground(true);
1 ✔
1585
  }
1586
}
1587

1588
/**
1589
 * @brief MainWindow::keyPressEvent did anyone press return, enter or escape?
1590
 * @param event
1591
 */
1592
void MainWindow::keyPressEvent(QKeyEvent *event) {
1 ✔
1593
  switch (event->key()) {
1 ✔
1594
  case Qt::Key_Delete:
×
1595
    onDelete();
×
1596
    break;
×
1597
  case Qt::Key_Return:
1 ✔
1598
  case Qt::Key_Enter:
1599
    // While content search results hide the tree, its current entry is not
1600
    // what the user looks at: Return on a result opens that result.
1601
    if (ui->treeView->isHidden()) {
1 ✔
1602
      QTreeWidgetItem *result = ui->grepResultsList->currentItem();
1 ✔
1603
      if (result != nullptr && ui->grepResultsList->hasFocus()) {
1 ✔
1604
        on_grepResultsList_itemClicked(result, 0);
1 ✔
1605
      }
1606
      break;
1607
    }
1608
    if (proxyModel.rowCount() > 0) {
×
1609
      on_treeView_clicked(ui->treeView->currentIndex());
×
1610
    }
1611
    break;
1612
  case Qt::Key_Escape:
×
1613
    ui->lineEdit->clear();
×
1614
    break;
×
1615
  default:
1616
    break;
1617
  }
1618
}
1 ✔
1619

1620
/**
1621
 * @brief MainWindow::showContextMenu show us the (file or folder) context
1622
 * menu
1623
 * @param pos
1624
 */
1625
void MainWindow::showContextMenu(const QPoint &pos) {
×
1626
  const AppSettings s = QtPassSettings::load();
×
1627
  QModelIndex index = ui->treeView->indexAt(pos);
×
1628
  bool selected = true;
1629
  if (!index.isValid()) {
1630
    ui->treeView->clearSelection();
×
1631
    ui->actionDelete->setEnabled(false);
×
1632
    ui->actionEdit->setEnabled(false);
×
1633
    m_currentDir = "";
×
1634
    selected = false;
1635
  }
1636

1637
  ui->treeView->setCurrentIndex(index);
×
1638

1639
  QPoint globalPos = ui->treeView->viewport()->mapToGlobal(pos);
×
1640

1641
  QFileInfo fileOrFolder =
1642
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
1643

1644
  QMenu contextMenu;
×
1645
  if (!selected || fileOrFolder.isDir()) {
×
1646
    QAction *openFolder =
1647
        contextMenu.addAction(tr("Open folder with file manager"));
×
1648
    QAction *addFolder = contextMenu.addAction(tr("Add folder"));
×
1649
    QAction *addPassword = contextMenu.addAction(tr("Add password"));
×
1650
    QAction *users = contextMenu.addAction(tr("Users"));
×
1651
    connect(openFolder, &QAction::triggered, this, &MainWindow::openFolder);
×
1652
    connect(addFolder, &QAction::triggered, this, &MainWindow::addFolder);
×
1653
    connect(addPassword, &QAction::triggered, this, &MainWindow::addPassword);
×
1654
    connect(users, &QAction::triggered, this, &MainWindow::onUsers);
×
1655
  } else if (fileOrFolder.isFile()) {
×
1656
    QAction *edit = contextMenu.addAction(tr("Edit"));
×
1657
    connect(edit, &QAction::triggered, this, &MainWindow::onEdit);
×
1658
  }
1659
  if (selected) {
×
1660
    contextMenu.addSeparator();
×
1661
    if (fileOrFolder.isDir()) {
×
1662
      QAction *renameFolder = contextMenu.addAction(tr("Rename folder"));
×
1663
      connect(renameFolder, &QAction::triggered, this,
×
1664
              &MainWindow::renameFolder);
×
1665
    } else if (fileOrFolder.isFile()) {
×
1666
      QAction *renamePassword = contextMenu.addAction(tr("Rename password"));
×
1667
      connect(renamePassword, &QAction::triggered, this,
×
1668
              &MainWindow::renamePassword);
×
1669
    }
1670
    QAction *deleteItem = contextMenu.addAction(tr("Delete"));
×
1671
    connect(deleteItem, &QAction::triggered, this, &MainWindow::onDelete);
×
1672
    if (fileOrFolder.isDir()) {
×
1673
      QString dirPath = QDir::cleanPath(Util::getDir(
×
1674
          ui->treeView->currentIndex(), false, model, proxyModel, s.passStore));
×
1675

1676
      auto *shareMenu = new QMenu(tr("Share"), &contextMenu);
×
1677
      contextMenu.addMenu(shareMenu);
×
1678

1679
      QString gpgIdPath = Pass::getGpgIdPath(dirPath, s.passStore);
×
1680
      bool gpgIdExists = !gpgIdPath.isEmpty() && QFile(gpgIdPath).exists();
×
1681

1682
      const QString exePath = s.usePass ? s.passExecutable : s.gpgExecutable;
×
1683
      bool gpgAvailable = !exePath.isEmpty() && (exePath.startsWith("wsl ") ||
×
1684
                                                 QFile(exePath).exists());
×
1685

1686
      QAction *reencrypt = shareMenu->addAction(tr("Re-encrypt all passwords"));
×
1687
      reencrypt->setEnabled(gpgIdExists && gpgAvailable);
×
1688
      connect(reencrypt, &QAction::triggered, this,
×
1689
              [this, dirPath]() { reencryptPath(dirPath); });
×
1690

1691
      QAction *exportKey = shareMenu->addAction(tr("Export my public key..."));
×
1692
      exportKey->setEnabled(gpgAvailable);
×
1693
      connect(exportKey, &QAction::triggered, this,
×
1694
              &MainWindow::exportPublicKey);
×
1695

1696
      QAction *addRecipientAction =
1697
          shareMenu->addAction(tr("Add recipient..."));
×
1698
      addRecipientAction->setEnabled(gpgIdExists && gpgAvailable);
×
1699
      connect(addRecipientAction, &QAction::triggered, this,
×
1700
              [this, dirPath]() { addRecipient(dirPath); });
×
1701

1702
      QAction *shareHelp = shareMenu->addAction(tr("What is this?"));
×
1703
      connect(shareHelp, &QAction::triggered, this, &MainWindow::showShareHelp);
×
1704
    }
1705
  }
1706
  contextMenu.exec(globalPos);
×
1707
}
×
1708

1709
/**
1710
 * @brief MainWindow::showBrowserContextMenu show us the context menu in
1711
 * password window
1712
 * @param pos
1713
 */
1714
void MainWindow::showBrowserContextMenu(const QPoint &pos) {
×
1715
  QMenu *contextMenu = ui->textBrowser->createStandardContextMenu(pos);
×
1716
  // createStandardContextMenu() parents the menu to textBrowser. A stylesheet
1717
  // on the browser (it used to carry "background: palette(base)") cascades to
1718
  // the child QMenu and breaks its opaque native background. Reparent to the
1719
  // main window so the menu paints solid regardless of browser styling.
1720
  contextMenu->setParent(this, contextMenu->windowFlags());
×
1721
  QPoint globalPos = ui->textBrowser->viewport()->mapToGlobal(pos);
×
1722

1723
  contextMenu->exec(globalPos);
×
1724
  delete contextMenu;
×
1725
}
×
1726

1727
/**
1728
 * @brief MainWindow::openFolder open the folder in the default file manager
1729
 */
1730
void MainWindow::openFolder() {
×
1731
  QString dir = Util::getDir(ui->treeView->currentIndex(), false, model,
×
1732
                             proxyModel, QtPassSettings::getPassStore());
×
1733

1734
  QString path = QDir::toNativeSeparators(dir);
×
1735
  QDesktopServices::openUrl(QUrl::fromLocalFile(path));
×
1736
}
×
1737

1738
/**
1739
 * @brief MainWindow::addFolder add a new folder to store passwords in
1740
 */
1741
void MainWindow::addFolder() {
×
1742
  const AppSettings s = QtPassSettings::load();
×
1743
  bool ok;
1744
  QString dir = Util::getDir(ui->treeView->currentIndex(), false, model,
×
1745
                             proxyModel, s.passStore);
×
1746
  QString newdir = QInputDialog::getText(
1747
      this, tr("New file"),
×
1748
      tr("New Folder: \n(Will be placed in %1 )")
×
1749
          .arg(s.passStore + Util::getDir(ui->treeView->currentIndex(), true,
×
1750
                                          model, proxyModel, s.passStore)),
×
1751
      QLineEdit::Normal, "", &ok);
×
1752
  if (!ok || newdir.isEmpty()) {
×
1753
    return;
1754
  }
1755
  newdir.prepend(dir);
1756
  if (!confirmPathInStore(newdir)) {
×
1757
    return;
1758
  }
1759
  if (!QDir().mkdir(newdir)) {
×
1760
    QMessageBox::warning(this, tr("Error"),
×
1761
                         tr("Failed to create folder: %1").arg(newdir));
×
1762
    return;
×
1763
  }
1764
  // A .gpg-id only counts when it is signed once a signing key is configured:
1765
  // ImitatePass::verifyGpgIdFile and pass (PASSWORD_STORE_SIGNING_KEY) both
1766
  // refuse to encrypt into a folder whose .gpg-id has no matching
1767
  // .gpg-id.sig. Signing here would need the signing secret key and a
1768
  // passphrase prompt just to create a folder, so in that case leave the
1769
  // folder without its own .gpg-id: it inherits the parent's signed list,
1770
  // which encrypts to the same recipients. UsersDialog (Init) is the place to
1771
  // give it a distinct, signed list.
1772
  const bool signingConfigured = !s.passSigningKey.trimmed().isEmpty();
×
1773
  if (s.addGPGId && !signingConfigured) {
×
1774
    // Seed the new folder's .gpg-id from the recipients that are currently
1775
    // in effect for its parent. The previous implementation walked
1776
    // listKeys("", true) and wrote every key whose `enabled` flag was set,
1777
    // but that flag is only toggled inside UsersDialog, so the loop wrote
1778
    // nothing and left a zero-byte .gpg-id that shadowed the parent's
1779
    // recipients (see #1682).
1780
    if (!Pass::seedGpgIdFile(newdir, s.passStore)) {
×
1781
      QMessageBox::warning(
×
1782
          this, tr("Error"),
×
1783
          tr("Failed to create .gpg-id file in: %1").arg(newdir));
×
1784
      return;
×
1785
    }
1786
  }
1787
}
×
1788

1789
/**
1790
 * @brief MainWindow::renameFolder rename an existing folder
1791
 */
1792
void MainWindow::renameFolder() {
×
1793
  bool ok;
1794
  QString srcDir =
1795
      QDir::cleanPath(Util::getDir(ui->treeView->currentIndex(), false, model,
×
1796
                                   proxyModel, QtPassSettings::getPassStore()));
×
1797
  QString srcDirName = QDir(srcDir).dirName();
×
1798
  QString newName =
1799
      QInputDialog::getText(this, tr("Rename file"), tr("Rename Folder To: "),
×
1800
                            QLineEdit::Normal, srcDirName, &ok);
×
1801
  if (!ok || newName.isEmpty()) {
×
1802
    return;
1803
  }
1804
  QString destDir = srcDir;
1805
  destDir.replace(srcDir.lastIndexOf(srcDirName), srcDirName.length(), newName);
×
1806
  if (!confirmPathInStore(destDir)) {
×
1807
    return;
1808
  }
1809
  QtPassSettings::getPass()->Move(srcDir, destDir, false);
×
1810
}
1811

1812
/**
1813
 * @brief MainWindow::editPassword read password and open edit window via
1814
 * MainWindow::onEdit()
1815
 */
1816
void MainWindow::editPassword(const QString &file) {
1 ✔
1817
  if (!file.isEmpty()) {
1 ✔
1818
    const AppSettings s = QtPassSettings::load();
1 ✔
1819
    if (s.useGit && s.autoPull) {
1 ✔
1820
      onUpdate(true);
×
1821
    }
1822
    setPassword(file, false);
1 ✔
1823
  }
1 ✔
1824
}
1 ✔
1825

1826
/**
1827
 * @brief MainWindow::renamePassword rename an existing password
1828
 */
1829
void MainWindow::renamePassword() {
×
1830
  bool ok;
1831
  QString file = getFile(ui->treeView->currentIndex(), false);
×
1832
  QString filePath = QFileInfo(file).path();
×
1833
  QString fileName = QFileInfo(file).fileName();
×
1834
  if (fileName.endsWith(".gpg", Qt::CaseInsensitive)) {
×
1835
    fileName.chop(4);
×
1836
  }
1837

1838
  QString newName =
1839
      QInputDialog::getText(this, tr("Rename file"), tr("Rename File To: "),
×
1840
                            QLineEdit::Normal, fileName, &ok);
×
1841
  if (!ok || newName.isEmpty()) {
×
1842
    return;
1843
  }
1844
  QString newFile = QDir(filePath).filePath(newName);
×
1845
  if (!confirmPathInStore(newFile)) {
×
1846
    return;
1847
  }
1848
  QtPassSettings::getPass()->Move(file, newFile, false);
×
1849
}
1850

1851
/**
1852
 * @brief Copies the password of the selected file from the tree view to the
1853
 * clipboard.
1854
 * @example
1855
 * MainWindow::copyPasswordFromTreeview();
1856
 *
1857
 * @return void - This function does not return a value.
1858
 */
1859
void MainWindow::copyPasswordFromTreeview() {
×
1860
  QFileInfo fileOrFolder =
1861
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
1862

1863
  if (fileOrFolder.isFile()) {
×
1864
    // finishedShow carries no request identity, so allow only one copy request
1865
    // in flight: otherwise a second Ctrl+C on a different entry would re-arm
1866
    // the single-shot slot and the first decrypt to finish would copy the wrong
1867
    // entry while the later request is silently dropped. See
1868
    // m_passwordCopyPending.
1869
    if (m_passwordCopyPending) {
×
1870
      return;
×
1871
    }
1872
    m_passwordCopyPending = true;
×
1873
    QString file = getFile(ui->treeView->currentIndex(), true);
×
1874
    connectSingleShot(QtPassSettings::getPass(), &Pass::finishedShow, this,
×
1875
                      &MainWindow::passwordFromFileToClipboard);
1876
    // This Show repaints the panel as well; see onOtp().
1877
    m_shownFile = file;
×
1878
    QtPassSettings::getPass()->Show(file);
×
1879
  }
1880
}
×
1881

1882
void MainWindow::passwordFromFileToClipboard(const QString &text) {
2 ✔
1883
  disconnectSingleShot(QtPassSettings::getPass(), &Pass::finishedShow, this,
2 ✔
1884
                       &MainWindow::passwordFromFileToClipboard);
1885
  m_passwordCopyPending = false;
2 ✔
1886
  const QStringList tokens = text.split('\n');
2 ✔
1887
  if (tokens.isEmpty()) {
2 ✔
1888
    return;
1889
  }
1890
  // An entry created by `pass otp insert` has the otpauth:// URI as its first
1891
  // line. That URI carries the shared TOTP secret (the seed, not a code), so
1892
  // copying it to the clipboard would leak 2FA material. Skip it, matching the
1893
  // display path (FileContent::getPasswordForDisplay / PasswordDisplayPanel).
1894
  if (FileContent::isOtpUriValue(tokens[0])) {
2 ✔
1895
    flashText(tr("This entry holds an OTP secret, not a password"), true);
1 ✔
1896
    return;
1 ✔
1897
  }
1898
  m_qtPass->copyTextToClipboard(tokens[0]);
1 ✔
1899
}
1900

1901
/**
1902
 * @brief Displays message in status bar
1903
 *
1904
 * @param msg     text to be displayed
1905
 * @param timeout time for which msg shall be visible
1906
 */
1907
void MainWindow::showStatusMessage(const QString &msg, int timeout) {
9 ✔
1908
  ui->statusBar->showMessage(msg, timeout);
9 ✔
1909
}
9 ✔
1910

1911
/**
1912
 * @brief MainWindow::reencryptPath re-encrypt all passwords in a directory
1913
 * @param dir Directory path to re-encrypt
1914
 */
1915
void MainWindow::reencryptPath(const QString &dir) {
×
1916
  QDir checkDir(dir);
×
1917
  if (!checkDir.exists()) {
×
1918
    QMessageBox::critical(this, tr("Error"),
×
1919
                          tr("Directory does not exist: %1").arg(dir));
×
1920
    return;
×
1921
  }
1922

1923
  int ret = QMessageBox::question(
×
1924
      this, tr("Re-encrypt passwords"),
×
1925
      tr("Re-encrypt all passwords in %1?\n\n"
×
1926
         "This will re-encrypt ALL password files in this folder "
1927
         "using the current recipients defined in .gpg-id.\n\n"
1928
         "This may rewrite many files and cannot be undone easily.\n\n"
1929
         "Continue?")
1930
          .arg(QDir(dir).dirName()),
×
1931
      QMessageBox::Yes | QMessageBox::No);
1932

1933
  if (ret != QMessageBox::Yes)
×
1934
    return;
1935

1936
  // Disable preemptively. ImitatePass::reencryptPath emits
1937
  // startReencryptPath asynchronously and the slot would re-run this,
1938
  // but setEnabled(false) is idempotent so the duplicate is harmless.
1939
  startReencryptPath();
×
1940

1941
  QtPassSettings::getImitatePass()->reencryptPath(
×
1942
      QDir::cleanPath(QDir(dir).absolutePath()));
×
1943
}
×
1944

1945
/**
1946
 * @brief MainWindow::startReencryptPath disable ui elements and treeview
1947
 */
1948
void MainWindow::startReencryptPath() {
×
1949
  setUiElementsEnabled(false);
×
1950
  ui->treeView->setDisabled(true);
×
1951
}
×
1952

1953
/**
1954
 * @brief MainWindow::endReencryptPath re-enable ui elements
1955
 */
1956
void MainWindow::endReencryptPath() { setUiElementsEnabled(true); }
×
1957

1958
/**
1959
 * @brief MainWindow::exportPublicKey export the configured signing key in
1960
 *        ASCII-armored form via gpg and show it in ExportPublicKeyDialog.
1961
 *
1962
 * Falls back to a help dialog when no signing key is configured or gpg is
1963
 * unavailable, so the user still gets actionable guidance.
1964
 */
1965
void MainWindow::exportPublicKey() {
×
1966
  const AppSettings s = QtPassSettings::load();
×
1967
  const QString identity = s.passSigningKey;
1968
  if (identity.isEmpty()) {
×
1969
    QMessageBox::information(
×
1970
        this, tr("Export Public Key"),
×
1971
        tr("<h3>Export Your Public Key</h3>"
×
1972
           "<p>No signing key is configured. Set one in QtPass Settings "
1973
           "&gt; GPG keys, or run this in a terminal:</p>"
1974
           "<pre>gpg --armor --export --output my_key.asc &lt;your-key-id"
1975
           "&gt;</pre>"
1976
           "<p>Then send the file to your teammates.</p>"));
1977
    return;
×
1978
  }
1979
  QString gpgExe = s.gpgExecutable;
1980
  if (gpgExe.isEmpty()) {
×
1981
    gpgExe = QStringLiteral("gpg");
×
1982
  }
1983
  QStringList args = {"--armor", "--export"};
×
1984
  args.append(identity.split(' ', Qt::SkipEmptyParts));
×
1985
  QString stdOut;
×
1986
  QString stdErr;
×
1987
  int exitCode = Executor::executeBlocking(gpgExe, args, &stdOut, &stdErr);
×
1988
  if (exitCode != 0 || stdOut.isEmpty()) {
×
1989
    QMessageBox::warning(this, tr("Export Public Key"),
×
1990
                         tr("Could not export public key for %1.\n\n%2")
×
1991
                             .arg(identity, stdErr.isEmpty()
×
1992
                                                ? tr("No output from gpg.")
×
1993
                                                : stdErr));
1994
    return;
1995
  }
1996
  ExportPublicKeyDialog dialog(identity, stdOut, this);
×
1997
  dialog.exec();
×
1998
}
×
1999

2000
/**
2001
 * @brief MainWindow::addRecipient open the recipient management dialog for
2002
 *        the supplied directory.
2003
 * @param dir Folder whose .gpg-id should be edited.
2004
 *
2005
 * Delegates to UsersDialog so users can tick/untick keys from their
2006
 * keyring as recipients of the folder; importing a foreign key into the
2007
 * keyring still has to happen via gpg (or QtPass settings) first.
2008
 */
2009
void MainWindow::addRecipient(const QString &dir) {
×
2010
  UsersDialog d(QtPassSettings::getPass(), QtPassSettings::load(), dir, this);
×
2011
  d.exec();
×
2012
}
×
2013

2014
/**
2015
 * @brief MainWindow::showShareHelp show help about GPG sharing
2016
 */
2017
void MainWindow::showShareHelp() {
×
2018
  QMessageBox::information(
×
2019
      this, tr("Sharing Passwords with GPG"),
×
2020
      tr("<h3>Sharing Passwords with GPG</h3>"
×
2021
         "<p>To share passwords with other users:</p>"
2022
         "<ol>"
2023
         "<li><b>Export your public key</b> and send it to teammates</li>"
2024
         "<li><b>Import teammates' public keys</b> into your GPG keyring</li>"
2025
         "<li><b>Re-encrypt passwords</b> so all recipients can decrypt "
2026
         "them</li>"
2027
         "</ol>"
2028
         "<p>Only people who have a matching secret key can decrypt the "
2029
         "passwords.</p>"
2030
         "<p><b>Tip:</b> Use the same GPG key for all shared folders.</p>"
2031
         "<p>See the FAQ for more details.</p>"));
2032
}
×
2033

2034
void MainWindow::updateGitButtonVisibility() {
61 ✔
2035
  const AppSettings s = QtPassSettings::load();
61 ✔
2036
  if (!s.useGit || (s.gitExecutable.isEmpty() && s.passExecutable.isEmpty())) {
61 ✔
2037
    enableGitButtons(false);
61 ✔
2038
  } else {
2039
    enableGitButtons(true);
×
2040
  }
2041
}
61 ✔
2042

2043
void MainWindow::updateOtpButtonVisibility(bool uiEnabled) {
61 ✔
2044
  // No platform gating any more: codes are generated in-process, so this works
2045
  // on Windows and macOS and with either backend. It used to be hidden there
2046
  // because the pass-otp extension is Unix-only.
2047
  //
2048
  // Kept visible but disabled when OTP is off, as it was before: hiding it
2049
  // removed the only discoverable trace of the feature, and since an OTP field
2050
  // is suppressed from the panel unconditionally (its value is a secret), a
2051
  // user with the setting off would see nothing at all where their OTP data
2052
  // used to be.
2053
  //
2054
  // Enablement must honour uiEnabled: this is called from
2055
  // setUiElementsEnabled(), and ignoring the argument re-enabled the action
2056
  // while a decrypt was in flight, letting the user stack Show calls.
2057
  ui->actionOtp->setVisible(true);
61 ✔
2058
  ui->actionOtp->setEnabled(QtPassSettings::isUseOtp() && uiEnabled);
61 ✔
2059
}
61 ✔
2060

2061
void MainWindow::updateGrepButtonVisibility() {
35 ✔
2062
  const bool enabled = QtPassSettings::isUseGrepSearch();
35 ✔
2063
  ui->grepButton->setVisible(enabled);
35 ✔
2064
  ui->grepCaseButton->setVisible(enabled);
35 ✔
2065
  if (!enabled && m_grep.inGrepMode()) {
35 ✔
2066
    ui->grepButton->setChecked(false);
×
2067
  }
2068
}
35 ✔
2069

2070
void MainWindow::enableGitButtons(const bool &state) {
61 ✔
2071
  // Following GNOME guidelines is preferable disable buttons instead of hide
2072
  ui->actionPush->setEnabled(state);
61 ✔
2073
  ui->actionUpdate->setEnabled(state);
61 ✔
2074
}
61 ✔
2075

2076
/**
2077
 * @brief MainWindow::critical critical message popup wrapper.
2078
 * @param title
2079
 * @param msg
2080
 */
2081
void MainWindow::critical(const QString &title, const QString &msg) {
×
2082
  QMessageBox::critical(this, title, msg);
×
2083
}
×
2084

2085
/**
2086
 * @brief Appends processed command output to the output panel.
2087
 *
2088
 * Appends text to the process output text edit, with per-line numbering,
2089
 * optional command prefix, and color coding for errors vs. success.
2090
 * Handles auto-scrolling and line limits.
2091
 *
2092
 * @param output The raw output text from the command.
2093
 * @param isError true if this is error output (stderr).
2094
 * @param linePrefix Optional command name to prefix each line with.
2095
 */
2096
void MainWindow::appendProcessOutput(const QString &output, bool isError,
2 ✔
2097
                                     const QString &linePrefix) {
2098
  if (!QtPassSettings::isShowProcessOutput()) {
2 ✔
2099
    return;
1 ✔
2100
  }
2101

2102
  QStringList lines = output.split('\n', Qt::SkipEmptyParts);
1 ✔
2103
  for (QString &line : lines) {
2 ✔
2104
    // Right-trim only: remove trailing CR and whitespace, preserve leading
2105
    // indentation
2106
    line.remove('\r');
1 ✔
2107
    while (!line.isEmpty() && line.back().isSpace()) {
2 ✔
2108
      line.chop(1);
×
2109
    }
2110
    if (line.isEmpty()) {
1 ✔
2111
      continue;
×
2112
    }
2113

2114
    m_outputCounter++;
1 ✔
2115
    QString lineNumber = QString::number(m_outputCounter);
1 ✔
2116

2117
    QColor textColor =
2118
        isError ? QColor(Qt::red)
1 ✔
2119
                : m_processOutputEdit->palette().color(QPalette::Text);
2 ✔
2120
    QString colorHex = textColor.name();
1 ✔
2121
    // Apply the optional prefix per line so multi-line output stays
2122
    // attributed to its command (e.g. all 3 lines of a `git push` show
2123
    // "git push: ..." rather than only the first).
2124
    QString prefixed =
2125
        linePrefix.isEmpty() ? line : linePrefix + QStringLiteral(": ") + line;
2 ✔
2126
    QString coloredOutput =
2127
        QString("<span style=\"color: %1;\">%2: %3</span>")
1 ✔
2128
            .arg(colorHex, lineNumber, prefixed.toHtmlEscaped());
2 ✔
2129

2130
    m_processOutputEdit->append(coloredOutput);
1 ✔
2131
  }
2132

2133
  limitOutputLines();
1 ✔
2134

2135
  if (m_autoScroll) {
1 ✔
2136
    m_processOutputEdit->verticalScrollBar()->setValue(
2 ✔
2137
        m_processOutputEdit->verticalScrollBar()->maximum());
1 ✔
2138
  }
2139
}
2140

2141
/**
2142
 * @brief Handles process output from the Pass executor.
2143
 *
2144
 * Called when any non-sensitive process completes. Filters out password-
2145
 * related commands (pass show, insert, etc.) and delegates to
2146
 * appendProcessOutput.
2147
 *
2148
 * @param output The stdout/stderr text from the process.
2149
 * @param isError true if this is error output (stderr).
2150
 * @param pid The process ID identifying which command ran.
2151
 */
2152
void MainWindow::onProcessOutput(const QString &output, bool isError,
2 ✔
2153
                                 Enums::PROCESS pid) {
2154
  appendProcessOutput(output, isError, getProcessName(pid));
2 ✔
2155
}
2 ✔
2156

2157
/**
2158
 * @brief Maps a process ID to its human-readable command name.
2159
 *
2160
 * Returns static strings for git/pass commands that appear in output.
2161
 * Password-related commands return empty (they are filtered).
2162
 *
2163
 * @param pid The process ID to look up.
2164
 * @return QString with command name, or empty if filtered.
2165
 */
2166
auto MainWindow::getProcessName(Enums::PROCESS pid) -> QString {
2 ✔
2167
  switch (pid) {
2 ✔
2168
  case Enums::GIT_INIT:
×
2169
    return QStringLiteral("git init"); // no-tr
×
2170
  case Enums::GIT_ADD:
×
2171
    return QStringLiteral("git add"); // no-tr
×
2172
  case Enums::GIT_COMMIT:
×
2173
    return QStringLiteral("git commit"); // no-tr
×
2174
  case Enums::GIT_RM:
×
2175
    return QStringLiteral("git rm"); // no-tr
×
2176
  case Enums::GIT_PULL:
×
2177
    return QStringLiteral("git pull"); // no-tr
×
2178
  case Enums::GIT_PUSH:
×
2179
    return QStringLiteral("git push"); // no-tr
×
2180
  case Enums::GIT_MOVE:
×
2181
    return QStringLiteral("git mv"); // no-tr
×
2182
  case Enums::GIT_COPY:
×
2183
    // ImitatePass::Copy literally invokes `git cp` (a git-extras
2184
    // subcommand), so the label matches what's run. Stock-git users
2185
    // without git-extras will see the underlying "'cp' is not a git
2186
    // command" failure surfaced in the process output panel.
2187
    return QStringLiteral("git cp"); // no-tr
×
2188
  case Enums::PASS_INSERT:
×
2189
    return QStringLiteral("pass insert"); // no-tr
×
2190
  case Enums::PASS_REMOVE:
×
2191
    return QStringLiteral("pass rm"); // no-tr
×
2192
  case Enums::PASS_INIT:
×
2193
    return QStringLiteral("pass init"); // no-tr
×
2194
  case Enums::PASS_MOVE:
×
2195
    return QStringLiteral("pass mv"); // no-tr
×
2196
  case Enums::PASS_COPY:
×
2197
    return QStringLiteral("pass cp"); // no-tr
×
2198
  case Enums::PASS_GREP:
×
2199
    return QStringLiteral("pass grep"); // no-tr
×
2200
  case Enums::GPG_GENKEYS:
×
2201
    return QStringLiteral("gpg --gen-key"); // no-tr
×
2202
  case Enums::PASS_SHOW:
2203
  case Enums::PASS_OTP_GENERATE:
2204
  case Enums::PROCESS_COUNT:
2205
  case Enums::INVALID:
2206
    break;
2207
  }
2208
  return {};
2 ✔
2209
}
2210

2211
/**
2212
 * @brief Checks if a process ID represents a sensitive operation whose
2213
 * output should not be shown in the process output panel.
2214
 *
2215
 * Password-related commands (pass show, OTP generate, grep, insert)
2216
 * display their output in other UI areas, so we skip them here.
2217
 *
2218
 * @param pid The process ID to check.
2219
 * @return true if the process is sensitive and should be filtered.
2220
 */
2221
auto MainWindow::isSensitiveProcess(Enums::PROCESS pid) -> bool {
×
2222
  switch (pid) {
×
2223
  case Enums::PASS_SHOW:
2224
  case Enums::PASS_OTP_GENERATE:
2225
  case Enums::PASS_GREP:
2226
  case Enums::PASS_INSERT:
2227
    return true;
2228
  case Enums::GIT_INIT:
2229
  case Enums::GIT_ADD:
2230
  case Enums::GIT_COMMIT:
2231
  case Enums::GIT_RM:
2232
  case Enums::GIT_PULL:
2233
  case Enums::GIT_PUSH:
2234
  case Enums::GIT_MOVE:
2235
  case Enums::GIT_COPY:
2236
  case Enums::PASS_REMOVE:
2237
  case Enums::PASS_INIT:
2238
  case Enums::PASS_MOVE:
2239
  case Enums::PASS_COPY:
2240
  case Enums::GPG_GENKEYS:
2241
  case Enums::PROCESS_COUNT:
2242
  case Enums::INVALID:
2243
    break;
2244
  }
2245
  return false;
×
2246
}
2247

2248
/**
2249
 * @brief Updates the visibility of the process output panel.
2250
 *
2251
 * Shows or hides the process output widget based on the user's
2252
 * showProcessOutput setting.
2253
 */
2254
void MainWindow::updateProcessOutputVisibility() {
3 ✔
2255
  m_processOutputDock->setVisible(QtPassSettings::isShowProcessOutput());
3 ✔
2256
}
3 ✔
2257

2258
/**
2259
 * @brief Limits the output panel to max lines, trimming old excess.
2260
 *
2261
 * Removes the oldest lines when the document exceeds MaxOutputLines (1000).
2262
 * Called after each append to prevent unbounded growth.
2263
 */
2264
void MainWindow::limitOutputLines() {
1 ✔
2265
  QTextDocument *doc = m_processOutputEdit->document();
1 ✔
2266
  int excess = doc->blockCount() - MaxOutputLines;
1 ✔
2267
  if (excess <= 0) {
1 ✔
2268
    return;
1 ✔
2269
  }
2270

2271
  QTextCursor cursor(doc);
×
2272
  cursor.movePosition(QTextCursor::Start);
×
2273
  cursor.movePosition(QTextCursor::NextBlock, QTextCursor::KeepAnchor, excess);
×
2274
  cursor.removeSelectedText();
×
2275
}
×
2276

2277
/**
2278
 * @brief Clears the process output panel.
2279
 *
2280
 * Clears all output, resets the line counter, and re-enables auto-scroll.
2281
 */
2282
void MainWindow::on_clearOutputButton_clicked() {
×
2283
  m_processOutputEdit->clear();
×
2284
  m_outputCounter = 0;
×
2285
  m_autoScroll = true;
×
2286
}
×
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