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

IJHack / QtPass / 46628912606

01 Dec 2026 10:40AM UTC coverage: 94.514% (+0.006%) from 94.508%
46628912606

Pull #2432

github

web-flow
Merge 94109470a into 11c8c2071
Pull Request #2432: Tree menu actions run on the entry the menu was opened on

32 of 33 new or added lines in 1 file covered. (96.97%)

19 existing lines in 1 file now uncovered.

11440 of 12104 relevant lines covered (94.51%)

23930.19 hits per line

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

95.6
/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 "processinfo.h"
26
#include "processoutputpanel.h"
27
#include "qpushbuttonasqrcode.h"
28
#include "qpushbuttonshowpassword.h"
29
#include "qpushbuttonwithclipboard.h"
30
#include "qtpass.h"
31
#include "qtpasssettings.h"
32
#include "templateio.h"
33
#include "totp.h"
34
#include "trayicon.h"
35
#include "ui_mainwindow.h"
36
#include "usersdialog.h"
37
#include "util.h"
38
#include "windowstatestore.h"
39
#include <QApplication>
40
#include <QCloseEvent>
41
#include <QDate>
42
#include <QDesktopServices>
43
#include <QDialog>
44
#include <QDockWidget>
45
#include <QFileInfo>
46
#include <QFileSystemModel>
47
#include <QHBoxLayout>
48
#include <QInputDialog>
49
#include <QLabel>
50
#include <QLineEdit>
51
#include <QMenu>
52
#include <QMenuBar>
53
#include <QMessageBox>
54
#include <QProgressDialog>
55
#include <QPushButton>
56
#include <QScrollBar>
57
#include <QShortcut>
58
#include <QTextBlock>
59
#include <QTextCharFormat>
60
#include <QTextCursor>
61
#include <QTextDocument>
62
#include <QTextEdit>
63
#include <QTextStream>
64
#include <QTimer>
65
#include <QTreeWidget>
66
#include <QUrl>
67
#include <algorithm>
68
#include <utility>
69

70
/**
71
 * @brief What the Stop button calls a run.
72
 * @param pid The kind of command that runs.
73
 * @return Its command line label ("git pull", "pass init"); "a decrypt" for
74
 *         a decrypt, whose label the output panel leaves empty; "a command"
75
 *         when the kind is unknown.
76
 */
77
static auto runLabel(Enums::PROCESS pid) -> QString {
14 ✔
78
  if (pid == Enums::PASS_SHOW) {
14 ✔
79
    return QCoreApplication::translate("MainWindow", "a decrypt");
4 ✔
80
  }
81
  const QString label = Enums::processLabel(pid);
10 ✔
82
  return label.isEmpty()
83
             ? QCoreApplication::translate("MainWindow", "a command")
10 ✔
84
             : label;
×
85
}
86

87
MainWindow::MainWindow(const QString &searchText, QWidget *parent)
206 ✔
88
    : QMainWindow(parent), ui(new Ui::MainWindow) {
206 ✔
89
#ifdef __APPLE__
90
  // extra treatment for mac os
91
  // see https://doc.qt.io/qt-6/qkeysequence.html#qt_set_sequence_auto_mnemonic
92
  qt_set_sequence_auto_mnemonic(true);
93
#endif
94
  ui->setupUi(this);
206 ✔
95

96
  m_qtPass = new QtPass(this);
206 ✔
97
  restoreWindow();
206 ✔
98
  connectBackends();
206 ✔
99

100
  // Every Copy binding, not only the first (Ctrl+C): Ctrl+Insert and F16
101
  // otherwise reached the views' own copy, which put decrypted text on the
102
  // clipboard bare, without the secret hint or the autoclear.
103
  const QList<QKeySequence> copyKeys =
104
      QKeySequence::keyBindings(QKeySequence::StandardKey::Copy);
206 ✔
105
  for (const QKeySequence &keys : copyKeys) {
618 ✔
106
    new QShortcut(keys, this, this, &MainWindow::copySelectionOrPassword);
412 ✔
107
  }
108

109
  m_tree = new StoreTree(ui->treeView, this);
206 ✔
110
  m_tree->setStore(QtPassSettings::getPassStore(Util::findPasswordStore()));
206 ✔
111
  m_tree->setPass(QtPassSettings::getPass());
206 ✔
112
  connect(ui->treeView, &QWidget::customContextMenuRequested, this,
206 ✔
113
          &MainWindow::showContextMenu);
206 ✔
114
  connect(ui->treeView, &DeselectableTreeView::emptyClicked, this,
206 ✔
115
          &MainWindow::deselect);
206 ✔
116

117
  initTextBrowser();
206 ✔
118

119
  updateProfileBox();
206 ✔
120

121
  initDisplayPanel();
206 ✔
122

123
  QtPassSettings::getPass()->updateEnv();
206 ✔
124

125
  // Install the search-box key filter once, not on every setUiElementsEnabled
126
  // call.
127
  ui->lineEdit->installEventFilter(this);
206 ✔
128
  // Both live in Breeze's "tools area" and get its header palette; see the
129
  // PaletteChange branch in eventFilter().
130
  ui->toolBar->installEventFilter(this);
206 ✔
131
  menuBar()->installEventFilter(this);
206 ✔
132

133
  initTimers();
206 ✔
134

135
  initToolBarButtons();
206 ✔
136
  initStatusBar();
206 ✔
137
  initProcessOutput();
206 ✔
138

139
  ui->lineEdit->setClearButtonEnabled(true);
206 ✔
140
  updateGrepButtonVisibility();
206 ✔
141

142
  setUiElementsEnabled(true);
206 ✔
143

144
  // No QApplication::quit() here: before exec() it is a documented no-op.
145
  // main() checks initSucceeded() and exits before show() instead.
146
  m_qtPass->init();
206 ✔
147
  // OK is not gated on Util::configIsValid(): an accepted configuration can
148
  // still lack a .gpg-id, so ask again; only a cancel ends the loop.
149
  while (!Util::configIsValid(QtPassSettings::load())) {
207 ✔
150
    if (!config()) {
2 ✔
151
      return;
152
    }
153
  }
154
  // Set up, with or without the wizard (a fresh install can find a store
155
  // that already works): a later run of the wizard keeps the saved backend
156
  // and Git choices. A cancelled first run returned above and keeps it.
157
  QtPassSettings::getInstance()->remove(SettingsConstants::firstRunPending);
205 ✔
158
  m_freshStart = false;
205 ✔
159
  m_initSucceeded = true;
205 ✔
160

161
  // Searched as qtpass(1) promises, once the window and its tree are up:
162
  // filtered at once and an entry named exactly so opened. Setting the
163
  // text here left it to the search timer, which only highlights. Queued
164
  // only now: from before the configuration loop, a wizard's nested event
165
  // loop ran it while no store was set yet.
166
  if (!searchText.isEmpty()) {
205 ✔
167
    QTimer::singleShot(0, this,
168
                       [this, searchText] { applySearchText(searchText); });
×
169
  }
170

171
  // Initial focus is set in showEvent(): a 10 ms QTimer here could fire
172
  // before the window was realised (queued ActivationChange, nested exec() in
173
  // init()) and selectAll() segfaulted inside Qt (#1187, #1188).
174
}
×
175

176
void MainWindow::connectBackends() {
206 ✔
177
  connect(m_qtPass, &QtPass::outputReady, this,
206 ✔
178
          [this](const QString &html) { flashText(html, false, true); });
252 ✔
179
  connect(m_qtPass, &QtPass::operationFinished, this,
206 ✔
180
          [this]() { setUiElementsEnabled(true); });
277 ✔
181
  connect(m_qtPass, &QtPass::statusMessage, this,
206 ✔
182
          &MainWindow::showStatusMessage);
206 ✔
183
  connect(m_qtPass, &QtPass::pushRequested, this, &MainWindow::onAutoPush);
206 ✔
184
  // With automatic push, the push is queued first and the refresh would start
185
  // as soon as it ends, emptying the browser before a failed push's error was
186
  // painted. So the refresh waits for the push (see connectPassSignals()). It
187
  // claims the panel now, as its decrypt would: whatever drops a pending
188
  // decrypt (another entry, a search, Escape, Edit, an error) drops it too.
189
  connect(m_qtPass, &QtPass::entryInserted, this, [this]() {
206 ✔
190
    const QModelIndex index = getCurrentTreeViewIndex();
11 ✔
191
    const QString file = getFile(index, true);
11 ✔
192
    Pass *pass = QtPassSettings::getPass();
11 ✔
193
    // Only the entry the save wrote is shown again, when it is the selected
194
    // one. After Add, or a save that reports once another row is selected,
195
    // the selected row is another entry: showing it decrypted it once more
196
    // and, with "Always copy", put its password on the clipboard.
197
    if (const QString saved = pass->reportedInsert();
11 ✔
198
        !saved.isEmpty() &&
3 ✔
199
        QDir::cleanPath(saved) != QDir::cleanPath(getFile(index, false))) {
20 ✔
200
      return;
201
    }
202
    if (!file.isEmpty() && pass->isPushing()) {
20 ✔
203
      m_refreshAfterPush = file;
8 ✔
204
      m_refreshAfterPushOwner = pass;
8 ✔
205
      m_shownFile = file;
8 ✔
206
      return;
8 ✔
207
    }
208
    on_treeView_clicked(index);
2 ✔
209
  });
210
  connect(&m_qtPass->clipboard(), &ClipboardManager::statusMessage, this,
206 ✔
211
          [this](const QString &message) { showStatusMessage(message); });
229 ✔
212
  // Both backends: the active one can change through the configuration
213
  // dialog without a restart.
214
  connectPassSignals(QtPassSettings::getRealPass());
206 ✔
215
  connectPassSignals(QtPassSettings::getImitatePass());
206 ✔
216
  ImitatePass *ipass = QtPassSettings::getImitatePass();
206 ✔
217
  connect(ipass, &ImitatePass::startReencryptPath, this,
206 ✔
218
          &MainWindow::startReencryptPath);
206 ✔
219
  connect(ipass, &ImitatePass::reencryptProgress, this,
206 ✔
220
          &MainWindow::reencryptProgress);
206 ✔
221
  connect(ipass, &ImitatePass::endReencryptPath, this,
206 ✔
222
          &MainWindow::endReencryptPath);
206 ✔
223
  connect(ipass, &ImitatePass::unexpectedRecipients, this,
206 ✔
224
          &MainWindow::askReencryptUnexpected);
206 ✔
225
}
206 ✔
226

227
void MainWindow::initTextBrowser() {
206 ✔
228
  {
229
    const AppSettings s = QtPassSettings::load();
206 ✔
230
    if (s.useMonospace) {
206 ✔
231
      QFont monospace("Monospace");
1 ✔
232
      monospace.setStyleHint(QFont::Monospace);
1 ✔
233
      ui->textBrowser->setFont(monospace);
1 ✔
234
    }
1 ✔
235
    if (s.noLineWrapping) {
206 ✔
236
      ui->textBrowser->setLineWrapMode(QTextBrowser::NoWrap);
1 ✔
237
    }
238
    clearPanelTimer.setInterval(MS_PER_SECOND * s.autoclearPanelSeconds);
206 ✔
239
    clearResultsTimer.setInterval(clearPanelTimer.interval());
206 ✔
240
  }
206 ✔
241
  ui->textBrowser->setOpenExternalLinks(true);
206 ✔
242
  ui->textBrowser->setContextMenuPolicy(Qt::CustomContextMenu);
206 ✔
243
  connect(ui->textBrowser, &QWidget::customContextMenuRequested, this,
206 ✔
244
          &MainWindow::showBrowserContextMenu);
206 ✔
245
}
206 ✔
246

247
void MainWindow::initDisplayPanel() {
206 ✔
248
  m_displayPanel = new PasswordDisplayPanel(
206 ✔
249
      ui->gridLayout, ui->verticalLayoutPassword, this, this);
206 ✔
250
  connect(m_displayPanel, &PasswordDisplayPanel::copyRequested,
206 ✔
251
          &m_qtPass->clipboard(), &ClipboardManager::copyText);
206 ✔
252
  connect(m_displayPanel, &PasswordDisplayPanel::textCopied,
206 ✔
253
          &m_qtPass->clipboard(), &ClipboardManager::trackCopied);
206 ✔
254
  connect(ui->textBrowser, &SecretTextBrowser::copied, &m_qtPass->clipboard(),
206 ✔
255
          &ClipboardManager::trackCopied);
206 ✔
256
  connect(m_displayPanel, &PasswordDisplayPanel::qrRequested, m_qtPass,
206 ✔
257
          &QtPass::showTextAsQRCode);
206 ✔
258
  // Double-click on what is shown edits it, as in the tree.
259
  // The entry whose rows were double-clicked, not the tree's current row:
260
  // arrow keys and a right-click move that row without repainting the panel.
261
  connect(m_displayPanel, &PasswordDisplayPanel::editRequested, this, [this] {
206 ✔
262
    if (ui->actionEdit->isEnabled() && !m_panelEntry.isEmpty()) {
4 ✔
263
      editPassword(m_panelEntry);
3 ✔
264
    }
265
  });
4 ✔
266
}
206 ✔
267

268
void MainWindow::initTimers() {
206 ✔
269
  clearPanelTimer.setSingleShot(true);
206 ✔
270
  connect(&clearPanelTimer, &QTimer::timeout, this,
206 ✔
271
          [this]() { clearShownEntry(true); });
208 ✔
272
  clearResultsTimer.setSingleShot(true);
206 ✔
273
  connect(&clearResultsTimer, &QTimer::timeout, this,
206 ✔
274
          &MainWindow::clearContentResults);
206 ✔
275

276
  searchTimer.setInterval(350);
206 ✔
277
  searchTimer.setSingleShot(true);
206 ✔
278

279
  connect(&searchTimer, &QTimer::timeout, this, &MainWindow::onTimeoutSearch);
206 ✔
280

281
  // Safety net: if a backend operation disables the UI but never signals
282
  // completion, re-enable after a timeout so the window can't get stuck.
283
  m_uiWatchdog.setSingleShot(true);
206 ✔
284
  m_uiWatchdog.setInterval(UiWatchdogMs);
206 ✔
285
  connect(&m_uiWatchdog, &QTimer::timeout, this, [this]() {
206 ✔
286
    showStatusMessage(tr("Operation timed out; re-enabling interface."));
6 ✔
287
    // What still runs can be stopped: a store entry built to keep gpg busy
288
    // holds up everything queued behind it. No timer stops it by itself, as
289
    // a decrypt may be waiting for a passphrase.
290
    if (Pass *pass = QtPassSettings::getPass();
6 ✔
291
        pass != nullptr && !pass->isIdle()) {
6 ✔
292
      m_stopButton->setToolTip(tr("Stop %1, which is still running")
12 ✔
293
                                   .arg(runLabel(pass->runningProcess())));
18 ✔
294
      m_stopButton->show();
6 ✔
295
    }
296
    // Drop any in-flight OTP request so a late finishedShow cannot be mistaken
297
    // for the answer to it.
298
    cancelOtpRequest();
6 ✔
299
    setUiElementsEnabled(true);
6 ✔
300
  });
6 ✔
301
}
206 ✔
302

303
void MainWindow::initProcessOutput() {
206 ✔
304
  m_processOutput = new ProcessOutputPanel(this);
206 ✔
305
  addDockWidget(Qt::BottomDockWidgetArea, m_processOutput);
206 ✔
306
  // After addDockWidget so our preference wins over any cached state
307
  // QMainWindow applies; restoreWindow() already processed the saved layout.
308
  m_processOutput->setVisible(QtPassSettings::isShowProcessOutput());
206 ✔
309
  // From the setting, not isVisible(): the window is not shown yet, so no
310
  // child of it reports visible.
311
  ui->actionShowProcessOutput->setChecked(
206 ✔
312
      QtPassSettings::isShowProcessOutput());
206 ✔
313
  connect(ui->actionShowProcessOutput, &QAction::toggled, this,
206 ✔
314
          [this](bool show) {
206 ✔
315
            m_processOutput->setVisible(show);
2 ✔
316
            AppSettings s = QtPassSettings::load();
2 ✔
317
            if (s.showProcessOutput != show) {
2 ✔
318
              s.showProcessOutput = show;
2 ✔
319
              QtPassSettings::save(s);
2 ✔
320
            }
321
          });
2 ✔
322

323
  connect(QtPassSettings::getPass(), &Pass::finishedAnyWithPid, this,
206 ✔
324
          [this](const QString &out, const QString &err, Enums::PROCESS pid) {
206 ✔
325
            // Never route potentially-secret output through the panel:
326
            // PASS_SHOW goes to the text browser (cleared on a timer when
327
            // "Autoclear panel" is set),
328
            // PASS_GREP would return password-file lines (#252; it is no
329
            // longer started, the check stays), and PASS_INSERT
330
            // is excluded defensively in case a future path uses --echo.
331
            if (ProcessOutputPanel::isSensitiveProcess(pid)) {
17 ✔
332
              return;
333
            }
334
            if (!out.isEmpty()) {
16 ✔
335
              onProcessOutput(out, false, pid);
1 ✔
336
            }
337
            if (!err.isEmpty()) {
16 ✔
338
              onProcessOutput(err, true, pid);
4 ✔
339
            }
340
          });
341
}
206 ✔
342

343
MainWindow::~MainWindow() {
408 ✔
344
  // Quit from the tray menu or a SIGTERM never delivers closeEvent(); the
345
  // window still knows its last geometry here.
346
  saveWindowState();
206 ✔
347
  delete m_qtPass;
206 ✔
348
}
614 ✔
349

350
// The signals of one backend that the window answers itself.
351
void MainWindow::connectPassSignals(Pass *pass) {
412 ✔
352
  // A failed decrypt never emits finishedShow; drop the pending OTP/copy
353
  // request so a later decrypt of the same entry is not taken as its answer.
354
  connect(pass, &Pass::processErrorExit, this, &MainWindow::onOperationError);
412 ✔
355
  connect(pass, &Pass::critical, this, &MainWindow::critical);
412 ✔
356
  connect(pass, &Pass::startingExecuteWrapper, this,
412 ✔
357
          &MainWindow::executeWrapperStarted);
412 ✔
358
  // The profile box comes back when the queue is done, also after the
359
  // watchdog released the rest of the interface early.
360
  connect(pass, &Pass::idle, this, &MainWindow::updateProfileBoxEnabled);
412 ✔
361
  // The button names what it stops, also once the queue moved on.
362
  connect(pass, &Pass::startingExecuteWrapper, this, [this, pass]() {
412 ✔
363
    if (m_stopButton != nullptr && !m_stopButton->isHidden()) {
76 ✔
364
      m_stopButton->setToolTip(tr("Stop %1, which is still running")
4 ✔
365
                                   .arg(runLabel(pass->runningProcess())));
6 ✔
366
    }
367
  });
76 ✔
368
  // Nothing left to stop.
369
  connect(pass, &Pass::idle, this, [this]() {
412 ✔
370
    if (m_stopButton != nullptr) {
50 ✔
371
      m_stopButton->hide();
50 ✔
372
    }
373
  });
50 ✔
374
  connect(pass, &Pass::statusMsg, this, &MainWindow::showStatusMessage);
412 ✔
375
  connect(pass, &Pass::finishedShow, this, &MainWindow::passShowHandler);
412 ✔
376
  // Both check the file against their own pending request and ignore the
377
  // rest, so they can stay connected for good.
378
  connect(pass, &Pass::finishedShow, this, &MainWindow::otpFromFileToClipboard);
412 ✔
379
  connect(pass, &Pass::finishedShow, this,
412 ✔
380
          &MainWindow::passwordFromFileToClipboard);
412 ✔
381
  connect(pass, &Pass::finishedGrep, this, &MainWindow::onGrepFinished);
412 ✔
382
  // The refresh a save left waiting runs once the last push went through,
383
  // by name as it was queued before (the save's rewrite of the file may have
384
  // replaced its row in the tree), and only while the entry still holds the
385
  // panel and nothing else is queued: queued work would run first, and the
386
  // refresh would empty the browser of its error. A failed push dropped it
387
  // (onOperationError()).
388
  connect(pass, &Pass::finishedGitPush, this, [this, pass]() {
412 ✔
389
    if (m_refreshAfterPush.isEmpty() || m_refreshAfterPushOwner != pass ||
31 ✔
390
        pass->isPushing()) {
9 ✔
391
      return;
5 ✔
392
    }
393
    const QString file = std::exchange(m_refreshAfterPush, QString());
7 ✔
394
    m_refreshAfterPushOwner = nullptr;
7 ✔
395
    if (file == m_shownFile && pass->isIdle()) {
7 ✔
396
      ui->passwordName->setText(Util::shownName(file));
4 ✔
397
      pass->Show(file);
8 ✔
398
    }
399
  });
400
}
412 ✔
401

402
// Idempotent; called from closeEvent() and the destructor.
403
void MainWindow::saveWindowState() {
210 ✔
404
  QtPassSettings::setGeometry(saveGeometry());
210 ✔
405
  QtPassSettings::setSavestate(saveState());
210 ✔
406
}
210 ✔
407

408
void MainWindow::focusInput() {
82 ✔
409
  // findChild() rather than ui->lineEdit: on a fresh-config first launch
410
  // config() calls setWindowFlags(), which rebuilds the native window, and
411
  // under Qt 6.11 the QLineEdit was destroyed while ui->lineEdit kept its old
412
  // address (SIGSEGV in QWidget::testAttribute). findChild() returns null.
413
  if (!isVisible()) {
82 ✔
414
    return;
415
  }
416
  auto *lineEdit = findChild<QLineEdit *>(QStringLiteral("lineEdit"));
82 ✔
417
  if (lineEdit == nullptr || !lineEdit->isVisible()) {
82 ✔
418
    return;
419
  }
420
  lineEdit->selectAll();
82 ✔
421
  lineEdit->setFocus();
82 ✔
422
  // Only once focus has landed: set in showEvent(), an early return above
423
  // would consume the one-shot and never retry.
424
  m_firstShowCompleted = true;
82 ✔
425
}
426

427
auto MainWindow::event(QEvent *event) -> bool {
9,573 ✔
428
  if (event->type() == QEvent::ApplicationPaletteChange) {
9,573 ✔
429
    m_themeSwitched = true;
11 ✔
430
    // Breeze may re-stamp the bars before this arrives (Plasma 6 does):
431
    // their PaletteChange then found no switch yet, so check them now too.
432
    QTimer::singleShot(0, this, &MainWindow::dropStaleToolsAreaPalettes);
11 ✔
433
  }
434
  return QMainWindow::event(event);
9,573 ✔
435
}
436

437
void MainWindow::changeEvent(QEvent *event) {
276 ✔
438
  QWidget::changeEvent(event);
276 ✔
439
  if (event->type() == QEvent::PaletteChange && m_displayPanel != nullptr) {
276 ✔
440
    // Desktop switched light/dark. Top-level widgets get PaletteChange
441
    // (ApplicationPaletteChange goes to QApplication); stylesheets with
442
    // baked-in palette colours must be re-derived by hand.
443
    m_displayPanel->refreshPalette();
10 ✔
444
  }
445
  if (event->type() == QEvent::ActivationChange && isActiveWindow() &&
276 ✔
446
      isVisible()) {
447
    // Defer a tick so the activation dispatch chain unwinds first: calling
448
    // focusInput() inline has segfaulted on half-rebuilt ui state.
449
    QMetaObject::invokeMethod(this, &MainWindow::focusInput,
47 ✔
450
                              Qt::QueuedConnection);
451
  }
452
}
276 ✔
453

454
void MainWindow::showEvent(QShowEvent *event) {
49 ✔
455
  QMainWindow::showEvent(event);
49 ✔
456
  if (m_firstShowCompleted) {
49 ✔
457
    return;
458
  }
459
  // Queued so the platform map and pending rebuilds (setWindowFlags on the
460
  // wizard path) settle first. focusInput() sets the latch only on success,
461
  // so a failed lookup retries on the next show.
462
  QMetaObject::invokeMethod(this, &MainWindow::focusInput,
47 ✔
463
                            Qt::QueuedConnection);
464
}
465

466
void MainWindow::initToolBarButtons() {
206 ✔
467
  connect(ui->actionAddPassword, &QAction::triggered, this,
206 ✔
468
          &MainWindow::addPassword);
206 ✔
469
  connect(ui->actionAddFolder, &QAction::triggered, this,
206 ✔
470
          &MainWindow::addFolder);
206 ✔
471
  connect(ui->actionEdit, &QAction::triggered, this, &MainWindow::onEdit);
206 ✔
472
  connect(ui->actionDelete, &QAction::triggered, this, &MainWindow::onDelete);
206 ✔
473
  connect(ui->actionPush, &QAction::triggered, this, &MainWindow::onPush);
206 ✔
474
  connect(ui->actionUpdate, &QAction::triggered, this, &MainWindow::onUpdate);
206 ✔
475
  connect(ui->actionUsers, &QAction::triggered, this, &MainWindow::onUsers);
206 ✔
476
  connect(ui->actionConfig, &QAction::triggered, this, &MainWindow::onConfig);
206 ✔
477
  connect(ui->actionOtp, &QAction::triggered, this, &MainWindow::onOtp);
206 ✔
478

479
  // Menu-only. Quit ends the application, tray icon or not, as in KeePassXC,
480
  // Telegram and the KDE, GNOME and macOS guidelines (#1788). Close is
481
  // close(), a hide when "hide on close" is set, like the X button and Alt+F4.
482
  connect(ui->actionQuit, &QAction::triggered, qApp, &QApplication::quit);
206 ✔
483
  connect(ui->actionClose, &QAction::triggered, this, &MainWindow::close);
206 ✔
484
#ifdef Q_OS_MACOS
485
  // The menu bar is the system's up there; nothing to hide.
486
  ui->actionShowMenuBar->setVisible(false);
487
#else
488
  // The action lives in the menu it hides, so it has to be on the window as
489
  // well for Ctrl+M to keep working while the bar is gone.
490
  addAction(ui->actionShowMenuBar);
206 ✔
491
  ui->actionShowMenuBar->setChecked(QtPassSettings::load().showMenuBar);
206 ✔
492
  menuBar()->setVisible(ui->actionShowMenuBar->isChecked());
206 ✔
493
  connect(ui->actionShowMenuBar, &QAction::toggled, this, [this](bool show) {
206 ✔
494
    menuBar()->setVisible(show);
5 ✔
495
    AppSettings s = QtPassSettings::load();
5 ✔
496
    s.showMenuBar = show;
5 ✔
497
    QtPassSettings::save(s);
5 ✔
498
  });
5 ✔
499
  new MenuBarPeek(this, ui->actionShowMenuBar);
206 ✔
500
#endif
501
  connect(ui->actionFaq, &QAction::triggered, this, [] {
207 ✔
502
    QDesktopServices::openUrl(QUrl(QStringLiteral("https://qtpass.org/faq")));
2 ✔
503
  });
1 ✔
504
  connect(ui->actionAbout, &QAction::triggered, this, &MainWindow::showAbout);
206 ✔
505
  connect(ui->actionAboutQt, &QAction::triggered, qApp, &QApplication::aboutQt);
206 ✔
506

507
  ui->actionAddPassword->setIcon(
206 ✔
508
      QIcon::fromTheme("document-new", QIcon(":/icons/document-new.svg")));
824 ✔
509
  ui->actionAddFolder->setIcon(
206 ✔
510
      QIcon::fromTheme("folder-new", QIcon(":/icons/folder-new.svg")));
824 ✔
511
  ui->actionEdit->setIcon(QIcon::fromTheme(
206 ✔
512
      "document-properties", QIcon(":/icons/document-properties.svg")));
618 ✔
513
  ui->actionDelete->setIcon(
206 ✔
514
      QIcon::fromTheme("edit-delete", QIcon(":/icons/edit-delete.svg")));
824 ✔
515
  ui->actionPush->setIcon(
206 ✔
516
      QIcon::fromTheme("go-up", QIcon(":/icons/go-top.svg")));
824 ✔
517
  ui->actionUpdate->setIcon(
206 ✔
518
      QIcon::fromTheme("go-down", QIcon(":/icons/go-bottom.svg")));
824 ✔
519
  ui->actionUsers->setIcon(QIcon::fromTheme(
206 ✔
520
      "x-office-address-book", QIcon(":/icons/x-office-address-book.svg")));
618 ✔
521
  ui->actionConfig->setIcon(QIcon::fromTheme(
206 ✔
522
      "applications-system", QIcon(":/icons/applications-system.svg")));
412 ✔
523
}
206 ✔
524

525
void MainWindow::initStatusBar() {
206 ✔
526
  ui->statusBar->showMessage(tr("Welcome to QtPass %1").arg(VERSION), 2000);
412 ✔
527

528
  QPixmap logo = QPixmap::fromImage(QImage(":/artwork/icon.svg"))
412 ✔
529
                     .scaledToHeight(statusBar()->height());
206 ✔
530
  auto *logoApp = new QLabel(statusBar());
206 ✔
531
  logoApp->setPixmap(logo);
206 ✔
532
  m_stopButton = new QPushButton(tr("Stop"), statusBar());
412 ✔
533
  m_stopButton->setObjectName(QStringLiteral("stopButton"));
412 ✔
534
  m_stopButton->setToolTip(
206 ✔
535
      tr("Stop the gpg, git or pass run that is still going"));
206 ✔
536
  m_stopButton->hide();
206 ✔
537
  connect(m_stopButton, &QPushButton::clicked, this, [this]() {
206 ✔
538
    Pass *pass = QtPassSettings::getPass();
6 ✔
539
    if (pass == nullptr || pass->isIdle()) {
6 ✔
540
      m_stopButton->hide();
×
541
      return;
2 ✔
542
    }
543
    const Enums::PROCESS pid = pass->runningProcess();
544
    const quint64 run = pass->runningSerial();
545
    const QString label = runLabel(pid);
6 ✔
546
    // A decrypt or a search changes nothing. Anything else may be half done
547
    // when stopped: some entries re-encrypted and others not, a Git step cut
548
    // off with its lock left behind.
549
    const bool writes = pid != Enums::PASS_SHOW && pid != Enums::PASS_GREP;
6 ✔
550
    if (writes) {
6 ✔
551
      const auto answer = QMessageBox::question(
8 ✔
552
          this, tr("Stop %1?").arg(label),
8 ✔
553
          tr("%1 has not finished. Stopping it can leave its change half "
4 ✔
554
             "done: some entries re-encrypted and others not, or a Git step "
555
             "cut off, after which Git may refuse to run until "
556
             ".git/index.lock is removed.\n\nStop it anyway?")
557
              .arg(label),
8 ✔
558
          QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
559
      // The queue may have moved on while the question was open: stop
560
      // nothing but what was asked about.
561
      if (answer != QMessageBox::Yes || pass->runningSerial() != run) {
7 ✔
562
        return;
563
      }
564
    }
565
    m_stopButton->hide();
4 ✔
566
    if (pass->stopRunning()) {
4 ✔
567
      showStatusMessage(
4 ✔
568
          writes ? tr("Stopped %1 before it finished; the store may be "
12 ✔
569
                      "partly changed.")
570
                       .arg(label)
571
                 : tr("Stopped %1.").arg(label));
6 ✔
572
    }
573
  });
574
  statusBar()->addPermanentWidget(m_stopButton);
206 ✔
575
  statusBar()->addPermanentWidget(logoApp);
206 ✔
576
}
206 ✔
577

578
auto MainWindow::getCurrentTreeViewIndex() -> QModelIndex {
11 ✔
579
  return ui->treeView->currentIndex();
11 ✔
580
}
581

582
void MainWindow::flashText(const QString &text, const bool isError,
303 ✔
583
                           const bool isHtml) {
584
  // setText() applies the current char format to the whole message. Start
585
  // from an empty one: inherited from a cursor on a linkified URL it carried
586
  // the anchor, and the message became a link to that address. No colour
587
  // but red for an error, so text follows runtime light/dark switches (#946).
588
  QTextCursor cursor = ui->textBrowser->textCursor();
303 ✔
589
  cursor.clearSelection();
303 ✔
590
  ui->textBrowser->setTextCursor(cursor);
303 ✔
591
  QTextCharFormat format;
303 ✔
592
  if (isError) {
303 ✔
593
    format.setForeground(QColor(Qt::red));
11 ✔
594
  }
595
  ui->textBrowser->setCurrentCharFormat(format);
303 ✔
596

597
  // Wrapped at word boundaries, a run of hundreds of thousands of letters
598
  // took Qt seconds to minutes; anywhere, it is linear. Anywhere while the
599
  // text goes in, then word wrap back unless what is shown has such a run:
600
  // markup (a link's "<a href") splits a run in the source, not on screen.
601
  ui->textBrowser->setWordWrapMode(QTextOption::WrapAnywhere);
303 ✔
602
  if (isHtml) {
303 ✔
603
    QString _text = text;
604
    // What was shown before this message: the part the cap may remove.
605
    // The message itself is never cut, so an entry shown through here
606
    // (passShowHandler()) stays whole however long it is.
607
    int older = 0;
284 ✔
608
    if (!ui->textBrowser->toPlainText().isEmpty()) {
568 ✔
609
      older = ui->textBrowser->document()->characterCount() - 1;
224 ✔
610
      _text = ui->textBrowser->toHtml() + _text;
448 ✔
611
    }
612
    ui->textBrowser->setHtml(_text);
284 ✔
613
    // Only the latest output: from the front, up to the start of the first
614
    // paragraph that ends the excess, within what was shown before (a
615
    // message that starts a paragraph starts one past it, after the
616
    // separator).
617
    QTextDocument *doc = ui->textBrowser->document();
284 ✔
618
    int cut = qMin(doc->characterCount() - kMaxFlashCharacters, older);
284 ✔
619
    if (cut > 0) {
284 ✔
620
      const QTextBlock block = doc->findBlock(cut);
140 ✔
621
      if (block.isValid() && cut > block.position() && block.next().isValid() &&
140 ✔
622
          block.next().position() <= older + 1) {
140 ✔
623
        cut = block.next().position();
140 ✔
624
      }
625
      QTextCursor trim(doc);
140 ✔
626
      trim.setPosition(cut, QTextCursor::KeepAnchor);
140 ✔
627
      trim.removeSelectedText();
140 ✔
628
    }
140 ✔
629
  } else {
630
    ui->textBrowser->setText(text);
19 ✔
631
  }
632
  // The raw text: toPlainText() turns a no-break space into a plain one.
633
  if (!Util::hasLongUnbrokenRun(ui->textBrowser->document()->toRawText())) {
606 ✔
634
    ui->textBrowser->setWordWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
297 ✔
635
  }
636
}
303 ✔
637

638
void MainWindow::applyTextBrowserSettings() {
5 ✔
639
  const AppSettings s = QtPassSettings::load();
5 ✔
640
  if (s.useMonospace) {
5 ✔
641
    QFont monospace("Monospace");
1 ✔
642
    monospace.setStyleHint(QFont::Monospace);
1 ✔
643
    ui->textBrowser->setFont(monospace);
1 ✔
644
  } else {
1 ✔
645
    ui->textBrowser->setFont(QFont());
4 ✔
646
  }
647

648
  if (s.noLineWrapping) {
5 ✔
649
    ui->textBrowser->setLineWrapMode(QTextBrowser::NoWrap);
1 ✔
650
  } else {
651
    ui->textBrowser->setLineWrapMode(QTextBrowser::WidgetWidth);
4 ✔
652
  }
653
}
5 ✔
654

655
void MainWindow::applyWindowFlagsSettings() {
222 ✔
656
  const bool wantOnTop = QtPassSettings::isAlwaysOnTop();
222 ✔
657
  const Qt::WindowFlags flags = windowFlags();
658
  if (flags.testFlag(Qt::WindowStaysOnTopHint) == wantOnTop) {
222 ✔
659
    // setWindowFlags() rebuilds the native window, the teardown that left
660
    // ui->lineEdit dangling (see focusInput()); skip it when nothing changes.
661
    return;
662
  }
663
  // Toggle just this hint; resetting to Qt::Window discarded every other flag.
664
  const bool wasVisible = isVisible();
665
  setWindowFlags(wantOnTop ? (flags | Qt::WindowStaysOnTopHint)
4 ✔
666
                           : (flags & ~Qt::WindowStaysOnTopHint));
667
  // setWindowFlags() hides a shown window; a window that was not shown yet
668
  // (first-run wizard from the constructor) is left to its normal show.
669
  if (wasVisible) {
2 ✔
670
    show();
2 ✔
671
  }
672
}
673

674
auto MainWindow::config() -> bool {
8 ✔
675
  if (m_freshStart) {
8 ✔
676
    // No usable configuration yet: the wizard finds the programs, the key
677
    // and the store, and creates the store when it has to.
678
    FirstRunWizard wizard(this);
2 ✔
679
    if (wizard.exec() != QDialog::Accepted) {
2 ✔
680
      return false;
681
    }
682
  } else {
2 ✔
683
    ConfigDialog d(this);
6 ✔
684
    d.setModal(true);
6 ✔
685
    if (d.exec() != QDialog::Accepted) {
6 ✔
686
      return false;
687
    }
688
  }
6 ✔
689

690
  applyTextBrowserSettings();
5 ✔
691
  applyWindowFlagsSettings();
5 ✔
692

693
  updateProfileBox();
5 ✔
694
  const AppSettings s = QtPassSettings::load();
5 ✔
695
  // An open still waiting for the tree was asked of the old view; once
696
  // re-rooted, it would find that name in the new store. A profile switch
697
  // ends it by clearing the search text.
698
  delete m_pendingOpen;
5 ✔
699
  // A content search still running searched the old store, and its matches
700
  // would be listed for this one: onGrepFinished() cannot tell. Cancelled,
701
  // and content-search results on screen go with it (clearPanel()).
702
  cancelContentSearch();
5 ✔
703
  if (m_grep.cancelSearch()) {
704
    QApplication::restoreOverrideCursor();
1 ✔
705
  }
706
  clearPanel(false);
5 ✔
707
  m_tree->setStore(s.passStore);
5 ✔
708
  deselect();
5 ✔
709
  ui->treeView->setCurrentIndex(QModelIndex());
5 ✔
710

711
  Pass *activePass = QtPassSettings::getPass();
5 ✔
712
  activePass->updateEnv();
5 ✔
713
  m_tree->setPass(activePass);
5 ✔
714
  clearPanelTimer.setInterval(MS_PER_SECOND * s.autoclearPanelSeconds);
5 ✔
715
  clearResultsTimer.setInterval(clearPanelTimer.interval());
5 ✔
716
  m_qtPass->clipboard().setAutoclearTimer();
5 ✔
717

718
  updateGitButtonVisibility();
5 ✔
719
  updateOtpButtonVisibility();
5 ✔
720
  updateGrepButtonVisibility();
5 ✔
721
  updateProcessOutputVisibility();
5 ✔
722
#ifndef Q_OS_MACOS
723
  // The action's toggled handler shows or hides the bar (and saves again).
724
  ui->actionShowMenuBar->setChecked(s.showMenuBar);
5 ✔
725
#endif
726
  if (s.useTrayIcon && m_tray == nullptr) {
5 ✔
727
    initTrayIcon();
1 ✔
728
  } else if (!s.useTrayIcon && m_tray != nullptr) {
4 ✔
729
    destroyTrayIcon();
×
730
  }
731

732
  // Stay fresh-start while the configuration is unusable, so the
733
  // constructor's loop re-runs the wizard. The re-prompt lives there:
734
  // recursing here never reported a cancel back to the caller.
735
  if (Util::configIsValid(s)) {
5 ✔
736
    m_freshStart = false;
5 ✔
737
  }
738
  return true;
739
}
5 ✔
740

741
void MainWindow::onUpdate(bool block) {
2 ✔
742
  ui->statusBar->showMessage(tr("Updating password-store"), 2000);
2 ✔
743
  if (block) {
2 ✔
744
    QtPassSettings::getPass()->GitPull_b(Pass::kBlockingPullMs);
1 ✔
745
  } else {
746
    QtPassSettings::getPass()->GitPull();
1 ✔
747
  }
748
}
2 ✔
749

750
void MainWindow::onPush() {
1 ✔
751
  if (QtPassSettings::isUseGit()) {
1 ✔
752
    ui->statusBar->showMessage(tr("Updating password-store"), 2000);
1 ✔
753
    QtPassSettings::getPass()->GitPush();
1 ✔
754
  }
755
}
1 ✔
756

757
void MainWindow::onAutoPush() {
8 ✔
758
  if (QtPassSettings::isUseGit()) {
8 ✔
759
    ui->statusBar->showMessage(tr("Updating password-store"), 2000);
8 ✔
760
    QtPassSettings::getPass()->GitPushAutomatic();
8 ✔
761
  }
762
}
8 ✔
763

764
auto MainWindow::getFile(const QModelIndex &index, bool forPass) -> QString {
68 ✔
765
  return m_tree->fileFor(index, forPass);
68 ✔
766
}
767

768
void MainWindow::on_treeView_clicked(const QModelIndex &index) {
27 ✔
769
  bool cleared = ui->treeView->currentIndex().flags() == Qt::NoItemFlags;
27 ✔
770
  QString file = getFile(index, true);
27 ✔
771
  ui->passwordName->setText(Util::shownName(file));
54 ✔
772
  if (!file.isEmpty() && !cleared) {
27 ✔
773
    // Remember what the panel is about to show, so onOtp() can tell whether the
774
    // code it can see belongs to the entry that is currently selected.
775
    m_shownFile = file;
26 ✔
776
    QtPassSettings::getPass()->Show(file);
52 ✔
777
  } else {
778
    m_shownFile.clear();
1 ✔
779
    clearPanel(false);
1 ✔
780
    ui->actionEdit->setEnabled(false);
1 ✔
781
    ui->actionDelete->setEnabled(true);
1 ✔
782
  }
783
}
27 ✔
784

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

788
  if (fileOrFolder.isFile()) {
4 ✔
789
    editPassword(getFile(index, true));
6 ✔
790
  }
791
}
4 ✔
792

793
void MainWindow::deselect() {
21 ✔
794
  m_shownFile.clear();
21 ✔
795
  cancelOtpRequest();
21 ✔
796
  m_qtPass->clipboard().clear();
21 ✔
797
  ui->treeView->clearSelection();
21 ✔
798
  // The current index too: clearSelection() keeps it, and whatever asks for
799
  // the "current" folder (Users, Add password, Add folder) took the hidden
800
  // entry it was left on, such as the first hit of a search just emptied.
801
  ui->treeView->setCurrentIndex(QModelIndex());
21 ✔
802
  ui->actionEdit->setEnabled(false);
21 ✔
803
  ui->actionDelete->setEnabled(false);
21 ✔
804
  ui->passwordName->setText("");
21 ✔
805
  clearPanel(false);
21 ✔
806
}
21 ✔
807

808
void MainWindow::executeWrapperStarted() {
78 ✔
809
  m_displayPanel->clear();
78 ✔
810
  m_panelEntry.clear();
78 ✔
811
  ui->textBrowser->clear();
78 ✔
812
  setUiElementsEnabled(false);
78 ✔
813
  clearPanelTimer.stop();
78 ✔
814
  if (QtPassSettings::isShowProcessOutput()) {
78 ✔
815
    m_processOutput->setVisible(true);
73 ✔
816
  }
817
}
78 ✔
818

819
void MainWindow::passShowHandler(const QString &p_output, const QString &file) {
42 ✔
820
  // Only the entry we most recently asked to show may repaint the panel; a
821
  // slower decrypt of an entry the user has since left is dropped, and so is
822
  // one that arrives after the selection was cleared (deselect, a profile
823
  // switch): nothing is asked to be shown then.
824
  if (!file.isEmpty() && file != m_shownFile) {
42 ✔
825
    // A newer show is pending and releases the interface when it lands;
826
    // with none (the selection was cleared) nothing else would until the
827
    // watchdog. setUiElementsEnabled() keeps a re-encryption's lock.
828
    if (m_shownFile.isEmpty()) {
10 ✔
829
      setUiElementsEnabled(true);
8 ✔
830
    }
831
    return;
10 ✔
832
  }
833
  const AppSettings s = QtPassSettings::load();
32 ✔
834
  refreshMarkedSecrets(s);
32 ✔
835
  QStringList templ =
836
      s.useTemplate ? TemplateIO::fieldsIn(s.passTemplate) : QStringList();
32 ✔
837
  bool allFields = s.useTemplate && s.templateAllFields;
32 ✔
838
  // A secret the panel hides is a field even when the template doesn't list
839
  // it: left in the text below the fields, it would show in plain view.
840
  FileContent fileContent = FileContent::parse(
841
      p_output, templ, allFields, [this, &s](const QString &name) {
32 ✔
842
        return m_displayPanel->isSecret(name, s);
19 ✔
843
      });
32 ✔
844
  QString output = p_output;
845
  // Display variant: empty when the password line is itself an otpauth URI, so
846
  // the shared secret is neither rendered nor copied to the clipboard.
847
  QString password = fileContent.getPasswordForDisplay();
32 ✔
848

849
  // Skipped for an OTP request: the user asked for a code, and two
850
  // OleSetClipboard calls in one turn can leave the Windows clipboard empty.
851
  if (m_otpRequestFile.isEmpty() || m_otpRequestFile != file) {
32 ✔
852
    m_qtPass->clipboard().copyIfAlways(password, p_output);
30 ✔
853
  }
854

855
  m_displayPanel->clear();
32 ✔
856
  m_panelEntry.clear();
32 ✔
857

858
  if (s.hideContent) {
32 ✔
859
    output = "***" + tr("Content hidden") + "***";
4 ✔
860
  } else if (s.displayAsIs) {
30 ✔
861
    // As it is, but not a block per line of millions.
862
    output = FileContent::boundedForDisplay(p_output);
4 ✔
863
  } else {
864
    m_panelEntry = file;
28 ✔
865
    m_displayPanel->displayFields(password, fileContent.getNamedValues(), s,
56 ✔
866
                                  s.useOtp ? fileContent.getOtpUri()
28 ✔
867
                                           : QString());
868
    output = fileContent.getRemainingDataForDisplay();
56 ✔
869
  }
870

871
  if (s.useAutoclearPanel) {
32 ✔
872
    clearPanelTimer.start();
3 ✔
873
  }
874

875
  // Shown as it is, the text holds the password and every secret field: no
876
  // links in it, or a click on a URL-shaped one handed it to the browser.
877
  flashText(QtPass::formatOutput(output, QString(), QString(),
64 ✔
878
                                 !s.displayAsIs || s.hideContent),
32 ✔
879
            false, true);
880
  setUiElementsEnabled(true);
32 ✔
881
}
64 ✔
882

883
void MainWindow::otpFromFileToClipboard(const QString &p_output,
31 ✔
884
                                        const QString &file) {
885
  // Permanently connected: only the decrypt of the entry onOtp() asked for
886
  // is ours, everything else belongs to a tree click or a Ctrl+C.
887
  if (m_otpRequestFile.isEmpty() || file != m_otpRequestFile) {
31 ✔
888
    return;
27 ✔
889
  }
890
  m_otpRequestFile.clear();
6 ✔
891

892
  if (p_output.isEmpty()) {
6 ✔
893
    // Distinguish "could not read the entry" from "entry has no OTP".
894
    flashText(tr("Could not decrypt this password entry"), true);
1 ✔
895
    setUiElementsEnabled(true);
1 ✔
896
    return;
1 ✔
897
  }
898

899
  // passShowHandler ran first for this finishedShow; if it rendered the OTP
900
  // row, reuse its code (as onOtp()'s fast path does). Otherwise parse:
901
  // hideContent, displayAsIs or no OTP field.
902
  const QString shown = m_displayPanel->currentOtpCode();
5 ✔
903
  if (!shown.isEmpty()) {
5 ✔
904
    m_qtPass->clipboard().copyText(shown);
1 ✔
905
    showStatusMessage(tr("OTP code copied to clipboard"));
1 ✔
906
    setUiElementsEnabled(true);
1 ✔
907
    return;
908
  }
909

910
  const AppSettings s = QtPassSettings::load();
4 ✔
911
  // Parse with the same template settings passShowHandler uses, so an OTP
912
  // field is recognised identically in both paths.
913
  const QStringList templ =
914
      s.useTemplate ? TemplateIO::fieldsIn(s.passTemplate) : QStringList();
4 ✔
915
  const bool allFields = s.useTemplate && s.templateAllFields;
4 ✔
916
  const FileContent fileContent =
917
      FileContent::parse(p_output, templ, allFields);
4 ✔
918

919
  Totp::Refusal why = Totp::Refusal::None;
4 ✔
920
  const std::optional<Totp::Settings> settings =
921
      Totp::parse(fileContent.getOtpUri(), &why);
8 ✔
922
  if (settings.has_value()) {
4 ✔
923
    m_qtPass->clipboard().copyText(Totp::generateNow(*settings));
4 ✔
924
    showStatusMessage(tr("OTP code copied to clipboard"));
4 ✔
925
  } else {
926
    // Why, when there is a configuration that gives no code.
927
    const QString reason = Totp::describe(why);
2 ✔
928
    flashText(reason.isEmpty() ? tr("No OTP code found in this password entry")
6 ✔
929
                               : reason,
930
              true);
931
  }
932
  setUiElementsEnabled(true);
4 ✔
933
}
8 ✔
934

935
void MainWindow::clearPanel(bool notify) {
67 ✔
936
  clearShownEntry(notify);
67 ✔
937
  clearContentResults();
67 ✔
938
}
67 ✔
939

940
void MainWindow::clearShownEntry(bool notify) {
69 ✔
941
  m_displayPanel->clear();
69 ✔
942
  m_panelEntry.clear();
69 ✔
943
  // A QR code of the password is the password on screen as much as the
944
  // panel is; it is a popup of its own, not part of the panel.
945
  m_qtPass->closeQRCode();
69 ✔
946
  if (notify) {
69 ✔
947
    QString output = "***" + tr("Password and content hidden") + "***";
4 ✔
948
    ui->textBrowser->setHtml(output);
2 ✔
949
  } else {
950
    ui->textBrowser->setHtml("");
134 ✔
951
  }
952
}
69 ✔
953

954
void MainWindow::clearContentResults() {
70 ✔
955
  clearResultsTimer.stop();
70 ✔
956
  const bool grepWasVisible = ui->grepResultsList->isVisible();
70 ✔
957
  ui->grepResultsList->clear();
70 ✔
958
  if (grepWasVisible) {
70 ✔
959
    showContentResults(false);
7 ✔
960
    if (m_grep.inGrepMode()) {
7 ✔
961
      // Left as the button leaves it: a search still running would otherwise
962
      // hand its partial matches to a content search entered meanwhile.
963
      cancelContentSearch();
7 ✔
964
      if (m_grep.leaveGrepMode()) {
965
        QApplication::restoreOverrideCursor();
2 ✔
966
      }
967
      ui->grepButton->blockSignals(true);
7 ✔
968
      ui->grepButton->setChecked(false);
7 ✔
969
      ui->grepButton->blockSignals(false);
7 ✔
970
      ui->lineEdit->blockSignals(true);
7 ✔
971
      ui->lineEdit->clear();
7 ✔
972
      ui->lineEdit->blockSignals(false);
7 ✔
973
      ui->lineEdit->setPlaceholderText(tr("Search password"));
14 ✔
974
    }
975
  }
976
}
70 ✔
977

978
void MainWindow::setUiElementsEnabled(bool state) {
477 ✔
979
  // A running re-encryption owns the UI state: the progress dialog's Cancel is
980
  // the user's escape hatch and endReencryptPath() releases the interface, so
981
  // neither an unrelated completion nor the watchdog may re-enable it early.
982
  if (state && m_reencryptRunning) {
477 ✔
983
    m_uiWatchdog.stop();
1 ✔
984
    return;
1 ✔
985
  }
986
  // Arm the watchdog while the UI is disabled; disarm once re-enabled.
987
  if (state) {
988
    m_uiWatchdog.stop();
374 ✔
989
  } else {
990
    m_uiWatchdog.start();
102 ✔
991
  }
992
  ui->treeView->setEnabled(state);
476 ✔
993
  ui->lineEdit->setEnabled(state);
476 ✔
994
  ui->actionAddPassword->setEnabled(state);
476 ✔
995
  ui->actionAddFolder->setEnabled(state);
476 ✔
996
  ui->actionUsers->setEnabled(state);
476 ✔
997
  ui->actionConfig->setEnabled(state);
476 ✔
998
  m_uiEnabled = state;
476 ✔
999
  updateProfileBoxEnabled();
476 ✔
1000
  const bool uiEnabled = state;
1001
  // is a file selected, and in sight (content search results hide the tree)?
1002
  state &= ui->treeView->currentIndex().isValid() && !ui->treeView->isHidden();
955 ✔
1003
  ui->actionDelete->setEnabled(state);
476 ✔
1004
  ui->actionEdit->setEnabled(state);
476 ✔
1005
  updateGitButtonVisibility(uiEnabled);
476 ✔
1006
  // `state` is now "UI enabled AND a file is selected", which is exactly when
1007
  // generating an OTP makes sense.
1008
  updateOtpButtonVisibility(state);
476 ✔
1009
}
1010

1011
void MainWindow::restoreWindow() {
217 ✔
1012
  // saveGeometry() covers position, size, maximized state and screen;
1013
  // anything applied on top discards it. Centre only when nothing was saved.
1014
  const QByteArray geometry = QtPassSettings::getGeometry();
434 ✔
1015
  if (geometry.isEmpty() || !restoreGeometry(geometry)) {
217 ✔
1016
    WindowStateStore::centreOnCursorScreen(*this);
4 ✔
1017
  }
1018
  restoreState(QtPassSettings::getSavestate(saveState()));
217 ✔
1019
  const AppSettings s = QtPassSettings::load();
217 ✔
1020

1021
  applyWindowFlagsSettings();
217 ✔
1022

1023
  if (s.useTrayIcon && m_tray == nullptr) {
217 ✔
1024
    initTrayIcon();
2 ✔
1025
    // Minimized to the tray only when there is one: without a system tray
1026
    // initTrayIcon() gave up, and a hidden window could not be brought back.
1027
    if (s.startMinimized && m_tray != nullptr) {
2 ✔
1028
      // since we are still in constructor, can't directly hide
1029
      QTimer::singleShot(10, this, &MainWindow::hide);
×
1030
    }
1031
  } else if (!s.useTrayIcon && m_tray != nullptr) {
215 ✔
1032
    destroyTrayIcon();
×
1033
  }
1034
}
434 ✔
1035

1036
void MainWindow::onConfig() {
3 ✔
1037
  // No Settings while anything of the store runs or waits, as with the
1038
  // profile box (#2071): the store, backend and programs chosen there apply
1039
  // to what is still queued, so a pending `pass init` re-encrypted the store
1040
  // just picked for the recipients chosen for the other. Asked of the
1041
  // backends: the watchdog releases the interface while a slow gpg or git
1042
  // still runs.
1043
  if (!QtPassSettings::backendsIdle()) {
3 ✔
1044
    critical(tr("Settings not opened"),
2 ✔
1045
             tr("A gpg, Git or pass command is still running or waiting. "
1 ✔
1046
                "Open the settings again once it has finished. If it does "
1047
                "not finish, answer or cancel the PIN or password prompt it "
1048
                "waits for, or restart QtPass. A restart forgets which "
1049
                "folders still need re-encrypting: re-encrypt any folder "
1050
                "whose re-encryption did not finish, or that you moved "
1051
                "entries into, before anything is pushed."));
1052
    return;
1 ✔
1053
  }
1054
  config();
2 ✔
1055
}
1056

1057
void MainWindow::showAbout() {
1 ✔
1058
  QMessageBox::about(
1 ✔
1059
      this, tr("About QtPass"),
1 ✔
1060
      tr("<h3>QtPass %1</h3>"
1 ✔
1061
         "<p>A multi-platform GUI for <a "
1062
         "href=\"https://www.passwordstore.org/\">"
1063
         "pass</a>, the standard Unix password manager.</p>"
1064
         "<p><a href=\"https://qtpass.org/\">qtpass.org</a> &middot; "
1065
         "<a href=\"https://github.com/IJHack/QtPass\">Source and "
1066
         "issues</a></p>"
1067
         "<p>Copyright &copy; 2014&ndash;%2 IJhack. Licensed under the "
1068
         "<a href=\"https://www.gnu.org/licenses/gpl-3.0.html\">GNU GPL "
1069
         "version 3</a> or later.</p>")
1070
          .arg(QStringLiteral(VERSION),
2 ✔
1071
               QString::number(QDate::currentDate().year())));
2 ✔
1072
}
1 ✔
1073

1074
void MainWindow::on_lineEdit_textChanged(const QString &arg1) {
50 ✔
1075
  if (m_grep.inGrepMode())
50 ✔
1076
    return;
1077
  ui->statusBar->showMessage(tr("Looking for: %1").arg(arg1), 1000);
74 ✔
1078
  ui->treeView->expandAll();
37 ✔
1079
  // Drop any decrypt still pending for the entry that was shown: otherwise it
1080
  // keeps its right to the panel and, with "Always copy", the clipboard, and
1081
  // when it lands late it shows that entry's password under the new heading.
1082
  m_shownFile.clear();
37 ✔
1083
  cancelOtpRequest();
37 ✔
1084
  clearPanel(false);
37 ✔
1085
  ui->passwordName->setText("");
74 ✔
1086
  ui->actionEdit->setEnabled(false);
37 ✔
1087
  ui->actionDelete->setEnabled(false);
37 ✔
1088
  searchTimer.start();
37 ✔
1089
}
1090

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

1096
  if (query.isEmpty()) {
41 ✔
1097
    ui->treeView->collapseAll();
2 ✔
1098
    deselect();
2 ✔
1099
  }
1100

1101
  // The words are matched literally, in order, with anything in between:
1102
  // "work vpn" finds work/acme/vpn.
1103
  m_tree->setFilter(StoreModel::wordsFilter(query));
41 ✔
1104

1105
  if (m_tree->proxy().rowCount() > 0 && !query.isEmpty()) {
41 ✔
1106
    selectFirstFile();
28 ✔
1107
  } else {
1108
    ui->actionEdit->setEnabled(false);
13 ✔
1109
    ui->actionDelete->setEnabled(false);
13 ✔
1110
  }
1111
}
41 ✔
1112

1113
void MainWindow::on_lineEdit_returnPressed() {
17 ✔
1114
  qCDebug(lcQtPass) << "on_lineEdit_returnPressed"
17 ✔
1115
                    << m_tree->proxy().rowCount();
×
1116

1117
  if (m_grep.inGrepMode()) {
17 ✔
1118
    const QString query = ui->lineEdit->text();
12 ✔
1119
    if (!query.isEmpty()) {
12 ✔
1120
      ui->grepResultsList->clear();
9 ✔
1121
      ui->statusBar->showMessage(tr("Searching…"));
18 ✔
1122
      if (m_grep.beginSearch()) {
1123
        QApplication::setOverrideCursor(Qt::WaitCursor);
9 ✔
1124
      }
1125
      QtPassSettings::getPass()->Grep(query, ui->grepCaseButton->isChecked());
18 ✔
1126
    } else {
1127
      cancelContentSearch();
3 ✔
1128
      if (m_grep.cancelSearch()) {
1129
        QApplication::restoreOverrideCursor();
2 ✔
1130
      }
1131
      ui->grepResultsList->clear();
3 ✔
1132
      showContentResults(false);
3 ✔
1133
    }
1134
    return;
1135
  }
1136

1137
  // Return within the search delay acts on the text as typed, not on the
1138
  // tree as the previous text filtered it.
1139
  if (searchTimer.isActive()) {
5 ✔
1140
    searchTimer.stop();
5 ✔
1141
    onTimeoutSearch();
5 ✔
1142
  }
1143
  if (m_tree->proxy().rowCount() > 0) {
5 ✔
1144
    selectFirstFile();
5 ✔
1145
    on_treeView_clicked(ui->treeView->currentIndex());
5 ✔
1146
  }
1147
}
1148

1149
void MainWindow::on_grepButton_toggled(bool checked) {
35 ✔
1150
  const AppSettings s = QtPassSettings::load();
35 ✔
1151
  if (checked) {
35 ✔
1152
    m_grep.enterGrepMode();
1153
    ui->lineEdit->setPlaceholderText(tr("Search content (regex)"));
44 ✔
1154
    // Both backends search through NativeGrep (QRegularExpression), so one
1155
    // dialect: PCRE.
1156
    ui->lineEdit->setToolTip(
22 ✔
1157
        tr("Content search uses Perl-compatible regular expressions (PCRE)."));
22 ✔
1158
    ui->lineEdit->clear();
22 ✔
1159
    searchTimer.stop();
22 ✔
1160
    m_tree->setFilter(QRegularExpression());
22 ✔
1161
    ui->grepResultsList->setVisible(false);
22 ✔
1162
    // Keep treeView visible until results arrive
1163
  } else {
1164
    cancelContentSearch();
13 ✔
1165
    if (m_grep.leaveGrepMode()) {
1166
      QApplication::restoreOverrideCursor();
2 ✔
1167
    }
1168
    searchTimer.stop();
13 ✔
1169
    ui->lineEdit->blockSignals(true);
13 ✔
1170
    ui->lineEdit->clear();
13 ✔
1171
    ui->lineEdit->blockSignals(false);
13 ✔
1172
    ui->lineEdit->setPlaceholderText(tr("Search password"));
26 ✔
1173
    ui->lineEdit->setToolTip(QString());
26 ✔
1174
    ui->grepResultsList->clear();
13 ✔
1175
    showContentResults(false);
13 ✔
1176
    m_tree->setFilter(QRegularExpression());
13 ✔
1177
  }
1178
}
35 ✔
1179

1180
void MainWindow::refreshMarkedSecrets(const AppSettings &s) {
42 ✔
1181
  if (s.hidePassword) {
42 ✔
1182
    m_displayPanel->setMarkedSecrets(
4 ✔
1183
        TemplateIO::secretFieldsIn(s.passTemplate) +
8 ✔
1184
        TemplateIO::readSecretFields(s.passStore));
12 ✔
1185
  }
1186
}
42 ✔
1187

1188
auto MainWindow::grepLineForDisplay(const QString &line,
43 ✔
1189
                                    const AppSettings &s) const -> QString {
1190
  const QString hidden =
1191
      QStringLiteral("***") + tr("hidden") + QStringLiteral("***");
86 ✔
1192
  if (NativeGrep::isOtpMarker(line)) {
43 ✔
1193
    return tr("One-time password secret: %1").arg(hidden);
2 ✔
1194
  }
1195
  // The panel's own rules: the password and a field it would put behind
1196
  // the eye button keep their value out of the list too.
1197
  if (NativeGrep::isPasswordMatch(line)) {
1198
    return m_displayPanel->hides(QObject::tr("Password"), s)
52 ✔
1199
               ? tr("Password: %1").arg(hidden)
52 ✔
1200
               : NativeGrep::passwordMatchText(line);
26 ✔
1201
  }
1202
  if (const qsizetype colon = line.indexOf(QLatin1Char(':')); colon > 0) {
15 ✔
1203
    if (m_displayPanel->hides(line.left(colon).trimmed(), s)) {
39 ✔
1204
      return line.left(colon + 1) + QLatin1Char(' ') + hidden;
4 ✔
1205
    }
1206
  }
1207
  return line;
1208
}
1209

1210
void MainWindow::onGrepFinished(
21 ✔
1211
    const QList<QPair<QString, QStringList>> &results) {
1212
  // Both backends stay connected, each with its own search: a search the
1213
  // other backend was still running when Settings switched backends is not
1214
  // this one, whatever the controller's state, and searched another store.
1215
  // Dropped before it can end (or be taken for) the current search.
1216
  if (const QObject *from = sender();
21 ✔
1217
      from != nullptr && from != QtPassSettings::getPass()) {
21 ✔
1218
    return;
11 ✔
1219
  }
1220
  const GrepSearchController::FinishOutcome outcome = m_grep.finishSearch();
1221
  if (outcome.restoreCursor) {
20 ✔
1222
    QApplication::restoreOverrideCursor();
2 ✔
1223
  }
1224
  // Re-enable the UI before the discard check so a cancelled search can never
1225
  // leave controls disabled.
1226
  setUiElementsEnabled(true);
20 ✔
1227
  if (outcome.discard) {
20 ✔
1228
    return;
1229
  }
1230
  if (!m_grep.inGrepMode())
12 ✔
1231
    return;
1232
  ui->grepResultsList->clear();
12 ✔
1233
  if (results.isEmpty()) {
12 ✔
1234
    ui->statusBar->showMessage(tr("No matches found."), 3000);
2 ✔
1235
    showContentResults(false);
2 ✔
1236
    return;
2 ✔
1237
  }
1238
  const AppSettings s = QtPassSettings::load();
10 ✔
1239
  const bool hideContent = s.hideContent;
10 ✔
1240
  refreshMarkedSecrets(s);
10 ✔
1241
  int totalLines = 0;
1242
  int entries = 0;
1243
  bool stopped = false;
1244
  for (const auto &pair : results) {
43 ✔
1245
    if (NativeGrep::isStoppedMarker(pair)) {
33 ✔
1246
      stopped = true;
1247
      continue;
×
1248
    }
1249
    ++entries;
33 ✔
1250
    auto *entryItem = new QTreeWidgetItem(ui->grepResultsList);
33 ✔
1251
    entryItem->setText(0, pair.first);
33 ✔
1252
    entryItem->setData(0, Qt::UserRole, pair.first);
33 ✔
1253
    for (const QString &line : pair.second) {
76 ✔
1254
      auto *lineItem = new QTreeWidgetItem(entryItem);
43 ✔
1255
      // The marker is no content: shown as it is with hidden content too,
1256
      // and not counted as a match.
1257
      if (NativeGrep::isMoreMarker(line)) {
43 ✔
1258
        lineItem->setText(0, tr("… more matches in this entry"));
×
1259
      } else {
1260
        lineItem->setText(0, hideContent ? "***" + tr("Content hidden") + "***"
86 ✔
1261
                                         : grepLineForDisplay(line, s));
1262
        ++totalLines;
43 ✔
1263
      }
1264
      lineItem->setData(0, Qt::UserRole, pair.first);
43 ✔
1265
    }
1266
  }
1267
  ui->grepResultsList->expandAll();
10 ✔
1268
  showContentResults(true);
10 ✔
1269
  if (stopped) {
10 ✔
1270
    // The search stopped there; more entries may match.
1271
    ui->statusBar->showMessage(
×
1272
        tr("Showing the first %n match(es); search for something narrower "
×
1273
           "to see the rest.",
1274
           nullptr, totalLines),
1275
        10000);
1276
  } else {
1277
    ui->statusBar->showMessage(tr("Found %n match(es)", nullptr, totalLines) +
30 ✔
1278
                                   " " +
10 ✔
1279
                                   tr("in %n entr(ies).", nullptr, entries),
20 ✔
1280
                               3000);
1281
  }
1282
  // The results' own deadline: restarting the entry's timer here gave an
1283
  // entry still on the panel a second period, and an operation that stops
1284
  // the entry's timer left the results up with none.
1285
  if (s.useAutoclearPanel)
10 ✔
1286
    clearResultsTimer.start();
3 ✔
1287
}
10 ✔
1288

1289
void MainWindow::on_grepResultsList_itemClicked(QTreeWidgetItem *item,
2 ✔
1290
                                                int /*column*/) {
1291
  const AppSettings s = QtPassSettings::load();
2 ✔
1292
  const QString entry = item->data(0, Qt::UserRole).toString();
2 ✔
1293
  if (entry.isEmpty())
2 ✔
1294
    return;
1295
  const QString fullPath =
1296
      QDir::cleanPath(Util::joinPath(s.passStore, entry + ".gpg"));
2 ✔
1297
  // Persistent: setCurrentIndex() runs the selection handlers, which can
1298
  // change the model before the click is handled.
1299
  const QPersistentModelIndex proxyIndex(m_tree->indexFor(fullPath));
2 ✔
1300
  if (!proxyIndex.isValid())
2 ✔
1301
    return;
1302
  ui->treeView->setCurrentIndex(proxyIndex);
2 ✔
1303
  if (!proxyIndex.isValid())
2 ✔
1304
    return;
1305
  on_treeView_clicked(proxyIndex);
2 ✔
1306
  if (s.hideContent || s.useAutoclearPanel)
2 ✔
1307
    ui->grepResultsList->clear();
1 ✔
1308
  showContentResults(false);
2 ✔
1309
  ui->treeView->scrollTo(proxyIndex);
2 ✔
1310
  ui->treeView->setFocus();
2 ✔
1311
}
4 ✔
1312

1313
void MainWindow::showContentResults(bool shown) {
37 ✔
1314
  ui->grepResultsList->setVisible(shown);
37 ✔
1315
  ui->treeView->setVisible(!shown);
37 ✔
1316
  if (shown) {
37 ✔
1317
    // The tree's current entry is out of sight: Delete, Edit and OTP would
1318
    // act on it, not on a result. Opening a result shows the tree again.
1319
    ui->actionDelete->setEnabled(false);
10 ✔
1320
    ui->actionEdit->setEnabled(false);
10 ✔
1321
    updateOtpButtonVisibility(false);
10 ✔
1322
  } else if (ui->treeView->selectionModel()->hasSelection()) {
27 ✔
1323
    // Only for an entry still selected: with nothing selected there is no
1324
    // entry for Edit and Delete to act on.
1325
    setUiElementsEnabled(m_uiEnabled);
8 ✔
1326
  }
1327
}
37 ✔
1328

1329
void MainWindow::cancelContentSearch() {
28 ✔
1330
  QtPassSettings::getRealPass()->CancelGrep();
28 ✔
1331
  QtPassSettings::getImitatePass()->CancelGrep();
28 ✔
1332
}
28 ✔
1333

1334
void MainWindow::selectFirstFile() {
33 ✔
1335
  // The entry named exactly as typed wins: with folders sorted first, the
1336
  // depth-first walk found team/bank before bank.
1337
  QModelIndex index = exactMatch();
33 ✔
1338
  if (!index.isValid()) {
1339
    index = firstFile(m_tree->rootIndex());
16 ✔
1340
  }
1341
  ui->treeView->setCurrentIndex(index);
33 ✔
1342
}
33 ✔
1343

1344
namespace {
1345
/**
1346
 * @brief @p path with each part below @p store spelled as stored on disk.
1347
 *
1348
 * Where the file system ignores case, "Bank.gpg" exists while the file is
1349
 * bank.gpg, and the tree knows the entry only by that spelling.
1350
 * @param store The store folder.
1351
 * @param path An existing file in the store.
1352
 * @return @p path itself when every part is spelled as stored, otherwise
1353
 *         the path with the stored spelling.
1354
 */
1355
auto spelledAsStored(const QString &store, const QString &path) -> QString {
33 ✔
1356
  const QStringList parts = QDir(store).relativeFilePath(path).split(
66 ✔
1357
      QLatin1Char('/'), Qt::SkipEmptyParts);
33 ✔
1358
  QDir dir(store);
33 ✔
1359
  bool respelled = false;
1360
  for (int i = 0; i < parts.size(); ++i) {
36 ✔
1361
    const bool leaf = i == parts.size() - 1;
36 ✔
1362
    const QStringList names =
1363
        dir.entryList((leaf ? QDir::Files : QDir::Dirs) | QDir::Hidden |
36 ✔
1364
                      QDir::NoDotAndDotDot);
39 ✔
1365
    QString name = parts.at(i);
1366
    if (!names.contains(name)) {
36 ✔
1367
      const auto stored = std::find_if(
×
1368
          names.cbegin(), names.cend(), [&name](const QString &candidate) {
1369
            return candidate.compare(name, Qt::CaseInsensitive) == 0;
×
1370
          });
1371
      if (stored == names.cend()) {
×
1372
        return path;
1373
      }
1374
      name = *stored;
×
1375
      respelled = true;
1376
    }
1377
    if (leaf) {
36 ✔
1378
      return respelled ? QDir::cleanPath(Util::joinPath(dir.path(), name))
66 ✔
1379
                       : path;
×
1380
    }
1381
    if (!dir.cd(name)) {
3 ✔
1382
      return path;
1383
    }
1384
  }
1385
  return path;
1386
}
33 ✔
1387
} // namespace
1388

1389
auto MainWindow::exactMatchPath() -> QString {
51 ✔
1390
  const QString text = QDir::fromNativeSeparators(ui->lineEdit->text());
102 ✔
1391
  const QString store = QtPassSettings::getPassStore();
102 ✔
1392
  // A name may begin or end with a space: " bank" is that entry, not bank.
1393
  // Only when no entry is named so are spaces around the text dropped.
1394
  for (const QString &typed : {text, text.trimmed()}) {
191 ✔
1395
    if (typed.isEmpty()) {
71 ✔
1396
      continue;
×
1397
    }
1398
    const QString path =
1399
        QDir::cleanPath(Util::joinPath(store, typed + QStringLiteral(".gpg")));
142 ✔
1400
    if (PathValidator::isPathInStore(store, path) && QFileInfo(path).isFile()) {
71 ✔
1401
      return spelledAsStored(store, path);
33 ✔
1402
    }
1403
  }
153 ✔
1404
  return {};
18 ✔
1405
}
1406

1407
auto MainWindow::exactMatch() -> QModelIndex {
47 ✔
1408
  const QString path = exactMatchPath();
47 ✔
1409
  if (path.isEmpty()) {
47 ✔
1410
    return {};
17 ✔
1411
  }
1412
  // indexFor() maps through the filter: a row the filter hides is no match.
1413
  const QModelIndex index = m_tree->indexFor(path);
30 ✔
1414
  if (!index.isValid() || !m_tree->fileInfo(index).isFile()) {
53 ✔
1415
    return {};
7 ✔
1416
  }
1417
  return index;
23 ✔
1418
}
1419

1420
void MainWindow::applySearchText(const QString &text) {
9 ✔
1421
  // A name search: content search, left on, kept its results over the tree
1422
  // and ignored the text.
1423
  if (ui->grepButton->isChecked()) {
9 ✔
1424
    ui->grepButton->setChecked(false);
1 ✔
1425
  }
1426
  delete m_pendingOpen;
9 ✔
1427
  ui->lineEdit->setText(text);
9 ✔
1428
  // Filter now, not after the search delay: the timer would leave the tree
1429
  // as the previous text filtered it.
1430
  searchTimer.stop();
9 ✔
1431
  onTimeoutSearch();
9 ✔
1432
  if (const QModelIndex exact = exactMatch(); exact.isValid()) {
9 ✔
1433
    openExactMatch(exact);
5 ✔
1434
    return;
5 ✔
1435
  }
1436
  // The tree loads folders in the background: at start, or right after the
1437
  // window is shown again, an entry that exists may not be in it yet. Try
1438
  // again as folders finish loading, for a few seconds, unless the search
1439
  // text changes meanwhile: any change ends the wait, even one typed back to
1440
  // this text, which is a new search that has not asked to open anything.
1441
  if (exactMatchPath().isEmpty()) {
8 ✔
1442
    return;
1443
  }
1444
  auto *pending = new QObject(this);
3 ✔
1445
  m_pendingOpen = pending;
1446
  QTimer::singleShot(5000, pending, &QObject::deleteLater);
3 ✔
1447
  // Disconnected at once: with deleteLater() alone, a folder that finished
1448
  // loading before the deletion still ran the open, or ran it twice.
1449
  const auto stop = [this, pending] {
2 ✔
1450
    disconnect(m_tree, nullptr, pending, nullptr);
2 ✔
1451
    disconnect(ui->lineEdit, nullptr, pending, nullptr);
2 ✔
1452
    pending->deleteLater();
2 ✔
1453
  };
5 ✔
1454
  connect(ui->lineEdit, &QLineEdit::textChanged, pending, stop);
3 ✔
1455
  connect(m_tree, &StoreTree::directoryLoaded, pending,
3 ✔
1456
          [this, stop](const QString &) {
6 ✔
1457
            searchTimer.stop();
5 ✔
1458
            onTimeoutSearch();
5 ✔
1459
            if (const QModelIndex exact = exactMatch(); exact.isValid()) {
5 ✔
1460
              stop();
1 ✔
1461
              openExactMatch(exact);
1 ✔
1462
            }
1463
          });
5 ✔
1464
}
1465

1466
void MainWindow::openExactMatch(const QModelIndex &index) {
6 ✔
1467
  // Made current here, not left to the filter pass before: the tree may have
1468
  // moved its current row since, and with none on_treeView_clicked() only
1469
  // names the entry without decrypting it.
1470
  ui->treeView->setCurrentIndex(index);
6 ✔
1471
  on_treeView_clicked(index);
6 ✔
1472
}
6 ✔
1473

1474
auto MainWindow::firstFile(QModelIndex parentIndex) -> QModelIndex {
23 ✔
1475
  StoreModel &proxy = m_tree->proxy();
23 ✔
1476
  int numRows = proxy.rowCount(parentIndex);
23 ✔
1477
  for (int row = 0; row < numRows; ++row) {
30 ✔
1478
    QModelIndex index = proxy.index(row, 0, parentIndex);
21 ✔
1479
    if (m_tree->fileInfo(index).isFile()) {
21 ✔
1480
      return index;
14 ✔
1481
    }
1482
    if (proxy.hasChildren(index)) {
12 ✔
1483
      QModelIndex childFile = firstFile(index);
7 ✔
1484
      if (childFile.isValid())
1485
        return childFile;
5 ✔
1486
    }
1487
  }
1488
  return QModelIndex();
9 ✔
1489
}
1490

1491
// Guards the input dialogs (create, move, rename) against names like
1492
// "../../etc/passwd" or absolute paths escaping the store root.
1493
auto MainWindow::confirmPathInStore(const QString &candidate) -> bool {
11 ✔
1494
  if (PathValidator::isPathInStore(QtPassSettings::getPassStore(), candidate)) {
22 ✔
1495
    return true;
1496
  }
1497
  QMessageBox::warning(this, tr("Invalid name"),
9 ✔
1498
                       tr("That name would resolve outside the password "
3 ✔
1499
                          "store. Please choose a different name."));
1500
  return false;
3 ✔
1501
}
1502

1503
void MainWindow::setPassword(const QString &file, bool isNew) {
8 ✔
1504
  const AppSettings s = QtPassSettings::load();
8 ✔
1505
  PasswordDialog d(QtPassSettings::getPass(), s, file, isNew, this);
8 ✔
1506
  // A copy out of the editor is autocleared like one from the display.
1507
  connect(&d, &PasswordDialog::copied, &m_qtPass->clipboard(),
8 ✔
1508
          &ClipboardManager::trackCopied);
8 ✔
1509

1510
  if (isNew) {
8 ✔
1511
    const QString storePath = s.passStore;
1512
    QString folder = m_tree->currentDir(false);
2 ✔
1513
    if (folder.isEmpty()) {
2 ✔
1514
      folder = storePath;
×
1515
    }
1516
    // A tree folder that is, or lies behind, a symbolic link is not part of the
1517
    // store (Users and re-encryption refuse it the same way). Adding here would
1518
    // silently fall back to the store root and encrypt the new entry to the
1519
    // root's recipients - which a co-writer who planted the link, and is on the
1520
    // root list but not the real folder's, can then read. Refuse instead.
1521
    if (refuseLinkedFolder(folder)) {
2 ✔
1522
      return;
1523
    }
1524
    // Folders to pick from, the tree's current one preselected. Real folders
1525
    // only: a linked or junctioned one would write the entry outside the store.
1526
    QStringList folders{QString()};
2 ✔
1527
    const QStringList found = Util::directoriesUnder(storePath);
1 ✔
1528
    for (const QString &path : found) {
19 ✔
1529
      const QString rel = QDir(storePath).relativeFilePath(path);
18 ✔
1530
      if (!rel.startsWith(u'.') && !rel.contains(QStringLiteral("/."))) {
54 ✔
1531
        folders << rel;
1532
      }
1533
    }
1534
    std::sort(folders.begin() + 1, folders.end());
1 ✔
1535
    d.setNewEntryLocation(storePath, folders,
1 ✔
1536
                          QDir(storePath).relativeFilePath(folder));
2 ✔
1537
    QHash<QString, QStringList> templates =
1538
        TemplateIO::readTemplates(storePath);
1 ✔
1539
    if (!templates.isEmpty()) {
1540
      QString defaultTemplate =
1541
          TemplateIO::getFolderTemplate(folder, storePath);
1 ✔
1542
      d.setAvailableTemplates(templates, defaultTemplate);
1 ✔
1543
    }
1544
  }
1 ✔
1545

1546
  if (!d.exec()) {
7 ✔
1547
    ui->treeView->setFocus();
6 ✔
1548
  }
1549
}
8 ✔
1550

1551
void MainWindow::addPassword() { setPassword(QString()); }
4 ✔
1552

1553
auto MainWindow::confirmDeletion(const QString &file, bool isDir) -> bool {
9 ✔
1554
  const QString path = QDir::separator() + file;
9 ✔
1555
  // As the platform writes paths: backslashes only on Windows, never a mix.
1556
  // On one line: a name from the store may hold a line feed (Unix allows
1557
  // one), which drew lines of its own into the question.
1558
  const QString shown =
1559
      Util::displayable(QDir::toNativeSeparators(path), false);
9 ✔
1560
  if (!isDir) {
9 ✔
1561
    return PlainMessageBox::askYes(
2 ✔
1562
        this, tr("Delete password?"),
2 ✔
1563
        tr("Are you sure you want to delete %1?").arg(shown));
4 ✔
1564
  }
1565
  // Whole sentences, not a question stitched from pieces: a verb-final
1566
  // language cannot put the rest of the question after the path.
1567
  // Plain text, as every box quoting the store: the path is a name other
1568
  // writers control, and as rich text "a  b" would also show as "a b".
1569
  QString question =
1570
      tr("Are you sure you want to delete %1 and the whole content?")
×
1571
          .arg(shown);
7 ✔
1572
  // A link, junction or special file inside is as unexpected as a stray
1573
  // plain file: the walker leaves them out of content and reports them.
1574
  QStringList skipped;
7 ✔
1575
  QStringList unlisted;
7 ✔
1576
  const QString root = m_tree->fileSystem().rootPath();
7 ✔
1577
  const QStringList content = Util::regularFilesUnder(
21 ✔
1578
      root + path, {QStringLiteral("*")}, &skipped, false, &unlisted);
21 ✔
1579
  const bool unexpected =
1580
      !skipped.isEmpty() ||
7 ✔
1581
      std::any_of(content.cbegin(), content.cend(), [](const QString &entry) {
7 ✔
1582
        return QFileInfo(entry).suffix() != QLatin1String("gpg");
10 ✔
1583
      });
1584
  if (unexpected) {
1585
    question += QStringLiteral("\n\n") +
1 ✔
1586
                tr("Attention: there are unexpected files in the given "
1 ✔
1587
                   "folder, check them before continuing.");
1 ✔
1588
  }
1589
  // A folder the walk cannot read is not empty but unknown: whatever it
1590
  // holds goes too, or stays behind when the removal cannot list it.
1591
  if (unlisted.size() == 1) {
7 ✔
1592
    //: %1 is a folder in the password store, such as /Work/bank.
1593
    const QString one =
1594
        tr("%1 could not be read, so what it holds is unknown.")
1 ✔
1595
            .arg(Util::displayable(
1 ✔
1596
                QDir::toNativeSeparators(
1 ✔
1597
                    QDir::separator() +
1 ✔
1598
                    QDir(root).relativeFilePath(unlisted.first())),
2 ✔
1599
                false));
3 ✔
1600
    question += QStringLiteral("\n\n") + one;
2 ✔
1601
  } else if (unlisted.size() > 1) {
6 ✔
1602
    //: Only shown for two or more folders; one folder is named instead.
1603
    const QString many =
1604
        tr("%n folder(s) in it could not be read, so what they hold "
1605
           "is unknown.",
1606
           nullptr, static_cast<int>(unlisted.size()));
1 ✔
1607
    question += QStringLiteral("\n\n") + many;
2 ✔
1608
  }
1609
  return PlainMessageBox::askYes(this, tr("Delete folder?"), question);
14 ✔
1610
}
1611

1612
auto MainWindow::confirmLinkRemoval(const QString &file) -> bool {
1 ✔
1613
  // Only the link goes (ImitatePass::Remove unlinks it); nothing behind it
1614
  // is looked at or mentioned.
1615
  return PlainMessageBox::askYes(
1 ✔
1616
      this, tr("Delete link?"),
1 ✔
1617
      tr("%1 is a symbolic link or junction. Remove the link? What it "
1 ✔
1618
         "points to is left alone.")
1619
          .arg(Util::displayable(QDir::separator() + file, false)));
2 ✔
1620
}
1621

1622
void MainWindow::onDelete() {
14 ✔
1623
  const QModelIndex currentIndex = ui->treeView->currentIndex();
14 ✔
1624
  // While content search results hide the tree, its current entry is not
1625
  // what the user looks at (the Delete key comes here directly).
1626
  if (!currentIndex.isValid() || ui->treeView->isHidden()) {
12 ✔
1627
    // Otherwise the whole password directory would be deleted (#556).
1628
    return;
11 ✔
1629
  }
1630

1631
  const bool isDir = !m_tree->fileInfo(currentIndex).isFile();
10 ✔
1632
  const QString file =
1633
      isDir ? m_tree->currentDir(true) : getFile(currentIndex, true);
10 ✔
1634
  const QString folder =
1635
      m_tree->fileSystem().rootPath() + QDir::separator() + file;
10 ✔
1636
  const bool linkedFolder = isDir && Util::isLinkedFolder(folder);
10 ✔
1637

1638
  if (!linkedFolder && refuseLinkedFolder(folder)) {
9 ✔
1639
    // Behind a link: deleting would reach outside the store.
1640
    return;
1641
  }
1642
  const bool confirmed =
1643
      linkedFolder ? confirmLinkRemoval(file) : confirmDeletion(file, isDir);
10 ✔
1644
  if (!confirmed) {
10 ✔
1645
    return;
1646
  }
1647
  QtPassSettings::getPass()->Remove(file, isDir);
6 ✔
1648
}
1649

1650
void MainWindow::cancelOtpRequest() {
104 ✔
1651
  m_otpRequestFile.clear();
104 ✔
1652
  m_copyRequestFile.clear();
104 ✔
1653
}
104 ✔
1654

1655
void MainWindow::onOperationError() {
39 ✔
1656
  cancelOtpRequest();
39 ✔
1657
  // executeWrapperStarted() emptied the panel and the browser when the
1658
  // operation started (a refusal says so too); what is left to forget is
1659
  // which entry the panel was about to show.
1660
  m_shownFile.clear();
39 ✔
1661
  // A save's refresh waiting for its push is dropped: it would clear the
1662
  // push's error (or whatever failed before it) from the browser.
1663
  m_refreshAfterPush.clear();
39 ✔
1664
  m_refreshAfterPushOwner = nullptr;
1665
}
39 ✔
1666

1667
// Derives the code in-process from one decrypt, so it works with either
1668
// backend on every platform; otpFromFileToClipboard() finishes the job.
1669
void MainWindow::onOtp() {
12 ✔
1670
  if (ui->treeView->isHidden()) {
12 ✔
1671
    return;
4 ✔
1672
  }
1673
  QString file = getFile(ui->treeView->currentIndex(), true);
11 ✔
1674
  if (file.isEmpty()) {
11 ✔
1675
    flashText(tr("No password selected for OTP generation"), true);
1 ✔
1676
    return;
1 ✔
1677
  }
1678
  if (!QtPassSettings::isUseOtp()) {
10 ✔
1679
    // Normally unreachable (the action is hidden), but never fail silently.
1680
    flashText(tr("No OTP code found in this password entry"), true);
1 ✔
1681
    return;
1 ✔
1682
  }
1683

1684
  // Fast path: the panel shows a live code, so no decrypt, and one clipboard
1685
  // write (two setMimeData calls in one turn can empty the Windows
1686
  // clipboard). Only for *this* entry: arrow keys and right-click move
1687
  // currentIndex without QTreeView::clicked, so the code may be another's.
1688
  const QString shown =
1689
      (m_shownFile == file) ? m_displayPanel->currentOtpCode() : QString();
9 ✔
1690
  if (!shown.isEmpty()) {
9 ✔
1691
    m_qtPass->clipboard().copyText(shown);
1 ✔
1692
    showStatusMessage(tr("OTP code copied to clipboard"));
2 ✔
1693
    return;
1694
  }
1695

1696
  // Fallback: decrypt once. The request file keeps passShowHandler from
1697
  // copying the password and tells otpFromFileToClipboard its answer.
1698
  m_otpRequestFile = file;
8 ✔
1699
  setUiElementsEnabled(false);
8 ✔
1700
  // Keep the marker in step so a second request takes the fast path; safe as
1701
  // executeWrapperStarted() clears the panel, so a failed decrypt shows none.
1702
  m_shownFile = file;
8 ✔
1703
  QtPassSettings::getPass()->Show(file);
16 ✔
1704
}
1705

1706
void MainWindow::onEdit() {
1 ✔
1707
  if (ui->treeView->isHidden()) {
1 ✔
1708
    return;
1 ✔
1709
  }
1710
  QString file = getFile(ui->treeView->currentIndex(), true);
×
1711
  editPassword(file);
×
1712
}
1713

1714
void MainWindow::onUsers() {
2 ✔
1715
  const QString dir = m_tree->currentDir(false);
2 ✔
1716
  if (refuseLinkedFolder(dir)) {
2 ✔
1717
    return;
1718
  }
1719

1720
  UsersDialog d(QtPassSettings::getPass(), QtPassSettings::load(), dir, this);
1 ✔
1721
  if (!d.exec()) {
1 ✔
1722
    ui->treeView->setFocus();
1 ✔
1723
  }
1724
}
1 ✔
1725

1726
void MainWindow::messageAvailable(const QString &message) {
10 ✔
1727
  show();
10 ✔
1728
  raise();
10 ✔
1729
  if (message.isEmpty()) {
10 ✔
1730
    focusInput();
1 ✔
1731
  } else {
1732
    ui->treeView->expandAll();
9 ✔
1733
    applySearchText(message);
9 ✔
1734
  }
1735
}
10 ✔
1736

1737
void MainWindow::updateProfileBox() {
215 ✔
1738
  const Profiles profiles = QtPassSettings::getProfiles();
215 ✔
1739
  bool activeGone = false;
1740

1741
  if (profiles.isEmpty()) {
8 ✔
1742
    ui->profileWidget->hide();
207 ✔
1743
  } else {
1744
    ui->profileWidget->show();
8 ✔
1745
    // A refill is no choice of the user's: clearing and adding items moves
1746
    // the current text, which would otherwise switch profiles.
1747
    const QSignalBlocker quiet(ui->profileBox);
8 ✔
1748
    ui->profileBox->clear();
8 ✔
1749
    for (auto i = profiles.cbegin(); i != profiles.cend(); ++i) {
22 ✔
1750
      if (!i.key().isEmpty()) {
14 ✔
1751
        ui->profileBox->addItem(i.key());
14 ✔
1752
      }
1753
    }
1754
    ui->profileBox->model()->sort(0);
8 ✔
1755
    int index = ui->profileBox->findText(QtPassSettings::getProfile());
16 ✔
1756
    if (index != -1) { //  -1 for not found
8 ✔
1757
      ui->profileBox->setCurrentIndex(index);
7 ✔
1758
    } else if (ui->profileBox->count() > 0) {
1 ✔
1759
      // The active profile is gone (removed in Settings): the box shows the
1760
      // first one, and the settings and backend must follow it, or the
1761
      // removed profile's store stays in use behind it.
1762
      ui->profileBox->setCurrentIndex(0);
1 ✔
1763
      activeGone = true;
1764
    }
1765
  }
8 ✔
1766
  if (activeGone) {
8 ✔
1767
    on_profileBox_currentTextChanged(ui->profileBox->currentText());
2 ✔
1768
  }
1769
  updateProfileBoxEnabled();
215 ✔
1770
}
215 ✔
1771

1772
void MainWindow::updateProfileBoxEnabled() {
741 ✔
1773
  // No profile switch while anything of the store runs or waits: the
1774
  // backend's store and environment would change under it, and what is
1775
  // still queued (a push after a save, say) would finish for the other
1776
  // profile (#2071). Asked of the backend, not only of the interface: the
1777
  // watchdog releases the interface while a slow gpg or git still runs.
1778
  // Every backend: one kept from before a switch of backend may still
1779
  // run what was queued on it.
1780
  ui->profileBox->setEnabled(m_uiEnabled && ui->profileBox->count() > 1 &&
1,484 ✔
1781
                             QtPassSettings::backendsIdle());
16 ✔
1782
}
741 ✔
1783

1784
void MainWindow::on_profileBox_currentTextChanged(const QString &name) {
8 ✔
1785
  if (m_freshStart || name == QtPassSettings::getProfile()) {
24 ✔
1786
    return;
1 ✔
1787
  }
1788
  // The box is disabled while anything runs; should a change come through
1789
  // anyway, the active profile stays and the box says so again.
1790
  if (!m_uiEnabled || !QtPassSettings::backendsIdle()) {
7 ✔
1791
    const QSignalBlocker quiet(ui->profileBox);
×
1792
    ui->profileBox->setCurrentText(QtPassSettings::getProfile());
×
1793
    return;
1794
  }
×
1795
  // A content search runs outside the queue: leaving grep mode cancels it,
1796
  // so its results for the old store are dropped, not shown for the new.
1797
  if (m_grep.inGrepMode()) {
7 ✔
1798
    ui->grepButton->setChecked(false);
1 ✔
1799
  }
1800

1801
  ui->lineEdit->clear();
7 ✔
1802

1803
  const Profile prof = QtPassSettings::getProfiles().value(name);
14 ✔
1804
  AppSettings s = QtPassSettings::load();
7 ✔
1805
  s.activeProfile = name;
7 ✔
1806
  s.passStore = prof.path;
7 ✔
1807
  s.passSigningKey = prof.signingKey;
7 ✔
1808
  // The profile's own Git flags are not written over the Git page's: every
1809
  // profile without flags of its own falls back to those.
1810
  // QtPassSettings::loadEffective() applies them while the profile is active.
1811
  QtPassSettings::save(s);
7 ✔
1812
  ui->statusBar->showMessage(tr("Profile changed to %1").arg(name), 2000);
14 ✔
1813

1814
  QtPassSettings::getPass()->updateEnv();
7 ✔
1815

1816
  m_tree->setStore(QtPassSettings::getPassStore());
14 ✔
1817
  deselect();
7 ✔
1818
  ui->treeView->setCurrentIndex(QModelIndex());
7 ✔
1819
}
7 ✔
1820

1821
void MainWindow::initTrayIcon() {
3 ✔
1822
  m_tray = new TrayIcon(this);
3 ✔
1823
  if (!m_tray->getIsAllocated()) {
3 ✔
1824
    destroyTrayIcon();
3 ✔
1825
    return;
3 ✔
1826
  }
1827
#ifndef Q_OS_MACOS
1828
  m_tray->addToggle(ui->actionShowMenuBar);
×
1829
#endif
1830
}
1831

1832
void MainWindow::destroyTrayIcon() {
3 ✔
1833
  delete m_tray;
3 ✔
1834
  m_tray = nullptr;
3 ✔
1835
}
3 ✔
1836

1837
void MainWindow::closeEvent(QCloseEvent *event) {
4 ✔
1838
  // Save in both branches: a tray user only ever hides the window, and
1839
  // used to quit through the tray menu with nothing ever written.
1840
  saveWindowState();
4 ✔
1841
  // Only with a tray icon to come back from: without one (none asked for, or
1842
  // no system tray in this session) a hidden QtPass ran on invisibly, with the
1843
  // last entry in its window and the password on the clipboard.
1844
  if (QtPassSettings::isHideOnClose() && m_tray != nullptr) {
8 ✔
1845
    this->hide();
×
1846
    event->ignore();
1847
  } else {
1848
    m_qtPass->clipboard().clear();
4 ✔
1849
    event->accept();
1850
    // A visible QSystemTrayIcon keeps the application alive, so
1851
    // quitOnLastWindowClosed never fires; quit explicitly.
1852
    QApplication::quit();
4 ✔
1853
  }
1854
}
4 ✔
1855

1856
auto MainWindow::eventFilter(QObject *obj, QEvent *event) -> bool {
8,758 ✔
1857
  if ((obj == ui->toolBar || obj == menuBar()) &&
8,758 ✔
1858
      event->type() == QEvent::PaletteChange) {
1859
    // Breeze gives these bars a "header" palette and, after a runtime
1860
    // light/dark switch, stamps the previous theme's colours back from a
1861
    // cached kdeglobals, hiding the toolbar icons. Deferred so we never
1862
    // re-enter the style while it is still applying its palette.
1863
    QTimer::singleShot(0, this, &MainWindow::dropStaleToolsAreaPalettes);
36 ✔
1864
  }
1865
  if (obj == ui->lineEdit && event->type() == QEvent::KeyPress) {
8,758 ✔
1866
    auto *key = dynamic_cast<QKeyEvent *>(event);
5 ✔
1867
    if (key != nullptr && key->key() == Qt::Key_Down) {
5 ✔
1868
      // Into whichever list is in sight: the tree, or content search results.
1869
      // Focus makes the list's first item current.
1870
      if (ui->treeView->isHidden()) {
2 ✔
1871
        ui->grepResultsList->setFocus();
1 ✔
1872
      } else {
1873
        ui->treeView->setFocus();
1 ✔
1874
      }
1875
    }
1876
    // Return ends at the search box: QLineEdit emits returnPressed() and
1877
    // leaves the key unaccepted, so keyPressEvent() would open the tree's
1878
    // current entry as well. In content search that is an entry nobody
1879
    // asked for; by name, the first hit a second time.
1880
    if (key != nullptr &&
5 ✔
1881
        (key->key() == Qt::Key_Return || key->key() == Qt::Key_Enter)) {
2 ✔
1882
      ui->lineEdit->event(event);
3 ✔
1883
      event->accept();
1884
      return true;
3 ✔
1885
    }
1886
  }
1887
  return QObject::eventFilter(obj, event);
8,755 ✔
1888
}
1889

1890
// Only once the application palette changed (see m_themeSwitched): a bar
1891
// whose active Window lightness is far from the application's shows the
1892
// other theme.
1893
void MainWindow::dropStaleToolsAreaPalettes() {
31 ✔
1894
  if (!m_themeSwitched) {
31 ✔
1895
    return;
1896
  }
1897
  constexpr int kStaleToolsAreaLightness = 64;
1898
  // The active group on both sides: a bar's palette() reads the inactive
1899
  // group while another window has focus (the settings app, during a theme
1900
  // switch), and Breeze gives the header set different inactive colours.
1901
  const int appLightness = QApplication::palette()
54 ✔
1902
                               .color(QPalette::Active, QPalette::Window)
1903
                               .lightness();
27 ✔
1904
  for (QWidget *bar : {static_cast<QWidget *>(ui->toolBar),
108 ✔
1905
                       static_cast<QWidget *>(menuBar())}) {
81 ✔
1906
    if (!bar->testAttribute(Qt::WA_SetPalette)) {
54 ✔
1907
      continue;
48 ✔
1908
    }
1909
    const int barLightness =
1910
        bar->palette().color(QPalette::Active, QPalette::Window).lightness();
12 ✔
1911
    if (qAbs(barLightness - appLightness) <= kStaleToolsAreaLightness) {
6 ✔
1912
      continue;
2 ✔
1913
    }
1914
    bar->setPalette(QPalette());
4 ✔
1915
    // Both bars are transparent and the style paints the tools area from the
1916
    // stale palette, so fill our own. Window, not their Button role, which is
1917
    // not the window colour in either theme.
1918
    bar->setBackgroundRole(QPalette::Window);
4 ✔
1919
    bar->setAutoFillBackground(true);
4 ✔
1920
  }
1921
}
1922

1923
void MainWindow::keyPressEvent(QKeyEvent *event) {
25 ✔
1924
  switch (event->key()) {
25 ✔
1925
  case Qt::Key_Delete:
2 ✔
1926
    onDelete();
2 ✔
1927
    break;
2 ✔
1928
  case Qt::Key_Return:
2 ✔
1929
  case Qt::Key_Enter:
1930
    // While content search results hide the tree, its current entry is not
1931
    // what the user looks at: Return on a result opens that result.
1932
    if (ui->treeView->isHidden()) {
2 ✔
1933
      QTreeWidgetItem *result = ui->grepResultsList->currentItem();
1 ✔
1934
      if (result != nullptr && ui->grepResultsList->hasFocus()) {
1 ✔
1935
        on_grepResultsList_itemClicked(result, 0);
1 ✔
1936
      }
1937
      break;
1938
    }
1939
    if (m_tree->proxy().rowCount() > 0) {
1 ✔
1940
      on_treeView_clicked(ui->treeView->currentIndex());
1 ✔
1941
    }
1942
    break;
1943
  case Qt::Key_Escape:
3 ✔
1944
    ui->lineEdit->clear();
3 ✔
1945
    break;
3 ✔
1946
  default:
1947
    break;
1948
  }
1949
}
25 ✔
1950

1951
void MainWindow::addShareMenu(QMenu &contextMenu, const AppSettings &s) {
13 ✔
1952
  const QString dirPath = QDir::cleanPath(m_tree->currentDir(false));
13 ✔
1953
  auto *shareMenu = new QMenu(tr("Share"), &contextMenu);
13 ✔
1954
  contextMenu.addMenu(shareMenu);
13 ✔
1955

1956
  const QString gpgIdPath = Pass::getGpgIdPath(dirPath, s.passStore);
13 ✔
1957
  const bool gpgIdExists = !gpgIdPath.isEmpty() && QFile(gpgIdPath).exists();
13 ✔
1958
  const QString exePath = s.usePass ? s.passExecutable : s.gpgExecutable;
13 ✔
1959
  const bool gpgAvailable =
1960
      !exePath.isEmpty() &&
26 ✔
1961
      (Executor::parseWslCommand(exePath) || QFile(exePath).exists());
26 ✔
1962

1963
  QAction *reencrypt = shareMenu->addAction(tr("Re-encrypt all passwords"));
13 ✔
1964
  reencrypt->setEnabled(gpgIdExists && gpgAvailable);
13 ✔
1965
  connect(reencrypt, &QAction::triggered, this,
13 ✔
1966
          [this, dirPath]() { reencryptPath(dirPath); });
43 ✔
1967

1968
  QAction *exportKey = shareMenu->addAction(tr("Export my public key..."));
13 ✔
1969
  exportKey->setEnabled(gpgAvailable);
13 ✔
1970
  connect(exportKey, &QAction::triggered, this, &MainWindow::exportPublicKey);
13 ✔
1971

1972
  QAction *addRecipientAction = shareMenu->addAction(tr("Add recipient..."));
13 ✔
1973
  addRecipientAction->setEnabled(gpgIdExists && gpgAvailable);
13 ✔
1974
  connect(addRecipientAction, &QAction::triggered, this,
13 ✔
1975
          [this, dirPath]() { addRecipient(dirPath); });
41 ✔
1976

1977
  QAction *shareHelp = shareMenu->addAction(tr("What is this?"));
13 ✔
1978
  connect(shareHelp, &QAction::triggered, this, &MainWindow::showShareHelp);
13 ✔
1979
}
13 ✔
1980

1981
auto MainWindow::backOnMenuEntry(const QString &openedOn) -> bool {
3 ✔
1982
  const QModelIndex current = ui->treeView->currentIndex();
3 ✔
1983
  if (openedOn.isEmpty()) {
3 ✔
1984
    // Opened beside the entries: for the store itself.
1985
    if (current.isValid()) {
NEW
1986
      ui->treeView->setCurrentIndex(QModelIndex());
×
1987
    }
1988
    return true;
1 ✔
1989
  }
1990
  if (current.isValid() &&
2 ✔
1991
      m_tree->fileInfo(current).absoluteFilePath() == openedOn) {
4 ✔
1992
    return true;
1993
  }
1994
  // Asked only about a path that exists: the file system model on macOS
1995
  // lists a path again once it is asked for one that is gone.
1996
  const QModelIndex shown =
1997
      QFileInfo::exists(openedOn) ? m_tree->indexFor(openedOn) : QModelIndex();
2 ✔
1998
  if (!shown.isValid()) {
1999
    showStatusMessage(
1 ✔
2000
        tr("%1 is no longer in the list.").arg(Util::shownName(openedOn)));
2 ✔
2001
    return false;
1 ✔
2002
  }
2003
  ui->treeView->setCurrentIndex(shown);
1 ✔
2004
  return true;
2005
}
2006

2007
void MainWindow::showContextMenu(const QPoint &pos) {
15 ✔
2008
  const AppSettings s = QtPassSettings::load();
15 ✔
2009
  const QModelIndex index = ui->treeView->indexAt(pos);
15 ✔
2010
  const bool selected = index.isValid();
2011
  if (!selected) {
2012
    ui->treeView->clearSelection();
1 ✔
2013
    ui->actionDelete->setEnabled(false);
1 ✔
2014
    ui->actionEdit->setEnabled(false);
1 ✔
2015
  }
2016
  ui->treeView->setCurrentIndex(index);
15 ✔
2017
  const QPoint globalPos = ui->treeView->viewport()->mapToGlobal(pos);
15 ✔
2018
  const QFileInfo fileOrFolder = m_tree->fileInfo(ui->treeView->currentIndex());
15 ✔
2019
  const bool isDir = fileOrFolder.isDir();
15 ✔
2020

2021
  QMenu contextMenu;
15 ✔
2022
  // The actions read the current entry when picked, and that may be another
2023
  // one by then: a row removed in place by the file system model (its own
2024
  // watcher, on macOS) hands the current index to a neighbour, and the
2025
  // reload after it finds that one again. Delete would then remove the
2026
  // neighbour. So each action first goes back to the entry the menu was
2027
  // opened on, and does nothing when that is gone.
2028
  const QString openedOn =
2029
      selected ? fileOrFolder.absoluteFilePath() : QString();
15 ✔
2030
  const auto add = [this, &contextMenu, openedOn](const QString &text,
15 ✔
2031
                                                  void (MainWindow::*slot)()) {
2032
    connect(contextMenu.addAction(text), &QAction::triggered, this,
85 ✔
2033
            [this, openedOn, slot]() {
170 ✔
2034
              if (backOnMenuEntry(openedOn)) {
3 ✔
2035
                (this->*slot)();
2 ✔
2036
              }
2037
            });
3 ✔
2038
  };
100 ✔
2039
  if (!selected || isDir) {
15 ✔
2040
    add(tr("Open folder with file manager"), &MainWindow::openFolder);
14 ✔
2041
    add(tr("Add folder"), &MainWindow::addFolder);
14 ✔
2042
    add(tr("Add password"), &MainWindow::addPassword);
14 ✔
2043
    add(tr("Users"), &MainWindow::onUsers);
28 ✔
2044
  } else if (fileOrFolder.isFile()) {
1 ✔
2045
    add(tr("Edit"), &MainWindow::onEdit);
2 ✔
2046
  }
2047
  if (selected) {
15 ✔
2048
    contextMenu.addSeparator();
14 ✔
2049
    if (isDir) {
14 ✔
2050
      add(tr("Rename folder"), &MainWindow::renameFolder);
26 ✔
2051
    } else if (fileOrFolder.isFile()) {
1 ✔
2052
      add(tr("Rename password"), &MainWindow::renamePassword);
2 ✔
2053
    }
2054
    add(tr("Delete"), &MainWindow::onDelete);
14 ✔
2055
    if (isDir) {
14 ✔
2056
      addShareMenu(contextMenu, s);
13 ✔
2057
    }
2058
  }
2059
  // With the current entry gone and nothing else current, the menu has
2060
  // nothing left to act on.
2061
  connect(m_tree, &StoreTree::currentEntryLost, &contextMenu, &QMenu::close);
15 ✔
2062
  contextMenu.exec(globalPos);
15 ✔
2063
}
15 ✔
2064

2065
auto MainWindow::browserContextMenu(const QPoint &pos) -> QMenu * {
3 ✔
2066
  // createStandardContextMenu() takes document coordinates, anchorAt() and
2067
  // the menu's place viewport ones: scrolled, the menu checked the text
2068
  // above the link and left "Copy Link Location" disabled.
2069
  // Right to left, the horizontal offset counts from the other end.
2070
  const QScrollBar *across = ui->textBrowser->horizontalScrollBar();
3 ✔
2071
  const int dx = ui->textBrowser->isRightToLeft()
3 ✔
2072
                     ? across->maximum() - across->value()
3 ✔
2073
                     : across->value();
3 ✔
2074
  const QPoint documentPos =
2075
      pos + QPoint(dx, ui->textBrowser->verticalScrollBar()->value());
3 ✔
2076
  QMenu *contextMenu = ui->textBrowser->createStandardContextMenu(documentPos);
3 ✔
2077
  // Reparent from textBrowser: a browser stylesheet cascades to the child
2078
  // QMenu and breaks its opaque native background.
2079
  contextMenu->setParent(this, contextMenu->windowFlags());
3 ✔
2080
  if (auto *copyLink =
3 ✔
2081
          contextMenu->findChild<QAction *>(QStringLiteral("link-copy"))) {
3 ✔
2082
    const QString link = ui->textBrowser->anchorAt(pos);
3 ✔
2083
    disconnect(copyLink, &QAction::triggered, nullptr, nullptr);
3 ✔
2084
    connect(copyLink, &QAction::triggered, this, [this, link] {
10 ✔
2085
      if (!link.isEmpty()) {
1 ✔
2086
        m_qtPass->clipboard().copyText(link);
1 ✔
2087
      }
2088
    });
1 ✔
2089
  }
2090
  return contextMenu;
3 ✔
2091
}
2092

2093
void MainWindow::showBrowserContextMenu(const QPoint &pos) {
1 ✔
2094
  QMenu *contextMenu = browserContextMenu(pos);
1 ✔
2095
  contextMenu->exec(ui->textBrowser->viewport()->mapToGlobal(pos));
1 ✔
2096
  delete contextMenu;
1 ✔
2097
}
1 ✔
2098

2099
void MainWindow::openFolder() {
1 ✔
2100
  QString dir = m_tree->currentDir(false);
1 ✔
2101

2102
  QString path = QDir::toNativeSeparators(dir);
1 ✔
2103
  QDesktopServices::openUrl(QUrl::fromLocalFile(path));
1 ✔
2104
}
1 ✔
2105

2106
void MainWindow::addFolder() {
7 ✔
2107
  const AppSettings s = QtPassSettings::load();
7 ✔
2108
  bool ok;
2109
  QString dir = m_tree->currentDir(false);
7 ✔
2110
  QString newdir = QInputDialog::getText(
2111
      this, tr("New folder"),
7 ✔
2112
      tr("New folder: \n(Will be placed in %1 )")
7 ✔
2113
          .arg(Util::shownName(s.passStore + m_tree->currentDir(true))),
14 ✔
2114
      QLineEdit::Normal, "", &ok);
14 ✔
2115
  if (!ok || newdir.isEmpty()) {
7 ✔
2116
    return;
2117
  }
2118
  // Checked and created as one and the same path: the check resolves ".."
2119
  // lexically, the system after following links, so "link/../x" would pass
2120
  // as the store's x and be made beside the link's target.
2121
  newdir = QDir::cleanPath(newdir.prepend(dir));
6 ✔
2122
  if (!confirmPathInStore(newdir)) {
6 ✔
2123
    return;
2124
  }
2125
  // Behind a link the folder would be made outside the store, as Users,
2126
  // Re-encrypt and Delete already refuse.
2127
  if (refuseLinkedFolder(newdir)) {
5 ✔
2128
    return;
2129
  }
2130
  // The tree, like `pass ls`, hides names that start with a dot.
2131
  const QStringList parts =
2132
      QDir(s.passStore).relativeFilePath(newdir).split(u'/');
4 ✔
2133
  if (std::any_of(parts.cbegin(), parts.cend(), [](const QString &part) {
8 ✔
2134
        return part != u'.' && part.startsWith(u'.');
4 ✔
2135
      })) {
2136
    PlainMessageBox::warning(this, tr("Hidden folder"),
2 ✔
2137
                             tr("A folder that starts with a dot would be "
1 ✔
2138
                                "hidden from the list: %1")
2139
                                 .arg(newdir));
2 ✔
2140
    return;
1 ✔
2141
  }
2142
  // Exists already: an error, as QDir::mkdir() made it before.
2143
  if (QFileInfo::exists(newdir) || !Util::mkpathForStore(newdir)) {
3 ✔
2144
    PlainMessageBox::warning(this, tr("Error"),
2 ✔
2145
                             tr("Failed to create folder: %1").arg(newdir));
2 ✔
2146
    return;
1 ✔
2147
  }
2148
  // No .gpg-id of its own: the folder uses its parent's recipients, as with
2149
  // pass, until Users gives it a list. A copy of the parent's list (#1688)
2150
  // kept every recipient later removed above it, and its entries stayed
2151
  // readable by them.
2152
}
7 ✔
2153

2154
void MainWindow::renameFolder() {
4 ✔
2155
  bool ok;
2156
  QString srcDir = QDir::cleanPath(m_tree->currentDir(false));
4 ✔
2157
  QString srcDirName = QDir(srcDir).dirName();
4 ✔
2158
  QString newName =
2159
      QInputDialog::getText(this, tr("Rename folder"), tr("Rename folder to: "),
4 ✔
2160
                            QLineEdit::Normal, srcDirName, &ok);
8 ✔
2161
  if (!ok || newName.isEmpty()) {
4 ✔
2162
    return;
2163
  }
2164
  QString destDir = srcDir;
2165
  destDir.replace(srcDir.lastIndexOf(srcDirName), srcDirName.length(), newName);
3 ✔
2166
  if (!confirmPathInStore(destDir)) {
3 ✔
2167
    return;
2168
  }
2169
  if (!PlainMessageBox::confirmPassRun(
2 ✔
2170
          this, QtPassSettings::getPassStore(), [&srcDir, &destDir] {
4 ✔
2171
            return QtPassSettings::getPass()->entriesMoveWouldWiden(srcDir,
2 ✔
2172
                                                                    destDir);
2 ✔
2173
          })) {
2174
    return;
2175
  }
2176
  QtPassSettings::getPass()->Move(srcDir, destDir, false);
6 ✔
2177
}
2178

2179
void MainWindow::editPassword(const QString &file) {
6 ✔
2180
  if (!file.isEmpty()) {
6 ✔
2181
    const AppSettings s = QtPassSettings::loadEffective();
6 ✔
2182
    if (s.useGit && s.autoPull) {
6 ✔
2183
      onUpdate(true);
1 ✔
2184
    }
2185
    // The dialog decrypts the entry itself to fill its fields. That decrypt
2186
    // lands on the same finishedShow the panel uses, so drop the panel's claim
2187
    // to it: otherwise passShowHandler() repaints and, with "Always copy",
2188
    // puts the entry's old password on the clipboard - replacing whatever the
2189
    // user copied to paste into the dialog.
2190
    m_shownFile.clear();
6 ✔
2191
    setPassword(file, false);
6 ✔
2192
  }
6 ✔
2193
}
6 ✔
2194

2195
void MainWindow::renamePassword() {
2 ✔
2196
  bool ok;
2197
  QString file = getFile(ui->treeView->currentIndex(), false);
2 ✔
2198
  QString filePath = QFileInfo(file).path();
2 ✔
2199
  QString fileName = QFileInfo(file).fileName();
2 ✔
2200
  if (fileName.endsWith(".gpg", Qt::CaseInsensitive)) {
4 ✔
2201
    fileName.chop(4);
2 ✔
2202
  }
2203

2204
  QString newName =
2205
      QInputDialog::getText(this, tr("Rename file"), tr("Rename file to: "),
2 ✔
2206
                            QLineEdit::Normal, fileName, &ok);
4 ✔
2207
  if (!ok || newName.isEmpty()) {
2 ✔
2208
    return;
2209
  }
2210
  QString newFile = Util::joinPath(filePath, newName);
2 ✔
2211
  if (!confirmPathInStore(newFile)) {
2 ✔
2212
    return;
2213
  }
2214
  if (!PlainMessageBox::confirmPassRun(
1 ✔
2215
          this, QtPassSettings::getPassStore(), [&file, &newFile] {
2 ✔
2216
            return QtPassSettings::getPass()->entriesMoveWouldWiden(file,
1 ✔
2217
                                                                    newFile);
1 ✔
2218
          })) {
2219
    return;
2220
  }
2221
  QtPassSettings::getPass()->Move(file, newFile, false);
3 ✔
2222
}
2223

2224
void MainWindow::copySelectionOrPassword() {
5 ✔
2225
  QWidget *focus = QApplication::focusWidget();
5 ✔
2226
  // The widget's own copy: a SecretTextBrowser marks what it copies as
2227
  // secret for clipboard managers, as the context menu's Copy does.
2228
  if (auto *text = qobject_cast<QTextEdit *>(focus);
5 ✔
2229
      text != nullptr && text->textCursor().hasSelection()) {
5 ✔
2230
    text->copy();
1 ✔
2231
    return;
1 ✔
2232
  }
2233
  // Through the clipboard manager, as a copy button would: the label may be
2234
  // the OTP code, which gets the secret hint and the autoclear.
2235
  if (auto *label = qobject_cast<QLabel *>(focus);
2236
      label != nullptr && label->hasSelectedText()) {
4 ✔
2237
    m_qtPass->clipboard().copyText(label->selectedText());
1 ✔
2238
    return;
1 ✔
2239
  }
2240
  // A line of the content search results is decrypted text: through the
2241
  // clipboard manager too, for the secret hint and the autoclear.
2242
  if (focus == ui->grepResultsList) {
3 ✔
2243
    if (const QTreeWidgetItem *item = ui->grepResultsList->currentItem();
3 ✔
2244
        item != nullptr && !item->text(0).isEmpty()) {
6 ✔
2245
      m_qtPass->clipboard().copyText(item->text(0));
6 ✔
2246
    }
2247
    return;
3 ✔
2248
  }
UNCOV
2249
  copyPasswordFromTreeview();
×
2250
}
2251

2252
void MainWindow::copyPasswordFromTreeview() {
9 ✔
2253
  // While content search results hide the tree, its current entry is not
2254
  // what the user looks at: no decrypt, as for Edit and OTP.
2255
  if (ui->treeView->isHidden()) {
9 ✔
UNCOV
2256
    return;
×
2257
  }
2258
  QFileInfo fileOrFolder = m_tree->fileInfo(ui->treeView->currentIndex());
9 ✔
2259

2260
  if (fileOrFolder.isFile()) {
9 ✔
2261
    QString file = getFile(ui->treeView->currentIndex(), true);
9 ✔
2262
    // The newest Ctrl+C wins: finishedShow names its file, so the decrypt of
2263
    // an earlier request is simply not this one's.
2264
    m_copyRequestFile = file;
9 ✔
2265
    // This Show repaints the panel as well; see onOtp().
2266
    m_shownFile = file;
9 ✔
2267
    QtPassSettings::getPass()->Show(file);
18 ✔
2268
  }
2269
}
9 ✔
2270

2271
void MainWindow::passwordFromFileToClipboard(const QString &text,
32 ✔
2272
                                             const QString &file) {
2273
  if (m_copyRequestFile.isEmpty() || file != m_copyRequestFile) {
32 ✔
2274
    return;
27 ✔
2275
  }
2276
  m_copyRequestFile.clear();
8 ✔
2277
  // The first line, without a list of every line (an entry can expand into
2278
  // millions of them), and without the "\r" of a CRLF line end, as the
2279
  // password row and "Always copy" have it.
2280
  const QString first = FileContent::passwordLine(text);
8 ✔
2281
  // A `pass otp insert` entry's first line is the otpauth:// URI carrying the
2282
  // TOTP seed, and an OTP field holding a seed there is the same; copying it
2283
  // would leak 2FA material. Matches the display path
2284
  // (FileContent::getPasswordForDisplay / PasswordDisplayPanel).
2285
  if (FileContent::isOtpPasswordLine(first)) {
8 ✔
2286
    flashText(tr("This entry holds an OTP secret, not a password"), true);
6 ✔
2287
    return;
2288
  }
2289
  m_qtPass->clipboard().copyText(first);
5 ✔
2290
}
2291

2292
void MainWindow::showStatusMessage(const QString &msg, int timeout) {
45 ✔
2293
  ui->statusBar->showMessage(msg, timeout);
45 ✔
2294
}
45 ✔
2295

2296
void MainWindow::reencryptPath(const QString &dir) {
4 ✔
2297
  QDir checkDir(dir);
4 ✔
2298
  if (!checkDir.exists()) {
4 ✔
2299
    PlainMessageBox::critical(this, tr("Error"),
2 ✔
2300
                              tr("Directory does not exist: %1").arg(dir));
2 ✔
2301
    return;
1 ✔
2302
  }
2303
  if (refuseLinkedFolder(dir)) {
3 ✔
2304
    return;
2305
  }
2306

2307
  const bool yes = PlainMessageBox::askYes(
3 ✔
2308
      this, tr("Re-encrypt passwords"),
3 ✔
2309
      tr("Re-encrypt all passwords in %1?\n\n"
3 ✔
2310
         "This will re-encrypt ALL password files in this folder "
2311
         "using the current recipients defined in .gpg-id.\n\n"
2312
         "This may rewrite many files and cannot be undone easily.\n\n"
2313
         "Continue?")
2314
          // On one line: a name with line feeds pushed the warning out of
2315
          // the box, which shows 40 lines at most.
2316
          .arg(Util::displayable(QDir(dir).dirName(), false)));
6 ✔
2317

2318
  if (!yes)
3 ✔
2319
    return;
2320

2321
  // Disable now; the asynchronous startReencryptPath signal re-runs this
2322
  // harmlessly.
2323
  startReencryptPath();
1 ✔
2324

2325
  // Under the current profile's settings: with the pass backend active, the
2326
  // native one is not re-initialised on a profile switch.
2327
  QtPassSettings::getImitatePass()->reencryptPath(
2 ✔
2328
      QDir::cleanPath(QDir(dir).absolutePath()), QtPassSettings::load());
2 ✔
2329
}
4 ✔
2330

2331
// Idempotent: reencryptPath() calls it before ImitatePass emits the signal.
2332
void MainWindow::startReencryptPath() {
7 ✔
2333
  m_reencryptRunning = true;
7 ✔
2334
  setUiElementsEnabled(false);
7 ✔
2335
  // The worker always ends with endReencryptPath(), and Cancel is available
2336
  // throughout, so the generic watchdog is not needed for this operation.
2337
  m_uiWatchdog.stop();
7 ✔
2338
  ui->treeView->setDisabled(true);
7 ✔
2339
  if (m_reencryptProgress)
7 ✔
2340
    return;
2341
  auto *progress = new QProgressDialog(tr("Re-encrypting passwords..."),
5 ✔
2342
                                       tr("Cancel"), 0, 0, this);
10 ✔
2343
  progress->setWindowTitle(tr("Re-encrypt passwords"));
5 ✔
2344
  progress->setWindowModality(Qt::WindowModal);
5 ✔
2345
  progress->setAutoClose(false);
5 ✔
2346
  progress->setAutoReset(false);
5 ✔
2347
  progress->setMinimumDuration(0);
5 ✔
2348
  connect(progress, &QProgressDialog::canceled, this, [this]() {
5 ✔
2349
    QtPassSettings::getImitatePass()->cancelReencryptPath();
1 ✔
2350
    showStatusMessage(tr("Cancelling re-encryption"), 5000);
1 ✔
2351
  });
1 ✔
2352
  m_reencryptProgress = progress;
2353
  progress->show();
5 ✔
2354
}
2355

2356
void MainWindow::reencryptProgress(int current, int total) {
7 ✔
2357
  if (!m_reencryptProgress || m_inProgressUpdate)
7 ✔
2358
    return;
2359
  QProgressDialog *progress = m_reencryptProgress;
2360
  progress->setMaximum(total);
6 ✔
2361
  progress->setLabelText(
6 ✔
2362
      tr("Re-encrypting passwords: %1 of %2").arg(current).arg(total));
6 ✔
2363
  // On a modal dialog setValue() runs processEvents(), which can deliver
2364
  // endReencryptPath(), even inside a nested event loop that would delete a
2365
  // deleteLater()ed dialog under setValue()'s feet: keep this last, and
2366
  // delete the dialog only after it returns.
2367
  m_inProgressUpdate = true;
6 ✔
2368
  progress->setValue(current);
6 ✔
2369
  m_inProgressUpdate = false;
6 ✔
2370
  if (m_progressToDelete) {
6 ✔
2371
    m_progressToDelete->deleteLater();
2 ✔
2372
    m_progressToDelete = nullptr;
2373
  }
2374
}
2375

2376
void MainWindow::endReencryptPath() {
5 ✔
2377
  m_reencryptRunning = false;
5 ✔
2378
  if (m_reencryptProgress) {
5 ✔
2379
    m_reencryptProgress->hide();
5 ✔
2380
    if (m_inProgressUpdate) {
5 ✔
2381
      m_progressToDelete = m_reencryptProgress;
2382
    } else {
2383
      m_reencryptProgress->deleteLater();
3 ✔
2384
    }
2385
    m_reencryptProgress = nullptr;
2386
  }
2387
  setUiElementsEnabled(true);
5 ✔
2388
}
5 ✔
2389

UNCOV
2390
void MainWindow::askReencryptUnexpected(const QString &dir,
×
2391
                                        const QStringList &files,
2392
                                        const QStringList &details) {
2393
  const AppSettings s = QtPassSettings::load();
×
UNCOV
2394
  const QDir store(s.passStore);
×
2395
  // Sorted by name, so each folder's entries stand together; who would gain
2396
  // each one beside it, as the names alone are the writer's choosing.
2397
  QList<std::pair<QString, QString>> rows;
×
UNCOV
2398
  for (qsizetype i = 0; i < files.size(); ++i) {
×
UNCOV
2399
    rows.append({Util::displayable(store.relativeFilePath(files.at(i)), false),
×
2400
                 details.value(i)});
×
2401
  }
2402
  std::sort(rows.begin(), rows.end());
×
2403
  constexpr int kListed = 15;
UNCOV
2404
  QStringList lines;
×
2405
  for (qsizetype i = 0; i < rows.size() && i < kListed; ++i) {
×
UNCOV
2406
    lines << rows.at(i).first + QStringLiteral(": ") + rows.at(i).second;
×
2407
  }
2408
  if (rows.size() > kListed) {
×
2409
    lines << tr("... and %n more", nullptr,
×
UNCOV
2410
                static_cast<int>(rows.size() - kListed));
×
2411
  }
2412
  const int n = static_cast<int>(files.size());
×
2413
  const bool yes = PlainMessageBox::askYes(
×
UNCOV
2414
      this, tr("Re-encrypt these too?"),
×
2415
      tr("%n entry(s) here would become readable by people on this "
×
2416
         "folder's list who cannot read them now, and whom you did not just "
2417
         "add, so they were left as they are. Someone who can read this "
2418
         "folder may have copied them in from a folder they cannot read.",
UNCOV
2419
         nullptr, n) +
×
UNCOV
2420
          QStringLiteral("\n\n") + lines.join(QLatin1Char('\n')) +
×
UNCOV
2421
          QStringLiteral("\n\n") +
×
2422
          tr("Re-encrypt them for this folder's recipients? If not, they "
×
2423
             "stay readable only by whoever they are encrypted to now."));
×
2424
  if (!yes) {
×
2425
    return;
2426
  }
2427
  startReencryptPath();
×
UNCOV
2428
  QtPassSettings::getImitatePass()->reencryptAlso(dir, files, s);
×
UNCOV
2429
}
×
2430

2431
void MainWindow::exportPublicKey() {
4 ✔
2432
  const AppSettings s = QtPassSettings::load();
4 ✔
2433
  const QString identity = s.passSigningKey;
2434
  if (identity.isEmpty()) {
4 ✔
2435
    QMessageBox::information(
2 ✔
2436
        this, tr("Export public key"),
1 ✔
UNCOV
2437
        tr("<h3>Export your public key</h3>"
×
2438
           "<p>No signing key is configured. Set one in QtPass Settings "
2439
           "&gt; GPG keys, or run this in a terminal:</p>"
2440
           "<pre>gpg --armor --export --output my_key.asc &lt;your-key-id"
2441
           "&gt;</pre>"
2442
           "<p>Then send the file to your teammates.</p>"));
2443
    return;
1 ✔
2444
  }
2445
  QString gpgExe = s.gpgExecutable;
2446
  if (gpgExe.isEmpty()) {
3 ✔
UNCOV
2447
    gpgExe = QStringLiteral("gpg");
×
2448
  }
2449
  const QStringList keys = identity.split(' ', Qt::SkipEmptyParts);
3 ✔
2450
  // gpg --export takes every key block that holds the ID: another key that
2451
  // holds yours as a subkey would go out to your teammates as yours.
2452
  if (Pass *pass = QtPassSettings::getPass(); pass != nullptr) {
3 ✔
2453
    if (const std::optional<QHash<QString, QStringList>> held =
2454
            pass->keyLinesHeldTwice(keys);
3 ✔
2455
        !held || !held->isEmpty()) {
3 ✔
2456
      PlainMessageBox::warning(
1 ✔
2457
          this, tr("Export public key"),
1 ✔
2458
          tr("Your key cannot be exported on its own:\n\n%1")
1 ✔
2459
              .arg(Pass::describeKeyLinesHeldTwice(held)));
2 ✔
2460
      return;
2461
    }
2462
  }
2463
  QString stdOut;
2 ✔
2464
  QString stdErr;
2 ✔
2465
  // In the store's environment, the keyring the check above read.
2466
  Pass *pass = QtPassSettings::getPass();
2 ✔
2467
  int exitCode =
2468
      pass != nullptr
2469
          ? pass->exportPublicKeys(gpgExe, keys, &stdOut, &stdErr)
2 ✔
UNCOV
2470
          : Executor::executeBlocking(gpgExe,
×
UNCOV
2471
                                      QStringList{QStringLiteral("--armor"),
×
2472
                                                  QStringLiteral("--export")} +
2 ✔
2473
                                          keys,
×
2474
                                      &stdOut, &stdErr);
2475
  if (exitCode != 0 || stdOut.isEmpty()) {
2 ✔
2476
    PlainMessageBox::warning(this, tr("Export public key"),
2 ✔
2477
                             tr("Could not export public key for %1.\n\n%2")
1 ✔
2478
                                 .arg(identity, stdErr.isEmpty()
2 ✔
2479
                                                    ? tr("No output from gpg.")
2 ✔
2480
                                                    : stdErr));
2481
    return;
2482
  }
2483
  ExportPublicKeyDialog dialog(identity, stdOut, this);
1 ✔
2484
  dialog.exec();
1 ✔
2485
}
5 ✔
2486

2487
// UsersDialog only ticks keys already in the keyring; importing a foreign
2488
// key still has to happen via gpg (or QtPass settings) first.
2489
void MainWindow::addRecipient(const QString &dir) {
2 ✔
2490
  if (refuseLinkedFolder(dir)) {
2 ✔
2491
    return;
1 ✔
2492
  }
2493
  UsersDialog d(QtPassSettings::getPass(), QtPassSettings::load(), dir, this);
1 ✔
2494
  d.exec();
1 ✔
2495
}
1 ✔
2496

2497
// A tree-picked folder that is, or lies behind, a symlink or junction is not
2498
// a folder of the store. The store root itself may be a link (a synced
2499
// folder); that is configuration, not a tree pick.
2500
auto MainWindow::refuseLinkedFolder(const QString &dir) -> bool {
23 ✔
2501
  if (!Util::isUnderLink(dir, QtPassSettings::load().passStore)) {
23 ✔
2502
    return false;
2503
  }
2504
  PlainMessageBox::critical(
4 ✔
2505
      this, tr("Not a folder of the store"),
4 ✔
2506
      tr("%1 is, or lies behind, a symbolic link or junction. What that "
4 ✔
2507
         "points to is not part of the password store and is left alone.")
2508
          .arg(QDir::toNativeSeparators(QDir::cleanPath(dir))));
8 ✔
2509
  return true;
4 ✔
2510
}
2511

2512
void MainWindow::showShareHelp() {
1 ✔
2513
  QMessageBox::information(
2 ✔
2514
      this, tr("Sharing passwords with GPG"),
1 ✔
2515
      tr("<h3>Sharing passwords with GPG</h3>"
1 ✔
2516
         "<p>To share passwords with other users:</p>"
2517
         "<ol>"
2518
         "<li><b>Export your public key</b> and send it to teammates</li>"
2519
         "<li><b>Import teammates' public keys</b> into your GPG keyring</li>"
2520
         "<li><b>Re-encrypt passwords</b> so all recipients can decrypt "
2521
         "them</li>"
2522
         "</ol>"
2523
         "<p>Only people who have a matching secret key can decrypt the "
2524
         "passwords.</p>"
2525
         "<p><b>Tip:</b> Use the same GPG key for all shared folders.</p>"
2526
         "<p>See the FAQ for more details.</p>"));
2527
}
1 ✔
2528

2529
void MainWindow::updateGitButtonVisibility(bool uiEnabled) {
481 ✔
2530
  const AppSettings s = QtPassSettings::loadEffective();
481 ✔
2531
  // Without Git there is nothing to push or pull, ever: the buttons go, not
2532
  // grey out. While an operation runs they stay and are disabled.
2533
  const bool usable =
2534
      s.useGit && !(s.gitExecutable.isEmpty() && s.passExecutable.isEmpty());
481 ✔
2535
  ui->actionPush->setVisible(usable);
481 ✔
2536
  ui->actionUpdate->setVisible(usable);
481 ✔
2537
  // The separator in front of them would otherwise sit next to the next one.
2538
  const QList<QAction *> actions = ui->toolBar->actions();
481 ✔
2539
  const qsizetype at = actions.indexOf(ui->actionPush);
481 ✔
2540
  if (at > 0 && actions.at(at - 1)->isSeparator()) {
481 ✔
2541
    actions.at(at - 1)->setVisible(usable);
481 ✔
2542
  }
2543
  enableGitButtons(usable && uiEnabled);
481 ✔
2544
}
481 ✔
2545

2546
void MainWindow::updateOtpButtonVisibility(bool uiEnabled) {
491 ✔
2547
  // No platform gating: codes are generated in-process. Visible but disabled
2548
  // when OTP is off: the panel never shows an OTP field (a secret), so hiding
2549
  // this too would leave no trace of the feature. Honour uiEnabled, or the
2550
  // user can stack Show calls while a decrypt is in flight.
2551
  ui->actionOtp->setVisible(true);
491 ✔
2552
  ui->actionOtp->setEnabled(QtPassSettings::isUseOtp() && uiEnabled);
599 ✔
2553
}
491 ✔
2554

2555
void MainWindow::updateGrepButtonVisibility() {
211 ✔
2556
  const bool enabled = QtPassSettings::isUseGrepSearch();
211 ✔
2557
  ui->grepButton->setVisible(enabled);
211 ✔
2558
  ui->grepCaseButton->setVisible(enabled);
211 ✔
2559
  if (!enabled && m_grep.inGrepMode()) {
211 ✔
2560
    ui->grepButton->setChecked(false);
1 ✔
2561
  }
2562
}
211 ✔
2563

2564
void MainWindow::enableGitButtons(const bool &state) {
481 ✔
2565
  ui->actionPush->setEnabled(state);
481 ✔
2566
  ui->actionUpdate->setEnabled(state);
481 ✔
2567
}
481 ✔
2568

2569
void MainWindow::critical(const QString &title, const QString &msg) {
4 ✔
2570
  // Pass's messages quote store paths; see PlainMessageBox.
2571
  PlainMessageBox::critical(this, title, msg);
4 ✔
2572
}
4 ✔
2573

2574
void MainWindow::onProcessOutput(const QString &output, bool isError,
7 ✔
2575
                                 Enums::PROCESS pid) {
2576
  if (!QtPassSettings::isShowProcessOutput()) {
7 ✔
2577
    return;
2578
  }
2579
  m_processOutput->append(output, isError,
6 ✔
2580
                          ProcessOutputPanel::processName(pid));
12 ✔
2581
}
2582

2583
void MainWindow::updateProcessOutputVisibility() {
5 ✔
2584
  // The action's toggled handler shows or hides the dock.
2585
  ui->actionShowProcessOutput->setChecked(
5 ✔
2586
      QtPassSettings::isShowProcessOutput());
5 ✔
2587
  m_processOutput->setVisible(QtPassSettings::isShowProcessOutput());
5 ✔
2588
}
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