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

IJHack / QtPass / 24607514328

18 Apr 2026 03:10PM UTC coverage: 22.905% (+1.0%) from 21.908%
24607514328

Pull #1037

github

web-flow
Merge 056c1902a into dfd4e5b4c
Pull Request #1037: feat: implement pass grep content search (#109)

75 of 154 new or added lines in 5 files covered. (48.7%)

225 existing lines in 6 files now uncovered.

1298 of 5667 relevant lines covered (22.9%)

8.62 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);
×
123

124
  setUiElementsEnabled(true);
×
125

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

329
    m_qtPass->setFreshStart(false);
×
330
  }
331
}
×
332

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

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

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

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

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

412
  if (fileOrFolder.isFile()) {
×
413
    editPassword(getFile(index, true));
×
414
  }
415
}
×
416

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

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

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

457
  // set clipped text
458
  m_qtPass->setClippedText(password, p_output);
×
459

460
  // first clear the current view:
461
  clearTemplateWidgets();
×
462

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

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

483
    output = fileContent.getRemainingDataForDisplay();
×
484
  }
485

486
  if (QtPassSettings::isUseAutoclearPanel()) {
×
487
    clearPanelTimer.start();
×
488
  }
489

490
  emit passShowHandlerFinished(output);
×
491
  setUiElementsEnabled(true);
×
492
}
×
493

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

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

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

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

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

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

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

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

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

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

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

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

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

NEW
653
  if (m_grepMode) {
×
NEW
654
    const QString query = ui->lineEdit->text().trimmed();
×
NEW
655
    if (!query.isEmpty())
×
NEW
656
      QtPassSettings::getPass()->Grep(query, ui->grepCaseButton->isChecked());
×
657
    return;
658
  }
659

660
  if (proxyModel.rowCount() > 0) {
×
661
    selectFirstFile();
×
662
    on_treeView_clicked(ui->treeView->currentIndex());
×
663
  }
664
}
665

666
/**
667
 * @brief Toggle grep (content search) mode.
668
 */
NEW
669
void MainWindow::on_grepButton_toggled(bool checked) {
×
NEW
670
  m_grepMode = checked;
×
NEW
671
  if (checked) {
×
NEW
672
    ui->lineEdit->setPlaceholderText(tr("Search content (regex)"));
×
NEW
673
    ui->lineEdit->clear();
×
NEW
674
    searchTimer.stop();
×
NEW
675
    proxyModel.setFilterRegularExpression(QRegularExpression());
×
NEW
676
    ui->grepResultsList->setVisible(false);
×
677
    // Keep treeView visible until results arrive
678
  } else {
NEW
679
    ui->lineEdit->setPlaceholderText(tr("Search Password"));
×
NEW
680
    ui->grepResultsList->clear();
×
NEW
681
    ui->grepResultsList->setVisible(false);
×
NEW
682
    ui->treeView->setVisible(true);
×
NEW
683
    proxyModel.setFilterRegularExpression(QRegularExpression());
×
NEW
684
    ui->treeView->setRootIndex(proxyModel.mapFromSource(
×
NEW
685
        model.setRootPath(QtPassSettings::getPassStore())));
×
686
  }
NEW
687
}
×
688

689
/**
690
 * @brief Display grep results in grepResultsList.
691
 */
NEW
692
void MainWindow::onGrepFinished(
×
693
    const QList<QPair<QString, QStringList>> &results) {
NEW
694
  setUiElementsEnabled(true);
×
NEW
695
  if (!m_grepMode)
×
696
    return;
NEW
697
  ui->grepResultsList->clear();
×
NEW
698
  if (results.isEmpty()) {
×
NEW
699
    ui->statusBar->showMessage(tr("No matches found."), 3000);
×
NEW
700
    ui->grepResultsList->setVisible(false);
×
NEW
701
    ui->treeView->setVisible(true);
×
NEW
702
    return;
×
703
  }
NEW
704
  for (const auto &pair : results) {
×
NEW
705
    QTreeWidgetItem *entryItem = new QTreeWidgetItem(ui->grepResultsList);
×
NEW
706
    entryItem->setText(0, pair.first);
×
NEW
707
    entryItem->setData(0, Qt::UserRole, pair.first);
×
NEW
708
    for (const QString &line : pair.second) {
×
NEW
709
      QTreeWidgetItem *lineItem = new QTreeWidgetItem(entryItem);
×
NEW
710
      lineItem->setText(0, line);
×
NEW
711
      lineItem->setData(0, Qt::UserRole, pair.first);
×
712
    }
713
  }
NEW
714
  ui->grepResultsList->expandAll();
×
NEW
715
  ui->treeView->setVisible(false);
×
NEW
716
  ui->grepResultsList->setVisible(true);
×
NEW
717
  ui->statusBar->showMessage(tr("Found %1 match(es).").arg(results.size()),
×
718
                             3000);
719
}
720

721
/**
722
 * @brief Navigate to the password entry when a grep result is clicked.
723
 */
NEW
724
void MainWindow::on_grepResultsList_itemClicked(QTreeWidgetItem *item,
×
725
                                                int /*column*/) {
NEW
726
  const QString entry = item->data(0, Qt::UserRole).toString();
×
NEW
727
  if (entry.isEmpty())
×
728
    return;
729
  const QString fullPath = QDir::cleanPath(
NEW
730
      QDir(QtPassSettings::getPassStore()).filePath(entry + ".gpg"));
×
NEW
731
  QModelIndex srcIndex = model.index(fullPath);
×
732
  if (!srcIndex.isValid())
733
    return;
NEW
734
  QModelIndex proxyIndex = proxyModel.mapFromSource(srcIndex);
×
735
  if (!proxyIndex.isValid())
736
    return;
NEW
737
  ui->treeView->setCurrentIndex(proxyIndex);
×
NEW
738
  on_treeView_clicked(proxyIndex);
×
739
}
740

741
/**
742
 * @brief MainWindow::selectFirstFile select the first possible file in the
743
 * tree
744
 */
745
void MainWindow::selectFirstFile() {
×
746
  QModelIndex index = proxyModel.mapFromSource(
×
747
      model.setRootPath(QtPassSettings::getPassStore()));
×
748
  index = firstFile(index);
×
749
  ui->treeView->setCurrentIndex(index);
×
750
}
×
751

752
/**
753
 * @brief MainWindow::firstFile return location of first possible file
754
 * @param parentIndex
755
 * @return QModelIndex
756
 */
757
auto MainWindow::firstFile(QModelIndex parentIndex) -> QModelIndex {
×
758
  QModelIndex index = parentIndex;
×
759
  int numRows = proxyModel.rowCount(parentIndex);
×
760
  for (int row = 0; row < numRows; ++row) {
×
761
    index = proxyModel.index(row, 0, parentIndex);
×
762
    if (model.fileInfo(proxyModel.mapToSource(index)).isFile()) {
×
763
      return index;
×
764
    }
765
    if (proxyModel.hasChildren(index)) {
×
766
      return firstFile(index);
×
767
    }
768
  }
769
  return index;
×
770
}
771

772
/**
773
 * @brief MainWindow::setPassword open passworddialog
774
 * @param file which pgp file
775
 * @param isNew insert (not update)
776
 */
777
void MainWindow::setPassword(const QString &file, bool isNew) {
×
778
  PasswordDialog d(file, isNew, this);
×
779

780
  if (!d.exec()) {
×
781
    ui->treeView->setFocus();
×
782
  }
783
}
×
784

785
/**
786
 * @brief MainWindow::addPassword add a new password by showing a
787
 * number of dialogs.
788
 */
789
void MainWindow::addPassword() {
×
790
  bool ok;
791
  QString dir =
792
      Util::getDir(ui->treeView->currentIndex(), true, model, proxyModel);
×
793
  QString file =
794
      QInputDialog::getText(this, tr("New file"),
×
795
                            tr("New password file: \n(Will be placed in %1 )")
×
796
                                .arg(QtPassSettings::getPassStore() +
×
797
                                     Util::getDir(ui->treeView->currentIndex(),
×
798
                                                  true, model, proxyModel)),
799
                            QLineEdit::Normal, "", &ok);
×
800
  if (!ok || file.isEmpty()) {
×
801
    return;
802
  }
803
  file = dir + file;
×
804
  setPassword(file);
×
805
}
806

807
/**
808
 * @brief MainWindow::onDelete remove password, if you are
809
 * sure.
810
 */
811
void MainWindow::onDelete() {
×
812
  QModelIndex currentIndex = ui->treeView->currentIndex();
×
813
  if (!currentIndex.isValid()) {
814
    // This fixes https://github.com/IJHack/QtPass/issues/556
815
    // Otherwise the entire password directory would be deleted if
816
    // nothing is selected in the tree view.
817
    return;
×
818
  }
819

820
  QFileInfo fileOrFolder =
821
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
822
  QString file = "";
×
823
  bool isDir = false;
824

825
  if (fileOrFolder.isFile()) {
×
826
    file = getFile(ui->treeView->currentIndex(), true);
×
827
  } else {
828
    file = Util::getDir(ui->treeView->currentIndex(), true, model, proxyModel);
×
829
    isDir = true;
830
  }
831

832
  QString dirMessage = tr(" and the whole content?");
833
  if (isDir) {
×
834
    QDirIterator it(model.rootPath() + QDir::separator() + file,
×
835
                    QDirIterator::Subdirectories);
×
836
    bool okDir = true;
837
    while (it.hasNext() && okDir) {
×
838
      it.next();
×
839
      if (QFileInfo(it.filePath()).isFile()) {
×
840
        if (QFileInfo(it.filePath()).suffix() != "gpg") {
×
841
          okDir = false;
842
          dirMessage = tr(" and the whole content? <br><strong>Attention: "
×
843
                          "there are unexpected files in the given folder, "
844
                          "check them before continue.</strong>");
845
        }
846
      }
847
    }
848
  }
×
849

850
  if (QMessageBox::question(
×
851
          this, isDir ? tr("Delete folder?") : tr("Delete password?"),
×
852
          tr("Are you sure you want to delete %1%2?")
×
853
              .arg(QDir::separator() + file, isDir ? dirMessage : "?"),
×
854
          QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) {
855
    return;
856
  }
857

858
  QtPassSettings::getPass()->Remove(file, isDir);
×
859
}
×
860

861
/**
862
 * @brief MainWindow::onOTP try and generate (selected) OTP code.
863
 */
864
void MainWindow::onOtp() {
×
865
  QString file = getFile(ui->treeView->currentIndex(), true);
×
866
  if (!file.isEmpty()) {
×
867
    if (QtPassSettings::isUseOtp()) {
×
868
      setUiElementsEnabled(false);
×
869
      QtPassSettings::getPass()->OtpGenerate(file);
×
870
    }
871
  } else {
872
    flashText(tr("No password selected for OTP generation"), true);
×
873
  }
874
}
×
875

876
/**
877
 * @brief MainWindow::onEdit try and edit (selected) password.
878
 */
879
void MainWindow::onEdit() {
×
880
  QString file = getFile(ui->treeView->currentIndex(), true);
×
881
  editPassword(file);
×
882
}
×
883

884
/**
885
 * @brief MainWindow::userDialog see MainWindow::onUsers()
886
 * @param dir folder to edit users for.
887
 */
888
void MainWindow::userDialog(const QString &dir) {
×
889
  if (!dir.isEmpty()) {
×
890
    currentDir = dir;
×
891
  }
892
  onUsers();
×
893
}
×
894

895
/**
896
 * @brief MainWindow::onUsers edit users for the current
897
 * folder,
898
 * gets lists and opens UserDialog.
899
 */
900
void MainWindow::onUsers() {
×
901
  QString dir =
902
      currentDir.isEmpty()
903
          ? Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel)
×
904
          : currentDir;
×
905

906
  UsersDialog d(dir, this);
×
907
  if (!d.exec()) {
×
908
    ui->treeView->setFocus();
×
909
  }
910
}
×
911

912
/**
913
 * @brief MainWindow::messageAvailable we have some text/message/search to do.
914
 * @param message
915
 */
916
void MainWindow::messageAvailable(const QString &message) {
×
917
  if (message.isEmpty()) {
×
918
    focusInput();
×
919
  } else {
920
    ui->treeView->expandAll();
×
921
    ui->lineEdit->setText(message);
×
922
    on_lineEdit_returnPressed();
×
923
  }
924
  show();
×
925
  raise();
×
926
}
×
927

928
/**
929
 * @brief MainWindow::generateKeyPair internal gpg keypair generator . .
930
 * @param batch
931
 * @param keygenWindow
932
 */
933
void MainWindow::generateKeyPair(const QString &batch, QDialog *keygenWindow) {
×
934
  keygen = keygenWindow;
×
935
  emit generateGPGKeyPair(batch);
×
936
}
×
937

938
/**
939
 * @brief MainWindow::updateProfileBox update the list of profiles, optionally
940
 * select a more appropriate one to view too
941
 */
942
void MainWindow::updateProfileBox() {
×
943
  QHash<QString, QHash<QString, QString>> profiles =
944
      QtPassSettings::getProfiles();
×
945

946
  if (profiles.isEmpty()) {
947
    ui->profileWidget->hide();
×
948
  } else {
949
    ui->profileWidget->show();
×
950
    ui->profileBox->setEnabled(profiles.size() > 1);
×
951
    ui->profileBox->clear();
×
952
    QHashIterator<QString, QHash<QString, QString>> i(profiles);
×
953
    while (i.hasNext()) {
×
954
      i.next();
955
      if (!i.key().isEmpty()) {
×
956
        ui->profileBox->addItem(i.key());
×
957
      }
958
    }
959
    ui->profileBox->model()->sort(0);
×
960
  }
961
  int index = ui->profileBox->findText(QtPassSettings::getProfile());
×
962
  if (index != -1) { //  -1 for not found
×
963
    ui->profileBox->setCurrentIndex(index);
×
964
  }
965
}
×
966

967
/**
968
 * @brief MainWindow::on_profileBox_currentIndexChanged make sure we show the
969
 * correct "profile"
970
 * @param name
971
 */
972
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
973
void MainWindow::on_profileBox_currentIndexChanged(QString name) {
974
#else
975
/**
976
 * @brief Handles changes to the selected profile in the profile combo box.
977
 * @details Ignores the event during a fresh start or when the selected profile
978
 * matches the current profile. Otherwise, it clears the password field, updates
979
 * the active profile and related settings, refreshes the environment, and
980
 * resets the tree view and action states to reflect the newly selected profile.
981
 *
982
 * @param name - The newly selected profile name.
983
 * @return void - This function does not return a value.
984
 *
985
 */
986
void MainWindow::on_profileBox_currentTextChanged(const QString &name) {
×
987
#endif
988
  if (m_qtPass->isFreshStart() || name == QtPassSettings::getProfile()) {
×
989
    return;
×
990
  }
991

992
  ui->lineEdit->clear();
×
993

994
  QtPassSettings::setProfile(name);
×
995

996
  QtPassSettings::setPassStore(
×
997
      QtPassSettings::getProfiles().value(name).value("path"));
×
998
  QtPassSettings::setPassSigningKey(
×
999
      QtPassSettings::getProfiles().value(name).value("signingKey"));
×
1000
  ui->statusBar->showMessage(tr("Profile changed to %1").arg(name), 2000);
×
1001

1002
  QtPassSettings::getPass()->updateEnv();
×
1003

1004
  const QString passStore = QtPassSettings::getPassStore();
×
1005
  proxyModel.setStore(passStore);
×
1006
  ui->treeView->setRootIndex(
×
1007
      proxyModel.mapFromSource(model.setRootPath(passStore)));
×
1008
  deselect();
×
1009
  ui->treeView->setCurrentIndex(QModelIndex());
×
1010
}
1011

1012
/**
1013
 * @brief MainWindow::initTrayIcon show a nice tray icon on systems that
1014
 * support
1015
 * it
1016
 */
1017
void MainWindow::initTrayIcon() {
×
1018
  this->tray = new TrayIcon(this);
×
1019
  // Setup tray icon
1020

1021
  if (tray == nullptr) {
1022
#ifdef QT_DEBUG
1023
    dbg() << "Allocating tray icon failed.";
1024
#endif
1025
  }
1026

1027
  if (!tray->getIsAllocated()) {
×
1028
    destroyTrayIcon();
×
1029
  }
1030
}
×
1031

1032
/**
1033
 * @brief MainWindow::destroyTrayIcon remove that pesky tray icon
1034
 */
1035
void MainWindow::destroyTrayIcon() {
×
1036
  delete this->tray;
×
1037
  tray = nullptr;
×
1038
}
×
1039

1040
/**
1041
 * @brief MainWindow::closeEvent hide or quit
1042
 * @param event
1043
 */
1044
void MainWindow::closeEvent(QCloseEvent *event) {
×
1045
  if (QtPassSettings::isHideOnClose()) {
×
1046
    this->hide();
×
1047
    event->ignore();
1048
  } else {
1049
    m_qtPass->clearClipboard();
×
1050

1051
    QtPassSettings::setGeometry(saveGeometry());
×
1052
    QtPassSettings::setSavestate(saveState());
×
1053
    QtPassSettings::setMaximized(isMaximized());
×
1054
    if (!isMaximized()) {
×
1055
      QtPassSettings::setPos(pos());
×
1056
      QtPassSettings::setSize(size());
×
1057
    }
1058
    event->accept();
1059
  }
1060
}
×
1061

1062
/**
1063
 * @brief MainWindow::eventFilter filter out some events and focus the
1064
 * treeview
1065
 * @param obj
1066
 * @param event
1067
 * @return
1068
 */
1069
auto MainWindow::eventFilter(QObject *obj, QEvent *event) -> bool {
×
1070
  if (obj == ui->lineEdit && event->type() == QEvent::KeyPress) {
×
1071
    auto *key = dynamic_cast<QKeyEvent *>(event);
×
1072
    if (key != nullptr && key->key() == Qt::Key_Down) {
×
1073
      ui->treeView->setFocus();
×
1074
    }
1075
  }
1076
  return QObject::eventFilter(obj, event);
×
1077
}
1078

1079
/**
1080
 * @brief MainWindow::keyPressEvent did anyone press return, enter or escape?
1081
 * @param event
1082
 */
1083
void MainWindow::keyPressEvent(QKeyEvent *event) {
×
1084
  switch (event->key()) {
×
1085
  case Qt::Key_Delete:
×
1086
    onDelete();
×
1087
    break;
×
1088
  case Qt::Key_Return:
×
1089
  case Qt::Key_Enter:
1090
    if (proxyModel.rowCount() > 0) {
×
1091
      on_treeView_clicked(ui->treeView->currentIndex());
×
1092
    }
1093
    break;
1094
  case Qt::Key_Escape:
×
1095
    ui->lineEdit->clear();
×
1096
    break;
×
1097
  default:
1098
    break;
1099
  }
1100
}
×
1101

1102
/**
1103
 * @brief MainWindow::showContextMenu show us the (file or folder) context
1104
 * menu
1105
 * @param pos
1106
 */
1107
void MainWindow::showContextMenu(const QPoint &pos) {
×
1108
  QModelIndex index = ui->treeView->indexAt(pos);
×
1109
  bool selected = true;
1110
  if (!index.isValid()) {
1111
    ui->treeView->clearSelection();
×
1112
    ui->actionDelete->setEnabled(false);
×
1113
    ui->actionEdit->setEnabled(false);
×
1114
    currentDir = "";
×
1115
    selected = false;
1116
  }
1117

1118
  ui->treeView->setCurrentIndex(index);
×
1119

1120
  QPoint globalPos = ui->treeView->viewport()->mapToGlobal(pos);
×
1121

1122
  QFileInfo fileOrFolder =
1123
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
1124

1125
  QMenu contextMenu;
×
1126
  if (!selected || fileOrFolder.isDir()) {
×
1127
    QAction *openFolder =
1128
        contextMenu.addAction(tr("Open folder with file manager"));
×
1129
    QAction *addFolder = contextMenu.addAction(tr("Add folder"));
×
1130
    QAction *addPassword = contextMenu.addAction(tr("Add password"));
×
1131
    QAction *users = contextMenu.addAction(tr("Users"));
×
1132
    connect(openFolder, &QAction::triggered, this, &MainWindow::openFolder);
×
1133
    connect(addFolder, &QAction::triggered, this, &MainWindow::addFolder);
×
1134
    connect(addPassword, &QAction::triggered, this, &MainWindow::addPassword);
×
1135
    connect(users, &QAction::triggered, this, &MainWindow::onUsers);
×
1136
  } else if (fileOrFolder.isFile()) {
×
1137
    QAction *edit = contextMenu.addAction(tr("Edit"));
×
1138
    connect(edit, &QAction::triggered, this, &MainWindow::onEdit);
×
1139
  }
1140
  if (selected) {
×
1141
    contextMenu.addSeparator();
×
1142
    if (fileOrFolder.isDir()) {
×
1143
      QAction *renameFolder = contextMenu.addAction(tr("Rename folder"));
×
1144
      connect(renameFolder, &QAction::triggered, this,
×
1145
              &MainWindow::renameFolder);
×
1146
    } else if (fileOrFolder.isFile()) {
×
1147
      QAction *renamePassword = contextMenu.addAction(tr("Rename password"));
×
1148
      connect(renamePassword, &QAction::triggered, this,
×
1149
              &MainWindow::renamePassword);
×
1150
    }
1151
    QAction *deleteItem = contextMenu.addAction(tr("Delete"));
×
1152
    connect(deleteItem, &QAction::triggered, this, &MainWindow::onDelete);
×
1153
    if (fileOrFolder.isDir()) {
×
1154
      QString dirPath = QDir::cleanPath(
1155
          Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel));
×
1156
      QAction *reencrypt = contextMenu.addAction(tr("Re-encrypt"));
×
1157
      connect(reencrypt, &QAction::triggered, this,
×
1158
              [this, dirPath]() { reencryptPath(dirPath); });
×
1159
    }
1160
  }
1161
  contextMenu.exec(globalPos);
×
1162
}
×
1163

