35#include "ui_mainwindow.h"
39#include <QApplication>
42#include <QDesktopServices>
46#include <QFileSystemModel>
48#include <QInputDialog>
54#include <QProgressDialog>
59#include <QTextCharFormat>
61#include <QTextDocument>
79 return QCoreApplication::translate(
"MainWindow",
"a decrypt");
82 return label.isEmpty()
83 ? QCoreApplication::translate(
"MainWindow",
"a command")
92 qt_set_sequence_auto_mnemonic(
true);
103 const QList<QKeySequence> copyKeys =
104 QKeySequence::keyBindings(QKeySequence::StandardKey::Copy);
105 for (
const QKeySequence &keys : copyKeys) {
112 connect(
ui->treeView, &QWidget::customContextMenuRequested,
this,
127 ui->lineEdit->installEventFilter(
this);
130 ui->toolBar->installEventFilter(
this);
131 menuBar()->installEventFilter(
this);
139 ui->lineEdit->setClearButtonEnabled(
true);
166 if (!searchText.isEmpty()) {
167 QTimer::singleShot(0,
this,
178 [
this](
const QString &html) {
flashText(html,
false,
true); });
191 const QString file =
getFile(index,
true);
199 QDir::cleanPath(saved) != QDir::cleanPath(
getFile(index,
false))) {
202 if (!file.isEmpty() && pass->
isPushing()) {
211 [
this](
const QString &message) { showStatusMessage(message); });
231 QFont monospace(
"Monospace");
232 monospace.setStyleHint(QFont::Monospace);
233 ui->textBrowser->setFont(monospace);
236 ui->textBrowser->setLineWrapMode(QTextBrowser::NoWrap);
241 ui->textBrowser->setOpenExternalLinks(
true);
242 ui->textBrowser->setContextMenuPolicy(Qt::CustomContextMenu);
243 connect(
ui->textBrowser, &QWidget::customContextMenuRequested,
this,
249 ui->gridLayout,
ui->verticalLayoutPassword,
this,
this);
285 connect(&
m_uiWatchdog, &QTimer::timeout,
this, [
this]() {
291 pass !=
nullptr && !pass->isIdle()) {
292 m_stopButton->setToolTip(tr(
"Stop %1, which is still running")
293 .arg(
runLabel(pass->runningProcess())));
311 ui->actionShowProcessOutput->setChecked(
313 connect(
ui->actionShowProcessOutput, &QAction::toggled,
this,
315 m_processOutput->setVisible(show);
316 AppSettings s = QtPassSettings::load();
317 if (s.showProcessOutput != show) {
318 s.showProcessOutput = show;
319 QtPassSettings::save(s);
324 [
this](
const QString &out,
const QString &err,
Enums::PROCESS pid) {
334 if (!out.isEmpty()) {
335 onProcessOutput(out,
false, pid);
337 if (!err.isEmpty()) {
338 onProcessOutput(err,
true, pid);
364 m_stopButton->setToolTip(tr(
"Stop %1, which is still running")
416 auto *lineEdit = findChild<QLineEdit *>(QStringLiteral(
"lineEdit"));
417 if (lineEdit ==
nullptr || !lineEdit->isVisible()) {
420 lineEdit->selectAll();
421 lineEdit->setFocus();
428 if (
event->type() == QEvent::ApplicationPaletteChange) {
434 return QMainWindow::event(
event);
438 QWidget::changeEvent(
event);
445 if (
event->type() == QEvent::ActivationChange && isActiveWindow() &&
450 Qt::QueuedConnection);
455 QMainWindow::showEvent(
event);
463 Qt::QueuedConnection);
467 connect(
ui->actionAddPassword, &QAction::triggered,
this,
469 connect(
ui->actionAddFolder, &QAction::triggered,
this,
482 connect(
ui->actionQuit, &QAction::triggered, qApp, &QApplication::quit);
483 connect(
ui->actionClose, &QAction::triggered,
this, &MainWindow::close);
486 ui->actionShowMenuBar->setVisible(
false);
490 addAction(
ui->actionShowMenuBar);
492 menuBar()->setVisible(
ui->actionShowMenuBar->isChecked());
493 connect(
ui->actionShowMenuBar, &QAction::toggled,
this, [
this](
bool show) {
494 menuBar()->setVisible(show);
495 AppSettings s = QtPassSettings::load();
496 s.showMenuBar = show;
497 QtPassSettings::save(s);
501 connect(
ui->actionFaq, &QAction::triggered,
this, [] {
502 QDesktopServices::openUrl(QUrl(QStringLiteral(
"https://qtpass.org/faq")));
505 connect(
ui->actionAboutQt, &QAction::triggered, qApp, &QApplication::aboutQt);
507 ui->actionAddPassword->setIcon(
508 QIcon::fromTheme(
"document-new", QIcon(
":/icons/document-new.svg")));
509 ui->actionAddFolder->setIcon(
510 QIcon::fromTheme(
"folder-new", QIcon(
":/icons/folder-new.svg")));
511 ui->actionEdit->setIcon(QIcon::fromTheme(
512 "document-properties", QIcon(
":/icons/document-properties.svg")));
513 ui->actionDelete->setIcon(
514 QIcon::fromTheme(
"edit-delete", QIcon(
":/icons/edit-delete.svg")));
515 ui->actionPush->setIcon(
516 QIcon::fromTheme(
"go-up", QIcon(
":/icons/go-top.svg")));
517 ui->actionUpdate->setIcon(
518 QIcon::fromTheme(
"go-down", QIcon(
":/icons/go-bottom.svg")));
519 ui->actionUsers->setIcon(QIcon::fromTheme(
520 "x-office-address-book", QIcon(
":/icons/x-office-address-book.svg")));
521 ui->actionConfig->setIcon(QIcon::fromTheme(
522 "applications-system", QIcon(
":/icons/applications-system.svg")));
526 ui->statusBar->showMessage(tr(
"Welcome to QtPass %1").arg(VERSION), 2000);
528 QPixmap logo = QPixmap::fromImage(QImage(
":/artwork/icon.svg"))
529 .scaledToHeight(statusBar()->height());
530 auto *logoApp =
new QLabel(statusBar());
531 logoApp->setPixmap(logo);
532 m_stopButton =
new QPushButton(tr(
"Stop"), statusBar());
533 m_stopButton->setObjectName(QStringLiteral(
"stopButton"));
535 tr(
"Stop the gpg, git or pass run that is still going"));
537 connect(
m_stopButton, &QPushButton::clicked,
this, [
this]() {
539 if (pass ==
nullptr || pass->
isIdle()) {
545 const QString label =
runLabel(pid);
551 const auto answer = QMessageBox::question(
552 this, tr(
"Stop %1?").arg(label),
553 tr(
"%1 has not finished. Stopping it can leave its change half "
554 "done: some entries re-encrypted and others not, or a Git step "
555 "cut off, after which Git may refuse to run until "
556 ".git/index.lock is removed.\n\nStop it anyway?")
558 QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
561 if (answer != QMessageBox::Yes || pass->
runningSerial() != run) {
568 writes ? tr(
"Stopped %1 before it finished; the store may be "
571 : tr(
"Stopped %1.").arg(label));
575 statusBar()->addPermanentWidget(logoApp);
579 return ui->treeView->currentIndex();
588 QTextCursor cursor =
ui->textBrowser->textCursor();
589 cursor.clearSelection();
590 ui->textBrowser->setTextCursor(cursor);
591 QTextCharFormat format;
593 format.setForeground(QColor(Qt::red));
595 ui->textBrowser->setCurrentCharFormat(format);
601 ui->textBrowser->setWordWrapMode(QTextOption::WrapAnywhere);
603 QString _text = text;
608 if (!
ui->textBrowser->toPlainText().isEmpty()) {
609 older =
ui->textBrowser->document()->characterCount() - 1;
610 _text =
ui->textBrowser->toHtml() + _text;
612 ui->textBrowser->setHtml(_text);
617 QTextDocument *doc =
ui->textBrowser->document();
620 const QTextBlock block = doc->findBlock(cut);
621 if (block.isValid() && cut > block.position() && block.next().isValid() &&
622 block.next().position() <= older + 1) {
623 cut = block.next().position();
625 QTextCursor trim(doc);
626 trim.setPosition(cut, QTextCursor::KeepAnchor);
627 trim.removeSelectedText();
630 ui->textBrowser->setText(text);
634 ui->textBrowser->setWordWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
641 QFont monospace(
"Monospace");
642 monospace.setStyleHint(QFont::Monospace);
643 ui->textBrowser->setFont(monospace);
645 ui->textBrowser->setFont(QFont());
649 ui->textBrowser->setLineWrapMode(QTextBrowser::NoWrap);
651 ui->textBrowser->setLineWrapMode(QTextBrowser::WidgetWidth);
657 const Qt::WindowFlags flags = windowFlags();
658 if (flags.testFlag(Qt::WindowStaysOnTopHint) == wantOnTop) {
664 const bool wasVisible = isVisible();
665 setWindowFlags(wantOnTop ? (flags | Qt::WindowStaysOnTopHint)
666 : (flags & ~Qt::WindowStaysOnTopHint));
679 if (wizard.exec() != QDialog::Accepted) {
685 if (d.exec() != QDialog::Accepted) {
703 if (
m_grep.cancelSearch()) {
704 QApplication::restoreOverrideCursor();
709 ui->treeView->setCurrentIndex(QModelIndex());
713 m_tree->setPass(activePass);
716 m_qtPass->clipboard().setAutoclearTimer();
742 ui->statusBar->showMessage(tr(
"Updating password-store"), 2000);
752 ui->statusBar->showMessage(tr(
"Updating password-store"), 2000);
759 ui->statusBar->showMessage(tr(
"Updating password-store"), 2000);
765 return m_tree->fileFor(index, forPass);
769 bool cleared =
ui->treeView->currentIndex().flags() == Qt::NoItemFlags;
770 QString file =
getFile(index,
true);
772 if (!file.isEmpty() && !cleared) {
780 ui->actionEdit->setEnabled(
false);
781 ui->actionDelete->setEnabled(
true);
788 if (fileOrFolder.isFile()) {
797 ui->treeView->clearSelection();
801 ui->treeView->setCurrentIndex(QModelIndex());
802 ui->actionEdit->setEnabled(
false);
803 ui->actionDelete->setEnabled(
false);
804 ui->passwordName->setText(
"");
811 ui->textBrowser->clear();
841 p_output, templ, allFields, [
this, &s](
const QString &name) {
844 QString output = p_output;
859 output =
"***" + tr(
"Content hidden") +
"***";
884 const QString &file) {
892 if (p_output.isEmpty()) {
894 flashText(tr(
"Could not decrypt this password entry"),
true);
903 if (!shown.isEmpty()) {
913 const QStringList templ =
920 const std::optional<Totp::Settings> settings =
922 if (settings.has_value()) {
928 flashText(reason.isEmpty() ? tr(
"No OTP code found in this password entry")
947 QString output =
"***" + tr(
"Password and content hidden") +
"***";
948 ui->textBrowser->setHtml(output);
950 ui->textBrowser->setHtml(
"");
956 const bool grepWasVisible =
ui->grepResultsList->isVisible();
957 ui->grepResultsList->clear();
958 if (grepWasVisible) {
965 QApplication::restoreOverrideCursor();
967 ui->grepButton->blockSignals(
true);
968 ui->grepButton->setChecked(
false);
969 ui->grepButton->blockSignals(
false);
970 ui->lineEdit->blockSignals(
true);
971 ui->lineEdit->clear();
972 ui->lineEdit->blockSignals(
false);
973 ui->lineEdit->setPlaceholderText(tr(
"Search password"));
992 ui->treeView->setEnabled(state);
993 ui->lineEdit->setEnabled(state);
994 ui->actionAddPassword->setEnabled(state);
995 ui->actionAddFolder->setEnabled(state);
996 ui->actionUsers->setEnabled(state);
997 ui->actionConfig->setEnabled(state);
1000 const bool uiEnabled = state;
1002 state &=
ui->treeView->currentIndex().isValid() && !
ui->treeView->isHidden();
1003 ui->actionDelete->setEnabled(state);
1004 ui->actionEdit->setEnabled(state);
1015 if (geometry.isEmpty() || !restoreGeometry(geometry)) {
1029 QTimer::singleShot(10,
this, &MainWindow::hide);
1044 critical(tr(
"Settings not opened"),
1045 tr(
"A gpg, Git or pass command is still running or waiting. "
1046 "Open the settings again once it has finished. If it does "
1047 "not finish, answer or cancel the PIN or password prompt it "
1048 "waits for, or restart QtPass. A restart forgets which "
1049 "folders still need re-encrypting: re-encrypt any folder "
1050 "whose re-encryption did not finish, or that you moved "
1051 "entries into, before anything is pushed."));
1059 this, tr(
"About QtPass"),
1060 tr(
"<h3>QtPass %1</h3>"
1061 "<p>A multi-platform GUI for <a "
1062 "href=\"https://www.passwordstore.org/\">"
1063 "pass</a>, the standard Unix password manager.</p>"
1064 "<p><a href=\"https://qtpass.org/\">qtpass.org</a> · "
1065 "<a href=\"https://github.com/IJHack/QtPass\">Source and "
1067 "<p>Copyright © 2014–%2 IJhack. Licensed under the "
1068 "<a href=\"https://www.gnu.org/licenses/gpl-3.0.html\">GNU GPL "
1069 "version 3</a> or later.</p>")
1070 .arg(QStringLiteral(VERSION),
1071 QString::number(QDate::currentDate().year())));
1077 ui->statusBar->showMessage(tr(
"Looking for: %1").arg(arg1), 1000);
1078 ui->treeView->expandAll();
1085 ui->passwordName->setText(
"");
1086 ui->actionEdit->setEnabled(
false);
1087 ui->actionDelete->setEnabled(
false);
1094 QString query = QDir::fromNativeSeparators(
ui->lineEdit->text());
1096 if (query.isEmpty()) {
1097 ui->treeView->collapseAll();
1105 if (
m_tree->
proxy().rowCount() > 0 && !query.isEmpty()) {
1108 ui->actionEdit->setEnabled(
false);
1109 ui->actionDelete->setEnabled(
false);
1114 qCDebug(lcQtPass) <<
"on_lineEdit_returnPressed"
1118 const QString query =
ui->lineEdit->text();
1119 if (!query.isEmpty()) {
1120 ui->grepResultsList->clear();
1121 ui->statusBar->showMessage(tr(
"Searching…"));
1123 QApplication::setOverrideCursor(Qt::WaitCursor);
1129 QApplication::restoreOverrideCursor();
1131 ui->grepResultsList->clear();
1153 ui->lineEdit->setPlaceholderText(tr(
"Search content (regex)"));
1156 ui->lineEdit->setToolTip(
1157 tr(
"Content search uses Perl-compatible regular expressions (PCRE)."));
1158 ui->lineEdit->clear();
1161 ui->grepResultsList->setVisible(
false);
1166 QApplication::restoreOverrideCursor();
1169 ui->lineEdit->blockSignals(
true);
1170 ui->lineEdit->clear();
1171 ui->lineEdit->blockSignals(
false);
1172 ui->lineEdit->setPlaceholderText(tr(
"Search password"));
1173 ui->lineEdit->setToolTip(QString());
1174 ui->grepResultsList->clear();
1190 const QString hidden =
1191 QStringLiteral(
"***") + tr(
"hidden") + QStringLiteral(
"***");
1193 return tr(
"One-time password secret: %1").arg(hidden);
1199 ? tr(
"Password: %1").arg(hidden)
1202 if (
const qsizetype colon = line.indexOf(QLatin1Char(
':')); colon > 0) {
1204 return line.left(colon + 1) + QLatin1Char(
' ') + hidden;
1211 const QList<QPair<QString, QStringList>> &results) {
1216 if (
const QObject *from = sender();
1222 QApplication::restoreOverrideCursor();
1232 ui->grepResultsList->clear();
1233 if (results.isEmpty()) {
1234 ui->statusBar->showMessage(tr(
"No matches found."), 3000);
1243 bool stopped =
false;
1244 for (
const auto &pair : results) {
1250 auto *entryItem =
new QTreeWidgetItem(
ui->grepResultsList);
1251 entryItem->setText(0, pair.first);
1252 entryItem->setData(0, Qt::UserRole, pair.first);
1253 for (
const QString &line : pair.second) {
1254 auto *lineItem =
new QTreeWidgetItem(entryItem);
1258 lineItem->setText(0, tr(
"… more matches in this entry"));
1260 lineItem->setText(0, hideContent ?
"***" + tr(
"Content hidden") +
"***"
1264 lineItem->setData(0, Qt::UserRole, pair.first);
1267 ui->grepResultsList->expandAll();
1271 ui->statusBar->showMessage(
1272 tr(
"Showing the first %n match(es); search for something narrower "
1274 nullptr, totalLines),
1277 ui->statusBar->showMessage(tr(
"Found %n match(es)",
nullptr, totalLines) +
1279 tr(
"in %n entr(ies).",
nullptr, entries),
1292 const QString entry = item->data(0, Qt::UserRole).toString();
1293 if (entry.isEmpty())
1295 const QString fullPath =
1299 const QPersistentModelIndex proxyIndex(
m_tree->
indexFor(fullPath));
1300 if (!proxyIndex.isValid())
1302 ui->treeView->setCurrentIndex(proxyIndex);
1303 if (!proxyIndex.isValid())
1307 ui->grepResultsList->clear();
1309 ui->treeView->scrollTo(proxyIndex);
1310 ui->treeView->setFocus();
1314 ui->grepResultsList->setVisible(shown);
1315 ui->treeView->setVisible(!shown);
1319 ui->actionDelete->setEnabled(
false);
1320 ui->actionEdit->setEnabled(
false);
1322 }
else if (
ui->treeView->selectionModel()->hasSelection()) {
1338 if (!index.isValid()) {
1341 ui->treeView->setCurrentIndex(index);
1355auto spelledAsStored(
const QString &store,
const QString &path) -> QString {
1356 const QStringList parts = QDir(store).relativeFilePath(path).split(
1357 QLatin1Char(
'/'), Qt::SkipEmptyParts);
1359 bool respelled =
false;
1360 for (
int i = 0; i < parts.size(); ++i) {
1361 const bool leaf = i == parts.size() - 1;
1362 const QStringList names =
1363 dir.entryList((leaf ? QDir::Files : QDir::Dirs) | QDir::Hidden |
1364 QDir::NoDotAndDotDot);
1365 QString name = parts.at(i);
1366 if (!names.contains(name)) {
1367 const auto stored = std::find_if(
1368 names.cbegin(), names.cend(), [&name](
const QString &candidate) {
1369 return candidate.compare(name, Qt::CaseInsensitive) == 0;
1371 if (stored == names.cend()) {
1378 return respelled ? QDir::cleanPath(
Util::joinPath(dir.path(), name))
1381 if (!dir.cd(name)) {
1390 const QString text = QDir::fromNativeSeparators(
ui->lineEdit->text());
1394 for (
const QString &typed : {text, text.trimmed()}) {
1395 if (typed.isEmpty()) {
1398 const QString path =
1399 QDir::cleanPath(
Util::joinPath(store, typed + QStringLiteral(
".gpg")));
1401 return spelledAsStored(store, path);
1409 if (path.isEmpty()) {
1413 const QModelIndex index =
m_tree->indexFor(path);
1414 if (!index.isValid() || !
m_tree->fileInfo(index).isFile()) {
1423 if (
ui->grepButton->isChecked()) {
1424 ui->grepButton->setChecked(
false);
1427 ui->lineEdit->setText(text);
1432 if (
const QModelIndex exact =
exactMatch(); exact.isValid()) {
1444 auto *pending =
new QObject(
this);
1446 QTimer::singleShot(5000, pending, &QObject::deleteLater);
1449 const auto stop = [
this, pending] {
1450 disconnect(
m_tree,
nullptr, pending,
nullptr);
1451 disconnect(
ui->lineEdit,
nullptr, pending,
nullptr);
1452 pending->deleteLater();
1454 connect(
ui->lineEdit, &QLineEdit::textChanged, pending, stop);
1456 [
this, stop](
const QString &) {
1459 if (
const QModelIndex exact =
exactMatch(); exact.isValid()) {
1470 ui->treeView->setCurrentIndex(index);
1476 int numRows = proxy.rowCount(parentIndex);
1477 for (
int row = 0; row < numRows; ++row) {
1478 QModelIndex index = proxy.index(row, 0, parentIndex);
1479 if (
m_tree->fileInfo(index).isFile()) {
1483 QModelIndex childFile =
firstFile(index);
1484 if (childFile.isValid())
1497 QMessageBox::warning(
this, tr(
"Invalid name"),
1498 tr(
"That name would resolve outside the password "
1499 "store. Please choose a different name."));
1513 if (folder.isEmpty()) {
1526 QStringList folders{QString()};
1528 for (
const QString &path : found) {
1529 const QString rel = QDir(storePath).relativeFilePath(path);
1530 if (!rel.startsWith(u
'.') && !rel.contains(QStringLiteral(
"/."))) {
1534 std::sort(folders.begin() + 1, folders.end());
1536 QDir(storePath).relativeFilePath(folder));
1537 QHash<QString, QStringList> templates =
1539 if (!templates.isEmpty()) {
1540 QString defaultTemplate =
1547 ui->treeView->setFocus();
1554 const QString path = QDir::separator() + file;
1558 const QString shown =
1562 this, tr(
"Delete password?"),
1563 tr(
"Are you sure you want to delete %1?").arg(shown));
1570 tr(
"Are you sure you want to delete %1 and the whole content?")
1574 QStringList skipped;
1575 QStringList unlisted;
1576 const QString root =
m_tree->fileSystem().rootPath();
1578 root + path, {QStringLiteral(
"*")}, &skipped,
false, &unlisted);
1579 const bool unexpected =
1580 !skipped.isEmpty() ||
1581 std::any_of(content.cbegin(), content.cend(), [](
const QString &entry) {
1582 return QFileInfo(entry).suffix() != QLatin1String(
"gpg");
1585 question += QStringLiteral(
"\n\n") +
1586 tr(
"Attention: there are unexpected files in the given "
1587 "folder, check them before continuing.");
1591 if (unlisted.size() == 1) {
1594 tr(
"%1 could not be read, so what it holds is unknown.")
1596 QDir::toNativeSeparators(
1598 QDir(root).relativeFilePath(unlisted.first())),
1600 question += QStringLiteral(
"\n\n") + one;
1601 }
else if (unlisted.size() > 1) {
1603 const QString many =
1604 tr(
"%n folder(s) in it could not be read, so what they hold "
1606 nullptr,
static_cast<int>(unlisted.size()));
1607 question += QStringLiteral(
"\n\n") + many;
1616 this, tr(
"Delete link?"),
1617 tr(
"%1 is a symbolic link or junction. Remove the link? What it "
1618 "points to is left alone.")
1623 const QModelIndex currentIndex =
ui->treeView->currentIndex();
1626 if (!currentIndex.isValid() ||
ui->treeView->isHidden()) {
1632 const QString file =
1634 const QString folder =
1642 const bool confirmed =
1670 if (
ui->treeView->isHidden()) {
1673 QString file =
getFile(
ui->treeView->currentIndex(),
true);
1674 if (file.isEmpty()) {
1675 flashText(tr(
"No password selected for OTP generation"),
true);
1680 flashText(tr(
"No OTP code found in this password entry"),
true);
1688 const QString shown =
1690 if (!shown.isEmpty()) {
1707 if (
ui->treeView->isHidden()) {
1710 QString file =
getFile(
ui->treeView->currentIndex(),
true);
1722 ui->treeView->setFocus();
1729 if (message.isEmpty()) {
1732 ui->treeView->expandAll();
1739 bool activeGone =
false;
1741 if (profiles.isEmpty()) {
1742 ui->profileWidget->hide();
1744 ui->profileWidget->show();
1747 const QSignalBlocker quiet(
ui->profileBox);
1748 ui->profileBox->clear();
1749 for (
auto i = profiles.cbegin(); i != profiles.cend(); ++i) {
1750 if (!i.key().isEmpty()) {
1751 ui->profileBox->addItem(i.key());
1754 ui->profileBox->model()->sort(0);
1757 ui->profileBox->setCurrentIndex(index);
1758 }
else if (
ui->profileBox->count() > 0) {
1762 ui->profileBox->setCurrentIndex(0);
1780 ui->profileBox->setEnabled(
m_uiEnabled &&
ui->profileBox->count() > 1 &&
1791 const QSignalBlocker quiet(
ui->profileBox);
1798 ui->grepButton->setChecked(
false);
1801 ui->lineEdit->clear();
1812 ui->statusBar->showMessage(tr(
"Profile changed to %1").arg(name), 2000);
1818 ui->treeView->setCurrentIndex(QModelIndex());
1852 QApplication::quit();
1857 if ((obj ==
ui->toolBar || obj == menuBar()) &&
1858 event->type() == QEvent::PaletteChange) {
1865 if (obj ==
ui->lineEdit &&
event->type() == QEvent::KeyPress) {
1866 auto *key =
dynamic_cast<QKeyEvent *
>(
event);
1867 if (key !=
nullptr && key->key() == Qt::Key_Down) {
1870 if (
ui->treeView->isHidden()) {
1871 ui->grepResultsList->setFocus();
1873 ui->treeView->setFocus();
1880 if (key !=
nullptr &&
1881 (key->key() == Qt::Key_Return || key->key() == Qt::Key_Enter)) {
1887 return QObject::eventFilter(obj,
event);
1897 constexpr int kStaleToolsAreaLightness = 64;
1901 const int appLightness = QApplication::palette()
1902 .color(QPalette::Active, QPalette::Window)
1904 for (QWidget *bar : {
static_cast<QWidget *
>(
ui->toolBar),
1905 static_cast<QWidget *
>(menuBar())}) {
1906 if (!bar->testAttribute(Qt::WA_SetPalette)) {
1909 const int barLightness =
1910 bar->palette().color(QPalette::Active, QPalette::Window).lightness();
1911 if (qAbs(barLightness - appLightness) <= kStaleToolsAreaLightness) {
1914 bar->setPalette(QPalette());
1918 bar->setBackgroundRole(QPalette::Window);
1919 bar->setAutoFillBackground(
true);
1924 switch (
event->key()) {
1925 case Qt::Key_Delete:
1928 case Qt::Key_Return:
1932 if (
ui->treeView->isHidden()) {
1933 QTreeWidgetItem *result =
ui->grepResultsList->currentItem();
1934 if (result !=
nullptr &&
ui->grepResultsList->hasFocus()) {
1943 case Qt::Key_Escape:
1944 ui->lineEdit->clear();
1953 auto *shareMenu =
new QMenu(tr(
"Share"), &contextMenu);
1954 contextMenu.addMenu(shareMenu);
1957 const bool gpgIdExists = !gpgIdPath.isEmpty() && QFile(gpgIdPath).exists();
1959 const bool gpgAvailable =
1960 !exePath.isEmpty() &&
1963 QAction *reencrypt = shareMenu->addAction(tr(
"Re-encrypt all passwords"));
1964 reencrypt->setEnabled(gpgIdExists && gpgAvailable);
1965 connect(reencrypt, &QAction::triggered,
this,
1968 QAction *exportKey = shareMenu->addAction(tr(
"Export my public key..."));
1969 exportKey->setEnabled(gpgAvailable);
1972 QAction *addRecipientAction = shareMenu->addAction(tr(
"Add recipient..."));
1973 addRecipientAction->setEnabled(gpgIdExists && gpgAvailable);
1974 connect(addRecipientAction, &QAction::triggered,
this,
1977 QAction *shareHelp = shareMenu->addAction(tr(
"What is this?"));
1982 const QModelIndex current =
ui->treeView->currentIndex();
1983 if (openedOn.isEmpty()) {
1985 if (current.isValid()) {
1986 ui->treeView->setCurrentIndex(QModelIndex());
1992 const QFileInfo entry(openedOn);
1993 const bool there = entry.exists() || entry.isSymLink();
1994 if (there && current.isValid() &&
1995 m_tree->fileInfo(current).absoluteFilePath() == openedOn) {
2000 const QModelIndex shown = there ?
m_tree->indexFor(openedOn) : QModelIndex();
2001 if (!shown.isValid()) {
2006 ui->treeView->setCurrentIndex(shown);
2012 const QModelIndex index =
ui->treeView->indexAt(pos);
2013 const bool selected = index.isValid();
2015 ui->treeView->clearSelection();
2016 ui->actionDelete->setEnabled(
false);
2017 ui->actionEdit->setEnabled(
false);
2019 ui->treeView->setCurrentIndex(index);
2020 const QPoint globalPos =
ui->treeView->viewport()->mapToGlobal(pos);
2021 const QFileInfo fileOrFolder =
m_tree->
fileInfo(
ui->treeView->currentIndex());
2022 const bool isDir = fileOrFolder.isDir();
2031 const QString openedOn =
2032 selected ? fileOrFolder.absoluteFilePath() : QString();
2033 const auto add = [
this, &contextMenu, openedOn](
const QString &text,
2035 connect(contextMenu.addAction(text), &QAction::triggered,
this,
2036 [
this, openedOn, slot]() {
2037 if (backOnMenuEntry(openedOn)) {
2042 if (!selected || isDir) {
2047 }
else if (fileOrFolder.isFile()) {
2051 contextMenu.addSeparator();
2054 }
else if (fileOrFolder.isFile()) {
2059 addShareMenu(contextMenu, s);
2065 contextMenu.exec(globalPos);
2073 const QScrollBar *across =
ui->textBrowser->horizontalScrollBar();
2074 const int dx =
ui->textBrowser->isRightToLeft()
2075 ? across->maximum() - across->value()
2077 const QPoint documentPos =
2078 pos + QPoint(dx,
ui->textBrowser->verticalScrollBar()->value());
2079 QMenu *contextMenu =
ui->textBrowser->createStandardContextMenu(documentPos);
2082 contextMenu->setParent(
this, contextMenu->windowFlags());
2083 if (
auto *copyLink =
2084 contextMenu->findChild<QAction *>(QStringLiteral(
"link-copy"))) {
2085 const QString link =
ui->textBrowser->anchorAt(pos);
2086 disconnect(copyLink, &QAction::triggered,
nullptr,
nullptr);
2087 connect(copyLink, &QAction::triggered,
this, [
this, link] {
2088 if (!link.isEmpty()) {
2089 m_qtPass->clipboard().copyText(link);
2098 contextMenu->exec(
ui->textBrowser->viewport()->mapToGlobal(pos));
2105 QString path = QDir::toNativeSeparators(dir);
2106 QDesktopServices::openUrl(QUrl::fromLocalFile(path));
2113 QString newdir = QInputDialog::getText(
2114 this, tr(
"New folder"),
2115 tr(
"New folder: \n(Will be placed in %1 )")
2117 QLineEdit::Normal,
"", &ok);
2118 if (!ok || newdir.isEmpty()) {
2124 newdir = QDir::cleanPath(newdir.prepend(dir));
2134 const QStringList parts =
2135 QDir(s.
passStore).relativeFilePath(newdir).split(u
'/');
2136 if (std::any_of(parts.cbegin(), parts.cend(), [](
const QString &part) {
2137 return part != u
'.' && part.startsWith(u
'.');
2140 tr(
"A folder that starts with a dot would be "
2141 "hidden from the list: %1")
2148 tr(
"Failed to create folder: %1").arg(newdir));
2160 QString srcDirName = QDir(srcDir).dirName();
2162 QInputDialog::getText(
this, tr(
"Rename folder"), tr(
"Rename folder to: "),
2163 QLineEdit::Normal, srcDirName, &ok);
2164 if (!ok || newName.isEmpty()) {
2167 QString destDir = srcDir;
2168 destDir.replace(srcDir.lastIndexOf(srcDirName), srcDirName.length(), newName);
2183 if (!file.isEmpty()) {
2200 QString file =
getFile(
ui->treeView->currentIndex(),
false);
2201 QString filePath = QFileInfo(file).path();
2202 QString fileName = QFileInfo(file).fileName();
2203 if (fileName.endsWith(
".gpg", Qt::CaseInsensitive)) {
2208 QInputDialog::getText(
this, tr(
"Rename file"), tr(
"Rename file to: "),
2209 QLineEdit::Normal, fileName, &ok);
2210 if (!ok || newName.isEmpty()) {
2228 QWidget *focus = QApplication::focusWidget();
2231 if (
auto *text = qobject_cast<QTextEdit *>(focus);
2232 text !=
nullptr && text->textCursor().hasSelection()) {
2238 if (
auto *label = qobject_cast<QLabel *>(focus);
2239 label !=
nullptr && label->hasSelectedText()) {
2245 if (focus ==
ui->grepResultsList) {
2246 if (
const QTreeWidgetItem *item =
ui->grepResultsList->currentItem();
2247 item !=
nullptr && !item->text(0).isEmpty()) {
2258 if (
ui->treeView->isHidden()) {
2263 if (fileOrFolder.isFile()) {
2264 QString file =
getFile(
ui->treeView->currentIndex(),
true);
2275 const QString &file) {
2289 flashText(tr(
"This entry holds an OTP secret, not a password"),
true);
2296 ui->statusBar->showMessage(msg, timeout);
2301 if (!checkDir.exists()) {
2303 tr(
"Directory does not exist: %1").arg(dir));
2311 this, tr(
"Re-encrypt passwords"),
2312 tr(
"Re-encrypt all passwords in %1?\n\n"
2313 "This will re-encrypt ALL password files in this folder "
2314 "using the current recipients defined in .gpg-id.\n\n"
2315 "This may rewrite many files and cannot be undone easily.\n\n"
2341 ui->treeView->setDisabled(
true);
2344 auto *progress =
new QProgressDialog(tr(
"Re-encrypting passwords..."),
2345 tr(
"Cancel"), 0, 0,
this);
2346 progress->setWindowTitle(tr(
"Re-encrypt passwords"));
2347 progress->setWindowModality(Qt::WindowModal);
2348 progress->setAutoClose(
false);
2349 progress->setAutoReset(
false);
2350 progress->setMinimumDuration(0);
2351 connect(progress, &QProgressDialog::canceled,
this, [
this]() {
2363 progress->setMaximum(total);
2364 progress->setLabelText(
2365 tr(
"Re-encrypting passwords: %1 of %2").arg(current).arg(total));
2371 progress->setValue(current);
2394 const QStringList &files,
2395 const QStringList &details) {
2400 QList<std::pair<QString, QString>> rows;
2401 for (qsizetype i = 0; i < files.size(); ++i) {
2405 std::sort(rows.begin(), rows.end());
2406 constexpr int kListed = 15;
2408 for (qsizetype i = 0; i < rows.size() && i < kListed; ++i) {
2409 lines << rows.at(i).first + QStringLiteral(
": ") + rows.at(i).second;
2411 if (rows.size() > kListed) {
2412 lines << tr(
"... and %n more",
nullptr,
2413 static_cast<int>(rows.size() - kListed));
2415 const int n =
static_cast<int>(files.size());
2417 this, tr(
"Re-encrypt these too?"),
2418 tr(
"%n entry(s) here would become readable by people on this "
2419 "folder's list who cannot read them now, and whom you did not just "
2420 "add, so they were left as they are. Someone who can read this "
2421 "folder may have copied them in from a folder they cannot read.",
2423 QStringLiteral(
"\n\n") + lines.join(QLatin1Char(
'\n')) +
2424 QStringLiteral(
"\n\n") +
2425 tr(
"Re-encrypt them for this folder's recipients? If not, they "
2426 "stay readable only by whoever they are encrypted to now."));
2437 if (identity.isEmpty()) {
2438 QMessageBox::information(
2439 this, tr(
"Export public key"),
2440 tr(
"<h3>Export your public key</h3>"
2441 "<p>No signing key is configured. Set one in QtPass Settings "
2442 "> GPG keys, or run this in a terminal:</p>"
2443 "<pre>gpg --armor --export --output my_key.asc <your-key-id"
2445 "<p>Then send the file to your teammates.</p>"));
2449 if (gpgExe.isEmpty()) {
2450 gpgExe = QStringLiteral(
"gpg");
2452 const QStringList keys = identity.split(
' ', Qt::SkipEmptyParts);
2456 if (
const std::optional<QHash<QString, QStringList>> held =
2457 pass->keyLinesHeldTwice(keys);
2458 !held || !held->isEmpty()) {
2460 this, tr(
"Export public key"),
2461 tr(
"Your key cannot be exported on its own:\n\n%1")
2474 QStringList{QStringLiteral(
"--armor"),
2475 QStringLiteral(
"--export")} +
2478 if (exitCode != 0 || stdOut.isEmpty()) {
2480 tr(
"Could not export public key for %1.\n\n%2")
2481 .arg(identity, stdErr.isEmpty()
2482 ? tr(
"No output from gpg.")
2508 this, tr(
"Not a folder of the store"),
2509 tr(
"%1 is, or lies behind, a symbolic link or junction. What that "
2510 "points to is not part of the password store and is left alone.")
2511 .arg(QDir::toNativeSeparators(QDir::cleanPath(dir))));
2516 QMessageBox::information(
2517 this, tr(
"Sharing passwords with GPG"),
2518 tr(
"<h3>Sharing passwords with GPG</h3>"
2519 "<p>To share passwords with other users:</p>"
2521 "<li><b>Export your public key</b> and send it to teammates</li>"
2522 "<li><b>Import teammates' public keys</b> into your GPG keyring</li>"
2523 "<li><b>Re-encrypt passwords</b> so all recipients can decrypt "
2526 "<p>Only people who have a matching secret key can decrypt the "
2528 "<p><b>Tip:</b> Use the same GPG key for all shared folders.</p>"
2529 "<p>See the FAQ for more details.</p>"));
2538 ui->actionPush->setVisible(usable);
2539 ui->actionUpdate->setVisible(usable);
2541 const QList<QAction *> actions =
ui->toolBar->actions();
2542 const qsizetype at = actions.indexOf(
ui->actionPush);
2543 if (at > 0 && actions.at(at - 1)->isSeparator()) {
2544 actions.at(at - 1)->setVisible(usable);
2554 ui->actionOtp->setVisible(
true);
2560 ui->grepButton->setVisible(enabled);
2561 ui->grepCaseButton->setVisible(enabled);
2563 ui->grepButton->setChecked(
false);
2568 ui->actionPush->setEnabled(state);
2569 ui->actionUpdate->setEnabled(state);
2588 ui->actionShowProcessOutput->setChecked(
void trackCopied(const QString &text)
Track text that got onto the clipboard some other way.
void copyText(const QString &text)
Copy text into the system clipboard (or the X11 primary selection when configured) and arm the autocl...
void statusMessage(const QString &message)
Something worth showing in the status bar happened.
The ConfigDialog handles the configuration interface.
void emptyClicked()
Emitted after deselect() has cleared the selection because of a single click on empty space or on a s...
static auto executeBlocking(const QString &app, const QStringList &args, const QString &input=QString(), QString *process_out=nullptr, QString *process_err=nullptr) -> int
Run a command synchronously and return its exit code.
static auto parseWslCommand(const QString &app) -> std::optional< WslCommand >
Parse a configured executable as a WSL command.
Dialog showing an ASCII-armored public GPG key for sharing.
Represents the parsed contents of a password file.
static auto boundedForDisplay(const QString &text) -> QString
text cut to kMaxDisplayLines lines, as getRemainingDataForDisplay() is: for showing an entry as it is...
static auto passwordLine(QStringView text) -> QString
The password of an entry: its first line, without the carriage return of a CRLF line end.
auto getNamedValues() const -> NamedValues
static auto parse(const QString &fileContent, const QStringList &templateFields, bool allFields, const std::function< bool(const QString &)> &alsoField={}) -> FileContent
parse parses the given fileContent in a FileContent object. The password is accessible through getPas...
auto getRemainingDataForDisplay() const -> QString
Like getRemainingData but without data that should not be displayed (like a TOTP secret).
auto getOtpUri() const -> QString
The entry's raw one-time password configuration, if it has one.
static auto isOtpPasswordLine(const QString &line) -> bool
Whether an entry's first line holds a TOTP shared secret rather than a password.
auto getPasswordForDisplay() const -> QString
Like getPassword but empty when the password line holds a TOTP shared secret (isOtpPasswordLine()).
The first start of QtPass: find GnuPG (and pass and Git), make sure there is a secret key,...
auto beginSearch() -> bool
Begin a search for a non-empty query.
auto leaveGrepMode() -> bool
Leave content-search mode (search button toggled off).
auto finishSearch() -> FinishOutcome
Record that a search finished and report required side effects.
void enterGrepMode()
Enter content-search mode (search button toggled on).
auto cancelSearch() -> bool
Cancel the current search (e.g. query cleared).
auto inGrepMode() const -> bool
Whether content-search mode is currently active.
Implementation that imitates 'pass' when the real tool is unavailable.
void unexpectedRecipients(const QString &dir, const QStringList &files, const QStringList &details)
A run left files alone: re-encrypting one would let someone on its folder's list read it who cannot n...
void reencryptProgress(int current, int total)
Re-encryption progress: current of total files checked.
void endReencryptPath()
A reencryptPath() run is over, whether it finished, failed, was cancelled or was refused; the main wi...
void startReencryptPath()
A reencryptPath() run is about to start its worker thread.
GrepSearchController m_grep
Mode/busy/cancelled state of the content search.
void dropStaleToolsAreaPalettes()
Drop a style-imposed menu bar or toolbar palette that belongs to the other theme (Breeze header palet...
void startReencryptPath()
Begin a re-encryption pass on the current path.
void addPassword()
Toolbar/context-menu "Add password": open PasswordDialog for a new entry in the current folder.
void closeEvent(QCloseEvent *event) override
Save window state and geometry on close.
void cancelOtpRequest()
Forget the pending OTP and copy requests.
void showContentResults(bool shown)
Show the content search results in place of the tree, or the tree again.
void renameFolder()
Context menu "Rename folder": ask for a new name and Move the current folder, refusing a target outsi...
void askReencryptUnexpected(const QString &dir, const QStringList &files, const QStringList &details)
Ask whether entries a re-encryption left alone, being encrypted to other keys than their folder had,...
void initTextBrowser()
Font, wrapping and link handling of the text browser, per the settings.
void enableGitButtons(const bool &state)
Enable or disable the Push and Pull actions together.
QPointer< Pass > m_refreshAfterPushOwner
void onConfig()
Toolbar "Config": config(), ignoring its result; refused while a backend still runs or waits,...
void initToolBarButtons()
~MainWindow() override
Save the window state (a quit from the tray menu or a SIGTERM never delivers closeEvent()) and delete...
void endReencryptPath()
Finish a re-encryption pass on the current path.
void onGrepFinished(const QList< QPair< QString, QStringList > > &results)
Handle results from a completed grep search.
void applySearchText(const QString &text)
Searches for text as qtpass(1) promises for the command line and for text handed over by another qtpa...
void setPassword(const QString &file, bool isNew=true)
Run PasswordDialog for a new or existing entry. For a new one the dialog gets the store's real folder...
QPointer< QObject > m_pendingOpen
void refreshMarkedSecrets(const AppSettings &s)
Hand the display panel what a template marks secret, in the settings or the store's ....
void executeWrapperStarted()
Slot called when an external process wrapper has started.
PasswordDisplayPanel * m_displayPanel
Renders decrypted fields into the grid; created in initDisplayPanel(), parented to this window.
void clearShownEntry(bool notify)
Empty the display panel and the text browser and close the QR code: the shown entry only....
void updateGitButtonVisibility(bool uiEnabled=true)
Show Push and Pull only when Git is in use; enable them only while the interface is.
void onDelete()
Toolbar "Delete" or the Delete key: confirm, then remove the current entry or folder....
void showEvent(QShowEvent *event) override
First-show hook used to focus the search input once the window is actually mapped (avoids races with ...
void editPassword(const QString &file)
Open PasswordDialog on an existing entry, after a blocking pull when auto-pull is on....
void changeEvent(QEvent *event) override
React to language or window state changes.
QPointer< QProgressDialog > m_reencryptProgress
void on_profileBox_currentTextChanged(const QString &name)
The user picked another profile: save its store, key and Git flags as the active settings,...
void addFolder()
Toolbar/context-menu "Add folder": ask for a name, create the folder under the current one (refusing ...
void updateGrepButtonVisibility()
auto grepLineForDisplay(const QString &line, const AppSettings &s) const -> QString
A content search match as the results list shows it, by the display panel's rules: a one-time passwor...
ProcessOutputPanel * m_processOutput
void messageAvailable(const QString &message)
Handle an incoming inter-process message (single-instance mode).
MainWindow(const QString &searchText=QString(), QWidget *parent=nullptr)
Construct the main window.
void copyPasswordFromTreeview()
Ctrl+C on the tree: decrypt the current entry and let passwordFromFileToClipboard() copy its first li...
void connectPassSignals(Pass *pass)
Connect the signals of one backend that the window answers itself: errors, critical messages,...
StoreTree * m_tree
The store as shown in the tree: models, view setup, path mapping.
void reencryptProgress(int current, int total)
Update the re-encryption progress dialog.
void keyPressEvent(QKeyEvent *event) override
Handle keyboard shortcuts.
void addShareMenu(QMenu &contextMenu, const AppSettings &s)
Add the Share submenu for the folder under the cursor: the entries are enabled only where a recipient...
void on_treeView_doubleClicked(const QModelIndex &index)
A double-click on a tree entry opens it for editing; folders are left to the view.
void showShareHelp()
Share menu "What is this?": the explanation of sharing with GPG.
auto exactMatch() -> QModelIndex
The entry whose name is exactly the search text, if the filtered tree shows it: team/bank for "team/b...
void onTimeoutSearch()
searchTimer fired: filter the tree on the typed words (matched literally, in order,...
void onPush()
Trigger a git push operation.
void showStatusMessage(const QString &msg, int timeout=2000)
Show a message in the status bar for the given duration.
void focusInput()
Select-all and focus the search box once the window is visible; sets m_firstShowCompleted only on suc...
void on_lineEdit_returnPressed()
Enter in the search box: in content-search mode start (or, for an empty query, cancel) the grep; othe...
auto refuseLinkedFolder(const QString &dir) -> bool
Refuse, with a message, a tree-picked folder that is or lies behind a symlink or junction: what it po...
QString m_copyRequestFile
void on_grepButton_toggled(bool checked)
The content-search toggle changed: switch the search box between name filtering and regex content sea...
auto confirmDeletion(const QString &file, bool isDir) -> bool
Ask before deleting an entry or a folder, naming what goes and warning when the folder holds anything...
void onOperationError()
An operation ended in an error before or instead of a result: forget the pending requests and what th...
static constexpr int kMaxFlashCharacters
Most characters the text panel keeps of appended output.
void updateProcessOutputVisibility()
void on_grepResultsList_itemClicked(QTreeWidgetItem *item, int column)
A content-search result was clicked: select the entry in the tree, show it, and go back to the tree (...
void reencryptPath(const QString &dir)
Share menu "Re-encrypt all passwords": confirm, lock the UI via startReencryptPath() and have Imitate...
void passwordFromFileToClipboard(const QString &text, const QString &file)
Copy the first line of a decrypted entry (Ctrl+C). Ignores decrypts of anything but the entry copyPas...
auto confirmPathInStore(const QString &candidate) -> bool
Guard the input dialogs (create, move, rename) against names like ../../etc/passwd or absolute paths ...
void onAutoPush()
Trigger the automatic git push after a change (QtPass::pushRequested()); see Pass::GitPushAutomatic()...
auto backOnMenuEntry(const QString &openedOn) -> bool
Make the entry a tree menu was opened on current again, for the action picked from it: the current in...
void showContextMenu(const QPoint &pos)
Build and show the tree's context menu for the item under the cursor: folder actions (open,...
void updateProfileBoxEnabled()
Enable the profile box only when there is more than one profile, the interface is enabled and the bac...
void critical(const QString &title, const QString &msg)
Display a critical error dialog.
void clearContentResults()
Empty the content search results and, if they were showing, put the tree back and leave content searc...
void applyWindowFlagsSettings()
void updateProfileBox()
Fill the profile box from the settings, the active profile selected, without switching profiles while...
void updateOtpButtonVisibility(bool uiEnabled=true)
Refresh the OTP toolbar action from settings.
QString m_refreshAfterPush
void addRecipient(const QString &dir)
Share menu "Add recipient": open UsersDialog for dir (keys already in the keyring only).
bool m_firstShowCompleted
Set once focusInput() has actually focused the search box, so later show events leave the focus alone...
void onEdit()
Toolbar "Edit" or a double-click: editPassword() on the current entry.
void restoreWindow()
Restore window geometry and state from saved settings.
auto exactMatchPath() -> QString
The entry file named exactly as the search text, spaces around the text included; failing that,...
void onOtp()
Toolbar "OTP": copy the current entry's one-time code. Uses the code the panel already shows for this...
auto confirmLinkRemoval(const QString &file) -> bool
Ask before removing a folder that is a link, which takes the link and leaves what it points to.
void showBrowserContextMenu(const QPoint &pos)
Show the text browser's standard context menu, reparented to the window so the browser's stylesheet d...
QScopedPointer< Ui::MainWindow > ui
The widgets generated from mainwindow.ui.
auto eventFilter(QObject *obj, QEvent *event) -> bool override
Filter events from watched objects.
auto browserContextMenu(const QPoint &pos) -> QMenu *
The text browser's standard context menu, with "Copy Link Location" copying through ClipboardMa...
QPushButton * m_stopButton
void showAbout()
Show the About box: version, project link, licence.
static constexpr int UiWatchdogMs
Interval of m_uiWatchdog in milliseconds.
void openFolder()
Context menu "Open folder with file manager" on the current folder.
void exportPublicKey()
Share menu "Export my public key": run gpg --armor --export for the configured signing key and show t...
void openExactMatch(const QModelIndex &index)
Makes index current and opens it, as a click on it would.
QPointer< QProgressDialog > m_progressToDelete
void initTrayIcon()
Create m_tray and add the menu bar toggle to its menu; gives up (m_tray stays null) when no system tr...
void flashText(const QString &text, const bool isError, const bool isHtml=false)
Display a transient message in the text panel.
void initStatusBar()
Welcome message and the permanent logo in the status bar.
void initDisplayPanel()
The grid of decrypted fields and what its buttons ask for.
void otpFromFileToClipboard(const QString &output, const QString &file)
Generate a one-time password from decrypted content and copy it. Ignores decrypts of anything but the...
void clearPanel(bool notify=true)
Empty the display panel and the text browser, and leave content search if its results were showing.
void setUiElementsEnabled(bool state)
Enable or disable the main UI elements.
auto event(QEvent *event) -> bool override
Notice an application palette change, the theme switch that makes a style-imposed bar palette suspect...
void applyTextBrowserSettings()
auto config() -> bool
Open the configuration dialog.
auto getCurrentTreeViewIndex() -> QModelIndex
Return the currently selected index in the tree view.
void cancelContentSearch()
void onUpdate(bool block=false)
Toolbar "Update": git pull.
void deselect()
Clear the current tree view selection.
auto getFile(const QModelIndex &index, bool forPass) -> QString
StoreTree::fileFor() on the tree.
void onProcessOutput(const QString &output, bool isError, Enums::PROCESS pid=Enums::INVALID)
Handle generic process output for display in output panel.
void passShowHandler(const QString &output, const QString &file=QString())
Render a decrypted entry: fields into the display panel, the rest into the text browser,...
void on_treeView_clicked(const QModelIndex &index)
Handle a click on an item in the tree view.
void onUsers()
Toolbar/context-menu "Users": open UsersDialog for the current folder, unless it lies behind a link.
void destroyTrayIcon()
Delete m_tray and reset it to null.
QtPass * m_qtPass
The UI-neutral glue to the backends (output, status, clipboard, QR codes); created in the constructor...
auto firstFile(QModelIndex parentIndex) -> QModelIndex
Depth-first search for the first entry under a folder.
void renamePassword()
Context menu "Rename password": ask for a new name and Move the current entry within its folder,...
void on_lineEdit_textChanged(const QString &arg1)
The search box changed (name filtering only): drop the pending decrypt and the panel,...
void copySelectionOrPassword()
Ctrl+C anywhere in the window: the selected text when the focus is in a text view or a selectable lab...
static auto isPasswordMatch(const QString &line) -> bool
Whether a line in a result is a match in the entry's first line, the password: passwordMatchText() is...
static auto isMoreMarker(const QString &line) -> bool
Whether a line in a result is the marker for "more matches inthis entry" rather than a match.
static auto passwordMatchText(const QString &line) -> QString
The text of a match isPasswordMatch() accepts.
static auto isStoppedMarker(const QPair< QString, QStringList > &result) -> bool
Whether a result is the marker for "the search stopped atkMaxMatches, more entries were not searched"...
static auto isOtpMarker(const QString &line) -> bool
Whether a line in a result stands for a match in a line holding a one-time password secret (FileConte...
Abstract base class for password store operations.
auto exportPublicKeys(const QString &gpg, const QStringList &keys, QString *out, QString *err) -> int
gpg --armor --export of keys, in the store's environment: the keyring keyLinesHeldTwice() reads.
void startingExecuteWrapper()
Emitted each time a queued process is about to start, and by the refusals that go on to emit processE...
void finishedAnyWithPid(const QString &out, const QString &err, Enums::PROCESS pid)
A process of any kind finished successfully and its output cannot contain a secret.
auto isPushing() const -> bool
Whether a Git push of this backend is queued or running.
static auto getGpgIdPath(const QString &for_file, const QString &passStore) -> QString
Get .gpg-id file path for a password file.
auto reportedInsert() const -> QString
The entry whose insert is reporting now: set while finishedInsert() or insertFailed() goes out,...
static auto describeKeyLinesHeldTwice(const std::optional< QHash< QString, QStringList > > &held) -> QString
A message naming each line keyLinesHeldTwice() found and what the user can do about it.
void statusMsg(const QString &msg, int timeout)
Progress or a non-fatal problem worth a line in the status bar ("Creating backup commit",...
auto runningProcess() const -> Enums::PROCESS
What kind of command is running now.
virtual void Show(QString file)=0
Show decrypted password file.
auto isIdle() const -> bool
Whether no gpg, git or pass of this backend runs or waits.
void finishedShow(const QString &out, const QString &file, bool lossless=true)
Emitted when a Show() succeeds.
void finishedGrep(const QList< QPair< QString, QStringList > > &results)
The newest Grep() is over; an empty list means no entry matched.
void finishedGitPush(const QString &out, const QString &err)
git push succeeded.
void processErrorExit(int exitCode, const QString &err)
An operation ended in failure: its process exited non-zero, could not be started or crashed,...
auto stopRunning() -> bool
Stop the queued command that is running now (Executor::stopRunning()); it then ends as a failed run.
auto runningSerial() const -> quint64
Which run is going (Executor::runningSerial()).
void updateEnv()
Update environment for subprocesses.
void idle()
Nothing of the store's runs or waits any more (isIdle()).
void critical(const QString &title, const QString &message)
Something went wrong that the user has to be told about in a dialog, such as a refused path or a fail...
static constexpr int kBlockingPullMs
How long the pull before an edit may block the window.
Dialog for creating a password entry or editing an existing one.
void setAvailableTemplates(const QHash< QString, QStringList > &templates, const QString &defaultTemplate)
Set available templates from file and select default.
void copied(const QString &text)
Text was copied out of the password, a field or the body, marked as a secret: for ClipboardManager::t...
void setNewEntryLocation(const QString &storeRoot, const QStringList &folders, const QString ¤tFolder)
Let a new entry be named inside the dialog: a folder picker over the store's folders and a name field...
auto isSecret(const QString &field, const AppSettings &s) const -> bool
Whether a field is a secret "Hide password" hides: one a template marks (setMarkedSecrets()),...
void qrRequested(const QString &text)
Emitted when a field's QR button is clicked.
void refreshPalette()
Re-derive palette-dependent styling after a runtime theme change.
void setMarkedSecrets(const QStringList &names)
Set the field names a template marks as secret.
void displayFields(const QString &password, const NamedValues &namedValues, const AppSettings &s, const QString &otpConfig={})
Render the password and template fields of a decrypted entry.
void clear()
Remove all field rows and collapse the container spacing.
PasswordDisplayPanel(QGridLayout *grid, QBoxLayout *container, QWidget *widgetParent, QObject *parent=nullptr)
Construct a panel that renders into the given layouts.
void textCopied(const QString &text)
Text was selected and copied out of a field's value (Ctrl+C, the context menu, a drag,...
void copyRequested(const QString &text)
Emitted when a field's copy button is clicked.
auto currentOtpCode() const -> QString
The one-time password currently on display, if there is one.
void editRequested()
Emitted on a double-click anywhere on a field row: the user wants to change what they are looking at.
static auto isPathInStore(const QString &storeRoot, const QString &candidate) -> bool
Check that a candidate path resolves inside the password store root, after following symlinks and res...
static auto isSensitiveProcess(Enums::PROCESS pid) -> bool
Whether a process's output may carry secrets and must never reach this long-lived panel (pass show,...
ProcessOutputPanel(QWidget *parent=nullptr)
Build the console (Clear button + read-only text edit).
static auto processName(Enums::PROCESS pid) -> QString
Human-readable command label for a process id.
void append(const QString &output, bool isError, const QString &linePrefix=QString())
Append output, one numbered line per non-empty input line.
void operationFinished()
A backend operation is over, successfully or not; the interface can be enabled again.
void statusMessage(const QString &message, int timeout)
A short message for the status bar.
static auto formatOutput(QString output, const QString &prefix=QString(), const QString &postfix=QString(), bool links=true) -> QString
Turn a process' plain-text output into the HTML the text browser shows: http(s) URLs become links,...
void entryInserted()
An entry was written; the view of the current entry is stale.
void pushRequested()
The store changed and the settings ask for an automatic push.
void outputReady(const QString &html)
Formatted output (see formatOutput()) or an error rendered in colour, ready for the text browser.
auto clipboard() -> ClipboardManager &
The clipboard handling for this application instance.
void init()
Resolve the password store and the executables and migrate the settings of an older version (fresh-in...
QtPass(QObject *parent=nullptr)
Construct the glue and connect it to both pass backends.
void closeQRCode()
Close the QR code popup showTextAsQRCode() has open, if any: the autoclear of the panel takes the cod...
void showTextAsQRCode(const QString &text)
Render text as a QR code with qrencode and show it in a popup at the cursor; failures are reported th...
static auto getInstance() -> QtPassSettings *
Get the singleton instance.
static auto getPass() -> Pass *
Get currently active pass backend instance.
static auto isUseGit(const bool &defaultValue=QVariant().toBool()) -> bool
Check whether Git integration is enabled.
static auto isUseOtp(const bool &defaultValue=true) -> bool
Check whether OTP support is enabled.
static auto getPassStore(const QString &defaultValue=QVariant().toString()) -> QString
Get password store directory path.
static auto load() -> AppSettings
Load all flat settings into an AppSettings value object.
static auto isUseGrepSearch(const bool &defaultValue=false) -> bool
Check whether content search is enabled.
static auto getProfiles() -> Profiles
Get all configured profiles.
static auto getRealPass() -> RealPass *
Get real pass backend instance.
static auto getProfile(const QString &defaultValue=QVariant().toString()) -> QString
Get active profile name.
static auto isShowProcessOutput(const bool &defaultValue=false) -> bool
Get showProcessOutput setting.
static void setSavestate(const QByteArray &saveState)
Save window state.
static auto isAlwaysOnTop(const bool &defaultValue=QVariant().toBool()) -> bool
Check whether main window should stay always on top.
static auto getImitatePass() -> ImitatePass *
Get imitate pass backend instance.
static auto isHideOnClose(const bool &defaultValue=QVariant().toBool()) -> bool
Check whether closing the window hides the application.
static void save(const AppSettings &settings)
Persist an AppSettings value object to the singleton store.
static void setGeometry(const QByteArray &geometry)
Save window geometry.
static auto getGeometry(const QByteArray &defaultValue=QVariant().toByteArray()) -> QByteArray
Get saved window geometry.
static auto loadEffective() -> AppSettings
load() with the active profile's own Git flags applied: what the backends and the Git actions run wit...
static auto getSavestate(const QByteArray &defaultValue=QVariant().toByteArray()) -> QByteArray
Get saved window state.
static auto backendsIdle() -> bool
Whether no backend, the active one or one kept from before a switch, runs or waits for anything (Pass...
void copied(const QString &text)
Selected text was copied out of the browser.
static const QString firstRunPending
Set on a fresh install until QtPass is first set up: the first-run wizard finished,...
QSortFilterProxyModel for filtering and displaying password store.
static auto wordsFilter(const QString &query) -> QRegularExpression
The tree filter for what is typed in the search box.
auto hasChildren(const QModelIndex &parent=QModelIndex()) const -> bool override
No children for a link inside the store: it is listed by name but never entered, so the view shows no...
auto fileInfo(const QModelIndex &index) const -> QFileInfo
File system information for a view index.
auto rootIndex() -> QModelIndex
The proxy's root index for the current store.
void setFilter(const QRegularExpression &pattern)
Filter the visible entries.
void directoryLoaded(const QString &path)
The file system model the view shows finished listing a folder; also once for the store root after re...
StoreTree(QTreeView *view, QObject *parent=nullptr)
Attach the proxy model to the view and set its look: hidden header, indentation, scroll bars,...
void setStore(const QString &path)
Point everything at path: file system root, proxy store and view root index. Also drops a search filt...
auto fileSystem() -> QFileSystemModel &
auto indexFor(const QString &path) const -> QModelIndex
The view index for an absolute path, or invalid when the file system model does not (yet) know it.
void currentEntryLost(const QString &path)
After a reload() the current entry or folder could not be shown again: it was removed or renamed,...
auto proxy() -> StoreModel &
void setPass(Pass *pass)
Hand the proxy the backend it drops onto.
auto currentDir(bool forPass) const -> QString
dirFor() applied to the view's current index.
static auto readTemplates(const QString &storePath) -> QHash< QString, QStringList >
Read templates from .templates file in password store.
static auto fieldsIn(const QString &templateText) -> QStringList
The field names of the template in the settings: one per line, with comment lines (starting with #,...
static auto getFolderTemplate(const QString &folderPath, const QString &storePath) -> QString
Get default template for a folder. Looks in folder, then parent folders up to root.
static auto readSecretFields(const QString &storePath) -> QStringList
The field names the store's .templates file marks as secret, in any of its sections (see secretFields...
static auto secretFieldsIn(const QString &templateText) -> QStringList
The field names a template marks as secret.
static auto generateNow(const Settings &settings) -> QString
Generate the code for the current wall-clock time.
static auto parse(const QString &config, Refusal *why=nullptr) -> std::optional< Settings >
Parse an OTP configuration string.
static auto describe(Refusal why) -> QString
One sentence for the user on why a configuration gives no code.
Refusal
Why parse() gave no settings, so the user can be told more than "invalid".
@ None
Parsed: there was nothing to refuse.
void addToggle(QAction *action)
Put one of the window's toggles in the tray menu, above Quit.
TrayIcon(QMainWindow *parent)
Construct a TrayIcon associated with the given main window.
auto getIsAllocated() -> bool
Check whether tray resources have been allocated and initialized.
Dialog for selecting GPG recipients for password encryption.
static auto hasLongUnbrokenRun(QStringView text) -> bool
Whether text holds more than kMaxUnbrokenRun characters in a row without white space Qt wraps at (a n...
static auto isUnderLink(const QString &path, const QString &storeRoot, bool includeSelf=true) -> bool
Whether the way from storeRoot down to path passes through a symbolic link or NTFS junction: path its...
static auto findPasswordStore() -> QString
Locate the password store directory.
static auto configIsValid(const AppSettings &s) -> bool
Verify that the required configuration is complete.
static auto regularFilesUnder(const QString &dir, const QStringList &nameFilters, QStringList *skipped=nullptr, bool hiddenFiles=false, QStringList *unlisted=nullptr) -> QStringList
Regular files under dir whose name matches one of nameFilters, found by walking only real directories...
static auto mkpathForStore(const QString &path) -> bool
Create path and any missing parents as pass would.
static auto displayable(const QString &text, bool lineBreaks=true) -> QString
text with the characters that change how the text around them reads replaced by U+FFFD,...
static auto isLinkedFolder(const QString &path) -> bool
Whether path names a symbolic link or NTFS junction, with or without a trailing separator (which woul...
static auto joinPath(const QString &dir, const QString &name) -> QString
name in dir, as the file system means it.
static auto shownName(const QString &name, qsizetype max=kMaxShownName) -> QString
A name or path from the store, as a label or list shows it: one line, at most max characters.
static auto directoriesUnder(const QString &dir) -> QStringList
Every real, visible directory under dir, walked by the same rules as regularFilesUnder(): links,...
Settings dialog: every page of the configuration window and the profile table, with the validation th...
The Enums namespace: clipboard behaviour and the identifiers of the subprocess kinds QtPass queues.
Executor, the FIFO queue every gpg, git and pass child process of QtPass goes through,...
Dialog that shows an ASCII-armored public key and lets the user copy it or save it as a ....
Parser for a decrypted password entry: password line, key: value fields, remaining text and the OTP c...
The first-run wizard and its four pages: programs, key, store and summary.
static auto runLabel(Enums::PROCESS pid) -> QString
What the Stop button calls a run.
MainWindow: the main application window (tree, toolbar, search, status bar, process output dock) and ...
auto processLabel(PROCESS pid) -> QString
The command label for pid, as the output panel shows it.
PROCESS
Identifies different subprocess operations used in QtPass.
auto confirmPassRun(QWidget *parent, const QString &store, const std::function< QStringList()> &check) -> bool
Run check (which lists the entries a pass run would give new readers, one gpg call each) under a wait...
auto askYes(QWidget *parent, const QString &title, const QString &text) -> bool
Ask a yes/no question in plain text.
void warning(QWidget *parent, const QString &title, const QString &text)
Show a warning in plain text.
void critical(QWidget *parent, const QString &title, const QString &text)
Show an error in plain text.
void centreOnCursorScreen(QWidget &window)
Move window so its frame is centred on the screen under the mouse pointer (the primary screen when th...
NativeGrep, the content search that decrypts every entry on a worker thread instead of running pass g...
Dialog for creating or editing one password entry, including the generator, template fields,...
PasswordDisplayPanel: renders the decrypted fields of an entry (password, template fields,...
PathValidator: is a path inside the password store, and how is it spelled relative to the store root.
QMessageBox helpers that force Qt::PlainText so store-controlled names can never be read as rich-text...
Enums::ProcessInfo, the one table that names each kind of subprocess and says whether its output may ...
ProcessOutputPanel: the dockable console that shows numbered, colour-coded git/pass/gpg output.
QMap< QString, Profile > Profiles
All profiles by name. QMap so iteration order is the name order.
QtPass: UI-neutral glue that turns backend completion signals into formatted output,...
The "qtpass" logging category.
QtPassSettings, the QSettings singleton behind every saved setting, the profiles and the Pass backend...
Plain value-object holding all flat QtPass configuration.
bool displayAsIs
Show file content unmodified.
QString gpgExecutable
Path to the gpg/gpg2 executable.
QString passSigningKey
GPG key used to sign .gpg-id files.
bool usePass
Use the pass CLI (true) or native git/gpg.
bool hideContent
Hide the entire content panel.
bool useOtp
Enable native TOTP (OTP) support.
QString passStore
Password-store root path.
bool useAutoclearPanel
Clear the content panel after a delay.
bool noLineWrapping
Disable line wrapping in the panel.
bool showMenuBar
Show the menu bar (Ctrl+M toggles it).
QString gitExecutable
Path to the git executable.
bool autoPull
git pull before an entry is edited and before a re-encryption.
int autoclearPanelSeconds
Panel autoclear delay (seconds).
bool startMinimized
Start the window minimised.
bool useTrayIcon
Show a system tray icon.
QString passExecutable
Path to the pass executable.
bool useGit
Enable git integration.
QString passTemplate
Newline-separated template field names.
bool useMonospace
Render content in a monospace font.
bool templateAllFields
Treat every key: line as a field.
QString activeProfile
Name of the active profile.
bool useTemplate
Use the password template.
Outcome of a search-completion transition.
bool discard
The finished search was cancelled; ignore results.
bool restoreCursor
A wait cursor was active and must be restored.
One named password store: where it is, how its .gpg-id is signed and, optionally, its own Git switche...
QString path
Password store directory.
QString signingKey
Key(s) that sign this store's .gpg-id.
TemplateIO: the store's .templates and .default_template files and the # secret: marker in template t...
RFC 6238 TOTP: otpauth URI parsing, code generation and canonical re-serialisation.
TrayIcon: the system tray icon and its context menu that show, hide, minimise, maximise,...
UsersDialog, the recipient picker for a folder's .gpg-id.
Util: static helpers for the process environment, binary discovery, store paths, URL safety and the l...
constexpr int MS_PER_SECOND
Milliseconds in a second, for timers set from a setting in seconds.
WindowStateStore: saves and restores top-level window geometry through QtPassSettings,...