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

IJHack / QtPass / 24966395320

26 Apr 2026 08:32PM UTC coverage: 27.593% (-0.03%) from 27.622%
24966395320

push

github

web-flow
fix: resolve focusInput's QLineEdit through findChild to survive widget rebuild (#1190)

A SIGSEGV on first launch was still reproducible after #1187 + #1188:

  $ ./main/qtpass
  Segmentation fault (core dumped)
  #0 QWidget::testAttribute
  #1 QWidget::isVisible
  #2 MainWindow::focusInput
  #3 MainWindow::changeEvent
  ...
  #7 QApplicationPrivate::setActiveWindow

Root cause traced with progressive fprintf probes:

- `this` (MainWindow) is valid and visible.
- `ui->lineEdit` is non-null but points at freed memory.
- `findChild<QLineEdit*>("lineEdit")` returns nullptr — the
  QLineEdit is no longer a child of MainWindow.

The destruction happens during the constructor's
`m_qtPass->init()` -> `MainWindow::config()` ->
`applyWindowFlagsSettings()` path, which runs
`setWindowFlags(...)` + `show()` on the main window. On Qt 6.11
that sequence rebuilds the native window via
`setParent(nullptr, flags)` and the QLineEdit attached to the
centralWidget gets recreated with a different underlying object,
leaving the cached `ui->lineEdit` pointer dangling.

Fix focusInput to look up the live widget by object name
(`findChild<QLineEdit*>("lineEdit")`) instead of trusting the
cached pointer. If the lookup returns nullptr (post-rebuild,
mid-init, etc.) focusInput becomes a safe no-op rather than a
use-after-free. Also:

- Add a first-time `showEvent()` hook that schedules focusInput
  via a queued invokeMethod, replacing the historic
  `QTimer::singleShot(10, this, SLOT(focusInput()))` in the
  constructor — show is the natural point at which the widget
  hierarchy has settled.
- In `changeEvent`, also defer focusInput via queued invokeMethod
  and require both `isActiveWindow()` and `isVisible()` so the
  ActivationChange dispatched from `activateWindow()` before
  `show()` does not run focusInput inline against a not-yet-
  realised hierarchy.

Verified locally: 8 consecutive fresh-launch attempts (timeout 3 s
each, alternating first-instance / sendMessage) pro... (continued)

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

2 existing lines 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);
×
UNCOV
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).
UNCOV
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.
NEW
206
  if (!isVisible()) {
×
207
    return;
208
  }
NEW
209
  QLineEdit *lineEdit = findChild<QLineEdit *>(QStringLiteral("lineEdit"));
×
NEW
210
  if (lineEdit == nullptr || !lineEdit->isVisible()) {
×
211
    return;
212
  }
NEW
213
  lineEdit->selectAll();
×
NEW
214
  lineEdit->setFocus();
×
215
}
216

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

235
/**
236
 * @brief First-show hook: run the initial focusInput() pulse once the
237
 *        window is actually mapped. The widget's internal data is fully
238
 *        initialised by this point, so QLineEdit::selectAll() is safe.
239
 * @param event Show event passed to the base class.
240
 */
NEW
241
void MainWindow::showEvent(QShowEvent *event) {
×
NEW
242
  QMainWindow::showEvent(event);
×
NEW
243
  if (m_initialShowDone) {
×
244
    return;
245
  }
NEW
246
  m_initialShowDone = true;
×
247
  // Defer one event loop tick so the X11/Wayland map round-trip can
248
  // complete before we read widget visibility. Calling focusInput()
249
  // directly here was crashing inside QWidget::testAttribute on first
250
  // run.
NEW
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
  statusBar()->addPermanentWidget(ui->processOutputWidget);
×
302

303
  updateProcessOutputVisibility();
×
304
}
×
305

306
auto MainWindow::getCurrentTreeViewIndex() -> QModelIndex {
×
307
  return ui->treeView->currentIndex();
×
308
}
309

310
void MainWindow::cleanKeygenDialog() {
×
311
  if (this->keygenDialog != nullptr) {
×
312
    this->keygenDialog->close();
×
313
  }
314
  this->keygenDialog = nullptr;
×
315
}
×
316

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

337
  if (isHtml) {
×
338
    QString _text = text;
339
    if (!ui->textBrowser->toPlainText().isEmpty()) {
×
340
      _text = ui->textBrowser->toHtml() + _text;
×
341
    }
342
    ui->textBrowser->setHtml(_text);
×
343
  } else {
344
    ui->textBrowser->setText(text);
×
345
  }
346
}
×
347

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

361
  if (QtPassSettings::isNoLineWrapping()) {
×
362
    ui->textBrowser->setLineWrapMode(QTextBrowser::NoWrap);
×
363
  } else {
364
    ui->textBrowser->setLineWrapMode(QTextBrowser::WidgetWidth);
×
365
  }
366
}
×
367

368
void MainWindow::applyWindowFlagsSettings() {
×
369
  if (QtPassSettings::isAlwaysOnTop()) {
×
370
    Qt::WindowFlags flags = windowFlags();
371
    this->setWindowFlags(flags | Qt::WindowStaysOnTopHint);
×
372
  } else {
373
    this->setWindowFlags(Qt::Window);
×
374
  }
375
  this->show();
×
376
}
×
377

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

395
  if (m_qtPass->isFreshStart()) {
×
396
    d->wizard(); // run initial setup wizard for first-time configuration
×
397
  }
398
  if (d->exec()) {
×
399
    if (d->result() == QDialog::Accepted) {
×
400
      applyTextBrowserSettings();
×
401
      applyWindowFlagsSettings();
×
402

403
      updateProfileBox();
×
404
      const QString passStore = QtPassSettings::getPassStore();
×
405
      proxyModel.setStore(passStore);
×
406
      ui->treeView->setRootIndex(
×
407
          proxyModel.mapFromSource(model.setRootPath(passStore)));
×
408
      deselect();
×
409
      ui->treeView->setCurrentIndex(QModelIndex());
×
410

411
      if (m_qtPass->isFreshStart() && !Util::configIsValid()) {
×
412
        config();
×
413
      }
414
      QtPassSettings::getPass()->updateEnv();
×
415
      clearPanelTimer.setInterval(MS_PER_SECOND *
×
416
                                  QtPassSettings::getAutoclearPanelSeconds());
×
417
      m_qtPass->setClipboardTimer();
×
418

419
      updateGitButtonVisibility();
×
420
      updateOtpButtonVisibility();
×
421
      updateGrepButtonVisibility();
×
422
      updateProcessOutputVisibility();
×
423
      if (QtPassSettings::isUseTrayIcon() && tray == nullptr) {
×
424
        initTrayIcon();
×
425
      } else if (!QtPassSettings::isUseTrayIcon() && tray != nullptr) {
×
426
        destroyTrayIcon();
×
427
      }
428
    }
429

430
    m_qtPass->setFreshStart(false);
×
431
  }
432
}
×
433

434
/**
435
 * @brief MainWindow::onUpdate do a git pull
436
 */
437
void MainWindow::onUpdate(bool block) {
×
438
  ui->statusBar->showMessage(tr("Updating password-store"), 2000);
×
439
  if (block) {
×
440
    QtPassSettings::getPass()->GitPull_b();
×
441
  } else {
442
    QtPassSettings::getPass()->GitPull();
×
443
  }
444
}
×
445

446
/**
447
 * @brief MainWindow::onPush do a git push
448
 */
449
void MainWindow::onPush() {
×
450
  if (QtPassSettings::isUseGit()) {
×
451
    ui->statusBar->showMessage(tr("Updating password-store"), 2000);
×
452
    QtPassSettings::getPass()->GitPush();
×
453
  }
454
}
×
455

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

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

497
/**
498
 * @brief MainWindow::on_treeView_doubleClicked when doubleclicked on
499
 * TreeViewItem, open the edit Window
500
 * @param index
501
 */
502
void MainWindow::on_treeView_doubleClicked(const QModelIndex &index) {
×
503
  QFileInfo fileOrFolder =
504
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
505

506
  if (fileOrFolder.isFile()) {
×
507
    editPassword(getFile(index, true));
×
508
  }
509
}
×
510

511
/**
512
 * @brief MainWindow::deselect clear the selection, password and copy buffer
513
 */
514
void MainWindow::deselect() {
×
515
  currentDir = "";
×
516
  m_qtPass->clearClipboard();
×
517
  ui->treeView->clearSelection();
×
518
  ui->actionEdit->setEnabled(false);
×
519
  ui->actionDelete->setEnabled(false);
×
520
  ui->passwordName->setText("");
×
521
  clearPanel(false);
×
522
}
×
523

524
void MainWindow::executeWrapperStarted() {
×
525
  clearTemplateWidgets();
×
526
  ui->textBrowser->clear();
×
527
  setUiElementsEnabled(false);
×
528
  clearPanelTimer.stop();
×
529
  if (QtPassSettings::isShowProcessOutput()) {
×
530
    ui->processOutputWidget->setVisible(true);
×
531
  }
532
}
×
533

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

554
  // set clipped text
555
  m_qtPass->setClippedText(password, p_output);
×
556

557
  // first clear the current view:
558
  clearTemplateWidgets();
×
559

560
  // show what is needed:
561
  if (QtPassSettings::isHideContent()) {
×
562
    output = "***" + tr("Content hidden") + "***";
×
563
  } else if (!QtPassSettings::isDisplayAsIs()) {
×
564
    if (!password.isEmpty()) {
×
565
      // set the password, it is hidden if needed in addToGridLayout
566
      addToGridLayout(0, tr("Password"), password);
×
567
    }
568

569
    NamedValues namedValues = fileContent.getNamedValues();
×
570
    for (int j = 0; j < namedValues.length(); ++j) {
×
571
      const NamedValue &nv = namedValues.at(j);
572
      addToGridLayout(j + 1, nv.name, nv.value);
×
573
    }
574
    if (ui->gridLayout->count() == 0) {
×
575
      ui->verticalLayoutPassword->setSpacing(0);
×
576
    } else {
577
      ui->verticalLayoutPassword->setSpacing(6);
×
578
    }
579

580
    output = fileContent.getRemainingDataForDisplay();
×
581
  }
582

583
  if (QtPassSettings::isUseAutoclearPanel()) {
×
584
    clearPanelTimer.start();
×
585
  }
586

587
  emit passShowHandlerFinished(output);
×
588
  setUiElementsEnabled(true);
×
589
}
×
590

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

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

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

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

691
  if (QtPassSettings::isAlwaysOnTop()) {
×
692
    Qt::WindowFlags flags = windowFlags();
693
    setWindowFlags(flags | Qt::WindowStaysOnTopHint);
×
694
    show();
×
695
  }
696

697
  if (QtPassSettings::isUseTrayIcon() && tray == nullptr) {
×
698
    initTrayIcon();
×
699
    if (QtPassSettings::isStartMinimized()) {
×
700
      // since we are still in constructor, can't directly hide
701
      QTimer::singleShot(10, this, SLOT(hide()));
×
702
    }
703
  } else if (!QtPassSettings::isUseTrayIcon() && tray != nullptr) {
×
704
    destroyTrayIcon();
×
705
  }
706
}
×
707

708
/**
709
 * @brief MainWindow::on_configButton_clicked run Mainwindow::config
710
 */
711
void MainWindow::onConfig() { config(); }
×
712

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

730
/**
731
 * @brief MainWindow::onTimeoutSearch Fired when search is finished or too much
732
 * time from two keypresses is elapsed
733
 */
