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

IJHack / QtPass / 43482519769

13 Nov 2026 06:25PM UTC coverage: 68.466% (+0.05%) from 68.419%
43482519769

push

github

web-flow
coverage: let lcov ignore inconsistent data on system headers (#2138)

lcov 2.x on the CI runner (gcc 15 headers) fails the coverage job with
"lcov: ERROR: (inconsistent) ...: function ... is not hit but line ... has
a non-zero hit count" on files outside the project (e.g. /usr/include/c++/15
and Qt headers), aborting lcov_prepare before coverage of src/ is produced.

The captures already pass "--ignore-errors unused"; add "inconsistent" the
same way. Only the consistency check on data filtered out anyway (-e src/*)
is bypassed; src/ coverage is unchanged. Backport of #2136.

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

5276 of 7706 relevant lines covered (68.47%)

72.38 hits per line

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

39.62
/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::textCopied, m_qtPass,
25 ✔
135
          &QtPass::trackCopied);
25 ✔
136
  connect(ui->textBrowser, &SecretTextBrowser::copied, m_qtPass,
25 ✔
137
          &QtPass::trackCopied);
25 ✔
138
  connect(m_displayPanel, &PasswordDisplayPanel::qrRequested, m_qtPass,
25 ✔
139
          &QtPass::showTextAsQRCode);
25 ✔
140

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

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

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

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

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

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

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

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

195
  setUiElementsEnabled(true);
25 ✔
196

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

710
  emit passShowHandlerFinished(output);
3 ✔
711
  setUiElementsEnabled(true);
3 ✔
712
}
6 ✔
713

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

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

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

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

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

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

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

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

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

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

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

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

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

910
  if (query.isEmpty()) {
×
911
    ui->treeView->collapseAll();
×
912
    deselect();
×
913
  }
914

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

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

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

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

961
  if (proxyModel.rowCount() > 0) {
×
962
    selectFirstFile();
×
963
    on_treeView_clicked(ui->treeView->currentIndex());
×
964
  }
965
}
966

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1246
  QtPassSettings::getPass()->Remove(file, isDir);
×
1247
}
×
1248

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

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

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

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

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

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

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

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

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

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

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

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

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

1444
  ui->lineEdit->clear();
×
1445

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

1464
  QtPassSettings::getPass()->updateEnv();
×
1465

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

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

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

1493
/**
1494
 * @brief MainWindow::closeEvent hide or quit
1495
 * @param event
1496
 */
1497
void MainWindow::closeEvent(QCloseEvent *event) {
×
1498
  if (QtPassSettings::isHideOnClose()) {
×
1499
    this->hide();
×
1500
    event->ignore();
1501
  } else {
1502
    m_qtPass->clearClipboard();
×
1503

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

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

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

1573
/**
1574
 * @brief MainWindow::keyPressEvent did anyone press return, enter or escape?
1575
 * @param event
1576
 */
1577
void MainWindow::keyPressEvent(QKeyEvent *event) {
×
1578
  switch (event->key()) {
×
1579
  case Qt::Key_Delete:
×
1580
    onDelete();
×
1581
    break;
×
1582
  case Qt::Key_Return:
×
1583
  case Qt::Key_Enter:
1584
    if (proxyModel.rowCount() > 0) {
×
1585
      on_treeView_clicked(ui->treeView->currentIndex());
×
1586
    }
1587
    break;
1588
  case Qt::Key_Escape:
×
1589
    ui->lineEdit->clear();
×
1590
    break;
×
1591
  default:
1592
    break;
1593
  }
1594
}
×
1595

1596
/**
1597
 * @brief MainWindow::showContextMenu show us the (file or folder) context
1598
 * menu
1599
 * @param pos
1600
 */
1601
void MainWindow::showContextMenu(const QPoint &pos) {
×
1602
  const AppSettings s = QtPassSettings::load();
×
1603
  QModelIndex index = ui->treeView->indexAt(pos);
×
1604
  bool selected = true;
1605
  if (!index.isValid()) {
1606
    ui->treeView->clearSelection();
×
1607
    ui->actionDelete->setEnabled(false);
×
1608
    ui->actionEdit->setEnabled(false);
×
1609
    m_currentDir = "";
×
1610
    selected = false;
1611
  }
1612

1613
  ui->treeView->setCurrentIndex(index);
×
1614

1615
  QPoint globalPos = ui->treeView->viewport()->mapToGlobal(pos);
×
1616

1617
  QFileInfo fileOrFolder =
1618
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
1619

1620
  QMenu contextMenu;
×
1621
  if (!selected || fileOrFolder.isDir()) {
×
1622
    QAction *openFolder =
1623
        contextMenu.addAction(tr("Open folder with file manager"));
×
1624
    QAction *addFolder = contextMenu.addAction(tr("Add folder"));
×
1625
    QAction *addPassword = contextMenu.addAction(tr("Add password"));
×
1626
    QAction *users = contextMenu.addAction(tr("Users"));
×
1627
    connect(openFolder, &QAction::triggered, this, &MainWindow::openFolder);
×
1628
    connect(addFolder, &QAction::triggered, this, &MainWindow::addFolder);
×
1629
    connect(addPassword, &QAction::triggered, this, &MainWindow::addPassword);
×
1630
    connect(users, &QAction::triggered, this, &MainWindow::onUsers);
×
1631
  } else if (fileOrFolder.isFile()) {
×
1632
    QAction *edit = contextMenu.addAction(tr("Edit"));
×
1633
    connect(edit, &QAction::triggered, this, &MainWindow::onEdit);
×
1634
  }
1635
  if (selected) {
×
1636
    contextMenu.addSeparator();
×
1637
    if (fileOrFolder.isDir()) {
×
1638
      QAction *renameFolder = contextMenu.addAction(tr("Rename folder"));
×
1639
      connect(renameFolder, &QAction::triggered, this,
×
1640
              &MainWindow::renameFolder);
×
1641
    } else if (fileOrFolder.isFile()) {
×
1642
      QAction *renamePassword = contextMenu.addAction(tr("Rename password"));
×
1643
      connect(renamePassword, &QAction::triggered, this,
×
1644
              &MainWindow::renamePassword);
×
1645
    }
1646
    QAction *deleteItem = contextMenu.addAction(tr("Delete"));
×
1647
    connect(deleteItem, &QAction::triggered, this, &MainWindow::onDelete);
×
1648
    if (fileOrFolder.isDir()) {
×
1649
      QString dirPath = QDir::cleanPath(Util::getDir(
×
1650
          ui->treeView->currentIndex(), false, model, proxyModel, s.passStore));
×
1651

1652
      auto *shareMenu = new QMenu(tr("Share"), &contextMenu);
×
1653
      contextMenu.addMenu(shareMenu);
×
1654

1655
      QString gpgIdPath = Pass::getGpgIdPath(dirPath, s.passStore);
×
1656
      bool gpgIdExists = !gpgIdPath.isEmpty() && QFile(gpgIdPath).exists();
×
1657

1658
      const QString exePath = s.usePass ? s.passExecutable : s.gpgExecutable;
×
1659
      bool gpgAvailable = !exePath.isEmpty() && (exePath.startsWith("wsl ") ||
×
1660
                                                 QFile(exePath).exists());
×
1661

1662
      QAction *reencrypt = shareMenu->addAction(tr("Re-encrypt all passwords"));
×
1663
      reencrypt->setEnabled(gpgIdExists && gpgAvailable);
×
1664
      connect(reencrypt, &QAction::triggered, this,
×
1665
              [this, dirPath]() { reencryptPath(dirPath); });
×
1666

1667
      QAction *exportKey = shareMenu->addAction(tr("Export my public key..."));
×
1668
      exportKey->setEnabled(gpgAvailable);
×
1669
      connect(exportKey, &QAction::triggered, this,
×
1670
              &MainWindow::exportPublicKey);
×
1671

1672
      QAction *addRecipientAction =
1673
          shareMenu->addAction(tr("Add recipient..."));
×
1674
      addRecipientAction->setEnabled(gpgIdExists && gpgAvailable);
×
1675
      connect(addRecipientAction, &QAction::triggered, this,
×
1676
              [this, dirPath]() { addRecipient(dirPath); });
×
1677

1678
      QAction *shareHelp = shareMenu->addAction(tr("What is this?"));
×
1679
      connect(shareHelp, &QAction::triggered, this, &MainWindow::showShareHelp);
×
1680
    }
1681
  }
1682
  contextMenu.exec(globalPos);
×
1683
}
×
1684

1685
/**
1686
 * @brief MainWindow::showBrowserContextMenu show us the context menu in
1687
 * password window
1688
 * @param pos
1689
 */
1690
void MainWindow::showBrowserContextMenu(const QPoint &pos) {
×
1691
  QMenu *contextMenu = ui->textBrowser->createStandardContextMenu(pos);
×
1692
  // createStandardContextMenu() parents the menu to textBrowser. A stylesheet
1693
  // on the browser (it used to carry "background: palette(base)") cascades to
1694
  // the child QMenu and breaks its opaque native background. Reparent to the
1695
  // main window so the menu paints solid regardless of browser styling.
1696
  contextMenu->setParent(this, contextMenu->windowFlags());
×
1697
  QPoint globalPos = ui->textBrowser->viewport()->mapToGlobal(pos);
×
1698

1699
  contextMenu->exec(globalPos);
×
1700
  delete contextMenu;
×
1701
}
×
1702

1703
/**
1704
 * @brief MainWindow::openFolder open the folder in the default file manager
1705
 */
1706
void MainWindow::openFolder() {
×
1707
  QString dir = Util::getDir(ui->treeView->currentIndex(), false, model,
×
1708
                             proxyModel, QtPassSettings::getPassStore());
×
1709

1710
  QString path = QDir::toNativeSeparators(dir);
×
1711
  QDesktopServices::openUrl(QUrl::fromLocalFile(path));
×
1712
}
×
1713

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

1765
/**
1766
 * @brief MainWindow::renameFolder rename an existing folder
1767
 */
1768
void MainWindow::renameFolder() {
×
1769
  bool ok;
1770
  QString srcDir =
1771
      QDir::cleanPath(Util::getDir(ui->treeView->currentIndex(), false, model,
×
1772
                                   proxyModel, QtPassSettings::getPassStore()));
×
1773
  QString srcDirName = QDir(srcDir).dirName();
×
1774
  QString newName =
1775
      QInputDialog::getText(this, tr("Rename file"), tr("Rename Folder To: "),
×
1776
                            QLineEdit::Normal, srcDirName, &ok);
×
1777
  if (!ok || newName.isEmpty()) {
×
1778
    return;
1779
  }
1780
  QString destDir = srcDir;
1781
  destDir.replace(srcDir.lastIndexOf(srcDirName), srcDirName.length(), newName);
×
1782
  if (!confirmPathInStore(destDir)) {
×
1783
    return;
1784
  }
1785
  QtPassSettings::getPass()->Move(srcDir, destDir, false);
×
1786
}
1787

1788
/**
1789
 * @brief MainWindow::editPassword read password and open edit window via
1790
 * MainWindow::onEdit()
1791
 */
1792
void MainWindow::editPassword(const QString &file) {
1 ✔
1793
  if (!file.isEmpty()) {
1 ✔
1794
    const AppSettings s = QtPassSettings::load();
1 ✔
1795
    if (s.useGit && s.autoPull) {
1 ✔
1796
      onUpdate(true);
×
1797
    }
1798
    setPassword(file, false);
1 ✔
1799
  }
1 ✔
1800
}
1 ✔
1801

1802
/**
1803
 * @brief MainWindow::renamePassword rename an existing password
1804
 */
1805
void MainWindow::renamePassword() {
×
1806
  bool ok;
1807
  QString file = getFile(ui->treeView->currentIndex(), false);
×
1808
  QString filePath = QFileInfo(file).path();
×
1809
  QString fileName = QFileInfo(file).fileName();
×
1810
  if (fileName.endsWith(".gpg", Qt::CaseInsensitive)) {
×
1811
    fileName.chop(4);
×
1812
  }
1813

1814
  QString newName =
1815
      QInputDialog::getText(this, tr("Rename file"), tr("Rename File To: "),
×
1816
                            QLineEdit::Normal, fileName, &ok);
×
1817
  if (!ok || newName.isEmpty()) {
×
1818
    return;
1819
  }
1820
  QString newFile = QDir(filePath).filePath(newName);
×
1821
  if (!confirmPathInStore(newFile)) {
×
1822
    return;
1823
  }
1824
  QtPassSettings::getPass()->Move(file, newFile, false);
×
1825
}
1826

1827
/**
1828
 * @brief Copies the password of the selected file from the tree view to the
1829
 * clipboard.
1830
 * @example
1831
 * MainWindow::copyPasswordFromTreeview();
1832
 *
1833
 * @return void - This function does not return a value.
1834
 */
1835
void MainWindow::copyPasswordFromTreeview() {
×
1836
  QFileInfo fileOrFolder =
1837
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
1838

1839
  if (fileOrFolder.isFile()) {
×
1840
    // finishedShow carries no request identity, so allow only one copy request
1841
    // in flight: otherwise a second Ctrl+C on a different entry would re-arm
1842
    // the single-shot slot and the first decrypt to finish would copy the wrong
1843
    // entry while the later request is silently dropped. See
1844
    // m_passwordCopyPending.
1845
    if (m_passwordCopyPending) {
×
1846
      return;
×
1847
    }
1848
    m_passwordCopyPending = true;
×
1849
    QString file = getFile(ui->treeView->currentIndex(), true);
×
1850
    connectSingleShot(QtPassSettings::getPass(), &Pass::finishedShow, this,
×
1851
                      &MainWindow::passwordFromFileToClipboard);
1852
    // This Show repaints the panel as well; see onOtp().
1853
    m_shownFile = file;
×
1854
    QtPassSettings::getPass()->Show(file);
×
1855
  }
1856
}
×
1857

1858
void MainWindow::passwordFromFileToClipboard(const QString &text) {
2 ✔
1859
  disconnectSingleShot(QtPassSettings::getPass(), &Pass::finishedShow, this,
2 ✔
1860
                       &MainWindow::passwordFromFileToClipboard);
1861
  m_passwordCopyPending = false;
2 ✔
1862
  const QStringList tokens = text.split('\n');
2 ✔
1863
  if (tokens.isEmpty()) {
2 ✔
1864
    return;
1865
  }
1866
  // An entry created by `pass otp insert` has the otpauth:// URI as its first
1867
  // line. That URI carries the shared TOTP secret (the seed, not a code), so
1868
  // copying it to the clipboard would leak 2FA material. Skip it, matching the
1869
  // display path (FileContent::getPasswordForDisplay / PasswordDisplayPanel).
1870
  if (FileContent::isOtpUriValue(tokens[0])) {
2 ✔
1871
    flashText(tr("This entry holds an OTP secret, not a password"), true);
1 ✔
1872
    return;
1 ✔
1873
  }
1874
  m_qtPass->copyTextToClipboard(tokens[0]);
1 ✔
1875
}
1876

1877
/**
1878
 * @brief Displays message in status bar
1879
 *
1880
 * @param msg     text to be displayed
1881
 * @param timeout time for which msg shall be visible
1882
 */
1883
void MainWindow::showStatusMessage(const QString &msg, int timeout) {
7 ✔
1884
  ui->statusBar->showMessage(msg, timeout);
7 ✔
1885
}
7 ✔
1886

1887
/**
1888
 * @brief MainWindow::reencryptPath re-encrypt all passwords in a directory
1889
 * @param dir Directory path to re-encrypt
1890
 */
1891
void MainWindow::reencryptPath(const QString &dir) {
×
1892
  QDir checkDir(dir);
×
1893
  if (!checkDir.exists()) {
×
1894
    QMessageBox::critical(this, tr("Error"),
×
1895
                          tr("Directory does not exist: %1").arg(dir));
×
1896
    return;
×
1897
  }
1898

1899
  int ret = QMessageBox::question(
×
1900
      this, tr("Re-encrypt passwords"),
×
1901
      tr("Re-encrypt all passwords in %1?\n\n"
×
1902
         "This will re-encrypt ALL password files in this folder "
1903
         "using the current recipients defined in .gpg-id.\n\n"
1904
         "This may rewrite many files and cannot be undone easily.\n\n"
1905
         "Continue?")
1906
          .arg(QDir(dir).dirName()),
×
1907
      QMessageBox::Yes | QMessageBox::No);
1908

1909
  if (ret != QMessageBox::Yes)
×
1910
    return;
1911

1912
  // Disable preemptively. ImitatePass::reencryptPath emits
1913
  // startReencryptPath asynchronously and the slot would re-run this,
1914
  // but setEnabled(false) is idempotent so the duplicate is harmless.
1915
  startReencryptPath();
×
1916

1917
  QtPassSettings::getImitatePass()->reencryptPath(
×
1918
      QDir::cleanPath(QDir(dir).absolutePath()));
×
1919
}
×
1920

1921
/**
1922
 * @brief MainWindow::startReencryptPath disable ui elements and treeview
1923
 */
1924
void MainWindow::startReencryptPath() {
×
1925
  setUiElementsEnabled(false);
×
1926
  ui->treeView->setDisabled(true);
×
1927
}
×
1928

1929
/**
1930
 * @brief MainWindow::endReencryptPath re-enable ui elements
1931
 */
1932
void MainWindow::endReencryptPath() { setUiElementsEnabled(true); }
×
1933

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

1976
/**
1977
 * @brief MainWindow::addRecipient open the recipient management dialog for
1978
 *        the supplied directory.
1979
 * @param dir Folder whose .gpg-id should be edited.
1980
 *
1981
 * Delegates to UsersDialog so users can tick/untick keys from their
1982
 * keyring as recipients of the folder; importing a foreign key into the
1983
 * keyring still has to happen via gpg (or QtPass settings) first.
1984
 */
1985
void MainWindow::addRecipient(const QString &dir) {
×
1986
  UsersDialog d(QtPassSettings::getPass(), QtPassSettings::load(), dir, this);
×
1987
  d.exec();
×
1988
}
×
1989

1990
/**
1991
 * @brief MainWindow::showShareHelp show help about GPG sharing
1992
 */
1993
void MainWindow::showShareHelp() {
×
1994
  QMessageBox::information(
×
1995
      this, tr("Sharing Passwords with GPG"),
×
1996
      tr("<h3>Sharing Passwords with GPG</h3>"
×
1997
         "<p>To share passwords with other users:</p>"
1998
         "<ol>"
1999
         "<li><b>Export your public key</b> and send it to teammates</li>"
2000
         "<li><b>Import teammates' public keys</b> into your GPG keyring</li>"
2001
         "<li><b>Re-encrypt passwords</b> so all recipients can decrypt "
2002
         "them</li>"
2003
         "</ol>"
2004
         "<p>Only people who have a matching secret key can decrypt the "
2005
         "passwords.</p>"
2006
         "<p><b>Tip:</b> Use the same GPG key for all shared folders.</p>"
2007
         "<p>See the FAQ for more details.</p>"));
2008
}
×
2009

2010
void MainWindow::updateGitButtonVisibility() {
41 ✔
2011
  const AppSettings s = QtPassSettings::load();
41 ✔
2012
  if (!s.useGit || (s.gitExecutable.isEmpty() && s.passExecutable.isEmpty())) {
41 ✔
2013
    enableGitButtons(false);
41 ✔
2014
  } else {
2015
    enableGitButtons(true);
×
2016
  }
2017
}
41 ✔
2018

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

2037
void MainWindow::updateGrepButtonVisibility() {
28 ✔
2038
  const bool enabled = QtPassSettings::isUseGrepSearch();
28 ✔
2039
  ui->grepButton->setVisible(enabled);
28 ✔
2040
  ui->grepCaseButton->setVisible(enabled);
28 ✔
2041
  if (!enabled && m_grep.inGrepMode()) {
28 ✔
2042
    ui->grepButton->setChecked(false);
×
2043
  }
2044
}
28 ✔
2045

2046
void MainWindow::enableGitButtons(const bool &state) {
41 ✔
2047
  // Following GNOME guidelines is preferable disable buttons instead of hide
2048
  ui->actionPush->setEnabled(state);
41 ✔
2049
  ui->actionUpdate->setEnabled(state);
41 ✔
2050
}
41 ✔
2051

2052
/**
2053
 * @brief MainWindow::critical critical message popup wrapper.
2054
 * @param title
2055
 * @param msg
2056
 */
2057
void MainWindow::critical(const QString &title, const QString &msg) {
×
2058
  QMessageBox::critical(this, title, msg);
×
2059
}
×
2060

2061
/**
2062
 * @brief Appends processed command output to the output panel.
2063
 *
2064
 * Appends text to the process output text edit, with per-line numbering,
2065
 * optional command prefix, and color coding for errors vs. success.
2066
 * Handles auto-scrolling and line limits.
2067
 *
2068
 * @param output The raw output text from the command.
2069
 * @param isError true if this is error output (stderr).
2070
 * @param linePrefix Optional command name to prefix each line with.
2071
 */
2072
void MainWindow::appendProcessOutput(const QString &output, bool isError,
2 ✔
2073
                                     const QString &linePrefix) {
2074
  if (!QtPassSettings::isShowProcessOutput()) {
2 ✔
2075
    return;
1 ✔
2076
  }
2077

2078
  QStringList lines = output.split('\n', Qt::SkipEmptyParts);
1 ✔
2079
  for (QString &line : lines) {
2 ✔
2080
    // Right-trim only: remove trailing CR and whitespace, preserve leading
2081
    // indentation
2082
    line.remove('\r');
1 ✔
2083
    while (!line.isEmpty() && line.back().isSpace()) {
2 ✔
2084
      line.chop(1);
×
2085
    }
2086
    if (line.isEmpty()) {
1 ✔
2087
      continue;
×
2088
    }
2089

2090
    m_outputCounter++;
1 ✔
2091
    QString lineNumber = QString::number(m_outputCounter);
1 ✔
2092

2093
    QColor textColor =
2094
        isError ? QColor(Qt::red)
1 ✔
2095
                : m_processOutputEdit->palette().color(QPalette::Text);
2 ✔
2096
    QString colorHex = textColor.name();
1 ✔
2097
    // Apply the optional prefix per line so multi-line output stays
2098
    // attributed to its command (e.g. all 3 lines of a `git push` show
2099
    // "git push: ..." rather than only the first).
2100
    QString prefixed =
2101
        linePrefix.isEmpty() ? line : linePrefix + QStringLiteral(": ") + line;
2 ✔
2102
    QString coloredOutput =
2103
        QString("<span style=\"color: %1;\">%2: %3</span>")
1 ✔
2104
            .arg(colorHex, lineNumber, prefixed.toHtmlEscaped());
2 ✔
2105

2106
    m_processOutputEdit->append(coloredOutput);
1 ✔
2107
  }
2108

2109
  limitOutputLines();
1 ✔
2110

2111
  if (m_autoScroll) {
1 ✔
2112
    m_processOutputEdit->verticalScrollBar()->setValue(
2 ✔
2113
        m_processOutputEdit->verticalScrollBar()->maximum());
1 ✔
2114
  }
2115
}
2116

2117
/**
2118
 * @brief Handles process output from the Pass executor.
2119
 *
2120
 * Called when any non-sensitive process completes. Filters out password-
2121
 * related commands (pass show, insert, etc.) and delegates to
2122
 * appendProcessOutput.
2123
 *
2124
 * @param output The stdout/stderr text from the process.
2125
 * @param isError true if this is error output (stderr).
2126
 * @param pid The process ID identifying which command ran.
2127
 */
2128
void MainWindow::onProcessOutput(const QString &output, bool isError,
2 ✔
2129
                                 Enums::PROCESS pid) {
2130
  appendProcessOutput(output, isError, getProcessName(pid));
2 ✔
2131
}
2 ✔
2132

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

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

2224
/**
2225
 * @brief Updates the visibility of the process output panel.
2226
 *
2227
 * Shows or hides the process output widget based on the user's
2228
 * showProcessOutput setting.
2229
 */
2230
void MainWindow::updateProcessOutputVisibility() {
3 ✔
2231
  m_processOutputDock->setVisible(QtPassSettings::isShowProcessOutput());
3 ✔
2232
}
3 ✔
2233

2234
/**
2235
 * @brief Limits the output panel to max lines, trimming old excess.
2236
 *
2237
 * Removes the oldest lines when the document exceeds MaxOutputLines (1000).
2238
 * Called after each append to prevent unbounded growth.
2239
 */
2240
void MainWindow::limitOutputLines() {
1 ✔
2241
  QTextDocument *doc = m_processOutputEdit->document();
1 ✔
2242
  int excess = doc->blockCount() - MaxOutputLines;
1 ✔
2243
  if (excess <= 0) {
1 ✔
2244
    return;
1 ✔
2245
  }
2246

2247
  QTextCursor cursor(doc);
×
2248
  cursor.movePosition(QTextCursor::Start);
×
2249
  cursor.movePosition(QTextCursor::NextBlock, QTextCursor::KeepAnchor, excess);
×
2250
  cursor.removeSelectedText();
×
2251
}
×
2252

2253
/**
2254
 * @brief Clears the process output panel.
2255
 *
2256
 * Clears all output, resets the line counter, and re-enables auto-scroll.
2257
 */
2258
void MainWindow::on_clearOutputButton_clicked() {
×
2259
  m_processOutputEdit->clear();
×
2260
  m_outputCounter = 0;
×
2261
  m_autoScroll = true;
×
2262
}
×
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