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

IJHack / QtPass / 34957285919

15 Sep 2026 10:18AM UTC coverage: 69.949%. First build
34957285919

Pull #1746

github

web-flow
Merge 67767953c into 078384549
Pull Request #1746: QtPass 2.0 development moves to main; 1.8.x continues on the 1.8 branch

228 of 262 new or added lines in 13 files covered. (87.02%)

5235 of 7484 relevant lines covered (69.95%)

72.84 hits per line

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

41.57
/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 <QProgressDialog>
43
#include <QPushButton>
44
#include <QScrollBar>
45
#include <QShortcut>
46
#include <QTextCharFormat>
47
#include <QTextCursor>
48
#include <QTextEdit>
49
#include <QTextStream>
50
#include <QTimer>
51
#include <QToolButton>
52
#include <QTreeWidget>
53
#include <QUrl>
54
#include <utility>
55

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

71
  m_qtPass = new QtPass(this);
28 ✔
72

73
  // register shortcut ctrl/cmd + Q to close the main window
74
  new QShortcut(QKeySequence(Qt::CTRL | Qt::Key_Q), this, this,
28 ✔
75
                &MainWindow::close);
28 ✔
76
  // register shortcut ctrl/cmd + C to copy the currently selected password
77
  new QShortcut(QKeySequence(QKeySequence::StandardKey::Copy), this, this,
28 ✔
78
                &MainWindow::copyPasswordFromTreeview);
28 ✔
79

80
  model.setNameFilters(QStringList() << "*.gpg");
84 ✔
81
  model.setNameFilterDisables(false);
28 ✔
82

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

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

88
  proxyModel.setModelAndStore(&model, passStore);
28 ✔
89
  proxyModel.setPass(QtPassSettings::getPass());
28 ✔
90
  selectionModel.reset(new QItemSelectionModel(&proxyModel));
28 ✔
91

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

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

125
  updateProfileBox();
28 ✔
126

127
  m_displayPanel = new PasswordDisplayPanel(
28 ✔
128
      ui->gridLayout, ui->verticalLayoutPassword, this, this);
28 ✔
129
  connect(m_displayPanel, &PasswordDisplayPanel::copyRequested, m_qtPass,
28 ✔
130
          &QtPass::copyTextToClipboard);
28 ✔
131
  connect(m_displayPanel, &PasswordDisplayPanel::qrRequested, m_qtPass,
28 ✔
132
          &QtPass::showTextAsQRCode);
28 ✔
133

134
  QtPassSettings::getPass()->updateEnv();
28 ✔
135
  clearPanelTimer.setSingleShot(true);
28 ✔
136
  connect(&clearPanelTimer, &QTimer::timeout, this, [this]() { clearPanel(); });
28 ✔
137

138
  searchTimer.setInterval(350);
28 ✔
139
  searchTimer.setSingleShot(true);
28 ✔
140

141
  connect(&searchTimer, &QTimer::timeout, this, &MainWindow::onTimeoutSearch);
28 ✔
142

143
  // Install the search-box key filter once, not on every setUiElementsEnabled
144
  // call.
145
  ui->lineEdit->installEventFilter(this);
28 ✔
146
  ui->toolBar->installEventFilter(this);
28 ✔
147

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

160
  initToolBarButtons();
28 ✔
161
  initStatusBar();
28 ✔
162
  initProcessOutputPanel();
28 ✔
163

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

185
  ui->lineEdit->setClearButtonEnabled(true);
28 ✔
186
  updateGrepButtonVisibility();
28 ✔
187

188
  setUiElementsEnabled(true);
28 ✔
189

190
  ui->lineEdit->setText(searchText);
28 ✔
191

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

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

211
MainWindow::~MainWindow() { delete m_qtPass; }
108 ✔
212

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

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

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

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

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

332
/**
333
 * @brief MainWindow::initStatusBar init statusBar with default message and logo
334
 */
335
void MainWindow::initStatusBar() {
28 ✔
336
  ui->statusBar->showMessage(tr("Welcome to QtPass %1").arg(VERSION), 2000);
56 ✔
337

338
  QPixmap logo = QPixmap::fromImage(QImage(":/artwork/icon.svg"))
56 ✔
339
                     .scaledToHeight(statusBar()->height());
28 ✔
340
  auto *logoApp = new QLabel(statusBar());
28 ✔
341
  logoApp->setPixmap(logo);
28 ✔
342
  statusBar()->addPermanentWidget(logoApp);
28 ✔
343
}
28 ✔
344

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

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

390
  connect(m_clearOutputButton, &QToolButton::clicked, this,
28 ✔
391
          &MainWindow::on_clearOutputButton_clicked);
28 ✔
392

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

412
auto MainWindow::getCurrentTreeViewIndex() -> QModelIndex {
1 ✔
413
  return ui->treeView->currentIndex();
1 ✔
414
}
415

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

423
/**
424
 * @brief Displays the given text in the main window text browser, optionally
425
 * marking it as an error and/or rendering it as HTML.
426
 * @example
427
 * MainWindow window;
428
 * window.flashText("Operation completed.", false, false);
429
 *
430
 * @param const QString &text - The text content to display.
431
 * @param const bool isError - If true, sets the text color to red before
432
 * displaying the text; otherwise any earlier error colour is cleared.
433
 * @param const bool isHtml - If true, treats the text as HTML and appends it to
434
 * the existing HTML content.
435
 * @return void - No return value.
436
 */
437
void MainWindow::flashText(const QString &text, const bool isError,
11 ✔
438
                           const bool isHtml) {
439
  if (isError) {
11 ✔
440
    ui->textBrowser->setTextColor(Qt::red);
3 ✔
441
  } else {
442
    // setTextColor() merges the red foreground into the browser's current
443
    // char format, and setText()/setPlainText() re-applies that format to the
444
    // whole new document. Without clearing it, a plain-text non-error message
445
    // shown after an error would still be red. Remove the property rather
446
    // than pinning a palette colour: an explicit foreground would stop the
447
    // text from following runtime light/dark palette switches (#946).
448
    QTextCharFormat format = ui->textBrowser->currentCharFormat();
8 ✔
449
    format.clearForeground();
450
    ui->textBrowser->setCurrentCharFormat(format);
8 ✔
451
  }
452

453
  if (isHtml) {
11 ✔
454
    QString _text = text;
455
    if (!ui->textBrowser->toPlainText().isEmpty()) {
12 ✔
456
      _text = ui->textBrowser->toHtml() + _text;
2 ✔
457
    }
458
    ui->textBrowser->setHtml(_text);
6 ✔
459
  } else {
460
    ui->textBrowser->setText(text);
5 ✔
461
  }
462
}
11 ✔
463

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

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

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

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

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

524
  applyTextBrowserSettings();
3 ✔
525
  applyWindowFlagsSettings();
3 ✔
526

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

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

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

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

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

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

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

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

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

636
  if (fileOrFolder.isFile()) {
1 ✔
637
    editPassword(getFile(index, true));
2 ✔
638
  }
639
}
1 ✔
640

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

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

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

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

696
  // first clear the current view:
697
  m_displayPanel->clear();
3 ✔
698

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

709
  if (s.useAutoclearPanel) {
3 ✔
710
    clearPanelTimer.start();
×
711
  }
712

713
  emit passShowHandlerFinished(output);
3 ✔
714
  setUiElementsEnabled(true);
3 ✔
715
}
6 ✔
716

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

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

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

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

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

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

814
/**
815
 * @brief MainWindow::setUiElementsEnabled enable or disable the relevant UI
816
 * elements
817
 * @param state
818
 */
819
void MainWindow::setUiElementsEnabled(bool state) {
49 ✔
820
  // A running re-encryption owns the UI state: the progress dialog's Cancel is
821
  // the user's escape hatch and endReencryptPath() releases the interface, so
822
  // neither an unrelated completion nor the watchdog may re-enable it early.
823
  if (state && m_reencryptRunning) {
49 ✔
824
    m_uiWatchdog.stop();
1 ✔
825
    return;
1 ✔
826
  }
827
  // Arm the watchdog while the UI is disabled; disarm once re-enabled.
828
  if (state) {
829
    m_uiWatchdog.stop();
37 ✔
830
  } else {
831
    m_uiWatchdog.start();
11 ✔
832
  }
833
  ui->treeView->setEnabled(state);
48 ✔
834
  ui->lineEdit->setEnabled(state);
48 ✔
835
  ui->actionAddPassword->setEnabled(state);
48 ✔
836
  ui->actionAddFolder->setEnabled(state);
48 ✔
837
  ui->actionUsers->setEnabled(state);
48 ✔
838
  ui->actionConfig->setEnabled(state);
48 ✔
839
  // is a file selected?
840
  state &= ui->treeView->currentIndex().isValid();
96 ✔
841
  ui->actionDelete->setEnabled(state);
48 ✔
842
  ui->actionEdit->setEnabled(state);
48 ✔
843
  updateGitButtonVisibility();
48 ✔
844
  // `state` is now "UI enabled AND a file is selected", which is exactly when
845
  // generating an OTP makes sense.
846
  updateOtpButtonVisibility(state);
48 ✔
847
}
848

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

872
  if (s.alwaysOnTop) {
28 ✔
873
    Qt::WindowFlags flags = windowFlags();
874
    setWindowFlags(flags | Qt::WindowStaysOnTopHint);
×
875
    show();
×
876
  }
877

878
  if (s.useTrayIcon && m_tray == nullptr) {
28 ✔
879
    initTrayIcon();
×
880
    if (s.startMinimized) {
×
881
      // since we are still in constructor, can't directly hide
NEW
882
      QTimer::singleShot(10, this, &MainWindow::hide);
×
883
    }
884
  } else if (!s.useTrayIcon && m_tray != nullptr) {
28 ✔
885
    destroyTrayIcon();
×
886
  }
887
}
56 ✔
888

889
/**
890
 * @brief MainWindow::on_configButton_clicked run Mainwindow::config
891
 */
892
void MainWindow::onConfig() { config(); }
×
893

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

911
/**
912
 * @brief MainWindow::onTimeoutSearch Fired when search is finished or too much
913
 * time from two keypresses is elapsed
914
 */
915
void MainWindow::onTimeoutSearch() {
×
916
  QString query = ui->lineEdit->text();
×
917

918
  if (query.isEmpty()) {
×
919
    ui->treeView->collapseAll();
×
920
    deselect();
×
921
  }
922

923
  query.replace(QStringLiteral(" "), ".*");
×
924
  QRegularExpression regExp(query, QRegularExpression::CaseInsensitiveOption);
×
925
  if (!regExp.isValid())
×
926
    return;
927
  proxyModel.setFilterRegularExpression(regExp);
×
928
  ui->treeView->setRootIndex(
×
929
      proxyModel.rootIndexFor(QtPassSettings::getPassStore()));
×
930

931
  if (proxyModel.rowCount() > 0 && !query.isEmpty()) {
×
932
    selectFirstFile();
×
933
  } else {
934
    ui->actionEdit->setEnabled(false);
×
935
    ui->actionDelete->setEnabled(false);
×
936
  }
937
}
×
938

939
/**
940
 * @brief MainWindow::on_lineEdit_returnPressed get searching
941
 *
942
 * Select the first possible file in the tree
943
 */
944
void MainWindow::on_lineEdit_returnPressed() {
×
945
#ifdef QT_DEBUG
946
  dbg() << "on_lineEdit_returnPressed" << proxyModel.rowCount();
947
#endif
948

949
  if (m_grep.inGrepMode()) {
×
950
    const QString query = ui->lineEdit->text();
×
951
    if (!query.isEmpty()) {
×
952
      ui->grepResultsList->clear();
×
953
      ui->statusBar->showMessage(tr("Searching…"));
×
954
      if (m_grep.beginSearch()) {
955
        QApplication::setOverrideCursor(Qt::WaitCursor);
×
956
      }
957
      QtPassSettings::getPass()->Grep(query, ui->grepCaseButton->isChecked());
×
958
    } else {
959
      if (m_grep.cancelSearch()) {
960
        QApplication::restoreOverrideCursor();
×
961
      }
962
      ui->grepResultsList->clear();
×
963
      ui->grepResultsList->setVisible(false);
×
964
      ui->treeView->setVisible(true);
×
965
    }
966
    return;
967
  }
968

969
  if (proxyModel.rowCount() > 0) {
×
970
    selectFirstFile();
×
971
    on_treeView_clicked(ui->treeView->currentIndex());
×
972
  }
973
}
974

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

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

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

1092
/**
1093
 * @brief MainWindow::selectFirstFile select the first possible file in the
1094
 * tree
1095
 */
1096
void MainWindow::selectFirstFile() {
×
1097
  QModelIndex index = proxyModel.rootIndexFor(QtPassSettings::getPassStore());
×
1098
  index = firstFile(index);
×
1099
  ui->treeView->setCurrentIndex(index);
×
1100
}
×
1101

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

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

1145
/**
1146
 * @brief MainWindow::setPassword open passworddialog
1147
 * @param file which pgp file
1148
 * @param isNew insert (not update)
1149
 */
1150
void MainWindow::setPassword(const QString &file, bool isNew) {
1 ✔
1151
  const AppSettings s = QtPassSettings::load();
1 ✔
1152
  PasswordDialog d(QtPassSettings::getPass(), s, file, isNew, this);
1 ✔
1153

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

1172
  if (!d.exec()) {
1 ✔
1173
    ui->treeView->setFocus();
×
1174
  }
1175
}
1 ✔
1176

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

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

1215
  QFileInfo fileOrFolder =
1216
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
1217
  QString file = "";
×
1218
  bool isDir = false;
1219

1220
  if (fileOrFolder.isFile()) {
×
1221
    file = getFile(ui->treeView->currentIndex(), true);
×
1222
  } else {
1223
    file = Util::getDir(ui->treeView->currentIndex(), true, model, proxyModel,
×
1224
                        QtPassSettings::getPassStore());
×
1225
    isDir = true;
1226
  }
1227

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

1246
  if (QMessageBox::question(
×
1247
          this, isDir ? tr("Delete folder?") : tr("Delete password?"),
×
1248
          tr("Are you sure you want to delete %1%2?")
×
1249
              .arg(QDir::separator() + file, isDir ? dirMessage : "?"),
×
1250
          QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) {
1251
    return;
1252
  }
1253

1254
  QtPassSettings::getPass()->Remove(file, isDir);
×
1255
}
×
1256

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

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

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

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

1335
/**
1336
 * @brief MainWindow::onEdit try and edit (selected) password.
1337
 */
1338
void MainWindow::onEdit() {
×
1339
  QString file = getFile(ui->treeView->currentIndex(), true);
×
1340
  editPassword(file);
×
1341
}
×
1342

1343
/**
1344
 * @brief MainWindow::userDialog see MainWindow::onUsers()
1345
 * @param dir folder to edit users for.
1346
 */
1347
void MainWindow::userDialog(const QString &dir) {
×
1348
  if (!dir.isEmpty()) {
×
1349
    m_currentDir = dir;
×
1350
  }
1351
  onUsers();
×
1352
}
×
1353

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

1365
  UsersDialog d(QtPassSettings::getPass(), QtPassSettings::load(), dir, this);
×
1366
  if (!d.exec()) {
×
1367
    ui->treeView->setFocus();
×
1368
  }
1369
}
×
1370

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

1387
/**
1388
 * @brief MainWindow::generateKeyPair internal gpg keypair generator . .
1389
 * @param batch
1390
 * @param keygenWindow
1391
 */
1392
void MainWindow::generateKeyPair(const QString &batch, QDialog *keygenWindow) {
×
1393
  m_keyGenDialog = keygenWindow;
1394
  emit generateGPGKeyPair(batch);
×
1395
}
×
1396

1397
/**
1398
 * @brief MainWindow::updateProfileBox update the list of profiles, optionally
1399
 * select a more appropriate one to view too
1400
 */
1401
void MainWindow::updateProfileBox() {
31 ✔
1402
  QHash<QString, QHash<QString, QString>> profiles =
1403
      QtPassSettings::getProfiles();
31 ✔
1404

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

1426
/**
1427
 * @brief Handles changes to the selected profile in the profile combo box.
1428
 * @details Ignores the event during a fresh start or when the selected profile
1429
 * matches the current profile. Otherwise, it clears the password field, updates
1430
 * the active profile and related settings, refreshes the environment, and
1431
 * resets the tree view and action states to reflect the newly selected profile.
1432
 *
1433
 * @param name - The newly selected profile name.
1434
 * @return void - This function does not return a value.
1435
 *
1436
 */
1437
void MainWindow::on_profileBox_currentTextChanged(const QString &name) {
×
1438
  if (m_qtPass->isFreshStart() || name == QtPassSettings::getProfile()) {
×
1439
    return;
×
1440
  }
1441

1442
  ui->lineEdit->clear();
×
1443

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

1453
  QtPassSettings::getPass()->updateEnv();
×
1454

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

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

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

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

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

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

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

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

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

1602
  ui->treeView->setCurrentIndex(index);
×
1603

1604
  QPoint globalPos = ui->treeView->viewport()->mapToGlobal(pos);
×
1605

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

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

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

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

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

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

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

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

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

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

1688
  contextMenu->exec(globalPos);
×
1689
  delete contextMenu;
×
1690
}
×
1691

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1908
/**
1909
 * @brief MainWindow::startReencryptPath disable ui elements and treeview and
1910
 * show the progress dialog. Idempotent: MainWindow::reencryptPath calls it
1911
 * before ImitatePass emits startReencryptPath.
1912
 */
1913
void MainWindow::startReencryptPath() {
3 ✔
1914
  m_reencryptRunning = true;
3 ✔
1915
  setUiElementsEnabled(false);
3 ✔
1916
  // The worker always ends with endReencryptPath(), and Cancel is available
1917
  // throughout, so the generic watchdog is not needed for this operation.
1918
  m_uiWatchdog.stop();
3 ✔
1919
  ui->treeView->setDisabled(true);
3 ✔
1920
  if (m_reencryptProgress)
3 ✔
1921
    return;
1922
  auto *progress = new QProgressDialog(tr("Re-encrypting passwords..."),
2 ✔
1923
                                       tr("Cancel"), 0, 0, this);
4 ✔
1924
  progress->setWindowTitle(tr("Re-encrypt passwords"));
2 ✔
1925
  progress->setWindowModality(Qt::WindowModal);
2 ✔
1926
  progress->setAutoClose(false);
2 ✔
1927
  progress->setAutoReset(false);
2 ✔
1928
  progress->setMinimumDuration(0);
2 ✔
1929
  connect(progress, &QProgressDialog::canceled, this, [this]() {
2 ✔
NEW
1930
    QtPassSettings::getImitatePass()->cancelReencryptPath();
×
NEW
1931
    showStatusMessage(tr("Cancelling re-encryption"), 5000);
×
NEW
1932
  });
×
1933
  m_reencryptProgress = progress;
1934
  progress->show();
2 ✔
1935
}
1936

1937
/**
1938
 * @brief MainWindow::reencryptProgress show how many files were checked
1939
 * @param current files checked so far
1940
 * @param total files found under the folder
1941
 */
1942
void MainWindow::reencryptProgress(int current, int total) {
4 ✔
1943
  if (!m_reencryptProgress)
4 ✔
1944
    return;
1945
  m_reencryptProgress->setMaximum(total);
3 ✔
1946
  m_reencryptProgress->setLabelText(
3 ✔
1947
      tr("Re-encrypting passwords: %1 of %2").arg(current).arg(total));
6 ✔
1948
  // On a modal QProgressDialog setValue() calls processEvents(), which can
1949
  // deliver the queued completion: endReencryptPath() then hides the dialog
1950
  // and resets m_reencryptProgress under our feet. Keep it last and touch
1951
  // nothing afterwards.
1952
  m_reencryptProgress->setValue(current);
3 ✔
1953
}
1954

1955
/**
1956
 * @brief MainWindow::endReencryptPath re-enable ui elements
1957
 */
1958
void MainWindow::endReencryptPath() {
2 ✔
1959
  m_reencryptRunning = false;
2 ✔
1960
  if (m_reencryptProgress) {
2 ✔
1961
    m_reencryptProgress->hide();
2 ✔
1962
    m_reencryptProgress->deleteLater();
2 ✔
1963
    m_reencryptProgress = nullptr;
1964
  }
1965
  setUiElementsEnabled(true);
2 ✔
1966
}
2 ✔
1967

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

2010
/**
2011
 * @brief MainWindow::addRecipient open the recipient management dialog for
2012
 *        the supplied directory.
2013
 * @param dir Folder whose .gpg-id should be edited.
2014
 *
2015
 * Delegates to UsersDialog so users can tick/untick keys from their
2016
 * keyring as recipients of the folder; importing a foreign key into the
2017
 * keyring still has to happen via gpg (or QtPass settings) first.
2018
 */
2019
void MainWindow::addRecipient(const QString &dir) {
×
2020
  UsersDialog d(QtPassSettings::getPass(), QtPassSettings::load(), dir, this);
×
2021
  d.exec();
×
2022
}
×
2023

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

2044
void MainWindow::updateGitButtonVisibility() {
51 ✔
2045
  const AppSettings s = QtPassSettings::load();
51 ✔
2046
  if (!s.useGit || (s.gitExecutable.isEmpty() && s.passExecutable.isEmpty())) {
51 ✔
2047
    enableGitButtons(false);
51 ✔
2048
  } else {
2049
    enableGitButtons(true);
×
2050
  }
2051
}
51 ✔
2052

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

2071
void MainWindow::updateGrepButtonVisibility() {
31 ✔
2072
  const bool enabled = QtPassSettings::isUseGrepSearch();
31 ✔
2073
  ui->grepButton->setVisible(enabled);
31 ✔
2074
  ui->grepCaseButton->setVisible(enabled);
31 ✔
2075
  if (!enabled && m_grep.inGrepMode()) {
31 ✔
2076
    ui->grepButton->setChecked(false);
×
2077
  }
2078
}
31 ✔
2079

2080
void MainWindow::enableGitButtons(const bool &state) {
51 ✔
2081
  // Following GNOME guidelines is preferable disable buttons instead of hide
2082
  ui->actionPush->setEnabled(state);
51 ✔
2083
  ui->actionUpdate->setEnabled(state);
51 ✔
2084
}
51 ✔
2085

2086
/**
2087
 * @brief MainWindow::critical critical message popup wrapper.
2088
 * @param title
2089
 * @param msg
2090
 */
2091
void MainWindow::critical(const QString &title, const QString &msg) {
×
2092
  QMessageBox::critical(this, title, msg);
×
2093
}
×
2094

2095
/**
2096
 * @brief Appends processed command output to the output panel.
2097
 *
2098
 * Appends text to the process output text edit, with per-line numbering,
2099
 * optional command prefix, and color coding for errors vs. success.
2100
 * Handles auto-scrolling and line limits.
2101
 *
2102
 * @param output The raw output text from the command.
2103
 * @param isError true if this is error output (stderr).
2104
 * @param linePrefix Optional command name to prefix each line with.
2105
 */
2106
void MainWindow::appendProcessOutput(const QString &output, bool isError,
2 ✔
2107
                                     const QString &linePrefix) {
2108
  if (!QtPassSettings::isShowProcessOutput()) {
2 ✔
2109
    return;
1 ✔
2110
  }
2111

2112
  QStringList lines = output.split('\n', Qt::SkipEmptyParts);
1 ✔
2113
  for (QString &line : lines) {
2 ✔
2114
    // Right-trim only: remove trailing CR and whitespace, preserve leading
2115
    // indentation
2116
    line.remove('\r');
1 ✔
2117
    while (!line.isEmpty() && line.back().isSpace()) {
2 ✔
2118
      line.chop(1);
×
2119
    }
2120
    if (line.isEmpty()) {
1 ✔
2121
      continue;
×
2122
    }
2123

2124
    m_outputCounter++;
1 ✔
2125
    QString lineNumber = QString::number(m_outputCounter);
1 ✔
2126

2127
    QColor textColor =
2128
        isError ? QColor(Qt::red)
1 ✔
2129
                : m_processOutputEdit->palette().color(QPalette::Text);
2 ✔
2130
    QString colorHex = textColor.name();
1 ✔
2131
    // Apply the optional prefix per line so multi-line output stays
2132
    // attributed to its command (e.g. all 3 lines of a `git push` show
2133
    // "git push: ..." rather than only the first).
2134
    QString prefixed =
2135
        linePrefix.isEmpty() ? line : linePrefix + QStringLiteral(": ") + line;
2 ✔
2136
    QString coloredOutput =
2137
        QString("<span style=\"color: %1;\">%2: %3</span>")
1 ✔
2138
            .arg(colorHex, lineNumber, prefixed.toHtmlEscaped());
2 ✔
2139

2140
    m_processOutputEdit->append(coloredOutput);
1 ✔
2141
  }
2142

2143
  limitOutputLines();
1 ✔
2144

2145
  if (m_autoScroll) {
1 ✔
2146
    m_processOutputEdit->verticalScrollBar()->setValue(
2 ✔
2147
        m_processOutputEdit->verticalScrollBar()->maximum());
1 ✔
2148
  }
2149
}
2150

2151
/**
2152
 * @brief Handles process output from the Pass executor.
2153
 *
2154
 * Called when any non-sensitive process completes. Filters out password-
2155
 * related commands (pass show, insert, etc.) and delegates to
2156
 * appendProcessOutput.
2157
 *
2158
 * @param output The stdout/stderr text from the process.
2159
 * @param isError true if this is error output (stderr).
2160
 * @param pid The process ID identifying which command ran.
2161
 */
2162
void MainWindow::onProcessOutput(const QString &output, bool isError,
2 ✔
2163
                                 Enums::PROCESS pid) {
2164
  appendProcessOutput(output, isError, getProcessName(pid));
2 ✔
2165
}
2 ✔
2166

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

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

2258
/**
2259
 * @brief Updates the visibility of the process output panel.
2260
 *
2261
 * Shows or hides the process output widget based on the user's
2262
 * showProcessOutput setting.
2263
 */
2264
void MainWindow::updateProcessOutputVisibility() {
3 ✔
2265
  m_processOutputDock->setVisible(QtPassSettings::isShowProcessOutput());
3 ✔
2266
}
3 ✔
2267

2268
/**
2269
 * @brief Limits the output panel to max lines, trimming old excess.
2270
 *
2271
 * Removes the oldest lines when the document exceeds MaxOutputLines (1000).
2272
 * Called after each append to prevent unbounded growth.
2273
 */
2274
void MainWindow::limitOutputLines() {
1 ✔
2275
  QTextDocument *doc = m_processOutputEdit->document();
1 ✔
2276
  int excess = doc->blockCount() - MaxOutputLines;
1 ✔
2277
  if (excess <= 0) {
1 ✔
2278
    return;
1 ✔
2279
  }
2280

2281
  QTextCursor cursor(doc);
×
2282
  cursor.movePosition(QTextCursor::Start);
×
2283
  cursor.movePosition(QTextCursor::NextBlock, QTextCursor::KeepAnchor, excess);
×
2284
  cursor.removeSelectedText();
×
2285
}
×
2286

2287
/**
2288
 * @brief Clears the process output panel.
2289
 *
2290
 * Clears all output, resets the line counter, and re-enables auto-scroll.
2291
 */
2292
void MainWindow::on_clearOutputButton_clicked() {
×
2293
  m_processOutputEdit->clear();
×
2294
  m_outputCounter = 0;
×
2295
  m_autoScroll = true;
×
2296
}
×
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