fix: kanshi-Profile mergen + Hotplug-Watcher mit OSD

This commit is contained in:
humocs-man committed 2026-10-07 19:20:04 +02:00
1 parent 76c914db54
commit 84b037ec73
5 files changed
+238 -4

No files matched your search

@@ -7,6 +7,9 @@
# kanshi-autoconfig --print # zeigt erkannte Outputs + Vorschlag
# kanshi-autoconfig --apply # schreibt ~/.config/kanshi/config
# wdisplays # grafisches Feintuning (optional)
# Neugenerierung mergt: Profile anderer Setups bleiben erhalten (nur
# gleichnamige werden ersetzt). Der Autostart-Watcher (--watch) erkennt
# Docking auch mitten in der Session und meldet Wechsel per OSD.
#
# Die generierte Config enthaelt drei Profile:
# docked – externe Monitore in einer Reihe, internes Panel aus
+5 -1
View File
@@ -31,7 +31,11 @@ xdg-user-dirs-update >/dev/null 2>&1 || true
# wenn sie fehlt oder von kanshi-autoconfig verwaltet wird.
# Eigene Hand-Edits bleiben unangetastet.
kanshi-autoconfig --apply-if-managed >/dev/null 2>&1 || true
kanshi >/dev/null 2>&1 &
# Watcher-Daemon: erkennt Docking mitten in der Session (Hotplug),
# schreibt bei neuem Output-Set neu (Merge: fremde Profile bleiben),
# startet kanshi bei Bedarf (neu) und meldet Profilwechsel per OSD
# (notify-send). Ersetzt das blosse `kanshi &` von frueher.
kanshi-autoconfig --watch >/dev/null 2>&1 &
# 2. Hintergrund-Fallback (Noctalia setzt das Wallpaper selbst)
swaybg -c '#1a1b26' >/dev/null 2>&1 &
Binary file not shown.
+212 -3
View File
@@ -14,6 +14,17 @@ Verhalten:
unveraendertem Output-Set bleibt eine verwaltete Config
unangetastet (Modus-Tweaks inklusive). Wird vom
labwc-Autostart bei jedem Login aufgerufen.
--watch Dauerlauf (Autostart): erkennt Docking mitten in der
Session, schreibt bei neuem Output-Set neu (Merge,
siehe unten), startet kanshi bei Bedarf (neu) und
meldet Profilwechsel per notify-send (kanshi selbst
hat kein OSD).
MERGE statt Ueberschreiben: Eine Neugenerierung ersetzt nur Profile
gleichen Namens; Profile anderer Setups (z.B. docked bei gerade
ungedocktem Rechner) bleiben erhalten. Sonst wuerde ein ungedockter
Login das docked-Profil loeschen und der Daemon koennte spaeter nicht
mehr umschalten (interner Bildschirm bliebe an).
Moduswahl: Auf echter Hardware der EDID-preferred-Modus (meist nativ =
richtig). In VMs meldet die Firmware oft einen Kleinstmodus als preferred
@@ -28,14 +39,19 @@ ohne Layout dasteht.
"""
import json
import os
import re
import shutil
import signal
import subprocess
import sys
import time
from datetime import datetime
from pathlib import Path
MARKER = "# kanshi-autoconfig: managed"
CONFIG_PATH = Path.home() / ".config" / "kanshi" / "config"
POLL_INTERVAL = 5
def detect_vm():
@@ -214,7 +230,200 @@ def config_output_names(path: Path):
return names
def safe_read(path: Path):
try:
return path.read_text()
except OSError:
return ""
def split_profiles(text):
"""kanshi-Config zerlegen in (Header, {Name: Zeilen}, Reihenfolge)."""
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:
header.append(line)
else:
sections[cur].append(line)
if line.strip() == "}":
cur = None
return header, sections, order
def merge_configs(old_text, new_text):
"""Profile mergen: Neue gewinnen bei Namensgleichheit; alte
nicht-fallback Profile (z.B. docked bei ungedocktem Rechner) bleiben
erhalten. Fallback kommt immer frisch aus dem neuen Render.
Reihenfolge ist wesentlich (kanshi nimmt das erste passende Profil):
docked vor undocked, fallback zuletzt."""
new_h, new_s, new_o = split_profiles(new_text)
_, old_s, old_o = split_profiles(old_text or "")
combined = list(new_o)
for name in old_o:
if name not in new_s and name != "fallback" and name not in combined:
combined.append(name)
def rank(name):
if name == "fallback":
return 99
return {"docked": 0, "undocked": 1}.get(name, 50)
final_o = sorted(combined, key=rank) # stabil: Rest behält Reihenfolge
final_s = dict(new_s)
for name in final_o:
if name not in final_s:
final_s[name] = old_s[name]
kept = [n for n in final_o if n not in new_o]
lines = list(new_h)
if kept:
lines.append(f"# Beibehaltene Profile anderer Setups: {', '.join(kept)} "
"(Bestaende, werden ignoriert wenn unpassend).")
lines.append("")
for name in final_o:
lines.extend(final_s[name])
lines.append("")
return "\n".join(lines)
def matching_profile_name(connected, path=CONFIG_PATH):
"""Erstes Profil, dessen Outputs alle angeschlossen sind (kanshi-Logik)."""
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:
if outs and all(o in connected for o in outs):
return name
if any(n == "fallback" for n, _ in profiles):
return "fallback"
return None
def notify_send(summary, body=""):
if shutil.which("notify-send") is None:
return
try:
subprocess.run(
["notify-send", summary, body, "--app-name=kanshi-autoconfig",
"--icon=preferences-desktop-display"],
timeout=10, check=False,
)
except Exception:
pass
def find_kanshi_pids():
"""PIDs laufender kanshi-Prozesse (ohne uns selbst), ohne pkill-Abhaengigkeit."""
pids, me = [], os.getpid()
try:
entries = os.listdir("/proc")
except OSError:
return []
for e in entries:
if not e.isdigit() or int(e) == me:
continue
try:
with open(f"/proc/{e}/comm") as f:
if f.read().strip() == "kanshi":
pids.append(int(e))
except OSError:
continue
return pids
def ensure_kanshi(child):
"""kanshi sicherstellen: eigener Child bevorzugt, fremde Instanz respektiert."""
if child is not None and child.poll() is None:
return child
if find_kanshi_pids():
return None
try:
return subprocess.Popen(
["kanshi"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
except (FileNotFoundError, OSError):
return None
def restart_kanshi(child):
"""kanshi neu starten (Config wurde umgeschrieben und wird sonst nicht neu gelesen)."""
if child is not None and child.poll() is None:
child.terminate()
try:
child.wait(timeout=5)
except Exception:
child.kill()
for pid in find_kanshi_pids():
try:
os.kill(pid, signal.SIGTERM)
except OSError:
pass
return ensure_kanshi(None)
def run_watch():
"""Dauerlauf: Output-Wechsel erkennen, Config mergen, kanshi (neu)
starten, Profilwechsel per notify-send melden."""
child, last_set = None, None
print("kanshi-autoconfig --watch: gestartet (Intervall 5s)", flush=True)
while True:
try:
outputs = detect_outputs()
except Exception as e: # noqa: BLE001 - Watcher darf nie sterben
print(f"WARN: Erkennung fehlgeschlagen: {e}", file=sys.stderr, flush=True)
outputs = []
if outputs:
names = {o["name"] for o in outputs}
if last_set is None:
# Erstlauf: wie --apply-if-managed sicherstellen, kanshi starten.
if is_managed(CONFIG_PATH) and names != config_output_names(CONFIG_PATH):
apply(merge_configs(safe_read(CONFIG_PATH), render(outputs)))
elif names != last_set:
profile = None
if is_managed(CONFIG_PATH):
if names != config_output_names(CONFIG_PATH):
apply(merge_configs(safe_read(CONFIG_PATH), render(outputs)))
child = restart_kanshi(child)
profile = matching_profile_name(names)
notify_send("Monitorprofil gewechselt",
f"{profile or 'unbekannt'}: {', '.join(sorted(names))}")
last_set = names
child = ensure_kanshi(child)
time.sleep(POLL_INTERVAL)
def main(argv):
if "--watch" in argv:
run_watch()
return 0
outputs = detect_outputs()
if not outputs:
print("WARN: keine Outputs erkannt", file=sys.stderr)
@@ -232,7 +441,7 @@ def main(argv):
return 0
if "--apply-if-managed" in argv:
if not CONFIG_PATH.exists():
apply(text) # Erst-Login: anlegen
apply(merge_configs("", text)) # Erst-Login: anlegen
return 0
if not is_managed(CONFIG_PATH):
print(f"{CONFIG_PATH} ist hand-gepflegt - lasse sie unangetastet.")
@@ -248,8 +457,8 @@ def main(argv):
print(f"Outputs unveraendert ({', '.join(sorted(config_output_names(CONFIG_PATH)))})"
" - behalte Config (inkl. Modus-Tweaks) bei.")
return 0
# Output-Set geaendert (angedockt/abgedockt): neu generieren.
apply(text)
# Output-Set geaendert (angedockt/abgedockt): mergen (andere Profile bleiben).
apply(merge_configs(safe_read(CONFIG_PATH), text))
return 0
+18
View File
@@ -46,6 +46,24 @@ if [[ -f "${AUTOSTART}" ]] && grep -q 'swayidle' "${AUTOSTART}"; then
echo "migriert: swayidle-Block aus ${AUTOSTART} entfernt (Backup .bak)"
fi
# Migration: kanshi-Watcher statt blossem `kanshi &` (Hotplug mitten in
# der Session + OSD bei Profilwechsel). Greift nur, wenn noch kein
# --watch laeuft und eine blosse kanshi-Zeile existiert. Mit Backup.
if [[ -f "${AUTOSTART}" ]] && ! grep -q 'kanshi-autoconfig --watch' "${AUTOSTART}" \
&& grep -Eq '^[[:space:]]*kanshi([[:space:]]|$)' "${AUTOSTART}"; then
cp -n "${AUTOSTART}" "${AUTOSTART}.bak" 2>/dev/null || true
read -r -d '' KANSHI_BLOCK <<'EOF' || true
# Watcher-Daemon: erkennt Docking mitten in der Session (Hotplug),
# schreibt bei neuem Output-Set neu (Merge: fremde Profile bleiben),
# startet kanshi bei Bedarf (neu) und meldet Profilwechsel per OSD
# (notify-send). Ersetzt das blosse `kanshi &` von frueher.
kanshi-autoconfig --watch >/dev/null 2>&1 &
EOF
awk -v block="${KANSHI_BLOCK}" '{ if (!done && $0 ~ /^[[:space:]]*kanshi([[:space:]]|$)/) { print block; done=1; next } print }' "${AUTOSTART}" > "${AUTOSTART}.new" \
&& mv "${AUTOSTART}.new" "${AUTOSTART}"
echo "migriert: kanshi-Watcher in ${AUTOSTART} (Backup .bak)"
fi
# Migration: Session-Integration (graphical-session.target + Portal-Units).
# Bestandnutzer haben eine Autostart ohne den Block (skel greift nur bei
# Neuanlage). Der Block wird aus /etc/skel gelesen, damit er nur an einer