#!/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())