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

IJHack / QtPass / 27480142055

13 Jun 2026 09:50PM UTC coverage: 56.384% (+0.8%) from 55.569%
27480142055

push

github

web-flow
refactor: introduce AppSettings struct + SettingsSerializer (#1511) (#1528)

First stage of the QtPassSettings boilerplate reduction (#1511). Adds the
foundation without touching existing behaviour:

- AppSettings (src/appsettings.h): a plain value object with one field per
  flat setting, carrying the same defaults the legacy getters apply
  (PasswordConfiguration length 16, clipBoardType NEVER, etc.). No QSettings
  dependency.
- SettingsSerializer (src/settingsserializer.{h,cpp}): pure, side-effect-free
  load()/save() between AppSettings and a QSettings store, using the exact
  same keys QtPassSettings uses so existing config files keep working.
  Unlike the old getters it performs no path normalisation, directory
  creation, screen-centring or .git auto-detection — those stay in the
  consumers.
- Tests in tst_settings: load-defaults, full save/load round-trip across
  every field, and key-compatibility against SettingsConstants.

Nested/keyed settings (profiles, per-dialog geometry, splitter positions)
are intentionally out of scope and still go through QtPassSettings; the
profile type is tracked separately. No existing getters are rewired yet —
that is staged in follow-up PRs (ConfigDialog, then other readers, then
deleting the wrappers). #1511 stays open.

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

132 of 133 new or added lines in 1 file covered. (99.25%)

292 existing lines in 3 files now uncovered.

3864 of 6853 relevant lines covered (56.38%)

36.36 hits per line

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

24.66
/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 "pathvalidator.h"
16
#include "qpushbuttonasqrcode.h"
17
#include "qpushbuttonshowpassword.h"
18
#include "qpushbuttonwithclipboard.h"
19
#include "qtpass.h"
20
#include "qtpasssettings.h"
21
#include "templateio.h"
22
#include "trayicon.h"
23
#include "ui_mainwindow.h"
24
#include "usersdialog.h"
25
#include "util.h"
26
#include <QApplication>
27
#include <QCloseEvent>
28
#include <QDesktopServices>
29
#include <QDialog>
30
#include <QDirIterator>
31
#include <QDockWidget>
32
#include <QFileInfo>
33
#include <QHBoxLayout>
34
#include <QInputDialog>
35
#include <QLabel>
36
#include <QLineEdit>
37
#include <QMenu>
38
#include <QMessageBox>
39
#include <QPushButton>
40
#include <QScrollBar>
41
#include <QShortcut>
42
#include <QTextCursor>
43
#include <QTextEdit>
44
#include <QTimer>
45
#include <QToolButton>
46
#include <QTreeWidget>
47
#include <QUrl>
48
#include <utility>
49

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

65
  m_qtPass = new QtPass(this);
12✔
66

67
  // register shortcut ctrl/cmd + Q to close the main window
68
  new QShortcut(QKeySequence(Qt::CTRL | Qt::Key_Q), this, SLOT(close()));
12✔
69
  // register shortcut ctrl/cmd + C to copy the currently selected password
70
  new QShortcut(QKeySequence(QKeySequence::StandardKey::Copy), this,
24✔
71
                SLOT(copyPasswordFromTreeview()));
24✔
72

73
  model.setNameFilters(QStringList() << "*.gpg");
36✔
74
  model.setNameFilterDisables(false);
12✔
75

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

83
  QString passStore = QtPassSettings::getPassStore(Util::findPasswordStore());
12✔
84

85
  QModelIndex rootDir = model.setRootPath(passStore);
12✔
86
  model.fetchMore(rootDir);
12✔
87

88
  proxyModel.setModelAndStore(&model, passStore);
12✔
89
  selectionModel.reset(new QItemSelectionModel(&proxyModel));
12✔
90

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

107
  if (QtPassSettings::isUseMonospace()) {
12✔
108
    QFont monospace("Monospace");
×
109
    monospace.setStyleHint(QFont::Monospace);
×
110
    ui->textBrowser->setFont(monospace);
×
111
  }
×
112
  if (QtPassSettings::isNoLineWrapping()) {
12✔
113
    ui->textBrowser->setLineWrapMode(QTextBrowser::NoWrap);
×
114
  }
115
  ui->textBrowser->setOpenExternalLinks(true);
12✔
116
  ui->textBrowser->setContextMenuPolicy(Qt::CustomContextMenu);
12✔
117
  connect(ui->textBrowser, &QWidget::customContextMenuRequested, this,
12✔
118
          &MainWindow::showBrowserContextMenu);
12✔
119

120
  updateProfileBox();
12✔
121

122
  QtPassSettings::getPass()->updateEnv();
12✔
123
  clearPanelTimer.setInterval(MS_PER_SECOND *
12✔
124
                              QtPassSettings::getAutoclearPanelSeconds());
24✔
125
  clearPanelTimer.setSingleShot(true);
12✔
126
  connect(&clearPanelTimer, &QTimer::timeout, this, [this]() { clearPanel(); });
12✔
127

128
  searchTimer.setInterval(350);
12✔
129
  searchTimer.setSingleShot(true);
12✔
130

131
  connect(&searchTimer, &QTimer::timeout, this, &MainWindow::onTimeoutSearch);
12✔
132

133
  initToolBarButtons();
12✔
134
  initStatusBar();
12✔
135
  initProcessOutputPanel();
12✔
136

137
  connect(QtPassSettings::getPass(), &Pass::finishedAnyWithPid, this,
12✔
138
          [this](const QString &out, const QString &err, Enums::PROCESS pid) {
24✔
139
            // Never route potentially-secret output through the panel:
140
            // - PASS_SHOW / PASS_OTP_GENERATE go via dedicated signals to
141
            //   the main text browser (which clears on a timer).
142
            // - PASS_GREP returns lines from password files; #252 must
143
            //   not leak those into a long-lived panel.
144
            // - PASS_INSERT's stdin is the password; stdout normally
145
            //   carries gpg/git progress only, but exclude defensively
146
            //   in case a future code path uses --echo or similar.
147
            if (isSensitiveProcess(pid)) {
×
148
              return;
149
            }
150
            if (!out.isEmpty()) {
×
151
              onProcessOutput(out, false, pid);
×
152
            }
153
            if (!err.isEmpty()) {
×
154
              onProcessOutput(err, true, pid);
×
155
            }
156
          });
157

158
  ui->lineEdit->setClearButtonEnabled(true);
12✔
159
  updateGrepButtonVisibility();
12✔
160

161
  setUiElementsEnabled(true);
12✔
162

163
  ui->lineEdit->setText(searchText);
12✔
164

165
  if (!m_qtPass->init()) {
12✔
166
    // no working config so this should just quit
167
    QApplication::quit();
×
168
    return;
169
  }
170

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

180
MainWindow::~MainWindow() { delete m_qtPass; }
36✔
181

182
/**
183
 * @brief MainWindow::focusInput selects any text (if applicable) in the search
184
 * box and sets focus to it. Allows for easy searching, called at application
185
 * start and when receiving empty message in MainWindow::messageAvailable when
186
 * compiled with SINGLE_APP=1 (default).
187
 */
188
void MainWindow::focusInput() {
×
189
  // Resolve the QLineEdit through the live widget tree rather than the
190
  // cached `ui->lineEdit` pointer.
191
  //
192
  // On a fresh-config first launch the constructor calls
193
  // `m_qtPass->init()` → `MainWindow::config()`, and `config()`'s
194
  // `applyWindowFlagsSettings()` does `setWindowFlags(...)` + `show()`
195
  // on the main window. `setWindowFlags` on a top-level widget rebuilds
196
  // the native window via `setParent(nullptr, flags)`; under Qt 6.11
197
  // we observed the QLineEdit attached to the centralWidget gets
198
  // destroyed in that rebuild while `ui->lineEdit` still holds its old
199
  // address — leading to a SIGSEGV inside `QWidget::testAttribute`
200
  // (called from `QLineEdit::isVisible` / `selectAll`). `findChild<>()`
201
  // walks the current hierarchy and returns null cleanly when the
202
  // widget is gone, so `focusInput` becomes a safe no-op instead of a
203
  // use-after-free.
204
  if (!isVisible()) {
×
205
    return;
206
  }
207
  auto *lineEdit = findChild<QLineEdit *>(QStringLiteral("lineEdit"));
×
208
  if (lineEdit == nullptr || !lineEdit->isVisible()) {
×
209
    return;
210
  }
211
  lineEdit->selectAll();
×
212
  lineEdit->setFocus();
×
213
  // Only mark the first-show focus pulse as done once it's actually
214
  // landed; setting it eagerly in showEvent() would consume the
215
  // one-shot if focusInput returned early (mid-rebuild widget state)
216
  // and we'd never retry.
217
  m_initialShowDone = true;
×
218
}
219

220
/**
221
 * @brief MainWindow::changeEvent sets focus to the search box
222
 * @param event
223
 */
224
void MainWindow::changeEvent(QEvent *event) {
12✔
225
  QWidget::changeEvent(event);
12✔
226
  if (event->type() == QEvent::ActivationChange && isActiveWindow() &&
12✔
227
      isVisible()) {
228
    // Defer one event-loop tick so the synchronous activation dispatch
229
    // chain (`QApplicationPrivate::setActiveWindow` → `notify_helper`)
230
    // unwinds before we touch widget state — calling `focusInput()`
231
    // inline from this stack has segfaulted in past iterations because
232
    // mid-rebuild ui state isn't fully wired up yet.
233
    QMetaObject::invokeMethod(this, &MainWindow::focusInput,
×
234
                              Qt::QueuedConnection);
235
  }
236
}
12✔
237

238
/**
239
 * @brief First-show hook: run the initial focusInput() pulse once the
240
 *        window is actually mapped. The widget's internal data is fully
241
 *        initialised by this point, so QLineEdit::selectAll() is safe.
242
 * @param event Show event passed to the base class.
243
 */
244
void MainWindow::showEvent(QShowEvent *event) {
×
245
  QMainWindow::showEvent(event);
×
246
  if (m_initialShowDone) {
×
247
    return;
248
  }
249
  // Queue the focus pulse for the next event-loop tick so the platform
250
  // map round-trip and any pending widget rebuilds (e.g. setWindowFlags
251
  // from the config wizard path) settle before we look up the line
252
  // edit. The `m_initialShowDone` latch is set inside focusInput()
253
  // *after* it actually focuses, so a transient failed lookup just
254
  // re-queues on the next show rather than silently dropping.
255
  QMetaObject::invokeMethod(this, &MainWindow::focusInput,
×
256
                            Qt::QueuedConnection);
257
}
258

259
/**
260
 * @brief MainWindow::initToolBarButtons init main ToolBar and connect actions
261
 */
262
void MainWindow::initToolBarButtons() {
12✔
263
  connect(ui->actionAddPassword, &QAction::triggered, this,
12✔
264
          &MainWindow::addPassword);
12✔
265
  connect(ui->actionAddFolder, &QAction::triggered, this,
12✔
266
          &MainWindow::addFolder);
12✔
267
  connect(ui->actionEdit, &QAction::triggered, this, &MainWindow::onEdit);
12✔
268
  connect(ui->actionDelete, &QAction::triggered, this, &MainWindow::onDelete);
12✔
269
  connect(ui->actionPush, &QAction::triggered, this, &MainWindow::onPush);
12✔
270
  connect(ui->actionUpdate, &QAction::triggered, this, &MainWindow::onUpdate);
12✔
271
  connect(ui->actionUsers, &QAction::triggered, this, &MainWindow::onUsers);
12✔
272
  connect(ui->actionConfig, &QAction::triggered, this, &MainWindow::onConfig);
12✔
273
  connect(ui->actionOtp, &QAction::triggered, this, &MainWindow::onOtp);
12✔
274

275
  ui->actionAddPassword->setIcon(
12✔
276
      QIcon::fromTheme("document-new", QIcon(":/icons/document-new.svg")));
48✔
277
  ui->actionAddFolder->setIcon(
12✔
278
      QIcon::fromTheme("folder-new", QIcon(":/icons/folder-new.svg")));
48✔
279
  ui->actionEdit->setIcon(QIcon::fromTheme(
12✔
280
      "document-properties", QIcon(":/icons/document-properties.svg")));
36✔
281
  ui->actionDelete->setIcon(
12✔
282
      QIcon::fromTheme("edit-delete", QIcon(":/icons/edit-delete.svg")));
48✔
283
  ui->actionPush->setIcon(
12✔
284
      QIcon::fromTheme("go-up", QIcon(":/icons/go-top.svg")));
48✔
285
  ui->actionUpdate->setIcon(
12✔
286
      QIcon::fromTheme("go-down", QIcon(":/icons/go-bottom.svg")));
48✔
287
  ui->actionUsers->setIcon(QIcon::fromTheme(
12✔
288
      "x-office-address-book", QIcon(":/icons/x-office-address-book.svg")));
36✔
289
  ui->actionConfig->setIcon(QIcon::fromTheme(
12✔
290
      "applications-system", QIcon(":/icons/applications-system.svg")));
24✔
291
}
12✔
292

293
/**
294
 * @brief MainWindow::initStatusBar init statusBar with default message and logo
295
 */
296
void MainWindow::initStatusBar() {
12✔
297
  ui->statusBar->showMessage(tr("Welcome to QtPass %1").arg(VERSION), 2000);
24✔
298

299
  QPixmap logo = QPixmap::fromImage(QImage(":/artwork/icon.svg"))
24✔
300
                     .scaledToHeight(statusBar()->height());
12✔
301
  auto *logoApp = new QLabel(statusBar());
12✔
302
  logoApp->setPixmap(logo);
12✔
303
  statusBar()->addPermanentWidget(logoApp);
12✔
304
}
12✔
305

306
/**
307
 * @brief Build the process-output panel as a bottom QDockWidget.
308
 *
309
 * The panel is constructed programmatically rather than declared in
310
 * mainwindow.ui: uic only places QMainWindow's top-level children into
311
 * the centralWidget / statusBar / menuBar / toolBars / dock-widget
312
 * slots, and the previous home (statusBar()->addPermanentWidget()) made
313
 * an 80–150 px tall QTextEdit sit inside what is otherwise a thin
314
 * status row. A QDockWidget at the bottom dock area is the conventional
315
 * place for an IDE-style output console, and it gives users
316
 * detach/move for free.
317
 */
318
void MainWindow::initProcessOutputPanel() {
12✔
319
  m_processOutputWidget = new QWidget;
12✔
320
  m_processOutputWidget->setObjectName(QStringLiteral("processOutputWidget"));
24✔
321
  auto *outputLayout = new QHBoxLayout(m_processOutputWidget);
12✔
322
  outputLayout->setObjectName(QStringLiteral("processOutputLayout"));
24✔
323
  outputLayout->setContentsMargins(0, 0, 0, 0);
12✔
324
  m_clearOutputButton = new QToolButton(m_processOutputWidget);
12✔
325
  m_clearOutputButton->setObjectName(QStringLiteral("clearOutputButton"));
24✔
326
  m_clearOutputButton->setText(tr("Clear"));
12✔
327
  m_clearOutputButton->setToolTip(tr("Clear output"));
12✔
328
  outputLayout->addWidget(m_clearOutputButton);
12✔
329
  m_processOutputEdit = new QTextEdit(m_processOutputWidget);
12✔
330
  m_processOutputEdit->setObjectName(QStringLiteral("processOutputEdit"));
24✔
331
  m_processOutputEdit->setReadOnly(true);
12✔
332
  m_processOutputEdit->setAcceptRichText(false);
12✔
333
  outputLayout->addWidget(m_processOutputEdit);
12✔
334

335
  m_processOutputDock = new QDockWidget(tr("Process Output"), this);
12✔
336
  m_processOutputDock->setObjectName(QStringLiteral("processOutputDock"));
24✔
337
  m_processOutputDock->setFeatures(QDockWidget::DockWidgetMovable |
12✔
338
                                   QDockWidget::DockWidgetFloatable);
339
  m_processOutputDock->setAllowedAreas(Qt::BottomDockWidgetArea |
12✔
340
                                       Qt::TopDockWidgetArea);
341
  m_processOutputDock->setWidget(m_processOutputWidget);
12✔
342
  addDockWidget(Qt::BottomDockWidgetArea, m_processOutputDock);
12✔
343
  // setVisible after addDockWidget so our explicit preference wins
344
  // even if QMainWindow applies any cached state when the dock is
345
  // attached. restoreWindow() runs before this method (it's called
346
  // from the QtPass ctor, which is constructed at the top of the
347
  // MainWindow ctor), so the saved layout has already been processed
348
  // by the time we get here.
349
  m_processOutputDock->setVisible(QtPassSettings::isShowProcessOutput());
12✔
350

351
  connect(m_clearOutputButton, &QToolButton::clicked, this,
12✔
352
          &MainWindow::on_clearOutputButton_clicked);
12✔
353

354
  // Hysteresis: while the user is actively dragging the slider, don't
355
  // touch m_autoScroll on every tick — a brief overshoot at maximum
356
  // would silently re-arm auto-scroll without an explicit release. Only
357
  // commit on slider release. Wheel/keyboard scroll never sets
358
  // isSliderDown(), so they still update immediately.
359
  connect(m_processOutputEdit->verticalScrollBar(), &QScrollBar::valueChanged,
12✔
360
          this, [this]() {
12✔
361
            auto *sb = m_processOutputEdit->verticalScrollBar();
×
362
            if (sb->isSliderDown())
×
363
              return;
364
            m_autoScroll = sb->value() >= sb->maximum();
×
365
          });
366
  connect(m_processOutputEdit->verticalScrollBar(), &QScrollBar::sliderReleased,
12✔
367
          this, [this]() {
12✔
368
            auto *sb = m_processOutputEdit->verticalScrollBar();
×
369
            m_autoScroll = sb->value() >= sb->maximum();
×
370
          });
×
371
}
12✔
372

373
auto MainWindow::getCurrentTreeViewIndex() -> QModelIndex {
×
374
  return ui->treeView->currentIndex();
×
375
}
376

377
void MainWindow::cleanKeygenDialog() {
1✔
378
  if (m_keygenDialog != nullptr) {
1✔
379
    m_keygenDialog->close();
×
380
  }
381
  m_keygenDialog = nullptr;
1✔
382
}
1✔
383

384
/**
385
 * @brief Displays the given text in the main window text browser, optionally
386
 * marking it as an error and/or rendering it as HTML.
387
 * @example
388
 * MainWindow window;
389
 * window.flashText("Operation completed.", false, false);
390
 *
391
 * @param const QString &text - The text content to display.
392
 * @param const bool isError - If true, sets the text color to red before
393
 * displaying the text.
394
 * @param const bool isHtml - If true, treats the text as HTML and appends it to
395
 * the existing HTML content.
396
 * @return void - No return value.
397
 */
398
void MainWindow::flashText(const QString &text, const bool isError,
3✔
399
                           const bool isHtml) {
400
  if (isError) {
3✔
401
    ui->textBrowser->setTextColor(Qt::red);
1✔
402
  }
403

404
  if (isHtml) {
3✔
405
    QString _text = text;
406
    if (!ui->textBrowser->toPlainText().isEmpty()) {
2✔
407
      _text = ui->textBrowser->toHtml() + _text;
2✔
408
    }
409
    ui->textBrowser->setHtml(_text);
1✔
410
  } else {
411
    ui->textBrowser->setText(text);
2✔
412
  }
413
}
3✔
414

415
/**
416
 * @brief MainWindow::config pops up the configuration screen and handles all
417
 * inter-window communication
418
 */
419
void MainWindow::applyTextBrowserSettings() {
×
420
  if (QtPassSettings::isUseMonospace()) {
×
421
    QFont monospace("Monospace");
×
422
    monospace.setStyleHint(QFont::Monospace);
×
423
    ui->textBrowser->setFont(monospace);
×
424
  } else {
×
425
    ui->textBrowser->setFont(QFont());
×
426
  }
427

428
  if (QtPassSettings::isNoLineWrapping()) {
×
429
    ui->textBrowser->setLineWrapMode(QTextBrowser::NoWrap);
×
430
  } else {
431
    ui->textBrowser->setLineWrapMode(QTextBrowser::WidgetWidth);
×
432
  }
433
}
×
434

435
void MainWindow::applyWindowFlagsSettings() {
×
436
  if (QtPassSettings::isAlwaysOnTop()) {
×
437
    Qt::WindowFlags flags = windowFlags();
438
    this->setWindowFlags(flags | Qt::WindowStaysOnTopHint);
×
439
  } else {
440
    this->setWindowFlags(Qt::Window);
×
441
  }
442
  this->show();
×
443
}
×
444

445
/**
446
 * @brief Opens and processes the application configuration dialog, then applies
447
 * any accepted settings.
448
 * @example
449
 * config();
450
 *
451
 * @return void - This function does not return a value.
452
 */
453
void MainWindow::config() {
×
454
  QScopedPointer<ConfigDialog> d(new ConfigDialog(this));
×
455
  d->setModal(true);
×
456
  // Automatically default to pass if it's available
457
  if (m_qtPass->isFreshStart() &&
×
458
      QFile(QtPassSettings::getPassExecutable()).exists()) {
×
459
    QtPassSettings::setUsePass(true);
×
460
  }
461

462
  if (m_qtPass->isFreshStart()) {
×
463
    d->wizard(); // run initial setup wizard for first-time configuration
×
464
  }
465
  if (d->exec()) {
×
466
    if (d->result() == QDialog::Accepted) {
×
467
      applyTextBrowserSettings();
×
468
      applyWindowFlagsSettings();
×
469

470
      updateProfileBox();
×
471
      const QString passStore = QtPassSettings::getPassStore();
×
472
      proxyModel.setStore(passStore);
×
473
      ui->treeView->setRootIndex(
×
474
          proxyModel.mapFromSource(model.setRootPath(passStore)));
×
475
      deselect();
×
476
      ui->treeView->setCurrentIndex(QModelIndex());
×
477

478
      if (m_qtPass->isFreshStart() && !Util::configIsValid()) {
×
479
        config();
×
480
      }
481
      QtPassSettings::getPass()->updateEnv();
×
482
      clearPanelTimer.setInterval(MS_PER_SECOND *
×
483
                                  QtPassSettings::getAutoclearPanelSeconds());
×
484
      m_qtPass->setClipboardTimer();
×
485

486
      updateGitButtonVisibility();
×
487
      updateOtpButtonVisibility();
×
488
      updateGrepButtonVisibility();
×
489
      updateProcessOutputVisibility();
×
490
      if (QtPassSettings::isUseTrayIcon() && m_tray == nullptr) {
×
491
        initTrayIcon();
×
492
      } else if (!QtPassSettings::isUseTrayIcon() && m_tray != nullptr) {
×
493
        destroyTrayIcon();
×
494
      }
495
    }
496

497
    m_qtPass->setFreshStart(false);
×
498
  }
499
}
×
500

501
/**
502
 * @brief MainWindow::onUpdate do a git pull
503
 */
504
void MainWindow::onUpdate(bool block) {
×
505
  ui->statusBar->showMessage(tr("Updating password-store"), 2000);
×
506
  if (block) {
×
507
    QtPassSettings::getPass()->GitPull_b();
×
508
  } else {
509
    QtPassSettings::getPass()->GitPull();
×
510
  }
511
}
×
512

513
/**
514
 * @brief MainWindow::onPush do a git push
515
 */
516
void MainWindow::onPush() {
×
517
  if (QtPassSettings::isUseGit()) {
×
518
    ui->statusBar->showMessage(tr("Updating password-store"), 2000);
×
519
    QtPassSettings::getPass()->GitPush();
×
520
  }
521
}
×
522

523
/**
524
 * @brief MainWindow::getFile get the selected file path
525
 * @param index
526
 * @param forPass returns relative path without '.gpg' extension
527
 * @return path
528
 * @return
529
 */
530
auto MainWindow::getFile(const QModelIndex &index, bool forPass) -> QString {
×
531
  if (!index.isValid() ||
×
532
      !model.fileInfo(proxyModel.mapToSource(index)).isFile()) {
×
533
    return {};
534
  }
535
  QString filePath = model.filePath(proxyModel.mapToSource(index));
×
536
  if (forPass) {
×
537
    filePath = QDir(QtPassSettings::getPassStore()).relativeFilePath(filePath);
×
538
    filePath.replace(Util::endsWithGpg(), "");
×
539
  }
540
  return filePath;
541
}
542

543
/**
544
 * @brief MainWindow::on_treeView_clicked read the selected password file
545
 * @param index
546
 */
547
void MainWindow::on_treeView_clicked(const QModelIndex &index) {
×
548
  bool cleared = ui->treeView->currentIndex().flags() == Qt::NoItemFlags;
×
549
  m_currentDir =
550
      Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel);
×
551
  // Clear any previously cached clipped text before showing new password
552
  m_qtPass->clearClippedText();
×
553
  QString file = getFile(index, true);
×
554
  ui->passwordName->setText(file);
×
555
  if (!file.isEmpty() && !cleared) {
×
556
    QtPassSettings::getPass()->Show(file);
×
557
  } else {
558
    clearPanel(false);
×
559
    ui->actionEdit->setEnabled(false);
×
560
    ui->actionDelete->setEnabled(true);
×
561
  }
562
}
×
563

564
/**
565
 * @brief MainWindow::on_treeView_doubleClicked when doubleclicked on
566
 * TreeViewItem, open the edit Window
567
 * @param index
568
 */
569
void MainWindow::on_treeView_doubleClicked(const QModelIndex &index) {
×
570
  QFileInfo fileOrFolder =
571
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
572

573
  if (fileOrFolder.isFile()) {
×
574
    editPassword(getFile(index, true));
×
575
  }
576
}
×
577

578
/**
579
 * @brief MainWindow::deselect clear the selection, password and copy buffer
580
 */
581
void MainWindow::deselect() {
1✔
582
  m_currentDir = "";
1✔
583
  m_qtPass->clearClipboard();
1✔
584
  ui->treeView->clearSelection();
1✔
585
  ui->actionEdit->setEnabled(false);
1✔
586
  ui->actionDelete->setEnabled(false);
1✔
587
  ui->passwordName->setText("");
1✔
588
  clearPanel(false);
1✔
589
}
1✔
590

591
void MainWindow::executeWrapperStarted() {
×
592
  clearTemplateWidgets();
×
593
  ui->textBrowser->clear();
×
594
  setUiElementsEnabled(false);
×
595
  clearPanelTimer.stop();
×
596
  if (QtPassSettings::isShowProcessOutput()) {
×
597
    m_processOutputDock->setVisible(true);
×
598
  }
599
}
×
600

601
/**
602
 * @brief Handles displaying parsed password entry content in the main window.
603
 * @example
604
 * void result = MainWindow::passShowHandler(p_output);
605
 * // Updates the UI with parsed fields and emits
606
 * passShowHandlerFinished(output)
607
 *
608
 * @param p_output - The raw output text containing the password entry data.
609
 * @return void - This function does not return a value.
610
 */
611
void MainWindow::passShowHandler(const QString &p_output) {
×
612
  QStringList templ = QtPassSettings::isUseTemplate()
×
613
                          ? QtPassSettings::getPassTemplate().split("\n")
×
614
                          : QStringList();
×
615
  bool allFields =
616
      QtPassSettings::isUseTemplate() && QtPassSettings::isTemplateAllFields();
×
617
  FileContent fileContent = FileContent::parse(p_output, templ, allFields);
×
618
  QString output = p_output;
619
  QString password = fileContent.getPassword();
×
620

621
  // set clipped text
622
  m_qtPass->setClippedText(password, p_output);
×
623

624
  // first clear the current view:
625
  clearTemplateWidgets();
×
626

627
  // show what is needed:
628
  if (QtPassSettings::isHideContent()) {
×
629
    output = "***" + tr("Content hidden") + "***";
×
630
  } else if (!QtPassSettings::isDisplayAsIs()) {
×
631
    if (!password.isEmpty()) {
×
632
      // set the password, it is hidden if needed in addToGridLayout
633
      addToGridLayout(0, tr("Password"), password);
×
634
    }
635

636
    NamedValues namedValues = fileContent.getNamedValues();
×
637
    for (int j = 0; j < namedValues.length(); ++j) {
×
638
      const NamedValue &nv = namedValues.at(j);
639
      addToGridLayout(j + 1, nv.name, nv.value);
×
640
    }
641
    if (ui->gridLayout->count() == 0) {
×
642
      ui->verticalLayoutPassword->setSpacing(0);
×
643
    } else {
644
      ui->verticalLayoutPassword->setSpacing(6);
×
645
    }
646

647
    output = fileContent.getRemainingDataForDisplay();
×
648
  }
649

650
  if (QtPassSettings::isUseAutoclearPanel()) {
×
651
    clearPanelTimer.start();
×
652
  }
653

654
  emit passShowHandlerFinished(output);
×
655
  setUiElementsEnabled(true);
×
656
}
×
657

658
/**
659
 * @brief Handles the OTP output by displaying it, copying it to the clipboard,
660
 * and updating the UI state.
661
 * @example
662
 * void MainWindow::passOtpHandler(const QString &p_output);
663
 *
664
 * @param const QString &p_output - The OTP code text to process; if empty, an
665
 * error message is shown instead.
666
 * @return void - This function does not return a value.
667
 */
668
void MainWindow::passOtpHandler(const QString &p_output) {
×
669
  if (!p_output.isEmpty()) {
×
670
    addToGridLayout(ui->gridLayout->count() + 1, tr("OTP Code"), p_output);
×
671
    m_qtPass->copyTextToClipboard(p_output);
×
672
    showStatusMessage(tr("OTP code copied to clipboard"));
×
673
  } else {
674
    flashText(tr("No OTP code found in this password entry"), true);
×
675
  }
676
  if (QtPassSettings::isUseAutoclearPanel()) {
×
677
    clearPanelTimer.start();
×
678
  }
679
  setUiElementsEnabled(true);
×
680
}
×
681

682
/**
683
 * @brief MainWindow::clearPanel hide the information from shoulder surfers
684
 */
685
void MainWindow::clearPanel(bool notify) {
1✔
686
  while (ui->gridLayout->count() > 0) {
1✔
687
    QLayoutItem *item = ui->gridLayout->takeAt(0);
×
688
    delete item->widget();
×
689
    delete item;
×
690
  }
691
  const bool grepWasVisible = ui->grepResultsList->isVisible();
1✔
692
  ui->grepResultsList->clear();
1✔
693
  if (grepWasVisible) {
1✔
694
    ui->grepResultsList->setVisible(false);
×
695
    ui->treeView->setVisible(true);
×
696
    if (m_grepMode) {
×
697
      m_grepMode = false;
×
698
      ui->grepButton->blockSignals(true);
×
699
      ui->grepButton->setChecked(false);
×
700
      ui->grepButton->blockSignals(false);
×
701
      ui->lineEdit->blockSignals(true);
×
702
      ui->lineEdit->clear();
×
703
      ui->lineEdit->blockSignals(false);
×
704
      ui->lineEdit->setPlaceholderText(tr("Search Password"));
×
705
    }
706
  }
707
  if (notify) {
1✔
708
    QString output = "***" + tr("Password and Content hidden") + "***";
×
709
    ui->textBrowser->setHtml(output);
×
710
  } else {
711
    ui->textBrowser->setHtml("");
2✔
712
  }
713
}
1✔
714

715
/**
716
 * @brief MainWindow::setUiElementsEnabled enable or disable the relevant UI
717
 * elements
718
 * @param state
719
 */
720
void MainWindow::setUiElementsEnabled(bool state) {
15✔
721
  ui->treeView->setEnabled(state);
15✔
722
  ui->lineEdit->setEnabled(state);
15✔
723
  ui->lineEdit->installEventFilter(this);
15✔
724
  ui->actionAddPassword->setEnabled(state);
15✔
725
  ui->actionAddFolder->setEnabled(state);
15✔
726
  ui->actionUsers->setEnabled(state);
15✔
727
  ui->actionConfig->setEnabled(state);
15✔
728
  // is a file selected?
729
  state &= ui->treeView->currentIndex().isValid();
30✔
730
  ui->actionDelete->setEnabled(state);
15✔
731
  ui->actionEdit->setEnabled(state);
15✔
732
  updateGitButtonVisibility();
15✔
733
  updateOtpButtonVisibility();
15✔
734
}
15✔
735

736
/**
737
 * @brief Restores the main window geometry, state, position, size, and
738
 * tray/icon settings from saved application settings.
739
 * @example
740
 * MainWindow window;
741
 * window.restoreWindow();
742
 *
743
 * @return void - This function does not return a value.
744
 */
745
void MainWindow::restoreWindow() {
12✔
746
  QByteArray geometry = QtPassSettings::getGeometry(saveGeometry());
12✔
747
  restoreGeometry(geometry);
12✔
748
  QByteArray savestate = QtPassSettings::getSavestate(saveState());
12✔
749
  restoreState(savestate);
12✔
750
  QPoint position = QtPassSettings::getPos(pos());
12✔
751
  move(position);
12✔
752
  QSize newSize = QtPassSettings::getSize(size());
12✔
753
  resize(newSize);
12✔
754
  if (QtPassSettings::isMaximized(isMaximized())) {
12✔
755
    showMaximized();
×
756
  }
757

758
  if (QtPassSettings::isAlwaysOnTop()) {
12✔
759
    Qt::WindowFlags flags = windowFlags();
760
    setWindowFlags(flags | Qt::WindowStaysOnTopHint);
×
761
    show();
×
762
  }
763

764
  if (QtPassSettings::isUseTrayIcon() && m_tray == nullptr) {
24✔
765
    initTrayIcon();
×
766
    if (QtPassSettings::isStartMinimized()) {
×
767
      // since we are still in constructor, can't directly hide
768
      QTimer::singleShot(10, this, SLOT(hide()));
×
769
    }
770
  } else if (!QtPassSettings::isUseTrayIcon() && m_tray != nullptr) {
24✔
771
    destroyTrayIcon();
×
772
  }
773
}
12✔
774

775
/**
776
 * @brief MainWindow::on_configButton_clicked run Mainwindow::config
777
 */
778
void MainWindow::onConfig() { config(); }
×
779

780
/**
781
 * @brief Executes when the string in the search box changes, collapses the
782
 * TreeView
783
 * @param arg1
784
 */
785
void MainWindow::on_lineEdit_textChanged(const QString &arg1) {
×
786
  if (m_grepMode)
×
787
    return;
788
  ui->statusBar->showMessage(tr("Looking for: %1").arg(arg1), 1000);
×
789
  ui->treeView->expandAll();
×
790
  clearPanel(false);
×
791
  ui->passwordName->setText("");
×
792
  ui->actionEdit->setEnabled(false);
×
793
  ui->actionDelete->setEnabled(false);
×
794
  searchTimer.start();
×
795
}
796

797
/**
798
 * @brief MainWindow::onTimeoutSearch Fired when search is finished or too much
799
 * time from two keypresses is elapsed
800
 */
801
void MainWindow::onTimeoutSearch() {
×
802
  QString query = ui->lineEdit->text();
×
803

804
  if (query.isEmpty()) {
×
805
    ui->treeView->collapseAll();
×
806
    deselect();
×
807
  }
808

809
  query.replace(QStringLiteral(" "), ".*");
×
810
  QRegularExpression regExp(query, QRegularExpression::CaseInsensitiveOption);
×
811
  proxyModel.setFilterRegularExpression(regExp);
×
812
  ui->treeView->setRootIndex(proxyModel.mapFromSource(
×
813
      model.setRootPath(QtPassSettings::getPassStore())));
×
814

815
  if (proxyModel.rowCount() > 0 && !query.isEmpty()) {
×
816
    selectFirstFile();
×
817
  } else {
818
    ui->actionEdit->setEnabled(false);
×
819
    ui->actionDelete->setEnabled(false);
×
820
  }
821
}
×
822

823
/**
824
 * @brief MainWindow::on_lineEdit_returnPressed get searching
825
 *
826
 * Select the first possible file in the tree
827
 */
828
void MainWindow::on_lineEdit_returnPressed() {
×
829
#ifdef QT_DEBUG
830
  dbg() << "on_lineEdit_returnPressed" << proxyModel.rowCount();
831
#endif
832

833
  if (m_grepMode) {
×
834
    const QString query = ui->lineEdit->text();
×
835
    if (!query.isEmpty()) {
×
836
      m_grepCancelled = false;
×
837
      ui->grepResultsList->clear();
×
838
      ui->statusBar->showMessage(tr("Searching…"));
×
839
      if (!m_grepBusy) {
×
840
        m_grepBusy = true;
×
841
        QApplication::setOverrideCursor(Qt::WaitCursor);
×
842
      }
843
      QtPassSettings::getPass()->Grep(query, ui->grepCaseButton->isChecked());
×
844
    } else {
845
      m_grepCancelled = true;
×
846
      if (m_grepBusy) {
×
847
        m_grepBusy = false;
×
848
        QApplication::restoreOverrideCursor();
×
849
      }
850
      ui->grepResultsList->clear();
×
851
      ui->grepResultsList->setVisible(false);
×
852
      ui->treeView->setVisible(true);
×
853
    }
854
    return;
855
  }
856

857
  if (proxyModel.rowCount() > 0) {
×
858
    selectFirstFile();
×
859
    on_treeView_clicked(ui->treeView->currentIndex());
×
860
  }
861
}
862

863
/**
864
 * @brief Toggle grep (content search) mode.
865
 */
866
void MainWindow::on_grepButton_toggled(bool checked) {
×
867
  m_grepMode = checked;
×
868
  if (checked) {
×
869
    ui->lineEdit->setPlaceholderText(tr("Search content (regex)"));
×
870
    // The regex dialect depends on the backend (see Pass::Grep): the pass
871
    // backend uses POSIX BRE via `pass grep`, the native backend uses PCRE.
872
    ui->lineEdit->setToolTip(
×
873
        QtPassSettings::isUsePass()
×
874
            ? tr("Content search uses POSIX basic regular expressions "
×
875
                 "(pass grep).")
876
            : tr("Content search uses Perl-compatible regular expressions "
877
                 "(PCRE)."));
878
    ui->lineEdit->clear();
×
879
    searchTimer.stop();
×
880
    proxyModel.setFilterRegularExpression(QRegularExpression());
×
881
    ui->treeView->setRootIndex(proxyModel.mapFromSource(
×
UNCOV
882
        model.setRootPath(QtPassSettings::getPassStore())));
×
883
    ui->grepResultsList->setVisible(false);
×
884
    // Keep treeView visible until results arrive
885
  } else {
886
    if (m_grepBusy) {
×
887
      m_grepBusy = false;
×
888
      m_grepCancelled = true;
×
889
      QApplication::restoreOverrideCursor();
×
890
    }
891
    searchTimer.stop();
×
892
    ui->lineEdit->blockSignals(true);
×
893
    ui->lineEdit->clear();
×
UNCOV
894
    ui->lineEdit->blockSignals(false);
×
895
    ui->lineEdit->setPlaceholderText(tr("Search Password"));
×
UNCOV
896
    ui->lineEdit->setToolTip(QString());
×
UNCOV
897
    ui->grepResultsList->clear();
×
UNCOV
898
    ui->grepResultsList->setVisible(false);
×
UNCOV
899
    ui->treeView->setVisible(true);
×
900
    proxyModel.setFilterRegularExpression(QRegularExpression());
×
UNCOV
901
    ui->treeView->setRootIndex(proxyModel.mapFromSource(
×
902
        model.setRootPath(QtPassSettings::getPassStore())));
×
903
  }
904
}
×
905

906
/**
907
 * @brief Display grep results in grepResultsList.
908
 */
UNCOV
909
void MainWindow::onGrepFinished(
×
910
    const QList<QPair<QString, QStringList>> &results) {
911
  if (m_grepBusy) {
×
UNCOV
912
    m_grepBusy = false;
×
913
    QApplication::restoreOverrideCursor();
×
914
  }
915
  if (m_grepCancelled) {
×
916
    m_grepCancelled = false;
×
917
    return;
×
918
  }
UNCOV
919
  setUiElementsEnabled(true);
×
920
  if (!m_grepMode)
×
921
    return;
922
  ui->grepResultsList->clear();
×
923
  if (results.isEmpty()) {
×
924
    ui->statusBar->showMessage(tr("No matches found."), 3000);
×
925
    ui->grepResultsList->setVisible(false);
×
926
    ui->treeView->setVisible(true);
×
927
    return;
×
928
  }
UNCOV
929
  const bool hideContent = QtPassSettings::isHideContent();
×
930
  int totalLines = 0;
931
  for (const auto &pair : results) {
×
UNCOV
932
    auto *entryItem = new QTreeWidgetItem(ui->grepResultsList);
×
UNCOV
933
    entryItem->setText(0, pair.first);
×
934
    entryItem->setData(0, Qt::UserRole, pair.first);
×
935
    for (const QString &line : pair.second) {
×
936
      auto *lineItem = new QTreeWidgetItem(entryItem);
×
937
      lineItem->setText(0, hideContent ? "***" + tr("Content hidden") + "***"
×
938
                                       : line);
939
      lineItem->setData(0, Qt::UserRole, pair.first);
×
UNCOV
940
      ++totalLines;
×
941
    }
942
  }
UNCOV
943
  ui->grepResultsList->expandAll();
×
UNCOV
944
  ui->treeView->setVisible(false);
×
UNCOV
945
  ui->grepResultsList->setVisible(true);
×
UNCOV
946
  ui->statusBar->showMessage(
×
UNCOV
947
      tr("Found %n match(es)", nullptr, totalLines) + " " +
×
948
          tr("in %n entr(ies).", nullptr, static_cast<int>(results.size())),
×
949
      3000);
950
  if (QtPassSettings::isUseAutoclearPanel())
×
951
    clearPanelTimer.start();
×
952
}
953

954
/**
955
 * @brief Navigate to the password entry when a grep result is clicked.
956
 */
UNCOV
957
void MainWindow::on_grepResultsList_itemClicked(QTreeWidgetItem *item,
×
958
                                                int /*column*/) {
UNCOV
959
  const QString entry = item->data(0, Qt::UserRole).toString();
×
UNCOV
960
  if (entry.isEmpty())
×
961
    return;
962
  const QString fullPath = QDir::cleanPath(
963
      QDir(QtPassSettings::getPassStore()).filePath(entry + ".gpg"));
×
964
  QModelIndex srcIndex = model.index(fullPath);
×
965
  if (!srcIndex.isValid())
966
    return;
967
  QModelIndex proxyIndex = proxyModel.mapFromSource(srcIndex);
×
968
  if (!proxyIndex.isValid())
969
    return;
UNCOV
970
  ui->treeView->setCurrentIndex(proxyIndex);
×
UNCOV
971
  on_treeView_clicked(proxyIndex);
×
UNCOV
972
  if (QtPassSettings::isHideContent() || QtPassSettings::isUseAutoclearPanel())
×
UNCOV
973
    ui->grepResultsList->clear();
×
UNCOV
974
  ui->grepResultsList->setVisible(false);
×
975
  ui->treeView->setVisible(true);
×
976
  ui->treeView->scrollTo(proxyIndex);
×
977
  ui->treeView->setFocus();
×
978
}
979

980
/**
981
 * @brief MainWindow::selectFirstFile select the first possible file in the
982
 * tree
983
 */
UNCOV
984
void MainWindow::selectFirstFile() {
×
UNCOV
985
  QModelIndex index = proxyModel.mapFromSource(
×
UNCOV
986
      model.setRootPath(QtPassSettings::getPassStore()));
×
987
  index = firstFile(index);
×
988
  ui->treeView->setCurrentIndex(index);
×
989
}
×
990

991
/**
992
 * @brief MainWindow::firstFile return location of first possible file
993
 * @param parentIndex
994
 * @return QModelIndex
995
 */
996
auto MainWindow::firstFile(QModelIndex parentIndex) -> QModelIndex {
×
UNCOV
997
  QModelIndex index = parentIndex;
×
UNCOV
998
  int numRows = proxyModel.rowCount(parentIndex);
×
999
  for (int row = 0; row < numRows; ++row) {
×
UNCOV
1000
    index = proxyModel.index(row, 0, parentIndex);
×
UNCOV
1001
    if (model.fileInfo(proxyModel.mapToSource(index)).isFile()) {
×
UNCOV
1002
      return index;
×
1003
    }
UNCOV
1004
    if (proxyModel.hasChildren(index)) {
×
UNCOV
1005
      return firstFile(index);
×
1006
    }
1007
  }
UNCOV
1008
  return index;
×
1009
}
1010

1011
/**
1012
 * @brief MainWindow::confirmPathInStore reject paths that resolve outside
1013
 * the password store and warn the user.
1014
 *
1015
 * Used before file/folder creation, move, and rename to stop user-typed
1016
 * names like "../../etc/passwd" or absolute paths from escaping the
1017
 * configured store root via the input dialogs.
1018
 *
1019
 * @param candidate Absolute candidate path to validate.
1020
 * @return true if the path is inside the password store; false otherwise (a
1021
 * warning dialog is shown in that case).
1022
 */
UNCOV
1023
auto MainWindow::confirmPathInStore(const QString &candidate) -> bool {
×
UNCOV
1024
  if (PathValidator::isPathInStore(QtPassSettings::getPassStore(), candidate)) {
×
1025
    return true;
1026
  }
UNCOV
1027
  QMessageBox::warning(this, tr("Invalid name"),
×
UNCOV
1028
                       tr("That name would resolve outside the password "
×
1029
                          "store. Please choose a different name."));
1030
  return false;
×
1031
}
1032

1033
/**
1034
 * @brief MainWindow::setPassword open passworddialog
1035
 * @param file which pgp file
1036
 * @param isNew insert (not update)
1037
 */
UNCOV
1038
void MainWindow::setPassword(const QString &file, bool isNew) {
×
UNCOV
1039
  PasswordDialog d(file, isNew, this);
×
1040

UNCOV
1041
  if (isNew) {
×
UNCOV
1042
    QString storePath = QtPassSettings::getPassStore();
×
1043
    QString folder =
1044
        Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel);
×
1045
    if (folder.isEmpty()) {
×
1046
      folder = storePath;
×
1047
    }
1048
    QHash<QString, QStringList> templates =
UNCOV
1049
        TemplateIO::readTemplates(storePath);
×
1050
    if (!templates.isEmpty()) {
1051
      QString defaultTemplate =
UNCOV
1052
          TemplateIO::getFolderTemplate(folder, storePath);
×
1053
      d.setAvailableTemplates(templates, defaultTemplate);
×
UNCOV
1054
      new QShortcut(QKeySequence(Qt::CTRL | Qt::Key_T), &d,
×
UNCOV
1055
                    [&d]() { d.cycleTemplate(); });
×
1056
    }
UNCOV
1057
  }
×
1058

1059
  if (!d.exec()) {
×
UNCOV
1060
    ui->treeView->setFocus();
×
1061
  }
1062
}
×
1063

1064
/**
1065
 * @brief MainWindow::addPassword add a new password by showing a
1066
 * number of dialogs.
1067
 */
UNCOV
1068
void MainWindow::addPassword() {
×
1069
  bool ok;
1070
  QString dir =
UNCOV
1071
      Util::getDir(ui->treeView->currentIndex(), true, model, proxyModel);
×
1072
  QString file =
1073
      QInputDialog::getText(this, tr("New file"),
×
1074
                            tr("New password file: \n(Will be placed in %1 )")
×
UNCOV
1075
                                .arg(QtPassSettings::getPassStore() +
×
UNCOV
1076
                                     Util::getDir(ui->treeView->currentIndex(),
×
1077
                                                  true, model, proxyModel)),
UNCOV
1078
                            QLineEdit::Normal, "", &ok);
×
UNCOV
1079
  if (!ok || file.isEmpty()) {
×
1080
    return;
1081
  }
UNCOV
1082
  file = dir + file;
×
UNCOV
1083
  if (!confirmPathInStore(QtPassSettings::getPassStore() + file)) {
×
1084
    return;
1085
  }
UNCOV
1086
  setPassword(file);
×
1087
}
1088

1089
/**
1090
 * @brief MainWindow::onDelete remove password, if you are
1091
 * sure.
1092
 */
UNCOV
1093
void MainWindow::onDelete() {
×
1094
  QModelIndex currentIndex = ui->treeView->currentIndex();
×
1095
  if (!currentIndex.isValid()) {
1096
    // This fixes https://github.com/IJHack/QtPass/issues/556
1097
    // Otherwise the entire password directory would be deleted if
1098
    // nothing is selected in the tree view.
1099
    return;
×
1100
  }
1101

1102
  QFileInfo fileOrFolder =
UNCOV
1103
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
UNCOV
1104
  QString file = "";
×
1105
  bool isDir = false;
1106

1107
  if (fileOrFolder.isFile()) {
×
1108
    file = getFile(ui->treeView->currentIndex(), true);
×
1109
  } else {
1110
    file = Util::getDir(ui->treeView->currentIndex(), true, model, proxyModel);
×
1111
    isDir = true;
1112
  }
1113

1114
  QString dirMessage = tr(" and the whole content?");
1115
  if (isDir) {
×
UNCOV
1116
    QDirIterator it(model.rootPath() + QDir::separator() + file,
×
UNCOV
1117
                    QDirIterator::Subdirectories);
×
1118
    bool okDir = true;
UNCOV
1119
    while (it.hasNext() && okDir) {
×
UNCOV
1120
      it.next();
×
1121
      if (QFileInfo(it.filePath()).isFile()) {
×
UNCOV
1122
        if (QFileInfo(it.filePath()).suffix() != "gpg") {
×
1123
          okDir = false;
1124
          dirMessage = tr(" and the whole content? <br><strong>Attention: "
×
1125
                          "there are unexpected files in the given folder, "
1126
                          "check them before continue.</strong>");
1127
        }
1128
      }
1129
    }
UNCOV
1130
  }
×
1131

1132
  if (QMessageBox::question(
×
UNCOV
1133
          this, isDir ? tr("Delete folder?") : tr("Delete password?"),
×
UNCOV
1134
          tr("Are you sure you want to delete %1%2?")
×
UNCOV
1135
              .arg(QDir::separator() + file, isDir ? dirMessage : "?"),
×
1136
          QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) {
1137
    return;
1138
  }
1139

1140
  QtPassSettings::getPass()->Remove(file, isDir);
×
1141
}
×
1142

1143
/**
1144
 * @brief MainWindow::onOTP try and generate (selected) OTP code.
1145
 */
UNCOV
1146
void MainWindow::onOtp() {
×
1147
  QString file = getFile(ui->treeView->currentIndex(), true);
×
UNCOV
1148
  if (!file.isEmpty()) {
×
UNCOV
1149
    if (QtPassSettings::isUseOtp()) {
×
UNCOV
1150
      setUiElementsEnabled(false);
×
UNCOV
1151
      QtPassSettings::getPass()->OtpGenerate(file);
×
1152
    }
1153
  } else {
1154
    flashText(tr("No password selected for OTP generation"), true);
×
1155
  }
UNCOV
1156
}
×
1157

1158
/**
1159
 * @brief MainWindow::onEdit try and edit (selected) password.
1160
 */
1161
void MainWindow::onEdit() {
×
1162
  QString file = getFile(ui->treeView->currentIndex(), true);
×
1163
  editPassword(file);
×
UNCOV
1164
}
×
1165

1166
/**
1167
 * @brief MainWindow::userDialog see MainWindow::onUsers()
1168
 * @param dir folder to edit users for.
1169
 */
UNCOV
1170
void MainWindow::userDialog(const QString &dir) {
×
UNCOV
1171
  if (!dir.isEmpty()) {
×
UNCOV
1172
    m_currentDir = dir;
×
1173
  }
UNCOV
1174
  onUsers();
×
UNCOV
1175
}
×
1176

1177
/**
1178
 * @brief MainWindow::onUsers edit users for the current
1179
 * folder,
1180
 * gets lists and opens UserDialog.
1181
 */
UNCOV
1182
void MainWindow::onUsers() {
×
1183
  QString dir =
1184
      m_currentDir.isEmpty()
UNCOV
1185
          ? Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel)
×
UNCOV
1186
          : m_currentDir;
×
1187

UNCOV
1188
  UsersDialog d(dir, this);
×
1189
  if (!d.exec()) {
×
1190
    ui->treeView->setFocus();
×
1191
  }
1192
}
×
1193

1194
/**
1195
 * @brief MainWindow::messageAvailable we have some text/message/search to do.
1196
 * @param message
1197
 */
UNCOV
1198
void MainWindow::messageAvailable(const QString &message) {
×
1199
  show();
×
UNCOV
1200
  raise();
×
UNCOV
1201
  if (message.isEmpty()) {
×
UNCOV
1202
    focusInput();
×
1203
  } else {
UNCOV
1204
    ui->treeView->expandAll();
×
UNCOV
1205
    ui->lineEdit->setText(message);
×
1206
    on_lineEdit_returnPressed();
×
1207
  }
1208
}
×
1209

1210
/**
1211
 * @brief MainWindow::generateKeyPair internal gpg keypair generator . .
1212
 * @param batch
1213
 * @param keygenWindow
1214
 */
UNCOV
1215
void MainWindow::generateKeyPair(const QString &batch, QDialog *keygenWindow) {
×
UNCOV
1216
  m_keygenDialog = keygenWindow;
×
UNCOV
1217
  emit generateGPGKeyPair(batch);
×
UNCOV
1218
}
×
1219

1220
/**
1221
 * @brief MainWindow::updateProfileBox update the list of profiles, optionally
1222
 * select a more appropriate one to view too
1223
 */
1224
void MainWindow::updateProfileBox() {
12✔
1225
  QHash<QString, QHash<QString, QString>> profiles =
1226
      QtPassSettings::getProfiles();
12✔
1227

1228
  if (profiles.isEmpty()) {
UNCOV
1229
    ui->profileWidget->hide();
×
1230
  } else {
1231
    ui->profileWidget->show();
12✔
1232
    ui->profileBox->setEnabled(profiles.size() > 1);
24✔
1233
    ui->profileBox->clear();
12✔
1234
    QHashIterator<QString, QHash<QString, QString>> i(profiles);
12✔
1235
    while (i.hasNext()) {
12✔
1236
      i.next();
1237
      if (!i.key().isEmpty()) {
12✔
1238
        ui->profileBox->addItem(i.key());
12✔
1239
      }
1240
    }
1241
    ui->profileBox->model()->sort(0);
12✔
1242
  }
1243
  int index = ui->profileBox->findText(QtPassSettings::getProfile());
24✔
1244
  if (index != -1) { //  -1 for not found
12✔
UNCOV
1245
    ui->profileBox->setCurrentIndex(index);
×
1246
  }
1247
}
12✔
1248

