glassMxrph now owns org.freedesktop.Notifications. Banners drop out of the bar like the OSD; Control Center stacks history per app like macOS Notification Center. Do Not Disturb lives in the shell and falls back to SwayNC while another daemon holds the bus name. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
151 lines
9.3 KiB
Python
151 lines
9.3 KiB
Python
#!/usr/bin/env python3
|
|
"""Small system adapters. JSON protocol, argv-only execution, no daemon installation."""
|
|
import concurrent.futures
|
|
import json
|
|
import math
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
|
|
def run(args, timeout=4):
|
|
result = subprocess.run(args, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=timeout, env=dict(os.environ, LC_ALL='C'))
|
|
if result.returncode:
|
|
raise ValueError((result.stderr or result.stdout or 'Command failed').strip()[-500:])
|
|
return result.stdout.strip()
|
|
|
|
def bus(scope, *args):
|
|
return json.loads(run(['busctl', '--'+scope, '--auto-start=no', '--timeout=3', '--json=short', *args]))['data']
|
|
|
|
def command(args, **values):
|
|
if not isinstance(args, list) or not args or any(not isinstance(a, str) or not a for a in args):
|
|
raise ValueError('Configure a nonempty command argument array')
|
|
return [re.sub(r'\{(value|enabled)\}', lambda m: str(values.get(m[1], m[0])).lower(), a) for a in args]
|
|
|
|
def bounded(value, minimum, maximum):
|
|
if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or not minimum <= value <= maximum:
|
|
raise ValueError('Value outside supported range')
|
|
return value
|
|
|
|
def backlights():
|
|
result=[]
|
|
for path in sorted(Path('/sys/class/backlight').glob('*')):
|
|
maximum=int((path/'max_brightness').read_text())
|
|
if maximum > 0:
|
|
result.append({'id':path.name, 'value':100*int((path/'brightness').read_text())/maximum})
|
|
return result
|
|
|
|
def brightness(options):
|
|
if options.get('statusCommand'):
|
|
data=json.loads(run(command(options['statusCommand'])))
|
|
bounded(data['value'], 0, 100)
|
|
if 'available' in data and type(data['available']) is not bool:raise ValueError('Provider availability must be a boolean')
|
|
return dict(data, available=bool(data.get('available', True)), provider='custom', devices=[])
|
|
devices=backlights()
|
|
device=next((d for d in devices if d['id']==options.get('device')), devices[0] if devices and options.get('device','auto')=='auto' else None)
|
|
return {'available':bool(device) and bool(shutil.which('brightnessctl')), 'value':device['value'] if device else 0, 'device':device['id'] if device else '', 'devices':devices, 'provider':'brightnessctl', 'notice':'' if device else 'No selected backlight device. External displays need a configured brightness provider.'}
|
|
|
|
def night(options):
|
|
if options.get('statusCommand'):
|
|
data=json.loads(run(command(options['statusCommand'])))
|
|
if 'available' in data and type(data['available']) is not bool:raise ValueError('Provider availability must be a boolean')
|
|
if type(data.get('enabled')) is not bool:raise ValueError('Night Light status must include enabled: true/false')
|
|
return dict(data, available=bool(data.get('available',True)), provider='custom')
|
|
temp=bus('user','get-property','rs.wl-gammarelay','/','rs.wl.gammarelay','Temperature')
|
|
return {'available':True,'enabled':temp<6500,'temperature':temp,'provider':'wl-gammarelay'}
|
|
|
|
def notifications():
|
|
# The shell keeps its own DND state; only SwayNC is controlled over DBus.
|
|
try:owner=bus('user','call','org.freedesktop.DBus','/org/freedesktop/DBus','org.freedesktop.DBus','GetConnectionUnixProcessID','s','org.freedesktop.Notifications')[0]
|
|
except ValueError:return {'available':False,'provider':'','notice':'No notification server is running'}
|
|
if owner==os.getppid():return {'available':True,'provider':'shell'}
|
|
try:value=bus('user','call','org.erikreider.swaync.cc','/org/erikreider/swaync/cc','org.erikreider.swaync.cc','GetDnd')[0]
|
|
except ValueError:
|
|
try:name=Path(f'/proc/{owner}/comm').read_text().strip().lstrip('.').removesuffix('-wrapped')
|
|
except OSError:name='Another program'
|
|
return {'available':False,'provider':name,'notice':name+' handles notifications'}
|
|
if type(value) is not bool:raise ValueError('SwayNC did not return a DND state')
|
|
return {'available':True,'enabled':value,'provider':'swaync'}
|
|
|
|
def profiles():
|
|
service='net.hadess.PowerProfiles';path='/net/hadess/PowerProfiles'
|
|
values=bus('system','get-property',service,path,service,'Profiles')
|
|
current=bus('system','get-property',service,path,service,'ActiveProfile')
|
|
return {'available':True,'current':current,'profiles':[p['Profile']['data'] for p in values]}
|
|
|
|
def lock_command(options):
|
|
if options.get('lockCommand'):return command(options['lockCommand'])
|
|
if shutil.which('serpantinum'):return ['serpantinum','lock']
|
|
if shutil.which('hyprlock'):return ['hyprlock']
|
|
return []
|
|
|
|
def power(options):
|
|
result={'available':True,'lock':bool(lock_command(options)),'logout':bool(os.environ.get('HYPRLAND_INSTANCE_SIGNATURE')) and bool(shutil.which('hyprctl'))}
|
|
for key,method in [('suspend','CanSuspend'),('reboot','CanReboot'),('shutdown','CanPowerOff')]:
|
|
try:result[key]=bus('system','call','org.freedesktop.login1','/org/freedesktop/login1','org.freedesktop.login1.Manager',method)[0] in ['yes','challenge']
|
|
except (ValueError,OSError,subprocess.TimeoutExpired):result[key]=False
|
|
return result
|
|
|
|
def safely(fn):
|
|
try:return fn()
|
|
except (ValueError,OSError,KeyError,TypeError,subprocess.TimeoutExpired) as error:return {'available':False,'notice':str(error)}
|
|
|
|
def snapshot(options, features=None):
|
|
jobs={'brightness':lambda:brightness(options['brightness']), 'nightLight':lambda:night(options['nightLight']), 'dnd':notifications, 'profiles':profiles, 'power':lambda:power(options['power'])}
|
|
if features is not None:jobs={key:fn for key,fn in jobs.items() if key in features}
|
|
if not jobs:return {}
|
|
with concurrent.futures.ThreadPoolExecutor(max_workers=len(jobs)) as pool:
|
|
return dict(zip(jobs,pool.map(safely,jobs.values())))
|
|
|
|
def action(req):
|
|
options=req['options'];kind=req['action'];value=req.get('value')
|
|
if kind=='brightness':
|
|
value=round(bounded(value,1,100))
|
|
spec=options['brightness']
|
|
if spec.get('setCommand'):run(command(spec['setCommand'],value=value))
|
|
else:
|
|
state=brightness(spec)
|
|
if not state['available'] or state['provider']!='brightnessctl':raise ValueError('No writable brightness provider')
|
|
run(['brightnessctl','--class=backlight','--device='+state['device'],'set',str(value)+'%'])
|
|
elif kind=='nightLight':
|
|
if type(value) is not bool:raise ValueError('Night Light expects a boolean')
|
|
spec=options['nightLight']
|
|
if spec.get('setCommand'):run(command(spec['setCommand'],enabled=value,value=spec['temperature'] if value else 6500))
|
|
else:
|
|
night(spec) # Require a running provider; never auto-start a second gamma daemon.
|
|
temperature=round(bounded(spec['temperature'],1000,6500)) if value else 6500
|
|
run(['busctl','--user','--auto-start=no','--timeout=3','set-property','rs.wl-gammarelay','/','rs.wl.gammarelay','Temperature','q',str(temperature)])
|
|
elif kind=='dnd':
|
|
if type(value) is not bool:raise ValueError('DND expects a boolean')
|
|
if notifications().get('provider')!='swaync':raise ValueError('No external Do Not Disturb provider')
|
|
run(['busctl','--user','--auto-start=no','--timeout=3','call','org.erikreider.swaync.cc','/org/erikreider/swaync/cc','org.erikreider.swaync.cc','SetDnd','b',str(value).lower()])
|
|
elif kind=='profile':
|
|
if value not in profiles()['profiles']:raise ValueError('Unsupported power profile')
|
|
run(['busctl','--system','--auto-start=no','--timeout=3','set-property','net.hadess.PowerProfiles','/net/hadess/PowerProfiles','net.hadess.PowerProfiles','ActiveProfile','s',value])
|
|
elif kind=='power':
|
|
if value not in ['lock','logout','suspend','reboot','shutdown']:raise ValueError('Unsupported power action')
|
|
if value in ['logout','reboot','shutdown'] and req.get('confirmed') is not True:raise ValueError('Explicit confirmation required')
|
|
if not power(options['power']).get(value):raise ValueError('Power action unavailable')
|
|
if value=='lock':subprocess.Popen(lock_command(options['power']),stdin=subprocess.DEVNULL,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,start_new_session=True)
|
|
elif value=='logout':run(['hyprctl','dispatch','exit'])
|
|
else:run(['busctl','--system','--auto-start=no','--timeout=10','call','org.freedesktop.login1','/org/freedesktop/login1','org.freedesktop.login1.Manager',{'suspend':'Suspend','reboot':'Reboot','shutdown':'PowerOff'}[value],'b','true'],15)
|
|
elif kind=='manager':
|
|
executable={'network':'nm-connection-editor','bluetooth':'blueman-manager'}.get(value)
|
|
if not executable or not shutil.which(executable):raise ValueError('The existing connection manager is not installed')
|
|
subprocess.Popen([executable],stdin=subprocess.DEVNULL,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,start_new_session=True)
|
|
else:raise ValueError('Unsupported action')
|
|
return {'state':snapshot(options)}
|
|
|
|
def main(req):
|
|
if req.get('op')=='status':return {'state':snapshot(req['options'],req.get('features'))}
|
|
if req.get('op')=='action':return action(req)
|
|
raise ValueError('Unsupported operation')
|
|
|
|
if __name__=='__main__':
|
|
try:print(json.dumps(dict(ok=True,**main(json.loads(sys.argv[1])))))
|
|
except (ValueError,OSError,KeyError,TypeError,subprocess.TimeoutExpired) as error:
|
|
print(json.dumps({'ok':False,'error':str(error)}))
|
|
sys.exit(1)
|