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:
1 parent
44a5aedbb2
commit
5a10469efe
15 files changed
+392
-24
No files matched your search
@@ -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()
|
||||
@@ -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()
|
||||
@@ -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)
|
||||
|
||||
Reference in new issue
Block a user