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

IJHack / QtPass / 27482967311

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

Pull #1531

github

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

3 of 24 new or added lines in 2 files covered. (12.5%)

2 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
  }
NEW
909
  if (outcome.discard) {
×
910
    return;
×
911
  }
912
  setUiElementsEnabled(true);
×
NEW
913
  if (!m_grep.inGrepMode())
×
914
    return;
915
  ui->grepResultsList->clear();
×
916
  if (results.isEmpty()) {
×
917
    ui->statusBar->showMessage(tr("No matches found."), 3000);
×
918
    ui->grepResultsList->setVisible(false);
×
919
    ui->treeView->setVisible(true);
×
920
    return;
×
921
  }
922
  const bool hideContent = QtPassSettings::isHideContent();
×
923
  int totalLines = 0;
924
  for (const auto &pair : results) {
×
925
    auto *entryItem = new QTreeWidgetItem(ui->grepResultsList);
×
926
    entryItem->setText(0, pair.first);
×
927
    entryItem->setData(0, Qt::UserRole, pair.first);
×
928
    for (const QString &line : pair.second) {
×
929
      auto *lineItem = new QTreeWidgetItem(entryItem);
×
930
      lineItem->setText(0, hideContent ? "***" + tr("Content hidden") + "***"
×
931
                                       : line);
932
      lineItem->setData(0, Qt::UserRole, pair.first);
×
933
      ++totalLines;
×
934
    }
935
  }
936
  ui->grepResultsList->expandAll();
×
937
  ui->treeView->setVisible(false);
×
938
  ui->grepResultsList->setVisible(true);
×
939
  ui->statusBar->showMessage(
×
940
      tr("Found %n match(es)", nullptr, totalLines) + " " +
×
941
          tr("in %n entr(ies).", nullptr, static_cast<int>(results.size())),
×
942
      3000);
943
  if (QtPassSettings::isUseAutoclearPanel())
×
944
    clearPanelTimer.start();
×
945
}
946

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

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

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

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

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

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

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

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

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

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

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

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

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

1133
  QtPassSettings::getPass()->Remove(file, isDir);
×
1134
}
×
1135

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

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

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

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

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

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

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

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

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

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

1267
  ui->lineEdit->clear();
×
1268

1269
  QtPassSettings::setProfile(name);
×
1270

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

1277
  QtPassSettings::getPass()->updateEnv();
×
1278

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

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

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

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

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

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

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

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

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

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

1394
  ui->treeView->setCurrentIndex(index);
×
1395

1396
  QPoint globalPos = ui->treeView->viewport()->mapToGlobal(pos);
×
1397

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

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

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

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

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

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

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

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

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

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

1477
  contextMenu->exec(globalPos);
×
1478
  delete contextMenu;
×
1479
}
×
1480

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

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

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

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

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

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

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

1601
/**
1602
 * @brief MainWindow::clearTemplateWidgets empty the template widget fields in
1603
 * the UI
1604
 */
1605
void MainWindow::clearTemplateWidgets() {
×
1606
  while (ui->gridLayout->count() > 0) {
×
1607
    QLayoutItem *item = ui->gridLayout->takeAt(0);
×
1608
    delete item->widget();
×
1609
    delete item;
×
1610
  }
1611
  ui->verticalLayoutPassword->setSpacing(0);
×
1612
}
×
1613

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

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

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

1642
/**
1643
 * @brief MainWindow::addToGridLayout add a field to the template grid
1644
 * @param position
1645
 * @param field
1646
 * @param value
1647
 */
1648
void MainWindow::addToGridLayout(int position, const QString &field,
×
1649
                                 const QString &value) {
1650
  QString trimmedField = field.trimmed();
1651
  QString trimmedValue = value.trimmed();
1652

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

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

1668
    fieldLabel->setStyleSheet(buttonStyle);
×
1669
    frame->layout()->addWidget(fieldLabel);
×
1670
  }
1671

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

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

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

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

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

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

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

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

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

1782
  if (ret != QMessageBox::Yes)
×
1783
    return;
1784

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1957
    m_outputCounter++;
1✔
1958
    QString lineNumber = QString::number(m_outputCounter);
1✔
1959

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

1973
    m_processOutputEdit->append(coloredOutput);
1✔
1974
  }
1975

1976
  limitOutputLines();
1✔
1977

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

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

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

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

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

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

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

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