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

IJHack / QtPass / 24886502223

24 Apr 2026 11:11AM UTC coverage: 26.828%. First build
24886502223

Pull #1150

github

web-flow
Merge a10a91e52 into 6d61ab3d3
Pull Request #1150: fix: address Copilot review findings

12 of 20 new or added lines in 3 files covered. (60.0%)

1640 of 6113 relevant lines covered (26.83%)

28.94 hits per line

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

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

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

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

36
/**
37
 * @brief MainWindow::MainWindow handles all of the main functionality and also
38
 * the main window.
39
 * @param searchText for searching from cli
40
 * @param parent pointer
41
 */
42
MainWindow::MainWindow(const QString &searchText, QWidget *parent)
×
NEW
43
    : QMainWindow(parent), ui(new Ui::MainWindow) {
×
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
  updateGrepButtonVisibility();
×
124

125
  setUiElementsEnabled(true);
×
126

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

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

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

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

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

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

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

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

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

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

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

214
void MainWindow::cleanKeygenDialog() {
×
NEW
215
  if (this->keygenDialog != nullptr) {
×
NEW
216
    this->keygenDialog->close();
×
217
  }
NEW
218
  this->keygenDialog = nullptr;
×
219
}
×
220

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

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

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

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

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

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

299
  if (m_qtPass->isFreshStart()) {
×
NEW
300
    d->wizard(); // run initial setup wizard for first-time configuration
×
301
  }
302
  if (d->exec()) {
×
303
    if (d->result() == QDialog::Accepted) {
×
304
      applyTextBrowserSettings();
×
305
      applyWindowFlagsSettings();
×
306

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

515
/**
516
 * @brief MainWindow::clearPanel hide the information from shoulder surfers
517
 */
518
void MainWindow::clearPanel(bool notify) {
×
519
  while (ui->gridLayout->count() > 0) {
×
520
    QLayoutItem *item = ui->gridLayout->takeAt(0);
×
521
    delete item->widget();
×
522
    delete item;
×
523
  }
524
  const bool grepWasVisible = ui->grepResultsList->isVisible();
×
525
  ui->grepResultsList->clear();
×
526
  if (grepWasVisible) {
×
527
    ui->grepResultsList->setVisible(false);
×
528
    ui->treeView->setVisible(true);
×
529
    if (m_grepMode) {
×
530
      m_grepMode = false;
×
531
      ui->grepButton->blockSignals(true);
×
532
      ui->grepButton->setChecked(false);
×
533
      ui->grepButton->blockSignals(false);
×
534
      ui->lineEdit->blockSignals(true);
×
535
      ui->lineEdit->clear();
×
536
      ui->lineEdit->blockSignals(false);
×
537
      ui->lineEdit->setPlaceholderText(tr("Search Password"));
×
538
    }
539
  }
540
  if (notify) {
×
541
    QString output = "***" + tr("Password and Content hidden") + "***";
×
542
    ui->textBrowser->setHtml(output);
×
543
  } else {
544
    ui->textBrowser->setHtml("");
×
545
  }
546
}
×
547

548
/**
549
 * @brief MainWindow::setUiElementsEnabled enable or disable the relevant UI
550
 * elements
551
 * @param state
552
 */
553
void MainWindow::setUiElementsEnabled(bool state) {
×
554
  ui->treeView->setEnabled(state);
×
555
  ui->lineEdit->setEnabled(state);
×
556
  ui->lineEdit->installEventFilter(this);
×
557
  ui->actionAddPassword->setEnabled(state);
×
558
  ui->actionAddFolder->setEnabled(state);
×
559
  ui->actionUsers->setEnabled(state);
×
560
  ui->actionConfig->setEnabled(state);
×
561
  // is a file selected?
562
  state &= ui->treeView->currentIndex().isValid();
×
563
  ui->actionDelete->setEnabled(state);
×
564
  ui->actionEdit->setEnabled(state);
×
565
  updateGitButtonVisibility();
×
566
  updateOtpButtonVisibility();
×
567
}
×
568

569
/**
570
 * @brief Restores the main window geometry, state, position, size, and
571
 * tray/icon settings from saved application settings.
572
 * @example
573
 * MainWindow window;
574
 * window.restoreWindow();
575
 *
576
 * @return void - This function does not return a value.
577
 */
578
void MainWindow::restoreWindow() {
×
579
  QByteArray geometry = QtPassSettings::getGeometry(saveGeometry());
×
580
  restoreGeometry(geometry);
×
581
  QByteArray savestate = QtPassSettings::getSavestate(saveState());
×
582
  restoreState(savestate);
×
583
  QPoint position = QtPassSettings::getPos(pos());
×
584
  move(position);
×
585
  QSize newSize = QtPassSettings::getSize(size());
×
586
  resize(newSize);
×
587
  if (QtPassSettings::isMaximized(isMaximized())) {
×
588
    showMaximized();
×
589
  }
590

591
  if (QtPassSettings::isAlwaysOnTop()) {
×
592
    Qt::WindowFlags flags = windowFlags();
593
    setWindowFlags(flags | Qt::WindowStaysOnTopHint);
×
594
    show();
×
595
  }
596

597
  if (QtPassSettings::isUseTrayIcon() && tray == nullptr) {
×
598
    initTrayIcon();
×
599
    if (QtPassSettings::isStartMinimized()) {
×
600
      // since we are still in constructor, can't directly hide
601
      QTimer::singleShot(10, this, SLOT(hide()));
×
602
    }
603
  } else if (!QtPassSettings::isUseTrayIcon() && tray != nullptr) {
×
604
    destroyTrayIcon();
×
605
  }
606
}
×
607

608
/**
609
 * @brief MainWindow::on_configButton_clicked run Mainwindow::config
610
 */
611
void MainWindow::onConfig() { config(); }
×
612

613
/**
614
 * @brief Executes when the string in the search box changes, collapses the
615
 * TreeView
616
 * @param arg1
617
 */
618
void MainWindow::on_lineEdit_textChanged(const QString &arg1) {
×
619
  if (m_grepMode)
×
620
    return;
621
  ui->statusBar->showMessage(tr("Looking for: %1").arg(arg1), 1000);
×
622
  ui->treeView->expandAll();
×
623
  clearPanel(false);
×
624
  ui->passwordName->setText("");
×
625
  ui->actionEdit->setEnabled(false);
×
626
  ui->actionDelete->setEnabled(false);
×
627
  searchTimer.start();
×
628
}
629

630
/**
631
 * @brief MainWindow::onTimeoutSearch Fired when search is finished or too much
632
 * time from two keypresses is elapsed
633
 */
634
void MainWindow::onTimeoutSearch() {
×
635
  QString query = ui->lineEdit->text();
×
636

637
  if (query.isEmpty()) {
×
638
    ui->treeView->collapseAll();
×
639
    deselect();
×
640
  }
641

642
  query.replace(QStringLiteral(" "), ".*");
×
643
  QRegularExpression regExp(query, QRegularExpression::CaseInsensitiveOption);
×
644
  proxyModel.setFilterRegularExpression(regExp);
×
645
  ui->treeView->setRootIndex(proxyModel.mapFromSource(
×
646
      model.setRootPath(QtPassSettings::getPassStore())));
×
647

648
  if (proxyModel.rowCount() > 0 && !query.isEmpty()) {
×
649
    selectFirstFile();
×
650
  } else {
651
    ui->actionEdit->setEnabled(false);
×
652
    ui->actionDelete->setEnabled(false);
×
653
  }
654
}
×
655

656
/**
657
 * @brief MainWindow::on_lineEdit_returnPressed get searching
658
 *
659
 * Select the first possible file in the tree
660
 */
661
void MainWindow::on_lineEdit_returnPressed() {
×
662
#ifdef QT_DEBUG
663
  dbg() << "on_lineEdit_returnPressed" << proxyModel.rowCount();
664
#endif
665

666
  if (m_grepMode) {
×
667
    const QString query = ui->lineEdit->text();
×
668
    if (!query.isEmpty()) {
×
669
      m_grepCancelled = false;
×
670
      ui->grepResultsList->clear();
×
671
      ui->statusBar->showMessage(tr("Searching…"));
×
672
      if (!m_grepBusy) {
×
673
        m_grepBusy = true;
×
674
        QApplication::setOverrideCursor(Qt::WaitCursor);
×
675
      }
676
      QtPassSettings::getPass()->Grep(query, ui->grepCaseButton->isChecked());
×
677
    } else {
678
      m_grepCancelled = true;
×
679
      if (m_grepBusy) {
×
680
        m_grepBusy = false;
×
681
        QApplication::restoreOverrideCursor();
×
682
      }
683
      ui->grepResultsList->clear();
×
684
      ui->grepResultsList->setVisible(false);
×
685
      ui->treeView->setVisible(true);
×
686
    }
687
    return;
688
  }
689

690
  if (proxyModel.rowCount() > 0) {
×
691
    selectFirstFile();
×
692
    on_treeView_clicked(ui->treeView->currentIndex());
×
693
  }
694
}
695

696
/**
697
 * @brief Toggle grep (content search) mode.
698
 */
699
void MainWindow::on_grepButton_toggled(bool checked) {
×
700
  m_grepMode = checked;
×
701
  if (checked) {
×
702
    ui->lineEdit->setPlaceholderText(tr("Search content (regex)"));
×
703
    ui->lineEdit->clear();
×
704
    searchTimer.stop();
×
705
    proxyModel.setFilterRegularExpression(QRegularExpression());
×
706
    ui->treeView->setRootIndex(proxyModel.mapFromSource(
×
707
        model.setRootPath(QtPassSettings::getPassStore())));
×
708
    ui->grepResultsList->setVisible(false);
×
709
    // Keep treeView visible until results arrive
710
  } else {
711
    if (m_grepBusy) {
×
712
      m_grepBusy = false;
×
713
      m_grepCancelled = true;
×
714
      QApplication::restoreOverrideCursor();
×
715
    }
716
    searchTimer.stop();
×
717
    ui->lineEdit->blockSignals(true);
×
718
    ui->lineEdit->clear();
×
719
    ui->lineEdit->blockSignals(false);
×
720
    ui->lineEdit->setPlaceholderText(tr("Search Password"));
×
721
    ui->grepResultsList->clear();
×
722
    ui->grepResultsList->setVisible(false);
×
723
    ui->treeView->setVisible(true);
×
724
    proxyModel.setFilterRegularExpression(QRegularExpression());
×
725
    ui->treeView->setRootIndex(proxyModel.mapFromSource(
×
726
        model.setRootPath(QtPassSettings::getPassStore())));
×
727
  }
728
}
×
729

730
/**
731
 * @brief Display grep results in grepResultsList.
732
 */
733
void MainWindow::onGrepFinished(
×
734
    const QList<QPair<QString, QStringList>> &results) {
735
  if (m_grepBusy) {
×
736
    m_grepBusy = false;
×
737
    QApplication::restoreOverrideCursor();
×
738
  }
739
  if (m_grepCancelled) {
×
740
    m_grepCancelled = false;
×
741
    return;
×
742
  }
743
  setUiElementsEnabled(true);
×
744
  if (!m_grepMode)
×
745
    return;
746
  ui->grepResultsList->clear();
×
747
  if (results.isEmpty()) {
×
748
    ui->statusBar->showMessage(tr("No matches found."), 3000);
×
749
    ui->grepResultsList->setVisible(false);
×
750
    ui->treeView->setVisible(true);
×
751
    return;
×
752
  }
753
  const bool hideContent = QtPassSettings::isHideContent();
×
754
  int totalLines = 0;
755
  for (const auto &pair : results) {
×
756
    QTreeWidgetItem *entryItem = new QTreeWidgetItem(ui->grepResultsList);
×
757
    entryItem->setText(0, pair.first);
×
758
    entryItem->setData(0, Qt::UserRole, pair.first);
×
759
    for (const QString &line : pair.second) {
×
760
      QTreeWidgetItem *lineItem = new QTreeWidgetItem(entryItem);
×
761
      lineItem->setText(0, hideContent ? "***" + tr("Content hidden") + "***"
×
762
                                       : line);
763
      lineItem->setData(0, Qt::UserRole, pair.first);
×
764
      ++totalLines;
×
765
    }
766
  }
767
  ui->grepResultsList->expandAll();
×
768
  ui->treeView->setVisible(false);
×
769
  ui->grepResultsList->setVisible(true);
×
770
  ui->statusBar->showMessage(
×
771
      tr("Found %n match(es)", nullptr, totalLines) + " " +
×
772
          tr("in %n entr(ies).", nullptr, results.size()),
×
773
      3000);
774
  if (QtPassSettings::isUseAutoclearPanel())
×
775
    clearPanelTimer.start();
×
776
}
777

778
/**
779
 * @brief Navigate to the password entry when a grep result is clicked.
780
 */
781
void MainWindow::on_grepResultsList_itemClicked(QTreeWidgetItem *item,
×
782
                                                int /*column*/) {
783
  const QString entry = item->data(0, Qt::UserRole).toString();
×
784
  if (entry.isEmpty())
×
785
    return;
786
  const QString fullPath = QDir::cleanPath(
787
      QDir(QtPassSettings::getPassStore()).filePath(entry + ".gpg"));
×
788
  QModelIndex srcIndex = model.index(fullPath);
×
789
  if (!srcIndex.isValid())
790
    return;
791
  QModelIndex proxyIndex = proxyModel.mapFromSource(srcIndex);
×
792
  if (!proxyIndex.isValid())
793
    return;
794
  ui->treeView->setCurrentIndex(proxyIndex);
×
795
  on_treeView_clicked(proxyIndex);
×
796
  if (QtPassSettings::isHideContent() || QtPassSettings::isUseAutoclearPanel())
×
797
    ui->grepResultsList->clear();
×
798
  ui->grepResultsList->setVisible(false);
×
799
  ui->treeView->setVisible(true);
×
800
  ui->treeView->scrollTo(proxyIndex);
×
801
  ui->treeView->setFocus();
×
802
}
803

804
/**
805
 * @brief MainWindow::selectFirstFile select the first possible file in the
806
 * tree
807
 */
808
void MainWindow::selectFirstFile() {
×
809
  QModelIndex index = proxyModel.mapFromSource(
×
810
      model.setRootPath(QtPassSettings::getPassStore()));
×
811
  index = firstFile(index);
×
812
  ui->treeView->setCurrentIndex(index);
×
813
}
×
814

815
/**
816
 * @brief MainWindow::firstFile return location of first possible file
817
 * @param parentIndex
818
 * @return QModelIndex
819
 */
820
auto MainWindow::firstFile(QModelIndex parentIndex) -> QModelIndex {
×
821
  QModelIndex index = parentIndex;
×
822
  int numRows = proxyModel.rowCount(parentIndex);
×
823
  for (int row = 0; row < numRows; ++row) {
×
824
    index = proxyModel.index(row, 0, parentIndex);
×
825
    if (model.fileInfo(proxyModel.mapToSource(index)).isFile()) {
×
826
      return index;
×
827
    }
828
    if (proxyModel.hasChildren(index)) {
×
829
      return firstFile(index);
×
830
    }
831
  }
832
  return index;
×
833
}
834

835
/**
836
 * @brief MainWindow::setPassword open passworddialog
837
 * @param file which pgp file
838
 * @param isNew insert (not update)
839
 */
840
void MainWindow::setPassword(const QString &file, bool isNew) {
×
841
  PasswordDialog d(file, isNew, this);
×
842

843
  if (isNew) {
×
844
    QString storePath = QtPassSettings::getPassStore();
×
845
    QString folder =
846
        Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel);
×
847
    if (folder.isEmpty()) {
×
848
      folder = storePath;
×
849
    }
850
    QHash<QString, QStringList> templates = Util::readTemplates(storePath);
×
851
    if (!templates.isEmpty()) {
852
      QString defaultTemplate = Util::getFolderTemplate(folder, storePath);
×
853
      d.setAvailableTemplates(templates, defaultTemplate);
×
854
      new QShortcut(QKeySequence(Qt::CTRL | Qt::Key_T), &d,
×
855
                    [&d]() { d.cycleTemplate(); });
×
856
    }
857
  }
×
858

859
  if (!d.exec()) {
×
860
    ui->treeView->setFocus();
×
861
  }
862
}
×
863

864
/**
865
 * @brief MainWindow::addPassword add a new password by showing a
866
 * number of dialogs.
867
 */
868
void MainWindow::addPassword() {
×
869
  bool ok;
870
  QString dir =
871
      Util::getDir(ui->treeView->currentIndex(), true, model, proxyModel);
×
872
  QString file =
873
      QInputDialog::getText(this, tr("New file"),
×
874
                            tr("New password file: \n(Will be placed in %1 )")
×
875
                                .arg(QtPassSettings::getPassStore() +
×
876
                                     Util::getDir(ui->treeView->currentIndex(),
×
877
                                                  true, model, proxyModel)),
878
                            QLineEdit::Normal, "", &ok);
×
879
  if (!ok || file.isEmpty()) {
×
880
    return;
881
  }
882
  file = dir + file;
×
883
  setPassword(file);
×
884
}
885

886
/**
887
 * @brief MainWindow::onDelete remove password, if you are
888
 * sure.
889
 */
890
void MainWindow::onDelete() {
×
891
  QModelIndex currentIndex = ui->treeView->currentIndex();
×
892
  if (!currentIndex.isValid()) {
893
    // This fixes https://github.com/IJHack/QtPass/issues/556
894
    // Otherwise the entire password directory would be deleted if
895
    // nothing is selected in the tree view.
896
    return;
×
897
  }
898

899
  QFileInfo fileOrFolder =
900
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
901
  QString file = "";
×
902
  bool isDir = false;
903

904
  if (fileOrFolder.isFile()) {
×
905
    file = getFile(ui->treeView->currentIndex(), true);
×
906
  } else {
907
    file = Util::getDir(ui->treeView->currentIndex(), true, model, proxyModel);
×
908
    isDir = true;
909
  }
910

911
  QString dirMessage = tr(" and the whole content?");
912
  if (isDir) {
×
913
    QDirIterator it(model.rootPath() + QDir::separator() + file,
×
914
                    QDirIterator::Subdirectories);
×
915
    bool okDir = true;
916
    while (it.hasNext() && okDir) {
×
917
      it.next();
×
918
      if (QFileInfo(it.filePath()).isFile()) {
×
919
        if (QFileInfo(it.filePath()).suffix() != "gpg") {
×
920
          okDir = false;
921
          dirMessage = tr(" and the whole content? <br><strong>Attention: "
×
922
                          "there are unexpected files in the given folder, "
923
                          "check them before continue.</strong>");
924
        }
925
      }
926
    }
927
  }
×
928

929
  if (QMessageBox::question(
×
930
          this, isDir ? tr("Delete folder?") : tr("Delete password?"),
×
931
          tr("Are you sure you want to delete %1%2?")
×
932
              .arg(QDir::separator() + file, isDir ? dirMessage : "?"),
×
933
          QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) {
934
    return;
935
  }
936

937
  QtPassSettings::getPass()->Remove(file, isDir);
×
938
}
×
939

940
/**
941
 * @brief MainWindow::onOTP try and generate (selected) OTP code.
942
 */
943
void MainWindow::onOtp() {
×
944
  QString file = getFile(ui->treeView->currentIndex(), true);
×
945
  if (!file.isEmpty()) {
×
946
    if (QtPassSettings::isUseOtp()) {
×
947
      setUiElementsEnabled(false);
×
948
      QtPassSettings::getPass()->OtpGenerate(file);
×
949
    }
950
  } else {
951
    flashText(tr("No password selected for OTP generation"), true);
×
952
  }
953
}
×
954

955
/**
956
 * @brief MainWindow::onEdit try and edit (selected) password.
957
 */
958
void MainWindow::onEdit() {
×
959
  QString file = getFile(ui->treeView->currentIndex(), true);
×
960
  editPassword(file);
×
961
}
×
962

963
/**
964
 * @brief MainWindow::userDialog see MainWindow::onUsers()
965
 * @param dir folder to edit users for.
966
 */
967
void MainWindow::userDialog(const QString &dir) {
×
968
  if (!dir.isEmpty()) {
×
969
    currentDir = dir;
×
970
  }
971
  onUsers();
×
972
}
×
973

974
/**
975
 * @brief MainWindow::onUsers edit users for the current
976
 * folder,
977
 * gets lists and opens UserDialog.
978
 */
979
void MainWindow::onUsers() {
×
980
  QString dir =
981
      currentDir.isEmpty()
982
          ? Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel)
×
983
          : currentDir;
×
984

985
  UsersDialog d(dir, this);
×
986
  if (!d.exec()) {
×
987
    ui->treeView->setFocus();
×
988
  }
989
}
×
990

991
/**
992
 * @brief MainWindow::messageAvailable we have some text/message/search to do.
993
 * @param message
994
 */
995
void MainWindow::messageAvailable(const QString &message) {
×
996
  if (message.isEmpty()) {
×
997
    focusInput();
×
998
  } else {
999
    ui->treeView->expandAll();
×
1000
    ui->lineEdit->setText(message);
×
1001
    on_lineEdit_returnPressed();
×
1002
  }
1003
  show();
×
1004
  raise();
×
1005
}
×
1006

1007
/**
1008
 * @brief MainWindow::generateKeyPair internal gpg keypair generator . .
1009
 * @param batch
1010
 * @param keygenWindow
1011
 */
1012
void MainWindow::generateKeyPair(const QString &batch, QDialog *keygenWindow) {
×
NEW
1013
  keygenDialog = keygenWindow;
×
1014
  emit generateGPGKeyPair(batch);
×
1015
}
×
1016

1017
/**
1018
 * @brief MainWindow::updateProfileBox update the list of profiles, optionally
1019
 * select a more appropriate one to view too
1020
 */
1021
void MainWindow::updateProfileBox() {
×
1022
  QHash<QString, QHash<QString, QString>> profiles =
1023
      QtPassSettings::getProfiles();
×
1024

1025
  if (profiles.isEmpty()) {
1026
    ui->profileWidget->hide();
×
1027
  } else {
1028
    ui->profileWidget->show();
×
1029
    ui->profileBox->setEnabled(profiles.size() > 1);
×
1030
    ui->profileBox->clear();
×
1031
    QHashIterator<QString, QHash<QString, QString>> i(profiles);
×
1032
    while (i.hasNext()) {
×
1033
      i.next();
1034
      if (!i.key().isEmpty()) {
×
1035
        ui->profileBox->addItem(i.key());
×
1036
      }
1037
    }
1038
    ui->profileBox->model()->sort(0);
×
1039
  }
1040
  int index = ui->profileBox->findText(QtPassSettings::getProfile());
×
1041
  if (index != -1) { //  -1 for not found
×
1042
    ui->profileBox->setCurrentIndex(index);
×
1043
  }
1044
}
×
1045

1046
/**
1047
 * @brief MainWindow::on_profileBox_currentIndexChanged make sure we show the
1048
 * correct "profile"
1049
 * @param name
1050
 */
1051
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
1052
void MainWindow::on_profileBox_currentIndexChanged(QString name) {
1053
#else
1054
/**
1055
 * @brief Handles changes to the selected profile in the profile combo box.
1056
 * @details Ignores the event during a fresh start or when the selected profile
1057
 * matches the current profile. Otherwise, it clears the password field, updates
1058
 * the active profile and related settings, refreshes the environment, and
1059
 * resets the tree view and action states to reflect the newly selected profile.
1060
 *
1061
 * @param name - The newly selected profile name.
1062
 * @return void - This function does not return a value.
1063
 *
1064
 */
1065
void MainWindow::on_profileBox_currentTextChanged(const QString &name) {
×
1066
#endif
1067
  if (m_qtPass->isFreshStart() || name == QtPassSettings::getProfile()) {
×
1068
    return;
×
1069
  }
1070

1071
  ui->lineEdit->clear();
×
1072

1073
  QtPassSettings::setProfile(name);
×
1074

1075
  QtPassSettings::setPassStore(
×
1076
      QtPassSettings::getProfiles().value(name).value("path"));
×
1077
  QtPassSettings::setPassSigningKey(
×
1078
      QtPassSettings::getProfiles().value(name).value("signingKey"));
×
1079
  ui->statusBar->showMessage(tr("Profile changed to %1").arg(name), 2000);
×
1080

1081
  QtPassSettings::getPass()->updateEnv();
×
1082

1083
  const QString passStore = QtPassSettings::getPassStore();
×
1084
  proxyModel.setStore(passStore);
×
1085
  ui->treeView->setRootIndex(
×
1086
      proxyModel.mapFromSource(model.setRootPath(passStore)));
×
1087
  deselect();
×
1088
  ui->treeView->setCurrentIndex(QModelIndex());
×
1089
}
1090

1091
/**
1092
 * @brief MainWindow::initTrayIcon show a nice tray icon on systems that
1093
 * support
1094
 * it
1095
 */
1096
void MainWindow::initTrayIcon() {
×
1097
  this->tray = new TrayIcon(this);
×
1098
  // Setup tray icon
1099

1100
  if (tray == nullptr) {
1101
#ifdef QT_DEBUG
1102
    dbg() << "Allocating tray icon failed.";
1103
#endif
1104
    return;
1105
  }
1106

1107
  if (!tray->getIsAllocated()) {
×
1108
    destroyTrayIcon();
×
1109
  }
1110
}
1111

1112
/**
1113
 * @brief MainWindow::destroyTrayIcon remove that pesky tray icon
1114
 */
1115
void MainWindow::destroyTrayIcon() {
×
1116
  delete this->tray;
×
1117
  tray = nullptr;
×
1118
}
×
1119

1120
/**
1121
 * @brief MainWindow::closeEvent hide or quit
1122
 * @param event
1123
 */
1124
void MainWindow::closeEvent(QCloseEvent *event) {
×
1125
  if (QtPassSettings::isHideOnClose()) {
×
1126
    this->hide();
×
1127
    event->ignore();
1128
  } else {
1129
    m_qtPass->clearClipboard();
×
1130

1131
    QtPassSettings::setGeometry(saveGeometry());
×
1132
    QtPassSettings::setSavestate(saveState());
×
1133
    QtPassSettings::setMaximized(isMaximized());
×
1134
    if (!isMaximized()) {
×
1135
      QtPassSettings::setPos(pos());
×
1136
      QtPassSettings::setSize(size());
×
1137
    }
1138
    event->accept();
1139
  }
1140
}
×
1141

1142
/**
1143
 * @brief MainWindow::eventFilter filter out some events and focus the
1144
 * treeview
1145
 * @param obj
1146
 * @param event
1147
 * @return
1148
 */
1149
auto MainWindow::eventFilter(QObject *obj, QEvent *event) -> bool {
×
1150
  if (obj == ui->lineEdit && event->type() == QEvent::KeyPress) {
×
1151
    auto *key = dynamic_cast<QKeyEvent *>(event);
×
1152
    if (key != nullptr && key->key() == Qt::Key_Down) {
×
1153
      ui->treeView->setFocus();
×
1154
    }
1155
  }
1156
  return QObject::eventFilter(obj, event);
×
1157
}
1158

1159
/**
1160
 * @brief MainWindow::keyPressEvent did anyone press return, enter or escape?
1161
 * @param event
1162
 */
1163
void MainWindow::keyPressEvent(QKeyEvent *event) {
×
1164
  switch (event->key()) {
×
1165
  case Qt::Key_Delete:
×
1166
    onDelete();
×
1167
    break;
×
1168
  case Qt::Key_Return:
×
1169
  case Qt::Key_Enter:
1170
    if (proxyModel.rowCount() > 0) {
×
1171
      on_treeView_clicked(ui->treeView->currentIndex());
×
1172
    }
1173
    break;
1174
  case Qt::Key_Escape:
×
1175
    ui->lineEdit->clear();
×
1176
    break;
×
1177
  default:
1178
    break;
1179
  }
1180
}
×
1181

1182
/**
1183
 * @brief MainWindow::showContextMenu show us the (file or folder) context
1184
 * menu
1185
 * @param pos
1186
 */
1187
void MainWindow::showContextMenu(const QPoint &pos) {
×
1188
  QModelIndex index = ui->treeView->indexAt(pos);
×
1189
  bool selected = true;
1190
  if (!index.isValid()) {
1191
    ui->treeView->clearSelection();
×
1192
    ui->actionDelete->setEnabled(false);
×
1193
    ui->actionEdit->setEnabled(false);
×
1194
    currentDir = "";
×
1195
    selected = false;
1196
  }
1197

1198
  ui->treeView->setCurrentIndex(index);
×
1199

1200
  QPoint globalPos = ui->treeView->viewport()->mapToGlobal(pos);
×
1201

1202
  QFileInfo fileOrFolder =
1203
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
1204

1205
  QMenu contextMenu;
×
1206
  if (!selected || fileOrFolder.isDir()) {
×
1207
    QAction *openFolder =
1208
        contextMenu.addAction(tr("Open folder with file manager"));
×
1209
    QAction *addFolder = contextMenu.addAction(tr("Add folder"));
×
1210
    QAction *addPassword = contextMenu.addAction(tr("Add password"));
×
1211
    QAction *users = contextMenu.addAction(tr("Users"));
×
1212
    connect(openFolder, &QAction::triggered, this, &MainWindow::openFolder);
×
1213
    connect(addFolder, &QAction::triggered, this, &MainWindow::addFolder);
×
1214
    connect(addPassword, &QAction::triggered, this, &MainWindow::addPassword);
×
1215
    connect(users, &QAction::triggered, this, &MainWindow::onUsers);
×
1216
  } else if (fileOrFolder.isFile()) {
×
1217
    QAction *edit = contextMenu.addAction(tr("Edit"));
×
1218
    connect(edit, &QAction::triggered, this, &MainWindow::onEdit);
×
1219
  }
1220
  if (selected) {
×
1221
    contextMenu.addSeparator();
×
1222
    if (fileOrFolder.isDir()) {
×
1223
      QAction *renameFolder = contextMenu.addAction(tr("Rename folder"));
×
1224
      connect(renameFolder, &QAction::triggered, this,
×
1225
              &MainWindow::renameFolder);
×
1226
    } else if (fileOrFolder.isFile()) {
×
1227
      QAction *renamePassword = contextMenu.addAction(tr("Rename password"));
×
1228
      connect(renamePassword, &QAction::triggered, this,
×
1229
              &MainWindow::renamePassword);
×
1230
    }
1231
    QAction *deleteItem = contextMenu.addAction(tr("Delete"));
×
1232
    connect(deleteItem, &QAction::triggered, this, &MainWindow::onDelete);
×
1233
    if (fileOrFolder.isDir()) {
×
1234
      QString dirPath = QDir::cleanPath(
1235
          Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel));
×
1236

1237
      QMenu *shareMenu = new QMenu(tr("Share"), &contextMenu);
×
1238
      contextMenu.addMenu(shareMenu);
×
1239

1240
      QString gpgIdPath = Pass::getGpgIdPath(dirPath);
×
1241
      bool gpgIdExists = !gpgIdPath.isEmpty() && QFile(gpgIdPath).exists();
×
1242

1243
      QString exePath = QtPassSettings::isUsePass()
×
1244
                            ? QtPassSettings::getPassExecutable()
×
1245
                            : QtPassSettings::getGpgExecutable();
×
1246
      bool gpgAvailable = !exePath.isEmpty() && (exePath.startsWith("wsl ") ||
×
1247
                                                 QFile(exePath).exists());
×
1248

1249
      QAction *reencrypt = shareMenu->addAction(tr("Re-encrypt all passwords"));
×
1250
      reencrypt->setEnabled(gpgIdExists && gpgAvailable);
×
1251
      connect(reencrypt, &QAction::triggered, this,
×
1252
              [this, dirPath]() { reencryptPath(dirPath); });
×
1253

1254
      QAction *exportKey = shareMenu->addAction(tr("Export my public key..."));
×
1255
      exportKey->setEnabled(gpgAvailable);
×
1256
      connect(exportKey, &QAction::triggered, this,
×
1257
              &MainWindow::exportPublicKey);
×
1258

1259
      QAction *addRecipientAction =
1260
          shareMenu->addAction(tr("Add recipient..."));
×
1261
      addRecipientAction->setEnabled(gpgIdExists && gpgAvailable);
×
1262
      connect(addRecipientAction, &QAction::triggered, this,
×
1263
              [this, dirPath]() { addRecipient(dirPath); });
×
1264

1265
      QAction *shareHelp = shareMenu->addAction(tr("What is this?"));
×
1266
      connect(shareHelp, &QAction::triggered, this, &MainWindow::showShareHelp);
×
1267
    }
1268
  }
1269
  contextMenu.exec(globalPos);
×
1270
}
×
1271

1272
/**
1273
 * @brief MainWindow::showBrowserContextMenu show us the context menu in
1274
 * password window
1275
 * @param pos
1276
 */
1277
void MainWindow::showBrowserContextMenu(const QPoint &pos) {
×
1278
  QMenu *contextMenu = ui->textBrowser->createStandardContextMenu(pos);
×
1279
  QPoint globalPos = ui->textBrowser->viewport()->mapToGlobal(pos);
×
1280

1281
  contextMenu->exec(globalPos);
×
1282
  delete contextMenu;
×
1283
}
×
1284

1285
/**
1286
 * @brief MainWindow::openFolder open the folder in the default file manager
1287
 */
1288
void MainWindow::openFolder() {
×
1289
  QString dir =
1290
      Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel);
×
1291

1292
  QString path = QDir::toNativeSeparators(dir);
×
1293
  QDesktopServices::openUrl(QUrl::fromLocalFile(path));
×
1294
}
×
1295

1296
/**
1297
 * @brief MainWindow::addFolder add a new folder to store passwords in
1298
 */
1299
void MainWindow::addFolder() {
×
1300
  bool ok;
1301
  QString dir =
1302
      Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel);
×
1303
  QString newdir =
1304
      QInputDialog::getText(this, tr("New file"),
×
1305
                            tr("New Folder: \n(Will be placed in %1 )")
×
1306
                                .arg(QtPassSettings::getPassStore() +
×
1307
                                     Util::getDir(ui->treeView->currentIndex(),
×
1308
                                                  true, model, proxyModel)),
1309
                            QLineEdit::Normal, "", &ok);
×
1310
  if (!ok || newdir.isEmpty()) {
×
1311
    return;
1312
  }
1313
  newdir.prepend(dir);
1314
  if (!QDir().mkdir(newdir)) {
×
1315
    QMessageBox::warning(this, tr("Error"),
×
1316
                         tr("Failed to create folder: %1").arg(newdir));
×
1317
    return;
×
1318
  }
1319
  if (QtPassSettings::isAddGPGId(true)) {
×
1320
    QString gpgIdFile = newdir + "/.gpg-id";
×
1321
    QFile gpgId(gpgIdFile);
×
1322
    if (!gpgId.open(QIODevice::WriteOnly)) {
×
1323
      QMessageBox::warning(
×
1324
          this, tr("Error"),
×
1325
          tr("Failed to create .gpg-id file in: %1").arg(newdir));
×
1326
      return;
1327
    }
1328
    QList<UserInfo> users = QtPassSettings::getPass()->listKeys("", true);
×
1329
    for (const UserInfo &user : users) {
×
1330
      if (user.enabled) {
×
1331
        gpgId.write((user.key_id + "\n").toUtf8());
×
1332
      }
1333
    }
1334
    gpgId.close();
×
1335
  }
×
1336
}
1337

1338
/**
1339
 * @brief MainWindow::renameFolder rename an existing folder
1340
 */
1341
void MainWindow::renameFolder() {
×
1342
  bool ok;
1343
  QString srcDir = QDir::cleanPath(
1344
      Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel));
×
1345
  QString srcDirName = QDir(srcDir).dirName();
×
1346
  QString newName =
1347
      QInputDialog::getText(this, tr("Rename file"), tr("Rename Folder To: "),
×
1348
                            QLineEdit::Normal, srcDirName, &ok);
×
1349
  if (!ok || newName.isEmpty()) {
×
1350
    return;
1351
  }
1352
  QString destDir = srcDir;
1353
  destDir.replace(srcDir.lastIndexOf(srcDirName), srcDirName.length(), newName);
×
1354
  QtPassSettings::getPass()->Move(srcDir, destDir);
×
1355
}
1356

1357
/**
1358
 * @brief MainWindow::editPassword read password and open edit window via
1359
 * MainWindow::onEdit()
1360
 */
1361
void MainWindow::editPassword(const QString &file) {
×
1362
  if (!file.isEmpty()) {
×
1363
    if (QtPassSettings::isUseGit() && QtPassSettings::isAutoPull()) {
×
1364
      onUpdate(true);
×
1365
    }
1366
    setPassword(file, false);
×
1367
  }
1368
}
×
1369

1370
/**
1371
 * @brief MainWindow::renamePassword rename an existing password
1372
 */
1373
void MainWindow::renamePassword() {
×
1374
  bool ok;
1375
  QString file = getFile(ui->treeView->currentIndex(), false);
×
1376
  QString filePath = QFileInfo(file).path();
×
1377
  QString fileName = QFileInfo(file).fileName();
×
1378
  if (fileName.endsWith(".gpg", Qt::CaseInsensitive)) {
×
1379
    fileName.chop(4);
×
1380
  }
1381

1382
  QString newName =
1383
      QInputDialog::getText(this, tr("Rename file"), tr("Rename File To: "),
×
1384
                            QLineEdit::Normal, fileName, &ok);
×
1385
  if (!ok || newName.isEmpty()) {
×
1386
    return;
1387
  }
1388
  QString newFile = QDir(filePath).filePath(newName);
×
1389
  QtPassSettings::getPass()->Move(file, newFile);
×
1390
}
1391

1392
/**
1393
 * @brief MainWindow::clearTemplateWidgets empty the template widget fields in
1394
 * the UI
1395
 */
1396
void MainWindow::clearTemplateWidgets() {
×
1397
  while (ui->gridLayout->count() > 0) {
×
1398
    QLayoutItem *item = ui->gridLayout->takeAt(0);
×
1399
    delete item->widget();
×
1400
    delete item;
×
1401
  }
1402
  ui->verticalLayoutPassword->setSpacing(0);
×
1403
}
×
1404

