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

IJHack / QtPass / 25730755097

12 May 2026 11:12AM UTC coverage: 28.39%. First build
25730755097

Pull #1465

github

web-flow
Merge be70f2458 into b162da32e
Pull Request #1465: fix(security): chmod 0600 on .gpg-id after write

1 of 2 new or added lines in 2 files covered. (50.0%)

1897 of 6682 relevant lines covered (28.39%)

27.13 hits per line

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

0.0
/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 "qpushbuttonasqrcode.h"
16
#include "qpushbuttonshowpassword.h"
17
#include "qpushbuttonwithclipboard.h"
18
#include "qtpass.h"
19
#include "qtpasssettings.h"
20
#include "trayicon.h"
21
#include "ui_mainwindow.h"
22
#include "usersdialog.h"
23
#include "util.h"
24
#include <QApplication>
25
#include <QCloseEvent>
26
#include <QDesktopServices>
27
#include <QDialog>
28
#include <QDirIterator>
29
#include <QDockWidget>
30
#include <QFileInfo>
31
#include <QHBoxLayout>
32
#include <QInputDialog>
33
#include <QLabel>
34
#include <QLineEdit>
35
#include <QMenu>
36
#include <QMessageBox>
37
#include <QScrollBar>
38
#include <QShortcut>
39
#include <QTextCursor>
40
#include <QTextEdit>
41
#include <QTimer>
42
#include <QToolButton>
43
#include <QTreeWidget>
44
#include <utility>
45

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

61
  m_qtPass = new QtPass(this);
×
62

63
  // register shortcut ctrl/cmd + Q to close the main window
64
  new QShortcut(QKeySequence(Qt::CTRL | Qt::Key_Q), this, SLOT(close()));
×
65
  // register shortcut ctrl/cmd + C to copy the currently selected password
66
  new QShortcut(QKeySequence(QKeySequence::StandardKey::Copy), this,
×
67
                SLOT(copyPasswordFromTreeview()));
×
68

69
  model.setNameFilters(QStringList() << "*.gpg");
×
70
  model.setNameFilterDisables(false);
×
71

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

79
  QString passStore = QtPassSettings::getPassStore(Util::findPasswordStore());
×
80

81
  QModelIndex rootDir = model.setRootPath(passStore);
×
82
  model.fetchMore(rootDir);
×
83

84
  proxyModel.setModelAndStore(&model, passStore);
×
85
  selectionModel.reset(new QItemSelectionModel(&proxyModel));
×
86

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

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

116
  updateProfileBox();
×
117

118
  QtPassSettings::getPass()->updateEnv();
×
119
  clearPanelTimer.setInterval(MS_PER_SECOND *
×
120
                              QtPassSettings::getAutoclearPanelSeconds());
×
121
  clearPanelTimer.setSingleShot(true);
×
122
  connect(&clearPanelTimer, &QTimer::timeout, this, [this]() { clearPanel(); });
×
123

124
  searchTimer.setInterval(350);
×
125
  searchTimer.setSingleShot(true);
×
126

127
  connect(&searchTimer, &QTimer::timeout, this, &MainWindow::onTimeoutSearch);
×
128

129
  initToolBarButtons();
×
130
  initStatusBar();
×
131
  initProcessOutputPanel();
×
132

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

154
  ui->lineEdit->setClearButtonEnabled(true);
×
155
  updateGrepButtonVisibility();
×
156

157
  setUiElementsEnabled(true);
×
158

159
  ui->lineEdit->setText(searchText);
×
160

161
  if (!m_qtPass->init()) {
×
162
    // no working config so this should just quit
163
    QApplication::quit();
×
164
    return;
165
  }
166

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

176
MainWindow::~MainWindow() { delete m_qtPass; }
×
177

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

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

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

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

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

289
/**
290
 * @brief MainWindow::initStatusBar init statusBar with default message and logo
291
 */
292
void MainWindow::initStatusBar() {
×
293
  ui->statusBar->showMessage(tr("Welcome to QtPass %1").arg(VERSION), 2000);
×
294

295
  QPixmap logo = QPixmap::fromImage(QImage(":/artwork/icon.svg"))
×
296
                     .scaledToHeight(statusBar()->height());
×
297
  auto *logoApp = new QLabel(statusBar());
×
298
  logoApp->setPixmap(logo);
×
299
  statusBar()->addPermanentWidget(logoApp);
×
300
}
×
301

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

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

347
  connect(m_clearOutputButton, &QToolButton::clicked, this,
×
348
          &MainWindow::on_clearOutputButton_clicked);
×
349

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

369
auto MainWindow::getCurrentTreeViewIndex() -> QModelIndex {
×
370
  return ui->treeView->currentIndex();
×
371
}
372

373
void MainWindow::cleanKeygenDialog() {
×
374
  if (m_keygenDialog != nullptr) {
×
375
    m_keygenDialog->close();
×
376
  }
377
  m_keygenDialog = nullptr;
×
378
}
×
379

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

400
  if (isHtml) {
×
401
    QString _text = text;
402
    if (!ui->textBrowser->toPlainText().isEmpty()) {
×
403
      _text = ui->textBrowser->toHtml() + _text;
×
404
    }
405
    ui->textBrowser->setHtml(_text);
×
406
  } else {
407
    ui->textBrowser->setText(text);
×
408
  }
409
}
×
410

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

424
  if (QtPassSettings::isNoLineWrapping()) {
×
425
    ui->textBrowser->setLineWrapMode(QTextBrowser::NoWrap);
×
426
  } else {
427
    ui->textBrowser->setLineWrapMode(QTextBrowser::WidgetWidth);
×
428
  }
429
}
×
430

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

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

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

466
      updateProfileBox();
×
467
      const QString passStore = QtPassSettings::getPassStore();
×
468
      proxyModel.setStore(passStore);
×
469
      ui->treeView->setRootIndex(
×
470
          proxyModel.mapFromSource(model.setRootPath(passStore)));
×
471
      deselect();
×
472
      ui->treeView->setCurrentIndex(QModelIndex());
×
473

474
      if (m_qtPass->isFreshStart() && !Util::configIsValid()) {
×
475
        config();
×
476
      }
477
      QtPassSettings::getPass()->updateEnv();
×
478
      clearPanelTimer.setInterval(MS_PER_SECOND *
×
479
                                  QtPassSettings::getAutoclearPanelSeconds());
×
480
      m_qtPass->setClipboardTimer();
×
481

482
      updateGitButtonVisibility();
×
483
      updateOtpButtonVisibility();
×
484
      updateGrepButtonVisibility();
×
485
      updateProcessOutputVisibility();
×
486
      if (QtPassSettings::isUseTrayIcon() && m_tray == nullptr) {
×
487
        initTrayIcon();
×
488
      } else if (!QtPassSettings::isUseTrayIcon() && m_tray != nullptr) {
×
489
        destroyTrayIcon();
×
490
      }
491
    }
492

493
    m_qtPass->setFreshStart(false);
×
494
  }
495
}
×
496

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

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

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

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

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

569
  if (fileOrFolder.isFile()) {
×
570
    editPassword(getFile(index, true));
×
571
  }
572
}
×
573

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

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

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

617
  // set clipped text
618
  m_qtPass->setClippedText(password, p_output);
×
619

620
  // first clear the current view:
621
  clearTemplateWidgets();
×
622

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

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

643
    output = fileContent.getRemainingDataForDisplay();
×
644
  }
645

646
  if (QtPassSettings::isUseAutoclearPanel()) {
×
647
    clearPanelTimer.start();
×
648
  }
649

650
  emit passShowHandlerFinished(output);
×
651
  setUiElementsEnabled(true);
×
652
}
×
653

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

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

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

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

754
  if (QtPassSettings::isAlwaysOnTop()) {
×
755
    Qt::WindowFlags flags = windowFlags();
756
    setWindowFlags(flags | Qt::WindowStaysOnTopHint);
×
757
    show();
×
758
  }
759

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

771
/**
772
 * @brief MainWindow::on_configButton_clicked run Mainwindow::config
773
 */
774
void MainWindow::onConfig() { config(); }
×
775

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

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

800
  if (query.isEmpty()) {
×
801
    ui->treeView->collapseAll();
×
802
    deselect();
×
803
  }
804

805
  query.replace(QStringLiteral(" "), ".*");
×
806
  QRegularExpression regExp(query, QRegularExpression::CaseInsensitiveOption);
×
807
  proxyModel.setFilterRegularExpression(regExp);
×
808
  ui->treeView->setRootIndex(proxyModel.mapFromSource(
×
809
      model.setRootPath(QtPassSettings::getPassStore())));
×
810

811
  if (proxyModel.rowCount() > 0 && !query.isEmpty()) {
×
812
    selectFirstFile();
×
813
  } else {
814
    ui->actionEdit->setEnabled(false);
×
815
    ui->actionDelete->setEnabled(false);
×
816
  }
817
}
×
818

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

