#!/usr/bin/python3 """Apply the standard KDE Plasma settings used on the VDI clients. The settings are intentionally model-independent: * Touchpad settings are written to KWin's global ``[Libinput][Defaults][Touchpad]`` group, so they apply to every touchpad regardless of vendor/product/name. * PowerDevil is configured for AC, battery and low-battery profiles. * KScreenLocker is configured not to lock automatically. The module can be run in two modes: * as root (default): write the system-wide defaults, update every user in /home, install the session helper and apply the settings to any user who is currently logged in; * ``--session``: run as the logged-in user from the XDG autostart entry. It applies the settings to the running KWin/PowerDevil/KScreenLocker session. All operations are idempotent. Only the keys listed below are touched; other user settings are preserved. """ import json import logging import os import pwd import shutil import subprocess import sys import time from pathlib import Path logger = logging.getLogger("vdi-kde-settings") KWRITE = shutil.which("kwriteconfig6") KREAD = shutil.which("kreadconfig6") BUSCTL = shutil.which("busctl") RUNUSER = shutil.which("runuser") SUDO = shutil.which("sudo") SYSTEM_CONFIG_DIR = Path("/etc/xdg") HELPER_PATH = Path("/usr/local/bin/vdi-kde-settings") AUTOSTART_DIR = Path("/etc/xdg/autostart") AUTOSTART_FILE = AUTOSTART_DIR / "vdi-kde-settings.desktop" LEGACY_TOUCHPAD_CONFIG = Path("/etc/X11/xorg.conf.d/90-libinput-touchpad.conf") LEGACY_DPMS_SCRIPT = Path("/etc/profile.d/disable-dpms.sh") LEGACY_SDDM_CONFIG = Path("/etc/sddm.conf.d/10-x11-only.conf") TOUCHPAD_GROUP = ("Libinput", "Defaults", "Touchpad") TOUCHPAD_SETTINGS = ( # Match the old Xorg InputClass settings: tapping, natural scrolling, # disable-while-typing and clickfinger. ("TapToClick", "true", "bool"), ("NaturalScroll", "true", "bool"), ("DisableWhileTyping", "true", "bool"), ("ClickMethod", "2", None), # 2 == clickfinger ) POWER_PROFILES = ("AC", "Battery", "LowBattery") POWER_DISPLAY_SETTINGS = ( # "Never" in the PowerDevil KCM. ("DimDisplayWhenIdle", "false", "bool"), ("DimDisplayIdleTimeoutSec", "-1", None), ("TurnOffDisplayWhenIdle", "false", "bool"), ("TurnOffDisplayIdleTimeoutSec", "-1", None), ("LockBeforeTurnOffDisplay", "false", "bool"), ) POWER_SUSPEND_SETTINGS = ( # No automatic suspend. ("AutoSuspendAction", "0", None), # 0 == NoAction ("AutoSuspendIdleTimeoutSec", "0", None), ) LOCK_GROUP = ("Daemon",) LOCK_SETTINGS = ( ("Autolock", "false", "bool"), ("Timeout", "0", None), ("LockOnResume", "false", "bool"), ("LockOnStart", "false", "bool"), ) AUTOSTART_CONTENT = """[Desktop Entry] Type=Application Name=VDI KDE Settings Comment=Apply the standard VDI touchpad, power and screen-lock settings Exec=/usr/local/bin/vdi-kde-settings --session Terminal=false NoDisplay=true OnlyShowIn=KDE; X-KDE-autostart-phase=2 """ def _config_sections(): """Return [(filename, [((group...), ((key, value, type), ...)), ...])].""" sections = [("kcminputrc", [(TOUCHPAD_GROUP, TOUCHPAD_SETTINGS)])] power_sections = [] for profile in POWER_PROFILES: power_sections.append(((profile, "Display"), POWER_DISPLAY_SETTINGS)) power_sections.append(((profile, "SuspendAndShutdown"), POWER_SUSPEND_SETTINGS)) sections.append(("powerdevilrc", power_sections)) sections.append(("kscreenlockerrc", [(LOCK_GROUP, LOCK_SETTINGS)])) return sections def _kconfig_args(command, path, groups, key=None): args = [command, "--file", str(path)] for group in groups: args.extend(["--group", group]) if key is not None: args.extend(["--key", key]) return args def _kconfig_get(path, groups, key): if not KREAD: return None try: result = subprocess.run( _kconfig_args(KREAD, path, groups, key), check=False, capture_output=True, text=True, ) except OSError: return None if result.returncode != 0: return None return result.stdout.strip() def _kconfig_set(path, groups, key, value, type_name): if not KWRITE: logger.warning("kwriteconfig6 is not installed; cannot write %s", path) return False args = _kconfig_args(KWRITE, path, groups, key) if type_name == "bool": args.extend(["--type", "bool"]) # Values such as "-1" must not be interpreted as command line options. args.extend(["--", value]) try: result = subprocess.run(args, check=False, capture_output=True, text=True) except OSError as error: logger.warning("Could not run kwriteconfig6: %s", error) return False if result.returncode != 0: logger.warning( "Could not write %s [%s] %s: %s", path, "][".join(groups), key, result.stderr.strip(), ) return False return True def _ensure_key(path, groups, key, value, type_name): """Write a key only if it differs from the requested value.""" current = _kconfig_get(path, groups, key) if current == value: return False return _kconfig_set(path, groups, key, value, type_name) def _ensure_config(path, sections, owner=None): changed = False for groups, settings in sections: for key, value, type_name in settings: if _ensure_key(path, groups, key, value, type_name): changed = True if path.exists() and owner is not None: stat = path.stat() if stat.st_uid != owner[0] or stat.st_gid != owner[1]: try: os.chown(path, owner[0], owner[1]) except OSError as error: logger.warning("Could not change owner of %s: %s", path, error) return changed def ensure_system_configs(): """Write the system-wide defaults below /etc/xdg.""" try: SYSTEM_CONFIG_DIR.mkdir(parents=True, exist_ok=True) except OSError as error: logger.warning("Could not create %s: %s", SYSTEM_CONFIG_DIR, error) return for filename, sections in _config_sections(): path = SYSTEM_CONFIG_DIR / filename _ensure_config(path, sections, owner=(0, 0)) # kwriteconfig6 creates files with mode 0600; system-wide defaults must # be readable by the user sessions. if path.exists(): try: os.chmod(path, 0o644) except OSError as error: logger.warning("Could not change mode of %s: %s", path, error) def install_helper(): """Install the session helper and its XDG autostart entry.""" try: source = Path(__file__).resolve() target = HELPER_PATH.resolve() if source != target: HELPER_PATH.parent.mkdir(parents=True, exist_ok=True) temporary = HELPER_PATH.with_name(HELPER_PATH.name + ".tmp") shutil.copy2(source, temporary) os.chmod(temporary, 0o755) os.chown(temporary, 0, 0) os.replace(temporary, HELPER_PATH) else: os.chmod(HELPER_PATH, 0o755) os.chown(HELPER_PATH, 0, 0) except OSError as error: logger.warning("Could not install %s: %s", HELPER_PATH, error) return try: AUTOSTART_DIR.mkdir(parents=True, exist_ok=True) current = AUTOSTART_FILE.read_text() if AUTOSTART_FILE.exists() else None if current != AUTOSTART_CONTENT: temporary = AUTOSTART_FILE.with_name(AUTOSTART_FILE.name + ".tmp") temporary.write_text(AUTOSTART_CONTENT) os.chmod(temporary, 0o644) os.chown(temporary, 0, 0) os.replace(temporary, AUTOSTART_FILE) if AUTOSTART_FILE.exists(): os.chmod(AUTOSTART_FILE, 0o644) os.chown(AUTOSTART_FILE, 0, 0) except OSError as error: logger.warning("Could not install %s: %s", AUTOSTART_FILE, error) def ensure_user_configs(user): """Write the settings into a user's ~/.config, preserving other keys.""" home = Path(user.pw_dir) if not home.is_dir(): return False config_dir = home / ".config" created = False if not config_dir.is_dir(): try: config_dir.mkdir(mode=0o700, parents=True, exist_ok=True) created = True except OSError as error: logger.warning("Could not create %s: %s", config_dir, error) return False if created: try: os.chown(config_dir, user.pw_uid, user.pw_gid) except OSError as error: logger.warning("Could not change owner of %s: %s", config_dir, error) changed = False for filename, sections in _config_sections(): path = config_dir / filename if _ensure_config(path, sections, owner=(user.pw_uid, user.pw_gid)): changed = True return changed def system_users(): """Yield the regular users whose home is below /home.""" home_root = Path("/home") if not home_root.is_dir(): return for entry in sorted(home_root.iterdir()): if not entry.is_dir(): continue try: user = pwd.getpwnam(entry.name) except KeyError: continue if user.pw_uid < 1000: continue if Path(user.pw_dir).resolve() != entry.resolve(): continue if user.pw_shell.endswith(("nologin", "false")): continue yield user def _session_bus(user): runtime = Path(f"/run/user/{user.pw_uid}") return runtime, runtime / "bus" def _session_env(user): runtime, bus = _session_bus(user) env = os.environ.copy() env["XDG_RUNTIME_DIR"] = str(runtime) env["DBUS_SESSION_BUS_ADDRESS"] = f"unix:path={bus}" return env def _busctl(args, env): if not BUSCTL: return None try: return subprocess.run( [BUSCTL, "--user"] + args, env=env, check=False, capture_output=True, text=True, timeout=15, ) except (OSError, subprocess.TimeoutExpired): return None def _busctl_ok(args, env): result = _busctl(args, env) return result is not None and result.returncode == 0 def _kwin_devices(env): result = _busctl( [ "--json=short", "get-property", "org.kde.KWin", "/org/kde/KWin/InputDevice", "org.kde.KWin.InputDeviceManager", "devicesSysNames", ], env, ) if result is None or result.returncode != 0: return None try: return json.loads(result.stdout).get("data", []) except (json.JSONDecodeError, AttributeError): return None def _kwin_property(env, path, name): result = _busctl( [ "--json=short", "get-property", "org.kde.KWin", path, "org.kde.KWin.InputDevice", name, ], env, ) if result is None or result.returncode != 0: return None try: return json.loads(result.stdout).get("data") except (json.JSONDecodeError, AttributeError): return None def _set_kwin_bool(env, path, name, value=True): current = _kwin_property(env, path, name) if current is value: return False result = _busctl( [ "set-property", "org.kde.KWin", path, "org.kde.KWin.InputDevice", name, "b", "true" if value else "false", ], env, ) if result is None or result.returncode != 0: return False return True def _apply_touchpad(env, sysname): path = f"/org/kde/KWin/InputDevice/{sysname}" if _kwin_property(env, path, "touchpad") is not True: return name = _kwin_property(env, path, "name") or sysname changed = False for prop, support_prop in ( ("tapToClick", None), ("naturalScroll", "supportsNaturalScroll"), ("disableWhileTyping", "supportsDisableWhileTyping"), ("clickMethodClickfinger", "supportsClickMethodClickfinger"), ): if support_prop is not None and _kwin_property(env, path, support_prop) is False: continue if _set_kwin_bool(env, path, prop): changed = True if changed: logger.info("Applied touchpad settings to %s (%s)", name, sysname) def _emit_kwin_reload(env): _busctl_ok( [ "emit", "/KGlobalSettings", "org.kde.KGlobalSettings", "notifyChange", "ii", "3", "0", ], env, ) def apply_session(): """Apply settings to the current graphical session (run as the user).""" try: user = pwd.getpwuid(os.getuid()) except KeyError: logger.error("Could not determine the current user") return 1 try: ensure_user_configs(user) except Exception: logger.exception("Could not update the user configuration") env = _session_env(user) _runtime, bus = _session_bus(user) if not bus.exists(): logger.info("No session bus for %s; skipping live KDE settings", user.pw_name) return 0 # KWin and PowerDevil may still be starting when the autostart entry runs. devices = None deadline = time.monotonic() + 15 while time.monotonic() < deadline: devices = _kwin_devices(env) if devices is not None: break time.sleep(0.5) if devices is None: logger.warning("KWin input devices are not available yet") else: # Let KWin re-read kcminputrc, then force the values on every touchpad # so that stale per-device entries from older versions are corrected. _emit_kwin_reload(env) for sysname in devices: _apply_touchpad(env, sysname) _busctl_ok( [ "call", "org.kde.Solid.PowerManagement", "/org/kde/Solid/PowerManagement", "org.kde.Solid.PowerManagement", "refreshStatus", ], env, ) _busctl_ok( [ "call", "org.kde.screensaver", "/ScreenSaver", "org.kde.screensaver", "configure", ], env, ) return 0 def _run_session_helper(user): if not HELPER_PATH.exists(): return # Prefer sudo: it also performs the SELinux context transition to the # target user, which is needed to connect to that user's session bus from # a root cron job on Fedora. if SUDO: # -n: never prompt. Root does not need a password; this only prevents a # stuck cron job if sudo is misconfigured. runner = [SUDO, "-n", "-u", user.pw_name, "--"] elif RUNUSER: runner = [RUNUSER, "-u", user.pw_name, "--"] else: logger.warning("Neither sudo nor runuser is available; cannot run session helper") return runtime, _bus = _session_bus(user) command = runner + [ "/usr/bin/env", f"HOME={user.pw_dir}", f"XDG_RUNTIME_DIR={runtime}", f"DBUS_SESSION_BUS_ADDRESS=unix:path={runtime}/bus", "PATH=/usr/local/bin:/usr/bin:/bin", str(HELPER_PATH), "--session", ] try: result = subprocess.run( command, check=False, capture_output=True, text=True, timeout=45 ) except (OSError, subprocess.TimeoutExpired) as error: logger.warning("Could not apply settings for %s: %s", user.pw_name, error) return if result.returncode != 0: logger.warning( "Session helper failed for %s: %s", user.pw_name, result.stderr.strip(), ) def _remove_legacy_file(path, description): if not path.exists() and not path.is_symlink(): return try: path.unlink() logger.info("Removed legacy %s (%s)", description, path) except OSError as error: logger.warning("Could not remove %s: %s", path, error) def cleanup_legacy_config(): """Remove the old X11/SDDM-only provisioning files.""" _remove_legacy_file(LEGACY_TOUCHPAD_CONFIG, "Xorg touchpad configuration") _remove_legacy_file(LEGACY_DPMS_SCRIPT, "xset DPMS script") _remove_legacy_file(LEGACY_SDDM_CONFIG, "X11-only SDDM configuration") skel_link = Path("/etc/skel/.config/autostart-scripts/disable-dpms.sh") _remove_legacy_file(skel_link, "xset autostart symlink") # Older versions of the provisioning script disabled the Wayland session # by renaming its desktop file. disabled = Path("/usr/share/wayland-sessions/plasmawayland.desktop.disabled") current = Path("/usr/share/wayland-sessions/plasmawayland.desktop") plasma = Path("/usr/share/wayland-sessions/plasma.desktop") if disabled.exists(): try: if current.exists() or plasma.exists(): disabled.unlink() else: disabled.rename(current) logger.info("Restored the Wayland session entry") except OSError as error: logger.warning("Could not restore the Wayland session entry: %s", error) def cleanup_user_legacy(user): link = Path(user.pw_dir) / ".config/autostart-scripts/disable-dpms.sh" if not link.is_symlink(): return try: target = os.readlink(link) except OSError: return if target == str(LEGACY_DPMS_SCRIPT) or "disable-dpms.sh" in target: _remove_legacy_file(link, "user xset autostart symlink") def apply_all(): """Root entry point: write defaults and update all users.""" if os.geteuid() != 0: logger.error("This mode must be run as root") return 1 cleanup_legacy_config() install_helper() ensure_system_configs() for user in system_users(): try: ensure_user_configs(user) except Exception: logger.exception("Could not update configuration for %s", user.pw_name) try: cleanup_user_legacy(user) except Exception: logger.exception("Could not clean up legacy files for %s", user.pw_name) _runtime, bus = _session_bus(user) if bus.exists(): _run_session_helper(user) return 0 def main(): logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s", ) if "--session" in sys.argv[1:]: return apply_session() return apply_all() if __name__ == "__main__": sys.exit(main())