1249
/**
1250
 * @brief MainWindow::on_profileBox_currentIndexChanged make sure we show the
1251
 * correct "profile"
1252
 * @param name
1253
 */
1254
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
1255
void MainWindow::on_profileBox_currentIndexChanged(QString name) {
1256
#else
1257
/**
1258
 * @brief Handles changes to the selected profile in the profile combo box.
1259
 * @details Ignores the event during a fresh start or when the selected profile
1260
 * matches the current profile. Otherwise, it clears the password field, updates
1261
 * the active profile and related settings, refreshes the environment, and
1262
 * resets the tree view and action states to reflect the newly selected profile.
1263
 *
1264
 * @param name - The newly selected profile name.
1265
 * @return void - This function does not return a value.
1266
 *
1267
 */
1268
void MainWindow::on_profileBox_currentTextChanged(const QString &name) {
12✔
1269
#endif
1270
  if (m_qtPass->isFreshStart() || name == QtPassSettings::getProfile()) {
12✔
1271
    return;
12✔
1272
  }
1273

UNCOV
1274
  ui->lineEdit->clear();
×
1275

UNCOV
1276
  QtPassSettings::setProfile(name);
×
1277

1278
  QtPassSettings::setPassStore(
×
1279
      QtPassSettings::getProfiles().value(name).value("path"));
×
1280
  QtPassSettings::setPassSigningKey(
×
1281
      QtPassSettings::getProfiles().value(name).value("signingKey"));
×
1282
  ui->statusBar->showMessage(tr("Profile changed to %1").arg(name), 2000);
×
1283

UNCOV
1284
  QtPassSettings::getPass()->updateEnv();
×
1285

UNCOV
1286
  const QString passStore = QtPassSettings::getPassStore();
×
UNCOV
1287
  proxyModel.setStore(passStore);
×
UNCOV
1288
  ui->treeView->setRootIndex(
×
UNCOV
1289
      proxyModel.mapFromSource(model.setRootPath(passStore)));
×
1290
  deselect();
×
1291
  ui->treeView->setCurrentIndex(QModelIndex());
×
1292
}
1293

1294
/**
1295
 * @brief MainWindow::initTrayIcon show a nice tray icon on systems that
1296
 * support
1297
 * it
1298
 */
UNCOV
1299
void MainWindow::initTrayIcon() {
×
UNCOV
1300
  m_tray = new TrayIcon(this);
×
1301
  // Setup tray icon
1302

1303
  if (m_tray == nullptr) {
1304
#ifdef QT_DEBUG
1305
    dbg() << "Allocating tray icon failed.";
1306
#endif
1307
    return;
1308
  }
1309

1310
  if (!m_tray->getIsAllocated()) {
×
1311
    destroyTrayIcon();
×
1312
  }
1313
}
1314

1315
/**
1316
 * @brief MainWindow::destroyTrayIcon remove that pesky tray icon
1317
 */
1318
void MainWindow::destroyTrayIcon() {
×
1319
  delete m_tray;
×
1320
  m_tray = nullptr;
×
UNCOV
1321
}
×
1322

1323
/**
1324
 * @brief MainWindow::closeEvent hide or quit
1325
 * @param event
1326
 */
1327
void MainWindow::closeEvent(QCloseEvent *event) {
×
1328
  if (QtPassSettings::isHideOnClose()) {
×
1329
    this->hide();
×
1330
    event->ignore();
1331
  } else {
UNCOV
1332
    m_qtPass->clearClipboard();
×
1333

1334
    QtPassSettings::setGeometry(saveGeometry());
×
UNCOV
1335
    QtPassSettings::setSavestate(saveState());
×
UNCOV
1336
    QtPassSettings::setMaximized(isMaximized());
×
UNCOV
1337
    if (!isMaximized()) {
×
UNCOV
1338
      QtPassSettings::setPos(pos());
×
UNCOV
1339
      QtPassSettings::setSize(size());
×
1340
    }
1341
    event->accept();
1342
  }
UNCOV
1343
}
×
1344

1345
/**
1346
 * @brief MainWindow::eventFilter filter out some events and focus the
1347
 * treeview
1348
 * @param obj
1349
 * @param event
1350
 * @return
1351
 */
1352
auto MainWindow::eventFilter(QObject *obj, QEvent *event) -> bool {
3✔
1353
  if (obj == ui->lineEdit && event->type() == QEvent::KeyPress) {
3✔
UNCOV
1354
    auto *key = dynamic_cast<QKeyEvent *>(event);
×
UNCOV
1355
    if (key != nullptr && key->key() == Qt::Key_Down) {
×
UNCOV
1356
      ui->treeView->setFocus();
×
1357
    }
1358
  }
1359
  return QObject::eventFilter(obj, event);
3✔
1360
}
1361

1362
/**
1363
 * @brief MainWindow::keyPressEvent did anyone press return, enter or escape?
1364
 * @param event
1365
 */
UNCOV
1366
void MainWindow::keyPressEvent(QKeyEvent *event) {
×
UNCOV
1367
  switch (event->key()) {
×
1368
  case Qt::Key_Delete:
×
1369
    onDelete();
×
1370
    break;
×
UNCOV
1371
  case Qt::Key_Return:
×
1372
  case Qt::Key_Enter:
UNCOV
1373
    if (proxyModel.rowCount() > 0) {
×
1374
      on_treeView_clicked(ui->treeView->currentIndex());
×
1375
    }
1376
    break;
UNCOV
1377
  case Qt::Key_Escape:
×
UNCOV
1378
    ui->lineEdit->clear();
×
UNCOV
1379
    break;
×
1380
  default:
1381
    break;
1382
  }
UNCOV
1383
}
×
1384

1385
/**
1386
 * @brief MainWindow::showContextMenu show us the (file or folder) context
1387
 * menu
1388
 * @param pos
1389
 */
UNCOV
1390
void MainWindow::showContextMenu(const QPoint &pos) {
×
UNCOV
1391
  QModelIndex index = ui->treeView->indexAt(pos);
×
1392
  bool selected = true;
1393
  if (!index.isValid()) {
1394
    ui->treeView->clearSelection();
×
UNCOV
1395
    ui->actionDelete->setEnabled(false);
×
UNCOV
1396
    ui->actionEdit->setEnabled(false);
×
1397
    m_currentDir = "";
×
1398
    selected = false;
1399
  }
1400

UNCOV
1401
  ui->treeView->setCurrentIndex(index);
×
1402

1403
  QPoint globalPos = ui->treeView->viewport()->mapToGlobal(pos);
×
1404

1405
  QFileInfo fileOrFolder =
1406
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
1407

1408
  QMenu contextMenu;
×
1409
  if (!selected || fileOrFolder.isDir()) {
×
1410
    QAction *openFolder =
1411
        contextMenu.addAction(tr("Open folder with file manager"));
×
1412
    QAction *addFolder = contextMenu.addAction(tr("Add folder"));
×
UNCOV
1413
    QAction *addPassword = contextMenu.addAction(tr("Add password"));
×
1414
    QAction *users = contextMenu.addAction(tr("Users"));
×
1415
    connect(openFolder, &QAction::triggered, this, &MainWindow::openFolder);
×
1416
    connect(addFolder, &QAction::triggered, this, &MainWindow::addFolder);
×
1417
    connect(addPassword, &QAction::triggered, this, &MainWindow::addPassword);
×
1418
    connect(users, &QAction::triggered, this, &MainWindow::onUsers);
×
1419
  } else if (fileOrFolder.isFile()) {
×
1420
    QAction *edit = contextMenu.addAction(tr("Edit"));
×
1421
    connect(edit, &QAction::triggered, this, &MainWindow::onEdit);
×
1422
  }
1423
  if (selected) {
×
UNCOV
1424
    contextMenu.addSeparator();
×
1425
    if (fileOrFolder.isDir()) {
×
1426
      QAction *renameFolder = contextMenu.addAction(tr("Rename folder"));
×
1427
      connect(renameFolder, &QAction::triggered, this,
×
UNCOV
1428
              &MainWindow::renameFolder);
×
1429
    } else if (fileOrFolder.isFile()) {
×
UNCOV
1430
      QAction *renamePassword = contextMenu.addAction(tr("Rename password"));
×
1431
      connect(renamePassword, &QAction::triggered, this,
×
1432
              &MainWindow::renamePassword);
×
1433
    }
1434
    QAction *deleteItem = contextMenu.addAction(tr("Delete"));
×
1435
    connect(deleteItem, &QAction::triggered, this, &MainWindow::onDelete);
×
UNCOV
1436
    if (fileOrFolder.isDir()) {
×
1437
      QString dirPath = QDir::cleanPath(
1438
          Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel));
×
1439

1440
      auto *shareMenu = new QMenu(tr("Share"), &contextMenu);
×
1441
      contextMenu.addMenu(shareMenu);
×
1442

1443
      QString gpgIdPath = Pass::getGpgIdPath(dirPath);
×
1444
      bool gpgIdExists = !gpgIdPath.isEmpty() && QFile(gpgIdPath).exists();
×
1445

1446
      QString exePath = QtPassSettings::isUsePass()
×
UNCOV
1447
                            ? QtPassSettings::getPassExecutable()
×
1448
                            : QtPassSettings::getGpgExecutable();
×
1449
      bool gpgAvailable = !exePath.isEmpty() && (exePath.startsWith("wsl ") ||
×
1450
                                                 QFile(exePath).exists());
×
1451

UNCOV
1452
      QAction *reencrypt = shareMenu->addAction(tr("Re-encrypt all passwords"));
×
UNCOV
1453
      reencrypt->setEnabled(gpgIdExists && gpgAvailable);
×
1454
      connect(reencrypt, &QAction::triggered, this,
×
1455
              [this, dirPath]() { reencryptPath(dirPath); });
×
1456

1457
      QAction *exportKey = shareMenu->addAction(tr("Export my public key..."));
×
UNCOV
1458
      exportKey->setEnabled(gpgAvailable);
×
1459
      connect(exportKey, &QAction::triggered, this,
×
1460
              &MainWindow::exportPublicKey);
×
1461

1462
      QAction *addRecipientAction =
1463
          shareMenu->addAction(tr("Add recipient..."));
×
1464
      addRecipientAction->setEnabled(gpgIdExists && gpgAvailable);
×
UNCOV
1465
      connect(addRecipientAction, &QAction::triggered, this,
×
UNCOV
1466
              [this, dirPath]() { addRecipient(dirPath); });
×
1467

UNCOV
1468
      QAction *shareHelp = shareMenu->addAction(tr("What is this?"));
×
UNCOV
1469
      connect(shareHelp, &QAction::triggered, this, &MainWindow::showShareHelp);
×
1470
    }
1471
  }
1472
  contextMenu.exec(globalPos);
×
1473
}
×
1474

