Files
glassMxrph/tests/clipboard_runtime.py
mxandClaude Opus 5.5 5a10469efe 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>
2026-10-15 15:16:14 +02:00

80 lines
4.8 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/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()