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

IJHack / QtPass / 44203531244

17 Nov 2026 11:55PM UTC coverage: 96.386% (-0.009%) from 96.395%
44203531244

push

github

web-flow
Copies out of widgets go through the clipboard manager; QR closes (#2257)

* Copies out of widgets go through the clipboard manager; QR closes

- Every Copy key, not only the first: the window's shortcut was bound to
  Ctrl+C alone, so Ctrl+Insert and F16 reached the content search list's
  own copy, which put the decrypted line out bare. A focused search
  result is copied through ClipboardManager (ANT-2026-8O2CHMNT).
- The field name editor is a SecretLineEdit (with a new text
  constructor: QLineEdit takes that text as already finished, so focus
  loss alone does not end the edit) and its copies reach the dialog's
  copied() (ANT-2026-8PN56SET).
- "Copy Link Location" in the shown entry's menu copies through
  ClipboardManager; Qt's own action set bare text (ANT-2026-F6XDGDW8).
- The OTP code label is not selectable: its own Copy and the X11
  selection bypassed the hint, the autoclear and "never copy"; the copy
  button copies it (ANT-2026-3BM3VV2Z).
- clearPanel() closes the QR code popup, which is a window of its own
  and stayed on screen past the panel's autoclear (ANT-2026-TCCEFEJA).

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

* FAQ: I can't select or copy the OTP code

The code is no longer selectable (#2257): the copy button copies it the
tracked way, and with "No clipboard" there is no button, so the code is
read, not copied. The CHANGELOG line says so and links the FAQ.

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

* Link menu in document coordinates; tests use the platform's Copy keys

From the #2257 review:
- createStandardContextMenu() takes document coordinates; scrolled, it
  checked the text above the link and left Copy Link Location disabled.
- The copy-key test sends each of the platform's Copy bindings (no
  Ctrl+Insert on macOS, F16 on X11) to the focused results list.
- FAQ and CHANGELOG: autocle... (continued)

43 of 43 new or added lines in 6 files covered. (100.0%)

2 existing lines in 1 file now uncovered.

9040 of 9379 relevant lines covered (96.39%)

758.24 hits per line

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

97.51
/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)
178 ✔
68
    : QMainWindow(parent), ui(new Ui::MainWindow) {
178 ✔
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);
178 ✔
75

76
  m_qtPass = new QtPass(this);
178 ✔
77
  restoreWindow();
178 ✔
78
  connectBackends();
178 ✔
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);
178 ✔
85
  for (const QKeySequence &keys : copyKeys) {
534 ✔
86
    new QShortcut(keys, this, this, &MainWindow::copySelectionOrPassword);
356 ✔
87
  }
88

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

97
  initTextBrowser();
178 ✔
98

99
  updateProfileBox();
178 ✔
100

101
  initDisplayPanel();
178 ✔
102

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

105
  // Install the search-box key filter once, not on every setUiElementsEnabled
106
  // call.
107
  ui->lineEdit->installEventFilter(this);
178 ✔
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);
178 ✔
111
  menuBar()->installEventFilter(this);
178 ✔
112

113
  initTimers();
178 ✔
114

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

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

122
  setUiElementsEnabled(true);
178 ✔
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();
178 ✔
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())) {
179 ✔
130
    if (!config()) {
2 ✔
131
      return;
132
    }
133
  }
134
  m_freshStart = false;
177 ✔
135
  m_initSucceeded = true;
177 ✔
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()) {
177 ✔
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() {
178 ✔
153
  connect(m_qtPass, &QtPass::outputReady, this,
178 ✔
154
          [this](const QString &html) { flashText(html, false, true); });
219 ✔
155
  connect(m_qtPass, &QtPass::operationFinished, this,
178 ✔
156
          [this]() { setUiElementsEnabled(true); });
238 ✔
157
  connect(m_qtPass, &QtPass::statusMessage, this,
178 ✔
158
          &MainWindow::showStatusMessage);
178 ✔
159
  connect(m_qtPass, &QtPass::pushRequested, this, &MainWindow::onAutoPush);
178 ✔
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]() {
178 ✔
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,
178 ✔
178
          [this](const QString &message) { showStatusMessage(message); });
201 ✔
179
  // Both backends: the active one can change through the configuration
180
  // dialog without a restart.
181
  connectPassSignals(QtPassSettings::getRealPass());
178 ✔
182
  connectPassSignals(QtPassSettings::getImitatePass());
178 ✔
183
  ImitatePass *ipass = QtPassSettings::getImitatePass();
178 ✔
184
  connect(ipass, &ImitatePass::startReencryptPath, this,
178 ✔
185
          &MainWindow::startReencryptPath);
178 ✔
186
  connect(ipass, &ImitatePass::reencryptProgress, this,
178 ✔
187
          &MainWindow::reencryptProgress);
178 ✔
188
  connect(ipass, &ImitatePass::endReencryptPath, this,
178 ✔
189
          &MainWindow::endReencryptPath);
178 ✔
190
}
178 ✔
191

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

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

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

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

237
  connect(&searchTimer, &QTimer::timeout, this, &MainWindow::onTimeoutSearch);
178 ✔
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);
178 ✔
242
  m_uiWatchdog.setInterval(UiWatchdogMs);
178 ✔
243
  connect(&m_uiWatchdog, &QTimer::timeout, this, [this]() {
178 ✔
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
}
178 ✔
251

252
void MainWindow::initProcessOutput() {
178 ✔
253
  m_processOutput = new ProcessOutputPanel(this);
178 ✔
254
  addDockWidget(Qt::BottomDockWidgetArea, m_processOutput);
178 ✔
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());
178 ✔
258
  // From the setting, not isVisible(): the window is not shown yet, so no
259
  // child of it reports visible.
260
  ui->actionShowProcessOutput->setChecked(
178 ✔
261
      QtPassSettings::isShowProcessOutput());
178 ✔
262
  connect(ui->actionShowProcessOutput, &QAction::toggled, this,
178 ✔
263
          [this](bool show) {
178 ✔
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,
178 ✔
273
          [this](const QString &out, const QString &err, Enums::PROCESS pid) {
178 ✔
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
}
178 ✔
291

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

299
// The signals of one backend that the window answers itself.
300
void MainWindow::connectPassSignals(Pass *pass) {
356 ✔
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);
356 ✔
304
  connect(pass, &Pass::critical, this, &MainWindow::critical);
356 ✔
305
  connect(pass, &Pass::startingExecuteWrapper, this,
356 ✔
306
          &MainWindow::executeWrapperStarted);
356 ✔
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);
356 ✔
310
  connect(pass, &Pass::statusMsg, this, &MainWindow::showStatusMessage);
356 ✔
311
  connect(pass, &Pass::finishedShow, this, &MainWindow::passShowHandler);
356 ✔
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);
356 ✔
315
  connect(pass, &Pass::finishedShow, this,
356 ✔
316
          &MainWindow::passwordFromFileToClipboard);
356 ✔
317
  connect(pass, &Pass::finishedGrep, this, &MainWindow::onGrepFinished);
356 ✔
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]() {
356 ✔
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
}
356 ✔
337

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

344
void MainWindow::focusInput() {
70 ✔
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()) {
70 ✔
350
    return;
351
  }
352
  auto *lineEdit = findChild<QLineEdit *>(QStringLiteral("lineEdit"));
70 ✔
353
  if (lineEdit == nullptr || !lineEdit->isVisible()) {
70 ✔
354
    return;
355
  }
356
  lineEdit->selectAll();
70 ✔
357
  lineEdit->setFocus();
70 ✔
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;
70 ✔
361
}
362

363
auto MainWindow::event(QEvent *event) -> bool {
8,200 ✔
364
  if (event->type() == QEvent::ApplicationPaletteChange) {
8,200 ✔
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,200 ✔
371
}
372

373
void MainWindow::changeEvent(QEvent *event) {
240 ✔
374
  QWidget::changeEvent(event);
240 ✔
375
  if (event->type() == QEvent::PaletteChange && m_displayPanel != nullptr) {
240 ✔
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() &&
240 ✔
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,
41 ✔
386
                              Qt::QueuedConnection);
387
  }
388
}
240 ✔
389

390
void MainWindow::showEvent(QShowEvent *event) {
43 ✔
391
  QMainWindow::showEvent(event);
43 ✔
392
  if (m_firstShowCompleted) {
43 ✔
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,
41 ✔
399
                            Qt::QueuedConnection);
400
}
401

402
void MainWindow::initToolBarButtons() {
178 ✔
403
  connect(ui->actionAddPassword, &QAction::triggered, this,
178 ✔
404
          &MainWindow::addPassword);
178 ✔
405
  connect(ui->actionAddFolder, &QAction::triggered, this,
178 ✔
406
          &MainWindow::addFolder);
178 ✔
407
  connect(ui->actionEdit, &QAction::triggered, this, &MainWindow::onEdit);
178 ✔
408
  connect(ui->actionDelete, &QAction::triggered, this, &MainWindow::onDelete);
178 ✔
409
  connect(ui->actionPush, &QAction::triggered, this, &MainWindow::onPush);
178 ✔
410
  connect(ui->actionUpdate, &QAction::triggered, this, &MainWindow::onUpdate);
178 ✔
411
  connect(ui->actionUsers, &QAction::triggered, this, &MainWindow::onUsers);
178 ✔
412
  connect(ui->actionConfig, &QAction::triggered, this, &MainWindow::onConfig);
178 ✔
413
  connect(ui->actionOtp, &QAction::triggered, this, &MainWindow::onOtp);
178 ✔
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);
178 ✔
419
  connect(ui->actionClose, &QAction::triggered, this, &MainWindow::close);
178 ✔
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);
178 ✔
427
  ui->actionShowMenuBar->setChecked(QtPassSettings::load().showMenuBar);
178 ✔
428
  menuBar()->setVisible(ui->actionShowMenuBar->isChecked());
178 ✔
429
  connect(ui->actionShowMenuBar, &QAction::toggled, this, [this](bool show) {
178 ✔
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);
178 ✔
436
#endif
437
  connect(ui->actionFaq, &QAction::triggered, this, [] {
179 ✔
438
    QDesktopServices::openUrl(QUrl(QStringLiteral("https://qtpass.org/faq")));
2 ✔
439
  });
1 ✔
440
  connect(ui->actionAbout, &QAction::triggered, this, &MainWindow::showAbout);
178 ✔
441
  connect(ui->actionAboutQt, &QAction::triggered, qApp, &QApplication::aboutQt);
178 ✔
442

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

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

464
  QPixmap logo = QPixmap::fromImage(QImage(":/artwork/icon.svg"))
356 ✔
465
                     .scaledToHeight(statusBar()->height());
178 ✔
466
  auto *logoApp = new QLabel(statusBar());
178 ✔
467
  logoApp->setPixmap(logo);
178 ✔
468
  statusBar()->addPermanentWidget(logoApp);
178 ✔
469
}
178 ✔
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,
81 ✔
476
                           const bool isHtml) {
477
  if (isError) {
81 ✔
478
    ui->textBrowser->setTextColor(Qt::red);
10 ✔
479
  } else {
480
    // setText() re-applies the current char format, red after an error, to
481
    // the whole document. Clear the foreground rather than pin a palette
482
    // colour, so text follows runtime light/dark switches (#946).
483
    QTextCharFormat format = ui->textBrowser->currentCharFormat();
71 ✔
484
    format.clearForeground();
485
    ui->textBrowser->setCurrentCharFormat(format);
71 ✔
486
  }
487

488
  if (isHtml) {
81 ✔
489
    QString _text = text;
490
    if (!ui->textBrowser->toPlainText().isEmpty()) {
138 ✔
491
      _text = ui->textBrowser->toHtml() + _text;
36 ✔
492
    }
493
    ui->textBrowser->setHtml(_text);
69 ✔
494
  } else {
495
    ui->textBrowser->setText(text);
12 ✔
496
  }
497
}
81 ✔
498

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

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

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

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

551
  applyTextBrowserSettings();
5 ✔
552
  applyWindowFlagsSettings();
5 ✔
553

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

720
  m_displayPanel->clear();
27 ✔
721

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

734
  if (s.useAutoclearPanel) {
27 ✔
735
    clearPanelTimer.start();
2 ✔
736
  }
737

738
  flashText(QtPass::formatOutput(output), false, true);
54 ✔
739
  setUiElementsEnabled(true);
27 ✔
740
}
54 ✔
741

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

751
  if (p_output.isEmpty()) {
6 ✔
752
    // Distinguish "could not read the entry" from "entry has no OTP".
753
    flashText(tr("Could not decrypt this password entry"), true);
1 ✔
754
    setUiElementsEnabled(true);
1 ✔
755
    return;
1 ✔
756
  }
757

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

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

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

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

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

860
void MainWindow::restoreWindow() {
189 ✔
861
  // saveGeometry() covers position, size, maximized state and screen;
862
  // anything applied on top discards it. Centre only when nothing was saved.
863
  const QByteArray geometry = QtPassSettings::getGeometry();
378 ✔
864
  if (geometry.isEmpty() || !restoreGeometry(geometry)) {
189 ✔
865
    WindowStateStore::centreOnCursorScreen(*this);
4 ✔
866
  }
867
  restoreState(QtPassSettings::getSavestate(saveState()));
189 ✔
868
  const AppSettings s = QtPassSettings::load();
189 ✔
869

870
  applyWindowFlagsSettings();
189 ✔
871

872
  if (s.useTrayIcon && m_tray == nullptr) {
189 ✔
873
    initTrayIcon();
2 ✔
874
    // Minimized to the tray only when there is one: without a system tray
875
    // initTrayIcon() gave up, and a hidden window could not be brought back.
876
    if (s.startMinimized && m_tray != nullptr) {
2 ✔
877
      // since we are still in constructor, can't directly hide
878
      QTimer::singleShot(10, this, &MainWindow::hide);
×
879
    }
880
  } else if (!s.useTrayIcon && m_tray != nullptr) {
187 ✔
881
    destroyTrayIcon();
×
882
  }
883
}
378 ✔
884

885
void MainWindow::onConfig() { config(); }
1 ✔
886

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

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

921
void MainWindow::onTimeoutSearch() {
40 ✔
922
  // The tree matches slash-separated paths: on Windows, team\bank typed is
923
  // team/bank, as exactMatchPath() reads it too.
924
  QString query = QDir::fromNativeSeparators(ui->lineEdit->text());
80 ✔
925

926
  if (query.isEmpty()) {
40 ✔
927
    ui->treeView->collapseAll();
2 ✔
928
    deselect();
2 ✔
929
  }
930

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

943
  if (m_tree->proxy().rowCount() > 0 && !query.isEmpty()) {
40 ✔
944
    selectFirstFile();
28 ✔
945
  } else {
946
    ui->actionEdit->setEnabled(false);
12 ✔
947
    ui->actionDelete->setEnabled(false);
12 ✔
948
  }
949
}
80 ✔
950

951
void MainWindow::on_lineEdit_returnPressed() {
17 ✔
952
  qCDebug(lcQtPass) << "on_lineEdit_returnPressed"
17 ✔
953
                    << m_tree->proxy().rowCount();
×
954

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

975
  // Return within the search delay acts on the text as typed, not on the
976
  // tree as the previous text filtered it.
977
  if (searchTimer.isActive()) {
5 ✔
978
    searchTimer.stop();
5 ✔
979
    onTimeoutSearch();
5 ✔
980
  }
981
  if (m_tree->proxy().rowCount() > 0) {
5 ✔
982
    selectFirstFile();
5 ✔
983
    on_treeView_clicked(ui->treeView->currentIndex());
5 ✔
984
  }
985
}
986

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

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

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

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

1133
void MainWindow::cancelContentSearch() {
24 ✔
1134
  QtPassSettings::getRealPass()->CancelGrep();
24 ✔
1135
  QtPassSettings::getImitatePass()->CancelGrep();
24 ✔
1136
}
24 ✔
1137

1138
void MainWindow::selectFirstFile() {
33 ✔
1139
  // The entry named exactly as typed wins: with folders sorted first, the
1140
  // depth-first walk found team/bank before bank.
1141
  QModelIndex index = exactMatch();
33 ✔
1142
  if (!index.isValid()) {
1143
    index = firstFile(m_tree->rootIndex());
16 ✔
1144
  }
1145
  ui->treeView->setCurrentIndex(index);
33 ✔
1146
}
33 ✔
1147

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

1192
auto MainWindow::exactMatchPath() -> QString {
51 ✔
1193
  const QString text = QDir::fromNativeSeparators(ui->lineEdit->text());
102 ✔
1194
  const QString store = QtPassSettings::getPassStore();
102 ✔
1195
  // A name may begin or end with a space: " bank" is that entry, not bank.
1196
  // Only when no entry is named so are spaces around the text dropped.
1197
  for (const QString &typed : {text, text.trimmed()}) {
191 ✔
1198
    if (typed.isEmpty()) {
71 ✔
1199
      continue;
×
1200
    }
1201
    const QString path =
1202
        QDir::cleanPath(QDir(store).filePath(typed + QStringLiteral(".gpg")));
142 ✔
1203
    if (PathValidator::isPathInStore(store, path) && QFileInfo(path).isFile()) {
71 ✔
1204
      return spelledAsStored(store, path);
33 ✔
1205
    }
1206
  }
153 ✔
1207
  return {};
18 ✔
1208
}
1209

1210
auto MainWindow::exactMatch() -> QModelIndex {
47 ✔
1211
  const QString path = exactMatchPath();
47 ✔
1212
  if (path.isEmpty()) {
47 ✔
1213
    return {};
17 ✔
1214
  }
1215
  // indexFor() maps through the filter: a row the filter hides is no match.
1216
  const QModelIndex index = m_tree->indexFor(path);
30 ✔
1217
  if (!index.isValid() || !m_tree->fileInfo(index).isFile()) {
53 ✔
1218
    return {};
7 ✔
1219
  }
1220
  return index;
23 ✔
1221
}
1222

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

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

1277
auto MainWindow::firstFile(QModelIndex parentIndex) -> QModelIndex {
24 ✔
1278
  StoreModel &proxy = m_tree->proxy();
24 ✔
1279
  int numRows = proxy.rowCount(parentIndex);
24 ✔
1280
  for (int row = 0; row < numRows; ++row) {
31 ✔
1281
    QModelIndex index = proxy.index(row, 0, parentIndex);
22 ✔
1282
    if (m_tree->fileInfo(index).isFile()) {
22 ✔
1283
      return index;
15 ✔
1284
    }
1285
    if (proxy.hasChildren(index)) {
13 ✔
1286
      QModelIndex childFile = firstFile(index);
8 ✔
1287
      if (childFile.isValid())
1288
        return childFile;
6 ✔
1289
    }
1290
  }
1291
  return QModelIndex();
9 ✔
1292
}
1293

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

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

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

1341
  if (!d.exec()) {
6 ✔
1342
    ui->treeView->setFocus();
5 ✔
1343
  }
1344
}
6 ✔
1345

1346
void MainWindow::addPassword() { setPassword(QString()); }
2 ✔
1347

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

1401
auto MainWindow::confirmLinkRemoval(const QString &file) -> bool {
1 ✔
1402
  // Only the link goes (ImitatePass::Remove unlinks it); nothing behind it
1403
  // is looked at or mentioned.
1404
  return PlainMessageBox::askYes(
1 ✔
1405
      this, tr("Delete link?"),
1 ✔
1406
      tr("%1 is a symbolic link or junction. Remove the link? What it "
1 ✔
1407
         "points to is left alone.")
1408
          .arg(QDir::separator() + file));
2 ✔
1409
}
1410

1411
void MainWindow::onDelete() {
11 ✔
1412
  const QModelIndex currentIndex = ui->treeView->currentIndex();
11 ✔
1413
  // While content search results hide the tree, its current entry is not
1414
  // what the user looks at (the Delete key comes here directly).
1415
  if (!currentIndex.isValid() || ui->treeView->isHidden()) {
9 ✔
1416
    // Otherwise the whole password directory would be deleted (#556).
1417
    return;
8 ✔
1418
  }
1419

1420
  const bool isDir = !m_tree->fileInfo(currentIndex).isFile();
7 ✔
1421
  const QString file =
1422
      isDir ? m_tree->currentDir(true) : getFile(currentIndex, true);
7 ✔
1423
  const QString folder =
1424
      m_tree->fileSystem().rootPath() + QDir::separator() + file;
7 ✔
1425
  const bool linkedFolder = isDir && Util::isLinkedFolder(folder);
7 ✔
1426

1427
  if (!linkedFolder && refuseLinkedFolder(folder)) {
6 ✔
1428
    // Behind a link: deleting would reach outside the store.
1429
    return;
1430
  }
1431
  const bool confirmed =
1432
      linkedFolder ? confirmLinkRemoval(file) : confirmDeletion(file, isDir);
7 ✔
1433
  if (!confirmed) {
7 ✔
1434
    return;
1435
  }
1436
  QtPassSettings::getPass()->Remove(file, isDir);
6 ✔
1437
}
1438

1439
void MainWindow::cancelOtpRequest() {
90 ✔
1440
  m_otpRequestFile.clear();
90 ✔
1441
  m_copyRequestFile.clear();
90 ✔
1442
}
90 ✔
1443

1444
void MainWindow::onOperationError() {
34 ✔
1445
  cancelOtpRequest();
34 ✔
1446
  // executeWrapperStarted() emptied the panel and the browser when the
1447
  // operation started (a refusal says so too); what is left to forget is
1448
  // which entry the panel was about to show.
1449
  m_shownFile.clear();
34 ✔
1450
  // A save's refresh waiting for its push is dropped: it would clear the
1451
  // push's error (or whatever failed before it) from the browser.
1452
  m_refreshAfterPush.clear();
34 ✔
1453
  m_refreshAfterPushOwner = nullptr;
1454
}
34 ✔
1455

1456
// Derives the code in-process from one decrypt, so it works with either
1457
// backend on every platform; otpFromFileToClipboard() finishes the job.
1458
void MainWindow::onOtp() {
12 ✔
1459
  if (ui->treeView->isHidden()) {
12 ✔
1460
    return;
4 ✔
1461
  }
1462
  QString file = getFile(ui->treeView->currentIndex(), true);
11 ✔
1463
  if (file.isEmpty()) {
11 ✔
1464
    flashText(tr("No password selected for OTP generation"), true);
1 ✔
1465
    return;
1 ✔
1466
  }
1467
  if (!QtPassSettings::isUseOtp()) {
10 ✔
1468
    // Normally unreachable (the action is hidden), but never fail silently.
1469
    flashText(tr("No OTP code found in this password entry"), true);
1 ✔
1470
    return;
1 ✔
1471
  }
1472

1473
  // Fast path: the panel shows a live code, so no decrypt, and one clipboard
1474
  // write (two setMimeData calls in one turn can empty the Windows
1475
  // clipboard). Only for *this* entry: arrow keys and right-click move
1476
  // currentIndex without QTreeView::clicked, so the code may be another's.
1477
  const QString shown =
1478
      (m_shownFile == file) ? m_displayPanel->currentOtpCode() : QString();
9 ✔
1479
  if (!shown.isEmpty()) {
9 ✔
1480
    m_qtPass->clipboard().copyText(shown);
1 ✔
1481
    showStatusMessage(tr("OTP code copied to clipboard"));
2 ✔
1482
    return;
1483
  }
1484

1485
  // Fallback: decrypt once. The request file keeps passShowHandler from
1486
  // copying the password and tells otpFromFileToClipboard its answer.
1487
  m_otpRequestFile = file;
8 ✔
1488
  setUiElementsEnabled(false);
8 ✔
1489
  // Keep the marker in step so a second request takes the fast path; safe as
1490
  // executeWrapperStarted() clears the panel, so a failed decrypt shows none.
1491
  m_shownFile = file;
8 ✔
1492
  QtPassSettings::getPass()->Show(file);
16 ✔
1493
}
1494

1495
void MainWindow::onEdit() {
3 ✔
1496
  if (ui->treeView->isHidden()) {
3 ✔
1497
    return;
1 ✔
1498
  }
1499
  QString file = getFile(ui->treeView->currentIndex(), true);
2 ✔
1500
  editPassword(file);
2 ✔
1501
}
1502

1503
void MainWindow::onUsers() {
2 ✔
1504
  const QString dir = m_tree->currentDir(false);
2 ✔
1505
  if (refuseLinkedFolder(dir)) {
2 ✔
1506
    return;
1507
  }
1508

1509
  UsersDialog d(QtPassSettings::getPass(), QtPassSettings::load(), dir, this);
1 ✔
1510
  if (!d.exec()) {
1 ✔
1511
    ui->treeView->setFocus();
1 ✔
1512
  }
1513
}
1 ✔
1514

1515
void MainWindow::messageAvailable(const QString &message) {
10 ✔
1516
  show();
10 ✔
1517
  raise();
10 ✔
1518
  if (message.isEmpty()) {
10 ✔
1519
    focusInput();
1 ✔
1520
  } else {
1521
    ui->treeView->expandAll();
9 ✔
1522
    applySearchText(message);
9 ✔
1523
  }
1524
}
10 ✔
1525

1526
void MainWindow::updateProfileBox() {
187 ✔
1527
  const Profiles profiles = QtPassSettings::getProfiles();
187 ✔
1528
  bool activeGone = false;
1529

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

1561
void MainWindow::updateProfileBoxEnabled() {
629 ✔
1562
  // No profile switch while anything of the store runs or waits: the
1563
  // backend's store and environment would change under it, and what is
1564
  // still queued (a push after a save, say) would finish for the other
1565
  // profile (#2071). Asked of the backend, not only of the interface: the
1566
  // watchdog releases the interface while a slow gpg or git still runs.
1567
  // Every backend: one kept from before a switch of backend may still
1568
  // run what was queued on it.
1569
  ui->profileBox->setEnabled(m_uiEnabled && ui->profileBox->count() > 1 &&
1,259 ✔
1570
                             QtPassSettings::backendsIdle());
11 ✔
1571
}
629 ✔
1572

1573
void MainWindow::on_profileBox_currentTextChanged(const QString &name) {
6 ✔
1574
  if (m_freshStart || name == QtPassSettings::getProfile()) {
18 ✔
1575
    return;
1 ✔
1576
  }
1577
  // The box is disabled while anything runs; should a change come through
1578
  // anyway, the active profile stays and the box says so again.
1579
  if (!m_uiEnabled || !QtPassSettings::backendsIdle()) {
5 ✔
1580
    const QSignalBlocker quiet(ui->profileBox);
×
1581
    ui->profileBox->setCurrentText(QtPassSettings::getProfile());
×
1582
    return;
1583
  }
×
1584
  // A content search runs outside the queue: leaving grep mode cancels it,
1585
  // so its results for the old store are dropped, not shown for the new.
1586
  if (m_grep.inGrepMode()) {
5 ✔
1587
    ui->grepButton->setChecked(false);
1 ✔
1588
  }
1589

1590
  ui->lineEdit->clear();
5 ✔
1591

1592
  const Profile prof = QtPassSettings::getProfiles().value(name);
10 ✔
1593
  AppSettings s = QtPassSettings::load();
5 ✔
1594
  s.activeProfile = name;
5 ✔
1595
  s.passStore = prof.path;
5 ✔
1596
  s.passSigningKey = prof.signingKey;
5 ✔
1597
  // A profile without its own Git flags keeps the global values.
1598
  s.useGit = prof.useGit.value_or(s.useGit);
5 ✔
1599
  s.autoPush = prof.autoPush.value_or(s.autoPush);
5 ✔
1600
  s.autoPull = prof.autoPull.value_or(s.autoPull);
5 ✔
1601
  QtPassSettings::save(s);
5 ✔
1602
  ui->statusBar->showMessage(tr("Profile changed to %1").arg(name), 2000);
10 ✔
1603

1604
  QtPassSettings::getPass()->updateEnv();
5 ✔
1605

1606
  m_tree->setStore(QtPassSettings::getPassStore());
10 ✔
1607
  deselect();
5 ✔
1608
  ui->treeView->setCurrentIndex(QModelIndex());
5 ✔
1609
}
5 ✔
1610

1611
void MainWindow::initTrayIcon() {
3 ✔
1612
  m_tray = new TrayIcon(this);
3 ✔
1613
  if (!m_tray->getIsAllocated()) {
3 ✔
1614
    destroyTrayIcon();
3 ✔
1615
    return;
3 ✔
1616
  }
1617
#ifndef Q_OS_MACOS
1618
  m_tray->addToggle(ui->actionShowMenuBar);
×
1619
#endif
1620
}
1621

1622
void MainWindow::destroyTrayIcon() {
3 ✔
1623
  delete m_tray;
3 ✔
1624
  m_tray = nullptr;
3 ✔
1625
}
3 ✔
1626

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

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

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

1713
void MainWindow::keyPressEvent(QKeyEvent *event) {
25 ✔
1714
  switch (event->key()) {
25 ✔
1715
  case Qt::Key_Delete:
2 ✔
1716
    onDelete();
2 ✔
1717
    break;
2 ✔
1718
  case Qt::Key_Return:
2 ✔
1719
  case Qt::Key_Enter:
1720
    // While content search results hide the tree, its current entry is not
1721
    // what the user looks at: Return on a result opens that result.
1722
    if (ui->treeView->isHidden()) {
2 ✔
1723
      QTreeWidgetItem *result = ui->grepResultsList->currentItem();
1 ✔
1724
      if (result != nullptr && ui->grepResultsList->hasFocus()) {
1 ✔
1725
        on_grepResultsList_itemClicked(result, 0);
1 ✔
1726
      }
1727
      break;
1728
    }
1729
    if (m_tree->proxy().rowCount() > 0) {
1 ✔
1730
      on_treeView_clicked(ui->treeView->currentIndex());
1 ✔
1731
    }
1732
    break;
1733
  case Qt::Key_Escape:
3 ✔
1734
    ui->lineEdit->clear();
3 ✔
1735
    break;
3 ✔
1736
  default:
1737
    break;
1738
  }
1739
}
25 ✔
1740

1741
void MainWindow::addShareMenu(QMenu &contextMenu, const AppSettings &s) {
9 ✔
1742
  const QString dirPath = QDir::cleanPath(m_tree->currentDir(false));
9 ✔
1743
  auto *shareMenu = new QMenu(tr("Share"), &contextMenu);
9 ✔
1744
  contextMenu.addMenu(shareMenu);
9 ✔
1745

1746
  const QString gpgIdPath = Pass::getGpgIdPath(dirPath, s.passStore);
9 ✔
1747
  const bool gpgIdExists = !gpgIdPath.isEmpty() && QFile(gpgIdPath).exists();
9 ✔
1748
  const QString exePath = s.usePass ? s.passExecutable : s.gpgExecutable;
9 ✔
1749
  const bool gpgAvailable =
1750
      !exePath.isEmpty() &&
18 ✔
1751
      (Executor::parseWslCommand(exePath) || QFile(exePath).exists());
18 ✔
1752

1753
  QAction *reencrypt = shareMenu->addAction(tr("Re-encrypt all passwords"));
9 ✔
1754
  reencrypt->setEnabled(gpgIdExists && gpgAvailable);
9 ✔
1755
  connect(reencrypt, &QAction::triggered, this,
9 ✔
1756
          [this, dirPath]() { reencryptPath(dirPath); });
30 ✔
1757

1758
  QAction *exportKey = shareMenu->addAction(tr("Export my public key..."));
9 ✔
1759
  exportKey->setEnabled(gpgAvailable);
9 ✔
1760
  connect(exportKey, &QAction::triggered, this, &MainWindow::exportPublicKey);
9 ✔
1761

1762
  QAction *addRecipientAction = shareMenu->addAction(tr("Add recipient..."));
9 ✔
1763
  addRecipientAction->setEnabled(gpgIdExists && gpgAvailable);
9 ✔
1764
  connect(addRecipientAction, &QAction::triggered, this,
9 ✔
1765
          [this, dirPath]() { addRecipient(dirPath); });
29 ✔
1766

1767
  QAction *shareHelp = shareMenu->addAction(tr("What is this?"));
9 ✔
1768
  connect(shareHelp, &QAction::triggered, this, &MainWindow::showShareHelp);
9 ✔
1769
}
9 ✔
1770

1771
void MainWindow::showContextMenu(const QPoint &pos) {
11 ✔
1772
  const AppSettings s = QtPassSettings::load();
11 ✔
1773
  const QModelIndex index = ui->treeView->indexAt(pos);
11 ✔
1774
  const bool selected = index.isValid();
1775
  if (!selected) {
1776
    ui->treeView->clearSelection();
1 ✔
1777
    ui->actionDelete->setEnabled(false);
1 ✔
1778
    ui->actionEdit->setEnabled(false);
1 ✔
1779
  }
1780
  ui->treeView->setCurrentIndex(index);
11 ✔
1781
  const QPoint globalPos = ui->treeView->viewport()->mapToGlobal(pos);
11 ✔
1782
  const QFileInfo fileOrFolder = m_tree->fileInfo(ui->treeView->currentIndex());
11 ✔
1783
  const bool isDir = fileOrFolder.isDir();
11 ✔
1784

1785
  QMenu contextMenu;
11 ✔
1786
  if (!selected || isDir) {
11 ✔
1787
    const std::array<std::pair<QString, void (MainWindow::*)()>, 4> onFolder{{
1788
        {tr("Open folder with file manager"), &MainWindow::openFolder},
10 ✔
1789
        {tr("Add folder"), &MainWindow::addFolder},
10 ✔
1790
        {tr("Add password"), &MainWindow::addPassword},
10 ✔
1791
        {tr("Users"), &MainWindow::onUsers},
10 ✔
1792
    }};
×
1793
    for (const auto &[text, slot] : onFolder) {
50 ✔
1794
      connect(contextMenu.addAction(text), &QAction::triggered, this, slot);
40 ✔
1795
    }
1796
  } else if (fileOrFolder.isFile()) {
1 ✔
1797
    connect(contextMenu.addAction(tr("Edit")), &QAction::triggered, this,
1 ✔
1798
            &MainWindow::onEdit);
2 ✔
1799
  }
1800
  if (selected) {
11 ✔
1801
    contextMenu.addSeparator();
10 ✔
1802
    if (isDir) {
10 ✔
1803
      connect(contextMenu.addAction(tr("Rename folder")), &QAction::triggered,
9 ✔
1804
              this, &MainWindow::renameFolder);
18 ✔
1805
    } else if (fileOrFolder.isFile()) {
1 ✔
1806
      connect(contextMenu.addAction(tr("Rename password")), &QAction::triggered,
1 ✔
1807
              this, &MainWindow::renamePassword);
2 ✔
1808
    }
1809
    connect(contextMenu.addAction(tr("Delete")), &QAction::triggered, this,
10 ✔
1810
            &MainWindow::onDelete);
10 ✔
1811
    if (isDir) {
10 ✔
1812
      addShareMenu(contextMenu, s);
9 ✔
1813
    }
1814
  }
1815
  contextMenu.exec(globalPos);
11 ✔
1816
}
11 ✔
1817

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

1846
void MainWindow::showBrowserContextMenu(const QPoint &pos) {
1 ✔
1847
  QMenu *contextMenu = browserContextMenu(pos);
1 ✔
1848
  contextMenu->exec(ui->textBrowser->viewport()->mapToGlobal(pos));
1 ✔
1849
  delete contextMenu;
1 ✔
1850
}
1 ✔
1851

1852
void MainWindow::openFolder() {
1 ✔
1853
  QString dir = m_tree->currentDir(false);
1 ✔
1854

1855
  QString path = QDir::toNativeSeparators(dir);
1 ✔
1856
  QDesktopServices::openUrl(QUrl::fromLocalFile(path));
1 ✔
1857
}
1 ✔
1858

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

1907
void MainWindow::renameFolder() {
3 ✔
1908
  bool ok;
1909
  QString srcDir = QDir::cleanPath(m_tree->currentDir(false));
3 ✔
1910
  QString srcDirName = QDir(srcDir).dirName();
3 ✔
1911
  QString newName =
1912
      QInputDialog::getText(this, tr("Rename folder"), tr("Rename folder to: "),
3 ✔
1913
                            QLineEdit::Normal, srcDirName, &ok);
6 ✔
1914
  if (!ok || newName.isEmpty()) {
3 ✔
1915
    return;
1916
  }
1917
  QString destDir = srcDir;
1918
  destDir.replace(srcDir.lastIndexOf(srcDirName), srcDirName.length(), newName);
2 ✔
1919
  if (!confirmPathInStore(destDir)) {
2 ✔
1920
    return;
1921
  }
1922
  QtPassSettings::getPass()->Move(srcDir, destDir, false);
3 ✔
1923
}
1924

1925
void MainWindow::editPassword(const QString &file) {
5 ✔
1926
  if (!file.isEmpty()) {
5 ✔
1927
    const AppSettings s = QtPassSettings::load();
5 ✔
1928
    if (s.useGit && s.autoPull) {
5 ✔
1929
      onUpdate(true);
1 ✔
1930
    }
1931
    // The dialog decrypts the entry itself to fill its fields. That decrypt
1932
    // lands on the same finishedShow the panel uses, so drop the panel's claim
1933
    // to it: otherwise passShowHandler() repaints and, with "Always copy",
1934
    // puts the entry's old password on the clipboard - replacing whatever the
1935
    // user copied to paste into the dialog.
1936
    m_shownFile.clear();
5 ✔
1937
    setPassword(file, false);
5 ✔
1938
  }
5 ✔
1939
}
5 ✔
1940

1941
void MainWindow::renamePassword() {
2 ✔
1942
  bool ok;
1943
  QString file = getFile(ui->treeView->currentIndex(), false);
2 ✔
1944
  QString filePath = QFileInfo(file).path();
2 ✔
1945
  QString fileName = QFileInfo(file).fileName();
2 ✔
1946
  if (fileName.endsWith(".gpg", Qt::CaseInsensitive)) {
4 ✔
1947
    fileName.chop(4);
2 ✔
1948
  }
1949

1950
  QString newName =
1951
      QInputDialog::getText(this, tr("Rename file"), tr("Rename file to: "),
2 ✔
1952
                            QLineEdit::Normal, fileName, &ok);
4 ✔
1953
  if (!ok || newName.isEmpty()) {
2 ✔
1954
    return;
1955
  }
1956
  QString newFile = QDir(filePath).filePath(newName);
2 ✔
1957
  if (!confirmPathInStore(newFile)) {
2 ✔
1958
    return;
1959
  }
1960
  QtPassSettings::getPass()->Move(file, newFile, false);
3 ✔
1961
}
1962

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

1991
void MainWindow::copyPasswordFromTreeview() {
9 ✔
1992
  // While content search results hide the tree, its current entry is not
1993
  // what the user looks at: no decrypt, as for Edit and OTP.
1994
  if (ui->treeView->isHidden()) {
9 ✔
UNCOV
1995
    return;
×
1996
  }
1997
  QFileInfo fileOrFolder = m_tree->fileInfo(ui->treeView->currentIndex());
9 ✔
1998

1999
  if (fileOrFolder.isFile()) {
9 ✔
2000
    QString file = getFile(ui->treeView->currentIndex(), true);
9 ✔
2001
    // The newest Ctrl+C wins: finishedShow names its file, so the decrypt of
2002
    // an earlier request is simply not this one's.
2003
    m_copyRequestFile = file;
9 ✔
2004
    // This Show repaints the panel as well; see onOtp().
2005
    m_shownFile = file;
9 ✔
2006
    QtPassSettings::getPass()->Show(file);
18 ✔
2007
  }
2008
}
9 ✔
2009

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

2031
void MainWindow::showStatusMessage(const QString &msg, int timeout) {
34 ✔
2032
  ui->statusBar->showMessage(msg, timeout);
34 ✔
2033
}
34 ✔
2034

2035
void MainWindow::reencryptPath(const QString &dir) {
3 ✔
2036
  QDir checkDir(dir);
3 ✔
2037
  if (!checkDir.exists()) {
3 ✔
2038
    PlainMessageBox::critical(this, tr("Error"),
2 ✔
2039
                              tr("Directory does not exist: %1").arg(dir));
2 ✔
2040
    return;
1 ✔
2041
  }
2042
  if (refuseLinkedFolder(dir)) {
2 ✔
2043
    return;
2044
  }
2045

2046
  const bool yes = PlainMessageBox::askYes(
2 ✔
2047
      this, tr("Re-encrypt passwords"),
2 ✔
2048
      tr("Re-encrypt all passwords in %1?\n\n"
2 ✔
2049
         "This will re-encrypt ALL password files in this folder "
2050
         "using the current recipients defined in .gpg-id.\n\n"
2051
         "This may rewrite many files and cannot be undone easily.\n\n"
2052
         "Continue?")
2053
          .arg(QDir(dir).dirName()));
4 ✔
2054

2055
  if (!yes)
2 ✔
2056
    return;
2057

2058
  // Disable now; the asynchronous startReencryptPath signal re-runs this
2059
  // harmlessly.
2060
  startReencryptPath();
1 ✔
2061

2062
  // Under the current profile's settings: with the pass backend active, the
2063
  // native one is not re-initialised on a profile switch.
2064
  QtPassSettings::getImitatePass()->reencryptPath(
2 ✔
2065
      QDir::cleanPath(QDir(dir).absolutePath()), QtPassSettings::load());
2 ✔
2066
}
3 ✔
2067

2068
// Idempotent: reencryptPath() calls it before ImitatePass emits the signal.
2069
void MainWindow::startReencryptPath() {
7 ✔
2070
  m_reencryptRunning = true;
7 ✔
2071
  setUiElementsEnabled(false);
7 ✔
2072
  // The worker always ends with endReencryptPath(), and Cancel is available
2073
  // throughout, so the generic watchdog is not needed for this operation.
2074
  m_uiWatchdog.stop();
7 ✔
2075
  ui->treeView->setDisabled(true);
7 ✔
2076
  if (m_reencryptProgress)
7 ✔
2077
    return;
2078
  auto *progress = new QProgressDialog(tr("Re-encrypting passwords..."),
5 ✔
2079
                                       tr("Cancel"), 0, 0, this);
10 ✔
2080
  progress->setWindowTitle(tr("Re-encrypt passwords"));
5 ✔
2081
  progress->setWindowModality(Qt::WindowModal);
5 ✔
2082
  progress->setAutoClose(false);
5 ✔
2083
  progress->setAutoReset(false);
5 ✔
2084
  progress->setMinimumDuration(0);
5 ✔
2085
  connect(progress, &QProgressDialog::canceled, this, [this]() {
5 ✔
2086
    QtPassSettings::getImitatePass()->cancelReencryptPath();
1 ✔
2087
    showStatusMessage(tr("Cancelling re-encryption"), 5000);
1 ✔
2088
  });
1 ✔
2089
  m_reencryptProgress = progress;
2090
  progress->show();
5 ✔
2091
}
2092

2093
void MainWindow::reencryptProgress(int current, int total) {
7 ✔
2094
  if (!m_reencryptProgress || m_inProgressUpdate)
7 ✔
2095
    return;
2096
  QProgressDialog *progress = m_reencryptProgress;
2097
  progress->setMaximum(total);
6 ✔
2098
  progress->setLabelText(
6 ✔
2099
      tr("Re-encrypting passwords: %1 of %2").arg(current).arg(total));
6 ✔
2100
  // On a modal dialog setValue() runs processEvents(), which can deliver
2101
  // endReencryptPath(), even inside a nested event loop that would delete a
2102
  // deleteLater()ed dialog under setValue()'s feet: keep this last, and
2103
  // delete the dialog only after it returns.
2104
  m_inProgressUpdate = true;
6 ✔
2105
  progress->setValue(current);
6 ✔
2106
  m_inProgressUpdate = false;
6 ✔
2107
  if (m_progressToDelete) {
6 ✔
2108
    m_progressToDelete->deleteLater();
2 ✔
2109
    m_progressToDelete = nullptr;
2110
  }
2111
}
2112

2113
void MainWindow::endReencryptPath() {
5 ✔
2114
  m_reencryptRunning = false;
5 ✔
2115
  if (m_reencryptProgress) {
5 ✔
2116
    m_reencryptProgress->hide();
5 ✔
2117
    if (m_inProgressUpdate) {
5 ✔
2118
      m_progressToDelete = m_reencryptProgress;
2119
    } else {
2120
      m_reencryptProgress->deleteLater();
3 ✔
2121
    }
2122
    m_reencryptProgress = nullptr;
2123
  }
2124
  setUiElementsEnabled(true);
5 ✔
2125
}
5 ✔
2126

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

2162
// UsersDialog only ticks keys already in the keyring; importing a foreign
2163
// key still has to happen via gpg (or QtPass settings) first.
2164
void MainWindow::addRecipient(const QString &dir) {
2 ✔
2165
  if (refuseLinkedFolder(dir)) {
2 ✔
2166
    return;
1 ✔
2167
  }
2168
  UsersDialog d(QtPassSettings::getPass(), QtPassSettings::load(), dir, this);
1 ✔
2169
  d.exec();
1 ✔
2170
}
1 ✔
2171

2172
// A tree-picked folder that is, or lies behind, a symlink or junction is not
2173
// a folder of the store. The store root itself may be a link (a synced
2174
// folder); that is configuration, not a tree pick.
2175
auto MainWindow::refuseLinkedFolder(const QString &dir) -> bool {
17 ✔
2176
  if (!Util::isUnderLink(dir, QtPassSettings::load().passStore)) {
17 ✔
2177
    return false;
2178
  }
2179
  PlainMessageBox::critical(
3 ✔
2180
      this, tr("Not a folder of the store"),
3 ✔
2181
      tr("%1 is, or lies behind, a symbolic link or junction. What that "
3 ✔
2182
         "points to is not part of the password store and is left alone.")
2183
          .arg(QDir::toNativeSeparators(QDir::cleanPath(dir))));
6 ✔
2184
  return true;
3 ✔
2185
}
2186

2187
void MainWindow::showShareHelp() {
1 ✔
2188
  QMessageBox::information(
2 ✔
2189
      this, tr("Sharing passwords with GPG"),
1 ✔
2190
      tr("<h3>Sharing passwords with GPG</h3>"
1 ✔
2191
         "<p>To share passwords with other users:</p>"
2192
         "<ol>"
2193
         "<li><b>Export your public key</b> and send it to teammates</li>"
2194
         "<li><b>Import teammates' public keys</b> into your GPG keyring</li>"
2195
         "<li><b>Re-encrypt passwords</b> so all recipients can decrypt "
2196
         "them</li>"
2197
         "</ol>"
2198
         "<p>Only people who have a matching secret key can decrypt the "
2199
         "passwords.</p>"
2200
         "<p><b>Tip:</b> Use the same GPG key for all shared folders.</p>"
2201
         "<p>See the FAQ for more details.</p>"));
2202
}
1 ✔
2203

2204
void MainWindow::updateGitButtonVisibility(bool uiEnabled) {
408 ✔
2205
  const AppSettings s = QtPassSettings::load();
408 ✔
2206
  // Without Git there is nothing to push or pull, ever: the buttons go, not
2207
  // grey out. While an operation runs they stay and are disabled.
2208
  const bool usable =
2209
      s.useGit && !(s.gitExecutable.isEmpty() && s.passExecutable.isEmpty());
408 ✔
2210
  ui->actionPush->setVisible(usable);
408 ✔
2211
  ui->actionUpdate->setVisible(usable);
408 ✔
2212
  // The separator in front of them would otherwise sit next to the next one.
2213
  const QList<QAction *> actions = ui->toolBar->actions();
408 ✔
2214
  const qsizetype at = actions.indexOf(ui->actionPush);
408 ✔
2215
  if (at > 0 && actions.at(at - 1)->isSeparator()) {
408 ✔
2216
    actions.at(at - 1)->setVisible(usable);
408 ✔
2217
  }
2218
  enableGitButtons(usable && uiEnabled);
408 ✔
2219
}
408 ✔
2220

2221
void MainWindow::updateOtpButtonVisibility(bool uiEnabled) {
414 ✔
2222
  // No platform gating: codes are generated in-process. Visible but disabled
2223
  // when OTP is off: the panel never shows an OTP field (a secret), so hiding
2224
  // this too would leave no trace of the feature. Honour uiEnabled, or the
2225
  // user can stack Show calls while a decrypt is in flight.
2226
  ui->actionOtp->setVisible(true);
414 ✔
2227
  ui->actionOtp->setEnabled(QtPassSettings::isUseOtp() && uiEnabled);
427 ✔
2228
}
414 ✔
2229

2230
void MainWindow::updateGrepButtonVisibility() {
183 ✔
2231
  const bool enabled = QtPassSettings::isUseGrepSearch();
183 ✔
2232
  ui->grepButton->setVisible(enabled);
183 ✔
2233
  ui->grepCaseButton->setVisible(enabled);
183 ✔
2234
  if (!enabled && m_grep.inGrepMode()) {
183 ✔
2235
    ui->grepButton->setChecked(false);
1 ✔
2236
  }
2237
}
183 ✔
2238

2239
void MainWindow::enableGitButtons(const bool &state) {
408 ✔
2240
  ui->actionPush->setEnabled(state);
408 ✔
2241
  ui->actionUpdate->setEnabled(state);
408 ✔
2242
}
408 ✔
2243

2244
void MainWindow::critical(const QString &title, const QString &msg) {
3 ✔
2245
  // Pass's messages quote store paths; see PlainMessageBox.
2246
  PlainMessageBox::critical(this, title, msg);
3 ✔
2247
}
3 ✔
2248

2249
void MainWindow::onProcessOutput(const QString &output, bool isError,
7 ✔
2250
                                 Enums::PROCESS pid) {
2251
  if (!QtPassSettings::isShowProcessOutput()) {
7 ✔
2252
    return;
2253
  }
2254
  m_processOutput->append(output, isError,
6 ✔
2255
                          ProcessOutputPanel::processName(pid));
12 ✔
2256
}
2257

2258
void MainWindow::updateProcessOutputVisibility() {
5 ✔
2259
  // The action's toggled handler shows or hides the dock.
2260
  ui->actionShowProcessOutput->setChecked(
5 ✔
2261
      QtPassSettings::isShowProcessOutput());
5 ✔
2262
  m_processOutput->setVisible(QtPassSettings::isShowProcessOutput());
5 ✔
2263
}
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