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

IJHack / QtPass / 43781999534

16 Nov 2026 12:42AM UTC coverage: 72.784% (+0.2%) from 72.543%
43781999534

push

github

web-flow
Ctrl+C copies the text selected in the shown entry (#2216)

Backport of #2202 (ae511edb2) to 1.8: the window-wide Copy shortcut goes to copySelectionOrPassword(), which copies a focused text view's or selectable label's selection (the label through QtPass::copyTextToClipboard(), so an OTP code gets the autoclear) and otherwise the password, as before.

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

10 of 11 new or added lines in 1 file covered. (90.91%)

20 existing lines in 2 files now uncovered.

5739 of 7885 relevant lines covered (72.78%)

152.1 hits per line

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

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

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

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

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

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

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

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

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

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

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

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

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

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

128
  updateProfileBox();
37 ✔
129

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

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

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

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

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

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

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

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

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

195
  setUiElementsEnabled(true);
37 ✔
196

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

524
  updateProfileBox();
4 ✔
525
  const AppSettings s = QtPassSettings::load();
4 ✔
526
  // A content search still running searched the old store, and its matches
527
  // would be listed for this one: onGrepFinished() cannot tell. Cancelled,
528
  // and content-search results on screen go with it (clearPanel()).
529
  cancelContentSearch();
4 ✔
530
  if (m_grep.cancelSearch()) {
531
    QApplication::restoreOverrideCursor();
×
532
  }
533
  clearPanel(false);
4 ✔
534
  proxyModel.setStore(s.passStore);
4 ✔
535
  ui->treeView->setRootIndex(proxyModel.rootIndexFor(s.passStore));
4 ✔
536
  deselect();
4 ✔
537
  ui->treeView->setCurrentIndex(QModelIndex());
4 ✔
538

539
  Pass *activePass = QtPassSettings::getPass();
4 ✔
540
  activePass->updateEnv();
4 ✔
541
  proxyModel.setPass(activePass);
4 ✔
542
  clearPanelTimer.setInterval(MS_PER_SECOND * s.autoclearPanelSeconds);
4 ✔
543
  m_qtPass->setClipboardTimer();
4 ✔
544

545
  updateGitButtonVisibility();
4 ✔
546
  updateOtpButtonVisibility();
4 ✔
547
  updateGrepButtonVisibility();
4 ✔
548
  updateProcessOutputVisibility();
4 ✔
549
  if (s.useTrayIcon && m_tray == nullptr) {
4 ✔
550
    initTrayIcon();
×
551
  } else if (!s.useTrayIcon && m_tray != nullptr) {
4 ✔
552
    destroyTrayIcon();
×
553
  }
554

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

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

579
/**
580
 * @brief MainWindow::onPush do a git push
581
 */
582
void MainWindow::onPush() {
4 ✔
583
  if (QtPassSettings::isUseGit()) {
4 ✔
584
    ui->statusBar->showMessage(tr("Updating password-store"), 2000);
4 ✔
585
    QtPassSettings::getPass()->GitPush();
4 ✔
586
  }
587
}
4 ✔
588

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

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

632
// With automatic push, the push is queued first and the refresh would start as
633
// soon as it ends, emptying the browser before a failed push's error was
634
// painted. So the refresh waits for the push. It claims the panel now, as its
635
// decrypt would: deselecting meanwhile drops it.
636
void MainWindow::refreshAfterInsert() {
5 ✔
637
  const QModelIndex index = getCurrentTreeViewIndex();
5 ✔
638
  const QString file = getFile(index, true);
5 ✔
639
  Pass *pass = QtPassSettings::getPass();
5 ✔
640
  if (!file.isEmpty() && pass->isPushing()) {
10 ✔
641
    m_refreshAfterPush = file;
4 ✔
642
    m_refreshAfterPushOwner = pass;
643
    m_shownFile = file;
4 ✔
644
    return;
645
  }
646
  on_treeView_clicked(index);
1 ✔
647
}
648

649
// Runs once the last push went through, by name (the save's rewrite of the
650
// file may have replaced its row in the tree), and only while the entry still
651
// holds the panel and nothing else is queued: queued work would run first, and
652
// the refresh would empty the browser of its outcome. A failed push dropped it
653
// (dropRefreshAfterPush()).
654
void MainWindow::gitPushFinished(Pass *pass) {
6 ✔
655
  if (m_refreshAfterPush.isEmpty() || m_refreshAfterPushOwner != pass ||
16 ✔
656
      pass->isPushing()) {
657
    return;
3 ✔
658
  }
659
  const QString file = m_refreshAfterPush;
660
  dropRefreshAfterPush();
3 ✔
661
  if (file == m_shownFile && pass->isIdle()) {
3 ✔
662
    ui->passwordName->setText(file);
1 ✔
663
    pass->Show(file);
2 ✔
664
  }
665
}
666

667
void MainWindow::dropRefreshAfterPush() {
7 ✔
668
  m_refreshAfterPush.clear();
7 ✔
669
  m_refreshAfterPushOwner = nullptr;
670
}
7 ✔
671

672
/**
673
 * @brief MainWindow::on_treeView_doubleClicked when doubleclicked on
674
 * TreeViewItem, open the edit Window
675
 * @param index
676
 */
677
void MainWindow::on_treeView_doubleClicked(const QModelIndex &index) {
1 ✔
678
  QFileInfo fileOrFolder =
679
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
1 ✔
680

681
  if (fileOrFolder.isFile()) {
1 ✔
682
    editPassword(getFile(index, true));
2 ✔
683
  }
684
}
1 ✔
685

686
/**
687
 * @brief MainWindow::deselect clear the selection, password and copy buffer
688
 */
689
void MainWindow::deselect() {
6 ✔
690
  m_currentDir = "";
6 ✔
691
  m_shownFile.clear();
6 ✔
692
  cancelOtpRequest();
6 ✔
693
  m_qtPass->clearClipboard();
6 ✔
694
  ui->treeView->clearSelection();
6 ✔
695
  ui->actionEdit->setEnabled(false);
6 ✔
696
  ui->actionDelete->setEnabled(false);
6 ✔
697
  ui->passwordName->setText("");
6 ✔
698
  clearPanel(false);
6 ✔
699
}
6 ✔
700

701
void MainWindow::executeWrapperStarted() {
15 ✔
702
  m_displayPanel->clear();
15 ✔
703
  ui->textBrowser->clear();
15 ✔
704
  setUiElementsEnabled(false);
15 ✔
705
  clearPanelTimer.stop();
15 ✔
706
  if (QtPassSettings::isShowProcessOutput()) {
15 ✔
707
    m_processOutputDock->setVisible(true);
2 ✔
708
  }
709
}
15 ✔
710

711
/**
712
 * @brief Handles displaying parsed password entry content in the main window.
713
 * @example
714
 * void result = MainWindow::passShowHandler(p_output);
715
 * // Updates the UI with parsed fields and emits
716
 * passShowHandlerFinished(output)
717
 *
718
 * @param p_output - The raw output text containing the password entry data.
719
 * @return void - This function does not return a value.
720
 */
721
void MainWindow::passShowHandler(const QString &p_output) {
7 ✔
722
  const AppSettings s = QtPassSettings::load();
7 ✔
723
  QStringList templ =
724
      s.useTemplate ? s.passTemplate.split("\n") : QStringList();
7 ✔
725
  bool allFields = s.useTemplate && s.templateAllFields;
7 ✔
726
  FileContent fileContent = FileContent::parse(p_output, templ, allFields);
7 ✔
727
  QString output = p_output;
728
  // Display variant: empty when the password line is itself an otpauth URI, so
729
  // the shared secret is neither rendered nor copied to the clipboard.
730
  QString password = fileContent.getPasswordForDisplay();
7 ✔
731

732
  // set clipped text
733
  //
734
  // Skipped for an OTP request: the user asked for a one-time code, not the
735
  // password, and writing both in one event-loop turn can leave the Windows
736
  // clipboard empty (two OleSetClipboard calls back to back).
737
  if (!m_otpRequestPending) {
7 ✔
738
    m_qtPass->setClippedText(password, p_output);
7 ✔
739
  }
740

741
  // first clear the current view:
742
  m_displayPanel->clear();
7 ✔
743

744
  // show what is needed:
745
  if (s.hideContent) {
7 ✔
746
    output = "***" + tr("Content hidden") + "***";
×
747
  } else if (!s.displayAsIs) {
7 ✔
748
    m_displayPanel->displayFields(password, fileContent.getNamedValues(), s,
12 ✔
749
                                  s.useOtp ? fileContent.getOtpUri()
6 ✔
750
                                           : QString());
751
    output = fileContent.getRemainingDataForDisplay();
12 ✔
752
  }
753

754
  if (s.useAutoclearPanel) {
7 ✔
755
    clearPanelTimer.start();
×
756
  }
757

758
  emit passShowHandlerFinished(output);
7 ✔
759
  setUiElementsEnabled(true);
7 ✔
760
}
14 ✔
761

762
/**
763
 * @brief Generates a one-time password from a decrypted entry and copies it.
764
 *
765
 * Connected as a one-shot to Pass::finishedShow by onOtp(). passShowHandler is
766
 * connected first, so by the time this runs the panel has already been
767
 * repainted and the UI re-enabled.
768
 *
769
 * @param p_output - The decrypted entry content.
770
 * @return void - This function does not return a value.
771
 */
772
void MainWindow::otpFromFileToClipboard(const QString &p_output) {
×
773
  disconnectSingleShot(QtPassSettings::getPass(), &Pass::finishedShow, this,
×
774
                       &MainWindow::otpFromFileToClipboard);
775
  // A failed decrypt never fires finishedShow, and Qt::SingleShotConnection
776
  // only self-disconnects when it does fire, so a connection armed by an
777
  // earlier failed request can still be live here. Ignore it rather than
778
  // hijacking an unrelated entry's decrypted content.
779
  if (!m_otpRequestPending) {
×
780
    return;
×
781
  }
782
  // finishedShow carries no request identity, so make sure this decrypt is the
783
  // one we asked for and not a tree click that happened to land first.
784
  if (m_otpRequestFile != getFile(ui->treeView->currentIndex(), true)) {
×
785
    cancelOtpRequest();
×
786
    setUiElementsEnabled(true);
×
787
    return;
×
788
  }
789
  m_otpRequestPending = false;
×
790
  m_otpRequestFile.clear();
×
791

792
  if (p_output.isEmpty()) {
×
793
    // Distinguish "could not read the entry" from "entry has no OTP".
794
    flashText(tr("Could not decrypt this password entry"), true);
×
795
    setUiElementsEnabled(true);
×
796
    return;
×
797
  }
798

799
  // passShowHandler is connected first, so it has already repainted the panel
800
  // for this same finishedShow. When it rendered the OTP row the current code
801
  // is derived and cached, so reuse it instead of re-loading settings and
802
  // re-parsing p_output (mirrors onOtp()'s fast path). Falls through to a fresh
803
  // parse when no OTP row is shown (hideContent / displayAsIs / no OTP field).
804
  const QString shown = m_displayPanel->currentOtpCode();
×
805
  if (!shown.isEmpty()) {
×
806
    m_qtPass->copyTextToClipboard(shown);
×
807
    showStatusMessage(tr("OTP code copied to clipboard"));
×
808
    setUiElementsEnabled(true);
×
809
    return;
810
  }
811

812
  const AppSettings s = QtPassSettings::load();
×
813
  // Parse with the same template settings passShowHandler uses, so an OTP
814
  // field is recognised identically in both paths.
815
  const QStringList templ =
816
      s.useTemplate ? s.passTemplate.split("\n") : QStringList();
×
817
  const bool allFields = s.useTemplate && s.templateAllFields;
×
818
  const FileContent fileContent =
819
      FileContent::parse(p_output, templ, allFields);
×
820

821
  const std::optional<Totp::Settings> settings =
822
      Totp::parse(fileContent.getOtpUri());
×
823
  if (settings.has_value()) {
×
824
    m_qtPass->copyTextToClipboard(Totp::generateNow(*settings));
×
825
    showStatusMessage(tr("OTP code copied to clipboard"));
×
826
  } else {
827
    flashText(tr("No OTP code found in this password entry"), true);
×
828
  }
829
  setUiElementsEnabled(true);
×
830
}
×
831

832
/**
833
 * @brief MainWindow::clearPanel hide the information from shoulder surfers
834
 */
835
void MainWindow::clearPanel(bool notify) {
12 ✔
836
  m_displayPanel->clear();
12 ✔
837
  const bool grepWasVisible = ui->grepResultsList->isVisible();
12 ✔
838
  ui->grepResultsList->clear();
12 ✔
839
  if (grepWasVisible) {
12 ✔
840
    ui->grepResultsList->setVisible(false);
1 ✔
841
    ui->treeView->setVisible(true);
1 ✔
842
    if (m_grep.inGrepMode()) {
1 ✔
843
      // Left as the button leaves it: a search still running would otherwise
844
      // count as busy, keeping the wait cursor, and hand its result to a
845
      // content search entered meanwhile.
846
      cancelContentSearch();
1 ✔
847
      if (m_grep.leaveGrepMode()) {
848
        QApplication::restoreOverrideCursor();
1 ✔
849
      }
850
      ui->grepButton->blockSignals(true);
1 ✔
851
      ui->grepButton->setChecked(false);
1 ✔
852
      ui->grepButton->blockSignals(false);
1 ✔
853
      ui->lineEdit->blockSignals(true);
1 ✔
854
      ui->lineEdit->clear();
1 ✔
855
      ui->lineEdit->blockSignals(false);
1 ✔
856
      ui->lineEdit->setPlaceholderText(tr("Search Password"));
2 ✔
857
    }
858
  }
859
  if (notify) {
12 ✔
860
    QString output = "***" + tr("Password and Content hidden") + "***";
×
861
    ui->textBrowser->setHtml(output);
×
862
  } else {
863
    ui->textBrowser->setHtml("");
24 ✔
864
  }
865
}
12 ✔
866

867
/**
868
 * @brief MainWindow::setUiElementsEnabled enable or disable the relevant UI
869
 * elements
870
 * @param state
871
 */
872
void MainWindow::setUiElementsEnabled(bool state) {
99 ✔
873
  // Arm the watchdog while the UI is disabled; disarm once re-enabled.
874
  if (state) {
99 ✔
875
    m_uiWatchdog.stop();
82 ✔
876
  } else {
877
    m_uiWatchdog.start();
17 ✔
878
  }
879
  ui->treeView->setEnabled(state);
99 ✔
880
  ui->lineEdit->setEnabled(state);
99 ✔
881
  ui->actionAddPassword->setEnabled(state);
99 ✔
882
  ui->actionAddFolder->setEnabled(state);
99 ✔
883
  ui->actionUsers->setEnabled(state);
99 ✔
884
  ui->actionConfig->setEnabled(state);
99 ✔
885
  // is a file selected?
886
  state &= ui->treeView->currentIndex().isValid();
198 ✔
887
  ui->actionDelete->setEnabled(state);
99 ✔
888
  ui->actionEdit->setEnabled(state);
99 ✔
889
  updateGitButtonVisibility();
99 ✔
890
  // `state` is now "UI enabled AND a file is selected", which is exactly when
891
  // generating an OTP makes sense.
892
  updateOtpButtonVisibility(state);
99 ✔
893
}
99 ✔
894

895
/**
896
 * @brief Restores the main window geometry, state, position, size, and
897
 * tray/icon settings from saved application settings.
898
 * @example
899
 * MainWindow window;
900
 * window.restoreWindow();
901
 *
902
 * @return void - This function does not return a value.
903
 */
904
void MainWindow::restoreWindow() {
40 ✔
905
  QByteArray geometry = QtPassSettings::getGeometry(saveGeometry());
40 ✔
906
  restoreGeometry(geometry);
40 ✔
907
  QByteArray savestate = QtPassSettings::getSavestate(saveState());
40 ✔
908
  restoreState(savestate);
40 ✔
909
  QPoint position = QtPassSettings::getPos(pos());
40 ✔
910
  move(position);
40 ✔
911
  QSize newSize = QtPassSettings::getSize(size());
40 ✔
912
  resize(newSize);
40 ✔
913
  const AppSettings s = QtPassSettings::load();
40 ✔
914
  if (s.maximized) {
40 ✔
915
    showMaximized();
×
916
  }
917

918
  if (s.alwaysOnTop) {
40 ✔
919
    Qt::WindowFlags flags = windowFlags();
920
    setWindowFlags(flags | Qt::WindowStaysOnTopHint);
×
921
    show();
×
922
  }
923

924
  if (s.useTrayIcon && m_tray == nullptr) {
40 ✔
925
    initTrayIcon();
2 ✔
926
    // Minimized to the tray only when there is one: without a system tray
927
    // initTrayIcon() gave up, and a hidden window could not be brought back.
928
    if (s.startMinimized && m_tray != nullptr) {
2 ✔
929
      // since we are still in constructor, can't directly hide
930
      QTimer::singleShot(10, this, SLOT(hide()));
×
931
    }
932
  } else if (!s.useTrayIcon && m_tray != nullptr) {
38 ✔
933
    destroyTrayIcon();
×
934
  }
935
}
80 ✔
936

937
/**
938
 * @brief MainWindow::on_configButton_clicked run Mainwindow::config
939
 */
940
void MainWindow::onConfig() { config(); }
×
941

942
/**
943
 * @brief Executes when the string in the search box changes, collapses the
944
 * TreeView
945
 * @param arg1
946
 */
947
void MainWindow::on_lineEdit_textChanged(const QString &arg1) {
7 ✔
948
  if (m_grep.inGrepMode())
7 ✔
949
    return;
950
  ui->statusBar->showMessage(tr("Looking for: %1").arg(arg1), 1000);
2 ✔
951
  ui->treeView->expandAll();
1 ✔
952
  clearPanel(false);
1 ✔
953
  ui->passwordName->setText("");
2 ✔
954
  ui->actionEdit->setEnabled(false);
1 ✔
955
  ui->actionDelete->setEnabled(false);
1 ✔
956
  searchTimer.start();
1 ✔
957
}
958

959
/**
960
 * @brief MainWindow::onTimeoutSearch Fired when search is finished or too much
961
 * time from two keypresses is elapsed
962
 */
963
void MainWindow::onTimeoutSearch() {
1 ✔
964
  QString query = ui->lineEdit->text();
1 ✔
965

966
  if (query.isEmpty()) {
1 ✔
967
    ui->treeView->collapseAll();
×
968
    deselect();
×
969
  }
970

971
  query.replace(QStringLiteral(" "), ".*");
2 ✔
972
  QRegularExpression regExp(query, QRegularExpression::CaseInsensitiveOption);
1 ✔
973
  if (!regExp.isValid())
1 ✔
974
    return;
975
  proxyModel.setFilterRegularExpression(regExp);
1 ✔
976
  ui->treeView->setRootIndex(
1 ✔
977
      proxyModel.rootIndexFor(QtPassSettings::getPassStore()));
2 ✔
978

979
  if (proxyModel.rowCount() > 0 && !query.isEmpty()) {
1 ✔
980
    selectFirstFile();
1 ✔
981
  } else {
982
    ui->actionEdit->setEnabled(false);
×
983
    ui->actionDelete->setEnabled(false);
×
984
  }
985
}
1 ✔
986

987
/**
988
 * @brief MainWindow::on_lineEdit_returnPressed get searching
989
 *
990
 * Select the first possible file in the tree
991
 */
992
void MainWindow::on_lineEdit_returnPressed() {
7 ✔
993
#ifdef QT_DEBUG
994
  dbg() << "on_lineEdit_returnPressed" << proxyModel.rowCount();
995
#endif
996

997
  if (m_grep.inGrepMode()) {
7 ✔
998
    const QString query = ui->lineEdit->text();
6 ✔
999
    if (!query.isEmpty()) {
6 ✔
1000
      ui->grepResultsList->clear();
4 ✔
1001
      ui->statusBar->showMessage(tr("Searching…"));
8 ✔
1002
      if (m_grep.beginSearch()) {
1003
        QApplication::setOverrideCursor(Qt::WaitCursor);
4 ✔
1004
      }
1005
      QtPassSettings::getPass()->Grep(query, ui->grepCaseButton->isChecked());
8 ✔
1006
    } else {
1007
      cancelContentSearch();
2 ✔
1008
      if (m_grep.cancelSearch()) {
1009
        QApplication::restoreOverrideCursor();
1 ✔
1010
      }
1011
      ui->grepResultsList->clear();
2 ✔
1012
      ui->grepResultsList->setVisible(false);
2 ✔
1013
      ui->treeView->setVisible(true);
2 ✔
1014
    }
1015
    return;
1016
  }
1017

1018
  if (proxyModel.rowCount() > 0) {
1 ✔
1019
    selectFirstFile();
1 ✔
1020
    on_treeView_clicked(ui->treeView->currentIndex());
1 ✔
1021
  }
1022
}
1023

1024
/**
1025
 * @brief Toggle grep (content search) mode.
1026
 */
1027
void MainWindow::on_grepButton_toggled(bool checked) {
8 ✔
1028
  const AppSettings s = QtPassSettings::load();
8 ✔
1029
  if (checked) {
8 ✔
1030
    m_grep.enterGrepMode();
1031
    ui->lineEdit->setPlaceholderText(tr("Search content (regex)"));
10 ✔
1032
    // The regex dialect depends on the backend (see Pass::Grep): the pass
1033
    // backend uses POSIX BRE via `pass grep`, the native backend uses PCRE.
1034
    ui->lineEdit->setToolTip(
5 ✔
1035
        s.usePass
5 ✔
1036
            ? tr("Content search uses POSIX basic regular expressions "
10 ✔
1037
                 "(pass grep).")
1038
            : tr("Content search uses Perl-compatible regular expressions "
1039
                 "(PCRE)."));
1040
    ui->lineEdit->clear();
5 ✔
1041
    searchTimer.stop();
5 ✔
1042
    proxyModel.setFilterRegularExpression(QRegularExpression());
5 ✔
1043
    ui->treeView->setRootIndex(proxyModel.rootIndexFor(s.passStore));
5 ✔
1044
    ui->grepResultsList->setVisible(false);
5 ✔
1045
    // Keep treeView visible until results arrive
1046
  } else {
1047
    cancelContentSearch();
3 ✔
1048
    if (m_grep.leaveGrepMode()) {
1049
      QApplication::restoreOverrideCursor();
1 ✔
1050
    }
1051
    searchTimer.stop();
3 ✔
1052
    ui->lineEdit->blockSignals(true);
3 ✔
1053
    ui->lineEdit->clear();
3 ✔
1054
    ui->lineEdit->blockSignals(false);
3 ✔
1055
    ui->lineEdit->setPlaceholderText(tr("Search Password"));
6 ✔
1056
    ui->lineEdit->setToolTip(QString());
6 ✔
1057
    ui->grepResultsList->clear();
3 ✔
1058
    ui->grepResultsList->setVisible(false);
3 ✔
1059
    ui->treeView->setVisible(true);
3 ✔
1060
    proxyModel.setFilterRegularExpression(QRegularExpression());
3 ✔
1061
    ui->treeView->setRootIndex(proxyModel.rootIndexFor(s.passStore));
3 ✔
1062
  }
1063
}
8 ✔
1064

1065
/**
1066
 * @brief Display grep results in grepResultsList.
1067
 */
1068
void MainWindow::onGrepFinished(
6 ✔
1069
    const QList<QPair<QString, QStringList>> &results) {
1070
  // Both backends stay connected, each with its own search: a search the
1071
  // other backend was still running when Settings switched backends is not
1072
  // this one, whatever the controller's state, and searched another store.
1073
  // Dropped before it can end (or be taken for) the current search.
1074
  if (const QObject *from = sender();
6 ✔
1075
      from != nullptr && from != QtPassSettings::getPass()) {
6 ✔
1076
    return;
6 ✔
1077
  }
1078
  const GrepSearchController::FinishOutcome outcome = m_grep.finishSearch();
1079
  if (outcome.restoreCursor) {
5 ✔
1080
    QApplication::restoreOverrideCursor();
1 ✔
1081
  }
1082
  // Re-enable the UI before the discard check so a cancelled search can never
1083
  // leave controls disabled.
1084
  setUiElementsEnabled(true);
5 ✔
1085
  if (outcome.discard) {
5 ✔
1086
    return;
1087
  }
1088
  if (!m_grep.inGrepMode())
1 ✔
1089
    return;
1090
  ui->grepResultsList->clear();
1 ✔
1091
  if (results.isEmpty()) {
1 ✔
1092
    ui->statusBar->showMessage(tr("No matches found."), 3000);
2 ✔
1093
    ui->grepResultsList->setVisible(false);
1 ✔
1094
    ui->treeView->setVisible(true);
1 ✔
1095
    return;
1 ✔
1096
  }
1097
  const AppSettings s = QtPassSettings::load();
×
1098
  const bool hideContent = s.hideContent;
×
1099
  int totalLines = 0;
1100
  for (const auto &pair : results) {
×
1101
    auto *entryItem = new QTreeWidgetItem(ui->grepResultsList);
×
1102
    entryItem->setText(0, pair.first);
×
1103
    entryItem->setData(0, Qt::UserRole, pair.first);
×
1104
    for (const QString &line : pair.second) {
×
1105
      auto *lineItem = new QTreeWidgetItem(entryItem);
×
1106
      lineItem->setText(0, hideContent ? "***" + tr("Content hidden") + "***"
×
1107
                                       : line);
1108
      lineItem->setData(0, Qt::UserRole, pair.first);
×
1109
      ++totalLines;
×
1110
    }
1111
  }
1112
  ui->grepResultsList->expandAll();
×
1113
  ui->treeView->setVisible(false);
×
1114
  ui->grepResultsList->setVisible(true);
×
1115
  ui->statusBar->showMessage(
×
1116
      tr("Found %n match(es)", nullptr, totalLines) + " " +
×
1117
          tr("in %n entr(ies).", nullptr, static_cast<int>(results.size())),
×
1118
      3000);
1119
  if (s.useAutoclearPanel)
×
1120
    clearPanelTimer.start();
×
1121
}
×
1122

1123
/**
1124
 * @brief Navigate to the password entry when a grep result is clicked.
1125
 */
1126
void MainWindow::on_grepResultsList_itemClicked(QTreeWidgetItem *item,
1 ✔
1127
                                                int /*column*/) {
1128
  const AppSettings s = QtPassSettings::load();
1 ✔
1129
  const QString entry = item->data(0, Qt::UserRole).toString();
1 ✔
1130
  if (entry.isEmpty())
1 ✔
1131
    return;
1132
  const QString fullPath =
1133
      QDir::cleanPath(QDir(s.passStore).filePath(entry + ".gpg"));
2 ✔
1134
  QModelIndex srcIndex = model.index(fullPath);
1 ✔
1135
  if (!srcIndex.isValid())
1136
    return;
1137
  QModelIndex proxyIndex = proxyModel.mapFromSource(srcIndex);
1 ✔
1138
  if (!proxyIndex.isValid())
1139
    return;
1140
  ui->treeView->setCurrentIndex(proxyIndex);
1 ✔
1141
  on_treeView_clicked(proxyIndex);
1 ✔
1142
  if (s.hideContent || s.useAutoclearPanel)
1 ✔
1143
    ui->grepResultsList->clear();
×
1144
  ui->grepResultsList->setVisible(false);
1 ✔
1145
  ui->treeView->setVisible(true);
1 ✔
1146
  ui->treeView->scrollTo(proxyIndex);
1 ✔
1147
  ui->treeView->setFocus();
1 ✔
1148
}
1 ✔
1149

1150
/**
1151
 * @brief Stop a running content search of the native backend.
1152
 *
1153
 * The `pass` backend's `pass grep` runs in the process queue and is not
1154
 * stopped here.
1155
 */
1156
void MainWindow::cancelContentSearch() {
10 ✔
1157
  QtPassSettings::getImitatePass()->CancelGrep();
10 ✔
1158
}
10 ✔
1159

1160
/**
1161
 * @brief MainWindow::selectFirstFile select the first possible file in the
1162
 * tree
1163
 */
1164
void MainWindow::selectFirstFile() {
2 ✔
1165
  QModelIndex index = proxyModel.rootIndexFor(QtPassSettings::getPassStore());
4 ✔
1166
  index = firstFile(index);
2 ✔
1167
  ui->treeView->setCurrentIndex(index);
2 ✔
1168
}
2 ✔
1169

1170
/**
1171
 * @brief MainWindow::firstFile return location of first possible file
1172
 * @param parentIndex
1173
 * @return QModelIndex
1174
 */
1175
auto MainWindow::firstFile(QModelIndex parentIndex) -> QModelIndex {
2 ✔
1176
  int numRows = proxyModel.rowCount(parentIndex);
2 ✔
1177
  for (int row = 0; row < numRows; ++row) {
2 ✔
1178
    QModelIndex index = proxyModel.index(row, 0, parentIndex);
2 ✔
1179
    if (model.fileInfo(proxyModel.mapToSource(index)).isFile()) {
2 ✔
1180
      return index;
2 ✔
1181
    }
1182
    if (proxyModel.hasChildren(index)) {
×
1183
      QModelIndex childFile = firstFile(index);
×
1184
      if (childFile.isValid())
1185
        return childFile;
×
1186
    }
1187
  }
1188
  return QModelIndex();
×
1189
}
1190

1191
/**
1192
 * @brief MainWindow::confirmPathInStore reject paths that resolve outside
1193
 * the password store and warn the user.
1194
 *
1195
 * Used before file/folder creation, move, and rename to stop user-typed
1196
 * names like "../../etc/passwd" or absolute paths from escaping the
1197
 * configured store root via the input dialogs.
1198
 *
1199
 * @param candidate Absolute candidate path to validate.
1200
 * @return true if the path is inside the password store; false otherwise (a
1201
 * warning dialog is shown in that case).
1202
 */
1203
auto MainWindow::confirmPathInStore(const QString &candidate) -> bool {
×
1204
  if (PathValidator::isPathInStore(QtPassSettings::getPassStore(), candidate)) {
×
1205
    return true;
1206
  }
1207
  QMessageBox::warning(this, tr("Invalid name"),
×
1208
                       tr("That name would resolve outside the password "
×
1209
                          "store. Please choose a different name."));
1210
  return false;
×
1211
}
1212

1213
/**
1214
 * @brief MainWindow::setPassword open passworddialog
1215
 * @param file which pgp file
1216
 * @param isNew insert (not update)
1217
 */
1218
void MainWindow::setPassword(const QString &file, bool isNew) {
1 ✔
1219
  const AppSettings s = QtPassSettings::load();
1 ✔
1220
  PasswordDialog d(QtPassSettings::getPass(), s, file, isNew, this);
1 ✔
1221

1222
  if (isNew) {
1 ✔
1223
    const QString storePath = s.passStore;
1224
    QString folder = Util::getDir(ui->treeView->currentIndex(), false, model,
×
1225
                                  proxyModel, s.passStore);
×
1226
    if (folder.isEmpty()) {
×
1227
      folder = storePath;
×
1228
    }
1229
    QHash<QString, QStringList> templates =
1230
        TemplateIO::readTemplates(storePath);
×
1231
    if (!templates.isEmpty()) {
1232
      QString defaultTemplate =
1233
          TemplateIO::getFolderTemplate(folder, storePath);
×
1234
      d.setAvailableTemplates(templates, defaultTemplate);
×
1235
      new QShortcut(QKeySequence(Qt::CTRL | Qt::Key_T), &d,
×
1236
                    [&d]() { d.cycleTemplate(); });
×
1237
    }
1238
  }
×
1239

1240
  if (!d.exec()) {
1 ✔
1241
    ui->treeView->setFocus();
×
1242
  }
1243
}
1 ✔
1244

1245
/**
1246
 * @brief MainWindow::addPassword add a new password by showing a
1247
 * number of dialogs.
1248
 */
1249
void MainWindow::addPassword() {
×
1250
  const QString passStore = QtPassSettings::load().passStore;
×
1251
  bool ok;
1252
  QString dir = Util::getDir(ui->treeView->currentIndex(), true, model,
×
1253
                             proxyModel, passStore);
×
1254
  QString file = QInputDialog::getText(
1255
      this, tr("New file"),
×
1256
      tr("New password file: \n(Will be placed in %1 )")
×
1257
          .arg(passStore + Util::getDir(ui->treeView->currentIndex(), true,
×
1258
                                        model, proxyModel, passStore)),
×
1259
      QLineEdit::Normal, "", &ok);
×
1260
  if (!ok || file.isEmpty()) {
×
1261
    return;
1262
  }
1263
  file = dir + file;
×
1264
  if (!confirmPathInStore(passStore + file)) {
×
1265
    return;
1266
  }
1267
  setPassword(file);
×
1268
}
1269

1270
/**
1271
 * @brief MainWindow::onDelete remove password, if you are
1272
 * sure.
1273
 */
1274
void MainWindow::onDelete() {
×
1275
  QModelIndex currentIndex = ui->treeView->currentIndex();
×
1276
  if (!currentIndex.isValid()) {
1277
    // This fixes https://github.com/IJHack/QtPass/issues/556
1278
    // Otherwise the entire password directory would be deleted if
1279
    // nothing is selected in the tree view.
1280
    return;
×
1281
  }
1282

1283
  QFileInfo fileOrFolder =
1284
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
1285
  QString file = "";
×
1286
  bool isDir = false;
1287

1288
  if (fileOrFolder.isFile()) {
×
1289
    file = getFile(ui->treeView->currentIndex(), true);
×
1290
  } else {
1291
    file = Util::getDir(ui->treeView->currentIndex(), true, model, proxyModel,
×
1292
                        QtPassSettings::getPassStore());
×
1293
    isDir = true;
1294
  }
1295

1296
  QString dirMessage = tr(" and the whole content?");
1297
  if (isDir) {
×
1298
    QDirIterator it(model.rootPath() + QDir::separator() + file,
×
1299
                    QDirIterator::Subdirectories);
×
1300
    bool okDir = true;
1301
    while (it.hasNext() && okDir) {
×
1302
      it.next();
×
1303
      if (QFileInfo(it.filePath()).isFile()) {
×
1304
        if (QFileInfo(it.filePath()).suffix() != "gpg") {
×
1305
          okDir = false;
1306
          dirMessage = tr(" and the whole content? <br><strong>Attention: "
×
1307
                          "there are unexpected files in the given folder, "
1308
                          "check them before continue.</strong>");
1309
        }
1310
      }
1311
    }
1312
  }
×
1313

1314
  if (QMessageBox::question(
×
1315
          this, isDir ? tr("Delete folder?") : tr("Delete password?"),
×
1316
          tr("Are you sure you want to delete %1%2?")
×
1317
              .arg(QDir::separator() + file, isDir ? dirMessage : "?"),
×
1318
          QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) {
1319
    return;
1320
  }
1321

1322
  QtPassSettings::getPass()->Remove(file, isDir);
×
1323
}
×
1324

1325
/**
1326
 * @brief MainWindow::cancelOtpRequest abandon an in-flight OTP request.
1327
 *
1328
 * Connected to Pass::processErrorExit, and called from deselect(). A failed
1329
 * decrypt never emits finishedShow, and the error handler re-enables the UI —
1330
 * which stops the watchdog that was the only other thing clearing the flag.
1331
 * Left set, it permanently suppressed passShowHandler's copy-on-select and let
1332
 * the still-armed one-shot claim the next unrelated decrypt.
1333
 *
1334
 * The same failed decrypt would otherwise leave m_passwordCopyPending stuck
1335
 * (its only other reset is passwordFromFileToClipboard, which never runs when
1336
 * finishedShow is not emitted), permanently blocking Ctrl+C, so clear it here
1337
 * too. Unlike otpFromFileToClipboard, that slot has no pending-flag guard, so
1338
 * its single-shot connection must be torn down here as well — otherwise a
1339
 * connection left armed by the failed decrypt would claim the next unrelated
1340
 * finishedShow and copy the wrong entry to the clipboard. disconnectSingleShot
1341
 * is a no-op on Qt 6 (the never-fired connection persists until it emits), so
1342
 * disconnect unconditionally.
1343
 */
1344
void MainWindow::cancelOtpRequest() {
10 ✔
1345
  m_otpRequestPending = false;
10 ✔
1346
  m_otpRequestFile.clear();
10 ✔
1347
  disconnect(QtPassSettings::getPass(), &Pass::finishedShow, this,
10 ✔
1348
             &MainWindow::passwordFromFileToClipboard);
1349
  m_passwordCopyPending = false;
10 ✔
1350
}
10 ✔
1351

1352
/**
1353
 * @brief MainWindow::onOtp generate the selected entry's OTP code and copy it.
1354
 *
1355
 * Decrypts the entry once and derives the code in-process, so this works with
1356
 * either backend and on every platform. The code itself is produced by
1357
 * otpFromFileToClipboard once Pass::finishedShow arrives.
1358
 */
1359
void MainWindow::onOtp() {
×
1360
  QString file = getFile(ui->treeView->currentIndex(), true);
×
1361
  if (file.isEmpty()) {
×
1362
    flashText(tr("No password selected for OTP generation"), true);
×
1363
    return;
×
1364
  }
1365
  if (!QtPassSettings::isUseOtp()) {
×
1366
    // Normally unreachable (the action is hidden), but never fail silently.
1367
    flashText(tr("No OTP code found in this password entry"), true);
×
1368
    return;
×
1369
  }
1370

1371
  // Fast path: the panel already shows a live code for the selected entry, so
1372
  // there is nothing to decrypt. This also keeps the clipboard write single —
1373
  // going through Show() would let passShowHandler copy the password first, and
1374
  // two QClipboard::setMimeData calls in one event-loop turn can leave the
1375
  // Windows clipboard empty.
1376
  //
1377
  // Only when the panel is showing *this* entry: arrow-key navigation and
1378
  // right-clicking move the tree's currentIndex without emitting
1379
  // QTreeView::clicked, so the visible code can belong to a different account.
1380
  const QString shown =
1381
      (m_shownFile == file) ? m_displayPanel->currentOtpCode() : QString();
×
1382
  if (!shown.isEmpty()) {
×
1383
    m_qtPass->copyTextToClipboard(shown);
×
1384
    showStatusMessage(tr("OTP code copied to clipboard"));
×
1385
    return;
1386
  }
1387

1388
  // Fallback: no OTP row on screen, so decrypt once. The flag stops
1389
  // passShowHandler putting the password on the clipboard for a request that
1390
  // only asked for a code.
1391
  m_otpRequestPending = true;
×
1392
  m_otpRequestFile = file;
×
1393
  setUiElementsEnabled(false);
×
1394
  connectSingleShot(QtPassSettings::getPass(), &Pass::finishedShow, this,
×
1395
                    &MainWindow::otpFromFileToClipboard);
1396
  // passShowHandler repaints the panel for this Show too, so keep the marker in
1397
  // step or a second request would decrypt again instead of taking the fast
1398
  // path. Safe to set now: executeWrapperStarted() clears the panel on every
1399
  // command, so a failed decrypt leaves currentOtpCode() empty.
1400
  m_shownFile = file;
×
1401
  QtPassSettings::getPass()->Show(file);
×
1402
}
1403

1404
/**
1405
 * @brief MainWindow::onEdit try and edit (selected) password.
1406
 */
1407
void MainWindow::onEdit() {
×
1408
  QString file = getFile(ui->treeView->currentIndex(), true);
×
1409
  editPassword(file);
×
1410
}
×
1411

1412
/**
1413
 * @brief MainWindow::userDialog see MainWindow::onUsers()
1414
 * @param dir folder to edit users for.
1415
 */
1416
void MainWindow::userDialog(const QString &dir) {
×
1417
  if (!dir.isEmpty()) {
×
1418
    m_currentDir = dir;
×
1419
  }
1420
  onUsers();
×
1421
}
×
1422

1423
/**
1424
 * @brief MainWindow::onUsers edit users for the current
1425
 * folder,
1426
 * gets lists and opens UserDialog.
1427
 */
1428
void MainWindow::onUsers() {
×
1429
  QString dir = m_currentDir.isEmpty()
1430
                    ? Util::getDir(ui->treeView->currentIndex(), false, model,
×
1431
                                   proxyModel, QtPassSettings::getPassStore())
×
1432
                    : m_currentDir;
×
1433

1434
  UsersDialog d(QtPassSettings::getPass(), QtPassSettings::load(), dir, this);
×
1435
  if (!d.exec()) {
×
1436
    ui->treeView->setFocus();
×
1437
  }
1438
}
×
1439

1440
/**
1441
 * @brief MainWindow::messageAvailable we have some text/message/search to do.
1442
 * @param message
1443
 */
1444
void MainWindow::messageAvailable(const QString &message) {
×
1445
  show();
×
1446
  raise();
×
1447
  if (message.isEmpty()) {
×
1448
    focusInput();
×
1449
  } else {
1450
    ui->treeView->expandAll();
×
1451
    ui->lineEdit->setText(message);
×
1452
    on_lineEdit_returnPressed();
×
1453
  }
1454
}
×
1455

1456
/**
1457
 * @brief MainWindow::generateKeyPair internal gpg keypair generator . .
1458
 * @param batch
1459
 * @param keygenWindow
1460
 */
1461
void MainWindow::generateKeyPair(const QString &batch, QDialog *keygenWindow) {
×
1462
  m_keyGenDialog = keygenWindow;
1463
  emit generateGPGKeyPair(batch);
×
1464
}
×
1465

1466
/**
1467
 * @brief MainWindow::updateProfileBox update the list of profiles, optionally
1468
 * select a more appropriate one to view too
1469
 */
1470
void MainWindow::updateProfileBox() {
41 ✔
1471
  QHash<QString, QHash<QString, QString>> profiles =
1472
      QtPassSettings::getProfiles();
41 ✔
1473

1474
  if (profiles.isEmpty()) {
1475
    ui->profileWidget->hide();
41 ✔
1476
  } else {
1477
    ui->profileWidget->show();
×
1478
    ui->profileBox->setEnabled(profiles.size() > 1);
×
1479
    ui->profileBox->clear();
×
1480
    QHashIterator<QString, QHash<QString, QString>> i(profiles);
×
1481
    while (i.hasNext()) {
×
1482
      i.next();
1483
      if (!i.key().isEmpty()) {
×
1484
        ui->profileBox->addItem(i.key());
×
1485
      }
1486
    }
1487
    ui->profileBox->model()->sort(0);
×
1488
  }
1489
  int index = ui->profileBox->findText(QtPassSettings::getProfile());
82 ✔
1490
  if (index != -1) { //  -1 for not found
41 ✔
1491
    ui->profileBox->setCurrentIndex(index);
×
1492
  }
1493
}
41 ✔
1494

1495
/**
1496
 * @brief MainWindow::on_profileBox_currentIndexChanged make sure we show the
1497
 * correct "profile"
1498
 * @param name
1499
 */
1500
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
1501
void MainWindow::on_profileBox_currentIndexChanged(const QString &name) {
1502
#else
1503
/**
1504
 * @brief Handles changes to the selected profile in the profile combo box.
1505
 * @details Ignores the event during a fresh start or when the selected profile
1506
 * matches the current profile. Otherwise, it clears the password field, updates
1507
 * the active profile and related settings, refreshes the environment, and
1508
 * resets the tree view and action states to reflect the newly selected profile.
1509
 *
1510
 * @param name - The newly selected profile name.
1511
 * @return void - This function does not return a value.
1512
 *
1513
 */
1514
void MainWindow::on_profileBox_currentTextChanged(const QString &name) {
×
1515
#endif
1516
  if (m_qtPass->isFreshStart() || name == QtPassSettings::getProfile()) {
×
1517
    return;
×
1518
  }
1519

1520
  ui->lineEdit->clear();
×
1521

1522
  const QHash<QString, QString> prof =
1523
      QtPassSettings::getProfiles().value(name);
×
1524
  AppSettings s = QtPassSettings::load();
×
1525
  s.activeProfile = name;
×
1526
  s.passStore = prof.value("path");
×
1527
  s.passSigningKey = prof.value("signingKey");
×
1528
  // Per-profile git flags (#1140) were stored but never applied; a profile
1529
  // without them keeps the global values.
1530
  const auto flag = [&prof](const char *key, bool current) {
×
1531
    const QString value = prof.value(QLatin1String(key));
×
1532
    return value.isEmpty() ? current : value == QLatin1String("true");
×
1533
  };
×
1534
  s.useGit = flag("useGit", s.useGit);
×
1535
  s.autoPush = flag("autoPush", s.autoPush);
×
1536
  s.autoPull = flag("autoPull", s.autoPull);
×
1537
  QtPassSettings::save(s);
×
1538
  ui->statusBar->showMessage(tr("Profile changed to %1").arg(name), 2000);
×
1539

1540
  QtPassSettings::getPass()->updateEnv();
×
1541

1542
  const QString passStore = QtPassSettings::getPassStore();
×
1543
  proxyModel.setStore(passStore);
×
1544
  ui->treeView->setRootIndex(proxyModel.rootIndexFor(passStore));
×
1545
  deselect();
×
1546
  ui->treeView->setCurrentIndex(QModelIndex());
×
1547
}
×
1548

1549
/**
1550
 * @brief MainWindow::initTrayIcon show a nice tray icon on systems that
1551
 * support
1552
 * it
1553
 */
1554
void MainWindow::initTrayIcon() {
2 ✔
1555
  m_tray = new TrayIcon(this);
2 ✔
1556
  if (!m_tray->getIsAllocated()) {
2 ✔
1557
    destroyTrayIcon();
2 ✔
1558
  }
1559
}
2 ✔
1560

1561
/**
1562
 * @brief MainWindow::destroyTrayIcon remove that pesky tray icon
1563
 */
1564
void MainWindow::destroyTrayIcon() {
2 ✔
1565
  delete m_tray;
2 ✔
1566
  m_tray = nullptr;
2 ✔
1567
}
2 ✔
1568

1569
/**
1570
 * @brief MainWindow::closeEvent hide or quit
1571
 * @param event
1572
 */
1573
void MainWindow::closeEvent(QCloseEvent *event) {
2 ✔
1574
  // Only with a tray icon to come back from: without one (none asked for, or
1575
  // no system tray in this session) a hidden QtPass ran on invisibly, with the
1576
  // last entry in its window and the password on the clipboard.
1577
  if (QtPassSettings::isHideOnClose() && m_tray != nullptr) {
4 ✔
1578
    this->hide();
×
1579
    event->ignore();
1580
  } else {
1581
    m_qtPass->clearClipboard();
2 ✔
1582

1583
    QtPassSettings::setGeometry(saveGeometry());
2 ✔
1584
    QtPassSettings::setSavestate(saveState());
2 ✔
1585
    QtPassSettings::setMaximized(isMaximized());
2 ✔
1586
    if (!isMaximized()) {
2 ✔
1587
      QtPassSettings::setPos(pos());
2 ✔
1588
      QtPassSettings::setSize(size());
2 ✔
1589
    }
1590
    event->accept();
1591
    // A visible QSystemTrayIcon keeps the application alive after the last
1592
    // window closes, so quitOnLastWindowClosed never fires and the window
1593
    // merely vanishes into the tray. Quit explicitly so closing the window
1594
    // actually exits when "hide on close" is disabled.
1595
    QApplication::quit();
2 ✔
1596
  }
1597
}
2 ✔
1598

1599
/**
1600
 * @brief MainWindow::eventFilter filter out some events and focus the
1601
 * treeview
1602
 * @param obj
1603
 * @param event
1604
 * @return
1605
 */
1606
auto MainWindow::eventFilter(QObject *obj, QEvent *event) -> bool {
1,835 ✔
1607
  if (obj == ui->toolBar && event->type() == QEvent::PaletteChange) {
1,835 ✔
1608
    // KDE's Breeze style gives top toolbars a "header" palette of its own.
1609
    // After a runtime light/dark switch it recomputes that palette from a
1610
    // cached kdeglobals and stamps the previous theme's colours back on, so
1611
    // the toolbar stays dark on a light window (or vice versa) with matching
1612
    // invisible icons. A legitimate header tint is close to the window
1613
    // colour; a stale theme is not. When the two disagree, drop the imposed
1614
    // palette so the toolbar follows the application palette again. Deferred
1615
    // so we never re-enter the style while it is still applying its palette.
1616
    QTimer::singleShot(0, this, &MainWindow::dropStaleToolBarPalette);
6 ✔
1617
  }
1618
  if (obj == ui->lineEdit && event->type() == QEvent::KeyPress) {
1,835 ✔
1619
    auto *key = dynamic_cast<QKeyEvent *>(event);
3 ✔
1620
    if (key != nullptr && key->key() == Qt::Key_Down) {
3 ✔
1621
      ui->treeView->setFocus();
×
1622
    }
1623
    // Return ends at the search box: QLineEdit emits returnPressed() and
1624
    // leaves the key unaccepted, so keyPressEvent() would open the tree's
1625
    // current entry as well. In content search that is an entry nobody
1626
    // asked for; by name, the first hit a second time.
1627
    if (key != nullptr &&
3 ✔
1628
        (key->key() == Qt::Key_Return || key->key() == Qt::Key_Enter)) {
×
1629
      ui->lineEdit->event(event);
3 ✔
1630
      event->accept();
1631
      return true;
3 ✔
1632
    }
1633
  }
1634
  return QObject::eventFilter(obj, event);
1,832 ✔
1635
}
1636

1637
/**
1638
 * @brief Reset the toolbar palette when a style left it in the wrong theme.
1639
 *
1640
 * Compares the lightness of the toolbar's Window colour with the application
1641
 * palette; a difference above kStaleToolBarLightness means the toolbar shows
1642
 * the other theme. See the PaletteChange branch in eventFilter().
1643
 */
1644
void MainWindow::dropStaleToolBarPalette() {
3 ✔
1645
  if (!ui->toolBar->testAttribute(Qt::WA_SetPalette)) {
3 ✔
1646
    return;
1647
  }
1648
  constexpr int kStaleToolBarLightness = 64;
1649
  const int barLightness =
1650
      ui->toolBar->palette().color(QPalette::Window).lightness();
4 ✔
1651
  const int appLightness =
1652
      QApplication::palette().color(QPalette::Window).lightness();
4 ✔
1653
  if (qAbs(barLightness - appLightness) > kStaleToolBarLightness) {
2 ✔
1654
    ui->toolBar->setPalette(QPalette());
1 ✔
1655
    // The style also paints the tools-area background on the main window
1656
    // from the same stale palette, and the toolbar is transparent by default;
1657
    // paint our own background so the reset is actually visible.
1658
    ui->toolBar->setAutoFillBackground(true);
1 ✔
1659
  }
1660
}
1661

1662
/**
1663
 * @brief MainWindow::keyPressEvent did anyone press return, enter or escape?
1664
 * @param event
1665
 */
1666
void MainWindow::keyPressEvent(QKeyEvent *event) {
3 ✔
1667
  switch (event->key()) {
3 ✔
1668
  case Qt::Key_Delete:
×
1669
    onDelete();
×
1670
    break;
×
1671
  case Qt::Key_Return:
1 ✔
1672
  case Qt::Key_Enter:
1673
    // While content search results hide the tree, its current entry is not
1674
    // what the user looks at: Return on a result opens that result.
1675
    if (ui->treeView->isHidden()) {
1 ✔
1676
      QTreeWidgetItem *result = ui->grepResultsList->currentItem();
1 ✔
1677
      if (result != nullptr && ui->grepResultsList->hasFocus()) {
1 ✔
1678
        on_grepResultsList_itemClicked(result, 0);
1 ✔
1679
      }
1680
      break;
1681
    }
1682
    if (proxyModel.rowCount() > 0) {
×
1683
      on_treeView_clicked(ui->treeView->currentIndex());
×
1684
    }
1685
    break;
1686
  case Qt::Key_Escape:
×
1687
    ui->lineEdit->clear();
×
1688
    break;
×
1689
  default:
1690
    break;
1691
  }
1692
}
3 ✔
1693

1694
/**
1695
 * @brief MainWindow::showContextMenu show us the (file or folder) context
1696
 * menu
1697
 * @param pos
1698
 */
1699
void MainWindow::showContextMenu(const QPoint &pos) {
×
1700
  const AppSettings s = QtPassSettings::load();
×
1701
  QModelIndex index = ui->treeView->indexAt(pos);
×
1702
  bool selected = true;
1703
  if (!index.isValid()) {
1704
    ui->treeView->clearSelection();
×
1705
    ui->actionDelete->setEnabled(false);
×
1706
    ui->actionEdit->setEnabled(false);
×
1707
    m_currentDir = "";
×
1708
    selected = false;
1709
  }
1710

1711
  ui->treeView->setCurrentIndex(index);
×
1712

1713
  QPoint globalPos = ui->treeView->viewport()->mapToGlobal(pos);
×
1714

1715
  QFileInfo fileOrFolder =
1716
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
1717

1718
  QMenu contextMenu;
×
1719
  if (!selected || fileOrFolder.isDir()) {
×
1720
    QAction *openFolder =
1721
        contextMenu.addAction(tr("Open folder with file manager"));
×
1722
    QAction *addFolder = contextMenu.addAction(tr("Add folder"));
×
1723
    QAction *addPassword = contextMenu.addAction(tr("Add password"));
×
1724
    QAction *users = contextMenu.addAction(tr("Users"));
×
1725
    connect(openFolder, &QAction::triggered, this, &MainWindow::openFolder);
×
1726
    connect(addFolder, &QAction::triggered, this, &MainWindow::addFolder);
×
1727
    connect(addPassword, &QAction::triggered, this, &MainWindow::addPassword);
×
1728
    connect(users, &QAction::triggered, this, &MainWindow::onUsers);
×
1729
  } else if (fileOrFolder.isFile()) {
×
1730
    QAction *edit = contextMenu.addAction(tr("Edit"));
×
1731
    connect(edit, &QAction::triggered, this, &MainWindow::onEdit);
×
1732
  }
1733
  if (selected) {
×
1734
    contextMenu.addSeparator();
×
1735
    if (fileOrFolder.isDir()) {
×
1736
      QAction *renameFolder = contextMenu.addAction(tr("Rename folder"));
×
1737
      connect(renameFolder, &QAction::triggered, this,
×
1738
              &MainWindow::renameFolder);
×
1739
    } else if (fileOrFolder.isFile()) {
×
1740
      QAction *renamePassword = contextMenu.addAction(tr("Rename password"));
×
1741
      connect(renamePassword, &QAction::triggered, this,
×
1742
              &MainWindow::renamePassword);
×
1743
    }
1744
    QAction *deleteItem = contextMenu.addAction(tr("Delete"));
×
1745
    connect(deleteItem, &QAction::triggered, this, &MainWindow::onDelete);
×
1746
    if (fileOrFolder.isDir()) {
×
1747
      QString dirPath = QDir::cleanPath(Util::getDir(
×
1748
          ui->treeView->currentIndex(), false, model, proxyModel, s.passStore));
×
1749

1750
      auto *shareMenu = new QMenu(tr("Share"), &contextMenu);
×
1751
      contextMenu.addMenu(shareMenu);
×
1752

1753
      QString gpgIdPath = Pass::getGpgIdPath(dirPath, s.passStore);
×
1754
      bool gpgIdExists = !gpgIdPath.isEmpty() && QFile(gpgIdPath).exists();
×
1755

1756
      const QString exePath = s.usePass ? s.passExecutable : s.gpgExecutable;
×
1757
      bool gpgAvailable = !exePath.isEmpty() && (exePath.startsWith("wsl ") ||
×
1758
                                                 QFile(exePath).exists());
×
1759

1760
      QAction *reencrypt = shareMenu->addAction(tr("Re-encrypt all passwords"));
×
1761
      reencrypt->setEnabled(gpgIdExists && gpgAvailable);
×
1762
      connect(reencrypt, &QAction::triggered, this,
×
1763
              [this, dirPath]() { reencryptPath(dirPath); });
×
1764

1765
      QAction *exportKey = shareMenu->addAction(tr("Export my public key..."));
×
1766
      exportKey->setEnabled(gpgAvailable);
×
1767
      connect(exportKey, &QAction::triggered, this,
×
1768
              &MainWindow::exportPublicKey);
×
1769

1770
      QAction *addRecipientAction =
1771
          shareMenu->addAction(tr("Add recipient..."));
×
1772
      addRecipientAction->setEnabled(gpgIdExists && gpgAvailable);
×
1773
      connect(addRecipientAction, &QAction::triggered, this,
×
1774
              [this, dirPath]() { addRecipient(dirPath); });
×
1775

1776
      QAction *shareHelp = shareMenu->addAction(tr("What is this?"));
×
1777
      connect(shareHelp, &QAction::triggered, this, &MainWindow::showShareHelp);
×
1778
    }
1779
  }
1780
  contextMenu.exec(globalPos);
×
1781
}
×
1782

1783
/**
1784
 * @brief MainWindow::showBrowserContextMenu show us the context menu in
1785
 * password window
1786
 * @param pos
1787
 */
1788
void MainWindow::showBrowserContextMenu(const QPoint &pos) {
×
1789
  QMenu *contextMenu = ui->textBrowser->createStandardContextMenu(pos);
×
1790
  // createStandardContextMenu() parents the menu to textBrowser. A stylesheet
1791
  // on the browser (it used to carry "background: palette(base)") cascades to
1792
  // the child QMenu and breaks its opaque native background. Reparent to the
1793
  // main window so the menu paints solid regardless of browser styling.
1794
  contextMenu->setParent(this, contextMenu->windowFlags());
×
1795
  QPoint globalPos = ui->textBrowser->viewport()->mapToGlobal(pos);
×
1796

1797
  contextMenu->exec(globalPos);
×
1798
  delete contextMenu;
×
1799
}
×
1800

1801
/**
1802
 * @brief MainWindow::openFolder open the folder in the default file manager
1803
 */
1804
void MainWindow::openFolder() {
×
1805
  QString dir = Util::getDir(ui->treeView->currentIndex(), false, model,
×
1806
                             proxyModel, QtPassSettings::getPassStore());
×
1807

1808
  QString path = QDir::toNativeSeparators(dir);
×
1809
  QDesktopServices::openUrl(QUrl::fromLocalFile(path));
×
1810
}
×
1811

1812
/**
1813
 * @brief MainWindow::addFolder add a new folder to store passwords in
1814
 */
1815
void MainWindow::addFolder() {
×
1816
  const AppSettings s = QtPassSettings::load();
×
1817
  bool ok;
1818
  QString dir = Util::getDir(ui->treeView->currentIndex(), false, model,
×
1819
                             proxyModel, s.passStore);
×
1820
  QString newdir = QInputDialog::getText(
1821
      this, tr("New file"),
×
1822
      tr("New Folder: \n(Will be placed in %1 )")
×
1823
          .arg(s.passStore + Util::getDir(ui->treeView->currentIndex(), true,
×
1824
                                          model, proxyModel, s.passStore)),
×
1825
      QLineEdit::Normal, "", &ok);
×
1826
  if (!ok || newdir.isEmpty()) {
×
1827
    return;
1828
  }
1829
  newdir.prepend(dir);
1830
  if (!confirmPathInStore(newdir)) {
×
1831
    return;
1832
  }
1833
  if (!QDir().mkdir(newdir)) {
×
1834
    QMessageBox::warning(this, tr("Error"),
×
1835
                         tr("Failed to create folder: %1").arg(newdir));
×
1836
    return;
×
1837
  }
1838
  // A .gpg-id only counts when it is signed once a signing key is configured:
1839
  // ImitatePass::verifyGpgIdFile and pass (PASSWORD_STORE_SIGNING_KEY) both
1840
  // refuse to encrypt into a folder whose .gpg-id has no matching
1841
  // .gpg-id.sig. Signing here would need the signing secret key and a
1842
  // passphrase prompt just to create a folder, so in that case leave the
1843
  // folder without its own .gpg-id: it inherits the parent's signed list,
1844
  // which encrypts to the same recipients. UsersDialog (Init) is the place to
1845
  // give it a distinct, signed list.
1846
  const bool signingConfigured = !s.passSigningKey.trimmed().isEmpty();
×
1847
  if (s.addGPGId && !signingConfigured) {
×
1848
    // Seed the new folder's .gpg-id from the recipients that are currently
1849
    // in effect for its parent. The previous implementation walked
1850
    // listKeys("", true) and wrote every key whose `enabled` flag was set,
1851
    // but that flag is only toggled inside UsersDialog, so the loop wrote
1852
    // nothing and left a zero-byte .gpg-id that shadowed the parent's
1853
    // recipients (see #1682).
1854
    if (!Pass::seedGpgIdFile(newdir, s.passStore)) {
×
1855
      QMessageBox::warning(
×
1856
          this, tr("Error"),
×
1857
          tr("Failed to create .gpg-id file in: %1").arg(newdir));
×
1858
      return;
×
1859
    }
1860
  }
1861
}
×
1862

1863
/**
1864
 * @brief MainWindow::renameFolder rename an existing folder
1865
 */
1866
void MainWindow::renameFolder() {
×
1867
  bool ok;
1868
  QString srcDir =
1869
      QDir::cleanPath(Util::getDir(ui->treeView->currentIndex(), false, model,
×
1870
                                   proxyModel, QtPassSettings::getPassStore()));
×
1871
  QString srcDirName = QDir(srcDir).dirName();
×
1872
  QString newName =
1873
      QInputDialog::getText(this, tr("Rename file"), tr("Rename Folder To: "),
×
1874
                            QLineEdit::Normal, srcDirName, &ok);
×
1875
  if (!ok || newName.isEmpty()) {
×
1876
    return;
1877
  }
1878
  QString destDir = srcDir;
1879
  destDir.replace(srcDir.lastIndexOf(srcDirName), srcDirName.length(), newName);
×
1880
  if (!confirmPathInStore(destDir)) {
×
1881
    return;
1882
  }
1883
  QtPassSettings::getPass()->Move(srcDir, destDir, false);
×
1884
}
1885

1886
/**
1887
 * @brief MainWindow::editPassword read password and open edit window via
1888
 * MainWindow::onEdit()
1889
 */
1890
void MainWindow::editPassword(const QString &file) {
1 ✔
1891
  if (!file.isEmpty()) {
1 ✔
1892
    const AppSettings s = QtPassSettings::load();
1 ✔
1893
    if (s.useGit && s.autoPull) {
1 ✔
1894
      onUpdate(true);
×
1895
    }
1896
    setPassword(file, false);
1 ✔
1897
  }
1 ✔
1898
}
1 ✔
1899

1900
/**
1901
 * @brief MainWindow::renamePassword rename an existing password
1902
 */
1903
void MainWindow::renamePassword() {
×
1904
  bool ok;
1905
  QString file = getFile(ui->treeView->currentIndex(), false);
×
1906
  QString filePath = QFileInfo(file).path();
×
1907
  QString fileName = QFileInfo(file).fileName();
×
1908
  if (fileName.endsWith(".gpg", Qt::CaseInsensitive)) {
×
1909
    fileName.chop(4);
×
1910
  }
1911

1912
  QString newName =
1913
      QInputDialog::getText(this, tr("Rename file"), tr("Rename File To: "),
×
1914
                            QLineEdit::Normal, fileName, &ok);
×
1915
  if (!ok || newName.isEmpty()) {
×
1916
    return;
1917
  }
1918
  QString newFile = QDir(filePath).filePath(newName);
×
1919
  if (!confirmPathInStore(newFile)) {
×
1920
    return;
1921
  }
1922
  QtPassSettings::getPass()->Move(file, newFile, false);
×
1923
}
1924

1925
/**
1926
 * @brief Copies the password of the selected file from the tree view to the
1927
 * clipboard.
1928
 * @example
1929
 * MainWindow::copyPasswordFromTreeview();
1930
 *
1931
 * @return void - This function does not return a value.
1932
 */
1933
/**
1934
 * @brief MainWindow::copySelectionOrPassword Ctrl+C anywhere in the window.
1935
 *
1936
 * The selected text when the focus is in a text view or a selectable label
1937
 * with a selection, otherwise the password. The shortcut is window-wide, and
1938
 * read-only text views and labels do not take Ctrl+C for themselves, so a
1939
 * selected login or note was answered with the password.
1940
 */
1941
void MainWindow::copySelectionOrPassword() {
2 ✔
1942
  QWidget *focus = QApplication::focusWidget();
2 ✔
1943
  // The widget's own copy: a SecretTextBrowser marks what it copies as
1944
  // secret for clipboard managers, as the context menu's Copy does.
1945
  if (auto *text = qobject_cast<QTextEdit *>(focus);
2 ✔
1946
      text != nullptr && text->textCursor().hasSelection()) {
2 ✔
1947
    text->copy();
1 ✔
1948
    return;
1 ✔
1949
  }
1950
  // As a copy button would: the label may be the OTP code.
1951
  if (auto *label = qobject_cast<QLabel *>(focus);
1952
      label != nullptr && label->hasSelectedText()) {
1 ✔
1953
    m_qtPass->copyTextToClipboard(label->selectedText());
1 ✔
1954
    return;
1 ✔
1955
  }
NEW
1956
  copyPasswordFromTreeview();
×
1957
}
1958

UNCOV
1959
void MainWindow::copyPasswordFromTreeview() {
×
1960
  QFileInfo fileOrFolder =
1961
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
1962

1963
  if (fileOrFolder.isFile()) {
×
1964
    // finishedShow carries no request identity, so allow only one copy request
1965
    // in flight: otherwise a second Ctrl+C on a different entry would re-arm
1966
    // the single-shot slot and the first decrypt to finish would copy the wrong
1967
    // entry while the later request is silently dropped. See
1968
    // m_passwordCopyPending.
1969
    if (m_passwordCopyPending) {
×
1970
      return;
×
1971
    }
1972
    m_passwordCopyPending = true;
×
1973
    QString file = getFile(ui->treeView->currentIndex(), true);
×
1974
    connectSingleShot(QtPassSettings::getPass(), &Pass::finishedShow, this,
×
1975
                      &MainWindow::passwordFromFileToClipboard);
1976
    // This Show repaints the panel as well; see onOtp().
1977
    m_shownFile = file;
×
1978
    QtPassSettings::getPass()->Show(file);
×
1979
  }
1980
}
×
1981

1982
void MainWindow::passwordFromFileToClipboard(const QString &text) {
2 ✔
1983
  disconnectSingleShot(QtPassSettings::getPass(), &Pass::finishedShow, this,
2 ✔
1984
                       &MainWindow::passwordFromFileToClipboard);
1985
  m_passwordCopyPending = false;
2 ✔
1986
  const QStringList tokens = text.split('\n');
2 ✔
1987
  if (tokens.isEmpty()) {
2 ✔
1988
    return;
1989
  }
1990
  // An entry created by `pass otp insert` has the otpauth:// URI as its first
1991
  // line. That URI carries the shared TOTP secret (the seed, not a code), so
1992
  // copying it to the clipboard would leak 2FA material. Skip it, matching the
1993
  // display path (FileContent::getPasswordForDisplay / PasswordDisplayPanel).
1994
  if (FileContent::isOtpUriValue(tokens[0])) {
2 ✔
1995
    flashText(tr("This entry holds an OTP secret, not a password"), true);
1 ✔
1996
    return;
1 ✔
1997
  }
1998
  m_qtPass->copyTextToClipboard(tokens[0]);
1 ✔
1999
}
2000

2001
/**
2002
 * @brief Displays message in status bar
2003
 *
2004
 * @param msg     text to be displayed
2005
 * @param timeout time for which msg shall be visible
2006
 */
2007
void MainWindow::showStatusMessage(const QString &msg, int timeout) {
12 ✔
2008
  ui->statusBar->showMessage(msg, timeout);
12 ✔
2009
}
12 ✔
2010

2011
/**
2012
 * @brief MainWindow::reencryptPath re-encrypt all passwords in a directory
2013
 * @param dir Directory path to re-encrypt
2014
 */
2015
void MainWindow::reencryptPath(const QString &dir) {
×
2016
  QDir checkDir(dir);
×
2017
  if (!checkDir.exists()) {
×
2018
    QMessageBox::critical(this, tr("Error"),
×
2019
                          tr("Directory does not exist: %1").arg(dir));
×
2020
    return;
×
2021
  }
2022

2023
  int ret = QMessageBox::question(
×
2024
      this, tr("Re-encrypt passwords"),
×
2025
      tr("Re-encrypt all passwords in %1?\n\n"
×
2026
         "This will re-encrypt ALL password files in this folder "
2027
         "using the current recipients defined in .gpg-id.\n\n"
2028
         "This may rewrite many files and cannot be undone easily.\n\n"
2029
         "Continue?")
2030
          .arg(QDir(dir).dirName()),
×
2031
      QMessageBox::Yes | QMessageBox::No);
2032

2033
  if (ret != QMessageBox::Yes)
×
2034
    return;
2035

2036
  // Disable preemptively. ImitatePass::reencryptPath emits
2037
  // startReencryptPath asynchronously and the slot would re-run this,
2038
  // but setEnabled(false) is idempotent so the duplicate is harmless.
2039
  startReencryptPath();
×
2040

2041
  QtPassSettings::getImitatePass()->reencryptPath(
×
2042
      QDir::cleanPath(QDir(dir).absolutePath()));
×
2043
}
×
2044

2045
/**
2046
 * @brief MainWindow::startReencryptPath disable ui elements and treeview
2047
 */
2048
void MainWindow::startReencryptPath() {
×
2049
  setUiElementsEnabled(false);
×
2050
  ui->treeView->setDisabled(true);
×
2051
}
×
2052

2053
/**
2054
 * @brief MainWindow::endReencryptPath re-enable ui elements
2055
 */
2056
void MainWindow::endReencryptPath() { setUiElementsEnabled(true); }
×
2057

2058
/**
2059
 * @brief MainWindow::exportPublicKey export the configured signing key in
2060
 *        ASCII-armored form via gpg and show it in ExportPublicKeyDialog.
2061
 *
2062
 * Falls back to a help dialog when no signing key is configured or gpg is
2063
 * unavailable, so the user still gets actionable guidance.
2064
 */
2065
void MainWindow::exportPublicKey() {
×
2066
  const AppSettings s = QtPassSettings::load();
×
2067
  const QString identity = s.passSigningKey;
2068
  if (identity.isEmpty()) {
×
2069
    QMessageBox::information(
×
2070
        this, tr("Export Public Key"),
×
2071
        tr("<h3>Export Your Public Key</h3>"
×
2072
           "<p>No signing key is configured. Set one in QtPass Settings "
2073
           "&gt; GPG keys, or run this in a terminal:</p>"
2074
           "<pre>gpg --armor --export --output my_key.asc &lt;your-key-id"
2075
           "&gt;</pre>"
2076
           "<p>Then send the file to your teammates.</p>"));
2077
    return;
×
2078
  }
2079
  QString gpgExe = s.gpgExecutable;
2080
  if (gpgExe.isEmpty()) {
×
2081
    gpgExe = QStringLiteral("gpg");
×
2082
  }
2083
  QStringList args = {"--armor", "--export"};
×
2084
  args.append(identity.split(' ', Qt::SkipEmptyParts));
×
2085
  QString stdOut;
×
2086
  QString stdErr;
×
2087
  int exitCode = Executor::executeBlocking(gpgExe, args, &stdOut, &stdErr);
×
2088
  if (exitCode != 0 || stdOut.isEmpty()) {
×
2089
    QMessageBox::warning(this, tr("Export Public Key"),
×
2090
                         tr("Could not export public key for %1.\n\n%2")
×
2091
                             .arg(identity, stdErr.isEmpty()
×
2092
                                                ? tr("No output from gpg.")
×
2093
                                                : stdErr));
2094
    return;
2095
  }
2096
  ExportPublicKeyDialog dialog(identity, stdOut, this);
×
2097
  dialog.exec();
×
2098
}
×
2099

2100
/**
2101
 * @brief MainWindow::addRecipient open the recipient management dialog for
2102
 *        the supplied directory.
2103
 * @param dir Folder whose .gpg-id should be edited.
2104
 *
2105
 * Delegates to UsersDialog so users can tick/untick keys from their
2106
 * keyring as recipients of the folder; importing a foreign key into the
2107
 * keyring still has to happen via gpg (or QtPass settings) first.
2108
 */
2109
void MainWindow::addRecipient(const QString &dir) {
×
2110
  UsersDialog d(QtPassSettings::getPass(), QtPassSettings::load(), dir, this);
×
2111
  d.exec();
×
2112
}
×
2113

2114
/**
2115
 * @brief MainWindow::showShareHelp show help about GPG sharing
2116
 */
2117
void MainWindow::showShareHelp() {
×
2118
  QMessageBox::information(
×
2119
      this, tr("Sharing Passwords with GPG"),
×
2120
      tr("<h3>Sharing Passwords with GPG</h3>"
×
2121
         "<p>To share passwords with other users:</p>"
2122
         "<ol>"
2123
         "<li><b>Export your public key</b> and send it to teammates</li>"
2124
         "<li><b>Import teammates' public keys</b> into your GPG keyring</li>"
2125
         "<li><b>Re-encrypt passwords</b> so all recipients can decrypt "
2126
         "them</li>"
2127
         "</ol>"
2128
         "<p>Only people who have a matching secret key can decrypt the "
2129
         "passwords.</p>"
2130
         "<p><b>Tip:</b> Use the same GPG key for all shared folders.</p>"
2131
         "<p>See the FAQ for more details.</p>"));
2132
}
×
2133

2134
void MainWindow::updateGitButtonVisibility() {
103 ✔
2135
  const AppSettings s = QtPassSettings::load();
103 ✔
2136
  if (!s.useGit || (s.gitExecutable.isEmpty() && s.passExecutable.isEmpty())) {
103 ✔
2137
    enableGitButtons(false);
71 ✔
2138
  } else {
2139
    enableGitButtons(true);
32 ✔
2140
  }
2141
}
103 ✔
2142

2143
void MainWindow::updateOtpButtonVisibility(bool uiEnabled) {
103 ✔
2144
  // No platform gating any more: codes are generated in-process, so this works
2145
  // on Windows and macOS and with either backend. It used to be hidden there
2146
  // because the pass-otp extension is Unix-only.
2147
  //
2148
  // Kept visible but disabled when OTP is off, as it was before: hiding it
2149
  // removed the only discoverable trace of the feature, and since an OTP field
2150
  // is suppressed from the panel unconditionally (its value is a secret), a
2151
  // user with the setting off would see nothing at all where their OTP data
2152
  // used to be.
2153
  //
2154
  // Enablement must honour uiEnabled: this is called from
2155
  // setUiElementsEnabled(), and ignoring the argument re-enabled the action
2156
  // while a decrypt was in flight, letting the user stack Show calls.
2157
  ui->actionOtp->setVisible(true);
103 ✔
2158
  ui->actionOtp->setEnabled(QtPassSettings::isUseOtp() && uiEnabled);
103 ✔
2159
}
103 ✔
2160

2161
void MainWindow::updateGrepButtonVisibility() {
41 ✔
2162
  const bool enabled = QtPassSettings::isUseGrepSearch();
41 ✔
2163
  ui->grepButton->setVisible(enabled);
41 ✔
2164
  ui->grepCaseButton->setVisible(enabled);
41 ✔
2165
  if (!enabled && m_grep.inGrepMode()) {
41 ✔
2166
    ui->grepButton->setChecked(false);
×
2167
  }
2168
}
41 ✔
2169

2170
void MainWindow::enableGitButtons(const bool &state) {
103 ✔
2171
  // Following GNOME guidelines is preferable disable buttons instead of hide
2172
  ui->actionPush->setEnabled(state);
103 ✔
2173
  ui->actionUpdate->setEnabled(state);
103 ✔
2174
}
103 ✔
2175

2176
/**
2177
 * @brief MainWindow::critical critical message popup wrapper.
2178
 * @param title
2179
 * @param msg
2180
 */
2181
void MainWindow::critical(const QString &title, const QString &msg) {
×
2182
  QMessageBox::critical(this, title, msg);
×
2183
}
×
2184

2185
/**
2186
 * @brief Appends processed command output to the output panel.
2187
 *
2188
 * Appends text to the process output text edit, with per-line numbering,
2189
 * optional command prefix, and color coding for errors vs. success.
2190
 * Handles auto-scrolling and line limits.
2191
 *
2192
 * @param output The raw output text from the command.
2193
 * @param isError true if this is error output (stderr).
2194
 * @param linePrefix Optional command name to prefix each line with.
2195
 */
2196
void MainWindow::appendProcessOutput(const QString &output, bool isError,
2 ✔
2197
                                     const QString &linePrefix) {
2198
  if (!QtPassSettings::isShowProcessOutput()) {
2 ✔
2199
    return;
1 ✔
2200
  }
2201

2202
  QStringList lines = output.split('\n', Qt::SkipEmptyParts);
1 ✔
2203
  for (QString &line : lines) {
2 ✔
2204
    // Right-trim only: remove trailing CR and whitespace, preserve leading
2205
    // indentation
2206
    line.remove('\r');
1 ✔
2207
    while (!line.isEmpty() && line.back().isSpace()) {
2 ✔
2208
      line.chop(1);
×
2209
    }
2210
    if (line.isEmpty()) {
1 ✔
2211
      continue;
×
2212
    }
2213

2214
    m_outputCounter++;
1 ✔
2215
    QString lineNumber = QString::number(m_outputCounter);
1 ✔
2216

2217
    QColor textColor =
2218
        isError ? QColor(Qt::red)
1 ✔
2219
                : m_processOutputEdit->palette().color(QPalette::Text);
2 ✔
2220
    QString colorHex = textColor.name();
1 ✔
2221
    // Apply the optional prefix per line so multi-line output stays
2222
    // attributed to its command (e.g. all 3 lines of a `git push` show
2223
    // "git push: ..." rather than only the first).
2224
    QString prefixed =
2225
        linePrefix.isEmpty() ? line : linePrefix + QStringLiteral(": ") + line;
2 ✔
2226
    QString coloredOutput =
2227
        QString("<span style=\"color: %1;\">%2: %3</span>")
1 ✔
2228
            .arg(colorHex, lineNumber, prefixed.toHtmlEscaped());
2 ✔
2229

2230
    m_processOutputEdit->append(coloredOutput);
1 ✔
2231
  }
2232

2233
  limitOutputLines();
1 ✔
2234

2235
  if (m_autoScroll) {
1 ✔
2236
    m_processOutputEdit->verticalScrollBar()->setValue(
2 ✔
2237
        m_processOutputEdit->verticalScrollBar()->maximum());
1 ✔
2238
  }
2239
}
2240

2241
/**
2242
 * @brief Handles process output from the Pass executor.
2243
 *
2244
 * Called when any non-sensitive process completes. Filters out password-
2245
 * related commands (pass show, insert, etc.) and delegates to
2246
 * appendProcessOutput.
2247
 *
2248
 * @param output The stdout/stderr text from the process.
2249
 * @param isError true if this is error output (stderr).
2250
 * @param pid The process ID identifying which command ran.
2251
 */
2252
void MainWindow::onProcessOutput(const QString &output, bool isError,
2 ✔
2253
                                 Enums::PROCESS pid) {
2254
  appendProcessOutput(output, isError, getProcessName(pid));
2 ✔
2255
}
2 ✔
2256

2257
/**
2258
 * @brief Maps a process ID to its human-readable command name.
2259
 *
2260
 * Returns static strings for git/pass commands that appear in output.
2261
 * Password-related commands return empty (they are filtered).
2262
 *
2263
 * @param pid The process ID to look up.
2264
 * @return QString with command name, or empty if filtered.
2265
 */
2266
auto MainWindow::getProcessName(Enums::PROCESS pid) -> QString {
2 ✔
2267
  switch (pid) {
2 ✔
2268
  case Enums::GIT_INIT:
×
2269
    return QStringLiteral("git init"); // no-tr
×
2270
  case Enums::GIT_ADD:
×
2271
    return QStringLiteral("git add"); // no-tr
×
2272
  case Enums::GIT_COMMIT:
×
2273
    return QStringLiteral("git commit"); // no-tr
×
2274
  case Enums::GIT_RM:
×
2275
    return QStringLiteral("git rm"); // no-tr
×
2276
  case Enums::GIT_PULL:
×
2277
    return QStringLiteral("git pull"); // no-tr
×
2278
  case Enums::GIT_PUSH:
×
2279
    return QStringLiteral("git push"); // no-tr
×
2280
  case Enums::GIT_MOVE:
×
2281
    return QStringLiteral("git mv"); // no-tr
×
2282
  case Enums::GIT_COPY:
×
2283
    // ImitatePass::Copy literally invokes `git cp` (a git-extras
2284
    // subcommand), so the label matches what's run. Stock-git users
2285
    // without git-extras will see the underlying "'cp' is not a git
2286
    // command" failure surfaced in the process output panel.
2287
    return QStringLiteral("git cp"); // no-tr
×
2288
  case Enums::PASS_INSERT:
×
2289
    return QStringLiteral("pass insert"); // no-tr
×
2290
  case Enums::PASS_REMOVE:
×
2291
    return QStringLiteral("pass rm"); // no-tr
×
2292
  case Enums::PASS_INIT:
×
2293
    return QStringLiteral("pass init"); // no-tr
×
2294
  case Enums::PASS_MOVE:
×
2295
    return QStringLiteral("pass mv"); // no-tr
×
2296
  case Enums::PASS_COPY:
×
2297
    return QStringLiteral("pass cp"); // no-tr
×
2298
  case Enums::PASS_GREP:
×
2299
    return QStringLiteral("pass grep"); // no-tr
×
2300
  case Enums::GPG_GENKEYS:
×
2301
    return QStringLiteral("gpg --gen-key"); // no-tr
×
2302
  case Enums::PASS_SHOW:
2303
  case Enums::PASS_OTP_GENERATE:
2304
  case Enums::PROCESS_COUNT:
2305
  case Enums::INVALID:
2306
    break;
2307
  }
2308
  return {};
2 ✔
2309
}
2310

2311
/**
2312
 * @brief Checks if a process ID represents a sensitive operation whose
2313
 * output should not be shown in the process output panel.
2314
 *
2315
 * Password-related commands (pass show, OTP generate, grep, insert)
2316
 * display their output in other UI areas, so we skip them here.
2317
 *
2318
 * @param pid The process ID to check.
2319
 * @return true if the process is sensitive and should be filtered.
2320
 */
2321
auto MainWindow::isSensitiveProcess(Enums::PROCESS pid) -> bool {
5 ✔
2322
  switch (pid) {
5 ✔
2323
  case Enums::PASS_SHOW:
2324
  case Enums::PASS_OTP_GENERATE:
2325
  case Enums::PASS_GREP:
2326
  case Enums::PASS_INSERT:
2327
    return true;
2328
  case Enums::GIT_INIT:
2329
  case Enums::GIT_ADD:
2330
  case Enums::GIT_COMMIT:
2331
  case Enums::GIT_RM:
2332
  case Enums::GIT_PULL:
2333
  case Enums::GIT_PUSH:
2334
  case Enums::GIT_MOVE:
2335
  case Enums::GIT_COPY:
2336
  case Enums::PASS_REMOVE:
2337
  case Enums::PASS_INIT:
2338
  case Enums::PASS_MOVE:
2339
  case Enums::PASS_COPY:
2340
  case Enums::GPG_GENKEYS:
2341
  case Enums::PROCESS_COUNT:
2342
  case Enums::INVALID:
2343
    break;
2344
  }
2345
  return false;
5 ✔
2346
}
2347

2348
/**
2349
 * @brief Updates the visibility of the process output panel.
2350
 *
2351
 * Shows or hides the process output widget based on the user's
2352
 * showProcessOutput setting.
2353
 */
2354
void MainWindow::updateProcessOutputVisibility() {
4 ✔
2355
  m_processOutputDock->setVisible(QtPassSettings::isShowProcessOutput());
4 ✔
2356
}
4 ✔
2357

2358
/**
2359
 * @brief Limits the output panel to max lines, trimming old excess.
2360
 *
2361
 * Removes the oldest lines when the document exceeds MaxOutputLines (1000).
2362
 * Called after each append to prevent unbounded growth.
2363
 */
2364
void MainWindow::limitOutputLines() {
1 ✔
2365
  QTextDocument *doc = m_processOutputEdit->document();
1 ✔
2366
  int excess = doc->blockCount() - MaxOutputLines;
1 ✔
2367
  if (excess <= 0) {
1 ✔
2368
    return;
1 ✔
2369
  }
2370

2371
  QTextCursor cursor(doc);
×
2372
  cursor.movePosition(QTextCursor::Start);
×
2373
  cursor.movePosition(QTextCursor::NextBlock, QTextCursor::KeepAnchor, excess);
×
2374
  cursor.removeSelectedText();
×
2375
}
×
2376

2377
/**
2378
 * @brief Clears the process output panel.
2379
 *
2380
 * Clears all output, resets the line counter, and re-enables auto-scroll.
2381
 */
2382
void MainWindow::on_clearOutputButton_clicked() {
×
2383
  m_processOutputEdit->clear();
×
2384
  m_outputCounter = 0;
×
2385
  m_autoScroll = true;
×
2386
}
×
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