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

IJHack / QtPass / 27704199392

17 Jun 2026 04:31PM UTC coverage: 57.077% (-0.002%) from 57.079%
27704199392

Pull #1560

github

web-flow
Merge 07790f968 into 0b6d117e7
Pull Request #1560: refactor(#1511): snapshot AppSettings in MainWindow multi-field read sites

11 of 59 new or added lines in 1 file covered. (18.64%)

10 existing lines in 1 file now uncovered.

3964 of 6945 relevant lines covered (57.08%)

23.69 hits per line

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

27.74
/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
  proxyModel.setPass(QtPassSettings::getPass());
12✔
91
  selectionModel.reset(new QItemSelectionModel(&proxyModel));
12✔
92

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

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

126
  updateProfileBox();
12✔
127

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

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

139
  searchTimer.setInterval(350);
12✔
140
  searchTimer.setSingleShot(true);
12✔
141

142
  connect(&searchTimer, &QTimer::timeout, this, &MainWindow::onTimeoutSearch);
12✔
143

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

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

157
  initToolBarButtons();
12✔
158
  initStatusBar();
12✔
159
  initProcessOutputPanel();
12✔
160

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

182
  ui->lineEdit->setClearButtonEnabled(true);
12✔
183
  updateGrepButtonVisibility();
12✔
184

185
  setUiElementsEnabled(true);
12✔
186

187
  ui->lineEdit->setText(searchText);
12✔
188

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

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

204
MainWindow::~MainWindow() { delete m_qtPass; }
36✔
205

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

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

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

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

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

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

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

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

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

375
  connect(m_clearOutputButton, &QToolButton::clicked, this,
12✔
376
          &MainWindow::on_clearOutputButton_clicked);
12✔
377

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

397
auto MainWindow::getCurrentTreeViewIndex() -> QModelIndex {
×
398
  return ui->treeView->currentIndex();
×
399
}
400

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

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

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

439
/**
440
 * @brief MainWindow::config pops up the configuration screen and handles all
441
 * inter-window communication
442
 */
443
void MainWindow::applyTextBrowserSettings() {
×
NEW
444
  const AppSettings s = QtPassSettings::load();
×
NEW
445
  if (s.useMonospace) {
×
446
    QFont monospace("Monospace");
×
447
    monospace.setStyleHint(QFont::Monospace);
×
448
    ui->textBrowser->setFont(monospace);
×
449
  } else {
×
450
    ui->textBrowser->setFont(QFont());
×
451
  }
452

NEW
453
  if (s.noLineWrapping) {
×
454
    ui->textBrowser->setLineWrapMode(QTextBrowser::NoWrap);
×
455
  } else {
456
    ui->textBrowser->setLineWrapMode(QTextBrowser::WidgetWidth);
×
457
  }
458
}
×
459

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

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

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

495
      updateProfileBox();
×
NEW
496
      const AppSettings s = QtPassSettings::load();
×
NEW
497
      proxyModel.setStore(s.passStore);
×
NEW
498
      ui->treeView->setRootIndex(proxyModel.rootIndexFor(s.passStore));
×
499
      deselect();
×
500
      ui->treeView->setCurrentIndex(QModelIndex());
×
501

NEW
502
      if (m_qtPass->isFreshStart() && !Util::configIsValid(s)) {
×
503
        config();
×
504
      }
505
      Pass *activePass = QtPassSettings::getPass();
×
506
      activePass->updateEnv();
×
507
      proxyModel.setPass(activePass);
×
NEW
508
      clearPanelTimer.setInterval(MS_PER_SECOND * s.autoclearPanelSeconds);
×
509
      m_qtPass->setClipboardTimer();
×
510

511
      updateGitButtonVisibility();
×
512
      updateOtpButtonVisibility();
×
513
      updateGrepButtonVisibility();
×
514
      updateProcessOutputVisibility();
×
NEW
515
      if (s.useTrayIcon && m_tray == nullptr) {
×
516
        initTrayIcon();
×
NEW
517
      } else if (!s.useTrayIcon && m_tray != nullptr) {
×
518
        destroyTrayIcon();
×
519
      }
UNCOV
520
    }
×
521

522
    m_qtPass->setFreshStart(false);
×
523
  }
524
}
×
525

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

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

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

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

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

598
  if (fileOrFolder.isFile()) {
×
599
    editPassword(getFile(index, true));
×
600
  }
601
}
×
602

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

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

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

645
  // set clipped text
646
  m_qtPass->setClippedText(password, p_output);
×
647

648
  // first clear the current view:
649
  m_displayPanel->clear();
×
650

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

659
  if (s.useAutoclearPanel) {
×
660
    clearPanelTimer.start();
×
661
  }
662

663
  emit passShowHandlerFinished(output);
×
664
  setUiElementsEnabled(true);
×
665
}
×
666

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

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

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

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

770
  if (s.alwaysOnTop) {
12✔
771
    Qt::WindowFlags flags = windowFlags();
772
    setWindowFlags(flags | Qt::WindowStaysOnTopHint);
×
773
    show();
×
774
  }
775

776
  if (s.useTrayIcon && m_tray == nullptr) {
12✔
777
    initTrayIcon();
×
NEW
778
    if (s.startMinimized) {
×
779
      // since we are still in constructor, can't directly hide
780
      QTimer::singleShot(10, this, SLOT(hide()));
×
781
    }
782
  } else if (!s.useTrayIcon && m_tray != nullptr) {
12✔
783
    destroyTrayIcon();
×
784
  }
785
}
24✔
786

787
/**
788
 * @brief MainWindow::on_configButton_clicked run Mainwindow::config
789
 */
790
void MainWindow::onConfig() { config(); }
×
791

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

809
/**
810
 * @brief MainWindow::onTimeoutSearch Fired when search is finished or too much
811
 * time from two keypresses is elapsed
812
 */
813
void MainWindow::onTimeoutSearch() {
×
814
  QString query = ui->lineEdit->text();
×
815

816
  if (query.isEmpty()) {
×
817
    ui->treeView->collapseAll();
×
818
    deselect();
×
819
  }
820

821
  query.replace(QStringLiteral(" "), ".*");
×
822
  QRegularExpression regExp(query, QRegularExpression::CaseInsensitiveOption);
×
823
  proxyModel.setFilterRegularExpression(regExp);
×
824
  ui->treeView->setRootIndex(
×
825
      proxyModel.rootIndexFor(QtPassSettings::getPassStore()));
×
826

827
  if (proxyModel.rowCount() > 0 && !query.isEmpty()) {
×
828
    selectFirstFile();
×
829
  } else {
830
    ui->actionEdit->setEnabled(false);
×
831
    ui->actionDelete->setEnabled(false);
×
832
  }
833
}
×
834

835
/**
836
 * @brief MainWindow::on_lineEdit_returnPressed get searching
837
 *
838
 * Select the first possible file in the tree
839
 */
840
void MainWindow::on_lineEdit_returnPressed() {
×
841
#ifdef QT_DEBUG
842
  dbg() << "on_lineEdit_returnPressed" << proxyModel.rowCount();
843
#endif
844

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

865
  if (proxyModel.rowCount() > 0) {
×
866
    selectFirstFile();
×
867
    on_treeView_clicked(ui->treeView->currentIndex());
×
868
  }
869
}
870

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

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

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

988
/**
989
 * @brief MainWindow::selectFirstFile select the first possible file in the
990
 * tree
991
 */
992
void MainWindow::selectFirstFile() {
×
993
  QModelIndex index = proxyModel.rootIndexFor(QtPassSettings::getPassStore());
×
994
  index = firstFile(index);
×
995
  ui->treeView->setCurrentIndex(index);
×
996
}
×
997

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

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

1040
/**
1041
 * @brief MainWindow::setPassword open passworddialog
1042
 * @param file which pgp file
1043
 * @param isNew insert (not update)
1044
 */
1045
void MainWindow::setPassword(const QString &file, bool isNew) {
×
NEW
1046
  const AppSettings s = QtPassSettings::load();
×
NEW
1047
  PasswordDialog d(QtPassSettings::getPass(), s, file, isNew, this);
×
1048

1049
  if (isNew) {
×
1050
    const QString storePath = s.passStore;
1051
    QString folder = Util::getDir(ui->treeView->currentIndex(), false, model,
×
NEW
1052
                                  proxyModel, s.passStore);
×
1053
    if (folder.isEmpty()) {
×
1054
      folder = storePath;
×
1055
    }
1056
    QHash<QString, QStringList> templates =
1057
        TemplateIO::readTemplates(storePath);
×
1058
    if (!templates.isEmpty()) {
1059
      QString defaultTemplate =
1060
          TemplateIO::getFolderTemplate(folder, storePath);
×
1061
      d.setAvailableTemplates(templates, defaultTemplate);
×
1062
      new QShortcut(QKeySequence(Qt::CTRL | Qt::Key_T), &d,
×
1063
                    [&d]() { d.cycleTemplate(); });
×
1064
    }
1065
  }
×
1066

1067
  if (!d.exec()) {
×
1068
    ui->treeView->setFocus();
×
1069
  }
1070
}
×
1071

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

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

1110
  QFileInfo fileOrFolder =
1111
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
1112
  QString file = "";
×
1113
  bool isDir = false;
1114

1115
  if (fileOrFolder.isFile()) {
×
1116
    file = getFile(ui->treeView->currentIndex(), true);
×
1117
  } else {
1118
    file = Util::getDir(ui->treeView->currentIndex(), true, model, proxyModel,
×
1119
                        QtPassSettings::getPassStore());
×
1120
    isDir = true;
1121
  }
1122

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

1141
  if (QMessageBox::question(
×
1142
          this, isDir ? tr("Delete folder?") : tr("Delete password?"),
×
1143
          tr("Are you sure you want to delete %1%2?")
×
1144
              .arg(QDir::separator() + file, isDir ? dirMessage : "?"),
×
1145
          QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) {
1146
    return;
1147
  }
1148

1149
  QtPassSettings::getPass()->Remove(file, isDir);
×
1150
}
×
1151

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

1167
/**
1168
 * @brief MainWindow::onEdit try and edit (selected) password.
1169
 */
1170
void MainWindow::onEdit() {
×
1171
  QString file = getFile(ui->treeView->currentIndex(), true);
×
1172
  editPassword(file);
×
1173
}
×
1174

1175
/**
1176
 * @brief MainWindow::userDialog see MainWindow::onUsers()
1177
 * @param dir folder to edit users for.
1178
 */
1179
void MainWindow::userDialog(const QString &dir) {
×
1180
  if (!dir.isEmpty()) {
×
1181
    m_currentDir = dir;
×
1182
  }
1183
  onUsers();
×
1184
}
×
1185

1186
/**
1187
 * @brief MainWindow::onUsers edit users for the current
1188
 * folder,
1189
 * gets lists and opens UserDialog.
1190
 */
1191
void MainWindow::onUsers() {
×
1192
  QString dir = m_currentDir.isEmpty()
1193
                    ? Util::getDir(ui->treeView->currentIndex(), false, model,
×
1194
                                   proxyModel, QtPassSettings::getPassStore())
×
1195
                    : m_currentDir;
×
1196

1197
  UsersDialog d(QtPassSettings::getPass(), QtPassSettings::load(), dir, this);
×
1198
  if (!d.exec()) {
×
1199
    ui->treeView->setFocus();
×
1200
  }
1201
}
×
1202

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

1219
/**
1220
 * @brief MainWindow::generateKeyPair internal gpg keypair generator . .
1221
 * @param batch
1222
 * @param keygenWindow
1223
 */
1224
void MainWindow::generateKeyPair(const QString &batch, QDialog *keygenWindow) {
×
1225
  m_keyGenDialog = keygenWindow;
×
1226
  emit generateGPGKeyPair(batch);
×
1227
}
×
1228

1229
/**
1230
 * @brief MainWindow::updateProfileBox update the list of profiles, optionally
1231
 * select a more appropriate one to view too
1232
 */
1233
void MainWindow::updateProfileBox() {
12✔
1234
  QHash<QString, QHash<QString, QString>> profiles =
1235
      QtPassSettings::getProfiles();
12✔
1236

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

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

1283
  ui->lineEdit->clear();
×
1284

1285
  QtPassSettings::setProfile(name);
×
1286

1287
  QtPassSettings::setPassStore(
×
1288
      QtPassSettings::getProfiles().value(name).value("path"));
×
1289
  QtPassSettings::setPassSigningKey(
×
1290
      QtPassSettings::getProfiles().value(name).value("signingKey"));
×
1291
  ui->statusBar->showMessage(tr("Profile changed to %1").arg(name), 2000);
×
1292

1293
  QtPassSettings::getPass()->updateEnv();
×
1294

1295
  const QString passStore = QtPassSettings::getPassStore();
×
1296
  proxyModel.setStore(passStore);
×
1297
  ui->treeView->setRootIndex(proxyModel.rootIndexFor(passStore));
×
1298
  deselect();
×
1299
  ui->treeView->setCurrentIndex(QModelIndex());
×
1300
}
1301

1302
/**
1303
 * @brief MainWindow::initTrayIcon show a nice tray icon on systems that
1304
 * support
1305
 * it
1306
 */
1307
void MainWindow::initTrayIcon() {
×
1308
  m_tray = new TrayIcon(this);
×
1309
  // Setup tray icon
1310

1311
  if (m_tray == nullptr) {
1312
#ifdef QT_DEBUG
1313
    dbg() << "Allocating tray icon failed.";
1314
#endif
1315
    return;
1316
  }
1317

1318
  if (!m_tray->getIsAllocated()) {
×
1319
    destroyTrayIcon();
×
1320
  }
1321
}
1322

1323
/**
1324
 * @brief MainWindow::destroyTrayIcon remove that pesky tray icon
1325
 */
1326
void MainWindow::destroyTrayIcon() {
×
1327
  delete m_tray;
×
1328
  m_tray = nullptr;
×
1329
}
×
1330

1331
/**
1332
 * @brief MainWindow::closeEvent hide or quit
1333
 * @param event
1334
 */
1335
void MainWindow::closeEvent(QCloseEvent *event) {
×
1336
  if (QtPassSettings::isHideOnClose()) {
×
1337
    this->hide();
×
1338
    event->ignore();
1339
  } else {
1340
    m_qtPass->clearClipboard();
×
1341

1342
    QtPassSettings::setGeometry(saveGeometry());
×
1343
    QtPassSettings::setSavestate(saveState());
×
1344
    QtPassSettings::setMaximized(isMaximized());
×
1345
    if (!isMaximized()) {
×
1346
      QtPassSettings::setPos(pos());
×
1347
      QtPassSettings::setSize(size());
×
1348
    }
1349
    event->accept();
1350
  }
1351
}
×
1352

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

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

1393
/**
1394
 * @brief MainWindow::showContextMenu show us the (file or folder) context
1395
 * menu
1396
 * @param pos
1397
 */
1398
void MainWindow::showContextMenu(const QPoint &pos) {
×
NEW
1399
  const AppSettings s = QtPassSettings::load();
×
UNCOV
1400
  QModelIndex index = ui->treeView->indexAt(pos);
×
1401
  bool selected = true;
1402
  if (!index.isValid()) {
1403
    ui->treeView->clearSelection();
×
1404
    ui->actionDelete->setEnabled(false);
×
1405
    ui->actionEdit->setEnabled(false);
×
1406
    m_currentDir = "";
×
1407
    selected = false;
1408
  }
1409

1410
  ui->treeView->setCurrentIndex(index);
×
1411

1412
  QPoint globalPos = ui->treeView->viewport()->mapToGlobal(pos);
×
1413

1414
  QFileInfo fileOrFolder =
1415
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
1416

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

1449
      auto *shareMenu = new QMenu(tr("Share"), &contextMenu);
×
1450
      contextMenu.addMenu(shareMenu);
×
1451

NEW
1452
      QString gpgIdPath = Pass::getGpgIdPath(dirPath, s.passStore);
×
1453
      bool gpgIdExists = !gpgIdPath.isEmpty() && QFile(gpgIdPath).exists();
×
1454

NEW
1455
      const QString exePath = s.usePass ? s.passExecutable : s.gpgExecutable;
×
1456
      bool gpgAvailable = !exePath.isEmpty() && (exePath.startsWith("wsl ") ||
×
1457
                                                 QFile(exePath).exists());
×
1458

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

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

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

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

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

1491
  contextMenu->exec(globalPos);
×
1492
  delete contextMenu;
×
1493
}
×
1494

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

1502
  QString path = QDir::toNativeSeparators(dir);
×
1503
  QDesktopServices::openUrl(QUrl::fromLocalFile(path));
×
1504
}
×
1505

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

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

1578
/**
1579
 * @brief MainWindow::editPassword read password and open edit window via
1580
 * MainWindow::onEdit()
1581
 */
1582
void MainWindow::editPassword(const QString &file) {
×
1583
  if (!file.isEmpty()) {
×
NEW
1584
    const AppSettings s = QtPassSettings::load();
×
NEW
1585
    if (s.useGit && s.autoPull) {
×
UNCOV
1586
      onUpdate(true);
×
1587
    }
1588
    setPassword(file, false);
×
UNCOV
1589
  }
×
1590
}
×
1591

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

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

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

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

1640
void MainWindow::passwordFromFileToClipboard(const QString &text) {
×
1641
  QStringList tokens = text.split('\n');
×
1642
  m_qtPass->copyTextToClipboard(tokens[0]);
×
1643
}
×
1644

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

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

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

1677
  if (ret != QMessageBox::Yes)
×
1678
    return;
1679

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

1685
  QtPassSettings::getImitatePass()->reencryptPath(
×
1686
      QDir::cleanPath(QDir(dir).absolutePath()));
×
1687
}
×
1688

1689
/**
1690
 * @brief MainWindow::startReencryptPath disable ui elements and treeview
1691
 */
1692
void MainWindow::startReencryptPath() {
×
1693
  setUiElementsEnabled(false);
×
1694
  ui->treeView->setDisabled(true);
×
1695
}
×
1696

1697
/**
1698
 * @brief MainWindow::endReencryptPath re-enable ui elements
1699
 */
1700
void MainWindow::endReencryptPath() { setUiElementsEnabled(true); }
×
1701

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

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

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

1778
void MainWindow::updateGitButtonVisibility() {
15✔
1779
  const AppSettings s = QtPassSettings::load();
15✔
1780
  if (!s.useGit || (s.gitExecutable.isEmpty() && s.passExecutable.isEmpty())) {
15✔
1781
    enableGitButtons(false);
15✔
1782
  } else {
1783
    enableGitButtons(true);
×
1784
  }
1785
}
15✔
1786

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

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

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

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

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

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

1851
    m_outputCounter++;
1✔
1852
    QString lineNumber = QString::number(m_outputCounter);
1✔
1853

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

1867
    m_processOutputEdit->append(coloredOutput);
1✔
1868
  }
1869

1870
  limitOutputLines();
1✔
1871

1872
  if (m_autoScroll) {
1✔
1873
    m_processOutputEdit->verticalScrollBar()->setValue(
2✔
1874
        m_processOutputEdit->verticalScrollBar()->maximum());
1✔
1875
  }
1876
}
1877

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

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

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

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

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

2008
  QTextCursor cursor(doc);
×
2009
  cursor.movePosition(QTextCursor::Start);
×
2010
  cursor.movePosition(QTextCursor::NextBlock, QTextCursor::KeepAnchor, excess);
×
2011
  cursor.removeSelectedText();
×
2012
}
×
2013

2014
/**
2015
 * @brief Clears the process output panel.
2016
 *
2017
 * Clears all output, resets the line counter, and re-enables auto-scroll.
2018
 */
2019
void MainWindow::on_clearOutputButton_clicked() {
×
2020
  m_processOutputEdit->clear();
×
2021
  m_outputCounter = 0;
×
2022
  m_autoScroll = true;
×
2023
}
×
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