143 lines
5.7 KiB
Python
143 lines
5.7 KiB
Python
#!/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)
|