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

IJHack / QtPass / 27629875352

16 Jun 2026 03:46PM UTC coverage: 57.471% (-0.06%) from 57.526%
27629875352

Pull #1550

github

web-flow
Merge d5a106b1a into 156c096e8
Pull Request #1550: refactor(executor): replace QStringList env with QProcessEnvironment (#1510)

18 of 21 new or added lines in 5 files covered. (85.71%)

74 existing lines in 2 files now uncovered.

3977 of 6920 relevant lines covered (57.47%)

31.87 hits per line

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

27.97
/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

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

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

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

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

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

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

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

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

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

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

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

621
/**
622
 * @brief Handles displaying parsed password entry content in the main window.
623
 * @example
624
 * void result = MainWindow::passShowHandler(p_output);
625
 * // Updates the UI with parsed fields and emits
626
 * passShowHandlerFinished(output)
627
 *
628
 * @param p_output - The raw output text containing the password entry data.
629
 * @return void - This function does not return a value.
630
 */
631
void MainWindow::passShowHandler(const QString &p_output) {
×
632
  QStringList templ = QtPassSettings::isUseTemplate()
×
633
                          ? QtPassSettings::getPassTemplate().split("\n")
×
634
                          : QStringList();
×
635
  bool allFields =
636
      QtPassSettings::isUseTemplate() && QtPassSettings::isTemplateAllFields();
×
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 (QtPassSettings::isHideContent()) {
×
649
    output = "***" + tr("Content hidden") + "***";
×
650
  } else if (!QtPassSettings::isDisplayAsIs()) {
×
651
    m_displayPanel->displayFields(password, fileContent.getNamedValues());
×
652
    output = fileContent.getRemainingDataForDisplay();
×
653
  }
654

655
  if (QtPassSettings::isUseAutoclearPanel()) {
×
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
    m_qtPass->copyTextToClipboard(p_output);
×
677
    showStatusMessage(tr("OTP code copied to clipboard"));
×
678
  } else {
679
    flashText(tr("No OTP code found in this password entry"), true);
×
680
  }
681
  if (QtPassSettings::isUseAutoclearPanel()) {
×
682
    clearPanelTimer.start();
×
683
  }
684
  setUiElementsEnabled(true);
×
685
}
×
686

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1140
  QtPassSettings::getPass()->Remove(file, isDir);
×
1141
}
×
1142

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

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

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

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

1188
  UsersDialog d(dir, this);
×
1189
  if (!d.exec()) {
×
1190
    ui->treeView->setFocus();
×
1191
  }
1192
}
×
1193

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

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

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

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

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

1274
  ui->lineEdit->clear();
×
1275

1276
  QtPassSettings::setProfile(name);
×
1277

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

1284
  QtPassSettings::getPass()->updateEnv();
×
1285

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

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

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

1309
  if (!m_tray->getIsAllocated()) {
×
1310
    destroyTrayIcon();
×
1311
  }
1312
}
1313

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

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

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

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

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

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

1400
  ui->treeView->setCurrentIndex(index);
×
1401

1402
  QPoint globalPos = ui->treeView->viewport()->mapToGlobal(pos);
×
1403

1404
  QFileInfo fileOrFolder =
1405
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
1406

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

1439
      auto *shareMenu = new QMenu(tr("Share"), &contextMenu);
×
1440
      contextMenu.addMenu(shareMenu);
×
1441

1442
      QString gpgIdPath = Pass::getGpgIdPath(dirPath);
×
1443
      bool gpgIdExists = !gpgIdPath.isEmpty() && QFile(gpgIdPath).exists();
×
1444

1445
      QString exePath = QtPassSettings::isUsePass()
×
1446
                            ? QtPassSettings::getPassExecutable()
×
1447
                            : QtPassSettings::getGpgExecutable();
×
1448
      bool gpgAvailable = !exePath.isEmpty() && (exePath.startsWith("wsl ") ||
×
1449
                                                 QFile(exePath).exists());
×
1450

1451
      QAction *reencrypt = shareMenu->addAction(tr("Re-encrypt all passwords"));
×
1452
      reencrypt->setEnabled(gpgIdExists && gpgAvailable);
×
1453
      connect(reencrypt, &QAction::triggered, this,
×
1454
              [this, dirPath]() { reencryptPath(dirPath); });
×
1455

1456
      QAction *exportKey = shareMenu->addAction(tr("Export my public key..."));
×
1457
      exportKey->setEnabled(gpgAvailable);
×
1458
      connect(exportKey, &QAction::triggered, this,
×
1459
              &MainWindow::exportPublicKey);
×
1460

1461
      QAction *addRecipientAction =
1462
          shareMenu->addAction(tr("Add recipient..."));
×
1463
      addRecipientAction->setEnabled(gpgIdExists && gpgAvailable);
×
1464
      connect(addRecipientAction, &QAction::triggered, this,
×
1465
              [this, dirPath]() { addRecipient(dirPath); });
×
1466

1467
      QAction *shareHelp = shareMenu->addAction(tr("What is this?"));
×
1468
      connect(shareHelp, &QAction::triggered, this, &MainWindow::showShareHelp);
×
1469
    }
1470
  }
1471
  contextMenu.exec(globalPos);
×
1472
}
×
1473

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

1483
  contextMenu->exec(globalPos);
×
1484
  delete contextMenu;
×
1485
}
×
1486

1487
/**
1488
 * @brief MainWindow::openFolder open the folder in the default file manager
1489
 */
1490
void MainWindow::openFolder() {
×
1491
  QString dir =
1492
      Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel);
×
1493

1494
  QString path = QDir::toNativeSeparators(dir);
