mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-19 12:56:06 +00:00
Merge upstream shortcuts and dual-screen session updates
Preserve profile bindings, shared held-input ownership and custom panels alongside upstream physical shortcuts, mouse routing and docked menus. Add integration regressions and record the full 2,918-test JVM run.
This commit is contained in:
commit
d6b4b0589b
630 files changed
+42269
-1875
No files matched your search
@@ -24,7 +24,8 @@ java_dir="${JAVA_HOME:-/opt/homebrew/opt/openjdk@17/libexec/openjdk.jdk/Contents
|
||||
[[ -x "$java_dir/bin/java" ]] || java_dir="${HOME}/.local/share/mise/installs/java/temurin-17"
|
||||
[[ "$java_dir" == */homebrew/* ]] && echo "using homebrew java path: $java_dir"
|
||||
[[ "$java_dir" == */mise/* ]] && echo "using mise java path: $java_dir"
|
||||
image_name=${DROIDDECK_BUILD_IMAGE:-droiddeck-local-cross:24.04-v3}
|
||||
. "${repo_root}/tools/docker_platform.sh"
|
||||
image_name=${DROIDDECK_BUILD_IMAGE}
|
||||
build_variant=${DROIDDECK_BUILD_VARIANT:-release}
|
||||
case "$build_variant" in
|
||||
debug) gradle_task=assembleDebug ;;
|
||||
@@ -113,7 +114,7 @@ image_id=$(docker image inspect --format '{{.Id}}' "${image_name}")
|
||||
rm -rf -- "${linuxfs_dir}"
|
||||
mkdir -p "${linuxfs_dir}"
|
||||
|
||||
docker run --rm --platform linux/amd64 \
|
||||
docker run --rm --platform "${docker_platform}" \
|
||||
--user "$(id -u):$(id -g)" \
|
||||
-v "${repo_root}:/src" -w /src "${image_name}" bash -lc '
|
||||
set -euo pipefail
|
||||
@@ -221,7 +222,7 @@ fi
|
||||
|
||||
. "${repo_root}/tools/linuxfs/uruntime.env"
|
||||
uruntime_binary=$(cached "${URUNTIME_SHA256}" "${URUNTIME_ASSET}" \
|
||||
bash -c 'curl -fsSL --retry 3 -o "$out" "$0"' "https://github.com/VHSgunzo/uruntime/releases/download/${URUNTIME_VERSION}/${URUNTIME_ASSET}")
|
||||
bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "https://github.com/VHSgunzo/uruntime/releases/download/${URUNTIME_VERSION}/${URUNTIME_ASSET}")
|
||||
mkdir -p "${linuxfs_dir}/usr/local/lib/droiddeck" "${linuxfs_dir}/usr/local/share/licenses/uruntime"
|
||||
install -m644 "${uruntime_binary}" "${linuxfs_dir}/usr/local/lib/droiddeck/uruntime"
|
||||
install -m644 "${repo_root}/tools/linuxfs/licenses/uruntime-LICENSE" "${linuxfs_dir}/usr/local/share/licenses/uruntime/LICENSE"
|
||||
@@ -256,7 +257,7 @@ mkdir -p "${msi_pkgs}" "${msi_dir}"
|
||||
while read -r package_sha256 package_url; do
|
||||
[[ -n "${package_url}" ]] || continue
|
||||
package_archive=$(cached "${package_sha256}" "$(basename "${package_url}")" \
|
||||
bash -c 'curl -fsSL --retry 3 -o "$out" "$0"' "${package_url}")
|
||||
bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "${package_url}")
|
||||
tar -xJf "${package_archive}" -C "${msi_pkgs}"
|
||||
done < <(grep -v '^#' "${repo_root}/tools/msitools/packages.txt")
|
||||
for tool in msiinfo cabextract; do install -m644 "${msi_pkgs}/usr/bin/${tool}" "${msi_dir}/${tool}"; done
|
||||
@@ -276,14 +277,14 @@ mkdir -p "${mango_dir}" "${mango_pkgs}"
|
||||
while read -r package_sha256 package_url; do
|
||||
[[ -n "${package_url}" ]] || continue
|
||||
package_archive=$(cached "${package_sha256}" "$(basename "${package_url}")" \
|
||||
bash -c 'curl -fsSL --retry 3 -o "$out" "$0"' "${package_url}")
|
||||
bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "${package_url}")
|
||||
zstd -dc "${package_archive}" | tar -xf - -C "${mango_pkgs}"
|
||||
done < <(grep -v '^#' "${repo_root}/tools/mangoapp/packages.txt")
|
||||
install -m644 "${mango_pkgs}/usr/bin/mangoapp" "${mango_dir}/mangoapp"
|
||||
for library in libfmt.so.10 libspdlog.so.1.13 libglfw.so.3 libtraceevent.so.1; do
|
||||
cp -L "${mango_pkgs}/usr/lib/${library}" "${mango_dir}/${library}"
|
||||
done
|
||||
docker run --rm --platform linux/amd64 --user "$(id -u):$(id -g)" -v "${repo_root}:/src" -w /src "${image_name}" \
|
||||
docker run --rm --platform "${docker_platform}" --user "$(id -u):$(id -g)" -v "${repo_root}:/src" -w /src "${image_name}" \
|
||||
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -Wl,-soname,libtracefs.so.1 \
|
||||
-o app/src/main/assets/linuxfs/usr/local/lib/mangoapp/libtracefs.so.1 tools/mangoapp/libtracefs-shim.c
|
||||
mkdir -p "${linuxfs_dir}/usr/local/bin"
|
||||
@@ -294,7 +295,7 @@ mkdir -p "${pw_pkgs}"
|
||||
while read -r package_sha256 package_url; do
|
||||
[[ -n "${package_url}" ]] || continue
|
||||
package_archive=$(cached "${package_sha256}" "$(basename "${package_url}")" \
|
||||
bash -c 'curl -fsSL --retry 3 -o "$out" "$0"' "${package_url}")
|
||||
bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "${package_url}")
|
||||
zstd -dc "${package_archive}" | tar -xf - -C "${pw_pkgs}"
|
||||
done < <(grep -v '^#' "${repo_root}/tools/pipewire/packages.txt")
|
||||
"${repo_root}/tools/pipewire/assemble.sh" "${pw_pkgs}" "${linuxfs_dir}/usr/local/lib/droiddeck-pipewire.tzst"
|
||||
@@ -303,7 +304,7 @@ pa_source=${DROIDDECK_PA13_SOURCE_DIR:-"${staging_dir}/pulseaudio-13.0"}
|
||||
if [[ -z "${DROIDDECK_PA13_SOURCE_DIR:-}" ]]; then
|
||||
pa_tarball="${cache_dir}/pulseaudio-13.0.tar.gz"
|
||||
if [[ ! -s "${pa_tarball}" ]] || ! tar -tzf "${pa_tarball}" >/dev/null 2>&1; then
|
||||
curl -fsSL -o "${pa_tarball}.part" \
|
||||
curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "${pa_tarball}.part" \
|
||||
https://github.com/pulseaudio/pulseaudio/archive/refs/tags/v13.0.tar.gz
|
||||
mv "${pa_tarball}.part" "${pa_tarball}"
|
||||
fi
|
||||
|
||||
Executable
+32
@@ -0,0 +1,32 @@
|
||||
#!/usr/bin/env bash
|
||||
set -uo pipefail
|
||||
cd "$(dirname "$0")/../.."
|
||||
groups=${PYTHON_TEST_GROUPS:-3}
|
||||
work=$(mktemp -d)
|
||||
trap 'rm -rf "$work"' EXIT
|
||||
index=0
|
||||
while read -r file; do
|
||||
module=$(basename "$file" .py)
|
||||
echo "$module" >> "$work/group-$((index % groups)).list"
|
||||
index=$((index + 1))
|
||||
done < <(ls -S tools/tests/test_*.py)
|
||||
pids=()
|
||||
for list in "$work"/group-*.list; do
|
||||
(
|
||||
PYTHONPATH=tools/tests python3 -m unittest $(cat "$list") > "${list%.list}.log" 2>&1
|
||||
echo $? > "${list%.list}.status"
|
||||
) &
|
||||
pids+=($!)
|
||||
done
|
||||
wait "${pids[@]}"
|
||||
failed=0
|
||||
for list in "$work"/group-*.list; do
|
||||
echo "::group::$(basename "$list"): $(tr '\n' ' ' < "$list" | cut -c1-120)"
|
||||
cat "${list%.list}.log"
|
||||
echo "::endgroup::"
|
||||
if [ "$(cat "${list%.list}.status")" != 0 ]; then
|
||||
failed=1
|
||||
echo "::error::$(basename "$list") failed"
|
||||
fi
|
||||
done
|
||||
exit "$failed"
|
||||
@@ -1,14 +1,19 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
repo=$(cd "$(dirname "$0")/../.." && pwd)
|
||||
image=${DROIDDECK_BUILD_IMAGE:-droiddeck-local-cross:24.04-v3}
|
||||
docker run --rm --platform linux/amd64 -v "$repo:/src" \
|
||||
-v "${HOME}/.cache/droiddeck-comet-rust:/rust" -w /src \
|
||||
. "$repo/tools/docker_platform.sh"
|
||||
image=${DROIDDECK_BUILD_IMAGE}
|
||||
platform=${DROIDDECK_DOCKER_PLATFORM}
|
||||
rust_cache="${HOME}/.cache/droiddeck-comet-rust${platform#linux/amd64}"
|
||||
rust_cache=${rust_cache/\/arm64/-arm64}
|
||||
docker run --rm --platform "$platform" -v "$repo:/src" \
|
||||
-v "${rust_cache}:/rust" -w /src \
|
||||
-e CARGO_HOME=/rust/cargo -e RUSTUP_HOME=/rust/rustup "$image" bash -lc '
|
||||
set -euo pipefail
|
||||
trap "chown -R '"$(id -u):$(id -g)"' app/build/comet app/src/main/assets/linuxfs/usr/local/lib/droiddeck-comet /rust 2>/dev/null || true" EXIT
|
||||
apt-get update -qq
|
||||
apt-get install -y -qq curl git unzip ca-certificates pkg-config >/dev/null
|
||||
git config --global --add safe.directory "*"
|
||||
export PATH=/rust/cargo/bin:$PATH
|
||||
if ! command -v cargo >/dev/null; then
|
||||
curl -fsSL https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain 1.90.0
|
||||
|
||||
@@ -16,7 +16,7 @@ cargo build --locked --release --target aarch64-unknown-linux-gnu
|
||||
install -m644 target/aarch64-unknown-linux-gnu/release/comet "$out/comet"
|
||||
zip="$cache/dummy-service.zip"
|
||||
if ! echo "7fc5facd1fce4d516cd3ce527e7e4dbe0bfd17649cea805e8ea7c37d4ba58d9a $zip" | sha256sum -c - >/dev/null 2>&1; then
|
||||
curl -fsSL --retry 3 -o "$zip" https://github.com/imLinguin/comet/releases/download/v0.3.2/dummy-service.zip
|
||||
curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$zip" https://github.com/imLinguin/comet/releases/download/v0.3.2/dummy-service.zip
|
||||
fi
|
||||
echo "7fc5facd1fce4d516cd3ce527e7e4dbe0bfd17649cea805e8ea7c37d4ba58d9a $zip" | sha256sum -c -
|
||||
unzip -o "$zip" GalaxyCommunication.exe update-permissions.exe -d "$out"
|
||||
|
||||
@@ -3,12 +3,12 @@ set -euo pipefail
|
||||
if [ -f tools/droiddeck-esync/release.env ]; then
|
||||
. tools/droiddeck-esync/release.env
|
||||
release_url="https://github.com/${SYNC_BUNDLE_REPO}/releases/download/${SYNC_BUNDLE_TAG}"
|
||||
curl -fsSL --retry 3 -o sync-bundle.tzst "$release_url/$SYNC_BUNDLE_ASSET"
|
||||
curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o sync-bundle.tzst "$release_url/$SYNC_BUNDLE_ASSET"
|
||||
echo "$SYNC_BUNDLE_SHA256 sync-bundle.tzst" | sha256sum -c -
|
||||
mkdir -p app/src/main/assets/droiddeck-esync
|
||||
tar --use-compress-program=unzstd -xf sync-bundle.tzst -C app/src/main/assets/droiddeck-esync
|
||||
rm sync-bundle.tzst
|
||||
curl -fsSL --retry 3 -o sync-index.json "$release_url/index.json"
|
||||
curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o sync-index.json "$release_url/index.json"
|
||||
revoked=$(python3 -c 'import json, sys; print(" ".join(p["id"] for p in json.load(open(sys.argv[1]))["packs"] if p.get("revoked") is True))' sync-index.json)
|
||||
for id in $revoked; do
|
||||
if [ -e "app/src/main/assets/droiddeck-esync/packs/$id.tzst" ]; then
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
curl -fsSL --retry 3 -o pa.tar.gz "$COMPONENT_SOURCE_URL"
|
||||
curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o pa.tar.gz "$COMPONENT_SOURCE_URL"
|
||||
echo "$COMPONENT_SOURCE_SHA256 pa.tar.gz" | sha256sum -c -
|
||||
mkdir -p pa13 && tar -xzf pa.tar.gz -C pa13 --strip-components=1 && rm pa.tar.gz
|
||||
@@ -12,14 +12,14 @@ for f in tools/linuxfs/overlay/usr/bin/* tools/linuxfs/overlay/usr/bin/steamos-p
|
||||
done
|
||||
if [ -f tools/gamescope/release.env ]; then
|
||||
. tools/gamescope/release.env
|
||||
curl -fsSL --retry 3 -o gamescope.tzst "https://github.com/${GAMESCOPE_REPO:-${GITHUB_REPOSITORY}}/releases/download/${GAMESCOPE_TAG}/gamescope.tzst"
|
||||
curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o gamescope.tzst "https://github.com/${GAMESCOPE_REPO:-${GITHUB_REPOSITORY}}/releases/download/${GAMESCOPE_TAG}/gamescope.tzst"
|
||||
echo "${GAMESCOPE_SHA256} gamescope.tzst" | sha256sum -c -
|
||||
tar --use-compress-program=unzstd -xf gamescope.tzst -C "$D"
|
||||
test -f "$D/usr/local/bin/gamescope"
|
||||
rm gamescope.tzst
|
||||
fi
|
||||
. tools/linuxfs/uruntime.env
|
||||
curl -fsSL --retry 3 -o uruntime "https://github.com/VHSgunzo/uruntime/releases/download/${URUNTIME_VERSION}/${URUNTIME_ASSET}"
|
||||
curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o uruntime "https://github.com/VHSgunzo/uruntime/releases/download/${URUNTIME_VERSION}/${URUNTIME_ASSET}"
|
||||
echo "${URUNTIME_SHA256} uruntime" | sha256sum -c -
|
||||
install -Dm644 uruntime "$D/usr/local/lib/droiddeck/uruntime"
|
||||
install -Dm644 tools/linuxfs/licenses/uruntime-LICENSE "$D/usr/local/share/licenses/uruntime/LICENSE"
|
||||
@@ -28,7 +28,7 @@ M="$D/usr/local/lib/mangoapp"
|
||||
mkdir -p "$M" mango-pkgs
|
||||
grep -v '^#' tools/mangoapp/packages.txt | while read -r sum url; do
|
||||
[ -n "$url" ] || continue
|
||||
curl -fsSL --retry 3 -o mango-pkgs/pkg.tar.zst "$url"
|
||||
curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o mango-pkgs/pkg.tar.zst "$url"
|
||||
echo "$sum mango-pkgs/pkg.tar.zst" | sha256sum -c -
|
||||
tar --use-compress-program=unzstd -xf mango-pkgs/pkg.tar.zst -C mango-pkgs
|
||||
rm mango-pkgs/pkg.tar.zst
|
||||
@@ -46,7 +46,7 @@ ls -l "$M"
|
||||
mkdir -p pw-pkgs
|
||||
grep -v '^#' tools/pipewire/packages.txt | while read -r sum url; do
|
||||
[ -n "$url" ] || continue
|
||||
curl -fsSL --retry 3 -o pw-pkgs/pkg.tar.zst "$url"
|
||||
curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o pw-pkgs/pkg.tar.zst "$url"
|
||||
echo "$sum pw-pkgs/pkg.tar.zst" | sha256sum -c -
|
||||
tar --use-compress-program=unzstd -xf pw-pkgs/pkg.tar.zst -C pw-pkgs
|
||||
rm pw-pkgs/pkg.tar.zst
|
||||
@@ -58,7 +58,7 @@ T="$D/usr/local/lib/droiddeck-msitools"
|
||||
mkdir -p "$T" msi-pkgs
|
||||
grep -v '^#' tools/msitools/packages.txt | while read -r sum url; do
|
||||
[ -n "$url" ] || continue
|
||||
curl -fsSL --retry 3 -o msi-pkgs/pkg.tar.xz "$url"
|
||||
curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o msi-pkgs/pkg.tar.xz "$url"
|
||||
echo "$sum msi-pkgs/pkg.tar.xz" | sha256sum -c -
|
||||
tar -xJf msi-pkgs/pkg.tar.xz -C msi-pkgs
|
||||
rm msi-pkgs/pkg.tar.xz
|
||||
|
||||
@@ -0,0 +1,330 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Deploy session-helper changes by grafting them into the latest main CI APK.
|
||||
|
||||
Downloads the newest release-signed main build from DroidDeck-CI that this checkout
|
||||
descends from, replaces the helper assets whose sources differ from that build, re-signs
|
||||
the result with the local release signer and optionally installs it. Any other change
|
||||
(Kotlin, resources, native code, runtime components, deletions) stops the run so a full
|
||||
build covers it.
|
||||
"""
|
||||
import argparse
|
||||
import copy
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from zipfile import ZipFile
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tools/release'))
|
||||
from check_session_assets import source_assets
|
||||
|
||||
CI_REPO = 'Droid-Deck/DroidDeck-CI'
|
||||
CACHE = Path.home() / '.cache/droiddeck-donors'
|
||||
IGNORED_PREFIXES = ('docs/', '.github/', 'tools/tests/', 'tools/ci/')
|
||||
IGNORED_FILES = {'.gitignore', 'LICENSE', 'tools/deploy_fast.py'}
|
||||
SIGNATURE_SUFFIXES = ('.SF', '.RSA', '.DSA', '.EC')
|
||||
SIGNER = Path(os.environ.get('LOCALAPPDATA', '')) / 'DroidDeckSigning/Sign-DroidDeckApk.ps1'
|
||||
PWSH_FALLBACK = Path.home() / '.cache/codex-runtimes/codex-primary-runtime/dependencies/native/powershell/pwsh.exe'
|
||||
|
||||
|
||||
class Refused(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def run_bounded(command, timeout, **options):
|
||||
try:
|
||||
return subprocess.run(command, timeout=timeout, **options)
|
||||
except subprocess.TimeoutExpired:
|
||||
raise Refused(' '.join(map(str, command[:4])) + ' timed out')
|
||||
|
||||
|
||||
def git(*args, check=True):
|
||||
result = run_bounded(['git', '-C', str(ROOT), *args], 300, capture_output=True, check=False)
|
||||
if check and result.returncode:
|
||||
raise Refused('git ' + ' '.join(args) + ' failed: ' + result.stderr.decode(errors='replace').strip())
|
||||
return result.stdout
|
||||
|
||||
|
||||
def digest(path):
|
||||
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def is_ignored(path):
|
||||
return path in IGNORED_FILES or path.endswith('.md') or path.startswith(IGNORED_PREFIXES)
|
||||
|
||||
|
||||
def graft_targets():
|
||||
return {source.relative_to(ROOT).as_posix(): asset for source, asset in source_assets().items()}
|
||||
|
||||
|
||||
def changed_paths(donor_commit):
|
||||
"""Return {path: status} for the checkout, uncommitted and untracked files included."""
|
||||
changes = {}
|
||||
fields = git('diff', '--name-status', '-z', '--no-renames', donor_commit).decode().split('\0')
|
||||
for status, path in zip(fields[0::2], fields[1::2]):
|
||||
changes[path] = status
|
||||
for path in filter(None, git('ls-files', '-z', '-o', '--exclude-standard').decode().split('\0')):
|
||||
changes[path] = 'A'
|
||||
return changes
|
||||
|
||||
|
||||
def classify(changes, targets, donor_entries):
|
||||
"""Split changes into grafts {path: asset}, ignored paths and blockers {path: reason}."""
|
||||
grafts, ignored, blocked = {}, [], {}
|
||||
for path, status in sorted(changes.items()):
|
||||
if is_ignored(path):
|
||||
ignored.append(path)
|
||||
elif path not in targets:
|
||||
blocked[path] = 'not a graftable session helper'
|
||||
elif status == 'D':
|
||||
blocked[path] = 'deleted helper'
|
||||
elif targets[path] not in donor_entries:
|
||||
blocked[path] = 'new helper the donor APK does not carry'
|
||||
else:
|
||||
grafts[path] = targets[path]
|
||||
return grafts, ignored, blocked
|
||||
|
||||
|
||||
def helper_bytes(path):
|
||||
data = (ROOT / path).read_bytes()
|
||||
return data if b'\0' in data else data.replace(b'\r\n', b'\n')
|
||||
|
||||
|
||||
def graft(donor, replacements, output):
|
||||
"""Copy the donor with entries replaced, dropping its signature so it can be re-signed."""
|
||||
with ZipFile(donor) as source, ZipFile(output, 'w') as target:
|
||||
for info in source.infolist():
|
||||
name = info.filename
|
||||
if name.startswith('META-INF/') and (name == 'META-INF/MANIFEST.MF' or name.endswith(SIGNATURE_SUFFIXES)):
|
||||
continue
|
||||
data = replacements.get(name)
|
||||
if data is None:
|
||||
data = source.read(name)
|
||||
entry = copy.copy(info)
|
||||
entry.extra = b''
|
||||
target.writestr(entry, data, compress_type=info.compress_type)
|
||||
missing = set(replacements) - {i.filename for i in ZipFile(output).infolist()}
|
||||
if missing:
|
||||
raise Refused('Replacement entries missing from the output: ' + ', '.join(sorted(missing)))
|
||||
|
||||
|
||||
def release_tags(limit=60):
|
||||
out = run_bounded(['gh', 'release', 'list', '-R', CI_REPO, '--limit', str(limit), '--json', 'tagName'],
|
||||
120, capture_output=True, text=True)
|
||||
if out.returncode:
|
||||
raise Refused('Could not list DroidDeck-CI releases: ' + out.stderr.strip())
|
||||
return [item['tagName'] for item in json.loads(out.stdout) if item['tagName'].startswith('main-')]
|
||||
|
||||
|
||||
def donor_commit(tag):
|
||||
short = tag.removeprefix('main-')
|
||||
commit = git('rev-parse', '--verify', '--quiet', short + '^{commit}', check=False).decode().strip()
|
||||
if not commit:
|
||||
git('fetch', '--no-tags', 'origin', 'main')
|
||||
commit = git('rev-parse', '--verify', short + '^{commit}').decode().strip()
|
||||
return commit
|
||||
|
||||
|
||||
def is_ancestor(commit):
|
||||
return subprocess.run(['git', '-C', str(ROOT), 'merge-base', '--is-ancestor', commit, 'HEAD']).returncode == 0
|
||||
|
||||
|
||||
def pick_tag(requested):
|
||||
if requested:
|
||||
return requested
|
||||
for tag in release_tags():
|
||||
try:
|
||||
if is_ancestor(donor_commit(tag)):
|
||||
return tag
|
||||
except Refused:
|
||||
continue
|
||||
raise Refused('No recent DroidDeck-CI main build is an ancestor of this checkout; merge main first.')
|
||||
|
||||
|
||||
def fetch_donor(tag):
|
||||
folder = CACHE / tag
|
||||
apk = folder / f'DroidDeck-{tag}.apk'
|
||||
sums = folder / 'SHA256SUMS.txt'
|
||||
if not (apk.is_file() and sums.is_file()):
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
for pattern in (apk.name, sums.name):
|
||||
try:
|
||||
result = run_bounded(['gh', 'release', 'download', tag, '-R', CI_REPO, '-p', pattern,
|
||||
'-D', str(folder), '--clobber'], 900, capture_output=True, text=True)
|
||||
if result.returncode:
|
||||
raise Refused('Download failed: ' + result.stderr.strip())
|
||||
except Refused:
|
||||
apk.unlink(missing_ok=True)
|
||||
raise
|
||||
expected = dict(reversed(line.split(None, 1)) for line in sums.read_text().splitlines() if line.strip())
|
||||
if digest(apk) != expected.get(apk.name, '').strip():
|
||||
apk.unlink()
|
||||
raise Refused('Donor APK does not match SHA256SUMS.txt: ' + apk.name)
|
||||
return apk
|
||||
|
||||
|
||||
def sdk_root():
|
||||
return Path(os.environ.get('ANDROID_HOME') or os.environ.get('ANDROID_SDK_ROOT') or Path.home() / 'android-sdk')
|
||||
|
||||
|
||||
def apksigner():
|
||||
candidates = sorted((sdk_root() / 'build-tools').glob('*/apksigner*'), reverse=True)
|
||||
for path in candidates:
|
||||
if path.suffix in ('', '.bat'):
|
||||
return str(path)
|
||||
raise Refused('apksigner not found under ' + str(sdk_root() / 'build-tools'))
|
||||
|
||||
|
||||
def signer_sha256(apk):
|
||||
result = subprocess.run([apksigner(), 'verify', '--print-certs', str(apk)], capture_output=True, text=True)
|
||||
if result.returncode:
|
||||
raise Refused('APK signature does not verify: ' + (result.stdout + result.stderr).strip())
|
||||
for line in result.stdout.splitlines():
|
||||
if 'certificate SHA-256 digest:' in line:
|
||||
return line.rsplit(':', 1)[1].strip().lower()
|
||||
raise Refused('apksigner reported no certificate digest')
|
||||
|
||||
|
||||
def pwsh():
|
||||
found = shutil.which('pwsh')
|
||||
if found:
|
||||
return found
|
||||
if PWSH_FALLBACK.is_file():
|
||||
return str(PWSH_FALLBACK)
|
||||
raise Refused('PowerShell 7 (pwsh) is required for the local signer')
|
||||
|
||||
|
||||
def signing_env():
|
||||
"""The .signing.env build_local.sh uses: the override, else the checkout's own, else the main checkout's."""
|
||||
common = Path(git('rev-parse', '--path-format=absolute', '--git-common-dir').decode().strip())
|
||||
for candidate in (os.environ.get('DROIDDECK_SIGNING_ENV'), ROOT / '.signing.env', common.parent / '.signing.env'):
|
||||
if candidate and Path(candidate).is_file():
|
||||
return Path(candidate).resolve()
|
||||
return None
|
||||
|
||||
|
||||
def version_key(path):
|
||||
return [int(part) if part.isdigit() else -1 for part in path.parent.name.replace('-', '.').split('.')]
|
||||
|
||||
|
||||
def sign_with_env(env_file, unsigned, signed):
|
||||
complete = [path for path in (sdk_root() / 'build-tools').glob('*/aapt')
|
||||
if all((path.parent / tool).is_file() for tool in ('zipalign', 'apksigner'))]
|
||||
build_tools = sorted(complete, key=version_key, reverse=True)
|
||||
if not build_tools:
|
||||
raise Refused('no build-tools with aapt, zipalign and apksigner under ' + str(sdk_root() / 'build-tools'))
|
||||
# BUILD_TOOLS is assigned after the env file is sourced so the file cannot replace the chosen SDK.
|
||||
script = 'set -a; cd "$(dirname "$1")"; . "$1"; set +a; BUILD_TOOLS="$5" exec "$2" "$3" standard "$4"'
|
||||
result = subprocess.run(['bash', '-c', script, 'sign', str(env_file), str(ROOT / 'tools/release/sign-apk.sh'),
|
||||
str(unsigned), str(signed), str(build_tools[0].parent.resolve())],
|
||||
capture_output=True, text=True)
|
||||
if result.returncode or not signed.is_file():
|
||||
raise Refused('Signing failed:\n' + (result.stdout + result.stderr).strip())
|
||||
|
||||
|
||||
def sign(unsigned, signed):
|
||||
if not SIGNER.is_file() and (env_file := signing_env()):
|
||||
return sign_with_env(env_file, unsigned, signed)
|
||||
# Microsoft Store Python virtualizes AppData for child processes too and hides the signer; use a python.org install.
|
||||
def quoted(value):
|
||||
return "'" + str(value).replace("'", "''") + "'"
|
||||
command = (f"if (-not (Test-Path -LiteralPath {quoted(SIGNER)})) {{ Write-Error 'Local signer not found'; exit 1 }}; "
|
||||
f"& {quoted(SIGNER)} -InputApk {quoted(unsigned)} -OutputApk {quoted(signed)} -SdkRoot {quoted(sdk_root())}")
|
||||
result = subprocess.run([pwsh(), '-NoProfile', '-Command', command], capture_output=True, text=True)
|
||||
if result.returncode or not signed.is_file():
|
||||
raise Refused('Signing failed:\n' + (result.stdout + result.stderr).strip())
|
||||
|
||||
|
||||
def verify_output(apk, grafts, pinned):
|
||||
if signer_sha256(apk) != pinned:
|
||||
raise Refused('Output is not signed with the release certificate')
|
||||
with ZipFile(apk) as package:
|
||||
for path, asset in grafts.items():
|
||||
if package.read(asset) != helper_bytes(path):
|
||||
raise Refused('Grafted helper does not match its source: ' + asset)
|
||||
for path, asset in graft_targets().items():
|
||||
if asset in package.namelist() and package.read(asset) != helper_bytes(path):
|
||||
raise Refused('Stale helper in the output: ' + asset)
|
||||
|
||||
|
||||
def install(apk):
|
||||
adb = Path(os.environ.get('ADB') or sdk_root() / 'platform-tools/adb.exe')
|
||||
if not adb.is_file():
|
||||
adb = Path(shutil.which('adb') or '')
|
||||
if not adb.is_file():
|
||||
raise Refused('adb not found; set ADB or ANDROID_HOME')
|
||||
serial = subprocess.run([sys.executable, str(ROOT / 'tools/adb_device.py'), '--adb', str(adb)],
|
||||
capture_output=True, text=True)
|
||||
if serial.returncode:
|
||||
raise Refused(serial.stderr.strip() or 'No device resolved')
|
||||
device = serial.stdout.strip()
|
||||
result = subprocess.run([str(adb), '-s', device, 'install', '-r', '--no-incremental', str(apk)])
|
||||
if result.returncode:
|
||||
raise Refused('adb install failed (a different signing certificate needs a manual uninstall)')
|
||||
print('Installed on ' + device)
|
||||
|
||||
|
||||
def run(args):
|
||||
pinned = (ROOT / 'keystore/release-signer.sha256').read_text().strip().lower()
|
||||
tag = pick_tag(args.donor)
|
||||
commit = donor_commit(tag)
|
||||
if not is_ancestor(commit):
|
||||
raise Refused(f'{tag} is not an ancestor of this checkout; merge main or pick an older build')
|
||||
donor = fetch_donor(tag)
|
||||
if signer_sha256(donor) != pinned:
|
||||
raise Refused('Donor APK is not signed with the release certificate')
|
||||
with ZipFile(donor) as package:
|
||||
entries = set(package.namelist())
|
||||
grafts, ignored, blocked = classify(changed_paths(commit), graft_targets(), entries)
|
||||
print(f'Donor {tag} ({commit[:7]})')
|
||||
for path in ignored:
|
||||
print(' ignored', path)
|
||||
for path, asset in grafts.items():
|
||||
print(' graft ', path, '->', asset)
|
||||
if blocked:
|
||||
for path, reason in blocked.items():
|
||||
print(' BLOCKED', path, f'({reason})')
|
||||
raise Refused('Changes outside the graftable set; run tools/build_local.sh for these.')
|
||||
if not grafts:
|
||||
print('Nothing to graft; the donor already matches this checkout.')
|
||||
if not args.plan:
|
||||
print('Donor APK:', donor)
|
||||
if args.install:
|
||||
install(donor)
|
||||
return
|
||||
if args.plan:
|
||||
return
|
||||
out_dir = ROOT / 'app/build/outputs/apk/fast'
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
stamp = f'{tag}-{git("rev-parse", "--short", "HEAD").decode().strip()}-{int(time.time())}'
|
||||
unsigned = out_dir / f'unsigned-{stamp}.apk'
|
||||
signed = out_dir / f'DroidDeck-fast-{stamp}.apk'
|
||||
graft(donor, {asset: helper_bytes(path) for path, asset in grafts.items()}, unsigned)
|
||||
try:
|
||||
sign(unsigned, signed)
|
||||
finally:
|
||||
unsigned.unlink(missing_ok=True)
|
||||
verify_output(signed, grafts, pinned)
|
||||
print('Signed APK:', signed)
|
||||
if args.install:
|
||||
install(signed)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--donor', help='DroidDeck-CI main tag such as main-4aa19b6; default is the newest ancestor build')
|
||||
parser.add_argument('--plan', action='store_true', help='Show what would be grafted without building')
|
||||
parser.add_argument('--install', action='store_true', help='Install the signed APK on the connected device')
|
||||
try:
|
||||
run(parser.parse_args())
|
||||
except Refused as error:
|
||||
parser.exit(2, str(error) + '\n')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -11,8 +11,30 @@ icon, Plasma's default bottom panel, and "Return to Gaming Mode" and Steam on th
|
||||
- `overlay/`: our files on top - system-wide KDE defaults in `/etc/xdg`, the Vapor theme and its
|
||||
layout script, the menu entries Steam and Return to Gaming Mode use.
|
||||
|
||||
pacman works on the desktop. `pacman-db.py` writes an install record for every package the desktop
|
||||
ships into `/var/lib/pacman/local`, and builds the `droiddeck` repository: Arch Linux ARM's core,
|
||||
extra and alarm databases as they were at build time, with the runtime's and the desktop's own
|
||||
packages at the installed versions. The release carries that database (`droiddeck.db`) and the
|
||||
packages `mirror.txt` names; everything else downloads from Arch Linux ARM as a `CacheServer`, so its
|
||||
404s never disable a mirror. Installs therefore resolve against the desktop's exact Qt and KDE
|
||||
versions, and `pacman -Syu` only ever moves packages the user added.
|
||||
|
||||
- `/usr/local/bin/pacman` runs the real pacman with `/usr/share/droiddeck/pacman/pacman.conf`, first
|
||||
copying in the shipped database and dropping the runtime's records for packages the desktop
|
||||
replaced (`prepare`). As root it adds `--needed` to installs, so guides that reinstall
|
||||
something the desktop has just skip it.
|
||||
- `sudo`, `su` and `sudoedit` run commands as root: the session is the app's own Android user, and
|
||||
`libdroiddeck-root.so` (`root/root.c`, preloaded by `sudo`) reports uid 0, accepts ownership
|
||||
changes and shows the runtime's 0700 directories as 0755. It grants nothing the user lacked.
|
||||
- `hooks/droiddeck-system.hook` refuses to remove or replace any runtime or desktop package;
|
||||
`droiddeck-remember.hook` keeps the user's own packages in
|
||||
`~/.local/share/droiddeck/pacman/packages.txt`, and `restore` (autostarted) reinstalls them after a
|
||||
runtime update and upgrades them after a desktop update. Hooks that need systemd, udev, kernel
|
||||
modules or an initramfs are masked.
|
||||
|
||||
`.github/workflows/build-desktop-kde.yml` builds it and, run with a new tag, publishes it as a
|
||||
release in Droid-Deck/DroidDeck-Components. `release.env` pins the tag, sha256 and size the apk
|
||||
release in Droid-Deck/DroidDeck-Components (tags with `-rc` are published as pre-releases for testing
|
||||
before an app build points at them). `release.env` pins the tag, sha256 and size the apk
|
||||
installs (`DesktopCatalog.desktopEntry`); a published tag is never replaced, so a changed package
|
||||
is a new tag and a `release.env` update.
|
||||
|
||||
@@ -20,6 +42,8 @@ At run time the desktop is started by `tools/linuxfs/desktop/droiddeck-desktop`
|
||||
at every session): Plasma's own `startplasma-wayland`, with KWin nested in the app's compositor
|
||||
through `kwin_wayland_wrapper`. The package's `kwin-compositor` marker selects OpenGL through
|
||||
Zink for KWin 6.8, which removed QPainter. Older packages retain their software compositor.
|
||||
KWin runs without Gallium's threaded context and without overlay layers. With the threaded context, KWin crashed
|
||||
uploading windows' shared-memory buffers by reading past their end, and the host shows only a single buffer.
|
||||
On Android the launcher explicitly selects the KGSL render node; the nested backend can use it
|
||||
when the host's dmabuf feedback cannot name a DRM device. Games and emulators from the menu go
|
||||
through `droiddeck-gpu`, and Steam goes back to the app as a Steam session.
|
||||
@@ -35,6 +59,9 @@ The behavior is enabled only with `DROIDDECK_NESTED_SCALE`, which the desktop sc
|
||||
`0002-select-explicit-nested-render-node.patch` lets that nested backend use one explicitly
|
||||
selected `KWIN_RENDER_NODES` device when host feedback cannot identify it. It does not guess
|
||||
between GPUs or change normal KWin device selection.
|
||||
`0003-forward-nested-scroll-source.patch` passes the host's scroll source, wheel steps and scroll stops
|
||||
through the nested backend, which upstream leaves as a TODO. Two-finger touch scrolling then reaches
|
||||
apps as touchpad scrolling, and wheel steps stay whole clicks.
|
||||
|
||||
`pins/mesa/desc` keeps Mesa 26.2.4 and its actual package dependencies ahead of the rolling
|
||||
repository metadata. Mesa 26.2.5 crashes in Zink shader compilation on Thor with the selected
|
||||
@@ -44,7 +71,7 @@ both build jobs verify the Arch Linux ARM signature and pinned SHA-256 as for ev
|
||||
The desktop workflow replaces the same-version `kwin_wayland` executable and `libkwin.so`; the rest
|
||||
comes from the signature-checked Arch packages. `desktop-kde.kwin.txt` records the source, patch,
|
||||
executable, library and build package hashes. Corresponding source is
|
||||
https://download.kde.org/stable/plasma/6.8.0/kwin-6.8.0.tar.xz plus the patch in this repository.
|
||||
https://download.kde.org/stable/plasma/6.8.2/kwin-6.8.2.tar.xz plus the patch in this repository.
|
||||
|
||||
The inventories use `.gzip` rather than `.gz`: Android's asset packer expands `.gz` and strips
|
||||
its suffix. The shared local/CI runtime payload check verifies the exact APK names and bytes.
|
||||
|
||||
@@ -6,7 +6,7 @@ here=$(cd "$(dirname "$0")" && pwd)
|
||||
source "$here/kwin.env"
|
||||
source "$here/mesa.env"
|
||||
version=$DESKTOP_KWIN_VERSION
|
||||
source_sha=4bfaf31e29a8f9fdf231dc3bbb9b09b0ce07cae9fee7a01cfc86425ece796258
|
||||
source_sha=ea5e68d957c7d70abed97222a592d4445fda29129e20942658badd224ee138b4
|
||||
mirror=https://fl.us.mirror.archlinuxarm.org/aarch64
|
||||
builder=68B3537F39A313B3E574D06777193F152BDBE6A6
|
||||
work=$(mktemp -d)
|
||||
@@ -52,6 +52,7 @@ sudo mount -t proc proc "$work/root/proc"
|
||||
sudo tar -xf "$work/kwin.tar.xz" -C "$work/root/build"
|
||||
sudo patch -d "$work/root/build/kwin-$version" -p1 < "$here/patches/0001-respect-nested-desktop-scale.patch"
|
||||
sudo patch -d "$work/root/build/kwin-$version" -p1 < "$here/patches/0002-select-explicit-nested-render-node.patch"
|
||||
sudo patch -d "$work/root/build/kwin-$version" -p1 < "$here/patches/0003-forward-nested-scroll-source.patch"
|
||||
sudo chroot "$work/root" /usr/bin/env PATH=/usr/bin:/bin HOME=/root LC_ALL=C.UTF-8 \
|
||||
/usr/bin/cmake -S "/build/kwin-$version" -B /build/out -G Ninja \
|
||||
-DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr -DCMAKE_INSTALL_LIBEXECDIR=lib \
|
||||
@@ -72,6 +73,7 @@ grep -aq DROIDDECK_NESTED_SCALE "$out/libkwin.so.$version"
|
||||
echo "KWin $version source sha256 $source_sha"
|
||||
echo "Patch sha256 $(sha256sum "$here/patches/0001-respect-nested-desktop-scale.patch" | cut -d' ' -f1)"
|
||||
echo "Render node patch sha256 $(sha256sum "$here/patches/0002-select-explicit-nested-render-node.patch" | cut -d' ' -f1)"
|
||||
echo "Scroll source patch sha256 $(sha256sum "$here/patches/0003-forward-nested-scroll-source.patch" | cut -d' ' -f1)"
|
||||
echo "Executable sha256 $(sha256sum "$out/kwin_wayland" | cut -d' ' -f1)"
|
||||
echo "Library sha256 $(sha256sum "$out/libkwin.so.$version" | cut -d' ' -f1)"
|
||||
echo 'Build packages (Arch Linux ARM signatures verified):'
|
||||
|
||||
@@ -38,6 +38,12 @@ while read -r entry sum; do
|
||||
done < "$work/pkglist.txt"
|
||||
|
||||
cp -a "$here/overlay/." "$work/root/"
|
||||
mkdir -p "$work/root/usr/lib/droiddeck"
|
||||
${CC_AARCH64:-aarch64-linux-gnu-gcc} -shared -fPIC -O2 -Wall -Wextra \
|
||||
-o "$work/root/usr/lib/droiddeck/libdroiddeck-root.so" "$here/root/root.c" -ldl
|
||||
${STRIP_AARCH64:-aarch64-linux-gnu-strip} --strip-unneeded "$work/root/usr/lib/droiddeck/libdroiddeck-root.so"
|
||||
python3 "$here/pacman-db.py" "$work/db" "$pkgs" "$work/pkglist.txt" "$here/runtime-packages.txt" \
|
||||
"$here/mirror.txt" "${DESKTOP_KDE_RELEASE_TAG:-}" "$work/root" "$out/repo"
|
||||
|
||||
if [ -n "${KDE_KWIN_OVERRIDE:-}" ]; then
|
||||
kwin_package=$(awk '$1 ~ /^extra\/kwin-.*-aarch64\.pkg\.tar\./ {print $1}' "$work/pkglist.txt")
|
||||
@@ -61,7 +67,7 @@ if [ -d "$work/root/usr/share/locale" ]; then
|
||||
echo "i18n: $(wc -l < "$out/desktop-kde.i18n.txt") language packs"
|
||||
fi
|
||||
|
||||
rm -rf "$work/root/usr/share/doc" "$work/root/usr/share/man" "$work/root/usr/share/info" \
|
||||
rm -rf "$work/root/usr/share/doc" "$work/root/usr/share/info" \
|
||||
"$work/root/usr/share/gtk-doc" "$work/root/usr/include" "$work/root/usr/lib/pkgconfig" \
|
||||
"$work/root/usr/lib/cmake" "$work/root/usr/share/help"
|
||||
find "$work/root/usr/share/locale" -mindepth 1 -maxdepth 1 -type d ! -name 'en*' -exec rm -rf {} + 2>/dev/null || true
|
||||
|
||||
@@ -1 +1 @@
|
||||
DESKTOP_KWIN_VERSION=6.8.0
|
||||
DESKTOP_KWIN_VERSION=6.8.2
|
||||
@@ -0,0 +1,16 @@
|
||||
neovim
|
||||
tmux
|
||||
screen
|
||||
rsync
|
||||
jq
|
||||
ripgrep
|
||||
fd
|
||||
bat
|
||||
ncdu
|
||||
btop
|
||||
fastfetch
|
||||
lsof
|
||||
strace
|
||||
python-pip
|
||||
nodejs
|
||||
npm
|
||||
@@ -0,0 +1,7 @@
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=Restore pacman packages
|
||||
Exec=/usr/share/droiddeck/pacman/restore
|
||||
NoDisplay=true
|
||||
OnlyShowIn=KDE;
|
||||
X-KDE-autostart-phase=2
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
#!/bin/bash
|
||||
dir=/usr/share/droiddeck/pacman
|
||||
[ -r "$dir/pacman.conf" ] || exec /usr/bin/pacman "$@"
|
||||
"$dir/prepare" || exit 1
|
||||
install=0
|
||||
if [ "$(id -u)" = 0 ]; then
|
||||
letters= install=1
|
||||
for arg in "$@"; do
|
||||
case $arg in
|
||||
--) break ;;
|
||||
--sync) letters+=S ;;
|
||||
--search|--info|--clean|--groups|--list|--print|--print-format|--downloadonly) install=0 ;;
|
||||
--*) ;;
|
||||
-*) letters+=${arg#-} ;;
|
||||
esac
|
||||
done
|
||||
case $letters in *S*) ;; *) install=0 ;; esac
|
||||
case $letters in *[sicglpw]*) install=0 ;; esac
|
||||
[ "$install" = 1 ] && set -- --needed "$@"
|
||||
fi
|
||||
[ "$install" = 1 ] || exec /usr/bin/pacman --config "$dir/pacman.conf" "$@"
|
||||
/usr/bin/pacman --config "$dir/pacman.conf" "$@" && exit 0
|
||||
status=$?
|
||||
mapfile -t paths < <("$dir/adopt" "$@")
|
||||
[ ${#paths[@]} -gt 0 ] || exit "$status"
|
||||
overwrite=()
|
||||
for path in "${paths[@]}"; do overwrite+=(--overwrite "$path"); done
|
||||
/usr/bin/pacman --config "$dir/pacman.conf" "${overwrite[@]}" "$@" || exit
|
||||
mapfile -t shared < <(/usr/bin/pacman --config "$dir/pacman.conf" -Qqd 2>/dev/null | grep -xF -f /var/lib/pacman/droiddeck-shared)
|
||||
[ ${#shared[@]} -eq 0 ] || /usr/bin/pacman --config "$dir/pacman.conf" -D --asexplicit "${shared[@]}" >/dev/null
|
||||
"$dir/remember"
|
||||
Executable
+32
@@ -0,0 +1,32 @@
|
||||
#!/bin/bash
|
||||
login=0 command= shell=
|
||||
while [ $# -gt 0 ]; do
|
||||
case $1 in
|
||||
-|-l|--login) login=1; shift ;;
|
||||
-c|--command) [ $# -ge 2 ] || { echo "su: option requires an argument -- 'c'" >&2; exit 1; }; command=$2; shift 2 ;;
|
||||
--command=*) command=${1#*=}; shift ;;
|
||||
-s|--shell) [ $# -ge 2 ] || { echo "su: option requires an argument -- 's'" >&2; exit 1; }; shell=$2; shift 2 ;;
|
||||
--shell=*) shell=${1#*=}; shift ;;
|
||||
-m|-p|--preserve-environment|-P|--pty|-f|--fast) shift ;;
|
||||
-h|--help) echo "usage: su [-] [-c command] [-s shell] [root]"; exit 0 ;;
|
||||
-V|--version) echo "DroidDeck su: runs a root shell inside the DroidDeck desktop"; exit 0 ;;
|
||||
--) shift; break ;;
|
||||
-*) echo "su: invalid option -- '${1#-}'" >&2; exit 1 ;;
|
||||
*) break ;;
|
||||
esac
|
||||
done
|
||||
user=${1:-root}
|
||||
[ $# -gt 0 ] && shift
|
||||
case $user in
|
||||
root|0|"$(id -un 2>/dev/null)") ;;
|
||||
*) echo "su: user $user does not exist or the user entry does not contain all the required fields" >&2; exit 1 ;;
|
||||
esac
|
||||
args=()
|
||||
[ "$login" = 1 ] && args+=(-i)
|
||||
if [ -n "$shell" ]; then
|
||||
if [ -n "$command" ]; then exec /usr/local/bin/sudo "${args[@]}" "$shell" -c "$command" "$@"; fi
|
||||
exec /usr/local/bin/sudo "${args[@]}" "$shell" "$@"
|
||||
fi
|
||||
if [ -n "$command" ]; then exec /usr/local/bin/sudo "${args[@]}" -s "$command"; fi
|
||||
[ "$login" = 1 ] && exec /usr/local/bin/sudo -i
|
||||
exec /usr/local/bin/sudo -s
|
||||
Executable
+94
@@ -0,0 +1,94 @@
|
||||
#!/bin/bash
|
||||
lib=/usr/lib/droiddeck/libdroiddeck-root.so
|
||||
me=${0##*/}
|
||||
usage() {
|
||||
echo "usage: $me [-EHiknsSv] [-u user] [-g group] [-D directory] [--] command [arg ...]"
|
||||
echo " $me -e file ..."
|
||||
}
|
||||
known_user() {
|
||||
case $1 in
|
||||
''|root|0|'#0'|"$(id -un 2>/dev/null)"|"#$(id -ru 2>/dev/null)") return 0 ;;
|
||||
esac
|
||||
echo "$me: unknown user $1" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
login=0 shell=0 edit=0 background=0 dir=
|
||||
[ "$me" = sudoedit ] && edit=1
|
||||
while [ $# -gt 0 ]; do
|
||||
case $1 in
|
||||
--) shift; break ;;
|
||||
-h|--help) usage; exit 0 ;;
|
||||
-V|--version) echo "DroidDeck sudo: runs commands as root inside the DroidDeck desktop"; exit 0 ;;
|
||||
-l|--list) echo "User $(id -un 2>/dev/null) may run the following commands on $(uname -n):"; echo " (ALL : ALL) ALL"; exit 0 ;;
|
||||
-v|--validate|-K|--remove-timestamp) exit 0 ;;
|
||||
-k|--reset-timestamp) shift; [ $# -eq 0 ] && exit 0 ;;
|
||||
-i|--login) login=1; shift ;;
|
||||
-s|--shell) shell=1; shift ;;
|
||||
-e|--edit) edit=1; shift ;;
|
||||
-b|--background) background=1; shift ;;
|
||||
-E|--preserve-env|--preserve-env=*|-H|--set-home|-n|--non-interactive|-S|--stdin|-P|--preserve-groups|-A|--askpass|-B|--bell|-N|--no-update) shift ;;
|
||||
-u|--user|-g|--group) [ $# -ge 2 ] || { usage >&2; exit 1; }; known_user "$2"; shift 2 ;;
|
||||
--user=*|--group=*) known_user "${1#*=}"; shift ;;
|
||||
-u*|-g*) known_user "${1:2}"; shift ;;
|
||||
-D|--chdir) [ $# -ge 2 ] || { usage >&2; exit 1; }; dir=$2; shift 2 ;;
|
||||
--chdir=*) dir=${1#*=}; shift ;;
|
||||
-p|--prompt|-C|--close-from|-r|--role|-t|--type|-T|--command-timeout|-R|--chroot) [ $# -ge 2 ] || { usage >&2; exit 1; }; shift 2 ;;
|
||||
--prompt=*|--close-from=*|--role=*|--type=*|--command-timeout=*) shift ;;
|
||||
-[A-Za-z][A-Za-z]*)
|
||||
flags=${1#-}; shift
|
||||
split=()
|
||||
while [ -n "$flags" ]; do
|
||||
split+=("-${flags:0:1}")
|
||||
case ${flags:0:1} in
|
||||
u|g|D|p|C|r|t|T|R) [ -n "${flags:1}" ] && split+=("${flags:1}"); flags= ;;
|
||||
*) flags=${flags:1} ;;
|
||||
esac
|
||||
done
|
||||
set -- "${split[@]}" "$@"
|
||||
;;
|
||||
-*) echo "$me: invalid option -- '${1#-}'" >&2; usage >&2; exit 1 ;;
|
||||
*) break ;;
|
||||
esac
|
||||
done
|
||||
|
||||
if [ "$edit" = 1 ]; then
|
||||
[ $# -gt 0 ] || { usage >&2; exit 1; }
|
||||
editor=${SUDO_EDITOR:-${VISUAL:-${EDITOR:-nano}}}
|
||||
exec $editor "$@"
|
||||
fi
|
||||
|
||||
if [ ! -r "$lib" ]; then
|
||||
echo "$me: $lib is missing; reinstall the desktop from DroidDeck's Desktop page" >&2
|
||||
exit 1
|
||||
fi
|
||||
case ":${LD_PRELOAD:-}:" in
|
||||
*":$lib:"*) ;;
|
||||
*) export LD_PRELOAD="$lib${LD_PRELOAD:+:$LD_PRELOAD}" ;;
|
||||
esac
|
||||
export SUDO_USER=${SUDO_USER:-$(id -un 2>/dev/null)}
|
||||
export SUDO_UID=${SUDO_UID:-$(id -ru 2>/dev/null)}
|
||||
export SUDO_GID=${SUDO_GID:-$(id -rg 2>/dev/null)}
|
||||
export SUDO_COMMAND="$*"
|
||||
[ -z "$dir" ] || cd "$dir" || exit 1
|
||||
|
||||
target_shell=$(getent passwd "$(id -un 2>/dev/null)" | cut -d: -f7)
|
||||
target_shell=${target_shell:-/bin/bash}
|
||||
if [ "$login" = 1 ]; then
|
||||
cd "${HOME:-/root}" 2>/dev/null
|
||||
if [ $# -gt 0 ]; then set -- "$target_shell" -l -c "$*"; else set -- "$target_shell" -l; fi
|
||||
elif [ "$shell" = 1 ]; then
|
||||
if [ $# -gt 0 ]; then set -- "${SHELL:-$target_shell}" -c "$*"; else set -- "${SHELL:-$target_shell}"; fi
|
||||
elif [ $# -eq 0 ]; then
|
||||
usage >&2
|
||||
exit 1
|
||||
elif ! command -v "$1" >/dev/null 2>&1; then
|
||||
echo "$me: $1: command not found" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ "$background" = 1 ]; then
|
||||
"$@" &
|
||||
exit 0
|
||||
fi
|
||||
exec "$@"
|
||||
@@ -0,0 +1 @@
|
||||
sudo
|
||||
@@ -0,0 +1,6 @@
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=Avahi Zeroconf Browser
|
||||
Exec=/usr/bin/avahi-discover
|
||||
Icon=network-wired
|
||||
NoDisplay=true
|
||||
@@ -0,0 +1,6 @@
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=Avahi SSH Server Browser
|
||||
Exec=/usr/bin/bssh
|
||||
Icon=network-wired
|
||||
NoDisplay=true
|
||||
@@ -0,0 +1,6 @@
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=Avahi VNC Server Browser
|
||||
Exec=/usr/bin/bvnc
|
||||
Icon=network-wired
|
||||
NoDisplay=true
|
||||
@@ -0,0 +1,6 @@
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=Foot Server
|
||||
Exec=foot --server
|
||||
Icon=foot
|
||||
NoDisplay=true
|
||||
@@ -0,0 +1,6 @@
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=Foot Client
|
||||
Exec=footclient
|
||||
Icon=foot
|
||||
NoDisplay=true
|
||||
@@ -0,0 +1,6 @@
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=Hardware Locality lstopo
|
||||
Exec=lstopo
|
||||
Icon=hwloc
|
||||
NoDisplay=true
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=IBus Preferences
|
||||
Exec=ibus-setup
|
||||
Icon=ibus-setup
|
||||
NoDisplay=true
|
||||
@@ -0,0 +1,6 @@
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=Qt V4L2 test Utility
|
||||
Exec=qv4l2
|
||||
Icon=qv4l2
|
||||
NoDisplay=true
|
||||
@@ -0,0 +1,6 @@
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=Qt V4L2 video capture utility
|
||||
Exec=qvidcap
|
||||
Icon=qvidcap
|
||||
NoDisplay=true
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
#!/usr/bin/python3
|
||||
import hashlib
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
|
||||
SHARE = "/usr/share/droiddeck/pacman"
|
||||
LIB = "/var/lib/pacman"
|
||||
CACHE = "/var/cache/pacman/pkg"
|
||||
SHARED = os.path.join(LIB, "droiddeck-shared")
|
||||
SHARED_FILES = SHARED + "-files"
|
||||
|
||||
|
||||
def owned():
|
||||
paths = set()
|
||||
local = os.path.join(LIB, "local")
|
||||
for entry in os.listdir(local):
|
||||
try:
|
||||
with open(os.path.join(local, entry, "files"), encoding="utf-8", errors="surrogateescape") as f:
|
||||
lines = f.read().split("\n")
|
||||
except OSError:
|
||||
continue
|
||||
reading = False
|
||||
for line in lines:
|
||||
if line.startswith("%"):
|
||||
reading = line == "%FILES%"
|
||||
elif reading and line:
|
||||
paths.add(line.rstrip("/"))
|
||||
return paths
|
||||
|
||||
|
||||
def same(archive, member, path):
|
||||
if member.issym():
|
||||
return os.path.islink(path) and os.readlink(path) == member.linkname
|
||||
if not member.isfile() or os.path.islink(path) or not os.path.isfile(path):
|
||||
return False
|
||||
if os.path.getsize(path) != member.size:
|
||||
return False
|
||||
with archive.extractfile(member) as packaged, open(path, "rb") as installed:
|
||||
return hashlib.file_digest(packaged, "sha256").digest() == hashlib.file_digest(installed, "sha256").digest()
|
||||
|
||||
|
||||
def planned(args):
|
||||
query = []
|
||||
for arg in args:
|
||||
if arg == "--refresh" or arg == "--noconfirm":
|
||||
continue
|
||||
if re.fullmatch(r"-[A-Za-z]+", arg):
|
||||
arg = arg.replace("y", "")
|
||||
if arg == "-":
|
||||
continue
|
||||
query.append(arg)
|
||||
run = subprocess.run(["/usr/bin/pacman", "--config", os.path.join(SHARE, "pacman.conf"), "--noconfirm", *query,
|
||||
"--print", "--print-format", "%n %f"], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
|
||||
text=True)
|
||||
if run.returncode != 0:
|
||||
return []
|
||||
return [line.split(" ", 1) for line in run.stdout.splitlines() if " " in line]
|
||||
|
||||
|
||||
def main():
|
||||
targets = [(name, os.path.join(CACHE, os.path.basename(file))) for name, file in planned(sys.argv[1:])]
|
||||
targets = [(name, path) for name, path in targets if os.path.isfile(path)]
|
||||
if not targets:
|
||||
return 0
|
||||
have = owned()
|
||||
paths, names = [], []
|
||||
for name, path in targets:
|
||||
found = False
|
||||
with tarfile.open(path) as archive:
|
||||
for member in archive:
|
||||
if member.isdir() or member.name.startswith("."):
|
||||
continue
|
||||
if member.name in have or not os.path.lexists("/" + member.name) or os.path.isdir("/" + member.name):
|
||||
continue
|
||||
if not same(archive, member, "/" + member.name):
|
||||
continue
|
||||
paths.append("/" + member.name)
|
||||
found = True
|
||||
if found:
|
||||
names.append(name)
|
||||
if not paths:
|
||||
return 0
|
||||
shared = set()
|
||||
try:
|
||||
with open(SHARED) as f:
|
||||
shared = {line.strip() for line in f if line.strip()}
|
||||
except OSError:
|
||||
pass
|
||||
with open(SHARED + ".tmp", "w") as f:
|
||||
f.write("".join(f"{name}\n" for name in sorted(shared | set(names))))
|
||||
os.replace(SHARED + ".tmp", SHARED)
|
||||
files = set()
|
||||
try:
|
||||
with open(SHARED_FILES, encoding="utf-8", errors="surrogateescape") as f:
|
||||
files = {line.rstrip("\n") for line in f if line.strip()}
|
||||
except OSError:
|
||||
pass
|
||||
with open(SHARED_FILES + ".tmp", "w", encoding="utf-8", errors="surrogateescape") as f:
|
||||
f.write("".join(f"{path}\n" for path in sorted(files | set(paths))))
|
||||
os.replace(SHARED_FILES + ".tmp", SHARED_FILES)
|
||||
print(f":: Other DroidDeck software already installed {len(paths)} files from {' '.join(names)}.", file=sys.stderr)
|
||||
print(":: pacman will take them over and keep these packages installed so that software keeps working.",
|
||||
file=sys.stderr)
|
||||
for path in paths:
|
||||
print(re.sub(r"([\\*?\[])", r"\\\1", path))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
sys.exit(main())
|
||||
except (OSError, tarfile.TarError) as e:
|
||||
print(f"error: could not check for files other DroidDeck software installed: {e}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
/dev/null
|
||||
+1
@@ -0,0 +1 @@
|
||||
/dev/null
|
||||
+1
@@ -0,0 +1 @@
|
||||
/dev/null
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
/dev/null
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
/dev/null
|
||||
+1
@@ -0,0 +1 @@
|
||||
/dev/null
|
||||
+1
@@ -0,0 +1 @@
|
||||
/dev/null
|
||||
+1
@@ -0,0 +1 @@
|
||||
/dev/null
|
||||
@@ -0,0 +1 @@
|
||||
/dev/null
|
||||
+1
@@ -0,0 +1 @@
|
||||
/dev/null
|
||||
+1
@@ -0,0 +1 @@
|
||||
/dev/null
|
||||
+1
@@ -0,0 +1 @@
|
||||
/dev/null
|
||||
@@ -0,0 +1 @@
|
||||
/dev/null
|
||||
@@ -0,0 +1,11 @@
|
||||
[Trigger]
|
||||
Operation = Install
|
||||
Operation = Upgrade
|
||||
Operation = Remove
|
||||
Type = Package
|
||||
Target = *
|
||||
|
||||
[Action]
|
||||
Description = Remembering the packages you installed...
|
||||
When = PostTransaction
|
||||
Exec = /usr/share/droiddeck/pacman/remember
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
[Trigger]
|
||||
Operation = Upgrade
|
||||
Type = Package
|
||||
Target = *
|
||||
|
||||
[Action]
|
||||
Description = Putting back files other DroidDeck software needs...
|
||||
When = PostTransaction
|
||||
Exec = /usr/share/droiddeck/pacman/keep restore
|
||||
@@ -0,0 +1,9 @@
|
||||
[Trigger]
|
||||
Operation = Upgrade
|
||||
Type = Package
|
||||
Target = *
|
||||
|
||||
[Action]
|
||||
Description = Saving files other DroidDeck software needs...
|
||||
When = PreTransaction
|
||||
Exec = /usr/share/droiddeck/pacman/keep save
|
||||
@@ -0,0 +1,11 @@
|
||||
[Trigger]
|
||||
Operation = Remove
|
||||
Type = Package
|
||||
Target = *
|
||||
|
||||
[Action]
|
||||
Description = Checking for files other DroidDeck software needs...
|
||||
When = PreTransaction
|
||||
Exec = /usr/share/droiddeck/pacman/shared
|
||||
NeedsTargets
|
||||
AbortOnFail
|
||||
@@ -0,0 +1,26 @@
|
||||
#!/bin/bash
|
||||
list=/var/lib/pacman/droiddeck-shared-files
|
||||
store=/var/lib/pacman/droiddeck-shared-keep
|
||||
[ -s "$list" ] || exit 0
|
||||
case $1 in
|
||||
save)
|
||||
mkdir -p "$store"
|
||||
while IFS= read -r path; do
|
||||
[ -e "$path" ] || [ -L "$path" ] || continue
|
||||
mkdir -p "$store${path%/*}"
|
||||
rm -f -- "$store$path"
|
||||
cp -a -- "$path" "$store$path"
|
||||
done < "$list"
|
||||
;;
|
||||
restore)
|
||||
[ -d "$store" ] || exit 0
|
||||
while IFS= read -r path; do
|
||||
[ -e "$path" ] || [ -L "$path" ] && continue
|
||||
[ -e "$store$path" ] || [ -L "$store$path" ] || continue
|
||||
mkdir -p "${path%/*}"
|
||||
cp -a -- "$store$path" "$path"
|
||||
done < "$list"
|
||||
rm -rf -- /var/lib/pacman/droiddeck-shared-keep
|
||||
;;
|
||||
esac
|
||||
exit 0
|
||||
@@ -0,0 +1,55 @@
|
||||
#!/usr/bin/python3
|
||||
import hashlib
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
|
||||
SHARE = "/usr/share/droiddeck/pacman"
|
||||
LIB = "/var/lib/pacman"
|
||||
STATE = os.path.join(LIB, "droiddeck-desktop")
|
||||
|
||||
|
||||
def digest(path):
|
||||
with open(path, "rb") as f:
|
||||
return hashlib.sha256(f.read()).hexdigest()
|
||||
|
||||
|
||||
def main():
|
||||
for path in ("/var/cache/pacman/pkg", os.path.join(LIB, "sync"), "/etc/pacman.d/hooks", "/var/log"):
|
||||
os.makedirs(path, exist_ok=True)
|
||||
stamp = digest(os.path.join(SHARE, "desktop-packages.txt")) + " " + digest(os.path.join(SHARE, "droiddeck.db"))
|
||||
try:
|
||||
with open(STATE) as f:
|
||||
if f.read().strip() == stamp:
|
||||
return 0
|
||||
except OSError:
|
||||
pass
|
||||
want = dict(line.split() for line in open(os.path.join(SHARE, "desktop-packages.txt")) if line.strip())
|
||||
local = os.path.join(LIB, "local")
|
||||
for entry in os.listdir(local):
|
||||
desc = os.path.join(local, entry, "desc")
|
||||
if not os.path.isfile(desc):
|
||||
continue
|
||||
name = version = None
|
||||
with open(desc, encoding="utf-8", errors="replace") as f:
|
||||
lines = f.read().split("\n")
|
||||
for i, line in enumerate(lines[:-1]):
|
||||
if line == "%NAME%":
|
||||
name = lines[i + 1]
|
||||
elif line == "%VERSION%":
|
||||
version = lines[i + 1]
|
||||
if name in want and version != want[name]:
|
||||
shutil.rmtree(os.path.join(local, entry))
|
||||
shutil.copyfile(os.path.join(SHARE, "droiddeck.db"), os.path.join(LIB, "sync", "droiddeck.db"))
|
||||
with open(STATE + ".tmp", "w") as f:
|
||||
f.write(stamp + "\n")
|
||||
os.replace(STATE + ".tmp", STATE)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
sys.exit(main())
|
||||
except OSError as e:
|
||||
print(f"error: could not prepare pacman's database: {e}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,5 @@
|
||||
#!/bin/bash
|
||||
packages=$(tr '\n' ' ')
|
||||
echo "error: ${packages% } came with DroidDeck, so pacman can't remove or replace it." >&2
|
||||
echo "error: DroidDeck updates these itself; packages you installed with pacman are yours to change." >&2
|
||||
exit 1
|
||||
@@ -0,0 +1,15 @@
|
||||
#!/bin/bash
|
||||
dir=/usr/share/droiddeck/pacman
|
||||
state=/root/.local/share/droiddeck/pacman
|
||||
mkdir -p "$state"
|
||||
if [ -z "${DROIDDECK_PACMAN_RESTORING:-}" ] && explicit=$(/usr/bin/pacman --config "$dir/pacman.conf" -Qqe 2>/dev/null); then
|
||||
printf '%s\n' "$explicit" | grep -vxF -f "$dir/system-packages.txt" > "$state/packages.txt.tmp"
|
||||
if [ $? -le 1 ] && [ -f "$state/packages.txt.tmp" ]; then
|
||||
mv -f "$state/packages.txt.tmp" "$state/packages.txt"
|
||||
else
|
||||
rm -f "$state/packages.txt.tmp"
|
||||
fi
|
||||
fi
|
||||
[ -s "$state/restored" ] || sha256sum "$dir/droiddeck.db" | cut -d' ' -f1 > "$state/restored"
|
||||
rm -f /var/cache/pacman/pkg/*.pkg.tar.* /var/cache/pacman/pkg/*.pkg.tar.*.sig 2>/dev/null
|
||||
exit 0
|
||||
@@ -0,0 +1,37 @@
|
||||
#!/bin/bash
|
||||
dir=/usr/share/droiddeck/pacman
|
||||
state=/root/.local/share/droiddeck/pacman
|
||||
list=$state/packages.txt
|
||||
log=/root/.cache/droiddeck/pacman-restore.log
|
||||
[ -s "$list" ] && [ -r "$dir/pacman.conf" ] || exit 0
|
||||
pacman() { /usr/local/bin/pacman "$@"; }
|
||||
"$dir/prepare" || exit 0
|
||||
snapshot=$(sha256sum "$dir/droiddeck.db" | cut -d' ' -f1)
|
||||
mapfile -t missing < <(grep -vxF -f <(pacman -Qq 2>/dev/null) "$list")
|
||||
done_for=$(cat "$state/restored" 2>/dev/null)
|
||||
[ ${#missing[@]} -eq 0 ] && [ "$done_for" = "$snapshot" ] && exit 0
|
||||
attempt="$snapshot ${missing[*]}"
|
||||
[ "$(cat "$state/attempted" 2>/dev/null)" = "$attempt" ] && exit 0
|
||||
tries=$(cat "$state/tries" 2>/dev/null)
|
||||
count=0
|
||||
[ "${tries#* }" = "$attempt" ] && count=${tries%% *}
|
||||
count=$((count + 1))
|
||||
echo "$count $attempt" > "$state/tries"
|
||||
[ "$count" -ge 3 ] && echo "$attempt" > "$state/attempted"
|
||||
export DROIDDECK_PACMAN_RESTORING=1
|
||||
mkdir -p "${log%/*}"
|
||||
notify() { notify-send -a DroidDeck -i system-software-update "$@" 2>/dev/null; }
|
||||
notify "Restoring your packages" "Reinstalling software you added with pacman after a DroidDeck update."
|
||||
export LD_PRELOAD="/usr/lib/droiddeck/libdroiddeck-root.so${LD_PRELOAD:+:$LD_PRELOAD}"
|
||||
{
|
||||
date
|
||||
ok=1
|
||||
[ "$done_for" = "$snapshot" ] || pacman -Su --noconfirm || ok=0
|
||||
[ ${#missing[@]} -eq 0 ] || pacman -S --needed --noconfirm "${missing[@]}" || ok=0
|
||||
} >> "$log" 2>&1
|
||||
if [ "$ok" = 1 ]; then
|
||||
echo "$snapshot" > "$state/restored"
|
||||
notify "Packages restored" "Your pacman packages are installed again."
|
||||
else
|
||||
notify "Some packages couldn't be restored" "See $log, then try sudo pacman -S in Konsole."
|
||||
fi
|
||||
@@ -0,0 +1,7 @@
|
||||
#!/bin/bash
|
||||
list=/var/lib/pacman/droiddeck-shared
|
||||
[ -s "$list" ] || exit 0
|
||||
mapfile -t packages < <(grep -xF -f "$list")
|
||||
[ ${#packages[@]} -eq 0 ] && exit 0
|
||||
echo "error: ${packages[*]} shares files with other DroidDeck software, so pacman can't remove it." >&2
|
||||
exit 1
|
||||
@@ -8,8 +8,8 @@ Third-party files in DroidDeck's KDE desktop package (tools/desktop-kde/overlay)
|
||||
- steam.svg: Papirus icon theme (https://github.com/PapirusDevelopmentTeam/papirus-icon-theme),
|
||||
GPL-3.0.
|
||||
|
||||
- kwin_wayland: KWin 6.8.0, GPL-2.0-or-later. Built with DroidDeck's nested desktop scale patch.
|
||||
Corresponding source: https://download.kde.org/stable/plasma/6.8.0/kwin-6.8.0.tar.xz and
|
||||
- kwin_wayland: KWin 6.8.2, GPL-2.0-or-later. Built with DroidDeck's nested desktop scale patch.
|
||||
Corresponding source: https://download.kde.org/stable/plasma/6.8.2/kwin-6.8.2.tar.xz and
|
||||
https://github.com/Droid-Deck/DroidDeck/tree/fix/kde-desktop-followups/tools/desktop-kde/patches
|
||||
(the source and patch hashes are recorded in desktop-kde.kwin.txt beside the package).
|
||||
|
||||
|
||||
+9
@@ -14,6 +14,14 @@ kickoff.currentConfigGroup = ["Shortcuts"];
|
||||
kickoff.writeConfig("global", "Alt+F1");
|
||||
kickoff.currentConfigGroup = ["General"];
|
||||
kickoff.writeConfig("icon", "distributor-logo-steamdeck");
|
||||
kickoff.writeConfig("favorites", [
|
||||
"preferred://browser",
|
||||
"applications:org.kde.dolphin.desktop",
|
||||
"applications:org.kde.konsole.desktop",
|
||||
"applications:org.kde.kate.desktop",
|
||||
"applications:org.kde.discover.desktop",
|
||||
"applications:systemsettings.desktop",
|
||||
]);
|
||||
|
||||
panel.addWidget("org.kde.plasma.pager");
|
||||
|
||||
@@ -24,6 +32,7 @@ tasks.writeConfig("launchers", [
|
||||
"preferred://filemanager",
|
||||
"preferred://browser",
|
||||
"applications:org.kde.konsole.desktop",
|
||||
"applications:org.kde.kate.desktop",
|
||||
]);
|
||||
|
||||
panel.addWidget("org.kde.plasma.marginsseparator");
|
||||
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
panels().forEach(function (panel) {
|
||||
panel.widgets("org.kde.plasma.icontasks").forEach(function (tasks) {
|
||||
tasks.currentConfigGroup = ["General"];
|
||||
var launchers = tasks.readConfig("launchers");
|
||||
if (typeof launchers === "string") launchers = launchers.length ? launchers.split(",") : [];
|
||||
if (launchers.indexOf("applications:org.kde.kate.desktop") < 0) {
|
||||
launchers.push("applications:org.kde.kate.desktop");
|
||||
tasks.writeConfig("launchers", launchers);
|
||||
}
|
||||
});
|
||||
});
|
||||
Executable
+258
@@ -0,0 +1,258 @@
|
||||
#!/usr/bin/env python3
|
||||
import base64
|
||||
import hashlib
|
||||
import io
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import time
|
||||
|
||||
REPOS = ("core", "extra", "alarm")
|
||||
FIELDS = ("NAME", "VERSION", "BASE", "DESC", "URL", "ARCH", "BUILDDATE", "INSTALLDATE", "PACKAGER", "SIZE",
|
||||
"GROUPS", "LICENSE", "VALIDATION", "REPLACES", "DEPENDS", "OPTDEPENDS", "CONFLICTS", "PROVIDES", "XDATA")
|
||||
PKGINFO = {"pkgname": "NAME", "pkgbase": "BASE", "pkgver": "VERSION", "pkgdesc": "DESC", "url": "URL",
|
||||
"builddate": "BUILDDATE", "packager": "PACKAGER", "size": "SIZE", "arch": "ARCH", "license": "LICENSE",
|
||||
"replaces": "REPLACES", "group": "GROUPS", "conflict": "CONFLICTS", "provides": "PROVIDES",
|
||||
"depend": "DEPENDS", "optdepend": "OPTDEPENDS", "xdata": "XDATA"}
|
||||
BLOCKED = re.compile(r"^(sudo|opendoas|doas|mkinitcpio.*|linux|linux-.*|.*-firmware|firmware-.*|grub|uboot-.*|"
|
||||
r"raspberrypi-.*|archlinuxarm-keyring|pacman|pacman-mirrorlist)$")
|
||||
ALARM = "http://mirror.archlinuxarm.org/aarch64"
|
||||
RELEASES = "https://github.com/Droid-Deck/DroidDeck-Components/releases/download"
|
||||
BUILDER = "68B3537F39A313B3E574D06777193F152BDBE6A6"
|
||||
|
||||
|
||||
def read_entry(path):
|
||||
fields, key = {}, None
|
||||
for name in ("desc", "depends"):
|
||||
file = os.path.join(path, name)
|
||||
if not os.path.exists(file):
|
||||
continue
|
||||
for line in open(file, encoding="utf-8", errors="replace"):
|
||||
line = line.rstrip("\n")
|
||||
if line.startswith("%") and line.endswith("%") and len(line) > 2:
|
||||
key = line.strip("%")
|
||||
fields[key] = []
|
||||
elif line == "":
|
||||
key = None
|
||||
elif key:
|
||||
fields[key].append(line)
|
||||
return fields
|
||||
|
||||
|
||||
def write_fields(fields, order):
|
||||
out = []
|
||||
for key in order:
|
||||
values = fields.get(key)
|
||||
if values:
|
||||
out.append("%" + key + "%\n" + "".join(v + "\n" for v in values))
|
||||
return "\n".join(out)
|
||||
|
||||
|
||||
def dep_name(dep):
|
||||
return re.split(r"[<>=]", dep, maxsplit=1)[0]
|
||||
|
||||
|
||||
def asset_name(name):
|
||||
return re.sub(r"[^A-Za-z0-9._-]", ".", name)
|
||||
|
||||
|
||||
def package_members(path):
|
||||
if path.endswith(".zst"):
|
||||
data = subprocess.run(["zstd", "-dc", path], check=True, stdout=subprocess.PIPE).stdout
|
||||
return tarfile.open(fileobj=io.BytesIO(data), mode="r:")
|
||||
return tarfile.open(path)
|
||||
|
||||
|
||||
def local_record(path, installed):
|
||||
with package_members(path) as tar:
|
||||
info, mtree, install, files = None, None, None, []
|
||||
for member in tar:
|
||||
name = member.name.removeprefix("./")
|
||||
if name == ".PKGINFO":
|
||||
info = tar.extractfile(member).read().decode("utf-8", "replace")
|
||||
elif name == ".MTREE":
|
||||
mtree = tar.extractfile(member).read()
|
||||
elif name == ".INSTALL":
|
||||
install = tar.extractfile(member).read()
|
||||
elif name in (".BUILDINFO", ".CHANGELOG") or not name:
|
||||
continue
|
||||
else:
|
||||
files.append(name.rstrip("/") + ("/" if member.isdir() else ""))
|
||||
if info is None or mtree is None:
|
||||
raise SystemExit(f"{path}: no .PKGINFO or .MTREE")
|
||||
fields, backup = {}, []
|
||||
for line in info.splitlines():
|
||||
if " = " not in line or line.startswith("#"):
|
||||
continue
|
||||
key, value = line.split(" = ", 1)
|
||||
if key == "backup":
|
||||
backup.append(value)
|
||||
elif key in PKGINFO:
|
||||
fields.setdefault(PKGINFO[key], []).append(value)
|
||||
fields["INSTALLDATE"] = [str(installed)]
|
||||
fields["VALIDATION"] = ["pgp"]
|
||||
for dir_ in sorted({f.rsplit("/", 1)[0] + "/" for f in files if "/" in f.rstrip("/")}):
|
||||
parts = dir_.rstrip("/").split("/")
|
||||
for i in range(1, len(parts) + 1):
|
||||
entry = "/".join(parts[:i]) + "/"
|
||||
if entry not in files:
|
||||
files.append(entry)
|
||||
sums = {}
|
||||
if backup:
|
||||
with package_members(path) as tar:
|
||||
for member in tar:
|
||||
name = member.name.removeprefix("./")
|
||||
if name in backup and member.isfile():
|
||||
sums[name] = hashlib.md5(tar.extractfile(member).read()).hexdigest()
|
||||
listing = "%FILES%\n" + "".join(f + "\n" for f in sorted(set(files)))
|
||||
if backup:
|
||||
listing += "\n%BACKUP%\n" + "".join(f"{b}\t{sums.get(b, '')}\n" for b in backup)
|
||||
return fields, listing, mtree, install
|
||||
|
||||
|
||||
def fetch(dest, *urls):
|
||||
for url in urls:
|
||||
if subprocess.run(["curl", "-fsSL", "--retry", "6", "--retry-delay", "5", "--retry-all-errors",
|
||||
"-o", dest, url]).returncode == 0:
|
||||
return
|
||||
raise SystemExit(f"could not download {os.path.basename(dest)}")
|
||||
|
||||
|
||||
def main():
|
||||
dbdir, cache, pkglist, runtime_file, mirror_file, tag, root, repo = sys.argv[1:9]
|
||||
here = os.path.dirname(os.path.abspath(__file__))
|
||||
installed = int(os.environ.get("SOURCE_DATE_EPOCH", time.time()))
|
||||
|
||||
entries = {}
|
||||
for source, path in [("extra", os.path.join(here, "pins"))] + [(r, os.path.join(dbdir, "x_" + r)) for r in REPOS]:
|
||||
for entry in sorted(os.listdir(path)):
|
||||
fields = read_entry(os.path.join(path, entry))
|
||||
name = fields.get("NAME", [None])[0]
|
||||
if name and name not in entries:
|
||||
entries[name] = (source, fields)
|
||||
by_file = {fields["FILENAME"][0]: name for name, (_, fields) in entries.items()}
|
||||
|
||||
runtime = dict(line.split() for line in open(runtime_file) if len(line.split()) == 2)
|
||||
shipped = {}
|
||||
for line in open(pkglist):
|
||||
file = line.split()[0].split("/", 1)[1]
|
||||
shipped[by_file[file]] = file
|
||||
|
||||
local = os.path.join(root, "var/lib/pacman/local")
|
||||
os.makedirs(local, exist_ok=True)
|
||||
for name, file in sorted(shipped.items()):
|
||||
fields, listing, mtree, install = local_record(os.path.join(cache, file), installed)
|
||||
if fields["NAME"][0] != name:
|
||||
raise SystemExit(f"{file}: .PKGINFO names {fields['NAME'][0]}, not {name}")
|
||||
record = os.path.join(local, f"{name}-{fields['VERSION'][0]}")
|
||||
os.makedirs(record, exist_ok=True)
|
||||
with open(os.path.join(record, "desc"), "w") as out:
|
||||
out.write(write_fields(fields, FIELDS))
|
||||
with open(os.path.join(record, "files"), "w") as out:
|
||||
out.write(listing)
|
||||
with open(os.path.join(record, "mtree"), "wb") as out:
|
||||
out.write(mtree)
|
||||
if install:
|
||||
with open(os.path.join(record, "install"), "wb") as out:
|
||||
out.write(install)
|
||||
|
||||
system = set(runtime) | set(shipped)
|
||||
available = {n for n in entries if not BLOCKED.match(n)} | system
|
||||
providers = {}
|
||||
for name in available:
|
||||
if name in entries:
|
||||
for p in entries[name][1].get("PROVIDES", []):
|
||||
providers.setdefault(dep_name(p), name)
|
||||
satisfied = set(system)
|
||||
for name in system:
|
||||
if name in entries:
|
||||
satisfied.update(dep_name(p) for p in entries[name][1].get("PROVIDES", []))
|
||||
|
||||
wanted = [l.strip() for l in open(mirror_file) if l.strip() and not l.startswith("#")]
|
||||
mirrored, queue = set(), list(wanted)
|
||||
while queue:
|
||||
dep = dep_name(queue.pop())
|
||||
if dep in satisfied:
|
||||
continue
|
||||
name = dep if dep in available and dep in entries else providers.get(dep)
|
||||
if name is None:
|
||||
raise SystemExit(f"mirror.txt: nothing in the repository provides {dep}")
|
||||
if name in mirrored or name in system:
|
||||
continue
|
||||
mirrored.add(name)
|
||||
queue.extend(entries[name][1].get("DEPENDS", []))
|
||||
|
||||
os.makedirs(repo, exist_ok=True)
|
||||
for name in sorted(mirrored):
|
||||
source, fields = entries[name]
|
||||
file = fields["FILENAME"][0]
|
||||
dest = os.path.join(repo, asset_name(file))
|
||||
if not os.path.exists(dest) or hashlib.sha256(open(dest, "rb").read()).hexdigest() != fields["SHA256SUM"][0]:
|
||||
fetch(dest, f"{ALARM}/{source}/{file}")
|
||||
if hashlib.sha256(open(dest, "rb").read()).hexdigest() != fields["SHA256SUM"][0]:
|
||||
raise SystemExit(f"{file}: sha256 differs from the repository database's")
|
||||
signature = fields.get("PGPSIG", [None])[0]
|
||||
sig = dest + ".sig"
|
||||
if signature:
|
||||
with open(sig, "wb") as out:
|
||||
out.write(base64.b64decode(signature))
|
||||
else:
|
||||
fetch(sig, f"{ALARM}/{source}/{file}.sig")
|
||||
check = subprocess.run(["gpgv", "--status-fd", "1", "--keyring", os.path.join(here, "archlinuxarm-builder.gpg"),
|
||||
sig, dest], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True).stdout
|
||||
if not re.search(rf"^\[GNUPG:\] VALIDSIG .* {BUILDER}$", check, re.M):
|
||||
raise SystemExit(f"{file}: no valid Arch Linux ARM Build System signature")
|
||||
if not signature:
|
||||
fields["PGPSIG"] = [base64.b64encode(open(sig, "rb").read()).decode()]
|
||||
os.remove(sig)
|
||||
print(f"pacman: {len(shipped)} install records, {len(mirrored)} mirrored packages, "
|
||||
f"{sum(os.path.getsize(os.path.join(repo, asset_name(entries[n][1]['FILENAME'][0]))) for n in mirrored) // 1048576} MiB")
|
||||
|
||||
order = ["FILENAME", "NAME", "BASE", "VERSION", "DESC", "GROUPS", "CSIZE", "ISIZE", "MD5SUM", "SHA256SUM", "PGPSIG",
|
||||
"URL", "LICENSE", "ARCH", "BUILDDATE", "PACKAGER", "REPLACES", "CONFLICTS", "PROVIDES", "DEPENDS",
|
||||
"OPTDEPENDS", "MAKEDEPENDS", "CHECKDEPENDS", "XDATA"]
|
||||
buffer = io.BytesIO()
|
||||
with tarfile.open(fileobj=buffer, mode="w:gz", format=tarfile.GNU_FORMAT) as db:
|
||||
for name in sorted(available):
|
||||
if name in entries and (name not in runtime or name in shipped or runtime[name] == entries[name][1]["VERSION"][0]):
|
||||
fields = dict(entries[name][1])
|
||||
else:
|
||||
fields = {"FILENAME": [f"{name}-{runtime[name]}-aarch64.pkg.tar.xz"], "NAME": [name],
|
||||
"VERSION": [runtime[name]], "ARCH": ["aarch64"]}
|
||||
if name in mirrored:
|
||||
fields["FILENAME"] = [asset_name(fields["FILENAME"][0])]
|
||||
data = write_fields(fields, order).encode()
|
||||
folder = f"{name}-{fields['VERSION'][0]}"
|
||||
info = tarfile.TarInfo(folder)
|
||||
info.type, info.mode, info.mtime = tarfile.DIRTYPE, 0o755, installed
|
||||
db.addfile(info)
|
||||
info = tarfile.TarInfo(folder + "/desc")
|
||||
info.size, info.mode, info.mtime = len(data), 0o644, installed
|
||||
db.addfile(info, io.BytesIO(data))
|
||||
with open(os.path.join(repo, "droiddeck.db"), "wb") as out:
|
||||
out.write(buffer.getvalue())
|
||||
|
||||
share = os.path.join(root, "usr/share/droiddeck/pacman")
|
||||
os.makedirs(os.path.join(share, "hooks"), exist_ok=True)
|
||||
with open(os.path.join(share, "droiddeck.db"), "wb") as out:
|
||||
out.write(buffer.getvalue())
|
||||
with open(os.path.join(share, "system-packages.txt"), "w") as out:
|
||||
out.write("".join(n + "\n" for n in sorted(system)))
|
||||
with open(os.path.join(share, "desktop-packages.txt"), "w") as out:
|
||||
out.write("".join(f"{n} {entries[n][1]['VERSION'][0]}\n" for n in sorted(shipped)))
|
||||
with open(os.path.join(share, "hooks", "droiddeck-system.hook"), "w") as out:
|
||||
out.write("[Trigger]\nOperation = Upgrade\nOperation = Remove\nType = Package\n")
|
||||
out.write("".join(f"Target = {n}\n" for n in sorted(system)))
|
||||
out.write("\n[Action]\nDescription = Keeping the packages DroidDeck installed...\nWhen = PreTransaction\n"
|
||||
"Exec = /usr/share/droiddeck/pacman/refuse\nNeedsTargets\nAbortOnFail\n")
|
||||
server = f"{RELEASES}/{tag}" if tag else f"{RELEASES}/unpublished"
|
||||
template = open(os.path.join(here, "pacman.conf.in")).read()
|
||||
with open(os.path.join(share, "pacman.conf"), "w") as out:
|
||||
out.write(template.replace("@SERVER@", server).replace("@ALARM@", ALARM))
|
||||
print(f"pacman: repository {server}, {len(available)} packages ({len(system)} installed by DroidDeck)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,22 @@
|
||||
[options]
|
||||
RootDir = /
|
||||
DBPath = /var/lib/pacman/
|
||||
CacheDir = /var/cache/pacman/pkg/
|
||||
LogFile = /var/log/pacman.log
|
||||
GPGDir = /etc/pacman.d/gnupg/
|
||||
HookDir = /etc/pacman.d/hooks/
|
||||
HookDir = /usr/share/droiddeck/pacman/hooks/
|
||||
HoldPkg = pacman glibc
|
||||
Architecture = aarch64
|
||||
Color
|
||||
ParallelDownloads = 4
|
||||
DisableSandbox
|
||||
SigLevel = Required DatabaseOptional
|
||||
LocalFileSigLevel = Optional
|
||||
NoExtract = usr/share/doc/* usr/share/gtk-doc/* usr/share/help/*
|
||||
|
||||
[droiddeck]
|
||||
Server = @SERVER@
|
||||
CacheServer = @ALARM@/extra
|
||||
CacheServer = @ALARM@/core
|
||||
CacheServer = @ALARM@/alarm
|
||||
@@ -0,0 +1,67 @@
|
||||
--- a/src/backends/wayland/wayland_backend.cpp
|
||||
+++ b/src/backends/wayland/wayland_backend.cpp
|
||||
@@ -30,6 +30,9 @@
|
||||
|
||||
#include <QAbstractEventDispatcher>
|
||||
|
||||
+#include <array>
|
||||
+#include <memory>
|
||||
+
|
||||
#include <drm_fourcc.h>
|
||||
#include <fcntl.h>
|
||||
#include <gbm.h>
|
||||
@@ -124,8 +127,31 @@
|
||||
}
|
||||
Q_EMIT pointerButtonChanged(button, state, std::chrono::milliseconds(time), this);
|
||||
});
|
||||
- // TODO: Send discreteDelta and source as well.
|
||||
- connect(pointer, &Pointer::axisChanged, this, [this](quint32 time, Pointer::Axis nativeAxis, qreal delta) {
|
||||
+ auto axisSource = std::make_shared<PointerAxisSource>(PointerAxisSource::Unknown);
|
||||
+ auto axisDiscrete = std::make_shared<std::array<qint32, 2>>();
|
||||
+ connect(pointer, &Pointer::axisSourceChanged, this, [axisSource](Pointer::AxisSource source) {
|
||||
+ switch (source) {
|
||||
+ case Pointer::AxisSource::Wheel:
|
||||
+ *axisSource = PointerAxisSource::Wheel;
|
||||
+ break;
|
||||
+ case Pointer::AxisSource::Finger:
|
||||
+ *axisSource = PointerAxisSource::Finger;
|
||||
+ break;
|
||||
+ case Pointer::AxisSource::Continuous:
|
||||
+ *axisSource = PointerAxisSource::Continuous;
|
||||
+ break;
|
||||
+ case Pointer::AxisSource::WheelTilt:
|
||||
+ *axisSource = PointerAxisSource::WheelTilt;
|
||||
+ break;
|
||||
+ default:
|
||||
+ *axisSource = PointerAxisSource::Unknown;
|
||||
+ break;
|
||||
+ }
|
||||
+ });
|
||||
+ connect(pointer, &Pointer::axisDiscreteChanged, this, [axisDiscrete](Pointer::Axis nativeAxis, qint32 discreteDelta) {
|
||||
+ (*axisDiscrete)[nativeAxis == Pointer::Axis::Vertical ? 0 : 1] = discreteDelta * 120;
|
||||
+ });
|
||||
+ connect(pointer, &Pointer::axisChanged, this, [this, axisSource, axisDiscrete](quint32 time, Pointer::Axis nativeAxis, qreal delta) {
|
||||
PointerAxis axis;
|
||||
switch (nativeAxis) {
|
||||
case Pointer::Axis::Horizontal:
|
||||
@@ -137,10 +163,18 @@
|
||||
default:
|
||||
Q_UNREACHABLE();
|
||||
}
|
||||
- Q_EMIT pointerAxisChanged(axis, delta, 0, PointerAxisSource::Unknown, false, false, std::chrono::milliseconds(time), this);
|
||||
+ qint32 &discrete = (*axisDiscrete)[nativeAxis == Pointer::Axis::Vertical ? 0 : 1];
|
||||
+ Q_EMIT pointerAxisChanged(axis, delta, discrete, *axisSource, false, false, std::chrono::milliseconds(time), this);
|
||||
+ discrete = 0;
|
||||
+ });
|
||||
+ connect(pointer, &Pointer::axisStopped, this, [this, axisSource](quint32 time, Pointer::Axis nativeAxis) {
|
||||
+ const PointerAxis axis = nativeAxis == Pointer::Axis::Vertical ? PointerAxis::Vertical : PointerAxis::Horizontal;
|
||||
+ Q_EMIT pointerAxisChanged(axis, 0, 0, *axisSource, false, false, std::chrono::milliseconds(time), this);
|
||||
});
|
||||
|
||||
- connect(pointer, &Pointer::frame, this, [this]() {
|
||||
+ connect(pointer, &Pointer::frame, this, [this, axisSource, axisDiscrete]() {
|
||||
+ *axisSource = PointerAxisSource::Unknown;
|
||||
+ axisDiscrete->fill(0);
|
||||
Q_EMIT pointerFrame(this);
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
DESKTOP_KDE_REPO=Droid-Deck/DroidDeck-Components
|
||||
DESKTOP_KDE_TAG=desktop-kde-r2
|
||||
DESKTOP_KDE_SHA256=9ba832677b498654136c69d8c8330434d17e4d53cd099acac9bde3ba429b35bf
|
||||
DESKTOP_KDE_SIZE=846933224
|
||||
DESKTOP_KDE_TAG=desktop-kde-r3
|
||||
DESKTOP_KDE_SHA256=8b7142fcec8d86143ae39fc14ffc86907d30d9a5b5a45f49cb1b55109d6fc4eb
|
||||
DESKTOP_KDE_SIZE=972598429
|
||||
@@ -4,6 +4,7 @@
|
||||
Usage: removal-manifests.py <LXQt tar.zst> <KDE r1 tar.zst> <KDE r2 tar.zst>
|
||||
<emulators tar.zst> <verified KDE package cache> <output dir>
|
||||
<verified LXQt package cache>
|
||||
removal-manifests.py --add <KDE tar.zst> <tag> <sha256> <verified KDE package cache> <output dir>
|
||||
Removal includes desktop applications/themes and our overlay, not their shared dependencies.
|
||||
The KDE cache is verified against the published desktop-kde.packages.txt before use.
|
||||
The LXQt cache contains the signed application packages listed by desktop.packages.txt;
|
||||
@@ -63,10 +64,7 @@ def write(out, name, records):
|
||||
gz.write(('\n'.join(sorted(set(records))) + '\n').encode())
|
||||
|
||||
|
||||
def main():
|
||||
archives = [pathlib.Path(p) for p in sys.argv[1:5]]
|
||||
cache, out, legacy_cache = map(pathlib.Path, sys.argv[5:8])
|
||||
here = pathlib.Path(__file__).resolve().parent
|
||||
def application_paths(here, cache):
|
||||
seeds = {line.strip() for line in (here / 'seeds.txt').read_text().splitlines() if line.strip() and not line.startswith('#')} - SHARED_SEEDS
|
||||
packages = dict(line.split() for line in (cache / 'desktop-kde.packages.txt').read_text().splitlines())
|
||||
selected = set()
|
||||
@@ -79,10 +77,39 @@ def main():
|
||||
if sha(archive) != digest:
|
||||
raise ValueError(f'{filename}: source package checksum mismatch')
|
||||
with tarfile.open(archive) as tar:
|
||||
selected.update(e.name.removeprefix('./').rstrip('/') for e in tar if not e.isdir())
|
||||
selected.update(e.name.removeprefix('./').rstrip('/') for e in tar if not e.isdir() and not e.name.removeprefix('./').startswith('.'))
|
||||
found.add(package)
|
||||
assert found == seeds, f'missing desktop packages: {seeds - found}'
|
||||
selected.update(str(p.relative_to(here / 'overlay')) for p in (here / 'overlay').rglob('*') if p.is_file())
|
||||
selected.update(str(p.relative_to(here / 'overlay')) for p in (here / 'overlay').rglob('*') if p.is_file() or p.is_symlink())
|
||||
return selected, packages, seeds
|
||||
|
||||
|
||||
def add(archive, tag, digest, cache, out):
|
||||
here = pathlib.Path(__file__).resolve().parent
|
||||
selected, packages, seeds = application_paths(here, cache)
|
||||
inv = inventory(archive, digest)
|
||||
generated = ('usr/share/droiddeck/pacman/', 'usr/lib/droiddeck/')
|
||||
remove = gzip.decompress((out / 'kde-remove.tsv.gzip').read_bytes()).decode().splitlines()
|
||||
keep = gzip.decompress((out / 'kde-keep.txt.gzip').read_bytes()).decode().splitlines()
|
||||
remove += [record for path, record in inv.items() if path in selected or path.startswith(generated)]
|
||||
keep += list(inv)
|
||||
write(out, 'kde-remove.tsv.gzip', remove)
|
||||
write(out, 'kde-keep.txt.gzip', keep)
|
||||
versions = (out / 'versions.txt').read_text().split()
|
||||
(out / 'versions.txt').write_text('\n'.join(dict.fromkeys(versions + [tag])) + '\n')
|
||||
sources = json.loads((out / 'sources.json').read_text())
|
||||
sources['archives'][tag] = digest
|
||||
sources['desktopApplications'] = {n: h for n, h in packages.items() if n.rsplit('-', 3)[0] in seeds}
|
||||
(out / 'sources.json').write_text(json.dumps(sources, indent=2) + '\n')
|
||||
print(tag, digest)
|
||||
print('KDE removable paths', sum(path in selected or path.startswith(generated) for path in inv))
|
||||
|
||||
|
||||
def main():
|
||||
archives = [pathlib.Path(p) for p in sys.argv[1:5]]
|
||||
cache, out, legacy_cache = map(pathlib.Path, sys.argv[5:8])
|
||||
here = pathlib.Path(__file__).resolve().parent
|
||||
selected, packages, seeds = application_paths(here, cache)
|
||||
inventories = [inventory(p, pin[1]) for p, pin in zip(archives, PINS)]
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
legacy_seeds = {line.strip() for line in (here / 'lxqt-applications.txt').read_text().splitlines()
|
||||
@@ -115,4 +142,7 @@ def main():
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
if sys.argv[1:2] == ['--add']:
|
||||
add(pathlib.Path(sys.argv[2]), sys.argv[3], sys.argv[4], pathlib.Path(sys.argv[5]), pathlib.Path(sys.argv[6]))
|
||||
else:
|
||||
main()
|
||||
@@ -0,0 +1,190 @@
|
||||
#define _GNU_SOURCE
|
||||
#include <dlfcn.h>
|
||||
#include <errno.h>
|
||||
#include <grp.h>
|
||||
#include <pwd.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <sys/types.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#define REAL(name) static __typeof__(name) *real_##name; if (!real_##name) real_##name = dlsym(RTLD_NEXT, #name)
|
||||
|
||||
static uid_t real_uid(void) { return (uid_t)syscall(SYS_getuid); }
|
||||
static gid_t real_gid(void) { return (gid_t)syscall(SYS_getgid); }
|
||||
|
||||
uid_t getuid(void) { return 0; }
|
||||
uid_t geteuid(void) { return 0; }
|
||||
gid_t getgid(void) { return 0; }
|
||||
gid_t getegid(void) { return 0; }
|
||||
|
||||
int getresuid(uid_t *r, uid_t *e, uid_t *s) {
|
||||
if (r) *r = 0;
|
||||
if (e) *e = 0;
|
||||
if (s) *s = 0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int getresgid(gid_t *r, gid_t *e, gid_t *s) {
|
||||
if (r) *r = 0;
|
||||
if (e) *e = 0;
|
||||
if (s) *s = 0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int setuid(uid_t u) { (void)u; return 0; }
|
||||
int seteuid(uid_t u) { (void)u; return 0; }
|
||||
int setgid(gid_t g) { (void)g; return 0; }
|
||||
int setegid(gid_t g) { (void)g; return 0; }
|
||||
int setreuid(uid_t r, uid_t e) { (void)r; (void)e; return 0; }
|
||||
int setregid(gid_t r, gid_t e) { (void)r; (void)e; return 0; }
|
||||
int setresuid(uid_t r, uid_t e, uid_t s) { (void)r; (void)e; (void)s; return 0; }
|
||||
int setresgid(gid_t r, gid_t e, gid_t s) { (void)r; (void)e; (void)s; return 0; }
|
||||
int setgroups(size_t n, const gid_t *list) { (void)n; (void)list; return 0; }
|
||||
int initgroups(const char *user, gid_t group) { (void)user; (void)group; return 0; }
|
||||
|
||||
static int owner_result(int rc) {
|
||||
if (rc != 0 && (errno == EPERM || errno == EINVAL)) {
|
||||
errno = 0;
|
||||
return 0;
|
||||
}
|
||||
return rc;
|
||||
}
|
||||
|
||||
int chown(const char *path, uid_t u, gid_t g) {
|
||||
REAL(chown);
|
||||
return owner_result(real_chown(path, u, g));
|
||||
}
|
||||
|
||||
int lchown(const char *path, uid_t u, gid_t g) {
|
||||
REAL(lchown);
|
||||
return owner_result(real_lchown(path, u, g));
|
||||
}
|
||||
|
||||
int fchown(int fd, uid_t u, gid_t g) {
|
||||
REAL(fchown);
|
||||
return owner_result(real_fchown(fd, u, g));
|
||||
}
|
||||
|
||||
int fchownat(int dirfd, const char *path, uid_t u, gid_t g, int flags) {
|
||||
REAL(fchownat);
|
||||
return owner_result(real_fchownat(dirfd, path, u, g, flags));
|
||||
}
|
||||
|
||||
static struct passwd *as_root_user(struct passwd *pw) {
|
||||
if (pw && pw->pw_uid == real_uid()) {
|
||||
pw->pw_uid = 0;
|
||||
pw->pw_gid = 0;
|
||||
}
|
||||
return pw;
|
||||
}
|
||||
|
||||
static struct group *as_root_group(struct group *gr) {
|
||||
if (gr && gr->gr_gid == real_gid()) gr->gr_gid = 0;
|
||||
return gr;
|
||||
}
|
||||
|
||||
struct passwd *getpwuid(uid_t uid) {
|
||||
REAL(getpwuid);
|
||||
return as_root_user(real_getpwuid(uid == 0 ? real_uid() : uid));
|
||||
}
|
||||
|
||||
struct passwd *getpwnam(const char *name) {
|
||||
REAL(getpwnam);
|
||||
return as_root_user(real_getpwnam(name));
|
||||
}
|
||||
|
||||
struct passwd *getpwent(void) {
|
||||
REAL(getpwent);
|
||||
return as_root_user(real_getpwent());
|
||||
}
|
||||
|
||||
int getpwuid_r(uid_t uid, struct passwd *pw, char *buf, size_t len, struct passwd **out) {
|
||||
REAL(getpwuid_r);
|
||||
int rc = real_getpwuid_r(uid == 0 ? real_uid() : uid, pw, buf, len, out);
|
||||
if (rc == 0) as_root_user(*out);
|
||||
return rc;
|
||||
}
|
||||
|
||||
int getpwnam_r(const char *name, struct passwd *pw, char *buf, size_t len, struct passwd **out) {
|
||||
REAL(getpwnam_r);
|
||||
int rc = real_getpwnam_r(name, pw, buf, len, out);
|
||||
if (rc == 0) as_root_user(*out);
|
||||
return rc;
|
||||
}
|
||||
|
||||
struct group *getgrgid(gid_t gid) {
|
||||
REAL(getgrgid);
|
||||
return as_root_group(real_getgrgid(gid == 0 ? real_gid() : gid));
|
||||
}
|
||||
|
||||
struct group *getgrnam(const char *name) {
|
||||
REAL(getgrnam);
|
||||
return as_root_group(real_getgrnam(name));
|
||||
}
|
||||
|
||||
int getgrgid_r(gid_t gid, struct group *gr, char *buf, size_t len, struct group **out) {
|
||||
REAL(getgrgid_r);
|
||||
int rc = real_getgrgid_r(gid == 0 ? real_gid() : gid, gr, buf, len, out);
|
||||
if (rc == 0) as_root_group(*out);
|
||||
return rc;
|
||||
}
|
||||
|
||||
int getgrnam_r(const char *name, struct group *gr, char *buf, size_t len, struct group **out) {
|
||||
REAL(getgrnam_r);
|
||||
int rc = real_getgrnam_r(name, gr, buf, len, out);
|
||||
if (rc == 0) as_root_group(*out);
|
||||
return rc;
|
||||
}
|
||||
|
||||
static int shown_mode(int rc, struct stat *st) {
|
||||
if (rc == 0 && S_ISDIR(st->st_mode) && (st->st_mode & 0777) == 0700) st->st_mode = (st->st_mode & ~0777) | 0755;
|
||||
return rc;
|
||||
}
|
||||
|
||||
int stat(const char *path, struct stat *st) {
|
||||
REAL(stat);
|
||||
return shown_mode(real_stat(path, st), st);
|
||||
}
|
||||
|
||||
int lstat(const char *path, struct stat *st) {
|
||||
REAL(lstat);
|
||||
return shown_mode(real_lstat(path, st), st);
|
||||
}
|
||||
|
||||
int fstat(int fd, struct stat *st) {
|
||||
REAL(fstat);
|
||||
return shown_mode(real_fstat(fd, st), st);
|
||||
}
|
||||
|
||||
int fstatat(int dirfd, const char *path, struct stat *st, int flags) {
|
||||
REAL(fstatat);
|
||||
return shown_mode(real_fstatat(dirfd, path, st, flags), st);
|
||||
}
|
||||
|
||||
int statx(int dirfd, const char *path, int flags, unsigned int mask, struct statx *st) {
|
||||
REAL(statx);
|
||||
int rc = real_statx(dirfd, path, flags, mask, st);
|
||||
if (rc == 0 && S_ISDIR(st->stx_mode) && (st->stx_mode & 0777) == 0700) st->stx_mode = (st->stx_mode & ~0777) | 0755;
|
||||
return rc;
|
||||
}
|
||||
|
||||
int stat64(const char *path, struct stat64 *st) {
|
||||
REAL(stat64);
|
||||
return shown_mode(real_stat64(path, st), (struct stat *)st);
|
||||
}
|
||||
|
||||
int lstat64(const char *path, struct stat64 *st) {
|
||||
REAL(lstat64);
|
||||
return shown_mode(real_lstat64(path, st), (struct stat *)st);
|
||||
}
|
||||
|
||||
int fstat64(int fd, struct stat64 *st) {
|
||||
REAL(fstat64);
|
||||
return shown_mode(real_fstat64(fd, st), (struct stat *)st);
|
||||
}
|
||||
|
||||
int fstatat64(int dirfd, const char *path, struct stat64 *st, int flags) {
|
||||
REAL(fstatat64);
|
||||
return shown_mode(real_fstatat64(dirfd, path, st, flags), (struct stat *)st);
|
||||
}
|
||||
@@ -26,3 +26,23 @@ noto-fonts-emoji
|
||||
xdg-utils
|
||||
firefox
|
||||
mpv
|
||||
zip
|
||||
unzip
|
||||
7zip
|
||||
unrar
|
||||
less
|
||||
man-db
|
||||
man-pages
|
||||
htop
|
||||
wl-clipboard
|
||||
xclip
|
||||
git
|
||||
wget
|
||||
kcalc
|
||||
okular
|
||||
filelight
|
||||
kfind
|
||||
plasma-systemmonitor
|
||||
elisa
|
||||
discover
|
||||
flatpak-kcm
|
||||
@@ -15,7 +15,7 @@ fetch() {
|
||||
local name=$1 sha=$2 kept="${cache}/$2-$1" part
|
||||
if ! echo "${sha} ${kept}" | sha256sum -c - >/dev/null 2>&1; then
|
||||
part=$(mktemp "${kept}.part.XXXXXX")
|
||||
curl -fsSL --retry 3 -o "${part}" \
|
||||
curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "${part}" \
|
||||
"https://github.com/${DIRECTAUDIO_REPO}/releases/download/${DIRECTAUDIO_TAG}/${name}"
|
||||
echo "${sha} ${part}" | sha256sum -c - >/dev/null || { echo "${name}: checksum mismatch" >&2; rm -f "${part}"; exit 1; }
|
||||
mv "${part}" "${kept}"
|
||||
@@ -26,7 +26,7 @@ fetch directaudio-linux-wine11.zip "${DIRECTAUDIO_WINE11_SHA256}"
|
||||
fetch directaudio-linux-wine11-systhread.zip "${DIRECTAUDIO_SYSTHREAD_SHA256}"
|
||||
source_archive="${cache}/${DIRECTAUDIO_SOURCE_SHA256}-directaudio-source.tar.gz"
|
||||
if ! echo "${DIRECTAUDIO_SOURCE_SHA256} ${source_archive}" | sha256sum -c - >/dev/null 2>&1; then
|
||||
curl -fsSL --retry 3 -o "${work}/source.tar.gz" \
|
||||
curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "${work}/source.tar.gz" \
|
||||
"https://github.com/${DIRECTAUDIO_REPO}/archive/${DIRECTAUDIO_SOURCE_COMMIT}.tar.gz"
|
||||
echo "${DIRECTAUDIO_SOURCE_SHA256} ${work}/source.tar.gz" | sha256sum -c - >/dev/null
|
||||
mv "${work}/source.tar.gz" "${source_archive}"
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
# Sourced by the build scripts: picks the Docker platform and the matching cross-build image.
|
||||
docker_platform=${DROIDDECK_DOCKER_PLATFORM:-}
|
||||
if [[ -z "${docker_platform}" ]]; then
|
||||
case "$(uname -m)" in arm64|aarch64) docker_platform=linux/arm64 ;; *) docker_platform=linux/amd64 ;; esac
|
||||
fi
|
||||
case "${docker_platform}" in linux/arm64|linux/arm64/*) docker_platform=linux/arm64 ;; esac
|
||||
if [[ -z "${DROIDDECK_BUILD_IMAGE:-}" ]]; then
|
||||
DROIDDECK_BUILD_IMAGE=droiddeck-local-cross:24.04-v3
|
||||
[[ "${docker_platform}" == linux/arm64 ]] && DROIDDECK_BUILD_IMAGE+=-arm64
|
||||
fi
|
||||
export DROIDDECK_DOCKER_PLATFORM=${docker_platform} DROIDDECK_BUILD_IMAGE
|
||||
@@ -1,4 +1,5 @@
|
||||
"""Check the engine before modifying build assets; never rebuild for a daemon error."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
@@ -20,5 +21,5 @@ if __name__ == '__main__':
|
||||
if 'No such image' not in image.stderr and 'image not known' not in image.stderr: # Docker, Podman
|
||||
sys.exit('Cannot inspect the build image: ' + image.stderr.strip())
|
||||
repo = Path(__file__).resolve().parents[1]
|
||||
subprocess.run(['docker', 'build', '--platform', 'linux/amd64', '-t', sys.argv[1],
|
||||
subprocess.run(['docker', 'build', '--platform', os.environ.get('DROIDDECK_DOCKER_PLATFORM', 'linux/amd64'), '-t', sys.argv[1],
|
||||
'-f', str(repo / 'tools/local-cross.Dockerfile'), str(repo)], check=True)
|
||||
@@ -199,3 +199,13 @@ is marked done at once - no duplicate fence, no epoll add or delete, no waiter w
|
||||
loop handles it in the same pass, after the import (FIFO commits still wait for a vblank). The
|
||||
`commit_ready_check` convar (default on, `gamescopectl commit_ready_check 0`) turns it off; the
|
||||
`xwm` log counts fences ready at import and waited for, every 10 s.
|
||||
|
||||
## 0125 steamcompmgr: share mangoapp's frame times with DroidDeck's HUD
|
||||
|
||||
DroidDeck's in-app HUD shows the same frame rate and frame times as Steam's performance overlay.
|
||||
DroidDeck's mangoapp (Valve's 20260902.1 build) reads the field at byte 16 of gamescope's messages as
|
||||
its frame time; gamescope 3.16.29 puts `app_frametime_ns` there, the time between signalled commits of
|
||||
the connector's windows (`mangoapp_nudge_app_frame`). With `DROIDDECK_HUD_FRAMES` set (droiddeck-session
|
||||
sets `/run/droiddeck-hud/frames`), gamescope maps that file and writes the same commits of connector 0,
|
||||
whether or not a mangoapp runs, plus the focused pid, output size, refresh, Steam focus and engine name.
|
||||
The layout is in the comment above `droiddeck_hud_frames_map`; the app reads it in `hudframes.c`.
|
||||
@@ -0,0 +1,227 @@
|
||||
diff --git a/src/commit.cpp b/src/commit.cpp
|
||||
index f2e0f0c..fbfb550 100644
|
||||
--- a/src/commit.cpp
|
||||
+++ b/src/commit.cpp
|
||||
@@ -86,6 +86,8 @@ void commit_t::Signal()
|
||||
mangoapp_nudge_app_frame( k_uMangoappLegacyMsgType, now );
|
||||
if ( m_uMangoMsgType != 0 )
|
||||
mangoapp_nudge_app_frame( m_uMangoMsgType, now );
|
||||
+ if ( m_bDroidDeckHudFrame )
|
||||
+ droiddeck_hud_app_frame( now );
|
||||
}
|
||||
|
||||
void commit_t::OnPollHangUp()
|
||||
@@ -113,7 +115,7 @@ bool commit_t::CloseFenceInternal()
|
||||
return true;
|
||||
}
|
||||
|
||||
-void commit_t::SetFence( int nFence, bool bMangoNudge, uint32_t uMangoMsgType, const std::shared_ptr<CommitDoneList_t> &pDoneCommits )
|
||||
+void commit_t::SetFence( int nFence, bool bMangoNudge, uint32_t uMangoMsgType, const std::shared_ptr<CommitDoneList_t> &pDoneCommits, bool bDroidDeckHudFrame )
|
||||
{
|
||||
std::unique_lock lock( m_WaitableCommitStateMutex );
|
||||
CloseFenceInternal();
|
||||
@@ -121,6 +123,7 @@ void commit_t::SetFence( int nFence, bool bMangoNudge, uint32_t uMangoMsgType, c
|
||||
m_nCommitFence = nFence;
|
||||
m_bMangoNudge = bMangoNudge;
|
||||
m_uMangoMsgType = uMangoMsgType;
|
||||
+ m_bDroidDeckHudFrame = bDroidDeckHudFrame;
|
||||
m_pDoneCommits = pDoneCommits;
|
||||
}
|
||||
|
||||
diff --git a/src/commit.h b/src/commit.h
|
||||
index 8603a9a..ae767b6 100644
|
||||
--- a/src/commit.h
|
||||
+++ b/src/commit.h
|
||||
@@ -35,7 +35,7 @@ struct commit_t final : public gamescope::RcObject, public gamescope::IWaitable,
|
||||
|
||||
// Returns true if we had a fence that was closed.
|
||||
bool CloseFenceInternal();
|
||||
- void SetFence( int nFence, bool bMangoNudge, uint32_t uMangoMsgType, const std::shared_ptr<CommitDoneList_t> &pDoneCommits );
|
||||
+ void SetFence( int nFence, bool bMangoNudge, uint32_t uMangoMsgType, const std::shared_ptr<CommitDoneList_t> &pDoneCommits, bool bDroidDeckHudFrame = false );
|
||||
|
||||
bool ShouldPreemptivelyUpscale( GamescopeUpscaleFilter eFilter, GamescopeUpscaleScaler eScaler );
|
||||
|
||||
@@ -82,5 +82,6 @@ struct commit_t final : public gamescope::RcObject, public gamescope::IWaitable,
|
||||
bool m_bMangoNudge = false;
|
||||
// Typed mangoapp stream to nudge, 0 for none, never the legacy type.
|
||||
uint32_t m_uMangoMsgType = 0;
|
||||
+ bool m_bDroidDeckHudFrame = false;
|
||||
std::shared_ptr<CommitDoneList_t> m_pDoneCommits; // I hate this
|
||||
};
|
||||
diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp
|
||||
index 0aef598..1473148 100644
|
||||
--- a/src/steamcompmgr.cpp
|
||||
+++ b/src/steamcompmgr.cpp
|
||||
@@ -57,6 +57,7 @@
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <fcntl.h>
|
||||
+#include <sys/mman.h>
|
||||
#include <sys/poll.h>
|
||||
#include <sys/inotify.h>
|
||||
#include <sys/time.h>
|
||||
@@ -8359,6 +8360,8 @@ static TempUpscaleImage_t *GetTempUpscaleImage( global_focus_t *pFocus, uint32_t
|
||||
|
||||
gamescope::ConVar<bool> cv_surface_update_force_only_current_surface( "surface_update_force_only_current_surface", false, "Force updates to apply only to the current surface, ignoring commits for other surfaces." );
|
||||
|
||||
+static bool droiddeck_hud_frames_wanted();
|
||||
+
|
||||
gamescope::ConVar<bool> cv_commit_ready_check( "commit_ready_check", true, "Check a new commit's fence at import; a finished frame is marked done in the same pass instead of through the image waiter." );
|
||||
|
||||
// Set when update_wayland_res marks a commit done itself, so the main loop handles it in the same pass.
|
||||
@@ -8519,6 +8522,16 @@ void update_wayland_res(const std::shared_ptr<CommitDoneList_t> &doneCommits, st
|
||||
uMangoMsgType = pMangoFocus->externalOverlayWindow->uMangoappMsgType;
|
||||
}
|
||||
|
||||
+ // The commits the typed stream of connector 0 counts, whether or not a mangoapp runs.
|
||||
+ bool bDroidDeckHudFrame = false;
|
||||
+ if ( pUpscaleFocus && !w->isSteamStreamingClient )
|
||||
+ bDroidDeckHudFrame = pUpscaleFocus->ulVirtualFocusKey == 0;
|
||||
+ else if ( w->isSteamStreamingClientVideo )
|
||||
+ {
|
||||
+ auto iter = g_VirtualConnectorFocuses.find( 0 );
|
||||
+ bDroidDeckHudFrame = iter != g_VirtualConnectorFocuses.end() && iter->second.focusWindow && iter->second.focusWindow->isSteamStreamingClient;
|
||||
+ }
|
||||
+
|
||||
bool bValidPreemptiveScale = reslistentry.pAcquirePoint && pUpscaleFocus && cv_upscale_preemptive;
|
||||
bool bPreemptiveUpscale = bValidPreemptiveScale && newCommit->ShouldPreemptivelyUpscale( pUpscaleFocus->eUpscaleFilter, pUpscaleFocus->eUpscaleScaler );
|
||||
|
||||
@@ -8650,7 +8663,7 @@ void update_wayland_res(const std::shared_ptr<CommitDoneList_t> &doneCommits, st
|
||||
|
||||
gpuvis_trace_printf( "pushing wait for commit %lu win %lx", newCommit->commitID, w->type == steamcompmgr_win_type_t::XWAYLAND ? w->xwayland().id : 0 );
|
||||
{
|
||||
- newCommit->SetFence( fence, mango_nudge, uMangoMsgType, doneCommits );
|
||||
+ newCommit->SetFence( fence, mango_nudge, uMangoMsgType, doneCommits, bDroidDeckHudFrame && droiddeck_hud_frames_wanted() );
|
||||
if ( bKnownReady )
|
||||
{
|
||||
newCommit->Signal();
|
||||
@@ -9865,6 +9878,109 @@ static void publish_mangoapp_connector_snapshots()
|
||||
}
|
||||
}
|
||||
|
||||
+// DroidDeck's own HUD reads the frame times DroidDeck's mangoapp shows from a shared file named by
|
||||
+// DROIDDECK_HUD_FRAMES, also while no mangoapp runs. That mangoapp (Valve's 20260902.1 build) reads the
|
||||
+// field at byte 16 of each message as its frame time, which is app_frametime_ns here: one time per
|
||||
+// signalled commit of the connector's windows (mangoapp_nudge_app_frame). The file gets the same commits
|
||||
+// of connector 0. Little-endian: 0 magic, 4 version, 8 capacity, 12 pid, 16 frames written (u64),
|
||||
+// 24 info sequence (odd while the info is written), 28 output width, 32 height, 36 refresh mHz, 40 Steam
|
||||
+// focused, 44 engine (40 bytes), then from 128 one { frametime ns, monotonic time ns } pair per frame,
|
||||
+// a ring of capacity.
|
||||
+static constexpr uint32_t k_uDroidDeckHudFramesMagic = 0x46484444;
|
||||
+static constexpr uint32_t k_uDroidDeckHudFramesVersion = 1;
|
||||
+static constexpr uint32_t k_uDroidDeckHudFramesCapacity = 1024;
|
||||
+static constexpr size_t k_zDroidDeckHudFramesHeader = 128;
|
||||
+static constexpr size_t k_zDroidDeckHudFramesSize = k_zDroidDeckHudFramesHeader + k_uDroidDeckHudFramesCapacity * 16;
|
||||
+static std::mutex s_DroidDeckHudFramesMutex;
|
||||
+
|
||||
+static uint8_t *droiddeck_hud_frames_map()
|
||||
+{
|
||||
+ static uint8_t *s_pMap = nullptr;
|
||||
+ static bool s_bTried = false;
|
||||
+ if ( s_bTried )
|
||||
+ return s_pMap;
|
||||
+ s_bTried = true;
|
||||
+
|
||||
+ const char *pszPath = getenv( "DROIDDECK_HUD_FRAMES" );
|
||||
+ if ( !pszPath || !*pszPath )
|
||||
+ return nullptr;
|
||||
+ int fd = open( pszPath, O_RDWR | O_CREAT | O_CLOEXEC, 0644 );
|
||||
+ if ( fd < 0 )
|
||||
+ {
|
||||
+ xwm_log.errorf_errno( "DroidDeck HUD frames: open %s", pszPath );
|
||||
+ return nullptr;
|
||||
+ }
|
||||
+ void *pMap = MAP_FAILED;
|
||||
+ if ( ftruncate( fd, k_zDroidDeckHudFramesSize ) == 0 )
|
||||
+ pMap = mmap( nullptr, k_zDroidDeckHudFramesSize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0 );
|
||||
+ close( fd );
|
||||
+ if ( pMap == MAP_FAILED )
|
||||
+ {
|
||||
+ xwm_log.errorf_errno( "DroidDeck HUD frames: map %s", pszPath );
|
||||
+ return nullptr;
|
||||
+ }
|
||||
+ uint8_t *pBytes = static_cast<uint8_t *>( pMap );
|
||||
+ __atomic_store_n( reinterpret_cast<uint32_t *>( pBytes ), 0u, __ATOMIC_RELEASE );
|
||||
+ memset( pBytes + 4, 0, k_zDroidDeckHudFramesSize - 4 );
|
||||
+ memcpy( pBytes + 4, &k_uDroidDeckHudFramesVersion, 4 );
|
||||
+ memcpy( pBytes + 8, &k_uDroidDeckHudFramesCapacity, 4 );
|
||||
+ __atomic_store_n( reinterpret_cast<uint32_t *>( pBytes ), k_uDroidDeckHudFramesMagic, __ATOMIC_RELEASE );
|
||||
+ xwm_log.infof( "DroidDeck HUD frames: %s", pszPath );
|
||||
+ s_pMap = pBytes;
|
||||
+ return s_pMap;
|
||||
+}
|
||||
+
|
||||
+static bool droiddeck_hud_frames_wanted()
|
||||
+{
|
||||
+ std::unique_lock lock( s_DroidDeckHudFramesMutex );
|
||||
+ return droiddeck_hud_frames_map() != nullptr;
|
||||
+}
|
||||
+
|
||||
+// Signal() runs on the image waiter thread or, for a frame finished at import, on steamcompmgr's.
|
||||
+void droiddeck_hud_app_frame( uint64_t ulNow )
|
||||
+{
|
||||
+ std::unique_lock lock( s_DroidDeckHudFramesMutex );
|
||||
+ uint8_t *pMap = droiddeck_hud_frames_map();
|
||||
+ if ( !pMap )
|
||||
+ return;
|
||||
+ static uint64_t s_ulLastFrame = 0;
|
||||
+ uint64_t ulLast = s_ulLastFrame;
|
||||
+ s_ulLastFrame = ulNow;
|
||||
+ if ( !ulLast || ulNow <= ulLast )
|
||||
+ return;
|
||||
+ uint64_t *pCount = reinterpret_cast<uint64_t *>( pMap + 16 );
|
||||
+ uint64_t ulCount = __atomic_load_n( pCount, __ATOMIC_RELAXED );
|
||||
+ uint64_t ulFrame[2] = { ulNow - ulLast, ulNow };
|
||||
+ memcpy( pMap + k_zDroidDeckHudFramesHeader + ( ulCount % k_uDroidDeckHudFramesCapacity ) * 16, ulFrame, sizeof( ulFrame ) );
|
||||
+ __atomic_store_n( pCount, ulCount + 1, __ATOMIC_RELEASE );
|
||||
+}
|
||||
+
|
||||
+static void publish_droiddeck_hud_info()
|
||||
+{
|
||||
+ std::unique_lock lock( s_DroidDeckHudFramesMutex );
|
||||
+ uint8_t *pMap = droiddeck_hud_frames_map();
|
||||
+ if ( !pMap )
|
||||
+ return;
|
||||
+ auto focusIter = g_VirtualConnectorFocuses.find( 0 );
|
||||
+ global_focus_t *pFocus = focusIter != g_VirtualConnectorFocuses.end() ? &focusIter->second : GetCurrentFocus();
|
||||
+ if ( !pFocus )
|
||||
+ return;
|
||||
+
|
||||
+ uint32_t *pSeq = reinterpret_cast<uint32_t *>( pMap + 24 );
|
||||
+ uint32_t uSeq = __atomic_load_n( pSeq, __ATOMIC_RELAXED );
|
||||
+ __atomic_store_n( pSeq, uSeq + 1, __ATOMIC_RELAXED );
|
||||
+ __atomic_thread_fence( __ATOMIC_RELEASE );
|
||||
+ uint32_t uPid = uint32_t( pFocus->nFocusWindowPid );
|
||||
+ uint32_t uOutput[4] = { g_nOutputWidth, g_nOutputHeight, uint32_t( g_nOutputRefresh ), window_is_steam( pFocus->inputFocusWindow ) ? 1u : 0u };
|
||||
+ char szEngine[40] = {};
|
||||
+ if ( pFocus->pFocusWindowEngine )
|
||||
+ pFocus->pFocusWindowEngine->copy( szEngine, sizeof( szEngine ) - 1 );
|
||||
+ memcpy( pMap + 12, &uPid, 4 );
|
||||
+ memcpy( pMap + 28, uOutput, sizeof( uOutput ) );
|
||||
+ memcpy( pMap + 44, szEngine, sizeof( szEngine ) );
|
||||
+ __atomic_store_n( pSeq, uSeq + 2, __ATOMIC_RELEASE );
|
||||
+}
|
||||
+
|
||||
// mangohudctl posts one control message for every instance to act on.
|
||||
static void relay_mangoapp_control()
|
||||
{
|
||||
@@ -10843,6 +10959,7 @@ steamcompmgr_main(int argc, char **argv)
|
||||
|
||||
publish_mangoapp_snapshot();
|
||||
publish_mangoapp_connector_snapshots();
|
||||
+ publish_droiddeck_hud_info();
|
||||
relay_mangoapp_control();
|
||||
|
||||
if ( bIsVBlankFromTimer )
|
||||
diff --git a/src/steamcompmgr.hpp b/src/steamcompmgr.hpp
|
||||
index bd62fd1..7a7119f 100644
|
||||
--- a/src/steamcompmgr.hpp
|
||||
+++ b/src/steamcompmgr.hpp
|
||||
@@ -173,6 +173,7 @@ static constexpr uint32_t MangoappControlMsgType( uint32_t uMsgType )
|
||||
static_assert( MangoappControlMsgType( k_uMangoappLegacyMsgType ) == k_uMangoappControlMsgType );
|
||||
|
||||
extern void mangoapp_update( uint64_t visible_frametime, uint64_t app_frametime_ns, uint64_t latency_ns, uint32_t uMsgType = k_uMangoappLegacyMsgType );
|
||||
+extern void droiddeck_hud_app_frame( uint64_t ulNow );
|
||||
extern void mangoapp_nudge_app_frame( uint32_t uMsgType, uint64_t ulNow );
|
||||
extern void mangoapp_set_connector_snapshots( std::unordered_map<uint32_t, MangoappSnapshot_t> snapshots );
|
||||
extern void mangoapp_drop_stream( uint32_t uMsgType );
|
||||
@@ -1,3 +1,3 @@
|
||||
GAMESCOPE_REPO=Droid-Deck/DroidDeck-Components
|
||||
GAMESCOPE_TAG=gamescope-3.16.29-p18
|
||||
GAMESCOPE_SHA256=a79d8acc5628973c807a43524638c20e7d5c101a4fc3bcb8b5068631e6f6fe55
|
||||
GAMESCOPE_TAG=gamescope-3.16.29-p19
|
||||
GAMESCOPE_SHA256=e7333c6a2b95708b199c2c5bd0973e3f0e711e2dc746950cc648c2515ea2926b
|
||||
@@ -45,7 +45,7 @@ lib=$out/x86_64/libwebkitinput.so
|
||||
gcc -m64 -shared -fPIC -O2 -Wall -Wextra -nostdlib -fno-stack-protector -fno-builtin -fvisibility=hidden \
|
||||
-o "$lib" tools/linuxfs/fex/webkitinput.c
|
||||
strip --strip-unneeded "$lib"
|
||||
if objdump -p "$lib" | grep -q NEEDED || [ "$(nm -D --undefined-only "$lib" | awk '{print $1 $2}' | LC_ALL=C sort | tr '\n' ' ')" != "wdlsym wg_object_get_data wg_object_set wg_object_set_data wg_type_check_instance_is_a wgtk_container_forall wgtk_container_get_type wgtk_key_snooper_install wgtk_widget_get_toplevel wwebkit_user_script_new wwebkit_user_script_unref wwebkit_web_view_get_type wwebkit_web_view_get_uri wwebkit_web_view_run_javascript " ]; then
|
||||
if objdump -p "$lib" | grep -q NEEDED || [ "$(nm -D --undefined-only "$lib" | awk '{print $1 $2}' | LC_ALL=C sort | tr '\n' ' ')" != "wdlsym wg_getenv wg_object_get_data wg_object_set wg_object_set_data wg_type_check_instance_is_a wgtk_container_forall wgtk_container_get_type wgtk_key_snooper_install wgtk_widget_get_toplevel wwebkit_user_script_new wwebkit_user_script_unref wwebkit_web_view_get_type wwebkit_web_view_get_uri wwebkit_web_view_run_javascript " ]; then
|
||||
echo "$lib must need nothing but weak GLib, GTK and WebKit calls" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
@@ -11,6 +11,7 @@ export MOZ_DISABLE_CONTENT_SANDBOX=1 MOZ_DISABLE_GMP_SANDBOX=1 MOZ_DISABLE_RDD_S
|
||||
export MOZ_DISABLE_SOCKET_PROCESS_SANDBOX=1 MOZ_DISABLE_UTILITY_SANDBOX=1
|
||||
export MOZ_SHM_NO_SEALS=1
|
||||
export KWIN_COMPOSE=Q QT_QUICK_BACKEND=software LIBGL_ALWAYS_SOFTWARE=1 GALLIUM_DRIVER=llvmpipe
|
||||
export KWIN_USE_OVERLAYS=0
|
||||
[ -e /etc/mpv/mpv.conf ] || { mkdir -p /etc/mpv && echo gpu-sw=yes >/etc/mpv/mpv.conf; } 2>/dev/null
|
||||
for conf in client client-rt; do
|
||||
mkdir -p "/etc/pipewire/$conf.conf.d" && printf 'context.properties = {\n module.rt = false\n}\n' >"/etc/pipewire/$conf.conf.d/droiddeck-rt.conf"
|
||||
@@ -35,7 +36,7 @@ cat > /usr/share/applications/droiddeck-steam-x64.desktop <<'ENTRY'
|
||||
Type=Application
|
||||
Name=Steam x86-64 (FEX, experimental)
|
||||
Comment=Valve's x86-64 Linux client under FEX, in its own home with its own login
|
||||
Exec=qterminal -e /usr/local/bin/droiddeck-steam-x64
|
||||
Exec=konsole -e /usr/local/bin/droiddeck-steam-x64
|
||||
Icon=steam
|
||||
Categories=System;
|
||||
ENTRY
|
||||
@@ -43,6 +44,20 @@ python3 /usr/local/bin/droiddeck-pad-defaults 2>&1 | sed 's/^/[pads] /'
|
||||
( while sleep 30; do python3 /usr/local/bin/droiddeck-pad-defaults 2>&1 | sed 's/^/[pads] /'; done ) &
|
||||
python3 /usr/local/bin/droiddeck-desktop-gpu 2>&1 | sed 's/^/[gpu] /'
|
||||
/usr/local/bin/droiddeck-desktop-window-rules 2>&1 | sed 's/^/[rules] /'
|
||||
( python3 /usr/local/bin/droiddeck-library-perms 2>&1 | sed 's/^/[perms] /' ) &
|
||||
mkdir -p /usr/local/share/applications
|
||||
cat > /usr/local/share/applications/droiddeck-ime.desktop <<'ENTRY'
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=Android keyboard
|
||||
Exec=/usr/local/bin/droiddeck-ime
|
||||
NoDisplay=true
|
||||
X-KDE-Wayland-VirtualKeyboard=true
|
||||
ENTRY
|
||||
input_method=$(kreadconfig6 --file kwinrc --group Wayland --key InputMethod 2>/dev/null)
|
||||
case $input_method in
|
||||
''|*/droiddeck-ime.desktop) kwriteconfig6 --file kwinrc --group Wayland --key InputMethod /usr/local/share/applications/droiddeck-ime.desktop ;;
|
||||
esac
|
||||
python3 /usr/local/bin/droiddeck-open --install 2>&1 | sed 's/^/[open] /'
|
||||
export APPIMAGE_EXTRACT_AND_RUN=1
|
||||
[ -e /etc/xdg/kiorc ] || printf '[Executable scripts]\nbehaviourOnLaunch=execute\n' >/etc/xdg/kiorc 2>/dev/null
|
||||
@@ -55,6 +70,19 @@ if [ ! -e "$HOME/.config/droiddeck-desktop-icons" ]; then
|
||||
touch "$HOME/.config/droiddeck-desktop-icons"
|
||||
fi
|
||||
[ -f "$desktop_dir/Return.desktop" ] && cp -f /usr/share/applications/droiddeck-return-gaming.desktop "$desktop_dir/Return.desktop" 2>/dev/null
|
||||
if command -v flatpak >/dev/null 2>&1 && [ ! -d /var/lib/pacman ]; then
|
||||
FLATPAK_BWRAP=/usr/local/bin/droiddeck-bwrap flatpak remote-add --user --if-not-exists flathub https://dl.flathub.org/repo/flathub.flatpakrepo >/dev/null 2>&1 &
|
||||
fi
|
||||
skel_done=$HOME/.local/share/droiddeck/skel-copied
|
||||
if [ -d /etc/skel ] && [ ! -e "$skel_done" ]; then
|
||||
cp -rn /etc/skel/. "$HOME/" 2>/dev/null
|
||||
mkdir -p "${skel_done%/*}" && : > "$skel_done"
|
||||
fi
|
||||
if [ -x /usr/lib/snapd/snap-confine ] && [ ! -d /var/lib/pacman ]; then
|
||||
/usr/local/bin/droiddeck-snapd >/dev/null 2>&1 &
|
||||
export XDG_DATA_DIRS=/var/lib/snapd/desktop:${XDG_DATA_DIRS:-/usr/local/share:/usr/share}
|
||||
export PATH=$PATH:/snap/bin
|
||||
fi
|
||||
update-mime-database /usr/share/mime >/dev/null 2>&1 &
|
||||
[ -f /usr/share/icons/hicolor/icon-theme.cache ] || gtk-update-icon-cache -q -t /usr/share/icons/hicolor 2>/dev/null &
|
||||
[ -f /usr/share/glib-2.0/schemas/gschemas.compiled ] || glib-compile-schemas /usr/share/glib-2.0/schemas 2>/dev/null
|
||||
@@ -82,6 +110,10 @@ if [ "$(cat /usr/share/droiddeck/kwin-compositor 2>/dev/null)" = opengl ]; then
|
||||
if [ -z "${KWIN_RENDER_NODES:-}" ] && [ -c /dev/dri/renderD0 ]; then
|
||||
export KWIN_RENDER_NODES=/dev/dri/renderD0
|
||||
fi
|
||||
mkdir -p /run/droiddeck/kwin
|
||||
printf '#!/bin/sh\nGALLIUM_THREAD=0 exec /usr/bin/kwin_wayland "$@"\n' > /run/droiddeck/kwin/kwin_wayland
|
||||
chmod 755 /run/droiddeck/kwin/kwin_wayland
|
||||
export PATH=/run/droiddeck/kwin:$PATH
|
||||
fi
|
||||
echo "== droiddeck-desktop: Plasma on $WAYLAND_DISPLAY"
|
||||
dbus-run-session -- startplasma-wayland
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#!/usr/bin/python3
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
|
||||
HOME = os.environ.get("HOME", "/root")
|
||||
SYSTEM_DIR = "/usr/share/applications"
|
||||
@@ -9,6 +10,8 @@ FLATPAK_DIR = os.path.join(HOME, ".local/share/flatpak/exports/share/application
|
||||
USER_DIR = os.path.join(HOME, ".local/share/applications")
|
||||
MARK = "X-DroidDeck-GPU=1"
|
||||
SKIP = re.compile(r"^(steam|droiddeck-game-|droiddeck-steam|steamdeck-)", re.I)
|
||||
CHROMIUM_ENV = "env -u WAYLAND_DISPLAY XDG_SESSION_TYPE=x11 ELECTRON_DISABLE_SANDBOX=1 "
|
||||
CHROMIUM_FLAGS = " --no-sandbox --ozone-platform=x11"
|
||||
|
||||
|
||||
def enabled():
|
||||
@@ -25,6 +28,33 @@ def main_group(text):
|
||||
return lines[:start + 1], lines[start + 1:end], lines[end:]
|
||||
|
||||
|
||||
def split_program(exec_line):
|
||||
if exec_line.startswith('"'):
|
||||
end = exec_line.find('"', 1)
|
||||
if end < 0:
|
||||
return None, None
|
||||
return exec_line[:end + 1], exec_line[end + 1:]
|
||||
program, _, rest = exec_line.partition(" ")
|
||||
return program, (" " + rest) if rest else ""
|
||||
|
||||
|
||||
def chromium(exec_line):
|
||||
program, _ = split_program(exec_line)
|
||||
if not program:
|
||||
return False
|
||||
program = program.strip('"')
|
||||
path = program if os.path.isabs(program) else shutil.which(program)
|
||||
if not path:
|
||||
return False
|
||||
here = os.path.dirname(os.path.realpath(path))
|
||||
return any(os.path.exists(os.path.join(d, "chrome-sandbox")) for d in (here, os.path.dirname(here)))
|
||||
|
||||
|
||||
def chromium_exec(exec_line):
|
||||
program, rest = split_program(exec_line)
|
||||
return CHROMIUM_ENV + program + CHROMIUM_FLAGS + rest
|
||||
|
||||
|
||||
def gpu_exec(exec_line):
|
||||
"""The Exec that runs a program on the GPU; a Flatpak app goes through its launcher, which
|
||||
keeps it on gamescope's X server instead of the desktop's Wayland socket."""
|
||||
@@ -33,7 +63,7 @@ def gpu_exec(exec_line):
|
||||
return "droiddeck-gpu " + exec_line
|
||||
|
||||
|
||||
def wrap(text):
|
||||
def wrap(text, gpu_on=True):
|
||||
head, group, rest = main_group(text)
|
||||
if group is None:
|
||||
return None
|
||||
@@ -42,14 +72,30 @@ def wrap(text):
|
||||
if "=" in l and not l.lstrip().startswith("#"):
|
||||
k, v = l.split("=", 1)
|
||||
keys.setdefault(k.strip(), v)
|
||||
cats = set(filter(None, keys.get("Categories", "").split(";")))
|
||||
if not cats & {"Game", "Emulator"}:
|
||||
return None
|
||||
if keys.get("Type", "Application") != "Application" or keys.get("NoDisplay", "").lower() == "true":
|
||||
return None
|
||||
exec_line = keys.get("Exec", "").strip()
|
||||
if not exec_line or exec_line.startswith("droiddeck-gpu "):
|
||||
return None
|
||||
cats = set(filter(None, keys.get("Categories", "").split(";")))
|
||||
gpu = gpu_on and bool(cats & {"Game", "Emulator"})
|
||||
browser = chromium(exec_line)
|
||||
if not gpu and not browser:
|
||||
return None
|
||||
if browser:
|
||||
exec_line = chromium_exec(exec_line)
|
||||
if not gpu:
|
||||
def fix(lines):
|
||||
return ["Exec=" + chromium_exec(l[5:].strip()) if l.startswith("Exec=") and chromium(l[5:].strip()) else l
|
||||
for l in lines]
|
||||
out_group = fix(group)
|
||||
while out_group and not out_group[-1].strip():
|
||||
out_group.pop()
|
||||
out_group.append(MARK)
|
||||
out_rest = fix(rest)
|
||||
if out_rest and out_rest[0].strip():
|
||||
out_rest.insert(0, "")
|
||||
return "\n".join(head + out_group + out_rest) + "\n"
|
||||
out_group = []
|
||||
actions = keys.get("Actions", "")
|
||||
for l in group:
|
||||
@@ -68,7 +114,8 @@ def wrap(text):
|
||||
wrapped_rest = []
|
||||
for l in rest:
|
||||
if l.startswith("Exec=") and not l[5:].startswith("droiddeck-gpu "):
|
||||
l = "Exec=" + gpu_exec(l[5:])
|
||||
action = l[5:].strip()
|
||||
l = "Exec=" + gpu_exec(chromium_exec(action) if chromium(action) else action)
|
||||
wrapped_rest.append(l)
|
||||
if wrapped_rest and wrapped_rest[0].strip():
|
||||
wrapped_rest.insert(0, "")
|
||||
@@ -87,7 +134,7 @@ def main():
|
||||
on = enabled()
|
||||
os.makedirs(USER_DIR, exist_ok=True)
|
||||
written = set()
|
||||
sources = [d for d in (SYSTEM_DIR, LOCAL_DIR, FLATPAK_DIR) if os.path.isdir(d)] if on else []
|
||||
sources = [d for d in (SYSTEM_DIR, LOCAL_DIR, FLATPAK_DIR) if os.path.isdir(d)]
|
||||
for source in sources:
|
||||
for name in sorted(os.listdir(source)):
|
||||
if not name.endswith(".desktop") or SKIP.match(name):
|
||||
@@ -97,7 +144,7 @@ def main():
|
||||
continue
|
||||
try:
|
||||
with open(os.path.join(source, name), encoding="utf-8", errors="replace") as f:
|
||||
text = wrap(f.read())
|
||||
text = wrap(f.read(), on)
|
||||
except OSError:
|
||||
continue
|
||||
if text is None:
|
||||
|
||||
@@ -22,6 +22,7 @@ extern void webkit_web_view_run_javascript(void *view, const char *script, void
|
||||
extern WebKitUserScript *webkit_user_script_new(const char *source, int frames, int time,
|
||||
const char *const *allow, const char *const *block) __attribute__((weak));
|
||||
extern void webkit_user_script_unref(WebKitUserScript *script) __attribute__((weak));
|
||||
extern const char *g_getenv(const char *name) __attribute__((weak));
|
||||
|
||||
static const char NAV_SCRIPT[] =
|
||||
"(()=>{let open=-1e9,arrowAt=-1e9,ringed=null,ringOutline='',ringOffset='',settleTimer=0,settling=false,redirecting=false;"
|
||||
@@ -196,3 +197,45 @@ __attribute__((visibility("default"))) void webkit_user_content_manager_add_scri
|
||||
}
|
||||
next(manager, script);
|
||||
}
|
||||
|
||||
static int starts(const char *text, const char *prefix)
|
||||
{
|
||||
while (*prefix)
|
||||
if (*text++ != *prefix++)
|
||||
return 0;
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int fab_uri(const char *uri)
|
||||
{
|
||||
if (!uri)
|
||||
return 0;
|
||||
if (starts(uri, "https://"))
|
||||
uri += 8;
|
||||
else if (starts(uri, "http://"))
|
||||
uri += 7;
|
||||
else
|
||||
return 0;
|
||||
if (starts(uri, "www."))
|
||||
uri += 4;
|
||||
if (!starts(uri, "fab.com"))
|
||||
return 0;
|
||||
uri += 7;
|
||||
return !*uri || *uri == '/' || *uri == '?' || *uri == '#' || *uri == ':';
|
||||
}
|
||||
|
||||
static int hidden_launcher(void)
|
||||
{
|
||||
const char *hidden = g_getenv ? g_getenv("DROIDDECK_EPIC_HIDDEN") : 0;
|
||||
return hidden && hidden[0] == '1' && !hidden[1];
|
||||
}
|
||||
|
||||
__attribute__((visibility("default"))) void webkit_web_view_load_uri(void *view, const char *uri)
|
||||
{
|
||||
static void (*next)(void *, const char *);
|
||||
if (!next && dlsym)
|
||||
next = (void (*)(void *, const char *))dlsym((void *)-1l, "webkit_web_view_load_uri");
|
||||
if (!next)
|
||||
return;
|
||||
next(view, hidden_launcher() && fab_uri(uri) ? "about:blank" : uri);
|
||||
}
|
||||
@@ -605,9 +605,56 @@ KEYBOARD_CHECK_SECONDS = 30
|
||||
KEYBOARD_JS = r"""
|
||||
(() => {
|
||||
const self = window.__droiddeckKeyboard || (window.__droiddeckKeyboard = { watched: new WeakSet(), last: null });
|
||||
self.wrapped = self.wrapped || new WeakSet();
|
||||
self.route = self.route === true;
|
||||
self.wrap = vkm => {
|
||||
if (!vkm || self.wrapped.has(vkm) || typeof vkm.ShowVirtualKeyboard !== "function") return;
|
||||
self.wrapped.add(vkm);
|
||||
const show = vkm.ShowVirtualKeyboard;
|
||||
vkm.ShowVirtualKeyboard = function (ref, props, modal) {
|
||||
if (self.route && !modal && typeof this.SetActiveVirtualKeyboardTarget === "function" &&
|
||||
!this.BUseVRKeyboard?.() && !this.m_Instance?.IsDesktopOverlayWindow?.()) {
|
||||
this.SetActiveVirtualKeyboardTarget(ref, props);
|
||||
self.follow(this);
|
||||
if (typeof window.__BINDING__ === "function") window.__BINDING__("request");
|
||||
return;
|
||||
}
|
||||
return show.call(this, ref, props, modal);
|
||||
};
|
||||
};
|
||||
self.editing = vkm => {
|
||||
let el = null;
|
||||
try { el = vkm?.m_ownerWindow?.document?.activeElement || null; } catch (e) {}
|
||||
if (!el) return null;
|
||||
return el.tagName === "TEXTAREA" || el.isContentEditable === true ||
|
||||
(el.tagName === "INPUT" && !/^(button|checkbox|radio|range|submit|reset|file|image|color)$/i.test(el.type || ""));
|
||||
};
|
||||
self.follow = vkm => {
|
||||
self.active = vkm;
|
||||
self.missed = 0;
|
||||
self.seen = false;
|
||||
self.follower = self.follower || setInterval(() => {
|
||||
if (!self.active) return;
|
||||
const ref = self.active.m_currentVirtualKeyboardRef;
|
||||
const editing = self.editing(self.active);
|
||||
const valid = !!ref && (editing !== null ? editing :
|
||||
(typeof ref.BIsElementValidForInput !== "function" || ref.BIsElementValidForInput()));
|
||||
if (valid) self.seen = true;
|
||||
if (self.route && ref && (valid || !self.seen)) {
|
||||
self.missed = 0;
|
||||
return;
|
||||
}
|
||||
if (++self.missed < 2) return;
|
||||
self.active = null;
|
||||
clearInterval(self.follower);
|
||||
self.follower = null;
|
||||
if (typeof window.__BINDING__ === "function") window.__BINDING__("dismiss");
|
||||
}, 150);
|
||||
};
|
||||
self.check = () => {
|
||||
let showing = false;
|
||||
for (const win of Array.from(globalThis.SteamUIStore?.WindowStore?.SteamUIWindows || [])) {
|
||||
self.wrap(win?.VirtualKeyboardManager);
|
||||
const value = win?.VirtualKeyboardManager?.IsShowingVirtualKeyboard;
|
||||
if (!value) continue;
|
||||
if (!self.watched.has(value) && typeof value.Subscribe === "function") {
|
||||
@@ -626,6 +673,29 @@ KEYBOARD_JS = r"""
|
||||
return self.check();
|
||||
})()
|
||||
""".replace("__BINDING__", KEYBOARD_BINDING)
|
||||
KEYBOARD_ROUTE_SECONDS = 0.5
|
||||
KEYBOARD_ROUTE_JS = r"""
|
||||
(route => {
|
||||
const self = window.__droiddeckKeyboard;
|
||||
if (!self) return false;
|
||||
self.route = route;
|
||||
if (!route) return true;
|
||||
for (const win of Array.from(globalThis.SteamUIStore?.WindowStore?.SteamUIWindows || [])) {
|
||||
const vkm = win?.VirtualKeyboardManager;
|
||||
if (vkm?.m_bIsInlineVirtualKeyboardOpen?.m_currentValue === true && vkm?.m_bIsVirtualKeyboardModal?.m_currentValue !== true &&
|
||||
typeof vkm.SetVirtualKeyboardHidden === "function") {
|
||||
const ref = vkm.m_currentVirtualKeyboardRef, props = vkm.m_ActiveElementProps;
|
||||
vkm.SetVirtualKeyboardHidden();
|
||||
if (ref && typeof vkm.SetActiveVirtualKeyboardTarget === "function") {
|
||||
vkm.SetActiveVirtualKeyboardTarget(ref, props);
|
||||
if (typeof self.follow === "function") self.follow(vkm);
|
||||
}
|
||||
if (typeof window.__BINDING__ === "function") window.__BINDING__("request");
|
||||
}
|
||||
}
|
||||
return true;
|
||||
})(__ROUTE__)
|
||||
""".replace("__BINDING__", KEYBOARD_BINDING)
|
||||
|
||||
|
||||
class KeyboardWatcher(threading.Thread):
|
||||
@@ -633,8 +703,14 @@ class KeyboardWatcher(threading.Thread):
|
||||
super().__init__(daemon=True, name="keyboard")
|
||||
self.agent_dir = agent_dir
|
||||
self.path = agent_dir / "keyboard.json"
|
||||
self.request_path = agent_dir / "keyboard-request.json"
|
||||
self.dismiss_path = agent_dir / "keyboard-dismiss.json"
|
||||
self.dismissals = 0
|
||||
self.route_path = agent_dir / "keyboard-route"
|
||||
self.showing = None
|
||||
self.seq = 0
|
||||
self.requests = 0
|
||||
self.route = None
|
||||
self.next_id = 0
|
||||
self.attached = False
|
||||
|
||||
@@ -645,6 +721,30 @@ class KeyboardWatcher(threading.Thread):
|
||||
self.seq += 1
|
||||
write_json(self.path, {"steamKeyboard": showing, "seq": self.seq})
|
||||
|
||||
def request(self):
|
||||
self.requests += 1
|
||||
write_json(self.request_path, {"seq": self.requests})
|
||||
|
||||
def dismiss(self):
|
||||
self.dismissals += 1
|
||||
write_json(self.dismiss_path, {"seq": self.dismissals})
|
||||
|
||||
def wanted_route(self):
|
||||
try:
|
||||
return self.route_path.read_text().strip() == "bottom"
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
def apply_route(self, ws, force=False):
|
||||
route = self.wanted_route()
|
||||
if route == self.route and not force:
|
||||
return
|
||||
result = self.call(ws, "Runtime.evaluate", {
|
||||
"expression": KEYBOARD_ROUTE_JS.replace("__ROUTE__", "true" if route else "false"), "returnByValue": True})
|
||||
if result.get("exceptionDetails"):
|
||||
raise AgentError("JS_EXCEPTION", json.dumps(result["exceptionDetails"])[:500])
|
||||
self.route = route
|
||||
|
||||
def run(self):
|
||||
failures, last = 0, None
|
||||
while True:
|
||||
@@ -671,10 +771,18 @@ class KeyboardWatcher(threading.Thread):
|
||||
try:
|
||||
self.call(ws, "Runtime.addBinding", {"name": KEYBOARD_BINDING})
|
||||
self.report(self.install(ws))
|
||||
self.apply_route(ws, force=True)
|
||||
self.attached = True
|
||||
installed = time.monotonic()
|
||||
while True:
|
||||
if not ws.buffer and not select.select([ws.s], [], [], KEYBOARD_CHECK_SECONDS)[0]:
|
||||
self.report(self.install(ws))
|
||||
wait = min(KEYBOARD_ROUTE_SECONDS, KEYBOARD_CHECK_SECONDS)
|
||||
if not ws.buffer and not select.select([ws.s], [], [], wait)[0]:
|
||||
if time.monotonic() - installed >= KEYBOARD_CHECK_SECONDS:
|
||||
self.report(self.install(ws))
|
||||
self.apply_route(ws, force=True)
|
||||
installed = time.monotonic()
|
||||
else:
|
||||
self.apply_route(ws)
|
||||
continue
|
||||
self.event(json.loads(ws.recv()))
|
||||
finally:
|
||||
@@ -702,7 +810,12 @@ class KeyboardWatcher(threading.Thread):
|
||||
def event(self, message):
|
||||
params = message.get("params") or {}
|
||||
if message.get("method") == "Runtime.bindingCalled" and params.get("name") == KEYBOARD_BINDING:
|
||||
self.report(params.get("payload") == "true")
|
||||
if params.get("payload") == "request":
|
||||
self.request()
|
||||
elif params.get("payload") == "dismiss":
|
||||
self.dismiss()
|
||||
else:
|
||||
self.report(params.get("payload") == "true")
|
||||
|
||||
|
||||
def steam_idle_inhibit(agent_dir, inhibit):
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#!/usr/bin/python3
|
||||
import base64
|
||||
import fcntl
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
@@ -87,6 +88,7 @@ class Spec:
|
||||
self.info_fds = []
|
||||
self.json_fds = []
|
||||
self.keep_fds = []
|
||||
self.lock_files = []
|
||||
self.command = []
|
||||
self.argv0 = None
|
||||
|
||||
@@ -159,6 +161,8 @@ def parse(argv):
|
||||
read_fd(int(args[0]))
|
||||
elif a == "--sync-fd":
|
||||
s.keep_fds.append(int(args[0]))
|
||||
elif a == "--lock-file":
|
||||
s.lock_files.append(args[0])
|
||||
elif a == "--info-fd":
|
||||
s.info_fds.append(int(args[0]))
|
||||
elif a == "--json-status-fd":
|
||||
@@ -203,6 +207,31 @@ def remaps_nothing(s):
|
||||
return True
|
||||
|
||||
|
||||
def host_path(s, path):
|
||||
for op in reversed(s.ops):
|
||||
if op["t"] != "bind":
|
||||
continue
|
||||
dest = op["dest"].rstrip("/")
|
||||
if path == dest or path.startswith(dest + "/"):
|
||||
return op["src"].rstrip("/") + path[len(dest):]
|
||||
return path
|
||||
|
||||
|
||||
def hold_locks(s):
|
||||
for path in s.lock_files:
|
||||
try:
|
||||
fd = os.open(host_path(s, path), os.O_RDONLY)
|
||||
except OSError as e:
|
||||
sys.stderr.write("bwrap: Can't open lock file %s: %s\n" % (path, e.strerror))
|
||||
sys.exit(1)
|
||||
try:
|
||||
fcntl.lockf(fd, fcntl.LOCK_SH | fcntl.LOCK_NB)
|
||||
except OSError as e:
|
||||
sys.stderr.write("bwrap: Can't lock file %s: %s\n" % (path, e.strerror))
|
||||
sys.exit(1)
|
||||
os.set_inheritable(fd, True)
|
||||
|
||||
|
||||
def report_pid(s, pid):
|
||||
for fd in s.info_fds:
|
||||
try:
|
||||
@@ -282,7 +311,7 @@ def run_by_app(s):
|
||||
if payload is None:
|
||||
break
|
||||
if kind == b"P":
|
||||
report_pid(s, int(payload))
|
||||
report_pid(s, os.getpid())
|
||||
elif kind == b"O":
|
||||
out.write(payload)
|
||||
out.flush()
|
||||
@@ -301,6 +330,7 @@ def run_by_app(s):
|
||||
|
||||
def main():
|
||||
s = parse(expand(sys.argv[1:]))
|
||||
hold_locks(s)
|
||||
if remaps_nothing(s):
|
||||
run_here(s)
|
||||
else:
|
||||
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
#!/bin/bash
|
||||
free_name() {
|
||||
local dir=$1 name=$2 base ext n=2
|
||||
[ -e "$dir/$name" ] || { echo "$name"; return; }
|
||||
base=${name%.*} ext=
|
||||
[ "$base" != "$name" ] && [ -n "$base" ] && ext=.${name##*.} || base=$name
|
||||
while [ -e "$dir/$base ($n)$ext" ]; do n=$((n + 1)); done
|
||||
echo "$base ($n)$ext"
|
||||
}
|
||||
share() {
|
||||
local android=$HOME/Storage/$1 link=$HOME/$2 f
|
||||
[ -d "$android" ] && [ -w "$android" ] || return 0
|
||||
[ "$(readlink "$link" 2>/dev/null)" = "$android" ] && return 0
|
||||
if [ -L "$link" ]; then
|
||||
rm -f "$link"
|
||||
elif [ -d "$link" ]; then
|
||||
shopt -s dotglob nullglob
|
||||
for f in "$link"/*; do
|
||||
mv -n -- "$f" "$android/$(free_name "$android" "${f##*/}")" || return 1
|
||||
done
|
||||
shopt -u dotglob nullglob
|
||||
rmdir "$link" 2>/dev/null || mv "$link" "$link.old.$$" || return 1
|
||||
elif [ -e "$link" ]; then
|
||||
mv "$link" "$link.old.$$" || return 1
|
||||
fi
|
||||
ln -s "$android" "$link"
|
||||
}
|
||||
status=0
|
||||
share Download Downloads || status=1
|
||||
share Documents Documents || status=1
|
||||
exit $status
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
#!/bin/bash
|
||||
set -u
|
||||
export FLATPAK_BWRAP=/usr/local/bin/droiddeck-bwrap
|
||||
cores="libretro-core-info libretro-beetle-pce-fast libretro-beetle-psx libretro-beetle-vb libretro-beetle-wswan
|
||||
libretro-bsnes-mercury-performance libretro-desmume libretro-gambatte libretro-genesisplusgx libretro-mgba
|
||||
libretro-nestopia libretro-sameboy libretro-snes9x"
|
||||
case "${1:-}" in
|
||||
install)
|
||||
echo "== STEP RetroArch"
|
||||
droiddeck-root /usr/bin/apt-get update -q || { echo "== FAIL apt-get update"; exit 1; }
|
||||
droiddeck-root /usr/bin/apt-get install -y -q retroarch retroarch-assets $cores || { echo "== FAIL apt-get install"; exit 1; }
|
||||
echo "== STEP PPSSPP"
|
||||
flatpak remote-add --user --if-not-exists flathub https://dl.flathub.org/repo/flathub.flatpakrepo || { echo "== FAIL flathub"; exit 1; }
|
||||
flatpak install --user -y --noninteractive flathub org.ppsspp.PPSSPP || { echo "== FAIL org.ppsspp.PPSSPP"; exit 1; }
|
||||
printf '#!/bin/sh\nexec /usr/local/bin/droiddeck-flatpak-run org.ppsspp.PPSSPP "$@"\n' > /usr/local/bin/PPSSPPSDL.new &&
|
||||
chmod 755 /usr/local/bin/PPSSPPSDL.new && mv -f /usr/local/bin/PPSSPPSDL.new /usr/local/bin/PPSSPPSDL || { echo "== FAIL PPSSPPSDL"; exit 1; }
|
||||
;;
|
||||
*)
|
||||
echo "usage: droiddeck-emulators install" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
@@ -100,6 +100,10 @@ CLIENT_ENV = {
|
||||
"JSC_useDFGJIT": "0",
|
||||
"JSC_useFTLJIT": "0",
|
||||
}
|
||||
HIDDEN_ENV = {
|
||||
"DROIDDECK_EPIC_HIDDEN": "1",
|
||||
"EGL_DISABLE_STORE_PREWARM": "1",
|
||||
}
|
||||
KEPT_ENV = ("HOME", "USER", "LOGNAME", "LANG", "LANGUAGE", "LC_ALL", "LC_MESSAGES", "TZ", "XDG_RUNTIME_DIR", "BL_LAUNCH_DIR")
|
||||
LAUNCH_VERBS = ("waitforexitandrun", "run", "runinprefix")
|
||||
EPIC_ARGS = ("-auth_", "-epic")
|
||||
@@ -725,7 +729,7 @@ def fex_environment(fex, files, env):
|
||||
return result
|
||||
|
||||
|
||||
def client_environment(base, fex, files, display, bus, broker, a11y=None):
|
||||
def client_environment(base, fex, files, display, bus, broker, a11y=None, hidden=False):
|
||||
env = {name: base[name] for name in KEPT_ENV if base.get(name)}
|
||||
env.setdefault("HOME", HOME)
|
||||
env.setdefault("LANG", "C.UTF-8")
|
||||
@@ -734,6 +738,8 @@ def client_environment(base, fex, files, display, bus, broker, a11y=None):
|
||||
env["DBUS_SESSION_BUS_ADDRESS"] = bus
|
||||
env[BROKER_ENV] = broker
|
||||
env.update(CLIENT_ENV)
|
||||
if hidden:
|
||||
env.update(HIDDEN_ENV)
|
||||
if a11y:
|
||||
for name in A11Y_OFF:
|
||||
env.pop(name, None)
|
||||
@@ -1248,7 +1254,7 @@ class Session:
|
||||
path = broker_path()
|
||||
self.broker = Broker(path, self.mode, base)
|
||||
write_json(instance_file(), {"pid": os.getpid(), "mode": self.mode, "bus": bus, "broker": path})
|
||||
env = client_environment(base, fex, files, display, bus, path, self.a11y)
|
||||
env = client_environment(base, fex, files, display, bus, path, self.a11y, hidden=self.mode == "hidden")
|
||||
self.command = [fex["bin"], os.path.join(app_dir, "AppRun")]
|
||||
self.env = env
|
||||
say("starting the Epic Games Launcher %s (%s, display %s)" % (current.get("app"), self.mode, display))
|
||||
|
||||
@@ -5,6 +5,7 @@ step() { echo "== STEP $*"; }
|
||||
fail() { echo "== FAIL $*"; exit 1; }
|
||||
[ "$(id -u)" = 0 ] || fail "needs root: install Flatpak from the launcher's Store, which runs this as root"
|
||||
|
||||
if command -v pacman >/dev/null 2>&1; then
|
||||
PACKAGES="flatpak ostree appstream libxmlb libmalcontent libfyaml accountsservice composefs xdg-dbus-proxy"
|
||||
while read -r pkg probe; do
|
||||
[ -n "$pkg" ] || continue
|
||||
@@ -77,7 +78,13 @@ done
|
||||
mv -f "$WORK/installed.new" "$WORK/installed"
|
||||
find "$WORK/pkg" -type f -mtime +1 -delete 2>/dev/null
|
||||
|
||||
missing=$(for f in /usr/bin/flatpak /usr/lib/libflatpak.so.0 /usr/lib/libostree-1.so.1 /usr/bin/xdg-dbus-proxy; do
|
||||
else
|
||||
command -v flatpak >/dev/null 2>&1 || fail "Flatpak is missing from the runtime"
|
||||
WORK=$(mktemp -d)
|
||||
trap 'rm -rf "$WORK"' EXIT
|
||||
fi
|
||||
missing=$(for f in /usr/bin/flatpak /usr/lib/libflatpak.so.0 /usr/lib/libostree-1.so.1 /usr/lib/aarch64-linux-gnu/libflatpak.so.0 /usr/lib/aarch64-linux-gnu/libostree-1.so.1 /usr/bin/xdg-dbus-proxy; do
|
||||
[ -e "$f" ] || continue
|
||||
ldd "$f" 2>&1 | grep -E 'not found|version .* not found'
|
||||
done | sort -u)
|
||||
[ -z "$missing" ] || { echo "$missing"; fail "Flatpak is missing libraries"; }
|
||||
@@ -97,7 +104,7 @@ Description=Central repository of Flatpak applications
|
||||
Icon=https://dl.flathub.org/repo/logo.svg
|
||||
GPGKey=mQINBFlD2sABEADsiUZUOYBg1UdDaWkEdJYkTSZD68214m8Q1fbrP5AptaUfCl8KYKFMNoAJRBXn9FbE6q6VBzghHXj/rSnA8WPnkbaEWR7xltOqzB1yHpCQ1l8xSfH5N02DMUBSRtD/rOYsBKbaJcOgW0K21sX+BecMY/AI2yADvCJEjhVKrjR9yfRX+NQEhDcbXUFRGt9ZT+TI5yT4xcwbvvTu7aFUR/dH7+wjrQ7lzoGlZGFFrQXSs2WI0WaYHWDeCwymtohXryF8lcWQkhH8UhfNJVBJFgCY8Q6UHkZG0FxMu8xnIDBMjBmSZKwKQn0nwzwM2afskZEnmNPYDI8nuNsSZBZSAw+ThhkdCZHZZRwzmjzyRuLLVFpOj3XryXwZcSefNMPDkZAuWWzPYjxS80cm2hG1WfqrG0Gl8+iX69cbQchb7gbEb0RtqNskTo9DDmO0bNKNnMbzmIJ3/rTbSahKSwtewklqSP/01o0WKZiy+n/RAkUKOFBprjJtWOZkc8SPXV/rnoS2dWsJWQZhuPPtv3tefdDiEyp7ePrfgfKxuHpZES0IZRiFI4J/nAUP5bix+srcIxOVqAam68CbAlPvWTivRUMRVbKjJiGXIOJ78wAMjqPg3QIC0GQ0EPAWwAOzzpdgbnG7TCQetaVV8rSYCuirlPYN+bJIwBtkOC9SWLoPMVZTwQARAQABtC5GbGF0aHViIFJlcG8gU2lnbmluZyBLZXkgPGZsYXRodWJAZmxhdGh1Yi5vcmc+iQJUBBMBCAA+FiEEblwF2XnHba+TwIE1QYTdTZB6fK4FAllD2sACGwMFCRLMAwAFCwkIBwIGFQgJCgsCBBYCAwECHgECF4AACgkQQYTdTZB6fK5RJQ/+Ptd4sWxaiAW91FFk7+wmYOkEe1NY2UDNJjEEz34PNP/1RoxveHDt43kYJQ23OWaPJuZAbu+fWtjRYcMBzOsMCaFcRSHFiDIC9aTp4ux/mo+IEeyarYt/oyKb5t5lta6xaAqg7rwt65jW5/aQjnS4h7eFZ+dAKta7Y/fljNrOznUp81/SMcx4QA5G2Pw0hs4Xrxg59oONOTFGBgA6FF8WQghrpR7SnEe0FSEOVsAjwQ13Cfkfa7b70omXSWp7GWfUzgBKyoWxKTqzMN3RQHjjhPJcsQnrqH5enUu4Pcb2LcMFpzimHnUgb9ft72DP5wxfzHGAWOUiUXHbAekfq5iFks8cha/RST6wkxG3Rf44Zn09aOxh1btMcGL+5xb1G0BuCQnA0fP/kDYIPwh9z22EqwRQOspIcvGeLVkFeIfubxpcMdOfQqQnZtHMCabV5Q/Rk9K1ZGc8M2hlg8gHbXMFch2xJ0Wu72eXbA/UY5MskEeBgawTQnQOK/vNm7t0AJMpWK26Qg6178UmRghmeZDj9uNRc3EI1nSbgvmGlpDmCxaAGqaGL1zW4KPW5yN25/qeqXcgCvUjZLI9PNq3Kvizp1lUrbx7heRiSoazCucvHQ1VHUzcPVLUKKTkoTP8okThnRRRsBcZ1+jI4yMWIDLOCT7IW3FePr+3xyuy5eEo9a25Ag0EWUPa7AEQALT/CmSyZ8LWlRYQZKYw417p7Z2hxqd6TjwkwM3IQ1irumkWcTZBZIbBgrSOg6CcXD2oWydCQHWi9qaxhuhEl2bJL5LskmBcMxVdQeD0LLHd8QUnbnnIby8ocvWN1alPfvJFjCUTrmD22U1ycOzRw2lIe4kiQONbOZtdWrVImQQSndjFlisitbmlWHvHm2lOOYy8+GJB7YffVV193hmnBSJffCy4bvkuLxsI+n1DhOzc7MPV3z6HGk4HiEcF0yyt9tCYhpsxHFdBoq2h771HfAcS0s98EVAqYMFnf9em+4cnYpdI6mhIfS1FQiKl6DBAYA8tT3ggla00DurPo0JwX/zN+PaO5h/6O9aCZwV7G6rbkgMuqMergXaf8oP38gr0z+MqWnkfM63Bodq68GP4l4hd02BoFBbDf38TMuGQB14+twJMdfbAxo2MbgluvQgfwHfZ2ca6gyEY+9s/YD1gugLjV+S6CB51WkFNe1z4tAPgJZNxUcKCbeaHNbthl8Hks/pY9RCEseX/EdfzF18epbSjJMPh4DPQXbUoFwmyuYcoBOPmvZHNl9hK7B/1RP8w1ZrXk8qdupC0SNbafX7270B7lMMVImzZetGsM9ypXJ6llhp3FwW09iseNyGJGPsr/dvTMGDXqOPfU/9SAS1LSTY4K9PbRtdrBE318YX8mIk5ABEBAAGJBHIEGAEIACYWIQRuXAXZecdtr5PAgTVBhN1NkHp8rgUCWUPa7AIbAgUJEswDAAJACRBBhN1NkHp8rsF0IAQZAQgAHRYhBFSmzd2JGfsgQgDYrFYnAunj7X7oBQJZQ9rsAAoJEFYnAunj7X7oR6AP/0KYmiAFeqx14Z43/6s2gt3VhxlSd8bmcVV7oJFbMhdHBIeWBp2BvsUf00I0Zl14ZkwCKfLwbbORC2eIxvzJ+QWjGfPhDmS4XUSmhlXxWnYEveSek5Tde+fmu6lqKM8CHg5BNx4GWIX/vdLi1wWJZyhrUwwICAxkuhKxuP2Z1An48930eslTD2GGcjByc27+9cIZjHKa07I/aLffo04V+oMT9/tgzoquzgpVV4jwekADo2MJjhkkPveSNI420bgT+Q7Fi1l0X1aFUniBvQMsaBa27PngWm6xE2ZYvh7nWCdd5g0c0eLIHxWwzV1lZ4Ryx4ITO/VL25ItECcjhTRdYa64sA62MYSaB0x3eR+SihpgP3wSNPFu3MJo6FKTFdi4CBAEmpWHFW7FcRmd+cQXeFrHLN3iNVWryy0HK/CUEJmiZEmpNiXecl4vPIIuyF0zgSCztQtKoMr+injpmQGC/rF/ELBVZTUSLNB350S0Ztvw0FKWDAJSxFmoxt3xycqvvt47rxTrhi78nkk6jATKGyvP55sO+K7Q7Wh0DXA69hvPrYW2eu8jGCdVGxi6HX7L1qcfEd0378S71dZ3g9o6KKl1OsDWWQ6MJ6FGBZedl/ibRfs8p5+sbCX3lQSjEFy3rx6n0rUrXx8U2qb+RCLzJlmC5MNBOTDJwHPcX6gKsUcXZrEQALmRHoo3SrewO41RCr+5nUlqiqV3AohBMhnQbGzyHf2+drutIaoh7Rj80XRh2bkkuPLwlNPf+bTXwNVGse4bej7B3oV6Ae1N7lTNVF4Qh+1OowtGjmfJPWo0z1s6HFJVxoIof9z58Msvgao0zrKGqaMWaNQ6LUeC9g9Aj/9Uqjbo8X54aLiYs8Z1WNc06jKP+gv8AWLtv6CR+l2kLez1YMDucjm7v6iuCMVAmZdmxhg5I/X2+OM3vBsqPDdQpr2TPDLX3rCrSBiS0gOQ6DwN5N5QeTkxmY/7QO8bgLo/Wzu1iilH4vMKW6LBKCaRx5UEJxKpL4wkgITsYKneIt3NTHo5EOuaYk+y2+Dvt6EQFiuMsdbfUjs3seIHsghX/cbPJa4YUqZAL8C4OtVHaijwGo0ymt9MWvS9yNKMyT0JhN2/BdeOVWrHk7wXXJn/ZjpXilicXKPx4udCF76meE+6N2u/T+RYZ7fP1QMEtNZNmYDOfA6sViuPDfQSHLNbauJBo/n1sRYAsL5mcG22UDchJrlKvmK3EOADCQg+myrm8006LltubNB4wWNzHDJ0Ls2JGzQZCd/xGyVmUiidCBUrD537WdknOYE4FD7P0cHaM9brKJ/M8LkEH0zUlo73bY4XagbnCqve6PvQb5G2Z55qhWphd6f4B6DGed86zJEa/RhS
|
||||
REPO
|
||||
if ! flatpak remote-list --user --columns=name 2>/dev/null | grep -qx flathub; then
|
||||
if ! flatpak remote-list --columns=name 2>/dev/null | grep -qx flathub; then
|
||||
out=$(flatpak remote-add --user --if-not-exists flathub "$WORK/flathub.flatpakrepo" 2>&1)
|
||||
rc=$?
|
||||
echo "$out"
|
||||
|
||||
@@ -131,6 +131,12 @@ def arkham_city_x87(game):
|
||||
|
||||
|
||||
|
||||
@fix
|
||||
def teardown_vsync(game):
|
||||
if game.stem == "teardown":
|
||||
return {"vblank_mode": "2"}, [], "Teardown: OpenGL keeps the game's own vsync"
|
||||
|
||||
|
||||
@fix
|
||||
def protonfixes_off(game):
|
||||
if game.stem in ("blackops3", "darksoulsremastered"):
|
||||
@@ -432,6 +438,24 @@ def cpu_topology(env, command=()):
|
||||
print("droiddeck-game-env: Windows sees %d cores (%s)" % (len(cores), env["WINE_CPU_TOPOLOGY"]), file=sys.stderr)
|
||||
|
||||
|
||||
def gl_vsync(env):
|
||||
"""OpenGL stops waiting for each screen refresh; Steam's Frame Limit still holds the game through gamescope."""
|
||||
# Wine asks for interval 1 on every GL window, and WineD3D's front-buffer drawing (DirectDraw,
|
||||
# Direct3D 1-7) never lowers it, so those games ran at the refresh rate with no limit set.
|
||||
if "vblank_mode" in env or game_id(env) is None:
|
||||
return False
|
||||
env["vblank_mode"] = "0"
|
||||
return True
|
||||
|
||||
|
||||
def game_images(env):
|
||||
if game_id(env) is None:
|
||||
return False
|
||||
env.setdefault("GAMESCOPE_WSI_MIN_IMAGE_COUNT", "8")
|
||||
env.setdefault("GAMESCOPE_WSI_ENSURE_MIN_IMAGE_COUNT", "1")
|
||||
return True
|
||||
|
||||
|
||||
def apply_config(env, config, app_id, fixes=None):
|
||||
if config.get("version") != 1:
|
||||
raise ValueError("unsupported environment configuration")
|
||||
@@ -729,12 +753,17 @@ def main():
|
||||
digest = None
|
||||
app_id = game_id(env)
|
||||
if app_id:
|
||||
gl_default = gl_vsync(env)
|
||||
waiting = len(command) > 1 and command[1] == "waitforexitandrun"
|
||||
if waiting:
|
||||
game_images(env)
|
||||
fixes = {}
|
||||
if waiting:
|
||||
command = skip_red_launcher(command)
|
||||
ubisoft_overlay_off(env)
|
||||
fixes, extra, notes = engine_fixes(command[2], command[3:]) if len(command) > 2 else ({}, [], [])
|
||||
if not gl_default:
|
||||
fixes.pop("vblank_mode", None)
|
||||
for note in notes:
|
||||
print("droiddeck-game-env: " + note, file=sys.stderr)
|
||||
command += extra
|
||||
@@ -748,6 +777,8 @@ def main():
|
||||
with path.open(encoding="utf-8") as source:
|
||||
config = json.load(source)
|
||||
if waiting:
|
||||
if "vblank_mode" in config.get("shared", {}):
|
||||
fixes.pop("vblank_mode", None)
|
||||
env = apply_config(env, config, app_id, fixes)
|
||||
else:
|
||||
env = apply_config(env, sync_config(config, app_id), app_id)
|
||||
@@ -761,6 +792,8 @@ def main():
|
||||
env = apply_game_debug_logs(env, config, debug_dir)
|
||||
if env is not before_debug:
|
||||
print("droiddeck-game-env: game debug logs enabled for this launch", file=sys.stderr)
|
||||
if gl_default and env.get("vblank_mode") == "0":
|
||||
print("droiddeck-game-env: OpenGL does not wait for the screen refresh (vblank_mode=0)", file=sys.stderr)
|
||||
if app_id and len(command) > 1 and command[1] == "waitforexitandrun":
|
||||
command = offline_without_anticheat(command, env)
|
||||
if mic_enabled == "0":
|
||||
|
||||
@@ -0,0 +1,344 @@
|
||||
#!/usr/bin/python3
|
||||
"""GOG patch installers and the lease shared by maintenance and game launches."""
|
||||
import fcntl
|
||||
import errno
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import runpy
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
BIN = Path(__file__).resolve().parent
|
||||
IDLE = {"wineserver", "services.exe", "winedevice.exe", "explorer.exe", "rpcss.exe", "plugplay.exe",
|
||||
"conhost.exe", "lsass.exe", "svchost.exe", "steam.exe", "wineboot.exe", "winemenubuilder.exe"}
|
||||
|
||||
|
||||
def control(folder):
|
||||
folder = Path(folder).resolve(strict=True)
|
||||
root = folder / ".droiddeck-gog"
|
||||
if root.is_symlink():
|
||||
raise ValueError("GOG control directory is a symbolic link")
|
||||
root.mkdir(exist_ok=True)
|
||||
return root
|
||||
|
||||
|
||||
def read(path):
|
||||
if path.is_symlink():
|
||||
raise ValueError("GOG metadata is a symbolic link")
|
||||
return json.loads(path.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def write(path, value):
|
||||
if path.is_symlink():
|
||||
raise ValueError("GOG metadata is a symbolic link")
|
||||
descriptor, name = tempfile.mkstemp(prefix=path.name + ".", suffix=".new", dir=path.parent)
|
||||
temporary = Path(name)
|
||||
try:
|
||||
with os.fdopen(descriptor, "w") as stream:
|
||||
json.dump(value, stream)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(temporary, path)
|
||||
directory = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY)
|
||||
try:
|
||||
try:
|
||||
os.fsync(directory)
|
||||
except OSError as error:
|
||||
if error.errno not in (errno.EINVAL, errno.ENOTSUP):
|
||||
raise
|
||||
finally:
|
||||
os.close(directory)
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def lock_file(root):
|
||||
return os.fdopen(os.open(root / "lease", os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600), "r+")
|
||||
|
||||
|
||||
def generation(pid):
|
||||
try:
|
||||
return Path("/proc/%s/stat" % pid).read_text().rsplit(")", 1)[1].split()[19]
|
||||
except (OSError, IndexError):
|
||||
return None
|
||||
|
||||
|
||||
def lease(folder, owner):
|
||||
root = control(folder)
|
||||
with lock_file(root) as stream:
|
||||
fcntl.lockf(stream, fcntl.LOCK_SH | fcntl.LOCK_NB)
|
||||
sidecar = read(Path(folder) / ".droiddeck-store.json")
|
||||
if sidecar.get("state", "installed") != "installed":
|
||||
raise ValueError("Resume or recover the GOG update before playing")
|
||||
journal = root / "operation.json"
|
||||
if journal.exists() and read(journal).get("phase") != "download":
|
||||
raise ValueError("GOG maintenance is incomplete")
|
||||
start = generation(owner)
|
||||
if start is None:
|
||||
raise ValueError("Game launcher has exited")
|
||||
print("ready", flush=True)
|
||||
sys.stdout.close()
|
||||
while generation(owner) == start:
|
||||
time.sleep(0.25)
|
||||
return 0
|
||||
|
||||
|
||||
def desktop_environment(base, proc=Path("/proc")):
|
||||
env = dict(base)
|
||||
if env.get("DROIDDECK_GOG_DESKTOP") != "1":
|
||||
return env
|
||||
deadline = time.monotonic() + 45
|
||||
while True:
|
||||
for entry in proc.iterdir():
|
||||
if not entry.name.isdigit():
|
||||
continue
|
||||
try:
|
||||
command = (entry / "cmdline").read_bytes().split(b"\0")[0]
|
||||
if command != b"/usr/bin/plasmashell":
|
||||
continue
|
||||
values = dict(os.fsdecode(item).split("=", 1) for item in (entry / "environ").read_bytes().split(b"\0") if b"=" in item)
|
||||
if values.get("BL_DESKTOP") != "1" or values.get("XDG_RUNTIME_DIR") != env.get("XDG_RUNTIME_DIR"):
|
||||
continue
|
||||
if not values.get("DISPLAY") or values.get("WAYLAND_DISPLAY") == env.get("WAYLAND_DISPLAY"):
|
||||
continue
|
||||
for key in ("DISPLAY", "WAYLAND_DISPLAY", "XAUTHORITY", "DBUS_SESSION_BUS_ADDRESS", "BL_DESKTOP"):
|
||||
if key in values:
|
||||
env[key] = values[key]
|
||||
return env
|
||||
except (OSError, ValueError):
|
||||
continue
|
||||
if time.monotonic() >= deadline:
|
||||
raise ValueError("The desktop display is not ready; resume the Linux session and verify recovery before retrying")
|
||||
time.sleep(0.25)
|
||||
|
||||
|
||||
def target_for(folder, appid, game):
|
||||
run = runpy.run_path(str(BIN / "droiddeck-proton-run"))["main"].__globals__
|
||||
root = os.environ.get("STEAM_COMPAT_CLIENT_INSTALL_PATH") or run["STEAM_ROOT"]
|
||||
target = run["shortcut_target"](str(int(appid) & 0xffffffff), str(game), str(folder), root)
|
||||
target.install = str(folder)
|
||||
return run, root, target
|
||||
|
||||
|
||||
def runner(folder, appid, game, graphical=False):
|
||||
run, root, target = target_for(folder, appid, game)
|
||||
available = run["tools"](root)
|
||||
name, _ = run["choose_tool"](target.appid, run["mapping"](root), available)
|
||||
if name is None:
|
||||
raise ValueError("No Proton tool is installed for this game")
|
||||
tool, command = available[name]
|
||||
base = desktop_environment(os.environ) if graphical else dict(os.environ)
|
||||
env = run["environment"](base, target, tool, root, window=base.get("BL_DESKTOP") == "1")
|
||||
env["DROIDDECK_GOG_MAINTENANCE"] = "1"
|
||||
# Installer copy routines use x87 integer loads/stores; reduced precision corrupts paths (FEX #5827).
|
||||
env["FEX_X87REDUCEDPRECISION"] = "0"
|
||||
env.pop("BL_STORE_EXIT", None)
|
||||
return str(Path(tool) / command), env, target.compatdata
|
||||
|
||||
|
||||
def active(prefix, proc=Path("/proc")):
|
||||
result = []
|
||||
prefix = os.path.realpath(os.path.join(prefix, "pfx"))
|
||||
for entry in proc.iterdir():
|
||||
if not entry.name.isdigit():
|
||||
continue
|
||||
try:
|
||||
env = dict(part.split(b"=", 1) for part in (entry / "environ").read_bytes().split(b"\0") if b"=" in part)
|
||||
if os.path.realpath(os.fsdecode(env.get(b"WINEPREFIX", b""))) != prefix:
|
||||
continue
|
||||
args = (entry / "cmdline").read_bytes().split(b"\0")
|
||||
name = os.fsdecode(args[0]).replace("\\", "/").rsplit("/", 1)[-1].lower()
|
||||
if name not in IDLE:
|
||||
result.append(int(entry.name))
|
||||
except (OSError, ValueError):
|
||||
continue
|
||||
return result
|
||||
|
||||
|
||||
def idle(folder, appid, game):
|
||||
_, _, target = target_for(folder, appid, game)
|
||||
if active(target.compatdata):
|
||||
raise ValueError("Close the GOG game before maintenance")
|
||||
return 0
|
||||
|
||||
|
||||
def validate_installer(folder, installer):
|
||||
root = control(folder)
|
||||
path = Path(installer)
|
||||
if path.is_symlink() or not path.resolve(strict=True).is_relative_to(root / "downloads") or path.suffix.lower() != ".exe":
|
||||
raise ValueError("The patch executable is outside GOG download storage")
|
||||
with path.open("rb") as stream:
|
||||
if stream.read(2) != b"MZ":
|
||||
raise ValueError("The GOG patch is not a Windows executable")
|
||||
return path
|
||||
|
||||
|
||||
def installer_arguments(path):
|
||||
with path.open("rb") as stream:
|
||||
data = stream.read(4 * 1024 * 1024)
|
||||
return ["/NOGUI"] if b"Inno Setup Setup Data" in data else []
|
||||
|
||||
|
||||
def start(folder, appid, installer, game):
|
||||
root = control(folder)
|
||||
validate_installer(folder, installer)
|
||||
with lock_file(root) as stream:
|
||||
fcntl.lockf(stream, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
journal = read(root / "operation.json")
|
||||
if journal.get("phase") != "patch-ready":
|
||||
raise ValueError("The patch must be selected again before it can run")
|
||||
idle(folder, appid, game)
|
||||
journal["phase"] = "patch-starting"
|
||||
write(root / "operation.json", journal)
|
||||
write(root / "patch-status.json", {"state": "starting", "startedAt": time.time()})
|
||||
with (root / "patch.log").open("ab") as log:
|
||||
subprocess.Popen([sys.executable, str(Path(__file__).resolve()), "run", folder, appid, installer, game],
|
||||
stdin=subprocess.DEVNULL, stdout=log, stderr=log, start_new_session=True, close_fds=True)
|
||||
return 0
|
||||
|
||||
|
||||
def status(folder):
|
||||
root = control(folder)
|
||||
path = root / "patch-status.json"
|
||||
result = read(path)
|
||||
ended = result.get("state") == "running" and generation(result.get("pid")) != result.get("generation")
|
||||
abandoned = result.get("state") == "starting" and time.time() - result.get("startedAt", 0) > 60
|
||||
if ended or abandoned:
|
||||
result = {"state": "uncertain", "reason": "The patch helper ended without a confirmed result; verify recovery before retrying"}
|
||||
write(path, result)
|
||||
journal = read(root / "operation.json")
|
||||
journal["phase"] = "patch-uncertain"
|
||||
write(root / "operation.json", journal)
|
||||
print(json.dumps(result), flush=True)
|
||||
return 0
|
||||
|
||||
|
||||
def run_patch(folder, appid, installer, game):
|
||||
root = control(folder)
|
||||
try:
|
||||
with lock_file(root) as stream:
|
||||
fcntl.lockf(stream, fcntl.LOCK_EX)
|
||||
path = validate_installer(folder, installer)
|
||||
command, env, prefix = runner(folder, appid, game, True)
|
||||
if active(prefix):
|
||||
raise ValueError("Close the GOG game before applying the patch")
|
||||
journal = read(root / "operation.json")
|
||||
if journal.get("phase") != "patch-starting":
|
||||
raise ValueError("The patch is already running or needs recovery")
|
||||
journal["phase"] = "patch-applying"
|
||||
write(root / "operation.json", journal)
|
||||
sidecar_path = Path(folder) / ".droiddeck-store.json"
|
||||
sidecar = read(sidecar_path)
|
||||
sidecar["state"] = "updating"
|
||||
write(sidecar_path, sidecar)
|
||||
installed_path = root / "installed.json"
|
||||
if installed_path.is_file():
|
||||
installed = read(installed_path)
|
||||
installed.update(verified=False, manifest={}, files=[])
|
||||
write(installed_path, installed)
|
||||
write(root / "patch-status.json", {"state": "running", "pid": os.getpid(), "generation": generation(os.getpid())})
|
||||
os.makedirs(prefix, exist_ok=True)
|
||||
setup = runpy.run_path(str(BIN / "droiddeck-store-launch"))["main"].__globals__
|
||||
previous = dict(os.environ)
|
||||
try:
|
||||
os.environ.update(env)
|
||||
pfx = Path(prefix) / "pfx"
|
||||
if not (pfx / "system.reg").is_file() or not (pfx / "drive_c/windows/system32/reg.exe").is_file():
|
||||
subprocess.run([command, "run", "wineboot.exe", "-u"], env=env, timeout=90, check=True)
|
||||
if not (pfx / "drive_c/windows/system32/reg.exe").is_file():
|
||||
raise ValueError("Proton did not initialize the game's registry tool")
|
||||
result = setup["apply_gog_registry"](Path(folder), prefix, command, installation=journal.get("before"))
|
||||
if not result.startswith(("ready", "written=")):
|
||||
raise ValueError("GOG registry preparation failed; the patch was not applied")
|
||||
prepare_setup(folder, command, env)
|
||||
finally:
|
||||
os.environ.clear(); os.environ.update(previous)
|
||||
proc = subprocess.Popen([command, "run", str(path), *installer_arguments(path)], cwd=str(path.parent), env=env)
|
||||
code = proc.wait()
|
||||
quiet_at = time.monotonic()
|
||||
while True:
|
||||
if active(prefix):
|
||||
quiet_at = time.monotonic()
|
||||
elif time.monotonic() - quiet_at >= 2:
|
||||
break
|
||||
time.sleep(0.25)
|
||||
journal["phase"] = "patch-uncertain"
|
||||
write(root / "operation.json", journal)
|
||||
if code:
|
||||
raise ValueError("GOG patch installer exited with code %d; inspect patch.log" % code)
|
||||
write(root / "patch-status.json", {"state": "done", "exitCode": code})
|
||||
return 0
|
||||
except Exception as error:
|
||||
write(root / "patch-status.json", {"state": "failed", "reason": str(error)})
|
||||
return 1
|
||||
|
||||
|
||||
def prepare_setup(folder, command, env):
|
||||
root = control(folder)
|
||||
record_path = root / "installed.json"
|
||||
if not record_path.is_file():
|
||||
return
|
||||
journal = read(root / "operation.json")
|
||||
record = journal.get("before") or read(record_path)
|
||||
manifest = record.get("manifest", {})
|
||||
if not record.get("build"):
|
||||
return
|
||||
info_path = Path(folder) / ("goggame-%s.info" % record["id"])
|
||||
language = read(info_path).get("language", "") if info_path.is_file() else ""
|
||||
legacy = manifest.get("product", {})
|
||||
products = manifest.get("products", []) if not legacy else [
|
||||
{"productId": str(item["gameID"]), "temp_executable": item["executable"].lstrip("/\\")}
|
||||
for item in legacy.get("support_commands", [])
|
||||
if "Neutral" in item.get("languages", []) or record.get("language") in item.get("languages", []) or language in item.get("languages", [])]
|
||||
for product in products:
|
||||
if str(product.get("productId")) not in record.get("products", []):
|
||||
continue
|
||||
program = None
|
||||
if manifest.get("scriptInterpreter"):
|
||||
if not (Path(folder) / ("goggame-%s.script" % product["productId"])).is_file():
|
||||
continue
|
||||
program = Path(folder) / "support/__redist/ISI/scriptinterpreter.exe"
|
||||
elif product.get("temp_executable"):
|
||||
relative = product["temp_executable"].replace("\\", "/")
|
||||
for candidate in (Path(folder) / "support" / str(product["productId"]) / relative, Path(folder) / relative):
|
||||
if candidate.is_file():
|
||||
program = candidate
|
||||
break
|
||||
if program is None:
|
||||
continue
|
||||
if not program.resolve(strict=True).is_relative_to(Path(folder).resolve()):
|
||||
raise ValueError("GOG setup executable leaves the installation")
|
||||
windows = "Z:" + str(Path(folder).resolve()).replace("/", "\\")
|
||||
args = ["/VERYSILENT", "/DIR=" + windows, "/ProductId=" + str(product["productId"]),
|
||||
"/galaxyclient", "/buildId=" + str(legacy.get("timestamp", record["build"])), "/versionName=" + record.get("version", ""),
|
||||
"/lang-code=" + record.get("language", "en-US"), "/supportDir=" + windows + "\\support", "/nodesktopshortcut"]
|
||||
if language:
|
||||
args += ["/Language=" + language, "/LANG=" + language.lower()]
|
||||
result = subprocess.run([command, "run", str(program), *args], env=env, cwd=folder, timeout=120)
|
||||
if result.returncode:
|
||||
raise ValueError("GOG installation setup failed; the patch was not applied")
|
||||
|
||||
|
||||
def main(argv):
|
||||
if len(argv) == 3 and argv[0] == "lease":
|
||||
return lease(argv[1], int(argv[2]))
|
||||
if len(argv) == 4 and argv[0] == "idle":
|
||||
return idle(*argv[1:])
|
||||
if len(argv) == 2 and argv[0] == "status":
|
||||
return status(argv[1])
|
||||
if len(argv) == 5 and argv[0] == "start":
|
||||
return start(*argv[1:])
|
||||
if len(argv) == 5 and argv[0] == "run":
|
||||
return run_patch(*argv[1:])
|
||||
raise ValueError("Invalid GOG maintenance command")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
except Exception as error:
|
||||
print("GOG maintenance: " + str(error), file=sys.stderr)
|
||||
sys.exit(1)
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
#!/usr/bin/env python3
|
||||
import json
|
||||
import os
|
||||
import select
|
||||
import socket
|
||||
import struct
|
||||
import sys
|
||||
import time
|
||||
|
||||
DISPLAY_ID = 1
|
||||
REGISTRY_ID = 2
|
||||
METHOD_ID = 3
|
||||
SETTLE = 0.15
|
||||
|
||||
|
||||
def wl_string(value):
|
||||
data = value.encode() + b"\0"
|
||||
return struct.pack("<I", len(data)) + data + b"\0" * (-len(data) % 4)
|
||||
|
||||
|
||||
def read_string(payload, offset):
|
||||
(length,) = struct.unpack_from("<I", payload, offset)
|
||||
start = offset + 4
|
||||
text = payload[start:start + length - 1].decode(errors="replace")
|
||||
return text, start + length + (-length % 4)
|
||||
|
||||
|
||||
class Connection:
|
||||
def __init__(self, sock):
|
||||
self.sock = sock
|
||||
self.buffer = b""
|
||||
|
||||
def send(self, obj, opcode, payload=b""):
|
||||
self.sock.sendall(struct.pack("<II", obj, ((8 + len(payload)) << 16) | opcode) + payload)
|
||||
|
||||
def messages(self, timeout):
|
||||
ready, _, _ = select.select([self.sock], [], [], timeout)
|
||||
if not ready:
|
||||
return []
|
||||
data, _, _, _ = self.sock.recvmsg(65536, socket.CMSG_SPACE(16 * 4))
|
||||
if not data:
|
||||
raise EOFError
|
||||
self.buffer += data
|
||||
out = []
|
||||
while len(self.buffer) >= 8:
|
||||
obj, word = struct.unpack_from("<II", self.buffer)
|
||||
size = word >> 16
|
||||
if size < 8 or len(self.buffer) < size:
|
||||
break
|
||||
out.append((obj, word & 0xFFFF, self.buffer[8:size]))
|
||||
self.buffer = self.buffer[size:]
|
||||
return out
|
||||
|
||||
|
||||
class Report:
|
||||
def __init__(self, directory):
|
||||
self.directory = directory
|
||||
self.seq = 0
|
||||
self.sent = None
|
||||
|
||||
def write(self, field, hint=0, purpose=0):
|
||||
state = (field, purpose)
|
||||
if state == self.sent or not self.directory:
|
||||
return
|
||||
self.sent = state
|
||||
self.seq += 1
|
||||
os.makedirs(self.directory, exist_ok=True)
|
||||
target = os.path.join(self.directory, "ime.json")
|
||||
temp = target + ".tmp"
|
||||
fd = os.open(temp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||||
with os.fdopen(fd, "w") as handle:
|
||||
json.dump({"textField": field, "hint": hint, "purpose": purpose, "seq": self.seq}, handle)
|
||||
os.replace(temp, target)
|
||||
print(f"droiddeck-ime: text field {'focused' if field else 'left'}", file=sys.stderr, flush=True)
|
||||
|
||||
|
||||
def connect():
|
||||
fd = os.environ.pop("WAYLAND_SOCKET", "")
|
||||
if fd.isdigit():
|
||||
return socket.socket(socket.AF_UNIX, socket.SOCK_STREAM, fileno=int(fd))
|
||||
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
sock.connect(os.path.join(os.environ["XDG_RUNTIME_DIR"], os.environ.get("WAYLAND_DISPLAY", "wayland-0")))
|
||||
return sock
|
||||
|
||||
|
||||
def main():
|
||||
launch = os.environ.get("BL_LAUNCH_DIR", "")
|
||||
report = Report(os.path.join(launch, "agent") if launch else "")
|
||||
conn = Connection(connect())
|
||||
conn.send(DISPLAY_ID, 1, struct.pack("<I", REGISTRY_ID))
|
||||
contexts = {}
|
||||
current = None
|
||||
pending = None
|
||||
while True:
|
||||
timeout = None if pending is None else max(0.0, pending - time.monotonic())
|
||||
try:
|
||||
batch = conn.messages(timeout)
|
||||
except (EOFError, ConnectionError):
|
||||
report.write(False)
|
||||
return 0
|
||||
for obj, opcode, payload in batch:
|
||||
if obj == DISPLAY_ID and opcode == 0:
|
||||
_, code = struct.unpack_from("<II", payload)
|
||||
message, _ = read_string(payload, 8)
|
||||
print(f"droiddeck-ime: protocol error {code}: {message}", file=sys.stderr, flush=True)
|
||||
report.write(False)
|
||||
return 1
|
||||
if obj == REGISTRY_ID and opcode == 0:
|
||||
(name,) = struct.unpack_from("<I", payload)
|
||||
interface, offset = read_string(payload, 4)
|
||||
(version,) = struct.unpack_from("<I", payload, offset)
|
||||
if interface == "zwp_input_method_v1":
|
||||
conn.send(REGISTRY_ID, 0, struct.pack("<I", name) + wl_string(interface)
|
||||
+ struct.pack("<II", min(version, 1), METHOD_ID))
|
||||
elif obj == METHOD_ID and opcode == 0:
|
||||
(context,) = struct.unpack_from("<I", payload)
|
||||
contexts[context] = [0, 0]
|
||||
current = context
|
||||
pending = None
|
||||
report.write(True)
|
||||
elif obj == METHOD_ID and opcode == 1:
|
||||
(context,) = struct.unpack_from("<I", payload)
|
||||
contexts.pop(context, None)
|
||||
conn.send(context, 0)
|
||||
if context == current:
|
||||
current = None
|
||||
pending = time.monotonic() + SETTLE
|
||||
elif obj in contexts and opcode == 2:
|
||||
hint, purpose = struct.unpack_from("<II", payload)
|
||||
contexts[obj] = [hint, purpose]
|
||||
if obj == current:
|
||||
report.write(True, hint, purpose)
|
||||
if pending is not None and time.monotonic() >= pending:
|
||||
pending = None
|
||||
if current is None:
|
||||
report.write(False)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,93 @@
|
||||
#!/usr/bin/python3
|
||||
import os
|
||||
import re
|
||||
import stat
|
||||
import sys
|
||||
|
||||
HOME = os.environ.get("HOME", "/root")
|
||||
STEAM = os.path.join(HOME, ".local/share/Steam")
|
||||
STORES = os.environ.get("DROIDDECK_STORES_ROOT", "/mnt/droiddeck-stores")
|
||||
TOOLS = re.compile(r"^(Proton |Proton$|SteamLinuxRuntime|Steamworks Shared$)")
|
||||
|
||||
|
||||
def libraries():
|
||||
paths = [STEAM]
|
||||
try:
|
||||
with open(os.path.join(STEAM, "steamapps/libraryfolders.vdf"), encoding="utf-8", errors="replace") as f:
|
||||
paths += [p.replace("\\\\", "\\") for p in re.findall(r'"path"\s+"([^"]+)"', f.read())]
|
||||
except OSError:
|
||||
pass
|
||||
seen = []
|
||||
for path in paths:
|
||||
real = os.path.realpath(path)
|
||||
if real not in seen:
|
||||
seen.append(real)
|
||||
return seen
|
||||
|
||||
|
||||
def roots():
|
||||
found = []
|
||||
for library in libraries():
|
||||
for name in ("common", "compatdata"):
|
||||
found.append((os.path.join(library, "steamapps", name), name == "common"))
|
||||
found.append((os.path.join(HOME, "Games"), False))
|
||||
try:
|
||||
found += [(entry.path, False) for entry in os.scandir(STORES) if entry.is_dir(follow_symlinks=False)]
|
||||
except OSError:
|
||||
pass
|
||||
return [(path, skip_tools) for path, skip_tools in found if os.path.isdir(path)]
|
||||
|
||||
|
||||
def fix(path, st, wanted):
|
||||
if st.st_uid != os.geteuid() or st.st_mode & wanted == wanted:
|
||||
return 0
|
||||
try:
|
||||
os.chmod(path, stat.S_IMODE(st.st_mode) | wanted)
|
||||
return 1
|
||||
except OSError:
|
||||
return 0
|
||||
|
||||
|
||||
def walk(top, skip_tools):
|
||||
fixed = 0
|
||||
stack = [(top, True)]
|
||||
while stack:
|
||||
directory, first = stack.pop()
|
||||
try:
|
||||
entries = list(os.scandir(directory))
|
||||
except OSError:
|
||||
continue
|
||||
for entry in entries:
|
||||
if first and skip_tools and TOOLS.match(entry.name):
|
||||
continue
|
||||
try:
|
||||
st = entry.stat(follow_symlinks=False)
|
||||
except OSError:
|
||||
continue
|
||||
if stat.S_ISDIR(st.st_mode):
|
||||
fixed += fix(entry.path, st, stat.S_IRWXU)
|
||||
stack.append((entry.path, False))
|
||||
elif stat.S_ISREG(st.st_mode):
|
||||
fixed += fix(entry.path, st, stat.S_IRUSR | stat.S_IWUSR)
|
||||
return fixed
|
||||
|
||||
|
||||
def main():
|
||||
try:
|
||||
os.nice(19)
|
||||
except OSError:
|
||||
pass
|
||||
total = 0
|
||||
for top, skip_tools in roots():
|
||||
try:
|
||||
fixed = fix(top, os.stat(top), stat.S_IRWXU) + walk(top, skip_tools)
|
||||
except OSError:
|
||||
continue
|
||||
if fixed:
|
||||
print(f"droiddeck-library-perms: {top}: {fixed} made writable")
|
||||
total += fixed
|
||||
print(f"droiddeck-library-perms: {total} files and folders made writable")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
#!/usr/bin/python3
|
||||
import array
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import socket
|
||||
import struct
|
||||
import sys
|
||||
|
||||
SOCKET_FILE = "/etc/droiddeck/root-socket"
|
||||
|
||||
|
||||
def socket_name():
|
||||
name = os.environ.get("DROIDDECK_ROOT_SOCKET", "")
|
||||
if not name:
|
||||
try:
|
||||
with open(SOCKET_FILE, encoding="utf-8") as f:
|
||||
name = f.read().strip()
|
||||
except OSError:
|
||||
pass
|
||||
return "\0" + (name or "com.droiddeck.launcher.root")
|
||||
|
||||
|
||||
def frame(sock, kind, payload):
|
||||
sock.sendall(kind.encode() + struct.pack(">i", len(payload)) + payload)
|
||||
|
||||
|
||||
def read_exact(sock, n):
|
||||
data = b""
|
||||
while len(data) < n:
|
||||
chunk = sock.recv(n - len(data))
|
||||
if not chunk:
|
||||
return None
|
||||
data += chunk
|
||||
return data
|
||||
|
||||
|
||||
def main(argv):
|
||||
if len(argv) < 2 or argv[1] in ("-h", "--help"):
|
||||
print("usage: droiddeck-root [--check] command [arg ...]", file=sys.stderr)
|
||||
return 2
|
||||
try:
|
||||
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
sock.connect(socket_name())
|
||||
except OSError as e:
|
||||
print(f"droiddeck-root: DroidDeck's root service is not reachable: {e}", file=sys.stderr)
|
||||
return 126
|
||||
if argv[1] == "--check":
|
||||
return 0
|
||||
env = dict(os.environ)
|
||||
for name in ("LD_PRELOAD", "PROOT_FASTPATH", "DROIDDECK_ROOT_SOCKET"):
|
||||
env.pop(name, None)
|
||||
for name in [k for k in env if k.startswith("PROOT_")]:
|
||||
env.pop(name, None)
|
||||
try:
|
||||
cwd = os.getcwd()
|
||||
except OSError:
|
||||
cwd = "/root"
|
||||
body = json.dumps({"argv": argv[1:], "env": env, "cwd": cwd}).encode()
|
||||
fds = array.array("i", [0, 1, 2])
|
||||
sock.sendmsg([b"R" + struct.pack(">i", len(body))], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, fds)])
|
||||
sock.sendall(body)
|
||||
|
||||
def forward(signum, _frame):
|
||||
try:
|
||||
frame(sock, "S", str(signum).encode())
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
for signum in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP, signal.SIGQUIT, signal.SIGUSR1, signal.SIGUSR2):
|
||||
signal.signal(signum, forward)
|
||||
signal.signal(signal.SIGTSTP, signal.SIG_IGN)
|
||||
status = 1
|
||||
while True:
|
||||
try:
|
||||
head = read_exact(sock, 5)
|
||||
except InterruptedError:
|
||||
continue
|
||||
except OSError:
|
||||
break
|
||||
if head is None:
|
||||
break
|
||||
kind = chr(head[0])
|
||||
payload = read_exact(sock, struct.unpack(">i", head[1:])[0]) or b""
|
||||
if kind == "E":
|
||||
print("droiddeck-root: " + payload.decode(errors="replace"), file=sys.stderr)
|
||||
elif kind == "X":
|
||||
status = int(payload.decode() or "1")
|
||||
break
|
||||
return status
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv))
|
||||
@@ -14,22 +14,59 @@ if [ -n "${BL_LOG:-}" ] && [ -z "${BL_INSIDE:-}" ]; then
|
||||
if [ "$(stat -c %s "$BL_LOG" 2>/dev/null || echo 0)" -gt 8388608 ]; then
|
||||
mv -f "$BL_LOG" "$BL_LOG.1"
|
||||
fi
|
||||
exec > >({ dd of="$BL_LOG" oflag=append conv=notrunc iflag=count_bytes count="${BL_LOG_CAP:-268435456}" bs=65536 status=none; cat >/dev/null; }) 2>&1
|
||||
dd=$(command -v gnudd || echo dd)
|
||||
exec > >({ "$dd" of="$BL_LOG" oflag=append conv=notrunc iflag=count_bytes count="${BL_LOG_CAP:-268435456}" bs=65536 status=none; cat >/dev/null; }) 2>&1
|
||||
echo "== droiddeck-session $(date) mode=$mode $*"
|
||||
echo "== uid=$(id -u) size=${BL_WIDTH:-?}x${BL_HEIGHT:-?} icd=${VK_ICD_FILENAMES:-none}"
|
||||
echo "== gamescope: $(gamescope --version 2>&1 | head -1) at $(command -v gamescope)"
|
||||
echo "== rootfs: $(cat /.version 2>/dev/null || echo unversioned)"
|
||||
fi
|
||||
|
||||
sync_timezone() {
|
||||
local zone=${TZ:-}
|
||||
case "$zone" in ''|/*|*..*) return 0 ;; esac
|
||||
[ -f "/usr/share/zoneinfo/$zone" ] || return 0
|
||||
if [ "$(readlink /etc/localtime 2>/dev/null)" != "/usr/share/zoneinfo/$zone" ]; then
|
||||
ln -sfn "/usr/share/zoneinfo/$zone" /etc/localtime.droiddeck && mv -Tf /etc/localtime.droiddeck /etc/localtime || return 0
|
||||
fi
|
||||
[ "$(cat /etc/timezone 2>/dev/null)" = "$zone" ] || printf '%s\n' "$zone" > /etc/timezone
|
||||
} 2>/dev/null
|
||||
sync_timezone
|
||||
|
||||
write_system_bus_config() {
|
||||
mkdir -p /run/dbus /usr/local/share/droiddeck
|
||||
cat > /usr/local/share/droiddeck/system-bus.conf <<'BUSCONF'
|
||||
<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN"
|
||||
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
|
||||
<busconfig>
|
||||
<type>system</type>
|
||||
<listen>unix:path=/run/dbus/system_bus_socket</listen>
|
||||
<auth>EXTERNAL</auth>
|
||||
<servicedir>/usr/share/droiddeck/system-services</servicedir>
|
||||
<policy context="default">
|
||||
<allow user="*"/>
|
||||
<allow own="*"/>
|
||||
<allow send_destination="*"/>
|
||||
<allow receive_sender="*"/>
|
||||
</policy>
|
||||
</busconfig>
|
||||
BUSCONF
|
||||
rm -f /run/dbus/system_bus_socket
|
||||
}
|
||||
|
||||
prepare_locale() {
|
||||
local dir=/usr/lib/locale stamp=/usr/lib/locale/.droiddeck-archive want have= pkg
|
||||
pkg=(/var/lib/pacman/local/glibc-[0-9]*)
|
||||
want=${pkg[0]##*/}
|
||||
if [ -d /var/lib/pacman/local ]; then
|
||||
pkg=(/var/lib/pacman/local/glibc-[0-9]*)
|
||||
want=${pkg[0]##*/}
|
||||
else
|
||||
want=libc6-$(dpkg-query -W -f='${Version}' libc6 2>/dev/null)
|
||||
fi
|
||||
[ -f "$stamp" ] && read -r have < "$stamp"
|
||||
[ "$have" = "$want" ] && [ -f "$dir/locale-archive" ] && [ ! "$dir/locale-archive" -nt "$stamp" ] && return 0
|
||||
[ -d "$dir/C.utf8" ] && command -v localedef >/dev/null 2>&1 || return 0
|
||||
DROIDDECK_LINK_RENAME=1 localedef --add-to-archive --replace "$dir/C.utf8" >/dev/null 2>&1 || return 0
|
||||
rm -f /usr/lib/gconv/gconv-modules.cache
|
||||
rm -f /usr/lib/gconv/gconv-modules.cache /usr/lib/aarch64-linux-gnu/gconv/gconv-modules.cache
|
||||
command -v iconvconfig >/dev/null 2>&1 && iconvconfig >/dev/null 2>&1
|
||||
printf '%s\n' "$want" > "$stamp"
|
||||
echo "== locale archive built for $want"
|
||||
@@ -64,8 +101,33 @@ if [ -z "${BL_INSIDE:-}" ]; then
|
||||
if [ "${BL_ZRAM:-0}" = 1 ]; then printf 0 > /tmp/.bl-zram; else rm -f /tmp/.bl-zram; fi
|
||||
fi
|
||||
|
||||
steam_devtools() {
|
||||
_bl_cdp=()
|
||||
if [ -f "$steam_root/.cef-enable-remote-debugging" ]; then
|
||||
if timeout 5 python3 -c 'import socket, sys
|
||||
s = socket.socket()
|
||||
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
s.bind(("127.0.0.1", int(sys.argv[1])))' "$1" 2>/dev/null; then
|
||||
BL_CDP_PORT=$1
|
||||
return 0
|
||||
fi
|
||||
echo "== steam: port $1 is held by another app; Decky cannot load this session and Steam's devtools use another port"
|
||||
fi
|
||||
BL_CDP_PORT=$((20000 + RANDOM % 30000))
|
||||
_bl_cdp=(-cef-enable-debugging -devtools-port "$BL_CDP_PORT")
|
||||
}
|
||||
|
||||
steam_update_stuck() {
|
||||
[ "$1" -lt 60 ] || steam_updates=0
|
||||
local stamp
|
||||
stamp=$(stat -c '%n %Y %s' "${steam_root:-}"/package/*.installed 2>/dev/null)
|
||||
if [ "$1" -ge 60 ]; then
|
||||
steam_updates=0
|
||||
steam_installs=0
|
||||
elif [ "$stamp" != "${steam_update_stamp-$stamp}" ] && [ "${steam_installs:-0}" -lt 5 ]; then
|
||||
steam_updates=0
|
||||
steam_installs=$((${steam_installs:-0} + 1))
|
||||
fi
|
||||
steam_update_stamp=$stamp
|
||||
steam_updates=$((steam_updates + 1))
|
||||
[ "$steam_updates" -ge 3 ]
|
||||
}
|
||||
@@ -134,6 +196,7 @@ rm -f "${XDG_RUNTIME_DIR:-/run/droiddeck}/droiddeck-remote-play"
|
||||
/usr/local/bin/droiddeck-steamvr unregister >/dev/null 2>&1 || true
|
||||
if [ "$mode" = lxqt ] || [ "$mode" = desktop ]; then
|
||||
/usr/local/bin/droiddeck-desktop-bookmarks || true
|
||||
/usr/local/bin/droiddeck-downloads || true
|
||||
fi
|
||||
export FLATPAK_BWRAP=/usr/local/bin/droiddeck-bwrap
|
||||
export XDG_DATA_DIRS=$XDG_DATA_HOME/flatpak/exports/share:${XDG_DATA_DIRS:-/usr/local/share:/usr/share}
|
||||
@@ -201,6 +264,20 @@ if [ -z "${BL_INSIDE:-}" ]; then
|
||||
step "starting the desktop"
|
||||
start_agent --no-focus
|
||||
[ -x /usr/local/bin/droiddeck-desktop ] || { echo "== the desktop package is not installed"; exit 66; }
|
||||
if command -v dbus-daemon >/dev/null 2>&1 && command -v droiddeck-netmanager >/dev/null 2>&1; then
|
||||
write_system_bus_config
|
||||
dbus-daemon --config-file=/usr/local/share/droiddeck/system-bus.conf --nofork --nopidfile &
|
||||
for _ in $(seq 1 50); do
|
||||
[ -S /run/dbus/system_bus_socket ] && break
|
||||
nap 0.1
|
||||
done
|
||||
if [ -S /run/dbus/system_bus_socket ]; then
|
||||
droiddeck-login1 --with-netmanager &
|
||||
echo "== desktop: system bus up, network and power services running"
|
||||
else
|
||||
echo "== desktop: the system bus did not come up"
|
||||
fi
|
||||
fi
|
||||
cores=$(program_cores)
|
||||
if [ -n "$cores" ]; then
|
||||
echo "== desktop cores: $cores (the desktop and every program started from it)"
|
||||
@@ -257,6 +334,8 @@ if [ -z "${BL_INSIDE:-}" ]; then
|
||||
args+=(--mangoapp)
|
||||
echo "== gamescope: mangoapp on ($(command -v mangoapp), config $MANGOHUD_CONFIGFILE)"
|
||||
fi
|
||||
# gamescope writes the frame times the app's HUD shows here (patch 0125).
|
||||
mkdir -p /run/droiddeck-hud && export DROIDDECK_HUD_FRAMES=/run/droiddeck-hud/frames
|
||||
export BL_INSIDE=1
|
||||
# A fixed path: left to itself gamescope creates a new limiter state file on every start.
|
||||
rm -f "${XDG_RUNTIME_DIR:-/tmp}"/gamescope-limiter-*
|
||||
@@ -459,7 +538,7 @@ case $mode in
|
||||
fi
|
||||
if [ "${BL_ZRAM:-0}" = 1 ]; then
|
||||
step "zRAM compression: on"
|
||||
[ "${BL_ZRAM_CLIENT:-1}" = 1 ] || step "zRAM: Steam is not compressed while games run (turned off in Performance)"
|
||||
[ "${BL_ZRAM_CLIENT:-1}" = 1 ] || step "zRAM: Steam and the hidden Epic Games Launcher are not compressed while games run (turned off in Performance)"
|
||||
_bl_ram_cap=0
|
||||
case ${BL_RAM_CAP_MB:-} in
|
||||
''|0) ;;
|
||||
@@ -469,16 +548,16 @@ case $mode in
|
||||
(
|
||||
bl_zram_scan() {
|
||||
_bl_game=0 _bl_pids=() _bl_others=() _bl_apps=
|
||||
local _d _c _args _name _a _id
|
||||
local _d _c _args _name _a _id _fex
|
||||
for _d in /proc/[0-9]*; do
|
||||
[ "${_d##*/}" != "$BASHPID" ] || continue
|
||||
_args=()
|
||||
# Under FEX the program is FEX's first argument. AppId= is its own argument.
|
||||
while IFS= read -r -d '' _c; do _args+=("$_c"); done 2>/dev/null < "$_d/cmdline" || true
|
||||
[ "${#_args[@]}" -gt 0 ] || continue
|
||||
_name=${_args[0]}
|
||||
_name=${_args[0]} _fex=0
|
||||
if [ "${#_args[@]}" -gt 1 ]; then
|
||||
case ${_name##*/} in FEX|FEXInterpreter) _name=${_args[1]} ;; esac
|
||||
case ${_name##*/} in FEX|FEXInterpreter) _name=${_args[1]} _fex=1 ;; esac
|
||||
fi
|
||||
case ${_name##*/} in
|
||||
reaper)
|
||||
@@ -493,7 +572,13 @@ case $mode in
|
||||
done
|
||||
;;
|
||||
steam|steamwebhelper) _bl_pids+=("${_d##*/}") ;;
|
||||
*) _bl_others+=("${_d##*/}") ;;
|
||||
*)
|
||||
if [ "$_fex" = 1 ] && grep -qz '^DROIDDECK_EPIC_HIDDEN=1$' "$_d/environ" 2>/dev/null; then
|
||||
_bl_pids+=("${_d##*/}")
|
||||
else
|
||||
_bl_others+=("${_d##*/}")
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
done
|
||||
}
|
||||
@@ -840,23 +925,7 @@ case $mode in
|
||||
set -- "$@" "$_bl_url"
|
||||
fi
|
||||
if command -v dbus-daemon >/dev/null 2>&1 && command -v droiddeck-netmanager >/dev/null 2>&1; then
|
||||
mkdir -p /run/dbus /usr/local/share/droiddeck
|
||||
cat > /usr/local/share/droiddeck/system-bus.conf <<'BUSCONF'
|
||||
<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN"
|
||||
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
|
||||
<busconfig>
|
||||
<type>system</type>
|
||||
<listen>unix:path=/run/dbus/system_bus_socket</listen>
|
||||
<auth>EXTERNAL</auth>
|
||||
<policy context="default">
|
||||
<allow user="*"/>
|
||||
<allow own="*"/>
|
||||
<allow send_destination="*"/>
|
||||
<allow receive_sender="*"/>
|
||||
</policy>
|
||||
</busconfig>
|
||||
BUSCONF
|
||||
rm -f /run/dbus/system_bus_socket
|
||||
write_system_bus_config
|
||||
dbus-daemon --config-file=/usr/local/share/droiddeck/system-bus.conf --nofork --nopidfile &
|
||||
system_bus=$!
|
||||
for _ in $(seq 1 50); do
|
||||
@@ -930,14 +999,9 @@ BUSCONF
|
||||
echo "== Decky: installed loader architecture is unsupported by this guest; not starting"
|
||||
fi
|
||||
fi
|
||||
_bl_cdp=()
|
||||
if [ -f "$steam_root/.cef-enable-remote-debugging" ]; then
|
||||
export BL_CDP_PORT=8080
|
||||
else
|
||||
export BL_CDP_PORT=$((20000 + RANDOM % 30000))
|
||||
_bl_cdp=(-cef-enable-debugging -devtools-port "$BL_CDP_PORT")
|
||||
fi
|
||||
if [ -f "$HOME/.droiddeck-decky-enabled" ] && [ "${decky_arch:-}" = x86_64 ]; then
|
||||
steam_devtools 8080
|
||||
export BL_CDP_PORT
|
||||
if [ -f "$HOME/.droiddeck-decky-enabled" ] && [ "${decky_arch:-}" = x86_64 ] && [ ${#_bl_cdp[@]} = 0 ]; then
|
||||
echo "== steam: devtools port $BL_CDP_PORT left open for the x86_64 Decky loader"
|
||||
else
|
||||
export BL_CDP_GUARD=$BL_CDP_PORT
|
||||
@@ -996,6 +1060,8 @@ BUSCONF
|
||||
fi
|
||||
echo "== steam args: ${_bl_ui[*]} ${_bl_cdp[*]} ${_bl_lang[*]} -clientbeta $steam_channel -no-cef-sandbox -cef-ozone-platform=x11 ${_bl_cef[*]} $*$([ "$steam_x64" = 1 ] && echo ' (x86-64 client under FEX)')"
|
||||
steam_updates=0
|
||||
steam_installs=0
|
||||
steam_update_stamp=$(stat -c '%n %Y %s' "$steam_root"/package/*.installed 2>/dev/null)
|
||||
rm -f "$HOME/.bl-stop-requested" "$STEAMOS_STEAM_SHUTDOWN_SENTINEL" "$STEAMOS_STEAM_REBOOT_SENTINEL"
|
||||
steam_other_game_running() {
|
||||
local line value n open
|
||||
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
#!/bin/bash
|
||||
[ "${1:-}" = run ] || exec /usr/bin/snap "$@"
|
||||
shift
|
||||
while [ $# -gt 0 ]; do
|
||||
case $1 in
|
||||
--) shift; break ;;
|
||||
-*) shift ;;
|
||||
*) break ;;
|
||||
esac
|
||||
done
|
||||
target=${1:?usage: snap run <snap>[.<app>] [args...]}
|
||||
shift
|
||||
name=${target%%.*}
|
||||
app=${target#*.}
|
||||
exec /usr/local/bin/droiddeck-snap-run "$name" "$app" "$@"
|
||||
@@ -0,0 +1,19 @@
|
||||
#!/bin/bash
|
||||
while [ $# -gt 0 ]; do
|
||||
case $1 in
|
||||
--classic) shift ;;
|
||||
--base) shift 2 ;;
|
||||
--*) shift ;;
|
||||
*) break ;;
|
||||
esac
|
||||
done
|
||||
tag=${1:?security tag}
|
||||
shift
|
||||
[ "${1##*/}" = snap-exec ] && shift
|
||||
app=${1:-}
|
||||
shift
|
||||
name=${tag#snap.}
|
||||
name=${name%%.*}
|
||||
app=${app#*.}
|
||||
[ -n "$app" ] || app=$name
|
||||
exec /usr/local/bin/droiddeck-snap-run "$name" "$app" "$@"
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
#!/usr/bin/python3
|
||||
import os
|
||||
import re
|
||||
import shlex
|
||||
import sys
|
||||
|
||||
import yaml
|
||||
|
||||
SNAP_DIR = "/snap"
|
||||
HOST_DIRS = ("/etc", "/home", "/root", "/tmp", "/run", "/var/snap", "/var/lib/snapd", "/var/tmp", "/var/log",
|
||||
"/media", "/mnt", "/snap", "/usr/src", "/lib/modules")
|
||||
|
||||
|
||||
def load(name):
|
||||
with open(f"{SNAP_DIR}/{name}/current/meta/snap.yaml") as f:
|
||||
return yaml.safe_load(f) or {}
|
||||
|
||||
|
||||
def expand(value, env):
|
||||
return re.sub(r"\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?", lambda m: env.get(m.group(1), ""), str(value))
|
||||
|
||||
|
||||
def provider_path(path, provider, revision):
|
||||
snap = f"{SNAP_DIR}/{provider}/{revision}"
|
||||
for var, value in (("$SNAP_DATA", f"/var/snap/{provider}/{revision}"),
|
||||
("$SNAP_COMMON", f"/var/snap/{provider}/common"), ("$SNAP", snap)):
|
||||
if path == var or path.startswith(var + "/"):
|
||||
return os.path.normpath(value + path[len(var):])
|
||||
return os.path.normpath(f"{snap}/{path}")
|
||||
|
||||
|
||||
def content_binds(name, meta, env):
|
||||
out = []
|
||||
for plug_name, plug in (meta.get("plugs") or {}).items():
|
||||
if not isinstance(plug, dict) or plug.get("interface") != "content" or not plug.get("target"):
|
||||
continue
|
||||
provider = (plug.get("default-provider") or "").split(":")[0]
|
||||
if not provider or not os.path.isdir(f"{SNAP_DIR}/{provider}/current"):
|
||||
continue
|
||||
try:
|
||||
slots = load(provider).get("slots") or {}
|
||||
except OSError:
|
||||
continue
|
||||
revision = os.path.basename(os.path.realpath(f"{SNAP_DIR}/{provider}/current"))
|
||||
target = expand(plug["target"], env)
|
||||
for slot_name, slot in slots.items():
|
||||
if not isinstance(slot, dict) or slot.get("interface") != "content":
|
||||
continue
|
||||
if slot.get("content", slot_name) != plug.get("content", plug_name):
|
||||
continue
|
||||
nested = "source" in slot
|
||||
reads = (slot.get("source") or {}).get("read") if nested else slot.get("read")
|
||||
for path in reads or []:
|
||||
source = provider_path(str(path), provider, revision)
|
||||
out.append((plug_name, source, os.path.join(target, os.path.basename(source)) if nested else target))
|
||||
if not nested:
|
||||
break
|
||||
break
|
||||
return out
|
||||
|
||||
|
||||
def main(argv):
|
||||
if len(argv) < 3:
|
||||
print("usage: droiddeck-snap-run SNAP APP [ARG...]", file=sys.stderr)
|
||||
return 2
|
||||
name, app, args = argv[1], argv[2], argv[3:]
|
||||
meta = load(name)
|
||||
spec = (meta.get("apps") or {}).get(app)
|
||||
if spec is None:
|
||||
print(f"error: snap \"{name}\" has no app \"{app}\"", file=sys.stderr)
|
||||
return 1
|
||||
revision = os.path.basename(os.path.realpath(f"{SNAP_DIR}/{name}/current"))
|
||||
home = os.environ.get("HOME", "/root")
|
||||
snap = f"{SNAP_DIR}/{name}/{revision}"
|
||||
env = dict(os.environ)
|
||||
for k in ("LD_PRELOAD", "LD_LIBRARY_PATH"):
|
||||
env.pop(k, None)
|
||||
env.update({
|
||||
"SNAP": snap, "SNAP_NAME": name, "SNAP_INSTANCE_NAME": name, "SNAP_INSTANCE_KEY": "",
|
||||
"SNAP_REVISION": revision, "SNAP_VERSION": str(meta.get("version", "")), "SNAP_ARCH": "arm64",
|
||||
"SNAP_LIBRARY_PATH": "/var/lib/snapd/lib/gl:/var/lib/snapd/lib/gl32:/var/lib/snapd/void",
|
||||
"SNAP_DATA": f"/var/snap/{name}/{revision}", "SNAP_COMMON": f"/var/snap/{name}/common",
|
||||
"SNAP_USER_DATA": f"{home}/snap/{name}/{revision}", "SNAP_USER_COMMON": f"{home}/snap/{name}/common",
|
||||
"SNAP_REAL_HOME": home, "SNAP_UID": str(os.getuid()), "SNAP_EUID": str(os.geteuid()),
|
||||
"SNAP_COOKIE": "", "SNAP_CONTEXT": "", "SNAP_REEXEC": "0",
|
||||
})
|
||||
for d in (env["SNAP_USER_DATA"], env["SNAP_USER_COMMON"], env["SNAP_DATA"], env["SNAP_COMMON"]):
|
||||
os.makedirs(d, exist_ok=True)
|
||||
current = f"{home}/snap/{name}/current"
|
||||
if os.path.realpath(current) != env["SNAP_USER_DATA"]:
|
||||
try:
|
||||
os.unlink(current)
|
||||
except OSError:
|
||||
pass
|
||||
os.symlink(revision, current)
|
||||
confinement = meta.get("confinement", "strict")
|
||||
if confinement != "classic":
|
||||
env["HOME"] = env["SNAP_USER_DATA"]
|
||||
env["PATH"] = ":".join([f"{snap}/usr/sbin", f"{snap}/usr/bin", f"{snap}/sbin", f"{snap}/bin",
|
||||
"/usr/local/sbin", "/usr/local/bin", "/usr/sbin", "/usr/bin", "/sbin", "/bin", "/usr/games"])
|
||||
env["LD_LIBRARY_PATH"] = env["SNAP_LIBRARY_PATH"]
|
||||
for scope in (meta.get("environment") or {}, spec.get("environment") or {}):
|
||||
for k, v in scope.items():
|
||||
env[k] = expand(v, env)
|
||||
command = shlex.split(expand(spec.get("command", ""), env))
|
||||
if command and not command[0].startswith("/"):
|
||||
command[0] = f"{snap}/{command[0]}"
|
||||
chain = [c if c.startswith("/") else f"{snap}/{c}" for c in (meta.get("command-chain") or []) + (spec.get("command-chain") or [])]
|
||||
program = chain + command + args
|
||||
if confinement == "classic":
|
||||
os.execvpe(program[0], program, env)
|
||||
base = meta.get("base") or "core"
|
||||
root = f"{SNAP_DIR}/{base}/current"
|
||||
if not os.path.isdir(root):
|
||||
print(f"error: the base snap \"{base}\" is not installed; run: snap install {base}", file=sys.stderr)
|
||||
return 1
|
||||
bwrap = ["/usr/local/bin/droiddeck-bwrap", "--bind", root, "/", "--dev-bind", "/dev", "/dev", "--proc", "/proc",
|
||||
"--bind", "/sys", "/sys"]
|
||||
for d in HOST_DIRS:
|
||||
if os.path.isdir(d):
|
||||
bwrap += ["--bind", d, d]
|
||||
bwrap += ["--bind", "/", "/var/lib/snapd/hostfs"]
|
||||
bwrap += ["--bind", "/dev/null", "/etc/ld.so.preload"]
|
||||
binds = content_binds(name, meta, env)
|
||||
for _, source, target in binds:
|
||||
if os.path.isdir(source):
|
||||
bwrap += ["--bind", source, target]
|
||||
content = {k for k, v in (meta.get("plugs") or {}).items() if isinstance(v, dict) and v.get("interface") == "content"}
|
||||
plugs = (set(meta.get("plugs") or {}) | set(spec.get("plugs") or [])) - content | {plug for plug, _, _ in binds}
|
||||
env["DROIDDECK_SNAP_PLUGS"] = " ".join(sorted(plugs))
|
||||
bwrap += ["--bind", "/usr/local/bin/droiddeck-snapctl", "/usr/lib/snapd/snapctl"]
|
||||
bwrap += ["--chdir", os.getcwd() if os.path.isdir(os.getcwd()) else env["HOME"], "--clearenv"]
|
||||
for k, v in env.items():
|
||||
bwrap += ["--setenv", k, v]
|
||||
os.execv(bwrap[0], bwrap + ["--"] + program)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv))
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
#!/bin/sh
|
||||
case $1 in
|
||||
is-connected)
|
||||
shift
|
||||
while [ $# -gt 1 ]; do shift; done
|
||||
case " $DROIDDECK_SNAP_PLUGS " in
|
||||
*" ${1:-} "*) exit 0 ;;
|
||||
esac
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
exit 0
|
||||
+542
@@ -0,0 +1,542 @@
|
||||
#!/usr/bin/python3
|
||||
import datetime
|
||||
import hashlib
|
||||
import http.server
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import socketserver
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
STORE = "https://api.snapcraft.io/v2"
|
||||
ARCH = "arm64"
|
||||
SNAP_DIR = "/snap"
|
||||
BIN_DIR = "/snap/bin"
|
||||
LIB = "/var/lib/snapd"
|
||||
STATE = LIB + "/droiddeck-state.json"
|
||||
DESKTOP_DIR = LIB + "/desktop/applications"
|
||||
SOCKETS = ("/run/snapd.socket", "/run/snapd-snap.socket")
|
||||
FIND_FIELDS = ("title,summary,description,version,revision,confinement,base,publisher,license,contact,website,"
|
||||
"media,categories,store-url,download,type,channel,common-ids,links")
|
||||
INFO_FIELDS = ("title,summary,description,version,revision,confinement,base,publisher,license,contact,website,"
|
||||
"media,categories,snap-id,store-url,download,type,channel-map,common-ids,links,created-at")
|
||||
HEADERS = {"Snap-Device-Series": "16", "Snap-Device-Architecture": ARCH, "User-Agent": "snapd/2.70 droiddeck"}
|
||||
|
||||
lock = threading.RLock()
|
||||
install_lock = threading.Lock()
|
||||
changes = {}
|
||||
change_seq = [0]
|
||||
|
||||
|
||||
def now():
|
||||
return datetime.datetime.now(datetime.timezone.utc).isoformat()
|
||||
|
||||
|
||||
def load_state():
|
||||
try:
|
||||
with open(STATE) as f:
|
||||
return json.load(f)
|
||||
except (OSError, ValueError):
|
||||
return {"snaps": {}}
|
||||
|
||||
|
||||
def save_state(state):
|
||||
tmp = STATE + ".tmp"
|
||||
with open(tmp, "w") as f:
|
||||
json.dump(state, f, indent=1)
|
||||
os.replace(tmp, STATE)
|
||||
|
||||
|
||||
def store_get(path, params=None):
|
||||
url = STORE + path + ("?" + urllib.parse.urlencode(params) if params else "")
|
||||
req = urllib.request.Request(url, headers=HEADERS)
|
||||
with urllib.request.urlopen(req, timeout=60) as r:
|
||||
return json.load(r)
|
||||
|
||||
|
||||
def publisher(p):
|
||||
p = p or {}
|
||||
return {"id": p.get("id", ""), "username": p.get("username", ""), "display-name": p.get("display-name", ""),
|
||||
"validation": p.get("validation", "unproven")}
|
||||
|
||||
|
||||
def media_of(snap):
|
||||
out = []
|
||||
for m in snap.get("media") or []:
|
||||
if m.get("type") in ("icon", "screenshot", "banner") and m.get("url"):
|
||||
item = {"type": m["type"], "url": m["url"]}
|
||||
if m.get("width"):
|
||||
item["width"] = m["width"]
|
||||
item["height"] = m.get("height", 0)
|
||||
out.append(item)
|
||||
return out
|
||||
|
||||
|
||||
def icon_of(media):
|
||||
return next((m["url"] for m in media if m["type"] == "icon"), "")
|
||||
|
||||
|
||||
def from_store(name, snap, revision=None, channel=None):
|
||||
media = media_of(snap)
|
||||
rev = revision or snap.get("revision") or {}
|
||||
out = {
|
||||
"id": snap.get("snap-id", ""), "name": name, "title": snap.get("title") or name,
|
||||
"summary": snap.get("summary", ""), "description": snap.get("description", ""),
|
||||
"type": rev.get("type") or snap.get("type") or "app", "version": rev.get("version", ""),
|
||||
"revision": str(rev.get("revision", "")), "channel": channel or "stable",
|
||||
"confinement": rev.get("confinement") or "strict", "base": rev.get("base") or "",
|
||||
"publisher": publisher(snap.get("publisher")), "developer": (snap.get("publisher") or {}).get("username", ""),
|
||||
"license": snap.get("license", ""), "contact": snap.get("contact", ""), "website": snap.get("website", ""),
|
||||
"media": media, "icon": icon_of(media), "store-url": snap.get("store-url", ""),
|
||||
"download-size": (rev.get("download") or {}).get("size", 0), "status": "available",
|
||||
"categories": [{"name": c.get("name", ""), "featured": bool(c.get("featured"))} for c in snap.get("categories") or []],
|
||||
"common-ids": rev.get("common-ids") or snap.get("common-ids") or [],
|
||||
"private": False, "devmode": False, "jailmode": False, "trymode": False, "apps": [],
|
||||
}
|
||||
return out
|
||||
|
||||
|
||||
def installed_snap(name, entry):
|
||||
snap = dict(entry["info"])
|
||||
snap["status"] = "active"
|
||||
snap["install-date"] = entry.get("installed", now())
|
||||
snap["installed-size"] = entry.get("size", 0)
|
||||
snap["revision"] = str(entry["revision"])
|
||||
snap["version"] = entry.get("version", snap.get("version", ""))
|
||||
snap["tracking-channel"] = entry.get("channel", "latest/stable")
|
||||
snap["channel"] = entry.get("channel", "latest/stable")
|
||||
snap["mounted-from"] = f"{LIB}/snaps/{name}_{entry['revision']}.snap"
|
||||
snap["apps"] = [{"name": a, "snap": name, "desktop-file": f"{DESKTOP_DIR}/{name}_{a}.desktop"} for a in entry.get("apps", [])]
|
||||
return snap
|
||||
|
||||
|
||||
def find(query, section=None, name_exact=False):
|
||||
if name_exact:
|
||||
try:
|
||||
info = store_get(f"/snaps/info/{query}", {"architecture": ARCH, "fields": INFO_FIELDS})
|
||||
except Exception:
|
||||
return []
|
||||
rev = next((c for c in info.get("channel-map", []) if c["channel"]["architecture"] == ARCH
|
||||
and c["channel"]["risk"] == "stable"), None)
|
||||
if not rev:
|
||||
return []
|
||||
return [from_store(info["name"], dict(info["snap"], **{"snap-id": info.get("snap-id", "")}), rev, "stable")]
|
||||
params = {"architecture": ARCH, "fields": FIND_FIELDS}
|
||||
if query:
|
||||
params["q"] = query
|
||||
if section:
|
||||
params["category"] = section
|
||||
if not query and not section:
|
||||
params["featured"] = "true"
|
||||
result = store_get("/snaps/find", params)
|
||||
out = []
|
||||
state = load_state()
|
||||
for r in result.get("results", []):
|
||||
snap = from_store(r["name"], dict(r.get("snap", {}), **{"snap-id": r.get("snap-id", "")}), r.get("revision"))
|
||||
if r["name"] in state["snaps"]:
|
||||
snap["status"] = "active"
|
||||
snap["installed-size"] = state["snaps"][r["name"]].get("size", 0)
|
||||
out.append(snap)
|
||||
return out
|
||||
|
||||
|
||||
def new_change(kind, summary, snaps):
|
||||
with lock:
|
||||
change_seq[0] += 1
|
||||
cid = str(change_seq[0])
|
||||
changes[cid] = {"id": cid, "kind": kind, "summary": summary, "status": "Doing", "ready": False,
|
||||
"spawn-time": now(), "tasks": [{"id": cid + "-1", "kind": kind, "summary": summary, "status": "Doing",
|
||||
"progress": {"label": "", "done": 0, "total": 1},
|
||||
"spawn-time": now()}],
|
||||
"data": {"snap-names": snaps}}
|
||||
return cid
|
||||
|
||||
|
||||
def progress(cid, label, done, total):
|
||||
with lock:
|
||||
task = changes[cid]["tasks"][0]
|
||||
task["progress"] = {"label": label, "done": done, "total": max(total, 1)}
|
||||
task["summary"] = changes[cid]["summary"]
|
||||
|
||||
|
||||
def finish(cid, err=None):
|
||||
with lock:
|
||||
c = changes[cid]
|
||||
c["status"] = "Error" if err else "Done"
|
||||
c["ready"] = True
|
||||
c["ready-time"] = now()
|
||||
c["tasks"][0]["status"] = c["status"]
|
||||
if err:
|
||||
c["err"] = err
|
||||
|
||||
|
||||
def root_run(argv):
|
||||
if os.getuid() == 0:
|
||||
return subprocess.run(argv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
|
||||
return subprocess.run(["/usr/local/bin/droiddeck-root"] + argv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
|
||||
text=True)
|
||||
|
||||
|
||||
def snap_yaml(path):
|
||||
try:
|
||||
import yaml
|
||||
with open(path) as f:
|
||||
return yaml.safe_load(f) or {}
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def download(cid, name, url, sha3, size, target):
|
||||
tmp = target + ".partial"
|
||||
h = hashlib.sha3_384()
|
||||
req = urllib.request.Request(url, headers=HEADERS)
|
||||
with urllib.request.urlopen(req, timeout=120) as r, open(tmp, "wb") as out:
|
||||
done = 0
|
||||
while True:
|
||||
chunk = r.read(1 << 20)
|
||||
if not chunk:
|
||||
break
|
||||
out.write(chunk)
|
||||
h.update(chunk)
|
||||
done += len(chunk)
|
||||
progress(cid, f"Download snap \"{name}\"", done, size)
|
||||
if sha3 and h.hexdigest() != sha3:
|
||||
os.unlink(tmp)
|
||||
raise RuntimeError(f"{name}: downloaded snap does not match the store's sha3-384")
|
||||
os.replace(tmp, target)
|
||||
|
||||
|
||||
def write_desktop(name, rev, meta):
|
||||
os.makedirs(DESKTOP_DIR, exist_ok=True)
|
||||
gui = f"{SNAP_DIR}/{name}/{rev}/meta/gui"
|
||||
apps = (meta.get("apps") or {})
|
||||
for app, spec in apps.items():
|
||||
source = os.path.join(gui, f"{app}.desktop")
|
||||
if (spec or {}).get("daemon") or not os.path.isfile(source):
|
||||
continue
|
||||
command = name if app == name else f"{name}.{app}"
|
||||
out = []
|
||||
with open(source, encoding="utf-8", errors="replace") as f:
|
||||
for line in f:
|
||||
if line.startswith("Exec="):
|
||||
args = line[5:].strip().split(" ", 1)
|
||||
rest = (" " + args[1]) if len(args) > 1 else ""
|
||||
line = f"Exec={BIN_DIR}/{command}{rest}\n"
|
||||
elif line.startswith("Icon="):
|
||||
line = "Icon=" + line[5:].replace("${SNAP}", f"{SNAP_DIR}/{name}/current")
|
||||
out.append(line)
|
||||
out.append(f"X-SnapInstanceName={name}\n")
|
||||
target = f"{DESKTOP_DIR}/{name}_{app}.desktop"
|
||||
with open(target + ".tmp", "w", encoding="utf-8") as f:
|
||||
f.writelines(out)
|
||||
os.replace(target + ".tmp", target)
|
||||
subprocess.run(["update-desktop-database", DESKTOP_DIR], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
|
||||
|
||||
def link_bins(name, meta):
|
||||
os.makedirs(BIN_DIR, exist_ok=True)
|
||||
apps = []
|
||||
for app, spec in (meta.get("apps") or {}).items():
|
||||
if (spec or {}).get("daemon"):
|
||||
continue
|
||||
command = name if app == name else f"{name}.{app}"
|
||||
path = os.path.join(BIN_DIR, command)
|
||||
with open(path + ".tmp", "w") as f:
|
||||
f.write(f"#!/bin/sh\nexec /usr/local/bin/droiddeck-snap-run {name} {app} \"$@\"\n")
|
||||
os.chmod(path + ".tmp", 0o755)
|
||||
os.replace(path + ".tmp", path)
|
||||
apps.append(app)
|
||||
return apps
|
||||
|
||||
|
||||
def remove_tree(top):
|
||||
if os.path.isdir(top) and not os.path.islink(top):
|
||||
os.chmod(top, 0o700)
|
||||
for root, dirs, _ in os.walk(top):
|
||||
for d in dirs:
|
||||
path = os.path.join(root, d)
|
||||
if not os.path.islink(path):
|
||||
os.chmod(path, 0o700)
|
||||
shutil.rmtree(top, ignore_errors=True)
|
||||
|
||||
|
||||
def install_one(cid, name, channel, state, parents=()):
|
||||
if name in state["snaps"] or name in parents:
|
||||
return
|
||||
info = store_get(f"/snaps/info/{name}", {"architecture": ARCH, "fields": INFO_FIELDS})
|
||||
risk = channel.split("/")[-1] if channel else "stable"
|
||||
track = channel.split("/")[0] if channel and "/" in channel else "latest"
|
||||
rev = next((c for c in info.get("channel-map", []) if c["channel"]["architecture"] == ARCH
|
||||
and c["channel"]["risk"] == risk and c["channel"]["track"] == track), None)
|
||||
if not rev:
|
||||
raise RuntimeError(f"snap \"{name}\" has no {track}/{risk} release for {ARCH}")
|
||||
number = rev["revision"]
|
||||
os.makedirs(f"{LIB}/snaps", exist_ok=True)
|
||||
blob = f"{LIB}/snaps/{name}_{number}.snap"
|
||||
d = rev.get("download") or {}
|
||||
with lock:
|
||||
changes[cid]["summary"] = f"Install \"{name}\" snap"
|
||||
download(cid, name, d["url"], d.get("sha3-384"), d.get("size", 0), blob)
|
||||
progress(cid, f"Unpack snap \"{name}\"", 0, 1)
|
||||
target = f"{SNAP_DIR}/{name}/{number}"
|
||||
remove_tree(target)
|
||||
os.makedirs(os.path.dirname(target), exist_ok=True)
|
||||
r = root_run(["unsquashfs", "-q", "-n", "-no-xattrs", "-f", "-excludes", "-d", target, blob, "dev"])
|
||||
if r.returncode != 0:
|
||||
raise RuntimeError(f"cannot unpack {name}: {r.stdout.strip()[-400:]}")
|
||||
os.makedirs(f"{target}/dev", exist_ok=True)
|
||||
current = f"{SNAP_DIR}/{name}/current"
|
||||
if os.path.islink(current):
|
||||
os.unlink(current)
|
||||
os.symlink(str(number), current)
|
||||
for sub in (f"/var/snap/{name}/{number}", f"/var/snap/{name}/common"):
|
||||
os.makedirs(sub, exist_ok=True)
|
||||
cur = f"/var/snap/{name}/current"
|
||||
if os.path.islink(cur):
|
||||
os.unlink(cur)
|
||||
os.symlink(str(number), cur)
|
||||
meta = snap_yaml(f"{target}/meta/snap.yaml")
|
||||
entry = {"revision": number, "version": rev.get("version", ""), "channel": f"{track}/{risk}",
|
||||
"installed": now(), "size": d.get("size", 0), "info": from_store(name, dict(info["snap"], **{"snap-id": info.get("snap-id", "")}), rev, f"{track}/{risk}"),
|
||||
"base": meta.get("base") or ("core" if (meta.get("type") or "app") == "app" else ""), "apps": []}
|
||||
base = meta.get("base")
|
||||
if (meta.get("type") or "app") == "app":
|
||||
install_one(cid, base or "core", "latest/stable", state, parents + (name,))
|
||||
for plug in (meta.get("plugs") or {}).values():
|
||||
if isinstance(plug, dict) and plug.get("interface") == "content" and plug.get("default-provider"):
|
||||
provider = plug["default-provider"].split(":")[0]
|
||||
install_one(cid, provider, "latest/stable", state, parents + (name,))
|
||||
entry["apps"] = link_bins(name, meta)
|
||||
write_desktop(name, number, meta)
|
||||
state["snaps"][name] = entry
|
||||
save_state(state)
|
||||
|
||||
|
||||
def remove_one(name, state):
|
||||
entry = state["snaps"].pop(name, None)
|
||||
if not entry:
|
||||
raise RuntimeError(f"snap \"{name}\" is not installed")
|
||||
for app in entry.get("apps", []):
|
||||
command = name if app == name else f"{name}.{app}"
|
||||
try:
|
||||
os.unlink(os.path.join(BIN_DIR, command))
|
||||
except OSError:
|
||||
pass
|
||||
if os.path.isdir(DESKTOP_DIR):
|
||||
for f in os.listdir(DESKTOP_DIR):
|
||||
if f.startswith(name + "_") and f.endswith(".desktop"):
|
||||
os.unlink(os.path.join(DESKTOP_DIR, f))
|
||||
subprocess.run(["update-desktop-database", DESKTOP_DIR], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
remove_tree(f"{SNAP_DIR}/{name}")
|
||||
for f in os.listdir(f"{LIB}/snaps"):
|
||||
if f.startswith(name + "_"):
|
||||
os.unlink(os.path.join(f"{LIB}/snaps", f))
|
||||
save_state(state)
|
||||
|
||||
|
||||
def run_change(cid, action, names, channel):
|
||||
with install_lock:
|
||||
apply_change(cid, action, names, channel)
|
||||
|
||||
|
||||
def apply_change(cid, action, names, channel):
|
||||
try:
|
||||
state = load_state()
|
||||
for name in names:
|
||||
if action == "install":
|
||||
install_one(cid, name, channel or "latest/stable", state)
|
||||
elif action == "remove":
|
||||
remove_one(name, state)
|
||||
elif action == "refresh":
|
||||
old = state["snaps"].get(name)
|
||||
if old:
|
||||
remove_one(name, state)
|
||||
install_one(cid, name, old.get("channel", "latest/stable"), state)
|
||||
else:
|
||||
raise RuntimeError(f"unsupported action {action}")
|
||||
finish(cid)
|
||||
except Exception as e:
|
||||
finish(cid, str(e))
|
||||
|
||||
|
||||
SECTIONS = ["featured", "art-and-design", "books-and-reference", "development", "devices-and-iot", "education",
|
||||
"entertainment", "finance", "games", "health-and-fitness", "music-and-audio", "news-and-weather",
|
||||
"personalisation", "photo-and-video", "productivity", "science", "security", "server-and-cloud",
|
||||
"social", "utilities"]
|
||||
|
||||
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
protocol_version = "HTTP/1.1"
|
||||
|
||||
def log_message(self, fmt, *args):
|
||||
pass
|
||||
|
||||
def address_string(self):
|
||||
return "snapd"
|
||||
|
||||
def reply(self, body, code=200, kind="sync"):
|
||||
payload = {"type": kind, "status-code": code, "status": http.client.responses.get(code, "")}
|
||||
payload.update(body)
|
||||
data = json.dumps(payload).encode()
|
||||
self.send_response(code)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
|
||||
def ok(self, result):
|
||||
self.reply({"result": result})
|
||||
|
||||
def error(self, code, message, kind=""):
|
||||
self.reply({"result": {"message": message, "kind": kind}}, code, "error")
|
||||
|
||||
def body(self):
|
||||
n = int(self.headers.get("Content-Length") or 0)
|
||||
raw = self.rfile.read(n) if n else b"{}"
|
||||
try:
|
||||
return json.loads(raw or b"{}")
|
||||
except ValueError:
|
||||
return {}
|
||||
|
||||
def do_GET(self):
|
||||
url = urllib.parse.urlsplit(self.path)
|
||||
q = urllib.parse.parse_qs(url.query)
|
||||
path = url.path
|
||||
try:
|
||||
if path == "/v2/system-info":
|
||||
return self.ok({"series": "16", "version": "2.70+droiddeck", "build-id": "droiddeck", "os-release": {"id": "ubuntu", "version-id": "26.04"},
|
||||
"on-classic": True, "managed": False, "kernel-version": os.uname().release,
|
||||
"locations": {"snap-mount-dir": SNAP_DIR, "snap-bin-dir": BIN_DIR},
|
||||
"refresh": {"timer": "00:00~24:00/4"}, "confinement": "partial",
|
||||
"sandbox-features": {}, "architecture": ARCH})
|
||||
if path == "/v2/snaps":
|
||||
state = load_state()
|
||||
wanted = (q.get("snaps", [""])[0] or "").split(",")
|
||||
snaps = [installed_snap(n, e) for n, e in state["snaps"].items() if not wanted[0] or n in wanted]
|
||||
return self.ok(snaps)
|
||||
m = re.fullmatch(r"/v2/snaps/([^/]+)", path)
|
||||
if m:
|
||||
state = load_state()
|
||||
if m.group(1) in state["snaps"]:
|
||||
return self.ok(installed_snap(m.group(1), state["snaps"][m.group(1)]))
|
||||
return self.error(404, f"snap not installed", "snap-not-found")
|
||||
if path == "/v2/find":
|
||||
name = q.get("name", [None])[0]
|
||||
query = name or q.get("q", [""])[0]
|
||||
section = q.get("section", [None])[0] or q.get("category", [None])[0]
|
||||
if section == "featured":
|
||||
section = None
|
||||
select = q.get("select", [""])[0]
|
||||
if select == "refresh":
|
||||
return self.ok([])
|
||||
if select == "private":
|
||||
return self.ok([])
|
||||
return self.ok(find(query, section, bool(name)))
|
||||
if path in ("/v2/sections",):
|
||||
return self.ok(SECTIONS)
|
||||
if path == "/v2/categories":
|
||||
return self.ok([{"name": s} for s in SECTIONS if s != "featured"])
|
||||
m = re.fullmatch(r"/v2/changes/([^/]+)", path)
|
||||
if m:
|
||||
with lock:
|
||||
c = changes.get(m.group(1))
|
||||
c = json.loads(json.dumps(c)) if c else None
|
||||
return self.ok(c) if c else self.error(404, "cannot find change", "")
|
||||
if path == "/v2/changes":
|
||||
with lock:
|
||||
return self.ok([json.loads(json.dumps(c)) for c in changes.values()])
|
||||
m = re.fullmatch(r"/v2/icons/([^/]+)/icon", path)
|
||||
if m:
|
||||
return self.icon(m.group(1))
|
||||
if path == "/v2/apps":
|
||||
state = load_state()
|
||||
apps = [{"snap": n, "name": a, "desktop-file": f"{DESKTOP_DIR}/{n}_{a}.desktop"}
|
||||
for n, e in state["snaps"].items() for a in e.get("apps", [])]
|
||||
return self.ok(apps)
|
||||
if path in ("/v2/connections", "/v2/interfaces"):
|
||||
return self.ok({"established": [], "plugs": [], "slots": []})
|
||||
if path in ("/v2/aliases", "/v2/users", "/v2/notices", "/v2/assertions/model"):
|
||||
return self.ok({} if path == "/v2/aliases" else [])
|
||||
return self.error(404, f"not found: {path}")
|
||||
except Exception as e:
|
||||
return self.error(500, str(e))
|
||||
|
||||
def icon(self, name):
|
||||
state = load_state()
|
||||
entry = state["snaps"].get(name)
|
||||
if not entry:
|
||||
return self.error(404, "not installed", "snap-not-found")
|
||||
for candidate in ("meta/gui/icon.png", "meta/gui/icon.svg"):
|
||||
path = f"{SNAP_DIR}/{name}/current/{candidate}"
|
||||
if os.path.isfile(path):
|
||||
with open(path, "rb") as f:
|
||||
data = f.read()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "image/svg+xml" if path.endswith("svg") else "image/png")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
return
|
||||
return self.error(404, "no icon", "")
|
||||
|
||||
def do_POST(self):
|
||||
path = urllib.parse.urlsplit(self.path).path
|
||||
body = self.body()
|
||||
m = re.fullmatch(r"/v2/snaps/([^/]+)", path)
|
||||
if m or path == "/v2/snaps":
|
||||
names = [m.group(1)] if m else body.get("snaps") or []
|
||||
action = body.get("action", "")
|
||||
channel = body.get("channel") or ""
|
||||
if channel and "/" not in channel:
|
||||
channel = "latest/" + channel
|
||||
if action not in ("install", "remove", "refresh"):
|
||||
return self.error(400, f"unsupported action \"{action}\"")
|
||||
cid = new_change(f"{action}-snap", f"{action.capitalize()} {', '.join(names)}", names)
|
||||
threading.Thread(target=run_change, args=(cid, action, names, channel), daemon=True).start()
|
||||
return self.reply({"change": cid}, 202, "async")
|
||||
m = re.fullmatch(r"/v2/changes/([^/]+)", path)
|
||||
if m:
|
||||
return self.error(400, "changes cannot be aborted")
|
||||
if path in ("/v2/login", "/v2/logout", "/v2/snapctl"):
|
||||
return self.error(400, "not supported by DroidDeck's snap service")
|
||||
return self.error(404, f"not found: {path}")
|
||||
|
||||
def do_PUT(self):
|
||||
return self.do_POST()
|
||||
|
||||
|
||||
class Server(socketserver.ThreadingMixIn, socketserver.UnixStreamServer):
|
||||
daemon_threads = True
|
||||
|
||||
def get_request(self):
|
||||
conn, _ = self.socket.accept()
|
||||
return conn, ("snapd", 0)
|
||||
|
||||
|
||||
def serve(path):
|
||||
try:
|
||||
os.unlink(path)
|
||||
except OSError:
|
||||
pass
|
||||
server = Server(path, Handler)
|
||||
os.chmod(path, 0o666)
|
||||
server.serve_forever()
|
||||
|
||||
|
||||
def main():
|
||||
for d in (LIB, SNAP_DIR, BIN_DIR, DESKTOP_DIR, LIB + "/snaps"):
|
||||
os.makedirs(d, exist_ok=True)
|
||||
threads = [threading.Thread(target=serve, args=(p,), daemon=True) for p in SOCKETS]
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -23,15 +23,20 @@ BRIGHTNESS_JS = r"""
|
||||
if (window.__droiddeckBrightness) return "present";
|
||||
const display = SteamClient.System?.Display;
|
||||
if (!display?.RegisterForBrightnessChanges || !display?.SetBrightness) return "unavailable";
|
||||
const self = { expected: null, updating: true, revision: 0 };
|
||||
const self = { expected: null, updating: true, revision: 0, localAt: -Infinity };
|
||||
// A held stick steps Steam faster than Android's readback returns; those stale readbacks would snap the slider back.
|
||||
const HOLD_MS = 750;
|
||||
// Returns "held" while a readback is being ignored, so the caller retries it after the hold.
|
||||
self.set = value => {
|
||||
if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 1) return;
|
||||
if (!self.updating && self.expected !== null && Math.abs(value - self.expected) < 0.0001) return;
|
||||
if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 1) return true;
|
||||
if (performance.now() - self.localAt < HOLD_MS) return "held";
|
||||
if (!self.updating && self.expected !== null && Math.abs(value - self.expected) < 0.0001) return true;
|
||||
self.expected = value;
|
||||
self.updating = true;
|
||||
const revision = ++self.revision;
|
||||
setTimeout(() => { if (self.revision === revision) self.updating = false; }, 500);
|
||||
display.SetBrightness(value);
|
||||
return true;
|
||||
};
|
||||
self.subscription = display.RegisterForBrightnessChanges(state => {
|
||||
const value = state?.flBrightness;
|
||||
@@ -39,6 +44,7 @@ BRIGHTNESS_JS = r"""
|
||||
if (Math.abs(value - self.expected) < 0.0001) { self.updating = false; return; }
|
||||
if (self.updating) { self.updating = false; return; }
|
||||
self.expected = value;
|
||||
self.localAt = performance.now();
|
||||
if (typeof window.__BINDING__ === "function") window.__BINDING__(String(value));
|
||||
});
|
||||
window.__droiddeckBrightness = self;
|
||||
@@ -764,9 +770,10 @@ class Helper:
|
||||
if not self.controls_installed:
|
||||
return
|
||||
if state != self.controls_state:
|
||||
if self.page.evaluate("!!window.__droiddeckBrightness && (window.__droiddeckBrightness.set(%s), true)" % json.dumps(value)) is True:
|
||||
applied = self.page.evaluate("window.__droiddeckBrightness ? window.__droiddeckBrightness.set(%s) : false" % json.dumps(value))
|
||||
if applied is True:
|
||||
self.controls_state = state
|
||||
else:
|
||||
elif applied != "held":
|
||||
self.controls_installed = False
|
||||
self.controls_state = None
|
||||
except (OSError, ValueError, TypeError):
|
||||
|
||||
@@ -14,6 +14,7 @@ import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
STATE = ".droiddeck-games.json"
|
||||
TRIED = ".droiddeck-import-tried.json"
|
||||
WINNATIVE = ".winnative-steam/steamapps"
|
||||
LIBRARY = "/mnt/droiddeck-sd"
|
||||
LEGACY_LIBRARY = "/mnt/bannerlator-sd"
|
||||
@@ -179,10 +180,44 @@ def request_restart(steam_root):
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=30)
|
||||
|
||||
|
||||
def ask_restart(names, timeout=600, clock=None, sleep=None):
|
||||
"""The app asks whether to restart the client now; anything but "now" leaves the import to the next start."""
|
||||
clock, sleep = clock or time.monotonic, sleep or time.sleep
|
||||
folder = Path(os.environ.get("HOME", "/root"), ".cache/droiddeck")
|
||||
ask, answer = folder / "steam-import.json", folder / "steam-import.answer"
|
||||
token = str(time.time_ns())
|
||||
answer.unlink(missing_ok=True)
|
||||
save_json(ask, {"token": token, "games": names})
|
||||
try:
|
||||
deadline = clock() + timeout
|
||||
while clock() < deadline:
|
||||
reply = read_json(answer, None)
|
||||
if isinstance(reply, dict) and reply.get("token") == token:
|
||||
return reply.get("choice") == "now"
|
||||
sleep(1)
|
||||
return False
|
||||
finally:
|
||||
ask.unlink(missing_ok=True)
|
||||
answer.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def unimported(steam_root, snapshot, candidates):
|
||||
routes = read_json(Path(steam_root) / "userdata" / snapshot["account"] / "config/.droiddeck-routes.json", {})
|
||||
config = Path(steam_root) / "userdata" / snapshot["account"] / "config"
|
||||
routes = read_json(config / ".droiddeck-routes.json", {})
|
||||
routed = set(routes.values()) if isinstance(routes, dict) else set()
|
||||
return sorted({appid for appid in candidates.values() if snapshot["owned"].get(str(appid)) is True} - routed)
|
||||
tried = read_json(config / TRIED, [])
|
||||
tried = {appid for appid in tried if isinstance(appid, int)} if isinstance(tried, list) else set()
|
||||
owned = {appid for appid in candidates.values() if snapshot["owned"].get(str(appid)) is True}
|
||||
if tried - routed != tried:
|
||||
save_json(config / TRIED, sorted(tried - routed))
|
||||
return sorted(owned - routed - tried)
|
||||
|
||||
|
||||
def remember_tried(steam_root, account, appids):
|
||||
config = Path(steam_root) / "userdata" / account / "config"
|
||||
tried = read_json(config / TRIED, [])
|
||||
tried = {appid for appid in tried if isinstance(appid, int)} if isinstance(tried, list) else set()
|
||||
save_json(config / TRIED, sorted(tried | set(appids)))
|
||||
|
||||
|
||||
def watch(steam_root, listing):
|
||||
@@ -193,7 +228,7 @@ def watch(steam_root, listing):
|
||||
next_lookup = 0
|
||||
last_status = None
|
||||
probed, next_probe, failures = None, 0, 0
|
||||
pending, requested = [], []
|
||||
pending, requested, account = [], [], None
|
||||
while True:
|
||||
now = time.monotonic()
|
||||
for game in games:
|
||||
@@ -233,6 +268,7 @@ def watch(steam_root, listing):
|
||||
snapshot["sources"] = sources
|
||||
save_json(Path(steam_root) / "userdata" / snapshot["account"] / "config" / STATE, snapshot)
|
||||
pending = unimported(steam_root, snapshot, candidates)
|
||||
account = snapshot["account"]
|
||||
status = "matched %d/%d games; %d owned" % (len(candidates), len(games), sum(snapshot["owned"].values()))
|
||||
except (OSError, ValueError, KeyError, StopIteration, subprocess.TimeoutExpired) as error:
|
||||
status = "ownership check unavailable: " + str(error)
|
||||
@@ -242,9 +278,14 @@ def watch(steam_root, listing):
|
||||
status = last_status
|
||||
if pending and pending != requested and not game_running() and downloads_idle(steam_root):
|
||||
requested = pending
|
||||
print("droiddeck-steam-games: restarting the client once to import %s" % pending, flush=True)
|
||||
names = sorted({game["name"] for game in games if candidates.get(game["folder"]) in pending})
|
||||
try:
|
||||
request_restart(steam_root)
|
||||
remember_tried(steam_root, account, pending)
|
||||
if ask_restart(names) and not game_running() and downloads_idle(steam_root):
|
||||
print("droiddeck-steam-games: restarting the client once to import %s" % pending, flush=True)
|
||||
request_restart(steam_root)
|
||||
else:
|
||||
print("droiddeck-steam-games: %s will be imported the next time the client starts" % pending, flush=True)
|
||||
except (OSError, subprocess.TimeoutExpired) as error:
|
||||
print("droiddeck-steam-games: restart unavailable: %s" % error, flush=True)
|
||||
if status != last_status:
|
||||
@@ -436,6 +477,7 @@ def route(steam_root, acct, games):
|
||||
if seed_install(steam_root, game, appid):
|
||||
routes[str(game["appid"])] = appid
|
||||
continue
|
||||
print(f"droiddeck-steam-games: {game.get('name', appid)} stays a shortcut this session: it could not be linked as Steam app {appid}")
|
||||
except OSError as error:
|
||||
print(f"droiddeck-steam-games: import unavailable ({error})")
|
||||
elif isinstance(appid, int) and 0 < appid < 0x80000000 and seeded(steamapps, game, appid):
|
||||
|
||||
@@ -39,6 +39,7 @@ if [ "$ui" = desktop ] && [ "${BL_DESKTOP:-}" = 1 ]; then
|
||||
echo "droiddeck-steam-launch: the desktop client did not become ready" >&2
|
||||
exit 69
|
||||
fi
|
||||
[ "$url" = steam://exit ] && exit 0
|
||||
export BL_INSIDE=1 BL_STEAM_UI=desktop
|
||||
exec /usr/local/bin/droiddeck-session steam "${url:-steam://open/library}"
|
||||
fi
|
||||
|
||||
@@ -6,6 +6,7 @@ if [ "${BL_DESKTOP:-}" = 1 ]; then
|
||||
for arg in "$@"; do
|
||||
case $arg in
|
||||
steam://*) url=$arg ;;
|
||||
-shutdown) url=steam://exit ;;
|
||||
-gamepadui|-bigpicture) ui=bigpicture ;;
|
||||
esac
|
||||
done
|
||||
|
||||
@@ -40,6 +40,7 @@ import time
|
||||
import subprocess
|
||||
import tempfile
|
||||
import hashlib
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
LAUNCHER = ".droiddeck-launch.bat"
|
||||
@@ -494,8 +495,27 @@ def gog_registry(folder):
|
||||
return entries, skipped
|
||||
|
||||
|
||||
def apply_gog_registry(folder, compat_data, proton, timeout=90):
|
||||
def apply_gog_registry(folder, compat_data, proton, timeout=90, installation=None):
|
||||
entries, skipped = gog_registry(folder)
|
||||
if installation:
|
||||
product = str(installation["id"])
|
||||
if not product.isdigit():
|
||||
raise ValueError("Invalid GOG product identifier")
|
||||
values = {"PATH": windows_path(str(folder))}
|
||||
identity = Path(folder) / ("goggame-%s.id" % product)
|
||||
if identity.is_file():
|
||||
actual = json.loads(identity.read_text(encoding="utf-8-sig")).get("buildId")
|
||||
if actual and installation.get("build") and str(actual) != str(installation["build"]):
|
||||
raise ValueError("GOG build metadata changed before patch setup")
|
||||
if installation.get("build"):
|
||||
values["BUILDID"] = installation["build"]
|
||||
if installation.get("version"):
|
||||
values["VER"] = installation["version"]
|
||||
for key, value in values.items():
|
||||
entry = gog_entry({"root": "HKLM", "subkey": "Software\\GOG.com\\Games\\" + product,
|
||||
"valueName": key, "valueData": value, "valueType": "string"}, {})
|
||||
if entry:
|
||||
entries.append(entry)
|
||||
note = " skipped=%d" % skipped if skipped else ""
|
||||
if not entries:
|
||||
return "none" + note
|
||||
@@ -512,7 +532,8 @@ def apply_gog_registry(folder, compat_data, proton, timeout=90):
|
||||
with tempfile.TemporaryDirectory(prefix="droiddeck-gog-") as tmp:
|
||||
source = Path(tmp) / "registry.reg"
|
||||
source.write_bytes(b"\xff\xfe" + text.encode("utf-16-le"))
|
||||
run = subprocess.run([proton, "run", "reg.exe", "import", windows_path(str(source)), "/reg:32"],
|
||||
executable = pfx / "drive_c/windows/system32/reg.exe"
|
||||
run = subprocess.run([proton, "run", str(executable) if executable.is_file() else "reg.exe", "import", windows_path(str(source)), "/reg:32"],
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=timeout)
|
||||
if run.returncode or not (pfx / "system.reg").is_file():
|
||||
return "import-failed" + note
|
||||
@@ -525,6 +546,8 @@ def apply_gog_registry(folder, compat_data, proton, timeout=90):
|
||||
|
||||
|
||||
def main(argv):
|
||||
if os.environ.get("DROIDDECK_GOG_MAINTENANCE") == "1":
|
||||
return 0
|
||||
if argv and argv[0] == "--exited":
|
||||
rest, code = argv[1:], 0
|
||||
if rest[:1] == ["--code"] and len(rest) > 1:
|
||||
@@ -543,6 +566,18 @@ def main(argv):
|
||||
return 0
|
||||
folder, sidecar = found
|
||||
store, game = str(sidecar.get("store")), str(sidecar.get("id"))
|
||||
if store == "gog":
|
||||
helper = Path(__file__).resolve().with_name("droiddeck-gog-maintenance")
|
||||
if helper.is_file():
|
||||
child = subprocess.Popen([sys.executable, str(helper), "lease", str(folder), str(os.getppid())],
|
||||
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, stdin=subprocess.DEVNULL,
|
||||
start_new_session=True)
|
||||
ready = child.stdout.readline().decode().strip()
|
||||
child.stdout.close()
|
||||
threading.Thread(target=child.wait, daemon=True).start()
|
||||
if ready != "ready":
|
||||
log("gog: close or recover the maintenance operation before playing")
|
||||
return RAN_FAILED
|
||||
compat_data = os.environ.get("STEAM_COMPAT_DATA_PATH", "").rstrip("/")
|
||||
prefix_id = os.path.basename(compat_data) if compat_data else ""
|
||||
launch_dir = os.environ.get("BL_LAUNCH_DIR", "")
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
#!/usr/bin/python3
|
||||
import os
|
||||
import sys
|
||||
|
||||
REAL = "/usr/bin/systemd-run"
|
||||
VALUED = {"-u", "--unit", "-p", "--property", "--description", "--slice", "-E", "--setenv",
|
||||
"--working-directory", "--uid", "--gid", "--nice", "-H", "--host", "-M", "--machine",
|
||||
"--on-active", "--on-boot", "--on-startup", "--on-unit-active", "--on-unit-inactive",
|
||||
"--on-calendar", "--path-property", "--socket-property", "--timer-property", "--service-type",
|
||||
"--shell", "--slice-inherit"}
|
||||
|
||||
|
||||
def main(argv):
|
||||
args = argv[1:]
|
||||
if "--user" not in args:
|
||||
os.execv(REAL, [REAL] + args)
|
||||
env = dict(os.environ)
|
||||
cwd = None
|
||||
foreground = False
|
||||
i = 0
|
||||
while i < len(args):
|
||||
a = args[i]
|
||||
if a == "--":
|
||||
i += 1
|
||||
break
|
||||
if not a.startswith("-"):
|
||||
break
|
||||
name, _, inline = a.partition("=")
|
||||
value = inline if inline else (args[i + 1] if name in VALUED and i + 1 < len(args) else "")
|
||||
if name in ("-E", "--setenv") and "=" in value:
|
||||
k, _, v = value.partition("=")
|
||||
env[k] = v
|
||||
elif name == "--working-directory":
|
||||
cwd = value
|
||||
elif name in ("--scope", "--wait", "-W", "--pipe", "-P", "-t", "--pty"):
|
||||
foreground = True
|
||||
i += 1 if inline or name not in VALUED else 2
|
||||
command = args[i:]
|
||||
if not command:
|
||||
os.execv(REAL, [REAL] + args)
|
||||
if cwd:
|
||||
os.chdir(cwd)
|
||||
if foreground:
|
||||
os.execvpe(command[0], command, env)
|
||||
if os.fork() == 0:
|
||||
os.setsid()
|
||||
null = os.open(os.devnull, os.O_RDWR)
|
||||
os.dup2(null, 0)
|
||||
try:
|
||||
os.execvpe(command[0], command, env)
|
||||
except OSError:
|
||||
os._exit(127)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv))
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
#!/bin/bash
|
||||
key=$1
|
||||
shift
|
||||
line=$(grep -m1 "^$key=" /etc/droiddeck/strings 2>/dev/null)
|
||||
text=${line#*=}
|
||||
[ -n "$line" ] || text=$key
|
||||
printf "$text\n" "$@"
|
||||
@@ -101,16 +101,18 @@ def registry_values(root):
|
||||
return good
|
||||
|
||||
|
||||
def expand(store, ids):
|
||||
def expand(store, ids, saved=None):
|
||||
"""The picks with everything they bundle, each once, a bundle's parts before it."""
|
||||
out, seen = [], set()
|
||||
saved = saved if isinstance(saved, dict) else {}
|
||||
|
||||
def visit(cid, depth):
|
||||
if cid in seen or depth > 8:
|
||||
return
|
||||
seen.add(cid)
|
||||
found = component(store, cid)
|
||||
for dep in (found[2] if found else []):
|
||||
parts = found[2] if found else [d for d in saved.get(cid, []) if valid_id(d)]
|
||||
for dep in parts:
|
||||
visit(dep, depth + 1)
|
||||
out.append(cid)
|
||||
|
||||
@@ -444,7 +446,7 @@ def list_line(name, current, item, separator, add, at_end=True):
|
||||
return reg_value_line(name, "expand_sz" if expand else "sz", separator.join(items))
|
||||
|
||||
|
||||
def apply_registry(pfx, values, state):
|
||||
def apply_registry(pfx, values, state, held=()):
|
||||
"""Writes the picked components' registry values into the prefix and takes out the ones of
|
||||
components turned off: a value goes back to what it was before, an entry added to a list such
|
||||
as PATH just leaves the list. Returns (values written, notes)."""
|
||||
@@ -478,6 +480,9 @@ def apply_registry(pfx, values, state):
|
||||
for ident, record in old.items():
|
||||
if ident in keep or not isinstance(record, dict) or not isinstance(record.get("key"), str):
|
||||
continue
|
||||
if record.get("cid") in held:
|
||||
keep[ident] = record
|
||||
continue
|
||||
reg = files.get(record.get("hive"))
|
||||
if reg is None:
|
||||
keep[ident] = record
|
||||
@@ -555,14 +560,44 @@ def apply(compat_path, app_id, selection=SELECTION, store=STORE, pending=PENDING
|
||||
copied = 0
|
||||
installed = []
|
||||
values = []
|
||||
for cid in expand(store, ids):
|
||||
held = set()
|
||||
saved_overrides = state.get("overrides") if isinstance(state.get("overrides"), dict) else {}
|
||||
saved_requires = state.get("requires") if isinstance(state.get("requires"), dict) else {}
|
||||
recorded = [c for c in state.get("components", []) if isinstance(c, str) and valid_id(c)]
|
||||
owners = set(state["files"].values())
|
||||
registry_owners = {r.get("cid") for r in (state.get("registry") or {}).values() if isinstance(r, dict)}
|
||||
inferred = set()
|
||||
guessed = set(state.get("guessed") or []) if "requires" in state else set(ids)
|
||||
loose = [c for c in recorded if c not in ids and (c in owners or c in registry_owners)]
|
||||
for cid in ids:
|
||||
if cid in guessed and component(store, cid) is None and cid in recorded:
|
||||
saved_requires = dict(saved_requires, **{cid: loose})
|
||||
inferred.add(cid)
|
||||
kept_overrides, kept_requires = {}, {}
|
||||
for cid in expand(store, ids, saved_requires):
|
||||
found = component(store, cid)
|
||||
if found is None:
|
||||
notes.append("%s is not installed; skipped" % cid)
|
||||
if cid in saved_requires or cid in recorded or cid in owners or cid in registry_owners:
|
||||
held.add(cid)
|
||||
if cid in saved_overrides:
|
||||
names = [n for n in saved_overrides.get(cid, []) if isinstance(n, str)]
|
||||
else:
|
||||
names = sorted({Path(rel).stem.lower() for rel, owner in state["files"].items()
|
||||
if owner == cid and rel.lower().endswith(".dll")})
|
||||
overrides += names
|
||||
kept_overrides[cid] = names
|
||||
if isinstance(saved_requires.get(cid), list) and cid not in inferred:
|
||||
kept_requires[cid] = saved_requires[cid]
|
||||
notes.append("%s is not in the store; kept the files it placed until it is installed again" % cid)
|
||||
else:
|
||||
notes.append("%s is not installed; skipped" % cid)
|
||||
continue
|
||||
installed.append(cid)
|
||||
names, files, _, registry = found
|
||||
names, files, requires, registry = found
|
||||
overrides += names
|
||||
kept_overrides[cid] = list(names)
|
||||
if requires:
|
||||
kept_requires[cid] = list(requires)
|
||||
values += [(cid, value) for value in registry]
|
||||
for rel, src in files:
|
||||
if place(src, pfx / rel, None if rel in state["files"] else compat / BACKUP / rel):
|
||||
@@ -572,6 +607,9 @@ def apply(compat_path, app_id, selection=SELECTION, store=STORE, pending=PENDING
|
||||
for rel, cid in state["files"].items():
|
||||
if rel in keep:
|
||||
continue
|
||||
if cid in held:
|
||||
keep[rel] = cid
|
||||
continue
|
||||
path = existing(pfx / rel)
|
||||
saved = compat / BACKUP / rel
|
||||
if saved.is_file():
|
||||
@@ -587,10 +625,13 @@ def apply(compat_path, app_id, selection=SELECTION, store=STORE, pending=PENDING
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
compat.mkdir(parents=True, exist_ok=True)
|
||||
new_state = {"files": keep, "components": installed, "registry": state.get("registry", {})}
|
||||
new_state = {"files": keep, "components": installed + sorted(held), "overrides": kept_overrides,
|
||||
"requires": kept_requires, "registry": state.get("registry", {})}
|
||||
if inferred:
|
||||
new_state["guessed"] = sorted(inferred)
|
||||
written = 0
|
||||
if values or new_state["registry"]:
|
||||
written, registry_notes = apply_registry(pfx, values, new_state)
|
||||
written, registry_notes = apply_registry(pfx, values, new_state, held)
|
||||
notes += registry_notes
|
||||
save_state(compat, new_state)
|
||||
if copied or removed or restored or written:
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
#define _GNU_SOURCE
|
||||
#include <errno.h>
|
||||
#include <limits.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/statfs.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#define FUSE_MAGIC 0x65735546
|
||||
#define SDCARDFS_MAGIC 0x5dca2df5
|
||||
|
||||
static int is_wineserver(void) {
|
||||
static int cached = -1;
|
||||
char exe[PATH_MAX];
|
||||
const char *base;
|
||||
ssize_t n;
|
||||
|
||||
if (cached >= 0) return cached;
|
||||
n = readlink("/proc/self/exe", exe, sizeof(exe) - 1);
|
||||
if (n <= 0) {
|
||||
cached = 0;
|
||||
return cached;
|
||||
}
|
||||
exe[n] = '\0';
|
||||
base = strrchr(exe, '/');
|
||||
cached = strcmp(base ? base + 1 : exe, "wineserver") == 0;
|
||||
return cached;
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden")))
|
||||
void bl_storage_owner(int fd, struct stat *st) {
|
||||
struct statfs fs;
|
||||
int saved = errno;
|
||||
uid_t uid;
|
||||
|
||||
if (st != NULL && is_wineserver()) {
|
||||
uid = getuid();
|
||||
if (st->st_uid != uid && fstatfs(fd, &fs) == 0 && (fs.f_type == FUSE_MAGIC || fs.f_type == SDCARDFS_MAGIC)) st->st_uid = uid;
|
||||
}
|
||||
errno = saved;
|
||||
}
|
||||
@@ -139,17 +139,31 @@ static int (*next_faccessat(void))(int, const char *, int, int) {
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) int bl_binfmt_runnable(const char *path, int mode);
|
||||
__attribute__((visibility("hidden"))) int bl_writable_access(int dirfd, const char *path, int mode, int flags);
|
||||
|
||||
static int writable_as_owner(int (*real)(int, const char *, int, int), int dirfd, const char *path, int mode, int flags) {
|
||||
if (!bl_writable_access(dirfd, path, mode, flags)) return -1;
|
||||
if ((mode & ~W_OK) == 0 || real(dirfd, path, mode & ~W_OK, flags) == 0) return 0;
|
||||
return -1;
|
||||
}
|
||||
|
||||
static int check_cwd(const char *path, int mode, int flags) {
|
||||
int (*real)(int, const char *, int, int) = next_faccessat();
|
||||
int result;
|
||||
int err;
|
||||
|
||||
if (real == NULL) {
|
||||
errno = ENOSYS;
|
||||
return -1;
|
||||
}
|
||||
result = real(AT_FDCWD, path, mode, flags);
|
||||
return result != 0 && errno == EACCES && bl_binfmt_runnable(path, mode) ? 0 : result;
|
||||
if (result == 0) return 0;
|
||||
err = errno;
|
||||
if (err == EACCES && bl_binfmt_runnable(path, mode)) return 0;
|
||||
errno = err;
|
||||
if (writable_as_owner(real, AT_FDCWD, path, mode, flags) == 0) return 0;
|
||||
errno = err;
|
||||
return result;
|
||||
}
|
||||
|
||||
int access(const char *path, int mode) {
|
||||
@@ -166,6 +180,7 @@ int eaccess(const char *path, int mode) {
|
||||
|
||||
int faccessat(int dirfd, const char *path, int mode, int flags) {
|
||||
int (*real)(int, const char *, int, int);
|
||||
int err;
|
||||
|
||||
if (dirfd == AT_FDCWD) {
|
||||
return cached_access(path, mode, flags, check_cwd);
|
||||
@@ -175,5 +190,9 @@ int faccessat(int dirfd, const char *path, int mode, int flags) {
|
||||
errno = ENOSYS;
|
||||
return -1;
|
||||
}
|
||||
return real(dirfd, path, mode, flags);
|
||||
if (real(dirfd, path, mode, flags) == 0) return 0;
|
||||
err = errno;
|
||||
if (writable_as_owner(real, dirfd, path, mode, flags) == 0) return 0;
|
||||
errno = err;
|
||||
return -1;
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
#include <fcntl.h>
|
||||
#include <limits.h>
|
||||
#include <string.h>
|
||||
#include <strings.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
|
||||
@@ -23,6 +24,34 @@ static int is_steam_client(void) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
static int wine_name(const char *path) {
|
||||
const char *base;
|
||||
size_t n;
|
||||
|
||||
if (path == NULL) return 0;
|
||||
base = strrchr(path, '/');
|
||||
base = base ? base + 1 : path;
|
||||
n = strlen(path);
|
||||
return strncmp(base, "wine", 4) == 0 || strstr(path, "/lib/wine/") != NULL
|
||||
|| (n > 4 && strcasecmp(path + n - 4, ".exe") == 0);
|
||||
}
|
||||
|
||||
static int is_wine(void) {
|
||||
static int cached = -1;
|
||||
char exe[PATH_MAX];
|
||||
ssize_t n;
|
||||
|
||||
if (cached >= 0) return cached;
|
||||
n = readlink("/proc/self/exe", exe, sizeof(exe) - 1);
|
||||
if (n > 0) exe[n] = '\0';
|
||||
cached = (n > 0 && wine_name(exe)) || wine_name(program_invocation_name);
|
||||
return cached;
|
||||
}
|
||||
|
||||
static int acts_as_root(void) {
|
||||
return is_steam_client() || !is_wine();
|
||||
}
|
||||
|
||||
static int grant_owner_write(int dirfd, const char *path) {
|
||||
struct stat st;
|
||||
|
||||
@@ -37,7 +66,7 @@ int bl_writable_retry(int dirfd, const char *path, int flags) {
|
||||
char parent[PATH_MAX];
|
||||
const char *slash;
|
||||
|
||||
if (saved != EACCES || path == NULL || (flags & O_ACCMODE) == O_RDONLY || !is_steam_client()) return 0;
|
||||
if (saved != EACCES || path == NULL || (flags & O_ACCMODE) == O_RDONLY || !acts_as_root()) return 0;
|
||||
if (faccessat(dirfd, path, F_OK, 0) == 0) {
|
||||
granted = grant_owner_write(dirfd, path);
|
||||
} else if (flags & O_CREAT) {
|
||||
@@ -53,3 +82,15 @@ int bl_writable_retry(int dirfd, const char *path, int flags) {
|
||||
errno = saved;
|
||||
return granted;
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden")))
|
||||
int bl_writable_access(int dirfd, const char *path, int mode, int flags) {
|
||||
int saved = errno;
|
||||
struct stat st;
|
||||
int owned;
|
||||
|
||||
if (saved != EACCES || path == NULL || !(mode & W_OK) || !acts_as_root()) return 0;
|
||||
owned = fstatat(dirfd, path, &st, flags & AT_SYMLINK_NOFOLLOW) == 0 && st.st_uid == geteuid();
|
||||
errno = saved;
|
||||
return owned;
|
||||
}
|
||||
@@ -49,6 +49,7 @@ static int openat2_missing;
|
||||
static int (*next_fstatat)(int, const char *, bl_stat *, int);
|
||||
static int (*next_openat)(int, const char *, int, ...);
|
||||
static ssize_t (*next_readlinkat)(int, const char *, char *, size_t);
|
||||
static int (*next_statx)(int, const char *, int, unsigned int, struct statx *);
|
||||
|
||||
static int find_fastpath(struct dl_phdr_info *info, size_t size, void *name) {
|
||||
(void)size;
|
||||
@@ -68,6 +69,7 @@ __attribute__((constructor)) static void find_fastpath_calls(void) {
|
||||
next_fstatat = (int (*)(int, const char *, bl_stat *, int))dlsym(fastpath, BL_FSTATAT_NAME);
|
||||
next_openat = (int (*)(int, const char *, int, ...))dlsym(fastpath, "openat");
|
||||
next_readlinkat = (ssize_t (*)(int, const char *, char *, size_t))dlsym(fastpath, "readlinkat");
|
||||
next_statx = (int (*)(int, const char *, int, unsigned int, struct statx *))dlsym(fastpath, "statx");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -92,6 +94,13 @@ static long path_readlink(int dirfd, const char *path, char *buf, size_t size) {
|
||||
return next_readlinkat(dirfd, path, buf, size);
|
||||
}
|
||||
|
||||
static long path_statx(int dirfd, const char *path, int flags, unsigned int mask, struct statx *out) {
|
||||
if (!next_statx) {
|
||||
return real_syscall(SYS_statx, (long)dirfd, (long)path, (long)flags, (long)mask, (long)out);
|
||||
}
|
||||
return next_statx(dirfd, path, flags, mask, out);
|
||||
}
|
||||
|
||||
void *dlopen(const char *filename, int flags) {
|
||||
if (!real_dlopen) {
|
||||
real_dlopen = (void *(*)(const char *, int))dlsym(RTLD_NEXT, "dlopen");
|
||||
@@ -329,6 +338,26 @@ static int execveat_is_execve(const long *args) {
|
||||
return path[0] == '/' || (int)args[0] == AT_FDCWD;
|
||||
}
|
||||
|
||||
static long openat2_call(const long *args) {
|
||||
if (!real_syscall) {
|
||||
real_syscall = (long (*)(long, ...)) dlsym(RTLD_NEXT, "syscall");
|
||||
}
|
||||
if (!__atomic_load_n(&openat2_missing, __ATOMIC_RELAXED)) {
|
||||
long fd = real_syscall(SYS_openat2, args[0], args[1], args[2], args[3]);
|
||||
if (fd != -1 || errno != ENOSYS) {
|
||||
return fd;
|
||||
}
|
||||
__atomic_store_n(&openat2_missing, 1, __ATOMIC_RELAXED);
|
||||
}
|
||||
return openat2_via_openat(args);
|
||||
}
|
||||
|
||||
int bl_openat2(int dirfd, const char *path, void *how, size_t size) __asm__("openat2");
|
||||
int bl_openat2(int dirfd, const char *path, void *how, size_t size) {
|
||||
long args[6] = {dirfd, (long)path, (long)how, (long)size, 0, 0};
|
||||
return (int)openat2_call(args);
|
||||
}
|
||||
|
||||
int bl_writewatch_syscall(long number, const long *args, long (*real)(long, ...), long *rc) __attribute__((visibility("hidden")));
|
||||
|
||||
long syscall(long number, ...) {
|
||||
@@ -360,18 +389,20 @@ long syscall(long number, ...) {
|
||||
return handled;
|
||||
}
|
||||
if (number == SYS_openat2) {
|
||||
if (!__atomic_load_n(&openat2_missing, __ATOMIC_RELAXED)) {
|
||||
long fd = real_syscall(number, args[0], args[1], args[2], args[3]);
|
||||
if (fd != -1 || errno != ENOSYS) {
|
||||
return fd;
|
||||
}
|
||||
__atomic_store_n(&openat2_missing, 1, __ATOMIC_RELAXED);
|
||||
}
|
||||
return openat2_via_openat(args);
|
||||
return openat2_call(args);
|
||||
}
|
||||
if (number == SYS_openat) {
|
||||
return path_open((int)args[0], (const char *)args[1], (int)args[2], args[3]);
|
||||
}
|
||||
if (number == BL_SYS_FSTATAT) {
|
||||
return path_stat((int)args[0], (const char *)args[1], (bl_stat *)args[2], (int)args[3]);
|
||||
}
|
||||
if (number == SYS_readlinkat) {
|
||||
return path_readlink((int)args[0], (const char *)args[1], (char *)args[2], (size_t)args[3]);
|
||||
}
|
||||
if (number == SYS_statx) {
|
||||
return path_statx((int)args[0], (const char *)args[1], (int)args[2], (unsigned int)args[3], (struct statx *)args[4]);
|
||||
}
|
||||
if (number == SYS_execveat && execveat_is_execve(args)) {
|
||||
return real_syscall(SYS_execve, args[1], args[2], args[3]);
|
||||
}
|
||||
|
||||
Loaded 100 of 630 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user