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

IJHack / QtPass / 24611749315

18 Apr 2026 07:04PM UTC coverage: 22.726% (+0.8%) from 21.908%
24611749315

Pull #1037

github

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

81 of 217 new or added lines in 7 files covered. (37.33%)

401 existing lines in 9 files now uncovered.

1304 of 5738 relevant lines covered (22.73%)

8.57 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 <QCloseEvent>
22
#include <QDesktopServices>
23
#include <QDialog>
24
#include <QDirIterator>
25
#include <QFileInfo>
26
#include <QInputDialog>
27
#include <QLabel>
28
#include <QMenu>
29
#include <QMessageBox>
30
#include <QShortcut>
31
#include <QTimer>
32
#include <QTreeWidget>
33
#include <utility>
34

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

51
  m_qtPass = new QtPass(this);
×
52

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

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

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

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

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

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

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

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

106
  updateProfileBox();
×
107

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

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

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

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

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

125
  setUiElementsEnabled(true);
×
126

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

377
/**
378
 * @brief MainWindow::on_treeView_clicked read the selected password file
379
 * @param index
380
 */
381
void MainWindow::on_treeView_clicked(const QModelIndex &index) {
×
382
  bool cleared = ui->treeView->currentIndex().flags() == Qt::NoItemFlags;
×
383
  currentDir =
384
      Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel);
×
385
  // Clear any previously cached clipped text before showing new password
386
  m_qtPass->clearClippedText();
×
387
  QString file = getFile(index, true);
×
NEW
388
  ui->passwordName->setText(file);
×
389
  if (!file.isEmpty() && !cleared) {
×
390
    QtPassSettings::getPass()->Show(file);
×
391
  } else {
392
    clearPanel(false);
×
393
    ui->actionEdit->setEnabled(false);
×
394
    ui->actionDelete->setEnabled(true);
×
395
  }
396
  // Reset filter after index has been consumed to avoid stale proxy index
NEW
397
  if (!m_grepMode && !ui->lineEdit->text().isEmpty()) {
×
NEW
398
    searchTimer.stop();
×
NEW
399
    ui->lineEdit->blockSignals(true);
×
NEW
400
    ui->lineEdit->clear();
×
NEW
401
    ui->lineEdit->blockSignals(false);
×
NEW
402
    proxyModel.setFilterRegularExpression(QRegularExpression());
×
403
  }
UNCOV
404
}
×
405

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

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

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

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

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

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

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

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

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

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

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

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

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

521
/**
522
 * @brief MainWindow::clearPanel hide the information from shoulder surfers
523
 */
524
void MainWindow::clearPanel(bool notify) {
×
525
  while (ui->gridLayout->count() > 0) {
×
526
    QLayoutItem *item = ui->gridLayout->takeAt(0);
×
527
    delete item->widget();
×
528
    delete item;
×
529
  }
NEW
530
  const bool grepWasVisible = ui->grepResultsList->isVisible();
×
NEW
531
  ui->grepResultsList->clear();
×
NEW
532
  if (grepWasVisible) {
×
NEW
533
    ui->grepResultsList->setVisible(false);
×
NEW
534
    ui->treeView->setVisible(true);
×
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
      QtPassSettings::getPass()->Grep(query, ui->grepCaseButton->isChecked());
×
667
    } else {
NEW
668
      ui->grepResultsList->clear();
×
NEW
669
      ui->grepResultsList->setVisible(false);
×
NEW
670
      ui->treeView->setVisible(true);
×
671
    }
672
    return;
673
  }
674

675
  if (proxyModel.rowCount() > 0) {
×
676
    selectFirstFile();
×
677
    on_treeView_clicked(ui->treeView->currentIndex());
×
678
  }
679
}
680

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

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

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

774
/**
775
 * @brief MainWindow::selectFirstFile select the first possible file in the
776
 * tree
777
 */
778
void MainWindow::selectFirstFile() {
×
779
  QModelIndex index = proxyModel.mapFromSource(
×
780
      model.setRootPath(QtPassSettings::getPassStore()));
×
781
  index = firstFile(index);
×
782
  ui->treeView->setCurrentIndex(index);
×
783
}
×
784

785
/**
786
 * @brief MainWindow::firstFile return location of first possible file
787
 * @param parentIndex
788
 * @return QModelIndex
789
 */
790
auto MainWindow::firstFile(QModelIndex parentIndex) -> QModelIndex {
×
791
  QModelIndex index = parentIndex;
×
792
  int numRows = proxyModel.rowCount(parentIndex);
×
793
  for (int row = 0; row < numRows; ++row) {
×
794
    index = proxyModel.index(row, 0, parentIndex);
×
795
    if (model.fileInfo(proxyModel.mapToSource(index)).isFile()) {
×
796
      return index;
×
797
    }
798
    if (proxyModel.hasChildren(index)) {
×
799
      return firstFile(index);
×
800
    }
801
  }
802
  return index;
×
803
}
804

805
/**
806
 * @brief MainWindow::setPassword open passworddialog
807
 * @param file which pgp file
808
 * @param isNew insert (not update)
809
 */
810
void MainWindow::setPassword(const QString &file, bool isNew) {
×
811
  PasswordDialog d(file, isNew, this);
×
812

813
  if (!d.exec()) {
×
814
    ui->treeView->setFocus();
×
815
  }
816
}
×
817

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

840
/**
841
 * @brief MainWindow::onDelete remove password, if you are
842
 * sure.
843
 */
844
void MainWindow::onDelete() {
×
845
  QModelIndex currentIndex = ui->treeView->currentIndex();
×
846
  if (!currentIndex.isValid()) {
847
    // This fixes https://github.com/IJHack/QtPass/issues/556
848
    // Otherwise the entire password directory would be deleted if
849
    // nothing is selected in the tree view.
850
    return;
×
851
  }
852

853
  QFileInfo fileOrFolder =
854
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
855
  QString file = "";
×
856
  bool isDir = false;
857

858
  if (fileOrFolder.isFile()) {
×
859
    file = getFile(ui->treeView->currentIndex(), true);
×
860
  } else {
861
    file = Util::getDir(ui->treeView->currentIndex(), true, model, proxyModel);
×
862
    isDir = true;
863
  }
864

865
  QString dirMessage = tr(" and the whole content?");
866
  if (isDir) {
×
867
    QDirIterator it(model.rootPath() + QDir::separator() + file,
×
868
                    QDirIterator::Subdirectories);
×
869
    bool okDir = true;
870
    while (it.hasNext() && okDir) {
×
871
      it.next();
×
872
      if (QFileInfo(it.filePath()).isFile()) {
×
873
        if (QFileInfo(it.filePath()).suffix() != "gpg") {
×
874
          okDir = false;
875
          dirMessage = tr(" and the whole content? <br><strong>Attention: "
×
876
                          "there are unexpected files in the given folder, "
877
                          "check them before continue.</strong>");
878
        }
879
      }
880
    }
881
  }
×
882

883
  if (QMessageBox::question(
×
884
          this, isDir ? tr("Delete folder?") : tr("Delete password?"),
×
885
          tr("Are you sure you want to delete %1%2?")
×
886
              .arg(QDir::separator() + file, isDir ? dirMessage : "?"),
×
887
          QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) {
888
    return;
889
  }
890

891
  QtPassSettings::getPass()->Remove(file, isDir);
×
892
}
×
893

894
/**
895
 * @brief MainWindow::onOTP try and generate (selected) OTP code.
896
 */
897
void MainWindow::onOtp() {
×
898
  QString file = getFile(ui->treeView->currentIndex(), true);
×
899
  if (!file.isEmpty()) {
×
900
    if (QtPassSettings::isUseOtp()) {
×
901
      setUiElementsEnabled(false);
×
902
      QtPassSettings::getPass()->OtpGenerate(file);
×
903
    }
904
  } else {
905
    flashText(tr("No password selected for OTP generation"), true);
×
906
  }
907
}
×
908

909
/**
910
 * @brief MainWindow::onEdit try and edit (selected) password.
911
 */
912
void MainWindow::onEdit() {
×
913
  QString file = getFile(ui->treeView->currentIndex(), true);
×
914
  editPassword(file);
×
915
}
×
916

917
/**
918
 * @brief MainWindow::userDialog see MainWindow::onUsers()
919
 * @param dir folder to edit users for.
920
 */
921
void MainWindow::userDialog(const QString &dir) {
×
922
  if (!dir.isEmpty()) {
×
923
    currentDir = dir;
×
924
  }
925
  onUsers();
×
926
}
×
927

928
/**
929
 * @brief MainWindow::onUsers edit users for the current
930
 * folder,
931
 * gets lists and opens UserDialog.
932
 */
933
void MainWindow::onUsers() {
×
934
  QString dir =
935
      currentDir.isEmpty()
936
          ? Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel)
×
937
          : currentDir;
×
938

939
  UsersDialog d(dir, this);
×
940
  if (!d.exec()) {
×
941
    ui->treeView->setFocus();
×
942
  }
943
}
×
944

945
/**
946
 * @brief MainWindow::messageAvailable we have some text/message/search to do.
947
 * @param message
948
 */
949
void MainWindow::messageAvailable(const QString &message) {
×
950
  if (message.isEmpty()) {
×
951
    focusInput();
×
952
  } else {
953
    ui->treeView->expandAll();
×
954
    ui->lineEdit->setText(message);
×
955
    on_lineEdit_returnPressed();
×
956
  }
957
  show();
×
958
  raise();
×
959
}
×
960

961
/**
962
 * @brief MainWindow::generateKeyPair internal gpg keypair generator . .
963
 * @param batch
964
 * @param keygenWindow
965
 */
966
void MainWindow::generateKeyPair(const QString &batch, QDialog *keygenWindow) {
×
967
  keygen = keygenWindow;
×
968
  emit generateGPGKeyPair(batch);
×
969
}
×
970

971
/**
972
 * @brief MainWindow::updateProfileBox update the list of profiles, optionally
973
 * select a more appropriate one to view too
974
 */
975
void MainWindow::updateProfileBox() {
×
976
  QHash<QString, QHash<QString, QString>> profiles =
977
      QtPassSettings::getProfiles();
×
978

979
  if (profiles.isEmpty()) {
980
    ui->profileWidget->hide();
×
981
  } else {
982
    ui->profileWidget->show();
×
983
    ui->profileBox->setEnabled(profiles.size() > 1);
×
984
    ui->profileBox->clear();
×
985
    QHashIterator<QString, QHash<QString, QString>> i(profiles);
×
986
    while (i.hasNext()) {
×
987
      i.next();
988
      if (!i.key().isEmpty()) {
×
989
        ui->profileBox->addItem(i.key());
×
990
      }
991
    }
992
    ui->profileBox->model()->sort(0);
×
993
  }
994
  int index = ui->profileBox->findText(QtPassSettings::getProfile());
×
995
  if (index != -1) { //  -1 for not found
×
996
    ui->profileBox->setCurrentIndex(index);
×
997
  }
998
}
×
999

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

1025
  ui->lineEdit->clear();
×
1026

1027
  QtPassSettings::setProfile(name);
×
1028

1029
  QtPassSettings::setPassStore(
×
1030
      QtPassSettings::getProfiles().value(name).value("path"));
×
1031
  QtPassSettings::setPassSigningKey(
×
1032
      QtPassSettings::getProfiles().value(name).value("signingKey"));
×
1033
  ui->statusBar->showMessage(tr("Profile changed to %1").arg(name), 2000);
×
1034

1035
  QtPassSettings::getPass()->updateEnv();
×
1036

1037
  const QString passStore = QtPassSettings::getPassStore();
×
1038
  proxyModel.setStore(passStore);
×
1039
  ui->treeView->setRootIndex(
×
1040
      proxyModel.mapFromSource(model.setRootPath(passStore)));
×
1041
  deselect();
×
1042
  ui->treeView->setCurrentIndex(QModelIndex());
×
1043
}
1044

1045
/**
1046
 * @brief MainWindow::initTrayIcon show a nice tray icon on systems that
1047
 * support
1048
 * it
1049
 */
1050
void MainWindow::initTrayIcon() {
×
1051
  this->tray = new TrayIcon(this);
×
1052
  // Setup tray icon
1053

1054
  if (tray == nullptr) {
1055
#ifdef QT_DEBUG
1056
    dbg() << "Allocating tray icon failed.";
1057
#endif
1058
  }
1059

1060
  if (!tray->getIsAllocated()) {
×
1061
    destroyTrayIcon();
×
1062
  }
1063
}
×
1064

1065
/**
1066
 * @brief MainWindow::destroyTrayIcon remove that pesky tray icon
1067
 */
1068
void MainWindow::destroyTrayIcon() {
×
1069
  delete this->tray;
×
1070
  tray = nullptr;
×
1071
}
×
1072

1073
/**
1074
 * @brief MainWindow::closeEvent hide or quit
1075
 * @param event
1076
 */
1077
void MainWindow::closeEvent(QCloseEvent *event) {
×
1078
  if (QtPassSettings::isHideOnClose()) {
×
1079
    this->hide();
×
1080
    event->ignore();
1081
  } else {
1082
    m_qtPass->clearClipboard();
×
1083

1084
    QtPassSettings::setGeometry(saveGeometry());
×
1085
    QtPassSettings::setSavestate(saveState());
×
1086
    QtPassSettings::setMaximized(isMaximized());
×
1087
    if (!isMaximized()) {
×
1088
      QtPassSettings::setPos(pos());
×
1089
      QtPassSettings::setSize(size());
×
1090
    }
1091
    event->accept();
1092
  }
1093
}
×
1094

1095
/**
1096
 * @brief MainWindow::eventFilter filter out some events and focus the
1097
 * treeview
1098
 * @param obj
1099
 * @param event
1100
 * @return
1101
 */
1102
auto MainWindow::eventFilter(QObject *obj, QEvent *event) -> bool {
×
1103
  if (obj == ui->lineEdit && event->type() == QEvent::KeyPress) {
×
1104
    auto *key = dynamic_cast<QKeyEvent *>(event);
×
1105
    if (key != nullptr && key->key() == Qt::Key_Down) {
×
1106
      ui->treeView->setFocus();
×
1107
    }
1108
  }
1109
  return QObject::eventFilter(obj, event);
×
1110
}
1111

1112
/**
1113
 * @brief MainWindow::keyPressEvent did anyone press return, enter or escape?
1114
 * @param event
1115
 */
1116
void MainWindow::keyPressEvent(QKeyEvent *event) {
×
1117
  switch (event->key()) {
×
1118
  case Qt::Key_Delete:
×
1119
    onDelete();
×
1120
    break;
×
1121
  case Qt::Key_Return:
×
1122
  case Qt::Key_Enter:
1123
    if (proxyModel.rowCount() > 0) {
×
1124
      on_treeView_clicked(ui->treeView->currentIndex());
×
1125
    }
1126
    break;
1127
  case Qt::Key_Escape:
×
1128
    ui->lineEdit->clear();
×
1129
    break;
×
1130
  default:
1131
    break;
1132
  }
1133
}
×
1134

1135
/**
1136
 * @brief MainWindow::showContextMenu show us the (file or folder) context
1137
 * menu
1138
 * @param pos
1139
 */
1140
void MainWindow::showContextMenu(const QPoint &pos) {
×
1141
  QModelIndex index = ui->treeView->indexAt(pos);
×
1142
  bool selected = true;
1143
  if (!index.isValid()) {
1144
    ui->treeView->clearSelection();
×
1145
    ui->actionDelete->setEnabled(false);
×
1146
    ui->actionEdit->setEnabled(false);
×
1147
    currentDir = "";
×
1148
    selected = false;
1149
  }
1150

1151
  ui->treeView->setCurrentIndex(index);
×
1152

1153
  QPoint globalPos = ui->treeView->viewport()->mapToGlobal(pos);
×
1154

1155
  QFileInfo fileOrFolder =
1156
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
1157

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

1197
/**
1198
 * @brief MainWindow::showBrowserContextMenu show us the context menu in
1199
 * password window
1200
 * @param pos
1201
 */
1202
void MainWindow::showBrowserContextMenu(const QPoint &pos) {
×
1203
  QMenu *contextMenu = ui->textBrowser->createStandardContextMenu(pos);
×
1204
  QPoint globalPos = ui->textBrowser->viewport()->mapToGlobal(pos);
×
1205

1206
  contextMenu->exec(globalPos);
×
1207
  delete contextMenu;
×
1208
}
×
1209

1210
/**
1211
 * @brief MainWindow::openFolder open the folder in the default file manager
1212
 */
1213
void MainWindow::openFolder() {
×
1214
  QString dir =
1215
      Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel);
×
1216

1217
  QString path = QDir::toNativeSeparators(dir);
×
1218
  QDesktopServices::openUrl(QUrl::fromLocalFile(path));
×
1219
}
×
1220

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

1263
/**
1264
 * @brief MainWindow::renameFolder rename an existing folder
1265
 */
1266
void MainWindow::renameFolder() {
×
1267
  bool ok;
1268
  QString srcDir = QDir::cleanPath(
1269
      Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel));
×
1270
  QString srcDirName = QDir(srcDir).dirName();
×
1271
  QString newName =
1272
      QInputDialog::getText(this, tr("Rename file"), tr("Rename Folder To: "),
×
1273
                            QLineEdit::Normal, srcDirName, &ok);
×
1274
  if (!ok || newName.isEmpty()) {
×
1275
    return;
1276
  }
1277
  QString destDir = srcDir;
1278
  destDir.replace(srcDir.lastIndexOf(srcDirName), srcDirName.length(), newName);
×
1279
  QtPassSettings::getPass()->Move(srcDir, destDir);
×
1280
}
1281

1282
/**
1283
 * @brief MainWindow::editPassword read password and open edit window via
1284
 * MainWindow::onEdit()
1285
 */
1286
void MainWindow::editPassword(const QString &file) {
×
1287
  if (!file.isEmpty()) {
×
1288
    if (QtPassSettings::isUseGit() && QtPassSettings::isAutoPull()) {
×
1289
      onUpdate(true);
×
1290
    }
1291
    setPassword(file, false);
×
1292
  }
1293
}
×
1294

1295
/**
1296
 * @brief MainWindow::renamePassword rename an existing password
1297
 */
1298
void MainWindow::renamePassword() {
×
1299
  bool ok;
1300
  QString file = getFile(ui->treeView->currentIndex(), false);
×
1301
  QString filePath = QFileInfo(file).path();
×
1302
  QString fileName = QFileInfo(file).fileName();
×
1303
  if (fileName.endsWith(".gpg", Qt::CaseInsensitive)) {
×
1304
    fileName.chop(4);
×
1305
  }
1306

1307
  QString newName =
1308
      QInputDialog::getText(this, tr("Rename file"), tr("Rename File To: "),
×
1309
                            QLineEdit::Normal, fileName, &ok);
×
1310
  if (!ok || newName.isEmpty()) {
×
1311
    return;
1312
  }
1313
  QString newFile = QDir(filePath).filePath(newName);
×
1314
  QtPassSettings::getPass()->Move(file, newFile);
×
1315
}
1316

1317
/**
1318
 * @brief MainWindow::clearTemplateWidgets empty the template widget fields in
1319
 * the UI
1320
 */
1321
void MainWindow::clearTemplateWidgets() {
×
1322
  while (ui->gridLayout->count() > 0) {
×
1323
    QLayoutItem *item = ui->gridLayout->takeAt(0);
×
1324
    delete item->widget();
×
1325
    delete item;
×
1326
  }
1327
  ui->verticalLayoutPassword->setSpacing(0);
×
1328
}
×
1329

1330
/**
1331
 * @brief Copies the password of the selected file from the tree view to the
1332
 * clipboard.
1333
 * @example
1334
 * MainWindow::copyPasswordFromTreeview();
1335
 *
1336
 * @return void - This function does not return a value.
1337
 */
1338
void MainWindow::copyPasswordFromTreeview() {
×
1339
  QFileInfo fileOrFolder =
1340
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
1341

1342
  if (fileOrFolder.isFile()) {
×
1343
    QString file = getFile(ui->treeView->currentIndex(), true);
×
1344
    // Disconnect any previous connection to avoid accumulation
1345
    disconnect(QtPassSettings::getPass(), &Pass::finishedShow, this,
×
1346
               &MainWindow::passwordFromFileToClipboard);
1347
    connect(QtPassSettings::getPass(), &Pass::finishedShow, this,
×
1348
            &MainWindow::passwordFromFileToClipboard);
×
1349
    QtPassSettings::getPass()->Show(file);
×
1350
  }
1351
}
×
1352

1353
void MainWindow::passwordFromFileToClipboard(const QString &text) {
×
1354
  QStringList tokens = text.split('\n');
×
1355
  m_qtPass->copyTextToClipboard(tokens[0]);
×
1356
}
×
1357

1358
/**
1359
 * @brief MainWindow::addToGridLayout add a field to the template grid
1360
 * @param position
1361
 * @param field
1362
 * @param value
1363
 */
1364
void MainWindow::addToGridLayout(int position, const QString &field,
×
1365
                                 const QString &value) {
1366
  QString trimmedField = field.trimmed();
1367
  QString trimmedValue = value.trimmed();
1368

1369
  const QString buttonStyle =
1370
      "border-style: none; background: transparent; padding: 0; margin: 0; "
1371
      "icon-size: 16px; color: inherit;";
×
1372

1373
  // Combine the Copy button and the line edit in one widget
1374
  auto *frame = new QFrame();
×
1375
  QLayout *ly = new QHBoxLayout();
×
1376
  ly->setContentsMargins(5, 2, 2, 2);
×
1377
  ly->setSpacing(0);
×
1378
  frame->setLayout(ly);
×
1379
  if (QtPassSettings::getClipBoardType() != Enums::CLIPBOARD_NEVER) {
×
1380
    auto *fieldLabel = new QPushButtonWithClipboard(trimmedValue, this);
×
1381
    connect(fieldLabel, &QPushButtonWithClipboard::clicked, m_qtPass,
×
1382
            &QtPass::copyTextToClipboard);
×
1383

1384
    fieldLabel->setStyleSheet(buttonStyle);
×
1385
    frame->layout()->addWidget(fieldLabel);
×
1386
  }
1387

1388
  if (QtPassSettings::isUseQrencode()) {
×
1389
    auto *qrbutton = new QPushButtonAsQRCode(trimmedValue, this);
×
1390
    connect(qrbutton, &QPushButtonAsQRCode::clicked, m_qtPass,
×
1391
            &QtPass::showTextAsQRCode);
×
1392
    qrbutton->setStyleSheet(buttonStyle);
×
1393
    frame->layout()->addWidget(qrbutton);
×
1394
  }
1395

1396
  // set the echo mode to password, if the field is "password"
1397
  const QString lineStyle =
1398
      QtPassSettings::isUseMonospace()
×
1399
          ? "border-style: none; background: transparent; font-family: "
1400
            "monospace;"
1401
          : "border-style: none; background: transparent;";
×
1402

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

1433
  frame->setStyleSheet(
×
1434
      ".QFrame{border: 1px solid lightgrey; border-radius: 5px;}");
1435

1436
  // set into the layout
1437
  ui->gridLayout->addWidget(new QLabel(trimmedField), position, 0);
×
1438
  ui->gridLayout->addWidget(frame, position, 1);
×
1439
}
×
1440

1441
/**
1442
 * @brief Displays message in status bar
1443
 *
1444
 * @param msg     text to be displayed
1445
 * @param timeout time for which msg shall be visible
1446
 */
1447
void MainWindow::showStatusMessage(const QString &msg, int timeout) {
×
1448
  ui->statusBar->showMessage(msg, timeout);
×
1449
}
×
1450

1451
/**
1452
 * @brief MainWindow::reencryptPath re-encrypt all passwords in a directory
1453
 * @param dir Directory path to re-encrypt
1454
 */
1455
void MainWindow::reencryptPath(const QString &dir) {
×
1456
  QDir checkDir(dir);
×
1457
  if (!checkDir.exists()) {
×
1458
    QMessageBox::critical(this, tr("Error"),
×
1459
                          tr("Directory does not exist: %1").arg(dir));
×
1460
    return;
×
1461
  }
1462

1463
  int ret = QMessageBox::question(
×
1464
      this, tr("Re-encrypt passwords"),
×
1465
      tr("Re-encrypt all passwords in %1?\n\n"
×
1466
         "This will re-encrypt ALL password files in this folder "
1467
         "using the current recipients defined in .gpg-id.\n\n"
1468
         "This may rewrite many files and cannot be undone easily.\n\n"
1469
         "Continue?")
1470
          .arg(QDir(dir).dirName()),
×
1471
      QMessageBox::Yes | QMessageBox::No);
1472

1473
  if (ret != QMessageBox::Yes)
×
1474
    return;
1475

1476
  // Prevent double execution - use same method as startReencryptPath
1477
  setUiElementsEnabled(false);
×
1478
  ui->treeView->setDisabled(true);
×
1479

1480
  QtPassSettings::getImitatePass()->reencryptPath(
×
1481
      QDir::cleanPath(QDir(dir).absolutePath()));
×
1482
}
×
1483

1484
/**
1485
 * @brief MainWindow::startReencryptPath disable ui elements and treeview
1486
 */
1487
void MainWindow::startReencryptPath() {
×
1488
  setUiElementsEnabled(false);
×
1489
  ui->treeView->setDisabled(true);
×
1490
}
×
1491

1492
/**
1493
 * @brief MainWindow::endReencryptPath re-enable ui elements
1494
 */
1495
void MainWindow::endReencryptPath() { setUiElementsEnabled(true); }
×
1496

1497
void MainWindow::updateGitButtonVisibility() {
×
1498
  if (!QtPassSettings::isUseGit() ||
×
1499
      (QtPassSettings::getGitExecutable().isEmpty() &&
×
1500
       QtPassSettings::getPassExecutable().isEmpty())) {
×
1501
    enableGitButtons(false);
×
1502
  } else {
1503
    enableGitButtons(true);
×
1504
  }
1505
}
×
1506

1507
void MainWindow::updateOtpButtonVisibility() {
×
1508
#if defined(Q_OS_WIN) || defined(__APPLE__)
1509
  ui->actionOtp->setVisible(false);
1510
#endif
1511
  if (!QtPassSettings::isUseOtp()) {
×
1512
    ui->actionOtp->setEnabled(false);
×
1513
  } else {
1514
    ui->actionOtp->setEnabled(true);
×
1515
  }
1516
}
×
1517

NEW
1518
void MainWindow::updateGrepButtonVisibility() {
×
NEW
1519
  const bool enabled = QtPassSettings::isUseGrepSearch();
×
NEW
1520
  ui->grepButton->setVisible(enabled);
×
NEW
1521
  ui->grepCaseButton->setVisible(enabled);
×
NEW
1522
  if (!enabled && m_grepMode) {
×
NEW
1523
    ui->grepButton->setChecked(false);
×
1524
  }
NEW
1525
}
×
1526

UNCOV
1527
void MainWindow::enableGitButtons(const bool &state) {
×
1528
  // Following GNOME guidelines is preferable disable buttons instead of hide
1529
  ui->actionPush->setEnabled(state);
×
1530
  ui->actionUpdate->setEnabled(state);
×
1531
}
×
1532

1533
/**
1534
 * @brief MainWindow::critical critical message popup wrapper.
1535
 * @param title
1536
 * @param msg
1537
 */
1538
void MainWindow::critical(const QString &title, const QString &msg) {
×
1539
  QMessageBox::critical(this, title, msg);
×
1540
}
×
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