QtPass Developer documentation
QtPass test coverage
Current view: top level - src/passworddialog.cpp (source / functions) Coverage Total Hit
Test: QtPass Lines: 98.7 % 546 539
Test Date: 2026-12-03 23:34:20 Functions: 100.0 % 44 44
Branches: 88.0 % 400 352

             Branch data     Line data    Source code
       1                 :             : // SPDX-FileCopyrightText: 2015 Anne Jan Brouwer
       2                 :             : // SPDX-License-Identifier: GPL-3.0-or-later
       3                 :             : /**
       4                 :             :  * @file
       5                 :             :  * @brief Implements PasswordDialog: field rows built from templates and entry
       6                 :             :  * content, round-trip-safe serialisation in getPassword(), OTP validation and
       7                 :             :  * the locked-while-saving insert protocol.
       8                 :             :  */
       9                 :             : #include "passworddialog.h"
      10                 :             : #include "fieldlabel.h"
      11                 :             : #include "filecontent.h"
      12                 :             : #include "pass.h"
      13                 :             : #include "passwordconfiguration.h"
      14                 :             : #include "pathvalidator.h"
      15                 :             : #include "qtpasssettings.h"
      16                 :             : #include "secretlineedit.h"
      17                 :             : #include "secretplaintextedit.h"
      18                 :             : #include "templateio.h"
      19                 :             : #include "totp.h"
      20                 :             : #include "ui_passworddialog.h"
      21                 :             : #include "util.h"
      22                 :             : #include <algorithm>
      23                 :             : #include <limits>
      24                 :             : 
      25                 :             : #include <QAction>
      26                 :             : #include <QCheckBox>
      27                 :             : #include <QComboBox>
      28                 :             : #include <QDialogButtonBox>
      29                 :             : #include <QDir>
      30                 :             : #include <QFileInfo>
      31                 :             : #include <QFormLayout>
      32                 :             : #include <QHash>
      33                 :             : #include <QIcon>
      34                 :             : #include <QLabel>
      35                 :             : #include <QLineEdit>
      36                 :             : #include <QMessageBox>
      37                 :             : #include <QPushButton>
      38                 :             : #include <QSet>
      39                 :             : #include <QShortcut>
      40                 :             : #include <QSignalBlocker>
      41                 :             : #include <QTextDocument>
      42                 :             : #include <utility>
      43                 :             : 
      44                 :             : #include "qtpasslogging.h"
      45                 :             : 
      46                 :             : namespace {
      47                 :             : /// Dynamic property markOtpFieldEdited() sets on the line edit the user typed
      48                 :             : /// in; normalizeOtpField() reads it from the field that is the OTP one.
      49                 :             : constexpr const char *kOtpEditedProperty = "qtpassOtpEdited";
      50                 :             : /// Dynamic property holding a field row's verbatim source line, so
      51                 :             : /// getPassword() can write an untouched field back exactly as it was read.
      52                 :             : constexpr const char *kOriginalLineProperty = "qtpassOriginalLine";
      53                 :             : } // namespace
      54                 :             : 
      55                 :          24 : PasswordDialog::PasswordDialog(PasswordConfiguration passConfig,
      56                 :          24 :                                QWidget *parent)
      57                 :          24 :     : QDialog(parent), ui(new Ui::PasswordDialog),
      58                 :          48 :       m_passConfig(std::move(passConfig)), m_pass(QtPassSettings::getPass()) {
      59                 :             :   // Only reached from tests; production uses the overload taking an
      60                 :             :   // explicit Pass* with a caller-controlled lifetime.
      61                 :             :   m_templating = false;
      62                 :             :   m_isNew = false;
      63                 :             : 
      64                 :          24 :   ui->setupUi(this);
      65                 :          24 :   connect(ui->checkBoxShow, &QCheckBox::toggled, this,
      66         [ +  + ]:          48 :           &PasswordDialog::setPasswordVisible);
      67                 :          24 :   reportCopies(ui->lineEditPassword);
      68                 :          24 :   connect(ui->plainTextEdit, &SecretPlainTextEdit::copied, this,
      69                 :          24 :           &PasswordDialog::copied);
      70                 :          24 :   setupTemplateBox();
      71                 :          24 :   setLength(m_passConfig.length);
      72                 :          24 :   setPasswordCharTemplate(m_passConfig.selected);
      73                 :             : 
      74                 :          24 :   connect(m_pass, &Pass::finishedShow, this, &PasswordDialog::setPass);
      75                 :          24 :   connect(m_pass, &Pass::finishedInsert, this,
      76                 :          24 :           &PasswordDialog::onInsertFinished);
      77                 :          24 :   connect(m_pass, &Pass::insertFailed, this, &PasswordDialog::onInsertFailed);
      78                 :          24 : }
      79                 :             : 
      80                 :         117 : PasswordDialog::PasswordDialog(Pass *pass, const AppSettings &s, QString file,
      81                 :         117 :                                const bool &isNew, QWidget *parent)
      82                 :         117 :     : QDialog(parent), ui(new Ui::PasswordDialog), m_pass(pass),
      83                 :         117 :       m_file(std::move(file)), m_isNew(isNew) {
      84                 :             : 
      85                 :         117 :   ui->setupUi(this);
      86                 :         117 :   connect(ui->checkBoxShow, &QCheckBox::toggled, this,
      87         [ +  + ]:         234 :           &PasswordDialog::setPasswordVisible);
      88                 :         117 :   reportCopies(ui->lineEditPassword);
      89                 :         117 :   connect(ui->plainTextEdit, &SecretPlainTextEdit::copied, this,
      90                 :         117 :           &PasswordDialog::copied);
      91                 :         117 :   setupTemplateBox();
      92                 :             :   // The name row only appears once setNewEntryLocation() says where a new
      93                 :             :   // entry may go; an existing entry keeps its name.
      94                 :         117 :   ui->nameRow->hide();
      95                 :             : 
      96      [ +  +  + ]:         159 :   setWindowTitle(isNew && m_file.isEmpty()
      97      [ +  +  + ]:         209 :                      ? tr("New password")
      98   [ +  +  +  +  :         393 :                      : this->windowTitle() + " " + m_file);
          +  +  -  -  -  
                      - ]
      99                 :             :   m_passConfig = s.passwordConfiguration;
     100                 :         117 :   usePwgen(s.usePwgen);
     101                 :         117 :   setTemplate(s.passTemplate, s.useTemplate);
     102                 :         117 :   templateAll(s.templateAllFields);
     103                 :             : 
     104                 :         117 :   setLength(m_passConfig.length);
     105                 :         117 :   setPasswordCharTemplate(m_passConfig.selected);
     106                 :             : 
     107                 :         117 :   connect(m_pass, &Pass::finishedShow, this, &PasswordDialog::setPass);
     108                 :         117 :   connect(m_pass, &Pass::processErrorExit, this, &PasswordDialog::onShowError);
     109                 :         117 :   connect(m_pass, &Pass::finishedInsert, this,
     110                 :         117 :           &PasswordDialog::onInsertFinished);
     111                 :         117 :   connect(m_pass, &Pass::insertFailed, this, &PasswordDialog::onInsertFailed);
     112                 :         117 :   connect(this, &PasswordDialog::rejected, this, &PasswordDialog::on_rejected);
     113                 :             : 
     114         [ +  + ]:         117 :   if (!isNew) {
     115                 :             :     // Show() is asynchronous: until finishedShow lands the fields are empty,
     116                 :             :     // so an early Ok would write nothing and the late setPass() would clobber
     117                 :             :     // what was typed. Lock the editor and Ok until the decrypt arrives.
     118                 :          75 :     ui->statusLabel->setText(tr("Decrypting…"));
     119                 :          75 :     setEditorEnabled(false);
     120                 :          75 :     ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
     121                 :         150 :     m_pass->Show(m_file);
     122                 :             :   }
     123                 :         117 : }
     124                 :             : 
     125                 :         167 : PasswordDialog::~PasswordDialog() {
     126                 :             :   // QDialog's destructor hides the window after this body, and losing focus
     127                 :             :   // emits editingFinished() into normalizeOtpField() or renameField(), slots
     128                 :             :   // of a PasswordDialog already gone. Hide here, while the object is whole.
     129                 :         141 :   hide();
     130                 :         308 : }
     131                 :             : 
     132                 :           5 : void PasswordDialog::setPasswordVisible(bool show) {
     133         [ +  + ]:           5 :   if (show) {
     134                 :           3 :     ui->lineEditPassword->setEchoMode(QLineEdit::Normal);
     135                 :             :   } else {
     136                 :           2 :     ui->lineEditPassword->setEchoMode(QLineEdit::Password);
     137                 :             :   }
     138                 :           5 : }
     139                 :             : 
     140                 :           3 : void PasswordDialog::on_createPasswordButton_clicked() {
     141                 :           3 :   ui->widget->setEnabled(false);
     142                 :           3 :   const int currentIndex = ui->passwordTemplateSwitch->currentIndex();
     143         [ +  + ]:           3 :   if (currentIndex < 0 ||
     144                 :             :       currentIndex >= static_cast<int>(PasswordConfiguration::CHARSETS_COUNT)) {
     145                 :           1 :     ui->widget->setEnabled(true);
     146                 :           1 :     return;
     147                 :             :   }
     148                 :             : 
     149                 :           2 :   QString newPass = m_pass->generatePassword(
     150                 :           2 :       static_cast<unsigned int>(ui->spinBox_pwdLength->value()),
     151                 :             :       m_passConfig.Characters[static_cast<PasswordConfiguration::CharacterSet>(
     152                 :           2 :           currentIndex)]);
     153         [ +  - ]:           2 :   if (!newPass.isEmpty()) {
     154                 :           2 :     ui->lineEditPassword->setText(newPass);
     155                 :             :   }
     156                 :           2 :   ui->widget->setEnabled(true);
     157                 :             : }
     158                 :             : 
     159                 :          43 : void PasswordDialog::save() {
     160                 :             :   // Show is asynchronous: refuse to save an existing entry before its
     161                 :             :   // content loads. getPassword() always returns at least a newline, so an
     162                 :             :   // isEmpty() check cannot stand in for this.
     163   [ +  +  +  + ]:          43 :   if (!m_isNew && !m_contentLoaded) {
     164                 :           5 :     return;
     165                 :             :   }
     166                 :             : 
     167                 :             :   // Canonicalise before serialising: getPassword() stays a dumb serializer.
     168                 :          40 :   normalizeOtpField();
     169                 :             : 
     170                 :          40 :   QString newValue = getPassword();
     171      [ +  +  + ]:          80 :   if (newValue.right(1) != "\n") {
     172                 :           2 :     newValue += "\n";
     173                 :             :   }
     174                 :             : 
     175                 :             :   // Saving over an entry encrypts it to its folder's list as it is now. A
     176                 :             :   // list that changed under the entry (a folder renamed past its own signed
     177                 :             :   // list falls back to its parent's) would hand it to someone who cannot
     178                 :             :   // read it: asked, and asked again if the answer was given for a list that
     179                 :             :   // changed while the question was open.
     180         [ +  + ]:          40 :   if (!m_isNew) {
     181                 :          17 :     Pass::EditReaders shown;
     182                 :          17 :     for (Pass::EditReaders gain = m_pass->readersAnEditWouldAdd(m_file);
     183   [ +  +  +  + ]:          19 :          !gain.names.isEmpty() && !(gain == shown);
     184                 :           4 :          gain = m_pass->readersAnEditWouldAdd(m_file)) {
     185                 :             :       shown = gain;
     186                 :           8 :       const QString who = gain.names.join(QStringLiteral(", "));
     187                 :             :       const QString text =
     188                 :           4 :           gain.notSavedHere
     189         [ -  + ]:           4 :               ? tr("%1 has not been saved from this device before, and its "
     190                 :             :                    "folder takes its recipients from a folder above it. "
     191                 :             :                    "Saving encrypts it to: %2.\n\nIf you did not expect "
     192                 :             :                    "this folder here, it may have been renamed or moved, and "
     193                 :             :                    "its own recipient list removed. Save anyway?")
     194                 :             :                     .arg(m_file, who)
     195                 :           4 :               : tr("Saving re-encrypts %1 to its folder's recipients, and "
     196                 :             :                    "that now includes someone who cannot read it: %2.\n\nIf "
     197                 :             :                    "you did not change who may read this folder, its "
     198                 :             :                    "recipient list may have been changed or the folder "
     199                 :             :                    "moved. Save anyway?")
     200                 :           4 :                     .arg(m_file, who);
     201   [ +  +  +  + ]:           8 :       if (QMessageBox::question(this, tr("Give this entry new readers?"), text,
     202                 :             :                                 QMessageBox::Save | QMessageBox::Cancel,
     203                 :             :                                 QMessageBox::Cancel) != QMessageBox::Save) {
     204                 :             :         return;
     205                 :             :       }
     206                 :             :     }
     207                 :             :   }
     208                 :             : 
     209                 :          38 :   setSaving(true);
     210                 :             :   // A refusal (the name is taken, the .gpg-id is unusable, a linked path)
     211                 :             :   // comes through critical() before Insert() returns, with nothing started
     212                 :             :   // that could still report.
     213                 :          38 :   QString refusal;
     214                 :             :   // The lambda refers to a local: safe, as the connection ends right after
     215                 :             :   // Insert(), while refusal is still in scope.
     216                 :             :   const auto keepRefusal = [&refusal](const QString &, const QString &message) {
     217                 :           1 :     refusal = message;
     218                 :          38 :   };
     219                 :             :   const QMetaObject::Connection refused =
     220                 :          38 :       connect(m_pass, &Pass::critical, this, keepRefusal);
     221                 :             :   // Reports from inserts already queued (an earlier dialog that a hanging
     222                 :             :   // queue let close while its save was still pending) must pass before one is
     223                 :             :   // taken as this dialog's own. The count is read before our own Insert()
     224                 :             :   // queues, so it does not include it.
     225                 :          38 :   m_insertsAhead = m_pass->insertsPending();
     226                 :          76 :   m_pass->Insert(m_file, std::move(newValue), !m_isNew);
     227                 :          38 :   disconnect(refused);
     228   [ +  +  +  + ]:          38 :   if (m_saving && !refusal.isEmpty()) {
     229                 :           1 :     setSaving(false);
     230                 :           1 :     showNotSaved(refusal);
     231                 :             :   }
     232                 :          38 : }
     233                 :             : 
     234                 :          74 : void PasswordDialog::setSaving(bool saving) {
     235         [ +  + ]:          74 :   if (saving) {
     236                 :          38 :     m_focusBeforeSave = focusWidget();
     237                 :             :   }
     238                 :          74 :   m_saving = saving;
     239                 :          74 :   setEditorEnabled(!saving);
     240                 :          74 :   ui->nameRow->setEnabled(!saving);
     241                 :             :   // Another template would rebuild the field rows under a pending insert.
     242                 :          74 :   ui->templateBox->setEnabled(!saving);
     243                 :             :   // Cancel stays: a save that never reports (an unanswered PIN prompt, a
     244                 :             :   // queue held up by a hanging pull) must not leave quitting as the only
     245                 :             :   // way out. reject() asks first.
     246                 :          74 :   ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(!saving);
     247      [ +  +  + ]:         112 :   ui->statusLabel->setText(saving ? tr("Saving…") : QString());
     248         [ +  + ]:          74 :   if (!saving) {
     249                 :             :     // Disabling the widget with the focus moved it onto Cancel, which then
     250                 :             :     // became the default: the next Enter, pressed to try again, would close
     251                 :             :     // the dialog and drop what was typed. The focus goes back where it was,
     252                 :             :     // or to the password; Cancel losing it makes OK the default again.
     253                 :             :     QWidget *back = m_focusBeforeSave;
     254                 :             :     m_focusBeforeSave = nullptr;
     255   [ +  +  +  -  :          36 :     if (back == nullptr || !back->isEnabled() || !back->isVisible()) {
                   +  + ]
     256                 :          27 :       back = ui->lineEditPassword;
     257                 :             :     }
     258                 :          36 :     back->setFocus(Qt::OtherFocusReason);
     259                 :             :   }
     260                 :          74 : }
     261                 :             : 
     262                 :          42 : auto PasswordDialog::isOwnInsertReport() -> bool {
     263         [ +  + ]:          42 :   if (!m_saving) {
     264                 :             :     return false;
     265                 :             :   }
     266                 :             :   // Since a hanging queue can let a dialog close while its insert is still
     267                 :             :   // queued (#1965), more than one insert can be in flight, and neither
     268                 :             :   // finishedInsert nor insertFailed says which it is. The Executor runs the
     269                 :             :   // queue in order, so the first m_insertsAhead reports belong to inserts
     270                 :             :   // queued before this dialog's; let them pass before taking one as our own.
     271         [ +  + ]:          37 :   if (m_insertsAhead > 0) {
     272                 :           2 :     --m_insertsAhead;
     273                 :           2 :     return false;
     274                 :             :   }
     275                 :             :   return true;
     276                 :             : }
     277                 :             : 
     278                 :          34 : void PasswordDialog::onInsertFinished() {
     279         [ +  + ]:          34 :   if (!isOwnInsertReport()) {
     280                 :             :     return;
     281                 :             :   }
     282                 :          29 :   setSaving(false);
     283                 :          29 :   QDialog::accept();
     284                 :             : }
     285                 :             : 
     286                 :           8 : void PasswordDialog::onInsertFailed(const QString &err, bool written) {
     287         [ +  + ]:           8 :   if (!isOwnInsertReport()) {
     288                 :             :     return;
     289                 :             :   }
     290                 :           6 :   setSaving(false);
     291                 :             :   // The entry is in the store and a later step (git add or commit) failed,
     292                 :             :   // which the backend reports ("Saved, not committed"). Saved is saved, so
     293                 :             :   // the dialog closes, also for an existing entry: "Not saved" would be
     294                 :             :   // wrong, and a new entry could only be tried again under a name it now
     295                 :             :   // has.
     296         [ +  + ]:           6 :   if (written) {
     297                 :           2 :     QDialog::accept();
     298                 :           2 :     return;
     299                 :             :   }
     300                 :           4 :   showNotSaved(err);
     301                 :             : }
     302                 :             : 
     303                 :          10 : void PasswordDialog::reject() {
     304         [ +  + ]:          10 :   if (m_saving) {
     305                 :           6 :     const QMessageBox::StandardButton answer = QMessageBox::question(
     306                 :           3 :         this, tr("Still saving"),
     307                 :           3 :         tr("The entry is still being saved. Close the dialog anyway? If "
     308                 :             :            "saving then fails, what you typed is lost."),
     309                 :             :         QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
     310                 :             :     // The insert may have reported while the question was up.
     311   [ +  +  +  - ]:           3 :     if (answer != QMessageBox::Yes || !m_saving) {
     312                 :             :       return;
     313                 :             :     }
     314                 :             :     // Whatever the insert reports later, the main window shows it.
     315                 :           1 :     m_saving = false;
     316                 :             :   }
     317                 :           8 :   QDialog::reject();
     318                 :             : }
     319                 :             : 
     320                 :           5 : void PasswordDialog::showNotSaved(const QString &err) {
     321         [ +  - ]:           5 :   if (!m_storeRoot.isEmpty()) {
     322                 :           5 :     validateNewEntry(); // gates OK on the name again
     323                 :             :   }
     324                 :          10 :   ui->statusLabel->setText(tr("Not saved: %1").arg(err.trimmed()));
     325                 :           5 : }
     326                 :             : 
     327                 :          16 : void PasswordDialog::on_rejected() { setPassword(QString()); }
     328                 :             : 
     329                 :          22 : void PasswordDialog::setNewEntryLocation(const QString &storeRoot,
     330                 :             :                                          const QStringList &folders,
     331                 :             :                                          const QString &currentFolder) {
     332                 :          44 :   m_storeRoot = QDir::cleanPath(storeRoot);
     333                 :             :   // Not sized to its items: the box shaped the text of every folder path to
     334                 :             :   // find its width, and a co-writer's thousands of nested folders froze
     335                 :             :   // Add password for half a minute and made the dialog thousands of pixels
     336                 :             :   // wide.
     337                 :          22 :   ui->folderBox->setSizeAdjustPolicy(
     338                 :             :       QComboBox::AdjustToMinimumContentsLengthWithIcon);
     339                 :          22 :   ui->folderBox->setMinimumContentsLength(30);
     340                 :          22 :   ui->folderBox->clear();
     341                 :             :   int current = 0;
     342         [ +  + ]:       20068 :   for (const QString &folder : folders) {
     343                 :       40092 :     const QString rel = QDir::cleanPath(folder) == QStringLiteral(".")
     344         [ -  + ]:       20046 :                             ? QString()
     345                 :       20046 :                             : QDir::cleanPath(folder);
     346   [ +  +  +  +  :       40092 :     if (rel == QDir::cleanPath(currentFolder) ||
                +  +  + ]
     347                 :             :         (rel.isEmpty() &&
     348   [ +  +  +  +  :       20054 :          QDir::cleanPath(currentFolder) == QStringLiteral("."))) {
          +  -  -  -  -  
                   -  - ]
     349                 :          22 :       current = ui->folderBox->count();
     350                 :             :     }
     351                 :             :     // A long path is shown cut in the middle, whole in its tooltip: the
     352                 :             :     // list that drops down still measures every row it shows.
     353                 :             :     constexpr qsizetype kMaxShown = 120;
     354   [ +  +  +  +  :       20046 :     const QString shown = rel.isEmpty() ? QStringLiteral("/") : rel + u'/';
                      + ]
     355         [ +  + ]:       20046 :     if (shown.size() > kMaxShown) {
     356                 :             :       // Never between the halves of a surrogate pair.
     357                 :             :       qsizetype head = kMaxShown / 3;
     358         [ +  + ]:       18821 :       if (shown.at(head - 1).isHighSurrogate()) {
     359                 :             :         --head;
     360                 :             :       }
     361                 :             :       qsizetype tail = kMaxShown - kMaxShown / 3 - 1;
     362         [ +  + ]:       18821 :       if (shown.at(shown.size() - tail).isLowSurrogate()) {
     363                 :             :         --tail;
     364                 :             :       }
     365                 :       18821 :       ui->folderBox->addItem(
     366   [ +  +  +  +  :       37642 :           shown.left(head) + QChar(0x2026) + shown.right(tail), rel);
                      + ]
     367                 :       18821 :       ui->folderBox->setItemData(ui->folderBox->count() - 1,
     368                 :       56463 :                                  Util::plainToolTip(shown), Qt::ToolTipRole);
     369                 :             :     } else {
     370                 :        1225 :       ui->folderBox->addItem(shown, rel);
     371                 :             :     }
     372                 :             :   }
     373                 :          22 :   ui->folderBox->setCurrentIndex(current);
     374                 :          44 :   m_newEntryFolder = ui->folderBox->currentData().toString();
     375                 :          22 :   ui->nameRow->show();
     376                 :          22 :   connect(ui->nameEdit, &QLineEdit::textChanged, this,
     377                 :          22 :           &PasswordDialog::validateNewEntry);
     378                 :          22 :   connect(ui->folderBox, &QComboBox::currentIndexChanged, this,
     379                 :          22 :           &PasswordDialog::validateNewEntry);
     380                 :          22 :   validateNewEntry();
     381                 :          22 :   ui->nameEdit->setFocus();
     382                 :          22 : }
     383                 :             : 
     384                 :          52 : auto PasswordDialog::whyNotSavedAs(const QString &absolute,
     385                 :             :                                    const QString &rel) const -> QString {
     386                 :             :   // The tree, like `pass ls`, hides names that start with a dot: such an
     387                 :             :   // entry would be saved but never listed.
     388                 :          52 :   const QStringList parts = rel.split(u'/');
     389         [ +  + ]:          52 :   if (std::any_of(parts.cbegin(), parts.cend(),
     390         [ +  + ]:        1073 :                   [](const QString &part) { return part.startsWith(u'.'); })) {
     391                 :             :     return tr("A name or folder that starts with a dot would be hidden "
     392                 :             :               "from the list.");
     393                 :             :   }
     394                 :             :   // Checked here, not only by Insert(): accept() creates the entry's folder
     395                 :             :   // first, and behind a link that folder is outside the store.
     396      [ +  +  + ]:          50 :   if (Util::isUnderLink(absolute, m_storeRoot)) {
     397                 :           2 :     return tr("%1 lies behind a symbolic link or junction, outside the "
     398                 :             :               "password store.")
     399                 :           2 :         .arg(rel);
     400                 :             :   }
     401   [ +  +  +  + ]:          96 :   if (QFileInfo::exists(absolute + QStringLiteral(".gpg"))) {
     402                 :           3 :     return tr("An entry called %1 already exists.").arg(rel);
     403                 :             :   }
     404   [ +  +  +  + ]:          45 :   if (QFileInfo(absolute).isDir()) {
     405                 :           1 :     return tr("%1 is a folder.").arg(rel);
     406                 :             :   }
     407                 :          44 :   return {};
     408                 :             : }
     409                 :             : 
     410                 :          79 : auto PasswordDialog::resolveNewEntry(QString *problem) const -> QString {
     411                 :         237 :   QString name = QDir::fromNativeSeparators(ui->nameEdit->text().trimmed());
     412                 :             :   // The suffix belongs to the file, not the entry: Insert() appends it, so a
     413                 :             :   // typed "github.gpg" would otherwise become github.gpg.gpg.
     414      [ +  +  + ]:         158 :   if (name.endsWith(QStringLiteral(".gpg"), Qt::CaseInsensitive)) {
     415                 :           3 :     name.chop(4);
     416                 :             :   }
     417         [ +  + ]:          79 :   if (name.isEmpty()) {
     418                 :          24 :     *problem = tr("Give the entry a name.");
     419                 :          24 :     return {};
     420                 :             :   }
     421      [ +  +  + ]:          55 :   if (name.endsWith(u'/')) {
     422                 :           1 :     *problem = tr("A name cannot end in /.");
     423                 :           1 :     return {};
     424                 :             :   }
     425                 :          54 :   const QString folder = ui->folderBox->currentData().toString();
     426                 :             :   // A name typed as a full path is not put under the chosen folder; it
     427                 :             :   // stays as it is (filePath() does not join it either), so the store
     428                 :             :   // check below covers it.
     429                 :             :   // A name starting with ':' is a name in the store, not a full path: Qt's
     430                 :             :   // isAbsolutePath() takes it for a resource path (Util::joinPath()).
     431                 :             :   const bool fullPath =
     432   [ +  +  +  -  :         104 :       QDir::isAbsolutePath(name) && !name.startsWith(QLatin1Char(':'));
                +  +  + ]
     433                 :             :   const QString typed = QDir::cleanPath(
     434   [ +  +  +  +  :         152 :       (folder.isEmpty() || fullPath) ? name : folder + u'/' + name);
          +  +  +  +  +  
                   -  - ]
     435                 :         108 :   const QString absolute = QDir::cleanPath(Util::joinPath(m_storeRoot, typed));
     436   [ +  -  -  +  :         162 :   if (typed.isEmpty() || typed == QStringLiteral(".") ||
          +  +  +  -  +  
                      + ]
     437                 :          54 :       !PathValidator::isPathInStore(m_storeRoot, absolute)) {
     438                 :           2 :     *problem = tr("That name would resolve outside the password store.");
     439                 :           2 :     return {};
     440                 :             :   }
     441                 :             :   // The entry's name is relative to the store, also when it was typed as
     442                 :             :   // the full path of its file: `pass insert` takes any name as one below
     443                 :             :   // the store root and would save it there, for the root's recipients.
     444                 :             :   const QString rel =
     445                 :         104 :       QDir(QDir::cleanPath(m_storeRoot)).relativeFilePath(absolute);
     446   [ +  -  +  -  :         104 :   if (rel.isEmpty() || rel == QStringLiteral(".")) {
                   -  + ]
     447                 :           0 :     *problem = tr("That name would resolve outside the password store.");
     448                 :           0 :     return {};
     449                 :             :   }
     450                 :         104 :   *problem = whyNotSavedAs(absolute, rel);
     451         [ +  + ]:          52 :   return problem->isEmpty() ? rel : QString();
     452                 :             : }
     453                 :             : 
     454                 :             : // Re-checked on every keystroke; gates OK.
     455                 :          60 : void PasswordDialog::validateNewEntry() {
     456                 :          60 :   QString problem;
     457                 :          60 :   const QString rel = resolveNewEntry(&problem);
     458                 :             :   // A folder shown cut could be a look-alike of another long one: the box's
     459                 :             :   // tooltip names the chosen one whole, and the status says to look.
     460                 :          60 :   const QString whole = ui->folderBox->currentData(Qt::ToolTipRole).toString();
     461      [ +  +  + ]:         120 :   ui->folderBox->setToolTip(
     462   [ +  +  +  + ]:         120 :       whole.isEmpty() ? tr("The folder of the password store the new entry "
     463                 :             :                            "goes into")
     464                 :             :                       : whole);
     465   [ +  +  +  + ]:          60 :   if (problem.isEmpty() && !whole.isEmpty()) {
     466                 :           1 :     problem = tr("The folder's path is shortened above; hold the pointer "
     467                 :             :                  "over it to read it whole before you save.");
     468                 :             :   }
     469                 :          60 :   ui->statusLabel->setText(problem);
     470         [ +  + ]:          60 :   ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(!rel.isEmpty());
     471                 :          60 : }
     472                 :             : 
     473                 :          46 : void PasswordDialog::accept() {
     474         [ +  + ]:          46 :   if (m_saving) {
     475                 :             :     return;
     476                 :             :   }
     477         [ +  + ]:          45 :   if (!m_storeRoot.isEmpty()) {
     478                 :          19 :     QString problem;
     479                 :          19 :     const QString rel = resolveNewEntry(&problem);
     480         [ +  + ]:          19 :     if (rel.isEmpty()) {
     481                 :           1 :       ui->statusLabel->setText(problem);
     482                 :             :       return;
     483                 :             :     }
     484                 :             :     // A name like work/vpn may need its folder; gpg does not create it.
     485                 :          18 :     const QString parent = QFileInfo(Util::joinPath(m_storeRoot, rel)).path();
     486   [ +  +  +  +  :          35 :     if (!QDir(parent).exists() && !Util::mkpathForStore(parent)) {
             +  +  +  +  
                      + ]
     487                 :           2 :       ui->statusLabel->setText(
     488                 :           2 :           tr("Could not create the folder %1.").arg(parent));
     489                 :             :       return;
     490                 :             :     }
     491                 :          17 :     m_file = rel;
     492                 :          34 :     setWindowTitle(tr("Password") + QStringLiteral(" ") + m_file);
     493                 :             :   }
     494                 :          43 :   save();
     495                 :             : }
     496                 :             : 
     497                 :          93 : void PasswordDialog::setPassword(const QString &password) {
     498                 :             :   // Which lines become fields is the user's choice: forcing allFields
     499                 :             :   // (#1138, for #132) made every `key: value` line a label-locked widget,
     500                 :             :   // even with templates off (#1766). MainWindow renders by the same rule.
     501                 :             :   FileContent fileContent =
     502                 :         123 :       FileContent::parse(password, m_templating ? m_fields : QStringList(),
     503   [ +  +  +  +  :         186 :                          m_templating && m_allFields);
                      + ]
     504                 :             :   // As stored, past the line-break filter for input: an unedited save must
     505                 :             :   // write the entry back exactly. The "\r" of a CRLF line end is not part of
     506                 :             :   // the password: it stays out of the field and is written back after it.
     507                 :         186 :   ui->lineEditPassword->setStoredText(fileContent.getPassword());
     508                 :             :   m_passwordLineEnd = QStringView(password)
     509                 :          93 :                               .left(password.indexOf(QLatin1Char('\n')))
     510                 :             :                               .endsWith(u'\r')
     511      [ +  +  + ]:         183 :                           ? QStringLiteral("\r")
     512                 :             :                           : QString();
     513                 :             : 
     514                 :          93 :   QWidget *previous = ui->checkBoxShow;
     515                 :          93 :   NamedValues namedValues = fileContent.getNamedValues();
     516         [ +  + ]:         123 :   for (QLineEdit *line : std::as_const(m_templateLines)) {
     517                 :          60 :     const NamedValue nv = namedValues.takeNamedValue(line->objectName());
     518         [ +  - ]:          30 :     if (auto *secret = qobject_cast<SecretLineEdit *>(line)) {
     519                 :          30 :       secret->setStoredText(nv.value);
     520                 :             :     } else {
     521                 :           0 :       line->setText(nv.value);
     522                 :             :     }
     523                 :          60 :     line->setProperty(kOriginalLineProperty, nv.originalLine);
     524                 :             :     // The value is the entry's again, whatever the user typed before this
     525                 :             :     // reload: not a value normalizeOtpField() may rewrite.
     526                 :          30 :     line->setProperty(kOtpEditedProperty, QVariant());
     527                 :             :     previous = line;
     528                 :          30 :   }
     529                 :             :   // Remove previously created dynamic widgets to prevent duplicates and leaks
     530      [ +  +  + ]:          95 :   for (QLineEdit *line : std::as_const(m_otherLines)) {
     531                 :           2 :     ui->formLayout->removeRow(line);
     532                 :             :   }
     533                 :          93 :   m_otherLines.clear();
     534         [ +  + ]:         141 :   for (const NamedValue &nv : std::as_const(namedValues)) {
     535                 :          48 :     previous = addFieldRow(nv, previous);
     536                 :             :   }
     537                 :             : 
     538                 :             :   // setPlainText, not insertPlainText: re-populating must replace the body,
     539                 :             :   // not save back a duplicated copy.
     540                 :             :   // A run of hundreds of thousands of letters wraps anywhere: at word
     541                 :             :   // boundaries Qt took minutes to lay it out.
     542      [ +  +  + ]:         185 :   ui->plainTextEdit->setWordWrapMode(
     543                 :         186 :       Util::hasLongUnbrokenRun(fileContent.getRemainingData())
     544                 :             :           ? QTextOption::WrapAnywhere
     545                 :             :           : QTextOption::WrapAtWordBoundaryOrAnywhere);
     546                 :          93 :   ui->plainTextEdit->setPlainText(fileContent.getRemainingData());
     547                 :             : 
     548                 :             :   // m_otherLines was just rebuilt, so the OTP field may be a new widget.
     549                 :          93 :   hookOtpField();
     550                 :          93 : }
     551                 :             : 
     552                 :          11 : void PasswordDialog::renameField(QLineEdit *line, FieldLabel *label,
     553                 :             :                                  const QString &to) {
     554                 :             :   QList<QLineEdit *> allLines(m_templateLines);
     555                 :          11 :   allLines.append(m_otherLines);
     556         [ +  + ]:          28 :   for (QLineEdit *other : std::as_const(allLines)) {
     557   [ +  +  +  +  :          25 :     if (other != line && other->objectName() == to) {
                      + ]
     558                 :           2 :       ui->statusLabel->setText(
     559         [ +  + ]:           2 :           tr("A field called %1 already exists.").arg(Util::shownName(to)));
     560                 :             :       return;
     561                 :             :     }
     562                 :             :   }
     563                 :          10 :   ui->statusLabel->clear();
     564                 :          10 :   line->setObjectName(to);
     565                 :          10 :   label->setName(to);
     566                 :             :   // The field may have become, or stopped being, the OTP one.
     567                 :          10 :   hookOtpField();
     568                 :             : }
     569                 :             : 
     570                 :           4 : void PasswordDialog::removeField(QLineEdit *line) {
     571                 :           4 :   m_otherLines.removeAll(line);
     572                 :             :   // takeRow(), not removeRow(): removeRow() deletes the widgets while the
     573                 :             :   // label's contextMenuEvent() or the action's triggered() is still on the
     574                 :             :   // stack. They are deleted once the stack has unwound.
     575                 :           4 :   const QFormLayout::TakeRowResult row = ui->formLayout->takeRow(line);
     576                 :             :   // hide() takes the focus from a focused line, and that emits
     577                 :             :   // editingFinished(): not into normalizeOtpField() for a field that is
     578                 :             :   // being removed.
     579                 :           4 :   disconnect(line, nullptr, this, nullptr);
     580         [ +  + ]:           4 :   if (m_otpLine == line) {
     581                 :             :     m_otpLine = nullptr;
     582                 :             :   }
     583         [ +  + ]:          12 :   for (QLayoutItem *item : {row.labelItem, row.fieldItem}) {
     584         [ -  + ]:           8 :     if (item == nullptr) {
     585                 :           0 :       continue;
     586                 :             :     }
     587         [ +  - ]:           8 :     if (QWidget *widget = item->widget()) {
     588                 :           8 :       widget->hide();
     589                 :           8 :       widget->deleteLater();
     590                 :             :     }
     591                 :           8 :     delete item;
     592                 :             :   }
     593                 :           4 :   hookOtpField();
     594                 :           4 : }
     595                 :             : 
     596                 :         262 : auto PasswordDialog::otpLineEdit() const -> QLineEdit * {
     597                 :             :   QList<QLineEdit *> allLines(m_templateLines);
     598                 :         262 :   allLines.append(m_otherLines);
     599                 :             :   QLineEdit *firstMatch = nullptr;
     600         [ +  + ]:         407 :   for (QLineEdit *line : std::as_const(allLines)) {
     601   [ +  +  +  + ]:         328 :     if (!FileContent::isOtpFieldName(line->objectName())) {
     602                 :         121 :       continue;
     603                 :             :     }
     604                 :             :     // Prefer a populated field: the default template's empty `OTP` widget
     605                 :             :     // would otherwise shadow a `TOTP:` value in m_otherLines, leaving the
     606                 :             :     // real secret unvalidated and unnormalised.
     607      [ +  +  + ]:          86 :     if (!line->text().trimmed().isEmpty()) {
     608                 :             :       return line;
     609                 :             :     }
     610         [ -  + ]:          24 :     if (firstMatch == nullptr) {
     611                 :             :       firstMatch = line;
     612                 :             :     }
     613                 :             :   }
     614                 :             :   return firstMatch;
     615                 :             : }
     616                 :             : 
     617                 :         262 : void PasswordDialog::hookOtpField() {
     618                 :             :   // Only m_otherLines widgets are deleted by removeRow(); a template widget
     619                 :             :   // keeps its action, and the next validate would add a second icon.
     620                 :             :   // m_otpWarning is a QPointer: null when setPassword() deleted its owner.
     621         [ +  + ]:         262 :   if (!m_otpWarning.isNull()) {
     622                 :             :     if (auto *owner = qobject_cast<QWidget *>(m_otpWarning->parent())) {
     623                 :           3 :       owner->removeAction(m_otpWarning);
     624                 :             :     }
     625                 :           3 :     delete m_otpWarning;
     626                 :             :   }
     627                 :             :   m_otpWarning = nullptr;
     628                 :             : 
     629                 :         262 :   QLineEdit *otp = otpLineEdit();
     630                 :             :   // The field that was the OTP one may not be any more (renamed away, or
     631                 :             :   // another one now comes first): it stops being validated and normalised
     632                 :             :   // here, so its OTP hooks go with the role. Its copies are still reported.
     633   [ +  +  +  + ]:         281 :   if (!m_otpLine.isNull() && m_otpLine != otp) {
     634                 :           5 :     disconnect(m_otpLine, &QLineEdit::textChanged, this,
     635                 :             :                &PasswordDialog::validateOtpField);
     636                 :           5 :     disconnect(m_otpLine, &QLineEdit::textEdited, this,
     637                 :             :                &PasswordDialog::markOtpFieldEdited);
     638                 :           5 :     disconnect(m_otpLine, &QLineEdit::editingFinished, this,
     639                 :             :                &PasswordDialog::normalizeOtpField);
     640                 :             :   }
     641                 :             :   m_otpLine = otp;
     642         [ +  + ]:         262 :   if (otp == nullptr) {
     643                 :             :     return;
     644                 :             :   }
     645                 :          41 :   otp->setPlaceholderText(tr("otpauth:// URI or base32 secret"));
     646                 :          41 :   connect(otp, &QLineEdit::textChanged, this, &PasswordDialog::validateOtpField,
     647                 :             :           Qt::UniqueConnection);
     648                 :             :   // textEdited, not textChanged: it fires only for user input, so programmatic
     649                 :             :   // population does not count as the user having touched the field.
     650                 :          41 :   connect(otp, &QLineEdit::textEdited, this,
     651                 :          41 :           &PasswordDialog::markOtpFieldEdited, Qt::UniqueConnection);
     652                 :             :   // Canonicalise as soon as the user leaves the field, so the value they end
     653                 :             :   // up saving is the value they were shown.
     654                 :          41 :   connect(otp, &QLineEdit::editingFinished, this,
     655                 :          41 :           &PasswordDialog::normalizeOtpField, Qt::UniqueConnection);
     656                 :          41 :   validateOtpField();
     657                 :             : }
     658                 :             : 
     659                 :         395 : void PasswordDialog::markOtpFieldEdited() {
     660         [ +  - ]:         395 :   if (QObject *line = sender()) {
     661                 :         790 :     line->setProperty(kOtpEditedProperty, true);
     662                 :             :   }
     663                 :         395 : }
     664                 :             : 
     665                 :         463 : void PasswordDialog::validateOtpField() {
     666                 :             :   // m_otpLine, not otpLineEdit(): the signals that bring us here and the
     667                 :             :   // edit mark are that line's. The OTP role is settled when fields change.
     668                 :             :   QLineEdit *otp = m_otpLine;
     669         [ -  + ]:         463 :   if (otp == nullptr) {
     670                 :           0 :     return;
     671                 :             :   }
     672                 :             : 
     673                 :         463 :   const QString text = otp->text().trimmed();
     674                 :         463 :   Totp::Refusal why = Totp::Refusal::None;
     675   [ +  +  +  +  :         463 :   const bool bad = !text.isEmpty() && !Totp::parse(text, &why).has_value();
                      + ]
     676         [ +  + ]:         463 :   if (bad) {
     677         [ +  + ]:         274 :     if (m_otpWarning.isNull()) {
     678                 :             :       // Theme-aware indicator: no hardcoded colours and no extra layout row.
     679                 :             :       m_otpWarning =
     680                 :         201 :           otp->addAction(QIcon::fromTheme(QStringLiteral("dialog-warning")),
     681                 :          67 :                          QLineEdit::TrailingPosition);
     682                 :             :     }
     683                 :             :     // The reason, where parse() names one: "invalid" alone left the user
     684                 :             :     // guessing whether the secret, the algorithm or the kind was wrong.
     685                 :         274 :     const QString reason = Totp::describe(why);
     686      [ -  +  + ]:         822 :     otp->setToolTip(reason.isEmpty() ? tr("Invalid OTP secret") : reason);
     687                 :             :   } else {
     688         [ +  + ]:         189 :     if (!m_otpWarning.isNull()) {
     689                 :          60 :       otp->removeAction(m_otpWarning);
     690                 :          60 :       delete m_otpWarning;
     691                 :             :       m_otpWarning = nullptr;
     692                 :             :     }
     693                 :         378 :     otp->setToolTip(QString());
     694                 :             :   }
     695                 :             : }
     696                 :             : 
     697                 :             : // Only a value typed or pasted into this field is rewritten; an untouched
     698                 :             : // one, otpauth:// URI or not, is written back as read. Base32::sanitizeInput()
     699                 :             : // maps 1 to L and 8 to B, so a backup code like `12345678` passes as base32
     700                 :             : // and was silently rewritten on any OK. A bare secret left alone still works:
     701                 :             : // Totp::parse() accepts one.
     702                 :          51 : void PasswordDialog::normalizeOtpField() {
     703                 :             :   QLineEdit *otp = m_otpLine;
     704         [ +  + ]:          51 :   if (otp == nullptr) {
     705                 :          36 :     return;
     706                 :             :   }
     707                 :          52 :   const QString text = otp->text().trimmed();
     708         [ +  + ]:          26 :   if (text.isEmpty()) {
     709                 :             :     return;
     710                 :             :   }
     711                 :             :   // Only what the user typed or pasted here: an untouched line is written
     712                 :             :   // back as it was read, as every other untouched line is (#2147).
     713                 :             :   // Canonicalising it on every OK lost parameters with capitalised names, the
     714                 :             :   // text after a "#", and turned backup codes into secrets.
     715   [ +  +  +  + ]:          25 :   if (!otp->property(kOtpEditedProperty).toBool()) {
     716                 :             :     return;
     717                 :             :   }
     718                 :             :   // fileName(), not completeBaseName(): the latter truncates at the last dot,
     719                 :             :   // turning an entry called github.com into a label of "github". m_file already
     720                 :             :   // has its .gpg suffix stripped by MainWindow::getFile().
     721                 :          30 :   const QString canonical = Totp::normalize(text, QFileInfo(m_file).fileName());
     722         [ +  + ]:          15 :   if (!canonical.isEmpty()) {
     723                 :          11 :     otp->setText(canonical);
     724                 :             :   }
     725                 :             : }
     726                 :             : 
     727                 :          82 : auto PasswordDialog::getPassword() -> QString {
     728                 :         164 :   QString passFile = ui->lineEditPassword->text() + m_passwordLineEnd + "\n";
     729                 :             :   QList<QLineEdit *> allLines(m_templateLines);
     730                 :          82 :   allLines.append(m_otherLines);
     731         [ +  + ]:         151 :   for (QLineEdit *line : std::as_const(allLines)) {
     732                 :          69 :     const QString text = line->text();
     733                 :          69 :     const QString name = line->objectName();
     734                 :          69 :     const QString original = line->property(kOriginalLineProperty).toString();
     735                 :             :     // A field whose name and value are still exactly what was parsed keeps its
     736                 :             :     // source line verbatim: reserialising would turn `key:value` into
     737                 :             :     // `key: value`, trim whitespace the value carried, and drop a field with an
     738                 :             :     // empty value (`recovery:`) entirely. The widget holds trimmed name/value,
     739                 :             :     // so compare against the original line split and trimmed the same way.
     740         [ +  + ]:          69 :     if (!original.isEmpty()) {
     741                 :          54 :       const qsizetype colon = original.indexOf(QLatin1Char(':'));
     742   [ +  -  +  +  :         216 :       if (colon >= 0 && original.left(colon).trimmed() == name &&
          +  +  -  +  +  
                   -  - ]
     743   [ +  +  +  +  :         150 :           original.right(original.length() - colon - 1).trimmed() == text) {
             -  -  -  -  
                      - ]
     744                 :          44 :         passFile += original + "\n";
     745                 :          44 :         continue;
     746                 :             :       }
     747                 :             :     }
     748         [ +  + ]:          25 :     if (text.isEmpty()) {
     749                 :           4 :       continue;
     750                 :             :     }
     751                 :          42 :     passFile += name + ": " + text + "\n";
     752                 :             :   }
     753                 :             :   // Not toPlainText(): it saves a blank for every no-break space (U+00A0) in
     754                 :             :   // the notes, so any OK rewrites even lines the user never touched and a
     755                 :             :   // passphrase or recovery code with no-break spaces is corrupted. The raw
     756                 :             :   // document text keeps the no-break spaces; only the block and line
     757                 :             :   // separators it uses are normalised back to '\n'.
     758                 :          82 :   QString notes = ui->plainTextEdit->document()->toRawText();
     759                 :          82 :   notes.replace(QChar(QChar::ParagraphSeparator), QLatin1Char('\n'));
     760                 :          82 :   notes.replace(QChar(QChar::LineSeparator), QLatin1Char('\n'));
     761                 :             :   passFile += notes;
     762                 :          82 :   return passFile;
     763                 :             : }
     764                 :             : 
     765                 :         155 : void PasswordDialog::setTemplate(const QString &rawFields, bool useTemplate) {
     766                 :         155 :   m_fields = TemplateIO::fieldsIn(rawFields);
     767                 :         155 :   m_templating = useTemplate;
     768                 :             : 
     769                 :             :   // removeRow() deletes the line edits, text and all, so what the rows hold
     770                 :             :   // is carried over: switching the template, or Ctrl+T (which with a single
     771                 :             :   // template rebuilds the same rows), used to empty everything typed into
     772                 :             :   // them. A value the new template has a row for goes there; any other stays
     773                 :             :   // a field row of its own, so nothing is dropped and nothing is doubled.
     774                 :         155 :   NamedValues held;
     775                 :             :   QSet<QString> otpTyped;
     776                 :         310 :   const auto holdAndRemove = [this, &held,
     777                 :             :                               &otpTyped](QList<QLineEdit *> &lines) {
     778         [ +  + ]:         326 :     for (QLineEdit *line : std::as_const(lines)) {
     779                 :          16 :       const QString original = line->property(kOriginalLineProperty).toString();
     780                 :             :       // A stored field with no value ("recovery:") has an empty row but a
     781                 :             :       // source line, which getPassword() writes back as it was: keep it too.
     782   [ +  +  +  +  :          32 :       if (!line->text().isEmpty() || !original.isEmpty()) {
                +  +  + ]
     783                 :           8 :         held.append({line->objectName(), line->text(), original});
     784   [ +  +  +  + ]:           8 :         if (line->property(kOtpEditedProperty).toBool()) {
     785                 :           2 :           otpTyped.insert(line->objectName());
     786                 :             :         }
     787                 :             :       }
     788                 :          16 :       ui->formLayout->removeRow(line);
     789                 :             :     }
     790                 :         310 :     lines.clear();
     791                 :         318 :   };
     792                 :         155 :   holdAndRemove(m_templateLines);
     793                 :         155 :   holdAndRemove(m_otherLines);
     794                 :             : 
     795                 :         155 :   QWidget *previous = ui->checkBoxShow;
     796         [ +  + ]:         155 :   if (m_templating) {
     797         [ +  + ]:         199 :     for (const QString &field : std::as_const(m_fields)) {
     798         [ +  + ]:         104 :       if (field.isEmpty()) {
     799                 :          42 :         continue;
     800                 :             :       }
     801                 :          62 :       auto *line = new SecretLineEdit();
     802                 :          62 :       reportCopies(line);
     803                 :             :       // Plain text before the name is set: the template comes from the
     804                 :             :       // store, and as rich text <img src="/dev/zero"> has Qt read that file
     805                 :             :       // without end.
     806                 :          62 :       auto *label = new QLabel();
     807                 :          62 :       label->setTextFormat(Qt::PlainText);
     808                 :          62 :       label->setText(Util::shownName(field));
     809                 :          62 :       line->setObjectName(field);
     810                 :          62 :       const NamedValue kept = held.takeNamedValue(field);
     811         [ +  + ]:          62 :       if (!kept.name.isEmpty()) {
     812                 :           2 :         line->setStoredText(kept.value);
     813                 :           4 :         line->setProperty(kOriginalLineProperty, kept.originalLine);
     814         [ -  + ]:           2 :         if (otpTyped.contains(field)) {
     815                 :           0 :           line->setProperty(kOtpEditedProperty, true);
     816                 :             :         }
     817                 :             :       }
     818                 :          62 :       ui->formLayout->addRow(label, line);
     819                 :          62 :       setTabOrder(previous, line);
     820                 :          62 :       m_templateLines.append(line);
     821                 :             :       previous = line;
     822                 :          62 :     }
     823                 :             :   }
     824         [ +  + ]:         161 :   for (const NamedValue &field : std::as_const(held)) {
     825                 :           6 :     SecretLineEdit *line = addFieldRow(field, previous);
     826                 :             :     // A typed OTP value keeps its mark in a field row too, so save() still
     827                 :             :     // turns a bare secret into an otpauth:// URI.
     828         [ +  + ]:           6 :     if (otpTyped.contains(field.name)) {
     829                 :           2 :       line->setProperty(kOtpEditedProperty, true);
     830                 :             :     }
     831                 :             :     previous = line;
     832                 :             :   }
     833                 :             : 
     834                 :         155 :   hookOtpField();
     835                 :         155 : }
     836                 :             : 
     837                 :         257 : void PasswordDialog::reportCopies(SecretLineEdit *line) {
     838                 :         257 :   connect(line, &SecretLineEdit::copied, this, &PasswordDialog::copied);
     839                 :         257 : }
     840                 :             : 
     841                 :          54 : auto PasswordDialog::addFieldRow(const NamedValue &field, QWidget *previous)
     842                 :             :     -> SecretLineEdit * {
     843                 :          54 :   auto *line = new SecretLineEdit();
     844                 :          54 :   reportCopies(line);
     845                 :          54 :   line->setObjectName(field.name);
     846                 :          54 :   line->setStoredText(field.value);
     847                 :         108 :   line->setProperty(kOriginalLineProperty, field.originalLine);
     848                 :          54 :   auto *label = new FieldLabel(field.name);
     849                 :          54 :   label->setBuddy(line);
     850                 :          54 :   ui->formLayout->addRow(label, line);
     851                 :          54 :   setTabOrder(previous, line);
     852                 :          54 :   m_otherLines.append(line);
     853                 :             :   // Both widgets are rows of the form; removeRow() deletes them together,
     854                 :             :   // so a rename or removal that arrives afterwards finds no receiver.
     855                 :          54 :   connect(label, &FieldLabel::renamed, this,
     856                 :          54 :           [this, line, label](const QString &, const QString &to) {
     857                 :          11 :             renameField(line, label, to);
     858                 :             :           });
     859                 :          54 :   connect(label, &FieldLabel::removeRequested, this,
     860                 :          55 :           [this, line] { removeField(line); });
     861                 :          54 :   connect(label, &FieldLabel::copied, this, &PasswordDialog::copied);
     862                 :             :   // The visible way to remove the field; the context menu is the other.
     863                 :         108 :   auto *remove = line->addAction(
     864                 :         162 :       QIcon::fromTheme(QStringLiteral("edit-delete"),
     865                 :         162 :                        QIcon(QStringLiteral(":/icons/edit-delete.svg"))),
     866                 :             :       QLineEdit::TrailingPosition);
     867                 :         108 :   remove->setObjectName(QStringLiteral("removeFieldAction"));
     868                 :          54 :   remove->setToolTip(tr("Remove field"));
     869                 :          54 :   connect(remove, &QAction::triggered, this,
     870                 :          57 :           [this, line] { removeField(line); });
     871                 :          54 :   return line;
     872                 :             : }
     873                 :             : 
     874                 :         123 : void PasswordDialog::templateAll(bool templateAll) {
     875                 :         123 :   m_allFields = templateAll;
     876                 :         123 : }
     877                 :             : 
     878                 :         144 : void PasswordDialog::setLength(int length) {
     879                 :         144 :   ui->spinBox_pwdLength->setValue(length);
     880                 :         144 : }
     881                 :             : 
     882                 :         145 : void PasswordDialog::setPasswordCharTemplate(int templateIndex) {
     883                 :         145 :   ui->passwordTemplateSwitch->setCurrentIndex(templateIndex);
     884                 :         145 : }
     885                 :             : 
     886                 :         119 : void PasswordDialog::usePwgen(bool usePwgen) {
     887                 :         119 :   m_usePwgen = usePwgen;
     888                 :         119 :   ui->passwordTemplateSwitch->setDisabled(usePwgen);
     889                 :         119 :   ui->label_characterset->setDisabled(usePwgen);
     890                 :         119 : }
     891                 :             : 
     892                 :             : // The template row stays hidden until setAvailableTemplates() fills it.
     893                 :         141 : void PasswordDialog::setupTemplateBox() {
     894                 :         141 :   ui->label_template->hide();
     895                 :         141 :   ui->templateBox->hide();
     896                 :             :   // The names are the items' data; the text shown may be cut.
     897                 :         141 :   ui->templateBox->setSizeAdjustPolicy(
     898                 :             :       QComboBox::AdjustToMinimumContentsLengthWithIcon);
     899                 :         141 :   ui->templateBox->setMinimumContentsLength(20);
     900                 :         141 :   connect(ui->templateBox, &QComboBox::currentIndexChanged, this, [this] {
     901                 :             :     // applyTemplate() rebuilds the field rows, so only act on a real
     902                 :             :     // change; the box is also updated from applyTemplate() itself.
     903                 :           6 :     const QString name = ui->templateBox->currentData().toString();
     904         [ +  - ]:           6 :     if (name != m_currentTemplateName) {
     905                 :           6 :       applyTemplate(name);
     906                 :             :     }
     907                 :           6 :   });
     908                 :         141 : }
     909                 :             : 
     910                 :          15 : void PasswordDialog::setAvailableTemplates(
     911                 :             :     const QHash<QString, QStringList> &templates,
     912                 :             :     const QString &defaultTemplate) {
     913                 :          15 :   m_availableTemplates = templates;
     914                 :          15 :   QStringList templateNames = templates.keys();
     915         [ -  + ]:          15 :   if (templateNames.isEmpty()) {
     916                 :             :     return;
     917                 :             :   }
     918                 :          30 :   std::sort(templateNames.begin(), templateNames.end());
     919                 :             :   {
     920                 :          15 :     const QSignalBlocker blocker(ui->templateBox);
     921                 :          15 :     ui->templateBox->clear();
     922         [ +  + ]:          43 :     for (const QString &name : std::as_const(templateNames)) {
     923                 :          56 :       ui->templateBox->addItem(Util::shownName(name), name);
     924                 :          28 :       ui->templateBox->setItemData(ui->templateBox->count() - 1,
     925                 :          84 :                                    Util::plainToolTip(name), Qt::ToolTipRole);
     926                 :             :     }
     927                 :          15 :   }
     928                 :          15 :   ui->label_template->show();
     929                 :          15 :   ui->templateBox->show();
     930         [ +  - ]:          15 :   if (!m_templateShortcut) {
     931                 :          15 :     m_templateShortcut = new QShortcut(QKeySequence(Qt::CTRL | Qt::Key_T), this,
     932      [ +  +  + ]:          18 :                                        this, [this] { cycleTemplate(); });
     933                 :             :   }
     934                 :             :   QString selected = defaultTemplate;
     935         [ +  + ]:          15 :   if (!templateNames.contains(selected)) {
     936                 :           1 :     selected = templateNames.first();
     937                 :             :   }
     938                 :          15 :   applyTemplate(selected);
     939                 :             : }
     940                 :             : 
     941                 :          25 : void PasswordDialog::applyTemplate(const QString &templateName) {
     942         [ +  + ]:          25 :   if (m_saving) {
     943                 :           1 :     return;
     944                 :             :   }
     945                 :          24 :   auto it = m_availableTemplates.constFind(templateName);
     946                 :             :   if (it != m_availableTemplates.constEnd()) {
     947                 :          24 :     m_currentTemplateName = templateName;
     948                 :          24 :     const QSignalBlocker blocker(ui->templateBox);
     949                 :          24 :     ui->templateBox->setCurrentIndex(ui->templateBox->findData(templateName));
     950                 :          24 :     QString fields = it.value().join("\n");
     951                 :          24 :     setTemplate(fields, true);
     952                 :          24 :   }
     953                 :             : }
     954                 :             : 
     955                 :           7 : void PasswordDialog::cycleTemplate() {
     956                 :             :   if (m_availableTemplates.isEmpty()) {
     957                 :           3 :     return;
     958                 :             :   }
     959                 :           5 :   QStringList names = m_availableTemplates.keys();
     960                 :          10 :   std::sort(names.begin(), names.end());
     961                 :             : 
     962                 :             :   qsizetype currentIdx = names.indexOf(m_currentTemplateName);
     963                 :             :   qsizetype nextIdx;
     964         [ +  - ]:           5 :   if (currentIdx < 0) {
     965                 :             :     nextIdx = 0;
     966                 :             :   } else {
     967                 :           5 :     nextIdx = (currentIdx + 1) % names.size();
     968                 :             :   }
     969                 :             :   // With a single template there is nothing to switch to: leave the rows,
     970                 :             :   // and the cursor in them, alone.
     971         [ +  + ]:           5 :   if (names.at(nextIdx) == m_currentTemplateName) {
     972                 :             :     return;
     973                 :             :   }
     974                 :           4 :   applyTemplate(names.at(nextIdx));
     975                 :             : }
     976                 :             : 
     977                 :          93 : void PasswordDialog::setPass(const QString &output, const QString &file,
     978                 :             :                              bool lossless) {
     979                 :             :   // finishedShow names its file: a decrypt of any other entry (a tree click
     980                 :             :   // that was still queued when the dialog opened) is not ours.
     981   [ +  +  +  + ]:          93 :   if (!file.isEmpty() && file != m_file) {
     982                 :          11 :     return;
     983                 :             :   }
     984                 :             :   // A refusal also takes back an earlier load of this entry: a later answer
     985                 :             :   // for it says the entry is not one this dialog can save, so OK must not
     986                 :             :   // write what was loaded before.
     987                 :           9 :   const auto refuse = [this](const QString &why) {
     988                 :           9 :     m_contentLoaded = false;
     989                 :           9 :     setEditorEnabled(false);
     990                 :           9 :     ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
     991                 :           9 :     ui->statusLabel->setText(why);
     992                 :         101 :   };
     993                 :             :   // Bytes that are not UTF-8 (a password typed on a Latin-1 terminal, a key
     994                 :             :   // file stored with `pass insert -m`) reach here as U+FFFD (on Windows as
     995                 :             :   // characters of the code page), a leading byte order mark not at all, and
     996                 :             :   // OK writes the whole entry back from this text: those bytes were changed
     997                 :             :   // for good, with the save reported as done. Not loaded, as below, so nothing
     998                 :             :   // is saved over the entry; showing and copying it are unaffected.
     999         [ +  + ]:          92 :   if (!lossless) {
    1000                 :           3 :     refuse(tr("This entry contains bytes QtPass cannot save unchanged, so it "
    1001                 :             :               "cannot be edited here."));
    1002                 :           3 :     return;
    1003                 :             :   }
    1004                 :             :   // An editor block per line: an entry of millions of lines (a small,
    1005                 :             :   // compressed one in a shared store can be one) would take QtPass down.
    1006                 :             :   // Not loaded at all, so nothing can be saved over it from here either.
    1007                 :             :   // Counted as an editor of the whole entry would hold it: the final
    1008                 :             :   // newline pass and QtPass write ends the last line, it starts no new one.
    1009                 :             :   // Password and fields count too, so this is stricter than the display's
    1010                 :             :   // limit on the remaining text alone.
    1011                 :             :   // Every block break counts, not only "\n": the editor starts a block at
    1012                 :             :   // a carriage return and U+2029 too ("\r\n" is one).
    1013                 :          89 :   if (const qsizetype lines =
    1014                 :             :           std::count_if(output.cbegin(), output.cend(),
    1015                 :             :                         [](QChar c) {
    1016   [ +  +  +  + ]:     9592815 :                           return c == QLatin1Char('\n') ||
    1017                 :     4781324 :                                  Util::isOtherBlockBreak(c);
    1018         [ +  + ]:          89 :                         }) -
    1019                 :         178 :           output.count(QStringLiteral("\r\n")) +
    1020   [ +  +  +  +  :         165 :           (output.isEmpty() || output.endsWith(QLatin1Char('\n')) ? 0 : 1);
                      + ]
    1021                 :             :       lines > FileContent::kMaxDisplayLines) {
    1022                 :             :     // The count in a variable first, as in FileContent: older lupdate
    1023                 :             :     // versions lose a tr() with template arguments among its arguments.
    1024                 :             :     const int n = static_cast<int>(
    1025                 :           4 :         std::min<qsizetype>(lines, std::numeric_limits<int>::max()));
    1026                 :           8 :     refuse(tr("This entry has %n line(s), too many to edit here.", nullptr, n));
    1027                 :             :     return;
    1028                 :             :   }
    1029                 :             :   // A password or field longer than its line edit holds would be cut on
    1030                 :             :   // load and the cut value saved. Every line counts: a template switch can
    1031                 :             :   // make a line of the notes a field. The CR of a CRLF line end is not
    1032                 :             :   // part of what a field holds (FileContent::passwordLine()).
    1033                 :          85 :   qsizetype longest = 0;
    1034   [ +  +  +  + ]:       20336 :   for (QStringView line : QStringView(output).tokenize(u'\n')) {
    1035                 :             :     if (line.endsWith(u'\r')) {
    1036                 :             :       line.chop(1);
    1037                 :             :     }
    1038                 :       20251 :     longest = std::max(longest, line.size());
    1039                 :             :   }
    1040         [ +  + ]:          85 :   if (longest > SecretLineEdit::kMaxLength) {
    1041                 :             :     const int n = static_cast<int>(
    1042                 :           2 :         std::min<qsizetype>(longest, std::numeric_limits<int>::max()));
    1043                 :           2 :     refuse(tr("This entry has a line of %n character(s), too long to edit "
    1044                 :             :               "here.",
    1045                 :             :               nullptr, n));
    1046                 :           2 :     return;
    1047                 :             :   }
    1048                 :             :   // Loaded already: a later decrypt of this entry (Edit run again while the
    1049                 :             :   // first was slow, a second `qtpass` launch) must not put the stored text
    1050                 :             :   // back over what the user typed, which OK would then save as if it were
    1051                 :             :   // the change. A refusal above still takes the load back.
    1052         [ +  + ]:          83 :   if (m_contentLoaded) {
    1053                 :             :     return;
    1054                 :             :   }
    1055                 :          82 :   setPassword(output);
    1056                 :          82 :   m_contentLoaded = true;
    1057                 :             :   // Drop the "Decrypting…" note so it cannot be mistaken for a warning.
    1058                 :          82 :   ui->statusLabel->clear();
    1059                 :          82 :   setEditorEnabled(true);
    1060                 :          82 :   ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(true);
    1061                 :             : }
    1062                 :             : 
    1063                 :           2 : void PasswordDialog::onShowError(int /* exitCode */, const QString &err) {
    1064                 :             :   // React only while the dialog is still waiting for its own decrypt.
    1065                 :             :   // processErrorExit carries no request identity, but for an existing entry
    1066                 :             :   // the only Pass operation in flight is the Show() that opened this dialog.
    1067   [ +  -  +  + ]:           2 :   if (m_isNew || m_contentLoaded) {
    1068                 :             :     return;
    1069                 :             :   }
    1070                 :           1 :   ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
    1071                 :           1 :   setEditorEnabled(false);
    1072                 :           1 :   ui->statusLabel->setText(err);
    1073                 :             : }
    1074                 :             : 
    1075                 :         241 : void PasswordDialog::setEditorEnabled(bool enabled) {
    1076                 :         241 :   ui->lineEditPassword->setEnabled(enabled);
    1077                 :         241 :   ui->createPasswordButton->setEnabled(enabled);
    1078                 :         241 :   ui->checkBoxShow->setEnabled(enabled);
    1079                 :         241 :   ui->passwordTemplateSwitch->setEnabled(enabled);
    1080                 :         241 :   ui->label_characterset->setEnabled(enabled);
    1081                 :         241 :   ui->spinBox_pwdLength->setEnabled(enabled);
    1082                 :         241 :   ui->plainTextEdit->setEnabled(enabled);
    1083         [ +  + ]:         314 :   for (QLineEdit *line : std::as_const(m_templateLines)) {
    1084                 :          73 :     line->setEnabled(enabled);
    1085                 :             :   }
    1086         [ +  + ]:         298 :   for (QLineEdit *line : std::as_const(m_otherLines)) {
    1087                 :          57 :     line->setEnabled(enabled);
    1088                 :             :   }
    1089                 :             :   // Re-apply the pwgen policy on the way back up, or the two widgets usePwgen()
    1090                 :             :   // locks would be spuriously re-enabled with the rest of the editor.
    1091   [ +  +  -  + ]:         241 :   if (enabled && m_usePwgen) {
    1092                 :           0 :     usePwgen(true);
    1093                 :             :   }
    1094                 :         241 : }
        

Generated by: LCOV version 2.0-1