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

IJHack / QtPass / 27478026925

13 Jun 2026 08:21PM UTC coverage: 55.613% (+0.04%) from 55.57%
27478026925

push

github

web-flow
refactor: extract template I/O into TemplateIO module (#1514) (#1525)

* refactor: extract template I/O into TemplateIO module (#1514)

Move Util::readTemplates / writeTemplates / getFolderTemplate into a
dedicated TemplateIO class (src/templateio.{h,cpp}), completing the Util
grab-bag split. Template handling (the .templates INI file and per-folder
.default_template lookup) is a self-contained concern used only by the
add-password flow in MainWindow.

- Verbatim move of all three impls.
- Update the two MainWindow callers to TemplateIO::.
- Retarget the readTemplates*/writeTemplates*/getFolderTemplate* cases in
  tst_util to TemplateIO.
- Drop now-dead includes from util.cpp (QSaveFile, QTextStream,
  QStringConverter, algorithm).
- Wire templateio.cpp/.h into src/src.pro.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix: build on Qt 5.15 and check store boundary before file read

- Include <QDebug> in templateio.cpp: qWarning() needs the complete QDebug
  type, which Qt 6 pulled in transitively but Qt 5.15 does not, breaking
  the CI build.
- getFolderTemplate: move the store-boundary check to the top of the loop
  so paths resolving outside the store are rejected before any
  .default_template file is opened. The store root and its descendants are
  still probed (root read, then loop stops); only out-of-store paths are
  short-circuited.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

---------

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

61 of 63 new or added lines in 2 files covered. (96.83%)

3735 of 6716 relevant lines covered (55.61%)

36.9 hits per line

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

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

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

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

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

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

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

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

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

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

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

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

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

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

120
  updateProfileBox();
12 ✔
121

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

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

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

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

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

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

161
  setUiElementsEnabled(true);
12 ✔
162

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

863
/**
864
 * @brief Toggle grep (content search) mode.
865
 */
866
void MainWindow::on_grepButton_toggled(bool checked) {
×
867
  m_grepMode = checked;
×
868
  if (checked) {
×
869
    ui->lineEdit->setPlaceholderText(tr("Search content (regex)"));
×
870
    ui->lineEdit->clear();
×
871
    searchTimer.stop();
×
872
    proxyModel.setFilterRegularExpression(QRegularExpression());
×
873
    ui->treeView->setRootIndex(proxyModel.mapFromSource(
×
874
        model.setRootPath(QtPassSettings::getPassStore())));
×
875
    ui->grepResultsList->setVisible(false);
×
876
    // Keep treeView visible until results arrive
877
  } else {
878
    if (m_grepBusy) {
×
879
      m_grepBusy = false;
×
880
      m_grepCancelled = true;
×
881
      QApplication::restoreOverrideCursor();
×
882
    }
883
    searchTimer.stop();
×
884
    ui->lineEdit->blockSignals(true);
×
885
    ui->lineEdit->clear();
×
886
    ui->lineEdit->blockSignals(false);
×
887
    ui->lineEdit->setPlaceholderText(tr("Search Password"));
×
888
    ui->grepResultsList->clear();
×
889
    ui->grepResultsList->setVisible(false);
×
890
    ui->treeView->setVisible(true);
×
891
    proxyModel.setFilterRegularExpression(QRegularExpression());
×
892
    ui->treeView->setRootIndex(proxyModel.mapFromSource(
×
893
        model.setRootPath(QtPassSettings::getPassStore())));
×
894
  }
895
}
×
896

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

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

971
/**
972
 * @brief MainWindow::selectFirstFile select the first possible file in the
973
 * tree
974
 */
975
void MainWindow::selectFirstFile() {
×
976
  QModelIndex index = proxyModel.mapFromSource(
×
977
      model.setRootPath(QtPassSettings::getPassStore()));
×
978
  index = firstFile(index);
×
979
  ui->treeView->setCurrentIndex(index);
×
980
}
×
981

982
/**
983
 * @brief MainWindow::firstFile return location of first possible file
984
 * @param parentIndex
985
 * @return QModelIndex
986
 */
987
auto MainWindow::firstFile(QModelIndex parentIndex) -> QModelIndex {
×
988
  QModelIndex index = parentIndex;
×
989
  int numRows = proxyModel.rowCount(parentIndex);
×
990
  for (int row = 0; row < numRows; ++row) {
×
991
    index = proxyModel.index(row, 0, parentIndex);
×
992
    if (model.fileInfo(proxyModel.mapToSource(index)).isFile()) {
×
993
      return index;
×
994
    }
995
    if (proxyModel.hasChildren(index)) {
×
996
      return firstFile(index);
×
997
    }
998
  }
999
  return index;
×
1000
}
1001

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

1024
/**
1025
 * @brief MainWindow::setPassword open passworddialog
1026
 * @param file which pgp file
1027
 * @param isNew insert (not update)
1028
 */
1029
void MainWindow::setPassword(const QString &file, bool isNew) {
×
1030
  PasswordDialog d(file, isNew, this);
×
1031

1032
  if (isNew) {
×
1033
    QString storePath = QtPassSettings::getPassStore();
×
1034
    QString folder =
1035
        Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel);
×
1036
    if (folder.isEmpty()) {
×
1037
      folder = storePath;
×
1038
    }
1039
    QHash<QString, QStringList> templates =
NEW
1040
        TemplateIO::readTemplates(storePath);
×
1041
    if (!templates.isEmpty()) {
1042
      QString defaultTemplate =
NEW
1043
          TemplateIO::getFolderTemplate(folder, storePath);
×
1044
      d.setAvailableTemplates(templates, defaultTemplate);
×
1045
      new QShortcut(QKeySequence(Qt::CTRL | Qt::Key_T), &d,
×
1046
                    [&d]() { d.cycleTemplate(); });
×
1047
    }
1048
  }
×
1049

1050
  if (!d.exec()) {
×
1051
    ui->treeView->setFocus();
×
1052
  }
1053
}
×
1054

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

1080
/**
1081
 * @brief MainWindow::onDelete remove password, if you are
1082
 * sure.
1083
 */
1084
void MainWindow::onDelete() {
×
1085
  QModelIndex currentIndex = ui->treeView->currentIndex();
×
1086
  if (!currentIndex.isValid()) {
1087
    // This fixes https://github.com/IJHack/QtPass/issues/556
1088
    // Otherwise the entire password directory would be deleted if
1089
    // nothing is selected in the tree view.
1090
    return;
×
1091
  }
1092

1093
  QFileInfo fileOrFolder =
1094
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
1095
  QString file = "";
×
1096
  bool isDir = false;
1097

1098
  if (fileOrFolder.isFile()) {
×
1099
    file = getFile(ui->treeView->currentIndex(), true);
×
1100
  } else {
1101
    file = Util::getDir(ui->treeView->currentIndex(), true, model, proxyModel);
×
1102
    isDir = true;
1103
  }
1104

1105
  QString dirMessage = tr(" and the whole content?");
1106
  if (isDir) {
×
1107
    QDirIterator it(model.rootPath() + QDir::separator() + file,
×
1108
                    QDirIterator::Subdirectories);
×
1109
    bool okDir = true;
1110
    while (it.hasNext() && okDir) {
×
1111
      it.next();
×
1112
      if (QFileInfo(it.filePath()).isFile()) {
×
1113
        if (QFileInfo(it.filePath()).suffix() != "gpg") {
×
1114
          okDir = false;
1115
          dirMessage = tr(" and the whole content? <br><strong>Attention: "
×
1116
                          "there are unexpected files in the given folder, "
1117
                          "check them before continue.</strong>");
1118
        }
1119
      }
1120
    }
1121
  }
×
1122

1123
  if (QMessageBox::question(
×
1124
          this, isDir ? tr("Delete folder?") : tr("Delete password?"),
×
1125
          tr("Are you sure you want to delete %1%2?")
×
1126
              .arg(QDir::separator() + file, isDir ? dirMessage : "?"),
×
1127
          QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) {
1128
    return;
1129
  }
1130

1131
  QtPassSettings::getPass()->Remove(file, isDir);
×
1132
}
×
1133

1134
/**
1135
 * @brief MainWindow::onOTP try and generate (selected) OTP code.
1136
 */
1137
void MainWindow::onOtp() {
×
1138
  QString file = getFile(ui->treeView->currentIndex(), true);
×
1139
  if (!file.isEmpty()) {
×
1140
    if (QtPassSettings::isUseOtp()) {
×
1141
      setUiElementsEnabled(false);
×
1142
      QtPassSettings::getPass()->OtpGenerate(file);
×
1143
    }
1144
  } else {
1145
    flashText(tr("No password selected for OTP generation"), true);
×
1146
  }
1147
}
×
1148

1149
/**
1150
 * @brief MainWindow::onEdit try and edit (selected) password.
1151
 */
1152
void MainWindow::onEdit() {
×
1153
  QString file = getFile(ui->treeView->currentIndex(), true);
×
1154
  editPassword(file);
×
1155
}
×
1156

1157
/**
1158
 * @brief MainWindow::userDialog see MainWindow::onUsers()
1159
 * @param dir folder to edit users for.
1160
 */
1161
void MainWindow::userDialog(const QString &dir) {
×
1162
  if (!dir.isEmpty()) {
×
1163
    m_currentDir = dir;
×
1164
  }
1165
  onUsers();
×
1166
}
×
1167

1168
/**
1169
 * @brief MainWindow::onUsers edit users for the current
1170
 * folder,
1171
 * gets lists and opens UserDialog.
1172
 */
1173
void MainWindow::onUsers() {
×
1174
  QString dir =
1175
      m_currentDir.isEmpty()
1176
          ? Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel)
×
1177
          : m_currentDir;
×
1178

1179
  UsersDialog d(dir, this);
×
1180
  if (!d.exec()) {
×
1181
    ui->treeView->setFocus();
×
1182
  }
1183
}
×
1184

1185
/**
1186
 * @brief MainWindow::messageAvailable we have some text/message/search to do.
1187
 * @param message
1188
 */
1189
void MainWindow::messageAvailable(const QString &message) {
×
1190
  show();
×
1191
  raise();
×
1192
  if (message.isEmpty()) {
×
1193
    focusInput();
×
1194
  } else {
1195
    ui->treeView->expandAll();
×
1196
    ui->lineEdit->setText(message);
×
1197
    on_lineEdit_returnPressed();
×
1198
  }
1199
}
×
1200

1201
/**
1202
 * @brief MainWindow::generateKeyPair internal gpg keypair generator . .
1203
 * @param batch
1204
 * @param keygenWindow
1205
 */
1206
void MainWindow::generateKeyPair(const QString &batch, QDialog *keygenWindow) {
×
1207
  m_keygenDialog = keygenWindow;
×
1208
  emit generateGPGKeyPair(batch);
×
1209
}
×
1210

1211
/**
1212
 * @brief MainWindow::updateProfileBox update the list of profiles, optionally
1213
 * select a more appropriate one to view too
1214
 */
1215
void MainWindow::updateProfileBox() {
12 ✔
1216
  QHash<QString, QHash<QString, QString>> profiles =
1217
      QtPassSettings::getProfiles();
12 ✔
1218

1219
  if (profiles.isEmpty()) {
1220
    ui->profileWidget->hide();
×
1221
  } else {
1222
    ui->profileWidget->show();
12 ✔
1223
    ui->profileBox->setEnabled(profiles.size() > 1);
24 ✔
1224
    ui->profileBox->clear();
12 ✔
1225
    QHashIterator<QString, QHash<QString, QString>> i(profiles);
12 ✔
1226
    while (i.hasNext()) {
12 ✔
1227
      i.next();
1228
      if (!i.key().isEmpty()) {
12 ✔
1229
        ui->profileBox->addItem(i.key());
12 ✔
1230
      }
1231
    }
1232
    ui->profileBox->model()->sort(0);
12 ✔
1233
  }
1234
  int index = ui->profileBox->findText(QtPassSettings::getProfile());
24 ✔
1235
  if (index != -1) { //  -1 for not found
12 ✔
1236
    ui->profileBox->setCurrentIndex(index);
×
1237
  }
1238
}
12 ✔
1239

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

1265
  ui->lineEdit->clear();
×
1266

1267
  QtPassSettings::setProfile(name);
×
1268

1269
  QtPassSettings::setPassStore(
×
1270
      QtPassSettings::getProfiles().value(name).value("path"));
×
1271
  QtPassSettings::setPassSigningKey(
×
1272
      QtPassSettings::getProfiles().value(name).value("signingKey"));
×
1273
  ui->statusBar->showMessage(tr("Profile changed to %1").arg(name), 2000);
×
1274

1275
  QtPassSettings::getPass()->updateEnv();
×
1276

1277
  const QString passStore = QtPassSettings::getPassStore();
×
1278
  proxyModel.setStore(passStore);
×
1279
  ui->treeView->setRootIndex(
×
1280
      proxyModel.mapFromSource(model.setRootPath(passStore)));
×
1281
  deselect();
×
1282
  ui->treeView->setCurrentIndex(QModelIndex());
×
1283
}
1284

