Files
glassMxrph/quickshell/helpers/gamemode.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

96 lines
4.3 KiB
Python

#!/usr/bin/env python3
"""Game Mode system side: turn animations, blur, shadows and HyprGlass off and
switch to the performance power profile, remembering the live values in a
journal so they come back exactly, even after a shell crash. Options Hyprland
does not have (no HyprGlass) and a missing power-profiles-daemon are skipped."""
import json,os,subprocess,sys
from pathlib import Path
KEYS=['animations:enabled','decoration:blur:enabled','decoration:shadow:enabled','plugin:hyprglass:enabled']
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_many(keys):
# Missing options (an unloaded plugin) are left out.
out=run(['-j','--batch',';'.join('getoption '+k for k in keys)])
decoder,pos,found=json.JSONDecoder(),0,{}
while pos<len(out):
while pos<len(out) and out[pos].isspace():pos+=1
if pos>=len(out):break
try:data,pos=decoder.raw_decode(out,pos)
except ValueError:
# Non-JSON error text for a missing option: skip to the next object.
nxt=out.find('{',pos+1)
if nxt<0:break
pos=nxt;continue
if isinstance(data,dict) and ('int' in data or 'bool' in data):found[str(data.get('option',''))]=int(data.get('int',data.get('bool')))
return {k:found[k] for k in keys if k in found}
def lua_set(key,value):
# "decoration:blur:enabled" -> hl.config({ decoration = { blur = { enabled = false } } })
path=key.split(':');text='true' if value else 'false'
target='hl.config('
if path[0]=='plugin':target='hl.plugin.%s.config('%path[1];path=path[2:]
for part in reversed(path):text='{ '+part+' = '+text+' }'
return target+text+')'
def put_many(values):
if not values:return
out=run(['--batch',';'.join('eval '+lua_set(k,v) for k,v in values.items())])
bad=[line for line in out.splitlines() if line.strip() and line.strip()!='ok']
if bad:raise ValueError(bad[0][:350])
PROFILES=('net.hadess.PowerProfiles','/net/hadess/PowerProfiles','net.hadess.PowerProfiles')
def busctl(*args):
p=subprocess.run(['busctl','--system','--auto-start=no','--timeout=3','--json=short',*args],text=True,capture_output=True,timeout=5)
if p.returncode:raise ValueError((p.stderr or p.stdout).strip()[:350])
return json.loads(p.stdout)['data'] if p.stdout.strip() else None
def get_profile():
"""The active profile, or None without power-profiles-daemon or a performance profile."""
try:
names=[p['Profile']['data'] for p in busctl('get-property',*PROFILES,'Profiles')]
return busctl('get-property',*PROFILES,'ActiveProfile') if 'performance' in names else None
except (ValueError,KeyError,TypeError,subprocess.TimeoutExpired):return None
def set_profile(name):
p=subprocess.run(['busctl','--system','--auto-start=no','--timeout=3','set-property',*PROFILES,'ActiveProfile','s',name],text=True,capture_output=True,timeout=5)
if p.returncode:raise ValueError((p.stderr or p.stdout).strip()[:350])
def journal_path():
# Per Hyprland session: a journal from an older session is never applied.
sig=os.environ.get('HYPRLAND_INSTANCE_SIGNATURE','none')
return Path(os.environ.get('XDG_STATE_HOME',Path.home()/'.local/state'))/('glassMxrph/gamemode-%s.json'%sig)
def dispatch(req):
path=journal_path();action=req.get('action')
if action=='on':
if not path.exists():
saved={'keywords':get_many(KEYS) if req.get('effects',True) else {},
'profile':get_profile() if req.get('performance',True) else None}
path.parent.mkdir(parents=True,exist_ok=True)
temp=path.with_suffix('.tmp');temp.write_text(json.dumps(saved));temp.replace(path)
saved=json.loads(path.read_text())
put_many({k:0 for k in saved['keywords']})
if saved['profile'] and saved['profile']!='performance':set_profile('performance')
return dict(active=True)
if action=='off':
if path.exists():
saved=json.loads(path.read_text())
put_many(saved['keywords'])
if saved['profile'] and saved['profile']!='performance':set_profile(saved['profile'])
path.unlink()
return dict(active=False)
if action=='status':
return dict(active=path.exists())
raise ValueError('Unknown Game Mode action')
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))))