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

IJHack / QtPass / 24250518166

10 Apr 2026 03:26PM UTC coverage: 20.884%. First build
24250518166

Pull #967

github

web-flow
Merge 9f5798cf5 into cac8860d3
Pull Request #967: fix: fix transparent context menu in dark mode

0 of 7 new or added lines in 1 file covered. (0.0%)

1106 of 5296 relevant lines covered (20.88%)

7.75 hits per line

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

0.0
/src/mainwindow.cpp
1
// SPDX-FileCopyrightText: 2014 Anne Jan Brouwer
2
// SPDX-License-Identifier: GPL-3.0-or-later
3
#include "mainwindow.h"
4

5
#ifdef QT_DEBUG
6
#include "debughelper.h"
7
#endif
8

9
#include "configdialog.h"
10
#include "filecontent.h"
11
#include "passworddialog.h"
12
#include "qpushbuttonasqrcode.h"
13
#include "qpushbuttonshowpassword.h"
14
#include "qpushbuttonwithclipboard.h"
15
#include "qtpass.h"
16
#include "qtpasssettings.h"
17
#include "trayicon.h"
18
#include "ui_mainwindow.h"
19
#include "usersdialog.h"
20
#include "util.h"
21
#include <QCloseEvent>
22
#include <QDesktopServices>
23
#include <QDialog>
24
#include <QDirIterator>
25
#include <QFileInfo>
26
#include <QInputDialog>
27
#include <QLabel>
28
#include <QMenu>
29
#include <QMessageBox>
30
#include <QShortcut>
31
#include <QTimer>
32
#include <utility>
33

34
/**
35
 * @brief MainWindow::MainWindow handles all of the main functionality and also
36
 * the main window.
37
 * @param searchText for searching from cli
38
 * @param parent pointer
39
 */
40
MainWindow::MainWindow(const QString &searchText, QWidget *parent)
×
41
    : QMainWindow(parent), ui(new Ui::MainWindow), keygen(nullptr),
×
42
      tray(nullptr) {
×
43
#ifdef __APPLE__
44
  // extra treatment for mac os
45
  // see http://doc.qt.io/qt-5/qkeysequence.html#qt_set_sequence_auto_mnemonic
46
  qt_set_sequence_auto_mnemonic(true);
47
#endif
48
  ui->setupUi(this);
×
49

50
  m_qtPass = new QtPass(this);
×
51

52
  // register shortcut ctrl/cmd + Q to close the main window
53
  new QShortcut(QKeySequence(Qt::CTRL | Qt::Key_Q), this, SLOT(close()));
×
54
  // register shortcut ctrl/cmd + C to copy the currently selected password
55
  new QShortcut(QKeySequence(QKeySequence::StandardKey::Copy), this,
×
56
                SLOT(copyPasswordFromTreeview()));
×
57

58
  model.setNameFilters(QStringList() << "*.gpg");
×
59
  model.setNameFilterDisables(false);
×
60

61
  /*
62
   * I added this to solve Windows bug but now on GNU/Linux the main folder,
63
   * if hidden, disappear
64
   *
65
   * model.setFilter(QDir::NoDot);
66
   */
67

68
  QString passStore = QtPassSettings::getPassStore(Util::findPasswordStore());
×
69

70
  QModelIndex rootDir = model.setRootPath(passStore);
×
71
  model.fetchMore(rootDir);
×
72

73
  proxyModel.setModelAndStore(&model, passStore);
×
74
  selectionModel.reset(new QItemSelectionModel(&proxyModel));
×
75

76
  ui->treeView->setModel(&proxyModel);
×
77
  ui->treeView->setRootIndex(proxyModel.mapFromSource(rootDir));
×
78
  ui->treeView->setColumnHidden(1, true);
×
79
  ui->treeView->setColumnHidden(2, true);
×
80
  ui->treeView->setColumnHidden(3, true);
×
81
  ui->treeView->setHeaderHidden(true);
×
82
  ui->treeView->setIndentation(15);
×
83
  ui->treeView->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
×
84
  ui->treeView->setContextMenuPolicy(Qt::CustomContextMenu);
×
85
  ui->treeView->header()->setSectionResizeMode(0, QHeaderView::Stretch);
×
86
  ui->treeView->sortByColumn(0, Qt::AscendingOrder);
×
87
  connect(ui->treeView, &QWidget::customContextMenuRequested, this,
×
88
          &MainWindow::showContextMenu);
×
89
  connect(ui->treeView, &DeselectableTreeView::emptyClicked, this,
×
90
          &MainWindow::deselect);
×
91

92
  if (QtPassSettings::isUseMonospace()) {
×
93
    QFont monospace("Monospace");
×
94
    monospace.setStyleHint(QFont::Monospace);
×
95
    ui->textBrowser->setFont(monospace);
×
96
  }
×
97
  if (QtPassSettings::isNoLineWrapping()) {
×
98
    ui->textBrowser->setLineWrapMode(QTextBrowser::NoWrap);
×
99
  }
100
  ui->textBrowser->setOpenExternalLinks(true);
×
101
  ui->textBrowser->setContextMenuPolicy(Qt::CustomContextMenu);
×
102
  connect(ui->textBrowser, &QWidget::customContextMenuRequested, this,
×
103
          &MainWindow::showBrowserContextMenu);
×
104

105
  updateProfileBox();
×
106

107
  QtPassSettings::getPass()->updateEnv();
×
108
  clearPanelTimer.setInterval(MS_PER_SECOND *
×
109
                              QtPassSettings::getAutoclearPanelSeconds());
×
110
  clearPanelTimer.setSingleShot(true);
×
111
  connect(&clearPanelTimer, &QTimer::timeout, this, [this]() { clearPanel(); });
×
112

113
  searchTimer.setInterval(350);
×
114
  searchTimer.setSingleShot(true);
×
115

116
  connect(&searchTimer, &QTimer::timeout, this, &MainWindow::onTimeoutSearch);
×
117

118
  initToolBarButtons();
×
119
  initStatusBar();
×
120

121
  ui->lineEdit->setClearButtonEnabled(true);
×
122

123
  setUiElementsEnabled(true);
×
124

125
  QTimer::singleShot(10, this, SLOT(focusInput()));
126

127
  ui->lineEdit->setText(searchText);
×
128

129
  if (!m_qtPass->init()) {
×
130
    // no working config so this should just quit
131
    QApplication::quit();
×
132
  }
133
}
×
134

135
MainWindow::~MainWindow() { delete m_qtPass; }
×
136

137
/**
138
 * @brief MainWindow::focusInput selects any text (if applicable) in the search
139
 * box and sets focus to it. Allows for easy searching, called at application
140
 * start and when receiving empty message in MainWindow::messageAvailable when
141
 * compiled with SINGLE_APP=1 (default).
142
 */
143
void MainWindow::focusInput() {
×
144
  ui->lineEdit->selectAll();
×
145
  ui->lineEdit->setFocus();
×
146
}
×
147

148
/**
149
 * @brief MainWindow::changeEvent sets focus to the search box
150
 * @param event
151
 */
152
void MainWindow::changeEvent(QEvent *event) {
×
153
  QWidget::changeEvent(event);
×
154
  if (event->type() == QEvent::ActivationChange) {
×
155
    if (isActiveWindow()) {
×
156
      focusInput();
×
157
    }
158
  }
159
}
×
160

