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

IJHack / QtPass / 24612849137

18 Apr 2026 08:06PM UTC coverage: 22.69% (+0.8%) from 21.908%
24612849137

Pull #1037

github

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

81 of 226 new or added lines in 7 files covered. (35.84%)

400 existing lines in 9 files now uncovered.

1304 of 5747 relevant lines covered (22.69%)

8.55 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->setPlaceholderText(tr("Search Password"));
×
534
    }
535
  }
536
  if (notify) {
×
537
    QString output = "***" + tr("Password and Content hidden") + "***";
×
538
    ui->textBrowser->setHtml(output);
×
539
  } else {
540
    ui->textBrowser->setHtml("");
×
541
  }
542
}
×
543

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

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

587
  if (QtPassSettings::isAlwaysOnTop()) {
×
588
    Qt::WindowFlags flags = windowFlags();
589
    setWindowFlags(flags | Qt::WindowStaysOnTopHint);
×
590
    show();
×
591
  }
592

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

604
/**
605
 * @brief MainWindow::on_configButton_clicked run Mainwindow::config
606
 */
607
void MainWindow::onConfig() { config(); }
×
608

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

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

633
  if (query.isEmpty()) {
×
634
    ui->treeView->collapseAll();
×
635
    deselect();
×
636
  }
637

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

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

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

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

680
  if (proxyModel.rowCount() > 0) {
×
681
    selectFirstFile();
×
682
    on_treeView_clicked(ui->treeView->currentIndex());
×
683
  }
684
}
685

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

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

759
/**
760
 * @brief Navigate to the password entry when a grep result is clicked.
761
 */
NEW
762
void MainWindow::on_grepResultsList_itemClicked(QTreeWidgetItem *item,
×
763
                                                int /*column*/) {
NEW
764
  const QString entry = item->data(0, Qt::UserRole).toString();
×
NEW
765
  if (entry.isEmpty())
×
766
    return;
767
  const QString fullPath = QDir::cleanPath(
NEW
768
      QDir(QtPassSettings::getPassStore()).filePath(entry + ".gpg"));
×
NEW
769
  QModelIndex srcIndex = model.index(fullPath);
×
770
  if (!srcIndex.isValid())
771
    return;
NEW
772
  QModelIndex proxyIndex = proxyModel.mapFromSource(srcIndex);
×
773
  if (!proxyIndex.isValid())
774
    return;
NEW
775
  ui->treeView->setCurrentIndex(proxyIndex);
×
NEW
776
  on_treeView_clicked(proxyIndex);
×
NEW
777
  if (QtPassSettings::isHideContent() || QtPassSettings::isUseAutoclearPanel())
×
NEW
778
    ui->grepResultsList->clear();
×
NEW
779
  ui->grepResultsList->setVisible(false);
×
NEW
780
  ui->treeView->setVisible(true);
×
NEW
781
  ui->treeView->scrollTo(proxyIndex);
×
NEW
782
  ui->treeView->setFocus();
×
783
}
784

785
/**
786
 * @brief MainWindow::selectFirstFile select the first possible file in the
787
 * tree
788
 */
789
void MainWindow::selectFirstFile() {
×
790
  QModelIndex index = proxyModel.mapFromSource(
×
791
      model.setRootPath(QtPassSettings::getPassStore()));
×
792
  index = firstFile(index);
×
793
  ui->treeView->setCurrentIndex(index);
×
794
}
×
795

796
/**
797
 * @brief MainWindow::firstFile return location of first possible file
798
 * @param parentIndex
799
 * @return QModelIndex
800
 */
801
auto MainWindow::firstFile(QModelIndex parentIndex) -> QModelIndex {
×
802
  QModelIndex index = parentIndex;
×
803
  int numRows = proxyModel.rowCount(parentIndex);
×
804
  for (int row = 0; row < numRows; ++row) {
×
805
    index = proxyModel.index(row, 0, parentIndex);
×
806
    if (model.fileInfo(proxyModel.mapToSource(index)).isFile()) {
×
807
      return index;
×
808
    }
809
    if (proxyModel.hasChildren(index)) {
×
810
      return firstFile(index);
×
811
    }
812
  }
813
  return index;
×
814
}
815

816
/**
817
 * @brief MainWindow::setPassword open passworddialog
818
 * @param file which pgp file
819
 * @param isNew insert (not update)
820
 */
821
void MainWindow::setPassword(const QString &file, bool isNew) {
×
822
  PasswordDialog d(file, isNew, this);
×
823

824
  if (!d.exec()) {
×
825
    ui->treeView->setFocus();
×
826
  }
827
}
×
828

829
/**
830
 * @brief MainWindow::addPassword add a new password by showing a
831
 * number of dialogs.
832
 */
833
void MainWindow::addPassword() {
×
834
  bool ok;
835
  QString dir =
836
      Util::getDir(ui->treeView->currentIndex(), true, model, proxyModel);
×
837
  QString file =
838
      QInputDialog::getText(this, tr("New file"),
×
839
                            tr("New password file: \n(Will be placed in %1 )")
×
840
                                .arg(QtPassSettings::getPassStore() +
×
841
                                     Util::getDir(ui->treeView->currentIndex(),
×
842
                                                  true, model, proxyModel)),
843
                            QLineEdit::Normal, "", &ok);
×
844
  if (!ok || file.isEmpty()) {
×
845
    return;
846
  }
847
  file = dir + file;
×
848
  setPassword(file);
×
849
}
850

851
/**
852
 * @brief MainWindow::onDelete remove password, if you are
853
 * sure.
854
 */
855
void MainWindow::onDelete() {
×
856
  QModelIndex currentIndex = ui->treeView->currentIndex();
×
857
  if (!currentIndex.isValid()) {
858
    // This fixes https://github.com/IJHack/QtPass/issues/556
859
    // Otherwise the entire password directory would be deleted if
860
    // nothing is selected in the tree view.
861
    return;
×
862
  }
863

864
  QFileInfo fileOrFolder =
865
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
866
  QString file = "";
×
867
  bool isDir = false;
868

869
  if (fileOrFolder.isFile()) {
×
870
    file = getFile(ui->treeView->currentIndex(), true);
×
871
  } else {
872
    file = Util::getDir(ui->treeView->currentIndex(), true, model, proxyModel);
×
873
    isDir = true;
874
  }
875

876
  QString dirMessage = tr(" and the whole content?");
877
  if (isDir) {
×
878
    QDirIterator it(model.rootPath() + QDir::separator() + file,
×
879
                    QDirIterator::Subdirectories);
×
880
    bool okDir = true;
881
    while (it.hasNext() && okDir) {
×
882
      it.next();
×
883
      if (QFileInfo(it.filePath()).isFile()) {
×
884
        if (QFileInfo(it.filePath()).suffix() != "gpg") {
×
885
          okDir = false;
886
          dirMessage = tr(" and the whole content? <br><strong>Attention: "
×
887
                          "there are unexpected files in the given folder, "
888
                          "check them before continue.</strong>");
889
        }
890
      }
891
    }
892
  }
×
893

894
  if (QMessageBox::question(
×
895
          this, isDir ? tr("Delete folder?") : tr("Delete password?"),
×
896
          tr("Are you sure you want to delete %1%2?")
×
897
              .arg(QDir::separator() + file, isDir ? dirMessage : "?"),
×
898
          QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) {
899
    return;
900
  }
901

902
  QtPassSettings::getPass()->Remove(file, isDir);
×
903
}
×
904

905
/**
906
 * @brief MainWindow::onOTP try and generate (selected) OTP code.
907
 */
908
void MainWindow::onOtp() {
×
909
  QString file = getFile(ui->treeView->currentIndex(), true);
×
910
  if (!file.isEmpty()) {
×
911
    if (QtPassSettings::isUseOtp()) {
×
912
      setUiElementsEnabled(false);
×
913
      QtPassSettings::getPass()->OtpGenerate(file);
×
914
    }
915
  } else {
916
    flashText(tr("No password selected for OTP generation"), true);
×
917
  }
918
}
×
919

920
/**
921
 * @brief MainWindow::onEdit try and edit (selected) password.
922
 */
923
void MainWindow::onEdit() {
×
924
  QString file = getFile(ui->treeView->currentIndex(), true);
×
925
  editPassword(file);
×
926
}
×
927

928
/**
929
 * @brief MainWindow::userDialog see MainWindow::onUsers()
930
 * @param dir folder to edit users for.
931
 */
932
void MainWindow::userDialog(const QString &dir) {
×
933
  if (!dir.isEmpty()) {
×
934
    currentDir = dir;
×
935
  }
936
  onUsers();
×
937
}
×
938

939
/**
940
 * @brief MainWindow::onUsers edit users for the current
941
 * folder,
942
 * gets lists and opens UserDialog.
943
 */
944
void MainWindow::onUsers() {
×
945
  QString dir =
946
      currentDir.isEmpty()
947
          ? Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel)
×
948
          : currentDir;
×
949

950
  UsersDialog d(dir, this);
×
951
  if (!d.exec()) {
×
952
    ui->treeView->setFocus();
×
953
  }
954
}
×
955

956
/**
957
 * @brief MainWindow::messageAvailable we have some text/message/search to do.
958
 * @param message
959
 */
960
void MainWindow::messageAvailable(const QString &message) {
×
961
  if (message.isEmpty()) {
×
962
    focusInput();
×
963
  } else {
964
    ui->treeView->expandAll();
×
965
    ui->lineEdit->setText(message);
×
966
    on_lineEdit_returnPressed();
×
967
  }
968
  show();
×
969
  raise();
×
970
}
×
971

972
/**
973
 * @brief MainWindow::generateKeyPair internal gpg keypair generator . .
974
 * @param batch
975
 * @param keygenWindow
976
 */
977
void MainWindow::generateKeyPair(const QString &batch, QDialog *keygenWindow) {
×
978
  keygen = keygenWindow;
×
979
  emit generateGPGKeyPair(batch);
×
980
}
×
981

982
/**
983
 * @brief MainWindow::updateProfileBox update the list of profiles, optionally
984
 * select a more appropriate one to view too
985
 */
986
void MainWindow::updateProfileBox() {
×
987
  QHash<QString, QHash<QString, QString>> profiles =
988
      QtPassSettings::getProfiles();
×
989

990
  if (profiles.isEmpty()) {
991
    ui->profileWidget->hide();
×
992
  } else {
993
    ui->profileWidget->show();
×
994
    ui->profileBox->setEnabled(profiles.size() > 1);
×
995
    ui->profileBox->clear();
×
996
    QHashIterator<QString, QHash<QString, QString>> i(profiles);
×
997
    while (i.hasNext()) {
×
998
      i.next();
999
      if (!i.key().isEmpty()) {
×
1000
        ui->profileBox->addItem(i.key());
×
1001
      }
1002
    }
1003
    ui->profileBox->model()->sort(0);
×
1004
  }
1005
  int index = ui->profileBox->findText(QtPassSettings::getProfile());
×
1006
  if (index != -1) { //  -1 for not found
×
1007
    ui->profileBox->setCurrentIndex(index);
×
1008
  }
1009
}
×
1010

1011
/**
1012
 * @brief MainWindow::on_profileBox_currentIndexChanged make sure we show the
1013
 * correct "profile"
1014
 * @param name
1015
 */
1016
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
1017
void MainWindow::on_profileBox_currentIndexChanged(QString name) {
1018
#else
1019
/**
1020
 * @brief Handles changes to the selected profile in the profile combo box.
1021
 * @details Ignores the event during a fresh start or when the selected profile
1022
 * matches the current profile. Otherwise, it clears the password field, updates
1023
 * the active profile and related settings, refreshes the environment, and
1024
 * resets the tree view and action states to reflect the newly selected profile.
1025
 *
1026
 * @param name - The newly selected profile name.
1027
 * @return void - This function does not return a value.
1028
 *
1029
 */
1030
void MainWindow::on_profileBox_currentTextChanged(const QString &name) {
×
1031
#endif
1032
  if (m_qtPass->isFreshStart() || name == QtPassSettings::getProfile()) {
×
1033
    return;
×
1034
  }
1035

1036
  ui->lineEdit->clear();
×
1037

1038
  QtPassSettings::setProfile(name);
×
1039

1040
  QtPassSettings::setPassStore(
×
1041
      QtPassSettings::getProfiles().value(name).value("path"));
×
1042
  QtPassSettings::setPassSigningKey(
×
1043
      QtPassSettings::getProfiles().value(name).value("signingKey"));
×
1044
  ui->statusBar->showMessage(tr("Profile changed to %1").arg(name), 2000);
×
1045

1046
  QtPassSettings::getPass()->updateEnv();
×
1047

1048
  const QString passStore = QtPassSettings::getPassStore();
×
1049
  proxyModel.setStore(passStore);
×
1050
  ui->treeView->setRootIndex(
×
1051
      proxyModel.mapFromSource(model.setRootPath(passStore)));
×
1052
  deselect();
×
1053
  ui->treeView->setCurrentIndex(QModelIndex());
×
1054
}
1055

1056
/**
1057
 * @brief MainWindow::initTrayIcon show a nice tray icon on systems that
1058
 * support
1059
 * it
1060
 */
1061
void MainWindow::initTrayIcon() {
×
1062
  this->tray = new TrayIcon(this);
×
1063
  // Setup tray icon
1064

1065
  if (tray == nullptr) {
1066
#ifdef QT_DEBUG
1067
    dbg() << "Allocating tray icon failed.";
1068
#endif
1069
  }
1070

1071
  if (!tray->getIsAllocated()) {
×
1072
    destroyTrayIcon();
×
1073
  }
1074
}
×
1075

1076
/**
1077
 * @brief MainWindow::destroyTrayIcon remove that pesky tray icon
1078
 */
1079
void MainWindow::destroyTrayIcon() {
×
1080
  delete this->tray;
×
1081
  tray = nullptr;
×
1082
}
×
1083

1084
/**
1085
 * @brief MainWindow::closeEvent hide or quit
1086
 * @param event
1087
 */
1088
void MainWindow::closeEvent(QCloseEvent *event) {
×
1089
  if (QtPassSettings::isHideOnClose()) {
×
1090
    this->hide();
×
1091
    event->ignore();
1092
  } else {
1093
    m_qtPass->clearClipboard();
×
1094

1095
    QtPassSettings::setGeometry(saveGeometry());
×
1096
    QtPassSettings::setSavestate(saveState());
×
1097
    QtPassSettings::setMaximized(isMaximized());
×
1098
    if (!isMaximized()) {
×
1099
      QtPassSettings::setPos(pos());
×
1100
      QtPassSettings::setSize(size());
×
1101
    }
1102
    event->accept();
1103
  }
1104
}
×
1105

1106
/**
1107
 * @brief MainWindow::eventFilter filter out some events and focus the
1108
 * treeview
1109
 * @param obj
1110
 * @param event
1111
 * @return
1112
 */
1113
auto MainWindow::eventFilter(QObject *obj, QEvent *event) -> bool {
×
1114
  if (obj == ui->lineEdit && event->type() == QEvent::KeyPress) {
×
1115
    auto *key = dynamic_cast<QKeyEvent *>(event);
×
1116
    if (key != nullptr && key->key() == Qt::Key_Down) {
×
1117
      ui->treeView->setFocus();
×
1118
    }
1119
  }
1120
  return QObject::eventFilter(obj, event);
×
1121
}
1122

1123
/**
1124
 * @brief MainWindow::keyPressEvent did anyone press return, enter or escape?
1125
 * @param event
1126
 */
1127
void MainWindow::keyPressEvent(QKeyEvent *event) {
×
1128
  switch (event->key()) {
×
1129
  case Qt::Key_Delete:
×
1130
    onDelete();
×
1131
    break;
×
1132
  case Qt::Key_Return:
×
1133
  case Qt::Key_Enter:
1134
    if (proxyModel.rowCount() > 0) {
×
1135
      on_treeView_clicked(ui->treeView->currentIndex());
×
1136
    }
1137
    break;
1138
  case Qt::Key_Escape:
×
1139
    ui->lineEdit->clear();
×
1140
    break;
×
1141
  default:
1142
    break;
1143
  }
1144
}
×
1145

1146
/**
1147
 * @brief MainWindow::showContextMenu show us the (file or folder) context
1148
 * menu
1149
 * @param pos
1150
 */
1151
void MainWindow::showContextMenu(const QPoint &pos) {
×
1152
  QModelIndex index = ui->treeView->indexAt(pos);
×
1153
  bool selected = true;
1154
  if (!index.isValid()) {
1155
    ui->treeView->clearSelection();
×
1156
    ui->actionDelete->setEnabled(false);
×
1157
    ui->actionEdit->setEnabled(false);
×
1158
    currentDir = "";
×
1159
    selected = false;
1160
  }
1161

1162
  ui->treeView->setCurrentIndex(index);
×
1163

1164
  QPoint globalPos = ui->treeView->viewport()->mapToGlobal(pos);
×
1165

1166
  QFileInfo fileOrFolder =
1167
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
1168

1169
  QMenu contextMenu;
×
1170
  if (!selected || fileOrFolder.isDir()) {
×
1171
    QAction *openFolder =
1172
        contextMenu.addAction(tr("Open folder with file manager"));
×
1173
    QAction *addFolder = contextMenu.addAction(tr("Add folder"));
×
1174
    QAction *addPassword = contextMenu.addAction(tr("Add password"));
×
1175
    QAction *users = contextMenu.addAction(tr("Users"));
×
1176
    connect(openFolder, &QAction::triggered, this, &MainWindow::openFolder);
×
1177
    connect(addFolder, &QAction::triggered, this, &MainWindow::addFolder);
×
1178
    connect(addPassword, &QAction::triggered, this, &MainWindow::addPassword);
×
1179
    connect(users, &QAction::triggered, this, &MainWindow::onUsers);
×
1180
  } else if (fileOrFolder.isFile()) {
×
1181
    QAction *edit = contextMenu.addAction(tr("Edit"));
×
1182
    connect(edit, &QAction::triggered, this, &MainWindow::onEdit);
×
1183
  }
1184
  if (selected) {
×
1185
    contextMenu.addSeparator();
×
1186
    if (fileOrFolder.isDir()) {
×
1187
      QAction *renameFolder = contextMenu.addAction(tr("Rename folder"));
×
1188
      connect(renameFolder, &QAction::triggered, this,
×
1189
              &MainWindow::renameFolder);
×
1190
    } else if (fileOrFolder.isFile()) {
×
1191
      QAction *renamePassword = contextMenu.addAction(tr("Rename password"));
×
1192
      connect(renamePassword, &QAction::triggered, this,
×
1193
              &MainWindow::renamePassword);
×
1194
    }
1195
    QAction *deleteItem = contextMenu.addAction(tr("Delete"));
×
1196
    connect(deleteItem, &QAction::triggered, this, &MainWindow::onDelete);
×
1197
    if (fileOrFolder.isDir()) {
×
1198
      QString dirPath = QDir::cleanPath(
1199
          Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel));
×
1200
      QAction *reencrypt = contextMenu.addAction(tr("Re-encrypt"));
×
1201
      connect(reencrypt, &QAction::triggered, this,
×
1202
              [this, dirPath]() { reencryptPath(dirPath); });
×
1203
    }
1204
  }
1205
  contextMenu.exec(globalPos);
×
1206
}
×
1207

1208
/**
1209
 * @brief MainWindow::showBrowserContextMenu show us the context menu in
1210
 * password window
1211
 * @param pos
1212
 */
1213
void MainWindow::showBrowserContextMenu(const QPoint &pos) {
×
1214
  QMenu *contextMenu = ui->textBrowser->createStandardContextMenu(pos);
×
1215
  QPoint globalPos = ui->textBrowser->viewport()->mapToGlobal(pos);
×
1216

1217
  contextMenu->exec(globalPos);
×
1218
  delete contextMenu;
×
1219
}
×
1220

1221
/**
1222
 * @brief MainWindow::openFolder open the folder in the default file manager
1223
 */
1224
void MainWindow::openFolder() {
×
1225
  QString dir =
1226
      Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel);
×
1227

1228
  QString path = QDir::toNativeSeparators(dir);
×
1229
  QDesktopServices::openUrl(QUrl::fromLocalFile(path));
×
1230
}
×
1231

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

1274
/**
1275
 * @brief MainWindow::renameFolder rename an existing folder
1276
 */
1277
void MainWindow::renameFolder() {
×
1278
  bool ok;
1279
  QString srcDir = QDir::cleanPath(
1280
      Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel));
×
1281
  QString srcDirName = QDir(srcDir).dirName();
×
1282
  QString newName =
1283
      QInputDialog::getText(this, tr("Rename file"), tr("Rename Folder To: "),
×
1284
                            QLineEdit::Normal, srcDirName, &ok);
×
1285
  if (!ok || newName.isEmpty()) {
×
1286
    return;
1287
  }
1288
  QString destDir = srcDir;
1289
  destDir.replace(srcDir.lastIndexOf(srcDirName), srcDirName.length(), newName);
×
1290
  QtPassSettings::getPass()->Move(srcDir, destDir);
×
1291
}
1292

1293
/**
1294
 * @brief MainWindow::editPassword read password and open edit window via
1295
 * MainWindow::onEdit()
1296
 */
1297
void MainWindow::editPassword(const QString &file) {
×
1298
  if (!file.isEmpty()) {
×
1299
    if (QtPassSettings::isUseGit() && QtPassSettings::isAutoPull()) {
×
1300
      onUpdate(true);
×
1301
    }
1302
    setPassword(file, false);
×
1303
  }
1304
}
×
1305

1306
/**
1307
 * @brief MainWindow::renamePassword rename an existing password
1308
 */
1309
void MainWindow::renamePassword() {
×
1310
  bool ok;
1311
  QString file = getFile(ui->treeView->currentIndex(), false);
×
1312
  QString filePath = QFileInfo(file).path();
×
1313
  QString fileName = QFileInfo(file).fileName();
×
1314
  if (fileName.endsWith(".gpg", Qt::CaseInsensitive)) {
×
1315
    fileName.chop(4);
×
1316
  }
1317

1318
  QString newName =
1319
      QInputDialog::getText(this, tr("Rename file"), tr("Rename File To: "),
×
1320
                            QLineEdit::Normal, fileName, &ok);
×
1321
  if (!ok || newName.isEmpty()) {
×
1322
    return;
1323
  }
1324
  QString newFile = QDir(filePath).filePath(newName);
×
1325
  QtPassSettings::getPass()->Move(file, newFile);
×
1326
}
1327

1328
/**
1329
 * @brief MainWindow::clearTemplateWidgets empty the template widget fields in
1330
 * the UI
1331
 */
1332
void MainWindow::clearTemplateWidgets() {
×
1333
  while (ui->gridLayout->count() > 0) {
×
1334
    QLayoutItem *item = ui->gridLayout->takeAt(0);
×
1335
    delete item->widget();
×
1336
    delete item;
×
1337
  }
1338
  ui->verticalLayoutPassword->setSpacing(0);
×
1339
}
×
1340

1341
/**
1342
 * @brief Copies the password of the selected file from the tree view to the
1343
 * clipboard.
1344
 * @example
1345
 * MainWindow::copyPasswordFromTreeview();
1346
 *
1347
 * @return void - This function does not return a value.
1348
 */
1349
void MainWindow::copyPasswordFromTreeview() {
×
1350
  QFileInfo fileOrFolder =
1351
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
1352

1353
  if (fileOrFolder.isFile()) {
×
1354
    QString file = getFile(ui->treeView->currentIndex(), true);
×
1355
    // Disconnect any previous connection to avoid accumulation
1356
    disconnect(QtPassSettings::getPass(), &Pass::finishedShow, this,
×
1357
               &MainWindow::passwordFromFileToClipboard);
1358
    connect(QtPassSettings::getPass(), &Pass::finishedShow, this,
×
1359
            &MainWindow::passwordFromFileToClipboard);
×
1360
    QtPassSettings::getPass()->Show(file);
×
1361
  }
1362
}
×
1363

1364
void MainWindow::passwordFromFileToClipboard(const QString &text) {
×
1365
  QStringList tokens = text.split('\n');
×
1366
  m_qtPass->copyTextToClipboard(tokens[0]);
×
1367
}
×
1368

1369
/**
1370
 * @brief MainWindow::addToGridLayout add a field to the template grid
1371
 * @param position
1372
 * @param field
1373
 * @param value
1374
 */
1375
void MainWindow::addToGridLayout(int position, const QString &field,
×
1376
                                 const QString &value) {
1377
  QString trimmedField = field.trimmed();
1378
  QString trimmedValue = value.trimmed();
1379

1380
  const QString buttonStyle =
1381
      "border-style: none; background: transparent; padding: 0; margin: 0; "
1382
      "icon-size: 16px; color: inherit;";
×
1383

1384
  // Combine the Copy button and the line edit in one widget
1385
  auto *frame = new QFrame();
×
1386
  QLayout *ly = new QHBoxLayout();
×
1387
  ly->setContentsMargins(5, 2, 2, 2);
×
1388
  ly->setSpacing(0);
×
1389
  frame->setLayout(ly);
×
1390
  if (QtPassSettings::getClipBoardType() != Enums::CLIPBOARD_NEVER) {
×
1391
    auto *fieldLabel = new QPushButtonWithClipboard(trimmedValue, this);
×
1392
    connect(fieldLabel, &QPushButtonWithClipboard::clicked, m_qtPass,
×
1393
            &QtPass::copyTextToClipboard);
×
1394

1395
    fieldLabel->setStyleSheet(buttonStyle);
×
1396
    frame->layout()->addWidget(fieldLabel);
×
1397
  }
1398

1399
  if (QtPassSettings::isUseQrencode()) {
×
1400
    auto *qrbutton = new QPushButtonAsQRCode(trimmedValue, this);
×
1401
    connect(qrbutton, &QPushButtonAsQRCode::clicked, m_qtPass,
×
1402
            &QtPass::showTextAsQRCode);
×
1403
    qrbutton->setStyleSheet(buttonStyle);
×
1404
    frame->layout()->addWidget(qrbutton);
×
1405
  }
1406

1407
  // set the echo mode to password, if the field is "password"
1408
  const QString lineStyle =
1409
      QtPassSettings::isUseMonospace()
×
1410
          ? "border-style: none; background: transparent; font-family: "
1411
            "monospace;"
1412
          : "border-style: none; background: transparent;";
×
1413

1414
  if (QtPassSettings::isHidePassword() && trimmedField == tr("Password")) {
×
1415
    auto *line = new QLineEdit();
×
1416
    line->setObjectName(trimmedField);
×
1417
    line->setText(trimmedValue);
×
1418
    line->setReadOnly(true);
×
1419
    line->setStyleSheet(lineStyle);
×
1420
    line->setContentsMargins(0, 0, 0, 0);
×
1421
    line->setEchoMode(QLineEdit::Password);
×
1422
    auto *showButton = new QPushButtonShowPassword(line, this);
×
1423
    showButton->setStyleSheet(buttonStyle);
×
1424
    showButton->setContentsMargins(0, 0, 0, 0);
×
1425
    frame->layout()->addWidget(showButton);
×
1426
    frame->layout()->addWidget(line);
×
1427
  } else {
1428
    auto *line = new QTextBrowser();
×
1429
    line->setOpenExternalLinks(true);
×
1430
    line->setOpenLinks(true);
×
1431
    line->setMaximumHeight(26);
×
1432
    line->setMinimumHeight(26);
×
1433
    line->setSizePolicy(
×
1434
        QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum));
1435
    line->setObjectName(trimmedField);
×
1436
    trimmedValue.replace(Util::protocolRegex(), R"(<a href="\1">\1</a>)");
×
1437
    line->setText(trimmedValue);
×
1438
    line->setReadOnly(true);
×
1439
    line->setStyleSheet(lineStyle);
×
1440
    line->setContentsMargins(0, 0, 0, 0);
×
1441
    frame->layout()->addWidget(line);
×
1442
  }
1443

1444
  frame->setStyleSheet(
×
1445
      ".QFrame{border: 1px solid lightgrey; border-radius: 5px;}");
1446

1447
  // set into the layout
1448
  ui->gridLayout->addWidget(new QLabel(trimmedField), position, 0);
×
1449
  ui->gridLayout->addWidget(frame, position, 1);
×
1450
}
×
1451

1452
/**
1453
 * @brief Displays message in status bar
1454
 *
1455
 * @param msg     text to be displayed
1456
 * @param timeout time for which msg shall be visible
1457
 */
1458
void MainWindow::showStatusMessage(const QString &msg, int timeout) {
×
1459
  ui->statusBar->showMessage(msg, timeout);
×
1460
}
×
1461

1462
/**
1463
 * @brief MainWindow::reencryptPath re-encrypt all passwords in a directory
1464
 * @param dir Directory path to re-encrypt
1465
 */
1466
void MainWindow::reencryptPath(const QString &dir) {
×
1467
  QDir checkDir(dir);
×
1468
  if (!checkDir.exists()) {
×
1469
    QMessageBox::critical(this, tr("Error"),
×
1470
                          tr("Directory does not exist: %1").arg(dir));
×
1471
    return;
×
1472
  }
1473

1474
  int ret = QMessageBox::question(
×
1475
      this, tr("Re-encrypt passwords"),
×
1476
      tr("Re-encrypt all passwords in %1?\n\n"
×
1477
         "This will re-encrypt ALL password files in this folder "
1478
         "using the current recipients defined in .gpg-id.\n\n"
1479
         "This may rewrite many files and cannot be undone easily.\n\n"
1480
         "Continue?")
1481
          .arg(QDir(dir).dirName()),
×
1482
      QMessageBox::Yes | QMessageBox::No);
1483

1484
  if (ret != QMessageBox::Yes)
×
1485
    return;
1486

1487
  // Prevent double execution - use same method as startReencryptPath
1488
  setUiElementsEnabled(false);
×
1489
  ui->treeView->setDisabled(true);
×
1490

1491
  QtPassSettings::getImitatePass()->reencryptPath(
×
1492
      QDir::cleanPath(QDir(dir).absolutePath()));
×
1493
}
×
1494

1495
/**
1496
 * @brief MainWindow::startReencryptPath disable ui elements and treeview
1497
 */
1498
void MainWindow::startReencryptPath() {
×
1499
  setUiElementsEnabled(false);
×
1500
  ui->treeView->setDisabled(true);
×
1501
}
×
1502

1503
/**
1504
 * @brief MainWindow::endReencryptPath re-enable ui elements
1505
 */
1506
void MainWindow::endReencryptPath() { setUiElementsEnabled(true); }
×
1507

1508
void MainWindow::updateGitButtonVisibility() {
×
1509
  if (!QtPassSettings::isUseGit() ||
×
1510
      (QtPassSettings::getGitExecutable().isEmpty() &&
×
1511
       QtPassSettings::getPassExecutable().isEmpty())) {
×
1512
    enableGitButtons(false);
×
1513
  } else {
1514
    enableGitButtons(true);
×
1515
  }
1516
}
×
1517

1518
void MainWindow::updateOtpButtonVisibility() {
×
1519
#if defined(Q_OS_WIN) || defined(__APPLE__)
1520
  ui->actionOtp->setVisible(false);
1521
#endif
1522
  if (!QtPassSettings::isUseOtp()) {
×
1523
    ui->actionOtp->setEnabled(false);
×
1524
  } else {
1525
    ui->actionOtp->setEnabled(true);
×
1526
  }
1527
}
×
1528

NEW
1529
void MainWindow::updateGrepButtonVisibility() {
×
NEW
1530
  const bool enabled = QtPassSettings::isUseGrepSearch();
×
NEW
1531
  ui->grepButton->setVisible(enabled);
×
NEW
1532
  ui->grepCaseButton->setVisible(enabled);
×
NEW
1533
  if (!enabled && m_grepMode) {
×
NEW
1534
    ui->grepButton->setChecked(false);
×
1535
  }
NEW
1536
}
×
1537

UNCOV
1538
void MainWindow::enableGitButtons(const bool &state) {
×
1539
  // Following GNOME guidelines is preferable disable buttons instead of hide
1540
  ui->actionPush->setEnabled(state);
×
1541
  ui->actionUpdate->setEnabled(state);
×
1542
}
×
1543

1544
/**
1545
 * @brief MainWindow::critical critical message popup wrapper.
1546
 * @param title
1547
 * @param msg
1548
 */
1549
void MainWindow::critical(const QString &title, const QString &msg) {
×
1550
  QMessageBox::critical(this, title, msg);
×
1551
}
×
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