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

IJHack / QtPass / 45412276043

24 Nov 2026 02:16PM UTC coverage: 94.768% (+0.001%) from 94.767%
45412276043

Pull #2319

github

web-flow
Merge d2819b984 into 731fe85d7
Pull Request #2319: Main window: after a save, show only the entry that was saved

5 of 5 new or added lines in 2 files covered. (100.0%)

29 existing lines in 3 files now uncovered.

9835 of 10378 relevant lines covered (94.77%)

20801.62 hits per line

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

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

11
#include "qtpasslogging.h"
12

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

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

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

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

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

97
  initTextBrowser();
192 ✔
98

99
  updateProfileBox();
192 ✔
100

101
  initDisplayPanel();
192 ✔
102

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

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

113
  initTimers();
192 ✔
114

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

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

122
  setUiElementsEnabled(true);
192 ✔
123

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

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

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

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

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

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

239
void MainWindow::initTimers() {
192 ✔
240
  clearPanelTimer.setSingleShot(true);
192 ✔
241
  connect(&clearPanelTimer, &QTimer::timeout, this, [this]() { clearPanel(); });
194 ✔
242

243
  searchTimer.setInterval(350);
192 ✔
244
  searchTimer.setSingleShot(true);
192 ✔
245

246
  connect(&searchTimer, &QTimer::timeout, this, &MainWindow::onTimeoutSearch);
192 ✔
247

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

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

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

301
MainWindow::~MainWindow() {
380 ✔
302
  // Quit from the tray menu or a SIGTERM never delivers closeEvent(); the
303
  // window still knows its last geometry here.
304
  saveWindowState();
192 ✔
305
  delete m_qtPass;
192 ✔
306
}
572 ✔
307

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

347
// Idempotent; called from closeEvent() and the destructor.
348
void MainWindow::saveWindowState() {
196 ✔
349
  QtPassSettings::setGeometry(saveGeometry());
196 ✔
350
  QtPassSettings::setSavestate(saveState());
196 ✔
351
}
196 ✔
352

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

372
auto MainWindow::event(QEvent *event) -> bool {
8,809 ✔
373
  if (event->type() == QEvent::ApplicationPaletteChange) {
8,809 ✔
374
    m_themeSwitched = true;
11 ✔
375
    // Breeze may re-stamp the bars before this arrives (Plasma 6 does):
376
    // their PaletteChange then found no switch yet, so check them now too.
377
    QTimer::singleShot(0, this, &MainWindow::dropStaleToolsAreaPalettes);
11 ✔
378
  }
379
  return QMainWindow::event(event);
8,809 ✔
380
}
381

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

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

411
void MainWindow::initToolBarButtons() {
192 ✔
412
  connect(ui->actionAddPassword, &QAction::triggered, this,
192 ✔
413
          &MainWindow::addPassword);
192 ✔
414
  connect(ui->actionAddFolder, &QAction::triggered, this,
192 ✔
415
          &MainWindow::addFolder);
192 ✔
416
  connect(ui->actionEdit, &QAction::triggered, this, &MainWindow::onEdit);
192 ✔
417
  connect(ui->actionDelete, &QAction::triggered, this, &MainWindow::onDelete);
192 ✔
418
  connect(ui->actionPush, &QAction::triggered, this, &MainWindow::onPush);
192 ✔
419
  connect(ui->actionUpdate, &QAction::triggered, this, &MainWindow::onUpdate);
192 ✔
420
  connect(ui->actionUsers, &QAction::triggered, this, &MainWindow::onUsers);
192 ✔
421
  connect(ui->actionConfig, &QAction::triggered, this, &MainWindow::onConfig);
192 ✔
422
  connect(ui->actionOtp, &QAction::triggered, this, &MainWindow::onOtp);
192 ✔
423

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

452
  ui->actionAddPassword->setIcon(
192 ✔
453
      QIcon::fromTheme("document-new", QIcon(":/icons/document-new.svg")));
768 ✔
454
  ui->actionAddFolder->setIcon(
192 ✔
455
      QIcon::fromTheme("folder-new", QIcon(":/icons/folder-new.svg")));
768 ✔
456
  ui->actionEdit->setIcon(QIcon::fromTheme(
192 ✔
457
      "document-properties", QIcon(":/icons/document-properties.svg")));
576 ✔
458
  ui->actionDelete->setIcon(
192 ✔
459
      QIcon::fromTheme("edit-delete", QIcon(":/icons/edit-delete.svg")));
768 ✔
460
  ui->actionPush->setIcon(
192 ✔
461
      QIcon::fromTheme("go-up", QIcon(":/icons/go-top.svg")));
768 ✔
462
  ui->actionUpdate->setIcon(
192 ✔
463
      QIcon::fromTheme("go-down", QIcon(":/icons/go-bottom.svg")));
768 ✔
464
  ui->actionUsers->setIcon(QIcon::fromTheme(
192 ✔
465
      "x-office-address-book", QIcon(":/icons/x-office-address-book.svg")));
576 ✔
466
  ui->actionConfig->setIcon(QIcon::fromTheme(
192 ✔
467
      "applications-system", QIcon(":/icons/applications-system.svg")));
384 ✔
468
}
192 ✔
469

470
void MainWindow::initStatusBar() {
192 ✔
471
  ui->statusBar->showMessage(tr("Welcome to QtPass %1").arg(VERSION), 2000);
384 ✔
472

473
  QPixmap logo = QPixmap::fromImage(QImage(":/artwork/icon.svg"))
384 ✔
474
                     .scaledToHeight(statusBar()->height());
192 ✔
475
  auto *logoApp = new QLabel(statusBar());
192 ✔
476
  logoApp->setPixmap(logo);
192 ✔
477
  statusBar()->addPermanentWidget(logoApp);
192 ✔
478
}
192 ✔
479

480
auto MainWindow::getCurrentTreeViewIndex() -> QModelIndex {
11 ✔
481
  return ui->treeView->currentIndex();
11 ✔
482
}
483

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

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

519
void MainWindow::applyTextBrowserSettings() {
4 ✔
520
  const AppSettings s = QtPassSettings::load();
4 ✔
521
  if (s.useMonospace) {
4 ✔
522
    QFont monospace("Monospace");
1 ✔
523
    monospace.setStyleHint(QFont::Monospace);
1 ✔
524
    ui->textBrowser->setFont(monospace);
1 ✔
525
  } else {
1 ✔
526
    ui->textBrowser->setFont(QFont());
3 ✔
527
  }
528

529
  if (s.noLineWrapping) {
4 ✔
530
    ui->textBrowser->setLineWrapMode(QTextBrowser::NoWrap);
1 ✔
531
  } else {
532
    ui->textBrowser->setLineWrapMode(QTextBrowser::WidgetWidth);
3 ✔
533
  }
534
}
4 ✔
535

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

555
auto MainWindow::config() -> bool {
7 ✔
556
  if (m_freshStart) {
7 ✔
557
    // No usable configuration yet: the wizard finds the programs, the key
558
    // and the store, and creates the store when it has to.
559
    FirstRunWizard wizard(this);
2 ✔
560
    if (wizard.exec() != QDialog::Accepted) {
2 ✔
561
      return false;
562
    }
563
  } else {
2 ✔
564
    ConfigDialog d(this);
5 ✔
565
    d.setModal(true);
5 ✔
566
    if (d.exec() != QDialog::Accepted) {
5 ✔
567
      return false;
568
    }
569
  }
5 ✔
570

571
  applyTextBrowserSettings();
4 ✔
572
  applyWindowFlagsSettings();
4 ✔
573

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

592
  Pass *activePass = QtPassSettings::getPass();
4 ✔
593
  activePass->updateEnv();
4 ✔
594
  m_tree->setPass(activePass);
4 ✔
595
  clearPanelTimer.setInterval(MS_PER_SECOND * s.autoclearPanelSeconds);
4 ✔
596
  m_qtPass->clipboard().setAutoclearTimer();
4 ✔
597

598
  updateGitButtonVisibility();
4 ✔
599
  updateOtpButtonVisibility();
4 ✔
600
  updateGrepButtonVisibility();
4 ✔
601
  updateProcessOutputVisibility();
4 ✔
602
#ifndef Q_OS_MACOS
603
  // The action's toggled handler shows or hides the bar (and saves again).
604
  ui->actionShowMenuBar->setChecked(s.showMenuBar);
4 ✔
605
#endif
606
  if (s.useTrayIcon && m_tray == nullptr) {
4 ✔
607
    initTrayIcon();
1 ✔
608
  } else if (!s.useTrayIcon && m_tray != nullptr) {
3 ✔
UNCOV
609
    destroyTrayIcon();
×
610
  }
611

612
  // Stay fresh-start while the configuration is unusable, so the
613
  // constructor's loop re-runs the wizard. The re-prompt lives there:
614
  // recursing here never reported a cancel back to the caller.
615
  if (Util::configIsValid(s)) {
4 ✔
616
    m_freshStart = false;
4 ✔
617
  }
618
  return true;
619
}
4 ✔
620

621
void MainWindow::onUpdate(bool block) {
2 ✔
622
  ui->statusBar->showMessage(tr("Updating password-store"), 2000);
2 ✔
623
  if (block) {
2 ✔
624
    QtPassSettings::getPass()->GitPull_b(Pass::kBlockingPullMs);
1 ✔
625
  } else {
626
    QtPassSettings::getPass()->GitPull();
1 ✔
627
  }
628
}
2 ✔
629

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

637
void MainWindow::onAutoPush() {
8 ✔
638
  if (QtPassSettings::isUseGit()) {
8 ✔
639
    ui->statusBar->showMessage(tr("Updating password-store"), 2000);
8 ✔
640
    QtPassSettings::getPass()->GitPushAutomatic();
8 ✔
641
  }
642
}
8 ✔
643

644
auto MainWindow::getFile(const QModelIndex &index, bool forPass) -> QString {
66 ✔
645
  return m_tree->fileFor(index, forPass);
66 ✔
646
}
647

648
void MainWindow::on_treeView_clicked(const QModelIndex &index) {
28 ✔
649
  bool cleared = ui->treeView->currentIndex().flags() == Qt::NoItemFlags;
28 ✔
650
  QString file = getFile(index, true);
28 ✔
651
  ui->passwordName->setText(Util::shownName(file));
56 ✔
652
  if (!file.isEmpty() && !cleared) {
28 ✔
653
    // Remember what the panel is about to show, so onOtp() can tell whether the
654
    // code it can see belongs to the entry that is currently selected.
655
    m_shownFile = file;
27 ✔
656
    QtPassSettings::getPass()->Show(file);
54 ✔
657
  } else {
658
    m_shownFile.clear();
1 ✔
659
    clearPanel(false);
1 ✔
660
    ui->actionEdit->setEnabled(false);
1 ✔
661
    ui->actionDelete->setEnabled(true);
1 ✔
662
  }
663
}
28 ✔
664

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

668
  if (fileOrFolder.isFile()) {
4 ✔
669
    editPassword(getFile(index, true));
6 ✔
670
  }
671
}
4 ✔
672

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

688
void MainWindow::executeWrapperStarted() {
69 ✔
689
  m_displayPanel->clear();
69 ✔
690
  m_panelEntry.clear();
69 ✔
691
  ui->textBrowser->clear();
69 ✔
692
  setUiElementsEnabled(false);
69 ✔
693
  clearPanelTimer.stop();
69 ✔
694
  if (QtPassSettings::isShowProcessOutput()) {
69 ✔
695
    m_processOutput->setVisible(true);
64 ✔
696
  }
697
}
69 ✔
698

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

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

735
  m_displayPanel->clear();
31 ✔
736
  m_panelEntry.clear();
31 ✔
737

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

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

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

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

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

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

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

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

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

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

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

892
  applyWindowFlagsSettings();
203 ✔
893

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

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

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

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

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

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

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

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

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

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

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

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

1051
void MainWindow::refreshMarkedSecrets(const AppSettings &s) {
39 ✔
1052
  if (s.hidePassword) {
39 ✔
1053
    m_displayPanel->setMarkedSecrets(
4 ✔
1054
        TemplateIO::secretFieldsIn(s.passTemplate) +
8 ✔
1055
        TemplateIO::readSecretFields(s.passStore));
12 ✔
1056
  }
1057
}
39 ✔
1058

1059
auto MainWindow::grepLineForDisplay(const QString &line,
41 ✔
1060
                                    const AppSettings &s) const -> QString {
1061
  const QString hidden =
1062
      QStringLiteral("***") + tr("hidden") + QStringLiteral("***");
82 ✔
1063
  if (NativeGrep::isOtpMarker(line)) {
41 ✔
1064
    return tr("One-time password secret: %1").arg(hidden);
2 ✔
1065
  }
1066
  // The panel's own rules: the password and a field it would put behind
1067
  // the eye button keep their value out of the list too.
1068
  if (NativeGrep::isPasswordMatch(line)) {
1069
    return m_displayPanel->hides(QObject::tr("Password"), s)
52 ✔
1070
               ? tr("Password: %1").arg(hidden)
52 ✔
1071
               : NativeGrep::passwordMatchText(line);
26 ✔
1072
  }
1073
  if (const qsizetype colon = line.indexOf(QLatin1Char(':')); colon > 0) {
13 ✔
1074
    if (m_displayPanel->hides(line.left(colon).trimmed(), s)) {
33 ✔
1075
      return line.left(colon + 1) + QLatin1Char(' ') + hidden;
4 ✔
1076
    }
1077
  }
1078
  return line;
1079
}
1080

1081
void MainWindow::onGrepFinished(
19 ✔
1082
    const QList<QPair<QString, QStringList>> &results) {
1083
  // Both backends stay connected, each with its own search: a search the
1084
  // other backend was still running when Settings switched backends is not
1085
  // this one, whatever the controller's state, and searched another store.
1086
  // Dropped before it can end (or be taken for) the current search.
1087
  if (const QObject *from = sender();
19 ✔
1088
      from != nullptr && from != QtPassSettings::getPass()) {
19 ✔
1089
    return;
11 ✔
1090
  }
1091
  const GrepSearchController::FinishOutcome outcome = m_grep.finishSearch();
1092
  if (outcome.restoreCursor) {
18 ✔
1093
    QApplication::restoreOverrideCursor();
2 ✔
1094
  }
1095
  // Re-enable the UI before the discard check so a cancelled search can never
1096
  // leave controls disabled.
1097
  setUiElementsEnabled(true);
18 ✔
1098
  if (outcome.discard) {
18 ✔
1099
    return;
1100
  }
1101
  if (!m_grep.inGrepMode())
10 ✔
1102
    return;
1103
  ui->grepResultsList->clear();
10 ✔
1104
  if (results.isEmpty()) {
10 ✔
1105
    ui->statusBar->showMessage(tr("No matches found."), 3000);
2 ✔
1106
    showContentResults(false);
2 ✔
1107
    return;
2 ✔
1108
  }
1109
  const AppSettings s = QtPassSettings::load();
8 ✔
1110
  const bool hideContent = s.hideContent;
8 ✔
1111
  refreshMarkedSecrets(s);
8 ✔
1112
  int totalLines = 0;
1113
  int entries = 0;
1114
  bool stopped = false;
1115
  for (const auto &pair : results) {
39 ✔
1116
    if (NativeGrep::isStoppedMarker(pair)) {
31 ✔
1117
      stopped = true;
UNCOV
1118
      continue;
×
1119
    }
1120
    ++entries;
31 ✔
1121
    auto *entryItem = new QTreeWidgetItem(ui->grepResultsList);
31 ✔
1122
    entryItem->setText(0, pair.first);
31 ✔
1123
    entryItem->setData(0, Qt::UserRole, pair.first);
31 ✔
1124
    for (const QString &line : pair.second) {
72 ✔
1125
      auto *lineItem = new QTreeWidgetItem(entryItem);
41 ✔
1126
      // The marker is no content: shown as it is with hidden content too,
1127
      // and not counted as a match.
1128
      if (NativeGrep::isMoreMarker(line)) {
41 ✔
UNCOV
1129
        lineItem->setText(0, tr("… more matches in this entry"));
×
1130
      } else {
1131
        lineItem->setText(0, hideContent ? "***" + tr("Content hidden") + "***"
82 ✔
1132
                                         : grepLineForDisplay(line, s));
1133
        ++totalLines;
41 ✔
1134
      }
1135
      lineItem->setData(0, Qt::UserRole, pair.first);
41 ✔
1136
    }
1137
  }
1138
  ui->grepResultsList->expandAll();
8 ✔
1139
  showContentResults(true);
8 ✔
1140
  if (stopped) {
8 ✔
1141
    // The search stopped there; more entries may match.
UNCOV
1142
    ui->statusBar->showMessage(
×
UNCOV
1143
        tr("Showing the first %n match(es); search for something narrower "
×
1144
           "to see the rest.",
1145
           nullptr, totalLines),
1146
        10000);
1147
  } else {
1148
    ui->statusBar->showMessage(tr("Found %n match(es)", nullptr, totalLines) +
24 ✔
1149
                                   " " +
8 ✔
1150
                                   tr("in %n entr(ies).", nullptr, entries),
16 ✔
1151
                               3000);
1152
  }
1153
  if (s.useAutoclearPanel)
8 ✔
1154
    clearPanelTimer.start();
1 ✔
1155
}
8 ✔
1156

1157
void MainWindow::on_grepResultsList_itemClicked(QTreeWidgetItem *item,
2 ✔
1158
                                                int /*column*/) {
1159
  const AppSettings s = QtPassSettings::load();
2 ✔
1160
  const QString entry = item->data(0, Qt::UserRole).toString();
2 ✔
1161
  if (entry.isEmpty())
2 ✔
1162
    return;
1163
  const QString fullPath =
1164
      QDir::cleanPath(QDir(s.passStore).filePath(entry + ".gpg"));
4 ✔
1165
  // Persistent: setCurrentIndex() runs the selection handlers, which can
1166
  // change the model before the click is handled.
1167
  const QPersistentModelIndex proxyIndex(m_tree->indexFor(fullPath));
2 ✔
1168
  if (!proxyIndex.isValid())
2 ✔
1169
    return;
1170
  ui->treeView->setCurrentIndex(proxyIndex);
2 ✔
1171
  if (!proxyIndex.isValid())
2 ✔
1172
    return;
1173
  on_treeView_clicked(proxyIndex);
2 ✔
1174
  if (s.hideContent || s.useAutoclearPanel)
2 ✔
1175
    ui->grepResultsList->clear();
1 ✔
1176
  showContentResults(false);
2 ✔
1177
  ui->treeView->scrollTo(proxyIndex);
2 ✔
1178
  ui->treeView->setFocus();
2 ✔
1179
}
4 ✔
1180

1181
void MainWindow::showContentResults(bool shown) {
33 ✔
1182
  ui->grepResultsList->setVisible(shown);
33 ✔
1183
  ui->treeView->setVisible(!shown);
33 ✔
1184
  if (shown) {
33 ✔
1185
    // The tree's current entry is out of sight: Delete, Edit and OTP would
1186
    // act on it, not on a result. Opening a result shows the tree again.
1187
    ui->actionDelete->setEnabled(false);
8 ✔
1188
    ui->actionEdit->setEnabled(false);
8 ✔
1189
    updateOtpButtonVisibility(false);
8 ✔
1190
  } else if (ui->treeView->selectionModel()->hasSelection()) {
25 ✔
1191
    // Only for an entry still selected: with nothing selected there is no
1192
    // entry for Edit and Delete to act on.
1193
    setUiElementsEnabled(m_uiEnabled);
8 ✔
1194
  }
1195
}
33 ✔
1196

1197
void MainWindow::cancelContentSearch() {
25 ✔
1198
  QtPassSettings::getRealPass()->CancelGrep();
25 ✔
1199
  QtPassSettings::getImitatePass()->CancelGrep();
25 ✔
1200
}
25 ✔
1201

1202
void MainWindow::selectFirstFile() {
34 ✔
1203
  // The entry named exactly as typed wins: with folders sorted first, the
1204
  // depth-first walk found team/bank before bank.
1205
  QModelIndex index = exactMatch();
34 ✔
1206
  if (!index.isValid()) {
1207
    index = firstFile(m_tree->rootIndex());
17 ✔
1208
  }
1209
  ui->treeView->setCurrentIndex(index);
34 ✔
1210
}
34 ✔
1211

1212
namespace {
1213
/**
1214
 * @brief @p path with each part below @p store spelled as stored on disk.
1215
 *
1216
 * Where the file system ignores case, "Bank.gpg" exists while the file is
1217
 * bank.gpg, and the tree knows the entry only by that spelling.
1218
 * @param store The store folder.
1219
 * @param path An existing file in the store.
1220
 * @return @p path itself when every part is spelled as stored, otherwise
1221
 *         the path with the stored spelling.
1222
 */
1223
auto spelledAsStored(const QString &store, const QString &path) -> QString {
28 ✔
1224
  const QStringList parts = QDir(store).relativeFilePath(path).split(
56 ✔
1225
      QLatin1Char('/'), Qt::SkipEmptyParts);
28 ✔
1226
  QDir dir(store);
28 ✔
1227
  bool respelled = false;
1228
  for (int i = 0; i < parts.size(); ++i) {
31 ✔
1229
    const bool leaf = i == parts.size() - 1;
31 ✔
1230
    const QStringList names =
1231
        dir.entryList((leaf ? QDir::Files : QDir::Dirs) | QDir::Hidden |
31 ✔
1232
                      QDir::NoDotAndDotDot);
34 ✔
1233
    QString name = parts.at(i);
1234
    if (!names.contains(name)) {
31 ✔
UNCOV
1235
      const auto stored = std::find_if(
×
1236
          names.cbegin(), names.cend(), [&name](const QString &candidate) {
1237
            return candidate.compare(name, Qt::CaseInsensitive) == 0;
×
1238
          });
1239
      if (stored == names.cend()) {
×
1240
        return path;
1241
      }
UNCOV
1242
      name = *stored;
×
1243
      respelled = true;
1244
    }
1245
    if (leaf) {
31 ✔
1246
      return respelled ? QDir::cleanPath(dir.filePath(name)) : path;
56 ✔
1247
    }
1248
    if (!dir.cd(name)) {
3 ✔
1249
      return path;
1250
    }
1251
  }
1252
  return path;
1253
}
28 ✔
1254
} // namespace
1255

1256
auto MainWindow::exactMatchPath() -> QString {
47 ✔
1257
  const QString text = QDir::fromNativeSeparators(ui->lineEdit->text());
94 ✔
1258
  const QString store = QtPassSettings::getPassStore();
94 ✔
1259
  // A name may begin or end with a space: " bank" is that entry, not bank.
1260
  // Only when no entry is named so are spaces around the text dropped.
1261
  for (const QString &typed : {text, text.trimmed()}) {
181 ✔
1262
    if (typed.isEmpty()) {
68 ✔
UNCOV
1263
      continue;
×
1264
    }
1265
    const QString path =
1266
        QDir::cleanPath(QDir(store).filePath(typed + QStringLiteral(".gpg")));
136 ✔
1267
    if (PathValidator::isPathInStore(store, path) && QFileInfo(path).isFile()) {
68 ✔
1268
      return spelledAsStored(store, path);
28 ✔
1269
    }
1270
  }
141 ✔
1271
  return {};
19 ✔
1272
}
1273

1274
auto MainWindow::exactMatch() -> QModelIndex {
44 ✔
1275
  const QString path = exactMatchPath();
44 ✔
1276
  if (path.isEmpty()) {
44 ✔
1277
    return {};
18 ✔
1278
  }
1279
  // indexFor() maps through the filter: a row the filter hides is no match.
1280
  const QModelIndex index = m_tree->indexFor(path);
26 ✔
1281
  if (!index.isValid() || !m_tree->fileInfo(index).isFile()) {
50 ✔
1282
    return {};
2 ✔
1283
  }
1284
  return index;
24 ✔
1285
}
1286

1287
void MainWindow::applySearchText(const QString &text) {
9 ✔
1288
  // A name search: content search, left on, kept its results over the tree
1289
  // and ignored the text.
1290
  if (ui->grepButton->isChecked()) {
9 ✔
1291
    ui->grepButton->setChecked(false);
1 ✔
1292
  }
1293
  delete m_pendingOpen;
9 ✔
1294
  ui->lineEdit->setText(text);
9 ✔
1295
  // Filter now, not after the search delay: the timer would leave the tree
1296
  // as the previous text filtered it.
1297
  searchTimer.stop();
9 ✔
1298
  onTimeoutSearch();
9 ✔
1299
  if (const QModelIndex exact = exactMatch(); exact.isValid()) {
9 ✔
1300
    openExactMatch(exact);
6 ✔
1301
    return;
6 ✔
1302
  }
1303
  // The tree loads folders in the background: at start, or right after the
1304
  // window is shown again, an entry that exists may not be in it yet. Try
1305
  // again as folders finish loading, for a few seconds, unless the search
1306
  // text changes meanwhile: any change ends the wait, even one typed back to
1307
  // this text, which is a new search that has not asked to open anything.
1308
  if (exactMatchPath().isEmpty()) {
6 ✔
1309
    return;
1310
  }
1311
  auto *pending = new QObject(this);
2 ✔
1312
  m_pendingOpen = pending;
1313
  QTimer::singleShot(5000, pending, &QObject::deleteLater);
2 ✔
1314
  // Disconnected at once: with deleteLater() alone, a folder that finished
1315
  // loading before the deletion still ran the open, or ran it twice.
1316
  const auto stop = [this, pending] {
2 ✔
1317
    disconnect(&m_tree->fileSystem(), nullptr, pending, nullptr);
2 ✔
1318
    disconnect(ui->lineEdit, nullptr, pending, nullptr);
2 ✔
1319
    pending->deleteLater();
2 ✔
1320
  };
4 ✔
1321
  connect(ui->lineEdit, &QLineEdit::textChanged, pending, stop);
2 ✔
1322
  connect(&m_tree->fileSystem(), &QFileSystemModel::directoryLoaded, pending,
2 ✔
1323
          [this, stop](const QString &) {
4 ✔
1324
            searchTimer.stop();
1 ✔
1325
            onTimeoutSearch();
1 ✔
1326
            if (const QModelIndex exact = exactMatch(); exact.isValid()) {
1 ✔
1327
              stop();
1 ✔
1328
              openExactMatch(exact);
1 ✔
1329
            }
1330
          });
1 ✔
1331
}
1332

1333
void MainWindow::openExactMatch(const QModelIndex &index) {
7 ✔
1334
  // Made current here, not left to the filter pass before: the tree may have
1335
  // moved its current row since, and with none on_treeView_clicked() only
1336
  // names the entry without decrypting it.
1337
  ui->treeView->setCurrentIndex(index);
7 ✔
1338
  on_treeView_clicked(index);
7 ✔
1339
}
7 ✔
1340

1341
auto MainWindow::firstFile(QModelIndex parentIndex) -> QModelIndex {
26 ✔
1342
  StoreModel &proxy = m_tree->proxy();
26 ✔
1343
  int numRows = proxy.rowCount(parentIndex);
26 ✔
1344
  for (int row = 0; row < numRows; ++row) {
33 ✔
1345
    QModelIndex index = proxy.index(row, 0, parentIndex);
24 ✔
1346
    if (m_tree->fileInfo(index).isFile()) {
24 ✔
1347
      return index;
17 ✔
1348
    }
1349
    if (proxy.hasChildren(index)) {
14 ✔
1350
      QModelIndex childFile = firstFile(index);
9 ✔
1351
      if (childFile.isValid())
1352
        return childFile;
7 ✔
1353
    }
1354
  }
1355
  return QModelIndex();
9 ✔
1356
}
1357

1358
// Guards the input dialogs (create, move, rename) against names like
1359
// "../../etc/passwd" or absolute paths escaping the store root.
1360
auto MainWindow::confirmPathInStore(const QString &candidate) -> bool {
10 ✔
1361
  if (PathValidator::isPathInStore(QtPassSettings::getPassStore(), candidate)) {
20 ✔
1362
    return true;
1363
  }
1364
  QMessageBox::warning(this, tr("Invalid name"),
9 ✔
1365
                       tr("That name would resolve outside the password "
3 ✔
1366
                          "store. Please choose a different name."));
1367
  return false;
3 ✔
1368
}
1369

1370
void MainWindow::setPassword(const QString &file, bool isNew) {
8 ✔
1371
  const AppSettings s = QtPassSettings::load();
8 ✔
1372
  PasswordDialog d(QtPassSettings::getPass(), s, file, isNew, this);
8 ✔
1373
  // A copy out of the editor is autocleared like one from the display.
1374
  connect(&d, &PasswordDialog::copied, &m_qtPass->clipboard(),
8 ✔
1375
          &ClipboardManager::trackCopied);
8 ✔
1376

1377
  if (isNew) {
8 ✔
1378
    const QString storePath = s.passStore;
1379
    QString folder = m_tree->currentDir(false);
2 ✔
1380
    if (folder.isEmpty()) {
2 ✔
UNCOV
1381
      folder = storePath;
×
1382
    }
1383
    // Folders to pick from, the tree's current one preselected. Real folders
1384
    // only: a linked or junctioned one would write the entry outside the store.
1385
    QStringList folders{QString()};
4 ✔
1386
    const QStringList found = Util::directoriesUnder(storePath);
2 ✔
1387
    for (const QString &path : found) {
36 ✔
1388
      const QString rel = QDir(storePath).relativeFilePath(path);
34 ✔
1389
      if (!rel.startsWith(u'.') && !rel.contains(QStringLiteral("/."))) {
102 ✔
1390
        folders << rel;
1391
      }
1392
    }
1393
    std::sort(folders.begin() + 1, folders.end());
2 ✔
1394
    d.setNewEntryLocation(storePath, folders,
2 ✔
1395
                          QDir(storePath).relativeFilePath(folder));
4 ✔
1396
    QHash<QString, QStringList> templates =
1397
        TemplateIO::readTemplates(storePath);
2 ✔
1398
    if (!templates.isEmpty()) {
1399
      QString defaultTemplate =
1400
          TemplateIO::getFolderTemplate(folder, storePath);
1 ✔
1401
      d.setAvailableTemplates(templates, defaultTemplate);
1 ✔
1402
    }
1403
  }
2 ✔
1404

1405
  m_editDialog = &d;
1406
  if (!d.exec()) {
8 ✔
1407
    ui->treeView->setFocus();
7 ✔
1408
  }
1409
  m_editDialog.clear();
1410
}
8 ✔
1411

1412
void MainWindow::addPassword() { setPassword(QString()); }
4 ✔
1413

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

1473
auto MainWindow::confirmLinkRemoval(const QString &file) -> bool {
1 ✔
1474
  // Only the link goes (ImitatePass::Remove unlinks it); nothing behind it
1475
  // is looked at or mentioned.
1476
  return PlainMessageBox::askYes(
1 ✔
1477
      this, tr("Delete link?"),
1 ✔
1478
      tr("%1 is a symbolic link or junction. Remove the link? What it "
1 ✔
1479
         "points to is left alone.")
1480
          .arg(Util::displayable(QDir::separator() + file, false)));
2 ✔
1481
}
1482

1483
void MainWindow::onDelete() {
13 ✔
1484
  const QModelIndex currentIndex = ui->treeView->currentIndex();
13 ✔
1485
  // While content search results hide the tree, its current entry is not
1486
  // what the user looks at (the Delete key comes here directly).
1487
  if (!currentIndex.isValid() || ui->treeView->isHidden()) {
11 ✔
1488
    // Otherwise the whole password directory would be deleted (#556).
1489
    return;
10 ✔
1490
  }
1491

1492
  const bool isDir = !m_tree->fileInfo(currentIndex).isFile();
9 ✔
1493
  const QString file =
1494
      isDir ? m_tree->currentDir(true) : getFile(currentIndex, true);
9 ✔
1495
  const QString folder =
1496
      m_tree->fileSystem().rootPath() + QDir::separator() + file;
9 ✔
1497
  const bool linkedFolder = isDir && Util::isLinkedFolder(folder);
9 ✔
1498

1499
  if (!linkedFolder && refuseLinkedFolder(folder)) {
8 ✔
1500
    // Behind a link: deleting would reach outside the store.
1501
    return;
1502
  }
1503
  const bool confirmed =
1504
      linkedFolder ? confirmLinkRemoval(file) : confirmDeletion(file, isDir);
9 ✔
1505
  if (!confirmed) {
9 ✔
1506
    return;
1507
  }
1508
  QtPassSettings::getPass()->Remove(file, isDir);
6 ✔
1509
}
1510

1511
void MainWindow::cancelOtpRequest() {
91 ✔
1512
  m_otpRequestFile.clear();
91 ✔
1513
  m_copyRequestFile.clear();
91 ✔
1514
}
91 ✔
1515

1516
void MainWindow::onOperationError() {
35 ✔
1517
  cancelOtpRequest();
35 ✔
1518
  // executeWrapperStarted() emptied the panel and the browser when the
1519
  // operation started (a refusal says so too); what is left to forget is
1520
  // which entry the panel was about to show.
1521
  m_shownFile.clear();
35 ✔
1522
  // A save's refresh waiting for its push is dropped: it would clear the
1523
  // push's error (or whatever failed before it) from the browser.
1524
  m_refreshAfterPush.clear();
35 ✔
1525
  m_refreshAfterPushOwner = nullptr;
1526
}
35 ✔
1527

1528
// Derives the code in-process from one decrypt, so it works with either
1529
// backend on every platform; otpFromFileToClipboard() finishes the job.
1530
void MainWindow::onOtp() {
12 ✔
1531
  if (ui->treeView->isHidden()) {
12 ✔
1532
    return;
4 ✔
1533
  }
1534
  QString file = getFile(ui->treeView->currentIndex(), true);
11 ✔
1535
  if (file.isEmpty()) {
11 ✔
1536
    flashText(tr("No password selected for OTP generation"), true);
1 ✔
1537
    return;
1 ✔
1538
  }
1539
  if (!QtPassSettings::isUseOtp()) {
10 ✔
1540
    // Normally unreachable (the action is hidden), but never fail silently.
1541
    flashText(tr("No OTP code found in this password entry"), true);
1 ✔
1542
    return;
1 ✔
1543
  }
1544

1545
  // Fast path: the panel shows a live code, so no decrypt, and one clipboard
1546
  // write (two setMimeData calls in one turn can empty the Windows
1547
  // clipboard). Only for *this* entry: arrow keys and right-click move
1548
  // currentIndex without QTreeView::clicked, so the code may be another's.
1549
  const QString shown =
1550
      (m_shownFile == file) ? m_displayPanel->currentOtpCode() : QString();
9 ✔
1551
  if (!shown.isEmpty()) {
9 ✔
1552
    m_qtPass->clipboard().copyText(shown);
1 ✔
1553
    showStatusMessage(tr("OTP code copied to clipboard"));
2 ✔
1554
    return;
1555
  }
1556

1557
  // Fallback: decrypt once. The request file keeps passShowHandler from
1558
  // copying the password and tells otpFromFileToClipboard its answer.
1559
  m_otpRequestFile = file;
8 ✔
1560
  setUiElementsEnabled(false);
8 ✔
1561
  // Keep the marker in step so a second request takes the fast path; safe as
1562
  // executeWrapperStarted() clears the panel, so a failed decrypt shows none.
1563
  m_shownFile = file;
8 ✔
1564
  QtPassSettings::getPass()->Show(file);
16 ✔
1565
}
1566

1567
void MainWindow::onEdit() {
1 ✔
1568
  if (ui->treeView->isHidden()) {
1 ✔
1569
    return;
1 ✔
1570
  }
1571
  QString file = getFile(ui->treeView->currentIndex(), true);
×
1572
  editPassword(file);
×
1573
}
1574

1575
void MainWindow::onUsers() {
2 ✔
1576
  const QString dir = m_tree->currentDir(false);
2 ✔
1577
  if (refuseLinkedFolder(dir)) {
2 ✔
1578
    return;
1579
  }
1580

1581
  UsersDialog d(QtPassSettings::getPass(), QtPassSettings::load(), dir, this);
1 ✔
1582
  if (!d.exec()) {
1 ✔
1583
    ui->treeView->setFocus();
1 ✔
1584
  }
1585
}
1 ✔
1586

1587
void MainWindow::messageAvailable(const QString &message) {
10 ✔
1588
  show();
10 ✔
1589
  raise();
10 ✔
1590
  if (message.isEmpty()) {
10 ✔
1591
    focusInput();
1 ✔
1592
  } else {
1593
    ui->treeView->expandAll();
9 ✔
1594
    applySearchText(message);
9 ✔
1595
  }
1596
}
10 ✔
1597

1598
void MainWindow::updateProfileBox() {
200 ✔
1599
  const Profiles profiles = QtPassSettings::getProfiles();
200 ✔
1600
  bool activeGone = false;
1601

1602
  if (profiles.isEmpty()) {
7 ✔
1603
    ui->profileWidget->hide();
193 ✔
1604
  } else {
1605
    ui->profileWidget->show();
7 ✔
1606
    // A refill is no choice of the user's: clearing and adding items moves
1607
    // the current text, which would otherwise switch profiles.
1608
    const QSignalBlocker quiet(ui->profileBox);
7 ✔
1609
    ui->profileBox->clear();
7 ✔
1610
    for (auto i = profiles.cbegin(); i != profiles.cend(); ++i) {
19 ✔
1611
      if (!i.key().isEmpty()) {
12 ✔
1612
        ui->profileBox->addItem(i.key());
12 ✔
1613
      }
1614
    }
1615
    ui->profileBox->model()->sort(0);
7 ✔
1616
    int index = ui->profileBox->findText(QtPassSettings::getProfile());
14 ✔
1617
    if (index != -1) { //  -1 for not found
7 ✔
1618
      ui->profileBox->setCurrentIndex(index);
6 ✔
1619
    } else if (ui->profileBox->count() > 0) {
1 ✔
1620
      // The active profile is gone (removed in Settings): the box shows the
1621
      // first one, and the settings and backend must follow it, or the
1622
      // removed profile's store stays in use behind it.
1623
      ui->profileBox->setCurrentIndex(0);
1 ✔
1624
      activeGone = true;
1625
    }
1626
  }
7 ✔
1627
  if (activeGone) {
7 ✔
1628
    on_profileBox_currentTextChanged(ui->profileBox->currentText());
2 ✔
1629
  }
1630
  updateProfileBoxEnabled();
200 ✔
1631
}
200 ✔
1632

1633
void MainWindow::updateProfileBoxEnabled() {
680 ✔
1634
  // No profile switch while anything of the store runs or waits: the
1635
  // backend's store and environment would change under it, and what is
1636
  // still queued (a push after a save, say) would finish for the other
1637
  // profile (#2071). Asked of the backend, not only of the interface: the
1638
  // watchdog releases the interface while a slow gpg or git still runs.
1639
  // Every backend: one kept from before a switch of backend may still
1640
  // run what was queued on it.
1641
  ui->profileBox->setEnabled(m_uiEnabled && ui->profileBox->count() > 1 &&
1,362 ✔
1642
                             QtPassSettings::backendsIdle());
14 ✔
1643
}
680 ✔
1644

1645
void MainWindow::on_profileBox_currentTextChanged(const QString &name) {
6 ✔
1646
  if (m_freshStart || name == QtPassSettings::getProfile()) {
18 ✔
1647
    return;
1 ✔
1648
  }
1649
  // The box is disabled while anything runs; should a change come through
1650
  // anyway, the active profile stays and the box says so again.
1651
  if (!m_uiEnabled || !QtPassSettings::backendsIdle()) {
5 ✔
1652
    const QSignalBlocker quiet(ui->profileBox);
×
1653
    ui->profileBox->setCurrentText(QtPassSettings::getProfile());
×
1654
    return;
1655
  }
×
1656
  // A content search runs outside the queue: leaving grep mode cancels it,
1657
  // so its results for the old store are dropped, not shown for the new.
1658
  if (m_grep.inGrepMode()) {
5 ✔
1659
    ui->grepButton->setChecked(false);
1 ✔
1660
  }
1661

1662
  ui->lineEdit->clear();
5 ✔
1663

1664
  const Profile prof = QtPassSettings::getProfiles().value(name);
10 ✔
1665
  AppSettings s = QtPassSettings::load();
5 ✔
1666
  s.activeProfile = name;
5 ✔
1667
  s.passStore = prof.path;
5 ✔
1668
  s.passSigningKey = prof.signingKey;
5 ✔
1669
  // A profile without its own Git flags keeps the global values.
1670
  s.useGit = prof.useGit.value_or(s.useGit);
5 ✔
1671
  s.autoPush = prof.autoPush.value_or(s.autoPush);
5 ✔
1672
  s.autoPull = prof.autoPull.value_or(s.autoPull);
5 ✔
1673
  QtPassSettings::save(s);
5 ✔
1674
  ui->statusBar->showMessage(tr("Profile changed to %1").arg(name), 2000);
10 ✔
1675

1676
  QtPassSettings::getPass()->updateEnv();
5 ✔
1677

1678
  m_tree->setStore(QtPassSettings::getPassStore());
10 ✔
1679
  deselect();
5 ✔
1680
  ui->treeView->setCurrentIndex(QModelIndex());
5 ✔
1681
}
5 ✔
1682

1683
void MainWindow::initTrayIcon() {
3 ✔
1684
  m_tray = new TrayIcon(this);
3 ✔
1685
  if (!m_tray->getIsAllocated()) {
3 ✔
1686
    destroyTrayIcon();
3 ✔
1687
    return;
3 ✔
1688
  }
1689
#ifndef Q_OS_MACOS
1690
  m_tray->addToggle(ui->actionShowMenuBar);
×
1691
#endif
1692
}
1693

1694
void MainWindow::destroyTrayIcon() {
3 ✔
1695
  delete m_tray;
3 ✔
1696
  m_tray = nullptr;
3 ✔
1697
}
3 ✔
1698

1699
void MainWindow::closeEvent(QCloseEvent *event) {
4 ✔
1700
  // Save in both branches: a tray user only ever hides the window, and
1701
  // used to quit through the tray menu with nothing ever written.
1702
  saveWindowState();
4 ✔
1703
  // Only with a tray icon to come back from: without one (none asked for, or
1704
  // no system tray in this session) a hidden QtPass ran on invisibly, with the
1705
  // last entry in its window and the password on the clipboard.
1706
  if (QtPassSettings::isHideOnClose() && m_tray != nullptr) {
8 ✔
1707
    this->hide();
×
1708
    event->ignore();
1709
  } else {
1710
    m_qtPass->clipboard().clear();
4 ✔
1711
    event->accept();
1712
    // A visible QSystemTrayIcon keeps the application alive, so
1713
    // quitOnLastWindowClosed never fires; quit explicitly.
1714
    QApplication::quit();
4 ✔
1715
  }
1716
}
4 ✔
1717

1718
auto MainWindow::eventFilter(QObject *obj, QEvent *event) -> bool {
8,051 ✔
1719
  if ((obj == ui->toolBar || obj == menuBar()) &&
8,051 ✔
1720
      event->type() == QEvent::PaletteChange) {
1721
    // Breeze gives these bars a "header" palette and, after a runtime
1722
    // light/dark switch, stamps the previous theme's colours back from a
1723
    // cached kdeglobals, hiding the toolbar icons. Deferred so we never
1724
    // re-enter the style while it is still applying its palette.
1725
    QTimer::singleShot(0, this, &MainWindow::dropStaleToolsAreaPalettes);
36 ✔
1726
  }
1727
  if (obj == ui->lineEdit && event->type() == QEvent::KeyPress) {
8,051 ✔
1728
    auto *key = dynamic_cast<QKeyEvent *>(event);
5 ✔
1729
    if (key != nullptr && key->key() == Qt::Key_Down) {
5 ✔
1730
      // Into whichever list is in sight: the tree, or content search results.
1731
      // Focus makes the list's first item current.
1732
      if (ui->treeView->isHidden()) {
2 ✔
1733
        ui->grepResultsList->setFocus();
1 ✔
1734
      } else {
1735
        ui->treeView->setFocus();
1 ✔
1736
      }
1737
    }
1738
    // Return ends at the search box: QLineEdit emits returnPressed() and
1739
    // leaves the key unaccepted, so keyPressEvent() would open the tree's
1740
    // current entry as well. In content search that is an entry nobody
1741
    // asked for; by name, the first hit a second time.
1742
    if (key != nullptr &&
5 ✔
1743
        (key->key() == Qt::Key_Return || key->key() == Qt::Key_Enter)) {
2 ✔
1744
      ui->lineEdit->event(event);
3 ✔
1745
      event->accept();
1746
      return true;
3 ✔
1747
    }
1748
  }
1749
  return QObject::eventFilter(obj, event);
8,048 ✔
1750
}
1751

1752
// Only once the application palette changed (see m_themeSwitched): a bar
1753
// whose active Window lightness is far from the application's shows the
1754
// other theme.
1755
void MainWindow::dropStaleToolsAreaPalettes() {
31 ✔
1756
  if (!m_themeSwitched) {
31 ✔
1757
    return;
1758
  }
1759
  constexpr int kStaleToolsAreaLightness = 64;
1760
  // The active group on both sides: a bar's palette() reads the inactive
1761
  // group while another window has focus (the settings app, during a theme
1762
  // switch), and Breeze gives the header set different inactive colours.
1763
  const int appLightness = QApplication::palette()
54 ✔
1764
                               .color(QPalette::Active, QPalette::Window)
1765
                               .lightness();
27 ✔
1766
  for (QWidget *bar : {static_cast<QWidget *>(ui->toolBar),
108 ✔
1767
                       static_cast<QWidget *>(menuBar())}) {
81 ✔
1768
    if (!bar->testAttribute(Qt::WA_SetPalette)) {
54 ✔
1769
      continue;
48 ✔
1770
    }
1771
    const int barLightness =
1772
        bar->palette().color(QPalette::Active, QPalette::Window).lightness();
12 ✔
1773
    if (qAbs(barLightness - appLightness) <= kStaleToolsAreaLightness) {
6 ✔
1774
      continue;
2 ✔
1775
    }
1776
    bar->setPalette(QPalette());
4 ✔
1777
    // Both bars are transparent and the style paints the tools area from the
1778
    // stale palette, so fill our own. Window, not their Button role, which is
1779
    // not the window colour in either theme.
1780
    bar->setBackgroundRole(QPalette::Window);
4 ✔
1781
    bar->setAutoFillBackground(true);
4 ✔
1782
  }
1783
}
1784

1785
void MainWindow::keyPressEvent(QKeyEvent *event) {
25 ✔
1786
  switch (event->key()) {
25 ✔
1787
  case Qt::Key_Delete:
2 ✔
1788
    onDelete();
2 ✔
1789
    break;
2 ✔
1790
  case Qt::Key_Return:
2 ✔
1791
  case Qt::Key_Enter:
1792
    // While content search results hide the tree, its current entry is not
1793
    // what the user looks at: Return on a result opens that result.
1794
    if (ui->treeView->isHidden()) {
2 ✔
1795
      QTreeWidgetItem *result = ui->grepResultsList->currentItem();
1 ✔
1796
      if (result != nullptr && ui->grepResultsList->hasFocus()) {
1 ✔
1797
        on_grepResultsList_itemClicked(result, 0);
1 ✔
1798
      }
1799
      break;
1800
    }
1801
    if (m_tree->proxy().rowCount() > 0) {
1 ✔
1802
      on_treeView_clicked(ui->treeView->currentIndex());
1 ✔
1803
    }
1804
    break;
1805
  case Qt::Key_Escape:
3 ✔
1806
    ui->lineEdit->clear();
3 ✔
1807
    break;
3 ✔
1808
  default:
1809
    break;
1810
  }
1811
}
25 ✔
1812

1813
void MainWindow::addShareMenu(QMenu &contextMenu, const AppSettings &s) {
10 ✔
1814
  const QString dirPath = QDir::cleanPath(m_tree->currentDir(false));
10 ✔
1815
  auto *shareMenu = new QMenu(tr("Share"), &contextMenu);
10 ✔
1816
  contextMenu.addMenu(shareMenu);
10 ✔
1817

1818
  const QString gpgIdPath = Pass::getGpgIdPath(dirPath, s.passStore);
10 ✔
1819
  const bool gpgIdExists = !gpgIdPath.isEmpty() && QFile(gpgIdPath).exists();
10 ✔
1820
  const QString exePath = s.usePass ? s.passExecutable : s.gpgExecutable;
10 ✔
1821
  const bool gpgAvailable =
1822
      !exePath.isEmpty() &&
20 ✔
1823
      (Executor::parseWslCommand(exePath) || QFile(exePath).exists());
20 ✔
1824

1825
  QAction *reencrypt = shareMenu->addAction(tr("Re-encrypt all passwords"));
10 ✔
1826
  reencrypt->setEnabled(gpgIdExists && gpgAvailable);
10 ✔
1827
  connect(reencrypt, &QAction::triggered, this,
10 ✔
1828
          [this, dirPath]() { reencryptPath(dirPath); });
34 ✔
1829

1830
  QAction *exportKey = shareMenu->addAction(tr("Export my public key..."));
10 ✔
1831
  exportKey->setEnabled(gpgAvailable);
10 ✔
1832
  connect(exportKey, &QAction::triggered, this, &MainWindow::exportPublicKey);
10 ✔
1833

1834
  QAction *addRecipientAction = shareMenu->addAction(tr("Add recipient..."));
10 ✔
1835
  addRecipientAction->setEnabled(gpgIdExists && gpgAvailable);
10 ✔
1836
  connect(addRecipientAction, &QAction::triggered, this,
10 ✔
1837
          [this, dirPath]() { addRecipient(dirPath); });
32 ✔
1838

1839
  QAction *shareHelp = shareMenu->addAction(tr("What is this?"));
10 ✔
1840
  connect(shareHelp, &QAction::triggered, this, &MainWindow::showShareHelp);
10 ✔
1841
}
10 ✔
1842

1843
void MainWindow::showContextMenu(const QPoint &pos) {
12 ✔
1844
  const AppSettings s = QtPassSettings::load();
12 ✔
1845
  const QModelIndex index = ui->treeView->indexAt(pos);
12 ✔
1846
  const bool selected = index.isValid();
1847
  if (!selected) {
1848
    ui->treeView->clearSelection();
1 ✔
1849
    ui->actionDelete->setEnabled(false);
1 ✔
1850
    ui->actionEdit->setEnabled(false);
1 ✔
1851
  }
1852
  ui->treeView->setCurrentIndex(index);
12 ✔
1853
  const QPoint globalPos = ui->treeView->viewport()->mapToGlobal(pos);
12 ✔
1854
  const QFileInfo fileOrFolder = m_tree->fileInfo(ui->treeView->currentIndex());
12 ✔
1855
  const bool isDir = fileOrFolder.isDir();
12 ✔
1856

1857
  QMenu contextMenu;
12 ✔
1858
  if (!selected || isDir) {
12 ✔
1859
    const std::array<std::pair<QString, void (MainWindow::*)()>, 4> onFolder{{
1860
        {tr("Open folder with file manager"), &MainWindow::openFolder},
11 ✔
1861
        {tr("Add folder"), &MainWindow::addFolder},
11 ✔
1862
        {tr("Add password"), &MainWindow::addPassword},
11 ✔
1863
        {tr("Users"), &MainWindow::onUsers},
11 ✔
1864
    }};
×
1865
    for (const auto &[text, slot] : onFolder) {
55 ✔
1866
      connect(contextMenu.addAction(text), &QAction::triggered, this, slot);
44 ✔
1867
    }
1868
  } else if (fileOrFolder.isFile()) {
1 ✔
1869
    connect(contextMenu.addAction(tr("Edit")), &QAction::triggered, this,
1 ✔
1870
            &MainWindow::onEdit);
2 ✔
1871
  }
1872
  if (selected) {
12 ✔
1873
    contextMenu.addSeparator();
11 ✔
1874
    if (isDir) {
11 ✔
1875
      connect(contextMenu.addAction(tr("Rename folder")), &QAction::triggered,
10 ✔
1876
              this, &MainWindow::renameFolder);
20 ✔
1877
    } else if (fileOrFolder.isFile()) {
1 ✔
1878
      connect(contextMenu.addAction(tr("Rename password")), &QAction::triggered,
1 ✔
1879
              this, &MainWindow::renamePassword);
2 ✔
1880
    }
1881
    connect(contextMenu.addAction(tr("Delete")), &QAction::triggered, this,
11 ✔
1882
            &MainWindow::onDelete);
11 ✔
1883
    if (isDir) {
11 ✔
1884
      addShareMenu(contextMenu, s);
10 ✔
1885
    }
1886
  }
1887
  contextMenu.exec(globalPos);
12 ✔
1888
}
12 ✔
1889

1890
auto MainWindow::browserContextMenu(const QPoint &pos) -> QMenu * {
3 ✔
1891
  // createStandardContextMenu() takes document coordinates, anchorAt() and
1892
  // the menu's place viewport ones: scrolled, the menu checked the text
1893
  // above the link and left "Copy Link Location" disabled.
1894
  // Right to left, the horizontal offset counts from the other end.
1895
  const QScrollBar *across = ui->textBrowser->horizontalScrollBar();
3 ✔
1896
  const int dx = ui->textBrowser->isRightToLeft()
3 ✔
1897
                     ? across->maximum() - across->value()
3 ✔
1898
                     : across->value();
3 ✔
1899
  const QPoint documentPos =
1900
      pos + QPoint(dx, ui->textBrowser->verticalScrollBar()->value());
3 ✔
1901
  QMenu *contextMenu = ui->textBrowser->createStandardContextMenu(documentPos);
3 ✔
1902
  // Reparent from textBrowser: a browser stylesheet cascades to the child
1903
  // QMenu and breaks its opaque native background.
1904
  contextMenu->setParent(this, contextMenu->windowFlags());
3 ✔
1905
  if (auto *copyLink =
3 ✔
1906
          contextMenu->findChild<QAction *>(QStringLiteral("link-copy"))) {
3 ✔
1907
    const QString link = ui->textBrowser->anchorAt(pos);
3 ✔
1908
    disconnect(copyLink, &QAction::triggered, nullptr, nullptr);
3 ✔
1909
    connect(copyLink, &QAction::triggered, this, [this, link] {
10 ✔
1910
      if (!link.isEmpty()) {
1 ✔
1911
        m_qtPass->clipboard().copyText(link);
1 ✔
1912
      }
1913
    });
1 ✔
1914
  }
1915
  return contextMenu;
3 ✔
1916
}
1917

1918
void MainWindow::showBrowserContextMenu(const QPoint &pos) {
1 ✔
1919
  QMenu *contextMenu = browserContextMenu(pos);
1 ✔
1920
  contextMenu->exec(ui->textBrowser->viewport()->mapToGlobal(pos));
1 ✔
1921
  delete contextMenu;
1 ✔
1922
}
1 ✔
1923

1924
void MainWindow::openFolder() {
1 ✔
1925
  QString dir = m_tree->currentDir(false);
1 ✔
1926

1927
  QString path = QDir::toNativeSeparators(dir);
1 ✔
1928
  QDesktopServices::openUrl(QUrl::fromLocalFile(path));
1 ✔
1929
}
1 ✔
1930

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

1979
void MainWindow::renameFolder() {
3 ✔
1980
  bool ok;
1981
  QString srcDir = QDir::cleanPath(m_tree->currentDir(false));
3 ✔
1982
  QString srcDirName = QDir(srcDir).dirName();
3 ✔
1983
  QString newName =
1984
      QInputDialog::getText(this, tr("Rename folder"), tr("Rename folder to: "),
3 ✔
1985
                            QLineEdit::Normal, srcDirName, &ok);
6 ✔
1986
  if (!ok || newName.isEmpty()) {
3 ✔
1987
    return;
1988
  }
1989
  QString destDir = srcDir;
1990
  destDir.replace(srcDir.lastIndexOf(srcDirName), srcDirName.length(), newName);
2 ✔
1991
  if (!confirmPathInStore(destDir)) {
2 ✔
1992
    return;
1993
  }
1994
  QtPassSettings::getPass()->Move(srcDir, destDir, false);
3 ✔
1995
}
1996

1997
void MainWindow::editPassword(const QString &file) {
6 ✔
1998
  if (!file.isEmpty()) {
6 ✔
1999
    const AppSettings s = QtPassSettings::load();
6 ✔
2000
    if (s.useGit && s.autoPull) {
6 ✔
2001
      onUpdate(true);
1 ✔
2002
    }
2003
    // The dialog decrypts the entry itself to fill its fields. That decrypt
2004
    // lands on the same finishedShow the panel uses, so drop the panel's claim
2005
    // to it: otherwise passShowHandler() repaints and, with "Always copy",
2006
    // puts the entry's old password on the clipboard - replacing whatever the
2007
    // user copied to paste into the dialog.
2008
    m_shownFile.clear();
6 ✔
2009
    setPassword(file, false);
6 ✔
2010
  }
6 ✔
2011
}
6 ✔
2012

2013
void MainWindow::renamePassword() {
2 ✔
2014
  bool ok;
2015
  QString file = getFile(ui->treeView->currentIndex(), false);
2 ✔
2016
  QString filePath = QFileInfo(file).path();
2 ✔
2017
  QString fileName = QFileInfo(file).fileName();
2 ✔
2018
  if (fileName.endsWith(".gpg", Qt::CaseInsensitive)) {
4 ✔
2019
    fileName.chop(4);
2 ✔
2020
  }
2021

2022
  QString newName =
2023
      QInputDialog::getText(this, tr("Rename file"), tr("Rename file to: "),
2 ✔
2024
                            QLineEdit::Normal, fileName, &ok);
4 ✔
2025
  if (!ok || newName.isEmpty()) {
2 ✔
2026
    return;
2027
  }
2028
  QString newFile = QDir(filePath).filePath(newName);
2 ✔
2029
  if (!confirmPathInStore(newFile)) {
2 ✔
2030
    return;
2031
  }
2032
  QtPassSettings::getPass()->Move(file, newFile, false);
3 ✔
2033
}
2034

2035
void MainWindow::copySelectionOrPassword() {
5 ✔
2036
  QWidget *focus = QApplication::focusWidget();
5 ✔
2037
  // The widget's own copy: a SecretTextBrowser marks what it copies as
2038
  // secret for clipboard managers, as the context menu's Copy does.
2039
  if (auto *text = qobject_cast<QTextEdit *>(focus);
5 ✔
2040
      text != nullptr && text->textCursor().hasSelection()) {
5 ✔
2041
    text->copy();
1 ✔
2042
    return;
1 ✔
2043
  }
2044
  // Through the clipboard manager, as a copy button would: the label may be
2045
  // the OTP code, which gets the secret hint and the autoclear.
2046
  if (auto *label = qobject_cast<QLabel *>(focus);
2047
      label != nullptr && label->hasSelectedText()) {
4 ✔
2048
    m_qtPass->clipboard().copyText(label->selectedText());
1 ✔
2049
    return;
1 ✔
2050
  }
2051
  // A line of the content search results is decrypted text: through the
2052
  // clipboard manager too, for the secret hint and the autoclear.
2053
  if (focus == ui->grepResultsList) {
3 ✔
2054
    if (const QTreeWidgetItem *item = ui->grepResultsList->currentItem();
3 ✔
2055
        item != nullptr && !item->text(0).isEmpty()) {
6 ✔
2056
      m_qtPass->clipboard().copyText(item->text(0));
6 ✔
2057
    }
2058
    return;
3 ✔
2059
  }
2060
  copyPasswordFromTreeview();
×
2061
}
2062

2063
void MainWindow::copyPasswordFromTreeview() {
9 ✔
2064
  // While content search results hide the tree, its current entry is not
2065
  // what the user looks at: no decrypt, as for Edit and OTP.
2066
  if (ui->treeView->isHidden()) {
9 ✔
2067
    return;
×
2068
  }
2069
  QFileInfo fileOrFolder = m_tree->fileInfo(ui->treeView->currentIndex());
9 ✔
2070

2071
  if (fileOrFolder.isFile()) {
9 ✔
2072
    QString file = getFile(ui->treeView->currentIndex(), true);
9 ✔
2073
    // The newest Ctrl+C wins: finishedShow names its file, so the decrypt of
2074
    // an earlier request is simply not this one's.
2075
    m_copyRequestFile = file;
9 ✔
2076
    // This Show repaints the panel as well; see onOtp().
2077
    m_shownFile = file;
9 ✔
2078
    QtPassSettings::getPass()->Show(file);
18 ✔
2079
  }
2080
}
9 ✔
2081

2082
void MainWindow::passwordFromFileToClipboard(const QString &text,
33 ✔
2083
                                             const QString &file) {
2084
  if (m_copyRequestFile.isEmpty() || file != m_copyRequestFile) {
33 ✔
2085
    return;
28 ✔
2086
  }
2087
  m_copyRequestFile.clear();
8 ✔
2088
  // The first line, without a list of every line (an entry can expand into
2089
  // millions of them), and without the "\r" of a CRLF line end, as the
2090
  // password row and "Always copy" have it.
2091
  const QString first = FileContent::passwordLine(text);
8 ✔
2092
  // A `pass otp insert` entry's first line is the otpauth:// URI carrying the
2093
  // TOTP seed, and an OTP field holding a seed there is the same; copying it
2094
  // would leak 2FA material. Matches the display path
2095
  // (FileContent::getPasswordForDisplay / PasswordDisplayPanel).
2096
  if (FileContent::isOtpPasswordLine(first)) {
8 ✔
2097
    flashText(tr("This entry holds an OTP secret, not a password"), true);
6 ✔
2098
    return;
2099
  }
2100
  m_qtPass->clipboard().copyText(first);
5 ✔
2101
}
2102

2103
void MainWindow::showStatusMessage(const QString &msg, int timeout) {
34 ✔
2104
  ui->statusBar->showMessage(msg, timeout);
34 ✔
2105
}
34 ✔
2106

2107
void MainWindow::reencryptPath(const QString &dir) {
4 ✔
2108
  QDir checkDir(dir);
4 ✔
2109
  if (!checkDir.exists()) {
4 ✔
2110
    PlainMessageBox::critical(this, tr("Error"),
2 ✔
2111
                              tr("Directory does not exist: %1").arg(dir));
2 ✔
2112
    return;
1 ✔
2113
  }
2114
  if (refuseLinkedFolder(dir)) {
3 ✔
2115
    return;
2116
  }
2117

2118
  const bool yes = PlainMessageBox::askYes(
3 ✔
2119
      this, tr("Re-encrypt passwords"),
3 ✔
2120
      tr("Re-encrypt all passwords in %1?\n\n"
3 ✔
2121
         "This will re-encrypt ALL password files in this folder "
2122
         "using the current recipients defined in .gpg-id.\n\n"
2123
         "This may rewrite many files and cannot be undone easily.\n\n"
2124
         "Continue?")
2125
          // On one line: a name with line feeds pushed the warning out of
2126
          // the box, which shows 40 lines at most.
2127
          .arg(Util::displayable(QDir(dir).dirName(), false)));
6 ✔
2128

2129
  if (!yes)
3 ✔
2130
    return;
2131

2132
  // Disable now; the asynchronous startReencryptPath signal re-runs this
2133
  // harmlessly.
2134
  startReencryptPath();
1 ✔
2135

2136
  // Under the current profile's settings: with the pass backend active, the
2137
  // native one is not re-initialised on a profile switch.
2138
  QtPassSettings::getImitatePass()->reencryptPath(
2 ✔
2139
      QDir::cleanPath(QDir(dir).absolutePath()), QtPassSettings::load());
2 ✔
2140
}
4 ✔
2141

2142
// Idempotent: reencryptPath() calls it before ImitatePass emits the signal.
2143
void MainWindow::startReencryptPath() {
7 ✔
2144
  m_reencryptRunning = true;
7 ✔
2145
  setUiElementsEnabled(false);
7 ✔
2146
  // The worker always ends with endReencryptPath(), and Cancel is available
2147
  // throughout, so the generic watchdog is not needed for this operation.
2148
  m_uiWatchdog.stop();
7 ✔
2149
  ui->treeView->setDisabled(true);
7 ✔
2150
  if (m_reencryptProgress)
7 ✔
2151
    return;
2152
  auto *progress = new QProgressDialog(tr("Re-encrypting passwords..."),
5 ✔
2153
                                       tr("Cancel"), 0, 0, this);
10 ✔
2154
  progress->setWindowTitle(tr("Re-encrypt passwords"));
5 ✔
2155
  progress->setWindowModality(Qt::WindowModal);
5 ✔
2156
  progress->setAutoClose(false);
5 ✔
2157
  progress->setAutoReset(false);
5 ✔
2158
  progress->setMinimumDuration(0);
5 ✔
2159
  connect(progress, &QProgressDialog::canceled, this, [this]() {
5 ✔
2160
    QtPassSettings::getImitatePass()->cancelReencryptPath();
1 ✔
2161
    showStatusMessage(tr("Cancelling re-encryption"), 5000);
1 ✔
2162
  });
1 ✔
2163
  m_reencryptProgress = progress;
2164
  progress->show();
5 ✔
2165
}
2166

2167
void MainWindow::reencryptProgress(int current, int total) {
7 ✔
2168
  if (!m_reencryptProgress || m_inProgressUpdate)
7 ✔
2169
    return;
2170
  QProgressDialog *progress = m_reencryptProgress;
2171
  progress->setMaximum(total);
6 ✔
2172
  progress->setLabelText(
6 ✔
2173
      tr("Re-encrypting passwords: %1 of %2").arg(current).arg(total));
6 ✔
2174
  // On a modal dialog setValue() runs processEvents(), which can deliver
2175
  // endReencryptPath(), even inside a nested event loop that would delete a
2176
  // deleteLater()ed dialog under setValue()'s feet: keep this last, and
2177
  // delete the dialog only after it returns.
2178
  m_inProgressUpdate = true;
6 ✔
2179
  progress->setValue(current);
6 ✔
2180
  m_inProgressUpdate = false;
6 ✔
2181
  if (m_progressToDelete) {
6 ✔
2182
    m_progressToDelete->deleteLater();
2 ✔
2183
    m_progressToDelete = nullptr;
2184
  }
2185
}
2186

2187
void MainWindow::endReencryptPath() {
5 ✔
2188
  m_reencryptRunning = false;
5 ✔
2189
  if (m_reencryptProgress) {
5 ✔
2190
    m_reencryptProgress->hide();
5 ✔
2191
    if (m_inProgressUpdate) {
5 ✔
2192
      m_progressToDelete = m_reencryptProgress;
2193
    } else {
2194
      m_reencryptProgress->deleteLater();
3 ✔
2195
    }
2196
    m_reencryptProgress = nullptr;
2197
  }
2198
  setUiElementsEnabled(true);
5 ✔
2199
}
5 ✔
2200

2201
void MainWindow::exportPublicKey() {
3 ✔
2202
  const AppSettings s = QtPassSettings::load();
3 ✔
2203
  const QString identity = s.passSigningKey;
2204
  if (identity.isEmpty()) {
3 ✔
2205
    QMessageBox::information(
2 ✔
2206
        this, tr("Export public key"),
1 ✔
2207
        tr("<h3>Export your public key</h3>"
×
2208
           "<p>No signing key is configured. Set one in QtPass Settings "
2209
           "&gt; GPG keys, or run this in a terminal:</p>"
2210
           "<pre>gpg --armor --export --output my_key.asc &lt;your-key-id"
2211
           "&gt;</pre>"
2212
           "<p>Then send the file to your teammates.</p>"));
2213
    return;
1 ✔
2214
  }
2215
  QString gpgExe = s.gpgExecutable;
2216
  if (gpgExe.isEmpty()) {
2 ✔
2217
    gpgExe = QStringLiteral("gpg");
×
2218
  }
2219
  QStringList args = {"--armor", "--export"};
10 ✔
2220
  args.append(identity.split(' ', Qt::SkipEmptyParts));
2 ✔
2221
  QString stdOut;
2 ✔
2222
  QString stdErr;
2 ✔
2223
  int exitCode = Executor::executeBlocking(gpgExe, args, &stdOut, &stdErr);
2 ✔
2224
  if (exitCode != 0 || stdOut.isEmpty()) {
2 ✔
2225
    PlainMessageBox::warning(this, tr("Export public key"),
2 ✔
2226
                             tr("Could not export public key for %1.\n\n%2")
1 ✔
2227
                                 .arg(identity, stdErr.isEmpty()
2 ✔
2228
                                                    ? tr("No output from gpg.")
2 ✔
2229
                                                    : stdErr));
2230
    return;
2231
  }
2232
  ExportPublicKeyDialog dialog(identity, stdOut, this);
1 ✔
2233
  dialog.exec();
1 ✔
2234
}
4 ✔
2235

2236
// UsersDialog only ticks keys already in the keyring; importing a foreign
2237
// key still has to happen via gpg (or QtPass settings) first.
2238
void MainWindow::addRecipient(const QString &dir) {
2 ✔
2239
  if (refuseLinkedFolder(dir)) {
2 ✔
2240
    return;
1 ✔
2241
  }
2242
  UsersDialog d(QtPassSettings::getPass(), QtPassSettings::load(), dir, this);
1 ✔
2243
  d.exec();
1 ✔
2244
}
1 ✔
2245

2246
// A tree-picked folder that is, or lies behind, a symlink or junction is not
2247
// a folder of the store. The store root itself may be a link (a synced
2248
// folder); that is configuration, not a tree pick.
2249
auto MainWindow::refuseLinkedFolder(const QString &dir) -> bool {
20 ✔
2250
  if (!Util::isUnderLink(dir, QtPassSettings::load().passStore)) {
20 ✔
2251
    return false;
2252
  }
2253
  PlainMessageBox::critical(
3 ✔
2254
      this, tr("Not a folder of the store"),
3 ✔
2255
      tr("%1 is, or lies behind, a symbolic link or junction. What that "
3 ✔
2256
         "points to is not part of the password store and is left alone.")
2257
          .arg(QDir::toNativeSeparators(QDir::cleanPath(dir))));
6 ✔
2258
  return true;
3 ✔
2259
}
2260

2261
void MainWindow::showShareHelp() {
1 ✔
2262
  QMessageBox::information(
2 ✔
2263
      this, tr("Sharing passwords with GPG"),
1 ✔
2264
      tr("<h3>Sharing passwords with GPG</h3>"
1 ✔
2265
         "<p>To share passwords with other users:</p>"
2266
         "<ol>"
2267
         "<li><b>Export your public key</b> and send it to teammates</li>"
2268
         "<li><b>Import teammates' public keys</b> into your GPG keyring</li>"
2269
         "<li><b>Re-encrypt passwords</b> so all recipients can decrypt "
2270
         "them</li>"
2271
         "</ol>"
2272
         "<p>Only people who have a matching secret key can decrypt the "
2273
         "passwords.</p>"
2274
         "<p><b>Tip:</b> Use the same GPG key for all shared folders.</p>"
2275
         "<p>See the FAQ for more details.</p>"));
2276
}
1 ✔
2277

2278
void MainWindow::updateGitButtonVisibility(bool uiEnabled) {
440 ✔
2279
  const AppSettings s = QtPassSettings::load();
440 ✔
2280
  // Without Git there is nothing to push or pull, ever: the buttons go, not
2281
  // grey out. While an operation runs they stay and are disabled.
2282
  const bool usable =
2283
      s.useGit && !(s.gitExecutable.isEmpty() && s.passExecutable.isEmpty());
440 ✔
2284
  ui->actionPush->setVisible(usable);
440 ✔
2285
  ui->actionUpdate->setVisible(usable);
440 ✔
2286
  // The separator in front of them would otherwise sit next to the next one.
2287
  const QList<QAction *> actions = ui->toolBar->actions();
440 ✔
2288
  const qsizetype at = actions.indexOf(ui->actionPush);
440 ✔
2289
  if (at > 0 && actions.at(at - 1)->isSeparator()) {
440 ✔
2290
    actions.at(at - 1)->setVisible(usable);
440 ✔
2291
  }
2292
  enableGitButtons(usable && uiEnabled);
440 ✔
2293
}
440 ✔
2294

2295
void MainWindow::updateOtpButtonVisibility(bool uiEnabled) {
448 ✔
2296
  // No platform gating: codes are generated in-process. Visible but disabled
2297
  // when OTP is off: the panel never shows an OTP field (a secret), so hiding
2298
  // this too would leave no trace of the feature. Honour uiEnabled, or the
2299
  // user can stack Show calls while a decrypt is in flight.
2300
  ui->actionOtp->setVisible(true);
448 ✔
2301
  ui->actionOtp->setEnabled(QtPassSettings::isUseOtp() && uiEnabled);
554 ✔
2302
}
448 ✔
2303

2304
void MainWindow::updateGrepButtonVisibility() {
196 ✔
2305
  const bool enabled = QtPassSettings::isUseGrepSearch();
196 ✔
2306
  ui->grepButton->setVisible(enabled);
196 ✔
2307
  ui->grepCaseButton->setVisible(enabled);
196 ✔
2308
  if (!enabled && m_grep.inGrepMode()) {
196 ✔
2309
    ui->grepButton->setChecked(false);
1 ✔
2310
  }
2311
}
196 ✔
2312

2313
void MainWindow::enableGitButtons(const bool &state) {
440 ✔
2314
  ui->actionPush->setEnabled(state);
440 ✔
2315
  ui->actionUpdate->setEnabled(state);
440 ✔
2316
}
440 ✔
2317

2318
void MainWindow::critical(const QString &title, const QString &msg) {
4 ✔
2319
  // Pass's messages quote store paths; see PlainMessageBox.
2320
  PlainMessageBox::critical(this, title, msg);
4 ✔
2321
}
4 ✔
2322

2323
void MainWindow::onProcessOutput(const QString &output, bool isError,
7 ✔
2324
                                 Enums::PROCESS pid) {
2325
  if (!QtPassSettings::isShowProcessOutput()) {
7 ✔
2326
    return;
2327
  }
2328
  m_processOutput->append(output, isError,
6 ✔
2329
                          ProcessOutputPanel::processName(pid));
12 ✔
2330
}
2331

2332
void MainWindow::updateProcessOutputVisibility() {
4 ✔
2333
  // The action's toggled handler shows or hides the dock.
2334
  ui->actionShowProcessOutput->setChecked(
4 ✔
2335
      QtPassSettings::isShowProcessOutput());
4 ✔
2336
  m_processOutput->setVisible(QtPassSettings::isShowProcessOutput());
4 ✔
2337
}
4 ✔
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