61 lines
2.0 KiB
Python
61 lines
2.0 KiB
Python
#!/usr/bin/env python3
|
|
"""Unprivileged brightnessctl adapter; never invokes a shell or sudo."""
|
|
import json
|
|
import re
|
|
import subprocess
|
|
import sys
|
|
|
|
DEVICE = re.compile(r'^[A-Za-z0-9_.:-]{1,128}$')
|
|
|
|
|
|
def run(args):
|
|
return subprocess.run(['brightnessctl', '--machine-readable', *args], capture_output=True, text=True, timeout=8, check=True).stdout
|
|
|
|
|
|
def parse_devices(output):
|
|
devices = []
|
|
for line in output.splitlines():
|
|
fields = line.split(',')
|
|
if len(fields) < 5:
|
|
continue
|
|
name, kind, current, maximum, percent = (x.strip() for x in fields[:5])
|
|
if kind != 'backlight' or not DEVICE.fullmatch(name):
|
|
continue
|
|
try:
|
|
current, maximum = int(current), int(maximum)
|
|
except ValueError:
|
|
continue
|
|
if maximum <= 0:
|
|
continue
|
|
devices.append({'name': name, 'current': current, 'maximum': maximum,
|
|
'percent': round(100 * current / maximum)})
|
|
return devices
|
|
|
|
|
|
def main(argv):
|
|
if len(argv) < 2 or argv[1] not in ('list', 'set'):
|
|
raise ValueError('Expected list or set')
|
|
if argv[1] == 'list':
|
|
return {'ok': True, 'devices': parse_devices(run(['--list']))}
|
|
if len(argv) != 4 or not DEVICE.fullmatch(argv[2]):
|
|
raise ValueError('Invalid device')
|
|
try:
|
|
value = int(argv[3])
|
|
except ValueError:
|
|
raise ValueError('Invalid percentage') from None
|
|
if not 1 <= value <= 100:
|
|
raise ValueError('Percentage must be 1..100')
|
|
known = {item['name'] for item in parse_devices(run(['--list']))}
|
|
if argv[2] not in known:
|
|
raise ValueError('Unknown backlight device')
|
|
run(['--device', argv[2], 'set', f'{value}%'])
|
|
return {'ok': True, 'devices': parse_devices(run(['--list']))}
|
|
|
|
|
|
if __name__ == '__main__':
|
|
try:
|
|
print(json.dumps(main(sys.argv), ensure_ascii=False))
|
|
except (ValueError, subprocess.SubprocessError, OSError) as exc:
|
|
print(json.dumps({'ok': False, 'error': str(exc)}, ensure_ascii=False))
|
|
sys.exit(1)
|