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

IJHack / QtPass / 43920729650

16 Nov 2026 05:39PM UTC coverage: 96.333% (-0.06%) from 96.394%
43920729650

push

github

web-flow
OTP: read the split otpauth: // form older versions saved (#2226)

With "otpauth" in the template, the edit dialog of 1.8 to 2.0-rc2 split
an otpauth:// line at its colon and saved it as `otpauth: //totp/...`.
Since #2199 that line is kept off the screen, but it gave no OTP code:
it is neither a bare otpauth:// line nor a field whose value is one.
bareOtpUriOf() now reads a line written as `otpauth:`, blanks, then
`//...` as the URI without the blanks, for body lines and for the first
line. The entry itself is kept as written.

Signed-off-by: Anne Jan Brouwer <brouwer@annejan.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

15 of 15 new or added lines in 1 file covered. (100.0%)

6 existing lines in 1 file now uncovered.

8879 of 9217 relevant lines covered (96.33%)

731.42 hits per line

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

97.19
/src/mainwindow.cpp
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 "processoutputpanel.h"
26
#include "qpushbuttonasqrcode.h"
27
#include "qpushbuttonshowpassword.h"
28
#include "qpushbuttonwithclipboard.h"
29
#include "qtpass.h"
30
#include "qtpasssettings.h"
31
#include "templateio.h"
32
#include "totp.h"
33
#include "trayicon.h"
34
#include "ui_mainwindow.h"
35
#include "usersdialog.h"
36
#include "util.h"
37
#include "windowstatestore.h"
38
#include <QApplication>
39
#include <QCloseEvent>
40
#include <QDate>
41
#include <QDesktopServices>
42
#include <QDialog>
43
#include <QDockWidget>
44
#include <QFileInfo>
45
#include <QFileSystemModel>
46
#include <QHBoxLayout>
47
#include <QInputDialog>
48
#include <QLabel>
49
#include <QLineEdit>
50
#include <QMenu>
51
#include <QMenuBar>
52
#include <QMessageBox>
53
#include <QProgressDialog>
54
#include <QPushButton>
55
#include <QShortcut>
56
#include <QTextCharFormat>
57
#include <QTextEdit>
58
#include <QTextStream>
59
#include <QTimer>
60
#include <QTreeWidget>
61
#include <QUrl>
62
#include <algorithm>
63
#include <array>
64
#include <utility>
65

66
MainWindow::MainWindow(const QString &searchText, QWidget *parent)
171 ✔
67
    : QMainWindow(parent), ui(new Ui::MainWindow) {
171 ✔
68
#ifdef __APPLE__
69
  // extra treatment for mac os
70
  // see https://doc.qt.io/qt-6/qkeysequence.html#qt_set_sequence_auto_mnemonic
71
  qt_set_sequence_auto_mnemonic(true);
72
#endif
73
  ui->setupUi(this);
171 ✔
74

75
  m_qtPass = new QtPass(this);
171 ✔
76
  restoreWindow();
171 ✔
77
  connectBackends();
171 ✔
78

79
  new QShortcut(QKeySequence(QKeySequence::StandardKey::Copy), this, this,
171 ✔
80
                &MainWindow::copySelectionOrPassword);
171 ✔
81

82
  m_tree = new StoreTree(ui->treeView, this);
171 ✔
83
  m_tree->setStore(QtPassSettings::getPassStore(Util::findPasswordStore()));
171 ✔
84
  m_tree->setPass(QtPassSettings::getPass());
171 ✔
85
  connect(ui->treeView, &QWidget::customContextMenuRequested, this,
171 ✔
86
          &MainWindow::showContextMenu);
171 ✔
87
  connect(ui->treeView, &DeselectableTreeView::emptyClicked, this,
171 ✔
88
          &MainWindow::deselect);
171 ✔
89

90
  initTextBrowser();
171 ✔
91

92
  updateProfileBox();
171 ✔
93

94
  initDisplayPanel();
171 ✔
95

96
  QtPassSettings::getPass()->updateEnv();
171 ✔
97

98
  // Install the search-box key filter once, not on every setUiElementsEnabled
99
  // call.
100
  ui->lineEdit->installEventFilter(this);
171 ✔
101
  // Both live in Breeze's "tools area" and get its header palette; see the
102
  // PaletteChange branch in eventFilter().
103
  ui->toolBar->installEventFilter(this);
171 ✔
104
  menuBar()->installEventFilter(this);
171 ✔
105

106
  initTimers();
171 ✔
107

108
  initToolBarButtons();
171 ✔
109
  initStatusBar();
171 ✔
110
  initProcessOutput();
171 ✔
111

112
  ui->lineEdit->setClearButtonEnabled(true);
171 ✔
113
  updateGrepButtonVisibility();
171 ✔
114

115
  setUiElementsEnabled(true);
171 ✔
116

117
  // No QApplication::quit() here: before exec() it is a documented no-op.
118
  // main() checks initSucceeded() and exits before show() instead.
119
  m_qtPass->init();
171 ✔
120
  // OK is not gated on Util::configIsValid(): an accepted configuration can
121
  // still lack a .gpg-id, so ask again; only a cancel ends the loop.
122
  while (!Util::configIsValid(QtPassSettings::load())) {
172 ✔
123
    if (!config()) {
2 ✔
124
      return;
125
    }
126
  }
127
  m_freshStart = false;
170 ✔
128
  m_initSucceeded = true;
170 ✔
129

130
  // Searched as qtpass(1) promises, once the window and its tree are up:
131
  // filtered at once and an entry named exactly so opened. Setting the
132
  // text here left it to the search timer, which only highlights. Queued
133
  // only now: from before the configuration loop, a wizard's nested event
134
  // loop ran it while no store was set yet.
135
  if (!searchText.isEmpty()) {
170 ✔
136
    QTimer::singleShot(0, this,
137
                       [this, searchText] { applySearchText(searchText); });
×
138
  }
139

140
  // Initial focus is set in showEvent(): a 10 ms QTimer here could fire
141
  // before the window was realised (queued ActivationChange, nested exec() in
142
  // init()) and selectAll() segfaulted inside Qt (#1187, #1188).
143
}
×
144

145
void MainWindow::connectBackends() {
171 ✔
146
  connect(m_qtPass, &QtPass::outputReady, this,
171 ✔
147
          [this](const QString &html) { flashText(html, false, true); });
212 ✔
148
  connect(m_qtPass, &QtPass::operationFinished, this,
171 ✔
149
          [this]() { setUiElementsEnabled(true); });
231 ✔
150
  connect(m_qtPass, &QtPass::statusMessage, this,
171 ✔
151
          &MainWindow::showStatusMessage);
171 ✔
152
  connect(m_qtPass, &QtPass::pushRequested, this, &MainWindow::onAutoPush);
171 ✔
153
  // With automatic push, the push is queued first and the refresh would start
154
  // as soon as it ends, emptying the browser before a failed push's error was
155
  // painted. So the refresh waits for the push (see connectPassSignals()). It
156
  // claims the panel now, as its decrypt would: whatever drops a pending
157
  // decrypt (another entry, a search, Escape, Edit, an error) drops it too.
158
  connect(m_qtPass, &QtPass::entryInserted, this, [this]() {
171 ✔
159
    const QModelIndex index = getCurrentTreeViewIndex();
9 ✔
160
    const QString file = getFile(index, true);
9 ✔
161
    Pass *pass = QtPassSettings::getPass();
9 ✔
162
    if (!file.isEmpty() && pass->isPushing()) {
18 ✔
163
      m_refreshAfterPush = file;
8 ✔
164
      m_refreshAfterPushOwner = pass;
8 ✔
165
      m_shownFile = file;
8 ✔
166
      return;
167
    }
168
    on_treeView_clicked(index);
1 ✔
169
  });
170
  connect(&m_qtPass->clipboard(), &ClipboardManager::statusMessage, this,
171 ✔
171
          [this](const QString &message) { showStatusMessage(message); });
187 ✔
172
  // Both backends: the active one can change through the configuration
173
  // dialog without a restart.
174
  connectPassSignals(QtPassSettings::getRealPass());
171 ✔
175
  connectPassSignals(QtPassSettings::getImitatePass());
171 ✔
176
  ImitatePass *ipass = QtPassSettings::getImitatePass();
171 ✔
177
  connect(ipass, &ImitatePass::startReencryptPath, this,
171 ✔
178
          &MainWindow::startReencryptPath);
171 ✔
179
  connect(ipass, &ImitatePass::reencryptProgress, this,
171 ✔
180
          &MainWindow::reencryptProgress);
171 ✔
181
  connect(ipass, &ImitatePass::endReencryptPath, this,
171 ✔
182
          &MainWindow::endReencryptPath);
171 ✔
183
}
171 ✔
184

185
void MainWindow::initTextBrowser() {
171 ✔
186
  {
187
    const AppSettings s = QtPassSettings::load();
171 ✔
188
    if (s.useMonospace) {
171 ✔
189
      QFont monospace("Monospace");
1 ✔
190
      monospace.setStyleHint(QFont::Monospace);
1 ✔
191
      ui->textBrowser->setFont(monospace);
1 ✔
192
    }
1 ✔
193
    if (s.noLineWrapping) {
171 ✔
194
      ui->textBrowser->setLineWrapMode(QTextBrowser::NoWrap);
1 ✔
195
    }
196
    clearPanelTimer.setInterval(MS_PER_SECOND * s.autoclearPanelSeconds);
171 ✔
197
  }
171 ✔
198
  ui->textBrowser->setOpenExternalLinks(true);
171 ✔
199
  ui->textBrowser->setContextMenuPolicy(Qt::CustomContextMenu);
171 ✔
200
  connect(ui->textBrowser, &QWidget::customContextMenuRequested, this,
171 ✔
201
          &MainWindow::showBrowserContextMenu);
171 ✔
202
}
171 ✔
203

204
void MainWindow::initDisplayPanel() {
171 ✔
205
  m_displayPanel = new PasswordDisplayPanel(
171 ✔
206
      ui->gridLayout, ui->verticalLayoutPassword, this, this);
171 ✔
207
  connect(m_displayPanel, &PasswordDisplayPanel::copyRequested,
171 ✔
208
          &m_qtPass->clipboard(), &ClipboardManager::copyText);
171 ✔
209
  connect(m_displayPanel, &PasswordDisplayPanel::textCopied,
171 ✔
210
          &m_qtPass->clipboard(), &ClipboardManager::trackCopied);
171 ✔
211
  connect(ui->textBrowser, &SecretTextBrowser::copied, &m_qtPass->clipboard(),
171 ✔
212
          &ClipboardManager::trackCopied);
171 ✔
213
  connect(m_displayPanel, &PasswordDisplayPanel::qrRequested, m_qtPass,
171 ✔
214
          &QtPass::showTextAsQRCode);
171 ✔
215
  // Double-click on what is shown edits it, as in the tree.
216
  connect(m_displayPanel, &PasswordDisplayPanel::editRequested, this, [this] {
171 ✔
217
    if (ui->actionEdit->isEnabled()) {
3 ✔
218
      onEdit();
2 ✔
219
    }
220
  });
3 ✔
221
}
171 ✔
222

223
void MainWindow::initTimers() {
171 ✔
224
  clearPanelTimer.setSingleShot(true);
171 ✔
225
  connect(&clearPanelTimer, &QTimer::timeout, this, [this]() { clearPanel(); });
173 ✔
226

227
  searchTimer.setInterval(350);
171 ✔
228
  searchTimer.setSingleShot(true);
171 ✔
229

230
  connect(&searchTimer, &QTimer::timeout, this, &MainWindow::onTimeoutSearch);
171 ✔
231

232
  // Safety net: if a backend operation disables the UI but never signals
233
  // completion, re-enable after a timeout so the window can't get stuck.
234
  m_uiWatchdog.setSingleShot(true);
171 ✔
235
  m_uiWatchdog.setInterval(UiWatchdogMs);
171 ✔
236
  connect(&m_uiWatchdog, &QTimer::timeout, this, [this]() {
171 ✔
237
    showStatusMessage(tr("Operation timed out; re-enabling interface."));
×
238
    // Drop any in-flight OTP request so a late finishedShow cannot be mistaken
239
    // for the answer to it.
240
    cancelOtpRequest();
×
241
    setUiElementsEnabled(true);
×
242
  });
×
243
}
171 ✔
244

245
void MainWindow::initProcessOutput() {
171 ✔
246
  m_processOutput = new ProcessOutputPanel(this);
171 ✔
247
  addDockWidget(Qt::BottomDockWidgetArea, m_processOutput);
171 ✔
248
  // After addDockWidget so our preference wins over any cached state
249
  // QMainWindow applies; restoreWindow() already processed the saved layout.
250
  m_processOutput->setVisible(QtPassSettings::isShowProcessOutput());
171 ✔
251
  // From the setting, not isVisible(): the window is not shown yet, so no
252
  // child of it reports visible.
253
  ui->actionShowProcessOutput->setChecked(
171 ✔
254
      QtPassSettings::isShowProcessOutput());
171 ✔
255
  connect(ui->actionShowProcessOutput, &QAction::toggled, this,
171 ✔
256
          [this](bool show) {
171 ✔
257
            m_processOutput->setVisible(show);
2 ✔
258
            AppSettings s = QtPassSettings::load();
2 ✔
259
            if (s.showProcessOutput != show) {
2 ✔
260
              s.showProcessOutput = show;
2 ✔
261
              QtPassSettings::save(s);
2 ✔
262
            }
263
          });
2 ✔
264

265
  connect(QtPassSettings::getPass(), &Pass::finishedAnyWithPid, this,
171 ✔
266
          [this](const QString &out, const QString &err, Enums::PROCESS pid) {
171 ✔
267
            // Never route potentially-secret output through the panel:
268
            // PASS_SHOW goes to the text browser (cleared on a timer when
269
            // "Autoclear panel" is set),
270
            // PASS_GREP would return password-file lines (#252; it is no
271
            // longer started, the check stays), and PASS_INSERT
272
            // is excluded defensively in case a future path uses --echo.
273
            if (ProcessOutputPanel::isSensitiveProcess(pid)) {
13 ✔
274
              return;
275
            }
276
            if (!out.isEmpty()) {
12 ✔
277
              onProcessOutput(out, false, pid);
1 ✔
278
            }
279
            if (!err.isEmpty()) {
12 ✔
280
              onProcessOutput(err, true, pid);
4 ✔
281
            }
282
          });
283
}
171 ✔
284

285
MainWindow::~MainWindow() {
338 ✔
286
  // Quit from the tray menu or a SIGTERM never delivers closeEvent(); the
287
  // window still knows its last geometry here.
288
  saveWindowState();
171 ✔
289
  delete m_qtPass;
171 ✔
290
}
509 ✔
291

292
// The signals of one backend that the window answers itself.
293
void MainWindow::connectPassSignals(Pass *pass) {
342 ✔
294
  // A failed decrypt never emits finishedShow; drop the pending OTP/copy
295
  // request so a later decrypt of the same entry is not taken as its answer.
296
  connect(pass, &Pass::processErrorExit, this, &MainWindow::onOperationError);
342 ✔
297
  connect(pass, &Pass::critical, this, &MainWindow::critical);
342 ✔
298
  connect(pass, &Pass::startingExecuteWrapper, this,
342 ✔
299
          &MainWindow::executeWrapperStarted);
342 ✔
300
  // The profile box comes back when the queue is done, also after the
301
  // watchdog released the rest of the interface early.
302
  connect(pass, &Pass::idle, this, &MainWindow::updateProfileBoxEnabled);
342 ✔
303
  connect(pass, &Pass::statusMsg, this, &MainWindow::showStatusMessage);
342 ✔
304
  connect(pass, &Pass::finishedShow, this, &MainWindow::passShowHandler);
342 ✔
305
  // Both check the file against their own pending request and ignore the
306
  // rest, so they can stay connected for good.
307
  connect(pass, &Pass::finishedShow, this, &MainWindow::otpFromFileToClipboard);
342 ✔
308
  connect(pass, &Pass::finishedShow, this,
342 ✔
309
          &MainWindow::passwordFromFileToClipboard);
342 ✔
310
  connect(pass, &Pass::finishedGrep, this, &MainWindow::onGrepFinished);
342 ✔
311
  // The refresh a save left waiting runs once the last push went through,
312
  // by name as it was queued before (the save's rewrite of the file may have
313
  // replaced its row in the tree), and only while the entry still holds the
314
  // panel and nothing else is queued: queued work would run first, and the
315
  // refresh would empty the browser of its error. A failed push dropped it
316
  // (onOperationError()).
317
  connect(pass, &Pass::finishedGitPush, this, [this, pass]() {
342 ✔
318
    if (m_refreshAfterPush.isEmpty() || m_refreshAfterPushOwner != pass ||
31 ✔
319
        pass->isPushing()) {
9 ✔
320
      return;
5 ✔
321
    }
322
    const QString file = std::exchange(m_refreshAfterPush, QString());
7 ✔
323
    m_refreshAfterPushOwner = nullptr;
7 ✔
324
    if (file == m_shownFile && pass->isIdle()) {
7 ✔
325
      ui->passwordName->setText(file);
4 ✔
326
      pass->Show(file);
8 ✔
327
    }
328
  });
329
}
342 ✔
330

331
// Idempotent; called from closeEvent() and the destructor.
332
void MainWindow::saveWindowState() {
175 ✔
333
  QtPassSettings::setGeometry(saveGeometry());
175 ✔
334
  QtPassSettings::setSavestate(saveState());
175 ✔
335
}
175 ✔
336

337
void MainWindow::focusInput() {
67 ✔
338
  // findChild() rather than ui->lineEdit: on a fresh-config first launch
339
  // config() calls setWindowFlags(), which rebuilds the native window, and
340
  // under Qt 6.11 the QLineEdit was destroyed while ui->lineEdit kept its old
341
  // address (SIGSEGV in QWidget::testAttribute). findChild() returns null.
342
  if (!isVisible()) {
67 ✔
343
    return;
344
  }
345
  auto *lineEdit = findChild<QLineEdit *>(QStringLiteral("lineEdit"));
67 ✔
346
  if (lineEdit == nullptr || !lineEdit->isVisible()) {
67 ✔
347
    return;
348
  }
349
  lineEdit->selectAll();
67 ✔
350
  lineEdit->setFocus();
67 ✔
351
  // Only once focus has landed: set in showEvent(), an early return above
352
  // would consume the one-shot and never retry.
353
  m_firstShowCompleted = true;
67 ✔
354
}
355

356
auto MainWindow::event(QEvent *event) -> bool {
7,672 ✔
357
  if (event->type() == QEvent::ApplicationPaletteChange) {
7,672 ✔
358
    m_themeSwitched = true;
11 ✔
359
    // Breeze may re-stamp the bars before this arrives (Plasma 6 does):
360
    // their PaletteChange then found no switch yet, so check them now too.
361
    QTimer::singleShot(0, this, &MainWindow::dropStaleToolsAreaPalettes);
11 ✔
362
  }
363
  return QMainWindow::event(event);
7,672 ✔
364
}
365

366
void MainWindow::changeEvent(QEvent *event) {
230 ✔
367
  QWidget::changeEvent(event);
230 ✔
368
  if (event->type() == QEvent::PaletteChange && m_displayPanel != nullptr) {
230 ✔
369
    // Desktop switched light/dark. Top-level widgets get PaletteChange
370
    // (ApplicationPaletteChange goes to QApplication); stylesheets with
371
    // baked-in palette colours must be re-derived by hand.
372
    m_displayPanel->refreshPalette();
10 ✔
373
  }
374
  if (event->type() == QEvent::ActivationChange && isActiveWindow() &&
230 ✔
375
      isVisible()) {
376
    // Defer a tick so the activation dispatch chain unwinds first: calling
377
    // focusInput() inline has segfaulted on half-rebuilt ui state.
378
    QMetaObject::invokeMethod(this, &MainWindow::focusInput,
38 ✔
379
                              Qt::QueuedConnection);
380
  }
381
}
230 ✔
382

383
void MainWindow::showEvent(QShowEvent *event) {
40 ✔
384
  QMainWindow::showEvent(event);
40 ✔
385
  if (m_firstShowCompleted) {
40 ✔
386
    return;
387
  }
388
  // Queued so the platform map and pending rebuilds (setWindowFlags on the
389
  // wizard path) settle first. focusInput() sets the latch only on success,
390
  // so a failed lookup retries on the next show.
391
  QMetaObject::invokeMethod(this, &MainWindow::focusInput,
38 ✔
392
                            Qt::QueuedConnection);
393
}
394

395
void MainWindow::initToolBarButtons() {
171 ✔
396
  connect(ui->actionAddPassword, &QAction::triggered, this,
171 ✔
397
          &MainWindow::addPassword);
171 ✔
398
  connect(ui->actionAddFolder, &QAction::triggered, this,
171 ✔
399
          &MainWindow::addFolder);
171 ✔
400
  connect(ui->actionEdit, &QAction::triggered, this, &MainWindow::onEdit);
171 ✔
401
  connect(ui->actionDelete, &QAction::triggered, this, &MainWindow::onDelete);
171 ✔
402
  connect(ui->actionPush, &QAction::triggered, this, &MainWindow::onPush);
171 ✔
403
  connect(ui->actionUpdate, &QAction::triggered, this, &MainWindow::onUpdate);
171 ✔
404
  connect(ui->actionUsers, &QAction::triggered, this, &MainWindow::onUsers);
171 ✔
405
  connect(ui->actionConfig, &QAction::triggered, this, &MainWindow::onConfig);
171 ✔
406
  connect(ui->actionOtp, &QAction::triggered, this, &MainWindow::onOtp);
171 ✔
407

408
  // Menu-only. Quit ends the application, tray icon or not, as in KeePassXC,
409
  // Telegram and the KDE, GNOME and macOS guidelines (#1788). Close is
410
  // close(), a hide when "hide on close" is set, like the X button and Alt+F4.
411
  connect(ui->actionQuit, &QAction::triggered, qApp, &QApplication::quit);
171 ✔
412
  connect(ui->actionClose, &QAction::triggered, this, &MainWindow::close);
171 ✔
413
#ifdef Q_OS_MACOS
414
  // The menu bar is the system's up there; nothing to hide.
415
  ui->actionShowMenuBar->setVisible(false);
416
#else
417
  // The action lives in the menu it hides, so it has to be on the window as
418
  // well for Ctrl+M to keep working while the bar is gone.
419
  addAction(ui->actionShowMenuBar);
171 ✔
420
  ui->actionShowMenuBar->setChecked(QtPassSettings::load().showMenuBar);
171 ✔
421
  menuBar()->setVisible(ui->actionShowMenuBar->isChecked());
171 ✔
422
  connect(ui->actionShowMenuBar, &QAction::toggled, this, [this](bool show) {
171 ✔
423
    menuBar()->setVisible(show);
5 ✔
424
    AppSettings s = QtPassSettings::load();
5 ✔
425
    s.showMenuBar = show;
5 ✔
426
    QtPassSettings::save(s);
5 ✔
427
  });
5 ✔
428
  new MenuBarPeek(this, ui->actionShowMenuBar);
171 ✔
429
#endif
430
  connect(ui->actionFaq, &QAction::triggered, this, [] {
172 ✔
431
    QDesktopServices::openUrl(QUrl(QStringLiteral("https://qtpass.org/faq")));
2 ✔
432
  });
1 ✔
433
  connect(ui->actionAbout, &QAction::triggered, this, &MainWindow::showAbout);
171 ✔
434
  connect(ui->actionAboutQt, &QAction::triggered, qApp, &QApplication::aboutQt);
171 ✔
435

436
  ui->actionAddPassword->setIcon(
171 ✔
437
      QIcon::fromTheme("document-new", QIcon(":/icons/document-new.svg")));
684 ✔
438
  ui->actionAddFolder->setIcon(
171 ✔
439
      QIcon::fromTheme("folder-new", QIcon(":/icons/folder-new.svg")));
684 ✔
440
  ui->actionEdit->setIcon(QIcon::fromTheme(
171 ✔
441
      "document-properties", QIcon(":/icons/document-properties.svg")));
513 ✔
442
  ui->actionDelete->setIcon(
171 ✔
443
      QIcon::fromTheme("edit-delete", QIcon(":/icons/edit-delete.svg")));
684 ✔
444
  ui->actionPush->setIcon(
171 ✔
445
      QIcon::fromTheme("go-up", QIcon(":/icons/go-top.svg")));
684 ✔
446
  ui->actionUpdate->setIcon(
171 ✔
447
      QIcon::fromTheme("go-down", QIcon(":/icons/go-bottom.svg")));
684 ✔
448
  ui->actionUsers->setIcon(QIcon::fromTheme(
171 ✔
449
      "x-office-address-book", QIcon(":/icons/x-office-address-book.svg")));
513 ✔
450
  ui->actionConfig->setIcon(QIcon::fromTheme(
171 ✔
451
      "applications-system", QIcon(":/icons/applications-system.svg")));
342 ✔
452
}
171 ✔
453

454
void MainWindow::initStatusBar() {
171 ✔
455
  ui->statusBar->showMessage(tr("Welcome to QtPass %1").arg(VERSION), 2000);
342 ✔
456

457
  QPixmap logo = QPixmap::fromImage(QImage(":/artwork/icon.svg"))
342 ✔
458
                     .scaledToHeight(statusBar()->height());
171 ✔
459
  auto *logoApp = new QLabel(statusBar());
171 ✔
460
  logoApp->setPixmap(logo);
171 ✔
461
  statusBar()->addPermanentWidget(logoApp);
171 ✔
462
}
171 ✔
463

464
auto MainWindow::getCurrentTreeViewIndex() -> QModelIndex {
9 ✔
465
  return ui->treeView->currentIndex();
9 ✔
466
}
467

468
void MainWindow::flashText(const QString &text, const bool isError,
80 ✔
469
                           const bool isHtml) {
470
  if (isError) {
80 ✔
471
    ui->textBrowser->setTextColor(Qt::red);
9 ✔
472
  } else {
473
    // setText() re-applies the current char format, red after an error, to
474
    // the whole document. Clear the foreground rather than pin a palette
475
    // colour, so text follows runtime light/dark switches (#946).
476
    QTextCharFormat format = ui->textBrowser->currentCharFormat();
71 ✔
477
    format.clearForeground();
478
    ui->textBrowser->setCurrentCharFormat(format);
71 ✔
479
  }
480

481
  if (isHtml) {
80 ✔
482
    QString _text = text;
483
    if (!ui->textBrowser->toPlainText().isEmpty()) {
138 ✔
484
      _text = ui->textBrowser->toHtml() + _text;
38 ✔
485
    }
486
    ui->textBrowser->setHtml(_text);
69 ✔
487
  } else {
488
    ui->textBrowser->setText(text);
11 ✔
489
  }
490
}
80 ✔
491

492
void MainWindow::applyTextBrowserSettings() {
5 ✔
493
  const AppSettings s = QtPassSettings::load();
5 ✔
494
  if (s.useMonospace) {
5 ✔
495
    QFont monospace("Monospace");
1 ✔
496
    monospace.setStyleHint(QFont::Monospace);
1 ✔
497
    ui->textBrowser->setFont(monospace);
1 ✔
498
  } else {
1 ✔
499
    ui->textBrowser->setFont(QFont());
4 ✔
500
  }
501

502
  if (s.noLineWrapping) {
5 ✔
503
    ui->textBrowser->setLineWrapMode(QTextBrowser::NoWrap);
1 ✔
504
  } else {
505
    ui->textBrowser->setLineWrapMode(QTextBrowser::WidgetWidth);
4 ✔
506
  }
507
}
5 ✔
508

509
void MainWindow::applyWindowFlagsSettings() {
187 ✔
510
  const bool wantOnTop = QtPassSettings::isAlwaysOnTop();
187 ✔
511
  const Qt::WindowFlags flags = windowFlags();
512
  if (flags.testFlag(Qt::WindowStaysOnTopHint) == wantOnTop) {
187 ✔
513
    // setWindowFlags() rebuilds the native window, the teardown that left
514
    // ui->lineEdit dangling (see focusInput()); skip it when nothing changes.
515
    return;
516
  }
517
  // Toggle just this hint; resetting to Qt::Window discarded every other flag.
518
  const bool wasVisible = isVisible();
519
  setWindowFlags(wantOnTop ? (flags | Qt::WindowStaysOnTopHint)
4 ✔
520
                           : (flags & ~Qt::WindowStaysOnTopHint));
521
  // setWindowFlags() hides a shown window; a window that was not shown yet
522
  // (first-run wizard from the constructor) is left to its normal show.
523
  if (wasVisible) {
2 ✔
524
    show();
2 ✔
525
  }
526
}
527

528
auto MainWindow::config() -> bool {
7 ✔
529
  if (m_freshStart) {
7 ✔
530
    // No usable configuration yet: the wizard finds the programs, the key
531
    // and the store, and creates the store when it has to.
532
    FirstRunWizard wizard(this);
2 ✔
533
    if (wizard.exec() != QDialog::Accepted) {
2 ✔
534
      return false;
535
    }
536
  } else {
2 ✔
537
    ConfigDialog d(this);
5 ✔
538
    d.setModal(true);
5 ✔
539
    if (d.exec() != QDialog::Accepted) {
5 ✔
540
      return false;
541
    }
542
  }
5 ✔
543

544
  applyTextBrowserSettings();
5 ✔
545
  applyWindowFlagsSettings();
5 ✔
546

547
  updateProfileBox();
5 ✔
548
  const AppSettings s = QtPassSettings::load();
5 ✔
549
  // An open still waiting for the tree was asked of the old view; once
550
  // re-rooted, it would find that name in the new store. A profile switch
551
  // ends it by clearing the search text.
552
  delete m_pendingOpen;
5 ✔
553
  // A content search still running searched the old store, and its matches
554
  // would be listed for this one: onGrepFinished() cannot tell. Cancelled,
555
  // and content-search results on screen go with it (clearPanel()).
556
  cancelContentSearch();
5 ✔
557
  if (m_grep.cancelSearch()) {
558
    QApplication::restoreOverrideCursor();
1 ✔
559
  }
560
  clearPanel(false);
5 ✔
561
  m_tree->setStore(s.passStore);
5 ✔
562
  deselect();
5 ✔
563
  ui->treeView->setCurrentIndex(QModelIndex());
5 ✔
564

565
  Pass *activePass = QtPassSettings::getPass();
5 ✔
566
  activePass->updateEnv();
5 ✔
567
  m_tree->setPass(activePass);
5 ✔
568
  clearPanelTimer.setInterval(MS_PER_SECOND * s.autoclearPanelSeconds);
5 ✔
569
  m_qtPass->clipboard().setAutoclearTimer();
5 ✔
570

571
  updateGitButtonVisibility();
5 ✔
572
  updateOtpButtonVisibility();
5 ✔
573
  updateGrepButtonVisibility();
5 ✔
574
  updateProcessOutputVisibility();
5 ✔
575
#ifndef Q_OS_MACOS
576
  // The action's toggled handler shows or hides the bar (and saves again).
577
  ui->actionShowMenuBar->setChecked(s.showMenuBar);
5 ✔
578
#endif
579
  if (s.useTrayIcon && m_tray == nullptr) {
5 ✔
580
    initTrayIcon();
1 ✔
581
  } else if (!s.useTrayIcon && m_tray != nullptr) {
4 ✔
582
    destroyTrayIcon();
×
583
  }
584

585
  // Stay fresh-start while the configuration is unusable, so the
586
  // constructor's loop re-runs the wizard. The re-prompt lives there:
587
  // recursing here never reported a cancel back to the caller.
588
  if (Util::configIsValid(s)) {
5 ✔
589
    m_freshStart = false;
5 ✔
590
  }
591
  return true;
592
}
5 ✔
593

594
void MainWindow::onUpdate(bool block) {
2 ✔
595
  ui->statusBar->showMessage(tr("Updating password-store"), 2000);
2 ✔
596
  if (block) {
2 ✔
597
    QtPassSettings::getPass()->GitPull_b();
1 ✔
598
  } else {
599
    QtPassSettings::getPass()->GitPull();
1 ✔
600
  }
601
}
2 ✔
602

603
void MainWindow::onPush() {
1 ✔
604
  if (QtPassSettings::isUseGit()) {
1 ✔
605
    ui->statusBar->showMessage(tr("Updating password-store"), 2000);
1 ✔
606
    QtPassSettings::getPass()->GitPush();
1 ✔
607
  }
608
}
1 ✔
609

610
void MainWindow::onAutoPush() {
8 ✔
611
  if (QtPassSettings::isUseGit()) {
8 ✔
612
    ui->statusBar->showMessage(tr("Updating password-store"), 2000);
8 ✔
613
    QtPassSettings::getPass()->GitPushAutomatic();
8 ✔
614
  }
615
}
8 ✔
616

617
auto MainWindow::getFile(const QModelIndex &index, bool forPass) -> QString {
62 ✔
618
  return m_tree->fileFor(index, forPass);
62 ✔
619
}
620

621
void MainWindow::on_treeView_clicked(const QModelIndex &index) {
24 ✔
622
  bool cleared = ui->treeView->currentIndex().flags() == Qt::NoItemFlags;
24 ✔
623
  QString file = getFile(index, true);
24 ✔
624
  ui->passwordName->setText(file);
24 ✔
625
  if (!file.isEmpty() && !cleared) {
24 ✔
626
    // Remember what the panel is about to show, so onOtp() can tell whether the
627
    // code it can see belongs to the entry that is currently selected.
628
    m_shownFile = file;
23 ✔
629
    QtPassSettings::getPass()->Show(file);
46 ✔
630
  } else {
631
    m_shownFile.clear();
1 ✔
632
    clearPanel(false);
1 ✔
633
    ui->actionEdit->setEnabled(false);
1 ✔
634
    ui->actionDelete->setEnabled(true);
1 ✔
635
  }
636
}
24 ✔
637

638
void MainWindow::on_treeView_doubleClicked(const QModelIndex &index) {
4 ✔
639
  QFileInfo fileOrFolder = m_tree->fileInfo(ui->treeView->currentIndex());
4 ✔
640

641
  if (fileOrFolder.isFile()) {
4 ✔
642
    editPassword(getFile(index, true));
6 ✔
643
  }
644
}
4 ✔
645

646
void MainWindow::deselect() {
18 ✔
647
  m_shownFile.clear();
18 ✔
648
  cancelOtpRequest();
18 ✔
649
  m_qtPass->clipboard().clear();
18 ✔
650
  ui->treeView->clearSelection();
18 ✔
651
  ui->actionEdit->setEnabled(false);
18 ✔
652
  ui->actionDelete->setEnabled(false);
18 ✔
653
  ui->passwordName->setText("");
18 ✔
654
  clearPanel(false);
18 ✔
655
}
18 ✔
656

657
void MainWindow::executeWrapperStarted() {
62 ✔
658
  m_displayPanel->clear();
62 ✔
659
  ui->textBrowser->clear();
62 ✔
660
  setUiElementsEnabled(false);
62 ✔
661
  clearPanelTimer.stop();
62 ✔
662
  if (QtPassSettings::isShowProcessOutput()) {
62 ✔
663
    m_processOutput->setVisible(true);
57 ✔
664
  }
665
}
62 ✔
666

667
void MainWindow::passShowHandler(const QString &p_output, const QString &file) {
36 ✔
668
  // Only the entry we most recently asked to show may repaint the panel; a
669
  // slower decrypt of an entry the user has since left is dropped, and so is
670
  // one that arrives after the selection was cleared (deselect, a profile
671
  // switch): nothing is asked to be shown then.
672
  if (!file.isEmpty() && file != m_shownFile) {
36 ✔
673
    // A newer show is pending and releases the interface when it lands;
674
    // with none (the selection was cleared) nothing else would until the
675
    // watchdog. setUiElementsEnabled() keeps a re-encryption's lock.
676
    if (m_shownFile.isEmpty()) {
9 ✔
677
      setUiElementsEnabled(true);
7 ✔
678
    }
679
    return;
9 ✔
680
  }
681
  const AppSettings s = QtPassSettings::load();
27 ✔
682
  // What a template marks secret, in the settings or the store's
683
  // .templates; read per entry shown, so an edit there counts at once.
684
  if (s.hidePassword) {
27 ✔
685
    m_displayPanel->setMarkedSecrets(
3 ✔
686
        TemplateIO::secretFieldsIn(s.passTemplate) +
6 ✔
687
        TemplateIO::readSecretFields(s.passStore));
9 ✔
688
  }
689
  QStringList templ =
690
      s.useTemplate ? TemplateIO::fieldsIn(s.passTemplate) : QStringList();
27 ✔
691
  bool allFields = s.useTemplate && s.templateAllFields;
27 ✔
692
  // A secret the panel hides is a field even when the template doesn't list
693
  // it: left in the text below the fields, it would show in plain view.
694
  FileContent fileContent = FileContent::parse(
695
      p_output, templ, allFields, [this, &s](const QString &name) {
27 ✔
696
        return m_displayPanel->isSecret(name, s);
17 ✔
697
      });
27 ✔
698
  QString output = p_output;
699
  // Display variant: empty when the password line is itself an otpauth URI, so
700
  // the shared secret is neither rendered nor copied to the clipboard.
701
  QString password = fileContent.getPasswordForDisplay();
27 ✔
702

703
  // Skipped for an OTP request: the user asked for a code, and two
704
  // OleSetClipboard calls in one turn can leave the Windows clipboard empty.
705
  if (m_otpRequestFile.isEmpty() || m_otpRequestFile != file) {
27 ✔
706
    m_qtPass->clipboard().copyIfAlways(password, p_output);
25 ✔
707
  }
708

709
  m_displayPanel->clear();
27 ✔
710

711
  if (s.hideContent) {
27 ✔
712
    output = "***" + tr("Content hidden") + "***";
4 ✔
713
  } else if (s.displayAsIs) {
25 ✔
714
    // As it is, but not a block per line of millions.
715
    output = FileContent::boundedForDisplay(p_output);
2 ✔
716
  } else {
717
    m_displayPanel->displayFields(password, fileContent.getNamedValues(), s,
48 ✔
718
                                  s.useOtp ? fileContent.getOtpUri()
24 ✔
719
                                           : QString());
720
    output = fileContent.getRemainingDataForDisplay();
48 ✔
721
  }
722

723
  if (s.useAutoclearPanel) {
27 ✔
724
    clearPanelTimer.start();
2 ✔
725
  }
726

727
  flashText(QtPass::formatOutput(output), false, true);
54 ✔
728
  setUiElementsEnabled(true);
27 ✔
729
}
54 ✔
730

731
void MainWindow::otpFromFileToClipboard(const QString &p_output,
26 ✔
732
                                        const QString &file) {
733
  // Permanently connected: only the decrypt of the entry onOtp() asked for
734
  // is ours, everything else belongs to a tree click or a Ctrl+C.
735
  if (m_otpRequestFile.isEmpty() || file != m_otpRequestFile) {
26 ✔
736
    return;
23 ✔
737
  }
738
  m_otpRequestFile.clear();
5 ✔
739

740
  if (p_output.isEmpty()) {
5 ✔
741
    // Distinguish "could not read the entry" from "entry has no OTP".
742
    flashText(tr("Could not decrypt this password entry"), true);
1 ✔
743
    setUiElementsEnabled(true);
1 ✔
744
    return;
1 ✔
745
  }
746

747
  // passShowHandler ran first for this finishedShow; if it rendered the OTP
748
  // row, reuse its code (as onOtp()'s fast path does). Otherwise parse:
749
  // hideContent, displayAsIs or no OTP field.
750
  const QString shown = m_displayPanel->currentOtpCode();
4 ✔
751
  if (!shown.isEmpty()) {
4 ✔
752
    m_qtPass->clipboard().copyText(shown);
1 ✔
753
    showStatusMessage(tr("OTP code copied to clipboard"));
1 ✔
754
    setUiElementsEnabled(true);
1 ✔
755
    return;
756
  }
757

758
  const AppSettings s = QtPassSettings::load();
3 ✔
759
  // Parse with the same template settings passShowHandler uses, so an OTP
760
  // field is recognised identically in both paths.
761
  const QStringList templ =
762
      s.useTemplate ? TemplateIO::fieldsIn(s.passTemplate) : QStringList();
3 ✔
763
  const bool allFields = s.useTemplate && s.templateAllFields;
3 ✔
764
  const FileContent fileContent =
765
      FileContent::parse(p_output, templ, allFields);
3 ✔
766

767
  const std::optional<Totp::Settings> settings =
768
      Totp::parse(fileContent.getOtpUri());
6 ✔
769
  if (settings.has_value()) {
3 ✔
770
    m_qtPass->clipboard().copyText(Totp::generateNow(*settings));
4 ✔
771
    showStatusMessage(tr("OTP code copied to clipboard"));
4 ✔
772
  } else {
773
    flashText(tr("No OTP code found in this password entry"), true);
2 ✔
774
  }
775
  setUiElementsEnabled(true);
3 ✔
776
}
6 ✔
777

778
void MainWindow::clearPanel(bool notify) {
60 ✔
779
  m_displayPanel->clear();
60 ✔
780
  const bool grepWasVisible = ui->grepResultsList->isVisible();
60 ✔
781
  ui->grepResultsList->clear();
60 ✔
782
  if (grepWasVisible) {
60 ✔
783
    showContentResults(false);
5 ✔
784
    if (m_grep.inGrepMode()) {
5 ✔
785
      // Left as the button leaves it: a search still running would otherwise
786
      // hand its partial matches to a content search entered meanwhile.
787
      cancelContentSearch();
5 ✔
788
      if (m_grep.leaveGrepMode()) {
789
        QApplication::restoreOverrideCursor();
2 ✔
790
      }
791
      ui->grepButton->blockSignals(true);
5 ✔
792
      ui->grepButton->setChecked(false);
5 ✔
793
      ui->grepButton->blockSignals(false);
5 ✔
794
      ui->lineEdit->blockSignals(true);
5 ✔
795
      ui->lineEdit->clear();
5 ✔
796
      ui->lineEdit->blockSignals(false);
5 ✔
797
      ui->lineEdit->setPlaceholderText(tr("Search password"));
10 ✔
798
    }
799
  }
800
  if (notify) {
60 ✔
801
    QString output = "***" + tr("Password and content hidden") + "***";
4 ✔
802
    ui->textBrowser->setHtml(output);
2 ✔
803
  } else {
804
    ui->textBrowser->setHtml("");
116 ✔
805
  }
806
}
60 ✔
807

808
void MainWindow::setUiElementsEnabled(bool state) {
392 ✔
809
  // A running re-encryption owns the UI state: the progress dialog's Cancel is
810
  // the user's escape hatch and endReencryptPath() releases the interface, so
811
  // neither an unrelated completion nor the watchdog may re-enable it early.
812
  if (state && m_reencryptRunning) {
392 ✔
813
    m_uiWatchdog.stop();
1 ✔
814
    return;
1 ✔
815
  }
816
  // Arm the watchdog while the UI is disabled; disarm once re-enabled.
817
  if (state) {
818
    m_uiWatchdog.stop();
307 ✔
819
  } else {
820
    m_uiWatchdog.start();
84 ✔
821
  }
822
  ui->treeView->setEnabled(state);
391 ✔
823
  ui->lineEdit->setEnabled(state);
391 ✔
824
  ui->actionAddPassword->setEnabled(state);
391 ✔
825
  ui->actionAddFolder->setEnabled(state);
391 ✔
826
  ui->actionUsers->setEnabled(state);
391 ✔
827
  ui->actionConfig->setEnabled(state);
391 ✔
828
  m_uiEnabled = state;
391 ✔
829
  updateProfileBoxEnabled();
391 ✔
830
  const bool uiEnabled = state;
831
  // is a file selected, and in sight (content search results hide the tree)?
832
  state &= ui->treeView->currentIndex().isValid() && !ui->treeView->isHidden();
785 ✔
833
  ui->actionDelete->setEnabled(state);
391 ✔
834
  ui->actionEdit->setEnabled(state);
391 ✔
835
  updateGitButtonVisibility(uiEnabled);
391 ✔
836
  // `state` is now "UI enabled AND a file is selected", which is exactly when
837
  // generating an OTP makes sense.
838
  updateOtpButtonVisibility(state);
391 ✔
839
}
840

841
void MainWindow::restoreWindow() {
182 ✔
842
  // saveGeometry() covers position, size, maximized state and screen;
843
  // anything applied on top discards it. Centre only when nothing was saved.
844
  const QByteArray geometry = QtPassSettings::getGeometry();
364 ✔
845
  if (geometry.isEmpty() || !restoreGeometry(geometry)) {
182 ✔
846
    WindowStateStore::centreOnCursorScreen(*this);
4 ✔
847
  }
848
  restoreState(QtPassSettings::getSavestate(saveState()));
182 ✔
849
  const AppSettings s = QtPassSettings::load();
182 ✔
850

851
  applyWindowFlagsSettings();
182 ✔
852

853
  if (s.useTrayIcon && m_tray == nullptr) {
182 ✔
854
    initTrayIcon();
2 ✔
855
    // Minimized to the tray only when there is one: without a system tray
856
    // initTrayIcon() gave up, and a hidden window could not be brought back.
857
    if (s.startMinimized && m_tray != nullptr) {
2 ✔
858
      // since we are still in constructor, can't directly hide
859
      QTimer::singleShot(10, this, &MainWindow::hide);
×
860
    }
861
  } else if (!s.useTrayIcon && m_tray != nullptr) {
180 ✔
862
    destroyTrayIcon();
×
863
  }
864
}
364 ✔
865

866
void MainWindow::onConfig() { config(); }
1 ✔
867

868
void MainWindow::showAbout() {
1 ✔
869
  QMessageBox::about(
1 ✔
870
      this, tr("About QtPass"),
1 ✔
871
      tr("<h3>QtPass %1</h3>"
1 ✔
872
         "<p>A multi-platform GUI for <a "
873
         "href=\"https://www.passwordstore.org/\">"
874
         "pass</a>, the standard Unix password manager.</p>"
875
         "<p><a href=\"https://qtpass.org/\">qtpass.org</a> &middot; "
876
         "<a href=\"https://github.com/IJHack/QtPass\">Source and "
877
         "issues</a></p>"
878
         "<p>Copyright &copy; 2014&ndash;%2 IJhack. Licensed under the "
879
         "<a href=\"https://www.gnu.org/licenses/gpl-3.0.html\">GNU GPL "
880
         "version 3</a> or later.</p>")
881
          .arg(QStringLiteral(VERSION),
2 ✔
882
               QString::number(QDate::currentDate().year())));
2 ✔
883
}
1 ✔
884

885
void MainWindow::on_lineEdit_textChanged(const QString &arg1) {
45 ✔
886
  if (m_grep.inGrepMode())
45 ✔
887
    return;
888
  ui->statusBar->showMessage(tr("Looking for: %1").arg(arg1), 1000);
64 ✔
889
  ui->treeView->expandAll();
32 ✔
890
  // Drop any decrypt still pending for the entry that was shown: otherwise it
891
  // keeps its right to the panel and, with "Always copy", the clipboard, and
892
  // when it lands late it shows that entry's password under the new heading.
893
  m_shownFile.clear();
32 ✔
894
  cancelOtpRequest();
32 ✔
895
  clearPanel(false);
32 ✔
896
  ui->passwordName->setText("");
64 ✔
897
  ui->actionEdit->setEnabled(false);
32 ✔
898
  ui->actionDelete->setEnabled(false);
32 ✔
899
  searchTimer.start();
32 ✔
900
}
901

902
void MainWindow::onTimeoutSearch() {
36 ✔
903
  // The tree matches slash-separated paths: on Windows, team\bank typed is
904
  // team/bank, as exactMatchPath() reads it too.
905
  QString query = QDir::fromNativeSeparators(ui->lineEdit->text());
72 ✔
906

907
  if (query.isEmpty()) {
36 ✔
908
    ui->treeView->collapseAll();
1 ✔
909
    deselect();
1 ✔
910
  }
911

912
  // The words are matched literally, in order, with anything in between:
913
  // "work vpn" finds work/acme/vpn. Regular expressions belong to the
914
  // content search; here a typed "[" or "(" must not switch filtering off.
915
  QStringList words;
36 ✔
916
  for (const QString &word :
917
       query.split(QLatin1Char(' '), Qt::SkipEmptyParts)) {
108 ✔
918
    words << QRegularExpression::escape(word);
36 ✔
919
  }
920
  QRegularExpression regExp(words.join(QStringLiteral(".*")),
72 ✔
921
                            QRegularExpression::CaseInsensitiveOption);
36 ✔
922
  m_tree->setFilter(regExp);
36 ✔
923

924
  if (m_tree->proxy().rowCount() > 0 && !query.isEmpty()) {
36 ✔
925
    selectFirstFile();
26 ✔
926
  } else {
927
    ui->actionEdit->setEnabled(false);
10 ✔
928
    ui->actionDelete->setEnabled(false);
10 ✔
929
  }
930
}
72 ✔
931

932
void MainWindow::on_lineEdit_returnPressed() {
17 ✔
933
  qCDebug(lcQtPass) << "on_lineEdit_returnPressed"
17 ✔
934
                    << m_tree->proxy().rowCount();
×
935

936
  if (m_grep.inGrepMode()) {
17 ✔
937
    const QString query = ui->lineEdit->text();
12 ✔
938
    if (!query.isEmpty()) {
12 ✔
939
      ui->grepResultsList->clear();
9 ✔
940
      ui->statusBar->showMessage(tr("Searching…"));
18 ✔
941
      if (m_grep.beginSearch()) {
942
        QApplication::setOverrideCursor(Qt::WaitCursor);
9 ✔
943
      }
944
      QtPassSettings::getPass()->Grep(query, ui->grepCaseButton->isChecked());
18 ✔
945
    } else {
946
      cancelContentSearch();
3 ✔
947
      if (m_grep.cancelSearch()) {
948
        QApplication::restoreOverrideCursor();
2 ✔
949
      }
950
      ui->grepResultsList->clear();
3 ✔
951
      showContentResults(false);
3 ✔
952
    }
953
    return;
954
  }
955

956
  // Return within the search delay acts on the text as typed, not on the
957
  // tree as the previous text filtered it.
958
  if (searchTimer.isActive()) {
5 ✔
959
    searchTimer.stop();
5 ✔
960
    onTimeoutSearch();
5 ✔
961
  }
962
  if (m_tree->proxy().rowCount() > 0) {
5 ✔
963
    selectFirstFile();
5 ✔
964
    on_treeView_clicked(ui->treeView->currentIndex());
5 ✔
965
  }
966
}
967

968
void MainWindow::on_grepButton_toggled(bool checked) {
29 ✔
969
  const AppSettings s = QtPassSettings::load();
29 ✔
970
  if (checked) {
29 ✔
971
    m_grep.enterGrepMode();
972
    ui->lineEdit->setPlaceholderText(tr("Search content (regex)"));
36 ✔
973
    // Both backends search through NativeGrep (QRegularExpression), so one
974
    // dialect: PCRE.
975
    ui->lineEdit->setToolTip(
18 ✔
976
        tr("Content search uses Perl-compatible regular expressions (PCRE)."));
18 ✔
977
    ui->lineEdit->clear();
18 ✔
978
    searchTimer.stop();
18 ✔
979
    m_tree->setFilter(QRegularExpression());
18 ✔
980
    ui->grepResultsList->setVisible(false);
18 ✔
981
    // Keep treeView visible until results arrive
982
  } else {
983
    cancelContentSearch();
11 ✔
984
    if (m_grep.leaveGrepMode()) {
985
      QApplication::restoreOverrideCursor();
2 ✔
986
    }
987
    searchTimer.stop();
11 ✔
988
    ui->lineEdit->blockSignals(true);
11 ✔
989
    ui->lineEdit->clear();
11 ✔
990
    ui->lineEdit->blockSignals(false);
11 ✔
991
    ui->lineEdit->setPlaceholderText(tr("Search password"));
22 ✔
992
    ui->lineEdit->setToolTip(QString());
22 ✔
993
    ui->grepResultsList->clear();
11 ✔
994
    showContentResults(false);
11 ✔
995
    m_tree->setFilter(QRegularExpression());
11 ✔
996
  }
997
}
29 ✔
998

999
void MainWindow::onGrepFinished(
17 ✔
1000
    const QList<QPair<QString, QStringList>> &results) {
1001
  // Both backends stay connected, each with its own search: a search the
1002
  // other backend was still running when Settings switched backends is not
1003
  // this one, whatever the controller's state, and searched another store.
1004
  // Dropped before it can end (or be taken for) the current search.
1005
  if (const QObject *from = sender();
17 ✔
1006
      from != nullptr && from != QtPassSettings::getPass()) {
17 ✔
1007
    return;
11 ✔
1008
  }
1009
  const GrepSearchController::FinishOutcome outcome = m_grep.finishSearch();
1010
  if (outcome.restoreCursor) {
16 ✔
1011
    QApplication::restoreOverrideCursor();
2 ✔
1012
  }
1013
  // Re-enable the UI before the discard check so a cancelled search can never
1014
  // leave controls disabled.
1015
  setUiElementsEnabled(true);
16 ✔
1016
  if (outcome.discard) {
16 ✔
1017
    return;
1018
  }
1019
  if (!m_grep.inGrepMode())
8 ✔
1020
    return;
1021
  ui->grepResultsList->clear();
8 ✔
1022
  if (results.isEmpty()) {
8 ✔
1023
    ui->statusBar->showMessage(tr("No matches found."), 3000);
2 ✔
1024
    showContentResults(false);
2 ✔
1025
    return;
2 ✔
1026
  }
1027
  const AppSettings s = QtPassSettings::load();
6 ✔
1028
  const bool hideContent = s.hideContent;
6 ✔
1029
  int totalLines = 0;
1030
  int entries = 0;
1031
  bool stopped = false;
1032
  for (const auto &pair : results) {
33 ✔
1033
    if (NativeGrep::isStoppedMarker(pair)) {
27 ✔
1034
      stopped = true;
1035
      continue;
×
1036
    }
1037
    ++entries;
27 ✔
1038
    auto *entryItem = new QTreeWidgetItem(ui->grepResultsList);
27 ✔
1039
    entryItem->setText(0, pair.first);
27 ✔
1040
    entryItem->setData(0, Qt::UserRole, pair.first);
27 ✔
1041
    for (const QString &line : pair.second) {
54 ✔
1042
      auto *lineItem = new QTreeWidgetItem(entryItem);
27 ✔
1043
      // The marker is no content: shown as it is with hidden content too,
1044
      // and not counted as a match.
1045
      if (NativeGrep::isMoreMarker(line)) {
27 ✔
1046
        lineItem->setText(0, tr("… more matches in this entry"));
×
1047
      } else {
1048
        lineItem->setText(0, hideContent ? "***" + tr("Content hidden") + "***"
81 ✔
1049
                                         : line);
1050
        ++totalLines;
27 ✔
1051
      }
1052
      lineItem->setData(0, Qt::UserRole, pair.first);
27 ✔
1053
    }
1054
  }
1055
  ui->grepResultsList->expandAll();
6 ✔
1056
  showContentResults(true);
6 ✔
1057
  if (stopped) {
6 ✔
1058
    // The search stopped there; more entries may match.
1059
    ui->statusBar->showMessage(
×
1060
        tr("Showing the first %n match(es); search for something narrower "
×
1061
           "to see the rest.",
1062
           nullptr, totalLines),
1063
        10000);
1064
  } else {
1065
    ui->statusBar->showMessage(tr("Found %n match(es)", nullptr, totalLines) +
18 ✔
1066
                                   " " +
6 ✔
1067
                                   tr("in %n entr(ies).", nullptr, entries),
12 ✔
1068
                               3000);
1069
  }
1070
  if (s.useAutoclearPanel)
6 ✔
1071
    clearPanelTimer.start();
1 ✔
1072
}
6 ✔
1073

1074
void MainWindow::on_grepResultsList_itemClicked(QTreeWidgetItem *item,
2 ✔
1075
                                                int /*column*/) {
1076
  const AppSettings s = QtPassSettings::load();
2 ✔
1077
  const QString entry = item->data(0, Qt::UserRole).toString();
2 ✔
1078
  if (entry.isEmpty())
2 ✔
1079
    return;
1080
  const QString fullPath =
1081
      QDir::cleanPath(QDir(s.passStore).filePath(entry + ".gpg"));
4 ✔
1082
  const QModelIndex proxyIndex = m_tree->indexFor(fullPath);
2 ✔
1083
  if (!proxyIndex.isValid())
1084
    return;
1085
  ui->treeView->setCurrentIndex(proxyIndex);
2 ✔
1086
  on_treeView_clicked(proxyIndex);
2 ✔
1087
  if (s.hideContent || s.useAutoclearPanel)
2 ✔
1088
    ui->grepResultsList->clear();
1 ✔
1089
  showContentResults(false);
2 ✔
1090
  ui->treeView->scrollTo(proxyIndex);
2 ✔
1091
  ui->treeView->setFocus();
2 ✔
1092
}
2 ✔
1093

1094
void MainWindow::showContentResults(bool shown) {
29 ✔
1095
  ui->grepResultsList->setVisible(shown);
29 ✔
1096
  ui->treeView->setVisible(!shown);
29 ✔
1097
  if (shown) {
29 ✔
1098
    // The tree's current entry is out of sight: Delete, Edit and OTP would
1099
    // act on it, not on a result. Opening a result shows the tree again.
1100
    ui->actionDelete->setEnabled(false);
6 ✔
1101
    ui->actionEdit->setEnabled(false);
6 ✔
1102
    updateOtpButtonVisibility(false);
6 ✔
1103
  } else if (ui->treeView->selectionModel()->hasSelection()) {
23 ✔
1104
    // Only for an entry still selected: deselect() clears the selection but
1105
    // keeps the current index, which would turn Edit and Delete back on.
1106
    setUiElementsEnabled(m_uiEnabled);
8 ✔
1107
  }
1108
}
29 ✔
1109

1110
void MainWindow::cancelContentSearch() {
24 ✔
1111
  QtPassSettings::getRealPass()->CancelGrep();
24 ✔
1112
  QtPassSettings::getImitatePass()->CancelGrep();
24 ✔
1113
}
24 ✔
1114

1115
void MainWindow::selectFirstFile() {
31 ✔
1116
  // The entry named exactly as typed wins: with folders sorted first, the
1117
  // depth-first walk found team/bank before bank.
1118
  QModelIndex index = exactMatch();
31 ✔
1119
  if (!index.isValid()) {
1120
    index = firstFile(m_tree->rootIndex());
15 ✔
1121
  }
1122
  ui->treeView->setCurrentIndex(index);
31 ✔
1123
}
31 ✔
1124

1125
namespace {
1126
/**
1127
 * @brief @p path with each part below @p store spelled as stored on disk.
1128
 *
1129
 * Where the file system ignores case, "Bank.gpg" exists while the file is
1130
 * bank.gpg, and the tree knows the entry only by that spelling.
1131
 * @param store The store folder.
1132
 * @param path An existing file in the store.
1133
 * @return @p path itself when every part is spelled as stored, otherwise
1134
 *         the path with the stored spelling.
1135
 */
1136
auto spelledAsStored(const QString &store, const QString &path) -> QString {
28 ✔
1137
  const QStringList parts = QDir(store).relativeFilePath(path).split(
56 ✔
1138
      QLatin1Char('/'), Qt::SkipEmptyParts);
28 ✔
1139
  QDir dir(store);
28 ✔
1140
  bool respelled = false;
1141
  for (int i = 0; i < parts.size(); ++i) {
31 ✔
1142
    const bool leaf = i == parts.size() - 1;
31 ✔
1143
    const QStringList names =
1144
        dir.entryList((leaf ? QDir::Files : QDir::Dirs) | QDir::Hidden |
31 ✔
1145
                      QDir::NoDotAndDotDot);
34 ✔
1146
    QString name = parts.at(i);
1147
    if (!names.contains(name)) {
31 ✔
1148
      const auto stored = std::find_if(
×
1149
          names.cbegin(), names.cend(), [&name](const QString &candidate) {
1150
            return candidate.compare(name, Qt::CaseInsensitive) == 0;
×
1151
          });
1152
      if (stored == names.cend()) {
×
1153
        return path;
1154
      }
1155
      name = *stored;
×
1156
      respelled = true;
1157
    }
1158
    if (leaf) {
31 ✔
1159
      return respelled ? QDir::cleanPath(dir.filePath(name)) : path;
56 ✔
1160
    }
1161
    if (!dir.cd(name)) {
3 ✔
1162
      return path;
1163
    }
1164
  }
1165
  return path;
1166
}
28 ✔
1167
} // namespace
1168

1169
auto MainWindow::exactMatchPath() -> QString {
45 ✔
1170
  const QString text = QDir::fromNativeSeparators(ui->lineEdit->text());
90 ✔
1171
  const QString store = QtPassSettings::getPassStore();
90 ✔
1172
  // A name may begin or end with a space: " bank" is that entry, not bank.
1173
  // Only when no entry is named so are spaces around the text dropped.
1174
  for (const QString &typed : {text, text.trimmed()}) {
171 ✔
1175
    if (typed.isEmpty()) {
64 ✔
1176
      continue;
×
1177
    }
1178
    const QString path =
1179
        QDir::cleanPath(QDir(store).filePath(typed + QStringLiteral(".gpg")));
128 ✔
1180
    if (PathValidator::isPathInStore(store, path) && QFileInfo(path).isFile()) {
64 ✔
1181
      return spelledAsStored(store, path);
28 ✔
1182
    }
1183
  }
135 ✔
1184
  return {};
17 ✔
1185
}
1186

1187
auto MainWindow::exactMatch() -> QModelIndex {
43 ✔
1188
  const QString path = exactMatchPath();
43 ✔
1189
  if (path.isEmpty()) {
43 ✔
1190
    return {};
16 ✔
1191
  }
1192
  // indexFor() maps through the filter: a row the filter hides is no match.
1193
  const QModelIndex index = m_tree->indexFor(path);
27 ✔
1194
  if (!index.isValid() || !m_tree->fileInfo(index).isFile()) {
49 ✔
1195
    return {};
5 ✔
1196
  }
1197
  return index;
22 ✔
1198
}
1199

1200
void MainWindow::applySearchText(const QString &text) {
8 ✔
1201
  // A name search: content search, left on, kept its results over the tree
1202
  // and ignored the text.
1203
  if (ui->grepButton->isChecked()) {
8 ✔
1204
    ui->grepButton->setChecked(false);
1 ✔
1205
  }
1206
  delete m_pendingOpen;
8 ✔
1207
  ui->lineEdit->setText(text);
8 ✔
1208
  // Filter now, not after the search delay: the timer would leave the tree
1209
  // as the previous text filtered it.
1210
  searchTimer.stop();
8 ✔
1211
  onTimeoutSearch();
8 ✔
1212
  if (const QModelIndex exact = exactMatch(); exact.isValid()) {
8 ✔
1213
    openExactMatch(exact);
6 ✔
1214
    return;
6 ✔
1215
  }
1216
  // The tree loads folders in the background: at start, or right after the
1217
  // window is shown again, an entry that exists may not be in it yet. Try
1218
  // again as folders finish loading, for a few seconds, unless the search
1219
  // text changes meanwhile: any change ends the wait, even one typed back to
1220
  // this text, which is a new search that has not asked to open anything.
1221
  if (exactMatchPath().isEmpty()) {
4 ✔
1222
    return;
1223
  }
1224
  auto *pending = new QObject(this);
1 ✔
1225
  m_pendingOpen = pending;
1226
  QTimer::singleShot(5000, pending, &QObject::deleteLater);
1 ✔
1227
  // Disconnected at once: with deleteLater() alone, a folder that finished
1228
  // loading before the deletion still ran the open, or ran it twice.
UNCOV
1229
  const auto stop = [this, pending] {
×
UNCOV
1230
    disconnect(&m_tree->fileSystem(), nullptr, pending, nullptr);
×
UNCOV
1231
    disconnect(ui->lineEdit, nullptr, pending, nullptr);
×
UNCOV
1232
    pending->deleteLater();
×
1233
  };
1 ✔
1234
  connect(ui->lineEdit, &QLineEdit::textChanged, pending, stop);
1 ✔
1235
  connect(&m_tree->fileSystem(), &QFileSystemModel::directoryLoaded, pending,
1 ✔
1236
          [this, stop](const QString &) {
2 ✔
1237
            searchTimer.stop();
4 ✔
1238
            onTimeoutSearch();
4 ✔
1239
            if (const QModelIndex exact = exactMatch(); exact.isValid()) {
4 ✔
UNCOV
1240
              stop();
×
UNCOV
1241
              openExactMatch(exact);
×
1242
            }
1243
          });
4 ✔
1244
}
1245

1246
void MainWindow::openExactMatch(const QModelIndex &index) {
6 ✔
1247
  // Made current here, not left to the filter pass before: the tree may have
1248
  // moved its current row since, and with none on_treeView_clicked() only
1249
  // names the entry without decrypting it.
1250
  ui->treeView->setCurrentIndex(index);
6 ✔
1251
  on_treeView_clicked(index);
6 ✔
1252
}
6 ✔
1253

1254
auto MainWindow::firstFile(QModelIndex parentIndex) -> QModelIndex {
23 ✔
1255
  StoreModel &proxy = m_tree->proxy();
23 ✔
1256
  int numRows = proxy.rowCount(parentIndex);
23 ✔
1257
  for (int row = 0; row < numRows; ++row) {
30 ✔
1258
    QModelIndex index = proxy.index(row, 0, parentIndex);
20 ✔
1259
    if (m_tree->fileInfo(index).isFile()) {
20 ✔
1260
      return index;
13 ✔
1261
    }
1262
    if (proxy.hasChildren(index)) {
12 ✔
1263
      QModelIndex childFile = firstFile(index);
8 ✔
1264
      if (childFile.isValid())
1265
        return childFile;
5 ✔
1266
    }
1267
  }
1268
  return QModelIndex();
10 ✔
1269
}
1270

1271
// Guards the input dialogs (create, move, rename) against names like
1272
// "../../etc/passwd" or absolute paths escaping the store root.
1273
auto MainWindow::confirmPathInStore(const QString &candidate) -> bool {
11 ✔
1274
  if (PathValidator::isPathInStore(QtPassSettings::getPassStore(), candidate)) {
22 ✔
1275
    return true;
1276
  }
1277
  QMessageBox::warning(this, tr("Invalid name"),
9 ✔
1278
                       tr("That name would resolve outside the password "
3 ✔
1279
                          "store. Please choose a different name."));
1280
  return false;
3 ✔
1281
}
1282

1283
void MainWindow::setPassword(const QString &file, bool isNew) {
6 ✔
1284
  const AppSettings s = QtPassSettings::load();
6 ✔
1285
  PasswordDialog d(QtPassSettings::getPass(), s, file, isNew, this);
6 ✔
1286
  // A copy out of the editor is autocleared like one from the display.
1287
  connect(&d, &PasswordDialog::copied, &m_qtPass->clipboard(),
6 ✔
1288
          &ClipboardManager::trackCopied);
6 ✔
1289

1290
  if (isNew) {
6 ✔
1291
    const QString storePath = s.passStore;
1292
    QString folder = m_tree->currentDir(false);
1 ✔
1293
    if (folder.isEmpty()) {
1 ✔
1294
      folder = storePath;
×
1295
    }
1296
    // Folders to pick from, the tree's current one preselected. Real folders
1297
    // only: a linked or junctioned one would write the entry outside the store.
1298
    QStringList folders{QString()};
2 ✔
1299
    const QStringList found = Util::directoriesUnder(storePath);
1 ✔
1300
    for (const QString &path : found) {
16 ✔
1301
      const QString rel = QDir(storePath).relativeFilePath(path);
15 ✔
1302
      if (!rel.startsWith(u'.') && !rel.contains(QStringLiteral("/."))) {
45 ✔
1303
        folders << rel;
1304
      }
1305
    }
1306
    std::sort(folders.begin() + 1, folders.end());
1 ✔
1307
    d.setNewEntryLocation(storePath, folders,
1 ✔
1308
                          QDir(storePath).relativeFilePath(folder));
2 ✔
1309
    QHash<QString, QStringList> templates =
1310
        TemplateIO::readTemplates(storePath);
1 ✔
1311
    if (!templates.isEmpty()) {
1312
      QString defaultTemplate =
1313
          TemplateIO::getFolderTemplate(folder, storePath);
1 ✔
1314
      d.setAvailableTemplates(templates, defaultTemplate);
1 ✔
1315
    }
1316
  }
1 ✔
1317

1318
  if (!d.exec()) {
6 ✔
1319
    ui->treeView->setFocus();
5 ✔
1320
  }
1321
}
6 ✔
1322

1323
void MainWindow::addPassword() { setPassword(QString()); }
2 ✔
1324

1325
auto MainWindow::confirmDeletion(const QString &file, bool isDir) -> bool {
4 ✔
1326
  const QString path = QDir::separator() + file;
4 ✔
1327
  if (!isDir) {
4 ✔
1328
    return PlainMessageBox::askYes(
2 ✔
1329
        this, tr("Delete password?"),
2 ✔
1330
        tr("Are you sure you want to delete %1?").arg(path));
2 ✔
1331
  }
1332
  // Whole sentences, not a question stitched from pieces: a verb-final
1333
  // language cannot put the rest of the question after the path.
1334
  // Plain text, as every box quoting the store: the path is a name other
1335
  // writers control, and as rich text "a  b" would also show as "a b".
1336
  QString question =
1337
      tr("Are you sure you want to delete %1 and the whole content?").arg(path);
2 ✔
1338
  // A link, junction or special file inside is as unexpected as a stray
1339
  // plain file: the walker leaves them out of content and reports them.
1340
  QStringList skipped;
2 ✔
1341
  const QStringList content = Util::regularFilesUnder(
6 ✔
1342
      m_tree->fileSystem().rootPath() + path, {QStringLiteral("*")}, &skipped);
6 ✔
1343
  const bool unexpected =
1344
      !skipped.isEmpty() ||
2 ✔
1345
      std::any_of(content.cbegin(), content.cend(), [](const QString &entry) {
2 ✔
1346
        return QFileInfo(entry).suffix() != QLatin1String("gpg");
4 ✔
1347
      });
1348
  if (unexpected) {
1349
    question += QStringLiteral("\n\n") +
1 ✔
1350
                tr("Attention: there are unexpected files in the given "
1 ✔
1351
                   "folder, check them before continuing.");
1 ✔
1352
  }
1353
  return PlainMessageBox::askYes(this, tr("Delete folder?"), question);
4 ✔
1354
}
1355

1356
auto MainWindow::confirmLinkRemoval(const QString &file) -> bool {
1 ✔
1357
  // Only the link goes (ImitatePass::Remove unlinks it); nothing behind it
1358
  // is looked at or mentioned.
1359
  return PlainMessageBox::askYes(
1 ✔
1360
      this, tr("Delete link?"),
1 ✔
1361
      tr("%1 is a symbolic link or junction. Remove the link? What it "
1 ✔
1362
         "points to is left alone.")
1363
          .arg(QDir::separator() + file));
2 ✔
1364
}
1365

1366
void MainWindow::onDelete() {
10 ✔
1367
  const QModelIndex currentIndex = ui->treeView->currentIndex();
10 ✔
1368
  // While content search results hide the tree, its current entry is not
1369
  // what the user looks at (the Delete key comes here directly).
1370
  if (!currentIndex.isValid() || ui->treeView->isHidden()) {
8 ✔
1371
    // Otherwise the whole password directory would be deleted (#556).
1372
    return;
7 ✔
1373
  }
1374

1375
  const bool isDir = !m_tree->fileInfo(currentIndex).isFile();
6 ✔
1376
  const QString file =
1377
      isDir ? m_tree->currentDir(true) : getFile(currentIndex, true);
6 ✔
1378
  const QString folder =
1379
      m_tree->fileSystem().rootPath() + QDir::separator() + file;
6 ✔
1380
  const bool linkedFolder = isDir && Util::isLinkedFolder(folder);
6 ✔
1381

1382
  if (!linkedFolder && refuseLinkedFolder(folder)) {
5 ✔
1383
    // Behind a link: deleting would reach outside the store.
1384
    return;
1385
  }
1386
  const bool confirmed =
1387
      linkedFolder ? confirmLinkRemoval(file) : confirmDeletion(file, isDir);
5 ✔
1388
  if (!confirmed) {
5 ✔
1389
    return;
1390
  }
1391
  QtPassSettings::getPass()->Remove(file, isDir);
6 ✔
1392
}
1393

1394
void MainWindow::cancelOtpRequest() {
85 ✔
1395
  m_otpRequestFile.clear();
85 ✔
1396
  m_copyRequestFile.clear();
85 ✔
1397
}
85 ✔
1398

1399
void MainWindow::onOperationError() {
34 ✔
1400
  cancelOtpRequest();
34 ✔
1401
  // executeWrapperStarted() emptied the panel and the browser when the
1402
  // operation started (a refusal says so too); what is left to forget is
1403
  // which entry the panel was about to show.
1404
  m_shownFile.clear();
34 ✔
1405
  // A save's refresh waiting for its push is dropped: it would clear the
1406
  // push's error (or whatever failed before it) from the browser.
1407
  m_refreshAfterPush.clear();
34 ✔
1408
  m_refreshAfterPushOwner = nullptr;
1409
}
34 ✔
1410

1411
// Derives the code in-process from one decrypt, so it works with either
1412
// backend on every platform; otpFromFileToClipboard() finishes the job.
1413
void MainWindow::onOtp() {
11 ✔
1414
  if (ui->treeView->isHidden()) {
11 ✔
1415
    return;
4 ✔
1416
  }
1417
  QString file = getFile(ui->treeView->currentIndex(), true);
10 ✔
1418
  if (file.isEmpty()) {
10 ✔
1419
    flashText(tr("No password selected for OTP generation"), true);
1 ✔
1420
    return;
1 ✔
1421
  }
1422
  if (!QtPassSettings::isUseOtp()) {
9 ✔
1423
    // Normally unreachable (the action is hidden), but never fail silently.
1424
    flashText(tr("No OTP code found in this password entry"), true);
1 ✔
1425
    return;
1 ✔
1426
  }
1427

1428
  // Fast path: the panel shows a live code, so no decrypt, and one clipboard
1429
  // write (two setMimeData calls in one turn can empty the Windows
1430
  // clipboard). Only for *this* entry: arrow keys and right-click move
1431
  // currentIndex without QTreeView::clicked, so the code may be another's.
1432
  const QString shown =
1433
      (m_shownFile == file) ? m_displayPanel->currentOtpCode() : QString();
8 ✔
1434
  if (!shown.isEmpty()) {
8 ✔
1435
    m_qtPass->clipboard().copyText(shown);
1 ✔
1436
    showStatusMessage(tr("OTP code copied to clipboard"));
2 ✔
1437
    return;
1438
  }
1439

1440
  // Fallback: decrypt once. The request file keeps passShowHandler from
1441
  // copying the password and tells otpFromFileToClipboard its answer.
1442
  m_otpRequestFile = file;
7 ✔
1443
  setUiElementsEnabled(false);
7 ✔
1444
  // Keep the marker in step so a second request takes the fast path; safe as
1445
  // executeWrapperStarted() clears the panel, so a failed decrypt shows none.
1446
  m_shownFile = file;
7 ✔
1447
  QtPassSettings::getPass()->Show(file);
14 ✔
1448
}
1449

1450
void MainWindow::onEdit() {
3 ✔
1451
  if (ui->treeView->isHidden()) {
3 ✔
1452
    return;
1 ✔
1453
  }
1454
  QString file = getFile(ui->treeView->currentIndex(), true);
2 ✔
1455
  editPassword(file);
2 ✔
1456
}
1457

1458
void MainWindow::onUsers() {
2 ✔
1459
  const QString dir = m_tree->currentDir(false);
2 ✔
1460
  if (refuseLinkedFolder(dir)) {
2 ✔
1461
    return;
1462
  }
1463

1464
  UsersDialog d(QtPassSettings::getPass(), QtPassSettings::load(), dir, this);
1 ✔
1465
  if (!d.exec()) {
1 ✔
1466
    ui->treeView->setFocus();
1 ✔
1467
  }
1468
}
1 ✔
1469

1470
void MainWindow::messageAvailable(const QString &message) {
9 ✔
1471
  show();
9 ✔
1472
  raise();
9 ✔
1473
  if (message.isEmpty()) {
9 ✔
1474
    focusInput();
1 ✔
1475
  } else {
1476
    ui->treeView->expandAll();
8 ✔
1477
    applySearchText(message);
8 ✔
1478
  }
1479
}
9 ✔
1480

1481
void MainWindow::updateProfileBox() {
180 ✔
1482
  const Profiles profiles = QtPassSettings::getProfiles();
180 ✔
1483
  bool activeGone = false;
1484

1485
  if (profiles.isEmpty()) {
7 ✔
1486
    ui->profileWidget->hide();
173 ✔
1487
  } else {
1488
    ui->profileWidget->show();
7 ✔
1489
    // A refill is no choice of the user's: clearing and adding items moves
1490
    // the current text, which would otherwise switch profiles.
1491
    const QSignalBlocker quiet(ui->profileBox);
7 ✔
1492
    ui->profileBox->clear();
7 ✔
1493
    for (auto i = profiles.cbegin(); i != profiles.cend(); ++i) {
19 ✔
1494
      if (!i.key().isEmpty()) {
12 ✔
1495
        ui->profileBox->addItem(i.key());
12 ✔
1496
      }
1497
    }
1498
    ui->profileBox->model()->sort(0);
7 ✔
1499
    int index = ui->profileBox->findText(QtPassSettings::getProfile());
14 ✔
1500
    if (index != -1) { //  -1 for not found
7 ✔
1501
      ui->profileBox->setCurrentIndex(index);
6 ✔
1502
    } else if (ui->profileBox->count() > 0) {
1 ✔
1503
      // The active profile is gone (removed in Settings): the box shows the
1504
      // first one, and the settings and backend must follow it, or the
1505
      // removed profile's store stays in use behind it.
1506
      ui->profileBox->setCurrentIndex(0);
1 ✔
1507
      activeGone = true;
1508
    }
1509
  }
7 ✔
1510
  if (activeGone) {
7 ✔
1511
    on_profileBox_currentTextChanged(ui->profileBox->currentText());
2 ✔
1512
  }
1513
  updateProfileBoxEnabled();
180 ✔
1514
}
180 ✔
1515

1516
void MainWindow::updateProfileBoxEnabled() {
611 ✔
1517
  // No profile switch while anything of the store runs or waits: the
1518
  // backend's store and environment would change under it, and what is
1519
  // still queued (a push after a save, say) would finish for the other
1520
  // profile (#2071). Asked of the backend, not only of the interface: the
1521
  // watchdog releases the interface while a slow gpg or git still runs.
1522
  // Every backend: one kept from before a switch of backend may still
1523
  // run what was queued on it.
1524
  ui->profileBox->setEnabled(m_uiEnabled && ui->profileBox->count() > 1 &&
1,223 ✔
1525
                             QtPassSettings::backendsIdle());
11 ✔
1526
}
611 ✔
1527

1528
void MainWindow::on_profileBox_currentTextChanged(const QString &name) {
6 ✔
1529
  if (m_freshStart || name == QtPassSettings::getProfile()) {
18 ✔
1530
    return;
1 ✔
1531
  }
1532
  // The box is disabled while anything runs; should a change come through
1533
  // anyway, the active profile stays and the box says so again.
1534
  if (!m_uiEnabled || !QtPassSettings::backendsIdle()) {
5 ✔
1535
    const QSignalBlocker quiet(ui->profileBox);
×
1536
    ui->profileBox->setCurrentText(QtPassSettings::getProfile());
×
1537
    return;
1538
  }
×
1539
  // A content search runs outside the queue: leaving grep mode cancels it,
1540
  // so its results for the old store are dropped, not shown for the new.
1541
  if (m_grep.inGrepMode()) {
5 ✔
1542
    ui->grepButton->setChecked(false);
1 ✔
1543
  }
1544

1545
  ui->lineEdit->clear();
5 ✔
1546

1547
  const Profile prof = QtPassSettings::getProfiles().value(name);
10 ✔
1548
  AppSettings s = QtPassSettings::load();
5 ✔
1549
  s.activeProfile = name;
5 ✔
1550
  s.passStore = prof.path;
5 ✔
1551
  s.passSigningKey = prof.signingKey;
5 ✔
1552
  // A profile without its own Git flags keeps the global values.
1553
  s.useGit = prof.useGit.value_or(s.useGit);
5 ✔
1554
  s.autoPush = prof.autoPush.value_or(s.autoPush);
5 ✔
1555
  s.autoPull = prof.autoPull.value_or(s.autoPull);
5 ✔
1556
  QtPassSettings::save(s);
5 ✔
1557
  ui->statusBar->showMessage(tr("Profile changed to %1").arg(name), 2000);
10 ✔
1558

1559
  QtPassSettings::getPass()->updateEnv();
5 ✔
1560

1561
  m_tree->setStore(QtPassSettings::getPassStore());
10 ✔
1562
  deselect();
5 ✔
1563
  ui->treeView->setCurrentIndex(QModelIndex());
5 ✔
1564
}
5 ✔
1565

1566
void MainWindow::initTrayIcon() {
3 ✔
1567
  m_tray = new TrayIcon(this);
3 ✔
1568
  if (!m_tray->getIsAllocated()) {
3 ✔
1569
    destroyTrayIcon();
3 ✔
1570
    return;
3 ✔
1571
  }
1572
#ifndef Q_OS_MACOS
1573
  m_tray->addToggle(ui->actionShowMenuBar);
×
1574
#endif
1575
}
1576

1577
void MainWindow::destroyTrayIcon() {
3 ✔
1578
  delete m_tray;
3 ✔
1579
  m_tray = nullptr;
3 ✔
1580
}
3 ✔
1581

1582
void MainWindow::closeEvent(QCloseEvent *event) {
4 ✔
1583
  // Save in both branches: a tray user only ever hides the window, and
1584
  // used to quit through the tray menu with nothing ever written.
1585
  saveWindowState();
4 ✔
1586
  // Only with a tray icon to come back from: without one (none asked for, or
1587
  // no system tray in this session) a hidden QtPass ran on invisibly, with the
1588
  // last entry in its window and the password on the clipboard.
1589
  if (QtPassSettings::isHideOnClose() && m_tray != nullptr) {
8 ✔
1590
    this->hide();
×
1591
    event->ignore();
1592
  } else {
1593
    m_qtPass->clipboard().clear();
4 ✔
1594
    event->accept();
1595
    // A visible QSystemTrayIcon keeps the application alive, so
1596
    // quitOnLastWindowClosed never fires; quit explicitly.
1597
    QApplication::quit();
4 ✔
1598
  }
1599
}
4 ✔
1600

1601
auto MainWindow::eventFilter(QObject *obj, QEvent *event) -> bool {
7,230 ✔
1602
  if ((obj == ui->toolBar || obj == menuBar()) &&
7,230 ✔
1603
      event->type() == QEvent::PaletteChange) {
1604
    // Breeze gives these bars a "header" palette and, after a runtime
1605
    // light/dark switch, stamps the previous theme's colours back from a
1606
    // cached kdeglobals, hiding the toolbar icons. Deferred so we never
1607
    // re-enter the style while it is still applying its palette.
1608
    QTimer::singleShot(0, this, &MainWindow::dropStaleToolsAreaPalettes);
36 ✔
1609
  }
1610
  if (obj == ui->lineEdit && event->type() == QEvent::KeyPress) {
7,230 ✔
1611
    auto *key = dynamic_cast<QKeyEvent *>(event);
5 ✔
1612
    if (key != nullptr && key->key() == Qt::Key_Down) {
5 ✔
1613
      // Into whichever list is in sight: the tree, or content search results.
1614
      // Focus makes the list's first item current.
1615
      if (ui->treeView->isHidden()) {
2 ✔
1616
        ui->grepResultsList->setFocus();
1 ✔
1617
      } else {
1618
        ui->treeView->setFocus();
1 ✔
1619
      }
1620
    }
1621
    // Return ends at the search box: QLineEdit emits returnPressed() and
1622
    // leaves the key unaccepted, so keyPressEvent() would open the tree's
1623
    // current entry as well. In content search that is an entry nobody
1624
    // asked for; by name, the first hit a second time.
1625
    if (key != nullptr &&
5 ✔
1626
        (key->key() == Qt::Key_Return || key->key() == Qt::Key_Enter)) {
2 ✔
1627
      ui->lineEdit->event(event);
3 ✔
1628
      event->accept();
1629
      return true;
3 ✔
1630
    }
1631
  }
1632
  return QObject::eventFilter(obj, event);
7,227 ✔
1633
}
1634

1635
// Only once the application palette changed (see m_themeSwitched): a bar
1636
// whose active Window lightness is far from the application's shows the
1637
// other theme.
1638
void MainWindow::dropStaleToolsAreaPalettes() {
31 ✔
1639
  if (!m_themeSwitched) {
31 ✔
1640
    return;
1641
  }
1642
  constexpr int kStaleToolsAreaLightness = 64;
1643
  // The active group on both sides: a bar's palette() reads the inactive
1644
  // group while another window has focus (the settings app, during a theme
1645
  // switch), and Breeze gives the header set different inactive colours.
1646
  const int appLightness = QApplication::palette()
54 ✔
1647
                               .color(QPalette::Active, QPalette::Window)
1648
                               .lightness();
27 ✔
1649
  for (QWidget *bar : {static_cast<QWidget *>(ui->toolBar),
108 ✔
1650
                       static_cast<QWidget *>(menuBar())}) {
81 ✔
1651
    if (!bar->testAttribute(Qt::WA_SetPalette)) {
54 ✔
1652
      continue;
48 ✔
1653
    }
1654
    const int barLightness =
1655
        bar->palette().color(QPalette::Active, QPalette::Window).lightness();
12 ✔
1656
    if (qAbs(barLightness - appLightness) <= kStaleToolsAreaLightness) {
6 ✔
1657
      continue;
2 ✔
1658
    }
1659
    bar->setPalette(QPalette());
4 ✔
1660
    // Both bars are transparent and the style paints the tools area from the
1661
    // stale palette, so fill our own. Window, not their Button role, which is
1662
    // not the window colour in either theme.
1663
    bar->setBackgroundRole(QPalette::Window);
4 ✔
1664
    bar->setAutoFillBackground(true);
4 ✔
1665
  }
1666
}
1667

1668
void MainWindow::keyPressEvent(QKeyEvent *event) {
23 ✔
1669
  switch (event->key()) {
23 ✔
1670
  case Qt::Key_Delete:
2 ✔
1671
    onDelete();
2 ✔
1672
    break;
2 ✔
1673
  case Qt::Key_Return:
2 ✔
1674
  case Qt::Key_Enter:
1675
    // While content search results hide the tree, its current entry is not
1676
    // what the user looks at: Return on a result opens that result.
1677
    if (ui->treeView->isHidden()) {
2 ✔
1678
      QTreeWidgetItem *result = ui->grepResultsList->currentItem();
1 ✔
1679
      if (result != nullptr && ui->grepResultsList->hasFocus()) {
1 ✔
1680
        on_grepResultsList_itemClicked(result, 0);
1 ✔
1681
      }
1682
      break;
1683
    }
1684
    if (m_tree->proxy().rowCount() > 0) {
1 ✔
1685
      on_treeView_clicked(ui->treeView->currentIndex());
1 ✔
1686
    }
1687
    break;
1688
  case Qt::Key_Escape:
3 ✔
1689
    ui->lineEdit->clear();
3 ✔
1690
    break;
3 ✔
1691
  default:
1692
    break;
1693
  }
1694
}
23 ✔
1695

1696
void MainWindow::addShareMenu(QMenu &contextMenu, const AppSettings &s) {
9 ✔
1697
  const QString dirPath = QDir::cleanPath(m_tree->currentDir(false));
9 ✔
1698
  auto *shareMenu = new QMenu(tr("Share"), &contextMenu);
9 ✔
1699
  contextMenu.addMenu(shareMenu);
9 ✔
1700

1701
  const QString gpgIdPath = Pass::getGpgIdPath(dirPath, s.passStore);
9 ✔
1702
  const bool gpgIdExists = !gpgIdPath.isEmpty() && QFile(gpgIdPath).exists();
9 ✔
1703
  const QString exePath = s.usePass ? s.passExecutable : s.gpgExecutable;
9 ✔
1704
  const bool gpgAvailable =
1705
      !exePath.isEmpty() &&
18 ✔
1706
      (Executor::parseWslCommand(exePath) || QFile(exePath).exists());
18 ✔
1707

1708
  QAction *reencrypt = shareMenu->addAction(tr("Re-encrypt all passwords"));
9 ✔
1709
  reencrypt->setEnabled(gpgIdExists && gpgAvailable);
9 ✔
1710
  connect(reencrypt, &QAction::triggered, this,
9 ✔
1711
          [this, dirPath]() { reencryptPath(dirPath); });
30 ✔
1712

1713
  QAction *exportKey = shareMenu->addAction(tr("Export my public key..."));
9 ✔
1714
  exportKey->setEnabled(gpgAvailable);
9 ✔
1715
  connect(exportKey, &QAction::triggered, this, &MainWindow::exportPublicKey);
9 ✔
1716

1717
  QAction *addRecipientAction = shareMenu->addAction(tr("Add recipient..."));
9 ✔
1718
  addRecipientAction->setEnabled(gpgIdExists && gpgAvailable);
9 ✔
1719
  connect(addRecipientAction, &QAction::triggered, this,
9 ✔
1720
          [this, dirPath]() { addRecipient(dirPath); });
29 ✔
1721

1722
  QAction *shareHelp = shareMenu->addAction(tr("What is this?"));
9 ✔
1723
  connect(shareHelp, &QAction::triggered, this, &MainWindow::showShareHelp);
9 ✔
1724
}
9 ✔
1725

1726
void MainWindow::showContextMenu(const QPoint &pos) {
11 ✔
1727
  const AppSettings s = QtPassSettings::load();
11 ✔
1728
  const QModelIndex index = ui->treeView->indexAt(pos);
11 ✔
1729
  const bool selected = index.isValid();
1730
  if (!selected) {
1731
    ui->treeView->clearSelection();
1 ✔
1732
    ui->actionDelete->setEnabled(false);
1 ✔
1733
    ui->actionEdit->setEnabled(false);
1 ✔
1734
  }
1735
  ui->treeView->setCurrentIndex(index);
11 ✔
1736
  const QPoint globalPos = ui->treeView->viewport()->mapToGlobal(pos);
11 ✔
1737
  const QFileInfo fileOrFolder = m_tree->fileInfo(ui->treeView->currentIndex());
11 ✔
1738
  const bool isDir = fileOrFolder.isDir();
11 ✔
1739

1740
  QMenu contextMenu;
11 ✔
1741
  if (!selected || isDir) {
11 ✔
1742
    const std::array<std::pair<QString, void (MainWindow::*)()>, 4> onFolder{{
1743
        {tr("Open folder with file manager"), &MainWindow::openFolder},
10 ✔
1744
        {tr("Add folder"), &MainWindow::addFolder},
10 ✔
1745
        {tr("Add password"), &MainWindow::addPassword},
10 ✔
1746
        {tr("Users"), &MainWindow::onUsers},
10 ✔
1747
    }};
×
1748
    for (const auto &[text, slot] : onFolder) {
50 ✔
1749
      connect(contextMenu.addAction(text), &QAction::triggered, this, slot);
40 ✔
1750
    }
1751
  } else if (fileOrFolder.isFile()) {
1 ✔
1752
    connect(contextMenu.addAction(tr("Edit")), &QAction::triggered, this,
1 ✔
1753
            &MainWindow::onEdit);
2 ✔
1754
  }
1755
  if (selected) {
11 ✔
1756
    contextMenu.addSeparator();
10 ✔
1757
    if (isDir) {
10 ✔
1758
      connect(contextMenu.addAction(tr("Rename folder")), &QAction::triggered,
9 ✔
1759
              this, &MainWindow::renameFolder);
18 ✔
1760
    } else if (fileOrFolder.isFile()) {
1 ✔
1761
      connect(contextMenu.addAction(tr("Rename password")), &QAction::triggered,
1 ✔
1762
              this, &MainWindow::renamePassword);
2 ✔
1763
    }
1764
    connect(contextMenu.addAction(tr("Delete")), &QAction::triggered, this,
10 ✔
1765
            &MainWindow::onDelete);
10 ✔
1766
    if (isDir) {
10 ✔
1767
      addShareMenu(contextMenu, s);
9 ✔
1768
    }
1769
  }
1770
  contextMenu.exec(globalPos);
11 ✔
1771
}
11 ✔
1772

1773
void MainWindow::showBrowserContextMenu(const QPoint &pos) {
1 ✔
1774
  QMenu *contextMenu = ui->textBrowser->createStandardContextMenu(pos);
1 ✔
1775
  // Reparent from textBrowser: a browser stylesheet cascades to the child
1776
  // QMenu and breaks its opaque native background.
1777
  contextMenu->setParent(this, contextMenu->windowFlags());
1 ✔
1778
  QPoint globalPos = ui->textBrowser->viewport()->mapToGlobal(pos);
1 ✔
1779

1780
  contextMenu->exec(globalPos);
1 ✔
1781
  delete contextMenu;
1 ✔
1782
}
1 ✔
1783

1784
void MainWindow::openFolder() {
1 ✔
1785
  QString dir = m_tree->currentDir(false);
1 ✔
1786

1787
  QString path = QDir::toNativeSeparators(dir);
1 ✔
1788
  QDesktopServices::openUrl(QUrl::fromLocalFile(path));
1 ✔
1789
}
1 ✔
1790

1791
void MainWindow::addFolder() {
8 ✔
1792
  const AppSettings s = QtPassSettings::load();
8 ✔
1793
  bool ok;
1794
  QString dir = m_tree->currentDir(false);
8 ✔
1795
  QString newdir =
1796
      QInputDialog::getText(this, tr("New folder"),
8 ✔
1797
                            tr("New folder: \n(Will be placed in %1 )")
8 ✔
1798
                                .arg(s.passStore + m_tree->currentDir(true)),
16 ✔
1799
                            QLineEdit::Normal, "", &ok);
16 ✔
1800
  if (!ok || newdir.isEmpty()) {
8 ✔
1801
    return;
1802
  }
1803
  // Checked and created as one and the same path: the check resolves ".."
1804
  // lexically, the system after following links, so "link/../x" would pass
1805
  // as the store's x and be made beside the link's target.
1806
  newdir = QDir::cleanPath(newdir.prepend(dir));
7 ✔
1807
  if (!confirmPathInStore(newdir)) {
7 ✔
1808
    return;
1809
  }
1810
  // Behind a link the folder would be made outside the store, as Users,
1811
  // Re-encrypt and Delete already refuse.
1812
  if (refuseLinkedFolder(newdir)) {
6 ✔
1813
    return;
1814
  }
1815
  // The tree, like `pass ls`, hides names that start with a dot.
1816
  const QStringList parts =
1817
      QDir(s.passStore).relativeFilePath(newdir).split(u'/');
5 ✔
1818
  if (std::any_of(parts.cbegin(), parts.cend(), [](const QString &part) {
10 ✔
1819
        return part != u'.' && part.startsWith(u'.');
5 ✔
1820
      })) {
1821
    PlainMessageBox::warning(this, tr("Hidden folder"),
2 ✔
1822
                             tr("A folder that starts with a dot would be "
1 ✔
1823
                                "hidden from the list: %1")
1824
                                 .arg(newdir));
2 ✔
1825
    return;
1 ✔
1826
  }
1827
  // Exists already: an error, as QDir::mkdir() made it before.
1828
  if (QFileInfo::exists(newdir) || !Util::mkpathForStore(newdir)) {
4 ✔
1829
    PlainMessageBox::warning(this, tr("Error"),
2 ✔
1830
                             tr("Failed to create folder: %1").arg(newdir));
2 ✔
1831
    return;
1 ✔
1832
  }
1833
  // With a signing key, ImitatePass::loadVerifiedRecipients and pass
1834
  // (PASSWORD_STORE_SIGNING_KEY) refuse a .gpg-id without .gpg-id.sig, and
1835
  // signing needs a passphrase just to make a folder. So it inherits the
1836
  // parent's signed list; UsersDialog (Init) gives it its own.
1837
  const bool signingConfigured = !s.passSigningKey.trimmed().isEmpty();
3 ✔
1838
  if (s.addGPGId && !signingConfigured) {
3 ✔
1839
    // Seed from the parent's recipients in effect, not from `enabled` keys:
1840
    // that flag is only set in UsersDialog, so it left a zero-byte .gpg-id
1841
    // shadowing the parent's recipients (#1682).
1842
    if (!Pass::seedGpgIdFile(newdir, s.passStore)) {
3 ✔
1843
      PlainMessageBox::warning(
1 ✔
1844
          this, tr("Error"),
1 ✔
1845
          tr("Failed to create .gpg-id file in: %1").arg(newdir));
2 ✔
1846
      return;
1 ✔
1847
    }
1848
  }
1849
}
8 ✔
1850

1851
void MainWindow::renameFolder() {
3 ✔
1852
  bool ok;
1853
  QString srcDir = QDir::cleanPath(m_tree->currentDir(false));
3 ✔
1854
  QString srcDirName = QDir(srcDir).dirName();
3 ✔
1855
  QString newName =
1856
      QInputDialog::getText(this, tr("Rename folder"), tr("Rename folder to: "),
3 ✔
1857
                            QLineEdit::Normal, srcDirName, &ok);
6 ✔
1858
  if (!ok || newName.isEmpty()) {
3 ✔
1859
    return;
1860
  }
1861
  QString destDir = srcDir;
1862
  destDir.replace(srcDir.lastIndexOf(srcDirName), srcDirName.length(), newName);
2 ✔
1863
  if (!confirmPathInStore(destDir)) {
2 ✔
1864
    return;
1865
  }
1866
  QtPassSettings::getPass()->Move(srcDir, destDir, false);
3 ✔
1867
}
1868

1869
void MainWindow::editPassword(const QString &file) {
5 ✔
1870
  if (!file.isEmpty()) {
5 ✔
1871
    const AppSettings s = QtPassSettings::load();
5 ✔
1872
    if (s.useGit && s.autoPull) {
5 ✔
1873
      onUpdate(true);
1 ✔
1874
    }
1875
    // The dialog decrypts the entry itself to fill its fields. That decrypt
1876
    // lands on the same finishedShow the panel uses, so drop the panel's claim
1877
    // to it: otherwise passShowHandler() repaints and, with "Always copy",
1878
    // puts the entry's old password on the clipboard - replacing whatever the
1879
    // user copied to paste into the dialog.
1880
    m_shownFile.clear();
5 ✔
1881
    setPassword(file, false);
5 ✔
1882
  }
5 ✔
1883
}
5 ✔
1884

1885
void MainWindow::renamePassword() {
2 ✔
1886
  bool ok;
1887
  QString file = getFile(ui->treeView->currentIndex(), false);
2 ✔
1888
  QString filePath = QFileInfo(file).path();
2 ✔
1889
  QString fileName = QFileInfo(file).fileName();
2 ✔
1890
  if (fileName.endsWith(".gpg", Qt::CaseInsensitive)) {
4 ✔
1891
    fileName.chop(4);
2 ✔
1892
  }
1893

1894
  QString newName =
1895
      QInputDialog::getText(this, tr("Rename file"), tr("Rename file to: "),
2 ✔
1896
                            QLineEdit::Normal, fileName, &ok);
4 ✔
1897
  if (!ok || newName.isEmpty()) {
2 ✔
1898
    return;
1899
  }
1900
  QString newFile = QDir(filePath).filePath(newName);
2 ✔
1901
  if (!confirmPathInStore(newFile)) {
2 ✔
1902
    return;
1903
  }
1904
  QtPassSettings::getPass()->Move(file, newFile, false);
3 ✔
1905
}
1906

1907
void MainWindow::copySelectionOrPassword() {
3 ✔
1908
  QWidget *focus = QApplication::focusWidget();
3 ✔
1909
  // The widget's own copy: a SecretTextBrowser marks what it copies as
1910
  // secret for clipboard managers, as the context menu's Copy does.
1911
  if (auto *text = qobject_cast<QTextEdit *>(focus);
3 ✔
1912
      text != nullptr && text->textCursor().hasSelection()) {
3 ✔
1913
    text->copy();
1 ✔
1914
    return;
1 ✔
1915
  }
1916
  // Through the clipboard manager, as a copy button would: the label may be
1917
  // the OTP code, which gets the secret hint and the autoclear.
1918
  if (auto *label = qobject_cast<QLabel *>(focus);
1919
      label != nullptr && label->hasSelectedText()) {
2 ✔
1920
    m_qtPass->clipboard().copyText(label->selectedText());
1 ✔
1921
    return;
1 ✔
1922
  }
1923
  copyPasswordFromTreeview();
1 ✔
1924
}
1925

1926
void MainWindow::copyPasswordFromTreeview() {
10 ✔
1927
  // While content search results hide the tree, its current entry is not
1928
  // what the user looks at: no decrypt, as for Edit and OTP.
1929
  if (ui->treeView->isHidden()) {
10 ✔
1930
    return;
1 ✔
1931
  }
1932
  QFileInfo fileOrFolder = m_tree->fileInfo(ui->treeView->currentIndex());
9 ✔
1933

1934
  if (fileOrFolder.isFile()) {
9 ✔
1935
    QString file = getFile(ui->treeView->currentIndex(), true);
9 ✔
1936
    // The newest Ctrl+C wins: finishedShow names its file, so the decrypt of
1937
    // an earlier request is simply not this one's.
1938
    m_copyRequestFile = file;
9 ✔
1939
    // This Show repaints the panel as well; see onOtp().
1940
    m_shownFile = file;
9 ✔
1941
    QtPassSettings::getPass()->Show(file);
18 ✔
1942
  }
1943
}
9 ✔
1944

1945
void MainWindow::passwordFromFileToClipboard(const QString &text,
28 ✔
1946
                                             const QString &file) {
1947
  if (m_copyRequestFile.isEmpty() || file != m_copyRequestFile) {
28 ✔
1948
    return;
23 ✔
1949
  }
1950
  m_copyRequestFile.clear();
8 ✔
1951
  // The first line, without a list of every line (an entry can expand into
1952
  // millions of them), and without the "\r" of a CRLF line end, as the
1953
  // password row and "Always copy" have it.
1954
  const QString first = FileContent::passwordLine(text);
8 ✔
1955
  // A `pass otp insert` entry's first line is the otpauth:// URI carrying the
1956
  // TOTP seed, and an OTP field holding a seed there is the same; copying it
1957
  // would leak 2FA material. Matches the display path
1958
  // (FileContent::getPasswordForDisplay / PasswordDisplayPanel).
1959
  if (FileContent::isOtpPasswordLine(first)) {
8 ✔
1960
    flashText(tr("This entry holds an OTP secret, not a password"), true);
6 ✔
1961
    return;
1962
  }
1963
  m_qtPass->clipboard().copyText(first);
5 ✔
1964
}
1965

1966
void MainWindow::showStatusMessage(const QString &msg, int timeout) {
27 ✔
1967
  ui->statusBar->showMessage(msg, timeout);
27 ✔
1968
}
27 ✔
1969

1970
void MainWindow::reencryptPath(const QString &dir) {
3 ✔
1971
  QDir checkDir(dir);
3 ✔
1972
  if (!checkDir.exists()) {
3 ✔
1973
    PlainMessageBox::critical(this, tr("Error"),
2 ✔
1974
                              tr("Directory does not exist: %1").arg(dir));
2 ✔
1975
    return;
1 ✔
1976
  }
1977
  if (refuseLinkedFolder(dir)) {
2 ✔
1978
    return;
1979
  }
1980

1981
  const bool yes = PlainMessageBox::askYes(
2 ✔
1982
      this, tr("Re-encrypt passwords"),
2 ✔
1983
      tr("Re-encrypt all passwords in %1?\n\n"
2 ✔
1984
         "This will re-encrypt ALL password files in this folder "
1985
         "using the current recipients defined in .gpg-id.\n\n"
1986
         "This may rewrite many files and cannot be undone easily.\n\n"
1987
         "Continue?")
1988
          .arg(QDir(dir).dirName()));
4 ✔
1989

1990
  if (!yes)
2 ✔
1991
    return;
1992

1993
  // Disable now; the asynchronous startReencryptPath signal re-runs this
1994
  // harmlessly.
1995
  startReencryptPath();
1 ✔
1996

1997
  // Under the current profile's settings: with the pass backend active, the
1998
  // native one is not re-initialised on a profile switch.
1999
  QtPassSettings::getImitatePass()->reencryptPath(
2 ✔
2000
      QDir::cleanPath(QDir(dir).absolutePath()), QtPassSettings::load());
2 ✔
2001
}
3 ✔
2002

2003
// Idempotent: reencryptPath() calls it before ImitatePass emits the signal.
2004
void MainWindow::startReencryptPath() {
6 ✔
2005
  m_reencryptRunning = true;
6 ✔
2006
  setUiElementsEnabled(false);
6 ✔
2007
  // The worker always ends with endReencryptPath(), and Cancel is available
2008
  // throughout, so the generic watchdog is not needed for this operation.
2009
  m_uiWatchdog.stop();
6 ✔
2010
  ui->treeView->setDisabled(true);
6 ✔
2011
  if (m_reencryptProgress)
6 ✔
2012
    return;
2013
  auto *progress = new QProgressDialog(tr("Re-encrypting passwords..."),
4 ✔
2014
                                       tr("Cancel"), 0, 0, this);
8 ✔
2015
  progress->setWindowTitle(tr("Re-encrypt passwords"));
4 ✔
2016
  progress->setWindowModality(Qt::WindowModal);
4 ✔
2017
  progress->setAutoClose(false);
4 ✔
2018
  progress->setAutoReset(false);
4 ✔
2019
  progress->setMinimumDuration(0);
4 ✔
2020
  connect(progress, &QProgressDialog::canceled, this, [this]() {
4 ✔
2021
    QtPassSettings::getImitatePass()->cancelReencryptPath();
1 ✔
2022
    showStatusMessage(tr("Cancelling re-encryption"), 5000);
1 ✔
2023
  });
1 ✔
2024
  m_reencryptProgress = progress;
2025
  progress->show();
4 ✔
2026
}
2027

2028
void MainWindow::reencryptProgress(int current, int total) {
5 ✔
2029
  if (!m_reencryptProgress)
5 ✔
2030
    return;
2031
  m_reencryptProgress->setMaximum(total);
4 ✔
2032
  m_reencryptProgress->setLabelText(
4 ✔
2033
      tr("Re-encrypting passwords: %1 of %2").arg(current).arg(total));
8 ✔
2034
  // On a modal dialog setValue() runs processEvents(), which can deliver
2035
  // endReencryptPath() and reset m_reencryptProgress: keep this last.
2036
  m_reencryptProgress->setValue(current);
4 ✔
2037
}
2038

2039
void MainWindow::endReencryptPath() {
4 ✔
2040
  m_reencryptRunning = false;
4 ✔
2041
  if (m_reencryptProgress) {
4 ✔
2042
    m_reencryptProgress->hide();
4 ✔
2043
    m_reencryptProgress->deleteLater();
4 ✔
2044
    m_reencryptProgress = nullptr;
2045
  }
2046
  setUiElementsEnabled(true);
4 ✔
2047
}
4 ✔
2048

2049
void MainWindow::exportPublicKey() {
3 ✔
2050
  const AppSettings s = QtPassSettings::load();
3 ✔
2051
  const QString identity = s.passSigningKey;
2052
  if (identity.isEmpty()) {
3 ✔
2053
    QMessageBox::information(
2 ✔
2054
        this, tr("Export public key"),
1 ✔
2055
        tr("<h3>Export your public key</h3>"
×
2056
           "<p>No signing key is configured. Set one in QtPass Settings "
2057
           "&gt; GPG keys, or run this in a terminal:</p>"
2058
           "<pre>gpg --armor --export --output my_key.asc &lt;your-key-id"
2059
           "&gt;</pre>"
2060
           "<p>Then send the file to your teammates.</p>"));
2061
    return;
1 ✔
2062
  }
2063
  QString gpgExe = s.gpgExecutable;
2064
  if (gpgExe.isEmpty()) {
2 ✔
2065
    gpgExe = QStringLiteral("gpg");
×
2066
  }
2067
  QStringList args = {"--armor", "--export"};
10 ✔
2068
  args.append(identity.split(' ', Qt::SkipEmptyParts));
2 ✔
2069
  QString stdOut;
2 ✔
2070
  QString stdErr;
2 ✔
2071
  int exitCode = Executor::executeBlocking(gpgExe, args, &stdOut, &stdErr);
2 ✔
2072
  if (exitCode != 0 || stdOut.isEmpty()) {
2 ✔
2073
    PlainMessageBox::warning(this, tr("Export public key"),
2 ✔
2074
                             tr("Could not export public key for %1.\n\n%2")
1 ✔
2075
                                 .arg(identity, stdErr.isEmpty()
2 ✔
2076
                                                    ? tr("No output from gpg.")
2 ✔
2077
                                                    : stdErr));
2078
    return;
2079
  }
2080
  ExportPublicKeyDialog dialog(identity, stdOut, this);
1 ✔
2081
  dialog.exec();
1 ✔
2082
}
4 ✔
2083

2084
// UsersDialog only ticks keys already in the keyring; importing a foreign
2085
// key still has to happen via gpg (or QtPass settings) first.
2086
void MainWindow::addRecipient(const QString &dir) {
2 ✔
2087
  if (refuseLinkedFolder(dir)) {
2 ✔
2088
    return;
1 ✔
2089
  }
2090
  UsersDialog d(QtPassSettings::getPass(), QtPassSettings::load(), dir, this);
1 ✔
2091
  d.exec();
1 ✔
2092
}
1 ✔
2093

2094
// A tree-picked folder that is, or lies behind, a symlink or junction is not
2095
// a folder of the store. The store root itself may be a link (a synced
2096
// folder); that is configuration, not a tree pick.
2097
auto MainWindow::refuseLinkedFolder(const QString &dir) -> bool {
17 ✔
2098
  if (!Util::isUnderLink(dir, QtPassSettings::load().passStore)) {
17 ✔
2099
    return false;
2100
  }
2101
  PlainMessageBox::critical(
4 ✔
2102
      this, tr("Not a folder of the store"),
4 ✔
2103
      tr("%1 is, or lies behind, a symbolic link or junction. What that "
4 ✔
2104
         "points to is not part of the password store and is left alone.")
2105
          .arg(QDir::toNativeSeparators(QDir::cleanPath(dir))));
8 ✔
2106
  return true;
4 ✔
2107
}
2108

2109
void MainWindow::showShareHelp() {
1 ✔
2110
  QMessageBox::information(
2 ✔
2111
      this, tr("Sharing passwords with GPG"),
1 ✔
2112
      tr("<h3>Sharing passwords with GPG</h3>"
1 ✔
2113
         "<p>To share passwords with other users:</p>"
2114
         "<ol>"
2115
         "<li><b>Export your public key</b> and send it to teammates</li>"
2116
         "<li><b>Import teammates' public keys</b> into your GPG keyring</li>"
2117
         "<li><b>Re-encrypt passwords</b> so all recipients can decrypt "
2118
         "them</li>"
2119
         "</ol>"
2120
         "<p>Only people who have a matching secret key can decrypt the "
2121
         "passwords.</p>"
2122
         "<p><b>Tip:</b> Use the same GPG key for all shared folders.</p>"
2123
         "<p>See the FAQ for more details.</p>"));
2124
}
1 ✔
2125

2126
void MainWindow::updateGitButtonVisibility(bool uiEnabled) {
396 ✔
2127
  const AppSettings s = QtPassSettings::load();
396 ✔
2128
  // Without Git there is nothing to push or pull, ever: the buttons go, not
2129
  // grey out. While an operation runs they stay and are disabled.
2130
  const bool usable =
2131
      s.useGit && !(s.gitExecutable.isEmpty() && s.passExecutable.isEmpty());
396 ✔
2132
  ui->actionPush->setVisible(usable);
396 ✔
2133
  ui->actionUpdate->setVisible(usable);
396 ✔
2134
  // The separator in front of them would otherwise sit next to the next one.
2135
  const QList<QAction *> actions = ui->toolBar->actions();
396 ✔
2136
  const qsizetype at = actions.indexOf(ui->actionPush);
396 ✔
2137
  if (at > 0 && actions.at(at - 1)->isSeparator()) {
396 ✔
2138
    actions.at(at - 1)->setVisible(usable);
396 ✔
2139
  }
2140
  enableGitButtons(usable && uiEnabled);
396 ✔
2141
}
396 ✔
2142

2143
void MainWindow::updateOtpButtonVisibility(bool uiEnabled) {
402 ✔
2144
  // No platform gating: codes are generated in-process. Visible but disabled
2145
  // when OTP is off: the panel never shows an OTP field (a secret), so hiding
2146
  // this too would leave no trace of the feature. Honour uiEnabled, or the
2147
  // user can stack Show calls while a decrypt is in flight.
2148
  ui->actionOtp->setVisible(true);
402 ✔
2149
  ui->actionOtp->setEnabled(QtPassSettings::isUseOtp() && uiEnabled);
415 ✔
2150
}
402 ✔
2151

2152
void MainWindow::updateGrepButtonVisibility() {
176 ✔
2153
  const bool enabled = QtPassSettings::isUseGrepSearch();
176 ✔
2154
  ui->grepButton->setVisible(enabled);
176 ✔
2155
  ui->grepCaseButton->setVisible(enabled);
176 ✔
2156
  if (!enabled && m_grep.inGrepMode()) {
176 ✔
2157
    ui->grepButton->setChecked(false);
1 ✔
2158
  }
2159
}
176 ✔
2160

2161
void MainWindow::enableGitButtons(const bool &state) {
396 ✔
2162
  ui->actionPush->setEnabled(state);
396 ✔
2163
  ui->actionUpdate->setEnabled(state);
396 ✔
2164
}
396 ✔
2165

2166
void MainWindow::critical(const QString &title, const QString &msg) {
3 ✔
2167
  // Pass's messages quote store paths; see PlainMessageBox.
2168
  PlainMessageBox::critical(this, title, msg);
3 ✔
2169
}
3 ✔
2170

2171
void MainWindow::onProcessOutput(const QString &output, bool isError,
7 ✔
2172
                                 Enums::PROCESS pid) {
2173
  if (!QtPassSettings::isShowProcessOutput()) {
7 ✔
2174
    return;
2175
  }
2176
  m_processOutput->append(output, isError,
6 ✔
2177
                          ProcessOutputPanel::processName(pid));
12 ✔
2178
}
2179

2180
void MainWindow::updateProcessOutputVisibility() {
5 ✔
2181
  // The action's toggled handler shows or hides the dock.
2182
  ui->actionShowProcessOutput->setChecked(
5 ✔
2183
      QtPassSettings::isShowProcessOutput());
5 ✔
2184
  m_processOutput->setVisible(QtPassSettings::isShowProcessOutput());
5 ✔
2185
}
5 ✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc