QtPass Developer documentation
QtPass test coverage
Current view: top level - src/passworddialog.h Coverage Total Hit
Test: QtPass Lines: 100.0 % 1 1
Test Date: 2026-12-03 23:34:20 Functions: - 0 0

            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 Dialog for creating or editing one password entry, including the
       6              :  * generator, template fields, OTP handling and the asynchronous save.
       7              :  */
       8              : #ifndef SRC_PASSWORDDIALOG_H_
       9              : #define SRC_PASSWORDDIALOG_H_
      10              : 
      11              : #include "appsettings.h"
      12              : 
      13              : #include <QDialog>
      14              : #include <QPointer>
      15              : #include <QScopedPointer>
      16              : 
      17              : namespace Ui {
      18              : class PasswordDialog;
      19              : }
      20              : 
      21              : class Pass;
      22              : class FieldLabel;
      23              : struct NamedValue;
      24              : class QAction;
      25              : class QLineEdit;
      26              : class SecretLineEdit;
      27              : class QShortcut;
      28              : class QWidget;
      29              : 
      30              : /**
      31              :  * @class PasswordDialog
      32              :  * @ingroup ui
      33              :  * @brief Dialog for creating a password entry or editing an existing one.
      34              :  *
      35              :  * The first line is the password, with a generator beside it; below it are
      36              :  * one field per template line when templates are in use, and a free text
      37              :  * box for everything else. For an existing entry the dialog asks the
      38              :  * backend to Show() it and fills the fields when the content arrives. On OK
      39              :  * it puts the entry together again and calls Pass::Insert(), then stays
      40              :  * open with its fields locked until the backend reports: it closes on
      41              :  * Pass::finishedInsert() and gives the fields back with the reason on
      42              :  * Pass::insertFailed(), so a failed save never loses what was typed.
      43              :  */
      44              : class PasswordDialog : public QDialog {
      45          372 :   Q_OBJECT
      46              : 
      47              : public:
      48              :   /**
      49              :    * @brief Construct a PasswordDialog for entering a new password.
      50              :    * @param passConfig Password generation configuration.
      51              :    * @param parent Optional parent widget.
      52              :    */
      53              :   explicit PasswordDialog(PasswordConfiguration passConfig,
      54              :                           QWidget *parent = nullptr);
      55              :   /**
      56              :    * @brief Construct a PasswordDialog for editing an existing password file.
      57              :    * @param pass Backend used to show, insert, and generate passwords.
      58              :    * @param s Application settings snapshot (password config, template, pwgen).
      59              :    * @param file Path to the password file being edited.
      60              :    * @param isNew true if creating a new entry, false if editing existing.
      61              :    * @param parent Optional parent widget.
      62              :    */
      63              :   PasswordDialog(Pass *pass, const AppSettings &s, QString file,
      64              :                  const bool &isNew, QWidget *parent = nullptr);
      65              :   /**
      66              :    * @brief Hides the window before QDialog tears it down, so the focus-out
      67              :    * emitted on hiding cannot reach slots of a half-destroyed dialog.
      68              :    */
      69              :   ~PasswordDialog() override;
      70              : 
      71              :   /**
      72              :    * @brief OK: for a new entry, resolve and check the name first and stay
      73              :    * open when it is not usable; then insert the entry and close as accepted
      74              :    * only once the insert has succeeded.
      75              :    *
      76              :    * The insert is asynchronous. Until it reports back the dialog stays open
      77              :    * with its fields locked; when it fails (a missing recipient key, an
      78              :    * unusable `.gpg-id`, a refused path) the fields come back with what was
      79              :    * typed and the reason is shown, instead of the entry being lost with the
      80              :    * closed dialog.
      81              :    */
      82              :   void accept() override;
      83              : 
      84              :   /**
      85              :    * @brief Cancel, Esc and the window's close button. While an insert is in
      86              :    * flight they ask first: closing then means a failure can no longer hand
      87              :    * back what was typed, but a save that never reports must not leave
      88              :    * quitting as the only way out.
      89              :    */
      90              :   void reject() override;
      91              : 
      92              :   /**
      93              :    * @brief Let a new entry be named inside the dialog: a folder picker over
      94              :    * the store's folders and a name field, instead of a separate prompt.
      95              :    *
      96              :    * The dialog validates as the user types (empty, escaping the store,
      97              :    * already taken) and keeps OK off until the name is good; accept() then
      98              :    * creates any subfolder the name needs and inserts the entry at
      99              :    * entryPath(). Only meaningful for a dialog constructed with isNew.
     100              :    * @param storeRoot Absolute path of the password store.
     101              :    * @param folders Folders relative to the store, "" for the root; shown in
     102              :    *        the picker in this order.
     103              :    * @param currentFolder The folder to preselect (relative, may be "").
     104              :    */
     105              :   void setNewEntryLocation(const QString &storeRoot, const QStringList &folders,
     106              :                            const QString &currentFolder);
     107              : 
     108              :   /**
     109              :    * @brief The entry the dialog writes to, relative to the store and
     110              :    * without the `.gpg` suffix (for example `work/vpn`).
     111              :    * @return The path; for an existing entry the one given at construction.
     112              :    */
     113              :   auto entryPath() const -> QString { return m_file; }
     114              : 
     115              :   /**
     116              :    * @brief Populate the dialog's password field with the given text.
     117              :    * @param password Password text to display.
     118              :    * @sa getPassword
     119              :    */
     120              :   void setPassword(const QString &password);
     121              : 
     122              :   /**
     123              :    * @brief Retrieve the current text from the dialog's password field.
     124              :    * @return Current password as a QString.
     125              :    * @sa setPassword
     126              :    */
     127              :   auto getPassword() -> QString;
     128              : 
     129              :   /**
     130              :    * @brief Set the template fields and whether templating is enabled.
     131              :    * @param rawFields Template text containing field definitions.
     132              :    * @param useTemplate true to enable the template, false to disable.
     133              :    */
     134              :   void setTemplate(const QString &rawFields, bool useTemplate);
     135              : 
     136              :   /**
     137              :    * @brief Whether every `key: value` line becomes a field of its own.
     138              :    *
     139              :    * Mirrors the "Template all fields" setting. Off, only the template's
     140              :    * fields get widgets and every other line stays in the free-text body,
     141              :    * where the user can edit key and value alike.
     142              :    * @param templateAll true to split every tokenisable line into a field.
     143              :    */
     144              :   void templateAll(bool templateAll);
     145              : 
     146              :   /**
     147              :    * @brief Set the desired password length shown in the dialog.
     148              :    * @param length Desired password length.
     149              :    */
     150              :   void setLength(int length);
     151              : 
     152              :   /**
     153              :    * @brief Set the password character template index.
     154              :    * @param templateIndex Index identifying the character template to use.
     155              :    */
     156              :   void setPasswordCharTemplate(int templateIndex);
     157              : 
     158              :   /**
     159              :    * @brief Enable or disable pwgen-style password generation mode.
     160              :    * @param usePwgen true to enable pwgen mode, false to disable.
     161              :    */
     162              :   void usePwgen(bool usePwgen);
     163              : 
     164              :   /**
     165              :    * @brief Set available templates from file and select default.
     166              :    * @param templates Hash of template name to field list.
     167              :    * @param defaultTemplate Name of default template.
     168              :    */
     169              :   void setAvailableTemplates(const QHash<QString, QStringList> &templates,
     170              :                              const QString &defaultTemplate);
     171              : 
     172              : signals:
     173              :   /**
     174              :    * @brief Text was copied out of the password, a field or the body, marked
     175              :    * as a secret: for ClipboardManager::trackCopied(), so autoclear clears it.
     176              :    * @param text The text copied.
     177              :    */
     178              :   void copied(const QString &text);
     179              : 
     180              : public slots:
     181              :   /**
     182              :    * @brief Cycle to next template (Ctrl+T).
     183              :    */
     184              :   void cycleTemplate();
     185              : 
     186              :   /**
     187              :    * @brief Populate the dialog from a decrypted entry (Pass::finishedShow).
     188              :    *
     189              :    * Entries with more than FileContent::kMaxDisplayLines lines or a line
     190              :    * longer than SecretLineEdit::kMaxLength, and entries whose text does not
     191              :    * encode back to their bytes (@p lossless false), are not loaded at all; the
     192              :    * status label says so and the editor stays locked.
     193              :    * Once the entry is loaded, a later decrypt of it does not fill the form
     194              :    * again: it would put the stored text back over what the user typed.
     195              :    * @param output Decrypted content of the entry.
     196              :    * @param file The entry the output belongs to; output for any other entry
     197              :    *        than the one being edited is ignored. Empty means unspecified.
     198              :    * @param lossless false when @p output does not encode back to the entry's
     199              :    *        bytes (Pass::finishedShow()): saving it would change them.
     200              :    */
     201              :   void setPass(const QString &output, const QString &file = QString(),
     202              :                bool lossless = true);
     203              : 
     204              : private slots:
     205              :   /**
     206              :    * @brief Show or mask the password field.
     207              :    *
     208              :    * Connected explicitly to QCheckBox::toggled in both constructors; the box
     209              :    * is two-state, so the deprecated stateChanged(int) is not needed.
     210              :    * @param show true to display the password in clear text.
     211              :    */
     212              :   void setPasswordVisible(bool show);
     213              :   /**
     214              :    * @brief "Generate" button: asks the backend for a password of the chosen
     215              :    * length from the selected character set (Pass::generatePassword, which
     216              :    * runs pwgen when that mode is on) and puts it in the password field. An
     217              :    * empty result leaves the field alone.
     218              :    */
     219              :   void on_createPasswordButton_clicked();
     220              :   /**
     221              :    * @brief Connected to QDialog::rejected: blanks the password and field
     222              :    * widgets so the decrypted secret does not linger in a dialog that is
     223              :    * being discarded.
     224              :    */
     225              :   void on_rejected();
     226              : 
     227              :   /**
     228              :    * @brief The insert started by accept() succeeded: close as accepted.
     229              :    */
     230              :   void onInsertFinished();
     231              :   /**
     232              :    * @brief The insert started by accept() failed: unlock the fields, which
     233              :    * still hold what was typed, and show why.
     234              :    * @param err The reason reported by the backend.
     235              :    * @param written true when the entry was written and only a later step
     236              :    *        (git) failed; a new entry then closes the dialog.
     237              :    */
     238              :   void onInsertFailed(const QString &err, bool written);
     239              : 
     240              :   /**
     241              :    * @brief Handle a process error while waiting for an entry's decrypt.
     242              :    *
     243              :    * When the asynchronous Show() fails, keep the dialog open and surface the
     244              :    * reason in statusLabel instead of closing silently: Ok stays disabled and
     245              :    * the editor keeps its lock so the user can only Cancel/withdraw.
     246              :    * @param exitCode Exit code of the failed process (unused).
     247              :    * @param err Error output to present to the user.
     248              :    */
     249              :   void onShowError(int exitCode, const QString &err);
     250              : 
     251              : private:
     252              :   /**
     253              :    * @brief Forwards the line edit's SecretLineEdit::copied to this dialog's
     254              :    * copied(), so every copy out of any field reaches ClipboardManager.
     255              :    * @param line A password or field editor just created.
     256              :    */
     257              :   void reportCopies(SecretLineEdit *line);
     258              :   /**
     259              :    * @brief Adds a row for a field outside the template: a FieldLabel that
     260              :    * can be renamed or removed, and a line edit holding the value as stored.
     261              :    * @param field The field's name, value and verbatim source line.
     262              :    * @param previous The widget before it in the tab order.
     263              :    * @return The new line edit, also appended to m_otherLines.
     264              :    */
     265              :   auto addFieldRow(const NamedValue &field, QWidget *previous)
     266              :       -> SecretLineEdit *;
     267              :   /**
     268              :    * @brief Locate the field that holds the one-time password configuration.
     269              :    * @return The matching QLineEdit, or nullptr when the entry has no OTP field.
     270              :    */
     271              :   [[nodiscard]] auto otpLineEdit() const -> QLineEdit *;
     272              :   /**
     273              :    * @brief Enabled or grey out every editable field of the dialog.
     274              :    *
     275              :    * Used while an existing entry's decrypted content is being fetched, so an
     276              :    * early Ok cannot report success while writing nothing and a late setPass()
     277              :    * cannot clobber edits made on the still-empty fields.
     278              :    * @param enabled true to restore the editor, false to lock it.
     279              :    */
     280              :   void setEditorEnabled(bool enabled);
     281              :   /**
     282              :    * @brief Start inserting what the dialog holds and wait for the result.
     283              :    */
     284              :   void save();
     285              :   /**
     286              :    * @brief Lock or unlock the dialog while an insert is in flight.
     287              :    * @param saving true while waiting for the backend.
     288              :    */
     289              :   void setSaving(bool saving);
     290              :   /**
     291              :    * @brief Whether the insert report now arriving is this dialog's own.
     292              :    *
     293              :    * False when the dialog is not saving. Otherwise it lets the reports of the
     294              :    * inserts that were already pending when save() ran pass first (one per
     295              :    * call), so an earlier dialog's result does not close or fail this one.
     296              :    * @return true when the arriving report belongs to this dialog's insert.
     297              :    */
     298              :   auto isOwnInsertReport() -> bool;
     299              :   /**
     300              :    * @brief Say why the entry was not saved and let the user try again; the
     301              :    * fields keep what was typed.
     302              :    * @param err The reason reported by the backend.
     303              :    */
     304              :   void showNotSaved(const QString &err);
     305              :   /**
     306              :    * @brief Connect validation and normalisation to the OTP field, if present.
     307              :    *
     308              :    * Called whenever the field widgets are rebuilt, since both setTemplate()
     309              :    * and setPassword() recreate them.
     310              :    */
     311              :   void hookOtpField();
     312              :   /**
     313              :    * @brief Flag an OTP value that is neither a URI nor valid base32.
     314              :    */
     315              :   void validateOtpField();
     316              :   /**
     317              :    * @brief Remember, on the line edit that sent textEdited(), that the user
     318              :    * typed in it: only such a field has a bare secret canonicalised, a loaded
     319              :    * value is kept as it was. The mark lives on the widget, not on the dialog,
     320              :    * so typing into a field that used to be the OTP one (renamed away) says
     321              :    * nothing about the field that is the OTP one now. A member function:
     322              :    * Qt::UniqueConnection, which hookOtpField() needs because it runs more
     323              :    * than once for the same field, is refused for a lambda (a debug build
     324              :    * asserts, a release build makes no connection).
     325              :    */
     326              :   void markOtpFieldEdited();
     327              :   /**
     328              :    * @brief Rewrite the OTP field as a canonical otpauth URI.
     329              :    *
     330              :    * A value that cannot be parsed is left exactly as the user typed it, so
     331              :    * nothing is silently destroyed.
     332              :    */
     333              :   void normalizeOtpField();
     334              : 
     335              :   /** @brief Generated form (`passworddialog.ui`); owned. */
     336              :   QScopedPointer<Ui::PasswordDialog> ui;
     337              :   /** @brief Generator settings: character sets and default length. */
     338              :   PasswordConfiguration m_passConfig;
     339              :   /** @brief Backend for Show, Insert and generatePassword; not owned. */
     340              :   Pass *m_pass{nullptr};
     341              :   /** @brief Field names of the current template, in template order. */
     342              :   QStringList m_fields;
     343              :   /** @brief Entry path relative to the store, without `.gpg`; empty for a
     344              :    * new entry until accept() resolves the typed name. */
     345              :   QString m_file;
     346              :   /// Absolute store root while a new entry is being named; empty otherwise.
     347              :   QString m_storeRoot;
     348              :   /// Folder chosen when the dialog opened; the template default follows the
     349              :   /// picker, so this is what setAvailableTemplates() was computed for.
     350              :   QString m_newEntryFolder;
     351              : 
     352              :   /**
     353              :    * @brief The name the user typed, resolved against the picked folder.
     354              :    * @param problem Receives a translated reason when the name is unusable.
     355              :    * @return The relative entry path, or an empty string on a problem.
     356              :    */
     357              :   auto resolveNewEntry(QString *problem) const -> QString;
     358              :   /**
     359              :    * @brief Why a name inside the store cannot be saved as a new entry: it
     360              :    * would be hidden, lies behind a link, or is taken by an entry or folder.
     361              :    * @param absolute The entry's absolute path, without `.gpg`.
     362              :    * @param rel The same path relative to the store root.
     363              :    * @return A translated reason, or an empty string when the name is free.
     364              :    */
     365              :   auto whyNotSavedAs(const QString &absolute, const QString &rel) const
     366              :       -> QString;
     367              :   /**
     368              :    * @brief Re-runs resolveNewEntry() as the user types or picks a folder:
     369              :    * shows the problem (if any) in the status label and enables OK only for a
     370              :    * usable name.
     371              :    */
     372              :   void validateNewEntry();
     373              :   /**
     374              :    * @brief Give a `key: value` field a new key (#132). Refused, with the
     375              :    *        reason in the status label, when another field has that name.
     376              :    *        Re-runs hookOtpField(), as the field may have become or stopped
     377              :    *        being the OTP one.
     378              :    * @param line The field's editor; its object name is the key.
     379              :    * @param label The field's label, updated to show the new key.
     380              :    * @param to The new key.
     381              :    */
     382              :   void renameField(QLineEdit *line, FieldLabel *label, const QString &to);
     383              :   /**
     384              :    * @brief Drop a `key: value` field and its row from the form. The widgets
     385              :    * are deleted once control is back in the event loop: the request comes
     386              :    * from the line's own trailing action or its label's context menu, both
     387              :    * still on the stack.
     388              :    * @param line The field's editor, one of m_otherLines.
     389              :    */
     390              :   void removeField(QLineEdit *line);
     391              :   /** @brief Whether template fields get widgets of their own (the
     392              :    * "Use template" setting). */
     393              :   bool m_templating{};
     394              :   /** @brief Whether every `key: value` line becomes a field (the "Template
     395              :    * all fields" setting), as given to FileContent::parse(). */
     396              :   bool m_allFields{};
     397              :   /** @brief True when creating an entry, false when editing one; decides
     398              :    * whether the name row and the decrypt-before-edit lock apply. */
     399              :   bool m_isNew{};
     400              :   /// True once the existing entry's decrypted content has been loaded, so
     401              :   /// save() can refuse to overwrite it with empty fields before the
     402              :   /// asynchronous Show completes.
     403              :   bool m_contentLoaded{};
     404              :   /// "\r" when the entry's password line ended in a CRLF line end, else
     405              :   /// empty. The password field never holds it (a character typed at the end
     406              :   /// would land behind it); getPassword() writes it back, so a save keeps
     407              :   /// the entry's line end.
     408              :   QString m_passwordLineEnd;
     409              :   /// True from accept() starting an insert until the backend reports back.
     410              :   bool m_saving{};
     411              :   /// The widget that had the keyboard focus when the save started. Locking
     412              :   /// the dialog moves the focus along the tab chain onto Cancel, the only
     413              :   /// widget left enabled; a failed save gives it back, so the next Enter
     414              :   /// tries again instead of cancelling.
     415              :   QPointer<QWidget> m_focusBeforeSave;
     416              :   /// Inserts already pending when save() ran, whose reports must pass before
     417              :   /// one is taken as this dialog's own (counted down in isOwnInsertReport()).
     418              :   int m_insertsAhead{};
     419              :   /// Last pwgen mode passed to usePwgen(), so the policy can be re-applied
     420              :   /// after setEditorEnabled() re-enables the character-set widgets.
     421              :   bool m_usePwgen{};
     422              :   /// Editors for the template's fields, in template order; rebuilt by
     423              :   /// setTemplate(). Their labels are plain QLabels: the names are fixed.
     424              :   QList<QLineEdit *> m_templateLines;
     425              :   /// Fields that came from the entry rather than the template; their names
     426              :   /// are the user's, so their labels are FieldLabels that can be renamed.
     427              :   QList<QLineEdit *> m_otherLines;
     428              :   /// Named templates from `.templates`, name to field list, as given to
     429              :   /// setAvailableTemplates(); empty when the store has none.
     430              :   QHash<QString, QStringList> m_availableTemplates;
     431              :   /// Name of the template currently applied; cycleTemplate() steps from it.
     432              :   QString m_currentTemplateName;
     433              :   /// Ctrl+T, created once templates are available; owned by the dialog.
     434              :   QShortcut *m_templateShortcut{nullptr};
     435              :   /// Warning indicator shown inside the OTP field; owned by that field.
     436              :   ///
     437              :   /// QPointer, not a raw pointer: the QAction is parented to the QLineEdit, and
     438              :   /// setPassword() deletes the m_otherLines widgets before calling
     439              :   /// hookOtpField(), so a raw pointer would already dangle there.
     440              :   QPointer<QAction> m_otpWarning;
     441              :   /// The line edit hookOtpField() last wired up, so its signals can be
     442              :   /// disconnected when another field becomes the OTP one (a rename, a
     443              :   /// removal): a stale editingFinished from the old field must not rewrite
     444              :   /// the new one.
     445              :   QPointer<QLineEdit> m_otpLine;
     446              : 
     447              :   /**
     448              :    * @brief Switch to a named template: records it, selects it in the combo
     449              :    * box and rebuilds the field rows through setTemplate(). Unknown names
     450              :    * are ignored, and nothing changes while a save is in flight.
     451              :    * @param templateName A key of m_availableTemplates.
     452              :    */
     453              :   void applyTemplate(const QString &templateName);
     454              :   /**
     455              :    * @brief Hides the template row until setAvailableTemplates() fills it and
     456              :    * wires the combo box so that a user selection calls applyTemplate().
     457              :    */
     458              :   void setupTemplateBox();
     459              : };
     460              : 
     461              : #endif // SRC_PASSWORDDIALOG_H_
        

Generated by: LCOV version 2.0-1