repositories / dotfiles
dotfiles
bugabingas dorkfiles
owned by admin
quickshell/nuguland/features/clipboard/Clipboard.qml
Rawimport QtQuick
import Quickshell
import Quickshell.Io
import "../.."
import "clip.js" as Clip
Item {
id: root
property SurfaceManager surfaces
property Niri niriService
property string pendingPasteId: ""
property var pasteWindowId: null
property bool privateMode: false
property bool vaultCopyActive: false
property bool vaultPauseAcknowledged: false
property var rows: []
signal vaultCapturePaused
property var lastAction: ({})
property bool persistenceReady: false
readonly property int maxRows: 40
readonly property string historyPath: Quickshell.statePath("clipboard-history.json")
// --- linear lookup over the raw persisted rows (id, title, body, pinned, createdAt) ---
function rawRowById(id) {
const needle = String(id);
for (let i = 0; i < rows.length; i++)
if (rows[i].id === needle) {
return rows[i];
}
return null;
}
function captureClipboard(text) {
const body = String(text || "");
if (privateMode || !Clip.isReadableText(body))
return;
const id = `clip-${Clip.hashText(body)}`;
const next = [];
let existingPin = false;
for (let i = 0; i < rows.length; i++) {
if (rows[i].id === id) {
existingPin = !!rows[i].pinned;
continue;
}
next.push(rows[i]);
}
next.unshift({
"id": id,
"title": Clip.rowTitle(body),
"body": body,
"pinned": existingPin,
"createdAt": Date.now()
});
rows = next.slice(0, maxRows);
saveHistory();
}
// The panel binds these rows directly; ages are relative to the call.
function viewRows(query) {
const now = Date.now();
return Clip.filterRows(rows, query).map(row => {
return Clip.cloneRow(row, now);
});
}
function stateObject(query) {
return {
"privateMode": privateMode,
"privateRole": privateMode ? "warning" : "ui.accent",
"rows": viewRows(query),
"lastAction": lastAction
};
}
function stateJson() {
return JSON.stringify(stateObject(""));
}
function search(query) {
return JSON.stringify(stateObject(query));
}
function mutateRow(id, callback) {
const next = [];
for (let i = 0; i < rows.length; i++) {
const row = Object.assign({}, rows[i]);
if (row.id === String(id))
callback(row);
next.push(row);
}
rows = next;
saveHistory();
}
function togglePin(id) {
mutateRow(id, row => {
return row.pinned = !row.pinned;
});
lastAction = {
"kind": "pin",
"id": String(id)
};
return stateJson();
}
function copy(id) {
const row = rawRowById(id);
if (row)
textProcess.createObject(root, {
"command": ["wl-copy"],
"payload": String(row.body || "")
});
lastAction = {
"kind": "copy",
"id": String(id),
"accepted": !!row
};
return stateJson();
}
function paste(id) {
if (pendingPasteId.length > 0)
return stateJson();
const target = surfaces && surfaces.popupOpen ? surfaces.returnWindowId : (niriService ? niriService.focusedWindow : null);
const accepted = !!rawRowById(id) && target !== null && target !== undefined;
// The destination's app id names the pending paste's scope, never its title.
const window = niriService ? niriService.windowById(target) : null;
lastAction = {
"kind": "paste",
"id": String(id),
"accepted": accepted,
"pending": accepted,
"target": window ? String(window.app_id || window.appId || "") : "",
"error": accepted ? "" : "no paste destination",
"route": "clipboard-target-typing",
"pasteInputRoute": "wtype"
};
if (!accepted)
return stateJson();
pendingPasteId = String(id);
pasteWindowId = target;
if (surfaces)
surfaces.closePopup("clipboard-paste");
// The stream may already reflect the destination when no popup was open.
pasteFocusTimer.start();
if (niriService && niriService.focusedWindow === pasteWindowId)
checkPasteFocus();
return stateJson();
}
function finishPaste(error) {
lastAction = Object.assign({}, lastAction, {
"pending": false,
"error": error
});
pendingPasteId = "";
pasteWindowId = null;
pasteFocusTimer.stop();
}
function checkPasteFocus() {
if (pendingPasteId.length === 0)
return;
if (surfaces && surfaces.popupOpen) {
finishPaste("paste cancelled: another panel opened");
return;
}
const focused = niriService ? niriService.focusedWindow : null;
if (focused === pasteWindowId) {
const row = rawRowById(pendingPasteId);
if (row)
textProcess.createObject(root, {
"command": ["/usr/bin/wtype", "-"],
"payload": String(row.body || "")
});
finishPaste(row ? "" : "clipboard item no longer available");
} else if (focused !== null && focused !== undefined) {
finishPaste("paste destination lost focus");
}
}
function deleteRow(id) {
const target = String(id);
const next = [];
for (let i = 0; i < rows.length; i++) {
if (rows[i].id !== target)
next.push(rows[i]);
}
rows = next;
saveHistory();
lastAction = {
"kind": "delete",
"id": target
};
return stateJson();
}
function loadHistoryText(text) {
try {
const parsed = JSON.parse(String(text || "{}"));
const loadedRows = Array.isArray(parsed.rows) ? parsed.rows : [];
rows = loadedRows.map(row => {
return Clip.persistedRow(row);
}).filter(row => {
return row.id.length > 0 && Clip.isReadableText(row.body);
}).slice(0, maxRows);
} catch (error) {
rows = [];
}
persistenceReady = true;
saveHistory();
}
function saveHistory() {
if (!persistenceReady)
return;
const payload = {
"version": 1,
"rows": rows.map(row => {
return Clip.persistedRow(row);
}).slice(0, maxRows)
};
clipboardHistoryFile.setText(JSON.stringify(payload, null, 2));
}
function setPrivateMode(enabled) {
privateMode = enabled;
lastAction = {
"kind": "private",
"enabled": enabled
};
return stateJson();
}
function pauseForVaultCopy(timeoutSeconds) {
vaultPauseAcknowledged = false;
vaultCopyActive = true;
vaultCopyFailsafe.interval = (Math.max(1, Number(timeoutSeconds || 30)) + 2) * 1000;
vaultCopyFailsafe.restart();
if (!clipboardWatcher.running) {
vaultPauseAcknowledged = true;
vaultCapturePaused();
}
}
function resumeAfterVaultCopy() {
vaultCopyFailsafe.stop();
vaultCopyActive = false;
vaultPauseAcknowledged = false;
}
FileView {
id: clipboardHistoryFile
path: root.historyPath
blockWrites: true
atomicWrites: true
printErrors: false
onLoaded: root.loadHistoryText(clipboardHistoryFile.text())
onLoadFailed: {
root.persistenceReady = true;
root.saveHistory();
}
}
Timer {
id: pasteFocusTimer
interval: 1000
onTriggered: root.finishPaste("paste destination lost focus")
}
Connections {
target: root.niriService
function onFocusedWindowChanged() {
root.checkPasteFocus();
}
}
Connections {
target: root.surfaces
function onPopupOpenChanged() {
if (root.surfaces.popupOpen)
root.checkPasteFocus();
}
}
Component {
id: textProcess
Process {
property string payload
stdinEnabled: true
running: true
onStarted: {
write(payload);
stdinEnabled = false;
payload = "";
}
onRunningChanged: if (!running)
destroy()
}
}
Timer {
id: vaultCopyFailsafe
onTriggered: root.resumeAfterVaultCopy()
}
Process {
id: clipboardWatcher
command: ["wl-paste", "--type", "text/plain", "--watch", "sh", "-c", "cat; printf '\\036'"]
running: !root.vaultCopyActive
onRunningChanged: {
if (root.vaultCopyActive && !running && !root.vaultPauseAcknowledged) {
root.vaultPauseAcknowledged = true;
root.vaultCapturePaused();
}
}
stdout: SplitParser {
splitMarker: "\u001e"
onRead: data => {
return root.captureClipboard(data);
}
}
}
}