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

IJHack / QtPass / 27697884856

17 Jun 2026 02:51PM UTC coverage: 57.128% (-0.1%) from 57.238%
27697884856

push

github

web-flow
refactor(#1511): wire passStore into static chain; parameterise Util::configIsValid/getDir (#1555)

* refactor(#1511): wire passStore into static chain; parameterise Util::configIsValid/getDir

- Pass::getGpgIdPath/getRecipientList/getRecipientString now take an
  explicit passStore parameter; removes qtpasssettings.h from pass.cpp
- Util::configIsValid(const AppSettings &) and getDir(..., passStore)
  parameterised; removes qtpasssettings.h from util.cpp
- imitatepass.cpp uses m_settings.passStore at all 4 call sites
- mainwindow.cpp, configdialog.cpp, qtpass.cpp, usersdialog.cpp updated
  at all affected call sites
- tst_util.cpp: PassStoreGuard+setPassStore boilerplate removed from
  static-chain tests; passStore passed directly; configIsValid/getDir
  calls updated with explicit AppSettings / passStore args

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(#1555): normalise fallback path, guard root store, update stale doc examples

- pass.cpp getGpgIdPath: use normalizedStore (not raw passStore) in the
  !found fallback so both branches always return a forward-slash path;
  guard the startsWith boundary check against root-store ("/") causing a
  "//" prefix by only appending "/" when cleanPassStore doesn't already
  end with one
- util.cpp: update @example and @param blocks for configIsValid and
  getDir to match their current signatures (AppSettings + passStore args)
- tst_util.cpp getGpgIdPathSubfolder: apply QDir::cleanPath to both
  sides of the comparison for cross-platform path separator consistency

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* style: clang-format mainwindow.cpp, pass.h, usersdialog.cpp, util.h

Reflow long Util::getDir / Pass::getRecipientString / getGpgIdPath call
sites that exceeded the 80-column limit after the passStore parameter was
added in the previous commit.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>

23 of 62 new or added lines in 7 files covered. (37.1%)

14 existing lines in 2 files now uncovered.

3963 of 6937 relevant lines covered (57.13%)

23.21 hits per line

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

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

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

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

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

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

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

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

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

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

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

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

121
  updateProfileBox();
12✔
122

123
  m_displayPanel = new PasswordDisplayPanel(
12✔
124
      ui->gridLayout, ui->verticalLayoutPassword, this, this);
12✔
125
  connect(m_displayPanel, &PasswordDisplayPanel::copyRequested, m_qtPass,
12✔
126
          &QtPass::copyTextToClipboard);
12✔
127
  connect(m_displayPanel, &PasswordDisplayPanel::qrRequested, m_qtPass,
12✔
128
          &QtPass::showTextAsQRCode);
12✔
129

130
  QtPassSettings::getPass()->updateEnv();
12✔
131
  clearPanelTimer.setInterval(MS_PER_SECOND *
12✔
132
                              QtPassSettings::getAutoclearPanelSeconds());
24✔
133
  clearPanelTimer.setSingleShot(true);
12✔
134
  connect(&clearPanelTimer, &QTimer::timeout, this, [this]() { clearPanel(); });
12✔
135

136
  searchTimer.setInterval(350);
12✔
137
  searchTimer.setSingleShot(true);
12✔
138

139
  connect(&searchTimer, &QTimer::timeout, this, &MainWindow::onTimeoutSearch);
12✔
140

141
  // Install the search-box key filter once, not on every setUiElementsEnabled
142
  // call.
143
  ui->lineEdit->installEventFilter(this);
12✔
144

145
  // Safety net: if a backend operation disables the UI but never signals
146
  // completion, re-enable after a timeout so the window can't get stuck.
147
  m_uiWatchdog.setSingleShot(true);
12✔
148
  m_uiWatchdog.setInterval(UiWatchdogMs);
12✔
149
  connect(&m_uiWatchdog, &QTimer::timeout, this, [this]() {
12✔
150
    showStatusMessage(tr("Operation timed out; re-enabling interface."));
×
151
    setUiElementsEnabled(true);
×
152
  });
×
153

154
  initToolBarButtons();
12✔
155
  initStatusBar();
12✔
156
  initProcessOutputPanel();
12✔
157

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

179
  ui->lineEdit->setClearButtonEnabled(true);
12✔
180
  updateGrepButtonVisibility();
12✔
181

182
  setUiElementsEnabled(true);
12✔
183

184
  ui->lineEdit->setText(searchText);
12✔
185

186
  if (!m_qtPass->init()) {
12✔
187
    // no working config so this should just quit
188
    QApplication::quit();
×
189
    return;
190
  }
191

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

201
MainWindow::~MainWindow() { delete m_qtPass; }
36✔
202

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

241
/**
242
 * @brief MainWindow::changeEvent sets focus to the search box
243
 * @param event
244
 */
245
void MainWindow::changeEvent(QEvent *event) {
12✔
246
  QWidget::changeEvent(event);
12✔
247
  if (event->type() == QEvent::ActivationChange && isActiveWindow() &&
12✔
248
      isVisible()) {
249
    // Defer one event-loop tick so the synchronous activation dispatch
250
    // chain (`QApplicationPrivate::setActiveWindow` → `notify_helper`)
251
    // unwinds before we touch widget state — calling `focusInput()`
252
    // inline from this stack has segfaulted in past iterations because
253
    // mid-rebuild ui state isn't fully wired up yet.
254
    QMetaObject::invokeMethod(this, &MainWindow::focusInput,
×
255
                              Qt::QueuedConnection);
256
  }
257
}
12✔
258

259
/**
260
 * @brief First-show hook: run the initial focusInput() pulse once the
261
 *        window is actually mapped. The widget's internal data is fully
262
 *        initialised by this point, so QLineEdit::selectAll() is safe.
263
 * @param event Show event passed to the base class.
264
 */
265
void MainWindow::showEvent(QShowEvent *event) {
×
266
  QMainWindow::showEvent(event);
×
267
  if (m_firstShowCompleted) {
×
268
    return;
269
  }
270
  // Queue the focus pulse for the next event-loop tick so the platform
271
  // map round-trip and any pending widget rebuilds (e.g. setWindowFlags
272
  // from the config wizard path) settle before we look up the line
273
  // edit. The `m_firstShowCompleted` latch is set inside focusInput()
274
  // *after* it actually focuses, so a transient failed lookup just
275
  // re-queues on the next show rather than silently dropping.
276
  QMetaObject::invokeMethod(this, &MainWindow::focusInput,
×
277
                            Qt::QueuedConnection);
278
}
279

280
/**
281
 * @brief MainWindow::initToolBarButtons init main ToolBar and connect actions
282
 */
283
void MainWindow::initToolBarButtons() {
12✔
284
  connect(ui->actionAddPassword, &QAction::triggered, this,
12✔
285
          &MainWindow::addPassword);
12✔
286
  connect(ui->actionAddFolder, &QAction::triggered, this,
12✔
287
          &MainWindow::addFolder);
12✔
288
  connect(ui->actionEdit, &QAction::triggered, this, &MainWindow::onEdit);
12✔
289
  connect(ui->actionDelete, &QAction::triggered, this, &MainWindow::onDelete);
12✔
290
  connect(ui->actionPush, &QAction::triggered, this, &MainWindow::onPush);
12✔
291
  connect(ui->actionUpdate, &QAction::triggered, this, &MainWindow::onUpdate);
12✔
292
  connect(ui->actionUsers, &QAction::triggered, this, &MainWindow::onUsers);
12✔
293
  connect(ui->actionConfig, &QAction::triggered, this, &MainWindow::onConfig);
12✔
294
  connect(ui->actionOtp, &QAction::triggered, this, &MainWindow::onOtp);
12✔
295

296
  ui->actionAddPassword->setIcon(
12✔
297
      QIcon::fromTheme("document-new", QIcon(":/icons/document-new.svg")));
48✔
298
  ui->actionAddFolder->setIcon(
12✔
299
      QIcon::fromTheme("folder-new", QIcon(":/icons/folder-new.svg")));
48✔
300
  ui->actionEdit->setIcon(QIcon::fromTheme(
12✔
301
      "document-properties", QIcon(":/icons/document-properties.svg")));
36✔
302
  ui->actionDelete->setIcon(
12✔
303
      QIcon::fromTheme("edit-delete", QIcon(":/icons/edit-delete.svg")));
48✔
304
  ui->actionPush->setIcon(
12✔
305
      QIcon::fromTheme("go-up", QIcon(":/icons/go-top.svg")));
48✔
306
  ui->actionUpdate->setIcon(
12✔
307
      QIcon::fromTheme("go-down", QIcon(":/icons/go-bottom.svg")));
48✔
308
  ui->actionUsers->setIcon(QIcon::fromTheme(
12✔
309
      "x-office-address-book", QIcon(":/icons/x-office-address-book.svg")));
36✔
310
  ui->actionConfig->setIcon(QIcon::fromTheme(
12✔
311
      "applications-system", QIcon(":/icons/applications-system.svg")));
24✔
312
}
12✔
313

314
/**
315
 * @brief MainWindow::initStatusBar init statusBar with default message and logo
316
 */
317
void MainWindow::initStatusBar() {
12✔
318
  ui->statusBar->showMessage(tr("Welcome to QtPass %1").arg(VERSION), 2000);
24✔
319

320
  QPixmap logo = QPixmap::fromImage(QImage(":/artwork/icon.svg"))
24✔
321
                     .scaledToHeight(statusBar()->height());
12✔
322
  auto *logoApp = new QLabel(statusBar());
12✔
323
  logoApp->setPixmap(logo);
12✔
324
  statusBar()->addPermanentWidget(logoApp);
12✔
325
}
12✔
326

327
/**
328
 * @brief Build the process-output panel as a bottom QDockWidget.
329
 *
330
 * The panel is constructed programmatically rather than declared in
331
 * mainwindow.ui: uic only places QMainWindow's top-level children into
332
 * the centralWidget / statusBar / menuBar / toolBars / dock-widget
333
 * slots, and the previous home (statusBar()->addPermanentWidget()) made
334
 * an 80–150 px tall QTextEdit sit inside what is otherwise a thin
335
 * status row. A QDockWidget at the bottom dock area is the conventional
336
 * place for an IDE-style output console, and it gives users
337
 * detach/move for free.
338
 */
339
void MainWindow::initProcessOutputPanel() {
12✔
340
  m_processOutputWidget = new QWidget;
12✔
341
  m_processOutputWidget->setObjectName(QStringLiteral("processOutputWidget"));
24✔
342
  auto *outputLayout = new QHBoxLayout(m_processOutputWidget);
12✔
343
  outputLayout->setObjectName(QStringLiteral("processOutputLayout"));
24✔
344
  outputLayout->setContentsMargins(0, 0, 0, 0);
12✔
345
  m_clearOutputButton = new QToolButton(m_processOutputWidget);
12✔
346
  m_clearOutputButton->setObjectName(QStringLiteral("clearOutputButton"));
24✔
347
  m_clearOutputButton->setText(tr("Clear"));
12✔
348
  m_clearOutputButton->setToolTip(tr("Clear output"));
12✔
349
  outputLayout->addWidget(m_clearOutputButton);
12✔
350
  m_processOutputEdit = new QTextEdit(m_processOutputWidget);
12✔
351
  m_processOutputEdit->setObjectName(QStringLiteral("processOutputEdit"));
24✔
352
  m_processOutputEdit->setReadOnly(true);
12✔
353
  m_processOutputEdit->setAcceptRichText(false);
12✔
354
  outputLayout->addWidget(m_processOutputEdit);
12✔
355

356
  m_processOutputDock = new QDockWidget(tr("Process Output"), this);
12✔
357
  m_processOutputDock->setObjectName(QStringLiteral("processOutputDock"));
24✔
358
  m_processOutputDock->setFeatures(QDockWidget::DockWidgetMovable |
12✔
359
                                   QDockWidget::DockWidgetFloatable);
360
  m_processOutputDock->setAllowedAreas(Qt::BottomDockWidgetArea |
12✔
361
                                       Qt::TopDockWidgetArea);
362
  m_processOutputDock->setWidget(m_processOutputWidget);
12✔
363
  addDockWidget(Qt::BottomDockWidgetArea, m_processOutputDock);
12✔
364
  // setVisible after addDockWidget so our explicit preference wins
365
  // even if QMainWindow applies any cached state when the dock is
366
  // attached. restoreWindow() runs before this method (it's called
367
  // from the QtPass ctor, which is constructed at the top of the
368
  // MainWindow ctor), so the saved layout has already been processed
369
  // by the time we get here.
370
  m_processOutputDock->setVisible(QtPassSettings::isShowProcessOutput());
12✔
371

372
  connect(m_clearOutputButton, &QToolButton::clicked, this,
12✔
373
          &MainWindow::on_clearOutputButton_clicked);
12✔
374

375
  // Hysteresis: while the user is actively dragging the slider, don't
376
  // touch m_autoScroll on every tick — a brief overshoot at maximum
377
  // would silently re-arm auto-scroll without an explicit release. Only
378
  // commit on slider release. Wheel/keyboard scroll never sets
379
  // isSliderDown(), so they still update immediately.
380
  connect(m_processOutputEdit->verticalScrollBar(), &QScrollBar::valueChanged,
12✔
381
          this, [this]() {
12✔
382
            auto *sb = m_processOutputEdit->verticalScrollBar();
×
383
            if (sb->isSliderDown())
×
384
              return;
385
            m_autoScroll = sb->value() >= sb->maximum();
×
386
          });
387
  connect(m_processOutputEdit->verticalScrollBar(), &QScrollBar::sliderReleased,
12✔
388
          this, [this]() {
12✔
389
            auto *sb = m_processOutputEdit->verticalScrollBar();
×
390
            m_autoScroll = sb->value() >= sb->maximum();
×
391
          });
×
392
}
12✔
393

394
auto MainWindow::getCurrentTreeViewIndex() -> QModelIndex {
×
395
  return ui->treeView->currentIndex();
×
396
}
397

398
void MainWindow::cleanKeygenDialog() {
1✔
399
  if (m_keyGenDialog != nullptr) {
1✔
400
    m_keyGenDialog->close();
×
401
  }
402
  m_keyGenDialog = nullptr;
1✔
403
}
1✔
404

405
/**
406
 * @brief Displays the given text in the main window text browser, optionally
407
 * marking it as an error and/or rendering it as HTML.
408
 * @example
409
 * MainWindow window;
410
 * window.flashText("Operation completed.", false, false);
411
 *
412
 * @param const QString &text - The text content to display.
413
 * @param const bool isError - If true, sets the text color to red before
414
 * displaying the text.
415
 * @param const bool isHtml - If true, treats the text as HTML and appends it to
416
 * the existing HTML content.
417
 * @return void - No return value.
418
 */
419
void MainWindow::flashText(const QString &text, const bool isError,
3✔
420
                           const bool isHtml) {
421
  if (isError) {
3✔
422
    ui->textBrowser->setTextColor(Qt::red);
1✔
423
  }
424

425
  if (isHtml) {
3✔
426
    QString _text = text;
427
    if (!ui->textBrowser->toPlainText().isEmpty()) {
2✔
428
      _text = ui->textBrowser->toHtml() + _text;
2✔
429
    }
430
    ui->textBrowser->setHtml(_text);
1✔
431
  } else {
432
    ui->textBrowser->setText(text);
2✔
433
  }
434
}
3✔
435

436
/**
437
 * @brief MainWindow::config pops up the configuration screen and handles all
438
 * inter-window communication
439
 */
440
void MainWindow::applyTextBrowserSettings() {
×
441
  if (QtPassSettings::isUseMonospace()) {
×
442
    QFont monospace("Monospace");
×
443
    monospace.setStyleHint(QFont::Monospace);
×
444
    ui->textBrowser->setFont(monospace);
×
445
  } else {
×
446
    ui->textBrowser->setFont(QFont());
×
447
  }
448

449
  if (QtPassSettings::isNoLineWrapping()) {
×
450
    ui->textBrowser->setLineWrapMode(QTextBrowser::NoWrap);
×
451
  } else {
452
    ui->textBrowser->setLineWrapMode(QTextBrowser::WidgetWidth);
×
453
  }
454
}
×
455

456
void MainWindow::applyWindowFlagsSettings() {
×
457
  if (QtPassSettings::isAlwaysOnTop()) {
×
458
    Qt::WindowFlags flags = windowFlags();
459
    this->setWindowFlags(flags | Qt::WindowStaysOnTopHint);
×
460
  } else {
461
    this->setWindowFlags(Qt::Window);
×
462
  }
463
  this->show();
×
464
}
×
465

466
/**
467
 * @brief Opens and processes the application configuration dialog, then applies
468
 * any accepted settings.
469
 * @example
470
 * config();
471
 *
472
 * @return void - This function does not return a value.
473
 */
474
void MainWindow::config() {
×
475
  QScopedPointer<ConfigDialog> d(new ConfigDialog(this));
×
476
  d->setModal(true);
×
477
  // Automatically default to pass if it's available
478
  if (m_qtPass->isFreshStart() &&
×
479
      QFile(QtPassSettings::getPassExecutable()).exists()) {
×
480
    QtPassSettings::setUsePass(true);
×
481
  }
482

483
  if (m_qtPass->isFreshStart()) {
×
484
    d->wizard(); // run initial setup wizard for first-time configuration
×
485
  }
486
  if (d->exec()) {
×
487
    if (d->result() == QDialog::Accepted) {
×
488
      applyTextBrowserSettings();
×
489
      applyWindowFlagsSettings();
×
490

491
      updateProfileBox();
×
492
      const QString passStore = QtPassSettings::getPassStore();
×
493
      proxyModel.setStore(passStore);
×
494
      ui->treeView->setRootIndex(proxyModel.rootIndexFor(passStore));
×
495
      deselect();
×
496
      ui->treeView->setCurrentIndex(QModelIndex());
×
497

NEW
498
      if (m_qtPass->isFreshStart() &&
×
NEW
499
          !Util::configIsValid(QtPassSettings::load())) {
×
UNCOV
500
        config();
×
501
      }
502
      QtPassSettings::getPass()->updateEnv();
×
503
      clearPanelTimer.setInterval(MS_PER_SECOND *
×
504
                                  QtPassSettings::getAutoclearPanelSeconds());
×
505
      m_qtPass->setClipboardTimer();
×
506

507
      updateGitButtonVisibility();
×
508
      updateOtpButtonVisibility();
×
509
      updateGrepButtonVisibility();
×
510
      updateProcessOutputVisibility();
×
511
      if (QtPassSettings::isUseTrayIcon() && m_tray == nullptr) {
×
512
        initTrayIcon();
×
513
      } else if (!QtPassSettings::isUseTrayIcon() && m_tray != nullptr) {
×
514
        destroyTrayIcon();
×
515
      }
516
    }
517

518
    m_qtPass->setFreshStart(false);
×
519
  }
520
}
×
521

522
/**
523
 * @brief MainWindow::onUpdate do a git pull
524
 */
525
void MainWindow::onUpdate(bool block) {
×
526
  ui->statusBar->showMessage(tr("Updating password-store"), 2000);
×
527
  if (block) {
×
528
    QtPassSettings::getPass()->GitPull_b();
×
529
  } else {
530
    QtPassSettings::getPass()->GitPull();
×
531
  }
532
}
×
533

534
/**
535
 * @brief MainWindow::onPush do a git push
536
 */
537
void MainWindow::onPush() {
×
538
  if (QtPassSettings::isUseGit()) {
×
539
    ui->statusBar->showMessage(tr("Updating password-store"), 2000);
×
540
    QtPassSettings::getPass()->GitPush();
×
541
  }
542
}
×
543

544
/**
545
 * @brief MainWindow::getFile get the selected file path
546
 * @param index
547
 * @param forPass returns relative path without '.gpg' extension
548
 * @return path
549
 * @return
550
 */
551
auto MainWindow::getFile(const QModelIndex &index, bool forPass) -> QString {
×
552
  if (!index.isValid() ||
×
553
      !model.fileInfo(proxyModel.mapToSource(index)).isFile()) {
×
554
    return {};
555
  }
556
  QString filePath = model.filePath(proxyModel.mapToSource(index));
×
557
  if (forPass) {
×
558
    filePath = QDir(QtPassSettings::getPassStore()).relativeFilePath(filePath);
×
559
    filePath.replace(Util::endsWithGpg(), "");
×
560
  }
561
  return filePath;
562
}
563

564
/**
565
 * @brief MainWindow::on_treeView_clicked read the selected password file
566
 * @param index
567
 */
568
void MainWindow::on_treeView_clicked(const QModelIndex &index) {
×
569
  bool cleared = ui->treeView->currentIndex().flags() == Qt::NoItemFlags;
×
NEW
570
  m_currentDir = Util::getDir(ui->treeView->currentIndex(), false, model,
×
NEW
571
                              proxyModel, QtPassSettings::getPassStore());
×
572
  // Clear any previously cached clipped text before showing new password
573
  m_qtPass->clearClippedText();
×
574
  QString file = getFile(index, true);
×
575
  ui->passwordName->setText(file);
×
576
  if (!file.isEmpty() && !cleared) {
×
577
    QtPassSettings::getPass()->Show(file);
×
578
  } else {
579
    clearPanel(false);
×
580
    ui->actionEdit->setEnabled(false);
×
581
    ui->actionDelete->setEnabled(true);
×
582
  }
583
}
×
584

585
/**
586
 * @brief MainWindow::on_treeView_doubleClicked when doubleclicked on
587
 * TreeViewItem, open the edit Window
588
 * @param index
589
 */
590
void MainWindow::on_treeView_doubleClicked(const QModelIndex &index) {
×
591
  QFileInfo fileOrFolder =
592
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
593

594
  if (fileOrFolder.isFile()) {
×
595
    editPassword(getFile(index, true));
×
596
  }
597
}
×
598

599
/**
600
 * @brief MainWindow::deselect clear the selection, password and copy buffer
601
 */
602
void MainWindow::deselect() {
1✔
603
  m_currentDir = "";
1✔
604
  m_qtPass->clearClipboard();
1✔
605
  ui->treeView->clearSelection();
1✔
606
  ui->actionEdit->setEnabled(false);
1✔
607
  ui->actionDelete->setEnabled(false);
1✔
608
  ui->passwordName->setText("");
1✔
609
  clearPanel(false);
1✔
610
}
1✔
611

612
void MainWindow::executeWrapperStarted() {
×
613
  m_displayPanel->clear();
×
614
  ui->textBrowser->clear();
×
615
  setUiElementsEnabled(false);
×
616
  clearPanelTimer.stop();
×
617
  if (QtPassSettings::isShowProcessOutput()) {
×
618
    m_processOutputDock->setVisible(true);
×
619
  }
620
}
×
621

622
/**
623
 * @brief Handles displaying parsed password entry content in the main window.
624
 * @example
625
 * void result = MainWindow::passShowHandler(p_output);
626
 * // Updates the UI with parsed fields and emits
627
 * passShowHandlerFinished(output)
628
 *
629
 * @param p_output - The raw output text containing the password entry data.
630
 * @return void - This function does not return a value.
631
 */
632
void MainWindow::passShowHandler(const QString &p_output) {
×
633
  const AppSettings s = QtPassSettings::load();
×
634
  QStringList templ =
635
      s.useTemplate ? s.passTemplate.split("\n") : QStringList();
×
636
  bool allFields = s.useTemplate && s.templateAllFields;
×
637
  FileContent fileContent = FileContent::parse(p_output, templ, allFields);
×
638
  QString output = p_output;
639
  QString password = fileContent.getPassword();
×
640

641
  // set clipped text
642
  m_qtPass->setClippedText(password, p_output);
×
643

644
  // first clear the current view:
645
  m_displayPanel->clear();
×
646

647
  // show what is needed:
648
  if (s.hideContent) {
×
649
    output = "***" + tr("Content hidden") + "***";
×
650
  } else if (!s.displayAsIs) {
×
651
    m_displayPanel->displayFields(password, fileContent.getNamedValues(), s);
×
652
    output = fileContent.getRemainingDataForDisplay();
×
653
  }
654

655
  if (s.useAutoclearPanel) {
×
656
    clearPanelTimer.start();
×
657
  }
658

659
  emit passShowHandlerFinished(output);
×
660
  setUiElementsEnabled(true);
×
661
}
×
662

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

688
/**
689
 * @brief MainWindow::clearPanel hide the information from shoulder surfers
690
 */
691
void MainWindow::clearPanel(bool notify) {
1✔
692
  m_displayPanel->clear();
1✔
693
  const bool grepWasVisible = ui->grepResultsList->isVisible();
1✔
694
  ui->grepResultsList->clear();
1✔
695
  if (grepWasVisible) {
1✔
696
    ui->grepResultsList->setVisible(false);
×
697
    ui->treeView->setVisible(true);
×
698
    if (m_grep.inGrepMode()) {
×
699
      m_grep.clearGrepMode();
700
      ui->grepButton->blockSignals(true);
×
701
      ui->grepButton->setChecked(false);
×
702
      ui->grepButton->blockSignals(false);
×
703
      ui->lineEdit->blockSignals(true);
×
704
      ui->lineEdit->clear();
×
705
      ui->lineEdit->blockSignals(false);
×
706
      ui->lineEdit->setPlaceholderText(tr("Search Password"));
×
707
    }
708
  }
709
  if (notify) {
1✔
710
    QString output = "***" + tr("Password and Content hidden") + "***";
×
711
    ui->textBrowser->setHtml(output);
×
712
  } else {
713
    ui->textBrowser->setHtml("");
2✔
714
  }
715
}
1✔
716

717
/**
718
 * @brief MainWindow::setUiElementsEnabled enable or disable the relevant UI
719
 * elements
720
 * @param state
721
 */
722
void MainWindow::setUiElementsEnabled(bool state) {
15✔
723
  // Arm the watchdog while the UI is disabled; disarm once re-enabled.
724
  if (state) {
15✔
725
    m_uiWatchdog.stop();
13✔
726
  } else {
727
    m_uiWatchdog.start();
2✔
728
  }
729
  ui->treeView->setEnabled(state);
15✔
730
  ui->lineEdit->setEnabled(state);
15✔
731
  ui->actionAddPassword->setEnabled(state);
15✔
732
  ui->actionAddFolder->setEnabled(state);
15✔
733
  ui->actionUsers->setEnabled(state);
15✔
734
  ui->actionConfig->setEnabled(state);
15✔
735
  // is a file selected?
736
  state &= ui->treeView->currentIndex().isValid();
30✔
737
  ui->actionDelete->setEnabled(state);
15✔
738
  ui->actionEdit->setEnabled(state);
15✔
739
  updateGitButtonVisibility();
15✔
740
  updateOtpButtonVisibility();
15✔
741
}
15✔
742

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

765
  if (QtPassSettings::isAlwaysOnTop()) {
12✔
766
    Qt::WindowFlags flags = windowFlags();
767
    setWindowFlags(flags | Qt::WindowStaysOnTopHint);
×
768
    show();
×
769
  }
770

771
  if (QtPassSettings::isUseTrayIcon() && m_tray == nullptr) {
24✔
772
    initTrayIcon();
×
773
    if (QtPassSettings::isStartMinimized()) {
×
774
      // since we are still in constructor, can't directly hide
775
      QTimer::singleShot(10, this, SLOT(hide()));
×
776
    }
777
  } else if (!QtPassSettings::isUseTrayIcon() && m_tray != nullptr) {
24✔
778
    destroyTrayIcon();
×
779
  }
780
}
12✔
781

782
/**
783
 * @brief MainWindow::on_configButton_clicked run Mainwindow::config
784
 */
785
void MainWindow::onConfig() { config(); }
×
786

787
/**
788
 * @brief Executes when the string in the search box changes, collapses the
789
 * TreeView
790
 * @param arg1
791
 */
792
void MainWindow::on_lineEdit_textChanged(const QString &arg1) {
×
793
  if (m_grep.inGrepMode())
×
794
    return;
795
  ui->statusBar->showMessage(tr("Looking for: %1").arg(arg1), 1000);
×
796
  ui->treeView->expandAll();
×
797
  clearPanel(false);
×
798
  ui->passwordName->setText("");
×
799
  ui->actionEdit->setEnabled(false);
×
800
  ui->actionDelete->setEnabled(false);
×
801
  searchTimer.start();
×
802
}
803

804
/**
805
 * @brief MainWindow::onTimeoutSearch Fired when search is finished or too much
806
 * time from two keypresses is elapsed
807
 */
808
void MainWindow::onTimeoutSearch() {
×
809
  QString query = ui->lineEdit->text();
×
810

811
  if (query.isEmpty()) {
×
812
    ui->treeView->collapseAll();
×
813
    deselect();
×
814
  }
815

816
  query.replace(QStringLiteral(" "), ".*");
×
817
  QRegularExpression regExp(query, QRegularExpression::CaseInsensitiveOption);
×
818
  proxyModel.setFilterRegularExpression(regExp);
×
819
  ui->treeView->setRootIndex(
×
820
      proxyModel.rootIndexFor(QtPassSettings::getPassStore()));
×
821

822
  if (proxyModel.rowCount() > 0 && !query.isEmpty()) {
×
823
    selectFirstFile();
×
824
  } else {
825
    ui->actionEdit->setEnabled(false);
×
826
    ui->actionDelete->setEnabled(false);
×
827
  }
828
}
×
829

830
/**
831
 * @brief MainWindow::on_lineEdit_returnPressed get searching
832
 *
833
 * Select the first possible file in the tree
834
 */
835
void MainWindow::on_lineEdit_returnPressed() {
×
836
#ifdef QT_DEBUG
837
  dbg() << "on_lineEdit_returnPressed" << proxyModel.rowCount();
838
#endif
839

840
  if (m_grep.inGrepMode()) {
×
841
    const QString query = ui->lineEdit->text();
×
842
    if (!query.isEmpty()) {
×
843
      ui->grepResultsList->clear();
×
844
      ui->statusBar->showMessage(tr("Searching…"));
×
845
      if (m_grep.beginSearch()) {
846
        QApplication::setOverrideCursor(Qt::WaitCursor);
×
847
      }
848
      QtPassSettings::getPass()->Grep(query, ui->grepCaseButton->isChecked());
×
849
    } else {
850
      if (m_grep.cancelSearch()) {
851
        QApplication::restoreOverrideCursor();
×
852
      }
853
      ui->grepResultsList->clear();
×
854
      ui->grepResultsList->setVisible(false);
×
855
      ui->treeView->setVisible(true);
×
856
    }
857
    return;
858
  }
859

860
  if (proxyModel.rowCount() > 0) {
×
861
    selectFirstFile();
×
862
    on_treeView_clicked(ui->treeView->currentIndex());
×
863
  }
864
}
865

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

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

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

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

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

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

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

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

1061
  if (!d.exec()) {
×
1062
    ui->treeView->setFocus();
×
1063
  }
1064
}
×
1065

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

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

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

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

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

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

1143
  QtPassSettings::getPass()->Remove(file, isDir);
×
1144
}
×
1145

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

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

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

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

