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

IJHack / QtPass / 27700566420

17 Jun 2026 03:32PM UTC coverage: 57.087% (-0.02%) from 57.104%
27700566420

Pull #1558

github

web-flow
Merge f6b05cb01 into e096ad176
Pull Request #1558: refactor(#1511): inject Pass*/AppSettings into UsersDialog

0 of 16 new or added lines in 3 files covered. (0.0%)

1 existing line in 1 file now uncovered.

3963 of 6942 relevant lines covered (57.09%)

23.24 hits per line

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

27.69
/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);
24✔
108

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

122
  updateProfileBox();
12✔
123

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

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

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

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

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

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

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

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

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

183
  setUiElementsEnabled(true);
12✔
184

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1064
  if (!d.exec()) {
×
1065
    ui->treeView->setFocus();
×
1066
  }
1067
}
×
1068

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

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

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

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

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

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

1146
  QtPassSettings::getPass()->Remove(file, isDir);
×
1147
}
×
1148

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

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

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

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

NEW
1194
  UsersDialog d(QtPassSettings::getPass(), QtPassSettings::load(), dir, this);
×
1195
  if (!d.exec()) {
×
1196
    ui->treeView->setFocus();
×
1197
  }
1198
}
×
1199

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

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

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

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

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

1280
  ui->lineEdit->clear();
×
1281

1282
  QtPassSettings::setProfile(name);
×
1283

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

1290
  QtPassSettings::getPass()->updateEnv();
×
1291

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

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

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

1315
  if (!m_tray->getIsAllocated()) {
×
1316
    destroyTrayIcon();
×
1317
  }
1318
}
1319

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

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

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

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

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

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

1406
  ui->treeView->setCurrentIndex(index);
×
1407

1408
  QPoint globalPos = ui->treeView->viewport()->mapToGlobal(pos);
×
1409

1410
  QFileInfo fileOrFolder =
1411
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
1412

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

1446
      auto *shareMenu = new QMenu(tr("Share"), &contextMenu);
×
1447
      contextMenu.addMenu(shareMenu);
×
1448

1449
      QString gpgIdPath =
1450
          Pass::getGpgIdPath(dirPath, QtPassSettings::getPassStore());
×
1451
      bool gpgIdExists = !gpgIdPath.isEmpty() && QFile(gpgIdPath).exists();
×
1452

1453
      QString exePath = QtPassSettings::isUsePass()
×
1454
                            ? QtPassSettings::getPassExecutable()
×
1455
                            : QtPassSettings::getGpgExecutable();
×
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() {
×
1510
  bool ok;
1511
  QString dir = Util::getDir(ui->treeView->currentIndex(), false, model,
×
1512
                             proxyModel, QtPassSettings::getPassStore());
×
1513
  QString newdir = QInputDialog::getText(
1514
      this, tr("New file"),
×
1515
      tr("New Folder: \n(Will be placed in %1 )")
×
1516
          .arg(QtPassSettings::getPassStore() +
×
1517
               Util::getDir(ui->treeView->currentIndex(), true, model,
×
1518
                            proxyModel, QtPassSettings::getPassStore())),
×
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
  }
1532
  if (QtPassSettings::isAddGPGId(true)) {
×
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
  }
×
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()) {
×
1584
    if (QtPassSettings::isUseGit() && QtPassSettings::isAutoPull()) {
×
1585
      onUpdate(true);
×
1586
    }
1587
    setPassword(file, false);
×
1588
  }
1589
}
×
1590

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1869
  limitOutputLines();
1✔
1870

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

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

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

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

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

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

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

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