- The bar now reserves its margin and height as an exclusive zone, so windows tile below it instead of underneath. The overhang below the bar, where drawers attach, stays unreserved. - The "auto" wallpaper backend falls back to glassMxrph's native background when no external provider (serpantinum, awww) is running, instead of reporting none. The background surface follows the resolved backend. - The package adds Qt's extra image-format plugins (qtimageformats) to QT_PLUGIN_PATH, so WebP wallpapers (including WebP files with a .jpg name) decode. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
120 lines
6.8 KiB
Python
120 lines
6.8 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 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();found[str(resolved)]={'path':str(resolved),'url':resolved.as_uri(),'name':entry.name}
|
|
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)}))
|