1405
/**
1406
 * @brief Copies the password of the selected file from the tree view to the
1407
 * clipboard.
1408
 * @example
1409
 * MainWindow::copyPasswordFromTreeview();
1410
 *
1411
 * @return void - This function does not return a value.
1412
 */
1413
void MainWindow::copyPasswordFromTreeview() {
×
1414
  QFileInfo fileOrFolder =
1415
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
1416

1417
  if (fileOrFolder.isFile()) {
×
1418
    QString file = getFile(ui->treeView->currentIndex(), true);
×
1419
    // Disconnect any previous connection to avoid accumulation
1420
    disconnect(QtPassSettings::getPass(), &Pass::finishedShow, this,
×
1421
               &MainWindow::passwordFromFileToClipboard);
1422
    connect(QtPassSettings::getPass(), &Pass::finishedShow, this,
×
1423
            &MainWindow::passwordFromFileToClipboard);
×
1424
    QtPassSettings::getPass()->Show(file);
×
1425
  }
1426
}
×
1427

1428
void MainWindow::passwordFromFileToClipboard(const QString &text) {
×
1429
  QStringList tokens = text.split('\n');
×
1430
  m_qtPass->copyTextToClipboard(tokens[0]);
×
1431
}
×
1432

1433
/**
1434
 * @brief MainWindow::addToGridLayout add a field to the template grid
1435
 * @param position
1436
 * @param field
1437
 * @param value
1438
 */
1439
void MainWindow::addToGridLayout(int position, const QString &field,
×
1440
                                 const QString &value) {
1441
  QString trimmedField = field.trimmed();
1442
  QString trimmedValue = value.trimmed();
1443

1444
  const QString buttonStyle =
1445
      "border-style: none; background: transparent; padding: 0; margin: 0; "
1446
      "icon-size: 16px; color: inherit;";
×
1447

1448
  // Combine the Copy button and the line edit in one widget
1449
  auto *frame = new QFrame();
×
1450
  QLayout *ly = new QHBoxLayout();
×
1451
  ly->setContentsMargins(5, 2, 2, 2);
×
1452
  ly->setSpacing(0);
×
1453
  frame->setLayout(ly);
×
1454
  if (QtPassSettings::getClipBoardType() != Enums::CLIPBOARD_NEVER) {
×
1455
    auto *fieldLabel = new QPushButtonWithClipboard(trimmedValue, this);
×
1456
    connect(fieldLabel, &QPushButtonWithClipboard::clicked, m_qtPass,
×
1457
            &QtPass::copyTextToClipboard);
×
1458

1459
    fieldLabel->setStyleSheet(buttonStyle);
×
1460
    frame->layout()->addWidget(fieldLabel);
×
1461
  }
1462

1463
  if (QtPassSettings::isUseQrencode()) {
×
1464
    auto *qrbutton = new QPushButtonAsQRCode(trimmedValue, this);
×
1465
    connect(qrbutton, &QPushButtonAsQRCode::clicked, m_qtPass,
×
1466
            &QtPass::showTextAsQRCode);
×
1467
    qrbutton->setStyleSheet(buttonStyle);
×
1468
    frame->layout()->addWidget(qrbutton);
×
1469
  }
1470

1471
  // set the echo mode to password, if the field is "password"
1472
  const QString lineStyle =
1473
      QtPassSettings::isUseMonospace()
×
1474
          ? "border-style: none; background: transparent; font-family: "
1475
            "monospace;"
1476
          : "border-style: none; background: transparent;";
×
1477

1478
  if (QtPassSettings::isHidePassword() && trimmedField == tr("Password")) {
×
1479
    auto *line = new QLineEdit();
×
1480
    line->setObjectName(trimmedField);
×
1481
    line->setText(trimmedValue);
×
1482
    line->setReadOnly(true);
×
1483
    line->setStyleSheet(lineStyle);
×
1484
    line->setContentsMargins(0, 0, 0, 0);
×
1485
    line->setEchoMode(QLineEdit::Password);
×
1486
    auto *showButton = new QPushButtonShowPassword(line, this);
×
1487
    showButton->setStyleSheet(buttonStyle);
×
1488
    showButton->setContentsMargins(0, 0, 0, 0);
×
1489
    frame->layout()->addWidget(showButton);
×
1490
    frame->layout()->addWidget(line);
×
1491
  } else {
1492
    auto *line = new QTextBrowser();
×
1493
    line->setOpenExternalLinks(true);
×
1494
    line->setOpenLinks(true);
×
1495
    line->setMaximumHeight(26);
×
1496
    line->setMinimumHeight(26);
×
1497
    line->setSizePolicy(
×
1498
        QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum));
1499
    line->setObjectName(trimmedField);
×
1500
    trimmedValue.replace(Util::protocolRegex(), R"(<a href="\1">\1</a>)");
×
1501
    line->setText(trimmedValue);
×
1502
    line->setReadOnly(true);
×
1503
    line->setStyleSheet(lineStyle);
×
1504
    line->setContentsMargins(0, 0, 0, 0);
×
1505
    frame->layout()->addWidget(line);
×
1506
  }
1507

1508
  frame->setStyleSheet(
×
1509
      ".QFrame{border: 1px solid lightgrey; border-radius: 5px;}");
1510

1511
  // set into the layout
1512
  ui->gridLayout->addWidget(new QLabel(trimmedField), position, 0);
×
1513
  ui->gridLayout->addWidget(frame, position, 1);
×
1514
}
×
1515

1516
/**
1517
 * @brief Displays message in status bar
1518
 *
1519
 * @param msg     text to be displayed
1520
 * @param timeout time for which msg shall be visible
1521
 */
1522
void MainWindow::showStatusMessage(const QString &msg, int timeout) {
×
1523
  ui->statusBar->showMessage(msg, timeout);
×
1524
}
×
1525

1526
/**
1527
 * @brief MainWindow::reencryptPath re-encrypt all passwords in a directory
1528
 * @param dir Directory path to re-encrypt
1529
 */
1530
void MainWindow::reencryptPath(const QString &dir) {
×
1531
  QDir checkDir(dir);
×
1532
  if (!checkDir.exists()) {
×
1533
    QMessageBox::critical(this, tr("Error"),
×
1534
                          tr("Directory does not exist: %1").arg(dir));
×
1535
    return;
×
1536
  }
1537

1538
  int ret = QMessageBox::question(
×
1539
      this, tr("Re-encrypt passwords"),
×
1540
      tr("Re-encrypt all passwords in %1?\n\n"
×
1541
         "This will re-encrypt ALL password files in this folder "
1542
         "using the current recipients defined in .gpg-id.\n\n"
1543
         "This may rewrite many files and cannot be undone easily.\n\n"
1544
         "Continue?")
1545
          .arg(QDir(dir).dirName()),
×
1546
      QMessageBox::Yes | QMessageBox::No);
1547

1548
  if (ret != QMessageBox::Yes)
×
1549
    return;
1550

1551
  // Prevent double execution - use same method as startReencryptPath
1552
  setUiElementsEnabled(false);
×
1553
  ui->treeView->setDisabled(true);
×
1554

1555
  QtPassSettings::getImitatePass()->reencryptPath(
×
1556
      QDir::cleanPath(QDir(dir).absolutePath()));
×
1557
}
×
1558

