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

IJHack / QtPass / 24607260560

18 Apr 2026 02:56PM UTC coverage: 22.902% (+1.0%) from 21.908%
24607260560

Pull #1037

github

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

72 of 145 new or added lines in 5 files covered. (49.66%)

225 existing lines in 6 files now uncovered.

1296 of 5659 relevant lines covered (22.9%)

8.61 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
    ui->lineEdit->clear();
×
UNCOV
382
  bool cleared = ui->treeView->currentIndex().flags() == Qt::NoItemFlags;
×
383
  currentDir =
384
      Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel);
×
385
  // Clear any previously cached clipped text before showing new password
386
  m_qtPass->clearClippedText();
×
387
  QString file = getFile(index, true);
×
388
  ui->passwordName->setText(getFile(index, true));
×
389
  if (!file.isEmpty() && !cleared) {
×
390
    QtPassSettings::getPass()->Show(file);
×
391
  } else {
392
    clearPanel(false);
×
393
    ui->actionEdit->setEnabled(false);
×
394
    ui->actionDelete->setEnabled(true);
×
395
  }
396
}
×
397

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

573
  if (QtPassSettings::isAlwaysOnTop()) {
×
574
    Qt::WindowFlags flags = windowFlags();
575
    setWindowFlags(flags | Qt::WindowStaysOnTopHint);
×
576
    show();
×
577
  }
578

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

590
/**
591
 * @brief MainWindow::on_configButton_clicked run Mainwindow::config
592
 */
593
void MainWindow::onConfig() { config(); }
×
594

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

612
/**
613
 * @brief MainWindow::onTimeoutSearch Fired when search is finished or too much
614
 * time from two keypresses is elapsed
615
 */
616
void MainWindow::onTimeoutSearch() {
×
617
  QString query = ui->lineEdit->text();
×
618

619
  if (query.isEmpty()) {
×
620
    ui->treeView->collapseAll();
×
621
    deselect();
×
622
  }
623

624
  query.replace(QStringLiteral(" "), ".*");
×
625
  QRegularExpression regExp(query, QRegularExpression::CaseInsensitiveOption);
×
626
  proxyModel.setFilterRegularExpression(regExp);
×
627
  ui->treeView->setRootIndex(proxyModel.mapFromSource(
×
628
      model.setRootPath(QtPassSettings::getPassStore())));
×
629

630
  if (proxyModel.rowCount() > 0 && !query.isEmpty()) {
×
631
    selectFirstFile();
×
632
  } else {
633
    ui->actionEdit->setEnabled(false);
×
634
    ui->actionDelete->setEnabled(false);
×
635
  }
636
}
×
637

638
/**
639
 * @brief MainWindow::on_lineEdit_returnPressed get searching
640
 *
641
 * Select the first possible file in the tree
642
 */
643
void MainWindow::on_lineEdit_returnPressed() {
×
644
#ifdef QT_DEBUG
645
  dbg() << "on_lineEdit_returnPressed" << proxyModel.rowCount();
646
#endif
647

NEW
648
  if (m_grepMode) {
×
NEW
649
    const QString query = ui->lineEdit->text().trimmed();
×
NEW
650
    if (!query.isEmpty())
×
NEW
651
      QtPassSettings::getPass()->Grep(query, ui->grepCaseButton->isChecked());
×
652
    return;
653
  }
654

655
  if (proxyModel.rowCount() > 0) {
×
656
    selectFirstFile();
×
657
    on_treeView_clicked(ui->treeView->currentIndex());
×
658
  }
659
}
660

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

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

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

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

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

767
/**
768
 * @brief MainWindow::setPassword open passworddialog
769
 * @param file which pgp file
770
 * @param isNew insert (not update)
771
 */
772
void MainWindow::setPassword(const QString &file, bool isNew) {
×
773
  PasswordDialog d(file, isNew, this);
×
774

775
  if (!d.exec()) {
×
776
    ui->treeView->setFocus();
×
777
  }
778
}
×
779

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

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

815
  QFileInfo fileOrFolder =
816
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
817
  QString file = "";
×
818
  bool isDir = false;
819

820
  if (fileOrFolder.isFile()) {
×
821
    file = getFile(ui->treeView->currentIndex(), true);
×
822
  } else {
823
    file = Util::getDir(ui->treeView->currentIndex(), true, model, proxyModel);
×
824
    isDir = true;
825
  }
826

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

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

853
  QtPassSettings::getPass()->Remove(file, isDir);
×
854
}
×
855

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

871
/**
872
 * @brief MainWindow::onEdit try and edit (selected) password.
873
 */
874
void MainWindow::onEdit() {
×
875
  QString file = getFile(ui->treeView->currentIndex(), true);
×
876
  editPassword(file);
×
877
}
×
878

879
/**
880
 * @brief MainWindow::userDialog see MainWindow::onUsers()
881
 * @param dir folder to edit users for.
882
 */
883
void MainWindow::userDialog(const QString &dir) {
×
884
  if (!dir.isEmpty()) {
×
885
    currentDir = dir;
×
886
  }
887
  onUsers();
×
888
}
×
889

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

901
  UsersDialog d(dir, this);
×
902
  if (!d.exec()) {
×
903
    ui->treeView->setFocus();
×
904
  }
905
}
×
906

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

923
/**
924
 * @brief MainWindow::generateKeyPair internal gpg keypair generator . .
925
 * @param batch
926
 * @param keygenWindow
927
 */
928
void MainWindow::generateKeyPair(const QString &batch, QDialog *keygenWindow) {
×
929
  keygen = keygenWindow;
×
930
  emit generateGPGKeyPair(batch);
×
931
}
×
932

933
/**
934
 * @brief MainWindow::updateProfileBox update the list of profiles, optionally
935
 * select a more appropriate one to view too
936
 */
937
void MainWindow::updateProfileBox() {
×
938
  QHash<QString, QHash<QString, QString>> profiles =
939
      QtPassSettings::getProfiles();
×
940

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

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

987
  ui->lineEdit->clear();
×
988

989
  QtPassSettings::setProfile(name);
×
990

991
  QtPassSettings::setPassStore(
×
992
      QtPassSettings::getProfiles().value(name).value("path"));
×
993
  QtPassSettings::setPassSigningKey(
×
994
      QtPassSettings::getProfiles().value(name).value("signingKey"));
×
995
  ui->statusBar->showMessage(tr("Profile changed to %1").arg(name), 2000);
×
996

997
  QtPassSettings::getPass()->updateEnv();
×
998

999
  const QString passStore = QtPassSettings::getPassStore();
×
1000
  proxyModel.setStore(passStore);
×
1001
  ui->treeView->setRootIndex(
×
1002
      proxyModel.mapFromSource(model.setRootPath(passStore)));
×
1003
  deselect();
×
1004
  ui->treeView->setCurrentIndex(QModelIndex());
×
1005
}
1006

1007
/**
1008
 * @brief MainWindow::initTrayIcon show a nice tray icon on systems that
1009
 * support
1010
 * it
1011
 */
1012
void MainWindow::initTrayIcon() {
×
1013
  this->tray = new TrayIcon(this);
×
1014
  // Setup tray icon
1015

1016
  if (tray == nullptr) {
1017
#ifdef QT_DEBUG
1018
    dbg() << "Allocating tray icon failed.";
1019
#endif
1020
  }
1021

1022
  if (!tray->getIsAllocated()) {
×
1023
    destroyTrayIcon();
×
1024
  }
1025
}
×
1026

1027
/**
1028
 * @brief MainWindow::destroyTrayIcon remove that pesky tray icon
1029
 */
1030
void MainWindow::destroyTrayIcon() {
×
1031
  delete this->tray;
×
1032
  tray = nullptr;
×
1033
}
×
1034

1035
/**
1036
 * @brief MainWindow::closeEvent hide or quit
1037
 * @param event
1038
 */
1039
void MainWindow::closeEvent(QCloseEvent *event) {
×
1040
  if (QtPassSettings::isHideOnClose()) {
×
1041
    this->hide();
×
1042
    event->ignore();
1043
  } else {
1044
    m_qtPass->clearClipboard();
×
1045

1046
    QtPassSettings::setGeometry(saveGeometry());
×
1047
    QtPassSettings::setSavestate(saveState());
×
1048
    QtPassSettings::setMaximized(isMaximized());
×
1049
    if (!isMaximized()) {
×
1050
      QtPassSettings::setPos(pos());
×
1051
      QtPassSettings::setSize(size());
×
1052
    }
1053
    event->accept();
1054
  }
1055
}
×
1056

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

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

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

1113
  ui->treeView->setCurrentIndex(index);
×
1114

1115
  QPoint globalPos = ui->treeView->viewport()->mapToGlobal(pos);
×
1116

1117
  QFileInfo fileOrFolder =
1118
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
1119

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

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

1168
  contextMenu->exec(globalPos);
×
1169
  delete contextMenu;
×
1170
}
×
1171

1172
/**
1173
 * @brief MainWindow::openFolder open the folder in the default file manager
1174
 */
1175
void MainWindow::openFolder() {
×
1176
  QString dir =
1177
      Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel);
×
1178

1179
  QString path = QDir::toNativeSeparators(dir);
×
1180
  QDesktopServices::openUrl(QUrl::fromLocalFile(path));
×
1181
}
×
1182

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

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

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

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

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

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

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

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

1315
void MainWindow::passwordFromFileToClipboard(const QString &text) {
×
1316
  QStringList tokens = text.split('\n');
×
1317
  m_qtPass->copyTextToClipboard(tokens[0]);
×
1318
}
×
1319

1320
/**
1321
 * @brief MainWindow::addToGridLayout add a field to the template grid
1322
 * @param position
1323
 * @param field
1324
 * @param value
1325
 */
1326
void MainWindow::addToGridLayout(int position, const QString &field,
×
1327
                                 const QString &value) {
1328
  QString trimmedField = field.trimmed();
1329
  QString trimmedValue = value.trimmed();
1330

1331
  const QString buttonStyle =
1332
      "border-style: none; background: transparent; padding: 0; margin: 0; "
1333
      "icon-size: 16px; color: inherit;";
×
1334

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

1346
    fieldLabel->setStyleSheet(buttonStyle);
×
1347
    frame->layout()->addWidget(fieldLabel);
×
1348
  }
1349

1350
  if (QtPassSettings::isUseQrencode()) {
×
1351
    auto *qrbutton = new QPushButtonAsQRCode(trimmedValue, this);
×
1352
    connect(qrbutton, &QPushButtonAsQRCode::clicked, m_qtPass,
×
1353
            &QtPass::showTextAsQRCode);
×
1354
    qrbutton->setStyleSheet(buttonStyle);
×
1355
    frame->layout()->addWidget(qrbutton);
×
1356
  }
1357

1358
  // set the echo mode to password, if the field is "password"
1359
  const QString lineStyle =
1360
      QtPassSettings::isUseMonospace()
×
1361
          ? "border-style: none; background: transparent; font-family: "
1362
            "monospace;"
1363
          : "border-style: none; background: transparent;";
×
1364

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

1395
  frame->setStyleSheet(
×
1396
      ".QFrame{border: 1px solid lightgrey; border-radius: 5px;}");
1397

1398
  // set into the layout
1399
  ui->gridLayout->addWidget(new QLabel(trimmedField), position, 0);
×
1400
  ui->gridLayout->addWidget(frame, position, 1);
×
1401
}
×
1402

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

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

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

1435
  if (ret != QMessageBox::Yes)
×
1436
    return;
1437

1438
  // Prevent double execution - use same method as startReencryptPath
1439
  setUiElementsEnabled(false);
×
1440
  ui->treeView->setDisabled(true);
×
1441

1442
  QtPassSettings::getImitatePass()->reencryptPath(
×
1443
      QDir::cleanPath(QDir(dir).absolutePath()));
×
1444
}
×
1445

1446
/**
1447
 * @brief MainWindow::startReencryptPath disable ui elements and treeview
1448
 */
1449
void MainWindow::startReencryptPath() {
×
1450
  setUiElementsEnabled(false);
×
1451
  ui->treeView->setDisabled(true);
×
1452
}
×
1453

1454
/**
1455
 * @brief MainWindow::endReencryptPath re-enable ui elements
1456
 */
1457
void MainWindow::endReencryptPath() { setUiElementsEnabled(true); }
×
1458

1459
void MainWindow::updateGitButtonVisibility() {
×
1460
  if (!QtPassSettings::isUseGit() ||
×
1461
      (QtPassSettings::getGitExecutable().isEmpty() &&
×
1462
       QtPassSettings::getPassExecutable().isEmpty())) {
×
1463
    enableGitButtons(false);
×
1464
  } else {
1465
    enableGitButtons(true);
×
1466
  }
1467
}
×
1468

1469
void MainWindow::updateOtpButtonVisibility() {
×
1470
#if defined(Q_OS_WIN) || defined(__APPLE__)
1471
  ui->actionOtp->setVisible(false);
1472
#endif
1473
  if (!QtPassSettings::isUseOtp()) {
×
1474
    ui->actionOtp->setEnabled(false);
×
1475
  } else {
1476
    ui->actionOtp->setEnabled(true);
×
1477
  }
1478
}
×
1479

1480
void MainWindow::enableGitButtons(const bool &state) {
×
1481
  // Following GNOME guidelines is preferable disable buttons instead of hide
1482
  ui->actionPush->setEnabled(state);
×
1483
  ui->actionUpdate->setEnabled(state);
×
1484
}
×
1485

1486
/**
1487
 * @brief MainWindow::critical critical message popup wrapper.
1488
 * @param title
1489
 * @param msg
1490
 */
1491
void MainWindow::critical(const QString &title, const QString &msg) {
×
1492
  QMessageBox::critical(this, title, msg);
×
1493
}
×
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