1191
  UsersDialog d(dir, this);
×
1192
  if (!d.exec()) {
×
1193
    ui->treeView->setFocus();
×
1194
  }
1195
}
×
1196

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

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

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

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

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

1277
  ui->lineEdit->clear();
×
1278

1279
  QtPassSettings::setProfile(name);
×
1280

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

1287
  QtPassSettings::getPass()->updateEnv();
×
1288

1289
  const QString passStore = QtPassSettings::getPassStore();
×
1290
  proxyModel.setStore(passStore);
×
1291
  ui->treeView->setRootIndex(proxyModel.rootIndexFor(passStore));
×
1292
  deselect();
×
1293
  ui->treeView->setCurrentIndex(QModelIndex());
×
1294
}
1295

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

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

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

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

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

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

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

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

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

1403
  ui->treeView->setCurrentIndex(index);
×
1404

1405
  QPoint globalPos = ui->treeView->viewport()->mapToGlobal(pos);
×
1406

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

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

1443
      auto *shareMenu = new QMenu(tr("Share"), &contextMenu);
×
1444
      contextMenu.addMenu(shareMenu);
×
1445

1446
      QString gpgIdPath =
NEW
1447
          Pass::getGpgIdPath(dirPath, QtPassSettings::getPassStore());
×
UNCOV
1448
      bool gpgIdExists = !gpgIdPath.isEmpty() && QFile(gpgIdPath).exists();
×
1449

1450
      QString exePath = QtPassSettings::isUsePass()
×
1451
                            ? QtPassSettings::getPassExecutable()
×
1452
                            : QtPassSettings::getGpgExecutable();
×
1453
      bool gpgAvailable = !exePath.isEmpty() && (exePath.startsWith("wsl ") ||
×
1454
                                                 QFile(exePath).exists());
×
1455

1456
      QAction *reencrypt = shareMenu->addAction(tr("Re-encrypt all passwords"));
×
1457
      reencrypt->setEnabled(gpgIdExists && gpgAvailable);
×
1458
      connect(reencrypt, &QAction::triggered, this,
×
1459
              [this, dirPath]() { reencryptPath(dirPath); });
×
1460

1461
      QAction *exportKey = shareMenu->addAction(tr("Export my public key..."));
×
1462
      exportKey->setEnabled(gpgAvailable);
×
1463
      connect(exportKey, &QAction::triggered, this,
×
1464
              &MainWindow::exportPublicKey);
×
1465

1466
      QAction *addRecipientAction =
1467
          shareMenu->addAction(tr("Add recipient..."));
×
1468
      addRecipientAction->setEnabled(gpgIdExists && gpgAvailable);
×
1469
      connect(addRecipientAction, &QAction::triggered, this,
×
1470
              [this, dirPath]() { addRecipient(dirPath); });
