QtPass 2.0.0
Developer documentation
Loading...
Searching...
No Matches
mainwindow.cpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2014 Anne Jan Brouwer
2// SPDX-License-Identifier: GPL-3.0-or-later
9#include "mainwindow.h"
10
11#include "qtpasslogging.h"
12
13#include "configdialog.h"
14#include "enums.h"
15#include "executor.h"
17#include "filecontent.h"
18#include "firstrunwizard.h"
19#include "menubarpeek.h"
20#include "nativegrep.h"
21#include "passworddialog.h"
23#include "pathvalidator.h"
24#include "plainmessagebox.h"
25#include "processinfo.h"
26#include "processoutputpanel.h"
27#include "qpushbuttonasqrcode.h"
30#include "qtpass.h"
31#include "qtpasssettings.h"
32#include "templateio.h"
33#include "totp.h"
34#include "trayicon.h"
35#include "ui_mainwindow.h"
36#include "usersdialog.h"
37#include "util.h"
38#include "windowstatestore.h"
39#include <QApplication>
40#include <QCloseEvent>
41#include <QDate>
42#include <QDesktopServices>
43#include <QDialog>
44#include <QDockWidget>
45#include <QFileInfo>
46#include <QFileSystemModel>
47#include <QHBoxLayout>
48#include <QInputDialog>
49#include <QLabel>
50#include <QLineEdit>
51#include <QMenu>
52#include <QMenuBar>
53#include <QMessageBox>
54#include <QProgressDialog>
55#include <QPushButton>
56#include <QScrollBar>
57#include <QShortcut>
58#include <QTextBlock>
59#include <QTextCharFormat>
60#include <QTextCursor>
61#include <QTextDocument>
62#include <QTextEdit>
63#include <QTextStream>
64#include <QTimer>
65#include <QTreeWidget>
66#include <QUrl>
67#include <algorithm>
68#include <utility>
69
77static auto runLabel(Enums::PROCESS pid) -> QString {
78 if (pid == Enums::PASS_SHOW) {
79 return QCoreApplication::translate("MainWindow", "a decrypt");
80 }
81 const QString label = Enums::processLabel(pid);
82 return label.isEmpty()
83 ? QCoreApplication::translate("MainWindow", "a command")
84 : label;
85}
86
87MainWindow::MainWindow(const QString &searchText, QWidget *parent)
88 : QMainWindow(parent), ui(new Ui::MainWindow) {
89#ifdef __APPLE__
90 // extra treatment for mac os
91 // see https://doc.qt.io/qt-6/qkeysequence.html#qt_set_sequence_auto_mnemonic
92 qt_set_sequence_auto_mnemonic(true);
93#endif
94 ui->setupUi(this);
95
96 m_qtPass = new QtPass(this);
99
100 // Every Copy binding, not only the first (Ctrl+C): Ctrl+Insert and F16
101 // otherwise reached the views' own copy, which put decrypted text on the
102 // clipboard bare, without the secret hint or the autoclear.
103 const QList<QKeySequence> copyKeys =
104 QKeySequence::keyBindings(QKeySequence::StandardKey::Copy);
105 for (const QKeySequence &keys : copyKeys) {
106 new QShortcut(keys, this, this, &MainWindow::copySelectionOrPassword);
107 }
108
109 m_tree = new StoreTree(ui->treeView, this);
112 connect(ui->treeView, &QWidget::customContextMenuRequested, this,
114 connect(ui->treeView, &DeselectableTreeView::emptyClicked, this,
116
118
120
122
123 QtPassSettings::getPass()->updateEnv();
124
125 // Install the search-box key filter once, not on every setUiElementsEnabled
126 // call.
127 ui->lineEdit->installEventFilter(this);
128 // Both live in Breeze's "tools area" and get its header palette; see the
129 // PaletteChange branch in eventFilter().
130 ui->toolBar->installEventFilter(this);
131 menuBar()->installEventFilter(this);
132
133 initTimers();
134
138
139 ui->lineEdit->setClearButtonEnabled(true);
141
143
144 // No QApplication::quit() here: before exec() it is a documented no-op.
145 // main() checks initSucceeded() and exits before show() instead.
146 m_qtPass->init();
147 // OK is not gated on Util::configIsValid(): an accepted configuration can
148 // still lack a .gpg-id, so ask again; only a cancel ends the loop.
150 if (!config()) {
151 return;
152 }
153 }
154 // Set up, with or without the wizard (a fresh install can find a store
155 // that already works): a later run of the wizard keeps the saved backend
156 // and Git choices. A cancelled first run returned above and keeps it.
158 m_freshStart = false;
159 m_initSucceeded = true;
160
161 // Searched as qtpass(1) promises, once the window and its tree are up:
162 // filtered at once and an entry named exactly so opened. Setting the
163 // text here left it to the search timer, which only highlights. Queued
164 // only now: from before the configuration loop, a wizard's nested event
165 // loop ran it while no store was set yet.
166 if (!searchText.isEmpty()) {
167 QTimer::singleShot(0, this,
168 [this, searchText] { applySearchText(searchText); });
169 }
170
171 // Initial focus is set in showEvent(): a 10 ms QTimer here could fire
172 // before the window was realised (queued ActivationChange, nested exec() in
173 // init()) and selectAll() segfaulted inside Qt (#1187, #1188).
174}
175
177 connect(m_qtPass, &QtPass::outputReady, this,
178 [this](const QString &html) { flashText(html, false, true); });
179 connect(m_qtPass, &QtPass::operationFinished, this,
180 [this]() { setUiElementsEnabled(true); });
181 connect(m_qtPass, &QtPass::statusMessage, this,
184 // With automatic push, the push is queued first and the refresh would start
185 // as soon as it ends, emptying the browser before a failed push's error was
186 // painted. So the refresh waits for the push (see connectPassSignals()). It
187 // claims the panel now, as its decrypt would: whatever drops a pending
188 // decrypt (another entry, a search, Escape, Edit, an error) drops it too.
189 connect(m_qtPass, &QtPass::entryInserted, this, [this]() {
190 const QModelIndex index = getCurrentTreeViewIndex();
191 const QString file = getFile(index, true);
193 // Only the entry the save wrote is shown again, when it is the selected
194 // one. After Add, or a save that reports once another row is selected,
195 // the selected row is another entry: showing it decrypted it once more
196 // and, with "Always copy", put its password on the clipboard.
197 if (const QString saved = pass->reportedInsert();
198 !saved.isEmpty() &&
199 QDir::cleanPath(saved) != QDir::cleanPath(getFile(index, false))) {
200 return;
201 }
202 if (!file.isEmpty() && pass->isPushing()) {
203 m_refreshAfterPush = file;
205 m_shownFile = file;
206 return;
207 }
208 on_treeView_clicked(index);
209 });
211 [this](const QString &message) { showStatusMessage(message); });
212 // Both backends: the active one can change through the configuration
213 // dialog without a restart.
217 connect(ipass, &ImitatePass::startReencryptPath, this,
219 connect(ipass, &ImitatePass::reencryptProgress, this,
221 connect(ipass, &ImitatePass::endReencryptPath, this,
223 connect(ipass, &ImitatePass::unexpectedRecipients, this,
225}
226
228 {
230 if (s.useMonospace) {
231 QFont monospace("Monospace");
232 monospace.setStyleHint(QFont::Monospace);
233 ui->textBrowser->setFont(monospace);
234 }
235 if (s.noLineWrapping) {
236 ui->textBrowser->setLineWrapMode(QTextBrowser::NoWrap);
237 }
239 clearResultsTimer.setInterval(clearPanelTimer.interval());
240 }
241 ui->textBrowser->setOpenExternalLinks(true);
242 ui->textBrowser->setContextMenuPolicy(Qt::CustomContextMenu);
243 connect(ui->textBrowser, &QWidget::customContextMenuRequested, this,
245}
246
249 ui->gridLayout, ui->verticalLayoutPassword, this, this);
254 connect(ui->textBrowser, &SecretTextBrowser::copied, &m_qtPass->clipboard(),
258 // Double-click on what is shown edits it, as in the tree.
259 // The entry whose rows were double-clicked, not the tree's current row:
260 // arrow keys and a right-click move that row without repainting the panel.
262 if (ui->actionEdit->isEnabled() && !m_panelEntry.isEmpty()) {
264 }
265 });
266}
267
269 clearPanelTimer.setSingleShot(true);
270 connect(&clearPanelTimer, &QTimer::timeout, this,
271 [this]() { clearShownEntry(true); });
272 clearResultsTimer.setSingleShot(true);
273 connect(&clearResultsTimer, &QTimer::timeout, this,
275
276 searchTimer.setInterval(350);
277 searchTimer.setSingleShot(true);
278
279 connect(&searchTimer, &QTimer::timeout, this, &MainWindow::onTimeoutSearch);
280
281 // Safety net: if a backend operation disables the UI but never signals
282 // completion, re-enable after a timeout so the window can't get stuck.
283 m_uiWatchdog.setSingleShot(true);
284 m_uiWatchdog.setInterval(UiWatchdogMs);
285 connect(&m_uiWatchdog, &QTimer::timeout, this, [this]() {
286 showStatusMessage(tr("Operation timed out; re-enabling interface."));
287 // What still runs can be stopped: a store entry built to keep gpg busy
288 // holds up everything queued behind it. No timer stops it by itself, as
289 // a decrypt may be waiting for a passphrase.
290 if (Pass *pass = QtPassSettings::getPass();
291 pass != nullptr && !pass->isIdle()) {
292 m_stopButton->setToolTip(tr("Stop %1, which is still running")
293 .arg(runLabel(pass->runningProcess())));
294 m_stopButton->show();
295 }
296 // Drop any in-flight OTP request so a late finishedShow cannot be mistaken
297 // for the answer to it.
300 });
301}
302
305 addDockWidget(Qt::BottomDockWidgetArea, m_processOutput);
306 // After addDockWidget so our preference wins over any cached state
307 // QMainWindow applies; restoreWindow() already processed the saved layout.
309 // From the setting, not isVisible(): the window is not shown yet, so no
310 // child of it reports visible.
311 ui->actionShowProcessOutput->setChecked(
313 connect(ui->actionShowProcessOutput, &QAction::toggled, this,
314 [this](bool show) {
315 m_processOutput->setVisible(show);
316 AppSettings s = QtPassSettings::load();
317 if (s.showProcessOutput != show) {
318 s.showProcessOutput = show;
319 QtPassSettings::save(s);
320 }
321 });
322
324 [this](const QString &out, const QString &err, Enums::PROCESS pid) {
325 // Never route potentially-secret output through the panel:
326 // PASS_SHOW goes to the text browser (cleared on a timer when
327 // "Autoclear panel" is set),
328 // PASS_GREP would return password-file lines (#252; it is no
329 // longer started, the check stays), and PASS_INSERT
330 // is excluded defensively in case a future path uses --echo.
332 return;
333 }
334 if (!out.isEmpty()) {
335 onProcessOutput(out, false, pid);
336 }
337 if (!err.isEmpty()) {
338 onProcessOutput(err, true, pid);
339 }
340 });
341}
342
344 // Quit from the tray menu or a SIGTERM never delivers closeEvent(); the
345 // window still knows its last geometry here.
347 delete m_qtPass;
348}
349
350// The signals of one backend that the window answers itself.
352 // A failed decrypt never emits finishedShow; drop the pending OTP/copy
353 // request so a later decrypt of the same entry is not taken as its answer.
355 connect(pass, &Pass::critical, this, &MainWindow::critical);
356 connect(pass, &Pass::startingExecuteWrapper, this,
358 // The profile box comes back when the queue is done, also after the
359 // watchdog released the rest of the interface early.
360 connect(pass, &Pass::idle, this, &MainWindow::updateProfileBoxEnabled);
361 // The button names what it stops, also once the queue moved on.
362 connect(pass, &Pass::startingExecuteWrapper, this, [this, pass]() {
363 if (m_stopButton != nullptr && !m_stopButton->isHidden()) {
364 m_stopButton->setToolTip(tr("Stop %1, which is still running")
365 .arg(runLabel(pass->runningProcess())));
366 }
367 });
368 // Nothing left to stop.
369 connect(pass, &Pass::idle, this, [this]() {
370 if (m_stopButton != nullptr) {
371 m_stopButton->hide();
372 }
373 });
374 connect(pass, &Pass::statusMsg, this, &MainWindow::showStatusMessage);
375 connect(pass, &Pass::finishedShow, this, &MainWindow::passShowHandler);
376 // Both check the file against their own pending request and ignore the
377 // rest, so they can stay connected for good.
379 connect(pass, &Pass::finishedShow, this,
381 connect(pass, &Pass::finishedGrep, this, &MainWindow::onGrepFinished);
382 // The refresh a save left waiting runs once the last push went through,
383 // by name as it was queued before (the save's rewrite of the file may have
384 // replaced its row in the tree), and only while the entry still holds the
385 // panel and nothing else is queued: queued work would run first, and the
386 // refresh would empty the browser of its error. A failed push dropped it
387 // (onOperationError()).
388 connect(pass, &Pass::finishedGitPush, this, [this, pass]() {
389 if (m_refreshAfterPush.isEmpty() || m_refreshAfterPushOwner != pass ||
390 pass->isPushing()) {
391 return;
392 }
393 const QString file = std::exchange(m_refreshAfterPush, QString());
394 m_refreshAfterPushOwner = nullptr;
395 if (file == m_shownFile && pass->isIdle()) {
396 ui->passwordName->setText(Util::shownName(file));
397 pass->Show(file);
398 }
399 });
400}
401
402// Idempotent; called from closeEvent() and the destructor.
407
409 // findChild() rather than ui->lineEdit: on a fresh-config first launch
410 // config() calls setWindowFlags(), which rebuilds the native window, and
411 // under Qt 6.11 the QLineEdit was destroyed while ui->lineEdit kept its old
412 // address (SIGSEGV in QWidget::testAttribute). findChild() returns null.
413 if (!isVisible()) {
414 return;
415 }
416 auto *lineEdit = findChild<QLineEdit *>(QStringLiteral("lineEdit"));
417 if (lineEdit == nullptr || !lineEdit->isVisible()) {
418 return;
419 }
420 lineEdit->selectAll();
421 lineEdit->setFocus();
422 // Only once focus has landed: set in showEvent(), an early return above
423 // would consume the one-shot and never retry.
425}
426
427auto MainWindow::event(QEvent *event) -> bool {
428 if (event->type() == QEvent::ApplicationPaletteChange) {
429 m_themeSwitched = true;
430 // Breeze may re-stamp the bars before this arrives (Plasma 6 does):
431 // their PaletteChange then found no switch yet, so check them now too.
432 QTimer::singleShot(0, this, &MainWindow::dropStaleToolsAreaPalettes);
433 }
434 return QMainWindow::event(event);
435}
436
438 QWidget::changeEvent(event);
439 if (event->type() == QEvent::PaletteChange && m_displayPanel != nullptr) {
440 // Desktop switched light/dark. Top-level widgets get PaletteChange
441 // (ApplicationPaletteChange goes to QApplication); stylesheets with
442 // baked-in palette colours must be re-derived by hand.
444 }
445 if (event->type() == QEvent::ActivationChange && isActiveWindow() &&
446 isVisible()) {
447 // Defer a tick so the activation dispatch chain unwinds first: calling
448 // focusInput() inline has segfaulted on half-rebuilt ui state.
449 QMetaObject::invokeMethod(this, &MainWindow::focusInput,
450 Qt::QueuedConnection);
451 }
452}
453
454void MainWindow::showEvent(QShowEvent *event) {
455 QMainWindow::showEvent(event);
457 return;
458 }
459 // Queued so the platform map and pending rebuilds (setWindowFlags on the
460 // wizard path) settle first. focusInput() sets the latch only on success,
461 // so a failed lookup retries on the next show.
462 QMetaObject::invokeMethod(this, &MainWindow::focusInput,
463 Qt::QueuedConnection);
464}
465
467 connect(ui->actionAddPassword, &QAction::triggered, this,
469 connect(ui->actionAddFolder, &QAction::triggered, this,
471 connect(ui->actionEdit, &QAction::triggered, this, &MainWindow::onEdit);
472 connect(ui->actionDelete, &QAction::triggered, this, &MainWindow::onDelete);
473 connect(ui->actionPush, &QAction::triggered, this, &MainWindow::onPush);
474 connect(ui->actionUpdate, &QAction::triggered, this, &MainWindow::onUpdate);
475 connect(ui->actionUsers, &QAction::triggered, this, &MainWindow::onUsers);
476 connect(ui->actionConfig, &QAction::triggered, this, &MainWindow::onConfig);
477 connect(ui->actionOtp, &QAction::triggered, this, &MainWindow::onOtp);
478
479 // Menu-only. Quit ends the application, tray icon or not, as in KeePassXC,
480 // Telegram and the KDE, GNOME and macOS guidelines (#1788). Close is
481 // close(), a hide when "hide on close" is set, like the X button and Alt+F4.
482 connect(ui->actionQuit, &QAction::triggered, qApp, &QApplication::quit);
483 connect(ui->actionClose, &QAction::triggered, this, &MainWindow::close);
484#ifdef Q_OS_MACOS
485 // The menu bar is the system's up there; nothing to hide.
486 ui->actionShowMenuBar->setVisible(false);
487#else
488 // The action lives in the menu it hides, so it has to be on the window as
489 // well for Ctrl+M to keep working while the bar is gone.
490 addAction(ui->actionShowMenuBar);
491 ui->actionShowMenuBar->setChecked(QtPassSettings::load().showMenuBar);
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);
498 });
499 new MenuBarPeek(this, ui->actionShowMenuBar);
500#endif
501 connect(ui->actionFaq, &QAction::triggered, this, [] {
502 QDesktopServices::openUrl(QUrl(QStringLiteral("https://qtpass.org/faq")));
503 });
504 connect(ui->actionAbout, &QAction::triggered, this, &MainWindow::showAbout);
505 connect(ui->actionAboutQt, &QAction::triggered, qApp, &QApplication::aboutQt);
506
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")));
523}
524
526 ui->statusBar->showMessage(tr("Welcome to QtPass %1").arg(VERSION), 2000);
527
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"));
534 m_stopButton->setToolTip(
535 tr("Stop the gpg, git or pass run that is still going"));
536 m_stopButton->hide();
537 connect(m_stopButton, &QPushButton::clicked, this, [this]() {
539 if (pass == nullptr || pass->isIdle()) {
540 m_stopButton->hide();
541 return;
542 }
543 const Enums::PROCESS pid = pass->runningProcess();
544 const quint64 run = pass->runningSerial();
545 const QString label = runLabel(pid);
546 // A decrypt or a search changes nothing. Anything else may be half done
547 // when stopped: some entries re-encrypted and others not, a Git step cut
548 // off with its lock left behind.
549 const bool writes = pid != Enums::PASS_SHOW && pid != Enums::PASS_GREP;
550 if (writes) {
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?")
557 .arg(label),
558 QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
559 // The queue may have moved on while the question was open: stop
560 // nothing but what was asked about.
561 if (answer != QMessageBox::Yes || pass->runningSerial() != run) {
562 return;
563 }
564 }
565 m_stopButton->hide();
566 if (pass->stopRunning()) {
568 writes ? tr("Stopped %1 before it finished; the store may be "
569 "partly changed.")
570 .arg(label)
571 : tr("Stopped %1.").arg(label));
572 }
573 });
574 statusBar()->addPermanentWidget(m_stopButton);
575 statusBar()->addPermanentWidget(logoApp);
576}
577
579 return ui->treeView->currentIndex();
580}
581
582void MainWindow::flashText(const QString &text, const bool isError,
583 const bool isHtml) {
584 // setText() applies the current char format to the whole message. Start
585 // from an empty one: inherited from a cursor on a linkified URL it carried
586 // the anchor, and the message became a link to that address. No colour
587 // but red for an error, so text follows runtime light/dark switches (#946).
588 QTextCursor cursor = ui->textBrowser->textCursor();
589 cursor.clearSelection();
590 ui->textBrowser->setTextCursor(cursor);
591 QTextCharFormat format;
592 if (isError) {
593 format.setForeground(QColor(Qt::red));
594 }
595 ui->textBrowser->setCurrentCharFormat(format);
596
597 // Wrapped at word boundaries, a run of hundreds of thousands of letters
598 // took Qt seconds to minutes; anywhere, it is linear. Anywhere while the
599 // text goes in, then word wrap back unless what is shown has such a run:
600 // markup (a link's "<a href") splits a run in the source, not on screen.
601 ui->textBrowser->setWordWrapMode(QTextOption::WrapAnywhere);
602 if (isHtml) {
603 QString _text = text;
604 // What was shown before this message: the part the cap may remove.
605 // The message itself is never cut, so an entry shown through here
606 // (passShowHandler()) stays whole however long it is.
607 int older = 0;
608 if (!ui->textBrowser->toPlainText().isEmpty()) {
609 older = ui->textBrowser->document()->characterCount() - 1;
610 _text = ui->textBrowser->toHtml() + _text;
611 }
612 ui->textBrowser->setHtml(_text);
613 // Only the latest output: from the front, up to the start of the first
614 // paragraph that ends the excess, within what was shown before (a
615 // message that starts a paragraph starts one past it, after the
616 // separator).
617 QTextDocument *doc = ui->textBrowser->document();
618 int cut = qMin(doc->characterCount() - kMaxFlashCharacters, older);
619 if (cut > 0) {
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();
624 }
625 QTextCursor trim(doc);
626 trim.setPosition(cut, QTextCursor::KeepAnchor);
627 trim.removeSelectedText();
628 }
629 } else {
630 ui->textBrowser->setText(text);
631 }
632 // The raw text: toPlainText() turns a no-break space into a plain one.
633 if (!Util::hasLongUnbrokenRun(ui->textBrowser->document()->toRawText())) {
634 ui->textBrowser->setWordWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
635 }
636}
637
640 if (s.useMonospace) {
641 QFont monospace("Monospace");
642 monospace.setStyleHint(QFont::Monospace);
643 ui->textBrowser->setFont(monospace);
644 } else {
645 ui->textBrowser->setFont(QFont());
646 }
647
648 if (s.noLineWrapping) {
649 ui->textBrowser->setLineWrapMode(QTextBrowser::NoWrap);
650 } else {
651 ui->textBrowser->setLineWrapMode(QTextBrowser::WidgetWidth);
652 }
653}
654
656 const bool wantOnTop = QtPassSettings::isAlwaysOnTop();
657 const Qt::WindowFlags flags = windowFlags();
658 if (flags.testFlag(Qt::WindowStaysOnTopHint) == wantOnTop) {
659 // setWindowFlags() rebuilds the native window, the teardown that left
660 // ui->lineEdit dangling (see focusInput()); skip it when nothing changes.
661 return;
662 }
663 // Toggle just this hint; resetting to Qt::Window discarded every other flag.
664 const bool wasVisible = isVisible();
665 setWindowFlags(wantOnTop ? (flags | Qt::WindowStaysOnTopHint)
666 : (flags & ~Qt::WindowStaysOnTopHint));
667 // setWindowFlags() hides a shown window; a window that was not shown yet
668 // (first-run wizard from the constructor) is left to its normal show.
669 if (wasVisible) {
670 show();
671 }
672}
673
674auto MainWindow::config() -> bool {
675 if (m_freshStart) {
676 // No usable configuration yet: the wizard finds the programs, the key
677 // and the store, and creates the store when it has to.
678 FirstRunWizard wizard(this);
679 if (wizard.exec() != QDialog::Accepted) {
680 return false;
681 }
682 } else {
683 ConfigDialog d(this);
684 d.setModal(true);
685 if (d.exec() != QDialog::Accepted) {
686 return false;
687 }
688 }
689
692
695 // An open still waiting for the tree was asked of the old view; once
696 // re-rooted, it would find that name in the new store. A profile switch
697 // ends it by clearing the search text.
698 delete m_pendingOpen;
699 // A content search still running searched the old store, and its matches
700 // would be listed for this one: onGrepFinished() cannot tell. Cancelled,
701 // and content-search results on screen go with it (clearPanel()).
703 if (m_grep.cancelSearch()) {
704 QApplication::restoreOverrideCursor();
705 }
706 clearPanel(false);
707 m_tree->setStore(s.passStore);
708 deselect();
709 ui->treeView->setCurrentIndex(QModelIndex());
710
711 Pass *activePass = QtPassSettings::getPass();
712 activePass->updateEnv();
713 m_tree->setPass(activePass);
715 clearResultsTimer.setInterval(clearPanelTimer.interval());
716 m_qtPass->clipboard().setAutoclearTimer();
717
722#ifndef Q_OS_MACOS
723 // The action's toggled handler shows or hides the bar (and saves again).
724 ui->actionShowMenuBar->setChecked(s.showMenuBar);
725#endif
726 if (s.useTrayIcon && m_tray == nullptr) {
727 initTrayIcon();
728 } else if (!s.useTrayIcon && m_tray != nullptr) {
730 }
731
732 // Stay fresh-start while the configuration is unusable, so the
733 // constructor's loop re-runs the wizard. The re-prompt lives there:
734 // recursing here never reported a cancel back to the caller.
735 if (Util::configIsValid(s)) {
736 m_freshStart = false;
737 }
738 return true;
739}
740
741void MainWindow::onUpdate(bool block) {
742 ui->statusBar->showMessage(tr("Updating password-store"), 2000);
743 if (block) {
745 } else {
746 QtPassSettings::getPass()->GitPull();
747 }
748}
749
752 ui->statusBar->showMessage(tr("Updating password-store"), 2000);
753 QtPassSettings::getPass()->GitPush();
754 }
755}
756
759 ui->statusBar->showMessage(tr("Updating password-store"), 2000);
760 QtPassSettings::getPass()->GitPushAutomatic();
761 }
762}
763
764auto MainWindow::getFile(const QModelIndex &index, bool forPass) -> QString {
765 return m_tree->fileFor(index, forPass);
766}
767
768void MainWindow::on_treeView_clicked(const QModelIndex &index) {
769 bool cleared = ui->treeView->currentIndex().flags() == Qt::NoItemFlags;
770 QString file = getFile(index, true);
771 ui->passwordName->setText(Util::shownName(file));
772 if (!file.isEmpty() && !cleared) {
773 // Remember what the panel is about to show, so onOtp() can tell whether the
774 // code it can see belongs to the entry that is currently selected.
775 m_shownFile = file;
776 QtPassSettings::getPass()->Show(std::move(file));
777 } else {
778 m_shownFile.clear();
779 clearPanel(false);
780 ui->actionEdit->setEnabled(false);
781 ui->actionDelete->setEnabled(true);
782 }
783}
784
785void MainWindow::on_treeView_doubleClicked(const QModelIndex &index) {
786 QFileInfo fileOrFolder = m_tree->fileInfo(ui->treeView->currentIndex());
787
788 if (fileOrFolder.isFile()) {
789 editPassword(getFile(index, true));
790 }
791}
792
794 m_shownFile.clear();
796 m_qtPass->clipboard().clear();
797 ui->treeView->clearSelection();
798 // The current index too: clearSelection() keeps it, and whatever asks for
799 // the "current" folder (Users, Add password, Add folder) took the hidden
800 // entry it was left on, such as the first hit of a search just emptied.
801 ui->treeView->setCurrentIndex(QModelIndex());
802 ui->actionEdit->setEnabled(false);
803 ui->actionDelete->setEnabled(false);
804 ui->passwordName->setText("");
805 clearPanel(false);
806}
807
810 m_panelEntry.clear();
811 ui->textBrowser->clear();
813 clearPanelTimer.stop();
815 m_processOutput->setVisible(true);
816 }
817}
818
819void MainWindow::passShowHandler(const QString &p_output, const QString &file) {
820 // Only the entry we most recently asked to show may repaint the panel; a
821 // slower decrypt of an entry the user has since left is dropped, and so is
822 // one that arrives after the selection was cleared (deselect, a profile
823 // switch): nothing is asked to be shown then.
824 if (!file.isEmpty() && file != m_shownFile) {
825 // A newer show is pending and releases the interface when it lands;
826 // with none (the selection was cleared) nothing else would until the
827 // watchdog. setUiElementsEnabled() keeps a re-encryption's lock.
828 if (m_shownFile.isEmpty()) {
830 }
831 return;
832 }
835 QStringList templ =
836 s.useTemplate ? TemplateIO::fieldsIn(s.passTemplate) : QStringList();
837 bool allFields = s.useTemplate && s.templateAllFields;
838 // A secret the panel hides is a field even when the template doesn't list
839 // it: left in the text below the fields, it would show in plain view.
840 FileContent fileContent = FileContent::parse(
841 p_output, templ, allFields, [this, &s](const QString &name) {
842 return m_displayPanel->isSecret(name, s);
843 });
844 QString output = p_output;
845 // Display variant: empty when the password line is itself an otpauth URI, so
846 // the shared secret is neither rendered nor copied to the clipboard.
847 QString password = fileContent.getPasswordForDisplay();
848
849 // Skipped for an OTP request: the user asked for a code, and two
850 // OleSetClipboard calls in one turn can leave the Windows clipboard empty.
851 if (m_otpRequestFile.isEmpty() || m_otpRequestFile != file) {
852 m_qtPass->clipboard().copyIfAlways(password, p_output);
853 }
854
856 m_panelEntry.clear();
857
858 if (s.hideContent) {
859 output = "***" + tr("Content hidden") + "***";
860 } else if (s.displayAsIs) {
861 // As it is, but not a block per line of millions.
862 output = FileContent::boundedForDisplay(p_output);
863 } else {
864 m_panelEntry = file;
865 m_displayPanel->displayFields(password, fileContent.getNamedValues(), s,
866 s.useOtp ? fileContent.getOtpUri()
867 : QString());
868 output = fileContent.getRemainingDataForDisplay();
869 }
870
871 if (s.useAutoclearPanel) {
872 clearPanelTimer.start();
873 }
874
875 // Shown as it is, the text holds the password and every secret field: no
876 // links in it, or a click on a URL-shaped one handed it to the browser.
877 flashText(QtPass::formatOutput(std::move(output), QString(), QString(),
878 !s.displayAsIs || s.hideContent),
879 false, true);
881}
882
883void MainWindow::otpFromFileToClipboard(const QString &p_output,
884 const QString &file) {
885 // Permanently connected: only the decrypt of the entry onOtp() asked for
886 // is ours, everything else belongs to a tree click or a Ctrl+C.
887 if (m_otpRequestFile.isEmpty() || file != m_otpRequestFile) {
888 return;
889 }
890 m_otpRequestFile.clear();
891
892 if (p_output.isEmpty()) {
893 // Distinguish "could not read the entry" from "entry has no OTP".
894 flashText(tr("Could not decrypt this password entry"), true);
896 return;
897 }
898
899 // passShowHandler ran first for this finishedShow; if it rendered the OTP
900 // row, reuse its code (as onOtp()'s fast path does). Otherwise parse:
901 // hideContent, displayAsIs or no OTP field.
902 const QString shown = m_displayPanel->currentOtpCode();
903 if (!shown.isEmpty()) {
904 m_qtPass->clipboard().copyText(shown);
905 showStatusMessage(tr("OTP code copied to clipboard"));
907 return;
908 }
909
911 // Parse with the same template settings passShowHandler uses, so an OTP
912 // field is recognised identically in both paths.
913 const QStringList templ =
914 s.useTemplate ? TemplateIO::fieldsIn(s.passTemplate) : QStringList();
915 const bool allFields = s.useTemplate && s.templateAllFields;
916 const FileContent fileContent =
917 FileContent::parse(p_output, templ, allFields);
918
920 const std::optional<Totp::Settings> settings =
921 Totp::parse(fileContent.getOtpUri(), &why);
922 if (settings.has_value()) {
923 m_qtPass->clipboard().copyText(Totp::generateNow(*settings));
924 showStatusMessage(tr("OTP code copied to clipboard"));
925 } else {
926 // Why, when there is a configuration that gives no code.
927 const QString reason = Totp::describe(why);
928 flashText(reason.isEmpty() ? tr("No OTP code found in this password entry")
929 : reason,
930 true);
931 }
933}
934
935void MainWindow::clearPanel(bool notify) {
936 clearShownEntry(notify);
938}
939
942 m_panelEntry.clear();
943 // A QR code of the password is the password on screen as much as the
944 // panel is; it is a popup of its own, not part of the panel.
946 if (notify) {
947 QString output = "***" + tr("Password and content hidden") + "***";
948 ui->textBrowser->setHtml(output);
949 } else {
950 ui->textBrowser->setHtml("");
951 }
952}
953
955 clearResultsTimer.stop();
956 const bool grepWasVisible = ui->grepResultsList->isVisible();
957 ui->grepResultsList->clear();
958 if (grepWasVisible) {
959 showContentResults(false);
960 if (m_grep.inGrepMode()) {
961 // Left as the button leaves it: a search still running would otherwise
962 // hand its partial matches to a content search entered meanwhile.
964 if (m_grep.leaveGrepMode()) {
965 QApplication::restoreOverrideCursor();
966 }
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"));
974 }
975 }
976}
977
979 // A running re-encryption owns the UI state: the progress dialog's Cancel is
980 // the user's escape hatch and endReencryptPath() releases the interface, so
981 // neither an unrelated completion nor the watchdog may re-enable it early.
982 if (state && m_reencryptRunning) {
983 m_uiWatchdog.stop();
984 return;
985 }
986 // Arm the watchdog while the UI is disabled; disarm once re-enabled.
987 if (state) {
988 m_uiWatchdog.stop();
989 } else {
990 m_uiWatchdog.start();
991 }
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);
998 m_uiEnabled = state;
1000 const bool uiEnabled = state;
1001 // is a file selected, and in sight (content search results hide the tree)?
1002 state &= ui->treeView->currentIndex().isValid() && !ui->treeView->isHidden();
1003 ui->actionDelete->setEnabled(state);
1004 ui->actionEdit->setEnabled(state);
1005 updateGitButtonVisibility(uiEnabled);
1006 // `state` is now "UI enabled AND a file is selected", which is exactly when
1007 // generating an OTP makes sense.
1009}
1010
1012 // saveGeometry() covers position, size, maximized state and screen;
1013 // anything applied on top discards it. Centre only when nothing was saved.
1014 const QByteArray geometry = QtPassSettings::getGeometry();
1015 if (geometry.isEmpty() || !restoreGeometry(geometry)) {
1017 }
1018 restoreState(QtPassSettings::getSavestate(saveState()));
1020
1022
1023 if (s.useTrayIcon && m_tray == nullptr) {
1024 initTrayIcon();
1025 // Minimized to the tray only when there is one: without a system tray
1026 // initTrayIcon() gave up, and a hidden window could not be brought back.
1027 if (s.startMinimized && m_tray != nullptr) {
1028 // since we are still in constructor, can't directly hide
1029 QTimer::singleShot(10, this, &MainWindow::hide);
1030 }
1031 } else if (!s.useTrayIcon && m_tray != nullptr) {
1033 }
1034}
1035
1037 // No Settings while anything of the store runs or waits, as with the
1038 // profile box (#2071): the store, backend and programs chosen there apply
1039 // to what is still queued, so a pending `pass init` re-encrypted the store
1040 // just picked for the recipients chosen for the other. Asked of the
1041 // backends: the watchdog releases the interface while a slow gpg or git
1042 // still runs.
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."));
1052 return;
1053 }
1054 config();
1055}
1056
1058 QMessageBox::about(
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> &middot; "
1065 "<a href=\"https://github.com/IJHack/QtPass\">Source and "
1066 "issues</a></p>"
1067 "<p>Copyright &copy; 2014&ndash;%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())));
1072}
1073
1074void MainWindow::on_lineEdit_textChanged(const QString &arg1) {
1075 if (m_grep.inGrepMode())
1076 return;
1077 ui->statusBar->showMessage(tr("Looking for: %1").arg(arg1), 1000);
1078 ui->treeView->expandAll();
1079 // Drop any decrypt still pending for the entry that was shown: otherwise it
1080 // keeps its right to the panel and, with "Always copy", the clipboard, and
1081 // when it lands late it shows that entry's password under the new heading.
1082 m_shownFile.clear();
1084 clearPanel(false);
1085 ui->passwordName->setText("");
1086 ui->actionEdit->setEnabled(false);
1087 ui->actionDelete->setEnabled(false);
1088 searchTimer.start();
1089}
1090
1092 // The tree matches slash-separated paths: on Windows, team\bank typed is
1093 // team/bank, as exactMatchPath() reads it too.
1094 QString query = QDir::fromNativeSeparators(ui->lineEdit->text());
1095
1096 if (query.isEmpty()) {
1097 ui->treeView->collapseAll();
1098 deselect();
1099 }
1100
1101 // The words are matched literally, in order, with anything in between:
1102 // "work vpn" finds work/acme/vpn.
1104
1105 if (m_tree->proxy().rowCount() > 0 && !query.isEmpty()) {
1107 } else {
1108 ui->actionEdit->setEnabled(false);
1109 ui->actionDelete->setEnabled(false);
1110 }
1111}
1112
1114 qCDebug(lcQtPass) << "on_lineEdit_returnPressed"
1115 << m_tree->proxy().rowCount();
1116
1117 if (m_grep.inGrepMode()) {
1118 const QString query = ui->lineEdit->text();
1119 if (!query.isEmpty()) {
1120 ui->grepResultsList->clear();
1121 ui->statusBar->showMessage(tr("Searching…"));
1122 if (m_grep.beginSearch()) {
1123 QApplication::setOverrideCursor(Qt::WaitCursor);
1124 }
1125 QtPassSettings::getPass()->Grep(query, ui->grepCaseButton->isChecked());
1126 } else {
1128 if (m_grep.cancelSearch()) {
1129 QApplication::restoreOverrideCursor();
1130 }
1131 ui->grepResultsList->clear();
1132 showContentResults(false);
1133 }
1134 return;
1135 }
1136
1137 // Return within the search delay acts on the text as typed, not on the
1138 // tree as the previous text filtered it.
1139 if (searchTimer.isActive()) {
1140 searchTimer.stop();
1142 }
1143 if (m_tree->proxy().rowCount() > 0) {
1145 on_treeView_clicked(ui->treeView->currentIndex());
1146 }
1147}
1148
1151 if (checked) {
1153 ui->lineEdit->setPlaceholderText(tr("Search content (regex)"));
1154 // Both backends search through NativeGrep (QRegularExpression), so one
1155 // dialect: PCRE.
1156 ui->lineEdit->setToolTip(
1157 tr("Content search uses Perl-compatible regular expressions (PCRE)."));
1158 ui->lineEdit->clear();
1159 searchTimer.stop();
1160 m_tree->setFilter(QRegularExpression());
1161 ui->grepResultsList->setVisible(false);
1162 // Keep treeView visible until results arrive
1163 } else {
1165 if (m_grep.leaveGrepMode()) {
1166 QApplication::restoreOverrideCursor();
1167 }
1168 searchTimer.stop();
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();
1175 showContentResults(false);
1176 m_tree->setFilter(QRegularExpression());
1177 }
1178}
1179
1187
1188auto MainWindow::grepLineForDisplay(const QString &line,
1189 const AppSettings &s) const -> QString {
1190 const QString hidden =
1191 QStringLiteral("***") + tr("hidden") + QStringLiteral("***");
1192 if (NativeGrep::isOtpMarker(line)) {
1193 return tr("One-time password secret: %1").arg(hidden);
1194 }
1195 // The panel's own rules: the password and a field it would put behind
1196 // the eye button keep their value out of the list too.
1197 if (NativeGrep::isPasswordMatch(line)) {
1198 return m_displayPanel->hides(QObject::tr("Password"), s)
1199 ? tr("Password: %1").arg(hidden)
1201 }
1202 if (const qsizetype colon = line.indexOf(QLatin1Char(':')); colon > 0) {
1203 if (m_displayPanel->hides(line.left(colon).trimmed(), s)) {
1204 return line.left(colon + 1) + QLatin1Char(' ') + hidden;
1205 }
1206 }
1207 return line;
1208}
1209
1211 const QList<QPair<QString, QStringList>> &results) {
1212 // Both backends stay connected, each with its own search: a search the
1213 // other backend was still running when Settings switched backends is not
1214 // this one, whatever the controller's state, and searched another store.
1215 // Dropped before it can end (or be taken for) the current search.
1216 if (const QObject *from = sender();
1217 from != nullptr && from != QtPassSettings::getPass()) {
1218 return;
1219 }
1221 if (outcome.restoreCursor) {
1222 QApplication::restoreOverrideCursor();
1223 }
1224 // Re-enable the UI before the discard check so a cancelled search can never
1225 // leave controls disabled.
1227 if (outcome.discard) {
1228 return;
1229 }
1230 if (!m_grep.inGrepMode())
1231 return;
1232 ui->grepResultsList->clear();
1233 if (results.isEmpty()) {
1234 ui->statusBar->showMessage(tr("No matches found."), 3000);
1235 showContentResults(false);
1236 return;
1237 }
1239 const bool hideContent = s.hideContent;
1241 int totalLines = 0;
1242 int entries = 0;
1243 bool stopped = false;
1244 for (const auto &pair : results) {
1245 if (NativeGrep::isStoppedMarker(pair)) {
1246 stopped = true;
1247 continue;
1248 }
1249 ++entries;
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);
1255 // The marker is no content: shown as it is with hidden content too,
1256 // and not counted as a match.
1257 if (NativeGrep::isMoreMarker(line)) {
1258 lineItem->setText(0, tr("… more matches in this entry"));
1259 } else {
1260 lineItem->setText(0, hideContent ? "***" + tr("Content hidden") + "***"
1261 : grepLineForDisplay(line, s));
1262 ++totalLines;
1263 }
1264 lineItem->setData(0, Qt::UserRole, pair.first);
1265 }
1266 }
1267 ui->grepResultsList->expandAll();
1268 showContentResults(true);
1269 if (stopped) {
1270 // The search stopped there; more entries may match.
1271 ui->statusBar->showMessage(
1272 tr("Showing the first %n match(es); search for something narrower "
1273 "to see the rest.",
1274 nullptr, totalLines),
1275 10000);
1276 } else {
1277 ui->statusBar->showMessage(tr("Found %n match(es)", nullptr, totalLines) +
1278 " " +
1279 tr("in %n entr(ies).", nullptr, entries),
1280 3000);
1281 }
1282 // The results' own deadline: restarting the entry's timer here gave an
1283 // entry still on the panel a second period, and an operation that stops
1284 // the entry's timer left the results up with none.
1285 if (s.useAutoclearPanel)
1286 clearResultsTimer.start();
1287}
1288
1290 int /*column*/) {
1292 const QString entry = item->data(0, Qt::UserRole).toString();
1293 if (entry.isEmpty())
1294 return;
1295 const QString fullPath =
1296 QDir::cleanPath(Util::joinPath(s.passStore, entry + ".gpg"));
1297 // Persistent: setCurrentIndex() runs the selection handlers, which can
1298 // change the model before the click is handled.
1299 const QPersistentModelIndex proxyIndex(m_tree->indexFor(fullPath));
1300 if (!proxyIndex.isValid())
1301 return;
1302 ui->treeView->setCurrentIndex(proxyIndex);
1303 if (!proxyIndex.isValid())
1304 return;
1305 on_treeView_clicked(proxyIndex);
1306 if (s.hideContent || s.useAutoclearPanel)
1307 ui->grepResultsList->clear();
1308 showContentResults(false);
1309 ui->treeView->scrollTo(proxyIndex);
1310 ui->treeView->setFocus();
1311}
1312
1314 ui->grepResultsList->setVisible(shown);
1315 ui->treeView->setVisible(!shown);
1316 if (shown) {
1317 // The tree's current entry is out of sight: Delete, Edit and OTP would
1318 // act on it, not on a result. Opening a result shows the tree again.
1319 ui->actionDelete->setEnabled(false);
1320 ui->actionEdit->setEnabled(false);
1322 } else if (ui->treeView->selectionModel()->hasSelection()) {
1323 // Only for an entry still selected: with nothing selected there is no
1324 // entry for Edit and Delete to act on.
1326 }
1327}
1328
1330 QtPassSettings::getRealPass()->CancelGrep();
1331 QtPassSettings::getImitatePass()->CancelGrep();
1332}
1333
1335 // The entry named exactly as typed wins: with folders sorted first, the
1336 // depth-first walk found team/bank before bank.
1337 QModelIndex index = exactMatch();
1338 if (!index.isValid()) {
1339 index = firstFile(m_tree->rootIndex());
1340 }
1341 ui->treeView->setCurrentIndex(index);
1342}
1343
1344namespace {
1355auto spelledAsStored(const QString &store, const QString &path) -> QString {
1356 const QStringList parts = QDir(store).relativeFilePath(path).split(
1357 QLatin1Char('/'), Qt::SkipEmptyParts);
1358 QDir dir(store);
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;
1370 });
1371 if (stored == names.cend()) {
1372 return path;
1373 }
1374 name = *stored;
1375 respelled = true;
1376 }
1377 if (leaf) {
1378 return respelled ? QDir::cleanPath(Util::joinPath(dir.path(), name))
1379 : path;
1380 }
1381 if (!dir.cd(name)) {
1382 return path;
1383 }
1384 }
1385 return path;
1386}
1387} // namespace
1388
1390 const QString text = QDir::fromNativeSeparators(ui->lineEdit->text());
1391 const QString store = QtPassSettings::getPassStore();
1392 // A name may begin or end with a space: " bank" is that entry, not bank.
1393 // Only when no entry is named so are spaces around the text dropped.
1394 for (const QString &typed : {text, text.trimmed()}) {
1395 if (typed.isEmpty()) {
1396 continue;
1397 }
1398 const QString path =
1399 QDir::cleanPath(Util::joinPath(store, typed + QStringLiteral(".gpg")));
1400 if (PathValidator::isPathInStore(store, path) && QFileInfo(path).isFile()) {
1401 return spelledAsStored(store, path);
1402 }
1403 }
1404 return {};
1405}
1406
1407auto MainWindow::exactMatch() -> QModelIndex {
1408 const QString path = exactMatchPath();
1409 if (path.isEmpty()) {
1410 return {};
1411 }
1412 // indexFor() maps through the filter: a row the filter hides is no match.
1413 const QModelIndex index = m_tree->indexFor(path);
1414 if (!index.isValid() || !m_tree->fileInfo(index).isFile()) {
1415 return {};
1416 }
1417 return index;
1418}
1419
1420void MainWindow::applySearchText(const QString &text) {
1421 // A name search: content search, left on, kept its results over the tree
1422 // and ignored the text.
1423 if (ui->grepButton->isChecked()) {
1424 ui->grepButton->setChecked(false);
1425 }
1426 delete m_pendingOpen;
1427 ui->lineEdit->setText(text);
1428 // Filter now, not after the search delay: the timer would leave the tree
1429 // as the previous text filtered it.
1430 searchTimer.stop();
1432 if (const QModelIndex exact = exactMatch(); exact.isValid()) {
1433 openExactMatch(exact);
1434 return;
1435 }
1436 // The tree loads folders in the background: at start, or right after the
1437 // window is shown again, an entry that exists may not be in it yet. Try
1438 // again as folders finish loading, for a few seconds, unless the search
1439 // text changes meanwhile: any change ends the wait, even one typed back to
1440 // this text, which is a new search that has not asked to open anything.
1441 if (exactMatchPath().isEmpty()) {
1442 return;
1443 }
1444 auto *pending = new QObject(this);
1445 m_pendingOpen = pending;
1446 QTimer::singleShot(5000, pending, &QObject::deleteLater);
1447 // Disconnected at once: with deleteLater() alone, a folder that finished
1448 // loading before the deletion still ran the open, or ran it twice.
1449 const auto stop = [this, pending] {
1450 disconnect(m_tree, nullptr, pending, nullptr);
1451 disconnect(ui->lineEdit, nullptr, pending, nullptr);
1452 pending->deleteLater();
1453 };
1454 connect(ui->lineEdit, &QLineEdit::textChanged, pending, stop);
1455 connect(m_tree, &StoreTree::directoryLoaded, pending,
1456 [this, stop](const QString &) {
1457 searchTimer.stop();
1459 if (const QModelIndex exact = exactMatch(); exact.isValid()) {
1460 stop();
1461 openExactMatch(exact);
1462 }
1463 });
1464}
1465
1466void MainWindow::openExactMatch(const QModelIndex &index) {
1467 // Made current here, not left to the filter pass before: the tree may have
1468 // moved its current row since, and with none on_treeView_clicked() only
1469 // names the entry without decrypting it.
1470 ui->treeView->setCurrentIndex(index);
1471 on_treeView_clicked(index);
1472}
1473
1474auto MainWindow::firstFile(QModelIndex parentIndex) -> QModelIndex {
1475 StoreModel &proxy = m_tree->proxy();
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()) {
1480 return index;
1481 }
1482 if (proxy.hasChildren(index)) {
1483 QModelIndex childFile = firstFile(index);
1484 if (childFile.isValid())
1485 return childFile;
1486 }
1487 }
1488 return {};
1489}
1490
1491// Guards the input dialogs (create, move, rename) against names like
1492// "../../etc/passwd" or absolute paths escaping the store root.
1493auto MainWindow::confirmPathInStore(const QString &candidate) -> bool {
1495 return true;
1496 }
1497 QMessageBox::warning(this, tr("Invalid name"),
1498 tr("That name would resolve outside the password "
1499 "store. Please choose a different name."));
1500 return false;
1501}
1502
1503void MainWindow::setPassword(const QString &file, bool isNew) {
1505 PasswordDialog d(QtPassSettings::getPass(), s, file, isNew, this);
1506 // A copy out of the editor is autocleared like one from the display.
1507 connect(&d, &PasswordDialog::copied, &m_qtPass->clipboard(),
1509
1510 if (isNew) {
1511 const QString storePath = s.passStore;
1512 QString folder = m_tree->currentDir(false);
1513 if (folder.isEmpty()) {
1514 folder = storePath;
1515 }
1516 // A tree folder that is, or lies behind, a symbolic link is not part of the
1517 // store (Users and re-encryption refuse it the same way). Adding here would
1518 // silently fall back to the store root and encrypt the new entry to the
1519 // root's recipients - which a co-writer who planted the link, and is on the
1520 // root list but not the real folder's, can then read. Refuse instead.
1521 if (refuseLinkedFolder(folder)) {
1522 return;
1523 }
1524 // Folders to pick from, the tree's current one preselected. Real folders
1525 // only: a linked or junctioned one would write the entry outside the store.
1526 QStringList folders{QString()};
1527 const QStringList found = Util::directoriesUnder(storePath);
1528 for (const QString &path : found) {
1529 const QString rel = QDir(storePath).relativeFilePath(path);
1530 if (!rel.startsWith(u'.') && !rel.contains(QStringLiteral("/."))) {
1531 folders << rel;
1532 }
1533 }
1534 std::sort(folders.begin() + 1, folders.end());
1535 d.setNewEntryLocation(storePath, folders,
1536 QDir(storePath).relativeFilePath(folder));
1537 QHash<QString, QStringList> templates =
1538 TemplateIO::readTemplates(storePath);
1539 if (!templates.isEmpty()) {
1540 QString defaultTemplate =
1541 TemplateIO::getFolderTemplate(folder, storePath);
1542 d.setAvailableTemplates(templates, defaultTemplate);
1543 }
1544 }
1545
1546 if (!d.exec()) {
1547 ui->treeView->setFocus();
1548 }
1549}
1550
1552
1553auto MainWindow::confirmDeletion(const QString &file, bool isDir) -> bool {
1554 const QString path = QDir::separator() + file;
1555 // As the platform writes paths: backslashes only on Windows, never a mix.
1556 // On one line: a name from the store may hold a line feed (Unix allows
1557 // one), which drew lines of its own into the question.
1558 const QString shown =
1559 Util::displayable(QDir::toNativeSeparators(path), false);
1560 if (!isDir) {
1562 this, tr("Delete password?"),
1563 tr("Are you sure you want to delete %1?").arg(shown));
1564 }
1565 // Whole sentences, not a question stitched from pieces: a verb-final
1566 // language cannot put the rest of the question after the path.
1567 // Plain text, as every box quoting the store: the path is a name other
1568 // writers control, and as rich text "a b" would also show as "a b".
1569 QString question =
1570 tr("Are you sure you want to delete %1 and the whole content?")
1571 .arg(shown);
1572 // A link, junction or special file inside is as unexpected as a stray
1573 // plain file: the walker leaves them out of content and reports them.
1574 QStringList skipped;
1575 QStringList unlisted;
1576 const QString root = m_tree->fileSystem().rootPath();
1577 const QStringList content = Util::regularFilesUnder(
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");
1583 });
1584 if (unexpected) {
1585 question += QStringLiteral("\n\n") +
1586 tr("Attention: there are unexpected files in the given "
1587 "folder, check them before continuing.");
1588 }
1589 // A folder the walk cannot read is not empty but unknown: whatever it
1590 // holds goes too, or stays behind when the removal cannot list it.
1591 if (unlisted.size() == 1) {
1592 //: %1 is a folder in the password store, such as /Work/bank.
1593 const QString one =
1594 tr("%1 could not be read, so what it holds is unknown.")
1595 .arg(Util::displayable(
1596 QDir::toNativeSeparators(
1597 QDir::separator() +
1598 QDir(root).relativeFilePath(unlisted.first())),
1599 false));
1600 question += QStringLiteral("\n\n") + one;
1601 } else if (unlisted.size() > 1) {
1602 //: Only shown for two or more folders; one folder is named instead.
1603 const QString many =
1604 tr("%n folder(s) in it could not be read, so what they hold "
1605 "is unknown.",
1606 nullptr, static_cast<int>(unlisted.size()));
1607 question += QStringLiteral("\n\n") + many;
1608 }
1609 return PlainMessageBox::askYes(this, tr("Delete folder?"), question);
1610}
1611
1612auto MainWindow::confirmLinkRemoval(const QString &file) -> bool {
1613 // Only the link goes (ImitatePass::Remove unlinks it); nothing behind it
1614 // is looked at or mentioned.
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.")
1619 .arg(Util::displayable(QDir::separator() + file, false)));
1620}
1621
1623 const QModelIndex currentIndex = ui->treeView->currentIndex();
1624 // While content search results hide the tree, its current entry is not
1625 // what the user looks at (the Delete key comes here directly).
1626 if (!currentIndex.isValid() || ui->treeView->isHidden()) {
1627 // Otherwise the whole password directory would be deleted (#556).
1628 return;
1629 }
1630
1631 const bool isDir = !m_tree->fileInfo(currentIndex).isFile();
1632 const QString file =
1633 isDir ? m_tree->currentDir(true) : getFile(currentIndex, true);
1634 const QString folder =
1635 m_tree->fileSystem().rootPath() + QDir::separator() + file;
1636 const bool linkedFolder = isDir && Util::isLinkedFolder(folder);
1637
1638 if (!linkedFolder && refuseLinkedFolder(folder)) {
1639 // Behind a link: deleting would reach outside the store.
1640 return;
1641 }
1642 const bool confirmed =
1643 linkedFolder ? confirmLinkRemoval(file) : confirmDeletion(file, isDir);
1644 if (!confirmed) {
1645 return;
1646 }
1647 QtPassSettings::getPass()->Remove(file, isDir);
1648}
1649
1651 m_otpRequestFile.clear();
1652 m_copyRequestFile.clear();
1653}
1654
1657 // executeWrapperStarted() emptied the panel and the browser when the
1658 // operation started (a refusal says so too); what is left to forget is
1659 // which entry the panel was about to show.
1660 m_shownFile.clear();
1661 // A save's refresh waiting for its push is dropped: it would clear the
1662 // push's error (or whatever failed before it) from the browser.
1663 m_refreshAfterPush.clear();
1664 m_refreshAfterPushOwner = nullptr;
1665}
1666
1667// Derives the code in-process from one decrypt, so it works with either
1668// backend on every platform; otpFromFileToClipboard() finishes the job.
1670 if (ui->treeView->isHidden()) {
1671 return;
1672 }
1673 QString file = getFile(ui->treeView->currentIndex(), true);
1674 if (file.isEmpty()) {
1675 flashText(tr("No password selected for OTP generation"), true);
1676 return;
1677 }
1678 if (!QtPassSettings::isUseOtp()) {
1679 // Normally unreachable (the action is hidden), but never fail silently.
1680 flashText(tr("No OTP code found in this password entry"), true);
1681 return;
1682 }
1683
1684 // Fast path: the panel shows a live code, so no decrypt, and one clipboard
1685 // write (two setMimeData calls in one turn can empty the Windows
1686 // clipboard). Only for *this* entry: arrow keys and right-click move
1687 // currentIndex without QTreeView::clicked, so the code may be another's.
1688 const QString shown =
1689 (m_shownFile == file) ? m_displayPanel->currentOtpCode() : QString();
1690 if (!shown.isEmpty()) {
1691 m_qtPass->clipboard().copyText(shown);
1692 showStatusMessage(tr("OTP code copied to clipboard"));
1693 return;
1694 }
1695
1696 // Fallback: decrypt once. The request file keeps passShowHandler from
1697 // copying the password and tells otpFromFileToClipboard its answer.
1698 m_otpRequestFile = file;
1699 setUiElementsEnabled(false);
1700 // Keep the marker in step so a second request takes the fast path; safe as
1701 // executeWrapperStarted() clears the panel, so a failed decrypt shows none.
1702 m_shownFile = file;
1703 QtPassSettings::getPass()->Show(std::move(file));
1704}
1705
1707 if (ui->treeView->isHidden()) {
1708 return;
1709 }
1710 QString file = getFile(ui->treeView->currentIndex(), true);
1711 editPassword(file);
1712}
1713
1715 const QString dir = m_tree->currentDir(false);
1716 if (refuseLinkedFolder(dir)) {
1717 return;
1718 }
1719
1721 if (!d.exec()) {
1722 ui->treeView->setFocus();
1723 }
1724}
1725
1726void MainWindow::messageAvailable(const QString &message) {
1727 show();
1728 raise();
1729 if (message.isEmpty()) {
1730 focusInput();
1731 } else {
1732 ui->treeView->expandAll();
1733 applySearchText(message);
1734 }
1735}
1736
1738 const Profiles profiles = QtPassSettings::getProfiles();
1739 bool activeGone = false;
1740
1741 if (profiles.isEmpty()) {
1742 ui->profileWidget->hide();
1743 } else {
1744 ui->profileWidget->show();
1745 // A refill is no choice of the user's: clearing and adding items moves
1746 // the current text, which would otherwise switch profiles.
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());
1752 }
1753 }
1754 ui->profileBox->model()->sort(0);
1755 int index = ui->profileBox->findText(QtPassSettings::getProfile());
1756 if (index != -1) { // -1 for not found
1757 ui->profileBox->setCurrentIndex(index);
1758 } else if (ui->profileBox->count() > 0) {
1759 // The active profile is gone (removed in Settings): the box shows the
1760 // first one, and the settings and backend must follow it, or the
1761 // removed profile's store stays in use behind it.
1762 ui->profileBox->setCurrentIndex(0);
1763 activeGone = true;
1764 }
1765 }
1766 if (activeGone) {
1767 on_profileBox_currentTextChanged(ui->profileBox->currentText());
1768 }
1770}
1771
1773 // No profile switch while anything of the store runs or waits: the
1774 // backend's store and environment would change under it, and what is
1775 // still queued (a push after a save, say) would finish for the other
1776 // profile (#2071). Asked of the backend, not only of the interface: the
1777 // watchdog releases the interface while a slow gpg or git still runs.
1778 // Every backend: one kept from before a switch of backend may still
1779 // run what was queued on it.
1780 ui->profileBox->setEnabled(m_uiEnabled && ui->profileBox->count() > 1 &&
1782}
1783
1785 if (m_freshStart || name == QtPassSettings::getProfile()) {
1786 return;
1787 }
1788 // The box is disabled while anything runs; should a change come through
1789 // anyway, the active profile stays and the box says so again.
1791 const QSignalBlocker quiet(ui->profileBox);
1792 ui->profileBox->setCurrentText(QtPassSettings::getProfile());
1793 return;
1794 }
1795 // A content search runs outside the queue: leaving grep mode cancels it,
1796 // so its results for the old store are dropped, not shown for the new.
1797 if (m_grep.inGrepMode()) {
1798 ui->grepButton->setChecked(false);
1799 }
1800
1801 ui->lineEdit->clear();
1802
1803 const Profile prof = QtPassSettings::getProfiles().value(name);
1805 s.activeProfile = name;
1806 s.passStore = prof.path;
1807 s.passSigningKey = prof.signingKey;
1808 // The profile's own Git flags are not written over the Git page's: every
1809 // profile without flags of its own falls back to those.
1810 // QtPassSettings::loadEffective() applies them while the profile is active.
1812 ui->statusBar->showMessage(tr("Profile changed to %1").arg(name), 2000);
1813
1814 QtPassSettings::getPass()->updateEnv();
1815
1817 deselect();
1818 ui->treeView->setCurrentIndex(QModelIndex());
1819}
1820
1822 m_tray = new TrayIcon(this);
1823 if (!m_tray->getIsAllocated()) {
1825 return;
1826 }
1827#ifndef Q_OS_MACOS
1828 m_tray->addToggle(ui->actionShowMenuBar);
1829#endif
1830}
1831
1833 delete m_tray;
1834 m_tray = nullptr;
1835}
1836
1837void MainWindow::closeEvent(QCloseEvent *event) {
1838 // Save in both branches: a tray user only ever hides the window, and
1839 // used to quit through the tray menu with nothing ever written.
1841 // Only with a tray icon to come back from: without one (none asked for, or
1842 // no system tray in this session) a hidden QtPass ran on invisibly, with the
1843 // last entry in its window and the password on the clipboard.
1844 if (QtPassSettings::isHideOnClose() && m_tray != nullptr) {
1845 this->hide();
1846 event->ignore();
1847 } else {
1848 m_qtPass->clipboard().clear();
1849 event->accept();
1850 // A visible QSystemTrayIcon keeps the application alive, so
1851 // quitOnLastWindowClosed never fires; quit explicitly.
1852 QApplication::quit();
1853 }
1854}
1855
1856auto MainWindow::eventFilter(QObject *obj, QEvent *event) -> bool {
1857 if ((obj == ui->toolBar || obj == menuBar()) &&
1858 event->type() == QEvent::PaletteChange) {
1859 // Breeze gives these bars a "header" palette and, after a runtime
1860 // light/dark switch, stamps the previous theme's colours back from a
1861 // cached kdeglobals, hiding the toolbar icons. Deferred so we never
1862 // re-enter the style while it is still applying its palette.
1863 QTimer::singleShot(0, this, &MainWindow::dropStaleToolsAreaPalettes);
1864 }
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) {
1868 // Into whichever list is in sight: the tree, or content search results.
1869 // Focus makes the list's first item current.
1870 if (ui->treeView->isHidden()) {
1871 ui->grepResultsList->setFocus();
1872 } else {
1873 ui->treeView->setFocus();
1874 }
1875 }
1876 // Return ends at the search box: QLineEdit emits returnPressed() and
1877 // leaves the key unaccepted, so keyPressEvent() would open the tree's
1878 // current entry as well. In content search that is an entry nobody
1879 // asked for; by name, the first hit a second time.
1880 if (key != nullptr &&
1881 (key->key() == Qt::Key_Return || key->key() == Qt::Key_Enter)) {
1882 ui->lineEdit->event(event);
1883 event->accept();
1884 return true;
1885 }
1886 }
1887 return QObject::eventFilter(obj, event);
1888}
1889
1890// Only once the application palette changed (see m_themeSwitched): a bar
1891// whose active Window lightness is far from the application's shows the
1892// other theme.
1894 if (!m_themeSwitched) {
1895 return;
1896 }
1897 constexpr int kStaleToolsAreaLightness = 64;
1898 // The active group on both sides: a bar's palette() reads the inactive
1899 // group while another window has focus (the settings app, during a theme
1900 // switch), and Breeze gives the header set different inactive colours.
1901 const int appLightness = QApplication::palette()
1902 .color(QPalette::Active, QPalette::Window)
1903 .lightness();
1904 for (QWidget *bar : {static_cast<QWidget *>(ui->toolBar),
1905 static_cast<QWidget *>(menuBar())}) {
1906 if (!bar->testAttribute(Qt::WA_SetPalette)) {
1907 continue;
1908 }
1909 const int barLightness =
1910 bar->palette().color(QPalette::Active, QPalette::Window).lightness();
1911 if (qAbs(barLightness - appLightness) <= kStaleToolsAreaLightness) {
1912 continue;
1913 }
1914 bar->setPalette(QPalette());
1915 // Both bars are transparent and the style paints the tools area from the
1916 // stale palette, so fill our own. Window, not their Button role, which is
1917 // not the window colour in either theme.
1918 bar->setBackgroundRole(QPalette::Window);
1919 bar->setAutoFillBackground(true);
1920 }
1921}
1922
1924 switch (event->key()) {
1925 case Qt::Key_Delete:
1926 onDelete();
1927 break;
1928 case Qt::Key_Return:
1929 case Qt::Key_Enter:
1930 // While content search results hide the tree, its current entry is not
1931 // what the user looks at: Return on a result opens that result.
1932 if (ui->treeView->isHidden()) {
1933 QTreeWidgetItem *result = ui->grepResultsList->currentItem();
1934 if (result != nullptr && ui->grepResultsList->hasFocus()) {
1936 }
1937 break;
1938 }
1939 if (m_tree->proxy().rowCount() > 0) {
1940 on_treeView_clicked(ui->treeView->currentIndex());
1941 }
1942 break;
1943 case Qt::Key_Escape:
1944 ui->lineEdit->clear();
1945 break;
1946 default:
1947 break;
1948 }
1949}
1950
1951void MainWindow::addShareMenu(QMenu &contextMenu, const AppSettings &s) {
1952 const QString dirPath = QDir::cleanPath(m_tree->currentDir(false));
1953 auto *shareMenu = new QMenu(tr("Share"), &contextMenu);
1954 contextMenu.addMenu(shareMenu);
1955
1956 const QString gpgIdPath = Pass::getGpgIdPath(dirPath, s.passStore);
1957 const bool gpgIdExists = !gpgIdPath.isEmpty() && QFile(gpgIdPath).exists();
1958 const QString exePath = s.usePass ? s.passExecutable : s.gpgExecutable;
1959 const bool gpgAvailable =
1960 !exePath.isEmpty() &&
1961 (Executor::parseWslCommand(exePath) || QFile(exePath).exists());
1962
1963 QAction *reencrypt = shareMenu->addAction(tr("Re-encrypt all passwords"));
1964 reencrypt->setEnabled(gpgIdExists && gpgAvailable);
1965 connect(reencrypt, &QAction::triggered, this,
1966 [this, dirPath]() { reencryptPath(dirPath); });
1967
1968 QAction *exportKey = shareMenu->addAction(tr("Export my public key..."));
1969 exportKey->setEnabled(gpgAvailable);
1970 connect(exportKey, &QAction::triggered, this, &MainWindow::exportPublicKey);
1971
1972 QAction *addRecipientAction = shareMenu->addAction(tr("Add recipient..."));
1973 addRecipientAction->setEnabled(gpgIdExists && gpgAvailable);
1974 connect(addRecipientAction, &QAction::triggered, this,
1975 [this, dirPath]() { addRecipient(dirPath); });
1976
1977 QAction *shareHelp = shareMenu->addAction(tr("What is this?"));
1978 connect(shareHelp, &QAction::triggered, this, &MainWindow::showShareHelp);
1979}
1980
1981auto MainWindow::backOnMenuEntry(const QString &openedOn) -> bool {
1982 const QModelIndex current = ui->treeView->currentIndex();
1983 if (openedOn.isEmpty()) {
1984 // Opened beside the entries: for the store itself.
1985 if (current.isValid()) {
1986 ui->treeView->setCurrentIndex(QModelIndex());
1987 }
1988 return true;
1989 }
1990 // Gone, also while the tree still lists it: the reload comes later. A
1991 // link that leads nowhere is still an entry.
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) {
1996 return true;
1997 }
1998 // Asked only about a path that exists: the file system model on macOS
1999 // lists a path again once it is asked for one that is gone.
2000 const QModelIndex shown = there ? m_tree->indexFor(openedOn) : QModelIndex();
2001 if (!shown.isValid()) {
2003 tr("%1 is no longer in the list.").arg(Util::shownName(openedOn)));
2004 return false;
2005 }
2006 ui->treeView->setCurrentIndex(shown);
2007 return true;
2008}
2009
2010void MainWindow::showContextMenu(const QPoint &pos) {
2012 const QModelIndex index = ui->treeView->indexAt(pos);
2013 const bool selected = index.isValid();
2014 if (!selected) {
2015 ui->treeView->clearSelection();
2016 ui->actionDelete->setEnabled(false);
2017 ui->actionEdit->setEnabled(false);
2018 }
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();
2023
2024 QMenu contextMenu;
2025 // The actions read the current entry when picked, and that may be another
2026 // one by then: a row removed in place by the file system model (its own
2027 // watcher, on macOS) hands the current index to a neighbour, and the
2028 // reload after it finds that one again. Delete would then remove the
2029 // neighbour. So each action first goes back to the entry the menu was
2030 // opened on, and does nothing when that is gone.
2031 const QString openedOn =
2032 selected ? fileOrFolder.absoluteFilePath() : QString();
2033 const auto add = [this, &contextMenu, openedOn](const QString &text,
2034 void (MainWindow::*slot)()) {
2035 connect(contextMenu.addAction(text), &QAction::triggered, this,
2036 [this, openedOn, slot]() {
2037 if (backOnMenuEntry(openedOn)) {
2038 (this->*slot)();
2039 }
2040 });
2041 };
2042 if (!selected || isDir) {
2043 add(tr("Open folder with file manager"), &MainWindow::openFolder);
2044 add(tr("Add folder"), &MainWindow::addFolder);
2045 add(tr("Add password"), &MainWindow::addPassword);
2046 add(tr("Users"), &MainWindow::onUsers);
2047 } else if (fileOrFolder.isFile()) {
2048 add(tr("Edit"), &MainWindow::onEdit);
2049 }
2050 if (selected) {
2051 contextMenu.addSeparator();
2052 if (isDir) {
2053 add(tr("Rename folder"), &MainWindow::renameFolder);
2054 } else if (fileOrFolder.isFile()) {
2055 add(tr("Rename password"), &MainWindow::renamePassword);
2056 }
2057 add(tr("Delete"), &MainWindow::onDelete);
2058 if (isDir) {
2059 addShareMenu(contextMenu, s);
2060 }
2061 }
2062 // With the current entry gone and nothing else current, the menu has
2063 // nothing left to act on.
2064 connect(m_tree, &StoreTree::currentEntryLost, &contextMenu, &QMenu::close);
2065 contextMenu.exec(globalPos);
2066}
2067
2068auto MainWindow::browserContextMenu(const QPoint &pos) -> QMenu * {
2069 // createStandardContextMenu() takes document coordinates, anchorAt() and
2070 // the menu's place viewport ones: scrolled, the menu checked the text
2071 // above the link and left "Copy Link Location" disabled.
2072 // Right to left, the horizontal offset counts from the other end.
2073 const QScrollBar *across = ui->textBrowser->horizontalScrollBar();
2074 const int dx = ui->textBrowser->isRightToLeft()
2075 ? across->maximum() - across->value()
2076 : across->value();
2077 const QPoint documentPos =
2078 pos + QPoint(dx, ui->textBrowser->verticalScrollBar()->value());
2079 QMenu *contextMenu = ui->textBrowser->createStandardContextMenu(documentPos);
2080 // Reparent from textBrowser: a browser stylesheet cascades to the child
2081 // QMenu and breaks its opaque native background.
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);
2090 }
2091 });
2092 }
2093 return contextMenu;
2094}
2095
2096void MainWindow::showBrowserContextMenu(const QPoint &pos) {
2097 QMenu *contextMenu = browserContextMenu(pos);
2098 contextMenu->exec(ui->textBrowser->viewport()->mapToGlobal(pos));
2099 delete contextMenu;
2100}
2101
2103 QString dir = m_tree->currentDir(false);
2104
2105 QString path = QDir::toNativeSeparators(dir);
2106 QDesktopServices::openUrl(QUrl::fromLocalFile(path));
2107}
2108
2111 bool ok;
2112 QString dir = m_tree->currentDir(false);
2113 QString newdir = QInputDialog::getText(
2114 this, tr("New folder"),
2115 tr("New folder: \n(Will be placed in %1 )")
2116 .arg(Util::shownName(s.passStore + m_tree->currentDir(true))),
2117 QLineEdit::Normal, "", &ok);
2118 if (!ok || newdir.isEmpty()) {
2119 return;
2120 }
2121 // Checked and created as one and the same path: the check resolves ".."
2122 // lexically, the system after following links, so "link/../x" would pass
2123 // as the store's x and be made beside the link's target.
2124 newdir = QDir::cleanPath(newdir.prepend(dir));
2125 if (!confirmPathInStore(newdir)) {
2126 return;
2127 }
2128 // Behind a link the folder would be made outside the store, as Users,
2129 // Re-encrypt and Delete already refuse.
2130 if (refuseLinkedFolder(newdir)) {
2131 return;
2132 }
2133 // The tree, like `pass ls`, hides names that start with a dot.
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'.');
2138 })) {
2139 PlainMessageBox::warning(this, tr("Hidden folder"),
2140 tr("A folder that starts with a dot would be "
2141 "hidden from the list: %1")
2142 .arg(newdir));
2143 return;
2144 }
2145 // Exists already: an error, as QDir::mkdir() made it before.
2146 if (QFileInfo::exists(newdir) || !Util::mkpathForStore(newdir)) {
2147 PlainMessageBox::warning(this, tr("Error"),
2148 tr("Failed to create folder: %1").arg(newdir));
2149 return;
2150 }
2151 // No .gpg-id of its own: the folder uses its parent's recipients, as with
2152 // pass, until Users gives it a list. A copy of the parent's list (#1688)
2153 // kept every recipient later removed above it, and its entries stayed
2154 // readable by them.
2155}
2156
2158 bool ok;
2159 QString srcDir = QDir::cleanPath(m_tree->currentDir(false));
2160 QString srcDirName = QDir(srcDir).dirName();
2161 QString newName =
2162 QInputDialog::getText(this, tr("Rename folder"), tr("Rename folder to: "),
2163 QLineEdit::Normal, srcDirName, &ok);
2164 if (!ok || newName.isEmpty()) {
2165 return;
2166 }
2167 QString destDir = srcDir;
2168 destDir.replace(srcDir.lastIndexOf(srcDirName), srcDirName.length(), newName);
2169 if (!confirmPathInStore(destDir)) {
2170 return;
2171 }
2173 this, QtPassSettings::getPassStore(), [&srcDir, &destDir] {
2174 return QtPassSettings::getPass()->entriesMoveWouldWiden(srcDir,
2175 destDir);
2176 })) {
2177 return;
2178 }
2179 QtPassSettings::getPass()->Move(std::move(srcDir), std::move(destDir), false);
2180}
2181
2182void MainWindow::editPassword(const QString &file) {
2183 if (!file.isEmpty()) {
2185 if (s.useGit && s.autoPull) {
2186 onUpdate(true);
2187 }
2188 // The dialog decrypts the entry itself to fill its fields. That decrypt
2189 // lands on the same finishedShow the panel uses, so drop the panel's claim
2190 // to it: otherwise passShowHandler() repaints and, with "Always copy",
2191 // puts the entry's old password on the clipboard - replacing whatever the
2192 // user copied to paste into the dialog.
2193 m_shownFile.clear();
2194 setPassword(file, false);
2195 }
2196}
2197
2199 bool ok;
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)) {
2204 fileName.chop(4);
2205 }
2206
2207 QString newName =
2208 QInputDialog::getText(this, tr("Rename file"), tr("Rename file to: "),
2209 QLineEdit::Normal, fileName, &ok);
2210 if (!ok || newName.isEmpty()) {
2211 return;
2212 }
2213 QString newFile = Util::joinPath(filePath, newName);
2214 if (!confirmPathInStore(newFile)) {
2215 return;
2216 }
2218 this, QtPassSettings::getPassStore(), [&file, &newFile] {
2219 return QtPassSettings::getPass()->entriesMoveWouldWiden(file,
2220 newFile);
2221 })) {
2222 return;
2223 }
2224 QtPassSettings::getPass()->Move(std::move(file), std::move(newFile), false);
2225}
2226
2228 QWidget *focus = QApplication::focusWidget();
2229 // The widget's own copy: a SecretTextBrowser marks what it copies as
2230 // secret for clipboard managers, as the context menu's Copy does.
2231 if (auto *text = qobject_cast<QTextEdit *>(focus);
2232 text != nullptr && text->textCursor().hasSelection()) {
2233 text->copy();
2234 return;
2235 }
2236 // Through the clipboard manager, as a copy button would: the label may be
2237 // the OTP code, which gets the secret hint and the autoclear.
2238 if (auto *label = qobject_cast<QLabel *>(focus);
2239 label != nullptr && label->hasSelectedText()) {
2240 m_qtPass->clipboard().copyText(label->selectedText());
2241 return;
2242 }
2243 // A line of the content search results is decrypted text: through the
2244 // clipboard manager too, for the secret hint and the autoclear.
2245 if (focus == ui->grepResultsList) {
2246 if (const QTreeWidgetItem *item = ui->grepResultsList->currentItem();
2247 item != nullptr && !item->text(0).isEmpty()) {
2248 m_qtPass->clipboard().copyText(item->text(0));
2249 }
2250 return;
2251 }
2253}
2254
2256 // While content search results hide the tree, its current entry is not
2257 // what the user looks at: no decrypt, as for Edit and OTP.
2258 if (ui->treeView->isHidden()) {
2259 return;
2260 }
2261 QFileInfo fileOrFolder = m_tree->fileInfo(ui->treeView->currentIndex());
2262
2263 if (fileOrFolder.isFile()) {
2264 QString file = getFile(ui->treeView->currentIndex(), true);
2265 // The newest Ctrl+C wins: finishedShow names its file, so the decrypt of
2266 // an earlier request is simply not this one's.
2267 m_copyRequestFile = file;
2268 // This Show repaints the panel as well; see onOtp().
2269 m_shownFile = file;
2270 QtPassSettings::getPass()->Show(std::move(file));
2271 }
2272}
2273
2275 const QString &file) {
2276 if (m_copyRequestFile.isEmpty() || file != m_copyRequestFile) {
2277 return;
2278 }
2279 m_copyRequestFile.clear();
2280 // The first line, without a list of every line (an entry can expand into
2281 // millions of them), and without the "\r" of a CRLF line end, as the
2282 // password row and "Always copy" have it.
2283 const QString first = FileContent::passwordLine(text);
2284 // A `pass otp insert` entry's first line is the otpauth:// URI carrying the
2285 // TOTP seed, and an OTP field holding a seed there is the same; copying it
2286 // would leak 2FA material. Matches the display path
2287 // (FileContent::getPasswordForDisplay / PasswordDisplayPanel).
2288 if (FileContent::isOtpPasswordLine(first)) {
2289 flashText(tr("This entry holds an OTP secret, not a password"), true);
2290 return;
2291 }
2292 m_qtPass->clipboard().copyText(first);
2293}
2294
2295void MainWindow::showStatusMessage(const QString &msg, int timeout) {
2296 ui->statusBar->showMessage(msg, timeout);
2297}
2298
2299void MainWindow::reencryptPath(const QString &dir) {
2300 QDir checkDir(dir);
2301 if (!checkDir.exists()) {
2302 PlainMessageBox::critical(this, tr("Error"),
2303 tr("Directory does not exist: %1").arg(dir));
2304 return;
2305 }
2306 if (refuseLinkedFolder(dir)) {
2307 return;
2308 }
2309
2310 const bool yes = PlainMessageBox::askYes(
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"
2316 "Continue?")
2317 // On one line: a name with line feeds pushed the warning out of
2318 // the box, which shows 40 lines at most.
2319 .arg(Util::displayable(QDir(dir).dirName(), false)));
2320
2321 if (!yes)
2322 return;
2323
2324 // Disable now; the asynchronous startReencryptPath signal re-runs this
2325 // harmlessly.
2327
2328 // Under the current profile's settings: with the pass backend active, the
2329 // native one is not re-initialised on a profile switch.
2330 QtPassSettings::getImitatePass()->reencryptPath(
2331 QDir::cleanPath(QDir(dir).absolutePath()), QtPassSettings::load());
2332}
2333
2334// Idempotent: reencryptPath() calls it before ImitatePass emits the signal.
2336 m_reencryptRunning = true;
2337 setUiElementsEnabled(false);
2338 // The worker always ends with endReencryptPath(), and Cancel is available
2339 // throughout, so the generic watchdog is not needed for this operation.
2340 m_uiWatchdog.stop();
2341 ui->treeView->setDisabled(true);
2343 return;
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]() {
2352 QtPassSettings::getImitatePass()->cancelReencryptPath();
2353 showStatusMessage(tr("Cancelling re-encryption"), 5000);
2354 });
2355 m_reencryptProgress = progress;
2356 progress->show();
2357}
2358
2359void MainWindow::reencryptProgress(int current, int total) {
2361 return;
2362 QProgressDialog *progress = m_reencryptProgress;
2363 progress->setMaximum(total);
2364 progress->setLabelText(
2365 tr("Re-encrypting passwords: %1 of %2").arg(current).arg(total));
2366 // On a modal dialog setValue() runs processEvents(), which can deliver
2367 // endReencryptPath(), even inside a nested event loop that would delete a
2368 // deleteLater()ed dialog under setValue()'s feet: keep this last, and
2369 // delete the dialog only after it returns.
2370 m_inProgressUpdate = true;
2371 progress->setValue(current);
2372 m_inProgressUpdate = false;
2373 if (m_progressToDelete) {
2374 m_progressToDelete->deleteLater();
2375 m_progressToDelete = nullptr;
2376 }
2377}
2378
2380 m_reencryptRunning = false;
2381 if (m_reencryptProgress) {
2382 m_reencryptProgress->hide();
2383 if (m_inProgressUpdate) {
2385 } else {
2386 m_reencryptProgress->deleteLater();
2387 }
2388 m_reencryptProgress = nullptr;
2389 }
2391}
2392
2394 const QStringList &files,
2395 const QStringList &details) {
2397 const QDir store(s.passStore);
2398 // Sorted by name, so each folder's entries stand together; who would gain
2399 // each one beside it, as the names alone are the writer's choosing.
2400 QList<std::pair<QString, QString>> rows;
2401 for (qsizetype i = 0; i < files.size(); ++i) {
2402 rows.append({Util::displayable(store.relativeFilePath(files.at(i)), false),
2403 details.value(i)});
2404 }
2405 std::sort(rows.begin(), rows.end());
2406 constexpr int kListed = 15;
2407 QStringList lines;
2408 for (qsizetype i = 0; i < rows.size() && i < kListed; ++i) {
2409 lines << rows.at(i).first + QStringLiteral(": ") + rows.at(i).second;
2410 }
2411 if (rows.size() > kListed) {
2412 lines << tr("... and %n more", nullptr,
2413 static_cast<int>(rows.size() - kListed));
2414 }
2415 const int n = static_cast<int>(files.size());
2416 const bool yes = PlainMessageBox::askYes(
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.",
2422 nullptr, n) +
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."));
2427 if (!yes) {
2428 return;
2429 }
2431 QtPassSettings::getImitatePass()->reencryptAlso(dir, files, s);
2432}
2433
2436 const QString identity = s.passSigningKey;
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 "&gt; GPG keys, or run this in a terminal:</p>"
2443 "<pre>gpg --armor --export --output my_key.asc &lt;your-key-id"
2444 "&gt;</pre>"
2445 "<p>Then send the file to your teammates.</p>"));
2446 return;
2447 }
2448 QString gpgExe = s.gpgExecutable;
2449 if (gpgExe.isEmpty()) {
2450 gpgExe = QStringLiteral("gpg");
2451 }
2452 const QStringList keys = identity.split(' ', Qt::SkipEmptyParts);
2453 // gpg --export takes every key block that holds the ID: another key that
2454 // holds yours as a subkey would go out to your teammates as yours.
2455 if (Pass *pass = QtPassSettings::getPass(); pass != nullptr) {
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")
2463 return;
2464 }
2465 }
2466 QString stdOut;
2467 QString stdErr;
2468 // In the store's environment, the keyring the check above read.
2469 Pass *pass = QtPassSettings::getPass();
2470 int exitCode =
2471 pass != nullptr
2472 ? pass->exportPublicKeys(gpgExe, keys, &stdOut, &stdErr)
2474 QStringList{QStringLiteral("--armor"),
2475 QStringLiteral("--export")} +
2476 keys,
2477 &stdOut, &stdErr);
2478 if (exitCode != 0 || stdOut.isEmpty()) {
2479 PlainMessageBox::warning(this, tr("Export public key"),
2480 tr("Could not export public key for %1.\n\n%2")
2481 .arg(identity, stdErr.isEmpty()
2482 ? tr("No output from gpg.")
2483 : stdErr));
2484 return;
2485 }
2486 ExportPublicKeyDialog dialog(identity, stdOut, this);
2487 dialog.exec();
2488}
2489
2490// UsersDialog only ticks keys already in the keyring; importing a foreign
2491// key still has to happen via gpg (or QtPass settings) first.
2492void MainWindow::addRecipient(const QString &dir) {
2493 if (refuseLinkedFolder(dir)) {
2494 return;
2495 }
2497 d.exec();
2498}
2499
2500// A tree-picked folder that is, or lies behind, a symlink or junction is not
2501// a folder of the store. The store root itself may be a link (a synced
2502// folder); that is configuration, not a tree pick.
2503auto MainWindow::refuseLinkedFolder(const QString &dir) -> bool {
2504 if (!Util::isUnderLink(dir, QtPassSettings::load().passStore)) {
2505 return false;
2506 }
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))));
2512 return true;
2513}
2514
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>"
2520 "<ol>"
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 "
2524 "them</li>"
2525 "</ol>"
2526 "<p>Only people who have a matching secret key can decrypt the "
2527 "passwords.</p>"
2528 "<p><b>Tip:</b> Use the same GPG key for all shared folders.</p>"
2529 "<p>See the FAQ for more details.</p>"));
2530}
2531
2534 // Without Git there is nothing to push or pull, ever: the buttons go, not
2535 // grey out. While an operation runs they stay and are disabled.
2536 const bool usable =
2537 s.useGit && !(s.gitExecutable.isEmpty() && s.passExecutable.isEmpty());
2538 ui->actionPush->setVisible(usable);
2539 ui->actionUpdate->setVisible(usable);
2540 // The separator in front of them would otherwise sit next to the next one.
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);
2545 }
2546 enableGitButtons(usable && uiEnabled);
2547}
2548
2550 // No platform gating: codes are generated in-process. Visible but disabled
2551 // when OTP is off: the panel never shows an OTP field (a secret), so hiding
2552 // this too would leave no trace of the feature. Honour uiEnabled, or the
2553 // user can stack Show calls while a decrypt is in flight.
2554 ui->actionOtp->setVisible(true);
2555 ui->actionOtp->setEnabled(QtPassSettings::isUseOtp() && uiEnabled);
2556}
2557
2559 const bool enabled = QtPassSettings::isUseGrepSearch();
2560 ui->grepButton->setVisible(enabled);
2561 ui->grepCaseButton->setVisible(enabled);
2562 if (!enabled && m_grep.inGrepMode()) {
2563 ui->grepButton->setChecked(false);
2564 }
2565}
2566
2567void MainWindow::enableGitButtons(const bool &state) {
2568 ui->actionPush->setEnabled(state);
2569 ui->actionUpdate->setEnabled(state);
2570}
2571
2572void MainWindow::critical(const QString &title, const QString &msg) {
2573 // Pass's messages quote store paths; see PlainMessageBox.
2574 PlainMessageBox::critical(this, title, msg);
2575}
2576
2577void MainWindow::onProcessOutput(const QString &output, bool isError,
2578 Enums::PROCESS pid) {
2580 return;
2581 }
2582 m_processOutput->append(output, isError,
2584}
2585
2587 // The action's toggled handler shows or hides the dock.
2588 ui->actionShowProcessOutput->setChecked(
2591}
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.
Definition executor.cpp:700
static auto parseWslCommand(const QString &app) -> std::optional< WslCommand >
Parse a configured executable as a WSL command.
Definition executor.cpp:272
Dialog showing an ASCII-armored public GPG key for sharing.
Represents the parsed contents of a password file.
Definition filecontent.h:92
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.
Definition imitatepass.h:41
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.
Definition mainwindow.h:578
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.
bool m_uiEnabled
Definition mainwindow.h:667
void renameFolder()
Context menu "Rename folder": ask for a new name and Move the current folder, refusing a target outsi...
QString m_panelEntry
Definition mainwindow.h:602
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
Definition mainwindow.h:609
void onConfig()
Toolbar "Config": config(), ignoring its result; refused while a backend still runs or waits,...
void saveWindowState()
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.
QTimer m_uiWatchdog
Definition mainwindow.h:639
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
Definition mainwindow.h:659
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.
Definition mainwindow.h:583
QTimer searchTimer
Definition mainwindow.h:629
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
Definition mainwindow.h:647
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
Definition mainwindow.h:624
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.
Definition mainwindow.h:626
void reencryptProgress(int current, int total)
Update the re-encryption progress dialog.
void keyPressEvent(QKeyEvent *event) override
Handle keyboard shortcuts.
bool m_freshStart
Definition mainwindow.h:678
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.
QTimer clearResultsTimer
Definition mainwindow.h:635
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...
bool m_themeSwitched
Definition mainwindow.h:593
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
Definition mainwindow.h:617
void on_grepButton_toggled(bool checked)
The content-search toggle changed: switch the search box between name filtering and regex content sea...
QTimer clearPanelTimer
Definition mainwindow.h:629
void selectFirstFile()
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.
Definition mainwindow.h:116
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
Definition mainwindow.h:606
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...
Definition mainwindow.h:588
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,...
QString m_otpRequestFile
Definition mainwindow.h:613
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.
Definition mainwindow.h:576
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
Definition mainwindow.h:642
void showAbout()
Show the About box: version, project link, licence.
static constexpr int UiWatchdogMs
Interval of m_uiWatchdog in milliseconds.
Definition mainwindow.h:644
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.
QString m_shownFile
Definition mainwindow.h:598
QPointer< QProgressDialog > m_progressToDelete
Definition mainwindow.h:656
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 connectBackends()
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...
bool m_inProgressUpdate
Definition mainwindow.h:653
void applyTextBrowserSettings()
auto config() -> bool
Open the configuration dialog.
auto getCurrentTreeViewIndex() -> QModelIndex
Return the currently selected index in the tree view.
bool m_initSucceeded
Definition mainwindow.h:675
void cancelContentSearch()
void onUpdate(bool block=false)
Toolbar "Update": git pull.
void initTimers()
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 initProcessOutput()
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.
TrayIcon * m_tray
Definition mainwindow.h:671
QtPass * m_qtPass
The UI-neutral glue to the backends (output, status, clipboard, QR codes); created in the constructor...
Definition mainwindow.h:574
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...
bool m_reencryptRunning
Definition mainwindow.h:664
MenuBarPeek(QMainWindow *window, QAction *toggle)
Watch window for Alt while its menu bar is hidden.
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...
Definition nativegrep.h:108
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.
Definition nativegrep.h:80
static auto passwordMatchText(const QString &line) -> QString
The text of a match isPasswordMatch() accepts.
Definition nativegrep.h:117
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"...
Definition nativegrep.h:131
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...
Definition nativegrep.h:95
Abstract base class for password store operations.
Definition pass.h:77
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.
Definition pass.cpp:558
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.
Definition pass.h:740
static auto getGpgIdPath(const QString &for_file, const QString &passStore) -> QString
Get .gpg-id file path for a password file.
Definition pass.cpp:1511
auto reportedInsert() const -> QString
The entry whose insert is reporting now: set while finishedInsert() or insertFailed() goes out,...
Definition pass.h:336
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.
Definition pass.cpp:643
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.
Definition pass.h:729
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.
Definition pass.h:711
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.
Definition pass.h:717
auto runningSerial() const -> quint64
Which run is going (Executor::runningSerial()).
Definition pass.h:722
void updateEnv()
Update environment for subprocesses.
Definition pass.cpp:984
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.
Definition pass.h:216
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 &currentFolder)
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,...
Definition qtpass.cpp:146
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.
Definition qtpass.h:55
void init()
Resolve the password store and the executables and migrate the settings of an older version (fresh-in...
Definition qtpass.cpp:31
QtPass(QObject *parent=nullptr)
Construct the glue and connect it to both pass backends.
Definition qtpass.cpp:22
void closeQRCode()
Close the QR code popup showTextAsQRCode() has open, if any: the autoclear of the panel takes the cod...
Definition qtpass.cpp:228
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...
Definition qtpass.cpp:184
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.
Definition storemodel.h:85
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,...
Definition storetree.cpp:16
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 &
Definition storetree.h:156
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 &
Definition storetree.h:154
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.
Definition totp.cpp:422
static auto parse(const QString &config, Refusal *why=nullptr) -> std::optional< Settings >
Parse an OTP configuration string.
Definition totp.cpp:264
static auto describe(Refusal why) -> QString
One sentence for the user on why a configuration gives no code.
Definition totp.cpp:329
Refusal
Why parse() gave no settings, so the user can be told more than "invalid".
Definition totp.h:59
@ None
Parsed: there was nothing to refuse.
Definition totp.h:60
void addToggle(QAction *action)
Put one of the window's toggles in the tray menu, above Quit.
Definition trayicon.cpp:76
TrayIcon(QMainWindow *parent)
Construct a TrayIcon associated with the given main window.
Definition trayicon.cpp:16
auto getIsAllocated() -> bool
Check whether tray resources have been allocated and initialized.
Definition trayicon.cpp:38
Dialog for selecting GPG recipients for password encryption.
Definition usersdialog.h:36
static auto hasLongUnbrokenRun(QStringView text) -> bool
Whether text holds more than kMaxUnbrokenRun characters in a row without white space Qt wraps at (a n...
Definition util.cpp:976
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...
Definition util.cpp:1217
static auto findPasswordStore() -> QString
Locate the password store directory.
Definition util.cpp:81
static auto configIsValid(const AppSettings &s) -> bool
Verify that the required configuration is complete.
Definition util.cpp:733
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...
Definition util.cpp:1149
static auto mkpathForStore(const QString &path) -> bool
Create path and any missing parents as pass would.
Definition util.cpp:615
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,...
Definition util.cpp:898
static auto isLinkedFolder(const QString &path) -> bool
Whether path names a symbolic link or NTFS junction, with or without a trailing separator (which woul...
Definition util.cpp:1213
static auto joinPath(const QString &dir, const QString &name) -> QString
name in dir, as the file system means it.
Definition util.cpp:110
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.
Definition util.cpp:1000
static auto directoriesUnder(const QString &dir) -> QStringList
Every real, visible directory under dir, walked by the same rules as regularFilesUnder(): links,...
Definition util.cpp:1180
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 ...
MenuBarPeek: shows the main window's hidden menu bar while Alt is held or tapped, and hides it again ...
auto processLabel(PROCESS pid) -> QString
The command label for pid, as the output panel shows it.
PROCESS
Identifies different subprocess operations used in QtPass.
Definition enums.h:43
@ PASS_GREP
Definition enums.h:59
@ PASS_SHOW
Definition enums.h:50
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.
Definition profile.h:81
Icon button that asks for a stored secret to be shown as a QR code.
Eye-icon button that toggles a QLineEdit between password and plain-text echo mode.
Copy-to-clipboard icon button that carries the text of the field it sits next to.
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.
Definition appsettings.h:36
bool displayAsIs
Show file content unmodified.
Definition appsettings.h:97
QString gpgExecutable
Path to the gpg/gpg2 executable.
Definition appsettings.h:66
QString passSigningKey
GPG key used to sign .gpg-id files.
Definition appsettings.h:61
bool usePass
Use the pass CLI (true) or native git/gpg.
Definition appsettings.h:59
bool hideContent
Hide the entire content panel.
Definition appsettings.h:95
bool useOtp
Enable native TOTP (OTP) support.
QString passStore
Password-store root path.
Definition appsettings.h:60
bool hidePassword
Definition appsettings.h:85
bool useAutoclearPanel
Clear the content panel after a delay.
Definition appsettings.h:81
bool noLineWrapping
Disable line wrapping in the panel.
Definition appsettings.h:98
bool showMenuBar
Show the menu bar (Ctrl+M toggles it).
QString gitExecutable
Path to the git executable.
Definition appsettings.h:65
bool autoPull
git pull before an entry is edited and before a re-encryption.
int autoclearPanelSeconds
Panel autoclear delay (seconds).
Definition appsettings.h:82
bool startMinimized
Start the window minimised.
bool useTrayIcon
Show a system tray icon.
QString passExecutable
Path to the pass executable.
Definition appsettings.h:64
bool useGit
Enable git integration.
QString passTemplate
Newline-separated template field names.
bool useMonospace
Render content in a monospace font.
Definition appsettings.h:96
bool templateAllFields
Treat every key: line as a field.
QString activeProfile
Name of the active profile.
Definition appsettings.h:56
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...
Definition profile.h:26
QString path
Password store directory.
Definition profile.h:27
QString signingKey
Key(s) that sign this store's .gpg-id.
Definition profile.h:28
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.
Definition util.h:25
WindowStateStore: saves and restores top-level window geometry through QtPassSettings,...