fix(desktop): address KDE feedback and keep local builds in sync with CI (#488)

This commit is contained in:
Kurt Himebauch authored and GitHub committed 2026-10-09 21:35:37 +00:00
1 parent c761b83112
commit d99ed8e00b
41 files changed
+1252 -191

No files matched your search

@@ -1,13 +1,114 @@
#!/usr/bin/env python3
"""Expose the selected secondary library in PCManFM's Places sidebar."""
"""Expose available Steam libraries in Dolphin, retaining the old PCManFM bookmark."""
import hashlib
import json
import os
from pathlib import Path
import re
import runpy
import sys
import tempfile
from urllib.parse import unquote, urlsplit
import xml.etree.ElementTree as ET
LIBRARY = Path("/mnt/droiddeck-sd")
URI = "file:///mnt/droiddeck-sd"
KDE_OWNER = "http://www.kde.org"
MARK = "DroidDeckSteamLibrary"
ICON_NS = "http://www.freedesktop.org/standards/desktop-bookmarks"
ET.register_namespace("bookmark", ICON_NS)
def steam_libraries(home, data):
steam = data / "Steam"
libraries = {steam: "Internal Storage"}
listing = os.environ.get("BL_STEAM_LIBRARIES")
selected = None
if listing:
try:
selected = {Path(e["path"]): str(e["label"]) for e in json.loads(Path(listing).read_text())}
except (OSError, ValueError, KeyError, TypeError):
pass # Fall back to the client's registered libraries if the app's list is unreadable.
vdf = steam / "steamapps/libraryfolders.vdf"
if vdf.is_file():
parser = runpy.run_path(str(Path(__file__).with_name("droiddeck-steam-ui-scale")))
folders = parser["parse"](vdf.read_text()).get("libraryfolders")
if not isinstance(folders, parser["Block"]):
raise ValueError("missing libraryfolders")
for _, entry in folders.pairs:
if not isinstance(entry, parser["Block"]):
continue
path = entry.get("path")
if not isinstance(path, str):
continue
path = Path(re.sub(r'\\(["\\])', r'\1', path))
managed = path == LIBRARY or path.is_relative_to(home / "Games")
if selected is not None and managed and path not in selected:
continue
if path == LIBRARY and selected is None and not os.environ.get("BL_LIBRARY_LABEL"):
continue
label = entry.get("label")
label = re.sub(r'\\(["\\])', r'\1', label) if isinstance(label, str) else ""
libraries[path] = label or path.name
if selected is not None:
libraries.update(selected)
elif os.environ.get("BL_LIBRARY_LABEL"):
libraries[LIBRARY] = os.environ["BL_LIBRARY_LABEL"]
libraries[steam] = "Internal Storage"
return {path.as_uri(): "Steam (" + (" ".join(label.split()) or path.name) + ")"
for path, label in libraries.items() if path.is_absolute() and (path / "steamapps").is_dir()}
def place_uri(uri):
url = urlsplit(uri or "")
if url.scheme == "file" and url.netloc in ("", "localhost") and url.path.startswith("/"):
return Path(unquote(url.path)).as_uri()
return uri
def update_places(path, libraries):
if path.is_file():
parser = ET.XMLParser(target=ET.TreeBuilder(insert_comments=True, insert_pis=True))
root = ET.fromstring(path.read_bytes(), parser=parser)
if root.tag != "xbel":
raise ValueError("invalid Dolphin places file")
else:
if not libraries:
return
# Leave KDE's file version unset so it still adds its normal Home/Downloads/etc. places.
root = ET.Element("xbel", {"version": "1.0"})
before = ET.tostring(root)
seen = set()
personal = {place_uri(b.get("href")) for b in root.findall("bookmark")
if b.find("info/metadata[@owner='" + KDE_OWNER + "']/" + MARK) is None}
for bookmark in root.findall("bookmark"):
metadata = bookmark.find("info/metadata[@owner='" + KDE_OWNER + "']")
if metadata is None or metadata.find(MARK) is None:
continue
uri = place_uri(bookmark.get("href"))
if uri not in libraries or uri in seen or uri in personal:
root.remove(bookmark)
continue
seen.add(uri)
title = bookmark.find("title")
if title is None:
title = ET.SubElement(bookmark, "title")
title.text = libraries[uri]
for uri, label in libraries.items():
if uri in seen or uri in personal:
continue
bookmark = ET.SubElement(root, "bookmark", {"href": uri})
ET.SubElement(bookmark, "title").text = label
info = ET.SubElement(bookmark, "info")
icon = ET.SubElement(info, "metadata", {"owner": "http://freedesktop.org"})
ET.SubElement(icon, "{" + ICON_NS + "}icon", {"name": "steam"})
metadata = ET.SubElement(info, "metadata", {"owner": KDE_OWNER})
ET.SubElement(metadata, "ID").text = "droiddeck-steam-" + hashlib.sha256(uri.encode()).hexdigest()[:16]
ET.SubElement(metadata, MARK).text = "true"
ET.SubElement(metadata, "isSystemItem").text = "false"
if ET.tostring(root) != before:
atomic_write(path, ET.tostring(root, encoding="unicode", xml_declaration=True))
def bookmarks_file(home, config):
@@ -31,6 +132,10 @@ def update_bookmark(path, label):
content += URI + " " + label + "\n"
if content == original:
return
atomic_write(path, content)
def atomic_write(path, content):
path.parent.mkdir(parents=True, exist_ok=True)
temporary = None
try:
@@ -51,10 +156,12 @@ def main():
# An unbound mount-point directory may remain from a previous session.
available = bool(label) and (LIBRARY / "steamapps").is_dir()
update_bookmark(bookmarks_file(home, config), label if available else None)
data = Path(os.environ.get("XDG_DATA_HOME") or home / ".local/share")
update_places(data / "user-places.xbel", steam_libraries(home, data))
if __name__ == "__main__":
try:
main()
except OSError as error:
except (OSError, ValueError, ET.ParseError) as error:
print("== desktop library bookmark: " + str(error), file=sys.stderr)
@@ -0,0 +1,11 @@
#!/bin/bash
# Plasma starts this after its nested Xwayland display is available. The session launcher still
# sees the outer compositor before startplasma, so starting its X11 helper there cannot work.
[ -n "${BL_ANDROID_CLIPBOARD:-}" ] && [ -n "${DISPLAY:-}" ] || exit 0
# The native helper dies with its parent. Keep this shell until it exits: Plasma's autostart
# launcher may itself exit immediately after starting us.
/usr/local/bin/droiddeck-clipboard "$BL_ANDROID_CLIPBOARD" &
child=$!
trap 'kill "$child" 2>/dev/null' EXIT
trap 'exit 0' TERM INT
wait "$child"
@@ -0,0 +1,30 @@
#!/bin/bash
# Port the old desktop's melonDS window rule once; later window rules belong to the user.
set -euo pipefail
config=${XDG_CONFIG_HOME:-$HOME/.config}
marker=$config/droiddeck-window-rules-v1
[ ! -e "$marker" ] || exit 0
rules=$(kreadconfig6 --file kwinrulesrc --group General --key rules)
IFS=, read -ra groups <<< "$rules"
for group in "${groups[@]}"; do
title=$(kreadconfig6 --file kwinrulesrc --group "$group" --key title)
wmclass=$(kreadconfig6 --file kwinrulesrc --group "$group" --key wmclass)
case ${title,,}${wmclass,,} in
*melonds*) mkdir -p "$config"; touch "$marker"; exit 0 ;;
esac
done
write() { kwriteconfig6 --file kwinrulesrc --group droiddeck-melonds --key "$1" "$2"; }
write Description 'melonDS desktop window'
write title '^melonDS.*'
write titlematch 3
write types 1
write size 800,600
write sizerule 3
write placement Centered
write placementrule 2
write ignoregeometry true
write ignoregeometryrule 3
kwriteconfig6 --file kwinrulesrc --group General --key rules "${rules:+$rules,}droiddeck-melonds"
kwriteconfig6 --file kwinrulesrc --group General --key count "$(( ${#groups[@]} + 1 ))"
mkdir -p "$config"
touch "$marker"
+60
View File
@@ -0,0 +1,60 @@
#!/usr/bin/python3
"""Let GTK draw close buttons inside gamescope, which supplies no window decorations."""
import ctypes as c
import os
import signal
import subprocess
import sys
def advertise_compositing():
# This is gamescope's private X server: it composites alpha buffers already, but GTK also
# requires the compositing-manager selection and frame-extents hint before enabling CSD.
x = c.CDLL('libX11.so.6')
display_type, window_type = c.c_void_p, c.c_ulong
x.XOpenDisplay.argtypes = [c.c_char_p]
x.XOpenDisplay.restype = display_type
display = x.XOpenDisplay(None)
if not display:
raise RuntimeError('no X display')
x.XDefaultRootWindow.argtypes = [display_type]
x.XDefaultRootWindow.restype = window_type
x.XDefaultScreen.argtypes = [display_type]
x.XDefaultScreen.restype = c.c_int
root = x.XDefaultRootWindow(display)
x.XInternAtom.argtypes = [display_type, c.c_char_p, c.c_int]
x.XInternAtom.restype = window_type
atom = lambda name: x.XInternAtom(display, name.encode(), False)
manager = atom('_NET_WM_CM_S%d' % x.XDefaultScreen(display))
x.XGetSelectionOwner.argtypes = [display_type, window_type]
x.XGetSelectionOwner.restype = window_type
if not x.XGetSelectionOwner(display, manager):
x.XCreateSimpleWindow.argtypes = [display_type, window_type, c.c_int, c.c_int,
c.c_uint, c.c_uint, c.c_uint, window_type, window_type]
x.XCreateSimpleWindow.restype = window_type
owner = x.XCreateSimpleWindow(display, root, 0, 0, 1, 1, 0, 0, 0)
x.XSetSelectionOwner.argtypes = [display_type, window_type, window_type, window_type]
x.XSetSelectionOwner(display, manager, owner, 0)
x.XChangeProperty.argtypes = [display_type, window_type, window_type, window_type,
c.c_int, c.c_int, c.c_void_p, c.c_int]
extents = window_type(atom('_GTK_FRAME_EXTENTS'))
x.XChangeProperty(display, root, atom('_NET_SUPPORTED'), atom('ATOM'), 32, 2, c.byref(extents), 1)
x.XSync.argtypes = [display_type, c.c_int]
x.XSync(display, False)
# Keep the selection's connection alive until the program exits.
return x, display
if __name__ == '__main__':
if len(sys.argv) < 2:
raise SystemExit('usage: droiddeck-gpu-window <program> [args...]')
os.environ.setdefault('GTK_CSD', '1')
try:
connection = advertise_compositing()
except (OSError, RuntimeError):
os.execvp(sys.argv[1], sys.argv[1:])
child = subprocess.Popen(sys.argv[1:])
for sig in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP):
signal.signal(sig, lambda number, frame: child.send_signal(number))
status = child.wait()
raise SystemExit(status if status >= 0 else 128 - status)
@@ -214,7 +214,9 @@ if [ -z "${BL_INSIDE:-}" ]; then
elif [ "${BL_REFRESH:-0}" -gt 0 ]; then
args+=(-r "$BL_REFRESH")
fi
[ "$mode" = steam ] && args+=(-e)
# Steam integration advertises a Deck session and makes the client select Big Picture even
# without -gamepadui. The desktop UI uses ordinary gamescope window management instead.
[ "$mode" = steam ] && [ "${BL_STEAM_UI:-}" != desktop ] && args+=(-e)
# Two Xwayland servers, as SteamOS runs Steam: the client on the first, games on the second
# (STEAM_GAME_DISPLAY_0). The client then sizes the games' server to each game's Game Resolution
# (GAMESCOPE_XWAYLAND_MODE_CONTROL; native unless one is set), and gamescope scales it to the
@@ -886,10 +888,19 @@ BUSCONF
droiddeck-steam-language "$HOME" "$BL_STEAM_LANGUAGE" || true
fi
step "starting the Steam client${BL_STEAM_UI:+ ($BL_STEAM_UI UI)}"
desktop_ui_pid=
if [ "${BL_STEAM_UI:-}" = desktop ]; then
/usr/local/bin/droiddeck-steam-desktop-ui &
desktop_ui_pid=$!
fi
"$steam_root/steamrtarm64/steam" "${_bl_ui[@]}" "${_bl_cdp[@]}" "${_bl_lang[@]}" -clientbeta "$steam_channel" \
-no-cef-sandbox -cef-force-gpu -cef-ozone-platform=x11 \
-cef-use-gl=angle -cef-use-angle=vulkan "$@"
rc=$?
if [ -n "$desktop_ui_pid" ]; then
kill "$desktop_ui_pid" 2>/dev/null || true
wait "$desktop_ui_pid" 2>/dev/null || true
fi
echo "== steam exited rc=$rc"
if [ -n "${BL_ADDED_GAMES:-}" ] && [ -f "$BL_ADDED_GAMES" ]; then
droiddeck-steam-shortcuts "$steam_root" "$BL_ADDED_GAMES" || true
@@ -0,0 +1,33 @@
#!/usr/bin/python3
"""Honor a desktop launch even when Steam remembers Big Picture from its last session."""
import os
from pathlib import Path
import runpy
import time
def select_desktop(evaluate, timeout=90):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
result = evaluate("typeof SteamClient !== 'undefined' && "
"typeof SteamClient.UI.ExitBigPictureMode === 'function' && "
"(SteamClient.UI.ExitBigPictureMode(), true)")
if result.get('value') is True:
return True
except Exception:
# CEF and SharedJSContext are not ready during the client's initial startup/update.
pass
time.sleep(1)
return False
if __name__ == '__main__':
base = os.environ.get('BL_LAUNCH_DIR')
if not base:
raise SystemExit('BL_LAUNCH_DIR is not set')
agent = runpy.run_path('/usr/local/bin/droiddeck-agent')
selected = select_desktop(lambda expression: agent['cdp_eval'](
Path(base) / 'agent', expression, timeout=2))
print('== steam: desktop UI selected' if selected else
'== steam: desktop UI was not ready within 90 seconds', flush=True)