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

IJHack / QtPass / 27483391683

14 Jun 2026 12:23AM UTC coverage: 56.421% (-0.004%) from 56.425%
27483391683

Pull #1531

github

web-flow
Merge f078678b5 into 8d8385169
Pull Request #1531: refactor: extract grep search state into GrepSearchController (#1512)

3 of 25 new or added lines in 2 files covered. (12.0%)

3 existing lines in 1 file now uncovered.

3875 of 6868 relevant lines covered (56.42%)

35.92 hits per line

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

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

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

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

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

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

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

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

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

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

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

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

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

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

120
  updateProfileBox();
12✔
121

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

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

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

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

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

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

161
  setUiElementsEnabled(true);
12✔
162

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

853
  if (proxyModel.rowCount() > 0) {
×
854
    selectFirstFile();
×
855
    on_treeView_clicked(ui->treeView->currentIndex());
×
856
  }
857
}
858

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

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

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

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

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

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

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

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

1054
  if (!d.exec()) {
×
1055
    ui->treeView->setFocus();
×
1056
  }
1057
}
×
1058

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

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

1097
  QFileInfo fileOrFolder =
1098
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
1099
  QString file = "";
×
1100
  bool isDir = false;
1101

1102
  if (fileOrFolder.isFile()) {
×
1103
    file = getFile(ui->treeView->currentIndex(), true);
×
1104
  } else {
1105
    file = Util::getDir(ui->treeView->currentIndex(), true, model, proxyModel);
×
1106
    isDir = true;
1107
  }
1108

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

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

1135
  QtPassSettings::getPass()->Remove(file, isDir);
×
1136
}
×
1137

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

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

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

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

1183
  UsersDialog d(dir, this);
×
1184
  if (!d.exec()) {
×
1185
    ui->treeView->setFocus();
×
1186
  }
1187
}
×
1188

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

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

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

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

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

1269
  ui->lineEdit->clear();
×
1270

1271
  QtPassSettings::setProfile(name);
×
1272

1273
  QtPassSettings::setPassStore(
×
1274
      QtPassSettings::getProfiles().value(name).value("path"));
×
1275
  QtPassSettings::setPassSigningKey(
×
1276
      QtPassSettings::getProfiles().value(name).value("signingKey"));
×
1277
  ui->statusBar->showMessage(tr("Profile changed to %1").arg(name), 2000);
×
1278

1279
  QtPassSettings::getPass()->updateEnv();
×
1280

1281
  const QString passStore = QtPassSettings::getPassStore();
×
1282
  proxyModel.setStore(passStore);
×
1283
  ui->treeView->setRootIndex(
×
1284
      proxyModel.mapFromSource(model.setRootPath(passStore)));
×
1285
  deselect();
×
1286
  ui->treeView->setCurrentIndex(QModelIndex());
×
1287
}
1288

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

1298
  if (m_tray == nullptr) {
1299
#ifdef QT_DEBUG
1300
    dbg() << "Allocating tray icon failed.";
1301
#endif
1302
    return;
1303
  }
1304

1305
  if (!m_tray->getIsAllocated()) {
×
1306
    destroyTrayIcon();
×
1307
  }
1308
}
1309

1310
/**
1311
 * @brief MainWindow::destroyTrayIcon remove that pesky tray icon
1312
 */
1313
void MainWindow::destroyTrayIcon() {
×
1314
  delete m_tray;
×
1315
  m_tray = nullptr;
×
1316
}
×
1317

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

1329
    QtPassSettings::setGeometry(saveGeometry());
×
1330
    QtPassSettings::setSavestate(saveState());
×
1331
    QtPassSettings::setMaximized(isMaximized());
×
1332
    if (!isMaximized()) {
×
1333
      QtPassSettings::setPos(pos());
×
1334
      QtPassSettings::setSize(size());
×
1335
    }
1336
    event->accept();
1337
  }
1338
}
×
1339

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

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

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

1396
  ui->treeView->setCurrentIndex(index);
×
1397

1398
  QPoint globalPos = ui->treeView->viewport()->mapToGlobal(pos);
×
1399

1400
  QFileInfo fileOrFolder =
1401
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
1402

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

1435
      auto *shareMenu = new QMenu(tr("Share"), &contextMenu);
×
1436
      contextMenu.addMenu(shareMenu);
×
1437

1438
      QString gpgIdPath = Pass::getGpgIdPath(dirPath);
×
1439
      bool gpgIdExists = !gpgIdPath.isEmpty() && QFile(gpgIdPath).exists();
×
1440

1441
      QString exePath = QtPassSettings::isUsePass()
×
1442
                            ? QtPassSettings::getPassExecutable()
×
1443
                            : QtPassSettings::getGpgExecutable();
×
1444
      bool gpgAvailable = !exePath.isEmpty() && (exePath.startsWith("wsl ") ||
×
1445
                                                 QFile(exePath).exists());
×
1446

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

1452
      QAction *exportKey = shareMenu->addAction(tr("Export my public key..."));
×
1453
      exportKey->setEnabled(gpgAvailable);
×
1454
      connect(exportKey, &QAction::triggered, this,
×
1455
              &MainWindow::exportPublicKey);
×
1456

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

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

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

1479
  contextMenu->exec(globalPos);
×
1480
  delete contextMenu;
×
1481
}
×
1482

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

1490
  QString path = QDir::toNativeSeparators(dir);
×
1491
  QDesktopServices::openUrl(QUrl::fromLocalFile(path));
×
1492
}
×
1493

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

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

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

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

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

1603
/**
1604
 * @brief MainWindow::clearTemplateWidgets empty the template widget fields in
1605
 * the UI
1606
 */
1607
void MainWindow::clearTemplateWidgets() {
×
1608
  while (ui->gridLayout->count() > 0) {
×
1609
    QLayoutItem *item = ui->gridLayout->takeAt(0);
×
1610
    delete item->widget();
×
1611
    delete item;
×
1612
  }
1613
  ui->verticalLayoutPassword->setSpacing(0);
×
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 MainWindow::addToGridLayout add a field to the template grid
1646
 * @param position
1647
 * @param field
1648
 * @param value
1649
 */
1650
void MainWindow::addToGridLayout(int position, const QString &field,
×
1651
                                 const QString &value) {
1652
  QString trimmedField = field.trimmed();
1653
  QString trimmedValue = value.trimmed();
1654

1655
  const QString buttonStyle =
1656
      "border-style: none; background: transparent; padding: 0; margin: 0; "
1657
      "icon-size: 16px; color: inherit;";
×
1658

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

1670
    fieldLabel->setStyleSheet(buttonStyle);
×
1671
    frame->layout()->addWidget(fieldLabel);
×
1672
  }
1673

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

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

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

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

1744
  frame->setStyleSheet(
×
1745
      ".QFrame{border: 1px solid lightgrey; border-radius: 5px;}");
1746

1747
  // set into the layout
1748
  ui->gridLayout->addWidget(new QLabel(trimmedField), position, 0);
×
1749
  ui->gridLayout->addWidget(frame, position, 1);
×
1750
}
×
1751

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

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

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

1784
  if (ret != QMessageBox::Yes)
×
1785
    return;
1786

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

1792
  QtPassSettings::getImitatePass()->reencryptPath(
×
1793
      QDir::cleanPath(QDir(dir).absolutePath()));
×
1794
}
×
1795

1796
/**
1797
 * @brief MainWindow::startReencryptPath disable ui elements and treeview
1798
 */
1799
void MainWindow::startReencryptPath() {
×
1800
  setUiElementsEnabled(false);
×
1801
  ui->treeView->setDisabled(true);
×
1802
}
×
1803

1804
/**
1805
 * @brief MainWindow::endReencryptPath re-enable ui elements
1806
 */
1807
void MainWindow::endReencryptPath() { setUiElementsEnabled(true); }
×
1808

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

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

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

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

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

1906
void MainWindow::updateGrepButtonVisibility() {
12✔
1907
  const bool enabled = QtPassSettings::isUseGrepSearch();
12✔
1908
  ui->grepButton->setVisible(enabled);
12✔
1909
  ui->grepCaseButton->setVisible(enabled);
12✔
1910
  if (!enabled && m_grep.inGrepMode()) {
12✔
1911
    ui->grepButton->setChecked(false);
×
1912
  }
1913
}
12✔
1914

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

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

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

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

1959
    m_outputCounter++;
1✔
1960
    QString lineNumber = QString::number(m_outputCounter);
1✔
1961

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

1975
    m_processOutputEdit->append(coloredOutput);
1✔
1976
  }
1977

1978
  limitOutputLines();
1✔
1979

1980
  if (m_autoScroll) {
1✔
1981
    m_processOutputEdit->verticalScrollBar()->setValue(
2✔
1982
        m_processOutputEdit->verticalScrollBar()->maximum());
1✔
1983
  }
1984
}
1985

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

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

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

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

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

2116
  QTextCursor cursor(doc);
×
2117
  cursor.movePosition(QTextCursor::Start);
×
2118
  cursor.movePosition(QTextCursor::NextBlock, QTextCursor::KeepAnchor, excess);
×
2119
  cursor.removeSelectedText();
×
2120
}
×
2121

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