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

IJHack / QtPass / 34832508871

14 Sep 2026 10:18AM UTC coverage: 67.618% (+2.4%) from 65.229%
34832508871

push

github

web-flow
Backport: quit on cancelled first-run wizard, re-ask when invalid (#1709) (#1717)

* fix: quit when the first-run wizard is cancelled (#1682) (#1689)

(cherry picked from commit d49c319ee)

* Follow-up to #1689: re-ask for a first-run config that is still invalid (#1696)

cancelled first-run wizard reaches QtPass::init() and main() exits. That
left the accepted path uncovered: the ConfigDialog's OK button is not
gated on Util::configIsValid(), so a user who declines "Create
password-store?" and presses OK gets an accepted dialog with a store
that has no .gpg-id. config() then cleared the fresh-start flag, init()'s
`freshStart && !configIsValid` guard never fired, init() returned true
and the main window opened on a non-existent store.

Restore the "ask again until valid or cancelled" contract without the
recursion: config() now returns whether the dialog was accepted and only
clears the fresh-start flag once the accepted configuration is valid, so
the wizard runs again on the retry. QtPass::init() loops on
Util::configIsValid() and gives up (returns false) only when config()
reports a cancel, which main() already turns into an exit.

Two MainWindow tests drive the whole first-run flow headlessly with a
modal-dialog poker: accept-then-cancel must leave initSucceeded() false
after two dialogs, and accept-then-fix-then-accept must succeed.

Claude-Session: https://claude.ai/code/session_01JuQsrHonihp1nARE7bzstc

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>

Backport to main (1.8.x): the only conflict was the test's #include block;
the QProgressDialog include belongs to the 2.0-only re-encryption worker
and was dropped, QPushButton was kept. Source hunks applied unchanged.
(cherry picked from commit 70ce5d680)

* Flatpak: overlay the first-run fix sources onto v1.8.0 (#1709)

The Flatpak manifest builds the qtpass module from the v1.8.0 tag and
overlays main/main.cpp from the repositor... (continued)

26 of 28 new or added lines in 2 files covered. (92.86%)

4905 of 7254 relevant lines covered (67.62%)

62.82 hits per line

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

39.79
/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)
25 ✔
60
    : QMainWindow(parent), ui(new Ui::MainWindow) {
25 ✔
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);
25 ✔
67

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

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

76
  model.setNameFilters(QStringList() << "*.gpg");
75 ✔
77
  model.setNameFilterDisables(false);
25 ✔
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());
25 ✔
87

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

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

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

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

128
  updateProfileBox();
25 ✔
129

130
  m_displayPanel = new PasswordDisplayPanel(
25 ✔
131
      ui->gridLayout, ui->verticalLayoutPassword, this, this);
25 ✔
132
  connect(m_displayPanel, &PasswordDisplayPanel::copyRequested, m_qtPass,
25 ✔
133
          &QtPass::copyTextToClipboard);
25 ✔
134
  connect(m_displayPanel, &PasswordDisplayPanel::qrRequested, m_qtPass,
25 ✔
135
          &QtPass::showTextAsQRCode);
25 ✔
136

137
  QtPassSettings::getPass()->updateEnv();
25 ✔
138
  clearPanelTimer.setSingleShot(true);
25 ✔
139
  connect(&clearPanelTimer, &QTimer::timeout, this, [this]() { clearPanel(); });
25 ✔
140

141
  searchTimer.setInterval(350);
25 ✔
142
  searchTimer.setSingleShot(true);
25 ✔
143

144
  connect(&searchTimer, &QTimer::timeout, this, &MainWindow::onTimeoutSearch);
25 ✔
145

146
  // Install the search-box key filter once, not on every setUiElementsEnabled
147
  // call.
148
  ui->lineEdit->installEventFilter(this);
25 ✔
149
  ui->toolBar->installEventFilter(this);
25 ✔
150

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

163
  initToolBarButtons();
25 ✔
164
  initStatusBar();
25 ✔
165
  initProcessOutputPanel();
25 ✔
166

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

188
  ui->lineEdit->setClearButtonEnabled(true);
25 ✔
189
  updateGrepButtonVisibility();
25 ✔
190

191
  setUiElementsEnabled(true);
25 ✔
192

193
  ui->lineEdit->setText(searchText);
25 ✔
194

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

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

214
MainWindow::~MainWindow() { delete m_qtPass; }
96 ✔
215

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

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

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

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

317
  ui->actionAddPassword->setIcon(
25 ✔
318
      QIcon::fromTheme("document-new", QIcon(":/icons/document-new.svg")));
100 ✔
319
  ui->actionAddFolder->setIcon(
25 ✔
320
      QIcon::fromTheme("folder-new", QIcon(":/icons/folder-new.svg")));
100 ✔
321
  ui->actionEdit->setIcon(QIcon::fromTheme(
25 ✔
322
      "document-properties", QIcon(":/icons/document-properties.svg")));
75 ✔
323
  ui->actionDelete->setIcon(
25 ✔
324
      QIcon::fromTheme("edit-delete", QIcon(":/icons/edit-delete.svg")));
100 ✔
325
  ui->actionPush->setIcon(
25 ✔
326
      QIcon::fromTheme("go-up", QIcon(":/icons/go-top.svg")));
100 ✔
327
  ui->actionUpdate->setIcon(
25 ✔
328
      QIcon::fromTheme("go-down", QIcon(":/icons/go-bottom.svg")));
100 ✔
329
  ui->actionUsers->setIcon(QIcon::fromTheme(
25 ✔
330
      "x-office-address-book", QIcon(":/icons/x-office-address-book.svg")));
75 ✔
331
  ui->actionConfig->setIcon(QIcon::fromTheme(
25 ✔
332
      "applications-system", QIcon(":/icons/applications-system.svg")));
50 ✔
333
}
25 ✔
334

335
/**
336
 * @brief MainWindow::initStatusBar init statusBar with default message and logo
337
 */
338
void MainWindow::initStatusBar() {
25 ✔
339
  ui->statusBar->showMessage(tr("Welcome to QtPass %1").arg(VERSION), 2000);
50 ✔
340

341
  QPixmap logo = QPixmap::fromImage(QImage(":/artwork/icon.svg"))
50 ✔
342
                     .scaledToHeight(statusBar()->height());
25 ✔
343
  auto *logoApp = new QLabel(statusBar());
25 ✔
344
  logoApp->setPixmap(logo);
25 ✔
345
  statusBar()->addPermanentWidget(logoApp);
25 ✔
346
}
25 ✔
347

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

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

393
  connect(m_clearOutputButton, &QToolButton::clicked, this,
25 ✔
394
          &MainWindow::on_clearOutputButton_clicked);
25 ✔
395

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

415
auto MainWindow::getCurrentTreeViewIndex() -> QModelIndex {
1 ✔
416
  return ui->treeView->currentIndex();
1 ✔
417
}
418

419
void MainWindow::cleanKeygenDialog() {
1 ✔
420
  if (m_keyGenDialog != nullptr) {
1 ✔
421
    m_keyGenDialog->close();
×
422
  }
423
  m_keyGenDialog = nullptr;
424
}
1 ✔
425

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

446
  if (isHtml) {
9 ✔
447
    QString _text = text;
448
    if (!ui->textBrowser->toPlainText().isEmpty()) {
12 ✔
449
      _text = ui->textBrowser->toHtml() + _text;
2 ✔
450
    }
451
    ui->textBrowser->setHtml(_text);
6 ✔
452
  } else {
453
    ui->textBrowser->setText(text);
3 ✔
454
  }
455
}
9 ✔
456

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

471
  if (s.noLineWrapping) {
3 ✔
472
    ui->textBrowser->setLineWrapMode(QTextBrowser::NoWrap);
×
473
  } else {
474
    ui->textBrowser->setLineWrapMode(QTextBrowser::WidgetWidth);
3 ✔
475
  }
476
}
3 ✔
477

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

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

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

517
  applyTextBrowserSettings();
3 ✔
518
  applyWindowFlagsSettings();
3 ✔
519

520
  updateProfileBox();
3 ✔
521
  const AppSettings s = QtPassSettings::load();
3 ✔
522
  proxyModel.setStore(s.passStore);
3 ✔
523
  ui->treeView->setRootIndex(proxyModel.rootIndexFor(s.passStore));
3 ✔
524
  deselect();
3 ✔
525
  ui->treeView->setCurrentIndex(QModelIndex());
3 ✔
526

527
  Pass *activePass = QtPassSettings::getPass();
3 ✔
528
  activePass->updateEnv();
3 ✔
529
  proxyModel.setPass(activePass);
3 ✔
530
  clearPanelTimer.setInterval(MS_PER_SECOND * s.autoclearPanelSeconds);
3 ✔
531
  m_qtPass->setClipboardTimer();
3 ✔
532

533
  updateGitButtonVisibility();
3 ✔
534
  updateOtpButtonVisibility();
3 ✔
535
  updateGrepButtonVisibility();
3 ✔
536
  updateProcessOutputVisibility();
3 ✔
537
  if (s.useTrayIcon && m_tray == nullptr) {
3 ✔
NEW
538
    initTrayIcon();
×
539
  } else if (!s.useTrayIcon && m_tray != nullptr) {
3 ✔
NEW
540
    destroyTrayIcon();
×
541
  }
542

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

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

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

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

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

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

629
  if (fileOrFolder.isFile()) {
1 ✔
630
    editPassword(getFile(index, true));
2 ✔
631
  }
632
}
1 ✔
633

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

649
void MainWindow::executeWrapperStarted() {
5 ✔
650
  m_displayPanel->clear();
5 ✔
651
  ui->textBrowser->clear();
5 ✔
652
  setUiElementsEnabled(false);
5 ✔
653
  clearPanelTimer.stop();
5 ✔
654
  if (QtPassSettings::isShowProcessOutput()) {
5 ✔
655
    m_processOutputDock->setVisible(true);
×
656
  }
657
}
5 ✔
658

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

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

689
  // first clear the current view:
690
  m_displayPanel->clear();
3 ✔
691

692
  // show what is needed:
693
  if (s.hideContent) {
3 ✔
694
    output = "***" + tr("Content hidden") + "***";
×
695
  } else if (!s.displayAsIs) {
3 ✔
696
    m_displayPanel->displayFields(password, fileContent.getNamedValues(), s,
6 ✔
697
                                  s.useOtp ? fileContent.getOtpUri()
3 ✔
698
                                           : QString());
699
    output = fileContent.getRemainingDataForDisplay();
6 ✔
700
  }
701

702
  if (s.useAutoclearPanel) {
3 ✔
703
    clearPanelTimer.start();
×
704
  }
705

706
  emit passShowHandlerFinished(output);
3 ✔
707
  setUiElementsEnabled(true);
3 ✔
708
}
6 ✔
709

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

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

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

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

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

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

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

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

860
  if (s.alwaysOnTop) {
25 ✔
861
    Qt::WindowFlags flags = windowFlags();
862
    setWindowFlags(flags | Qt::WindowStaysOnTopHint);
×
863
    show();
×
864
  }
865

866
  if (s.useTrayIcon && m_tray == nullptr) {
25 ✔
867
    initTrayIcon();
×
868
    if (s.startMinimized) {
×
869
      // since we are still in constructor, can't directly hide
870
      QTimer::singleShot(10, this, SLOT(hide()));
×
871
    }
872
  } else if (!s.useTrayIcon && m_tray != nullptr) {
25 ✔
873
    destroyTrayIcon();
×
874
  }
875
}
50 ✔
876

877
/**
878
 * @brief MainWindow::on_configButton_clicked run Mainwindow::config
879
 */
880
void MainWindow::onConfig() { config(); }
×
881

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

899
/**
900
 * @brief MainWindow::onTimeoutSearch Fired when search is finished or too much
901
 * time from two keypresses is elapsed
902
 */
903
void MainWindow::onTimeoutSearch() {
×
904
  QString query = ui->lineEdit->text();
×
905

906
  if (query.isEmpty()) {
×
907
    ui->treeView->collapseAll();
×
908
    deselect();
×
909
  }
910

911
  query.replace(QStringLiteral(" "), ".*");
×
912
  QRegularExpression regExp(query, QRegularExpression::CaseInsensitiveOption);
×
913
  if (!regExp.isValid())
×
914
    return;
915
  proxyModel.setFilterRegularExpression(regExp);
×
916
  ui->treeView->setRootIndex(
×
917
      proxyModel.rootIndexFor(QtPassSettings::getPassStore()));
×
918

919
  if (proxyModel.rowCount() > 0 && !query.isEmpty()) {
×
920
    selectFirstFile();
×
921
  } else {
922
    ui->actionEdit->setEnabled(false);
×
923
    ui->actionDelete->setEnabled(false);
×
924
  }
925
}
×
926

927
/**
928
 * @brief MainWindow::on_lineEdit_returnPressed get searching
929
 *
930
 * Select the first possible file in the tree
931
 */
932
void MainWindow::on_lineEdit_returnPressed() {
×
933
#ifdef QT_DEBUG
934
  dbg() << "on_lineEdit_returnPressed" << proxyModel.rowCount();
935
#endif
936

937
  if (m_grep.inGrepMode()) {
×
938
    const QString query = ui->lineEdit->text();
×
939
    if (!query.isEmpty()) {
×
940
      ui->grepResultsList->clear();
×
941
      ui->statusBar->showMessage(tr("Searching…"));
×
942
      if (m_grep.beginSearch()) {
943
        QApplication::setOverrideCursor(Qt::WaitCursor);
×
944
      }
945
      QtPassSettings::getPass()->Grep(query, ui->grepCaseButton->isChecked());
×
946
    } else {
947
      if (m_grep.cancelSearch()) {
948
        QApplication::restoreOverrideCursor();
×
949
      }
950
      ui->grepResultsList->clear();
×
951
      ui->grepResultsList->setVisible(false);
×
952
      ui->treeView->setVisible(true);
×
953
    }
954
    return;
955
  }
956

957
  if (proxyModel.rowCount() > 0) {
×
958
    selectFirstFile();
×
959
    on_treeView_clicked(ui->treeView->currentIndex());
×
960
  }
961
}
962

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

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

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

1080
/**
1081
 * @brief MainWindow::selectFirstFile select the first possible file in the
1082
 * tree
1083
 */
1084
void MainWindow::selectFirstFile() {
×
1085
  QModelIndex index = proxyModel.rootIndexFor(QtPassSettings::getPassStore());
×
1086
  index = firstFile(index);
×
1087
  ui->treeView->setCurrentIndex(index);
×
1088
}
×
1089

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

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

1133
/**
1134
 * @brief MainWindow::setPassword open passworddialog
1135
 * @param file which pgp file
1136
 * @param isNew insert (not update)
1137
 */
1138
void MainWindow::setPassword(const QString &file, bool isNew) {
1 ✔
1139
  const AppSettings s = QtPassSettings::load();
1 ✔
1140
  PasswordDialog d(QtPassSettings::getPass(), s, file, isNew, this);
1 ✔
1141

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

1160
  if (!d.exec()) {
1 ✔
1161
    ui->treeView->setFocus();
×
1162
  }
1163
}
1 ✔
1164

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

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

1203
  QFileInfo fileOrFolder =
1204
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
1205
  QString file = "";
×
1206
  bool isDir = false;
1207

1208
  if (fileOrFolder.isFile()) {
×
1209
    file = getFile(ui->treeView->currentIndex(), true);
×
1210
  } else {
1211
    file = Util::getDir(ui->treeView->currentIndex(), true, model, proxyModel,
×
1212
                        QtPassSettings::getPassStore());
×
1213
    isDir = true;
1214
  }
1215

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

1234
  if (QMessageBox::question(
×
1235
          this, isDir ? tr("Delete folder?") : tr("Delete password?"),
×
1236
          tr("Are you sure you want to delete %1%2?")
×
1237
              .arg(QDir::separator() + file, isDir ? dirMessage : "?"),
×
1238
          QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) {
1239
    return;
1240
  }
1241

1242
  QtPassSettings::getPass()->Remove(file, isDir);
×
1243
}
×
1244

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

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

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

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

1324
/**
1325
 * @brief MainWindow::onEdit try and edit (selected) password.
1326
 */
1327
void MainWindow::onEdit() {
×
1328
  QString file = getFile(ui->treeView->currentIndex(), true);
×
1329
  editPassword(file);
×
1330
}
1331

1332
/**
1333
 * @brief MainWindow::userDialog see MainWindow::onUsers()
1334
 * @param dir folder to edit users for.
1335
 */
1336
void MainWindow::userDialog(const QString &dir) {
×
1337
  if (!dir.isEmpty()) {
×
1338
    m_currentDir = dir;
×
1339
  }
1340
  onUsers();
×
1341
}
×
1342

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

1354
  UsersDialog d(QtPassSettings::getPass(), QtPassSettings::load(), dir, this);
×
1355
  if (!d.exec()) {
×
1356
    ui->treeView->setFocus();
×
1357
  }
1358
}
×
1359

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

1376
/**
1377
 * @brief MainWindow::generateKeyPair internal gpg keypair generator . .
1378
 * @param batch
1379
 * @param keygenWindow
1380
 */
1381
void MainWindow::generateKeyPair(const QString &batch, QDialog *keygenWindow) {
×
1382
  m_keyGenDialog = keygenWindow;
1383
  emit generateGPGKeyPair(batch);
×
1384
}
×
1385

1386
/**
1387
 * @brief MainWindow::updateProfileBox update the list of profiles, optionally
1388
 * select a more appropriate one to view too
1389
 */
1390
void MainWindow::updateProfileBox() {
28 ✔
1391
  QHash<QString, QHash<QString, QString>> profiles =
1392
      QtPassSettings::getProfiles();
28 ✔
1393

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

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

1440
  ui->lineEdit->clear();
×
1441

1442
  const QHash<QString, QString> prof =
1443
      QtPassSettings::getProfiles().value(name);
×
1444
  AppSettings s = QtPassSettings::load();
×
1445
  s.activeProfile = name;
×
1446
  s.passStore = prof.value("path");
×
1447
  s.passSigningKey = prof.value("signingKey");
×
1448
  QtPassSettings::save(s);
×
1449
  ui->statusBar->showMessage(tr("Profile changed to %1").arg(name), 2000);
×
1450

1451
  QtPassSettings::getPass()->updateEnv();
×
1452

1453
  const QString passStore = QtPassSettings::getPassStore();
×
1454
  proxyModel.setStore(passStore);
×
1455
  ui->treeView->setRootIndex(proxyModel.rootIndexFor(passStore));
×
1456
  deselect();
×
1457
  ui->treeView->setCurrentIndex(QModelIndex());
×
1458
}
×
1459

1460
/**
1461
 * @brief MainWindow::initTrayIcon show a nice tray icon on systems that
1462
 * support
1463
 * it
1464
 */
1465
void MainWindow::initTrayIcon() {
×
1466
  m_tray = new TrayIcon(this);
×
1467
  if (!m_tray->getIsAllocated()) {
×
1468
    destroyTrayIcon();
×
1469
  }
1470
}
×
1471

1472
/**
1473
 * @brief MainWindow::destroyTrayIcon remove that pesky tray icon
1474
 */
1475
void MainWindow::destroyTrayIcon() {
×
1476
  delete m_tray;
×
1477
  m_tray = nullptr;
×
1478
}
×
1479

1480
/**
1481
 * @brief MainWindow::closeEvent hide or quit
1482
 * @param event
1483
 */
1484
void MainWindow::closeEvent(QCloseEvent *event) {
×
1485
  if (QtPassSettings::isHideOnClose()) {
×
1486
    this->hide();
×
1487
    event->ignore();
1488
  } else {
1489
    m_qtPass->clearClipboard();
×
1490

1491
    QtPassSettings::setGeometry(saveGeometry());
×
1492
    QtPassSettings::setSavestate(saveState());
×
1493
    QtPassSettings::setMaximized(isMaximized());
×
1494
    if (!isMaximized()) {
×
1495
      QtPassSettings::setPos(pos());
×
1496
      QtPassSettings::setSize(size());
×
1497
    }
1498
    event->accept();
1499
    // A visible QSystemTrayIcon keeps the application alive after the last
1500
    // window closes, so quitOnLastWindowClosed never fires and the window
1501
    // merely vanishes into the tray. Quit explicitly so closing the window
1502
    // actually exits when "hide on close" is disabled.
1503
    QApplication::quit();
×
1504
  }
1505
}
×
1506

1507
/**
1508
 * @brief MainWindow::eventFilter filter out some events and focus the
1509
 * treeview
1510
 * @param obj
1511
 * @param event
1512
 * @return
1513
 */