1475
/**
1476
 * @brief MainWindow::showBrowserContextMenu show us the context menu in
1477
 * password window
1478
 * @param pos
1479
 */
UNCOV
1480
void MainWindow::showBrowserContextMenu(const QPoint &pos) {
×
UNCOV
1481
  QMenu *contextMenu = ui->textBrowser->createStandardContextMenu(pos);
×
1482
  QPoint globalPos = ui->textBrowser->viewport()->mapToGlobal(pos);
×
1483

1484
  contextMenu->exec(globalPos);
×
UNCOV
1485
  delete contextMenu;
×
1486
}
×
1487

1488
/**
1489
 * @brief MainWindow::openFolder open the folder in the default file manager
1490
 */
UNCOV
1491
void MainWindow::openFolder() {
×
1492
  QString dir =
1493
      Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel);
×
1494

UNCOV
1495
  QString path = QDir::toNativeSeparators(dir);
×
1496
  QDesktopServices::openUrl(QUrl::fromLocalFile(path));
×
UNCOV
1497
}
×
1498

1499
/**
1500
 * @brief MainWindow::addFolder add a new folder to store passwords in
1501
 */
UNCOV
1502
void MainWindow::addFolder() {
×
1503
  bool ok;
1504
  QString dir =
UNCOV
1505
      Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel);
×
1506
  QString newdir =
UNCOV
1507
      QInputDialog::getText(this, tr("New file"),
×
1508
                            tr("New Folder: \n(Will be placed in %1 )")
×
UNCOV
1509
                                .arg(QtPassSettings::getPassStore() +
×
UNCOV
1510
                                     Util::getDir(ui->treeView->currentIndex(),
×
1511
                                                  true, model, proxyModel)),
1512
                            QLineEdit::Normal, "", &ok);
×
1513
  if (!ok || newdir.isEmpty()) {
×
1514
    return;
1515
  }
1516
  newdir.prepend(dir);
1517
  if (!confirmPathInStore(newdir)) {
×
1518
    return;
1519
  }
1520
  if (!QDir().mkdir(newdir)) {
×
1521
    QMessageBox::warning(this, tr("Error"),
×
1522
                         tr("Failed to create folder: %1").arg(newdir));
×
UNCOV
1523
    return;
×
1524
  }
1525
  if (QtPassSettings::isAddGPGId(true)) {
×
1526
    QString gpgIdFile = newdir + "/.gpg-id";
×
1527
    QFile gpgId(gpgIdFile);
×
1528
    if (!gpgId.open(QIODevice::WriteOnly)) {
×
UNCOV
1529
      QMessageBox::warning(
×
UNCOV
1530
          this, tr("Error"),
×
1531
          tr("Failed to create .gpg-id file in: %1").arg(newdir));
×
1532
      return;
1533
    }
UNCOV
1534
    QList<UserInfo> users = QtPassSettings::getPass()->listKeys("", true);
×
1535
    for (const UserInfo &user : users) {
×
1536
      if (user.enabled) {
×
UNCOV
1537
        gpgId.write((user.key_id + "\n").toUtf8());
×
1538
      }
1539
    }
UNCOV
1540
    gpgId.close();
×
1541
    // Lock to owner-only access; see ImitatePass::writeGpgIdFile for
1542
    // rationale (NFS / USB / unusual umask scenarios). Best-effort on
1543
    // platforms where setPermissions is a no-op.
UNCOV
1544
    QFile::setPermissions(gpgIdFile, QFile::ReadOwner | QFile::WriteOwner);
×
1545
  }
×
1546
}
1547

1548
/**
1549
 * @brief MainWindow::renameFolder rename an existing folder
1550
 */
UNCOV
1551
void MainWindow::renameFolder() {
×
1552
  bool ok;
1553
  QString srcDir = QDir::cleanPath(
1554
      Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel));
×
1555
  QString srcDirName = QDir(srcDir).dirName();
×
1556
  QString newName =
UNCOV
1557
      QInputDialog::getText(this, tr("Rename file"), tr("Rename Folder To: "),
×
1558
                            QLineEdit::Normal, srcDirName, &ok);
×
UNCOV
1559
  if (!ok || newName.isEmpty()) {
×
1560
    return;
1561
  }
1562
  QString destDir = srcDir;
UNCOV
1563
  destDir.replace(srcDir.lastIndexOf(srcDirName), srcDirName.length(), newName);
×
UNCOV
1564
  if (!confirmPathInStore(destDir)) {
×
1565
    return;
1566
  }
1567
  QtPassSettings::getPass()->Move(srcDir, destDir, false);
×
1568
}
1569

1570
/**
1571
 * @brief MainWindow::editPassword read password and open edit window via
1572
 * MainWindow::onEdit()
1573
 */
UNCOV
1574
void MainWindow::editPassword(const QString &file) {
×
UNCOV
1575
  if (!file.isEmpty()) {
×
UNCOV
1576
    if (QtPassSettings::isUseGit() && QtPassSettings::isAutoPull()) {
×
1577
      onUpdate(true);
×
1578
    }
1579
    setPassword(file, false);
×
1580
  }
1581
}
×
1582

1583
/**
1584
 * @brief MainWindow::renamePassword rename an existing password
1585
 */
UNCOV
1586
void MainWindow::renamePassword() {
×
1587
  bool ok;
1588
  QString file = getFile(ui->treeView->currentIndex(), false);
×
1589
  QString filePath = QFileInfo(file).path();
×
UNCOV
1590
  QString fileName = QFileInfo(file).fileName();
×
UNCOV
1591
  if (fileName.endsWith(".gpg", Qt::CaseInsensitive)) {
×
1592
    fileName.chop(4);
×
1593
  }
1594

1595
  QString newName =
1596
      QInputDialog::getText(this, tr("Rename file"), tr("Rename File To: "),
×
UNCOV
1597
                            QLineEdit::Normal, fileName, &ok);
×
UNCOV
1598
  if (!ok || newName.isEmpty()) {
×
1599
    return;
1600
  }
UNCOV
1601
  QString newFile = QDir(filePath).filePath(newName);
×
UNCOV
1602
  if (!confirmPathInStore(newFile)) {
×
1603
    return;
1604
  }
1605
  QtPassSettings::getPass()->Move(file, newFile, false);
×
1606
}
1607

1608
/**
1609
 * @brief MainWindow::clearTemplateWidgets empty the template widget fields in
1610
 * the UI
1611
 */
UNCOV
1612
void MainWindow::clearTemplateWidgets() {
×
UNCOV
1613
  while (ui->gridLayout->count() > 0) {
×
UNCOV
1614
    QLayoutItem *item = ui->gridLayout->takeAt(0);
×
UNCOV
1615
    delete item->widget();
×
UNCOV
1616
    delete item;
×
1617
  }
UNCOV
1618
  ui->verticalLayoutPassword->setSpacing(0);
×
UNCOV
1619
}
×
1620

1621
/**
1622
 * @brief Copies the password of the selected file from the tree view to the
1623
 * clipboard.
1624
 * @example
1625
 * MainWindow::copyPasswordFromTreeview();
1626
 *
1627
 * @return void - This function does not return a value.
1628
 */
1629
void MainWindow::copyPasswordFromTreeview() {
×
1630
  QFileInfo fileOrFolder =
1631
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
1632

1633
  if (fileOrFolder.isFile()) {
×
UNCOV
1634
    QString file = getFile(ui->treeView->currentIndex(), true);
×
1635
    // Disconnect any previous connection to avoid accumulation
1636
    disconnect(QtPassSettings::getPass(), &Pass::finishedShow, this,
×
1637
               &MainWindow::passwordFromFileToClipboard);
1638
    connect(QtPassSettings::getPass(), &Pass::finishedShow, this,
×
UNCOV
1639
            &MainWindow::passwordFromFileToClipboard);
×
UNCOV
1640
    QtPassSettings::getPass()->Show(file);
×
1641
  }
UNCOV
1642
}
×
1643

UNCOV
1644
void MainWindow::passwordFromFileToClipboard(const QString &text) {
×
UNCOV
1645
  QStringList tokens = text.split('\n');
×
1646
  m_qtPass->copyTextToClipboard(tokens[0]);
×
UNCOV
1647
}
×
1648

1649
/**
1650
 * @brief MainWindow::addToGridLayout add a field to the template grid
1651
 * @param position
1652
 * @param field
1653
 * @param value
1654
 */
UNCOV
1655
void MainWindow::addToGridLayout(int position, const QString &field,
×
1656
                                 const QString &value) {
1657
  QString trimmedField = field.trimmed();
1658
  QString trimmedValue = value.trimmed();
1659

1660
  const QString buttonStyle =
1661
      "border-style: none; background: transparent; padding: 0; margin: 0; "
1662
      "icon-size: 16px; color: inherit;";
×
1663

1664
  // Combine the Copy button and the line edit in one widget
UNCOV
1665
  auto *frame = new QFrame();
×
1666
  QLayout *ly = new QHBoxLayout();
×
1667
  ly->setContentsMargins(5, 2, 2, 2);
×
UNCOV
1668
  ly->setSpacing(0);
×
UNCOV
1669
  frame->setLayout(ly);
×
1670
  if (QtPassSettings::getClipBoardType() != Enums::CLIPBOARD_NEVER) {
×
1671
    auto *fieldLabel = new QPushButtonWithClipboard(trimmedValue, this);
×
1672
    connect(fieldLabel, &QPushButtonWithClipboard::clicked, m_qtPass,
×
1673
            &QtPass::copyTextToClipboard);
×
1674

1675
    fieldLabel->setStyleSheet(buttonStyle);
×
UNCOV
1676
    frame->layout()->addWidget(fieldLabel);
×
1677
  }
1678

UNCOV
1679
  if (QtPassSettings::isUseQrencode()) {
×
UNCOV
1680
    auto *qrbutton = new QPushButtonAsQRCode(trimmedValue, this);
×
UNCOV
1681
    connect(qrbutton, &QPushButtonAsQRCode::clicked, m_qtPass,
×
UNCOV
1682
            &QtPass::showTextAsQRCode);
×
1683
    qrbutton->setStyleSheet(buttonStyle);
×
1684
    frame->layout()->addWidget(qrbutton);
×
1685
  }
1686

1687
  // Show an explicit "open in browser" button when the value is a safe
1688
  // http(s) URL. The inline clickable link still works for URLs embedded in
1689
  // prose; this button is the discoverable affordance for url fields.
1690
  // Never on the password field: its value is a secret and must not be
1691
  // surfaced in a tooltip or handed to the browser.
1692
  if (trimmedField != tr("Password") &&
×
UNCOV
1693
      Util::isLaunchableWebUrl(trimmedValue)) {
×
UNCOV
1694
    auto *urlButton = new QPushButton(this);
×
UNCOV
1695
    urlButton->setIcon(QIcon::fromTheme(QStringLiteral("applications-internet"),
×
1696
                                        QIcon(":/icons/open-url.svg")));
×
1697
    urlButton->setToolTip(
×
UNCOV
1698
        tr("Open %1 in browser").arg(trimmedValue.toHtmlEscaped()));
×
1699
    urlButton->setStyleSheet(buttonStyle);
×
1700
    urlButton->setCursor(Qt::PointingHandCursor);
×
UNCOV
1701
    connect(urlButton, &QPushButton::clicked, this, [trimmedValue]() {
×
1702
      // Re-validate before launching (defence in depth: the value is
1703
      // immutable here, but never hand an unvalidated string to the OS
1704
      // URL handler).
1705
      if (Util::isLaunchableWebUrl(trimmedValue)) {
×
UNCOV
1706
        QDesktopServices::openUrl(QUrl(trimmedValue));
×
1707
      }
1708
    });
×
UNCOV
1709
    frame->layout()->addWidget(urlButton);
×
1710
  }
1711

1712
  // set the echo mode to password, if the field is "password"
1713
  const QString lineStyle =
1714
      QtPassSettings::isUseMonospace()
×
1715
          ? "border-style: none; background: transparent; font-family: "
1716
            "monospace;"
1717
          : "border-style: none; background: transparent;";
×
1718

1719
  if (QtPassSettings::isHidePassword() && trimmedField == tr("Password")) {
×
1720
    auto *line = new QLineEdit();
×
1721
    line->setObjectName(trimmedField);
×
1722
    line->setText(trimmedValue);
×
UNCOV
1723
    line->setReadOnly(true);
×
1724
    line->setStyleSheet(lineStyle);
×
1725
    line->setContentsMargins(0, 0, 0, 0);
×
1726
    line->setEchoMode(QLineEdit::Password);
×
1727
    auto *showButton = new QPushButtonShowPassword(line, this);
×
1728
    showButton->setStyleSheet(buttonStyle);
×
1729
    showButton->setContentsMargins(0, 0, 0, 0);
×
UNCOV
1730
    frame->layout()->addWidget(showButton);
×
1731
    frame->layout()->addWidget(line);
×
1732
  } else {
1733
    auto *line = new QTextBrowser();
×
1734
    line->setOpenExternalLinks(true);
×
1735
    line->setOpenLinks(true);
×
1736
    line->setMaximumHeight(26);
×
1737
    line->setMinimumHeight(26);
×
UNCOV
1738
    line->setSizePolicy(
×
1739
        QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum));
1740
    line->setObjectName(trimmedField);
×
UNCOV
1741
    trimmedValue.replace(Util::protocolRegex(), R"(<a href="\1">\1</a>)");
×
UNCOV
1742
    line->setText(trimmedValue);
×
UNCOV
1743
    line->setReadOnly(true);
×
1744
    line->setStyleSheet(lineStyle);
×
1745
    line->setContentsMargins(0, 0, 0, 0);
×
1746
    frame->layout()->addWidget(line);
×
1747
  }
1748

UNCOV
1749
  frame->setStyleSheet(
×
1750
      ".QFrame{border: 1px solid lightgrey; border-radius: 5px;}");
1751

1752
  // set into the layout
UNCOV
1753
  ui->gridLayout->addWidget(new QLabel(trimmedField), position, 0);
×
UNCOV
1754
  ui->gridLayout->addWidget(frame, position, 1);
×
UNCOV
1755
}
×
1756

1757
/**
1758
 * @brief Displays message in status bar
1759
 *
1760
 * @param msg     text to be displayed
1761
 * @param timeout time for which msg shall be visible
1762
 */
1763
void MainWindow::showStatusMessage(const QString &msg, int timeout) {
2✔
1764
  ui->statusBar->showMessage(msg, timeout);
2✔
1765
}
2✔
1766

1767
/**
1768
 * @brief MainWindow::reencryptPath re-encrypt all passwords in a directory
1769
 * @param dir Directory path to re-encrypt
1770
 */
1771
void MainWindow::reencryptPath(const QString &dir) {
×
1772
  QDir checkDir(dir);
×
UNCOV
1773
  if (!checkDir.exists()) {
×
UNCOV
1774
    QMessageBox::critical(this, tr("Error"),
×
UNCOV
1775
                          tr("Directory does not exist: %1").arg(dir));
×
UNCOV
1776
    return;
×
1777
  }
1778

UNCOV
1779
  int ret = QMessageBox::question(
×
1780
      this, tr("Re-encrypt passwords"),
×
UNCOV
1781
      tr("Re-encrypt all passwords in %1?\n\n"
×
1782
         "This will re-encrypt ALL password files in this folder "
1783
         "using the current recipients defined in .gpg-id.\n\n"
1784
         "This may rewrite many files and cannot be undone easily.\n\n"
1785
         "Continue?")
1786
          .arg(QDir(dir).dirName()),
×
1787
      QMessageBox::Yes | QMessageBox::No);
1788

1789
  if (ret != QMessageBox::Yes)
×
1790
    return;
1791

1792
  // Disable preemptively. ImitatePass::reencryptPath emits
1793
  // startReencryptPath asynchronously and the slot would re-run this,
1794
  // but setEnabled(false) is idempotent so the duplicate is harmless.
1795
  startReencryptPath();
×
1796

1797
  QtPassSettings::getImitatePass()->reencryptPath(
×
1798
      QDir::cleanPath(QDir(dir).absolutePath()));
×
UNCOV
1799
}
×
1800

1801
/**
1802
 * @brief MainWindow::startReencryptPath disable ui elements and treeview
1803
 */
UNCOV
1804
void MainWindow::startReencryptPath() {
×
UNCOV
1805
  setUiElementsEnabled(false);
×
UNCOV
1806
  ui->treeView->setDisabled(true);
×
UNCOV
1807
}
×
1808

1809
/**
1810
 * @brief MainWindow::endReencryptPath re-enable ui elements
1811
 */
1812
void MainWindow::endReencryptPath() { setUiElementsEnabled(true); }
×
1813

1814
/**
1815
 * @brief MainWindow::exportPublicKey export the configured signing key in
1816
 *        ASCII-armored form via gpg and show it in ExportPublicKeyDialog.
1817
 *
1818
 * Falls back to a help dialog when no signing key is configured or gpg is
1819
 * unavailable, so the user still gets actionable guidance.
1820
 */
UNCOV
1821
void MainWindow::exportPublicKey() {
×
UNCOV
1822
  QString identity = QtPassSettings::getPassSigningKey();
×
1823
  if (identity.isEmpty()) {
×
UNCOV
1824
    QMessageBox::information(
×
1825
        this, tr("Export Public Key"),
×
1826
        tr("<h3>Export Your Public Key</h3>"
×
1827
           "<p>No signing key is configured. Set one in QtPass Settings "
1828
           "&gt; GPG keys, or run this in a terminal:</p>"
1829
           "<pre>gpg --armor --export --output my_key.asc &lt;your-key-id"
1830
           "&gt;</pre>"
1831
           "<p>Then send the file to your teammates.</p>"));
1832
    return;
×
1833
  }
1834
  QString gpgExe = QtPassSettings::getGpgExecutable();
×
1835
  if (gpgExe.isEmpty()) {
×
1836
    gpgExe = QStringLiteral("gpg");
×
1837
  }
1838
  QStringList args = {"--armor", "--export"};
×
1839
  args.append(identity.split(' ', Qt::SkipEmptyParts));
×
UNCOV
1840
  QString stdOut;
×
UNCOV
1841
  QString stdErr;
×
1842
  int exitCode =
1843
      Executor::executeBlocking(gpgExe, args, QString(), &stdOut, &stdErr);
×
1844
  if (exitCode != 0 || stdOut.isEmpty()) {
×
1845
    QMessageBox::warning(this, tr("Export Public Key"),
×
UNCOV
1846
                         tr("Could not export public key for %1.\n\n%2")
×
UNCOV
1847
                             .arg(identity, stdErr.isEmpty()
×
UNCOV
1848
                                                ? tr("No output from gpg.")
×
1849
                                                : stdErr));
1850
    return;
1851
  }
UNCOV
1852
  ExportPublicKeyDialog dialog(identity, stdOut, this);
×
UNCOV
1853
  dialog.exec();
×
UNCOV
1854
}
×
1855

1856
/**
1857
 * @brief MainWindow::addRecipient open the recipient management dialog for
1858
 *        the supplied directory.
1859
 * @param dir Folder whose .gpg-id should be edited.
1860
 *
1861
 * Delegates to UsersDialog so users can tick/untick keys from their
1862
 * keyring as recipients of the folder; importing a foreign key into the
1863
 * keyring still has to happen via gpg (or QtPass settings) first.
1864
 */
1865
void MainWindow::addRecipient(const QString &dir) {
×
1866
  UsersDialog d(dir, this);
×
1867
  d.exec();
×
UNCOV
1868
}
×
1869

1870
/**
1871
 * @brief MainWindow::showShareHelp show help about GPG sharing
1872
 */
UNCOV
1873
void MainWindow::showShareHelp() {
×
UNCOV
1874
  QMessageBox::information(
×
UNCOV
1875
      this, tr("Sharing Passwords with GPG"),
×
UNCOV
1876
      tr("<h3>Sharing Passwords with GPG</h3>"
×
1877
         "<p>To share passwords with other users:</p>"
1878
         "<ol>"
1879
         "<li><b>Export your public key</b> and send it to teammates</li>"
1880
         "<li><b>Import teammates' public keys</b> into your GPG keyring</li>"
1881
         "<li><b>Re-encrypt passwords</b> so all recipients can decrypt "
1882
         "them</li>"
1883
         "</ol>"
1884
         "<p>Only people who have a matching secret key can decrypt the "
1885
         "passwords.</p>"
1886
         "<p><b>Tip:</b> Use the same GPG key for all shared folders.</p>"
1887
         "<p>See the FAQ for more details.</p>"));
UNCOV
1888
}
×
1889

1890
void MainWindow::updateGitButtonVisibility() {
15✔
1891
  if (!QtPassSettings::isUseGit() ||
30✔
1892
      (QtPassSettings::getGitExecutable().isEmpty() &&
15✔
1893
       QtPassSettings::getPassExecutable().isEmpty())) {
15✔
1894
    enableGitButtons(false);
15✔
1895
  } else {
UNCOV
1896
    enableGitButtons(true);
×
1897
  }
1898
}
15✔
1899

1900
void MainWindow::updateOtpButtonVisibility() {
15✔
1901
#if defined(Q_OS_WIN) || defined(__APPLE__)
1902
  ui->actionOtp->setVisible(false);
1903
#endif
1904
  if (!QtPassSettings::isUseOtp()) {
15✔
1905
    ui->actionOtp->setEnabled(false);
15✔
1906
  } else {
1907
    ui->actionOtp->setEnabled(true);
×
1908
  }
1909
}
15✔
1910

1911
void MainWindow::updateGrepButtonVisibility() {
12✔
1912
  const bool enabled = QtPassSettings::isUseGrepSearch();
12✔
1913
  ui->grepButton->setVisible(enabled);
12✔
1914
  ui->grepCaseButton->setVisible(enabled);
12✔
1915
  if (!enabled && m_grepMode) {
12✔
UNCOV
1916
    ui->grepButton->setChecked(false);
×
1917
  }
1918
}
12✔
1919

1920
void MainWindow::enableGitButtons(const bool &state) {
15✔
1921
  // Following GNOME guidelines is preferable disable buttons instead of hide
1922
  ui->actionPush->setEnabled(state);
15✔
1923
  ui->actionUpdate->setEnabled(state);
15✔
1924
}
15✔
1925

1926
/**
1927
 * @brief MainWindow::critical critical message popup wrapper.
1928
 * @param title
1929
 * @param msg
1930
 */
UNCOV
1931
void MainWindow::critical(const QString &title, const QString &msg) {
×
UNCOV
1932
  QMessageBox::critical(this, title, msg);
×
UNCOV
1933
}
×
1934

1935
/**
1936
 * @brief Appends processed command output to the output panel.
1937
 *
1938
 * Appends text to the process output text edit, with per-line numbering,
1939
 * optional command prefix, and color coding for errors vs. success.
1940
 * Handles auto-scrolling and line limits.
1941
 *
1942
 * @param output The raw output text from the command.
1943
 * @param isError true if this is error output (stderr).
1944
 * @param linePrefix Optional command name to prefix each line with.
1945
 */
1946
void MainWindow::appendProcessOutput(const QString &output, bool isError,
2✔
1947
                                     const QString &linePrefix) {
1948
  if (!QtPassSettings::isShowProcessOutput()) {
2✔
1949
    return;
1✔
1950
  }
1951

1952
  QStringList lines = output.split('\n', Qt::SkipEmptyParts);
1✔
1953
  for (QString &line : lines) {
2✔
1954
    // Right-trim only: remove trailing CR and whitespace, preserve leading
1955
    // indentation
1956
    line.remove('\r');
1✔
1957
    while (!line.isEmpty() && line.back().isSpace()) {
2✔
UNCOV
1958
      line.chop(1);
×
1959
    }
1960
    if (line.isEmpty()) {
1✔
UNCOV
1961
      continue;
×
1962
    }
1963

1964
    m_outputCounter++;
1✔
1965
    QString lineNumber = QString::number(m_outputCounter);
1✔
1966

1967
    QColor textColor =
1968
        isError ? QColor(Qt::red)
1✔
1969
                : m_processOutputEdit->palette().color(QPalette::Text);
2✔
1970
    QString colorHex = textColor.name();
1✔
1971
    // Apply the optional prefix per line so multi-line output stays
1972
    // attributed to its command (e.g. all 3 lines of a `git push` show
1973
    // "git push: ..." rather than only the first).
1974
    QString prefixed =
1975
        linePrefix.isEmpty() ? line : linePrefix + QStringLiteral(": ") + line;
2✔
1976
    QString coloredOutput =
1977
        QString("<span style=\"color: %1;\">%2: %3</span>")
1✔
1978
            .arg(colorHex, lineNumber, prefixed.toHtmlEscaped());
2✔
1979

1980
    m_processOutputEdit->append(coloredOutput);
1✔
1981
  }
1982

1983
  limitOutputLines();
1✔
1984

1985
  if (m_autoScroll) {
1✔
1986
    m_processOutputEdit->verticalScrollBar()->setValue(
2✔
1987
        m_processOutputEdit->verticalScrollBar()->maximum());
1✔
1988
  }
1989
}
1990

1991
/**
1992
 * @brief Handles process output from the Pass executor.
1993
 *
1994
 * Called when any non-sensitive process completes. Filters out password-
1995
 * related commands (pass show, insert, etc.) and delegates to
1996
 * appendProcessOutput.
1997
 *
1998
 * @param output The stdout/stderr text from the process.
1999
 * @param isError true if this is error output (stderr).
2000
 * @param pid The process ID identifying which command ran.
2001
 */
2002
void MainWindow::onProcessOutput(const QString &output, bool isError,
2✔
2003
                                 Enums::PROCESS pid) {
2004
  appendProcessOutput(output, isError, getProcessName(pid));
2✔
2005
}
2✔
2006

2007
/**
2008
 * @brief Maps a process ID to its human-readable command name.
2009
 *
2010
 * Returns static strings for git/pass commands that appear in output.
2011
 * Password-related commands return empty (they are filtered).
2012
 *
2013
 * @param pid The process ID to look up.
2014
 * @return QString with command name, or empty if filtered.
2015
 */
2016
auto MainWindow::getProcessName(Enums::PROCESS pid) -> QString {
2✔
2017
  switch (pid) {
2✔
2018
  case Enums::GIT_INIT:
×
2019
    return QStringLiteral("git init"); // no-tr
×
2020
  case Enums::GIT_ADD:
×
2021
    return QStringLiteral("git add"); // no-tr
×
2022
  case Enums::GIT_COMMIT:
×
2023
    return QStringLiteral("git commit"); // no-tr
×
UNCOV
2024
  case Enums::GIT_RM:
×
UNCOV
2025
    return QStringLiteral("git rm"); // no-tr
×
UNCOV
2026
  case Enums::GIT_PULL:
×
UNCOV
2027
    return QStringLiteral("git pull"); // no-tr
×
2028
  case Enums::GIT_PUSH:
×
2029
    return QStringLiteral("git push"); // no-tr
×
2030
  case Enums::GIT_MOVE:
×
2031
    return QStringLiteral("git mv"); // no-tr
×
2032
  case Enums::GIT_COPY:
×
2033
    // ImitatePass::Copy literally invokes `git cp` (a git-extras
2034
    // subcommand), so the label matches what's run. Stock-git users
2035
    // without git-extras will see the underlying "'cp' is not a git
2036
    // command" failure surfaced in the process output panel.
2037
    return QStringLiteral("git cp"); // no-tr
×
2038
  case Enums::PASS_INSERT:
×
2039
    return QStringLiteral("pass insert"); // no-tr
×
2040
  case Enums::PASS_REMOVE:
×
2041
    return QStringLiteral("pass rm"); // no-tr
×
2042
  case Enums::PASS_INIT:
×
UNCOV
2043
    return QStringLiteral("pass init"); // no-tr
×
UNCOV
2044
  case Enums::PASS_MOVE:
×
UNCOV
2045
    return QStringLiteral("pass mv"); // no-tr
×
UNCOV
2046
  case Enums::PASS_COPY:
×
UNCOV
2047
    return QStringLiteral("pass cp"); // no-tr
×
UNCOV
2048
  case Enums::PASS_GREP:
×
UNCOV
2049
    return QStringLiteral("pass grep"); // no-tr
×
UNCOV
2050
  case Enums::GPG_GENKEYS:
×
UNCOV
2051
    return QStringLiteral("gpg --gen-key"); // no-tr
×
2052
  case Enums::PASS_SHOW:
2053
  case Enums::PASS_OTP_GENERATE:
2054
  case Enums::PROCESS_COUNT:
2055
  case Enums::INVALID:
2056
    break;
2057
  }
2058
  return {};
2059
}
2060

2061
/**
2062
 * @brief Checks if a process ID represents a sensitive operation whose
2063
 * output should not be shown in the process output panel.
2064
 *
2065
 * Password-related commands (pass show, OTP generate, grep, insert)
2066
 * display their output in other UI areas, so we skip them here.
2067
 *
2068
 * @param pid The process ID to check.
2069
 * @return true if the process is sensitive and should be filtered.
2070
 */
UNCOV
2071
auto MainWindow::isSensitiveProcess(Enums::PROCESS pid) -> bool {
×
UNCOV
2072
  switch (pid) {
×
2073
  case Enums::PASS_SHOW:
2074
  case Enums::PASS_OTP_GENERATE:
2075
  case Enums::PASS_GREP:
2076
  case Enums::PASS_INSERT:
2077
    return true;
2078
  case Enums::GIT_INIT:
2079
  case Enums::GIT_ADD:
2080
  case Enums::GIT_COMMIT:
2081
  case Enums::GIT_RM:
2082
  case Enums::GIT_PULL:
2083
  case Enums::GIT_PUSH:
2084
  case Enums::GIT_MOVE:
2085
  case Enums::GIT_COPY:
2086
  case Enums::PASS_REMOVE:
2087
  case Enums::PASS_INIT:
2088
  case Enums::PASS_MOVE:
2089
  case Enums::PASS_COPY:
2090
  case Enums::GPG_GENKEYS:
2091
  case Enums::PROCESS_COUNT:
2092
  case Enums::INVALID:
2093
    break;
2094
  }
2095
  return false;
×
2096
}
2097

2098
/**
2099
 * @brief Updates the visibility of the process output panel.
2100
 *
2101
 * Shows or hides the process output widget based on the user's
2102
 * showProcessOutput setting.
2103
 */
UNCOV
2104
void MainWindow::updateProcessOutputVisibility() {
×
UNCOV
2105
  m_processOutputDock->setVisible(QtPassSettings::isShowProcessOutput());
×
UNCOV
2106
}
×
2107

2108
/**
2109
 * @brief Limits the output panel to max lines, trimming old excess.
2110
 *
2111
 * Removes the oldest lines when the document exceeds MaxOutputLines (1000).
2112
 * Called after each append to prevent unbounded growth.
2113
 */
2114
void MainWindow::limitOutputLines() {
1✔
2115
  QTextDocument *doc = m_processOutputEdit->document();
1✔
2116
  int excess = doc->blockCount() - MaxOutputLines;
1✔
2117
  if (excess <= 0) {
1✔
2118
    return;
1✔
2119
  }
2120

UNCOV
2121
  QTextCursor cursor(doc);
×
UNCOV
2122
  cursor.movePosition(QTextCursor::Start);
×
2123
  cursor.movePosition(QTextCursor::NextBlock, QTextCursor::KeepAnchor, excess);
×
2124
  cursor.removeSelectedText();
×
2125
}
×
2126

2127
/**
2128
 * @brief Clears the process output panel.
2129
 *
2130
 * Clears all output, resets the line counter, and re-enables auto-scroll.
2131
 */
UNCOV
2132
void MainWindow::on_clearOutputButton_clicked() {
×
UNCOV
2133
  m_processOutputEdit->clear();
×
UNCOV
2134
  m_outputCounter = 0;
×
UNCOV
2135
  m_autoScroll = true;
×
UNCOV
2136
}
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc