refactor: kanshi atomar, Watch-Lock, disable-Semantik, Tweak-Erhalt

This commit is contained in:
humocs-man committed 2026-10-10 17:10:32 +02:00
1 parent d26c1f90f5
commit cb683976a1
2 files changed
+133 -41

No files matched your search

Binary file not shown.
+133 -41
View File
@@ -54,15 +54,22 @@ CONFIG_PATH = Path.home() / ".config" / "kanshi" / "config"
POLL_INTERVAL = 5 POLL_INTERVAL = 5
_VM_CACHE = None
def detect_vm(): def detect_vm():
"""True, wenn wir virtualisiert laufen (QEMU/Boxes-Test).""" """True, wenn wir virtualisiert laufen (QEMU/Boxes-Test). Einmalig
try: gecached (wird im Watch-Poll sonst alle 5 s neu gespawnt)."""
proc = subprocess.run( global _VM_CACHE
["systemd-detect-virt", "--vm"], capture_output=True, timeout=10 if _VM_CACHE is None:
) try:
except (FileNotFoundError, subprocess.TimeoutExpired): proc = subprocess.run(
return False ["systemd-detect-virt", "--vm"], capture_output=True, timeout=10
return proc.returncode == 0 )
_VM_CACHE = proc.returncode == 0
except (FileNotFoundError, subprocess.TimeoutExpired):
_VM_CACHE = False
return _VM_CACHE
def norm_rate(value): def norm_rate(value):
@@ -110,6 +117,11 @@ def detect_outputs():
chosen = choose_mode(modes, current, in_vm) chosen = choose_mode(modes, current, in_vm)
if not chosen: if not chosen:
continue continue
if not chosen.get("width") or not chosen.get("height"):
# Kaputter Modus (wlr-randr ohne Dimension) -> Output
# ueberspringen statt "NonexNone"-Config zu schreiben.
print(f"WARN: {name} ohne gueltigen Modus - uebersprungen", file=sys.stderr)
continue
outputs.append( outputs.append(
{ {
"name": name, "name": name,
@@ -208,15 +220,53 @@ def is_managed(path: Path):
def apply(text): def apply(text):
# Atomar: tmp + fsync + rename. Bei ENOSPC/Absturz bleibt die alte
# Config intakt statt trunkiert (schwarzer Bildschirm).
CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True) CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True)
if CONFIG_PATH.exists(): if CONFIG_PATH.exists():
backup = CONFIG_PATH.with_suffix(".bak") backup = CONFIG_PATH.with_suffix(".bak")
shutil.copy2(CONFIG_PATH, backup) shutil.copy2(CONFIG_PATH, backup)
print(f"Backup: {backup}") print(f"Backup: {backup}")
CONFIG_PATH.write_text(text) tmp = CONFIG_PATH.with_suffix(".tmp")
tmp.write_text(text)
with open(tmp, "rb") as f:
os.fsync(f.fileno())
os.replace(tmp, CONFIG_PATH)
print(f"Geschrieben: {CONFIG_PATH}") print(f"Geschrieben: {CONFIG_PATH}")
_WATCH_LOCK_FD = None
def acquire_watch_lock():
"""Single-Instance fuer --watch (zwei Daemonen wuerden Config + kanshi
im Wechsel umschreiben/neustarten). Zweite Instanz beendet sich leise."""
global _WATCH_LOCK_FD
import fcntl
lock_path = Path.home() / ".cache" / "kanshi-autoconfig" / "watch.lock"
try:
lock_path.parent.mkdir(parents=True, exist_ok=True)
fd = os.open(lock_path, os.O_CREAT | os.O_RDWR, 0o600)
except OSError:
return True # Lock nicht moeglich -> trotzdem laufen, kein harter Stopp
try:
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except OSError:
os.close(fd)
return False
_WATCH_LOCK_FD = fd
return True
_DISPLAY_WARNED = False
def wayland_socket_present():
rt = os.environ.get("XDG_RUNTIME_DIR")
disp = os.environ.get("WAYLAND_DISPLAY")
return bool(rt and disp and Path(rt, disp).exists())
def config_output_names(path: Path): def config_output_names(path: Path):
"""Output-Namen aus einer bestehenden kanshi-Config (ohne '*' Fallback).""" """Output-Namen aus einer bestehenden kanshi-Config (ohne '*' Fallback)."""
names = set() names = set()
@@ -238,17 +288,20 @@ def safe_read(path: Path):
def split_profiles(text): def split_profiles(text):
"""kanshi-Config zerlegen in (Header, {Name: Zeilen}, Reihenfolge).""" """kanshi-Config zerlegen in (Header, {Name: Zeilen}, Reihenfolge).
Versteht auch einzeilige Profile ('profile x { ... }')."""
header, sections, order = [], {}, [] header, sections, order = [], {}, []
cur = None cur = None
for line in text.splitlines(): for line in text.splitlines():
m = re.match(r"^\s*profile\s+(\S+)\s*\{", line)
if m:
cur = m.group(1)
sections[cur] = [line]
order.append(cur)
continue
if cur is None: if cur is None:
m = re.match(r"^\s*profile\s+(\S+)\s*\{", line)
if m:
cur = m.group(1)
sections[cur] = [line]
order.append(cur)
if line.strip().endswith("}"):
cur = None # einzeiliges Profil
continue
header.append(line) header.append(line)
else: else:
sections[cur].append(line) sections[cur].append(line)
@@ -257,6 +310,50 @@ def split_profiles(text):
return header, sections, order return header, sections, order
def profile_output_names(block_lines):
"""Output-Namen eines Profil-Blocks; 'disable'-Zeilen zaehlen NICHT
als benoetigt (deaktivierte Outputs muessen nicht angeschlossen sein)."""
names = set()
for line in block_lines:
parts = line.strip().split()
if len(parts) >= 2 and parts[0] == "output" and parts[1] != "*":
if len(parts) >= 3 and parts[2] == "disable":
continue
names.add(parts[1].strip("'\""))
return names
def output_name_of(line):
parts = line.strip().split()
if len(parts) >= 2 and parts[0] == "output" and parts[1] != "*":
return parts[1].strip("'\"")
return None
def merge_profile_lines(old_lines, new_lines):
"""Gleichnamige Profile zeilenweise mergen: User-Zeilen (Modi, Positionen,
Tweaks wie 75 Hz) bleiben fuer fortbestehende Outputs erhalten; nur
entfallene Outputs fliegen raus, neue kommen aus dem frischen Render.
So ueberlebt z.B. Deckel-auf/zu-Wechsel ohne Modus-Verlust."""
old_by_name = {}
for line in old_lines:
n = output_name_of(line)
if n is not None:
old_by_name[n] = line
head = new_lines[:1]
foot = [l for l in new_lines[-1:] if l.strip() == "}"] or ["}"]
out = list(head)
for line in new_lines[1:]:
n = output_name_of(line)
if n is None:
continue
if line.strip() == "}":
continue
out.append(old_by_name.get(n, line))
out.extend(foot)
return out
def merge_configs(old_text, new_text): def merge_configs(old_text, new_text):
"""Profile mergen: Neue gewinnen bei Namensgleichheit; alte """Profile mergen: Neue gewinnen bei Namensgleichheit; alte
nicht-fallback Profile (z.B. docked bei ungedocktem Rechner) bleiben nicht-fallback Profile (z.B. docked bei ungedocktem Rechner) bleiben
@@ -280,6 +377,9 @@ def merge_configs(old_text, new_text):
for name in final_o: for name in final_o:
if name not in final_s: if name not in final_s:
final_s[name] = old_s[name] final_s[name] = old_s[name]
elif name in old_s:
# Gleichnamig: Zeilen mergen statt ersetzen (Tweaks bleiben).
final_s[name] = merge_profile_lines(old_s[name], new_s[name])
kept = [n for n in final_o if n not in new_o] kept = [n for n in final_o if n not in new_o]
lines = list(new_h) lines = list(new_h)
if kept: if kept:
@@ -293,36 +393,18 @@ def merge_configs(old_text, new_text):
def matching_profile_name(connected, path=CONFIG_PATH): def matching_profile_name(connected, path=CONFIG_PATH):
"""Erstes Profil, dessen Outputs alle angeschlossen sind (kanshi-Logik).""" """Erstes Profil, dessen (nicht-disabled) Outputs alle angeschlossen
sind (kanshi-Logik). Nutzt denselben Parser wie der Merge (kein Drift)."""
try: try:
text = path.read_text() text = path.read_text()
except OSError: except OSError:
return None return None
profiles = [] _, sections, order = split_profiles(text)
cur, outs = None, [] for name in order:
for line in text.splitlines(): outs = profile_output_names(sections[name])
s = line.strip()
if s.startswith("profile"):
parts = s.split()
if cur is not None:
profiles.append((cur, outs))
cur = parts[1].rstrip("{").strip() if len(parts) >= 2 else None
outs = []
continue
if cur is not None:
if s == "}":
profiles.append((cur, outs))
cur, outs = None, []
elif s.startswith("output"):
p = s.split()
if len(p) >= 2 and p[1] != "*":
outs.append(p[1].strip("'\""))
if cur is not None:
profiles.append((cur, outs))
for name, outs in profiles:
if outs and all(o in connected for o in outs): if outs and all(o in connected for o in outs):
return name return name
if any(n == "fallback" for n, _ in profiles): if "fallback" in sections:
return "fallback" return "fallback"
return None return None
@@ -379,9 +461,16 @@ def find_kanshi_pids():
def ensure_kanshi(child): def ensure_kanshi(child):
"""kanshi sicherstellen: eigener Child bevorzugt, fremde Instanz respektiert.""" """kanshi sicherstellen: eigener Child bevorzugt, fremde Instanz respektiert.
Ohne Wayland-Socket nicht spammen (kein Fork-Loop ausserhalb der Session)."""
global _DISPLAY_WARNED
if child is not None and child.poll() is None: if child is not None and child.poll() is None:
return child return child
if not wayland_socket_present():
if not _DISPLAY_WARNED:
print("WARN: kein Wayland-Socket - kanshi wird nicht gestartet", file=sys.stderr)
_DISPLAY_WARNED = True
return child
if find_kanshi_pids(): if find_kanshi_pids():
return None return None
try: try:
@@ -411,6 +500,9 @@ def restart_kanshi(child):
def run_watch(): def run_watch():
"""Dauerlauf: Output-Wechsel erkennen, Config mergen, kanshi (neu) """Dauerlauf: Output-Wechsel erkennen, Config mergen, kanshi (neu)
starten, Profilwechsel per notify-send melden.""" starten, Profilwechsel per notify-send melden."""
if not acquire_watch_lock():
print("kanshi-autoconfig --watch: bereits aktiv - beende mich.")
return
child, last_set = None, None child, last_set = None, None
print("kanshi-autoconfig --watch: gestartet (Intervall 5s)", flush=True) print("kanshi-autoconfig --watch: gestartet (Intervall 5s)", flush=True)
while True: while True: