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

IJHack / QtPass / 44265697413

18 Nov 2026 08:17AM UTC coverage: 96.28% (-0.1%) from 96.396%
44265697413

push

github

web-flow
Git commits take only their own paths; tool output stays plain and short (#2260)

* Git commits take only their own paths; tool output stays plain and short

- createBackupCommit() stages and commits the store only (`-- .` with -C
  the store): in a repository above it, a modified tracked file outside
  was committed and auto-pushed. The conflict check keeps its
  repository-wide status. Move and copy commit their own paths, not
  whatever else was staged (ANT-2026-P6R5B5PK).
- The first-run wizard, Settings and the key export show their boxes
  with PlainMessageBox: ProfileInit's note ends in git's stderr, which can
  quote a pushed .gitattributes value as markup and a link
  (ANT-2026-V7X4M2B6).
- PlainMessageBox shows at most 40 lines and 4000 characters: a box
  laying out git's whole error output froze the GUI
  (ANT-2026-J1OLDGTJ).
- repositoryPassClimbsTo() reads HEAD and a .git file with
  openRegularFile(): a link to a FIFO or a device blocked the open on the
  GUI thread when Settings opened (ANT-2026-0KZE41ZD).

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

* Names on one line in confirmations; git's own metadata links count

From the #2260 review:
- The re-encrypt, link-removal and overwrite questions put the quoted
  names on one line: a folder name with line feeds pushed the warning out
  of the box, which now shows 40 lines at most, and Yes still ran.
- repositoryPassClimbsTo() opens HEAD and a .git file following links
  but only to a regular file, without blocking (O_NONBLOCK, then fstat):
  git takes HEAD -> refs/heads/main and a .git link to a gitfile, which
  openRegularFile()'s O_NOFOLLOW refused, so the Settings warning about
  the repository pass commits in went missing.

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

* Message boxes: the rest of a cut message under Show Details

From the #2260 review:... (continued)

79 of 93 new or added lines in 8 files covered. (84.95%)

6 existing lines in 1 file now uncovered.

9110 of 9462 relevant lines covered (96.28%)

1291.19 hits per line

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

97.05
/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 <QScrollBar>
56
#include <QShortcut>
57
#include <QTextCharFormat>
58
#include <QTextEdit>
59
#include <QTextStream>
60
#include <QTimer>
61
#include <QTreeWidget>
62
#include <QUrl>
63
#include <algorithm>
64
#include <array>
65
#include <utility>
66

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

76
  m_qtPass = new QtPass(this);
184 ✔
77
  restoreWindow();
184 ✔
78
  connectBackends();
184 ✔
79

80
  // Every Copy binding, not only the first (Ctrl+C): Ctrl+Insert and F16
81
  // otherwise reached the views' own copy, which put decrypted text on the
82
  // clipboard bare, without the secret hint or the autoclear.
83
  const QList<QKeySequence> copyKeys =
84
      QKeySequence::keyBindings(QKeySequence::StandardKey::Copy);
184 ✔
85
  for (const QKeySequence &keys : copyKeys) {
552 ✔
86
    new QShortcut(keys, this, this, &MainWindow::copySelectionOrPassword);
368 ✔
87
  }
88

89
  m_tree = new StoreTree(ui->treeView, this);
184 ✔
90
  m_tree->setStore(QtPassSettings::getPassStore(Util::findPasswordStore()));
184 ✔
91
  m_tree->setPass(QtPassSettings::getPass());
184 ✔
92
  connect(ui->treeView, &QWidget::customContextMenuRequested, this,
184 ✔
93
          &MainWindow::showContextMenu);
368 ✔
94
  connect(ui->treeView, &DeselectableTreeView::emptyClicked, this,
184 ✔
95
          &MainWindow::deselect);
184 ✔
96

97
  initTextBrowser();
184 ✔
98

99
  updateProfileBox();
184 ✔
100

101
  initDisplayPanel();
184 ✔
102

103
  QtPassSettings::getPass()->updateEnv();
184 ✔
104

105
  // Install the search-box key filter once, not on every setUiElementsEnabled
106
  // call.
107
  ui->lineEdit->installEventFilter(this);
184 ✔
108
  // Both live in Breeze's "tools area" and get its header palette; see the
109
  // PaletteChange branch in eventFilter().
110
  ui->toolBar->installEventFilter(this);
184 ✔
111
  menuBar()->installEventFilter(this);
184 ✔
112

113
  initTimers();
184 ✔
114

115
  initToolBarButtons();
184 ✔
116
  initStatusBar();
184 ✔
117
  initProcessOutput();
184 ✔
118

119
  ui->lineEdit->setClearButtonEnabled(true);
184 ✔
120
  updateGrepButtonVisibility();
184 ✔
121

122
  setUiElementsEnabled(true);
184 ✔
123

124
  // No QApplication::quit() here: before exec() it is a documented no-op.
125
  // main() checks initSucceeded() and exits before show() instead.
126
  m_qtPass->init();
184 ✔
127
  // OK is not gated on Util::configIsValid(): an accepted configuration can
128
  // still lack a .gpg-id, so ask again; only a cancel ends the loop.
129
  while (!Util::configIsValid(QtPassSettings::load())) {
185 ✔
130
    if (!config()) {
2 ✔
131
      return;
132
    }
133
  }
134
  m_freshStart = false;
183 ✔
135
  m_initSucceeded = true;
183 ✔
136

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

147
  // Initial focus is set in showEvent(): a 10 ms QTimer here could fire
148
  // before the window was realised (queued ActivationChange, nested exec() in
149
  // init()) and selectAll() segfaulted inside Qt (#1187, #1188).
150
}
×
151

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

192
void MainWindow::initTextBrowser() {
184 ✔
193
  {
194
    const AppSettings s = QtPassSettings::load();
184 ✔
195
    if (s.useMonospace) {
184 ✔
196
      QFont monospace("Monospace");
1 ✔
197
      monospace.setStyleHint(QFont::Monospace);
1 ✔
198
      ui->textBrowser->setFont(monospace);
1 ✔
199
    }
1 ✔
200
    if (s.noLineWrapping) {
184 ✔
201
      ui->textBrowser->setLineWrapMode(QTextBrowser::NoWrap);
1 ✔
202
    }
203
    clearPanelTimer.setInterval(MS_PER_SECOND * s.autoclearPanelSeconds);
184 ✔
204
  }
184 ✔
205
  ui->textBrowser->setOpenExternalLinks(true);
184 ✔
206
  ui->textBrowser->setContextMenuPolicy(Qt::CustomContextMenu);
184 ✔
207
  connect(ui->textBrowser, &QWidget::customContextMenuRequested, this,
184 ✔
208
          &MainWindow::showBrowserContextMenu);
184 ✔
209
}
184 ✔
210

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

230
void MainWindow::initTimers() {
184 ✔
231
  clearPanelTimer.setSingleShot(true);
184 ✔
232
  connect(&clearPanelTimer, &QTimer::timeout, this, [this]() { clearPanel(); });
186 ✔
233

234
  searchTimer.setInterval(350);
184 ✔
235
  searchTimer.setSingleShot(true);
184 ✔
236

237
  connect(&searchTimer, &QTimer::timeout, this, &MainWindow::onTimeoutSearch);
184 ✔
238

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

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

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

292
MainWindow::~MainWindow() {
364 ✔
293
  // Quit from the tray menu or a SIGTERM never delivers closeEvent(); the
294
  // window still knows its last geometry here.
295
  saveWindowState();
184 ✔
296
  delete m_qtPass;
184 ✔
297
}
548 ✔
298

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

338
// Idempotent; called from closeEvent() and the destructor.
339
void MainWindow::saveWindowState() {
188 ✔
340
  QtPassSettings::setGeometry(saveGeometry());
188 ✔
341
  QtPassSettings::setSavestate(saveState());
188 ✔
342
}
188 ✔
343

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

363
auto MainWindow::event(QEvent *event) -> bool {
8,503 ✔
364
  if (event->type() == QEvent::ApplicationPaletteChange) {
8,503 ✔
365
    m_themeSwitched = true;
11 ✔
366
    // Breeze may re-stamp the bars before this arrives (Plasma 6 does):
367
    // their PaletteChange then found no switch yet, so check them now too.
368
    QTimer::singleShot(0, this, &MainWindow::dropStaleToolsAreaPalettes);
11 ✔
369
  }
370
  return QMainWindow::event(event);
8,503 ✔
371
}
372

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

390
void MainWindow::showEvent(QShowEvent *event) {
44 ✔
391
  QMainWindow::showEvent(event);
44 ✔
392
  if (m_firstShowCompleted) {
44 ✔
393
    return;
394
  }
395
  // Queued so the platform map and pending rebuilds (setWindowFlags on the
396
  // wizard path) settle first. focusInput() sets the latch only on success,
397
  // so a failed lookup retries on the next show.
398
  QMetaObject::invokeMethod(this, &MainWindow::focusInput,
42 ✔
399
                            Qt::QueuedConnection);
400
}
401

402
void MainWindow::initToolBarButtons() {
184 ✔
403
  connect(ui->actionAddPassword, &QAction::triggered, this,
184 ✔
404
          &MainWindow::addPassword);
184 ✔
405
  connect(ui->actionAddFolder, &QAction::triggered, this,
184 ✔
406
          &MainWindow::addFolder);
184 ✔
407
  connect(ui->actionEdit, &QAction::triggered, this, &MainWindow::onEdit);
184 ✔
408
  connect(ui->actionDelete, &QAction::triggered, this, &MainWindow::onDelete);
184 ✔
409
  connect(ui->actionPush, &QAction::triggered, this, &MainWindow::onPush);
184 ✔
410
  connect(ui->actionUpdate, &QAction::triggered, this, &MainWindow::onUpdate);
184 ✔
411
  connect(ui->actionUsers, &QAction::triggered, this, &MainWindow::onUsers);
184 ✔
412
  connect(ui->actionConfig, &QAction::triggered, this, &MainWindow::onConfig);
184 ✔
413
  connect(ui->actionOtp, &QAction::triggered, this, &MainWindow::onOtp);
184 ✔
414

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

443
  ui->actionAddPassword->setIcon(
184 ✔
444
      QIcon::fromTheme("document-new", QIcon(":/icons/document-new.svg")));
736 ✔
445
  ui->actionAddFolder->setIcon(
184 ✔
446
      QIcon::fromTheme("folder-new", QIcon(":/icons/folder-new.svg")));
736 ✔
447
  ui->actionEdit->setIcon(QIcon::fromTheme(
184 ✔
448
      "document-properties", QIcon(":/icons/document-properties.svg")));
552 ✔
449
  ui->actionDelete->setIcon(
184 ✔
450
      QIcon::fromTheme("edit-delete", QIcon(":/icons/edit-delete.svg")));
736 ✔
451
  ui->actionPush->setIcon(
184 ✔
452
      QIcon::fromTheme("go-up", QIcon(":/icons/go-top.svg")));
736 ✔
453
  ui->actionUpdate->setIcon(
184 ✔
454
      QIcon::fromTheme("go-down", QIcon(":/icons/go-bottom.svg")));
736 ✔
455
  ui->actionUsers->setIcon(QIcon::fromTheme(
184 ✔
456
      "x-office-address-book", QIcon(":/icons/x-office-address-book.svg")));
552 ✔
457
  ui->actionConfig->setIcon(QIcon::fromTheme(
184 ✔
458
      "applications-system", QIcon(":/icons/applications-system.svg")));
368 ✔
459
}
184 ✔
460

461
void MainWindow::initStatusBar() {
184 ✔
462
  ui->statusBar->showMessage(tr("Welcome to QtPass %1").arg(VERSION), 2000);
368 ✔
463

464
  QPixmap logo = QPixmap::fromImage(QImage(":/artwork/icon.svg"))
368 ✔
465
                     .scaledToHeight(statusBar()->height());
184 ✔
466
  auto *logoApp = new QLabel(statusBar());
184 ✔
467
  logoApp->setPixmap(logo);
184 ✔
468
  statusBar()->addPermanentWidget(logoApp);
184 ✔
469
}
184 ✔
470

471
auto MainWindow::getCurrentTreeViewIndex() -> QModelIndex {
9 ✔
472
  return ui->treeView->currentIndex();
9 ✔
473
}
474

475
void MainWindow::flashText(const QString &text, const bool isError,
84 ✔
476
                           const bool isHtml) {
477
  // setText() applies the current char format to the whole message. Start
478
  // from an empty one: inherited from a cursor on a linkified URL it carried
479
  // the anchor, and the message became a link to that address. No colour
480
  // but red for an error, so text follows runtime light/dark switches (#946).
481
  QTextCursor cursor = ui->textBrowser->textCursor();
84 ✔
482
  cursor.clearSelection();
84 ✔
483
  ui->textBrowser->setTextCursor(cursor);
84 ✔
484
  QTextCharFormat format;
84 ✔
485
  if (isError) {
84 ✔
486
    format.setForeground(QColor(Qt::red));
11 ✔
487
  }
488
  ui->textBrowser->setCurrentCharFormat(format);
84 ✔
489

490
  if (isHtml) {
84 ✔
491
    QString _text = text;
492
    if (!ui->textBrowser->toPlainText().isEmpty()) {
140 ✔
493
      _text = ui->textBrowser->toHtml() + _text;
36 ✔
494
    }
495
    ui->textBrowser->setHtml(_text);
70 ✔
496
  } else {
497
    ui->textBrowser->setText(text);
14 ✔
498
  }
499
}
84 ✔
500

501
void MainWindow::applyTextBrowserSettings() {
5 ✔
502
  const AppSettings s = QtPassSettings::load();
5 ✔
503
  if (s.useMonospace) {
5 ✔
504
    QFont monospace("Monospace");
1 ✔
505
    monospace.setStyleHint(QFont::Monospace);
1 ✔
506
    ui->textBrowser->setFont(monospace);
1 ✔
507
  } else {
1 ✔
508
    ui->textBrowser->setFont(QFont());
4 ✔
509
  }
510

511
  if (s.noLineWrapping) {
5 ✔
512
    ui->textBrowser->setLineWrapMode(QTextBrowser::NoWrap);
1 ✔
513
  } else {
514
    ui->textBrowser->setLineWrapMode(QTextBrowser::WidgetWidth);
4 ✔
515
  }
516
}
5 ✔
517

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

537
auto MainWindow::config() -> bool {
7 ✔
538
  if (m_freshStart) {
7 ✔
539
    // No usable configuration yet: the wizard finds the programs, the key
540
    // and the store, and creates the store when it has to.
541
    FirstRunWizard wizard(this);
2 ✔
542
    if (wizard.exec() != QDialog::Accepted) {
2 ✔
543
      return false;
544
    }
545
  } else {
2 ✔
546
    ConfigDialog d(this);
5 ✔
547
    d.setModal(true);
5 ✔
548
    if (d.exec() != QDialog::Accepted) {
5 ✔
549
      return false;
550
    }
551
  }
5 ✔
552

553
  applyTextBrowserSettings();
5 ✔
554
  applyWindowFlagsSettings();
5 ✔
555

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

574
  Pass *activePass = QtPassSettings::getPass();
5 ✔
575
  activePass->updateEnv();
5 ✔
576
  m_tree->setPass(activePass);
5 ✔
577
  clearPanelTimer.setInterval(MS_PER_SECOND * s.autoclearPanelSeconds);
5 ✔
578
  m_qtPass->clipboard().setAutoclearTimer();
5 ✔
579

580
  updateGitButtonVisibility();
5 ✔
581
  updateOtpButtonVisibility();
5 ✔
582
  updateGrepButtonVisibility();
5 ✔
583
  updateProcessOutputVisibility();
5 ✔
584
#ifndef Q_OS_MACOS
585
  // The action's toggled handler shows or hides the bar (and saves again).
586
  ui->actionShowMenuBar->setChecked(s.showMenuBar);
5 ✔
587
#endif
588
  if (s.useTrayIcon && m_tray == nullptr) {
5 ✔
589
    initTrayIcon();
1 ✔
590
  } else if (!s.useTrayIcon && m_tray != nullptr) {
4 ✔
591
    destroyTrayIcon();
×
592
  }
593

594
  // Stay fresh-start while the configuration is unusable, so the
595
  // constructor's loop re-runs the wizard. The re-prompt lives there:
596
  // recursing here never reported a cancel back to the caller.
597
  if (Util::configIsValid(s)) {
5 ✔
598
    m_freshStart = false;
5 ✔
599
  }
600
  return true;
601
}
5 ✔
602

603
void MainWindow::onUpdate(bool block) {
2 ✔
604
  ui->statusBar->showMessage(tr("Updating password-store"), 2000);
2 ✔
605
  if (block) {
2 ✔
606
    QtPassSettings::getPass()->GitPull_b();
1 ✔
607
  } else {
608
    QtPassSettings::getPass()->GitPull();
1 ✔
609
  }
610
}
2 ✔
611

612
void MainWindow::onPush() {
1 ✔
613
  if (QtPassSettings::isUseGit()) {
1 ✔
614
    ui->statusBar->showMessage(tr("Updating password-store"), 2000);
1 ✔
615
    QtPassSettings::getPass()->GitPush();
1 ✔
616
  }
617
}
1 ✔
618

619
void MainWindow::onAutoPush() {
8 ✔
620
  if (QtPassSettings::isUseGit()) {
8 ✔
621
    ui->statusBar->showMessage(tr("Updating password-store"), 2000);
8 ✔
622
    QtPassSettings::getPass()->GitPushAutomatic();
8 ✔
623
  }
624
}
8 ✔
625

626
auto MainWindow::getFile(const QModelIndex &index, bool forPass) -> QString {
62 ✔
627
  return m_tree->fileFor(index, forPass);
62 ✔
628
}
629

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

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

650
  if (fileOrFolder.isFile()) {
4 ✔
651
    editPassword(getFile(index, true));
6 ✔
652
  }
653
}
4 ✔
654

655
void MainWindow::deselect() {
19 ✔
656
  m_shownFile.clear();
19 ✔
657
  cancelOtpRequest();
19 ✔
658
  m_qtPass->clipboard().clear();
19 ✔
659
  ui->treeView->clearSelection();
19 ✔
660
  // The current index too: clearSelection() keeps it, and whatever asks for
661
  // the "current" folder (Users, Add password, Add folder) took the hidden
662
  // entry it was left on, such as the first hit of a search just emptied.
663
  ui->treeView->setCurrentIndex(QModelIndex());
19 ✔
664
  ui->actionEdit->setEnabled(false);
19 ✔
665
  ui->actionDelete->setEnabled(false);
19 ✔
666
  ui->passwordName->setText("");
19 ✔
667
  clearPanel(false);
19 ✔
668
}
19 ✔
669

670
void MainWindow::executeWrapperStarted() {
63 ✔
671
  m_displayPanel->clear();
63 ✔
672
  ui->textBrowser->clear();
63 ✔
673
  setUiElementsEnabled(false);
63 ✔
674
  clearPanelTimer.stop();
63 ✔
675
  if (QtPassSettings::isShowProcessOutput()) {
63 ✔
676
    m_processOutput->setVisible(true);
58 ✔
677
  }
678
}
63 ✔
679

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

716
  // Skipped for an OTP request: the user asked for a code, and two
717
  // OleSetClipboard calls in one turn can leave the Windows clipboard empty.
718
  if (m_otpRequestFile.isEmpty() || m_otpRequestFile != file) {
28 ✔
719
    m_qtPass->clipboard().copyIfAlways(password, p_output);
26 ✔
720
  }
721

722
  m_displayPanel->clear();
28 ✔
723

724
  if (s.hideContent) {
28 ✔
725
    output = "***" + tr("Content hidden") + "***";
4 ✔
726
  } else if (s.displayAsIs) {
26 ✔
727
    // As it is, but not a block per line of millions.
728
    output = FileContent::boundedForDisplay(p_output);
4 ✔
729
  } else {
730
    m_displayPanel->displayFields(password, fileContent.getNamedValues(), s,
48 ✔
731
                                  s.useOtp ? fileContent.getOtpUri()
24 ✔
732
                                           : QString());
733
    output = fileContent.getRemainingDataForDisplay();
48 ✔
734
  }
735

736
  if (s.useAutoclearPanel) {
28 ✔
737
    clearPanelTimer.start();
2 ✔
738
  }
739

740
  // Shown as it is, the text holds the password and every secret field: no
741
  // links in it, or a click on a URL-shaped one handed it to the browser.
742
  flashText(QtPass::formatOutput(output, QString(), QString(),
56 ✔
743
                                 !s.displayAsIs || s.hideContent),
28 ✔
744
            false, true);
745
  setUiElementsEnabled(true);
28 ✔
746
}
56 ✔
747

748
void MainWindow::otpFromFileToClipboard(const QString &p_output,
28 ✔
749
                                        const QString &file) {
750
  // Permanently connected: only the decrypt of the entry onOtp() asked for
751
  // is ours, everything else belongs to a tree click or a Ctrl+C.
752
  if (m_otpRequestFile.isEmpty() || file != m_otpRequestFile) {
28 ✔
753
    return;
24 ✔
754
  }
755
  m_otpRequestFile.clear();
6 ✔
756

757
  if (p_output.isEmpty()) {
6 ✔
758
    // Distinguish "could not read the entry" from "entry has no OTP".
759
    flashText(tr("Could not decrypt this password entry"), true);
1 ✔
760
    setUiElementsEnabled(true);
1 ✔
761
    return;
1 ✔
762
  }
763

764
  // passShowHandler ran first for this finishedShow; if it rendered the OTP
765
  // row, reuse its code (as onOtp()'s fast path does). Otherwise parse:
766
  // hideContent, displayAsIs or no OTP field.
767
  const QString shown = m_displayPanel->currentOtpCode();
5 ✔
768
  if (!shown.isEmpty()) {
5 ✔
769
    m_qtPass->clipboard().copyText(shown);
1 ✔
770
    showStatusMessage(tr("OTP code copied to clipboard"));
1 ✔
771
    setUiElementsEnabled(true);
1 ✔
772
    return;
773
  }
774

775
  const AppSettings s = QtPassSettings::load();
4 ✔
776
  // Parse with the same template settings passShowHandler uses, so an OTP
777
  // field is recognised identically in both paths.
778
  const QStringList templ =
779
      s.useTemplate ? TemplateIO::fieldsIn(s.passTemplate) : QStringList();
4 ✔
780
  const bool allFields = s.useTemplate && s.templateAllFields;
4 ✔
781
  const FileContent fileContent =
782
      FileContent::parse(p_output, templ, allFields);
4 ✔
783

784
  Totp::Refusal why = Totp::Refusal::None;
4 ✔
785
  const std::optional<Totp::Settings> settings =
786
      Totp::parse(fileContent.getOtpUri(), &why);
8 ✔
787
  if (settings.has_value()) {
4 ✔
788
    m_qtPass->clipboard().copyText(Totp::generateNow(*settings));
4 ✔
789
    showStatusMessage(tr("OTP code copied to clipboard"));
4 ✔
790
  } else {
791
    // Why, when there is a configuration that gives no code.
792
    const QString reason = Totp::describe(why);
2 ✔
793
    flashText(reason.isEmpty() ? tr("No OTP code found in this password entry")
6 ✔
794
                               : reason,
795
              true);
796
  }
797
  setUiElementsEnabled(true);
4 ✔
798
}
8 ✔
799

800
void MainWindow::clearPanel(bool notify) {
65 ✔
801
  m_displayPanel->clear();
65 ✔
802
  // A QR code of the password is the password on screen as much as the
803
  // panel is; it is a popup of its own, not part of the panel.
804
  m_qtPass->closeQRCode();
65 ✔
805
  const bool grepWasVisible = ui->grepResultsList->isVisible();
65 ✔
806
  ui->grepResultsList->clear();
65 ✔
807
  if (grepWasVisible) {
65 ✔
808
    showContentResults(false);
5 ✔
809
    if (m_grep.inGrepMode()) {
5 ✔
810
      // Left as the button leaves it: a search still running would otherwise
811
      // hand its partial matches to a content search entered meanwhile.
812
      cancelContentSearch();
5 ✔
813
      if (m_grep.leaveGrepMode()) {
814
        QApplication::restoreOverrideCursor();
2 ✔
815
      }
816
      ui->grepButton->blockSignals(true);
5 ✔
817
      ui->grepButton->setChecked(false);
5 ✔
818
      ui->grepButton->blockSignals(false);
5 ✔
819
      ui->lineEdit->blockSignals(true);
5 ✔
820
      ui->lineEdit->clear();
5 ✔
821
      ui->lineEdit->blockSignals(false);
5 ✔
822
      ui->lineEdit->setPlaceholderText(tr("Search password"));
10 ✔
823
    }
824
  }
825
  if (notify) {
65 ✔
826
    QString output = "***" + tr("Password and content hidden") + "***";
4 ✔
827
    ui->textBrowser->setHtml(output);
2 ✔
828
  } else {
829
    ui->textBrowser->setHtml("");
126 ✔
830
  }
831
}
65 ✔
832

833
void MainWindow::setUiElementsEnabled(bool state) {
411 ✔
834
  // A running re-encryption owns the UI state: the progress dialog's Cancel is
835
  // the user's escape hatch and endReencryptPath() releases the interface, so
836
  // neither an unrelated completion nor the watchdog may re-enable it early.
837
  if (state && m_reencryptRunning) {
411 ✔
838
    m_uiWatchdog.stop();
1 ✔
839
    return;
1 ✔
840
  }
841
  // Arm the watchdog while the UI is disabled; disarm once re-enabled.
842
  if (state) {
843
    m_uiWatchdog.stop();
323 ✔
844
  } else {
845
    m_uiWatchdog.start();
87 ✔
846
  }
847
  ui->treeView->setEnabled(state);
410 ✔
848
  ui->lineEdit->setEnabled(state);
410 ✔
849
  ui->actionAddPassword->setEnabled(state);
410 ✔
850
  ui->actionAddFolder->setEnabled(state);
410 ✔
851
  ui->actionUsers->setEnabled(state);
410 ✔
852
  ui->actionConfig->setEnabled(state);
410 ✔
853
  m_uiEnabled = state;
410 ✔
854
  updateProfileBoxEnabled();
410 ✔
855
  const bool uiEnabled = state;
856
  // is a file selected, and in sight (content search results hide the tree)?
857
  state &= ui->treeView->currentIndex().isValid() && !ui->treeView->isHidden();
823 ✔
858
  ui->actionDelete->setEnabled(state);
410 ✔
859
  ui->actionEdit->setEnabled(state);
410 ✔
860
  updateGitButtonVisibility(uiEnabled);
410 ✔
861
  // `state` is now "UI enabled AND a file is selected", which is exactly when
862
  // generating an OTP makes sense.
863
  updateOtpButtonVisibility(state);
410 ✔
864
}
865

866
void MainWindow::restoreWindow() {
195 ✔
867
  // saveGeometry() covers position, size, maximized state and screen;
868
  // anything applied on top discards it. Centre only when nothing was saved.
869
  const QByteArray geometry = QtPassSettings::getGeometry();
390 ✔
870
  if (geometry.isEmpty() || !restoreGeometry(geometry)) {
195 ✔
871
    WindowStateStore::centreOnCursorScreen(*this);
4 ✔
872
  }
873
  restoreState(QtPassSettings::getSavestate(saveState()));
195 ✔
874
  const AppSettings s = QtPassSettings::load();
195 ✔
875

876
  applyWindowFlagsSettings();
195 ✔
877

878
  if (s.useTrayIcon && m_tray == nullptr) {
195 ✔
879
    initTrayIcon();
2 ✔
880
    // Minimized to the tray only when there is one: without a system tray
881
    // initTrayIcon() gave up, and a hidden window could not be brought back.
882
    if (s.startMinimized && m_tray != nullptr) {
2 ✔
883
      // since we are still in constructor, can't directly hide
884
      QTimer::singleShot(10, this, &MainWindow::hide);
×
885
    }
886
  } else if (!s.useTrayIcon && m_tray != nullptr) {
193 ✔
887
    destroyTrayIcon();
×
888
  }
889
}
390 ✔
890

891
void MainWindow::onConfig() { config(); }
1 ✔
892

893
void MainWindow::showAbout() {
1 ✔
894
  QMessageBox::about(
1 ✔
895
      this, tr("About QtPass"),
1 ✔
896
      tr("<h3>QtPass %1</h3>"
1 ✔
897
         "<p>A multi-platform GUI for <a "
898
         "href=\"https://www.passwordstore.org/\">"
899
         "pass</a>, the standard Unix password manager.</p>"
900
         "<p><a href=\"https://qtpass.org/\">qtpass.org</a> &middot; "
901
         "<a href=\"https://github.com/IJHack/QtPass\">Source and "
902
         "issues</a></p>"
903
         "<p>Copyright &copy; 2014&ndash;%2 IJhack. Licensed under the "
904
         "<a href=\"https://www.gnu.org/licenses/gpl-3.0.html\">GNU GPL "
905
         "version 3</a> or later.</p>")
906
          .arg(QStringLiteral(VERSION),
2 ✔
907
               QString::number(QDate::currentDate().year())));
2 ✔
908
}
1 ✔
909

910
void MainWindow::on_lineEdit_textChanged(const QString &arg1) {
48 ✔
911
  if (m_grep.inGrepMode())
48 ✔
912
    return;
913
  ui->statusBar->showMessage(tr("Looking for: %1").arg(arg1), 1000);
70 ✔
914
  ui->treeView->expandAll();
35 ✔
915
  // Drop any decrypt still pending for the entry that was shown: otherwise it
916
  // keeps its right to the panel and, with "Always copy", the clipboard, and
917
  // when it lands late it shows that entry's password under the new heading.
918
  m_shownFile.clear();
35 ✔
919
  cancelOtpRequest();
35 ✔
920
  clearPanel(false);
35 ✔
921
  ui->passwordName->setText("");
70 ✔
922
  ui->actionEdit->setEnabled(false);
35 ✔
923
  ui->actionDelete->setEnabled(false);
35 ✔
924
  searchTimer.start();
35 ✔
925
}
926

927
void MainWindow::onTimeoutSearch() {
39 ✔
928
  // The tree matches slash-separated paths: on Windows, team\bank typed is
929
  // team/bank, as exactMatchPath() reads it too.
930
  QString query = QDir::fromNativeSeparators(ui->lineEdit->text());
78 ✔
931

932
  if (query.isEmpty()) {
39 ✔
933
    ui->treeView->collapseAll();
2 ✔
934
    deselect();
2 ✔
935
  }
936

937
  // The words are matched literally, in order, with anything in between:
938
  // "work vpn" finds work/acme/vpn. Regular expressions belong to the
939
  // content search; here a typed "[" or "(" must not switch filtering off.
940
  QStringList words;
39 ✔
941
  for (const QString &word :
942
       query.split(QLatin1Char(' '), Qt::SkipEmptyParts)) {
116 ✔
943
    words << QRegularExpression::escape(word);
38 ✔
944
  }
945
  QRegularExpression regExp(words.join(QStringLiteral(".*")),
78 ✔
946
                            QRegularExpression::CaseInsensitiveOption);
39 ✔
947
  m_tree->setFilter(regExp);
39 ✔
948

949
  if (m_tree->proxy().rowCount() > 0 && !query.isEmpty()) {
39 ✔
950
    selectFirstFile();
28 ✔
951
  } else {
952
    ui->actionEdit->setEnabled(false);
11 ✔
953
    ui->actionDelete->setEnabled(false);
11 ✔
954
  }
955
}
78 ✔
956

957
void MainWindow::on_lineEdit_returnPressed() {
17 ✔
958
  qCDebug(lcQtPass) << "on_lineEdit_returnPressed"
17 ✔
959
                    << m_tree->proxy().rowCount();
×
960

961
  if (m_grep.inGrepMode()) {
17 ✔
962
    const QString query = ui->lineEdit->text();
12 ✔
963
    if (!query.isEmpty()) {
12 ✔
964
      ui->grepResultsList->clear();
9 ✔
965
      ui->statusBar->showMessage(tr("Searching…"));
18 ✔
966
      if (m_grep.beginSearch()) {
967
        QApplication::setOverrideCursor(Qt::WaitCursor);
9 ✔
968
      }
969
      QtPassSettings::getPass()->Grep(query, ui->grepCaseButton->isChecked());
18 ✔
970
    } else {
971
      cancelContentSearch();
3 ✔
972
      if (m_grep.cancelSearch()) {
973
        QApplication::restoreOverrideCursor();
2 ✔
974
      }
975
      ui->grepResultsList->clear();
3 ✔
976
      showContentResults(false);
3 ✔
977
    }
978
    return;
979
  }
980

981
  // Return within the search delay acts on the text as typed, not on the
982
  // tree as the previous text filtered it.
983
  if (searchTimer.isActive()) {
5 ✔
984
    searchTimer.stop();
5 ✔
985
    onTimeoutSearch();
5 ✔
986
  }
987
  if (m_tree->proxy().rowCount() > 0) {
5 ✔
988
    selectFirstFile();
5 ✔
989
    on_treeView_clicked(ui->treeView->currentIndex());
5 ✔
990
  }
991
}
992

993
void MainWindow::on_grepButton_toggled(bool checked) {
29 ✔
994
  const AppSettings s = QtPassSettings::load();
29 ✔
995
  if (checked) {
29 ✔
996
    m_grep.enterGrepMode();
997
    ui->lineEdit->setPlaceholderText(tr("Search content (regex)"));
36 ✔
998
    // Both backends search through NativeGrep (QRegularExpression), so one
999
    // dialect: PCRE.
1000
    ui->lineEdit->setToolTip(
18 ✔
1001
        tr("Content search uses Perl-compatible regular expressions (PCRE)."));
18 ✔
1002
    ui->lineEdit->clear();
18 ✔
1003
    searchTimer.stop();
18 ✔
1004
    m_tree->setFilter(QRegularExpression());
18 ✔
1005
    ui->grepResultsList->setVisible(false);
18 ✔
1006
    // Keep treeView visible until results arrive
1007
  } else {
1008
    cancelContentSearch();
11 ✔
1009
    if (m_grep.leaveGrepMode()) {
1010
      QApplication::restoreOverrideCursor();
2 ✔
1011
    }
1012
    searchTimer.stop();
11 ✔
1013
    ui->lineEdit->blockSignals(true);
11 ✔
1014
    ui->lineEdit->clear();
11 ✔
1015
    ui->lineEdit->blockSignals(false);
11 ✔
1016
    ui->lineEdit->setPlaceholderText(tr("Search password"));
22 ✔
1017
    ui->lineEdit->setToolTip(QString());
22 ✔
1018
    ui->grepResultsList->clear();
11 ✔
1019
    showContentResults(false);
11 ✔
1020
    m_tree->setFilter(QRegularExpression());
11 ✔
1021
  }
1022
}
29 ✔
1023

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

1099
void MainWindow::on_grepResultsList_itemClicked(QTreeWidgetItem *item,
2 ✔
1100
                                                int /*column*/) {
1101
  const AppSettings s = QtPassSettings::load();
2 ✔
1102
  const QString entry = item->data(0, Qt::UserRole).toString();
2 ✔
1103
  if (entry.isEmpty())
2 ✔
1104
    return;
1105
  const QString fullPath =
1106
      QDir::cleanPath(QDir(s.passStore).filePath(entry + ".gpg"));
4 ✔
1107
  // Persistent: setCurrentIndex() runs the selection handlers, which can
1108
  // change the model before the click is handled.
1109
  const QPersistentModelIndex proxyIndex(m_tree->indexFor(fullPath));
2 ✔
1110
  if (!proxyIndex.isValid())
2 ✔
1111
    return;
1112
  ui->treeView->setCurrentIndex(proxyIndex);
2 ✔
1113
  if (!proxyIndex.isValid())
2 ✔
1114
    return;
1115
  on_treeView_clicked(proxyIndex);
2 ✔
1116
  if (s.hideContent || s.useAutoclearPanel)
2 ✔
1117
    ui->grepResultsList->clear();
1 ✔
1118
  showContentResults(false);
2 ✔
1119
  ui->treeView->scrollTo(proxyIndex);
2 ✔
1120
  ui->treeView->setFocus();
2 ✔
1121
}
4 ✔
1122

1123
void MainWindow::showContentResults(bool shown) {
29 ✔
1124
  ui->grepResultsList->setVisible(shown);
29 ✔
1125
  ui->treeView->setVisible(!shown);
29 ✔
1126
  if (shown) {
29 ✔
1127
    // The tree's current entry is out of sight: Delete, Edit and OTP would
1128
    // act on it, not on a result. Opening a result shows the tree again.
1129
    ui->actionDelete->setEnabled(false);
6 ✔
1130
    ui->actionEdit->setEnabled(false);
6 ✔
1131
    updateOtpButtonVisibility(false);
6 ✔
1132
  } else if (ui->treeView->selectionModel()->hasSelection()) {
23 ✔
1133
    // Only for an entry still selected: with nothing selected there is no
1134
    // entry for Edit and Delete to act on.
1135
    setUiElementsEnabled(m_uiEnabled);
8 ✔
1136
  }
1137
}
29 ✔
1138

1139
void MainWindow::cancelContentSearch() {
24 ✔
1140
  QtPassSettings::getRealPass()->CancelGrep();
24 ✔
1141
  QtPassSettings::getImitatePass()->CancelGrep();
24 ✔
1142
}
24 ✔
1143

1144
void MainWindow::selectFirstFile() {
33 ✔
1145
  // The entry named exactly as typed wins: with folders sorted first, the
1146
  // depth-first walk found team/bank before bank.
1147
  QModelIndex index = exactMatch();
33 ✔
1148
  if (!index.isValid()) {
1149
    index = firstFile(m_tree->rootIndex());
17 ✔
1150
  }
1151
  ui->treeView->setCurrentIndex(index);
33 ✔
1152
}
33 ✔
1153

1154
namespace {
1155
/**
1156
 * @brief @p path with each part below @p store spelled as stored on disk.
1157
 *
1158
 * Where the file system ignores case, "Bank.gpg" exists while the file is
1159
 * bank.gpg, and the tree knows the entry only by that spelling.
1160
 * @param store The store folder.
1161
 * @param path An existing file in the store.
1162
 * @return @p path itself when every part is spelled as stored, otherwise
1163
 *         the path with the stored spelling.
1164
 */
1165
auto spelledAsStored(const QString &store, const QString &path) -> QString {
28 ✔
1166
  const QStringList parts = QDir(store).relativeFilePath(path).split(
56 ✔
1167
      QLatin1Char('/'), Qt::SkipEmptyParts);
28 ✔
1168
  QDir dir(store);
28 ✔
1169
  bool respelled = false;
1170
  for (int i = 0; i < parts.size(); ++i) {
31 ✔
1171
    const bool leaf = i == parts.size() - 1;
31 ✔
1172
    const QStringList names =
1173
        dir.entryList((leaf ? QDir::Files : QDir::Dirs) | QDir::Hidden |
31 ✔
1174
                      QDir::NoDotAndDotDot);
34 ✔
1175
    QString name = parts.at(i);
1176
    if (!names.contains(name)) {
31 ✔
1177
      const auto stored = std::find_if(
×
1178
          names.cbegin(), names.cend(), [&name](const QString &candidate) {
1179
            return candidate.compare(name, Qt::CaseInsensitive) == 0;
×
1180
          });
1181
      if (stored == names.cend()) {
×
1182
        return path;
1183
      }
1184
      name = *stored;
×
1185
      respelled = true;
1186
    }
1187
    if (leaf) {
31 ✔
1188
      return respelled ? QDir::cleanPath(dir.filePath(name)) : path;
56 ✔
1189
    }
1190
    if (!dir.cd(name)) {
3 ✔
1191
      return path;
1192
    }
1193
  }
1194
  return path;
1195
}
28 ✔
1196
} // namespace
1197

1198
auto MainWindow::exactMatchPath() -> QString {
47 ✔
1199
  const QString text = QDir::fromNativeSeparators(ui->lineEdit->text());
94 ✔
1200
  const QString store = QtPassSettings::getPassStore();
94 ✔
1201
  // A name may begin or end with a space: " bank" is that entry, not bank.
1202
  // Only when no entry is named so are spaces around the text dropped.
1203
  for (const QString &typed : {text, text.trimmed()}) {
181 ✔
1204
    if (typed.isEmpty()) {
68 ✔
1205
      continue;
×
1206
    }
1207
    const QString path =
1208
        QDir::cleanPath(QDir(store).filePath(typed + QStringLiteral(".gpg")));
136 ✔
1209
    if (PathValidator::isPathInStore(store, path) && QFileInfo(path).isFile()) {
68 ✔
1210
      return spelledAsStored(store, path);
28 ✔
1211
    }
1212
  }
141 ✔
1213
  return {};
19 ✔
1214
}
1215

1216
auto MainWindow::exactMatch() -> QModelIndex {
45 ✔
1217
  const QString path = exactMatchPath();
45 ✔
1218
  if (path.isEmpty()) {
45 ✔
1219
    return {};
18 ✔
1220
  }
1221
  // indexFor() maps through the filter: a row the filter hides is no match.
1222
  const QModelIndex index = m_tree->indexFor(path);
27 ✔
1223
  if (!index.isValid() || !m_tree->fileInfo(index).isFile()) {
49 ✔
1224
    return {};
5 ✔
1225
  }
1226
  return index;
22 ✔
1227
}
1228

1229
void MainWindow::applySearchText(const QString &text) {
8 ✔
1230
  // A name search: content search, left on, kept its results over the tree
1231
  // and ignored the text.
1232
  if (ui->grepButton->isChecked()) {
8 ✔
1233
    ui->grepButton->setChecked(false);
1 ✔
1234
  }
1235
  delete m_pendingOpen;
8 ✔
1236
  ui->lineEdit->setText(text);
8 ✔
1237
  // Filter now, not after the search delay: the timer would leave the tree
1238
  // as the previous text filtered it.
1239
  searchTimer.stop();
8 ✔
1240
  onTimeoutSearch();
8 ✔
1241
  if (const QModelIndex exact = exactMatch(); exact.isValid()) {
8 ✔
1242
    openExactMatch(exact);
6 ✔
1243
    return;
6 ✔
1244
  }
1245
  // The tree loads folders in the background: at start, or right after the
1246
  // window is shown again, an entry that exists may not be in it yet. Try
1247
  // again as folders finish loading, for a few seconds, unless the search
1248
  // text changes meanwhile: any change ends the wait, even one typed back to
1249
  // this text, which is a new search that has not asked to open anything.
1250
  if (exactMatchPath().isEmpty()) {
4 ✔
1251
    return;
1252
  }
1253
  auto *pending = new QObject(this);
1 ✔
1254
  m_pendingOpen = pending;
1255
  QTimer::singleShot(5000, pending, &QObject::deleteLater);
1 ✔
1256
  // Disconnected at once: with deleteLater() alone, a folder that finished
1257
  // loading before the deletion still ran the open, or ran it twice.
UNCOV
1258
  const auto stop = [this, pending] {
×
UNCOV
1259
    disconnect(&m_tree->fileSystem(), nullptr, pending, nullptr);
×
UNCOV
1260
    disconnect(ui->lineEdit, nullptr, pending, nullptr);
×
UNCOV
1261
    pending->deleteLater();
×
1262
  };
1 ✔
1263
  connect(ui->lineEdit, &QLineEdit::textChanged, pending, stop);
1 ✔
1264
  connect(&m_tree->fileSystem(), &QFileSystemModel::directoryLoaded, pending,
1 ✔
1265
          [this, stop](const QString &) {
2 ✔
1266
            searchTimer.stop();
4 ✔
1267
            onTimeoutSearch();
4 ✔
1268
            if (const QModelIndex exact = exactMatch(); exact.isValid()) {
4 ✔
UNCOV
1269
              stop();
×
UNCOV
1270
              openExactMatch(exact);
×
1271
            }
1272
          });
4 ✔
1273
}
1274

1275
void MainWindow::openExactMatch(const QModelIndex &index) {
6 ✔
1276
  // Made current here, not left to the filter pass before: the tree may have
1277
  // moved its current row since, and with none on_treeView_clicked() only
1278
  // names the entry without decrypting it.
1279
  ui->treeView->setCurrentIndex(index);
6 ✔
1280
  on_treeView_clicked(index);
6 ✔
1281
}
6 ✔
1282

1283
auto MainWindow::firstFile(QModelIndex parentIndex) -> QModelIndex {
26 ✔
1284
  StoreModel &proxy = m_tree->proxy();
26 ✔
1285
  int numRows = proxy.rowCount(parentIndex);
26 ✔
1286
  for (int row = 0; row < numRows; ++row) {
33 ✔
1287
    QModelIndex index = proxy.index(row, 0, parentIndex);
24 ✔
1288
    if (m_tree->fileInfo(index).isFile()) {
24 ✔
1289
      return index;
17 ✔
1290
    }
1291
    if (proxy.hasChildren(index)) {
14 ✔
1292
      QModelIndex childFile = firstFile(index);
9 ✔
1293
      if (childFile.isValid())
1294
        return childFile;
7 ✔
1295
    }
1296
  }
1297
  return QModelIndex();
9 ✔
1298
}
1299

1300
// Guards the input dialogs (create, move, rename) against names like
1301
// "../../etc/passwd" or absolute paths escaping the store root.
1302
auto MainWindow::confirmPathInStore(const QString &candidate) -> bool {
10 ✔
1303
  if (PathValidator::isPathInStore(QtPassSettings::getPassStore(), candidate)) {
20 ✔
1304
    return true;
1305
  }
1306
  QMessageBox::warning(this, tr("Invalid name"),
9 ✔
1307
                       tr("That name would resolve outside the password "
3 ✔
1308
                          "store. Please choose a different name."));
1309
  return false;
3 ✔
1310
}
1311

1312
void MainWindow::setPassword(const QString &file, bool isNew) {
6 ✔
1313
  const AppSettings s = QtPassSettings::load();
6 ✔
1314
  PasswordDialog d(QtPassSettings::getPass(), s, file, isNew, this);
6 ✔
1315
  // A copy out of the editor is autocleared like one from the display.
1316
  connect(&d, &PasswordDialog::copied, &m_qtPass->clipboard(),
6 ✔
1317
          &ClipboardManager::trackCopied);
6 ✔
1318

1319
  if (isNew) {
6 ✔
1320
    const QString storePath = s.passStore;
1321
    QString folder = m_tree->currentDir(false);
1 ✔
1322
    if (folder.isEmpty()) {
1 ✔
1323
      folder = storePath;
×
1324
    }
1325
    // Folders to pick from, the tree's current one preselected. Real folders
1326
    // only: a linked or junctioned one would write the entry outside the store.
1327
    QStringList folders{QString()};
2 ✔
1328
    const QStringList found = Util::directoriesUnder(storePath);
1 ✔
1329
    for (const QString &path : found) {
18 ✔
1330
      const QString rel = QDir(storePath).relativeFilePath(path);
17 ✔
1331
      if (!rel.startsWith(u'.') && !rel.contains(QStringLiteral("/."))) {
51 ✔
1332
        folders << rel;
1333
      }
1334
    }
1335
    std::sort(folders.begin() + 1, folders.end());
1 ✔
1336
    d.setNewEntryLocation(storePath, folders,
1 ✔
1337
                          QDir(storePath).relativeFilePath(folder));
2 ✔
1338
    QHash<QString, QStringList> templates =
1339
        TemplateIO::readTemplates(storePath);
1 ✔
1340
    if (!templates.isEmpty()) {
1341
      QString defaultTemplate =
1342
          TemplateIO::getFolderTemplate(folder, storePath);
1 ✔
1343
      d.setAvailableTemplates(templates, defaultTemplate);
1 ✔
1344
    }
1345
  }
1 ✔
1346

1347
  if (!d.exec()) {
6 ✔
1348
    ui->treeView->setFocus();
5 ✔
1349
  }
1350
}
6 ✔
1351

1352
void MainWindow::addPassword() { setPassword(QString()); }
2 ✔
1353

1354
auto MainWindow::confirmDeletion(const QString &file, bool isDir) -> bool {
8 ✔
1355
  const QString path = QDir::separator() + file;
8 ✔
1356
  // As the platform writes paths: backslashes only on Windows, never a mix.
1357
  // On one line: a name from the store may hold a line feed (Unix allows
1358
  // one), which drew lines of its own into the question.
1359
  const QString shown =
1360
      Util::displayable(QDir::toNativeSeparators(path), false);
8 ✔
1361
  if (!isDir) {
8 ✔
1362
    return PlainMessageBox::askYes(
2 ✔
1363
        this, tr("Delete password?"),
2 ✔
1364
        tr("Are you sure you want to delete %1?").arg(shown));
4 ✔
1365
  }
1366
  // Whole sentences, not a question stitched from pieces: a verb-final
1367
  // language cannot put the rest of the question after the path.
1368
  // Plain text, as every box quoting the store: the path is a name other
1369
  // writers control, and as rich text "a  b" would also show as "a b".
1370
  QString question =
1371
      tr("Are you sure you want to delete %1 and the whole content?")
×
1372
          .arg(shown);
6 ✔
1373
  // A link, junction or special file inside is as unexpected as a stray
1374
  // plain file: the walker leaves them out of content and reports them.
1375
  QStringList skipped;
6 ✔
1376
  QStringList unlisted;
6 ✔
1377
  const QString root = m_tree->fileSystem().rootPath();
6 ✔
1378
  const QStringList content = Util::regularFilesUnder(
18 ✔
1379
      root + path, {QStringLiteral("*")}, &skipped, false, &unlisted);
18 ✔
1380
  const bool unexpected =
1381
      !skipped.isEmpty() ||
6 ✔
1382
      std::any_of(content.cbegin(), content.cend(), [](const QString &entry) {
6 ✔
1383
        return QFileInfo(entry).suffix() != QLatin1String("gpg");
8 ✔
1384
      });
1385
  if (unexpected) {
1386
    question += QStringLiteral("\n\n") +
1 ✔
1387
                tr("Attention: there are unexpected files in the given "
1 ✔
1388
                   "folder, check them before continuing.");
1 ✔
1389
  }
1390
  // A folder the walk cannot read is not empty but unknown: whatever it
1391
  // holds goes too, or stays behind when the removal cannot list it.
1392
  if (unlisted.size() == 1) {
6 ✔
1393
    //: %1 is a folder in the password store, such as /Work/bank.
1394
    const QString one =
1395
        tr("%1 could not be read, so what it holds is unknown.")
1 ✔
1396
            .arg(Util::displayable(
1 ✔
1397
                QDir::toNativeSeparators(
1 ✔
1398
                    QDir::separator() +
1 ✔
1399
                    QDir(root).relativeFilePath(unlisted.first())),
2 ✔
1400
                false));
3 ✔
1401
    question += QStringLiteral("\n\n") + one;
2 ✔
1402
  } else if (unlisted.size() > 1) {
5 ✔
1403
    //: Only shown for two or more folders; one folder is named instead.
1404
    const QString many =
1405
        tr("%n folder(s) in it could not be read, so what they hold "
1406
           "is unknown.",
1407
           nullptr, static_cast<int>(unlisted.size()));
1 ✔
1408
    question += QStringLiteral("\n\n") + many;
2 ✔
1409
  }
1410
  return PlainMessageBox::askYes(this, tr("Delete folder?"), question);
12 ✔
1411
}
1412

1413
auto MainWindow::confirmLinkRemoval(const QString &file) -> bool {
1 ✔
1414
  // Only the link goes (ImitatePass::Remove unlinks it); nothing behind it
1415
  // is looked at or mentioned.
1416
  return PlainMessageBox::askYes(
1 ✔
1417
      this, tr("Delete link?"),
1 ✔
1418
      tr("%1 is a symbolic link or junction. Remove the link? What it "
1 ✔
1419
         "points to is left alone.")
1420
          .arg(Util::displayable(QDir::separator() + file, false)));
2 ✔
1421
}
1422

1423
void MainWindow::onDelete() {
13 ✔
1424
  const QModelIndex currentIndex = ui->treeView->currentIndex();
13 ✔
1425
  // While content search results hide the tree, its current entry is not
1426
  // what the user looks at (the Delete key comes here directly).
1427
  if (!currentIndex.isValid() || ui->treeView->isHidden()) {
11 ✔
1428
    // Otherwise the whole password directory would be deleted (#556).
1429
    return;
10 ✔
1430
  }
1431

1432
  const bool isDir = !m_tree->fileInfo(currentIndex).isFile();
9 ✔
1433
  const QString file =
1434
      isDir ? m_tree->currentDir(true) : getFile(currentIndex, true);
9 ✔
1435
  const QString folder =
1436
      m_tree->fileSystem().rootPath() + QDir::separator() + file;
9 ✔
1437
  const bool linkedFolder = isDir && Util::isLinkedFolder(folder);
9 ✔
1438

1439
  if (!linkedFolder && refuseLinkedFolder(folder)) {
8 ✔
1440
    // Behind a link: deleting would reach outside the store.
1441
    return;
1442
  }
1443
  const bool confirmed =
1444
      linkedFolder ? confirmLinkRemoval(file) : confirmDeletion(file, isDir);
9 ✔
1445
  if (!confirmed) {
9 ✔
1446
    return;
1447
  }
1448
  QtPassSettings::getPass()->Remove(file, isDir);
6 ✔
1449
}
1450

1451
void MainWindow::cancelOtpRequest() {
89 ✔
1452
  m_otpRequestFile.clear();
89 ✔
1453
  m_copyRequestFile.clear();
89 ✔
1454
}
89 ✔
1455

1456
void MainWindow::onOperationError() {
34 ✔
1457
  cancelOtpRequest();
34 ✔
1458
  // executeWrapperStarted() emptied the panel and the browser when the
1459
  // operation started (a refusal says so too); what is left to forget is
1460
  // which entry the panel was about to show.
1461
  m_shownFile.clear();
34 ✔
1462
  // A save's refresh waiting for its push is dropped: it would clear the
1463
  // push's error (or whatever failed before it) from the browser.
1464
  m_refreshAfterPush.clear();
34 ✔
1465
  m_refreshAfterPushOwner = nullptr;
1466
}
34 ✔
1467

1468
// Derives the code in-process from one decrypt, so it works with either
1469
// backend on every platform; otpFromFileToClipboard() finishes the job.
1470
void MainWindow::onOtp() {
12 ✔
1471
  if (ui->treeView->isHidden()) {
12 ✔
1472
    return;
4 ✔
1473
  }
1474
  QString file = getFile(ui->treeView->currentIndex(), true);
11 ✔
1475
  if (file.isEmpty()) {
11 ✔
1476
    flashText(tr("No password selected for OTP generation"), true);
1 ✔
1477
    return;
1 ✔
1478
  }
1479
  if (!QtPassSettings::isUseOtp()) {
10 ✔
1480
    // Normally unreachable (the action is hidden), but never fail silently.
1481
    flashText(tr("No OTP code found in this password entry"), true);
1 ✔
1482
    return;
1 ✔
1483
  }
1484

1485
  // Fast path: the panel shows a live code, so no decrypt, and one clipboard
1486
  // write (two setMimeData calls in one turn can empty the Windows
1487
  // clipboard). Only for *this* entry: arrow keys and right-click move
1488
  // currentIndex without QTreeView::clicked, so the code may be another's.
1489
  const QString shown =
1490
      (m_shownFile == file) ? m_displayPanel->currentOtpCode() : QString();
9 ✔
1491
  if (!shown.isEmpty()) {
9 ✔
1492
    m_qtPass->clipboard().copyText(shown);
1 ✔
1493
    showStatusMessage(tr("OTP code copied to clipboard"));
2 ✔
1494
    return;
1495
  }
1496

1497
  // Fallback: decrypt once. The request file keeps passShowHandler from
1498
  // copying the password and tells otpFromFileToClipboard its answer.
1499
  m_otpRequestFile = file;
8 ✔
1500
  setUiElementsEnabled(false);
8 ✔
1501
  // Keep the marker in step so a second request takes the fast path; safe as
1502
  // executeWrapperStarted() clears the panel, so a failed decrypt shows none.
1503
  m_shownFile = file;
8 ✔
1504
  QtPassSettings::getPass()->Show(file);
16 ✔
1505
}
1506

1507
void MainWindow::onEdit() {
3 ✔
1508
  if (ui->treeView->isHidden()) {
3 ✔
1509
    return;
1 ✔
1510
  }
1511
  QString file = getFile(ui->treeView->currentIndex(), true);
2 ✔
1512
  editPassword(file);
2 ✔
1513
}
1514

1515
void MainWindow::onUsers() {
2 ✔
1516
  const QString dir = m_tree->currentDir(false);
2 ✔
1517
  if (refuseLinkedFolder(dir)) {
2 ✔
1518
    return;
1519
  }
1520

1521
  UsersDialog d(QtPassSettings::getPass(), QtPassSettings::load(), dir, this);
1 ✔
1522
  if (!d.exec()) {
1 ✔
1523
    ui->treeView->setFocus();
1 ✔
1524
  }
1525
}
1 ✔
1526

1527
void MainWindow::messageAvailable(const QString &message) {
9 ✔
1528
  show();
9 ✔
1529
  raise();
9 ✔
1530
  if (message.isEmpty()) {
9 ✔
1531
    focusInput();
1 ✔
1532
  } else {
1533
    ui->treeView->expandAll();
8 ✔
1534
    applySearchText(message);
8 ✔
1535
  }
1536
}
9 ✔
1537

1538
void MainWindow::updateProfileBox() {
193 ✔
1539
  const Profiles profiles = QtPassSettings::getProfiles();
193 ✔
1540
  bool activeGone = false;
1541

1542
  if (profiles.isEmpty()) {
7 ✔
1543
    ui->profileWidget->hide();
186 ✔
1544
  } else {
1545
    ui->profileWidget->show();
7 ✔
1546
    // A refill is no choice of the user's: clearing and adding items moves
1547
    // the current text, which would otherwise switch profiles.
1548
    const QSignalBlocker quiet(ui->profileBox);
7 ✔
1549
    ui->profileBox->clear();
7 ✔
1550
    for (auto i = profiles.cbegin(); i != profiles.cend(); ++i) {
19 ✔
1551
      if (!i.key().isEmpty()) {
12 ✔
1552
        ui->profileBox->addItem(i.key());
12 ✔
1553
      }
1554
    }
1555
    ui->profileBox->model()->sort(0);
7 ✔
1556
    int index = ui->profileBox->findText(QtPassSettings::getProfile());
14 ✔
1557
    if (index != -1) { //  -1 for not found
7 ✔
1558
      ui->profileBox->setCurrentIndex(index);
6 ✔
1559
    } else if (ui->profileBox->count() > 0) {
1 ✔
1560
      // The active profile is gone (removed in Settings): the box shows the
1561
      // first one, and the settings and backend must follow it, or the
1562
      // removed profile's store stays in use behind it.
1563
      ui->profileBox->setCurrentIndex(0);
1 ✔
1564
      activeGone = true;
1565
    }
1566
  }
7 ✔
1567
  if (activeGone) {
7 ✔
1568
    on_profileBox_currentTextChanged(ui->profileBox->currentText());
2 ✔
1569
  }
1570
  updateProfileBoxEnabled();
193 ✔
1571
}
193 ✔
1572

1573
void MainWindow::updateProfileBoxEnabled() {
643 ✔
1574
  // No profile switch while anything of the store runs or waits: the
1575
  // backend's store and environment would change under it, and what is
1576
  // still queued (a push after a save, say) would finish for the other
1577
  // profile (#2071). Asked of the backend, not only of the interface: the
1578
  // watchdog releases the interface while a slow gpg or git still runs.
1579
  // Every backend: one kept from before a switch of backend may still
1580
  // run what was queued on it.
1581
  ui->profileBox->setEnabled(m_uiEnabled && ui->profileBox->count() > 1 &&
1,287 ✔
1582
                             QtPassSettings::backendsIdle());
11 ✔
1583
}
643 ✔
1584

1585
void MainWindow::on_profileBox_currentTextChanged(const QString &name) {
6 ✔
1586
  if (m_freshStart || name == QtPassSettings::getProfile()) {
18 ✔
1587
    return;
1 ✔
1588
  }
1589
  // The box is disabled while anything runs; should a change come through
1590
  // anyway, the active profile stays and the box says so again.
1591
  if (!m_uiEnabled || !QtPassSettings::backendsIdle()) {
5 ✔
1592
    const QSignalBlocker quiet(ui->profileBox);
×
1593
    ui->profileBox->setCurrentText(QtPassSettings::getProfile());
×
1594
    return;
1595
  }
×
1596
  // A content search runs outside the queue: leaving grep mode cancels it,
1597
  // so its results for the old store are dropped, not shown for the new.
1598
  if (m_grep.inGrepMode()) {
5 ✔
1599
    ui->grepButton->setChecked(false);
1 ✔
1600
  }
1601

1602
  ui->lineEdit->clear();
5 ✔
1603

1604
  const Profile prof = QtPassSettings::getProfiles().value(name);
10 ✔
1605
  AppSettings s = QtPassSettings::load();
5 ✔
1606
  s.activeProfile = name;
5 ✔
1607
  s.passStore = prof.path;
5 ✔
1608
  s.passSigningKey = prof.signingKey;
5 ✔
1609
  // A profile without its own Git flags keeps the global values.
1610
  s.useGit = prof.useGit.value_or(s.useGit);
5 ✔
1611
  s.autoPush = prof.autoPush.value_or(s.autoPush);
5 ✔
1612
  s.autoPull = prof.autoPull.value_or(s.autoPull);
5 ✔
1613
  QtPassSettings::save(s);
5 ✔
1614
  ui->statusBar->showMessage(tr("Profile changed to %1").arg(name), 2000);
10 ✔
1615

1616
  QtPassSettings::getPass()->updateEnv();
5 ✔
1617

1618
  m_tree->setStore(QtPassSettings::getPassStore());
10 ✔
1619
  deselect();
5 ✔
1620
  ui->treeView->setCurrentIndex(QModelIndex());
5 ✔
1621
}
5 ✔
1622

1623
void MainWindow::initTrayIcon() {
3 ✔
1624
  m_tray = new TrayIcon(this);
3 ✔
1625
  if (!m_tray->getIsAllocated()) {
3 ✔
1626
    destroyTrayIcon();
3 ✔
1627
    return;
3 ✔
1628
  }
1629
#ifndef Q_OS_MACOS
1630
  m_tray->addToggle(ui->actionShowMenuBar);
×
1631
#endif
1632
}
1633

1634
void MainWindow::destroyTrayIcon() {
3 ✔
1635
  delete m_tray;
3 ✔
1636
  m_tray = nullptr;
3 ✔
1637
}
3 ✔
1638

1639
void MainWindow::closeEvent(QCloseEvent *event) {
4 ✔
1640
  // Save in both branches: a tray user only ever hides the window, and
1641
  // used to quit through the tray menu with nothing ever written.
1642
  saveWindowState();
4 ✔
1643
  // Only with a tray icon to come back from: without one (none asked for, or
1644
  // no system tray in this session) a hidden QtPass ran on invisibly, with the
1645
  // last entry in its window and the password on the clipboard.
1646
  if (QtPassSettings::isHideOnClose() && m_tray != nullptr) {
8 ✔
1647
    this->hide();
×
1648
    event->ignore();
1649
  } else {
1650
    m_qtPass->clipboard().clear();
4 ✔
1651
    event->accept();
1652
    // A visible QSystemTrayIcon keeps the application alive, so
1653
    // quitOnLastWindowClosed never fires; quit explicitly.
1654
    QApplication::quit();
4 ✔
1655
  }
1656
}
4 ✔
1657

1658
auto MainWindow::eventFilter(QObject *obj, QEvent *event) -> bool {
7,805 ✔
1659
  if ((obj == ui->toolBar || obj == menuBar()) &&
7,805 ✔
1660
      event->type() == QEvent::PaletteChange) {
1661
    // Breeze gives these bars a "header" palette and, after a runtime
1662
    // light/dark switch, stamps the previous theme's colours back from a
1663
    // cached kdeglobals, hiding the toolbar icons. Deferred so we never
1664
    // re-enter the style while it is still applying its palette.
1665
    QTimer::singleShot(0, this, &MainWindow::dropStaleToolsAreaPalettes);
36 ✔
1666
  }
1667
  if (obj == ui->lineEdit && event->type() == QEvent::KeyPress) {
7,805 ✔
1668
    auto *key = dynamic_cast<QKeyEvent *>(event);
5 ✔
1669
    if (key != nullptr && key->key() == Qt::Key_Down) {
5 ✔
1670
      // Into whichever list is in sight: the tree, or content search results.
1671
      // Focus makes the list's first item current.
1672
      if (ui->treeView->isHidden()) {
2 ✔
1673
        ui->grepResultsList->setFocus();
1 ✔
1674
      } else {
1675
        ui->treeView->setFocus();
1 ✔
1676
      }
1677
    }
1678
    // Return ends at the search box: QLineEdit emits returnPressed() and
1679
    // leaves the key unaccepted, so keyPressEvent() would open the tree's
1680
    // current entry as well. In content search that is an entry nobody
1681
    // asked for; by name, the first hit a second time.
1682
    if (key != nullptr &&
5 ✔
1683
        (key->key() == Qt::Key_Return || key->key() == Qt::Key_Enter)) {
2 ✔
1684
      ui->lineEdit->event(event);
3 ✔
1685
      event->accept();
1686
      return true;
3 ✔
1687
    }
1688
  }
1689
  return QObject::eventFilter(obj, event);
7,802 ✔
1690
}
1691

1692
// Only once the application palette changed (see m_themeSwitched): a bar
1693
// whose active Window lightness is far from the application's shows the
1694
// other theme.
1695
void MainWindow::dropStaleToolsAreaPalettes() {
31 ✔
1696
  if (!m_themeSwitched) {
31 ✔
1697
    return;
1698
  }
1699
  constexpr int kStaleToolsAreaLightness = 64;
1700
  // The active group on both sides: a bar's palette() reads the inactive
1701
  // group while another window has focus (the settings app, during a theme
1702
  // switch), and Breeze gives the header set different inactive colours.
1703
  const int appLightness = QApplication::palette()
54 ✔
1704
                               .color(QPalette::Active, QPalette::Window)
1705
                               .lightness();
27 ✔
1706
  for (QWidget *bar : {static_cast<QWidget *>(ui->toolBar),
108 ✔
1707
                       static_cast<QWidget *>(menuBar())}) {
81 ✔
1708
    if (!bar->testAttribute(Qt::WA_SetPalette)) {
54 ✔
1709
      continue;
48 ✔
1710
    }
1711
    const int barLightness =
1712
        bar->palette().color(QPalette::Active, QPalette::Window).lightness();
12 ✔
1713
    if (qAbs(barLightness - appLightness) <= kStaleToolsAreaLightness) {
6 ✔
1714
      continue;
2 ✔
1715
    }
1716
    bar->setPalette(QPalette());
4 ✔
1717
    // Both bars are transparent and the style paints the tools area from the
1718
    // stale palette, so fill our own. Window, not their Button role, which is
1719
    // not the window colour in either theme.
1720
    bar->setBackgroundRole(QPalette::Window);
4 ✔
1721
    bar->setAutoFillBackground(true);
4 ✔
1722
  }
1723
}
1724

1725
void MainWindow::keyPressEvent(QKeyEvent *event) {
25 ✔
1726
  switch (event->key()) {
25 ✔
1727
  case Qt::Key_Delete:
2 ✔
1728
    onDelete();
2 ✔
1729
    break;
2 ✔
1730
  case Qt::Key_Return:
2 ✔
1731
  case Qt::Key_Enter:
1732
    // While content search results hide the tree, its current entry is not
1733
    // what the user looks at: Return on a result opens that result.
1734
    if (ui->treeView->isHidden()) {
2 ✔
1735
      QTreeWidgetItem *result = ui->grepResultsList->currentItem();
1 ✔
1736
      if (result != nullptr && ui->grepResultsList->hasFocus()) {
1 ✔
1737
        on_grepResultsList_itemClicked(result, 0);
1 ✔
1738
      }
1739
      break;
1740
    }
1741
    if (m_tree->proxy().rowCount() > 0) {
1 ✔
1742
      on_treeView_clicked(ui->treeView->currentIndex());
1 ✔
1743
    }
1744
    break;
1745
  case Qt::Key_Escape:
3 ✔
1746
    ui->lineEdit->clear();
3 ✔
1747
    break;
3 ✔
1748
  default:
1749
    break;
1750
  }
1751
}
25 ✔
1752

1753
void MainWindow::addShareMenu(QMenu &contextMenu, const AppSettings &s) {
10 ✔
1754
  const QString dirPath = QDir::cleanPath(m_tree->currentDir(false));
10 ✔
1755
  auto *shareMenu = new QMenu(tr("Share"), &contextMenu);
10 ✔
1756
  contextMenu.addMenu(shareMenu);
10 ✔
1757

1758
  const QString gpgIdPath = Pass::getGpgIdPath(dirPath, s.passStore);
10 ✔
1759
  const bool gpgIdExists = !gpgIdPath.isEmpty() && QFile(gpgIdPath).exists();
10 ✔
1760
  const QString exePath = s.usePass ? s.passExecutable : s.gpgExecutable;
10 ✔
1761
  const bool gpgAvailable =
1762
      !exePath.isEmpty() &&
20 ✔
1763
      (Executor::parseWslCommand(exePath) || QFile(exePath).exists());
20 ✔
1764

1765
  QAction *reencrypt = shareMenu->addAction(tr("Re-encrypt all passwords"));
10 ✔
1766
  reencrypt->setEnabled(gpgIdExists && gpgAvailable);
10 ✔
1767
  connect(reencrypt, &QAction::triggered, this,
10 ✔
1768
          [this, dirPath]() { reencryptPath(dirPath); });
34 ✔
1769

1770
  QAction *exportKey = shareMenu->addAction(tr("Export my public key..."));
10 ✔
1771
  exportKey->setEnabled(gpgAvailable);
10 ✔
1772
  connect(exportKey, &QAction::triggered, this, &MainWindow::exportPublicKey);
10 ✔
1773

1774
  QAction *addRecipientAction = shareMenu->addAction(tr("Add recipient..."));
10 ✔
1775
  addRecipientAction->setEnabled(gpgIdExists && gpgAvailable);
10 ✔
1776
  connect(addRecipientAction, &QAction::triggered, this,
10 ✔
1777
          [this, dirPath]() { addRecipient(dirPath); });
32 ✔
1778

1779
  QAction *shareHelp = shareMenu->addAction(tr("What is this?"));
10 ✔
1780
  connect(shareHelp, &QAction::triggered, this, &MainWindow::showShareHelp);
10 ✔
1781
}
10 ✔
1782

1783
void MainWindow::showContextMenu(const QPoint &pos) {
12 ✔
1784
  const AppSettings s = QtPassSettings::load();
12 ✔
1785
  const QModelIndex index = ui->treeView->indexAt(pos);
12 ✔
1786
  const bool selected = index.isValid();
1787
  if (!selected) {
1788
    ui->treeView->clearSelection();
1 ✔
1789
    ui->actionDelete->setEnabled(false);
1 ✔
1790
    ui->actionEdit->setEnabled(false);
1 ✔
1791
  }
1792
  ui->treeView->setCurrentIndex(index);
12 ✔
1793
  const QPoint globalPos = ui->treeView->viewport()->mapToGlobal(pos);
12 ✔
1794
  const QFileInfo fileOrFolder = m_tree->fileInfo(ui->treeView->currentIndex());
12 ✔
1795
  const bool isDir = fileOrFolder.isDir();
12 ✔
1796

1797
  QMenu contextMenu;
12 ✔
1798
  if (!selected || isDir) {
12 ✔
1799
    const std::array<std::pair<QString, void (MainWindow::*)()>, 4> onFolder{{
1800
        {tr("Open folder with file manager"), &MainWindow::openFolder},
11 ✔
1801
        {tr("Add folder"), &MainWindow::addFolder},
11 ✔
1802
        {tr("Add password"), &MainWindow::addPassword},
11 ✔
1803
        {tr("Users"), &MainWindow::onUsers},
11 ✔
1804
    }};
×
1805
    for (const auto &[text, slot] : onFolder) {
55 ✔
1806
      connect(contextMenu.addAction(text), &QAction::triggered, this, slot);
44 ✔
1807
    }
1808
  } else if (fileOrFolder.isFile()) {
1 ✔
1809
    connect(contextMenu.addAction(tr("Edit")), &QAction::triggered, this,
1 ✔
1810
            &MainWindow::onEdit);
2 ✔
1811
  }
1812
  if (selected) {
12 ✔
1813
    contextMenu.addSeparator();
11 ✔
1814
    if (isDir) {
11 ✔
1815
      connect(contextMenu.addAction(tr("Rename folder")), &QAction::triggered,
10 ✔
1816
              this, &MainWindow::renameFolder);
20 ✔
1817
    } else if (fileOrFolder.isFile()) {
1 ✔
1818
      connect(contextMenu.addAction(tr("Rename password")), &QAction::triggered,
1 ✔
1819
              this, &MainWindow::renamePassword);
2 ✔
1820
    }
1821
    connect(contextMenu.addAction(tr("Delete")), &QAction::triggered, this,
11 ✔
1822
            &MainWindow::onDelete);
11 ✔
1823
    if (isDir) {
11 ✔
1824
      addShareMenu(contextMenu, s);
10 ✔
1825
    }
1826
  }
1827
  contextMenu.exec(globalPos);
12 ✔
1828
}
12 ✔
1829

1830
auto MainWindow::browserContextMenu(const QPoint &pos) -> QMenu * {
3 ✔
1831
  // createStandardContextMenu() takes document coordinates, anchorAt() and
1832
  // the menu's place viewport ones: scrolled, the menu checked the text
1833
  // above the link and left "Copy Link Location" disabled.
1834
  // Right to left, the horizontal offset counts from the other end.
1835
  const QScrollBar *across = ui->textBrowser->horizontalScrollBar();
3 ✔
1836
  const int dx = ui->textBrowser->isRightToLeft()
3 ✔
1837
                     ? across->maximum() - across->value()
3 ✔
1838
                     : across->value();
3 ✔
1839
  const QPoint documentPos =
1840
      pos + QPoint(dx, ui->textBrowser->verticalScrollBar()->value());
3 ✔
1841
  QMenu *contextMenu = ui->textBrowser->createStandardContextMenu(documentPos);
3 ✔
1842
  // Reparent from textBrowser: a browser stylesheet cascades to the child
1843
  // QMenu and breaks its opaque native background.
1844
  contextMenu->setParent(this, contextMenu->windowFlags());
3 ✔
1845
  if (auto *copyLink =
3 ✔
1846
          contextMenu->findChild<QAction *>(QStringLiteral("link-copy"))) {
3 ✔
1847
    const QString link = ui->textBrowser->anchorAt(pos);
3 ✔
1848
    disconnect(copyLink, &QAction::triggered, nullptr, nullptr);
3 ✔
1849
    connect(copyLink, &QAction::triggered, this, [this, link] {
10 ✔
1850
      if (!link.isEmpty()) {
1 ✔
1851
        m_qtPass->clipboard().copyText(link);
1 ✔
1852
      }
1853
    });
1 ✔
1854
  }
1855
  return contextMenu;
3 ✔
1856
}
1857

1858
void MainWindow::showBrowserContextMenu(const QPoint &pos) {
1 ✔
1859
  QMenu *contextMenu = browserContextMenu(pos);
1 ✔
1860
  contextMenu->exec(ui->textBrowser->viewport()->mapToGlobal(pos));
1 ✔
1861
  delete contextMenu;
1 ✔
1862
}
1 ✔
1863

1864
void MainWindow::openFolder() {
1 ✔
1865
  QString dir = m_tree->currentDir(false);
1 ✔
1866

1867
  QString path = QDir::toNativeSeparators(dir);
1 ✔
1868
  QDesktopServices::openUrl(QUrl::fromLocalFile(path));
1 ✔
1869
}
1 ✔
1870

1871
void MainWindow::addFolder() {
7 ✔
1872
  const AppSettings s = QtPassSettings::load();
7 ✔
1873
  bool ok;
1874
  QString dir = m_tree->currentDir(false);
7 ✔
1875
  QString newdir =
1876
      QInputDialog::getText(this, tr("New folder"),
7 ✔
1877
                            tr("New folder: \n(Will be placed in %1 )")
7 ✔
1878
                                .arg(s.passStore + m_tree->currentDir(true)),
14 ✔
1879
                            QLineEdit::Normal, "", &ok);
14 ✔
1880
  if (!ok || newdir.isEmpty()) {
7 ✔
1881
    return;
1882
  }
1883
  // Checked and created as one and the same path: the check resolves ".."
1884
  // lexically, the system after following links, so "link/../x" would pass
1885
  // as the store's x and be made beside the link's target.
1886
  newdir = QDir::cleanPath(newdir.prepend(dir));
6 ✔
1887
  if (!confirmPathInStore(newdir)) {
6 ✔
1888
    return;
1889
  }
1890
  // Behind a link the folder would be made outside the store, as Users,
1891
  // Re-encrypt and Delete already refuse.
1892
  if (refuseLinkedFolder(newdir)) {
5 ✔
1893
    return;
1894
  }
1895
  // The tree, like `pass ls`, hides names that start with a dot.
1896
  const QStringList parts =
1897
      QDir(s.passStore).relativeFilePath(newdir).split(u'/');
4 ✔
1898
  if (std::any_of(parts.cbegin(), parts.cend(), [](const QString &part) {
8 ✔
1899
        return part != u'.' && part.startsWith(u'.');
4 ✔
1900
      })) {
1901
    PlainMessageBox::warning(this, tr("Hidden folder"),
2 ✔
1902
                             tr("A folder that starts with a dot would be "
1 ✔
1903
                                "hidden from the list: %1")
1904
                                 .arg(newdir));
2 ✔
1905
    return;
1 ✔
1906
  }
1907
  // Exists already: an error, as QDir::mkdir() made it before.
1908
  if (QFileInfo::exists(newdir) || !Util::mkpathForStore(newdir)) {
3 ✔
1909
    PlainMessageBox::warning(this, tr("Error"),
2 ✔
1910
                             tr("Failed to create folder: %1").arg(newdir));
2 ✔
1911
    return;
1 ✔
1912
  }
1913
  // No .gpg-id of its own: the folder uses its parent's recipients, as with
1914
  // pass, until Users gives it a list. A copy of the parent's list (#1688)
1915
  // kept every recipient later removed above it, and its entries stayed
1916
  // readable by them.
1917
}
7 ✔
1918

1919
void MainWindow::renameFolder() {
3 ✔
1920
  bool ok;
1921
  QString srcDir = QDir::cleanPath(m_tree->currentDir(false));
3 ✔
1922
  QString srcDirName = QDir(srcDir).dirName();
3 ✔
1923
  QString newName =
1924
      QInputDialog::getText(this, tr("Rename folder"), tr("Rename folder to: "),
3 ✔
1925
                            QLineEdit::Normal, srcDirName, &ok);
6 ✔
1926
  if (!ok || newName.isEmpty()) {
3 ✔
1927
    return;
1928
  }
1929
  QString destDir = srcDir;
1930
  destDir.replace(srcDir.lastIndexOf(srcDirName), srcDirName.length(), newName);
2 ✔
1931
  if (!confirmPathInStore(destDir)) {
2 ✔
1932
    return;
1933
  }
1934
  QtPassSettings::getPass()->Move(srcDir, destDir, false);
3 ✔
1935
}
1936

1937
void MainWindow::editPassword(const QString &file) {
5 ✔
1938
  if (!file.isEmpty()) {
5 ✔
1939
    const AppSettings s = QtPassSettings::load();
5 ✔
1940
    if (s.useGit && s.autoPull) {
5 ✔
1941
      onUpdate(true);
1 ✔
1942
    }
1943
    // The dialog decrypts the entry itself to fill its fields. That decrypt
1944
    // lands on the same finishedShow the panel uses, so drop the panel's claim
1945
    // to it: otherwise passShowHandler() repaints and, with "Always copy",
1946
    // puts the entry's old password on the clipboard - replacing whatever the
1947
    // user copied to paste into the dialog.
1948
    m_shownFile.clear();
5 ✔
1949
    setPassword(file, false);
5 ✔
1950
  }
5 ✔
1951
}
5 ✔
1952

1953
void MainWindow::renamePassword() {
2 ✔
1954
  bool ok;
1955
  QString file = getFile(ui->treeView->currentIndex(), false);
2 ✔
1956
  QString filePath = QFileInfo(file).path();
2 ✔
1957
  QString fileName = QFileInfo(file).fileName();
2 ✔
1958
  if (fileName.endsWith(".gpg", Qt::CaseInsensitive)) {
4 ✔
1959
    fileName.chop(4);
2 ✔
1960
  }
1961

1962
  QString newName =
1963
      QInputDialog::getText(this, tr("Rename file"), tr("Rename file to: "),
2 ✔
1964
                            QLineEdit::Normal, fileName, &ok);
4 ✔
1965
  if (!ok || newName.isEmpty()) {
2 ✔
1966
    return;
1967
  }
1968
  QString newFile = QDir(filePath).filePath(newName);
2 ✔
1969
  if (!confirmPathInStore(newFile)) {
2 ✔
1970
    return;
1971
  }
1972
  QtPassSettings::getPass()->Move(file, newFile, false);
3 ✔
1973
}
1974

1975
void MainWindow::copySelectionOrPassword() {
5 ✔
1976
  QWidget *focus = QApplication::focusWidget();
5 ✔
1977
  // The widget's own copy: a SecretTextBrowser marks what it copies as
1978
  // secret for clipboard managers, as the context menu's Copy does.
1979
  if (auto *text = qobject_cast<QTextEdit *>(focus);
5 ✔
1980
      text != nullptr && text->textCursor().hasSelection()) {
5 ✔
1981
    text->copy();
1 ✔
1982
    return;
1 ✔
1983
  }
1984
  // Through the clipboard manager, as a copy button would: the label may be
1985
  // the OTP code, which gets the secret hint and the autoclear.
1986
  if (auto *label = qobject_cast<QLabel *>(focus);
1987
      label != nullptr && label->hasSelectedText()) {
4 ✔
1988
    m_qtPass->clipboard().copyText(label->selectedText());
1 ✔
1989
    return;
1 ✔
1990
  }
1991
  // A line of the content search results is decrypted text: through the
1992
  // clipboard manager too, for the secret hint and the autoclear.
1993
  if (focus == ui->grepResultsList) {
3 ✔
1994
    if (const QTreeWidgetItem *item = ui->grepResultsList->currentItem();
3 ✔
1995
        item != nullptr && !item->text(0).isEmpty()) {
6 ✔
1996
      m_qtPass->clipboard().copyText(item->text(0));
6 ✔
1997
    }
1998
    return;
3 ✔
1999
  }
2000
  copyPasswordFromTreeview();
×
2001
}
2002

2003
void MainWindow::copyPasswordFromTreeview() {
9 ✔
2004
  // While content search results hide the tree, its current entry is not
2005
  // what the user looks at: no decrypt, as for Edit and OTP.
2006
  if (ui->treeView->isHidden()) {
9 ✔
2007
    return;
×
2008
  }
2009
  QFileInfo fileOrFolder = m_tree->fileInfo(ui->treeView->currentIndex());
9 ✔
2010

2011
  if (fileOrFolder.isFile()) {
9 ✔
2012
    QString file = getFile(ui->treeView->currentIndex(), true);
9 ✔
2013
    // The newest Ctrl+C wins: finishedShow names its file, so the decrypt of
2014
    // an earlier request is simply not this one's.
2015
    m_copyRequestFile = file;
9 ✔
2016
    // This Show repaints the panel as well; see onOtp().
2017
    m_shownFile = file;
9 ✔
2018
    QtPassSettings::getPass()->Show(file);
18 ✔
2019
  }
2020
}
9 ✔
2021

2022
void MainWindow::passwordFromFileToClipboard(const QString &text,
29 ✔
2023
                                             const QString &file) {
2024
  if (m_copyRequestFile.isEmpty() || file != m_copyRequestFile) {
29 ✔
2025
    return;
24 ✔
2026
  }
2027
  m_copyRequestFile.clear();
8 ✔
2028
  // The first line, without a list of every line (an entry can expand into
2029
  // millions of them), and without the "\r" of a CRLF line end, as the
2030
  // password row and "Always copy" have it.
2031
  const QString first = FileContent::passwordLine(text);
8 ✔
2032
  // A `pass otp insert` entry's first line is the otpauth:// URI carrying the
2033
  // TOTP seed, and an OTP field holding a seed there is the same; copying it
2034
  // would leak 2FA material. Matches the display path
2035
  // (FileContent::getPasswordForDisplay / PasswordDisplayPanel).
2036
  if (FileContent::isOtpPasswordLine(first)) {
8 ✔
2037
    flashText(tr("This entry holds an OTP secret, not a password"), true);
6 ✔
2038
    return;
2039
  }
2040
  m_qtPass->clipboard().copyText(first);
5 ✔
2041
}
2042

2043
void MainWindow::showStatusMessage(const QString &msg, int timeout) {
34 ✔
2044
  ui->statusBar->showMessage(msg, timeout);
34 ✔
2045
}
34 ✔
2046

2047
void MainWindow::reencryptPath(const QString &dir) {
4 ✔
2048
  QDir checkDir(dir);
4 ✔
2049
  if (!checkDir.exists()) {
4 ✔
2050
    PlainMessageBox::critical(this, tr("Error"),
2 ✔
2051
                              tr("Directory does not exist: %1").arg(dir));
2 ✔
2052
    return;
1 ✔
2053
  }
2054
  if (refuseLinkedFolder(dir)) {
3 ✔
2055
    return;
2056
  }
2057

2058
  const bool yes = PlainMessageBox::askYes(
3 ✔
2059
      this, tr("Re-encrypt passwords"),
3 ✔
2060
      tr("Re-encrypt all passwords in %1?\n\n"
3 ✔
2061
         "This will re-encrypt ALL password files in this folder "
2062
         "using the current recipients defined in .gpg-id.\n\n"
2063
         "This may rewrite many files and cannot be undone easily.\n\n"
2064
         "Continue?")
2065
          // On one line: a name with line feeds pushed the warning out of
2066
          // the box, which shows 40 lines at most.
2067
          .arg(Util::displayable(QDir(dir).dirName(), false)));
6 ✔
2068

2069
  if (!yes)
3 ✔
2070
    return;
2071

2072
  // Disable now; the asynchronous startReencryptPath signal re-runs this
2073
  // harmlessly.
2074
  startReencryptPath();
1 ✔
2075

2076
  // Under the current profile's settings: with the pass backend active, the
2077
  // native one is not re-initialised on a profile switch.
2078
  QtPassSettings::getImitatePass()->reencryptPath(
2 ✔
2079
      QDir::cleanPath(QDir(dir).absolutePath()), QtPassSettings::load());
2 ✔
2080
}
4 ✔
2081

2082
// Idempotent: reencryptPath() calls it before ImitatePass emits the signal.
2083
void MainWindow::startReencryptPath() {
7 ✔
2084
  m_reencryptRunning = true;
7 ✔
2085
  setUiElementsEnabled(false);
7 ✔
2086
  // The worker always ends with endReencryptPath(), and Cancel is available
2087
  // throughout, so the generic watchdog is not needed for this operation.
2088
  m_uiWatchdog.stop();
7 ✔
2089
  ui->treeView->setDisabled(true);
7 ✔
2090
  if (m_reencryptProgress)
7 ✔
2091
    return;
2092
  auto *progress = new QProgressDialog(tr("Re-encrypting passwords..."),
5 ✔
2093
                                       tr("Cancel"), 0, 0, this);
10 ✔
2094
  progress->setWindowTitle(tr("Re-encrypt passwords"));
5 ✔
2095
  progress->setWindowModality(Qt::WindowModal);
5 ✔
2096
  progress->setAutoClose(false);
5 ✔
2097
  progress->setAutoReset(false);
5 ✔
2098
  progress->setMinimumDuration(0);
5 ✔
2099
  connect(progress, &QProgressDialog::canceled, this, [this]() {
5 ✔
2100
    QtPassSettings::getImitatePass()->cancelReencryptPath();
1 ✔
2101
    showStatusMessage(tr("Cancelling re-encryption"), 5000);
1 ✔
2102
  });
1 ✔
2103
  m_reencryptProgress = progress;
2104
  progress->show();
5 ✔
2105
}
2106

2107
void MainWindow::reencryptProgress(int current, int total) {
7 ✔
2108
  if (!m_reencryptProgress || m_inProgressUpdate)
7 ✔
2109
    return;
2110
  QProgressDialog *progress = m_reencryptProgress;
2111
  progress->setMaximum(total);
6 ✔
2112
  progress->setLabelText(
6 ✔
2113
      tr("Re-encrypting passwords: %1 of %2").arg(current).arg(total));
6 ✔
2114
  // On a modal dialog setValue() runs processEvents(), which can deliver
2115
  // endReencryptPath(), even inside a nested event loop that would delete a
2116
  // deleteLater()ed dialog under setValue()'s feet: keep this last, and
2117
  // delete the dialog only after it returns.
2118
  m_inProgressUpdate = true;
6 ✔
2119
  progress->setValue(current);
6 ✔
2120
  m_inProgressUpdate = false;
6 ✔
2121
  if (m_progressToDelete) {
6 ✔
2122
    m_progressToDelete->deleteLater();
2 ✔
2123
    m_progressToDelete = nullptr;
2124
  }
2125
}
2126

2127
void MainWindow::endReencryptPath() {
5 ✔
2128
  m_reencryptRunning = false;
5 ✔
2129
  if (m_reencryptProgress) {
5 ✔
2130
    m_reencryptProgress->hide();
5 ✔
2131
    if (m_inProgressUpdate) {
5 ✔
2132
      m_progressToDelete = m_reencryptProgress;
2133
    } else {
2134
      m_reencryptProgress->deleteLater();
3 ✔
2135
    }
2136
    m_reencryptProgress = nullptr;
2137
  }
2138
  setUiElementsEnabled(true);
5 ✔
2139
}
5 ✔
2140

2141
void MainWindow::exportPublicKey() {
3 ✔
2142
  const AppSettings s = QtPassSettings::load();
3 ✔
2143
  const QString identity = s.passSigningKey;
2144
  if (identity.isEmpty()) {
3 ✔
2145
    QMessageBox::information(
2 ✔
2146
        this, tr("Export public key"),
1 ✔
2147
        tr("<h3>Export your public key</h3>"
×
2148
           "<p>No signing key is configured. Set one in QtPass Settings "
2149
           "&gt; GPG keys, or run this in a terminal:</p>"
2150
           "<pre>gpg --armor --export --output my_key.asc &lt;your-key-id"
2151
           "&gt;</pre>"
2152
           "<p>Then send the file to your teammates.</p>"));
2153
    return;
1 ✔
2154
  }
2155
  QString gpgExe = s.gpgExecutable;
2156
  if (gpgExe.isEmpty()) {
2 ✔
2157
    gpgExe = QStringLiteral("gpg");
×
2158
  }
2159
  QStringList args = {"--armor", "--export"};
10 ✔
2160
  args.append(identity.split(' ', Qt::SkipEmptyParts));
2 ✔
2161
  QString stdOut;
2 ✔
2162
  QString stdErr;
2 ✔
2163
  int exitCode = Executor::executeBlocking(gpgExe, args, &stdOut, &stdErr);
2 ✔
2164
  if (exitCode != 0 || stdOut.isEmpty()) {
2 ✔
2165
    PlainMessageBox::warning(this, tr("Export public key"),
2 ✔
2166
                             tr("Could not export public key for %1.\n\n%2")
1 ✔
2167
                                 .arg(identity, stdErr.isEmpty()
2 ✔
2168
                                                    ? tr("No output from gpg.")
2 ✔
2169
                                                    : stdErr));
2170
    return;
2171
  }
2172
  ExportPublicKeyDialog dialog(identity, stdOut, this);
1 ✔
2173
  dialog.exec();
1 ✔
2174
}
4 ✔
2175

2176
// UsersDialog only ticks keys already in the keyring; importing a foreign
2177
// key still has to happen via gpg (or QtPass settings) first.
2178
void MainWindow::addRecipient(const QString &dir) {
2 ✔
2179
  if (refuseLinkedFolder(dir)) {
2 ✔
2180
    return;
1 ✔
2181
  }
2182
  UsersDialog d(QtPassSettings::getPass(), QtPassSettings::load(), dir, this);
1 ✔
2183
  d.exec();
1 ✔
2184
}
1 ✔
2185

2186
// A tree-picked folder that is, or lies behind, a symlink or junction is not
2187
// a folder of the store. The store root itself may be a link (a synced
2188
// folder); that is configuration, not a tree pick.
2189
auto MainWindow::refuseLinkedFolder(const QString &dir) -> bool {
20 ✔
2190
  if (!Util::isUnderLink(dir, QtPassSettings::load().passStore)) {
20 ✔
2191
    return false;
2192
  }
2193
  PlainMessageBox::critical(
3 ✔
2194
      this, tr("Not a folder of the store"),
3 ✔
2195
      tr("%1 is, or lies behind, a symbolic link or junction. What that "
3 ✔
2196
         "points to is not part of the password store and is left alone.")
2197
          .arg(QDir::toNativeSeparators(QDir::cleanPath(dir))));
6 ✔
2198
  return true;
3 ✔
2199
}
2200

2201
void MainWindow::showShareHelp() {
1 ✔
2202
  QMessageBox::information(
2 ✔
2203
      this, tr("Sharing passwords with GPG"),
1 ✔
2204
      tr("<h3>Sharing passwords with GPG</h3>"
1 ✔
2205
         "<p>To share passwords with other users:</p>"
2206
         "<ol>"
2207
         "<li><b>Export your public key</b> and send it to teammates</li>"
2208
         "<li><b>Import teammates' public keys</b> into your GPG keyring</li>"
2209
         "<li><b>Re-encrypt passwords</b> so all recipients can decrypt "
2210
         "them</li>"
2211
         "</ol>"
2212
         "<p>Only people who have a matching secret key can decrypt the "
2213
         "passwords.</p>"
2214
         "<p><b>Tip:</b> Use the same GPG key for all shared folders.</p>"
2215
         "<p>See the FAQ for more details.</p>"));
2216
}
1 ✔
2217

2218
void MainWindow::updateGitButtonVisibility(bool uiEnabled) {
415 ✔
2219
  const AppSettings s = QtPassSettings::load();
415 ✔
2220
  // Without Git there is nothing to push or pull, ever: the buttons go, not
2221
  // grey out. While an operation runs they stay and are disabled.
2222
  const bool usable =
2223
      s.useGit && !(s.gitExecutable.isEmpty() && s.passExecutable.isEmpty());
415 ✔
2224
  ui->actionPush->setVisible(usable);
415 ✔
2225
  ui->actionUpdate->setVisible(usable);
415 ✔
2226
  // The separator in front of them would otherwise sit next to the next one.
2227
  const QList<QAction *> actions = ui->toolBar->actions();
415 ✔
2228
  const qsizetype at = actions.indexOf(ui->actionPush);
415 ✔
2229
  if (at > 0 && actions.at(at - 1)->isSeparator()) {
415 ✔
2230
    actions.at(at - 1)->setVisible(usable);
415 ✔
2231
  }
2232
  enableGitButtons(usable && uiEnabled);
415 ✔
2233
}
415 ✔
2234

2235
void MainWindow::updateOtpButtonVisibility(bool uiEnabled) {
421 ✔
2236
  // No platform gating: codes are generated in-process. Visible but disabled
2237
  // when OTP is off: the panel never shows an OTP field (a secret), so hiding
2238
  // this too would leave no trace of the feature. Honour uiEnabled, or the
2239
  // user can stack Show calls while a decrypt is in flight.
2240
  ui->actionOtp->setVisible(true);
421 ✔
2241
  ui->actionOtp->setEnabled(QtPassSettings::isUseOtp() && uiEnabled);
434 ✔
2242
}
421 ✔
2243

2244
void MainWindow::updateGrepButtonVisibility() {
189 ✔
2245
  const bool enabled = QtPassSettings::isUseGrepSearch();
189 ✔
2246
  ui->grepButton->setVisible(enabled);
189 ✔
2247
  ui->grepCaseButton->setVisible(enabled);
189 ✔
2248
  if (!enabled && m_grep.inGrepMode()) {
189 ✔
2249
    ui->grepButton->setChecked(false);
1 ✔
2250
  }
2251
}
189 ✔
2252

2253
void MainWindow::enableGitButtons(const bool &state) {
415 ✔
2254
  ui->actionPush->setEnabled(state);
415 ✔
2255
  ui->actionUpdate->setEnabled(state);
415 ✔
2256
}
415 ✔
2257

2258
void MainWindow::critical(const QString &title, const QString &msg) {
3 ✔
2259
  // Pass's messages quote store paths; see PlainMessageBox.
2260
  PlainMessageBox::critical(this, title, msg);
3 ✔
2261
}
3 ✔
2262

2263
void MainWindow::onProcessOutput(const QString &output, bool isError,
7 ✔
2264
                                 Enums::PROCESS pid) {
2265
  if (!QtPassSettings::isShowProcessOutput()) {
7 ✔
2266
    return;
2267
  }
2268
  m_processOutput->append(output, isError,
6 ✔
2269
                          ProcessOutputPanel::processName(pid));
12 ✔
2270
}
2271

2272
void MainWindow::updateProcessOutputVisibility() {
5 ✔
2273
  // The action's toggled handler shows or hides the dock.
2274
  ui->actionShowProcessOutput->setChecked(
5 ✔
2275
      QtPassSettings::isShowProcessOutput());
5 ✔
2276
  m_processOutput->setVisible(QtPassSettings::isShowProcessOutput());
5 ✔
2277
}
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