Add a manual Game Mode Control Center tile
Turns off animations, blur, shadows and HyprGlass, switches to the performance power profile and turns on Do Not Disturb, each optional in Settings > Power. The helper journals the values it changes per Hyprland session and restores them exactly, also after a shell crash. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9e1ac4efe7
commit
bfbfc8961e
15 files changed
+325
-1
No files matched your search
@@ -0,0 +1,87 @@
|
||||
#!/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:found[str(data.get('option',''))]=data['int']
|
||||
return {k:found[k] for k in keys if k in found}
|
||||
|
||||
def put_many(values):
|
||||
if not values:return
|
||||
out=run(['--batch',';'.join('keyword %s %d'%(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))))
|
||||
Reference in new issue
Block a user