1514
auto MainWindow::eventFilter(QObject *obj, QEvent *event) -> bool {
900 ✔
1515
  if (obj == ui->toolBar && event->type() == QEvent::PaletteChange) {
900 ✔
1516
    // KDE's Breeze style gives top toolbars a "header" palette of its own.
1517
    // After a runtime light/dark switch it recomputes that palette from a
1518
    // cached kdeglobals and stamps the previous theme's colours back on, so
1519
    // the toolbar stays dark on a light window (or vice versa) with matching
1520
    // invisible icons. A legitimate header tint is close to the window
1521
    // colour; a stale theme is not. When the two disagree, drop the imposed
1522
    // palette so the toolbar follows the application palette again. Deferred
1523
    // so we never re-enter the style while it is still applying its palette.
1524
    QTimer::singleShot(0, this, &MainWindow::dropStaleToolBarPalette);
6 ✔
1525
  }
1526
  if (obj == ui->lineEdit && event->type() == QEvent::KeyPress) {
900 ✔
1527
    auto *key = dynamic_cast<QKeyEvent *>(event);
×
1528
    if (key != nullptr && key->key() == Qt::Key_Down) {
×
1529
      ui->treeView->setFocus();
×
1530
    }
1531
  }
1532
  return QObject::eventFilter(obj, event);
900 ✔
1533
}
1534

1535
/**
1536
 * @brief Reset the toolbar palette when a style left it in the wrong theme.
1537
 *
1538
 * Compares the lightness of the toolbar's Window colour with the application
1539
 * palette; a difference above kStaleToolBarLightness means the toolbar shows
1540
 * the other theme. See the PaletteChange branch in eventFilter().
1541
 */
1542
void MainWindow::dropStaleToolBarPalette() {
3 ✔
1543
  if (!ui->toolBar->testAttribute(Qt::WA_SetPalette)) {
3 ✔
1544
    return;
1545
  }
1546
  constexpr int kStaleToolBarLightness = 64;
1547
  const int barLightness =
1548
      ui->toolBar->palette().color(QPalette::Window).lightness();
4 ✔
1549
  const int appLightness =
1550
      QApplication::palette().color(QPalette::Window).lightness();
4 ✔
1551
  if (qAbs(barLightness - appLightness) > kStaleToolBarLightness) {
2 ✔
1552
    ui->toolBar->setPalette(QPalette());
1 ✔
1553
    // The style also paints the tools-area background on the main window
1554
    // from the same stale palette, and the toolbar is transparent by default;
1555
    // paint our own background so the reset is actually visible.
1556
    ui->toolBar->setAutoFillBackground(true);
1 ✔
1557
  }
1558
}
1559

1560
/**
1561
 * @brief MainWindow::keyPressEvent did anyone press return, enter or escape?
1562
 * @param event
1563
 */
1564
void MainWindow::keyPressEvent(QKeyEvent *event) {
×
1565
  switch (event->key()) {
×
1566
  case Qt::Key_Delete:
×
1567
    onDelete();
×
1568
    break;
×
1569
  case Qt::Key_Return:
×
1570
  case Qt::Key_Enter:
1571
    if (proxyModel.rowCount() > 0) {
×
1572
      on_treeView_clicked(ui->treeView->currentIndex());
×
1573
    }
1574
    break;
1575
  case Qt::Key_Escape:
×
1576
    ui->lineEdit->clear();
×
1577
    break;
×
1578
  default:
1579
    break;
1580
  }
1581
}
×
1582

1583
/**
1584
 * @brief MainWindow::showContextMenu show us the (file or folder) context
1585
 * menu
1586
 * @param pos
1587
 */
1588
void MainWindow::showContextMenu(const QPoint &pos) {
×
1589
  const AppSettings s = QtPassSettings::load();
×
1590
  QModelIndex index = ui->treeView->indexAt(pos);
×
1591
  bool selected = true;
1592
  if (!index.isValid()) {
1593
    ui->treeView->clearSelection();
×
1594
    ui->actionDelete->setEnabled(false);
×
1595
    ui->actionEdit->setEnabled(false);
×
1596
    m_currentDir = "";
×
1597
    selected = false;
1598
  }
1599

1600
  ui->treeView->setCurrentIndex(index);
×
1601

1602
  QPoint globalPos = ui->treeView->viewport()->mapToGlobal(pos);
×
1603

1604
  QFileInfo fileOrFolder =
1605
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
1606

1607
  QMenu contextMenu;
×
1608
  if (!selected || fileOrFolder.isDir()) {
×
1609
    QAction *openFolder =
1610
        contextMenu.addAction(tr("Open folder with file manager"));
×
1611
    QAction *addFolder = contextMenu.addAction(tr("Add folder"));
×
1612
    QAction *addPassword = contextMenu.addAction(tr("Add password"));
×
1613
    QAction *users = contextMenu.addAction(tr("Users"));
×
1614
    connect(openFolder, &QAction::triggered, this, &MainWindow::openFolder);
×
1615
    connect(addFolder, &QAction::triggered, this, &MainWindow::addFolder);
×
1616
    connect(addPassword, &QAction::triggered, this, &MainWindow::addPassword);
×
1617
    connect(users, &QAction::triggered, this, &MainWindow::onUsers);
×
1618
  } else if (fileOrFolder.isFile()) {
×
1619
    QAction *edit = contextMenu.addAction(tr("Edit"));
×
1620
    connect(edit, &QAction::triggered, this, &MainWindow::onEdit);
×
1621
  }
1622
  if (selected) {
×
1623
    contextMenu.addSeparator();
×
1624
    if (fileOrFolder.isDir()) {
×
1625
      QAction *renameFolder = contextMenu.addAction(tr("Rename folder"));
×
1626
      connect(renameFolder, &QAction::triggered, this,
×
1627
              &MainWindow::renameFolder);
×
1628
    } else if (fileOrFolder.isFile()) {
×
1629
      QAction *renamePassword = contextMenu.addAction(tr("Rename password"));
×
1630
      connect(renamePassword, &QAction::triggered, this,
×
1631
              &MainWindow::renamePassword);
×
1632
    }
1633
    QAction *deleteItem = contextMenu.addAction(tr("Delete"));
×
1634
    connect(deleteItem, &QAction::triggered, this, &MainWindow::onDelete);
×
1635
    if (fileOrFolder.isDir()) {
×
1636
      QString dirPath = QDir::cleanPath(Util::getDir(
×
1637
          ui->treeView->currentIndex(), false, model, proxyModel, s.passStore));
×
1638

1639
      auto *shareMenu = new QMenu(tr("Share"), &contextMenu);
×
1640
      contextMenu.addMenu(shareMenu);
×
1641

1642
      QString gpgIdPath = Pass::getGpgIdPath(dirPath, s.passStore);
×
1643
      bool gpgIdExists = !gpgIdPath.isEmpty() && QFile(gpgIdPath).exists();
×
1644

1645
      const QString exePath = s.usePass ? s.passExecutable : s.gpgExecutable;
×
1646
      bool gpgAvailable = !exePath.isEmpty() && (exePath.startsWith("wsl ") ||
×
1647
                                                 QFile(exePath).exists());
×
1648

1649
      QAction *reencrypt = shareMenu->addAction(tr("Re-encrypt all passwords"));
×
1650
      reencrypt->setEnabled(gpgIdExists && gpgAvailable);
×
1651
      connect(reencrypt, &QAction::triggered, this,
×
1652
              [this, dirPath]() { reencryptPath(dirPath); });
×
1653

1654
      QAction *exportKey = shareMenu->addAction(tr("Export my public key..."));
×
1655
      exportKey->setEnabled(gpgAvailable);
×
1656
      connect(exportKey, &QAction::triggered, this,
×
1657
              &MainWindow::exportPublicKey);
×
1658

1659
      QAction *addRecipientAction =
1660
          shareMenu->addAction(tr("Add recipient..."));
×
1661
      addRecipientAction->setEnabled(gpgIdExists && gpgAvailable);
×
1662
      connect(addRecipientAction, &QAction::triggered, this,
×
1663
              [this, dirPath]() { addRecipient(dirPath); });
×
1664

1665
      QAction *shareHelp = shareMenu->addAction(tr("What is this?"));
×
1666
      connect(shareHelp, &QAction::triggered, this, &MainWindow::showShareHelp);
×
1667
    }
1668
  }
1669
  contextMenu.exec(globalPos);
×
1670
}
×
1671

1672
/**
1673
 * @brief MainWindow::showBrowserContextMenu show us the context menu in
1674
 * password window
1675
 * @param pos
1676
 */
1677
void MainWindow::showBrowserContextMenu(const QPoint &pos) {
×
1678
  QMenu *contextMenu = ui->textBrowser->createStandardContextMenu(pos);
×
1679
  // createStandardContextMenu() parents the menu to textBrowser. A stylesheet
1680
  // on the browser (it used to carry "background: palette(base)") cascades to
1681
  // the child QMenu and breaks its opaque native background. Reparent to the
1682
  // main window so the menu paints solid regardless of browser styling.
1683
  contextMenu->setParent(this, contextMenu->windowFlags());
×
1684
  QPoint globalPos = ui->textBrowser->viewport()->mapToGlobal(pos);
×
1685

1686
  contextMenu->exec(globalPos);
×
1687
  delete contextMenu;
×
1688
}
×
1689

1690
/**
1691
 * @brief MainWindow::openFolder open the folder in the default file manager
1692
 */
1693
void MainWindow::openFolder() {
×
1694
  QString dir = Util::getDir(ui->treeView->currentIndex(), false, model,
×
1695
                             proxyModel, QtPassSettings::getPassStore());
×
1696

1697
  QString path = QDir::toNativeSeparators(dir);
×
1698
  QDesktopServices::openUrl(QUrl::fromLocalFile(path));
×
1699
}
×
1700

1701
/**
1702
 * @brief MainWindow::addFolder add a new folder to store passwords in
1703
 */
1704
void MainWindow::addFolder() {
×
1705
  const AppSettings s = QtPassSettings::load();
×
1706
  bool ok;
1707
  QString dir = Util::getDir(ui->treeView->currentIndex(), false, model,
×
1708
                             proxyModel, s.passStore);
×
1709
  QString newdir = QInputDialog::getText(
1710
      this, tr("New file"),
×
1711
      tr("New Folder: \n(Will be placed in %1 )")
×
1712
          .arg(s.passStore + Util::getDir(ui->treeView->currentIndex(), true,
×
1713
                                          model, proxyModel, s.passStore)),
1714
      QLineEdit::Normal, "", &ok);
×
1715
  if (!ok || newdir.isEmpty()) {
×
1716
    return;
1717
  }
1718
  newdir.prepend(dir);
1719
  if (!confirmPathInStore(newdir)) {
×
1720
    return;
1721
  }
1722
  if (!QDir().mkdir(newdir)) {
×
1723
    QMessageBox::warning(this, tr("Error"),
×
1724
                         tr("Failed to create folder: %1").arg(newdir));
×
1725
    return;
×
1726
  }
1727
  // A .gpg-id only counts when it is signed once a signing key is configured:
1728
  // ImitatePass::verifyGpgIdFile and pass (PASSWORD_STORE_SIGNING_KEY) both
1729
  // refuse to encrypt into a folder whose .gpg-id has no matching
1730
  // .gpg-id.sig. Signing here would need the signing secret key and a
1731
  // passphrase prompt just to create a folder, so in that case leave the
1732
  // folder without its own .gpg-id: it inherits the parent's signed list,
1733
  // which encrypts to the same recipients. UsersDialog (Init) is the place to
1734
  // give it a distinct, signed list.
1735
  const bool signingConfigured = !s.passSigningKey.trimmed().isEmpty();
×
1736
  if (s.addGPGId && !signingConfigured) {
×
1737
    // Seed the new folder's .gpg-id from the recipients that are currently
1738
    // in effect for its parent. The previous implementation walked
1739
    // listKeys("", true) and wrote every key whose `enabled` flag was set,
1740
    // but that flag is only toggled inside UsersDialog, so the loop wrote
1741
    // nothing and left a zero-byte .gpg-id that shadowed the parent's
1742
    // recipients (see #1682).
1743
    if (!Pass::seedGpgIdFile(newdir, s.passStore)) {
×
1744
      QMessageBox::warning(
×
1745
          this, tr("Error"),
×
1746
          tr("Failed to create .gpg-id file in: %1").arg(newdir));
×
1747
      return;
×
1748
    }
1749
  }
1750
}
×
1751

1752
/**
1753
 * @brief MainWindow::renameFolder rename an existing folder
1754
 */
1755
void MainWindow::renameFolder() {
×
1756
  bool ok;
1757
  QString srcDir =
1758
      QDir::cleanPath(Util::getDir(ui->treeView->currentIndex(), false, model,
×
1759
                                   proxyModel, QtPassSettings::getPassStore()));
×
1760
  QString srcDirName = QDir(srcDir).dirName();
×
1761
  QString newName =
1762
      QInputDialog::getText(this, tr("Rename file"), tr("Rename Folder To: "),
×
1763
                            QLineEdit::Normal, srcDirName, &ok);
×
1764
  if (!ok || newName.isEmpty()) {
×
1765
    return;
1766
  }
1767
  QString destDir = srcDir;
1768
  destDir.replace(srcDir.lastIndexOf(srcDirName), srcDirName.length(), newName);
×
1769
  if (!confirmPathInStore(destDir)) {
×
1770
    return;
1771
  }
1772
  QtPassSettings::getPass()->Move(srcDir, destDir, false);
×
1773
}
1774

1775
/**
1776
 * @brief MainWindow::editPassword read password and open edit window via
1777
 * MainWindow::onEdit()
1778
 */
1779
void MainWindow::editPassword(const QString &file) {
1 ✔
1780
  if (!file.isEmpty()) {
1 ✔
1781
    const AppSettings s = QtPassSettings::load();
1 ✔
1782
    if (s.useGit && s.autoPull) {
1 ✔
1783
      onUpdate(true);
×
1784
    }
1785
    setPassword(file, false);
1 ✔
1786
  }
1 ✔
1787
}
1 ✔
1788

1789
/**
1790
 * @brief MainWindow::renamePassword rename an existing password
1791
 */
1792
void MainWindow::renamePassword() {
×
1793
  bool ok;
1794
  QString file = getFile(ui->treeView->currentIndex(), false);
×
1795
  QString filePath = QFileInfo(file).path();
×
1796
  QString fileName = QFileInfo(file).fileName();
×
1797
  if (fileName.endsWith(".gpg", Qt::CaseInsensitive)) {
×
1798
    fileName.chop(4);
×
1799
  }
1800

1801
  QString newName =
1802
      QInputDialog::getText(this, tr("Rename file"), tr("Rename File To: "),
×
1803
                            QLineEdit::Normal, fileName, &ok);
×
1804
  if (!ok || newName.isEmpty()) {
×
1805
    return;
1806
  }
1807
  QString newFile = QDir(filePath).filePath(newName);
×
1808
  if (!confirmPathInStore(newFile)) {
×
1809
    return;
1810
  }
1811
  QtPassSettings::getPass()->Move(file, newFile, false);
×
1812
}
1813

1814
/**
1815
 * @brief Copies the password of the selected file from the tree view to the
1816
 * clipboard.
1817
 * @example
1818
 * MainWindow::copyPasswordFromTreeview();
1819
 *
1820
 * @return void - This function does not return a value.
1821
 */
1822
void MainWindow::copyPasswordFromTreeview() {
×
1823
  QFileInfo fileOrFolder =
1824
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
1825

1826
  if (fileOrFolder.isFile()) {
×
1827
    // finishedShow carries no request identity, so allow only one copy request
1828
    // in flight: otherwise a second Ctrl+C on a different entry would re-arm
1829
    // the single-shot slot and the first decrypt to finish would copy the wrong
1830
    // entry while the later request is silently dropped. See
1831
    // m_passwordCopyPending.
1832
    if (m_passwordCopyPending) {
×
1833
      return;
×
1834
    }
1835
    m_passwordCopyPending = true;
×
1836
    QString file = getFile(ui->treeView->currentIndex(), true);
×
1837
    connectSingleShot(QtPassSettings::getPass(), &Pass::finishedShow, this,
×
1838
                      &MainWindow::passwordFromFileToClipboard);
1839
    // This Show repaints the panel as well; see onOtp().
1840
    m_shownFile = file;
×
1841
    QtPassSettings::getPass()->Show(file);
×
1842
  }
1843
}
×
1844

1845
void MainWindow::passwordFromFileToClipboard(const QString &text) {
2 ✔
1846
  disconnectSingleShot(QtPassSettings::getPass(), &Pass::finishedShow, this,
2 ✔
1847
                       &MainWindow::passwordFromFileToClipboard);
1848
  m_passwordCopyPending = false;
2 ✔
1849
  const QStringList tokens = text.split('\n');
2 ✔
1850
  if (tokens.isEmpty()) {
2 ✔
1851
    return;
1852
  }
1853
  // An entry created by `pass otp insert` has the otpauth:// URI as its first
1854
  // line. That URI carries the shared TOTP secret (the seed, not a code), so
1855
  // copying it to the clipboard would leak 2FA material. Skip it, matching the
1856
  // display path (FileContent::getPasswordForDisplay / PasswordDisplayPanel).
1857
  if (FileContent::isOtpUriValue(tokens[0])) {
2 ✔
1858
    flashText(tr("This entry holds an OTP secret, not a password"), true);
1 ✔
1859
    return;
1 ✔
1860
  }
1861
  m_qtPass->copyTextToClipboard(tokens[0]);
1 ✔
1862
}
1863

1864
/**
1865
 * @brief Displays message in status bar
1866
 *
1867
 * @param msg     text to be displayed
1868
 * @param timeout time for which msg shall be visible
1869
 */
1870
void MainWindow::showStatusMessage(const QString &msg, int timeout) {
7 ✔
1871
  ui->statusBar->showMessage(msg, timeout);
7 ✔
1872
}
7 ✔
1873

1874
/**
1875
 * @brief MainWindow::reencryptPath re-encrypt all passwords in a directory
1876
 * @param dir Directory path to re-encrypt
1877
 */
1878
void MainWindow::reencryptPath(const QString &dir) {
×
1879
  QDir checkDir(dir);
×
1880
  if (!checkDir.exists()) {
×
1881
    QMessageBox::critical(this, tr("Error"),
×
1882
                          tr("Directory does not exist: %1").arg(dir));
×
1883
    return;
×
1884
  }
1885

1886
  int ret = QMessageBox::question(
×
1887
      this, tr("Re-encrypt passwords"),
×
1888
      tr("Re-encrypt all passwords in %1?\n\n"
×
1889
         "This will re-encrypt ALL password files in this folder "
1890
         "using the current recipients defined in .gpg-id.\n\n"
1891
         "This may rewrite many files and cannot be undone easily.\n\n"
1892
         "Continue?")
1893
          .arg(QDir(dir).dirName()),
×
1894
      QMessageBox::Yes | QMessageBox::No);
1895

1896
  if (ret != QMessageBox::Yes)
×
1897
    return;
1898

1899
  // Disable preemptively. ImitatePass::reencryptPath emits
1900
  // startReencryptPath asynchronously and the slot would re-run this,
1901
  // but setEnabled(false) is idempotent so the duplicate is harmless.
1902
  startReencryptPath();
×
1903

1904
  QtPassSettings::getImitatePass()->reencryptPath(
×
1905
      QDir::cleanPath(QDir(dir).absolutePath()));
×
1906
}
×
1907

1908
/**
1909
 * @brief MainWindow::startReencryptPath disable ui elements and treeview
1910
 */
1911
void MainWindow::startReencryptPath() {
×
1912
  setUiElementsEnabled(false);
×
1913
  ui->treeView->setDisabled(true);
×
1914
}
×
1915

1916
/**
1917
 * @brief MainWindow::endReencryptPath re-enable ui elements
1918
 */
1919
void MainWindow::endReencryptPath() { setUiElementsEnabled(true); }
×
1920

1921
/**
1922
 * @brief MainWindow::exportPublicKey export the configured signing key in
1923
 *        ASCII-armored form via gpg and show it in ExportPublicKeyDialog.
1924
 *
1925
 * Falls back to a help dialog when no signing key is configured or gpg is
1926
 * unavailable, so the user still gets actionable guidance.
1927
 */
1928
void MainWindow::exportPublicKey() {
×
1929
  const AppSettings s = QtPassSettings::load();
×
1930
  const QString identity = s.passSigningKey;
1931
  if (identity.isEmpty()) {
×
1932
    QMessageBox::information(
×
1933
        this, tr("Export Public Key"),
×
1934
        tr("<h3>Export Your Public Key</h3>"
×
1935
           "<p>No signing key is configured. Set one in QtPass Settings "
1936
           "&gt; GPG keys, or run this in a terminal:</p>"
1937
           "<pre>gpg --armor --export --output my_key.asc &lt;your-key-id"
1938
           "&gt;</pre>"
1939
           "<p>Then send the file to your teammates.</p>"));
1940
    return;
×
1941
  }
1942
  QString gpgExe = s.gpgExecutable;
1943
  if (gpgExe.isEmpty()) {
×
1944
    gpgExe = QStringLiteral("gpg");
×
1945
  }
1946
  QStringList args = {"--armor", "--export"};
×
1947
  args.append(identity.split(' ', Qt::SkipEmptyParts));
×
1948
  QString stdOut;
×
1949
  QString stdErr;
×
1950
  int exitCode = Executor::executeBlocking(gpgExe, args, &stdOut, &stdErr);
×
1951
  if (exitCode != 0 || stdOut.isEmpty()) {
×
1952
    QMessageBox::warning(this, tr("Export Public Key"),
×
1953
                         tr("Could not export public key for %1.\n\n%2")
×
1954
                             .arg(identity, stdErr.isEmpty()
×
1955
                                                ? tr("No output from gpg.")
×
1956
                                                : stdErr));
1957
    return;
1958
  }
1959
  ExportPublicKeyDialog dialog(identity, stdOut, this);
×
1960
  dialog.exec();
×
1961
}
×
1962

1963
/**
1964
 * @brief MainWindow::addRecipient open the recipient management dialog for
1965
 *        the supplied directory.
1966
 * @param dir Folder whose .gpg-id should be edited.
1967
 *
1968
 * Delegates to UsersDialog so users can tick/untick keys from their
1969
 * keyring as recipients of the folder; importing a foreign key into the
1970
 * keyring still has to happen via gpg (or QtPass settings) first.
1971
 */
1972
void MainWindow::addRecipient(const QString &dir) {
×
1973
  UsersDialog d(QtPassSettings::getPass(), QtPassSettings::load(), dir, this);
×
1974
  d.exec();
×
1975
}
×
1976

1977
/**
1978
 * @brief MainWindow::showShareHelp show help about GPG sharing
1979
 */
1980
void MainWindow::showShareHelp() {
×
1981
  QMessageBox::information(
×
1982
      this, tr("Sharing Passwords with GPG"),
×
1983
      tr("<h3>Sharing Passwords with GPG</h3>"
×
1984
         "<p>To share passwords with other users:</p>"
1985
         "<ol>"
1986
         "<li><b>Export your public key</b> and send it to teammates</li>"
1987
         "<li><b>Import teammates' public keys</b> into your GPG keyring</li>"
1988
         "<li><b>Re-encrypt passwords</b> so all recipients can decrypt "
1989
         "them</li>"
1990
         "</ol>"
1991
         "<p>Only people who have a matching secret key can decrypt the "
1992
         "passwords.</p>"
1993
         "<p><b>Tip:</b> Use the same GPG key for all shared folders.</p>"
1994
         "<p>See the FAQ for more details.</p>"));
1995
}
×
1996

1997
void MainWindow::updateGitButtonVisibility() {
41 ✔
1998
  const AppSettings s = QtPassSettings::load();
41 ✔
1999
  if (!s.useGit || (s.gitExecutable.isEmpty() && s.passExecutable.isEmpty())) {
41 ✔
2000
    enableGitButtons(false);
41 ✔
2001
  } else {
2002
    enableGitButtons(true);
×
2003
  }
2004
}
41 ✔
2005

2006
void MainWindow::updateOtpButtonVisibility(bool uiEnabled) {
41 ✔
2007
  // No platform gating any more: codes are generated in-process, so this works
2008
  // on Windows and macOS and with either backend. It used to be hidden there
2009
  // because the pass-otp extension is Unix-only.
2010
  //
2011
  // Kept visible but disabled when OTP is off, as it was before: hiding it
2012
  // removed the only discoverable trace of the feature, and since an OTP field
2013
  // is suppressed from the panel unconditionally (its value is a secret), a
2014
  // user with the setting off would see nothing at all where their OTP data
2015
  // used to be.
2016
  //
2017
  // Enablement must honour uiEnabled: this is called from
2018
  // setUiElementsEnabled(), and ignoring the argument re-enabled the action
2019
  // while a decrypt was in flight, letting the user stack Show calls.
2020
  ui->actionOtp->setVisible(true);
41 ✔
2021
  ui->actionOtp->setEnabled(QtPassSettings::isUseOtp() && uiEnabled);
41 ✔
2022
}
41 ✔
2023

2024
void MainWindow::updateGrepButtonVisibility() {
28 ✔
2025
  const bool enabled = QtPassSettings::isUseGrepSearch();
28 ✔
2026
  ui->grepButton->setVisible(enabled);
28 ✔
2027
  ui->grepCaseButton->setVisible(enabled);
28 ✔
2028
  if (!enabled && m_grep.inGrepMode()) {
28 ✔
2029
    ui->grepButton->setChecked(false);
×
2030
  }
2031
}
28 ✔
2032

2033
void MainWindow::enableGitButtons(const bool &state) {
41 ✔
2034
  // Following GNOME guidelines is preferable disable buttons instead of hide
2035
  ui->actionPush->setEnabled(state);
41 ✔
2036
  ui->actionUpdate->setEnabled(state);
41 ✔
2037
}
41 ✔
2038

2039
/**
2040
 * @brief MainWindow::critical critical message popup wrapper.
2041
 * @param title
2042
 * @param msg
2043
 */
2044
void MainWindow::critical(const QString &title, const QString &msg) {
×
2045
  QMessageBox::critical(this, title, msg);
×
2046
}
×
2047

2048
/**
2049
 * @brief Appends processed command output to the output panel.
2050
 *
2051
 * Appends text to the process output text edit, with per-line numbering,
2052
 * optional command prefix, and color coding for errors vs. success.
2053
 * Handles auto-scrolling and line limits.
2054
 *
2055
 * @param output The raw output text from the command.
2056
 * @param isError true if this is error output (stderr).
2057
 * @param linePrefix Optional command name to prefix each line with.
2058
 */
2059
void MainWindow::appendProcessOutput(const QString &output, bool isError,
2 ✔
2060
                                     const QString &linePrefix) {
2061
  if (!QtPassSettings::isShowProcessOutput()) {
2 ✔
2062
    return;
1 ✔
2063
  }
2064

2065
  QStringList lines = output.split('\n', Qt::SkipEmptyParts);
1 ✔
2066
  for (QString &line : lines) {
2 ✔
2067
    // Right-trim only: remove trailing CR and whitespace, preserve leading
2068
    // indentation
2069
    line.remove('\r');
1 ✔
2070
    while (!line.isEmpty() && line.back().isSpace()) {
2 ✔
2071
      line.chop(1);
×
2072
    }
2073
    if (line.isEmpty()) {
1 ✔
2074
      continue;
×
2075
    }
2076

2077
    m_outputCounter++;
1 ✔
2078
    QString lineNumber = QString::number(m_outputCounter);
1 ✔
2079

2080
    QColor textColor =
2081
        isError ? QColor(Qt::red)
1 ✔
2082
                : m_processOutputEdit->palette().color(QPalette::Text);
2 ✔
2083
    QString colorHex = textColor.name();
1 ✔
2084
    // Apply the optional prefix per line so multi-line output stays
2085
    // attributed to its command (e.g. all 3 lines of a `git push` show
2086
    // "git push: ..." rather than only the first).
2087
    QString prefixed =
2088
        linePrefix.isEmpty() ? line : linePrefix + QStringLiteral(": ") + line;
2 ✔
2089
    QString coloredOutput =
2090
        QString("<span style=\"color: %1;\">%2: %3</span>")
1 ✔
2091
            .arg(colorHex, lineNumber, prefixed.toHtmlEscaped());
2 ✔
2092

2093
    m_processOutputEdit->append(coloredOutput);
1 ✔
2094
  }
2095

2096
  limitOutputLines();
1 ✔
2097

2098
  if (m_autoScroll) {
1 ✔
2099
    m_processOutputEdit->verticalScrollBar()->setValue(
2 ✔
2100
        m_processOutputEdit->verticalScrollBar()->maximum());
1 ✔
2101
  }
2102
}
2103

2104
/**
2105
 * @brief Handles process output from the Pass executor.
2106
 *
2107
 * Called when any non-sensitive process completes. Filters out password-
2108
 * related commands (pass show, insert, etc.) and delegates to
2109
 * appendProcessOutput.
2110
 *
2111
 * @param output The stdout/stderr text from the process.
2112
 * @param isError true if this is error output (stderr).
2113
 * @param pid The process ID identifying which command ran.
2114
 */
2115
void MainWindow::onProcessOutput(const QString &output, bool isError,
2 ✔
2116
                                 Enums::PROCESS pid) {
2117
  appendProcessOutput(output, isError, getProcessName(pid));
2 ✔
2118
}
2 ✔
2119

2120
/**
2121
 * @brief Maps a process ID to its human-readable command name.
2122
 *
2123
 * Returns static strings for git/pass commands that appear in output.
2124
 * Password-related commands return empty (they are filtered).
2125
 *
2126
 * @param pid The process ID to look up.
2127
 * @return QString with command name, or empty if filtered.
2128
 */
2129
auto MainWindow::getProcessName(Enums::PROCESS pid) -> QString {
2 ✔
2130
  switch (pid) {
2 ✔
2131
  case Enums::GIT_INIT:
×
2132
    return QStringLiteral("git init"); // no-tr
×
2133
  case Enums::GIT_ADD:
×
2134
    return QStringLiteral("git add"); // no-tr
×
2135
  case Enums::GIT_COMMIT:
×
2136
    return QStringLiteral("git commit"); // no-tr
×
2137
  case Enums::GIT_RM:
×
2138
    return QStringLiteral("git rm"); // no-tr
×
2139
  case Enums::GIT_PULL:
×
2140
    return QStringLiteral("git pull"); // no-tr
×
2141
  case Enums::GIT_PUSH:
×
2142
    return QStringLiteral("git push"); // no-tr
×
2143
  case Enums::GIT_MOVE:
×
2144
    return QStringLiteral("git mv"); // no-tr
×
2145
  case Enums::GIT_COPY:
×
2146
    // ImitatePass::Copy literally invokes `git cp` (a git-extras
2147
    // subcommand), so the label matches what's run. Stock-git users
2148
    // without git-extras will see the underlying "'cp' is not a git
2149
    // command" failure surfaced in the process output panel.
2150
    return QStringLiteral("git cp"); // no-tr
×
2151
  case Enums::PASS_INSERT:
×
2152
    return QStringLiteral("pass insert"); // no-tr
×
2153
  case Enums::PASS_REMOVE:
×
2154
    return QStringLiteral("pass rm"); // no-tr
×
2155
  case Enums::PASS_INIT:
×
2156
    return QStringLiteral("pass init"); // no-tr
×
2157
  case Enums::PASS_MOVE:
×
2158
    return QStringLiteral("pass mv"); // no-tr
×
2159
  case Enums::PASS_COPY:
×
2160
    return QStringLiteral("pass cp"); // no-tr
×
2161
  case Enums::PASS_GREP:
×
2162
    return QStringLiteral("pass grep"); // no-tr
×
2163
  case Enums::GPG_GENKEYS:
×
2164
    return QStringLiteral("gpg --gen-key"); // no-tr
×
2165
  case Enums::PASS_SHOW:
2166
  case Enums::PASS_OTP_GENERATE:
2167
  case Enums::PROCESS_COUNT:
2168
  case Enums::INVALID:
2169
    break;
2170
  }
2171
  return {};
2172
}
2173

2174
/**
2175
 * @brief Checks if a process ID represents a sensitive operation whose
2176
 * output should not be shown in the process output panel.
2177
 *
2178
 * Password-related commands (pass show, OTP generate, grep, insert)
2179
 * display their output in other UI areas, so we skip them here.
2180
 *
2181
 * @param pid The process ID to check.
2182
 * @return true if the process is sensitive and should be filtered.
2183
 */
2184
auto MainWindow::isSensitiveProcess(Enums::PROCESS pid) -> bool {
×
2185
  switch (pid) {
×
2186
  case Enums::PASS_SHOW:
2187
  case Enums::PASS_OTP_GENERATE:
2188
  case Enums::PASS_GREP:
2189
  case Enums::PASS_INSERT:
2190
    return true;
2191
  case Enums::GIT_INIT:
2192
  case Enums::GIT_ADD:
2193
  case Enums::GIT_COMMIT:
2194
  case Enums::GIT_RM:
2195
  case Enums::GIT_PULL:
2196
  case Enums::GIT_PUSH:
2197
  case Enums::GIT_MOVE:
2198
  case Enums::GIT_COPY:
2199
  case Enums::PASS_REMOVE:
2200
  case Enums::PASS_INIT:
2201
  case Enums::PASS_MOVE:
2202
  case Enums::PASS_COPY:
2203
  case Enums::GPG_GENKEYS:
2204
  case Enums::PROCESS_COUNT:
2205
  case Enums::INVALID:
2206
    break;
2207
  }
2208
  return false;
×
2209
}
2210

2211
/**
2212
 * @brief Updates the visibility of the process output panel.
2213
 *
2214
 * Shows or hides the process output widget based on the user's
2215
 * showProcessOutput setting.
2216
 */
2217
void MainWindow::updateProcessOutputVisibility() {
3 ✔
2218
  m_processOutputDock->setVisible(QtPassSettings::isShowProcessOutput());
3 ✔
2219
}
3 ✔
2220

2221
/**
2222
 * @brief Limits the output panel to max lines, trimming old excess.
2223
 *
2224
 * Removes the oldest lines when the document exceeds MaxOutputLines (1000).
2225
 * Called after each append to prevent unbounded growth.
2226
 */
2227
void MainWindow::limitOutputLines() {
1 ✔
2228
  QTextDocument *doc = m_processOutputEdit->document();
1 ✔
2229
  int excess = doc->blockCount() - MaxOutputLines;
1 ✔
2230
  if (excess <= 0) {
1 ✔
2231
    return;
1 ✔
2232
  }
2233

2234
  QTextCursor cursor(doc);
×
2235
  cursor.movePosition(QTextCursor::Start);
×
2236
  cursor.movePosition(QTextCursor::NextBlock, QTextCursor::KeepAnchor, excess);
×
2237
  cursor.removeSelectedText();
×
2238
}
×
2239

2240
/**
2241
 * @brief Clears the process output panel.
2242
 *
2243
 * Clears all output, resets the line counter, and re-enables auto-scroll.
2244
 */
2245
void MainWindow::on_clearOutputButton_clicked() {
×
2246
  m_processOutputEdit->clear();
×
2247
  m_outputCounter = 0;
×
2248
  m_autoScroll = true;
×
2249
}
×
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