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

IJHack / QtPass / 43749409987

15 Nov 2026 06:54PM UTC coverage: 96.293% (-0.04%) from 96.334%
43749409987

Pull #2202

github

web-flow
Merge ed6256ed7 into 7c0a4e4af
Pull Request #2202: Ctrl+C copies the text selected in the shown entry

8 of 12 new or added lines in 1 file covered. (66.67%)

24 existing lines in 1 file now uncovered.

8703 of 9038 relevant lines covered (96.29%)

714.97 hits per line

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

97.3
/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 <QClipboard>
40
#include <QCloseEvent>
41
#include <QDate>
42
#include <QDesktopServices>
43
#include <QDialog>
44
#include <QDockWidget>
45
#include <QFileInfo>
46
#include <QFileSystemModel>
47
#include <QHBoxLayout>
48
#include <QInputDialog>
49
#include <QLabel>
50
#include <QLineEdit>
51
#include <QMenu>
52
#include <QMenuBar>
53
#include <QMessageBox>
54
#include <QProgressDialog>
55
#include <QPushButton>
56
#include <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)
165 ✔
68
    : QMainWindow(parent), ui(new Ui::MainWindow) {
165 ✔
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);
165 ✔
75

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

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

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

91
  initTextBrowser();
165 ✔
92

93
  updateProfileBox();
165 ✔
94

95
  initDisplayPanel();
165 ✔
96

97
  QtPassSettings::getPass()->updateEnv();
165 ✔
98

99
  // Install the search-box key filter once, not on every setUiElementsEnabled
100
  // call.
101
  ui->lineEdit->installEventFilter(this);
165 ✔
102
  // Both live in Breeze's "tools area" and get its header palette; see the
103
  // PaletteChange branch in eventFilter().
104
  ui->toolBar->installEventFilter(this);
165 ✔
105
  menuBar()->installEventFilter(this);
165 ✔
106

107
  initTimers();
165 ✔
108

109
  initToolBarButtons();
165 ✔
110
  initStatusBar();
165 ✔
111
  initProcessOutput();
165 ✔
112

113
  ui->lineEdit->setClearButtonEnabled(true);
165 ✔
114
  updateGrepButtonVisibility();
165 ✔
115

116
  setUiElementsEnabled(true);
165 ✔
117

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

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

141
  // Initial focus is set in showEvent(): a 10 ms QTimer here could fire
142
  // before the window was realised (queued ActivationChange, nested exec() in
143
  // init()) and selectAll() segfaulted inside Qt (#1187, #1188).
UNCOV
144
}
×
145

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

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

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

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

228
  searchTimer.setInterval(350);
165 ✔
229
  searchTimer.setSingleShot(true);
165 ✔
230

231
  connect(&searchTimer, &QTimer::timeout, this, &MainWindow::onTimeoutSearch);
165 ✔
232

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

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

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

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

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

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

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

357
auto MainWindow::event(QEvent *event) -> bool {
7,372 ✔
358
  if (event->type() == QEvent::ApplicationPaletteChange) {
7,372 ✔
359
    m_themeSwitched = true;
11 ✔
360
    // Breeze may re-stamp the bars before this arrives (Plasma 6 does):
361
    // their PaletteChange then found no switch yet, so check them now too.
362
    QTimer::singleShot(0, this, &MainWindow::dropStaleToolsAreaPalettes);
11 ✔
363
  }
364
  return QMainWindow::event(event);
7,372 ✔
365
}
366

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

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

396
void MainWindow::initToolBarButtons() {
165 ✔
397
  connect(ui->actionAddPassword, &QAction::triggered, this,
165 ✔
398
          &MainWindow::addPassword);
165 ✔
399
  connect(ui->actionAddFolder, &QAction::triggered, this,
165 ✔
400
          &MainWindow::addFolder);
165 ✔
401
  connect(ui->actionEdit, &QAction::triggered, this, &MainWindow::onEdit);
165 ✔
402
  connect(ui->actionDelete, &QAction::triggered, this, &MainWindow::onDelete);
165 ✔
403
  connect(ui->actionPush, &QAction::triggered, this, &MainWindow::onPush);
165 ✔
404
  connect(ui->actionUpdate, &QAction::triggered, this, &MainWindow::onUpdate);
165 ✔
405
  connect(ui->actionUsers, &QAction::triggered, this, &MainWindow::onUsers);
165 ✔
406
  connect(ui->actionConfig, &QAction::triggered, this, &MainWindow::onConfig);
165 ✔
407
  connect(ui->actionOtp, &QAction::triggered, this, &MainWindow::onOtp);
165 ✔
408

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

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

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

458
  QPixmap logo = QPixmap::fromImage(QImage(":/artwork/icon.svg"))
330 ✔
459
                     .scaledToHeight(statusBar()->height());
165 ✔
460
  auto *logoApp = new QLabel(statusBar());
165 ✔
461
  logoApp->setPixmap(logo);
165 ✔
462
  statusBar()->addPermanentWidget(logoApp);
165 ✔
463
}
165 ✔
464

465
auto MainWindow::getCurrentTreeViewIndex() -> QModelIndex {
9 ✔
466
  return ui->treeView->currentIndex();
9 ✔
467
}
468

469
void MainWindow::flashText(const QString &text, const bool isError,
80 ✔
470
                           const bool isHtml) {
471
  if (isError) {
80 ✔
472
    ui->textBrowser->setTextColor(Qt::red);
9 ✔
473
  } else {
474
    // setText() re-applies the current char format, red after an error, to
475
    // the whole document. Clear the foreground rather than pin a palette
476
    // colour, so text follows runtime light/dark switches (#946).
477
    QTextCharFormat format = ui->textBrowser->currentCharFormat();
71 ✔
478
    format.clearForeground();
479
    ui->textBrowser->setCurrentCharFormat(format);
71 ✔
480
  }
481

482
  if (isHtml) {
80 ✔
483
    QString _text = text;
484
    if (!ui->textBrowser->toPlainText().isEmpty()) {
138 ✔
485
      _text = ui->textBrowser->toHtml() + _text;
38 ✔
486
    }
487
    ui->textBrowser->setHtml(_text);
69 ✔
488
  } else {
489
    ui->textBrowser->setText(text);
11 ✔
490
  }
491
}
80 ✔
492

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

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

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

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

545
  applyTextBrowserSettings();
3 ✔
546
  applyWindowFlagsSettings();
3 ✔
547

548
  updateProfileBox();
3 ✔
549
  const AppSettings s = QtPassSettings::load();
3 ✔
550
  // An open still waiting for the tree was asked of the old view; once
551
  // re-rooted, it would find that name in the new store. A profile switch
552
  // ends it by clearing the search text.
553
  delete m_pendingOpen;
3 ✔
554
  m_tree->setStore(s.passStore);
3 ✔
555
  deselect();
3 ✔
556
  ui->treeView->setCurrentIndex(QModelIndex());
3 ✔
557

558
  Pass *activePass = QtPassSettings::getPass();
3 ✔
559
  activePass->updateEnv();
3 ✔
560
  m_tree->setPass(activePass);
3 ✔
561
  clearPanelTimer.setInterval(MS_PER_SECOND * s.autoclearPanelSeconds);
3 ✔
562
  m_qtPass->clipboard().setAutoclearTimer();
3 ✔
563

564
  updateGitButtonVisibility();
3 ✔
565
  updateOtpButtonVisibility();
3 ✔
566
  updateGrepButtonVisibility();
3 ✔
567
  updateProcessOutputVisibility();
3 ✔
568
#ifndef Q_OS_MACOS
569
  // The action's toggled handler shows or hides the bar (and saves again).
570
  ui->actionShowMenuBar->setChecked(s.showMenuBar);
3 ✔
571
#endif
572
  if (s.useTrayIcon && m_tray == nullptr) {
3 ✔
573
    initTrayIcon();
1 ✔
574
  } else if (!s.useTrayIcon && m_tray != nullptr) {
2 ✔
UNCOV
575
    destroyTrayIcon();
×
576
  }
577

578
  // Stay fresh-start while the configuration is unusable, so the
579
  // constructor's loop re-runs the wizard. The re-prompt lives there:
580
  // recursing here never reported a cancel back to the caller.
581
  if (Util::configIsValid(s)) {
3 ✔
582
    m_freshStart = false;
3 ✔
583
  }
584
  return true;
585
}
3 ✔
586

587
void MainWindow::onUpdate(bool block) {
2 ✔
588
  ui->statusBar->showMessage(tr("Updating password-store"), 2000);
2 ✔
589
  if (block) {
2 ✔
590
    QtPassSettings::getPass()->GitPull_b();
1 ✔
591
  } else {
592
    QtPassSettings::getPass()->GitPull();
1 ✔
593
  }
594
}
2 ✔
595

596
void MainWindow::onPush() {
9 ✔
597
  if (QtPassSettings::isUseGit()) {
9 ✔
598
    ui->statusBar->showMessage(tr("Updating password-store"), 2000);
9 ✔
599
    QtPassSettings::getPass()->GitPush();
9 ✔
600
  }
601
}
9 ✔
602

603
auto MainWindow::getFile(const QModelIndex &index, bool forPass) -> QString {
62 ✔
604
  return m_tree->fileFor(index, forPass);
62 ✔
605
}
606

607
void MainWindow::on_treeView_clicked(const QModelIndex &index) {
24 ✔
608
  bool cleared = ui->treeView->currentIndex().flags() == Qt::NoItemFlags;
24 ✔
609
  QString file = getFile(index, true);
24 ✔
610
  ui->passwordName->setText(file);
24 ✔
611
  if (!file.isEmpty() && !cleared) {
24 ✔
612
    // Remember what the panel is about to show, so onOtp() can tell whether the
613
    // code it can see belongs to the entry that is currently selected.
614
    m_shownFile = file;
23 ✔
615
    QtPassSettings::getPass()->Show(file);
46 ✔
616
  } else {
617
    m_shownFile.clear();
1 ✔
618
    clearPanel(false);
1 ✔
619
    ui->actionEdit->setEnabled(false);
1 ✔
620
    ui->actionDelete->setEnabled(true);
1 ✔
621
  }
622
}
24 ✔
623

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

627
  if (fileOrFolder.isFile()) {
4 ✔
628
    editPassword(getFile(index, true));
6 ✔
629
  }
630
}
4 ✔
631

632
void MainWindow::deselect() {
15 ✔
633
  m_shownFile.clear();
15 ✔
634
  cancelOtpRequest();
15 ✔
635
  m_qtPass->clipboard().clear();
15 ✔
636
  ui->treeView->clearSelection();
15 ✔
637
  ui->actionEdit->setEnabled(false);
15 ✔
638
  ui->actionDelete->setEnabled(false);
15 ✔
639
  ui->passwordName->setText("");
15 ✔
640
  clearPanel(false);
15 ✔
641
}
15 ✔
642

643
void MainWindow::executeWrapperStarted() {
62 ✔
644
  m_displayPanel->clear();
62 ✔
645
  ui->textBrowser->clear();
62 ✔
646
  setUiElementsEnabled(false);
62 ✔
647
  clearPanelTimer.stop();
62 ✔
648
  if (QtPassSettings::isShowProcessOutput()) {
62 ✔
649
    m_processOutput->setVisible(true);
57 ✔
650
  }
651
}
62 ✔
652

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

689
  // Skipped for an OTP request: the user asked for a code, and two
690
  // OleSetClipboard calls in one turn can leave the Windows clipboard empty.
691
  if (m_otpRequestFile.isEmpty() || m_otpRequestFile != file) {
27 ✔
692
    m_qtPass->clipboard().copyIfAlways(password, p_output);
25 ✔
693
  }
694

695
  m_displayPanel->clear();
27 ✔
696

697
  if (s.hideContent) {
27 ✔
698
    output = "***" + tr("Content hidden") + "***";
4 ✔
699
  } else if (s.displayAsIs) {
25 ✔
700
    // As it is, but not a block per line of millions.
701
    output = FileContent::boundedForDisplay(p_output);
2 ✔
702
  } else {
703
    m_displayPanel->displayFields(password, fileContent.getNamedValues(), s,
48 ✔
704
                                  s.useOtp ? fileContent.getOtpUri()
24 ✔
705
                                           : QString());
706
    output = fileContent.getRemainingDataForDisplay();
48 ✔
707
  }
708

709
  if (s.useAutoclearPanel) {
27 ✔
710
    clearPanelTimer.start();
2 ✔
711
  }
712

713
  flashText(QtPass::formatOutput(output), false, true);
54 ✔
714
  setUiElementsEnabled(true);
27 ✔
715
}
54 ✔
716

717
void MainWindow::otpFromFileToClipboard(const QString &p_output,
26 ✔
718
                                        const QString &file) {
719
  // Permanently connected: only the decrypt of the entry onOtp() asked for
720
  // is ours, everything else belongs to a tree click or a Ctrl+C.
721
  if (m_otpRequestFile.isEmpty() || file != m_otpRequestFile) {
26 ✔
722
    return;
23 ✔
723
  }
724
  m_otpRequestFile.clear();
5 ✔
725

726
  if (p_output.isEmpty()) {
5 ✔
727
    // Distinguish "could not read the entry" from "entry has no OTP".
728
    flashText(tr("Could not decrypt this password entry"), true);
1 ✔
729
    setUiElementsEnabled(true);
1 ✔
730
    return;
1 ✔
731
  }
732

733
  // passShowHandler ran first for this finishedShow; if it rendered the OTP
734
  // row, reuse its code (as onOtp()'s fast path does). Otherwise parse:
735
  // hideContent, displayAsIs or no OTP field.
736
  const QString shown = m_displayPanel->currentOtpCode();
4 ✔
737
  if (!shown.isEmpty()) {
4 ✔
738
    m_qtPass->clipboard().copyText(shown);
1 ✔
739
    showStatusMessage(tr("OTP code copied to clipboard"));
1 ✔
740
    setUiElementsEnabled(true);
1 ✔
741
    return;
742
  }
743

744
  const AppSettings s = QtPassSettings::load();
3 ✔
745
  // Parse with the same template settings passShowHandler uses, so an OTP
746
  // field is recognised identically in both paths.
747
  const QStringList templ =
748
      s.useTemplate ? TemplateIO::fieldsIn(s.passTemplate) : QStringList();
3 ✔
749
  const bool allFields = s.useTemplate && s.templateAllFields;
3 ✔
750
  const FileContent fileContent =
751
      FileContent::parse(p_output, templ, allFields);
3 ✔
752

753
  const std::optional<Totp::Settings> settings =
754
      Totp::parse(fileContent.getOtpUri());
6 ✔
755
  if (settings.has_value()) {
3 ✔
756
    m_qtPass->clipboard().copyText(Totp::generateNow(*settings));
4 ✔
757
    showStatusMessage(tr("OTP code copied to clipboard"));
4 ✔
758
  } else {
759
    flashText(tr("No OTP code found in this password entry"), true);
2 ✔
760
  }
761
  setUiElementsEnabled(true);
3 ✔
762
}
6 ✔
763

764
void MainWindow::clearPanel(bool notify) {
54 ✔
765
  m_displayPanel->clear();
54 ✔
766
  const bool grepWasVisible = ui->grepResultsList->isVisible();
54 ✔
767
  ui->grepResultsList->clear();
54 ✔
768
  if (grepWasVisible) {
54 ✔
769
    ui->grepResultsList->setVisible(false);
4 ✔
770
    ui->treeView->setVisible(true);
4 ✔
771
    if (m_grep.inGrepMode()) {
4 ✔
772
      // Left as the button leaves it: a search still running would otherwise
773
      // hand its partial matches to a content search entered meanwhile.
774
      cancelContentSearch();
4 ✔
775
      if (m_grep.leaveGrepMode()) {
776
        QApplication::restoreOverrideCursor();
2 ✔
777
      }
778
      ui->grepButton->blockSignals(true);
4 ✔
779
      ui->grepButton->setChecked(false);
4 ✔
780
      ui->grepButton->blockSignals(false);
4 ✔
781
      ui->lineEdit->blockSignals(true);
4 ✔
782
      ui->lineEdit->clear();
4 ✔
783
      ui->lineEdit->blockSignals(false);
4 ✔
784
      ui->lineEdit->setPlaceholderText(tr("Search password"));
8 ✔
785
    }
786
  }
787
  if (notify) {
54 ✔
788
    QString output = "***" + tr("Password and content hidden") + "***";
4 ✔
789
    ui->textBrowser->setHtml(output);
2 ✔
790
  } else {
791
    ui->textBrowser->setHtml("");
104 ✔
792
  }
793
}
54 ✔
794

795
void MainWindow::setUiElementsEnabled(bool state) {
371 ✔
796
  // A running re-encryption owns the UI state: the progress dialog's Cancel is
797
  // the user's escape hatch and endReencryptPath() releases the interface, so
798
  // neither an unrelated completion nor the watchdog may re-enable it early.
799
  if (state && m_reencryptRunning) {
371 ✔
800
    m_uiWatchdog.stop();
1 ✔
801
    return;
1 ✔
802
  }
803
  // Arm the watchdog while the UI is disabled; disarm once re-enabled.
804
  if (state) {
805
    m_uiWatchdog.stop();
288 ✔
806
  } else {
807
    m_uiWatchdog.start();
82 ✔
808
  }
809
  ui->treeView->setEnabled(state);
370 ✔
810
  ui->lineEdit->setEnabled(state);
370 ✔
811
  ui->actionAddPassword->setEnabled(state);
370 ✔
812
  ui->actionAddFolder->setEnabled(state);
370 ✔
813
  ui->actionUsers->setEnabled(state);
370 ✔
814
  ui->actionConfig->setEnabled(state);
370 ✔
815
  m_uiEnabled = state;
370 ✔
816
  updateProfileBoxEnabled();
370 ✔
817
  const bool uiEnabled = state;
818
  // is a file selected?
819
  state &= ui->treeView->currentIndex().isValid();
740 ✔
820
  ui->actionDelete->setEnabled(state);
370 ✔
821
  ui->actionEdit->setEnabled(state);
370 ✔
822
  updateGitButtonVisibility(uiEnabled);
370 ✔
823
  // `state` is now "UI enabled AND a file is selected", which is exactly when
824
  // generating an OTP makes sense.
825
  updateOtpButtonVisibility(state);
370 ✔
826
}
827

828
void MainWindow::restoreWindow() {
176 ✔
829
  // saveGeometry() covers position, size, maximized state and screen;
830
  // anything applied on top discards it. Centre only when nothing was saved.
831
  const QByteArray geometry = QtPassSettings::getGeometry();
352 ✔
832
  if (geometry.isEmpty() || !restoreGeometry(geometry)) {
176 ✔
833
    WindowStateStore::centreOnCursorScreen(*this);
4 ✔
834
  }
835
  restoreState(QtPassSettings::getSavestate(saveState()));
176 ✔
836
  const AppSettings s = QtPassSettings::load();
176 ✔
837

838
  applyWindowFlagsSettings();
176 ✔
839

840
  if (s.useTrayIcon && m_tray == nullptr) {
176 ✔
841
    initTrayIcon();
2 ✔
842
    // Minimized to the tray only when there is one: without a system tray
843
    // initTrayIcon() gave up, and a hidden window could not be brought back.
844
    if (s.startMinimized && m_tray != nullptr) {
2 ✔
845
      // since we are still in constructor, can't directly hide
UNCOV
846
      QTimer::singleShot(10, this, &MainWindow::hide);
×
847
    }
848
  } else if (!s.useTrayIcon && m_tray != nullptr) {
174 ✔
UNCOV
849
    destroyTrayIcon();
×
850
  }
851
}
352 ✔
852

853
void MainWindow::onConfig() { config(); }
1 ✔
854

855
void MainWindow::showAbout() {
1 ✔
856
  QMessageBox::about(
1 ✔
857
      this, tr("About QtPass"),
1 ✔
858
      tr("<h3>QtPass %1</h3>"
1 ✔
859
         "<p>A multi-platform GUI for <a "
860
         "href=\"https://www.passwordstore.org/\">"
861
         "pass</a>, the standard Unix password manager.</p>"
862
         "<p><a href=\"https://qtpass.org/\">qtpass.org</a> &middot; "
863
         "<a href=\"https://github.com/IJHack/QtPass\">Source and "
864
         "issues</a></p>"
865
         "<p>Copyright &copy; 2014&ndash;%2 IJhack. Licensed under the "
866
         "<a href=\"https://www.gnu.org/licenses/gpl-3.0.html\">GNU GPL "
867
         "version 3</a> or later.</p>")
868
          .arg(QStringLiteral(VERSION),
2 ✔
869
               QString::number(QDate::currentDate().year())));
2 ✔
870
}
1 ✔
871

872
void MainWindow::on_lineEdit_textChanged(const QString &arg1) {
46 ✔
873
  if (m_grep.inGrepMode())
46 ✔
874
    return;
875
  ui->statusBar->showMessage(tr("Looking for: %1").arg(arg1), 1000);
68 ✔
876
  ui->treeView->expandAll();
34 ✔
877
  // Drop any decrypt still pending for the entry that was shown: otherwise it
878
  // keeps its right to the panel and, with "Always copy", the clipboard, and
879
  // when it lands late it shows that entry's password under the new heading.
880
  m_shownFile.clear();
34 ✔
881
  cancelOtpRequest();
34 ✔
882
  clearPanel(false);
34 ✔
883
  ui->passwordName->setText("");
68 ✔
884
  ui->actionEdit->setEnabled(false);
34 ✔
885
  ui->actionDelete->setEnabled(false);
34 ✔
886
  searchTimer.start();
34 ✔
887
}
888

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

894
  if (query.isEmpty()) {
38 ✔
895
    ui->treeView->collapseAll();
1 ✔
896
    deselect();
1 ✔
897
  }
898

899
  // The words are matched literally, in order, with anything in between:
900
  // "work vpn" finds work/acme/vpn. Regular expressions belong to the
901
  // content search; here a typed "[" or "(" must not switch filtering off.
902
  QStringList words;
38 ✔
903
  for (const QString &word :
904
       query.split(QLatin1Char(' '), Qt::SkipEmptyParts)) {
114 ✔
905
    words << QRegularExpression::escape(word);
38 ✔
906
  }
907
  QRegularExpression regExp(words.join(QStringLiteral(".*")),
76 ✔
908
                            QRegularExpression::CaseInsensitiveOption);
38 ✔
909
  m_tree->setFilter(regExp);
38 ✔
910

911
  if (m_tree->proxy().rowCount() > 0 && !query.isEmpty()) {
38 ✔
912
    selectFirstFile();
27 ✔
913
  } else {
914
    ui->actionEdit->setEnabled(false);
11 ✔
915
    ui->actionDelete->setEnabled(false);
11 ✔
916
  }
917
}
76 ✔
918

919
void MainWindow::on_lineEdit_returnPressed() {
16 ✔
920
  qCDebug(lcQtPass) << "on_lineEdit_returnPressed"
16 ✔
UNCOV
921
                    << m_tree->proxy().rowCount();
×
922

923
  if (m_grep.inGrepMode()) {
16 ✔
924
    const QString query = ui->lineEdit->text();
11 ✔
925
    if (!query.isEmpty()) {
11 ✔
926
      ui->grepResultsList->clear();
8 ✔
927
      ui->statusBar->showMessage(tr("Searching…"));
16 ✔
928
      if (m_grep.beginSearch()) {
929
        QApplication::setOverrideCursor(Qt::WaitCursor);
8 ✔
930
      }
931
      QtPassSettings::getPass()->Grep(query, ui->grepCaseButton->isChecked());
16 ✔
932
    } else {
933
      cancelContentSearch();
3 ✔
934
      if (m_grep.cancelSearch()) {
935
        QApplication::restoreOverrideCursor();
2 ✔
936
      }
937
      ui->grepResultsList->clear();
3 ✔
938
      ui->grepResultsList->setVisible(false);
3 ✔
939
      ui->treeView->setVisible(true);
3 ✔
940
    }
941
    return;
942
  }
943

944
  // Return within the search delay acts on the text as typed, not on the
945
  // tree as the previous text filtered it.
946
  if (searchTimer.isActive()) {
5 ✔
947
    searchTimer.stop();
5 ✔
948
    onTimeoutSearch();
5 ✔
949
  }
950
  if (m_tree->proxy().rowCount() > 0) {
5 ✔
951
    selectFirstFile();
5 ✔
952
    on_treeView_clicked(ui->treeView->currentIndex());
5 ✔
953
  }
954
}
955

956
void MainWindow::on_grepButton_toggled(bool checked) {
22 ✔
957
  const AppSettings s = QtPassSettings::load();
22 ✔
958
  if (checked) {
22 ✔
959
    m_grep.enterGrepMode();
960
    ui->lineEdit->setPlaceholderText(tr("Search content (regex)"));
28 ✔
961
    // Both backends search through NativeGrep (QRegularExpression), so one
962
    // dialect: PCRE.
963
    ui->lineEdit->setToolTip(
14 ✔
964
        tr("Content search uses Perl-compatible regular expressions (PCRE)."));
14 ✔
965
    ui->lineEdit->clear();
14 ✔
966
    searchTimer.stop();
14 ✔
967
    m_tree->setFilter(QRegularExpression());
14 ✔
968
    ui->grepResultsList->setVisible(false);
14 ✔
969
    // Keep treeView visible until results arrive
970
  } else {
971
    cancelContentSearch();
8 ✔
972
    if (m_grep.leaveGrepMode()) {
973
      QApplication::restoreOverrideCursor();
2 ✔
974
    }
975
    searchTimer.stop();
8 ✔
976
    ui->lineEdit->blockSignals(true);
8 ✔
977
    ui->lineEdit->clear();
8 ✔
978
    ui->lineEdit->blockSignals(false);
8 ✔
979
    ui->lineEdit->setPlaceholderText(tr("Search password"));
16 ✔
980
    ui->lineEdit->setToolTip(QString());
16 ✔
981
    ui->grepResultsList->clear();
8 ✔
982
    ui->grepResultsList->setVisible(false);
8 ✔
983
    ui->treeView->setVisible(true);
8 ✔
984
    m_tree->setFilter(QRegularExpression());
8 ✔
985
  }
986
}
22 ✔
987

988
void MainWindow::onGrepFinished(
11 ✔
989
    const QList<QPair<QString, QStringList>> &results) {
990
  const GrepSearchController::FinishOutcome outcome = m_grep.finishSearch();
991
  if (outcome.restoreCursor) {
11 ✔
992
    QApplication::restoreOverrideCursor();
2 ✔
993
  }
994
  // Re-enable the UI before the discard check so a cancelled search can never
995
  // leave controls disabled.
996
  setUiElementsEnabled(true);
11 ✔
997
  if (outcome.discard) {
11 ✔
998
    return;
8 ✔
999
  }
1000
  if (!m_grep.inGrepMode())
5 ✔
1001
    return;
1002
  ui->grepResultsList->clear();
5 ✔
1003
  if (results.isEmpty()) {
5 ✔
1004
    ui->statusBar->showMessage(tr("No matches found."), 3000);
4 ✔
1005
    ui->grepResultsList->setVisible(false);
2 ✔
1006
    ui->treeView->setVisible(true);
2 ✔
1007
    return;
2 ✔
1008
  }
1009
  const AppSettings s = QtPassSettings::load();
3 ✔
1010
  const bool hideContent = s.hideContent;
3 ✔
1011
  int totalLines = 0;
1012
  int entries = 0;
1013
  bool stopped = false;
1014
  for (const auto &pair : results) {
27 ✔
1015
    if (NativeGrep::isStoppedMarker(pair)) {
24 ✔
1016
      stopped = true;
UNCOV
1017
      continue;
×
1018
    }
1019
    ++entries;
24 ✔
1020
    auto *entryItem = new QTreeWidgetItem(ui->grepResultsList);
24 ✔
1021
    entryItem->setText(0, pair.first);
24 ✔
1022
    entryItem->setData(0, Qt::UserRole, pair.first);
24 ✔
1023
    for (const QString &line : pair.second) {
48 ✔
1024
      auto *lineItem = new QTreeWidgetItem(entryItem);
24 ✔
1025
      // The marker is no content: shown as it is with hidden content too,
1026
      // and not counted as a match.
1027
      if (NativeGrep::isMoreMarker(line)) {
24 ✔
UNCOV
1028
        lineItem->setText(0, tr("… more matches in this entry"));
×
1029
      } else {
1030
        lineItem->setText(0, hideContent ? "***" + tr("Content hidden") + "***"
72 ✔
1031
                                         : line);
1032
        ++totalLines;
24 ✔
1033
      }
1034
      lineItem->setData(0, Qt::UserRole, pair.first);
24 ✔
1035
    }
1036
  }
1037
  ui->grepResultsList->expandAll();
3 ✔
1038
  ui->treeView->setVisible(false);
3 ✔
1039
  ui->grepResultsList->setVisible(true);
3 ✔
1040
  if (stopped) {
3 ✔
1041
    // The search stopped there; more entries may match.
1042
    ui->statusBar->showMessage(
×
UNCOV
1043
        tr("Showing the first %n match(es); search for something narrower "
×
1044
           "to see the rest.",
1045
           nullptr, totalLines),
1046
        10000);
1047
  } else {
1048
    ui->statusBar->showMessage(tr("Found %n match(es)", nullptr, totalLines) +
9 ✔
1049
                                   " " +
3 ✔
1050
                                   tr("in %n entr(ies).", nullptr, entries),
6 ✔
1051
                               3000);
1052
  }
1053
  if (s.useAutoclearPanel)
3 ✔
1054
    clearPanelTimer.start();
1 ✔
1055
}
3 ✔
1056

1057
void MainWindow::on_grepResultsList_itemClicked(QTreeWidgetItem *item,
2 ✔
1058
                                                int /*column*/) {
1059
  const AppSettings s = QtPassSettings::load();
2 ✔
1060
  const QString entry = item->data(0, Qt::UserRole).toString();
2 ✔
1061
  if (entry.isEmpty())
2 ✔
1062
    return;
1063
  const QString fullPath =
1064
      QDir::cleanPath(QDir(s.passStore).filePath(entry + ".gpg"));
4 ✔
1065
  const QModelIndex proxyIndex = m_tree->indexFor(fullPath);
2 ✔
1066
  if (!proxyIndex.isValid())
1067
    return;
1068
  ui->treeView->setCurrentIndex(proxyIndex);
2 ✔
1069
  on_treeView_clicked(proxyIndex);
2 ✔
1070
  if (s.hideContent || s.useAutoclearPanel)
2 ✔
1071
    ui->grepResultsList->clear();
1 ✔
1072
  ui->grepResultsList->setVisible(false);
2 ✔
1073
  ui->treeView->setVisible(true);
2 ✔
1074
  ui->treeView->scrollTo(proxyIndex);
2 ✔
1075
  ui->treeView->setFocus();
2 ✔
1076
}
2 ✔
1077

1078
void MainWindow::cancelContentSearch() {
15 ✔
1079
  QtPassSettings::getRealPass()->CancelGrep();
15 ✔
1080
  QtPassSettings::getImitatePass()->CancelGrep();
15 ✔
1081
}
15 ✔
1082

1083
void MainWindow::selectFirstFile() {
32 ✔
1084
  // The entry named exactly as typed wins: with folders sorted first, the
1085
  // depth-first walk found team/bank before bank.
1086
  QModelIndex index = exactMatch();
32 ✔
1087
  if (!index.isValid()) {
1088
    index = firstFile(m_tree->rootIndex());
15 ✔
1089
  }
1090
  ui->treeView->setCurrentIndex(index);
32 ✔
1091
}
32 ✔
1092

1093
namespace {
1094
/**
1095
 * @brief @p path with each part below @p store spelled as stored on disk.
1096
 *
1097
 * Where the file system ignores case, "Bank.gpg" exists while the file is
1098
 * bank.gpg, and the tree knows the entry only by that spelling.
1099
 * @param store The store folder.
1100
 * @param path An existing file in the store.
1101
 * @return @p path itself when every part is spelled as stored, otherwise
1102
 *         the path with the stored spelling.
1103
 */
1104
auto spelledAsStored(const QString &store, const QString &path) -> QString {
33 ✔
1105
  const QStringList parts = QDir(store).relativeFilePath(path).split(
66 ✔
1106
      QLatin1Char('/'), Qt::SkipEmptyParts);
33 ✔
1107
  QDir dir(store);
33 ✔
1108
  bool respelled = false;
1109
  for (int i = 0; i < parts.size(); ++i) {
36 ✔
1110
    const bool leaf = i == parts.size() - 1;
36 ✔
1111
    const QStringList names =
1112
        dir.entryList((leaf ? QDir::Files : QDir::Dirs) | QDir::Hidden |
36 ✔
1113
                      QDir::NoDotAndDotDot);
39 ✔
1114
    QString name = parts.at(i);
1115
    if (!names.contains(name)) {
36 ✔
UNCOV
1116
      const auto stored = std::find_if(
×
1117
          names.cbegin(), names.cend(), [&name](const QString &candidate) {
UNCOV
1118
            return candidate.compare(name, Qt::CaseInsensitive) == 0;
×
1119
          });
UNCOV
1120
      if (stored == names.cend()) {
×
1121
        return path;
1122
      }
UNCOV
1123
      name = *stored;
×
1124
      respelled = true;
1125
    }
1126
    if (leaf) {
36 ✔
1127
      return respelled ? QDir::cleanPath(dir.filePath(name)) : path;
66 ✔
1128
    }
1129
    if (!dir.cd(name)) {
3 ✔
1130
      return path;
1131
    }
1132
  }
1133
  return path;
1134
}
33 ✔
1135
} // namespace
1136

1137
auto MainWindow::exactMatchPath() -> QString {
50 ✔
1138
  const QString text = QDir::fromNativeSeparators(ui->lineEdit->text());
100 ✔
1139
  const QString store = QtPassSettings::getPassStore();
100 ✔
1140
  // A name may begin or end with a space: " bank" is that entry, not bank.
1141
  // Only when no entry is named so are spaces around the text dropped.
1142
  for (const QString &typed : {text, text.trimmed()}) {
186 ✔
1143
    if (typed.isEmpty()) {
69 ✔
UNCOV
1144
      continue;
×
1145
    }
1146
    const QString path =
1147
        QDir::cleanPath(QDir(store).filePath(typed + QStringLiteral(".gpg")));
138 ✔
1148
    if (PathValidator::isPathInStore(store, path) && QFileInfo(path).isFile()) {
69 ✔
1149
      return spelledAsStored(store, path);
33 ✔
1150
    }
1151
  }
150 ✔
1152
  return {};
17 ✔
1153
}
1154

1155
auto MainWindow::exactMatch() -> QModelIndex {
46 ✔
1156
  const QString path = exactMatchPath();
46 ✔
1157
  if (path.isEmpty()) {
46 ✔
1158
    return {};
16 ✔
1159
  }
1160
  // indexFor() maps through the filter: a row the filter hides is no match.
1161
  const QModelIndex index = m_tree->indexFor(path);
30 ✔
1162
  if (!index.isValid() || !m_tree->fileInfo(index).isFile()) {
53 ✔
1163
    return {};
7 ✔
1164
  }
1165
  return index;
23 ✔
1166
}
1167

1168
void MainWindow::applySearchText(const QString &text) {
9 ✔
1169
  // A name search: content search, left on, kept its results over the tree
1170
  // and ignored the text.
1171
  if (ui->grepButton->isChecked()) {
9 ✔
1172
    ui->grepButton->setChecked(false);
1 ✔
1173
  }
1174
  delete m_pendingOpen;
9 ✔
1175
  ui->lineEdit->setText(text);
9 ✔
1176
  // Filter now, not after the search delay: the timer would leave the tree
1177
  // as the previous text filtered it.
1178
  searchTimer.stop();
9 ✔
1179
  onTimeoutSearch();
9 ✔
1180
  if (const QModelIndex exact = exactMatch(); exact.isValid()) {
9 ✔
1181
    openExactMatch(exact);
5 ✔
1182
    return;
5 ✔
1183
  }
1184
  // The tree loads folders in the background: at start, or right after the
1185
  // window is shown again, an entry that exists may not be in it yet. Try
1186
  // again as folders finish loading, for a few seconds, unless the search
1187
  // text changes meanwhile: any change ends the wait, even one typed back to
1188
  // this text, which is a new search that has not asked to open anything.
1189
  if (exactMatchPath().isEmpty()) {
8 ✔
1190
    return;
1191
  }
1192
  auto *pending = new QObject(this);
3 ✔
1193
  m_pendingOpen = pending;
1194
  QTimer::singleShot(5000, pending, &QObject::deleteLater);
3 ✔
1195
  // Disconnected at once: with deleteLater() alone, a folder that finished
1196
  // loading before the deletion still ran the open, or ran it twice.
1197
  const auto stop = [this, pending] {
2 ✔
1198
    disconnect(&m_tree->fileSystem(), nullptr, pending, nullptr);
2 ✔
1199
    disconnect(ui->lineEdit, nullptr, pending, nullptr);
2 ✔
1200
    pending->deleteLater();
2 ✔
1201
  };
5 ✔
1202
  connect(ui->lineEdit, &QLineEdit::textChanged, pending, stop);
3 ✔
1203
  connect(&m_tree->fileSystem(), &QFileSystemModel::directoryLoaded, pending,
3 ✔
1204
          [this, stop](const QString &) {
6 ✔
1205
            searchTimer.stop();
5 ✔
1206
            onTimeoutSearch();
5 ✔
1207
            if (const QModelIndex exact = exactMatch(); exact.isValid()) {
5 ✔
1208
              stop();
1 ✔
1209
              openExactMatch(exact);
1 ✔
1210
            }
1211
          });
5 ✔
1212
}
1213

1214
void MainWindow::openExactMatch(const QModelIndex &index) {
6 ✔
1215
  // Made current here, not left to the filter pass before: the tree may have
1216
  // moved its current row since, and with none on_treeView_clicked() only
1217
  // names the entry without decrypting it.
1218
  ui->treeView->setCurrentIndex(index);
6 ✔
1219
  on_treeView_clicked(index);
6 ✔
1220
}
6 ✔
1221

1222
auto MainWindow::firstFile(QModelIndex parentIndex) -> QModelIndex {
23 ✔
1223
  StoreModel &proxy = m_tree->proxy();
23 ✔
1224
  int numRows = proxy.rowCount(parentIndex);
23 ✔
1225
  for (int row = 0; row < numRows; ++row) {
30 ✔
1226
    QModelIndex index = proxy.index(row, 0, parentIndex);
20 ✔
1227
    if (m_tree->fileInfo(index).isFile()) {
20 ✔
1228
      return index;
13 ✔
1229
    }
1230
    if (proxy.hasChildren(index)) {
12 ✔
1231
      QModelIndex childFile = firstFile(index);
8 ✔
1232
      if (childFile.isValid())
1233
        return childFile;
5 ✔
1234
    }
1235
  }
1236
  return QModelIndex();
10 ✔
1237
}
1238

1239
// Guards the input dialogs (create, move, rename) against names like
1240
// "../../etc/passwd" or absolute paths escaping the store root.
1241
auto MainWindow::confirmPathInStore(const QString &candidate) -> bool {
11 ✔
1242
  if (PathValidator::isPathInStore(QtPassSettings::getPassStore(), candidate)) {
22 ✔
1243
    return true;
1244
  }
1245
  QMessageBox::warning(this, tr("Invalid name"),
9 ✔
1246
                       tr("That name would resolve outside the password "
3 ✔
1247
                          "store. Please choose a different name."));
1248
  return false;
3 ✔
1249
}
1250

1251
void MainWindow::setPassword(const QString &file, bool isNew) {
6 ✔
1252
  const AppSettings s = QtPassSettings::load();
6 ✔
1253
  PasswordDialog d(QtPassSettings::getPass(), s, file, isNew, this);
6 ✔
1254
  // A copy out of the editor is autocleared like one from the display.
1255
  connect(&d, &PasswordDialog::copied, &m_qtPass->clipboard(),
6 ✔
1256
          &ClipboardManager::trackCopied);
6 ✔
1257

1258
  if (isNew) {
6 ✔
1259
    const QString storePath = s.passStore;
1260
    QString folder = m_tree->currentDir(false);
1 ✔
1261
    if (folder.isEmpty()) {
1 ✔
UNCOV
1262
      folder = storePath;
×
1263
    }
1264
    // Folders to pick from, the tree's current one preselected. Real folders
1265
    // only: a linked or junctioned one would write the entry outside the store.
1266
    QStringList folders{QString()};
2 ✔
1267
    const QStringList found = Util::directoriesUnder(storePath);
1 ✔
1268
    for (const QString &path : found) {
16 ✔
1269
      const QString rel = QDir(storePath).relativeFilePath(path);
15 ✔
1270
      if (!rel.startsWith(u'.') && !rel.contains(QStringLiteral("/."))) {
45 ✔
1271
        folders << rel;
1272
      }
1273
    }
1274
    std::sort(folders.begin() + 1, folders.end());
1 ✔
1275
    d.setNewEntryLocation(storePath, folders,
1 ✔
1276
                          QDir(storePath).relativeFilePath(folder));
2 ✔
1277
    QHash<QString, QStringList> templates =
1278
        TemplateIO::readTemplates(storePath);
1 ✔
1279
    if (!templates.isEmpty()) {
1280
      QString defaultTemplate =
1281
          TemplateIO::getFolderTemplate(folder, storePath);
1 ✔
1282
      d.setAvailableTemplates(templates, defaultTemplate);
1 ✔
1283
    }
1284
  }
1 ✔
1285

1286
  if (!d.exec()) {
6 ✔
1287
    ui->treeView->setFocus();
5 ✔
1288
  }
1289
}
6 ✔
1290

1291
void MainWindow::addPassword() { setPassword(QString()); }
2 ✔
1292

1293
auto MainWindow::confirmDeletion(const QString &file, bool isDir) -> bool {
4 ✔
1294
  const QString path = QDir::separator() + file;
4 ✔
1295
  if (!isDir) {
4 ✔
1296
    return PlainMessageBox::askYes(
2 ✔
1297
        this, tr("Delete password?"),
2 ✔
1298
        tr("Are you sure you want to delete %1?").arg(path));
4 ✔
1299
  }
1300
  // Whole sentences, not a question stitched from pieces: a verb-final
1301
  // language cannot put the rest of the question after the path.
1302
  // Plain text, as every box quoting the store: the path is a name other
1303
  // writers control, and as rich text "a  b" would also show as "a b".
1304
  QString question =
1305
      tr("Are you sure you want to delete %1 and the whole content?").arg(path);
2 ✔
1306
  // A link, junction or special file inside is as unexpected as a stray
1307
  // plain file: the walker leaves them out of content and reports them.
1308
  QStringList skipped;
2 ✔
1309
  const QStringList content = Util::regularFilesUnder(
6 ✔
1310
      m_tree->fileSystem().rootPath() + path, {QStringLiteral("*")}, &skipped);
6 ✔
1311
  const bool unexpected =
1312
      !skipped.isEmpty() ||
2 ✔
1313
      std::any_of(content.cbegin(), content.cend(), [](const QString &entry) {
2 ✔
1314
        return QFileInfo(entry).suffix() != QLatin1String("gpg");
4 ✔
1315
      });
1316
  if (unexpected) {
1317
    question += QStringLiteral("\n\n") +
1 ✔
1318
                tr("Attention: there are unexpected files in the given "
1 ✔
1319
                   "folder, check them before continuing.");
1 ✔
1320
  }
1321
  return PlainMessageBox::askYes(this, tr("Delete folder?"), question);
4 ✔
1322
}
1323

1324
auto MainWindow::confirmLinkRemoval(const QString &file) -> bool {
1 ✔
1325
  // Only the link goes (ImitatePass::Remove unlinks it); nothing behind it
1326
  // is looked at or mentioned.
1327
  return PlainMessageBox::askYes(
1 ✔
1328
      this, tr("Delete link?"),
1 ✔
1329
      tr("%1 is a symbolic link or junction. Remove the link? What it "
1 ✔
1330
         "points to is left alone.")
1331
          .arg(QDir::separator() + file));
2 ✔
1332
}
1333

1334
void MainWindow::onDelete() {
8 ✔
1335
  const QModelIndex currentIndex = ui->treeView->currentIndex();
8 ✔
1336
  if (!currentIndex.isValid()) {
1337
    // Otherwise the whole password directory would be deleted (#556).
1338
    return;
5 ✔
1339
  }
1340

1341
  const bool isDir = !m_tree->fileInfo(currentIndex).isFile();
6 ✔
1342
  const QString file =
1343
      isDir ? m_tree->currentDir(true) : getFile(currentIndex, true);
6 ✔
1344
  const QString folder =
1345
      m_tree->fileSystem().rootPath() + QDir::separator() + file;
6 ✔
1346
  const bool linkedFolder = isDir && Util::isLinkedFolder(folder);
6 ✔
1347

1348
  if (!linkedFolder && refuseLinkedFolder(folder)) {
5 ✔
1349
    // Behind a link: deleting would reach outside the store.
1350
    return;
1351
  }
1352
  const bool confirmed =
1353
      linkedFolder ? confirmLinkRemoval(file) : confirmDeletion(file, isDir);
5 ✔
1354
  if (!confirmed) {
5 ✔
1355
    return;
1356
  }
1357
  QtPassSettings::getPass()->Remove(file, isDir);
6 ✔
1358
}
1359

1360
void MainWindow::cancelOtpRequest() {
84 ✔
1361
  m_otpRequestFile.clear();
84 ✔
1362
  m_copyRequestFile.clear();
84 ✔
1363
}
84 ✔
1364

1365
void MainWindow::onOperationError() {
34 ✔
1366
  cancelOtpRequest();
34 ✔
1367
  // executeWrapperStarted() emptied the panel and the browser when the
1368
  // operation started (a refusal says so too); what is left to forget is
1369
  // which entry the panel was about to show.
1370
  m_shownFile.clear();
34 ✔
1371
  // A save's refresh waiting for its push is dropped: it would clear the
1372
  // push's error (or whatever failed before it) from the browser.
1373
  m_refreshAfterPush.clear();
34 ✔
1374
  m_refreshAfterPushOwner = nullptr;
1375
}
34 ✔
1376

1377
// Derives the code in-process from one decrypt, so it works with either
1378
// backend on every platform; otpFromFileToClipboard() finishes the job.
1379
void MainWindow::onOtp() {
10 ✔
1380
  QString file = getFile(ui->treeView->currentIndex(), true);
10 ✔
1381
  if (file.isEmpty()) {
10 ✔
1382
    flashText(tr("No password selected for OTP generation"), true);
1 ✔
1383
    return;
1 ✔
1384
  }
1385
  if (!QtPassSettings::isUseOtp()) {
9 ✔
1386
    // Normally unreachable (the action is hidden), but never fail silently.
1387
    flashText(tr("No OTP code found in this password entry"), true);
1 ✔
1388
    return;
1 ✔
1389
  }
1390

1391
  // Fast path: the panel shows a live code, so no decrypt, and one clipboard
1392
  // write (two setMimeData calls in one turn can empty the Windows
1393
  // clipboard). Only for *this* entry: arrow keys and right-click move
1394
  // currentIndex without QTreeView::clicked, so the code may be another's.
1395
  const QString shown =
1396
      (m_shownFile == file) ? m_displayPanel->currentOtpCode() : QString();
8 ✔
1397
  if (!shown.isEmpty()) {
8 ✔
1398
    m_qtPass->clipboard().copyText(shown);
1 ✔
1399
    showStatusMessage(tr("OTP code copied to clipboard"));
2 ✔
1400
    return;
1401
  }
1402

1403
  // Fallback: decrypt once. The request file keeps passShowHandler from
1404
  // copying the password and tells otpFromFileToClipboard its answer.
1405
  m_otpRequestFile = file;
7 ✔
1406
  setUiElementsEnabled(false);
7 ✔
1407
  // Keep the marker in step so a second request takes the fast path; safe as
1408
  // executeWrapperStarted() clears the panel, so a failed decrypt shows none.
1409
  m_shownFile = file;
7 ✔
1410
  QtPassSettings::getPass()->Show(file);
14 ✔
1411
}
1412

1413
void MainWindow::onEdit() {
2 ✔
1414
  QString file = getFile(ui->treeView->currentIndex(), true);
2 ✔
1415
  editPassword(file);
2 ✔
1416
}
2 ✔
1417

1418
void MainWindow::onUsers() {
2 ✔
1419
  const QString dir = m_tree->currentDir(false);
2 ✔
1420
  if (refuseLinkedFolder(dir)) {
2 ✔
1421
    return;
1422
  }
1423

1424
  UsersDialog d(QtPassSettings::getPass(), QtPassSettings::load(), dir, this);
1 ✔
1425
  if (!d.exec()) {
1 ✔
1426
    ui->treeView->setFocus();
1 ✔
1427
  }
1428
}
1 ✔
1429

1430
void MainWindow::messageAvailable(const QString &message) {
10 ✔
1431
  show();
10 ✔
1432
  raise();
10 ✔
1433
  if (message.isEmpty()) {
10 ✔
1434
    focusInput();
1 ✔
1435
  } else {
1436
    ui->treeView->expandAll();
9 ✔
1437
    applySearchText(message);
9 ✔
1438
  }
1439
}
10 ✔
1440

1441
void MainWindow::updateProfileBox() {
172 ✔
1442
  const Profiles profiles = QtPassSettings::getProfiles();
172 ✔
1443
  bool activeGone = false;
1444

1445
  if (profiles.isEmpty()) {
7 ✔
1446
    ui->profileWidget->hide();
165 ✔
1447
  } else {
1448
    ui->profileWidget->show();
7 ✔
1449
    // A refill is no choice of the user's: clearing and adding items moves
1450
    // the current text, which would otherwise switch profiles.
1451
    const QSignalBlocker quiet(ui->profileBox);
7 ✔
1452
    ui->profileBox->clear();
7 ✔
1453
    for (auto i = profiles.cbegin(); i != profiles.cend(); ++i) {
19 ✔
1454
      if (!i.key().isEmpty()) {
12 ✔
1455
        ui->profileBox->addItem(i.key());
12 ✔
1456
      }
1457
    }
1458
    ui->profileBox->model()->sort(0);
7 ✔
1459
    int index = ui->profileBox->findText(QtPassSettings::getProfile());
14 ✔
1460
    if (index != -1) { //  -1 for not found
7 ✔
1461
      ui->profileBox->setCurrentIndex(index);
6 ✔
1462
    } else if (ui->profileBox->count() > 0) {
1 ✔
1463
      // The active profile is gone (removed in Settings): the box shows the
1464
      // first one, and the settings and backend must follow it, or the
1465
      // removed profile's store stays in use behind it.
1466
      ui->profileBox->setCurrentIndex(0);
1 ✔
1467
      activeGone = true;
1468
    }
1469
  }
7 ✔
1470
  if (activeGone) {
7 ✔
1471
    on_profileBox_currentTextChanged(ui->profileBox->currentText());
2 ✔
1472
  }
1473
  updateProfileBoxEnabled();
172 ✔
1474
}
172 ✔
1475

1476
void MainWindow::updateProfileBoxEnabled() {
581 ✔
1477
  // No profile switch while anything of the store runs or waits: the
1478
  // backend's store and environment would change under it, and what is
1479
  // still queued (a push after a save, say) would finish for the other
1480
  // profile (#2071). Asked of the backend, not only of the interface: the
1481
  // watchdog releases the interface while a slow gpg or git still runs.
1482
  // Every backend: one kept from before a switch of backend may still
1483
  // run what was queued on it.
1484
  ui->profileBox->setEnabled(m_uiEnabled && ui->profileBox->count() > 1 &&
1,163 ✔
1485
                             QtPassSettings::backendsIdle());
11 ✔
1486
}
581 ✔
1487

1488
void MainWindow::on_profileBox_currentTextChanged(const QString &name) {
6 ✔
1489
  if (m_freshStart || name == QtPassSettings::getProfile()) {
18 ✔
1490
    return;
1 ✔
1491
  }
1492
  // The box is disabled while anything runs; should a change come through
1493
  // anyway, the active profile stays and the box says so again.
1494
  if (!m_uiEnabled || !QtPassSettings::backendsIdle()) {
5 ✔
1495
    const QSignalBlocker quiet(ui->profileBox);
×
UNCOV
1496
    ui->profileBox->setCurrentText(QtPassSettings::getProfile());
×
1497
    return;
UNCOV
1498
  }
×
1499
  // A content search runs outside the queue: leaving grep mode cancels it,
1500
  // so its results for the old store are dropped, not shown for the new.
1501
  if (m_grep.inGrepMode()) {
5 ✔
1502
    ui->grepButton->setChecked(false);
1 ✔
1503
  }
1504

1505
  ui->lineEdit->clear();
5 ✔
1506

1507
  const Profile prof = QtPassSettings::getProfiles().value(name);
10 ✔
1508
  AppSettings s = QtPassSettings::load();
5 ✔
1509
  s.activeProfile = name;
5 ✔
1510
  s.passStore = prof.path;
5 ✔
1511
  s.passSigningKey = prof.signingKey;
5 ✔
1512
  // A profile without its own Git flags keeps the global values.
1513
  s.useGit = prof.useGit.value_or(s.useGit);
5 ✔
1514
  s.autoPush = prof.autoPush.value_or(s.autoPush);
5 ✔
1515
  s.autoPull = prof.autoPull.value_or(s.autoPull);
5 ✔
1516
  QtPassSettings::save(s);
5 ✔
1517
  ui->statusBar->showMessage(tr("Profile changed to %1").arg(name), 2000);
10 ✔
1518

1519
  QtPassSettings::getPass()->updateEnv();
5 ✔
1520

1521
  m_tree->setStore(QtPassSettings::getPassStore());
10 ✔
1522
  deselect();
5 ✔
1523
  ui->treeView->setCurrentIndex(QModelIndex());
5 ✔
1524
}
5 ✔
1525

1526
void MainWindow::initTrayIcon() {
3 ✔
1527
  m_tray = new TrayIcon(this);
3 ✔
1528
  if (!m_tray->getIsAllocated()) {
3 ✔
1529
    destroyTrayIcon();
3 ✔
1530
    return;
3 ✔
1531
  }
1532
#ifndef Q_OS_MACOS
UNCOV
1533
  m_tray->addToggle(ui->actionShowMenuBar);
×
1534
#endif
1535
}
1536

1537
void MainWindow::destroyTrayIcon() {
3 ✔
1538
  delete m_tray;
3 ✔
1539
  m_tray = nullptr;
3 ✔
1540
}
3 ✔
1541

1542
void MainWindow::closeEvent(QCloseEvent *event) {
4 ✔
1543
  // Save in both branches: a tray user only ever hides the window, and
1544
  // used to quit through the tray menu with nothing ever written.
1545
  saveWindowState();
4 ✔
1546
  // Only with a tray icon to come back from: without one (none asked for, or
1547
  // no system tray in this session) a hidden QtPass ran on invisibly, with the
1548
  // last entry in its window and the password on the clipboard.
1549
  if (QtPassSettings::isHideOnClose() && m_tray != nullptr) {
8 ✔
UNCOV
1550
    this->hide();
×
1551
    event->ignore();
1552
  } else {
1553
    m_qtPass->clipboard().clear();
4 ✔
1554
    event->accept();
1555
    // A visible QSystemTrayIcon keeps the application alive, so
1556
    // quitOnLastWindowClosed never fires; quit explicitly.
1557
    QApplication::quit();
4 ✔
1558
  }
1559
}
4 ✔
1560

1561
auto MainWindow::eventFilter(QObject *obj, QEvent *event) -> bool {
6,938 ✔
1562
  if ((obj == ui->toolBar || obj == menuBar()) &&
6,938 ✔
1563
      event->type() == QEvent::PaletteChange) {
1564
    // Breeze gives these bars a "header" palette and, after a runtime
1565
    // light/dark switch, stamps the previous theme's colours back from a
1566
    // cached kdeglobals, hiding the toolbar icons. Deferred so we never
1567
    // re-enter the style while it is still applying its palette.
1568
    QTimer::singleShot(0, this, &MainWindow::dropStaleToolsAreaPalettes);
36 ✔
1569
  }
1570
  if (obj == ui->lineEdit && event->type() == QEvent::KeyPress) {
6,938 ✔
1571
    auto *key = dynamic_cast<QKeyEvent *>(event);
4 ✔
1572
    if (key != nullptr && key->key() == Qt::Key_Down) {
4 ✔
1573
      ui->treeView->setFocus();
1 ✔
1574
    }
1575
    // Return ends at the search box: QLineEdit emits returnPressed() and
1576
    // leaves the key unaccepted, so keyPressEvent() would open the tree's
1577
    // current entry as well. In content search that is an entry nobody
1578
    // asked for; by name, the first hit a second time.
1579
    if (key != nullptr &&
4 ✔
1580
        (key->key() == Qt::Key_Return || key->key() == Qt::Key_Enter)) {
1 ✔
1581
      ui->lineEdit->event(event);
3 ✔
1582
      event->accept();
1583
      return true;
3 ✔
1584
    }
1585
  }
1586
  return QObject::eventFilter(obj, event);
6,935 ✔
1587
}
1588

1589
// Only once the application palette changed (see m_themeSwitched): a bar
1590
// whose active Window lightness is far from the application's shows the
1591
// other theme.
1592
void MainWindow::dropStaleToolsAreaPalettes() {
31 ✔
1593
  if (!m_themeSwitched) {
31 ✔
1594
    return;
1595
  }
1596
  constexpr int kStaleToolsAreaLightness = 64;
1597
  // The active group on both sides: a bar's palette() reads the inactive
1598
  // group while another window has focus (the settings app, during a theme
1599
  // switch), and Breeze gives the header set different inactive colours.
1600
  const int appLightness = QApplication::palette()
54 ✔
1601
                               .color(QPalette::Active, QPalette::Window)
1602
                               .lightness();
27 ✔
1603
  for (QWidget *bar : {static_cast<QWidget *>(ui->toolBar),
108 ✔
1604
                       static_cast<QWidget *>(menuBar())}) {
81 ✔
1605
    if (!bar->testAttribute(Qt::WA_SetPalette)) {
54 ✔
1606
      continue;
48 ✔
1607
    }
1608
    const int barLightness =
1609
        bar->palette().color(QPalette::Active, QPalette::Window).lightness();
12 ✔
1610
    if (qAbs(barLightness - appLightness) <= kStaleToolsAreaLightness) {
6 ✔
1611
      continue;
2 ✔
1612
    }
1613
    bar->setPalette(QPalette());
4 ✔
1614
    // Both bars are transparent and the style paints the tools area from the
1615
    // stale palette, so fill our own. Window, not their Button role, which is
1616
    // not the window colour in either theme.
1617
    bar->setBackgroundRole(QPalette::Window);
4 ✔
1618
    bar->setAutoFillBackground(true);
4 ✔
1619
  }
1620
}
1621

1622
void MainWindow::keyPressEvent(QKeyEvent *event) {
20 ✔
1623
  switch (event->key()) {
20 ✔
1624
  case Qt::Key_Delete:
1 ✔
1625
    onDelete();
1 ✔
1626
    break;
1 ✔
1627
  case Qt::Key_Return:
2 ✔
1628
  case Qt::Key_Enter:
1629
    // While content search results hide the tree, its current entry is not
1630
    // what the user looks at: Return on a result opens that result.
1631
    if (ui->treeView->isHidden()) {
2 ✔
1632
      QTreeWidgetItem *result = ui->grepResultsList->currentItem();
1 ✔
1633
      if (result != nullptr && ui->grepResultsList->hasFocus()) {
1 ✔
1634
        on_grepResultsList_itemClicked(result, 0);
1 ✔
1635
      }
1636
      break;
1637
    }
1638
    if (m_tree->proxy().rowCount() > 0) {
1 ✔
1639
      on_treeView_clicked(ui->treeView->currentIndex());
1 ✔
1640
    }
1641
    break;
1642
  case Qt::Key_Escape:
3 ✔
1643
    ui->lineEdit->clear();
3 ✔
1644
    break;
3 ✔
1645
  default:
1646
    break;
1647
  }
1648
}
20 ✔
1649

1650
void MainWindow::addShareMenu(QMenu &contextMenu, const AppSettings &s) {
9 ✔
1651
  const QString dirPath = QDir::cleanPath(m_tree->currentDir(false));
9 ✔
1652
  auto *shareMenu = new QMenu(tr("Share"), &contextMenu);
9 ✔
1653
  contextMenu.addMenu(shareMenu);
9 ✔
1654

1655
  const QString gpgIdPath = Pass::getGpgIdPath(dirPath, s.passStore);
9 ✔
1656
  const bool gpgIdExists = !gpgIdPath.isEmpty() && QFile(gpgIdPath).exists();
9 ✔
1657
  const QString exePath = s.usePass ? s.passExecutable : s.gpgExecutable;
9 ✔
1658
  const bool gpgAvailable =
1659
      !exePath.isEmpty() &&
18 ✔
1660
      (Executor::parseWslCommand(exePath) || QFile(exePath).exists());
18 ✔
1661

1662
  QAction *reencrypt = shareMenu->addAction(tr("Re-encrypt all passwords"));
9 ✔
1663
  reencrypt->setEnabled(gpgIdExists && gpgAvailable);
9 ✔
1664
  connect(reencrypt, &QAction::triggered, this,
9 ✔
1665
          [this, dirPath]() { reencryptPath(dirPath); });
30 ✔
1666

1667
  QAction *exportKey = shareMenu->addAction(tr("Export my public key..."));
9 ✔
1668
  exportKey->setEnabled(gpgAvailable);
9 ✔
1669
  connect(exportKey, &QAction::triggered, this, &MainWindow::exportPublicKey);
9 ✔
1670

1671
  QAction *addRecipientAction = shareMenu->addAction(tr("Add recipient..."));
9 ✔
1672
  addRecipientAction->setEnabled(gpgIdExists && gpgAvailable);
9 ✔
1673
  connect(addRecipientAction, &QAction::triggered, this,
9 ✔
1674
          [this, dirPath]() { addRecipient(dirPath); });
29 ✔
1675

1676
  QAction *shareHelp = shareMenu->addAction(tr("What is this?"));
9 ✔
1677
  connect(shareHelp, &QAction::triggered, this, &MainWindow::showShareHelp);
9 ✔
1678
}
9 ✔
1679

1680
void MainWindow::showContextMenu(const QPoint &pos) {
11 ✔
1681
  const AppSettings s = QtPassSettings::load();
11 ✔
1682
  const QModelIndex index = ui->treeView->indexAt(pos);
11 ✔
1683
  const bool selected = index.isValid();
1684
  if (!selected) {
1685
    ui->treeView->clearSelection();
1 ✔
1686
    ui->actionDelete->setEnabled(false);
1 ✔
1687
    ui->actionEdit->setEnabled(false);
1 ✔
1688
  }
1689
  ui->treeView->setCurrentIndex(index);
11 ✔
1690
  const QPoint globalPos = ui->treeView->viewport()->mapToGlobal(pos);
11 ✔
1691
  const QFileInfo fileOrFolder = m_tree->fileInfo(ui->treeView->currentIndex());
11 ✔
1692
  const bool isDir = fileOrFolder.isDir();
11 ✔
1693

1694
  QMenu contextMenu;
11 ✔
1695
  if (!selected || isDir) {
11 ✔
1696
    const std::array<std::pair<QString, void (MainWindow::*)()>, 4> onFolder{{
1697
        {tr("Open folder with file manager"), &MainWindow::openFolder},
10 ✔
1698
        {tr("Add folder"), &MainWindow::addFolder},
10 ✔
1699
        {tr("Add password"), &MainWindow::addPassword},
10 ✔
1700
        {tr("Users"), &MainWindow::onUsers},
10 ✔
UNCOV
1701
    }};
×
1702
    for (const auto &[text, slot] : onFolder) {
50 ✔
1703
      connect(contextMenu.addAction(text), &QAction::triggered, this, slot);
40 ✔
1704
    }
1705
  } else if (fileOrFolder.isFile()) {
1 ✔
1706
    connect(contextMenu.addAction(tr("Edit")), &QAction::triggered, this,
1 ✔
1707
            &MainWindow::onEdit);
2 ✔
1708
  }
1709
  if (selected) {
11 ✔
1710
    contextMenu.addSeparator();
10 ✔
1711
    if (isDir) {
10 ✔
1712
      connect(contextMenu.addAction(tr("Rename folder")), &QAction::triggered,
9 ✔
1713
              this, &MainWindow::renameFolder);
18 ✔
1714
    } else if (fileOrFolder.isFile()) {
1 ✔
1715
      connect(contextMenu.addAction(tr("Rename password")), &QAction::triggered,
1 ✔
1716
              this, &MainWindow::renamePassword);
2 ✔
1717
    }
1718
    connect(contextMenu.addAction(tr("Delete")), &QAction::triggered, this,
10 ✔
1719
            &MainWindow::onDelete);
10 ✔
1720
    if (isDir) {
10 ✔
1721
      addShareMenu(contextMenu, s);
9 ✔
1722
    }
1723
  }
1724
  contextMenu.exec(globalPos);
11 ✔
1725
}
11 ✔
1726

1727
void MainWindow::showBrowserContextMenu(const QPoint &pos) {
1 ✔
1728
  QMenu *contextMenu = ui->textBrowser->createStandardContextMenu(pos);
1 ✔
1729
  // Reparent from textBrowser: a browser stylesheet cascades to the child
1730
  // QMenu and breaks its opaque native background.
1731
  contextMenu->setParent(this, contextMenu->windowFlags());
1 ✔
1732
  QPoint globalPos = ui->textBrowser->viewport()->mapToGlobal(pos);
1 ✔
1733

1734
  contextMenu->exec(globalPos);
1 ✔
1735
  delete contextMenu;
1 ✔
1736
}
1 ✔
1737

1738
void MainWindow::openFolder() {
1 ✔
1739
  QString dir = m_tree->currentDir(false);
1 ✔
1740

1741
  QString path = QDir::toNativeSeparators(dir);
1 ✔
1742
  QDesktopServices::openUrl(QUrl::fromLocalFile(path));
1 ✔
1743
}
1 ✔
1744

1745
void MainWindow::addFolder() {
8 ✔
1746
  const AppSettings s = QtPassSettings::load();
8 ✔
1747
  bool ok;
1748
  QString dir = m_tree->currentDir(false);
8 ✔
1749
  QString newdir =
1750
      QInputDialog::getText(this, tr("New folder"),
8 ✔
1751
                            tr("New folder: \n(Will be placed in %1 )")
8 ✔
1752
                                .arg(s.passStore + m_tree->currentDir(true)),
16 ✔
1753
                            QLineEdit::Normal, "", &ok);
16 ✔
1754
  if (!ok || newdir.isEmpty()) {
8 ✔
1755
    return;
1756
  }
1757
  // Checked and created as one and the same path: the check resolves ".."
1758
  // lexically, the system after following links, so "link/../x" would pass
1759
  // as the store's x and be made beside the link's target.
1760
  newdir = QDir::cleanPath(newdir.prepend(dir));
7 ✔
1761
  if (!confirmPathInStore(newdir)) {
7 ✔
1762
    return;
1763
  }
1764
  // Behind a link the folder would be made outside the store, as Users,
1765
  // Re-encrypt and Delete already refuse.
1766
  if (refuseLinkedFolder(newdir)) {
6 ✔
1767
    return;
1768
  }
1769
  // The tree, like `pass ls`, hides names that start with a dot.
1770
  const QStringList parts =
1771
      QDir(s.passStore).relativeFilePath(newdir).split(u'/');
5 ✔
1772
  if (std::any_of(parts.cbegin(), parts.cend(), [](const QString &part) {
10 ✔
1773
        return part != u'.' && part.startsWith(u'.');
5 ✔
1774
      })) {
1775
    PlainMessageBox::warning(this, tr("Hidden folder"),
2 ✔
1776
                             tr("A folder that starts with a dot would be "
1 ✔
1777
                                "hidden from the list: %1")
1778
                                 .arg(newdir));
2 ✔
1779
    return;
1 ✔
1780
  }
1781
  // Exists already: an error, as QDir::mkdir() made it before.
1782
  if (QFileInfo::exists(newdir) || !Util::mkpathForStore(newdir)) {
4 ✔
1783
    PlainMessageBox::warning(this, tr("Error"),
2 ✔
1784
                             tr("Failed to create folder: %1").arg(newdir));
2 ✔
1785
    return;
1 ✔
1786
  }
1787
  // With a signing key, ImitatePass::loadVerifiedRecipients and pass
1788
  // (PASSWORD_STORE_SIGNING_KEY) refuse a .gpg-id without .gpg-id.sig, and
1789
  // signing needs a passphrase just to make a folder. So it inherits the
1790
  // parent's signed list; UsersDialog (Init) gives it its own.
1791
  const bool signingConfigured = !s.passSigningKey.trimmed().isEmpty();
3 ✔
1792
  if (s.addGPGId && !signingConfigured) {
3 ✔
1793
    // Seed from the parent's recipients in effect, not from `enabled` keys:
1794
    // that flag is only set in UsersDialog, so it left a zero-byte .gpg-id
1795
    // shadowing the parent's recipients (#1682).
1796
    if (!Pass::seedGpgIdFile(newdir, s.passStore)) {
3 ✔
1797
      PlainMessageBox::warning(
1 ✔
1798
          this, tr("Error"),
1 ✔
1799
          tr("Failed to create .gpg-id file in: %1").arg(newdir));
2 ✔
1800
      return;
1 ✔
1801
    }
1802
  }
1803
}
8 ✔
1804

1805
void MainWindow::renameFolder() {
3 ✔
1806
  bool ok;
1807
  QString srcDir = QDir::cleanPath(m_tree->currentDir(false));
3 ✔
1808
  QString srcDirName = QDir(srcDir).dirName();
3 ✔
1809
  QString newName =
1810
      QInputDialog::getText(this, tr("Rename folder"), tr("Rename folder to: "),
3 ✔
1811
                            QLineEdit::Normal, srcDirName, &ok);
6 ✔
1812
  if (!ok || newName.isEmpty()) {
3 ✔
1813
    return;
1814
  }
1815
  QString destDir = srcDir;
1816
  destDir.replace(srcDir.lastIndexOf(srcDirName), srcDirName.length(), newName);
2 ✔
1817
  if (!confirmPathInStore(destDir)) {
2 ✔
1818
    return;
1819
  }
1820
  QtPassSettings::getPass()->Move(srcDir, destDir, false);
3 ✔
1821
}
1822

1823
void MainWindow::editPassword(const QString &file) {
5 ✔
1824
  if (!file.isEmpty()) {
5 ✔
1825
    const AppSettings s = QtPassSettings::load();
5 ✔
1826
    if (s.useGit && s.autoPull) {
5 ✔
1827
      onUpdate(true);
1 ✔
1828
    }
1829
    // The dialog decrypts the entry itself to fill its fields. That decrypt
1830
    // lands on the same finishedShow the panel uses, so drop the panel's claim
1831
    // to it: otherwise passShowHandler() repaints and, with "Always copy",
1832
    // puts the entry's old password on the clipboard - replacing whatever the
1833
    // user copied to paste into the dialog.
1834
    m_shownFile.clear();
5 ✔
1835
    setPassword(file, false);
5 ✔
1836
  }
5 ✔
1837
}
5 ✔
1838

1839
void MainWindow::renamePassword() {
2 ✔
1840
  bool ok;
1841
  QString file = getFile(ui->treeView->currentIndex(), false);
2 ✔
1842
  QString filePath = QFileInfo(file).path();
2 ✔
1843
  QString fileName = QFileInfo(file).fileName();
2 ✔
1844
  if (fileName.endsWith(".gpg", Qt::CaseInsensitive)) {
4 ✔
1845
    fileName.chop(4);
2 ✔
1846
  }
1847

1848
  QString newName =
1849
      QInputDialog::getText(this, tr("Rename file"), tr("Rename file to: "),
2 ✔
1850
                            QLineEdit::Normal, fileName, &ok);
4 ✔
1851
  if (!ok || newName.isEmpty()) {
2 ✔
1852
    return;
1853
  }
1854
  QString newFile = QDir(filePath).filePath(newName);
2 ✔
1855
  if (!confirmPathInStore(newFile)) {
2 ✔
1856
    return;
1857
  }
1858
  QtPassSettings::getPass()->Move(file, newFile, false);
3 ✔
1859
}
1860

1861
void MainWindow::copySelectionOrPassword() {
1 ✔
1862
  QWidget *focus = QApplication::focusWidget();
1 ✔
1863
  // The widget's own copy: a SecretTextBrowser marks what it copies as
1864
  // secret for clipboard managers, as the context menu's Copy does.
1865
  if (auto *text = qobject_cast<QTextEdit *>(focus);
1 ✔
1866
      text != nullptr && text->textCursor().hasSelection()) {
1 ✔
1867
    text->copy();
1 ✔
1868
    return;
1 ✔
1869
  }
1870
  if (auto *label = qobject_cast<QLabel *>(focus);
NEW
1871
      label != nullptr && label->hasSelectedText()) {
×
NEW
1872
    QGuiApplication::clipboard()->setText(label->selectedText());
×
NEW
1873
    return;
×
1874
  }
NEW
1875
  copyPasswordFromTreeview();
×
1876
}
1877

1878
void MainWindow::copyPasswordFromTreeview() {
9 ✔
1879
  QFileInfo fileOrFolder = m_tree->fileInfo(ui->treeView->currentIndex());
9 ✔
1880

1881
  if (fileOrFolder.isFile()) {
9 ✔
1882
    QString file = getFile(ui->treeView->currentIndex(), true);
9 ✔
1883
    // The newest Ctrl+C wins: finishedShow names its file, so the decrypt of
1884
    // an earlier request is simply not this one's.
1885
    m_copyRequestFile = file;
9 ✔
1886
    // This Show repaints the panel as well; see onOtp().
1887
    m_shownFile = file;
9 ✔
1888
    QtPassSettings::getPass()->Show(file);
18 ✔
1889
  }
1890
}
9 ✔
1891

1892
void MainWindow::passwordFromFileToClipboard(const QString &text,
28 ✔
1893
                                             const QString &file) {
1894
  if (m_copyRequestFile.isEmpty() || file != m_copyRequestFile) {
28 ✔
1895
    return;
23 ✔
1896
  }
1897
  m_copyRequestFile.clear();
8 ✔
1898
  // The first line, without a list of every line (an entry can expand into
1899
  // millions of them), and without the "\r" of a CRLF line end, as the
1900
  // password row and "Always copy" have it.
1901
  const QString first = FileContent::passwordLine(text);
8 ✔
1902
  // A `pass otp insert` entry's first line is the otpauth:// URI carrying the
1903
  // TOTP seed, and an OTP field holding a seed there is the same; copying it
1904
  // would leak 2FA material. Matches the display path
1905
  // (FileContent::getPasswordForDisplay / PasswordDisplayPanel).
1906
  if (FileContent::isOtpPasswordLine(first)) {
8 ✔
1907
    flashText(tr("This entry holds an OTP secret, not a password"), true);
6 ✔
1908
    return;
1909
  }
1910
  m_qtPass->clipboard().copyText(first);
5 ✔
1911
}
1912

1913
void MainWindow::showStatusMessage(const QString &msg, int timeout) {
26 ✔
1914
  ui->statusBar->showMessage(msg, timeout);
26 ✔
1915
}
26 ✔
1916

1917
void MainWindow::reencryptPath(const QString &dir) {
3 ✔
1918
  QDir checkDir(dir);
3 ✔
1919
  if (!checkDir.exists()) {
3 ✔
1920
    PlainMessageBox::critical(this, tr("Error"),
2 ✔
1921
                              tr("Directory does not exist: %1").arg(dir));
2 ✔
1922
    return;
1 ✔
1923
  }
1924
  if (refuseLinkedFolder(dir)) {
2 ✔
1925
    return;
1926
  }
1927

1928
  const bool yes = PlainMessageBox::askYes(
2 ✔
1929
      this, tr("Re-encrypt passwords"),
2 ✔
1930
      tr("Re-encrypt all passwords in %1?\n\n"
2 ✔
1931
         "This will re-encrypt ALL password files in this folder "
1932
         "using the current recipients defined in .gpg-id.\n\n"
1933
         "This may rewrite many files and cannot be undone easily.\n\n"
1934
         "Continue?")
1935
          .arg(QDir(dir).dirName()));
4 ✔
1936

1937
  if (!yes)
2 ✔
1938
    return;
1939

1940
  // Disable now; the asynchronous startReencryptPath signal re-runs this
1941
  // harmlessly.
1942
  startReencryptPath();
1 ✔
1943

1944
  // Under the current profile's settings: with the pass backend active, the
1945
  // native one is not re-initialised on a profile switch.
1946
  QtPassSettings::getImitatePass()->reencryptPath(
2 ✔
1947
      QDir::cleanPath(QDir(dir).absolutePath()), QtPassSettings::load());
2 ✔
1948
}
3 ✔
1949

1950
// Idempotent: reencryptPath() calls it before ImitatePass emits the signal.
1951
void MainWindow::startReencryptPath() {
6 ✔
1952
  m_reencryptRunning = true;
6 ✔
1953
  setUiElementsEnabled(false);
6 ✔
1954
  // The worker always ends with endReencryptPath(), and Cancel is available
1955
  // throughout, so the generic watchdog is not needed for this operation.
1956
  m_uiWatchdog.stop();
6 ✔
1957
  ui->treeView->setDisabled(true);
6 ✔
1958
  if (m_reencryptProgress)
6 ✔
1959
    return;
1960
  auto *progress = new QProgressDialog(tr("Re-encrypting passwords..."),
4 ✔
1961
                                       tr("Cancel"), 0, 0, this);
8 ✔
1962
  progress->setWindowTitle(tr("Re-encrypt passwords"));
4 ✔
1963
  progress->setWindowModality(Qt::WindowModal);
4 ✔
1964
  progress->setAutoClose(false);
4 ✔
1965
  progress->setAutoReset(false);
4 ✔
1966
  progress->setMinimumDuration(0);
4 ✔
1967
  connect(progress, &QProgressDialog::canceled, this, [this]() {
4 ✔
1968
    QtPassSettings::getImitatePass()->cancelReencryptPath();
1 ✔
1969
    showStatusMessage(tr("Cancelling re-encryption"), 5000);
1 ✔
1970
  });
1 ✔
1971
  m_reencryptProgress = progress;
1972
  progress->show();
4 ✔
1973
}
1974

1975
void MainWindow::reencryptProgress(int current, int total) {
5 ✔
1976
  if (!m_reencryptProgress)
5 ✔
1977
    return;
1978
  m_reencryptProgress->setMaximum(total);
4 ✔
1979
  m_reencryptProgress->setLabelText(
4 ✔
1980
      tr("Re-encrypting passwords: %1 of %2").arg(current).arg(total));
8 ✔
1981
  // On a modal dialog setValue() runs processEvents(), which can deliver
1982
  // endReencryptPath() and reset m_reencryptProgress: keep this last.
1983
  m_reencryptProgress->setValue(current);
4 ✔
1984
}
1985

1986
void MainWindow::endReencryptPath() {
4 ✔
1987
  m_reencryptRunning = false;
4 ✔
1988
  if (m_reencryptProgress) {
4 ✔
1989
    m_reencryptProgress->hide();
4 ✔
1990
    m_reencryptProgress->deleteLater();
4 ✔
1991
    m_reencryptProgress = nullptr;
1992
  }
1993
  setUiElementsEnabled(true);
4 ✔
1994
}
4 ✔
1995

1996
void MainWindow::exportPublicKey() {
3 ✔
1997
  const AppSettings s = QtPassSettings::load();
3 ✔
1998
  const QString identity = s.passSigningKey;
1999
  if (identity.isEmpty()) {
3 ✔
2000
    QMessageBox::information(
2 ✔
2001
        this, tr("Export public key"),
1 ✔
UNCOV
2002
        tr("<h3>Export your public key</h3>"
×
2003
           "<p>No signing key is configured. Set one in QtPass Settings "
2004
           "&gt; GPG keys, or run this in a terminal:</p>"
2005
           "<pre>gpg --armor --export --output my_key.asc &lt;your-key-id"
2006
           "&gt;</pre>"
2007
           "<p>Then send the file to your teammates.</p>"));
2008
    return;
1 ✔
2009
  }
2010
  QString gpgExe = s.gpgExecutable;
2011
  if (gpgExe.isEmpty()) {
2 ✔
UNCOV
2012
    gpgExe = QStringLiteral("gpg");
×
2013
  }
2014
  QStringList args = {"--armor", "--export"};
10 ✔
2015
  args.append(identity.split(' ', Qt::SkipEmptyParts));
2 ✔
2016
  QString stdOut;
2 ✔
2017
  QString stdErr;
2 ✔
2018
  int exitCode = Executor::executeBlocking(gpgExe, args, &stdOut, &stdErr);
2 ✔
2019
  if (exitCode != 0 || stdOut.isEmpty()) {
2 ✔
2020
    PlainMessageBox::warning(this, tr("Export public key"),
2 ✔
2021
                             tr("Could not export public key for %1.\n\n%2")
1 ✔
2022
                                 .arg(identity, stdErr.isEmpty()
2 ✔
2023
                                                    ? tr("No output from gpg.")
2 ✔
2024
                                                    : stdErr));
2025
    return;
2026
  }
2027
  ExportPublicKeyDialog dialog(identity, stdOut, this);
1 ✔
2028
  dialog.exec();
1 ✔
2029
}
4 ✔
2030

2031
// UsersDialog only ticks keys already in the keyring; importing a foreign
2032
// key still has to happen via gpg (or QtPass settings) first.
2033
void MainWindow::addRecipient(const QString &dir) {
2 ✔
2034
  if (refuseLinkedFolder(dir)) {
2 ✔
2035
    return;
1 ✔
2036
  }
2037
  UsersDialog d(QtPassSettings::getPass(), QtPassSettings::load(), dir, this);
1 ✔
2038
  d.exec();
1 ✔
2039
}
1 ✔
2040

2041
// A tree-picked folder that is, or lies behind, a symlink or junction is not
2042
// a folder of the store. The store root itself may be a link (a synced
2043
// folder); that is configuration, not a tree pick.
2044
auto MainWindow::refuseLinkedFolder(const QString &dir) -> bool {
17 ✔
2045
  if (!Util::isUnderLink(dir, QtPassSettings::load().passStore)) {
17 ✔
2046
    return false;
2047
  }
2048
  PlainMessageBox::critical(
4 ✔
2049
      this, tr("Not a folder of the store"),
4 ✔
2050
      tr("%1 is, or lies behind, a symbolic link or junction. What that "
4 ✔
2051
         "points to is not part of the password store and is left alone.")
2052
          .arg(QDir::toNativeSeparators(QDir::cleanPath(dir))));
8 ✔
2053
  return true;
4 ✔
2054
}
2055

2056
void MainWindow::showShareHelp() {
1 ✔
2057
  QMessageBox::information(
2 ✔
2058
      this, tr("Sharing passwords with GPG"),
1 ✔
2059
      tr("<h3>Sharing passwords with GPG</h3>"
1 ✔
2060
         "<p>To share passwords with other users:</p>"
2061
         "<ol>"
2062
         "<li><b>Export your public key</b> and send it to teammates</li>"
2063
         "<li><b>Import teammates' public keys</b> into your GPG keyring</li>"
2064
         "<li><b>Re-encrypt passwords</b> so all recipients can decrypt "
2065
         "them</li>"
2066
         "</ol>"
2067
         "<p>Only people who have a matching secret key can decrypt the "
2068
         "passwords.</p>"
2069
         "<p><b>Tip:</b> Use the same GPG key for all shared folders.</p>"
2070
         "<p>See the FAQ for more details.</p>"));
2071
}
1 ✔
2072

2073
void MainWindow::updateGitButtonVisibility(bool uiEnabled) {
373 ✔
2074
  const AppSettings s = QtPassSettings::load();
373 ✔
2075
  // Without Git there is nothing to push or pull, ever: the buttons go, not
2076
  // grey out. While an operation runs they stay and are disabled.
2077
  const bool usable =
2078
      s.useGit && !(s.gitExecutable.isEmpty() && s.passExecutable.isEmpty());
373 ✔
2079
  ui->actionPush->setVisible(usable);
373 ✔
2080
  ui->actionUpdate->setVisible(usable);
373 ✔
2081
  // The separator in front of them would otherwise sit next to the next one.
2082
  const QList<QAction *> actions = ui->toolBar->actions();
373 ✔
2083
  const qsizetype at = actions.indexOf(ui->actionPush);
373 ✔
2084
  if (at > 0 && actions.at(at - 1)->isSeparator()) {
373 ✔
2085
    actions.at(at - 1)->setVisible(usable);
373 ✔
2086
  }
2087
  enableGitButtons(usable && uiEnabled);
373 ✔
2088
}
373 ✔
2089

2090
void MainWindow::updateOtpButtonVisibility(bool uiEnabled) {
373 ✔
2091
  // No platform gating: codes are generated in-process. Visible but disabled
2092
  // when OTP is off: the panel never shows an OTP field (a secret), so hiding
2093
  // this too would leave no trace of the feature. Honour uiEnabled, or the
2094
  // user can stack Show calls while a decrypt is in flight.
2095
  ui->actionOtp->setVisible(true);
373 ✔
2096
  ui->actionOtp->setEnabled(QtPassSettings::isUseOtp() && uiEnabled);
386 ✔
2097
}
373 ✔
2098

2099
void MainWindow::updateGrepButtonVisibility() {
168 ✔
2100
  const bool enabled = QtPassSettings::isUseGrepSearch();
168 ✔
2101
  ui->grepButton->setVisible(enabled);
168 ✔
2102
  ui->grepCaseButton->setVisible(enabled);
168 ✔
2103
  if (!enabled && m_grep.inGrepMode()) {
168 ✔
2104
    ui->grepButton->setChecked(false);
1 ✔
2105
  }
2106
}
168 ✔
2107

2108
void MainWindow::enableGitButtons(const bool &state) {
373 ✔
2109
  ui->actionPush->setEnabled(state);
373 ✔
2110
  ui->actionUpdate->setEnabled(state);
373 ✔
2111
}
373 ✔
2112

2113
void MainWindow::critical(const QString &title, const QString &msg) {
3 ✔
2114
  // Pass's messages quote store paths; see PlainMessageBox.
2115
  PlainMessageBox::critical(this, title, msg);
3 ✔
2116
}
3 ✔
2117

2118
void MainWindow::onProcessOutput(const QString &output, bool isError,
7 ✔
2119
                                 Enums::PROCESS pid) {
2120
  if (!QtPassSettings::isShowProcessOutput()) {
7 ✔
2121
    return;
2122
  }
2123
  m_processOutput->append(output, isError,
6 ✔
2124
                          ProcessOutputPanel::processName(pid));
12 ✔
2125
}
2126

2127
void MainWindow::updateProcessOutputVisibility() {
3 ✔
2128
  // The action's toggled handler shows or hides the dock.
2129
  ui->actionShowProcessOutput->setChecked(
3 ✔
2130
      QtPassSettings::isShowProcessOutput());
3 ✔
2131
  m_processOutput->setVisible(QtPassSettings::isShowProcessOutput());
3 ✔
2132
}
3 ✔
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