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

IJHack / QtPass / 43752888616

15 Nov 2026 07:31PM UTC coverage: 96.316% (-0.02%) from 96.334%
43752888616

push

github

web-flow
Ctrl+C copies the text selected in the shown entry (#2202)

* Ctrl+C copies the text selected in the shown entry

Ctrl+C is a window-wide shortcut for copying the current entry's
password, and the read-only views of an entry (the text browser, the
field rows, selectable labels) do not take Ctrl+C for themselves. So a
login, URL or note selected there was answered with the password, with
"Copied to clipboard", and the decrypt's repaint cleared the selection;
only the context menu's Copy took the selection.

The shortcut now goes to copySelectionOrPassword(): the focused text
view's own copy() when it has a selection (a SecretTextBrowser still
marks it secret for clipboard managers), a selectable label's selected
text, and otherwise the password, as before.

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

* Ctrl+C on a selected label goes through the clipboard manager

The label may be the OTP code: it gets the secret hint and the autoclear, as a copy button's copy does. Doc says which widgets take the selection (review).

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

---------

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

10 of 11 new or added lines in 1 file covered. (90.91%)

1 existing line in 1 file now uncovered.

8705 of 9038 relevant lines covered (96.32%)

714.64 hits per line

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

97.56
/src/mainwindow.cpp
1
// SPDX-FileCopyrightText: 2014 Anne Jan Brouwer
2
// SPDX-License-Identifier: GPL-3.0-or-later
3
/**
4
 * @file
5
 * @brief Implements MainWindow; the backend signal wiring lives in
6
 *        connectBackends() and connectPassSignals(), the decrypted-entry
7
 *        rendering in passShowHandler().
8
 */
9
#include "mainwindow.h"
10

11
#include "qtpasslogging.h"
12

13
#include "configdialog.h"
14
#include "enums.h"
15
#include "executor.h"
16
#include "exportpublickeydialog.h"
17
#include "filecontent.h"
18
#include "firstrunwizard.h"
19
#include "menubarpeek.h"
20
#include "nativegrep.h"
21
#include "passworddialog.h"
22
#include "passworddisplaypanel.h"
23
#include "pathvalidator.h"
24
#include "plainmessagebox.h"
25
#include "processoutputpanel.h"
26
#include "qpushbuttonasqrcode.h"
27
#include "qpushbuttonshowpassword.h"
28
#include "qpushbuttonwithclipboard.h"
29
#include "qtpass.h"
30
#include "qtpasssettings.h"
31
#include "templateio.h"
32
#include "totp.h"
33
#include "trayicon.h"
34
#include "ui_mainwindow.h"
35
#include "usersdialog.h"
36
#include "util.h"
37
#include "windowstatestore.h"
38
#include <QApplication>
39
#include <QCloseEvent>
40
#include <QDate>
41
#include <QDesktopServices>
42
#include <QDialog>
43
#include <QDockWidget>
44
#include <QFileInfo>
45
#include <QFileSystemModel>
46
#include <QHBoxLayout>
47
#include <QInputDialog>
48
#include <QLabel>
49
#include <QLineEdit>
50
#include <QMenu>
51
#include <QMenuBar>
52
#include <QMessageBox>
53
#include <QProgressDialog>
54
#include <QPushButton>
55
#include <QShortcut>
56
#include <QTextCharFormat>
57
#include <QTextEdit>
58
#include <QTextStream>
59
#include <QTimer>
60
#include <QTreeWidget>
61
#include <QUrl>
62
#include <algorithm>
63
#include <array>
64
#include <utility>
65

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

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

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

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

90
  initTextBrowser();
165 ✔
91

92
  updateProfileBox();
165 ✔
93

94
  initDisplayPanel();
165 ✔
95

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

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

106
  initTimers();
165 ✔
107

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

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

115
  setUiElementsEnabled(true);
165 ✔
116

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

547
  updateProfileBox();
3 ✔
548
  const AppSettings s = QtPassSettings::load();
3 ✔
549
  // An open still waiting for the tree was asked of the old view; once
550
  // re-rooted, it would find that name in the new store. A profile switch
551
  // ends it by clearing the search text.
552
  delete m_pendingOpen;
3 ✔
553
  m_tree->setStore(s.passStore);
3 ✔
554
  deselect();
3 ✔
555
  ui->treeView->setCurrentIndex(QModelIndex());
3 ✔
556

557
  Pass *activePass = QtPassSettings::getPass();
3 ✔
558
  activePass->updateEnv();
3 ✔
559
  m_tree->setPass(activePass);
3 ✔
560
  clearPanelTimer.setInterval(MS_PER_SECOND * s.autoclearPanelSeconds);
3 ✔
561
  m_qtPass->clipboard().setAutoclearTimer();
3 ✔
562

563
  updateGitButtonVisibility();
3 ✔
564
  updateOtpButtonVisibility();
3 ✔
565
  updateGrepButtonVisibility();
3 ✔
566
  updateProcessOutputVisibility();
3 ✔
567
#ifndef Q_OS_MACOS
568
  // The action's toggled handler shows or hides the bar (and saves again).
569
  ui->actionShowMenuBar->setChecked(s.showMenuBar);
3 ✔
570
#endif
571
  if (s.useTrayIcon && m_tray == nullptr) {
3 ✔
572
    initTrayIcon();
1 ✔
573
  } else if (!s.useTrayIcon && m_tray != nullptr) {
2 ✔
574
    destroyTrayIcon();
×
575
  }
576

577
  // Stay fresh-start while the configuration is unusable, so the
578
  // constructor's loop re-runs the wizard. The re-prompt lives there:
579
  // recursing here never reported a cancel back to the caller.
580
  if (Util::configIsValid(s)) {
3 ✔
581
    m_freshStart = false;
3 ✔
582
  }
583
  return true;
584
}
3 ✔
585

586
void MainWindow::onUpdate(bool block) {
2 ✔
587
  ui->statusBar->showMessage(tr("Updating password-store"), 2000);
2 ✔
588
  if (block) {
2 ✔
589
    QtPassSettings::getPass()->GitPull_b();
1 ✔
590
  } else {
591
    QtPassSettings::getPass()->GitPull();
1 ✔
592
  }
593
}
2 ✔
594

595
void MainWindow::onPush() {
9 ✔
596
  if (QtPassSettings::isUseGit()) {
9 ✔
597
    ui->statusBar->showMessage(tr("Updating password-store"), 2000);
9 ✔
598
    QtPassSettings::getPass()->GitPush();
9 ✔
599
  }
600
}
9 ✔
601

602
auto MainWindow::getFile(const QModelIndex &index, bool forPass) -> QString {
62 ✔
603
  return m_tree->fileFor(index, forPass);
62 ✔
604
}
605

606
void MainWindow::on_treeView_clicked(const QModelIndex &index) {
24 ✔
607
  bool cleared = ui->treeView->currentIndex().flags() == Qt::NoItemFlags;
24 ✔
608
  QString file = getFile(index, true);
24 ✔
609
  ui->passwordName->setText(file);
24 ✔
610
  if (!file.isEmpty() && !cleared) {
24 ✔
611
    // Remember what the panel is about to show, so onOtp() can tell whether the
612
    // code it can see belongs to the entry that is currently selected.
613
    m_shownFile = file;
23 ✔
614
    QtPassSettings::getPass()->Show(file);
46 ✔
615
  } else {
616
    m_shownFile.clear();
1 ✔
617
    clearPanel(false);
1 ✔
618
    ui->actionEdit->setEnabled(false);
1 ✔
619
    ui->actionDelete->setEnabled(true);
1 ✔
620
  }
621
}
24 ✔
622

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

626
  if (fileOrFolder.isFile()) {
4 ✔
627
    editPassword(getFile(index, true));
6 ✔
628
  }
629
}
4 ✔
630

631
void MainWindow::deselect() {
15 ✔
632
  m_shownFile.clear();
15 ✔
633
  cancelOtpRequest();
15 ✔
634
  m_qtPass->clipboard().clear();
15 ✔
635
  ui->treeView->clearSelection();
15 ✔
636
  ui->actionEdit->setEnabled(false);
15 ✔
637
  ui->actionDelete->setEnabled(false);
15 ✔
638
  ui->passwordName->setText("");
15 ✔
639
  clearPanel(false);
15 ✔
640
}
15 ✔
641

642
void MainWindow::executeWrapperStarted() {
62 ✔
643
  m_displayPanel->clear();
62 ✔
644
  ui->textBrowser->clear();
62 ✔
645
  setUiElementsEnabled(false);
62 ✔
646
  clearPanelTimer.stop();
62 ✔
647
  if (QtPassSettings::isShowProcessOutput()) {
62 ✔
648
    m_processOutput->setVisible(true);
57 ✔
649
  }
650
}
62 ✔
651

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

688
  // Skipped for an OTP request: the user asked for a code, and two
689
  // OleSetClipboard calls in one turn can leave the Windows clipboard empty.
690
  if (m_otpRequestFile.isEmpty() || m_otpRequestFile != file) {
27 ✔
691
    m_qtPass->clipboard().copyIfAlways(password, p_output);
25 ✔
692
  }
693

694
  m_displayPanel->clear();
27 ✔
695

696
  if (s.hideContent) {
27 ✔
697
    output = "***" + tr("Content hidden") + "***";
4 ✔
698
  } else if (s.displayAsIs) {
25 ✔
699
    // As it is, but not a block per line of millions.
700
    output = FileContent::boundedForDisplay(p_output);
2 ✔
701
  } else {
702
    m_displayPanel->displayFields(password, fileContent.getNamedValues(), s,
48 ✔
703
                                  s.useOtp ? fileContent.getOtpUri()
24 ✔
704
                                           : QString());
705
    output = fileContent.getRemainingDataForDisplay();
48 ✔
706
  }
707

708
  if (s.useAutoclearPanel) {
27 ✔
709
    clearPanelTimer.start();
2 ✔
710
  }
711

712
  flashText(QtPass::formatOutput(output), false, true);
54 ✔
713
  setUiElementsEnabled(true);
27 ✔
714
}
54 ✔
715

716
void MainWindow::otpFromFileToClipboard(const QString &p_output,
27 ✔
717
                                        const QString &file) {
718
  // Permanently connected: only the decrypt of the entry onOtp() asked for
719
  // is ours, everything else belongs to a tree click or a Ctrl+C.
720
  if (m_otpRequestFile.isEmpty() || file != m_otpRequestFile) {
27 ✔
721
    return;
24 ✔
722
  }
723
  m_otpRequestFile.clear();
5 ✔
724

725
  if (p_output.isEmpty()) {
5 ✔
726
    // Distinguish "could not read the entry" from "entry has no OTP".
727
    flashText(tr("Could not decrypt this password entry"), true);
1 ✔
728
    setUiElementsEnabled(true);
1 ✔
729
    return;
1 ✔
730
  }
731

732
  // passShowHandler ran first for this finishedShow; if it rendered the OTP
733
  // row, reuse its code (as onOtp()'s fast path does). Otherwise parse:
734
  // hideContent, displayAsIs or no OTP field.
735
  const QString shown = m_displayPanel->currentOtpCode();
4 ✔
736
  if (!shown.isEmpty()) {
4 ✔
737
    m_qtPass->clipboard().copyText(shown);
1 ✔
738
    showStatusMessage(tr("OTP code copied to clipboard"));
1 ✔
739
    setUiElementsEnabled(true);
1 ✔
740
    return;
741
  }
742

743
  const AppSettings s = QtPassSettings::load();
3 ✔
744
  // Parse with the same template settings passShowHandler uses, so an OTP
745
  // field is recognised identically in both paths.
746
  const QStringList templ =
747
      s.useTemplate ? TemplateIO::fieldsIn(s.passTemplate) : QStringList();
3 ✔
748
  const bool allFields = s.useTemplate && s.templateAllFields;
3 ✔
749
  const FileContent fileContent =
750
      FileContent::parse(p_output, templ, allFields);
3 ✔
751

752
  const std::optional<Totp::Settings> settings =
753
      Totp::parse(fileContent.getOtpUri());
6 ✔
754
  if (settings.has_value()) {
3 ✔
755
    m_qtPass->clipboard().copyText(Totp::generateNow(*settings));
4 ✔
756
    showStatusMessage(tr("OTP code copied to clipboard"));
4 ✔
757
  } else {
758
    flashText(tr("No OTP code found in this password entry"), true);
2 ✔
759
  }
760
  setUiElementsEnabled(true);
3 ✔
761
}
6 ✔
762

763
void MainWindow::clearPanel(bool notify) {
54 ✔
764
  m_displayPanel->clear();
54 ✔
765
  const bool grepWasVisible = ui->grepResultsList->isVisible();
54 ✔
766
  ui->grepResultsList->clear();
54 ✔
767
  if (grepWasVisible) {
54 ✔
768
    ui->grepResultsList->setVisible(false);
4 ✔
769
    ui->treeView->setVisible(true);
4 ✔
770
    if (m_grep.inGrepMode()) {
4 ✔
771
      // Left as the button leaves it: a search still running would otherwise
772
      // hand its partial matches to a content search entered meanwhile.
773
      cancelContentSearch();
4 ✔
774
      if (m_grep.leaveGrepMode()) {
775
        QApplication::restoreOverrideCursor();
2 ✔
776
      }
777
      ui->grepButton->blockSignals(true);
4 ✔
778
      ui->grepButton->setChecked(false);
4 ✔
779
      ui->grepButton->blockSignals(false);
4 ✔
780
      ui->lineEdit->blockSignals(true);
4 ✔
781
      ui->lineEdit->clear();
4 ✔
782
      ui->lineEdit->blockSignals(false);
4 ✔
783
      ui->lineEdit->setPlaceholderText(tr("Search password"));
8 ✔
784
    }
785
  }
786
  if (notify) {
54 ✔
787
    QString output = "***" + tr("Password and content hidden") + "***";
4 ✔
788
    ui->textBrowser->setHtml(output);
2 ✔
789
  } else {
790
    ui->textBrowser->setHtml("");
104 ✔
791
  }
792
}
54 ✔
793

794
void MainWindow::setUiElementsEnabled(bool state) {
370 ✔
795
  // A running re-encryption owns the UI state: the progress dialog's Cancel is
796
  // the user's escape hatch and endReencryptPath() releases the interface, so
797
  // neither an unrelated completion nor the watchdog may re-enable it early.
798
  if (state && m_reencryptRunning) {
370 ✔
799
    m_uiWatchdog.stop();
1 ✔
800
    return;
1 ✔
801
  }
802
  // Arm the watchdog while the UI is disabled; disarm once re-enabled.
803
  if (state) {
804
    m_uiWatchdog.stop();
287 ✔
805
  } else {
806
    m_uiWatchdog.start();
82 ✔
807
  }
808
  ui->treeView->setEnabled(state);
369 ✔
809
  ui->lineEdit->setEnabled(state);
369 ✔
810
  ui->actionAddPassword->setEnabled(state);
369 ✔
811
  ui->actionAddFolder->setEnabled(state);
369 ✔
812
  ui->actionUsers->setEnabled(state);
369 ✔
813
  ui->actionConfig->setEnabled(state);
369 ✔
814
  m_uiEnabled = state;
369 ✔
815
  updateProfileBoxEnabled();
369 ✔
816
  const bool uiEnabled = state;
817
  // is a file selected?
818
  state &= ui->treeView->currentIndex().isValid();
738 ✔
819
  ui->actionDelete->setEnabled(state);
369 ✔
820
  ui->actionEdit->setEnabled(state);
369 ✔
821
  updateGitButtonVisibility(uiEnabled);
369 ✔
822
  // `state` is now "UI enabled AND a file is selected", which is exactly when
823
  // generating an OTP makes sense.
824
  updateOtpButtonVisibility(state);
369 ✔
825
}
826

827
void MainWindow::restoreWindow() {
176 ✔
828
  // saveGeometry() covers position, size, maximized state and screen;
829
  // anything applied on top discards it. Centre only when nothing was saved.
830
  const QByteArray geometry = QtPassSettings::getGeometry();
352 ✔
831
  if (geometry.isEmpty() || !restoreGeometry(geometry)) {
176 ✔
832
    WindowStateStore::centreOnCursorScreen(*this);
4 ✔
833
  }
834
  restoreState(QtPassSettings::getSavestate(saveState()));
176 ✔
835
  const AppSettings s = QtPassSettings::load();
176 ✔
836

837
  applyWindowFlagsSettings();
176 ✔
838

839
  if (s.useTrayIcon && m_tray == nullptr) {
176 ✔
840
    initTrayIcon();
2 ✔
841
    // Minimized to the tray only when there is one: without a system tray
842
    // initTrayIcon() gave up, and a hidden window could not be brought back.
843
    if (s.startMinimized && m_tray != nullptr) {
2 ✔
844
      // since we are still in constructor, can't directly hide
845
      QTimer::singleShot(10, this, &MainWindow::hide);
×
846
    }
847
  } else if (!s.useTrayIcon && m_tray != nullptr) {
174 ✔
848
    destroyTrayIcon();
×
849
  }
850
}
352 ✔
851

852
void MainWindow::onConfig() { config(); }
1 ✔
853

854
void MainWindow::showAbout() {
1 ✔
855
  QMessageBox::about(
1 ✔
856
      this, tr("About QtPass"),
1 ✔
857
      tr("<h3>QtPass %1</h3>"
1 ✔
858
         "<p>A multi-platform GUI for <a "
859
         "href=\"https://www.passwordstore.org/\">"
860
         "pass</a>, the standard Unix password manager.</p>"
861
         "<p><a href=\"https://qtpass.org/\">qtpass.org</a> &middot; "
862
         "<a href=\"https://github.com/IJHack/QtPass\">Source and "
863
         "issues</a></p>"
864
         "<p>Copyright &copy; 2014&ndash;%2 IJhack. Licensed under the "
865
         "<a href=\"https://www.gnu.org/licenses/gpl-3.0.html\">GNU GPL "
866
         "version 3</a> or later.</p>")
867
          .arg(QStringLiteral(VERSION),
2 ✔
868
               QString::number(QDate::currentDate().year())));
2 ✔
869
}
1 ✔
870

871
void MainWindow::on_lineEdit_textChanged(const QString &arg1) {
46 ✔
872
  if (m_grep.inGrepMode())
46 ✔
873
    return;
874
  ui->statusBar->showMessage(tr("Looking for: %1").arg(arg1), 1000);
68 ✔
875
  ui->treeView->expandAll();
34 ✔
876
  // Drop any decrypt still pending for the entry that was shown: otherwise it
877
  // keeps its right to the panel and, with "Always copy", the clipboard, and
878
  // when it lands late it shows that entry's password under the new heading.
879
  m_shownFile.clear();
34 ✔
880
  cancelOtpRequest();
34 ✔
881
  clearPanel(false);
34 ✔
882
  ui->passwordName->setText("");
68 ✔
883
  ui->actionEdit->setEnabled(false);
34 ✔
884
  ui->actionDelete->setEnabled(false);
34 ✔
885
  searchTimer.start();
34 ✔
886
}
887

888
void MainWindow::onTimeoutSearch() {
38 ✔
889
  // The tree matches slash-separated paths: on Windows, team\bank typed is
890
  // team/bank, as exactMatchPath() reads it too.
891
  QString query = QDir::fromNativeSeparators(ui->lineEdit->text());
76 ✔
892

893
  if (query.isEmpty()) {
38 ✔
894
    ui->treeView->collapseAll();
1 ✔
895
    deselect();
1 ✔
896
  }
897

898
  // The words are matched literally, in order, with anything in between:
899
  // "work vpn" finds work/acme/vpn. Regular expressions belong to the
900
  // content search; here a typed "[" or "(" must not switch filtering off.
901
  QStringList words;
38 ✔
902
  for (const QString &word :
903
       query.split(QLatin1Char(' '), Qt::SkipEmptyParts)) {
114 ✔
904
    words << QRegularExpression::escape(word);
38 ✔
905
  }
906
  QRegularExpression regExp(words.join(QStringLiteral(".*")),
76 ✔
907
                            QRegularExpression::CaseInsensitiveOption);
38 ✔
908
  m_tree->setFilter(regExp);
38 ✔
909

910
  if (m_tree->proxy().rowCount() > 0 && !query.isEmpty()) {
38 ✔
911
    selectFirstFile();
27 ✔
912
  } else {
913
    ui->actionEdit->setEnabled(false);
11 ✔
914
    ui->actionDelete->setEnabled(false);
11 ✔
915
  }
916
}
76 ✔
917

918
void MainWindow::on_lineEdit_returnPressed() {
16 ✔
919
  qCDebug(lcQtPass) << "on_lineEdit_returnPressed"
16 ✔
920
                    << m_tree->proxy().rowCount();
×
921

922
  if (m_grep.inGrepMode()) {
16 ✔
923
    const QString query = ui->lineEdit->text();
11 ✔
924
    if (!query.isEmpty()) {
11 ✔
925
      ui->grepResultsList->clear();
8 ✔
926
      ui->statusBar->showMessage(tr("Searching…"));
16 ✔
927
      if (m_grep.beginSearch()) {
928
        QApplication::setOverrideCursor(Qt::WaitCursor);
8 ✔
929
      }
930
      QtPassSettings::getPass()->Grep(query, ui->grepCaseButton->isChecked());
16 ✔
931
    } else {
932
      cancelContentSearch();
3 ✔
933
      if (m_grep.cancelSearch()) {
934
        QApplication::restoreOverrideCursor();
2 ✔
935
      }
936
      ui->grepResultsList->clear();
3 ✔
937
      ui->grepResultsList->setVisible(false);
3 ✔
938
      ui->treeView->setVisible(true);
3 ✔
939
    }
940
    return;
941
  }
942

943
  // Return within the search delay acts on the text as typed, not on the
944
  // tree as the previous text filtered it.
945
  if (searchTimer.isActive()) {
5 ✔
946
    searchTimer.stop();
5 ✔
947
    onTimeoutSearch();
5 ✔
948
  }
949
  if (m_tree->proxy().rowCount() > 0) {
5 ✔
950
    selectFirstFile();
5 ✔
951
    on_treeView_clicked(ui->treeView->currentIndex());
5 ✔
952
  }
953
}
954

955
void MainWindow::on_grepButton_toggled(bool checked) {
22 ✔
956
  const AppSettings s = QtPassSettings::load();
22 ✔
957
  if (checked) {
22 ✔
958
    m_grep.enterGrepMode();
959
    ui->lineEdit->setPlaceholderText(tr("Search content (regex)"));
28 ✔
960
    // Both backends search through NativeGrep (QRegularExpression), so one
961
    // dialect: PCRE.
962
    ui->lineEdit->setToolTip(
14 ✔
963
        tr("Content search uses Perl-compatible regular expressions (PCRE)."));
14 ✔
964
    ui->lineEdit->clear();
14 ✔
965
    searchTimer.stop();
14 ✔
966
    m_tree->setFilter(QRegularExpression());
14 ✔
967
    ui->grepResultsList->setVisible(false);
14 ✔
968
    // Keep treeView visible until results arrive
969
  } else {
970
    cancelContentSearch();
8 ✔
971
    if (m_grep.leaveGrepMode()) {
972
      QApplication::restoreOverrideCursor();
2 ✔
973
    }
974
    searchTimer.stop();
8 ✔
975
    ui->lineEdit->blockSignals(true);
8 ✔
976
    ui->lineEdit->clear();
8 ✔
977
    ui->lineEdit->blockSignals(false);
8 ✔
978
    ui->lineEdit->setPlaceholderText(tr("Search password"));
16 ✔
979
    ui->lineEdit->setToolTip(QString());
16 ✔
980
    ui->grepResultsList->clear();
8 ✔
981
    ui->grepResultsList->setVisible(false);
8 ✔
982
    ui->treeView->setVisible(true);
8 ✔
983
    m_tree->setFilter(QRegularExpression());
8 ✔
984
  }
985
}
22 ✔
986

987
void MainWindow::onGrepFinished(
11 ✔
988
    const QList<QPair<QString, QStringList>> &results) {
989
  const GrepSearchController::FinishOutcome outcome = m_grep.finishSearch();
990
  if (outcome.restoreCursor) {
11 ✔
991
    QApplication::restoreOverrideCursor();
2 ✔
992
  }
993
  // Re-enable the UI before the discard check so a cancelled search can never
994
  // leave controls disabled.
995
  setUiElementsEnabled(true);
11 ✔
996
  if (outcome.discard) {
11 ✔
997
    return;
8 ✔
998
  }
999
  if (!m_grep.inGrepMode())
5 ✔
1000
    return;
1001
  ui->grepResultsList->clear();
5 ✔
1002
  if (results.isEmpty()) {
5 ✔
1003
    ui->statusBar->showMessage(tr("No matches found."), 3000);
4 ✔
1004
    ui->grepResultsList->setVisible(false);
2 ✔
1005
    ui->treeView->setVisible(true);
2 ✔
1006
    return;
2 ✔
1007
  }
1008
  const AppSettings s = QtPassSettings::load();
3 ✔
1009
  const bool hideContent = s.hideContent;
3 ✔
1010
  int totalLines = 0;
1011
  int entries = 0;
1012
  bool stopped = false;
1013
  for (const auto &pair : results) {
27 ✔
1014
    if (NativeGrep::isStoppedMarker(pair)) {
24 ✔
1015
      stopped = true;
1016
      continue;
×
1017
    }
1018
    ++entries;
24 ✔
1019
    auto *entryItem = new QTreeWidgetItem(ui->grepResultsList);
24 ✔
1020
    entryItem->setText(0, pair.first);
24 ✔
1021
    entryItem->setData(0, Qt::UserRole, pair.first);
24 ✔
1022
    for (const QString &line : pair.second) {
48 ✔
1023
      auto *lineItem = new QTreeWidgetItem(entryItem);
24 ✔
1024
      // The marker is no content: shown as it is with hidden content too,
1025
      // and not counted as a match.
1026
      if (NativeGrep::isMoreMarker(line)) {
24 ✔
1027
        lineItem->setText(0, tr("… more matches in this entry"));
×
1028
      } else {
1029
        lineItem->setText(0, hideContent ? "***" + tr("Content hidden") + "***"
72 ✔
1030
                                         : line);
1031
        ++totalLines;
24 ✔
1032
      }
1033
      lineItem->setData(0, Qt::UserRole, pair.first);
24 ✔
1034
    }
1035
  }
1036
  ui->grepResultsList->expandAll();
3 ✔
1037
  ui->treeView->setVisible(false);
3 ✔
1038
  ui->grepResultsList->setVisible(true);
3 ✔
1039
  if (stopped) {
3 ✔
1040
    // The search stopped there; more entries may match.
1041
    ui->statusBar->showMessage(
×
1042
        tr("Showing the first %n match(es); search for something narrower "
×
1043
           "to see the rest.",
1044
           nullptr, totalLines),
1045
        10000);
1046
  } else {
1047
    ui->statusBar->showMessage(tr("Found %n match(es)", nullptr, totalLines) +
9 ✔
1048
                                   " " +
3 ✔
1049
                                   tr("in %n entr(ies).", nullptr, entries),
6 ✔
1050
                               3000);
1051
  }
1052
  if (s.useAutoclearPanel)
3 ✔
1053
    clearPanelTimer.start();
1 ✔
1054
}
3 ✔
1055

1056
void MainWindow::on_grepResultsList_itemClicked(QTreeWidgetItem *item,
2 ✔
1057
                                                int /*column*/) {
1058
  const AppSettings s = QtPassSettings::load();
2 ✔
1059
  const QString entry = item->data(0, Qt::UserRole).toString();
2 ✔
1060
  if (entry.isEmpty())
2 ✔
1061
    return;
1062
  const QString fullPath =
1063
      QDir::cleanPath(QDir(s.passStore).filePath(entry + ".gpg"));
4 ✔
1064
  const QModelIndex proxyIndex = m_tree->indexFor(fullPath);
2 ✔
1065
  if (!proxyIndex.isValid())
1066
    return;
1067
  ui->treeView->setCurrentIndex(proxyIndex);
2 ✔
1068
  on_treeView_clicked(proxyIndex);
2 ✔
1069
  if (s.hideContent || s.useAutoclearPanel)
2 ✔
1070
    ui->grepResultsList->clear();
1 ✔
1071
  ui->grepResultsList->setVisible(false);
2 ✔
1072
  ui->treeView->setVisible(true);
2 ✔
1073
  ui->treeView->scrollTo(proxyIndex);
2 ✔
1074
  ui->treeView->setFocus();
2 ✔
1075
}
2 ✔
1076

1077
void MainWindow::cancelContentSearch() {
15 ✔
1078
  QtPassSettings::getRealPass()->CancelGrep();
15 ✔
1079
  QtPassSettings::getImitatePass()->CancelGrep();
15 ✔
1080
}
15 ✔
1081

1082
void MainWindow::selectFirstFile() {
32 ✔
1083
  // The entry named exactly as typed wins: with folders sorted first, the
1084
  // depth-first walk found team/bank before bank.
1085
  QModelIndex index = exactMatch();
32 ✔
1086
  if (!index.isValid()) {
1087
    index = firstFile(m_tree->rootIndex());
15 ✔
1088
  }
1089
  ui->treeView->setCurrentIndex(index);
32 ✔
1090
}
32 ✔
1091

1092
namespace {
1093
/**
1094
 * @brief @p path with each part below @p store spelled as stored on disk.
1095
 *
1096
 * Where the file system ignores case, "Bank.gpg" exists while the file is
1097
 * bank.gpg, and the tree knows the entry only by that spelling.
1098
 * @param store The store folder.
1099
 * @param path An existing file in the store.
1100
 * @return @p path itself when every part is spelled as stored, otherwise
1101
 *         the path with the stored spelling.
1102
 */
1103
auto spelledAsStored(const QString &store, const QString &path) -> QString {
33 ✔
1104
  const QStringList parts = QDir(store).relativeFilePath(path).split(
66 ✔
1105
      QLatin1Char('/'), Qt::SkipEmptyParts);
33 ✔
1106
  QDir dir(store);
33 ✔
1107
  bool respelled = false;
1108
  for (int i = 0; i < parts.size(); ++i) {
36 ✔
1109
    const bool leaf = i == parts.size() - 1;
36 ✔
1110
    const QStringList names =
1111
        dir.entryList((leaf ? QDir::Files : QDir::Dirs) | QDir::Hidden |
36 ✔
1112
                      QDir::NoDotAndDotDot);
39 ✔
1113
    QString name = parts.at(i);
1114
    if (!names.contains(name)) {
36 ✔
1115
      const auto stored = std::find_if(
×
1116
          names.cbegin(), names.cend(), [&name](const QString &candidate) {
1117
            return candidate.compare(name, Qt::CaseInsensitive) == 0;
×
1118
          });
1119
      if (stored == names.cend()) {
×
1120
        return path;
1121
      }
1122
      name = *stored;
×
1123
      respelled = true;
1124
    }
1125
    if (leaf) {
36 ✔
1126
      return respelled ? QDir::cleanPath(dir.filePath(name)) : path;
66 ✔
1127
    }
1128
    if (!dir.cd(name)) {
3 ✔
1129
      return path;
1130
    }
1131
  }
1132
  return path;
1133
}
33 ✔
1134
} // namespace
1135

1136
auto MainWindow::exactMatchPath() -> QString {
50 ✔
1137
  const QString text = QDir::fromNativeSeparators(ui->lineEdit->text());
100 ✔
1138
  const QString store = QtPassSettings::getPassStore();
100 ✔
1139
  // A name may begin or end with a space: " bank" is that entry, not bank.
1140
  // Only when no entry is named so are spaces around the text dropped.
1141
  for (const QString &typed : {text, text.trimmed()}) {
186 ✔
1142
    if (typed.isEmpty()) {
69 ✔
1143
      continue;
×
1144
    }
1145
    const QString path =
1146
        QDir::cleanPath(QDir(store).filePath(typed + QStringLiteral(".gpg")));
138 ✔
1147
    if (PathValidator::isPathInStore(store, path) && QFileInfo(path).isFile()) {
69 ✔
1148
      return spelledAsStored(store, path);
33 ✔
1149
    }
1150
  }
150 ✔
1151
  return {};
17 ✔
1152
}
1153

1154
auto MainWindow::exactMatch() -> QModelIndex {
46 ✔
1155
  const QString path = exactMatchPath();
46 ✔
1156
  if (path.isEmpty()) {
46 ✔
1157
    return {};
16 ✔
1158
  }
1159
  // indexFor() maps through the filter: a row the filter hides is no match.
1160
  const QModelIndex index = m_tree->indexFor(path);
30 ✔
1161
  if (!index.isValid() || !m_tree->fileInfo(index).isFile()) {
53 ✔
1162
    return {};
7 ✔
1163
  }
1164
  return index;
23 ✔
1165
}
1166

1167
void MainWindow::applySearchText(const QString &text) {
9 ✔
1168
  // A name search: content search, left on, kept its results over the tree
1169
  // and ignored the text.
1170
  if (ui->grepButton->isChecked()) {
9 ✔
1171
    ui->grepButton->setChecked(false);
1 ✔
1172
  }
1173
  delete m_pendingOpen;
9 ✔
1174
  ui->lineEdit->setText(text);
9 ✔
1175
  // Filter now, not after the search delay: the timer would leave the tree
1176
  // as the previous text filtered it.
1177
  searchTimer.stop();
9 ✔
1178
  onTimeoutSearch();
9 ✔
1179
  if (const QModelIndex exact = exactMatch(); exact.isValid()) {
9 ✔
1180
    openExactMatch(exact);
5 ✔
1181
    return;
5 ✔
1182
  }
1183
  // The tree loads folders in the background: at start, or right after the
1184
  // window is shown again, an entry that exists may not be in it yet. Try
1185
  // again as folders finish loading, for a few seconds, unless the search
1186
  // text changes meanwhile: any change ends the wait, even one typed back to
1187
  // this text, which is a new search that has not asked to open anything.
1188
  if (exactMatchPath().isEmpty()) {
8 ✔
1189
    return;
1190
  }
1191
  auto *pending = new QObject(this);
3 ✔
1192
  m_pendingOpen = pending;
1193
  QTimer::singleShot(5000, pending, &QObject::deleteLater);
3 ✔
1194
  // Disconnected at once: with deleteLater() alone, a folder that finished
1195
  // loading before the deletion still ran the open, or ran it twice.
1196
  const auto stop = [this, pending] {
2 ✔
1197
    disconnect(&m_tree->fileSystem(), nullptr, pending, nullptr);
2 ✔
1198
    disconnect(ui->lineEdit, nullptr, pending, nullptr);
2 ✔
1199
    pending->deleteLater();
2 ✔
1200
  };
5 ✔
1201
  connect(ui->lineEdit, &QLineEdit::textChanged, pending, stop);
3 ✔
1202
  connect(&m_tree->fileSystem(), &QFileSystemModel::directoryLoaded, pending,
3 ✔
1203
          [this, stop](const QString &) {
6 ✔
1204
            searchTimer.stop();
5 ✔
1205
            onTimeoutSearch();
5 ✔
1206
            if (const QModelIndex exact = exactMatch(); exact.isValid()) {
5 ✔
1207
              stop();
1 ✔
1208
              openExactMatch(exact);
1 ✔
1209
            }
1210
          });
5 ✔
1211
}
1212

1213
void MainWindow::openExactMatch(const QModelIndex &index) {
6 ✔
1214
  // Made current here, not left to the filter pass before: the tree may have
1215
  // moved its current row since, and with none on_treeView_clicked() only
1216
  // names the entry without decrypting it.
1217
  ui->treeView->setCurrentIndex(index);
6 ✔
1218
  on_treeView_clicked(index);
6 ✔
1219
}
6 ✔
1220

1221
auto MainWindow::firstFile(QModelIndex parentIndex) -> QModelIndex {
23 ✔
1222
  StoreModel &proxy = m_tree->proxy();
23 ✔
1223
  int numRows = proxy.rowCount(parentIndex);
23 ✔
1224
  for (int row = 0; row < numRows; ++row) {
30 ✔
1225
    QModelIndex index = proxy.index(row, 0, parentIndex);
20 ✔
1226
    if (m_tree->fileInfo(index).isFile()) {
20 ✔
1227
      return index;
13 ✔
1228
    }
1229
    if (proxy.hasChildren(index)) {
12 ✔
1230
      QModelIndex childFile = firstFile(index);
8 ✔
1231
      if (childFile.isValid())
1232
        return childFile;
5 ✔
1233
    }
1234
  }
1235
  return QModelIndex();
10 ✔
1236
}
1237

1238
// Guards the input dialogs (create, move, rename) against names like
1239
// "../../etc/passwd" or absolute paths escaping the store root.
1240
auto MainWindow::confirmPathInStore(const QString &candidate) -> bool {
11 ✔
1241
  if (PathValidator::isPathInStore(QtPassSettings::getPassStore(), candidate)) {
22 ✔
1242
    return true;
1243
  }
1244
  QMessageBox::warning(this, tr("Invalid name"),
9 ✔
1245
                       tr("That name would resolve outside the password "
3 ✔
1246
                          "store. Please choose a different name."));
1247
  return false;
3 ✔
1248
}
1249

1250
void MainWindow::setPassword(const QString &file, bool isNew) {
6 ✔
1251
  const AppSettings s = QtPassSettings::load();
6 ✔
1252
  PasswordDialog d(QtPassSettings::getPass(), s, file, isNew, this);
6 ✔
1253
  // A copy out of the editor is autocleared like one from the display.
1254
  connect(&d, &PasswordDialog::copied, &m_qtPass->clipboard(),
6 ✔
1255
          &ClipboardManager::trackCopied);
6 ✔
1256

1257
  if (isNew) {
6 ✔
1258
    const QString storePath = s.passStore;
1259
    QString folder = m_tree->currentDir(false);
1 ✔
1260
    if (folder.isEmpty()) {
1 ✔
1261
      folder = storePath;
×
1262
    }
1263
    // Folders to pick from, the tree's current one preselected. Real folders
1264
    // only: a linked or junctioned one would write the entry outside the store.
1265
    QStringList folders{QString()};
2 ✔
1266
    const QStringList found = Util::directoriesUnder(storePath);
1 ✔
1267
    for (const QString &path : found) {
16 ✔
1268
      const QString rel = QDir(storePath).relativeFilePath(path);
15 ✔
1269
      if (!rel.startsWith(u'.') && !rel.contains(QStringLiteral("/."))) {
45 ✔
1270
        folders << rel;
1271
      }
1272
    }
1273
    std::sort(folders.begin() + 1, folders.end());
1 ✔
1274
    d.setNewEntryLocation(storePath, folders,
1 ✔
1275
                          QDir(storePath).relativeFilePath(folder));
2 ✔
1276
    QHash<QString, QStringList> templates =
1277
        TemplateIO::readTemplates(storePath);
1 ✔
1278
    if (!templates.isEmpty()) {
1279
      QString defaultTemplate =
1280
          TemplateIO::getFolderTemplate(folder, storePath);
1 ✔
1281
      d.setAvailableTemplates(templates, defaultTemplate);
1 ✔
1282
    }
1283
  }
1 ✔
1284

1285
  if (!d.exec()) {
6 ✔
1286
    ui->treeView->setFocus();
5 ✔
1287
  }
1288
}
6 ✔
1289

1290
void MainWindow::addPassword() { setPassword(QString()); }
2 ✔
1291

1292
auto MainWindow::confirmDeletion(const QString &file, bool isDir) -> bool {
4 ✔
1293
  const QString path = QDir::separator() + file;
4 ✔
1294
  if (!isDir) {
4 ✔
1295
    return PlainMessageBox::askYes(
2 ✔
1296
        this, tr("Delete password?"),
2 ✔
1297
        tr("Are you sure you want to delete %1?").arg(path));
4 ✔
1298
  }
1299
  // Whole sentences, not a question stitched from pieces: a verb-final
1300
  // language cannot put the rest of the question after the path.
1301
  // Plain text, as every box quoting the store: the path is a name other
1302
  // writers control, and as rich text "a  b" would also show as "a b".
1303
  QString question =
1304
      tr("Are you sure you want to delete %1 and the whole content?").arg(path);
2 ✔
1305
  // A link, junction or special file inside is as unexpected as a stray
1306
  // plain file: the walker leaves them out of content and reports them.
1307
  QStringList skipped;
2 ✔
1308
  const QStringList content = Util::regularFilesUnder(
6 ✔
1309
      m_tree->fileSystem().rootPath() + path, {QStringLiteral("*")}, &skipped);
6 ✔
1310
  const bool unexpected =
1311
      !skipped.isEmpty() ||
2 ✔
1312
      std::any_of(content.cbegin(), content.cend(), [](const QString &entry) {
2 ✔
1313
        return QFileInfo(entry).suffix() != QLatin1String("gpg");
4 ✔
1314
      });
1315
  if (unexpected) {
1316
    question += QStringLiteral("\n\n") +
1 ✔
1317
                tr("Attention: there are unexpected files in the given "
1 ✔
1318
                   "folder, check them before continuing.");
1 ✔
1319
  }
1320
  return PlainMessageBox::askYes(this, tr("Delete folder?"), question);
4 ✔
1321
}
1322

1323
auto MainWindow::confirmLinkRemoval(const QString &file) -> bool {
1 ✔
1324
  // Only the link goes (ImitatePass::Remove unlinks it); nothing behind it
1325
  // is looked at or mentioned.
1326
  return PlainMessageBox::askYes(
1 ✔
1327
      this, tr("Delete link?"),
1 ✔
1328
      tr("%1 is a symbolic link or junction. Remove the link? What it "
1 ✔
1329
         "points to is left alone.")
1330
          .arg(QDir::separator() + file));
2 ✔
1331
}
1332

1333
void MainWindow::onDelete() {
8 ✔
1334
  const QModelIndex currentIndex = ui->treeView->currentIndex();
8 ✔
1335
  if (!currentIndex.isValid()) {
1336
    // Otherwise the whole password directory would be deleted (#556).
1337
    return;
5 ✔
1338
  }
1339

1340
  const bool isDir = !m_tree->fileInfo(currentIndex).isFile();
6 ✔
1341
  const QString file =
1342
      isDir ? m_tree->currentDir(true) : getFile(currentIndex, true);
6 ✔
1343
  const QString folder =
1344
      m_tree->fileSystem().rootPath() + QDir::separator() + file;
6 ✔
1345
  const bool linkedFolder = isDir && Util::isLinkedFolder(folder);
6 ✔
1346

1347
  if (!linkedFolder && refuseLinkedFolder(folder)) {
5 ✔
1348
    // Behind a link: deleting would reach outside the store.
1349
    return;
1350
  }
1351
  const bool confirmed =
1352
      linkedFolder ? confirmLinkRemoval(file) : confirmDeletion(file, isDir);
5 ✔
1353
  if (!confirmed) {
5 ✔
1354
    return;
1355
  }
1356
  QtPassSettings::getPass()->Remove(file, isDir);
6 ✔
1357
}
1358

1359
void MainWindow::cancelOtpRequest() {
83 ✔
1360
  m_otpRequestFile.clear();
83 ✔
1361
  m_copyRequestFile.clear();
83 ✔
1362
}
83 ✔
1363

1364
void MainWindow::onOperationError() {
33 ✔
1365
  cancelOtpRequest();
33 ✔
1366
  // executeWrapperStarted() emptied the panel and the browser when the
1367
  // operation started (a refusal says so too); what is left to forget is
1368
  // which entry the panel was about to show.
1369
  m_shownFile.clear();
33 ✔
1370
  // A save's refresh waiting for its push is dropped: it would clear the
1371
  // push's error (or whatever failed before it) from the browser.
1372
  m_refreshAfterPush.clear();
33 ✔
1373
  m_refreshAfterPushOwner = nullptr;
1374
}
33 ✔
1375

1376
// Derives the code in-process from one decrypt, so it works with either
1377
// backend on every platform; otpFromFileToClipboard() finishes the job.
1378
void MainWindow::onOtp() {
10 ✔
1379
  QString file = getFile(ui->treeView->currentIndex(), true);
10 ✔
1380
  if (file.isEmpty()) {
10 ✔
1381
    flashText(tr("No password selected for OTP generation"), true);
1 ✔
1382
    return;
1 ✔
1383
  }
1384
  if (!QtPassSettings::isUseOtp()) {
9 ✔
1385
    // Normally unreachable (the action is hidden), but never fail silently.
1386
    flashText(tr("No OTP code found in this password entry"), true);
1 ✔
1387
    return;
1 ✔
1388
  }
1389

1390
  // Fast path: the panel shows a live code, so no decrypt, and one clipboard
1391
  // write (two setMimeData calls in one turn can empty the Windows
1392
  // clipboard). Only for *this* entry: arrow keys and right-click move
1393
  // currentIndex without QTreeView::clicked, so the code may be another's.
1394
  const QString shown =
1395
      (m_shownFile == file) ? m_displayPanel->currentOtpCode() : QString();
8 ✔
1396
  if (!shown.isEmpty()) {
8 ✔
1397
    m_qtPass->clipboard().copyText(shown);
1 ✔
1398
    showStatusMessage(tr("OTP code copied to clipboard"));
2 ✔
1399
    return;
1400
  }
1401

1402
  // Fallback: decrypt once. The request file keeps passShowHandler from
1403
  // copying the password and tells otpFromFileToClipboard its answer.
1404
  m_otpRequestFile = file;
7 ✔
1405
  setUiElementsEnabled(false);
7 ✔
1406
  // Keep the marker in step so a second request takes the fast path; safe as
1407
  // executeWrapperStarted() clears the panel, so a failed decrypt shows none.
1408
  m_shownFile = file;
7 ✔
1409
  QtPassSettings::getPass()->Show(file);
14 ✔
1410
}
1411

1412
void MainWindow::onEdit() {
2 ✔
1413
  QString file = getFile(ui->treeView->currentIndex(), true);
2 ✔
1414
  editPassword(file);
2 ✔
1415
}
2 ✔
1416

1417
void MainWindow::onUsers() {
2 ✔
1418
  const QString dir = m_tree->currentDir(false);
2 ✔
1419
  if (refuseLinkedFolder(dir)) {
2 ✔
1420
    return;
1421
  }
1422

1423
  UsersDialog d(QtPassSettings::getPass(), QtPassSettings::load(), dir, this);
1 ✔
1424
  if (!d.exec()) {
1 ✔
1425
    ui->treeView->setFocus();
1 ✔
1426
  }
1427
}
1 ✔
1428

1429
void MainWindow::messageAvailable(const QString &message) {
10 ✔
1430
  show();
10 ✔
1431
  raise();
10 ✔
1432
  if (message.isEmpty()) {
10 ✔
1433
    focusInput();
1 ✔
1434
  } else {
1435
    ui->treeView->expandAll();
9 ✔
1436
    applySearchText(message);
9 ✔
1437
  }
1438
}
10 ✔
1439

1440
void MainWindow::updateProfileBox() {
172 ✔
1441
  const Profiles profiles = QtPassSettings::getProfiles();
172 ✔
1442
  bool activeGone = false;
1443

1444
  if (profiles.isEmpty()) {
7 ✔
1445
    ui->profileWidget->hide();
165 ✔
1446
  } else {
1447
    ui->profileWidget->show();
7 ✔
1448
    // A refill is no choice of the user's: clearing and adding items moves
1449
    // the current text, which would otherwise switch profiles.
1450
    const QSignalBlocker quiet(ui->profileBox);
7 ✔
1451
    ui->profileBox->clear();
7 ✔
1452
    for (auto i = profiles.cbegin(); i != profiles.cend(); ++i) {
19 ✔
1453
      if (!i.key().isEmpty()) {
12 ✔
1454
        ui->profileBox->addItem(i.key());
12 ✔
1455
      }
1456
    }
1457
    ui->profileBox->model()->sort(0);
7 ✔
1458
    int index = ui->profileBox->findText(QtPassSettings::getProfile());
14 ✔
1459
    if (index != -1) { //  -1 for not found
7 ✔
1460
      ui->profileBox->setCurrentIndex(index);
6 ✔
1461
    } else if (ui->profileBox->count() > 0) {
1 ✔
1462
      // The active profile is gone (removed in Settings): the box shows the
1463
      // first one, and the settings and backend must follow it, or the
1464
      // removed profile's store stays in use behind it.
1465
      ui->profileBox->setCurrentIndex(0);
1 ✔
1466
      activeGone = true;
1467
    }
1468
  }
7 ✔
1469
  if (activeGone) {
7 ✔
1470
    on_profileBox_currentTextChanged(ui->profileBox->currentText());
2 ✔
1471
  }
1472
  updateProfileBoxEnabled();
172 ✔
1473
}
172 ✔
1474

1475
void MainWindow::updateProfileBoxEnabled() {
580 ✔
1476
  // No profile switch while anything of the store runs or waits: the
1477
  // backend's store and environment would change under it, and what is
1478
  // still queued (a push after a save, say) would finish for the other
1479
  // profile (#2071). Asked of the backend, not only of the interface: the
1480
  // watchdog releases the interface while a slow gpg or git still runs.
1481
  // Every backend: one kept from before a switch of backend may still
1482
  // run what was queued on it.
1483
  ui->profileBox->setEnabled(m_uiEnabled && ui->profileBox->count() > 1 &&
1,161 ✔
1484
                             QtPassSettings::backendsIdle());
11 ✔
1485
}
580 ✔
1486

1487
void MainWindow::on_profileBox_currentTextChanged(const QString &name) {
6 ✔
1488
  if (m_freshStart || name == QtPassSettings::getProfile()) {
18 ✔
1489
    return;
1 ✔
1490
  }
1491
  // The box is disabled while anything runs; should a change come through
1492
  // anyway, the active profile stays and the box says so again.
1493
  if (!m_uiEnabled || !QtPassSettings::backendsIdle()) {
5 ✔
1494
    const QSignalBlocker quiet(ui->profileBox);
×
1495
    ui->profileBox->setCurrentText(QtPassSettings::getProfile());
×
1496
    return;
1497
  }
×
1498
  // A content search runs outside the queue: leaving grep mode cancels it,
1499
  // so its results for the old store are dropped, not shown for the new.
1500
  if (m_grep.inGrepMode()) {
5 ✔
1501
    ui->grepButton->setChecked(false);
1 ✔
1502
  }
1503

1504
  ui->lineEdit->clear();
5 ✔
1505

1506
  const Profile prof = QtPassSettings::getProfiles().value(name);
10 ✔
1507
  AppSettings s = QtPassSettings::load();
5 ✔
1508
  s.activeProfile = name;
5 ✔
1509
  s.passStore = prof.path;
5 ✔
1510
  s.passSigningKey = prof.signingKey;
5 ✔
1511
  // A profile without its own Git flags keeps the global values.
1512
  s.useGit = prof.useGit.value_or(s.useGit);
5 ✔
1513
  s.autoPush = prof.autoPush.value_or(s.autoPush);
5 ✔
1514
  s.autoPull = prof.autoPull.value_or(s.autoPull);
5 ✔
1515
  QtPassSettings::save(s);
5 ✔
1516
  ui->statusBar->showMessage(tr("Profile changed to %1").arg(name), 2000);
10 ✔
1517

1518
  QtPassSettings::getPass()->updateEnv();
5 ✔
1519

1520
  m_tree->setStore(QtPassSettings::getPassStore());
10 ✔
1521
  deselect();
5 ✔
1522
  ui->treeView->setCurrentIndex(QModelIndex());
5 ✔
1523
}
5 ✔
1524

1525
void MainWindow::initTrayIcon() {
3 ✔
1526
  m_tray = new TrayIcon(this);
3 ✔
1527
  if (!m_tray->getIsAllocated()) {
3 ✔
1528
    destroyTrayIcon();
3 ✔
1529
    return;
3 ✔
1530
  }
1531
#ifndef Q_OS_MACOS
1532
  m_tray->addToggle(ui->actionShowMenuBar);
×
1533
#endif
1534
}
1535

1536
void MainWindow::destroyTrayIcon() {
3 ✔
1537
  delete m_tray;
3 ✔
1538
  m_tray = nullptr;
3 ✔
1539
}
3 ✔
1540

1541
void MainWindow::closeEvent(QCloseEvent *event) {
4 ✔
1542
  // Save in both branches: a tray user only ever hides the window, and
1543
  // used to quit through the tray menu with nothing ever written.
1544
  saveWindowState();
4 ✔
1545
  // Only with a tray icon to come back from: without one (none asked for, or
1546
  // no system tray in this session) a hidden QtPass ran on invisibly, with the
1547
  // last entry in its window and the password on the clipboard.
1548
  if (QtPassSettings::isHideOnClose() && m_tray != nullptr) {
8 ✔
1549
    this->hide();
×
1550
    event->ignore();
1551
  } else {
1552
    m_qtPass->clipboard().clear();
4 ✔
1553
    event->accept();
1554
    // A visible QSystemTrayIcon keeps the application alive, so
1555
    // quitOnLastWindowClosed never fires; quit explicitly.
1556
    QApplication::quit();
4 ✔
1557
  }
1558
}
4 ✔
1559

1560
auto MainWindow::eventFilter(QObject *obj, QEvent *event) -> bool {
6,934 ✔
1561
  if ((obj == ui->toolBar || obj == menuBar()) &&
6,934 ✔
1562
      event->type() == QEvent::PaletteChange) {
1563
    // Breeze gives these bars a "header" palette and, after a runtime
1564
    // light/dark switch, stamps the previous theme's colours back from a
1565
    // cached kdeglobals, hiding the toolbar icons. Deferred so we never
1566
    // re-enter the style while it is still applying its palette.
1567
    QTimer::singleShot(0, this, &MainWindow::dropStaleToolsAreaPalettes);
36 ✔
1568
  }
1569
  if (obj == ui->lineEdit && event->type() == QEvent::KeyPress) {
6,934 ✔
1570
    auto *key = dynamic_cast<QKeyEvent *>(event);
4 ✔
1571
    if (key != nullptr && key->key() == Qt::Key_Down) {
4 ✔
1572
      ui->treeView->setFocus();
1 ✔
1573
    }
1574
    // Return ends at the search box: QLineEdit emits returnPressed() and
1575
    // leaves the key unaccepted, so keyPressEvent() would open the tree's
1576
    // current entry as well. In content search that is an entry nobody
1577
    // asked for; by name, the first hit a second time.
1578
    if (key != nullptr &&
4 ✔
1579
        (key->key() == Qt::Key_Return || key->key() == Qt::Key_Enter)) {
1 ✔
1580
      ui->lineEdit->event(event);
3 ✔
1581
      event->accept();
1582
      return true;
3 ✔
1583
    }
1584
  }
1585
  return QObject::eventFilter(obj, event);
6,931 ✔
1586
}
1587

1588
// Only once the application palette changed (see m_themeSwitched): a bar
1589
// whose active Window lightness is far from the application's shows the
1590
// other theme.
1591
void MainWindow::dropStaleToolsAreaPalettes() {
31 ✔
1592
  if (!m_themeSwitched) {
31 ✔
1593
    return;
1594
  }
1595
  constexpr int kStaleToolsAreaLightness = 64;
1596
  // The active group on both sides: a bar's palette() reads the inactive
1597
  // group while another window has focus (the settings app, during a theme
1598
  // switch), and Breeze gives the header set different inactive colours.
1599
  const int appLightness = QApplication::palette()
54 ✔
1600
                               .color(QPalette::Active, QPalette::Window)
1601
                               .lightness();
27 ✔
1602
  for (QWidget *bar : {static_cast<QWidget *>(ui->toolBar),
108 ✔
1603
                       static_cast<QWidget *>(menuBar())}) {
81 ✔
1604
    if (!bar->testAttribute(Qt::WA_SetPalette)) {
54 ✔
1605
      continue;
48 ✔
1606
    }
1607
    const int barLightness =
1608
        bar->palette().color(QPalette::Active, QPalette::Window).lightness();
12 ✔
1609
    if (qAbs(barLightness - appLightness) <= kStaleToolsAreaLightness) {
6 ✔
1610
      continue;
2 ✔
1611
    }
1612
    bar->setPalette(QPalette());
4 ✔
1613
    // Both bars are transparent and the style paints the tools area from the
1614
    // stale palette, so fill our own. Window, not their Button role, which is
1615
    // not the window colour in either theme.
1616
    bar->setBackgroundRole(QPalette::Window);
4 ✔
1617
    bar->setAutoFillBackground(true);
4 ✔
1618
  }
1619
}
1620

1621
void MainWindow::keyPressEvent(QKeyEvent *event) {
21 ✔
1622
  switch (event->key()) {
21 ✔
1623
  case Qt::Key_Delete:
1 ✔
1624
    onDelete();
1 ✔
1625
    break;
1 ✔
1626
  case Qt::Key_Return:
2 ✔
1627
  case Qt::Key_Enter:
1628
    // While content search results hide the tree, its current entry is not
1629
    // what the user looks at: Return on a result opens that result.
1630
    if (ui->treeView->isHidden()) {
2 ✔
1631
      QTreeWidgetItem *result = ui->grepResultsList->currentItem();
1 ✔
1632
      if (result != nullptr && ui->grepResultsList->hasFocus()) {
1 ✔
1633
        on_grepResultsList_itemClicked(result, 0);
1 ✔
1634
      }
1635
      break;
1636
    }
1637
    if (m_tree->proxy().rowCount() > 0) {
1 ✔
1638
      on_treeView_clicked(ui->treeView->currentIndex());
1 ✔
1639
    }
1640
    break;
1641
  case Qt::Key_Escape:
3 ✔
1642
    ui->lineEdit->clear();
3 ✔
1643
    break;
3 ✔
1644
  default:
1645
    break;
1646
  }
1647
}
21 ✔
1648

1649
void MainWindow::addShareMenu(QMenu &contextMenu, const AppSettings &s) {
9 ✔
1650
  const QString dirPath = QDir::cleanPath(m_tree->currentDir(false));
9 ✔
1651
  auto *shareMenu = new QMenu(tr("Share"), &contextMenu);
9 ✔
1652
  contextMenu.addMenu(shareMenu);
9 ✔
1653

1654
  const QString gpgIdPath = Pass::getGpgIdPath(dirPath, s.passStore);
9 ✔
1655
  const bool gpgIdExists = !gpgIdPath.isEmpty() && QFile(gpgIdPath).exists();
9 ✔
1656
  const QString exePath = s.usePass ? s.passExecutable : s.gpgExecutable;
9 ✔
1657
  const bool gpgAvailable =
1658
      !exePath.isEmpty() &&
18 ✔
1659
      (Executor::parseWslCommand(exePath) || QFile(exePath).exists());
18 ✔
1660

1661
  QAction *reencrypt = shareMenu->addAction(tr("Re-encrypt all passwords"));
9 ✔
1662
  reencrypt->setEnabled(gpgIdExists && gpgAvailable);
9 ✔
1663
  connect(reencrypt, &QAction::triggered, this,
9 ✔
1664
          [this, dirPath]() { reencryptPath(dirPath); });
30 ✔
1665

1666
  QAction *exportKey = shareMenu->addAction(tr("Export my public key..."));
9 ✔
1667
  exportKey->setEnabled(gpgAvailable);
9 ✔
1668
  connect(exportKey, &QAction::triggered, this, &MainWindow::exportPublicKey);
9 ✔
1669

1670
  QAction *addRecipientAction = shareMenu->addAction(tr("Add recipient..."));
9 ✔
1671
  addRecipientAction->setEnabled(gpgIdExists && gpgAvailable);
9 ✔
1672
  connect(addRecipientAction, &QAction::triggered, this,
9 ✔
1673
          [this, dirPath]() { addRecipient(dirPath); });
29 ✔
1674

1675
  QAction *shareHelp = shareMenu->addAction(tr("What is this?"));
9 ✔
1676
  connect(shareHelp, &QAction::triggered, this, &MainWindow::showShareHelp);
9 ✔
1677
}
9 ✔
1678

1679
void MainWindow::showContextMenu(const QPoint &pos) {
11 ✔
1680
  const AppSettings s = QtPassSettings::load();
11 ✔
1681
  const QModelIndex index = ui->treeView->indexAt(pos);
11 ✔
1682
  const bool selected = index.isValid();
1683
  if (!selected) {
1684
    ui->treeView->clearSelection();
1 ✔
1685
    ui->actionDelete->setEnabled(false);
1 ✔
1686
    ui->actionEdit->setEnabled(false);
1 ✔
1687
  }
1688
  ui->treeView->setCurrentIndex(index);
11 ✔
1689
  const QPoint globalPos = ui->treeView->viewport()->mapToGlobal(pos);
11 ✔
1690
  const QFileInfo fileOrFolder = m_tree->fileInfo(ui->treeView->currentIndex());
11 ✔
1691
  const bool isDir = fileOrFolder.isDir();
11 ✔
1692

1693
  QMenu contextMenu;
11 ✔
1694
  if (!selected || isDir) {
11 ✔
1695
    const std::array<std::pair<QString, void (MainWindow::*)()>, 4> onFolder{{
1696
        {tr("Open folder with file manager"), &MainWindow::openFolder},
10 ✔
1697
        {tr("Add folder"), &MainWindow::addFolder},
10 ✔
1698
        {tr("Add password"), &MainWindow::addPassword},
10 ✔
1699
        {tr("Users"), &MainWindow::onUsers},
10 ✔
1700
    }};
×
1701
    for (const auto &[text, slot] : onFolder) {
50 ✔
1702
      connect(contextMenu.addAction(text), &QAction::triggered, this, slot);
40 ✔
1703
    }
1704
  } else if (fileOrFolder.isFile()) {
1 ✔
1705
    connect(contextMenu.addAction(tr("Edit")), &QAction::triggered, this,
1 ✔
1706
            &MainWindow::onEdit);
2 ✔
1707
  }
1708
  if (selected) {
11 ✔
1709
    contextMenu.addSeparator();
10 ✔
1710
    if (isDir) {
10 ✔
1711
      connect(contextMenu.addAction(tr("Rename folder")), &QAction::triggered,
9 ✔
1712
              this, &MainWindow::renameFolder);
18 ✔
1713
    } else if (fileOrFolder.isFile()) {
1 ✔
1714
      connect(contextMenu.addAction(tr("Rename password")), &QAction::triggered,
1 ✔
1715
              this, &MainWindow::renamePassword);
2 ✔
1716
    }
1717
    connect(contextMenu.addAction(tr("Delete")), &QAction::triggered, this,
10 ✔
1718
            &MainWindow::onDelete);
10 ✔
1719
    if (isDir) {
10 ✔
1720
      addShareMenu(contextMenu, s);
9 ✔
1721
    }
1722
  }
1723
  contextMenu.exec(globalPos);
11 ✔
1724
}
11 ✔
1725

1726
void MainWindow::showBrowserContextMenu(const QPoint &pos) {
1 ✔
1727
  QMenu *contextMenu = ui->textBrowser->createStandardContextMenu(pos);
1 ✔
1728
  // Reparent from textBrowser: a browser stylesheet cascades to the child
1729
  // QMenu and breaks its opaque native background.
1730
  contextMenu->setParent(this, contextMenu->windowFlags());
1 ✔
1731
  QPoint globalPos = ui->textBrowser->viewport()->mapToGlobal(pos);
1 ✔
1732

1733
  contextMenu->exec(globalPos);
1 ✔
1734
  delete contextMenu;
1 ✔
1735
}
1 ✔
1736

1737
void MainWindow::openFolder() {
1 ✔
1738
  QString dir = m_tree->currentDir(false);
1 ✔
1739

1740
  QString path = QDir::toNativeSeparators(dir);
1 ✔
1741
  QDesktopServices::openUrl(QUrl::fromLocalFile(path));
1 ✔
1742
}
1 ✔
1743

1744
void MainWindow::addFolder() {
8 ✔
1745
  const AppSettings s = QtPassSettings::load();
8 ✔
1746
  bool ok;
1747
  QString dir = m_tree->currentDir(false);
8 ✔
1748
  QString newdir =
1749
      QInputDialog::getText(this, tr("New folder"),
8 ✔
1750
                            tr("New folder: \n(Will be placed in %1 )")
8 ✔
1751
                                .arg(s.passStore + m_tree->currentDir(true)),
16 ✔
1752
                            QLineEdit::Normal, "", &ok);
16 ✔
1753
  if (!ok || newdir.isEmpty()) {
8 ✔
1754
    return;
1755
  }
1756
  // Checked and created as one and the same path: the check resolves ".."
1757
  // lexically, the system after following links, so "link/../x" would pass
1758
  // as the store's x and be made beside the link's target.
1759
  newdir = QDir::cleanPath(newdir.prepend(dir));
7 ✔
1760
  if (!confirmPathInStore(newdir)) {
7 ✔
1761
    return;
1762
  }
1763
  // Behind a link the folder would be made outside the store, as Users,
1764
  // Re-encrypt and Delete already refuse.
1765
  if (refuseLinkedFolder(newdir)) {
6 ✔
1766
    return;
1767
  }
1768
  // The tree, like `pass ls`, hides names that start with a dot.
1769
  const QStringList parts =
1770
      QDir(s.passStore).relativeFilePath(newdir).split(u'/');
5 ✔
1771
  if (std::any_of(parts.cbegin(), parts.cend(), [](const QString &part) {
10 ✔
1772
        return part != u'.' && part.startsWith(u'.');
5 ✔
1773
      })) {
1774
    PlainMessageBox::warning(this, tr("Hidden folder"),
2 ✔
1775
                             tr("A folder that starts with a dot would be "
1 ✔
1776
                                "hidden from the list: %1")
1777
                                 .arg(newdir));
2 ✔
1778
    return;
1 ✔
1779
  }
1780
  // Exists already: an error, as QDir::mkdir() made it before.
1781
  if (QFileInfo::exists(newdir) || !Util::mkpathForStore(newdir)) {
4 ✔
1782
    PlainMessageBox::warning(this, tr("Error"),
2 ✔
1783
                             tr("Failed to create folder: %1").arg(newdir));
2 ✔
1784
    return;
1 ✔
1785
  }
1786
  // With a signing key, ImitatePass::loadVerifiedRecipients and pass
1787
  // (PASSWORD_STORE_SIGNING_KEY) refuse a .gpg-id without .gpg-id.sig, and
1788
  // signing needs a passphrase just to make a folder. So it inherits the
1789
  // parent's signed list; UsersDialog (Init) gives it its own.
1790
  const bool signingConfigured = !s.passSigningKey.trimmed().isEmpty();
3 ✔
1791
  if (s.addGPGId && !signingConfigured) {
3 ✔
1792
    // Seed from the parent's recipients in effect, not from `enabled` keys:
1793
    // that flag is only set in UsersDialog, so it left a zero-byte .gpg-id
1794
    // shadowing the parent's recipients (#1682).
1795
    if (!Pass::seedGpgIdFile(newdir, s.passStore)) {
3 ✔
1796
      PlainMessageBox::warning(
1 ✔
1797
          this, tr("Error"),
1 ✔
1798
          tr("Failed to create .gpg-id file in: %1").arg(newdir));
2 ✔
1799
      return;
1 ✔
1800
    }
1801
  }
1802
}
8 ✔
1803

1804
void MainWindow::renameFolder() {
3 ✔
1805
  bool ok;
1806
  QString srcDir = QDir::cleanPath(m_tree->currentDir(false));
3 ✔
1807
  QString srcDirName = QDir(srcDir).dirName();
3 ✔
1808
  QString newName =
1809
      QInputDialog::getText(this, tr("Rename folder"), tr("Rename folder to: "),
3 ✔
1810
                            QLineEdit::Normal, srcDirName, &ok);
6 ✔
1811
  if (!ok || newName.isEmpty()) {
3 ✔
1812
    return;
1813
  }
1814
  QString destDir = srcDir;
1815
  destDir.replace(srcDir.lastIndexOf(srcDirName), srcDirName.length(), newName);
2 ✔
1816
  if (!confirmPathInStore(destDir)) {
2 ✔
1817
    return;
1818
  }
1819
  QtPassSettings::getPass()->Move(srcDir, destDir, false);
3 ✔
1820
}
1821

1822
void MainWindow::editPassword(const QString &file) {
5 ✔
1823
  if (!file.isEmpty()) {
5 ✔
1824
    const AppSettings s = QtPassSettings::load();
5 ✔
1825
    if (s.useGit && s.autoPull) {
5 ✔
1826
      onUpdate(true);
1 ✔
1827
    }
1828
    // The dialog decrypts the entry itself to fill its fields. That decrypt
1829
    // lands on the same finishedShow the panel uses, so drop the panel's claim
1830
    // to it: otherwise passShowHandler() repaints and, with "Always copy",
1831
    // puts the entry's old password on the clipboard - replacing whatever the
1832
    // user copied to paste into the dialog.
1833
    m_shownFile.clear();
5 ✔
1834
    setPassword(file, false);
5 ✔
1835
  }
5 ✔
1836
}
5 ✔
1837

1838
void MainWindow::renamePassword() {
2 ✔
1839
  bool ok;
1840
  QString file = getFile(ui->treeView->currentIndex(), false);
2 ✔
1841
  QString filePath = QFileInfo(file).path();
2 ✔
1842
  QString fileName = QFileInfo(file).fileName();
2 ✔
1843
  if (fileName.endsWith(".gpg", Qt::CaseInsensitive)) {
4 ✔
1844
    fileName.chop(4);
2 ✔
1845
  }
1846

1847
  QString newName =
1848
      QInputDialog::getText(this, tr("Rename file"), tr("Rename file to: "),
2 ✔
1849
                            QLineEdit::Normal, fileName, &ok);
4 ✔
1850
  if (!ok || newName.isEmpty()) {
2 ✔
1851
    return;
1852
  }
1853
  QString newFile = QDir(filePath).filePath(newName);
2 ✔
1854
  if (!confirmPathInStore(newFile)) {
2 ✔
1855
    return;
1856
  }
1857
  QtPassSettings::getPass()->Move(file, newFile, false);
3 ✔
1858
}
1859

1860
void MainWindow::copySelectionOrPassword() {
2 ✔
1861
  QWidget *focus = QApplication::focusWidget();
2 ✔
1862
  // The widget's own copy: a SecretTextBrowser marks what it copies as
1863
  // secret for clipboard managers, as the context menu's Copy does.
1864
  if (auto *text = qobject_cast<QTextEdit *>(focus);
2 ✔
1865
      text != nullptr && text->textCursor().hasSelection()) {
2 ✔
1866
    text->copy();
1 ✔
1867
    return;
1 ✔
1868
  }
1869
  // Through the clipboard manager, as a copy button would: the label may be
1870
  // the OTP code, which gets the secret hint and the autoclear.
1871
  if (auto *label = qobject_cast<QLabel *>(focus);
1872
      label != nullptr && label->hasSelectedText()) {
1 ✔
1873
    m_qtPass->clipboard().copyText(label->selectedText());
1 ✔
1874
    return;
1 ✔
1875
  }
NEW
1876
  copyPasswordFromTreeview();
×
1877
}
1878

1879
void MainWindow::copyPasswordFromTreeview() {
9 ✔
1880
  QFileInfo fileOrFolder = m_tree->fileInfo(ui->treeView->currentIndex());
9 ✔
1881

1882
  if (fileOrFolder.isFile()) {
9 ✔
1883
    QString file = getFile(ui->treeView->currentIndex(), true);
9 ✔
1884
    // The newest Ctrl+C wins: finishedShow names its file, so the decrypt of
1885
    // an earlier request is simply not this one's.
1886
    m_copyRequestFile = file;
9 ✔
1887
    // This Show repaints the panel as well; see onOtp().
1888
    m_shownFile = file;
9 ✔
1889
    QtPassSettings::getPass()->Show(file);
18 ✔
1890
  }
1891
}
9 ✔
1892

1893
void MainWindow::passwordFromFileToClipboard(const QString &text,
29 ✔
1894
                                             const QString &file) {
1895
  if (m_copyRequestFile.isEmpty() || file != m_copyRequestFile) {
29 ✔
1896
    return;
24 ✔
1897
  }
1898
  m_copyRequestFile.clear();
8 ✔
1899
  // The first line, without a list of every line (an entry can expand into
1900
  // millions of them), and without the "\r" of a CRLF line end, as the
1901
  // password row and "Always copy" have it.
1902
  const QString first = FileContent::passwordLine(text);
8 ✔
1903
  // A `pass otp insert` entry's first line is the otpauth:// URI carrying the
1904
  // TOTP seed, and an OTP field holding a seed there is the same; copying it
1905
  // would leak 2FA material. Matches the display path
1906
  // (FileContent::getPasswordForDisplay / PasswordDisplayPanel).
1907
  if (FileContent::isOtpPasswordLine(first)) {
8 ✔
1908
    flashText(tr("This entry holds an OTP secret, not a password"), true);
6 ✔
1909
    return;
1910
  }
1911
  m_qtPass->clipboard().copyText(first);
5 ✔
1912
}
1913

1914
void MainWindow::showStatusMessage(const QString &msg, int timeout) {
27 ✔
1915
  ui->statusBar->showMessage(msg, timeout);
27 ✔
1916
}
27 ✔
1917

1918
void MainWindow::reencryptPath(const QString &dir) {
3 ✔
1919
  QDir checkDir(dir);
3 ✔
1920
  if (!checkDir.exists()) {
3 ✔
1921
    PlainMessageBox::critical(this, tr("Error"),
2 ✔
1922
                              tr("Directory does not exist: %1").arg(dir));
2 ✔
1923
    return;
1 ✔
1924
  }
1925
  if (refuseLinkedFolder(dir)) {
2 ✔
1926
    return;
1927
  }
1928

1929
  const bool yes = PlainMessageBox::askYes(
2 ✔
1930
      this, tr("Re-encrypt passwords"),
2 ✔
1931
      tr("Re-encrypt all passwords in %1?\n\n"
2 ✔
1932
         "This will re-encrypt ALL password files in this folder "
1933
         "using the current recipients defined in .gpg-id.\n\n"
1934
         "This may rewrite many files and cannot be undone easily.\n\n"
1935
         "Continue?")
1936
          .arg(QDir(dir).dirName()));
4 ✔
1937

1938
  if (!yes)
2 ✔
1939
    return;
1940

1941
  // Disable now; the asynchronous startReencryptPath signal re-runs this
1942
  // harmlessly.
1943
  startReencryptPath();
1 ✔
1944

1945
  // Under the current profile's settings: with the pass backend active, the
1946
  // native one is not re-initialised on a profile switch.
1947
  QtPassSettings::getImitatePass()->reencryptPath(
2 ✔
1948
      QDir::cleanPath(QDir(dir).absolutePath()), QtPassSettings::load());
2 ✔
1949
}
3 ✔
1950

1951
// Idempotent: reencryptPath() calls it before ImitatePass emits the signal.
1952
void MainWindow::startReencryptPath() {
6 ✔
1953
  m_reencryptRunning = true;
6 ✔
1954
  setUiElementsEnabled(false);
6 ✔
1955
  // The worker always ends with endReencryptPath(), and Cancel is available
1956
  // throughout, so the generic watchdog is not needed for this operation.
1957
  m_uiWatchdog.stop();
6 ✔
1958
  ui->treeView->setDisabled(true);
6 ✔
1959
  if (m_reencryptProgress)
6 ✔
1960
    return;
1961
  auto *progress = new QProgressDialog(tr("Re-encrypting passwords..."),
4 ✔
1962
                                       tr("Cancel"), 0, 0, this);
8 ✔
1963
  progress->setWindowTitle(tr("Re-encrypt passwords"));
4 ✔
1964
  progress->setWindowModality(Qt::WindowModal);
4 ✔
1965
  progress->setAutoClose(false);
4 ✔
1966
  progress->setAutoReset(false);
4 ✔
1967
  progress->setMinimumDuration(0);
4 ✔
1968
  connect(progress, &QProgressDialog::canceled, this, [this]() {
4 ✔
1969
    QtPassSettings::getImitatePass()->cancelReencryptPath();
1 ✔
1970
    showStatusMessage(tr("Cancelling re-encryption"), 5000);
1 ✔
1971
  });
1 ✔
1972
  m_reencryptProgress = progress;
1973
  progress->show();
4 ✔
1974
}
1975

1976
void MainWindow::reencryptProgress(int current, int total) {
5 ✔
1977
  if (!m_reencryptProgress)
5 ✔
1978
    return;
1979
  m_reencryptProgress->setMaximum(total);
4 ✔
1980
  m_reencryptProgress->setLabelText(
4 ✔
1981
      tr("Re-encrypting passwords: %1 of %2").arg(current).arg(total));
8 ✔
1982
  // On a modal dialog setValue() runs processEvents(), which can deliver
1983
  // endReencryptPath() and reset m_reencryptProgress: keep this last.
1984
  m_reencryptProgress->setValue(current);
4 ✔
1985
}
1986

1987
void MainWindow::endReencryptPath() {
4 ✔
1988
  m_reencryptRunning = false;
4 ✔
1989
  if (m_reencryptProgress) {
4 ✔
1990
    m_reencryptProgress->hide();
4 ✔
1991
    m_reencryptProgress->deleteLater();
4 ✔
1992
    m_reencryptProgress = nullptr;
1993
  }
1994
  setUiElementsEnabled(true);
4 ✔
1995
}
4 ✔
1996

1997
void MainWindow::exportPublicKey() {
3 ✔
1998
  const AppSettings s = QtPassSettings::load();
3 ✔
1999
  const QString identity = s.passSigningKey;
2000
  if (identity.isEmpty()) {
3 ✔
2001
    QMessageBox::information(
2 ✔
2002
        this, tr("Export public key"),
1 ✔
2003
        tr("<h3>Export your public key</h3>"
×
2004
           "<p>No signing key is configured. Set one in QtPass Settings "
2005
           "&gt; GPG keys, or run this in a terminal:</p>"
2006
           "<pre>gpg --armor --export --output my_key.asc &lt;your-key-id"
2007
           "&gt;</pre>"
2008
           "<p>Then send the file to your teammates.</p>"));
2009
    return;
1 ✔
2010
  }
2011
  QString gpgExe = s.gpgExecutable;
2012
  if (gpgExe.isEmpty()) {
2 ✔
2013
    gpgExe = QStringLiteral("gpg");
×
2014
  }
2015
  QStringList args = {"--armor", "--export"};
10 ✔
2016
  args.append(identity.split(' ', Qt::SkipEmptyParts));
2 ✔
2017
  QString stdOut;
2 ✔
2018
  QString stdErr;
2 ✔
2019
  int exitCode = Executor::executeBlocking(gpgExe, args, &stdOut, &stdErr);
2 ✔
2020
  if (exitCode != 0 || stdOut.isEmpty()) {
2 ✔
2021
    PlainMessageBox::warning(this, tr("Export public key"),
2 ✔
2022
                             tr("Could not export public key for %1.\n\n%2")
1 ✔
2023
                                 .arg(identity, stdErr.isEmpty()
2 ✔
2024
                                                    ? tr("No output from gpg.")
2 ✔
2025
                                                    : stdErr));
2026
    return;
2027
  }
2028
  ExportPublicKeyDialog dialog(identity, stdOut, this);
1 ✔
2029
  dialog.exec();
1 ✔
2030
}
4 ✔
2031

2032
// UsersDialog only ticks keys already in the keyring; importing a foreign
2033
// key still has to happen via gpg (or QtPass settings) first.
2034
void MainWindow::addRecipient(const QString &dir) {
2 ✔
2035
  if (refuseLinkedFolder(dir)) {
2 ✔
2036
    return;
1 ✔
2037
  }
2038
  UsersDialog d(QtPassSettings::getPass(), QtPassSettings::load(), dir, this);
1 ✔
2039
  d.exec();
1 ✔
2040
}
1 ✔
2041

2042
// A tree-picked folder that is, or lies behind, a symlink or junction is not
2043
// a folder of the store. The store root itself may be a link (a synced
2044
// folder); that is configuration, not a tree pick.
2045
auto MainWindow::refuseLinkedFolder(const QString &dir) -> bool {
17 ✔
2046
  if (!Util::isUnderLink(dir, QtPassSettings::load().passStore)) {
17 ✔
2047
    return false;
2048
  }
2049
  PlainMessageBox::critical(
4 ✔
2050
      this, tr("Not a folder of the store"),
4 ✔
2051
      tr("%1 is, or lies behind, a symbolic link or junction. What that "
4 ✔
2052
         "points to is not part of the password store and is left alone.")
2053
          .arg(QDir::toNativeSeparators(QDir::cleanPath(dir))));
8 ✔
2054
  return true;
4 ✔
2055
}
2056

2057
void MainWindow::showShareHelp() {
1 ✔
2058
  QMessageBox::information(
2 ✔
2059
      this, tr("Sharing passwords with GPG"),
1 ✔
2060
      tr("<h3>Sharing passwords with GPG</h3>"
1 ✔
2061
         "<p>To share passwords with other users:</p>"
2062
         "<ol>"
2063
         "<li><b>Export your public key</b> and send it to teammates</li>"
2064
         "<li><b>Import teammates' public keys</b> into your GPG keyring</li>"
2065
         "<li><b>Re-encrypt passwords</b> so all recipients can decrypt "
2066
         "them</li>"
2067
         "</ol>"
2068
         "<p>Only people who have a matching secret key can decrypt the "
2069
         "passwords.</p>"
2070
         "<p><b>Tip:</b> Use the same GPG key for all shared folders.</p>"
2071
         "<p>See the FAQ for more details.</p>"));
2072
}
1 ✔
2073

2074
void MainWindow::updateGitButtonVisibility(bool uiEnabled) {
372 ✔
2075
  const AppSettings s = QtPassSettings::load();
372 ✔
2076
  // Without Git there is nothing to push or pull, ever: the buttons go, not
2077
  // grey out. While an operation runs they stay and are disabled.
2078
  const bool usable =
2079
      s.useGit && !(s.gitExecutable.isEmpty() && s.passExecutable.isEmpty());
372 ✔
2080
  ui->actionPush->setVisible(usable);
372 ✔
2081
  ui->actionUpdate->setVisible(usable);
372 ✔
2082
  // The separator in front of them would otherwise sit next to the next one.
2083
  const QList<QAction *> actions = ui->toolBar->actions();
372 ✔
2084
  const qsizetype at = actions.indexOf(ui->actionPush);
372 ✔
2085
  if (at > 0 && actions.at(at - 1)->isSeparator()) {
372 ✔
2086
    actions.at(at - 1)->setVisible(usable);
372 ✔
2087
  }
2088
  enableGitButtons(usable && uiEnabled);
372 ✔
2089
}
372 ✔
2090

2091
void MainWindow::updateOtpButtonVisibility(bool uiEnabled) {
372 ✔
2092
  // No platform gating: codes are generated in-process. Visible but disabled
2093
  // when OTP is off: the panel never shows an OTP field (a secret), so hiding
2094
  // this too would leave no trace of the feature. Honour uiEnabled, or the
2095
  // user can stack Show calls while a decrypt is in flight.
2096
  ui->actionOtp->setVisible(true);
372 ✔
2097
  ui->actionOtp->setEnabled(QtPassSettings::isUseOtp() && uiEnabled);
385 ✔
2098
}
372 ✔
2099

2100
void MainWindow::updateGrepButtonVisibility() {
168 ✔
2101
  const bool enabled = QtPassSettings::isUseGrepSearch();
168 ✔
2102
  ui->grepButton->setVisible(enabled);
168 ✔
2103
  ui->grepCaseButton->setVisible(enabled);
168 ✔
2104
  if (!enabled && m_grep.inGrepMode()) {
168 ✔
2105
    ui->grepButton->setChecked(false);
1 ✔
2106
  }
2107
}
168 ✔
2108

2109
void MainWindow::enableGitButtons(const bool &state) {
372 ✔
2110
  ui->actionPush->setEnabled(state);
372 ✔
2111
  ui->actionUpdate->setEnabled(state);
372 ✔
2112
}
372 ✔
2113

2114
void MainWindow::critical(const QString &title, const QString &msg) {
3 ✔
2115
  // Pass's messages quote store paths; see PlainMessageBox.
2116
  PlainMessageBox::critical(this, title, msg);
3 ✔
2117
}
3 ✔
2118

2119
void MainWindow::onProcessOutput(const QString &output, bool isError,
7 ✔
2120
                                 Enums::PROCESS pid) {
2121
  if (!QtPassSettings::isShowProcessOutput()) {
7 ✔
2122
    return;
2123
  }
2124
  m_processOutput->append(output, isError,
6 ✔
2125
                          ProcessOutputPanel::processName(pid));
12 ✔
2126
}
2127

2128
void MainWindow::updateProcessOutputVisibility() {
3 ✔
2129
  // The action's toggled handler shows or hides the dock.
2130
  ui->actionShowProcessOutput->setChecked(
3 ✔
2131
      QtPassSettings::isShowProcessOutput());
3 ✔
2132
  m_processOutput->setVisible(QtPassSettings::isShowProcessOutput());
3 ✔
2133
}
3 ✔
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