×
1495
  QDesktopServices::openUrl(QUrl::fromLocalFile(path));
×
1496
}
×
1497

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

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

1569
/**
1570
 * @brief MainWindow::editPassword read password and open edit window via
1571
 * MainWindow::onEdit()
1572
 */
1573
void MainWindow::editPassword(const QString &file) {
×
1574
  if (!file.isEmpty()) {
×
1575
    if (QtPassSettings::isUseGit() && QtPassSettings::isAutoPull()) {
×
1576
      onUpdate(true);
×
1577
    }
1578
    setPassword(file, false);
×
1579
  }
1580
}
×
1581

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

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

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

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

1630
void MainWindow::passwordFromFileToClipboard(const QString &text) {
×
1631
  QStringList tokens = text.split('\n');
×
1632
  m_qtPass->copyTextToClipboard(tokens[0]);
×
1633
}
×
1634

1635
/**
1636
 * @brief Displays message in status bar
1637
 *
1638
 * @param msg     text to be displayed
1639
 * @param timeout time for which msg shall be visible
1640
 */
1641
void MainWindow::showStatusMessage(const QString &msg, int timeout) {
2✔
1642
  ui->statusBar->showMessage(msg, timeout);
2✔
1643
}
2✔
1644

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

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

1667
  if (ret != QMessageBox::Yes)
×
1668
    return;
1669

1670
  // Disable preemptively. ImitatePass::reencryptPath emits
1671
  // startReencryptPath asynchronously and the slot would re-run this,
1672
  // but setEnabled(false) is idempotent so the duplicate is harmless.
1673
  startReencryptPath();
×
1674

1675
  QtPassSettings::getImitatePass()->reencryptPath(
×
1676
      QDir::cleanPath(QDir(dir).absolutePath()));
×
1677
}
×
1678

1679
/**
1680
 * @brief MainWindow::startReencryptPath disable ui elements and treeview
1681
 */
1682
void MainWindow::startReencryptPath() {
×
1683
  setUiElementsEnabled(false);
×
1684
  ui->treeView->setDisabled(true);
×
1685
}
×
1686

1687
/**
1688
 * @brief MainWindow::endReencryptPath re-enable ui elements
1689
 */
1690
void MainWindow::endReencryptPath() { setUiElementsEnabled(true); }
×
1691

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

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

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

1768
void MainWindow::updateGitButtonVisibility() {
15✔
1769
  if (!QtPassSettings::isUseGit() ||
30✔
1770
      (QtPassSettings::getGitExecutable().isEmpty() &&
15✔
1771
       QtPassSettings::getPassExecutable().isEmpty())) {
15✔
1772
    enableGitButtons(false);
15✔
1773
  } else {
UNCOV
1774
    enableGitButtons(true);
×
1775
  }
1776
}
15✔
1777

1778
void MainWindow::updateOtpButtonVisibility() {
15✔
1779
#if defined(Q_OS_WIN) || defined(__APPLE__)
1780
  ui->actionOtp->setVisible(false);
1781
#endif
1782
  if (!QtPassSettings::isUseOtp()) {
15✔
1783
    ui->actionOtp->setEnabled(false);
15✔
1784
  } else {
UNCOV
1785
    ui->actionOtp->setEnabled(true);
×
1786
  }
1787
}
15✔
1788

1789
void MainWindow::updateGrepButtonVisibility() {
12✔
1790
  const bool enabled = QtPassSettings::isUseGrepSearch();
12✔
1791
  ui->grepButton->setVisible(enabled);
12✔
1792
  ui->grepCaseButton->setVisible(enabled);
12✔
1793
  if (!enabled && m_grep.inGrepMode()) {
12✔
UNCOV
1794
    ui->grepButton->setChecked(false);
×
1795
  }
1796
}
12✔
1797

1798
void MainWindow::enableGitButtons(const bool &state) {
15✔
1799
  // Following GNOME guidelines is preferable disable buttons instead of hide
1800
  ui->actionPush->setEnabled(state);
15✔
1801
  ui->actionUpdate->setEnabled(state);
15✔
1802
}
15✔
1803

1804
/**
1805
 * @brief MainWindow::critical critical message popup wrapper.
1806
 * @param title
1807
 * @param msg
1808
 */
1809
void MainWindow::critical(const QString &title, const QString &msg) {
×
1810
  QMessageBox::critical(this, title, msg);
×
UNCOV
1811
}
×
1812

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

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

1842
    m_outputCounter++;
1✔
1843
    QString lineNumber = QString::number(m_outputCounter);
1✔
1844

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

1858
    m_processOutputEdit->append(coloredOutput);
1✔
1859
  }
1860

1861
  limitOutputLines();
1✔
1862

1863
  if (m_autoScroll) {
1✔
1864
    m_processOutputEdit->verticalScrollBar()->setValue(
2✔
1865
        m_processOutputEdit->verticalScrollBar()->maximum());
1✔
1866
  }
1867
}
1868

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

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

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

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

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

1999
  QTextCursor cursor(doc);
×
2000
  cursor.movePosition(QTextCursor::Start);
×
2001
  cursor.movePosition(QTextCursor::NextBlock, QTextCursor::KeepAnchor, excess);
×
2002
  cursor.removeSelectedText();
×
UNCOV
2003
}
×
2004

2005
/**
2006
 * @brief Clears the process output panel.
2007
 *
2008
 * Clears all output, resets the line counter, and re-enables auto-scroll.
2009
 */
2010
void MainWindow::on_clearOutputButton_clicked() {
×
2011
  m_processOutputEdit->clear();
×
2012
  m_outputCounter = 0;
×
2013
  m_autoScroll = true;
×
UNCOV
2014
}
×
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