QtPass 2.0.0
Developer documentation
Loading...
Searching...
No Matches
secretlineedit.cpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2026 Anne Jan Brouwer
2// SPDX-License-Identifier: GPL-3.0-or-later
8#include "secretlineedit.h"
9#include "clipboardmanager.h"
10#include <QAction>
11#include <QApplication>
12#include <QContextMenuEvent>
13#include <QKeyEvent>
14#include <QMenu>
15#include <QMouseEvent>
16#include <QValidator>
17#include <algorithm>
18
19namespace {
30class SingleLineValidator : public QValidator {
31public:
32 using QValidator::QValidator;
33
41 auto validate(QString &input, int &pos) const -> State override {
42 if (std::none_of(input.cbegin(), input.cend(),
44 return Acceptable;
45 }
46 const QStringView head = QStringView(input).left(pos);
47 pos -= static_cast<int>(std::count_if(head.cbegin(), head.cend(),
50 return Acceptable;
51 }
52};
53} // namespace
54
55auto SecretLineEdit::isLineBreak(QChar ch) -> bool {
56 const char16_t c = ch.unicode();
57 return c == u'\n' || c == u'\r' || c == u'\u0085' || c == u'\u2028' ||
58 c == u'\u2029';
59}
60
61auto SecretLineEdit::withoutLineBreaks(QString text) -> QString {
62 text.removeIf(&SecretLineEdit::isLineBreak);
63 return text;
64}
65
66void SecretLineEdit::setStoredText(const QString &text) {
67 // setValidator() only swaps the pointer; nothing is checked again when the
68 // filter comes back, so the stored text stays as it is until edited.
69 const QValidator *filter = validator();
70 setValidator(nullptr);
71 setText(text);
72 setValidator(filter);
73}
74
75SecretLineEdit::SecretLineEdit(QWidget *parent) : QLineEdit(parent) {
76 // QLineEdit cuts setText(), a paste and typing to maxLength without a
77 // word; its default of 32767 cut long key lines (see kMaxLength).
78 setMaxLength(kMaxLength);
79 setValidator(new SingleLineValidator(this));
80}
81
82SecretLineEdit::SecretLineEdit(const QString &text, QWidget *parent)
83 : QLineEdit(text, parent) {
84 setMaxLength(kMaxLength);
85 setValidator(new SingleLineValidator(this));
86}
87
89 QMenu *menu = createStandardContextMenu();
90 for (QAction *action : menu->actions()) {
91 // The standard actions call QLineEdit::copy() and cut(), which are not
92 // virtual.
93 if (action->objectName() == QLatin1String("edit-copy")) {
94 disconnect(action, &QAction::triggered, this, nullptr);
95 connect(action, &QAction::triggered, this,
96 [this] { copySelection(QClipboard::Clipboard); });
97 } else if (action->objectName() == QLatin1String("edit-cut")) {
98 disconnect(action, &QAction::triggered, this, nullptr);
99 connect(action, &QAction::triggered, this, [this] { cutSelection(); });
100 } else if (action->objectName() == QLatin1String("edit-paste")) {
101 disconnect(action, &QAction::triggered, this, nullptr);
102 connect(action, &QAction::triggered, this,
103 [this] { pasteOneLine(QClipboard::Clipboard); });
104 }
105 }
106 return menu;
107}
108
109void SecretLineEdit::keyPressEvent(QKeyEvent *event) {
110 if (event->matches(QKeySequence::Copy)) {
111 copySelection(QClipboard::Clipboard);
112 event->accept();
113 return;
114 }
115 if (event->matches(QKeySequence::Cut)) {
116 cutSelection();
117 event->accept();
118 return;
119 }
120 if (event->matches(QKeySequence::Paste)) {
121 // As QWidgetLineControl: Ctrl+Shift+Insert is a Paste key only with the
122 // X11 key bindings, and there it pastes the primary selection.
123 const bool selection =
124 event->key() == Qt::Key_Insert &&
125 event->modifiers() == (Qt::ControlModifier | Qt::ShiftModifier) &&
126 QApplication::clipboard()->supportsSelection();
127 pasteOneLine(selection ? QClipboard::Selection : QClipboard::Clipboard);
128 event->accept();
129 return;
130 }
131 // QLineEdit copies what these delete (Ctrl+K and Ctrl+U with the X11 key
132 // bindings), as a cut.
133 const bool toEnd = event->matches(QKeySequence::DeleteEndOfLine);
134 if (toEnd || event->matches(QKeySequence::DeleteCompleteLine)) {
135 if (!isReadOnly()) {
136 const int from = toEnd ? cursorPosition() : 0;
137 setSelection(from, static_cast<int>(text().size()) - from);
138 cutSelection();
139 }
140 event->accept();
141 return;
142 }
143 withoutPlainSelectionCopy([this, event] { QLineEdit::keyPressEvent(event); });
144 // Where QLineEdit would have copied: after a key it handled, not after a
145 // lone modifier or another key it ignores.
146 if (event->isAccepted()) {
148 }
149}
150
151void SecretLineEdit::mouseReleaseEvent(QMouseEvent *event) {
152 // QLineEdit pastes the primary selection here on a middle click.
153 if (event->button() == Qt::MiddleButton && !isReadOnly() &&
154 QApplication::clipboard()->supportsSelection()) {
155 deselect();
156 pasteOneLine(QClipboard::Selection);
157 event->accept();
158 return;
159 }
161 [this, event] { QLineEdit::mouseReleaseEvent(event); });
162 if (event->button() == Qt::LeftButton) {
164 }
165}
166
167void SecretLineEdit::contextMenuEvent(QContextMenuEvent *event) {
168 QMenu *menu = createSecretContextMenu();
169 menu->setAttribute(Qt::WA_DeleteOnClose);
170 menu->popup(event->globalPos());
171}
172
173void SecretLineEdit::copySelection(QClipboard::Mode mode) {
174 // As QLineEdit itself: nothing leaves a field that shows dots.
175 if (echoMode() != QLineEdit::Normal || !hasSelectedText()) {
176 return;
177 }
178 const QString text = selectedText();
179 QApplication::clipboard()->setMimeData(buildClipboardMimeData(text), mode);
180 emit copied(text);
181}
182
184 // As QLineEdit::cut(): a field that shows dots deletes without copying.
185 if (isReadOnly() || !hasSelectedText()) {
186 return;
187 }
188 copySelection(QClipboard::Clipboard);
189 del();
190}
191
193 const std::function<void()> &handler) {
194 // QLineEdit fills the primary selection with plain text itself, at the end
195 // of every key it handles and on a left-button release, but only in Normal
196 // echo mode (QWidgetLineControl::copy()). Replacing that afterwards still
197 // leaves a moment in which a clipboard manager could take the unmarked
198 // text, so the base handler runs in Password mode instead: same length,
199 // so cursor and selection stay where they are, and no copy.
200 // Editable, the field keeps Normal mode (see the class description) and
201 // publishSelection() replaces the plain copy.
202 if (echoMode() != QLineEdit::Normal || !isReadOnly()) {
203 handler();
204 return;
205 }
206 setEchoMode(QLineEdit::Password);
207 handler();
208 setEchoMode(QLineEdit::Normal);
209}
210
212 if (QApplication::clipboard()->supportsSelection()) {
213 copySelection(QClipboard::Selection);
214 }
215}
216
217void SecretLineEdit::pasteOneLine(QClipboard::Mode mode) {
218 if (isReadOnly()) {
219 return;
220 }
221 const QString text = withoutLineBreaks(QApplication::clipboard()->text(mode));
222 if (text.isEmpty() && !hasSelectedText()) {
223 return;
224 }
225 // insert() replaces the selection and records the edit for Undo; with no
226 // line break left the validator changes nothing, so the history stays.
227 // QLineEdit::paste() also makes the paste an undo step of its own, apart
228 // from the typing around it; the boundaries do that here.
230 insert(text);
232}
233
235 // QWidgetLineControl::separate(), which QLineEdit::paste() calls, is
236 // private; a cursor move calls it too, and the boundary lands before the
237 // next edit. A selection needs none: removing it sets its own.
238 if (hasSelectedText() || text().isEmpty()) {
239 return;
240 }
241 const int pos = cursorPosition();
242 setCursorPosition(pos > 0 ? pos - 1 : pos + 1);
243 setCursorPosition(pos);
244}
void mouseReleaseEvent(QMouseEvent *event) override
Fills the primary selection with the marked selection on a left-button release, instead of QLineEdit'...
void copied(const QString &text)
Selected text was copied out of the line edit.
void cutSelection()
Copies the selection through copySelection() and then deletes it. Does nothing when read-only or with...
void withoutPlainSelectionCopy(const std::function< void()> &handler)
Runs a base-class event handler so that it cannot fill the primary selection with plain text: in a re...
static auto withoutLineBreaks(QString text) -> QString
text with every line break (see isLineBreak()) removed: what a one-line field keeps of a paste.
auto createSecretContextMenu() -> QMenu *
The standard context menu, with Copy and Cut going through the secret copy.
void publishSelection()
Fills the X11 primary selection with the marked selection, on platforms that have one; called after a...
SecretLineEdit(QWidget *parent=nullptr)
Constructs the line edit.
void contextMenuEvent(QContextMenuEvent *event) override
Shows createSecretContextMenu().
static constexpr int kMaxLength
Most characters the line edit holds (1 MiB of them): its maxLength in place of QLineEdit's 32767.
void setStoredText(const QString &text)
Shows a value read from the entry exactly as it is stored.
static auto isLineBreak(QChar ch) -> bool
Whether ch breaks a line: LF, CR, NEL (U+0085), or the Unicode line and paragraph separators (U+2028,...
void markUndoBoundary()
Ends the current undo step, so that the next edit starts its own, as QLineEdit::paste() does around a...
void pasteOneLine(QClipboard::Mode mode)
Pastes the clipboard or the primary selection with its line breaks removed, as one undoable edit....
void copySelection(QClipboard::Mode mode)
Puts the selection on the clipboard or in the primary selection as secret-marked MIME data and emits ...
void keyPressEvent(QKeyEvent *event) override
Ctrl+C copies with the hints, Ctrl+X as well before it deletes; after any other key the primary selec...
auto buildClipboardMimeData(const QString &text) -> QMimeData *
Build clipboard MIME data with platform-specific security hints.
ClipboardManager, which puts secrets on the clipboard and removes them again, and the MIME data that ...
QLineEdit whose copies, cuts and primary-selection fills carry the secret clipboard hints and are rep...