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

IJHack / QtPass / 44081359370

17 Nov 2026 12:14PM UTC coverage: 96.369% (-0.05%) from 96.422%
44081359370

push

github

web-flow
Add folder: inherit the parent's recipients, name nested lists (#2248)

* Add folder: inherit the parent's recipients, name nested lists

"Add folder" copied the parent's recipients into the new folder's own
.gpg-id when no signing key was set (#1688). A later removal above it
did not reach that copy, so the folder's entries stayed encrypted to the
person removed, while the users dialog suggested subfolders were
covered. The folder now gets no .gpg-id and uses its parent's list, as
with pass and as QtPass already did with a signing key; the users dialog
gives it its own. Pass::seedGpgIdFile() and its tests go.

Copies made by earlier versions stay, so the users dialog names the
folders below the edited one that have a list of their own, which saving
there does not change.

Scan finding ANT-2026-3I1PV36T.

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

* CHANGELOG: with a signing key, save a nested copy, do not delete it

From the #2248 review: a list this device accepted is not replaced by
the parent's when deleted; saving into that folder then stops with
"Recipient list missing". Deleting a copy is the advice only for a store
without a signing key.

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

* CHANGELOG: untick removed recipients before saving a nested copy

From the #2248 review: the users dialog opens with the copy's list
ticked, so saving it unchanged keeps whoever was removed above.

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

* CHANGELOG: rewrap the Add folder upgrade note

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

* CHANGELOG: re-encrypt the folder after removing a nested copy

From the #2248 review: removing an unsigned copy changes which list new
entries use, not the ciphertext o... (continued)

19 of 20 new or added lines in 1 file covered. (95.0%)

7 existing lines in 2 files now uncovered.

8972 of 9310 relevant lines covered (96.37%)

756.22 hits per line

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

97.13
/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)
173 ✔
67
    : QMainWindow(parent), ui(new Ui::MainWindow) {
173 ✔
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);
173 ✔
74

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

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

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

90
  initTextBrowser();
173 ✔
91

92
  updateProfileBox();
173 ✔
93

94
  initDisplayPanel();
173 ✔
95

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

98
  // Install the search-box key filter once, not on every setUiElementsEnabled
99
  // call.
100
  ui->lineEdit->installEventFilter(this);
173 ✔
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);
173 ✔
104
  menuBar()->installEventFilter(this);
173 ✔
105

106
  initTimers();
173 ✔
107

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

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

115
  setUiElementsEnabled(true);
173 ✔
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();
173 ✔
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())) {
174 ✔
123
    if (!config()) {
2 ✔
124
      return;
125
    }
126
  }
127
  m_freshStart = false;
172 ✔
128
  m_initSucceeded = true;
172 ✔
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()) {
172 ✔
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() {
173 ✔
146
  connect(m_qtPass, &QtPass::outputReady, this,
173 ✔
147
          [this](const QString &html) { flashText(html, false, true); });
215 ✔
148
  connect(m_qtPass, &QtPass::operationFinished, this,
173 ✔
149
          [this]() { setUiElementsEnabled(true); });
234 ✔
150
  connect(m_qtPass, &QtPass::statusMessage, this,
173 ✔
151
          &MainWindow::showStatusMessage);
173 ✔
152
  connect(m_qtPass, &QtPass::pushRequested, this, &MainWindow::onAutoPush);
173 ✔
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]() {
173 ✔
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,
173 ✔
171
          [this](const QString &message) { showStatusMessage(message); });
190 ✔
172
  // Both backends: the active one can change through the configuration
173
  // dialog without a restart.
174
  connectPassSignals(QtPassSettings::getRealPass());
173 ✔
175
  connectPassSignals(QtPassSettings::getImitatePass());
173 ✔
176
  ImitatePass *ipass = QtPassSettings::getImitatePass();
173 ✔
177
  connect(ipass, &ImitatePass::startReencryptPath, this,
173 ✔
178
          &MainWindow::startReencryptPath);
173 ✔
179
  connect(ipass, &ImitatePass::reencryptProgress, this,
173 ✔
180
          &MainWindow::reencryptProgress);
173 ✔
181
  connect(ipass, &ImitatePass::endReencryptPath, this,
173 ✔
182
          &MainWindow::endReencryptPath);
173 ✔
183
}
173 ✔
184

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

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

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

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

230
  connect(&searchTimer, &QTimer::timeout, this, &MainWindow::onTimeoutSearch);
173 ✔
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);
173 ✔
235
  m_uiWatchdog.setInterval(UiWatchdogMs);
173 ✔
236
  connect(&m_uiWatchdog, &QTimer::timeout, this, [this]() {
173 ✔
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
}
173 ✔
244

245
void MainWindow::initProcessOutput() {
173 ✔
246
  m_processOutput = new ProcessOutputPanel(this);
173 ✔
247
  addDockWidget(Qt::BottomDockWidgetArea, m_processOutput);
173 ✔
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());
173 ✔
251
  // From the setting, not isVisible(): the window is not shown yet, so no
252
  // child of it reports visible.
253
  ui->actionShowProcessOutput->setChecked(
173 ✔
254
      QtPassSettings::isShowProcessOutput());
173 ✔
255
  connect(ui->actionShowProcessOutput, &QAction::toggled, this,
173 ✔
256
          [this](bool show) {
173 ✔
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,
173 ✔
266
          [this](const QString &out, const QString &err, Enums::PROCESS pid) {
173 ✔
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
}
173 ✔
284

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

292
// The signals of one backend that the window answers itself.
293
void MainWindow::connectPassSignals(Pass *pass) {
346 ✔
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);
346 ✔
297
  connect(pass, &Pass::critical, this, &MainWindow::critical);
346 ✔
298
  connect(pass, &Pass::startingExecuteWrapper, this,
346 ✔
299
          &MainWindow::executeWrapperStarted);
346 ✔
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);
346 ✔
303
  connect(pass, &Pass::statusMsg, this, &MainWindow::showStatusMessage);
346 ✔
304
  connect(pass, &Pass::finishedShow, this, &MainWindow::passShowHandler);
346 ✔
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);
346 ✔
308
  connect(pass, &Pass::finishedShow, this,
346 ✔
309
          &MainWindow::passwordFromFileToClipboard);
346 ✔
310
  connect(pass, &Pass::finishedGrep, this, &MainWindow::onGrepFinished);
346 ✔
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]() {
346 ✔
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
}
346 ✔
330

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

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

356
auto MainWindow::event(QEvent *event) -> bool {
7,739 ✔
357
  if (event->type() == QEvent::ApplicationPaletteChange) {
7,739 ✔
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,739 ✔
364
}
365

366
void MainWindow::changeEvent(QEvent *event) {
232 ✔
367
  QWidget::changeEvent(event);
232 ✔
368
  if (event->type() == QEvent::PaletteChange && m_displayPanel != nullptr) {
232 ✔
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() &&
232 ✔
375
      isVisible()) {
376
    // Defer a tick so the activation dispatch chain unwinds first: calling
377
    // focusInput() inline has segfaulted on half-rebuilt ui state.
378
    QMetaObject::invokeMethod(this, &MainWindow::focusInput,
38 ✔
379
                              Qt::QueuedConnection);
380
  }
381
}
232 ✔
382

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

395
void MainWindow::initToolBarButtons() {
173 ✔
396
  connect(ui->actionAddPassword, &QAction::triggered, this,
173 ✔
397
          &MainWindow::addPassword);
173 ✔
398
  connect(ui->actionAddFolder, &QAction::triggered, this,
173 ✔
399
          &MainWindow::addFolder);
173 ✔
400
  connect(ui->actionEdit, &QAction::triggered, this, &MainWindow::onEdit);
173 ✔
401
  connect(ui->actionDelete, &QAction::triggered, this, &MainWindow::onDelete);
173 ✔
402
  connect(ui->actionPush, &QAction::triggered, this, &MainWindow::onPush);
173 ✔
403
  connect(ui->actionUpdate, &QAction::triggered, this, &MainWindow::onUpdate);
173 ✔
404
  connect(ui->actionUsers, &QAction::triggered, this, &MainWindow::onUsers);
173 ✔
405
  connect(ui->actionConfig, &QAction::triggered, this, &MainWindow::onConfig);
173 ✔
406
  connect(ui->actionOtp, &QAction::triggered, this, &MainWindow::onOtp);
173 ✔
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);
173 ✔
412
  connect(ui->actionClose, &QAction::triggered, this, &MainWindow::close);
173 ✔
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);
173 ✔
420
  ui->actionShowMenuBar->setChecked(QtPassSettings::load().showMenuBar);
173 ✔
421
  menuBar()->setVisible(ui->actionShowMenuBar->isChecked());
173 ✔
422
  connect(ui->actionShowMenuBar, &QAction::toggled, this, [this](bool show) {
173 ✔
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);
173 ✔
429
#endif
430
  connect(ui->actionFaq, &QAction::triggered, this, [] {
174 ✔
431
    QDesktopServices::openUrl(QUrl(QStringLiteral("https://qtpass.org/faq")));
2 ✔
432
  });
1 ✔
433
  connect(ui->actionAbout, &QAction::triggered, this, &MainWindow::showAbout);
173 ✔
434
  connect(ui->actionAboutQt, &QAction::triggered, qApp, &QApplication::aboutQt);
173 ✔
435

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

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

457
  QPixmap logo = QPixmap::fromImage(QImage(":/artwork/icon.svg"))
346 ✔
458
                     .scaledToHeight(statusBar()->height());
173 ✔
459
  auto *logoApp = new QLabel(statusBar());
173 ✔
460
  logoApp->setPixmap(logo);
173 ✔
461
  statusBar()->addPermanentWidget(logoApp);
173 ✔
462
}
173 ✔
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,
82 ✔
469
                           const bool isHtml) {
470
  if (isError) {
82 ✔
471
    ui->textBrowser->setTextColor(Qt::red);
10 ✔
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();
72 ✔
477
    format.clearForeground();
478
    ui->textBrowser->setCurrentCharFormat(format);
72 ✔
479
  }
480

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

661
void MainWindow::executeWrapperStarted() {
63 ✔
662
  m_displayPanel->clear();
63 ✔
663
  ui->textBrowser->clear();
63 ✔
664
  setUiElementsEnabled(false);
63 ✔
665
  clearPanelTimer.stop();
63 ✔
666
  if (QtPassSettings::isShowProcessOutput()) {
63 ✔
667
    m_processOutput->setVisible(true);
58 ✔
668
  }
669
}
63 ✔
670

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

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

713
  m_displayPanel->clear();
27 ✔
714

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

727
  if (s.useAutoclearPanel) {
27 ✔
728
    clearPanelTimer.start();
2 ✔
729
  }
730

731
  flashText(QtPass::formatOutput(output), false, true);
54 ✔
732
  setUiElementsEnabled(true);
27 ✔
733
}
54 ✔
734

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

744
  if (p_output.isEmpty()) {
6 ✔
745
    // Distinguish "could not read the entry" from "entry has no OTP".
746
    flashText(tr("Could not decrypt this password entry"), true);
1 ✔
747
    setUiElementsEnabled(true);
1 ✔
748
    return;
1 ✔
749
  }
750

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

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

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

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

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

850
void MainWindow::restoreWindow() {
184 ✔
851
  // saveGeometry() covers position, size, maximized state and screen;
852
  // anything applied on top discards it. Centre only when nothing was saved.
853
  const QByteArray geometry = QtPassSettings::getGeometry();
368 ✔
854
  if (geometry.isEmpty() || !restoreGeometry(geometry)) {
184 ✔
855
    WindowStateStore::centreOnCursorScreen(*this);
4 ✔
856
  }
857
  restoreState(QtPassSettings::getSavestate(saveState()));
184 ✔
858
  const AppSettings s = QtPassSettings::load();
184 ✔
859

860
  applyWindowFlagsSettings();
184 ✔
861

862
  if (s.useTrayIcon && m_tray == nullptr) {
184 ✔
863
    initTrayIcon();
2 ✔
864
    // Minimized to the tray only when there is one: without a system tray
865
    // initTrayIcon() gave up, and a hidden window could not be brought back.
866
    if (s.startMinimized && m_tray != nullptr) {
2 ✔
867
      // since we are still in constructor, can't directly hide
868
      QTimer::singleShot(10, this, &MainWindow::hide);
×
869
    }
870
  } else if (!s.useTrayIcon && m_tray != nullptr) {
182 ✔
871
    destroyTrayIcon();
×
872
  }
873
}
368 ✔
874

875
void MainWindow::onConfig() { config(); }
1 ✔
876

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

894
void MainWindow::on_lineEdit_textChanged(const QString &arg1) {
47 ✔
895
  if (m_grep.inGrepMode())
47 ✔
896
    return;
897
  ui->statusBar->showMessage(tr("Looking for: %1").arg(arg1), 1000);
68 ✔
898
  ui->treeView->expandAll();
34 ✔
899
  // Drop any decrypt still pending for the entry that was shown: otherwise it
900
  // keeps its right to the panel and, with "Always copy", the clipboard, and
901
  // when it lands late it shows that entry's password under the new heading.
902
  m_shownFile.clear();
34 ✔
903
  cancelOtpRequest();
34 ✔
904
  clearPanel(false);
34 ✔
905
  ui->passwordName->setText("");
68 ✔
906
  ui->actionEdit->setEnabled(false);
34 ✔
907
  ui->actionDelete->setEnabled(false);
34 ✔
908
  searchTimer.start();
34 ✔
909
}
910

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

916
  if (query.isEmpty()) {
38 ✔
917
    ui->treeView->collapseAll();
2 ✔
918
    deselect();
2 ✔
919
  }
920

921
  // The words are matched literally, in order, with anything in between:
922
  // "work vpn" finds work/acme/vpn. Regular expressions belong to the
923
  // content search; here a typed "[" or "(" must not switch filtering off.
924
  QStringList words;
38 ✔
925
  for (const QString &word :
926
       query.split(QLatin1Char(' '), Qt::SkipEmptyParts)) {
113 ✔
927
    words << QRegularExpression::escape(word);
37 ✔
928
  }
929
  QRegularExpression regExp(words.join(QStringLiteral(".*")),
76 ✔
930
                            QRegularExpression::CaseInsensitiveOption);
38 ✔
931
  m_tree->setFilter(regExp);
38 ✔
932

933
  if (m_tree->proxy().rowCount() > 0 && !query.isEmpty()) {
38 ✔
934
    selectFirstFile();
27 ✔
935
  } else {
936
    ui->actionEdit->setEnabled(false);
11 ✔
937
    ui->actionDelete->setEnabled(false);
11 ✔
938
  }
939
}
76 ✔
940

941
void MainWindow::on_lineEdit_returnPressed() {
17 ✔
942
  qCDebug(lcQtPass) << "on_lineEdit_returnPressed"
17 ✔
943
                    << m_tree->proxy().rowCount();
×
944

945
  if (m_grep.inGrepMode()) {
17 ✔
946
    const QString query = ui->lineEdit->text();
12 ✔
947
    if (!query.isEmpty()) {
12 ✔
948
      ui->grepResultsList->clear();
9 ✔
949
      ui->statusBar->showMessage(tr("Searching…"));
18 ✔
950
      if (m_grep.beginSearch()) {
951
        QApplication::setOverrideCursor(Qt::WaitCursor);
9 ✔
952
      }
953
      QtPassSettings::getPass()->Grep(query, ui->grepCaseButton->isChecked());
18 ✔
954
    } else {
955
      cancelContentSearch();
3 ✔
956
      if (m_grep.cancelSearch()) {
957
        QApplication::restoreOverrideCursor();
2 ✔
958
      }
959
      ui->grepResultsList->clear();
3 ✔
960
      showContentResults(false);
3 ✔
961
    }
962
    return;
963
  }
964

965
  // Return within the search delay acts on the text as typed, not on the
966
  // tree as the previous text filtered it.
967
  if (searchTimer.isActive()) {
5 ✔
968
    searchTimer.stop();
5 ✔
969
    onTimeoutSearch();
5 ✔
970
  }
971
  if (m_tree->proxy().rowCount() > 0) {
5 ✔
972
    selectFirstFile();
5 ✔
973
    on_treeView_clicked(ui->treeView->currentIndex());
5 ✔
974
  }
975
}
976

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

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

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

1103
void MainWindow::showContentResults(bool shown) {
29 ✔
1104
  ui->grepResultsList->setVisible(shown);
29 ✔
1105
  ui->treeView->setVisible(!shown);
29 ✔
1106
  if (shown) {
29 ✔
1107
    // The tree's current entry is out of sight: Delete, Edit and OTP would
1108
    // act on it, not on a result. Opening a result shows the tree again.
1109
    ui->actionDelete->setEnabled(false);
6 ✔
1110
    ui->actionEdit->setEnabled(false);
6 ✔
1111
    updateOtpButtonVisibility(false);
6 ✔
1112
  } else if (ui->treeView->selectionModel()->hasSelection()) {
23 ✔
1113
    // Only for an entry still selected: with nothing selected there is no
1114
    // entry for Edit and Delete to act on.
1115
    setUiElementsEnabled(m_uiEnabled);
8 ✔
1116
  }
1117
}
29 ✔
1118

1119
void MainWindow::cancelContentSearch() {
24 ✔
1120
  QtPassSettings::getRealPass()->CancelGrep();
24 ✔
1121
  QtPassSettings::getImitatePass()->CancelGrep();
24 ✔
1122
}
24 ✔
1123

1124
void MainWindow::selectFirstFile() {
32 ✔
1125
  // The entry named exactly as typed wins: with folders sorted first, the
1126
  // depth-first walk found team/bank before bank.
1127
  QModelIndex index = exactMatch();
32 ✔
1128
  if (!index.isValid()) {
1129
    index = firstFile(m_tree->rootIndex());
16 ✔
1130
  }
1131
  ui->treeView->setCurrentIndex(index);
32 ✔
1132
}
32 ✔
1133

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

1178
auto MainWindow::exactMatchPath() -> QString {
46 ✔
1179
  const QString text = QDir::fromNativeSeparators(ui->lineEdit->text());
92 ✔
1180
  const QString store = QtPassSettings::getPassStore();
92 ✔
1181
  // A name may begin or end with a space: " bank" is that entry, not bank.
1182
  // Only when no entry is named so are spaces around the text dropped.
1183
  for (const QString &typed : {text, text.trimmed()}) {
176 ✔
1184
    if (typed.isEmpty()) {
66 ✔
1185
      continue;
×
1186
    }
1187
    const QString path =
1188
        QDir::cleanPath(QDir(store).filePath(typed + QStringLiteral(".gpg")));
132 ✔
1189
    if (PathValidator::isPathInStore(store, path) && QFileInfo(path).isFile()) {
66 ✔
1190
      return spelledAsStored(store, path);
28 ✔
1191
    }
1192
  }
138 ✔
1193
  return {};
18 ✔
1194
}
1195

1196
auto MainWindow::exactMatch() -> QModelIndex {
44 ✔
1197
  const QString path = exactMatchPath();
44 ✔
1198
  if (path.isEmpty()) {
44 ✔
1199
    return {};
17 ✔
1200
  }
1201
  // indexFor() maps through the filter: a row the filter hides is no match.
1202
  const QModelIndex index = m_tree->indexFor(path);
27 ✔
1203
  if (!index.isValid() || !m_tree->fileInfo(index).isFile()) {
49 ✔
1204
    return {};
5 ✔
1205
  }
1206
  return index;
22 ✔
1207
}
1208

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

1255
void MainWindow::openExactMatch(const QModelIndex &index) {
6 ✔
1256
  // Made current here, not left to the filter pass before: the tree may have
1257
  // moved its current row since, and with none on_treeView_clicked() only
1258
  // names the entry without decrypting it.
1259
  ui->treeView->setCurrentIndex(index);
6 ✔
1260
  on_treeView_clicked(index);
6 ✔
1261
}
6 ✔
1262

1263
auto MainWindow::firstFile(QModelIndex parentIndex) -> QModelIndex {
24 ✔
1264
  StoreModel &proxy = m_tree->proxy();
24 ✔
1265
  int numRows = proxy.rowCount(parentIndex);
24 ✔
1266
  for (int row = 0; row < numRows; ++row) {
31 ✔
1267
    QModelIndex index = proxy.index(row, 0, parentIndex);
22 ✔
1268
    if (m_tree->fileInfo(index).isFile()) {
22 ✔
1269
      return index;
15 ✔
1270
    }
1271
    if (proxy.hasChildren(index)) {
13 ✔
1272
      QModelIndex childFile = firstFile(index);
8 ✔
1273
      if (childFile.isValid())
1274
        return childFile;
6 ✔
1275
    }
1276
  }
1277
  return QModelIndex();
9 ✔
1278
}
1279

1280
// Guards the input dialogs (create, move, rename) against names like
1281
// "../../etc/passwd" or absolute paths escaping the store root.
1282
auto MainWindow::confirmPathInStore(const QString &candidate) -> bool {
10 ✔
1283
  if (PathValidator::isPathInStore(QtPassSettings::getPassStore(), candidate)) {
20 ✔
1284
    return true;
1285
  }
1286
  QMessageBox::warning(this, tr("Invalid name"),
9 ✔
1287
                       tr("That name would resolve outside the password "
3 ✔
1288
                          "store. Please choose a different name."));
1289
  return false;
3 ✔
1290
}
1291

1292
void MainWindow::setPassword(const QString &file, bool isNew) {
6 ✔
1293
  const AppSettings s = QtPassSettings::load();
6 ✔
1294
  PasswordDialog d(QtPassSettings::getPass(), s, file, isNew, this);
6 ✔
1295
  // A copy out of the editor is autocleared like one from the display.
1296
  connect(&d, &PasswordDialog::copied, &m_qtPass->clipboard(),
6 ✔
1297
          &ClipboardManager::trackCopied);
6 ✔
1298

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

1327
  if (!d.exec()) {
6 ✔
1328
    ui->treeView->setFocus();
5 ✔
1329
  }
1330
}
6 ✔
1331

1332
void MainWindow::addPassword() { setPassword(QString()); }
2 ✔
1333

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

1387
auto MainWindow::confirmLinkRemoval(const QString &file) -> bool {
1 ✔
1388
  // Only the link goes (ImitatePass::Remove unlinks it); nothing behind it
1389
  // is looked at or mentioned.
1390
  return PlainMessageBox::askYes(
1 ✔
1391
      this, tr("Delete link?"),
1 ✔
1392
      tr("%1 is a symbolic link or junction. Remove the link? What it "
1 ✔
1393
         "points to is left alone.")
1394
          .arg(QDir::separator() + file));
2 ✔
1395
}
1396

1397
void MainWindow::onDelete() {
11 ✔
1398
  const QModelIndex currentIndex = ui->treeView->currentIndex();
11 ✔
1399
  // While content search results hide the tree, its current entry is not
1400
  // what the user looks at (the Delete key comes here directly).
1401
  if (!currentIndex.isValid() || ui->treeView->isHidden()) {
9 ✔
1402
    // Otherwise the whole password directory would be deleted (#556).
1403
    return;
8 ✔
1404
  }
1405

1406
  const bool isDir = !m_tree->fileInfo(currentIndex).isFile();
7 ✔
1407
  const QString file =
1408
      isDir ? m_tree->currentDir(true) : getFile(currentIndex, true);
7 ✔
1409
  const QString folder =
1410
      m_tree->fileSystem().rootPath() + QDir::separator() + file;
7 ✔
1411
  const bool linkedFolder = isDir && Util::isLinkedFolder(folder);
7 ✔
1412

1413
  if (!linkedFolder && refuseLinkedFolder(folder)) {
6 ✔
1414
    // Behind a link: deleting would reach outside the store.
1415
    return;
1416
  }
1417
  const bool confirmed =
1418
      linkedFolder ? confirmLinkRemoval(file) : confirmDeletion(file, isDir);
7 ✔
1419
  if (!confirmed) {
7 ✔
1420
    return;
1421
  }
1422
  QtPassSettings::getPass()->Remove(file, isDir);
6 ✔
1423
}
1424

1425
void MainWindow::cancelOtpRequest() {
89 ✔
1426
  m_otpRequestFile.clear();
89 ✔
1427
  m_copyRequestFile.clear();
89 ✔
1428
}
89 ✔
1429

1430
void MainWindow::onOperationError() {
35 ✔
1431
  cancelOtpRequest();
35 ✔
1432
  // executeWrapperStarted() emptied the panel and the browser when the
1433
  // operation started (a refusal says so too); what is left to forget is
1434
  // which entry the panel was about to show.
1435
  m_shownFile.clear();
35 ✔
1436
  // A save's refresh waiting for its push is dropped: it would clear the
1437
  // push's error (or whatever failed before it) from the browser.
1438
  m_refreshAfterPush.clear();
35 ✔
1439
  m_refreshAfterPushOwner = nullptr;
1440
}
35 ✔
1441

1442
// Derives the code in-process from one decrypt, so it works with either
1443
// backend on every platform; otpFromFileToClipboard() finishes the job.
1444
void MainWindow::onOtp() {
12 ✔
1445
  if (ui->treeView->isHidden()) {
12 ✔
1446
    return;
4 ✔
1447
  }
1448
  QString file = getFile(ui->treeView->currentIndex(), true);
11 ✔
1449
  if (file.isEmpty()) {
11 ✔
1450
    flashText(tr("No password selected for OTP generation"), true);
1 ✔
1451
    return;
1 ✔
1452
  }
1453
  if (!QtPassSettings::isUseOtp()) {
10 ✔
1454
    // Normally unreachable (the action is hidden), but never fail silently.
1455
    flashText(tr("No OTP code found in this password entry"), true);
1 ✔
1456
    return;
1 ✔
1457
  }
1458

1459
  // Fast path: the panel shows a live code, so no decrypt, and one clipboard
1460
  // write (two setMimeData calls in one turn can empty the Windows
1461
  // clipboard). Only for *this* entry: arrow keys and right-click move
1462
  // currentIndex without QTreeView::clicked, so the code may be another's.
1463
  const QString shown =
1464
      (m_shownFile == file) ? m_displayPanel->currentOtpCode() : QString();
9 ✔
1465
  if (!shown.isEmpty()) {
9 ✔
1466
    m_qtPass->clipboard().copyText(shown);
1 ✔
1467
    showStatusMessage(tr("OTP code copied to clipboard"));
2 ✔
1468
    return;
1469
  }
1470

1471
  // Fallback: decrypt once. The request file keeps passShowHandler from
1472
  // copying the password and tells otpFromFileToClipboard its answer.
1473
  m_otpRequestFile = file;
8 ✔
1474
  setUiElementsEnabled(false);
8 ✔
1475
  // Keep the marker in step so a second request takes the fast path; safe as
1476
  // executeWrapperStarted() clears the panel, so a failed decrypt shows none.
1477
  m_shownFile = file;
8 ✔
1478
  QtPassSettings::getPass()->Show(file);
16 ✔
1479
}
1480

1481
void MainWindow::onEdit() {
3 ✔
1482
  if (ui->treeView->isHidden()) {
3 ✔
1483
    return;
1 ✔
1484
  }
1485
  QString file = getFile(ui->treeView->currentIndex(), true);
2 ✔
1486
  editPassword(file);
2 ✔
1487
}
1488

1489
void MainWindow::onUsers() {
2 ✔
1490
  const QString dir = m_tree->currentDir(false);
2 ✔
1491
  if (refuseLinkedFolder(dir)) {
2 ✔
1492
    return;
1493
  }
1494

1495
  UsersDialog d(QtPassSettings::getPass(), QtPassSettings::load(), dir, this);
1 ✔
1496
  if (!d.exec()) {
1 ✔
1497
    ui->treeView->setFocus();
1 ✔
1498
  }
1499
}
1 ✔
1500

1501
void MainWindow::messageAvailable(const QString &message) {
9 ✔
1502
  show();
9 ✔
1503
  raise();
9 ✔
1504
  if (message.isEmpty()) {
9 ✔
1505
    focusInput();
1 ✔
1506
  } else {
1507
    ui->treeView->expandAll();
8 ✔
1508
    applySearchText(message);
8 ✔
1509
  }
1510
}
9 ✔
1511

1512
void MainWindow::updateProfileBox() {
182 ✔
1513
  const Profiles profiles = QtPassSettings::getProfiles();
182 ✔
1514
  bool activeGone = false;
1515

1516
  if (profiles.isEmpty()) {
7 ✔
1517
    ui->profileWidget->hide();
175 ✔
1518
  } else {
1519
    ui->profileWidget->show();
7 ✔
1520
    // A refill is no choice of the user's: clearing and adding items moves
1521
    // the current text, which would otherwise switch profiles.
1522
    const QSignalBlocker quiet(ui->profileBox);
7 ✔
1523
    ui->profileBox->clear();
7 ✔
1524
    for (auto i = profiles.cbegin(); i != profiles.cend(); ++i) {
19 ✔
1525
      if (!i.key().isEmpty()) {
12 ✔
1526
        ui->profileBox->addItem(i.key());
12 ✔
1527
      }
1528
    }
1529
    ui->profileBox->model()->sort(0);
7 ✔
1530
    int index = ui->profileBox->findText(QtPassSettings::getProfile());
14 ✔
1531
    if (index != -1) { //  -1 for not found
7 ✔
1532
      ui->profileBox->setCurrentIndex(index);
6 ✔
1533
    } else if (ui->profileBox->count() > 0) {
1 ✔
1534
      // The active profile is gone (removed in Settings): the box shows the
1535
      // first one, and the settings and backend must follow it, or the
1536
      // removed profile's store stays in use behind it.
1537
      ui->profileBox->setCurrentIndex(0);
1 ✔
1538
      activeGone = true;
1539
    }
1540
  }
7 ✔
1541
  if (activeGone) {
7 ✔
1542
    on_profileBox_currentTextChanged(ui->profileBox->currentText());
2 ✔
1543
  }
1544
  updateProfileBoxEnabled();
182 ✔
1545
}
182 ✔
1546

1547
void MainWindow::updateProfileBoxEnabled() {
619 ✔
1548
  // No profile switch while anything of the store runs or waits: the
1549
  // backend's store and environment would change under it, and what is
1550
  // still queued (a push after a save, say) would finish for the other
1551
  // profile (#2071). Asked of the backend, not only of the interface: the
1552
  // watchdog releases the interface while a slow gpg or git still runs.
1553
  // Every backend: one kept from before a switch of backend may still
1554
  // run what was queued on it.
1555
  ui->profileBox->setEnabled(m_uiEnabled && ui->profileBox->count() > 1 &&
1,239 ✔
1556
                             QtPassSettings::backendsIdle());
11 ✔
1557
}
619 ✔
1558

1559
void MainWindow::on_profileBox_currentTextChanged(const QString &name) {
6 ✔
1560
  if (m_freshStart || name == QtPassSettings::getProfile()) {
18 ✔
1561
    return;
1 ✔
1562
  }
1563
  // The box is disabled while anything runs; should a change come through
1564
  // anyway, the active profile stays and the box says so again.
1565
  if (!m_uiEnabled || !QtPassSettings::backendsIdle()) {
5 ✔
1566
    const QSignalBlocker quiet(ui->profileBox);
×
1567
    ui->profileBox->setCurrentText(QtPassSettings::getProfile());
×
1568
    return;
1569
  }
×
1570
  // A content search runs outside the queue: leaving grep mode cancels it,
1571
  // so its results for the old store are dropped, not shown for the new.
1572
  if (m_grep.inGrepMode()) {
5 ✔
1573
    ui->grepButton->setChecked(false);
1 ✔
1574
  }
1575

1576
  ui->lineEdit->clear();
5 ✔
1577

1578
  const Profile prof = QtPassSettings::getProfiles().value(name);
10 ✔
1579
  AppSettings s = QtPassSettings::load();
5 ✔
1580
  s.activeProfile = name;
5 ✔
1581
  s.passStore = prof.path;
5 ✔
1582
  s.passSigningKey = prof.signingKey;
5 ✔
1583
  // A profile without its own Git flags keeps the global values.
1584
  s.useGit = prof.useGit.value_or(s.useGit);
5 ✔
1585
  s.autoPush = prof.autoPush.value_or(s.autoPush);
5 ✔
1586
  s.autoPull = prof.autoPull.value_or(s.autoPull);
5 ✔
1587
  QtPassSettings::save(s);
5 ✔
1588
  ui->statusBar->showMessage(tr("Profile changed to %1").arg(name), 2000);
10 ✔
1589

1590
  QtPassSettings::getPass()->updateEnv();
5 ✔
1591

1592
  m_tree->setStore(QtPassSettings::getPassStore());
10 ✔
1593
  deselect();
5 ✔
1594
  ui->treeView->setCurrentIndex(QModelIndex());
5 ✔
1595
}
5 ✔
1596

1597
void MainWindow::initTrayIcon() {
3 ✔
1598
  m_tray = new TrayIcon(this);
3 ✔
1599
  if (!m_tray->getIsAllocated()) {
3 ✔
1600
    destroyTrayIcon();
3 ✔
1601
    return;
3 ✔
1602
  }
1603
#ifndef Q_OS_MACOS
1604
  m_tray->addToggle(ui->actionShowMenuBar);
×
1605
#endif
1606
}
1607

1608
void MainWindow::destroyTrayIcon() {
3 ✔
1609
  delete m_tray;
3 ✔
1610
  m_tray = nullptr;
3 ✔
1611
}
3 ✔
1612

1613
void MainWindow::closeEvent(QCloseEvent *event) {
4 ✔
1614
  // Save in both branches: a tray user only ever hides the window, and
1615
  // used to quit through the tray menu with nothing ever written.
1616
  saveWindowState();
4 ✔
1617
  // Only with a tray icon to come back from: without one (none asked for, or
1618
  // no system tray in this session) a hidden QtPass ran on invisibly, with the
1619
  // last entry in its window and the password on the clipboard.
1620
  if (QtPassSettings::isHideOnClose() && m_tray != nullptr) {
8 ✔
1621
    this->hide();
×
1622
    event->ignore();
1623
  } else {
1624
    m_qtPass->clipboard().clear();
4 ✔
1625
    event->accept();
1626
    // A visible QSystemTrayIcon keeps the application alive, so
1627
    // quitOnLastWindowClosed never fires; quit explicitly.
1628
    QApplication::quit();
4 ✔
1629
  }
1630
}
4 ✔
1631

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

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

1699
void MainWindow::keyPressEvent(QKeyEvent *event) {
23 ✔
1700
  switch (event->key()) {
23 ✔
1701
  case Qt::Key_Delete:
2 ✔
1702
    onDelete();
2 ✔
1703
    break;
2 ✔
1704
  case Qt::Key_Return:
2 ✔
1705
  case Qt::Key_Enter:
1706
    // While content search results hide the tree, its current entry is not
1707
    // what the user looks at: Return on a result opens that result.
1708
    if (ui->treeView->isHidden()) {
2 ✔
1709
      QTreeWidgetItem *result = ui->grepResultsList->currentItem();
1 ✔
1710
      if (result != nullptr && ui->grepResultsList->hasFocus()) {
1 ✔
1711
        on_grepResultsList_itemClicked(result, 0);
1 ✔
1712
      }
1713
      break;
1714
    }
1715
    if (m_tree->proxy().rowCount() > 0) {
1 ✔
1716
      on_treeView_clicked(ui->treeView->currentIndex());
1 ✔
1717
    }
1718
    break;
1719
  case Qt::Key_Escape:
3 ✔
1720
    ui->lineEdit->clear();
3 ✔
1721
    break;
3 ✔
1722
  default:
1723
    break;
1724
  }
1725
}
23 ✔
1726

1727
void MainWindow::addShareMenu(QMenu &contextMenu, const AppSettings &s) {
9 ✔
1728
  const QString dirPath = QDir::cleanPath(m_tree->currentDir(false));
9 ✔
1729
  auto *shareMenu = new QMenu(tr("Share"), &contextMenu);
9 ✔
1730
  contextMenu.addMenu(shareMenu);
9 ✔
1731

1732
  const QString gpgIdPath = Pass::getGpgIdPath(dirPath, s.passStore);
9 ✔
1733
  const bool gpgIdExists = !gpgIdPath.isEmpty() && QFile(gpgIdPath).exists();
9 ✔
1734
  const QString exePath = s.usePass ? s.passExecutable : s.gpgExecutable;
9 ✔
1735
  const bool gpgAvailable =
1736
      !exePath.isEmpty() &&
18 ✔
1737
      (Executor::parseWslCommand(exePath) || QFile(exePath).exists());
18 ✔
1738

1739
  QAction *reencrypt = shareMenu->addAction(tr("Re-encrypt all passwords"));
9 ✔
1740
  reencrypt->setEnabled(gpgIdExists && gpgAvailable);
9 ✔
1741
  connect(reencrypt, &QAction::triggered, this,
9 ✔
1742
          [this, dirPath]() { reencryptPath(dirPath); });
30 ✔
1743

1744
  QAction *exportKey = shareMenu->addAction(tr("Export my public key..."));
9 ✔
1745
  exportKey->setEnabled(gpgAvailable);
9 ✔
1746
  connect(exportKey, &QAction::triggered, this, &MainWindow::exportPublicKey);
9 ✔
1747

1748
  QAction *addRecipientAction = shareMenu->addAction(tr("Add recipient..."));
9 ✔
1749
  addRecipientAction->setEnabled(gpgIdExists && gpgAvailable);
9 ✔
1750
  connect(addRecipientAction, &QAction::triggered, this,
9 ✔
1751
          [this, dirPath]() { addRecipient(dirPath); });
29 ✔
1752

1753
  QAction *shareHelp = shareMenu->addAction(tr("What is this?"));
9 ✔
1754
  connect(shareHelp, &QAction::triggered, this, &MainWindow::showShareHelp);
9 ✔
1755
}
9 ✔
1756

1757
void MainWindow::showContextMenu(const QPoint &pos) {
11 ✔
1758
  const AppSettings s = QtPassSettings::load();
11 ✔
1759
  const QModelIndex index = ui->treeView->indexAt(pos);
11 ✔
1760
  const bool selected = index.isValid();
1761
  if (!selected) {
1762
    ui->treeView->clearSelection();
1 ✔
1763
    ui->actionDelete->setEnabled(false);
1 ✔
1764
    ui->actionEdit->setEnabled(false);
1 ✔
1765
  }
1766
  ui->treeView->setCurrentIndex(index);
11 ✔
1767
  const QPoint globalPos = ui->treeView->viewport()->mapToGlobal(pos);
11 ✔
1768
  const QFileInfo fileOrFolder = m_tree->fileInfo(ui->treeView->currentIndex());
11 ✔
1769
  const bool isDir = fileOrFolder.isDir();
11 ✔
1770

1771
  QMenu contextMenu;
11 ✔
1772
  if (!selected || isDir) {
11 ✔
1773
    const std::array<std::pair<QString, void (MainWindow::*)()>, 4> onFolder{{
1774
        {tr("Open folder with file manager"), &MainWindow::openFolder},
10 ✔
1775
        {tr("Add folder"), &MainWindow::addFolder},
10 ✔
1776
        {tr("Add password"), &MainWindow::addPassword},
10 ✔
1777
        {tr("Users"), &MainWindow::onUsers},
10 ✔
1778
    }};
×
1779
    for (const auto &[text, slot] : onFolder) {
50 ✔
1780
      connect(contextMenu.addAction(text), &QAction::triggered, this, slot);
40 ✔
1781
    }
1782
  } else if (fileOrFolder.isFile()) {
1 ✔
1783
    connect(contextMenu.addAction(tr("Edit")), &QAction::triggered, this,
1 ✔
1784
            &MainWindow::onEdit);
2 ✔
1785
  }
1786
  if (selected) {
11 ✔
1787
    contextMenu.addSeparator();
10 ✔
1788
    if (isDir) {
10 ✔
1789
      connect(contextMenu.addAction(tr("Rename folder")), &QAction::triggered,
9 ✔
1790
              this, &MainWindow::renameFolder);
18 ✔
1791
    } else if (fileOrFolder.isFile()) {
1 ✔
1792
      connect(contextMenu.addAction(tr("Rename password")), &QAction::triggered,
1 ✔
1793
              this, &MainWindow::renamePassword);
2 ✔
1794
    }
1795
    connect(contextMenu.addAction(tr("Delete")), &QAction::triggered, this,
10 ✔
1796
            &MainWindow::onDelete);
10 ✔
1797
    if (isDir) {
10 ✔
1798
      addShareMenu(contextMenu, s);
9 ✔
1799
    }
1800
  }
1801
  contextMenu.exec(globalPos);
11 ✔
1802
}
11 ✔
1803

1804
void MainWindow::showBrowserContextMenu(const QPoint &pos) {
1 ✔
1805
  QMenu *contextMenu = ui->textBrowser->createStandardContextMenu(pos);
1 ✔
1806
  // Reparent from textBrowser: a browser stylesheet cascades to the child
1807
  // QMenu and breaks its opaque native background.
1808
  contextMenu->setParent(this, contextMenu->windowFlags());
1 ✔
1809
  QPoint globalPos = ui->textBrowser->viewport()->mapToGlobal(pos);
1 ✔
1810

1811
  contextMenu->exec(globalPos);
1 ✔
1812
  delete contextMenu;
1 ✔
1813
}
1 ✔
1814

1815
void MainWindow::openFolder() {
1 ✔
1816
  QString dir = m_tree->currentDir(false);
1 ✔
1817

1818
  QString path = QDir::toNativeSeparators(dir);
1 ✔
1819
  QDesktopServices::openUrl(QUrl::fromLocalFile(path));
1 ✔
1820
}
1 ✔
1821

1822
void MainWindow::addFolder() {
7 ✔
1823
  const AppSettings s = QtPassSettings::load();
7 ✔
1824
  bool ok;
1825
  QString dir = m_tree->currentDir(false);
7 ✔
1826
  QString newdir =
1827
      QInputDialog::getText(this, tr("New folder"),
7 ✔
1828
                            tr("New folder: \n(Will be placed in %1 )")
7 ✔
1829
                                .arg(s.passStore + m_tree->currentDir(true)),
14 ✔
1830
                            QLineEdit::Normal, "", &ok);
14 ✔
1831
  if (!ok || newdir.isEmpty()) {
7 ✔
1832
    return;
1833
  }
1834
  // Checked and created as one and the same path: the check resolves ".."
1835
  // lexically, the system after following links, so "link/../x" would pass
1836
  // as the store's x and be made beside the link's target.
1837
  newdir = QDir::cleanPath(newdir.prepend(dir));
6 ✔
1838
  if (!confirmPathInStore(newdir)) {
6 ✔
1839
    return;
1840
  }
1841
  // Behind a link the folder would be made outside the store, as Users,
1842
  // Re-encrypt and Delete already refuse.
1843
  if (refuseLinkedFolder(newdir)) {
5 ✔
1844
    return;
1845
  }
1846
  // The tree, like `pass ls`, hides names that start with a dot.
1847
  const QStringList parts =
1848
      QDir(s.passStore).relativeFilePath(newdir).split(u'/');
4 ✔
1849
  if (std::any_of(parts.cbegin(), parts.cend(), [](const QString &part) {
8 ✔
1850
        return part != u'.' && part.startsWith(u'.');
4 ✔
1851
      })) {
1852
    PlainMessageBox::warning(this, tr("Hidden folder"),
2 ✔
1853
                             tr("A folder that starts with a dot would be "
1 ✔
1854
                                "hidden from the list: %1")
1855
                                 .arg(newdir));
2 ✔
1856
    return;
1 ✔
1857
  }
1858
  // Exists already: an error, as QDir::mkdir() made it before.
1859
  if (QFileInfo::exists(newdir) || !Util::mkpathForStore(newdir)) {
3 ✔
1860
    PlainMessageBox::warning(this, tr("Error"),
2 ✔
1861
                             tr("Failed to create folder: %1").arg(newdir));
2 ✔
1862
    return;
1 ✔
1863
  }
1864
  // No .gpg-id of its own: the folder uses its parent's recipients, as with
1865
  // pass, until Users gives it a list. A copy of the parent's list (#1688)
1866
  // kept every recipient later removed above it, and its entries stayed
1867
  // readable by them.
1868
}
7 ✔
1869

1870
void MainWindow::renameFolder() {
3 ✔
1871
  bool ok;
1872
  QString srcDir = QDir::cleanPath(m_tree->currentDir(false));
3 ✔
1873
  QString srcDirName = QDir(srcDir).dirName();
3 ✔
1874
  QString newName =
1875
      QInputDialog::getText(this, tr("Rename folder"), tr("Rename folder to: "),
3 ✔
1876
                            QLineEdit::Normal, srcDirName, &ok);
6 ✔
1877
  if (!ok || newName.isEmpty()) {
3 ✔
1878
    return;
1879
  }
1880
  QString destDir = srcDir;
1881
  destDir.replace(srcDir.lastIndexOf(srcDirName), srcDirName.length(), newName);
2 ✔
1882
  if (!confirmPathInStore(destDir)) {
2 ✔
1883
    return;
1884
  }
1885
  QtPassSettings::getPass()->Move(srcDir, destDir, false);
3 ✔
1886
}
1887

1888
void MainWindow::editPassword(const QString &file) {
5 ✔
1889
  if (!file.isEmpty()) {
5 ✔
1890
    const AppSettings s = QtPassSettings::load();
5 ✔
1891
    if (s.useGit && s.autoPull) {
5 ✔
1892
      onUpdate(true);
1 ✔
1893
    }
1894
    // The dialog decrypts the entry itself to fill its fields. That decrypt
1895
    // lands on the same finishedShow the panel uses, so drop the panel's claim
1896
    // to it: otherwise passShowHandler() repaints and, with "Always copy",
1897
    // puts the entry's old password on the clipboard - replacing whatever the
1898
    // user copied to paste into the dialog.
1899
    m_shownFile.clear();
5 ✔
1900
    setPassword(file, false);
5 ✔
1901
  }
5 ✔
1902
}
5 ✔
1903

1904
void MainWindow::renamePassword() {
2 ✔
1905
  bool ok;
1906
  QString file = getFile(ui->treeView->currentIndex(), false);
2 ✔
1907
  QString filePath = QFileInfo(file).path();
2 ✔
1908
  QString fileName = QFileInfo(file).fileName();
2 ✔
1909
  if (fileName.endsWith(".gpg", Qt::CaseInsensitive)) {
4 ✔
1910
    fileName.chop(4);
2 ✔
1911
  }
1912

1913
  QString newName =
1914
      QInputDialog::getText(this, tr("Rename file"), tr("Rename file to: "),
2 ✔
1915
                            QLineEdit::Normal, fileName, &ok);
4 ✔
1916
  if (!ok || newName.isEmpty()) {
2 ✔
1917
    return;
1918
  }
1919
  QString newFile = QDir(filePath).filePath(newName);
2 ✔
1920
  if (!confirmPathInStore(newFile)) {
2 ✔
1921
    return;
1922
  }
1923
  QtPassSettings::getPass()->Move(file, newFile, false);
3 ✔
1924
}
1925

1926
void MainWindow::copySelectionOrPassword() {
3 ✔
1927
  QWidget *focus = QApplication::focusWidget();
3 ✔
1928
  // The widget's own copy: a SecretTextBrowser marks what it copies as
1929
  // secret for clipboard managers, as the context menu's Copy does.
1930
  if (auto *text = qobject_cast<QTextEdit *>(focus);
3 ✔
1931
      text != nullptr && text->textCursor().hasSelection()) {
3 ✔
1932
    text->copy();
1 ✔
1933
    return;
1 ✔
1934
  }
1935
  // Through the clipboard manager, as a copy button would: the label may be
1936
  // the OTP code, which gets the secret hint and the autoclear.
1937
  if (auto *label = qobject_cast<QLabel *>(focus);
1938
      label != nullptr && label->hasSelectedText()) {
2 ✔
1939
    m_qtPass->clipboard().copyText(label->selectedText());
1 ✔
1940
    return;
1 ✔
1941
  }
1942
  copyPasswordFromTreeview();
1 ✔
1943
}
1944

1945
void MainWindow::copyPasswordFromTreeview() {
10 ✔
1946
  // While content search results hide the tree, its current entry is not
1947
  // what the user looks at: no decrypt, as for Edit and OTP.
1948
  if (ui->treeView->isHidden()) {
10 ✔
1949
    return;
1 ✔
1950
  }
1951
  QFileInfo fileOrFolder = m_tree->fileInfo(ui->treeView->currentIndex());
9 ✔
1952

1953
  if (fileOrFolder.isFile()) {
9 ✔
1954
    QString file = getFile(ui->treeView->currentIndex(), true);
9 ✔
1955
    // The newest Ctrl+C wins: finishedShow names its file, so the decrypt of
1956
    // an earlier request is simply not this one's.
1957
    m_copyRequestFile = file;
9 ✔
1958
    // This Show repaints the panel as well; see onOtp().
1959
    m_shownFile = file;
9 ✔
1960
    QtPassSettings::getPass()->Show(file);
18 ✔
1961
  }
1962
}
9 ✔
1963

1964
void MainWindow::passwordFromFileToClipboard(const QString &text,
28 ✔
1965
                                             const QString &file) {
1966
  if (m_copyRequestFile.isEmpty() || file != m_copyRequestFile) {
28 ✔
1967
    return;
23 ✔
1968
  }
1969
  m_copyRequestFile.clear();
8 ✔
1970
  // The first line, without a list of every line (an entry can expand into
1971
  // millions of them), and without the "\r" of a CRLF line end, as the
1972
  // password row and "Always copy" have it.
1973
  const QString first = FileContent::passwordLine(text);
8 ✔
1974
  // A `pass otp insert` entry's first line is the otpauth:// URI carrying the
1975
  // TOTP seed, and an OTP field holding a seed there is the same; copying it
1976
  // would leak 2FA material. Matches the display path
1977
  // (FileContent::getPasswordForDisplay / PasswordDisplayPanel).
1978
  if (FileContent::isOtpPasswordLine(first)) {
8 ✔
1979
    flashText(tr("This entry holds an OTP secret, not a password"), true);
6 ✔
1980
    return;
1981
  }
1982
  m_qtPass->clipboard().copyText(first);
5 ✔
1983
}
1984

1985
void MainWindow::showStatusMessage(const QString &msg, int timeout) {
28 ✔
1986
  ui->statusBar->showMessage(msg, timeout);
28 ✔
1987
}
28 ✔
1988

1989
void MainWindow::reencryptPath(const QString &dir) {
3 ✔
1990
  QDir checkDir(dir);
3 ✔
1991
  if (!checkDir.exists()) {
3 ✔
1992
    PlainMessageBox::critical(this, tr("Error"),
2 ✔
1993
                              tr("Directory does not exist: %1").arg(dir));
2 ✔
1994
    return;
1 ✔
1995
  }
1996
  if (refuseLinkedFolder(dir)) {
2 ✔
1997
    return;
1998
  }
1999

2000
  const bool yes = PlainMessageBox::askYes(
2 ✔
2001
      this, tr("Re-encrypt passwords"),
2 ✔
2002
      tr("Re-encrypt all passwords in %1?\n\n"
2 ✔
2003
         "This will re-encrypt ALL password files in this folder "
2004
         "using the current recipients defined in .gpg-id.\n\n"
2005
         "This may rewrite many files and cannot be undone easily.\n\n"
2006
         "Continue?")
2007
          .arg(QDir(dir).dirName()));
4 ✔
2008

2009
  if (!yes)
2 ✔
2010
    return;
2011

2012
  // Disable now; the asynchronous startReencryptPath signal re-runs this
2013
  // harmlessly.
2014
  startReencryptPath();
1 ✔
2015

2016
  // Under the current profile's settings: with the pass backend active, the
2017
  // native one is not re-initialised on a profile switch.
2018
  QtPassSettings::getImitatePass()->reencryptPath(
2 ✔
2019
      QDir::cleanPath(QDir(dir).absolutePath()), QtPassSettings::load());
2 ✔
2020
}
3 ✔
2021

2022
// Idempotent: reencryptPath() calls it before ImitatePass emits the signal.
2023
void MainWindow::startReencryptPath() {
6 ✔
2024
  m_reencryptRunning = true;
6 ✔
2025
  setUiElementsEnabled(false);
6 ✔
2026
  // The worker always ends with endReencryptPath(), and Cancel is available
2027
  // throughout, so the generic watchdog is not needed for this operation.
2028
  m_uiWatchdog.stop();
6 ✔
2029
  ui->treeView->setDisabled(true);
6 ✔
2030
  if (m_reencryptProgress)
6 ✔
2031
    return;
2032
  auto *progress = new QProgressDialog(tr("Re-encrypting passwords..."),
4 ✔
2033
                                       tr("Cancel"), 0, 0, this);
8 ✔
2034
  progress->setWindowTitle(tr("Re-encrypt passwords"));
4 ✔
2035
  progress->setWindowModality(Qt::WindowModal);
4 ✔
2036
  progress->setAutoClose(false);
4 ✔
2037
  progress->setAutoReset(false);
4 ✔
2038
  progress->setMinimumDuration(0);
4 ✔
2039
  connect(progress, &QProgressDialog::canceled, this, [this]() {
4 ✔
2040
    QtPassSettings::getImitatePass()->cancelReencryptPath();
1 ✔
2041
    showStatusMessage(tr("Cancelling re-encryption"), 5000);
1 ✔
2042
  });
1 ✔
2043
  m_reencryptProgress = progress;
2044
  progress->show();
4 ✔
2045
}
2046

2047
void MainWindow::reencryptProgress(int current, int total) {
5 ✔
2048
  if (!m_reencryptProgress)
5 ✔
2049
    return;
2050
  m_reencryptProgress->setMaximum(total);
4 ✔
2051
  m_reencryptProgress->setLabelText(
4 ✔
2052
      tr("Re-encrypting passwords: %1 of %2").arg(current).arg(total));
8 ✔
2053
  // On a modal dialog setValue() runs processEvents(), which can deliver
2054
  // endReencryptPath() and reset m_reencryptProgress: keep this last.
2055
  m_reencryptProgress->setValue(current);
4 ✔
2056
}
2057

2058
void MainWindow::endReencryptPath() {
4 ✔
2059
  m_reencryptRunning = false;
4 ✔
2060
  if (m_reencryptProgress) {
4 ✔
2061
    m_reencryptProgress->hide();
4 ✔
2062
    m_reencryptProgress->deleteLater();
4 ✔
2063
    m_reencryptProgress = nullptr;
2064
  }
2065
  setUiElementsEnabled(true);
4 ✔
2066
}
4 ✔
2067

2068
void MainWindow::exportPublicKey() {
3 ✔
2069
  const AppSettings s = QtPassSettings::load();
3 ✔
2070
  const QString identity = s.passSigningKey;
2071
  if (identity.isEmpty()) {
3 ✔
2072
    QMessageBox::information(
2 ✔
2073
        this, tr("Export public key"),
1 ✔
2074
        tr("<h3>Export your public key</h3>"
×
2075
           "<p>No signing key is configured. Set one in QtPass Settings "
2076
           "&gt; GPG keys, or run this in a terminal:</p>"
2077
           "<pre>gpg --armor --export --output my_key.asc &lt;your-key-id"
2078
           "&gt;</pre>"
2079
           "<p>Then send the file to your teammates.</p>"));
2080
    return;
1 ✔
2081
  }
2082
  QString gpgExe = s.gpgExecutable;
2083
  if (gpgExe.isEmpty()) {
2 ✔
2084
    gpgExe = QStringLiteral("gpg");
×
2085
  }
2086
  QStringList args = {"--armor", "--export"};
10 ✔
2087
  args.append(identity.split(' ', Qt::SkipEmptyParts));
2 ✔
2088
  QString stdOut;
2 ✔
2089
  QString stdErr;
2 ✔
2090
  int exitCode = Executor::executeBlocking(gpgExe, args, &stdOut, &stdErr);
2 ✔
2091
  if (exitCode != 0 || stdOut.isEmpty()) {
2 ✔
2092
    PlainMessageBox::warning(this, tr("Export public key"),
2 ✔
2093
                             tr("Could not export public key for %1.\n\n%2")
1 ✔
2094
                                 .arg(identity, stdErr.isEmpty()
2 ✔
2095
                                                    ? tr("No output from gpg.")
2 ✔
2096
                                                    : stdErr));
2097
    return;
2098
  }
2099
  ExportPublicKeyDialog dialog(identity, stdOut, this);
1 ✔
2100
  dialog.exec();
1 ✔
2101
}
4 ✔
2102

2103
// UsersDialog only ticks keys already in the keyring; importing a foreign
2104
// key still has to happen via gpg (or QtPass settings) first.
2105
void MainWindow::addRecipient(const QString &dir) {
2 ✔
2106
  if (refuseLinkedFolder(dir)) {
2 ✔
2107
    return;
1 ✔
2108
  }
2109
  UsersDialog d(QtPassSettings::getPass(), QtPassSettings::load(), dir, this);
1 ✔
2110
  d.exec();
1 ✔
2111
}
1 ✔
2112

2113
// A tree-picked folder that is, or lies behind, a symlink or junction is not
2114
// a folder of the store. The store root itself may be a link (a synced
2115
// folder); that is configuration, not a tree pick.
2116
auto MainWindow::refuseLinkedFolder(const QString &dir) -> bool {
17 ✔
2117
  if (!Util::isUnderLink(dir, QtPassSettings::load().passStore)) {
17 ✔
2118
    return false;
2119
  }
2120
  PlainMessageBox::critical(
3 ✔
2121
      this, tr("Not a folder of the store"),
3 ✔
2122
      tr("%1 is, or lies behind, a symbolic link or junction. What that "
3 ✔
2123
         "points to is not part of the password store and is left alone.")
2124
          .arg(QDir::toNativeSeparators(QDir::cleanPath(dir))));
6 ✔
2125
  return true;
3 ✔
2126
}
2127

2128
void MainWindow::showShareHelp() {
1 ✔
2129
  QMessageBox::information(
2 ✔
2130
      this, tr("Sharing passwords with GPG"),
1 ✔
2131
      tr("<h3>Sharing passwords with GPG</h3>"
1 ✔
2132
         "<p>To share passwords with other users:</p>"
2133
         "<ol>"
2134
         "<li><b>Export your public key</b> and send it to teammates</li>"
2135
         "<li><b>Import teammates' public keys</b> into your GPG keyring</li>"
2136
         "<li><b>Re-encrypt passwords</b> so all recipients can decrypt "
2137
         "them</li>"
2138
         "</ol>"
2139
         "<p>Only people who have a matching secret key can decrypt the "
2140
         "passwords.</p>"
2141
         "<p><b>Tip:</b> Use the same GPG key for all shared folders.</p>"
2142
         "<p>See the FAQ for more details.</p>"));
2143
}
1 ✔
2144

2145
void MainWindow::updateGitButtonVisibility(bool uiEnabled) {
402 ✔
2146
  const AppSettings s = QtPassSettings::load();
402 ✔
2147
  // Without Git there is nothing to push or pull, ever: the buttons go, not
2148
  // grey out. While an operation runs they stay and are disabled.
2149
  const bool usable =
2150
      s.useGit && !(s.gitExecutable.isEmpty() && s.passExecutable.isEmpty());
402 ✔
2151
  ui->actionPush->setVisible(usable);
402 ✔
2152
  ui->actionUpdate->setVisible(usable);
402 ✔
2153
  // The separator in front of them would otherwise sit next to the next one.
2154
  const QList<QAction *> actions = ui->toolBar->actions();
402 ✔
2155
  const qsizetype at = actions.indexOf(ui->actionPush);
402 ✔
2156
  if (at > 0 && actions.at(at - 1)->isSeparator()) {
402 ✔
2157
    actions.at(at - 1)->setVisible(usable);
402 ✔
2158
  }
2159
  enableGitButtons(usable && uiEnabled);
402 ✔
2160
}
402 ✔
2161

2162
void MainWindow::updateOtpButtonVisibility(bool uiEnabled) {
408 ✔
2163
  // No platform gating: codes are generated in-process. Visible but disabled
2164
  // when OTP is off: the panel never shows an OTP field (a secret), so hiding
2165
  // this too would leave no trace of the feature. Honour uiEnabled, or the
2166
  // user can stack Show calls while a decrypt is in flight.
2167
  ui->actionOtp->setVisible(true);
408 ✔
2168
  ui->actionOtp->setEnabled(QtPassSettings::isUseOtp() && uiEnabled);
421 ✔
2169
}
408 ✔
2170

2171
void MainWindow::updateGrepButtonVisibility() {
178 ✔
2172
  const bool enabled = QtPassSettings::isUseGrepSearch();
178 ✔
2173
  ui->grepButton->setVisible(enabled);
178 ✔
2174
  ui->grepCaseButton->setVisible(enabled);
178 ✔
2175
  if (!enabled && m_grep.inGrepMode()) {
178 ✔
2176
    ui->grepButton->setChecked(false);
1 ✔
2177
  }
2178
}
178 ✔
2179

2180
void MainWindow::enableGitButtons(const bool &state) {
402 ✔
2181
  ui->actionPush->setEnabled(state);
402 ✔
2182
  ui->actionUpdate->setEnabled(state);
402 ✔
2183
}
402 ✔
2184

2185
void MainWindow::critical(const QString &title, const QString &msg) {
3 ✔
2186
  // Pass's messages quote store paths; see PlainMessageBox.
2187
  PlainMessageBox::critical(this, title, msg);
3 ✔
2188
}
3 ✔
2189

2190
void MainWindow::onProcessOutput(const QString &output, bool isError,
7 ✔
2191
                                 Enums::PROCESS pid) {
2192
  if (!QtPassSettings::isShowProcessOutput()) {
7 ✔
2193
    return;
2194
  }
2195
  m_processOutput->append(output, isError,
6 ✔
2196
                          ProcessOutputPanel::processName(pid));
12 ✔
2197
}
2198

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

© 2026 Coveralls, Inc