829
  if (m_grepMode) {
×
830
    const QString query = ui->lineEdit->text();
×
831
    if (!query.isEmpty()) {
×
832
      m_grepCancelled = false;
×
833
      ui->grepResultsList->clear();
×
834
      ui->statusBar->showMessage(tr("Searching…"));
×
835
      if (!m_grepBusy) {
×
836
        m_grepBusy = true;
×
837
        QApplication::setOverrideCursor(Qt::WaitCursor);
×
838
      }
839
      QtPassSettings::getPass()->Grep(query, ui->grepCaseButton->isChecked());
×
840
    } else {
841
      m_grepCancelled = true;
×
842
      if (m_grepBusy) {
×
843
        m_grepBusy = false;
×
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
  m_grepMode = checked;
×
864
  if (checked) {
×
865
    ui->lineEdit->setPlaceholderText(tr("Search content (regex)"));
×
866
    ui->lineEdit->clear();
×
867
    searchTimer.stop();
×
868
    proxyModel.setFilterRegularExpression(QRegularExpression());
×
869
    ui->treeView->setRootIndex(proxyModel.mapFromSource(
×
870
        model.setRootPath(QtPassSettings::getPassStore())));
×
871
    ui->grepResultsList->setVisible(false);
×
872
    // Keep treeView visible until results arrive
873
  } else {
874
    if (m_grepBusy) {
×
875
      m_grepBusy = false;
×
876
      m_grepCancelled = true;
×
877
      QApplication::restoreOverrideCursor();
×
878
    }
879
    searchTimer.stop();
×
880
    ui->lineEdit->blockSignals(true);
×
881
    ui->lineEdit->clear();
×
882
    ui->lineEdit->blockSignals(false);
×
883
    ui->lineEdit->setPlaceholderText(tr("Search Password"));
×
884
    ui->grepResultsList->clear();
×
885
    ui->grepResultsList->setVisible(false);
×
886
    ui->treeView->setVisible(true);
×
887
    proxyModel.setFilterRegularExpression(QRegularExpression());
×
888
    ui->treeView->setRootIndex(proxyModel.mapFromSource(
×
889
        model.setRootPath(QtPassSettings::getPassStore())));
×
890
  }
891
}
×
892

893
/**
894
 * @brief Display grep results in grepResultsList.
895
 */
896
void MainWindow::onGrepFinished(
×
897
    const QList<QPair<QString, QStringList>> &results) {
898
  if (m_grepBusy) {
×
899
    m_grepBusy = false;
×
900
    QApplication::restoreOverrideCursor();
×
901
  }
902
  if (m_grepCancelled) {
×
903
    m_grepCancelled = false;
×
904
    return;
×
905
  }
906
  setUiElementsEnabled(true);
×
907
  if (!m_grepMode)
×
908
    return;
909
  ui->grepResultsList->clear();
×
910
  if (results.isEmpty()) {
×
911
    ui->statusBar->showMessage(tr("No matches found."), 3000);
×
912
    ui->grepResultsList->setVisible(false);
×
913
    ui->treeView->setVisible(true);
×
914
    return;
×
915
  }
916
  const bool hideContent = QtPassSettings::isHideContent();
×
917
  int totalLines = 0;
918
  for (const auto &pair : results) {
×
919
    auto *entryItem = new QTreeWidgetItem(ui->grepResultsList);
×
920
    entryItem->setText(0, pair.first);
×
921
    entryItem->setData(0, Qt::UserRole, pair.first);
×
922
    for (const QString &line : pair.second) {
×
923
      auto *lineItem = new QTreeWidgetItem(entryItem);
×
924
      lineItem->setText(0, hideContent ? "***" + tr("Content hidden") + "***"
×
925
                                       : line);
926
      lineItem->setData(0, Qt::UserRole, pair.first);
×
927
      ++totalLines;
×
928
    }
929
  }
930
  ui->grepResultsList->expandAll();
×
931
  ui->treeView->setVisible(false);
×
932
  ui->grepResultsList->setVisible(true);
×
933
  ui->statusBar->showMessage(
×
934
      tr("Found %n match(es)", nullptr, totalLines) + " " +
×
935
          tr("in %n entr(ies).", nullptr, static_cast<int>(results.size())),
×
936
      3000);
937
  if (QtPassSettings::isUseAutoclearPanel())
×
938
    clearPanelTimer.start();
×
939
}
940

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

967
/**
968
 * @brief MainWindow::selectFirstFile select the first possible file in the
969
 * tree
970
 */
971
void MainWindow::selectFirstFile() {
×
972
  QModelIndex index = proxyModel.mapFromSource(
×
973
      model.setRootPath(QtPassSettings::getPassStore()));
×
974
  index = firstFile(index);
×
975
  ui->treeView->setCurrentIndex(index);
×
976
}
×
977

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

998
/**
999
 * @brief MainWindow::setPassword open passworddialog
1000
 * @param file which pgp file
1001
 * @param isNew insert (not update)
1002
 */
1003
void MainWindow::setPassword(const QString &file, bool isNew) {
×
1004
  PasswordDialog d(file, isNew, this);
×
1005

1006
  if (isNew) {
×
1007
    QString storePath = QtPassSettings::getPassStore();
×
1008
    QString folder =
1009
        Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel);
×
1010
    if (folder.isEmpty()) {
×
1011
      folder = storePath;
×
1012
    }
1013
    QHash<QString, QStringList> templates = Util::readTemplates(storePath);
×
1014
    if (!templates.isEmpty()) {
1015
      QString defaultTemplate = Util::getFolderTemplate(folder, storePath);
×
1016
      d.setAvailableTemplates(templates, defaultTemplate);
×
1017
      new QShortcut(QKeySequence(Qt::CTRL | Qt::Key_T), &d,
×
1018
                    [&d]() { d.cycleTemplate(); });
×
1019
    }
1020
  }
×
1021

1022
  if (!d.exec()) {
×
1023
    ui->treeView->setFocus();
×
1024
  }
1025
}
×
1026

1027
/**
1028
 * @brief MainWindow::addPassword add a new password by showing a
1029
 * number of dialogs.
1030
 */
1031
void MainWindow::addPassword() {
×
1032
  bool ok;
1033
  QString dir =
1034
      Util::getDir(ui->treeView->currentIndex(), true, model, proxyModel);
×
1035
  QString file =
1036
      QInputDialog::getText(this, tr("New file"),
×
1037
                            tr("New password file: \n(Will be placed in %1 )")
×
1038
                                .arg(QtPassSettings::getPassStore() +
×
1039
                                     Util::getDir(ui->treeView->currentIndex(),
×
1040
                                                  true, model, proxyModel)),
1041
                            QLineEdit::Normal, "", &ok);
×
1042
  if (!ok || file.isEmpty()) {
×
1043
    return;
1044
  }
1045
  file = dir + file;
×
1046
  setPassword(file);
×
1047
}
1048

1049
/**
1050
 * @brief MainWindow::onDelete remove password, if you are
1051
 * sure.
1052
 */
1053
void MainWindow::onDelete() {
×
1054
  QModelIndex currentIndex = ui->treeView->currentIndex();
×
1055
  if (!currentIndex.isValid()) {
1056
    // This fixes https://github.com/IJHack/QtPass/issues/556
1057
    // Otherwise the entire password directory would be deleted if
1058
    // nothing is selected in the tree view.
1059
    return;
×
1060
  }
1061

1062
  QFileInfo fileOrFolder =
1063
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
1064
  QString file = "";
×
1065
  bool isDir = false;
1066

1067
  if (fileOrFolder.isFile()) {
×
1068
    file = getFile(ui->treeView->currentIndex(), true);
×
1069
  } else {
1070
    file = Util::getDir(ui->treeView->currentIndex(), true, model, proxyModel);
×
1071
    isDir = true;
1072
  }
1073

1074
  QString dirMessage = tr(" and the whole content?");
1075
  if (isDir) {
×
1076
    QDirIterator it(model.rootPath() + QDir::separator() + file,
×
1077
                    QDirIterator::Subdirectories);
×
1078
    bool okDir = true;
1079
    while (it.hasNext() && okDir) {
×
1080
      it.next();
×
1081
      if (QFileInfo(it.filePath()).isFile()) {
×
1082
        if (QFileInfo(it.filePath()).suffix() != "gpg") {
×
1083
          okDir = false;
1084
          dirMessage = tr(" and the whole content? <br><strong>Attention: "
×
1085
                          "there are unexpected files in the given folder, "
1086
                          "check them before continue.</strong>");
1087
        }
1088
      }
1089
    }
1090
  }
×
1091

1092
  if (QMessageBox::question(
×
1093
          this, isDir ? tr("Delete folder?") : tr("Delete password?"),
×
1094
          tr("Are you sure you want to delete %1%2?")
×
1095
              .arg(QDir::separator() + file, isDir ? dirMessage : "?"),
×
1096
          QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) {
1097
    return;
1098
  }
1099

1100
  QtPassSettings::getPass()->Remove(file, isDir);
×
1101
}
×
1102

1103
/**
1104
 * @brief MainWindow::onOTP try and generate (selected) OTP code.
1105
 */
1106
void MainWindow::onOtp() {
×
1107
  QString file = getFile(ui->treeView->currentIndex(), true);
×
1108
  if (!file.isEmpty()) {
×
1109
    if (QtPassSettings::isUseOtp()) {
×
1110
      setUiElementsEnabled(false);
×
1111
      QtPassSettings::getPass()->OtpGenerate(file);
×
1112
    }
1113
  } else {
1114
    flashText(tr("No password selected for OTP generation"), true);
×
1115
  }
1116
}
×
1117

1118
/**
1119
 * @brief MainWindow::onEdit try and edit (selected) password.
1120
 */
1121
void MainWindow::onEdit() {
×
1122
  QString file = getFile(ui->treeView->currentIndex(), true);
×
1123
  editPassword(file);
×
1124
}
×
1125

1126
/**
1127
 * @brief MainWindow::userDialog see MainWindow::onUsers()
1128
 * @param dir folder to edit users for.
1129
 */
1130
void MainWindow::userDialog(const QString &dir) {
×
1131
  if (!dir.isEmpty()) {
×
1132
    m_currentDir = dir;
×
1133
  }
1134
  onUsers();
×
1135
}
×
1136

1137
/**
1138
 * @brief MainWindow::onUsers edit users for the current
1139
 * folder,
1140
 * gets lists and opens UserDialog.
1141
 */
1142
void MainWindow::onUsers() {
×
1143
  QString dir =
1144
      m_currentDir.isEmpty()
1145
          ? Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel)
×
1146
          : m_currentDir;
×
1147

1148
  UsersDialog d(dir, this);
×
1149
  if (!d.exec()) {
×
1150
    ui->treeView->setFocus();
×
1151
  }
1152
}
×
1153

1154
/**
1155
 * @brief MainWindow::messageAvailable we have some text/message/search to do.
1156
 * @param message
1157
 */
1158
void MainWindow::messageAvailable(const QString &message) {
×
1159
  show();
×
1160
  raise();
×
1161
  if (message.isEmpty()) {
×
1162
    focusInput();
×
1163
  } else {
1164
    ui->treeView->expandAll();
×
1165
    ui->lineEdit->setText(message);
×
1166
    on_lineEdit_returnPressed();
×
1167
  }
1168
}
×
1169

1170
/**
1171
 * @brief MainWindow::generateKeyPair internal gpg keypair generator . .
1172
 * @param batch
1173
 * @param keygenWindow
1174
 */
1175
void MainWindow::generateKeyPair(const QString &batch, QDialog *keygenWindow) {
×
1176
  m_keygenDialog = keygenWindow;
×
1177
  emit generateGPGKeyPair(batch);
×
1178
}
×
1179

1180
/**
1181
 * @brief MainWindow::updateProfileBox update the list of profiles, optionally
1182
 * select a more appropriate one to view too
1183
 */
1184
void MainWindow::updateProfileBox() {
×
1185
  QHash<QString, QHash<QString, QString>> profiles =
1186
      QtPassSettings::getProfiles();
×
1187

1188
  if (profiles.isEmpty()) {
1189
    ui->profileWidget->hide();
×
1190
  } else {
1191
    ui->profileWidget->show();
×
1192
    ui->profileBox->setEnabled(profiles.size() > 1);
×
1193
    ui->profileBox->clear();
×
1194
    QHashIterator<QString, QHash<QString, QString>> i(profiles);
×
1195
    while (i.hasNext()) {
×
1196
      i.next();
1197
      if (!i.key().isEmpty()) {
×
1198
        ui->profileBox->addItem(i.key());
×
1199
      }
1200
    }
1201
    ui->profileBox->model()->sort(0);
×
1202
  }
1203
  int index = ui->profileBox->findText(QtPassSettings::getProfile());
×
1204
  if (index != -1) { //  -1 for not found
×
1205
    ui->profileBox->setCurrentIndex(index);
×
1206
  }
1207
}
×
1208

1209
/**
1210
 * @brief MainWindow::on_profileBox_currentIndexChanged make sure we show the
1211
 * correct "profile"
1212
 * @param name
1213
 */
1214
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
1215
void MainWindow::on_profileBox_currentIndexChanged(QString name) {
1216
#else
1217
/**
1218
 * @brief Handles changes to the selected profile in the profile combo box.
1219
 * @details Ignores the event during a fresh start or when the selected profile
1220
 * matches the current profile. Otherwise, it clears the password field, updates
1221
 * the active profile and related settings, refreshes the environment, and
1222
 * resets the tree view and action states to reflect the newly selected profile.
1223
 *
1224
 * @param name - The newly selected profile name.
1225
 * @return void - This function does not return a value.
1226
 *
1227
 */
1228
void MainWindow::on_profileBox_currentTextChanged(const QString &name) {
×
1229
#endif
1230
  if (m_qtPass->isFreshStart() || name == QtPassSettings::getProfile()) {
×
1231
    return;
×
1232
  }
1233

1234
  ui->lineEdit->clear();
×
1235

1236
  QtPassSettings::setProfile(name);
×
1237

1238
  QtPassSettings::setPassStore(
×
1239
      QtPassSettings::getProfiles().value(name).value("path"));
×
1240
  QtPassSettings::setPassSigningKey(
×
1241
      QtPassSettings::getProfiles().value(name).value("signingKey"));
×
1242
  ui->statusBar->showMessage(tr("Profile changed to %1").arg(name), 2000);
×
1243

1244
  QtPassSettings::getPass()->updateEnv();
×
1245

1246
  const QString passStore = QtPassSettings::getPassStore();
×
1247
  proxyModel.setStore(passStore);
×
1248
  ui->treeView->setRootIndex(
×
1249
      proxyModel.mapFromSource(model.setRootPath(passStore)));
×
1250
  deselect();
×
1251
  ui->treeView->setCurrentIndex(QModelIndex());
×
1252
}
1253

1254
/**
1255
 * @brief MainWindow::initTrayIcon show a nice tray icon on systems that
1256
 * support
1257
 * it
1258
 */
1259
void MainWindow::initTrayIcon() {
×
1260
  m_tray = new TrayIcon(this);
×
1261
  // Setup tray icon
1262

1263
  if (m_tray == nullptr) {
1264
#ifdef QT_DEBUG
1265
    dbg() << "Allocating tray icon failed.";
1266
#endif
1267
    return;
1268
  }
1269

1270
  if (!m_tray->getIsAllocated()) {
×
1271
    destroyTrayIcon();
×
1272
  }
1273
}
1274

1275
/**
1276
 * @brief MainWindow::destroyTrayIcon remove that pesky tray icon
1277
 */
1278
void MainWindow::destroyTrayIcon() {
×
1279
  delete m_tray;
×
1280
  m_tray = nullptr;
×
1281
}
×
1282

1283
/**
1284
 * @brief MainWindow::closeEvent hide or quit
1285
 * @param event
1286
 */
1287
void MainWindow::closeEvent(QCloseEvent *event) {
×
1288
  if (QtPassSettings::isHideOnClose()) {
×
1289
    this->hide();
×
1290
    event->ignore();
1291
  } else {
1292
    m_qtPass->clearClipboard();
×
1293

1294
    QtPassSettings::setGeometry(saveGeometry());
×
1295
    QtPassSettings::setSavestate(saveState());
×
1296
    QtPassSettings::setMaximized(isMaximized());
×
1297
    if (!isMaximized()) {
×
1298
      QtPassSettings::setPos(pos());
×
1299
      QtPassSettings::setSize(size());
×
1300
    }
1301
    event->accept();
1302
  }
1303
}
×
1304

1305
/**
1306
 * @brief MainWindow::eventFilter filter out some events and focus the
1307
 * treeview
1308
 * @param obj
1309
 * @param event
1310
 * @return
1311
 */
1312
auto MainWindow::eventFilter(QObject *obj, QEvent *event) -> bool {
×
1313
  if (obj == ui->lineEdit && event->type() == QEvent::KeyPress) {
×
1314
    auto *key = dynamic_cast<QKeyEvent *>(event);
×
1315
    if (key != nullptr && key->key() == Qt::Key_Down) {
×
1316
      ui->treeView->setFocus();
×
1317
    }
1318
  }
1319
  return QObject::eventFilter(obj, event);
×
1320
}
1321

1322
/**
1323
 * @brief MainWindow::keyPressEvent did anyone press return, enter or escape?
1324
 * @param event
1325
 */
1326
void MainWindow::keyPressEvent(QKeyEvent *event) {
×
1327
  switch (event->key()) {
×
1328
  case Qt::Key_Delete:
×
1329
    onDelete();
×
1330
    break;
×
1331
  case Qt::Key_Return:
×
1332
  case Qt::Key_Enter:
1333
    if (proxyModel.rowCount() > 0) {
×
1334
      on_treeView_clicked(ui->treeView->currentIndex());
×
1335
    }
1336
    break;
1337
  case Qt::Key_Escape:
×
1338
    ui->lineEdit->clear();
×
1339
    break;
×
1340
  default:
1341
    break;
1342
  }
1343
}
×
1344

1345
/**
1346
 * @brief MainWindow::showContextMenu show us the (file or folder) context
1347
 * menu
1348
 * @param pos
1349
 */
1350
void MainWindow::showContextMenu(const QPoint &pos) {
×
1351
  QModelIndex index = ui->treeView->indexAt(pos);
×
1352
  bool selected = true;
1353
  if (!index.isValid()) {
1354
    ui->treeView->clearSelection();
×
1355
    ui->actionDelete->setEnabled(false);
×
1356
    ui->actionEdit->setEnabled(false);
×
1357
    m_currentDir = "";
×
1358
    selected = false;
1359
  }
1360

1361
  ui->treeView->setCurrentIndex(index);
×
1362

1363
  QPoint globalPos = ui->treeView->viewport()->mapToGlobal(pos);
×
1364

1365
  QFileInfo fileOrFolder =
1366
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
1367

1368
  QMenu contextMenu;
×
1369
  if (!selected || fileOrFolder.isDir()) {
×
1370
    QAction *openFolder =
1371
        contextMenu.addAction(tr("Open folder with file manager"));
×
1372
    QAction *addFolder = contextMenu.addAction(tr("Add folder"));
×
1373
    QAction *addPassword = contextMenu.addAction(tr("Add password"));
×
1374
    QAction *users = contextMenu.addAction(tr("Users"));
×
1375
    connect(openFolder, &QAction::triggered, this, &MainWindow::openFolder);
×
1376
    connect(addFolder, &QAction::triggered, this, &MainWindow::addFolder);
×
1377
    connect(addPassword, &QAction::triggered, this, &MainWindow::addPassword);
×
1378
    connect(users, &QAction::triggered, this, &MainWindow::onUsers);
×
1379
  } else if (fileOrFolder.isFile()) {
×
1380
    QAction *edit = contextMenu.addAction(tr("Edit"));
×
1381
    connect(edit, &QAction::triggered, this, &MainWindow::onEdit);
×
1382
  }
1383
  if (selected) {
×
1384
    contextMenu.addSeparator();
×
1385
    if (fileOrFolder.isDir()) {
×
1386
      QAction *renameFolder = contextMenu.addAction(tr("Rename folder"));
×
1387
      connect(renameFolder, &QAction::triggered, this,
×
1388
              &MainWindow::renameFolder);
×
1389
    } else if (fileOrFolder.isFile()) {
×
1390
      QAction *renamePassword = contextMenu.addAction(tr("Rename password"));
×
1391
      connect(renamePassword, &QAction::triggered, this,
×
1392
              &MainWindow::renamePassword);
×
1393
    }
1394
    QAction *deleteItem = contextMenu.addAction(tr("Delete"));
×
1395
    connect(deleteItem, &QAction::triggered, this, &MainWindow::onDelete);
×
1396
    if (fileOrFolder.isDir()) {
×
1397
      QString dirPath = QDir::cleanPath(
1398
          Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel));
×
1399

1400
      auto *shareMenu = new QMenu(tr("Share"), &contextMenu);
×
1401
      contextMenu.addMenu(shareMenu);
×
1402

1403
      QString gpgIdPath = Pass::getGpgIdPath(dirPath);
×
1404
      bool gpgIdExists = !gpgIdPath.isEmpty() && QFile(gpgIdPath).exists();
×
1405

1406
      QString exePath = QtPassSettings::isUsePass()
×
1407
                            ? QtPassSettings::getPassExecutable()
×
1408
                            : QtPassSettings::getGpgExecutable();
×
1409
      bool gpgAvailable = !exePath.isEmpty() && (exePath.startsWith("wsl ") ||
×
1410
                                                 QFile(exePath).exists());
×
1411

1412
      QAction *reencrypt = shareMenu->addAction(tr("Re-encrypt all passwords"));
×
1413
      reencrypt->setEnabled(gpgIdExists && gpgAvailable);
×
1414
      connect(reencrypt, &QAction::triggered, this,
×
1415
              [this, dirPath]() { reencryptPath(dirPath); });
×
1416

1417
      QAction *exportKey = shareMenu->addAction(tr("Export my public key..."));
×
1418
      exportKey->setEnabled(gpgAvailable);
×
1419
      connect(exportKey, &QAction::triggered, this,
×
1420
              &MainWindow::exportPublicKey);
×
1421

1422
      QAction *addRecipientAction =
1423
          shareMenu->addAction(tr("Add recipient..."));
×
1424
      addRecipientAction->setEnabled(gpgIdExists && gpgAvailable);
×
1425
      connect(addRecipientAction, &QAction::triggered, this,
×
1426
              [this, dirPath]() { addRecipient(dirPath); });
×
1427

1428
      QAction *shareHelp = shareMenu->addAction(tr("What is this?"));
×
1429
      connect(shareHelp, &QAction::triggered, this, &MainWindow::showShareHelp);
×
1430
    }
1431
  }
1432
  contextMenu.exec(globalPos);
×
1433
}
×
1434

1435
/**
1436
 * @brief MainWindow::showBrowserContextMenu show us the context menu in
1437
 * password window
1438
 * @param pos
1439
 */
1440
void MainWindow::showBrowserContextMenu(const QPoint &pos) {
×
1441
  QMenu *contextMenu = ui->textBrowser->createStandardContextMenu(pos);
×
1442
  QPoint globalPos = ui->textBrowser->viewport()->mapToGlobal(pos);
×
1443

1444
  contextMenu->exec(globalPos);
×
1445
  delete contextMenu;
×
1446
}
×
1447

1448
/**
1449
 * @brief MainWindow::openFolder open the folder in the default file manager
1450
 */
1451
void MainWindow::openFolder() {
×
1452
  QString dir =
1453
      Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel);
×
1454

1455
  QString path = QDir::toNativeSeparators(dir);
×
1456
  QDesktopServices::openUrl(QUrl::fromLocalFile(path));
×
1457
}
×
1458

1459
/**
1460
 * @brief MainWindow::addFolder add a new folder to store passwords in
1461
 */
1462
void MainWindow::addFolder() {
×
1463
  bool ok;
1464
  QString dir =
1465
      Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel);
×
1466
  QString newdir =
1467
      QInputDialog::getText(this, tr("New file"),
×
1468
                            tr("New Folder: \n(Will be placed in %1 )")
×
1469
                                .arg(QtPassSettings::getPassStore() +
×
1470
                                     Util::getDir(ui->treeView->currentIndex(),
×
1471
                                                  true, model, proxyModel)),
1472
                            QLineEdit::Normal, "", &ok);
×
1473
  if (!ok || newdir.isEmpty()) {
×
1474
    return;
1475
  }
1476
  newdir.prepend(dir);
1477
  if (!QDir().mkdir(newdir)) {
×
1478
    QMessageBox::warning(this, tr("Error"),
×
1479
                         tr("Failed to create folder: %1").arg(newdir));
×
1480
    return;
×
1481
  }
1482
  if (QtPassSettings::isAddGPGId(true)) {
×
1483
    QString gpgIdFile = newdir + "/.gpg-id";
×
1484
    QFile gpgId(gpgIdFile);
×
1485
    if (!gpgId.open(QIODevice::WriteOnly)) {
×
1486
      QMessageBox::warning(
×
1487
          this, tr("Error"),
×
1488
          tr("Failed to create .gpg-id file in: %1").arg(newdir));
×
1489
      return;
1490
    }
1491
    QList<UserInfo> users = QtPassSettings::getPass()->listKeys("", true);
×
1492
    for (const UserInfo &user : users) {
×
1493
      if (user.enabled) {
×
1494
        gpgId.write((user.key_id + "\n").toUtf8());
×
1495
      }
1496
    }
1497
    gpgId.close();
×
1498
    // Lock to owner-only access; see ImitatePass::writeGpgIdFile for
1499
    // rationale (NFS / USB / unusual umask scenarios). Best-effort on
1500
    // platforms where setPermissions is a no-op.
NEW
1501
    QFile::setPermissions(gpgIdFile, QFile::ReadOwner | QFile::WriteOwner);
×
1502
  }
×
1503
}
1504

1505
/**
1506
 * @brief MainWindow::renameFolder rename an existing folder
1507
 */
1508
void MainWindow::renameFolder() {
×
1509
  bool ok;
1510
  QString srcDir = QDir::cleanPath(
1511
      Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel));
×
1512
  QString srcDirName = QDir(srcDir).dirName();
×
1513
  QString newName =
1514
      QInputDialog::getText(this, tr("Rename file"), tr("Rename Folder To: "),
×
1515
                            QLineEdit::Normal, srcDirName, &ok);
×
1516
  if (!ok || newName.isEmpty()) {
×
1517
    return;
1518
  }
1519
  QString destDir = srcDir;
1520
  destDir.replace(srcDir.lastIndexOf(srcDirName), srcDirName.length(), newName);
×
1521
  QtPassSettings::getPass()->Move(srcDir, destDir);
×
1522
}
1523

1524
/**
1525
 * @brief MainWindow::editPassword read password and open edit window via
1526
 * MainWindow::onEdit()
1527
 */
1528
void MainWindow::editPassword(const QString &file) {
×
1529
  if (!file.isEmpty()) {
×
1530
    if (QtPassSettings::isUseGit() && QtPassSettings::isAutoPull()) {
×
1531
      onUpdate(true);
×
1532
    }
1533
    setPassword(file, false);
×
1534
  }
1535
}
×
1536

1537
/**
1538
 * @brief MainWindow::renamePassword rename an existing password
1539
 */
1540
void MainWindow::renamePassword() {
×
1541
  bool ok;
1542
  QString file = getFile(ui->treeView->currentIndex(), false);
×
1543
  QString filePath = QFileInfo(file).path();
×
1544
  QString fileName = QFileInfo(file).fileName();
×
1545
  if (fileName.endsWith(".gpg", Qt::CaseInsensitive)) {
×
1546
    fileName.chop(4);
×
1547
  }
1548

1549
  QString newName =
1550
      QInputDialog::getText(this, tr("Rename file"), tr("Rename File To: "),
×
1551
                            QLineEdit::Normal, fileName, &ok);
×
1552
  if (!ok || newName.isEmpty()) {
×
1553
    return;
1554
  }
1555
  QString newFile = QDir(filePath).filePath(newName);
×
1556
  QtPassSettings::getPass()->Move(file, newFile);
×
1557
}
1558

1559
/**
1560
 * @brief MainWindow::clearTemplateWidgets empty the template widget fields in
1561
 * the UI
1562
 */
1563
void MainWindow::clearTemplateWidgets() {
×
1564
  while (ui->gridLayout->count() > 0) {
×
1565
    QLayoutItem *item = ui->gridLayout->takeAt(0);
×
1566
    delete item->widget();
×
1567
    delete item;
×
1568
  }
1569
  ui->verticalLayoutPassword->setSpacing(0);
×
1570
}
×
1571

1572
/**
1573
 * @brief Copies the password of the selected file from the tree view to the
1574
 * clipboard.
1575
 * @example
1576
 * MainWindow::copyPasswordFromTreeview();
1577
 *
1578
 * @return void - This function does not return a value.
1579
 */
1580
void MainWindow::copyPasswordFromTreeview() {
×
1581
  QFileInfo fileOrFolder =
1582
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
1583

1584
  if (fileOrFolder.isFile()) {
×
1585
    QString file = getFile(ui->treeView->currentIndex(), true);
×
1586
    // Disconnect any previous connection to avoid accumulation
1587
    disconnect(QtPassSettings::getPass(), &Pass::finishedShow, this,
×
1588
               &MainWindow::passwordFromFileToClipboard);
1589
    connect(QtPassSettings::getPass(), &Pass::finishedShow, this,
×
1590
            &MainWindow::passwordFromFileToClipboard);
×
1591
    QtPassSettings::getPass()->Show(file);
×
1592
  }
1593
}
×
1594

1595
void MainWindow::passwordFromFileToClipboard(const QString &text) {
×
1596
  QStringList tokens = text.split('\n');
×
1597
  m_qtPass->copyTextToClipboard(tokens[0]);
×
1598
}
×
1599

1600
/**
1601
 * @brief MainWindow::addToGridLayout add a field to the template grid
1602
 * @param position
1603
 * @param field
1604
 * @param value
1605
 */
1606
void MainWindow::addToGridLayout(int position, const QString &field,
×
1607
                                 const QString &value) {
1608
  QString trimmedField = field.trimmed();
1609
  QString trimmedValue = value.trimmed();
1610

1611
  const QString buttonStyle =
1612
      "border-style: none; background: transparent; padding: 0; margin: 0; "
1613
      "icon-size: 16px; color: inherit;";
×
1614

1615
  // Combine the Copy button and the line edit in one widget
1616
  auto *frame = new QFrame();
×
1617
  QLayout *ly = new QHBoxLayout();
×
1618
  ly->setContentsMargins(5, 2, 2, 2);
×
1619
  ly->setSpacing(0);
×
1620
  frame->setLayout(ly);
×
1621
  if (QtPassSettings::getClipBoardType() != Enums::CLIPBOARD_NEVER) {
×
1622
    auto *fieldLabel = new QPushButtonWithClipboard(trimmedValue, this);
×
1623
    connect(fieldLabel, &QPushButtonWithClipboard::clicked, m_qtPass,
×
1624
            &QtPass::copyTextToClipboard);
×
1625

1626
    fieldLabel->setStyleSheet(buttonStyle);
×
1627
    frame->layout()->addWidget(fieldLabel);
×
1628
  }
1629

1630
  if (QtPassSettings::isUseQrencode()) {
×
1631
    auto *qrbutton = new QPushButtonAsQRCode(trimmedValue, this);
×
1632
    connect(qrbutton, &QPushButtonAsQRCode::clicked, m_qtPass,
×
1633
            &QtPass::showTextAsQRCode);
×
1634
    qrbutton->setStyleSheet(buttonStyle);
×
1635
    frame->layout()->addWidget(qrbutton);
×
1636
  }
1637

1638
  // set the echo mode to password, if the field is "password"
1639
  const QString lineStyle =
1640
      QtPassSettings::isUseMonospace()
×
1641
          ? "border-style: none; background: transparent; font-family: "
1642
            "monospace;"
1643
          : "border-style: none; background: transparent;";
×
1644

1645
  if (QtPassSettings::isHidePassword() && trimmedField == tr("Password")) {
×
1646
    auto *line = new QLineEdit();
×
1647
    line->setObjectName(trimmedField);
×
1648
    line->setText(trimmedValue);
×
1649
    line->setReadOnly(true);
×
1650
    line->setStyleSheet(lineStyle);
×
1651
    line->setContentsMargins(0, 0, 0, 0);
×
1652
    line->setEchoMode(QLineEdit::Password);
×
1653
    auto *showButton = new QPushButtonShowPassword(line, this);
×
1654
    showButton->setStyleSheet(buttonStyle);
×
1655
    showButton->setContentsMargins(0, 0, 0, 0);
×
1656
    frame->layout()->addWidget(showButton);
×
1657
    frame->layout()->addWidget(line);
×
1658
  } else {
1659
    auto *line = new QTextBrowser();
×
1660
    line->setOpenExternalLinks(true);
×
1661
    line->setOpenLinks(true);
×
1662
    line->setMaximumHeight(26);
×
1663
    line->setMinimumHeight(26);
×
1664
    line->setSizePolicy(
×
1665
        QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum));
1666
    line->setObjectName(trimmedField);
×
1667
    trimmedValue.replace(Util::protocolRegex(), R"(<a href="\1">\1</a>)");
×
1668
    line->setText(trimmedValue);
×
1669
    line->setReadOnly(true);
×
1670
    line->setStyleSheet(lineStyle);
×
1671
    line->setContentsMargins(0, 0, 0, 0);
×
1672
    frame->layout()->addWidget(line);
×
1673
  }
1674

1675
  frame->setStyleSheet(
×
1676
      ".QFrame{border: 1px solid lightgrey; border-radius: 5px;}");
1677

1678
  // set into the layout
1679
  ui->gridLayout->addWidget(new QLabel(trimmedField), position, 0);
×
1680
  ui->gridLayout->addWidget(frame, position, 1);
×
1681
}
×
1682

1683
/**
1684
 * @brief Displays message in status bar
1685
 *
1686
 * @param msg     text to be displayed
1687
 * @param timeout time for which msg shall be visible
1688
 */
1689
void MainWindow::showStatusMessage(const QString &msg, int timeout) {
×
1690
  ui->statusBar->showMessage(msg, timeout);
×
1691
}
×
1692

1693
/**
1694
 * @brief MainWindow::reencryptPath re-encrypt all passwords in a directory
1695
 * @param dir Directory path to re-encrypt
1696
 */
1697
void MainWindow::reencryptPath(const QString &dir) {
×
1698
  QDir checkDir(dir);
×
1699
  if (!checkDir.exists()) {
×
1700
    QMessageBox::critical(this, tr("Error"),
×
1701
                          tr("Directory does not exist: %1").arg(dir));
×
1702
    return;
×
1703
  }
1704

1705
  int ret = QMessageBox::question(
×
1706
      this, tr("Re-encrypt passwords"),
×
1707
      tr("Re-encrypt all passwords in %1?\n\n"
×
1708
         "This will re-encrypt ALL password files in this folder "
1709
         "using the current recipients defined in .gpg-id.\n\n"
1710
         "This may rewrite many files and cannot be undone easily.\n\n"
1711
         "Continue?")
1712
          .arg(QDir(dir).dirName()),
×
1713
      QMessageBox::Yes | QMessageBox::No);
1714

1715
  if (ret != QMessageBox::Yes)
×
1716
    return;
1717

1718
  // Disable preemptively. ImitatePass::reencryptPath emits
1719
  // startReencryptPath asynchronously and the slot would re-run this,
1720
  // but setEnabled(false) is idempotent so the duplicate is harmless.
1721
  startReencryptPath();
×
1722

1723
  QtPassSettings::getImitatePass()->reencryptPath(
×
1724
      QDir::cleanPath(QDir(dir).absolutePath()));
×
1725
}
×
1726

1727
/**
1728
 * @brief MainWindow::startReencryptPath disable ui elements and treeview
1729
 */
1730
void MainWindow::startReencryptPath() {
×
1731
  setUiElementsEnabled(false);
×
1732
  ui->treeView->setDisabled(true);
×
1733
}
×
1734

1735
/**
1736
 * @brief MainWindow::endReencryptPath re-enable ui elements
1737
 */
1738
void MainWindow::endReencryptPath() { setUiElementsEnabled(true); }
×
1739

1740
/**
1741
 * @brief MainWindow::exportPublicKey export the configured signing key in
1742
 *        ASCII-armored form via gpg and show it in ExportPublicKeyDialog.
1743
 *
1744
 * Falls back to a help dialog when no signing key is configured or gpg is
1745
 * unavailable, so the user still gets actionable guidance.
1746
 */
1747
void MainWindow::exportPublicKey() {
×
1748
  QString identity = QtPassSettings::getPassSigningKey();
×
1749
  if (identity.isEmpty()) {
×
1750
    QMessageBox::information(
×
1751
        this, tr("Export Public Key"),
×
1752
        tr("<h3>Export Your Public Key</h3>"
×
1753
           "<p>No signing key is configured. Set one in QtPass Settings "
1754
           "&gt; GPG keys, or run this in a terminal:</p>"
1755
           "<pre>gpg --armor --export --output my_key.asc &lt;your-key-id"
1756
           "&gt;</pre>"
1757
           "<p>Then send the file to your teammates.</p>"));
1758
    return;
×
1759
  }
1760
  QString gpgExe = QtPassSettings::getGpgExecutable();
×
1761
  if (gpgExe.isEmpty()) {
×
1762
    gpgExe = QStringLiteral("gpg");
×
1763
  }
1764
  QStringList args = {"--armor", "--export"};
×
1765
  args.append(identity.split(' ', Qt::SkipEmptyParts));
×
1766
  QString stdOut;
×
1767
  QString stdErr;
×
1768
  int exitCode =
1769
      Executor::executeBlocking(gpgExe, args, QString(), &stdOut, &stdErr);
×
1770
  if (exitCode != 0 || stdOut.isEmpty()) {
×
1771
    QMessageBox::warning(this, tr("Export Public Key"),
×
1772
                         tr("Could not export public key for %1.\n\n%2")
×
1773
                             .arg(identity, stdErr.isEmpty()
×
1774
                                                ? tr("No output from gpg.")
×
1775
                                                : stdErr));
1776
    return;
1777
  }
1778
  ExportPublicKeyDialog dialog(identity, stdOut, this);
×
1779
  dialog.exec();
×
1780
}
×
1781

1782
/**
1783
 * @brief MainWindow::addRecipient open the recipient management dialog for
1784
 *        the supplied directory.
1785
 * @param dir Folder whose .gpg-id should be edited.
1786
 *
1787
 * Delegates to UsersDialog so users can tick/untick keys from their
1788
 * keyring as recipients of the folder; importing a foreign key into the
1789
 * keyring still has to happen via gpg (or QtPass settings) first.
1790
 */
1791
void MainWindow::addRecipient(const QString &dir) {
×
1792
  UsersDialog d(dir, this);
×
1793
  d.exec();
×
1794
}
×
1795

1796
/**
1797
 * @brief MainWindow::showShareHelp show help about GPG sharing
1798
 */
1799
void MainWindow::showShareHelp() {
×
1800
  QMessageBox::information(
×
1801
      this, tr("Sharing Passwords with GPG"),
×
1802
      tr("<h3>Sharing Passwords with GPG</h3>"
×
1803
         "<p>To share passwords with other users:</p>"
1804
         "<ol>"
1805
         "<li><b>Export your public key</b> and send it to teammates</li>"
1806
         "<li><b>Import teammates' public keys</b> into your GPG keyring</li>"
1807
         "<li><b>Re-encrypt passwords</b> so all recipients can decrypt "
1808
         "them</li>"
1809
         "</ol>"
1810
         "<p>Only people who have a matching secret key can decrypt the "
1811
         "passwords.</p>"
1812
         "<p><b>Tip:</b> Use the same GPG key for all shared folders.</p>"
1813
         "<p>See the FAQ for more details.</p>"));
1814
}
×
1815

1816
void MainWindow::updateGitButtonVisibility() {
×
1817
  if (!QtPassSettings::isUseGit() ||
×
1818
      (QtPassSettings::getGitExecutable().isEmpty() &&
×
1819
       QtPassSettings::getPassExecutable().isEmpty())) {
×
1820
    enableGitButtons(false);
×
1821
  } else {
1822
    enableGitButtons(true);
×
1823
  }
1824
}
×
1825

1826
void MainWindow::updateOtpButtonVisibility() {
×
1827
#if defined(Q_OS_WIN) || defined(__APPLE__)
1828
  ui->actionOtp->setVisible(false);
1829
#endif
1830
  if (!QtPassSettings::isUseOtp()) {
×
1831
    ui->actionOtp->setEnabled(false);
×
1832
  } else {
1833
    ui->actionOtp->setEnabled(true);
×
1834
  }
1835
}
×
1836

1837
void MainWindow::updateGrepButtonVisibility() {
×
1838
  const bool enabled = QtPassSettings::isUseGrepSearch();
×
1839
  ui->grepButton->setVisible(enabled);
×
1840
  ui->grepCaseButton->setVisible(enabled);
×
1841
  if (!enabled && m_grepMode) {
×
1842
    ui->grepButton->setChecked(false);
×
1843
  }
1844
}
×
1845

1846
void MainWindow::enableGitButtons(const bool &state) {
×
1847
  // Following GNOME guidelines is preferable disable buttons instead of hide
1848
  ui->actionPush->setEnabled(state);
×
1849
  ui->actionUpdate->setEnabled(state);
×
1850
}
×
1851

1852
/**
1853
 * @brief MainWindow::critical critical message popup wrapper.
1854
 * @param title
1855
 * @param msg
1856
 */
1857
void MainWindow::critical(const QString &title, const QString &msg) {
×
1858
  QMessageBox::critical(this, title, msg);
×
1859
}
×
1860

1861
/**
1862
 * @brief Appends processed command output to the output panel.
1863
 *
1864
 * Appends text to the process output text edit, with per-line numbering,
1865
 * optional command prefix, and color coding for errors vs. success.
1866
 * Handles auto-scrolling and line limits.
1867
 *
1868
 * @param output The raw output text from the command.
1869
 * @param isError true if this is error output (stderr).
1870
 * @param linePrefix Optional command name to prefix each line with.
1871
 */
1872
void MainWindow::appendProcessOutput(const QString &output, bool isError,
×
1873
                                     const QString &linePrefix) {
1874
  if (!QtPassSettings::isShowProcessOutput()) {
×
1875
    return;
×
1876
  }
1877

1878
  QStringList lines = output.split('\n', Qt::SkipEmptyParts);
×
1879
  for (QString &line : lines) {
×
1880
    // Right-trim only: remove trailing CR and whitespace, preserve leading
1881
    // indentation
1882
    line.remove('\r');
×
1883
    while (!line.isEmpty() && line.back().isSpace()) {
×
1884
      line.chop(1);
×
1885
    }
1886
    if (line.isEmpty()) {
×
1887
      continue;
×
1888
    }
1889

1890
    m_outputCounter++;
×
1891
    QString lineNumber = QString::number(m_outputCounter);
×
1892

1893
    QColor textColor =
1894
        isError ? QColor(Qt::red)
×
1895
                : m_processOutputEdit->palette().color(QPalette::Text);
×
1896
    QString colorHex = textColor.name();
×
1897
    // Apply the optional prefix per line so multi-line output stays
1898
    // attributed to its command (e.g. all 3 lines of a `git push` show
1899
    // "git push: ..." rather than only the first).
1900
    QString prefixed =
1901
        linePrefix.isEmpty() ? line : linePrefix + QStringLiteral(": ") + line;
×
1902
    QString coloredOutput =
1903
        QString("<span style=\"color: %1;\">%2: %3</span>")
×
1904
            .arg(colorHex, lineNumber, prefixed.toHtmlEscaped());
×
1905

1906
    m_processOutputEdit->append(coloredOutput);
×
1907
  }
1908

1909
  limitOutputLines();
×
1910

1911
  if (m_autoScroll) {
×
1912
    m_processOutputEdit->verticalScrollBar()->setValue(
×
1913
        m_processOutputEdit->verticalScrollBar()->maximum());
×
1914
  }
1915
}
1916

1917
/**
1918
 * @brief Handles process output from the Pass executor.
1919
 *
1920
 * Called when any non-sensitive process completes. Filters out password-
1921
 * related commands (pass show, insert, etc.) and delegates to
1922
 * appendProcessOutput.
1923
 *
1924
 * @param output The stdout/stderr text from the process.
1925
 * @param isError true if this is error output (stderr).
1926
 * @param pid The process ID identifying which command ran.
1927
 */
1928
void MainWindow::onProcessOutput(const QString &output, bool isError,
×
1929
                                 Enums::PROCESS pid) {
1930
  appendProcessOutput(output, isError, getProcessName(pid));
×
1931
}
×
1932

1933
/**
1934
 * @brief Maps a process ID to its human-readable command name.
1935
 *
1936
 * Returns static strings for git/pass commands that appear in output.
1937
 * Password-related commands return empty (they are filtered).
1938
 *
1939
 * @param pid The process ID to look up.
1940
 * @return QString with command name, or empty if filtered.
1941
 */
1942
auto MainWindow::getProcessName(Enums::PROCESS pid) -> QString {
×
1943
  switch (pid) {
×
1944
  case Enums::GIT_INIT:
×
1945
    return QStringLiteral("git init"); // no-tr
×
1946
  case Enums::GIT_ADD:
×
1947
    return QStringLiteral("git add"); // no-tr
×
1948
  case Enums::GIT_COMMIT:
×
1949
    return QStringLiteral("git commit"); // no-tr
×
1950
  case Enums::GIT_RM:
×
1951
    return QStringLiteral("git rm"); // no-tr
×
1952
  case Enums::GIT_PULL:
×
1953
    return QStringLiteral("git pull"); // no-tr
×
1954
  case Enums::GIT_PUSH:
×
1955
    return QStringLiteral("git push"); // no-tr
×
1956
  case Enums::GIT_MOVE:
×
1957
    return QStringLiteral("git mv"); // no-tr
×
1958
  case Enums::GIT_COPY:
×
1959
    // ImitatePass::Copy literally invokes `git cp` (a git-extras
1960
    // subcommand), so the label matches what's run. Stock-git users
1961
    // without git-extras will see the underlying "'cp' is not a git
1962
    // command" failure surfaced in the process output panel.
1963
    return QStringLiteral("git cp"); // no-tr
×
1964
  case Enums::PASS_INSERT:
×
1965
    return QStringLiteral("pass insert"); // no-tr
×
1966
  case Enums::PASS_REMOVE:
×
1967
    return QStringLiteral("pass rm"); // no-tr
×
1968
  case Enums::PASS_INIT:
×
1969
    return QStringLiteral("pass init"); // no-tr
×
1970
  case Enums::PASS_MOVE:
×
1971
    return QStringLiteral("pass mv"); // no-tr
×
1972
  case Enums::PASS_COPY:
×
1973
    return QStringLiteral("pass cp"); // no-tr
×
1974
  case Enums::PASS_GREP:
×
1975
    return QStringLiteral("pass grep"); // no-tr
×
1976
  case Enums::GPG_GENKEYS:
×
1977
    return QStringLiteral("gpg --gen-key"); // no-tr
×
1978
  case Enums::PASS_SHOW:
1979
  case Enums::PASS_OTP_GENERATE:
1980
  case Enums::PROCESS_COUNT:
1981
  case Enums::INVALID:
1982
    break;
1983
  }
1984
  return {};
1985
}
1986

1987
/**
1988
 * @brief Checks if a process ID represents a sensitive operation whose
1989
 * output should not be shown in the process output panel.
1990
 *
1991
 * Password-related commands (pass show, OTP generate, grep, insert)
1992
 * display their output in other UI areas, so we skip them here.
1993
 *
1994
 * @param pid The process ID to check.
1995
 * @return true if the process is sensitive and should be filtered.
1996
 */
1997
auto MainWindow::isSensitiveProcess(Enums::PROCESS pid) -> bool {
×
1998
  switch (pid) {
×
1999
  case Enums::PASS_SHOW:
2000
  case Enums::PASS_OTP_GENERATE:
2001
  case Enums::PASS_GREP:
2002
  case Enums::PASS_INSERT:
2003
    return true;
2004
  case Enums::GIT_INIT:
2005
  case Enums::GIT_ADD:
2006
  case Enums::GIT_COMMIT:
2007
  case Enums::GIT_RM:
2008
  case Enums::GIT_PULL:
2009
  case Enums::GIT_PUSH:
2010
  case Enums::GIT_MOVE:
2011
  case Enums::GIT_COPY:
2012
  case Enums::PASS_REMOVE:
2013
  case Enums::PASS_INIT:
2014
  case Enums::PASS_MOVE:
2015
  case Enums::PASS_COPY:
2016
  case Enums::GPG_GENKEYS:
2017
  case Enums::PROCESS_COUNT:
2018
  case Enums::INVALID:
2019
    break;
2020
  }
2021
  return false;
×
2022
}
2023

2024
/**
2025
 * @brief Updates the visibility of the process output panel.
2026
 *
2027
 * Shows or hides the process output widget based on the user's
2028
 * showProcessOutput setting.
2029
 */
2030
void MainWindow::updateProcessOutputVisibility() {
×
2031
  m_processOutputDock->setVisible(QtPassSettings::isShowProcessOutput());
×
2032
}
×
2033

2034
/**
2035
 * @brief Limits the output panel to max lines, trimming old excess.
2036
 *
2037
 * Removes the oldest lines when the document exceeds MaxOutputLines (1000).
2038
 * Called after each append to prevent unbounded growth.
2039
 */
2040
void MainWindow::limitOutputLines() {
×
2041
  QTextDocument *doc = m_processOutputEdit->document();
×
2042
  int excess = doc->blockCount() - MaxOutputLines;
×
2043
  if (excess <= 0) {
×
2044
    return;
×
2045
  }
2046

2047
  QTextCursor cursor(doc);
×
2048
  cursor.movePosition(QTextCursor::Start);
×
2049
  cursor.movePosition(QTextCursor::NextBlock, QTextCursor::KeepAnchor, excess);
×
2050
  cursor.removeSelectedText();
×
2051
}
×
2052

2053
/**
2054
 * @brief Clears the process output panel.
2055
 *
2056
 * Clears all output, resets the line counter, and re-enables auto-scroll.
2057
 */
2058
void MainWindow::on_clearOutputButton_clicked() {
×
2059
  m_processOutputEdit->clear();
×
2060
  m_outputCounter = 0;
×
2061
  m_autoScroll = true;
×
2062
}
×
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