From 5a10469efea8b739bf0b5796ef5b9242b6220a1f Mon Sep 17 00:00:00 2001 From: mx Date: Thu, 15 Oct 2026 15:16:14 +0200 Subject: [PATCH] Add Clipboard History as a launcher mode backed by cliphist The launcher gains a clipboard mode with the same bar, position and size: the latest five entries show at once and the rest scroll, search filters in recency order, Enter copies, Shift+Delete removes an entry. >clipboard switches in place without closing or animating; glassmxrph clipboard toggles it directly. History stays with the user's cliphist watcher. Co-Authored-By: Claude Opus 5.5 --- docs/architecture.md | 9 +++ quickshell/core/ShellState.qml | 12 +++- quickshell/helpers/clipboard.py | 90 +++++++++++++++++++++++ quickshell/launcher/CommandRegistry.qml | 13 +++- quickshell/launcher/CommandSearch.qml | 1 + quickshell/launcher/Launcher.qml | 92 +++++++++++++++++++----- quickshell/launcher/LauncherState.qml | 5 ++ quickshell/services/ClipboardService.qml | 69 ++++++++++++++++++ quickshell/services/qmldir | 1 + quickshell/testing/LauncherDriver.qml | 4 +- scripts/glassmxrph | 5 +- scripts/validate | 1 + tests/clipboard_runtime.py | 79 ++++++++++++++++++++ tests/clipboard_test.py | 33 +++++++++ tests/launcher_runtime.py | 2 +- 15 files changed, 392 insertions(+), 24 deletions(-) create mode 100644 quickshell/helpers/clipboard.py create mode 100644 quickshell/services/ClipboardService.qml create mode 100644 tests/clipboard_runtime.py create mode 100644 tests/clipboard_test.py diff --git a/docs/architecture.md b/docs/architecture.md index 8cf4bf7..34642b7 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -146,3 +146,12 @@ is up. Banners time out into history, pause while hovered, and are cleared when opens. `controlcenter/modules/Notifications.qml` stacks history per app (macOS Notification Center); `NotificationCard` is shared by both. Critical notifications stay until dismissed and may break through DND. `tests/notifications_runtime.py` runs on a private session bus. + +## Clipboard History + +Clipboard History is a launcher mode (`ShellState.launcherMode`), so it shares the launcher's +position, size and keyboard handling; `>clipboard` switches in place without closing the window +and snaps the height instead of animating it. `ClipboardService` reads the user's existing cliphist +history through `helpers/clipboard.py` only when the launcher opens, and keeps the last list cached. +The helper never stores entries (the user's `wl-paste --watch cliphist store` does), decodes +thumbnails for the newest images into the cache, and detaches `wl-copy` when copying. diff --git a/quickshell/core/ShellState.qml b/quickshell/core/ShellState.qml index 1c064f5..4d7ff40 100644 --- a/quickshell/core/ShellState.qml +++ b/quickshell/core/ShellState.qml @@ -54,12 +54,16 @@ Singleton { } property bool launcherOpen: false property var launcherScreen: null + // "apps" searches applications and commands; "clipboard" is Clipboard History. + // Changing it on an open launcher switches in place. + property string launcherMode: "apps" function activeScreen() { return ScreenService.active; } - function openLauncher() { + function openLauncher(mode) { wallpaperPickerOpen=false; dashboardOpen = false; + launcherMode = mode === "clipboard" ? "clipboard" : "apps"; if (launcherOpen) return; controlCenterOpen = false; @@ -73,6 +77,12 @@ Singleton { else openLauncher(); } + function toggleClipboard() { + if (launcherOpen && launcherMode === "clipboard") + launcherOpen = false; + else + openLauncher("clipboard"); + } property var settingsWindow: null property bool settingsOpen: false property string settingsPage: "about" diff --git a/quickshell/helpers/clipboard.py b/quickshell/helpers/clipboard.py new file mode 100644 index 0000000..03dc04c --- /dev/null +++ b/quickshell/helpers/clipboard.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python3 +"""cliphist adapter for the launcher's Clipboard History. JSON protocol, argv-only execution. +History is recorded by the user's own `wl-paste --watch cliphist store`; this never stores.""" +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import sys + +IMAGE = re.compile(r'^\[\[ binary data .* (png|jpe?g|gif|webp|bmp) (\d+)x(\d+) \]\]$') +CACHE = Path(os.environ.get('XDG_CACHE_HOME') or Path.home() / '.cache') / 'glassMxrph' / 'clipboard' +THUMBS = 60 # newest images decoded for thumbnails + +def cliphist(*args, data=None, timeout=5): + if not shutil.which('cliphist'): + raise ValueError('cliphist is not installed') + result = subprocess.run(['cliphist', *args], input=data, capture_output=True, timeout=timeout) + if result.returncode: + raise ValueError((result.stderr.decode(errors='replace') or 'cliphist failed').strip()[-300:]) + return result.stdout + +def entry_id(value): + if isinstance(value, bool) or not isinstance(value, int) or value < 0: + raise ValueError('Invalid clipboard entry') + return value + +def thumbnail(id_, ext): + path = CACHE / f'{id_}.{ext}' + if not path.exists(): + CACHE.mkdir(parents=True, exist_ok=True) + tmp = path.with_suffix('.part') + tmp.write_bytes(cliphist('decode', data=f'{id_}\t'.encode())) + tmp.replace(path) + return str(path) + +def history(): + entries, images = [], 0 + for line in cliphist('list').decode(errors='replace').splitlines(): + id_, _, preview = line.partition('\t') + if not id_.isdigit(): + continue + item = {'id': int(id_), 'text': preview} + match = IMAGE.match(preview) + if match: + ext = 'jpg' if match[1] == 'jpeg' else match[1] + item.update(image=True, text=f'Image {match[2]}×{match[3]}') + if images < THUMBS: + images += 1 + try: + item['thumb'] = thumbnail(item['id'], ext) + except (ValueError, OSError, subprocess.TimeoutExpired): + pass + entries.append(item) + # Thumbnails of entries that left the history are removed. + keep = {Path(e['thumb']).name for e in entries if 'thumb' in e} + if CACHE.is_dir(): + for path in CACHE.iterdir(): + if path.name not in keep: + path.unlink(missing_ok=True) + return entries + +def copy(id_): + data = cliphist('decode', data=f'{entry_id(id_)}\t'.encode()) + if not shutil.which('wl-copy'): + raise ValueError('wl-copy is not installed') + # wl-copy stays behind to serve the selection; detach it from this job's pipes. + proc = subprocess.Popen(['wl-copy'], stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True) + proc.stdin.write(data) + proc.stdin.close() + +def main(req): + op = req.get('op') + if op == 'list': + return {'entries': history()} + if op == 'copy': + copy(req.get('id')) + return {} + if op == 'delete': + cliphist('delete', data=f'{entry_id(req.get("id"))}\t'.encode()) + return {'entries': history()} + raise ValueError('Unsupported operation') + +if __name__ == '__main__': + try: + print(json.dumps(dict(ok=True, **main(json.loads(sys.argv[1]))))) + except (ValueError, OSError, KeyError, TypeError, subprocess.TimeoutExpired) as error: + print(json.dumps({'ok': False, 'error': str(error)})) + sys.exit(1) diff --git a/quickshell/launcher/CommandRegistry.qml b/quickshell/launcher/CommandRegistry.qml index f7f3983..4946ccb 100644 --- a/quickshell/launcher/CommandRegistry.qml +++ b/quickshell/launcher/CommandRegistry.qml @@ -13,7 +13,18 @@ Singleton { page: page.id, available: page.available, run: page.launcherAction ? () => ShellState[page.launcherAction]() : undefined - })).concat(extensions) + })).concat(builtins, extensions) + // `stay` commands keep the launcher open (they change its mode in place). + readonly property var builtins: [ + { + id: "clipboard", + title: "Clipboard History", + description: "Search and copy from cliphist", + kind: "Command", + stay: true, + run: () => ShellState.openLauncher("clipboard") + } + ] // Extensions are registered by trusted QML code, never interpreted from search text. function registerCommand(command) { if (!command || !/^[a-z][a-z0-9-]*$/.test(command.id) || !command.title || typeof command.run !== "function" || commands.some(c => c.id === command.id)) diff --git a/quickshell/launcher/CommandSearch.qml b/quickshell/launcher/CommandSearch.qml index fa541b4..ea5301b 100644 --- a/quickshell/launcher/CommandSearch.qml +++ b/quickshell/launcher/CommandSearch.qml @@ -10,6 +10,7 @@ QtObject { title: command.title, description: command.description || "Shell command", command: true, + kind: command.kind || "Settings", fields: [ { text: command.id diff --git a/quickshell/launcher/Launcher.qml b/quickshell/launcher/Launcher.qml index bccb1a5..585c207 100644 --- a/quickshell/launcher/Launcher.qml +++ b/quickshell/launcher/Launcher.qml @@ -12,6 +12,8 @@ import "../core" // Spotlight-style launcher: opens as a single search bar in the upper third. // Typing shows ranked results below it; the magnifying glass (or ↓ in an // empty bar) browses every application as an icon grid; > lists commands. +// Clipboard mode (>clipboard, `glassmxrph clipboard`) lists cliphist history +// in the same bar, newest first, without closing the window to switch. // Runtime selects the concrete Wayland layer implementation. // qmllint disable uncreatable-type PanelWindow { @@ -36,9 +38,10 @@ PanelWindow { showDescriptions: true }) readonly property string query: search.text.trim() - readonly property bool commandMode: query.startsWith(">") + readonly property bool clipboardMode: ShellState.launcherMode === "clipboard" + readonly property bool commandMode: !clipboardMode && query.startsWith(">") property bool browsing: false - readonly property bool showList: query !== "" + readonly property bool showList: clipboardMode || query !== "" readonly property bool showGrid: !showList && browsing readonly property var allApps: ApplicationsService.launchable.map(entry => ({ id: entry.id, @@ -46,13 +49,28 @@ PanelWindow { description: entry.genericName || entry.comment || entry.id, entry: entry })) - readonly property var results: showList ? (commandMode ? commands.results : apps.results) : showGrid ? allApps : [] + readonly property var clipboardResults: clipboardMode && ShellState.launcherOpen ? ClipboardService.filter(query).map(e => ({ + id: e.id, + title: e.text.replace(/\s+/g, " ").trim(), + description: "", + clip: e + })) : [] + readonly property var results: clipboardMode ? clipboardResults : showList ? (commandMode ? commands.results : apps.results) : showGrid ? allApps : [] property int selectedIndex: 0 property string launchError: "" readonly property real targetWidth: Math.min(options.width, root.width - 40) readonly property int barHeight: 60 readonly property real maxBodyHeight: Math.min(460, root.height * 0.78 - barHeight - (root.height * 0.22)) - readonly property real bodyHeight: showList ? Math.min(maxBodyHeight, Math.max(84, list.contentHeight + 46 + (launchError ? 22 : 0))) : showGrid ? Math.min(maxBodyHeight, grid.contentHeight + 46) : 0 + // Clipboard mode shows the latest five rows; the rest scroll. + readonly property real clipboardRows: 5 * 48 - 2 + readonly property real bodyHeight: showList ? Math.min(maxBodyHeight, Math.max(84, (clipboardMode ? Math.min(list.contentHeight, clipboardRows) : list.contentHeight) + 46 + (launchError ? 22 : 0))) : showGrid ? Math.min(maxBodyHeight, grid.contentHeight + 46) : 0 + // Mode switches resize without animating, so >clipboard lands in place. + property bool snapping: false + Timer { + id: unsnap + interval: 120 + onTriggered: root.snapping = false + } readonly property int gridColumns: Math.max(1, Math.floor((targetWidth - 24) / 112)) onResultsChanged: { selectedIndex = 0; @@ -72,8 +90,13 @@ PanelWindow { const result = results[index]; if (!result) return; - if (result.command) { + if (result.clip) { + ClipboardService.copy(result.clip); ShellState.launcherOpen = false; + } else if (result.command) { + const command = CommandRegistry.commands.find(c => c.id === result.id); + if (!command || !command.stay) + ShellState.launcherOpen = false; CommandRegistry.execute(result.id); } else if (ApplicationsService.launch(result.entry, null)) ShellState.launcherOpen = false; @@ -81,6 +104,10 @@ PanelWindow { launchError = ApplicationsService.error; } function toggleBrowse() { + if (clipboardMode) { + ShellState.launcherMode = "apps"; + return; + } browsing = !browsing; if (browsing) search.clear(); @@ -97,9 +124,21 @@ PanelWindow { root.browsing = false; root.launchError = ""; root.selectedIndex = 0; + ClipboardService.refresh(); Qt.callLater(() => search.forceActiveFocus()); } } + function onLauncherModeChanged() { + if (!ShellState.launcherOpen) + return; + root.snapping = true; + unsnap.restart(); + search.text = ""; + root.browsing = false; + root.launchError = ""; + root.selectedIndex = 0; + search.forceActiveFocus(); + } } AppSearch { id: apps @@ -135,6 +174,7 @@ PanelWindow { } } Behavior on height { + enabled: !root.snapping NumberAnimation { duration: Theme.duration easing.type: Easing.OutCubic @@ -172,7 +212,7 @@ PanelWindow { radius: 12 color: root.browsing ? Theme.accent : browseArea.containsMouse ? Theme.hover : Theme.transparent Accessible.role: Accessible.Button - Accessible.name: root.browsing ? "Hide applications" : "Show all applications" + Accessible.name: root.clipboardMode ? "Back to search" : root.browsing ? "Hide applications" : "Show all applications" Behavior on color { ColorAnimation { duration: Theme.duration / 2 @@ -180,7 +220,7 @@ PanelWindow { } Text { anchors.centerIn: parent - text: root.commandMode ? ">" : Icons.available ? "󰍉" : "⌕" + text: root.commandMode ? ">" : !Icons.available ? (root.clipboardMode ? "⎘" : "⌕") : root.clipboardMode ? "󰅌" : "󰍉" font.family: Icons.available && !root.commandMode ? Icons.family : "" color: root.browsing ? Theme.accentText : Theme.textSecondary font.pixelSize: 20 @@ -194,14 +234,14 @@ PanelWindow { } ToolTip.visible: browseArea.containsMouse ToolTip.delay: 600 - ToolTip.text: root.browsing ? "Hide applications" : "All applications" + ToolTip.text: root.clipboardMode ? "Back to search" : root.browsing ? "Hide applications" : "All applications" } TextField { id: search objectName: "launcherSearch" Layout.fillWidth: true Layout.preferredHeight: 40 - placeholderText: root.browsing ? "Search applications" : "Search :3" + placeholderText: root.clipboardMode ? "Clipboard History" : root.browsing ? "Search applications" : "Search :3" color: Theme.text placeholderTextColor: Theme.textSecondary selectByMouse: true @@ -238,6 +278,13 @@ PanelWindow { else event.accepted = false; } + // Shift+Delete removes the selected clipboard entry from history. + Keys.onDeletePressed: event => { + if (root.clipboardMode && event.modifiers & Qt.ShiftModifier && root.results[root.selectedIndex]) + ClipboardService.remove(root.results[root.selectedIndex].clip); + else + event.accepted = false; + } Keys.onTabPressed: root.select(1) Keys.onBacktabPressed: root.select(-1) Keys.onReturnPressed: root.activate(root.selectedIndex) @@ -265,7 +312,7 @@ PanelWindow { id: section x: 22 y: 12 - text: root.showGrid ? "Applications" : root.commandMode ? "Settings" : root.results.length ? "Top hits" : "" + text: root.clipboardMode ? (!root.results.length ? "" : root.query ? "Matches" : "Recent") : root.showGrid ? "Applications" : root.commandMode ? "Settings" : root.results.length ? "Top hits" : "" color: Theme.textSecondary font.pixelSize: 11 font.weight: Font.DemiBold @@ -299,32 +346,39 @@ PanelWindow { anchors.rightMargin: 12 spacing: 12 Item { - Layout.preferredWidth: 30 + readonly property var copied: resultRow.modelData.clip + // Copied images get a wider thumbnail slot. + Layout.preferredWidth: copied && copied.thumb ? 52 : 30 Layout.preferredHeight: 30 Image { id: icon anchors.fill: parent - source: resultRow.modelData.entry ? ApplicationsService.icon(resultRow.modelData.entry) : "" - sourceSize: Qt.size(60, 60) + source: parent.copied ? (parent.copied.thumb ? "file://" + parent.copied.thumb : "") : resultRow.modelData.entry ? ApplicationsService.icon(resultRow.modelData.entry) : "" + sourceSize: parent.copied ? Qt.size(104, 60) : Qt.size(60, 60) fillMode: Image.PreserveAspectFit + asynchronous: !!parent.copied } Text { anchors.centerIn: parent visible: icon.source.toString() === "" || icon.status === Image.Error - text: resultRow.modelData.command ? "⚙" : resultRow.modelData.title.slice(0, 2).toUpperCase() + text: parent.copied ? (Icons.available ? (parent.copied.image ? "󰋩" : "󰅍") : "¶") : resultRow.modelData.command ? "⚙" : resultRow.modelData.title.slice(0, 2).toUpperCase() + font.family: parent.copied && Icons.available ? Icons.family : "" color: resultRow.selected ? Theme.accentText : Theme.textSecondary - font.pixelSize: 16 + font.pixelSize: parent.copied ? 18 : 16 } } Text { text: resultRow.modelData.title + // Clipboard text is shown as is, never as markup. + textFormat: Text.PlainText + Layout.fillWidth: !!resultRow.modelData.clip elide: Text.ElideRight color: resultRow.selected ? Theme.accentText : Theme.text font.pixelSize: 14 font.weight: Font.Medium } Text { - visible: root.options.showDescriptions + visible: root.options.showDescriptions && !resultRow.modelData.clip text: "— " + resultRow.modelData.description Layout.fillWidth: true elide: Text.ElideRight @@ -332,11 +386,11 @@ PanelWindow { font.pixelSize: 12 } Item { - visible: !root.options.showDescriptions + visible: !root.options.showDescriptions && !resultRow.modelData.clip Layout.fillWidth: true } Text { - text: resultRow.modelData.command ? "Settings" : "Application" + text: resultRow.modelData.clip ? (resultRow.modelData.clip.image ? "Image" : "Text") : resultRow.modelData.command ? resultRow.modelData.kind : "Application" color: resultRow.selected ? Qt.alpha(Theme.accentText, 0.75) : Theme.textSecondary font.pixelSize: 11 } @@ -429,7 +483,7 @@ PanelWindow { anchors.centerIn: parent anchors.verticalCenterOffset: 12 visible: root.showList && root.results.length === 0 - text: root.commandMode ? "No matching settings" : "No results" + text: root.clipboardMode ? (ClipboardService.error || (root.query ? "No matches" : ClipboardService.loaded ? "Clipboard history is empty" : "Loading…")) : root.commandMode ? "No matching settings" : "No results" color: Theme.textSecondary font.pixelSize: 13 } diff --git a/quickshell/launcher/LauncherState.qml b/quickshell/launcher/LauncherState.qml index 7c6d66f..465a466 100644 --- a/quickshell/launcher/LauncherState.qml +++ b/quickshell/launcher/LauncherState.qml @@ -18,9 +18,14 @@ Singleton { function close(): void { ShellState.launcherOpen = false; } + // Opens Clipboard History, or closes it when it is showing. + function clipboard(): void { + ShellState.toggleClipboard(); + } function status(): string { return JSON.stringify({ opened: ShellState.launcherOpen, + mode: ShellState.launcherMode, screen: root.window && root.window.screen ? root.window.screen.name : "", ready: !!root.window }); diff --git a/quickshell/services/ClipboardService.qml b/quickshell/services/ClipboardService.qml new file mode 100644 index 0000000..732da3c --- /dev/null +++ b/quickshell/services/ClipboardService.qml @@ -0,0 +1,69 @@ +pragma Singleton +import QtQuick +import Quickshell + +// Clipboard history from cliphist, for the launcher's clipboard mode. The +// list is read only while the launcher opens; the last result stays cached so +// switching into clipboard mode shows entries immediately. +Singleton { + id: root + // Newest first: {id, text, image?, thumb?}. + property var entries: [] + property string error: "" + property bool loaded: false + readonly property bool loading: lister.running + + function refresh() { + lister.start({ + op: "list" + }); + } + // Space-separated terms, all required; recency order is kept like rofi. + function filter(query) { + const terms = query.toLowerCase().split(/\s+/).filter(t => t); + if (!terms.length) + return entries; + return entries.filter(e => { + const text = e.text.toLowerCase(); + return terms.every(t => text.includes(t)); + }); + } + function copy(entry) { + return entry && actions.start({ + op: "copy", + id: entry.id + }); + } + function remove(entry) { + if (!entry) + return false; + // Optimistic: the row leaves at once; the helper returns the new list. + entries = entries.filter(e => e.id !== entry.id); + return actions.start({ + op: "delete", + id: entry.id + }); + } + + ProviderJob { + id: lister + helper: "helpers/clipboard.py" + onFinished: (request, result) => root.apply(result) + } + ProviderJob { + id: actions + helper: "helpers/clipboard.py" + onFinished: (request, result) => root.apply(result) + } + function apply(result) { + if (!result.ok) { + error = result.error || "Clipboard history is unavailable"; + return; + } + error = ""; + if (result.entries) { + entries = result.entries; + loaded = true; + } + } +} diff --git a/quickshell/services/qmldir b/quickshell/services/qmldir index 7ed596c..e42c4b9 100644 --- a/quickshell/services/qmldir +++ b/quickshell/services/qmldir @@ -17,3 +17,4 @@ singleton GlassService 1.0 GlassService.qml singleton EasyEffectsService 1.0 EasyEffectsService.qml singleton PluginService 1.0 PluginService.qml singleton NotificationService 1.0 NotificationService.qml +singleton ClipboardService 1.0 ClipboardService.qml diff --git a/quickshell/testing/LauncherDriver.qml b/quickshell/testing/LauncherDriver.qml index e565eb1..d302335 100644 --- a/quickshell/testing/LauncherDriver.qml +++ b/quickshell/testing/LauncherDriver.qml @@ -44,6 +44,7 @@ Item { return JSON.stringify({ activeMonitor: ScreenService.active ? ScreenService.active.name : "", opened: ShellState.launcherOpen, + mode: ShellState.launcherMode, screen: w.screen.name, screenWidth: w.width, screenHeight: w.height, @@ -58,7 +59,8 @@ Item { results: w.results.map(r => ({ id: r.id, title: r.title, - command: !!r.command + command: !!r.command, + image: !!(r.clip && r.clip.image) })), error: w.launchError }); diff --git a/scripts/glassmxrph b/scripts/glassmxrph index fe6659c..f621700 100755 --- a/scripts/glassmxrph +++ b/scripts/glassmxrph @@ -31,6 +31,9 @@ case "${1:-run}" in launcher) exec quickshell ipc --path "$project_dir/quickshell" call launcher toggle ;; + clipboard) + exec quickshell ipc --path "$project_dir/quickshell" call launcher clipboard + ;; plugin) # glassmxrph plugin [list|install SOURCE|remove ID|enable ID|disable ID|summon ID|toggle ID] action=${2:-list} @@ -67,5 +70,5 @@ case "${1:-run}" in settings|close|status) exec quickshell ipc --path "$project_dir/quickshell" call shell "$1" ;; - *) echo 'Usage: glassmxrph [run|wallpaper|launcher|dashboard [TAB]|plugin ACTION|controlcenter|lock|widgets|osd ACTION|notifications ACTION|settings|close|status|doctor]' >&2; exit 2 ;; + *) echo 'Usage: glassmxrph [run|wallpaper|launcher|clipboard|dashboard [TAB]|plugin ACTION|controlcenter|lock|widgets|osd ACTION|notifications ACTION|settings|close|status|doctor]' >&2; exit 2 ;; esac diff --git a/scripts/validate b/scripts/validate index 8299c69..b7147b2 100755 --- a/scripts/validate +++ b/scripts/validate @@ -10,6 +10,7 @@ python3 "$project_dir/tests/providers_test.py" python3 "$project_dir/tests/system_providers_test.py" python3 "$project_dir/tests/metrics_test.py" python3 "$project_dir/tests/glass_test.py" +python3 "$project_dir/tests/clipboard_test.py" # compat/ holds vendored third-party UI kits (qs.compat.* imports qmllint cannot # resolve); they are exercised by the plugin runtime test instead. find "$project_dir/quickshell" -name '*.qml' -not -path '*/compat/*' -exec qmllint -E "$@" {} + diff --git a/tests/clipboard_runtime.py b/tests/clipboard_runtime.py new file mode 100644 index 0000000..48f7440 --- /dev/null +++ b/tests/clipboard_runtime.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python3 +"""Real Wayland Clipboard History test: a private cliphist database and session bus. +Copying is global on Wayland, so the user's clipboard is saved and restored. +Run: dbus-run-session -- python3 tests/clipboard_runtime.py [screenshot-dir]""" +import json,os,struct,subprocess,sys,tempfile,time,zlib +from pathlib import Path +ROOT=Path(__file__).resolve().parents[1] +BASE=['quickshell','ipc','--path',str(ROOT/'quickshell'),'call'] +SHOTS=Path(sys.argv[1]) if len(sys.argv)>1 else None +Key={'Return':0x01000004,'Down':0x01000015} +def ipc(target,method,*args): + r=subprocess.run(BASE+[target,method,*map(str,args)],capture_output=True,text=True) + out=r.stdout.strip() + if r.returncode or not out:return None + try:return json.loads(out) + except ValueError:return out +def snap():return ipc('launcherTest','snapshot') or {} +def wait(check,label,timeout=10): + end=time.monotonic()+timeout + while time.monotonic()I',len(data))+kind+data+struct.pack('>I',zlib.crc32(kind+data)) + rows=b''.join(b'\0'+bytes(rgb)*w for _ in range(h)) + return b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('>IIBBBBB',w,h,8,2,0,0,0))+chunk(b'IDAT',zlib.compress(rows))+chunk(b'IEND',b'') +def shot(name): + if SHOTS: + time.sleep(.5);SHOTS.mkdir(parents=True,exist_ok=True) + subprocess.run(['grim','-o',snap()['screen'],str(SHOTS/(name+'.png'))],check=False) +if 'DBUS_SESSION_BUS_ADDRESS' not in os.environ or ipc('shell','status'):raise SystemExit('Run in a private dbus-run-session with no instance from this path.') +saved=subprocess.run(['wl-paste','--no-newline'],capture_output=True,timeout=5) +log=ROOT/'.cache/clipboard-runtime.log';log.parent.mkdir(exist_ok=True) +with tempfile.TemporaryDirectory(prefix='glassmxrph-clipboard-') as tmp: + env=dict(os.environ,XDG_CONFIG_HOME=tmp+'/config',XDG_STATE_HOME=tmp+'/state',XDG_CACHE_HOME=tmp+'/cache',GLASSMXRPH_LAUNCHER_TESTING='1',QT_NO_XDG_DESKTOP_PORTAL='1') + Path(tmp,'config/glassMxrph').mkdir(parents=True) + Path(tmp,'config/glassMxrph/config.json').write_text(json.dumps({'schemaVersion':3,'dock':{'enabled':False}})) + texts=['alpha one','beta two','gamma three','delta four','epsilon five','zeta six','eta seven','theta eight'] + for t in texts:subprocess.run(['cliphist','store'],input=t.encode(),env=env,check=True) + subprocess.run(['cliphist','store'],input=png(160,90,(64,140,220)),env=env,check=True) + with log.open('w') as output: + shell=subprocess.Popen([str(ROOT/'scripts/glassmxrph'),'run'],env=env,stdout=output,stderr=subprocess.STDOUT) + try: + wait(lambda:ipc('shell','status')['ready'],'ready') + ipc('launcher','open');wait(lambda:snap()['opened'] and snap()['focused'],'launcher opens') + time.sleep(.4);before=snap() + ipc('launcherTest','query','>clipboard') + wait(lambda:snap()['results'][0]['id']=='clipboard','clipboard command listed') + ipc('launcherTest','key',Key['Return']) + wait(lambda:snap()['mode']=='clipboard' and len(snap()['results'])==9,'command switches to clipboard mode') + s=snap();assert s['opened'] and s['query']=='' and s['focused'],s + assert (s['x'],s['y'],s['width'])==(before['x'],before['y'],before['width']),(before,s) + assert s['results'][0]['image'] and s['results'][0]['title']=='Image 160×90',s['results'][0] + assert [r['title'] for r in s['results'][1:]]==texts[::-1],s['results'] + time.sleep(.3);shot('1-clipboard') + # Five rows visible: the body stops growing past them. + assert 60+5*48-2+46-2<=snap()['height']<=60+5*48-2+46+2,snap()['height'] + ipc('launcherTest','query','be') + wait(lambda:[r['title'] for r in snap()['results']]==['beta two'],'search filters') + shot('2-search') + ipc('launcherTest','key',Key['Return']) + wait(lambda:not snap()['opened'],'copying closes') + wait(lambda:subprocess.run(['wl-paste','--no-newline'],capture_output=True,text=True,timeout=5).stdout=='beta two','entry copied') + ipc('launcher','clipboard');wait(lambda:snap()['opened'] and snap()['mode']=='clipboard','IPC opens clipboard') + ipc('launcher','clipboard');wait(lambda:not snap()['opened'],'IPC toggles it closed') + ipc('launcher','open');wait(lambda:snap()['opened'] and snap()['mode']=='apps','launcher reopens in app mode') + ipc('launcher','close') + print('Clipboard history: >clipboard switches in place, five recent rows, search, copy, IPC toggle passed.') + finally: + shell.terminate() + try:shell.wait(5) + except subprocess.TimeoutExpired:shell.kill() + # wl-copy stays behind to serve the selection; keep it off this process's pipes. + if saved.returncode==0: + restore=subprocess.Popen(['wl-copy'],stdin=subprocess.PIPE,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,start_new_session=True) + restore.stdin.write(saved.stdout);restore.stdin.close() diff --git a/tests/clipboard_test.py b/tests/clipboard_test.py new file mode 100644 index 0000000..0e8f239 --- /dev/null +++ b/tests/clipboard_test.py @@ -0,0 +1,33 @@ +#!/usr/bin/env python3 +import json,subprocess,sys,tempfile,unittest +from pathlib import Path +from unittest.mock import patch +ROOT=Path(__file__).resolve().parents[1] +sys.path.insert(0,str(ROOT/'quickshell/helpers')) +import clipboard +class ClipboardHelper(unittest.TestCase): + def setUp(self): + self.tmp=tempfile.TemporaryDirectory();self.cache=patch.object(clipboard,'CACHE',Path(self.tmp.name));self.cache.start() + def tearDown(self):self.cache.stop();self.tmp.cleanup() + def test_history_parses_text_and_images_newest_first(self): + listing=b'3\t[[ binary data 2 KiB png 640x480 ]]\n2\thello\tworld\n1\tplain\n' + def fake(*args,data=None,timeout=5):return listing if args==('list',) else b'PNGDATA' + with patch.object(clipboard,'cliphist',side_effect=fake): + entries=clipboard.history() + self.assertEqual([e['id'] for e in entries],[3,2,1]) + self.assertTrue(entries[0]['image']);self.assertEqual(entries[0]['text'],'Image 640×480') + self.assertEqual(Path(entries[0]['thumb']).read_bytes(),b'PNGDATA') + self.assertEqual(entries[1]['text'],'hello\tworld') + def test_stale_thumbnails_are_pruned(self): + (Path(self.tmp.name)/'9.png').write_bytes(b'old') + with patch.object(clipboard,'cliphist',return_value=b'1\ttext\n'):clipboard.history() + self.assertFalse((Path(self.tmp.name)/'9.png').exists()) + def test_ids_are_validated_before_cliphist_runs(self): + with patch.object(clipboard,'cliphist') as run: + for bad in [None,'1;rm',-1,True,1.5]: + with self.assertRaises(ValueError):clipboard.main({'op':'delete','id':bad}) + run.assert_not_called() + def test_cli_errors_are_json(self): + p=subprocess.run([sys.executable,str(ROOT/'quickshell/helpers/clipboard.py'),'{"op":"unknown"}'],capture_output=True,text=True) + self.assertFalse(json.loads(p.stdout)['ok']);self.assertEqual(p.returncode,1) +if __name__=='__main__':unittest.main() diff --git a/tests/launcher_runtime.py b/tests/launcher_runtime.py index 4da7be6..98a7746 100644 --- a/tests/launcher_runtime.py +++ b/tests/launcher_runtime.py @@ -112,7 +112,7 @@ Terminal={'true' if suffix=='Terminal' else 'false'} ipc('launcherTest','key',ESC) eventually(lambda:not snapshot()['visible'],'Escape dismiss') open_launcher();query('>') - eventually(lambda:{r['id'] for r in snapshot()['results']}=={'about','appearance','audio','bar','tray','bluetooth','controlcenter','display','dock','launcher','media','metrics','network','notifications','power','wallpaper','widgets','osd','lock','dashboard','plugins'},'all commands registered') + eventually(lambda:{r['id'] for r in snapshot()['results']}=={'about','appearance','audio','bar','tray','bluetooth','controlcenter','display','dock','launcher','media','metrics','network','notifications','power','wallpaper','widgets','osd','lock','dashboard','plugins','clipboard'},'all commands registered') time.sleep(.3);assert ipc('launcherTest','screenshot',str(ROOT/'.cache/launcher-preview.png')) for text,page in [('>metrics','metrics'),('>dock','dock'),('>media','media'),('>tray','tray'),('>display','displays'),('>launcher','launcher'),('>appearance','appearance'),('>bar','bar'),('>network','network'),('>bluetooth','bluetooth'),('>audio','audio'),('>controlcenter','controlcenter'),('>notifications','notifications'),('>power','power'),('>about','about')]: query(text)