×
1471

1472
      QAction *shareHelp = shareMenu->addAction(tr("What is this?"));
×
1473
      connect(shareHelp, &QAction::triggered, this, &MainWindow::showShareHelp);
×
1474
    }
1475
  }
1476
  contextMenu.exec(globalPos);
×
1477
}
×
1478

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

1488
  contextMenu->exec(globalPos);
×
1489
  delete contextMenu;
×
1490
}
×
1491

1492
/**
1493
 * @brief MainWindow::openFolder open the folder in the default file manager
1494
 */
1495
void MainWindow::openFolder() {
×
NEW
1496
  QString dir = Util::getDir(ui->treeView->currentIndex(), false, model,
×
NEW
1497
                             proxyModel, QtPassSettings::getPassStore());
×
1498

1499
  QString path = QDir::toNativeSeparators(dir);
×
1500
  QDesktopServices::openUrl(QUrl::fromLocalFile(path));
×
1501
}
×
1502

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

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

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

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

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

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

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

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

1641
/**
1642
 * @brief Displays message in status bar
1643
 *
1644
 * @param msg     text to be displayed
1645
 * @param timeout time for which msg shall be visible
1646
 */
1647
void MainWindow::showStatusMessage(const QString &msg, int timeout) {
2✔
1648
  ui->statusBar->showMessage(msg, timeout);
2✔
1649
}
2✔
1650

