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

IJHack / QtPass / 45053779388

22 Nov 2026 06:12PM UTC coverage: 94.693% (-0.02%) from 94.71%
45053779388

push

github

web-flow
Display panel: double-click edits the entry it shows (#2305)

The panel's editRequested handler called onEdit(), which edits the
tree's current index. Arrow keys and a right-click move that index
without repainting the panel, so a double-click on the shown password
could open and overwrite a different entry, encrypted to that folder's
recipients.

MainWindow now records the entry whose fields the panel renders
(m_panelEntry, cleared with the panel) and edits that one.

Scan ANT-2026-GVHYU5T1.

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

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

2 existing lines in 1 file now uncovered.

9617 of 10156 relevant lines covered (94.69%)

18576.44 hits per line

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

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

11
#include "qtpasslogging.h"
12

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

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

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

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

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

97
  initTextBrowser();
187 ✔
98

99
  updateProfileBox();
187 ✔
100

101
  initDisplayPanel();
187 ✔
102

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

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

113
  initTimers();
187 ✔
114

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

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

122
  setUiElementsEnabled(true);
187 ✔
123

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

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

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

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

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

211
void MainWindow::initDisplayPanel() {
187 ✔
212
  m_displayPanel = new PasswordDisplayPanel(
187 ✔
213
      ui->gridLayout, ui->verticalLayoutPassword, this, this);
187 ✔
214
  connect(m_displayPanel, &PasswordDisplayPanel::copyRequested,
187 ✔
215
          &m_qtPass->clipboard(), &ClipboardManager::copyText);
187 ✔
216
  connect(m_displayPanel, &PasswordDisplayPanel::textCopied,
187 ✔
217
          &m_qtPass->clipboard(), &ClipboardManager::trackCopied);
187 ✔
218
  connect(ui->textBrowser, &SecretTextBrowser::copied, &m_qtPass->clipboard(),
187 ✔
219
          &ClipboardManager::trackCopied);
187 ✔
220
  connect(m_displayPanel, &PasswordDisplayPanel::qrRequested, m_qtPass,
187 ✔
221
          &QtPass::showTextAsQRCode);
187 ✔
222
  // Double-click on what is shown edits it, as in the tree.
223
  // The entry whose rows were double-clicked, not the tree's current row:
224
  // arrow keys and a right-click move that row without repainting the panel.
225
  connect(m_displayPanel, &PasswordDisplayPanel::editRequested, this, [this] {
187 ✔
226
    if (ui->actionEdit->isEnabled() && !m_panelEntry.isEmpty()) {
4 ✔
227
      editPassword(m_panelEntry);
3 ✔
228
    }
229
  });
4 ✔
230
}
187 ✔
231

232
void MainWindow::initTimers() {
187 ✔
233
  clearPanelTimer.setSingleShot(true);
187 ✔
234
  connect(&clearPanelTimer, &QTimer::timeout, this, [this]() { clearPanel(); });
189 ✔
235

236
  searchTimer.setInterval(350);
187 ✔
237
  searchTimer.setSingleShot(true);
187 ✔
238

239
  connect(&searchTimer, &QTimer::timeout, this, &MainWindow::onTimeoutSearch);
187 ✔
240

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

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

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

294
MainWindow::~MainWindow() {
370 ✔
295
  // Quit from the tray menu or a SIGTERM never delivers closeEvent(); the
296
  // window still knows its last geometry here.
297
  saveWindowState();
187 ✔
298
  delete m_qtPass;
187 ✔
299
}
557 ✔
300

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

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

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

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

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

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

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

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

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

463
void MainWindow::initStatusBar() {
187 ✔
464
  ui->statusBar->showMessage(tr("Welcome to QtPass %1").arg(VERSION), 2000);
374 ✔
465

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

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

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

492
  // Wrapped at word boundaries, a run of hundreds of thousands of letters
493
  // took Qt seconds to minutes; anywhere, it is linear. Anywhere while the
494
  // text goes in, then word wrap back unless what is shown has such a run:
495
  // markup (a link's "<a href") splits a run in the source, not on screen.
496
  ui->textBrowser->setWordWrapMode(QTextOption::WrapAnywhere);
91 ✔
497
  if (isHtml) {
91 ✔
498
    QString _text = text;
499
    if (!ui->textBrowser->toPlainText().isEmpty()) {
148 ✔
500
      _text = ui->textBrowser->toHtml() + _text;
38 ✔
501
    }
502
    ui->textBrowser->setHtml(_text);
74 ✔
503
  } else {
504
    ui->textBrowser->setText(text);
17 ✔
505
  }
506
  // The raw text: toPlainText() turns a no-break space into a plain one.
507
  if (!Util::hasLongUnbrokenRun(ui->textBrowser->document()->toRawText())) {
182 ✔
508
    ui->textBrowser->setWordWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
87 ✔
509
  }
510
}
91 ✔
511

512
void MainWindow::applyTextBrowserSettings() {
5 ✔
513
  const AppSettings s = QtPassSettings::load();
5 ✔
514
  if (s.useMonospace) {
5 ✔
515
    QFont monospace("Monospace");
1 ✔
516
    monospace.setStyleHint(QFont::Monospace);
1 ✔
517
    ui->textBrowser->setFont(monospace);
1 ✔
518
  } else {
1 ✔
519
    ui->textBrowser->setFont(QFont());
4 ✔
520
  }
521

522
  if (s.noLineWrapping) {
5 ✔
523
    ui->textBrowser->setLineWrapMode(QTextBrowser::NoWrap);
1 ✔
524
  } else {
525
    ui->textBrowser->setLineWrapMode(QTextBrowser::WidgetWidth);
4 ✔
526
  }
527
}
5 ✔
528

529
void MainWindow::applyWindowFlagsSettings() {
203 ✔
530
  const bool wantOnTop = QtPassSettings::isAlwaysOnTop();
203 ✔
531
  const Qt::WindowFlags flags = windowFlags();
532
  if (flags.testFlag(Qt::WindowStaysOnTopHint) == wantOnTop) {
203 ✔
533
    // setWindowFlags() rebuilds the native window, the teardown that left
534
    // ui->lineEdit dangling (see focusInput()); skip it when nothing changes.
535
    return;
536
  }
537
  // Toggle just this hint; resetting to Qt::Window discarded every other flag.
538
  const bool wasVisible = isVisible();
539
  setWindowFlags(wantOnTop ? (flags | Qt::WindowStaysOnTopHint)
4 ✔
540
                           : (flags & ~Qt::WindowStaysOnTopHint));
541
  // setWindowFlags() hides a shown window; a window that was not shown yet
542
  // (first-run wizard from the constructor) is left to its normal show.
543
  if (wasVisible) {
2 ✔
544
    show();
2 ✔
545
  }
546
}
547

548
auto MainWindow::config() -> bool {
8 ✔
549
  if (m_freshStart) {
8 ✔
550
    // No usable configuration yet: the wizard finds the programs, the key
551
    // and the store, and creates the store when it has to.
552
    FirstRunWizard wizard(this);
2 ✔
553
    if (wizard.exec() != QDialog::Accepted) {
2 ✔
554
      return false;
555
    }
556
  } else {
2 ✔
557
    ConfigDialog d(this);
6 ✔
558
    d.setModal(true);
6 ✔
559
    if (d.exec() != QDialog::Accepted) {
6 ✔
560
      return false;
561
    }
562
  }
6 ✔
563

564
  applyTextBrowserSettings();
5 ✔
565
  applyWindowFlagsSettings();
5 ✔
566

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

585
  Pass *activePass = QtPassSettings::getPass();
5 ✔
586
  activePass->updateEnv();
5 ✔
587
  m_tree->setPass(activePass);
5 ✔
588
  clearPanelTimer.setInterval(MS_PER_SECOND * s.autoclearPanelSeconds);
5 ✔
589
  m_qtPass->clipboard().setAutoclearTimer();
5 ✔
590

591
  updateGitButtonVisibility();
5 ✔
592
  updateOtpButtonVisibility();
5 ✔
593
  updateGrepButtonVisibility();
5 ✔
594
  updateProcessOutputVisibility();
5 ✔
595
#ifndef Q_OS_MACOS
596
  // The action's toggled handler shows or hides the bar (and saves again).
597
  ui->actionShowMenuBar->setChecked(s.showMenuBar);
5 ✔
598
#endif
599
  if (s.useTrayIcon && m_tray == nullptr) {
5 ✔
600
    initTrayIcon();
1 ✔
601
  } else if (!s.useTrayIcon && m_tray != nullptr) {
4 ✔
602
    destroyTrayIcon();
×
603
  }
604

605
  // Stay fresh-start while the configuration is unusable, so the
606
  // constructor's loop re-runs the wizard. The re-prompt lives there:
607
  // recursing here never reported a cancel back to the caller.
608
  if (Util::configIsValid(s)) {
5 ✔
609
    m_freshStart = false;
5 ✔
610
  }
611
  return true;
612
}
5 ✔
613

614
void MainWindow::onUpdate(bool block) {
2 ✔
615
  ui->statusBar->showMessage(tr("Updating password-store"), 2000);
2 ✔
616
  if (block) {
2 ✔
617
    QtPassSettings::getPass()->GitPull_b(Pass::kBlockingPullMs);
1 ✔
618
  } else {
619
    QtPassSettings::getPass()->GitPull();
1 ✔
620
  }
621
}
2 ✔
622

623
void MainWindow::onPush() {
1 ✔
624
  if (QtPassSettings::isUseGit()) {
1 ✔
625
    ui->statusBar->showMessage(tr("Updating password-store"), 2000);
1 ✔
626
    QtPassSettings::getPass()->GitPush();
1 ✔
627
  }
628
}
1 ✔
629

630
void MainWindow::onAutoPush() {
8 ✔
631
  if (QtPassSettings::isUseGit()) {
8 ✔
632
    ui->statusBar->showMessage(tr("Updating password-store"), 2000);
8 ✔
633
    QtPassSettings::getPass()->GitPushAutomatic();
8 ✔
634
  }
635
}
8 ✔
636

637
auto MainWindow::getFile(const QModelIndex &index, bool forPass) -> QString {
62 ✔
638
  return m_tree->fileFor(index, forPass);
62 ✔
639
}
640

641
void MainWindow::on_treeView_clicked(const QModelIndex &index) {
26 ✔
642
  bool cleared = ui->treeView->currentIndex().flags() == Qt::NoItemFlags;
26 ✔
643
  QString file = getFile(index, true);
26 ✔
644
  ui->passwordName->setText(Util::shownName(file));
52 ✔
645
  if (!file.isEmpty() && !cleared) {
26 ✔
646
    // Remember what the panel is about to show, so onOtp() can tell whether the
647
    // code it can see belongs to the entry that is currently selected.
648
    m_shownFile = file;
25 ✔
649
    QtPassSettings::getPass()->Show(file);
50 ✔
650
  } else {
651
    m_shownFile.clear();
1 ✔
652
    clearPanel(false);
1 ✔
653
    ui->actionEdit->setEnabled(false);
1 ✔
654
    ui->actionDelete->setEnabled(true);
1 ✔
655
  }
656
}
26 ✔
657

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

661
  if (fileOrFolder.isFile()) {
4 ✔
662
    editPassword(getFile(index, true));
6 ✔
663
  }
664
}
4 ✔
665

666
void MainWindow::deselect() {
19 ✔
667
  m_shownFile.clear();
19 ✔
668
  cancelOtpRequest();
19 ✔
669
  m_qtPass->clipboard().clear();
19 ✔
670
  ui->treeView->clearSelection();
19 ✔
671
  // The current index too: clearSelection() keeps it, and whatever asks for
672
  // the "current" folder (Users, Add password, Add folder) took the hidden
673
  // entry it was left on, such as the first hit of a search just emptied.
674
  ui->treeView->setCurrentIndex(QModelIndex());
19 ✔
675
  ui->actionEdit->setEnabled(false);
19 ✔
676
  ui->actionDelete->setEnabled(false);
19 ✔
677
  ui->passwordName->setText("");
19 ✔
678
  clearPanel(false);
19 ✔
679
}
19 ✔
680

681
void MainWindow::executeWrapperStarted() {
67 ✔
682
  m_displayPanel->clear();
67 ✔
683
  m_panelEntry.clear();
67 ✔
684
  ui->textBrowser->clear();
67 ✔
685
  setUiElementsEnabled(false);
67 ✔
686
  clearPanelTimer.stop();
67 ✔
687
  if (QtPassSettings::isShowProcessOutput()) {
67 ✔
688
    m_processOutput->setVisible(true);
62 ✔
689
  }
690
}
67 ✔
691

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

728
  // Skipped for an OTP request: the user asked for a code, and two
729
  // OleSetClipboard calls in one turn can leave the Windows clipboard empty.
730
  if (m_otpRequestFile.isEmpty() || m_otpRequestFile != file) {
30 ✔
731
    m_qtPass->clipboard().copyIfAlways(password, p_output);
28 ✔
732
  }
733

734
  m_displayPanel->clear();
30 ✔
735
  m_panelEntry.clear();
30 ✔
736

737
  if (s.hideContent) {
30 ✔
738
    output = "***" + tr("Content hidden") + "***";
4 ✔
739
  } else if (s.displayAsIs) {
28 ✔
740
    // As it is, but not a block per line of millions.
741
    output = FileContent::boundedForDisplay(p_output);
4 ✔
742
  } else {
743
    m_panelEntry = file;
26 ✔
744
    m_displayPanel->displayFields(password, fileContent.getNamedValues(), s,
52 ✔
745
                                  s.useOtp ? fileContent.getOtpUri()
26 ✔
746
                                           : QString());
747
    output = fileContent.getRemainingDataForDisplay();
52 ✔
748
  }
749

750
  if (s.useAutoclearPanel) {
30 ✔
751
    clearPanelTimer.start();
2 ✔
752
  }
753

754
  // Shown as it is, the text holds the password and every secret field: no
755
  // links in it, or a click on a URL-shaped one handed it to the browser.
756
  flashText(QtPass::formatOutput(output, QString(), QString(),
60 ✔
757
                                 !s.displayAsIs || s.hideContent),
30 ✔
758
            false, true);
759
  setUiElementsEnabled(true);
30 ✔
760
}
60 ✔
761

762
void MainWindow::otpFromFileToClipboard(const QString &p_output,
31 ✔
763
                                        const QString &file) {
764
  // Permanently connected: only the decrypt of the entry onOtp() asked for
765
  // is ours, everything else belongs to a tree click or a Ctrl+C.
766
  if (m_otpRequestFile.isEmpty() || file != m_otpRequestFile) {
31 ✔
767
    return;
27 ✔
768
  }
769
  m_otpRequestFile.clear();
6 ✔
770

771
  if (p_output.isEmpty()) {
6 ✔
772
    // Distinguish "could not read the entry" from "entry has no OTP".
773
    flashText(tr("Could not decrypt this password entry"), true);
1 ✔
774
    setUiElementsEnabled(true);
1 ✔
775
    return;
1 ✔
776
  }
777

778
  // passShowHandler ran first for this finishedShow; if it rendered the OTP
779
  // row, reuse its code (as onOtp()'s fast path does). Otherwise parse:
780
  // hideContent, displayAsIs or no OTP field.
781
  const QString shown = m_displayPanel->currentOtpCode();
5 ✔
782
  if (!shown.isEmpty()) {
5 ✔
783
    m_qtPass->clipboard().copyText(shown);
1 ✔
784
    showStatusMessage(tr("OTP code copied to clipboard"));
1 ✔
785
    setUiElementsEnabled(true);
1 ✔
786
    return;
787
  }
788

789
  const AppSettings s = QtPassSettings::load();
4 ✔
790
  // Parse with the same template settings passShowHandler uses, so an OTP
791
  // field is recognised identically in both paths.
792
  const QStringList templ =
793
      s.useTemplate ? TemplateIO::fieldsIn(s.passTemplate) : QStringList();
4 ✔
794
  const bool allFields = s.useTemplate && s.templateAllFields;
4 ✔
795
  const FileContent fileContent =
796
      FileContent::parse(p_output, templ, allFields);
4 ✔
797

798
  Totp::Refusal why = Totp::Refusal::None;
4 ✔
799
  const std::optional<Totp::Settings> settings =
800
      Totp::parse(fileContent.getOtpUri(), &why);
8 ✔
801
  if (settings.has_value()) {
4 ✔
802
    m_qtPass->clipboard().copyText(Totp::generateNow(*settings));
4 ✔
803
    showStatusMessage(tr("OTP code copied to clipboard"));
4 ✔
804
  } else {
805
    // Why, when there is a configuration that gives no code.
806
    const QString reason = Totp::describe(why);
2 ✔
807
    flashText(reason.isEmpty() ? tr("No OTP code found in this password entry")
6 ✔
808
                               : reason,
809
              true);
810
  }
811
  setUiElementsEnabled(true);
4 ✔
812
}
8 ✔
813

814
void MainWindow::clearPanel(bool notify) {
67 ✔
815
  m_displayPanel->clear();
67 ✔
816
  m_panelEntry.clear();
67 ✔
817
  // A QR code of the password is the password on screen as much as the
818
  // panel is; it is a popup of its own, not part of the panel.
819
  m_qtPass->closeQRCode();
67 ✔
820
  const bool grepWasVisible = ui->grepResultsList->isVisible();
67 ✔
821
  ui->grepResultsList->clear();
67 ✔
822
  if (grepWasVisible) {
67 ✔
823
    showContentResults(false);
5 ✔
824
    if (m_grep.inGrepMode()) {
5 ✔
825
      // Left as the button leaves it: a search still running would otherwise
826
      // hand its partial matches to a content search entered meanwhile.
827
      cancelContentSearch();
5 ✔
828
      if (m_grep.leaveGrepMode()) {
829
        QApplication::restoreOverrideCursor();
2 ✔
830
      }
831
      ui->grepButton->blockSignals(true);
5 ✔
832
      ui->grepButton->setChecked(false);
5 ✔
833
      ui->grepButton->blockSignals(false);
5 ✔
834
      ui->lineEdit->blockSignals(true);
5 ✔
835
      ui->lineEdit->clear();
5 ✔
836
      ui->lineEdit->blockSignals(false);
5 ✔
837
      ui->lineEdit->setPlaceholderText(tr("Search password"));
10 ✔
838
    }
839
  }
840
  if (notify) {
67 ✔
841
    QString output = "***" + tr("Password and content hidden") + "***";
4 ✔
842
    ui->textBrowser->setHtml(output);
2 ✔
843
  } else {
844
    ui->textBrowser->setHtml("");
130 ✔
845
  }
846
}
67 ✔
847

848
void MainWindow::setUiElementsEnabled(bool state) {
424 ✔
849
  // A running re-encryption owns the UI state: the progress dialog's Cancel is
850
  // the user's escape hatch and endReencryptPath() releases the interface, so
851
  // neither an unrelated completion nor the watchdog may re-enable it early.
852
  if (state && m_reencryptRunning) {
424 ✔
853
    m_uiWatchdog.stop();
1 ✔
854
    return;
1 ✔
855
  }
856
  // Arm the watchdog while the UI is disabled; disarm once re-enabled.
857
  if (state) {
858
    m_uiWatchdog.stop();
332 ✔
859
  } else {
860
    m_uiWatchdog.start();
91 ✔
861
  }
862
  ui->treeView->setEnabled(state);
423 ✔
863
  ui->lineEdit->setEnabled(state);
423 ✔
864
  ui->actionAddPassword->setEnabled(state);
423 ✔
865
  ui->actionAddFolder->setEnabled(state);
423 ✔
866
  ui->actionUsers->setEnabled(state);
423 ✔
867
  ui->actionConfig->setEnabled(state);
423 ✔
868
  m_uiEnabled = state;
423 ✔
869
  updateProfileBoxEnabled();
423 ✔
870
  const bool uiEnabled = state;
871
  // is a file selected, and in sight (content search results hide the tree)?
872
  state &= ui->treeView->currentIndex().isValid() && !ui->treeView->isHidden();
849 ✔
873
  ui->actionDelete->setEnabled(state);
423 ✔
874
  ui->actionEdit->setEnabled(state);
423 ✔
875
  updateGitButtonVisibility(uiEnabled);
423 ✔
876
  // `state` is now "UI enabled AND a file is selected", which is exactly when
877
  // generating an OTP makes sense.
878
  updateOtpButtonVisibility(state);
423 ✔
879
}
880

881
void MainWindow::restoreWindow() {
198 ✔
882
  // saveGeometry() covers position, size, maximized state and screen;
883
  // anything applied on top discards it. Centre only when nothing was saved.
884
  const QByteArray geometry = QtPassSettings::getGeometry();
396 ✔
885
  if (geometry.isEmpty() || !restoreGeometry(geometry)) {
198 ✔
886
    WindowStateStore::centreOnCursorScreen(*this);
4 ✔
887
  }
888
  restoreState(QtPassSettings::getSavestate(saveState()));
198 ✔
889
  const AppSettings s = QtPassSettings::load();
198 ✔
890

891
  applyWindowFlagsSettings();
198 ✔
892

893
  if (s.useTrayIcon && m_tray == nullptr) {
198 ✔
894
    initTrayIcon();
2 ✔
895
    // Minimized to the tray only when there is one: without a system tray
896
    // initTrayIcon() gave up, and a hidden window could not be brought back.
897
    if (s.startMinimized && m_tray != nullptr) {
2 ✔
898
      // since we are still in constructor, can't directly hide
899
      QTimer::singleShot(10, this, &MainWindow::hide);
×
900
    }
901
  } else if (!s.useTrayIcon && m_tray != nullptr) {
196 ✔
902
    destroyTrayIcon();
×
903
  }
904
}
396 ✔
905

906
void MainWindow::onConfig() {
3 ✔
907
  // No Settings while anything of the store runs or waits, as with the
908
  // profile box (#2071): the store, backend and programs chosen there apply
909
  // to what is still queued, so a pending `pass init` re-encrypted the store
910
  // just picked for the recipients chosen for the other. Asked of the
911
  // backends: the watchdog releases the interface while a slow gpg or git
912
  // still runs.
913
  if (!QtPassSettings::backendsIdle()) {
3 ✔
914
    critical(tr("Settings not opened"),
2 ✔
915
             tr("A gpg, Git or pass command is still running or waiting. "
1 ✔
916
                "Open the settings again once it has finished. If it does "
917
                "not finish, answer or cancel the PIN or password prompt it "
918
                "waits for, or restart QtPass. A restart forgets which "
919
                "folders still need re-encrypting: re-encrypt any folder "
920
                "whose re-encryption did not finish, or that you moved "
921
                "entries into, before anything is pushed."));
922
    return;
1 ✔
923
  }
924
  config();
2 ✔
925
}
926

927
void MainWindow::showAbout() {
1 ✔
928
  QMessageBox::about(
1 ✔
929
      this, tr("About QtPass"),
1 ✔
930
      tr("<h3>QtPass %1</h3>"
1 ✔
931
         "<p>A multi-platform GUI for <a "
932
         "href=\"https://www.passwordstore.org/\">"
933
         "pass</a>, the standard Unix password manager.</p>"
934
         "<p><a href=\"https://qtpass.org/\">qtpass.org</a> &middot; "
935
         "<a href=\"https://github.com/IJHack/QtPass\">Source and "
936
         "issues</a></p>"
937
         "<p>Copyright &copy; 2014&ndash;%2 IJhack. Licensed under the "
938
         "<a href=\"https://www.gnu.org/licenses/gpl-3.0.html\">GNU GPL "
939
         "version 3</a> or later.</p>")
940
          .arg(QStringLiteral(VERSION),
2 ✔
941
               QString::number(QDate::currentDate().year())));
2 ✔
942
}
1 ✔
943

944
void MainWindow::on_lineEdit_textChanged(const QString &arg1) {
50 ✔
945
  if (m_grep.inGrepMode())
50 ✔
946
    return;
947
  ui->statusBar->showMessage(tr("Looking for: %1").arg(arg1), 1000);
74 ✔
948
  ui->treeView->expandAll();
37 ✔
949
  // Drop any decrypt still pending for the entry that was shown: otherwise it
950
  // keeps its right to the panel and, with "Always copy", the clipboard, and
951
  // when it lands late it shows that entry's password under the new heading.
952
  m_shownFile.clear();
37 ✔
953
  cancelOtpRequest();
37 ✔
954
  clearPanel(false);
37 ✔
955
  ui->passwordName->setText("");
74 ✔
956
  ui->actionEdit->setEnabled(false);
37 ✔
957
  ui->actionDelete->setEnabled(false);
37 ✔
958
  searchTimer.start();
37 ✔
959
}
960

961
void MainWindow::onTimeoutSearch() {
41 ✔
962
  // The tree matches slash-separated paths: on Windows, team\bank typed is
963
  // team/bank, as exactMatchPath() reads it too.
964
  QString query = QDir::fromNativeSeparators(ui->lineEdit->text());
82 ✔
965

966
  if (query.isEmpty()) {
41 ✔
967
    ui->treeView->collapseAll();
2 ✔
968
    deselect();
2 ✔
969
  }
970

971
  // The words are matched literally, in order, with anything in between:
972
  // "work vpn" finds work/acme/vpn.
973
  m_tree->setFilter(StoreModel::wordsFilter(query));
41 ✔
974

975
  if (m_tree->proxy().rowCount() > 0 && !query.isEmpty()) {
41 ✔
976
    selectFirstFile();
29 ✔
977
  } else {
978
    ui->actionEdit->setEnabled(false);
12 ✔
979
    ui->actionDelete->setEnabled(false);
12 ✔
980
  }
981
}
41 ✔
982

983
void MainWindow::on_lineEdit_returnPressed() {
17 ✔
984
  qCDebug(lcQtPass) << "on_lineEdit_returnPressed"
17 ✔
985
                    << m_tree->proxy().rowCount();
×
986

987
  if (m_grep.inGrepMode()) {
17 ✔
988
    const QString query = ui->lineEdit->text();
12 ✔
989
    if (!query.isEmpty()) {
12 ✔
990
      ui->grepResultsList->clear();
9 ✔
991
      ui->statusBar->showMessage(tr("Searching…"));
18 ✔
992
      if (m_grep.beginSearch()) {
993
        QApplication::setOverrideCursor(Qt::WaitCursor);
9 ✔
994
      }
995
      QtPassSettings::getPass()->Grep(query, ui->grepCaseButton->isChecked());
18 ✔
996
    } else {
997
      cancelContentSearch();
3 ✔
998
      if (m_grep.cancelSearch()) {
999
        QApplication::restoreOverrideCursor();
2 ✔
1000
      }
1001
      ui->grepResultsList->clear();
3 ✔
1002
      showContentResults(false);
3 ✔
1003
    }
1004
    return;
1005
  }
1006

1007
  // Return within the search delay acts on the text as typed, not on the
1008
  // tree as the previous text filtered it.
1009
  if (searchTimer.isActive()) {
5 ✔
1010
    searchTimer.stop();
5 ✔
1011
    onTimeoutSearch();
5 ✔
1012
  }
1013
  if (m_tree->proxy().rowCount() > 0) {
5 ✔
1014
    selectFirstFile();
5 ✔
1015
    on_treeView_clicked(ui->treeView->currentIndex());
5 ✔
1016
  }
1017
}
1018

1019
void MainWindow::on_grepButton_toggled(bool checked) {
29 ✔
1020
  const AppSettings s = QtPassSettings::load();
29 ✔
1021
  if (checked) {
29 ✔
1022
    m_grep.enterGrepMode();
1023
    ui->lineEdit->setPlaceholderText(tr("Search content (regex)"));
36 ✔
1024
    // Both backends search through NativeGrep (QRegularExpression), so one
1025
    // dialect: PCRE.
1026
    ui->lineEdit->setToolTip(
18 ✔
1027
        tr("Content search uses Perl-compatible regular expressions (PCRE)."));
18 ✔
1028
    ui->lineEdit->clear();
18 ✔
1029
    searchTimer.stop();
18 ✔
1030
    m_tree->setFilter(QRegularExpression());
18 ✔
1031
    ui->grepResultsList->setVisible(false);
18 ✔
1032
    // Keep treeView visible until results arrive
1033
  } else {
1034
    cancelContentSearch();
11 ✔
1035
    if (m_grep.leaveGrepMode()) {
1036
      QApplication::restoreOverrideCursor();
2 ✔
1037
    }
1038
    searchTimer.stop();
11 ✔
1039
    ui->lineEdit->blockSignals(true);
11 ✔
1040
    ui->lineEdit->clear();
11 ✔
1041
    ui->lineEdit->blockSignals(false);
11 ✔
1042
    ui->lineEdit->setPlaceholderText(tr("Search password"));
22 ✔
1043
    ui->lineEdit->setToolTip(QString());
22 ✔
1044
    ui->grepResultsList->clear();
11 ✔
1045
    showContentResults(false);
11 ✔
1046
    m_tree->setFilter(QRegularExpression());
11 ✔
1047
  }
1048
}
29 ✔
1049

1050
void MainWindow::onGrepFinished(
17 ✔
1051
    const QList<QPair<QString, QStringList>> &results) {
1052
  // Both backends stay connected, each with its own search: a search the
1053
  // other backend was still running when Settings switched backends is not
1054
  // this one, whatever the controller's state, and searched another store.
1055
  // Dropped before it can end (or be taken for) the current search.
1056
  if (const QObject *from = sender();
17 ✔
1057
      from != nullptr && from != QtPassSettings::getPass()) {
17 ✔
1058
    return;
11 ✔
1059
  }
1060
  const GrepSearchController::FinishOutcome outcome = m_grep.finishSearch();
1061
  if (outcome.restoreCursor) {
16 ✔
1062
    QApplication::restoreOverrideCursor();
2 ✔
1063
  }
1064
  // Re-enable the UI before the discard check so a cancelled search can never
1065
  // leave controls disabled.
1066
  setUiElementsEnabled(true);
16 ✔
1067
  if (outcome.discard) {
16 ✔
1068
    return;
1069
  }
1070
  if (!m_grep.inGrepMode())
8 ✔
1071
    return;
1072
  ui->grepResultsList->clear();
8 ✔
1073
  if (results.isEmpty()) {
8 ✔
1074
    ui->statusBar->showMessage(tr("No matches found."), 3000);
2 ✔
1075
    showContentResults(false);
2 ✔
1076
    return;
2 ✔
1077
  }
1078
  const AppSettings s = QtPassSettings::load();
6 ✔
1079
  const bool hideContent = s.hideContent;
6 ✔
1080
  int totalLines = 0;
1081
  int entries = 0;
1082
  bool stopped = false;
1083
  for (const auto &pair : results) {
35 ✔
1084
    if (NativeGrep::isStoppedMarker(pair)) {
29 ✔
1085
      stopped = true;
1086
      continue;
×
1087
    }
1088
    ++entries;
29 ✔
1089
    auto *entryItem = new QTreeWidgetItem(ui->grepResultsList);
29 ✔
1090
    entryItem->setText(0, pair.first);
29 ✔
1091
    entryItem->setData(0, Qt::UserRole, pair.first);
29 ✔
1092
    for (const QString &line : pair.second) {
58 ✔
1093
      auto *lineItem = new QTreeWidgetItem(entryItem);
29 ✔
1094
      // The marker is no content: shown as it is with hidden content too,
1095
      // and not counted as a match.
1096
      if (NativeGrep::isMoreMarker(line)) {
29 ✔
1097
        lineItem->setText(0, tr("… more matches in this entry"));
×
1098
      } else {
1099
        lineItem->setText(0, hideContent ? "***" + tr("Content hidden") + "***"
87 ✔
1100
                                         : line);
1101
        ++totalLines;
29 ✔
1102
      }
1103
      lineItem->setData(0, Qt::UserRole, pair.first);
29 ✔
1104
    }
1105
  }
1106
  ui->grepResultsList->expandAll();
6 ✔
1107
  showContentResults(true);
6 ✔
1108
  if (stopped) {
6 ✔
1109
    // The search stopped there; more entries may match.
1110
    ui->statusBar->showMessage(
×
1111
        tr("Showing the first %n match(es); search for something narrower "
×
1112
           "to see the rest.",
1113
           nullptr, totalLines),
1114
        10000);
1115
  } else {
1116
    ui->statusBar->showMessage(tr("Found %n match(es)", nullptr, totalLines) +
18 ✔
1117
                                   " " +
6 ✔
1118
                                   tr("in %n entr(ies).", nullptr, entries),
12 ✔
1119
                               3000);
1120
  }
1121
  if (s.useAutoclearPanel)
6 ✔
1122
    clearPanelTimer.start();
1 ✔
1123
}
6 ✔
1124

1125
void MainWindow::on_grepResultsList_itemClicked(QTreeWidgetItem *item,
2 ✔
1126
                                                int /*column*/) {
1127
  const AppSettings s = QtPassSettings::load();
2 ✔
1128
  const QString entry = item->data(0, Qt::UserRole).toString();
2 ✔
1129
  if (entry.isEmpty())
2 ✔
1130
    return;
1131
  const QString fullPath =
1132
      QDir::cleanPath(QDir(s.passStore).filePath(entry + ".gpg"));
4 ✔
1133
  // Persistent: setCurrentIndex() runs the selection handlers, which can
1134
  // change the model before the click is handled.
1135
  const QPersistentModelIndex proxyIndex(m_tree->indexFor(fullPath));
2 ✔
1136
  if (!proxyIndex.isValid())
2 ✔
1137
    return;
1138
  ui->treeView->setCurrentIndex(proxyIndex);
2 ✔
1139
  if (!proxyIndex.isValid())
2 ✔
1140
    return;
1141
  on_treeView_clicked(proxyIndex);
2 ✔
1142
  if (s.hideContent || s.useAutoclearPanel)
2 ✔
1143
    ui->grepResultsList->clear();
1 ✔
1144
  showContentResults(false);
2 ✔
1145
  ui->treeView->scrollTo(proxyIndex);
2 ✔
1146
  ui->treeView->setFocus();
2 ✔
1147
}
4 ✔
1148

1149
void MainWindow::showContentResults(bool shown) {
29 ✔
1150
  ui->grepResultsList->setVisible(shown);
29 ✔
1151
  ui->treeView->setVisible(!shown);
29 ✔
1152
  if (shown) {
29 ✔
1153
    // The tree's current entry is out of sight: Delete, Edit and OTP would
1154
    // act on it, not on a result. Opening a result shows the tree again.
1155
    ui->actionDelete->setEnabled(false);
6 ✔
1156
    ui->actionEdit->setEnabled(false);
6 ✔
1157
    updateOtpButtonVisibility(false);
6 ✔
1158
  } else if (ui->treeView->selectionModel()->hasSelection()) {
23 ✔
1159
    // Only for an entry still selected: with nothing selected there is no
1160
    // entry for Edit and Delete to act on.
1161
    setUiElementsEnabled(m_uiEnabled);
8 ✔
1162
  }
1163
}
29 ✔
1164

1165
void MainWindow::cancelContentSearch() {
24 ✔
1166
  QtPassSettings::getRealPass()->CancelGrep();
24 ✔
1167
  QtPassSettings::getImitatePass()->CancelGrep();
24 ✔
1168
}
24 ✔
1169

1170
void MainWindow::selectFirstFile() {
34 ✔
1171
  // The entry named exactly as typed wins: with folders sorted first, the
1172
  // depth-first walk found team/bank before bank.
1173
  QModelIndex index = exactMatch();
34 ✔
1174
  if (!index.isValid()) {
1175
    index = firstFile(m_tree->rootIndex());
17 ✔
1176
  }
1177
  ui->treeView->setCurrentIndex(index);
34 ✔
1178
}
34 ✔
1179

1180
namespace {
1181
/**
1182
 * @brief @p path with each part below @p store spelled as stored on disk.
1183
 *
1184
 * Where the file system ignores case, "Bank.gpg" exists while the file is
1185
 * bank.gpg, and the tree knows the entry only by that spelling.
1186
 * @param store The store folder.
1187
 * @param path An existing file in the store.
1188
 * @return @p path itself when every part is spelled as stored, otherwise
1189
 *         the path with the stored spelling.
1190
 */
1191
auto spelledAsStored(const QString &store, const QString &path) -> QString {
33 ✔
1192
  const QStringList parts = QDir(store).relativeFilePath(path).split(
66 ✔
1193
      QLatin1Char('/'), Qt::SkipEmptyParts);
33 ✔
1194
  QDir dir(store);
33 ✔
1195
  bool respelled = false;
1196
  for (int i = 0; i < parts.size(); ++i) {
36 ✔
1197
    const bool leaf = i == parts.size() - 1;
36 ✔
1198
    const QStringList names =
1199
        dir.entryList((leaf ? QDir::Files : QDir::Dirs) | QDir::Hidden |
36 ✔
1200
                      QDir::NoDotAndDotDot);
39 ✔
1201
    QString name = parts.at(i);
1202
    if (!names.contains(name)) {
36 ✔
1203
      const auto stored = std::find_if(
×
1204
          names.cbegin(), names.cend(), [&name](const QString &candidate) {
1205
            return candidate.compare(name, Qt::CaseInsensitive) == 0;
×
1206
          });
1207
      if (stored == names.cend()) {
×
1208
        return path;
1209
      }
1210
      name = *stored;
×
1211
      respelled = true;
1212
    }
1213
    if (leaf) {
36 ✔
1214
      return respelled ? QDir::cleanPath(dir.filePath(name)) : path;
66 ✔
1215
    }
1216
    if (!dir.cd(name)) {
3 ✔
1217
      return path;
1218
    }
1219
  }
1220
  return path;
1221
}
33 ✔
1222
} // namespace
1223

1224
auto MainWindow::exactMatchPath() -> QString {
52 ✔
1225
  const QString text = QDir::fromNativeSeparators(ui->lineEdit->text());
104 ✔
1226
  const QString store = QtPassSettings::getPassStore();
104 ✔
1227
  // A name may begin or end with a space: " bank" is that entry, not bank.
1228
  // Only when no entry is named so are spaces around the text dropped.
1229
  for (const QString &typed : {text, text.trimmed()}) {
196 ✔
1230
    if (typed.isEmpty()) {
73 ✔
1231
      continue;
×
1232
    }
1233
    const QString path =
1234
        QDir::cleanPath(QDir(store).filePath(typed + QStringLiteral(".gpg")));
146 ✔
1235
    if (PathValidator::isPathInStore(store, path) && QFileInfo(path).isFile()) {
73 ✔
1236
      return spelledAsStored(store, path);
33 ✔
1237
    }
1238
  }
156 ✔
1239
  return {};
19 ✔
1240
}
1241

1242
auto MainWindow::exactMatch() -> QModelIndex {
48 ✔
1243
  const QString path = exactMatchPath();
48 ✔
1244
  if (path.isEmpty()) {
48 ✔
1245
    return {};
18 ✔
1246
  }
1247
  // indexFor() maps through the filter: a row the filter hides is no match.
1248
  const QModelIndex index = m_tree->indexFor(path);
30 ✔
1249
  if (!index.isValid() || !m_tree->fileInfo(index).isFile()) {
53 ✔
1250
    return {};
7 ✔
1251
  }
1252
  return index;
23 ✔
1253
}
1254

1255
void MainWindow::applySearchText(const QString &text) {
9 ✔
1256
  // A name search: content search, left on, kept its results over the tree
1257
  // and ignored the text.
1258
  if (ui->grepButton->isChecked()) {
9 ✔
1259
    ui->grepButton->setChecked(false);
1 ✔
1260
  }
1261
  delete m_pendingOpen;
9 ✔
1262
  ui->lineEdit->setText(text);
9 ✔
1263
  // Filter now, not after the search delay: the timer would leave the tree
1264
  // as the previous text filtered it.
1265
  searchTimer.stop();
9 ✔
1266
  onTimeoutSearch();
9 ✔
1267
  if (const QModelIndex exact = exactMatch(); exact.isValid()) {
9 ✔
1268
    openExactMatch(exact);
5 ✔
1269
    return;
5 ✔
1270
  }
1271
  // The tree loads folders in the background: at start, or right after the
1272
  // window is shown again, an entry that exists may not be in it yet. Try
1273
  // again as folders finish loading, for a few seconds, unless the search
1274
  // text changes meanwhile: any change ends the wait, even one typed back to
1275
  // this text, which is a new search that has not asked to open anything.
1276
  if (exactMatchPath().isEmpty()) {
8 ✔
1277
    return;
1278
  }
1279
  auto *pending = new QObject(this);
3 ✔
1280
  m_pendingOpen = pending;
1281
  QTimer::singleShot(5000, pending, &QObject::deleteLater);
3 ✔
1282
  // Disconnected at once: with deleteLater() alone, a folder that finished
1283
  // loading before the deletion still ran the open, or ran it twice.
1284
  const auto stop = [this, pending] {
2 ✔
1285
    disconnect(&m_tree->fileSystem(), nullptr, pending, nullptr);
2 ✔
1286
    disconnect(ui->lineEdit, nullptr, pending, nullptr);
2 ✔
1287
    pending->deleteLater();
2 ✔
1288
  };
5 ✔
1289
  connect(ui->lineEdit, &QLineEdit::textChanged, pending, stop);
3 ✔
1290
  connect(&m_tree->fileSystem(), &QFileSystemModel::directoryLoaded, pending,
3 ✔
1291
          [this, stop](const QString &) {
6 ✔
1292
            searchTimer.stop();
5 ✔
1293
            onTimeoutSearch();
5 ✔
1294
            if (const QModelIndex exact = exactMatch(); exact.isValid()) {
5 ✔
1295
              stop();
1 ✔
1296
              openExactMatch(exact);
1 ✔
1297
            }
1298
          });
5 ✔
1299
}
1300

1301
void MainWindow::openExactMatch(const QModelIndex &index) {
6 ✔
1302
  // Made current here, not left to the filter pass before: the tree may have
1303
  // moved its current row since, and with none on_treeView_clicked() only
1304
  // names the entry without decrypting it.
1305
  ui->treeView->setCurrentIndex(index);
6 ✔
1306
  on_treeView_clicked(index);
6 ✔
1307
}
6 ✔
1308

1309
auto MainWindow::firstFile(QModelIndex parentIndex) -> QModelIndex {
26 ✔
1310
  StoreModel &proxy = m_tree->proxy();
26 ✔
1311
  int numRows = proxy.rowCount(parentIndex);
26 ✔
1312
  for (int row = 0; row < numRows; ++row) {
33 ✔
1313
    QModelIndex index = proxy.index(row, 0, parentIndex);
24 ✔
1314
    if (m_tree->fileInfo(index).isFile()) {
24 ✔
1315
      return index;
17 ✔
1316
    }
1317
    if (proxy.hasChildren(index)) {
14 ✔
1318
      QModelIndex childFile = firstFile(index);
9 ✔
1319
      if (childFile.isValid())
1320
        return childFile;
7 ✔
1321
    }
1322
  }
1323
  return QModelIndex();
9 ✔
1324
}
1325

1326
// Guards the input dialogs (create, move, rename) against names like
1327
// "../../etc/passwd" or absolute paths escaping the store root.
1328
auto MainWindow::confirmPathInStore(const QString &candidate) -> bool {
10 ✔
1329
  if (PathValidator::isPathInStore(QtPassSettings::getPassStore(), candidate)) {
20 ✔
1330
    return true;
1331
  }
1332
  QMessageBox::warning(this, tr("Invalid name"),
9 ✔
1333
                       tr("That name would resolve outside the password "
3 ✔
1334
                          "store. Please choose a different name."));
1335
  return false;
3 ✔
1336
}
1337

1338
void MainWindow::setPassword(const QString &file, bool isNew) {
7 ✔
1339
  const AppSettings s = QtPassSettings::load();
7 ✔
1340
  PasswordDialog d(QtPassSettings::getPass(), s, file, isNew, this);
7 ✔
1341
  // A copy out of the editor is autocleared like one from the display.
1342
  connect(&d, &PasswordDialog::copied, &m_qtPass->clipboard(),
7 ✔
1343
          &ClipboardManager::trackCopied);
7 ✔
1344

1345
  if (isNew) {
7 ✔
1346
    const QString storePath = s.passStore;
1347
    QString folder = m_tree->currentDir(false);
1 ✔
1348
    if (folder.isEmpty()) {
1 ✔
1349
      folder = storePath;
×
1350
    }
1351
    // Folders to pick from, the tree's current one preselected. Real folders
1352
    // only: a linked or junctioned one would write the entry outside the store.
1353
    QStringList folders{QString()};
2 ✔
1354
    const QStringList found = Util::directoriesUnder(storePath);
1 ✔
1355
    for (const QString &path : found) {
18 ✔
1356
      const QString rel = QDir(storePath).relativeFilePath(path);
17 ✔
1357
      if (!rel.startsWith(u'.') && !rel.contains(QStringLiteral("/."))) {
51 ✔
1358
        folders << rel;
1359
      }
1360
    }
1361
    std::sort(folders.begin() + 1, folders.end());
1 ✔
1362
    d.setNewEntryLocation(storePath, folders,
1 ✔
1363
                          QDir(storePath).relativeFilePath(folder));
2 ✔
1364
    QHash<QString, QStringList> templates =
1365
        TemplateIO::readTemplates(storePath);
1 ✔
1366
    if (!templates.isEmpty()) {
1367
      QString defaultTemplate =
1368
          TemplateIO::getFolderTemplate(folder, storePath);
1 ✔
1369
      d.setAvailableTemplates(templates, defaultTemplate);
1 ✔
1370
    }
1371
  }
1 ✔
1372

1373
  if (!d.exec()) {
7 ✔
1374
    ui->treeView->setFocus();
6 ✔
1375
  }
1376
}
7 ✔
1377

1378
void MainWindow::addPassword() { setPassword(QString()); }
2 ✔
1379

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

1439
auto MainWindow::confirmLinkRemoval(const QString &file) -> bool {
1 ✔
1440
  // Only the link goes (ImitatePass::Remove unlinks it); nothing behind it
1441
  // is looked at or mentioned.
1442
  return PlainMessageBox::askYes(
1 ✔
1443
      this, tr("Delete link?"),
1 ✔
1444
      tr("%1 is a symbolic link or junction. Remove the link? What it "
1 ✔
1445
         "points to is left alone.")
1446
          .arg(Util::displayable(QDir::separator() + file, false)));
2 ✔
1447
}
1448

1449
void MainWindow::onDelete() {
13 ✔
1450
  const QModelIndex currentIndex = ui->treeView->currentIndex();
13 ✔
1451
  // While content search results hide the tree, its current entry is not
1452
  // what the user looks at (the Delete key comes here directly).
1453
  if (!currentIndex.isValid() || ui->treeView->isHidden()) {
11 ✔
1454
    // Otherwise the whole password directory would be deleted (#556).
1455
    return;
10 ✔
1456
  }
1457

1458
  const bool isDir = !m_tree->fileInfo(currentIndex).isFile();
9 ✔
1459
  const QString file =
1460
      isDir ? m_tree->currentDir(true) : getFile(currentIndex, true);
9 ✔
1461
  const QString folder =
1462
      m_tree->fileSystem().rootPath() + QDir::separator() + file;
9 ✔
1463
  const bool linkedFolder = isDir && Util::isLinkedFolder(folder);
9 ✔
1464

1465
  if (!linkedFolder && refuseLinkedFolder(folder)) {
8 ✔
1466
    // Behind a link: deleting would reach outside the store.
1467
    return;
1468
  }
1469
  const bool confirmed =
1470
      linkedFolder ? confirmLinkRemoval(file) : confirmDeletion(file, isDir);
9 ✔
1471
  if (!confirmed) {
9 ✔
1472
    return;
1473
  }
1474
  QtPassSettings::getPass()->Remove(file, isDir);
6 ✔
1475
}
1476

1477
void MainWindow::cancelOtpRequest() {
91 ✔
1478
  m_otpRequestFile.clear();
91 ✔
1479
  m_copyRequestFile.clear();
91 ✔
1480
}
91 ✔
1481

1482
void MainWindow::onOperationError() {
34 ✔
1483
  cancelOtpRequest();
34 ✔
1484
  // executeWrapperStarted() emptied the panel and the browser when the
1485
  // operation started (a refusal says so too); what is left to forget is
1486
  // which entry the panel was about to show.
1487
  m_shownFile.clear();
34 ✔
1488
  // A save's refresh waiting for its push is dropped: it would clear the
1489
  // push's error (or whatever failed before it) from the browser.
1490
  m_refreshAfterPush.clear();
34 ✔
1491
  m_refreshAfterPushOwner = nullptr;
1492
}
34 ✔
1493

1494
// Derives the code in-process from one decrypt, so it works with either
1495
// backend on every platform; otpFromFileToClipboard() finishes the job.
1496
void MainWindow::onOtp() {
12 ✔
1497
  if (ui->treeView->isHidden()) {
12 ✔
1498
    return;
4 ✔
1499
  }
1500
  QString file = getFile(ui->treeView->currentIndex(), true);
11 ✔
1501
  if (file.isEmpty()) {
11 ✔
1502
    flashText(tr("No password selected for OTP generation"), true);
1 ✔
1503
    return;
1 ✔
1504
  }
1505
  if (!QtPassSettings::isUseOtp()) {
10 ✔
1506
    // Normally unreachable (the action is hidden), but never fail silently.
1507
    flashText(tr("No OTP code found in this password entry"), true);
1 ✔
1508
    return;
1 ✔
1509
  }
1510

1511
  // Fast path: the panel shows a live code, so no decrypt, and one clipboard
1512
  // write (two setMimeData calls in one turn can empty the Windows
1513
  // clipboard). Only for *this* entry: arrow keys and right-click move
1514
  // currentIndex without QTreeView::clicked, so the code may be another's.
1515
  const QString shown =
1516
      (m_shownFile == file) ? m_displayPanel->currentOtpCode() : QString();
9 ✔
1517
  if (!shown.isEmpty()) {
9 ✔
1518
    m_qtPass->clipboard().copyText(shown);
1 ✔
1519
    showStatusMessage(tr("OTP code copied to clipboard"));
2 ✔
1520
    return;
1521
  }
1522

1523
  // Fallback: decrypt once. The request file keeps passShowHandler from
1524
  // copying the password and tells otpFromFileToClipboard its answer.
1525
  m_otpRequestFile = file;
8 ✔
1526
  setUiElementsEnabled(false);
8 ✔
1527
  // Keep the marker in step so a second request takes the fast path; safe as
1528
  // executeWrapperStarted() clears the panel, so a failed decrypt shows none.
1529
  m_shownFile = file;
8 ✔
1530
  QtPassSettings::getPass()->Show(file);
16 ✔
1531
}
1532

1533
void MainWindow::onEdit() {
1 ✔
1534
  if (ui->treeView->isHidden()) {
1 ✔
1535
    return;
1 ✔
1536
  }
UNCOV
1537
  QString file = getFile(ui->treeView->currentIndex(), true);
×
UNCOV
1538
  editPassword(file);
×
1539
}
1540

1541
void MainWindow::onUsers() {
2 ✔
1542
  const QString dir = m_tree->currentDir(false);
2 ✔
1543
  if (refuseLinkedFolder(dir)) {
2 ✔
1544
    return;
1545
  }
1546

1547
  UsersDialog d(QtPassSettings::getPass(), QtPassSettings::load(), dir, this);
1 ✔
1548
  if (!d.exec()) {
1 ✔
1549
    ui->treeView->setFocus();
1 ✔
1550
  }
1551
}
1 ✔
1552

1553
void MainWindow::messageAvailable(const QString &message) {
10 ✔
1554
  show();
10 ✔
1555
  raise();
10 ✔
1556
  if (message.isEmpty()) {
10 ✔
1557
    focusInput();
1 ✔
1558
  } else {
1559
    ui->treeView->expandAll();
9 ✔
1560
    applySearchText(message);
9 ✔
1561
  }
1562
}
10 ✔
1563

1564
void MainWindow::updateProfileBox() {
196 ✔
1565
  const Profiles profiles = QtPassSettings::getProfiles();
196 ✔
1566
  bool activeGone = false;
1567

1568
  if (profiles.isEmpty()) {
7 ✔
1569
    ui->profileWidget->hide();
189 ✔
1570
  } else {
1571
    ui->profileWidget->show();
7 ✔
1572
    // A refill is no choice of the user's: clearing and adding items moves
1573
    // the current text, which would otherwise switch profiles.
1574
    const QSignalBlocker quiet(ui->profileBox);
7 ✔
1575
    ui->profileBox->clear();
7 ✔
1576
    for (auto i = profiles.cbegin(); i != profiles.cend(); ++i) {
19 ✔
1577
      if (!i.key().isEmpty()) {
12 ✔
1578
        ui->profileBox->addItem(i.key());
12 ✔
1579
      }
1580
    }
1581
    ui->profileBox->model()->sort(0);
7 ✔
1582
    int index = ui->profileBox->findText(QtPassSettings::getProfile());
14 ✔
1583
    if (index != -1) { //  -1 for not found
7 ✔
1584
      ui->profileBox->setCurrentIndex(index);
6 ✔
1585
    } else if (ui->profileBox->count() > 0) {
1 ✔
1586
      // The active profile is gone (removed in Settings): the box shows the
1587
      // first one, and the settings and backend must follow it, or the
1588
      // removed profile's store stays in use behind it.
1589
      ui->profileBox->setCurrentIndex(0);
1 ✔
1590
      activeGone = true;
1591
    }
1592
  }
7 ✔
1593
  if (activeGone) {
7 ✔
1594
    on_profileBox_currentTextChanged(ui->profileBox->currentText());
2 ✔
1595
  }
1596
  updateProfileBoxEnabled();
196 ✔
1597
}
196 ✔
1598

1599
void MainWindow::updateProfileBoxEnabled() {
662 ✔
1600
  // No profile switch while anything of the store runs or waits: the
1601
  // backend's store and environment would change under it, and what is
1602
  // still queued (a push after a save, say) would finish for the other
1603
  // profile (#2071). Asked of the backend, not only of the interface: the
1604
  // watchdog releases the interface while a slow gpg or git still runs.
1605
  // Every backend: one kept from before a switch of backend may still
1606
  // run what was queued on it.
1607
  ui->profileBox->setEnabled(m_uiEnabled && ui->profileBox->count() > 1 &&
1,326 ✔
1608
                             QtPassSettings::backendsIdle());
14 ✔
1609
}
662 ✔
1610

1611
void MainWindow::on_profileBox_currentTextChanged(const QString &name) {
6 ✔
1612
  if (m_freshStart || name == QtPassSettings::getProfile()) {
18 ✔
1613
    return;
1 ✔
1614
  }
1615
  // The box is disabled while anything runs; should a change come through
1616
  // anyway, the active profile stays and the box says so again.
1617
  if (!m_uiEnabled || !QtPassSettings::backendsIdle()) {
5 ✔
1618
    const QSignalBlocker quiet(ui->profileBox);
×
1619
    ui->profileBox->setCurrentText(QtPassSettings::getProfile());
×
1620
    return;
1621
  }
×
1622
  // A content search runs outside the queue: leaving grep mode cancels it,
1623
  // so its results for the old store are dropped, not shown for the new.
1624
  if (m_grep.inGrepMode()) {
5 ✔
1625
    ui->grepButton->setChecked(false);
1 ✔
1626
  }
1627

1628
  ui->lineEdit->clear();
5 ✔
1629

1630
  const Profile prof = QtPassSettings::getProfiles().value(name);
10 ✔
1631
  AppSettings s = QtPassSettings::load();
5 ✔
1632
  s.activeProfile = name;
5 ✔
1633
  s.passStore = prof.path;
5 ✔
1634
  s.passSigningKey = prof.signingKey;
5 ✔
1635
  // A profile without its own Git flags keeps the global values.
1636
  s.useGit = prof.useGit.value_or(s.useGit);
5 ✔
1637
  s.autoPush = prof.autoPush.value_or(s.autoPush);
5 ✔
1638
  s.autoPull = prof.autoPull.value_or(s.autoPull);
5 ✔
1639
  QtPassSettings::save(s);
5 ✔
1640
  ui->statusBar->showMessage(tr("Profile changed to %1").arg(name), 2000);
10 ✔
1641

1642
  QtPassSettings::getPass()->updateEnv();
5 ✔
1643

1644
  m_tree->setStore(QtPassSettings::getPassStore());
10 ✔
1645
  deselect();
5 ✔
1646
  ui->treeView->setCurrentIndex(QModelIndex());
5 ✔
1647
}
5 ✔
1648

1649
void MainWindow::initTrayIcon() {
3 ✔
1650
  m_tray = new TrayIcon(this);
3 ✔
1651
  if (!m_tray->getIsAllocated()) {
3 ✔
1652
    destroyTrayIcon();
3 ✔
1653
    return;
3 ✔
1654
  }
1655
#ifndef Q_OS_MACOS
1656
  m_tray->addToggle(ui->actionShowMenuBar);
×
1657
#endif
1658
}
1659

1660
void MainWindow::destroyTrayIcon() {
3 ✔
1661
  delete m_tray;
3 ✔
1662
  m_tray = nullptr;
3 ✔
1663
}
3 ✔
1664

1665
void MainWindow::closeEvent(QCloseEvent *event) {
4 ✔
1666
  // Save in both branches: a tray user only ever hides the window, and
1667
  // used to quit through the tray menu with nothing ever written.
1668
  saveWindowState();
4 ✔
1669
  // Only with a tray icon to come back from: without one (none asked for, or
1670
  // no system tray in this session) a hidden QtPass ran on invisibly, with the
1671
  // last entry in its window and the password on the clipboard.
1672
  if (QtPassSettings::isHideOnClose() && m_tray != nullptr) {
8 ✔
1673
    this->hide();
×
1674
    event->ignore();
1675
  } else {
1676
    m_qtPass->clipboard().clear();
4 ✔
1677
    event->accept();
1678
    // A visible QSystemTrayIcon keeps the application alive, so
1679
    // quitOnLastWindowClosed never fires; quit explicitly.
1680
    QApplication::quit();
4 ✔
1681
  }
1682
}
4 ✔
1683

1684
auto MainWindow::eventFilter(QObject *obj, QEvent *event) -> bool {
7,917 ✔
1685
  if ((obj == ui->toolBar || obj == menuBar()) &&
7,917 ✔
1686
      event->type() == QEvent::PaletteChange) {
1687
    // Breeze gives these bars a "header" palette and, after a runtime
1688
    // light/dark switch, stamps the previous theme's colours back from a
1689
    // cached kdeglobals, hiding the toolbar icons. Deferred so we never
1690
    // re-enter the style while it is still applying its palette.
1691
    QTimer::singleShot(0, this, &MainWindow::dropStaleToolsAreaPalettes);
36 ✔
1692
  }
1693
  if (obj == ui->lineEdit && event->type() == QEvent::KeyPress) {
7,917 ✔
1694
    auto *key = dynamic_cast<QKeyEvent *>(event);
5 ✔
1695
    if (key != nullptr && key->key() == Qt::Key_Down) {
5 ✔
1696
      // Into whichever list is in sight: the tree, or content search results.
1697
      // Focus makes the list's first item current.
1698
      if (ui->treeView->isHidden()) {
2 ✔
1699
        ui->grepResultsList->setFocus();
1 ✔
1700
      } else {
1701
        ui->treeView->setFocus();
1 ✔
1702
      }
1703
    }
1704
    // Return ends at the search box: QLineEdit emits returnPressed() and
1705
    // leaves the key unaccepted, so keyPressEvent() would open the tree's
1706
    // current entry as well. In content search that is an entry nobody
1707
    // asked for; by name, the first hit a second time.
1708
    if (key != nullptr &&
5 ✔
1709
        (key->key() == Qt::Key_Return || key->key() == Qt::Key_Enter)) {
2 ✔
1710
      ui->lineEdit->event(event);
3 ✔
1711
      event->accept();
1712
      return true;
3 ✔
1713
    }
1714
  }
1715
  return QObject::eventFilter(obj, event);
7,914 ✔
1716
}
1717

1718
// Only once the application palette changed (see m_themeSwitched): a bar
1719
// whose active Window lightness is far from the application's shows the
1720
// other theme.
1721
void MainWindow::dropStaleToolsAreaPalettes() {
31 ✔
1722
  if (!m_themeSwitched) {
31 ✔
1723
    return;
1724
  }
1725
  constexpr int kStaleToolsAreaLightness = 64;
1726
  // The active group on both sides: a bar's palette() reads the inactive
1727
  // group while another window has focus (the settings app, during a theme
1728
  // switch), and Breeze gives the header set different inactive colours.
1729
  const int appLightness = QApplication::palette()
54 ✔
1730
                               .color(QPalette::Active, QPalette::Window)
1731
                               .lightness();
27 ✔
1732
  for (QWidget *bar : {static_cast<QWidget *>(ui->toolBar),
108 ✔
1733
                       static_cast<QWidget *>(menuBar())}) {
81 ✔
1734
    if (!bar->testAttribute(Qt::WA_SetPalette)) {
54 ✔
1735
      continue;
48 ✔
1736
    }
1737
    const int barLightness =
1738
        bar->palette().color(QPalette::Active, QPalette::Window).lightness();
12 ✔
1739
    if (qAbs(barLightness - appLightness) <= kStaleToolsAreaLightness) {
6 ✔
1740
      continue;
2 ✔
1741
    }
1742
    bar->setPalette(QPalette());
4 ✔
1743
    // Both bars are transparent and the style paints the tools area from the
1744
    // stale palette, so fill our own. Window, not their Button role, which is
1745
    // not the window colour in either theme.
1746
    bar->setBackgroundRole(QPalette::Window);
4 ✔
1747
    bar->setAutoFillBackground(true);
4 ✔
1748
  }
1749
}
1750

1751
void MainWindow::keyPressEvent(QKeyEvent *event) {
25 ✔
1752
  switch (event->key()) {
25 ✔
1753
  case Qt::Key_Delete:
2 ✔
1754
    onDelete();
2 ✔
1755
    break;
2 ✔
1756
  case Qt::Key_Return:
2 ✔
1757
  case Qt::Key_Enter:
1758
    // While content search results hide the tree, its current entry is not
1759
    // what the user looks at: Return on a result opens that result.
1760
    if (ui->treeView->isHidden()) {
2 ✔
1761
      QTreeWidgetItem *result = ui->grepResultsList->currentItem();
1 ✔
1762
      if (result != nullptr && ui->grepResultsList->hasFocus()) {
1 ✔
1763
        on_grepResultsList_itemClicked(result, 0);
1 ✔
1764
      }
1765
      break;
1766
    }
1767
    if (m_tree->proxy().rowCount() > 0) {
1 ✔
1768
      on_treeView_clicked(ui->treeView->currentIndex());
1 ✔
1769
    }
1770
    break;
1771
  case Qt::Key_Escape:
3 ✔
1772
    ui->lineEdit->clear();
3 ✔
1773
    break;
3 ✔
1774
  default:
1775
    break;
1776
  }
1777
}
25 ✔
1778

1779
void MainWindow::addShareMenu(QMenu &contextMenu, const AppSettings &s) {
10 ✔
1780
  const QString dirPath = QDir::cleanPath(m_tree->currentDir(false));
10 ✔
1781
  auto *shareMenu = new QMenu(tr("Share"), &contextMenu);
10 ✔
1782
  contextMenu.addMenu(shareMenu);
10 ✔
1783

1784
  const QString gpgIdPath = Pass::getGpgIdPath(dirPath, s.passStore);
10 ✔
1785
  const bool gpgIdExists = !gpgIdPath.isEmpty() && QFile(gpgIdPath).exists();
10 ✔
1786
  const QString exePath = s.usePass ? s.passExecutable : s.gpgExecutable;
10 ✔
1787
  const bool gpgAvailable =
1788
      !exePath.isEmpty() &&
20 ✔
1789
      (Executor::parseWslCommand(exePath) || QFile(exePath).exists());
20 ✔
1790

1791
  QAction *reencrypt = shareMenu->addAction(tr("Re-encrypt all passwords"));
10 ✔
1792
  reencrypt->setEnabled(gpgIdExists && gpgAvailable);
10 ✔
1793
  connect(reencrypt, &QAction::triggered, this,
10 ✔
1794
          [this, dirPath]() { reencryptPath(dirPath); });
34 ✔
1795

1796
  QAction *exportKey = shareMenu->addAction(tr("Export my public key..."));
10 ✔
1797
  exportKey->setEnabled(gpgAvailable);
10 ✔
1798
  connect(exportKey, &QAction::triggered, this, &MainWindow::exportPublicKey);
10 ✔
1799

1800
  QAction *addRecipientAction = shareMenu->addAction(tr("Add recipient..."));
10 ✔
1801
  addRecipientAction->setEnabled(gpgIdExists && gpgAvailable);
10 ✔
1802
  connect(addRecipientAction, &QAction::triggered, this,
10 ✔
1803
          [this, dirPath]() { addRecipient(dirPath); });
32 ✔
1804

1805
  QAction *shareHelp = shareMenu->addAction(tr("What is this?"));
10 ✔
1806
  connect(shareHelp, &QAction::triggered, this, &MainWindow::showShareHelp);
10 ✔
1807
}
10 ✔
1808

1809
void MainWindow::showContextMenu(const QPoint &pos) {
12 ✔
1810
  const AppSettings s = QtPassSettings::load();
12 ✔
1811
  const QModelIndex index = ui->treeView->indexAt(pos);
12 ✔
1812
  const bool selected = index.isValid();
1813
  if (!selected) {
1814
    ui->treeView->clearSelection();
1 ✔
1815
    ui->actionDelete->setEnabled(false);
1 ✔
1816
    ui->actionEdit->setEnabled(false);
1 ✔
1817
  }
1818
  ui->treeView->setCurrentIndex(index);
12 ✔
1819
  const QPoint globalPos = ui->treeView->viewport()->mapToGlobal(pos);
12 ✔
1820
  const QFileInfo fileOrFolder = m_tree->fileInfo(ui->treeView->currentIndex());
12 ✔
1821
  const bool isDir = fileOrFolder.isDir();
12 ✔
1822

1823
  QMenu contextMenu;
12 ✔
1824
  if (!selected || isDir) {
12 ✔
1825
    const std::array<std::pair<QString, void (MainWindow::*)()>, 4> onFolder{{
1826
        {tr("Open folder with file manager"), &MainWindow::openFolder},
11 ✔
1827
        {tr("Add folder"), &MainWindow::addFolder},
11 ✔
1828
        {tr("Add password"), &MainWindow::addPassword},
11 ✔
1829
        {tr("Users"), &MainWindow::onUsers},
11 ✔
1830
    }};
×
1831
    for (const auto &[text, slot] : onFolder) {
55 ✔
1832
      connect(contextMenu.addAction(text), &QAction::triggered, this, slot);
44 ✔
1833
    }
1834
  } else if (fileOrFolder.isFile()) {
1 ✔
1835
    connect(contextMenu.addAction(tr("Edit")), &QAction::triggered, this,
1 ✔
1836
            &MainWindow::onEdit);
2 ✔
1837
  }
1838
  if (selected) {
12 ✔
1839
    contextMenu.addSeparator();
11 ✔
1840
    if (isDir) {
11 ✔
1841
      connect(contextMenu.addAction(tr("Rename folder")), &QAction::triggered,
10 ✔
1842
              this, &MainWindow::renameFolder);
20 ✔
1843
    } else if (fileOrFolder.isFile()) {
1 ✔
1844
      connect(contextMenu.addAction(tr("Rename password")), &QAction::triggered,
1 ✔
1845
              this, &MainWindow::renamePassword);
2 ✔
1846
    }
1847
    connect(contextMenu.addAction(tr("Delete")), &QAction::triggered, this,
11 ✔
1848
            &MainWindow::onDelete);
11 ✔
1849
    if (isDir) {
11 ✔
1850
      addShareMenu(contextMenu, s);
10 ✔
1851
    }
1852
  }
1853
  contextMenu.exec(globalPos);
12 ✔
1854
}
12 ✔
1855

1856
auto MainWindow::browserContextMenu(const QPoint &pos) -> QMenu * {
3 ✔
1857
  // createStandardContextMenu() takes document coordinates, anchorAt() and
1858
  // the menu's place viewport ones: scrolled, the menu checked the text
1859
  // above the link and left "Copy Link Location" disabled.
1860
  // Right to left, the horizontal offset counts from the other end.
1861
  const QScrollBar *across = ui->textBrowser->horizontalScrollBar();
3 ✔
1862
  const int dx = ui->textBrowser->isRightToLeft()
3 ✔
1863
                     ? across->maximum() - across->value()
3 ✔
1864
                     : across->value();
3 ✔
1865
  const QPoint documentPos =
1866
      pos + QPoint(dx, ui->textBrowser->verticalScrollBar()->value());
3 ✔
1867
  QMenu *contextMenu = ui->textBrowser->createStandardContextMenu(documentPos);
3 ✔
1868
  // Reparent from textBrowser: a browser stylesheet cascades to the child
1869
  // QMenu and breaks its opaque native background.
1870
  contextMenu->setParent(this, contextMenu->windowFlags());
3 ✔
1871
  if (auto *copyLink =
3 ✔
1872
          contextMenu->findChild<QAction *>(QStringLiteral("link-copy"))) {
3 ✔
1873
    const QString link = ui->textBrowser->anchorAt(pos);
3 ✔
1874
    disconnect(copyLink, &QAction::triggered, nullptr, nullptr);
3 ✔
1875
    connect(copyLink, &QAction::triggered, this, [this, link] {
10 ✔
1876
      if (!link.isEmpty()) {
1 ✔
1877
        m_qtPass->clipboard().copyText(link);
1 ✔
1878
      }
1879
    });
1 ✔
1880
  }
1881
  return contextMenu;
3 ✔
1882
}
1883

1884
void MainWindow::showBrowserContextMenu(const QPoint &pos) {
1 ✔
1885
  QMenu *contextMenu = browserContextMenu(pos);
1 ✔
1886
  contextMenu->exec(ui->textBrowser->viewport()->mapToGlobal(pos));
1 ✔
1887
  delete contextMenu;
1 ✔
1888
}
1 ✔
1889

1890
void MainWindow::openFolder() {
1 ✔
1891
  QString dir = m_tree->currentDir(false);
1 ✔
1892

1893
  QString path = QDir::toNativeSeparators(dir);
1 ✔
1894
  QDesktopServices::openUrl(QUrl::fromLocalFile(path));
1 ✔
1895
}
1 ✔
1896

1897
void MainWindow::addFolder() {
7 ✔
1898
  const AppSettings s = QtPassSettings::load();
7 ✔
1899
  bool ok;
1900
  QString dir = m_tree->currentDir(false);
7 ✔
1901
  QString newdir = QInputDialog::getText(
1902
      this, tr("New folder"),
7 ✔
1903
      tr("New folder: \n(Will be placed in %1 )")
7 ✔
1904
          .arg(Util::shownName(s.passStore + m_tree->currentDir(true))),
14 ✔
1905
      QLineEdit::Normal, "", &ok);
14 ✔
1906
  if (!ok || newdir.isEmpty()) {
7 ✔
1907
    return;
1908
  }
1909
  // Checked and created as one and the same path: the check resolves ".."
1910
  // lexically, the system after following links, so "link/../x" would pass
1911
  // as the store's x and be made beside the link's target.
1912
  newdir = QDir::cleanPath(newdir.prepend(dir));
6 ✔
1913
  if (!confirmPathInStore(newdir)) {
6 ✔
1914
    return;
1915
  }
1916
  // Behind a link the folder would be made outside the store, as Users,
1917
  // Re-encrypt and Delete already refuse.
1918
  if (refuseLinkedFolder(newdir)) {
5 ✔
1919
    return;
1920
  }
1921
  // The tree, like `pass ls`, hides names that start with a dot.
1922
  const QStringList parts =
1923
      QDir(s.passStore).relativeFilePath(newdir).split(u'/');
4 ✔
1924
  if (std::any_of(parts.cbegin(), parts.cend(), [](const QString &part) {
8 ✔
1925
        return part != u'.' && part.startsWith(u'.');
4 ✔
1926
      })) {
1927
    PlainMessageBox::warning(this, tr("Hidden folder"),
2 ✔
1928
                             tr("A folder that starts with a dot would be "
1 ✔
1929
                                "hidden from the list: %1")
1930
                                 .arg(newdir));
2 ✔
1931
    return;
1 ✔
1932
  }
1933
  // Exists already: an error, as QDir::mkdir() made it before.
1934
  if (QFileInfo::exists(newdir) || !Util::mkpathForStore(newdir)) {
3 ✔
1935
    PlainMessageBox::warning(this, tr("Error"),
2 ✔
1936
                             tr("Failed to create folder: %1").arg(newdir));
2 ✔
1937
    return;
1 ✔
1938
  }
1939
  // No .gpg-id of its own: the folder uses its parent's recipients, as with
1940
  // pass, until Users gives it a list. A copy of the parent's list (#1688)
1941
  // kept every recipient later removed above it, and its entries stayed
1942
  // readable by them.
1943
}
7 ✔
1944

1945
void MainWindow::renameFolder() {
3 ✔
1946
  bool ok;
1947
  QString srcDir = QDir::cleanPath(m_tree->currentDir(false));
3 ✔
1948
  QString srcDirName = QDir(srcDir).dirName();
3 ✔
1949
  QString newName =
1950
      QInputDialog::getText(this, tr("Rename folder"), tr("Rename folder to: "),
3 ✔
1951
                            QLineEdit::Normal, srcDirName, &ok);
6 ✔
1952
  if (!ok || newName.isEmpty()) {
3 ✔
1953
    return;
1954
  }
1955
  QString destDir = srcDir;
1956
  destDir.replace(srcDir.lastIndexOf(srcDirName), srcDirName.length(), newName);
2 ✔
1957
  if (!confirmPathInStore(destDir)) {
2 ✔
1958
    return;
1959
  }
1960
  QtPassSettings::getPass()->Move(srcDir, destDir, false);
3 ✔
1961
}
1962

1963
void MainWindow::editPassword(const QString &file) {
6 ✔
1964
  if (!file.isEmpty()) {
6 ✔
1965
    const AppSettings s = QtPassSettings::load();
6 ✔
1966
    if (s.useGit && s.autoPull) {
6 ✔
1967
      onUpdate(true);
1 ✔
1968
    }
1969
    // The dialog decrypts the entry itself to fill its fields. That decrypt
1970
    // lands on the same finishedShow the panel uses, so drop the panel's claim
1971
    // to it: otherwise passShowHandler() repaints and, with "Always copy",
1972
    // puts the entry's old password on the clipboard - replacing whatever the
1973
    // user copied to paste into the dialog.
1974
    m_shownFile.clear();
6 ✔
1975
    setPassword(file, false);
6 ✔
1976
  }
6 ✔
1977
}
6 ✔
1978

1979
void MainWindow::renamePassword() {
2 ✔
1980
  bool ok;
1981
  QString file = getFile(ui->treeView->currentIndex(), false);
2 ✔
1982
  QString filePath = QFileInfo(file).path();
2 ✔
1983
  QString fileName = QFileInfo(file).fileName();
2 ✔
1984
  if (fileName.endsWith(".gpg", Qt::CaseInsensitive)) {
4 ✔
1985
    fileName.chop(4);
2 ✔
1986
  }
1987

1988
  QString newName =
1989
      QInputDialog::getText(this, tr("Rename file"), tr("Rename file to: "),
2 ✔
1990
                            QLineEdit::Normal, fileName, &ok);
4 ✔
1991
  if (!ok || newName.isEmpty()) {
2 ✔
1992
    return;
1993
  }
1994
  QString newFile = QDir(filePath).filePath(newName);
2 ✔
1995
  if (!confirmPathInStore(newFile)) {
2 ✔
1996
    return;
1997
  }
1998
  QtPassSettings::getPass()->Move(file, newFile, false);
3 ✔
1999
}
2000

2001
void MainWindow::copySelectionOrPassword() {
5 ✔
2002
  QWidget *focus = QApplication::focusWidget();
5 ✔
2003
  // The widget's own copy: a SecretTextBrowser marks what it copies as
2004
  // secret for clipboard managers, as the context menu's Copy does.
2005
  if (auto *text = qobject_cast<QTextEdit *>(focus);
5 ✔
2006
      text != nullptr && text->textCursor().hasSelection()) {
5 ✔
2007
    text->copy();
1 ✔
2008
    return;
1 ✔
2009
  }
2010
  // Through the clipboard manager, as a copy button would: the label may be
2011
  // the OTP code, which gets the secret hint and the autoclear.
2012
  if (auto *label = qobject_cast<QLabel *>(focus);
2013
      label != nullptr && label->hasSelectedText()) {
4 ✔
2014
    m_qtPass->clipboard().copyText(label->selectedText());
1 ✔
2015
    return;
1 ✔
2016
  }
2017
  // A line of the content search results is decrypted text: through the
2018
  // clipboard manager too, for the secret hint and the autoclear.
2019
  if (focus == ui->grepResultsList) {
3 ✔
2020
    if (const QTreeWidgetItem *item = ui->grepResultsList->currentItem();
3 ✔
2021
        item != nullptr && !item->text(0).isEmpty()) {
6 ✔
2022
      m_qtPass->clipboard().copyText(item->text(0));
6 ✔
2023
    }
2024
    return;
3 ✔
2025
  }
2026
  copyPasswordFromTreeview();
×
2027
}
2028

2029
void MainWindow::copyPasswordFromTreeview() {
9 ✔
2030
  // While content search results hide the tree, its current entry is not
2031
  // what the user looks at: no decrypt, as for Edit and OTP.
2032
  if (ui->treeView->isHidden()) {
9 ✔
2033
    return;
×
2034
  }
2035
  QFileInfo fileOrFolder = m_tree->fileInfo(ui->treeView->currentIndex());
9 ✔
2036

2037
  if (fileOrFolder.isFile()) {
9 ✔
2038
    QString file = getFile(ui->treeView->currentIndex(), true);
9 ✔
2039
    // The newest Ctrl+C wins: finishedShow names its file, so the decrypt of
2040
    // an earlier request is simply not this one's.
2041
    m_copyRequestFile = file;
9 ✔
2042
    // This Show repaints the panel as well; see onOtp().
2043
    m_shownFile = file;
9 ✔
2044
    QtPassSettings::getPass()->Show(file);
18 ✔
2045
  }
2046
}
9 ✔
2047

2048
void MainWindow::passwordFromFileToClipboard(const QString &text,
32 ✔
2049
                                             const QString &file) {
2050
  if (m_copyRequestFile.isEmpty() || file != m_copyRequestFile) {
32 ✔
2051
    return;
27 ✔
2052
  }
2053
  m_copyRequestFile.clear();
8 ✔
2054
  // The first line, without a list of every line (an entry can expand into
2055
  // millions of them), and without the "\r" of a CRLF line end, as the
2056
  // password row and "Always copy" have it.
2057
  const QString first = FileContent::passwordLine(text);
8 ✔
2058
  // A `pass otp insert` entry's first line is the otpauth:// URI carrying the
2059
  // TOTP seed, and an OTP field holding a seed there is the same; copying it
2060
  // would leak 2FA material. Matches the display path
2061
  // (FileContent::getPasswordForDisplay / PasswordDisplayPanel).
2062
  if (FileContent::isOtpPasswordLine(first)) {
8 ✔
2063
    flashText(tr("This entry holds an OTP secret, not a password"), true);
6 ✔
2064
    return;
2065
  }
2066
  m_qtPass->clipboard().copyText(first);
5 ✔
2067
}
2068

2069
void MainWindow::showStatusMessage(const QString &msg, int timeout) {
34 ✔
2070
  ui->statusBar->showMessage(msg, timeout);
34 ✔
2071
}
34 ✔
2072

2073
void MainWindow::reencryptPath(const QString &dir) {
4 ✔
2074
  QDir checkDir(dir);
4 ✔
2075
  if (!checkDir.exists()) {
4 ✔
2076
    PlainMessageBox::critical(this, tr("Error"),
2 ✔
2077
                              tr("Directory does not exist: %1").arg(dir));
2 ✔
2078
    return;
1 ✔
2079
  }
2080
  if (refuseLinkedFolder(dir)) {
3 ✔
2081
    return;
2082
  }
2083

2084
  const bool yes = PlainMessageBox::askYes(
3 ✔
2085
      this, tr("Re-encrypt passwords"),
3 ✔
2086
      tr("Re-encrypt all passwords in %1?\n\n"
3 ✔
2087
         "This will re-encrypt ALL password files in this folder "
2088
         "using the current recipients defined in .gpg-id.\n\n"
2089
         "This may rewrite many files and cannot be undone easily.\n\n"
2090
         "Continue?")
2091
          // On one line: a name with line feeds pushed the warning out of
2092
          // the box, which shows 40 lines at most.
2093
          .arg(Util::displayable(QDir(dir).dirName(), false)));
6 ✔
2094

2095
  if (!yes)
3 ✔
2096
    return;
2097

2098
  // Disable now; the asynchronous startReencryptPath signal re-runs this
2099
  // harmlessly.
2100
  startReencryptPath();
1 ✔
2101

2102
  // Under the current profile's settings: with the pass backend active, the
2103
  // native one is not re-initialised on a profile switch.
2104
  QtPassSettings::getImitatePass()->reencryptPath(
2 ✔
2105
      QDir::cleanPath(QDir(dir).absolutePath()), QtPassSettings::load());
2 ✔
2106
}
4 ✔
2107

2108
// Idempotent: reencryptPath() calls it before ImitatePass emits the signal.
2109
void MainWindow::startReencryptPath() {
7 ✔
2110
  m_reencryptRunning = true;
7 ✔
2111
  setUiElementsEnabled(false);
7 ✔
2112
  // The worker always ends with endReencryptPath(), and Cancel is available
2113
  // throughout, so the generic watchdog is not needed for this operation.
2114
  m_uiWatchdog.stop();
7 ✔
2115
  ui->treeView->setDisabled(true);
7 ✔
2116
  if (m_reencryptProgress)
7 ✔
2117
    return;
2118
  auto *progress = new QProgressDialog(tr("Re-encrypting passwords..."),
5 ✔
2119
                                       tr("Cancel"), 0, 0, this);
10 ✔
2120
  progress->setWindowTitle(tr("Re-encrypt passwords"));
5 ✔
2121
  progress->setWindowModality(Qt::WindowModal);
5 ✔
2122
  progress->setAutoClose(false);
5 ✔
2123
  progress->setAutoReset(false);
5 ✔
2124
  progress->setMinimumDuration(0);
5 ✔
2125
  connect(progress, &QProgressDialog::canceled, this, [this]() {
5 ✔
2126
    QtPassSettings::getImitatePass()->cancelReencryptPath();
1 ✔
2127
    showStatusMessage(tr("Cancelling re-encryption"), 5000);
1 ✔
2128
  });
1 ✔
2129
  m_reencryptProgress = progress;
2130
  progress->show();
5 ✔
2131
}
2132

2133
void MainWindow::reencryptProgress(int current, int total) {
7 ✔
2134
  if (!m_reencryptProgress || m_inProgressUpdate)
7 ✔
2135
    return;
2136
  QProgressDialog *progress = m_reencryptProgress;
2137
  progress->setMaximum(total);
6 ✔
2138
  progress->setLabelText(
6 ✔
2139
      tr("Re-encrypting passwords: %1 of %2").arg(current).arg(total));
6 ✔
2140
  // On a modal dialog setValue() runs processEvents(), which can deliver
2141
  // endReencryptPath(), even inside a nested event loop that would delete a
2142
  // deleteLater()ed dialog under setValue()'s feet: keep this last, and
2143
  // delete the dialog only after it returns.
2144
  m_inProgressUpdate = true;
6 ✔
2145
  progress->setValue(current);
6 ✔
2146
  m_inProgressUpdate = false;
6 ✔
2147
  if (m_progressToDelete) {
6 ✔
2148
    m_progressToDelete->deleteLater();
2 ✔
2149
    m_progressToDelete = nullptr;
2150
  }
2151
}
2152

2153
void MainWindow::endReencryptPath() {
5 ✔
2154
  m_reencryptRunning = false;
5 ✔
2155
  if (m_reencryptProgress) {
5 ✔
2156
    m_reencryptProgress->hide();
5 ✔
2157
    if (m_inProgressUpdate) {
5 ✔
2158
      m_progressToDelete = m_reencryptProgress;
2159
    } else {
2160
      m_reencryptProgress->deleteLater();
3 ✔
2161
    }
2162
    m_reencryptProgress = nullptr;
2163
  }
2164
  setUiElementsEnabled(true);
5 ✔
2165
}
5 ✔
2166

2167
void MainWindow::exportPublicKey() {
3 ✔
2168
  const AppSettings s = QtPassSettings::load();
3 ✔
2169
  const QString identity = s.passSigningKey;
2170
  if (identity.isEmpty()) {
3 ✔
2171
    QMessageBox::information(
2 ✔
2172
        this, tr("Export public key"),
1 ✔
2173
        tr("<h3>Export your public key</h3>"
×
2174
           "<p>No signing key is configured. Set one in QtPass Settings "
2175
           "&gt; GPG keys, or run this in a terminal:</p>"
2176
           "<pre>gpg --armor --export --output my_key.asc &lt;your-key-id"
2177
           "&gt;</pre>"
2178
           "<p>Then send the file to your teammates.</p>"));
2179
    return;
1 ✔
2180
  }
2181
  QString gpgExe = s.gpgExecutable;
2182
  if (gpgExe.isEmpty()) {
2 ✔
2183
    gpgExe = QStringLiteral("gpg");
×
2184
  }
2185
  QStringList args = {"--armor", "--export"};
10 ✔
2186
  args.append(identity.split(' ', Qt::SkipEmptyParts));
2 ✔
2187
  QString stdOut;
2 ✔
2188
  QString stdErr;
2 ✔
2189
  int exitCode = Executor::executeBlocking(gpgExe, args, &stdOut, &stdErr);
2 ✔
2190
  if (exitCode != 0 || stdOut.isEmpty()) {
2 ✔
2191
    PlainMessageBox::warning(this, tr("Export public key"),
2 ✔
2192
                             tr("Could not export public key for %1.\n\n%2")
1 ✔
2193
                                 .arg(identity, stdErr.isEmpty()
2 ✔
2194
                                                    ? tr("No output from gpg.")
2 ✔
2195
                                                    : stdErr));
2196
    return;
2197
  }
2198
  ExportPublicKeyDialog dialog(identity, stdOut, this);
1 ✔
2199
  dialog.exec();
1 ✔
2200
}
4 ✔
2201

2202
// UsersDialog only ticks keys already in the keyring; importing a foreign
2203
// key still has to happen via gpg (or QtPass settings) first.
2204
void MainWindow::addRecipient(const QString &dir) {
2 ✔
2205
  if (refuseLinkedFolder(dir)) {
2 ✔
2206
    return;
1 ✔
2207
  }
2208
  UsersDialog d(QtPassSettings::getPass(), QtPassSettings::load(), dir, this);
1 ✔
2209
  d.exec();
1 ✔
2210
}
1 ✔
2211

2212
// A tree-picked folder that is, or lies behind, a symlink or junction is not
2213
// a folder of the store. The store root itself may be a link (a synced
2214
// folder); that is configuration, not a tree pick.
2215
auto MainWindow::refuseLinkedFolder(const QString &dir) -> bool {
20 ✔
2216
  if (!Util::isUnderLink(dir, QtPassSettings::load().passStore)) {
20 ✔
2217
    return false;
2218
  }
2219
  PlainMessageBox::critical(
3 ✔
2220
      this, tr("Not a folder of the store"),
3 ✔
2221
      tr("%1 is, or lies behind, a symbolic link or junction. What that "
3 ✔
2222
         "points to is not part of the password store and is left alone.")
2223
          .arg(QDir::toNativeSeparators(QDir::cleanPath(dir))));
6 ✔
2224
  return true;
3 ✔
2225
}
2226

2227
void MainWindow::showShareHelp() {
1 ✔
2228
  QMessageBox::information(
2 ✔
2229
      this, tr("Sharing passwords with GPG"),
1 ✔
2230
      tr("<h3>Sharing passwords with GPG</h3>"
1 ✔
2231
         "<p>To share passwords with other users:</p>"
2232
         "<ol>"
2233
         "<li><b>Export your public key</b> and send it to teammates</li>"
2234
         "<li><b>Import teammates' public keys</b> into your GPG keyring</li>"
2235
         "<li><b>Re-encrypt passwords</b> so all recipients can decrypt "
2236
         "them</li>"
2237
         "</ol>"
2238
         "<p>Only people who have a matching secret key can decrypt the "
2239
         "passwords.</p>"
2240
         "<p><b>Tip:</b> Use the same GPG key for all shared folders.</p>"
2241
         "<p>See the FAQ for more details.</p>"));
2242
}
1 ✔
2243

2244
void MainWindow::updateGitButtonVisibility(bool uiEnabled) {
428 ✔
2245
  const AppSettings s = QtPassSettings::load();
428 ✔
2246
  // Without Git there is nothing to push or pull, ever: the buttons go, not
2247
  // grey out. While an operation runs they stay and are disabled.
2248
  const bool usable =
2249
      s.useGit && !(s.gitExecutable.isEmpty() && s.passExecutable.isEmpty());
428 ✔
2250
  ui->actionPush->setVisible(usable);
428 ✔
2251
  ui->actionUpdate->setVisible(usable);
428 ✔
2252
  // The separator in front of them would otherwise sit next to the next one.
2253
  const QList<QAction *> actions = ui->toolBar->actions();
428 ✔
2254
  const qsizetype at = actions.indexOf(ui->actionPush);
428 ✔
2255
  if (at > 0 && actions.at(at - 1)->isSeparator()) {
428 ✔
2256
    actions.at(at - 1)->setVisible(usable);
428 ✔
2257
  }
2258
  enableGitButtons(usable && uiEnabled);
428 ✔
2259
}
428 ✔
2260

2261
void MainWindow::updateOtpButtonVisibility(bool uiEnabled) {
434 ✔
2262
  // No platform gating: codes are generated in-process. Visible but disabled
2263
  // when OTP is off: the panel never shows an OTP field (a secret), so hiding
2264
  // this too would leave no trace of the feature. Honour uiEnabled, or the
2265
  // user can stack Show calls while a decrypt is in flight.
2266
  ui->actionOtp->setVisible(true);
434 ✔
2267
  ui->actionOtp->setEnabled(QtPassSettings::isUseOtp() && uiEnabled);
540 ✔
2268
}
434 ✔
2269

2270
void MainWindow::updateGrepButtonVisibility() {
192 ✔
2271
  const bool enabled = QtPassSettings::isUseGrepSearch();
192 ✔
2272
  ui->grepButton->setVisible(enabled);
192 ✔
2273
  ui->grepCaseButton->setVisible(enabled);
192 ✔
2274
  if (!enabled && m_grep.inGrepMode()) {
192 ✔
2275
    ui->grepButton->setChecked(false);
1 ✔
2276
  }
2277
}
192 ✔
2278

2279
void MainWindow::enableGitButtons(const bool &state) {
428 ✔
2280
  ui->actionPush->setEnabled(state);
428 ✔
2281
  ui->actionUpdate->setEnabled(state);
428 ✔
2282
}
428 ✔
2283

2284
void MainWindow::critical(const QString &title, const QString &msg) {
4 ✔
2285
  // Pass's messages quote store paths; see PlainMessageBox.
2286
  PlainMessageBox::critical(this, title, msg);
4 ✔
2287
}
4 ✔
2288

2289
void MainWindow::onProcessOutput(const QString &output, bool isError,
7 ✔
2290
                                 Enums::PROCESS pid) {
2291
  if (!QtPassSettings::isShowProcessOutput()) {
7 ✔
2292
    return;
2293
  }
2294
  m_processOutput->append(output, isError,
6 ✔
2295
                          ProcessOutputPanel::processName(pid));
12 ✔
2296
}
2297

2298
void MainWindow::updateProcessOutputVisibility() {
5 ✔
2299
  // The action's toggled handler shows or hides the dock.
2300
  ui->actionShowProcessOutput->setChecked(
5 ✔
2301
      QtPassSettings::isShowProcessOutput());
5 ✔
2302
  m_processOutput->setVisible(QtPassSettings::isShowProcessOutput());
5 ✔
2303
}
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