161
/**
162
 * @brief MainWindow::initToolBarButtons init main ToolBar and connect actions
163
 */
164
void MainWindow::initToolBarButtons() {
×
165
  connect(ui->actionAddPassword, &QAction::triggered, this,
×
166
          &MainWindow::addPassword);
×
167
  connect(ui->actionAddFolder, &QAction::triggered, this,
×
168
          &MainWindow::addFolder);
×
169
  connect(ui->actionEdit, &QAction::triggered, this, &MainWindow::onEdit);
×
170
  connect(ui->actionDelete, &QAction::triggered, this, &MainWindow::onDelete);
×
171
  connect(ui->actionPush, &QAction::triggered, this, &MainWindow::onPush);
×
172
  connect(ui->actionUpdate, &QAction::triggered, this, &MainWindow::onUpdate);
×
173
  connect(ui->actionUsers, &QAction::triggered, this, &MainWindow::onUsers);
×
174
  connect(ui->actionConfig, &QAction::triggered, this, &MainWindow::onConfig);
×
175
  connect(ui->actionOtp, &QAction::triggered, this, &MainWindow::onOtp);
×
176

177
  ui->actionAddPassword->setIcon(
×
178
      QIcon::fromTheme("document-new", QIcon(":/icons/document-new.svg")));
×
179
  ui->actionAddFolder->setIcon(
×
180
      QIcon::fromTheme("folder-new", QIcon(":/icons/folder-new.svg")));
×
181
  ui->actionEdit->setIcon(QIcon::fromTheme(
×
182
      "document-properties", QIcon(":/icons/document-properties.svg")));
×
183
  ui->actionDelete->setIcon(
×
184
      QIcon::fromTheme("edit-delete", QIcon(":/icons/edit-delete.svg")));
×
185
  ui->actionPush->setIcon(
×
186
      QIcon::fromTheme("go-up", QIcon(":/icons/go-top.svg")));
×
187
  ui->actionUpdate->setIcon(
×
188
      QIcon::fromTheme("go-down", QIcon(":/icons/go-bottom.svg")));
×
189
  ui->actionUsers->setIcon(QIcon::fromTheme(
×
190
      "x-office-address-book", QIcon(":/icons/x-office-address-book.svg")));
×
191
  ui->actionConfig->setIcon(QIcon::fromTheme(
×
192
      "applications-system", QIcon(":/icons/applications-system.svg")));
×
193
}
×
194

195
/**
196
 * @brief MainWindow::initStatusBar init statusBar with default message and logo
197
 */
198
void MainWindow::initStatusBar() {
×
199
  ui->statusBar->showMessage(tr("Welcome to QtPass %1").arg(VERSION), 2000);
×
200

201
  QPixmap logo = QPixmap::fromImage(QImage(":/artwork/icon.svg"))
×
202
                     .scaledToHeight(statusBar()->height());
×
203
  auto *logoApp = new QLabel(statusBar());
×
204
  logoApp->setPixmap(logo);
×
205
  statusBar()->addPermanentWidget(logoApp);
×
206
}
×
207

208
auto MainWindow::getCurrentTreeViewIndex() -> QModelIndex {
×
209
  return ui->treeView->currentIndex();
×
210
}
211

212
void MainWindow::cleanKeygenDialog() {
×
213
  this->keygen->close();
×
214
  this->keygen = nullptr;
×
215
}
×
216

217
/**
218
 * @brief Displays the given text in the main window text browser, optionally
219
 * marking it as an error and/or rendering it as HTML.
220
 * @example
221
 * MainWindow window;
222
 * window.flashText("Operation completed.", false, false);
223
 *
224
 * @param const QString &text - The text content to display.
225
 * @param const bool isError - If true, sets the text color to red before
226
 * displaying the text.
227
 * @param const bool isHtml - If true, treats the text as HTML and appends it to
228
 * the existing HTML content.
229
 * @return void - No return value.
230
 */
231
void MainWindow::flashText(const QString &text, const bool isError,
×
232
                           const bool isHtml) {
233
  if (isError) {
×
234
    ui->textBrowser->setTextColor(Qt::red);
×
235
  }
236

237
  if (isHtml) {
×
238
    QString _text = text;
239
    if (!ui->textBrowser->toPlainText().isEmpty()) {
×
240
      _text = ui->textBrowser->toHtml() + _text;
×
241
    }
242
    ui->textBrowser->setHtml(_text);
×
243
  } else {
244
    ui->textBrowser->setText(text);
×
245
  }
246
}
×
247

248
/**
249
 * @brief MainWindow::config pops up the configuration screen and handles all
250
 * inter-window communication
251
 */
252
void MainWindow::applyTextBrowserSettings() {
×
253
  if (QtPassSettings::isUseMonospace()) {
×
254
    QFont monospace("Monospace");
×
255
    monospace.setStyleHint(QFont::Monospace);
×
256
    ui->textBrowser->setFont(monospace);
×
257
  } else {
×
258
    ui->textBrowser->setFont(QFont());
×
259
  }
260

261
  if (QtPassSettings::isNoLineWrapping()) {
×
262
    ui->textBrowser->setLineWrapMode(QTextBrowser::NoWrap);
×
263
  } else {
264
    ui->textBrowser->setLineWrapMode(QTextBrowser::WidgetWidth);
×
265
  }
266
}
×
267

268
void MainWindow::applyWindowFlagsSettings() {
×
269
  if (QtPassSettings::isAlwaysOnTop()) {
×
270
    Qt::WindowFlags flags = windowFlags();
271
    this->setWindowFlags(flags | Qt::WindowStaysOnTopHint);
×
272
  } else {
273
    this->setWindowFlags(Qt::Window);
×
274
  }
275
  this->show();
×
276
}
×
277

278
/**
279
 * @brief Opens and processes the application configuration dialog, then applies
280
 * any accepted settings.
281
 * @example
282
 * config();
283
 *
284
 * @return void - This function does not return a value.
285
 */
286
void MainWindow::config() {
×
287
  QScopedPointer<ConfigDialog> d(new ConfigDialog(this));
×
288
  d->setModal(true);
×
289
  // Automatically default to pass if it's available
290
  if (m_qtPass->isFreshStart() &&
×
291
      QFile(QtPassSettings::getPassExecutable()).exists()) {
×
292
    QtPassSettings::setUsePass(true);
×
293
  }
294

295
  if (m_qtPass->isFreshStart()) {
×
296
    d->wizard(); //  does shit
×
297
  }
298
  if (d->exec()) {
×
299
    if (d->result() == QDialog::Accepted) {
×
300
      applyTextBrowserSettings();
×
301
      applyWindowFlagsSettings();
×
302

303
      updateProfileBox();
×
304
      ui->treeView->setRootIndex(proxyModel.mapFromSource(
×
305
          model.setRootPath(QtPassSettings::getPassStore())));
×
306

307
      if (m_qtPass->isFreshStart() && !Util::configIsValid()) {
×
308
        config();
×
309
      }
310
      QtPassSettings::getPass()->updateEnv();
×
311
      clearPanelTimer.setInterval(MS_PER_SECOND *
×
312
                                  QtPassSettings::getAutoclearPanelSeconds());
×
313
      m_qtPass->setClipboardTimer();
×
314

315
      updateGitButtonVisibility();
×
316
      updateOtpButtonVisibility();
×
317
      if (QtPassSettings::isUseTrayIcon() && tray == nullptr) {
×
318
        initTrayIcon();
×
319
      } else if (!QtPassSettings::isUseTrayIcon() && tray != nullptr) {
×
320
        destroyTrayIcon();
×
321
      }
322
    }
323

324
    m_qtPass->setFreshStart(false);
×
325
  }
326
}
×
327

328
/**
329
 * @brief MainWindow::onUpdate do a git pull
330
 */
331
void MainWindow::onUpdate(bool block) {
×
332
  ui->statusBar->showMessage(tr("Updating password-store"), 2000);
×
333
  if (block) {
×
334
    QtPassSettings::getPass()->GitPull_b();
×
335
  } else {
336
    QtPassSettings::getPass()->GitPull();
×
337
  }
338
}
×
339

340
/**
341
 * @brief MainWindow::onPush do a git push
342
 */
343
void MainWindow::onPush() {
×
344
  if (QtPassSettings::isUseGit()) {
×
345
    ui->statusBar->showMessage(tr("Updating password-store"), 2000);
×
346
    QtPassSettings::getPass()->GitPush();
×
347
  }
348
}
×
349

350
/**
351
 * @brief MainWindow::getFile get the selected file path
352
 * @param index
353
 * @param forPass returns relative path without '.gpg' extension
354
 * @return path
355
 * @return
356
 */
357
auto MainWindow::getFile(const QModelIndex &index, bool forPass) -> QString {
×
358
  if (!index.isValid() ||
×
359
      !model.fileInfo(proxyModel.mapToSource(index)).isFile()) {
×
360
    return {};
361
  }
362
  QString filePath = model.filePath(proxyModel.mapToSource(index));
×
363
  if (forPass) {
×
364
    filePath = QDir(QtPassSettings::getPassStore()).relativeFilePath(filePath);
×
365
    filePath.replace(Util::endsWithGpg(), "");
×
366
  }
367
  return filePath;
368
}
369

370
/**
371
 * @brief MainWindow::on_treeView_clicked read the selected password file
372
 * @param index
373
 */
374
void MainWindow::on_treeView_clicked(const QModelIndex &index) {
×
375
  bool cleared = ui->treeView->currentIndex().flags() == Qt::NoItemFlags;
×
376
  currentDir =
377
      Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel);
×
378
  // Clear any previously cached clipped text before showing new password
379
  m_qtPass->clearClippedText();
×
380
  QString file = getFile(index, true);
×
381
  ui->passwordName->setText(getFile(index, true));
×
382
  if (!file.isEmpty() && !cleared) {
×
383
    QtPassSettings::getPass()->Show(file);
×
384
  } else {
385
    clearPanel(false);
×
386
    ui->actionEdit->setEnabled(false);
×
387
    ui->actionDelete->setEnabled(true);
×
388
  }
389
}
×
390

391
/**
392
 * @brief MainWindow::on_treeView_doubleClicked when doubleclicked on
393
 * TreeViewItem, open the edit Window
394
 * @param index
395
 */
396
void MainWindow::on_treeView_doubleClicked(const QModelIndex &index) {
×
397
  QFileInfo fileOrFolder =
398
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
399

400
  if (fileOrFolder.isFile()) {
×
401
    editPassword(getFile(index, true));
×
402
  }
403
}
×
404

405
/**
406
 * @brief MainWindow::deselect clear the selection, password and copy buffer
407
 */
408
void MainWindow::deselect() {
×
409
  currentDir = "";
×
410
  m_qtPass->clearClipboard();
×
411
  ui->treeView->clearSelection();
×
412
  ui->actionEdit->setEnabled(false);
×
413
  ui->actionDelete->setEnabled(false);
×
414
  ui->passwordName->setText("");
×
415
  clearPanel(false);
×
416
}
×
417

418
void MainWindow::executeWrapperStarted() {
×
419
  clearTemplateWidgets();
×
420
  ui->textBrowser->clear();
×
421
  setUiElementsEnabled(false);
×
422
  clearPanelTimer.stop();
×
423
}
×
424

425
/**
426
 * @brief Handles displaying parsed password entry content in the main window.
427
 * @example
428
 * void result = MainWindow::passShowHandler(p_output);
429
 * // Updates the UI with parsed fields and emits
430
 * passShowHandlerFinished(output)
431
 *
432
 * @param p_output - The raw output text containing the password entry data.
433
 * @return void - This function does not return a value.
434
 */
435
void MainWindow::passShowHandler(const QString &p_output) {
×
436
  QStringList templ = QtPassSettings::isUseTemplate()
×
437
                          ? QtPassSettings::getPassTemplate().split("\n")
×
438
                          : QStringList();
×
439
  bool allFields =
440
      QtPassSettings::isUseTemplate() && QtPassSettings::isTemplateAllFields();
×
441
  FileContent fileContent = FileContent::parse(p_output, templ, allFields);
×
442
  QString output = p_output;
443
  QString password = fileContent.getPassword();
×
444

445
  // set clipped text
446
  m_qtPass->setClippedText(password, p_output);
×
447

448
  // first clear the current view:
449
  clearTemplateWidgets();
×
450

451
  // show what is needed:
452
  if (QtPassSettings::isHideContent()) {
×
453
    output = "***" + tr("Content hidden") + "***";
×
454
  } else if (!QtPassSettings::isDisplayAsIs()) {
×
455
    if (!password.isEmpty()) {
×
456
      // set the password, it is hidden if needed in addToGridLayout
457
      addToGridLayout(0, tr("Password"), password);
×
458
    }
459

460
    NamedValues namedValues = fileContent.getNamedValues();
×
461
    for (int j = 0; j < namedValues.length(); ++j) {
×
462
      const NamedValue &nv = namedValues.at(j);
463
      addToGridLayout(j + 1, nv.name, nv.value);
×
464
    }
465
    if (ui->gridLayout->count() == 0) {
×
466
      ui->verticalLayoutPassword->setSpacing(0);
×
467
    } else {
468
      ui->verticalLayoutPassword->setSpacing(6);
×
469
    }
470

471
    output = fileContent.getRemainingDataForDisplay();
×
472
  }
473

474
  if (QtPassSettings::isUseAutoclearPanel()) {
×
475
    clearPanelTimer.start();
×
476
  }
477

478
  emit passShowHandlerFinished(output);
×
479
  setUiElementsEnabled(true);
×
480
}
×
481

482
/**
483
 * @brief Handles the OTP output by displaying it, copying it to the clipboard,
484
 * and updating the UI state.
485
 * @example
486
 * void MainWindow::passOtpHandler(const QString &p_output);
487
 *
488
 * @param const QString &p_output - The OTP code text to process; if empty, an
489
 * error message is shown instead.
490
 * @return void - This function does not return a value.
491
 */
