diff --git a/scripts/__pycache__/kanshi-autoconfigcpython-314.pyc b/scripts/__pycache__/kanshi-autoconfigcpython-314.pyc index 41663ee..53672ab 100644 Binary files a/scripts/__pycache__/kanshi-autoconfigcpython-314.pyc and b/scripts/__pycache__/kanshi-autoconfigcpython-314.pyc differ diff --git a/scripts/kanshi-autoconfig b/scripts/kanshi-autoconfig index 23a780b..bdfa08a 100755 --- a/scripts/kanshi-autoconfig +++ b/scripts/kanshi-autoconfig @@ -54,15 +54,22 @@ CONFIG_PATH = Path.home() / ".config" / "kanshi" / "config" POLL_INTERVAL = 5 +_VM_CACHE = None + + def detect_vm(): - """True, wenn wir virtualisiert laufen (QEMU/Boxes-Test).""" - try: - proc = subprocess.run( - ["systemd-detect-virt", "--vm"], capture_output=True, timeout=10 - ) - except (FileNotFoundError, subprocess.TimeoutExpired): - return False - return proc.returncode == 0 + """True, wenn wir virtualisiert laufen (QEMU/Boxes-Test). Einmalig + gecached (wird im Watch-Poll sonst alle 5 s neu gespawnt).""" + global _VM_CACHE + if _VM_CACHE is None: + try: + proc = subprocess.run( + ["systemd-detect-virt", "--vm"], capture_output=True, timeout=10 + ) + _VM_CACHE = proc.returncode == 0 + except (FileNotFoundError, subprocess.TimeoutExpired): + _VM_CACHE = False + return _VM_CACHE def norm_rate(value): @@ -110,6 +117,11 @@ def detect_outputs(): chosen = choose_mode(modes, current, in_vm) if not chosen: 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( { "name": name, @@ -208,15 +220,53 @@ def is_managed(path: Path): 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) if CONFIG_PATH.exists(): backup = CONFIG_PATH.with_suffix(".bak") shutil.copy2(CONFIG_PATH, 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}") +_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): """Output-Namen aus einer bestehenden kanshi-Config (ohne '*' Fallback).""" names = set() @@ -238,17 +288,20 @@ def safe_read(path: Path): 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 = [], {}, [] cur = None 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: + 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) else: sections[cur].append(line) @@ -257,6 +310,50 @@ def split_profiles(text): 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): """Profile mergen: Neue gewinnen bei Namensgleichheit; alte 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: if name not in final_s: 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] lines = list(new_h) if kept: @@ -293,36 +393,18 @@ def merge_configs(old_text, new_text): 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: text = path.read_text() except OSError: return None - profiles = [] - cur, outs = None, [] - for line in text.splitlines(): - 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: + _, sections, order = split_profiles(text) + for name in order: + outs = profile_output_names(sections[name]) if outs and all(o in connected for o in outs): return name - if any(n == "fallback" for n, _ in profiles): + if "fallback" in sections: return "fallback" return None @@ -379,9 +461,16 @@ def find_kanshi_pids(): 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: 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(): return None try: @@ -411,6 +500,9 @@ def restart_kanshi(child): def run_watch(): """Dauerlauf: Output-Wechsel erkennen, Config mergen, kanshi (neu) 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 print("kanshi-autoconfig --watch: gestartet (Intervall 5s)", flush=True) while True: