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

IJHack / QtPass / 24966775936

26 Apr 2026 08:52PM UTC coverage: 27.593%. Remained the same
24966775936

push

github

web-flow
fix: only set m_initialShowDone after focusInput actually focuses (#1191)

`showEvent` was eagerly setting `m_initialShowDone = true` *before*
queuing focusInput. If the queued slot then took an early-return
branch (window not visible, or the cached lineEdit lookup returned
nullptr because of a mid-init widget rebuild), the one-shot was
consumed and the focus pulse would never retry on the next show.

Move the latch inside focusInput, set only after the selectAll() +
setFocus() actually run. A transient failed lookup now leaves
`m_initialShowDone` false and the next showEvent re-queues the
attempt.

0 of 1 new or added line in 1 file covered. (0.0%)

1 existing line in 1 file now uncovered.

1825 of 6614 relevant lines covered (27.59%)

26.92 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 <QFileInfo>
30
#include <QInputDialog>
31
#include <QLabel>
32
#include <QLineEdit>
33
#include <QMenu>
34
#include <QMessageBox>
35
#include <QScrollBar>
36
#include <QShortcut>
37
#include <QTextCursor>
38
#include <QTimer>
39
#include <QTreeWidget>
40
#include <utility>
41

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

57
  m_qtPass = new QtPass(this);
×
58

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

65
  model.setNameFilters(QStringList() << "*.gpg");
×
66
  model.setNameFilterDisables(false);
×
67

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

75
  QString passStore = QtPassSettings::getPassStore(Util::findPasswordStore());
×
76

77
  QModelIndex rootDir = model.setRootPath(passStore);
×
78
  model.fetchMore(rootDir);
×
79

80
  proxyModel.setModelAndStore(&model, passStore);
×
81
  selectionModel.reset(new QItemSelectionModel(&proxyModel));
×
82

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

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

112
  updateProfileBox();
×
113

114
  QtPassSettings::getPass()->updateEnv();
×
115
  clearPanelTimer.setInterval(MS_PER_SECOND *
×
116
                              QtPassSettings::getAutoclearPanelSeconds());
×
117
  clearPanelTimer.setSingleShot(true);
×
118
  connect(&clearPanelTimer, &QTimer::timeout, this, [this]() { clearPanel(); });
×
119

120
  searchTimer.setInterval(350);
×
121
  searchTimer.setSingleShot(true);
×
122

123
  connect(&searchTimer, &QTimer::timeout, this, &MainWindow::onTimeoutSearch);
×
124

125
  initToolBarButtons();
×
126
  initStatusBar();
×
127

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

149
  connect(ui->processOutputEdit->verticalScrollBar(),
×
150
          &QScrollBar::sliderPressed, this, [this]() {
×
151
            auto *sb = ui->processOutputEdit->verticalScrollBar();
×
152
            m_autoScroll = sb->value() >= sb->maximum();
×
153
          });
×
154
  connect(ui->processOutputEdit->verticalScrollBar(), &QScrollBar::valueChanged,
×
155
          this, [this]() {
×
156
            auto *sb = ui->processOutputEdit->verticalScrollBar();
×
157
            m_autoScroll = sb->value() >= sb->maximum();
×
158
          });
×
159

160
  ui->lineEdit->setClearButtonEnabled(true);
×
161
  updateGrepButtonVisibility();
×
162

163
  setUiElementsEnabled(true);
×
164

165
  ui->lineEdit->setText(searchText);
×
166

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

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

182
MainWindow::~MainWindow() { delete m_qtPass; }
×
183

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

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

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

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

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

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

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

307
  statusBar()->addPermanentWidget(ui->processOutputWidget);
×
308

309
  updateProcessOutputVisibility();
×
310
}
×
311

312
auto MainWindow::getCurrentTreeViewIndex() -> QModelIndex {
×
313
  return ui->treeView->currentIndex();
×
314
}
315

316
void MainWindow::cleanKeygenDialog() {
×
317
  if (this->keygenDialog != nullptr) {
×
318
    this->keygenDialog->close();
×
319
  }
320
  this->keygenDialog = nullptr;
×
321
}
×
322

323
/**
324
 * @brief Displays the given text in the main window text browser, optionally
325
 * marking it as an error and/or rendering it as HTML.
326
 * @example
327
 * MainWindow window;
328
 * window.flashText("Operation completed.", false, false);
329
 *
330
 * @param const QString &text - The text content to display.
331
 * @param const bool isError - If true, sets the text color to red before
332
 * displaying the text.
333
 * @param const bool isHtml - If true, treats the text as HTML and appends it to
334
 * the existing HTML content.
335
 * @return void - No return value.
336
 */
337
void MainWindow::flashText(const QString &text, const bool isError,
×
338
                           const bool isHtml) {
339
  if (isError) {
×
340
    ui->textBrowser->setTextColor(Qt::red);
×
341
  }
342

343
  if (isHtml) {
×
344
    QString _text = text;
345
    if (!ui->textBrowser->toPlainText().isEmpty()) {
×
346
      _text = ui->textBrowser->toHtml() + _text;
×
347
    }
348
    ui->textBrowser->setHtml(_text);
×
349
  } else {
350
    ui->textBrowser->setText(text);
×
351
  }
352
}
×
353

354
/**
355
 * @brief MainWindow::config pops up the configuration screen and handles all
356
 * inter-window communication
357
 */
358
void MainWindow::applyTextBrowserSettings() {
×
359
  if (QtPassSettings::isUseMonospace()) {
×
360
    QFont monospace("Monospace");
×
361
    monospace.setStyleHint(QFont::Monospace);
×
362
    ui->textBrowser->setFont(monospace);
×
363
  } else {
×
364
    ui->textBrowser->setFont(QFont());
×
365
  }
366

367
  if (QtPassSettings::isNoLineWrapping()) {
×
368
    ui->textBrowser->setLineWrapMode(QTextBrowser::NoWrap);
×
369
  } else {
370
    ui->textBrowser->setLineWrapMode(QTextBrowser::WidgetWidth);
×
371
  }
372
}
×
373

374
void MainWindow::applyWindowFlagsSettings() {
×
375
  if (QtPassSettings::isAlwaysOnTop()) {
×
376
    Qt::WindowFlags flags = windowFlags();
377
    this->setWindowFlags(flags | Qt::WindowStaysOnTopHint);
×
378
  } else {
379
    this->setWindowFlags(Qt::Window);
×
380
  }
381
  this->show();
×
382
}
×
383

384
/**
385
 * @brief Opens and processes the application configuration dialog, then applies
386
 * any accepted settings.
387
 * @example
388
 * config();
389
 *
390
 * @return void - This function does not return a value.
391
 */
392
void MainWindow::config() {
×
393
  QScopedPointer<ConfigDialog> d(new ConfigDialog(this));
×
394
  d->setModal(true);
×
395
  // Automatically default to pass if it's available
396
  if (m_qtPass->isFreshStart() &&
×
397
      QFile(QtPassSettings::getPassExecutable()).exists()) {
×
398
    QtPassSettings::setUsePass(true);
×
399
  }
400

401
  if (m_qtPass->isFreshStart()) {
×
402
    d->wizard(); // run initial setup wizard for first-time configuration
×
403
  }
404
  if (d->exec()) {
×
405
    if (d->result() == QDialog::Accepted) {
×
406
      applyTextBrowserSettings();
×
407
      applyWindowFlagsSettings();
×
408

409
      updateProfileBox();
×
410
      const QString passStore = QtPassSettings::getPassStore();
×
411
      proxyModel.setStore(passStore);
×
412
      ui->treeView->setRootIndex(
×
413
          proxyModel.mapFromSource(model.setRootPath(passStore)));
×
414
      deselect();
×
415
      ui->treeView->setCurrentIndex(QModelIndex());
×
416

417
      if (m_qtPass->isFreshStart() && !Util::configIsValid()) {
×
418
        config();
×
419
      }
420
      QtPassSettings::getPass()->updateEnv();
×
421
      clearPanelTimer.setInterval(MS_PER_SECOND *
×
422
                                  QtPassSettings::getAutoclearPanelSeconds());
×
423
      m_qtPass->setClipboardTimer();
×
424

425
      updateGitButtonVisibility();
×
426
      updateOtpButtonVisibility();
×
427
      updateGrepButtonVisibility();
×
428
      updateProcessOutputVisibility();
×
429
      if (QtPassSettings::isUseTrayIcon() && tray == nullptr) {
×
430
        initTrayIcon();
×
431
      } else if (!QtPassSettings::isUseTrayIcon() && tray != nullptr) {
×
432
        destroyTrayIcon();
×
433
      }
434
    }
435

436
    m_qtPass->setFreshStart(false);
×
437
  }
438
}
×
439

440
/**
441
 * @brief MainWindow::onUpdate do a git pull
442
 */
443
void MainWindow::onUpdate(bool block) {
×
444
  ui->statusBar->showMessage(tr("Updating password-store"), 2000);
×
445
  if (block) {
×
446
    QtPassSettings::getPass()->GitPull_b();
×
447
  } else {
448
    QtPassSettings::getPass()->GitPull();
×
449
  }
450
}
×
451

452
/**
453
 * @brief MainWindow::onPush do a git push
454
 */
455
void MainWindow::onPush() {
×
456
  if (QtPassSettings::isUseGit()) {
×
457
    ui->statusBar->showMessage(tr("Updating password-store"), 2000);
×
458
    QtPassSettings::getPass()->GitPush();
×
459
  }
460
}
×
461

462
/**
463
 * @brief MainWindow::getFile get the selected file path
464
 * @param index
465
 * @param forPass returns relative path without '.gpg' extension
466
 * @return path
467
 * @return
468
 */
469
auto MainWindow::getFile(const QModelIndex &index, bool forPass) -> QString {
×
470
  if (!index.isValid() ||
×
471
      !model.fileInfo(proxyModel.mapToSource(index)).isFile()) {
×
472
    return {};
473
  }
474
  QString filePath = model.filePath(proxyModel.mapToSource(index));
×
475
  if (forPass) {
×
476
    filePath = QDir(QtPassSettings::getPassStore()).relativeFilePath(filePath);
×
477
    filePath.replace(Util::endsWithGpg(), "");
×
478
  }
479
  return filePath;
480
}
481

482
/**
483
 * @brief MainWindow::on_treeView_clicked read the selected password file
484
 * @param index
485
 */
486
void MainWindow::on_treeView_clicked(const QModelIndex &index) {
×
487
  bool cleared = ui->treeView->currentIndex().flags() == Qt::NoItemFlags;
×
488
  currentDir =
489
      Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel);
×
490
  // Clear any previously cached clipped text before showing new password
491
  m_qtPass->clearClippedText();
×
492
  QString file = getFile(index, true);
×
493
  ui->passwordName->setText(file);
×
494
  if (!file.isEmpty() && !cleared) {
×
495
    QtPassSettings::getPass()->Show(file);
×
496
  } else {
497
    clearPanel(false);
×
498
    ui->actionEdit->setEnabled(false);
×
499
    ui->actionDelete->setEnabled(true);
×
500
  }
501
}
×
502

503
/**
504
 * @brief MainWindow::on_treeView_doubleClicked when doubleclicked on
505
 * TreeViewItem, open the edit Window
506
 * @param index
507
 */
508
void MainWindow::on_treeView_doubleClicked(const QModelIndex &index) {
×
509
  QFileInfo fileOrFolder =
510
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
511

512
  if (fileOrFolder.isFile()) {
×
513
    editPassword(getFile(index, true));
×
514
  }
515
}
×
516

517
/**
518
 * @brief MainWindow::deselect clear the selection, password and copy buffer
519
 */
520
void MainWindow::deselect() {
×
521
  currentDir = "";
×
522
  m_qtPass->clearClipboard();
×
523
  ui->treeView->clearSelection();
×
524
  ui->actionEdit->setEnabled(false);
×
525
  ui->actionDelete->setEnabled(false);
×
526
  ui->passwordName->setText("");
×
527
  clearPanel(false);
×
528
}
×
529

530
void MainWindow::executeWrapperStarted() {
×
531
  clearTemplateWidgets();
×
532
  ui->textBrowser->clear();
×
533
  setUiElementsEnabled(false);
×
534
  clearPanelTimer.stop();
×
535
  if (QtPassSettings::isShowProcessOutput()) {
×
536
    ui->processOutputWidget->setVisible(true);
×
537
  }
538
}
×
539

540
/**
541
 * @brief Handles displaying parsed password entry content in the main window.
542
 * @example
543
 * void result = MainWindow::passShowHandler(p_output);
544
 * // Updates the UI with parsed fields and emits
545
 * passShowHandlerFinished(output)
546
 *
547
 * @param p_output - The raw output text containing the password entry data.
548
 * @return void - This function does not return a value.
549
 */
550
void MainWindow::passShowHandler(const QString &p_output) {
×
551
  QStringList templ = QtPassSettings::isUseTemplate()
×
552
                          ? QtPassSettings::getPassTemplate().split("\n")
×
553
                          : QStringList();
×
554
  bool allFields =
555
      QtPassSettings::isUseTemplate() && QtPassSettings::isTemplateAllFields();
×
556
  FileContent fileContent = FileContent::parse(p_output, templ, allFields);
×
557
  QString output = p_output;
558
  QString password = fileContent.getPassword();
×
559

560
  // set clipped text
561
  m_qtPass->setClippedText(password, p_output);
×
562

563
  // first clear the current view:
564
  clearTemplateWidgets();
×
565

566
  // show what is needed:
567
  if (QtPassSettings::isHideContent()) {
×
568
    output = "***" + tr("Content hidden") + "***";
×
569
  } else if (!QtPassSettings::isDisplayAsIs()) {
×
570
    if (!password.isEmpty()) {
×
571
      // set the password, it is hidden if needed in addToGridLayout
572
      addToGridLayout(0, tr("Password"), password);
×
573
    }
574

575
    NamedValues namedValues = fileContent.getNamedValues();
×
576
    for (int j = 0; j < namedValues.length(); ++j) {
×
577
      const NamedValue &nv = namedValues.at(j);
578
      addToGridLayout(j + 1, nv.name, nv.value);
×
579
    }
580
    if (ui->gridLayout->count() == 0) {
×
581
      ui->verticalLayoutPassword->setSpacing(0);
×
582
    } else {
583
      ui->verticalLayoutPassword->setSpacing(6);
×
584
    }
585

586
    output = fileContent.getRemainingDataForDisplay();
×
587
  }
588

589
  if (QtPassSettings::isUseAutoclearPanel()) {
×
590
    clearPanelTimer.start();
×
591
  }
592

593
  emit passShowHandlerFinished(output);
×
594
  setUiElementsEnabled(true);
×
595
}
×
596

597
/**
598
 * @brief Handles the OTP output by displaying it, copying it to the clipboard,
599
 * and updating the UI state.
600
 * @example
601
 * void MainWindow::passOtpHandler(const QString &p_output);
602
 *
603
 * @param const QString &p_output - The OTP code text to process; if empty, an
604
 * error message is shown instead.
605
 * @return void - This function does not return a value.
606
 */
607
void MainWindow::passOtpHandler(const QString &p_output) {
×
608
  if (!p_output.isEmpty()) {
×
609
    addToGridLayout(ui->gridLayout->count() + 1, tr("OTP Code"), p_output);
×
610
    m_qtPass->copyTextToClipboard(p_output);
×
611
    showStatusMessage(tr("OTP code copied to clipboard"));
×
612
  } else {
613
    flashText(tr("No OTP code found in this password entry"), true);
×
614
  }
615
  if (QtPassSettings::isUseAutoclearPanel()) {
×
616
    clearPanelTimer.start();
×
617
  }
618
  setUiElementsEnabled(true);
×
619
}
×
620

621
/**
622
 * @brief MainWindow::clearPanel hide the information from shoulder surfers
623
 */
624
void MainWindow::clearPanel(bool notify) {
×
625
  while (ui->gridLayout->count() > 0) {
×
626
    QLayoutItem *item = ui->gridLayout->takeAt(0);
×
627
    delete item->widget();
×
628
    delete item;
×
629
  }
630
  const bool grepWasVisible = ui->grepResultsList->isVisible();
×
631
  ui->grepResultsList->clear();
×
632
  if (grepWasVisible) {
×
633
    ui->grepResultsList->setVisible(false);
×
634
    ui->treeView->setVisible(true);
×
635
    if (m_grepMode) {
×
636
      m_grepMode = false;
×
637
      ui->grepButton->blockSignals(true);
×
638
      ui->grepButton->setChecked(false);
×
639
      ui->grepButton->blockSignals(false);
×
640
      ui->lineEdit->blockSignals(true);
×
641
      ui->lineEdit->clear();
×
642
      ui->lineEdit->blockSignals(false);
×
643
      ui->lineEdit->setPlaceholderText(tr("Search Password"));
×
644
    }
645
  }
646
  if (notify) {
×
647
    QString output = "***" + tr("Password and Content hidden") + "***";
×
648
    ui->textBrowser->setHtml(output);
×
649
  } else {
650
    ui->textBrowser->setHtml("");
×
651
  }
652
}
×
653

654
/**
655
 * @brief MainWindow::setUiElementsEnabled enable or disable the relevant UI
656
 * elements
657
 * @param state
658
 */
659
void MainWindow::setUiElementsEnabled(bool state) {
×
660
  ui->treeView->setEnabled(state);
×
661
  ui->lineEdit->setEnabled(state);
×
662
  ui->lineEdit->installEventFilter(this);
×
663
  ui->actionAddPassword->setEnabled(state);
×
664
  ui->actionAddFolder->setEnabled(state);
×
665
  ui->actionUsers->setEnabled(state);
×
666
  ui->actionConfig->setEnabled(state);
×
667
  // is a file selected?
668
  state &= ui->treeView->currentIndex().isValid();
×
669
  ui->actionDelete->setEnabled(state);
×
670
  ui->actionEdit->setEnabled(state);
×
671
  updateGitButtonVisibility();
×
672
  updateOtpButtonVisibility();
×
673
}
×
674

675
/**
676
 * @brief Restores the main window geometry, state, position, size, and
677
 * tray/icon settings from saved application settings.
678
 * @example
679
 * MainWindow window;
680
 * window.restoreWindow();
681
 *
682
 * @return void - This function does not return a value.
683
 */
684
void MainWindow::restoreWindow() {
×
685
  QByteArray geometry = QtPassSettings::getGeometry(saveGeometry());
×
686
  restoreGeometry(geometry);
×
687
  QByteArray savestate = QtPassSettings::getSavestate(saveState());
×
688
  restoreState(savestate);
×
689
  QPoint position = QtPassSettings::getPos(pos());
×
690
  move(position);
×
691
  QSize newSize = QtPassSettings::getSize(size());
×
692
  resize(newSize);
×
693
  if (QtPassSettings::isMaximized(isMaximized())) {
×
694
    showMaximized();
×
695
  }
696

697
  if (QtPassSettings::isAlwaysOnTop()) {
×
698
    Qt::WindowFlags flags = windowFlags();
699
    setWindowFlags(flags | Qt::WindowStaysOnTopHint);
×
700
    show();
×
701
  }
702

703
  if (QtPassSettings::isUseTrayIcon() && tray == nullptr) {
×
704
    initTrayIcon();
×
705
    if (QtPassSettings::isStartMinimized()) {
×
706
      // since we are still in constructor, can't directly hide
707
      QTimer::singleShot(10, this, SLOT(hide()));
×
708
    }
709
  } else if (!QtPassSettings::isUseTrayIcon() && tray != nullptr) {
×
710
    destroyTrayIcon();
×
711
  }
712
}
×
713

714
/**
715
 * @brief MainWindow::on_configButton_clicked run Mainwindow::config
716
 */
717
void MainWindow::onConfig() { config(); }
×
718

719
/**
720
 * @brief Executes when the string in the search box changes, collapses the
721
 * TreeView
722
 * @param arg1
723
 */
724
void MainWindow::on_lineEdit_textChanged(const QString &arg1) {
×
725
  if (m_grepMode)
×
726
    return;
727
  ui->statusBar->showMessage(tr("Looking for: %1").arg(arg1), 1000);
×
728
  ui->treeView->expandAll();
×
729
  clearPanel(false);
×
730
  ui->passwordName->setText("");
×
731
  ui->actionEdit->setEnabled(false);
×
732
  ui->actionDelete->setEnabled(false);
×
733
  searchTimer.start();
×
734
}
735

736
/**
737
 * @brief MainWindow::onTimeoutSearch Fired when search is finished or too much
738
 * time from two keypresses is elapsed
739
 */
740
void MainWindow::onTimeoutSearch() {
×
741
  QString query = ui->lineEdit->text();
×
742

743
  if (query.isEmpty()) {
×
744
    ui->treeView->collapseAll();
×
745
    deselect();
×
746
  }
747

748
  query.replace(QStringLiteral(" "), ".*");
×
749
  QRegularExpression regExp(query, QRegularExpression::CaseInsensitiveOption);
×
750
  proxyModel.setFilterRegularExpression(regExp);
×
751
  ui->treeView->setRootIndex(proxyModel.mapFromSource(
×
752
      model.setRootPath(QtPassSettings::getPassStore())));
×
753

754
  if (proxyModel.rowCount() > 0 && !query.isEmpty()) {
×
755
    selectFirstFile();
×
756
  } else {
757
    ui->actionEdit->setEnabled(false);
×
758
    ui->actionDelete->setEnabled(false);
×
759
  }
760
}
×
761

762
/**
763
 * @brief MainWindow::on_lineEdit_returnPressed get searching
764
 *
765
 * Select the first possible file in the tree
766
 */
767
void MainWindow::on_lineEdit_returnPressed() {
×
768
#ifdef QT_DEBUG
769
  dbg() << "on_lineEdit_returnPressed" << proxyModel.rowCount();
770
#endif
771

772
  if (m_grepMode) {
×
773
    const QString query = ui->lineEdit->text();
×
774
    if (!query.isEmpty()) {
×
775
      m_grepCancelled = false;
×
776
      ui->grepResultsList->clear();
×
777
      ui->statusBar->showMessage(tr("Searching…"));
×
778
      if (!m_grepBusy) {
×
779
        m_grepBusy = true;
×
780
        QApplication::setOverrideCursor(Qt::WaitCursor);
×
781
      }
782
      QtPassSettings::getPass()->Grep(query, ui->grepCaseButton->isChecked());
×
783
    } else {
784
      m_grepCancelled = true;
×
785
      if (m_grepBusy) {
×
786
        m_grepBusy = false;
×
787
        QApplication::restoreOverrideCursor();
×
788
      }
789
      ui->grepResultsList->clear();
×
790
      ui->grepResultsList->setVisible(false);
×
791
      ui->treeView->setVisible(true);
×
792
    }
793
    return;
794
  }
795

796
  if (proxyModel.rowCount() > 0) {
×
797
    selectFirstFile();
×
798
    on_treeView_clicked(ui->treeView->currentIndex());
×
799
  }
800
}
801

802
/**
803
 * @brief Toggle grep (content search) mode.
804
 */
805
void MainWindow::on_grepButton_toggled(bool checked) {
×
806
  m_grepMode = checked;
×
807
  if (checked) {
×
808
    ui->lineEdit->setPlaceholderText(tr("Search content (regex)"));
×
809
    ui->lineEdit->clear();
×
810
    searchTimer.stop();
×
811
    proxyModel.setFilterRegularExpression(QRegularExpression());
×
812
    ui->treeView->setRootIndex(proxyModel.mapFromSource(
×
813
        model.setRootPath(QtPassSettings::getPassStore())));
×
814
    ui->grepResultsList->setVisible(false);
×
815
    // Keep treeView visible until results arrive
816
  } else {
817
    if (m_grepBusy) {
×
818
      m_grepBusy = false;
×
819
      m_grepCancelled = true;
×
820
      QApplication::restoreOverrideCursor();
×
821
    }
822
    searchTimer.stop();
×
823
    ui->lineEdit->blockSignals(true);
×
824
    ui->lineEdit->clear();
×
825
    ui->lineEdit->blockSignals(false);
×
826
    ui->lineEdit->setPlaceholderText(tr("Search Password"));
×
827
    ui->grepResultsList->clear();
×
828
    ui->grepResultsList->setVisible(false);
×
829
    ui->treeView->setVisible(true);
×
830
    proxyModel.setFilterRegularExpression(QRegularExpression());
×
831
    ui->treeView->setRootIndex(proxyModel.mapFromSource(
×
832
        model.setRootPath(QtPassSettings::getPassStore())));
×
833
  }
834
}
×
835

836
/**
837
 * @brief Display grep results in grepResultsList.
838
 */
839
void MainWindow::onGrepFinished(
×
840
    const QList<QPair<QString, QStringList>> &results) {
841
  if (m_grepBusy) {
×
842
    m_grepBusy = false;
×
843
    QApplication::restoreOverrideCursor();
×
844
  }
845
  if (m_grepCancelled) {
×
846
    m_grepCancelled = false;
×
847
    return;
×
848
  }
849
  setUiElementsEnabled(true);
×
850
  if (!m_grepMode)
×
851
    return;
852
  ui->grepResultsList->clear();
×
853
  if (results.isEmpty()) {
×
854
    ui->statusBar->showMessage(tr("No matches found."), 3000);
×
855
    ui->grepResultsList->setVisible(false);
×
856
    ui->treeView->setVisible(true);
×
857
    return;
×
858
  }
859
  const bool hideContent = QtPassSettings::isHideContent();
×
860
  int totalLines = 0;
861
  for (const auto &pair : results) {
×
862
    QTreeWidgetItem *entryItem = new QTreeWidgetItem(ui->grepResultsList);
×
863
    entryItem->setText(0, pair.first);
×
864
    entryItem->setData(0, Qt::UserRole, pair.first);
×
865
    for (const QString &line : pair.second) {
×
866
      QTreeWidgetItem *lineItem = new QTreeWidgetItem(entryItem);
×
867
      lineItem->setText(0, hideContent ? "***" + tr("Content hidden") + "***"
×
868
                                       : line);
869
      lineItem->setData(0, Qt::UserRole, pair.first);
×
870
      ++totalLines;
×
871
    }
872
  }
873
  ui->grepResultsList->expandAll();
×
874
  ui->treeView->setVisible(false);
×
875
  ui->grepResultsList->setVisible(true);
×
876
  ui->statusBar->showMessage(
×
877
      tr("Found %n match(es)", nullptr, totalLines) + " " +
×
878
          tr("in %n entr(ies).", nullptr, results.size()),
×
879
      3000);
880
  if (QtPassSettings::isUseAutoclearPanel())
×
881
    clearPanelTimer.start();
×
882
}
883

884
/**
885
 * @brief Navigate to the password entry when a grep result is clicked.
886
 */
887
void MainWindow::on_grepResultsList_itemClicked(QTreeWidgetItem *item,
×
888
                                                int /*column*/) {
889
  const QString entry = item->data(0, Qt::UserRole).toString();
×
890
  if (entry.isEmpty())
×
891
    return;
892
  const QString fullPath = QDir::cleanPath(
893
      QDir(QtPassSettings::getPassStore()).filePath(entry + ".gpg"));
×
894
  QModelIndex srcIndex = model.index(fullPath);
×
895
  if (!srcIndex.isValid())
896
    return;
897
  QModelIndex proxyIndex = proxyModel.mapFromSource(srcIndex);
×
898
  if (!proxyIndex.isValid())
899
    return;
900
  ui->treeView->setCurrentIndex(proxyIndex);
×
901
  on_treeView_clicked(proxyIndex);
×
902
  if (QtPassSettings::isHideContent() || QtPassSettings::isUseAutoclearPanel())
×
903
    ui->grepResultsList->clear();
×
904
  ui->grepResultsList->setVisible(false);
×
905
  ui->treeView->setVisible(true);
×
906
  ui->treeView->scrollTo(proxyIndex);
×
907
  ui->treeView->setFocus();
×
908
}
909

910
/**
911
 * @brief MainWindow::selectFirstFile select the first possible file in the
912
 * tree
913
 */
914
void MainWindow::selectFirstFile() {
×
915
  QModelIndex index = proxyModel.mapFromSource(
×
916
      model.setRootPath(QtPassSettings::getPassStore()));
×
917
  index = firstFile(index);
×
918
  ui->treeView->setCurrentIndex(index);
×
919
}
×
920

921
/**
922
 * @brief MainWindow::firstFile return location of first possible file
923
 * @param parentIndex
924
 * @return QModelIndex
925
 */
926
auto MainWindow::firstFile(QModelIndex parentIndex) -> QModelIndex {
×
927
  QModelIndex index = parentIndex;
×
928
  int numRows = proxyModel.rowCount(parentIndex);
×
929
  for (int row = 0; row < numRows; ++row) {
×
930
    index = proxyModel.index(row, 0, parentIndex);
×
931
    if (model.fileInfo(proxyModel.mapToSource(index)).isFile()) {
×
932
      return index;
×
933
    }
934
    if (proxyModel.hasChildren(index)) {
×
935
      return firstFile(index);
×
936
    }
937
  }
938
  return index;
×
939
}
940

941
/**
942
 * @brief MainWindow::setPassword open passworddialog
943
 * @param file which pgp file
944
 * @param isNew insert (not update)
945
 */
946
void MainWindow::setPassword(const QString &file, bool isNew) {
×
947
  PasswordDialog d(file, isNew, this);
×
948

949
  if (isNew) {
×
950
    QString storePath = QtPassSettings::getPassStore();
×
951
    QString folder =
952
        Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel);
×
953
    if (folder.isEmpty()) {
×
954
      folder = storePath;
×
955
    }
956
    QHash<QString, QStringList> templates = Util::readTemplates(storePath);
×
957
    if (!templates.isEmpty()) {
958
      QString defaultTemplate = Util::getFolderTemplate(folder, storePath);
×
959
      d.setAvailableTemplates(templates, defaultTemplate);
×
960
      new QShortcut(QKeySequence(Qt::CTRL | Qt::Key_T), &d,
×
961
                    [&d]() { d.cycleTemplate(); });
×
962
    }
963
  }
×
964

965
  if (!d.exec()) {
×
966
    ui->treeView->setFocus();
×
967
  }
968
}
×
969

970
/**
971
 * @brief MainWindow::addPassword add a new password by showing a
972
 * number of dialogs.
973
 */
974
void MainWindow::addPassword() {
×
975
  bool ok;
976
  QString dir =
977
      Util::getDir(ui->treeView->currentIndex(), true, model, proxyModel);
×
978
  QString file =
979
      QInputDialog::getText(this, tr("New file"),
×
980
                            tr("New password file: \n(Will be placed in %1 )")
×
981
                                .arg(QtPassSettings::getPassStore() +
×
982
                                     Util::getDir(ui->treeView->currentIndex(),
×
983
                                                  true, model, proxyModel)),
984
                            QLineEdit::Normal, "", &ok);
×
985
  if (!ok || file.isEmpty()) {
×
986
    return;
987
  }
988
  file = dir + file;
×
989
  setPassword(file);
×
990
}
991

992
/**
993
 * @brief MainWindow::onDelete remove password, if you are
994
 * sure.
995
 */
996
void MainWindow::onDelete() {
×
997
  QModelIndex currentIndex = ui->treeView->currentIndex();
×
998
  if (!currentIndex.isValid()) {
999
    // This fixes https://github.com/IJHack/QtPass/issues/556
1000
    // Otherwise the entire password directory would be deleted if
1001
    // nothing is selected in the tree view.
1002
    return;
×
1003
  }
1004

1005
  QFileInfo fileOrFolder =
1006
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
1007
  QString file = "";
×
1008
  bool isDir = false;
1009

1010
  if (fileOrFolder.isFile()) {
×
1011
    file = getFile(ui->treeView->currentIndex(), true);
×
1012
  } else {
1013
    file = Util::getDir(ui->treeView->currentIndex(), true, model, proxyModel);
×
1014
    isDir = true;
1015
  }
1016

1017
  QString dirMessage = tr(" and the whole content?");
1018
  if (isDir) {
×
1019
    QDirIterator it(model.rootPath() + QDir::separator() + file,
×
1020
                    QDirIterator::Subdirectories);
×
1021
    bool okDir = true;
1022
    while (it.hasNext() && okDir) {
×
1023
      it.next();
×
1024
      if (QFileInfo(it.filePath()).isFile()) {
×
1025
        if (QFileInfo(it.filePath()).suffix() != "gpg") {
×
1026
          okDir = false;
1027
          dirMessage = tr(" and the whole content? <br><strong>Attention: "
×
1028
                          "there are unexpected files in the given folder, "
1029
                          "check them before continue.</strong>");
1030
        }
1031
      }
1032
    }
1033
  }
×
1034

1035
  if (QMessageBox::question(
×
1036
          this, isDir ? tr("Delete folder?") : tr("Delete password?"),
×
1037
          tr("Are you sure you want to delete %1%2?")
×
1038
              .arg(QDir::separator() + file, isDir ? dirMessage : "?"),
×
1039
          QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) {
1040
    return;
1041
  }
1042

1043
  QtPassSettings::getPass()->Remove(file, isDir);
×
1044
}
×
1045

1046
/**
1047
 * @brief MainWindow::onOTP try and generate (selected) OTP code.
1048
 */
1049
void MainWindow::onOtp() {
×
1050
  QString file = getFile(ui->treeView->currentIndex(), true);
×
1051
  if (!file.isEmpty()) {
×
1052
    if (QtPassSettings::isUseOtp()) {
×
1053
      setUiElementsEnabled(false);
×
1054
      QtPassSettings::getPass()->OtpGenerate(file);
×
1055
    }
1056
  } else {
1057
    flashText(tr("No password selected for OTP generation"), true);
×
1058
  }
1059
}
×
1060

1061
/**
1062
 * @brief MainWindow::onEdit try and edit (selected) password.
1063
 */
1064
void MainWindow::onEdit() {
×
1065
  QString file = getFile(ui->treeView->currentIndex(), true);
×
1066
  editPassword(file);
×
1067
}
×
1068

1069
/**
1070
 * @brief MainWindow::userDialog see MainWindow::onUsers()
1071
 * @param dir folder to edit users for.
1072
 */
1073
void MainWindow::userDialog(const QString &dir) {
×
1074
  if (!dir.isEmpty()) {
×
1075
    currentDir = dir;
×
1076
  }
1077
  onUsers();
×
1078
}
×
1079

1080
/**
1081
 * @brief MainWindow::onUsers edit users for the current
1082
 * folder,
1083
 * gets lists and opens UserDialog.
1084
 */
1085
void MainWindow::onUsers() {
×
1086
  QString dir =
1087
      currentDir.isEmpty()
1088
          ? Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel)
×
1089
          : currentDir;
×
1090

1091
  UsersDialog d(dir, this);
×
1092
  if (!d.exec()) {
×
1093
    ui->treeView->setFocus();
×
1094
  }
1095
}
×
1096

1097
/**
1098
 * @brief MainWindow::messageAvailable we have some text/message/search to do.
1099
 * @param message
1100
 */
1101
void MainWindow::messageAvailable(const QString &message) {
×
1102
  show();
×
1103
  raise();
×
1104
  if (message.isEmpty()) {
×
1105
    focusInput();
×
1106
  } else {
1107
    ui->treeView->expandAll();
×
1108
    ui->lineEdit->setText(message);
×
1109
    on_lineEdit_returnPressed();
×
1110
  }
1111
}
×
1112

1113
/**
1114
 * @brief MainWindow::generateKeyPair internal gpg keypair generator . .
1115
 * @param batch
1116
 * @param keygenWindow
1117
 */
1118
void MainWindow::generateKeyPair(const QString &batch, QDialog *keygenWindow) {
×
1119
  keygenDialog = keygenWindow;
×
1120
  emit generateGPGKeyPair(batch);
×
1121
}
×
1122

1123
/**
1124
 * @brief MainWindow::updateProfileBox update the list of profiles, optionally
1125
 * select a more appropriate one to view too
1126
 */
1127
void MainWindow::updateProfileBox() {
×
1128
  QHash<QString, QHash<QString, QString>> profiles =
1129
      QtPassSettings::getProfiles();
×
1130

1131
  if (profiles.isEmpty()) {
1132
    ui->profileWidget->hide();
×
1133
  } else {
1134
    ui->profileWidget->show();
×
1135
    ui->profileBox->setEnabled(profiles.size() > 1);
×
1136
    ui->profileBox->clear();
×
1137
    QHashIterator<QString, QHash<QString, QString>> i(profiles);
×
1138
    while (i.hasNext()) {
×
1139
      i.next();
1140
      if (!i.key().isEmpty()) {
×
1141
        ui->profileBox->addItem(i.key());
×
1142
      }
1143
    }
1144
    ui->profileBox->model()->sort(0);
×
1145
  }
1146
  int index = ui->profileBox->findText(QtPassSettings::getProfile());
×
1147
  if (index != -1) { //  -1 for not found
×
1148
    ui->profileBox->setCurrentIndex(index);
×
1149
  }
1150
}
×
1151

1152
/**
1153
 * @brief MainWindow::on_profileBox_currentIndexChanged make sure we show the
1154
 * correct "profile"
1155
 * @param name
1156
 */
1157
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
1158
void MainWindow::on_profileBox_currentIndexChanged(QString name) {
1159
#else
1160
/**
1161
 * @brief Handles changes to the selected profile in the profile combo box.
1162
 * @details Ignores the event during a fresh start or when the selected profile
1163
 * matches the current profile. Otherwise, it clears the password field, updates
1164
 * the active profile and related settings, refreshes the environment, and
1165
 * resets the tree view and action states to reflect the newly selected profile.
1166
 *
1167
 * @param name - The newly selected profile name.
1168
 * @return void - This function does not return a value.
1169
 *
1170
 */
1171
void MainWindow::on_profileBox_currentTextChanged(const QString &name) {
×
1172
#endif
1173
  if (m_qtPass->isFreshStart() || name == QtPassSettings::getProfile()) {
×
1174
    return;
×
1175
  }
1176

1177
  ui->lineEdit->clear();
×
1178

1179
  QtPassSettings::setProfile(name);
×
1180

1181
  QtPassSettings::setPassStore(
×
1182
      QtPassSettings::getProfiles().value(name).value("path"));
×
1183
  QtPassSettings::setPassSigningKey(
×
1184
      QtPassSettings::getProfiles().value(name).value("signingKey"));
×
1185
  ui->statusBar->showMessage(tr("Profile changed to %1").arg(name), 2000);
×
1186

1187
  QtPassSettings::getPass()->updateEnv();
×
1188

1189
  const QString passStore = QtPassSettings::getPassStore();
×
1190
  proxyModel.setStore(passStore);
×
1191
  ui->treeView->setRootIndex(
×
1192
      proxyModel.mapFromSource(model.setRootPath(passStore)));
×
1193
  deselect();
×
1194
  ui->treeView->setCurrentIndex(QModelIndex());
×
1195
}
1196

1197
/**
1198
 * @brief MainWindow::initTrayIcon show a nice tray icon on systems that
1199
 * support
1200
 * it
1201
 */
1202
void MainWindow::initTrayIcon() {
×
1203
  this->tray = new TrayIcon(this);
×
1204
  // Setup tray icon
1205

1206
  if (tray == nullptr) {
1207
#ifdef QT_DEBUG
1208
    dbg() << "Allocating tray icon failed.";
1209
#endif
1210
    return;
1211
  }
1212

1213
  if (!tray->getIsAllocated()) {
×
1214
    destroyTrayIcon();
×
1215
  }
1216
}
1217

1218
/**
1219
 * @brief MainWindow::destroyTrayIcon remove that pesky tray icon
1220
 */
1221
void MainWindow::destroyTrayIcon() {
×
1222
  delete this->tray;
×
1223
  tray = nullptr;
×
1224
}
×
1225

1226
/**
1227
 * @brief MainWindow::closeEvent hide or quit
1228
 * @param event
1229
 */
1230
void MainWindow::closeEvent(QCloseEvent *event) {
×
1231
  if (QtPassSettings::isHideOnClose()) {
×
1232
    this->hide();
×
1233
    event->ignore();
1234
  } else {
1235
    m_qtPass->clearClipboard();
×
1236

1237
    QtPassSettings::setGeometry(saveGeometry());
×
1238
    QtPassSettings::setSavestate(saveState());
×
1239
    QtPassSettings::setMaximized(isMaximized());
×
1240
    if (!isMaximized()) {
×
1241
      QtPassSettings::setPos(pos());
×
1242
      QtPassSettings::setSize(size());
×
1243
    }
1244
    event->accept();
1245
  }
1246
}
×
1247

1248
/**
1249
 * @brief MainWindow::eventFilter filter out some events and focus the
1250
 * treeview
1251
 * @param obj
1252
 * @param event
1253
 * @return
1254
 */
1255
auto MainWindow::eventFilter(QObject *obj, QEvent *event) -> bool {
×
1256
  if (obj == ui->lineEdit && event->type() == QEvent::KeyPress) {
×
1257
    auto *key = dynamic_cast<QKeyEvent *>(event);
×
1258
    if (key != nullptr && key->key() == Qt::Key_Down) {
×
1259
      ui->treeView->setFocus();
×
1260
    }
1261
  }
1262
  return QObject::eventFilter(obj, event);
×
1263
}
1264

1265
/**
1266
 * @brief MainWindow::keyPressEvent did anyone press return, enter or escape?
1267
 * @param event
1268
 */
1269
void MainWindow::keyPressEvent(QKeyEvent *event) {
×
1270
  switch (event->key()) {
×
1271
  case Qt::Key_Delete:
×
1272
    onDelete();
×
1273
    break;
×
1274
  case Qt::Key_Return:
×
1275
  case Qt::Key_Enter:
1276
    if (proxyModel.rowCount() > 0) {
×
1277
      on_treeView_clicked(ui->treeView->currentIndex());
×
1278
    }
1279
    break;
1280
  case Qt::Key_Escape:
×
1281
    ui->lineEdit->clear();
×
1282
    break;
×
1283
  default:
1284
    break;
1285
  }
1286
}
×
1287

1288
/**
1289
 * @brief MainWindow::showContextMenu show us the (file or folder) context
1290
 * menu
1291
 * @param pos
1292
 */
1293
void MainWindow::showContextMenu(const QPoint &pos) {
×
1294
  QModelIndex index = ui->treeView->indexAt(pos);
×
1295
  bool selected = true;
1296
  if (!index.isValid()) {
1297
    ui->treeView->clearSelection();
×
1298
    ui->actionDelete->setEnabled(false);
×
1299
    ui->actionEdit->setEnabled(false);
×
1300
    currentDir = "";
×
1301
    selected = false;
1302
  }
1303

1304
  ui->treeView->setCurrentIndex(index);
×
1305

1306
  QPoint globalPos = ui->treeView->viewport()->mapToGlobal(pos);
×
1307

1308
  QFileInfo fileOrFolder =
1309
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
1310

1311
  QMenu contextMenu;
×
1312
  if (!selected || fileOrFolder.isDir()) {
×
1313
    QAction *openFolder =
1314
        contextMenu.addAction(tr("Open folder with file manager"));
×
1315
    QAction *addFolder = contextMenu.addAction(tr("Add folder"));
×
1316
    QAction *addPassword = contextMenu.addAction(tr("Add password"));
×
1317
    QAction *users = contextMenu.addAction(tr("Users"));
×
1318
    connect(openFolder, &QAction::triggered, this, &MainWindow::openFolder);
×
1319
    connect(addFolder, &QAction::triggered, this, &MainWindow::addFolder);
×
1320
    connect(addPassword, &QAction::triggered, this, &MainWindow::addPassword);
×
1321
    connect(users, &QAction::triggered, this, &MainWindow::onUsers);
×
1322
  } else if (fileOrFolder.isFile()) {
×
1323
    QAction *edit = contextMenu.addAction(tr("Edit"));
×
1324
    connect(edit, &QAction::triggered, this, &MainWindow::onEdit);
×
1325
  }
1326
  if (selected) {
×
1327
    contextMenu.addSeparator();
×
1328
    if (fileOrFolder.isDir()) {
×
1329
      QAction *renameFolder = contextMenu.addAction(tr("Rename folder"));
×
1330
      connect(renameFolder, &QAction::triggered, this,
×
1331
              &MainWindow::renameFolder);
×
1332
    } else if (fileOrFolder.isFile()) {
×
1333
      QAction *renamePassword = contextMenu.addAction(tr("Rename password"));
×
1334
      connect(renamePassword, &QAction::triggered, this,
×
1335
              &MainWindow::renamePassword);
×
1336
    }
1337
    QAction *deleteItem = contextMenu.addAction(tr("Delete"));
×
1338
    connect(deleteItem, &QAction::triggered, this, &MainWindow::onDelete);
×
1339
    if (fileOrFolder.isDir()) {
×
1340
      QString dirPath = QDir::cleanPath(
1341
          Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel));
×
1342

1343
      QMenu *shareMenu = new QMenu(tr("Share"), &contextMenu);
×
1344
      contextMenu.addMenu(shareMenu);
×
1345

1346
      QString gpgIdPath = Pass::getGpgIdPath(dirPath);
×
1347
      bool gpgIdExists = !gpgIdPath.isEmpty() && QFile(gpgIdPath).exists();
×
1348

1349
      QString exePath = QtPassSettings::isUsePass()
×
1350
                            ? QtPassSettings::getPassExecutable()
×
1351
                            : QtPassSettings::getGpgExecutable();
×
1352
      bool gpgAvailable = !exePath.isEmpty() && (exePath.startsWith("wsl ") ||
×
1353
                                                 QFile(exePath).exists());
×
1354

1355
      QAction *reencrypt = shareMenu->addAction(tr("Re-encrypt all passwords"));
×
1356
      reencrypt->setEnabled(gpgIdExists && gpgAvailable);
×
1357
      connect(reencrypt, &QAction::triggered, this,
×
1358
              [this, dirPath]() { reencryptPath(dirPath); });
×
1359

1360
      QAction *exportKey = shareMenu->addAction(tr("Export my public key..."));
×
1361
      exportKey->setEnabled(gpgAvailable);
×
1362
      connect(exportKey, &QAction::triggered, this,
×
1363
              &MainWindow::exportPublicKey);
×
1364

1365
      QAction *addRecipientAction =
1366
          shareMenu->addAction(tr("Add recipient..."));
×
1367
      addRecipientAction->setEnabled(gpgIdExists && gpgAvailable);
×
1368
      connect(addRecipientAction, &QAction::triggered, this,
×
1369
              [this, dirPath]() { addRecipient(dirPath); });
×
1370

1371
      QAction *shareHelp = shareMenu->addAction(tr("What is this?"));
×
1372
      connect(shareHelp, &QAction::triggered, this, &MainWindow::showShareHelp);
×
1373
    }
1374
  }
1375
  contextMenu.exec(globalPos);
×
1376
}
×
1377

