71 lines
2.8 KiB
Python
71 lines
2.8 KiB
Python
"""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()
|