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

IJHack / QtPass / 24944379542

26 Apr 2026 12:36AM UTC coverage: 27.497% (-0.7%) from 28.163%
24944379542

push

github

web-flow
Merge pull request #1172 from IJHack/feat/252-process-output-area

feat: add process output area to mainwindow (#252)

1 of 119 new or added lines in 5 files covered. (0.84%)

426 existing lines in 6 files now uncovered.

1817 of 6608 relevant lines covered (27.5%)

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

NEW
127
  connect(QtPassSettings::getPass(), &Pass::finishedAnyWithPid, this,
×
NEW
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.
NEW
137
            if (isSensitiveProcess(pid)) {
×
138
              return;
139
            }
NEW
140
            if (!out.isEmpty()) {
×
NEW
141
              onProcessOutput(out, false, pid);
×
142
            }
NEW
143
            if (!err.isEmpty()) {
×
NEW
144
              onProcessOutput(err, true, pid);
×
145
            }
146
          });
147

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

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

162
  setUiElementsEnabled(true);
×
163

164
  QTimer::singleShot(10, this, SLOT(focusInput()));
165

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

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

174
MainWindow::~MainWindow() { delete m_qtPass; }
×
175

176
/**
177
 * @brief MainWindow::focusInput selects any text (if applicable) in the search
178
 * box and sets focus to it. Allows for easy searching, called at application
179
 * start and when receiving empty message in MainWindow::messageAvailable when
180
 * compiled with SINGLE_APP=1 (default).
181
 */
182
void MainWindow::focusInput() {
×
183
  ui->lineEdit->selectAll();
×
184
  ui->lineEdit->setFocus();
×
185
}
×
186

187
/**
188
 * @brief MainWindow::changeEvent sets focus to the search box
189
 * @param event
190
 */
191
void MainWindow::changeEvent(QEvent *event) {
×
192
  QWidget::changeEvent(event);
×
193
  if (event->type() == QEvent::ActivationChange) {
×
194
    if (isActiveWindow()) {
×
195
      focusInput();
×
196
    }
197
  }
198
}
×
199

200
/**
201
 * @brief MainWindow::initToolBarButtons init main ToolBar and connect actions
202
 */
203
void MainWindow::initToolBarButtons() {
×
204
  connect(ui->actionAddPassword, &QAction::triggered, this,
×
205
          &MainWindow::addPassword);
×
206
  connect(ui->actionAddFolder, &QAction::triggered, this,
×
207
          &MainWindow::addFolder);
×
208
  connect(ui->actionEdit, &QAction::triggered, this, &MainWindow::onEdit);
×
209
  connect(ui->actionDelete, &QAction::triggered, this, &MainWindow::onDelete);
×
210
  connect(ui->actionPush, &QAction::triggered, this, &MainWindow::onPush);
×
211
  connect(ui->actionUpdate, &QAction::triggered, this, &MainWindow::onUpdate);
×
212
  connect(ui->actionUsers, &QAction::triggered, this, &MainWindow::onUsers);
×
213
  connect(ui->actionConfig, &QAction::triggered, this, &MainWindow::onConfig);
×
214
  connect(ui->actionOtp, &QAction::triggered, this, &MainWindow::onOtp);
×
215

216
  ui->actionAddPassword->setIcon(
×
217
      QIcon::fromTheme("document-new", QIcon(":/icons/document-new.svg")));
×
218
  ui->actionAddFolder->setIcon(
×
219
      QIcon::fromTheme("folder-new", QIcon(":/icons/folder-new.svg")));
×
220
  ui->actionEdit->setIcon(QIcon::fromTheme(
×
221
      "document-properties", QIcon(":/icons/document-properties.svg")));
×
222
  ui->actionDelete->setIcon(
×
223
      QIcon::fromTheme("edit-delete", QIcon(":/icons/edit-delete.svg")));
×
224
  ui->actionPush->setIcon(
×
225
      QIcon::fromTheme("go-up", QIcon(":/icons/go-top.svg")));
×
226
  ui->actionUpdate->setIcon(
×
227
      QIcon::fromTheme("go-down", QIcon(":/icons/go-bottom.svg")));
×
228
  ui->actionUsers->setIcon(QIcon::fromTheme(
×
229
      "x-office-address-book", QIcon(":/icons/x-office-address-book.svg")));
×
230
  ui->actionConfig->setIcon(QIcon::fromTheme(
×
231
      "applications-system", QIcon(":/icons/applications-system.svg")));
×
232
}
×
233

234
/**
235
 * @brief MainWindow::initStatusBar init statusBar with default message and logo
236
 */
237
void MainWindow::initStatusBar() {
×
238
  ui->statusBar->showMessage(tr("Welcome to QtPass %1").arg(VERSION), 2000);
×
239

240
  QPixmap logo = QPixmap::fromImage(QImage(":/artwork/icon.svg"))
×
241
                     .scaledToHeight(statusBar()->height());
×
242
  auto *logoApp = new QLabel(statusBar());
×
243
  logoApp->setPixmap(logo);
×
244
  statusBar()->addPermanentWidget(logoApp);
×
245

NEW
246
  statusBar()->addPermanentWidget(ui->processOutputWidget);
×
247

NEW
248
  updateProcessOutputVisibility();
×
UNCOV
249
}
×
250

251
auto MainWindow::getCurrentTreeViewIndex() -> QModelIndex {
×
252
  return ui->treeView->currentIndex();
×
253
}
254

255
void MainWindow::cleanKeygenDialog() {
×
256
  if (this->keygenDialog != nullptr) {
×
257
    this->keygenDialog->close();
×
258
  }
259
  this->keygenDialog = nullptr;
×
260
}
×
261

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

282
  if (isHtml) {
×
283
    QString _text = text;
284
    if (!ui->textBrowser->toPlainText().isEmpty()) {
×
285
      _text = ui->textBrowser->toHtml() + _text;
×
286
    }
287
    ui->textBrowser->setHtml(_text);
×
288
  } else {
289
    ui->textBrowser->setText(text);
×
290
  }
291
}
×
292

293
/**
294
 * @brief MainWindow::config pops up the configuration screen and handles all
295
 * inter-window communication
296
 */
297
void MainWindow::applyTextBrowserSettings() {
×
298
  if (QtPassSettings::isUseMonospace()) {
×
299
    QFont monospace("Monospace");
×
300
    monospace.setStyleHint(QFont::Monospace);
×
301
    ui->textBrowser->setFont(monospace);
×
302
  } else {
×
303
    ui->textBrowser->setFont(QFont());
×
304
  }
305

306
  if (QtPassSettings::isNoLineWrapping()) {
×
307
    ui->textBrowser->setLineWrapMode(QTextBrowser::NoWrap);
×
308
  } else {
309
    ui->textBrowser->setLineWrapMode(QTextBrowser::WidgetWidth);
×
310
  }
311
}
×
312

313
void MainWindow::applyWindowFlagsSettings() {
×
314
  if (QtPassSettings::isAlwaysOnTop()) {
×
315
    Qt::WindowFlags flags = windowFlags();
316
    this->setWindowFlags(flags | Qt::WindowStaysOnTopHint);
×
317
  } else {
318
    this->setWindowFlags(Qt::Window);
×
319
  }
320
  this->show();
×
321
}
×
322

323
/**
324
 * @brief Opens and processes the application configuration dialog, then applies
325
 * any accepted settings.
326
 * @example
327
 * config();
328
 *
329
 * @return void - This function does not return a value.
330
 */
331
void MainWindow::config() {
×
332
  QScopedPointer<ConfigDialog> d(new ConfigDialog(this));
×
333
  d->setModal(true);
×
334
  // Automatically default to pass if it's available
335
  if (m_qtPass->isFreshStart() &&
×
336
      QFile(QtPassSettings::getPassExecutable()).exists()) {
×
337
    QtPassSettings::setUsePass(true);
×
338
  }
339

340
  if (m_qtPass->isFreshStart()) {
×
341
    d->wizard(); // run initial setup wizard for first-time configuration
×
342
  }
343
  if (d->exec()) {
×
344
    if (d->result() == QDialog::Accepted) {
×
345
      applyTextBrowserSettings();
×
346
      applyWindowFlagsSettings();
×
347

348
      updateProfileBox();
×
349
      const QString passStore = QtPassSettings::getPassStore();
×
350
      proxyModel.setStore(passStore);
×
351
      ui->treeView->setRootIndex(
×
352
          proxyModel.mapFromSource(model.setRootPath(passStore)));
×
353
      deselect();
×
354
      ui->treeView->setCurrentIndex(QModelIndex());
×
355

356
      if (m_qtPass->isFreshStart() && !Util::configIsValid()) {
×
357
        config();
×
358
      }
359
      QtPassSettings::getPass()->updateEnv();
×
360
      clearPanelTimer.setInterval(MS_PER_SECOND *
×
361
                                  QtPassSettings::getAutoclearPanelSeconds());
×
362
      m_qtPass->setClipboardTimer();
×
363

364
      updateGitButtonVisibility();
×
365
      updateOtpButtonVisibility();
×
366
      updateGrepButtonVisibility();
×
NEW
367
      updateProcessOutputVisibility();
×
368
      if (QtPassSettings::isUseTrayIcon() && tray == nullptr) {
×
369
        initTrayIcon();
×
370
      } else if (!QtPassSettings::isUseTrayIcon() && tray != nullptr) {
×
371
        destroyTrayIcon();
×
372
      }
373
    }
374

375
    m_qtPass->setFreshStart(false);
×
376
  }
377
}
×
378

379
/**
380
 * @brief MainWindow::onUpdate do a git pull
381
 */
382
void MainWindow::onUpdate(bool block) {
×
383
  ui->statusBar->showMessage(tr("Updating password-store"), 2000);
×
384
  if (block) {
×
385
    QtPassSettings::getPass()->GitPull_b();
×
386
  } else {
387
    QtPassSettings::getPass()->GitPull();
×
388
  }
389
}
×
390

391
/**
392
 * @brief MainWindow::onPush do a git push
393
 */
394
void MainWindow::onPush() {
×
395
  if (QtPassSettings::isUseGit()) {
×
396
    ui->statusBar->showMessage(tr("Updating password-store"), 2000);
×
397
    QtPassSettings::getPass()->GitPush();
×
398
  }
399
}
×
400

401
/**
402
 * @brief MainWindow::getFile get the selected file path
403
 * @param index
404
 * @param forPass returns relative path without '.gpg' extension
405
 * @return path
406
 * @return
407
 */
408
auto MainWindow::getFile(const QModelIndex &index, bool forPass) -> QString {
×
409
  if (!index.isValid() ||
×
410
      !model.fileInfo(proxyModel.mapToSource(index)).isFile()) {
×
411
    return {};
412
  }
413
  QString filePath = model.filePath(proxyModel.mapToSource(index));
×
414
  if (forPass) {
×
415
    filePath = QDir(QtPassSettings::getPassStore()).relativeFilePath(filePath);
×
416
    filePath.replace(Util::endsWithGpg(), "");
×
417
  }
418
  return filePath;
419
}
420

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

442
/**
443
 * @brief MainWindow::on_treeView_doubleClicked when doubleclicked on
444
 * TreeViewItem, open the edit Window
445
 * @param index
446
 */
447
void MainWindow::on_treeView_doubleClicked(const QModelIndex &index) {
×
448
  QFileInfo fileOrFolder =
449
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
450

451
  if (fileOrFolder.isFile()) {
×
452
    editPassword(getFile(index, true));
×
453
  }
454
}
×
455

456
/**
457
 * @brief MainWindow::deselect clear the selection, password and copy buffer
458
 */
459
void MainWindow::deselect() {
×
460
  currentDir = "";
×
461
  m_qtPass->clearClipboard();
×
462
  ui->treeView->clearSelection();
×
463
  ui->actionEdit->setEnabled(false);
×
464
  ui->actionDelete->setEnabled(false);
×
465
  ui->passwordName->setText("");
×
466
  clearPanel(false);
×
467
}
×
468

469
void MainWindow::executeWrapperStarted() {
×
470
  clearTemplateWidgets();
×
471
  ui->textBrowser->clear();
×
472
  setUiElementsEnabled(false);
×
473
  clearPanelTimer.stop();
×
NEW
474
  if (QtPassSettings::isShowProcessOutput()) {
×
NEW
475
    ui->processOutputWidget->setVisible(true);
×
476
  }
UNCOV
477
}
×
478

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

499
  // set clipped text
500
  m_qtPass->setClippedText(password, p_output);
×
501

502
  // first clear the current view:
503
  clearTemplateWidgets();
×
504

505
  // show what is needed:
506
  if (QtPassSettings::isHideContent()) {
×
507
    output = "***" + tr("Content hidden") + "***";
×
508
  } else if (!QtPassSettings::isDisplayAsIs()) {
×
509
    if (!password.isEmpty()) {
×
510
      // set the password, it is hidden if needed in addToGridLayout
511
      addToGridLayout(0, tr("Password"), password);
×
512
    }
513

514
    NamedValues namedValues = fileContent.getNamedValues();
×
515
    for (int j = 0; j < namedValues.length(); ++j) {
×
516
      const NamedValue &nv = namedValues.at(j);
517
      addToGridLayout(j + 1, nv.name, nv.value);
×
518
    }
519
    if (ui->gridLayout->count() == 0) {
×
520
      ui->verticalLayoutPassword->setSpacing(0);
×
521
    } else {
522
      ui->verticalLayoutPassword->setSpacing(6);
×
523
    }
524

525
    output = fileContent.getRemainingDataForDisplay();
×
526
  }
527

528
  if (QtPassSettings::isUseAutoclearPanel()) {
×
529
    clearPanelTimer.start();
×
530
  }
531

532
  emit passShowHandlerFinished(output);
×
533
  setUiElementsEnabled(true);
×
534
}
×
535

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

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

593
/**
594
 * @brief MainWindow::setUiElementsEnabled enable or disable the relevant UI
595
 * elements
596
 * @param state
597
 */
598
void MainWindow::setUiElementsEnabled(bool state) {
×
599
  ui->treeView->setEnabled(state);
×
600
  ui->lineEdit->setEnabled(state);
×
601
  ui->lineEdit->installEventFilter(this);
×
602
  ui->actionAddPassword->setEnabled(state);
×
603
  ui->actionAddFolder->setEnabled(state);
×
604
  ui->actionUsers->setEnabled(state);
×
605
  ui->actionConfig->setEnabled(state);
×
606
  // is a file selected?
607
  state &= ui->treeView->currentIndex().isValid();
×
608
  ui->actionDelete->setEnabled(state);
×
609
  ui->actionEdit->setEnabled(state);
×
610
  updateGitButtonVisibility();
×
611
  updateOtpButtonVisibility();
×
612
}
×
613

614
/**
615
 * @brief Restores the main window geometry, state, position, size, and
616
 * tray/icon settings from saved application settings.
617
 * @example
618
 * MainWindow window;
619
 * window.restoreWindow();
620
 *
621
 * @return void - This function does not return a value.
622
 */
623
void MainWindow::restoreWindow() {
×
624
  QByteArray geometry = QtPassSettings::getGeometry(saveGeometry());
×
625
  restoreGeometry(geometry);
×
626
  QByteArray savestate = QtPassSettings::getSavestate(saveState());
×
627
  restoreState(savestate);
×
628
  QPoint position = QtPassSettings::getPos(pos());
×
629
  move(position);
×
630
  QSize newSize = QtPassSettings::getSize(size());
×
631
  resize(newSize);
×
632
  if (QtPassSettings::isMaximized(isMaximized())) {
×
633
    showMaximized();
×
634
  }
635

636
  if (QtPassSettings::isAlwaysOnTop()) {
×
637
    Qt::WindowFlags flags = windowFlags();
638
    setWindowFlags(flags | Qt::WindowStaysOnTopHint);
×
639
    show();
×
640
  }
641

642
  if (QtPassSettings::isUseTrayIcon() && tray == nullptr) {
×
643
    initTrayIcon();
×
644
    if (QtPassSettings::isStartMinimized()) {
×
645
      // since we are still in constructor, can't directly hide
646
      QTimer::singleShot(10, this, SLOT(hide()));
×
647
    }
648
  } else if (!QtPassSettings::isUseTrayIcon() && tray != nullptr) {
×
649
    destroyTrayIcon();
×
650
  }
651
}
×
652

653
/**
654
 * @brief MainWindow::on_configButton_clicked run Mainwindow::config
655
 */
656
void MainWindow::onConfig() { config(); }
×
657

658
/**
659
 * @brief Executes when the string in the search box changes, collapses the
660
 * TreeView
661
 * @param arg1
662
 */
663
void MainWindow::on_lineEdit_textChanged(const QString &arg1) {
×
664
  if (m_grepMode)
×
665
    return;
666
  ui->statusBar->showMessage(tr("Looking for: %1").arg(arg1), 1000);
×
667
  ui->treeView->expandAll();
×
668
  clearPanel(false);
×
669
  ui->passwordName->setText("");
×
670
  ui->actionEdit->setEnabled(false);
×
671
  ui->actionDelete->setEnabled(false);
×
672
  searchTimer.start();
×
673
}
674

675
/**
676
 * @brief MainWindow::onTimeoutSearch Fired when search is finished or too much
677
 * time from two keypresses is elapsed
678
 */
679
void MainWindow::onTimeoutSearch() {
×
680
  QString query = ui->lineEdit->text();
×
681

682
  if (query.isEmpty()) {
×
683
    ui->treeView->collapseAll();
×
684
    deselect();
×
685
  }
686

687
  query.replace(QStringLiteral(" "), ".*");
×
688
  QRegularExpression regExp(query, QRegularExpression::CaseInsensitiveOption);
×
689
  proxyModel.setFilterRegularExpression(regExp);
×
690
  ui->treeView->setRootIndex(proxyModel.mapFromSource(
×
691
      model.setRootPath(QtPassSettings::getPassStore())));
×
692

693
  if (proxyModel.rowCount() > 0 && !query.isEmpty()) {
×
694
    selectFirstFile();
×
695
  } else {
696
    ui->actionEdit->setEnabled(false);
×
697
    ui->actionDelete->setEnabled(false);
×
698
  }
699
}
×
700

701
/**
702
 * @brief MainWindow::on_lineEdit_returnPressed get searching
703
 *
704
 * Select the first possible file in the tree
705
 */
706
void MainWindow::on_lineEdit_returnPressed() {
×
707
#ifdef QT_DEBUG
708
  dbg() << "on_lineEdit_returnPressed" << proxyModel.rowCount();
709
#endif
710

711
  if (m_grepMode) {
×
712
    const QString query = ui->lineEdit->text();
×
713
    if (!query.isEmpty()) {
×
714
      m_grepCancelled = false;
×
715
      ui->grepResultsList->clear();
×
716
      ui->statusBar->showMessage(tr("Searching…"));
×
717
      if (!m_grepBusy) {
×
718
        m_grepBusy = true;
×
719
        QApplication::setOverrideCursor(Qt::WaitCursor);
×
720
      }
721
      QtPassSettings::getPass()->Grep(query, ui->grepCaseButton->isChecked());
×
722
    } else {
723
      m_grepCancelled = true;
×
724
      if (m_grepBusy) {
×
725
        m_grepBusy = false;
×
726
        QApplication::restoreOverrideCursor();
×
727
      }
728
      ui->grepResultsList->clear();
×
729
      ui->grepResultsList->setVisible(false);
×
730
      ui->treeView->setVisible(true);
×
731
    }
732
    return;
733
  }
734

735
  if (proxyModel.rowCount() > 0) {
×
736
    selectFirstFile();
×
737
    on_treeView_clicked(ui->treeView->currentIndex());
×
738
  }
739
}
740

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

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

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

849
/**
850
 * @brief MainWindow::selectFirstFile select the first possible file in the
851
 * tree
852
 */
853
void MainWindow::selectFirstFile() {
×
854
  QModelIndex index = proxyModel.mapFromSource(
×
855
      model.setRootPath(QtPassSettings::getPassStore()));
×
856
  index = firstFile(index);
×
857
  ui->treeView->setCurrentIndex(index);
×
858
}
×
859

860
/**
861
 * @brief MainWindow::firstFile return location of first possible file
862
 * @param parentIndex
863
 * @return QModelIndex
864
 */
865
auto MainWindow::firstFile(QModelIndex parentIndex) -> QModelIndex {
×
866
  QModelIndex index = parentIndex;
×
867
  int numRows = proxyModel.rowCount(parentIndex);
×
868
  for (int row = 0; row < numRows; ++row) {
×
869
    index = proxyModel.index(row, 0, parentIndex);
×
870
    if (model.fileInfo(proxyModel.mapToSource(index)).isFile()) {
×
871
      return index;
×
872
    }
873
    if (proxyModel.hasChildren(index)) {
×
874
      return firstFile(index);
×
875
    }
876
  }
877
  return index;
×
878
}
879

880
/**
881
 * @brief MainWindow::setPassword open passworddialog
882
 * @param file which pgp file
883
 * @param isNew insert (not update)
884
 */
885
void MainWindow::setPassword(const QString &file, bool isNew) {
×
886
  PasswordDialog d(file, isNew, this);
×
887

888
  if (isNew) {
×
889
    QString storePath = QtPassSettings::getPassStore();
×
890
    QString folder =
891
        Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel);
×
892
    if (folder.isEmpty()) {
×
893
      folder = storePath;
×
894
    }
895
    QHash<QString, QStringList> templates = Util::readTemplates(storePath);
×
896
    if (!templates.isEmpty()) {
897
      QString defaultTemplate = Util::getFolderTemplate(folder, storePath);
×
898
      d.setAvailableTemplates(templates, defaultTemplate);
×
899
      new QShortcut(QKeySequence(Qt::CTRL | Qt::Key_T), &d,
×
900
                    [&d]() { d.cycleTemplate(); });
×
901
    }
902
  }
×
903

904
  if (!d.exec()) {
×
905
    ui->treeView->setFocus();
×
906
  }
907
}
×
908

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

931
/**
932
 * @brief MainWindow::onDelete remove password, if you are
933
 * sure.
934
 */
935
void MainWindow::onDelete() {
×
936
  QModelIndex currentIndex = ui->treeView->currentIndex();
×
937
  if (!currentIndex.isValid()) {
938
    // This fixes https://github.com/IJHack/QtPass/issues/556
939
    // Otherwise the entire password directory would be deleted if
940
    // nothing is selected in the tree view.
941
    return;
×
942
  }
943

944
  QFileInfo fileOrFolder =
945
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
946
  QString file = "";
×
947
  bool isDir = false;
948

949
  if (fileOrFolder.isFile()) {
×
950
    file = getFile(ui->treeView->currentIndex(), true);
×
951
  } else {
952
    file = Util::getDir(ui->treeView->currentIndex(), true, model, proxyModel);
×
953
    isDir = true;
954
  }
955

956
  QString dirMessage = tr(" and the whole content?");
957
  if (isDir) {
×
958
    QDirIterator it(model.rootPath() + QDir::separator() + file,
×
959
                    QDirIterator::Subdirectories);
×
960
    bool okDir = true;
961
    while (it.hasNext() && okDir) {
×
962
      it.next();
×
963
      if (QFileInfo(it.filePath()).isFile()) {
×
964
        if (QFileInfo(it.filePath()).suffix() != "gpg") {
×
965
          okDir = false;
966
          dirMessage = tr(" and the whole content? <br><strong>Attention: "
×
967
                          "there are unexpected files in the given folder, "
968
                          "check them before continue.</strong>");
969
        }
970
      }
971
    }
972
  }
×
973

974
  if (QMessageBox::question(
×
975
          this, isDir ? tr("Delete folder?") : tr("Delete password?"),
×
976
          tr("Are you sure you want to delete %1%2?")
×
977
              .arg(QDir::separator() + file, isDir ? dirMessage : "?"),
×
978
          QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) {
979
    return;
980
  }
981

982
  QtPassSettings::getPass()->Remove(file, isDir);
×
983
}
×
984

985
/**
986
 * @brief MainWindow::onOTP try and generate (selected) OTP code.
987
 */
988
void MainWindow::onOtp() {
×
989
  QString file = getFile(ui->treeView->currentIndex(), true);
×
990
  if (!file.isEmpty()) {
×
991
    if (QtPassSettings::isUseOtp()) {
×
992
      setUiElementsEnabled(false);
×
993
      QtPassSettings::getPass()->OtpGenerate(file);
×
994
    }
995
  } else {
996
    flashText(tr("No password selected for OTP generation"), true);
×
997
  }
998
}
×
999

1000
/**
1001
 * @brief MainWindow::onEdit try and edit (selected) password.
1002
 */
1003
void MainWindow::onEdit() {
×
1004
  QString file = getFile(ui->treeView->currentIndex(), true);
×
1005
  editPassword(file);
×
1006
}
×
1007

1008
/**
1009
 * @brief MainWindow::userDialog see MainWindow::onUsers()
1010
 * @param dir folder to edit users for.
1011
 */
1012
void MainWindow::userDialog(const QString &dir) {
×
1013
  if (!dir.isEmpty()) {
×
1014
    currentDir = dir;
×
1015
  }
1016
  onUsers();
×
1017
}
×
1018

1019
/**
1020
 * @brief MainWindow::onUsers edit users for the current
1021
 * folder,
1022
 * gets lists and opens UserDialog.
1023
 */
1024
void MainWindow::onUsers() {
×
1025
  QString dir =
1026
      currentDir.isEmpty()
1027
          ? Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel)
×
1028
          : currentDir;
×
1029

1030
  UsersDialog d(dir, this);
×
1031
  if (!d.exec()) {
×
1032
    ui->treeView->setFocus();
×
1033
  }
1034
}
×
1035

1036
/**
1037
 * @brief MainWindow::messageAvailable we have some text/message/search to do.
1038
 * @param message
1039
 */
1040
void MainWindow::messageAvailable(const QString &message) {
×
1041
  if (message.isEmpty()) {
×
1042
    focusInput();
×
1043
  } else {
1044
    ui->treeView->expandAll();
×
1045
    ui->lineEdit->setText(message);
×
1046
    on_lineEdit_returnPressed();
×
1047
  }
1048
  show();
×
1049
  raise();
×
1050
}
×
1051

1052
/**
1053
 * @brief MainWindow::generateKeyPair internal gpg keypair generator . .
1054
 * @param batch
1055
 * @param keygenWindow
1056
 */
1057
void MainWindow::generateKeyPair(const QString &batch, QDialog *keygenWindow) {
×
1058
  keygenDialog = keygenWindow;
×
1059
  emit generateGPGKeyPair(batch);
×
1060
}
×
1061

1062
/**
1063
 * @brief MainWindow::updateProfileBox update the list of profiles, optionally
1064
 * select a more appropriate one to view too
1065
 */
1066
void MainWindow::updateProfileBox() {
×
1067
  QHash<QString, QHash<QString, QString>> profiles =
1068
      QtPassSettings::getProfiles();
×
1069

1070
  if (profiles.isEmpty()) {
1071
    ui->profileWidget->hide();
×
1072
  } else {
1073
    ui->profileWidget->show();
×
1074
    ui->profileBox->setEnabled(profiles.size() > 1);
×
1075
    ui->profileBox->clear();
×
1076
    QHashIterator<QString, QHash<QString, QString>> i(profiles);
×
1077
    while (i.hasNext()) {
×
1078
      i.next();
1079
      if (!i.key().isEmpty()) {
×
1080
        ui->profileBox->addItem(i.key());
×
1081
      }
1082
    }
1083
    ui->profileBox->model()->sort(0);
×
1084
  }
1085
  int index = ui->profileBox->findText(QtPassSettings::getProfile());
×
1086
  if (index != -1) { //  -1 for not found
×
1087
    ui->profileBox->setCurrentIndex(index);
×
1088
  }
1089
}
×
1090

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

1116
  ui->lineEdit->clear();
×
1117

1118
  QtPassSettings::setProfile(name);
×
1119

1120
  QtPassSettings::setPassStore(
×
1121
      QtPassSettings::getProfiles().value(name).value("path"));
×
1122
  QtPassSettings::setPassSigningKey(
×
1123
      QtPassSettings::getProfiles().value(name).value("signingKey"));
×
1124
  ui->statusBar->showMessage(tr("Profile changed to %1").arg(name), 2000);
×
1125

1126
  QtPassSettings::getPass()->updateEnv();
×
1127

1128
  const QString passStore = QtPassSettings::getPassStore();
×
1129
  proxyModel.setStore(passStore);
×
1130
  ui->treeView->setRootIndex(
×
1131
      proxyModel.mapFromSource(model.setRootPath(passStore)));
×
1132
  deselect();
×
1133
  ui->treeView->setCurrentIndex(QModelIndex());
×
1134
}
1135

1136
/**
1137
 * @brief MainWindow::initTrayIcon show a nice tray icon on systems that
1138
 * support
1139
 * it
1140
 */
1141
void MainWindow::initTrayIcon() {
×
1142
  this->tray = new TrayIcon(this);
×
1143
  // Setup tray icon
1144

1145
  if (tray == nullptr) {
1146
#ifdef QT_DEBUG
1147
    dbg() << "Allocating tray icon failed.";
1148
#endif
1149
    return;
1150
  }
1151

1152
  if (!tray->getIsAllocated()) {
×
1153
    destroyTrayIcon();
×
1154
  }
1155
}
1156

1157
/**
1158
 * @brief MainWindow::destroyTrayIcon remove that pesky tray icon
1159
 */
1160
void MainWindow::destroyTrayIcon() {
×
1161
  delete this->tray;
×
1162
  tray = nullptr;
×
1163
}
×
1164

1165
/**
1166
 * @brief MainWindow::closeEvent hide or quit
1167
 * @param event
1168
 */
1169
void MainWindow::closeEvent(QCloseEvent *event) {
×
1170
  if (QtPassSettings::isHideOnClose()) {
×
1171
    this->hide();
×
1172
    event->ignore();
1173
  } else {
1174
    m_qtPass->clearClipboard();
×
1175

1176
    QtPassSettings::setGeometry(saveGeometry());
×
1177
    QtPassSettings::setSavestate(saveState());
×
1178
    QtPassSettings::setMaximized(isMaximized());
×
1179
    if (!isMaximized()) {
×
1180
      QtPassSettings::setPos(pos());
×
1181
      QtPassSettings::setSize(size());
×
1182
    }
1183
    event->accept();
1184
  }
1185
}
×
1186

1187
/**
1188
 * @brief MainWindow::eventFilter filter out some events and focus the
1189
 * treeview
1190
 * @param obj
1191
 * @param event
1192
 * @return
1193
 */
1194
auto MainWindow::eventFilter(QObject *obj, QEvent *event) -> bool {
×
1195
  if (obj == ui->lineEdit && event->type() == QEvent::KeyPress) {
×
1196
    auto *key = dynamic_cast<QKeyEvent *>(event);
×
1197
    if (key != nullptr && key->key() == Qt::Key_Down) {
×
1198
      ui->treeView->setFocus();
×
1199
    }
1200
  }
1201
  return QObject::eventFilter(obj, event);
×
1202
}
1203

1204
/**
1205
 * @brief MainWindow::keyPressEvent did anyone press return, enter or escape?
1206
 * @param event
1207
 */
1208
void MainWindow::keyPressEvent(QKeyEvent *event) {
×
1209
  switch (event->key()) {
×
1210
  case Qt::Key_Delete:
×
1211
    onDelete();
×
1212
    break;
×
1213
  case Qt::Key_Return:
×
1214
  case Qt::Key_Enter:
1215
    if (proxyModel.rowCount() > 0) {
×
1216
      on_treeView_clicked(ui->treeView->currentIndex());
×
1217
    }
1218
    break;
1219
  case Qt::Key_Escape:
×
1220
    ui->lineEdit->clear();
×
1221
    break;
×
1222
  default:
1223
    break;
1224
  }
1225
}
×
1226

1227
/**
1228
 * @brief MainWindow::showContextMenu show us the (file or folder) context
1229
 * menu
1230
 * @param pos
1231
 */
1232
void MainWindow::showContextMenu(const QPoint &pos) {
×
1233
  QModelIndex index = ui->treeView->indexAt(pos);
×
1234
  bool selected = true;
1235
  if (!index.isValid()) {
1236
    ui->treeView->clearSelection();
×
1237
    ui->actionDelete->setEnabled(false);
×
1238
    ui->actionEdit->setEnabled(false);
×
1239
    currentDir = "";
×
1240
    selected = false;
1241
  }
1242

1243
  ui->treeView->setCurrentIndex(index);
×
1244

1245
  QPoint globalPos = ui->treeView->viewport()->mapToGlobal(pos);
×
1246

1247
  QFileInfo fileOrFolder =
1248
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
1249

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

1282
      QMenu *shareMenu = new QMenu(tr("Share"), &contextMenu);
×
1283
      contextMenu.addMenu(shareMenu);
×
1284

1285
      QString gpgIdPath = Pass::getGpgIdPath(dirPath);
×
1286
      bool gpgIdExists = !gpgIdPath.isEmpty() && QFile(gpgIdPath).exists();
×
1287

1288
      QString exePath = QtPassSettings::isUsePass()
×
1289
                            ? QtPassSettings::getPassExecutable()
×
1290
                            : QtPassSettings::getGpgExecutable();
×
1291
      bool gpgAvailable = !exePath.isEmpty() && (exePath.startsWith("wsl ") ||
×
1292
                                                 QFile(exePath).exists());
×
1293

1294
      QAction *reencrypt = shareMenu->addAction(tr("Re-encrypt all passwords"));
×
1295
      reencrypt->setEnabled(gpgIdExists && gpgAvailable);
×
1296
      connect(reencrypt, &QAction::triggered, this,
×
1297
              [this, dirPath]() { reencryptPath(dirPath); });
×
1298

1299
      QAction *exportKey = shareMenu->addAction(tr("Export my public key..."));
×
1300
      exportKey->setEnabled(gpgAvailable);
×
1301
      connect(exportKey, &QAction::triggered, this,
×
1302
              &MainWindow::exportPublicKey);
×
1303

1304
      QAction *addRecipientAction =
1305
          shareMenu->addAction(tr("Add recipient..."));
×
1306
      addRecipientAction->setEnabled(gpgIdExists && gpgAvailable);
×
1307
      connect(addRecipientAction, &QAction::triggered, this,
×
1308
              [this, dirPath]() { addRecipient(dirPath); });
×
1309

1310
      QAction *shareHelp = shareMenu->addAction(tr("What is this?"));
×
1311
      connect(shareHelp, &QAction::triggered, this, &MainWindow::showShareHelp);
×
1312
    }
1313
  }
1314
  contextMenu.exec(globalPos);
×
1315
}
×
1316

1317
/**
1318
 * @brief MainWindow::showBrowserContextMenu show us the context menu in
1319
 * password window
1320
 * @param pos
1321
 */
1322
void MainWindow::showBrowserContextMenu(const QPoint &pos) {
×
1323
  QMenu *contextMenu = ui->textBrowser->createStandardContextMenu(pos);
×
1324
  QPoint globalPos = ui->textBrowser->viewport()->mapToGlobal(pos);
×
1325

1326
  contextMenu->exec(globalPos);
×
1327
  delete contextMenu;
×
1328
}
×
1329

1330
/**
1331
 * @brief MainWindow::openFolder open the folder in the default file manager
1332
 */
1333
void MainWindow::openFolder() {
×
1334
  QString dir =
1335
      Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel);
×
1336

1337
  QString path = QDir::toNativeSeparators(dir);
×
1338
  QDesktopServices::openUrl(QUrl::fromLocalFile(path));
×
1339
}
×
1340

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

1383
/**
1384
 * @brief MainWindow::renameFolder rename an existing folder
1385
 */
1386
void MainWindow::renameFolder() {
×
1387
  bool ok;
1388
  QString srcDir = QDir::cleanPath(
1389
      Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel));
×
1390
  QString srcDirName = QDir(srcDir).dirName();
×
1391
  QString newName =
1392
      QInputDialog::getText(this, tr("Rename file"), tr("Rename Folder To: "),
×
1393
                            QLineEdit::Normal, srcDirName, &ok);
×
1394
  if (!ok || newName.isEmpty()) {
×
1395
    return;
1396
  }
1397
  QString destDir = srcDir;
1398
  destDir.replace(srcDir.lastIndexOf(srcDirName), srcDirName.length(), newName);
×
1399
  QtPassSettings::getPass()->Move(srcDir, destDir);
×
1400
}
1401

1402
/**
1403
 * @brief MainWindow::editPassword read password and open edit window via
1404
 * MainWindow::onEdit()
1405
 */
1406
void MainWindow::editPassword(const QString &file) {
×
1407
  if (!file.isEmpty()) {
×
1408
    if (QtPassSettings::isUseGit() && QtPassSettings::isAutoPull()) {
×
1409
      onUpdate(true);
×
1410
    }
1411
    setPassword(file, false);
×
1412
  }
1413
}
×
1414

1415
/**
1416
 * @brief MainWindow::renamePassword rename an existing password
1417
 */
1418
void MainWindow::renamePassword() {
×
1419
  bool ok;
1420
  QString file = getFile(ui->treeView->currentIndex(), false);
×
1421
  QString filePath = QFileInfo(file).path();
×
1422
  QString fileName = QFileInfo(file).fileName();
×
1423
  if (fileName.endsWith(".gpg", Qt::CaseInsensitive)) {
×
1424
    fileName.chop(4);
×
1425
  }
1426

1427
  QString newName =
1428
      QInputDialog::getText(this, tr("Rename file"), tr("Rename File To: "),
×
1429
                            QLineEdit::Normal, fileName, &ok);
×
1430
  if (!ok || newName.isEmpty()) {
×
1431
    return;
1432
  }
1433
  QString newFile = QDir(filePath).filePath(newName);
×
1434
  QtPassSettings::getPass()->Move(file, newFile);
×
1435
}
1436

1437
/**
1438
 * @brief MainWindow::clearTemplateWidgets empty the template widget fields in
1439
 * the UI
1440
 */
1441
void MainWindow::clearTemplateWidgets() {
×
1442
  while (ui->gridLayout->count() > 0) {
×
1443
    QLayoutItem *item = ui->gridLayout->takeAt(0);
×
1444
    delete item->widget();
×
1445
    delete item;
×
1446
  }
1447
  ui->verticalLayoutPassword->setSpacing(0);
×
1448
}
×
1449

1450
/**
1451
 * @brief Copies the password of the selected file from the tree view to the
1452
 * clipboard.
1453
 * @example
1454
 * MainWindow::copyPasswordFromTreeview();
1455
 *
1456
 * @return void - This function does not return a value.
1457
 */
1458
void MainWindow::copyPasswordFromTreeview() {
×
1459
  QFileInfo fileOrFolder =
1460
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
1461

1462
  if (fileOrFolder.isFile()) {
×
1463
    QString file = getFile(ui->treeView->currentIndex(), true);
×
1464
    // Disconnect any previous connection to avoid accumulation
1465
    disconnect(QtPassSettings::getPass(), &Pass::finishedShow, this,
×
1466
               &MainWindow::passwordFromFileToClipboard);
1467
    connect(QtPassSettings::getPass(), &Pass::finishedShow, this,
×
1468
            &MainWindow::passwordFromFileToClipboard);
×
1469
    QtPassSettings::getPass()->Show(file);
×
1470
  }
1471
}
×
1472

1473
void MainWindow::passwordFromFileToClipboard(const QString &text) {
×
1474
  QStringList tokens = text.split('\n');
×
1475
  m_qtPass->copyTextToClipboard(tokens[0]);
×
1476
}
×
1477

1478
/**
1479
 * @brief MainWindow::addToGridLayout add a field to the template grid
1480
 * @param position
1481
 * @param field
1482
 * @param value
1483
 */
1484
void MainWindow::addToGridLayout(int position, const QString &field,
×
1485
                                 const QString &value) {
1486
  QString trimmedField = field.trimmed();
1487
  QString trimmedValue = value.trimmed();
1488

1489
  const QString buttonStyle =
1490
      "border-style: none; background: transparent; padding: 0; margin: 0; "
1491
      "icon-size: 16px; color: inherit;";
×
1492

1493
  // Combine the Copy button and the line edit in one widget
1494
  auto *frame = new QFrame();
×
1495
  QLayout *ly = new QHBoxLayout();
×
1496
  ly->setContentsMargins(5, 2, 2, 2);
×
1497
  ly->setSpacing(0);
×
1498
  frame->setLayout(ly);
×
1499
  if (QtPassSettings::getClipBoardType() != Enums::CLIPBOARD_NEVER) {
×
1500
    auto *fieldLabel = new QPushButtonWithClipboard(trimmedValue, this);
×
1501
    connect(fieldLabel, &QPushButtonWithClipboard::clicked, m_qtPass,
×
1502
            &QtPass::copyTextToClipboard);
×
1503

1504
    fieldLabel->setStyleSheet(buttonStyle);
×
1505
    frame->layout()->addWidget(fieldLabel);
×
1506
  }
1507

1508
  if (QtPassSettings::isUseQrencode()) {
×
1509
    auto *qrbutton = new QPushButtonAsQRCode(trimmedValue, this);
×
1510
    connect(qrbutton, &QPushButtonAsQRCode::clicked, m_qtPass,
×
1511
            &QtPass::showTextAsQRCode);
×
1512
    qrbutton->setStyleSheet(buttonStyle);
×
1513
    frame->layout()->addWidget(qrbutton);
×
1514
  }
1515

1516
  // set the echo mode to password, if the field is "password"
1517
  const QString lineStyle =
1518
      QtPassSettings::isUseMonospace()
×
1519
          ? "border-style: none; background: transparent; font-family: "
1520
            "monospace;"
1521
          : "border-style: none; background: transparent;";
×
1522

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

1553
  frame->setStyleSheet(
×
1554
      ".QFrame{border: 1px solid lightgrey; border-radius: 5px;}");
1555

1556
  // set into the layout
1557
  ui->gridLayout->addWidget(new QLabel(trimmedField), position, 0);
×
1558
  ui->gridLayout->addWidget(frame, position, 1);
×
1559
}
×
1560

1561
/**
1562
 * @brief Displays message in status bar
1563
 *
1564
 * @param msg     text to be displayed
1565
 * @param timeout time for which msg shall be visible
1566
 */
1567
void MainWindow::showStatusMessage(const QString &msg, int timeout) {
×
1568
  ui->statusBar->showMessage(msg, timeout);
×
1569
}
×
1570

1571
/**
1572
 * @brief MainWindow::reencryptPath re-encrypt all passwords in a directory
1573
 * @param dir Directory path to re-encrypt
1574
 */
1575
void MainWindow::reencryptPath(const QString &dir) {
×
1576
  QDir checkDir(dir);
×
1577
  if (!checkDir.exists()) {
×
1578
    QMessageBox::critical(this, tr("Error"),
×
1579
                          tr("Directory does not exist: %1").arg(dir));
×
1580
    return;
×
1581
  }
1582

1583
  int ret = QMessageBox::question(
×
1584
      this, tr("Re-encrypt passwords"),
×
1585
      tr("Re-encrypt all passwords in %1?\n\n"
×
1586
         "This will re-encrypt ALL password files in this folder "
1587
         "using the current recipients defined in .gpg-id.\n\n"
1588
         "This may rewrite many files and cannot be undone easily.\n\n"
1589
         "Continue?")
1590
          .arg(QDir(dir).dirName()),
×
1591
      QMessageBox::Yes | QMessageBox::No);
1592

1593
  if (ret != QMessageBox::Yes)
×
1594
    return;
1595

1596
  // Prevent double execution - use same method as startReencryptPath
1597
  setUiElementsEnabled(false);
×
1598
  ui->treeView->setDisabled(true);
×
1599

1600
  QtPassSettings::getImitatePass()->reencryptPath(
×
1601
      QDir::cleanPath(QDir(dir).absolutePath()));
×
1602
}
×
1603

1604
/**
1605
 * @brief MainWindow::startReencryptPath disable ui elements and treeview
1606
 */
1607
void MainWindow::startReencryptPath() {
×
1608
  setUiElementsEnabled(false);
×
1609
  ui->treeView->setDisabled(true);
×
1610
}
×
1611

1612
/**
1613
 * @brief MainWindow::endReencryptPath re-enable ui elements
1614
 */
1615
void MainWindow::endReencryptPath() { setUiElementsEnabled(true); }
×
1616

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

1659
/**
1660
 * @brief MainWindow::addRecipient open the recipient management dialog for
1661
 *        the supplied directory.
1662
 * @param dir Folder whose .gpg-id should be edited.
1663
 *
1664
 * Delegates to UsersDialog so users can tick/untick keys from their
1665
 * keyring as recipients of the folder; importing a foreign key into the
1666
 * keyring still has to happen via gpg (or QtPass settings) first.
1667
 */
1668
void MainWindow::addRecipient(const QString &dir) {
×
1669
  UsersDialog d(dir, this);
×
1670
  d.exec();
×
1671
}
×
1672

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

1693
void MainWindow::updateGitButtonVisibility() {
×
1694
  if (!QtPassSettings::isUseGit() ||
×
1695
      (QtPassSettings::getGitExecutable().isEmpty() &&
×
1696
       QtPassSettings::getPassExecutable().isEmpty())) {
×
1697
    enableGitButtons(false);
×
1698
  } else {
1699
    enableGitButtons(true);
×
1700
  }
1701
}
×
1702

1703
void MainWindow::updateOtpButtonVisibility() {
×
1704
#if defined(Q_OS_WIN) || defined(__APPLE__)
1705
  ui->actionOtp->setVisible(false);
1706
#endif
1707
  if (!QtPassSettings::isUseOtp()) {
×
1708
    ui->actionOtp->setEnabled(false);
×
1709
  } else {
1710
    ui->actionOtp->setEnabled(true);
×
1711
  }
1712
}
×
1713

1714
void MainWindow::updateGrepButtonVisibility() {
×
1715
  const bool enabled = QtPassSettings::isUseGrepSearch();
×
1716
  ui->grepButton->setVisible(enabled);
×
1717
  ui->grepCaseButton->setVisible(enabled);
×
1718
  if (!enabled && m_grepMode) {
×
1719
    ui->grepButton->setChecked(false);
×
1720
  }
1721
}
×
1722

1723
void MainWindow::enableGitButtons(const bool &state) {
×
1724
  // Following GNOME guidelines is preferable disable buttons instead of hide
1725
  ui->actionPush->setEnabled(state);
×
1726
  ui->actionUpdate->setEnabled(state);
×
1727
}
×
1728

1729
/**
1730
 * @brief MainWindow::critical critical message popup wrapper.
1731
 * @param title
1732
 * @param msg
1733
 */
1734
void MainWindow::critical(const QString &title, const QString &msg) {
×
1735
  QMessageBox::critical(this, title, msg);
×
1736
}
×
1737

1738
/**
1739
 * @brief Appends processed command output to the output panel.
1740
 *
1741
 * Appends text to the process output text edit, with per-line numbering,
1742
 * optional command prefix, and color coding for errors vs. success.
1743
 * Handles auto-scrolling and line limits.
1744
 *
1745
 * @param output The raw output text from the command.
1746
 * @param isError true if this is error output (stderr).
1747
 * @param linePrefix Optional command name to prefix each line with.
1748
 */
NEW
1749
void MainWindow::appendProcessOutput(const QString &output, bool isError,
×
1750
                                     const QString &linePrefix) {
NEW
1751
  if (!QtPassSettings::isShowProcessOutput()) {
×
NEW
1752
    return;
×
1753
  }
1754

NEW
1755
  QStringList lines = output.split('\n', Qt::SkipEmptyParts);
×
NEW
1756
  for (QString &line : lines) {
×
1757
    // Right-trim only: remove trailing CR and whitespace, preserve leading
1758
    // indentation
NEW
1759
    line.remove('\r');
×
NEW
1760
    while (!line.isEmpty() && line.back().isSpace()) {
×
NEW
1761
      line.chop(1);
×
1762
    }
NEW
1763
    if (line.isEmpty()) {
×
NEW
1764
      continue;
×
1765
    }
1766

NEW
1767
    m_outputCounter++;
×
NEW
1768
    QString lineNumber = QString::number(m_outputCounter);
×
1769

1770
    QColor textColor =
NEW
1771
        isError ? QColor(Qt::red)
×
NEW
1772
                : ui->processOutputEdit->palette().color(QPalette::Text);
×
NEW
1773
    QString colorHex = textColor.name();
×
1774
    // Apply the optional prefix per line so multi-line output stays
1775
    // attributed to its command (e.g. all 3 lines of a `git push` show
1776
    // "git push: ..." rather than only the first).
1777
    QString prefixed =
NEW
1778
        linePrefix.isEmpty() ? line : linePrefix + QStringLiteral(": ") + line;
×
1779
    QString coloredOutput =
NEW
1780
        QString("<span style=\"color: %1;\">%2: %3</span>")
×
NEW
1781
            .arg(colorHex, lineNumber, prefixed.toHtmlEscaped());
×
1782

NEW
1783
    ui->processOutputEdit->append(coloredOutput);
×
1784
  }
1785

NEW
1786
  limitOutputLines();
×
1787

NEW
1788
  if (m_autoScroll) {
×
NEW
1789
    ui->processOutputEdit->verticalScrollBar()->setValue(
×
NEW
1790
        ui->processOutputEdit->verticalScrollBar()->maximum());
×
1791
  }
1792
}
1793

1794
/**
1795
 * @brief Handles process output from the Pass executor.
1796
 *
1797
 * Called when any non-sensitive process completes. Filters out password-
1798
 * related commands (pass show, insert, etc.) and delegates to
1799
 * appendProcessOutput.
1800
 *
1801
 * @param output The stdout/stderr text from the process.
1802
 * @param isError true if this is error output (stderr).
1803
 * @param pid The process ID identifying which command ran.
1804
 */
NEW
1805
void MainWindow::onProcessOutput(const QString &output, bool isError,
×
1806
                                 Enums::PROCESS pid) {
NEW
1807
  appendProcessOutput(output, isError, getProcessName(pid));
×
NEW
1808
}
×
1809

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

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

1897
/**
1898
 * @brief Updates the visibility of the process output panel.
1899
 *
1900
 * Shows or hides the process output widget based on the user's
1901
 * showProcessOutput setting.
1902
 */
NEW
1903
void MainWindow::updateProcessOutputVisibility() {
×
NEW
1904
  ui->processOutputWidget->setVisible(QtPassSettings::isShowProcessOutput());
×
NEW
1905
}
×
1906

1907
/**
1908
 * @brief Limits the output panel to max lines, trimming old excess.
1909
 *
1910
 * Removes the oldest lines when the document exceeds MaxOutputLines (1000).
1911
 * Called after each append to prevent unbounded growth.
1912
 */
NEW
1913
void MainWindow::limitOutputLines() {
×
NEW
1914
  QTextDocument *doc = ui->processOutputEdit->document();
×
NEW
1915
  int excess = doc->blockCount() - MaxOutputLines;
×
NEW
1916
  if (excess <= 0) {
×
NEW
1917
    return;
×
1918
  }
1919

NEW
1920
  QTextCursor cursor(doc);
×
NEW
1921
  cursor.movePosition(QTextCursor::Start);
×
NEW
1922
  cursor.movePosition(QTextCursor::NextBlock, QTextCursor::KeepAnchor, excess);
×
NEW
1923
  cursor.removeSelectedText();
×
NEW
1924
}
×
1925

1926
/**
1927
 * @brief Clears the process output panel.
1928
 *
1929
 * Clears all output, resets the line counter, and re-enables auto-scroll.
1930
 */
NEW
1931
void MainWindow::on_clearOutputButton_clicked() {
×
NEW
1932
  ui->processOutputEdit->clear();
×
NEW
1933
  m_outputCounter = 0;
×
NEW
1934
  m_autoScroll = true;
×
NEW
1935
}
×
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