492
void MainWindow::passOtpHandler(const QString &p_output) {
×
493
  if (!p_output.isEmpty()) {
×
494
    addToGridLayout(ui->gridLayout->count() + 1, tr("OTP Code"), p_output);
×
495
    m_qtPass->copyTextToClipboard(p_output);
×
496
    showStatusMessage(tr("OTP code copied to clipboard"));
×
497
  } else {
498
    flashText(tr("No OTP code found in this password entry"), true);
×
499
  }
500
  if (QtPassSettings::isUseAutoclearPanel()) {
×
501
    clearPanelTimer.start();
×
502
  }
503
  setUiElementsEnabled(true);
×
504
}
×
505

506
/**
507
 * @brief MainWindow::clearPanel hide the information from shoulder surfers
508
 */
509
void MainWindow::clearPanel(bool notify) {
×
510
  while (ui->gridLayout->count() > 0) {
×
511
    QLayoutItem *item = ui->gridLayout->takeAt(0);
×
512
    delete item->widget();
×
513
    delete item;
×
514
  }
515
  if (notify) {
×
516
    QString output = "***" + tr("Password and Content hidden") + "***";
×
517
    ui->textBrowser->setHtml(output);
×
518
  } else {
519
    ui->textBrowser->setHtml("");
×
520
  }
521
}
×
522

523
/**
524
 * @brief MainWindow::setUiElementsEnabled enable or disable the relevant UI
525
 * elements
526
 * @param state
527
 */
528
void MainWindow::setUiElementsEnabled(bool state) {
×
529
  ui->treeView->setEnabled(state);
×
530
  ui->lineEdit->setEnabled(state);
×
531
  ui->lineEdit->installEventFilter(this);
×
532
  ui->actionAddPassword->setEnabled(state);
×
533
  ui->actionAddFolder->setEnabled(state);
×
534
  ui->actionUsers->setEnabled(state);
×
535
  ui->actionConfig->setEnabled(state);
×
536
  // is a file selected?
537
  state &= ui->treeView->currentIndex().isValid();
×
538
  ui->actionDelete->setEnabled(state);
×
539
  ui->actionEdit->setEnabled(state);
×
540
  updateGitButtonVisibility();
×
541
  updateOtpButtonVisibility();
×
542
}
×
543

544
/**
545
 * @brief Restores the main window geometry, state, position, size, and
546
 * tray/icon settings from saved application settings.
547
 * @example
548
 * MainWindow window;
549
 * window.restoreWindow();
550
 *
551
 * @return void - This function does not return a value.
552
 */
553
void MainWindow::restoreWindow() {
×
554
  QByteArray geometry = QtPassSettings::getGeometry(saveGeometry());
×
555
  restoreGeometry(geometry);
×
556
  QByteArray savestate = QtPassSettings::getSavestate(saveState());
×
557
  restoreState(savestate);
×
558
  QPoint position = QtPassSettings::getPos(pos());
×
559
  move(position);
×
560
  QSize newSize = QtPassSettings::getSize(size());
×
561
  resize(newSize);
×
562
  if (QtPassSettings::isMaximized(isMaximized())) {
×
563
    showMaximized();
×
564
  }
565

566
  if (QtPassSettings::isAlwaysOnTop()) {
×
567
    Qt::WindowFlags flags = windowFlags();
568
    setWindowFlags(flags | Qt::WindowStaysOnTopHint);
×
569
    show();
×
570
  }
571

572
  if (QtPassSettings::isUseTrayIcon() && tray == nullptr) {
×
573
    initTrayIcon();
×
574
    if (QtPassSettings::isStartMinimized()) {
×
575
      // since we are still in constructor, can't directly hide
576
      QTimer::singleShot(10, this, SLOT(hide()));
×
577
    }
578
  } else if (!QtPassSettings::isUseTrayIcon() && tray != nullptr) {
×
579
    destroyTrayIcon();
×
580
  }
581
}
×
582

583
/**
584
 * @brief MainWindow::on_configButton_clicked run Mainwindow::config
585
 */
586
void MainWindow::onConfig() { config(); }
×
587

588
/**
589
 * @brief Executes when the string in the search box changes, collapses the
590
 * TreeView
591
 * @param arg1
592
 */
593
void MainWindow::on_lineEdit_textChanged(const QString &arg1) {
×
594
  ui->statusBar->showMessage(tr("Looking for: %1").arg(arg1), 1000);
×
595
  ui->treeView->expandAll();
×
596
  clearPanel(false);
×
597
  ui->passwordName->setText("");
×
598
  ui->actionEdit->setEnabled(false);
×
599
  ui->actionDelete->setEnabled(false);
×
600
  searchTimer.start();
×
601
}
×
602

603
/**
604
 * @brief MainWindow::onTimeoutSearch Fired when search is finished or too much
605
 * time from two keypresses is elapsed
606
 */
607
void MainWindow::onTimeoutSearch() {
×
608
  QString query = ui->lineEdit->text();
×
609

610
  if (query.isEmpty()) {
×
611
    ui->treeView->collapseAll();
×
612
    deselect();
×
613
  }
614

615
  query.replace(QStringLiteral(" "), ".*");
×
616
  QRegularExpression regExp(query, QRegularExpression::CaseInsensitiveOption);
×
617
  proxyModel.setFilterRegularExpression(regExp);
×
618
  ui->treeView->setRootIndex(proxyModel.mapFromSource(
×
619
      model.setRootPath(QtPassSettings::getPassStore())));
×
620

621
  if (proxyModel.rowCount() > 0 && !query.isEmpty()) {
×
622
    selectFirstFile();
×
623
  } else {
624
    ui->actionEdit->setEnabled(false);
×
625
    ui->actionDelete->setEnabled(false);
×
626
  }
627
}
×
628

629
/**
630
 * @brief MainWindow::on_lineEdit_returnPressed get searching
631
 *
632
 * Select the first possible file in the tree
633
 */
634
void MainWindow::on_lineEdit_returnPressed() {
×
635
#ifdef QT_DEBUG
636
  dbg() << "on_lineEdit_returnPressed" << proxyModel.rowCount();
637
#endif
638

639
  if (proxyModel.rowCount() > 0) {
×
640
    selectFirstFile();
×
641
    on_treeView_clicked(ui->treeView->currentIndex());
×
642
  }
643
}
×
644

645
/**
646
 * @brief MainWindow::selectFirstFile select the first possible file in the
647
 * tree
648
 */
649
void MainWindow::selectFirstFile() {
×
650
  QModelIndex index = proxyModel.mapFromSource(
×
651
      model.setRootPath(QtPassSettings::getPassStore()));
×
652
  index = firstFile(index);
×
653
  ui->treeView->setCurrentIndex(index);
×
654
}
×
655

656
/**
657
 * @brief MainWindow::firstFile return location of first possible file
658
 * @param parentIndex
659
 * @return QModelIndex
660
 */
661
auto MainWindow::firstFile(QModelIndex parentIndex) -> QModelIndex {
×
662
  QModelIndex index = parentIndex;
×
663
  int numRows = proxyModel.rowCount(parentIndex);
×
664
  for (int row = 0; row < numRows; ++row) {
×
665
    index = proxyModel.index(row, 0, parentIndex);
×
666
    if (model.fileInfo(proxyModel.mapToSource(index)).isFile()) {
×
667
      return index;
×
668
    }
669
    if (proxyModel.hasChildren(index)) {
×
670
      return firstFile(index);
×
671
    }
672
  }
673
  return index;
×
674
}
675