1164
/**
1165
 * @brief MainWindow::showBrowserContextMenu show us the context menu in
1166
 * password window
1167
 * @param pos
1168
 */
1169
void MainWindow::showBrowserContextMenu(const QPoint &pos) {
×
1170
  QMenu *contextMenu = ui->textBrowser->createStandardContextMenu(pos);
×
1171
  QPoint globalPos = ui->textBrowser->viewport()->mapToGlobal(pos);
×
1172

1173
  contextMenu->exec(globalPos);
×
1174
  delete contextMenu;
×
1175
}
×
1176

1177
/**
1178
 * @brief MainWindow::openFolder open the folder in the default file manager
1179
 */
1180
void MainWindow::openFolder() {
×
1181
  QString dir =
1182
      Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel);
×
1183

1184
  QString path = QDir::toNativeSeparators(dir);
×
1185
  QDesktopServices::openUrl(QUrl::fromLocalFile(path));
×
1186
}
×
1187

1188
/**
1189
 * @brief MainWindow::addFolder add a new folder to store passwords in
1190
 */
1191
void MainWindow::addFolder() {
×
1192
  bool ok;
1193
  QString dir =
1194
      Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel);
×
1195
  QString newdir =
1196
      QInputDialog::getText(this, tr("New file"),
×
1197
                            tr("New Folder: \n(Will be placed in %1 )")
×
1198
                                .arg(QtPassSettings::getPassStore() +
×
1199
                                     Util::getDir(ui->treeView->currentIndex(),
×
1200
                                                  true, model, proxyModel)),
1201
                            QLineEdit::Normal, "", &ok);
×
1202
  if (!ok || newdir.isEmpty()) {
×
1203
    return;
1204
  }
1205
  newdir.prepend(dir);
1206
  if (!QDir().mkdir(newdir)) {
×
1207
    QMessageBox::warning(this, tr("Error"),
×
1208
                         tr("Failed to create folder: %1").arg(newdir));
×
1209
    return;
×
1210
  }
1211
  if (QtPassSettings::isAddGPGId(true)) {
×
1212
    QString gpgIdFile = newdir + "/.gpg-id";
×
1213
    QFile gpgId(gpgIdFile);
×
1214
    if (!gpgId.open(QIODevice::WriteOnly)) {
×
1215
      QMessageBox::warning(
×
1216
          this, tr("Error"),
×
1217
          tr("Failed to create .gpg-id file in: %1").arg(newdir));
×
1218
      return;
1219
    }
1220
    QList<UserInfo> users = QtPassSettings::getPass()->listKeys("", true);
×
1221
    for (const UserInfo &user : users) {
×
1222
      if (user.enabled) {
×
1223
        gpgId.write((user.key_id + "\n").toUtf8());
×
1224
      }
1225
    }
1226
    gpgId.close();
×
1227
  }
×
1228
}
1229

1230
/**
1231
 * @brief MainWindow::renameFolder rename an existing folder
1232
 */
1233
void MainWindow::renameFolder() {
×
1234
  bool ok;
1235
  QString srcDir = QDir::cleanPath(
1236
      Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel));
×
1237
  QString srcDirName = QDir(srcDir).dirName();
×
1238
  QString newName =
1239
      QInputDialog::getText(this, tr("Rename file"), tr("Rename Folder To: "),
×
1240
                            QLineEdit::Normal, srcDirName, &ok);
×
1241
  if (!ok || newName.isEmpty()) {
×
1242
    return;
1243
  }
1244
  QString destDir = srcDir;
1245
  destDir.replace(srcDir.lastIndexOf(srcDirName), srcDirName.length(), newName);
×
1246
  QtPassSettings::getPass()->Move(srcDir, destDir);
×
1247
}
1248

1249
/**
1250
 * @brief MainWindow::editPassword read password and open edit window via
1251
 * MainWindow::onEdit()
1252
 */
1253
void MainWindow::editPassword(const QString &file) {
×
1254
  if (!file.isEmpty()) {
×
1255
    if (QtPassSettings::isUseGit() && QtPassSettings::isAutoPull()) {
×
1256
      onUpdate(true);
×
1257
    }
1258
    setPassword(file, false);
×
1259
  }
1260
}
×
1261

1262
/**
1263
 * @brief MainWindow::renamePassword rename an existing password
1264
 */
1265
void MainWindow::renamePassword() {
×
1266
  bool ok;
1267
  QString file = getFile(ui->treeView->currentIndex(), false);
×
1268
  QString filePath = QFileInfo(file).path();
×
1269
  QString fileName = QFileInfo(file).fileName();
×
1270
  if (fileName.endsWith(".gpg", Qt::CaseInsensitive)) {
×
1271
    fileName.chop(4);
×
1272
  }
1273

1274
  QString newName =
1275
      QInputDialog::getText(this, tr("Rename file"), tr("Rename File To: "),
×
1276
                            QLineEdit::Normal, fileName, &ok);
×
1277
  if (!ok || newName.isEmpty()) {
×
1278
    return;
1279
  }
1280
  QString newFile = QDir(filePath).filePath(newName);
×
1281
  QtPassSettings::getPass()->Move(file, newFile);
×
1282
}
1283

1284
/**
1285
 * @brief MainWindow::clearTemplateWidgets empty the template widget fields in
1286
 * the UI
1287
 */
1288
void MainWindow::clearTemplateWidgets() {
×
1289
  while (ui->gridLayout->count() > 0) {
×
1290
    QLayoutItem *item = ui->gridLayout->takeAt(0);
×
1291
    delete item->widget();
×
1292
    delete item;
×
1293
  }
1294
  ui->verticalLayoutPassword->setSpacing(0);
×
1295
}
×
1296

1297
/**
1298
 * @brief Copies the password of the selected file from the tree view to the
1299
 * clipboard.
1300
 * @example
1301
 * MainWindow::copyPasswordFromTreeview();
1302
 *
1303
 * @return void - This function does not return a value.
1304
 */
1305
void MainWindow::copyPasswordFromTreeview() {
×
1306
  QFileInfo fileOrFolder =
1307
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
1308

1309
  if (fileOrFolder.isFile()) {
×
1310
    QString file = getFile(ui->treeView->currentIndex(), true);
×
1311
    // Disconnect any previous connection to avoid accumulation
1312
    disconnect(QtPassSettings::getPass(), &Pass::finishedShow, this,
×
1313
               &MainWindow::passwordFromFileToClipboard);
1314
    connect(QtPassSettings::getPass(), &Pass::finishedShow, this,
×
1315
            &MainWindow::passwordFromFileToClipboard);
×
1316
    QtPassSettings::getPass()->Show(file);
×
1317
  }
1318
}
×
1319

1320
void MainWindow::passwordFromFileToClipboard(const QString &text) {
×
1321
  QStringList tokens = text.split('\n');
×
1322
  m_qtPass->copyTextToClipboard(tokens[0]);
×
1323
}
×
1324

1325
/**
1326
 * @brief MainWindow::addToGridLayout add a field to the template grid
1327
 * @param position
1328
 * @param field
1329
 * @param value
1330
 */
1331
void MainWindow::addToGridLayout(int position, const QString &field,
×
1332
                                 const QString &value) {
1333
  QString trimmedField = field.trimmed();
1334
  QString trimmedValue = value.trimmed();
1335

1336
  const QString buttonStyle =
1337
      "border-style: none; background: transparent; padding: 0; margin: 0; "
1338
      "icon-size: 16px; color: inherit;";
×
1339

1340
  // Combine the Copy button and the line edit in one widget
1341
  auto *frame = new QFrame();
×
1342
  QLayout *ly = new QHBoxLayout();
×
1343
  ly->setContentsMargins(5, 2, 2, 2);
×
1344
  ly->setSpacing(0);
×
1345
  frame->setLayout(ly);
×
1346
  if (QtPassSettings::getClipBoardType() != Enums::CLIPBOARD_NEVER) {
×
1347
    auto *fieldLabel = new QPushButtonWithClipboard(trimmedValue, this);
×
1348
    connect(fieldLabel, &QPushButtonWithClipboard::clicked, m_qtPass,
×
1349
            &QtPass::copyTextToClipboard);
×
1350

1351
    fieldLabel->setStyleSheet(buttonStyle);
×
1352
    frame->layout()->addWidget(fieldLabel);
×
1353
  }
1354

1355
  if (QtPassSettings::isUseQrencode()) {
×
1356
    auto *qrbutton = new QPushButtonAsQRCode(trimmedValue, this);
×
1357
    connect(qrbutton, &QPushButtonAsQRCode::clicked, m_qtPass,
×
1358
            &QtPass::showTextAsQRCode);
×
1359
    qrbutton->setStyleSheet(buttonStyle);
×
1360
    frame->layout()->addWidget(qrbutton);
×
1361
  }
1362

1363
  // set the echo mode to password, if the field is "password"
1364
  const QString lineStyle =
1365
      QtPassSettings::isUseMonospace()
×
1366
          ? "border-style: none; background: transparent; font-family: "
1367
            "monospace;"
1368
          : "border-style: none; background: transparent;";
×
1369

1370
  if (QtPassSettings::isHidePassword() && trimmedField == tr("Password")) {
×
1371
    auto *line = new QLineEdit();
×
1372
    line->setObjectName(trimmedField);
×
1373
    line->setText(trimmedValue);
×
1374
    line->setReadOnly(true);
×
1375
    line->setStyleSheet(lineStyle);
×
1376
    line->setContentsMargins(0, 0, 0, 0);
×
1377
    line->setEchoMode(QLineEdit::Password);
×
1378
    auto *showButton = new QPushButtonShowPassword(line, this);
×
1379
    showButton->setStyleSheet(buttonStyle);
×
1380
    showButton->setContentsMargins(0, 0, 0, 0);
×
1381
    frame->layout()->addWidget(showButton);
×
1382
    frame->layout()->addWidget(line);
×
1383
  } else {
1384
    auto *line = new QTextBrowser();
×
1385
    line->setOpenExternalLinks(true);
×
1386
    line->setOpenLinks(true);
×
1387
    line->setMaximumHeight(26);
×
1388
    line->setMinimumHeight(26);
×
1389
    line->setSizePolicy(
×
1390
        QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum));
1391
    line->setObjectName(trimmedField);
×
1392
    trimmedValue.replace(Util::protocolRegex(), R"(<a href="\1">\1</a>)");
×
1393
    line->setText(trimmedValue);
×
1394
    line->setReadOnly(true);
×
1395
    line->setStyleSheet(lineStyle);
×
1396
    line->setContentsMargins(0, 0, 0, 0);
×
1397
    frame->layout()->addWidget(line);
×
1398
  }
1399

1400
  frame->setStyleSheet(
×
1401
      ".QFrame{border: 1px solid lightgrey; border-radius: 5px;}");
1402

1403
  // set into the layout
1404
  ui->gridLayout->addWidget(new QLabel(trimmedField), position, 0);
×
1405
  ui->gridLayout->addWidget(frame, position, 1);
×
1406
}
×
1407

1408
/**
1409
 * @brief Displays message in status bar
1410
 *
1411
 * @param msg     text to be displayed
1412
 * @param timeout time for which msg shall be visible
1413
 */
1414
void MainWindow::showStatusMessage(const QString &msg, int timeout) {
×
1415
  ui->statusBar->showMessage(msg, timeout);
×
1416
}
×
1417

1418
/**
1419
 * @brief MainWindow::reencryptPath re-encrypt all passwords in a directory
1420
 * @param dir Directory path to re-encrypt
1421
 */
1422
void MainWindow::reencryptPath(const QString &dir) {
×
1423
  QDir checkDir(dir);
×
1424
  if (!checkDir.exists()) {
×
1425
    QMessageBox::critical(this, tr("Error"),
×
1426
                          tr("Directory does not exist: %1").arg(dir));
×
1427
    return;
×
1428
  }
1429

1430
  int ret = QMessageBox::question(
×
1431
      this, tr("Re-encrypt passwords"),
×
1432
      tr("Re-encrypt all passwords in %1?\n\n"
×
1433
         "This will re-encrypt ALL password files in this folder "
1434
         "using the current recipients defined in .gpg-id.\n\n"
1435
         "This may rewrite many files and cannot be undone easily.\n\n"
1436
         "Continue?")
1437
          .arg(QDir(dir).dirName()),
×
1438
      QMessageBox::Yes | QMessageBox::No);
1439

1440
  if (ret != QMessageBox::Yes)
×
1441
    return;
1442

1443
  // Prevent double execution - use same method as startReencryptPath
1444
  setUiElementsEnabled(false);
×
1445
  ui->treeView->setDisabled(true);
×
1446

1447
  QtPassSettings::getImitatePass()->reencryptPath(
×
1448
      QDir::cleanPath(QDir(dir).absolutePath()));
×
1449
}
×
1450

1451
/**
1452
 * @brief MainWindow::startReencryptPath disable ui elements and treeview
1453
 */
1454
void MainWindow::startReencryptPath() {
×
1455
  setUiElementsEnabled(false);
×
1456
  ui->treeView->setDisabled(true);
×
1457
}
×
1458

1459
/**
1460
 * @brief MainWindow::endReencryptPath re-enable ui elements
1461
 */
1462
void MainWindow::endReencryptPath() { setUiElementsEnabled(true); }
×
1463

1464
void MainWindow::updateGitButtonVisibility() {
×
1465
  if (!QtPassSettings::isUseGit() ||
×
1466
      (QtPassSettings::getGitExecutable().isEmpty() &&
×
1467
       QtPassSettings::getPassExecutable().isEmpty())) {
×
1468
    enableGitButtons(false);
×
1469
  } else {
1470
    enableGitButtons(true);
×
1471
  }
1472
}
×
1473

1474
void MainWindow::updateOtpButtonVisibility() {
×
1475
#if defined(Q_OS_WIN) || defined(__APPLE__)
1476
  ui->actionOtp->setVisible(false);
1477
#endif
1478
  if (!QtPassSettings::isUseOtp()) {
×
1479
    ui->actionOtp->setEnabled(false);
×
1480
  } else {
1481
    ui->actionOtp->setEnabled(true);
×
1482
  }
1483
}
×
1484

1485
void MainWindow::enableGitButtons(const bool &state) {
×
1486
  // Following GNOME guidelines is preferable disable buttons instead of hide
1487
  ui->actionPush->setEnabled(state);
×
1488
  ui->actionUpdate->setEnabled(state);
×
1489
}
×
1490

1491
/**
1492
 * @brief MainWindow::critical critical message popup wrapper.
1493
 * @param title
1494
 * @param msg
1495
 */
1496
void MainWindow::critical(const QString &title, const QString &msg) {
×
1497
  QMessageBox::critical(this, title, msg);
×
1498
}
×
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