QtPass 2.0.0
Developer documentation
Loading...
Searching...
No Matches
clipboardmanager.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 "clipboardmanager.h"
9#include "qtpasssettings.h"
10#include "util.h"
11#include <QApplication>
12#include <QClipboard>
13#include <QMimeData>
14#include <utility>
15#include <vector>
16
17ClipboardManager::ClipboardManager(QObject *parent) : QObject(parent) {
19 m_clearTimer.setSingleShot(true);
20 connect(&m_clearTimer, &QTimer::timeout, this, &ClipboardManager::clear);
21 connect(QApplication::instance(), &QApplication::aboutToQuit, this,
23}
24
29
30namespace {
41auto markedSecret(const QMimeData *data) -> bool {
42 if (data == nullptr) {
43 return false;
44 }
45 const QStringList formats = data->formats();
46 for (const QString &format : formats) {
47 for (const char *mark :
48 {"passwordManagerHint", "nspasteboard-concealed-type",
49 "nspasteboard.ConcealedType",
50 "ExcludeClipboardContentFromMonitorProcessing"}) {
51 if (format.contains(QLatin1String(mark), Qt::CaseInsensitive)) {
52 return true;
53 }
54 }
55 }
56 return false;
57}
58
68auto oneHoldsTheOther(const QString &a, const QString &b) -> bool {
69 const QString &longer = a.size() >= b.size() ? a : b;
70 const QString &part = a.size() >= b.size() ? b : a;
71 const qsizetype m = part.size();
72 if (m == 0) {
73 return true;
74 }
75 // fallback[i]: length of the longest proper prefix of part[0..i] that
76 // also ends there, so a mismatch resumes there instead of from the start.
77 std::vector<qsizetype> fallback(static_cast<size_t>(m), 0);
78 for (qsizetype i = 1, k = 0; i < m; ++i) {
79 while (k > 0 && part.at(i) != part.at(k)) {
80 k = fallback[static_cast<size_t>(k - 1)];
81 }
82 if (part.at(i) == part.at(k)) {
83 ++k;
84 }
85 fallback[static_cast<size_t>(i)] = k;
86 }
87 for (qsizetype i = 0, k = 0; i < longer.size(); ++i) {
88 while (k > 0 && longer.at(i) != part.at(k)) {
89 k = fallback[static_cast<size_t>(k - 1)];
90 }
91 if (longer.at(i) == part.at(k)) {
92 ++k;
93 }
94 if (k == m) {
95 return true;
96 }
97 }
98 return false;
99}
100} // namespace
101
102void ClipboardManager::copyIfAlways(const QString &text,
103 const QString &p_output) {
105 // Only "always copy" mode actually places text on the clipboard here; in
106 // on-demand mode the copy happens later from the field's copy button.
107 // Crucially, do not touch m_clippedText otherwise — it tracks what is
108 // currently on the clipboard so the autoclear timer knows what to clear.
109 // Overwriting it when merely showing another entry left a previously copied
110 // password on the clipboard past its autoclear window (#1607).
111 if (s.clipBoardType == Enums::CLIPBOARD_ALWAYS && !p_output.isEmpty()) {
112 copyText(text);
113 }
114}
115
116void ClipboardManager::copyText(const QString &text) {
118 QClipboard *clip = QApplication::clipboard();
119
120 QClipboard::Mode mode = QClipboard::Clipboard;
121 if (s.useSelection && clip->supportsSelection()) {
122 mode = QClipboard::Selection;
123 }
124
125 // What was there before the first secret, to put back when autoclear
126 // runs (as pass -c does). Text only, as pass keeps it: rich content comes
127 // back as its plain text. Where Qt cannot read the clipboard without focus
128 // (some Wayland compositors, a copy from the tray), "before" reads as
129 // nothing and autoclear clears instead: the safe way round.
130 if (s.useAutoclear && s.restoreClipboard) {
131 saveWhatWasThere(clip, mode, text);
132 }
133 forgetIfSaved(text);
134 clip->setMimeData(buildClipboardMimeData(text), mode);
135
136 // The text copied before may still be in the other buffer (a PIN copied to
137 // the clipboard, then selected, so also in the X11 selection): replacing
138 // it here would leave it there past autoclear.
139 if (!m_clippedText.isEmpty() && m_clippedText != text &&
140 !m_otherCopies.contains(m_clippedText) &&
141 (clip->text(QClipboard::Clipboard) == m_clippedText ||
142 clip->text(QClipboard::Selection) == m_clippedText)) {
144 }
145 m_clippedText = text;
146 emit statusMessage(tr("Copied to clipboard"));
147 if (s.useAutoclear) {
148 m_clearTimer.start();
149 }
150}
151
152void ClipboardManager::saveWhatWasThere(QClipboard *clip, QClipboard::Mode mode,
153 const QString &text) {
154 std::optional<QString> &previous =
155 mode == QClipboard::Selection ? m_previousSelection : m_previousClipboard;
156 const QString now = clip->text(mode);
157 // Taken once per window, at the first copy, whatever is there: a text
158 // of ours, or the very text being copied, is saved as nothing (restoring
159 // it would leave a secret on the clipboard for good), and a later copy
160 // in the window cannot take a snapshot instead.
161 if (!previous) {
162 // Another password manager's secret is marked as one; put back as
163 // plain text it would lose that mark (and go into clipboard history)
164 // and nobody would clear it again.
165 const bool safe = now != text && now != m_clippedText &&
166 !m_otherCopies.contains(now) &&
167 !markedSecret(clip->mimeData(mode));
168 previous = safe ? now : QString();
169 }
170}
171
172void ClipboardManager::forgetIfSaved(const QString &text) {
173 // The saved text is copied as a secret now: putting it back would leave
174 // that secret on the clipboard. Emptied, not dropped, so no later copy
175 // takes a new snapshot in this window either; clear() then clears.
176 for (std::optional<QString> *previous :
178 if (*previous && **previous == text) {
179 *previous = QString();
180 }
181 }
182}
183
184void ClipboardManager::trackCopied(const QString &text) {
185 if (text.isEmpty()) {
186 return;
187 }
188 forgetIfSaved(text);
189 // Kept beside m_clippedText, not instead of it: replacing it would leave a
190 // password copied earlier on the clipboard past its autoclear (#1607).
191 if (text != m_clippedText && !m_otherCopies.contains(text)) {
192 // A mouse selection reports itself on every change while it grows or
193 // shrinks (the X11 primary selection); only where it ends counts, or a
194 // passing "a" would stay tracked and autoclear could take someone
195 // else's "a" later.
196 // An earlier copy still on the clipboard proper (Ctrl+C) stays tracked.
197 // A step holds the one before or lies in it (a word double-clicked,
198 // then Ctrl+A); oneHoldsTheOther() asks that in linear time.
199 const QString &last =
200 m_otherCopies.isEmpty() ? QString() : m_otherCopies.last();
201 if (!last.isEmpty() && oneHoldsTheOther(text, last) &&
202 QApplication::clipboard()->text(QClipboard::Clipboard) != last &&
203 QApplication::clipboard()->text(QClipboard::Selection) != last) {
204 m_otherCopies.last() = text;
205 } else {
207 m_otherCopies.append(text);
208 }
209 }
210 // Not pushed back: a selection reports itself on every change, and a drag
211 // too, so restarting here gave a password copied earlier a new full
212 // period each time. The first deadline clears everything tracked.
213 if (QtPassSettings::load().useAutoclear && !m_clearTimer.isActive()) {
214 m_clearTimer.start();
215 }
216}
217
219 constexpr qsizetype kMaxOtherCopies = 16;
220 if (m_otherCopies.size() >= kMaxOtherCopies) {
221 // Make room, but never by forgetting a text that is still on the
222 // clipboard or in the selection: it would then outlive autoclear.
223 // At most two are, so the oldest of the rest can always go.
224 const QString onClipboard =
225 QApplication::clipboard()->text(QClipboard::Clipboard);
226 const QString inSelection =
227 QApplication::clipboard()->text(QClipboard::Selection);
228 for (qsizetype i = 0; i < m_otherCopies.size(); ++i) {
229 if (m_otherCopies.at(i) != onClipboard &&
230 m_otherCopies.at(i) != inSelection) {
231 m_otherCopies.removeAt(i);
232 break;
233 }
234 }
235 }
236}
237
239 // A clear before the deadline (a deselect) ends this window: a copy
240 // tracked after it starts a full one, not the rest of the old one.
241 m_clearTimer.stop();
242 // Whatever happens below, the saved text is forgotten: it is the user's,
243 // and no later autoclear may put it back.
244 const std::optional<QString> previousClipboard =
245 std::exchange(m_previousClipboard, std::nullopt);
246 const std::optional<QString> previousSelection =
247 std::exchange(m_previousSelection, std::nullopt);
248 if (m_clippedText.isEmpty() && m_otherCopies.isEmpty()) {
249 // Nothing of ours is out there. The old code compared the empty tracker
250 // with an empty selection, "cleared" that and said so on every deselect.
251 return;
252 }
253 const auto ours = [this](const QString &text) {
254 return !text.isEmpty() &&
255 (text == m_clippedText || m_otherCopies.contains(text));
256 };
257 QClipboard *clipboard = QApplication::clipboard();
258 const bool restore = QtPassSettings::load().restoreClipboard;
259 bool cleared = false;
260 bool restored = false;
261 // Ours still there: the text from before comes back if there was one and
262 // what is there is copyText()'s own copy, otherwise it is cleared. A copy
263 // from a shown field (trackCopied()) is cleared on purpose, not restored
264 // over: it can come long after copyText(), when "before" is stale, and the
265 // user chose that copy themselves. Something else copied meanwhile is left
266 // alone. The setting is read now: switched off during the window, the
267 // saved text was still held until here, and is dropped unused.
268 const auto putBack = [&](QClipboard::Mode mode,
269 const std::optional<QString> &previous) {
270 const QString now = clipboard->text(mode);
271 if (!ours(now)) {
272 return;
273 }
274 if (restore && previous && !previous->isEmpty() && now == m_clippedText) {
275 clipboard->setText(*previous, mode);
276 restored = true;
277 return;
278 }
279 clipboard->clear(mode);
280 if (mode == QClipboard::Selection) {
281 clipboard->setText(QString(""), QClipboard::Selection);
282 }
283 cleared = true;
284 };
285 putBack(QClipboard::Selection, previousSelection);
286 putBack(QClipboard::Clipboard, previousClipboard);
287 emit statusMessage(restored ? tr("Clipboard restored")
288 : cleared ? tr("Clipboard cleared")
289 : tr("Clipboard not cleared"));
290 m_clippedText.clear();
291 m_otherCopies.clear();
292}
293
294auto buildClipboardMimeData(const QString &text) -> QMimeData * {
295 auto *mimeData = new QMimeData();
296 mimeData->setText(text);
297// The KDE hint (what wl-copy --sensitive sets) keeps the secret out of
298// Klipper, CopyQ and cliphist history, on the BSDs as well as on Linux.
299#if defined(Q_OS_UNIX) && !defined(Q_OS_DARWIN)
300 mimeData->setData("x-kde-passwordManagerHint", QByteArray("secret"));
301#endif
302#ifdef Q_OS_MAC
303 mimeData->setData("application/x-nspasteboard-concealed-type", QByteArray());
304#endif
305#ifdef Q_OS_WIN
306 mimeData->setData("ExcludeClipboardContentFromMonitorProcessing",
307 dwordBytes(1));
308 mimeData->setData("CanIncludeInClipboardHistory", dwordBytes(0));
309 mimeData->setData("CanUploadToCloudClipboard", dwordBytes(0));
310#endif
311 return mimeData;
312}
void trackCopied(const QString &text)
Track text that got onto the clipboard some other way.
QStringList m_otherCopies
trackCopied() texts, cleared with the rest
void makeRoomInOtherCopies()
Keep m_otherCopies below its cap before trackCopied() appends: drop the oldest text that is neither o...
void copyIfAlways(const QString &text, const QString &p_output=QString())
Handle clipboard copying for a shown entry.
void setAutoclearTimer()
Re-read the autoclear delay from the settings.
void forgetIfSaved(const QString &text)
Empty a saved previous text equal to text, now copied as a secret, so clear() does not put the secret...
void copyText(const QString &text)
Copy text into the system clipboard (or the X11 primary selection when configured) and arm the autocl...
QTimer m_clearTimer
Single-shot autoclear timer; started by copyText() when the autoclear setting is on,...
void clear()
Remove the tracked text from the clipboard if it is still there. Silent no-op when nothing is tracked...
std::optional< QString > m_previousSelection
As m_previousClipboard, for the X11 primary selection.
QString m_clippedText
The secret copyText() last put on the clipboard; clear() removes the clipboard content only while it ...
void statusMessage(const QString &message)
Something worth showing in the status bar happened.
ClipboardManager(QObject *parent=nullptr)
Construct a manager that also clears its text when the application quits.
std::optional< QString > m_previousClipboard
void saveWhatWasThere(QClipboard *clip, QClipboard::Mode mode, const QString &text)
Save what mode holds before the first secret of an autoclear window, for clear() to put back; saved a...
static auto load() -> AppSettings
Load all flat settings into an AppSettings value object.
static auto getAutoclearSeconds(const int &defaultValue=QVariant().toInt()) -> int
Get autoclear delay in seconds.
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 ...
auto buildClipboardMimeData(const QString &text) -> QMimeData *
Build clipboard MIME data with platform-specific security hints.
@ CLIPBOARD_ALWAYS
Definition enums.h:26
QtPassSettings, the QSettings singleton behind every saved setting, the profiles and the Pass backend...
Plain value-object holding all flat QtPass configuration.
Definition appsettings.h:36
bool useSelection
Use the X11 primary selection.
Definition appsettings.h:75
bool restoreClipboard
Definition appsettings.h:79
Enums::ClipBoardType clipBoardType
Clipboard copy behaviour.
Definition appsettings.h:73
bool useAutoclear
Definition appsettings.h:76
Util: static helpers for the process environment, binary discovery, store paths, URL safety and the l...
constexpr int MS_PER_SECOND
Milliseconds in a second, for timers set from a setting in seconds.
Definition util.h:25