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

IJHack / QtPass / 24593019107

18 Apr 2026 12:52AM UTC coverage: 22.91% (+1.0%) from 21.908%
24593019107

Pull #1037

github

web-flow
Merge 1732d6c55 into 79d758a1a
Pull Request #1037: feat: implement pass grep content search (#109)

72 of 143 new or added lines in 5 files covered. (50.35%)

198 existing lines in 4 files now uncovered.

1296 of 5657 relevant lines covered (22.91%)

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

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

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

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

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

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

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

453
  // first clear the current view:
454
  clearTemplateWidgets();
×
455

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

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

476
    output = fileContent.getRemainingDataForDisplay();
×
477
  }
478

479
  if (QtPassSettings::isUseAutoclearPanel()) {
×
480
    clearPanelTimer.start();
×
481
  }
482

483
  emit passShowHandlerFinished(output);
×
484
  setUiElementsEnabled(true);
×
485
}
×
486

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

851
  QtPassSettings::getPass()->Remove(file, isDir);
×
852
}
×
853

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

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

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

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

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

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

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

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

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

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

985
  ui->lineEdit->clear();
×
986

987
  QtPassSettings::setProfile(name);
×
988

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

995
  QtPassSettings::getPass()->updateEnv();
×
996

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

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

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

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

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

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

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

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

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

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

1111
  ui->treeView->setCurrentIndex(index);
×
1112

1113
  QPoint globalPos = ui->treeView->viewport()->mapToGlobal(pos);
×
1114

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

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

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

1166
  contextMenu->exec(globalPos);
×
1167
  delete contextMenu;
×
1168
}
×
1169

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1344
    fieldLabel->setStyleSheet(buttonStyle);
×
1345
    frame->layout()->addWidget(fieldLabel);
×
1346
  }
1347

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

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

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

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

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

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

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

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

1433
  if (ret != QMessageBox::Yes)
×
1434
    return;
1435

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

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

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

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

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

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

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

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