added adaptive quickshell

This commit is contained in:
wt committed 2026-11-17 18:15:16 +07:00
1 parent 6eb56d2065
commit 5b33a73fd8
189 files changed
+8678 -15

No files matched your search

+81
View File
@@ -0,0 +1,81 @@
#!/usr/bin/env python3
"""One-shot BlueZ calls with structured errors; no pairing agent or discovery lease."""
import json
import re
import sys
ADAPTER = re.compile(r'/org/bluez/hci[0-9]+')
DEVICE = re.compile(r'/org/bluez/hci[0-9]+/dev_(?:[0-9A-Fa-f]{2}_){5}[0-9A-Fa-f]{2}')
class Bluez:
def __init__(self):
from gi.repository import Gio, GLib
self.Gio, self.GLib = Gio, GLib
self.bus = Gio.bus_get_sync(Gio.BusType.SYSTEM, None)
def call(self, path, interface, method, signature=None, args=(), timeout=45000):
params = self.GLib.Variant(signature, args) if signature else None
return self.bus.call_sync('org.bluez', path, interface, method, params, None,
self.Gio.DBusCallFlags.NO_AUTO_START, timeout, None).unpack()
def status(self):
objects = self.call('/', 'org.freedesktop.DBus.ObjectManager', 'GetManagedObjects', timeout=5000)[0]
return {'adapterCount': sum('org.bluez.Adapter1' in interfaces for interfaces in objects.values())}
def power(self, path, enabled):
self.call(path, 'org.freedesktop.DBus.Properties', 'Set', '(ssv)',
('org.bluez.Adapter1', 'Powered', self.GLib.Variant('b', enabled)))
def discover(self, path):
import signal
loop = self.GLib.MainLoop()
# GLib delivers these signals without polling while the lease is held.
self.GLib.unix_signal_add(self.GLib.PRIORITY_DEFAULT, signal.SIGTERM, lambda: (loop.quit(), False)[1])
self.GLib.timeout_add_seconds(60, lambda: (loop.quit(), False)[1])
started = False
try:
self.call(path, 'org.bluez.Adapter1', 'StartDiscovery', timeout=5000)
started = True
print(json.dumps({'ok': True, 'event': 'started'}), flush=True)
loop.run()
finally:
if started:
self.call(path, 'org.bluez.Adapter1', 'StopDiscovery', timeout=5000)
def connect(self, path): self.call(path, 'org.bluez.Device1', 'Connect')
def disconnect(self, path): self.call(path, 'org.bluez.Device1', 'Disconnect')
def forget(self, path): self.call(path.rsplit('/', 1)[0], 'org.bluez.Adapter1', 'RemoveDevice', '(o)', (path,))
def execute(action, path='', factory=Bluez):
if action == 'status':
if path: raise ValueError('status does not accept a device path')
return factory().status()
if action == 'discover':
if not ADAPTER.fullmatch(path): raise ValueError('Invalid BlueZ adapter path')
factory().discover(path)
elif action in {'power-on', 'power-off'}:
if not ADAPTER.fullmatch(path): raise ValueError('Invalid BlueZ adapter path')
factory().power(path, action == 'power-on')
elif action in {'connect', 'disconnect', 'forget'}:
if not DEVICE.fullmatch(path): raise ValueError('Invalid BlueZ device path')
getattr(factory(), action)(path)
else:
raise ValueError('Unsupported Bluetooth action')
return {}
def main():
try:
if len(sys.argv) not in {2, 3}: raise ValueError('Expected action and optional BlueZ path')
result = execute(sys.argv[1], sys.argv[2] if len(sys.argv) == 3 else '')
print(json.dumps({'ok': True, **result}))
return 0
except Exception as error:
print(json.dumps({'ok': False, 'error': str(error)}))
return 1
if __name__ == '__main__': sys.exit(main())
+60
View File
@@ -0,0 +1,60 @@
#!/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)
+142
View File
@@ -0,0 +1,142 @@
#!/usr/bin/env python3
"""Temporary Hyprland monitor changes with fail-safe rollback.
A detached watcher restores the original monitor rule unless confirmed within 20s.
The preview never modifies the user's persistent Hyprland configuration.
"""
import json
import os
from pathlib import Path
import re
import subprocess
import sys
import time
import uuid
DURATION = 20
NAME = re.compile(r'^[A-Za-z0-9_.:-]{1,128}$')
MODE = re.compile(r'^(?:preferred|[1-9][0-9]{2,4}x[1-9][0-9]{2,4}@[0-9]{1,3}(?:\.[0-9]{1,3})?)$')
SCALE = re.compile(r'^(?:0\.[5-9][0-9]?|[1-3](?:\.[0-9]{1,2})?)$')
TOKEN = re.compile(r'^[a-f0-9]{32}$')
TRANSFORMS = frozenset(range(8))
def state_dir():
base = Path(os.environ.get('XDG_RUNTIME_DIR', '/tmp'))
directory = base / f'adaptive-display-{os.getuid()}'
directory.mkdir(mode=0o700, exist_ok=True)
return directory
def monitor_rule(name, mode, position, scale, transform=None):
if not NAME.fullmatch(name) or not MODE.fullmatch(mode) or not SCALE.fullmatch(str(scale)):
raise ValueError('Недопустимые параметры монитора')
if position != 'auto' and not re.fullmatch(r'-?[0-9]{1,6}x-?[0-9]{1,6}', position):
raise ValueError('Недопустимая позиция монитора')
if transform is not None:
if isinstance(transform, bool) or not isinstance(transform, int) or transform not in TRANSFORMS:
raise ValueError('Недопустимая ориентация монитора')
return f'{name},{mode},{position},{scale},transform,{transform}'
return f'{name},{mode},{position},{scale}'
def run_hypr(rule):
subprocess.run(['hyprctl', 'keyword', 'monitor', rule], check=True, capture_output=True, text=True, timeout=8)
def current(name):
output = subprocess.run(['hyprctl', '-j', 'monitors', 'all'], check=True, capture_output=True, text=True, timeout=8)
for item in json.loads(output.stdout):
if item.get('name') == name:
return item
raise ValueError('Монитор не найден')
def original_rule(item):
rate = float(item.get('refreshRate') or 60)
mode = f"{int(item['width'])}x{int(item['height'])}@{rate:.2f}"
position = f"{int(item.get('x', 0))}x{int(item.get('y', 0))}"
return monitor_rule(item['name'], mode, position, str(float(item.get('scale') or 1)), int(item.get('transform') or 0))
def preview(name, mode, scale, transform=None, x=None, y=None):
item = current(name)
# Preserve physical layout: using "auto" here can unexpectedly move other screens.
if (x is None) != (y is None):
raise ValueError('Координаты необходимо задавать вместе')
if x is None:
x, y = int(item.get('x', 0)), int(item.get('y', 0))
else:
for value in (x, y):
if not re.fullmatch(r'-?[0-9]{1,6}', str(value)) or abs(int(value)) > 100000:
raise ValueError('Недопустимые координаты монитора')
x, y = int(x), int(y)
position = f"{x}x{y}"
if transform is None:
transform = int(item.get('transform') or 0)
else:
if not re.fullmatch(r'[0-7]', str(transform)):
raise ValueError('Недопустимая ориентация монитора')
transform = int(transform)
rule = monitor_rule(name, mode, position, scale, transform)
directory = state_dir()
lock = directory / 'active.json'
if lock.exists():
raise ValueError('Сначала подтвердите или дождитесь отката предыдущего изменения')
before = original_rule(item)
token = uuid.uuid4().hex
# Exclusive create ensures two concurrent previews cannot overwrite the same state.
with lock.open('x', encoding='utf-8') as handle:
json.dump({'token': token, 'before': before, 'name': name}, handle)
try:
watcher = subprocess.Popen([sys.executable, str(Path(__file__).resolve()), 'watch', token],
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, start_new_session=True)
run_hypr(rule)
except Exception:
lock.unlink(missing_ok=True)
raise
return {'ok': True, 'token': token, 'seconds': DURATION, 'watcherPid': watcher.pid}
def confirm(token):
if not TOKEN.fullmatch(token):
raise ValueError('Недопустимый токен')
lock = state_dir() / 'active.json'
state = json.loads(lock.read_text(encoding='utf-8'))
if state['token'] != token:
raise ValueError('Неверный токен подтверждения')
lock.unlink()
return {'ok': True}
def watch(token):
lock = state_dir() / 'active.json'
time.sleep(DURATION)
try:
state = json.loads(lock.read_text(encoding='utf-8'))
if state['token'] != token:
return {'ok': True}
run_hypr(state['before'])
lock.unlink(missing_ok=True)
except FileNotFoundError:
pass # Confirmed before timeout.
return {'ok': True}
def main(args):
if len(args) in (4, 5, 7) and args[0] == 'preview':
return preview(*args[1:])
if len(args) == 2 and args[0] == 'confirm':
return confirm(args[1])
if len(args) == 2 and args[0] == 'watch':
return watch(args[1])
raise ValueError('Неизвестная операция')
if __name__ == '__main__':
try:
print(json.dumps(main(sys.argv[1:]), ensure_ascii=False))
except (ValueError, OSError, KeyError, subprocess.SubprocessError, json.JSONDecodeError) as error:
print(json.dumps({'ok': False, 'error': str(error)}, ensure_ascii=False))
sys.exit(1)
+46
View File
@@ -0,0 +1,46 @@
#!/usr/bin/env python3
"""Read-only Hyprland display inventory. No shell, privilege escalation or writes."""
import json
import subprocess
import sys
def normalize(monitors):
if not isinstance(monitors, list):
raise ValueError('Expected monitor array')
result = []
for monitor in monitors:
if not isinstance(monitor, dict) or not isinstance(monitor.get('name'), str):
continue
name = monitor['name']
if not name or len(name) > 128:
continue
result.append({
'name': name,
'description': str(monitor.get('description') or name)[:256],
'width': int(monitor.get('width') or 0),
'height': int(monitor.get('height') or 0),
'refreshRate': round(float(monitor.get('refreshRate') or 0), 2),
'scale': float(monitor.get('scale') or 1),
'transform': int(monitor.get('transform') or 0),
'focused': bool(monitor.get('focused', False)),
'x': int(monitor.get('x') or 0),
'y': int(monitor.get('y') or 0),
'availableModes': [str(mode)[:80] for mode in monitor.get('availableModes', []) if isinstance(mode, str)][:128],
})
return result
def main(args):
if args != ['list']:
raise ValueError('Only list is supported')
output = subprocess.run(['hyprctl', '-j', 'monitors', 'all'], capture_output=True, text=True, timeout=8, check=True)
return {'ok': True, 'monitors': normalize(json.loads(output.stdout))}
if __name__ == '__main__':
try:
print(json.dumps(main(sys.argv[1:]), ensure_ascii=False))
except (ValueError, OSError, subprocess.SubprocessError, json.JSONDecodeError) as error:
print(json.dumps({'ok': False, 'error': str(error)}, ensure_ascii=False))
sys.exit(1)
+70
View File
@@ -0,0 +1,70 @@
"""Observe compositor-confirmed locks; never acquire or release a session lock itself."""
import select
import shutil
import subprocess
import time
class LockObserver:
def __init__(self):
from pywayland.client import Display
from protocols.hyprland_lock_notify_v1 import HyprlandLockNotifierV1
self.display = Display()
self.manager = None
self.notification = None
self.locked = False
try:
self.display.connect()
self.registry = self.display.get_registry()
def global_found(registry, name, interface, version):
if interface == HyprlandLockNotifierV1.name:
self.manager = registry.bind(name, HyprlandLockNotifierV1, 1)
self.registry.dispatcher['global'] = global_found
self.display.roundtrip()
if self.manager is None:
raise RuntimeError('Hyprland lock-notify is unavailable')
self.notification = self.manager.get_lock_notification()
self.notification.dispatcher['locked'] = lambda _: self._set_locked(True)
self.notification.dispatcher['unlocked'] = lambda _: self._set_locked(False)
self.display.roundtrip()
except BaseException:
self.display.disconnect()
raise
def _set_locked(self, value):
self.locked = value
def ensure_locked(self, timeout=12):
if self.locked:
self.display.roundtrip()
if self.locked:
return
locker = shutil.which('hyprlock')
if not locker:
raise RuntimeError('Hyprlock is not installed')
# Closing this helper never terminates the independent lock client.
child = subprocess.Popen([locker, '--grace', '0'], stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
start_new_session=True)
deadline = time.monotonic() + timeout
while not self.locked:
self.display.dispatch(block=False)
if self.locked:
break
if child.poll() is not None:
raise RuntimeError('Hyprlock exited before the compositor confirmed a lock')
remaining = deadline - time.monotonic()
if remaining <= 0:
raise RuntimeError('Timed out waiting for a compositor-confirmed lock')
if select.select([self.display.get_fd()], [], [], min(remaining, .25))[0]:
self.display.dispatch(block=True)
self.display.roundtrip()
if not self.locked:
raise RuntimeError('Session unlocked before the power request')
def close(self):
if self.notification:
self.notification.destroy()
if self.manager:
self.manager.destroy()
self.display.disconnect()
+78
View File
@@ -0,0 +1,78 @@
#!/usr/bin/env python3
"""Constrained NetworkManager GSM profile management; no shell or SIM secrets."""
import json
import re
import shutil
import subprocess
import sys
UUID = re.compile(r'^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$')
APN = re.compile(r'^[a-zA-Z0-9][a-zA-Z0-9.-]{0,99}$')
NAME = re.compile(r'^[^\x00-\x1f\x7f]{1,64}$')
def execute(args, runner=subprocess.run):
try:
proc = runner(['nmcli', '--wait', '15', *args], capture_output=True, text=True, timeout=22, check=False)
return {'ok': proc.returncode == 0, 'error': '' if proc.returncode == 0 else (proc.stderr.strip() or 'NetworkManager rejected request')[:300], 'output': proc.stdout}
except (OSError, subprocess.TimeoutExpired) as exc:
return {'ok': False, 'error': str(exc)[:300], 'output': ''}
def list_profiles(runner=subprocess.run):
if not shutil.which('nmcli'):
return {'ok': False, 'profiles': [], 'error': 'nmcli not installed'}
result = execute(['-g', 'UUID,TYPE,NAME', 'connection', 'show'], runner)
if not result['ok']:
return {'ok': False, 'profiles': [], 'error': result['error']}
profiles = []
# UUID and type are ASCII and fixed width; name may contain colons.
for line in result['output'].splitlines():
parts = line.split(':', 2)
if len(parts) != 3 or not UUID.fullmatch(parts[0]) or parts[1] not in ('gsm', 'cdma'):
continue
profiles.append({'uuid': parts[0], 'name': parts[2], 'type': parts[1]})
return {'ok': True, 'profiles': profiles, 'error': ''}
def manage(action, value='', apn='', runner=subprocess.run):
if action not in ('create', 'activate', 'deactivate', 'delete'):
return {'ok': False, 'error': 'Unsupported action'}
if not shutil.which('nmcli'):
return {'ok': False, 'error': 'nmcli not installed'}
if action == 'create':
if not NAME.fullmatch(value) or not APN.fullmatch(apn):
return {'ok': False, 'error': 'Invalid profile name or APN'}
args = ['connection', 'add', 'type', 'gsm', 'con-name', value, 'apn', apn, 'connection.autoconnect', 'no']
else:
if not UUID.fullmatch(value):
return {'ok': False, 'error': 'Invalid connection UUID'}
# Restrict operations to mobile profiles, not arbitrary network connections.
profiles = list_profiles(runner)
if not profiles['ok']:
return {'ok': False, 'error': profiles['error']}
if value.lower() not in {p['uuid'].lower() for p in profiles['profiles']}:
return {'ok': False, 'error': 'Not a mobile connection'}
if action == 'activate':
args = ['connection', 'up', 'uuid', value]
elif action == 'deactivate':
args = ['connection', 'down', 'uuid', value]
else:
args = ['connection', 'delete', 'uuid', value]
result = execute(args, runner)
return {'ok': result['ok'], 'error': result['error']}
if __name__ == '__main__':
if len(sys.argv) < 2:
response = {'ok': False, 'error': 'Missing action'}
elif sys.argv[1] == 'list' and len(sys.argv) == 2:
response = list_profiles()
elif len(sys.argv) == 4 and sys.argv[1] == 'create':
response = manage('create', sys.argv[2], sys.argv[3])
elif len(sys.argv) == 3:
response = manage(sys.argv[1], sys.argv[2])
else:
response = {'ok': False, 'error': 'Invalid arguments'}
print(json.dumps(response, ensure_ascii=False))
sys.exit(0 if response['ok'] else 1)
+38
View File
@@ -0,0 +1,38 @@
#!/usr/bin/env python3
"""Narrow, non-shell ModemManager control surface.
Only enable/disable is supported. Never accepts PIN/PUK or arbitrary mmcli flags.
Authorization is delegated to ModemManager/polkit.
"""
import json
import re
import shutil
import subprocess
import sys
ID = re.compile(r'^(?:[0-9]{1,5}|/org/freedesktop/ModemManager1/Modem/[0-9]{1,5})$')
def control(modem_id, action, runner=subprocess.run):
if not ID.fullmatch(modem_id):
return {'ok': False, 'error': 'Invalid modem identifier'}
if action not in ('enable', 'disable'):
return {'ok': False, 'error': 'Unsupported modem action'}
if not shutil.which('mmcli'):
return {'ok': False, 'error': 'mmcli not installed'}
try:
result = runner(['mmcli', '-m', modem_id, '--' + action], capture_output=True,
text=True, timeout=25, check=False)
return {'ok': result.returncode == 0,
'error': '' if result.returncode == 0 else (result.stderr.strip() or 'ModemManager rejected request')[:300]}
except (OSError, subprocess.TimeoutExpired) as exc:
return {'ok': False, 'error': str(exc)[:300]}
if __name__ == '__main__':
if len(sys.argv) != 3:
result = {'ok': False, 'error': 'Usage: modem_control.py MODEM_ID enable|disable'}
else:
result = control(sys.argv[1], sys.argv[2])
print(json.dumps(result, ensure_ascii=False))
sys.exit(0 if result['ok'] else 1)
+64
View File
@@ -0,0 +1,64 @@
#!/usr/bin/env python3
"""Read-only ModemManager inventory for the adaptive shell.
No SIM secrets are read, no privileged actions are attempted. JSON is stable
across a missing mmcli, an empty device list, and transient modem removal.
"""
import json
import re
import shutil
import subprocess
def run(*args):
proc = subprocess.run(['mmcli', *args, '--output-json'], capture_output=True,
text=True, timeout=8, check=False)
if proc.returncode:
raise RuntimeError(proc.stderr.strip()[:240] or 'ModemManager unavailable')
return json.loads(proc.stdout)
def modem_paths(payload):
value = payload.get('modem-list', [])
if isinstance(value, dict):
value = value.get('modems', [])
return [p for p in value if isinstance(p, str) and re.fullmatch(r'/org/freedesktop/ModemManager1/Modem/\d+', p)]
def describe(payload, path):
modem = payload.get('modem', {})
generic = modem.get('generic', {})
threegpp = modem.get('3gpp', {})
signal = generic.get('signal-quality', {})
if isinstance(signal, dict):
signal = signal.get('value', 0)
sim = generic.get('sim', '')
return {
'id': path.rsplit('/', 1)[-1],
'manufacturer': str(generic.get('manufacturer', '')),
'model': str(generic.get('model', '')),
'state': str(generic.get('state', 'unknown')),
'signal': signal if isinstance(signal, (int, float)) else 0,
'simPresent': isinstance(sim, str) and bool(sim) and sim != '--',
'operator': str(threegpp.get('operator-name', '')),
}
def snapshot():
if not shutil.which('mmcli'):
return {'backend': 'unavailable', 'modems': [], 'error': 'mmcli not installed'}
try:
paths = modem_paths(run('-L'))
devices = []
for path in paths:
try:
devices.append(describe(run('-m', path), path))
except (RuntimeError, ValueError, subprocess.TimeoutExpired) as exc:
devices.append({'id': path.rsplit('/', 1)[-1], 'state': 'error', 'error': str(exc)})
return {'backend': 'available', 'modems': devices, 'error': ''}
except (RuntimeError, ValueError, subprocess.TimeoutExpired, OSError) as exc:
return {'backend': 'error', 'modems': [], 'error': str(exc)}
if __name__ == '__main__':
print(json.dumps(snapshot(), ensure_ascii=False))
+134
View File
@@ -0,0 +1,134 @@
#!/usr/bin/env python3
"""One-shot desktop power backend. Only `capabilities` is read-only."""
import json
import os
import shutil
import signal
import subprocess
import sys
METHODS = {'suspend': 'Suspend', 'reboot': 'Reboot', 'poweroff': 'PowerOff'}
class Logind:
def __init__(self):
from gi.repository import Gio, GLib
self.Gio, self.GLib = Gio, GLib
self.bus = Gio.bus_get_sync(Gio.BusType.SYSTEM, None)
def call(self, method, interactive=None):
args = None if interactive is None else self.GLib.Variant('(b)', (interactive,))
result = self.bus.call_sync('org.freedesktop.login1', '/org/freedesktop/login1',
'org.freedesktop.login1.Manager', method, args, None,
self.Gio.DBusCallFlags.NONE, 5000 if interactive is None else 60000, None)
return result.unpack()
def can(self, action):
return self.call('Can' + METHODS[action])[0]
def perform(self, action):
self.call(METHODS[action], action != "suspend")
def compositor():
if not shutil.which('hyprctl') or not os.environ.get('HYPRLAND_INSTANCE_SIGNATURE'):
raise RuntimeError('Hyprland session is unavailable')
result = subprocess.run(['hyprctl', '-j', 'status'], capture_output=True, text=True, timeout=5, check=True)
return json.loads(result.stdout)
def lock_observer():
from lock_observer import LockObserver
return LockObserver()
def capabilities(logind_factory=Logind, observer_factory=lock_observer, compositor_query=compositor):
result = {'lock': {'state': 'unavailable'}, 'logout': {'state': 'unavailable'}}
try:
compositor_query()
result['logout'] = {'state': 'yes'}
except Exception as error:
result['logout']['reason'] = str(error)
try:
observer = observer_factory()
try:
if shutil.which('hyprlock'):
result['lock'] = {'state': 'yes'}
else:
result['lock']['reason'] = 'Hyprlock is not installed'
finally:
observer.close()
except Exception as error:
result['lock']['reason'] = str(error)
try:
logind = logind_factory()
for action in METHODS:
try:
state = logind.can(action)
if state not in {'yes', 'no', 'na', 'challenge'}:
raise RuntimeError('Unknown logind capability: ' + str(state))
result[action] = {'state': state}
if action == 'suspend' and (state == 'challenge' or result['lock']['state'] != 'yes'):
result[action]['state'] = 'unavailable'
result[action]['reason'] = 'Lock confirmation or pre-lock authorization is unavailable'
except Exception as error:
result[action] = {'state': 'error', 'reason': str(error)}
except Exception as error:
for action in METHODS:
result[action] = {'state': 'error', 'reason': str(error)}
return result
def execute(action, logind_factory=Logind, observer_factory=lock_observer, compositor_query=compositor, run=subprocess.run):
if action == 'logout':
info = compositor_query()
command = ['hyprctl', 'eval', 'hl.dispatch(hl.dsp.exit())'] if info.get('configProvider') == 'lua' else ['hyprctl', 'dispatch', 'exit']
run(command, check=True, capture_output=True, text=True, timeout=5)
return
if action == 'lock':
observer = observer_factory()
try: observer.ensure_locked()
finally: observer.close()
return
if action not in METHODS:
raise ValueError('Unknown power action')
logind = logind_factory()
state = logind.can(action)
if state not in {'yes', 'challenge'}:
raise RuntimeError('Power action is unavailable: ' + str(state))
if action == 'suspend':
if state != 'yes':
raise RuntimeError('Suspend requires authorization before locking')
observer = observer_factory()
try:
observer.ensure_locked()
logind.perform(action)
finally:
observer.close()
else:
logind.perform(action)
def main():
# Bound compositor roundtrips and authorization; a failed helper never forces an action.
def timed_out(*_):
raise TimeoutError('Power request timed out')
signal.signal(signal.SIGALRM, timed_out)
signal.alarm(85)
try:
if len(sys.argv) != 2:
raise ValueError('Expected capabilities, lock, logout, suspend, reboot or poweroff')
if sys.argv[1] == 'capabilities':
output = {'ok': True, 'capabilities': capabilities()}
else:
execute(sys.argv[1])
output = {'ok': True}
print(json.dumps(output))
return 0
except Exception as error:
print(json.dumps({'ok': False, 'error': str(error)}))
return 1
if __name__ == '__main__':
sys.exit(main())
+37
View File
@@ -0,0 +1,37 @@
#!/usr/bin/env python3
"""Strict JSON interface to powerprofilesctl, without shell execution."""
import json
import shutil
import subprocess
import sys
PROFILES = ('power-saver', 'balanced', 'performance')
def execute(argv, runner=subprocess.run, which=shutil.which):
if not which('powerprofilesctl'):
return {'ok': False, 'error': 'powerprofilesctl не установлен'}
if len(argv) == 1 and argv[0] == 'get':
args = ['powerprofilesctl', 'get']
elif len(argv) == 2 and argv[0] == 'set' and argv[1] in PROFILES:
args = ['powerprofilesctl', 'set', argv[1]]
else:
return {'ok': False, 'error': 'Недопустимая команда или профиль'}
try:
result = runner(args, capture_output=True, text=True, timeout=12, check=False)
except (OSError, subprocess.TimeoutExpired) as exc:
return {'ok': False, 'error': str(exc)[:300]}
if result.returncode:
return {'ok': False, 'error': (result.stderr or result.stdout or 'Команда завершилась с ошибкой').strip()[:300]}
if argv[0] == 'get':
profile = result.stdout.strip()
if profile not in PROFILES:
return {'ok': False, 'error': 'Неизвестный профиль: ' + profile[:100]}
return {'ok': True, 'profile': profile}
return {'ok': True, 'profile': argv[1]}
if __name__ == '__main__':
response = execute(sys.argv[1:])
print(json.dumps(response, ensure_ascii=False))
sys.exit(0 if response['ok'] else 1)
+16
View File
@@ -0,0 +1,16 @@
# Hyprland lock-notify bindings
Protocol source: https://github.com/hyprwm/hyprland-protocols/blob/main/protocols/hyprland-lock-notify-v1.xml
Retrieved 2026-11-17. Vendored XML SHA-256: `360589bc58a0a82768b477564f429dc4a8c016ae8311efad12e03f249ac704fc`.
The XML and generated Python retain the upstream copyright and BSD license.
Only this protocol is generated; the system pywayland package supplies the Wayland core.
Regenerate from the checked-in XML, without a network request:
```sh
python -m pywayland.scanner -i quickshell/backend/protocols/hyprland-lock-notify-v1.xml -o quickshell/backend/protocols
```
The observer never requests `ext_session_lock_v1` and cannot unlock the session.
It observes the compositor's notification after a lock client establishes the lock.
@@ -0,0 +1,99 @@
<?xml version="1.0" encoding="UTF-8"?>
<protocol name="hyprland_lock_notify_v1">
<copyright>
Copyright © 2025 Maximilian Seidler
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
</copyright>
<interface name="hyprland_lock_notifier_v1" version="1">
<description summary="lock notification manager">
This interface allows clients to monitor whether the wayland session is
locked or unlocked.
</description>
<request name="destroy" type="destructor">
<description summary="destroy the manager">
Destroy the manager object. All objects created via this interface
remain valid.
</description>
</request>
<request name="get_lock_notification">
<description summary="create a notification object">
Create a new lock notification object.
If the session is already locked when calling this method,
the locked event shall be sent immediately.
</description>
<arg name="id" type="new_id" interface="hyprland_lock_notification_v1"/>
</request>
</interface>
<interface name="hyprland_lock_notification_v1" version="1">
<description summary="lock notification">
This interface is used by the compositor to send lock notification events
to clients.
Typically the "locked" and "unlocked" events are emitted when a client
locks/unlocks the session via ext-session-lock, but the compositor may
choose to send notifications for any other locking mechanisms.
The compositor must notfiy after possible transition periods
between locked and unlocked states of the session.
In the context of ext-session-lock, that means the "locked" event is
expected to be sent after the session-lock client has presented
a lock screen frame on every output, which corresponds to the "locked"
event of ext-session-lock.
</description>
<request name="destroy" type="destructor">
<description summary="destroy the notification object">
Destroy the notification object.
</description>
</request>
<event name="locked">
<description summary="session is locked">
This event is sent when the wayland session is locked.
It's a compositor protocol error to send this event twice without an
unlock event in-between.
</description>
</event>
<event name="unlocked">
<description summary="session is no longer locked">
This event is sent when the wayland session is unlocked.
It's a compositor protocol error to send this event twice without an
locked event in-between. It's a compositor protocol error to send this
event prior to any locked event.
</description>
</event>
</interface>
</protocol>
@@ -0,0 +1,160 @@
# This file has been autogenerated by the pywayland scanner
# Copyright © 2025 Maximilian Seidler
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from __future__ import annotations
from pywayland.protocol_core import Argument, ArgumentType, Global, Interface, Proxy, Resource
class HyprlandLockNotificationV1(Interface):
"""Lock notification
This interface is used by the compositor to send lock notification events
to clients.
Typically the "locked" and "unlocked" events are emitted when a client
locks/unlocks the session via ext-session-lock, but the compositor may
choose to send notifications for any other locking mechanisms.
The compositor must notfiy after possible transition periods between locked
and unlocked states of the session. In the context of ext-session-lock,
that means the "locked" event is expected to be sent after the session-lock
client has presented a lock screen frame on every output, which corresponds
to the "locked" event of ext-session-lock.
"""
name = "hyprland_lock_notification_v1"
version = 1
class HyprlandLockNotifierV1(Interface):
"""Lock notification manager
This interface allows clients to monitor whether the wayland session is
locked or unlocked.
"""
name = "hyprland_lock_notifier_v1"
version = 1
class HyprlandLockNotificationV1Resource(Resource[HyprlandLockNotificationV1]):
interface = HyprlandLockNotificationV1
@HyprlandLockNotificationV1.event()
def locked(self) -> None:
"""Session is locked
This event is sent when the wayland session is locked.
It's a compositor protocol error to send this event twice without an
unlock event in-between.
"""
self._post_event(0)
@HyprlandLockNotificationV1.event()
def unlocked(self) -> None:
"""Session is no longer locked
This event is sent when the wayland session is unlocked.
It's a compositor protocol error to send this event twice without an
locked event in-between. It's a compositor protocol error to send this
event prior to any locked event.
"""
self._post_event(1)
class HyprlandLockNotifierV1Resource(Resource[HyprlandLockNotifierV1]):
interface = HyprlandLockNotifierV1
class HyprlandLockNotificationV1Proxy(Proxy[HyprlandLockNotificationV1]):
interface = HyprlandLockNotificationV1
@HyprlandLockNotificationV1.request()
def destroy(self) -> None:
"""Destroy the notification object
Destroy the notification object.
"""
self._marshal(0)
self._destroy()
class HyprlandLockNotifierV1Proxy(Proxy[HyprlandLockNotifierV1]):
interface = HyprlandLockNotifierV1
@HyprlandLockNotifierV1.request()
def destroy(self) -> None:
"""Destroy the manager
Destroy the manager object. All objects created via this interface
remain valid.
"""
self._marshal(0)
self._destroy()
@HyprlandLockNotifierV1.request(
Argument(ArgumentType.NewId, interface=HyprlandLockNotificationV1),
)
def get_lock_notification(self) -> HyprlandLockNotificationV1Proxy:
"""Create a notification object
Create a new lock notification object.
If the session is already locked when calling this method, the locked
event shall be sent immediately.
:returns:
:class:`~pywayland.protocol.hyprland_lock_notify_v1.HyprlandLockNotificationV1`
"""
id = self._marshal_constructor(1, HyprlandLockNotificationV1)
return id
class HyprlandLockNotificationV1Global(Global[HyprlandLockNotificationV1]):
interface = HyprlandLockNotificationV1
class HyprlandLockNotifierV1Global(Global[HyprlandLockNotifierV1]):
interface = HyprlandLockNotifierV1
HyprlandLockNotificationV1._gen_c()
HyprlandLockNotificationV1.proxy_class = HyprlandLockNotificationV1Proxy
HyprlandLockNotificationV1.resource_class = HyprlandLockNotificationV1Resource
HyprlandLockNotificationV1.global_class = HyprlandLockNotificationV1Global
HyprlandLockNotifierV1._gen_c()
HyprlandLockNotifierV1.proxy_class = HyprlandLockNotifierV1Proxy
HyprlandLockNotifierV1.resource_class = HyprlandLockNotifierV1Resource
HyprlandLockNotifierV1.global_class = HyprlandLockNotifierV1Global
+57
View File
@@ -0,0 +1,57 @@
#!/usr/bin/env python3
"""Read-only system overview. Never execute user-provided commands."""
import json
import os
import platform
from pathlib import Path
def os_release(path='/etc/os-release'):
result = {}
try:
for line in Path(path).read_text(encoding='utf-8').splitlines():
if '=' not in line or line.startswith('#'):
continue
key, value = line.split('=', 1)
if key in ('PRETTY_NAME', 'NAME', 'VERSION_ID'):
result[key] = value.strip().strip('"')
except OSError:
pass
return result
def memory_kib(path='/proc/meminfo'):
values = {}
try:
for line in Path(path).read_text(encoding='utf-8').splitlines():
key, _, val = line.partition(':')
if key in ('MemTotal', 'MemAvailable'):
values[key] = int(val.strip().split()[0])
except (OSError, ValueError, IndexError):
pass
return values
def uptime_seconds(path='/proc/uptime'):
try:
return max(0, int(float(Path(path).read_text().split()[0])))
except (OSError, ValueError, IndexError):
return 0
def snapshot():
release = os_release()
memory = memory_kib()
return {
'os': release.get('PRETTY_NAME') or release.get('NAME') or 'Linux',
'kernel': platform.release(),
'architecture': platform.machine(),
'hostname': platform.node(),
'memoryTotalMiB': memory.get('MemTotal', 0) // 1024,
'memoryAvailableMiB': memory.get('MemAvailable', 0) // 1024,
'uptimeSeconds': uptime_seconds(),
}
if __name__ == '__main__':
print(json.dumps(snapshot(), ensure_ascii=False))