734
void MainWindow::onTimeoutSearch() {
×
735
  QString query = ui->lineEdit->text();
×
736

737
  if (query.isEmpty()) {
×
738
    ui->treeView->collapseAll();
×
739
    deselect();
×
740
  }
741

742
  query.replace(QStringLiteral(" "), ".*");
×
743
  QRegularExpression regExp(query, QRegularExpression::CaseInsensitiveOption);
×
744
  proxyModel.setFilterRegularExpression(regExp);
×
745
  ui->treeView->setRootIndex(proxyModel.mapFromSource(
×
746
      model.setRootPath(QtPassSettings::getPassStore())));
×
747

748
  if (proxyModel.rowCount() > 0 && !query.isEmpty()) {
×
749
    selectFirstFile();
×
750
  } else {
751
    ui->actionEdit->setEnabled(false);
×
752
    ui->actionDelete->setEnabled(false);
×
753
  }
754
}
×
755

756
/**
757
 * @brief MainWindow::on_lineEdit_returnPressed get searching
758
 *
759
 * Select the first possible file in the tree
760
 */
761
void MainWindow::on_lineEdit_returnPressed() {
×
762
#ifdef QT_DEBUG
763
  dbg() << "on_lineEdit_returnPressed" << proxyModel.rowCount();
764
#endif
765

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

790
  if (proxyModel.rowCount() > 0) {
×
791
    selectFirstFile();
×
792
    on_treeView_clicked(ui->treeView->currentIndex());
×
793
  }
794
}
795

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

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

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

904
/**
905
 * @brief MainWindow::selectFirstFile select the first possible file in the
906
 * tree
907
 */
908
void MainWindow::selectFirstFile() {
×
909
  QModelIndex index = proxyModel.mapFromSource(
×
910
      model.setRootPath(QtPassSettings::getPassStore()));
×
911
  index = firstFile(index);
×
912
  ui->treeView->setCurrentIndex(index);
×
913
}
×
914

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

935
/**
936
 * @brief MainWindow::setPassword open passworddialog
937
 * @param file which pgp file
938
 * @param isNew insert (not update)
939
 */
940
void MainWindow::setPassword(const QString &file, bool isNew) {
×
941
  PasswordDialog d(file, isNew, this);
×
942

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

959
  if (!d.exec()) {
×
960
    ui->treeView->setFocus();
×
961
  }
962
}
×
963

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

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

999
  QFileInfo fileOrFolder =
1000
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
1001
  QString file = "";
×
1002
  bool isDir = false;
1003

1004
  if (fileOrFolder.isFile()) {
×
1005
    file = getFile(ui->treeView->currentIndex(), true);
×
1006
  } else {
1007
    file = Util::getDir(ui->treeView->currentIndex(), true, model, proxyModel);
×
1008
    isDir = true;
1009
  }
1010

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

1029
  if (QMessageBox::question(
×
1030
          this, isDir ? tr("Delete folder?") : tr("Delete password?"),
×
1031
          tr("Are you sure you want to delete %1%2?")
×
1032
              .arg(QDir::separator() + file, isDir ? dirMessage : "?"),
×
1033
          QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) {
1034
    return;
1035
  }
1036

1037
  QtPassSettings::getPass()->Remove(file, isDir);
×
1038
}
×
1039

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

1055
/**
1056
 * @brief MainWindow::onEdit try and edit (selected) password.
1057
 */
1058
void MainWindow::onEdit() {
×
1059
  QString file = getFile(ui->treeView->currentIndex(), true);
×
1060
  editPassword(file);
×
1061
}
×
1062

1063
/**
1064
 * @brief MainWindow::userDialog see MainWindow::onUsers()
1065
 * @param dir folder to edit users for.
1066
 */
1067
void MainWindow::userDialog(const QString &dir) {
×
1068
  if (!dir.isEmpty()) {
×
1069
    currentDir = dir;
×
1070
  }
1071
  onUsers();
×
1072
}
×
1073

1074
/**
1075
 * @brief MainWindow::onUsers edit users for the current
1076
 * folder,
1077
 * gets lists and opens UserDialog.
1078
 */
1079
void MainWindow::onUsers() {
×
1080
  QString dir =
1081
      currentDir.isEmpty()
1082
          ? Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel)
×
1083
          : currentDir;
×
1084

1085
  UsersDialog d(dir, this);
×
1086
  if (!d.exec()) {
×
1087
    ui->treeView->setFocus();
×
1088
  }
1089
}
×
1090

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

1107
/**
1108
 * @brief MainWindow::generateKeyPair internal gpg keypair generator . .
1109
 * @param batch
1110
 * @param keygenWindow
1111
 */
1112
void MainWindow::generateKeyPair(const QString &batch, QDialog *keygenWindow) {
×
1113
  keygenDialog = keygenWindow;
×
1114
  emit generateGPGKeyPair(batch);
×
1115
}
×
1116

1117
/**
1118
 * @brief MainWindow::updateProfileBox update the list of profiles, optionally
1119
 * select a more appropriate one to view too
1120
 */
1121
void MainWindow::updateProfileBox() {
×
1122
  QHash<QString, QHash<QString, QString>> profiles =
1123
      QtPassSettings::getProfiles();
×
1124

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

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

1171
  ui->lineEdit->clear();
×
1172

1173
  QtPassSettings::setProfile(name);
×
1174

1175
  QtPassSettings::setPassStore(
×
1176
      QtPassSettings::getProfiles().value(name).value("path"));
×
1177
  QtPassSettings::setPassSigningKey(
×
1178
      QtPassSettings::getProfiles().value(name).value("signingKey"));
×
1179
  ui->statusBar->showMessage(tr("Profile changed to %1").arg(name), 2000);
×
1180

1181
  QtPassSettings::getPass()->updateEnv();
×
1182

1183
  const QString passStore = QtPassSettings::getPassStore();
×
1184
  proxyModel.setStore(passStore);
×
1185
  ui->treeView->setRootIndex(
×
1186
      proxyModel.mapFromSource(model.setRootPath(passStore)));
×
1187
  deselect();
×
1188
  ui->treeView->setCurrentIndex(QModelIndex());
×
1189
}
1190

1191
/**
1192
 * @brief MainWindow::initTrayIcon show a nice tray icon on systems that
1193
 * support
1194
 * it
1195
 */
1196
void MainWindow::initTrayIcon() {
×
1197
  this->tray = new TrayIcon(this);
×
1198
  // Setup tray icon
1199

1200
  if (tray == nullptr) {
1201
#ifdef QT_DEBUG
1202
    dbg() << "Allocating tray icon failed.";
1203
#endif
1204
    return;
1205
  }
1206

1207
  if (!tray->getIsAllocated()) {
×
1208
    destroyTrayIcon();
×
1209
  }
1210
}
1211

1212
/**
1213
 * @brief MainWindow::destroyTrayIcon remove that pesky tray icon
1214
 */
1215
void MainWindow::destroyTrayIcon() {
×
1216
  delete this->tray;
×
1217
  tray = nullptr;
×
1218
}
×
1219

1220
/**
1221
 * @brief MainWindow::closeEvent hide or quit
1222
 * @param event
1223
 */
1224
void MainWindow::closeEvent(QCloseEvent *event) {
×
1225
  if (QtPassSettings::isHideOnClose()) {
×
1226
    this->hide();
×
1227
    event->ignore();
1228
  } else {
1229
    m_qtPass->clearClipboard();
×
1230

1231
    QtPassSettings::setGeometry(saveGeometry());
×
1232
    QtPassSettings::setSavestate(saveState());
×
1233
    QtPassSettings::setMaximized(isMaximized());
×
1234
    if (!isMaximized()) {
×
1235
      QtPassSettings::setPos(pos());
×
1236
      QtPassSettings::setSize(size());
×
1237
    }
1238
    event->accept();
1239
  }
1240
}
×
1241

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

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

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

1298
  ui->treeView->setCurrentIndex(index);
×
1299

1300
  QPoint globalPos = ui->treeView->viewport()->mapToGlobal(pos);
×
1301

1302
  QFileInfo fileOrFolder =
1303
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
1304

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

1337
      QMenu *shareMenu = new QMenu(tr("Share"), &contextMenu);
×
1338
      contextMenu.addMenu(shareMenu);
×
1339

1340
      QString gpgIdPath = Pass::getGpgIdPath(dirPath);
×
1341
      bool gpgIdExists = !gpgIdPath.isEmpty() && QFile(gpgIdPath).exists();
×
1342

1343
      QString exePath = QtPassSettings::isUsePass()
×
1344
                            ? QtPassSettings::getPassExecutable()
×
1345
                            : QtPassSettings::getGpgExecutable();
×
1346
      bool gpgAvailable = !exePath.isEmpty() && (exePath.startsWith("wsl ") ||
×
1347
                                                 QFile(exePath).exists());
×
1348

1349
      QAction *reencrypt = shareMenu->addAction(tr("Re-encrypt all passwords"));
×
1350
      reencrypt->setEnabled(gpgIdExists && gpgAvailable);
×
1351
      connect(reencrypt, &QAction::triggered, this,
×
1352
              [this, dirPath]() { reencryptPath(dirPath); });
×
1353

1354
      QAction *exportKey = shareMenu->addAction(tr("Export my public key..."));
×
1355
      exportKey->setEnabled(gpgAvailable);
×
1356
      connect(exportKey, &QAction::triggered, this,
×
1357
              &MainWindow::exportPublicKey);
×
1358

1359
      QAction *addRecipientAction =
1360
          shareMenu->addAction(tr("Add recipient..."));
×
1361
      addRecipientAction->setEnabled(gpgIdExists && gpgAvailable);
×
1362
      connect(addRecipientAction, &QAction::triggered, this,
×
1363
              [this, dirPath]() { addRecipient(dirPath); });
×
1364

1365
      QAction *shareHelp = shareMenu->addAction(tr("What is this?"));
×
1366
      connect(shareHelp, &QAction::triggered, this, &MainWindow::showShareHelp);
×
1367
    }
1368
  }
1369
  contextMenu.exec(globalPos);
×
1370
}
×
1371

1372
/**
1373
 * @brief MainWindow::showBrowserContextMenu show us the context menu in
1374
 * password window
1375
 * @param pos
1376
 */
1377
void MainWindow::showBrowserContextMenu(const QPoint &pos) {
×
1378
  QMenu *contextMenu = ui->textBrowser->createStandardContextMenu(pos);
×
1379
  QPoint globalPos = ui->textBrowser->viewport()->mapToGlobal(pos);
×
1380

1381
  contextMenu->exec(globalPos);
×
1382
  delete contextMenu;
×
1383
}
×
1384

1385
/**
1386
 * @brief MainWindow::openFolder open the folder in the default file manager
1387
 */
1388
void MainWindow::openFolder() {
×
1389
  QString dir =
1390
      Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel);
×
1391

1392
  QString path = QDir::toNativeSeparators(dir);
×
1393
  QDesktopServices::openUrl(QUrl::fromLocalFile(path));
×
1394
}
×
1395

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

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

1457
/**
1458
 * @brief MainWindow::editPassword read password and open edit window via
1459
 * MainWindow::onEdit()
1460
 */
1461
void MainWindow::editPassword(const QString &file) {
×
1462
  if (!file.isEmpty()) {
×
1463
    if (QtPassSettings::isUseGit() && QtPassSettings::isAutoPull()) {
×
1464
      onUpdate(true);
×
1465
    }
1466
    setPassword(file, false);
×
1467
  }
1468
}
×
1469

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

1482
  QString newName =
1483
      QInputDialog::getText(this, tr("Rename file"), tr("Rename File To: "),
×
1484
                            QLineEdit::Normal, fileName, &ok);
×
1485
  if (!ok || newName.isEmpty()) {
×
1486
    return;
1487
  }
1488
  QString newFile = QDir(filePath).filePath(newName);
×
1489
  QtPassSettings::getPass()->Move(file, newFile);
×
1490
}
1491

1492
/**
1493
 * @brief MainWindow::clearTemplateWidgets empty the template widget fields in
1494
 * the UI
1495
 */
1496
void MainWindow::clearTemplateWidgets() {
×
1497
  while (ui->gridLayout->count() > 0) {
×
1498
    QLayoutItem *item = ui->gridLayout->takeAt(0);
×
1499
    delete item->widget();
×
1500
    delete item;
×
1501
  }
1502
  ui->verticalLayoutPassword->setSpacing(0);
×
1503
}
×
1504

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

1517
  if (fileOrFolder.isFile()) {
×
1518
    QString file = getFile(ui->treeView->currentIndex(), true);
×
1519
    // Disconnect any previous connection to avoid accumulation
1520
    disconnect(QtPassSettings::getPass(), &Pass::finishedShow, this,
×
1521
               &MainWindow::passwordFromFileToClipboard);
1522
    connect(QtPassSettings::getPass(), &Pass::finishedShow, this,
×
1523
            &MainWindow::passwordFromFileToClipboard);
×
1524
    QtPassSettings::getPass()->Show(file);
×
1525
  }
1526
}
×
1527

1528
void MainWindow::passwordFromFileToClipboard(const QString &text) {
×
1529
  QStringList tokens = text.split('\n');
×
1530
  m_qtPass->copyTextToClipboard(tokens[0]);
×
1531
}
×
1532

1533
/**
1534
 * @brief MainWindow::addToGridLayout add a field to the template grid
1535
 * @param position
1536
 * @param field
1537
 * @param value
1538
 */
1539
void MainWindow::addToGridLayout(int position, const QString &field,
×
1540
                                 const QString &value) {
1541
  QString trimmedField = field.trimmed();
1542
  QString trimmedValue = value.trimmed();
1543

1544
  const QString buttonStyle =
1545
      "border-style: none; background: transparent; padding: 0; margin: 0; "
1546
      "icon-size: 16px; color: inherit;";
×
1547

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

1559
    fieldLabel->setStyleSheet(buttonStyle);
×
1560
    frame->layout()->addWidget(fieldLabel);
×
1561
  }
1562

1563
  if (QtPassSettings::isUseQrencode()) {
×
1564
    auto *qrbutton = new QPushButtonAsQRCode(trimmedValue, this);
×
1565
    connect(qrbutton, &QPushButtonAsQRCode::clicked, m_qtPass,
×
1566
            &QtPass::showTextAsQRCode);
×
1567
    qrbutton->setStyleSheet(buttonStyle);
×
1568
    frame->layout()->addWidget(qrbutton);
×
1569
  }
1570

1571
  // set the echo mode to password, if the field is "password"
1572
  const QString lineStyle =
1573
      QtPassSettings::isUseMonospace()
×
1574
          ? "border-style: none; background: transparent; font-family: "
1575
            "monospace;"
1576
          : "border-style: none; background: transparent;";
×
1577

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

1608
  frame->setStyleSheet(
×
1609
      ".QFrame{border: 1px solid lightgrey; border-radius: 5px;}");
1610

1611
  // set into the layout
1612
  ui->gridLayout->addWidget(new QLabel(trimmedField), position, 0);
×
1613
  ui->gridLayout->addWidget(frame, position, 1);
×
1614
}
×
1615

1616
/**
1617
 * @brief Displays message in status bar
1618
 *
1619
 * @param msg     text to be displayed
1620
 * @param timeout time for which msg shall be visible
1621
 */
1622
void MainWindow::showStatusMessage(const QString &msg, int timeout) {
×
1623
  ui->statusBar->showMessage(msg, timeout);
×
1624
}
×
1625

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

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

1648
  if (ret != QMessageBox::Yes)
×
1649
    return;
1650

1651
  // Prevent double execution - use same method as startReencryptPath
1652
  setUiElementsEnabled(false);
×
1653
  ui->treeView->setDisabled(true);
×
1654

1655
  QtPassSettings::getImitatePass()->reencryptPath(
×
1656
      QDir::cleanPath(QDir(dir).absolutePath()));
×
1657
}
×
1658

1659
/**
1660
 * @brief MainWindow::startReencryptPath disable ui elements and treeview
1661
 */
1662
void MainWindow::startReencryptPath() {
×
1663
  setUiElementsEnabled(false);
×
1664
  ui->treeView->setDisabled(true);
×
1665
}
×
1666

1667
/**
1668
 * @brief MainWindow::endReencryptPath re-enable ui elements
1669
 */
1670
void MainWindow::endReencryptPath() { setUiElementsEnabled(true); }
×
1671

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

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

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

1748
void MainWindow::updateGitButtonVisibility() {
×
1749
  if (!QtPassSettings::isUseGit() ||
×
1750
      (QtPassSettings::getGitExecutable().isEmpty() &&
×
1751
       QtPassSettings::getPassExecutable().isEmpty())) {
×
1752
    enableGitButtons(false);
×
1753
  } else {
1754
    enableGitButtons(true);
×
1755
  }
1756
}
×
1757

1758
void MainWindow::updateOtpButtonVisibility() {
×
1759
#if defined(Q_OS_WIN) || defined(__APPLE__)
1760
  ui->actionOtp->setVisible(false);
1761
#endif
1762
  if (!QtPassSettings::isUseOtp()) {
×
1763
    ui->actionOtp->setEnabled(false);
×
1764
  } else {
1765
    ui->actionOtp->setEnabled(true);
×
1766
  }
1767
}
×
1768

1769
void MainWindow::updateGrepButtonVisibility() {
×
1770
  const bool enabled = QtPassSettings::isUseGrepSearch();
×
1771
  ui->grepButton->setVisible(enabled);
×
1772
  ui->grepCaseButton->setVisible(enabled);
×
1773
  if (!enabled && m_grepMode) {
×
1774
    ui->grepButton->setChecked(false);
×
1775
  }
1776
}
×
1777

1778
void MainWindow::enableGitButtons(const bool &state) {
×
1779
  // Following GNOME guidelines is preferable disable buttons instead of hide
1780
  ui->actionPush->setEnabled(state);
×
1781
  ui->actionUpdate->setEnabled(state);
×
1782
}
×
1783

1784
/**
1785
 * @brief MainWindow::critical critical message popup wrapper.
1786
 * @param title
1787
 * @param msg
1788
 */
1789
void MainWindow::critical(const QString &title, const QString &msg) {
×
1790
  QMessageBox::critical(this, title, msg);
×
1791
}
×
1792

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

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

1822
    m_outputCounter++;
×
1823
    QString lineNumber = QString::number(m_outputCounter);
×
1824

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

1838
    ui->processOutputEdit->append(coloredOutput);
×
1839
  }
1840

1841
  limitOutputLines();
×
1842

1843
  if (m_autoScroll) {
×
1844
    ui->processOutputEdit->verticalScrollBar()->setValue(
×
1845
        ui->processOutputEdit->verticalScrollBar()->maximum());
×
1846
  }
1847
}
1848

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

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

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

1952
/**
1953
 * @brief Updates the visibility of the process output panel.
1954
 *
1955
 * Shows or hides the process output widget based on the user's
1956
 * showProcessOutput setting.
1957
 */
1958
void MainWindow::updateProcessOutputVisibility() {
×
1959
  ui->processOutputWidget->setVisible(QtPassSettings::isShowProcessOutput());
×
1960
}
×
1961

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

1975
  QTextCursor cursor(doc);
×
1976
  cursor.movePosition(QTextCursor::Start);
×
1977
  cursor.movePosition(QTextCursor::NextBlock, QTextCursor::KeepAnchor, excess);
×
1978
  cursor.removeSelectedText();
×
1979
}
×
1980

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