1285
/**
1286
 * @brief MainWindow::initTrayIcon show a nice tray icon on systems that
1287
 * support
1288
 * it
1289
 */
1290
void MainWindow::initTrayIcon() {
×
1291
  m_tray = new TrayIcon(this);
×
1292
  // Setup tray icon
1293

1294
  if (m_tray == nullptr) {
1295
#ifdef QT_DEBUG
1296
    dbg() << "Allocating tray icon failed.";
1297
#endif
1298
    return;
1299
  }
1300

1301
  if (!m_tray->getIsAllocated()) {
×
1302
    destroyTrayIcon();
×
1303
  }
1304
}
1305

1306
/**
1307
 * @brief MainWindow::destroyTrayIcon remove that pesky tray icon
1308
 */
1309
void MainWindow::destroyTrayIcon() {
×
1310
  delete m_tray;
×
1311
  m_tray = nullptr;
×
1312
}
×
1313

1314
/**
1315
 * @brief MainWindow::closeEvent hide or quit
1316
 * @param event
1317
 */
1318
void MainWindow::closeEvent(QCloseEvent *event) {
×
1319
  if (QtPassSettings::isHideOnClose()) {
×
1320
    this->hide();
×
1321
    event->ignore();
1322
  } else {
1323
    m_qtPass->clearClipboard();
×
1324

1325
    QtPassSettings::setGeometry(saveGeometry());
×
1326
    QtPassSettings::setSavestate(saveState());
×
1327
    QtPassSettings::setMaximized(isMaximized());
×
1328
    if (!isMaximized()) {
×
1329
      QtPassSettings::setPos(pos());
×
1330
      QtPassSettings::setSize(size());
×
1331
    }
1332
    event->accept();
1333
  }
1334
}
×
1335

1336
/**
1337
 * @brief MainWindow::eventFilter filter out some events and focus the
1338
 * treeview
1339
 * @param obj
1340
 * @param event
1341
 * @return
1342
 */
1343
auto MainWindow::eventFilter(QObject *obj, QEvent *event) -> bool {
3 ✔
1344
  if (obj == ui->lineEdit && event->type() == QEvent::KeyPress) {
3 ✔
1345
    auto *key = dynamic_cast<QKeyEvent *>(event);
×
1346
    if (key != nullptr && key->key() == Qt::Key_Down) {
×
1347
      ui->treeView->setFocus();
×
1348
    }
1349
  }
1350
  return QObject::eventFilter(obj, event);
3 ✔
1351
}
1352

1353
/**
1354
 * @brief MainWindow::keyPressEvent did anyone press return, enter or escape?
1355
 * @param event
1356
 */
1357
void MainWindow::keyPressEvent(QKeyEvent *event) {
×
1358
  switch (event->key()) {
×
1359
  case Qt::Key_Delete:
×
1360
    onDelete();
×
1361
    break;
×
1362
  case Qt::Key_Return:
×
1363
  case Qt::Key_Enter:
1364
    if (proxyModel.rowCount() > 0) {
×
1365
      on_treeView_clicked(ui->treeView->currentIndex());
×
1366
    }
1367
    break;
1368
  case Qt::Key_Escape:
×
1369
    ui->lineEdit->clear();
×
1370
    break;
×
1371
  default:
1372
    break;
1373
  }
1374
}
×
1375

1376
/**
1377
 * @brief MainWindow::showContextMenu show us the (file or folder) context
1378
 * menu
1379
 * @param pos
1380
 */
1381
void MainWindow::showContextMenu(const QPoint &pos) {
×
1382
  QModelIndex index = ui->treeView->indexAt(pos);
×
1383
  bool selected = true;
1384
  if (!index.isValid()) {
1385
    ui->treeView->clearSelection();
×
1386
    ui->actionDelete->setEnabled(false);
×
1387
    ui->actionEdit->setEnabled(false);
×
1388
    m_currentDir = "";
×
1389
    selected = false;
1390
  }
1391

1392
  ui->treeView->setCurrentIndex(index);
×
1393

1394
  QPoint globalPos = ui->treeView->viewport()->mapToGlobal(pos);
×
1395

1396
  QFileInfo fileOrFolder =
1397
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
1398

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

1431
      auto *shareMenu = new QMenu(tr("Share"), &contextMenu);
×
1432
      contextMenu.addMenu(shareMenu);
×
1433

1434
      QString gpgIdPath = Pass::getGpgIdPath(dirPath);
×
1435
      bool gpgIdExists = !gpgIdPath.isEmpty() && QFile(gpgIdPath).exists();
×
1436

1437
      QString exePath = QtPassSettings::isUsePass()
×
1438
                            ? QtPassSettings::getPassExecutable()
×
1439
                            : QtPassSettings::getGpgExecutable();
×
1440
      bool gpgAvailable = !exePath.isEmpty() && (exePath.startsWith("wsl ") ||
×
1441
                                                 QFile(exePath).exists());
×
1442

1443
      QAction *reencrypt = shareMenu->addAction(tr("Re-encrypt all passwords"));
×
1444
      reencrypt->setEnabled(gpgIdExists && gpgAvailable);
×
1445
      connect(reencrypt, &QAction::triggered, this,
×
1446
              [this, dirPath]() { reencryptPath(dirPath); });
×
1447

1448
      QAction *exportKey = shareMenu->addAction(tr("Export my public key..."));
×
1449
      exportKey->setEnabled(gpgAvailable);
×
1450
      connect(exportKey, &QAction::triggered, this,
×
1451
              &MainWindow::exportPublicKey);
×
1452

1453
      QAction *addRecipientAction =
1454
          shareMenu->addAction(tr("Add recipient..."));
×
1455
      addRecipientAction->setEnabled(gpgIdExists && gpgAvailable);
×
1456
      connect(addRecipientAction, &QAction::triggered, this,
×
1457
              [this, dirPath]() { addRecipient(dirPath); });
×
1458

1459
      QAction *shareHelp = shareMenu->addAction(tr("What is this?"));
×
1460
      connect(shareHelp, &QAction::triggered, this, &MainWindow::showShareHelp);
×
1461
    }
1462
  }
1463
  contextMenu.exec(globalPos);
×
1464
}
×
1465

1466
/**
1467
 * @brief MainWindow::showBrowserContextMenu show us the context menu in
1468
 * password window
1469
 * @param pos
1470
 */
1471
void MainWindow::showBrowserContextMenu(const QPoint &pos) {
×
1472
  QMenu *contextMenu = ui->textBrowser->createStandardContextMenu(pos);
×
1473
  QPoint globalPos = ui->textBrowser->viewport()->mapToGlobal(pos);
×
1474

1475
  contextMenu->exec(globalPos);
×
1476
  delete contextMenu;
×
1477
}
×
1478

1479
/**
1480
 * @brief MainWindow::openFolder open the folder in the default file manager
1481
 */
1482
void MainWindow::openFolder() {
×
1483
  QString dir =
1484
      Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel);
×
1485

1486
  QString path = QDir::toNativeSeparators(dir);
×
1487
  QDesktopServices::openUrl(QUrl::fromLocalFile(path));
×
1488
}
×
1489

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

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

1561
/**
1562
 * @brief MainWindow::editPassword read password and open edit window via
1563
 * MainWindow::onEdit()
1564
 */
1565
void MainWindow::editPassword(const QString &file) {
×
1566
  if (!file.isEmpty()) {
×
1567
    if (QtPassSettings::isUseGit() && QtPassSettings::isAutoPull()) {
×
1568
      onUpdate(true);
×
1569
    }
1570
    setPassword(file, false);
×
1571
  }
1572
}
×
1573

1574
/**
1575
 * @brief MainWindow::renamePassword rename an existing password
1576
 */
1577
void MainWindow::renamePassword() {
×
1578
  bool ok;
1579
  QString file = getFile(ui->treeView->currentIndex(), false);
×
1580
  QString filePath = QFileInfo(file).path();
×
1581
  QString fileName = QFileInfo(file).fileName();
×
1582
  if (fileName.endsWith(".gpg", Qt::CaseInsensitive)) {
×
1583
    fileName.chop(4);
×
1584
  }
1585

1586
  QString newName =
1587
      QInputDialog::getText(this, tr("Rename file"), tr("Rename File To: "),
×
1588
                            QLineEdit::Normal, fileName, &ok);
×
1589
  if (!ok || newName.isEmpty()) {
×
1590
    return;
1591
  }
1592
  QString newFile = QDir(filePath).filePath(newName);
×
1593
  if (!confirmPathInStore(newFile)) {
×
1594
    return;
1595
  }
1596
  QtPassSettings::getPass()->Move(file, newFile, false);
×
1597
}
1598

1599
/**
1600
 * @brief MainWindow::clearTemplateWidgets empty the template widget fields in
1601
 * the UI
1602
 */
1603
void MainWindow::clearTemplateWidgets() {
×
1604
  while (ui->gridLayout->count() > 0) {
×
1605
    QLayoutItem *item = ui->gridLayout->takeAt(0);
×
1606
    delete item->widget();
×
1607
    delete item;
×
1608
  }
1609
  ui->verticalLayoutPassword->setSpacing(0);
×
1610
}
×
1611

1612
/**
1613
 * @brief Copies the password of the selected file from the tree view to the
1614
 * clipboard.
1615
 * @example
1616
 * MainWindow::copyPasswordFromTreeview();
1617
 *
1618
 * @return void - This function does not return a value.
1619
 */
1620
void MainWindow::copyPasswordFromTreeview() {
×
1621
  QFileInfo fileOrFolder =
1622
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
1623

1624
  if (fileOrFolder.isFile()) {
×
1625
    QString file = getFile(ui->treeView->currentIndex(), true);
×
1626
    // Disconnect any previous connection to avoid accumulation
1627
    disconnect(QtPassSettings::getPass(), &Pass::finishedShow, this,
×
1628
               &MainWindow::passwordFromFileToClipboard);
1629
    connect(QtPassSettings::getPass(), &Pass::finishedShow, this,
×
1630
            &MainWindow::passwordFromFileToClipboard);
×
1631
    QtPassSettings::getPass()->Show(file);
×
1632
  }
1633
}
×
1634

1635
void MainWindow::passwordFromFileToClipboard(const QString &text) {
×
1636
  QStringList tokens = text.split('\n');
×
1637
  m_qtPass->copyTextToClipboard(tokens[0]);
×
1638
}
×
1639

1640
/**
1641
 * @brief MainWindow::addToGridLayout add a field to the template grid
1642
 * @param position
1643
 * @param field
1644
 * @param value
1645
 */
1646
void MainWindow::addToGridLayout(int position, const QString &field,
×
1647
                                 const QString &value) {
1648
  QString trimmedField = field.trimmed();
1649
  QString trimmedValue = value.trimmed();
1650

1651
  const QString buttonStyle =
1652
      "border-style: none; background: transparent; padding: 0; margin: 0; "
1653
      "icon-size: 16px; color: inherit;";
×
1654

1655
  // Combine the Copy button and the line edit in one widget
1656
  auto *frame = new QFrame();
×
1657
  QLayout *ly = new QHBoxLayout();
×
1658
  ly->setContentsMargins(5, 2, 2, 2);
×
1659
  ly->setSpacing(0);
×
1660
  frame->setLayout(ly);
×
1661
  if (QtPassSettings::getClipBoardType() != Enums::CLIPBOARD_NEVER) {
×
1662
    auto *fieldLabel = new QPushButtonWithClipboard(trimmedValue, this);
×
1663
    connect(fieldLabel, &QPushButtonWithClipboard::clicked, m_qtPass,
×
1664
            &QtPass::copyTextToClipboard);
×
1665

1666
    fieldLabel->setStyleSheet(buttonStyle);
×
1667
    frame->layout()->addWidget(fieldLabel);
×
1668
  }
1669

1670
  if (QtPassSettings::isUseQrencode()) {
×
1671
    auto *qrbutton = new QPushButtonAsQRCode(trimmedValue, this);
×
1672
    connect(qrbutton, &QPushButtonAsQRCode::clicked, m_qtPass,
×
1673
            &QtPass::showTextAsQRCode);
×
1674
    qrbutton->setStyleSheet(buttonStyle);
×
1675
    frame->layout()->addWidget(qrbutton);
×
1676
  }
1677

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

1703
  // set the echo mode to password, if the field is "password"
1704
  const QString lineStyle =
1705
      QtPassSettings::isUseMonospace()
×
1706
          ? "border-style: none; background: transparent; font-family: "
1707
            "monospace;"
1708
          : "border-style: none; background: transparent;";
×
1709

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

1740
  frame->setStyleSheet(
×
1741
      ".QFrame{border: 1px solid lightgrey; border-radius: 5px;}");
1742

1743
  // set into the layout
1744
  ui->gridLayout->addWidget(new QLabel(trimmedField), position, 0);
×
1745
  ui->gridLayout->addWidget(frame, position, 1);
×
1746
}
×
1747

1748
/**
1749
 * @brief Displays message in status bar
1750
 *
1751
 * @param msg     text to be displayed
1752
 * @param timeout time for which msg shall be visible
1753
 */
1754
void MainWindow::showStatusMessage(const QString &msg, int timeout) {
2 ✔
1755
  ui->statusBar->showMessage(msg, timeout);
2 ✔
1756
}
2 ✔
1757

1758
/**
1759
 * @brief MainWindow::reencryptPath re-encrypt all passwords in a directory
1760
 * @param dir Directory path to re-encrypt
1761
 */
1762
void MainWindow::reencryptPath(const QString &dir) {
×
1763
  QDir checkDir(dir);
×
1764
  if (!checkDir.exists()) {
×
1765
    QMessageBox::critical(this, tr("Error"),
×
1766
                          tr("Directory does not exist: %1").arg(dir));
×
1767
    return;
×
1768
  }
1769

1770
  int ret = QMessageBox::question(
×
1771
      this, tr("Re-encrypt passwords"),
×
1772
      tr("Re-encrypt all passwords in %1?\n\n"
×
1773
         "This will re-encrypt ALL password files in this folder "
1774
         "using the current recipients defined in .gpg-id.\n\n"
1775
         "This may rewrite many files and cannot be undone easily.\n\n"
1776
         "Continue?")
1777
          .arg(QDir(dir).dirName()),
×
1778
      QMessageBox::Yes | QMessageBox::No);
1779

1780
  if (ret != QMessageBox::Yes)
×
1781
    return;
1782

1783
  // Disable preemptively. ImitatePass::reencryptPath emits
1784
  // startReencryptPath asynchronously and the slot would re-run this,
1785
  // but setEnabled(false) is idempotent so the duplicate is harmless.
1786
  startReencryptPath();
×
1787

1788
  QtPassSettings::getImitatePass()->reencryptPath(
×
1789
      QDir::cleanPath(QDir(dir).absolutePath()));
×
1790
}
×
1791

1792
/**
1793
 * @brief MainWindow::startReencryptPath disable ui elements and treeview
1794
 */
1795
void MainWindow::startReencryptPath() {
×
1796
  setUiElementsEnabled(false);
×
1797
  ui->treeView->setDisabled(true);
×
1798
}
×
1799

1800
/**
1801
 * @brief MainWindow::endReencryptPath re-enable ui elements
1802
 */
1803
void MainWindow::endReencryptPath() { setUiElementsEnabled(true); }
×
1804

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

1847
/**
1848
 * @brief MainWindow::addRecipient open the recipient management dialog for
1849
 *        the supplied directory.
1850
 * @param dir Folder whose .gpg-id should be edited.
1851
 *
1852
 * Delegates to UsersDialog so users can tick/untick keys from their
1853
 * keyring as recipients of the folder; importing a foreign key into the
1854
 * keyring still has to happen via gpg (or QtPass settings) first.
1855
 */
1856
void MainWindow::addRecipient(const QString &dir) {
×
1857
  UsersDialog d(dir, this);
×
1858
  d.exec();
×
1859
}
×
1860

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

1881
void MainWindow::updateGitButtonVisibility() {
15 ✔
1882
  if (!QtPassSettings::isUseGit() ||
30 ✔
1883
      (QtPassSettings::getGitExecutable().isEmpty() &&
15 ✔
1884
       QtPassSettings::getPassExecutable().isEmpty())) {
15 ✔
1885
    enableGitButtons(false);
15 ✔
1886
  } else {
1887
    enableGitButtons(true);
×
1888
  }
1889
}
15 ✔
1890

1891
void MainWindow::updateOtpButtonVisibility() {
15 ✔
1892
#if defined(Q_OS_WIN) || defined(__APPLE__)
1893
  ui->actionOtp->setVisible(false);
1894
#endif
1895
  if (!QtPassSettings::isUseOtp()) {
15 ✔
1896
    ui->actionOtp->setEnabled(false);
15 ✔
1897
  } else {
1898
    ui->actionOtp->setEnabled(true);
×
1899
  }
1900
}
15 ✔
1901

1902
void MainWindow::updateGrepButtonVisibility() {
12 ✔
1903
  const bool enabled = QtPassSettings::isUseGrepSearch();
12 ✔
1904
  ui->grepButton->setVisible(enabled);
12 ✔
1905
  ui->grepCaseButton->setVisible(enabled);
12 ✔
1906
  if (!enabled && m_grepMode) {
12 ✔
1907
    ui->grepButton->setChecked(false);
×
1908
  }
1909
}
12 ✔
1910

1911
void MainWindow::enableGitButtons(const bool &state) {
15 ✔
1912
  // Following GNOME guidelines is preferable disable buttons instead of hide
1913
  ui->actionPush->setEnabled(state);
15 ✔
1914
  ui->actionUpdate->setEnabled(state);
15 ✔
1915
}
15 ✔
1916

1917
/**
1918
 * @brief MainWindow::critical critical message popup wrapper.
1919
 * @param title
1920
 * @param msg
1921
 */
1922
void MainWindow::critical(const QString &title, const QString &msg) {
×
1923
  QMessageBox::critical(this, title, msg);
×
1924
}
×
1925

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

1943
  QStringList lines = output.split('\n', Qt::SkipEmptyParts);
1 ✔
1944
  for (QString &line : lines) {
2 ✔
1945
    // Right-trim only: remove trailing CR and whitespace, preserve leading
1946
    // indentation
1947
    line.remove('\r');
1 ✔
1948
    while (!line.isEmpty() && line.back().isSpace()) {
2 ✔
1949
      line.chop(1);
×
1950
    }
1951
    if (line.isEmpty()) {
1 ✔
1952
      continue;
×
1953
    }
1954

1955
    m_outputCounter++;
1 ✔
1956
    QString lineNumber = QString::number(m_outputCounter);
1 ✔
1957

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

1971
    m_processOutputEdit->append(coloredOutput);
1 ✔
1972
  }
1973

1974
  limitOutputLines();
1 ✔
1975

1976
  if (m_autoScroll) {
1 ✔
1977
    m_processOutputEdit->verticalScrollBar()->setValue(
2 ✔
1978
        m_processOutputEdit->verticalScrollBar()->maximum());
1 ✔
1979
  }
1980
}
1981

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

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

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

2089
/**
2090
 * @brief Updates the visibility of the process output panel.
2091
 *
2092
 * Shows or hides the process output widget based on the user's
2093
 * showProcessOutput setting.
2094
 */
2095
void MainWindow::updateProcessOutputVisibility() {
×
2096
  m_processOutputDock->setVisible(QtPassSettings::isShowProcessOutput());
×
2097
}
×
2098

2099
/**
2100
 * @brief Limits the output panel to max lines, trimming old excess.
2101
 *
2102
 * Removes the oldest lines when the document exceeds MaxOutputLines (1000).
2103
 * Called after each append to prevent unbounded growth.
2104
 */
2105
void MainWindow::limitOutputLines() {
1 ✔
2106
  QTextDocument *doc = m_processOutputEdit->document();
1 ✔
2107
  int excess = doc->blockCount() - MaxOutputLines;
1 ✔
2108
  if (excess <= 0) {
1 ✔
2109
    return;
1 ✔
2110
  }
2111

2112
  QTextCursor cursor(doc);
×
2113
  cursor.movePosition(QTextCursor::Start);
×
2114
  cursor.movePosition(QTextCursor::NextBlock, QTextCursor::KeepAnchor, excess);
×
2115
  cursor.removeSelectedText();
×
2116
}
×
2117

2118
/**
2119
 * @brief Clears the process output panel.
2120
 *
2121
 * Clears all output, resets the line counter, and re-enables auto-scroll.
2122
 */
2123
void MainWindow::on_clearOutputButton_clicked() {
×
2124
  m_processOutputEdit->clear();
×
2125
  m_outputCounter = 0;
×
2126
  m_autoScroll = true;
×
2127
}
×
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