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

IJHack / QtPass / 24612324254

18 Apr 2026 07:37PM UTC coverage: 22.694% (+0.8%) from 21.908%
24612324254

Pull #1037

github

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

81 of 224 new or added lines in 7 files covered. (36.16%)

401 existing lines in 9 files now uncovered.

1304 of 5746 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
  // Reset filter after index has been consumed to avoid stale proxy index
NEW
398
  if (!m_grepMode && !ui->lineEdit->text().isEmpty()) {
×
NEW
399
    searchTimer.stop();
×
NEW
400
    ui->lineEdit->blockSignals(true);
×
NEW
401
    ui->lineEdit->clear();
×
NEW
402
    ui->lineEdit->blockSignals(false);
×
NEW
403
    proxyModel.setFilterRegularExpression(QRegularExpression());
×
404
  }
UNCOV
405
}
×
406

407
/**
408
 * @brief MainWindow::on_treeView_doubleClicked when doubleclicked on
409
 * TreeViewItem, open the edit Window
410
 * @param index
411
 */
412
void MainWindow::on_treeView_doubleClicked(const QModelIndex &index) {
×
413
  QFileInfo fileOrFolder =
414
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
415

416
  if (fileOrFolder.isFile()) {
×
417
    editPassword(getFile(index, true));
×
418
  }
419
}
×
420

421
/**
422
 * @brief MainWindow::deselect clear the selection, password and copy buffer
423
 */
424
void MainWindow::deselect() {
×
425
  currentDir = "";
×
426
  m_qtPass->clearClipboard();
×
427
  ui->treeView->clearSelection();
×
428
  ui->actionEdit->setEnabled(false);
×
429
  ui->actionDelete->setEnabled(false);
×
430
  ui->passwordName->setText("");
×
431
  clearPanel(false);
×
432
}
×
433

434
void MainWindow::executeWrapperStarted() {
×
435
  clearTemplateWidgets();
×
436
  ui->textBrowser->clear();
×
437
  setUiElementsEnabled(false);
×
438
  clearPanelTimer.stop();
×
439
}
×
440

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

461
  // set clipped text
462
  m_qtPass->setClippedText(password, p_output);
×
463

464
  // first clear the current view:
465
  clearTemplateWidgets();
×
466

467
  // show what is needed:
468
  if (QtPassSettings::isHideContent()) {
×
469
    output = "***" + tr("Content hidden") + "***";
×
470
  } else if (!QtPassSettings::isDisplayAsIs()) {
×
471
    if (!password.isEmpty()) {
×
472
      // set the password, it is hidden if needed in addToGridLayout
473
      addToGridLayout(0, tr("Password"), password);
×
474
    }
475

476
    NamedValues namedValues = fileContent.getNamedValues();
×
477
    for (int j = 0; j < namedValues.length(); ++j) {
×
478
      const NamedValue &nv = namedValues.at(j);
479
      addToGridLayout(j + 1, nv.name, nv.value);
×
480
    }
481
    if (ui->gridLayout->count() == 0) {
×
482
      ui->verticalLayoutPassword->setSpacing(0);
×
483
    } else {
484
      ui->verticalLayoutPassword->setSpacing(6);
×
485
    }
486

487
    output = fileContent.getRemainingDataForDisplay();
×
488
  }
489

490
  if (QtPassSettings::isUseAutoclearPanel()) {
×
491
    clearPanelTimer.start();
×
492
  }
493

494
  emit passShowHandlerFinished(output);
×
495
  setUiElementsEnabled(true);
×
496
}
×
497

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1037
  QtPassSettings::setProfile(name);
×
1038

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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