1559
/**
1560
 * @brief MainWindow::startReencryptPath disable ui elements and treeview
1561
 */
1562
void MainWindow::startReencryptPath() {
×
1563
  setUiElementsEnabled(false);
×
1564
  ui->treeView->setDisabled(true);
×
1565
}
×
1566

1567
/**
1568
 * @brief MainWindow::endReencryptPath re-enable ui elements
1569
 */
1570
void MainWindow::endReencryptPath() { setUiElementsEnabled(true); }
×
1571

1572
/**
1573
 * @brief MainWindow::exportPublicKey export current user's public key
1574
 * Shows instructions to export key via command line
1575
 * TODO: Wire to real gpg export via Executor - see issue #422
1576
 */
1577
void MainWindow::exportPublicKey() {
×
1578
  QString identity = QtPassSettings::getPassSigningKey();
×
1579
  if (identity.isEmpty()) {
×
1580
    identity = "<your-key-id>";
×
1581
  }
1582
  identity = identity.toHtmlEscaped();
×
1583
  QMessageBox::information(
×
1584
      this, tr("Export Public Key"),
×
1585
      tr("<h3>Export Your Public Key</h3>"
×
1586
         "<p>To export your public GPG key, run this in terminal:</p>"
1587
         "<pre>gpg --armor --export --output my_key.asc %1</pre>"
1588
         "<p>Then send the file to your teammates.</p>"
1589
         "<p>Your key ID: You can find it in QtPass Settings &gt; GPG "
1590
         "keys.</p>")
1591
          .arg(identity));
×
1592
}
×
1593

1594
/**
1595
 * @brief MainWindow::addRecipient add a new recipient's public key
1596
 * @param dir Directory path
1597
 */
1598
void MainWindow::addRecipient(const QString &dir) {
×
1599
  QString gpgIdPath = Pass::getGpgIdPath(dir).toHtmlEscaped();
×
1600
  QMessageBox::information(
×
1601
      this, tr("Add Recipient"),
×
1602
      tr("<h3>Add Recipient</h3>"
×
1603
         "<p>To add a teammate's public key:</p>"
1604
         "<ol>"
1605
         "<li>Save their public key as a .asc file</li>"
1606
         "<li>Copy the key text</li>"
1607
         "<li>Open %1</li>"
1608
         "<li>Add the new key ID to the file</li>"
1609
         "<li>Re-encrypt passwords to share with them</li>"
1610
         "</ol>"
1611
         "<p>Use the full fingerprint to ensure accuracy.</p>")
1612
          .arg(gpgIdPath));
×
1613
}
×
1614

1615
/**
1616
 * @brief MainWindow::showShareHelp show help about GPG sharing
1617
 */
1618
void MainWindow::showShareHelp() {
×
1619
  QMessageBox::information(
×
1620
      this, tr("Sharing Passwords with GPG"),
×
1621
      tr("<h3>Sharing Passwords with GPG</h3>"
×
1622
         "<p>To share passwords with other users:</p>"
1623
         "<ol>"
1624
         "<li><b>Export your public key</b> and send it to teammates</li>"
1625
         "<li><b>Import teammates' public keys</b> to their own folders</li>"
1626
         "<li><b>Re-encrypt passwords</b> so all recipients can decrypt "
1627
         "them</li>"
1628
         "</ol>"
1629
         "<p>Only people who have a matching secret key can decrypt the "
1630
         "passwords.</p>"
1631
         "<p><b>Tip:</b> Use the same GPG key for all shared folders.</p>"
1632
         "<p>See the FAQ for more details.</p>"));
1633
}
×
1634

1635
void MainWindow::updateGitButtonVisibility() {
×
1636
  if (!QtPassSettings::isUseGit() ||
×
1637
      (QtPassSettings::getGitExecutable().isEmpty() &&
×
1638
       QtPassSettings::getPassExecutable().isEmpty())) {
×
1639
    enableGitButtons(false);
×
1640
  } else {
1641
    enableGitButtons(true);
×
1642
  }
1643
}
×
1644

1645
void MainWindow::updateOtpButtonVisibility() {
×
1646
#if defined(Q_OS_WIN) || defined(__APPLE__)
1647
  ui->actionOtp->setVisible(false);
1648
#endif
1649
  if (!QtPassSettings::isUseOtp()) {
×
1650
    ui->actionOtp->setEnabled(false);
×
1651
  } else {
1652
    ui->actionOtp->setEnabled(true);
×
1653
  }
1654
}
×
1655

1656
void MainWindow::updateGrepButtonVisibility() {
×
1657
  const bool enabled = QtPassSettings::isUseGrepSearch();
×
1658
  ui->grepButton->setVisible(enabled);
×
1659
  ui->grepCaseButton->setVisible(enabled);
×
1660
  if (!enabled && m_grepMode) {
×
1661
    ui->grepButton->setChecked(false);
×
1662
  }
1663
}
×
1664

1665
void MainWindow::enableGitButtons(const bool &state) {
×
1666
  // Following GNOME guidelines is preferable disable buttons instead of hide
1667
  ui->actionPush->setEnabled(state);
×
1668
  ui->actionUpdate->setEnabled(state);
×
1669
}
×
1670

1671
/**
1672
 * @brief MainWindow::critical critical message popup wrapper.
1673
 * @param title
1674
 * @param msg
1675
 */
1676
void MainWindow::critical(const QString &title, const QString &msg) {
×
1677
  QMessageBox::critical(this, title, msg);
×
1678
}
×
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