Back to the drawer picker, now with justified rows: each thumbnail keeps its aspect ratio (read from the file header by the scan) and every row fills the width. Arrows move in two dimensions, click or Enter applies, ✦ marks outline wallpapers. Drops the full-screen preview picker. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
156 lines
8.6 KiB
Python
156 lines
8.6 KiB
Python
#!/usr/bin/env python3
|
|
"""One-shot filesystem/provider adapter. JSON in argv, JSON out; never shell-evaluates input."""
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
|
|
SCHEMES=['scheme-content','scheme-expressive','scheme-fidelity','scheme-fruit-salad','scheme-monochrome','scheme-neutral','scheme-rainbow','scheme-tonal-spot','scheme-vibrant','scheme-smart']
|
|
IMAGES={'.png','.jpg','.jpeg','.webp','.bmp'}
|
|
|
|
def run(argv,timeout=15):
|
|
p=subprocess.run(argv,capture_output=True,text=True,timeout=timeout,stdin=subprocess.DEVNULL)
|
|
if p.returncode:raise ValueError((p.stderr or p.stdout or 'Provider failed').strip()[-700:])
|
|
return p.stdout.strip()
|
|
|
|
def image_path(value):
|
|
path=Path(value).expanduser().resolve(strict=True)
|
|
if not path.is_file() or path.suffix.lower() not in IMAGES:raise ValueError('Select a supported still image')
|
|
return path
|
|
|
|
def probe_matugen(executable):
|
|
version=run([executable,'--version'])
|
|
if not re.search(r'\b4\.2\.\d+\b',version):raise ValueError('This adapter supports Matugen 4.2.x; found '+version)
|
|
return version
|
|
|
|
def palette(req):
|
|
executable=req.get('executable','matugen');version=probe_matugen(executable)
|
|
path=image_path(req['path']);scheme=req.get('scheme','scheme-tonal-spot');contrast=req.get('contrast',0)
|
|
if scheme not in SCHEMES or not isinstance(contrast,(int,float)) or not -1<=contrast<=1:raise ValueError('Unsupported Matugen options')
|
|
# The dedicated config has no hooks, app templates or wallpaper command.
|
|
with tempfile.TemporaryDirectory(prefix='glassmxrph-matugen-') as tmp:
|
|
base=Path(tmp);template=base/'palette.json';output=base/'generated.json';config=base/'config.toml'
|
|
template.write_text('{"accent":"{{colors.primary.default.hex}}","accentText":"{{colors.on_primary.default.hex}}","accentContainer":"{{colors.primary_container.default.hex}}"}')
|
|
config.write_text('[config]\n\n[templates.glassmxrph]\ninput_path = '+json.dumps(str(template))+'\noutput_path = '+json.dumps(str(output))+'\n')
|
|
run([executable,'--config',str(config),'--mode','dark','--type',scheme,'--contrast='+str(contrast),'--source-color-index','0','image',str(path)],timeout=60)
|
|
result=json.loads(output.read_text())
|
|
if not all(re.fullmatch(r'#[0-9a-fA-F]{6}',result.get(k,'')) for k in ['accent','accentText','accentContainer']):raise ValueError('Matugen generated an invalid palette')
|
|
return {'palette':result,'version':version,'path':str(path)}
|
|
|
|
def current(backend,monitor):
|
|
if backend=='serpantinum':return run(['serpantinum','ipc','call','wallpaper','getWallpaperPath',monitor],5)
|
|
if backend=='awww':
|
|
for line in run(['awww','query'],5).splitlines():
|
|
if line.startswith(monitor+':') and 'image: ' in line:return line.split('image: ',1)[1]
|
|
return ''
|
|
return ''
|
|
|
|
def provider(req):
|
|
backend=req.get('backend','auto');monitor=req.get('monitor','')
|
|
if backend=='auto':
|
|
for candidate in ['serpantinum','awww']:
|
|
if shutil.which(candidate):
|
|
try:return {'backend':candidate,'current':current(candidate,monitor)}
|
|
except (ValueError,subprocess.TimeoutExpired):pass
|
|
# No external provider running: glassMxrph draws the wallpaper itself.
|
|
return {'backend':'native','current':req.get('current','')}
|
|
if backend in ['serpantinum','awww']:return {'backend':backend,'current':current(backend,monitor)}
|
|
if backend=='native':return {'backend':'native','current':req.get('current','')}
|
|
if backend=='custom':return {'backend':'custom','current':req.get('current','')}
|
|
raise ValueError('Unsupported wallpaper backend')
|
|
|
|
def apply(req):
|
|
path=image_path(req['path']);monitor=req['monitor']
|
|
if not re.fullmatch(r'[\w.-]+',monitor):raise ValueError('Invalid output name')
|
|
backend=provider(req)['backend']
|
|
if backend=='native':return {'backend':'native','path':str(path),'url':path.as_uri(),'providerPath':str(path)}
|
|
if backend=='serpantinum':
|
|
# This provider interpolates filenames into shell commands. Pass a safe owned copy.
|
|
base=Path(os.environ.get('XDG_CACHE_HOME',Path.home()/'.cache'))/'glassMxrph/wallpapers'
|
|
base.mkdir(parents=True,exist_ok=True)
|
|
if "'" in str(base) or '\n' in str(base):raise ValueError('Serpantinum cannot safely handle this cache path')
|
|
dest=base/(hashlib.sha256(path.read_bytes()).hexdigest()+path.suffix.lower())
|
|
if not dest.exists():shutil.copyfile(path,dest)
|
|
run(['serpantinum','ipc','call','wallpaper','setWallpaper',monitor,str(dest),'fade'])
|
|
# IPC only acknowledges dispatch: poll read-only state for provider acceptance.
|
|
import time
|
|
for _ in range(20):
|
|
if current(backend,monitor)==str(dest):return {'backend':backend,'path':str(path),'providerPath':str(dest)}
|
|
time.sleep(.1)
|
|
raise ValueError('Wallpaper provider did not acknowledge the selected image')
|
|
if backend=='awww':run(['awww','img','--outputs',monitor,'--transition-type','fade',str(path)])
|
|
elif backend=='custom':
|
|
command=req.get('command',[])
|
|
if not isinstance(command,list) or not command or not all(isinstance(x,str) for x in command):raise ValueError('Custom command must be an argument array')
|
|
if not any('{path}' in x for x in command):raise ValueError('Custom command needs a {path} argument')
|
|
run([x.replace('{path}',str(path)).replace('{monitor}',monitor) for x in command])
|
|
else:raise ValueError('No active wallpaper provider')
|
|
return {'backend':backend,'path':str(path),'providerPath':str(path)}
|
|
|
|
def image_size(path):
|
|
"""(width, height) from the file header, or None. Standard library only:
|
|
the picker lays thumbnails out by aspect ratio before any is decoded."""
|
|
import struct
|
|
try:
|
|
with open(path,'rb') as f:
|
|
head=f.read(32)
|
|
if head[:8]==b'\x89PNG\r\n\x1a\n':
|
|
return struct.unpack('>II',head[16:24])
|
|
if head[:2]==b'BM':
|
|
w,h=struct.unpack('<ii',head[18:26]);return (abs(w),abs(h))
|
|
if head[:4]==b'RIFF' and head[8:12]==b'WEBP':
|
|
kind=head[12:16]
|
|
if kind==b'VP8 ':
|
|
w,h=struct.unpack('<HH',head[26:30]);return (w&0x3fff,h&0x3fff)
|
|
if kind==b'VP8L':
|
|
b=head[21:25];return (1+(((b[1]&0x3f)<<8)|b[0]),1+(((b[3]&0xf)<<10)|(b[2]<<2)|((b[1]&0xc0)>>6)))
|
|
if kind==b'VP8X':
|
|
return (1+int.from_bytes(head[24:27],'little'),1+int.from_bytes(head[27:30],'little'))
|
|
return None
|
|
if head[:2]==b'\xff\xd8':
|
|
f.seek(2)
|
|
while True:
|
|
marker=f.read(2)
|
|
if len(marker)<2 or marker[0]!=0xff:return None
|
|
while marker[1]==0xff:marker=marker[:1]+f.read(1)
|
|
if marker[1] in (0xd8,0x01) or 0xd0<=marker[1]<=0xd7:continue
|
|
length=struct.unpack('>H',f.read(2))[0]
|
|
if marker[1] in (0xc0,0xc1,0xc2,0xc3,0xc5,0xc6,0xc7,0xc9,0xca,0xcb,0xcd,0xce,0xcf):
|
|
h,w=struct.unpack('>xHH',f.read(5));return (w,h)
|
|
f.seek(length-2,1)
|
|
except (OSError,struct.error):
|
|
return None
|
|
return None
|
|
|
|
def scan(req):
|
|
found={};errors=[]
|
|
for directory in (req.get('directories') or [str(Path.home()/'Pictures/Wallpapers')]):
|
|
base=Path(directory).expanduser()
|
|
try:
|
|
for entry in base.iterdir():
|
|
if entry.is_file() and entry.suffix.lower() in IMAGES:
|
|
resolved=entry.resolve();size=image_size(resolved)
|
|
found[str(resolved)]={'path':str(resolved),'url':resolved.as_uri(),'name':entry.name,'width':size[0] if size else 0,'height':size[1] if size else 0}
|
|
if len(found)>=1000:break
|
|
except OSError as error:errors.append(str(error))
|
|
if len(found)>=1000:break
|
|
return {'images':sorted(found.values(),key=lambda x:x['name'].casefold()),'notice':'; '.join(errors),'limited':len(found)>=1000}
|
|
|
|
def dispatch(req):
|
|
action=req['action']
|
|
if action=='palette':return palette(req)
|
|
if action=='matugen-probe':return {'version':probe_matugen(req.get('executable','matugen')),'schemes':SCHEMES}
|
|
if action=='provider':return provider(req)
|
|
if action=='apply':return apply(req)
|
|
if action=='scan':return scan(req)
|
|
raise ValueError('Unknown adapter request')
|
|
|
|
if __name__=='__main__':
|
|
try:print(json.dumps({'ok':True,**dispatch(json.loads(sys.argv[1]))}))
|
|
except (ValueError,OSError,KeyError,subprocess.TimeoutExpired) as error:print(json.dumps({'ok':False,'error':str(error)}))
|