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

IJHack / QtPass / 24861164908

23 Apr 2026 10:03PM UTC coverage: 26.78% (-0.2%) from 26.966%
24861164908

push

github

web-flow
feat: add Share submenu for folders (#1144)

* feat: add Share submenu for folders

Add Share submenu to folder context menu with:
- Export my public key (shows instructions)
- Add recipient (shows instructions)
- Re-encrypt all passwords (moved from main menu)
- What is this? (help dialog)
- Use Pass::getGpgIdPath for correct path detection
- Enable/disable based on gpg availability and .gpg-id existence
- HTML-escape user input for safety

Part of issue #422

* fix: address review on share submenu

- Make gpgAvailable check symmetric and consistent with Util::configIsValid
  by using exePath in both branches and the standard "wsl " prefix heuristic
  instead of "/mnt".
- Use an obvious "<your-key-id>" placeholder in exportPublicKey instead of
  the realistic-looking "user@qtpass.org", so users do not copy a misleading
  email into the suggested gpg command.

---------

Co-authored-by: Henk de Bot <henk@annejan.com>
Co-authored-by: Anne Jan Brouwer <brouwer@annejan.com>

0 of 43 new or added lines in 1 file covered. (0.0%)

9 existing lines in 1 file now uncovered.

1636 of 6109 relevant lines covered (26.78%)

29.01 hits per line

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

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

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

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

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

52
  m_qtPass = new QtPass(this);
×
53

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

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

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

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

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

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

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

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

107
  updateProfileBox();
×
108

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

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

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

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

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

126
  setUiElementsEnabled(true);
×
127

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1072
  QtPassSettings::setProfile(name);
×
1073

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

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

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

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

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

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

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

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

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

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

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

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

1196
  ui->treeView->setCurrentIndex(index);
×
1197

1198
  QPoint globalPos = ui->treeView->viewport()->mapToGlobal(pos);
×
1199

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

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

NEW
1235
      QMenu *shareMenu = new QMenu(tr("Share"), &contextMenu);
×
NEW
1236
      contextMenu.addMenu(shareMenu);
×
1237

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

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

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

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

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

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

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

1279
  contextMenu->exec(globalPos);
×
1280
  delete contextMenu;
×
1281
}
×
1282

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1457
    fieldLabel->setStyleSheet(buttonStyle);
×
1458
    frame->layout()->addWidget(fieldLabel);
×
1459
  }
1460

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

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

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

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

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

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

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

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

1546
  if (ret != QMessageBox::Yes)
×
1547
    return;
1548

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

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

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

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

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

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

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

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

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

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

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

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