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

IJHack / QtPass / 24964110488

26 Apr 2026 06:39PM UTC coverage: 27.622% (-0.03%) from 27.652%
24964110488

push

github

web-flow
Fix: add ui null check in focusInput to prevent segfault (#1189)

When focusInput() is triggered during a nested event loop (e.g., ConfigDialog
wizard on first-run) or via single-instance wake-up, the timer can fire before
the MainWindow is fully constructed. The existing fix checked ui->lineEdit but not
ui itself, causing a segfault on null pointer dereference.

Add ui null check before dereferencing ui->lineEdit.

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

2 existing lines in 1 file now uncovered.

1825 of 6607 relevant lines covered (27.62%)

26.95 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 <QMenu>
33
#include <QMessageBox>
34
#include <QScrollBar>
35
#include <QShortcut>
36
#include <QTextCursor>
37
#include <QTimer>
38
#include <QTreeWidget>
39
#include <utility>
40

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

56
  m_qtPass = new QtPass(this);
×
57

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

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

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

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

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

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

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

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

111
  updateProfileBox();
×
112

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

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

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

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

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

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

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

162
  setUiElementsEnabled(true);
×
163

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

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

172
  // Schedule the initial focus pulse only after init() has returned. init()
173
  // can run a nested event loop (e.g. ConfigDialog::wizard for first-run
174
  // setup), and a timer scheduled before that loop would fire focusInput()
175
  // against a not-yet-shown window — QLineEdit::selectAll then crashes
176
  // inside Qt because the widget hasn't been parented into a visible
177
  // top-level yet.
178
  QTimer::singleShot(10, this, SLOT(focusInput()));
179
}
×
180

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

183
/**
184
 * @brief MainWindow::focusInput selects any text (if applicable) in the search
185
 * box and sets focus to it. Allows for easy searching, called at application
186
 * start and when receiving empty message in MainWindow::messageAvailable when
187
 * compiled with SINGLE_APP=1 (default).
188
 */
189
void MainWindow::focusInput() {
×
NEW
190
  if (!ui || !ui->lineEdit || !ui->lineEdit->isVisible()) {
×
191
    return;
192
  }
193
  ui->lineEdit->selectAll();
×
194
  ui->lineEdit->setFocus();
×
195
}
196

197
/**
198
 * @brief MainWindow::changeEvent sets focus to the search box
199
 * @param event
200
 */
201
void MainWindow::changeEvent(QEvent *event) {
×
202
  QWidget::changeEvent(event);
×
203
  if (event->type() == QEvent::ActivationChange) {
×
204
    if (isActiveWindow()) {
×
205
      focusInput();
×
206
    }
207
  }
208
}
×
209

210
/**
211
 * @brief MainWindow::initToolBarButtons init main ToolBar and connect actions
212
 */
213
void MainWindow::initToolBarButtons() {
×
214
  connect(ui->actionAddPassword, &QAction::triggered, this,
×
215
          &MainWindow::addPassword);
×
216
  connect(ui->actionAddFolder, &QAction::triggered, this,
×
217
          &MainWindow::addFolder);
×
218
  connect(ui->actionEdit, &QAction::triggered, this, &MainWindow::onEdit);
×
219
  connect(ui->actionDelete, &QAction::triggered, this, &MainWindow::onDelete);
×
220
  connect(ui->actionPush, &QAction::triggered, this, &MainWindow::onPush);
×
221
  connect(ui->actionUpdate, &QAction::triggered, this, &MainWindow::onUpdate);
×
222
  connect(ui->actionUsers, &QAction::triggered, this, &MainWindow::onUsers);
×
223
  connect(ui->actionConfig, &QAction::triggered, this, &MainWindow::onConfig);
×
224
  connect(ui->actionOtp, &QAction::triggered, this, &MainWindow::onOtp);
×
225

226
  ui->actionAddPassword->setIcon(
×
227
      QIcon::fromTheme("document-new", QIcon(":/icons/document-new.svg")));
×
228
  ui->actionAddFolder->setIcon(
×
229
      QIcon::fromTheme("folder-new", QIcon(":/icons/folder-new.svg")));
×
230
  ui->actionEdit->setIcon(QIcon::fromTheme(
×
231
      "document-properties", QIcon(":/icons/document-properties.svg")));
×
232
  ui->actionDelete->setIcon(
×
233
      QIcon::fromTheme("edit-delete", QIcon(":/icons/edit-delete.svg")));
×
234
  ui->actionPush->setIcon(
×
235
      QIcon::fromTheme("go-up", QIcon(":/icons/go-top.svg")));
×
236
  ui->actionUpdate->setIcon(
×
237
      QIcon::fromTheme("go-down", QIcon(":/icons/go-bottom.svg")));
×
238
  ui->actionUsers->setIcon(QIcon::fromTheme(
×
239
      "x-office-address-book", QIcon(":/icons/x-office-address-book.svg")));
×
240
  ui->actionConfig->setIcon(QIcon::fromTheme(
×
241
      "applications-system", QIcon(":/icons/applications-system.svg")));
×
242
}
×
243

244
/**
245
 * @brief MainWindow::initStatusBar init statusBar with default message and logo
246
 */
247
void MainWindow::initStatusBar() {
×
248
  ui->statusBar->showMessage(tr("Welcome to QtPass %1").arg(VERSION), 2000);
×
249

250
  QPixmap logo = QPixmap::fromImage(QImage(":/artwork/icon.svg"))
×
251
                     .scaledToHeight(statusBar()->height());
×
252
  auto *logoApp = new QLabel(statusBar());
×
253
  logoApp->setPixmap(logo);
×
254
  statusBar()->addPermanentWidget(logoApp);
×
255

256
  statusBar()->addPermanentWidget(ui->processOutputWidget);
×
257

258
  updateProcessOutputVisibility();
×
259
}
×
260

261
auto MainWindow::getCurrentTreeViewIndex() -> QModelIndex {
×
262
  return ui->treeView->currentIndex();
×
263
}
264

265
void MainWindow::cleanKeygenDialog() {
×
266
  if (this->keygenDialog != nullptr) {
×
267
    this->keygenDialog->close();
×
268
  }
269
  this->keygenDialog = nullptr;
×
270
}
×
271

272
/**
273
 * @brief Displays the given text in the main window text browser, optionally
274
 * marking it as an error and/or rendering it as HTML.
275
 * @example
276
 * MainWindow window;
277
 * window.flashText("Operation completed.", false, false);
278
 *
279
 * @param const QString &text - The text content to display.
280
 * @param const bool isError - If true, sets the text color to red before
281
 * displaying the text.
282
 * @param const bool isHtml - If true, treats the text as HTML and appends it to
283
 * the existing HTML content.
284
 * @return void - No return value.
285
 */
286
void MainWindow::flashText(const QString &text, const bool isError,
×
287
                           const bool isHtml) {
288
  if (isError) {
×
289
    ui->textBrowser->setTextColor(Qt::red);
×
290
  }
291

292
  if (isHtml) {
×
293
    QString _text = text;
294
    if (!ui->textBrowser->toPlainText().isEmpty()) {
×
295
      _text = ui->textBrowser->toHtml() + _text;
×
296
    }
297
    ui->textBrowser->setHtml(_text);
×
298
  } else {
299
    ui->textBrowser->setText(text);
×
300
  }
301
}
×
302

303
/**
304
 * @brief MainWindow::config pops up the configuration screen and handles all
305
 * inter-window communication
306
 */
307
void MainWindow::applyTextBrowserSettings() {
×
308
  if (QtPassSettings::isUseMonospace()) {
×
309
    QFont monospace("Monospace");
×
310
    monospace.setStyleHint(QFont::Monospace);
×
311
    ui->textBrowser->setFont(monospace);
×
312
  } else {
×
313
    ui->textBrowser->setFont(QFont());
×
314
  }
315

316
  if (QtPassSettings::isNoLineWrapping()) {
×
317
    ui->textBrowser->setLineWrapMode(QTextBrowser::NoWrap);
×
318
  } else {
319
    ui->textBrowser->setLineWrapMode(QTextBrowser::WidgetWidth);
×
320
  }
321
}
×
322

323
void MainWindow::applyWindowFlagsSettings() {
×
324
  if (QtPassSettings::isAlwaysOnTop()) {
×
325
    Qt::WindowFlags flags = windowFlags();
326
    this->setWindowFlags(flags | Qt::WindowStaysOnTopHint);
×
327
  } else {
328
    this->setWindowFlags(Qt::Window);
×
329
  }
330
  this->show();
×
331
}
×
332

333
/**
334
 * @brief Opens and processes the application configuration dialog, then applies
335
 * any accepted settings.
336
 * @example
337
 * config();
338
 *
339
 * @return void - This function does not return a value.
340
 */
341
void MainWindow::config() {
×
342
  QScopedPointer<ConfigDialog> d(new ConfigDialog(this));
×
343
  d->setModal(true);
×
344
  // Automatically default to pass if it's available
345
  if (m_qtPass->isFreshStart() &&
×
346
      QFile(QtPassSettings::getPassExecutable()).exists()) {
×
347
    QtPassSettings::setUsePass(true);
×
348
  }
349

350
  if (m_qtPass->isFreshStart()) {
×
351
    d->wizard(); // run initial setup wizard for first-time configuration
×
352
  }
353
  if (d->exec()) {
×
354
    if (d->result() == QDialog::Accepted) {
×
355
      applyTextBrowserSettings();
×
356
      applyWindowFlagsSettings();
×
357

358
      updateProfileBox();
×
359
      const QString passStore = QtPassSettings::getPassStore();
×
360
      proxyModel.setStore(passStore);
×
361
      ui->treeView->setRootIndex(
×
362
          proxyModel.mapFromSource(model.setRootPath(passStore)));
×
363
      deselect();
×
364
      ui->treeView->setCurrentIndex(QModelIndex());
×
365

366
      if (m_qtPass->isFreshStart() && !Util::configIsValid()) {
×
367
        config();
×
368
      }
369
      QtPassSettings::getPass()->updateEnv();
×
370
      clearPanelTimer.setInterval(MS_PER_SECOND *
×
371
                                  QtPassSettings::getAutoclearPanelSeconds());
×
372
      m_qtPass->setClipboardTimer();
×
373

374
      updateGitButtonVisibility();
×
375
      updateOtpButtonVisibility();
×
376
      updateGrepButtonVisibility();
×
377
      updateProcessOutputVisibility();
×
378
      if (QtPassSettings::isUseTrayIcon() && tray == nullptr) {
×
379
        initTrayIcon();
×
380
      } else if (!QtPassSettings::isUseTrayIcon() && tray != nullptr) {
×
381
        destroyTrayIcon();
×
382
      }
383
    }
384

385
    m_qtPass->setFreshStart(false);
×
386
  }
387
}
×
388

389
/**
390
 * @brief MainWindow::onUpdate do a git pull
391
 */
392
void MainWindow::onUpdate(bool block) {
×
393
  ui->statusBar->showMessage(tr("Updating password-store"), 2000);
×
394
  if (block) {
×
395
    QtPassSettings::getPass()->GitPull_b();
×
396
  } else {
397
    QtPassSettings::getPass()->GitPull();
×
398
  }
399
}
×
400

401
/**
402
 * @brief MainWindow::onPush do a git push
403
 */
404
void MainWindow::onPush() {
×
405
  if (QtPassSettings::isUseGit()) {
×
406
    ui->statusBar->showMessage(tr("Updating password-store"), 2000);
×
407
    QtPassSettings::getPass()->GitPush();
×
408
  }
409
}
×
410

411
/**
412
 * @brief MainWindow::getFile get the selected file path
413
 * @param index
414
 * @param forPass returns relative path without '.gpg' extension
415
 * @return path
416
 * @return
417
 */
418
auto MainWindow::getFile(const QModelIndex &index, bool forPass) -> QString {
×
419
  if (!index.isValid() ||
×
420
      !model.fileInfo(proxyModel.mapToSource(index)).isFile()) {
×
421
    return {};
422
  }
423
  QString filePath = model.filePath(proxyModel.mapToSource(index));
×
424
  if (forPass) {
×
425
    filePath = QDir(QtPassSettings::getPassStore()).relativeFilePath(filePath);
×
426
    filePath.replace(Util::endsWithGpg(), "");
×
427
  }
428
  return filePath;
429
}
430

431
/**
432
 * @brief MainWindow::on_treeView_clicked read the selected password file
433
 * @param index
434
 */
435
void MainWindow::on_treeView_clicked(const QModelIndex &index) {
×
436
  bool cleared = ui->treeView->currentIndex().flags() == Qt::NoItemFlags;
×
437
  currentDir =
438
      Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel);
×
439
  // Clear any previously cached clipped text before showing new password
440
  m_qtPass->clearClippedText();
×
441
  QString file = getFile(index, true);
×
442
  ui->passwordName->setText(file);
×
443
  if (!file.isEmpty() && !cleared) {
×
444
    QtPassSettings::getPass()->Show(file);
×
445
  } else {
446
    clearPanel(false);
×
447
    ui->actionEdit->setEnabled(false);
×
448
    ui->actionDelete->setEnabled(true);
×
449
  }
450
}
×
451

452
/**
453
 * @brief MainWindow::on_treeView_doubleClicked when doubleclicked on
454
 * TreeViewItem, open the edit Window
455
 * @param index
456
 */
457
void MainWindow::on_treeView_doubleClicked(const QModelIndex &index) {
×
458
  QFileInfo fileOrFolder =
459
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
460

461
  if (fileOrFolder.isFile()) {
×
462
    editPassword(getFile(index, true));
×
463
  }
464
}
×
465

466
/**
467
 * @brief MainWindow::deselect clear the selection, password and copy buffer
468
 */
469
void MainWindow::deselect() {
×
470
  currentDir = "";
×
471
  m_qtPass->clearClipboard();
×
472
  ui->treeView->clearSelection();
×
473
  ui->actionEdit->setEnabled(false);
×
474
  ui->actionDelete->setEnabled(false);
×
475
  ui->passwordName->setText("");
×
476
  clearPanel(false);
×
477
}
×
478

479
void MainWindow::executeWrapperStarted() {
×
480
  clearTemplateWidgets();
×
481
  ui->textBrowser->clear();
×
482
  setUiElementsEnabled(false);
×
483
  clearPanelTimer.stop();
×
484
  if (QtPassSettings::isShowProcessOutput()) {
×
485
    ui->processOutputWidget->setVisible(true);
×
486
  }
487
}
×
488

489
/**
490
 * @brief Handles displaying parsed password entry content in the main window.
491
 * @example
492
 * void result = MainWindow::passShowHandler(p_output);
493
 * // Updates the UI with parsed fields and emits
494
 * passShowHandlerFinished(output)
495
 *
496
 * @param p_output - The raw output text containing the password entry data.
497
 * @return void - This function does not return a value.
498
 */
499
void MainWindow::passShowHandler(const QString &p_output) {
×
500
  QStringList templ = QtPassSettings::isUseTemplate()
×
501
                          ? QtPassSettings::getPassTemplate().split("\n")
×
502
                          : QStringList();
×
503
  bool allFields =
504
      QtPassSettings::isUseTemplate() && QtPassSettings::isTemplateAllFields();
×
505
  FileContent fileContent = FileContent::parse(p_output, templ, allFields);
×
506
  QString output = p_output;
507
  QString password = fileContent.getPassword();
×
508

509
  // set clipped text
510
  m_qtPass->setClippedText(password, p_output);
×
511

512
  // first clear the current view:
513
  clearTemplateWidgets();
×
514

515
  // show what is needed:
516
  if (QtPassSettings::isHideContent()) {
×
517
    output = "***" + tr("Content hidden") + "***";
×
518
  } else if (!QtPassSettings::isDisplayAsIs()) {
×
519
    if (!password.isEmpty()) {
×
520
      // set the password, it is hidden if needed in addToGridLayout
521
      addToGridLayout(0, tr("Password"), password);
×
522
    }
523

524
    NamedValues namedValues = fileContent.getNamedValues();
×
525
    for (int j = 0; j < namedValues.length(); ++j) {
×
526
      const NamedValue &nv = namedValues.at(j);
527
      addToGridLayout(j + 1, nv.name, nv.value);
×
528
    }
529
    if (ui->gridLayout->count() == 0) {
×
530
      ui->verticalLayoutPassword->setSpacing(0);
×
531
    } else {
532
      ui->verticalLayoutPassword->setSpacing(6);
×
533
    }
534

535
    output = fileContent.getRemainingDataForDisplay();
×
536
  }
537

538
  if (QtPassSettings::isUseAutoclearPanel()) {
×
539
    clearPanelTimer.start();
×
540
  }
541

542
  emit passShowHandlerFinished(output);
×
543
  setUiElementsEnabled(true);
×
544
}
×
545

546
/**
547
 * @brief Handles the OTP output by displaying it, copying it to the clipboard,
548
 * and updating the UI state.
549
 * @example
550
 * void MainWindow::passOtpHandler(const QString &p_output);
551
 *
552
 * @param const QString &p_output - The OTP code text to process; if empty, an
553
 * error message is shown instead.
554
 * @return void - This function does not return a value.
555
 */
556
void MainWindow::passOtpHandler(const QString &p_output) {
×
557
  if (!p_output.isEmpty()) {
×
558
    addToGridLayout(ui->gridLayout->count() + 1, tr("OTP Code"), p_output);
×
559
    m_qtPass->copyTextToClipboard(p_output);
×
560
    showStatusMessage(tr("OTP code copied to clipboard"));
×
561
  } else {
562
    flashText(tr("No OTP code found in this password entry"), true);
×
563
  }
564
  if (QtPassSettings::isUseAutoclearPanel()) {
×
565
    clearPanelTimer.start();
×
566
  }
567
  setUiElementsEnabled(true);
×
568
}
×
569

570
/**
571
 * @brief MainWindow::clearPanel hide the information from shoulder surfers
572
 */
573
void MainWindow::clearPanel(bool notify) {
×
574
  while (ui->gridLayout->count() > 0) {
×
575
    QLayoutItem *item = ui->gridLayout->takeAt(0);
×
576
    delete item->widget();
×
577
    delete item;
×
578
  }
579
  const bool grepWasVisible = ui->grepResultsList->isVisible();
×
580
  ui->grepResultsList->clear();
×
581
  if (grepWasVisible) {
×
582
    ui->grepResultsList->setVisible(false);
×
583
    ui->treeView->setVisible(true);
×
584
    if (m_grepMode) {
×
585
      m_grepMode = false;
×
586
      ui->grepButton->blockSignals(true);
×
587
      ui->grepButton->setChecked(false);
×
588
      ui->grepButton->blockSignals(false);
×
589
      ui->lineEdit->blockSignals(true);
×
590
      ui->lineEdit->clear();
×
591
      ui->lineEdit->blockSignals(false);
×
592
      ui->lineEdit->setPlaceholderText(tr("Search Password"));
×
593
    }
594
  }
595
  if (notify) {
×
596
    QString output = "***" + tr("Password and Content hidden") + "***";
×
597
    ui->textBrowser->setHtml(output);
×
598
  } else {
599
    ui->textBrowser->setHtml("");
×
600
  }
601
}
×
602

603
/**
604
 * @brief MainWindow::setUiElementsEnabled enable or disable the relevant UI
605
 * elements
606
 * @param state
607
 */
608
void MainWindow::setUiElementsEnabled(bool state) {
×
609
  ui->treeView->setEnabled(state);
×
610
  ui->lineEdit->setEnabled(state);
×
611
  ui->lineEdit->installEventFilter(this);
×
612
  ui->actionAddPassword->setEnabled(state);
×
613
  ui->actionAddFolder->setEnabled(state);
×
614
  ui->actionUsers->setEnabled(state);
×
615
  ui->actionConfig->setEnabled(state);
×
616
  // is a file selected?
617
  state &= ui->treeView->currentIndex().isValid();
×
618
  ui->actionDelete->setEnabled(state);
×
619
  ui->actionEdit->setEnabled(state);
×
620
  updateGitButtonVisibility();
×
621
  updateOtpButtonVisibility();
×
622
}
×
623

624
/**
625
 * @brief Restores the main window geometry, state, position, size, and
626
 * tray/icon settings from saved application settings.
627
 * @example
628
 * MainWindow window;
629
 * window.restoreWindow();
630
 *
631
 * @return void - This function does not return a value.
632
 */
633
void MainWindow::restoreWindow() {
×
634
  QByteArray geometry = QtPassSettings::getGeometry(saveGeometry());
×
635
  restoreGeometry(geometry);
×
636
  QByteArray savestate = QtPassSettings::getSavestate(saveState());
×
637
  restoreState(savestate);
×
638
  QPoint position = QtPassSettings::getPos(pos());
×
639
  move(position);
×
640
  QSize newSize = QtPassSettings::getSize(size());
×
641
  resize(newSize);
×
642
  if (QtPassSettings::isMaximized(isMaximized())) {
×
643
    showMaximized();
×
644
  }
645

646
  if (QtPassSettings::isAlwaysOnTop()) {
×
647
    Qt::WindowFlags flags = windowFlags();
648
    setWindowFlags(flags | Qt::WindowStaysOnTopHint);
×
649
    show();
×
650
  }
651

652
  if (QtPassSettings::isUseTrayIcon() && tray == nullptr) {
×
653
    initTrayIcon();
×
654
    if (QtPassSettings::isStartMinimized()) {
×
655
      // since we are still in constructor, can't directly hide
656
      QTimer::singleShot(10, this, SLOT(hide()));
×
657
    }
658
  } else if (!QtPassSettings::isUseTrayIcon() && tray != nullptr) {
×
659
    destroyTrayIcon();
×
660
  }
661
}
×
662

663
/**
664
 * @brief MainWindow::on_configButton_clicked run Mainwindow::config
665
 */
666
void MainWindow::onConfig() { config(); }
×
667

668
/**
669
 * @brief Executes when the string in the search box changes, collapses the
670
 * TreeView
671
 * @param arg1
672
 */
673
void MainWindow::on_lineEdit_textChanged(const QString &arg1) {
×
674
  if (m_grepMode)
×
675
    return;
676
  ui->statusBar->showMessage(tr("Looking for: %1").arg(arg1), 1000);
×
677
  ui->treeView->expandAll();
×
678
  clearPanel(false);
×
679
  ui->passwordName->setText("");
×
680
  ui->actionEdit->setEnabled(false);
×
681
  ui->actionDelete->setEnabled(false);
×
682
  searchTimer.start();
×
683
}
684

685
/**
686
 * @brief MainWindow::onTimeoutSearch Fired when search is finished or too much
687
 * time from two keypresses is elapsed
688
 */
689
void MainWindow::onTimeoutSearch() {
×
690
  QString query = ui->lineEdit->text();
×
691

692
  if (query.isEmpty()) {
×
693
    ui->treeView->collapseAll();
×
694
    deselect();
×
695
  }
696

697
  query.replace(QStringLiteral(" "), ".*");
×
698
  QRegularExpression regExp(query, QRegularExpression::CaseInsensitiveOption);
×
699
  proxyModel.setFilterRegularExpression(regExp);
×
700
  ui->treeView->setRootIndex(proxyModel.mapFromSource(
×
701
      model.setRootPath(QtPassSettings::getPassStore())));
×
702

703
  if (proxyModel.rowCount() > 0 && !query.isEmpty()) {
×
704
    selectFirstFile();
×
705
  } else {
706
    ui->actionEdit->setEnabled(false);
×
707
    ui->actionDelete->setEnabled(false);
×
708
  }
709
}
×
710

711
/**
712
 * @brief MainWindow::on_lineEdit_returnPressed get searching
713
 *
714
 * Select the first possible file in the tree
715
 */
716
void MainWindow::on_lineEdit_returnPressed() {
×
717
#ifdef QT_DEBUG
718
  dbg() << "on_lineEdit_returnPressed" << proxyModel.rowCount();
719
#endif
720

721
  if (m_grepMode) {
×
722
    const QString query = ui->lineEdit->text();
×
723
    if (!query.isEmpty()) {
×
724
      m_grepCancelled = false;
×
725
      ui->grepResultsList->clear();
×
726
      ui->statusBar->showMessage(tr("Searching…"));
×
727
      if (!m_grepBusy) {
×
728
        m_grepBusy = true;
×
729
        QApplication::setOverrideCursor(Qt::WaitCursor);
×
730
      }
731
      QtPassSettings::getPass()->Grep(query, ui->grepCaseButton->isChecked());
×
732
    } else {
733
      m_grepCancelled = true;
×
734
      if (m_grepBusy) {
×
735
        m_grepBusy = false;
×
736
        QApplication::restoreOverrideCursor();
×
737
      }
738
      ui->grepResultsList->clear();
×
739
      ui->grepResultsList->setVisible(false);
×
740
      ui->treeView->setVisible(true);
×
741
    }
742
    return;
743
  }
744

745
  if (proxyModel.rowCount() > 0) {
×
746
    selectFirstFile();
×
747
    on_treeView_clicked(ui->treeView->currentIndex());
×
748
  }
749
}
750

751
/**
752
 * @brief Toggle grep (content search) mode.
753
 */
754
void MainWindow::on_grepButton_toggled(bool checked) {
×
755
  m_grepMode = checked;
×
756
  if (checked) {
×
757
    ui->lineEdit->setPlaceholderText(tr("Search content (regex)"));
×
758
    ui->lineEdit->clear();
×
759
    searchTimer.stop();
×
760
    proxyModel.setFilterRegularExpression(QRegularExpression());
×
761
    ui->treeView->setRootIndex(proxyModel.mapFromSource(
×
762
        model.setRootPath(QtPassSettings::getPassStore())));
×
763
    ui->grepResultsList->setVisible(false);
×
764
    // Keep treeView visible until results arrive
765
  } else {
766
    if (m_grepBusy) {
×
767
      m_grepBusy = false;
×
768
      m_grepCancelled = true;
×
769
      QApplication::restoreOverrideCursor();
×
770
    }
771
    searchTimer.stop();
×
772
    ui->lineEdit->blockSignals(true);
×
773
    ui->lineEdit->clear();
×
774
    ui->lineEdit->blockSignals(false);
×
775
    ui->lineEdit->setPlaceholderText(tr("Search Password"));
×
776
    ui->grepResultsList->clear();
×
777
    ui->grepResultsList->setVisible(false);
×
778
    ui->treeView->setVisible(true);
×
779
    proxyModel.setFilterRegularExpression(QRegularExpression());
×
780
    ui->treeView->setRootIndex(proxyModel.mapFromSource(
×
781
        model.setRootPath(QtPassSettings::getPassStore())));
×
782
  }
783
}
×
784

785
/**
786
 * @brief Display grep results in grepResultsList.
787
 */
788
void MainWindow::onGrepFinished(
×
789
    const QList<QPair<QString, QStringList>> &results) {
790
  if (m_grepBusy) {
×
791
    m_grepBusy = false;
×
792
    QApplication::restoreOverrideCursor();
×
793
  }
794
  if (m_grepCancelled) {
×
795
    m_grepCancelled = false;
×
796
    return;
×
797
  }
798
  setUiElementsEnabled(true);
×
799
  if (!m_grepMode)
×
800
    return;
801
  ui->grepResultsList->clear();
×
802
  if (results.isEmpty()) {
×
803
    ui->statusBar->showMessage(tr("No matches found."), 3000);
×
804
    ui->grepResultsList->setVisible(false);
×
805
    ui->treeView->setVisible(true);
×
806
    return;
×
807
  }
808
  const bool hideContent = QtPassSettings::isHideContent();
×
809
  int totalLines = 0;
810
  for (const auto &pair : results) {
×
811
    QTreeWidgetItem *entryItem = new QTreeWidgetItem(ui->grepResultsList);
×
812
    entryItem->setText(0, pair.first);
×
813
    entryItem->setData(0, Qt::UserRole, pair.first);
×
814
    for (const QString &line : pair.second) {
×
815
      QTreeWidgetItem *lineItem = new QTreeWidgetItem(entryItem);
×
816
      lineItem->setText(0, hideContent ? "***" + tr("Content hidden") + "***"
×
817
                                       : line);
818
      lineItem->setData(0, Qt::UserRole, pair.first);
×
819
      ++totalLines;
×
820
    }
821
  }
822
  ui->grepResultsList->expandAll();
×
823
  ui->treeView->setVisible(false);
×
824
  ui->grepResultsList->setVisible(true);
×
825
  ui->statusBar->showMessage(
×
826
      tr("Found %n match(es)", nullptr, totalLines) + " " +
×
827
          tr("in %n entr(ies).", nullptr, results.size()),
×
828
      3000);
829
  if (QtPassSettings::isUseAutoclearPanel())
×
830
    clearPanelTimer.start();
×
831
}
832

833
/**
834
 * @brief Navigate to the password entry when a grep result is clicked.
835
 */
836
void MainWindow::on_grepResultsList_itemClicked(QTreeWidgetItem *item,
×
837
                                                int /*column*/) {
838
  const QString entry = item->data(0, Qt::UserRole).toString();
×
839
  if (entry.isEmpty())
×
840
    return;
841
  const QString fullPath = QDir::cleanPath(
842
      QDir(QtPassSettings::getPassStore()).filePath(entry + ".gpg"));
×
843
  QModelIndex srcIndex = model.index(fullPath);
×
844
  if (!srcIndex.isValid())
845
    return;
846
  QModelIndex proxyIndex = proxyModel.mapFromSource(srcIndex);
×
847
  if (!proxyIndex.isValid())
848
    return;
849
  ui->treeView->setCurrentIndex(proxyIndex);
×
850
  on_treeView_clicked(proxyIndex);
×
851
  if (QtPassSettings::isHideContent() || QtPassSettings::isUseAutoclearPanel())
×
852
    ui->grepResultsList->clear();
×
853
  ui->grepResultsList->setVisible(false);
×
854
  ui->treeView->setVisible(true);
×
855
  ui->treeView->scrollTo(proxyIndex);
×
856
  ui->treeView->setFocus();
×
857
}
858

859
/**
860
 * @brief MainWindow::selectFirstFile select the first possible file in the
861
 * tree
862
 */
863
void MainWindow::selectFirstFile() {
×
864
  QModelIndex index = proxyModel.mapFromSource(
×
865
      model.setRootPath(QtPassSettings::getPassStore()));
×
866
  index = firstFile(index);
×
867
  ui->treeView->setCurrentIndex(index);
×
868
}
×
869

870
/**
871
 * @brief MainWindow::firstFile return location of first possible file
872
 * @param parentIndex
873
 * @return QModelIndex
874
 */
875
auto MainWindow::firstFile(QModelIndex parentIndex) -> QModelIndex {
×
876
  QModelIndex index = parentIndex;
×
877
  int numRows = proxyModel.rowCount(parentIndex);
×
878
  for (int row = 0; row < numRows; ++row) {
×
879
    index = proxyModel.index(row, 0, parentIndex);
×
880
    if (model.fileInfo(proxyModel.mapToSource(index)).isFile()) {
×
881
      return index;
×
882
    }
883
    if (proxyModel.hasChildren(index)) {
×
884
      return firstFile(index);
×
885
    }
886
  }
887
  return index;
×
888
}
889

890
/**
891
 * @brief MainWindow::setPassword open passworddialog
892
 * @param file which pgp file
893
 * @param isNew insert (not update)
894
 */
895
void MainWindow::setPassword(const QString &file, bool isNew) {
×
896
  PasswordDialog d(file, isNew, this);
×
897

898
  if (isNew) {
×
899
    QString storePath = QtPassSettings::getPassStore();
×
900
    QString folder =
901
        Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel);
×
902
    if (folder.isEmpty()) {
×
903
      folder = storePath;
×
904
    }
905
    QHash<QString, QStringList> templates = Util::readTemplates(storePath);
×
906
    if (!templates.isEmpty()) {
907
      QString defaultTemplate = Util::getFolderTemplate(folder, storePath);
×
908
      d.setAvailableTemplates(templates, defaultTemplate);
×
909
      new QShortcut(QKeySequence(Qt::CTRL | Qt::Key_T), &d,
×
910
                    [&d]() { d.cycleTemplate(); });
×
911
    }
912
  }
×
913

914
  if (!d.exec()) {
×
915
    ui->treeView->setFocus();
×
916
  }
917
}
×
918

919
/**
920
 * @brief MainWindow::addPassword add a new password by showing a
921
 * number of dialogs.
922
 */
923
void MainWindow::addPassword() {
×
924
  bool ok;
925
  QString dir =
926
      Util::getDir(ui->treeView->currentIndex(), true, model, proxyModel);
×
927
  QString file =
928
      QInputDialog::getText(this, tr("New file"),
×
929
                            tr("New password file: \n(Will be placed in %1 )")
×
930
                                .arg(QtPassSettings::getPassStore() +
×
931
                                     Util::getDir(ui->treeView->currentIndex(),
×
932
                                                  true, model, proxyModel)),
933
                            QLineEdit::Normal, "", &ok);
×
934
  if (!ok || file.isEmpty()) {
×
935
    return;
936
  }
937
  file = dir + file;
×
938
  setPassword(file);
×
939
}
940

941
/**
942
 * @brief MainWindow::onDelete remove password, if you are
943
 * sure.
944
 */
945
void MainWindow::onDelete() {
×
946
  QModelIndex currentIndex = ui->treeView->currentIndex();
×
947
  if (!currentIndex.isValid()) {
948
    // This fixes https://github.com/IJHack/QtPass/issues/556
949
    // Otherwise the entire password directory would be deleted if
950
    // nothing is selected in the tree view.
951
    return;
×
952
  }
953

954
  QFileInfo fileOrFolder =
955
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
956
  QString file = "";
×
957
  bool isDir = false;
958

959
  if (fileOrFolder.isFile()) {
×
960
    file = getFile(ui->treeView->currentIndex(), true);
×
961
  } else {
962
    file = Util::getDir(ui->treeView->currentIndex(), true, model, proxyModel);
×
963
    isDir = true;
964
  }
965

966
  QString dirMessage = tr(" and the whole content?");
967
  if (isDir) {
×
968
    QDirIterator it(model.rootPath() + QDir::separator() + file,
×
969
                    QDirIterator::Subdirectories);
×
970
    bool okDir = true;
971
    while (it.hasNext() && okDir) {
×
972
      it.next();
×
973
      if (QFileInfo(it.filePath()).isFile()) {
×
974
        if (QFileInfo(it.filePath()).suffix() != "gpg") {
×
975
          okDir = false;
976
          dirMessage = tr(" and the whole content? <br><strong>Attention: "
×
977
                          "there are unexpected files in the given folder, "
978
                          "check them before continue.</strong>");
979
        }
980
      }
981
    }
982
  }
×
983

984
  if (QMessageBox::question(
×
985
          this, isDir ? tr("Delete folder?") : tr("Delete password?"),
×
986
          tr("Are you sure you want to delete %1%2?")
×
987
              .arg(QDir::separator() + file, isDir ? dirMessage : "?"),
×
988
          QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) {
989
    return;
990
  }
991

992
  QtPassSettings::getPass()->Remove(file, isDir);
×
993
}
×
994

995
/**
996
 * @brief MainWindow::onOTP try and generate (selected) OTP code.
997
 */
998
void MainWindow::onOtp() {
×
999
  QString file = getFile(ui->treeView->currentIndex(), true);
×
1000
  if (!file.isEmpty()) {
×
1001
    if (QtPassSettings::isUseOtp()) {
×
1002
      setUiElementsEnabled(false);
×
1003
      QtPassSettings::getPass()->OtpGenerate(file);
×
1004
    }
1005
  } else {
1006
    flashText(tr("No password selected for OTP generation"), true);
×
1007
  }
1008
}
×
1009

1010
/**
1011
 * @brief MainWindow::onEdit try and edit (selected) password.
1012
 */
1013
void MainWindow::onEdit() {
×
1014
  QString file = getFile(ui->treeView->currentIndex(), true);
×
1015
  editPassword(file);
×
1016
}
×
1017

1018
/**
1019
 * @brief MainWindow::userDialog see MainWindow::onUsers()
1020
 * @param dir folder to edit users for.
1021
 */
1022
void MainWindow::userDialog(const QString &dir) {
×
1023
  if (!dir.isEmpty()) {
×
1024
    currentDir = dir;
×
1025
  }
1026
  onUsers();
×
1027
}
×
1028

1029
/**
1030
 * @brief MainWindow::onUsers edit users for the current
1031
 * folder,
1032
 * gets lists and opens UserDialog.
1033
 */
1034
void MainWindow::onUsers() {
×
1035
  QString dir =
1036
      currentDir.isEmpty()
1037
          ? Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel)
×
1038
          : currentDir;
×
1039

1040
  UsersDialog d(dir, this);
×
1041
  if (!d.exec()) {
×
1042
    ui->treeView->setFocus();
×
1043
  }
1044
}
×
1045

1046
/**
1047
 * @brief MainWindow::messageAvailable we have some text/message/search to do.
1048
 * @param message
1049
 */
1050
void MainWindow::messageAvailable(const QString &message) {
×
1051
  show();
×
1052
  raise();
×
1053
  if (message.isEmpty()) {
×
1054
    focusInput();
×
1055
  } else {
1056
    ui->treeView->expandAll();
×
1057
    ui->lineEdit->setText(message);
×
1058
    on_lineEdit_returnPressed();
×
1059
  }
1060
}
×
1061

1062
/**
1063
 * @brief MainWindow::generateKeyPair internal gpg keypair generator . .
1064
 * @param batch
1065
 * @param keygenWindow
1066
 */
1067
void MainWindow::generateKeyPair(const QString &batch, QDialog *keygenWindow) {
×
1068
  keygenDialog = keygenWindow;
×
1069
  emit generateGPGKeyPair(batch);
×
1070
}
×
1071

1072
/**
1073
 * @brief MainWindow::updateProfileBox update the list of profiles, optionally
1074
 * select a more appropriate one to view too
1075
 */
1076
void MainWindow::updateProfileBox() {
×
1077
  QHash<QString, QHash<QString, QString>> profiles =
1078
      QtPassSettings::getProfiles();
×
1079

1080
  if (profiles.isEmpty()) {
1081
    ui->profileWidget->hide();
×
1082
  } else {
1083
    ui->profileWidget->show();
×
1084
    ui->profileBox->setEnabled(profiles.size() > 1);
×
1085
    ui->profileBox->clear();
×
1086
    QHashIterator<QString, QHash<QString, QString>> i(profiles);
×
1087
    while (i.hasNext()) {
×
1088
      i.next();
1089
      if (!i.key().isEmpty()) {
×
1090
        ui->profileBox->addItem(i.key());
×
1091
      }
1092
    }
1093
    ui->profileBox->model()->sort(0);
×
1094
  }
1095
  int index = ui->profileBox->findText(QtPassSettings::getProfile());
×
1096
  if (index != -1) { //  -1 for not found
×
1097
    ui->profileBox->setCurrentIndex(index);
×
1098
  }
1099
}
×
1100

1101
/**
1102
 * @brief MainWindow::on_profileBox_currentIndexChanged make sure we show the
1103
 * correct "profile"
1104
 * @param name
1105
 */
1106
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
1107
void MainWindow::on_profileBox_currentIndexChanged(QString name) {
1108
#else
1109
/**
1110
 * @brief Handles changes to the selected profile in the profile combo box.
1111
 * @details Ignores the event during a fresh start or when the selected profile
1112
 * matches the current profile. Otherwise, it clears the password field, updates
1113
 * the active profile and related settings, refreshes the environment, and
1114
 * resets the tree view and action states to reflect the newly selected profile.
1115
 *
1116
 * @param name - The newly selected profile name.
1117
 * @return void - This function does not return a value.
1118
 *
1119
 */
1120
void MainWindow::on_profileBox_currentTextChanged(const QString &name) {
×
1121
#endif
1122
  if (m_qtPass->isFreshStart() || name == QtPassSettings::getProfile()) {
×
1123
    return;
×
1124
  }
1125

1126
  ui->lineEdit->clear();
×
1127

1128
  QtPassSettings::setProfile(name);
×
1129

1130
  QtPassSettings::setPassStore(
×
1131
      QtPassSettings::getProfiles().value(name).value("path"));
×
1132
  QtPassSettings::setPassSigningKey(
×
1133
      QtPassSettings::getProfiles().value(name).value("signingKey"));
×
1134
  ui->statusBar->showMessage(tr("Profile changed to %1").arg(name), 2000);
×
1135

1136
  QtPassSettings::getPass()->updateEnv();
×
1137

1138
  const QString passStore = QtPassSettings::getPassStore();
×
1139
  proxyModel.setStore(passStore);
×
1140
  ui->treeView->setRootIndex(
×
1141
      proxyModel.mapFromSource(model.setRootPath(passStore)));
×
1142
  deselect();
×
1143
  ui->treeView->setCurrentIndex(QModelIndex());
×
1144
}
1145

1146
/**
1147
 * @brief MainWindow::initTrayIcon show a nice tray icon on systems that
1148
 * support
1149
 * it
1150
 */
1151
void MainWindow::initTrayIcon() {
×
1152
  this->tray = new TrayIcon(this);
×
1153
  // Setup tray icon
1154

1155
  if (tray == nullptr) {
1156
#ifdef QT_DEBUG
1157
    dbg() << "Allocating tray icon failed.";
1158
#endif
1159
    return;
1160
  }
1161

1162
  if (!tray->getIsAllocated()) {
×
1163
    destroyTrayIcon();
×
1164
  }
1165
}
1166

1167
/**
1168
 * @brief MainWindow::destroyTrayIcon remove that pesky tray icon
1169
 */
1170
void MainWindow::destroyTrayIcon() {
×
1171
  delete this->tray;
×
1172
  tray = nullptr;
×
1173
}
×
1174

1175
/**
1176
 * @brief MainWindow::closeEvent hide or quit
1177
 * @param event
1178
 */
1179
void MainWindow::closeEvent(QCloseEvent *event) {
×
1180
  if (QtPassSettings::isHideOnClose()) {
×
1181
    this->hide();
×
1182
    event->ignore();
1183
  } else {
1184
    m_qtPass->clearClipboard();
×
1185

1186
    QtPassSettings::setGeometry(saveGeometry());
×
1187
    QtPassSettings::setSavestate(saveState());
×
1188
    QtPassSettings::setMaximized(isMaximized());
×
1189
    if (!isMaximized()) {
×
1190
      QtPassSettings::setPos(pos());
×
1191
      QtPassSettings::setSize(size());
×
1192
    }
1193
    event->accept();
1194
  }
1195
}
×
1196

1197
/**
1198
 * @brief MainWindow::eventFilter filter out some events and focus the
1199
 * treeview
1200
 * @param obj
1201
 * @param event
1202
 * @return
1203
 */
1204
auto MainWindow::eventFilter(QObject *obj, QEvent *event) -> bool {
×
1205
  if (obj == ui->lineEdit && event->type() == QEvent::KeyPress) {
×
1206
    auto *key = dynamic_cast<QKeyEvent *>(event);
×
1207
    if (key != nullptr && key->key() == Qt::Key_Down) {
×
1208
      ui->treeView->setFocus();
×
1209
    }
1210
  }
1211
  return QObject::eventFilter(obj, event);
×
1212
}
1213

1214
/**
1215
 * @brief MainWindow::keyPressEvent did anyone press return, enter or escape?
1216
 * @param event
1217
 */
1218
void MainWindow::keyPressEvent(QKeyEvent *event) {
×
1219
  switch (event->key()) {
×
1220
  case Qt::Key_Delete:
×
1221
    onDelete();
×
1222
    break;
×
1223
  case Qt::Key_Return:
×
1224
  case Qt::Key_Enter:
1225
    if (proxyModel.rowCount() > 0) {
×
1226
      on_treeView_clicked(ui->treeView->currentIndex());
×
1227
    }
1228
    break;
1229
  case Qt::Key_Escape:
×
1230
    ui->lineEdit->clear();
×
1231
    break;
×
1232
  default:
1233
    break;
1234
  }
1235
}
×
1236

1237
/**
1238
 * @brief MainWindow::showContextMenu show us the (file or folder) context
1239
 * menu
1240
 * @param pos
1241
 */
1242
void MainWindow::showContextMenu(const QPoint &pos) {
×
1243
  QModelIndex index = ui->treeView->indexAt(pos);
×
1244
  bool selected = true;
1245
  if (!index.isValid()) {
1246
    ui->treeView->clearSelection();
×
1247
    ui->actionDelete->setEnabled(false);
×
1248
    ui->actionEdit->setEnabled(false);
×
1249
    currentDir = "";
×
1250
    selected = false;
1251
  }
1252

1253
  ui->treeView->setCurrentIndex(index);
×
1254

1255
  QPoint globalPos = ui->treeView->viewport()->mapToGlobal(pos);
×
1256

1257
  QFileInfo fileOrFolder =
1258
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
1259

1260
  QMenu contextMenu;
×
1261
  if (!selected || fileOrFolder.isDir()) {
×
1262
    QAction *openFolder =
1263
        contextMenu.addAction(tr("Open folder with file manager"));
×
1264
    QAction *addFolder = contextMenu.addAction(tr("Add folder"));
×
1265
    QAction *addPassword = contextMenu.addAction(tr("Add password"));
×
1266
    QAction *users = contextMenu.addAction(tr("Users"));
×
1267
    connect(openFolder, &QAction::triggered, this, &MainWindow::openFolder);
×
1268
    connect(addFolder, &QAction::triggered, this, &MainWindow::addFolder);
×
1269
    connect(addPassword, &QAction::triggered, this, &MainWindow::addPassword);
×
1270
    connect(users, &QAction::triggered, this, &MainWindow::onUsers);
×
1271
  } else if (fileOrFolder.isFile()) {
×
1272
    QAction *edit = contextMenu.addAction(tr("Edit"));
×
1273
    connect(edit, &QAction::triggered, this, &MainWindow::onEdit);
×
1274
  }
1275
  if (selected) {
×
1276
    contextMenu.addSeparator();
×
1277
    if (fileOrFolder.isDir()) {
×
1278
      QAction *renameFolder = contextMenu.addAction(tr("Rename folder"));
×
1279
      connect(renameFolder, &QAction::triggered, this,
×
1280
              &MainWindow::renameFolder);
×
1281
    } else if (fileOrFolder.isFile()) {
×
1282
      QAction *renamePassword = contextMenu.addAction(tr("Rename password"));
×
1283
      connect(renamePassword, &QAction::triggered, this,
×
1284
              &MainWindow::renamePassword);
×
1285
    }
1286
    QAction *deleteItem = contextMenu.addAction(tr("Delete"));
×
1287
    connect(deleteItem, &QAction::triggered, this, &MainWindow::onDelete);
×
1288
    if (fileOrFolder.isDir()) {
×
1289
      QString dirPath = QDir::cleanPath(
1290
          Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel));
×
1291

1292
      QMenu *shareMenu = new QMenu(tr("Share"), &contextMenu);
×
1293
      contextMenu.addMenu(shareMenu);
×
1294

1295
      QString gpgIdPath = Pass::getGpgIdPath(dirPath);
×
1296
      bool gpgIdExists = !gpgIdPath.isEmpty() && QFile(gpgIdPath).exists();
×
1297

1298
      QString exePath = QtPassSettings::isUsePass()
×
1299
                            ? QtPassSettings::getPassExecutable()
×
1300
                            : QtPassSettings::getGpgExecutable();
×
1301
      bool gpgAvailable = !exePath.isEmpty() && (exePath.startsWith("wsl ") ||
×
1302
                                                 QFile(exePath).exists());
×
1303

1304
      QAction *reencrypt = shareMenu->addAction(tr("Re-encrypt all passwords"));
×
1305
      reencrypt->setEnabled(gpgIdExists && gpgAvailable);
×
1306
      connect(reencrypt, &QAction::triggered, this,
×
1307
              [this, dirPath]() { reencryptPath(dirPath); });
×
1308

1309
      QAction *exportKey = shareMenu->addAction(tr("Export my public key..."));
×
1310
      exportKey->setEnabled(gpgAvailable);
×
1311
      connect(exportKey, &QAction::triggered, this,
×
1312
              &MainWindow::exportPublicKey);
×
1313

1314
      QAction *addRecipientAction =
1315
          shareMenu->addAction(tr("Add recipient..."));
×
1316
      addRecipientAction->setEnabled(gpgIdExists && gpgAvailable);
×
1317
      connect(addRecipientAction, &QAction::triggered, this,
×
1318
              [this, dirPath]() { addRecipient(dirPath); });
×
1319

1320
      QAction *shareHelp = shareMenu->addAction(tr("What is this?"));
×
1321
      connect(shareHelp, &QAction::triggered, this, &MainWindow::showShareHelp);
×
1322
    }
1323
  }
1324
  contextMenu.exec(globalPos);
×
1325
}
×
1326

1327
/**
1328
 * @brief MainWindow::showBrowserContextMenu show us the context menu in
1329
 * password window
1330
 * @param pos
1331
 */
1332
void MainWindow::showBrowserContextMenu(const QPoint &pos) {
×
1333
  QMenu *contextMenu = ui->textBrowser->createStandardContextMenu(pos);
×
1334
  QPoint globalPos = ui->textBrowser->viewport()->mapToGlobal(pos);
×
1335

1336
  contextMenu->exec(globalPos);
×
1337
  delete contextMenu;
×
1338
}
×
1339

1340
/**
1341
 * @brief MainWindow::openFolder open the folder in the default file manager
1342
 */
1343
void MainWindow::openFolder() {
×
1344
  QString dir =
1345
      Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel);
×
1346

1347
  QString path = QDir::toNativeSeparators(dir);
×
1348
  QDesktopServices::openUrl(QUrl::fromLocalFile(path));
×
1349
}
×
1350

1351
/**
1352
 * @brief MainWindow::addFolder add a new folder to store passwords in
1353
 */
1354
void MainWindow::addFolder() {
×
1355
  bool ok;
1356
  QString dir =
1357
      Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel);
×
1358
  QString newdir =
1359
      QInputDialog::getText(this, tr("New file"),
×
1360
                            tr("New Folder: \n(Will be placed in %1 )")
×
1361
                                .arg(QtPassSettings::getPassStore() +
×
1362
                                     Util::getDir(ui->treeView->currentIndex(),
×
1363
                                                  true, model, proxyModel)),
1364
                            QLineEdit::Normal, "", &ok);
×
1365
  if (!ok || newdir.isEmpty()) {
×
1366
    return;
1367
  }
1368
  newdir.prepend(dir);
1369
  if (!QDir().mkdir(newdir)) {
×
1370
    QMessageBox::warning(this, tr("Error"),
×
1371
                         tr("Failed to create folder: %1").arg(newdir));
×
1372
    return;
×
1373
  }
1374
  if (QtPassSettings::isAddGPGId(true)) {
×
1375
    QString gpgIdFile = newdir + "/.gpg-id";
×
1376
    QFile gpgId(gpgIdFile);
×
1377
    if (!gpgId.open(QIODevice::WriteOnly)) {
×
1378
      QMessageBox::warning(
×
1379
          this, tr("Error"),
×
1380
          tr("Failed to create .gpg-id file in: %1").arg(newdir));
×
1381
      return;
1382
    }
1383
    QList<UserInfo> users = QtPassSettings::getPass()->listKeys("", true);
×
1384
    for (const UserInfo &user : users) {
×
1385
      if (user.enabled) {
×
1386
        gpgId.write((user.key_id + "\n").toUtf8());
×
1387
      }
1388
    }
1389
    gpgId.close();
×
1390
  }
×
1391
}
1392

1393
/**
1394
 * @brief MainWindow::renameFolder rename an existing folder
1395
 */
1396
void MainWindow::renameFolder() {
×
1397
  bool ok;
1398
  QString srcDir = QDir::cleanPath(
1399
      Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel));
×
1400
  QString srcDirName = QDir(srcDir).dirName();
×
1401
  QString newName =
1402
      QInputDialog::getText(this, tr("Rename file"), tr("Rename Folder To: "),
×
1403
                            QLineEdit::Normal, srcDirName, &ok);
×
1404
  if (!ok || newName.isEmpty()) {
×
1405
    return;
1406
  }
1407
  QString destDir = srcDir;
1408
  destDir.replace(srcDir.lastIndexOf(srcDirName), srcDirName.length(), newName);
×
1409
  QtPassSettings::getPass()->Move(srcDir, destDir);
×
1410
}
1411

1412
/**
1413
 * @brief MainWindow::editPassword read password and open edit window via
1414
 * MainWindow::onEdit()
1415
 */
1416
void MainWindow::editPassword(const QString &file) {
×
1417
  if (!file.isEmpty()) {
×
1418
    if (QtPassSettings::isUseGit() && QtPassSettings::isAutoPull()) {
×
1419
      onUpdate(true);
×
1420
    }
1421
    setPassword(file, false);
×
1422
  }
1423
}
×
1424

1425
/**
1426
 * @brief MainWindow::renamePassword rename an existing password
1427
 */
1428
void MainWindow::renamePassword() {
×
1429
  bool ok;
1430
  QString file = getFile(ui->treeView->currentIndex(), false);
×
1431
  QString filePath = QFileInfo(file).path();
×
1432
  QString fileName = QFileInfo(file).fileName();
×
1433
  if (fileName.endsWith(".gpg", Qt::CaseInsensitive)) {
×
1434
    fileName.chop(4);
×
1435
  }
1436

1437
  QString newName =
1438
      QInputDialog::getText(this, tr("Rename file"), tr("Rename File To: "),
×
1439
                            QLineEdit::Normal, fileName, &ok);
×
1440
  if (!ok || newName.isEmpty()) {
×
1441
    return;
1442
  }
1443
  QString newFile = QDir(filePath).filePath(newName);
×
1444
  QtPassSettings::getPass()->Move(file, newFile);
×
1445
}
1446

1447
/**
1448
 * @brief MainWindow::clearTemplateWidgets empty the template widget fields in
1449
 * the UI
1450
 */
1451
void MainWindow::clearTemplateWidgets() {
×
1452
  while (ui->gridLayout->count() > 0) {
×
1453
    QLayoutItem *item = ui->gridLayout->takeAt(0);
×
1454
    delete item->widget();
×
1455
    delete item;
×
1456
  }
1457
  ui->verticalLayoutPassword->setSpacing(0);
×
1458
}
×
1459

1460
/**
1461
 * @brief Copies the password of the selected file from the tree view to the
1462
 * clipboard.
1463
 * @example
1464
 * MainWindow::copyPasswordFromTreeview();
1465
 *
1466
 * @return void - This function does not return a value.
1467
 */
1468
void MainWindow::copyPasswordFromTreeview() {
×
1469
  QFileInfo fileOrFolder =
1470
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
1471

1472
  if (fileOrFolder.isFile()) {
×
1473
    QString file = getFile(ui->treeView->currentIndex(), true);
×
1474
    // Disconnect any previous connection to avoid accumulation
1475
    disconnect(QtPassSettings::getPass(), &Pass::finishedShow, this,
×
1476
               &MainWindow::passwordFromFileToClipboard);
1477
    connect(QtPassSettings::getPass(), &Pass::finishedShow, this,
×
1478
            &MainWindow::passwordFromFileToClipboard);
×
1479
    QtPassSettings::getPass()->Show(file);
×
1480
  }
1481
}
×
1482

1483
void MainWindow::passwordFromFileToClipboard(const QString &text) {
×
1484
  QStringList tokens = text.split('\n');
×
1485
  m_qtPass->copyTextToClipboard(tokens[0]);
×
1486
}
×
1487

1488
/**
1489
 * @brief MainWindow::addToGridLayout add a field to the template grid
1490
 * @param position
1491
 * @param field
1492
 * @param value
1493
 */
1494
void MainWindow::addToGridLayout(int position, const QString &field,
×
1495
                                 const QString &value) {
1496
  QString trimmedField = field.trimmed();
1497
  QString trimmedValue = value.trimmed();
1498

1499
  const QString buttonStyle =
1500
      "border-style: none; background: transparent; padding: 0; margin: 0; "
1501
      "icon-size: 16px; color: inherit;";
×
1502

1503
  // Combine the Copy button and the line edit in one widget
1504
  auto *frame = new QFrame();
×
1505
  QLayout *ly = new QHBoxLayout();
×
1506
  ly->setContentsMargins(5, 2, 2, 2);
×
1507
  ly->setSpacing(0);
×
1508
  frame->setLayout(ly);
×
1509
  if (QtPassSettings::getClipBoardType() != Enums::CLIPBOARD_NEVER) {
×
1510
    auto *fieldLabel = new QPushButtonWithClipboard(trimmedValue, this);
×
1511
    connect(fieldLabel, &QPushButtonWithClipboard::clicked, m_qtPass,
×
1512
            &QtPass::copyTextToClipboard);
×
1513

1514
    fieldLabel->setStyleSheet(buttonStyle);
×
1515
    frame->layout()->addWidget(fieldLabel);
×
1516
  }
1517

1518
  if (QtPassSettings::isUseQrencode()) {
×
1519
    auto *qrbutton = new QPushButtonAsQRCode(trimmedValue, this);
×
1520
    connect(qrbutton, &QPushButtonAsQRCode::clicked, m_qtPass,
×
1521
            &QtPass::showTextAsQRCode);
×
1522
    qrbutton->setStyleSheet(buttonStyle);
×
1523
    frame->layout()->addWidget(qrbutton);
×
1524
  }
1525

1526
  // set the echo mode to password, if the field is "password"
1527
  const QString lineStyle =
1528
      QtPassSettings::isUseMonospace()
×
1529
          ? "border-style: none; background: transparent; font-family: "
1530
            "monospace;"
1531
          : "border-style: none; background: transparent;";
×
1532

1533
  if (QtPassSettings::isHidePassword() && trimmedField == tr("Password")) {
×
1534
    auto *line = new QLineEdit();
×
1535
    line->setObjectName(trimmedField);
×
1536
    line->setText(trimmedValue);
×
1537
    line->setReadOnly(true);
×
1538
    line->setStyleSheet(lineStyle);
×
1539
    line->setContentsMargins(0, 0, 0, 0);
×
1540
    line->setEchoMode(QLineEdit::Password);
×
1541
    auto *showButton = new QPushButtonShowPassword(line, this);
×
1542
    showButton->setStyleSheet(buttonStyle);
×
1543
    showButton->setContentsMargins(0, 0, 0, 0);
×
1544
    frame->layout()->addWidget(showButton);
×
1545
    frame->layout()->addWidget(line);
×
1546
  } else {
1547
    auto *line = new QTextBrowser();
×
1548
    line->setOpenExternalLinks(true);
×
1549
    line->setOpenLinks(true);
×
1550
    line->setMaximumHeight(26);
×
1551
    line->setMinimumHeight(26);
×
1552
    line->setSizePolicy(
×
1553
        QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum));
1554
    line->setObjectName(trimmedField);
×
1555
    trimmedValue.replace(Util::protocolRegex(), R"(<a href="\1">\1</a>)");
×
1556
    line->setText(trimmedValue);
×
1557
    line->setReadOnly(true);
×
1558
    line->setStyleSheet(lineStyle);
×
1559
    line->setContentsMargins(0, 0, 0, 0);
×
1560
    frame->layout()->addWidget(line);
×
1561
  }
1562

1563
  frame->setStyleSheet(
×
1564
      ".QFrame{border: 1px solid lightgrey; border-radius: 5px;}");
1565

1566
  // set into the layout
1567
  ui->gridLayout->addWidget(new QLabel(trimmedField), position, 0);
×
1568
  ui->gridLayout->addWidget(frame, position, 1);
×
1569
}
×
1570

1571
/**
1572
 * @brief Displays message in status bar
1573
 *
1574
 * @param msg     text to be displayed
1575
 * @param timeout time for which msg shall be visible
1576
 */
1577
void MainWindow::showStatusMessage(const QString &msg, int timeout) {
×
1578
  ui->statusBar->showMessage(msg, timeout);
×
1579
}
×
1580

1581
/**
1582
 * @brief MainWindow::reencryptPath re-encrypt all passwords in a directory
1583
 * @param dir Directory path to re-encrypt
1584
 */
1585
void MainWindow::reencryptPath(const QString &dir) {
×
1586
  QDir checkDir(dir);
×
1587
  if (!checkDir.exists()) {
×
1588
    QMessageBox::critical(this, tr("Error"),
×
1589
                          tr("Directory does not exist: %1").arg(dir));
×
1590
    return;
×
1591
  }
1592

1593
  int ret = QMessageBox::question(
×
1594
      this, tr("Re-encrypt passwords"),
×
1595
      tr("Re-encrypt all passwords in %1?\n\n"
×
1596
         "This will re-encrypt ALL password files in this folder "
1597
         "using the current recipients defined in .gpg-id.\n\n"
1598
         "This may rewrite many files and cannot be undone easily.\n\n"
1599
         "Continue?")
1600
          .arg(QDir(dir).dirName()),
×
1601
      QMessageBox::Yes | QMessageBox::No);
1602

1603
  if (ret != QMessageBox::Yes)
×
1604
    return;
1605

1606
  // Prevent double execution - use same method as startReencryptPath
1607
  setUiElementsEnabled(false);
×
1608
  ui->treeView->setDisabled(true);
×
1609

1610
  QtPassSettings::getImitatePass()->reencryptPath(
×
1611
      QDir::cleanPath(QDir(dir).absolutePath()));
×
1612
}
×
1613

1614
/**
1615
 * @brief MainWindow::startReencryptPath disable ui elements and treeview
1616
 */
1617
void MainWindow::startReencryptPath() {
×
1618
  setUiElementsEnabled(false);
×
1619
  ui->treeView->setDisabled(true);
×
1620
}
×
1621

1622
/**
1623
 * @brief MainWindow::endReencryptPath re-enable ui elements
1624
 */
1625
void MainWindow::endReencryptPath() { setUiElementsEnabled(true); }
×
1626

1627
/**
1628
 * @brief MainWindow::exportPublicKey export the configured signing key in
1629
 *        ASCII-armored form via gpg and show it in ExportPublicKeyDialog.
1630
 *
1631
 * Falls back to a help dialog when no signing key is configured or gpg is
1632
 * unavailable, so the user still gets actionable guidance.
1633
 */
1634
void MainWindow::exportPublicKey() {
×
1635
  QString identity = QtPassSettings::getPassSigningKey();
×
1636
  if (identity.isEmpty()) {
×
1637
    QMessageBox::information(
×
1638
        this, tr("Export Public Key"),
×
1639
        tr("<h3>Export Your Public Key</h3>"
×
1640
           "<p>No signing key is configured. Set one in QtPass Settings "
1641
           "&gt; GPG keys, or run this in a terminal:</p>"
1642
           "<pre>gpg --armor --export --output my_key.asc &lt;your-key-id"
1643
           "&gt;</pre>"
1644
           "<p>Then send the file to your teammates.</p>"));
1645
    return;
×
1646
  }
1647
  QString gpgExe = QtPassSettings::getGpgExecutable();
×
1648
  if (gpgExe.isEmpty()) {
×
1649
    gpgExe = QStringLiteral("gpg");
×
1650
  }
1651
  QStringList args = {"--armor", "--export"};
×
1652
  args.append(identity.split(' ', Qt::SkipEmptyParts));
×
1653
  QString stdOut;
×
1654
  QString stdErr;
×
1655
  int exitCode =
1656
      Executor::executeBlocking(gpgExe, args, QString(), &stdOut, &stdErr);
×
1657
  if (exitCode != 0 || stdOut.isEmpty()) {
×
1658
    QMessageBox::warning(this, tr("Export Public Key"),
×
1659
                         tr("Could not export public key for %1.\n\n%2")
×
1660
                             .arg(identity, stdErr.isEmpty()
×
1661
                                                ? tr("No output from gpg.")
×
1662
                                                : stdErr));
1663
    return;
1664
  }
1665
  ExportPublicKeyDialog dialog(identity, stdOut, this);
×
1666
  dialog.exec();
×
1667
}
×
1668

1669
/**
1670
 * @brief MainWindow::addRecipient open the recipient management dialog for
1671
 *        the supplied directory.
1672
 * @param dir Folder whose .gpg-id should be edited.
1673
 *
1674
 * Delegates to UsersDialog so users can tick/untick keys from their
1675
 * keyring as recipients of the folder; importing a foreign key into the
1676
 * keyring still has to happen via gpg (or QtPass settings) first.
1677
 */
1678
void MainWindow::addRecipient(const QString &dir) {
×
1679
  UsersDialog d(dir, this);
×
1680
  d.exec();
×
1681
}
×
1682

1683
/**
1684
 * @brief MainWindow::showShareHelp show help about GPG sharing
1685
 */
1686
void MainWindow::showShareHelp() {
×
1687
  QMessageBox::information(
×
1688
      this, tr("Sharing Passwords with GPG"),
×
1689
      tr("<h3>Sharing Passwords with GPG</h3>"
×
1690
         "<p>To share passwords with other users:</p>"
1691
         "<ol>"
1692
         "<li><b>Export your public key</b> and send it to teammates</li>"
1693
         "<li><b>Import teammates' public keys</b> to their own folders</li>"
1694
         "<li><b>Re-encrypt passwords</b> so all recipients can decrypt "
1695
         "them</li>"
1696
         "</ol>"
1697
         "<p>Only people who have a matching secret key can decrypt the "
1698
         "passwords.</p>"
1699
         "<p><b>Tip:</b> Use the same GPG key for all shared folders.</p>"
1700
         "<p>See the FAQ for more details.</p>"));
1701
}
×
1702

1703
void MainWindow::updateGitButtonVisibility() {
×
1704
  if (!QtPassSettings::isUseGit() ||
×
1705
      (QtPassSettings::getGitExecutable().isEmpty() &&
×
1706
       QtPassSettings::getPassExecutable().isEmpty())) {
×
1707
    enableGitButtons(false);
×
1708
  } else {
1709
    enableGitButtons(true);
×
1710
  }
1711
}
×
1712

1713
void MainWindow::updateOtpButtonVisibility() {
×
1714
#if defined(Q_OS_WIN) || defined(__APPLE__)
1715
  ui->actionOtp->setVisible(false);
1716
#endif
1717
  if (!QtPassSettings::isUseOtp()) {
×
1718
    ui->actionOtp->setEnabled(false);
×
1719
  } else {
1720
    ui->actionOtp->setEnabled(true);
×
1721
  }
1722
}
×
1723

1724
void MainWindow::updateGrepButtonVisibility() {
×
1725
  const bool enabled = QtPassSettings::isUseGrepSearch();
×
1726
  ui->grepButton->setVisible(enabled);
×
1727
  ui->grepCaseButton->setVisible(enabled);
×
1728
  if (!enabled && m_grepMode) {
×
1729
    ui->grepButton->setChecked(false);
×
1730
  }
1731
}
×
1732

1733
void MainWindow::enableGitButtons(const bool &state) {
×
1734
  // Following GNOME guidelines is preferable disable buttons instead of hide
1735
  ui->actionPush->setEnabled(state);
×
1736
  ui->actionUpdate->setEnabled(state);
×
1737
}
×
1738

1739
/**
1740
 * @brief MainWindow::critical critical message popup wrapper.
1741
 * @param title
1742
 * @param msg
1743
 */
1744
void MainWindow::critical(const QString &title, const QString &msg) {
×
1745
  QMessageBox::critical(this, title, msg);
×
1746
}
×
1747

1748
/**
1749
 * @brief Appends processed command output to the output panel.
1750
 *
1751
 * Appends text to the process output text edit, with per-line numbering,
1752
 * optional command prefix, and color coding for errors vs. success.
1753
 * Handles auto-scrolling and line limits.
1754
 *
1755
 * @param output The raw output text from the command.
1756
 * @param isError true if this is error output (stderr).
1757
 * @param linePrefix Optional command name to prefix each line with.
1758
 */
1759
void MainWindow::appendProcessOutput(const QString &output, bool isError,
×
1760
                                     const QString &linePrefix) {
1761
  if (!QtPassSettings::isShowProcessOutput()) {
×
1762
    return;
×
1763
  }
1764

1765
  QStringList lines = output.split('\n', Qt::SkipEmptyParts);
×
1766
  for (QString &line : lines) {
×
1767
    // Right-trim only: remove trailing CR and whitespace, preserve leading
1768
    // indentation
1769
    line.remove('\r');
×
1770
    while (!line.isEmpty() && line.back().isSpace()) {
×
1771
      line.chop(1);
×
1772
    }
1773
    if (line.isEmpty()) {
×
1774
      continue;
×
1775
    }
1776

1777
    m_outputCounter++;
×
1778
    QString lineNumber = QString::number(m_outputCounter);
×
1779

1780
    QColor textColor =
1781
        isError ? QColor(Qt::red)
×
1782
                : ui->processOutputEdit->palette().color(QPalette::Text);
×
1783
    QString colorHex = textColor.name();
×
1784
    // Apply the optional prefix per line so multi-line output stays
1785
    // attributed to its command (e.g. all 3 lines of a `git push` show
1786
    // "git push: ..." rather than only the first).
1787
    QString prefixed =
1788
        linePrefix.isEmpty() ? line : linePrefix + QStringLiteral(": ") + line;
×
1789
    QString coloredOutput =
1790
        QString("<span style=\"color: %1;\">%2: %3</span>")
×
1791
            .arg(colorHex, lineNumber, prefixed.toHtmlEscaped());
×
1792

1793
    ui->processOutputEdit->append(coloredOutput);
×
1794
  }
1795

1796
  limitOutputLines();
×
1797

1798
  if (m_autoScroll) {
×
1799
    ui->processOutputEdit->verticalScrollBar()->setValue(
×
1800
        ui->processOutputEdit->verticalScrollBar()->maximum());
×
1801
  }
1802
}
1803

1804
/**
1805
 * @brief Handles process output from the Pass executor.
1806
 *
1807
 * Called when any non-sensitive process completes. Filters out password-
1808
 * related commands (pass show, insert, etc.) and delegates to
1809
 * appendProcessOutput.
1810
 *
1811
 * @param output The stdout/stderr text from the process.
1812
 * @param isError true if this is error output (stderr).
1813
 * @param pid The process ID identifying which command ran.
1814
 */
1815
void MainWindow::onProcessOutput(const QString &output, bool isError,
×
1816
                                 Enums::PROCESS pid) {
1817
  appendProcessOutput(output, isError, getProcessName(pid));
×
1818
}
×
1819

1820
/**
1821
 * @brief Maps a process ID to its human-readable command name.
1822
 *
1823
 * Returns static strings for git/pass commands that appear in output.
1824
 * Password-related commands return empty (they are filtered).
1825
 *
1826
 * @param pid The process ID to look up.
1827
 * @return QString with command name, or empty if filtered.
1828
 */
1829
auto MainWindow::getProcessName(Enums::PROCESS pid) -> QString {
×
1830
  switch (pid) {
×
1831
  case Enums::GIT_INIT:
×
1832
    return QStringLiteral("git init"); // no-tr
×
1833
  case Enums::GIT_ADD:
×
1834
    return QStringLiteral("git add"); // no-tr
×
1835
  case Enums::GIT_COMMIT:
×
1836
    return QStringLiteral("git commit"); // no-tr
×
1837
  case Enums::GIT_RM:
×
1838
    return QStringLiteral("git rm"); // no-tr
×
1839
  case Enums::GIT_PULL:
×
1840
    return QStringLiteral("git pull"); // no-tr
×
1841
  case Enums::GIT_PUSH:
×
1842
    return QStringLiteral("git push"); // no-tr
×
1843
  case Enums::GIT_MOVE:
×
1844
    return QStringLiteral("git mv"); // no-tr
×
1845
  case Enums::GIT_COPY:
×
1846
    return QStringLiteral("git cp"); // no-tr
×
1847
  case Enums::PASS_INSERT:
×
1848
    return QStringLiteral("pass insert"); // no-tr
×
1849
  case Enums::PASS_REMOVE:
×
1850
    return QStringLiteral("pass rm"); // no-tr
×
1851
  case Enums::PASS_INIT:
×
1852
    return QStringLiteral("pass init"); // no-tr
×
1853
  case Enums::PASS_MOVE:
×
1854
    return QStringLiteral("pass mv"); // no-tr
×
1855
  case Enums::PASS_COPY:
×
1856
    return QStringLiteral("pass cp"); // no-tr
×
1857
  case Enums::PASS_GREP:
×
1858
    return QStringLiteral("pass grep"); // no-tr
×
1859
  case Enums::GPG_GENKEYS:
×
1860
    return QStringLiteral("gpg --gen-key"); // no-tr
×
1861
  case Enums::PASS_SHOW:
1862
  case Enums::PASS_OTP_GENERATE:
1863
  case Enums::PROCESS_COUNT:
1864
  case Enums::INVALID:
1865
    break;
1866
  }
1867
  return QString();
1868
}
1869

1870
/**
1871
 * @brief Checks if a process ID represents a sensitive operation whose
1872
 * output should not be shown in the process output panel.
1873
 *
1874
 * Password-related commands (pass show, OTP generate, grep, insert)
1875
 * display their output in other UI areas, so we skip them here.
1876
 *
1877
 * @param pid The process ID to check.
1878
 * @return true if the process is sensitive and should be filtered.
1879
 */
1880
auto MainWindow::isSensitiveProcess(Enums::PROCESS pid) -> bool {
×
1881
  switch (pid) {
×
1882
  case Enums::PASS_SHOW:
1883
  case Enums::PASS_OTP_GENERATE:
1884
  case Enums::PASS_GREP:
1885
  case Enums::PASS_INSERT:
1886
    return true;
1887
  case Enums::GIT_INIT:
1888
  case Enums::GIT_ADD:
1889
  case Enums::GIT_COMMIT:
1890
  case Enums::GIT_RM:
1891
  case Enums::GIT_PULL:
1892
  case Enums::GIT_PUSH:
1893
  case Enums::GIT_MOVE:
1894
  case Enums::GIT_COPY:
1895
  case Enums::PASS_REMOVE:
1896
  case Enums::PASS_INIT:
1897
  case Enums::PASS_MOVE:
1898
  case Enums::PASS_COPY:
1899
  case Enums::GPG_GENKEYS:
1900
  case Enums::PROCESS_COUNT:
1901
  case Enums::INVALID:
1902
    break;
1903
  }
1904
  return false;
×
1905
}
1906

1907
/**
1908
 * @brief Updates the visibility of the process output panel.
1909
 *
1910
 * Shows or hides the process output widget based on the user's
1911
 * showProcessOutput setting.
1912
 */
1913
void MainWindow::updateProcessOutputVisibility() {
×
1914
  ui->processOutputWidget->setVisible(QtPassSettings::isShowProcessOutput());
×
1915
}
×
1916

1917
/**
1918
 * @brief Limits the output panel to max lines, trimming old excess.
1919
 *
1920
 * Removes the oldest lines when the document exceeds MaxOutputLines (1000).
1921
 * Called after each append to prevent unbounded growth.
1922
 */
1923
void MainWindow::limitOutputLines() {
×
1924
  QTextDocument *doc = ui->processOutputEdit->document();
×
1925
  int excess = doc->blockCount() - MaxOutputLines;
×
1926
  if (excess <= 0) {
×
1927
    return;
×
1928
  }
1929

1930
  QTextCursor cursor(doc);
×
1931
  cursor.movePosition(QTextCursor::Start);
×
1932
  cursor.movePosition(QTextCursor::NextBlock, QTextCursor::KeepAnchor, excess);
×
1933
  cursor.removeSelectedText();
×
1934
}
×
1935

1936
/**
1937
 * @brief Clears the process output panel.
1938
 *
1939
 * Clears all output, resets the line counter, and re-enables auto-scroll.
1940
 */
1941
void MainWindow::on_clearOutputButton_clicked() {
×
1942
  ui->processOutputEdit->clear();
×
1943
  m_outputCounter = 0;
×
1944
  m_autoScroll = true;
×
1945
}
×
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