From 68460f499bacdbee4b910897897d86426888b936 Mon Sep 17 00:00:00 2001 From: Hendrik Hogertz Date: Fri, 24 Jul 2026 19:11:35 +0200 Subject: [PATCH] Add a script for automatically scaling KDE VM when resolution changes --- .../99-auto-scale-virtual.rules | 22 +++ kde-virtual-display-autoscale/README.md | 79 +++++++++++ .../auto-scale-virtual.sh | 130 ++++++++++++++++++ kde-virtual-display-autoscale/install.sh | 63 +++++++++ 4 files changed, 294 insertions(+) create mode 100644 kde-virtual-display-autoscale/99-auto-scale-virtual.rules create mode 100644 kde-virtual-display-autoscale/README.md create mode 100755 kde-virtual-display-autoscale/auto-scale-virtual.sh create mode 100755 kde-virtual-display-autoscale/install.sh diff --git a/kde-virtual-display-autoscale/99-auto-scale-virtual.rules b/kde-virtual-display-autoscale/99-auto-scale-virtual.rules new file mode 100644 index 0000000..b3f15df --- /dev/null +++ b/kde-virtual-display-autoscale/99-auto-scale-virtual.rules @@ -0,0 +1,22 @@ +# auto-scale-virtual.rules +# +# When the virtio-gpu display ("card0") reports a mode change — which +# spice-vdagent fires as it resizes Virtual-1 to match the SPICE client window +# (e.g. on dock/undock) — re-run the auto-scale script so Plasma's scale is +# fixed to match the new resolution. +# +# Install with: +# sudo install -m 644 99-auto-scale-virtual.rules \ +# /etc/udev/rules.d/99-auto-scale-virtual.rules +# sudo udevadm control --reload-rules +# +# The script is invoked as the logged-in user via systemd-run, with the Plasma +# Wayland session environment hardcoded inside the script so it can reach +# kscreen-doctor. A short debounce lives in the script itself (flock), so the +# burst of change events from a single resize collapses to one application. +# +# Adjust the --uid/--gid values to match your user (run `id -u` / `id -g`). + +ACTION=="change", SUBSYSTEM=="drm", KERNEL=="card0", \ + RUN+="/usr/bin/systemd-run --uid=1001 --gid=1001 --no-block \ + /home/hendrik/.local/bin/auto-scale-virtual.sh" diff --git a/kde-virtual-display-autoscale/README.md b/kde-virtual-display-autoscale/README.md new file mode 100644 index 0000000..0a60af5 --- /dev/null +++ b/kde-virtual-display-autoscale/README.md @@ -0,0 +1,79 @@ +# kde-virtual-display-autoscale + +Automatically switch the Plasma display scale when a QEMU/KVM guest's +virtio-gpu display is resized — e.g. when docking or undocking the host laptop. + +The SPICE guest agent (`spice-vdagent`) resizes the guest's `Virtual-1` display +to match the SPICE client window. When the laptop is docked the guest sees a +low resolution (1080p) and wants 100% scale; undocked the laptop panel is +higher-DPI and wants 200%. A udev rule fires a script on the DRM `change` event +that reads the new resolution with `kscreen-doctor` and applies the matching +scale — no polling, ~0 ms reaction, idle CPU cost of zero. + +## Requirements + +- KDE Plasma 6 on Wayland (uses `kscreen-doctor`) +- `python3` (parses `kscreen-doctor` JSON) +- A single virtio-gpu display (`Virtual-1`) driven by `spice-vdagent` + +## Install + +The easiest way is the installer, which copies the script into `~/.local/bin` +and installs the udev rule (rewriting the rule's UID/GID to match your user): + +```bash +./install.sh +``` + +It needs `sudo` for the udev-rule install and reloads the rules when done. +Re-running it is safe — it overwrites the files in place. + +### Manual install + +Copy the script into `~/.local/bin`: + +```bash +cp auto-scale-virtual.sh ~/.local/bin/ +chmod +x ~/.local/bin/auto-scale-virtual.sh +``` + +Install the udev rule (run as root). If your UID/GID is not `1001/1001`, edit +the `--uid`/`--gid` in the rule to match (run `id -u` / `id -g`): + +```bash +sudo install -m 644 99-auto-scale-virtual.rules \ + /etc/udev/rules.d/99-auto-scale-virtual.rules +sudo udevadm control --reload-rules +``` + +Make sure `~/.local/bin` is in your `PATH` (only needed for manual runs; the +udev rule calls the script by absolute path). + +## Usage + +Once installed, docking/undocking the host resizes the guest display and the +scale is applied automatically. You can also run it manually at any time: + +```bash +auto-scale-virtual.sh +``` + +## Configuration + +The script is idempotent: it only changes the scale when the current one does +not match the desired one for the current resolution, so it never fights a +manually chosen scale between events. + +Tune these variables near the top of `auto-scale-virtual.sh`: + +- `OUTPUT_NAME` — the virtio-gpu connector name (`Virtual-1` by default). +- `HIGH_DPI_MIN_HEIGHT` — the resolution height (in pixels) at or above which + the high-DPI scale is used. `1400` makes 1080p (1080) → 100% and anything + taller → 200%. +- `SCALE_HIGH` / `SCALE_LOW` — the scales to apply (default `2` / `1`). + +The udev rule pins the user UID/GID (`--uid=1001 --gid=1001`) and the script +hardcodes the Plasma Wayland session env (`/run/user/1001`, `wayland-0`, etc.) +so it can reach `kscreen-doctor` even though udev starts it with an empty +environment. Update both the rule and the script's env-fallback block if your +UID or session differs. diff --git a/kde-virtual-display-autoscale/auto-scale-virtual.sh b/kde-virtual-display-autoscale/auto-scale-virtual.sh new file mode 100755 index 0000000..4c2eea0 --- /dev/null +++ b/kde-virtual-display-autoscale/auto-scale-virtual.sh @@ -0,0 +1,130 @@ +#!/bin/bash +# +# auto-scale-virtual.sh +# +# Automatically set Plasma's display scale for the SPICE/virtio-gpu virtual +# display ("Virtual-1") based on its current resolution. +# +# This is for a QEMU/KVM guest with a virtio-gpu display. spice-vdagent resizes +# Virtual-1 to match the SPICE client window. When the host laptop is docked the +# guest sees a low resolution (e.g. 1080p) and wants 100% scale; undocked the +# laptop panel is higher-DPI and wants 200%. This script picks the right scale +# and applies it idempotently with kscreen-doctor, only acting when the scale +# actually needs to change. +# +# Triggered by a udev rule on the drm "change" event (see the accompanying +# README). Because udev runs this with a near-empty environment, the session env +# is hardcoded as defaults below (real environment values still win when the +# script is run interactively). It is also safe to run manually at any time. + +set -u + +OUTPUT_NAME="Virtual-1" # virtio-gpu connector name +# Threshold in pixels (height). >= this -> high-DPI laptop panel -> 200%. +# 1080p is 1080, so anything 1400 and up counts as the high-res laptop. +HIGH_DPI_MIN_HEIGHT=1400 +SCALE_HIGH=2 +SCALE_LOW=1 + +# --- Session env fallbacks (used when invoked by udev/systemd-run) ---------- +# Machine-specific: this guest's single Plasma Wayland session. Adjust the +# UID/path values if your setup differs. +: "${XDG_RUNTIME_DIR:=/run/user/1001}" +: "${WAYLAND_DISPLAY:=wayland-0}" +: "${DISPLAY:=:0}" +: "${XDG_CURRENT_DESKTOP:=KDE}" +: "${DBUS_SESSION_BUS_ADDRESS:=unix:path=/run/user/1001/bus}" +: "${HOME:=/home/hendrik}" +: "${PATH:=/usr/bin:/bin}" +export XDG_RUNTIME_DIR WAYLAND_DISPLAY DISPLAY XDG_CURRENT_DESKTOP \ + DBUS_SESSION_BUS_ADDRESS HOME PATH + +log() { printf '[auto-scale] %s\n' "$*" >&2; } + +# --- Debounce: rapid resizes fire several change events; only one instance +# applies the scale at a time, concurrent ones skip. --------------------- +exec 9>/tmp/auto-scale-virtual.lock +if ! flock -n 9; then + # Another instance is already handling it. + exit 0 +fi + +# --- Read the *current* scale of the target output from kscreen-doctor JSON --- +get_current_scale() { + kscreen-doctor -j 2>/dev/null \ + | sed 's/\x1b\[[0-9;]*m//g' \ + | python3 -c ' +import sys, json +try: + d = json.load(sys.stdin) +except Exception: + sys.exit(1) +name = sys.argv[1] if len(sys.argv) > 1 else "Virtual-1" +for o in d.get("outputs", []): + if o.get("name") == name: + print(o.get("scale", 1)) + break +' "$OUTPUT_NAME" +} + +# --- Current resolution of the connector (from kscreen-doctor's text output) --- +# We parse the active mode name for the matching output: "1:3456x2168@75.00*" +# -> 3456x2168. +get_current_resolution() { + kscreen-doctor -o 2>/dev/null \ + | sed 's/\x1b\[[0-9;]*m//g' \ + | awk -v out="$OUTPUT_NAME" ' + /^[[:space:]]*Output:/ { cur=0 } + $0 ~ "Output:.*"out"[[:space:]]" { cur=1 } + cur && /[0-9]+x[0-9]+@[0-9.]+\*/ { + if (match($0, /[0-9]+x[0-9]+@/, m)) { + res=m[0]; sub(/@/,"",res); print res; exit + } + } + ' +} + +# --- Decide the desired scale from the resolution height --- +desired_scale() { + local res="${1:-}" + local h="${res#*x}" # take part after "x" + h="${h%%[!0-9]*}" # strip any trailing junk + [ -z "$h" ] && { echo "$SCALE_LOW"; return; } + if [ "$h" -ge "$HIGH_DPI_MIN_HEIGHT" ]; then + echo "$SCALE_HIGH" + else + echo "$SCALE_LOW" + fi +} + +main() { + local res cur want + res="$(get_current_resolution)" + if [ -z "$res" ]; then + log "could not determine resolution; skipping" + return 0 + fi + + cur="$(get_current_scale)" + want="$(desired_scale "$res")" + + if [ -z "$cur" ]; then + log "could not read current scale; will set to $want" + cur="?" + fi + + if [ "$cur" = "$want" ]; then + # Already correct; nothing to do. + return 0 + fi + + log "Virtual-1 is ${res}; scale ${cur} -> ${want}" + if ! kscreen-doctor "output.${OUTPUT_NAME}.scale.${want}" >/dev/null 2>&1; then + log "kscreen-doctor failed to set scale" + return 1 + fi + log "scale set to ${want}" + return 0 +} + +main "$@" diff --git a/kde-virtual-display-autoscale/install.sh b/kde-virtual-display-autoscale/install.sh new file mode 100755 index 0000000..2331c19 --- /dev/null +++ b/kde-virtual-display-autoscale/install.sh @@ -0,0 +1,63 @@ +#!/bin/bash +# +# install.sh — install the KDE virtual-display auto-scaler. +# +# Copies the script into ~/.local/bin and installs the udev rule that fires it +# on the DRM "change" event (the resize that spice-vdagent performs on +# dock/undock). Re-running it is safe: it overwrites the files in place. +# +# Requires sudo for the udev-rule install. + +set -eu + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +SCRIPT_NAME="auto-scale-virtual.sh" +RULE_NAME="99-auto-scale-virtual.rules" +BIN_DIR="${HOME}/.local/bin" +RULE_DIR="/etc/udev/rules.d" + +# --- sanity: we're next to the files we install ----------------------------- +if [ ! -f "${SCRIPT_DIR}/${SCRIPT_NAME}" ] || [ ! -f "${SCRIPT_DIR}/${RULE_NAME}" ]; then + echo "install.sh must sit next to ${SCRIPT_NAME} and ${RULE_NAME}." >&2 + exit 1 +fi + +# --- the udev rule pins the user's UID/GID; patch it to match $UID ----------- +# Keeps the repo version generic while installing a working rule for the +# current user. Falls back to 1001 if id is unavailable (matches the default +# baked into the shipped rule). +UID_NUM="${UID:-$(id -u 2>/dev/null || echo 1001)}" +GID_NUM="$(id -g 2>/dev/null || echo 1001)" + +# --- 1) the script into ~/.local/bin ---------------------------------------- +mkdir -p "${BIN_DIR}" +install -m 755 "${SCRIPT_DIR}/${SCRIPT_NAME}" "${BIN_DIR}/${SCRIPT_NAME}" +echo "installed ${SCRIPT_NAME} -> ${BIN_DIR}/${SCRIPT_NAME}" + +# --- 2) the udev rule, rewritten for the current user, then installed ------- +TMP_RULE="$(mktemp)" +trap 'rm -f "${TMP_RULE}"' EXIT +sed -E "s/--uid=[0-9]+/--uid=${UID_NUM}/; s/--gid=[0-9]+/--gid=${GID_NUM}/" \ + "${SCRIPT_DIR}/${RULE_NAME}" > "${TMP_RULE}" + +if [ "${EUID}" -eq 0 ]; then + install -m 644 "${TMP_RULE}" "${RULE_DIR}/${RULE_NAME}" + udevadm control --reload-rules +else + if command -v sudo >/dev/null 2>&1; then + install_sudo() { sudo install -m 644 "$@"; } + sudo udevadm control --reload-rules + else + echo "Need root to install the udev rule to ${RULE_DIR}." >&2 + echo "The rule has been generated at: ${TMP_RULE}" >&2 + echo "Run: sudo install -m 644 ${TMP_RULE} ${RULE_DIR}/${RULE_NAME} && sudo udevadm control --reload-rules" >&2 + exit 1 + fi + install_sudo "${TMP_RULE}" "${RULE_DIR}/${RULE_NAME}" +fi +echo "installed ${RULE_NAME} -> ${RULE_DIR}/${RULE_NAME}" +echo "udev rules reloaded" + +echo +echo "Done. Dock/undock (or resize the SPICE client) and the scale is applied" +echo "automatically. Run ${SCRIPT_NAME} manually at any time to fix the scale."