1651
/**
1652
 * @brief MainWindow::reencryptPath re-encrypt all passwords in a directory
1653
 * @param dir Directory path to re-encrypt
1654
 */
1655
void MainWindow::reencryptPath(const QString &dir) {
×
1656
  QDir checkDir(dir);
×
1657
  if (!checkDir.exists()) {
×
1658
    QMessageBox::critical(this, tr("Error"),
×
1659
                          tr("Directory does not exist: %1").arg(dir));
×
1660
    return;
×
1661
  }
1662

1663
  int ret = QMessageBox::question(
×
1664
      this, tr("Re-encrypt passwords"),
×
1665
      tr("Re-encrypt all passwords in %1?\n\n"
×
1666
         "This will re-encrypt ALL password files in this folder "
1667
         "using the current recipients defined in .gpg-id.\n\n"
1668
         "This may rewrite many files and cannot be undone easily.\n\n"
1669
         "Continue?")
1670
          .arg(QDir(dir).dirName()),
×
1671
      QMessageBox::Yes | QMessageBox::No);
1672

1673
  if (ret != QMessageBox::Yes)
×
1674
    return;
1675

1676
  // Disable preemptively. ImitatePass::reencryptPath emits
1677
  // startReencryptPath asynchronously and the slot would re-run this,
1678
  // but setEnabled(false) is idempotent so the duplicate is harmless.
1679
  startReencryptPath();
×
1680

1681
  QtPassSettings::getImitatePass()->reencryptPath(
×
1682
      QDir::cleanPath(QDir(dir).absolutePath()));
×
1683
}
×
1684

1685
/**
1686
 * @brief MainWindow::startReencryptPath disable ui elements and treeview
1687
 */
1688
void MainWindow::startReencryptPath() {
×
1689
  setUiElementsEnabled(false);
×
1690
  ui->treeView->setDisabled(true);
×
1691
}
×
1692

1693
/**
1694
 * @brief MainWindow::endReencryptPath re-enable ui elements
1695
 */
1696
void MainWindow::endReencryptPath() { setUiElementsEnabled(true); }
×
1697

1698
/**
1699
 * @brief MainWindow::exportPublicKey export the configured signing key in
1700
 *        ASCII-armored form via gpg and show it in ExportPublicKeyDialog.
1701
 *
1702
 * Falls back to a help dialog when no signing key is configured or gpg is
1703
 * unavailable, so the user still gets actionable guidance.
1704
 */
1705
void MainWindow::exportPublicKey() {
×
1706
  QString identity = QtPassSettings::getPassSigningKey();
×
1707
  if (identity.isEmpty()) {
×
1708
    QMessageBox::information(
×
1709
        this, tr("Export Public Key"),
×
1710
        tr("<h3>Export Your Public Key</h3>"
×
1711
           "<p>No signing key is configured. Set one in QtPass Settings "
1712
           "&gt; GPG keys, or run this in a terminal:</p>"
1713
           "<pre>gpg --armor --export --output my_key.asc &lt;your-key-id"
1714
           "&gt;</pre>"
1715
           "<p>Then send the file to your teammates.</p>"));
1716
    return;
×
1717
  }
1718
  QString gpgExe = QtPassSettings::getGpgExecutable();
×
1719
  if (gpgExe.isEmpty()) {
×
1720
    gpgExe = QStringLiteral("gpg");
×
1721
  }
1722
  QStringList args = {"--armor", "--export"};
×
1723
  args.append(identity.split(' ', Qt::SkipEmptyParts));
×
1724
  QString stdOut;
×
1725
  QString stdErr;
×
1726
  int exitCode = Executor::executeBlocking(gpgExe, args, &stdOut, &stdErr);
×
1727
  if (exitCode != 0 || stdOut.isEmpty()) {
×
1728
    QMessageBox::warning(this, tr("Export Public Key"),
×
1729
                         tr("Could not export public key for %1.\n\n%2")
×
1730
                             .arg(identity, stdErr.isEmpty()
×
1731
                                                ? tr("No output from gpg.")
×
1732
                                                : stdErr));
1733
    return;
1734
  }
1735
  ExportPublicKeyDialog dialog(identity, stdOut, this);
×
1736
  dialog.exec();
×
1737
}
×
1738

1739
/**
1740
 * @brief MainWindow::addRecipient open the recipient management dialog for
1741
 *        the supplied directory.
1742
 * @param dir Folder whose .gpg-id should be edited.
1743
 *
1744
 * Delegates to UsersDialog so users can tick/untick keys from their
1745
 * keyring as recipients of the folder; importing a foreign key into the
1746
 * keyring still has to happen via gpg (or QtPass settings) first.
1747
 */
1748
void MainWindow::addRecipient(const QString &dir) {
×
1749
  UsersDialog d(dir, this);
×
1750
  d.exec();
×
1751
}
×
1752

1753
/**
1754
 * @brief MainWindow::showShareHelp show help about GPG sharing
1755
 */
1756
void MainWindow::showShareHelp() {
×
1757
  QMessageBox::information(
×
1758
      this, tr("Sharing Passwords with GPG"),
×
1759
      tr("<h3>Sharing Passwords with GPG</h3>"
×
1760
         "<p>To share passwords with other users:</p>"
1761
         "<ol>"
1762
         "<li><b>Export your public key</b> and send it to teammates</li>"
1763
         "<li><b>Import teammates' public keys</b> into your GPG keyring</li>"
1764
         "<li><b>Re-encrypt passwords</b> so all recipients can decrypt "
1765
         "them</li>"
1766
         "</ol>"
1767
         "<p>Only people who have a matching secret key can decrypt the "
1768
         "passwords.</p>"
1769
         "<p><b>Tip:</b> Use the same GPG key for all shared folders.</p>"
1770
         "<p>See the FAQ for more details.</p>"));
1771
}
×
1772

1773
void MainWindow::updateGitButtonVisibility() {
15✔
1774
  if (!QtPassSettings::isUseGit() ||
30✔
1775
      (QtPassSettings::getGitExecutable().isEmpty() &&
15✔
1776
       QtPassSettings::getPassExecutable().isEmpty())) {
15✔
1777
    enableGitButtons(false);
15✔
1778
  } else {
1779
    enableGitButtons(true);
×
1780
  }
1781
}
15✔
1782

1783
void MainWindow::updateOtpButtonVisibility() {
15✔
1784
#if defined(Q_OS_WIN) || defined(__APPLE__)
1785
  ui->actionOtp->setVisible(false);
1786
#endif
1787
  if (!QtPassSettings::isUseOtp()) {
15✔
1788
    ui->actionOtp->setEnabled(false);
15✔
1789
  } else {
1790
    ui->actionOtp->setEnabled(true);
×
1791
  }
1792
}
15✔
1793

1794
void MainWindow::updateGrepButtonVisibility() {
12✔
1795
  const bool enabled = QtPassSettings::isUseGrepSearch();
12✔
1796
  ui->grepButton->setVisible(enabled);
12✔
1797
  ui->grepCaseButton->setVisible(enabled);
12✔
1798
  if (!enabled && m_grep.inGrepMode()) {
12✔
1799
    ui->grepButton->setChecked(false);
×
1800
  }
1801
}
12✔
1802

1803
void MainWindow::enableGitButtons(const bool &state) {
15✔
1804
  // Following GNOME guidelines is preferable disable buttons instead of hide
1805
  ui->actionPush->setEnabled(state);
15✔
1806
  ui->actionUpdate->setEnabled(state);
15✔
1807
}
15✔
1808

1809
/**
1810
 * @brief MainWindow::critical critical message popup wrapper.
1811
 * @param title
1812
 * @param msg
1813
 */
1814
void MainWindow::critical(const QString &title, const QString &msg) {
×
1815
  QMessageBox::critical(this, title, msg);
×
1816
}
×
1817

1818
/**
1819
 * @brief Appends processed command output to the output panel.
1820
 *
1821
 * Appends text to the process output text edit, with per-line numbering,
1822
 * optional command prefix, and color coding for errors vs. success.
1823
 * Handles auto-scrolling and line limits.
1824
 *
1825
 * @param output The raw output text from the command.
1826
 * @param isError true if this is error output (stderr).
1827
 * @param linePrefix Optional command name to prefix each line with.
1828
 */
1829
void MainWindow::appendProcessOutput(const QString &output, bool isError,
2✔
1830
                                     const QString &linePrefix) {
1831
  if (!QtPassSettings::isShowProcessOutput()) {
2✔
1832
    return;
1✔
1833
  }
1834

1835
  QStringList lines = output.split('\n', Qt::SkipEmptyParts);
1✔
1836
  for (QString &line : lines) {
2✔
1837
    // Right-trim only: remove trailing CR and whitespace, preserve leading
1838
    // indentation
1839
    line.remove('\r');
1✔
1840
    while (!line.isEmpty() && line.back().isSpace()) {
2✔
1841
      line.chop(1);
×
1842
    }
1843
    if (line.isEmpty()) {
1✔
1844
      continue;
×
1845
    }
1846

1847
    m_outputCounter++;
1✔
1848
    QString lineNumber = QString::number(m_outputCounter);
1✔
1849

1850
    QColor textColor =
1851
        isError ? QColor(Qt::red)
1✔
1852
                : m_processOutputEdit->palette().color(QPalette::Text);
2✔
1853
    QString colorHex = textColor.name();
1✔
1854
    // Apply the optional prefix per line so multi-line output stays
1855
    // attributed to its command (e.g. all 3 lines of a `git push` show
1856
    // "git push: ..." rather than only the first).
1857
    QString prefixed =
1858
        linePrefix.isEmpty() ? line : linePrefix + QStringLiteral(": ") + line;
2✔
1859
    QString coloredOutput =
1860
        QString("<span style=\"color: %1;\">%2: %3</span>")
1✔
1861
            .arg(colorHex, lineNumber, prefixed.toHtmlEscaped());
2✔
1862

1863
    m_processOutputEdit->append(coloredOutput);
1✔
1864
  }
1865

1866
  limitOutputLines();
1✔
1867

1868
  if (m_autoScroll) {
1✔
1869
    m_processOutputEdit->verticalScrollBar()->setValue(
2✔
1870
        m_processOutputEdit->verticalScrollBar()->maximum());
1✔
1871
  }
1872
}
1873

1874
/**
1875
 * @brief Handles process output from the Pass executor.
1876
 *
1877
 * Called when any non-sensitive process completes. Filters out password-
1878
 * related commands (pass show, insert, etc.) and delegates to
1879
 * appendProcessOutput.
1880
 *
1881
 * @param output The stdout/stderr text from the process.
1882
 * @param isError true if this is error output (stderr).
1883
 * @param pid The process ID identifying which command ran.
1884
 */
1885
void MainWindow::onProcessOutput(const QString &output, bool isError,
2✔
1886
                                 Enums::PROCESS pid) {
1887
  appendProcessOutput(output, isError, getProcessName(pid));
2✔
1888
}
2✔
1889

1890
/**
1891
 * @brief Maps a process ID to its human-readable command name.
1892
 *
1893
 * Returns static strings for git/pass commands that appear in output.
1894
 * Password-related commands return empty (they are filtered).
1895
 *
1896
 * @param pid The process ID to look up.
1897
 * @return QString with command name, or empty if filtered.
1898
 */
1899
auto MainWindow::getProcessName(Enums::PROCESS pid) -> QString {
2✔
1900
  switch (pid) {
2✔
1901
  case Enums::GIT_INIT:
×
1902
    return QStringLiteral("git init"); // no-tr
×
1903
  case Enums::GIT_ADD:
×
1904
    return QStringLiteral("git add"); // no-tr
×
1905
  case Enums::GIT_COMMIT:
×
1906
    return QStringLiteral("git commit"); // no-tr
×
1907
  case Enums::GIT_RM:
×
1908
    return QStringLiteral("git rm"); // no-tr
×
1909
  case Enums::GIT_PULL:
×
1910
    return QStringLiteral("git pull"); // no-tr
×
1911
  case Enums::GIT_PUSH:
×
1912
    return QStringLiteral("git push"); // no-tr
×
1913
  case Enums::GIT_MOVE:
×
1914
    return QStringLiteral("git mv"); // no-tr
×
1915
  case Enums::GIT_COPY:
×
1916
    // ImitatePass::Copy literally invokes `git cp` (a git-extras
1917
    // subcommand), so the label matches what's run. Stock-git users
1918
    // without git-extras will see the underlying "'cp' is not a git
1919
    // command" failure surfaced in the process output panel.
1920
    return QStringLiteral("git cp"); // no-tr
×
1921
  case Enums::PASS_INSERT:
×
1922
    return QStringLiteral("pass insert"); // no-tr
×
1923
  case Enums::PASS_REMOVE:
×
1924
    return QStringLiteral("pass rm"); // no-tr
×
1925
  case Enums::PASS_INIT:
×
1926
    return QStringLiteral("pass init"); // no-tr
×
1927
  case Enums::PASS_MOVE:
×
1928
    return QStringLiteral("pass mv"); // no-tr
×
1929
  case Enums::PASS_COPY:
×
1930
    return QStringLiteral("pass cp"); // no-tr
×
1931
  case Enums::PASS_GREP:
×
1932
    return QStringLiteral("pass grep"); // no-tr
×
1933
  case Enums::GPG_GENKEYS:
×
1934
    return QStringLiteral("gpg --gen-key"); // no-tr
×
1935
  case Enums::PASS_SHOW:
1936
  case Enums::PASS_OTP_GENERATE:
1937
  case Enums::PROCESS_COUNT:
1938
  case Enums::INVALID:
1939
    break;
1940
  }
1941
  return {};
1942
}
1943

1944
/**
1945
 * @brief Checks if a process ID represents a sensitive operation whose
1946
 * output should not be shown in the process output panel.
1947
 *
1948
 * Password-related commands (pass show, OTP generate, grep, insert)
1949
 * display their output in other UI areas, so we skip them here.
1950
 *
1951
 * @param pid The process ID to check.
1952
 * @return true if the process is sensitive and should be filtered.
1953
 */
1954
auto MainWindow::isSensitiveProcess(Enums::PROCESS pid) -> bool {
×
1955
  switch (pid) {
×
1956
  case Enums::PASS_SHOW:
1957
  case Enums::PASS_OTP_GENERATE:
1958
  case Enums::PASS_GREP:
1959
  case Enums::PASS_INSERT:
1960
    return true;
1961
  case Enums::GIT_INIT:
1962
  case Enums::GIT_ADD:
1963
  case Enums::GIT_COMMIT:
1964
  case Enums::GIT_RM:
1965
  case Enums::GIT_PULL:
1966
  case Enums::GIT_PUSH:
1967
  case Enums::GIT_MOVE:
1968
  case Enums::GIT_COPY:
1969
  case Enums::PASS_REMOVE:
1970
  case Enums::PASS_INIT:
1971
  case Enums::PASS_MOVE:
1972
  case Enums::PASS_COPY:
1973
  case Enums::GPG_GENKEYS:
1974
  case Enums::PROCESS_COUNT:
1975
  case Enums::INVALID:
1976
    break;
1977
  }
1978
  return false;
×
1979
}
1980

1981
/**
1982
 * @brief Updates the visibility of the process output panel.
1983
 *
1984
 * Shows or hides the process output widget based on the user's
1985
 * showProcessOutput setting.
1986
 */
1987
void MainWindow::updateProcessOutputVisibility() {
×
1988
  m_processOutputDock->setVisible(QtPassSettings::isShowProcessOutput());
×
1989
}
×
1990

1991
/**
1992
 * @brief Limits the output panel to max lines, trimming old excess.
1993
 *
1994
 * Removes the oldest lines when the document exceeds MaxOutputLines (1000).
1995
 * Called after each append to prevent unbounded growth.
1996
 */
1997
void MainWindow::limitOutputLines() {
1✔
1998
  QTextDocument *doc = m_processOutputEdit->document();
1✔
1999
  int excess = doc->blockCount() - MaxOutputLines;
1✔
2000
  if (excess <= 0) {
1✔
2001
    return;
1✔
2002
  }
2003

2004
  QTextCursor cursor(doc);
×
2005
  cursor.movePosition(QTextCursor::Start);
×
2006
  cursor.movePosition(QTextCursor::NextBlock, QTextCursor::KeepAnchor, excess);
×
2007
  cursor.removeSelectedText();
×
2008
}
×
2009

2010
/**
2011
 * @brief Clears the process output panel.
2012
 *
2013
 * Clears all output, resets the line counter, and re-enables auto-scroll.
2014
 */
2015
void MainWindow::on_clearOutputButton_clicked() {
×
2016
  m_processOutputEdit->clear();
×
2017
  m_outputCounter = 0;
×
2018
  m_autoScroll = true;
×
2019
}
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc