#!/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)