Files
glassMxrph/quickshell/helpers/glass.py
T
mxandClaude Opus 5.5 c716a20e04 Use Lua dispatches and options for Hyprland 0.57
Hyprland 0.57 removed hyprctl keyword and name-style dispatches, and
hyprglass 1.1 dropped its layer namespace options. Move workspace, window,
logout, glass and Game Mode calls to hl.dsp and hyprctl eval.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 20:39:45 +01:00

130 lines
5.8 KiB
Python

#!/usr/bin/env python3
"""Global HyprGlass controls using verified live scalar options, with a restore journal."""
import json,math,os,subprocess,sys
from pathlib import Path
PREFIX='plugin:hyprglass:'
RANGES={'blur_strength':(0,5),'blur_iterations':(1,5),'refraction_strength':(0,8),
'chromatic_aberration':(0,1),'fresnel_strength':(0,1),'specular_strength':(0,1),
'edge_thickness':(0,.15),'lens_distortion':(0,1),'brightness':(.2,2),
'contrast':(.2,2),'saturation':(0,2),'vibrancy':(0,1),'adaptive_dim':(0,1)}
BOOLS={'enabled','layers:enabled'}
GHOSTTY={'blur_strength':.45,'blur_iterations':2,'refraction_strength':3,
'chromatic_aberration':.45,'fresnel_strength':.5,'specular_strength':.8,
'edge_thickness':.065,'lens_distortion':.25,'brightness':.95,
'contrast':1,'saturation':1,'vibrancy':.15,'adaptive_dim':.2}
def run(args):
p=subprocess.run(['hyprctl',*args],text=True,capture_output=True,timeout=4)
if p.returncode:raise ValueError((p.stderr or p.stdout).strip()[:350])
return p.stdout.strip()
def get(key):
data=json.loads(run(['-j','getoption',PREFIX+key]))
for field in ['str','int','float','bool']:
if field in data:return int(data[field]) if field=='bool' else data[field]
raise ValueError('HyprGlass option unavailable: '+key)
def get_many(keys):
# One hyprctl call instead of one per option (apply reads about 40).
out=run(['-j','--batch',';'.join('getoption '+PREFIX+k for k in keys)])
decoder,pos,found=json.JSONDecoder(),0,{}
while True:
while pos<len(out) and out[pos].isspace():pos+=1
if pos>=len(out):break
data,pos=decoder.raw_decode(out,pos)
value=next((data[f] for f in ['str','int','float','bool'] if f in data),None)
if isinstance(value,bool):value=int(value)
if value is not None:found[str(data.get('option','')).removeprefix(PREFIX)]=value
missing=[k for k in keys if k not in found]
if missing:raise ValueError('HyprGlass option unavailable: '+missing[0])
return found
def lua_table(key,value):
# "dark:brightness" -> { dark = { brightness = 0.9 } }
if key in BOOLS:text='true' if value else 'false'
elif isinstance(value,str):text="'"+value+"'"
else:text=repr(value)
for part in reversed(key.split(':')):text='{ '+part+' = '+text+' }'
return text
def put(key,value):
result=run(['eval','hl.plugin.hyprglass.config('+lua_table(key,value)+')'])
if result!='ok':raise ValueError(result[:350])
if get(key)!=value:raise ValueError('HyprGlass did not accept '+key)
def values(options):
controls=options.get('values',{})
if set(controls)!=set(RANGES):raise ValueError('Incomplete glass settings')
for key,(low,high) in RANGES.items():
v=controls[key]
if type(v) not in (int,float) or not math.isfinite(v) or not low<=v<=high:raise ValueError('Invalid '+key)
if not float(controls['blur_iterations']).is_integer():raise ValueError('Blur passes must be an integer')
if type(options.get('layers')) is not bool or type(options.get('effectEnabled',True)) is not bool:raise ValueError('Invalid glass toggle')
# "default" is the plugin's documented fallback: custom presets otherwise
# override scalar sliders, and live preset definitions are only committed at reload.
result={}
for key,v in controls.items():
result['dark:'+key]=v
result['light:'+key]=v
result.update({'dark:tint_color':0xffffff08,'light:tint_color':0xffffff08,
'dark:glass_opacity':1,'light:glass_opacity':1,
'default_preset':'default','default_theme':'dark','layers:preset':'default','layers:mask_mode':'alpha',
'layers:enabled':int(options['layers'] and options.get('effectEnabled',True)),'enabled':int(options.get('effectEnabled',True))})
return result
def journal_path():
return Path(os.environ.get('XDG_STATE_HOME',Path.home()/'.local/state'))/'glassMxrph/glass-restore.json'
def save(path,data):
path.parent.mkdir(parents=True,exist_ok=True)
temp=path.with_suffix('.tmp');temp.write_text(json.dumps(data));temp.replace(path)
def probe():
try:
o=get_many(['default_preset','enabled','layers:enabled'])
return dict(available=True,preset=o['default_preset'],enabled=bool(o['enabled']),layers=bool(o['layers:enabled']),
namespaces='',exclusions='',overrides='')
except (OSError,ValueError,subprocess.TimeoutExpired) as error:return dict(available=False,reason=str(error)[:200])
def dispatch(req):
action=req.get('action')
if action=='probe':return probe()
path=journal_path();session=os.environ.get('HYPRLAND_INSTANCE_SIGNATURE','')
journal=json.loads(path.read_text()) if path.exists() else {}
if journal.get('session')!=session or req.get('reloaded'):journal={}
if action=='restore':
skipped=[]
for key,old in reversed(list(journal.get('before',{}).items())):
if get(key)==journal['after'].get(key):put(key,old)
else:skipped.append(key)
path.unlink(missing_ok=True)
return dict(**probe(),notice='Restored previous glass settings.' if not skipped else 'Preserved externally changed options: '+', '.join(skipped))
if action!='apply':raise ValueError('Unknown glass request')
target=values(req['options'])
current=get_many(list(target))
before=journal.get('before',current)
# Persist before writing so a partial operation can be restored after a crash.
record=dict(session=session,before=before,after=target)
save(path,record)
changed=[]
try:
for key,value in target.items():
if current[key]!=value:
changed.append(key);put(key,value)
except Exception:
rollback_failed=False
for key in reversed(changed):
try:put(key,current[key])
except Exception:rollback_failed=True
if not rollback_failed:
if journal:save(path,journal)
else:path.unlink(missing_ok=True)
raise
return dict(**probe(),notice='Global glass applied. Explicit per-application and per-layer preset rules still take priority.')
if __name__=='__main__':
try:print(json.dumps(dict(ok=True,**dispatch(json.loads(sys.argv[1])))))
except (OSError,ValueError,KeyError,subprocess.TimeoutExpired) as e:print(json.dumps(dict(ok=False,error=str(e))))