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

IJHack / QtPass / 24613047056

18 Apr 2026 08:17PM UTC coverage: 22.643% (+0.7%) from 21.908%
24613047056

Pull #1037

github

web-flow
Merge 238e0f5a7 into 0bcec6d3a
Pull Request #1037: feat: implement pass grep content search (#109)

81 of 237 new or added lines in 7 files covered. (34.18%)

400 existing lines in 9 files now uncovered.

1304 of 5759 relevant lines covered (22.64%)

8.53 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 "filecontent.h"
11
#include "passworddialog.h"
12
#include "qpushbuttonasqrcode.h"
13
#include "qpushbuttonshowpassword.h"
14
#include "qpushbuttonwithclipboard.h"
15
#include "qtpass.h"
16
#include "qtpasssettings.h"
17
#include "trayicon.h"
18
#include "ui_mainwindow.h"
19
#include "usersdialog.h"
20
#include "util.h"
21
#include <QApplication>
22
#include <QCloseEvent>
23
#include <QDesktopServices>
24
#include <QDialog>
25
#include <QDirIterator>
26
#include <QFileInfo>
27
#include <QInputDialog>
28
#include <QLabel>
29
#include <QMenu>
30
#include <QMessageBox>
31
#include <QShortcut>
32
#include <QTimer>
33
#include <QTreeWidget>
34
#include <utility>
35

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

52
  m_qtPass = new QtPass(this);
×
53

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

60
  model.setNameFilters(QStringList() << "*.gpg");
×
61
  model.setNameFilterDisables(false);
×
62

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

70
  QString passStore = QtPassSettings::getPassStore(Util::findPasswordStore());
×
71

72
  QModelIndex rootDir = model.setRootPath(passStore);
×
73
  model.fetchMore(rootDir);
×
74

75
  proxyModel.setModelAndStore(&model, passStore);
×
76
  selectionModel.reset(new QItemSelectionModel(&proxyModel));
×
77

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

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

107
  updateProfileBox();
×
108

109
  QtPassSettings::getPass()->updateEnv();
×
110
  clearPanelTimer.setInterval(MS_PER_SECOND *
×
111
                              QtPassSettings::getAutoclearPanelSeconds());
×
112
  clearPanelTimer.setSingleShot(true);
×
113
  connect(&clearPanelTimer, &QTimer::timeout, this, [this]() { clearPanel(); });
×
114

115
  searchTimer.setInterval(350);
×
116
  searchTimer.setSingleShot(true);
×
117

118
  connect(&searchTimer, &QTimer::timeout, this, &MainWindow::onTimeoutSearch);
×
119

120
  initToolBarButtons();
×
121
  initStatusBar();
×
122

123
  ui->lineEdit->setClearButtonEnabled(true);
×
NEW
124
  updateGrepButtonVisibility();
×
125

126
  setUiElementsEnabled(true);
×
127

128
  QTimer::singleShot(10, this, SLOT(focusInput()));
129

130
  ui->lineEdit->setText(searchText);
×
131

132
  if (!m_qtPass->init()) {
×
133
    // no working config so this should just quit
134
    QApplication::quit();
×
135
  }
136
}
×
137

138
MainWindow::~MainWindow() { delete m_qtPass; }
×
139

140
/**
141
 * @brief MainWindow::focusInput selects any text (if applicable) in the search
142
 * box and sets focus to it. Allows for easy searching, called at application
143
 * start and when receiving empty message in MainWindow::messageAvailable when
144
 * compiled with SINGLE_APP=1 (default).
145
 */
146
void MainWindow::focusInput() {
×
147
  ui->lineEdit->selectAll();
×
148
  ui->lineEdit->setFocus();
×
149
}
×
150

151
/**
152
 * @brief MainWindow::changeEvent sets focus to the search box
153
 * @param event
154
 */
155
void MainWindow::changeEvent(QEvent *event) {
×
156
  QWidget::changeEvent(event);
×
157
  if (event->type() == QEvent::ActivationChange) {
×
158
    if (isActiveWindow()) {
×
159
      focusInput();
×
160
    }
161
  }
162
}
×
163

164
/**
165
 * @brief MainWindow::initToolBarButtons init main ToolBar and connect actions
166
 */
167
void MainWindow::initToolBarButtons() {
×
168
  connect(ui->actionAddPassword, &QAction::triggered, this,
×
169
          &MainWindow::addPassword);
×
170
  connect(ui->actionAddFolder, &QAction::triggered, this,
×
171
          &MainWindow::addFolder);
×
172
  connect(ui->actionEdit, &QAction::triggered, this, &MainWindow::onEdit);
×
173
  connect(ui->actionDelete, &QAction::triggered, this, &MainWindow::onDelete);
×
174
  connect(ui->actionPush, &QAction::triggered, this, &MainWindow::onPush);
×
175
  connect(ui->actionUpdate, &QAction::triggered, this, &MainWindow::onUpdate);
×
176
  connect(ui->actionUsers, &QAction::triggered, this, &MainWindow::onUsers);
×
177
  connect(ui->actionConfig, &QAction::triggered, this, &MainWindow::onConfig);
×
178
  connect(ui->actionOtp, &QAction::triggered, this, &MainWindow::onOtp);
×
179

180
  ui->actionAddPassword->setIcon(
×
181
      QIcon::fromTheme("document-new", QIcon(":/icons/document-new.svg")));
×
182
  ui->actionAddFolder->setIcon(
×
183
      QIcon::fromTheme("folder-new", QIcon(":/icons/folder-new.svg")));
×
184
  ui->actionEdit->setIcon(QIcon::fromTheme(
×
185
      "document-properties", QIcon(":/icons/document-properties.svg")));
×
186
  ui->actionDelete->setIcon(
×
187
      QIcon::fromTheme("edit-delete", QIcon(":/icons/edit-delete.svg")));
×
188
  ui->actionPush->setIcon(
×
189
      QIcon::fromTheme("go-up", QIcon(":/icons/go-top.svg")));
×
190
  ui->actionUpdate->setIcon(
×
191
      QIcon::fromTheme("go-down", QIcon(":/icons/go-bottom.svg")));
×
192
  ui->actionUsers->setIcon(QIcon::fromTheme(
×
193
      "x-office-address-book", QIcon(":/icons/x-office-address-book.svg")));
×
194
  ui->actionConfig->setIcon(QIcon::fromTheme(
×
195
      "applications-system", QIcon(":/icons/applications-system.svg")));
×
196
}
×
197

198
/**
199
 * @brief MainWindow::initStatusBar init statusBar with default message and logo
200
 */
201
void MainWindow::initStatusBar() {
×
202
  ui->statusBar->showMessage(tr("Welcome to QtPass %1").arg(VERSION), 2000);
×
203

204
  QPixmap logo = QPixmap::fromImage(QImage(":/artwork/icon.svg"))
×
205
                     .scaledToHeight(statusBar()->height());
×
206
  auto *logoApp = new QLabel(statusBar());
×
207
  logoApp->setPixmap(logo);
×
208
  statusBar()->addPermanentWidget(logoApp);
×
209
}
×
210

211
auto MainWindow::getCurrentTreeViewIndex() -> QModelIndex {
×
212
  return ui->treeView->currentIndex();
×
213
}
214

215
void MainWindow::cleanKeygenDialog() {
×
216
  this->keygen->close();
×
217
  this->keygen = nullptr;
×
218
}
×
219

220
/**
221
 * @brief Displays the given text in the main window text browser, optionally
222
 * marking it as an error and/or rendering it as HTML.
223
 * @example
224
 * MainWindow window;
225
 * window.flashText("Operation completed.", false, false);
226
 *
227
 * @param const QString &text - The text content to display.
228
 * @param const bool isError - If true, sets the text color to red before
229
 * displaying the text.
230
 * @param const bool isHtml - If true, treats the text as HTML and appends it to
231
 * the existing HTML content.
232
 * @return void - No return value.
233
 */
234
void MainWindow::flashText(const QString &text, const bool isError,
×
235
                           const bool isHtml) {
236
  if (isError) {
×
237
    ui->textBrowser->setTextColor(Qt::red);
×
238
  }
239

240
  if (isHtml) {
×
241
    QString _text = text;
242
    if (!ui->textBrowser->toPlainText().isEmpty()) {
×
243
      _text = ui->textBrowser->toHtml() + _text;
×
244
    }
245
    ui->textBrowser->setHtml(_text);
×
246
  } else {
247
    ui->textBrowser->setText(text);
×
248
  }
249
}
×
250

251
/**
252
 * @brief MainWindow::config pops up the configuration screen and handles all
253
 * inter-window communication
254
 */
255
void MainWindow::applyTextBrowserSettings() {
×
256
  if (QtPassSettings::isUseMonospace()) {
×
257
    QFont monospace("Monospace");
×
258
    monospace.setStyleHint(QFont::Monospace);
×
259
    ui->textBrowser->setFont(monospace);
×
260
  } else {
×
261
    ui->textBrowser->setFont(QFont());
×
262
  }
263

264
  if (QtPassSettings::isNoLineWrapping()) {
×
265
    ui->textBrowser->setLineWrapMode(QTextBrowser::NoWrap);
×
266
  } else {
267
    ui->textBrowser->setLineWrapMode(QTextBrowser::WidgetWidth);
×
268
  }
269
}
×
270

271
void MainWindow::applyWindowFlagsSettings() {
×
272
  if (QtPassSettings::isAlwaysOnTop()) {
×
273
    Qt::WindowFlags flags = windowFlags();
274
    this->setWindowFlags(flags | Qt::WindowStaysOnTopHint);
×
275
  } else {
276
    this->setWindowFlags(Qt::Window);
×
277
  }
278
  this->show();
×
279
}
×
280

281
/**
282
 * @brief Opens and processes the application configuration dialog, then applies
283
 * any accepted settings.
284
 * @example
285
 * config();
286
 *
287
 * @return void - This function does not return a value.
288
 */
289
void MainWindow::config() {
×
290
  QScopedPointer<ConfigDialog> d(new ConfigDialog(this));
×
291
  d->setModal(true);
×
292
  // Automatically default to pass if it's available
293
  if (m_qtPass->isFreshStart() &&
×
294
      QFile(QtPassSettings::getPassExecutable()).exists()) {
×
295
    QtPassSettings::setUsePass(true);
×
296
  }
297

298
  if (m_qtPass->isFreshStart()) {
×
299
    d->wizard(); //  does shit
×
300
  }
301
  if (d->exec()) {
×
302
    if (d->result() == QDialog::Accepted) {
×
303
      applyTextBrowserSettings();
×
304
      applyWindowFlagsSettings();
×
305

306
      updateProfileBox();
×
307
      const QString passStore = QtPassSettings::getPassStore();
×
308
      proxyModel.setStore(passStore);
×
309
      ui->treeView->setRootIndex(
×
310
          proxyModel.mapFromSource(model.setRootPath(passStore)));
×
311
      deselect();
×
312
      ui->treeView->setCurrentIndex(QModelIndex());
×
313

314
      if (m_qtPass->isFreshStart() && !Util::configIsValid()) {
×
315
        config();
×
316
      }
317
      QtPassSettings::getPass()->updateEnv();
×
318
      clearPanelTimer.setInterval(MS_PER_SECOND *
×
319
                                  QtPassSettings::getAutoclearPanelSeconds());
×
320
      m_qtPass->setClipboardTimer();
×
321

322
      updateGitButtonVisibility();
×
323
      updateOtpButtonVisibility();
×
NEW
324
      updateGrepButtonVisibility();
×
325
      if (QtPassSettings::isUseTrayIcon() && tray == nullptr) {
×
326
        initTrayIcon();
×
327
      } else if (!QtPassSettings::isUseTrayIcon() && tray != nullptr) {
×
328
        destroyTrayIcon();
×
329
      }
330
    }
331

332
    m_qtPass->setFreshStart(false);
×
333
  }
334
}
×
335

336
/**
337
 * @brief MainWindow::onUpdate do a git pull
338
 */
339
void MainWindow::onUpdate(bool block) {
×
340
  ui->statusBar->showMessage(tr("Updating password-store"), 2000);
×
341
  if (block) {
×
342
    QtPassSettings::getPass()->GitPull_b();
×
343
  } else {
344
    QtPassSettings::getPass()->GitPull();
×
345
  }
346
}
×
347

348
/**
349
 * @brief MainWindow::onPush do a git push
350
 */
351
void MainWindow::onPush() {
×
352
  if (QtPassSettings::isUseGit()) {
×
353
    ui->statusBar->showMessage(tr("Updating password-store"), 2000);
×
354
    QtPassSettings::getPass()->GitPush();
×
355
  }
356
}
×
357

358
/**
359
 * @brief MainWindow::getFile get the selected file path
360
 * @param index
361
 * @param forPass returns relative path without '.gpg' extension
362
 * @return path
363
 * @return
364
 */
365
auto MainWindow::getFile(const QModelIndex &index, bool forPass) -> QString {
×
366
  if (!index.isValid() ||
×
367
      !model.fileInfo(proxyModel.mapToSource(index)).isFile()) {
×
368
    return {};
369
  }
370
  QString filePath = model.filePath(proxyModel.mapToSource(index));
×
371
  if (forPass) {
×
372
    filePath = QDir(QtPassSettings::getPassStore()).relativeFilePath(filePath);
×
373
    filePath.replace(Util::endsWithGpg(), "");
×
374
  }
375
  return filePath;
376
}
377

378
/**
379
 * @brief MainWindow::on_treeView_clicked read the selected password file
380
 * @param index
381
 */
382
void MainWindow::on_treeView_clicked(const QModelIndex &index) {
×
383
  bool cleared = ui->treeView->currentIndex().flags() == Qt::NoItemFlags;
×
384
  currentDir =
385
      Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel);
×
386
  // Clear any previously cached clipped text before showing new password
387
  m_qtPass->clearClippedText();
×
388
  QString file = getFile(index, true);
×
NEW
389
  ui->passwordName->setText(file);
×
390
  if (!file.isEmpty() && !cleared) {
×
391
    QtPassSettings::getPass()->Show(file);
×
392
  } else {
393
    clearPanel(false);
×
394
    ui->actionEdit->setEnabled(false);
×
395
    ui->actionDelete->setEnabled(true);
×
396
  }
397
}
×
398

399
/**
400
 * @brief MainWindow::on_treeView_doubleClicked when doubleclicked on
401
 * TreeViewItem, open the edit Window
402
 * @param index
403
 */
404
void MainWindow::on_treeView_doubleClicked(const QModelIndex &index) {
×
405
  QFileInfo fileOrFolder =
406
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
407

408
  if (fileOrFolder.isFile()) {
×
409
    editPassword(getFile(index, true));
×
410
  }
411
}
×
412

413
/**
414
 * @brief MainWindow::deselect clear the selection, password and copy buffer
415
 */
416
void MainWindow::deselect() {
×
417
  currentDir = "";
×
418
  m_qtPass->clearClipboard();
×
419
  ui->treeView->clearSelection();
×
420
  ui->actionEdit->setEnabled(false);
×
421
  ui->actionDelete->setEnabled(false);
×
422
  ui->passwordName->setText("");
×
423
  clearPanel(false);
×
424
}
×
425

426
void MainWindow::executeWrapperStarted() {
×
427
  clearTemplateWidgets();
×
428
  ui->textBrowser->clear();
×
429
  setUiElementsEnabled(false);
×
430
  clearPanelTimer.stop();
×
431
}
×
432

433
/**
434
 * @brief Handles displaying parsed password entry content in the main window.
435
 * @example
436
 * void result = MainWindow::passShowHandler(p_output);
437
 * // Updates the UI with parsed fields and emits
438
 * passShowHandlerFinished(output)
439
 *
440
 * @param p_output - The raw output text containing the password entry data.
441
 * @return void - This function does not return a value.
442
 */
443
void MainWindow::passShowHandler(const QString &p_output) {
×
444
  QStringList templ = QtPassSettings::isUseTemplate()
×
445
                          ? QtPassSettings::getPassTemplate().split("\n")
×
446
                          : QStringList();
×
447
  bool allFields =
448
      QtPassSettings::isUseTemplate() && QtPassSettings::isTemplateAllFields();
×
449
  FileContent fileContent = FileContent::parse(p_output, templ, allFields);
×
450
  QString output = p_output;
451
  QString password = fileContent.getPassword();
×
452

453
  // set clipped text
454
  m_qtPass->setClippedText(password, p_output);
×
455

456
  // first clear the current view:
457
  clearTemplateWidgets();
×
458

459
  // show what is needed:
460
  if (QtPassSettings::isHideContent()) {
×
461
    output = "***" + tr("Content hidden") + "***";
×
462
  } else if (!QtPassSettings::isDisplayAsIs()) {
×
463
    if (!password.isEmpty()) {
×
464
      // set the password, it is hidden if needed in addToGridLayout
465
      addToGridLayout(0, tr("Password"), password);
×
466
    }
467

468
    NamedValues namedValues = fileContent.getNamedValues();
×
469
    for (int j = 0; j < namedValues.length(); ++j) {
×
470
      const NamedValue &nv = namedValues.at(j);
471
      addToGridLayout(j + 1, nv.name, nv.value);
×
472
    }
473
    if (ui->gridLayout->count() == 0) {
×
474
      ui->verticalLayoutPassword->setSpacing(0);
×
475
    } else {
476
      ui->verticalLayoutPassword->setSpacing(6);
×
477
    }
478

479
    output = fileContent.getRemainingDataForDisplay();
×
480
  }
481

482
  if (QtPassSettings::isUseAutoclearPanel()) {
×
483
    clearPanelTimer.start();
×
484
  }
485

486
  emit passShowHandlerFinished(output);
×
487
  setUiElementsEnabled(true);
×
488
}
×
489

490
/**
491
 * @brief Handles the OTP output by displaying it, copying it to the clipboard,
492
 * and updating the UI state.
493
 * @example
494
 * void MainWindow::passOtpHandler(const QString &p_output);
495
 *
496
 * @param const QString &p_output - The OTP code text to process; if empty, an
497
 * error message is shown instead.
498
 * @return void - This function does not return a value.
499
 */
500
void MainWindow::passOtpHandler(const QString &p_output) {
×
501
  if (!p_output.isEmpty()) {
×
502
    addToGridLayout(ui->gridLayout->count() + 1, tr("OTP Code"), p_output);
×
503
    m_qtPass->copyTextToClipboard(p_output);
×
504
    showStatusMessage(tr("OTP code copied to clipboard"));
×
505
  } else {
506
    flashText(tr("No OTP code found in this password entry"), true);
×
507
  }
508
  if (QtPassSettings::isUseAutoclearPanel()) {
×
509
    clearPanelTimer.start();
×
510
  }
511
  setUiElementsEnabled(true);
×
512
}
×
513

514
/**
515
 * @brief MainWindow::clearPanel hide the information from shoulder surfers
516
 */
517
void MainWindow::clearPanel(bool notify) {
×
518
  while (ui->gridLayout->count() > 0) {
×
519
    QLayoutItem *item = ui->gridLayout->takeAt(0);
×
520
    delete item->widget();
×
521
    delete item;
×
522
  }
NEW
523
  const bool grepWasVisible = ui->grepResultsList->isVisible();
×
NEW
524
  ui->grepResultsList->clear();
×
NEW
525
  if (grepWasVisible) {
×
NEW
526
    ui->grepResultsList->setVisible(false);
×
NEW
527
    ui->treeView->setVisible(true);
×
NEW
528
    if (m_grepMode) {
×
NEW
529
      m_grepMode = false;
×
NEW
530
      ui->grepButton->blockSignals(true);
×
NEW
531
      ui->grepButton->setChecked(false);
×
NEW
532
      ui->grepButton->blockSignals(false);
×
NEW
533
      ui->lineEdit->blockSignals(true);
×
NEW
534
      ui->lineEdit->clear();
×
NEW
535
      ui->lineEdit->blockSignals(false);
×
NEW
536
      ui->lineEdit->setPlaceholderText(tr("Search Password"));
×
537
    }
538
  }
539
  if (notify) {
×
540
    QString output = "***" + tr("Password and Content hidden") + "***";
×
541
    ui->textBrowser->setHtml(output);
×
542
  } else {
543
    ui->textBrowser->setHtml("");
×
544
  }
545
}
×
546

547
/**
548
 * @brief MainWindow::setUiElementsEnabled enable or disable the relevant UI
549
 * elements
550
 * @param state
551
 */
552
void MainWindow::setUiElementsEnabled(bool state) {
×
553
  ui->treeView->setEnabled(state);
×
554
  ui->lineEdit->setEnabled(state);
×
555
  ui->lineEdit->installEventFilter(this);
×
556
  ui->actionAddPassword->setEnabled(state);
×
557
  ui->actionAddFolder->setEnabled(state);
×
558
  ui->actionUsers->setEnabled(state);
×
559
  ui->actionConfig->setEnabled(state);
×
560
  // is a file selected?
561
  state &= ui->treeView->currentIndex().isValid();
×
562
  ui->actionDelete->setEnabled(state);
×
563
  ui->actionEdit->setEnabled(state);
×
564
  updateGitButtonVisibility();
×
565
  updateOtpButtonVisibility();
×
566
}
×
567

568
/**
569
 * @brief Restores the main window geometry, state, position, size, and
570
 * tray/icon settings from saved application settings.
571
 * @example
572
 * MainWindow window;
573
 * window.restoreWindow();
574
 *
575
 * @return void - This function does not return a value.
576
 */
577
void MainWindow::restoreWindow() {
×
578
  QByteArray geometry = QtPassSettings::getGeometry(saveGeometry());
×
579
  restoreGeometry(geometry);
×
580
  QByteArray savestate = QtPassSettings::getSavestate(saveState());
×
581
  restoreState(savestate);
×
582
  QPoint position = QtPassSettings::getPos(pos());
×
583
  move(position);
×
584
  QSize newSize = QtPassSettings::getSize(size());
×
585
  resize(newSize);
×
586
  if (QtPassSettings::isMaximized(isMaximized())) {
×
587
    showMaximized();
×
588
  }
589

590
  if (QtPassSettings::isAlwaysOnTop()) {
×
591
    Qt::WindowFlags flags = windowFlags();
592
    setWindowFlags(flags | Qt::WindowStaysOnTopHint);
×
593
    show();
×
594
  }
595

596
  if (QtPassSettings::isUseTrayIcon() && tray == nullptr) {
×
597
    initTrayIcon();
×
598
    if (QtPassSettings::isStartMinimized()) {
×
599
      // since we are still in constructor, can't directly hide
600
      QTimer::singleShot(10, this, SLOT(hide()));
×
601
    }
602
  } else if (!QtPassSettings::isUseTrayIcon() && tray != nullptr) {
×
603
    destroyTrayIcon();
×
604
  }
605
}
×
606

607
/**
608
 * @brief MainWindow::on_configButton_clicked run Mainwindow::config
609
 */
610
void MainWindow::onConfig() { config(); }
×
611

612
/**
613
 * @brief Executes when the string in the search box changes, collapses the
614
 * TreeView
615
 * @param arg1
616
 */
617
void MainWindow::on_lineEdit_textChanged(const QString &arg1) {
×
NEW
618
  if (m_grepMode)
×
619
    return;
620
  ui->statusBar->showMessage(tr("Looking for: %1").arg(arg1), 1000);
×
621
  ui->treeView->expandAll();
×
622
  clearPanel(false);
×
623
  ui->passwordName->setText("");
×
624
  ui->actionEdit->setEnabled(false);
×
625
  ui->actionDelete->setEnabled(false);
×
626
  searchTimer.start();
×
627
}
628

629
/**
630
 * @brief MainWindow::onTimeoutSearch Fired when search is finished or too much
631
 * time from two keypresses is elapsed
632
 */
633
void MainWindow::onTimeoutSearch() {
×
634
  QString query = ui->lineEdit->text();
×
635

636
  if (query.isEmpty()) {
×
637
    ui->treeView->collapseAll();
×
638
    deselect();
×
639
  }
640

641
  query.replace(QStringLiteral(" "), ".*");
×
642
  QRegularExpression regExp(query, QRegularExpression::CaseInsensitiveOption);
×
643
  proxyModel.setFilterRegularExpression(regExp);
×
644
  ui->treeView->setRootIndex(proxyModel.mapFromSource(
×
645
      model.setRootPath(QtPassSettings::getPassStore())));
×
646

647
  if (proxyModel.rowCount() > 0 && !query.isEmpty()) {
×
648
    selectFirstFile();
×
649
  } else {
650
    ui->actionEdit->setEnabled(false);
×
651
    ui->actionDelete->setEnabled(false);
×
652
  }
653
}
×
654

655
/**
656
 * @brief MainWindow::on_lineEdit_returnPressed get searching
657
 *
658
 * Select the first possible file in the tree
659
 */
660
void MainWindow::on_lineEdit_returnPressed() {
×
661
#ifdef QT_DEBUG
662
  dbg() << "on_lineEdit_returnPressed" << proxyModel.rowCount();
663
#endif
664

NEW
665
  if (m_grepMode) {
×
NEW
666
    const QString query = ui->lineEdit->text();
×
NEW
667
    if (!query.isEmpty()) {
×
NEW
668
      m_grepCancelled = false;
×
NEW
669
      ui->grepResultsList->clear();
×
NEW
670
      ui->statusBar->showMessage(tr("Searching…"));
×
NEW
671
      if (!m_grepBusy) {
×
NEW
672
        m_grepBusy = true;
×
NEW
673
        QApplication::setOverrideCursor(Qt::WaitCursor);
×
674
      }
NEW
675
      QtPassSettings::getPass()->Grep(query, ui->grepCaseButton->isChecked());
×
676
    } else {
NEW
677
      m_grepCancelled = true;
×
NEW
678
      if (m_grepBusy) {
×
NEW
679
        m_grepBusy = false;
×
NEW
680
        QApplication::restoreOverrideCursor();
×
681
      }
NEW
682
      ui->grepResultsList->clear();
×
NEW
683
      ui->grepResultsList->setVisible(false);
×
NEW
684
      ui->treeView->setVisible(true);
×
685
    }
686
    return;
687
  }
688

689
  if (proxyModel.rowCount() > 0) {
×
690
    selectFirstFile();
×
691
    on_treeView_clicked(ui->treeView->currentIndex());
×
692
  }
693
}
694

695
/**
696
 * @brief Toggle grep (content search) mode.
697
 */
NEW
698
void MainWindow::on_grepButton_toggled(bool checked) {
×
NEW
699
  m_grepMode = checked;
×
NEW
700
  if (checked) {
×
NEW
701
    ui->lineEdit->setPlaceholderText(tr("Search content (regex)"));
×
NEW
702
    ui->lineEdit->clear();
×
NEW
703
    searchTimer.stop();
×
NEW
704
    proxyModel.setFilterRegularExpression(QRegularExpression());
×
NEW
705
    ui->treeView->setRootIndex(proxyModel.mapFromSource(
×
NEW
706
        model.setRootPath(QtPassSettings::getPassStore())));
×
NEW
707
    ui->grepResultsList->setVisible(false);
×
708
    // Keep treeView visible until results arrive
709
  } else {
NEW
710
    searchTimer.stop();
×
NEW
711
    ui->lineEdit->blockSignals(true);
×
NEW
712
    ui->lineEdit->clear();
×
NEW
713
    ui->lineEdit->blockSignals(false);
×
NEW
714
    ui->lineEdit->setPlaceholderText(tr("Search Password"));
×
NEW
715
    ui->grepResultsList->clear();
×
NEW
716
    ui->grepResultsList->setVisible(false);
×
NEW
717
    ui->treeView->setVisible(true);
×
NEW
718
    proxyModel.setFilterRegularExpression(QRegularExpression());
×
NEW
719
    ui->treeView->setRootIndex(proxyModel.mapFromSource(
×
NEW
720
        model.setRootPath(QtPassSettings::getPassStore())));
×
721
  }
NEW
722
}
×
723

724
/**
725
 * @brief Display grep results in grepResultsList.
726
 */
NEW
727
void MainWindow::onGrepFinished(
×
728
    const QList<QPair<QString, QStringList>> &results) {
NEW
729
  if (m_grepBusy) {
×
NEW
730
    m_grepBusy = false;
×
NEW
731
    QApplication::restoreOverrideCursor();
×
732
  }
NEW
733
  if (m_grepCancelled) {
×
NEW
734
    m_grepCancelled = false;
×
NEW
735
    return;
×
736
  }
NEW
737
  setUiElementsEnabled(true);
×
NEW
738
  if (!m_grepMode)
×
739
    return;
NEW
740
  ui->grepResultsList->clear();
×
NEW
741
  if (results.isEmpty()) {
×
NEW
742
    ui->statusBar->showMessage(tr("No matches found."), 3000);
×
NEW
743
    ui->grepResultsList->setVisible(false);
×
NEW
744
    ui->treeView->setVisible(true);
×
NEW
745
    return;
×
746
  }
NEW
747
  const bool hideContent = QtPassSettings::isHideContent();
×
748
  int totalLines = 0;
NEW
749
  for (const auto &pair : results) {
×
NEW
750
    QTreeWidgetItem *entryItem = new QTreeWidgetItem(ui->grepResultsList);
×
NEW
751
    entryItem->setText(0, pair.first);
×
NEW
752
    entryItem->setData(0, Qt::UserRole, pair.first);
×
NEW
753
    for (const QString &line : pair.second) {
×
NEW
754
      QTreeWidgetItem *lineItem = new QTreeWidgetItem(entryItem);
×
NEW
755
      lineItem->setText(0, hideContent ? "***" + tr("Content hidden") + "***"
×
756
                                       : line);
NEW
757
      lineItem->setData(0, Qt::UserRole, pair.first);
×
NEW
758
      ++totalLines;
×
759
    }
760
  }
NEW
761
  ui->grepResultsList->expandAll();
×
NEW
762
  ui->treeView->setVisible(false);
×
NEW
763
  ui->grepResultsList->setVisible(true);
×
NEW
764
  ui->statusBar->showMessage(
×
NEW
765
      tr("Found %n match(es) in %1 entr(ies).", nullptr, totalLines)
×
NEW
766
          .arg(results.size()),
×
767
      3000);
NEW
768
  if (QtPassSettings::isUseAutoclearPanel())
×
NEW
769
    clearPanelTimer.start();
×
770
}
771

772
/**
773
 * @brief Navigate to the password entry when a grep result is clicked.
774
 */
NEW
775
void MainWindow::on_grepResultsList_itemClicked(QTreeWidgetItem *item,
×
776
                                                int /*column*/) {
NEW
777
  const QString entry = item->data(0, Qt::UserRole).toString();
×
NEW
778
  if (entry.isEmpty())
×
779
    return;
780
  const QString fullPath = QDir::cleanPath(
NEW
781
      QDir(QtPassSettings::getPassStore()).filePath(entry + ".gpg"));
×
NEW
782
  QModelIndex srcIndex = model.index(fullPath);
×
783
  if (!srcIndex.isValid())
784
    return;
NEW
785
  QModelIndex proxyIndex = proxyModel.mapFromSource(srcIndex);
×
786
  if (!proxyIndex.isValid())
787
    return;
NEW
788
  ui->treeView->setCurrentIndex(proxyIndex);
×
NEW
789
  on_treeView_clicked(proxyIndex);
×
NEW
790
  if (QtPassSettings::isHideContent() || QtPassSettings::isUseAutoclearPanel())
×
NEW
791
    ui->grepResultsList->clear();
×
NEW
792
  ui->grepResultsList->setVisible(false);
×
NEW
793
  ui->treeView->setVisible(true);
×
NEW
794
  ui->treeView->scrollTo(proxyIndex);
×
NEW
795
  ui->treeView->setFocus();
×
796
}
797

798
/**
799
 * @brief MainWindow::selectFirstFile select the first possible file in the
800
 * tree
801
 */
802
void MainWindow::selectFirstFile() {
×
803
  QModelIndex index = proxyModel.mapFromSource(
×
804
      model.setRootPath(QtPassSettings::getPassStore()));
×
805
  index = firstFile(index);
×
806
  ui->treeView->setCurrentIndex(index);
×
807
}
×
808

809
/**
810
 * @brief MainWindow::firstFile return location of first possible file
811
 * @param parentIndex
812
 * @return QModelIndex
813
 */
814
auto MainWindow::firstFile(QModelIndex parentIndex) -> QModelIndex {
×
815
  QModelIndex index = parentIndex;
×
816
  int numRows = proxyModel.rowCount(parentIndex);
×
817
  for (int row = 0; row < numRows; ++row) {
×
818
    index = proxyModel.index(row, 0, parentIndex);
×
819
    if (model.fileInfo(proxyModel.mapToSource(index)).isFile()) {
×
820
      return index;
×
821
    }
822
    if (proxyModel.hasChildren(index)) {
×
823
      return firstFile(index);
×
824
    }
825
  }
826
  return index;
×
827
}
828

829
/**
830
 * @brief MainWindow::setPassword open passworddialog
831
 * @param file which pgp file
832
 * @param isNew insert (not update)
833
 */
834
void MainWindow::setPassword(const QString &file, bool isNew) {
×
835
  PasswordDialog d(file, isNew, this);
×
836

837
  if (!d.exec()) {
×
838
    ui->treeView->setFocus();
×
839
  }
840
}
×
841

842
/**
843
 * @brief MainWindow::addPassword add a new password by showing a
844
 * number of dialogs.
845
 */
846
void MainWindow::addPassword() {
×
847
  bool ok;
848
  QString dir =
849
      Util::getDir(ui->treeView->currentIndex(), true, model, proxyModel);
×
850
  QString file =
851
      QInputDialog::getText(this, tr("New file"),
×
852
                            tr("New password file: \n(Will be placed in %1 )")
×
853
                                .arg(QtPassSettings::getPassStore() +
×
854
                                     Util::getDir(ui->treeView->currentIndex(),
×
855
                                                  true, model, proxyModel)),
856
                            QLineEdit::Normal, "", &ok);
×
857
  if (!ok || file.isEmpty()) {
×
858
    return;
859
  }
860
  file = dir + file;
×
861
  setPassword(file);
×
862
}
863

864
/**
865
 * @brief MainWindow::onDelete remove password, if you are
866
 * sure.
867
 */
868
void MainWindow::onDelete() {
×
869
  QModelIndex currentIndex = ui->treeView->currentIndex();
×
870
  if (!currentIndex.isValid()) {
871
    // This fixes https://github.com/IJHack/QtPass/issues/556
872
    // Otherwise the entire password directory would be deleted if
873
    // nothing is selected in the tree view.
874
    return;
×
875
  }
876

877
  QFileInfo fileOrFolder =
878
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
879
  QString file = "";
×
880
  bool isDir = false;
881

882
  if (fileOrFolder.isFile()) {
×
883
    file = getFile(ui->treeView->currentIndex(), true);
×
884
  } else {
885
    file = Util::getDir(ui->treeView->currentIndex(), true, model, proxyModel);
×
886
    isDir = true;
887
  }
888

889
  QString dirMessage = tr(" and the whole content?");
890
  if (isDir) {
×
891
    QDirIterator it(model.rootPath() + QDir::separator() + file,
×
892
                    QDirIterator::Subdirectories);
×
893
    bool okDir = true;
894
    while (it.hasNext() && okDir) {
×
895
      it.next();
×
896
      if (QFileInfo(it.filePath()).isFile()) {
×
897
        if (QFileInfo(it.filePath()).suffix() != "gpg") {
×
898
          okDir = false;
899
          dirMessage = tr(" and the whole content? <br><strong>Attention: "
×
900
                          "there are unexpected files in the given folder, "
901
                          "check them before continue.</strong>");
902
        }
903
      }
904
    }
905
  }
×
906

907
  if (QMessageBox::question(
×
908
          this, isDir ? tr("Delete folder?") : tr("Delete password?"),
×
909
          tr("Are you sure you want to delete %1%2?")
×
910
              .arg(QDir::separator() + file, isDir ? dirMessage : "?"),
×
911
          QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) {
912
    return;
913
  }
914

915
  QtPassSettings::getPass()->Remove(file, isDir);
×
916
}
×
917

918
/**
919
 * @brief MainWindow::onOTP try and generate (selected) OTP code.
920
 */
921
void MainWindow::onOtp() {
×
922
  QString file = getFile(ui->treeView->currentIndex(), true);
×
923
  if (!file.isEmpty()) {
×
924
    if (QtPassSettings::isUseOtp()) {
×
925
      setUiElementsEnabled(false);
×
926
      QtPassSettings::getPass()->OtpGenerate(file);
×
927
    }
928
  } else {
929
    flashText(tr("No password selected for OTP generation"), true);
×
930
  }
931
}
×
932

933
/**
934
 * @brief MainWindow::onEdit try and edit (selected) password.
935
 */
936
void MainWindow::onEdit() {
×
937
  QString file = getFile(ui->treeView->currentIndex(), true);
×
938
  editPassword(file);
×
939
}
×
940

941
/**
942
 * @brief MainWindow::userDialog see MainWindow::onUsers()
943
 * @param dir folder to edit users for.
944
 */
945
void MainWindow::userDialog(const QString &dir) {
×
946
  if (!dir.isEmpty()) {
×
947
    currentDir = dir;
×
948
  }
949
  onUsers();
×
950
}
×
951

952
/**
953
 * @brief MainWindow::onUsers edit users for the current
954
 * folder,
955
 * gets lists and opens UserDialog.
956
 */
957
void MainWindow::onUsers() {
×
958
  QString dir =
959
      currentDir.isEmpty()
960
          ? Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel)
×
961
          : currentDir;
×
962

963
  UsersDialog d(dir, this);
×
964
  if (!d.exec()) {
×
965
    ui->treeView->setFocus();
×
966
  }
967
}
×
968

969
/**
970
 * @brief MainWindow::messageAvailable we have some text/message/search to do.
971
 * @param message
972
 */
973
void MainWindow::messageAvailable(const QString &message) {
×
974
  if (message.isEmpty()) {
×
975
    focusInput();
×
976
  } else {
977
    ui->treeView->expandAll();
×
978
    ui->lineEdit->setText(message);
×
979
    on_lineEdit_returnPressed();
×
980
  }
981
  show();
×
982
  raise();
×
983
}
×
984

985
/**
986
 * @brief MainWindow::generateKeyPair internal gpg keypair generator . .
987
 * @param batch
988
 * @param keygenWindow
989
 */
990
void MainWindow::generateKeyPair(const QString &batch, QDialog *keygenWindow) {
×
991
  keygen = keygenWindow;
×
992
  emit generateGPGKeyPair(batch);
×
993
}
×
994

995
/**
996
 * @brief MainWindow::updateProfileBox update the list of profiles, optionally
997
 * select a more appropriate one to view too
998
 */
999
void MainWindow::updateProfileBox() {
×
1000
  QHash<QString, QHash<QString, QString>> profiles =
1001
      QtPassSettings::getProfiles();
×
1002

1003
  if (profiles.isEmpty()) {
1004
    ui->profileWidget->hide();
×
1005
  } else {
1006
    ui->profileWidget->show();
×
1007
    ui->profileBox->setEnabled(profiles.size() > 1);
×
1008
    ui->profileBox->clear();
×
1009
    QHashIterator<QString, QHash<QString, QString>> i(profiles);
×
1010
    while (i.hasNext()) {
×
1011
      i.next();
1012
      if (!i.key().isEmpty()) {
×
1013
        ui->profileBox->addItem(i.key());
×
1014
      }
1015
    }
1016
    ui->profileBox->model()->sort(0);
×
1017
  }
1018
  int index = ui->profileBox->findText(QtPassSettings::getProfile());
×
1019
  if (index != -1) { //  -1 for not found
×
1020
    ui->profileBox->setCurrentIndex(index);
×
1021
  }
1022
}
×
1023

1024
/**
1025
 * @brief MainWindow::on_profileBox_currentIndexChanged make sure we show the
1026
 * correct "profile"
1027
 * @param name
1028
 */
1029
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
1030
void MainWindow::on_profileBox_currentIndexChanged(QString name) {
1031
#else
1032
/**
1033
 * @brief Handles changes to the selected profile in the profile combo box.
1034
 * @details Ignores the event during a fresh start or when the selected profile
1035
 * matches the current profile. Otherwise, it clears the password field, updates
1036
 * the active profile and related settings, refreshes the environment, and
1037
 * resets the tree view and action states to reflect the newly selected profile.
1038
 *
1039
 * @param name - The newly selected profile name.
1040
 * @return void - This function does not return a value.
1041
 *
1042
 */
1043
void MainWindow::on_profileBox_currentTextChanged(const QString &name) {
×
1044
#endif
1045
  if (m_qtPass->isFreshStart() || name == QtPassSettings::getProfile()) {
×
1046
    return;
×
1047
  }
1048

1049
  ui->lineEdit->clear();
×
1050

1051
  QtPassSettings::setProfile(name);
×
1052

1053
  QtPassSettings::setPassStore(
×
1054
      QtPassSettings::getProfiles().value(name).value("path"));
×
1055
  QtPassSettings::setPassSigningKey(
×
1056
      QtPassSettings::getProfiles().value(name).value("signingKey"));
×
1057
  ui->statusBar->showMessage(tr("Profile changed to %1").arg(name), 2000);
×
1058

1059
  QtPassSettings::getPass()->updateEnv();
×
1060

1061
  const QString passStore = QtPassSettings::getPassStore();
×
1062
  proxyModel.setStore(passStore);
×
1063
  ui->treeView->setRootIndex(
×
1064
      proxyModel.mapFromSource(model.setRootPath(passStore)));
×
1065
  deselect();
×
1066
  ui->treeView->setCurrentIndex(QModelIndex());
×
1067
}
1068

1069
/**
1070
 * @brief MainWindow::initTrayIcon show a nice tray icon on systems that
1071
 * support
1072
 * it
1073
 */
1074
void MainWindow::initTrayIcon() {
×
1075
  this->tray = new TrayIcon(this);
×
1076
  // Setup tray icon
1077

1078
  if (tray == nullptr) {
1079
#ifdef QT_DEBUG
1080
    dbg() << "Allocating tray icon failed.";
1081
#endif
1082
  }
1083

1084
  if (!tray->getIsAllocated()) {
×
1085
    destroyTrayIcon();
×
1086
  }
1087
}
×
1088

1089
/**
1090
 * @brief MainWindow::destroyTrayIcon remove that pesky tray icon
1091
 */
1092
void MainWindow::destroyTrayIcon() {
×
1093
  delete this->tray;
×
1094
  tray = nullptr;
×
1095
}
×
1096

1097
/**
1098
 * @brief MainWindow::closeEvent hide or quit
1099
 * @param event
1100
 */
1101
void MainWindow::closeEvent(QCloseEvent *event) {
×
1102
  if (QtPassSettings::isHideOnClose()) {
×
1103
    this->hide();
×
1104
    event->ignore();
1105
  } else {
1106
    m_qtPass->clearClipboard();
×
1107

1108
    QtPassSettings::setGeometry(saveGeometry());
×
1109
    QtPassSettings::setSavestate(saveState());
×
1110
    QtPassSettings::setMaximized(isMaximized());
×
1111
    if (!isMaximized()) {
×
1112
      QtPassSettings::setPos(pos());
×
1113
      QtPassSettings::setSize(size());
×
1114
    }
1115
    event->accept();
1116
  }
1117
}
×
1118

1119
/**
1120
 * @brief MainWindow::eventFilter filter out some events and focus the
1121
 * treeview
1122
 * @param obj
1123
 * @param event
1124
 * @return
1125
 */
1126
auto MainWindow::eventFilter(QObject *obj, QEvent *event) -> bool {
×
1127
  if (obj == ui->lineEdit && event->type() == QEvent::KeyPress) {
×
1128
    auto *key = dynamic_cast<QKeyEvent *>(event);
×
1129
    if (key != nullptr && key->key() == Qt::Key_Down) {
×
1130
      ui->treeView->setFocus();
×
1131
    }
1132
  }
1133
  return QObject::eventFilter(obj, event);
×
1134
}
1135

1136
/**
1137
 * @brief MainWindow::keyPressEvent did anyone press return, enter or escape?
1138
 * @param event
1139
 */
1140
void MainWindow::keyPressEvent(QKeyEvent *event) {
×
1141
  switch (event->key()) {
×
1142
  case Qt::Key_Delete:
×
1143
    onDelete();
×
1144
    break;
×
1145
  case Qt::Key_Return:
×
1146
  case Qt::Key_Enter:
1147
    if (proxyModel.rowCount() > 0) {
×
1148
      on_treeView_clicked(ui->treeView->currentIndex());
×
1149
    }
1150
    break;
1151
  case Qt::Key_Escape:
×
1152
    ui->lineEdit->clear();
×
1153
    break;
×
1154
  default:
1155
    break;
1156
  }
1157
}
×
1158

1159
/**
1160
 * @brief MainWindow::showContextMenu show us the (file or folder) context
1161
 * menu
1162
 * @param pos
1163
 */
1164
void MainWindow::showContextMenu(const QPoint &pos) {
×
1165
  QModelIndex index = ui->treeView->indexAt(pos);
×
1166
  bool selected = true;
1167
  if (!index.isValid()) {
1168
    ui->treeView->clearSelection();
×
1169
    ui->actionDelete->setEnabled(false);
×
1170
    ui->actionEdit->setEnabled(false);
×
1171
    currentDir = "";
×
1172
    selected = false;
1173
  }
1174

1175
  ui->treeView->setCurrentIndex(index);
×
1176

1177
  QPoint globalPos = ui->treeView->viewport()->mapToGlobal(pos);
×
1178

1179
  QFileInfo fileOrFolder =
1180
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
1181

1182
  QMenu contextMenu;
×
1183
  if (!selected || fileOrFolder.isDir()) {
×
1184
    QAction *openFolder =
1185
        contextMenu.addAction(tr("Open folder with file manager"));
×
1186
    QAction *addFolder = contextMenu.addAction(tr("Add folder"));
×
1187
    QAction *addPassword = contextMenu.addAction(tr("Add password"));
×
1188
    QAction *users = contextMenu.addAction(tr("Users"));
×
1189
    connect(openFolder, &QAction::triggered, this, &MainWindow::openFolder);
×
1190
    connect(addFolder, &QAction::triggered, this, &MainWindow::addFolder);
×
1191
    connect(addPassword, &QAction::triggered, this, &MainWindow::addPassword);
×
1192
    connect(users, &QAction::triggered, this, &MainWindow::onUsers);
×
1193
  } else if (fileOrFolder.isFile()) {
×
1194
    QAction *edit = contextMenu.addAction(tr("Edit"));
×
1195
    connect(edit, &QAction::triggered, this, &MainWindow::onEdit);
×
1196
  }
1197
  if (selected) {
×
1198
    contextMenu.addSeparator();
×
1199
    if (fileOrFolder.isDir()) {
×
1200
      QAction *renameFolder = contextMenu.addAction(tr("Rename folder"));
×
1201
      connect(renameFolder, &QAction::triggered, this,
×
1202
              &MainWindow::renameFolder);
×
1203
    } else if (fileOrFolder.isFile()) {
×
1204
      QAction *renamePassword = contextMenu.addAction(tr("Rename password"));
×
1205
      connect(renamePassword, &QAction::triggered, this,
×
1206
              &MainWindow::renamePassword);
×
1207
    }
1208
    QAction *deleteItem = contextMenu.addAction(tr("Delete"));
×
1209
    connect(deleteItem, &QAction::triggered, this, &MainWindow::onDelete);
×
1210
    if (fileOrFolder.isDir()) {
×
1211
      QString dirPath = QDir::cleanPath(
1212
          Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel));
×
1213
      QAction *reencrypt = contextMenu.addAction(tr("Re-encrypt"));
×
1214
      connect(reencrypt, &QAction::triggered, this,
×
1215
              [this, dirPath]() { reencryptPath(dirPath); });
×
1216
    }
1217
  }
1218
  contextMenu.exec(globalPos);
×
1219
}
×
1220

1221
/**
1222
 * @brief MainWindow::showBrowserContextMenu show us the context menu in
1223
 * password window
1224
 * @param pos
1225
 */
1226
void MainWindow::showBrowserContextMenu(const QPoint &pos) {
×
1227
  QMenu *contextMenu = ui->textBrowser->createStandardContextMenu(pos);
×
1228
  QPoint globalPos = ui->textBrowser->viewport()->mapToGlobal(pos);
×
1229

1230
  contextMenu->exec(globalPos);
×
1231
  delete contextMenu;
×
1232
}
×
1233

1234
/**
1235
 * @brief MainWindow::openFolder open the folder in the default file manager
1236
 */
1237
void MainWindow::openFolder() {
×
1238
  QString dir =
1239
      Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel);
×
1240

1241
  QString path = QDir::toNativeSeparators(dir);
×
1242
  QDesktopServices::openUrl(QUrl::fromLocalFile(path));
×
1243
}
×
1244

1245
/**
1246
 * @brief MainWindow::addFolder add a new folder to store passwords in
1247
 */
1248
void MainWindow::addFolder() {
×
1249
  bool ok;
1250
  QString dir =
1251
      Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel);
×
1252
  QString newdir =
1253
      QInputDialog::getText(this, tr("New file"),
×
1254
                            tr("New Folder: \n(Will be placed in %1 )")
×
1255
                                .arg(QtPassSettings::getPassStore() +
×
1256
                                     Util::getDir(ui->treeView->currentIndex(),
×
1257
                                                  true, model, proxyModel)),
1258
                            QLineEdit::Normal, "", &ok);
×
1259
  if (!ok || newdir.isEmpty()) {
×
1260
    return;
1261
  }
1262
  newdir.prepend(dir);
1263
  if (!QDir().mkdir(newdir)) {
×
1264
    QMessageBox::warning(this, tr("Error"),
×
1265
                         tr("Failed to create folder: %1").arg(newdir));
×
1266
    return;
×
1267
  }
1268
  if (QtPassSettings::isAddGPGId(true)) {
×
1269
    QString gpgIdFile = newdir + "/.gpg-id";
×
1270
    QFile gpgId(gpgIdFile);
×
1271
    if (!gpgId.open(QIODevice::WriteOnly)) {
×
1272
      QMessageBox::warning(
×
1273
          this, tr("Error"),
×
1274
          tr("Failed to create .gpg-id file in: %1").arg(newdir));
×
1275
      return;
1276
    }
1277
    QList<UserInfo> users = QtPassSettings::getPass()->listKeys("", true);
×
1278
    for (const UserInfo &user : users) {
×
1279
      if (user.enabled) {
×
1280
        gpgId.write((user.key_id + "\n").toUtf8());
×
1281
      }
1282
    }
1283
    gpgId.close();
×
1284
  }
×
1285
}
1286

1287
/**
1288
 * @brief MainWindow::renameFolder rename an existing folder
1289
 */
1290
void MainWindow::renameFolder() {
×
1291
  bool ok;
1292
  QString srcDir = QDir::cleanPath(
1293
      Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel));
×
1294
  QString srcDirName = QDir(srcDir).dirName();
×
1295
  QString newName =
1296
      QInputDialog::getText(this, tr("Rename file"), tr("Rename Folder To: "),
×
1297
                            QLineEdit::Normal, srcDirName, &ok);
×
1298
  if (!ok || newName.isEmpty()) {
×
1299
    return;
1300
  }
1301
  QString destDir = srcDir;
1302
  destDir.replace(srcDir.lastIndexOf(srcDirName), srcDirName.length(), newName);
×
1303
  QtPassSettings::getPass()->Move(srcDir, destDir);
×
1304
}
1305

1306
/**
1307
 * @brief MainWindow::editPassword read password and open edit window via
1308
 * MainWindow::onEdit()
1309
 */
1310
void MainWindow::editPassword(const QString &file) {
×
1311
  if (!file.isEmpty()) {
×
1312
    if (QtPassSettings::isUseGit() && QtPassSettings::isAutoPull()) {
×
1313
      onUpdate(true);
×
1314
    }
1315
    setPassword(file, false);
×
1316
  }
1317
}
×
1318

1319
/**
1320
 * @brief MainWindow::renamePassword rename an existing password
1321
 */
1322
void MainWindow::renamePassword() {
×
1323
  bool ok;
1324
  QString file = getFile(ui->treeView->currentIndex(), false);
×
1325
  QString filePath = QFileInfo(file).path();
×
1326
  QString fileName = QFileInfo(file).fileName();
×
1327
  if (fileName.endsWith(".gpg", Qt::CaseInsensitive)) {
×
1328
    fileName.chop(4);
×
1329
  }
1330

1331
  QString newName =
1332
      QInputDialog::getText(this, tr("Rename file"), tr("Rename File To: "),
×
1333
                            QLineEdit::Normal, fileName, &ok);
×
1334
  if (!ok || newName.isEmpty()) {
×
1335
    return;
1336
  }
1337
  QString newFile = QDir(filePath).filePath(newName);
×
1338
  QtPassSettings::getPass()->Move(file, newFile);
×
1339
}
1340

1341
/**
1342
 * @brief MainWindow::clearTemplateWidgets empty the template widget fields in
1343
 * the UI
1344
 */
1345
void MainWindow::clearTemplateWidgets() {
×
1346
  while (ui->gridLayout->count() > 0) {
×
1347
    QLayoutItem *item = ui->gridLayout->takeAt(0);
×
1348
    delete item->widget();
×
1349
    delete item;
×
1350
  }
1351
  ui->verticalLayoutPassword->setSpacing(0);
×
1352
}
×
1353

1354
/**
1355
 * @brief Copies the password of the selected file from the tree view to the
1356
 * clipboard.
1357
 * @example
1358
 * MainWindow::copyPasswordFromTreeview();
1359
 *
1360
 * @return void - This function does not return a value.
1361
 */
1362
void MainWindow::copyPasswordFromTreeview() {
×
1363
  QFileInfo fileOrFolder =
1364
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
1365

1366
  if (fileOrFolder.isFile()) {
×
1367
    QString file = getFile(ui->treeView->currentIndex(), true);
×
1368
    // Disconnect any previous connection to avoid accumulation
1369
    disconnect(QtPassSettings::getPass(), &Pass::finishedShow, this,
×
1370
               &MainWindow::passwordFromFileToClipboard);
1371
    connect(QtPassSettings::getPass(), &Pass::finishedShow, this,
×
1372
            &MainWindow::passwordFromFileToClipboard);
×
1373
    QtPassSettings::getPass()->Show(file);
×
1374
  }
1375
}
×
1376

1377
void MainWindow::passwordFromFileToClipboard(const QString &text) {
×
1378
  QStringList tokens = text.split('\n');
×
1379
  m_qtPass->copyTextToClipboard(tokens[0]);
×
1380
}
×
1381

1382
/**
1383
 * @brief MainWindow::addToGridLayout add a field to the template grid
1384
 * @param position
1385
 * @param field
1386
 * @param value
1387
 */
1388
void MainWindow::addToGridLayout(int position, const QString &field,
×
1389
                                 const QString &value) {
1390
  QString trimmedField = field.trimmed();
1391
  QString trimmedValue = value.trimmed();
1392

1393
  const QString buttonStyle =
1394
      "border-style: none; background: transparent; padding: 0; margin: 0; "
1395
      "icon-size: 16px; color: inherit;";
×
1396

1397
  // Combine the Copy button and the line edit in one widget
1398
  auto *frame = new QFrame();
×
1399
  QLayout *ly = new QHBoxLayout();
×
1400
  ly->setContentsMargins(5, 2, 2, 2);
×
1401
  ly->setSpacing(0);
×
1402
  frame->setLayout(ly);
×
1403
  if (QtPassSettings::getClipBoardType() != Enums::CLIPBOARD_NEVER) {
×
1404
    auto *fieldLabel = new QPushButtonWithClipboard(trimmedValue, this);
×
1405
    connect(fieldLabel, &QPushButtonWithClipboard::clicked, m_qtPass,
×
1406
            &QtPass::copyTextToClipboard);
×
1407

1408
    fieldLabel->setStyleSheet(buttonStyle);
×
1409
    frame->layout()->addWidget(fieldLabel);
×
1410
  }
1411

1412
  if (QtPassSettings::isUseQrencode()) {
×
1413
    auto *qrbutton = new QPushButtonAsQRCode(trimmedValue, this);
×
1414
    connect(qrbutton, &QPushButtonAsQRCode::clicked, m_qtPass,
×
1415
            &QtPass::showTextAsQRCode);
×
1416
    qrbutton->setStyleSheet(buttonStyle);
×
1417
    frame->layout()->addWidget(qrbutton);
×
1418
  }
1419

1420
  // set the echo mode to password, if the field is "password"
1421
  const QString lineStyle =
1422
      QtPassSettings::isUseMonospace()
×
1423
          ? "border-style: none; background: transparent; font-family: "
1424
            "monospace;"
1425
          : "border-style: none; background: transparent;";
×
1426

1427
  if (QtPassSettings::isHidePassword() && trimmedField == tr("Password")) {
×
1428
    auto *line = new QLineEdit();
×
1429
    line->setObjectName(trimmedField);
×
1430
    line->setText(trimmedValue);
×
1431
    line->setReadOnly(true);
×
1432
    line->setStyleSheet(lineStyle);
×
1433
    line->setContentsMargins(0, 0, 0, 0);
×
1434
    line->setEchoMode(QLineEdit::Password);
×
1435
    auto *showButton = new QPushButtonShowPassword(line, this);
×
1436
    showButton->setStyleSheet(buttonStyle);
×
1437
    showButton->setContentsMargins(0, 0, 0, 0);
×
1438
    frame->layout()->addWidget(showButton);
×
1439
    frame->layout()->addWidget(line);
×
1440
  } else {
1441
    auto *line = new QTextBrowser();
×
1442
    line->setOpenExternalLinks(true);
×
1443
    line->setOpenLinks(true);
×
1444
    line->setMaximumHeight(26);
×
1445
    line->setMinimumHeight(26);
×
1446
    line->setSizePolicy(
×
1447
        QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum));
1448
    line->setObjectName(trimmedField);
×
1449
    trimmedValue.replace(Util::protocolRegex(), R"(<a href="\1">\1</a>)");
×
1450
    line->setText(trimmedValue);
×
1451
    line->setReadOnly(true);
×
1452
    line->setStyleSheet(lineStyle);
×
1453
    line->setContentsMargins(0, 0, 0, 0);
×
1454
    frame->layout()->addWidget(line);
×
1455
  }
1456

1457
  frame->setStyleSheet(
×
1458
      ".QFrame{border: 1px solid lightgrey; border-radius: 5px;}");
1459

1460
  // set into the layout
1461
  ui->gridLayout->addWidget(new QLabel(trimmedField), position, 0);
×
1462
  ui->gridLayout->addWidget(frame, position, 1);
×
1463
}
×
1464

1465
/**
1466
 * @brief Displays message in status bar
1467
 *
1468
 * @param msg     text to be displayed
1469
 * @param timeout time for which msg shall be visible
1470
 */
1471
void MainWindow::showStatusMessage(const QString &msg, int timeout) {
×
1472
  ui->statusBar->showMessage(msg, timeout);
×
1473
}
×
1474

1475
/**
1476
 * @brief MainWindow::reencryptPath re-encrypt all passwords in a directory
1477
 * @param dir Directory path to re-encrypt
1478
 */
1479
void MainWindow::reencryptPath(const QString &dir) {
×
1480
  QDir checkDir(dir);
×
1481
  if (!checkDir.exists()) {
×
1482
    QMessageBox::critical(this, tr("Error"),
×
1483
                          tr("Directory does not exist: %1").arg(dir));
×
1484
    return;
×
1485
  }
1486

1487
  int ret = QMessageBox::question(
×
1488
      this, tr("Re-encrypt passwords"),
×
1489
      tr("Re-encrypt all passwords in %1?\n\n"
×
1490
         "This will re-encrypt ALL password files in this folder "
1491
         "using the current recipients defined in .gpg-id.\n\n"
1492
         "This may rewrite many files and cannot be undone easily.\n\n"
1493
         "Continue?")
1494
          .arg(QDir(dir).dirName()),
×
1495
      QMessageBox::Yes | QMessageBox::No);
1496

1497
  if (ret != QMessageBox::Yes)
×
1498
    return;
1499

1500
  // Prevent double execution - use same method as startReencryptPath
1501
  setUiElementsEnabled(false);
×
1502
  ui->treeView->setDisabled(true);
×
1503

1504
  QtPassSettings::getImitatePass()->reencryptPath(
×
1505
      QDir::cleanPath(QDir(dir).absolutePath()));
×
1506
}
×
1507

1508
/**
1509
 * @brief MainWindow::startReencryptPath disable ui elements and treeview
1510
 */
1511
void MainWindow::startReencryptPath() {
×
1512
  setUiElementsEnabled(false);
×
1513
  ui->treeView->setDisabled(true);
×
1514
}
×
1515

1516
/**
1517
 * @brief MainWindow::endReencryptPath re-enable ui elements
1518
 */
1519
void MainWindow::endReencryptPath() { setUiElementsEnabled(true); }
×
1520

1521
void MainWindow::updateGitButtonVisibility() {
×
1522
  if (!QtPassSettings::isUseGit() ||
×
1523
      (QtPassSettings::getGitExecutable().isEmpty() &&
×
1524
       QtPassSettings::getPassExecutable().isEmpty())) {
×
1525
    enableGitButtons(false);
×
1526
  } else {
1527
    enableGitButtons(true);
×
1528
  }
1529
}
×
1530

1531
void MainWindow::updateOtpButtonVisibility() {
×
1532
#if defined(Q_OS_WIN) || defined(__APPLE__)
1533
  ui->actionOtp->setVisible(false);
1534
#endif
1535
  if (!QtPassSettings::isUseOtp()) {
×
1536
    ui->actionOtp->setEnabled(false);
×
1537
  } else {
1538
    ui->actionOtp->setEnabled(true);
×
1539
  }
1540
}
×
1541

NEW
1542
void MainWindow::updateGrepButtonVisibility() {
×
NEW
1543
  const bool enabled = QtPassSettings::isUseGrepSearch();
×
NEW
1544
  ui->grepButton->setVisible(enabled);
×
NEW
1545
  ui->grepCaseButton->setVisible(enabled);
×
NEW
1546
  if (!enabled && m_grepMode) {
×
NEW
1547
    ui->grepButton->setChecked(false);
×
1548
  }
NEW
1549
}
×
1550

UNCOV
1551
void MainWindow::enableGitButtons(const bool &state) {
×
1552
  // Following GNOME guidelines is preferable disable buttons instead of hide
1553
  ui->actionPush->setEnabled(state);
×
1554
  ui->actionUpdate->setEnabled(state);
×
1555
}
×
1556

1557
/**
1558
 * @brief MainWindow::critical critical message popup wrapper.
1559
 * @param title
1560
 * @param msg
1561
 */
1562
void MainWindow::critical(const QString &title, const QString &msg) {
×
1563
  QMessageBox::critical(this, title, msg);
×
1564
}
×
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