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 <noreply@anthropic.com>
This commit is contained in:
mxandClaude Opus 5.5 committed 2026-10-15 15:16:14 +02:00
1 parent 44a5aedbb2
commit 5a10469efe
15 files changed
+392 -24

No files matched your search

+9
View File
@@ -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 opens. `controlcenter/modules/Notifications.qml` stacks history per app (macOS Notification
Center); `NotificationCard` is shared by both. Critical notifications stay until dismissed and 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. 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.
+11 -1
View File
@@ -54,12 +54,16 @@ Singleton {
} }
property bool launcherOpen: false property bool launcherOpen: false
property var launcherScreen: null 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() { function activeScreen() {
return ScreenService.active; return ScreenService.active;
} }
function openLauncher() { function openLauncher(mode) {
wallpaperPickerOpen=false; wallpaperPickerOpen=false;
dashboardOpen = false; dashboardOpen = false;
launcherMode = mode === "clipboard" ? "clipboard" : "apps";
if (launcherOpen) if (launcherOpen)
return; return;
controlCenterOpen = false; controlCenterOpen = false;
@@ -73,6 +77,12 @@ Singleton {
else else
openLauncher(); openLauncher();
} }
function toggleClipboard() {
if (launcherOpen && launcherMode === "clipboard")
launcherOpen = false;
else
openLauncher("clipboard");
}
property var settingsWindow: null property var settingsWindow: null
property bool settingsOpen: false property bool settingsOpen: false
property string settingsPage: "about" property string settingsPage: "about"
+90
View File
@@ -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)
+12 -1
View File
@@ -13,7 +13,18 @@ Singleton {
page: page.id, page: page.id,
available: page.available, available: page.available,
run: page.launcherAction ? () => ShellState[page.launcherAction]() : undefined 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. // Extensions are registered by trusted QML code, never interpreted from search text.
function registerCommand(command) { 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)) if (!command || !/^[a-z][a-z0-9-]*$/.test(command.id) || !command.title || typeof command.run !== "function" || commands.some(c => c.id === command.id))
+1
View File
@@ -10,6 +10,7 @@ QtObject {
title: command.title, title: command.title,
description: command.description || "Shell command", description: command.description || "Shell command",
command: true, command: true,
kind: command.kind || "Settings",
fields: [ fields: [
{ {
text: command.id text: command.id
+73 -19
View File
@@ -12,6 +12,8 @@ import "../core"
// Spotlight-style launcher: opens as a single search bar in the upper third. // 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 // Typing shows ranked results below it; the magnifying glass (or ↓ in an
// empty bar) browses every application as an icon grid; > lists commands. // 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. // Runtime selects the concrete Wayland layer implementation.
// qmllint disable uncreatable-type // qmllint disable uncreatable-type
PanelWindow { PanelWindow {
@@ -36,9 +38,10 @@ PanelWindow {
showDescriptions: true showDescriptions: true
}) })
readonly property string query: search.text.trim() 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 property bool browsing: false
readonly property bool showList: query !== "" readonly property bool showList: clipboardMode || query !== ""
readonly property bool showGrid: !showList && browsing readonly property bool showGrid: !showList && browsing
readonly property var allApps: ApplicationsService.launchable.map(entry => ({ readonly property var allApps: ApplicationsService.launchable.map(entry => ({
id: entry.id, id: entry.id,
@@ -46,13 +49,28 @@ PanelWindow {
description: entry.genericName || entry.comment || entry.id, description: entry.genericName || entry.comment || entry.id,
entry: entry 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 int selectedIndex: 0
property string launchError: "" property string launchError: ""
readonly property real targetWidth: Math.min(options.width, root.width - 40) readonly property real targetWidth: Math.min(options.width, root.width - 40)
readonly property int barHeight: 60 readonly property int barHeight: 60
readonly property real maxBodyHeight: Math.min(460, root.height * 0.78 - barHeight - (root.height * 0.22)) 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)) readonly property int gridColumns: Math.max(1, Math.floor((targetWidth - 24) / 112))
onResultsChanged: { onResultsChanged: {
selectedIndex = 0; selectedIndex = 0;
@@ -72,8 +90,13 @@ PanelWindow {
const result = results[index]; const result = results[index];
if (!result) if (!result)
return; return;
if (result.command) { if (result.clip) {
ClipboardService.copy(result.clip);
ShellState.launcherOpen = false; 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); CommandRegistry.execute(result.id);
} else if (ApplicationsService.launch(result.entry, null)) } else if (ApplicationsService.launch(result.entry, null))
ShellState.launcherOpen = false; ShellState.launcherOpen = false;
@@ -81,6 +104,10 @@ PanelWindow {
launchError = ApplicationsService.error; launchError = ApplicationsService.error;
} }
function toggleBrowse() { function toggleBrowse() {
if (clipboardMode) {
ShellState.launcherMode = "apps";
return;
}
browsing = !browsing; browsing = !browsing;
if (browsing) if (browsing)
search.clear(); search.clear();
@@ -97,9 +124,21 @@ PanelWindow {
root.browsing = false; root.browsing = false;
root.launchError = ""; root.launchError = "";
root.selectedIndex = 0; root.selectedIndex = 0;
ClipboardService.refresh();
Qt.callLater(() => search.forceActiveFocus()); 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 { AppSearch {
id: apps id: apps
@@ -135,6 +174,7 @@ PanelWindow {
} }
} }
Behavior on height { Behavior on height {
enabled: !root.snapping
NumberAnimation { NumberAnimation {
duration: Theme.duration duration: Theme.duration
easing.type: Easing.OutCubic easing.type: Easing.OutCubic
@@ -172,7 +212,7 @@ PanelWindow {
radius: 12 radius: 12
color: root.browsing ? Theme.accent : browseArea.containsMouse ? Theme.hover : Theme.transparent color: root.browsing ? Theme.accent : browseArea.containsMouse ? Theme.hover : Theme.transparent
Accessible.role: Accessible.Button 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 { Behavior on color {
ColorAnimation { ColorAnimation {
duration: Theme.duration / 2 duration: Theme.duration / 2
@@ -180,7 +220,7 @@ PanelWindow {
} }
Text { Text {
anchors.centerIn: parent 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 : "" font.family: Icons.available && !root.commandMode ? Icons.family : ""
color: root.browsing ? Theme.accentText : Theme.textSecondary color: root.browsing ? Theme.accentText : Theme.textSecondary
font.pixelSize: 20 font.pixelSize: 20
@@ -194,14 +234,14 @@ PanelWindow {
} }
ToolTip.visible: browseArea.containsMouse ToolTip.visible: browseArea.containsMouse
ToolTip.delay: 600 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 { TextField {
id: search id: search
objectName: "launcherSearch" objectName: "launcherSearch"
Layout.fillWidth: true Layout.fillWidth: true
Layout.preferredHeight: 40 Layout.preferredHeight: 40
placeholderText: root.browsing ? "Search applications" : "Search :3" placeholderText: root.clipboardMode ? "Clipboard History" : root.browsing ? "Search applications" : "Search :3"
color: Theme.text color: Theme.text
placeholderTextColor: Theme.textSecondary placeholderTextColor: Theme.textSecondary
selectByMouse: true selectByMouse: true
@@ -238,6 +278,13 @@ PanelWindow {
else else
event.accepted = false; 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.onTabPressed: root.select(1)
Keys.onBacktabPressed: root.select(-1) Keys.onBacktabPressed: root.select(-1)
Keys.onReturnPressed: root.activate(root.selectedIndex) Keys.onReturnPressed: root.activate(root.selectedIndex)
@@ -265,7 +312,7 @@ PanelWindow {
id: section id: section
x: 22 x: 22
y: 12 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 color: Theme.textSecondary
font.pixelSize: 11 font.pixelSize: 11
font.weight: Font.DemiBold font.weight: Font.DemiBold
@@ -299,32 +346,39 @@ PanelWindow {
anchors.rightMargin: 12 anchors.rightMargin: 12
spacing: 12 spacing: 12
Item { 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 Layout.preferredHeight: 30
Image { Image {
id: icon id: icon
anchors.fill: parent anchors.fill: parent
source: resultRow.modelData.entry ? ApplicationsService.icon(resultRow.modelData.entry) : "" source: parent.copied ? (parent.copied.thumb ? "file://" + parent.copied.thumb : "") : resultRow.modelData.entry ? ApplicationsService.icon(resultRow.modelData.entry) : ""
sourceSize: Qt.size(60, 60) sourceSize: parent.copied ? Qt.size(104, 60) : Qt.size(60, 60)
fillMode: Image.PreserveAspectFit fillMode: Image.PreserveAspectFit
asynchronous: !!parent.copied
} }
Text { Text {
anchors.centerIn: parent anchors.centerIn: parent
visible: icon.source.toString() === "" || icon.status === Image.Error 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 color: resultRow.selected ? Theme.accentText : Theme.textSecondary
font.pixelSize: 16 font.pixelSize: parent.copied ? 18 : 16
} }
} }
Text { Text {
text: resultRow.modelData.title text: resultRow.modelData.title
// Clipboard text is shown as is, never as markup.
textFormat: Text.PlainText
Layout.fillWidth: !!resultRow.modelData.clip
elide: Text.ElideRight elide: Text.ElideRight
color: resultRow.selected ? Theme.accentText : Theme.text color: resultRow.selected ? Theme.accentText : Theme.text
font.pixelSize: 14 font.pixelSize: 14
font.weight: Font.Medium font.weight: Font.Medium
} }
Text { Text {
visible: root.options.showDescriptions visible: root.options.showDescriptions && !resultRow.modelData.clip
text: "— " + resultRow.modelData.description text: "— " + resultRow.modelData.description
Layout.fillWidth: true Layout.fillWidth: true
elide: Text.ElideRight elide: Text.ElideRight
@@ -332,11 +386,11 @@ PanelWindow {
font.pixelSize: 12 font.pixelSize: 12
} }
Item { Item {
visible: !root.options.showDescriptions visible: !root.options.showDescriptions && !resultRow.modelData.clip
Layout.fillWidth: true Layout.fillWidth: true
} }
Text { 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 color: resultRow.selected ? Qt.alpha(Theme.accentText, 0.75) : Theme.textSecondary
font.pixelSize: 11 font.pixelSize: 11
} }
@@ -429,7 +483,7 @@ PanelWindow {
anchors.centerIn: parent anchors.centerIn: parent
anchors.verticalCenterOffset: 12 anchors.verticalCenterOffset: 12
visible: root.showList && root.results.length === 0 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 color: Theme.textSecondary
font.pixelSize: 13 font.pixelSize: 13
} }
+5
View File
@@ -18,9 +18,14 @@ Singleton {
function close(): void { function close(): void {
ShellState.launcherOpen = false; ShellState.launcherOpen = false;
} }
// Opens Clipboard History, or closes it when it is showing.
function clipboard(): void {
ShellState.toggleClipboard();
}
function status(): string { function status(): string {
return JSON.stringify({ return JSON.stringify({
opened: ShellState.launcherOpen, opened: ShellState.launcherOpen,
mode: ShellState.launcherMode,
screen: root.window && root.window.screen ? root.window.screen.name : "", screen: root.window && root.window.screen ? root.window.screen.name : "",
ready: !!root.window ready: !!root.window
}); });
+69
View File
@@ -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;
}
}
}
+1
View File
@@ -17,3 +17,4 @@ singleton GlassService 1.0 GlassService.qml
singleton EasyEffectsService 1.0 EasyEffectsService.qml singleton EasyEffectsService 1.0 EasyEffectsService.qml
singleton PluginService 1.0 PluginService.qml singleton PluginService 1.0 PluginService.qml
singleton NotificationService 1.0 NotificationService.qml singleton NotificationService 1.0 NotificationService.qml
singleton ClipboardService 1.0 ClipboardService.qml
+3 -1
View File
@@ -44,6 +44,7 @@ Item {
return JSON.stringify({ return JSON.stringify({
activeMonitor: ScreenService.active ? ScreenService.active.name : "", activeMonitor: ScreenService.active ? ScreenService.active.name : "",
opened: ShellState.launcherOpen, opened: ShellState.launcherOpen,
mode: ShellState.launcherMode,
screen: w.screen.name, screen: w.screen.name,
screenWidth: w.width, screenWidth: w.width,
screenHeight: w.height, screenHeight: w.height,
@@ -58,7 +59,8 @@ Item {
results: w.results.map(r => ({ results: w.results.map(r => ({
id: r.id, id: r.id,
title: r.title, title: r.title,
command: !!r.command command: !!r.command,
image: !!(r.clip && r.clip.image)
})), })),
error: w.launchError error: w.launchError
}); });
+4 -1
View File
@@ -31,6 +31,9 @@ case "${1:-run}" in
launcher) launcher)
exec quickshell ipc --path "$project_dir/quickshell" call launcher toggle exec quickshell ipc --path "$project_dir/quickshell" call launcher toggle
;; ;;
clipboard)
exec quickshell ipc --path "$project_dir/quickshell" call launcher clipboard
;;
plugin) plugin)
# glassmxrph plugin [list|install SOURCE|remove ID|enable ID|disable ID|summon ID|toggle ID] # glassmxrph plugin [list|install SOURCE|remove ID|enable ID|disable ID|summon ID|toggle ID]
action=${2:-list} action=${2:-list}
@@ -67,5 +70,5 @@ case "${1:-run}" in
settings|close|status) settings|close|status)
exec quickshell ipc --path "$project_dir/quickshell" call shell "$1" 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 esac
+1
View File
@@ -10,6 +10,7 @@ python3 "$project_dir/tests/providers_test.py"
python3 "$project_dir/tests/system_providers_test.py" python3 "$project_dir/tests/system_providers_test.py"
python3 "$project_dir/tests/metrics_test.py" python3 "$project_dir/tests/metrics_test.py"
python3 "$project_dir/tests/glass_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 # compat/ holds vendored third-party UI kits (qs.compat.* imports qmllint cannot
# resolve); they are exercised by the plugin runtime test instead. # resolve); they are exercised by the plugin runtime test instead.
find "$project_dir/quickshell" -name '*.qml' -not -path '*/compat/*' -exec qmllint -E "$@" {} + find "$project_dir/quickshell" -name '*.qml' -not -path '*/compat/*' -exec qmllint -E "$@" {} +
+79
View File
@@ -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()<end:
try:
if check():return
except (TypeError,KeyError,ValueError,IndexError):pass
time.sleep(.08)
raise AssertionError(label+': '+json.dumps(snap())[:600])
def png(w,h,rgb):
chunk=lambda kind,data:struct.pack('>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 <b>four</b>','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()
+33
View File
@@ -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()
+1 -1
View File
@@ -112,7 +112,7 @@ Terminal={'true' if suffix=='Terminal' else 'false'}
ipc('launcherTest','key',ESC) ipc('launcherTest','key',ESC)
eventually(lambda:not snapshot()['visible'],'Escape dismiss') eventually(lambda:not snapshot()['visible'],'Escape dismiss')
open_launcher();query('>') 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')) 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')]: 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) query(text)