1378
/**
1379
 * @brief MainWindow::showBrowserContextMenu show us the context menu in
1380
 * password window
1381
 * @param pos
1382
 */
1383
void MainWindow::showBrowserContextMenu(const QPoint &pos) {
×
1384
  QMenu *contextMenu = ui->textBrowser->createStandardContextMenu(pos);
×
1385
  QPoint globalPos = ui->textBrowser->viewport()->mapToGlobal(pos);
×
1386

1387
  contextMenu->exec(globalPos);
×
1388
  delete contextMenu;
×
1389
}
×
1390

1391
/**
1392
 * @brief MainWindow::openFolder open the folder in the default file manager
1393
 */
1394
void MainWindow::openFolder() {
×
1395
  QString dir =
1396
      Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel);
×
1397

1398
  QString path = QDir::toNativeSeparators(dir);
×
1399
  QDesktopServices::openUrl(QUrl::fromLocalFile(path));
×
1400
}
×
1401

1402
/**
1403
 * @brief MainWindow::addFolder add a new folder to store passwords in
1404
 */
1405
void MainWindow::addFolder() {
×
1406
  bool ok;
1407
  QString dir =
1408
      Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel);
×
1409
  QString newdir =
1410
      QInputDialog::getText(this, tr("New file"),
×
1411
                            tr("New Folder: \n(Will be placed in %1 )")
×
1412
                                .arg(QtPassSettings::getPassStore() +
×
1413
                                     Util::getDir(ui->treeView->currentIndex(),
×
1414
                                                  true, model, proxyModel)),
1415
                            QLineEdit::Normal, "", &ok);
×
1416
  if (!ok || newdir.isEmpty()) {
×
1417
    return;
1418
  }
1419
  newdir.prepend(dir);
1420
  if (!QDir().mkdir(newdir)) {
×
1421
    QMessageBox::warning(this, tr("Error"),
×
1422
                         tr("Failed to create folder: %1").arg(newdir));
×
1423
    return;
×
1424
  }
1425
  if (QtPassSettings::isAddGPGId(true)) {
×
1426
    QString gpgIdFile = newdir + "/.gpg-id";
×
1427
    QFile gpgId(gpgIdFile);
×
1428
    if (!gpgId.open(QIODevice::WriteOnly)) {
×
1429
      QMessageBox::warning(
×
1430
          this, tr("Error"),
×
1431
          tr("Failed to create .gpg-id file in: %1").arg(newdir));
×
1432
      return;
1433
    }
1434
    QList<UserInfo> users = QtPassSettings::getPass()->listKeys("", true);
×
1435
    for (const UserInfo &user : users) {
×
1436
      if (user.enabled) {
×
1437
        gpgId.write((user.key_id + "\n").toUtf8());
×
1438
      }
1439
    }
1440
    gpgId.close();
×
1441
  }
×
1442
}
1443

1444
/**
1445
 * @brief MainWindow::renameFolder rename an existing folder
1446
 */
1447
void MainWindow::renameFolder() {
×
1448
  bool ok;
1449
  QString srcDir = QDir::cleanPath(
1450
      Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel));
×
1451
  QString srcDirName = QDir(srcDir).dirName();
×
1452
  QString newName =
1453
      QInputDialog::getText(this, tr("Rename file"), tr("Rename Folder To: "),
×
1454
                            QLineEdit::Normal, srcDirName, &ok);
×
1455
  if (!ok || newName.isEmpty()) {
×
1456
    return;
1457
  }
1458
  QString destDir = srcDir;
1459
  destDir.replace(srcDir.lastIndexOf(srcDirName), srcDirName.length(), newName);
×
1460
  QtPassSettings::getPass()->Move(srcDir, destDir);
×
1461
}
1462

1463
/**
1464
 * @brief MainWindow::editPassword read password and open edit window via
1465
 * MainWindow::onEdit()
1466
 */
1467
void MainWindow::editPassword(const QString &file) {
×
1468
  if (!file.isEmpty()) {
×
1469
    if (QtPassSettings::isUseGit() && QtPassSettings::isAutoPull()) {
×
1470
      onUpdate(true);
×
1471
    }
1472
    setPassword(file, false);
×
1473
  }
1474
}
×
1475

1476
/**
1477
 * @brief MainWindow::renamePassword rename an existing password
1478
 */
1479
void MainWindow::renamePassword() {
×
1480
  bool ok;
1481
  QString file = getFile(ui->treeView->currentIndex(), false);
×
1482
  QString filePath = QFileInfo(file).path();
×
1483
  QString fileName = QFileInfo(file).fileName();
×
1484
  if (fileName.endsWith(".gpg", Qt::CaseInsensitive)) {
×
1485
    fileName.chop(4);
×
1486
  }
1487

1488
  QString newName =
1489
      QInputDialog::getText(this, tr("Rename file"), tr("Rename File To: "),
×
1490
                            QLineEdit::Normal, fileName, &ok);
×
1491
  if (!ok || newName.isEmpty()) {
×
1492
    return;
1493
  }
1494
  QString newFile = QDir(filePath).filePath(newName);
×
1495
  QtPassSettings::getPass()->Move(file, newFile);
×
1496
}
1497

1498
/**
1499
 * @brief MainWindow::clearTemplateWidgets empty the template widget fields in
1500
 * the UI
1501
 */
1502
void MainWindow::clearTemplateWidgets() {
×
1503
  while (ui->gridLayout->count() > 0) {
×
1504
    QLayoutItem *item = ui->gridLayout->takeAt(0);
×
1505
    delete item->widget();
×
1506
    delete item;
×
1507
  }
1508
  ui->verticalLayoutPassword->setSpacing(0);
×
1509
}
×
1510

1511
/**
1512
 * @brief Copies the password of the selected file from the tree view to the
1513
 * clipboard.
1514
 * @example
1515
 * MainWindow::copyPasswordFromTreeview();
1516
 *
1517
 * @return void - This function does not return a value.
1518
 */
1519
void MainWindow::copyPasswordFromTreeview() {
×
1520
  QFileInfo fileOrFolder =
1521
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
1522

1523
  if (fileOrFolder.isFile()) {
×
1524
    QString file = getFile(ui->treeView->currentIndex(), true);
×
1525
    // Disconnect any previous connection to avoid accumulation
1526
    disconnect(QtPassSettings::getPass(), &Pass::finishedShow, this,
×
1527
               &MainWindow::passwordFromFileToClipboard);
1528
    connect(QtPassSettings::getPass(), &Pass::finishedShow, this,
×
1529
            &MainWindow::passwordFromFileToClipboard);
×
1530
    QtPassSettings::getPass()->Show(file);
×
1531
  }
1532
}
×
1533

1534
void MainWindow::passwordFromFileToClipboard(const QString &text) {
×
1535
  QStringList tokens = text.split('\n');
×
1536
  m_qtPass->copyTextToClipboard(tokens[0]);
×
1537
}
×
1538

1539
/**
1540
 * @brief MainWindow::addToGridLayout add a field to the template grid
1541
 * @param position
1542
 * @param field
1543
 * @param value
1544
 */
1545
void MainWindow::addToGridLayout(int position, const QString &field,
×
1546
                                 const QString &value) {
1547
  QString trimmedField = field.trimmed();
1548
  QString trimmedValue = value.trimmed();
1549

1550
  const QString buttonStyle =
1551
      "border-style: none; background: transparent; padding: 0; margin: 0; "
1552
      "icon-size: 16px; color: inherit;";
×
1553

1554
  // Combine the Copy button and the line edit in one widget
1555
  auto *frame = new QFrame();
×
1556
  QLayout *ly = new QHBoxLayout();
×
1557
  ly->setContentsMargins(5, 2, 2, 2);
×
1558
  ly->setSpacing(0);
×
1559
  frame->setLayout(ly);
×
1560
  if (QtPassSettings::getClipBoardType() != Enums::CLIPBOARD_NEVER) {
×
1561
    auto *fieldLabel = new QPushButtonWithClipboard(trimmedValue, this);
×
1562
    connect(fieldLabel, &QPushButtonWithClipboard::clicked, m_qtPass,
×
1563
            &QtPass::copyTextToClipboard);
×
1564

1565
    fieldLabel->setStyleSheet(buttonStyle);
×
1566
    frame->layout()->addWidget(fieldLabel);
×
1567
  }
1568

1569
  if (QtPassSettings::isUseQrencode()) {
×
1570
    auto *qrbutton = new QPushButtonAsQRCode(trimmedValue, this);
×
1571
    connect(qrbutton, &QPushButtonAsQRCode::clicked, m_qtPass,
×
1572
            &QtPass::showTextAsQRCode);
×
1573
    qrbutton->setStyleSheet(buttonStyle);
×
1574
    frame->layout()->addWidget(qrbutton);
×
1575
  }
1576

1577
  // set the echo mode to password, if the field is "password"
1578
  const QString lineStyle =
1579
      QtPassSettings::isUseMonospace()
×
1580
          ? "border-style: none; background: transparent; font-family: "
1581
            "monospace;"
1582
          : "border-style: none; background: transparent;";
×
1583

1584
  if (QtPassSettings::isHidePassword() && trimmedField == tr("Password")) {
×
1585
    auto *line = new QLineEdit();
×
1586
    line->setObjectName(trimmedField);
×
1587
    line->setText(trimmedValue);
×
1588
    line->setReadOnly(true);
×
1589
    line->setStyleSheet(lineStyle);
×
1590
    line->setContentsMargins(0, 0, 0, 0);
×
1591
    line->setEchoMode(QLineEdit::Password);
×
1592
    auto *showButton = new QPushButtonShowPassword(line, this);
×
1593
    showButton->setStyleSheet(buttonStyle);
×
1594
    showButton->setContentsMargins(0, 0, 0, 0);
×
1595
    frame->layout()->addWidget(showButton);
×
1596
    frame->layout()->addWidget(line);
×
1597
  } else {
1598
    auto *line = new QTextBrowser();
×
1599
    line->setOpenExternalLinks(true);
×
1600
    line->setOpenLinks(true);
×
1601
    line->setMaximumHeight(26);
×
1602
    line->setMinimumHeight(26);
×
1603
    line->setSizePolicy(
×
1604
        QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum));
1605
    line->setObjectName(trimmedField);
×
1606
    trimmedValue.replace(Util::protocolRegex(), R"(<a href="\1">\1</a>)");
×
1607
    line->setText(trimmedValue);
×
1608
    line->setReadOnly(true);
×
1609
    line->setStyleSheet(lineStyle);
×
1610
    line->setContentsMargins(0, 0, 0, 0);
×
1611
    frame->layout()->addWidget(line);
×
1612
  }
1613

1614
  frame->setStyleSheet(
×
1615
      ".QFrame{border: 1px solid lightgrey; border-radius: 5px;}");
1616

1617
  // set into the layout
1618
  ui->gridLayout->addWidget(new QLabel(trimmedField), position, 0);
×
1619
  ui->gridLayout->addWidget(frame, position, 1);
×
1620
}
×
1621

1622
/**
1623
 * @brief Displays message in status bar
1624
 *
1625
 * @param msg     text to be displayed
1626
 * @param timeout time for which msg shall be visible
1627
 */
1628
void MainWindow::showStatusMessage(const QString &msg, int timeout) {
×
1629
  ui->statusBar->showMessage(msg, timeout);
×
1630
}
×
1631

1632
/**
1633
 * @brief MainWindow::reencryptPath re-encrypt all passwords in a directory
1634
 * @param dir Directory path to re-encrypt
1635
 */
1636
void MainWindow::reencryptPath(const QString &dir) {
×
1637
  QDir checkDir(dir);
×
1638
  if (!checkDir.exists()) {
×
1639
    QMessageBox::critical(this, tr("Error"),
×
1640
                          tr("Directory does not exist: %1").arg(dir));
×
1641
    return;
×
1642
  }
1643

1644
  int ret = QMessageBox::question(
×
1645
      this, tr("Re-encrypt passwords"),
×
1646
      tr("Re-encrypt all passwords in %1?\n\n"
×
1647
         "This will re-encrypt ALL password files in this folder "
1648
         "using the current recipients defined in .gpg-id.\n\n"
1649
         "This may rewrite many files and cannot be undone easily.\n\n"
1650
         "Continue?")
1651
          .arg(QDir(dir).dirName()),
×
1652
      QMessageBox::Yes | QMessageBox::No);
1653

1654
  if (ret != QMessageBox::Yes)
×
1655
    return;
1656

1657
  // Prevent double execution - use same method as startReencryptPath
1658
  setUiElementsEnabled(false);
×
1659
  ui->treeView->setDisabled(true);
×
1660

1661
  QtPassSettings::getImitatePass()->reencryptPath(
×
1662
      QDir::cleanPath(QDir(dir).absolutePath()));
×
1663
}
×
1664

1665
/**
1666
 * @brief MainWindow::startReencryptPath disable ui elements and treeview
1667
 */
1668
void MainWindow::startReencryptPath() {
×
1669
  setUiElementsEnabled(false);
×
1670
  ui->treeView->setDisabled(true);
×
1671
}
×
1672

1673
/**
1674
 * @brief MainWindow::endReencryptPath re-enable ui elements
1675
 */
1676
void MainWindow::endReencryptPath() { setUiElementsEnabled(true); }
×
1677

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

1720
/**
1721
 * @brief MainWindow::addRecipient open the recipient management dialog for
1722
 *        the supplied directory.
1723
 * @param dir Folder whose .gpg-id should be edited.
1724
 *
1725
 * Delegates to UsersDialog so users can tick/untick keys from their
1726
 * keyring as recipients of the folder; importing a foreign key into the
1727
 * keyring still has to happen via gpg (or QtPass settings) first.
1728
 */
1729
void MainWindow::addRecipient(const QString &dir) {
×
1730
  UsersDialog d(dir, this);
×
1731
  d.exec();
×
1732
}
×
1733

1734
/**
1735
 * @brief MainWindow::showShareHelp show help about GPG sharing
1736
 */
1737
void MainWindow::showShareHelp() {
×
1738
  QMessageBox::information(
×
1739
      this, tr("Sharing Passwords with GPG"),
×
1740
      tr("<h3>Sharing Passwords with GPG</h3>"
×
1741
         "<p>To share passwords with other users:</p>"
1742
         "<ol>"
1743
         "<li><b>Export your public key</b> and send it to teammates</li>"
1744
         "<li><b>Import teammates' public keys</b> to their own folders</li>"
1745
         "<li><b>Re-encrypt passwords</b> so all recipients can decrypt "
1746
         "them</li>"
1747
         "</ol>"
1748
         "<p>Only people who have a matching secret key can decrypt the "
1749
         "passwords.</p>"
1750
         "<p><b>Tip:</b> Use the same GPG key for all shared folders.</p>"
1751
         "<p>See the FAQ for more details.</p>"));
1752
}
×
1753

1754
void MainWindow::updateGitButtonVisibility() {
×
1755
  if (!QtPassSettings::isUseGit() ||
×
1756
      (QtPassSettings::getGitExecutable().isEmpty() &&
×
1757
       QtPassSettings::getPassExecutable().isEmpty())) {
×
1758
    enableGitButtons(false);
×
1759
  } else {
1760
    enableGitButtons(true);
×
1761
  }
1762
}
×
1763

1764
void MainWindow::updateOtpButtonVisibility() {
×
1765
#if defined(Q_OS_WIN) || defined(__APPLE__)
1766
  ui->actionOtp->setVisible(false);
1767
#endif
1768
  if (!QtPassSettings::isUseOtp()) {
×
1769
    ui->actionOtp->setEnabled(false);
×
1770
  } else {
1771
    ui->actionOtp->setEnabled(true);
×
1772
  }
1773
}
×
1774

1775
void MainWindow::updateGrepButtonVisibility() {
×
1776
  const bool enabled = QtPassSettings::isUseGrepSearch();
×
1777
  ui->grepButton->setVisible(enabled);
×
1778
  ui->grepCaseButton->setVisible(enabled);
×
1779
  if (!enabled && m_grepMode) {
×
1780
    ui->grepButton->setChecked(false);
×
1781
  }
1782
}
×
1783

1784
void MainWindow::enableGitButtons(const bool &state) {
×
1785
  // Following GNOME guidelines is preferable disable buttons instead of hide
1786
  ui->actionPush->setEnabled(state);
×
1787
  ui->actionUpdate->setEnabled(state);
×
1788
}
×
1789

1790
/**
1791
 * @brief MainWindow::critical critical message popup wrapper.
1792
 * @param title
1793
 * @param msg
1794
 */
1795
void MainWindow::critical(const QString &title, const QString &msg) {
×
1796
  QMessageBox::critical(this, title, msg);
×
1797
}
×
1798

1799
/**
1800
 * @brief Appends processed command output to the output panel.
1801
 *
1802
 * Appends text to the process output text edit, with per-line numbering,
1803
 * optional command prefix, and color coding for errors vs. success.
1804
 * Handles auto-scrolling and line limits.
1805
 *
1806
 * @param output The raw output text from the command.
1807
 * @param isError true if this is error output (stderr).
1808
 * @param linePrefix Optional command name to prefix each line with.
1809
 */
1810
void MainWindow::appendProcessOutput(const QString &output, bool isError,
×
1811
                                     const QString &linePrefix) {
1812
  if (!QtPassSettings::isShowProcessOutput()) {
×
1813
    return;
×
1814
  }
1815

1816
  QStringList lines = output.split('\n', Qt::SkipEmptyParts);
×
1817
  for (QString &line : lines) {
×
1818
    // Right-trim only: remove trailing CR and whitespace, preserve leading
1819
    // indentation
1820
    line.remove('\r');
×
1821
    while (!line.isEmpty() && line.back().isSpace()) {
×
1822
      line.chop(1);
×
1823
    }
1824
    if (line.isEmpty()) {
×
1825
      continue;
×
1826
    }
1827

1828
    m_outputCounter++;
×
1829
    QString lineNumber = QString::number(m_outputCounter);
×
1830

1831
    QColor textColor =
1832
        isError ? QColor(Qt::red)
×
1833
                : ui->processOutputEdit->palette().color(QPalette::Text);
×
1834
    QString colorHex = textColor.name();
×
1835
    // Apply the optional prefix per line so multi-line output stays
1836
    // attributed to its command (e.g. all 3 lines of a `git push` show
1837
    // "git push: ..." rather than only the first).
1838
    QString prefixed =
1839
        linePrefix.isEmpty() ? line : linePrefix + QStringLiteral(": ") + line;
×
1840
    QString coloredOutput =
1841
        QString("<span style=\"color: %1;\">%2: %3</span>")
×
1842
            .arg(colorHex, lineNumber, prefixed.toHtmlEscaped());
×
1843

1844
    ui->processOutputEdit->append(coloredOutput);
×
1845
  }
1846

1847
  limitOutputLines();
×
1848

1849
  if (m_autoScroll) {
×
1850
    ui->processOutputEdit->verticalScrollBar()->setValue(
×
1851
        ui->processOutputEdit->verticalScrollBar()->maximum());
×
1852
  }
1853
}
1854

1855
/**
1856
 * @brief Handles process output from the Pass executor.
1857
 *
1858
 * Called when any non-sensitive process completes. Filters out password-
1859
 * related commands (pass show, insert, etc.) and delegates to
1860
 * appendProcessOutput.
1861
 *
1862
 * @param output The stdout/stderr text from the process.
1863
 * @param isError true if this is error output (stderr).
1864
 * @param pid The process ID identifying which command ran.
1865
 */
1866
void MainWindow::onProcessOutput(const QString &output, bool isError,
×
1867
                                 Enums::PROCESS pid) {
1868
  appendProcessOutput(output, isError, getProcessName(pid));
×
1869
}
×
1870

1871
/**
1872
 * @brief Maps a process ID to its human-readable command name.
1873
 *
1874
 * Returns static strings for git/pass commands that appear in output.
1875
 * Password-related commands return empty (they are filtered).
1876
 *
1877
 * @param pid The process ID to look up.
1878
 * @return QString with command name, or empty if filtered.
1879
 */
1880
auto MainWindow::getProcessName(Enums::PROCESS pid) -> QString {
×
1881
  switch (pid) {
×
1882
  case Enums::GIT_INIT:
×
1883
    return QStringLiteral("git init"); // no-tr
×
1884
  case Enums::GIT_ADD:
×
1885
    return QStringLiteral("git add"); // no-tr
×
1886
  case Enums::GIT_COMMIT:
×
1887
    return QStringLiteral("git commit"); // no-tr
×
1888
  case Enums::GIT_RM:
×
1889
    return QStringLiteral("git rm"); // no-tr
×
1890
  case Enums::GIT_PULL:
×
1891
    return QStringLiteral("git pull"); // no-tr
×
1892
  case Enums::GIT_PUSH:
×
1893
    return QStringLiteral("git push"); // no-tr
×
1894
  case Enums::GIT_MOVE:
×
1895
    return QStringLiteral("git mv"); // no-tr
×
1896
  case Enums::GIT_COPY:
×
1897
    return QStringLiteral("git cp"); // no-tr
×
1898
  case Enums::PASS_INSERT:
×
1899
    return QStringLiteral("pass insert"); // no-tr
×
1900
  case Enums::PASS_REMOVE:
×
1901
    return QStringLiteral("pass rm"); // no-tr
×
1902
  case Enums::PASS_INIT:
×
1903
    return QStringLiteral("pass init"); // no-tr
×
1904
  case Enums::PASS_MOVE:
×
1905
    return QStringLiteral("pass mv"); // no-tr
×
1906
  case Enums::PASS_COPY:
×
1907
    return QStringLiteral("pass cp"); // no-tr
×
1908
  case Enums::PASS_GREP:
×
1909
    return QStringLiteral("pass grep"); // no-tr
×
1910
  case Enums::GPG_GENKEYS:
×
1911
    return QStringLiteral("gpg --gen-key"); // no-tr
×
1912
  case Enums::PASS_SHOW:
1913
  case Enums::PASS_OTP_GENERATE:
1914
  case Enums::PROCESS_COUNT:
1915
  case Enums::INVALID:
1916
    break;
1917
  }
1918
  return QString();
1919
}
1920

1921
/**
1922
 * @brief Checks if a process ID represents a sensitive operation whose
1923
 * output should not be shown in the process output panel.
1924
 *
1925
 * Password-related commands (pass show, OTP generate, grep, insert)
1926
 * display their output in other UI areas, so we skip them here.
1927
 *
1928
 * @param pid The process ID to check.
1929
 * @return true if the process is sensitive and should be filtered.
1930
 */
1931
auto MainWindow::isSensitiveProcess(Enums::PROCESS pid) -> bool {
×
1932
  switch (pid) {
×
1933
  case Enums::PASS_SHOW:
1934
  case Enums::PASS_OTP_GENERATE:
1935
  case Enums::PASS_GREP:
1936
  case Enums::PASS_INSERT:
1937
    return true;
1938
  case Enums::GIT_INIT:
1939
  case Enums::GIT_ADD:
1940
  case Enums::GIT_COMMIT:
1941
  case Enums::GIT_RM:
1942
  case Enums::GIT_PULL:
1943
  case Enums::GIT_PUSH:
1944
  case Enums::GIT_MOVE:
1945
  case Enums::GIT_COPY:
1946
  case Enums::PASS_REMOVE:
1947
  case Enums::PASS_INIT:
1948
  case Enums::PASS_MOVE:
1949
  case Enums::PASS_COPY:
1950
  case Enums::GPG_GENKEYS:
1951
  case Enums::PROCESS_COUNT:
1952
  case Enums::INVALID:
1953
    break;
1954
  }
1955
  return false;
×
1956
}
1957

1958
/**
1959
 * @brief Updates the visibility of the process output panel.
1960
 *
1961
 * Shows or hides the process output widget based on the user's
1962
 * showProcessOutput setting.
1963
 */
1964
void MainWindow::updateProcessOutputVisibility() {
×
1965
  ui->processOutputWidget->setVisible(QtPassSettings::isShowProcessOutput());
×
1966
}
×
1967

1968
/**
1969
 * @brief Limits the output panel to max lines, trimming old excess.
1970
 *
1971
 * Removes the oldest lines when the document exceeds MaxOutputLines (1000).
1972
 * Called after each append to prevent unbounded growth.
1973
 */
1974
void MainWindow::limitOutputLines() {
×
1975
  QTextDocument *doc = ui->processOutputEdit->document();
×
1976
  int excess = doc->blockCount() - MaxOutputLines;
×
1977
  if (excess <= 0) {
×
1978
    return;
×
1979
  }
1980

1981
  QTextCursor cursor(doc);
×
1982
  cursor.movePosition(QTextCursor::Start);
×
1983
  cursor.movePosition(QTextCursor::NextBlock, QTextCursor::KeepAnchor, excess);
×
1984
  cursor.removeSelectedText();
×
1985
}
×
1986

1987
/**
1988
 * @brief Clears the process output panel.
1989
 *
1990
 * Clears all output, resets the line counter, and re-enables auto-scroll.
1991
 */
1992
void MainWindow::on_clearOutputButton_clicked() {
×
1993
  ui->processOutputEdit->clear();
×
1994
  m_outputCounter = 0;
×
1995
  m_autoScroll = true;
×
1996
}
×
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