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

IJHack / QtPass / 24612481092

18 Apr 2026 07:46PM UTC coverage: 22.718% (+0.8%) from 21.908%
24612481092

Pull #1037

github

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

81 of 218 new or added lines in 7 files covered. (37.16%)

400 existing lines in 9 files now uncovered.

1304 of 5740 relevant lines covered (22.72%)

8.56 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
/src/mainwindow.cpp
1
// SPDX-FileCopyrightText: 2014 Anne Jan Brouwer
2
// SPDX-License-Identifier: GPL-3.0-or-later
3
#include "mainwindow.h"
4

5
#ifdef QT_DEBUG
6
#include "debughelper.h"
7
#endif
8

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

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

52
  m_qtPass = new QtPass(this);
×
53

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

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

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

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

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

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

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

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

107
  updateProfileBox();
×
108

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

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

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

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

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

126
  setUiElementsEnabled(true);
×
127

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

580
  if (QtPassSettings::isAlwaysOnTop()) {
×
581
    Qt::WindowFlags flags = windowFlags();
582
    setWindowFlags(flags | Qt::WindowStaysOnTopHint);
×
583
    show();
×
584
  }
585

586
  if (QtPassSettings::isUseTrayIcon() && tray == nullptr) {
×
587
    initTrayIcon();
×
588
    if (QtPassSettings::isStartMinimized()) {
×
589
      // since we are still in constructor, can't directly hide
590
      QTimer::singleShot(10, this, SLOT(hide()));
×
591
    }
592
  } else if (!QtPassSettings::isUseTrayIcon() && tray != nullptr) {
×
593
    destroyTrayIcon();
×
594
  }
595
}
×
596

597
/**
598
 * @brief MainWindow::on_configButton_clicked run Mainwindow::config
599
 */
600
void MainWindow::onConfig() { config(); }
×
601

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

619
/**
620
 * @brief MainWindow::onTimeoutSearch Fired when search is finished or too much
621
 * time from two keypresses is elapsed
622
 */
623
void MainWindow::onTimeoutSearch() {
×
624
  QString query = ui->lineEdit->text();
×
625

626
  if (query.isEmpty()) {
×
627
    ui->treeView->collapseAll();
×
628
    deselect();
×
629
  }
630

631
  query.replace(QStringLiteral(" "), ".*");
×
632
  QRegularExpression regExp(query, QRegularExpression::CaseInsensitiveOption);
×
633
  proxyModel.setFilterRegularExpression(regExp);
×
634
  ui->treeView->setRootIndex(proxyModel.mapFromSource(
×
635
      model.setRootPath(QtPassSettings::getPassStore())));
×
636

637
  if (proxyModel.rowCount() > 0 && !query.isEmpty()) {
×
638
    selectFirstFile();
×
639
  } else {
640
    ui->actionEdit->setEnabled(false);
×
641
    ui->actionDelete->setEnabled(false);
×
642
  }
643
}
×
644

645
/**
646
 * @brief MainWindow::on_lineEdit_returnPressed get searching
647
 *
648
 * Select the first possible file in the tree
649
 */
650
void MainWindow::on_lineEdit_returnPressed() {
×
651
#ifdef QT_DEBUG
652
  dbg() << "on_lineEdit_returnPressed" << proxyModel.rowCount();
653
#endif
654

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

893
  QtPassSettings::getPass()->Remove(file, isDir);
×
894
}
×
895

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

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

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

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

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

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

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

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

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

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

1027
  ui->lineEdit->clear();
×
1028

1029
  QtPassSettings::setProfile(name);
×
1030

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

1037
  QtPassSettings::getPass()->updateEnv();
×
1038

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

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

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

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

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

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

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

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

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

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

1153
  ui->treeView->setCurrentIndex(index);
×
1154

1155
  QPoint globalPos = ui->treeView->viewport()->mapToGlobal(pos);
×
1156

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

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

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

1208
  contextMenu->exec(globalPos);
×
1209
  delete contextMenu;
×
1210
}
×
1211

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1386
    fieldLabel->setStyleSheet(buttonStyle);
×
1387
    frame->layout()->addWidget(fieldLabel);
×
1388
  }
1389

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

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

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

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

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

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

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

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

1475
  if (ret != QMessageBox::Yes)
×
1476
    return;
1477

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

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

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

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

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

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

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

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

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