Branch data Line data Source code
1 : : // SPDX-FileCopyrightText: 2026 Anne Jan Brouwer
2 : : // SPDX-License-Identifier: GPL-3.0-or-later
3 : : /**
4 : : * @file
5 : : * @brief Implements SecretLineEdit: the four copy paths (Ctrl+C, Cut, context
6 : : * menu, X11 primary selection) routed through buildClipboardMimeData().
7 : : */
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 : :
19 : : namespace {
20 : : /**
21 : : * @brief Keeps a line edit to the one line it stands for.
22 : : *
23 : : * QLineEdit takes the CR and LF of a paste, a drop or an input method as they
24 : : * come, draws them as blanks and returns them from text(). In the password
25 : : * dialog a field's line break then ends its line in the entry: a password
26 : : * pasted as "\nhunter2" was saved as an empty first line. QLineEdit runs its
27 : : * validator on every change before it reports the new text, and validate()
28 : : * may correct what it is given.
29 : : */
30 : : class SingleLineValidator : public QValidator {
31 : : public:
32 : 600 : using QValidator::QValidator;
33 : :
34 : : /**
35 : : * @brief Remove the line breaks (SecretLineEdit::isLineBreak()) from
36 : : * @p input.
37 : : * @param input The text the field would hold; corrected in place.
38 : : * @param pos The cursor position; kept behind the character it was behind.
39 : : * @return Always Acceptable: every text is one line once corrected.
40 : : */
41 : 555 : auto validate(QString &input, int &pos) const -> State override {
42 [ + + ]: 555 : if (std::none_of(input.cbegin(), input.cend(),
43 : : &SecretLineEdit::isLineBreak)) {
44 : : return Acceptable;
45 : : }
46 : 6 : const QStringView head = QStringView(input).left(pos);
47 : 6 : pos -= static_cast<int>(std::count_if(head.cbegin(), head.cend(),
48 : : &SecretLineEdit::isLineBreak));
49 : 6 : input = SecretLineEdit::withoutLineBreaks(input);
50 : 6 : return Acceptable;
51 : : }
52 : : };
53 : : } // namespace
54 : :
55 : 98237 : auto SecretLineEdit::isLineBreak(QChar ch) -> bool {
56 : 98237 : const char16_t c = ch.unicode();
57 [ + + + + : 98237 : return c == u'\n' || c == u'\r' || c == u'\u0085' || c == u'\u2028' ||
+ + ]
58 : 98237 : c == u'\u2029';
59 : : }
60 : :
61 : 24 : auto SecretLineEdit::withoutLineBreaks(QString text) -> QString {
62 : : text.removeIf(&SecretLineEdit::isLineBreak);
63 : 24 : return text;
64 : : }
65 : :
66 : 200 : void 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 : 200 : const QValidator *filter = validator();
70 : 200 : setValidator(nullptr);
71 : 200 : setText(text);
72 : 200 : setValidator(filter);
73 : 200 : }
74 : :
75 : 282 : SecretLineEdit::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 : 282 : setMaxLength(kMaxLength);
79 : 282 : setValidator(new SingleLineValidator(this));
80 : 282 : }
81 : :
82 : 18 : SecretLineEdit::SecretLineEdit(const QString &text, QWidget *parent)
83 : 18 : : QLineEdit(text, parent) {
84 : 18 : setMaxLength(kMaxLength);
85 : 18 : setValidator(new SingleLineValidator(this));
86 : 18 : }
87 : :
88 : 3 : auto SecretLineEdit::createSecretContextMenu() -> QMenu * {
89 : 3 : QMenu *menu = createStandardContextMenu();
90 [ + + + ]: 27 : for (QAction *action : menu->actions()) {
91 : : // The standard actions call QLineEdit::copy() and cut(), which are not
92 : : // virtual.
93 [ + + + ]: 42 : if (action->objectName() == QLatin1String("edit-copy")) {
94 : 3 : disconnect(action, &QAction::triggered, this, nullptr);
95 : 3 : connect(action, &QAction::triggered, this,
96 : 7 : [this] { copySelection(QClipboard::Clipboard); });
97 [ + + + ]: 36 : } else if (action->objectName() == QLatin1String("edit-cut")) {
98 : 2 : disconnect(action, &QAction::triggered, this, nullptr);
99 : 3 : connect(action, &QAction::triggered, this, [this] { cutSelection(); });
100 [ + + + ]: 32 : } else if (action->objectName() == QLatin1String("edit-paste")) {
101 : 2 : disconnect(action, &QAction::triggered, this, nullptr);
102 : 2 : connect(action, &QAction::triggered, this,
103 : 5 : [this] { pasteOneLine(QClipboard::Clipboard); });
104 : : }
105 : : }
106 : 3 : return menu;
107 : : }
108 : :
109 : 459 : void SecretLineEdit::keyPressEvent(QKeyEvent *event) {
110 [ + + ]: 459 : if (event->matches(QKeySequence::Copy)) {
111 : 7 : copySelection(QClipboard::Clipboard);
112 : : event->accept();
113 : 7 : return;
114 : : }
115 [ + + ]: 452 : if (event->matches(QKeySequence::Cut)) {
116 : 3 : cutSelection();
117 : : event->accept();
118 : 3 : return;
119 : : }
120 [ + + ]: 449 : 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 [ # # ]: 0 : event->key() == Qt::Key_Insert &&
125 [ - + - - ]: 3 : event->modifiers() == (Qt::ControlModifier | Qt::ShiftModifier) &&
126 : 0 : QApplication::clipboard()->supportsSelection();
127 : 3 : pasteOneLine(selection ? QClipboard::Selection : QClipboard::Clipboard);
128 : : event->accept();
129 : 3 : return;
130 : : }
131 : : // QLineEdit copies what these delete (Ctrl+K and Ctrl+U with the X11 key
132 : : // bindings), as a cut.
133 : 446 : const bool toEnd = event->matches(QKeySequence::DeleteEndOfLine);
134 [ + - + - ]: 446 : if (toEnd || event->matches(QKeySequence::DeleteCompleteLine)) {
135 [ # # ]: 0 : if (!isReadOnly()) {
136 [ # # ]: 0 : const int from = toEnd ? cursorPosition() : 0;
137 : 0 : setSelection(from, static_cast<int>(text().size()) - from);
138 : 0 : cutSelection();
139 : : }
140 : : event->accept();
141 : 0 : return;
142 : : }
143 : 1338 : 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 [ + + ]: 446 : if (event->isAccepted()) {
147 : 425 : publishSelection();
148 : : }
149 : : }
150 : :
151 : 0 : void SecretLineEdit::mouseReleaseEvent(QMouseEvent *event) {
152 : : // QLineEdit pastes the primary selection here on a middle click.
153 [ # # # # : 0 : if (event->button() == Qt::MiddleButton && !isReadOnly() &&
# # ]
154 : 0 : QApplication::clipboard()->supportsSelection()) {
155 : 0 : deselect();
156 : 0 : pasteOneLine(QClipboard::Selection);
157 : : event->accept();
158 : 0 : return;
159 : : }
160 : 0 : withoutPlainSelectionCopy(
161 [ # # ]: 0 : [this, event] { QLineEdit::mouseReleaseEvent(event); });
162 [ # # ]: 0 : if (event->button() == Qt::LeftButton) {
163 : 0 : publishSelection();
164 : : }
165 : : }
166 : :
167 : 0 : void SecretLineEdit::contextMenuEvent(QContextMenuEvent *event) {
168 : 0 : QMenu *menu = createSecretContextMenu();
169 : 0 : menu->setAttribute(Qt::WA_DeleteOnClose);
170 : 0 : menu->popup(event->globalPos());
171 : 0 : }
172 : :
173 : 11 : void SecretLineEdit::copySelection(QClipboard::Mode mode) {
174 : : // As QLineEdit itself: nothing leaves a field that shows dots.
175 [ + + - + ]: 11 : if (echoMode() != QLineEdit::Normal || !hasSelectedText()) {
176 : 2 : return;
177 : : }
178 : 9 : const QString text = selectedText();
179 : 9 : QApplication::clipboard()->setMimeData(buildClipboardMimeData(text), mode);
180 : 9 : emit copied(text);
181 : : }
182 : :
183 : 4 : void SecretLineEdit::cutSelection() {
184 : : // As QLineEdit::cut(): a field that shows dots deletes without copying.
185 [ + + - + ]: 4 : if (isReadOnly() || !hasSelectedText()) {
186 : 1 : return;
187 : : }
188 : 3 : copySelection(QClipboard::Clipboard);
189 : 3 : del();
190 : : }
191 : :
192 : 446 : void SecretLineEdit::withoutPlainSelectionCopy(
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 [ + + + + ]: 446 : if (echoMode() != QLineEdit::Normal || !isReadOnly()) {
203 : 444 : handler();
204 : 444 : return;
205 : : }
206 : 2 : setEchoMode(QLineEdit::Password);
207 : 2 : handler();
208 : 2 : setEchoMode(QLineEdit::Normal);
209 : : }
210 : :
211 : 425 : void SecretLineEdit::publishSelection() {
212 [ - + ]: 425 : if (QApplication::clipboard()->supportsSelection()) {
213 : 0 : copySelection(QClipboard::Selection);
214 : : }
215 : 425 : }
216 : :
217 : 4 : void SecretLineEdit::pasteOneLine(QClipboard::Mode mode) {
218 [ + - ]: 4 : if (isReadOnly()) {
219 : 0 : return;
220 : : }
221 : 8 : const QString text = withoutLineBreaks(QApplication::clipboard()->text(mode));
222 [ - + - - : 4 : 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.
229 : 4 : markUndoBoundary();
230 : 4 : insert(text);
231 : 4 : markUndoBoundary();
232 : : }
233 : :
234 : 8 : void SecretLineEdit::markUndoBoundary() {
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 [ + + + - : 14 : if (hasSelectedText() || text().isEmpty()) {
+ + ]
239 : : return;
240 : : }
241 : 6 : const int pos = cursorPosition();
242 [ + - ]: 6 : setCursorPosition(pos > 0 ? pos - 1 : pos + 1);
243 : 6 : setCursorPosition(pos);
244 : : }
|