Branch data Line data Source code
1 : : // SPDX-FileCopyrightText: 2014 Anne Jan Brouwer
2 : : // SPDX-License-Identifier: GPL-3.0-or-later
3 : : /**
4 : : * @file
5 : : * @brief Implements MainWindow; the backend signal wiring lives in
6 : : * connectBackends() and connectPassSignals(), the decrypted-entry
7 : : * rendering in passShowHandler().
8 : : */
9 : : #include "mainwindow.h"
10 : :
11 : : #include "qtpasslogging.h"
12 : :
13 : : #include "configdialog.h"
14 : : #include "enums.h"
15 : : #include "executor.h"
16 : : #include "exportpublickeydialog.h"
17 : : #include "filecontent.h"
18 : : #include "firstrunwizard.h"
19 : : #include "menubarpeek.h"
20 : : #include "nativegrep.h"
21 : : #include "passworddialog.h"
22 : : #include "passworddisplaypanel.h"
23 : : #include "pathvalidator.h"
24 : : #include "plainmessagebox.h"
25 : : #include "processinfo.h"
26 : : #include "processoutputpanel.h"
27 : : #include "qpushbuttonasqrcode.h"
28 : : #include "qpushbuttonshowpassword.h"
29 : : #include "qpushbuttonwithclipboard.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 : :
70 : : /**
71 : : * @brief What the Stop button calls a run.
72 : : * @param pid The kind of command that runs.
73 : : * @return Its command line label ("git pull", "pass init"); "a decrypt" for
74 : : * a decrypt, whose label the output panel leaves empty; "a command"
75 : : * when the kind is unknown.
76 : : */
77 : 14 : static auto runLabel(Enums::PROCESS pid) -> QString {
78 [ + + ]: 14 : if (pid == Enums::PASS_SHOW) {
79 : 4 : return QCoreApplication::translate("MainWindow", "a decrypt");
80 : : }
81 : 10 : const QString label = Enums::processLabel(pid);
82 : : return label.isEmpty()
83 [ - + ]: 10 : ? QCoreApplication::translate("MainWindow", "a command")
84 : 0 : : label;
85 : : }
86 : :
87 : 206 : MainWindow::MainWindow(const QString &searchText, QWidget *parent)
88 : 206 : : 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 : 206 : ui->setupUi(this);
95 : :
96 : 206 : m_qtPass = new QtPass(this);
97 : 206 : restoreWindow();
98 : 206 : connectBackends();
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 : 206 : QKeySequence::keyBindings(QKeySequence::StandardKey::Copy);
105 [ + + ]: 618 : for (const QKeySequence &keys : copyKeys) {
106 : 412 : new QShortcut(keys, this, this, &MainWindow::copySelectionOrPassword);
107 : : }
108 : :
109 : 206 : m_tree = new StoreTree(ui->treeView, this);
110 : 206 : m_tree->setStore(QtPassSettings::getPassStore(Util::findPasswordStore()));
111 : 206 : m_tree->setPass(QtPassSettings::getPass());
112 : 206 : connect(ui->treeView, &QWidget::customContextMenuRequested, this,
113 : 206 : &MainWindow::showContextMenu);
114 : 206 : connect(ui->treeView, &DeselectableTreeView::emptyClicked, this,
115 : 206 : &MainWindow::deselect);
116 : :
117 : 206 : initTextBrowser();
118 : :
119 : 206 : updateProfileBox();
120 : :
121 : 206 : initDisplayPanel();
122 : :
123 : 206 : QtPassSettings::getPass()->updateEnv();
124 : :
125 : : // Install the search-box key filter once, not on every setUiElementsEnabled
126 : : // call.
127 : 206 : 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 : 206 : ui->toolBar->installEventFilter(this);
131 : 206 : menuBar()->installEventFilter(this);
132 : :
133 : 206 : initTimers();
134 : :
135 : 206 : initToolBarButtons();
136 : 206 : initStatusBar();
137 : 206 : initProcessOutput();
138 : :
139 : 206 : ui->lineEdit->setClearButtonEnabled(true);
140 : 206 : updateGrepButtonVisibility();
141 : :
142 : 206 : setUiElementsEnabled(true);
143 : :
144 : : // No QApplication::quit() here: before exec() it is a documented no-op.
145 : : // main() checks initSucceeded() and exits before show() instead.
146 : 206 : 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.
149 [ + + + + ]: 207 : while (!Util::configIsValid(QtPassSettings::load())) {
150 [ + + + ]: 2 : 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.
157 : 205 : QtPassSettings::getInstance()->remove(SettingsConstants::firstRunPending);
158 : 205 : m_freshStart = false;
159 : 205 : 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 [ - + ]: 205 : if (!searchText.isEmpty()) {
167 : : QTimer::singleShot(0, this,
168 : 0 : [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 : 0 : }
175 : :
176 : 206 : void MainWindow::connectBackends() {
177 : 206 : connect(m_qtPass, &QtPass::outputReady, this,
178 : 251 : [this](const QString &html) { flashText(html, false, true); });
179 : 206 : connect(m_qtPass, &QtPass::operationFinished, this,
180 : 276 : [this]() { setUiElementsEnabled(true); });
181 : 206 : connect(m_qtPass, &QtPass::statusMessage, this,
182 : 206 : &MainWindow::showStatusMessage);
183 : 206 : connect(m_qtPass, &QtPass::pushRequested, this, &MainWindow::onAutoPush);
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 : 206 : connect(m_qtPass, &QtPass::entryInserted, this, [this]() {
190 : 11 : const QModelIndex index = getCurrentTreeViewIndex();
191 : 11 : const QString file = getFile(index, true);
192 : 11 : Pass *pass = QtPassSettings::getPass();
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 : 11 : if (const QString saved = pass->reportedInsert();
198 [ + + ]: 3 : !saved.isEmpty() &&
199 [ + + + + : 20 : QDir::cleanPath(saved) != QDir::cleanPath(getFile(index, false))) {
+ + + + +
- - - - ]
200 : : return;
201 : : }
202 [ + - + + ]: 20 : if (!file.isEmpty() && pass->isPushing()) {
203 : 8 : m_refreshAfterPush = file;
204 : 8 : m_refreshAfterPushOwner = pass;
205 : 8 : m_shownFile = file;
206 : 8 : return;
207 : : }
208 : 2 : on_treeView_clicked(index);
209 : : });
210 : 206 : connect(&m_qtPass->clipboard(), &ClipboardManager::statusMessage, this,
211 : 229 : [this](const QString &message) { showStatusMessage(message); });
212 : : // Both backends: the active one can change through the configuration
213 : : // dialog without a restart.
214 : 206 : connectPassSignals(QtPassSettings::getRealPass());
215 : 206 : connectPassSignals(QtPassSettings::getImitatePass());
216 : 206 : ImitatePass *ipass = QtPassSettings::getImitatePass();
217 : 206 : connect(ipass, &ImitatePass::startReencryptPath, this,
218 : 206 : &MainWindow::startReencryptPath);
219 : 206 : connect(ipass, &ImitatePass::reencryptProgress, this,
220 : 206 : &MainWindow::reencryptProgress);
221 : 206 : connect(ipass, &ImitatePass::endReencryptPath, this,
222 : 206 : &MainWindow::endReencryptPath);
223 : 206 : connect(ipass, &ImitatePass::unexpectedRecipients, this,
224 : 206 : &MainWindow::askReencryptUnexpected);
225 : 206 : }
226 : :
227 : 206 : void MainWindow::initTextBrowser() {
228 : : {
229 : 206 : const AppSettings s = QtPassSettings::load();
230 [ + + ]: 206 : if (s.useMonospace) {
231 : 1 : QFont monospace("Monospace");
232 : 1 : monospace.setStyleHint(QFont::Monospace);
233 : 1 : ui->textBrowser->setFont(monospace);
234 : 1 : }
235 [ + + ]: 206 : if (s.noLineWrapping) {
236 : 1 : ui->textBrowser->setLineWrapMode(QTextBrowser::NoWrap);
237 : : }
238 : 206 : clearPanelTimer.setInterval(MS_PER_SECOND * s.autoclearPanelSeconds);
239 : 206 : clearResultsTimer.setInterval(clearPanelTimer.interval());
240 : 206 : }
241 : 206 : ui->textBrowser->setOpenExternalLinks(true);
242 : 206 : ui->textBrowser->setContextMenuPolicy(Qt::CustomContextMenu);
243 : 206 : connect(ui->textBrowser, &QWidget::customContextMenuRequested, this,
244 : 206 : &MainWindow::showBrowserContextMenu);
245 : 206 : }
246 : :
247 : 206 : void MainWindow::initDisplayPanel() {
248 : 206 : m_displayPanel = new PasswordDisplayPanel(
249 : 206 : ui->gridLayout, ui->verticalLayoutPassword, this, this);
250 : 206 : connect(m_displayPanel, &PasswordDisplayPanel::copyRequested,
251 : 206 : &m_qtPass->clipboard(), &ClipboardManager::copyText);
252 : 206 : connect(m_displayPanel, &PasswordDisplayPanel::textCopied,
253 : 206 : &m_qtPass->clipboard(), &ClipboardManager::trackCopied);
254 : 206 : connect(ui->textBrowser, &SecretTextBrowser::copied, &m_qtPass->clipboard(),
255 : 206 : &ClipboardManager::trackCopied);
256 : 206 : connect(m_displayPanel, &PasswordDisplayPanel::qrRequested, m_qtPass,
257 : 206 : &QtPass::showTextAsQRCode);
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.
261 : 206 : connect(m_displayPanel, &PasswordDisplayPanel::editRequested, this, [this] {
262 [ + + + - ]: 4 : if (ui->actionEdit->isEnabled() && !m_panelEntry.isEmpty()) {
263 : 3 : editPassword(m_panelEntry);
264 : : }
265 : 4 : });
266 : 206 : }
267 : :
268 : 206 : void MainWindow::initTimers() {
269 : 206 : clearPanelTimer.setSingleShot(true);
270 : 206 : connect(&clearPanelTimer, &QTimer::timeout, this,
271 : 208 : [this]() { clearShownEntry(true); });
272 : 206 : clearResultsTimer.setSingleShot(true);
273 : 206 : connect(&clearResultsTimer, &QTimer::timeout, this,
274 : 206 : &MainWindow::clearContentResults);
275 : :
276 : 206 : searchTimer.setInterval(350);
277 : 206 : searchTimer.setSingleShot(true);
278 : :
279 : 206 : 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 : 206 : m_uiWatchdog.setSingleShot(true);
284 : 206 : m_uiWatchdog.setInterval(UiWatchdogMs);
285 : 206 : connect(&m_uiWatchdog, &QTimer::timeout, this, [this]() {
286 : 6 : 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 : 6 : if (Pass *pass = QtPassSettings::getPass();
291 [ + - ]: 6 : pass != nullptr && !pass->isIdle()) {
292 : 12 : m_stopButton->setToolTip(tr("Stop %1, which is still running")
293 [ + - + + ]: 18 : .arg(runLabel(pass->runningProcess())));
294 : 6 : m_stopButton->show();
295 : : }
296 : : // Drop any in-flight OTP request so a late finishedShow cannot be mistaken
297 : : // for the answer to it.
298 : 6 : cancelOtpRequest();
299 : 6 : setUiElementsEnabled(true);
300 : 6 : });
301 : 206 : }
302 : :
303 : 206 : void MainWindow::initProcessOutput() {
304 : 206 : m_processOutput = new ProcessOutputPanel(this);
305 : 206 : 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.
308 : 206 : m_processOutput->setVisible(QtPassSettings::isShowProcessOutput());
309 : : // From the setting, not isVisible(): the window is not shown yet, so no
310 : : // child of it reports visible.
311 : 206 : ui->actionShowProcessOutput->setChecked(
312 : 206 : QtPassSettings::isShowProcessOutput());
313 : 206 : connect(ui->actionShowProcessOutput, &QAction::toggled, this,
314 : 206 : [this](bool show) {
315 : 2 : m_processOutput->setVisible(show);
316 : 2 : AppSettings s = QtPassSettings::load();
317 [ + - ]: 2 : if (s.showProcessOutput != show) {
318 : 2 : s.showProcessOutput = show;
319 : 2 : QtPassSettings::save(s);
320 : : }
321 : 2 : });
322 : :
323 : 206 : connect(QtPassSettings::getPass(), &Pass::finishedAnyWithPid, this,
324 : 206 : [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.
331 [ + + ]: 17 : if (ProcessOutputPanel::isSensitiveProcess(pid)) {
332 : : return;
333 : : }
334 [ + + ]: 16 : if (!out.isEmpty()) {
335 : 1 : onProcessOutput(out, false, pid);
336 : : }
337 [ + + ]: 16 : if (!err.isEmpty()) {
338 : 4 : onProcessOutput(err, true, pid);
339 : : }
340 : : });
341 : 206 : }
342 : :
343 : 408 : MainWindow::~MainWindow() {
344 : : // Quit from the tray menu or a SIGTERM never delivers closeEvent(); the
345 : : // window still knows its last geometry here.
346 : 206 : saveWindowState();
347 : 206 : delete m_qtPass;
348 : 614 : }
349 : :
350 : : // The signals of one backend that the window answers itself.
351 : 412 : void MainWindow::connectPassSignals(Pass *pass) {
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.
354 : 412 : connect(pass, &Pass::processErrorExit, this, &MainWindow::onOperationError);
355 : 412 : connect(pass, &Pass::critical, this, &MainWindow::critical);
356 : 412 : connect(pass, &Pass::startingExecuteWrapper, this,
357 : 412 : &MainWindow::executeWrapperStarted);
358 : : // The profile box comes back when the queue is done, also after the
359 : : // watchdog released the rest of the interface early.
360 : 412 : connect(pass, &Pass::idle, this, &MainWindow::updateProfileBoxEnabled);
361 : : // The button names what it stops, also once the queue moved on.
362 : 412 : connect(pass, &Pass::startingExecuteWrapper, this, [this, pass]() {
363 [ + - + + ]: 76 : if (m_stopButton != nullptr && !m_stopButton->isHidden()) {
364 : 4 : m_stopButton->setToolTip(tr("Stop %1, which is still running")
365 [ + - + + ]: 6 : .arg(runLabel(pass->runningProcess())));
366 : : }
367 : 76 : });
368 : : // Nothing left to stop.
369 : 412 : connect(pass, &Pass::idle, this, [this]() {
370 [ + - ]: 50 : if (m_stopButton != nullptr) {
371 : 50 : m_stopButton->hide();
372 : : }
373 : 50 : });
374 : 412 : connect(pass, &Pass::statusMsg, this, &MainWindow::showStatusMessage);
375 : 412 : 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.
378 : 412 : connect(pass, &Pass::finishedShow, this, &MainWindow::otpFromFileToClipboard);
379 : 412 : connect(pass, &Pass::finishedShow, this,
380 : 412 : &MainWindow::passwordFromFileToClipboard);
381 : 412 : 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 : 412 : connect(pass, &Pass::finishedGitPush, this, [this, pass]() {
389 [ + + + + : 31 : if (m_refreshAfterPush.isEmpty() || m_refreshAfterPushOwner != pass ||
+ + ]
390 : 9 : pass->isPushing()) {
391 : 5 : return;
392 : : }
393 : 7 : const QString file = std::exchange(m_refreshAfterPush, QString());
394 : 7 : m_refreshAfterPushOwner = nullptr;
395 [ + + + - ]: 7 : if (file == m_shownFile && pass->isIdle()) {
396 : 4 : ui->passwordName->setText(Util::shownName(file));
397 : 8 : pass->Show(file);
398 : : }
399 : : });
400 : 412 : }
401 : :
402 : : // Idempotent; called from closeEvent() and the destructor.
403 : 210 : void MainWindow::saveWindowState() {
404 : 210 : QtPassSettings::setGeometry(saveGeometry());
405 : 210 : QtPassSettings::setSavestate(saveState());
406 : 210 : }
407 : :
408 : 82 : void MainWindow::focusInput() {
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 [ + - ]: 82 : if (!isVisible()) {
414 : : return;
415 : : }
416 : 82 : auto *lineEdit = findChild<QLineEdit *>(QStringLiteral("lineEdit"));
417 [ + - + - ]: 82 : if (lineEdit == nullptr || !lineEdit->isVisible()) {
418 : : return;
419 : : }
420 : 82 : lineEdit->selectAll();
421 : 82 : lineEdit->setFocus();
422 : : // Only once focus has landed: set in showEvent(), an early return above
423 : : // would consume the one-shot and never retry.
424 : 82 : m_firstShowCompleted = true;
425 : : }
426 : :
427 : 9581 : auto MainWindow::event(QEvent *event) -> bool {
428 [ + + ]: 9581 : if (event->type() == QEvent::ApplicationPaletteChange) {
429 : 11 : 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 : 11 : QTimer::singleShot(0, this, &MainWindow::dropStaleToolsAreaPalettes);
433 : : }
434 : 9581 : return QMainWindow::event(event);
435 : : }
436 : :
437 : 276 : void MainWindow::changeEvent(QEvent *event) {
438 : 276 : QWidget::changeEvent(event);
439 [ + + + - ]: 276 : 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.
443 : 10 : m_displayPanel->refreshPalette();
444 : : }
445 [ + + + + : 276 : 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 : 47 : QMetaObject::invokeMethod(this, &MainWindow::focusInput,
450 : : Qt::QueuedConnection);
451 : : }
452 : 276 : }
453 : :
454 : 49 : void MainWindow::showEvent(QShowEvent *event) {
455 : 49 : QMainWindow::showEvent(event);
456 [ + + ]: 49 : if (m_firstShowCompleted) {
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 : 47 : QMetaObject::invokeMethod(this, &MainWindow::focusInput,
463 : : Qt::QueuedConnection);
464 : : }
465 : :
466 : 206 : void MainWindow::initToolBarButtons() {
467 : 206 : connect(ui->actionAddPassword, &QAction::triggered, this,
468 : 206 : &MainWindow::addPassword);
469 : 206 : connect(ui->actionAddFolder, &QAction::triggered, this,
470 : 206 : &MainWindow::addFolder);
471 : 206 : connect(ui->actionEdit, &QAction::triggered, this, &MainWindow::onEdit);
472 : 206 : connect(ui->actionDelete, &QAction::triggered, this, &MainWindow::onDelete);
473 : 206 : connect(ui->actionPush, &QAction::triggered, this, &MainWindow::onPush);
474 : 206 : connect(ui->actionUpdate, &QAction::triggered, this, &MainWindow::onUpdate);
475 : 206 : connect(ui->actionUsers, &QAction::triggered, this, &MainWindow::onUsers);
476 : 206 : connect(ui->actionConfig, &QAction::triggered, this, &MainWindow::onConfig);
477 : 206 : 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 : 206 : connect(ui->actionQuit, &QAction::triggered, qApp, &QApplication::quit);
483 : 206 : 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 : 206 : addAction(ui->actionShowMenuBar);
491 : 206 : ui->actionShowMenuBar->setChecked(QtPassSettings::load().showMenuBar);
492 : 206 : menuBar()->setVisible(ui->actionShowMenuBar->isChecked());
493 : 206 : connect(ui->actionShowMenuBar, &QAction::toggled, this, [this](bool show) {
494 : 5 : menuBar()->setVisible(show);
495 : 5 : AppSettings s = QtPassSettings::load();
496 : 5 : s.showMenuBar = show;
497 : 5 : QtPassSettings::save(s);
498 : 5 : });
499 : 206 : new MenuBarPeek(this, ui->actionShowMenuBar);
500 : : #endif
501 : 207 : connect(ui->actionFaq, &QAction::triggered, this, [] {
502 [ + + ]: 2 : QDesktopServices::openUrl(QUrl(QStringLiteral("https://qtpass.org/faq")));
503 : 1 : });
504 : 206 : connect(ui->actionAbout, &QAction::triggered, this, &MainWindow::showAbout);
505 : 206 : connect(ui->actionAboutQt, &QAction::triggered, qApp, &QApplication::aboutQt);
506 : :
507 : 206 : ui->actionAddPassword->setIcon(
508 [ + + + ]: 824 : QIcon::fromTheme("document-new", QIcon(":/icons/document-new.svg")));
509 : 206 : ui->actionAddFolder->setIcon(
510 [ + + + ]: 824 : QIcon::fromTheme("folder-new", QIcon(":/icons/folder-new.svg")));
511 : 206 : ui->actionEdit->setIcon(QIcon::fromTheme(
512 [ + + ]: 618 : "document-properties", QIcon(":/icons/document-properties.svg")));
513 : 206 : ui->actionDelete->setIcon(
514 [ + + + ]: 824 : QIcon::fromTheme("edit-delete", QIcon(":/icons/edit-delete.svg")));
515 : 206 : ui->actionPush->setIcon(
516 [ + + + ]: 824 : QIcon::fromTheme("go-up", QIcon(":/icons/go-top.svg")));
517 : 206 : ui->actionUpdate->setIcon(
518 [ + + + ]: 824 : QIcon::fromTheme("go-down", QIcon(":/icons/go-bottom.svg")));
519 : 206 : ui->actionUsers->setIcon(QIcon::fromTheme(
520 [ + + ]: 618 : "x-office-address-book", QIcon(":/icons/x-office-address-book.svg")));
521 : 206 : ui->actionConfig->setIcon(QIcon::fromTheme(
522 [ + + ]: 412 : "applications-system", QIcon(":/icons/applications-system.svg")));
523 : 206 : }
524 : :
525 : 206 : void MainWindow::initStatusBar() {
526 : 412 : ui->statusBar->showMessage(tr("Welcome to QtPass %1").arg(VERSION), 2000);
527 : :
528 : 412 : QPixmap logo = QPixmap::fromImage(QImage(":/artwork/icon.svg"))
529 : 206 : .scaledToHeight(statusBar()->height());
530 : 206 : auto *logoApp = new QLabel(statusBar());
531 : 206 : logoApp->setPixmap(logo);
532 : 412 : m_stopButton = new QPushButton(tr("Stop"), statusBar());
533 : 412 : m_stopButton->setObjectName(QStringLiteral("stopButton"));
534 : 206 : m_stopButton->setToolTip(
535 : 206 : tr("Stop the gpg, git or pass run that is still going"));
536 : 206 : m_stopButton->hide();
537 : 206 : connect(m_stopButton, &QPushButton::clicked, this, [this]() {
538 : 6 : Pass *pass = QtPassSettings::getPass();
539 [ + - ]: 6 : if (pass == nullptr || pass->isIdle()) {
540 : 0 : m_stopButton->hide();
541 : 2 : return;
542 : : }
543 : : const Enums::PROCESS pid = pass->runningProcess();
544 : : const quint64 run = pass->runningSerial();
545 : 6 : 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 : 6 : const bool writes = pid != Enums::PASS_SHOW && pid != Enums::PASS_GREP;
550 [ + + ]: 6 : if (writes) {
551 : 8 : const auto answer = QMessageBox::question(
552 : 8 : this, tr("Stop %1?").arg(label),
553 : 4 : 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 : 8 : .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 [ + + + + ]: 7 : if (answer != QMessageBox::Yes || pass->runningSerial() != run) {
562 : : return;
563 : : }
564 : : }
565 : 4 : m_stopButton->hide();
566 [ + - ]: 4 : if (pass->stopRunning()) {
567 : 4 : showStatusMessage(
568 [ + + + + ]: 12 : writes ? tr("Stopped %1 before it finished; the store may be "
569 : : "partly changed.")
570 : : .arg(label)
571 [ + + + + : 6 : : tr("Stopped %1.").arg(label));
- - - - ]
572 : : }
573 : : });
574 : 206 : statusBar()->addPermanentWidget(m_stopButton);
575 : 206 : statusBar()->addPermanentWidget(logoApp);
576 : 206 : }
577 : :
578 : 11 : auto MainWindow::getCurrentTreeViewIndex() -> QModelIndex {
579 : 11 : return ui->treeView->currentIndex();
580 : : }
581 : :
582 : 302 : void 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 : 302 : QTextCursor cursor = ui->textBrowser->textCursor();
589 : 302 : cursor.clearSelection();
590 : 302 : ui->textBrowser->setTextCursor(cursor);
591 : 302 : QTextCharFormat format;
592 [ + + ]: 302 : if (isError) {
593 : 11 : format.setForeground(QColor(Qt::red));
594 : : }
595 : 302 : 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 : 302 : ui->textBrowser->setWordWrapMode(QTextOption::WrapAnywhere);
602 [ + + ]: 302 : 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 : 283 : int older = 0;
608 [ + + + ]: 566 : if (!ui->textBrowser->toPlainText().isEmpty()) {
609 : 223 : older = ui->textBrowser->document()->characterCount() - 1;
610 : 446 : _text = ui->textBrowser->toHtml() + _text;
611 : : }
612 : 283 : 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 : 283 : QTextDocument *doc = ui->textBrowser->document();
618 : 283 : int cut = qMin(doc->characterCount() - kMaxFlashCharacters, older);
619 [ + + ]: 283 : if (cut > 0) {
620 : 140 : const QTextBlock block = doc->findBlock(cut);
621 [ + + - + : 140 : if (block.isValid() && cut > block.position() && block.next().isValid() &&
+ - + + +
- ]
622 [ + + + - ]: 140 : block.next().position() <= older + 1) {
623 : 140 : cut = block.next().position();
624 : : }
625 : 140 : QTextCursor trim(doc);
626 : 140 : trim.setPosition(cut, QTextCursor::KeepAnchor);
627 : 140 : trim.removeSelectedText();
628 : 140 : }
629 : : } else {
630 : 19 : ui->textBrowser->setText(text);
631 : : }
632 : : // The raw text: toPlainText() turns a no-break space into a plain one.
633 [ + + + + : 604 : if (!Util::hasLongUnbrokenRun(ui->textBrowser->document()->toRawText())) {
+ ]
634 : 296 : ui->textBrowser->setWordWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
635 : : }
636 : 302 : }
637 : :
638 : 5 : void MainWindow::applyTextBrowserSettings() {
639 : 5 : const AppSettings s = QtPassSettings::load();
640 [ + + ]: 5 : if (s.useMonospace) {
641 : 1 : QFont monospace("Monospace");
642 : 1 : monospace.setStyleHint(QFont::Monospace);
643 : 1 : ui->textBrowser->setFont(monospace);
644 : 1 : } else {
645 : 4 : ui->textBrowser->setFont(QFont());
646 : : }
647 : :
648 [ + + ]: 5 : if (s.noLineWrapping) {
649 : 1 : ui->textBrowser->setLineWrapMode(QTextBrowser::NoWrap);
650 : : } else {
651 : 4 : ui->textBrowser->setLineWrapMode(QTextBrowser::WidgetWidth);
652 : : }
653 : 5 : }
654 : :
655 : 222 : void MainWindow::applyWindowFlagsSettings() {
656 : 222 : const bool wantOnTop = QtPassSettings::isAlwaysOnTop();
657 : : const Qt::WindowFlags flags = windowFlags();
658 [ + + ]: 222 : 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 [ + + ]: 4 : 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 [ + - ]: 2 : if (wasVisible) {
670 : 2 : show();
671 : : }
672 : : }
673 : :
674 : 8 : auto MainWindow::config() -> bool {
675 [ + + ]: 8 : 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 : 2 : FirstRunWizard wizard(this);
679 [ + + + ]: 2 : if (wizard.exec() != QDialog::Accepted) {
680 : : return false;
681 : : }
682 : 2 : } else {
683 : 6 : ConfigDialog d(this);
684 : 6 : d.setModal(true);
685 [ + + + ]: 6 : if (d.exec() != QDialog::Accepted) {
686 : : return false;
687 : : }
688 : 6 : }
689 : :
690 : 5 : applyTextBrowserSettings();
691 : 5 : applyWindowFlagsSettings();
692 : :
693 : 5 : updateProfileBox();
694 : 5 : const AppSettings s = QtPassSettings::load();
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 : 5 : 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()).
702 : 5 : cancelContentSearch();
703 : : if (m_grep.cancelSearch()) {
704 : 1 : QApplication::restoreOverrideCursor();
705 : : }
706 : 5 : clearPanel(false);
707 : 5 : m_tree->setStore(s.passStore);
708 : 5 : deselect();
709 : 5 : ui->treeView->setCurrentIndex(QModelIndex());
710 : :
711 : 5 : Pass *activePass = QtPassSettings::getPass();
712 : 5 : activePass->updateEnv();
713 : 5 : m_tree->setPass(activePass);
714 : 5 : clearPanelTimer.setInterval(MS_PER_SECOND * s.autoclearPanelSeconds);
715 : 5 : clearResultsTimer.setInterval(clearPanelTimer.interval());
716 : 5 : m_qtPass->clipboard().setAutoclearTimer();
717 : :
718 : 5 : updateGitButtonVisibility();
719 : 5 : updateOtpButtonVisibility();
720 : 5 : updateGrepButtonVisibility();
721 : 5 : updateProcessOutputVisibility();
722 : : #ifndef Q_OS_MACOS
723 : : // The action's toggled handler shows or hides the bar (and saves again).
724 : 5 : ui->actionShowMenuBar->setChecked(s.showMenuBar);
725 : : #endif
726 [ + + + - ]: 5 : if (s.useTrayIcon && m_tray == nullptr) {
727 : 1 : initTrayIcon();
728 [ + - - + ]: 4 : } else if (!s.useTrayIcon && m_tray != nullptr) {
729 : 0 : destroyTrayIcon();
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 [ + + - ]: 5 : if (Util::configIsValid(s)) {
736 : 5 : m_freshStart = false;
737 : : }
738 : : return true;
739 : 5 : }
740 : :
741 : 2 : void MainWindow::onUpdate(bool block) {
742 : 2 : ui->statusBar->showMessage(tr("Updating password-store"), 2000);
743 [ + + ]: 2 : if (block) {
744 : 1 : QtPassSettings::getPass()->GitPull_b(Pass::kBlockingPullMs);
745 : : } else {
746 : 1 : QtPassSettings::getPass()->GitPull();
747 : : }
748 : 2 : }
749 : :
750 : 1 : void MainWindow::onPush() {
751 [ + + + - ]: 1 : if (QtPassSettings::isUseGit()) {
752 : 1 : ui->statusBar->showMessage(tr("Updating password-store"), 2000);
753 : 1 : QtPassSettings::getPass()->GitPush();
754 : : }
755 : 1 : }
756 : :
757 : 8 : void MainWindow::onAutoPush() {
758 [ + + + - ]: 8 : if (QtPassSettings::isUseGit()) {
759 : 8 : ui->statusBar->showMessage(tr("Updating password-store"), 2000);
760 : 8 : QtPassSettings::getPass()->GitPushAutomatic();
761 : : }
762 : 8 : }
763 : :
764 : 68 : auto MainWindow::getFile(const QModelIndex &index, bool forPass) -> QString {
765 : 68 : return m_tree->fileFor(index, forPass);
766 : : }
767 : :
768 : 27 : void MainWindow::on_treeView_clicked(const QModelIndex &index) {
769 : 27 : bool cleared = ui->treeView->currentIndex().flags() == Qt::NoItemFlags;
770 : 27 : QString file = getFile(index, true);
771 : 54 : ui->passwordName->setText(Util::shownName(file));
772 [ + + + - ]: 27 : 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 : 26 : m_shownFile = file;
776 : 52 : QtPassSettings::getPass()->Show(std::move(file));
777 : : } else {
778 : 1 : m_shownFile.clear();
779 : 1 : clearPanel(false);
780 : 1 : ui->actionEdit->setEnabled(false);
781 : 1 : ui->actionDelete->setEnabled(true);
782 : : }
783 : 27 : }
784 : :
785 : 4 : void MainWindow::on_treeView_doubleClicked(const QModelIndex &index) {
786 : 4 : QFileInfo fileOrFolder = m_tree->fileInfo(ui->treeView->currentIndex());
787 : :
788 [ + + + ]: 4 : if (fileOrFolder.isFile()) {
789 : 6 : editPassword(getFile(index, true));
790 : : }
791 : 4 : }
792 : :
793 : 21 : void MainWindow::deselect() {
794 : 21 : m_shownFile.clear();
795 : 21 : cancelOtpRequest();
796 : 21 : m_qtPass->clipboard().clear();
797 : 21 : 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 : 21 : ui->treeView->setCurrentIndex(QModelIndex());
802 : 21 : ui->actionEdit->setEnabled(false);
803 : 21 : ui->actionDelete->setEnabled(false);
804 : 21 : ui->passwordName->setText("");
805 : 21 : clearPanel(false);
806 : 21 : }
807 : :
808 : 78 : void MainWindow::executeWrapperStarted() {
809 : 78 : m_displayPanel->clear();
810 : 78 : m_panelEntry.clear();
811 : 78 : ui->textBrowser->clear();
812 : 78 : setUiElementsEnabled(false);
813 : 78 : clearPanelTimer.stop();
814 [ + + ]: 78 : if (QtPassSettings::isShowProcessOutput()) {
815 : 73 : m_processOutput->setVisible(true);
816 : : }
817 : 78 : }
818 : :
819 : 43 : void 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 [ + + + + ]: 43 : 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 [ + + ]: 11 : if (m_shownFile.isEmpty()) {
829 : 8 : setUiElementsEnabled(true);
830 : : }
831 : 11 : return;
832 : : }
833 : 32 : const AppSettings s = QtPassSettings::load();
834 : 32 : refreshMarkedSecrets(s);
835 : : QStringList templ =
836 [ + + + ]: 32 : s.useTemplate ? TemplateIO::fieldsIn(s.passTemplate) : QStringList();
837 [ + + ]: 32 : 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 : 32 : p_output, templ, allFields, [this, &s](const QString &name) {
842 : 19 : return m_displayPanel->isSecret(name, s);
843 : 32 : });
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 : 32 : 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 [ + + - + ]: 32 : if (m_otpRequestFile.isEmpty() || m_otpRequestFile != file) {
852 : 30 : m_qtPass->clipboard().copyIfAlways(password, p_output);
853 : : }
854 : :
855 : 32 : m_displayPanel->clear();
856 : 32 : m_panelEntry.clear();
857 : :
858 [ + + ]: 32 : if (s.hideContent) {
859 : 4 : output = "***" + tr("Content hidden") + "***";
860 [ + + ]: 30 : } else if (s.displayAsIs) {
861 : : // As it is, but not a block per line of millions.
862 : 4 : output = FileContent::boundedForDisplay(p_output);
863 : : } else {
864 : 28 : m_panelEntry = file;
865 [ + + ]: 56 : m_displayPanel->displayFields(password, fileContent.getNamedValues(), s,
866 [ + + + ]: 28 : s.useOtp ? fileContent.getOtpUri()
867 : : : QString());
868 : 56 : output = fileContent.getRemainingDataForDisplay();
869 : : }
870 : :
871 [ + + ]: 32 : if (s.useAutoclearPanel) {
872 : 3 : 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 [ + + ]: 64 : flashText(QtPass::formatOutput(std::move(output), QString(), QString(),
878 [ + + ]: 32 : !s.displayAsIs || s.hideContent),
879 : : false, true);
880 : 32 : setUiElementsEnabled(true);
881 : 64 : }
882 : :
883 : 32 : void 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 [ + + + + ]: 32 : if (m_otpRequestFile.isEmpty() || file != m_otpRequestFile) {
888 : 28 : return;
889 : : }
890 : 6 : m_otpRequestFile.clear();
891 : :
892 [ + + ]: 6 : if (p_output.isEmpty()) {
893 : : // Distinguish "could not read the entry" from "entry has no OTP".
894 : 1 : flashText(tr("Could not decrypt this password entry"), true);
895 : 1 : setUiElementsEnabled(true);
896 : 1 : 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 : 5 : const QString shown = m_displayPanel->currentOtpCode();
903 [ + + ]: 5 : if (!shown.isEmpty()) {
904 : 1 : m_qtPass->clipboard().copyText(shown);
905 : 1 : showStatusMessage(tr("OTP code copied to clipboard"));
906 : 1 : setUiElementsEnabled(true);
907 : : return;
908 : : }
909 : :
910 : 4 : const AppSettings s = QtPassSettings::load();
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 [ - + - ]: 4 : s.useTemplate ? TemplateIO::fieldsIn(s.passTemplate) : QStringList();
915 [ - + ]: 4 : const bool allFields = s.useTemplate && s.templateAllFields;
916 : : const FileContent fileContent =
917 : 4 : FileContent::parse(p_output, templ, allFields);
918 : :
919 : 4 : Totp::Refusal why = Totp::Refusal::None;
920 : : const std::optional<Totp::Settings> settings =
921 : 8 : Totp::parse(fileContent.getOtpUri(), &why);
922 [ + + ]: 4 : if (settings.has_value()) {
923 : 4 : m_qtPass->clipboard().copyText(Totp::generateNow(*settings));
924 : 4 : showStatusMessage(tr("OTP code copied to clipboard"));
925 : : } else {
926 : : // Why, when there is a configuration that gives no code.
927 : 2 : const QString reason = Totp::describe(why);
928 [ + + + ]: 6 : flashText(reason.isEmpty() ? tr("No OTP code found in this password entry")
929 : : : reason,
930 : : true);
931 : : }
932 : 4 : setUiElementsEnabled(true);
933 : 8 : }
934 : :
935 : 67 : void MainWindow::clearPanel(bool notify) {
936 : 67 : clearShownEntry(notify);
937 : 67 : clearContentResults();
938 : 67 : }
939 : :
940 : 69 : void MainWindow::clearShownEntry(bool notify) {
941 : 69 : m_displayPanel->clear();
942 : 69 : 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.
945 : 69 : m_qtPass->closeQRCode();
946 [ + + ]: 69 : if (notify) {
947 : 4 : QString output = "***" + tr("Password and content hidden") + "***";
948 : 2 : ui->textBrowser->setHtml(output);
949 : : } else {
950 : 134 : ui->textBrowser->setHtml("");
951 : : }
952 : 69 : }
953 : :
954 : 70 : void MainWindow::clearContentResults() {
955 : 70 : clearResultsTimer.stop();
956 : 70 : const bool grepWasVisible = ui->grepResultsList->isVisible();
957 : 70 : ui->grepResultsList->clear();
958 [ + + ]: 70 : if (grepWasVisible) {
959 : 7 : showContentResults(false);
960 [ + - ]: 7 : 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.
963 : 7 : cancelContentSearch();
964 : : if (m_grep.leaveGrepMode()) {
965 : 2 : QApplication::restoreOverrideCursor();
966 : : }
967 : 7 : ui->grepButton->blockSignals(true);
968 : 7 : ui->grepButton->setChecked(false);
969 : 7 : ui->grepButton->blockSignals(false);
970 : 7 : ui->lineEdit->blockSignals(true);
971 : 7 : ui->lineEdit->clear();
972 : 7 : ui->lineEdit->blockSignals(false);
973 : 14 : ui->lineEdit->setPlaceholderText(tr("Search password"));
974 : : }
975 : : }
976 : 70 : }
977 : :
978 : 476 : void MainWindow::setUiElementsEnabled(bool state) {
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 [ + + + + ]: 476 : if (state && m_reencryptRunning) {
983 : 1 : m_uiWatchdog.stop();
984 : 1 : return;
985 : : }
986 : : // Arm the watchdog while the UI is disabled; disarm once re-enabled.
987 : : if (state) {
988 : 373 : m_uiWatchdog.stop();
989 : : } else {
990 : 102 : m_uiWatchdog.start();
991 : : }
992 : 475 : ui->treeView->setEnabled(state);
993 : 475 : ui->lineEdit->setEnabled(state);
994 : 475 : ui->actionAddPassword->setEnabled(state);
995 : 475 : ui->actionAddFolder->setEnabled(state);
996 : 475 : ui->actionUsers->setEnabled(state);
997 : 475 : ui->actionConfig->setEnabled(state);
998 : 475 : m_uiEnabled = state;
999 : 475 : updateProfileBoxEnabled();
1000 : : const bool uiEnabled = state;
1001 : : // is a file selected, and in sight (content search results hide the tree)?
1002 [ + + ]: 953 : state &= ui->treeView->currentIndex().isValid() && !ui->treeView->isHidden();
1003 : 475 : ui->actionDelete->setEnabled(state);
1004 : 475 : ui->actionEdit->setEnabled(state);
1005 : 475 : updateGitButtonVisibility(uiEnabled);
1006 : : // `state` is now "UI enabled AND a file is selected", which is exactly when
1007 : : // generating an OTP makes sense.
1008 : 475 : updateOtpButtonVisibility(state);
1009 : : }
1010 : :
1011 : 217 : void MainWindow::restoreWindow() {
1012 : : // saveGeometry() covers position, size, maximized state and screen;
1013 : : // anything applied on top discards it. Centre only when nothing was saved.
1014 : 434 : const QByteArray geometry = QtPassSettings::getGeometry();
1015 [ + + + - : 217 : if (geometry.isEmpty() || !restoreGeometry(geometry)) {
+ ]
1016 : 4 : WindowStateStore::centreOnCursorScreen(*this);
1017 : : }
1018 : 217 : restoreState(QtPassSettings::getSavestate(saveState()));
1019 : 217 : const AppSettings s = QtPassSettings::load();
1020 : :
1021 : 217 : applyWindowFlagsSettings();
1022 : :
1023 [ + + + - ]: 217 : if (s.useTrayIcon && m_tray == nullptr) {
1024 : 2 : 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 [ + + - + ]: 2 : if (s.startMinimized && m_tray != nullptr) {
1028 : : // since we are still in constructor, can't directly hide
1029 : 0 : QTimer::singleShot(10, this, &MainWindow::hide);
1030 : : }
1031 [ + - - + ]: 215 : } else if (!s.useTrayIcon && m_tray != nullptr) {
1032 : 0 : destroyTrayIcon();
1033 : : }
1034 : 434 : }
1035 : :
1036 : 3 : void MainWindow::onConfig() {
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.
1043 [ + + ]: 3 : if (!QtPassSettings::backendsIdle()) {
1044 : 2 : critical(tr("Settings not opened"),
1045 : 1 : 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 : 1 : return;
1053 : : }
1054 : 2 : config();
1055 : : }
1056 : :
1057 : 1 : void MainWindow::showAbout() {
1058 : 1 : QMessageBox::about(
1059 : 1 : this, tr("About QtPass"),
1060 : 1 : tr("<h3>QtPass %1</h3>"
1061 : : "<p>A multi-platform GUI for <a "
1062 : : "href=\"https://www.passwordstore.org/\">"
1063 : : "pass</a>, the standard Unix password manager.</p>"
1064 : : "<p><a href=\"https://qtpass.org/\">qtpass.org</a> · "
1065 : : "<a href=\"https://github.com/IJHack/QtPass\">Source and "
1066 : : "issues</a></p>"
1067 : : "<p>Copyright © 2014–%2 IJhack. Licensed under the "
1068 : : "<a href=\"https://www.gnu.org/licenses/gpl-3.0.html\">GNU GPL "
1069 : : "version 3</a> or later.</p>")
1070 : 2 : .arg(QStringLiteral(VERSION),
1071 [ + + + ]: 2 : QString::number(QDate::currentDate().year())));
1072 : 1 : }
1073 : :
1074 : 50 : void MainWindow::on_lineEdit_textChanged(const QString &arg1) {
1075 [ + + ]: 50 : if (m_grep.inGrepMode())
1076 : : return;
1077 : 74 : ui->statusBar->showMessage(tr("Looking for: %1").arg(arg1), 1000);
1078 : 37 : 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 : 37 : m_shownFile.clear();
1083 : 37 : cancelOtpRequest();
1084 : 37 : clearPanel(false);
1085 : 74 : ui->passwordName->setText("");
1086 : 37 : ui->actionEdit->setEnabled(false);
1087 : 37 : ui->actionDelete->setEnabled(false);
1088 : 37 : searchTimer.start();
1089 : : }
1090 : :
1091 : 41 : void MainWindow::onTimeoutSearch() {
1092 : : // The tree matches slash-separated paths: on Windows, team\bank typed is
1093 : : // team/bank, as exactMatchPath() reads it too.
1094 : 82 : QString query = QDir::fromNativeSeparators(ui->lineEdit->text());
1095 : :
1096 [ + + ]: 41 : if (query.isEmpty()) {
1097 : 2 : ui->treeView->collapseAll();
1098 : 2 : deselect();
1099 : : }
1100 : :
1101 : : // The words are matched literally, in order, with anything in between:
1102 : : // "work vpn" finds work/acme/vpn.
1103 : 41 : m_tree->setFilter(StoreModel::wordsFilter(query));
1104 : :
1105 [ + + + + : 41 : if (m_tree->proxy().rowCount() > 0 && !query.isEmpty()) {
+ + ]
1106 : 28 : selectFirstFile();
1107 : : } else {
1108 : 13 : ui->actionEdit->setEnabled(false);
1109 : 13 : ui->actionDelete->setEnabled(false);
1110 : : }
1111 : 41 : }
1112 : :
1113 : 17 : void MainWindow::on_lineEdit_returnPressed() {
1114 : 17 : qCDebug(lcQtPass) << "on_lineEdit_returnPressed"
1115 : 0 : << m_tree->proxy().rowCount();
1116 : :
1117 [ + + ]: 17 : if (m_grep.inGrepMode()) {
1118 : 12 : const QString query = ui->lineEdit->text();
1119 [ + + ]: 12 : if (!query.isEmpty()) {
1120 : 9 : ui->grepResultsList->clear();
1121 : 18 : ui->statusBar->showMessage(tr("Searching…"));
1122 : : if (m_grep.beginSearch()) {
1123 : 9 : QApplication::setOverrideCursor(Qt::WaitCursor);
1124 : : }
1125 : 18 : QtPassSettings::getPass()->Grep(query, ui->grepCaseButton->isChecked());
1126 : : } else {
1127 : 3 : cancelContentSearch();
1128 : : if (m_grep.cancelSearch()) {
1129 : 2 : QApplication::restoreOverrideCursor();
1130 : : }
1131 : 3 : ui->grepResultsList->clear();
1132 : 3 : 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 [ + - ]: 5 : if (searchTimer.isActive()) {
1140 : 5 : searchTimer.stop();
1141 : 5 : onTimeoutSearch();
1142 : : }
1143 [ + - ]: 5 : if (m_tree->proxy().rowCount() > 0) {
1144 : 5 : selectFirstFile();
1145 : 5 : on_treeView_clicked(ui->treeView->currentIndex());
1146 : : }
1147 : : }
1148 : :
1149 : 35 : void MainWindow::on_grepButton_toggled(bool checked) {
1150 : 35 : const AppSettings s = QtPassSettings::load();
1151 [ + + ]: 35 : if (checked) {
1152 : : m_grep.enterGrepMode();
1153 : 44 : ui->lineEdit->setPlaceholderText(tr("Search content (regex)"));
1154 : : // Both backends search through NativeGrep (QRegularExpression), so one
1155 : : // dialect: PCRE.
1156 : 22 : ui->lineEdit->setToolTip(
1157 : 22 : tr("Content search uses Perl-compatible regular expressions (PCRE)."));
1158 : 22 : ui->lineEdit->clear();
1159 : 22 : searchTimer.stop();
1160 : 22 : m_tree->setFilter(QRegularExpression());
1161 : 22 : ui->grepResultsList->setVisible(false);
1162 : : // Keep treeView visible until results arrive
1163 : : } else {
1164 : 13 : cancelContentSearch();
1165 : : if (m_grep.leaveGrepMode()) {
1166 : 2 : QApplication::restoreOverrideCursor();
1167 : : }
1168 : 13 : searchTimer.stop();
1169 : 13 : ui->lineEdit->blockSignals(true);
1170 : 13 : ui->lineEdit->clear();
1171 : 13 : ui->lineEdit->blockSignals(false);
1172 : 26 : ui->lineEdit->setPlaceholderText(tr("Search password"));
1173 : 26 : ui->lineEdit->setToolTip(QString());
1174 : 13 : ui->grepResultsList->clear();
1175 : 13 : showContentResults(false);
1176 : 13 : m_tree->setFilter(QRegularExpression());
1177 : : }
1178 : 35 : }
1179 : :
1180 : 42 : void MainWindow::refreshMarkedSecrets(const AppSettings &s) {
1181 [ + + ]: 42 : if (s.hidePassword) {
1182 : 4 : m_displayPanel->setMarkedSecrets(
1183 : 8 : TemplateIO::secretFieldsIn(s.passTemplate) +
1184 : 12 : TemplateIO::readSecretFields(s.passStore));
1185 : : }
1186 : 42 : }
1187 : :
1188 : 43 : auto MainWindow::grepLineForDisplay(const QString &line,
1189 : : const AppSettings &s) const -> QString {
1190 : : const QString hidden =
1191 : 86 : QStringLiteral("***") + tr("hidden") + QStringLiteral("***");
1192 [ + + ]: 43 : if (NativeGrep::isOtpMarker(line)) {
1193 : 2 : 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 : 52 : return m_displayPanel->hides(QObject::tr("Password"), s)
1199 [ + + - - ]: 52 : ? tr("Password: %1").arg(hidden)
1200 : 26 : : NativeGrep::passwordMatchText(line);
1201 : : }
1202 [ + + ]: 15 : if (const qsizetype colon = line.indexOf(QLatin1Char(':')); colon > 0) {
1203 [ + + + + ]: 39 : if (m_displayPanel->hides(line.left(colon).trimmed(), s)) {
1204 : 4 : return line.left(colon + 1) + QLatin1Char(' ') + hidden;
1205 : : }
1206 : : }
1207 : : return line;
1208 : : }
1209 : :
1210 : 21 : void MainWindow::onGrepFinished(
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 : 21 : if (const QObject *from = sender();
1217 [ + + + + ]: 21 : from != nullptr && from != QtPassSettings::getPass()) {
1218 : 11 : return;
1219 : : }
1220 : : const GrepSearchController::FinishOutcome outcome = m_grep.finishSearch();
1221 [ + + ]: 20 : if (outcome.restoreCursor) {
1222 : 2 : QApplication::restoreOverrideCursor();
1223 : : }
1224 : : // Re-enable the UI before the discard check so a cancelled search can never
1225 : : // leave controls disabled.
1226 : 20 : setUiElementsEnabled(true);
1227 [ + + ]: 20 : if (outcome.discard) {
1228 : : return;
1229 : : }
1230 [ + - ]: 12 : if (!m_grep.inGrepMode())
1231 : : return;
1232 : 12 : ui->grepResultsList->clear();
1233 [ + + ]: 12 : if (results.isEmpty()) {
1234 : 2 : ui->statusBar->showMessage(tr("No matches found."), 3000);
1235 : 2 : showContentResults(false);
1236 : 2 : return;
1237 : : }
1238 : 10 : const AppSettings s = QtPassSettings::load();
1239 : 10 : const bool hideContent = s.hideContent;
1240 : 10 : refreshMarkedSecrets(s);
1241 : : int totalLines = 0;
1242 : : int entries = 0;
1243 : : bool stopped = false;
1244 [ + + ]: 43 : for (const auto &pair : results) {
1245 [ - + ]: 33 : if (NativeGrep::isStoppedMarker(pair)) {
1246 : : stopped = true;
1247 : 0 : continue;
1248 : : }
1249 : 33 : ++entries;
1250 : 33 : auto *entryItem = new QTreeWidgetItem(ui->grepResultsList);
1251 : 33 : entryItem->setText(0, pair.first);
1252 : 33 : entryItem->setData(0, Qt::UserRole, pair.first);
1253 [ + + ]: 76 : for (const QString &line : pair.second) {
1254 : 43 : 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 [ - + ]: 43 : if (NativeGrep::isMoreMarker(line)) {
1258 : 0 : lineItem->setText(0, tr("… more matches in this entry"));
1259 : : } else {
1260 [ - + - - : 86 : lineItem->setText(0, hideContent ? "***" + tr("Content hidden") + "***"
+ + - + -
+ - - -
- ]
1261 : : : grepLineForDisplay(line, s));
1262 : 43 : ++totalLines;
1263 : : }
1264 : 43 : lineItem->setData(0, Qt::UserRole, pair.first);
1265 : : }
1266 : : }
1267 : 10 : ui->grepResultsList->expandAll();
1268 : 10 : showContentResults(true);
1269 [ - + ]: 10 : if (stopped) {
1270 : : // The search stopped there; more entries may match.
1271 : 0 : ui->statusBar->showMessage(
1272 : 0 : tr("Showing the first %n match(es); search for something narrower "
1273 : : "to see the rest.",
1274 : : nullptr, totalLines),
1275 : : 10000);
1276 : : } else {
1277 : 30 : ui->statusBar->showMessage(tr("Found %n match(es)", nullptr, totalLines) +
1278 : 10 : " " +
1279 : 20 : 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 [ + + ]: 10 : if (s.useAutoclearPanel)
1286 : 3 : clearResultsTimer.start();
1287 : 10 : }
1288 : :
1289 : 2 : void MainWindow::on_grepResultsList_itemClicked(QTreeWidgetItem *item,
1290 : : int /*column*/) {
1291 : 2 : const AppSettings s = QtPassSettings::load();
1292 : 2 : const QString entry = item->data(0, Qt::UserRole).toString();
1293 [ + - ]: 2 : if (entry.isEmpty())
1294 : : return;
1295 : : const QString fullPath =
1296 : 2 : 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 : 2 : const QPersistentModelIndex proxyIndex(m_tree->indexFor(fullPath));
1300 [ + + - ]: 2 : if (!proxyIndex.isValid())
1301 : : return;
1302 : 2 : ui->treeView->setCurrentIndex(proxyIndex);
1303 [ + + - ]: 2 : if (!proxyIndex.isValid())
1304 : : return;
1305 : 2 : on_treeView_clicked(proxyIndex);
1306 [ + - + + ]: 2 : if (s.hideContent || s.useAutoclearPanel)
1307 : 1 : ui->grepResultsList->clear();
1308 : 2 : showContentResults(false);
1309 : 2 : ui->treeView->scrollTo(proxyIndex);
1310 : 2 : ui->treeView->setFocus();
1311 : 4 : }
1312 : :
1313 : 37 : void MainWindow::showContentResults(bool shown) {
1314 : 37 : ui->grepResultsList->setVisible(shown);
1315 : 37 : ui->treeView->setVisible(!shown);
1316 [ + + ]: 37 : 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 : 10 : ui->actionDelete->setEnabled(false);
1320 : 10 : ui->actionEdit->setEnabled(false);
1321 : 10 : updateOtpButtonVisibility(false);
1322 [ + + ]: 27 : } 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.
1325 : 8 : setUiElementsEnabled(m_uiEnabled);
1326 : : }
1327 : 37 : }
1328 : :
1329 : 28 : void MainWindow::cancelContentSearch() {
1330 : 28 : QtPassSettings::getRealPass()->CancelGrep();
1331 : 28 : QtPassSettings::getImitatePass()->CancelGrep();
1332 : 28 : }
1333 : :
1334 : 33 : void MainWindow::selectFirstFile() {
1335 : : // The entry named exactly as typed wins: with folders sorted first, the
1336 : : // depth-first walk found team/bank before bank.
1337 : 33 : QModelIndex index = exactMatch();
1338 : : if (!index.isValid()) {
1339 : 16 : index = firstFile(m_tree->rootIndex());
1340 : : }
1341 : 33 : ui->treeView->setCurrentIndex(index);
1342 : 33 : }
1343 : :
1344 : : namespace {
1345 : : /**
1346 : : * @brief @p path with each part below @p store spelled as stored on disk.
1347 : : *
1348 : : * Where the file system ignores case, "Bank.gpg" exists while the file is
1349 : : * bank.gpg, and the tree knows the entry only by that spelling.
1350 : : * @param store The store folder.
1351 : : * @param path An existing file in the store.
1352 : : * @return @p path itself when every part is spelled as stored, otherwise
1353 : : * the path with the stored spelling.
1354 : : */
1355 : 33 : auto spelledAsStored(const QString &store, const QString &path) -> QString {
1356 : 66 : const QStringList parts = QDir(store).relativeFilePath(path).split(
1357 : 33 : QLatin1Char('/'), Qt::SkipEmptyParts);
1358 : 33 : QDir dir(store);
1359 : : bool respelled = false;
1360 [ + - ]: 36 : for (int i = 0; i < parts.size(); ++i) {
1361 : 36 : const bool leaf = i == parts.size() - 1;
1362 : : const QStringList names =
1363 : 36 : dir.entryList((leaf ? QDir::Files : QDir::Dirs) | QDir::Hidden |
1364 [ + + + ]: 39 : QDir::NoDotAndDotDot);
1365 : : QString name = parts.at(i);
1366 [ - + ]: 36 : if (!names.contains(name)) {
1367 [ # # ]: 0 : const auto stored = std::find_if(
1368 : : names.cbegin(), names.cend(), [&name](const QString &candidate) {
1369 : 0 : return candidate.compare(name, Qt::CaseInsensitive) == 0;
1370 : : });
1371 [ # # ]: 0 : if (stored == names.cend()) {
1372 : : return path;
1373 : : }
1374 : 0 : name = *stored;
1375 : : respelled = true;
1376 : : }
1377 [ + + ]: 36 : if (leaf) {
1378 [ - + - - : 66 : return respelled ? QDir::cleanPath(Util::joinPath(dir.path(), name))
- + - - ]
1379 : 0 : : path;
1380 : : }
1381 [ + - + ]: 3 : if (!dir.cd(name)) {
1382 : : return path;
1383 : : }
1384 : : }
1385 : : return path;
1386 : 33 : }
1387 : : } // namespace
1388 : :
1389 : 51 : auto MainWindow::exactMatchPath() -> QString {
1390 : 102 : const QString text = QDir::fromNativeSeparators(ui->lineEdit->text());
1391 : 102 : 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 [ + + - - ]: 191 : for (const QString &typed : {text, text.trimmed()}) {
1395 [ - + ]: 71 : if (typed.isEmpty()) {
1396 : 0 : continue;
1397 : : }
1398 : : const QString path =
1399 : 142 : QDir::cleanPath(Util::joinPath(store, typed + QStringLiteral(".gpg")));
1400 [ + + - + : 71 : if (PathValidator::isPathInStore(store, path) && QFileInfo(path).isFile()) {
+ + + -
- ]
1401 : 33 : return spelledAsStored(store, path);
1402 : : }
1403 : 153 : }
1404 : 18 : return {};
1405 : : }
1406 : :
1407 : 47 : auto MainWindow::exactMatch() -> QModelIndex {
1408 : 47 : const QString path = exactMatchPath();
1409 [ + + ]: 47 : if (path.isEmpty()) {
1410 : 17 : return {};
1411 : : }
1412 : : // indexFor() maps through the filter: a row the filter hides is no match.
1413 : 30 : const QModelIndex index = m_tree->indexFor(path);
1414 [ + + + - : 53 : if (!index.isValid() || !m_tree->fileInfo(index).isFile()) {
+ + ]
1415 : 7 : return {};
1416 : : }
1417 : 23 : return index;
1418 : : }
1419 : :
1420 : 9 : void 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 [ + + ]: 9 : if (ui->grepButton->isChecked()) {
1424 : 1 : ui->grepButton->setChecked(false);
1425 : : }
1426 : 9 : delete m_pendingOpen;
1427 : 9 : 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 : 9 : searchTimer.stop();
1431 : 9 : onTimeoutSearch();
1432 : 9 : if (const QModelIndex exact = exactMatch(); exact.isValid()) {
1433 : 5 : openExactMatch(exact);
1434 : 5 : 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 [ + + ]: 8 : if (exactMatchPath().isEmpty()) {
1442 : : return;
1443 : : }
1444 : 3 : auto *pending = new QObject(this);
1445 : : m_pendingOpen = pending;
1446 : 3 : 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 : 2 : const auto stop = [this, pending] {
1450 : 2 : disconnect(m_tree, nullptr, pending, nullptr);
1451 : 2 : disconnect(ui->lineEdit, nullptr, pending, nullptr);
1452 : 2 : pending->deleteLater();
1453 : 5 : };
1454 : 3 : connect(ui->lineEdit, &QLineEdit::textChanged, pending, stop);
1455 : 3 : connect(m_tree, &StoreTree::directoryLoaded, pending,
1456 : 6 : [this, stop](const QString &) {
1457 : 5 : searchTimer.stop();
1458 : 5 : onTimeoutSearch();
1459 : 5 : if (const QModelIndex exact = exactMatch(); exact.isValid()) {
1460 : 1 : stop();
1461 : 1 : openExactMatch(exact);
1462 : : }
1463 : 5 : });
1464 : : }
1465 : :
1466 : 6 : void 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 : 6 : ui->treeView->setCurrentIndex(index);
1471 : 6 : on_treeView_clicked(index);
1472 : 6 : }
1473 : :
1474 : 23 : auto MainWindow::firstFile(QModelIndex parentIndex) -> QModelIndex {
1475 : 23 : StoreModel &proxy = m_tree->proxy();
1476 : 23 : int numRows = proxy.rowCount(parentIndex);
1477 [ + + ]: 30 : for (int row = 0; row < numRows; ++row) {
1478 : 21 : QModelIndex index = proxy.index(row, 0, parentIndex);
1479 [ + + + ]: 21 : if (m_tree->fileInfo(index).isFile()) {
1480 : 14 : return index;
1481 : : }
1482 [ + + ]: 12 : if (proxy.hasChildren(index)) {
1483 : 7 : QModelIndex childFile = firstFile(index);
1484 : : if (childFile.isValid())
1485 : 5 : return childFile;
1486 : : }
1487 : : }
1488 : 9 : return {};
1489 : : }
1490 : :
1491 : : // Guards the input dialogs (create, move, rename) against names like
1492 : : // "../../etc/passwd" or absolute paths escaping the store root.
1493 : 11 : auto MainWindow::confirmPathInStore(const QString &candidate) -> bool {
1494 [ + + + + : 22 : if (PathValidator::isPathInStore(QtPassSettings::getPassStore(), candidate)) {
+ ]
1495 : : return true;
1496 : : }
1497 : 9 : QMessageBox::warning(this, tr("Invalid name"),
1498 : 3 : tr("That name would resolve outside the password "
1499 : : "store. Please choose a different name."));
1500 : 3 : return false;
1501 : : }
1502 : :
1503 : 8 : void MainWindow::setPassword(const QString &file, bool isNew) {
1504 : 8 : const AppSettings s = QtPassSettings::load();
1505 : 8 : PasswordDialog d(QtPassSettings::getPass(), s, file, isNew, this);
1506 : : // A copy out of the editor is autocleared like one from the display.
1507 : 8 : connect(&d, &PasswordDialog::copied, &m_qtPass->clipboard(),
1508 : 8 : &ClipboardManager::trackCopied);
1509 : :
1510 [ + + ]: 8 : if (isNew) {
1511 : : const QString storePath = s.passStore;
1512 : 2 : QString folder = m_tree->currentDir(false);
1513 [ - + ]: 2 : if (folder.isEmpty()) {
1514 : 0 : 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 [ + + + ]: 2 : 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 : 2 : QStringList folders{QString()};
1527 : 1 : const QStringList found = Util::directoriesUnder(storePath);
1528 [ + + ]: 19 : for (const QString &path : found) {
1529 : 18 : const QString rel = QDir(storePath).relativeFilePath(path);
1530 [ + + - + : 54 : if (!rel.startsWith(u'.') && !rel.contains(QStringLiteral("/."))) {
- + - + -
- - - - ]
1531 : : folders << rel;
1532 : : }
1533 : : }
1534 : 1 : std::sort(folders.begin() + 1, folders.end());
1535 : 1 : d.setNewEntryLocation(storePath, folders,
1536 [ + + ]: 2 : QDir(storePath).relativeFilePath(folder));
1537 : : QHash<QString, QStringList> templates =
1538 : 1 : TemplateIO::readTemplates(storePath);
1539 : : if (!templates.isEmpty()) {
1540 : : QString defaultTemplate =
1541 : 1 : TemplateIO::getFolderTemplate(folder, storePath);
1542 : 1 : d.setAvailableTemplates(templates, defaultTemplate);
1543 : : }
1544 : 1 : }
1545 : :
1546 [ + + + ]: 7 : if (!d.exec()) {
1547 : 6 : ui->treeView->setFocus();
1548 : : }
1549 : 8 : }
1550 : :
1551 : 4 : void MainWindow::addPassword() { setPassword(QString()); }
1552 : :
1553 : 9 : auto MainWindow::confirmDeletion(const QString &file, bool isDir) -> bool {
1554 : 9 : 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 : 9 : Util::displayable(QDir::toNativeSeparators(path), false);
1560 [ + + ]: 9 : if (!isDir) {
1561 : 2 : return PlainMessageBox::askYes(
1562 : 2 : this, tr("Delete password?"),
1563 : 4 : 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 : 0 : tr("Are you sure you want to delete %1 and the whole content?")
1571 : 7 : .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 : 7 : QStringList skipped;
1575 : 7 : QStringList unlisted;
1576 : 7 : const QString root = m_tree->fileSystem().rootPath();
1577 : 21 : const QStringList content = Util::regularFilesUnder(
1578 [ + + + - ]: 21 : root + path, {QStringLiteral("*")}, &skipped, false, &unlisted);
1579 : : const bool unexpected =
1580 [ + - ]: 7 : !skipped.isEmpty() ||
1581 [ + + ]: 7 : std::any_of(content.cbegin(), content.cend(), [](const QString &entry) {
1582 : 10 : return QFileInfo(entry).suffix() != QLatin1String("gpg");
1583 : : });
1584 : : if (unexpected) {
1585 : 1 : question += QStringLiteral("\n\n") +
1586 : 1 : tr("Attention: there are unexpected files in the given "
1587 : 1 : "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 [ + + ]: 7 : if (unlisted.size() == 1) {
1592 : : //: %1 is a folder in the password store, such as /Work/bank.
1593 : : const QString one =
1594 : 1 : tr("%1 could not be read, so what it holds is unknown.")
1595 : 1 : .arg(Util::displayable(
1596 : 1 : QDir::toNativeSeparators(
1597 : 1 : QDir::separator() +
1598 [ + + ]: 2 : QDir(root).relativeFilePath(unlisted.first())),
1599 [ + + ]: 3 : false));
1600 : 2 : question += QStringLiteral("\n\n") + one;
1601 [ + + ]: 6 : } 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 : 1 : nullptr, static_cast<int>(unlisted.size()));
1607 : 2 : question += QStringLiteral("\n\n") + many;
1608 : : }
1609 : 14 : return PlainMessageBox::askYes(this, tr("Delete folder?"), question);
1610 : : }
1611 : :
1612 : 1 : auto MainWindow::confirmLinkRemoval(const QString &file) -> bool {
1613 : : // Only the link goes (ImitatePass::Remove unlinks it); nothing behind it
1614 : : // is looked at or mentioned.
1615 : 1 : return PlainMessageBox::askYes(
1616 : 1 : this, tr("Delete link?"),
1617 : 1 : tr("%1 is a symbolic link or junction. Remove the link? What it "
1618 : : "points to is left alone.")
1619 [ + + + ]: 2 : .arg(Util::displayable(QDir::separator() + file, false)));
1620 : : }
1621 : :
1622 : 14 : void MainWindow::onDelete() {
1623 : 14 : 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 [ + + ]: 12 : if (!currentIndex.isValid() || ui->treeView->isHidden()) {
1627 : : // Otherwise the whole password directory would be deleted (#556).
1628 : 11 : return;
1629 : : }
1630 : :
1631 : 10 : const bool isDir = !m_tree->fileInfo(currentIndex).isFile();
1632 : : const QString file =
1633 [ + + ]: 10 : isDir ? m_tree->currentDir(true) : getFile(currentIndex, true);
1634 : : const QString folder =
1635 : 10 : m_tree->fileSystem().rootPath() + QDir::separator() + file;
1636 [ + + + + : 10 : const bool linkedFolder = isDir && Util::isLinkedFolder(folder);
+ ]
1637 : :
1638 [ + + - ]: 9 : if (!linkedFolder && refuseLinkedFolder(folder)) {
1639 : : // Behind a link: deleting would reach outside the store.
1640 : : return;
1641 : : }
1642 : : const bool confirmed =
1643 [ + + + + ]: 10 : linkedFolder ? confirmLinkRemoval(file) : confirmDeletion(file, isDir);
1644 [ + + ]: 10 : if (!confirmed) {
1645 : : return;
1646 : : }
1647 : 6 : QtPassSettings::getPass()->Remove(file, isDir);
1648 : : }
1649 : :
1650 : 103 : void MainWindow::cancelOtpRequest() {
1651 : 103 : m_otpRequestFile.clear();
1652 : 103 : m_copyRequestFile.clear();
1653 : 103 : }
1654 : :
1655 : 38 : void MainWindow::onOperationError() {
1656 : 38 : cancelOtpRequest();
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 : 38 : 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 : 38 : m_refreshAfterPush.clear();
1664 : : m_refreshAfterPushOwner = nullptr;
1665 : 38 : }
1666 : :
1667 : : // Derives the code in-process from one decrypt, so it works with either
1668 : : // backend on every platform; otpFromFileToClipboard() finishes the job.
1669 : 12 : void MainWindow::onOtp() {
1670 [ + + ]: 12 : if (ui->treeView->isHidden()) {
1671 : 4 : return;
1672 : : }
1673 : 11 : QString file = getFile(ui->treeView->currentIndex(), true);
1674 [ + + ]: 11 : if (file.isEmpty()) {
1675 : 1 : flashText(tr("No password selected for OTP generation"), true);
1676 : 1 : return;
1677 : : }
1678 [ + + + ]: 10 : if (!QtPassSettings::isUseOtp()) {
1679 : : // Normally unreachable (the action is hidden), but never fail silently.
1680 : 1 : flashText(tr("No OTP code found in this password entry"), true);
1681 : 1 : 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 [ + + + ]: 9 : (m_shownFile == file) ? m_displayPanel->currentOtpCode() : QString();
1690 [ + + ]: 9 : if (!shown.isEmpty()) {
1691 : 1 : m_qtPass->clipboard().copyText(shown);
1692 : 2 : 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 : 8 : m_otpRequestFile = file;
1699 : 8 : 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 : 8 : m_shownFile = file;
1703 : 16 : QtPassSettings::getPass()->Show(std::move(file));
1704 : : }
1705 : :
1706 : 1 : void MainWindow::onEdit() {
1707 [ + - ]: 1 : if (ui->treeView->isHidden()) {
1708 : 1 : return;
1709 : : }
1710 : 0 : QString file = getFile(ui->treeView->currentIndex(), true);
1711 : 0 : editPassword(file);
1712 : : }
1713 : :
1714 : 2 : void MainWindow::onUsers() {
1715 : 2 : const QString dir = m_tree->currentDir(false);
1716 [ + + + ]: 2 : if (refuseLinkedFolder(dir)) {
1717 : : return;
1718 : : }
1719 : :
1720 : 1 : UsersDialog d(QtPassSettings::getPass(), QtPassSettings::load(), dir, this);
1721 [ + + - ]: 1 : if (!d.exec()) {
1722 : 1 : ui->treeView->setFocus();
1723 : : }
1724 : 1 : }
1725 : :
1726 : 10 : void MainWindow::messageAvailable(const QString &message) {
1727 : 10 : show();
1728 : 10 : raise();
1729 [ + + ]: 10 : if (message.isEmpty()) {
1730 : 1 : focusInput();
1731 : : } else {
1732 : 9 : ui->treeView->expandAll();
1733 : 9 : applySearchText(message);
1734 : : }
1735 : 10 : }
1736 : :
1737 : 215 : void MainWindow::updateProfileBox() {
1738 : 215 : const Profiles profiles = QtPassSettings::getProfiles();
1739 : : bool activeGone = false;
1740 : :
1741 [ - + ]: 8 : if (profiles.isEmpty()) {
1742 : 207 : ui->profileWidget->hide();
1743 : : } else {
1744 : 8 : 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 : 8 : const QSignalBlocker quiet(ui->profileBox);
1748 : 8 : ui->profileBox->clear();
1749 [ + + ]: 22 : for (auto i = profiles.cbegin(); i != profiles.cend(); ++i) {
1750 [ + - ]: 14 : if (!i.key().isEmpty()) {
1751 : 14 : ui->profileBox->addItem(i.key());
1752 : : }
1753 : : }
1754 : 8 : ui->profileBox->model()->sort(0);
1755 : 16 : int index = ui->profileBox->findText(QtPassSettings::getProfile());
1756 [ + + ]: 8 : if (index != -1) { // -1 for not found
1757 : 7 : ui->profileBox->setCurrentIndex(index);
1758 [ + - + ]: 1 : } 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 : 1 : ui->profileBox->setCurrentIndex(0);
1763 : : activeGone = true;
1764 : : }
1765 : 8 : }
1766 [ + + ]: 8 : if (activeGone) {
1767 : 2 : on_profileBox_currentTextChanged(ui->profileBox->currentText());
1768 : : }
1769 : 215 : updateProfileBoxEnabled();
1770 : 215 : }
1771 : :
1772 : 740 : void MainWindow::updateProfileBoxEnabled() {
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 [ + + + + : 1482 : ui->profileBox->setEnabled(m_uiEnabled && ui->profileBox->count() > 1 &&
+ + ]
1781 : 16 : QtPassSettings::backendsIdle());
1782 : 740 : }
1783 : :
1784 : 8 : void MainWindow::on_profileBox_currentTextChanged(const QString &name) {
1785 [ + - + + : 24 : if (m_freshStart || name == QtPassSettings::getProfile()) {
+ - + - +
+ - - ]
1786 : 1 : 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.
1790 [ + - + - ]: 7 : if (!m_uiEnabled || !QtPassSettings::backendsIdle()) {
1791 : 0 : const QSignalBlocker quiet(ui->profileBox);
1792 : 0 : ui->profileBox->setCurrentText(QtPassSettings::getProfile());
1793 : : return;
1794 : 0 : }
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 [ + + ]: 7 : if (m_grep.inGrepMode()) {
1798 : 1 : ui->grepButton->setChecked(false);
1799 : : }
1800 : :
1801 : 7 : ui->lineEdit->clear();
1802 : :
1803 : 14 : const Profile prof = QtPassSettings::getProfiles().value(name);
1804 : 7 : AppSettings s = QtPassSettings::load();
1805 : 7 : s.activeProfile = name;
1806 : 7 : s.passStore = prof.path;
1807 : 7 : 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.
1811 : 7 : QtPassSettings::save(s);
1812 : 14 : ui->statusBar->showMessage(tr("Profile changed to %1").arg(name), 2000);
1813 : :
1814 : 7 : QtPassSettings::getPass()->updateEnv();
1815 : :
1816 : 14 : m_tree->setStore(QtPassSettings::getPassStore());
1817 : 7 : deselect();
1818 : 7 : ui->treeView->setCurrentIndex(QModelIndex());
1819 : 7 : }
1820 : :
1821 : 3 : void MainWindow::initTrayIcon() {
1822 : 3 : m_tray = new TrayIcon(this);
1823 [ + - ]: 3 : if (!m_tray->getIsAllocated()) {
1824 : 3 : destroyTrayIcon();
1825 : 3 : return;
1826 : : }
1827 : : #ifndef Q_OS_MACOS
1828 : 0 : m_tray->addToggle(ui->actionShowMenuBar);
1829 : : #endif
1830 : : }
1831 : :
1832 : 3 : void MainWindow::destroyTrayIcon() {
1833 : 3 : delete m_tray;
1834 : 3 : m_tray = nullptr;
1835 : 3 : }
1836 : :
1837 : 4 : void 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.
1840 : 4 : saveWindowState();
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 [ + + + - : 8 : if (QtPassSettings::isHideOnClose() && m_tray != nullptr) {
+ - - + ]
1845 : 0 : this->hide();
1846 : : event->ignore();
1847 : : } else {
1848 : 4 : m_qtPass->clipboard().clear();
1849 : : event->accept();
1850 : : // A visible QSystemTrayIcon keeps the application alive, so
1851 : : // quitOnLastWindowClosed never fires; quit explicitly.
1852 : 4 : QApplication::quit();
1853 : : }
1854 : 4 : }
1855 : :
1856 : 8763 : auto MainWindow::eventFilter(QObject *obj, QEvent *event) -> bool {
1857 [ + + + + : 8763 : 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 : 36 : QTimer::singleShot(0, this, &MainWindow::dropStaleToolsAreaPalettes);
1864 : : }
1865 [ + + + + ]: 8763 : if (obj == ui->lineEdit && event->type() == QEvent::KeyPress) {
1866 : 5 : auto *key = dynamic_cast<QKeyEvent *>(event);
1867 [ + - + + ]: 5 : 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 [ + + ]: 2 : if (ui->treeView->isHidden()) {
1871 : 1 : ui->grepResultsList->setFocus();
1872 : : } else {
1873 : 1 : 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 [ + - + + ]: 5 : if (key != nullptr &&
1881 [ - + ]: 2 : (key->key() == Qt::Key_Return || key->key() == Qt::Key_Enter)) {
1882 : 3 : ui->lineEdit->event(event);
1883 : : event->accept();
1884 : 3 : return true;
1885 : : }
1886 : : }
1887 : 8760 : 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.
1893 : 31 : void MainWindow::dropStaleToolsAreaPalettes() {
1894 [ + + ]: 31 : 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 : 54 : const int appLightness = QApplication::palette()
1902 : : .color(QPalette::Active, QPalette::Window)
1903 : 27 : .lightness();
1904 : 108 : for (QWidget *bar : {static_cast<QWidget *>(ui->toolBar),
1905 [ + + ]: 81 : static_cast<QWidget *>(menuBar())}) {
1906 [ + + ]: 54 : if (!bar->testAttribute(Qt::WA_SetPalette)) {
1907 : 48 : continue;
1908 : : }
1909 : : const int barLightness =
1910 : 12 : bar->palette().color(QPalette::Active, QPalette::Window).lightness();
1911 [ + + ]: 6 : if (qAbs(barLightness - appLightness) <= kStaleToolsAreaLightness) {
1912 : 2 : continue;
1913 : : }
1914 : 4 : 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 : 4 : bar->setBackgroundRole(QPalette::Window);
1919 : 4 : bar->setAutoFillBackground(true);
1920 : : }
1921 : : }
1922 : :
1923 : 25 : void MainWindow::keyPressEvent(QKeyEvent *event) {
1924 [ + + + + ]: 25 : switch (event->key()) {
1925 : 2 : case Qt::Key_Delete:
1926 : 2 : onDelete();
1927 : 2 : break;
1928 [ + + ]: 2 : 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 [ + + ]: 2 : if (ui->treeView->isHidden()) {
1933 : 1 : QTreeWidgetItem *result = ui->grepResultsList->currentItem();
1934 [ + - + - ]: 1 : if (result != nullptr && ui->grepResultsList->hasFocus()) {
1935 : 1 : on_grepResultsList_itemClicked(result, 0);
1936 : : }
1937 : : break;
1938 : : }
1939 [ + - ]: 1 : if (m_tree->proxy().rowCount() > 0) {
1940 : 1 : on_treeView_clicked(ui->treeView->currentIndex());
1941 : : }
1942 : : break;
1943 : 3 : case Qt::Key_Escape:
1944 : 3 : ui->lineEdit->clear();
1945 : 3 : break;
1946 : : default:
1947 : : break;
1948 : : }
1949 : 25 : }
1950 : :
1951 : 14 : void MainWindow::addShareMenu(QMenu &contextMenu, const AppSettings &s) {
1952 : 14 : const QString dirPath = QDir::cleanPath(m_tree->currentDir(false));
1953 : 14 : auto *shareMenu = new QMenu(tr("Share"), &contextMenu);
1954 : 14 : contextMenu.addMenu(shareMenu);
1955 : :
1956 : 14 : const QString gpgIdPath = Pass::getGpgIdPath(dirPath, s.passStore);
1957 [ + - + + ]: 14 : const bool gpgIdExists = !gpgIdPath.isEmpty() && QFile(gpgIdPath).exists();
1958 [ - + ]: 14 : const QString exePath = s.usePass ? s.passExecutable : s.gpgExecutable;
1959 : : const bool gpgAvailable =
1960 [ + - + - ]: 28 : !exePath.isEmpty() &&
1961 [ + + + + : 28 : (Executor::parseWslCommand(exePath) || QFile(exePath).exists());
- - - ]
1962 : :
1963 : 14 : QAction *reencrypt = shareMenu->addAction(tr("Re-encrypt all passwords"));
1964 : 14 : reencrypt->setEnabled(gpgIdExists && gpgAvailable);
1965 : 14 : connect(reencrypt, &QAction::triggered, this,
1966 : 46 : [this, dirPath]() { reencryptPath(dirPath); });
1967 : :
1968 : 14 : QAction *exportKey = shareMenu->addAction(tr("Export my public key..."));
1969 : 14 : exportKey->setEnabled(gpgAvailable);
1970 : 14 : connect(exportKey, &QAction::triggered, this, &MainWindow::exportPublicKey);
1971 : :
1972 : 14 : QAction *addRecipientAction = shareMenu->addAction(tr("Add recipient..."));
1973 : 14 : addRecipientAction->setEnabled(gpgIdExists && gpgAvailable);
1974 : 14 : connect(addRecipientAction, &QAction::triggered, this,
1975 : 44 : [this, dirPath]() { addRecipient(dirPath); });
1976 : :
1977 : 14 : QAction *shareHelp = shareMenu->addAction(tr("What is this?"));
1978 : 14 : connect(shareHelp, &QAction::triggered, this, &MainWindow::showShareHelp);
1979 : 14 : }
1980 : :
1981 : 4 : auto MainWindow::backOnMenuEntry(const QString &openedOn) -> bool {
1982 : 4 : const QModelIndex current = ui->treeView->currentIndex();
1983 [ + + ]: 4 : if (openedOn.isEmpty()) {
1984 : : // Opened beside the entries: for the store itself.
1985 : : if (current.isValid()) {
1986 : 0 : ui->treeView->setCurrentIndex(QModelIndex());
1987 : : }
1988 : 1 : 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 : 3 : const QFileInfo entry(openedOn);
1993 [ + + + + : 3 : const bool there = entry.exists() || entry.isSymLink();
- + ]
1994 : 3 : if (there && current.isValid() &&
1995 [ + + + + : 4 : 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 [ + + + ]: 3 : const QModelIndex shown = there ? m_tree->indexFor(openedOn) : QModelIndex();
2001 : : if (!shown.isValid()) {
2002 : 2 : showStatusMessage(
2003 [ + + ]: 4 : tr("%1 is no longer in the list.").arg(Util::shownName(openedOn)));
2004 : 2 : return false;
2005 : : }
2006 : 1 : ui->treeView->setCurrentIndex(shown);
2007 : : return true;
2008 : 3 : }
2009 : :
2010 : 16 : void MainWindow::showContextMenu(const QPoint &pos) {
2011 : 16 : const AppSettings s = QtPassSettings::load();
2012 : 16 : const QModelIndex index = ui->treeView->indexAt(pos);
2013 : : const bool selected = index.isValid();
2014 : : if (!selected) {
2015 : 1 : ui->treeView->clearSelection();
2016 : 1 : ui->actionDelete->setEnabled(false);
2017 : 1 : ui->actionEdit->setEnabled(false);
2018 : : }
2019 : 16 : ui->treeView->setCurrentIndex(index);
2020 : 16 : const QPoint globalPos = ui->treeView->viewport()->mapToGlobal(pos);
2021 : 16 : const QFileInfo fileOrFolder = m_tree->fileInfo(ui->treeView->currentIndex());
2022 : 16 : const bool isDir = fileOrFolder.isDir();
2023 : :
2024 : 16 : 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 [ + + + ]: 16 : selected ? fileOrFolder.absoluteFilePath() : QString();
2033 : 16 : const auto add = [this, &contextMenu, openedOn](const QString &text,
2034 : : void (MainWindow::*slot)()) {
2035 : 91 : connect(contextMenu.addAction(text), &QAction::triggered, this,
2036 : 182 : [this, openedOn, slot]() {
2037 [ + + ]: 4 : if (backOnMenuEntry(openedOn)) {
2038 : 2 : (this->*slot)();
2039 : : }
2040 : 4 : });
2041 : 107 : };
2042 [ + + ]: 16 : if (!selected || isDir) {
2043 : 15 : add(tr("Open folder with file manager"), &MainWindow::openFolder);
2044 : 15 : add(tr("Add folder"), &MainWindow::addFolder);
2045 : 15 : add(tr("Add password"), &MainWindow::addPassword);
2046 : 30 : add(tr("Users"), &MainWindow::onUsers);
2047 [ + + - ]: 1 : } else if (fileOrFolder.isFile()) {
2048 : 2 : add(tr("Edit"), &MainWindow::onEdit);
2049 : : }
2050 [ + + ]: 16 : if (selected) {
2051 : 15 : contextMenu.addSeparator();
2052 [ + + ]: 15 : if (isDir) {
2053 : 28 : add(tr("Rename folder"), &MainWindow::renameFolder);
2054 [ + + - ]: 1 : } else if (fileOrFolder.isFile()) {
2055 : 2 : add(tr("Rename password"), &MainWindow::renamePassword);
2056 : : }
2057 : 15 : add(tr("Delete"), &MainWindow::onDelete);
2058 [ + + ]: 15 : if (isDir) {
2059 : 14 : 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 : 16 : connect(m_tree, &StoreTree::currentEntryLost, &contextMenu, &QMenu::close);
2065 : 16 : contextMenu.exec(globalPos);
2066 : 16 : }
2067 : :
2068 : 3 : auto 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 : 3 : const QScrollBar *across = ui->textBrowser->horizontalScrollBar();
2074 : 3 : const int dx = ui->textBrowser->isRightToLeft()
2075 [ + + ]: 3 : ? across->maximum() - across->value()
2076 : 3 : : across->value();
2077 : : const QPoint documentPos =
2078 : 3 : pos + QPoint(dx, ui->textBrowser->verticalScrollBar()->value());
2079 : 3 : 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 : 3 : contextMenu->setParent(this, contextMenu->windowFlags());
2083 : 3 : if (auto *copyLink =
2084 [ + + - ]: 3 : contextMenu->findChild<QAction *>(QStringLiteral("link-copy"))) {
2085 : 3 : const QString link = ui->textBrowser->anchorAt(pos);
2086 : 3 : disconnect(copyLink, &QAction::triggered, nullptr, nullptr);
2087 [ + + - ]: 10 : connect(copyLink, &QAction::triggered, this, [this, link] {
2088 [ + - ]: 1 : if (!link.isEmpty()) {
2089 : 1 : m_qtPass->clipboard().copyText(link);
2090 : : }
2091 : 1 : });
2092 : : }
2093 : 3 : return contextMenu;
2094 : : }
2095 : :
2096 : 1 : void MainWindow::showBrowserContextMenu(const QPoint &pos) {
2097 : 1 : QMenu *contextMenu = browserContextMenu(pos);
2098 : 1 : contextMenu->exec(ui->textBrowser->viewport()->mapToGlobal(pos));
2099 : 1 : delete contextMenu;
2100 : 1 : }
2101 : :
2102 : 1 : void MainWindow::openFolder() {
2103 : 1 : QString dir = m_tree->currentDir(false);
2104 : :
2105 : 1 : QString path = QDir::toNativeSeparators(dir);
2106 : 1 : QDesktopServices::openUrl(QUrl::fromLocalFile(path));
2107 : 1 : }
2108 : :
2109 : 7 : void MainWindow::addFolder() {
2110 : 7 : const AppSettings s = QtPassSettings::load();
2111 : : bool ok;
2112 : 7 : QString dir = m_tree->currentDir(false);
2113 : : QString newdir = QInputDialog::getText(
2114 : 7 : this, tr("New folder"),
2115 : 7 : tr("New folder: \n(Will be placed in %1 )")
2116 : 14 : .arg(Util::shownName(s.passStore + m_tree->currentDir(true))),
2117 [ + + ]: 14 : QLineEdit::Normal, "", &ok);
2118 [ + + + - ]: 7 : 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 : 6 : newdir = QDir::cleanPath(newdir.prepend(dir));
2125 [ + + + ]: 6 : 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 [ + + + ]: 5 : if (refuseLinkedFolder(newdir)) {
2131 : : return;
2132 : : }
2133 : : // The tree, like `pass ls`, hides names that start with a dot.
2134 : : const QStringList parts =
2135 : 4 : QDir(s.passStore).relativeFilePath(newdir).split(u'/');
2136 [ + + - + ]: 8 : if (std::any_of(parts.cbegin(), parts.cend(), [](const QString &part) {
2137 [ + + ]: 4 : return part != u'.' && part.startsWith(u'.');
2138 : : })) {
2139 : 2 : PlainMessageBox::warning(this, tr("Hidden folder"),
2140 : 1 : tr("A folder that starts with a dot would be "
2141 : : "hidden from the list: %1")
2142 : 2 : .arg(newdir));
2143 : 1 : return;
2144 : : }
2145 : : // Exists already: an error, as QDir::mkdir() made it before.
2146 [ + + + + : 3 : if (QFileInfo::exists(newdir) || !Util::mkpathForStore(newdir)) {
+ - ]
2147 : 2 : PlainMessageBox::warning(this, tr("Error"),
2148 : 2 : tr("Failed to create folder: %1").arg(newdir));
2149 : 1 : 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 : 7 : }
2156 : :
2157 : 4 : void MainWindow::renameFolder() {
2158 : : bool ok;
2159 : 4 : QString srcDir = QDir::cleanPath(m_tree->currentDir(false));
2160 : 4 : QString srcDirName = QDir(srcDir).dirName();
2161 : : QString newName =
2162 : 4 : QInputDialog::getText(this, tr("Rename folder"), tr("Rename folder to: "),
2163 [ + + ]: 8 : QLineEdit::Normal, srcDirName, &ok);
2164 [ + + + - ]: 4 : if (!ok || newName.isEmpty()) {
2165 : : return;
2166 : : }
2167 : : QString destDir = srcDir;
2168 : 3 : destDir.replace(srcDir.lastIndexOf(srcDirName), srcDirName.length(), newName);
2169 [ + + + ]: 3 : if (!confirmPathInStore(destDir)) {
2170 : : return;
2171 : : }
2172 : 2 : if (!PlainMessageBox::confirmPassRun(
2173 : 4 : this, QtPassSettings::getPassStore(), [&srcDir, &destDir] {
2174 : 2 : return QtPassSettings::getPass()->entriesMoveWouldWiden(srcDir,
2175 : 2 : destDir);
2176 : : })) {
2177 : : return;
2178 : : }
2179 : 4 : QtPassSettings::getPass()->Move(std::move(srcDir), std::move(destDir), false);
2180 : : }
2181 : :
2182 : 6 : void MainWindow::editPassword(const QString &file) {
2183 [ + - ]: 6 : if (!file.isEmpty()) {
2184 : 6 : const AppSettings s = QtPassSettings::loadEffective();
2185 [ + + + - ]: 6 : if (s.useGit && s.autoPull) {
2186 : 1 : 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 : 6 : m_shownFile.clear();
2194 : 6 : setPassword(file, false);
2195 : 6 : }
2196 : 6 : }
2197 : :
2198 : 2 : void MainWindow::renamePassword() {
2199 : : bool ok;
2200 : 2 : QString file = getFile(ui->treeView->currentIndex(), false);
2201 : 2 : QString filePath = QFileInfo(file).path();
2202 : 2 : QString fileName = QFileInfo(file).fileName();
2203 [ + + + - ]: 4 : if (fileName.endsWith(".gpg", Qt::CaseInsensitive)) {
2204 : 2 : fileName.chop(4);
2205 : : }
2206 : :
2207 : : QString newName =
2208 : 2 : QInputDialog::getText(this, tr("Rename file"), tr("Rename file to: "),
2209 [ + + ]: 4 : QLineEdit::Normal, fileName, &ok);
2210 [ + - + - ]: 2 : if (!ok || newName.isEmpty()) {
2211 : : return;
2212 : : }
2213 : 2 : QString newFile = Util::joinPath(filePath, newName);
2214 [ + + + ]: 2 : if (!confirmPathInStore(newFile)) {
2215 : : return;
2216 : : }
2217 : 1 : if (!PlainMessageBox::confirmPassRun(
2218 : 2 : this, QtPassSettings::getPassStore(), [&file, &newFile] {
2219 : 1 : return QtPassSettings::getPass()->entriesMoveWouldWiden(file,
2220 : 1 : newFile);
2221 : : })) {
2222 : : return;
2223 : : }
2224 : 2 : QtPassSettings::getPass()->Move(std::move(file), std::move(newFile), false);
2225 : : }
2226 : :
2227 : 5 : void MainWindow::copySelectionOrPassword() {
2228 : 5 : 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 : 5 : if (auto *text = qobject_cast<QTextEdit *>(focus);
2232 [ + + + + : 5 : text != nullptr && text->textCursor().hasSelection()) {
+ ]
2233 : 1 : text->copy();
2234 : 1 : 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 [ + + - + ]: 4 : label != nullptr && label->hasSelectedText()) {
2240 : 1 : m_qtPass->clipboard().copyText(label->selectedText());
2241 : 1 : 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 [ + - ]: 3 : if (focus == ui->grepResultsList) {
2246 : 3 : if (const QTreeWidgetItem *item = ui->grepResultsList->currentItem();
2247 [ + - + - : 6 : item != nullptr && !item->text(0).isEmpty()) {
+ - ]
2248 : 6 : m_qtPass->clipboard().copyText(item->text(0));
2249 : : }
2250 : 3 : return;
2251 : : }
2252 : 0 : copyPasswordFromTreeview();
2253 : : }
2254 : :
2255 : 9 : void MainWindow::copyPasswordFromTreeview() {
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 [ - + ]: 9 : if (ui->treeView->isHidden()) {
2259 : 0 : return;
2260 : : }
2261 : 9 : QFileInfo fileOrFolder = m_tree->fileInfo(ui->treeView->currentIndex());
2262 : :
2263 [ + + - ]: 9 : if (fileOrFolder.isFile()) {
2264 : 9 : 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 : 9 : m_copyRequestFile = file;
2268 : : // This Show repaints the panel as well; see onOtp().
2269 : 9 : m_shownFile = file;
2270 : 18 : QtPassSettings::getPass()->Show(std::move(file));
2271 : : }
2272 : 9 : }
2273 : :
2274 : 33 : void MainWindow::passwordFromFileToClipboard(const QString &text,
2275 : : const QString &file) {
2276 [ + + + + ]: 33 : if (m_copyRequestFile.isEmpty() || file != m_copyRequestFile) {
2277 : 28 : return;
2278 : : }
2279 : 8 : 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 : 8 : 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 [ + + + ]: 8 : if (FileContent::isOtpPasswordLine(first)) {
2289 : 6 : flashText(tr("This entry holds an OTP secret, not a password"), true);
2290 : : return;
2291 : : }
2292 : 5 : m_qtPass->clipboard().copyText(first);
2293 : : }
2294 : :
2295 : 46 : void MainWindow::showStatusMessage(const QString &msg, int timeout) {
2296 : 46 : ui->statusBar->showMessage(msg, timeout);
2297 : 46 : }
2298 : :
2299 : 4 : void MainWindow::reencryptPath(const QString &dir) {
2300 : 4 : QDir checkDir(dir);
2301 [ + + + ]: 4 : if (!checkDir.exists()) {
2302 : 2 : PlainMessageBox::critical(this, tr("Error"),
2303 : 2 : tr("Directory does not exist: %1").arg(dir));
2304 : 1 : return;
2305 : : }
2306 [ + + - ]: 3 : if (refuseLinkedFolder(dir)) {
2307 : : return;
2308 : : }
2309 : :
2310 : 3 : const bool yes = PlainMessageBox::askYes(
2311 : 3 : this, tr("Re-encrypt passwords"),
2312 : 3 : 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 [ + + + + ]: 6 : .arg(Util::displayable(QDir(dir).dirName(), false)));
2320 : :
2321 [ + + ]: 3 : if (!yes)
2322 : : return;
2323 : :
2324 : : // Disable now; the asynchronous startReencryptPath signal re-runs this
2325 : : // harmlessly.
2326 : 1 : startReencryptPath();
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 : 2 : QtPassSettings::getImitatePass()->reencryptPath(
2331 [ + + + + ]: 2 : QDir::cleanPath(QDir(dir).absolutePath()), QtPassSettings::load());
2332 : 4 : }
2333 : :
2334 : : // Idempotent: reencryptPath() calls it before ImitatePass emits the signal.
2335 : 7 : void MainWindow::startReencryptPath() {
2336 : 7 : m_reencryptRunning = true;
2337 : 7 : 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 : 7 : m_uiWatchdog.stop();
2341 : 7 : ui->treeView->setDisabled(true);
2342 [ + + ]: 7 : if (m_reencryptProgress)
2343 : : return;
2344 : 5 : auto *progress = new QProgressDialog(tr("Re-encrypting passwords..."),
2345 [ + + ]: 10 : tr("Cancel"), 0, 0, this);
2346 : 5 : progress->setWindowTitle(tr("Re-encrypt passwords"));
2347 : 5 : progress->setWindowModality(Qt::WindowModal);
2348 : 5 : progress->setAutoClose(false);
2349 : 5 : progress->setAutoReset(false);
2350 : 5 : progress->setMinimumDuration(0);
2351 : 5 : connect(progress, &QProgressDialog::canceled, this, [this]() {
2352 : 1 : QtPassSettings::getImitatePass()->cancelReencryptPath();
2353 : 1 : showStatusMessage(tr("Cancelling re-encryption"), 5000);
2354 : 1 : });
2355 : : m_reencryptProgress = progress;
2356 : 5 : progress->show();
2357 : : }
2358 : :
2359 : 7 : void MainWindow::reencryptProgress(int current, int total) {
2360 [ + + + - ]: 7 : if (!m_reencryptProgress || m_inProgressUpdate)
2361 : : return;
2362 : : QProgressDialog *progress = m_reencryptProgress;
2363 : 6 : progress->setMaximum(total);
2364 : 6 : progress->setLabelText(
2365 [ + + ]: 6 : 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 : 6 : m_inProgressUpdate = true;
2371 : 6 : progress->setValue(current);
2372 : 6 : m_inProgressUpdate = false;
2373 [ + + ]: 6 : if (m_progressToDelete) {
2374 : 2 : m_progressToDelete->deleteLater();
2375 : : m_progressToDelete = nullptr;
2376 : : }
2377 : : }
2378 : :
2379 : 5 : void MainWindow::endReencryptPath() {
2380 : 5 : m_reencryptRunning = false;
2381 [ + - ]: 5 : if (m_reencryptProgress) {
2382 : 5 : m_reencryptProgress->hide();
2383 [ + + ]: 5 : if (m_inProgressUpdate) {
2384 : : m_progressToDelete = m_reencryptProgress;
2385 : : } else {
2386 : 3 : m_reencryptProgress->deleteLater();
2387 : : }
2388 : : m_reencryptProgress = nullptr;
2389 : : }
2390 : 5 : setUiElementsEnabled(true);
2391 : 5 : }
2392 : :
2393 : 0 : void MainWindow::askReencryptUnexpected(const QString &dir,
2394 : : const QStringList &files,
2395 : : const QStringList &details) {
2396 : 0 : const AppSettings s = QtPassSettings::load();
2397 : 0 : 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 : 0 : QList<std::pair<QString, QString>> rows;
2401 [ # # ]: 0 : for (qsizetype i = 0; i < files.size(); ++i) {
2402 : 0 : rows.append({Util::displayable(store.relativeFilePath(files.at(i)), false),
2403 : 0 : details.value(i)});
2404 : : }
2405 : 0 : std::sort(rows.begin(), rows.end());
2406 : : constexpr int kListed = 15;
2407 : 0 : QStringList lines;
2408 [ # # # # ]: 0 : for (qsizetype i = 0; i < rows.size() && i < kListed; ++i) {
2409 : 0 : lines << rows.at(i).first + QStringLiteral(": ") + rows.at(i).second;
2410 : : }
2411 [ # # ]: 0 : if (rows.size() > kListed) {
2412 : 0 : lines << tr("... and %n more", nullptr,
2413 : 0 : static_cast<int>(rows.size() - kListed));
2414 : : }
2415 : 0 : const int n = static_cast<int>(files.size());
2416 : 0 : const bool yes = PlainMessageBox::askYes(
2417 : 0 : this, tr("Re-encrypt these too?"),
2418 : 0 : 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 : 0 : nullptr, n) +
2423 : 0 : QStringLiteral("\n\n") + lines.join(QLatin1Char('\n')) +
2424 : 0 : QStringLiteral("\n\n") +
2425 : 0 : tr("Re-encrypt them for this folder's recipients? If not, they "
2426 : 0 : "stay readable only by whoever they are encrypted to now."));
2427 [ # # ]: 0 : if (!yes) {
2428 : : return;
2429 : : }
2430 : 0 : startReencryptPath();
2431 : 0 : QtPassSettings::getImitatePass()->reencryptAlso(dir, files, s);
2432 : 0 : }
2433 : :
2434 : 4 : void MainWindow::exportPublicKey() {
2435 : 4 : const AppSettings s = QtPassSettings::load();
2436 : : const QString identity = s.passSigningKey;
2437 [ + + ]: 4 : if (identity.isEmpty()) {
2438 : 2 : QMessageBox::information(
2439 : 1 : this, tr("Export public key"),
2440 : 0 : tr("<h3>Export your public key</h3>"
2441 : : "<p>No signing key is configured. Set one in QtPass Settings "
2442 : : "> GPG keys, or run this in a terminal:</p>"
2443 : : "<pre>gpg --armor --export --output my_key.asc <your-key-id"
2444 : : "></pre>"
2445 : : "<p>Then send the file to your teammates.</p>"));
2446 : 1 : return;
2447 : : }
2448 : : QString gpgExe = s.gpgExecutable;
2449 [ - + ]: 3 : if (gpgExe.isEmpty()) {
2450 : 0 : gpgExe = QStringLiteral("gpg");
2451 : : }
2452 : 3 : 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 [ + + - ]: 3 : if (Pass *pass = QtPassSettings::getPass(); pass != nullptr) {
2456 : : if (const std::optional<QHash<QString, QStringList>> held =
2457 : 3 : pass->keyLinesHeldTwice(keys);
2458 [ + - ]: 3 : !held || !held->isEmpty()) {
2459 : 1 : PlainMessageBox::warning(
2460 : 1 : this, tr("Export public key"),
2461 : 1 : tr("Your key cannot be exported on its own:\n\n%1")
2462 [ + + ]: 2 : .arg(Pass::describeKeyLinesHeldTwice(held)));
2463 : : return;
2464 : : }
2465 : : }
2466 : 2 : QString stdOut;
2467 : 2 : QString stdErr;
2468 : : // In the store's environment, the keyring the check above read.
2469 : 2 : Pass *pass = QtPassSettings::getPass();
2470 : : int exitCode =
2471 : : pass != nullptr
2472 [ + - + ]: 2 : ? pass->exportPublicKeys(gpgExe, keys, &stdOut, &stdErr)
2473 : 0 : : Executor::executeBlocking(gpgExe,
2474 : 0 : QStringList{QStringLiteral("--armor"),
2475 : 2 : QStringLiteral("--export")} +
2476 : 0 : keys,
2477 : : &stdOut, &stdErr);
2478 [ + + + - ]: 2 : if (exitCode != 0 || stdOut.isEmpty()) {
2479 : 2 : PlainMessageBox::warning(this, tr("Export public key"),
2480 : 1 : tr("Could not export public key for %1.\n\n%2")
2481 : 2 : .arg(identity, stdErr.isEmpty()
2482 [ - + ]: 2 : ? tr("No output from gpg.")
2483 : : : stdErr));
2484 : : return;
2485 : : }
2486 : 1 : ExportPublicKeyDialog dialog(identity, stdOut, this);
2487 : 1 : dialog.exec();
2488 : 5 : }
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.
2492 : 2 : void MainWindow::addRecipient(const QString &dir) {
2493 [ + + ]: 2 : if (refuseLinkedFolder(dir)) {
2494 : 1 : return;
2495 : : }
2496 : 1 : UsersDialog d(QtPassSettings::getPass(), QtPassSettings::load(), dir, this);
2497 : 1 : d.exec();
2498 : 1 : }
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.
2503 : 23 : auto MainWindow::refuseLinkedFolder(const QString &dir) -> bool {
2504 [ + + + ]: 23 : if (!Util::isUnderLink(dir, QtPassSettings::load().passStore)) {
2505 : : return false;
2506 : : }
2507 : 4 : PlainMessageBox::critical(
2508 : 4 : this, tr("Not a folder of the store"),
2509 : 4 : 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 [ + + + ]: 8 : .arg(QDir::toNativeSeparators(QDir::cleanPath(dir))));
2512 : 4 : return true;
2513 : : }
2514 : :
2515 : 1 : void MainWindow::showShareHelp() {
2516 : 2 : QMessageBox::information(
2517 : 1 : this, tr("Sharing passwords with GPG"),
2518 : 1 : 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 : 1 : }
2531 : :
2532 : 480 : void MainWindow::updateGitButtonVisibility(bool uiEnabled) {
2533 : 480 : const AppSettings s = QtPassSettings::loadEffective();
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 [ + + - + : 480 : s.useGit && !(s.gitExecutable.isEmpty() && s.passExecutable.isEmpty());
- - ]
2538 : 480 : ui->actionPush->setVisible(usable);
2539 : 480 : ui->actionUpdate->setVisible(usable);
2540 : : // The separator in front of them would otherwise sit next to the next one.
2541 : 480 : const QList<QAction *> actions = ui->toolBar->actions();
2542 : 480 : const qsizetype at = actions.indexOf(ui->actionPush);
2543 [ + - + + : 480 : if (at > 0 && actions.at(at - 1)->isSeparator()) {
- ]
2544 : 480 : actions.at(at - 1)->setVisible(usable);
2545 : : }
2546 : 480 : enableGitButtons(usable && uiEnabled);
2547 : 480 : }
2548 : :
2549 : 490 : void MainWindow::updateOtpButtonVisibility(bool uiEnabled) {
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 : 490 : ui->actionOtp->setVisible(true);
2555 [ + + ]: 598 : ui->actionOtp->setEnabled(QtPassSettings::isUseOtp() && uiEnabled);
2556 : 490 : }
2557 : :
2558 : 211 : void MainWindow::updateGrepButtonVisibility() {
2559 : 211 : const bool enabled = QtPassSettings::isUseGrepSearch();
2560 : 211 : ui->grepButton->setVisible(enabled);
2561 : 211 : ui->grepCaseButton->setVisible(enabled);
2562 [ + + + + ]: 211 : if (!enabled && m_grep.inGrepMode()) {
2563 : 1 : ui->grepButton->setChecked(false);
2564 : : }
2565 : 211 : }
2566 : :
2567 : 480 : void MainWindow::enableGitButtons(const bool &state) {
2568 : 480 : ui->actionPush->setEnabled(state);
2569 : 480 : ui->actionUpdate->setEnabled(state);
2570 : 480 : }
2571 : :
2572 : 4 : void MainWindow::critical(const QString &title, const QString &msg) {
2573 : : // Pass's messages quote store paths; see PlainMessageBox.
2574 : 4 : PlainMessageBox::critical(this, title, msg);
2575 : 4 : }
2576 : :
2577 : 7 : void MainWindow::onProcessOutput(const QString &output, bool isError,
2578 : : Enums::PROCESS pid) {
2579 [ + + ]: 7 : if (!QtPassSettings::isShowProcessOutput()) {
2580 : : return;
2581 : : }
2582 : 6 : m_processOutput->append(output, isError,
2583 : 12 : ProcessOutputPanel::processName(pid));
2584 : : }
2585 : :
2586 : 5 : void MainWindow::updateProcessOutputVisibility() {
2587 : : // The action's toggled handler shows or hides the dock.
2588 : 5 : ui->actionShowProcessOutput->setChecked(
2589 : 5 : QtPassSettings::isShowProcessOutput());
2590 : 5 : m_processOutput->setVisible(QtPassSettings::isShowProcessOutput());
2591 : 5 : }
|