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

IJHack / QtPass / 45492193480

24 Nov 2026 09:32PM UTC coverage: 94.76% (-0.02%) from 94.784%
45492193480

push

github

web-flow
Key generation: no unprotected key from half an emoji (#2324)

KeygenDialog::applyPassphrase() and replace() cut the batch into lines
with Util::newLinesRegex(). QRegularExpression matches nothing in text
that is not valid UTF-16, so one lone surrogate anywhere (half of an
emoji, pasted in-process or from a UTF-16 clipboard) left the batch one
"line": %no-protection stayed, and Passphrase: went after %commit. gpg
created the key unprotected, then failed on the trailing line.

The batch is now split at CR and LF characters, without a regex.
isBatchValue() also refuses text that is not valid UTF-16, so such a
name stays out of the template, and OK refuses such a name or
passphrase with its own message.

Scan: ANT-2026-NBW31RDB

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

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

6 existing lines in 1 file now uncovered.

9892 of 10439 relevant lines covered (94.76%)

20699.39 hits per line

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

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

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

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

97
  initTextBrowser();
197 ✔
98

99
  updateProfileBox();
197 ✔
100

101
  initDisplayPanel();
197 ✔
102

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

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

113
  initTimers();
197 ✔
114

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

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

122
  setUiElementsEnabled(true);
197 ✔
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();
197 ✔
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())) {
198 ✔
130
    if (!config()) {
2 ✔
131
      return;
132
    }
133
  }
134
  // Set up, with or without the wizard (a fresh install can find a store
135
  // that already works): a later run of the wizard keeps the saved backend
136
  // and Git choices. A cancelled first run returned above and keeps it.
137
  QtPassSettings::getInstance()->remove(SettingsConstants::firstRunPending);
196 ✔
138
  m_freshStart = false;
196 ✔
139
  m_initSucceeded = true;
196 ✔
140

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

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

156
void MainWindow::connectBackends() {
197 ✔
157
  connect(m_qtPass, &QtPass::outputReady, this,
197 ✔
158
          [this](const QString &html) { flashText(html, false, true); });
239 ✔
159
  connect(m_qtPass, &QtPass::operationFinished, this,
197 ✔
160
          [this]() { setUiElementsEnabled(true); });
261 ✔
161
  connect(m_qtPass, &QtPass::statusMessage, this,
197 ✔
162
          &MainWindow::showStatusMessage);
197 ✔
163
  connect(m_qtPass, &QtPass::pushRequested, this, &MainWindow::onAutoPush);
197 ✔
164
  // With automatic push, the push is queued first and the refresh would start
165
  // as soon as it ends, emptying the browser before a failed push's error was
166
  // painted. So the refresh waits for the push (see connectPassSignals()). It
167
  // claims the panel now, as its decrypt would: whatever drops a pending
168
  // decrypt (another entry, a search, Escape, Edit, an error) drops it too.
169
  connect(m_qtPass, &QtPass::entryInserted, this, [this]() {
197 ✔
170
    const QModelIndex index = getCurrentTreeViewIndex();
11 ✔
171
    const QString file = getFile(index, true);
11 ✔
172
    Pass *pass = QtPassSettings::getPass();
11 ✔
173
    // Only the entry the save wrote is shown again, when it is the selected
174
    // one. After Add, or a save that reports once another row is selected,
175
    // the selected row is another entry: showing it decrypted it once more
176
    // and, with "Always copy", put its password on the clipboard.
177
    if (const QString saved = pass->reportedInsert();
11 ✔
178
        !saved.isEmpty() &&
14 ✔
179
        QDir::cleanPath(saved) != QDir::cleanPath(getFile(index, false))) {
20 ✔
180
      return;
181
    }
182
    if (!file.isEmpty() && pass->isPushing()) {
20 ✔
183
      m_refreshAfterPush = file;
8 ✔
184
      m_refreshAfterPushOwner = pass;
8 ✔
185
      m_shownFile = file;
8 ✔
186
      return;
8 ✔
187
    }
188
    on_treeView_clicked(index);
2 ✔
189
  });
190
  connect(&m_qtPass->clipboard(), &ClipboardManager::statusMessage, this,
197 ✔
191
          [this](const QString &message) { showStatusMessage(message); });
220 ✔
192
  // Both backends: the active one can change through the configuration
193
  // dialog without a restart.
194
  connectPassSignals(QtPassSettings::getRealPass());
197 ✔
195
  connectPassSignals(QtPassSettings::getImitatePass());
197 ✔
196
  ImitatePass *ipass = QtPassSettings::getImitatePass();
197 ✔
197
  connect(ipass, &ImitatePass::startReencryptPath, this,
197 ✔
198
          &MainWindow::startReencryptPath);
197 ✔
199
  connect(ipass, &ImitatePass::reencryptProgress, this,
197 ✔
200
          &MainWindow::reencryptProgress);
197 ✔
201
  connect(ipass, &ImitatePass::endReencryptPath, this,
197 ✔
202
          &MainWindow::endReencryptPath);
197 ✔
203
}
197 ✔
204

205
void MainWindow::initTextBrowser() {
197 ✔
206
  {
207
    const AppSettings s = QtPassSettings::load();
197 ✔
208
    if (s.useMonospace) {
197 ✔
209
      QFont monospace("Monospace");
1 ✔
210
      monospace.setStyleHint(QFont::Monospace);
1 ✔
211
      ui->textBrowser->setFont(monospace);
1 ✔
212
    }
1 ✔
213
    if (s.noLineWrapping) {
197 ✔
214
      ui->textBrowser->setLineWrapMode(QTextBrowser::NoWrap);
1 ✔
215
    }
216
    clearPanelTimer.setInterval(MS_PER_SECOND * s.autoclearPanelSeconds);
197 ✔
217
    clearResultsTimer.setInterval(clearPanelTimer.interval());
197 ✔
218
  }
197 ✔
219
  ui->textBrowser->setOpenExternalLinks(true);
197 ✔
220
  ui->textBrowser->setContextMenuPolicy(Qt::CustomContextMenu);
197 ✔
221
  connect(ui->textBrowser, &QWidget::customContextMenuRequested, this,
197 ✔
222
          &MainWindow::showBrowserContextMenu);
197 ✔
223
}
197 ✔
224

225
void MainWindow::initDisplayPanel() {
197 ✔
226
  m_displayPanel = new PasswordDisplayPanel(
197 ✔
227
      ui->gridLayout, ui->verticalLayoutPassword, this, this);
197 ✔
228
  connect(m_displayPanel, &PasswordDisplayPanel::copyRequested,
197 ✔
229
          &m_qtPass->clipboard(), &ClipboardManager::copyText);
197 ✔
230
  connect(m_displayPanel, &PasswordDisplayPanel::textCopied,
197 ✔
231
          &m_qtPass->clipboard(), &ClipboardManager::trackCopied);
197 ✔
232
  connect(ui->textBrowser, &SecretTextBrowser::copied, &m_qtPass->clipboard(),
197 ✔
233
          &ClipboardManager::trackCopied);
197 ✔
234
  connect(m_displayPanel, &PasswordDisplayPanel::qrRequested, m_qtPass,
197 ✔
235
          &QtPass::showTextAsQRCode);
197 ✔
236
  // Double-click on what is shown edits it, as in the tree.
237
  // The entry whose rows were double-clicked, not the tree's current row:
238
  // arrow keys and a right-click move that row without repainting the panel.
239
  connect(m_displayPanel, &PasswordDisplayPanel::editRequested, this, [this] {
197 ✔
240
    if (ui->actionEdit->isEnabled() && !m_panelEntry.isEmpty()) {
4 ✔
241
      editPassword(m_panelEntry);
3 ✔
242
    }
243
  });
4 ✔
244
}
197 ✔
245

246
void MainWindow::initTimers() {
197 ✔
247
  clearPanelTimer.setSingleShot(true);
197 ✔
248
  connect(&clearPanelTimer, &QTimer::timeout, this,
197 ✔
249
          [this]() { clearShownEntry(true); });
199 ✔
250
  clearResultsTimer.setSingleShot(true);
197 ✔
251
  connect(&clearResultsTimer, &QTimer::timeout, this,
197 ✔
252
          &MainWindow::clearContentResults);
197 ✔
253

254
  searchTimer.setInterval(350);
197 ✔
255
  searchTimer.setSingleShot(true);
197 ✔
256

257
  connect(&searchTimer, &QTimer::timeout, this, &MainWindow::onTimeoutSearch);
197 ✔
258

259
  // Safety net: if a backend operation disables the UI but never signals
260
  // completion, re-enable after a timeout so the window can't get stuck.
261
  m_uiWatchdog.setSingleShot(true);
197 ✔
262
  m_uiWatchdog.setInterval(UiWatchdogMs);
197 ✔
263
  connect(&m_uiWatchdog, &QTimer::timeout, this, [this]() {
197 ✔
264
    showStatusMessage(tr("Operation timed out; re-enabling interface."));
×
265
    // Drop any in-flight OTP request so a late finishedShow cannot be mistaken
266
    // for the answer to it.
267
    cancelOtpRequest();
×
268
    setUiElementsEnabled(true);
×
269
  });
×
270
}
197 ✔
271

272
void MainWindow::initProcessOutput() {
197 ✔
273
  m_processOutput = new ProcessOutputPanel(this);
197 ✔
274
  addDockWidget(Qt::BottomDockWidgetArea, m_processOutput);
197 ✔
275
  // After addDockWidget so our preference wins over any cached state
276
  // QMainWindow applies; restoreWindow() already processed the saved layout.
277
  m_processOutput->setVisible(QtPassSettings::isShowProcessOutput());
197 ✔
278
  // From the setting, not isVisible(): the window is not shown yet, so no
279
  // child of it reports visible.
280
  ui->actionShowProcessOutput->setChecked(
197 ✔
281
      QtPassSettings::isShowProcessOutput());
197 ✔
282
  connect(ui->actionShowProcessOutput, &QAction::toggled, this,
197 ✔
283
          [this](bool show) {
197 ✔
284
            m_processOutput->setVisible(show);
2 ✔
285
            AppSettings s = QtPassSettings::load();
2 ✔
286
            if (s.showProcessOutput != show) {
2 ✔
287
              s.showProcessOutput = show;
2 ✔
288
              QtPassSettings::save(s);
2 ✔
289
            }
290
          });
2 ✔
291

292
  connect(QtPassSettings::getPass(), &Pass::finishedAnyWithPid, this,
197 ✔
293
          [this](const QString &out, const QString &err, Enums::PROCESS pid) {
197 ✔
294
            // Never route potentially-secret output through the panel:
295
            // PASS_SHOW goes to the text browser (cleared on a timer when
296
            // "Autoclear panel" is set),
297
            // PASS_GREP would return password-file lines (#252; it is no
298
            // longer started, the check stays), and PASS_INSERT
299
            // is excluded defensively in case a future path uses --echo.
300
            if (ProcessOutputPanel::isSensitiveProcess(pid)) {
14 ✔
301
              return;
302
            }
303
            if (!out.isEmpty()) {
13 ✔
304
              onProcessOutput(out, false, pid);
1 ✔
305
            }
306
            if (!err.isEmpty()) {
13 ✔
307
              onProcessOutput(err, true, pid);
4 ✔
308
            }
309
          });
310
}
197 ✔
311

312
MainWindow::~MainWindow() {
390 ✔
313
  // Quit from the tray menu or a SIGTERM never delivers closeEvent(); the
314
  // window still knows its last geometry here.
315
  saveWindowState();
197 ✔
316
  delete m_qtPass;
197 ✔
317
}
587 ✔
318

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

358
// Idempotent; called from closeEvent() and the destructor.
359
void MainWindow::saveWindowState() {
201 ✔
360
  QtPassSettings::setGeometry(saveGeometry());
201 ✔
361
  QtPassSettings::setSavestate(saveState());
201 ✔
362
}
201 ✔
363

364
void MainWindow::focusInput() {
76 ✔
365
  // findChild() rather than ui->lineEdit: on a fresh-config first launch
366
  // config() calls setWindowFlags(), which rebuilds the native window, and
367
  // under Qt 6.11 the QLineEdit was destroyed while ui->lineEdit kept its old
368
  // address (SIGSEGV in QWidget::testAttribute). findChild() returns null.
369
  if (!isVisible()) {
76 ✔
370
    return;
371
  }
372
  auto *lineEdit = findChild<QLineEdit *>(QStringLiteral("lineEdit"));
76 ✔
373
  if (lineEdit == nullptr || !lineEdit->isVisible()) {
76 ✔
374
    return;
375
  }
376
  lineEdit->selectAll();
76 ✔
377
  lineEdit->setFocus();
76 ✔
378
  // Only once focus has landed: set in showEvent(), an early return above
379
  // would consume the one-shot and never retry.
380
  m_firstShowCompleted = true;
76 ✔
381
}
382

383
auto MainWindow::event(QEvent *event) -> bool {
9,054 ✔
384
  if (event->type() == QEvent::ApplicationPaletteChange) {
9,054 ✔
385
    m_themeSwitched = true;
11 ✔
386
    // Breeze may re-stamp the bars before this arrives (Plasma 6 does):
387
    // their PaletteChange then found no switch yet, so check them now too.
388
    QTimer::singleShot(0, this, &MainWindow::dropStaleToolsAreaPalettes);
11 ✔
389
  }
390
  return QMainWindow::event(event);
9,054 ✔
391
}
392

393
void MainWindow::changeEvent(QEvent *event) {
263 ✔
394
  QWidget::changeEvent(event);
263 ✔
395
  if (event->type() == QEvent::PaletteChange && m_displayPanel != nullptr) {
263 ✔
396
    // Desktop switched light/dark. Top-level widgets get PaletteChange
397
    // (ApplicationPaletteChange goes to QApplication); stylesheets with
398
    // baked-in palette colours must be re-derived by hand.
399
    m_displayPanel->refreshPalette();
10 ✔
400
  }
401
  if (event->type() == QEvent::ActivationChange && isActiveWindow() &&
263 ✔
402
      isVisible()) {
403
    // Defer a tick so the activation dispatch chain unwinds first: calling
404
    // focusInput() inline has segfaulted on half-rebuilt ui state.
405
    QMetaObject::invokeMethod(this, &MainWindow::focusInput,
44 ✔
406
                              Qt::QueuedConnection);
407
  }
408
}
263 ✔
409

410
void MainWindow::showEvent(QShowEvent *event) {
46 ✔
411
  QMainWindow::showEvent(event);
46 ✔
412
  if (m_firstShowCompleted) {
46 ✔
413
    return;
414
  }
415
  // Queued so the platform map and pending rebuilds (setWindowFlags on the
416
  // wizard path) settle first. focusInput() sets the latch only on success,
417
  // so a failed lookup retries on the next show.
418
  QMetaObject::invokeMethod(this, &MainWindow::focusInput,
44 ✔
419
                            Qt::QueuedConnection);
420
}
421

422
void MainWindow::initToolBarButtons() {
197 ✔
423
  connect(ui->actionAddPassword, &QAction::triggered, this,
197 ✔
424
          &MainWindow::addPassword);
197 ✔
425
  connect(ui->actionAddFolder, &QAction::triggered, this,
197 ✔
426
          &MainWindow::addFolder);
197 ✔
427
  connect(ui->actionEdit, &QAction::triggered, this, &MainWindow::onEdit);
197 ✔
428
  connect(ui->actionDelete, &QAction::triggered, this, &MainWindow::onDelete);
197 ✔
429
  connect(ui->actionPush, &QAction::triggered, this, &MainWindow::onPush);
197 ✔
430
  connect(ui->actionUpdate, &QAction::triggered, this, &MainWindow::onUpdate);
197 ✔
431
  connect(ui->actionUsers, &QAction::triggered, this, &MainWindow::onUsers);
197 ✔
432
  connect(ui->actionConfig, &QAction::triggered, this, &MainWindow::onConfig);
197 ✔
433
  connect(ui->actionOtp, &QAction::triggered, this, &MainWindow::onOtp);
197 ✔
434

435
  // Menu-only. Quit ends the application, tray icon or not, as in KeePassXC,
436
  // Telegram and the KDE, GNOME and macOS guidelines (#1788). Close is
437
  // close(), a hide when "hide on close" is set, like the X button and Alt+F4.
438
  connect(ui->actionQuit, &QAction::triggered, qApp, &QApplication::quit);
197 ✔
439
  connect(ui->actionClose, &QAction::triggered, this, &MainWindow::close);
197 ✔
440
#ifdef Q_OS_MACOS
441
  // The menu bar is the system's up there; nothing to hide.
442
  ui->actionShowMenuBar->setVisible(false);
443
#else
444
  // The action lives in the menu it hides, so it has to be on the window as
445
  // well for Ctrl+M to keep working while the bar is gone.
446
  addAction(ui->actionShowMenuBar);
197 ✔
447
  ui->actionShowMenuBar->setChecked(QtPassSettings::load().showMenuBar);
197 ✔
448
  menuBar()->setVisible(ui->actionShowMenuBar->isChecked());
197 ✔
449
  connect(ui->actionShowMenuBar, &QAction::toggled, this, [this](bool show) {
197 ✔
450
    menuBar()->setVisible(show);
5 ✔
451
    AppSettings s = QtPassSettings::load();
5 ✔
452
    s.showMenuBar = show;
5 ✔
453
    QtPassSettings::save(s);
5 ✔
454
  });
5 ✔
455
  new MenuBarPeek(this, ui->actionShowMenuBar);
197 ✔
456
#endif
457
  connect(ui->actionFaq, &QAction::triggered, this, [] {
198 ✔
458
    QDesktopServices::openUrl(QUrl(QStringLiteral("https://qtpass.org/faq")));
2 ✔
459
  });
1 ✔
460
  connect(ui->actionAbout, &QAction::triggered, this, &MainWindow::showAbout);
197 ✔
461
  connect(ui->actionAboutQt, &QAction::triggered, qApp, &QApplication::aboutQt);
197 ✔
462

463
  ui->actionAddPassword->setIcon(
197 ✔
464
      QIcon::fromTheme("document-new", QIcon(":/icons/document-new.svg")));
788 ✔
465
  ui->actionAddFolder->setIcon(
197 ✔
466
      QIcon::fromTheme("folder-new", QIcon(":/icons/folder-new.svg")));
788 ✔
467
  ui->actionEdit->setIcon(QIcon::fromTheme(
197 ✔
468
      "document-properties", QIcon(":/icons/document-properties.svg")));
591 ✔
469
  ui->actionDelete->setIcon(
197 ✔
470
      QIcon::fromTheme("edit-delete", QIcon(":/icons/edit-delete.svg")));
788 ✔
471
  ui->actionPush->setIcon(
197 ✔
472
      QIcon::fromTheme("go-up", QIcon(":/icons/go-top.svg")));
788 ✔
473
  ui->actionUpdate->setIcon(
197 ✔
474
      QIcon::fromTheme("go-down", QIcon(":/icons/go-bottom.svg")));
788 ✔
475
  ui->actionUsers->setIcon(QIcon::fromTheme(
197 ✔
476
      "x-office-address-book", QIcon(":/icons/x-office-address-book.svg")));
591 ✔
477
  ui->actionConfig->setIcon(QIcon::fromTheme(
197 ✔
478
      "applications-system", QIcon(":/icons/applications-system.svg")));
394 ✔
479
}
197 ✔
480

481
void MainWindow::initStatusBar() {
197 ✔
482
  ui->statusBar->showMessage(tr("Welcome to QtPass %1").arg(VERSION), 2000);
394 ✔
483

484
  QPixmap logo = QPixmap::fromImage(QImage(":/artwork/icon.svg"))
394 ✔
485
                     .scaledToHeight(statusBar()->height());
197 ✔
486
  auto *logoApp = new QLabel(statusBar());
197 ✔
487
  logoApp->setPixmap(logo);
197 ✔
488
  statusBar()->addPermanentWidget(logoApp);
197 ✔
489
}
197 ✔
490

491
auto MainWindow::getCurrentTreeViewIndex() -> QModelIndex {
11 ✔
492
  return ui->treeView->currentIndex();
11 ✔
493
}
494

495
void MainWindow::flashText(const QString &text, const bool isError,
94 ✔
496
                           const bool isHtml) {
497
  // setText() applies the current char format to the whole message. Start
498
  // from an empty one: inherited from a cursor on a linkified URL it carried
499
  // the anchor, and the message became a link to that address. No colour
500
  // but red for an error, so text follows runtime light/dark switches (#946).
501
  QTextCursor cursor = ui->textBrowser->textCursor();
94 ✔
502
  cursor.clearSelection();
94 ✔
503
  ui->textBrowser->setTextCursor(cursor);
94 ✔
504
  QTextCharFormat format;
94 ✔
505
  if (isError) {
94 ✔
506
    format.setForeground(QColor(Qt::red));
11 ✔
507
  }
508
  ui->textBrowser->setCurrentCharFormat(format);
94 ✔
509

510
  // Wrapped at word boundaries, a run of hundreds of thousands of letters
511
  // took Qt seconds to minutes; anywhere, it is linear. Anywhere while the
512
  // text goes in, then word wrap back unless what is shown has such a run:
513
  // markup (a link's "<a href") splits a run in the source, not on screen.
514
  ui->textBrowser->setWordWrapMode(QTextOption::WrapAnywhere);
94 ✔
515
  if (isHtml) {
94 ✔
516
    QString _text = text;
517
    if (!ui->textBrowser->toPlainText().isEmpty()) {
154 ✔
518
      _text = ui->textBrowser->toHtml() + _text;
42 ✔
519
    }
520
    ui->textBrowser->setHtml(_text);
77 ✔
521
  } else {
522
    ui->textBrowser->setText(text);
17 ✔
523
  }
524
  // The raw text: toPlainText() turns a no-break space into a plain one.
525
  if (!Util::hasLongUnbrokenRun(ui->textBrowser->document()->toRawText())) {
188 ✔
526
    ui->textBrowser->setWordWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
90 ✔
527
  }
528
}
94 ✔
529

530
void MainWindow::applyTextBrowserSettings() {
5 ✔
531
  const AppSettings s = QtPassSettings::load();
5 ✔
532
  if (s.useMonospace) {
5 ✔
533
    QFont monospace("Monospace");
1 ✔
534
    monospace.setStyleHint(QFont::Monospace);
1 ✔
535
    ui->textBrowser->setFont(monospace);
1 ✔
536
  } else {
1 ✔
537
    ui->textBrowser->setFont(QFont());
4 ✔
538
  }
539

540
  if (s.noLineWrapping) {
5 ✔
541
    ui->textBrowser->setLineWrapMode(QTextBrowser::NoWrap);
1 ✔
542
  } else {
543
    ui->textBrowser->setLineWrapMode(QTextBrowser::WidgetWidth);
4 ✔
544
  }
545
}
5 ✔
546

547
void MainWindow::applyWindowFlagsSettings() {
213 ✔
548
  const bool wantOnTop = QtPassSettings::isAlwaysOnTop();
213 ✔
549
  const Qt::WindowFlags flags = windowFlags();
550
  if (flags.testFlag(Qt::WindowStaysOnTopHint) == wantOnTop) {
213 ✔
551
    // setWindowFlags() rebuilds the native window, the teardown that left
552
    // ui->lineEdit dangling (see focusInput()); skip it when nothing changes.
553
    return;
554
  }
555
  // Toggle just this hint; resetting to Qt::Window discarded every other flag.
556
  const bool wasVisible = isVisible();
557
  setWindowFlags(wantOnTop ? (flags | Qt::WindowStaysOnTopHint)
4 ✔
558
                           : (flags & ~Qt::WindowStaysOnTopHint));
559
  // setWindowFlags() hides a shown window; a window that was not shown yet
560
  // (first-run wizard from the constructor) is left to its normal show.
561
  if (wasVisible) {
2 ✔
562
    show();
2 ✔
563
  }
564
}
565

566
auto MainWindow::config() -> bool {
8 ✔
567
  if (m_freshStart) {
8 ✔
568
    // No usable configuration yet: the wizard finds the programs, the key
569
    // and the store, and creates the store when it has to.
570
    FirstRunWizard wizard(this);
2 ✔
571
    if (wizard.exec() != QDialog::Accepted) {
2 ✔
572
      return false;
573
    }
574
  } else {
2 ✔
575
    ConfigDialog d(this);
6 ✔
576
    d.setModal(true);
6 ✔
577
    if (d.exec() != QDialog::Accepted) {
6 ✔
578
      return false;
579
    }
580
  }
6 ✔
581

582
  applyTextBrowserSettings();
5 ✔
583
  applyWindowFlagsSettings();
5 ✔
584

585
  updateProfileBox();
5 ✔
586
  const AppSettings s = QtPassSettings::load();
5 ✔
587
  // An open still waiting for the tree was asked of the old view; once
588
  // re-rooted, it would find that name in the new store. A profile switch
589
  // ends it by clearing the search text.
590
  delete m_pendingOpen;
5 ✔
591
  // A content search still running searched the old store, and its matches
592
  // would be listed for this one: onGrepFinished() cannot tell. Cancelled,
593
  // and content-search results on screen go with it (clearPanel()).
594
  cancelContentSearch();
5 ✔
595
  if (m_grep.cancelSearch()) {
596
    QApplication::restoreOverrideCursor();
1 ✔
597
  }
598
  clearPanel(false);
5 ✔
599
  m_tree->setStore(s.passStore);
5 ✔
600
  deselect();
5 ✔
601
  ui->treeView->setCurrentIndex(QModelIndex());
5 ✔
602

603
  Pass *activePass = QtPassSettings::getPass();
5 ✔
604
  activePass->updateEnv();
5 ✔
605
  m_tree->setPass(activePass);
5 ✔
606
  clearPanelTimer.setInterval(MS_PER_SECOND * s.autoclearPanelSeconds);
5 ✔
607
  clearResultsTimer.setInterval(clearPanelTimer.interval());
5 ✔
608
  m_qtPass->clipboard().setAutoclearTimer();
5 ✔
609

610
  updateGitButtonVisibility();
5 ✔
611
  updateOtpButtonVisibility();
5 ✔
612
  updateGrepButtonVisibility();
5 ✔
613
  updateProcessOutputVisibility();
5 ✔
614
#ifndef Q_OS_MACOS
615
  // The action's toggled handler shows or hides the bar (and saves again).
616
  ui->actionShowMenuBar->setChecked(s.showMenuBar);
5 ✔
617
#endif
618
  if (s.useTrayIcon && m_tray == nullptr) {
5 ✔
619
    initTrayIcon();
1 ✔
620
  } else if (!s.useTrayIcon && m_tray != nullptr) {
4 ✔
621
    destroyTrayIcon();
×
622
  }
623

624
  // Stay fresh-start while the configuration is unusable, so the
625
  // constructor's loop re-runs the wizard. The re-prompt lives there:
626
  // recursing here never reported a cancel back to the caller.
627
  if (Util::configIsValid(s)) {
5 ✔
628
    m_freshStart = false;
5 ✔
629
  }
630
  return true;
631
}
5 ✔
632

633
void MainWindow::onUpdate(bool block) {
2 ✔
634
  ui->statusBar->showMessage(tr("Updating password-store"), 2000);
2 ✔
635
  if (block) {
2 ✔
636
    QtPassSettings::getPass()->GitPull_b(Pass::kBlockingPullMs);
1 ✔
637
  } else {
638
    QtPassSettings::getPass()->GitPull();
1 ✔
639
  }
640
}
2 ✔
641

642
void MainWindow::onPush() {
1 ✔
643
  if (QtPassSettings::isUseGit()) {
1 ✔
644
    ui->statusBar->showMessage(tr("Updating password-store"), 2000);
1 ✔
645
    QtPassSettings::getPass()->GitPush();
1 ✔
646
  }
647
}
1 ✔
648

649
void MainWindow::onAutoPush() {
8 ✔
650
  if (QtPassSettings::isUseGit()) {
8 ✔
651
    ui->statusBar->showMessage(tr("Updating password-store"), 2000);
8 ✔
652
    QtPassSettings::getPass()->GitPushAutomatic();
8 ✔
653
  }
654
}
8 ✔
655

656
auto MainWindow::getFile(const QModelIndex &index, bool forPass) -> QString {
68 ✔
657
  return m_tree->fileFor(index, forPass);
68 ✔
658
}
659

660
void MainWindow::on_treeView_clicked(const QModelIndex &index) {
27 ✔
661
  bool cleared = ui->treeView->currentIndex().flags() == Qt::NoItemFlags;
27 ✔
662
  QString file = getFile(index, true);
27 ✔
663
  ui->passwordName->setText(Util::shownName(file));
54 ✔
664
  if (!file.isEmpty() && !cleared) {
27 ✔
665
    // Remember what the panel is about to show, so onOtp() can tell whether the
666
    // code it can see belongs to the entry that is currently selected.
667
    m_shownFile = file;
26 ✔
668
    QtPassSettings::getPass()->Show(file);
52 ✔
669
  } else {
670
    m_shownFile.clear();
1 ✔
671
    clearPanel(false);
1 ✔
672
    ui->actionEdit->setEnabled(false);
1 ✔
673
    ui->actionDelete->setEnabled(true);
1 ✔
674
  }
675
}
27 ✔
676

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

680
  if (fileOrFolder.isFile()) {
4 ✔
681
    editPassword(getFile(index, true));
6 ✔
682
  }
683
}
4 ✔
684

685
void MainWindow::deselect() {
19 ✔
686
  m_shownFile.clear();
19 ✔
687
  cancelOtpRequest();
19 ✔
688
  m_qtPass->clipboard().clear();
19 ✔
689
  ui->treeView->clearSelection();
19 ✔
690
  // The current index too: clearSelection() keeps it, and whatever asks for
691
  // the "current" folder (Users, Add password, Add folder) took the hidden
692
  // entry it was left on, such as the first hit of a search just emptied.
693
  ui->treeView->setCurrentIndex(QModelIndex());
19 ✔
694
  ui->actionEdit->setEnabled(false);
19 ✔
695
  ui->actionDelete->setEnabled(false);
19 ✔
696
  ui->passwordName->setText("");
19 ✔
697
  clearPanel(false);
19 ✔
698
}
19 ✔
699

700
void MainWindow::executeWrapperStarted() {
71 ✔
701
  m_displayPanel->clear();
71 ✔
702
  m_panelEntry.clear();
71 ✔
703
  ui->textBrowser->clear();
71 ✔
704
  setUiElementsEnabled(false);
71 ✔
705
  clearPanelTimer.stop();
71 ✔
706
  if (QtPassSettings::isShowProcessOutput()) {
71 ✔
707
    m_processOutput->setVisible(true);
66 ✔
708
  }
709
}
71 ✔
710

711
void MainWindow::passShowHandler(const QString &p_output, const QString &file) {
42 ✔
712
  // Only the entry we most recently asked to show may repaint the panel; a
713
  // slower decrypt of an entry the user has since left is dropped, and so is
714
  // one that arrives after the selection was cleared (deselect, a profile
715
  // switch): nothing is asked to be shown then.
716
  if (!file.isEmpty() && file != m_shownFile) {
42 ✔
717
    // A newer show is pending and releases the interface when it lands;
718
    // with none (the selection was cleared) nothing else would until the
719
    // watchdog. setUiElementsEnabled() keeps a re-encryption's lock.
720
    if (m_shownFile.isEmpty()) {
10 ✔
721
      setUiElementsEnabled(true);
8 ✔
722
    }
723
    return;
10 ✔
724
  }
725
  const AppSettings s = QtPassSettings::load();
32 ✔
726
  refreshMarkedSecrets(s);
32 ✔
727
  QStringList templ =
728
      s.useTemplate ? TemplateIO::fieldsIn(s.passTemplate) : QStringList();
32 ✔
729
  bool allFields = s.useTemplate && s.templateAllFields;
32 ✔
730
  // A secret the panel hides is a field even when the template doesn't list
731
  // it: left in the text below the fields, it would show in plain view.
732
  FileContent fileContent = FileContent::parse(
733
      p_output, templ, allFields, [this, &s](const QString &name) {
32 ✔
734
        return m_displayPanel->isSecret(name, s);
19 ✔
735
      });
32 ✔
736
  QString output = p_output;
737
  // Display variant: empty when the password line is itself an otpauth URI, so
738
  // the shared secret is neither rendered nor copied to the clipboard.
739
  QString password = fileContent.getPasswordForDisplay();
32 ✔
740

741
  // Skipped for an OTP request: the user asked for a code, and two
742
  // OleSetClipboard calls in one turn can leave the Windows clipboard empty.
743
  if (m_otpRequestFile.isEmpty() || m_otpRequestFile != file) {
32 ✔
744
    m_qtPass->clipboard().copyIfAlways(password, p_output);
30 ✔
745
  }
746

747
  m_displayPanel->clear();
32 ✔
748
  m_panelEntry.clear();
32 ✔
749

750
  if (s.hideContent) {
32 ✔
751
    output = "***" + tr("Content hidden") + "***";
4 ✔
752
  } else if (s.displayAsIs) {
30 ✔
753
    // As it is, but not a block per line of millions.
754
    output = FileContent::boundedForDisplay(p_output);
4 ✔
755
  } else {
756
    m_panelEntry = file;
28 ✔
757
    m_displayPanel->displayFields(password, fileContent.getNamedValues(), s,
56 ✔
758
                                  s.useOtp ? fileContent.getOtpUri()
28 ✔
759
                                           : QString());
760
    output = fileContent.getRemainingDataForDisplay();
56 ✔
761
  }
762

763
  if (s.useAutoclearPanel) {
32 ✔
764
    clearPanelTimer.start();
3 ✔
765
  }
766

767
  // Shown as it is, the text holds the password and every secret field: no
768
  // links in it, or a click on a URL-shaped one handed it to the browser.
769
  flashText(QtPass::formatOutput(output, QString(), QString(),
64 ✔
770
                                 !s.displayAsIs || s.hideContent),
32 ✔
771
            false, true);
772
  setUiElementsEnabled(true);
32 ✔
773
}
64 ✔
774

775
void MainWindow::otpFromFileToClipboard(const QString &p_output,
31 ✔
776
                                        const QString &file) {
777
  // Permanently connected: only the decrypt of the entry onOtp() asked for
778
  // is ours, everything else belongs to a tree click or a Ctrl+C.
779
  if (m_otpRequestFile.isEmpty() || file != m_otpRequestFile) {
31 ✔
780
    return;
27 ✔
781
  }
782
  m_otpRequestFile.clear();
6 ✔
783

784
  if (p_output.isEmpty()) {
6 ✔
785
    // Distinguish "could not read the entry" from "entry has no OTP".
786
    flashText(tr("Could not decrypt this password entry"), true);
1 ✔
787
    setUiElementsEnabled(true);
1 ✔
788
    return;
1 ✔
789
  }
790

791
  // passShowHandler ran first for this finishedShow; if it rendered the OTP
792
  // row, reuse its code (as onOtp()'s fast path does). Otherwise parse:
793
  // hideContent, displayAsIs or no OTP field.
794
  const QString shown = m_displayPanel->currentOtpCode();
5 ✔
795
  if (!shown.isEmpty()) {
5 ✔
796
    m_qtPass->clipboard().copyText(shown);
1 ✔
797
    showStatusMessage(tr("OTP code copied to clipboard"));
1 ✔
798
    setUiElementsEnabled(true);
1 ✔
799
    return;
800
  }
801

802
  const AppSettings s = QtPassSettings::load();
4 ✔
803
  // Parse with the same template settings passShowHandler uses, so an OTP
804
  // field is recognised identically in both paths.
805
  const QStringList templ =
806
      s.useTemplate ? TemplateIO::fieldsIn(s.passTemplate) : QStringList();
4 ✔
807
  const bool allFields = s.useTemplate && s.templateAllFields;
4 ✔
808
  const FileContent fileContent =
809
      FileContent::parse(p_output, templ, allFields);
4 ✔
810

811
  Totp::Refusal why = Totp::Refusal::None;
4 ✔
812
  const std::optional<Totp::Settings> settings =
813
      Totp::parse(fileContent.getOtpUri(), &why);
8 ✔
814
  if (settings.has_value()) {
4 ✔
815
    m_qtPass->clipboard().copyText(Totp::generateNow(*settings));
4 ✔
816
    showStatusMessage(tr("OTP code copied to clipboard"));
4 ✔
817
  } else {
818
    // Why, when there is a configuration that gives no code.
819
    const QString reason = Totp::describe(why);
2 ✔
820
    flashText(reason.isEmpty() ? tr("No OTP code found in this password entry")
6 ✔
821
                               : reason,
822
              true);
823
  }
824
  setUiElementsEnabled(true);
4 ✔
825
}
8 ✔
826

827
void MainWindow::clearPanel(bool notify) {
63 ✔
828
  clearShownEntry(notify);
63 ✔
829
  clearContentResults();
63 ✔
830
}
63 ✔
831

832
void MainWindow::clearShownEntry(bool notify) {
65 ✔
833
  m_displayPanel->clear();
65 ✔
834
  m_panelEntry.clear();
65 ✔
835
  // A QR code of the password is the password on screen as much as the
836
  // panel is; it is a popup of its own, not part of the panel.
837
  m_qtPass->closeQRCode();
65 ✔
838
  if (notify) {
65 ✔
839
    QString output = "***" + tr("Password and content hidden") + "***";
4 ✔
840
    ui->textBrowser->setHtml(output);
2 ✔
841
  } else {
842
    ui->textBrowser->setHtml("");
126 ✔
843
  }
844
}
65 ✔
845

846
void MainWindow::clearContentResults() {
66 ✔
847
  clearResultsTimer.stop();
66 ✔
848
  const bool grepWasVisible = ui->grepResultsList->isVisible();
66 ✔
849
  ui->grepResultsList->clear();
66 ✔
850
  if (grepWasVisible) {
66 ✔
851
    showContentResults(false);
7 ✔
852
    if (m_grep.inGrepMode()) {
7 ✔
853
      // Left as the button leaves it: a search still running would otherwise
854
      // hand its partial matches to a content search entered meanwhile.
855
      cancelContentSearch();
7 ✔
856
      if (m_grep.leaveGrepMode()) {
857
        QApplication::restoreOverrideCursor();
2 ✔
858
      }
859
      ui->grepButton->blockSignals(true);
7 ✔
860
      ui->grepButton->setChecked(false);
7 ✔
861
      ui->grepButton->blockSignals(false);
7 ✔
862
      ui->lineEdit->blockSignals(true);
7 ✔
863
      ui->lineEdit->clear();
7 ✔
864
      ui->lineEdit->blockSignals(false);
7 ✔
865
      ui->lineEdit->setPlaceholderText(tr("Search password"));
14 ✔
866
    }
867
  }
868
}
66 ✔
869

870
void MainWindow::setUiElementsEnabled(bool state) {
448 ✔
871
  // A running re-encryption owns the UI state: the progress dialog's Cancel is
872
  // the user's escape hatch and endReencryptPath() releases the interface, so
873
  // neither an unrelated completion nor the watchdog may re-enable it early.
874
  if (state && m_reencryptRunning) {
448 ✔
875
    m_uiWatchdog.stop();
1 ✔
876
    return;
1 ✔
877
  }
878
  // Arm the watchdog while the UI is disabled; disarm once re-enabled.
879
  if (state) {
880
    m_uiWatchdog.stop();
352 ✔
881
  } else {
882
    m_uiWatchdog.start();
95 ✔
883
  }
884
  ui->treeView->setEnabled(state);
447 ✔
885
  ui->lineEdit->setEnabled(state);
447 ✔
886
  ui->actionAddPassword->setEnabled(state);
447 ✔
887
  ui->actionAddFolder->setEnabled(state);
447 ✔
888
  ui->actionUsers->setEnabled(state);
447 ✔
889
  ui->actionConfig->setEnabled(state);
447 ✔
890
  m_uiEnabled = state;
447 ✔
891
  updateProfileBoxEnabled();
447 ✔
892
  const bool uiEnabled = state;
893
  // is a file selected, and in sight (content search results hide the tree)?
894
  state &= ui->treeView->currentIndex().isValid() && !ui->treeView->isHidden();
897 ✔
895
  ui->actionDelete->setEnabled(state);
447 ✔
896
  ui->actionEdit->setEnabled(state);
447 ✔
897
  updateGitButtonVisibility(uiEnabled);
447 ✔
898
  // `state` is now "UI enabled AND a file is selected", which is exactly when
899
  // generating an OTP makes sense.
900
  updateOtpButtonVisibility(state);
447 ✔
901
}
902

903
void MainWindow::restoreWindow() {
208 ✔
904
  // saveGeometry() covers position, size, maximized state and screen;
905
  // anything applied on top discards it. Centre only when nothing was saved.
906
  const QByteArray geometry = QtPassSettings::getGeometry();
416 ✔
907
  if (geometry.isEmpty() || !restoreGeometry(geometry)) {
208 ✔
908
    WindowStateStore::centreOnCursorScreen(*this);
4 ✔
909
  }
910
  restoreState(QtPassSettings::getSavestate(saveState()));
208 ✔
911
  const AppSettings s = QtPassSettings::load();
208 ✔
912

913
  applyWindowFlagsSettings();
208 ✔
914

915
  if (s.useTrayIcon && m_tray == nullptr) {
208 ✔
916
    initTrayIcon();
2 ✔
917
    // Minimized to the tray only when there is one: without a system tray
918
    // initTrayIcon() gave up, and a hidden window could not be brought back.
919
    if (s.startMinimized && m_tray != nullptr) {
2 ✔
920
      // since we are still in constructor, can't directly hide
921
      QTimer::singleShot(10, this, &MainWindow::hide);
×
922
    }
923
  } else if (!s.useTrayIcon && m_tray != nullptr) {
206 ✔
924
    destroyTrayIcon();
×
925
  }
926
}
416 ✔
927

928
void MainWindow::onConfig() {
3 ✔
929
  // No Settings while anything of the store runs or waits, as with the
930
  // profile box (#2071): the store, backend and programs chosen there apply
931
  // to what is still queued, so a pending `pass init` re-encrypted the store
932
  // just picked for the recipients chosen for the other. Asked of the
933
  // backends: the watchdog releases the interface while a slow gpg or git
934
  // still runs.
935
  if (!QtPassSettings::backendsIdle()) {
3 ✔
936
    critical(tr("Settings not opened"),
2 ✔
937
             tr("A gpg, Git or pass command is still running or waiting. "
1 ✔
938
                "Open the settings again once it has finished. If it does "
939
                "not finish, answer or cancel the PIN or password prompt it "
940
                "waits for, or restart QtPass. A restart forgets which "
941
                "folders still need re-encrypting: re-encrypt any folder "
942
                "whose re-encryption did not finish, or that you moved "
943
                "entries into, before anything is pushed."));
944
    return;
1 ✔
945
  }
946
  config();
2 ✔
947
}
948

949
void MainWindow::showAbout() {
1 ✔
950
  QMessageBox::about(
1 ✔
951
      this, tr("About QtPass"),
1 ✔
952
      tr("<h3>QtPass %1</h3>"
1 ✔
953
         "<p>A multi-platform GUI for <a "
954
         "href=\"https://www.passwordstore.org/\">"
955
         "pass</a>, the standard Unix password manager.</p>"
956
         "<p><a href=\"https://qtpass.org/\">qtpass.org</a> &middot; "
957
         "<a href=\"https://github.com/IJHack/QtPass\">Source and "
958
         "issues</a></p>"
959
         "<p>Copyright &copy; 2014&ndash;%2 IJhack. Licensed under the "
960
         "<a href=\"https://www.gnu.org/licenses/gpl-3.0.html\">GNU GPL "
961
         "version 3</a> or later.</p>")
962
          .arg(QStringLiteral(VERSION),
2 ✔
963
               QString::number(QDate::currentDate().year())));
2 ✔
964
}
1 ✔
965

966
void MainWindow::on_lineEdit_textChanged(const QString &arg1) {
48 ✔
967
  if (m_grep.inGrepMode())
48 ✔
968
    return;
969
  ui->statusBar->showMessage(tr("Looking for: %1").arg(arg1), 1000);
70 ✔
970
  ui->treeView->expandAll();
35 ✔
971
  // Drop any decrypt still pending for the entry that was shown: otherwise it
972
  // keeps its right to the panel and, with "Always copy", the clipboard, and
973
  // when it lands late it shows that entry's password under the new heading.
974
  m_shownFile.clear();
35 ✔
975
  cancelOtpRequest();
35 ✔
976
  clearPanel(false);
35 ✔
977
  ui->passwordName->setText("");
70 ✔
978
  ui->actionEdit->setEnabled(false);
35 ✔
979
  ui->actionDelete->setEnabled(false);
35 ✔
980
  searchTimer.start();
35 ✔
981
}
982

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

988
  if (query.isEmpty()) {
39 ✔
989
    ui->treeView->collapseAll();
2 ✔
990
    deselect();
2 ✔
991
  }
992

993
  // The words are matched literally, in order, with anything in between:
994
  // "work vpn" finds work/acme/vpn.
995
  m_tree->setFilter(StoreModel::wordsFilter(query));
39 ✔
996

997
  if (m_tree->proxy().rowCount() > 0 && !query.isEmpty()) {
39 ✔
998
    selectFirstFile();
28 ✔
999
  } else {
1000
    ui->actionEdit->setEnabled(false);
11 ✔
1001
    ui->actionDelete->setEnabled(false);
11 ✔
1002
  }
1003
}
39 ✔
1004

1005
void MainWindow::on_lineEdit_returnPressed() {
17 ✔
1006
  qCDebug(lcQtPass) << "on_lineEdit_returnPressed"
17 ✔
1007
                    << m_tree->proxy().rowCount();
×
1008

1009
  if (m_grep.inGrepMode()) {
17 ✔
1010
    const QString query = ui->lineEdit->text();
12 ✔
1011
    if (!query.isEmpty()) {
12 ✔
1012
      ui->grepResultsList->clear();
9 ✔
1013
      ui->statusBar->showMessage(tr("Searching…"));
18 ✔
1014
      if (m_grep.beginSearch()) {
1015
        QApplication::setOverrideCursor(Qt::WaitCursor);
9 ✔
1016
      }
1017
      QtPassSettings::getPass()->Grep(query, ui->grepCaseButton->isChecked());
18 ✔
1018
    } else {
1019
      cancelContentSearch();
3 ✔
1020
      if (m_grep.cancelSearch()) {
1021
        QApplication::restoreOverrideCursor();
2 ✔
1022
      }
1023
      ui->grepResultsList->clear();
3 ✔
1024
      showContentResults(false);
3 ✔
1025
    }
1026
    return;
1027
  }
1028

1029
  // Return within the search delay acts on the text as typed, not on the
1030
  // tree as the previous text filtered it.
1031
  if (searchTimer.isActive()) {
5 ✔
1032
    searchTimer.stop();
5 ✔
1033
    onTimeoutSearch();
5 ✔
1034
  }
1035
  if (m_tree->proxy().rowCount() > 0) {
5 ✔
1036
    selectFirstFile();
5 ✔
1037
    on_treeView_clicked(ui->treeView->currentIndex());
5 ✔
1038
  }
1039
}
1040

1041
void MainWindow::on_grepButton_toggled(bool checked) {
35 ✔
1042
  const AppSettings s = QtPassSettings::load();
35 ✔
1043
  if (checked) {
35 ✔
1044
    m_grep.enterGrepMode();
1045
    ui->lineEdit->setPlaceholderText(tr("Search content (regex)"));
44 ✔
1046
    // Both backends search through NativeGrep (QRegularExpression), so one
1047
    // dialect: PCRE.
1048
    ui->lineEdit->setToolTip(
22 ✔
1049
        tr("Content search uses Perl-compatible regular expressions (PCRE)."));
22 ✔
1050
    ui->lineEdit->clear();
22 ✔
1051
    searchTimer.stop();
22 ✔
1052
    m_tree->setFilter(QRegularExpression());
22 ✔
1053
    ui->grepResultsList->setVisible(false);
22 ✔
1054
    // Keep treeView visible until results arrive
1055
  } else {
1056
    cancelContentSearch();
13 ✔
1057
    if (m_grep.leaveGrepMode()) {
1058
      QApplication::restoreOverrideCursor();
2 ✔
1059
    }
1060
    searchTimer.stop();
13 ✔
1061
    ui->lineEdit->blockSignals(true);
13 ✔
1062
    ui->lineEdit->clear();
13 ✔
1063
    ui->lineEdit->blockSignals(false);
13 ✔
1064
    ui->lineEdit->setPlaceholderText(tr("Search password"));
26 ✔
1065
    ui->lineEdit->setToolTip(QString());
26 ✔
1066
    ui->grepResultsList->clear();
13 ✔
1067
    showContentResults(false);
13 ✔
1068
    m_tree->setFilter(QRegularExpression());
13 ✔
1069
  }
1070
}
35 ✔
1071

1072
void MainWindow::refreshMarkedSecrets(const AppSettings &s) {
42 ✔
1073
  if (s.hidePassword) {
42 ✔
1074
    m_displayPanel->setMarkedSecrets(
4 ✔
1075
        TemplateIO::secretFieldsIn(s.passTemplate) +
8 ✔
1076
        TemplateIO::readSecretFields(s.passStore));
12 ✔
1077
  }
1078
}
42 ✔
1079

1080
auto MainWindow::grepLineForDisplay(const QString &line,
43 ✔
1081
                                    const AppSettings &s) const -> QString {
1082
  const QString hidden =
1083
      QStringLiteral("***") + tr("hidden") + QStringLiteral("***");
86 ✔
1084
  if (NativeGrep::isOtpMarker(line)) {
43 ✔
1085
    return tr("One-time password secret: %1").arg(hidden);
2 ✔
1086
  }
1087
  // The panel's own rules: the password and a field it would put behind
1088
  // the eye button keep their value out of the list too.
1089
  if (NativeGrep::isPasswordMatch(line)) {
1090
    return m_displayPanel->hides(QObject::tr("Password"), s)
52 ✔
1091
               ? tr("Password: %1").arg(hidden)
52 ✔
1092
               : NativeGrep::passwordMatchText(line);
26 ✔
1093
  }
1094
  if (const qsizetype colon = line.indexOf(QLatin1Char(':')); colon > 0) {
15 ✔
1095
    if (m_displayPanel->hides(line.left(colon).trimmed(), s)) {
39 ✔
1096
      return line.left(colon + 1) + QLatin1Char(' ') + hidden;
4 ✔
1097
    }
1098
  }
1099
  return line;
1100
}
1101

1102
void MainWindow::onGrepFinished(
21 ✔
1103
    const QList<QPair<QString, QStringList>> &results) {
1104
  // Both backends stay connected, each with its own search: a search the
1105
  // other backend was still running when Settings switched backends is not
1106
  // this one, whatever the controller's state, and searched another store.
1107
  // Dropped before it can end (or be taken for) the current search.
1108
  if (const QObject *from = sender();
21 ✔
1109
      from != nullptr && from != QtPassSettings::getPass()) {
21 ✔
1110
    return;
11 ✔
1111
  }
1112
  const GrepSearchController::FinishOutcome outcome = m_grep.finishSearch();
1113
  if (outcome.restoreCursor) {
20 ✔
1114
    QApplication::restoreOverrideCursor();
2 ✔
1115
  }
1116
  // Re-enable the UI before the discard check so a cancelled search can never
1117
  // leave controls disabled.
1118
  setUiElementsEnabled(true);
20 ✔
1119
  if (outcome.discard) {
20 ✔
1120
    return;
1121
  }
1122
  if (!m_grep.inGrepMode())
12 ✔
1123
    return;
1124
  ui->grepResultsList->clear();
12 ✔
1125
  if (results.isEmpty()) {
12 ✔
1126
    ui->statusBar->showMessage(tr("No matches found."), 3000);
2 ✔
1127
    showContentResults(false);
2 ✔
1128
    return;
2 ✔
1129
  }
1130
  const AppSettings s = QtPassSettings::load();
10 ✔
1131
  const bool hideContent = s.hideContent;
10 ✔
1132
  refreshMarkedSecrets(s);
10 ✔
1133
  int totalLines = 0;
1134
  int entries = 0;
1135
  bool stopped = false;
1136
  for (const auto &pair : results) {
43 ✔
1137
    if (NativeGrep::isStoppedMarker(pair)) {
33 ✔
1138
      stopped = true;
1139
      continue;
×
1140
    }
1141
    ++entries;
33 ✔
1142
    auto *entryItem = new QTreeWidgetItem(ui->grepResultsList);
33 ✔
1143
    entryItem->setText(0, pair.first);
33 ✔
1144
    entryItem->setData(0, Qt::UserRole, pair.first);
33 ✔
1145
    for (const QString &line : pair.second) {
76 ✔
1146
      auto *lineItem = new QTreeWidgetItem(entryItem);
43 ✔
1147
      // The marker is no content: shown as it is with hidden content too,
1148
      // and not counted as a match.
1149
      if (NativeGrep::isMoreMarker(line)) {
43 ✔
1150
        lineItem->setText(0, tr("… more matches in this entry"));
×
1151
      } else {
1152
        lineItem->setText(0, hideContent ? "***" + tr("Content hidden") + "***"
86 ✔
1153
                                         : grepLineForDisplay(line, s));
1154
        ++totalLines;
43 ✔
1155
      }
1156
      lineItem->setData(0, Qt::UserRole, pair.first);
43 ✔
1157
    }
1158
  }
1159
  ui->grepResultsList->expandAll();
10 ✔
1160
  showContentResults(true);
10 ✔
1161
  if (stopped) {
10 ✔
1162
    // The search stopped there; more entries may match.
1163
    ui->statusBar->showMessage(
×
1164
        tr("Showing the first %n match(es); search for something narrower "
×
1165
           "to see the rest.",
1166
           nullptr, totalLines),
1167
        10000);
1168
  } else {
1169
    ui->statusBar->showMessage(tr("Found %n match(es)", nullptr, totalLines) +
30 ✔
1170
                                   " " +
10 ✔
1171
                                   tr("in %n entr(ies).", nullptr, entries),
20 ✔
1172
                               3000);
1173
  }
1174
  // The results' own deadline: restarting the entry's timer here gave an
1175
  // entry still on the panel a second period, and an operation that stops
1176
  // the entry's timer left the results up with none.
1177
  if (s.useAutoclearPanel)
10 ✔
1178
    clearResultsTimer.start();
3 ✔
1179
}
10 ✔
1180

1181
void MainWindow::on_grepResultsList_itemClicked(QTreeWidgetItem *item,
2 ✔
1182
                                                int /*column*/) {
1183
  const AppSettings s = QtPassSettings::load();
2 ✔
1184
  const QString entry = item->data(0, Qt::UserRole).toString();
2 ✔
1185
  if (entry.isEmpty())
2 ✔
1186
    return;
1187
  const QString fullPath =
1188
      QDir::cleanPath(QDir(s.passStore).filePath(entry + ".gpg"));
4 ✔
1189
  // Persistent: setCurrentIndex() runs the selection handlers, which can
1190
  // change the model before the click is handled.
1191
  const QPersistentModelIndex proxyIndex(m_tree->indexFor(fullPath));
2 ✔
1192
  if (!proxyIndex.isValid())
2 ✔
1193
    return;
1194
  ui->treeView->setCurrentIndex(proxyIndex);
2 ✔
1195
  if (!proxyIndex.isValid())
2 ✔
1196
    return;
1197
  on_treeView_clicked(proxyIndex);
2 ✔
1198
  if (s.hideContent || s.useAutoclearPanel)
2 ✔
1199
    ui->grepResultsList->clear();
1 ✔
1200
  showContentResults(false);
2 ✔
1201
  ui->treeView->scrollTo(proxyIndex);
2 ✔
1202
  ui->treeView->setFocus();
2 ✔
1203
}
4 ✔
1204

1205
void MainWindow::showContentResults(bool shown) {
37 ✔
1206
  ui->grepResultsList->setVisible(shown);
37 ✔
1207
  ui->treeView->setVisible(!shown);
37 ✔
1208
  if (shown) {
37 ✔
1209
    // The tree's current entry is out of sight: Delete, Edit and OTP would
1210
    // act on it, not on a result. Opening a result shows the tree again.
1211
    ui->actionDelete->setEnabled(false);
10 ✔
1212
    ui->actionEdit->setEnabled(false);
10 ✔
1213
    updateOtpButtonVisibility(false);
10 ✔
1214
  } else if (ui->treeView->selectionModel()->hasSelection()) {
27 ✔
1215
    // Only for an entry still selected: with nothing selected there is no
1216
    // entry for Edit and Delete to act on.
1217
    setUiElementsEnabled(m_uiEnabled);
8 ✔
1218
  }
1219
}
37 ✔
1220

1221
void MainWindow::cancelContentSearch() {
28 ✔
1222
  QtPassSettings::getRealPass()->CancelGrep();
28 ✔
1223
  QtPassSettings::getImitatePass()->CancelGrep();
28 ✔
1224
}
28 ✔
1225

1226
void MainWindow::selectFirstFile() {
33 ✔
1227
  // The entry named exactly as typed wins: with folders sorted first, the
1228
  // depth-first walk found team/bank before bank.
1229
  QModelIndex index = exactMatch();
33 ✔
1230
  if (!index.isValid()) {
1231
    index = firstFile(m_tree->rootIndex());
17 ✔
1232
  }
1233
  ui->treeView->setCurrentIndex(index);
33 ✔
1234
}
33 ✔
1235

1236
namespace {
1237
/**
1238
 * @brief @p path with each part below @p store spelled as stored on disk.
1239
 *
1240
 * Where the file system ignores case, "Bank.gpg" exists while the file is
1241
 * bank.gpg, and the tree knows the entry only by that spelling.
1242
 * @param store The store folder.
1243
 * @param path An existing file in the store.
1244
 * @return @p path itself when every part is spelled as stored, otherwise
1245
 *         the path with the stored spelling.
1246
 */
1247
auto spelledAsStored(const QString &store, const QString &path) -> QString {
28 ✔
1248
  const QStringList parts = QDir(store).relativeFilePath(path).split(
56 ✔
1249
      QLatin1Char('/'), Qt::SkipEmptyParts);
28 ✔
1250
  QDir dir(store);
28 ✔
1251
  bool respelled = false;
1252
  for (int i = 0; i < parts.size(); ++i) {
31 ✔
1253
    const bool leaf = i == parts.size() - 1;
31 ✔
1254
    const QStringList names =
1255
        dir.entryList((leaf ? QDir::Files : QDir::Dirs) | QDir::Hidden |
31 ✔
1256
                      QDir::NoDotAndDotDot);
34 ✔
1257
    QString name = parts.at(i);
1258
    if (!names.contains(name)) {
31 ✔
1259
      const auto stored = std::find_if(
×
1260
          names.cbegin(), names.cend(), [&name](const QString &candidate) {
1261
            return candidate.compare(name, Qt::CaseInsensitive) == 0;
×
1262
          });
1263
      if (stored == names.cend()) {
×
1264
        return path;
1265
      }
1266
      name = *stored;
×
1267
      respelled = true;
1268
    }
1269
    if (leaf) {
31 ✔
1270
      return respelled ? QDir::cleanPath(dir.filePath(name)) : path;
56 ✔
1271
    }
1272
    if (!dir.cd(name)) {
3 ✔
1273
      return path;
1274
    }
1275
  }
1276
  return path;
1277
}
28 ✔
1278
} // namespace
1279

1280
auto MainWindow::exactMatchPath() -> QString {
47 ✔
1281
  const QString text = QDir::fromNativeSeparators(ui->lineEdit->text());
94 ✔
1282
  const QString store = QtPassSettings::getPassStore();
94 ✔
1283
  // A name may begin or end with a space: " bank" is that entry, not bank.
1284
  // Only when no entry is named so are spaces around the text dropped.
1285
  for (const QString &typed : {text, text.trimmed()}) {
181 ✔
1286
    if (typed.isEmpty()) {
68 ✔
1287
      continue;
×
1288
    }
1289
    const QString path =
1290
        QDir::cleanPath(QDir(store).filePath(typed + QStringLiteral(".gpg")));
136 ✔
1291
    if (PathValidator::isPathInStore(store, path) && QFileInfo(path).isFile()) {
68 ✔
1292
      return spelledAsStored(store, path);
28 ✔
1293
    }
1294
  }
141 ✔
1295
  return {};
19 ✔
1296
}
1297

1298
auto MainWindow::exactMatch() -> QModelIndex {
45 ✔
1299
  const QString path = exactMatchPath();
45 ✔
1300
  if (path.isEmpty()) {
45 ✔
1301
    return {};
18 ✔
1302
  }
1303
  // indexFor() maps through the filter: a row the filter hides is no match.
1304
  const QModelIndex index = m_tree->indexFor(path);
27 ✔
1305
  if (!index.isValid() || !m_tree->fileInfo(index).isFile()) {
49 ✔
1306
    return {};
5 ✔
1307
  }
1308
  return index;
22 ✔
1309
}
1310

1311
void MainWindow::applySearchText(const QString &text) {
8 ✔
1312
  // A name search: content search, left on, kept its results over the tree
1313
  // and ignored the text.
1314
  if (ui->grepButton->isChecked()) {
8 ✔
1315
    ui->grepButton->setChecked(false);
1 ✔
1316
  }
1317
  delete m_pendingOpen;
8 ✔
1318
  ui->lineEdit->setText(text);
8 ✔
1319
  // Filter now, not after the search delay: the timer would leave the tree
1320
  // as the previous text filtered it.
1321
  searchTimer.stop();
8 ✔
1322
  onTimeoutSearch();
8 ✔
1323
  if (const QModelIndex exact = exactMatch(); exact.isValid()) {
8 ✔
1324
    openExactMatch(exact);
6 ✔
1325
    return;
6 ✔
1326
  }
1327
  // The tree loads folders in the background: at start, or right after the
1328
  // window is shown again, an entry that exists may not be in it yet. Try
1329
  // again as folders finish loading, for a few seconds, unless the search
1330
  // text changes meanwhile: any change ends the wait, even one typed back to
1331
  // this text, which is a new search that has not asked to open anything.
1332
  if (exactMatchPath().isEmpty()) {
4 ✔
1333
    return;
1334
  }
1335
  auto *pending = new QObject(this);
1 ✔
1336
  m_pendingOpen = pending;
1337
  QTimer::singleShot(5000, pending, &QObject::deleteLater);
1 ✔
1338
  // Disconnected at once: with deleteLater() alone, a folder that finished
1339
  // loading before the deletion still ran the open, or ran it twice.
UNCOV
1340
  const auto stop = [this, pending] {
×
UNCOV
1341
    disconnect(&m_tree->fileSystem(), nullptr, pending, nullptr);
×
UNCOV
1342
    disconnect(ui->lineEdit, nullptr, pending, nullptr);
×
UNCOV
1343
    pending->deleteLater();
×
1344
  };
1 ✔
1345
  connect(ui->lineEdit, &QLineEdit::textChanged, pending, stop);
1 ✔
1346
  connect(&m_tree->fileSystem(), &QFileSystemModel::directoryLoaded, pending,
1 ✔
1347
          [this, stop](const QString &) {
2 ✔
1348
            searchTimer.stop();
4 ✔
1349
            onTimeoutSearch();
4 ✔
1350
            if (const QModelIndex exact = exactMatch(); exact.isValid()) {
4 ✔
UNCOV
1351
              stop();
×
UNCOV
1352
              openExactMatch(exact);
×
1353
            }
1354
          });
4 ✔
1355
}
1356

1357
void MainWindow::openExactMatch(const QModelIndex &index) {
6 ✔
1358
  // Made current here, not left to the filter pass before: the tree may have
1359
  // moved its current row since, and with none on_treeView_clicked() only
1360
  // names the entry without decrypting it.
1361
  ui->treeView->setCurrentIndex(index);
6 ✔
1362
  on_treeView_clicked(index);
6 ✔
1363
}
6 ✔
1364

1365
auto MainWindow::firstFile(QModelIndex parentIndex) -> QModelIndex {
26 ✔
1366
  StoreModel &proxy = m_tree->proxy();
26 ✔
1367
  int numRows = proxy.rowCount(parentIndex);
26 ✔
1368
  for (int row = 0; row < numRows; ++row) {
33 ✔
1369
    QModelIndex index = proxy.index(row, 0, parentIndex);
24 ✔
1370
    if (m_tree->fileInfo(index).isFile()) {
24 ✔
1371
      return index;
17 ✔
1372
    }
1373
    if (proxy.hasChildren(index)) {
14 ✔
1374
      QModelIndex childFile = firstFile(index);
9 ✔
1375
      if (childFile.isValid())
1376
        return childFile;
7 ✔
1377
    }
1378
  }
1379
  return QModelIndex();
9 ✔
1380
}
1381

1382
// Guards the input dialogs (create, move, rename) against names like
1383
// "../../etc/passwd" or absolute paths escaping the store root.
1384
auto MainWindow::confirmPathInStore(const QString &candidate) -> bool {
10 ✔
1385
  if (PathValidator::isPathInStore(QtPassSettings::getPassStore(), candidate)) {
20 ✔
1386
    return true;
1387
  }
1388
  QMessageBox::warning(this, tr("Invalid name"),
9 ✔
1389
                       tr("That name would resolve outside the password "
3 ✔
1390
                          "store. Please choose a different name."));
1391
  return false;
3 ✔
1392
}
1393

1394
void MainWindow::setPassword(const QString &file, bool isNew) {
7 ✔
1395
  const AppSettings s = QtPassSettings::load();
7 ✔
1396
  PasswordDialog d(QtPassSettings::getPass(), s, file, isNew, this);
7 ✔
1397
  // A copy out of the editor is autocleared like one from the display.
1398
  connect(&d, &PasswordDialog::copied, &m_qtPass->clipboard(),
7 ✔
1399
          &ClipboardManager::trackCopied);
7 ✔
1400

1401
  if (isNew) {
7 ✔
1402
    const QString storePath = s.passStore;
1403
    QString folder = m_tree->currentDir(false);
1 ✔
1404
    if (folder.isEmpty()) {
1 ✔
1405
      folder = storePath;
×
1406
    }
1407
    // Folders to pick from, the tree's current one preselected. Real folders
1408
    // only: a linked or junctioned one would write the entry outside the store.
1409
    QStringList folders{QString()};
2 ✔
1410
    const QStringList found = Util::directoriesUnder(storePath);
1 ✔
1411
    for (const QString &path : found) {
18 ✔
1412
      const QString rel = QDir(storePath).relativeFilePath(path);
17 ✔
1413
      if (!rel.startsWith(u'.') && !rel.contains(QStringLiteral("/."))) {
51 ✔
1414
        folders << rel;
1415
      }
1416
    }
1417
    std::sort(folders.begin() + 1, folders.end());
1 ✔
1418
    d.setNewEntryLocation(storePath, folders,
1 ✔
1419
                          QDir(storePath).relativeFilePath(folder));
2 ✔
1420
    QHash<QString, QStringList> templates =
1421
        TemplateIO::readTemplates(storePath);
1 ✔
1422
    if (!templates.isEmpty()) {
1423
      QString defaultTemplate =
1424
          TemplateIO::getFolderTemplate(folder, storePath);
1 ✔
1425
      d.setAvailableTemplates(templates, defaultTemplate);
1 ✔
1426
    }
1427
  }
1 ✔
1428

1429
  if (!d.exec()) {
7 ✔
1430
    ui->treeView->setFocus();
6 ✔
1431
  }
1432
}
7 ✔
1433

1434
void MainWindow::addPassword() { setPassword(QString()); }
2 ✔
1435

1436
auto MainWindow::confirmDeletion(const QString &file, bool isDir) -> bool {
8 ✔
1437
  const QString path = QDir::separator() + file;
8 ✔
1438
  // As the platform writes paths: backslashes only on Windows, never a mix.
1439
  // On one line: a name from the store may hold a line feed (Unix allows
1440
  // one), which drew lines of its own into the question.
1441
  const QString shown =
1442
      Util::displayable(QDir::toNativeSeparators(path), false);
8 ✔
1443
  if (!isDir) {
8 ✔
1444
    return PlainMessageBox::askYes(
2 ✔
1445
        this, tr("Delete password?"),
2 ✔
1446
        tr("Are you sure you want to delete %1?").arg(shown));
4 ✔
1447
  }
1448
  // Whole sentences, not a question stitched from pieces: a verb-final
1449
  // language cannot put the rest of the question after the path.
1450
  // Plain text, as every box quoting the store: the path is a name other
1451
  // writers control, and as rich text "a  b" would also show as "a b".
1452
  QString question =
1453
      tr("Are you sure you want to delete %1 and the whole content?")
×
1454
          .arg(shown);
6 ✔
1455
  // A link, junction or special file inside is as unexpected as a stray
1456
  // plain file: the walker leaves them out of content and reports them.
1457
  QStringList skipped;
6 ✔
1458
  QStringList unlisted;
6 ✔
1459
  const QString root = m_tree->fileSystem().rootPath();
6 ✔
1460
  const QStringList content = Util::regularFilesUnder(
18 ✔
1461
      root + path, {QStringLiteral("*")}, &skipped, false, &unlisted);
18 ✔
1462
  const bool unexpected =
1463
      !skipped.isEmpty() ||
6 ✔
1464
      std::any_of(content.cbegin(), content.cend(), [](const QString &entry) {
6 ✔
1465
        return QFileInfo(entry).suffix() != QLatin1String("gpg");
8 ✔
1466
      });
1467
  if (unexpected) {
1468
    question += QStringLiteral("\n\n") +
1 ✔
1469
                tr("Attention: there are unexpected files in the given "
1 ✔
1470
                   "folder, check them before continuing.");
1 ✔
1471
  }
1472
  // A folder the walk cannot read is not empty but unknown: whatever it
1473
  // holds goes too, or stays behind when the removal cannot list it.
1474
  if (unlisted.size() == 1) {
6 ✔
1475
    //: %1 is a folder in the password store, such as /Work/bank.
1476
    const QString one =
1477
        tr("%1 could not be read, so what it holds is unknown.")
1 ✔
1478
            .arg(Util::displayable(
1 ✔
1479
                QDir::toNativeSeparators(
1 ✔
1480
                    QDir::separator() +
1 ✔
1481
                    QDir(root).relativeFilePath(unlisted.first())),
2 ✔
1482
                false));
3 ✔
1483
    question += QStringLiteral("\n\n") + one;
2 ✔
1484
  } else if (unlisted.size() > 1) {
5 ✔
1485
    //: Only shown for two or more folders; one folder is named instead.
1486
    const QString many =
1487
        tr("%n folder(s) in it could not be read, so what they hold "
1488
           "is unknown.",
1489
           nullptr, static_cast<int>(unlisted.size()));
1 ✔
1490
    question += QStringLiteral("\n\n") + many;
2 ✔
1491
  }
1492
  return PlainMessageBox::askYes(this, tr("Delete folder?"), question);
12 ✔
1493
}
1494

1495
auto MainWindow::confirmLinkRemoval(const QString &file) -> bool {
1 ✔
1496
  // Only the link goes (ImitatePass::Remove unlinks it); nothing behind it
1497
  // is looked at or mentioned.
1498
  return PlainMessageBox::askYes(
1 ✔
1499
      this, tr("Delete link?"),
1 ✔
1500
      tr("%1 is a symbolic link or junction. Remove the link? What it "
1 ✔
1501
         "points to is left alone.")
1502
          .arg(Util::displayable(QDir::separator() + file, false)));
2 ✔
1503
}
1504

1505
void MainWindow::onDelete() {
13 ✔
1506
  const QModelIndex currentIndex = ui->treeView->currentIndex();
13 ✔
1507
  // While content search results hide the tree, its current entry is not
1508
  // what the user looks at (the Delete key comes here directly).
1509
  if (!currentIndex.isValid() || ui->treeView->isHidden()) {
11 ✔
1510
    // Otherwise the whole password directory would be deleted (#556).
1511
    return;
10 ✔
1512
  }
1513

1514
  const bool isDir = !m_tree->fileInfo(currentIndex).isFile();
9 ✔
1515
  const QString file =
1516
      isDir ? m_tree->currentDir(true) : getFile(currentIndex, true);
9 ✔
1517
  const QString folder =
1518
      m_tree->fileSystem().rootPath() + QDir::separator() + file;
9 ✔
1519
  const bool linkedFolder = isDir && Util::isLinkedFolder(folder);
9 ✔
1520

1521
  if (!linkedFolder && refuseLinkedFolder(folder)) {
8 ✔
1522
    // Behind a link: deleting would reach outside the store.
1523
    return;
1524
  }
1525
  const bool confirmed =
1526
      linkedFolder ? confirmLinkRemoval(file) : confirmDeletion(file, isDir);
9 ✔
1527
  if (!confirmed) {
9 ✔
1528
    return;
1529
  }
1530
  QtPassSettings::getPass()->Remove(file, isDir);
6 ✔
1531
}
1532

1533
void MainWindow::cancelOtpRequest() {
90 ✔
1534
  m_otpRequestFile.clear();
90 ✔
1535
  m_copyRequestFile.clear();
90 ✔
1536
}
90 ✔
1537

1538
void MainWindow::onOperationError() {
35 ✔
1539
  cancelOtpRequest();
35 ✔
1540
  // executeWrapperStarted() emptied the panel and the browser when the
1541
  // operation started (a refusal says so too); what is left to forget is
1542
  // which entry the panel was about to show.
1543
  m_shownFile.clear();
35 ✔
1544
  // A save's refresh waiting for its push is dropped: it would clear the
1545
  // push's error (or whatever failed before it) from the browser.
1546
  m_refreshAfterPush.clear();
35 ✔
1547
  m_refreshAfterPushOwner = nullptr;
1548
}
35 ✔
1549

1550
// Derives the code in-process from one decrypt, so it works with either
1551
// backend on every platform; otpFromFileToClipboard() finishes the job.
1552
void MainWindow::onOtp() {
12 ✔
1553
  if (ui->treeView->isHidden()) {
12 ✔
1554
    return;
4 ✔
1555
  }
1556
  QString file = getFile(ui->treeView->currentIndex(), true);
11 ✔
1557
  if (file.isEmpty()) {
11 ✔
1558
    flashText(tr("No password selected for OTP generation"), true);
1 ✔
1559
    return;
1 ✔
1560
  }
1561
  if (!QtPassSettings::isUseOtp()) {
10 ✔
1562
    // Normally unreachable (the action is hidden), but never fail silently.
1563
    flashText(tr("No OTP code found in this password entry"), true);
1 ✔
1564
    return;
1 ✔
1565
  }
1566

1567
  // Fast path: the panel shows a live code, so no decrypt, and one clipboard
1568
  // write (two setMimeData calls in one turn can empty the Windows
1569
  // clipboard). Only for *this* entry: arrow keys and right-click move
1570
  // currentIndex without QTreeView::clicked, so the code may be another's.
1571
  const QString shown =
1572
      (m_shownFile == file) ? m_displayPanel->currentOtpCode() : QString();
9 ✔
1573
  if (!shown.isEmpty()) {
9 ✔
1574
    m_qtPass->clipboard().copyText(shown);
1 ✔
1575
    showStatusMessage(tr("OTP code copied to clipboard"));
2 ✔
1576
    return;
1577
  }
1578

1579
  // Fallback: decrypt once. The request file keeps passShowHandler from
1580
  // copying the password and tells otpFromFileToClipboard its answer.
1581
  m_otpRequestFile = file;
8 ✔
1582
  setUiElementsEnabled(false);
8 ✔
1583
  // Keep the marker in step so a second request takes the fast path; safe as
1584
  // executeWrapperStarted() clears the panel, so a failed decrypt shows none.
1585
  m_shownFile = file;
8 ✔
1586
  QtPassSettings::getPass()->Show(file);
16 ✔
1587
}
1588

1589
void MainWindow::onEdit() {
1 ✔
1590
  if (ui->treeView->isHidden()) {
1 ✔
1591
    return;
1 ✔
1592
  }
1593
  QString file = getFile(ui->treeView->currentIndex(), true);
×
1594
  editPassword(file);
×
1595
}
1596

1597
void MainWindow::onUsers() {
2 ✔
1598
  const QString dir = m_tree->currentDir(false);
2 ✔
1599
  if (refuseLinkedFolder(dir)) {
2 ✔
1600
    return;
1601
  }
1602

1603
  UsersDialog d(QtPassSettings::getPass(), QtPassSettings::load(), dir, this);
1 ✔
1604
  if (!d.exec()) {
1 ✔
1605
    ui->treeView->setFocus();
1 ✔
1606
  }
1607
}
1 ✔
1608

1609
void MainWindow::messageAvailable(const QString &message) {
9 ✔
1610
  show();
9 ✔
1611
  raise();
9 ✔
1612
  if (message.isEmpty()) {
9 ✔
1613
    focusInput();
1 ✔
1614
  } else {
1615
    ui->treeView->expandAll();
8 ✔
1616
    applySearchText(message);
8 ✔
1617
  }
1618
}
9 ✔
1619

1620
void MainWindow::updateProfileBox() {
206 ✔
1621
  const Profiles profiles = QtPassSettings::getProfiles();
206 ✔
1622
  bool activeGone = false;
1623

1624
  if (profiles.isEmpty()) {
7 ✔
1625
    ui->profileWidget->hide();
199 ✔
1626
  } else {
1627
    ui->profileWidget->show();
7 ✔
1628
    // A refill is no choice of the user's: clearing and adding items moves
1629
    // the current text, which would otherwise switch profiles.
1630
    const QSignalBlocker quiet(ui->profileBox);
7 ✔
1631
    ui->profileBox->clear();
7 ✔
1632
    for (auto i = profiles.cbegin(); i != profiles.cend(); ++i) {
19 ✔
1633
      if (!i.key().isEmpty()) {
12 ✔
1634
        ui->profileBox->addItem(i.key());
12 ✔
1635
      }
1636
    }
1637
    ui->profileBox->model()->sort(0);
7 ✔
1638
    int index = ui->profileBox->findText(QtPassSettings::getProfile());
14 ✔
1639
    if (index != -1) { //  -1 for not found
7 ✔
1640
      ui->profileBox->setCurrentIndex(index);
6 ✔
1641
    } else if (ui->profileBox->count() > 0) {
1 ✔
1642
      // The active profile is gone (removed in Settings): the box shows the
1643
      // first one, and the settings and backend must follow it, or the
1644
      // removed profile's store stays in use behind it.
1645
      ui->profileBox->setCurrentIndex(0);
1 ✔
1646
      activeGone = true;
1647
    }
1648
  }
7 ✔
1649
  if (activeGone) {
7 ✔
1650
    on_profileBox_currentTextChanged(ui->profileBox->currentText());
2 ✔
1651
  }
1652
  updateProfileBoxEnabled();
206 ✔
1653
}
206 ✔
1654

1655
void MainWindow::updateProfileBoxEnabled() {
698 ✔
1656
  // No profile switch while anything of the store runs or waits: the
1657
  // backend's store and environment would change under it, and what is
1658
  // still queued (a push after a save, say) would finish for the other
1659
  // profile (#2071). Asked of the backend, not only of the interface: the
1660
  // watchdog releases the interface while a slow gpg or git still runs.
1661
  // Every backend: one kept from before a switch of backend may still
1662
  // run what was queued on it.
1663
  ui->profileBox->setEnabled(m_uiEnabled && ui->profileBox->count() > 1 &&
1,398 ✔
1664
                             QtPassSettings::backendsIdle());
14 ✔
1665
}
698 ✔
1666

1667
void MainWindow::on_profileBox_currentTextChanged(const QString &name) {
6 ✔
1668
  if (m_freshStart || name == QtPassSettings::getProfile()) {
18 ✔
1669
    return;
1 ✔
1670
  }
1671
  // The box is disabled while anything runs; should a change come through
1672
  // anyway, the active profile stays and the box says so again.
1673
  if (!m_uiEnabled || !QtPassSettings::backendsIdle()) {
5 ✔
1674
    const QSignalBlocker quiet(ui->profileBox);
×
1675
    ui->profileBox->setCurrentText(QtPassSettings::getProfile());
×
1676
    return;
1677
  }
×
1678
  // A content search runs outside the queue: leaving grep mode cancels it,
1679
  // so its results for the old store are dropped, not shown for the new.
1680
  if (m_grep.inGrepMode()) {
5 ✔
1681
    ui->grepButton->setChecked(false);
1 ✔
1682
  }
1683

1684
  ui->lineEdit->clear();
5 ✔
1685

1686
  const Profile prof = QtPassSettings::getProfiles().value(name);
10 ✔
1687
  AppSettings s = QtPassSettings::load();
5 ✔
1688
  s.activeProfile = name;
5 ✔
1689
  s.passStore = prof.path;
5 ✔
1690
  s.passSigningKey = prof.signingKey;
5 ✔
1691
  // A profile without its own Git flags keeps the global values.
1692
  s.useGit = prof.useGit.value_or(s.useGit);
5 ✔
1693
  s.autoPush = prof.autoPush.value_or(s.autoPush);
5 ✔
1694
  s.autoPull = prof.autoPull.value_or(s.autoPull);
5 ✔
1695
  QtPassSettings::save(s);
5 ✔
1696
  ui->statusBar->showMessage(tr("Profile changed to %1").arg(name), 2000);
10 ✔
1697

1698
  QtPassSettings::getPass()->updateEnv();
5 ✔
1699

1700
  m_tree->setStore(QtPassSettings::getPassStore());
10 ✔
1701
  deselect();
5 ✔
1702
  ui->treeView->setCurrentIndex(QModelIndex());
5 ✔
1703
}
5 ✔
1704

1705
void MainWindow::initTrayIcon() {
3 ✔
1706
  m_tray = new TrayIcon(this);
3 ✔
1707
  if (!m_tray->getIsAllocated()) {
3 ✔
1708
    destroyTrayIcon();
3 ✔
1709
    return;
3 ✔
1710
  }
1711
#ifndef Q_OS_MACOS
1712
  m_tray->addToggle(ui->actionShowMenuBar);
×
1713
#endif
1714
}
1715

1716
void MainWindow::destroyTrayIcon() {
3 ✔
1717
  delete m_tray;
3 ✔
1718
  m_tray = nullptr;
3 ✔
1719
}
3 ✔
1720

1721
void MainWindow::closeEvent(QCloseEvent *event) {
4 ✔
1722
  // Save in both branches: a tray user only ever hides the window, and
1723
  // used to quit through the tray menu with nothing ever written.
1724
  saveWindowState();
4 ✔
1725
  // Only with a tray icon to come back from: without one (none asked for, or
1726
  // no system tray in this session) a hidden QtPass ran on invisibly, with the
1727
  // last entry in its window and the password on the clipboard.
1728
  if (QtPassSettings::isHideOnClose() && m_tray != nullptr) {
8 ✔
1729
    this->hide();
×
1730
    event->ignore();
1731
  } else {
1732
    m_qtPass->clipboard().clear();
4 ✔
1733
    event->accept();
1734
    // A visible QSystemTrayIcon keeps the application alive, so
1735
    // quitOnLastWindowClosed never fires; quit explicitly.
1736
    QApplication::quit();
4 ✔
1737
  }
1738
}
4 ✔
1739

1740
auto MainWindow::eventFilter(QObject *obj, QEvent *event) -> bool {
8,275 ✔
1741
  if ((obj == ui->toolBar || obj == menuBar()) &&
8,275 ✔
1742
      event->type() == QEvent::PaletteChange) {
1743
    // Breeze gives these bars a "header" palette and, after a runtime
1744
    // light/dark switch, stamps the previous theme's colours back from a
1745
    // cached kdeglobals, hiding the toolbar icons. Deferred so we never
1746
    // re-enter the style while it is still applying its palette.
1747
    QTimer::singleShot(0, this, &MainWindow::dropStaleToolsAreaPalettes);
36 ✔
1748
  }
1749
  if (obj == ui->lineEdit && event->type() == QEvent::KeyPress) {
8,275 ✔
1750
    auto *key = dynamic_cast<QKeyEvent *>(event);
5 ✔
1751
    if (key != nullptr && key->key() == Qt::Key_Down) {
5 ✔
1752
      // Into whichever list is in sight: the tree, or content search results.
1753
      // Focus makes the list's first item current.
1754
      if (ui->treeView->isHidden()) {
2 ✔
1755
        ui->grepResultsList->setFocus();
1 ✔
1756
      } else {
1757
        ui->treeView->setFocus();
1 ✔
1758
      }
1759
    }
1760
    // Return ends at the search box: QLineEdit emits returnPressed() and
1761
    // leaves the key unaccepted, so keyPressEvent() would open the tree's
1762
    // current entry as well. In content search that is an entry nobody
1763
    // asked for; by name, the first hit a second time.
1764
    if (key != nullptr &&
5 ✔
1765
        (key->key() == Qt::Key_Return || key->key() == Qt::Key_Enter)) {
2 ✔
1766
      ui->lineEdit->event(event);
3 ✔
1767
      event->accept();
1768
      return true;
3 ✔
1769
    }
1770
  }
1771
  return QObject::eventFilter(obj, event);
8,272 ✔
1772
}
1773

1774
// Only once the application palette changed (see m_themeSwitched): a bar
1775
// whose active Window lightness is far from the application's shows the
1776
// other theme.
1777
void MainWindow::dropStaleToolsAreaPalettes() {
31 ✔
1778
  if (!m_themeSwitched) {
31 ✔
1779
    return;
1780
  }
1781
  constexpr int kStaleToolsAreaLightness = 64;
1782
  // The active group on both sides: a bar's palette() reads the inactive
1783
  // group while another window has focus (the settings app, during a theme
1784
  // switch), and Breeze gives the header set different inactive colours.
1785
  const int appLightness = QApplication::palette()
54 ✔
1786
                               .color(QPalette::Active, QPalette::Window)
1787
                               .lightness();
27 ✔
1788
  for (QWidget *bar : {static_cast<QWidget *>(ui->toolBar),
108 ✔
1789
                       static_cast<QWidget *>(menuBar())}) {
81 ✔
1790
    if (!bar->testAttribute(Qt::WA_SetPalette)) {
54 ✔
1791
      continue;
48 ✔
1792
    }
1793
    const int barLightness =
1794
        bar->palette().color(QPalette::Active, QPalette::Window).lightness();
12 ✔
1795
    if (qAbs(barLightness - appLightness) <= kStaleToolsAreaLightness) {
6 ✔
1796
      continue;
2 ✔
1797
    }
1798
    bar->setPalette(QPalette());
4 ✔
1799
    // Both bars are transparent and the style paints the tools area from the
1800
    // stale palette, so fill our own. Window, not their Button role, which is
1801
    // not the window colour in either theme.
1802
    bar->setBackgroundRole(QPalette::Window);
4 ✔
1803
    bar->setAutoFillBackground(true);
4 ✔
1804
  }
1805
}
1806

1807
void MainWindow::keyPressEvent(QKeyEvent *event) {
25 ✔
1808
  switch (event->key()) {
25 ✔
1809
  case Qt::Key_Delete:
2 ✔
1810
    onDelete();
2 ✔
1811
    break;
2 ✔
1812
  case Qt::Key_Return:
2 ✔
1813
  case Qt::Key_Enter:
1814
    // While content search results hide the tree, its current entry is not
1815
    // what the user looks at: Return on a result opens that result.
1816
    if (ui->treeView->isHidden()) {
2 ✔
1817
      QTreeWidgetItem *result = ui->grepResultsList->currentItem();
1 ✔
1818
      if (result != nullptr && ui->grepResultsList->hasFocus()) {
1 ✔
1819
        on_grepResultsList_itemClicked(result, 0);
1 ✔
1820
      }
1821
      break;
1822
    }
1823
    if (m_tree->proxy().rowCount() > 0) {
1 ✔
1824
      on_treeView_clicked(ui->treeView->currentIndex());
1 ✔
1825
    }
1826
    break;
1827
  case Qt::Key_Escape:
3 ✔
1828
    ui->lineEdit->clear();
3 ✔
1829
    break;
3 ✔
1830
  default:
1831
    break;
1832
  }
1833
}
25 ✔
1834

1835
void MainWindow::addShareMenu(QMenu &contextMenu, const AppSettings &s) {
10 ✔
1836
  const QString dirPath = QDir::cleanPath(m_tree->currentDir(false));
10 ✔
1837
  auto *shareMenu = new QMenu(tr("Share"), &contextMenu);
10 ✔
1838
  contextMenu.addMenu(shareMenu);
10 ✔
1839

1840
  const QString gpgIdPath = Pass::getGpgIdPath(dirPath, s.passStore);
10 ✔
1841
  const bool gpgIdExists = !gpgIdPath.isEmpty() && QFile(gpgIdPath).exists();
10 ✔
1842
  const QString exePath = s.usePass ? s.passExecutable : s.gpgExecutable;
10 ✔
1843
  const bool gpgAvailable =
1844
      !exePath.isEmpty() &&
20 ✔
1845
      (Executor::parseWslCommand(exePath) || QFile(exePath).exists());
20 ✔
1846

1847
  QAction *reencrypt = shareMenu->addAction(tr("Re-encrypt all passwords"));
10 ✔
1848
  reencrypt->setEnabled(gpgIdExists && gpgAvailable);
10 ✔
1849
  connect(reencrypt, &QAction::triggered, this,
10 ✔
1850
          [this, dirPath]() { reencryptPath(dirPath); });
34 ✔
1851

1852
  QAction *exportKey = shareMenu->addAction(tr("Export my public key..."));
10 ✔
1853
  exportKey->setEnabled(gpgAvailable);
10 ✔
1854
  connect(exportKey, &QAction::triggered, this, &MainWindow::exportPublicKey);
10 ✔
1855

1856
  QAction *addRecipientAction = shareMenu->addAction(tr("Add recipient..."));
10 ✔
1857
  addRecipientAction->setEnabled(gpgIdExists && gpgAvailable);
10 ✔
1858
  connect(addRecipientAction, &QAction::triggered, this,
10 ✔
1859
          [this, dirPath]() { addRecipient(dirPath); });
32 ✔
1860

1861
  QAction *shareHelp = shareMenu->addAction(tr("What is this?"));
10 ✔
1862
  connect(shareHelp, &QAction::triggered, this, &MainWindow::showShareHelp);
10 ✔
1863
}
10 ✔
1864

1865
void MainWindow::showContextMenu(const QPoint &pos) {
12 ✔
1866
  const AppSettings s = QtPassSettings::load();
12 ✔
1867
  const QModelIndex index = ui->treeView->indexAt(pos);
12 ✔
1868
  const bool selected = index.isValid();
1869
  if (!selected) {
1870
    ui->treeView->clearSelection();
1 ✔
1871
    ui->actionDelete->setEnabled(false);
1 ✔
1872
    ui->actionEdit->setEnabled(false);
1 ✔
1873
  }
1874
  ui->treeView->setCurrentIndex(index);
12 ✔
1875
  const QPoint globalPos = ui->treeView->viewport()->mapToGlobal(pos);
12 ✔
1876
  const QFileInfo fileOrFolder = m_tree->fileInfo(ui->treeView->currentIndex());
12 ✔
1877
  const bool isDir = fileOrFolder.isDir();
12 ✔
1878

1879
  QMenu contextMenu;
12 ✔
1880
  if (!selected || isDir) {
12 ✔
1881
    const std::array<std::pair<QString, void (MainWindow::*)()>, 4> onFolder{{
1882
        {tr("Open folder with file manager"), &MainWindow::openFolder},
11 ✔
1883
        {tr("Add folder"), &MainWindow::addFolder},
11 ✔
1884
        {tr("Add password"), &MainWindow::addPassword},
11 ✔
1885
        {tr("Users"), &MainWindow::onUsers},
11 ✔
1886
    }};
×
1887
    for (const auto &[text, slot] : onFolder) {
55 ✔
1888
      connect(contextMenu.addAction(text), &QAction::triggered, this, slot);
44 ✔
1889
    }
1890
  } else if (fileOrFolder.isFile()) {
1 ✔
1891
    connect(contextMenu.addAction(tr("Edit")), &QAction::triggered, this,
1 ✔
1892
            &MainWindow::onEdit);
2 ✔
1893
  }
1894
  if (selected) {
12 ✔
1895
    contextMenu.addSeparator();
11 ✔
1896
    if (isDir) {
11 ✔
1897
      connect(contextMenu.addAction(tr("Rename folder")), &QAction::triggered,
10 ✔
1898
              this, &MainWindow::renameFolder);
20 ✔
1899
    } else if (fileOrFolder.isFile()) {
1 ✔
1900
      connect(contextMenu.addAction(tr("Rename password")), &QAction::triggered,
1 ✔
1901
              this, &MainWindow::renamePassword);
2 ✔
1902
    }
1903
    connect(contextMenu.addAction(tr("Delete")), &QAction::triggered, this,
11 ✔
1904
            &MainWindow::onDelete);
11 ✔
1905
    if (isDir) {
11 ✔
1906
      addShareMenu(contextMenu, s);
10 ✔
1907
    }
1908
  }
1909
  contextMenu.exec(globalPos);
12 ✔
1910
}
12 ✔
1911

1912
auto MainWindow::browserContextMenu(const QPoint &pos) -> QMenu * {
3 ✔
1913
  // createStandardContextMenu() takes document coordinates, anchorAt() and
1914
  // the menu's place viewport ones: scrolled, the menu checked the text
1915
  // above the link and left "Copy Link Location" disabled.
1916
  // Right to left, the horizontal offset counts from the other end.
1917
  const QScrollBar *across = ui->textBrowser->horizontalScrollBar();
3 ✔
1918
  const int dx = ui->textBrowser->isRightToLeft()
3 ✔
1919
                     ? across->maximum() - across->value()
3 ✔
1920
                     : across->value();
3 ✔
1921
  const QPoint documentPos =
1922
      pos + QPoint(dx, ui->textBrowser->verticalScrollBar()->value());
3 ✔
1923
  QMenu *contextMenu = ui->textBrowser->createStandardContextMenu(documentPos);
3 ✔
1924
  // Reparent from textBrowser: a browser stylesheet cascades to the child
1925
  // QMenu and breaks its opaque native background.
1926
  contextMenu->setParent(this, contextMenu->windowFlags());
3 ✔
1927
  if (auto *copyLink =
3 ✔
1928
          contextMenu->findChild<QAction *>(QStringLiteral("link-copy"))) {
3 ✔
1929
    const QString link = ui->textBrowser->anchorAt(pos);
3 ✔
1930
    disconnect(copyLink, &QAction::triggered, nullptr, nullptr);
3 ✔
1931
    connect(copyLink, &QAction::triggered, this, [this, link] {
10 ✔
1932
      if (!link.isEmpty()) {
1 ✔
1933
        m_qtPass->clipboard().copyText(link);
1 ✔
1934
      }
1935
    });
1 ✔
1936
  }
1937
  return contextMenu;
3 ✔
1938
}
1939

1940
void MainWindow::showBrowserContextMenu(const QPoint &pos) {
1 ✔
1941
  QMenu *contextMenu = browserContextMenu(pos);
1 ✔
1942
  contextMenu->exec(ui->textBrowser->viewport()->mapToGlobal(pos));
1 ✔
1943
  delete contextMenu;
1 ✔
1944
}
1 ✔
1945

1946
void MainWindow::openFolder() {
1 ✔
1947
  QString dir = m_tree->currentDir(false);
1 ✔
1948

1949
  QString path = QDir::toNativeSeparators(dir);
1 ✔
1950
  QDesktopServices::openUrl(QUrl::fromLocalFile(path));
1 ✔
1951
}
1 ✔
1952

1953
void MainWindow::addFolder() {
7 ✔
1954
  const AppSettings s = QtPassSettings::load();
7 ✔
1955
  bool ok;
1956
  QString dir = m_tree->currentDir(false);
7 ✔
1957
  QString newdir = QInputDialog::getText(
1958
      this, tr("New folder"),
7 ✔
1959
      tr("New folder: \n(Will be placed in %1 )")
7 ✔
1960
          .arg(Util::shownName(s.passStore + m_tree->currentDir(true))),
14 ✔
1961
      QLineEdit::Normal, "", &ok);
14 ✔
1962
  if (!ok || newdir.isEmpty()) {
7 ✔
1963
    return;
1964
  }
1965
  // Checked and created as one and the same path: the check resolves ".."
1966
  // lexically, the system after following links, so "link/../x" would pass
1967
  // as the store's x and be made beside the link's target.
1968
  newdir = QDir::cleanPath(newdir.prepend(dir));
6 ✔
1969
  if (!confirmPathInStore(newdir)) {
6 ✔
1970
    return;
1971
  }
1972
  // Behind a link the folder would be made outside the store, as Users,
1973
  // Re-encrypt and Delete already refuse.
1974
  if (refuseLinkedFolder(newdir)) {
5 ✔
1975
    return;
1976
  }
1977
  // The tree, like `pass ls`, hides names that start with a dot.
1978
  const QStringList parts =
1979
      QDir(s.passStore).relativeFilePath(newdir).split(u'/');
4 ✔
1980
  if (std::any_of(parts.cbegin(), parts.cend(), [](const QString &part) {
8 ✔
1981
        return part != u'.' && part.startsWith(u'.');
4 ✔
1982
      })) {
1983
    PlainMessageBox::warning(this, tr("Hidden folder"),
2 ✔
1984
                             tr("A folder that starts with a dot would be "
1 ✔
1985
                                "hidden from the list: %1")
1986
                                 .arg(newdir));
2 ✔
1987
    return;
1 ✔
1988
  }
1989
  // Exists already: an error, as QDir::mkdir() made it before.
1990
  if (QFileInfo::exists(newdir) || !Util::mkpathForStore(newdir)) {
3 ✔
1991
    PlainMessageBox::warning(this, tr("Error"),
2 ✔
1992
                             tr("Failed to create folder: %1").arg(newdir));
2 ✔
1993
    return;
1 ✔
1994
  }
1995
  // No .gpg-id of its own: the folder uses its parent's recipients, as with
1996
  // pass, until Users gives it a list. A copy of the parent's list (#1688)
1997
  // kept every recipient later removed above it, and its entries stayed
1998
  // readable by them.
1999
}
7 ✔
2000

2001
void MainWindow::renameFolder() {
3 ✔
2002
  bool ok;
2003
  QString srcDir = QDir::cleanPath(m_tree->currentDir(false));
3 ✔
2004
  QString srcDirName = QDir(srcDir).dirName();
3 ✔
2005
  QString newName =
2006
      QInputDialog::getText(this, tr("Rename folder"), tr("Rename folder to: "),
3 ✔
2007
                            QLineEdit::Normal, srcDirName, &ok);
6 ✔
2008
  if (!ok || newName.isEmpty()) {
3 ✔
2009
    return;
2010
  }
2011
  QString destDir = srcDir;
2012
  destDir.replace(srcDir.lastIndexOf(srcDirName), srcDirName.length(), newName);
2 ✔
2013
  if (!confirmPathInStore(destDir)) {
2 ✔
2014
    return;
2015
  }
2016
  QtPassSettings::getPass()->Move(srcDir, destDir, false);
3 ✔
2017
}
2018

2019
void MainWindow::editPassword(const QString &file) {
6 ✔
2020
  if (!file.isEmpty()) {
6 ✔
2021
    const AppSettings s = QtPassSettings::load();
6 ✔
2022
    if (s.useGit && s.autoPull) {
6 ✔
2023
      onUpdate(true);
1 ✔
2024
    }
2025
    // The dialog decrypts the entry itself to fill its fields. That decrypt
2026
    // lands on the same finishedShow the panel uses, so drop the panel's claim
2027
    // to it: otherwise passShowHandler() repaints and, with "Always copy",
2028
    // puts the entry's old password on the clipboard - replacing whatever the
2029
    // user copied to paste into the dialog.
2030
    m_shownFile.clear();
6 ✔
2031
    setPassword(file, false);
6 ✔
2032
  }
6 ✔
2033
}
6 ✔
2034

2035
void MainWindow::renamePassword() {
2 ✔
2036
  bool ok;
2037
  QString file = getFile(ui->treeView->currentIndex(), false);
2 ✔
2038
  QString filePath = QFileInfo(file).path();
2 ✔
2039
  QString fileName = QFileInfo(file).fileName();
2 ✔
2040
  if (fileName.endsWith(".gpg", Qt::CaseInsensitive)) {
4 ✔
2041
    fileName.chop(4);
2 ✔
2042
  }
2043

2044
  QString newName =
2045
      QInputDialog::getText(this, tr("Rename file"), tr("Rename file to: "),
2 ✔
2046
                            QLineEdit::Normal, fileName, &ok);
4 ✔
2047
  if (!ok || newName.isEmpty()) {
2 ✔
2048
    return;
2049
  }
2050
  QString newFile = QDir(filePath).filePath(newName);
2 ✔
2051
  if (!confirmPathInStore(newFile)) {
2 ✔
2052
    return;
2053
  }
2054
  QtPassSettings::getPass()->Move(file, newFile, false);
3 ✔
2055
}
2056

2057
void MainWindow::copySelectionOrPassword() {
5 ✔
2058
  QWidget *focus = QApplication::focusWidget();
5 ✔
2059
  // The widget's own copy: a SecretTextBrowser marks what it copies as
2060
  // secret for clipboard managers, as the context menu's Copy does.
2061
  if (auto *text = qobject_cast<QTextEdit *>(focus);
5 ✔
2062
      text != nullptr && text->textCursor().hasSelection()) {
5 ✔
2063
    text->copy();
1 ✔
2064
    return;
1 ✔
2065
  }
2066
  // Through the clipboard manager, as a copy button would: the label may be
2067
  // the OTP code, which gets the secret hint and the autoclear.
2068
  if (auto *label = qobject_cast<QLabel *>(focus);
2069
      label != nullptr && label->hasSelectedText()) {
4 ✔
2070
    m_qtPass->clipboard().copyText(label->selectedText());
1 ✔
2071
    return;
1 ✔
2072
  }
2073
  // A line of the content search results is decrypted text: through the
2074
  // clipboard manager too, for the secret hint and the autoclear.
2075
  if (focus == ui->grepResultsList) {
3 ✔
2076
    if (const QTreeWidgetItem *item = ui->grepResultsList->currentItem();
3 ✔
2077
        item != nullptr && !item->text(0).isEmpty()) {
6 ✔
2078
      m_qtPass->clipboard().copyText(item->text(0));
6 ✔
2079
    }
2080
    return;
3 ✔
2081
  }
2082
  copyPasswordFromTreeview();
×
2083
}
2084

2085
void MainWindow::copyPasswordFromTreeview() {
9 ✔
2086
  // While content search results hide the tree, its current entry is not
2087
  // what the user looks at: no decrypt, as for Edit and OTP.
2088
  if (ui->treeView->isHidden()) {
9 ✔
2089
    return;
×
2090
  }
2091
  QFileInfo fileOrFolder = m_tree->fileInfo(ui->treeView->currentIndex());
9 ✔
2092

2093
  if (fileOrFolder.isFile()) {
9 ✔
2094
    QString file = getFile(ui->treeView->currentIndex(), true);
9 ✔
2095
    // The newest Ctrl+C wins: finishedShow names its file, so the decrypt of
2096
    // an earlier request is simply not this one's.
2097
    m_copyRequestFile = file;
9 ✔
2098
    // This Show repaints the panel as well; see onOtp().
2099
    m_shownFile = file;
9 ✔
2100
    QtPassSettings::getPass()->Show(file);
18 ✔
2101
  }
2102
}
9 ✔
2103

2104
void MainWindow::passwordFromFileToClipboard(const QString &text,
32 ✔
2105
                                             const QString &file) {
2106
  if (m_copyRequestFile.isEmpty() || file != m_copyRequestFile) {
32 ✔
2107
    return;
27 ✔
2108
  }
2109
  m_copyRequestFile.clear();
8 ✔
2110
  // The first line, without a list of every line (an entry can expand into
2111
  // millions of them), and without the "\r" of a CRLF line end, as the
2112
  // password row and "Always copy" have it.
2113
  const QString first = FileContent::passwordLine(text);
8 ✔
2114
  // A `pass otp insert` entry's first line is the otpauth:// URI carrying the
2115
  // TOTP seed, and an OTP field holding a seed there is the same; copying it
2116
  // would leak 2FA material. Matches the display path
2117
  // (FileContent::getPasswordForDisplay / PasswordDisplayPanel).
2118
  if (FileContent::isOtpPasswordLine(first)) {
8 ✔
2119
    flashText(tr("This entry holds an OTP secret, not a password"), true);
6 ✔
2120
    return;
2121
  }
2122
  m_qtPass->clipboard().copyText(first);
5 ✔
2123
}
2124

2125
void MainWindow::showStatusMessage(const QString &msg, int timeout) {
34 ✔
2126
  ui->statusBar->showMessage(msg, timeout);
34 ✔
2127
}
34 ✔
2128

2129
void MainWindow::reencryptPath(const QString &dir) {
4 ✔
2130
  QDir checkDir(dir);
4 ✔
2131
  if (!checkDir.exists()) {
4 ✔
2132
    PlainMessageBox::critical(this, tr("Error"),
2 ✔
2133
                              tr("Directory does not exist: %1").arg(dir));
2 ✔
2134
    return;
1 ✔
2135
  }
2136
  if (refuseLinkedFolder(dir)) {
3 ✔
2137
    return;
2138
  }
2139

2140
  const bool yes = PlainMessageBox::askYes(
3 ✔
2141
      this, tr("Re-encrypt passwords"),
3 ✔
2142
      tr("Re-encrypt all passwords in %1?\n\n"
3 ✔
2143
         "This will re-encrypt ALL password files in this folder "
2144
         "using the current recipients defined in .gpg-id.\n\n"
2145
         "This may rewrite many files and cannot be undone easily.\n\n"
2146
         "Continue?")
2147
          // On one line: a name with line feeds pushed the warning out of
2148
          // the box, which shows 40 lines at most.
2149
          .arg(Util::displayable(QDir(dir).dirName(), false)));
6 ✔
2150

2151
  if (!yes)
3 ✔
2152
    return;
2153

2154
  // Disable now; the asynchronous startReencryptPath signal re-runs this
2155
  // harmlessly.
2156
  startReencryptPath();
1 ✔
2157

2158
  // Under the current profile's settings: with the pass backend active, the
2159
  // native one is not re-initialised on a profile switch.
2160
  QtPassSettings::getImitatePass()->reencryptPath(
2 ✔
2161
      QDir::cleanPath(QDir(dir).absolutePath()), QtPassSettings::load());
2 ✔
2162
}
4 ✔
2163

2164
// Idempotent: reencryptPath() calls it before ImitatePass emits the signal.
2165
void MainWindow::startReencryptPath() {
7 ✔
2166
  m_reencryptRunning = true;
7 ✔
2167
  setUiElementsEnabled(false);
7 ✔
2168
  // The worker always ends with endReencryptPath(), and Cancel is available
2169
  // throughout, so the generic watchdog is not needed for this operation.
2170
  m_uiWatchdog.stop();
7 ✔
2171
  ui->treeView->setDisabled(true);
7 ✔
2172
  if (m_reencryptProgress)
7 ✔
2173
    return;
2174
  auto *progress = new QProgressDialog(tr("Re-encrypting passwords..."),
5 ✔
2175
                                       tr("Cancel"), 0, 0, this);
10 ✔
2176
  progress->setWindowTitle(tr("Re-encrypt passwords"));
5 ✔
2177
  progress->setWindowModality(Qt::WindowModal);
5 ✔
2178
  progress->setAutoClose(false);
5 ✔
2179
  progress->setAutoReset(false);
5 ✔
2180
  progress->setMinimumDuration(0);
5 ✔
2181
  connect(progress, &QProgressDialog::canceled, this, [this]() {
5 ✔
2182
    QtPassSettings::getImitatePass()->cancelReencryptPath();
1 ✔
2183
    showStatusMessage(tr("Cancelling re-encryption"), 5000);
1 ✔
2184
  });
1 ✔
2185
  m_reencryptProgress = progress;
2186
  progress->show();
5 ✔
2187
}
2188

2189
void MainWindow::reencryptProgress(int current, int total) {
7 ✔
2190
  if (!m_reencryptProgress || m_inProgressUpdate)
7 ✔
2191
    return;
2192
  QProgressDialog *progress = m_reencryptProgress;
2193
  progress->setMaximum(total);
6 ✔
2194
  progress->setLabelText(
6 ✔
2195
      tr("Re-encrypting passwords: %1 of %2").arg(current).arg(total));
6 ✔
2196
  // On a modal dialog setValue() runs processEvents(), which can deliver
2197
  // endReencryptPath(), even inside a nested event loop that would delete a
2198
  // deleteLater()ed dialog under setValue()'s feet: keep this last, and
2199
  // delete the dialog only after it returns.
2200
  m_inProgressUpdate = true;
6 ✔
2201
  progress->setValue(current);
6 ✔
2202
  m_inProgressUpdate = false;
6 ✔
2203
  if (m_progressToDelete) {
6 ✔
2204
    m_progressToDelete->deleteLater();
2 ✔
2205
    m_progressToDelete = nullptr;
2206
  }
2207
}
2208

2209
void MainWindow::endReencryptPath() {
5 ✔
2210
  m_reencryptRunning = false;
5 ✔
2211
  if (m_reencryptProgress) {
5 ✔
2212
    m_reencryptProgress->hide();
5 ✔
2213
    if (m_inProgressUpdate) {
5 ✔
2214
      m_progressToDelete = m_reencryptProgress;
2215
    } else {
2216
      m_reencryptProgress->deleteLater();
3 ✔
2217
    }
2218
    m_reencryptProgress = nullptr;
2219
  }
2220
  setUiElementsEnabled(true);
5 ✔
2221
}
5 ✔
2222

2223
void MainWindow::exportPublicKey() {
3 ✔
2224
  const AppSettings s = QtPassSettings::load();
3 ✔
2225
  const QString identity = s.passSigningKey;
2226
  if (identity.isEmpty()) {
3 ✔
2227
    QMessageBox::information(
2 ✔
2228
        this, tr("Export public key"),
1 ✔
2229
        tr("<h3>Export your public key</h3>"
×
2230
           "<p>No signing key is configured. Set one in QtPass Settings "
2231
           "&gt; GPG keys, or run this in a terminal:</p>"
2232
           "<pre>gpg --armor --export --output my_key.asc &lt;your-key-id"
2233
           "&gt;</pre>"
2234
           "<p>Then send the file to your teammates.</p>"));
2235
    return;
1 ✔
2236
  }
2237
  QString gpgExe = s.gpgExecutable;
2238
  if (gpgExe.isEmpty()) {
2 ✔
2239
    gpgExe = QStringLiteral("gpg");
×
2240
  }
2241
  QStringList args = {"--armor", "--export"};
10 ✔
2242
  args.append(identity.split(' ', Qt::SkipEmptyParts));
2 ✔
2243
  QString stdOut;
2 ✔
2244
  QString stdErr;
2 ✔
2245
  int exitCode = Executor::executeBlocking(gpgExe, args, &stdOut, &stdErr);
2 ✔
2246
  if (exitCode != 0 || stdOut.isEmpty()) {
2 ✔
2247
    PlainMessageBox::warning(this, tr("Export public key"),
2 ✔
2248
                             tr("Could not export public key for %1.\n\n%2")
1 ✔
2249
                                 .arg(identity, stdErr.isEmpty()
2 ✔
2250
                                                    ? tr("No output from gpg.")
2 ✔
2251
                                                    : stdErr));
2252
    return;
2253
  }
2254
  ExportPublicKeyDialog dialog(identity, stdOut, this);
1 ✔
2255
  dialog.exec();
1 ✔
2256
}
4 ✔
2257

2258
// UsersDialog only ticks keys already in the keyring; importing a foreign
2259
// key still has to happen via gpg (or QtPass settings) first.
2260
void MainWindow::addRecipient(const QString &dir) {
2 ✔
2261
  if (refuseLinkedFolder(dir)) {
2 ✔
2262
    return;
1 ✔
2263
  }
2264
  UsersDialog d(QtPassSettings::getPass(), QtPassSettings::load(), dir, this);
1 ✔
2265
  d.exec();
1 ✔
2266
}
1 ✔
2267

2268
// A tree-picked folder that is, or lies behind, a symlink or junction is not
2269
// a folder of the store. The store root itself may be a link (a synced
2270
// folder); that is configuration, not a tree pick.
2271
auto MainWindow::refuseLinkedFolder(const QString &dir) -> bool {
20 ✔
2272
  if (!Util::isUnderLink(dir, QtPassSettings::load().passStore)) {
20 ✔
2273
    return false;
2274
  }
2275
  PlainMessageBox::critical(
3 ✔
2276
      this, tr("Not a folder of the store"),
3 ✔
2277
      tr("%1 is, or lies behind, a symbolic link or junction. What that "
3 ✔
2278
         "points to is not part of the password store and is left alone.")
2279
          .arg(QDir::toNativeSeparators(QDir::cleanPath(dir))));
6 ✔
2280
  return true;
3 ✔
2281
}
2282

2283
void MainWindow::showShareHelp() {
1 ✔
2284
  QMessageBox::information(
2 ✔
2285
      this, tr("Sharing passwords with GPG"),
1 ✔
2286
      tr("<h3>Sharing passwords with GPG</h3>"
1 ✔
2287
         "<p>To share passwords with other users:</p>"
2288
         "<ol>"
2289
         "<li><b>Export your public key</b> and send it to teammates</li>"
2290
         "<li><b>Import teammates' public keys</b> into your GPG keyring</li>"
2291
         "<li><b>Re-encrypt passwords</b> so all recipients can decrypt "
2292
         "them</li>"
2293
         "</ol>"
2294
         "<p>Only people who have a matching secret key can decrypt the "
2295
         "passwords.</p>"
2296
         "<p><b>Tip:</b> Use the same GPG key for all shared folders.</p>"
2297
         "<p>See the FAQ for more details.</p>"));
2298
}
1 ✔
2299

2300
void MainWindow::updateGitButtonVisibility(bool uiEnabled) {
452 ✔
2301
  const AppSettings s = QtPassSettings::load();
452 ✔
2302
  // Without Git there is nothing to push or pull, ever: the buttons go, not
2303
  // grey out. While an operation runs they stay and are disabled.
2304
  const bool usable =
2305
      s.useGit && !(s.gitExecutable.isEmpty() && s.passExecutable.isEmpty());
452 ✔
2306
  ui->actionPush->setVisible(usable);
452 ✔
2307
  ui->actionUpdate->setVisible(usable);
452 ✔
2308
  // The separator in front of them would otherwise sit next to the next one.
2309
  const QList<QAction *> actions = ui->toolBar->actions();
452 ✔
2310
  const qsizetype at = actions.indexOf(ui->actionPush);
452 ✔
2311
  if (at > 0 && actions.at(at - 1)->isSeparator()) {
452 ✔
2312
    actions.at(at - 1)->setVisible(usable);
452 ✔
2313
  }
2314
  enableGitButtons(usable && uiEnabled);
452 ✔
2315
}
452 ✔
2316

2317
void MainWindow::updateOtpButtonVisibility(bool uiEnabled) {
462 ✔
2318
  // No platform gating: codes are generated in-process. Visible but disabled
2319
  // when OTP is off: the panel never shows an OTP field (a secret), so hiding
2320
  // this too would leave no trace of the feature. Honour uiEnabled, or the
2321
  // user can stack Show calls while a decrypt is in flight.
2322
  ui->actionOtp->setVisible(true);
462 ✔
2323
  ui->actionOtp->setEnabled(QtPassSettings::isUseOtp() && uiEnabled);
568 ✔
2324
}
462 ✔
2325

2326
void MainWindow::updateGrepButtonVisibility() {
202 ✔
2327
  const bool enabled = QtPassSettings::isUseGrepSearch();
202 ✔
2328
  ui->grepButton->setVisible(enabled);
202 ✔
2329
  ui->grepCaseButton->setVisible(enabled);
202 ✔
2330
  if (!enabled && m_grep.inGrepMode()) {
202 ✔
2331
    ui->grepButton->setChecked(false);
1 ✔
2332
  }
2333
}
202 ✔
2334

2335
void MainWindow::enableGitButtons(const bool &state) {
452 ✔
2336
  ui->actionPush->setEnabled(state);
452 ✔
2337
  ui->actionUpdate->setEnabled(state);
452 ✔
2338
}
452 ✔
2339

2340
void MainWindow::critical(const QString &title, const QString &msg) {
4 ✔
2341
  // Pass's messages quote store paths; see PlainMessageBox.
2342
  PlainMessageBox::critical(this, title, msg);
4 ✔
2343
}
4 ✔
2344

2345
void MainWindow::onProcessOutput(const QString &output, bool isError,
7 ✔
2346
                                 Enums::PROCESS pid) {
2347
  if (!QtPassSettings::isShowProcessOutput()) {
7 ✔
2348
    return;
2349
  }
2350
  m_processOutput->append(output, isError,
6 ✔
2351
                          ProcessOutputPanel::processName(pid));
12 ✔
2352
}
2353

2354
void MainWindow::updateProcessOutputVisibility() {
5 ✔
2355
  // The action's toggled handler shows or hides the dock.
2356
  ui->actionShowProcessOutput->setChecked(
5 ✔
2357
      QtPassSettings::isShowProcessOutput());
5 ✔
2358
  m_processOutput->setVisible(QtPassSettings::isShowProcessOutput());
5 ✔
2359
}
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