676
/**
677
 * @brief MainWindow::setPassword open passworddialog
678
 * @param file which pgp file
679
 * @param isNew insert (not update)
680
 */
681
void MainWindow::setPassword(const QString &file, bool isNew) {
×
682
  PasswordDialog d(file, isNew, this);
×
683

684
  if (!d.exec()) {
×
685
    ui->treeView->setFocus();
×
686
  }
687
}
×
688

689
/**
690
 * @brief MainWindow::addPassword add a new password by showing a
691
 * number of dialogs.
692
 */
693
void MainWindow::addPassword() {
×
694
  bool ok;
695
  QString dir =
696
      Util::getDir(ui->treeView->currentIndex(), true, model, proxyModel);
×
697
  QString file =
698
      QInputDialog::getText(this, tr("New file"),
×
699
                            tr("New password file: \n(Will be placed in %1 )")
×
700
                                .arg(QtPassSettings::getPassStore() +
×
701
                                     Util::getDir(ui->treeView->currentIndex(),
×
702
                                                  true, model, proxyModel)),
703
                            QLineEdit::Normal, "", &ok);
×
704
  if (!ok || file.isEmpty()) {
×
705
    return;
706
  }
707
  file = dir + file;
×
708
  setPassword(file);
×
709
}
710

711
/**
712
 * @brief MainWindow::onDelete remove password, if you are
713
 * sure.
714
 */
715
void MainWindow::onDelete() {
×
716
  QModelIndex currentIndex = ui->treeView->currentIndex();
×
717
  if (!currentIndex.isValid()) {
718
    // This fixes https://github.com/IJHack/QtPass/issues/556
719
    // Otherwise the entire password directory would be deleted if
720
    // nothing is selected in the tree view.
721
    return;
×
722
  }
723

724
  QFileInfo fileOrFolder =
725
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
726
  QString file = "";
×
727
  bool isDir = false;
728

729
  if (fileOrFolder.isFile()) {
×
730
    file = getFile(ui->treeView->currentIndex(), true);
×
731
  } else {
732
    file = Util::getDir(ui->treeView->currentIndex(), true, model, proxyModel);
×
733
    isDir = true;
734
  }
735

736
  QString dirMessage = tr(" and the whole content?");
737
  if (isDir) {
×
738
    QDirIterator it(model.rootPath() + QDir::separator() + file,
×
739
                    QDirIterator::Subdirectories);
×
740
    bool okDir = true;
741
    while (it.hasNext() && okDir) {
×
742
      it.next();
×
743
      if (QFileInfo(it.filePath()).isFile()) {
×
744
        if (QFileInfo(it.filePath()).suffix() != "gpg") {
×
745
          okDir = false;
746
          dirMessage = tr(" and the whole content? <br><strong>Attention: "
×
747
                          "there are unexpected files in the given folder, "
748
                          "check them before continue.</strong>");
749
        }
750
      }
751
    }
752
  }
×
753

754
  if (QMessageBox::question(
×
755
          this, isDir ? tr("Delete folder?") : tr("Delete password?"),
×
756
          tr("Are you sure you want to delete %1%2?")
×
757
              .arg(QDir::separator() + file, isDir ? dirMessage : "?"),
×
758
          QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) {
759
    return;
760
  }
761

762
  QtPassSettings::getPass()->Remove(file, isDir);
×
763
}
×
764

765
/**
766
 * @brief MainWindow::onOTP try and generate (selected) OTP code.
767
 */
768
void MainWindow::onOtp() {
×
769
  QString file = getFile(ui->treeView->currentIndex(), true);
×
770
  if (!file.isEmpty()) {
×
771
    if (QtPassSettings::isUseOtp()) {
×
772
      setUiElementsEnabled(false);
×
773
      QtPassSettings::getPass()->OtpGenerate(file);
×
774
    }
775
  } else {
776
    flashText(tr("No password selected for OTP generation"), true);
×
777
  }
778
}
×
779

780
/**
781
 * @brief MainWindow::onEdit try and edit (selected) password.
782
 */
783
void MainWindow::onEdit() {
×
784
  QString file = getFile(ui->treeView->currentIndex(), true);
×
785
  editPassword(file);
×
786
}
×
787

788
/**
789
 * @brief MainWindow::userDialog see MainWindow::onUsers()
790
 * @param dir folder to edit users for.
791
 */
792
void MainWindow::userDialog(const QString &dir) {
×
793
  if (!dir.isEmpty()) {
×
794
    currentDir = dir;
×
795
  }
796
  onUsers();
×
797
}
×
798

799
/**
800
 * @brief MainWindow::onUsers edit users for the current
801
 * folder,
802
 * gets lists and opens UserDialog.
803
 */
804
void MainWindow::onUsers() {
×
805
  QString dir =
806
      currentDir.isEmpty()
807
          ? Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel)
×
808
          : currentDir;
×
809

810
  UsersDialog d(dir, this);
×
811
  if (!d.exec()) {
×
812
    ui->treeView->setFocus();
×
813
  }
814
}
×
815

816
/**
817
 * @brief MainWindow::messageAvailable we have some text/message/search to do.
818
 * @param message
819
 */
820
void MainWindow::messageAvailable(const QString &message) {
×
821
  if (message.isEmpty()) {
×
822
    focusInput();
×
823
  } else {
824
    ui->treeView->expandAll();
×
825
    ui->lineEdit->setText(message);
×
826
    on_lineEdit_returnPressed();
×
827
  }
828
  show();
×
829
  raise();
×
830
}
×
831

832
/**
833
 * @brief MainWindow::generateKeyPair internal gpg keypair generator . .
834
 * @param batch
835
 * @param keygenWindow
836
 */
837
void MainWindow::generateKeyPair(const QString &batch, QDialog *keygenWindow) {
×
838
  keygen = keygenWindow;
×
839
  emit generateGPGKeyPair(batch);
×
840
}
×
841

842
/**
843
 * @brief MainWindow::updateProfileBox update the list of profiles, optionally
844
 * select a more appropriate one to view too
845
 */
846
void MainWindow::updateProfileBox() {
×
847
  QHash<QString, QHash<QString, QString>> profiles =
848
      QtPassSettings::getProfiles();
×
849

850
  if (profiles.isEmpty()) {
851
    ui->profileWidget->hide();
×
852
  } else {
853
    ui->profileWidget->show();
×
854
    ui->profileBox->setEnabled(profiles.size() > 1);
×
855
    ui->profileBox->clear();
×
856
    QHashIterator<QString, QHash<QString, QString>> i(profiles);
×
857
    while (i.hasNext()) {
×
858
      i.next();
859
      if (!i.key().isEmpty()) {
×
860
        ui->profileBox->addItem(i.key());
×
861
      }
862
    }
863
    ui->profileBox->model()->sort(0);
×
864
  }
865
  int index = ui->profileBox->findText(QtPassSettings::getProfile());
×
866
  if (index != -1) { //  -1 for not found
×
867
    ui->profileBox->setCurrentIndex(index);
×
868
  }
869
}
×
870

871
/**
872
 * @brief MainWindow::on_profileBox_currentIndexChanged make sure we show the
873
 * correct "profile"
874
 * @param name
875
 */
876
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
877
void MainWindow::on_profileBox_currentIndexChanged(QString name) {
878
#else
879
/**
880
 * @brief Handles changes to the selected profile in the profile combo box.
881
 * @details Ignores the event during a fresh start or when the selected profile
882
 * matches the current profile. Otherwise, it clears the password field, updates
883
 * the active profile and related settings, refreshes the environment, and
884
 * resets the tree view and action states to reflect the newly selected profile.
885
 *
886
 * @param name - The newly selected profile name.
887
 * @return void - This function does not return a value.
888
 *
889
 */
890
void MainWindow::on_profileBox_currentTextChanged(const QString &name) {
×
891
#endif
892
  if (m_qtPass->isFreshStart() || name == QtPassSettings::getProfile()) {
×
893
    return;
894
  }
895

896
  ui->lineEdit->clear();
×
897

898
  QtPassSettings::setProfile(name);
×
899

900
  QtPassSettings::setPassStore(
×
901
      QtPassSettings::getProfiles().value(name).value("path"));
×
902
  QtPassSettings::setPassSigningKey(
×
903
      QtPassSettings::getProfiles().value(name).value("signingKey"));
×
904
  ui->statusBar->showMessage(tr("Profile changed to %1").arg(name), 2000);
×
905

906
  QtPassSettings::getPass()->updateEnv();
×
907

908
  ui->treeView->selectionModel()->clear();
×
909
  ui->treeView->setRootIndex(proxyModel.mapFromSource(
×
910
      model.setRootPath(QtPassSettings::getPassStore())));
×
911

912
  ui->actionEdit->setEnabled(false);
×
913
  ui->actionDelete->setEnabled(false);
×
914
}
915

916
/**
917
 * @brief MainWindow::initTrayIcon show a nice tray icon on systems that
918
 * support
919
 * it
920
 */
921
void MainWindow::initTrayIcon() {
×
922
  this->tray = new TrayIcon(this);
×
923
  // Setup tray icon
924

925
  if (tray == nullptr) {
926
#ifdef QT_DEBUG
927
    dbg() << "Allocating tray icon failed.";
928
#endif
929
  }
930

931
  if (!tray->getIsAllocated()) {
×
932
    destroyTrayIcon();
×
933
  }
934
}
×
935

936
/**
937
 * @brief MainWindow::destroyTrayIcon remove that pesky tray icon
938
 */
939
void MainWindow::destroyTrayIcon() {
×
940
  delete this->tray;
×
941
  tray = nullptr;
×
942
}
×
943

944
/**
945
 * @brief MainWindow::closeEvent hide or quit
946
 * @param event
947
 */
948
void MainWindow::closeEvent(QCloseEvent *event) {
×
949
  if (QtPassSettings::isHideOnClose()) {
×
950
    this->hide();
×
951
    event->ignore();
952
  } else {
953
    m_qtPass->clearClipboard();
×
954

955
    QtPassSettings::setGeometry(saveGeometry());
×
956
    QtPassSettings::setSavestate(saveState());
×
957
    QtPassSettings::setMaximized(isMaximized());
×
958
    if (!isMaximized()) {
×
959
      QtPassSettings::setPos(pos());
×
960
      QtPassSettings::setSize(size());
×
961
    }
962
    event->accept();
963
  }
964
}
×
965

966
/**
967
 * @brief MainWindow::eventFilter filter out some events and focus the
968
 * treeview
969
 * @param obj
970
 * @param event
971
 * @return
972
 */
973
auto MainWindow::eventFilter(QObject *obj, QEvent *event) -> bool {
×
974
  if (obj == ui->lineEdit && event->type() == QEvent::KeyPress) {
×
975
    auto *key = dynamic_cast<QKeyEvent *>(event);
×
976
    if (key != nullptr && key->key() == Qt::Key_Down) {
×
977
      ui->treeView->setFocus();
×
978
    }
979
  }
980
  return QObject::eventFilter(obj, event);
×
981
}
982

983
/**
984
 * @brief MainWindow::keyPressEvent did anyone press return, enter or escape?
985
 * @param event
986
 */
987
void MainWindow::keyPressEvent(QKeyEvent *event) {
×
988
  switch (event->key()) {
×
989
  case Qt::Key_Delete:
×
990
    onDelete();
×
991
    break;
×
992
  case Qt::Key_Return:
×
993
  case Qt::Key_Enter:
994
    if (proxyModel.rowCount() > 0) {
×
995
      on_treeView_clicked(ui->treeView->currentIndex());
×
996
    }
997
    break;
998
  case Qt::Key_Escape:
×
999
    ui->lineEdit->clear();
×
1000
    break;
×
1001
  default:
1002
    break;
1003
  }
1004
}
×
1005

1006
/**
1007
 * @brief MainWindow::showContextMenu show us the (file or folder) context
1008
 * menu
1009
 * @param pos
1010
 */
1011
void MainWindow::showContextMenu(const QPoint &pos) {
×
1012
  QModelIndex index = ui->treeView->indexAt(pos);
×
1013
  bool selected = true;
1014
  if (!index.isValid()) {
1015
    ui->treeView->clearSelection();
×
1016
    ui->actionDelete->setEnabled(false);
×
1017
    ui->actionEdit->setEnabled(false);
×
1018
    currentDir = "";
×
1019
    selected = false;
1020
  }
1021

1022
  ui->treeView->setCurrentIndex(index);
×
1023

1024
  QPoint globalPos = ui->treeView->viewport()->mapToGlobal(pos);
×
1025

1026
  QFileInfo fileOrFolder =
1027
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
1028

1029
  QMenu contextMenu;
×
1030
  if (!selected || fileOrFolder.isDir()) {
×
1031
    QAction *openFolder =
1032
        contextMenu.addAction(tr("Open folder with file manager"));
×
1033
    QAction *addFolder = contextMenu.addAction(tr("Add folder"));
×
1034
    QAction *addPassword = contextMenu.addAction(tr("Add password"));
×
1035
    QAction *users = contextMenu.addAction(tr("Users"));
×
1036
    connect(openFolder, &QAction::triggered, this, &MainWindow::openFolder);
×
1037
    connect(addFolder, &QAction::triggered, this, &MainWindow::addFolder);
×
1038
    connect(addPassword, &QAction::triggered, this, &MainWindow::addPassword);
×
1039
    connect(users, &QAction::triggered, this, &MainWindow::onUsers);
×
1040
  } else if (fileOrFolder.isFile()) {
×
1041
    QAction *edit = contextMenu.addAction(tr("Edit"));
×
1042
    connect(edit, &QAction::triggered, this, &MainWindow::onEdit);
×
1043
  }
1044
  if (selected) {
×
1045
    contextMenu.addSeparator();
×
1046
    if (fileOrFolder.isDir()) {
×
1047
      QAction *renameFolder = contextMenu.addAction(tr("Rename folder"));
×
1048
      connect(renameFolder, &QAction::triggered, this,
×
1049
              &MainWindow::renameFolder);
×
1050
    } else if (fileOrFolder.isFile()) {
×
1051
      QAction *renamePassword = contextMenu.addAction(tr("Rename password"));
×
1052
      connect(renamePassword, &QAction::triggered, this,
×
1053
              &MainWindow::renamePassword);
×
1054
    }
1055
    QAction *deleteItem = contextMenu.addAction(tr("Delete"));
×
1056
    connect(deleteItem, &QAction::triggered, this, &MainWindow::onDelete);
×
1057
  }
1058
  contextMenu.exec(globalPos);
×
1059
}
×
1060

1061
/**
1062
 * @brief MainWindow::showBrowserContextMenu show us the context menu in
1063
 * password window
1064
 * @param pos
1065
 */
1066
void MainWindow::showBrowserContextMenu(const QPoint &pos) {
×
1067
  QMenu *contextMenu = ui->textBrowser->createStandardContextMenu(pos);
×
1068

1069
  // Fix transparent menu in dark mode
NEW
1070
  QPalette p = contextMenu->palette();
×
NEW
1071
  p.setColor(QPalette::Window, p.color(QPalette::Window).toRgb());
×
NEW
1072
  p.setColor(QPalette::Base, p.color(QPalette::Base).toRgb());
×
NEW
1073
  contextMenu->setPalette(p);
×
NEW
1074
  contextMenu->setWindowFlags(contextMenu->windowFlags() | Qt::Popup);
×
NEW
1075
  contextMenu->setAttribute(Qt::WA_TranslucentBackground, false);
×
1076

NEW
1077
  QPoint globalPos = ui->textBrowser->viewport()->mapToGlobal(pos);
×
1078
  contextMenu->exec(globalPos);
×
1079
  delete contextMenu;
×
1080
}
×
1081

1082
/**
1083
 * @brief MainWindow::openFolder open the folder in the default file manager
1084
 */
1085
void MainWindow::openFolder() {
×
1086
  QString dir =
1087
      Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel);
×
1088

1089
  QString path = QDir::toNativeSeparators(dir);
×
1090
  QDesktopServices::openUrl(QUrl::fromLocalFile(path));
×
1091
}
×
1092

1093
/**
1094
 * @brief MainWindow::addFolder add a new folder to store passwords in
1095
 */
1096
void MainWindow::addFolder() {
×
1097
  bool ok;
1098
  QString dir =
1099
      Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel);
×
1100
  QString newdir =
1101
      QInputDialog::getText(this, tr("New file"),
×
1102
                            tr("New Folder: \n(Will be placed in %1 )")
×
1103
                                .arg(QtPassSettings::getPassStore() +
×
1104
                                     Util::getDir(ui->treeView->currentIndex(),
×
1105
                                                  true, model, proxyModel)),
1106
                            QLineEdit::Normal, "", &ok);
×
1107
  if (!ok || newdir.isEmpty()) {
×
1108
    return;
1109
  }
1110
  newdir.prepend(dir);
1111
  if (!QDir().mkdir(newdir)) {
×
1112
    QMessageBox::warning(this, tr("Error"),
×
1113
                         tr("Failed to create folder: %1").arg(newdir));
×
1114
    return;
×
1115
  }
1116
  if (QtPassSettings::isAddGPGId(true)) {
×
1117
    QString gpgIdFile = newdir + "/.gpg-id";
×
1118
    QFile gpgId(gpgIdFile);
×
1119
    if (!gpgId.open(QIODevice::WriteOnly)) {
×
1120
      QMessageBox::warning(
×
1121
          this, tr("Error"),
×
1122
          tr("Failed to create .gpg-id file in: %1").arg(newdir));
×
1123
      return;
1124
    }
1125
    QList<UserInfo> users = QtPassSettings::getPass()->listKeys("", true);
×
1126
    for (const UserInfo &user : users) {
×
1127
      if (user.enabled) {
×
1128
        gpgId.write((user.key_id + "\n").toUtf8());
×
1129
      }
1130
    }
1131
    gpgId.close();
×
1132
  }
×
1133
}
1134

1135
/**
1136
 * @brief MainWindow::renameFolder rename an existing folder
1137
 */
1138
void MainWindow::renameFolder() {
×
1139
  bool ok;
1140
  QString srcDir = QDir::cleanPath(
1141
      Util::getDir(ui->treeView->currentIndex(), false, model, proxyModel));
×
1142
  QString srcDirName = QDir(srcDir).dirName();
×
1143
  QString newName =
1144
      QInputDialog::getText(this, tr("Rename file"), tr("Rename Folder To: "),
×
1145
                            QLineEdit::Normal, srcDirName, &ok);
×
1146
  if (!ok || newName.isEmpty()) {
×
1147
    return;
1148
  }
1149
  QString destDir = srcDir;
1150
  destDir.replace(srcDir.lastIndexOf(srcDirName), srcDirName.length(), newName);
×
1151
  QtPassSettings::getPass()->Move(srcDir, destDir);
×
1152
}
1153

1154
/**
1155
 * @brief MainWindow::editPassword read password and open edit window via
1156
 * MainWindow::onEdit()
1157
 */
1158
void MainWindow::editPassword(const QString &file) {
×
1159
  if (!file.isEmpty()) {
×
1160
    if (QtPassSettings::isUseGit() && QtPassSettings::isAutoPull()) {
×
1161
      onUpdate(true);
×
1162
    }
1163
    setPassword(file, false);
×
1164
  }
1165
}
×
1166

1167
/**
1168
 * @brief MainWindow::renamePassword rename an existing password
1169
 */
1170
void MainWindow::renamePassword() {
×
1171
  bool ok;
1172
  QString file = getFile(ui->treeView->currentIndex(), false);
×
1173
  QString filePath = QFileInfo(file).path();
×
1174
  QString fileName = QFileInfo(file).fileName();
×
1175
  if (fileName.endsWith(".gpg", Qt::CaseInsensitive)) {
×
1176
    fileName.chop(4);
×
1177
  }
1178

1179
  QString newName =
1180
      QInputDialog::getText(this, tr("Rename file"), tr("Rename File To: "),
×
1181
                            QLineEdit::Normal, fileName, &ok);
×
1182
  if (!ok || newName.isEmpty()) {
×
1183
    return;
1184
  }
1185
  QString newFile = QDir(filePath).filePath(newName);
×
1186
  QtPassSettings::getPass()->Move(file, newFile);
×
1187
}
1188

1189
/**
1190
 * @brief MainWindow::clearTemplateWidgets empty the template widget fields in
1191
 * the UI
1192
 */
1193
void MainWindow::clearTemplateWidgets() {
×
1194
  while (ui->gridLayout->count() > 0) {
×
1195
    QLayoutItem *item = ui->gridLayout->takeAt(0);
×
1196
    delete item->widget();
×
1197
    delete item;
×
1198
  }
1199
  ui->verticalLayoutPassword->setSpacing(0);
×
1200
}
×
1201

1202
/**
1203
 * @brief Copies the password of the selected file from the tree view to the
1204
 * clipboard.
1205
 * @example
1206
 * MainWindow::copyPasswordFromTreeview();
1207
 *
1208
 * @return void - This function does not return a value.
1209
 */
1210
void MainWindow::copyPasswordFromTreeview() {
×
1211
  QFileInfo fileOrFolder =
1212
      model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex()));
×
1213

1214
  if (fileOrFolder.isFile()) {
×
1215
    QString file = getFile(ui->treeView->currentIndex(), true);
×
1216
    // Disconnect any previous connection to avoid accumulation
1217
    disconnect(QtPassSettings::getPass(), &Pass::finishedShow, this,
×
1218
               &MainWindow::passwordFromFileToClipboard);
1219
    connect(QtPassSettings::getPass(), &Pass::finishedShow, this,
×
1220
            &MainWindow::passwordFromFileToClipboard);
×
1221
    QtPassSettings::getPass()->Show(file);
×
1222
  }
1223
}
×
1224

1225
void MainWindow::passwordFromFileToClipboard(const QString &text) {
×
1226
  QStringList tokens = text.split('\n');
×
1227
  m_qtPass->copyTextToClipboard(tokens[0]);
×
1228
}
×
1229

1230
/**
1231
 * @brief MainWindow::addToGridLayout add a field to the template grid
1232
 * @param position
1233
 * @param field
1234
 * @param value
1235
 */
1236
void MainWindow::addToGridLayout(int position, const QString &field,
×
1237
                                 const QString &value) {
1238
  QString trimmedField = field.trimmed();
1239
  QString trimmedValue = value.trimmed();
1240

1241
  const QString buttonStyle =
1242
      "border-style: none; background: transparent; padding: 0; margin: 0; "
1243
      "icon-size: 16px; color: inherit;";
×
1244

1245
  // Combine the Copy button and the line edit in one widget
1246
  auto *frame = new QFrame();
×
1247
  QLayout *ly = new QHBoxLayout();
×
1248
  ly->setContentsMargins(5, 2, 2, 2);
×
1249
  ly->setSpacing(0);
×
1250
  frame->setLayout(ly);
×
1251
  if (QtPassSettings::getClipBoardType() != Enums::CLIPBOARD_NEVER) {
×
1252
    auto *fieldLabel = new QPushButtonWithClipboard(trimmedValue, this);
×
1253
    connect(fieldLabel, &QPushButtonWithClipboard::clicked, m_qtPass,
×
1254
            &QtPass::copyTextToClipboard);
×
1255

1256
    fieldLabel->setStyleSheet(buttonStyle);
×
1257
    frame->layout()->addWidget(fieldLabel);
×
1258
  }
1259

1260
  if (QtPassSettings::isUseQrencode()) {
×
1261
    auto *qrbutton = new QPushButtonAsQRCode(trimmedValue, this);
×
1262
    connect(qrbutton, &QPushButtonAsQRCode::clicked, m_qtPass,
×
1263
            &QtPass::showTextAsQRCode);
×
1264
    qrbutton->setStyleSheet(buttonStyle);
×
1265
    frame->layout()->addWidget(qrbutton);
×
1266
  }
1267

1268
  // set the echo mode to password, if the field is "password"
1269
  const QString lineStyle =
1270
      QtPassSettings::isUseMonospace()
×
1271
          ? "border-style: none; background: transparent; font-family: "
1272
            "monospace;"
1273
          : "border-style: none; background: transparent;";
×
1274

1275
  if (QtPassSettings::isHidePassword() && trimmedField == tr("Password")) {
×
1276
    auto *line = new QLineEdit();
×
1277
    line->setObjectName(trimmedField);
×
1278
    line->setText(trimmedValue);
×
1279
    line->setReadOnly(true);
×
1280
    line->setStyleSheet(lineStyle);
×
1281
    line->setContentsMargins(0, 0, 0, 0);
×
1282
    line->setEchoMode(QLineEdit::Password);
×
1283
    auto *showButton = new QPushButtonShowPassword(line, this);
×
1284
    showButton->setStyleSheet(buttonStyle);
×
1285
    showButton->setContentsMargins(0, 0, 0, 0);
×
1286
    frame->layout()->addWidget(showButton);
×
1287
    frame->layout()->addWidget(line);
×
1288
  } else {
1289
    auto *line = new QTextBrowser();
×
1290
    line->setOpenExternalLinks(true);
×
1291
    line->setOpenLinks(true);
×
1292
    line->setMaximumHeight(26);
×
1293
    line->setMinimumHeight(26);
×
1294
    line->setSizePolicy(
×
1295
        QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum));
1296
    line->setObjectName(trimmedField);
×
1297
    trimmedValue.replace(Util::protocolRegex(), R"(<a href="\1">\1</a>)");
×
1298
    line->setText(trimmedValue);
×
1299
    line->setReadOnly(true);
×
1300
    line->setStyleSheet(lineStyle);
×
1301
    line->setContentsMargins(0, 0, 0, 0);
×
1302
    frame->layout()->addWidget(line);
×
1303
  }
1304

1305
  frame->setStyleSheet(
×
1306
      ".QFrame{border: 1px solid lightgrey; border-radius: 5px;}");
1307

1308
  // set into the layout
1309
  ui->gridLayout->addWidget(new QLabel(trimmedField), position, 0);
×
1310
  ui->gridLayout->addWidget(frame, position, 1);
×
1311
}
×
1312

1313
/**
1314
 * @brief Displays message in status bar
1315
 *
1316
 * @param msg     text to be displayed
1317
 * @param timeout time for which msg shall be visible
1318
 */
1319
void MainWindow::showStatusMessage(const QString &msg, int timeout) {
×
1320
  ui->statusBar->showMessage(msg, timeout);
×
1321
}
×
1322

1323
/**
1324
 * @brief MainWindow::startReencryptPath disable ui elements and treeview
1325
 */
1326
void MainWindow::startReencryptPath() {
×
1327
  setUiElementsEnabled(false);
×
1328
  ui->treeView->setDisabled(true);
×
1329
}
×
1330

1331
/**
1332
 * @brief MainWindow::endReencryptPath re-enable ui elements
1333
 */
1334
void MainWindow::endReencryptPath() { setUiElementsEnabled(true); }
×
1335

1336
void MainWindow::updateGitButtonVisibility() {
×
1337
  if (!QtPassSettings::isUseGit() ||
×
1338
      (QtPassSettings::getGitExecutable().isEmpty() &&
×
1339
       QtPassSettings::getPassExecutable().isEmpty())) {
×
1340
    enableGitButtons(false);
×
1341
  } else {
1342
    enableGitButtons(true);
×
1343
  }
1344
}
×
1345

1346
void MainWindow::updateOtpButtonVisibility() {
×
1347
#if defined(Q_OS_WIN) || defined(__APPLE__)
1348
  ui->actionOtp->setVisible(false);
1349
#endif
1350
  if (!QtPassSettings::isUseOtp()) {
×
1351
    ui->actionOtp->setEnabled(false);
×
1352
  } else {
1353
    ui->actionOtp->setEnabled(true);
×
1354
  }
1355
}
×
1356

1357
void MainWindow::enableGitButtons(const bool &state) {
×
1358
  // Following GNOME guidelines is preferable disable buttons instead of hide
1359
  ui->actionPush->setEnabled(state);
×
1360
  ui->actionUpdate->setEnabled(state);
×
1361
}
×
1362

1363
/**
1364
 * @brief MainWindow::critical critical message popup wrapper.
1365
 * @param title
1366
 * @param msg
1367
 */
1368
void MainWindow::critical(const QString &title, const QString &msg) {
×
1369
  QMessageBox::critical(this, title, msg);
×
1370
}
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc