mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-05 12:35:42 +00:00
Compare commits
55
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bf811040ae | ||
|
|
272cd60b19 | ||
|
|
a844483080 | ||
|
|
1d1de10b2d | ||
|
|
7ab0c12c97 | ||
|
|
cd85eb1624 | ||
|
|
dd2b2b08c3 | ||
|
|
97a0f1553f | ||
|
|
78e4cb8369 | ||
|
|
64d5f92391 | ||
|
|
3dbc4ecc6d | ||
|
|
2f1e0a1348 | ||
|
|
ff9807ad29 | ||
|
|
37b6f336a7 | ||
|
|
1a527e8ed1 | ||
|
|
1379396b99 | ||
|
|
e835f5c523 | ||
|
|
4748a217b3 | ||
|
|
96d8678dd3 | ||
|
|
e0b0af4290 | ||
|
|
8940b0ca32 | ||
|
|
cb2f7c0109 | ||
|
|
a5f608b9d7 | ||
|
|
236eeddeec | ||
|
|
3a90ac0665 | ||
|
|
dd4c4a294c | ||
|
|
a0bd480576 | ||
|
|
01c7248965 | ||
|
|
b6903db58c | ||
|
|
33caa8a57c | ||
|
|
fbd068c6b8 | ||
|
|
35dfd99013 | ||
|
|
6ca3052eb7 | ||
|
|
2d70341214 | ||
|
|
5a1e5deba9 | ||
|
|
a2433f1965 | ||
|
|
f9db495e3f | ||
|
|
fdb9cbb7a5 | ||
|
|
79e1d30d6c | ||
|
|
a4841dff9d | ||
|
|
21aeab0126 | ||
|
|
fd0c6f124f | ||
|
|
9f5a2f39cd | ||
|
|
61a9a48e70 | ||
|
|
9c0f87a4c8 | ||
|
|
b5ae6cc63f | ||
|
|
4bcfca58e2 | ||
|
|
0c59f551af | ||
|
|
0687e3477e | ||
|
|
f467bb22e8 | ||
|
|
dad1aa2dc7 | ||
|
|
9f71b427bf | ||
|
|
0091b751f4 | ||
|
|
05097b0eea | ||
|
|
401a650b5b |
No files matched your search
@@ -1,80 +0,0 @@
|
||||
name: Build desktop package (KDE Plasma)
|
||||
|
||||
# The desktop the app installs into its Linux runtime on first use: KDE Plasma as SteamOS's desktop
|
||||
# mode has it, the closure of tools/desktop-kde/seeds.txt over Arch Linux ARM minus what the runtime
|
||||
# already carries, plus tools/desktop-kde/overlay (tools/desktop-kde/build.sh), every package
|
||||
# signature-checked. Published as a release in Droid-Deck/DroidDeck-Components with DroidDeck's
|
||||
# other components; the apk pins it in tools/desktop-kde/release.env (tag, sha256, size). A
|
||||
# published tag is never rebuilt: the packages are Arch Linux ARM's current ones, so a rebuild
|
||||
# would not match the pinned sha256. A changed package gets a new tag (desktop-kde-r2, ...) and a
|
||||
# release.env update.
|
||||
on:
|
||||
push:
|
||||
paths:
|
||||
- 'tools/desktop-kde/**'
|
||||
- '.github/workflows/build-desktop-kde.yml'
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: 'Release tag to publish as (e.g. desktop-kde-r1); empty = artifact only'
|
||||
required: false
|
||||
default: ''
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 90
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/create-github-app-token@v2
|
||||
id: components-token
|
||||
if: github.event_name == 'workflow_dispatch' && inputs.tag != ''
|
||||
with:
|
||||
app-id: ${{ vars.DROIDDECK_CI_APP_ID }}
|
||||
private-key: ${{ secrets.DROIDDECK_CI_APP_KEY }}
|
||||
owner: Droid-Deck
|
||||
repositories: DroidDeck-Components
|
||||
- name: Refuse a published tag
|
||||
if: github.event_name == 'workflow_dispatch' && inputs.tag != ''
|
||||
env:
|
||||
GH_TOKEN: ${{ steps.components-token.outputs.token }}
|
||||
run: |
|
||||
if gh release view '${{ inputs.tag }}' -R Droid-Deck/DroidDeck-Components >/dev/null 2>&1; then
|
||||
echo "::error::${{ inputs.tag }} is already published, and published tags are never replaced: use a new tag"
|
||||
exit 1
|
||||
fi
|
||||
- name: Build
|
||||
run: |
|
||||
set -euo pipefail
|
||||
sudo apt-get update -qq && sudo apt-get install -y -qq zstd xz-utils gpgv >/dev/null
|
||||
tools/desktop-kde/build.sh out
|
||||
echo "size $(stat -c %s out/desktop-kde.tar.zst) sha256 $(cat out/desktop-kde.sha256)"
|
||||
# The package itself too, briefly: enough to try a build on a device before publishing it.
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: desktop-kde
|
||||
retention-days: 7
|
||||
compression-level: 0
|
||||
path: |
|
||||
out/desktop-kde.tar.zst
|
||||
out/desktop-kde.packages.txt
|
||||
out/desktop-kde.sha256
|
||||
- name: Publish
|
||||
if: github.event_name == 'workflow_dispatch' && inputs.tag != ''
|
||||
env:
|
||||
GH_TOKEN: ${{ steps.components-token.outputs.token }}
|
||||
GH_REPO: Droid-Deck/DroidDeck-Components
|
||||
run: |
|
||||
set -euo pipefail
|
||||
TAG='${{ inputs.tag }}'
|
||||
if gh release view "$TAG" >/dev/null 2>&1; then
|
||||
echo "::error::$TAG is already published in DroidDeck-Components, and published tags are never replaced: use a new tag"
|
||||
exit 1
|
||||
fi
|
||||
gh release create "$TAG" --latest=false --prerelease=false --title "$TAG" \
|
||||
--notes "KDE Plasma desktop package for DroidDeck's Linux runtime ($GITHUB_REPOSITORY tools/desktop-kde, $GITHUB_SHA). size $(stat -c %s out/desktop-kde.tar.zst), sha256 $(cat out/desktop-kde.sha256). desktop-kde.packages.txt lists the signature-checked Arch Linux ARM packages it was built from." \
|
||||
out/desktop-kde.tar.zst out/desktop-kde.sha256 out/desktop-kde.packages.txt
|
||||
gh release edit "$TAG" --latest=false --prerelease=false
|
||||
@@ -0,0 +1,49 @@
|
||||
name: Build wlroots (patched)
|
||||
|
||||
# The desktop's wlroots (Arch Linux ARM's wlroots0.20, what the desktop package's labwc links)
|
||||
# rebuilt with tools/wlroots/patches: a Vulkan DMA-BUF allocator for the Adreno node, which is not
|
||||
# a DRM device, so labwc's vulkan and gles2 renderers can start. Built in an Arch Linux ARM
|
||||
# container on an arm64 runner and published as a release asset the apk build fetches
|
||||
# (tools/wlroots/release.env names the tag and sha). The hosted desktop package is never changed.
|
||||
on:
|
||||
push:
|
||||
paths:
|
||||
- 'tools/wlroots/**'
|
||||
- '.github/workflows/build-wlroots.yml'
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: 'Release tag to publish as (e.g. wlroots-0.20.2-p1); empty = artifact only'
|
||||
required: false
|
||||
default: ''
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-24.04-arm
|
||||
timeout-minutes: 90
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Build in Arch Linux ARM
|
||||
run: |
|
||||
set -euo pipefail
|
||||
docker run --rm -v "$PWD:/work" -w /work menci/archlinuxarm:base-devel bash tools/wlroots/build-in-arch.sh
|
||||
sudo chown -R "$(id -u):$(id -g)" .
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: wlroots-patched
|
||||
path: |
|
||||
wlroots.tzst
|
||||
wlroots.tzst.sha256
|
||||
- name: Publish
|
||||
if: github.event_name == 'workflow_dispatch' && inputs.tag != ''
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
gh release create "${{ inputs.tag }}" --latest=false --prerelease=false --title "${{ inputs.tag }}" --notes "wlroots 0.20.2 with tools/wlroots/patches (Vulkan DMA-BUF allocator for non-DRM GPU nodes); staged by the apk at /usr/local/lib/droiddeck-wlroots for the desktop's GPU renderers. sha256 $(cut -d' ' -f1 wlroots.tzst.sha256)" wlroots.tzst wlroots.tzst.sha256 || gh release upload "${{ inputs.tag }}" wlroots.tzst wlroots.tzst.sha256 --clobber
|
||||
# A component the apk fetches by tag, never something users install: it must not
|
||||
# become the repo's Latest release or appear as a pre-release, also when re-uploaded.
|
||||
gh release edit "${{ inputs.tag }}" --latest=false --prerelease=false
|
||||
@@ -216,6 +216,14 @@ jobs:
|
||||
test -f "$D/usr/local/bin/gamescope"
|
||||
rm gamescope.tzst
|
||||
fi
|
||||
if [ -f tools/wlroots/release.env ]; then
|
||||
. tools/wlroots/release.env
|
||||
gh release download "${WLROOTS_TAG}" -R "${GITHUB_REPOSITORY}" -p wlroots.tzst -O wlroots.tzst
|
||||
echo "${WLROOTS_SHA256} wlroots.tzst" | sha256sum -c -
|
||||
tar --use-compress-program=unzstd -xf wlroots.tzst -C "$D"
|
||||
test -f "$D/usr/local/lib/droiddeck-wlroots/libwlroots-0.20.so"
|
||||
rm wlroots.tzst
|
||||
fi
|
||||
. tools/linuxfs/uruntime.env
|
||||
curl -fsSL --retry 3 -o uruntime "https://github.com/VHSgunzo/uruntime/releases/download/${URUNTIME_VERSION}/${URUNTIME_ASSET}"
|
||||
echo "${URUNTIME_SHA256} uruntime" | sha256sum -c -
|
||||
@@ -254,13 +262,10 @@ jobs:
|
||||
done
|
||||
install -m644 msi-pkgs/usr/bin/msiinfo "$T/msiinfo"
|
||||
install -m644 msi-pkgs/usr/bin/cabextract "$T/cabextract"
|
||||
# 7-Zip (the full build with its format plugin) opens installer .exe wrappers.
|
||||
install -m644 msi-pkgs/usr/lib/7zip/7z "$T/7z"
|
||||
install -m644 msi-pkgs/usr/lib/7zip/7z.so "$T/7z.so"
|
||||
for so in libmsi-1.0.so.0 libgsf-1.so.114 libgcab-1.0.so.0; do
|
||||
cp -L "msi-pkgs/usr/lib/$so" "$T/$so"
|
||||
done
|
||||
for f in NOTICE GPL-2 GPL-3 LGPL-2.1 7zip-License 7zip-unRarLicense; do
|
||||
for f in NOTICE GPL-2 GPL-3 LGPL-2.1; do
|
||||
install -Dm644 "tools/msitools/licenses/$f" "$D/usr/local/share/licenses/droiddeck-msitools/$f"
|
||||
done
|
||||
rm -rf msi-pkgs
|
||||
@@ -268,7 +273,9 @@ jobs:
|
||||
install -Dm644 tools/linuxfs/desktop/droiddeck-desktop "$D/usr/local/bin/droiddeck-desktop"
|
||||
install -Dm644 tools/linuxfs/desktop/droiddeck-gpu "$D/usr/local/bin/droiddeck-gpu"
|
||||
install -Dm644 tools/linuxfs/desktop/droiddeck-desktop-gpu "$D/usr/local/bin/droiddeck-desktop-gpu"
|
||||
install -Dm644 tools/linuxfs/desktop/kwin_wayland_wrapper "$D/usr/local/bin/kwin_wayland_wrapper"
|
||||
install -Dm644 tools/linuxfs/desktop/autostart "$D/etc/xdg/labwc/autostart"
|
||||
install -Dm644 tools/linuxfs/desktop/rc.xml "$D/etc/xdg/labwc/rc.xml"
|
||||
install -Dm644 tools/linuxfs/desktop/panel.conf "$D/etc/xdg/lxqt/panel.conf"
|
||||
install -Dm644 tools/linuxfs/desktop/firefox-droiddeck.js "$D/usr/lib/firefox/defaults/pref/droiddeck.js"
|
||||
ls -lR "$D"
|
||||
|
||||
@@ -394,7 +401,7 @@ jobs:
|
||||
test -f "$D/usr/local/bin/droiddeck-session"
|
||||
test -f "$D/usr/local/bin/droiddeck-proton-extra"
|
||||
test -f "$D/usr/local/bin/droiddeck-msi-install"
|
||||
for f in msiinfo cabextract 7z 7z.so libmsi-1.0.so.0 libgsf-1.so.114 libgcab-1.0.so.0; do
|
||||
for f in msiinfo cabextract libmsi-1.0.so.0 libgsf-1.so.114 libgcab-1.0.so.0; do
|
||||
test -f "$D/usr/local/lib/droiddeck-msitools/$f" || { echo "::error::droiddeck-msitools/$f missing"; exit 1; }
|
||||
done
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ Before Steam launches, you must turn off **Restrict child processes** in Develop
|
||||
|
||||
## Community
|
||||
|
||||
Join the [DroidDeck Discord](https://discord.gg/JRGAvawjsm) for help, Preview builds, and device reports. Bug reports go in its **#bug-reports** forum; attach the zip from **Share logs** (Setup, or the session drawer) so the logs come with it.
|
||||
Join the [DroidDeck Discord](https://discord.gg/JRGAvawjsm) for help, Preview builds, and device reports. Bug reports go in its **#bug-reports** forum; attach the session folder from `Download/DroidDeck/` so the logs come with it.
|
||||
|
||||
## Build
|
||||
|
||||
@@ -29,7 +29,7 @@ Run `tools/build_local.sh` with Docker, Java 17, the Android SDK/NDK, and `zstd`
|
||||
|
||||
## Limits
|
||||
|
||||
Compatibility and performance vary by device; hardware validation is limited. Desktop compositing uses software rendering. Firefox sandboxing is reduced under proot. Logs are kept app-private (`files/logs/`, the last 30 sessions); **Share logs** packs the newest session, with the stores and tool logs, into one scrubbed zip.
|
||||
Compatibility and performance vary by device; hardware validation is limited. Desktop compositing uses software rendering. Firefox sandboxing is reduced under proot. See the session logs in `Download/DroidDeck/` when diagnosing problems.
|
||||
|
||||
## Credits and licence
|
||||
|
||||
|
||||
@@ -59,12 +59,6 @@ def ciBuild = providers.environmentVariable('GITHUB_ACTIONS').getOrNull() == 'tr
|
||||
def releaseSigner = rootProject.file('keystore/release-signer.sha256').text.trim()
|
||||
// When the source was committed, for "built 3 hours ago": fixed per commit, so it costs no rebuilds.
|
||||
def commitTime = (gitValue(['show', '-s', '--format=%ct', 'HEAD']) ?: '0').with { it.isLong() ? it : '0' }
|
||||
// The desktop package this apk installs (tools/desktop-kde/release.env): published once per tag in
|
||||
// DroidDeck-Components, pinned here with its checksum like gamescope and the esync packs, so the
|
||||
// desktop scripts in the apk always get the package they were made for.
|
||||
def desktopKde = rootProject.file('tools/desktop-kde/release.env').readLines()
|
||||
.findAll { it.contains('=') && !it.startsWith('#') }
|
||||
.collectEntries { def kv = it.split('=', 2); [(kv[0].trim()): kv[1].trim()] }
|
||||
// tools/release/variants.txt as "package=suffix;...", so the updater picks the apk of the package it runs as.
|
||||
def variantSuffixes = rootProject.file('tools/release/variants.txt').readLines()
|
||||
.findAll { it.trim() && !it.startsWith('#') }
|
||||
@@ -94,10 +88,6 @@ android {
|
||||
buildConfigField "String", "RELEASE_SIGNER", "\"${releaseSigner}\""
|
||||
buildConfigField "long", "COMMIT_TIME", "${commitTime}L * 1000L"
|
||||
buildConfigField "String", "VARIANT_SUFFIXES", "\"${variantSuffixes}\""
|
||||
buildConfigField "String", "DESKTOP_KDE_TAG", "\"${desktopKde.DESKTOP_KDE_TAG}\""
|
||||
buildConfigField "String", "DESKTOP_KDE_URL", "\"https://github.com/${desktopKde.DESKTOP_KDE_REPO}/releases/download/${desktopKde.DESKTOP_KDE_TAG}/desktop-kde.tar.zst\""
|
||||
buildConfigField "String", "DESKTOP_KDE_SHA256", "\"${desktopKde.DESKTOP_KDE_SHA256}\""
|
||||
buildConfigField "long", "DESKTOP_KDE_SIZE", "${desktopKde.DESKTOP_KDE_SIZE}L"
|
||||
|
||||
ndk {
|
||||
abiFilters 'arm64-v8a'
|
||||
|
||||
@@ -8,8 +8,6 @@
|
||||
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
|
||||
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||
<!-- Store download progress and "installed" / "failed" notices (Android 13+). -->
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<!-- The session keeps running while the app is not on screen: a foreground service holds the
|
||||
process at perceptible priority, and a high-performance WiFi lock keeps a backgrounded
|
||||
download from being throttled to nothing by the radio's power-save. -->
|
||||
|
||||
@@ -17,7 +17,6 @@ add_library(droiddeckwayland SHARED
|
||||
src/wl_clipboard.c
|
||||
src/wl_text_input.c
|
||||
src/wl_toplevel_icon.c
|
||||
src/wl_single_pixel.c
|
||||
src/wl_color_mgmt.c
|
||||
src/hdr_compose.c
|
||||
src/blend_pass.c
|
||||
@@ -32,7 +31,6 @@ add_library(droiddeckwayland SHARED
|
||||
generated/wlr-data-control-unstable-v1-protocol.c
|
||||
generated/text-input-unstable-v3-protocol.c
|
||||
generated/xdg-toplevel-icon-v1-protocol.c
|
||||
generated/single-pixel-buffer-v1-protocol.c
|
||||
generated/banner-ahb-v1-protocol.c
|
||||
src/framegen_bridge.c
|
||||
src/framegen_jni.c
|
||||
|
||||
@@ -1,61 +0,0 @@
|
||||
/* Generated by wayland-scanner 1.26.0 */
|
||||
|
||||
/*
|
||||
* Copyright © 2022 Simon Ser
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a
|
||||
* copy of this software and associated documentation files (the "Software"),
|
||||
* to deal in the Software without restriction, including without limitation
|
||||
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
* and/or sell copies of the Software, and to permit persons to whom the
|
||||
* Software is furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice (including the next
|
||||
* paragraph) shall be included in all copies or substantial portions of the
|
||||
* Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
|
||||
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
* DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdint.h>
|
||||
#include "wayland-util.h"
|
||||
|
||||
#ifndef __has_attribute
|
||||
# define __has_attribute(x) 0 /* Compatibility with non-clang compilers. */
|
||||
#endif
|
||||
|
||||
#if (__has_attribute(visibility) || defined(__GNUC__) && __GNUC__ >= 4)
|
||||
#define WL_PRIVATE __attribute__ ((visibility("hidden")))
|
||||
#else
|
||||
#define WL_PRIVATE
|
||||
#endif
|
||||
|
||||
extern const struct wl_interface wl_buffer_interface;
|
||||
|
||||
static const struct wl_interface *single_pixel_buffer_v1_types[] = {
|
||||
&wl_buffer_interface,
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
};
|
||||
|
||||
static const struct wl_message wp_single_pixel_buffer_manager_v1_requests[] = {
|
||||
{ "destroy", "", single_pixel_buffer_v1_types + 0 },
|
||||
{ "create_u32_rgba_buffer", "nuuuu", single_pixel_buffer_v1_types + 0 },
|
||||
};
|
||||
|
||||
WL_PRIVATE const struct wl_interface wp_single_pixel_buffer_manager_v1_interface = {
|
||||
"wp_single_pixel_buffer_manager_v1", 1,
|
||||
2, wp_single_pixel_buffer_manager_v1_requests,
|
||||
0, NULL,
|
||||
};
|
||||
|
||||
@@ -1,142 +0,0 @@
|
||||
/* Generated by wayland-scanner 1.26.0 */
|
||||
|
||||
#ifndef SINGLE_PIXEL_BUFFER_V1_SERVER_PROTOCOL_H
|
||||
#define SINGLE_PIXEL_BUFFER_V1_SERVER_PROTOCOL_H
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
#include "wayland-server.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
struct wl_client;
|
||||
struct wl_resource;
|
||||
|
||||
/**
|
||||
* @page page_single_pixel_buffer_v1 The single_pixel_buffer_v1 protocol
|
||||
* single pixel buffer factory
|
||||
*
|
||||
* @section page_desc_single_pixel_buffer_v1 Description
|
||||
*
|
||||
* This protocol extension allows clients to create single-pixel buffers.
|
||||
*
|
||||
* Compositors supporting this protocol extension should also support the
|
||||
* viewporter protocol extension. Clients may use viewporter to scale a
|
||||
* single-pixel buffer to a desired size.
|
||||
*
|
||||
* Warning! The protocol described in this file is currently in the testing
|
||||
* phase. Backward compatible changes may be added together with the
|
||||
* corresponding interface version bump. Backward incompatible changes can
|
||||
* only be done by creating a new major version of the extension.
|
||||
*
|
||||
* @section page_ifaces_single_pixel_buffer_v1 Interfaces
|
||||
* - @subpage page_iface_wp_single_pixel_buffer_manager_v1 - global factory for single-pixel buffers
|
||||
* @section page_copyright_single_pixel_buffer_v1 Copyright
|
||||
* <pre>
|
||||
*
|
||||
* Copyright © 2022 Simon Ser
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a
|
||||
* copy of this software and associated documentation files (the "Software"),
|
||||
* to deal in the Software without restriction, including without limitation
|
||||
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
* and/or sell copies of the Software, and to permit persons to whom the
|
||||
* Software is furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice (including the next
|
||||
* paragraph) shall be included in all copies or substantial portions of the
|
||||
* Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
|
||||
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
* DEALINGS IN THE SOFTWARE.
|
||||
* </pre>
|
||||
*/
|
||||
struct wl_buffer;
|
||||
struct wp_single_pixel_buffer_manager_v1;
|
||||
|
||||
#ifndef WP_SINGLE_PIXEL_BUFFER_MANAGER_V1_INTERFACE
|
||||
#define WP_SINGLE_PIXEL_BUFFER_MANAGER_V1_INTERFACE
|
||||
/**
|
||||
* @page page_iface_wp_single_pixel_buffer_manager_v1 wp_single_pixel_buffer_manager_v1
|
||||
* @section page_iface_wp_single_pixel_buffer_manager_v1_desc Description
|
||||
*
|
||||
* The wp_single_pixel_buffer_manager_v1 interface is a factory for
|
||||
* single-pixel buffers.
|
||||
* @section page_iface_wp_single_pixel_buffer_manager_v1_api API
|
||||
* See @ref iface_wp_single_pixel_buffer_manager_v1.
|
||||
*/
|
||||
/**
|
||||
* @defgroup iface_wp_single_pixel_buffer_manager_v1 The wp_single_pixel_buffer_manager_v1 interface
|
||||
*
|
||||
* The wp_single_pixel_buffer_manager_v1 interface is a factory for
|
||||
* single-pixel buffers.
|
||||
*/
|
||||
extern const struct wl_interface wp_single_pixel_buffer_manager_v1_interface;
|
||||
#endif
|
||||
|
||||
/**
|
||||
* @ingroup iface_wp_single_pixel_buffer_manager_v1
|
||||
* @struct wp_single_pixel_buffer_manager_v1_interface
|
||||
*/
|
||||
struct wp_single_pixel_buffer_manager_v1_interface {
|
||||
/**
|
||||
* destroy the manager
|
||||
*
|
||||
* Destroy the wp_single_pixel_buffer_manager_v1 object.
|
||||
*
|
||||
* The child objects created via this interface are unaffected.
|
||||
*/
|
||||
void (*destroy)(struct wl_client *client,
|
||||
struct wl_resource *resource);
|
||||
/**
|
||||
* create a 1×1 buffer from 32-bit RGBA values
|
||||
*
|
||||
* Create a single-pixel buffer from four 32-bit RGBA values.
|
||||
*
|
||||
* Unless specified in another protocol extension, the RGBA values
|
||||
* use pre-multiplied alpha.
|
||||
*
|
||||
* The width and height of the buffer are 1.
|
||||
*
|
||||
* The r, g, b and a arguments valid range is from UINT32_MIN (0)
|
||||
* to UINT32_MAX (0xffffffff).
|
||||
*
|
||||
* These arguments should be interpreted as a percentage, i.e. -
|
||||
* UINT32_MIN = 0% of the given color component - UINT32_MAX = 100%
|
||||
* of the given color component
|
||||
* @param r value of the buffer's red channel
|
||||
* @param g value of the buffer's green channel
|
||||
* @param b value of the buffer's blue channel
|
||||
* @param a value of the buffer's alpha channel
|
||||
*/
|
||||
void (*create_u32_rgba_buffer)(struct wl_client *client,
|
||||
struct wl_resource *resource,
|
||||
uint32_t id,
|
||||
uint32_t r,
|
||||
uint32_t g,
|
||||
uint32_t b,
|
||||
uint32_t a);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @ingroup iface_wp_single_pixel_buffer_manager_v1
|
||||
*/
|
||||
#define WP_SINGLE_PIXEL_BUFFER_MANAGER_V1_DESTROY_SINCE_VERSION 1
|
||||
/**
|
||||
* @ingroup iface_wp_single_pixel_buffer_manager_v1
|
||||
*/
|
||||
#define WP_SINGLE_PIXEL_BUFFER_MANAGER_V1_CREATE_U32_RGBA_BUFFER_SINCE_VERSION 1
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -1,76 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<protocol name="single_pixel_buffer_v1">
|
||||
<copyright>
|
||||
Copyright © 2022 Simon Ser
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a
|
||||
copy of this software and associated documentation files (the "Software"),
|
||||
to deal in the Software without restriction, including without limitation
|
||||
the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
and/or sell copies of the Software, and to permit persons to whom the
|
||||
Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice (including the next
|
||||
paragraph) shall be included in all copies or substantial portions of the
|
||||
Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
|
||||
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
||||
</copyright>
|
||||
|
||||
<description summary="single pixel buffer factory">
|
||||
This protocol extension allows clients to create single-pixel buffers.
|
||||
|
||||
Compositors supporting this protocol extension should also support the
|
||||
viewporter protocol extension. Clients may use viewporter to scale a
|
||||
single-pixel buffer to a desired size.
|
||||
|
||||
Warning! The protocol described in this file is currently in the testing
|
||||
phase. Backward compatible changes may be added together with the
|
||||
corresponding interface version bump. Backward incompatible changes can
|
||||
only be done by creating a new major version of the extension.
|
||||
</description>
|
||||
|
||||
<interface name="wp_single_pixel_buffer_manager_v1" version="1">
|
||||
<description summary="global factory for single-pixel buffers">
|
||||
The wp_single_pixel_buffer_manager_v1 interface is a factory for
|
||||
single-pixel buffers.
|
||||
</description>
|
||||
|
||||
<request name="destroy" type="destructor">
|
||||
<description summary="destroy the manager">
|
||||
Destroy the wp_single_pixel_buffer_manager_v1 object.
|
||||
|
||||
The child objects created via this interface are unaffected.
|
||||
</description>
|
||||
</request>
|
||||
|
||||
<request name="create_u32_rgba_buffer">
|
||||
<description summary="create a 1×1 buffer from 32-bit RGBA values">
|
||||
Create a single-pixel buffer from four 32-bit RGBA values.
|
||||
|
||||
Unless specified in another protocol extension, the RGBA values use
|
||||
pre-multiplied alpha.
|
||||
|
||||
The width and height of the buffer are 1.
|
||||
|
||||
The r, g, b and a arguments valid range is from UINT32_MIN (0)
|
||||
to UINT32_MAX (0xffffffff).
|
||||
|
||||
These arguments should be interpreted as a percentage, i.e.
|
||||
- UINT32_MIN = 0% of the given color component
|
||||
- UINT32_MAX = 100% of the given color component
|
||||
</description>
|
||||
<arg name="id" type="new_id" interface="wl_buffer"/>
|
||||
<arg name="r" type="uint" summary="value of the buffer's red channel"/>
|
||||
<arg name="g" type="uint" summary="value of the buffer's green channel"/>
|
||||
<arg name="b" type="uint" summary="value of the buffer's blue channel"/>
|
||||
<arg name="a" type="uint" summary="value of the buffer's alpha channel"/>
|
||||
</request>
|
||||
</interface>
|
||||
</protocol>
|
||||
@@ -745,21 +745,6 @@ static void take_shm(struct surface *s, struct wl_shm_buffer *shm, struct wl_res
|
||||
if (ci && ci->asked_feedback) ci->shm_frames++; /* since it asked for GPU buffers */
|
||||
}
|
||||
|
||||
/* A single-pixel buffer (wl_single_pixel.c) as a 1x1 image, which the surface's viewport stretches. */
|
||||
static void take_pixel(struct surface *s, const uint8_t bgra[4], struct wl_resource *buffer) {
|
||||
if (s->shm_img && (vkp_image_width(s->shm_img) != 1 || vkp_image_height(s->shm_img) != 1)) {
|
||||
vkp_image_destroy(s->shm_img);
|
||||
s->shm_img = NULL;
|
||||
}
|
||||
if (!s->shm_img) s->shm_img = vkp_image_create_shm(1, 1);
|
||||
if (s->shm_img) vkp_image_upload_shm(s->shm_img, bgra, 4);
|
||||
wl_buffer_send_release(buffer);
|
||||
s->buf_w = 1;
|
||||
s->buf_h = 1;
|
||||
s->buf_alpha = bgra[3] != 0xff;
|
||||
s->has_content = s->shm_img != NULL;
|
||||
}
|
||||
|
||||
/* The window the app's performance HUD follows: the latest one at least as big as the last to
|
||||
* start presenting GPU frames (take_dmabuf) (X11 binds the HUD to the _MESA_DRV window and counts X presents instead). JNI upcalls. */
|
||||
static struct surface *g_hud_surface;
|
||||
@@ -1099,7 +1084,6 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
|
||||
struct wl_resource *buffer = s->pending_buffer;
|
||||
struct dmabuf_buffer *db = get_dmabuf(buffer);
|
||||
struct wl_shm_buffer *shm = buffer && !db ? wl_shm_buffer_get(buffer) : NULL;
|
||||
uint8_t pixel[4];
|
||||
|
||||
/* The previous content is replaced before reaching the screen. */
|
||||
feedback_discard_all(&s->feedback);
|
||||
@@ -1129,9 +1113,6 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
|
||||
} else if (shm) {
|
||||
drop_dmabuf(s, 1);
|
||||
take_shm(s, shm, buffer);
|
||||
} else if (single_pixel_buffer_get(buffer, pixel)) {
|
||||
drop_dmabuf(s, 1);
|
||||
take_pixel(s, pixel, buffer);
|
||||
} else {
|
||||
drop_dmabuf(s, 1);
|
||||
s->has_content = 0;
|
||||
@@ -1680,24 +1661,15 @@ static void bind_desktop(struct wl_client *c, void *data, uint32_t ver, uint32_t
|
||||
static void output_release(struct wl_client *c, struct wl_resource *r) { wl_resource_destroy(r); }
|
||||
static const struct wl_output_interface output_impl = { .release = output_release };
|
||||
|
||||
/* Every bound wl_output, so a resized output (a foldable opening) can send its new mode. */
|
||||
static struct wl_list g_outputs;
|
||||
static void output_resource_destroy(struct wl_resource *r) { wl_list_remove(wl_resource_get_link(r)); }
|
||||
|
||||
static void output_send_mode(struct wl_resource *r) {
|
||||
wl_output_send_mode(r, WL_OUTPUT_MODE_CURRENT | WL_OUTPUT_MODE_PREFERRED,
|
||||
g_output_w > 0 ? g_output_w : 1920, g_output_h > 0 ? g_output_h : 1080,
|
||||
g_output_refresh_mhz > 0 ? g_output_refresh_mhz : 60000);
|
||||
}
|
||||
|
||||
static void bind_output(struct wl_client *c, void *data, uint32_t ver, uint32_t id) {
|
||||
struct wl_resource *r = wl_resource_create(c, &wl_output_interface, ver, id);
|
||||
if (!r) { wl_client_post_no_memory(c); return; }
|
||||
wl_resource_set_implementation(r, &output_impl, NULL, output_resource_destroy);
|
||||
wl_list_insert(&g_outputs, wl_resource_get_link(r));
|
||||
wl_resource_set_implementation(r, &output_impl, NULL, NULL);
|
||||
wl_output_send_geometry(r, 0, 0, 340, 190, WL_OUTPUT_SUBPIXEL_UNKNOWN,
|
||||
"DroidDeck", "Wayland", WL_OUTPUT_TRANSFORM_NORMAL);
|
||||
output_send_mode(r);
|
||||
wl_output_send_mode(r, WL_OUTPUT_MODE_CURRENT | WL_OUTPUT_MODE_PREFERRED,
|
||||
g_output_w > 0 ? g_output_w : 1920, g_output_h > 0 ? g_output_h : 1080,
|
||||
g_output_refresh_mhz > 0 ? g_output_refresh_mhz : 60000);
|
||||
if (ver >= WL_OUTPUT_NAME_SINCE_VERSION) {
|
||||
wl_output_send_name(r, "DroidDeck-1");
|
||||
wl_output_send_description(r, "DroidDeck display");
|
||||
@@ -3228,23 +3200,6 @@ static void key_event(uint32_t evdev, int pressed) {
|
||||
wl_display_flush_clients(g_display);
|
||||
}
|
||||
|
||||
/* The output changed size under a running session (a foldable opened or closed, with the
|
||||
* session following the screen). Every client that has had its first configure is told the new
|
||||
* size: gamescope's Wayland backend and the desktop's KWin both resize their output to it, and
|
||||
* the next buffers they commit fill the new panel instead of being letterboxed onto it. */
|
||||
static void output_resized(void) {
|
||||
struct surface *s;
|
||||
struct wl_resource *r;
|
||||
wl_resource_for_each(r, &g_outputs) {
|
||||
output_send_mode(r);
|
||||
if (wl_resource_get_version(r) >= 2) wl_output_send_done(r);
|
||||
}
|
||||
wl_list_for_each(s, &g_surfaces, link)
|
||||
if (s->xdg_toplevel && s->toplevel_committed) send_toplevel_configure(s);
|
||||
droiddeck_log("display", "output resized to %dx%d", g_output_w, g_output_h);
|
||||
wl_display_flush_clients(g_display);
|
||||
}
|
||||
|
||||
/* wl event-loop callback: drain queued input events written by the Android UI thread. */
|
||||
static int on_input_readable(int fd, uint32_t mask, void *data) {
|
||||
struct input_msg m;
|
||||
@@ -3257,7 +3212,6 @@ static int on_input_readable(int fd, uint32_t mask, void *data) {
|
||||
case 5: on_vsync(((int64_t)m.p1 << 32) | (uint32_t)m.p2); break;
|
||||
case 6: pointer_delta(m.p1 / 256.0, m.p2 / 256.0); break; /* relative motion, 1/256 px */
|
||||
case 7: deliver_touch(&m); break;
|
||||
case 8: output_resized(); break;
|
||||
default: deliver_pointer(&m); break;
|
||||
}
|
||||
}
|
||||
@@ -3288,14 +3242,6 @@ void droiddeck_wayland_send_key(int evdev, int state) {
|
||||
(void)n;
|
||||
}
|
||||
|
||||
/* Called from JNI after g_output_w/h changed: the compositor thread re-sends the size. */
|
||||
void droiddeck_wayland_output_resized(void) {
|
||||
if (g_input_pipe[1] < 0) return;
|
||||
struct input_msg m = { 8, 0, 0, 0, 0 };
|
||||
ssize_t n = write(g_input_pipe[1], &m, sizeof(m));
|
||||
(void)n;
|
||||
}
|
||||
|
||||
/* Called from JNI on every screen refresh (Choreographer). */
|
||||
void droiddeck_wayland_vsync(int64_t frame_time_ns) {
|
||||
if (g_input_pipe[1] < 0) return;
|
||||
@@ -3493,7 +3439,6 @@ static struct wl_listener g_client_created = { .notify = on_client_created };
|
||||
int droiddeck_wayland_run(void) {
|
||||
wl_list_init(&g_surfaces);
|
||||
wl_list_init(&g_toplevels);
|
||||
wl_list_init(&g_outputs);
|
||||
wl_list_init(&g_constraints);
|
||||
wl_list_init(&g_relative_pointers);
|
||||
open_session_log();
|
||||
|
||||
@@ -122,5 +122,4 @@ void droiddeck_ext_init(struct wl_display *display) {
|
||||
clipboard_init(display);
|
||||
text_input_init(display);
|
||||
toplevel_icon_init(display);
|
||||
single_pixel_init(display);
|
||||
}
|
||||
@@ -48,6 +48,3 @@ void text_input_host_commit(const char *utf8, size_t len);
|
||||
void text_input_host_preedit(const char *utf8, size_t len, int cursor_begin, int cursor_end);
|
||||
void text_input_host_delete(int before, int after);
|
||||
void toplevel_icon_init(struct wl_display *display);
|
||||
void single_pixel_init(struct wl_display *display);
|
||||
/* A wp_single_pixel_buffer_manager_v1 buffer: 1 and its pixel (B, G, R, A, premultiplied), else 0. */
|
||||
int single_pixel_buffer_get(struct wl_resource *buffer, uint8_t bgra[4]);
|
||||
@@ -160,11 +160,6 @@ static const char *vk_result_name(VkResult r);
|
||||
static pthread_mutex_t g_req_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
static ANativeWindow *g_req_window;
|
||||
static int g_req_pending;
|
||||
/* A detach was asked for since the compositor thread last looked. A rebind (null, then the same
|
||||
* window) to rebuild the swapchain at a new size can land in full before the thread gets to it,
|
||||
* and would otherwise read as the same window handed over again - nothing rebuilt, and the old
|
||||
* size's buffers scaled onto the rotated or refolded panel. */
|
||||
static int g_req_detached;
|
||||
|
||||
/* Scale mode + alignment (app values, see vk_present.h); written from any thread, read per frame. */
|
||||
static volatile int g_mode = VKP_MODE_STRETCH, g_align = VKP_ALIGN_CENTER;
|
||||
@@ -257,7 +252,6 @@ void vk_present_set_window(ANativeWindow *window) {
|
||||
if (g_req_pending && g_req_window && g_req_window != window) superseded = g_req_window;
|
||||
g_req_window = window;
|
||||
g_req_pending = 1;
|
||||
if (!window) g_req_detached = 1;
|
||||
pthread_mutex_unlock(&g_req_lock);
|
||||
if (superseded) ANativeWindow_release(superseded);
|
||||
}
|
||||
@@ -267,20 +261,13 @@ int vkp_apply_window_request(void) {
|
||||
pthread_mutex_lock(&g_req_lock);
|
||||
if (!g_req_pending) { pthread_mutex_unlock(&g_req_lock); return 0; }
|
||||
w = g_req_window;
|
||||
const int detached = g_req_detached;
|
||||
g_req_window = NULL;
|
||||
g_req_pending = 0;
|
||||
g_req_detached = 0;
|
||||
pthread_mutex_unlock(&g_req_lock);
|
||||
if (w == g_window) {
|
||||
/* The same window handed over again (ANativeWindow_fromSurface adds a reference each time). */
|
||||
if (w) ANativeWindow_release(w);
|
||||
if (!w || !detached) return 0;
|
||||
/* ... after a detach: a rebind for a resized surface. Rebuilt at its size on the next frame. */
|
||||
sc_layer_window_gone();
|
||||
destroy_swapchain();
|
||||
droiddeck_log("gpu", "screen surface rebound: rebuilding the swapchain at its new size");
|
||||
return 1;
|
||||
return 0;
|
||||
}
|
||||
sc_layer_window_gone(); /* the layer (if any) belongs to the old window */
|
||||
destroy_swapchain(); /* recreated against the new window on the next frame */
|
||||
@@ -1529,7 +1516,6 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
|
||||
const struct vkp_hdr_frame *hf, int *how) {
|
||||
if (how) *how = 0;
|
||||
vkp_apply_window_request();
|
||||
check_surface_changed(); /* a rotation or a fold the rebind did not cover: rebuild at the new size */
|
||||
if (g_dev_state == -2) return -1;
|
||||
if (dev_init() != 0 || !g_window || scene_w <= 0 || scene_h <= 0) return -1;
|
||||
|
||||
@@ -2113,7 +2099,6 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw
|
||||
const struct vkp_hdr_frame *hf, int *rw, int *rh) {
|
||||
if (g_pass.active) vkp_pass_abort();
|
||||
if (g_dev_state == -2 || dev_init() != 0 || !g_window || scene_w <= 0 || scene_h <= 0) return -1;
|
||||
check_surface_changed(); /* as in render_impl: the effects pass maps onto the output's size */
|
||||
if (!g_swapchain && swap_init() != 0) return -1; /* the mapping is in output pixels */
|
||||
update_map(scene_w, scene_h);
|
||||
if (!g_map.valid) return -1;
|
||||
|
||||
@@ -30,7 +30,6 @@ extern int droiddeck_cursor_serial(void);
|
||||
extern void droiddeck_wayland_send_key(int evdev, int state);
|
||||
extern void droiddeck_wayland_send_scene_input(int type, int a, int b);
|
||||
extern void droiddeck_wayland_vsync(int64_t frame_time_ns);
|
||||
extern void droiddeck_wayland_output_resized(void);
|
||||
extern volatile int g_fps_limit;
|
||||
extern volatile int g_hide_shell;
|
||||
extern volatile int g_zero_copy;
|
||||
@@ -402,17 +401,6 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetOutputSize(JNIEnv
|
||||
g_output_h = h > 0 ? h : 0;
|
||||
}
|
||||
|
||||
/* The output's size changed while the compositor runs (a foldable opening or closing with the
|
||||
* session following the screen): store it and have the compositor thread tell the clients. */
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeResizeOutput(JNIEnv *env, jclass clazz, jint w, jint h) {
|
||||
(void)env; (void)clazz;
|
||||
if (w <= 0 || h <= 0) return;
|
||||
g_output_w = w;
|
||||
g_output_h = h;
|
||||
droiddeck_wayland_output_resized();
|
||||
}
|
||||
|
||||
/* Fullscreen mode + screen alignment (Container.FULLSCREEN_* / ALIGN_* values): how the scene is
|
||||
* fitted onto the output. Any thread, any time; the next frame uses it. */
|
||||
JNIEXPORT void JNICALL
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
/*
|
||||
* wp_single_pixel_buffer_manager_v1 (version 1): a wl_buffer of one pixel of one colour, which a
|
||||
* client stretches over a surface with wp_viewporter. KWin's Wayland backend - the desktop's KWin
|
||||
* nested in this compositor - refuses to start without it. The surface takes the pixel as a 1x1
|
||||
* image, the way it takes a wl_shm buffer (compositor.c, take_pixel).
|
||||
*/
|
||||
#include <stdlib.h>
|
||||
#include "droiddeck_ext.h"
|
||||
#include "single-pixel-buffer-v1-server-protocol.h"
|
||||
|
||||
struct single_pixel {
|
||||
uint8_t bgra[4]; /* premultiplied, as wl_shm's ARGB8888 lies in memory */
|
||||
};
|
||||
|
||||
static void buffer_destroy(struct wl_client *c, struct wl_resource *r) { wl_resource_destroy(r); }
|
||||
static const struct wl_buffer_interface buffer_impl = { .destroy = buffer_destroy };
|
||||
|
||||
static void buffer_free(struct wl_resource *r) { free(wl_resource_get_user_data(r)); }
|
||||
|
||||
int single_pixel_buffer_get(struct wl_resource *buffer, uint8_t bgra[4]) {
|
||||
if (!buffer || !wl_resource_instance_of(buffer, &wl_buffer_interface, &buffer_impl)) return 0;
|
||||
struct single_pixel *p = wl_resource_get_user_data(buffer);
|
||||
for (int i = 0; i < 4; i++) bgra[i] = p->bgra[i];
|
||||
return 1;
|
||||
}
|
||||
|
||||
static void mgr_destroy(struct wl_client *c, struct wl_resource *r) { wl_resource_destroy(r); }
|
||||
static void mgr_create_buffer(struct wl_client *c, struct wl_resource *r, uint32_t id,
|
||||
uint32_t red, uint32_t green, uint32_t blue, uint32_t alpha) {
|
||||
struct single_pixel *p = calloc(1, sizeof(*p));
|
||||
struct wl_resource *buffer = p ? wl_resource_create(c, &wl_buffer_interface, 1, id) : NULL;
|
||||
if (!buffer) { free(p); wl_client_post_no_memory(c); return; }
|
||||
/* The protocol's values span the whole u32 range; the top byte is the 8-bit channel. */
|
||||
p->bgra[0] = blue >> 24;
|
||||
p->bgra[1] = green >> 24;
|
||||
p->bgra[2] = red >> 24;
|
||||
p->bgra[3] = alpha >> 24;
|
||||
wl_resource_set_implementation(buffer, &buffer_impl, p, buffer_free);
|
||||
}
|
||||
static const struct wp_single_pixel_buffer_manager_v1_interface mgr_impl = {
|
||||
.destroy = mgr_destroy, .create_u32_rgba_buffer = mgr_create_buffer,
|
||||
};
|
||||
static void bind_manager(struct wl_client *c, void *data, uint32_t ver, uint32_t id) {
|
||||
struct wl_resource *r = wl_resource_create(c, &wp_single_pixel_buffer_manager_v1_interface, ver, id);
|
||||
if (!r) { wl_client_post_no_memory(c); return; }
|
||||
wl_resource_set_implementation(r, &mgr_impl, NULL, NULL);
|
||||
}
|
||||
|
||||
void single_pixel_init(struct wl_display *display) {
|
||||
wl_global_create(display, &wp_single_pixel_buffer_manager_v1_interface, 1, NULL, bind_manager);
|
||||
}
|
||||
@@ -167,8 +167,6 @@ class MainActivity : ComponentActivity() {
|
||||
private var gameStoresEnabled by mutableStateOf(false)
|
||||
private var gameStoresSpeedTier by mutableStateOf("fast")
|
||||
private var storesOpenTab by mutableStateOf(SessionPrefs.STORES_OPEN_LIBRARY)
|
||||
/** A page a notification asked for ("stores:downloads", "app:<id>"), until the front end has gone there. */
|
||||
private var navRequest by mutableStateOf<String?>(null)
|
||||
private var storesShowMature by mutableStateOf(false)
|
||||
private var mic by mutableStateOf(false)
|
||||
private var wifiDiscovery by mutableStateOf(false)
|
||||
@@ -349,6 +347,7 @@ class MainActivity : ComponentActivity() {
|
||||
private var steamDownloadsInBackground by mutableStateOf(false)
|
||||
private var oscMode by mutableStateOf(SessionPrefs.OSC_AUTO)
|
||||
private var backActionsInverted by mutableStateOf(false)
|
||||
private var renderer by mutableStateOf("vulkan")
|
||||
private var gameStorage by mutableStateOf("")
|
||||
private var storageDiagnostics by mutableStateOf(false)
|
||||
private var storageOptions by mutableStateOf<List<GameStorage.Option>>(emptyList())
|
||||
@@ -442,7 +441,6 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
|
||||
private fun readGameIntent(request: Intent) {
|
||||
request.getStringExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV)?.let { navRequest = it; request.removeExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV) }
|
||||
shortcutPicker = request.action == Intent.ACTION_CREATE_SHORTCUT
|
||||
if (shortcutPicker) {
|
||||
// The shortcut picker must only offer games from the scan started for this request.
|
||||
@@ -589,7 +587,6 @@ class MainActivity : ComponentActivity() {
|
||||
gameStoresEnabled = gameStoresEnabled,
|
||||
gameStoresSpeedTier = gameStoresSpeedTier,
|
||||
storesOpenTab = storesOpenTab,
|
||||
navigate = navRequest,
|
||||
storesShowMature = storesShowMature,
|
||||
storeDownloadsActive = com.droiddeck.launcher.stores.StoresState.activeDownloads,
|
||||
),
|
||||
@@ -722,7 +719,6 @@ class MainActivity : ComponentActivity() {
|
||||
onGameStoresEnabled = { on -> SessionPrefs.setGameStoresEnabled(this, on); gameStoresEnabled = on; if (on) com.droiddeck.launcher.stores.StoresState.refresh(this) },
|
||||
onGameStoresSpeedTier = { tier -> SessionPrefs.setGameStoresSpeedTier(this, tier); gameStoresSpeedTier = tier },
|
||||
onStoresOpenTab = { tab -> SessionPrefs.setStoresOpenTab(this, tab); storesOpenTab = tab },
|
||||
onNavigated = { navRequest = null },
|
||||
onStoresShowMature = { show -> SessionPrefs.setStoresShowMature(this, show); storesShowMature = show },
|
||||
onLibraryChanged = { refreshAddedGames(); refresh() },
|
||||
onAnimationsEnabled = { on ->
|
||||
@@ -868,8 +864,6 @@ class MainActivity : ComponentActivity() {
|
||||
if (wanted.isNotEmpty()) requestPermissions(wanted.toTypedArray(), 1)
|
||||
// A session folder left without its ending - the process was killed - gets it now.
|
||||
if (!SessionState.running) Thread({
|
||||
com.droiddeck.launcher.session.LogMigration.run(this)
|
||||
SessionLogShare.clear(this)
|
||||
SessionArtifacts.finishAbandoned(this)
|
||||
SessionArtifacts.scrubOlder(this)
|
||||
SessionArtifacts.prune(this)
|
||||
@@ -1225,6 +1219,7 @@ class MainActivity : ComponentActivity() {
|
||||
directAudio = if (mode == SessionService.MODE_STEAM) directAudio else null,
|
||||
stretch16x9 = if (mode == SessionService.MODE_STEAM) stretch16x9 else null,
|
||||
mic = if (mode == SessionService.MODE_STEAM) mic else null,
|
||||
renderer = if (mode == SessionService.MODE_DESKTOP) renderer else null,
|
||||
gameStorage = if (mode == SessionService.MODE_STEAM) gameStorage else null,
|
||||
storageOptions = storageOptions,
|
||||
storageDiagnostics = mode == SessionService.MODE_STEAM && storageDiagnostics,
|
||||
@@ -1296,6 +1291,7 @@ class MainActivity : ComponentActivity() {
|
||||
requestPermissions(arrayOf(Manifest.permission.RECORD_AUDIO), 2)
|
||||
}
|
||||
},
|
||||
onRenderer = { r -> SessionPrefs.setDesktopRenderer(this, r); renderer = r },
|
||||
onGameStorage = { path, label -> setGameStorage(path, label) },
|
||||
onPickGameStorageFolder = {
|
||||
pickGameStorage.launch(InAppFilePicker.buildDirIntent(this, getString(R.string.main_pick_game_storage), gameStorage.ifEmpty { null }))
|
||||
@@ -1452,6 +1448,7 @@ class MainActivity : ComponentActivity() {
|
||||
stretch16x9 = SessionPrefs.stretch16x9(this)
|
||||
mic = SessionPrefs.micEnabled(this)
|
||||
refreshWifiDiscovery()
|
||||
renderer = SessionPrefs.desktopRenderer(this)
|
||||
gameStorage = SessionPrefs.gameStorage(this)
|
||||
storageDiagnostics = SessionPrefs.storageDiagnosticsEnabled(this)
|
||||
settingsMode = mode
|
||||
|
||||
@@ -336,8 +336,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
)
|
||||
}
|
||||
Log.i(TAG, "perf: " + PerfMode.apply(this, SessionState.fpsLimit))
|
||||
if (!SessionState.running) SessionState.followScreen = followChoice()
|
||||
applyFollowOrientation(resources.configuration)
|
||||
goFullscreen()
|
||||
// The device's volume keys change the stream the session plays on (the relay and
|
||||
// PulseAudio are media playback); they are never forwarded to the guest.
|
||||
@@ -745,9 +743,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
|
||||
private fun loadingTitle(): String = when (loadingMode()) {
|
||||
// Also when the desktop was asked for with Steam (Big Picture's Switch to Desktop): the client
|
||||
// does not open on it.
|
||||
SessionService.MODE_DESKTOP -> getString(R.string.session_starting_desktop)
|
||||
SessionService.MODE_DESKTOP ->
|
||||
if (!SessionState.running && intent.getStringExtra(SessionService.EXTRA_STEAM_UI) != null) getString(R.string.session_starting_steam_desktop)
|
||||
else getString(R.string.session_starting_desktop)
|
||||
SessionService.MODE_RUN -> {
|
||||
val program = if (SessionState.running) SessionState.program else intent.getStringExtra(SessionService.EXTRA_PROGRAM)
|
||||
com.droiddeck.launcher.frontend.Library.nameForProgram(program)?.let { getString(R.string.session_starting_named, it) }
|
||||
@@ -929,7 +927,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
/** Null when the desktop package is in, else the loading screen's closing line. */
|
||||
private fun installDesktop(): String? {
|
||||
uiHandler.post { loading.percent = -1; loading.say(getString(DESKTOP_LINES.downloading), DESKTOP_LINES.topic, readable = true) }
|
||||
val entry = com.droiddeck.launcher.runtime.DesktopCatalog.desktopEntry(this)
|
||||
val entry = com.droiddeck.launcher.runtime.DesktopCatalog.fetch()?.firstOrNull { it.id == "desktop" }
|
||||
?: return getString(R.string.session_desktop_catalog_unreachable)
|
||||
val problem = com.droiddeck.launcher.runtime.DesktopCatalog.install(this, entry,
|
||||
progressFor(DESKTOP_LINES, entry.size / 1_000_000))
|
||||
return problem?.let { getString(R.string.session_desktop_install_failed, it) }
|
||||
@@ -963,13 +962,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
// sized once when the session starts and cannot change. A foldable recreates the Surface
|
||||
// on the other panel, and recomputing the size there told the compositor a 21:9 buffer
|
||||
// was 16:9 - the picture came back squashed sideways. While a session runs, keep its size.
|
||||
// Follow screen is the exception: there the compositor tells gamescope the new size, so the
|
||||
// session takes the shape of the Surface it now has.
|
||||
val previous = SessionState.outputSize
|
||||
val live = if (SessionState.followScreen && !isInPictureInPictureMode)
|
||||
com.droiddeck.launcher.session.SessionDisplay.followSize(holder.surfaceFrame.width(), holder.surfaceFrame.height())
|
||||
else null
|
||||
val size = live ?: if (SessionState.running) previous else outputSize()
|
||||
val size = if (SessionState.running) SessionState.outputSize else outputSize()
|
||||
SessionState.outputSize = size
|
||||
if (!SessionState.running) SessionState.refreshHz = refreshHz()
|
||||
// How far the panel enlarges the session, for texture sharpness "Auto" (TextureFiltering):
|
||||
@@ -1028,10 +1021,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
driverId?.let { turnip.driverPath(it) }, driverId?.let { turnip.libraryName(it) },
|
||||
applicationInfo.nativeLibraryDir, size.first, size.second, refreshHz(), SessionState.fpsLimit,
|
||||
)
|
||||
if (SessionState.running && size != previous) {
|
||||
Log.i(TAG, "follow screen: ${previous.first}x${previous.second} -> ${size.first}x${size.second} on a new surface")
|
||||
WaylandCompositor.nativeResizeOutput(size.first, size.second)
|
||||
}
|
||||
if (!SessionState.running) SessionEvents.record("compositor.started")
|
||||
// The service owns everything below the compositor. It is started whenever no session is
|
||||
// running - NOT only when the compositor was just started: the compositor lives for the
|
||||
@@ -1060,51 +1049,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
if (resized) {
|
||||
Log.i(TAG, "surface resized to ${width}x$height - rebinding the compositor")
|
||||
CompositorHost.resize(holder.surface) { applyFrameGen() }
|
||||
followWindow(width, height)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Follow screen: the session's display takes the window's new size (a Fold opening onto its
|
||||
* inner panel, or closing onto the cover), so the picture fills the panel instead of being
|
||||
* letterboxed onto it. Not in picture-in-picture: that window is a preview of the session,
|
||||
* and resizing the guest to it would leave Steam laid out for a thumbnail.
|
||||
*/
|
||||
private fun followWindow(width: Int, height: Int) {
|
||||
if (!SessionState.followScreen || isInPictureInPictureMode || !CompositorHost.isStarted) return
|
||||
val size = com.droiddeck.launcher.session.SessionDisplay.followSize(width, height) ?: return
|
||||
if (size == SessionState.outputSize) return
|
||||
Log.i(TAG, "follow screen: ${SessionState.outputSize.first}x${SessionState.outputSize.second} -> ${size.first}x${size.second}")
|
||||
SessionState.outputSize = size
|
||||
val panel = panelBounds()
|
||||
SessionState.upscaleRatio = maxOf(panel.width(), panel.height()).toFloat() / maxOf(size.first, size.second).coerceAtLeast(1)
|
||||
WaylandCompositor.nativeResizeOutput(size.first, size.second)
|
||||
}
|
||||
|
||||
/** Whether this session's resolution is Follow screen; decided once, when it starts. */
|
||||
private fun followChoice(): Boolean {
|
||||
val mode = SessionPrefs.prefMode(intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM)
|
||||
return SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this)) ==
|
||||
com.droiddeck.launcher.session.SessionDisplay.FOLLOW_SCREEN
|
||||
}
|
||||
|
||||
/**
|
||||
* Follow screen on a large panel (a Fold's inner screen) may turn with the device: a window
|
||||
* locked to landscape on a squarer panel is letterboxed by the system itself, which no output
|
||||
* size can undo. A phone-sized panel (the cover screen) stays landscape as before.
|
||||
*/
|
||||
private fun applyFollowOrientation(config: android.content.res.Configuration) {
|
||||
if (!SessionState.followScreen) return
|
||||
val wanted = if (config.smallestScreenWidthDp >= 600) android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER
|
||||
else android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
|
||||
if (requestedOrientation != wanted) requestedOrientation = wanted
|
||||
}
|
||||
|
||||
override fun onConfigurationChanged(newConfig: android.content.res.Configuration) {
|
||||
super.onConfigurationChanged(newConfig)
|
||||
applyFollowOrientation(newConfig)
|
||||
}
|
||||
|
||||
override fun surfaceDestroyed(holder: SurfaceHolder) {
|
||||
surfaceW = 0
|
||||
surfaceH = 0
|
||||
@@ -1944,8 +1891,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
override fun onPictureInPictureModeChanged(inPip: Boolean, newConfig: android.content.res.Configuration) {
|
||||
super.onPictureInPictureModeChanged(inPip, newConfig)
|
||||
if (::pip.isInitialized) pip.changed(inPip)
|
||||
// The panel may have changed while the session was a thumbnail (folded or unfolded in PiP).
|
||||
if (!inPip && surfaceW > 0) followWindow(surfaceW, surfaceH)
|
||||
}
|
||||
|
||||
override fun startActivityForResult(intent: Intent, requestCode: Int, options: Bundle?) {
|
||||
@@ -2073,13 +2018,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
|
||||
or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
|
||||
or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)
|
||||
// ALWAYS from Android 11: SHORT_EDGES left a black strip along a camera on the long edge,
|
||||
// which is where a Fold's inner-screen camera sits with the device held in landscape.
|
||||
if (Build.VERSION.SDK_INT >= 28) {
|
||||
window.attributes = window.attributes.apply {
|
||||
layoutInDisplayCutoutMode = if (Build.VERSION.SDK_INT >= 30)
|
||||
WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS
|
||||
else WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
|
||||
layoutInDisplayCutoutMode =
|
||||
WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package com.droiddeck.launcher.agent
|
||||
|
||||
import com.droiddeck.launcher.session.SessionPaths
|
||||
import android.Manifest
|
||||
import android.content.ContentProvider
|
||||
import android.content.ContentValues
|
||||
@@ -108,7 +107,7 @@ class AgentBridgeProvider : ContentProvider() {
|
||||
|
||||
private fun state(context: Context): JSONObject {
|
||||
val runtimeVersion = LinuxRuntimeInstaller.installedVersion(context)
|
||||
val dir = SessionState.logDirectory ?: SessionState.logFile?.parentFile ?: SessionPaths.sessionFolders(context).lastOrNull()
|
||||
val dir = SessionState.logDirectory ?: SessionState.logFile?.parentFile ?: latestSessionDirectory()
|
||||
val session = JSONObject()
|
||||
.put("id", SessionState.sessionId ?: dir?.name ?: JSONObject.NULL)
|
||||
.put("phase", SessionState.phase.name)
|
||||
@@ -164,6 +163,12 @@ class AgentBridgeProvider : ContentProvider() {
|
||||
.put("session", session)
|
||||
}
|
||||
|
||||
private fun latestSessionDirectory(): File? {
|
||||
val parent = LinuxRuntime.debugLogDir()
|
||||
return parent.listFiles { file -> file.isDirectory && file.name.startsWith("session-") }
|
||||
?.maxWithOrNull(compareBy<File> { it.lastModified() }.thenBy { it.name })
|
||||
}
|
||||
|
||||
private fun stop(context: Context): JSONObject {
|
||||
if (SessionState.running) {
|
||||
SessionService.stop(context)
|
||||
|
||||
@@ -53,7 +53,7 @@ object DeviceReport {
|
||||
b.append("DroidDeck session report\n")
|
||||
b.append("========================\n")
|
||||
k("Written", SimpleDateFormat("yyyy-MM-dd HH:mm:ss zzz", Locale.US).format(Date()))
|
||||
k("Session mode", when (mode) { SessionService.MODE_DESKTOP -> "desktop (KDE Plasma)"; SessionService.MODE_RUN -> "a program under gamescope"; else -> "Steam client (gamescope)" })
|
||||
k("Session mode", when (mode) { SessionService.MODE_DESKTOP -> "desktop (labwc/LXQt)"; SessionService.MODE_RUN -> "a program under gamescope"; else -> "Steam client (gamescope)" })
|
||||
|
||||
h("App")
|
||||
runCatching {
|
||||
@@ -189,7 +189,7 @@ object DeviceReport {
|
||||
}
|
||||
for (name in listOf("droiddeck-tu-debug", "droiddeck-driver",
|
||||
"droiddeck-osc", "droiddeck-no-pad",
|
||||
"droiddeck-no-hud")) {
|
||||
"droiddeck-no-hud", "droiddeck-wlr-renderer")) {
|
||||
val f = File(Environment.getExternalStorageDirectory(), "Download/$name")
|
||||
if (f.isFile) k(name, FileUtils.readString(f)?.trim()?.replace('\n', ' ')?.ifEmpty { "(present, empty)" } ?: "(present)")
|
||||
}
|
||||
|
||||
@@ -75,24 +75,9 @@ object LogRedactor {
|
||||
* user who signs in with a plain account name, not an email, had it in every log. The single
|
||||
* space then a non-space keeps "OnLoginStateChange 0 1 0 0" (no account yet) as it is.
|
||||
*/
|
||||
private val LOGIN_STATE = Regex("(?i)(OnLoginStateChange:? )([^\\s<]\\S*)")
|
||||
private val LOGIN_STATE = Regex("(OnLoginStateChange )(\\S+)")
|
||||
private val LOGIN_USERS = Regex("(OnLoginUsersChanged )(\\S.*)$")
|
||||
|
||||
/**
|
||||
* An account name as a field: `AccountName`, `account_name`, `username` (`"AccountName"
|
||||
* "someone"` in a VDF, `account_name=...`, `"username": "..."`) and `login` - the last only
|
||||
* as `login=`, a quoted key or a VDF pair, so "Login: OnLoginStateChange ..." keeps its label.
|
||||
* A quoted value is blanked whole; one already blanked is left as it is.
|
||||
*/
|
||||
private const val ACCOUNT_VALUE = "(\"[^\"<\\r\\n]+\"|'[^'<\\r\\n]+'|[^\\s\"'<>&;,}]+)"
|
||||
private val ACCOUNT_KV = Regex(
|
||||
"(?i)(?<![A-Za-z0-9_])(account[_-]?name|user[_-]?name|epicusername)" +
|
||||
"([\"']?\\s*[=:]\\s*|[\"']\\s+)" + ACCOUNT_VALUE
|
||||
)
|
||||
private val LOGIN_KV = Regex(
|
||||
"(?i)(?<![A-Za-z0-9_])(login)(\\s*=\\s*|[\"']\\s*[=:]\\s*|[\"']\\s+)" + ACCOUNT_VALUE
|
||||
)
|
||||
|
||||
/** The device's Steam accounts and persona names as patterns (see [learnAccounts]). */
|
||||
@Volatile
|
||||
private var accounts: List<Regex> = emptyList()
|
||||
@@ -220,49 +205,13 @@ object LogRedactor {
|
||||
* only when that matches, so a folder scrubbed under older rules is scrubbed again on the way
|
||||
* out.
|
||||
*/
|
||||
const val RULES_VERSION = 3
|
||||
|
||||
/**
|
||||
* A private IPv4 address (10/8, 172.16/12, 192.168/16, link-local 169.254/16): the home
|
||||
* network's layout, e.g. its router as the resolver. Blanked in a shared zip only; public
|
||||
* server addresses stay. Not part of a longer dotted number (a version like 10.0.19041.1).
|
||||
*/
|
||||
private val LAN_IPV4 = Regex(
|
||||
"(?<![\\d.])(?:10\\.\\d{1,3}|192\\.168|172\\.(?:1[6-9]|2\\d|3[01])|169\\.254)\\.\\d{1,3}\\.\\d{1,3}(?!\\.?\\d)"
|
||||
)
|
||||
const val RULES_VERSION = 2
|
||||
|
||||
/** [src]'s lines, scrubbed, to [out]. */
|
||||
fun scrubTo(src: java.io.File, out: java.io.Writer) {
|
||||
src.forEachLine { line -> out.write(redact(line)); out.write("\n") }
|
||||
}
|
||||
|
||||
/**
|
||||
* The last pass for a file going into a shared zip: [redact], then the rules the stores' log
|
||||
* uses too ([SecretScrub]) - URLs without query, fragment and user:password and with any
|
||||
* token-bearing path segment blanked, token values and Authorization / Cookie headers blanked
|
||||
* - and private IPv4 addresses as `<lan-address>`. A line already clean comes out unchanged.
|
||||
*/
|
||||
fun redactForShare(line: String): String {
|
||||
if (line.isEmpty()) return line
|
||||
return try {
|
||||
val out = SecretScrub.scrub(redact(line), SecretScrub.Urls.KEEP_PATH, "<redacted:token>")
|
||||
LAN_IPV4.replace(out, "<lan-address>")
|
||||
} catch (t: Throwable) {
|
||||
"<redaction failed; line withheld>"
|
||||
}
|
||||
}
|
||||
|
||||
/** [src]'s lines through [redactForShare], to [out]: the pass every text file in a shared zip gets. */
|
||||
fun scrubForShare(src: java.io.File, out: java.io.Writer) {
|
||||
src.forEachLine { line -> out.write(redactForShare(line)); out.write("\n") }
|
||||
}
|
||||
|
||||
/** `<redacted:account>`, inside [value]'s quotes when it had them. */
|
||||
private fun quoted(value: String): String {
|
||||
val q = value.first().takeIf { it == '"' || it == '\'' }?.toString().orEmpty()
|
||||
return "$q<redacted:account>$q"
|
||||
}
|
||||
|
||||
/** [line] with every credential shape replaced. Null- and exception-safe by construction. */
|
||||
fun redact(line: String): String {
|
||||
if (line.isEmpty()) return line
|
||||
@@ -291,8 +240,6 @@ object LogRedactor {
|
||||
for (r in own) out = r.replace(out, "<redacted:ip>")
|
||||
out = LOGIN_STATE.replace(out) { "${it.groupValues[1]}<redacted:account>" }
|
||||
out = LOGIN_USERS.replace(out) { "${it.groupValues[1]}<redacted:account>" }
|
||||
out = ACCOUNT_KV.replace(out) { "${it.groupValues[1]}${it.groupValues[2]}${quoted(it.groupValues[3])}" }
|
||||
out = LOGIN_KV.replace(out) { "${it.groupValues[1]}${it.groupValues[2]}${quoted(it.groupValues[3])}" }
|
||||
for (r in accounts) out = r.replace(out, "<redacted:account>")
|
||||
out = EMAIL.replace(out, "<redacted:email>")
|
||||
out = RESIDUAL.replace(out) { "${it.groupValues[1]}=<redacted:token>" }
|
||||
|
||||
@@ -1,72 +0,0 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
/**
|
||||
* The one set of rules that keeps URLs and tokens out of anything the app writes or shares: the
|
||||
* stores' log ([com.droiddeck.launcher.stores.StoreLog.redactLine]) and the last pass over every
|
||||
* text file in a shared log zip ([LogRedactor.redactForShare]).
|
||||
*
|
||||
* - Every URL loses its query, fragment and `user:password@`. [Urls.SHORT] then keeps only the host
|
||||
* and a plain first path segment (the stores' lines, where a GOG secure link carries its token in
|
||||
* the path); [Urls.KEEP_PATH] keeps the path but blanks any segment that carries a token.
|
||||
* - Outside URLs, the values of token-like keys (`token`, `__token__`, `f_token`, `hdnts`, access /
|
||||
* refresh / id tokens; exchange and authorization codes of four characters or more, and a bare
|
||||
* `code=` where it is one: in a query string or on a line with OAuth keys such as `client_id`,
|
||||
* `redirect_uri` or `state`, never an 8-hex exception code like Proton's `code=c0000005`) and of
|
||||
* Authorization / Cookie headers are blanked with [mark].
|
||||
*
|
||||
* A line already scrubbed comes out unchanged.
|
||||
*/
|
||||
object SecretScrub {
|
||||
enum class Urls { SHORT, KEEP_PATH }
|
||||
|
||||
private val URL = Regex("""[A-Za-z][A-Za-z0-9+.\-]*://[^\s"'<>]+""")
|
||||
private val SAFE_SEGMENT = Regex("""[A-Za-z0-9._\-]{1,40}""")
|
||||
private val TOKEN_SEGMENT = Regex("""(?i)(token|hdnts|hmac|signature|sig|exp)=""")
|
||||
private val TOKEN = Regex("""(?i)(?<![A-Za-z0-9_])(__token__|f_token|hdnts|access_token|refresh_token|id_token|token)(["']?\s*[=:]\s*["']?)[^\s&;,"'<>}]+""")
|
||||
/** Codes that are only ever OAuth grants. */
|
||||
private val GRANT_CODE = Regex("""(?i)(?<![A-Za-z0-9_])(exchange_code|authorization_?code)(["']?\s*=\s*["']?)[^\s&;,"'<>}]{4,}""")
|
||||
/** A bare `code=`: a grant only right after `?` / `&` (a query string) or beside OAuth keys ([OAUTH_CONTEXT]). */
|
||||
private val CODE = Regex("""(?i)(?<![A-Za-z0-9_])(code)(["']?\s*=\s*["']?)([^\s&;,"'<>}]{4,})""")
|
||||
private val OAUTH_CONTEXT = Regex("""(?i)(?<![A-Za-z0-9_])(client_id|client_secret|redirect_uri|state|grant_type|response_type|access_token|refresh_token|id_token)["']?\s*[=:]""")
|
||||
/** A Windows exception or status code (`code=c0000005`, `code=0x80000003`): never a grant. */
|
||||
private val STATUS_CODE = Regex("""(?i)(0x)?[0-9a-f]{8}""")
|
||||
private val HEADER = Regex("""(?i)\b(authorization|cookie|set-cookie)(\s*[:=]\s*).+""")
|
||||
|
||||
fun scrub(text: String, urls: Urls, mark: String): String {
|
||||
var out = URL.replace(text) { m -> if (urls == Urls.SHORT) short(m.value) else keepPath(m.value, mark) }
|
||||
out = TOKEN.replace(out) { m -> m.groupValues[1] + m.groupValues[2] + mark }
|
||||
out = GRANT_CODE.replace(out) { m -> m.groupValues[1] + m.groupValues[2] + mark }
|
||||
val oauth = OAUTH_CONTEXT.containsMatchIn(text)
|
||||
val src = out
|
||||
out = CODE.replace(src) { m ->
|
||||
val inQuery = m.range.first > 0 && src[m.range.first - 1] in "?&"
|
||||
val grant = !STATUS_CODE.matches(m.groupValues[3]) && (oauth || inQuery)
|
||||
if (grant) m.groupValues[1] + m.groupValues[2] + mark else m.value
|
||||
}
|
||||
out = HEADER.replace(out) { m -> m.groupValues[1] + m.groupValues[2] + mark }
|
||||
return out
|
||||
}
|
||||
|
||||
private fun split(url: String): Triple<String, String, String?> {
|
||||
val schemeEnd = url.indexOf("://")
|
||||
val rest = url.substring(schemeEnd + 3).substringBefore('#').substringBefore('?')
|
||||
val slash = rest.indexOf('/')
|
||||
val authority = (if (slash >= 0) rest.substring(0, slash) else rest).substringAfterLast('@')
|
||||
return Triple(url.substring(0, schemeEnd), authority, if (slash >= 0) rest.substring(slash + 1) else null)
|
||||
}
|
||||
|
||||
private fun short(url: String): String {
|
||||
val (scheme, authority, path) = split(url)
|
||||
if (path == null) return "$scheme://$authority"
|
||||
val first = path.substringBefore('/')
|
||||
if (first.isEmpty()) return "$scheme://$authority/"
|
||||
val shown = if (SAFE_SEGMENT.matches(first)) first else "…"
|
||||
return "$scheme://$authority/$shown" + if (path.length > first.length && shown != "…") "/…" else ""
|
||||
}
|
||||
|
||||
private fun keepPath(url: String, mark: String): String {
|
||||
val (scheme, authority, path) = split(url)
|
||||
val clean = path?.split('/')?.joinToString("/") { seg -> if (TOKEN_SEGMENT.containsMatchIn(seg)) mark else seg }
|
||||
return "$scheme://$authority" + (clean?.let { "/$it" } ?: "")
|
||||
}
|
||||
}
|
||||
@@ -1020,8 +1020,7 @@ fun FileManagerScreen(
|
||||
// The ROMs folder chosen on the main screen: what the session shows as /root/ROMs.
|
||||
SessionPrefs.romsDir(context).takeIf { it.isNotEmpty() }?.let(::File)?.takeIf { it.isDirectory }
|
||||
?.let { add(locItem(stringResource(R.string.fm_rail_roms), Icons.Filled.SportsEsports, it)) }
|
||||
// The app's own logs folder: private, which this file manager (the app itself) can read.
|
||||
com.droiddeck.launcher.runtime.LinuxRuntime.logDir(context).takeIf { it.isDirectory }?.let { add(locItem(stringResource(R.string.fm_rail_session_logs), Icons.Filled.Description, it)) }
|
||||
File("/storage/emulated/0/Download/DroidDeck").takeIf { it.isDirectory }?.let { add(locItem(stringResource(R.string.fm_rail_session_logs), Icons.Filled.Description, it)) }
|
||||
File("/storage/emulated/0/Pictures").takeIf { it.isDirectory }?.let { add(locItem(stringResource(R.string.fm_rail_pictures), Icons.Filled.Image, it)) }
|
||||
}
|
||||
val favItems = remember(favTick) { FavoritesStore.list(context).map(::File).filter { it.exists() } }
|
||||
|
||||
@@ -25,7 +25,7 @@ import java.util.zip.ZipInputStream;
|
||||
/**
|
||||
* Imported LINUX Vulkan drivers: glibc Turnip ICDs ({@code Turnip-<tag>[-variant]-Linux.zip} from
|
||||
* Banners-Turnip) for the runtime - the gamescope session that runs Valve's native ARM64 Steam
|
||||
* client, and the KDE Plasma desktop beside it. This is the driver that DRAWS there: the client's own UI
|
||||
* client, and the labwc desktop beside it. This is the driver that DRAWS there: the client's own UI
|
||||
* (OpenGL through the runtime's Zink), every game the client launches (D3D through Proton's
|
||||
* DXVK/VKD3D) and everything on the desktop. Putting the frame on the screen stays the Android
|
||||
* driver's job, in the app's compositor ({@link TurnipDriver}).
|
||||
|
||||
@@ -242,7 +242,7 @@ object AppImageManager {
|
||||
|
||||
private fun menuEntry(context: Context, id: String) =
|
||||
// A system directory, not ~/.local/share/applications: the desktop copies game entries from
|
||||
// here into the user's with a GPU launcher (droiddeck-desktop-gpu), since it composites in software.
|
||||
// here into the user's with a GPU launcher (droiddeck-desktop-gpu) while it runs on pixman.
|
||||
File(LinuxRuntime.rootDir(context), "usr/local/share/applications/droiddeck-appimage-$id.desktop")
|
||||
|
||||
/** The Linux desktop's menu entry: the desktop's own Exec rules (and droiddeck-gpu) apply to it. */
|
||||
|
||||
@@ -232,10 +232,10 @@ object BwrapSpawner {
|
||||
val driver = File(lib, "libvulkan_freedreno.so")
|
||||
if (!driver.isFile || !File("/dev/kgsl-3d0").exists()) return null
|
||||
if (env.containsKey("VK_ICD_FILENAMES") || env.containsKey("VK_DRIVER_FILES")) return null
|
||||
// A window on the desktop gets shared-memory buffers only (KWin composites in software);
|
||||
// Zink cannot present there, so such an app keeps Flathub's own Mesa (llvmpipe). From the
|
||||
// desktop, games go through droiddeck-gpu's gamescope and do get the GPU.
|
||||
if (env["BL_DESKTOP"] == "1" && env["GAMESCOPE_WAYLAND_DISPLAY"] == null) return null
|
||||
// A window on the desktop while labwc composites with pixman gets shared-memory buffers
|
||||
// only; Zink cannot present there, so such an app keeps Flathub's own Mesa (llvmpipe).
|
||||
// From the desktop, games go through droiddeck-gpu's gamescope and do get the GPU.
|
||||
if (env["WLR_RENDERER"] == "pixman" && env["GAMESCOPE_WAYLAND_DISPLAY"] == null) return null
|
||||
val binds = ArrayList<Bind>()
|
||||
for (name in listOf("libvulkan_freedreno.so", "libdisplay-info.so.3", "libSPIRV-Tools.so", "libSPIRV-Tools-opt.so")) {
|
||||
val f = File(lib, name)
|
||||
|
||||
@@ -3,7 +3,6 @@ package com.droiddeck.launcher.runtime
|
||||
import com.droiddeck.launcher.core.Hashes
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.BuildConfig
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.core.Downloader
|
||||
import com.droiddeck.launcher.core.FileUtils
|
||||
@@ -75,32 +74,10 @@ object DesktopCatalog {
|
||||
installed(context, PROTON_SEED_ID) == null &&
|
||||
!File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/steamapps/appmanifest_4427310.acf").isFile
|
||||
|
||||
/**
|
||||
* The desktop: KDE Plasma (tools/desktop-kde). It replaced an LXQt/labwc package of id
|
||||
* "desktop", which a runtime may still carry; that one does not count, so the first desktop
|
||||
* after the update installs this one over it.
|
||||
*/
|
||||
const val DESKTOP_ID = "desktop-kde"
|
||||
|
||||
/**
|
||||
* The desktop package this apk installs: pinned in tools/desktop-kde/release.env and published
|
||||
* in DroidDeck-Components, not read from the catalog, so the desktop scripts staged by this
|
||||
* apk always get the package they were made for.
|
||||
*/
|
||||
fun desktopEntry(context: Context) = Entry(
|
||||
DESKTOP_ID, context.getString(R.string.content_linux_desktop), 1, BuildConfig.DESKTOP_KDE_TAG, "tar",
|
||||
BuildConfig.DESKTOP_KDE_URL, BuildConfig.DESKTOP_KDE_SHA256, BuildConfig.DESKTOP_KDE_SIZE, "",
|
||||
"", "",
|
||||
)
|
||||
|
||||
// The desktop package installed to the end: KWin is there and the marker install() writes once
|
||||
// the whole package is extracted. An install cut short (the app killed, storage full) leaves
|
||||
// KWin without the marker, and the next desktop installs it again. The launcher is staged by
|
||||
// the app at every session, so it cannot tell. SessionFiles uses the same test.
|
||||
fun desktopInstalled(context: Context): Boolean = desktopInstalled(LinuxRuntime.rootDir(context))
|
||||
|
||||
fun desktopInstalled(root: File): Boolean =
|
||||
File(root, "usr/bin/kwin_wayland").isFile && File(root, ".droiddeck-pkg-$DESKTOP_ID").isFile
|
||||
// labwc comes with the hosted desktop package itself (its launcher is staged by the app at
|
||||
// every session, so it cannot tell whether the package is there); SessionFiles uses the same test.
|
||||
fun desktopInstalled(context: Context): Boolean =
|
||||
File(LinuxRuntime.rootDir(context), "usr/bin/labwc").isFile
|
||||
|
||||
/** Downloads, verifies and installs one package. Returns null on success, else a message. */
|
||||
fun install(context: Context, entry: Entry, listener: LinuxRuntimeInstaller.ProgressListener?): String? {
|
||||
@@ -134,12 +111,7 @@ object DesktopCatalog {
|
||||
"Exec=env APPIMAGE_EXTRACT_AND_RUN=1 /opt/appimages/${entry.id}.AppImage\n" +
|
||||
"Icon=${entry.icon}\nTerminal=false\nCategories=${entry.category};\n")
|
||||
}
|
||||
else -> {
|
||||
// Not complete until written again at the end: a reinstall cut short must not
|
||||
// leave the last install's marker saying it is.
|
||||
marker(context, entry.id).delete()
|
||||
if (!LinuxRuntimeInstaller.extract(context, download, root, listener)) return context.getString(R.string.deskpkg_extract_failed)
|
||||
}
|
||||
else -> if (!LinuxRuntimeInstaller.extract(context, download, root, listener)) return context.getString(R.string.deskpkg_extract_failed)
|
||||
}
|
||||
FileUtils.writeString(marker(context, entry.id), entry.version)
|
||||
return null
|
||||
|
||||
@@ -87,7 +87,7 @@ object FlatpakManager {
|
||||
?.maxByOrNull { it.first }?.second
|
||||
}
|
||||
|
||||
/** Runs [argv] in the runtime, its output also in files/logs/tools/flatpak-<verb>.log. */
|
||||
/** Runs [argv] in the runtime, its output also in Download/DroidDeck/flatpak-<verb>.log. */
|
||||
private fun runGuest(context: Context, argv: List<String>, fakeRoot: Boolean, onLine: (String) -> Unit): Int {
|
||||
val name = "flatpak-" + (argv.getOrNull(2)?.takeIf { argv.getOrNull(1) == HELPER } ?: "setup")
|
||||
return GuestCommand.run(context, argv, fakeRoot, name, onLine = onLine)
|
||||
|
||||
@@ -17,7 +17,7 @@ object GuestCommand {
|
||||
/**
|
||||
* Runs [argv] and hands each output line to [onLine]; returns the exit status. [fakeRoot] is
|
||||
* for the package tools, which refuse any uid but 0. With [logName], everything the command
|
||||
* says also goes to files/logs/tools/<logName>.log beside the session logs, so a problem can
|
||||
* says also goes to Download/DroidDeck/tools/<logName>.log beside the session logs, so a problem can
|
||||
* be handed over like a session's. With [linkDir], hard links (which Android denies apps)
|
||||
* become symlinks to files proot keeps there (its link2symlink).
|
||||
*/
|
||||
@@ -25,7 +25,7 @@ object GuestCommand {
|
||||
linkDir: File? = null, onLine: (String) -> Unit): Int {
|
||||
val log = logName?.let {
|
||||
try {
|
||||
File(File(LinuxRuntime.logDir(context), SessionPaths.TOOLS_DIR).apply { mkdirs() }, "$it.log").printWriter()
|
||||
File(File(LinuxRuntime.debugLogDir(), SessionPaths.TOOLS_DIR).apply { mkdirs() }, "$it.log").printWriter()
|
||||
} catch (e: Exception) { null }
|
||||
}
|
||||
log?.println("== ${java.util.Date()} ${argv.joinToString(" ")}")
|
||||
|
||||
@@ -44,20 +44,10 @@ public final class LinuxRuntime {
|
||||
public static final String GUEST_RUNTIME_DIR = "/run/droiddeck";
|
||||
private static final String SYSTEM_FONTS = "/system/fonts";
|
||||
private static final String GUEST_SYSTEM_FONTS = "/usr/local/share/fonts/android";
|
||||
/** The folder under Downloads where builds before private logs wrote them; read only to move them. */
|
||||
/** Where every Linux session's debug log lands: public, so a user can just hand the folder over. */
|
||||
public static final String DEBUG_LOG_DIR = "DroidDeck";
|
||||
|
||||
/**
|
||||
* Where every log lands: app-private, {@code files/logs}. Session folders, tools/ (one-off
|
||||
* commands) and stores/ sit under it; the files directory is bound into every session at the
|
||||
* same path, so the guest writes there too. Share logs is how a folder leaves the device.
|
||||
*/
|
||||
public static File logDir(Context context) {
|
||||
return new File(context.getFilesDir(), "logs");
|
||||
}
|
||||
|
||||
/** {@code Download/DroidDeck}, where earlier builds wrote logs. Only LogMigration reads it. */
|
||||
public static File legacyLogDir() {
|
||||
public static File debugLogDir() {
|
||||
return new File(android.os.Environment.getExternalStoragePublicDirectory(
|
||||
android.os.Environment.DIRECTORY_DOWNLOADS), DEBUG_LOG_DIR);
|
||||
}
|
||||
|
||||
@@ -227,8 +227,7 @@ public final class LinuxRuntimeInstaller {
|
||||
// Its quarantined home is not user data to carry into an update.
|
||||
File pendingRemoval = removalDirectory(LinuxRuntime.rootDir(context));
|
||||
if (pendingRemoval.exists() && listener != null) listener.onProgress(context.getString(R.string.rtinst_removing_leftovers), -1);
|
||||
if (!discard(pendingRemoval, null)) throw new IOException("Cannot clear the previous runtime: " + pendingRemoval);
|
||||
emptyTrash(LinuxRuntime.rootDir(context).getParentFile());
|
||||
RuntimeFileTree.delete(pendingRemoval, null);
|
||||
String downloading = context.getString(R.string.rtinst_downloading);
|
||||
if (listener != null) listener.onProgress(Step.DOWNLOADING, downloading, 0);
|
||||
// Downloader reports a 0..1 fraction, or -1 while the total size is unknown.
|
||||
@@ -256,7 +255,8 @@ public final class LinuxRuntimeInstaller {
|
||||
File staging = new File(root.getParentFile(), LinuxRuntime.DIR + ".new");
|
||||
File old = new File(root.getParentFile(), LinuxRuntime.DIR + ".old");
|
||||
recoverInterruptedSwap(root, staging, old);
|
||||
if (!discard(staging, null) || !staging.mkdirs()) return false;
|
||||
RuntimeFileTree.delete(staging, null);
|
||||
if (!staging.mkdirs()) return false;
|
||||
if (listener != null) listener.onProgress(context.getString(R.string.rtinst_extracting), -1);
|
||||
if (!extract(context, archive, staging, listener)) {
|
||||
RuntimeFileTree.delete(staging, null);
|
||||
@@ -264,10 +264,7 @@ public final class LinuxRuntimeInstaller {
|
||||
}
|
||||
FileUtils.writeString(new File(staging, VERSION_FILE), release.version);
|
||||
|
||||
if (!discard(old, null)) {
|
||||
discard(staging, null);
|
||||
return false;
|
||||
}
|
||||
RuntimeFileTree.delete(old, null);
|
||||
if (root.isDirectory() && !root.renameTo(old)) {
|
||||
RuntimeFileTree.delete(staging, null);
|
||||
return false;
|
||||
@@ -295,7 +292,7 @@ public final class LinuxRuntimeInstaller {
|
||||
if (old.isDirectory()) old.renameTo(root);
|
||||
return false;
|
||||
}
|
||||
discard(old, null);
|
||||
RuntimeFileTree.delete(old, null);
|
||||
return LinuxRuntime.isInstalled(context);
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "install", e);
|
||||
@@ -318,35 +315,6 @@ public final class LinuxRuntimeInstaller {
|
||||
}
|
||||
}
|
||||
|
||||
/** Where entries the app cannot unlink are set aside, out of the way of the runtime's names. */
|
||||
static final String TRASH = ".runtime-trash";
|
||||
|
||||
/**
|
||||
* Gets {@code tree} out from under its name. What can be deleted is; if something inside
|
||||
* cannot be (a file made by root or {@code su} carries another SELinux category, and the app
|
||||
* may not unlink it), the remainder is moved aside into {@link #TRASH} instead of blocking
|
||||
* every later install and removal on it. False only when even that move is refused.
|
||||
*/
|
||||
static boolean discard(File tree, java.util.function.LongConsumer progress) {
|
||||
if (RuntimeFileTree.deleteWhatCan(tree, progress)) return true;
|
||||
File trash = new File(tree.getParentFile(), TRASH);
|
||||
trash.mkdirs();
|
||||
File aside = new File(trash, tree.getName() + "-" + System.currentTimeMillis());
|
||||
if (tree.renameTo(aside)) {
|
||||
Log.w(TAG, "could not delete all of " + tree + "; set the rest aside in " + aside);
|
||||
return true;
|
||||
}
|
||||
Log.w(TAG, "could not delete or set aside " + tree);
|
||||
return !tree.exists();
|
||||
}
|
||||
|
||||
/** Another try at what {@link #discard} set aside. Whatever still cannot go stays there. */
|
||||
static void emptyTrash(File parent) {
|
||||
File trash = new File(parent, TRASH);
|
||||
if (trash.exists() && !RuntimeFileTree.deleteWhatCan(trash, null))
|
||||
Log.i(TAG, "some runtime leftovers still cannot be deleted: " + trash);
|
||||
}
|
||||
|
||||
private static boolean isEmptyDir(File dir) {
|
||||
String[] names = dir.list();
|
||||
return dir.isDirectory() && names != null && names.length == 0;
|
||||
@@ -401,21 +369,15 @@ public final class LinuxRuntimeInstaller {
|
||||
// Invalidate the installation before traversing it. A process killed halfway
|
||||
// through leaves a named removal to resume, never a launchable partial runtime.
|
||||
if (root.exists()) {
|
||||
if (!discard(pending, progress) || !root.renameTo(pending))
|
||||
throw new IOException("Cannot prepare the runtime for removal");
|
||||
RuntimeFileTree.delete(pending, progress);
|
||||
if (!root.renameTo(pending)) throw new IOException("Cannot prepare the runtime for removal");
|
||||
} else if (!pending.isDirectory() && !pending.mkdirs()) {
|
||||
throw new IOException("Cannot prepare the runtime for removal");
|
||||
}
|
||||
// Keep the quarantine until all leftovers are gone, so a failure stays retryable.
|
||||
// An entry the app may not delete is set aside rather than failing the removal:
|
||||
// a quarantine that can never clear would block reinstalling for good.
|
||||
for (File leftover : new File[]{
|
||||
new File(root.getParentFile(), root.getName() + ".new"),
|
||||
new File(root.getParentFile(), root.getName() + ".old"),
|
||||
pending}) {
|
||||
if (!discard(leftover, progress)) throw new IOException("Cannot remove " + leftover);
|
||||
}
|
||||
emptyTrash(root.getParentFile());
|
||||
RuntimeFileTree.delete(new File(root.getParentFile(), root.getName() + ".new"), progress);
|
||||
RuntimeFileTree.delete(new File(root.getParentFile(), root.getName() + ".old"), progress);
|
||||
RuntimeFileTree.delete(pending, progress);
|
||||
job.ok = true;
|
||||
report(text(app, R.string.rtinst_removed), 100);
|
||||
return true;
|
||||
|
||||
@@ -24,15 +24,8 @@ object ProotFastPath {
|
||||
/** MAX_BINDS in fastpath.c: past it the library turns itself off, so the session keeps it off. */
|
||||
const val MAX_BINDS = 256
|
||||
|
||||
/**
|
||||
* Only the app's own proot (libproot.so, built with patches/0014) lets the trampoline through.
|
||||
* The runtime's fallback copy (LinuxRuntime.prootBinary) is Termux's, which traps those calls
|
||||
* too and translates their host paths a second time: every lookup then fails inside the
|
||||
* process and goes to proot anyway, paying for both.
|
||||
*/
|
||||
fun enabled(context: Context): Boolean =
|
||||
SessionPrefs.prootFastPath(context) && !SessionPrefs.prootNoSeccomp(context) &&
|
||||
LinuxRuntime.prootBinary(context).parent == context.applicationInfo.nativeLibraryDir
|
||||
SessionPrefs.prootFastPath(context) && !SessionPrefs.prootNoSeccomp(context)
|
||||
|
||||
/** The key for this rootfs and these binds, or null when the library cannot be told them. */
|
||||
fun key(root: File, binds: List<String>): String? {
|
||||
|
||||
@@ -2,7 +2,6 @@ package com.droiddeck.launcher.runtime;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.AccessDeniedException;
|
||||
import java.nio.file.DirectoryStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.LinkOption;
|
||||
@@ -10,15 +9,11 @@ import java.nio.file.NoSuchFileException;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.attribute.BasicFileAttributes;
|
||||
import java.util.function.LongConsumer;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
/** Checked removal of an app-owned runtime tree, including read-only directories. */
|
||||
final class RuntimeFileTree {
|
||||
private RuntimeFileTree() {}
|
||||
|
||||
/** Unit tests stand in for an entry the app cannot unlink (a file another SELinux user made). */
|
||||
static volatile Predicate<Path> refuseForTest;
|
||||
|
||||
static void delete(File root, LongConsumer progress) throws IOException {
|
||||
delete(root.toPath(), progress, new long[]{0});
|
||||
}
|
||||
@@ -35,46 +30,8 @@ final class RuntimeFileTree {
|
||||
for (Path child : children) delete(child, progress, removed);
|
||||
}
|
||||
}
|
||||
unlink(path);
|
||||
if (progress != null) progress.accept(++removed[0]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes what it can of {@code root} and carries on past entries it cannot, rather than
|
||||
* stopping at the first. Returns true when nothing is left.
|
||||
*/
|
||||
static boolean deleteWhatCan(File root, LongConsumer progress) {
|
||||
return deleteWhatCan(root.toPath(), progress, new long[]{0});
|
||||
}
|
||||
|
||||
private static boolean deleteWhatCan(Path path, LongConsumer progress, long[] removed) {
|
||||
BasicFileAttributes attrs;
|
||||
try { attrs = Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); }
|
||||
catch (NoSuchFileException e) { return true; }
|
||||
catch (IOException e) { return false; }
|
||||
boolean emptied = true;
|
||||
if (attrs.isDirectory()) {
|
||||
try {
|
||||
makeWritable(path.toFile());
|
||||
try (DirectoryStream<Path> children = Files.newDirectoryStream(path)) {
|
||||
for (Path child : children) emptied &= deleteWhatCan(child, progress, removed);
|
||||
}
|
||||
} catch (IOException | RuntimeException e) {
|
||||
emptied = false;
|
||||
}
|
||||
}
|
||||
if (!emptied) return false;
|
||||
try { unlink(path); }
|
||||
catch (NoSuchFileException e) { return true; }
|
||||
catch (IOException e) { return false; }
|
||||
if (progress != null) progress.accept(++removed[0]);
|
||||
return true;
|
||||
}
|
||||
|
||||
private static void unlink(Path path) throws IOException {
|
||||
Predicate<Path> refuse = refuseForTest;
|
||||
if (refuse != null && refuse.test(path)) throw new AccessDeniedException(path.toString());
|
||||
Files.delete(path);
|
||||
if (progress != null) progress.accept(++removed[0]);
|
||||
}
|
||||
|
||||
private static void makeWritable(File dir) throws IOException {
|
||||
|
||||
@@ -1,73 +0,0 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.FileUtils
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* Once, on the first start of a build with private logs: the session folders, tools/ and the loose
|
||||
* tool logs that earlier builds left in `Download/DroidDeck/` move into `files/logs/`. Best effort:
|
||||
* an item that cannot be moved stays where it is. Moved session folders lose their old scrub markers
|
||||
* ([SessionArtifacts.unmarkMoved]), so [SessionArtifacts.scrubOlder] scrubs them under the current rules. Nothing else in that folder is touched - game
|
||||
* save backups (Saves/) stay public - and after this pass the app never reads it again.
|
||||
*/
|
||||
object LogMigration {
|
||||
private const val TAG = "LogMigration"
|
||||
private const val MARKER = ".moved-from-downloads"
|
||||
|
||||
@Synchronized
|
||||
fun run(context: Context) {
|
||||
val target = LinuxRuntime.logDir(context).apply { mkdirs() }
|
||||
val marker = File(target, MARKER)
|
||||
if (marker.exists()) return
|
||||
val legacy = LinuxRuntime.legacyLogDir()
|
||||
val items = if (legacy.isDirectory) legacy.listFiles() else emptyArray()
|
||||
// Unreadable (no storage access yet): try again next start rather than give up on them.
|
||||
if (items == null) { Log.w(TAG, "$legacy cannot be listed; logs there stay until it can"); return }
|
||||
var moved = 0
|
||||
val movedFolders = ArrayList<File>()
|
||||
for (f in items) {
|
||||
val isLog = SessionPaths.isSessionFolder(f) ||
|
||||
(f.isDirectory && f.name == SessionPaths.TOOLS_DIR) ||
|
||||
(f.isFile && f.name.endsWith(".log"))
|
||||
if (!isLog) continue
|
||||
val dest = File(if (f.isFile) File(target, SessionPaths.TOOLS_DIR).apply { mkdirs() } else target, f.name)
|
||||
if (dest.exists() && f.name != SessionPaths.TOOLS_DIR) continue
|
||||
if (move(f, dest)) {
|
||||
moved++
|
||||
if (SessionPaths.isSessionFolder(dest)) movedFolders.add(dest)
|
||||
} else Log.w(TAG, "could not move ${f.name}; left in place")
|
||||
}
|
||||
// Earlier builds scrubbed these under older rules (or not at all) and marked them done:
|
||||
// without their markers, the pass over older folders that follows at the same start puts
|
||||
// them through the current redactor.
|
||||
SessionArtifacts.unmarkMoved(movedFolders)
|
||||
try { marker.writeText("moved $moved item(s)\n") } catch (e: Exception) { Log.w(TAG, "could not mark the move: ${e.message}") }
|
||||
if (moved > 0) Log.i(TAG, "moved $moved log item(s) from $legacy into $target")
|
||||
}
|
||||
|
||||
/** A rename where it works (same volume), else a copy then the source's removal; false = left as it was. */
|
||||
private fun move(src: File, dest: File): Boolean {
|
||||
if (src.renameTo(dest)) return true
|
||||
return try {
|
||||
copy(src, dest)
|
||||
FileUtils.delete(src)
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "copy of ${src.name} failed: ${e.message}")
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
private fun copy(src: File, dest: File) {
|
||||
if (src.isDirectory) {
|
||||
dest.mkdirs()
|
||||
src.listFiles()?.forEach { copy(it, File(dest, it.name)) }
|
||||
} else {
|
||||
dest.parentFile?.mkdirs()
|
||||
src.inputStream().use { input -> dest.outputStream().use { input.copyTo(it) } }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -31,20 +31,16 @@ object SessionArtifacts {
|
||||
/** Written last; a folder without it did not get its ending. */
|
||||
const val COMPLETE_MARKER = ".complete"
|
||||
|
||||
/**
|
||||
* Every file in the folder has been through the redactor under its current rules. Named after
|
||||
* [LogRedactor.RULES_VERSION], so a folder scrubbed under older rules is scrubbed again.
|
||||
*/
|
||||
private val SCRUBBED_MARKER = ".scrubbed-r${LogRedactor.RULES_VERSION}"
|
||||
private val OLD_SCRUBBED_MARKER = Regex("""\.scrubbed-(r?\d+)""")
|
||||
/** Every file in the folder has been through the redactor, own addresses and accounts included (-2: accounts added). */
|
||||
private const val SCRUBBED_MARKER = ".scrubbed-2"
|
||||
|
||||
/**
|
||||
* Written by a session's own ending, and only when every file in the folder, subfolders
|
||||
* included (whatever the session script copied into steam/ and droiddeck-esync/ as well as what
|
||||
* the app wrote), went through the redactor without a failure. It lists each of those files
|
||||
* with its size and modification time, under the redactor's rules version ([scrubbedFiles]).
|
||||
* A share no longer relies on it: every text file goes through the share pass on the way into
|
||||
* the zip regardless.
|
||||
* with its size and modification time, under the redactor's rules version: a share copies a
|
||||
* file as it is only when all three still match ([scrubbedFiles]), and scrubs anything else -
|
||||
* a file added or changed since, a hidden one, or every file of a folder without it.
|
||||
*/
|
||||
const val SCRUBBED_TREE_MARKER = ".scrubbed-tree"
|
||||
|
||||
@@ -71,48 +67,24 @@ object SessionArtifacts {
|
||||
}
|
||||
|
||||
/**
|
||||
* Every session folder not yet scrubbed under the redactor's current rules - written before
|
||||
* every file was scrubbed, before the device's own addresses or the Steam account were, or
|
||||
* moved in from Download/ ([LogMigration] strips their markers first, [unmarkMoved]): the
|
||||
* whole folder, steam/ and every other subfolder included, through the redactor, and the
|
||||
* current marker written in place of the old ones. Runs at app start with [finishAbandoned].
|
||||
*
|
||||
* A folder holds some 30 MB of Steam logs, about half a minute's work, so folders go through
|
||||
* a few at a time; one the process does not get to keeps its old marker and is taken up at
|
||||
* the next start.
|
||||
* Once, for session folders written before every file was scrubbed and before the device's own
|
||||
* addresses were (network.txt listed them; the client's IPv6 check logs "external address"
|
||||
* into steam/connection_log.txt): the whole folder, steam/ included, through the redactor.
|
||||
* A marker records it. Runs at app start with [finishAbandoned].
|
||||
*/
|
||||
@Synchronized
|
||||
fun scrubOlder(context: Context) {
|
||||
val current = SessionPaths.current()
|
||||
val dirs = LinuxRuntime.logDir(context).listFiles { f ->
|
||||
val dirs = LinuxRuntime.debugLogDir().listFiles { f ->
|
||||
SessionPaths.isSessionFolder(f) && f != current && !File(f, SCRUBBED_MARKER).exists()
|
||||
}?.toList() ?: return
|
||||
} ?: return
|
||||
if (dirs.isEmpty()) return
|
||||
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
|
||||
val workers = (Runtime.getRuntime().availableProcessors() / 2).coerceIn(1, 4)
|
||||
val pool = java.util.concurrent.Executors.newFixedThreadPool(workers) { r ->
|
||||
Thread({ android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND); r.run() }, "scrub-logs")
|
||||
}
|
||||
val done = try {
|
||||
pool.invokeAll(dirs.map { dir -> java.util.concurrent.Callable { scrubAndMark(dir) } })
|
||||
.count { f -> try { f.get() } catch (e: Exception) { false } }
|
||||
} finally {
|
||||
pool.shutdown()
|
||||
}
|
||||
val failed = dirs.size - done
|
||||
Log.i(TAG, "logs: scrubbed $done folders under r${LogRedactor.RULES_VERSION}" +
|
||||
if (failed > 0) ", $failed not fully (again at the next start)" else "")
|
||||
}
|
||||
|
||||
/**
|
||||
* Folders [LogMigration] just moved in lose every scrub marker an earlier build left, so
|
||||
* [scrubOlder], which runs right after it, puts them through the current rules whatever those
|
||||
* markers claimed.
|
||||
*/
|
||||
fun unmarkMoved(dirs: List<File>) {
|
||||
dirs.filter { SessionPaths.isSessionFolder(it) }.forEach { dir ->
|
||||
dir.listFiles { f -> OLD_SCRUBBED_MARKER.matches(f.name) || f.name == SCRUBBED_TREE_MARKER }?.forEach { it.delete() }
|
||||
dirs.forEach { dir ->
|
||||
Record(dir).let { r -> scrubFolder(dir, r); File(dir, "steam").takeIf { it.isDirectory }?.let { scrubFolder(it, r) } }
|
||||
try { File(dir, SCRUBBED_MARKER).writeText("scrubbed ${now()}\n") } catch (e: Exception) {}
|
||||
}
|
||||
Log.i(TAG, "scrubbed ${dirs.size} older session folder(s)")
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -171,17 +143,15 @@ object SessionArtifacts {
|
||||
* Records [record]'s folder as scrubbed - every file went through without a failure - or
|
||||
* leaves it unmarked, so the next share and the pass over older folders scrub it again.
|
||||
*/
|
||||
private fun markScrubbed(record: Record): Boolean {
|
||||
private fun markScrubbed(record: Record) {
|
||||
val dir = record.dir
|
||||
val tree = File(dir, SCRUBBED_TREE_MARKER)
|
||||
// A marker from older rules vouches for nothing now, whether or not this pass succeeded.
|
||||
dir.listFiles { f -> OLD_SCRUBBED_MARKER.matches(f.name) }?.forEach { it.delete() }
|
||||
if (record.failed) {
|
||||
tree.delete()
|
||||
Log.w(TAG, "$dir is not fully scrubbed; it is scrubbed again when shared")
|
||||
return false
|
||||
return
|
||||
}
|
||||
return try {
|
||||
try {
|
||||
File(dir, SCRUBBED_MARKER).writeText("scrubbed ${now()}\n")
|
||||
val lines = StringBuilder("rules ${LogRedactor.RULES_VERSION}\n")
|
||||
record.files.forEach { (f, s) ->
|
||||
@@ -189,11 +159,8 @@ object SessionArtifacts {
|
||||
.append(f.relativeTo(dir).path).append('\n')
|
||||
}
|
||||
tree.writeText(lines.toString())
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
tree.delete()
|
||||
File(dir, SCRUBBED_MARKER).delete()
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -214,8 +181,9 @@ object SessionArtifacts {
|
||||
}.toSet()
|
||||
}
|
||||
|
||||
/** The end-of-session scrub of [dir] on its own (steam/ already in place); also the pass over older and moved folders. */
|
||||
internal fun scrubAndMark(dir: File): Boolean = markScrubbed(scrubTree(Record(dir)))
|
||||
/** The end-of-session scrub of [dir] on its own (steam/ already in place), for tests. */
|
||||
@androidx.annotation.VisibleForTesting
|
||||
internal fun scrubAndMark(dir: File) = markScrubbed(scrubTree(Record(dir)))
|
||||
|
||||
/**
|
||||
* [record]'s folder and every folder under it (steam/, droiddeck-esync/): the session script
|
||||
@@ -255,7 +223,7 @@ object SessionArtifacts {
|
||||
*/
|
||||
@Synchronized
|
||||
fun finishAbandoned(context: Context) {
|
||||
val parent = LinuxRuntime.logDir(context)
|
||||
val parent = LinuxRuntime.debugLogDir()
|
||||
val abandoned = parent.listFiles { f ->
|
||||
SessionPaths.isSessionFolder(f) && !File(f, COMPLETE_MARKER).exists()
|
||||
}?.sortedWith(SessionPaths.chronological) ?: return
|
||||
@@ -314,7 +282,9 @@ object SessionArtifacts {
|
||||
val current = SessionPaths.current()
|
||||
val gone = SessionPaths.sessionFolders(context).filter { it != current }
|
||||
gone.forEach { com.droiddeck.launcher.core.FileUtils.delete(it) }
|
||||
com.droiddeck.launcher.core.FileUtils.delete(File(LinuxRuntime.logDir(context), SessionPaths.TOOLS_DIR))
|
||||
com.droiddeck.launcher.core.FileUtils.delete(File(LinuxRuntime.debugLogDir(), SessionPaths.TOOLS_DIR))
|
||||
// Before tools/, those logs sat loose beside the session folders.
|
||||
LinuxRuntime.debugLogDir().listFiles { f -> f.isFile && f.name.endsWith(".log") }?.forEach { it.delete() }
|
||||
Log.i(TAG, "cleared ${gone.size} session folder(s)")
|
||||
return gone.size
|
||||
}
|
||||
|
||||
@@ -6,11 +6,6 @@ import android.view.WindowManager
|
||||
/** The virtual display advertised to the guest, before it is fitted onto the Android panel. */
|
||||
object SessionDisplay {
|
||||
const val MATCH_SCREEN = "screen"
|
||||
/** The window's size, kept in step while the session runs: a foldable opening or closing, a
|
||||
* split screen or a freeform window resizes the guest's display instead of letterboxing it. */
|
||||
const val FOLLOW_SCREEN = "follow"
|
||||
/** Below this a side is a picture-in-picture or a sliver of split screen: not worth a resize. */
|
||||
const val FOLLOW_MIN_SIDE = 480
|
||||
|
||||
/**
|
||||
* Presets are heights, not sizes: "720p" is the panel's own shape at 720 lines, never narrower
|
||||
@@ -30,7 +25,7 @@ object SessionDisplay {
|
||||
(maxOf(panel.first, panel.second) and 1.inv()) to (minOf(panel.first, panel.second) and 1.inv())
|
||||
|
||||
fun resolveChoice(panel: Pair<Int, Int>, choice: String): Pair<Int, Int> {
|
||||
if (choice == MATCH_SCREEN || choice == FOLLOW_SCREEN) return screenSize(panel)
|
||||
if (choice == MATCH_SCREEN) return screenSize(panel)
|
||||
presetHeight(choice)?.let { return resolve(panel, it, SessionPrefs.SHAPE_AUTO) }
|
||||
// Fixed sizes (custom, or a preset saved before presets were heights) keep their exact size,
|
||||
// including legacy ones past the custom dialog's limit.
|
||||
@@ -39,19 +34,13 @@ object SessionDisplay {
|
||||
else resolve(panel, 720, SessionPrefs.SHAPE_AUTO)
|
||||
}
|
||||
|
||||
/** The height presets the panel is tall enough for, then the panel itself, with no duplicate
|
||||
* sizes, then Follow screen. */
|
||||
/** The height presets the panel is tall enough for, then the panel itself, with no duplicate sizes. */
|
||||
fun resolutionOptions(panel: Pair<Int, Int>): List<String> {
|
||||
val panelHeight = minOf(panel.first, panel.second)
|
||||
return PRESET_HEIGHTS.filter { it <= panelHeight }.map { "${it}p" }
|
||||
.filter { resolveChoice(panel, it) != screenSize(panel) } + MATCH_SCREEN + FOLLOW_SCREEN
|
||||
.filter { resolveChoice(panel, it) != screenSize(panel) } + MATCH_SCREEN
|
||||
}
|
||||
|
||||
/** A Follow screen session's display for a window of this size: its own shape, square or
|
||||
* portrait included, with even sides; null when it is too small to follow (PiP). */
|
||||
fun followSize(width: Int, height: Int): Pair<Int, Int>? =
|
||||
if (minOf(width, height) < FOLLOW_MIN_SIDE) null else (width and 1.inv()) to (height and 1.inv())
|
||||
|
||||
fun panelSize(context: Context): Pair<Int, Int> {
|
||||
val manager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
|
||||
@Suppress("DEPRECATION")
|
||||
|
||||
@@ -5,7 +5,6 @@ import android.os.Environment
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.core.FileUtils
|
||||
import com.droiddeck.launcher.runtime.DesktopCatalog
|
||||
import com.droiddeck.launcher.runtime.LegacyNames
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.runtime.ProotFastPath
|
||||
@@ -91,15 +90,16 @@ object SessionFiles {
|
||||
"usr/bin/steamos-polkit-helpers/jupiter-biosupdate" to "usr/bin/steamos-polkit-helpers/jupiter-biosupdate",
|
||||
"usr/bin/steamos-polkit-helpers/jupiter-dock-updater" to "usr/bin/steamos-polkit-helpers/jupiter-dock-updater",
|
||||
)
|
||||
// The desktop's launchers, only where the desktop package is installed:
|
||||
// The desktop's launcher and labwc defaults, only where the desktop package is installed:
|
||||
// staging them into a runtime without it would make the desktop look present when it is not.
|
||||
val desktop = arrayOf(
|
||||
"usr/local/bin/droiddeck-desktop" to "usr/local/bin/droiddeck-desktop",
|
||||
// Games and emulators from the menu, full screen in a gamescope of their own.
|
||||
"usr/local/bin/droiddeck-gpu" to "usr/local/bin/droiddeck-gpu",
|
||||
"usr/local/bin/droiddeck-desktop-gpu" to "usr/local/bin/droiddeck-desktop-gpu",
|
||||
// KWin at the app's surface size, for Plasma's session (it starts KWin through this name).
|
||||
"usr/local/bin/kwin_wayland_wrapper" to "usr/local/bin/kwin_wayland_wrapper",
|
||||
"etc/xdg/labwc/autostart" to "etc/xdg/labwc/autostart",
|
||||
"etc/xdg/labwc/rc.xml" to "etc/xdg/labwc/rc.xml",
|
||||
"etc/xdg/lxqt/panel.conf" to "etc/xdg/lxqt/panel.conf",
|
||||
"usr/lib/firefox/defaults/pref/droiddeck.js" to "usr/lib/firefox/defaults/pref/droiddeck.js",
|
||||
)
|
||||
// The patched gamescope (tools/gamescope): the runtime's own version rebuilt with the ARM64
|
||||
@@ -117,9 +117,13 @@ object SessionFiles {
|
||||
"usr/local/lib/mangoapp/libtracefs.so.1",
|
||||
).map { it to it }
|
||||
// What the Windows components installer reads .msi packages with (tools/msitools).
|
||||
val msitools = listOf("msiinfo", "cabextract", "7z", "7z.so", "libmsi-1.0.so.0", "libgsf-1.so.114", "libgcab-1.0.so.0")
|
||||
val msitools = listOf("msiinfo", "cabextract", "libmsi-1.0.so.0", "libgsf-1.so.114", "libgcab-1.0.so.0")
|
||||
.map { "usr/local/lib/droiddeck-msitools/$it" } +
|
||||
listOf("NOTICE", "GPL-2", "GPL-3", "LGPL-2.1", "7zip-License", "7zip-unRarLicense").map { "usr/local/share/licenses/droiddeck-msitools/$it" }
|
||||
listOf("NOTICE", "GPL-2", "GPL-3", "LGPL-2.1").map { "usr/local/share/licenses/droiddeck-msitools/$it" }
|
||||
// The patched wlroots (tools/wlroots) the desktop loads for its vulkan / gles2 renderers.
|
||||
val wlroots = if (File(root, "usr/bin/labwc").isFile) {
|
||||
arrayOf("usr/local/lib/droiddeck-wlroots/libwlroots-0.20.so" to "usr/local/lib/droiddeck-wlroots/libwlroots-0.20.so")
|
||||
} else emptyArray()
|
||||
val fexPreloads = listOf("x86_64", "i386").flatMap { arch ->
|
||||
listOf("libblsession.so", "libfakeinput.so").map { "$arch/$it" to "usr/local/lib/droiddeck-fex/$arch/$it" }
|
||||
} + listOf("libfaultreport.so", "libthunkaudit.so", "libvulkan-thunk.so").map { "x86_64/$it" to "usr/local/lib/droiddeck-fex/x86_64/$it" }
|
||||
@@ -127,11 +131,11 @@ object SessionFiles {
|
||||
"usr/local/bin/gamescope" to "usr/local/bin/gamescope",
|
||||
"usr/local/lib/droiddeck/uruntime" to "usr/local/lib/droiddeck/uruntime",
|
||||
"usr/local/share/licenses/uruntime/LICENSE" to "usr/local/share/licenses/uruntime/LICENSE",
|
||||
) + mangoapp + msitools.map { it to it } + fexPreloads).filter { (asset, _) ->
|
||||
) + wlroots + mangoapp + msitools.map { it to it } + fexPreloads).filter { (asset, _) ->
|
||||
val dir = asset.substringBeforeLast('/')
|
||||
runCatching { context.assets.list("linuxfs/$dir")?.contains(asset.substringAfterLast('/')) == true }.getOrDefault(false)
|
||||
}
|
||||
val all = (if (DesktopCatalog.desktopInstalled(root)) files + desktop else files) + optional
|
||||
val all = (if (File(root, "usr/bin/labwc").isFile) files + desktop else files) + optional
|
||||
for ((asset, relative) in all) {
|
||||
val target = File(root, relative)
|
||||
val staged = File(target.parentFile, target.name + ".staged")
|
||||
@@ -361,9 +365,25 @@ object SessionFiles {
|
||||
).joinToString(newline)
|
||||
|
||||
/**
|
||||
* Where the session writes its log: app-private `files/logs`, bound into the session at the same
|
||||
* path, so the session script's own redirection always opens. A folder leaves the device only
|
||||
* through Share logs, which scrubs every file again on the way into the zip.
|
||||
* Where the session writes its log. Downloads is the point - a failed run is handed over as a
|
||||
* folder rather than dug out of app-private storage - but the session script redirects its own
|
||||
* output there with `exec`, and a redirection a non-interactive shell cannot open ends that
|
||||
* shell. So a public directory is used only once it is proven writable; otherwise the app's
|
||||
* own files directory, which is bound into the session anyway, stands in.
|
||||
*/
|
||||
fun logDirectory(context: Context): File = LinuxRuntime.logDir(context).apply { mkdirs() }
|
||||
fun logDirectory(context: Context): File {
|
||||
val public = LinuxRuntime.debugLogDir()
|
||||
if (public.isDirectory || public.mkdirs()) {
|
||||
val probe = File(public, ".writable")
|
||||
try {
|
||||
if (probe.createNewFile() || probe.isFile) {
|
||||
probe.delete()
|
||||
return public
|
||||
}
|
||||
} catch (ignored: Exception) {
|
||||
}
|
||||
}
|
||||
Log.w(TAG, "$public is not writable (storage permission?); logging to files/logs")
|
||||
return File(context.filesDir, "logs").apply { mkdirs() }
|
||||
}
|
||||
}
|
||||
@@ -18,11 +18,9 @@ import java.util.zip.ZipEntry
|
||||
import java.util.zip.ZipOutputStream
|
||||
|
||||
/**
|
||||
* Share logs: one zip, made when asked, of a session folder (the newest by default) with the last
|
||||
* seven days of the stores' log and the one-off command logs beside it, handed to Android's share
|
||||
* sheet. Logs live in app-private `files/logs`; this is how they leave the device. Every text file
|
||||
* goes through [LogRedactor.redactForShare] on the way in, so even a file written before a rule
|
||||
* existed is clean in the zip. The zip sits in `cache/share/` until the next share or app start.
|
||||
* Zips the most recent session's log folder and hands it to Android's share sheet. Works where
|
||||
* the folder could not be written to Downloads (no storage permission, or a device that refuses
|
||||
* it) and landed in the app's private files instead, which a user cannot otherwise reach.
|
||||
*/
|
||||
object SessionLogShare {
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
@@ -64,7 +62,7 @@ object SessionLogShare {
|
||||
val files = folder.walkTopDown().filter { it.isFile }
|
||||
.filterNot { it.parentFile?.name == "steam" && it.length() > STEAM_LOG_MAX_BYTES }.toList()
|
||||
if (files.isEmpty()) return null
|
||||
val out = shareDir(context).apply { deleteRecursively(); mkdirs() }
|
||||
val out = File(context.cacheDir, "shared-logs").apply { deleteRecursively(); mkdirs() }
|
||||
val zip = File(out, "DroidDeck-${folder.name}.zip")
|
||||
// Scrubbed on the way into the zip: a session shared while it runs has not had its end-of-
|
||||
// session pass yet, and the redactor changes nothing in a line that is already clean.
|
||||
@@ -73,11 +71,11 @@ object SessionLogShare {
|
||||
// since, goes in as it is; anything else (added or changed since, hidden, or any file of a
|
||||
// session still running) is scrubbed again. Scrubbing tens of MB of the client's logs on
|
||||
// every share kept the share sheet from appearing for ten seconds or more.
|
||||
val scrubbed = SessionArtifacts.scrubbedFiles(folder)
|
||||
val live = liveSteamLogs(context, folder)
|
||||
val logs = LinuxRuntime.logDir(context)
|
||||
val stores = recent(File(logs, STORES_DIR))
|
||||
val tools = recent(File(logs, SessionPaths.TOOLS_DIR))
|
||||
val total = (files + live + stores + tools).sumOf { it.length() }.coerceAtLeast(1L)
|
||||
// The stores' own log (last 7 days, app-private, already redacted), under stores/.
|
||||
val storeLogs = com.droiddeck.launcher.stores.StoreLogFiles.files(context)
|
||||
val total = (files + live + storeLogs).sumOf { it.length() }.coerceAtLeast(1L)
|
||||
var done = 0L
|
||||
var shown = -1
|
||||
fun advance(f: File) {
|
||||
@@ -86,20 +84,18 @@ object SessionLogShare {
|
||||
if (percent != shown) { shown = percent; onProgress?.invoke(percent / 100f) }
|
||||
}
|
||||
ZipOutputStream(zip.outputStream().buffered()).use { z ->
|
||||
files.forEach { f -> addEntry(z, folder.name + "/" + f.relativeTo(folder).path, f); advance(f) }
|
||||
live.forEach { f -> addEntry(z, folder.name + "/steam/" + f.name, f); advance(f) }
|
||||
stores.forEach { f -> addEntry(z, "$STORES_DIR/" + f.name, f); advance(f) }
|
||||
tools.forEach { f -> addEntry(z, SessionPaths.TOOLS_DIR + "/" + f.name, f); advance(f) }
|
||||
files.forEach { f -> addEntry(z, folder.name + "/" + f.relativeTo(folder).path, f, f.relativeTo(folder).path in scrubbed); advance(f) }
|
||||
live.forEach { f -> addEntry(z, folder.name + "/steam/" + f.name, f, false); advance(f) }
|
||||
storeLogs.forEach { f -> addEntry(z, folder.name + "/stores/" + f.name, f, false); advance(f) }
|
||||
}
|
||||
return zip
|
||||
}
|
||||
|
||||
private fun addEntry(z: ZipOutputStream, name: String, f: File) {
|
||||
private fun addEntry(z: ZipOutputStream, name: String, f: File, scrubbed: Boolean) {
|
||||
z.putNextEntry(ZipEntry(name))
|
||||
// Every text file, every time: the folder's own scrub may predate a rule.
|
||||
if (LogRedactor.isText(f)) {
|
||||
if (!scrubbed && LogRedactor.isText(f)) {
|
||||
val w = z.bufferedWriter()
|
||||
LogRedactor.scrubForShare(f, w)
|
||||
LogRedactor.scrubTo(f, w)
|
||||
w.flush()
|
||||
} else {
|
||||
f.inputStream().use { it.copyTo(z) }
|
||||
@@ -123,25 +119,6 @@ object SessionLogShare {
|
||||
/** The client's content and bootstrap logs grow large over months and say nothing about a session. */
|
||||
private const val STEAM_LOG_MAX_BYTES = 8L * 1024 * 1024
|
||||
|
||||
/** The stores' engine log, one file a day, under files/logs. */
|
||||
const val STORES_DIR = "stores"
|
||||
private const val RECENT_DAYS = 7
|
||||
|
||||
private fun shareDir(context: Context): File = File(context.cacheDir, "share")
|
||||
|
||||
/** The files in [dir] changed in the last [RECENT_DAYS] days. */
|
||||
private fun recent(dir: File): List<File> {
|
||||
val since = System.currentTimeMillis() - RECENT_DAYS * 86_400_000L
|
||||
return dir.listFiles { f -> f.isFile && f.lastModified() >= since }?.sortedBy { it.name }.orEmpty()
|
||||
}
|
||||
|
||||
/** Deletes the last share's zip; at app start, so a zip never outlives the share it was made for. */
|
||||
fun clear(context: Context) {
|
||||
shareDir(context).deleteRecursively()
|
||||
// Where builds before this one put it.
|
||||
File(context.cacheDir, "shared-logs").deleteRecursively()
|
||||
}
|
||||
|
||||
fun shareIntent(context: Context, zip: File): Intent {
|
||||
val uri = FileProvider.getUriForFile(context, context.packageName + ".logs", zip)
|
||||
val send = Intent(Intent.ACTION_SEND)
|
||||
|
||||
@@ -8,20 +8,19 @@ import java.util.Date
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* One folder per session under app-private `files/logs/`, holding everything that session recorded,
|
||||
* One folder per session under `Download/DroidDeck/`, holding everything that session recorded,
|
||||
* named for the day, that day's session number and what was run, so the one a report is about can
|
||||
* be picked out without opening any:
|
||||
*
|
||||
* ```
|
||||
* files/logs/2026-09-30-03-steam/
|
||||
* Download/DroidDeck/2026-09-30-03-steam/
|
||||
* device.txt what this device is, and every setting the session ran with
|
||||
* session.log the guest session: proot, gamescope, the client's stdout
|
||||
* wayland.log the app's compositor
|
||||
* steam.log the Steam client's own log, scrubbed (Steam mode)
|
||||
* steam/ the rest of the client's logs, scrubbed (Steam mode)
|
||||
* desktop.log KWin, Plasma and the programs on it (desktop mode)
|
||||
* files/logs/tools/ one-off commands: Flatpak installs, AppImage imports
|
||||
* files/logs/stores/ the stores' engine log, one file a day
|
||||
* desktop.log labwc, the panel and the programs on it (desktop mode)
|
||||
* Download/DroidDeck/tools/ one-off commands: Flatpak installs, AppImage imports
|
||||
* ```
|
||||
*
|
||||
* Folders from before this naming (`session-20260930-180642`) are still recognised, shared and
|
||||
@@ -138,7 +137,8 @@ object SessionPaths {
|
||||
|
||||
/** Every session folder in the places logs are written, oldest first. */
|
||||
fun sessionFolders(context: Context): List<File> =
|
||||
(com.droiddeck.launcher.runtime.LinuxRuntime.logDir(context).listFiles { f -> isSessionFolder(f) }?.toList() ?: emptyList())
|
||||
listOf(com.droiddeck.launcher.runtime.LinuxRuntime.debugLogDir(), File(context.filesDir, "logs"))
|
||||
.flatMap { parent -> parent.listFiles { f -> isSessionFolder(f) }?.toList() ?: emptyList() }
|
||||
.sortedWith(chronological)
|
||||
|
||||
internal fun slug(text: String): String =
|
||||
|
||||
@@ -493,7 +493,7 @@ object SessionPrefs {
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a session keeps its folder under files/logs. Off, the same logs are kept in
|
||||
* Whether a session writes its folder under Download/DroidDeck. Off, the same logs are kept in
|
||||
* the app's cache for the session's lifetime (the scripts need somewhere to write) and thrown
|
||||
* away at the end, so nothing accumulates in Downloads.
|
||||
*/
|
||||
@@ -533,8 +533,7 @@ object SessionPrefs {
|
||||
fun resolutionChoice(context: Context, mode: String, panel: Pair<Int, Int>): String {
|
||||
val saved = prefs(context)
|
||||
saved.getString("displayResolution.$mode", null)?.let { value ->
|
||||
if (value == SessionDisplay.MATCH_SCREEN || value == SessionDisplay.FOLLOW_SCREEN ||
|
||||
SessionDisplay.presetHeight(value) != null) return value
|
||||
if (value == SessionDisplay.MATCH_SCREEN || SessionDisplay.presetHeight(value) != null) return value
|
||||
parseResolution(value)?.let { return "${it.first}x${it.second}" }
|
||||
}
|
||||
if (!resolutionChosen(context, mode) && !saved.contains("shape")) return SessionDisplay.DEFAULT_RESOLUTION
|
||||
@@ -544,8 +543,7 @@ object SessionPrefs {
|
||||
}
|
||||
|
||||
fun setResolutionChoice(context: Context, mode: String, choice: String) {
|
||||
val value = if (choice == SessionDisplay.MATCH_SCREEN || choice == SessionDisplay.FOLLOW_SCREEN ||
|
||||
SessionDisplay.presetHeight(choice) != null) choice else {
|
||||
val value = if (choice == SessionDisplay.MATCH_SCREEN || SessionDisplay.presetHeight(choice) != null) choice else {
|
||||
val size = requireNotNull(parseResolution(choice)) { "Invalid resolution" }
|
||||
"${size.first}x${size.second}"
|
||||
}
|
||||
@@ -680,6 +678,21 @@ object SessionPrefs {
|
||||
return Pair(w and 1.inv(), h and 1.inv())
|
||||
}
|
||||
|
||||
/**
|
||||
* What the desktop shell composites with: vulkan (the default) or gles2 on the GPU, through the
|
||||
* app's patched wlroots (tools/wlroots) - the Adreno stand-in is not a DRM device and stock
|
||||
* wlroots cannot allocate on it - or pixman in software. A GPU renderer a device cannot start
|
||||
* falls back to pixman by itself (droiddeck-desktop). `Download/droiddeck-wlr-renderer` still
|
||||
* overrides it.
|
||||
*/
|
||||
fun desktopRenderer(context: Context): String = prefs(context).getString("desktopRenderer", "vulkan") ?: "vulkan"
|
||||
|
||||
fun setDesktopRenderer(context: Context, renderer: String) {
|
||||
prefs(context).edit().putString("desktopRenderer", renderer).apply()
|
||||
// A choice made again is a retry: forget that a renderer failed to start here before.
|
||||
java.io.File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context), "root/.droiddeck-renderer-failed").delete()
|
||||
}
|
||||
|
||||
/**
|
||||
* HDR10 output for MODE_STEAM / MODE_DESKTOP. Off by default. Honoured only when the panel
|
||||
* lists HDR10 (HdrSupport), and decided when the compositor starts, which is once per app
|
||||
|
||||
@@ -354,9 +354,6 @@ class SessionService : Service() {
|
||||
|
||||
guest.add("BL_WIDTH=" + size.first)
|
||||
guest.add("BL_HEIGHT=" + size.second)
|
||||
// Follow screen: the output is resized under gamescope when a foldable opens or closes,
|
||||
// and the session script asks gamescope to resize Steam's X screen along with it.
|
||||
if (SessionState.followScreen) guest.add("BL_FOLLOW_OUTPUT=1")
|
||||
if (SessionState.hdr) {
|
||||
// The activity opened the compositor's HDR gate: gamescope offers HDR to its clients
|
||||
// and DXVK takes the HDR10 swapchain when a game asks for one.
|
||||
@@ -374,6 +371,16 @@ class SessionService : Service() {
|
||||
SessionState.deckPad = false
|
||||
deckBinds = emptyList()
|
||||
if (controllersOn) addControllerEnvironment(guest, fakeInputDir, sessionDir)
|
||||
// The desktop is wlroots (labwc). Stock wlroots allocates through gbm on a real DRM render
|
||||
// node, and ours is a KGSL stand-in - labwc died at "unable to create allocator" - so the
|
||||
// default is pixman (software, shm), where a Vulkan program cannot draw at all; those run
|
||||
// through droiddeck-gpu instead. vulkan / gles2 use the app's patched wlroots and fall back
|
||||
// to pixman by themselves. droiddeck-wlr-renderer in Downloads overrides the choice.
|
||||
if (SessionState.mode == MODE_DESKTOP) {
|
||||
val override = File(Environment.getExternalStorageDirectory(), "Download/droiddeck-wlr-renderer")
|
||||
.takeIf { it.isFile }?.let { FileUtils.readString(it)?.trim() }
|
||||
guest.add("BL_WLR_RENDERER=" + (override?.takeIf { it.isNotEmpty() } ?: SessionPrefs.desktopRenderer(this)))
|
||||
}
|
||||
// The user's own games, for the runtime's shortcuts writer to put in the client's library
|
||||
// before the client starts (see frontend/AddedGames and droiddeck-steam-shortcuts).
|
||||
if (steamHere) {
|
||||
@@ -389,6 +396,9 @@ class SessionService : Service() {
|
||||
// The second library's name, for droiddeck-steam-library; the bind itself is made below.
|
||||
GameStorage.effective(this)?.let { guest.add("BL_LIBRARY_LABEL=" + it.label.replace('"', ' ')) }
|
||||
if (SessionState.mode == MODE_STEAM && SessionState.steamUi == "desktop") guest.add("BL_STEAM_UI=desktop")
|
||||
// The desktop asked for with Steam in it (the front end's "Steam Desktop UI", Big Picture's
|
||||
// "Switch to Desktop"): the desktop's autostart opens the client's desktop UI there.
|
||||
if (SessionState.mode == MODE_DESKTOP && SessionState.steamUi == "desktop") guest.add("BL_DESKTOP_STEAM=1")
|
||||
val shellGuest = ArrayList(guest).apply {
|
||||
add("SHELL=/bin/bash")
|
||||
add("TERM=xterm-256color")
|
||||
@@ -404,7 +414,7 @@ class SessionService : Service() {
|
||||
}
|
||||
// A program under gamescope: the script's run mode takes the path (an AppImage, a script
|
||||
// or a binary inside the runtime). This is how an emulator gets the GPU - the desktop's
|
||||
// KWin composites in software and offers no dma-buf, so a Vulkan swapchain cannot exist
|
||||
// labwc composites in software and offers no dma-buf, so a Vulkan swapchain cannot exist
|
||||
// there (RPCS3 died with VK_ERROR_SURFACE_LOST); gamescope's Xwayland is the path the
|
||||
// Steam games already render through.
|
||||
if (SessionState.mode == MODE_RUN) {
|
||||
@@ -1407,9 +1417,6 @@ class SessionService : Service() {
|
||||
SessionState.guestPid = -1
|
||||
com.droiddeck.launcher.agent.AgentGuest.stop()
|
||||
com.droiddeck.launcher.stores.StoreLaunchRequests.stop()
|
||||
// Cloud saves of a store game played this session, if the compat tool's exit request did
|
||||
// not upload them (a session closed from the drawer never reaches it).
|
||||
Thread({ com.droiddeck.launcher.stores.CloudSaves.uploadAllDirty(applicationContext, "session-end", running = false) }, "cloud-session-end").start()
|
||||
runCatching { com.droiddeck.launcher.agent.AgentEnv.endSession(this) }
|
||||
.onFailure { Log.w(TAG, "clearing the agent's session environment", it) }
|
||||
releaseLocks()
|
||||
|
||||
@@ -96,10 +96,6 @@ object SessionState {
|
||||
@Volatile
|
||||
var outputSize: Pair<Int, Int> = Pair(1920, 1080)
|
||||
|
||||
/** The session's resolution is "Follow screen": outputSize tracks the window while it runs. */
|
||||
@Volatile
|
||||
var followScreen = false
|
||||
|
||||
@Volatile
|
||||
var refreshHz: Float = 60f
|
||||
|
||||
|
||||
@@ -47,35 +47,16 @@ object WinComponents {
|
||||
// at the same path, so the native file at that path is the one the registration loads.
|
||||
private val FILE_STEPS = setOf("download_archive", "archive_extract", "copy_dll", "copy_file", "override_dll", "register_dll")
|
||||
private val INSTALLER_STEPS = setOf("install_exe", "install_msi")
|
||||
/**
|
||||
* Steps done here without any installer running: a Windows version or registry value for the
|
||||
* prefix (written by droiddeck-wincomponents with the rest), files picked out of a cabinet, and
|
||||
* "uninstall Wine Mono", which the mscoree override beside it already does for the game.
|
||||
*/
|
||||
private val OFFLINE_STEPS = setOf("set_windows", "set_register_key", "get_from_cab", "uninstall")
|
||||
/**
|
||||
* Installers that are their own setup program (NSIS, InnoSetup, IExpress scripts): nothing
|
||||
* inside them is a package to lay out, so they wait for a way to run them.
|
||||
*/
|
||||
private val RUNS_OWN_SETUP = setOf(
|
||||
"K-Lite", "ffdshow", "lavfilters702", "lavfilters741", "quicktime72", "dirac", "webview2", "aairruntime",
|
||||
"gfw", "ie8_kb2936068", "art2kmin", "art2k7min", "vcredist6sp6", "VulkanRT", "jet40", "mdac28", "oalinst",
|
||||
"dotnet20", "dotnet20sp1", "dotnet35", "dotnet35sp1",
|
||||
)
|
||||
private const val MSI_INSTALL = "/usr/local/bin/droiddeck-msi-install"
|
||||
/** Where a downloaded package or installer waits for the installer, inside the runtime so it can read it. */
|
||||
/** Where a downloaded .msi waits for the installer, inside the runtime so it can read it. */
|
||||
private const val MSI_CACHE = "$STORE/.packages"
|
||||
/** Catalog entries Proton already provides newer copies of, which an install would only shadow. */
|
||||
private val PROTON_PROVIDES = setOf("gecko", "mono")
|
||||
/** The keys the catalog nests under "environment" on a few .NET entries. */
|
||||
private val NESTED_KEYS = setOf("url", "file_name", "file_checksum", "file_size")
|
||||
private val PROTON_PROVIDES = setOf("gecko")
|
||||
|
||||
fun validId(id: String): Boolean = ID.matches(id) && ".." !in id
|
||||
|
||||
class Step(val action: String, val json: JSONObject) {
|
||||
fun str(key: String): String = json.optString(key, "").ifEmpty {
|
||||
if (key in NESTED_KEYS) json.optJSONObject("environment")?.optString(key, "").orEmpty() else ""
|
||||
}
|
||||
fun str(key: String): String = json.optString(key, "")
|
||||
}
|
||||
|
||||
class Component(
|
||||
@@ -85,27 +66,10 @@ object WinComponents {
|
||||
|
||||
enum class Support { READY, NEEDS_INSTALLER, UNSUPPORTED }
|
||||
|
||||
/** The two halves of an install the page shows one after the other, each 0..100. */
|
||||
enum class Phase { DOWNLOAD, INSTALL }
|
||||
|
||||
/** Progress: the component being worked on, what it is doing, the phase, 0..100 or -1 when unknown. */
|
||||
class Progress(val component: String, val stage: String, val phase: Phase, val percent: Int)
|
||||
|
||||
/** The percent a droiddeck-msi-install progress line carries ("progress 37% placing files"), or -1. */
|
||||
private val PERCENT_LINE = Regex("""^(\d{1,3})% (.*)$""")
|
||||
private fun engineLine(text: String): Pair<String, Int> =
|
||||
PERCENT_LINE.find(text)?.let { it.groupValues[2] to it.groupValues[1].toInt().coerceIn(0, 100) } ?: (text to -1)
|
||||
|
||||
/**
|
||||
* A step that installs a Windows Installer package, or an installer .exe that is a wrapper
|
||||
* around packages (a WiX bundle, a self-extracting cabinet or 7-Zip archive), which
|
||||
* droiddeck-msi-install lays out here without running it.
|
||||
*/
|
||||
private fun isPackage(step: Step): Boolean = step.action in INSTALLER_STEPS && step.str("url").startsWith("https://") &&
|
||||
/** A step that installs a Windows Installer package, which droiddeck-msi-install does here. */
|
||||
private fun isMsi(step: Step): Boolean = step.action in INSTALLER_STEPS && step.str("url").startsWith("https://") &&
|
||||
(step.action == "install_msi" || listOf(step.str("file_name"), step.str("url").substringBefore('?'))
|
||||
.any { it.endsWith(".msi", ignoreCase = true) || it.endsWith(".exe", ignoreCase = true) })
|
||||
|
||||
private fun protonProvides(name: String): Boolean = name in PROTON_PROVIDES || name.startsWith("mono-")
|
||||
.any { it.endsWith(".msi", ignoreCase = true) })
|
||||
|
||||
fun fetch(): List<Component>? {
|
||||
val body = Downloader.downloadString(CATALOG_URL) ?: return null
|
||||
@@ -130,14 +94,13 @@ object WinComponents {
|
||||
|
||||
/** Whether [c] can be installed here, its bundled components included. */
|
||||
fun support(c: Component, all: Map<String, Component>, depth: Int = 0): Support {
|
||||
if (c.status != "ready" || depth > 8 || protonProvides(c.name)) return Support.UNSUPPORTED
|
||||
if (c.status != "ready" || depth > 8 || c.name in PROTON_PROVIDES) return Support.UNSUPPORTED
|
||||
val installers = c.steps.filter { it.action in INSTALLER_STEPS }
|
||||
fun offline(step: Step) = step.action == "delete_dlls" || step.action in OFFLINE_STEPS || step.action in FILE_STEPS && fileStepOk(step)
|
||||
val own = when {
|
||||
installers.isNotEmpty() && c.name !in RUNS_OWN_SETUP && installers.all { isPackage(it) } &&
|
||||
c.steps.all { it in installers || offline(it) } -> Support.READY
|
||||
installers.isNotEmpty() && installers.all { isMsi(it) } &&
|
||||
c.steps.all { it in installers || it.action == "delete_dlls" || it.action in FILE_STEPS && fileStepOk(it) } -> Support.READY
|
||||
installers.isNotEmpty() -> Support.NEEDS_INSTALLER
|
||||
c.steps.all { offline(it) } -> Support.READY
|
||||
c.steps.all { it.action in FILE_STEPS && fileStepOk(it) } -> Support.READY
|
||||
else -> Support.UNSUPPORTED
|
||||
}
|
||||
if (own != Support.READY) return own
|
||||
@@ -146,10 +109,9 @@ object WinComponents {
|
||||
}
|
||||
|
||||
private fun fileStepOk(step: Step): Boolean = when (step.action) {
|
||||
// An .exe or .cab archive (DirectX's redistributable) is opened by the runtime's tools.
|
||||
"download_archive", "archive_extract" -> step.str("url").let { url ->
|
||||
!url.startsWith("http") || url.startsWith("https://github.com/") &&
|
||||
url.substringBefore('?').lowercase().let { it.endsWith(".tar.xz") || it.endsWith(".zip") || it.endsWith(".exe") || it.endsWith(".cab") }
|
||||
url.substringBefore('?').let { it.endsWith(".tar.xz") || it.endsWith(".zip") }
|
||||
}
|
||||
"copy_dll", "copy_file" -> ".." !in step.str("dest")
|
||||
else -> true
|
||||
@@ -169,7 +131,7 @@ object WinComponents {
|
||||
* Installs [c] and the components it bundles that are not installed yet. [onProgress] gets a
|
||||
* line for the step and 0..100 (or -1). Returns null on success, else a message.
|
||||
*/
|
||||
fun install(context: Context, c: Component, all: Map<String, Component>, onProgress: (Progress) -> Unit): String? {
|
||||
fun install(context: Context, c: Component, all: Map<String, Component>, onProgress: (String, Int) -> Unit): String? {
|
||||
if (support(c, all) != Support.READY) return "${c.name} cannot be installed here yet"
|
||||
val order = ArrayList<Component>()
|
||||
fun visit(x: Component, depth: Int) {
|
||||
@@ -184,7 +146,7 @@ object WinComponents {
|
||||
val archives = HashMap<String, File>()
|
||||
return try {
|
||||
for (x in order) {
|
||||
onProgress(Progress(x.name, x.name, Phase.DOWNLOAD, -1))
|
||||
onProgress(x.name, -1)
|
||||
installOne(context, x, work, archives, onProgress)?.let { return "${x.name}: $it" }
|
||||
}
|
||||
null
|
||||
@@ -196,27 +158,18 @@ object WinComponents {
|
||||
}
|
||||
}
|
||||
|
||||
private fun installOne(context: Context, c: Component, work: File, archives: HashMap<String, File>, onProgress: (Progress) -> Unit): String? {
|
||||
private fun installOne(context: Context, c: Component, work: File, archives: HashMap<String, File>, onProgress: (String, Int) -> Unit): String? {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
if (!root.isDirectory) return "The Linux runtime is not installed"
|
||||
val staging = File(root, "$STORE/.${c.name}.new").apply { FileUtils.delete(this); mkdirs() }
|
||||
val overrides = ArrayList<String>()
|
||||
var source: File? = null
|
||||
var msi: JSONObject? = null
|
||||
// The registry values the steps themselves set (a Windows version, a key), beside the packages'.
|
||||
val registry = ArrayList<JSONObject>()
|
||||
// Archives the runtime's tools opened (installer .exe, cabinets), by the name the catalog
|
||||
// calls them, and the folders they were opened into; cleaned up at the end.
|
||||
val runtimeArchives = HashMap<String, File>()
|
||||
val runtimeDirs = ArrayList<File>()
|
||||
val cabs = HashMap<String, File>()
|
||||
val temp = File(root, "$MSI_CACHE/.t-${c.name}").apply { FileUtils.delete(this) }
|
||||
try {
|
||||
for (step in c.steps) when (step.action) {
|
||||
// A component may have several packages (PowerShell's 32- and 64-bit): each adds to the
|
||||
// same folder, the first one names the component.
|
||||
"install_msi", "install_exe" -> {
|
||||
val (result, problem) = installPackage(context, c, step, staging, onProgress)
|
||||
val (result, problem) = installMsi(context, c, step, staging, onProgress)
|
||||
if (result == null) return problem
|
||||
msi = msi?.apply {
|
||||
val notes = optJSONArray("notes") ?: JSONArray().also { put("notes", it) }
|
||||
@@ -230,84 +183,19 @@ object WinComponents {
|
||||
if (!url.startsWith("http")) continue
|
||||
source = archives[url] ?: run {
|
||||
val name = url.substringBefore('?').substringAfterLast('/')
|
||||
// A zip or tar.xz is opened here; an .exe or .cab by the runtime's tools, so it
|
||||
// is downloaded where the runtime can read it and kept for get_from_cab steps.
|
||||
val byRuntime = name.lowercase().let { it.endsWith(".exe") || it.endsWith(".cab") }
|
||||
val file = if (byRuntime) File(root, "$MSI_CACHE/${archives.size}-$name").apply { parentFile?.mkdirs() }
|
||||
else File(work, "${archives.size}-$name")
|
||||
val ok = Downloader.downloadFile(url, file, false) { f -> onProgress(Progress(c.name, name, Phase.DOWNLOAD, if (f < 0) -1 else Math.round(f * 100f))) }
|
||||
val file = File(work, "${archives.size}-$name")
|
||||
val ok = Downloader.downloadFile(url, file, false) { f -> onProgress("${c.name}: $name", if (f < 0) -1 else Math.round(f * 100f)) }
|
||||
if (!ok) return "download failed: $name"
|
||||
step.str("file_checksum").takeIf { it.length == 32 }?.let { md5 ->
|
||||
if (!digest(file, "MD5").equals(md5, ignoreCase = true)) return "checksum mismatch: $name"
|
||||
}
|
||||
onProgress(Progress(c.name, "unpacking $name", Phase.INSTALL, -1))
|
||||
val dir = if (byRuntime) {
|
||||
runtimeArchives[step.str("file_name").ifEmpty { name }] = file
|
||||
runtimeDirs += file
|
||||
unpackInRuntime(context, c, file, "${archives.size}-x", onProgress)?.also { runtimeDirs += it }
|
||||
?: return "could not unpack $name"
|
||||
} else {
|
||||
File(work, "${archives.size}-x").apply { mkdirs() }.also { if (!extract(file, it)) return "could not unpack $name" }
|
||||
.also { file.delete() }
|
||||
}
|
||||
onProgress("${c.name}: unpacking $name", -1)
|
||||
val dir = File(work, "${archives.size}-x").apply { mkdirs() }
|
||||
if (!extract(file, dir)) return "could not unpack $name"
|
||||
file.delete()
|
||||
dir.also { archives[url] = it }
|
||||
}
|
||||
}
|
||||
// Files picked out of a cabinet: one the catalog downloaded (DirectX's redistributable,
|
||||
// a self-extracting cabinet), or cabinets an earlier pick put under temp/.
|
||||
"get_from_cab" -> {
|
||||
val pattern = step.str("source")
|
||||
val containers = runtimeArchives[pattern]?.let { listOf(it) } ?: run {
|
||||
val folder = File(temp, pattern.substringBeforeLast('/', "").replace('\\', '/'))
|
||||
val rx = globRegex(pattern.substringAfterLast('/'))
|
||||
folder.listFiles { f -> f.isFile && rx.matches(f.name) }?.sortedBy { it.name }.orEmpty()
|
||||
}
|
||||
if (containers.isEmpty()) return "nothing is called $pattern"
|
||||
val dest = step.str("dest").replace('\\', '/')
|
||||
for (container in containers) {
|
||||
val unpacked = cabs.getOrPut(container.path) {
|
||||
unpackInRuntime(context, c, container, "c${cabs.size}", onProgress)?.also { runtimeDirs += it }
|
||||
?: return "could not open ${container.name}"
|
||||
}
|
||||
if (dest.startsWith("temp/", ignoreCase = true)) {
|
||||
copyMatching(unpacked, step.str("file_name"), File(temp, dest.substring(5).trimEnd('/')), null)
|
||||
} else {
|
||||
val (arch, base) = when (dest.substringBefore('/').lowercase()) {
|
||||
"win64", "system32" -> "win64" to "system32"
|
||||
"win32", "syswow64" -> "win32" to "syswow64"
|
||||
else -> null to "system32"
|
||||
}
|
||||
val sub = dest.substringAfter('/', "").trimEnd('/')
|
||||
copyMatching(unpacked, step.str("file_name"), File(staging, if (sub.isEmpty()) base else "$base/$sub"), arch)
|
||||
}
|
||||
}
|
||||
}
|
||||
// The Windows version a game sees: HKCU\Software\Wine "Version", the last word wins.
|
||||
"set_windows" -> step.str("version").takeIf { it.isNotEmpty() }?.let { version ->
|
||||
registry.removeAll { it.optString("key") == "Software\\Wine" && it.optString("name") == "Version" }
|
||||
registry += JSONObject().put("hive", "HKCU").put("key", "Software\\Wine").put("name", "Version").put("type", "sz").put("data", version)
|
||||
}
|
||||
"set_register_key" -> {
|
||||
val full = step.str("key").replace("\\\\", "\\").trim('\\')
|
||||
val hive = when (full.substringBefore('\\').uppercase()) {
|
||||
"HKLM", "HKEY_LOCAL_MACHINE" -> "HKLM"
|
||||
"HKCU", "HKEY_CURRENT_USER" -> "HKCU"
|
||||
else -> return "a registry key outside HKLM and HKCU: $full"
|
||||
}
|
||||
val key = full.substringAfter('\\', "")
|
||||
if (key.isEmpty()) return "a registry value without a key: $full"
|
||||
val data = step.str("data")
|
||||
val value = JSONObject().put("hive", hive).put("key", key).put("name", step.str("value"))
|
||||
when (step.str("type").uppercase()) {
|
||||
"REG_DWORD" -> value.put("type", "dword").put("data", data.trim().let { it.removePrefix("0x").toLongOrNull(if (it.startsWith("0x")) 16 else 10) ?: 0L })
|
||||
"REG_EXPAND_SZ" -> value.put("type", "expand_sz").put("data", data)
|
||||
else -> value.put("type", "sz").put("data", data)
|
||||
}
|
||||
registry += value
|
||||
}
|
||||
// "Uninstall Wine Mono" before a real .NET Framework: the mscoree override the catalog
|
||||
// sets beside it is what takes Mono out of the game's way; nothing to remove here.
|
||||
"uninstall" -> Unit
|
||||
"copy_dll", "copy_file" -> {
|
||||
val from = source ?: return "a copy step before any archive"
|
||||
val dest = step.str("dest")
|
||||
@@ -338,17 +226,6 @@ object WinComponents {
|
||||
"register_dll" -> Unit
|
||||
else -> return "unsupported step ${step.action}"
|
||||
}
|
||||
} finally {
|
||||
runtimeDirs.forEach { FileUtils.delete(it) }
|
||||
FileUtils.delete(temp)
|
||||
}
|
||||
if (registry.isNotEmpty()) {
|
||||
// The packages' values are already in registry.json; the steps' own go after them.
|
||||
val file = File(staging, "registry.json")
|
||||
val values = runCatching { JSONObject(file.readText()).optJSONArray("values") }.getOrNull() ?: JSONArray()
|
||||
registry.forEach { values.put(it) }
|
||||
FileUtils.writeString(file, JSONObject().put("version", 1).put("values", values).toString(1))
|
||||
}
|
||||
val version = msi?.optString("version")?.takeIf { it.isNotEmpty() }
|
||||
?: Regex("""\b(\d+\.\d+(\.\d+)*)\b""").find(c.description)?.value ?: "catalog"
|
||||
val meta = JSONObject()
|
||||
@@ -363,64 +240,31 @@ object WinComponents {
|
||||
return null
|
||||
}
|
||||
|
||||
/** The regex for a catalog file pattern: * matches anything, case does not matter. */
|
||||
private fun globRegex(pattern: String) =
|
||||
Regex("^" + pattern.split("*").joinToString(".*") { Regex.escape(it) } + "$", RegexOption.IGNORE_CASE)
|
||||
|
||||
/**
|
||||
* Has the runtime's tools open [archive] (an installer .exe, a cabinet, a self-extracting
|
||||
* one) into a folder of the package cache called [tag]; that folder, or null and a log line.
|
||||
* Downloads the component's .msi into the runtime and has droiddeck-msi-install lay it out in
|
||||
* [staging]. Returns the installer's result (product, version, counts, notes), or null and why.
|
||||
* Everything the installer prints also goes to Download/DroidDeck/tools.
|
||||
*/
|
||||
private fun unpackInRuntime(context: Context, c: Component, archive: File, tag: String, onProgress: (Progress) -> Unit): File? {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
val cache = File(root, MSI_CACHE)
|
||||
val dir = File(cache, ".x-$tag").apply { FileUtils.delete(this); mkdirs() }
|
||||
val inside = archive.relativeTo(root).path
|
||||
var problem: String? = null
|
||||
var ok = false
|
||||
val status = GuestCommand.run(context, listOf(MSI_INSTALL, "--unpack", "/$inside", "/$MSI_CACHE/${dir.name}"),
|
||||
logName = "wincomponents-${c.name}") { line ->
|
||||
when {
|
||||
line.startsWith("progress ") -> engineLine(line.removePrefix("progress ")).let { (text, _) -> onProgress(Progress(c.name, text, Phase.INSTALL, -1)) }
|
||||
line.startsWith("result ") -> ok = true
|
||||
line.startsWith("error ") -> problem = line.removePrefix("error ")
|
||||
}
|
||||
}
|
||||
if (status != 0 || !ok) {
|
||||
Log.w(TAG, "unpack ${archive.name}: ${problem ?: "status $status"}")
|
||||
FileUtils.delete(dir)
|
||||
return null
|
||||
}
|
||||
return dir
|
||||
}
|
||||
|
||||
/**
|
||||
* Downloads the component's package (.msi) or installer (.exe) into the runtime and has
|
||||
* droiddeck-msi-install lay it out in [staging]. Returns the installer's result (product,
|
||||
* version, counts, notes), or null and why. Everything the installer prints also goes to
|
||||
* files/logs/tools.
|
||||
*/
|
||||
private fun installPackage(context: Context, c: Component, step: Step, staging: File, onProgress: (Progress) -> Unit): Pair<JSONObject?, String> {
|
||||
private fun installMsi(context: Context, c: Component, step: Step, staging: File, onProgress: (String, Int) -> Unit): Pair<JSONObject?, String> {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
val url = step.str("url")
|
||||
val name = url.substringBefore('?').substringAfterLast('/')
|
||||
val cache = File(root, MSI_CACHE).apply { mkdirs() }
|
||||
val ext = if (listOf(step.str("file_name"), name).any { it.endsWith(".exe", ignoreCase = true) }) "exe" else "msi"
|
||||
val file = File(cache, "${c.name}-${c.steps.indexOf(step)}.$ext")
|
||||
val file = File(cache, "${c.name}.msi")
|
||||
try {
|
||||
if (!Downloader.downloadFile(url, file, false) { f -> onProgress(Progress(c.name, name, Phase.DOWNLOAD, if (f < 0) -1 else Math.round(f * 100f))) }) {
|
||||
if (!Downloader.downloadFile(url, file, false) { f -> onProgress("${c.name}: $name", if (f < 0) -1 else Math.round(f * 100f)) }) {
|
||||
return null to "download failed: $name"
|
||||
}
|
||||
step.str("file_checksum").takeIf { it.length == 32 }?.let { md5 ->
|
||||
if (!digest(file, "MD5").equals(md5, ignoreCase = true)) return null to "checksum mismatch: $name"
|
||||
}
|
||||
onProgress(Progress(c.name, "installing", Phase.INSTALL, 0))
|
||||
onProgress("${c.name}: installing", -1)
|
||||
var result: JSONObject? = null
|
||||
var problem: String? = null
|
||||
val status = GuestCommand.run(context, listOf(MSI_INSTALL, "/$MSI_CACHE/${file.name}", "/$STORE/${staging.name}"),
|
||||
logName = "wincomponents-${c.name}") { line ->
|
||||
when {
|
||||
line.startsWith("progress ") -> engineLine(line.removePrefix("progress ")).let { (text, pct) -> onProgress(Progress(c.name, text, Phase.INSTALL, pct)) }
|
||||
line.startsWith("progress ") -> onProgress("${c.name}: ${line.removePrefix("progress ")}", -1)
|
||||
line.startsWith("result ") -> result = runCatching { JSONObject(line.removePrefix("result ")) }.getOrNull()
|
||||
line.startsWith("error ") -> problem = line.removePrefix("error ")
|
||||
}
|
||||
@@ -429,7 +273,7 @@ object WinComponents {
|
||||
if (status != 0 || done == null) return null to (problem ?: "the installer stopped (status $status)")
|
||||
return done to ""
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "package ${c.name}", e)
|
||||
Log.e(TAG, "msi ${c.name}", e)
|
||||
return null to (e.message ?: "the installer failed")
|
||||
} finally {
|
||||
file.delete()
|
||||
|
||||
@@ -1,87 +0,0 @@
|
||||
package com.droiddeck.launcher.stores
|
||||
|
||||
import org.json.JSONObject
|
||||
|
||||
/**
|
||||
* What a cloud sync may do, decided from three views of each save file: the local copy, the cloud
|
||||
* copy, and the baseline - both as they were when this device last synced the game. Pure, so the
|
||||
* rules are tested on their own:
|
||||
*
|
||||
* - No upload before a download has completed once on this device (no baseline): a first launch
|
||||
* writes new profile files that must never replace the real saves in the cloud.
|
||||
* - The first download (no baseline) lets the cloud win where the two differ - the local folder is
|
||||
* backed up first.
|
||||
* - A file changed on both sides since the baseline is a conflict: neither side is overwritten; the
|
||||
* user picks Keep cloud or Keep local in Manage saves.
|
||||
* - Otherwise the side that changed since the baseline wins; one that changed on neither is left.
|
||||
*/
|
||||
object CloudPlan {
|
||||
/** One file as this device last saw it in sync: the local MD5, and the cloud's MD5 (when known) and time. */
|
||||
data class Entry(val localMd5: String, val cloudMd5: String?, val cloudModified: Long)
|
||||
|
||||
class Local(val md5: String)
|
||||
class Remote(val md5: String?, val modified: Long)
|
||||
|
||||
class Plan(val transfer: List<String>, val conflicts: List<String>, val same: List<String>, val refused: String? = null)
|
||||
|
||||
/** The cloud copy differs from what the baseline recorded of it. */
|
||||
private fun cloudChanged(r: Remote, b: Entry?): Boolean {
|
||||
if (b == null) return true
|
||||
if (r.md5 != null && b.cloudMd5 != null) return !r.md5.equals(b.cloudMd5, ignoreCase = true)
|
||||
// Times only (Epic's listing): the service's own clock, so a couple of seconds of slack.
|
||||
return r.modified > 0 && b.cloudModified > 0 && kotlin.math.abs(r.modified - b.cloudModified) > 2000
|
||||
}
|
||||
|
||||
private fun localChanged(l: Local, b: Entry?): Boolean = b == null || !l.md5.equals(b.localMd5, ignoreCase = true)
|
||||
|
||||
private fun same(l: Local, r: Remote): Boolean = r.md5 != null && r.md5.equals(l.md5, ignoreCase = true)
|
||||
|
||||
/** Cloud → device. [baseline] null = this device never synced the game. */
|
||||
fun down(local: Map<String, Local>, remote: Map<String, Remote>, baseline: Map<String, Entry>?): Plan {
|
||||
val transfer = ArrayList<String>(); val conflicts = ArrayList<String>(); val same = ArrayList<String>()
|
||||
for ((name, r) in remote) {
|
||||
val l = local[name]
|
||||
val b = baseline?.get(name)
|
||||
when {
|
||||
l == null -> transfer += name
|
||||
same(l, r) -> same += name
|
||||
baseline == null -> transfer += name
|
||||
cloudChanged(r, b) && localChanged(l, b) -> conflicts += name
|
||||
cloudChanged(r, b) -> transfer += name
|
||||
}
|
||||
}
|
||||
return Plan(transfer, conflicts, same)
|
||||
}
|
||||
|
||||
/** Device → cloud. Refused outright without a baseline. */
|
||||
fun up(local: Map<String, Local>, remote: Map<String, Remote>, baseline: Map<String, Entry>?): Plan {
|
||||
if (baseline == null) return Plan(emptyList(), emptyList(), emptyList(), refused = "no-baseline")
|
||||
val transfer = ArrayList<String>(); val conflicts = ArrayList<String>(); val same = ArrayList<String>()
|
||||
for ((name, l) in local) {
|
||||
val r = remote[name]
|
||||
val b = baseline[name]
|
||||
when {
|
||||
r == null -> transfer += name
|
||||
same(l, r) -> same += name
|
||||
localChanged(l, b) && cloudChanged(r, b) -> conflicts += name
|
||||
localChanged(l, b) -> transfer += name
|
||||
}
|
||||
}
|
||||
return Plan(transfer, conflicts, same)
|
||||
}
|
||||
|
||||
fun toJson(baseline: Map<String, Entry>): String = JSONObject().apply {
|
||||
for ((k, e) in baseline) put(k, JSONObject().put("l", e.localMd5).put("c", e.cloudMd5 ?: "").put("t", e.cloudModified))
|
||||
}.toString()
|
||||
|
||||
fun fromJson(text: String?): Map<String, Entry>? {
|
||||
if (text == null) return null
|
||||
return runCatching {
|
||||
val o = JSONObject(text)
|
||||
o.keys().asSequence().associateWith { k ->
|
||||
val e = o.getJSONObject(k)
|
||||
Entry(e.optString("l"), e.optString("c").ifEmpty { null }, e.optLong("t", -1L))
|
||||
}
|
||||
}.getOrNull()
|
||||
}
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
/*
|
||||
* Cloud-save folder resolution for GOG and Epic games, after Bannerlator's GogCloudSavePaths and
|
||||
* EpicCloudSavePaths (device-proven there, August 2026): a store's save-location template expanded
|
||||
* against the game's Proton prefix and its install folder.
|
||||
*/
|
||||
package com.droiddeck.launcher.stores
|
||||
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* Where a store keeps a game's saves on Windows, made concrete inside this game's Proton prefix.
|
||||
*
|
||||
* GOG gives a template per game in its public remote-config (`cloudStorage.locations[].location`):
|
||||
* a leading `<?TOKEN?>` (or `%TOKEN%`) and a path, e.g. ELDERBORN's
|
||||
* `<?APPLICATION_DATA_LOCAL_LOW?>/Hyperstrange/ELDERBORN`. Epic gives `CloudSaveFolder` in the
|
||||
* game's catalog attributes: a leading `{Token}`, with `{EpicId}` / `{AppName}` inside, e.g.
|
||||
* `{AppData}/Game/Saved/SaveGames`. Profile tokens map under the prefix's Wine user
|
||||
* (`drive_c/users/steamuser`), the install tokens to the game's folder. The path is walked against
|
||||
* what is on disk case-insensitively; a result outside its boundary is refused, never guessed.
|
||||
*/
|
||||
object CloudSavePaths {
|
||||
/** The Wine user every prefix has (Proton's). */
|
||||
fun profile(prefix: File): File = File(prefix, "drive_c/users/steamuser")
|
||||
|
||||
/** Expands a GOG location template; null for an unknown token or an escape. */
|
||||
fun gog(template: String, prefix: File, install: File): File? {
|
||||
val norm = template.replace('\\', '/').trim().trimStart('/')
|
||||
val match = Regex("^(<\\?[^?>]+\\?>|%[^%]+%)").find(norm) ?: return null
|
||||
val token = match.groupValues[1].trim('<', '>', '?', '%').uppercase()
|
||||
val profile = profile(prefix)
|
||||
val (base, boundary) = when (token) {
|
||||
"INSTALL" -> install to install
|
||||
"SAVED_GAMES" -> File(profile, "Saved Games") to profile
|
||||
"DOCUMENTS" -> File(profile, "Documents") to profile
|
||||
"APPLICATION_DATA_LOCAL", "LOCALAPPDATA" -> File(profile, "AppData/Local") to profile
|
||||
"APPLICATION_DATA_LOCAL_LOW" -> File(profile, "AppData/LocalLow") to profile
|
||||
"APPLICATION_DATA_ROAMING", "APPDATA" -> File(profile, "AppData/Roaming") to profile
|
||||
"USERPROFILE" -> profile to profile
|
||||
"PROGRAMDATA" -> File(prefix, "drive_c/ProgramData").let { it to it }
|
||||
else -> return null
|
||||
}
|
||||
return walk(base, boundary, norm.substring(match.value.length), fuzzy = false)
|
||||
}
|
||||
|
||||
/** Expands an Epic CloudSaveFolder; null for an unknown token or an escape. */
|
||||
fun epic(template: String, prefix: File, install: File, accountId: String, appName: String): File? {
|
||||
val norm = template.replace('\\', '/').trim().trimStart('/')
|
||||
val match = Regex("^\\{([^}]+)\\}").find(norm) ?: return null
|
||||
val profile = profile(prefix)
|
||||
val (base, boundary) = when (match.groupValues[1].lowercase()) {
|
||||
"installdir" -> install to install
|
||||
"userprofile" -> profile to profile
|
||||
"userdir" -> File(profile, "Documents") to profile
|
||||
"usersavedgames" -> File(profile, "Saved Games") to profile
|
||||
"appdata", "localappdata" -> File(profile, "AppData/Local") to profile
|
||||
"roamingappdata" -> File(profile, "AppData/Roaming") to profile
|
||||
else -> return null
|
||||
}
|
||||
val rest = norm.substring(match.value.length)
|
||||
.replace("{epicid}", accountId, ignoreCase = true)
|
||||
.replace("{appname}", appName, ignoreCase = true)
|
||||
return walk(base, boundary, rest, fuzzy = true)
|
||||
}
|
||||
|
||||
/**
|
||||
* Each segment matched against the folder's entries case-insensitively (and, for Epic, by letters
|
||||
* and digits alone when that names exactly one), else taken as written - a download creates it.
|
||||
*/
|
||||
private fun walk(base: File, boundary: File, rest: String, fuzzy: Boolean): File? {
|
||||
var dir = base
|
||||
for (seg in rest.trimStart('/').split('/').filter { it.isNotEmpty() && it != "." }) {
|
||||
if (seg == "..") { dir = dir.parentFile ?: return null; continue }
|
||||
val kids = dir.listFiles()
|
||||
val existing = kids?.firstOrNull { it.name.equals(seg, ignoreCase = true) }
|
||||
?: if (fuzzy) kids?.filter { squash(it.name) == squash(seg) && squash(seg).isNotEmpty() }?.singleOrNull() else null
|
||||
dir = existing ?: File(dir, seg)
|
||||
}
|
||||
val bound = runCatching { boundary.canonicalPath }.getOrNull() ?: return null
|
||||
val dest = runCatching { dir.canonicalPath }.getOrNull() ?: return null
|
||||
return if (dest == bound || dest.startsWith(bound + File.separator)) dir else null
|
||||
}
|
||||
|
||||
private fun squash(s: String) = s.lowercase().filter { it.isLetterOrDigit() }
|
||||
}
|
||||
@@ -1,387 +0,0 @@
|
||||
package com.droiddeck.launcher.stores
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.frontend.AddedGames
|
||||
import com.droiddeck.launcher.frontend.Library
|
||||
import com.droiddeck.launcher.stores.epic.EpicApiClient
|
||||
import com.droiddeck.launcher.stores.epic.EpicCredentialStore
|
||||
import com.droiddeck.launcher.stores.epic.EpicPrefs
|
||||
import com.droiddeck.launcher.stores.gog.GogAuth
|
||||
import com.droiddeck.launcher.stores.gog.GogPrefs
|
||||
import java.io.File
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.security.MessageDigest
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.concurrent.TimeUnit
|
||||
import org.json.JSONObject
|
||||
|
||||
/**
|
||||
* GOG and Epic cloud saves for an installed store game: before a launch the cloud copy is brought
|
||||
* down where it is newer, after the game exits what changed goes up - newest wins, file by file.
|
||||
* Before a download overwrites anything, the folder is copied to the app's storage (the last
|
||||
* [BACKUPS] per game). Both launch paths reach it: the compat tool's request from
|
||||
* droiddeck-store-launch ([StoreLaunchRequests]) for every launch, and the Games tab's Manage saves.
|
||||
*
|
||||
* The save folder: GOG's remote-config location template (by the game's Galaxy client id) or
|
||||
* Epic's CloudSaveFolder catalog attribute, cached per game, made concrete by [CloudSavePaths]
|
||||
* inside the game's Proton prefix. A game whose store gives none has no cloud saves.
|
||||
*/
|
||||
object CloudSaves {
|
||||
private const val TAG = "CloudSaves"
|
||||
private const val BACKUPS = 3
|
||||
private const val PARALLEL = 6
|
||||
|
||||
/** What a sync did, for the log and the Manage saves row. */
|
||||
/**
|
||||
* What a sync did, for the log and the Manage saves row. [result]: ok, skipped (nothing to do or
|
||||
* not possible: [reason] says why), deferred (no prefix yet; it runs once Proton makes one),
|
||||
* failed. [conflicts]: files changed on both sides, left alone.
|
||||
*/
|
||||
class Result(val result: String, val files: Int, val bytes: Long, val reason: String, val conflicts: Int = 0) {
|
||||
val ok: Boolean get() = result != "failed"
|
||||
val line: String get() = "result=$result files=$files bytes=$bytes reason=$reason" + if (conflicts > 0) " conflicts=$conflicts" else ""
|
||||
}
|
||||
|
||||
/** A game's cloud state for the Manage saves row. */
|
||||
class Status(val supported: Boolean, val folder: File?, val lastSync: Long, val reason: String, val conflicts: List<String> = emptyList())
|
||||
|
||||
private fun game(context: Context, store: Store, id: String): Pair<File, StoreGameSidecar>? =
|
||||
StoreInstallRoot.gameFolders(context).firstNotNullOfOrNull { f ->
|
||||
StoreGameSidecar.read(f)?.takeIf { it.store == store && it.id == id && it.isInstalled }?.let { f to it }
|
||||
}
|
||||
|
||||
/** The game's prefix: compatdata/<its shortcut appid>/pfx, wherever that library is. */
|
||||
fun prefix(context: Context, folder: File): File? {
|
||||
val appId = AddedGames.scan(context).firstOrNull { it.folder.absolutePath == folder.absolutePath }?.appId ?: return null
|
||||
return Library.protonPrefix(context, appId and 0xFFFFFFFFL)
|
||||
}
|
||||
|
||||
private fun prefs(context: Context, store: Store) = if (store == Store.GOG) GogPrefs.get(context) else EpicPrefs.get(context)
|
||||
|
||||
fun lastSync(context: Context, store: Store, id: String): Long = prefs(context, store).getLong("cloud_sync_$id", 0L)
|
||||
|
||||
private fun markSynced(context: Context, store: Store, id: String) = prefs(context, store).edit().putLong("cloud_sync_$id", System.currentTimeMillis()).apply()
|
||||
|
||||
// ---- the save folder ------------------------------------------------------------------------
|
||||
|
||||
/** The store's template for this game: cached, else fetched; "" when the store gives none, null when it could not be asked. */
|
||||
fun template(context: Context, store: Store, id: String, folder: File, sidecar: StoreGameSidecar): String? {
|
||||
val p = prefs(context, store)
|
||||
if (p.contains("cloud_template_$id")) return p.getString("cloud_template_$id", "")
|
||||
val fetched = when (store) {
|
||||
Store.GOG -> gogTemplate(context, id, folder)
|
||||
Store.EPIC -> {
|
||||
val token = EpicCredentialStore.getValidAccessToken(context) ?: return null
|
||||
val ns = sidecar.extra["namespace"].orEmpty()
|
||||
val item = sidecar.extra["catalogItemId"].orEmpty()
|
||||
if (ns.isEmpty() || item.isEmpty()) "" else EpicApiClient.getCustomAttribute(token, ns, item, "CloudSaveFolder")
|
||||
}
|
||||
Store.AMAZON -> ""
|
||||
} ?: return null
|
||||
p.edit().putString("cloud_template_$id", fetched).apply()
|
||||
Log.i(TAG, "cloud ${store.id} $id template ${if (fetched.isEmpty()) "none" else "found"}")
|
||||
return fetched
|
||||
}
|
||||
|
||||
private fun gogClientId(context: Context, id: String, folder: File): String? =
|
||||
GogPrefs.get(context).getString("client_id_$id", null)?.ifEmpty { null }
|
||||
?: runCatching { JSONObject(File(folder, "goggame-$id.info").readText()).optString("clientId").ifEmpty { null } }.getOrNull()
|
||||
|
||||
/** GOG's public remote-config: `content.Windows.cloudStorage.locations`, the one named "saves" first. */
|
||||
private fun gogTemplate(context: Context, id: String, folder: File): String? {
|
||||
val clientId = gogClientId(context, id, folder) ?: return ""
|
||||
return try {
|
||||
val c = URL("https://remote-config.gog.com/components/galaxy_client/clients/$clientId?component_version=2.0.45").openConnection() as HttpURLConnection
|
||||
c.connectTimeout = 15_000; c.readTimeout = 15_000
|
||||
c.setRequestProperty("User-Agent", "GOG Galaxy")
|
||||
if (c.responseCode !in 200..299) { c.disconnect(); return null }
|
||||
val cloud = JSONObject(c.inputStream.bufferedReader().readText()).optJSONObject("content")?.optJSONObject("Windows")?.optJSONObject("cloudStorage")
|
||||
c.disconnect()
|
||||
if (cloud?.optBoolean("enabled", false) != true) return ""
|
||||
val locations = cloud.optJSONArray("locations") ?: return ""
|
||||
val all = (0 until locations.length()).mapNotNull { locations.optJSONObject(it) }
|
||||
(all.firstOrNull { it.optString("name").equals("saves", true) } ?: all.firstOrNull())?.optString("location").orEmpty()
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "gog remote-config: ${e.javaClass.simpleName}")
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
/** The concrete save folder in the prefix, or null with why. */
|
||||
private fun saveFolder(context: Context, store: Store, id: String): Pair<File?, String> {
|
||||
val (folder, sidecar) = game(context, store, id) ?: return null to "not-installed"
|
||||
val template = template(context, store, id, folder, sidecar) ?: return null to "store-unreachable"
|
||||
if (template.isEmpty()) return null to "no-cloud-saves"
|
||||
val pfx = prefix(context, folder) ?: return null to "no-prefix"
|
||||
val dir = when (store) {
|
||||
Store.GOG -> CloudSavePaths.gog(template, pfx, folder)
|
||||
Store.EPIC -> CloudSavePaths.epic(template, pfx, folder, EpicCredentialStore.load(context)?.accountId.orEmpty(), id)
|
||||
Store.AMAZON -> null
|
||||
}
|
||||
return dir to (if (dir == null) "unresolved" else "ok")
|
||||
}
|
||||
|
||||
fun status(context: Context, store: Store, id: String): Status {
|
||||
val (dir, reason) = saveFolder(context, store, id)
|
||||
return Status(reason != "no-cloud-saves" && reason != "not-installed", dir, lastSync(context, store, id), reason, conflicts(context, store, id))
|
||||
}
|
||||
|
||||
// ---- transport ------------------------------------------------------------------------------
|
||||
|
||||
private fun transport(context: Context, store: Store, id: String, folder: File): CloudTransport? = when (store) {
|
||||
Store.GOG -> {
|
||||
val account = StoreAccounts.read(context, Store.GOG)
|
||||
val userId = account?.optString("user_id").orEmpty()
|
||||
val galaxy = GogAuth.validToken(context)
|
||||
val clientId = gogClientId(context, id, folder)
|
||||
if (userId.isEmpty() || galaxy == null || clientId == null) null
|
||||
else GogCloud(userId, clientId, gogScopedToken(context, id, clientId, account?.optString("refresh_token").orEmpty()) ?: galaxy)
|
||||
}
|
||||
Store.EPIC -> {
|
||||
val token = EpicCredentialStore.getValidAccessToken(context)
|
||||
val account = EpicCredentialStore.load(context)?.accountId.orEmpty()
|
||||
if (token == null || account.isEmpty()) null else EpicCloud(account, id, token)
|
||||
}
|
||||
Store.AMAZON -> null
|
||||
}
|
||||
|
||||
/** GOG cloud storage wants a token issued to the game's own client: the Galaxy refresh token, exchanged with the game's id and secret. */
|
||||
private fun gogScopedToken(context: Context, id: String, clientId: String, refresh: String): String? {
|
||||
val secret = GogPrefs.get(context).getString("client_secret_$id", null)?.ifEmpty { null } ?: return null
|
||||
if (refresh.isEmpty()) return null
|
||||
return try {
|
||||
val enc = { s: String -> java.net.URLEncoder.encode(s, "UTF-8") }
|
||||
val c = URL("https://auth.gog.com/token?client_id=${enc(clientId)}&client_secret=${enc(secret)}&grant_type=refresh_token&refresh_token=${enc(refresh)}").openConnection() as HttpURLConnection
|
||||
c.connectTimeout = 15_000; c.readTimeout = 15_000
|
||||
c.setRequestProperty("User-Agent", "GOG Galaxy")
|
||||
if (c.responseCode != 200) { c.disconnect(); return null }
|
||||
JSONObject(c.inputStream.bufferedReader().readText()).optString("access_token").ifEmpty { null }.also { c.disconnect() }
|
||||
} catch (e: Exception) { null }
|
||||
}
|
||||
|
||||
// ---- sync -----------------------------------------------------------------------------------
|
||||
|
||||
private fun baseline(context: Context, store: Store, id: String): Map<String, CloudPlan.Entry>? =
|
||||
CloudPlan.fromJson(prefs(context, store).getString("cloud_baseline_$id", null))
|
||||
|
||||
private fun saveBaseline(context: Context, store: Store, id: String, b: Map<String, CloudPlan.Entry>) =
|
||||
prefs(context, store).edit().putString("cloud_baseline_$id", CloudPlan.toJson(b)).apply()
|
||||
|
||||
/** Files changed on both sides since the last sync, waiting for Keep cloud / Keep local. */
|
||||
fun conflicts(context: Context, store: Store, id: String): List<String> =
|
||||
prefs(context, store).getString("cloud_conflicts_$id", "").orEmpty().split('\n').filter { it.isNotEmpty() }
|
||||
|
||||
private fun saveConflicts(context: Context, store: Store, id: String, names: Collection<String>) =
|
||||
prefs(context, store).edit().putString("cloud_conflicts_$id", names.joinToString("\n")).apply()
|
||||
|
||||
/** Cloud → device where the cloud copy changed (the first time: wherever it differs). [force]: conflicts too (Keep cloud). Blocking. */
|
||||
fun download(context: Context, store: Store, id: String, force: Boolean = false): Result =
|
||||
sync(context, store, id, "down") { dir, cloud -> downWith(context, store, id, dir, cloud, force) }
|
||||
|
||||
/** Device → cloud where the local copy changed, once a download has set the baseline. [force]: conflicts too (Keep local). Blocking. */
|
||||
fun upload(context: Context, store: Store, id: String, force: Boolean = false): Result =
|
||||
sync(context, store, id, "up") { dir, cloud -> upWith(context, store, id, dir, cloud, force) }
|
||||
|
||||
fun keepCloud(context: Context, store: Store, id: String): Result = download(context, store, id, force = true)
|
||||
fun keepLocal(context: Context, store: Store, id: String): Result = upload(context, store, id, force = true)
|
||||
|
||||
/**
|
||||
* The pre-launch download, or - when Proton has not made the game's prefix yet (a first launch)
|
||||
* - a deferred one: answered at once, then run in the background as soon as the prefix's user
|
||||
* folder appears (within [PREFIX_WAIT_MS]), so the launch is not held up for it.
|
||||
*/
|
||||
fun downloadOrDefer(context: Context, store: Store, id: String): Result {
|
||||
val app = context.applicationContext
|
||||
val g = game(app, store, id) ?: return done(store, id, "down", Result("skipped", 0, 0, "not-installed"))
|
||||
if (!g.second.cloud) return done(store, id, "down", Result("skipped", 0, 0, "off"))
|
||||
if (prefix(app, g.first)?.let { CloudSavePaths.profile(it).isDirectory } == true) return download(app, store, id)
|
||||
Thread({
|
||||
val end = System.currentTimeMillis() + PREFIX_WAIT_MS
|
||||
while (System.currentTimeMillis() < end) {
|
||||
if (prefix(app, g.first)?.let { CloudSavePaths.profile(it).isDirectory } == true) { download(app, store, id); return@Thread }
|
||||
Thread.sleep(2000)
|
||||
}
|
||||
done(store, id, "down", Result("skipped", 0, 0, "no-prefix"))
|
||||
}, "cloud-deferred").start()
|
||||
return done(store, id, "down", Result("deferred", 0, 0, "no-prefix"))
|
||||
}
|
||||
|
||||
private const val PREFIX_WAIT_MS = 60_000L
|
||||
|
||||
private fun sync(context: Context, store: Store, id: String, way: String, body: (File, CloudTransport) -> Result): Result {
|
||||
val result = try {
|
||||
val g = game(context, store, id)
|
||||
when {
|
||||
g == null -> Result("skipped", 0, 0, "not-installed")
|
||||
!g.second.cloud -> Result("skipped", 0, 0, "off")
|
||||
else -> {
|
||||
val (dir, reason) = saveFolder(context, store, id)
|
||||
val cloud = if (dir != null) transport(context, store, id, g.first) else null
|
||||
when {
|
||||
dir == null -> Result("skipped", 0, 0, reason)
|
||||
cloud == null -> Result("skipped", 0, 0, "not-signed-in")
|
||||
else -> body(dir, cloud).also { if (it.result == "ok") markSynced(context, store, id) }
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e: NoCloudSaves) {
|
||||
prefs(context, store).edit().putString("cloud_template_$id", "").apply()
|
||||
Result("skipped", 0, 0, "no-cloud-saves")
|
||||
} catch (e: Exception) {
|
||||
Result("failed", 0, 0, e.javaClass.simpleName)
|
||||
}
|
||||
return done(store, id, way, result)
|
||||
}
|
||||
|
||||
private fun done(store: Store, id: String, way: String, r: Result): Result {
|
||||
Log.i(TAG, "cloud ${store.id} $id $way ${r.line}")
|
||||
StoresState.logLine("cloud ${store.id} $id $way ${r.line}")
|
||||
return r
|
||||
}
|
||||
|
||||
private fun localFiles(dir: File): Map<String, File> =
|
||||
if (!dir.isDirectory) emptyMap()
|
||||
else dir.walkTopDown().filter { it.isFile }.associateBy { it.relativeTo(dir).path.replace(File.separatorChar, '/') }
|
||||
|
||||
internal fun md5(f: File): String = md5(f.readBytes())
|
||||
|
||||
internal fun md5(data: ByteArray): String = MessageDigest.getInstance("MD5").digest(data).joinToString("") { "%02x".format(it) }
|
||||
|
||||
/** The cloud listing, with MD5 and time filled in (one HEAD each where the listing lacks them, in parallel). */
|
||||
private fun remote(cloud: CloudTransport, wanted: (String) -> Boolean): Map<String, CloudFile> {
|
||||
val files = cloud.list()
|
||||
val pool = Executors.newFixedThreadPool(PARALLEL, com.droiddeck.launcher.stores.download.DownloadQueue.workerFactory("cloud"))
|
||||
for (f in files) if (wanted(f.name)) pool.execute { runCatching { cloud.details(f) } }
|
||||
pool.shutdown(); pool.awaitTermination(2, TimeUnit.MINUTES)
|
||||
return files.associateBy { it.name }
|
||||
}
|
||||
|
||||
internal fun downWith(context: Context, store: Store, id: String, dir: File, cloud: CloudTransport, force: Boolean): Result {
|
||||
val files = localFiles(dir)
|
||||
val remote = remote(cloud) { it in files }
|
||||
val local = files.mapValues { CloudPlan.Local(md5(it.value)) }
|
||||
val base = baseline(context, store, id)
|
||||
val plan = CloudPlan.down(local, remote.mapValues { CloudPlan.Remote(it.value.md5, it.value.modifiedMs) }, base)
|
||||
val take = if (force) plan.transfer + plan.conflicts else plan.transfer
|
||||
if (take.isNotEmpty() && files.isNotEmpty()) backup(context, store, id, dir, "local")
|
||||
val next = HashMap(base.orEmpty())
|
||||
var bytes = 0L
|
||||
for (name in take) {
|
||||
val f = remote[name] ?: continue
|
||||
val (data, modified) = cloud.get(f)
|
||||
val dest = File(dir, name)
|
||||
if (!dest.canonicalPath.startsWith(dir.canonicalPath + File.separator)) continue
|
||||
dest.parentFile?.mkdirs()
|
||||
dest.writeBytes(data)
|
||||
if (modified > 0) dest.setLastModified(modified)
|
||||
bytes += data.size
|
||||
next[name] = CloudPlan.Entry(md5(data), f.md5, if (modified > 0) modified else f.modifiedMs)
|
||||
}
|
||||
for (name in plan.same) remote[name]?.let { r -> next[name] = CloudPlan.Entry(local.getValue(name).md5, r.md5, r.modifiedMs) }
|
||||
// A download that completed sets the baseline even when the cloud was empty: uploads may follow.
|
||||
saveBaseline(context, store, id, next)
|
||||
val left = if (force) emptyList() else plan.conflicts
|
||||
saveConflicts(context, store, id, left)
|
||||
return Result("ok", take.size, bytes, if (take.isEmpty()) "up-to-date" else "downloaded", left.size)
|
||||
}
|
||||
|
||||
internal fun upWith(context: Context, store: Store, id: String, dir: File, cloud: CloudTransport, force: Boolean): Result {
|
||||
val base = baseline(context, store, id) ?: return Result("skipped", 0, 0, "no-baseline")
|
||||
val files = localFiles(dir)
|
||||
if (files.isEmpty()) return Result("skipped", 0, 0, "nothing-local")
|
||||
val remote = remote(cloud) { it in files }
|
||||
val local = files.mapValues { CloudPlan.Local(md5(it.value)) }
|
||||
val plan = CloudPlan.up(local, remote.mapValues { CloudPlan.Remote(it.value.md5, it.value.modifiedMs) }, base)
|
||||
val send = if (force) plan.transfer + plan.conflicts else plan.transfer
|
||||
val next = HashMap(base)
|
||||
for (name in plan.same) remote[name]?.let { r -> next[name] = CloudPlan.Entry(local.getValue(name).md5, r.md5, r.modifiedMs) }
|
||||
if (send.isNotEmpty()) {
|
||||
// The cloud copies about to be replaced are kept first, as a download keeps the local ones.
|
||||
backupCloud(context, store, id, cloud, send.mapNotNull { remote[it] })
|
||||
val data = send.associateWith { files.getValue(it).readBytes() }
|
||||
val stamped = cloud.put(data)
|
||||
for ((name, t) in stamped) if (t > 0) files[name]?.setLastModified(t)
|
||||
val after = remote(cloud) { it in data }
|
||||
for (name in data.keys) {
|
||||
val r = after[name]
|
||||
next[name] = CloudPlan.Entry(md5(data.getValue(name)), r?.md5, r?.modifiedMs ?: stamped[name] ?: -1L)
|
||||
}
|
||||
}
|
||||
saveBaseline(context, store, id, next)
|
||||
val left = if (force) emptyList() else plan.conflicts
|
||||
saveConflicts(context, store, id, left)
|
||||
return Result("ok", send.size, send.sumOf { files.getValue(it).length() }, if (send.isEmpty()) "up-to-date" else "uploaded", left.size)
|
||||
}
|
||||
|
||||
// ---- uploads that do not depend on one hook ---------------------------------------------------
|
||||
|
||||
/**
|
||||
* A game launched with cloud saves is marked dirty in the app's storage when its pre-launch step
|
||||
* runs. The upload happens on the first of: the compat tool's exit request (`exit`), the end of
|
||||
* the session (`session-end`), or the app's next start for a mark a killed app left (`recovery`)
|
||||
* - so a session closed from the drawer, a game Steam killed, or a crash still uploads. The mark
|
||||
* goes only after an upload that went through, or one skipped on purpose with its reason logged.
|
||||
*/
|
||||
private fun marks(context: Context) = context.applicationContext.getSharedPreferences("stores.cloud", Context.MODE_PRIVATE)
|
||||
|
||||
fun markDirty(context: Context, store: Store, id: String) {
|
||||
marks(context).edit().putLong("dirty:${store.id}:$id", System.currentTimeMillis()).apply()
|
||||
}
|
||||
|
||||
fun dirty(context: Context): List<Pair<Store, String>> = marks(context).all.keys.mapNotNull { k ->
|
||||
val parts = k.split(':', limit = 3)
|
||||
if (parts.size == 3 && parts[0] == "dirty") Store.byId(parts[1])?.let { it to parts[2] } else null
|
||||
}
|
||||
|
||||
private val markLock = Any()
|
||||
|
||||
/** Why a skip is final: retrying cannot change it, so the mark goes. */
|
||||
private val FINAL_SKIPS = setOf("off", "no-cloud-saves", "no-baseline", "not-installed", "nothing-local")
|
||||
|
||||
/** Uploads [id] if it is marked dirty; null when it is not (another trigger got there first). */
|
||||
fun uploadDirty(context: Context, store: Store, id: String, trigger: String): Result? = synchronized(markLock) {
|
||||
val key = "dirty:${store.id}:$id"
|
||||
if (!marks(context).contains(key)) return null
|
||||
val r = sync(context, store, id, "up trigger=$trigger") { dir, cloud -> upWith(context, store, id, dir, cloud, force = false) }
|
||||
if (r.result == "ok" || (r.result == "skipped" && r.reason in FINAL_SKIPS)) marks(context).edit().remove(key).apply()
|
||||
r
|
||||
}
|
||||
|
||||
/**
|
||||
* Every dirty game, uploaded; [running] says a game session is up, in which case `recovery` waits
|
||||
* - a marked game may be the one running.
|
||||
*/
|
||||
fun uploadAllDirty(context: Context, trigger: String, running: Boolean = com.droiddeck.launcher.session.SessionState.running) {
|
||||
if (trigger == "recovery" && running) return
|
||||
for ((store, id) in dirty(context)) uploadDirty(context, store, id, trigger)
|
||||
}
|
||||
|
||||
private fun backupRoot(context: Context, store: Store, id: String) =
|
||||
File(context.filesDir, "stores/cloud-backups/${store.id}-${id.replace(Regex("[^A-Za-z0-9._-]"), "_")}")
|
||||
|
||||
/** The local folder as it is, before a download changes it; the last [BACKUPS] of each kind are kept. */
|
||||
private fun backup(context: Context, store: Store, id: String, dir: File, kind: String) {
|
||||
val root = backupRoot(context, store, id)
|
||||
runCatching { dir.copyRecursively(File(root, "$kind-${System.currentTimeMillis()}"), overwrite = true) }
|
||||
prune(root, kind)
|
||||
}
|
||||
|
||||
private fun backupCloud(context: Context, store: Store, id: String, cloud: CloudTransport, files: List<CloudFile>) {
|
||||
if (files.isEmpty()) return
|
||||
val root = backupRoot(context, store, id)
|
||||
val target = File(root, "cloud-${System.currentTimeMillis()}")
|
||||
for (f in files) {
|
||||
val dest = File(target, f.name)
|
||||
if (!dest.canonicalPath.startsWith(target.canonicalPath + File.separator)) continue
|
||||
dest.parentFile?.mkdirs()
|
||||
dest.writeBytes(cloud.get(f).first)
|
||||
}
|
||||
prune(root, "cloud")
|
||||
}
|
||||
|
||||
private fun prune(root: File, kind: String) {
|
||||
root.listFiles { f -> f.name.startsWith("$kind-") }?.sortedByDescending { it.name }?.drop(BACKUPS)?.forEach { it.deleteRecursively() }
|
||||
}
|
||||
}
|
||||
@@ -1,191 +0,0 @@
|
||||
/*
|
||||
* The two stores' cloud-save services, after Bannerlator's GogCloudSaveManager and
|
||||
* EpicCloudSaveManager (device-proven there, August 2026): GOG's cloudstorage (one object per
|
||||
* file, Last-Modified and an MD5 ETag on a HEAD) and Epic's savesync data storage (a listing with
|
||||
* lastModified and signed read links; signed write links asked for per upload).
|
||||
*/
|
||||
package com.droiddeck.launcher.stores
|
||||
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.net.URLEncoder
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Locale
|
||||
import java.util.TimeZone
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
|
||||
/** One file in a game's cloud: its key (a path with '/'), when it was written (-1 unknown) and its MD5 when known. */
|
||||
class CloudFile(val name: String, var modifiedMs: Long, var md5: String? = null, val readLink: String? = null)
|
||||
|
||||
/** A store's cloud for one game. Every call is blocking network. */
|
||||
interface CloudTransport {
|
||||
fun list(): List<CloudFile>
|
||||
/** Fills in [CloudFile.modifiedMs] / [CloudFile.md5] where the listing left them out. */
|
||||
fun details(file: CloudFile) {}
|
||||
/** The file's bytes and its cloud time (-1 unknown). */
|
||||
fun get(file: CloudFile): Pair<ByteArray, Long>
|
||||
/** Writes [files] (key → bytes); the cloud times assigned, where the service says (-1 unknown). */
|
||||
fun put(files: Map<String, ByteArray>): Map<String, Long>
|
||||
}
|
||||
|
||||
private const val TIMEOUT = 30_000
|
||||
|
||||
private fun open(url: String, method: String, token: String?, ua: String): HttpURLConnection =
|
||||
(URL(url).openConnection() as HttpURLConnection).apply {
|
||||
requestMethod = method
|
||||
connectTimeout = TIMEOUT
|
||||
readTimeout = TIMEOUT
|
||||
setRequestProperty("User-Agent", ua)
|
||||
if (token != null) setRequestProperty("Authorization", "Bearer $token")
|
||||
}
|
||||
|
||||
private fun HttpURLConnection.body(): ByteArray = inputStream.use { input ->
|
||||
ByteArrayOutputStream().also { input.copyTo(it) }.toByteArray()
|
||||
}
|
||||
|
||||
private fun httpDate(s: String?): Long = try {
|
||||
SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US).apply { timeZone = TimeZone.getTimeZone("GMT") }.parse(s!!.trim())?.time ?: -1L
|
||||
} catch (e: Exception) { -1L }
|
||||
|
||||
internal fun isoDate(s: String?): Long {
|
||||
if (s == null || s.length < 19) return -1L
|
||||
return try {
|
||||
java.util.Calendar.getInstance(TimeZone.getTimeZone("UTC")).apply {
|
||||
clear()
|
||||
set(s.substring(0, 4).toInt(), s.substring(5, 7).toInt() - 1, s.substring(8, 10).toInt(),
|
||||
s.substring(11, 13).toInt(), s.substring(14, 16).toInt(), s.substring(17, 19).toInt())
|
||||
}.timeInMillis
|
||||
} catch (e: Exception) { -1L }
|
||||
}
|
||||
|
||||
/** Thrown when the store says the game has no cloud saves for this client. */
|
||||
class NoCloudSaves : Exception("no cloud saves")
|
||||
|
||||
/** GOG cloudstorage: `/v1/<userId>/<clientId>[/<key>]`. */
|
||||
class GogCloud(private val userId: String, private val clientId: String, private val token: String) : CloudTransport {
|
||||
private val base = "https://cloudstorage.gog.com/v1/$userId/$clientId"
|
||||
private val ua = "GOG Galaxy"
|
||||
|
||||
/** A path segment: '+' from a space is wrong in a path (it stores a second, '+'-named copy). */
|
||||
private fun key(name: String) = URLEncoder.encode(name, "UTF-8").replace("+", "%20")
|
||||
|
||||
override fun list(): List<CloudFile> {
|
||||
val c = open(base, "GET", token, ua)
|
||||
val code = c.responseCode
|
||||
if (code == 404) { c.disconnect(); return emptyList() }
|
||||
if (code !in 200..299) {
|
||||
val err = runCatching { c.errorStream?.readBytes()?.decodeToString().orEmpty() }.getOrDefault("")
|
||||
c.disconnect()
|
||||
if ("not_enabled_for_client" in err || "disabled" in err) throw NoCloudSaves()
|
||||
throw java.io.IOException("GOG cloud list HTTP $code")
|
||||
}
|
||||
val text = c.body().decodeToString().trim()
|
||||
c.disconnect()
|
||||
if (text.isEmpty() || text == "[]") return emptyList()
|
||||
// A plain newline-separated list of keys (checked on device); a JSON array is read too.
|
||||
if (text.startsWith("[")) {
|
||||
val a = JSONArray(text)
|
||||
return (0 until a.length()).mapNotNull { a.optJSONObject(it) }.mapNotNull { o ->
|
||||
val n = o.optString("name").ifEmpty { return@mapNotNull null }
|
||||
val lm = o.optLong("last_modified", 0L)
|
||||
CloudFile(n, if (lm > 1_000_000_000_000L) lm else if (lm > 0) lm * 1000 else -1L)
|
||||
}
|
||||
}
|
||||
return text.lines().map { it.trim() }.filter { it.isNotEmpty() }.map { CloudFile(it, -1L) }
|
||||
}
|
||||
|
||||
override fun details(file: CloudFile) {
|
||||
if (file.modifiedMs > 0 && file.md5 != null) return
|
||||
val c = open("$base/${key(file.name)}", "HEAD", token, ua)
|
||||
if (c.responseCode in 200..299) {
|
||||
httpDate(c.getHeaderField("Last-Modified")).takeIf { it > 0 }?.let { file.modifiedMs = it }
|
||||
c.getHeaderField("ETag")?.replace("\"", "")?.trim()?.ifEmpty { null }?.let { file.md5 = it }
|
||||
}
|
||||
c.disconnect()
|
||||
}
|
||||
|
||||
override fun get(file: CloudFile): Pair<ByteArray, Long> {
|
||||
val c = open("$base/${key(file.name)}", "GET", token, ua)
|
||||
if (c.responseCode !in 200..299) { val code = c.responseCode; c.disconnect(); throw java.io.IOException("GOG cloud get HTTP $code") }
|
||||
val modified = httpDate(c.getHeaderField("Last-Modified"))
|
||||
return c.body().also { c.disconnect() } to modified
|
||||
}
|
||||
|
||||
override fun put(files: Map<String, ByteArray>): Map<String, Long> = files.mapValues { (name, data) ->
|
||||
val c = open("$base/${key(name)}", "PUT", token, ua)
|
||||
c.doOutput = true
|
||||
c.setRequestProperty("Content-Type", "application/octet-stream")
|
||||
c.setFixedLengthStreamingMode(data.size)
|
||||
c.outputStream.use { it.write(data) }
|
||||
val code = c.responseCode
|
||||
c.disconnect()
|
||||
if (code !in 200..299) throw java.io.IOException("GOG cloud put HTTP $code")
|
||||
// The server stamps the object itself; that time, so the next sync sees the two as equal.
|
||||
CloudFile(name, -1L).also { details(it) }.modifiedMs
|
||||
}
|
||||
}
|
||||
|
||||
/** Epic savesync: `/api/v1/access/egstore/savesync/<accountId>/<appName>/`. */
|
||||
class EpicCloud(private val accountId: String, private val appName: String, private val token: String) : CloudTransport {
|
||||
private val base = "https://datastorage-public-service-liveegs.live.use1a.on.epicgames.com/api/v1/access/egstore/savesync/$accountId/$appName/"
|
||||
private val ua = "EpicGamesLauncher/15.17.1-22692490"
|
||||
|
||||
override fun list(): List<CloudFile> {
|
||||
val c = open(base, "GET", token, ua)
|
||||
val code = c.responseCode
|
||||
if (code == 404) { c.disconnect(); return emptyList() }
|
||||
if (code !in 200..299) { c.disconnect(); throw java.io.IOException("Epic cloud list HTTP $code") }
|
||||
val root = JSONObject(c.body().decodeToString().ifEmpty { "{}" })
|
||||
c.disconnect()
|
||||
val files = root.optJSONObject("files") ?: return emptyList()
|
||||
return files.keys().asSequence().mapNotNull { k ->
|
||||
val e = files.optJSONObject(k) ?: return@mapNotNull null
|
||||
CloudFile(strip(k), isoDate(e.optString("lastModified", null)), e.optString("hash", "").ifEmpty { null }, e.optString("readLink", "").ifEmpty { null })
|
||||
}.toList()
|
||||
}
|
||||
|
||||
/** The listing names a file `<...>/<appName>/<key>`; the key is what is under the save folder. */
|
||||
private fun strip(key: String): String {
|
||||
val marker = "/$appName/"
|
||||
val i = key.indexOf(marker)
|
||||
if (i >= 0) return key.substring(i + marker.length)
|
||||
return key.removePrefix("$appName/")
|
||||
}
|
||||
|
||||
override fun get(file: CloudFile): Pair<ByteArray, Long> {
|
||||
val link = file.readLink ?: throw java.io.IOException("Epic cloud: no read link")
|
||||
val c = open(link, "GET", null, ua)
|
||||
if (c.responseCode !in 200..299) { val code = c.responseCode; c.disconnect(); throw java.io.IOException("Epic cloud get HTTP $code") }
|
||||
return c.body().also { c.disconnect() } to file.modifiedMs
|
||||
}
|
||||
|
||||
override fun put(files: Map<String, ByteArray>): Map<String, Long> {
|
||||
if (files.isEmpty()) return emptyMap()
|
||||
val c = open(base, "POST", token, ua)
|
||||
c.doOutput = true
|
||||
c.setRequestProperty("Content-Type", "application/json")
|
||||
val req = JSONObject().put("files", JSONArray(files.keys.toList())).toString().toByteArray()
|
||||
c.outputStream.use { it.write(req) }
|
||||
if (c.responseCode !in 200..299) { val code = c.responseCode; c.disconnect(); throw java.io.IOException("Epic cloud write links HTTP $code") }
|
||||
val links = JSONObject(c.body().decodeToString()).optJSONObject("files") ?: JSONObject()
|
||||
c.disconnect()
|
||||
val out = HashMap<String, Long>()
|
||||
for (k in links.keys()) {
|
||||
val link = links.optJSONObject(k)?.optString("writeLink", "")?.ifEmpty { null } ?: continue
|
||||
val name = strip(k)
|
||||
val data = files[name] ?: files[k] ?: continue
|
||||
val p = open(link, "PUT", null, ua)
|
||||
p.doOutput = true
|
||||
p.setRequestProperty("Content-Type", "application/octet-stream")
|
||||
p.setFixedLengthStreamingMode(data.size)
|
||||
p.outputStream.use { it.write(data) }
|
||||
val code = p.responseCode
|
||||
p.disconnect()
|
||||
if (code !in 200..299) throw java.io.IOException("Epic cloud put HTTP $code")
|
||||
out[name] = -1L
|
||||
}
|
||||
return out
|
||||
}
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
package com.droiddeck.launcher.stores
|
||||
|
||||
import java.io.File
|
||||
import org.json.JSONObject
|
||||
|
||||
/**
|
||||
* Game sizes as found, kept per game AND the version they were found for, in
|
||||
* `filesDir/stores/<store>/sizes.json`: a size is never fetched twice for one version, and a
|
||||
* new version (a library refresh brings it) simply misses and is looked up again. The file carries
|
||||
* its format; one in another format is discarded, not read.
|
||||
*/
|
||||
class SizeCache(private val file: File) {
|
||||
private val sizes = HashMap<String, Pair<String, Long>>()
|
||||
|
||||
init {
|
||||
runCatching {
|
||||
val o = JSONObject(file.readText())
|
||||
if (o.optInt("format") == FORMAT) {
|
||||
val s = o.getJSONObject("sizes")
|
||||
for (k in s.keys()) s.optJSONObject(k)?.let { e -> sizes[k] = e.optString("v") to e.optLong("b") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun get(id: String, version: String): Long? = sizes[id]?.takeIf { it.first == version && it.second > 0 }?.second
|
||||
|
||||
@Synchronized
|
||||
fun put(id: String, version: String, bytes: Long) {
|
||||
if (bytes <= 0) return
|
||||
sizes[id] = version to bytes
|
||||
runCatching {
|
||||
file.parentFile?.mkdirs()
|
||||
val s = JSONObject()
|
||||
for ((k, v) in sizes) s.put(k, JSONObject().put("v", v.first).put("b", v.second))
|
||||
val tmp = File(file.path + ".tmp")
|
||||
tmp.writeText(JSONObject().put("format", FORMAT).put("sizes", s).toString())
|
||||
tmp.renameTo(file)
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val FORMAT = 1
|
||||
fun forStore(filesDir: File, store: Store) = SizeCache(File(filesDir, "stores/${store.id}/sizes.json"))
|
||||
}
|
||||
}
|
||||
@@ -81,18 +81,6 @@ fun installedCards(store: Store, installed: List<InstalledStoreGame>, library: L
|
||||
}.distinctBy { it.id }.sortedBy { it.title.lowercase() }
|
||||
}
|
||||
|
||||
/**
|
||||
* A refreshed list with every unchanged item kept as the very object already shown, so a refresh
|
||||
* that lands while the grid is on screen recomposes only the cards that changed - no reset, the
|
||||
* scroll position and the pad's focus stay.
|
||||
*/
|
||||
fun mergeItems(old: List<CatalogItem>?, new: List<CatalogItem>): List<CatalogItem> {
|
||||
if (old.isNullOrEmpty()) return new
|
||||
val before = old.associateBy { it.key }
|
||||
val merged = new.map { n -> before[n.key]?.takeIf { it == n } ?: n }
|
||||
return if (merged.size == old.size && merged.indices.all { merged[it] === old[it] }) old else merged
|
||||
}
|
||||
|
||||
class InstalledStoreGame(val sidecar: StoreGameSidecar, val folder: java.io.File) {
|
||||
val key: String get() = "${sidecar.store.id}:${sidecar.id}"
|
||||
}
|
||||
|
||||
@@ -40,8 +40,6 @@ class StoreGameSidecar(
|
||||
val state: String = STATE_INSTALLED,
|
||||
/** An Epic game's launch choices (the Games tab's Epic card); both launch paths read them from here. */
|
||||
val epic: EpicOptions = EpicOptions(),
|
||||
/** GOG / Epic cloud saves for this game: down before a launch, up after it (the game card's switch). */
|
||||
val cloud: Boolean = true,
|
||||
) {
|
||||
val isInstalled: Boolean get() = state == STATE_INSTALLED
|
||||
|
||||
@@ -52,8 +50,8 @@ class StoreGameSidecar(
|
||||
exe: String = this.exe, launcher: String? = this.launcher, args: List<String> = this.args,
|
||||
env: Map<String, String> = this.env, installVersion: String = this.installVersion,
|
||||
installedAt: Long = this.installedAt, cover: String? = this.cover, hero: String? = this.hero,
|
||||
extra: Map<String, String> = this.extra, state: String = this.state, epic: EpicOptions = this.epic, cloud: Boolean = this.cloud,
|
||||
) = StoreGameSidecar(store, id, title, exe, launcher, args, env, installVersion, installedAt, cover, hero, extra, state, epic, cloud)
|
||||
extra: Map<String, String> = this.extra, state: String = this.state, epic: EpicOptions = this.epic,
|
||||
) = StoreGameSidecar(store, id, title, exe, launcher, args, env, installVersion, installedAt, cover, hero, extra, state, epic)
|
||||
|
||||
fun toJson(): JSONObject = JSONObject().apply {
|
||||
put("version", VERSION)
|
||||
@@ -62,8 +60,7 @@ class StoreGameSidecar(
|
||||
put("title", title)
|
||||
if (exe.isNotEmpty()) put("exe", exe)
|
||||
if (state != STATE_INSTALLED) put("state", state)
|
||||
if (store == Store.EPIC) put("epic", JSONObject().put("eos", epic.eos).put("offline", epic.offline))
|
||||
if (store != Store.AMAZON) put("cloud", cloud)
|
||||
if (store == Store.EPIC) put("epic", JSONObject().put("v", EpicOptions.VERSION).put("eos", epic.eos).put("offline", epic.offline).put("overlay", epic.overlay))
|
||||
if (!launcher.isNullOrEmpty()) put("launcher", launcher)
|
||||
if (args.isNotEmpty()) put("args", JSONArray(args))
|
||||
if (env.isNotEmpty()) put("env", JSONObject(env as Map<*, *>))
|
||||
@@ -102,13 +99,6 @@ class StoreGameSidecar(
|
||||
return read(folder)?.takeIf { it.epic == next.epic }
|
||||
}
|
||||
|
||||
/** As [updateEpic], for the cloud-saves switch. */
|
||||
fun updateCloud(folder: File, on: Boolean): StoreGameSidecar? {
|
||||
val current = read(folder) ?: return null
|
||||
current.copy(cloud = on).write(folder)
|
||||
return read(folder)?.takeIf { it.cloud == on }
|
||||
}
|
||||
|
||||
/** The sidecar in [folder], or null when there is none or it cannot be read. */
|
||||
fun read(folder: File): StoreGameSidecar? {
|
||||
val f = file(folder)
|
||||
@@ -143,9 +133,12 @@ class StoreGameSidecar(
|
||||
hero = o.optString("hero", "").ifEmpty { null },
|
||||
extra = extra,
|
||||
state = state,
|
||||
// An "overlay" (or "v") field from an earlier build is read past: there is no overlay.
|
||||
epic = o.optJSONObject("epic")?.let { e -> EpicOptions(eos = e.optBoolean("eos", true), offline = e.optBoolean("offline", false)) } ?: EpicOptions(),
|
||||
cloud = o.optBoolean("cloud", true),
|
||||
epic = o.optJSONObject("epic")?.let { e ->
|
||||
// Before v2 the overlay was on by default and written so without anyone choosing
|
||||
// it; the overlay crashed games, so those read as off. From v2 it is a choice.
|
||||
val chosen = e.optInt("v", 1) >= EpicOptions.VERSION
|
||||
EpicOptions(eos = e.optBoolean("eos", true), offline = e.optBoolean("offline", false), overlay = chosen && e.optBoolean("overlay", false))
|
||||
} ?: EpicOptions(),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -158,8 +151,15 @@ class StoreGameSidecar(
|
||||
/**
|
||||
* An Epic game's launch choices. [eos]: pass a fresh exchange code (Epic sign-in). [offline]: start
|
||||
* with the Epic identity arguments only, no code - for a game that will not start when sign-in fails.
|
||||
* [overlay]: point the game's prefix at Epic's EOS overlay - off by default: with it on, a game can
|
||||
* exit while loading on this stack (Metalstorm did, twice; off, it signs in and runs).
|
||||
*/
|
||||
data class EpicOptions(val eos: Boolean = true, val offline: Boolean = false) {
|
||||
data class EpicOptions(val eos: Boolean = true, val offline: Boolean = false, val overlay: Boolean = false) {
|
||||
/** Whether a launch asks for a code at all. */
|
||||
val wantsCode: Boolean get() = eos && !offline
|
||||
|
||||
companion object {
|
||||
/** v2: the overlay is off unless chosen (Metalstorm exits while loading with it on). */
|
||||
const val VERSION = 2
|
||||
}
|
||||
}
|
||||
@@ -43,8 +43,8 @@ object StoreInstalls {
|
||||
val app = context.applicationContext
|
||||
onStep?.invoke(0, STEPS)
|
||||
// The user's launch choices survive an update or a repair.
|
||||
val before = StoreGameSidecar.read(folder)
|
||||
val finished = StoreLaunch.writeLauncher(folder, sidecar.copy(state = StoreGameSidecar.STATE_INSTALLED, epic = before?.epic ?: sidecar.epic, cloud = before?.cloud ?: sidecar.cloud))
|
||||
val kept = StoreGameSidecar.read(folder)?.epic ?: sidecar.epic
|
||||
val finished = StoreLaunch.writeLauncher(folder, sidecar.copy(state = StoreGameSidecar.STATE_INSTALLED, epic = kept))
|
||||
finished.write(folder)
|
||||
if (StoreGameSidecar.read(folder)?.isInstalled != true) throw java.io.IOException("the install record could not be written in ${folder.name}")
|
||||
onStep?.invoke(1, STEPS)
|
||||
|
||||
@@ -60,27 +60,15 @@ object StoreLaunchRequests {
|
||||
if (id.isEmpty()) JSONObject().put("ok", false).put("reason", "no-id")
|
||||
else {
|
||||
val code = StoreLaunch.epicCode(app, id)
|
||||
JSONObject().put("ok", true).put("code", code.written).put("reason", code.reason)
|
||||
// The overlay is placed once and shared; the launch writes the prefix's pointer.
|
||||
val overlay = com.droiddeck.launcher.stores.epic.EpicOverlay.installedVersion(app)
|
||||
val wanted = StoreInstallRoot.gameFolders(app).firstNotNullOfOrNull { f -> StoreGameSidecar.read(f)?.takeIf { it.store == Store.EPIC && it.id == id } }?.epic?.overlay == true
|
||||
Log.i(TAG, "epic overlay installed=${overlay ?: "no"} wanted=$wanted prefix=${request.optString("prefix").ifEmpty { "?" }}")
|
||||
// Fetched only for a game that has the overlay on (656 MB; off by default).
|
||||
if (overlay == null && wanted) com.droiddeck.launcher.stores.epic.EpicOverlay.ensureAsync(app)
|
||||
JSONObject().put("ok", true).put("code", code.written).put("reason", code.reason).put("overlay", overlay ?: "")
|
||||
}
|
||||
}
|
||||
// Cloud saves: down before Proton starts (the wrapper waits a bounded time), up after the
|
||||
// game exits (answered at once; the upload runs on without holding Steam).
|
||||
"cloud-down" -> {
|
||||
val store = Store.byId(request.optString("store"))
|
||||
val id = request.optString("id")
|
||||
if (store == null || id.isEmpty()) JSONObject().put("ok", false).put("reason", "no-game")
|
||||
else {
|
||||
// Marked before the game runs: whatever ends it, an upload follows (CloudSaves.uploadDirty).
|
||||
CloudSaves.markDirty(app, store, id)
|
||||
CloudSaves.downloadOrDefer(app, store, id).let { JSONObject().put("ok", it.ok).put("result", it.result).put("files", it.files).put("reason", it.reason) }
|
||||
}
|
||||
}
|
||||
"cloud-up" -> {
|
||||
val store = Store.byId(request.optString("store"))
|
||||
val id = request.optString("id")
|
||||
if (store != null && id.isNotEmpty()) Thread({ CloudSaves.uploadDirty(app, store, id, "exit") }, "cloud-up").start()
|
||||
JSONObject().put("ok", true)
|
||||
}
|
||||
// A browser a game opens inside the session (an EOS device sign-in, a store page):
|
||||
// http(s) only, handed to Android's browser.
|
||||
"open-url" -> {
|
||||
|
||||
@@ -125,12 +125,40 @@ object StoreLog {
|
||||
}
|
||||
}
|
||||
|
||||
private val URL_PATTERN = Regex("""[A-Za-z][A-Za-z0-9+.\-]*://[^\s"'<>]+""")
|
||||
private val SAFE_SEGMENT = Regex("""[A-Za-z0-9._\-]{1,40}""")
|
||||
private val SECRET = Regex("""(?i)(?<![A-Za-z0-9_])(__token__|f_token|hdnts|access_token|refresh_token|id_token|token)(["']?\s*[=:]\s*["']?)[^\s&;,"'}]+""")
|
||||
private val CODE = Regex("""(?i)(?<![A-Za-z0-9_])(code|exchange_code|authorizationCode)(["']?\s*=\s*["']?)[^\s&;,"'}]+""")
|
||||
private val AUTH_HEADER = Regex("""(?i)(authorization|cookie)(\s*[:=]\s*).*""")
|
||||
|
||||
/**
|
||||
* What any store line may say, for the stores' log and logcat alike: URLs cut to their host and a
|
||||
* plain first path segment, token values and Authorization / Cookie headers blanked - the shared
|
||||
* rules of [com.droiddeck.launcher.core.SecretScrub], which a shared log zip applies too.
|
||||
* What any store line may say, for the Downloads log and logcat alike: every URL cut to
|
||||
* `scheme://host/first-segment/…` (the segment kept only when it is a plain name - a GOG secure
|
||||
* link carries its token in the path), no query, fragment or userinfo; and outside URLs, the
|
||||
* values of token-like keys and of Authorization / Cookie headers blanked.
|
||||
*/
|
||||
@JvmStatic
|
||||
fun redactLine(text: String): String =
|
||||
com.droiddeck.launcher.core.SecretScrub.scrub(text, com.droiddeck.launcher.core.SecretScrub.Urls.SHORT, "…")
|
||||
fun redactLine(text: String): String {
|
||||
var out = URL_PATTERN.replace(text) { m -> shortUrl(m.value) }
|
||||
out = SECRET.replace(out) { m -> m.groupValues[1] + m.groupValues[2] + "…" }
|
||||
out = CODE.replace(out) { m -> m.groupValues[1] + m.groupValues[2] + "…" }
|
||||
out = AUTH_HEADER.replace(out) { m -> m.groupValues[1] + m.groupValues[2] + "…" }
|
||||
return out
|
||||
}
|
||||
|
||||
private fun shortUrl(url: String): String {
|
||||
val schemeEnd = url.indexOf("://")
|
||||
val scheme = url.substring(0, schemeEnd)
|
||||
var rest = url.substring(schemeEnd + 3)
|
||||
rest = rest.substringBefore('#').substringBefore('?')
|
||||
val slash = rest.indexOf('/')
|
||||
val authority = (if (slash >= 0) rest.substring(0, slash) else rest).substringAfterLast('@')
|
||||
if (slash < 0) return "$scheme://$authority"
|
||||
val path = rest.substring(slash + 1)
|
||||
val first = path.substringBefore('/')
|
||||
val more = path.length > first.length
|
||||
if (first.isEmpty()) return "$scheme://$authority/"
|
||||
val shown = if (SAFE_SEGMENT.matches(first)) first else "…"
|
||||
return "$scheme://$authority/$shown" + if (more && shown != "…") "/…" else ""
|
||||
}
|
||||
}
|
||||
@@ -1,96 +0,0 @@
|
||||
package com.droiddeck.launcher.stores
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import androidx.compose.runtime.mutableStateMapOf
|
||||
import com.droiddeck.launcher.stores.amazon.AmazonApiClient
|
||||
import com.droiddeck.launcher.stores.amazon.AmazonCredentialStore
|
||||
import com.droiddeck.launcher.stores.amazon.AmazonManifest
|
||||
import com.droiddeck.launcher.stores.amazon.AmazonPrefs
|
||||
import com.droiddeck.launcher.stores.epic.EpicApiClient
|
||||
import com.droiddeck.launcher.stores.epic.EpicCredentialStore
|
||||
import com.droiddeck.launcher.stores.epic.EpicDownloadManager
|
||||
import com.droiddeck.launcher.stores.epic.EpicInstallTags
|
||||
import com.droiddeck.launcher.stores.epic.EpicPrefs
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import java.util.concurrent.Executors
|
||||
|
||||
/**
|
||||
* Install sizes for owned Epic and Amazon games, whose library answers carry none: Epic's from the
|
||||
* game's build manifest (the files this device installs), Amazon's from its download manifest.
|
||||
* Asked for a card as it comes on screen, three at a time in the background, once per game - the
|
||||
* answer is kept in the store's prefs (`size_<id>`, where the library reads it too). Until it is
|
||||
* known the card shows nothing.
|
||||
*/
|
||||
object StoreSizes {
|
||||
private const val TAG = "StoreSizes"
|
||||
|
||||
/** Sizes found this run, by card key; the cards read them. */
|
||||
val known = mutableStateMapOf<String, Long>()
|
||||
|
||||
private val asked = ConcurrentHashMap.newKeySet<String>()
|
||||
private val pool = Executors.newFixedThreadPool(3, com.droiddeck.launcher.stores.download.DownloadQueue.workerFactory("sizes"))
|
||||
|
||||
fun size(item: CatalogItem): Long = known[item.key] ?: item.sizeBytes
|
||||
|
||||
private val caches = ConcurrentHashMap<Store, SizeCache>()
|
||||
private fun cache(context: Context, store: Store) = caches.getOrPut(store) { SizeCache.forStore(context.applicationContext.filesDir, store) }
|
||||
|
||||
/** A card for [item] is on screen (or about to be): its size from the cache for this version, else looked up. */
|
||||
fun request(context: Context, item: CatalogItem) {
|
||||
if (!item.owned || item.sizeBytes > 0 || item.store == Store.GOG) return
|
||||
if (known.containsKey(item.key) || !asked.add(item.key)) return
|
||||
val app = context.applicationContext
|
||||
val version = item.extra["version"].orEmpty()
|
||||
pool.execute {
|
||||
val cached = cache(app, item.store).get(item.id, version)
|
||||
if (cached != null) { StoresState.post { known[item.key] = cached }; return@execute }
|
||||
val bytes = runCatching { fetch(app, item) }.onFailure { Log.w(TAG, "${item.key}: ${it.javaClass.simpleName}") }.getOrNull() ?: 0L
|
||||
if (bytes > 0) {
|
||||
cache(app, item.store).put(item.id, version, bytes)
|
||||
when (item.store) {
|
||||
Store.EPIC -> EpicPrefs.get(app).edit().putLong("size_${item.id}", bytes).apply()
|
||||
Store.AMAZON -> AmazonPrefs.get(app).edit().putLong("size_${item.id}", bytes).apply()
|
||||
Store.GOG -> {}
|
||||
}
|
||||
StoresState.post { known[item.key] = bytes }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** An installed game's size on disk, by card key; worked out once per install. */
|
||||
val onDisk = mutableStateMapOf<String, Long>()
|
||||
|
||||
fun requestDisk(context: Context, key: String, game: InstalledStoreGame) {
|
||||
if (onDisk.containsKey(key) || !asked.add("disk:$key")) return
|
||||
val app = context.applicationContext
|
||||
val version = "disk:${game.sidecar.installedAt}:${game.sidecar.installVersion}"
|
||||
pool.execute {
|
||||
val c = cache(app, game.sidecar.store)
|
||||
val bytes = c.get("disk:${game.sidecar.id}", version)
|
||||
?: game.folder.walkTopDown().filter { it.isFile && !it.name.startsWith(".droiddeck") }.sumOf { it.length() }.also { c.put("disk:${game.sidecar.id}", version, it) }
|
||||
if (bytes > 0) StoresState.post { onDisk[key] = bytes }
|
||||
}
|
||||
}
|
||||
|
||||
private fun fetch(context: Context, item: CatalogItem): Long { return when (item.store) {
|
||||
Store.EPIC -> {
|
||||
val token = EpicCredentialStore.getValidAccessToken(context) ?: return 0L
|
||||
val ns = item.extra["namespace"].orEmpty()
|
||||
val catalogItemId = item.extra["catalogItemId"].orEmpty()
|
||||
if (ns.isEmpty() || catalogItemId.isEmpty()) return 0L
|
||||
val json = EpicApiClient.getManifestApiJson(token, ns, catalogItemId, item.id) ?: return 0L
|
||||
val bytes = EpicDownloadManager.downloadManifest(json, EpicDownloadManager.parseCdnUrls(json)) ?: return 0L
|
||||
val manifest = EpicDownloadManager.parseManifest(bytes) ?: return 0L
|
||||
EpicDownloadManager.resolveInstallFiles(manifest, EpicInstallTags.tagsForDevice()).sumOf { it.fileSize() }
|
||||
}
|
||||
Store.AMAZON -> {
|
||||
val token = AmazonCredentialStore.getValidAccessToken(context) ?: return 0L
|
||||
val entitlement = item.extra["entitlementId"].orEmpty().ifEmpty { return 0L }
|
||||
val spec = AmazonApiClient.getGameDownload(token, entitlement) ?: return 0L
|
||||
val bytes = AmazonApiClient.getBytes(AmazonApiClient.appendPath(spec.downloadUrl, "manifest.proto"), token) ?: return 0L
|
||||
AmazonManifest.parse(bytes).totalInstallSize
|
||||
}
|
||||
Store.GOG -> 0L
|
||||
} }
|
||||
}
|
||||
@@ -170,23 +170,6 @@ object StoresState {
|
||||
}, "stores-signout").start()
|
||||
}
|
||||
|
||||
/** A notification asked for the Downloads chip; the Stores page takes it and clears it. */
|
||||
var openDownloads by mutableStateOf(false)
|
||||
|
||||
/**
|
||||
* Android 13+: notifications need permission. Asked once, the first time a download starts from
|
||||
* a screen; refused, downloads still run, without their notification.
|
||||
*/
|
||||
private fun askForNotifications(context: Context) {
|
||||
val activity = context as? android.app.Activity ?: return
|
||||
if (android.os.Build.VERSION.SDK_INT < 33) return
|
||||
if (activity.checkSelfPermission("android.permission.POST_NOTIFICATIONS") == android.content.pm.PackageManager.PERMISSION_GRANTED) return
|
||||
val p = activity.getSharedPreferences("stores", Context.MODE_PRIVATE)
|
||||
if (p.getBoolean("asked_notifications", false)) return
|
||||
p.edit().putBoolean("asked_notifications", true).apply()
|
||||
runCatching { activity.requestPermissions(arrayOf("android.permission.POST_NOTIFICATIONS"), 7102) }
|
||||
}
|
||||
|
||||
/** An install waiting for the user to say where: the page shows the choice while this is set. */
|
||||
var pendingInstall by mutableStateOf<CatalogItem?>(null)
|
||||
|
||||
@@ -196,7 +179,6 @@ object StoresState {
|
||||
* storage at once.
|
||||
*/
|
||||
fun requestInstall(context: Context, item: CatalogItem) {
|
||||
askForNotifications(context)
|
||||
// A resume goes where the files already are; there is nothing to choose.
|
||||
if (isUnfinished(item)) { install(context, item); return }
|
||||
val targets = StoreInstallRoot.targets(context)
|
||||
@@ -244,12 +226,6 @@ object StoresState {
|
||||
fun init(context: Context) {
|
||||
appContext = context.applicationContext
|
||||
StoreLogFiles.prune(context)
|
||||
// The EOS overlay an earlier build downloaded (656 MB) is gone with the feature.
|
||||
val overlay = java.io.File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context), "root/.local/share/droiddeck/epic-overlay")
|
||||
if (overlay.exists()) Thread({ overlay.deleteRecursively(); Log.i(TAG, "removed the old EOS overlay download") }, "epic-overlay-cleanup").start()
|
||||
// Cloud saves a killed app never uploaded; not while a session (and maybe that game) runs.
|
||||
val app = context.applicationContext
|
||||
Thread({ CloudSaves.uploadAllDirty(app, "recovery") }, "cloud-recovery").start()
|
||||
}
|
||||
|
||||
internal fun post(block: () -> Unit) = main.post(block)
|
||||
|
||||
@@ -66,7 +66,7 @@ object AmazonBackend : StoreBackend {
|
||||
/** The library and, from it, the shelves. */
|
||||
private fun publish(app: Context, games: List<AmazonGame>) {
|
||||
val items = games.map { AmazonLibrary.toCatalogItem(app, it) }
|
||||
StoresState.library[store] = com.droiddeck.launcher.stores.mergeItems(StoresState.library[store], items)
|
||||
StoresState.library[store] = items
|
||||
val installed = StoresState.installed.filter { it.sidecar.store == store }.map { it.sidecar.id }.toSet()
|
||||
StoresState.shelves[store] = StoreShelves(trending = items.filter { it.id !in installed }, free = emptyList(), deals = emptyList(), whatsNew = emptyList())
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ object AmazonLibrary {
|
||||
private const val TAG = "AmazonLibrary"
|
||||
private const val CACHE_KEY = "library_cache"
|
||||
private const val LAST_SYNC_KEY = "library_synced_at"
|
||||
private const val THROTTLE_MS = 6L * 60L * 60L * 1000L
|
||||
private const val THROTTLE_MS = 15L * 60L * 1000L
|
||||
private const val POSTER_BUDGET = 40
|
||||
|
||||
private val syncing = AtomicBoolean(false)
|
||||
@@ -123,6 +123,6 @@ object AmazonLibrary {
|
||||
developer = g.developer, owned = true,
|
||||
sizeBytes = AmazonPrefs.get(context).getLong("size_${g.productId}", 0L),
|
||||
storeUrl = "https://gaming.amazon.com/home",
|
||||
extra = mapOf("entitlementId" to g.entitlementId, "sku" to g.productSku, "version" to (g.versionId ?: "")),
|
||||
extra = mapOf("entitlementId" to g.entitlementId, "sku" to g.productSku),
|
||||
)
|
||||
}
|
||||
@@ -248,14 +248,6 @@ object DownloadQueue {
|
||||
StoreDownloadService.finish(context.applicationContext, key)
|
||||
}
|
||||
|
||||
/** Drops every finished, failed or cancelled row; files a failed one kept stay (its game page's Clear removes them). */
|
||||
fun dismissFinished() {
|
||||
synchronized(lock) {
|
||||
items.entries.removeAll { !it.value.entry.isActive }
|
||||
publishLocked()
|
||||
}
|
||||
}
|
||||
|
||||
/** Drops a finished, failed or cancelled row from the list. */
|
||||
fun dismiss(key: String) {
|
||||
synchronized(lock) {
|
||||
@@ -361,15 +353,8 @@ object DownloadQueue {
|
||||
StoresState.logLine("installed \"${item.entry.name}\" → ${result}")
|
||||
// The folder is on disk and registered: the Installed tab and the Games list follow.
|
||||
StoresState.notifyLibraryChanged(context)
|
||||
val games = runCatching {
|
||||
com.droiddeck.launcher.frontend.Library.launchableGames(context).firstOrNull { it.gameFiles?.absolutePath == result }?.let { "app:${it.appId}" }
|
||||
}.getOrNull()
|
||||
StoreDownloadService.ended(context, item.entry, installed = true, gamesKey = games)
|
||||
}
|
||||
DownloadState.FAILED -> {
|
||||
StoresState.logLine("${item.entry.store.label}: \"${item.entry.name}\" failed: $error")
|
||||
StoreDownloadService.ended(context, item.entry, installed = false, gamesKey = null)
|
||||
}
|
||||
DownloadState.FAILED -> StoresState.logLine("${item.entry.store.label}: \"${item.entry.name}\" failed: $error")
|
||||
DownloadState.CANCELLED -> StoresState.notifyLibraryChanged(context)
|
||||
else -> {}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package com.droiddeck.launcher.stores.download
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.app.Notification
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
@@ -8,167 +7,76 @@ import android.app.PendingIntent
|
||||
import android.app.Service
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.wifi.WifiManager
|
||||
import android.os.Build
|
||||
import android.os.Handler
|
||||
import android.os.IBinder
|
||||
import android.os.Looper
|
||||
import android.os.PowerManager
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.MainActivity
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.stores.StoresState
|
||||
import com.droiddeck.launcher.stores.formatBytes
|
||||
import com.droiddeck.launcher.stores.formatSpeed
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
/**
|
||||
* Keeps store downloads going with the screen off or the app in the background: a foreground
|
||||
* service (dataSync) with a notification showing the active download's progress, Pause / Resume
|
||||
* and a two-step Cancel; a Wi-Fi lock and a partial wake lock while anything is running, so the
|
||||
* radio and the CPU do not sleep under a multi-gigabyte install; and a notification when a game
|
||||
* has installed or failed.
|
||||
* Keeps the process alive while a store download runs, with one quiet notification for the queue.
|
||||
* Without it Android demotes the app as soon as the launcher leaves the screen and a multi-gigabyte
|
||||
* install dies half way; the session has its own service for the same reason.
|
||||
*
|
||||
* [start] is called when a download begins and [finish] when one ends; the service stops itself when
|
||||
* nothing is running.
|
||||
* [start] is called when a download begins and [finish] when one ends; the notification is rebuilt
|
||||
* from the queue's live rows, and the service stops itself when nothing is active.
|
||||
*/
|
||||
class StoreDownloadService : Service() {
|
||||
private var wifi: WifiManager.WifiLock? = null
|
||||
private var wake: PowerManager.WakeLock? = null
|
||||
private var wakeAt = 0L
|
||||
/** The download whose Cancel was tapped once: its actions read Delete / Keep until [confirmUntil]. */
|
||||
private var confirmKey: String? = null
|
||||
private var confirmUntil = 0L
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
instance = this
|
||||
channels(this)
|
||||
val nm = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
|
||||
if (nm.getNotificationChannel(CHANNEL) == null) {
|
||||
nm.createNotificationChannel(NotificationChannel(CHANNEL, getString(R.string.stores_notification_channel), NotificationManager.IMPORTANCE_LOW).apply {
|
||||
description = getString(R.string.stores_notification_channel_hint)
|
||||
setShowBadge(false)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
instance = this
|
||||
startForegroundCompat(build())
|
||||
val key = intent?.getStringExtra(EXTRA_KEY)
|
||||
when (intent?.action) {
|
||||
ACTION_PAUSE -> key?.let {
|
||||
DownloadQueue.pause(it)
|
||||
// The progress notification goes with the last running download; this one stays to resume from.
|
||||
pausedNote(this, it)
|
||||
}
|
||||
ACTION_RESUME -> key?.let {
|
||||
runCatching { getSystemService(NotificationManager::class.java)?.cancel(pausedId(it)) }
|
||||
DownloadQueue.resume(this, it)
|
||||
}
|
||||
ACTION_CANCEL -> key?.let {
|
||||
confirmKey = it; confirmUntil = System.currentTimeMillis() + CONFIRM_MS
|
||||
main.postDelayed({ if (System.currentTimeMillis() >= confirmUntil) { confirmKey = null; refresh() } }, CONFIRM_MS + 100)
|
||||
}
|
||||
ACTION_DELETE -> key?.let { confirmKey = null; DownloadQueue.cancel(this, it) }
|
||||
ACTION_KEEP -> confirmKey = null
|
||||
}
|
||||
refresh()
|
||||
if (active.isEmpty() && StoresState.latestDownloads.none { it.state == DownloadState.RUNNING }) stopNow()
|
||||
if (active.isEmpty()) stopNow()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
releaseLocks()
|
||||
if (instance === this) instance = null
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
override fun onBind(intent: Intent?): IBinder? = null
|
||||
|
||||
private fun pending(action: String, key: String, code: Int): PendingIntent {
|
||||
val i = Intent(this, StoreDownloadService::class.java).setAction(action).putExtra(EXTRA_KEY, key)
|
||||
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) PendingIntent.getForegroundService(this, code, i, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
|
||||
else PendingIntent.getService(this, code, i, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
|
||||
}
|
||||
|
||||
private fun build(): Notification {
|
||||
val rows = StoresState.latestDownloads.filter { it.isActive }
|
||||
val first = rows.firstOrNull { it.state == DownloadState.RUNNING } ?: rows.firstOrNull()
|
||||
val title = if (rows.size > 1) getString(R.string.stores_notification_many, rows.size) else first?.name ?: getString(R.string.stores_notification_one)
|
||||
val b = Notification.Builder(this, CHANNEL)
|
||||
.setSmallIcon(android.R.drawable.stat_sys_download)
|
||||
.setContentTitle(title)
|
||||
.setOngoing(true).setOnlyAlertOnce(true)
|
||||
.setContentIntent(openDownloads(this, 1))
|
||||
if (first == null) return b.setContentText(getString(R.string.stores_notification_waiting)).setProgress(0, 0, true).build()
|
||||
b.setContentText(DownloadNotificationText.line(first, stageName(first.stage), getString(R.string.stores_dl_paused), getString(R.string.stores_dl_queued)))
|
||||
val fraction = first.stageFraction
|
||||
if (fraction >= 0f) b.setProgress(1000, (fraction * 1000).toInt(), false) else b.setProgress(0, 0, true)
|
||||
val code = first.key.hashCode()
|
||||
if (confirmKey == first.key && System.currentTimeMillis() < confirmUntil) {
|
||||
b.addAction(Notification.Action.Builder(null, getString(R.string.stores_notification_delete), pending(ACTION_DELETE, first.key, code + 3)).build())
|
||||
b.addAction(Notification.Action.Builder(null, getString(R.string.stores_notification_keep), pending(ACTION_KEEP, first.key, code + 4)).build())
|
||||
} else {
|
||||
if (first.state == DownloadState.PAUSED) b.addAction(Notification.Action.Builder(null, getString(R.string.stores_dl_resume), pending(ACTION_RESUME, first.key, code + 1)).build())
|
||||
else b.addAction(Notification.Action.Builder(null, getString(R.string.stores_dl_pause), pending(ACTION_PAUSE, first.key, code)).build())
|
||||
b.addAction(Notification.Action.Builder(null, getString(R.string.stores_dl_cancel), pending(ACTION_CANCEL, first.key, code + 2)).build())
|
||||
val entries = StoresState.latestDownloads.filter { it.state == DownloadState.RUNNING }
|
||||
val first = entries.firstOrNull()
|
||||
val title = if (active.size > 1) getString(R.string.stores_notification_many, active.size) else getString(R.string.stores_notification_one)
|
||||
val text = when {
|
||||
first == null -> getString(R.string.stores_notification_waiting)
|
||||
first.stage == com.droiddeck.launcher.stores.download.DownloadStage.DOWNLOAD && first.bytesTotal > 0 -> "${first.name} · ${first.percent}% (${formatBytes(first.bytesDone)} / ${formatBytes(first.bytesTotal)})"
|
||||
first.stageFraction >= 0f -> "${first.name} · ${first.percent}%"
|
||||
else -> first.name
|
||||
}
|
||||
return b.build()
|
||||
val tap = PendingIntent.getActivity(this, 0, Intent(this, MainActivity::class.java), PendingIntent.FLAG_IMMUTABLE)
|
||||
return Notification.Builder(this, CHANNEL)
|
||||
.setSmallIcon(android.R.drawable.stat_sys_download)
|
||||
.setContentTitle(title).setContentText(text).setOngoing(true).setContentIntent(tap).build()
|
||||
}
|
||||
|
||||
private fun stageName(stage: DownloadStage): String = getString(when (stage) {
|
||||
DownloadStage.MANIFEST -> R.string.stores_stage_manifest
|
||||
DownloadStage.DOWNLOAD -> R.string.stores_stage_downloading
|
||||
DownloadStage.VERIFY -> R.string.stores_stage_verifying
|
||||
DownloadStage.INSTALL -> R.string.stores_stage_installing
|
||||
DownloadStage.DONE -> R.string.stores_stage_done
|
||||
})
|
||||
|
||||
private fun refresh() {
|
||||
locks()
|
||||
runCatching { (getSystemService(NOTIFICATION_SERVICE) as NotificationManager).notify(ID, build()) }
|
||||
}
|
||||
|
||||
/**
|
||||
* While a download runs: a Wi-Fi lock (high-performance before Android 14, low-latency from it,
|
||||
* where the old mode is deprecated) and a partial wake lock, taken with a timeout and renewed
|
||||
* as progress comes in rather than held indefinitely. Released as soon as nothing runs.
|
||||
*/
|
||||
@SuppressLint("WakelockTimeout")
|
||||
private fun locks() {
|
||||
val running = StoresState.latestDownloads.any { it.state == DownloadState.RUNNING }
|
||||
if (!running) { releaseLocks(); return }
|
||||
if (wifi == null) {
|
||||
runCatching {
|
||||
val wm = applicationContext.getSystemService(WIFI_SERVICE) as WifiManager
|
||||
@Suppress("DEPRECATION")
|
||||
val mode = if (Build.VERSION.SDK_INT >= 34) WifiManager.WIFI_MODE_FULL_LOW_LATENCY else WifiManager.WIFI_MODE_FULL_HIGH_PERF
|
||||
wifi = wm.createWifiLock(mode, "DroidDeck:store-download").apply { setReferenceCounted(false); acquire() }
|
||||
Log.i(TAG, "wifi lock held")
|
||||
}
|
||||
}
|
||||
val now = System.currentTimeMillis()
|
||||
if (wake == null) {
|
||||
wake = (getSystemService(POWER_SERVICE) as PowerManager).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "DroidDeck:store-download").apply { setReferenceCounted(false) }
|
||||
Log.i(TAG, "wake lock held")
|
||||
}
|
||||
if (now - wakeAt > WAKE_RENEW_MS) {
|
||||
wake?.acquire(WAKE_TIMEOUT_MS)
|
||||
wakeAt = now
|
||||
}
|
||||
}
|
||||
|
||||
private fun releaseLocks() {
|
||||
wifi?.let { runCatching { if (it.isHeld) it.release() }; Log.i(TAG, "wifi lock released") }
|
||||
wifi = null
|
||||
wake?.let { runCatching { if (it.isHeld) it.release() }; Log.i(TAG, "wake lock released") }
|
||||
wake = null
|
||||
wakeAt = 0L
|
||||
}
|
||||
|
||||
private fun startForegroundCompat(n: Notification) {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) startForeground(ID, n, android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC)
|
||||
else startForeground(ID, n)
|
||||
}
|
||||
|
||||
private fun stopNow() {
|
||||
releaseLocks()
|
||||
stopForeground(STOP_FOREGROUND_REMOVE)
|
||||
stopSelf()
|
||||
}
|
||||
@@ -176,41 +84,10 @@ class StoreDownloadService : Service() {
|
||||
companion object {
|
||||
private const val TAG = "StoreDownloadService"
|
||||
private const val CHANNEL = "store_downloads"
|
||||
private const val DONE_CHANNEL = "store_downloads_done"
|
||||
private const val ID = 9102
|
||||
private const val CONFIRM_MS = 10_000L
|
||||
private const val WAKE_TIMEOUT_MS = 10 * 60_000L
|
||||
private const val WAKE_RENEW_MS = 5 * 60_000L
|
||||
private const val EXTRA_KEY = "key"
|
||||
private const val ACTION_PAUSE = "droiddeck.stores.PAUSE"
|
||||
private const val ACTION_RESUME = "droiddeck.stores.RESUME"
|
||||
private const val ACTION_CANCEL = "droiddeck.stores.CANCEL"
|
||||
private const val ACTION_DELETE = "droiddeck.stores.DELETE"
|
||||
private const val ACTION_KEEP = "droiddeck.stores.KEEP"
|
||||
/** MainActivity: which page to open ("stores:downloads", or a Games selection such as "app:<id>"). */
|
||||
const val EXTRA_NAV = "droiddeck.nav"
|
||||
private val active = ConcurrentHashMap.newKeySet<String>()
|
||||
@Volatile private var instance: StoreDownloadService? = null
|
||||
|
||||
private fun channels(context: Context) {
|
||||
val nm = context.getSystemService(NotificationManager::class.java) ?: return
|
||||
if (nm.getNotificationChannel(CHANNEL) == null) {
|
||||
nm.createNotificationChannel(NotificationChannel(CHANNEL, context.getString(R.string.stores_notification_channel), NotificationManager.IMPORTANCE_LOW).apply {
|
||||
description = context.getString(R.string.stores_notification_channel_hint)
|
||||
setShowBadge(false)
|
||||
})
|
||||
}
|
||||
if (nm.getNotificationChannel(DONE_CHANNEL) == null) {
|
||||
nm.createNotificationChannel(NotificationChannel(DONE_CHANNEL, context.getString(R.string.stores_notification_done_channel), NotificationManager.IMPORTANCE_DEFAULT))
|
||||
}
|
||||
}
|
||||
|
||||
private fun openPage(context: Context, nav: String, code: Int): PendingIntent =
|
||||
PendingIntent.getActivity(context, code, Intent(context, MainActivity::class.java).putExtra(EXTRA_NAV, nav)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP), PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
|
||||
|
||||
private fun openDownloads(context: Context, code: Int) = openPage(context, "stores:downloads", code)
|
||||
|
||||
/** A download started: the service is up (idempotent). */
|
||||
fun start(context: Context) {
|
||||
StoresState.latestDownloads.filter { it.state == DownloadState.RUNNING }.forEach { active.add(it.key) }
|
||||
@@ -223,12 +100,12 @@ class StoreDownloadService : Service() {
|
||||
}
|
||||
}
|
||||
|
||||
/** Progress moved: redraw the notification (StoresState calls it at most once a second). */
|
||||
/** Progress moved: redraw the notification line (StoresState calls it at most once a second). */
|
||||
fun tick() {
|
||||
instance?.refresh()
|
||||
}
|
||||
|
||||
/** The queue changed: redraw the notification. */
|
||||
/** The queue changed: redraw the notification line. */
|
||||
fun sync(context: Context) {
|
||||
instance?.refresh()
|
||||
}
|
||||
@@ -239,61 +116,5 @@ class StoreDownloadService : Service() {
|
||||
val inst = instance ?: return
|
||||
if (active.isEmpty() && StoresState.latestDownloads.none { it.state == DownloadState.RUNNING }) inst.stopNow() else inst.refresh()
|
||||
}
|
||||
|
||||
private fun pausedId(key: String) = ID + 0x20000 + (key.hashCode() and 0xFFFF)
|
||||
|
||||
/** "<game> paused" with Resume, once the progress notification has gone with the service. */
|
||||
private fun pausedNote(context: Context, key: String) {
|
||||
val entry = StoresState.latestDownloads.firstOrNull { it.key == key } ?: return
|
||||
val i = Intent(context, StoreDownloadService::class.java).setAction(ACTION_RESUME).putExtra(EXTRA_KEY, key)
|
||||
val resume = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) PendingIntent.getForegroundService(context, key.hashCode() + 5, i, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
|
||||
else PendingIntent.getService(context, key.hashCode() + 5, i, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
|
||||
val n = Notification.Builder(context, DONE_CHANNEL)
|
||||
.setSmallIcon(android.R.drawable.stat_sys_download)
|
||||
.setContentTitle(entry.name).setContentText(context.getString(R.string.stores_dl_paused))
|
||||
.setContentIntent(resume).setAutoCancel(true)
|
||||
.addAction(Notification.Action.Builder(null, context.getString(R.string.stores_dl_resume), resume).build())
|
||||
.build()
|
||||
runCatching { context.getSystemService(NotificationManager::class.java)?.notify(pausedId(key), n) }
|
||||
}
|
||||
|
||||
/** "<game> installed" (opens it in Games) or "<game> download failed" (opens Downloads); dismissible. */
|
||||
fun ended(context: Context, entry: DownloadEntry, installed: Boolean, gamesKey: String?) {
|
||||
val app = context.applicationContext
|
||||
channels(app)
|
||||
val code = entry.key.hashCode()
|
||||
val n = Notification.Builder(app, DONE_CHANNEL)
|
||||
.setSmallIcon(if (installed) android.R.drawable.stat_sys_download_done else android.R.drawable.stat_notify_error)
|
||||
.setContentTitle(app.getString(if (installed) R.string.stores_notification_installed else R.string.stores_notification_failed, entry.name))
|
||||
.setAutoCancel(true)
|
||||
.setContentIntent(if (installed && gamesKey != null) openPage(app, gamesKey, code + 10) else openDownloads(app, code + 11))
|
||||
.build()
|
||||
runCatching { app.getSystemService(NotificationManager::class.java)?.notify(ID + 1 + (code and 0xFFFF), n) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The notification's one line for a download. Pure, for the test. */
|
||||
object DownloadNotificationText {
|
||||
fun line(d: DownloadEntry, stageName: String, paused: String, queued: String): String {
|
||||
val parts = ArrayList<String>()
|
||||
parts += d.name
|
||||
when {
|
||||
d.state == DownloadState.PAUSED -> parts += paused
|
||||
d.state == DownloadState.QUEUED -> parts += queued
|
||||
d.stage == DownloadStage.DOWNLOAD -> {
|
||||
if (d.bytesTotal > 0) { parts += "${d.percent}%"; parts += "${formatBytes(d.bytesDone)}/${formatBytes(d.bytesTotal)}" }
|
||||
if (d.speedBps > 0) parts += formatSpeed(d.speedBps)
|
||||
if (d.etaSeconds >= 0) parts += eta(d.etaSeconds)
|
||||
}
|
||||
else -> parts += if (d.stageFraction >= 0f) "$stageName ${d.percent}%" else stageName
|
||||
}
|
||||
return parts.joinToString(" · ")
|
||||
}
|
||||
|
||||
fun eta(seconds: Long): String = when {
|
||||
seconds < 60 -> "<1 min"
|
||||
seconds < 3600 -> "${seconds / 60} min"
|
||||
else -> "${seconds / 3600} h ${(seconds % 3600) / 60} min"
|
||||
}
|
||||
}
|
||||
@@ -149,11 +149,6 @@ public final class EpicApiClient {
|
||||
|
||||
/** `customAttributes.AdditionalCommandLine.value` for the game, "" when it has none, null when the call failed. */
|
||||
public static String getAdditionalCommandLine(String accessToken, String namespace, String catalogItemId) {
|
||||
return getCustomAttribute(accessToken, namespace, catalogItemId, "AdditionalCommandLine");
|
||||
}
|
||||
|
||||
/** `customAttributes.<name>.value` for the game (CloudSaveFolder, AdditionalCommandLine), "" when it has none, null when the call failed. */
|
||||
public static String getCustomAttribute(String accessToken, String namespace, String catalogItemId, String name) {
|
||||
try {
|
||||
String url = CATALOG_BASE + "/" + namespace + "/bulk/items?id=" + catalogItemId + "&country=US";
|
||||
String resp = getWithLegendaryUA(url, accessToken);
|
||||
@@ -164,10 +159,10 @@ public final class EpicApiClient {
|
||||
if (item == null) return "";
|
||||
JSONObject attrs = item.optJSONObject("customAttributes");
|
||||
if (attrs == null) return "";
|
||||
JSONObject attr = attrs.optJSONObject(name);
|
||||
JSONObject attr = attrs.optJSONObject("AdditionalCommandLine");
|
||||
return attr == null ? "" : attr.optString("value", "");
|
||||
} catch (Exception e) {
|
||||
Log.w(TAG, "catalog attribute " + name + ": " + e.getClass().getSimpleName());
|
||||
Log.w(TAG, "additional command line: " + e.getClass().getSimpleName());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,7 +42,7 @@ object EpicBackend : StoreBackend, EpicLaunchSupport {
|
||||
override fun syncLibrary(context: Context, force: Boolean) {
|
||||
val app = context.applicationContext
|
||||
val cached = EpicLibrary.cached(app)
|
||||
if (cached.isNotEmpty()) StoresState.post { StoresState.library[store] = com.droiddeck.launcher.stores.mergeItems(StoresState.library[store], cached.map { EpicLibrary.toCatalogItem(app, it) }) }
|
||||
if (cached.isNotEmpty()) StoresState.post { StoresState.library[store] = cached.map { EpicLibrary.toCatalogItem(app, it) } }
|
||||
StoresState.post { StoresState.status[store] = "Fetching your library…" }
|
||||
Thread({
|
||||
val result = EpicLibrary.sync(app, force) { line -> StoresState.post { StoresState.status[store] = line } }
|
||||
@@ -50,11 +50,11 @@ object EpicBackend : StoreBackend, EpicLaunchSupport {
|
||||
StoresState.status.remove(store)
|
||||
when (result) {
|
||||
is EpicLibrary.SyncResult.Ok -> {
|
||||
StoresState.library[store] = com.droiddeck.launcher.stores.mergeItems(StoresState.library[store], result.games.map { EpicLibrary.toCatalogItem(app, it) }); StoresState.problems.remove(store)
|
||||
StoresState.library[store] = result.games.map { EpicLibrary.toCatalogItem(app, it) }; StoresState.problems.remove(store)
|
||||
}
|
||||
is EpicLibrary.SyncResult.Failed -> StoresState.problems[store] = result.message
|
||||
EpicLibrary.SyncResult.NotLoggedIn -> StoresState.problems[store] = "Epic session expired: sign in again."
|
||||
EpicLibrary.SyncResult.Throttled -> if (!StoresState.library.containsKey(store)) StoresState.library[store] = com.droiddeck.launcher.stores.mergeItems(StoresState.library[store], cached.map { EpicLibrary.toCatalogItem(app, it) })
|
||||
EpicLibrary.SyncResult.Throttled -> if (!StoresState.library.containsKey(store)) StoresState.library[store] = cached.map { EpicLibrary.toCatalogItem(app, it) }
|
||||
EpicLibrary.SyncResult.Busy -> {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ object EpicLibrary {
|
||||
private const val TAG = "EpicLibrary"
|
||||
private const val CACHE_KEY = "library_cache"
|
||||
private const val LAST_SYNC_KEY = "library_synced_at"
|
||||
private const val THROTTLE_MS = 6L * 60L * 60L * 1000L
|
||||
private const val THROTTLE_MS = 15L * 60L * 1000L
|
||||
|
||||
private val syncing = AtomicBoolean(false)
|
||||
|
||||
@@ -114,6 +114,6 @@ object EpicLibrary {
|
||||
developer = g.developer, description = com.droiddeck.launcher.stores.cleanStoreText(g.description), owned = true,
|
||||
sizeBytes = EpicPrefs.get(context).getLong("size_${g.appName}", g.installSize),
|
||||
storeUrl = "https://store.epicgames.com/en-US/browse?q=${java.net.URLEncoder.encode(g.title, "UTF-8")}",
|
||||
extra = mapOf("namespace" to g.namespace, "catalogItemId" to g.catalogItemId, "version" to (g.version ?: "")),
|
||||
extra = mapOf("namespace" to g.namespace, "catalogItemId" to g.catalogItemId),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
/*
|
||||
* Epic Online Services (EOS) overlay provisioning for DroidDeck.
|
||||
*
|
||||
* Credits: the provisioning MECHANISM - download Epic's own overlay component
|
||||
* ("EpicOnlineServicesOverlay") and point a game's bundled EOS SDK at it through a single HKCU
|
||||
* registry value - comes from Legendary's legendary/lfs/eos.py, by way of The GameNative Team's
|
||||
* work (https://github.com/utkarshdalal/GameNative) and Bannerlator's EpicOverlayManager. The Epic
|
||||
* app identifiers, the registry key and the EOSOVH-Win64-Shipping.dll name are public facts from
|
||||
* Epic / Legendary. Original implementation.
|
||||
*
|
||||
* Reference: https://github.com/derrod/legendary - legendary/lfs/eos.py
|
||||
* Reference: https://github.com/utkarshdalal/GameNative
|
||||
*
|
||||
* Provision only: Epic's signed component is placed once, shared by every prefix, and each Epic
|
||||
* game's prefix gets the one pointer (written by droiddeck-store-launch before Proton starts, where
|
||||
* the prefix is known). The game's EOS SDK loads it itself - which is what lets a "corrective
|
||||
* action" (a consent Epic wants once per product) show in game instead of waiting on a browser.
|
||||
*/
|
||||
package com.droiddeck.launcher.stores.epic
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.stores.StoresState
|
||||
import java.io.File
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
object EpicOverlay {
|
||||
private const val TAG = "EpicOverlay"
|
||||
|
||||
// Epic's "EpicOnlineServicesOverlay" app (public, from Legendary).
|
||||
private const val OVERLAY_APP = "98bc04bc842e4906993fd6d6644ffb8d"
|
||||
private const val OVERLAY_NAMESPACE = "302e5ede476149b1bc3e4fe6ae45e50e"
|
||||
private const val OVERLAY_CATALOG_ITEM = "cc15684f44d849e89e9bf4cec0508b68"
|
||||
const val OVERLAY_DLL = "EOSOVH-Win64-Shipping.dll"
|
||||
|
||||
/** Inside the session: `/root/.local/share/droiddeck/epic-overlay`, which every prefix reaches as Z:. droiddeck-store-launch names the same path. */
|
||||
const val GUEST_DIR = "/root/.local/share/droiddeck/epic-overlay"
|
||||
private const val VERSION_FILE = "droiddeck-version"
|
||||
|
||||
private val busy = AtomicBoolean(false)
|
||||
|
||||
fun dir(context: Context): File = File(LinuxRuntime.rootDir(context), GUEST_DIR.removePrefix("/"))
|
||||
|
||||
/** The installed overlay's build, or null when it is not there. */
|
||||
fun installedVersion(context: Context): String? {
|
||||
val d = dir(context)
|
||||
if (!File(d, OVERLAY_DLL).let { it.isFile && it.length() > 0 }) return null
|
||||
return runCatching { File(d, VERSION_FILE).readText().trim() }.getOrNull()?.ifEmpty { null } ?: "unknown"
|
||||
}
|
||||
|
||||
/** Starts the download in the background when the overlay is missing; nothing when it is there or under way. */
|
||||
fun ensureAsync(context: Context) {
|
||||
val app = context.applicationContext
|
||||
if (installedVersion(app) != null || !busy.compareAndSet(false, true)) return
|
||||
Thread({
|
||||
try { ensure(app) } finally { busy.set(false) }
|
||||
}, "epic-overlay").start()
|
||||
}
|
||||
|
||||
/** Blocking: downloads Epic's overlay component when it is missing. True when it is in place afterwards. */
|
||||
fun ensure(context: Context): Boolean {
|
||||
val app = context.applicationContext
|
||||
if (installedVersion(app) != null) return true
|
||||
return try {
|
||||
val token = EpicCredentialStore.getValidAccessToken(app) ?: return false.also { Log.i(TAG, "overlay: not signed in") }
|
||||
val manifest = EpicApiClient.getManifestApiJson(token, OVERLAY_NAMESPACE, OVERLAY_CATALOG_ITEM, OVERLAY_APP)
|
||||
?: return false.also { Log.w(TAG, "overlay: manifest not fetched") }
|
||||
val target = dir(app).apply { mkdirs() }
|
||||
StoresState.logLine("epic: fetching the EOS overlay")
|
||||
val result = EpicDownloadManager.install(app, manifest, target.path, "", null, AtomicBoolean(false), object : EpicDownloadManager.Callback {
|
||||
override fun onProgress(message: String, pct: Int) {}
|
||||
override fun onLog(line: String) { StoresState.logLine(line) }
|
||||
})
|
||||
val ok = result != null && File(target, OVERLAY_DLL).isFile
|
||||
if (ok) File(target, VERSION_FILE).writeText(result!!.buildVersion.ifEmpty { "unknown" })
|
||||
Log.i(TAG, "overlay: " + if (ok) "installed ${result!!.buildVersion}" else "install did not produce $OVERLAY_DLL")
|
||||
ok
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "overlay: ${e.javaClass.simpleName}: ${e.message}")
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -26,7 +26,7 @@ object EpicStoreCatalog {
|
||||
private const val TAG = "EpicStore"
|
||||
private const val GRAPHQL = "https://store.epicgames.com/graphql"
|
||||
private const val PROMOS = "https://store-site-backend-static-ipv4.ak.epicgames.com/freeGamesPromotions"
|
||||
private const val FEATURED_TTL_MS = 3 * 60 * 60 * 1000L
|
||||
private const val FEATURED_TTL_MS = 30 * 60 * 1000L
|
||||
private const val SEARCH_TTL_MS = 5 * 60 * 1000L
|
||||
private const val KEY_FEATURED = "store_featured"
|
||||
|
||||
@@ -136,8 +136,6 @@ object EpicStoreCatalog {
|
||||
fun featured(context: Context, force: Boolean = false): StoreShelves? {
|
||||
val now = System.currentTimeMillis()
|
||||
featuredCache?.let { if (!force && now - it.at < FEATURED_TTL_MS) return it.value }
|
||||
// Shelves saved on an earlier run are as good while they are young: shown, not fetched again.
|
||||
if (!force && now - EpicPrefs.get(context).getLong("store_featured_at", 0L) < FEATURED_TTL_MS) cachedFeatured(context)?.let { return it }
|
||||
val freeNow = fetchPromos()
|
||||
val onSale = searchStore(24, sortBy = "currentPrice", sortDir = "ASC", onSale = true).filter { it.discountPercent > 0 }
|
||||
val newest = searchStore(24, sortBy = "releaseDate", sortDir = "DESC", releasedOnly = true)
|
||||
@@ -213,7 +211,7 @@ object EpicStoreCatalog {
|
||||
|
||||
private fun persist(context: Context, f: StoreShelves) {
|
||||
runCatching {
|
||||
EpicPrefs.get(context).edit().putString(KEY_FEATURED, JSONObject().put("new", listToJson(f.whatsNew)).put("deals", listToJson(f.deals)).put("free", listToJson(f.free)).put("trending", listToJson(f.trending)).toString()).putLong("store_featured_at", System.currentTimeMillis()).apply()
|
||||
EpicPrefs.get(context).edit().putString(KEY_FEATURED, JSONObject().put("new", listToJson(f.whatsNew)).put("deals", listToJson(f.deals)).put("free", listToJson(f.free)).put("trending", listToJson(f.trending)).toString()).apply()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -33,14 +33,14 @@ object GogBackend : StoreBackend {
|
||||
val app = context.applicationContext
|
||||
// The cache first, so the tab has something while the sync runs.
|
||||
val cached = GogLibrary.cached(app)
|
||||
if (cached.isNotEmpty()) StoresState.post { StoresState.library[store] = com.droiddeck.launcher.stores.mergeItems(StoresState.library[store], cached.map { GogLibrary.toCatalogItem(app, it) }) }
|
||||
if (cached.isNotEmpty()) StoresState.post { StoresState.library[store] = cached.map { GogLibrary.toCatalogItem(app, it) } }
|
||||
StoresState.post { StoresState.status[store] = "Fetching your library…" }
|
||||
Thread({
|
||||
val result = GogLibrary.sync(app, force) { line -> StoresState.post { StoresState.status[store] = line } }
|
||||
StoresState.post {
|
||||
StoresState.status.remove(store)
|
||||
when (result) {
|
||||
is GogLibrary.SyncResult.Ok -> { StoresState.library[store] = com.droiddeck.launcher.stores.mergeItems(StoresState.library[store], result.games.map { GogLibrary.toCatalogItem(app, it) }); StoresState.problems.remove(store) }
|
||||
is GogLibrary.SyncResult.Ok -> { StoresState.library[store] = result.games.map { GogLibrary.toCatalogItem(app, it) }; StoresState.problems.remove(store) }
|
||||
is GogLibrary.SyncResult.Failed -> StoresState.problems[store] = result.message
|
||||
GogLibrary.SyncResult.NotLoggedIn -> StoresState.problems[store] = "GOG session expired: sign in again."
|
||||
GogLibrary.SyncResult.Busy -> {}
|
||||
|
||||
@@ -258,9 +258,6 @@ public final class GogDownloadManager {
|
||||
deleteCounted(new File(installPath, ".gog_chunks"), cb);
|
||||
String clientId = manifest.optString("clientId", null);
|
||||
if (clientId != null && !clientId.isEmpty()) GogPrefs.get(ctx).edit().putString("client_id_" + game.gameId, clientId).apply();
|
||||
// The game's own client secret: cloud saves need a token issued to the game's client.
|
||||
String clientSecret = manifest.optString("clientSecret", null);
|
||||
if (clientSecret != null && !clientSecret.isEmpty()) GogPrefs.get(ctx).edit().putString("client_secret_" + game.gameId, clientSecret).apply();
|
||||
out.result = new Result(pickExe(installPath, tempExe, game.title), gm.buildId, planned);
|
||||
return out;
|
||||
} catch (Exception e) {
|
||||
@@ -546,39 +543,23 @@ public final class GogDownloadManager {
|
||||
final AtomicBoolean okRef = new AtomicBoolean(false);
|
||||
final AtomicBoolean linkExpiryRef = new AtomicBoolean(false);
|
||||
final AtomicReference<String> errRef = new AtomicReference<>("");
|
||||
// The bar between file completions: what earlier runs counted, plus the files this run
|
||||
// skipped as already verified (the engine credits those no bytes), plus the engine's own
|
||||
// byte count, which includes the files still in flight. Never shown going back.
|
||||
final long runStart = totalBytes.get();
|
||||
final AtomicLong verifiedInRun = new AtomicLong(0);
|
||||
final AtomicLong shownBytes = new AtomicLong(runStart);
|
||||
GogNative.Listener listener = new GogNative.Listener() {
|
||||
@Override public void onProgress(long bytesDone, long bytesTotal, int filesDone, int filesTotal, String file, long fileBytes, boolean verified) {
|
||||
donePaths.add(file);
|
||||
int done = doneCount.incrementAndGet();
|
||||
int pct = 15 + (int) ((done / (float) total) * 80);
|
||||
long tb = totalBytes.addAndGet(fileBytes);
|
||||
if (verified) verifiedInRun.addAndGet(fileBytes);
|
||||
long shown = shownBytes.accumulateAndGet(tb, Math::max);
|
||||
if (verified) { cb.onProgress(verifiedMsg, pct); cb.onBytes(shown, planned, speedBps.get()); return; }
|
||||
sampleSpeed(shown, lastSpeedMs, lastSpeedB, speedBps);
|
||||
if (verified) { cb.onProgress(verifiedMsg, pct); cb.onBytes(tb, planned, speedBps.get()); return; }
|
||||
sampleSpeed(tb, lastSpeedMs, lastSpeedB, speedBps);
|
||||
cb.onProgress("Downloading: " + baseName(file) + speedSuffix(speedBps.get()), pct);
|
||||
cb.onBytes(shown, planned, speedBps.get());
|
||||
}
|
||||
@Override public void onBytes(long bytesDone, long bytesTotal) {
|
||||
long shown = shownBytes.accumulateAndGet(Math.min(planned, runStart + verifiedInRun.get() + bytesDone), Math::max);
|
||||
sampleSpeed(shown, lastSpeedMs, lastSpeedB, speedBps);
|
||||
cb.onBytes(shown, planned, speedBps.get());
|
||||
cb.onBytes(tb, planned, speedBps.get());
|
||||
}
|
||||
@Override public void onLog(String line) { cb.onLog(line); }
|
||||
@Override public void onComplete(boolean success, boolean wasCancelled, boolean linkExpiry, String error, long bytesWritten, int filesDone) {
|
||||
okRef.set(success); linkExpiryRef.set(linkExpiry); errRef.set(error == null ? "" : error); latch.countDown();
|
||||
}
|
||||
};
|
||||
// Every CDN of the set: the engine spreads its window across the hosts (JNI.md).
|
||||
String[] bases = (base == null || base.isEmpty()) ? new String[0] : base.split("\n");
|
||||
if (run == 1) cb.onLog("gog: " + bases.length + " CDN host(s) offered");
|
||||
long handle = GogNative.start(kind, manifests, bases, installPath.getAbsolutePath(), donePaths.toArray(new String[0]), "",
|
||||
long handle = GogNative.start(kind, manifests, base, installPath.getAbsolutePath(), donePaths.toArray(new String[0]), "",
|
||||
workers, process, sortLargestFirst, label + " run=" + run, listener);
|
||||
if (handle == 0L) { cb.onLog("gog: native start failed"); anyFailed.set(true); return; }
|
||||
boolean interrupted = false;
|
||||
@@ -667,53 +648,24 @@ public final class GogDownloadManager {
|
||||
return tmpFile.renameTo(outFile);
|
||||
}
|
||||
|
||||
/**
|
||||
* Every CDN the secure link offers, as one value - their bases, one per line - so the set is
|
||||
* refreshed (and compared on expiry) as a whole. GOG answers with several hosts in {@code urls[]};
|
||||
* taking only the first left every request on one host.
|
||||
*/
|
||||
private static String parseCdnUrl(String json) {
|
||||
java.util.List<String> all = parseCdnUrls(json);
|
||||
return all.isEmpty() ? null : String.join("\n", all);
|
||||
}
|
||||
|
||||
/** The CDN bases of a secure_link answer, in the order GOG gives them. */
|
||||
static java.util.List<String> parseCdnUrls(String json) {
|
||||
java.util.List<String> out = new ArrayList<>();
|
||||
if (json == null) return out;
|
||||
if (json == null) return null;
|
||||
try {
|
||||
JSONArray urls = new JSONObject(json).optJSONArray("urls");
|
||||
if (urls == null) return out;
|
||||
for (int i = 0; i < urls.length(); i++) {
|
||||
JSONObject u = urls.optJSONObject(i);
|
||||
if (u == null) continue;
|
||||
String urlFormat = u.optString("url_format");
|
||||
JSONObject params = u.optJSONObject("parameters");
|
||||
if (urlFormat == null || urlFormat.isEmpty() || params == null) continue;
|
||||
java.util.Iterator<String> keys = params.keys();
|
||||
while (keys.hasNext()) { String k = keys.next(); urlFormat = urlFormat.replace("{" + k + "}", params.optString(k)); }
|
||||
urlFormat = urlFormat.replace("\\/", "/");
|
||||
int idx = urlFormat.indexOf("/{path}");
|
||||
if (idx >= 0) urlFormat = urlFormat.substring(0, idx);
|
||||
if (!out.contains(urlFormat)) out.add(urlFormat);
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
if (urls == null || urls.length() == 0) return null;
|
||||
JSONObject first = urls.getJSONObject(0);
|
||||
String urlFormat = first.optString("url_format");
|
||||
JSONObject params = first.optJSONObject("parameters");
|
||||
if (urlFormat == null || params == null) return null;
|
||||
java.util.Iterator<String> keys = params.keys();
|
||||
while (keys.hasNext()) { String k = keys.next(); urlFormat = urlFormat.replace("{" + k + "}", params.optString(k)); }
|
||||
urlFormat = urlFormat.replace("\\/", "/");
|
||||
int idx = urlFormat.indexOf("/{path}");
|
||||
if (idx >= 0) urlFormat = urlFormat.substring(0, idx);
|
||||
return urlFormat;
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static final AtomicInteger CDN_TURN = new AtomicInteger();
|
||||
|
||||
/** One of the set's CDNs, in turn, so the Java pool spreads its requests over all of them. */
|
||||
static String pickCdn(String set) {
|
||||
String[] all = set.split("\n");
|
||||
return all[Math.floorMod(CDN_TURN.getAndIncrement(), all.length)];
|
||||
}
|
||||
|
||||
/** The first CDN of the set - what a caller that takes a single base gets. */
|
||||
static String firstCdn(String set) {
|
||||
int nl = set.indexOf('\n');
|
||||
return nl < 0 ? set : set.substring(0, nl);
|
||||
}
|
||||
|
||||
private static boolean downloadRange(String url, long offset, long size, File out) {
|
||||
@@ -895,7 +847,7 @@ public final class GogDownloadManager {
|
||||
while (guard++ < 8) {
|
||||
if (cancelled.get()) return null;
|
||||
String base = cdnBaseRef.get();
|
||||
HttpResult res = fetchBytesEx(buildChunkUrl(pickCdn(base), chunkPath), null);
|
||||
HttpResult res = fetchBytesEx(buildChunkUrl(base, chunkPath), null);
|
||||
if (res.body == null) {
|
||||
int code = res.status;
|
||||
if ((code == 401 || code == 403 || code == 404 || code == 500) && tryRefreshCdn(cdnBaseRef, base, secureLinkUrl, token, cdnRefreshCount, maxCdnRefresh, cb)) continue;
|
||||
|
||||
@@ -23,7 +23,7 @@ object GogLibrary {
|
||||
// v2: the card art moved from the store page's backdrop to the Galaxy library art; an older cache is re-fetched.
|
||||
private const val CACHE_KEY = "library_cache_v2"
|
||||
private const val LAST_SYNC_KEY = "library_synced_at"
|
||||
private const val THROTTLE_MS = 6L * 60L * 60L * 1000L
|
||||
private const val THROTTLE_MS = 15L * 60L * 1000L
|
||||
|
||||
private val syncing = AtomicBoolean(false)
|
||||
|
||||
|
||||
@@ -28,12 +28,6 @@ object GogNative {
|
||||
*/
|
||||
fun onProgress(bytesDone: Long, bytesTotal: Long, filesDone: Int, filesTotal: Int, file: String, fileBytes: Long, verified: Boolean)
|
||||
|
||||
/**
|
||||
* Byte progress between file completions, every 250 ms while fetching (and once at the end):
|
||||
* assembled bytes plus what the files in flight have so far. Drives the bar and the speed.
|
||||
*/
|
||||
fun onBytes(bytesDone: Long, bytesTotal: Long)
|
||||
|
||||
/** Engine diagnostics (already in logcat under `GogNative`). */
|
||||
fun onLog(line: String)
|
||||
|
||||
@@ -66,12 +60,12 @@ object GogNative {
|
||||
*/
|
||||
@JvmStatic
|
||||
fun start(
|
||||
kind: Int, depotManifests: Array<String>, cdnBases: Array<String>, installDir: String, skipPaths: Array<String>,
|
||||
kind: Int, depotManifests: Array<String>, cdnBase: String, installDir: String, skipPaths: Array<String>,
|
||||
caBundlePath: String, maxWorkers: Int, processWorkers: Int, sortLargestFirst: Boolean, label: String, listener: Listener,
|
||||
): Long {
|
||||
if (!isAvailable()) return 0L
|
||||
return try {
|
||||
nativeStart(kind, depotManifests, cdnBases, installDir, skipPaths, caBundlePath, maxWorkers, processWorkers, sortLargestFirst, label, listener)
|
||||
nativeStart(kind, depotManifests, cdnBase, installDir, skipPaths, caBundlePath, maxWorkers, processWorkers, sortLargestFirst, label, listener)
|
||||
} catch (t: Throwable) {
|
||||
Log.e(TAG, "nativeStart threw: ${t.javaClass.simpleName}: ${t.message}")
|
||||
0L
|
||||
@@ -97,7 +91,7 @@ object GogNative {
|
||||
|
||||
@JvmStatic
|
||||
private external fun nativeStart(
|
||||
kind: Int, depotManifests: Array<String>, cdnBases: Array<String>, installDir: String, skipPaths: Array<String>,
|
||||
kind: Int, depotManifests: Array<String>, cdnBase: String, installDir: String, skipPaths: Array<String>,
|
||||
caBundlePath: String, maxWorkers: Int, processWorkers: Int, sortLargestFirst: Boolean, label: String, listener: Listener,
|
||||
): Long
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ import java.util.concurrent.ConcurrentHashMap
|
||||
object GogStoreCatalog {
|
||||
private const val TAG = "GogStore"
|
||||
private const val CATALOG = "https://catalog.gog.com/v1/catalog"
|
||||
private const val FEATURED_TTL_MS = 3 * 60 * 60 * 1000L
|
||||
private const val FEATURED_TTL_MS = 30 * 60 * 1000L
|
||||
private const val SEARCH_TTL_MS = 5 * 60 * 1000L
|
||||
// v2: entries carry the mature mark; an older cache would show everything until it aged out.
|
||||
private const val KEY_FEATURED = "store_featured_v2"
|
||||
@@ -61,8 +61,6 @@ object GogStoreCatalog {
|
||||
fun featured(context: Context, force: Boolean = false): StoreShelves? {
|
||||
val now = System.currentTimeMillis()
|
||||
featuredCache?.let { if (!force && now - it.at < FEATURED_TTL_MS) return it.value }
|
||||
// Shelves saved on an earlier run are as good while they are young: shown, not fetched again.
|
||||
if (!force && now - GogPrefs.get(context).getLong("store_featured_at", 0L) < FEATURED_TTL_MS) cachedFeatured(context)?.let { return it }
|
||||
val trending = fetchProducts(baseQuery(24, "desc:trending"))
|
||||
val newest = fetchProducts(baseQuery(40, "desc:releaseDate")).filter { !isFuture(it.releaseDate) }.take(24)
|
||||
val deals = fetchProducts(baseQuery(24, "desc:discount", "&discounted=eq:true"))
|
||||
@@ -197,7 +195,7 @@ object GogStoreCatalog {
|
||||
private fun persist(context: Context, f: StoreShelves) {
|
||||
runCatching {
|
||||
val o = JSONObject().put("trending", listToJson(f.trending)).put("new", listToJson(f.whatsNew)).put("deals", listToJson(f.deals)).put("free", listToJson(f.free))
|
||||
GogPrefs.get(context).edit().putString(KEY_FEATURED, o.toString()).putLong("store_featured_at", System.currentTimeMillis()).apply()
|
||||
GogPrefs.get(context).edit().putString(KEY_FEATURED, o.toString()).apply()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -197,19 +197,15 @@ private fun ManageSaves(g: Library.SteamGame, prefix: java.io.File, a: FrontEndA
|
||||
}
|
||||
}
|
||||
Box {
|
||||
// A GOG or Epic game's saves are its cloud saves: the one place for them, named so.
|
||||
val cloudGame = com.droiddeck.launcher.stores.Store.byId(g.source).let { it == com.droiddeck.launcher.stores.Store.GOG || it == com.droiddeck.launcher.stores.Store.EPIC }
|
||||
val label = stringResource(if (cloudGame) R.string.store_cloud_saves else R.string.games_manage_saves)
|
||||
SecondaryButton(label, compact = true) { open = !open }
|
||||
AnchoredMenu(open, onDismiss = { open = false }, title = if (cloudGame) label else stringResource(R.string.games_saves), note = summary) { first ->
|
||||
if (cloudGame) CloudRows(g, open, first)
|
||||
MenuItem(stringResource(R.string.games_import_saves), checked = false, focusRequester = if (cloudGame) null else first) {
|
||||
SecondaryButton(stringResource(R.string.games_manage_saves), compact = true) { open = !open }
|
||||
AnchoredMenu(open, onDismiss = { open = false }, title = stringResource(R.string.games_saves), note = summary) { first ->
|
||||
MenuItem(stringResource(R.string.games_import_saves), checked = false, detail = stringResource(R.string.games_import_saves_hint), focusRequester = first) {
|
||||
open = false; a.onSaveImport(g)
|
||||
}
|
||||
MenuItem(stringResource(R.string.games_export_gamehub), checked = false) {
|
||||
MenuItem(stringResource(R.string.games_export_gamehub), checked = false, detail = stringResource(R.string.games_export_gamehub_hint)) {
|
||||
open = false; a.onSaveExport(g, com.droiddeck.launcher.session.GameSaves.Layout.GAMEHUB)
|
||||
}
|
||||
MenuItem(stringResource(R.string.games_export_winlator), checked = false) {
|
||||
MenuItem(stringResource(R.string.games_export_winlator), checked = false, detail = stringResource(R.string.games_export_winlator_hint)) {
|
||||
open = false; a.onSaveExport(g, com.droiddeck.launcher.session.GameSaves.Layout.WINLATOR)
|
||||
}
|
||||
found?.firstOrNull()?.let { d ->
|
||||
@@ -221,61 +217,6 @@ private fun ManageSaves(g: Library.SteamGame, prefix: java.io.File, a: FrontEndA
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A GOG or Epic game's cloud saves: the Cloud saves switch, Upload and Download - three rows from
|
||||
* the first frame, so nothing moves under the pad while the cloud is checked. Until the check is
|
||||
* back the two actions are disabled and read "…"; then only their subtitles change: the last sync,
|
||||
* "No cloud saves", or a conflict, when Upload and Download become Keep local and Keep cloud.
|
||||
*/
|
||||
@Composable
|
||||
private fun CloudRows(g: Library.SteamGame, open: Boolean, first: androidx.compose.ui.focus.FocusRequester) {
|
||||
val store = com.droiddeck.launcher.stores.Store.byId(g.source)?.takeIf { it != com.droiddeck.launcher.stores.Store.AMAZON } ?: return
|
||||
val id = g.storeId ?: return
|
||||
val context = androidx.compose.ui.platform.LocalContext.current.applicationContext
|
||||
var busy by remember(g.gameId) { androidx.compose.runtime.mutableStateOf<String?>(null) }
|
||||
var tick by remember(g.gameId) { androidx.compose.runtime.mutableStateOf(0) }
|
||||
val status by androidx.compose.runtime.produceState<com.droiddeck.launcher.stores.CloudSaves.Status?>(null, g.gameId, open, tick) {
|
||||
if (open) value = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
|
||||
runCatching { com.droiddeck.launcher.stores.CloudSaves.status(context, store, id) }.getOrNull()
|
||||
}
|
||||
}
|
||||
// The game's own switch (sidecar "cloud"), known locally: right from the first frame.
|
||||
val folder = g.gameFiles
|
||||
var enabled by remember(g.gameId, open) { androidx.compose.runtime.mutableStateOf(folder?.let { com.droiddeck.launcher.stores.StoreGameSidecar.read(it)?.cloud } ?: true) }
|
||||
val st = status
|
||||
val supported = st?.supported ?: true
|
||||
val conflict = st != null && st.conflicts.isNotEmpty()
|
||||
fun sync(up: Boolean, force: Boolean = false) {
|
||||
if (busy != null) return
|
||||
busy = if (up) "up" else "down"
|
||||
Thread({
|
||||
val r = if (up) com.droiddeck.launcher.stores.CloudSaves.upload(context, store, id, force) else com.droiddeck.launcher.stores.CloudSaves.download(context, store, id, force)
|
||||
com.droiddeck.launcher.stores.StoresState.post { busy = null; tick++; android.widget.Toast.makeText(context, if (r.ok) context.getString(R.string.cloud_done, r.files) else r.reason, android.widget.Toast.LENGTH_SHORT).show() }
|
||||
}, "cloud-manual").start()
|
||||
}
|
||||
MenuItem(stringResource(R.string.store_cloud_saves), checked = enabled && supported, enabled = supported, focusRequester = first,
|
||||
detail = if (!supported) stringResource(R.string.cloud_none) else null) {
|
||||
val f = folder ?: return@MenuItem
|
||||
val next = !enabled
|
||||
Thread({
|
||||
val written = runCatching { com.droiddeck.launcher.stores.StoreGameSidecar.updateCloud(f, next) }.getOrNull()
|
||||
com.droiddeck.launcher.stores.StoresState.post { enabled = written?.cloud ?: enabled }
|
||||
}, "cloud-switch").start()
|
||||
}
|
||||
val ready = st != null && supported && busy == null
|
||||
val pending = stringResource(R.string.cloud_pending)
|
||||
val summary = when {
|
||||
st == null || busy != null -> pending
|
||||
!supported -> stringResource(R.string.cloud_none)
|
||||
conflict -> stringResource(R.string.cloud_conflict_files, st.conflicts.size)
|
||||
st.lastSync > 0 -> stringResource(R.string.cloud_last_sync, android.text.format.DateUtils.getRelativeTimeSpanString(st.lastSync).toString())
|
||||
else -> stringResource(R.string.cloud_never)
|
||||
}
|
||||
// A conflict turns the two actions into its two answers; the rows stay where they are.
|
||||
MenuItem(stringResource(if (conflict) R.string.cloud_keep_local else R.string.cloud_upload), checked = false, enabled = ready, detail = summary) { sync(up = true, force = conflict) }
|
||||
MenuItem(stringResource(if (conflict) R.string.cloud_keep_cloud else R.string.cloud_download), checked = false, enabled = ready, detail = if (st == null || busy != null) pending else null) { sync(up = false, force = conflict) }
|
||||
}
|
||||
|
||||
/** When it was last played (or where it is, if never) over its name, then room for Launch. */
|
||||
@Composable
|
||||
private fun ColumnScope.GameHeroCopy(g: Library.SteamGame, titleSize: androidx.compose.ui.unit.TextUnit) {
|
||||
|
||||
@@ -135,8 +135,6 @@ class FrontEndState(
|
||||
val gameStoresSpeedTier: String = "fast",
|
||||
/** Setup › Stores: the tab a signed-in store opens on (SessionPrefs.STORES_OPEN_LIBRARY / STORE). */
|
||||
val storesOpenTab: String = SessionPrefs.STORES_OPEN_LIBRARY,
|
||||
/** A page to open once: "stores:downloads", or a selection such as "app:<id>" (a notification's tap). */
|
||||
val navigate: String? = null,
|
||||
val storesShowMature: Boolean = false,
|
||||
/** Downloads queued, running or paused across the three stores; the rail item's badge. */
|
||||
val storeDownloadsActive: Int = 0,
|
||||
@@ -193,7 +191,6 @@ class FrontEndActions(
|
||||
val onGameStoresEnabled: (Boolean) -> Unit = {},
|
||||
val onGameStoresSpeedTier: (String) -> Unit = {},
|
||||
val onStoresOpenTab: (String) -> Unit = {},
|
||||
val onNavigated: () -> Unit = {},
|
||||
val onStoresShowMature: (Boolean) -> Unit = {},
|
||||
/** The Games list rebuilt now: a store install or removal changed what is on disk. */
|
||||
val onLibraryChanged: () -> Unit = {},
|
||||
@@ -374,11 +371,6 @@ fun FrontEndScreen(s: FrontEndState, a: FrontEndActions, page: (@Composable () -
|
||||
private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Composable () -> Unit)?, frontFocus: FrontFocus) {
|
||||
var selected by rememberSaveable { mutableStateOf(if (s.shortcutPicker) "games" else "steam") }
|
||||
LaunchedEffect(s.shortcutPicker) { if (s.shortcutPicker) selected = "games" }
|
||||
LaunchedEffect(s.navigate) {
|
||||
val target = s.navigate ?: return@LaunchedEffect
|
||||
if (target == "stores:downloads") { com.droiddeck.launcher.stores.StoresState.openDownloads = true; selected = "stores" } else selected = target
|
||||
a.onNavigated()
|
||||
}
|
||||
var showWirelessAdbFix by rememberSaveable { mutableStateOf(false) }
|
||||
var showDeveloperDisplayChoice by rememberSaveable { mutableStateOf(false) }
|
||||
var wirelessAdbDesiredEnabled by rememberSaveable { mutableStateOf(false) }
|
||||
|
||||
@@ -477,11 +477,9 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
|
||||
if (controller != null) add { m -> SettingCard(stringResource(R.string.setup_card_controls), stringResource(R.string.setup_card_controls_hint), "card:controls", m, controller.onMapping) }
|
||||
// An Epic game's own launch choices, kept in its sidecar so a launch from the Steam client
|
||||
// honours them too (droiddeck-store-launch reads the same file).
|
||||
// Epic's launch choices; cloud saves live in the game's Cloud saves view, so a GOG game has no card.
|
||||
val cardStore = com.droiddeck.launcher.stores.Store.byId(game?.source.orEmpty())?.takeIf { it == com.droiddeck.launcher.stores.Store.EPIC }
|
||||
if (cardStore != null && game?.gameFiles != null) add { m ->
|
||||
if (game?.source == com.droiddeck.launcher.stores.Store.EPIC.id && game.gameFiles != null) add { m ->
|
||||
Box(m) {
|
||||
StoreLaunchCard(host, game.gameFiles!!, cardStore)
|
||||
EpicLaunchCard(host, game.gameFiles!!)
|
||||
}
|
||||
}
|
||||
if (wincompKey != null) add { m ->
|
||||
@@ -510,17 +508,16 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
|
||||
/** Epic's account page behind its sign-in: signing in there presents any step the account still owes. */
|
||||
private const val EPIC_RESOLVE_URL = "https://www.epicgames.com/id/login?redirectUrl=https%3A%2F%2Fwww.epicgames.com%2Faccount%2Fpersonal"
|
||||
|
||||
/** The Epic card: the sign-in and offline switches, read from and written to the game's sidecar, and Resolve Epic sign-in. */
|
||||
/** The Epic card: sign-in, offline and overlay switches, read from and written to the game's sidecar. */
|
||||
@Composable
|
||||
private fun StoreLaunchCard(host: MenuHost, folder: java.io.File, store: com.droiddeck.launcher.stores.Store) {
|
||||
private fun EpicLaunchCard(host: MenuHost, folder: java.io.File) {
|
||||
val appContext = androidx.compose.ui.platform.LocalContext.current.applicationContext
|
||||
var sidecar by remember(folder) { mutableStateOf(com.droiddeck.launcher.stores.StoreGameSidecar.read(folder)) }
|
||||
val options = sidecar?.epic ?: com.droiddeck.launcher.stores.EpicOptions()
|
||||
val epic = store == com.droiddeck.launcher.stores.Store.EPIC
|
||||
val key = "store-" + store.id
|
||||
val value = buildList {
|
||||
if (epic && options.offline) add(stringResource(R.string.epic_card_offline))
|
||||
else if (epic && options.eos) add(stringResource(R.string.epic_card_eos))
|
||||
if (options.offline) add(stringResource(R.string.epic_card_offline))
|
||||
else if (options.eos) add(stringResource(R.string.epic_card_eos))
|
||||
if (options.overlay) add(stringResource(R.string.epic_card_overlay))
|
||||
}.ifEmpty { listOf(stringResource(R.string.epic_card_none)) }.joinToString(" · ")
|
||||
// Each switch goes straight to the sidecar on disk - both launch paths read it there - and the
|
||||
// card shows what was read back, so a write that did not take is never shown as done.
|
||||
@@ -528,20 +525,19 @@ private fun StoreLaunchCard(host: MenuHost, folder: java.io.File, store: com.dro
|
||||
Thread({
|
||||
val written = runCatching { com.droiddeck.launcher.stores.StoreGameSidecar.updateEpic(folder, change) }
|
||||
.onFailure { android.util.Log.w("EpicLaunchCard", "could not write ${folder.name}: ${it.message}") }.getOrNull()
|
||||
if (written != null) android.util.Log.i("EpicLaunchCard", "epic options ${written.id} eos=${written.epic.eos} offline=${written.epic.offline}")
|
||||
if (written != null) android.util.Log.i("EpicLaunchCard", "epic options ${written.id} eos=${written.epic.eos} offline=${written.epic.offline} overlay=${written.epic.overlay}")
|
||||
if (written?.epic?.overlay == true) com.droiddeck.launcher.stores.epic.EpicOverlay.ensureAsync(appContext)
|
||||
else android.util.Log.w("EpicLaunchCard", "epic options not saved for ${folder.name}")
|
||||
com.droiddeck.launcher.stores.StoresState.post { sidecar = written ?: com.droiddeck.launcher.stores.StoreGameSidecar.read(folder) }
|
||||
}, "epic-options").start()
|
||||
}
|
||||
SettingCard(store.shortLabel, value, "card:$key", Modifier.fillMaxSize()) {
|
||||
host.open = if (host.open == key) null else key
|
||||
SettingCard(stringResource(R.string.epic_card_title), value, "card:epic", Modifier.fillMaxSize()) {
|
||||
host.open = if (host.open == "epic") null else "epic"
|
||||
}
|
||||
AnchoredMenu(host.open == key, onDismiss = { if (host.open == key) host.open = null }, title = store.shortLabel) { first ->
|
||||
if (epic) {
|
||||
MenuItem(stringResource(R.string.epic_eos), checked = options.eos, focusRequester = first) { set { it.copy(eos = !it.eos) } }
|
||||
MenuItem(stringResource(R.string.epic_offline), checked = options.offline) { set { it.copy(offline = !it.offline) } }
|
||||
}
|
||||
if (epic) {
|
||||
AnchoredMenu(host.open == "epic", onDismiss = { if (host.open == "epic") host.open = null }, title = stringResource(R.string.epic_card_title)) { first ->
|
||||
MenuItem(stringResource(R.string.epic_eos), checked = options.eos, focusRequester = first) { set { it.copy(eos = !it.eos) } }
|
||||
MenuItem(stringResource(R.string.epic_offline), checked = options.offline) { set { it.copy(offline = !it.offline) } }
|
||||
MenuItem(stringResource(R.string.epic_overlay), checked = options.overlay) { set { it.copy(overlay = !it.overlay) } }
|
||||
// Epic asks some accounts to accept something once (privacy policy, EULA) before a game may
|
||||
// sign in - EOS's "corrective action". Signing in on Epic's site shows it.
|
||||
MenuItem(stringResource(R.string.epic_resolve), checked = false) {
|
||||
@@ -550,7 +546,6 @@ private fun StoreLaunchCard(host: MenuHost, folder: java.io.File, store: com.dro
|
||||
appContext.startActivity(android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse(EPIC_RESOLVE_URL)).addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -76,6 +76,7 @@ class ModeSettings(
|
||||
val backActionsInverted: Boolean = false,
|
||||
val directAudio: Boolean?,
|
||||
val mic: Boolean?,
|
||||
val renderer: String?,
|
||||
val gameStorage: String? = null,
|
||||
val storageOptions: List<com.droiddeck.launcher.session.GameStorage.Option> = emptyList(),
|
||||
/** Steam only: record allocation and sampled storage timings in the next session's Share logs. */
|
||||
@@ -139,6 +140,7 @@ class ModeSettingsActions(
|
||||
val onBackActionsInverted: (Boolean) -> Unit = {},
|
||||
val onDirectAudio: (Boolean) -> Unit,
|
||||
val onMic: (Boolean) -> Unit,
|
||||
val onRenderer: (String) -> Unit,
|
||||
val onGameStorage: (path: String, label: String) -> Unit = { _, _ -> },
|
||||
val onPickGameStorageFolder: () -> Unit = {},
|
||||
val onStorageDiagnostics: (Boolean) -> Unit = {},
|
||||
@@ -526,6 +528,14 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
|
||||
onChange = a.onStorageDiagnostics,
|
||||
)
|
||||
}
|
||||
if (!steam && tab == ModeSettingsTab.DISPLAY && s.renderer != null) SettingsGroup(stringResource(R.string.mode_renderer)) {
|
||||
ChoiceRow(
|
||||
host, "renderer", stringResource(R.string.mode_desktop_renderer), stringResource(R.string.mode_renderer_hint),
|
||||
listOf("vulkan" to stringResource(R.string.mode_renderer_vulkan), "gles2" to stringResource(R.string.mode_renderer_gles2), "pixman" to stringResource(R.string.mode_renderer_pixman)), s.renderer,
|
||||
note = stringResource(R.string.mode_renderer_note),
|
||||
onPick = a.onRenderer,
|
||||
)
|
||||
}
|
||||
}
|
||||
if (explainWifiDiscovery) AlertDialog(
|
||||
onDismissRequest = { explainWifiDiscovery = false },
|
||||
|
||||
@@ -20,13 +20,11 @@ fun ResolutionRow(
|
||||
val size = SessionDisplay.resolveChoice(panel, choice)
|
||||
val screen = SessionDisplay.screenSize(panel)
|
||||
val choices = SessionDisplay.resolutionOptions(panel)
|
||||
val selected = if (choice == SessionDisplay.FOLLOW_SCREEN) choice
|
||||
else if (size == screen) SessionDisplay.MATCH_SCREEN else choice
|
||||
val selected = if (size == screen) SessionDisplay.MATCH_SCREEN else choice
|
||||
var editCustom by remember { mutableStateOf(false) }
|
||||
val options = choices.map { value ->
|
||||
val dimensions = SessionDisplay.resolveChoice(panel, value)
|
||||
value to if (value == SessionDisplay.MATCH_SCREEN) stringResource(R.string.display_match_screen, screen.first, screen.second)
|
||||
else if (value == SessionDisplay.FOLLOW_SCREEN) stringResource(R.string.display_follow_screen)
|
||||
else if (value == SessionDisplay.DEFAULT_RESOLUTION) stringResource(R.string.mode_res_default, "${dimensions.first}×${dimensions.second}")
|
||||
else "${dimensions.first}×${dimensions.second}"
|
||||
} + (custom to if (selected in choices) stringResource(R.string.mode_res_custom)
|
||||
|
||||
@@ -233,19 +233,6 @@ class MenuHost {
|
||||
@Composable
|
||||
fun rememberMenuHost(): MenuHost = remember { MenuHost() }
|
||||
|
||||
/** Under the anchor with left edges aligned, kept on screen: a dropdown that belongs to a tab. */
|
||||
private class BelowStartProvider(private val gap: Int) : PopupPositionProvider {
|
||||
override fun calculatePosition(anchorBounds: IntRect, windowSize: IntSize, layoutDirection: LayoutDirection, popupContentSize: IntSize): IntOffset {
|
||||
var x = anchorBounds.left
|
||||
if (x + popupContentSize.width > windowSize.width - 8) x = windowSize.width - 8 - popupContentSize.width
|
||||
if (x < 8) x = 8
|
||||
var y = anchorBounds.bottom + gap
|
||||
if (y + popupContentSize.height > windowSize.height - 8) y = anchorBounds.top - gap - popupContentSize.height
|
||||
if (y < 8) y = 8
|
||||
return IntOffset(x, y)
|
||||
}
|
||||
}
|
||||
|
||||
private class BelowEndProvider(private val gap: Int) : PopupPositionProvider {
|
||||
override fun calculatePosition(anchorBounds: IntRect, windowSize: IntSize, layoutDirection: LayoutDirection, popupContentSize: IntSize): IntOffset {
|
||||
var x = anchorBounds.right - popupContentSize.width
|
||||
@@ -258,12 +245,7 @@ private class BelowEndProvider(private val gap: Int) : PopupPositionProvider {
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun AnchoredMenu(
|
||||
open: Boolean, onDismiss: () -> Unit, title: String? = null, note: String? = null,
|
||||
/** A tab's dropdown: under its anchor, left edges aligned, as wide as its entries (within [minWidth]..260 dp). */
|
||||
compact: Boolean = false, minWidth: androidx.compose.ui.unit.Dp = 120.dp,
|
||||
content: @Composable ColumnScope.(FocusRequester) -> Unit,
|
||||
) {
|
||||
fun AnchoredMenu(open: Boolean, onDismiss: () -> Unit, title: String? = null, note: String? = null, content: @Composable ColumnScope.(FocusRequester) -> Unit) {
|
||||
val state = remember { MutableTransitionState(false) }
|
||||
state.targetState = open
|
||||
if (!state.currentState && !state.targetState && state.isIdle) return
|
||||
@@ -277,14 +259,14 @@ fun AnchoredMenu(
|
||||
}
|
||||
}
|
||||
val gap = with(LocalDensity.current) { 6.dp.roundToPx() }
|
||||
val provider = remember(gap, compact) { if (compact) BelowStartProvider(gap) else BelowEndProvider(gap) }
|
||||
val provider = remember(gap) { BelowEndProvider(gap) }
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
Popup(popupPositionProvider = provider, onDismissRequest = onDismiss, properties = PopupProperties(focusable = true)) {
|
||||
AnimatedVisibility(
|
||||
visibleState = state,
|
||||
enter = fadeIn(Motion.tw(180)) + scaleIn(Motion.sp(0.7f), initialScale = 0.94f, transformOrigin = TransformOrigin(if (compact) 0f else 1f, 0f)),
|
||||
exit = fadeOut(Motion.tw(140)) + scaleOut(Motion.tw(140), targetScale = 0.96f, transformOrigin = TransformOrigin(if (compact) 0f else 1f, 0f)),
|
||||
enter = fadeIn(Motion.tw(180)) + scaleIn(Motion.sp(0.7f), initialScale = 0.94f, transformOrigin = TransformOrigin(1f, 0f)),
|
||||
exit = fadeOut(Motion.tw(140)) + scaleOut(Motion.tw(140), targetScale = 0.96f, transformOrigin = TransformOrigin(1f, 0f)),
|
||||
label = "menu",
|
||||
) {
|
||||
// A long list (a driver menu with its downloads) must not run off the screen: the menu is
|
||||
@@ -292,7 +274,7 @@ fun AnchoredMenu(
|
||||
val maxHeight = (androidx.compose.ui.platform.LocalConfiguration.current.screenHeightDp * 0.86f).dp
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.then(if (compact) Modifier.widthIn(min = minWidth, max = 260.dp).width(androidx.compose.foundation.layout.IntrinsicSize.Max) else Modifier.widthIn(min = 220.dp, max = 340.dp))
|
||||
.widthIn(min = 220.dp, max = 340.dp)
|
||||
.heightIn(max = maxHeight)
|
||||
.shadow(24.dp, RowShape, ambientColor = Color.Black, spotColor = Color.Black)
|
||||
.clip(RowShape)
|
||||
|
||||
@@ -1,14 +1,5 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.ui.draw.alpha
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.hoverable
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.material.icons.automirrored.outlined.Undo
|
||||
import androidx.compose.material.icons.outlined.Delete
|
||||
import androidx.compose.material.icons.outlined.Close
|
||||
import androidx.compose.material.icons.filled.Refresh
|
||||
import androidx.compose.material.icons.filled.Pause
|
||||
import coil.compose.AsyncImage
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.graphics.Brush
|
||||
@@ -84,77 +75,9 @@ private fun DownloadList(s: FrontEndState, a: FrontEndActions) {
|
||||
}
|
||||
return
|
||||
}
|
||||
// Under way on top; finished below a line whose X clears them all (rows only - a failed
|
||||
// download's kept files stay until its game page's Clear).
|
||||
val (active, finished) = entries.partition { it.isActive }
|
||||
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
// The list changes only when rows come, go or change state; each row reads its own progress.
|
||||
active.forEachIndexed { i, row -> key(row.key) { Rise(1 + i.coerceAtMost(5)) { DownloadCard(StoresState.download(row.key) ?: row, s, a) } } }
|
||||
if (finished.isNotEmpty()) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().padding(top = if (active.isEmpty()) 0.dp else 4.dp)) {
|
||||
Box(Modifier.weight(1f).height(1.dp).background(LocalPalette.current.line))
|
||||
RoundAction(Icons.Outlined.Close, stringResource(R.string.stores_dl_clear_all), size = 30.dp) { DownloadQueue.dismissFinished() }
|
||||
}
|
||||
finished.forEach { row ->
|
||||
key(row.key) {
|
||||
val d = StoresState.download(row.key) ?: row
|
||||
if (d.state == DownloadState.FAILED) DownloadCard(d, s, a) else FinishedRow(d, s, a)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A finished download: its name and store, and Play when it installed. */
|
||||
@Composable
|
||||
private fun FinishedRow(d: DownloadEntry, s: FrontEndState, a: FrontEndActions) {
|
||||
val ctx = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp),
|
||||
modifier = Modifier.fillMaxWidth().clip(Shape12).background(colors.surface).padding(horizontal = 12.dp, vertical = 6.dp),
|
||||
) {
|
||||
Text(d.name, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))
|
||||
SourceChip(d.store.id, small = true)
|
||||
Text(stringResource(if (d.state == DownloadState.INSTALLED) R.string.stores_installed_chip else R.string.stores_dl_cancelled), fontSize = 11.sp, color = colors.onSurfaceVariant, maxLines = 1, modifier = Modifier.weight(1f))
|
||||
if (d.state == DownloadState.INSTALLED) RoundAction(Icons.Filled.PlayArrow, stringResource(R.string.stores_play), primary = true) { launchStoreGame(ctx, d.store, d.id, s, a) }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A row's action as a round icon button - the label is its description - sized like the old
|
||||
* compact buttons and focusable by pad. [primary] fills it with the accent, [danger] in red.
|
||||
*/
|
||||
@Composable
|
||||
internal fun RoundAction(
|
||||
icon: androidx.compose.ui.graphics.vector.ImageVector, description: String, primary: Boolean = false, danger: Boolean = false,
|
||||
enabled: Boolean = true, size: androidx.compose.ui.unit.Dp = 36.dp, onClick: () -> Unit,
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val src = remember { androidx.compose.foundation.interaction.MutableInteractionSource() }
|
||||
val hot = rememberHot(src)
|
||||
val fill = when { danger -> Color(0xFFD9443B); primary -> pal.signal; else -> colors.surface.copy(alpha = 0.85f) }
|
||||
val tint = if (primary || danger) Color.White else if (hot) pal.signal else colors.onBackground
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.size(size).clip(androidx.compose.foundation.shape.CircleShape).background(fill)
|
||||
.glideBorder(hot, androidx.compose.foundation.shape.CircleShape, if (primary || danger) colors.onBackground else pal.signal, pal.line)
|
||||
.alpha(if (enabled) 1f else 0.4f)
|
||||
.hoverable(src).clickable(interactionSource = src, indication = androidx.compose.foundation.LocalIndication.current, enabled = enabled, role = androidx.compose.ui.semantics.Role.Button, onClick = onClick)
|
||||
.controllerConfirm(enabled = enabled, onClick = onClick),
|
||||
) { androidx.compose.material3.Icon(icon, description, tint = tint, modifier = Modifier.size(size * 0.5f)) }
|
||||
}
|
||||
|
||||
/** Cancel in two taps: the stop icon, then a red delete and a keep that undoes it (back by itself after a few seconds). */
|
||||
@Composable
|
||||
private fun CancelAction(onDelete: () -> Unit) {
|
||||
var armed by remember { mutableStateOf(false) }
|
||||
androidx.compose.runtime.LaunchedEffect(armed) { if (armed) { kotlinx.coroutines.delay(4000); armed = false } }
|
||||
if (!armed) RoundAction(Icons.Outlined.Close, stringResource(R.string.stores_dl_cancel)) { armed = true }
|
||||
else {
|
||||
RoundAction(Icons.Outlined.Delete, stringResource(R.string.stores_dl_cancel_confirm), danger = true) { armed = false; onDelete() }
|
||||
RoundAction(Icons.AutoMirrored.Outlined.Undo, stringResource(R.string.stores_notification_keep)) { armed = false }
|
||||
entries.forEachIndexed { i, row -> key(row.key) { Rise(1 + i.coerceAtMost(5)) { DownloadCard(StoresState.download(row.key) ?: row, s, a) } } }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -204,20 +127,26 @@ private fun DownloadCard(d: DownloadEntry, s: FrontEndState, a: FrontEndActions)
|
||||
}
|
||||
}
|
||||
}
|
||||
// The row's actions on the right, over the art: icons, their labels as descriptions.
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
// The row's actions on the right, over the art.
|
||||
Column(verticalArrangement = Arrangement.spacedBy(6.dp), horizontalAlignment = Alignment.End) {
|
||||
when (d.state) {
|
||||
DownloadState.RUNNING, DownloadState.QUEUED -> {
|
||||
RoundAction(Icons.Filled.Pause, stringResource(R.string.stores_dl_pause)) { DownloadQueue.pause(d.key) }
|
||||
CancelAction { DownloadQueue.cancel(ctx, d.key) }
|
||||
SecondaryButton(stringResource(R.string.stores_dl_pause), compact = true) { DownloadQueue.pause(d.key) }
|
||||
ConfirmButton(stringResource(R.string.stores_dl_cancel), stringResource(R.string.stores_dl_cancel_confirm), compact = true) { DownloadQueue.cancel(ctx, d.key) }
|
||||
}
|
||||
DownloadState.PAUSED -> {
|
||||
RoundAction(Icons.Filled.PlayArrow, stringResource(R.string.stores_dl_resume), primary = true) { DownloadQueue.resume(ctx, d.key) }
|
||||
CancelAction { DownloadQueue.cancel(ctx, d.key) }
|
||||
PrimaryButton(stringResource(R.string.stores_dl_resume), compact = true) { DownloadQueue.resume(ctx, d.key) }
|
||||
ConfirmButton(stringResource(R.string.stores_dl_cancel), stringResource(R.string.stores_dl_cancel_confirm), compact = true) { DownloadQueue.cancel(ctx, d.key) }
|
||||
}
|
||||
DownloadState.FAILED -> RoundAction(Icons.Filled.Refresh, stringResource(R.string.stores_dl_resume), primary = true) { DownloadQueue.retry(ctx, d.key) }
|
||||
DownloadState.INSTALLED -> RoundAction(Icons.Filled.PlayArrow, stringResource(R.string.stores_play), primary = true) { launchStoreGame(ctx, d.store, d.id, s, a) }
|
||||
DownloadState.CANCELLED -> {}
|
||||
DownloadState.FAILED -> {
|
||||
PrimaryButton(stringResource(R.string.stores_dl_resume), compact = true) { DownloadQueue.retry(ctx, d.key) }
|
||||
ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) { DownloadQueue.clear(ctx, d.key) }
|
||||
}
|
||||
DownloadState.INSTALLED -> {
|
||||
PrimaryButton(stringResource(R.string.stores_play), compact = true, icon = Icons.Filled.PlayArrow) { launchStoreGame(ctx, d.store, d.id, s, a) }
|
||||
SecondaryButton(stringResource(R.string.stores_dl_clear), compact = true) { DownloadQueue.dismiss(d.key) }
|
||||
}
|
||||
DownloadState.CANCELLED -> SecondaryButton(stringResource(R.string.stores_dl_clear), compact = true) { DownloadQueue.dismiss(d.key) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,5 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.ui.layout.boundsInWindow
|
||||
import androidx.compose.ui.layout.onGloballyPositioned
|
||||
import androidx.compose.ui.layout.onSizeChanged
|
||||
import androidx.compose.ui.draw.drawWithContent
|
||||
import androidx.compose.ui.draw.drawBehind
|
||||
import androidx.compose.ui.graphics.Brush
|
||||
import androidx.compose.ui.draw.clipToBounds
|
||||
import androidx.compose.ui.draw.blur
|
||||
@@ -91,15 +86,15 @@ import com.droiddeck.launcher.stores.formatBytes
|
||||
/** The chip row's fourth entry, beside the three stores. */
|
||||
private const val DOWNLOADS = "downloads"
|
||||
|
||||
private val TABS = listOf("store", "library")
|
||||
private val TABS = listOf("store", "installed", "library", "all")
|
||||
|
||||
/**
|
||||
* The tabs a store has: Store and Library (whose dropdown filters All / Installed). Amazon has no
|
||||
* public catalog, so Library alone.
|
||||
* The tabs a store has. Amazon has no public catalog: its Store and All would only repeat the
|
||||
* library, so it has Installed and Library alone.
|
||||
*/
|
||||
internal fun tabsFor(store: Store?): List<String> = if (store == Store.AMAZON) listOf("library") else TABS
|
||||
internal fun tabsFor(store: Store?): List<String> = if (store == Store.AMAZON) listOf("installed", "library") else TABS
|
||||
|
||||
/** [tab] if [store] has it, else Library (the open-on Store choice, or an old Installed / All, falls back there). */
|
||||
/** [tab] if [store] has it, else Library (the open-on Store choice falls back there for Amazon). */
|
||||
internal fun tabFor(store: Store?, tab: String): String = if (tab in tabsFor(store)) tab else "library"
|
||||
|
||||
@Composable
|
||||
@@ -112,7 +107,6 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
|
||||
var query by rememberSaveable { mutableStateOf("") }
|
||||
var openGame by rememberSaveable { mutableStateOf<String?>(null) }
|
||||
var settings by rememberSaveable { mutableStateOf(false) }
|
||||
LaunchedEffect(StoresState.openDownloads) { if (StoresState.openDownloads) { chip = DOWNLOADS; StoresState.openDownloads = false } }
|
||||
val store = Store.byId(chip)
|
||||
// A tab this store does not have (Store or All on Amazon) reads as Library.
|
||||
val shownTab = tabFor(store, tab)
|
||||
@@ -159,24 +153,12 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
|
||||
onNext = { if (openGame == null && chip != DOWNLOADS) { val t = tabsFor(store); switchTab(t[(t.indexOf(shownTab) + 1) % t.size]) } },
|
||||
),
|
||||
) {
|
||||
// The chip row stays put and paints nothing - the page's background shows through it. What
|
||||
// scrolls is clipped at the row's lower edge and, once scrolled, faded out there: the
|
||||
// content's own alpha, not a colour laid over it.
|
||||
Box(Modifier.fillMaxWidth().padding(bottom = 8.dp)) {
|
||||
// The chip row stays put on the page's own ground; what scrolls passes under it, clipped,
|
||||
// with a short fade where it meets the row.
|
||||
Box(Modifier.fillMaxWidth().background(MaterialTheme.colorScheme.background).padding(bottom = 8.dp)) {
|
||||
Rise(0) { StoreChips(chip, s.storeDownloadsActive, onPick = pickChip, onSettings = { settings = true }) }
|
||||
}
|
||||
val fade = with(androidx.compose.ui.platform.LocalDensity.current) { 14.dp.toPx() }
|
||||
Box(
|
||||
Modifier.fillMaxWidth().weight(1f, fill = false).clipToBounds()
|
||||
.graphicsLayer { compositingStrategy = androidx.compose.ui.graphics.CompositingStrategy.Offscreen }
|
||||
.drawWithContent {
|
||||
drawContent()
|
||||
if (scroll.value > 0 && size.height > fade) drawRect(
|
||||
Brush.verticalGradient(0f to Color.Transparent, fade / size.height to Color.Black),
|
||||
blendMode = androidx.compose.ui.graphics.BlendMode.DstIn,
|
||||
)
|
||||
},
|
||||
) {
|
||||
Box(Modifier.fillMaxWidth().weight(1f, fill = false).clipToBounds()) {
|
||||
Column(modifier = Modifier.fillMaxWidth().verticalScroll(scroll).padding(top = 4.dp, bottom = 16.dp)) {
|
||||
when {
|
||||
chip == DOWNLOADS -> StoresDownloadsPane(s, a)
|
||||
@@ -189,6 +171,10 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
|
||||
else -> Storefront(store, shownTab, query, s, a, onTab = { switchTab(it) }, onQuery = { query = it }, onOpen = { open(it) })
|
||||
}
|
||||
}
|
||||
if (scroll.value > 0) Spacer(
|
||||
Modifier.align(Alignment.TopCenter).fillMaxWidth().height(14.dp)
|
||||
.background(Brush.verticalGradient(0f to MaterialTheme.colorScheme.background, 1f to Color.Transparent)),
|
||||
)
|
||||
}
|
||||
}
|
||||
if (settings) StoresSettingsDialog(s, a) { settings = false }
|
||||
@@ -324,27 +310,18 @@ private fun Storefront(
|
||||
// The storefront leaves out what the store rates or tags as adult unless the user shows it; owned games always show.
|
||||
fun shown(i: CatalogItem) = s.storesShowMature || !i.mature || i.owned
|
||||
fun shelf(l: List<CatalogItem>?) = l?.filter(::shown)
|
||||
// The Store tab's search: the catalog the shelves brought and the library, each title once.
|
||||
// Everything this store knows about: the library plus whatever the shelves brought, each title once.
|
||||
val everything = remember(library, shelves) { (library + (shelves?.all ?: emptyList())).distinctBy { it.id } }
|
||||
// Library's dropdown: All (every owned game, the default) or Installed.
|
||||
var installedOnly by rememberSaveable(store) { mutableStateOf(false) }
|
||||
var filterOpen by remember { mutableStateOf(false) }
|
||||
val libraryLabel = if (installedOnly) stringResource(R.string.stores_tab_count, stringResource(R.string.stores_tab_installed), installedItems.size)
|
||||
else stringResource(R.string.stores_tab_count, stringResource(R.string.stores_tab_library), library.size)
|
||||
Rise(1) {
|
||||
SubTabs(
|
||||
listOf("store" to stringResource(R.string.stores_tab_store), "library" to libraryLabel).filter { it.first in tabsFor(store) },
|
||||
tab,
|
||||
onPick = { key -> if (key == "library") { if (tab == "library") filterOpen = !filterOpen else onTab(key) } else onTab(key) },
|
||||
menuFor = { key, tabWidth ->
|
||||
if (key == "library") AnchoredMenu(filterOpen, onDismiss = { filterOpen = false }, compact = true, minWidth = tabWidth) { first ->
|
||||
MenuItem(stringResource(R.string.stores_tab_count, stringResource(R.string.stores_tab_all), library.size), checked = !installedOnly, focusRequester = first) { installedOnly = false; filterOpen = false; onTab("library") }
|
||||
MenuItem(stringResource(R.string.stores_tab_count, stringResource(R.string.stores_tab_installed), installedItems.size), checked = installedOnly) { installedOnly = true; filterOpen = false; onTab("library") }
|
||||
}
|
||||
},
|
||||
listOf(
|
||||
"store" to stringResource(R.string.stores_tab_store),
|
||||
"installed" to stringResource(R.string.stores_tab_count, stringResource(R.string.stores_tab_installed), installedItems.size),
|
||||
"library" to stringResource(R.string.stores_tab_count, stringResource(R.string.stores_tab_library), library.size),
|
||||
"all" to stringResource(R.string.stores_tab_count, stringResource(R.string.stores_tab_all), everything.size),
|
||||
).filter { it.first in tabsFor(store) },
|
||||
tab, onTab,
|
||||
trailing = {
|
||||
// A purchase made elsewhere shows on a refresh; otherwise the library refreshes itself every six hours.
|
||||
SmallTextButton(stringResource(R.string.stores_refresh)) { StoresState.open(ctx, store, force = true) }
|
||||
val name = StoresState.accounts[store] ?: ""
|
||||
SmallTextButton(stringResource(R.string.stores_signout_named, name)) { StoresState.signOut(ctx, store) }
|
||||
},
|
||||
@@ -353,10 +330,11 @@ private fun Storefront(
|
||||
Rise(2) {
|
||||
SearchField(
|
||||
query, onQuery,
|
||||
placeholder = when {
|
||||
tab == "store" -> stringResource(R.string.stores_search_catalog, store.label)
|
||||
installedOnly -> stringResource(R.string.stores_search_installed)
|
||||
else -> stringResource(R.string.stores_search_library)
|
||||
placeholder = when (tab) {
|
||||
"store" -> stringResource(R.string.stores_search_catalog, store.label)
|
||||
"installed" -> stringResource(R.string.stores_search_installed)
|
||||
"library" -> stringResource(R.string.stores_search_library)
|
||||
else -> stringResource(R.string.stores_search_all, store.label)
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -370,8 +348,9 @@ private fun Storefront(
|
||||
GameCard(item, store, s, a, installedKeys, onOpen, first)
|
||||
}
|
||||
when (tab) {
|
||||
"library" -> if (installedOnly) Grid(installedItems.filter(::matches), stringResource(R.string.stores_installed_empty), card)
|
||||
else Grid(library.filter(::matches), if (library.isEmpty() && StoresState.status[store] != null) stringResource(R.string.stores_library_loading) else stringResource(R.string.stores_nothing_matches), card)
|
||||
"installed" -> Grid(installedItems.filter(::matches), stringResource(R.string.stores_installed_empty), card)
|
||||
"library" -> Grid(library.filter(::matches), if (library.isEmpty() && StoresState.status[store] != null) stringResource(R.string.stores_library_loading) else stringResource(R.string.stores_nothing_matches), card)
|
||||
"all" -> Grid(everything.filter(::matches), stringResource(R.string.stores_nothing_matches), card)
|
||||
else -> {
|
||||
if (q.isNotEmpty()) Grid(everything.filter { matches(it) && shown(it) }, stringResource(R.string.stores_nothing_matches), card)
|
||||
else {
|
||||
@@ -389,10 +368,7 @@ private fun Storefront(
|
||||
|
||||
/** Underlined tabs as the preview draws them, with [trailing] (the account) at the right. */
|
||||
@Composable
|
||||
private fun SubTabs(
|
||||
tabs: List<Pair<String, String>>, selected: String, onPick: (String) -> Unit,
|
||||
menuFor: @Composable (String, androidx.compose.ui.unit.Dp) -> Unit = { _, _ -> }, trailing: @Composable () -> Unit,
|
||||
) {
|
||||
private fun SubTabs(tabs: List<Pair<String, String>>, selected: String, onPick: (String) -> Unit, trailing: @Composable () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
Column(Modifier.fillMaxWidth()) {
|
||||
@@ -403,9 +379,6 @@ private fun SubTabs(
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = rememberHot(src)
|
||||
val pick = { onPick(key) }
|
||||
val density = androidx.compose.ui.platform.LocalDensity.current
|
||||
var width by remember { mutableStateOf(0.dp) }
|
||||
Box(Modifier.onSizeChanged { width = with(density) { it.width.toDp() } }) {
|
||||
Column(
|
||||
modifier = Modifier.paneItem("storetab:$key").clip(RoundedCornerShape(8.dp))
|
||||
.background(if (hot) pal.signal.copy(alpha = 0.12f) else Color.Transparent)
|
||||
@@ -417,9 +390,6 @@ private fun SubTabs(
|
||||
Text(label, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = if (on) colors.onBackground else colors.onSurfaceVariant, maxLines = 1)
|
||||
Box(Modifier.padding(top = 4.dp).fillMaxWidth().height(2.dp).background(if (on) pal.signal else Color.Transparent))
|
||||
}
|
||||
// A tab's own dropdown (Library's filter), anchored under it.
|
||||
menuFor(key, width)
|
||||
}
|
||||
}
|
||||
}
|
||||
trailing()
|
||||
@@ -477,13 +447,7 @@ private fun Grid(items: List<CatalogItem>, empty: String, card: @Composable (Cat
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A card's least width: shelf cards are this wide and a grid fits as many columns as the width
|
||||
* allows at it (the columns then share the leftover), so a display-density setting changes the
|
||||
* column count rather than the cards' size. 25% under the first 150 dp: five columns where there
|
||||
* were four on the Pocket FIT.
|
||||
*/
|
||||
private val CardWidth = 112.dp
|
||||
private val CardWidth = 150.dp
|
||||
|
||||
/**
|
||||
* One title: its wide art, the title, a price or status line and one button that says the one
|
||||
@@ -502,18 +466,8 @@ private fun GameCard(item: CatalogItem, store: Store, s: FrontEndState, a: Front
|
||||
val installed = item.id in installedKeys
|
||||
val download = StoresState.download("${store.id}:${item.id}")?.takeIf { it.isActive }
|
||||
val open = { onOpen(item.key) }
|
||||
// A size the library did not give is looked up once the card is on screen or close to it.
|
||||
val screen = with(androidx.compose.ui.platform.LocalDensity.current) { androidx.compose.ui.platform.LocalConfiguration.current.screenHeightDp.dp.toPx() }
|
||||
val ahead = screen / 2
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
.onGloballyPositioned { c ->
|
||||
if (item.owned && item.sizeBytes <= 0) {
|
||||
val b = c.boundsInWindow()
|
||||
if (b.bottom > -ahead && b.top < screen + ahead && b.width > 0f) com.droiddeck.launcher.stores.StoreSizes.request(ctx, item)
|
||||
}
|
||||
}
|
||||
.paneItem("card:${item.key}").then(if (first) Modifier.firstTile() else Modifier).graphicsLayer { scaleX = scale; scaleY = scale }
|
||||
modifier = Modifier.fillMaxWidth().paneItem("card:${item.key}").then(if (first) Modifier.firstTile() else Modifier).graphicsLayer { scaleX = scale; scaleY = scale }
|
||||
.clip(RoundedCornerShape(10.dp)).glideBorder(hot, RoundedCornerShape(10.dp), pal.signal, pal.line)
|
||||
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = open).controllerConfirm(onClick = open),
|
||||
) {
|
||||
@@ -537,7 +491,7 @@ private fun SyncBar(line: String) {
|
||||
}
|
||||
|
||||
/** How tall the card's one line is, over the blurred foot of its art. */
|
||||
private val CardStrip = 26.dp
|
||||
private val CardStrip = 28.dp
|
||||
|
||||
/**
|
||||
* The card is its art: sharp above, and under the one line a blurred, darkened copy of the same
|
||||
@@ -582,18 +536,10 @@ private fun CardMarker(item: CatalogItem, installed: Boolean, download: com.droi
|
||||
val pal = LocalPalette.current
|
||||
val small = 10.sp
|
||||
when {
|
||||
// Installed: its size on disk and a small check after it.
|
||||
installed -> Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(3.dp)) {
|
||||
val ctx = LocalContext.current
|
||||
val game = StoresState.installedGame(item.store, item.id)
|
||||
if (game != null) androidx.compose.runtime.LaunchedEffect(item.key) { com.droiddeck.launcher.stores.StoreSizes.requestDisk(ctx, item.key, game) }
|
||||
com.droiddeck.launcher.stores.StoreSizes.onDisk[item.key]?.let { Text(formatBytes(it), fontSize = 11.sp, fontWeight = FontWeight.Bold, color = Color.White, maxLines = 1) }
|
||||
Icon(Icons.Filled.Check, stringResource(R.string.stores_installed_chip), tint = pal.good, modifier = Modifier.size(11.dp))
|
||||
}
|
||||
installed -> Icon(Icons.Filled.Check, stringResource(R.string.stores_installed_chip), tint = pal.good, modifier = Modifier.size(14.dp))
|
||||
download != null -> Text("${download.percent}%", fontSize = small, fontWeight = FontWeight.Bold, color = pal.signal, maxLines = 1)
|
||||
item.owned && StoresState.isUnfinished(item) -> Text(stringResource(R.string.stores_resume), fontSize = small, fontWeight = FontWeight.Bold, color = pal.signal, maxLines = 1)
|
||||
// The size in the title's own type; nothing until it is known.
|
||||
item.owned -> com.droiddeck.launcher.stores.StoreSizes.size(item).takeIf { it > 0 }?.let { Text(formatBytes(it), fontSize = 11.sp, fontWeight = FontWeight.Bold, color = Color.White, maxLines = 1) }
|
||||
item.owned -> if (item.sizeBytes > 0) Text(formatBytes(item.sizeBytes), fontSize = small, color = Color.White.copy(alpha = 0.8f), maxLines = 1)
|
||||
item.isFree -> Text(stringResource(R.string.stores_free), fontSize = small, fontWeight = FontWeight.Bold, color = pal.good, maxLines = 1)
|
||||
item.isDiscounted -> Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
StateChip("-${item.discountPercent}%", ChipTone.DEAL, small = true)
|
||||
@@ -621,15 +567,9 @@ internal fun ProgressBarThin(fraction: Float, paused: Boolean = false, verify: B
|
||||
val pal = LocalPalette.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val fill = when { done -> pal.good; paused -> Color(0xFFFFC24D); verify -> Color(0xFF9B6DFF); else -> pal.signal }
|
||||
// The fill glides to each new value over a quarter second - progress arrives a few times a second
|
||||
// and in steps - and is read only while drawing, so the bar animates without relayout.
|
||||
val shown = androidx.compose.animation.core.animateFloatAsState(
|
||||
fraction.coerceIn(0f, 1f), androidx.compose.animation.core.tween(250, easing = androidx.compose.animation.core.LinearEasing), label = "bar",
|
||||
)
|
||||
Box(
|
||||
Modifier.fillMaxWidth().height(height).clip(RoundedCornerShape(height / 2)).background(colors.surfaceVariant)
|
||||
.drawBehind { drawRect(fill, size = androidx.compose.ui.geometry.Size(size.width * shown.value, size.height)) },
|
||||
)
|
||||
Box(Modifier.fillMaxWidth().height(height).clip(RoundedCornerShape(height / 2)).background(colors.surfaceVariant)) {
|
||||
Box(Modifier.fillMaxWidth(fraction.coerceIn(0f, 1f)).height(height).background(fill))
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
|
||||
@@ -82,12 +82,7 @@ internal fun WinComponentsDialog(
|
||||
// Detector names (oalinst, physx...) already in the prefix from elsewhere.
|
||||
var present by remember { mutableStateOf(emptySet<String>()) }
|
||||
var picks by remember { mutableStateOf(WinComponents.picks(context, appKey)) }
|
||||
// The row being worked on: its id, the latest progress (a dependency's while that installs
|
||||
// first), and whether it is turning off rather than on. The row greys out and shows the bar
|
||||
// the moment the switch is pressed, and only that row; the rest of the page stays as it is.
|
||||
var busyId by remember { mutableStateOf<String?>(null) }
|
||||
var progress by remember { mutableStateOf<WinComponents.Progress?>(null) }
|
||||
var reverting by remember { mutableStateOf(false) }
|
||||
var progress by remember { mutableStateOf<Pair<String, Int>?>(null) }
|
||||
var error by remember { mutableStateOf<String?>(null) }
|
||||
// The component the error is about, so it shows on its own row and not only at the bottom.
|
||||
var failed by remember { mutableStateOf<String?>(null) }
|
||||
@@ -96,7 +91,6 @@ internal fun WinComponentsDialog(
|
||||
// pad, so the d-pad always has somewhere to start; LB and RB jump between the sections, since
|
||||
// the full list runs past sixty switches.
|
||||
val recFocus = remember { FocusRequester() }
|
||||
val activeFocus = remember { FocusRequester() }
|
||||
val allFocus = remember { FocusRequester() }
|
||||
val waitFocus = remember { FocusRequester() }
|
||||
val doneFocus = remember { FocusRequester() }
|
||||
@@ -122,35 +116,22 @@ internal fun WinComponentsDialog(
|
||||
}
|
||||
fun toggle(id: String, on: Boolean) {
|
||||
// Switches stay enabled during a download - a disabled one drops the pad's focus - so a press
|
||||
// then is ignored here; the busy row is greyed instead.
|
||||
if (busyId != null) return
|
||||
// then is ignored here.
|
||||
if (progress != null) return
|
||||
error = null
|
||||
failed = null
|
||||
if (!on) {
|
||||
// Turning off is a saved pick, quick, but the row greys out until it is written so the
|
||||
// press is seen to land; the files leave the prefix at the game's next launch.
|
||||
busyId = id; reverting = true; progress = null
|
||||
val next = picks - id
|
||||
picks = next
|
||||
coroutine.launch {
|
||||
withContext(Dispatchers.IO) { WinComponents.setPicks(context, appKey, next) }
|
||||
busyId = null; reverting = false
|
||||
}
|
||||
return
|
||||
}
|
||||
if (!on) { setPicks(picks - id); return }
|
||||
val all = catalog.orEmpty()
|
||||
val c = all[id]
|
||||
if (id in installed || c == null) { setPicks(picks + id); return }
|
||||
busyId = id; reverting = false
|
||||
progress = WinComponents.Progress(id, "", WinComponents.Phase.DOWNLOAD, -1)
|
||||
progress = id to -1
|
||||
coroutine.launch {
|
||||
val problem = withContext(Dispatchers.IO) {
|
||||
WinComponents.install(context, c, all) { p -> progress = p }
|
||||
WinComponents.install(context, c, all) { stage, percent -> progress = stage to percent }
|
||||
}
|
||||
progress = null
|
||||
installed = withContext(Dispatchers.IO) { WinComponents.installedIds(context).toSet() }
|
||||
if (problem != null) { error = problem; failed = id } else setPicks(picks + id)
|
||||
busyId = null
|
||||
}
|
||||
}
|
||||
|
||||
@@ -161,18 +142,12 @@ internal fun WinComponentsDialog(
|
||||
val recIds = if (all == null) emptyList() else recommended.distinctBy { installable(it.componentName, all) }
|
||||
val ready = all.orEmpty().values.filter { WinComponents.support(it, all.orEmpty()) == Support.READY }.map { it.name }
|
||||
val extra = (installed + picks).filter { all?.containsKey(it) != true }
|
||||
// What is turned on for this game gets its own section under the recommendations, which stay
|
||||
// where they are; the rest of the list is everything else, so a component turned off goes back
|
||||
// to its place in the alphabet.
|
||||
val recSet = recIds.map { installable(it.componentName, all.orEmpty()) }.toSet()
|
||||
val active = picks.filter { it !in recSet && (all?.containsKey(it) == true || it in installed) }.distinct()
|
||||
.sortedBy { WinComponentNames.of(it).lowercase() }
|
||||
val list = (ready + extra).distinct().filter { it !in active }.sortedBy { WinComponentNames.of(it).lowercase() }
|
||||
val list = (ready + extra).distinct().sortedBy { WinComponentNames.of(it).lowercase() }
|
||||
val waiting = all.orEmpty().values.filter { WinComponents.support(it, all.orEmpty()) == Support.NEEDS_INSTALLER }
|
||||
.map { it.name }.sortedBy { WinComponentNames.of(it).lowercase() }
|
||||
val hasRec = all != null && recIds.any { supportOf(installable(it.componentName, all)) == Support.READY }
|
||||
val sections = listOfNotNull(recFocus.takeIf { hasRec }, activeFocus.takeIf { active.isNotEmpty() },
|
||||
allFocus.takeIf { list.isNotEmpty() }, waitFocus.takeIf { waiting.isNotEmpty() }, doneFocus)
|
||||
val sections = listOfNotNull(recFocus.takeIf { hasRec }, allFocus.takeIf { list.isNotEmpty() },
|
||||
waitFocus.takeIf { waiting.isNotEmpty() }, doneFocus)
|
||||
var section by remember { mutableStateOf(0) }
|
||||
fun jump(step: Int) {
|
||||
section = (section + step + sections.size) % sections.size
|
||||
@@ -189,7 +164,7 @@ internal fun WinComponentsDialog(
|
||||
withFrameNanos { }
|
||||
runCatching { target.requestFocus() }
|
||||
withFrameNanos { }
|
||||
if (switchFocused || (target !== recFocus && target !== activeFocus && target !== allFocus)) return@LaunchedEffect
|
||||
if (switchFocused || (target !== recFocus && target !== allFocus)) return@LaunchedEffect
|
||||
}
|
||||
}
|
||||
|
||||
@@ -214,24 +189,9 @@ internal fun WinComponentsDialog(
|
||||
// The catalog key stays in the detail: it is what a log or a bug report names.
|
||||
val detail = listOfNotNull(reason, c?.description?.takeIf { it.isNotEmpty() }, status, id).joinToString(" · ")
|
||||
val usable = support == Support.READY
|
||||
val busy = id == busyId
|
||||
val caption = when {
|
||||
!busy -> null
|
||||
reverting -> stringResource(R.string.wincomp_reverting)
|
||||
else -> progress?.let { p ->
|
||||
val stage = if (p.component != id && p.stage.isNotEmpty()) "${WinComponentNames.of(p.component)}: ${p.stage}" else p.stage
|
||||
val text = when (p.phase) {
|
||||
WinComponents.Phase.DOWNLOAD -> stringResource(R.string.wincomp_downloading, stage)
|
||||
WinComponents.Phase.INSTALL -> stringResource(R.string.wincomp_installing, stage)
|
||||
}
|
||||
if (p.percent >= 0) "$text · ${p.percent}%" else text
|
||||
}
|
||||
}
|
||||
ComponentRow(
|
||||
WinComponentNames.of(id), detail, checked = id in picks, enabled = usable || id in picks,
|
||||
dim = !usable || busy, busy = busy, caption = caption,
|
||||
percent = if (busy && !reverting) progress?.percent ?: -1 else -1,
|
||||
modifier = (if (usable && focus != null) Modifier.focusRequester(focus) else Modifier)
|
||||
dim = !usable, modifier = (if (usable && focus != null) Modifier.focusRequester(focus) else Modifier)
|
||||
.onFocusChanged { if (it.isFocused) switchFocused = true },
|
||||
) { on -> toggle(id, on) }
|
||||
}
|
||||
@@ -260,11 +220,6 @@ internal fun WinComponentsDialog(
|
||||
}
|
||||
} else if (all != null && gameDir != null) Small(stringResource(R.string.wincomp_no_recommendation))
|
||||
|
||||
if (active.isNotEmpty()) {
|
||||
Section(stringResource(R.string.wincomp_active, active.size))
|
||||
val focusOf = firstUsable(active, activeFocus)
|
||||
Panel { active.forEachIndexed { i, id -> if (i > 0) Divider(); Item(id, null, focusOf(id)) } }
|
||||
}
|
||||
if (list.isNotEmpty()) {
|
||||
Section(stringResource(R.string.wincomp_all, list.size))
|
||||
val focusOf = firstUsable(list, allFocus)
|
||||
@@ -283,11 +238,16 @@ internal fun WinComponentsDialog(
|
||||
if (showWaiting) Panel { waiting.forEachIndexed { i, id -> if (i > 0) Divider(); Item(id, null, null) } }
|
||||
}
|
||||
|
||||
progress?.let { (stage, percent) ->
|
||||
Small(if (percent >= 0) "$stage · $percent%" else stage)
|
||||
if (percent >= 0) LinearProgressIndicator(progress = { percent / 100f }, modifier = Modifier.fillMaxWidth())
|
||||
else LinearProgressIndicator(Modifier.fillMaxWidth())
|
||||
}
|
||||
error?.let { Small(it, error = true) }
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(top = 4.dp)) {
|
||||
Small(stringResource(R.string.wincomp_next_launch))
|
||||
Spacer(Modifier.weight(1f))
|
||||
PrimaryButton(stringResource(R.string.game_env_done), enabled = busyId == null, modifier = Modifier.focusRequester(doneFocus), onClick = close)
|
||||
PrimaryButton(stringResource(R.string.game_env_done), enabled = progress == null, modifier = Modifier.focusRequester(doneFocus), onClick = close)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -304,34 +264,17 @@ private fun Panel(content: @Composable androidx.compose.foundation.layout.Column
|
||||
private fun Divider() =
|
||||
Box(Modifier.fillMaxWidth().padding(horizontal = 14.dp).heightIn(min = 1.dp, max = 1.dp).background(LocalPalette.current.line))
|
||||
|
||||
/**
|
||||
* One component: name, detail and its switch; while [busy] the row is greyed and a thin bar runs
|
||||
* across it with [caption] above (the download, then the install, each 0..100 as [percent], or
|
||||
* indeterminate at -1). The switch stays enabled while busy so a pad's focus does not drop; the
|
||||
* press is ignored by the caller instead.
|
||||
*/
|
||||
@Composable
|
||||
private fun ComponentRow(
|
||||
name: String, detail: String, checked: Boolean, enabled: Boolean, dim: Boolean, busy: Boolean = false,
|
||||
caption: String? = null, percent: Int = -1, modifier: Modifier, onChange: (Boolean) -> Unit,
|
||||
) {
|
||||
private fun ComponentRow(name: String, detail: String, checked: Boolean, enabled: Boolean, dim: Boolean, modifier: Modifier, onChange: (Boolean) -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
Column(Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 10.dp)) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
modifier = Modifier.fillMaxWidth().alpha(if (dim) 0.55f else 1f),
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(name, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
|
||||
if (detail.isNotEmpty()) Text(detail, fontSize = 12.sp, lineHeight = 16.sp, color = colors.onSurfaceVariant)
|
||||
}
|
||||
ToggleSwitch(checked, enabled, name, modifier.alpha(if (busy) 0.5f else 1f), onChange)
|
||||
}
|
||||
if (busy) {
|
||||
if (!caption.isNullOrEmpty()) Text(caption, fontSize = 12.sp, lineHeight = 16.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(top = 4.dp))
|
||||
val bar = Modifier.fillMaxWidth().padding(top = 6.dp).heightIn(min = 4.dp, max = 4.dp)
|
||||
if (percent >= 0) LinearProgressIndicator(progress = { percent / 100f }, modifier = bar)
|
||||
else LinearProgressIndicator(modifier = bar)
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 10.dp).alpha(if (dim) 0.55f else 1f),
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(name, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
|
||||
if (detail.isNotEmpty()) Text(detail, fontSize = 12.sp, lineHeight = 16.sp, color = colors.onSurfaceVariant)
|
||||
}
|
||||
ToggleSwitch(checked, enabled, name, modifier, onChange)
|
||||
}
|
||||
}
|
||||
@@ -312,11 +312,6 @@ public final class WaylandCompositor {
|
||||
* list stops at the desktop size, as the X server's does on X11. Set before the compositor starts. */
|
||||
public static native void nativeSetOutputSize(int width, int height);
|
||||
|
||||
/** A new output size for a running compositor ("Follow screen": a foldable opening or closing).
|
||||
* The compositor thread re-sends the wl_output mode and an xdg_toplevel configure to every
|
||||
* client, and gamescope / the desktop's KWin resize their output to it. Any thread. */
|
||||
public static native void nativeResizeOutput(int width, int height);
|
||||
|
||||
/** Re-arms the one-shot first-frame notice, for a new session under a compositor that has
|
||||
* already presented a previous one. */
|
||||
public static native void nativeResetFirstFrame();
|
||||
|
||||
@@ -358,6 +358,13 @@
|
||||
<string name="mode_storage_diagnostics">Diagnóstico de almacenamiento</string>
|
||||
<string name="mode_storage_diagnostics_hint">Registra los resultados de asignación y muestras de tiempos de almacenamiento en Compartir registros. Puede ralentizar las instalaciones mientras esté activado. Se aplica en la próxima sesión.</string>
|
||||
<string name="mode_choose_folder">Elegir una carpeta…</string>
|
||||
<string name="mode_renderer">Renderizador</string>
|
||||
<string name="mode_desktop_renderer">Renderizador del escritorio</string>
|
||||
<string name="mode_renderer_hint">Dibuja el escritorio.</string>
|
||||
<string name="mode_renderer_vulkan">vulkan - GPU</string>
|
||||
<string name="mode_renderer_gles2">gles2 - GPU (experimental)</string>
|
||||
<string name="mode_renderer_pixman">pixman - software</string>
|
||||
<string name="mode_renderer_note">Vulkan ejecuta los programas del escritorio en la GPU y recurre a pixman si falla. Con pixman, los juegos se abren a pantalla completa en la GPU.</string>
|
||||
<string name="mode_custom_res_title">Resolución personalizada</string>
|
||||
<string name="mode_custom_res_text">Sustituye el límite y la relación de aspecto. Un tamaño que no coincide con la pantalla muestra barras.</string>
|
||||
<string name="mode_width">Ancho</string>
|
||||
@@ -887,7 +894,7 @@
|
||||
<string name="content_open_desktop">Abrir escritorio</string>
|
||||
<string name="content_install_open_desktop">Instalar y abrir escritorio</string>
|
||||
<string name="content_linux_desktop">Escritorio de Linux</string>
|
||||
<string name="content_linux_desktop_hint">KDE Plasma, Firefox y tus emuladores</string>
|
||||
<string name="content_linux_desktop_hint">LXQt, Firefox y tus emuladores</string>
|
||||
<string name="games_empty">Los juegos que instales en Steam aparecen aquí después de la sesión.</string>
|
||||
<string name="games_play_steam">Jugar en Steam</string>
|
||||
<string name="games_launch_settings">Ajustes de inicio</string>
|
||||
@@ -902,8 +909,11 @@
|
||||
<string name="games_manage_saves">Gestionar partidas guardadas</string>
|
||||
<string name="games_saves">Partidas guardadas</string>
|
||||
<string name="games_import_saves">Importar partidas guardadas…</string>
|
||||
<string name="games_import_saves_hint">Zip de GameHub o Winlator. Antes se hace una copia de las partidas actuales.</string>
|
||||
<string name="games_export_gamehub">Exportar como zip de GameHub…</string>
|
||||
<string name="games_export_gamehub_hint">Para GameHub y BannerHub</string>
|
||||
<string name="games_export_winlator">Exportar como zip de Winlator…</string>
|
||||
<string name="games_export_winlator_hint">Para Winlator, WinNative y Bannerlator</string>
|
||||
<string name="games_open_save_folder">Abrir carpeta de guardado</string>
|
||||
<string name="games_never_played">Nunca jugado</string>
|
||||
<string name="games_runtime_busy_percent">Runtime ocupado · %1$d%%</string>
|
||||
@@ -1249,6 +1259,7 @@
|
||||
<!-- %1$s is the program's name -->
|
||||
<string name="session_named_paused">%1$s está en pausa</string>
|
||||
<string name="session_program_paused">El programa está en pausa</string>
|
||||
<string name="session_starting_steam_desktop">Iniciando Steam en el escritorio</string>
|
||||
<string name="session_starting_desktop">Iniciando el escritorio</string>
|
||||
|
||||
<!-- %1$s is the program's name -->
|
||||
@@ -1274,6 +1285,7 @@
|
||||
<string name="session_proton_unpacking">descomprimiendo Proton Experimental (ARM64)</string>
|
||||
<string name="session_runtime_catalog_unreachable">No se pudo acceder al catálogo del runtime. Revisa la conexión y vuelve a pulsar Jugar.</string>
|
||||
<string name="session_runtime_install_failed">El runtime de Linux no se instaló. Revisa el runtime en Configuración y vuelve a pulsar Jugar.</string>
|
||||
<string name="session_desktop_catalog_unreachable">No se pudo acceder al catálogo del escritorio. Revisa la conexión y pulsa Escritorio de nuevo.</string>
|
||||
|
||||
<!-- %1$s says what went wrong -->
|
||||
<string name="session_desktop_install_failed">El escritorio no se instaló (%1$s). Revisa la conexión y pulsa Escritorio de nuevo.</string>
|
||||
|
||||
@@ -303,6 +303,13 @@
|
||||
<string name="mode_second_library">Bibliothèque secondaire</string>
|
||||
<string name="mode_storage_note">Les jeux lisant des ressources depuis une carte SD ou un stockage partagé peuvent saccader.</string>
|
||||
<string name="mode_choose_folder">Choisir un dossier…</string>
|
||||
<string name="mode_renderer">Rendu</string>
|
||||
<string name="mode_desktop_renderer">Moteur de rendu du bureau</string>
|
||||
<string name="mode_renderer_hint">Responsable du dessin du bureau.</string>
|
||||
<string name="mode_renderer_vulkan">vulkan - GPU</string>
|
||||
<string name="mode_renderer_gles2">gles2 - GPU (expérimental)</string>
|
||||
<string name="mode_renderer_pixman">pixman - Logiciel</string>
|
||||
<string name="mode_renderer_note">Vulkan utilise le GPU pour exécuter les programmes de bureau, et bascule vers pixman en cas d\'échec. Avec pixman, les jeux s\'exécutent toujours en plein écran sur le GPU.</string>
|
||||
<string name="mode_custom_res_title">Résolution personnalisée</string>
|
||||
<string name="mode_custom_res_text">Remplace la limite de résolution et le format d\'écran. Les dimensions ne correspondant pas à l\'écran afficheront des bandes noires.</string>
|
||||
<string name="mode_width">Largeur</string>
|
||||
@@ -778,7 +785,7 @@
|
||||
<string name="content_open_desktop">Ouvrir le bureau</string>
|
||||
<string name="content_install_open_desktop">Installer et ouvrir le bureau</string>
|
||||
<string name="content_linux_desktop">Bureau Linux</string>
|
||||
<string name="content_linux_desktop_hint">KDE Plasma, Firefox et vos émulateurs</string>
|
||||
<string name="content_linux_desktop_hint">LXQt, Firefox et vos émulateurs</string>
|
||||
<string name="games_empty">Les jeux installés sur Steam apparaîtront ici après la fin de la session.</string>
|
||||
<string name="games_play_steam">Lancer Steam</string>
|
||||
<string name="games_launch_settings">Paramètres de lancement</string>
|
||||
@@ -793,8 +800,11 @@
|
||||
<string name="games_manage_saves">Gérer les sauvegardes</string>
|
||||
<string name="games_saves">Sauvegardes de jeu</string>
|
||||
<string name="games_import_saves">Importer des sauvegardes…</string>
|
||||
<string name="games_import_saves_hint">Archive GameHub ou Winlator. Les sauvegardes actuelles seront sauvegardées avant l\'importation.</string>
|
||||
<string name="games_export_gamehub">Exporter en tant qu\'archive GameHub…</string>
|
||||
<string name="games_export_gamehub_hint">Compatible avec GameHub et BannerHub</string>
|
||||
<string name="games_export_winlator">Exporter en tant qu\'archive Winlator…</string>
|
||||
<string name="games_export_winlator_hint">Compatible avec Winlator, WinNative et Bannerlator</string>
|
||||
<string name="games_open_save_folder">Ouvrir le dossier de sauvegarde</string>
|
||||
<string name="games_never_played">Jamais lancé</string>
|
||||
<string name="games_runtime_busy_percent">Environnement d\'exécution occupé · %1$d%%</string>
|
||||
|
||||
@@ -358,6 +358,13 @@
|
||||
<string name="mode_storage_diagnostics">ストレージ診断</string>
|
||||
<string name="mode_storage_diagnostics_hint">割り当て結果とサンプリングしたストレージの処理時間を「ログを共有」に記録します。有効中はインストールが遅くなる場合があります。次回のセッションで有効になります。</string>
|
||||
<string name="mode_choose_folder">フォルダを選択…</string>
|
||||
<string name="mode_renderer">レンダラー</string>
|
||||
<string name="mode_desktop_renderer">デスクトップレンダラー</string>
|
||||
<string name="mode_renderer_hint">デスクトップの描画を担当します。</string>
|
||||
<string name="mode_renderer_vulkan">vulkan - GPU</string>
|
||||
<string name="mode_renderer_gles2">gles2 - GPU(実験的)</string>
|
||||
<string name="mode_renderer_pixman">pixman - ソフトウェア</string>
|
||||
<string name="mode_renderer_note">VulkanはGPUを使用してデスクトッププログラムを実行し、失敗した場合はpixmanにフォールバックします。pixmanを使用する場合でも、ゲームはGPU上で全画面実行されます。</string>
|
||||
<string name="mode_custom_res_title">カスタム解像度</string>
|
||||
<string name="mode_custom_res_text">解像度の上限と画面比率を置き換えます。画面に合わないサイズは黒帯で表示されます。</string>
|
||||
<string name="mode_width">幅</string>
|
||||
@@ -879,7 +886,7 @@
|
||||
<string name="content_open_desktop">デスクトップを開く</string>
|
||||
<string name="content_install_open_desktop">インストールしてデスクトップを開く</string>
|
||||
<string name="content_linux_desktop">Linuxデスクトップ</string>
|
||||
<string name="content_linux_desktop_hint">KDE Plasma、Firefox、エミュレーター</string>
|
||||
<string name="content_linux_desktop_hint">LXQt、Firefox、エミュレーター</string>
|
||||
<string name="games_empty">Steamでインストールされたゲームは、セッション終了後にここに表示されます。</string>
|
||||
<string name="games_play_steam">Steamを実行</string>
|
||||
<string name="games_launch_settings">起動設定</string>
|
||||
@@ -894,8 +901,11 @@
|
||||
<string name="games_manage_saves">セーブデータの管理</string>
|
||||
<string name="games_saves">ゲームセーブデータ</string>
|
||||
<string name="games_import_saves">セーブデータをインポート…</string>
|
||||
<string name="games_import_saves_hint">GameHubまたはWinlatorのアーカイブ。インポート前に現在のセーブデータをバックアップします。</string>
|
||||
<string name="games_export_gamehub">GameHubアーカイブとしてエクスポート…</string>
|
||||
<string name="games_export_gamehub_hint">GameHubおよびBannerHubに適しています</string>
|
||||
<string name="games_export_winlator">Winlatorアーカイブとしてエクスポート…</string>
|
||||
<string name="games_export_winlator_hint">Winlator、WinNative、Bannerlatorに適しています</string>
|
||||
<string name="games_open_save_folder">セーブフォルダを開く</string>
|
||||
<string name="games_never_played">未プレイ</string>
|
||||
<string name="games_runtime_busy_percent">実行環境がビジー · %1$d%%</string>
|
||||
@@ -1227,6 +1237,7 @@
|
||||
<!-- %1$s is the program's name -->
|
||||
<string name="session_named_paused">%1$sは一時停止中です</string>
|
||||
<string name="session_program_paused">プログラムは一時停止中です</string>
|
||||
<string name="session_starting_steam_desktop">デスクトップでSteamを起動中</string>
|
||||
<string name="session_starting_desktop">デスクトップを起動中</string>
|
||||
|
||||
<!-- %1$s is the program's name -->
|
||||
@@ -1252,6 +1263,7 @@
|
||||
<string name="session_proton_unpacking">Proton Experimental(ARM64)を展開中</string>
|
||||
<string name="session_runtime_catalog_unreachable">実行環境のカタログに接続できませんでした。接続を確認して、もう一度Playをタップしてください。</string>
|
||||
<string name="session_runtime_install_failed">Linux実行環境をインストールできませんでした。「設定」で実行環境を確認して、もう一度Playをタップしてください。</string>
|
||||
<string name="session_desktop_catalog_unreachable">デスクトップのカタログに接続できませんでした。接続を確認して、もう一度「デスクトップ」をタップしてください。</string>
|
||||
|
||||
<!-- %1$s says what went wrong -->
|
||||
<string name="session_desktop_install_failed">デスクトップをインストールできませんでした(%1$s)。接続を確認して、もう一度「デスクトップ」をタップしてください。</string>
|
||||
|
||||
@@ -358,6 +358,13 @@
|
||||
<string name="mode_storage_diagnostics">저장 공간 진단</string>
|
||||
<string name="mode_storage_diagnostics_hint">할당 결과와 샘플링한 저장 공간 응답 시간을 \"로그 공유\"에 기록합니다. 켜져 있는 동안 설치가 느려질 수 있습니다. 다음 세션에 적용됩니다.</string>
|
||||
<string name="mode_choose_folder">폴더 선택…</string>
|
||||
<string name="mode_renderer">렌더러</string>
|
||||
<string name="mode_desktop_renderer">데스크톱 렌더러</string>
|
||||
<string name="mode_renderer_hint">데스크톱을 그리는 역할을 합니다.</string>
|
||||
<string name="mode_renderer_vulkan">vulkan - GPU</string>
|
||||
<string name="mode_renderer_gles2">gles2 - GPU(실험적)</string>
|
||||
<string name="mode_renderer_pixman">pixman - 소프트웨어</string>
|
||||
<string name="mode_renderer_note">Vulkan은 GPU를 사용하여 데스크톱 프로그램을 실행하고, 실패하면 pixman으로 대체합니다. pixman을 사용할 때도 게임은 GPU에서 전체 화면으로 실행됩니다.</string>
|
||||
<string name="mode_custom_res_title">사용자 정의 해상도</string>
|
||||
<string name="mode_custom_res_text">해상도 상한과 화면 비율을 대체합니다. 화면과 일치하지 않는 크기는 검은색 여백으로 표시됩니다.</string>
|
||||
<string name="mode_width">너비</string>
|
||||
@@ -879,7 +886,7 @@
|
||||
<string name="content_open_desktop">데스크톱 열기</string>
|
||||
<string name="content_install_open_desktop">설치 및 데스크톱 열기</string>
|
||||
<string name="content_linux_desktop">Linux 데스크톱</string>
|
||||
<string name="content_linux_desktop_hint">KDE Plasma, Firefox 및 에뮬레이터</string>
|
||||
<string name="content_linux_desktop_hint">LXQt, Firefox 및 에뮬레이터</string>
|
||||
<string name="games_empty">Steam에서 설치한 게임은 세션 종료 후 여기에 표시됩니다.</string>
|
||||
<string name="games_play_steam">Steam 실행</string>
|
||||
<string name="games_launch_settings">실행 설정</string>
|
||||
@@ -894,8 +901,11 @@
|
||||
<string name="games_manage_saves">저장 데이터 관리</string>
|
||||
<string name="games_saves">게임 저장 데이터</string>
|
||||
<string name="games_import_saves">저장 데이터 가져오기…</string>
|
||||
<string name="games_import_saves_hint">GameHub 또는 Winlator 아카이브. 가져오기 전에 현재 저장 데이터를 백업합니다.</string>
|
||||
<string name="games_export_gamehub">GameHub 아카이브로 내보내기…</string>
|
||||
<string name="games_export_gamehub_hint">GameHub 및 BannerHub에 적합</string>
|
||||
<string name="games_export_winlator">Winlator 아카이브로 내보내기…</string>
|
||||
<string name="games_export_winlator_hint">Winlator, WinNative 및 Bannerlator에 적합</string>
|
||||
<string name="games_open_save_folder">저장 폴더 열기</string>
|
||||
<string name="games_never_played">플레이한 적 없음</string>
|
||||
<string name="games_runtime_busy_percent">런타임 사용 중 · %1$d%%</string>
|
||||
@@ -1227,6 +1237,7 @@
|
||||
<!-- %1$s is the program's name -->
|
||||
<string name="session_named_paused">%1$s 일시 중지됨</string>
|
||||
<string name="session_program_paused">프로그램이 일시 중지됨</string>
|
||||
<string name="session_starting_steam_desktop">데스크톱에서 Steam 시작 중</string>
|
||||
<string name="session_starting_desktop">데스크톱 시작 중</string>
|
||||
|
||||
<!-- %1$s is the program's name -->
|
||||
@@ -1252,6 +1263,7 @@
|
||||
<string name="session_proton_unpacking">Proton Experimental(ARM64) 압축 해제 중</string>
|
||||
<string name="session_runtime_catalog_unreachable">런타임 카탈로그에 연결할 수 없습니다. 연결을 확인한 후 \"Steam 실행\"을 다시 누르세요.</string>
|
||||
<string name="session_runtime_install_failed">Linux 런타임이 설치되지 않았습니다. \"설정\"에서 런타임을 확인한 후 \"Steam 실행\"을 다시 누르세요.</string>
|
||||
<string name="session_desktop_catalog_unreachable">데스크톱 카탈로그에 연결할 수 없습니다. 연결을 확인한 후 \"데스크톱\"을 다시 누르세요.</string>
|
||||
|
||||
<!-- %1$s says what went wrong -->
|
||||
<string name="session_desktop_install_failed">데스크톱이 설치되지 않았습니다(%1$s). 연결을 확인한 후 \"데스크톱\"을 다시 누르세요.</string>
|
||||
|
||||
@@ -333,6 +333,13 @@
|
||||
<string name="mode_storage_diagnostics">Диагностика хранилища</string>
|
||||
<string name="mode_storage_diagnostics_hint">Записывает результаты выделения места и выборочные замеры скорости хранилища в журналы. Пока включено, установка может идти медленнее. Вступит в силу в следующей сессии.</string>
|
||||
<string name="mode_choose_folder">Выбрать папку…</string>
|
||||
<string name="mode_renderer">Рендерер</string>
|
||||
<string name="mode_desktop_renderer">Рендерер рабочего стола</string>
|
||||
<string name="mode_renderer_hint">Отвечает за отрисовку рабочего стола.</string>
|
||||
<string name="mode_renderer_vulkan">vulkan — GPU</string>
|
||||
<string name="mode_renderer_gles2">gles2 — GPU (экспериментально)</string>
|
||||
<string name="mode_renderer_pixman">pixman — программный</string>
|
||||
<string name="mode_renderer_note">Vulkan использует GPU для запуска программ рабочего стола, при сбое переключается на pixman. При использовании pixman игры по-прежнему запускаются в полноэкранном режиме на GPU.</string>
|
||||
<string name="mode_custom_res_title">Пользовательское разрешение</string>
|
||||
<string name="mode_custom_res_text">Заменяет предел разрешения и соотношение сторон. Размеры, не соответствующие экрану, будут отображаться с черными полосами.</string>
|
||||
<string name="mode_width">Ширина</string>
|
||||
@@ -862,7 +869,7 @@
|
||||
<string name="content_open_desktop">Открыть рабочий стол</string>
|
||||
<string name="content_install_open_desktop">Установить и открыть рабочий стол</string>
|
||||
<string name="content_linux_desktop">Рабочий стол Linux</string>
|
||||
<string name="content_linux_desktop_hint">KDE Plasma, Firefox и ваши эмуляторы</string>
|
||||
<string name="content_linux_desktop_hint">LXQt, Firefox и ваши эмуляторы</string>
|
||||
<string name="games_empty">Игры, установленные в Steam, появятся здесь после завершения сессии.</string>
|
||||
<string name="games_play_steam">Запустить Steam</string>
|
||||
<string name="games_launch_settings">Настройки запуска</string>
|
||||
@@ -877,8 +884,11 @@
|
||||
<string name="games_manage_saves">Управление сохранениями</string>
|
||||
<string name="games_saves">Сохранения игры</string>
|
||||
<string name="games_import_saves">Импорт сохранений…</string>
|
||||
<string name="games_import_saves_hint">Архив GameHub или Winlator. Перед импортом текущие сохранения будут сохранены в резервной копии.</string>
|
||||
<string name="games_export_gamehub">Экспорт как архив GameHub…</string>
|
||||
<string name="games_export_gamehub_hint">Подходит для GameHub и BannerHub</string>
|
||||
<string name="games_export_winlator">Экспорт как архив Winlator…</string>
|
||||
<string name="games_export_winlator_hint">Подходит для Winlator, WinNative и Bannerlator</string>
|
||||
<string name="games_open_save_folder">Открыть папку сохранений</string>
|
||||
<string name="games_never_played">Никогда не запускалась</string>
|
||||
<string name="games_runtime_busy_percent">Среда выполнения занята · %1$d%%</string>
|
||||
|
||||
@@ -358,6 +358,13 @@
|
||||
<string name="mode_storage_diagnostics">存储诊断</string>
|
||||
<string name="mode_storage_diagnostics_hint">在分享日志中记录分配结果和存储采样耗时。启用期间可能减慢安装。将在下次会话生效。</string>
|
||||
<string name="mode_choose_folder">选择文件夹…</string>
|
||||
<string name="mode_renderer">渲染器</string>
|
||||
<string name="mode_desktop_renderer">桌面渲染器</string>
|
||||
<string name="mode_renderer_hint">绘制桌面。</string>
|
||||
<string name="mode_renderer_vulkan">vulkan - GPU</string>
|
||||
<string name="mode_renderer_gles2">gles2 - GPU(实验性)</string>
|
||||
<string name="mode_renderer_pixman">pixman - 软件</string>
|
||||
<string name="mode_renderer_note">Vulkan 让桌面程序运行在 GPU 上,失败时回退到 pixman。桌面改用 pixman 时,游戏仍会全屏运行在 GPU 上。</string>
|
||||
<string name="mode_custom_res_title">自定义分辨率</string>
|
||||
<string name="mode_custom_res_text">取代上限与比例。与屏幕不匹配的尺寸会出现黑边。</string>
|
||||
<string name="mode_width">宽度</string>
|
||||
@@ -879,7 +886,7 @@
|
||||
<string name="content_open_desktop">打开桌面</string>
|
||||
<string name="content_install_open_desktop">安装并打开桌面</string>
|
||||
<string name="content_linux_desktop">Linux 桌面</string>
|
||||
<string name="content_linux_desktop_hint">KDE Plasma、Firefox 和你的模拟器</string>
|
||||
<string name="content_linux_desktop_hint">LXQt、Firefox 和你的模拟器</string>
|
||||
<string name="games_empty">你在 Steam 安装的游戏会在会话结束后显示在这里。</string>
|
||||
<string name="games_play_steam">游玩 Steam</string>
|
||||
<string name="games_launch_settings">启动设置</string>
|
||||
@@ -894,8 +901,11 @@
|
||||
<string name="games_manage_saves">管理存档</string>
|
||||
<string name="games_saves">游戏存档</string>
|
||||
<string name="games_import_saves">导入存档…</string>
|
||||
<string name="games_import_saves_hint">GameHub 或 Winlator 的 zip 包。会先备份当前存档。</string>
|
||||
<string name="games_export_gamehub">导出为 GameHub zip 包…</string>
|
||||
<string name="games_export_gamehub_hint">用于 GameHub 和 BannerHub</string>
|
||||
<string name="games_export_winlator">导出为 Winlator zip 包…</string>
|
||||
<string name="games_export_winlator_hint">用于 Winlator、WinNative 和 Bannerlator</string>
|
||||
<string name="games_open_save_folder">打开存档文件夹</string>
|
||||
<string name="games_never_played">从未游玩</string>
|
||||
<string name="games_runtime_busy_percent">运行时繁忙 · %1$d%%</string>
|
||||
@@ -1227,6 +1237,7 @@
|
||||
<!-- %1$s is the program's name -->
|
||||
<string name="session_named_paused">%1$s 已暂停</string>
|
||||
<string name="session_program_paused">程序已暂停</string>
|
||||
<string name="session_starting_steam_desktop">正在桌面上启动 Steam</string>
|
||||
<string name="session_starting_desktop">正在启动桌面</string>
|
||||
|
||||
<!-- %1$s is the program's name -->
|
||||
@@ -1252,6 +1263,7 @@
|
||||
<string name="session_proton_unpacking">正在解包 Proton Experimental(ARM64)</string>
|
||||
<string name="session_runtime_catalog_unreachable">无法连接运行时目录。请检查网络连接,然后再次点“游玩”。</string>
|
||||
<string name="session_runtime_install_failed">Linux 运行时未能安装。请在“配置”中检查运行时,然后再次点“游玩”。</string>
|
||||
<string name="session_desktop_catalog_unreachable">无法连接桌面目录。请检查网络连接,然后再次点“桌面”。</string>
|
||||
|
||||
<!-- %1$s says what went wrong -->
|
||||
<string name="session_desktop_install_failed">桌面未能安装(%1$s)。请检查网络连接,然后再次点“桌面”。</string>
|
||||
|
||||
@@ -358,6 +358,13 @@
|
||||
<string name="mode_storage_diagnostics">儲存空間診斷</string>
|
||||
<string name="mode_storage_diagnostics_hint">在分享的記錄中加入空間分配結果和抽樣的儲存時間數據。啟用時可能會減慢安裝速度。下次會話生效。</string>
|
||||
<string name="mode_choose_folder">選擇資料夾…</string>
|
||||
<string name="mode_renderer">渲染器</string>
|
||||
<string name="mode_desktop_renderer">桌面渲染器</string>
|
||||
<string name="mode_renderer_hint">負責繪製桌面。</string>
|
||||
<string name="mode_renderer_vulkan">vulkan - GPU</string>
|
||||
<string name="mode_renderer_gles2">gles2 - GPU(實驗性)</string>
|
||||
<string name="mode_renderer_pixman">pixman - 軟件</string>
|
||||
<string name="mode_renderer_note">Vulkan 會用 GPU 執行桌面程式,失敗時改用 pixman。使用 pixman 時,遊戲仍會以全螢幕在 GPU 上執行。</string>
|
||||
<string name="mode_custom_res_title">自訂解像度</string>
|
||||
<string name="mode_custom_res_text">取代解像度上限和螢幕比例。尺寸與螢幕不符時會顯示黑邊。</string>
|
||||
<string name="mode_width">寬度</string>
|
||||
@@ -879,7 +886,7 @@
|
||||
<string name="content_open_desktop">開啟桌面</string>
|
||||
<string name="content_install_open_desktop">安裝並開啟桌面</string>
|
||||
<string name="content_linux_desktop">Linux 桌面</string>
|
||||
<string name="content_linux_desktop_hint">KDE Plasma、Firefox 和你的模擬器</string>
|
||||
<string name="content_linux_desktop_hint">LXQt、Firefox 和你的模擬器</string>
|
||||
<string name="games_empty">你在 Steam 安裝的遊戲會在會話結束後顯示在這裡。</string>
|
||||
<string name="games_play_steam">開啟 Steam</string>
|
||||
<string name="games_launch_settings">啟動設定</string>
|
||||
@@ -894,8 +901,11 @@
|
||||
<string name="games_manage_saves">管理存檔</string>
|
||||
<string name="games_saves">遊戲存檔</string>
|
||||
<string name="games_import_saves">匯入存檔…</string>
|
||||
<string name="games_import_saves_hint">GameHub 或 Winlator zip。會先備份目前的存檔。</string>
|
||||
<string name="games_export_gamehub">匯出為 GameHub zip…</string>
|
||||
<string name="games_export_gamehub_hint">適用於 GameHub 和 BannerHub</string>
|
||||
<string name="games_export_winlator">匯出為 Winlator zip…</string>
|
||||
<string name="games_export_winlator_hint">適用於 Winlator、WinNative 和 Bannerlator</string>
|
||||
<string name="games_open_save_folder">開啟存檔資料夾</string>
|
||||
<string name="games_never_played">從未玩過</string>
|
||||
<string name="games_runtime_busy_percent">運行環境繁忙 · %1$d%%</string>
|
||||
@@ -1227,6 +1237,7 @@
|
||||
<!-- %1$s is the program's name -->
|
||||
<string name="session_named_paused">%1$s 已暫停</string>
|
||||
<string name="session_program_paused">程式已暫停</string>
|
||||
<string name="session_starting_steam_desktop">正在桌面上啟動 Steam</string>
|
||||
<string name="session_starting_desktop">正在啟動桌面</string>
|
||||
|
||||
<!-- %1$s is the program's name -->
|
||||
@@ -1252,6 +1263,7 @@
|
||||
<string name="session_proton_unpacking">正在解壓 Proton Experimental (ARM64)</string>
|
||||
<string name="session_runtime_catalog_unreachable">無法連接運行環境目錄。請檢查網絡連線,然後再按「開啟 Steam」。</string>
|
||||
<string name="session_runtime_install_failed">Linux 運行環境未能安裝。請在「設定」中檢查運行環境,然後再按「開啟 Steam」。</string>
|
||||
<string name="session_desktop_catalog_unreachable">無法連接桌面目錄。請檢查網絡連線,然後再按「桌面」。</string>
|
||||
|
||||
<!-- %1$s says what went wrong -->
|
||||
<string name="session_desktop_install_failed">桌面未能安裝(%1$s)。請檢查網絡連線,然後再按「桌面」。</string>
|
||||
|
||||
@@ -358,6 +358,13 @@
|
||||
<string name="mode_storage_diagnostics">儲存空間診斷</string>
|
||||
<string name="mode_storage_diagnostics_hint">在「分享日誌」中記錄空間配置結果和取樣的儲存存取時間。啟用期間可能會減慢安裝速度。下次工作階段生效。</string>
|
||||
<string name="mode_choose_folder">選擇資料夾…</string>
|
||||
<string name="mode_renderer">渲染器</string>
|
||||
<string name="mode_desktop_renderer">桌面渲染器</string>
|
||||
<string name="mode_renderer_hint">負責繪製桌面。</string>
|
||||
<string name="mode_renderer_vulkan">vulkan - GPU</string>
|
||||
<string name="mode_renderer_gles2">gles2 - GPU(實驗性)</string>
|
||||
<string name="mode_renderer_pixman">pixman - 軟體</string>
|
||||
<string name="mode_renderer_note">Vulkan 使用 GPU 執行桌面程式,失敗時退回 pixman。使用 pixman 時,遊戲仍會在 GPU 上全螢幕執行。</string>
|
||||
<string name="mode_custom_res_title">自訂解析度</string>
|
||||
<string name="mode_custom_res_text">取代解析度上限和螢幕比例。不符合螢幕的尺寸會顯示黑邊。</string>
|
||||
<string name="mode_width">寬度</string>
|
||||
@@ -879,7 +886,7 @@
|
||||
<string name="content_open_desktop">開啟桌面</string>
|
||||
<string name="content_install_open_desktop">安裝並開啟桌面</string>
|
||||
<string name="content_linux_desktop">Linux 桌面</string>
|
||||
<string name="content_linux_desktop_hint">KDE Plasma、Firefox 和你的模擬器</string>
|
||||
<string name="content_linux_desktop_hint">LXQt、Firefox 和你的模擬器</string>
|
||||
<string name="games_empty">在 Steam 中安裝的遊戲會在工作階段結束後顯示在這裡。</string>
|
||||
<string name="games_play_steam">執行 Steam</string>
|
||||
<string name="games_launch_settings">啟動設定</string>
|
||||
@@ -894,8 +901,11 @@
|
||||
<string name="games_manage_saves">管理存檔</string>
|
||||
<string name="games_saves">遊戲存檔</string>
|
||||
<string name="games_import_saves">匯入存檔…</string>
|
||||
<string name="games_import_saves_hint">GameHub 或 Winlator 壓縮檔。匯入前會先備份目前存檔。</string>
|
||||
<string name="games_export_gamehub">匯出為 GameHub 壓縮檔…</string>
|
||||
<string name="games_export_gamehub_hint">適用於 GameHub 和 BannerHub</string>
|
||||
<string name="games_export_winlator">匯出為 Winlator 壓縮檔…</string>
|
||||
<string name="games_export_winlator_hint">適用於 Winlator、WinNative 和 Bannerlator</string>
|
||||
<string name="games_open_save_folder">開啟存檔資料夾</string>
|
||||
<string name="games_never_played">從未執行</string>
|
||||
<string name="games_runtime_busy_percent">執行環境繁忙 · %1$d%%</string>
|
||||
@@ -1227,6 +1237,7 @@
|
||||
<!-- %1$s is the program's name -->
|
||||
<string name="session_named_paused">%1$s 已暫停</string>
|
||||
<string name="session_program_paused">程式已暫停</string>
|
||||
<string name="session_starting_steam_desktop">正在桌面上啟動 Steam</string>
|
||||
<string name="session_starting_desktop">正在啟動桌面</string>
|
||||
|
||||
<!-- %1$s is the program's name -->
|
||||
@@ -1252,6 +1263,7 @@
|
||||
<string name="session_proton_unpacking">正在解壓縮 Proton Experimental(ARM64)</string>
|
||||
<string name="session_runtime_catalog_unreachable">無法連線到執行環境目錄。請檢查網路連線,然後再按一次「執行」。</string>
|
||||
<string name="session_runtime_install_failed">Linux 執行環境未能安裝。請在「設定」中檢查執行環境,然後再按一次「執行」。</string>
|
||||
<string name="session_desktop_catalog_unreachable">無法連線到桌面目錄。請檢查網路連線,然後再按一次「桌面」。</string>
|
||||
|
||||
<!-- %1$s says what went wrong -->
|
||||
<string name="session_desktop_install_failed">桌面未能安裝(%1$s)。請檢查網路連線,然後再按一次「桌面」。</string>
|
||||
|
||||
@@ -326,20 +326,16 @@
|
||||
<string name="wincomp_found_steam">Steam installs %1$s with this game</string>
|
||||
<string name="wincomp_already_here">Already in this game</string>
|
||||
<string name="wincomp_no_recommendation">Nothing in the game\'s folder points at a component.</string>
|
||||
<string name="wincomp_active">Installed for this game (%1$d)</string>
|
||||
<string name="wincomp_all">All components (%1$d)</string>
|
||||
<string name="wincomp_installers">Need a Windows installer (%1$d)</string>
|
||||
<string name="wincomp_installers_note">These are their own setup programs (codec packs, browsers, old runtimes) with no package inside to take apart. DroidDeck cannot run a Windows setup program yet; it is coming next.</string>
|
||||
<string name="wincomp_installers_note">These run a real installer inside the prefix (.NET, PhysX, XNA, the full Visual C++ installers…). DroidDeck cannot do that yet; it is coming next.</string>
|
||||
<string name="wincomp_show">Show</string>
|
||||
<string name="wincomp_hide">Hide</string>
|
||||
<string name="wincomp_needs_installer">Runs its own setup program (coming)</string>
|
||||
<string name="wincomp_needs_installer">Needs a Windows installer (coming)</string>
|
||||
<string name="wincomp_unsupported">Not supported here yet</string>
|
||||
<string name="wincomp_loading">Loading the components…</string>
|
||||
<string name="wincomp_failed">Could not install: %1$s</string>
|
||||
<string name="wincomp_downloaded">Downloaded</string>
|
||||
<string name="wincomp_downloading">Downloading %1$s</string>
|
||||
<string name="wincomp_installing">Installing: %1$s</string>
|
||||
<string name="wincomp_reverting">Turning off…</string>
|
||||
<string name="wincomp_download_size">%1$s download</string>
|
||||
<string name="wincomp_next_launch">Takes effect the next time the game starts.</string>
|
||||
<string name="mode_stretch169">Stretch 16:9 games</string>
|
||||
@@ -368,6 +364,13 @@
|
||||
<string name="mode_storage_diagnostics">Storage diagnostics</string>
|
||||
<string name="mode_storage_diagnostics_hint">Record allocation results and sampled storage timings in Share logs. May slow installs while enabled. Applies next session.</string>
|
||||
<string name="mode_choose_folder">Choose a folder…</string>
|
||||
<string name="mode_renderer">Renderer</string>
|
||||
<string name="mode_desktop_renderer">Desktop renderer</string>
|
||||
<string name="mode_renderer_hint">Draws the desktop.</string>
|
||||
<string name="mode_renderer_vulkan">vulkan - GPU</string>
|
||||
<string name="mode_renderer_gles2">gles2 - GPU (experimental)</string>
|
||||
<string name="mode_renderer_pixman">pixman - software</string>
|
||||
<string name="mode_renderer_note">Vulkan runs desktop programs on the GPU, falling back to pixman if it fails. On pixman, games open full screen on the GPU.</string>
|
||||
<string name="mode_custom_res_title">Custom resolution</string>
|
||||
<string name="mode_custom_res_text">Replaces the cap and ratio. A size that doesn\'t match the screen gets bars.</string>
|
||||
<string name="mode_width">Width</string>
|
||||
@@ -893,7 +896,7 @@
|
||||
<string name="content_open_desktop">Open desktop</string>
|
||||
<string name="content_install_open_desktop">Install & open desktop</string>
|
||||
<string name="content_linux_desktop">Linux desktop</string>
|
||||
<string name="content_linux_desktop_hint">KDE Plasma, Firefox and your emulators</string>
|
||||
<string name="content_linux_desktop_hint">LXQt, Firefox and your emulators</string>
|
||||
<string name="games_empty">Games you install in Steam show up here after the session.</string>
|
||||
<string name="games_play_steam">Play Steam</string>
|
||||
<string name="games_launch_settings">Launch settings</string>
|
||||
@@ -908,8 +911,11 @@
|
||||
<string name="games_manage_saves">Manage saves</string>
|
||||
<string name="games_saves">Game saves</string>
|
||||
<string name="games_import_saves">Import saves…</string>
|
||||
<string name="games_import_saves_hint">GameHub or Winlator zip. Current saves are backed up first.</string>
|
||||
<string name="games_export_gamehub">Export as GameHub zip…</string>
|
||||
<string name="games_export_gamehub_hint">For GameHub and BannerHub</string>
|
||||
<string name="games_export_winlator">Export as Winlator zip…</string>
|
||||
<string name="games_export_winlator_hint">For Winlator, WinNative and Bannerlator</string>
|
||||
<string name="games_open_save_folder">Open save folder</string>
|
||||
<string name="games_never_played">Never played</string>
|
||||
<string name="games_runtime_busy_percent">Runtime busy · %1$d%%</string>
|
||||
@@ -1223,6 +1229,7 @@
|
||||
<!-- %1$s is the program's name -->
|
||||
<string name="session_named_paused">%1$s is paused</string>
|
||||
<string name="session_program_paused">The program is paused</string>
|
||||
<string name="session_starting_steam_desktop">Starting Steam on the desktop</string>
|
||||
<string name="session_starting_desktop">Starting the desktop</string>
|
||||
<!-- %1$s is the program's name -->
|
||||
<string name="session_starting_named">Starting %1$s</string>
|
||||
@@ -1246,6 +1253,7 @@
|
||||
<string name="session_proton_unpacking">unpacking Proton Experimental (ARM64)</string>
|
||||
<string name="session_runtime_catalog_unreachable">Could not reach the runtime catalog. Check the connection and press Play again.</string>
|
||||
<string name="session_runtime_install_failed">The Linux runtime did not install. Check the runtime in Setup and press Play again.</string>
|
||||
<string name="session_desktop_catalog_unreachable">Could not reach the desktop catalog. Check the connection and press Desktop again.</string>
|
||||
<!-- %1$s says what went wrong -->
|
||||
<string name="session_desktop_install_failed">The desktop did not install (%1$s). Check the connection and press Desktop again.</string>
|
||||
<!-- %1$s is the program's name, or Steam -->
|
||||
@@ -1942,7 +1950,6 @@
|
||||
<string name="display_frame_rate">Frame rate</string>
|
||||
<string name="display_look_filter">%1$s Sets scaling to %2$s.</string>
|
||||
<string name="display_match_screen">Match screen (%1$d×%2$d)</string>
|
||||
<string name="display_follow_screen">Follow screen (resizes when folded or unfolded)</string>
|
||||
<string name="mode_tab_steam">Steam</string>
|
||||
<string name="device_info_show">Show device details</string>
|
||||
<string name="device_info_hide">Hide device details</string>
|
||||
@@ -1982,6 +1989,7 @@
|
||||
<string name="stores_search_catalog">Search the %1$s catalog…</string>
|
||||
<string name="stores_search_installed">Search installed games…</string>
|
||||
<string name="stores_search_library">Search your library…</string>
|
||||
<string name="stores_search_all">Search everything on %1$s…</string>
|
||||
<string name="stores_installed_empty">Nothing installed</string>
|
||||
<string name="stores_library_loading">Loading</string>
|
||||
<string name="stores_nothing_matches">No games</string>
|
||||
@@ -2003,28 +2011,16 @@
|
||||
<string name="stores_in_library">In library</string>
|
||||
<string name="stores_free">Free</string>
|
||||
<string name="stores_resume">Resume</string>
|
||||
<string name="stores_refresh">Refresh</string>
|
||||
<string name="stores_show_mature">Show mature content</string>
|
||||
<string name="epic_card_title">Epic</string>
|
||||
<string name="epic_card_eos">EOS</string>
|
||||
<string name="epic_card_offline">Offline</string>
|
||||
<string name="epic_card_overlay">Overlay</string>
|
||||
<string name="epic_card_none">Off</string>
|
||||
<string name="epic_eos">Epic sign-in (EOS)</string>
|
||||
<string name="epic_offline">Launch offline</string>
|
||||
<string name="epic_overlay">Epic overlay</string>
|
||||
<string name="epic_resolve">Resolve Epic sign-in</string>
|
||||
<string name="store_cloud_saves">Cloud saves</string>
|
||||
<string name="cloud_upload">Upload to cloud</string>
|
||||
<string name="cloud_download">Download from cloud</string>
|
||||
<string name="cloud_none">No cloud saves</string>
|
||||
<string name="cloud_conflict">Cloud conflict</string>
|
||||
<string name="cloud_conflict_files">Cloud conflict · %1$d files</string>
|
||||
<string name="cloud_pending">…</string>
|
||||
<string name="cloud_keep_cloud">Keep cloud</string>
|
||||
<string name="cloud_keep_local">Keep local</string>
|
||||
<string name="cloud_checking">Checking cloud…</string>
|
||||
<string name="cloud_last_sync">Last sync %1$s</string>
|
||||
<string name="cloud_never">Not synced yet</string>
|
||||
<string name="cloud_done">%1$d files</string>
|
||||
<string name="stores_eyebrow_installed">installed</string>
|
||||
<string name="stores_eyebrow_library">in your library</string>
|
||||
<string name="stores_eyebrow_store">store</string>
|
||||
@@ -2066,7 +2062,6 @@
|
||||
<string name="stores_dl_cancel">Cancel</string>
|
||||
<string name="stores_dl_retry">Retry</string>
|
||||
<string name="stores_dl_clear">Clear</string>
|
||||
<string name="stores_dl_clear_all">Clear finished</string>
|
||||
<string name="stores_stage_manifest">Manifest</string>
|
||||
<string name="stores_stage_download">Download</string>
|
||||
<string name="stores_stage_verify">Verify</string>
|
||||
@@ -2093,11 +2088,6 @@
|
||||
<string name="stores_notification_one">Downloading</string>
|
||||
<string name="stores_notification_many">%1$d downloads</string>
|
||||
<string name="stores_notification_waiting">Preparing…</string>
|
||||
<string name="stores_notification_done_channel">Finished store downloads</string>
|
||||
<string name="stores_notification_installed">%1$s installed</string>
|
||||
<string name="stores_notification_failed">%1$s download failed</string>
|
||||
<string name="stores_notification_delete">Delete</string>
|
||||
<string name="stores_notification_keep">Keep</string>
|
||||
<string name="stores_login_title">Sign in to %1$s</string>
|
||||
<string name="stores_login_provider_title">Sign in with your provider</string>
|
||||
<string name="stores_login_reload">Reload</string>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<paths>
|
||||
<cache-path name="shared_logs" path="share/" />
|
||||
<cache-path name="shared_logs" path="shared-logs/" />
|
||||
</paths>
|
||||
@@ -70,7 +70,7 @@ after it (marker files, exe resolution, DLC markers, redist orchestration).
|
||||
| Method | JNI signature | Symbol |
|
||||
|---|---|---|
|
||||
| `nativeProbe(): Int` | `()I` | `Java_com_droiddeck_launcher_stores_gog_GogNative_nativeProbe` |
|
||||
| `nativeStart(...)`: Long | `(I[Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;IIZLjava/lang/String;Ljava/lang/Object;)J` (last parameter is the listener; its static type is the app's choice) | `Java_com_droiddeck_launcher_stores_gog_GogNative_nativeStart` |
|
||||
| `nativeStart(...)`: Long | `(I[Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;IIZLjava/lang/String;Ljava/lang/Object;)J` (last parameter is the listener; its static type is the app's choice) | `Java_com_droiddeck_launcher_stores_gog_GogNative_nativeStart` |
|
||||
| `nativeCancel(handle: Long)` | `(J)V` | `Java_com_droiddeck_launcher_stores_gog_GogNative_nativeCancel` |
|
||||
| `nativeRelease(handle: Long)` | `(J)V` | `Java_com_droiddeck_launcher_stores_gog_GogNative_nativeRelease` |
|
||||
|
||||
@@ -83,7 +83,7 @@ once at startup instead of mid-download.
|
||||
|---|---|---|
|
||||
| 1 | `kind: Int` | `0` = `KIND_GEN2_CHUNKS`, `1` = `KIND_GEN1_RANGES` (anything else → gen2) |
|
||||
| 2 | `depotManifests: Array<String>` | gen2: the inflated depot-manifest JSON strings, in fetch order, already filtered by product + language; gen1: the inflated build manifest (one element) |
|
||||
| 3 | `cdnBases: Array<String>` | gen2: **every** CDN base of the secure-link answer — one per `urls[]` entry, each resolved the way `parseCdnUrl` resolves `urls[0]` today (query string intact), in GOG's order — or the one unauthenticated dependency store base (an array of one); gen1: `emptyArray()` (file URLs are in the manifest). Blank entries are ignored and a base whose host already appeared is dropped (the first wins). The fetch core spreads the window across the distinct hosts with a per-host cap of `max(6, ceil(maxWorkers / hosts))`, rotating a failed chunk to another CDN; one base behaves exactly like the old single `cdnBase`. The start log line lists them as `hosts=a,b,c`. |
|
||||
| 3 | `cdnBase: String` | gen2: the resolved secure-link base (query string intact) or the unauthenticated dependency store base; gen1: `""` (file URLs are in the manifest) |
|
||||
| 4 | `installDir: String` | absolute install directory |
|
||||
| 5 | `skipPaths: Array<String>` | relative paths already completed by an earlier run of this same download (secure-link refresh re-run): counted done without re-hashing, no progress event |
|
||||
| 6 | `caBundlePath: String` | see conventions |
|
||||
@@ -94,15 +94,14 @@ once at startup instead of mid-download.
|
||||
| 11 | `listener` | see below |
|
||||
|
||||
Returns `0` without any callback when: the listener is null, the JavaVM cannot be obtained, the
|
||||
install dir or manifest list is empty, `cdnBases` holds no usable base for gen2, or the worker
|
||||
thread cannot be spawned. Otherwise the run is on a thread named `gog-dl` and `onComplete` fires exactly once.
|
||||
install dir or manifest list is empty, `cdnBase` is empty for gen2, or the worker thread cannot be
|
||||
spawned. Otherwise the run is on a thread named `gog-dl` and `onComplete` fires exactly once.
|
||||
|
||||
Suggested listener: `com.droiddeck.launcher.stores.gog.GogNative.Listener` (an interface).
|
||||
|
||||
| Listener method | JNI signature | When |
|
||||
|---|---|---|
|
||||
| `onProgress(bytesDone: Long, bytesTotal: Long, filesDone: Int, filesTotal: Int, file: String, fileBytes: Long, verified: Boolean)` | `(JJIILjava/lang/String;JZ)V` | one file reached its final state. `verified = true` = resume-skip (existing file passed size+MD5; no bytes credited, `fileBytes` = its size); `false` = freshly assembled, size+MD5-verified and renamed (`fileBytes` = its decompressed size). `filesDone` counts both, `bytesDone` counts assembled bytes only. Process-pool / worker thread. |
|
||||
| `onBytes(bytesDone: Long, bytesTotal: Long)` | `(JJ)V` | byte progress between file completions: every 250 ms while the run is fetching, only when the value moved, plus once when the fetch ends. `bytesDone` = bytes of assembled files + bytes of files still in flight (gen2: their finished chunks, decompressed; gen1: what the current attempt has written; a retried attempt starts over, so nothing is counted twice); `bytesTotal` is the same total `onProgress` reports. It never goes past the next `onProgress.bytesDone` by more than the in-flight files and is equal to it once they finish. Drive the progress bar and speed from this; keep `onProgress` for file counts and per-file events. Called from the engine's ticker thread. Optional: a listener without it still works (the call fails quietly). |
|
||||
| `onLog(line: String)` | `(Ljava/lang/String;)V` | engine diagnostics; the same line already went to logcat under the tag `GogNative`. Any native thread. |
|
||||
| `onComplete(success: Boolean, cancelled: Boolean, linkExpiry: Boolean, error: String, bytesWritten: Long, filesDone: Int)` | `(ZZZLjava/lang/String;JI)V` | exactly once, from the worker thread, last. `linkExpiry = true` = the run died on an HTTP 401/403/404/500, the codes the GOG secure link returns once it expired: refresh the link and call `nativeStart` again with the finished files in `skipPaths`. `error` is `""` on success. |
|
||||
|
||||
|
||||
@@ -34,17 +34,15 @@ use crate::fetch_tuning::{
|
||||
WINDOW_PLATEAU_REARM_MS, WINDOW_PROBE_INTERVAL_MS, WINDOW_SHRINK_FACTOR,
|
||||
WINDOW_SLOW_START_FACTOR, WINDOW_STEP_UP,
|
||||
};
|
||||
use futures_util::future::{select, Either};
|
||||
use futures_util::stream::FuturesUnordered;
|
||||
use futures_util::StreamExt;
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::fs;
|
||||
use std::pin::pin;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
|
||||
use std::sync::{mpsc as std_mpsc, Arc, Mutex};
|
||||
use std::thread;
|
||||
use std::time::{Duration, Instant};
|
||||
use tokio::sync::{Notify, Semaphore};
|
||||
use tokio::sync::Semaphore;
|
||||
|
||||
/// Maximum attempts per item (fetch failures AND `SinkError::Retry` both count). Same as Steam.
|
||||
pub const MAX_ITEM_ATTEMPTS: u32 = MAX_CHUNK_ATTEMPTS;
|
||||
@@ -53,44 +51,6 @@ pub const THROUGHPUT_SAMPLE_INTERVAL_MS: u64 = 5_000;
|
||||
/// Upper bound on how long the driver sits in one `await` before re-checking cancel/error/feedback.
|
||||
const DRIVER_POLL_MS: u64 = 250;
|
||||
|
||||
// ── Delay awareness (bufferbloat) ──
|
||||
// On a 5G hotspot the window kept growing (31 → 84) while the per-request delay went from 3 s to
|
||||
// 11 s and throughput stayed at 10-20 MB/s: every extra request only queued behind the others in
|
||||
// the link's buffer. The signal used here is time-to-first-byte (request sent → response headers),
|
||||
// which on a link with a deep buffer grows with the queue, while on a fast link it stays at a few
|
||||
// round trips however wide the window gets. The baseline is the lowest per-probe mean seen.
|
||||
|
||||
/// A probe needs at least this many TTFB samples before its mean is trusted.
|
||||
pub const LATENCY_MIN_SAMPLES: u32 = 3;
|
||||
/// Mean TTFB at or above `baseline ×` this counts as queueing delay…
|
||||
pub const LATENCY_HOLD_FACTOR: f64 = 2.5;
|
||||
/// …and only when it is also this far above the baseline in absolute terms: a fast link whose
|
||||
/// TTFB goes from 20 ms to 60 ms (new connections' TLS handshakes) is not bufferbloat.
|
||||
pub const LATENCY_MIN_EXCESS_MS: f64 = 250.0;
|
||||
/// Throughput above `best × (1 + this)` is a gain that justifies the extra delay: hold, but never
|
||||
/// shrink, while it lasts.
|
||||
pub const LATENCY_GAIN_EPS: f64 = 0.25;
|
||||
/// Gentle proportional shrink while the delay keeps rising (gentler than the error shrink).
|
||||
pub const LATENCY_SHRINK_FACTOR: f64 = 0.85;
|
||||
|
||||
// ── Stalled hosts ──
|
||||
// A CDN host can stop delivering while its connections stay open: on the device the Fastly host
|
||||
// froze at 49 MB for the rest of the run while the other host carried everything, and its requests
|
||||
// sat until their idle timeout. A host whose in-flight requests receive no byte for this long,
|
||||
// while another host is receiving, has its requests cancelled and re-queued and is put to rest.
|
||||
|
||||
/// No byte from any of a host's in-flight requests for this long (while another host delivers).
|
||||
pub const HOST_STALL_MS: u64 = if cfg!(test) { 1_500 } else { 10_000 };
|
||||
/// First rest for a stalled host; doubles per further stall of the same host, reset on success.
|
||||
pub const HOST_STALL_COOLDOWN_MS: u64 = 30_000;
|
||||
pub const HOST_STALL_COOLDOWN_MAX_MS: u64 = 300_000;
|
||||
/// How often the driver looks for stalled hosts.
|
||||
const STALL_CHECK_MS: u64 = 250;
|
||||
/// Stream mode: the longest a request may sit with no byte arriving before it is failed (the
|
||||
/// store's own timeout when it is shorter). A dead connection on a single-host run, where the
|
||||
/// stall detector has no healthy host to compare with, never holds an item longer than this.
|
||||
pub const STREAM_IDLE_CAP: Duration = Duration::from_secs(30);
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────────────────────
|
||||
// Public contract
|
||||
// ─────────────────────────────────────────────────────────────────────────────────────────────
|
||||
@@ -786,53 +746,31 @@ async fn send_checked(
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
/// Whole-body mode: one attempt for one item (the driver owns retry/rotation). `timeout` bounds the
|
||||
/// whole request (headers + body). The body is read piece by piece so `host_rx` sees every byte as
|
||||
/// it arrives (the stall detector's signal); `ttfb` is set when the response headers arrive.
|
||||
/// Whole-body mode: one attempt for one item (the driver owns retry/rotation).
|
||||
async fn fetch_once(
|
||||
http: &Http,
|
||||
url: &str,
|
||||
range: Option<(u64, u64)>,
|
||||
timeout: Duration,
|
||||
host_rx: &AtomicU64,
|
||||
started: Instant,
|
||||
ttfb: &mut Option<Duration>,
|
||||
) -> Result<Vec<u8>, AsyncFetchError> {
|
||||
let whole = async {
|
||||
let mut response = send_checked(http, url, range, None).await?;
|
||||
*ttfb = Some(started.elapsed());
|
||||
let content_length = response.content_length();
|
||||
let mut body = Vec::with_capacity(content_length.unwrap_or(0).min(64 << 20) as usize);
|
||||
loop {
|
||||
match response.chunk().await {
|
||||
Ok(Some(piece)) => {
|
||||
host_rx.fetch_add(piece.len() as u64, Ordering::Relaxed);
|
||||
body.extend_from_slice(&piece);
|
||||
}
|
||||
Ok(None) => break,
|
||||
Err(err) => {
|
||||
let kind = if err.is_timeout() {
|
||||
FetchFailKind::Timeout
|
||||
} else {
|
||||
FetchFailKind::Other
|
||||
};
|
||||
return Err(AsyncFetchError {
|
||||
message: format!("http body: {err}"),
|
||||
kind,
|
||||
});
|
||||
}
|
||||
}
|
||||
let response = send_checked(http, url, range, Some(timeout)).await?;
|
||||
let content_length = response.content_length();
|
||||
let body = match response.bytes().await {
|
||||
Ok(body) => body.to_vec(),
|
||||
Err(err) => {
|
||||
let kind = if err.is_timeout() {
|
||||
FetchFailKind::Timeout
|
||||
} else {
|
||||
FetchFailKind::Other
|
||||
};
|
||||
return Err(AsyncFetchError {
|
||||
message: format!("http body: {err}"),
|
||||
kind,
|
||||
});
|
||||
}
|
||||
validate_body_len(body.len() as u64, content_length, range)?;
|
||||
Ok(body)
|
||||
};
|
||||
match tokio::time::timeout(timeout, whole).await {
|
||||
Ok(res) => res,
|
||||
Err(_) => Err(AsyncFetchError {
|
||||
message: "http get: request timed out".to_string(),
|
||||
kind: FetchFailKind::Timeout,
|
||||
}),
|
||||
}
|
||||
validate_body_len(body.len() as u64, content_length, range)?;
|
||||
Ok(body)
|
||||
}
|
||||
|
||||
/// Stream mode: one attempt for one item. Pieces are pushed to the item's pool worker as they
|
||||
@@ -852,11 +790,7 @@ async fn fetch_stream(
|
||||
budget: u64,
|
||||
cancel: &AtomicBool,
|
||||
abandon: Option<&AtomicU32>,
|
||||
host_rx: &AtomicU64,
|
||||
started: Instant,
|
||||
ttfb: &mut Option<Duration>,
|
||||
) -> Result<u64, AsyncFetchError> {
|
||||
let idle = timeout.min(STREAM_IDLE_CAP);
|
||||
let mut response =
|
||||
match tokio::time::timeout(timeout, send_checked(http, url, range, None)).await {
|
||||
Ok(res) => res?,
|
||||
@@ -867,7 +801,6 @@ async fn fetch_stream(
|
||||
})
|
||||
}
|
||||
};
|
||||
*ttfb = Some(started.elapsed());
|
||||
let content_length = response.content_length();
|
||||
let mut offset = 0u64;
|
||||
loop {
|
||||
@@ -887,7 +820,7 @@ async fn fetch_stream(
|
||||
kind: FetchFailKind::Other,
|
||||
});
|
||||
}
|
||||
let piece = match tokio::time::timeout(idle, response.chunk()).await {
|
||||
let piece = match tokio::time::timeout(timeout, response.chunk()).await {
|
||||
Ok(Ok(Some(piece))) => piece,
|
||||
Ok(Ok(None)) => break,
|
||||
Ok(Err(err)) => {
|
||||
@@ -906,7 +839,6 @@ async fn fetch_stream(
|
||||
if piece.is_empty() {
|
||||
continue;
|
||||
}
|
||||
host_rx.fetch_add(piece.len() as u64, Ordering::Relaxed);
|
||||
let data = piece.to_vec();
|
||||
let len = data.len() as u64;
|
||||
in_flight.fetch_add(len, Ordering::Relaxed);
|
||||
@@ -995,12 +927,6 @@ struct FetchDone {
|
||||
reserve: u64,
|
||||
server_idx: usize,
|
||||
elapsed: Duration,
|
||||
/// Request sent → response headers, when the headers arrived.
|
||||
ttfb: Option<Duration>,
|
||||
/// Key in the driver's registry of running requests.
|
||||
req_id: u64,
|
||||
/// The request was cancelled because its host stalled (not a failure of the item).
|
||||
stalled: bool,
|
||||
res: Result<Fetched, AsyncFetchError>,
|
||||
}
|
||||
|
||||
@@ -1063,18 +989,6 @@ async fn run_driver(ctx: DriverCtx<'_>) {
|
||||
let mut errors_logged: u32 = 0;
|
||||
// Bodies / finishes handed to the pool whose verdict has not come back yet.
|
||||
let mut outstanding = 0usize;
|
||||
// Stall detection: bytes received per server (bumped by the request futures as pieces
|
||||
// arrive), when that count last moved, since when the server has had requests to answer,
|
||||
// how many requests it is running, and each running request's abort switch.
|
||||
let host_rx: Vec<AtomicU64> = hosts.iter().map(|_| AtomicU64::new(0)).collect();
|
||||
let mut last_rx: Vec<u64> = vec![0; hosts.len()];
|
||||
let mut last_rx_at: Vec<Option<Instant>> = vec![None; hosts.len()];
|
||||
let mut watch_from: Vec<Instant> = vec![Instant::now(); hosts.len()];
|
||||
let mut running: Vec<usize> = vec![0; hosts.len()];
|
||||
let mut stall_count: Vec<u32> = vec![0; hosts.len()];
|
||||
let mut aborts: HashMap<u64, (usize, Arc<Notify>)> = HashMap::new();
|
||||
let mut next_req_id: u64 = 0;
|
||||
let mut last_stall_check = Instant::now();
|
||||
// Declared AFTER `txs`/`http` so it is dropped BEFORE them (its futures borrow both).
|
||||
let mut inflight: FuturesUnordered<_> = FuturesUnordered::new();
|
||||
|
||||
@@ -1123,51 +1037,6 @@ async fn run_driver(ctx: DriverCtx<'_>) {
|
||||
log(&window.summary_line(label, inflight.len(), probe_now));
|
||||
}
|
||||
|
||||
// ── Stalled hosts: requests that receive nothing while another host delivers. ──
|
||||
if probe_now.duration_since(last_stall_check) >= Duration::from_millis(STALL_CHECK_MS) {
|
||||
last_stall_check = probe_now;
|
||||
for s in 0..hosts.len() {
|
||||
let rx = host_rx[s].load(Ordering::Relaxed);
|
||||
if rx != last_rx[s] {
|
||||
last_rx[s] = rx;
|
||||
last_rx_at[s] = Some(probe_now);
|
||||
}
|
||||
}
|
||||
let stall = Duration::from_millis(HOST_STALL_MS);
|
||||
for s in 0..hosts.len() {
|
||||
let silent_since = silent_since(last_rx_at[s], watch_from[s]);
|
||||
if running[s] == 0 || probe_now.duration_since(silent_since) < stall {
|
||||
continue;
|
||||
}
|
||||
let others_deliver = (0..hosts.len()).any(|o| {
|
||||
o != s && last_rx_at[o].is_some_and(|at| probe_now.duration_since(at) < stall)
|
||||
});
|
||||
if !others_deliver {
|
||||
continue;
|
||||
}
|
||||
let mut requeued = 0usize;
|
||||
for (srv, notify) in aborts.values() {
|
||||
if *srv == s {
|
||||
notify.notify_one();
|
||||
requeued += 1;
|
||||
}
|
||||
}
|
||||
let rest = HOST_STALL_COOLDOWN_MS
|
||||
.saturating_mul(1u64 << stall_count[s].min(8))
|
||||
.min(HOST_STALL_COOLDOWN_MAX_MS);
|
||||
stall_count[s] = stall_count[s].saturating_add(1);
|
||||
sched.rest(s, probe_now, Duration::from_millis(rest));
|
||||
window.note_stalled_host();
|
||||
log(&format!(
|
||||
"host-stall label={label} host={} requeued={requeued} idle_ms={} cooldown_ms={rest}",
|
||||
hosts[s],
|
||||
probe_now.duration_since(silent_since).as_millis()
|
||||
));
|
||||
// Do not fire again for the same silence while the cancelled requests wind down.
|
||||
watch_from[s] = probe_now;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Dispatch up to the current window ──
|
||||
while inflight.len() < window.current {
|
||||
if cancel.load(Ordering::Relaxed)
|
||||
@@ -1228,57 +1097,28 @@ async fn run_driver(ctx: DriverCtx<'_>) {
|
||||
let http = &http;
|
||||
let tx = &txs[if stream { idx % txs.len() } else { 0 }];
|
||||
let abandon_flag = abandon.get(idx);
|
||||
let rx_counter = &host_rx[server_idx];
|
||||
let started = Instant::now();
|
||||
if running[server_idx] == 0 {
|
||||
// The host had nothing to answer until now: its silence is measured from here.
|
||||
watch_from[server_idx] = started;
|
||||
}
|
||||
running[server_idx] += 1;
|
||||
let req_id = next_req_id;
|
||||
next_req_id += 1;
|
||||
let abort = Arc::new(Notify::new());
|
||||
aborts.insert(req_id, (server_idx, Arc::clone(&abort)));
|
||||
inflight.push(async move {
|
||||
let mut ttfb: Option<Duration> = None;
|
||||
let (res, stalled) = {
|
||||
let fetch = async {
|
||||
if stream {
|
||||
fetch_stream(
|
||||
http,
|
||||
&url,
|
||||
range,
|
||||
timeout,
|
||||
idx,
|
||||
attempts + 1,
|
||||
tx,
|
||||
in_flight,
|
||||
budget,
|
||||
cancel,
|
||||
abandon_flag,
|
||||
rx_counter,
|
||||
started,
|
||||
&mut ttfb,
|
||||
)
|
||||
.await
|
||||
.map(Fetched::Streamed)
|
||||
} else {
|
||||
fetch_once(http, &url, range, timeout, rx_counter, started, &mut ttfb)
|
||||
.await
|
||||
.map(Fetched::Body)
|
||||
}
|
||||
};
|
||||
// The stall detector's switch: dropping the fetch future closes its connection.
|
||||
match select(pin!(fetch), pin!(abort.notified())).await {
|
||||
Either::Left((res, _)) => (res, false),
|
||||
Either::Right(((), _)) => (
|
||||
Err(AsyncFetchError {
|
||||
message: "host stalled; request re-queued".to_string(),
|
||||
kind: FetchFailKind::Other,
|
||||
}),
|
||||
true,
|
||||
),
|
||||
}
|
||||
let res = if stream {
|
||||
fetch_stream(
|
||||
http,
|
||||
&url,
|
||||
range,
|
||||
timeout,
|
||||
idx,
|
||||
attempts + 1,
|
||||
tx,
|
||||
in_flight,
|
||||
budget,
|
||||
cancel,
|
||||
abandon_flag,
|
||||
)
|
||||
.await
|
||||
.map(Fetched::Streamed)
|
||||
} else {
|
||||
fetch_once(http, &url, range, timeout)
|
||||
.await
|
||||
.map(Fetched::Body)
|
||||
};
|
||||
drop(permit); // RAII per-host permit release (also on future drop / cancel-abort)
|
||||
FetchDone {
|
||||
@@ -1287,9 +1127,6 @@ async fn run_driver(ctx: DriverCtx<'_>) {
|
||||
reserve,
|
||||
server_idx,
|
||||
elapsed: started.elapsed(),
|
||||
ttfb,
|
||||
req_id,
|
||||
stalled,
|
||||
res,
|
||||
}
|
||||
});
|
||||
@@ -1314,26 +1151,6 @@ async fn run_driver(ctx: DriverCtx<'_>) {
|
||||
Err(_elapsed) => continue,
|
||||
};
|
||||
let now = Instant::now();
|
||||
aborts.remove(&done.req_id);
|
||||
running[done.server_idx] = running[done.server_idx].saturating_sub(1);
|
||||
if done.stalled {
|
||||
// Not the item's fault: straight back into the queue for a healthy host, no window
|
||||
// or host penalty beyond the rest the detector already gave the host. It still counts
|
||||
// as an attempt, which keeps each stream attempt's pieces distinguishable.
|
||||
in_flight.fetch_sub(done.reserve, Ordering::Relaxed);
|
||||
retry.push_front(PendingItem {
|
||||
idx: done.idx,
|
||||
attempts: done.attempts,
|
||||
not_before: now,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
if let Some(ttfb) = done.ttfb {
|
||||
window.record_ttfb(ttfb.as_secs_f64() * 1000.0);
|
||||
}
|
||||
if done.res.is_ok() {
|
||||
stall_count[done.server_idx] = 0;
|
||||
}
|
||||
match done.res {
|
||||
Ok(Fetched::Body(body)) => {
|
||||
let raw_len = body.len() as u64;
|
||||
@@ -1429,15 +1246,6 @@ window_shrink={} msg={}",
|
||||
drop(txs);
|
||||
}
|
||||
|
||||
/// Since when a server has been silent: its last byte, or when it was last given work to do if
|
||||
/// that came later.
|
||||
fn silent_since(last_rx_at: Option<Instant>, watch_from: Instant) -> Instant {
|
||||
match last_rx_at {
|
||||
Some(at) if at > watch_from => at,
|
||||
_ => watch_from,
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────────────────────
|
||||
// Bandwidth meter (per-host bytes + 5-s samples for peak)
|
||||
// ─────────────────────────────────────────────────────────────────────────────────────────────
|
||||
@@ -1635,14 +1443,6 @@ impl FetchScheduler {
|
||||
h.cooldown_until = None;
|
||||
}
|
||||
|
||||
/// A stalled host: out of the rotation for `rest`, and its speed estimate cut so it comes
|
||||
/// back behind the hosts that kept delivering.
|
||||
fn rest(&mut self, server_idx: usize, now: Instant, rest: Duration) {
|
||||
let h = &mut self.health[server_idx];
|
||||
h.cooldown_until = Some(now + rest);
|
||||
h.ewma_bps *= 0.25;
|
||||
}
|
||||
|
||||
fn on_error(&mut self, server_idx: usize, now: Instant, kind: FetchFailKind) {
|
||||
let h = &mut self.health[server_idx];
|
||||
h.consecutive_errors = h.consecutive_errors.saturating_add(1);
|
||||
@@ -1666,8 +1466,6 @@ enum WindowReason {
|
||||
HoldCeiling,
|
||||
HoldErrors,
|
||||
HoldThroughputDown,
|
||||
HoldLatency,
|
||||
ShrinkLatency,
|
||||
ShrinkRateLimited,
|
||||
ShrinkTimeout,
|
||||
ShrinkReset,
|
||||
@@ -1688,8 +1486,6 @@ impl WindowReason {
|
||||
WindowReason::HoldCeiling => "hold:ceiling",
|
||||
WindowReason::HoldErrors => "hold:errors",
|
||||
WindowReason::HoldThroughputDown => "hold:throughput-down",
|
||||
WindowReason::HoldLatency => "hold:latency",
|
||||
WindowReason::ShrinkLatency => "shrink:latency",
|
||||
WindowReason::ShrinkRateLimited => "shrink:429",
|
||||
WindowReason::ShrinkTimeout => "shrink:timeout",
|
||||
WindowReason::ShrinkReset => "shrink:reset",
|
||||
@@ -1733,16 +1529,6 @@ struct AdaptiveWindow {
|
||||
last_budget_stalls: u32,
|
||||
last_host_stalls: u32,
|
||||
latency_ewma_ms: f64,
|
||||
/// TTFB samples of the current probe interval.
|
||||
ttfb_sum_ms: f64,
|
||||
ttfb_samples: u32,
|
||||
/// Lowest per-probe mean TTFB seen this run (0 = none yet): the no-queue baseline.
|
||||
ttfb_base_ms: f64,
|
||||
/// Mean TTFB of the last probe that had enough samples.
|
||||
ttfb_last_ms: f64,
|
||||
/// Consecutive probes with queueing delay.
|
||||
latency_streak: u32,
|
||||
stalled_hosts: u32,
|
||||
cooldown_until: Option<Instant>,
|
||||
last_reason: WindowReason,
|
||||
last_err_rate: f64,
|
||||
@@ -1773,12 +1559,6 @@ impl AdaptiveWindow {
|
||||
last_budget_stalls: 0,
|
||||
last_host_stalls: 0,
|
||||
latency_ewma_ms: 0.0,
|
||||
ttfb_sum_ms: 0.0,
|
||||
ttfb_samples: 0,
|
||||
ttfb_base_ms: 0.0,
|
||||
ttfb_last_ms: 0.0,
|
||||
latency_streak: 0,
|
||||
stalled_hosts: 0,
|
||||
cooldown_until: None,
|
||||
last_reason: WindowReason::Start,
|
||||
last_err_rate: 0.0,
|
||||
@@ -1794,26 +1574,6 @@ impl AdaptiveWindow {
|
||||
self.host_stalls = self.host_stalls.saturating_add(1);
|
||||
}
|
||||
|
||||
fn record_ttfb(&mut self, ttfb_ms: f64) {
|
||||
self.ttfb_sum_ms += ttfb_ms;
|
||||
self.ttfb_samples = self.ttfb_samples.saturating_add(1);
|
||||
}
|
||||
|
||||
fn note_stalled_host(&mut self) {
|
||||
self.stalled_hosts = self.stalled_hosts.saturating_add(1);
|
||||
}
|
||||
|
||||
/// The latency brake's shrink: proportional and gentle, never below the floor, at least −1.
|
||||
fn shrink_latency(&mut self, now: Instant) {
|
||||
let scaled = (self.current as f64 * LATENCY_SHRINK_FACTOR).floor() as usize;
|
||||
self.current = scaled.min(self.current.saturating_sub(1)).max(self.min);
|
||||
self.cooldown_until = Some(now + Duration::from_millis(WINDOW_COOLDOWN_MS));
|
||||
self.slow_start = false;
|
||||
self.plateau_streak = 0;
|
||||
self.plateau_since = None;
|
||||
self.last_reason = WindowReason::ShrinkLatency;
|
||||
}
|
||||
|
||||
fn record_ok(&mut self, latency_ms: f64) {
|
||||
self.ok_count = self.ok_count.saturating_add(1);
|
||||
self.latency_ewma_ms = if self.latency_ewma_ms == 0.0 {
|
||||
@@ -1884,43 +1644,10 @@ impl AdaptiveWindow {
|
||||
let before = self.current;
|
||||
let cooling = self.cooldown_until.is_some_and(|t| now < t);
|
||||
|
||||
// Queueing delay: this probe's mean TTFB against the run's baseline.
|
||||
let probe_ttfb = (self.ttfb_samples >= LATENCY_MIN_SAMPLES)
|
||||
.then(|| self.ttfb_sum_ms / self.ttfb_samples as f64);
|
||||
let mut queueing = false;
|
||||
let mut rising = false;
|
||||
if let Some(ttfb) = probe_ttfb {
|
||||
if self.ttfb_base_ms == 0.0 || ttfb < self.ttfb_base_ms {
|
||||
self.ttfb_base_ms = ttfb;
|
||||
}
|
||||
queueing = ttfb >= self.ttfb_base_ms * LATENCY_HOLD_FACTOR
|
||||
&& ttfb - self.ttfb_base_ms >= LATENCY_MIN_EXCESS_MS;
|
||||
rising = self.ttfb_last_ms > 0.0 && ttfb >= self.ttfb_last_ms;
|
||||
self.ttfb_last_ms = ttfb;
|
||||
}
|
||||
if queueing {
|
||||
self.latency_streak = self.latency_streak.saturating_add(1);
|
||||
} else if probe_ttfb.is_some() {
|
||||
self.latency_streak = 0;
|
||||
}
|
||||
|
||||
if err_rate > WINDOW_ERR_RATE_HIGH {
|
||||
self.shrink(now, WindowReason::ShrinkErrorRate);
|
||||
} else if cooling {
|
||||
self.last_reason = WindowReason::HoldCooldown;
|
||||
} else if queueing {
|
||||
// More requests only made each one wait longer. Hold while a real gain still comes
|
||||
// with the delay; once the delay keeps rising without one, give some of the window
|
||||
// back, gently, and let the cooldown show whether that helped.
|
||||
let gain = self.bps_ewma > self.best_bps * (1.0 + LATENCY_GAIN_EPS);
|
||||
if gain {
|
||||
self.best_bps = self.bps_ewma;
|
||||
}
|
||||
if !gain && rising && self.latency_streak >= 2 && self.current > self.min {
|
||||
self.shrink_latency(now);
|
||||
} else {
|
||||
self.last_reason = WindowReason::HoldLatency;
|
||||
}
|
||||
} else if self.current >= self.max {
|
||||
self.last_reason = WindowReason::HoldCeiling;
|
||||
} else if err_rate > WINDOW_ERR_RATE_LOW {
|
||||
@@ -1967,8 +1694,6 @@ impl AdaptiveWindow {
|
||||
self.last_host_stalls = self.host_stalls;
|
||||
self.budget_stalls = 0;
|
||||
self.host_stalls = 0;
|
||||
self.ttfb_sum_ms = 0.0;
|
||||
self.ttfb_samples = 0;
|
||||
self.probes_since_log = self.probes_since_log.saturating_add(1);
|
||||
let changed = before != self.current;
|
||||
if changed || self.probes_since_log >= WINDOW_LOG_EVERY_PROBES {
|
||||
@@ -1990,8 +1715,7 @@ impl AdaptiveWindow {
|
||||
format!(
|
||||
"fetch-window label={label} window={} (min={} max={}) in_flight={in_flight_requests} \
|
||||
last={:.2}MB/s ewma={:.2}MB/s best={:.2}MB/s reason={} cooldown={}ms err_rate={:.1}% \
|
||||
phase={} rtt={:.0}ms budget_stalls={} host_stalls={} ttfb={:.0}ms ttfb_base={:.0}ms \
|
||||
stalled_hosts={}",
|
||||
phase={} rtt={:.0}ms budget_stalls={} host_stalls={}",
|
||||
self.current,
|
||||
self.min,
|
||||
self.max,
|
||||
@@ -2004,10 +1728,7 @@ stalled_hosts={}",
|
||||
if self.slow_start { "slow-start" } else { "steady" },
|
||||
self.latency_ewma_ms,
|
||||
self.last_budget_stalls,
|
||||
self.last_host_stalls,
|
||||
self.ttfb_last_ms,
|
||||
self.ttfb_base_ms,
|
||||
self.stalled_hosts
|
||||
self.last_host_stalls
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -2152,155 +1873,6 @@ mod tests {
|
||||
assert!(line.contains("phase=steady"));
|
||||
}
|
||||
|
||||
const MIB: u64 = 1024 * 1024;
|
||||
|
||||
/// Drive the window through probes 2.1 s apart, each with `samples` TTFB values and the
|
||||
/// bytes that arrived in it; returns (reason, window) after every probe.
|
||||
fn run_probes(w: &mut AdaptiveWindow, t0: Instant, probes: &[(f64, u64)]) -> Vec<(WindowReason, usize)> {
|
||||
let mut total = 0u64;
|
||||
let mut out = Vec::new();
|
||||
for (k, &(ttfb_ms, bytes)) in probes.iter().enumerate() {
|
||||
for _ in 0..5 {
|
||||
w.record_ttfb(ttfb_ms);
|
||||
}
|
||||
total += bytes;
|
||||
w.maybe_probe(t0 + Duration::from_millis(2_100 * (k as u64 + 1)), total);
|
||||
out.push((w.last_reason, w.current));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rising_delay_without_more_throughput_holds_then_shrinks_gently() {
|
||||
let t0 = Instant::now();
|
||||
let mut w = AdaptiveWindow::new(8, 2, 256, t0);
|
||||
// Flat ~15 MB/s while the time to first byte climbs from 0.4 s to 12 s (the 5G log).
|
||||
let flat = 32 * MIB;
|
||||
let probes: Vec<(f64, u64)> = [400.0, 400.0, 450.0, 900.0, 1500.0, 2500.0, 4000.0, 6000.0, 9000.0, 12000.0]
|
||||
.iter()
|
||||
.map(|&ttfb| (ttfb, flat))
|
||||
.collect();
|
||||
let seen = run_probes(&mut w, t0, &probes);
|
||||
let first_hold = seen.iter().position(|(r, _)| *r == WindowReason::HoldLatency).expect("hold:latency");
|
||||
let first_shrink = seen.iter().position(|(r, _)| *r == WindowReason::ShrinkLatency).expect("shrink:latency");
|
||||
assert!(first_hold < first_shrink, "{seen:?}");
|
||||
let before = seen[first_shrink - 1].1;
|
||||
assert_eq!(seen[first_shrink].1, (before as f64 * LATENCY_SHRINK_FACTOR).floor() as usize, "{seen:?}");
|
||||
// From the first sign of queueing on, the window never grows again.
|
||||
for pair in seen[first_hold..].windows(2) {
|
||||
assert!(pair[1].1 <= pair[0].1, "grew under queueing delay: {seen:?}");
|
||||
}
|
||||
assert!(seen.last().unwrap().1 < before, "{seen:?}");
|
||||
let line = w.summary_line("t", 0, t0);
|
||||
assert!(line.contains(" ttfb_base=400ms"), "{line}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fast_link_keeps_growing_while_its_delay_stays_low() {
|
||||
let t0 = Instant::now();
|
||||
let mut w = AdaptiveWindow::new(8, 2, 256, t0);
|
||||
// Throughput doubles with the window; TTFB wobbles between 25 and 70 ms (new connections).
|
||||
let probes: Vec<(f64, u64)> = (0..6)
|
||||
.map(|k| ([25.0, 70.0, 40.0, 60.0, 30.0, 65.0][k], (8 * MIB) << k))
|
||||
.collect();
|
||||
let seen = run_probes(&mut w, t0, &probes);
|
||||
assert!(
|
||||
seen.iter().all(|(r, _)| *r != WindowReason::HoldLatency && *r != WindowReason::ShrinkLatency),
|
||||
"{seen:?}"
|
||||
);
|
||||
assert!(w.current >= 128, "{seen:?}");
|
||||
}
|
||||
|
||||
/// Two-behaviour stub for the stall test: `freeze` answers the headers and 100 bytes, then
|
||||
/// never sends another byte; otherwise every path gets 10 000 bytes in ten paced slices.
|
||||
fn start_paced_stub(freeze: bool) -> String {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
|
||||
let port = listener.local_addr().expect("addr").port();
|
||||
thread::spawn(move || {
|
||||
for stream in listener.incoming() {
|
||||
let Ok(mut stream) = stream else { break };
|
||||
thread::spawn(move || {
|
||||
let mut buf = Vec::new();
|
||||
let mut tmp = [0u8; 1024];
|
||||
while !buf.windows(4).any(|w| w == b"\r\n\r\n") {
|
||||
match stream.read(&mut tmp) {
|
||||
Ok(0) | Err(_) => return,
|
||||
Ok(n) => buf.extend_from_slice(&tmp[..n]),
|
||||
}
|
||||
}
|
||||
let body = vec![7u8; 10_000];
|
||||
let head = format!(
|
||||
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
|
||||
body.len()
|
||||
);
|
||||
if stream.write_all(head.as_bytes()).is_err() {
|
||||
return;
|
||||
}
|
||||
if freeze {
|
||||
let _ = stream.write_all(&body[..100]);
|
||||
let _ = stream.flush();
|
||||
thread::sleep(Duration::from_secs(30));
|
||||
return;
|
||||
}
|
||||
for slice in body.chunks(1_000) {
|
||||
if stream.write_all(slice).is_err() {
|
||||
return;
|
||||
}
|
||||
let _ = stream.flush();
|
||||
thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
format!("http://127.0.0.1:{port}")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_frozen_host_is_detected_and_its_items_move_to_the_healthy_one() {
|
||||
let frozen = start_paced_stub(true);
|
||||
let healthy = start_paced_stub(false);
|
||||
let hosts = vec![frozen.clone(), healthy.clone()];
|
||||
let items: Vec<FetchItem> = (0..12u64)
|
||||
.map(|i| {
|
||||
let a = format!("{frozen}/item{i}");
|
||||
let b = format!("{healthy}/item{i}");
|
||||
item(i, &[a.as_str(), b.as_str()], None)
|
||||
})
|
||||
.collect();
|
||||
let sink = CollectSink {
|
||||
got: Mutex::new(HashMap::new()),
|
||||
retry_once_id: None,
|
||||
retried: AtomicUsize::new(0),
|
||||
};
|
||||
let cancel = AtomicBool::new(false);
|
||||
let lines: Mutex<Vec<String>> = Mutex::new(Vec::new());
|
||||
let started = Instant::now();
|
||||
let outcome = run_fetch(
|
||||
items,
|
||||
&hosts,
|
||||
&opts("stall"),
|
||||
&sink,
|
||||
&cancel,
|
||||
&|_: u64, _: u64| {},
|
||||
&|line: &str| lines.lock().unwrap().push(line.to_string()),
|
||||
);
|
||||
let elapsed = started.elapsed();
|
||||
let lines = lines.lock().unwrap();
|
||||
assert!(outcome.ok(), "outcome={outcome:?} lines={lines:?}");
|
||||
assert_eq!(outcome.items_ok, 12);
|
||||
let got = sink.got.lock().unwrap();
|
||||
assert!(got.values().all(|b| b.len() == 10_000));
|
||||
let stall = lines
|
||||
.iter()
|
||||
.find(|l| l.starts_with("host-stall label=stall "))
|
||||
.unwrap_or_else(|| panic!("no host-stall line: {lines:?}"));
|
||||
assert!(stall.contains(&format!(" host={frozen} ")), "{stall}");
|
||||
assert!(!stall.contains(" requeued=0 "), "{stall}");
|
||||
// Well inside the 10 s request timeout that would otherwise have freed the items.
|
||||
assert!(elapsed < Duration::from_secs(8), "took {elapsed:?}: {lines:?}");
|
||||
assert!(!lines.iter().any(|l| l.contains(&format!("host={healthy}")) && l.starts_with("host-stall")));
|
||||
}
|
||||
|
||||
// ── Minimal HTTP/1.1 stub: one thread per connection, `Connection: close`, Range-aware. ──
|
||||
struct Stub {
|
||||
base: String,
|
||||
|
||||
@@ -39,8 +39,7 @@ pub const TMP_SUFFIX: &str = ".bhtmp";
|
||||
/// Floor for the per-host cap (the core's default); a single-host store gets the whole ceiling.
|
||||
pub const PER_HOST_CAP_FLOOR: usize = 6;
|
||||
|
||||
/// `max(6, ceil(max_workers / distinct_hosts))` — one CDN host gets the whole ceiling, several
|
||||
/// share it.
|
||||
/// `max(6, ceil(max_workers / distinct_hosts))` — GOG's one CDN host gets the whole ceiling.
|
||||
pub fn per_host_cap_for(max_workers: usize, distinct_hosts: usize) -> usize {
|
||||
let hosts = distinct_hosts.max(1);
|
||||
let workers = max_workers.max(1);
|
||||
@@ -75,12 +74,9 @@ pub struct GogRequest {
|
||||
/// gen2: inflated depot-manifest JSON strings, in the order Java fetched them (already filtered
|
||||
/// by base-product / DLC-product and language in Java). gen1: the inflated build manifest.
|
||||
pub depot_manifests: Vec<String>,
|
||||
/// gen2: the resolved CDN bases from the secure-link answer (every `urls[]` entry, query
|
||||
/// strings kept, in the order GOG lists them), or the one unauthenticated dependency store
|
||||
/// base. Several bases on distinct hosts let the fetch core spread the window across CDNs
|
||||
/// with its per-host cap; a base on a host already listed is dropped (the first one wins).
|
||||
/// gen1: unused (file URLs live in the manifest).
|
||||
pub cdn_bases: Vec<String>,
|
||||
/// gen2: resolved CDN base from `parseCdnUrl` (secure-link query string kept), or the
|
||||
/// unauthenticated dependency store base. gen1: unused (file URLs live in the manifest).
|
||||
pub cdn_base: String,
|
||||
pub install_dir: String,
|
||||
/// Files already completed by an earlier run of this same download (secure-link refresh
|
||||
/// re-run): counted as done WITHOUT re-hashing and WITHOUT a progress event.
|
||||
@@ -113,10 +109,6 @@ pub trait GogEvents: Sync {
|
||||
bytes_total: u64,
|
||||
);
|
||||
fn on_log(&self, line: &str);
|
||||
/// Periodic byte progress while files are in flight (~4/s, only when the value moved):
|
||||
/// assembled bytes plus the bytes of files not yet finished. Same `bytes_total` as
|
||||
/// `on_file_done`. Default: ignored (test recorders).
|
||||
fn on_bytes(&self, _bytes_done: u64, _bytes_total: u64) {}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
@@ -186,9 +178,6 @@ pub fn is_link_expiry_status(code: u16) -> bool {
|
||||
struct FileState {
|
||||
handle: Option<Arc<File>>,
|
||||
chunks_done: usize,
|
||||
/// Decompressed bytes of this file's finished chunks, credited to the sink's `partial`
|
||||
/// counter until the file itself is finalized and moves into `bytes_done`.
|
||||
partial: u64,
|
||||
finalized: bool,
|
||||
failed: bool,
|
||||
tmp_path: PathBuf,
|
||||
@@ -333,9 +322,6 @@ struct GogSink<'a> {
|
||||
bytes_done: &'a AtomicU64,
|
||||
events: &'a dyn GogEvents,
|
||||
speed: Mutex<SpeedSampler>,
|
||||
/// Bytes of files still in flight (finished chunks; for gen1, the current attempt's pieces).
|
||||
/// `bytes_done + partial` is what the byte ticker reports between file completions.
|
||||
partial: AtomicU64,
|
||||
}
|
||||
|
||||
impl<'a> GogSink<'a> {
|
||||
@@ -388,7 +374,7 @@ impl<'a> GogSink<'a> {
|
||||
/// One verified chunk landed: count it; on the file's last chunk run the whole-file verify +
|
||||
/// rename and fire the per-file progress event (Java: doneCount++, totalBytes += df.totalSize,
|
||||
/// "Downloading: <name> <speed>").
|
||||
fn chunk_done(&self, file_idx: usize, chunk_bytes: u64) -> Result<(), SinkError> {
|
||||
fn chunk_done(&self, file_idx: usize) -> Result<(), SinkError> {
|
||||
let file = &self.files[file_idx];
|
||||
let mut st = self
|
||||
.states
|
||||
@@ -402,8 +388,6 @@ impl<'a> GogSink<'a> {
|
||||
)));
|
||||
}
|
||||
st.chunks_done += 1;
|
||||
st.partial += chunk_bytes;
|
||||
self.partial.fetch_add(chunk_bytes, Ordering::Relaxed);
|
||||
if st.chunks_done < file.chunks.len() {
|
||||
return Ok(());
|
||||
}
|
||||
@@ -411,14 +395,12 @@ impl<'a> GogSink<'a> {
|
||||
st.failed = true;
|
||||
return Err(SinkError::Fatal(err));
|
||||
}
|
||||
let partial = std::mem::take(&mut st.partial);
|
||||
drop(st);
|
||||
let done = self.files_done.fetch_add(1, Ordering::Relaxed) + 1;
|
||||
let bytes = self
|
||||
.bytes_done
|
||||
.fetch_add(file.total_size, Ordering::Relaxed)
|
||||
+ file.total_size;
|
||||
self.partial.fetch_sub(partial, Ordering::Relaxed);
|
||||
self.events.on_file_done(
|
||||
&file.relative_path,
|
||||
file.total_size,
|
||||
@@ -559,7 +541,7 @@ impl<'a> FetchSink for GogSink<'a> {
|
||||
}
|
||||
drop(handle);
|
||||
let credited = inflated.len() as u64;
|
||||
self.chunk_done(file_idx, credited)?;
|
||||
self.chunk_done(file_idx)?;
|
||||
Ok(credited)
|
||||
}
|
||||
|
||||
@@ -712,59 +694,11 @@ impl<'a> FetchSink for GogSink<'a> {
|
||||
return Err(SinkError::Retry(msg));
|
||||
}
|
||||
drop(writer.file);
|
||||
self.chunk_done(file_idx, writer.written)?;
|
||||
self.chunk_done(file_idx)?;
|
||||
Ok(0)
|
||||
}
|
||||
}
|
||||
|
||||
/// How often the byte ticker reports while files are in flight.
|
||||
pub const BYTE_TICK: Duration = Duration::from_millis(250);
|
||||
|
||||
/// The CDN bases to fetch from: empty entries dropped, then one per distinct host (`host_key`),
|
||||
/// the first base seen for a host kept, order preserved.
|
||||
pub fn distinct_bases(bases: &[String]) -> Vec<String> {
|
||||
let mut seen: HashSet<String> = HashSet::new();
|
||||
bases
|
||||
.iter()
|
||||
.map(|b| b.trim())
|
||||
.filter(|b| !b.is_empty() && seen.insert(host_key(b)))
|
||||
.map(str::to_string)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Runs `fetch` with a reporter thread beside it that calls `on_bytes(bytes_done + partial,
|
||||
/// bytes_total)` every [`BYTE_TICK`] when the value moved. `on_file_done` only fires when a whole
|
||||
/// file is finished, so a game made of a few large files gave the UI a progress bar that sat
|
||||
/// still and then jumped; this fills the gaps. One last report is made when `fetch` returns.
|
||||
fn with_byte_ticker<T>(
|
||||
events: &dyn GogEvents,
|
||||
bytes_done: &AtomicU64,
|
||||
partial: &AtomicU64,
|
||||
bytes_total: u64,
|
||||
fetch: impl FnOnce() -> T,
|
||||
) -> T {
|
||||
let stop = AtomicBool::new(false);
|
||||
let current = || bytes_done.load(Ordering::Relaxed) + partial.load(Ordering::Relaxed);
|
||||
std::thread::scope(|scope| {
|
||||
scope.spawn(|| {
|
||||
crate::priority::background();
|
||||
let mut last = u64::MAX;
|
||||
while !stop.load(Ordering::Relaxed) {
|
||||
std::thread::sleep(BYTE_TICK);
|
||||
let now = current();
|
||||
if now != last {
|
||||
last = now;
|
||||
events.on_bytes(now, bytes_total);
|
||||
}
|
||||
}
|
||||
});
|
||||
let out = fetch();
|
||||
stop.store(true, Ordering::Relaxed);
|
||||
events.on_bytes(current(), bytes_total);
|
||||
out
|
||||
})
|
||||
}
|
||||
|
||||
/// Runs one download loop. Blocking; returns when every pending file is finalized, on the first
|
||||
/// fatal file failure, or on cancel. Safe to call again with `skip_paths` extended by the files
|
||||
/// this run reported done (that is how the Java side re-runs after a secure-link refresh).
|
||||
@@ -784,12 +718,11 @@ fn run_gen2(req: &GogRequest, cancel: &AtomicBool, events: &dyn GogEvents) -> Go
|
||||
let chunk_count: usize = files.iter().map(|f| f.chunks.len()).sum();
|
||||
let max_workers = req.max_workers.max(1);
|
||||
let process_workers = req.process_workers.max(1);
|
||||
let bases = distinct_bases(&req.cdn_bases);
|
||||
let hosts: Vec<String> = bases.iter().map(|b| host_key(b)).collect();
|
||||
let per_host_cap = per_host_cap_for(max_workers, hosts.len());
|
||||
let host = host_key(&req.cdn_base);
|
||||
let per_host_cap = per_host_cap_for(max_workers, 1);
|
||||
|
||||
events.on_log(&format!(
|
||||
"engine=rust kind=gen2 mode=stream label={} files={} chunks={} planned_bytes={} skip_paths={} workers={} per_host_cap={} process_workers={} sort_largest_first={} hosts={} {}",
|
||||
"engine=rust kind=gen2 mode=stream label={} files={} chunks={} planned_bytes={} skip_paths={} workers={} per_host_cap={} process_workers={} sort_largest_first={} host={} {}",
|
||||
req.label,
|
||||
files_total,
|
||||
chunk_count,
|
||||
@@ -799,7 +732,7 @@ fn run_gen2(req: &GogRequest, cancel: &AtomicBool, events: &dyn GogEvents) -> Go
|
||||
per_host_cap,
|
||||
process_workers,
|
||||
req.sort_largest_first,
|
||||
hosts.join(","),
|
||||
host,
|
||||
crate::priority::log_field()
|
||||
));
|
||||
|
||||
@@ -883,7 +816,6 @@ fn run_gen2(req: &GogRequest, cancel: &AtomicBool, events: &dyn GogEvents) -> Go
|
||||
states.push(Mutex::new(FileState {
|
||||
handle: None,
|
||||
chunks_done: 0,
|
||||
partial: 0,
|
||||
// Files not pending (verified or skip-listed) are already final for this run.
|
||||
finalized: !is_pending,
|
||||
failed: false,
|
||||
@@ -896,11 +828,10 @@ fn run_gen2(req: &GogRequest, cancel: &AtomicBool, events: &dyn GogEvents) -> Go
|
||||
pending_files += 1;
|
||||
pending_bytes = pending_bytes.saturating_add(file.total_size);
|
||||
for (chunk_idx, chunk) in file.chunks.iter().enumerate() {
|
||||
let path = build_cdn_path(&chunk.hash);
|
||||
let url = build_chunk_url(&req.cdn_base, &build_cdn_path(&chunk.hash));
|
||||
items.push(FetchItem {
|
||||
id: table.len() as u64,
|
||||
// One URL per host, in `hosts` order: the core picks `urls[host_idx]`.
|
||||
urls: bases.iter().map(|b| build_chunk_url(b, &path)).collect(),
|
||||
urls: vec![url],
|
||||
reserve: chunk.compressed_size,
|
||||
range: None,
|
||||
});
|
||||
@@ -939,11 +870,11 @@ fn run_gen2(req: &GogRequest, cancel: &AtomicBool, events: &dyn GogEvents) -> Go
|
||||
bytes_done: &bytes_done,
|
||||
events,
|
||||
speed: Mutex::new(SpeedSampler::new()),
|
||||
partial: AtomicU64::new(0),
|
||||
};
|
||||
let hosts = vec![host];
|
||||
let opts = FetchOptions {
|
||||
max_workers,
|
||||
// The ceiling split across the distinct CDN hosts (floor 6); one host gets all of it.
|
||||
// One CDN host gets the whole ceiling (Java has no per-host cap either).
|
||||
per_host_cap,
|
||||
timeout: CHUNK_TIMEOUT,
|
||||
headers: vec![("User-Agent".to_string(), USER_AGENT.to_string())],
|
||||
@@ -956,9 +887,7 @@ fn run_gen2(req: &GogRequest, cancel: &AtomicBool, events: &dyn GogEvents) -> Go
|
||||
};
|
||||
let log = |line: &str| events.on_log(line);
|
||||
let progress = |_bytes: u64, _items_ok: u64| {};
|
||||
let outcome = with_byte_ticker(events, &bytes_done, &sink.partial, planned_bytes, || {
|
||||
run_fetch(items, &hosts, &opts, &sink, cancel, &progress, &log)
|
||||
});
|
||||
let outcome = run_fetch(items, &hosts, &opts, &sink, cancel, &progress, &log);
|
||||
|
||||
let cancelled = outcome.cancelled || cancel.load(Ordering::Relaxed);
|
||||
let mut error = outcome.error.clone().unwrap_or_default();
|
||||
@@ -1016,9 +945,6 @@ fn run_gen2(req: &GogRequest, cancel: &AtomicBool, events: &dyn GogEvents) -> Go
|
||||
|
||||
struct Gen1State {
|
||||
handle: Option<File>,
|
||||
/// Bytes this file's current attempt has written (credited to the sink's `partial`); a new
|
||||
/// attempt starts over, so a retry never counts its bytes twice.
|
||||
attempt_bytes: u64,
|
||||
out_path: PathBuf,
|
||||
finalized: bool,
|
||||
}
|
||||
@@ -1036,9 +962,6 @@ struct Gen1Sink<'a> {
|
||||
bytes_done: &'a AtomicU64,
|
||||
events: &'a dyn GogEvents,
|
||||
speed: Mutex<SpeedSampler>,
|
||||
/// Bytes of files still in flight (finished chunks; for gen1, the current attempt's pieces).
|
||||
/// `bytes_done + partial` is what the byte ticker reports between file completions.
|
||||
partial: AtomicU64,
|
||||
}
|
||||
|
||||
impl<'a> FetchSink for Gen1Sink<'a> {
|
||||
@@ -1062,8 +985,6 @@ impl<'a> FetchSink for Gen1Sink<'a> {
|
||||
.map_err(|_| SinkError::Fatal("gen1 state poisoned".to_string()))?;
|
||||
if offset == 0 {
|
||||
// New attempt: Java `outFile.delete()` + `new FileOutputStream(out)`.
|
||||
self.partial
|
||||
.fetch_sub(std::mem::take(&mut st.attempt_bytes), Ordering::Relaxed);
|
||||
st.handle = None;
|
||||
if let Some(parent) = st.out_path.parent() {
|
||||
let _ = fs::create_dir_all(parent);
|
||||
@@ -1095,8 +1016,6 @@ impl<'a> FetchSink for Gen1Sink<'a> {
|
||||
st.handle = None;
|
||||
return Err(SinkError::Retry(msg));
|
||||
}
|
||||
st.attempt_bytes += data.len() as u64;
|
||||
self.partial.fetch_add(data.len() as u64, Ordering::Relaxed);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1111,12 +1030,9 @@ impl<'a> FetchSink for Gen1Sink<'a> {
|
||||
.map_err(|_| SinkError::Fatal("gen1 state poisoned".to_string()))?;
|
||||
st.handle = None; // close
|
||||
st.finalized = true;
|
||||
let attempt = std::mem::take(&mut st.attempt_bytes);
|
||||
self.bytes_done.fetch_add(file.size, Ordering::Relaxed);
|
||||
self.partial.fetch_sub(attempt, Ordering::Relaxed);
|
||||
}
|
||||
let done = self.files_done.fetch_add(1, Ordering::Relaxed) + 1;
|
||||
let bytes = self.bytes_done.load(Ordering::Relaxed);
|
||||
let bytes = self.bytes_done.fetch_add(file.size, Ordering::Relaxed) + file.size;
|
||||
self.events.on_file_done(
|
||||
&file.path,
|
||||
file.size,
|
||||
@@ -1199,7 +1115,6 @@ fn run_gen1(req: &GogRequest, cancel: &AtomicBool, events: &dyn GogEvents) -> Go
|
||||
.unwrap_or(false);
|
||||
states.push(Mutex::new(Gen1State {
|
||||
handle: None,
|
||||
attempt_bytes: 0,
|
||||
out_path,
|
||||
finalized: skipped || resumed,
|
||||
}));
|
||||
@@ -1254,7 +1169,6 @@ fn run_gen1(req: &GogRequest, cancel: &AtomicBool, events: &dyn GogEvents) -> Go
|
||||
bytes_done: &bytes_done,
|
||||
events,
|
||||
speed: Mutex::new(SpeedSampler::new()),
|
||||
partial: AtomicU64::new(0),
|
||||
};
|
||||
let hosts = vec![host];
|
||||
let opts = FetchOptions {
|
||||
@@ -1269,9 +1183,7 @@ fn run_gen1(req: &GogRequest, cancel: &AtomicBool, events: &dyn GogEvents) -> Go
|
||||
};
|
||||
let log = |line: &str| events.on_log(line);
|
||||
let progress = |_bytes: u64, _items_ok: u64| {};
|
||||
let outcome = with_byte_ticker(events, &bytes_done, &sink.partial, planned_bytes, || {
|
||||
run_fetch(items, &hosts, &opts, &sink, cancel, &progress, &log)
|
||||
});
|
||||
let outcome = run_fetch(items, &hosts, &opts, &sink, cancel, &progress, &log);
|
||||
|
||||
let cancelled = outcome.cancelled || cancel.load(Ordering::Relaxed);
|
||||
let error = outcome.error.clone().unwrap_or_default();
|
||||
@@ -1374,24 +1286,6 @@ mod tests {
|
||||
assert_eq!(http_status_in("HTTP 404 not found"), Some(404));
|
||||
assert_eq!(http_status_in("chunk=abc403def timed out"), None, "hash digits are not a status");
|
||||
assert_eq!(http_status_in("timeout"), None);
|
||||
let bases = vec![
|
||||
"https://gog-cdn-fastly.gog.com/token/a?x=1".to_string(),
|
||||
" ".to_string(),
|
||||
"https://GOG-CDN-FASTLY.gog.com/token/b?x=2".to_string(),
|
||||
"https://gog-cdn-akamai.gog.com/token/c?y=3".to_string(),
|
||||
"https://gog-cdn-lumen.gog.com/token/d".to_string(),
|
||||
];
|
||||
assert_eq!(
|
||||
distinct_bases(&bases),
|
||||
vec![
|
||||
"https://gog-cdn-fastly.gog.com/token/a?x=1".to_string(),
|
||||
"https://gog-cdn-akamai.gog.com/token/c?y=3".to_string(),
|
||||
"https://gog-cdn-lumen.gog.com/token/d".to_string(),
|
||||
],
|
||||
"blank dropped, second fastly base dropped, order kept"
|
||||
);
|
||||
assert_eq!(per_host_cap_for(96, 3), 32);
|
||||
assert_eq!(per_host_cap_for(96, 1), 96);
|
||||
assert!(is_link_expiry_status(401));
|
||||
assert!(is_link_expiry_status(403));
|
||||
assert!(is_link_expiry_status(404));
|
||||
@@ -1451,7 +1345,6 @@ mod tests {
|
||||
states: vec![Mutex::new(FileState {
|
||||
handle: None,
|
||||
chunks_done: 0,
|
||||
partial: 0,
|
||||
finalized: false,
|
||||
failed: false,
|
||||
tmp_path: tmp_path.clone(),
|
||||
@@ -1464,7 +1357,6 @@ mod tests {
|
||||
bytes_done: &bytes_done,
|
||||
events: &rec,
|
||||
speed: Mutex::new(SpeedSampler::new()),
|
||||
partial: AtomicU64::new(0),
|
||||
};
|
||||
let item = |id: u64| FetchItem { id, urls: vec!["x".into()], reserve: 0, range: None };
|
||||
|
||||
@@ -1509,7 +1401,6 @@ mod tests {
|
||||
states: vec![Mutex::new(FileState {
|
||||
handle: None,
|
||||
chunks_done: 0,
|
||||
partial: 0,
|
||||
finalized: false,
|
||||
failed: false,
|
||||
tmp_path: tmp_path.clone(),
|
||||
@@ -1522,7 +1413,6 @@ mod tests {
|
||||
bytes_done: &bytes_done,
|
||||
events: &rec,
|
||||
speed: Mutex::new(SpeedSampler::new()),
|
||||
partial: AtomicU64::new(0),
|
||||
};
|
||||
let item = FetchItem { id: 0, urls: vec!["x".into()], reserve: 0, range: None };
|
||||
match sink.process(&item, raw) {
|
||||
@@ -1548,7 +1438,7 @@ mod tests {
|
||||
);
|
||||
let req = GogRequest {
|
||||
depot_manifests: vec![manifest],
|
||||
cdn_bases: vec!["https://example.invalid/store?tok=1".to_string()],
|
||||
cdn_base: "https://example.invalid/store?tok=1".to_string(),
|
||||
install_dir: dir.to_string_lossy().into_owned(),
|
||||
skip_paths: vec!["skipped.bin".to_string()],
|
||||
max_workers: 4,
|
||||
@@ -1615,7 +1505,6 @@ mod tests {
|
||||
states: vec![Mutex::new(FileState {
|
||||
handle: None,
|
||||
chunks_done: 0,
|
||||
partial: 0,
|
||||
finalized: false,
|
||||
failed: false,
|
||||
tmp_path: tmp_path.clone(),
|
||||
@@ -1628,7 +1517,6 @@ mod tests {
|
||||
bytes_done: &bytes_done,
|
||||
events: &rec,
|
||||
speed: Mutex::new(SpeedSampler::new()),
|
||||
partial: AtomicU64::new(0),
|
||||
};
|
||||
let item = |id: u64| FetchItem { id, urls: vec!["x".into()], reserve: 0, range: None };
|
||||
|
||||
@@ -1692,7 +1580,6 @@ mod tests {
|
||||
files: &files,
|
||||
states: vec![Mutex::new(Gen1State {
|
||||
handle: None,
|
||||
attempt_bytes: 0,
|
||||
out_path: dir.join("sub/blob.bin"),
|
||||
finalized: false,
|
||||
})],
|
||||
@@ -1702,7 +1589,6 @@ mod tests {
|
||||
bytes_done: &bytes_done,
|
||||
events: &rec,
|
||||
speed: Mutex::new(SpeedSampler::new()),
|
||||
partial: AtomicU64::new(0),
|
||||
};
|
||||
let item = FetchItem { id: 0, urls: vec!["x".into()], reserve: 8, range: Some((100, 107)) };
|
||||
// Attempt 1 writes a partial, attempt 2 restarts from offset 0 and truncates it.
|
||||
@@ -1756,7 +1642,7 @@ mod tests {
|
||||
let manifest = r#"{"depot":{"items":[{"path":"a.bin","chunks":[{"compressedMd5":"ab","size":4}]}]}}"#;
|
||||
let req = GogRequest {
|
||||
depot_manifests: vec![manifest.to_string()],
|
||||
cdn_bases: vec!["https://example.invalid/store".to_string()],
|
||||
cdn_base: "https://example.invalid/store".to_string(),
|
||||
install_dir: dir.to_string_lossy().into_owned(),
|
||||
max_workers: 1,
|
||||
process_workers: 1,
|
||||
@@ -1769,32 +1655,4 @@ mod tests {
|
||||
assert_eq!(res.error, "cancelled");
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn byte_ticker_reports_in_flight_bytes_between_file_completions() {
|
||||
struct Bytes(StdMutex<Vec<(u64, u64)>>);
|
||||
impl GogEvents for Bytes {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn on_file_done(&self, _: &str, _: u64, _: bool, _: u32, _: u32, _: u64, _: u64) {}
|
||||
fn on_log(&self, _: &str) {}
|
||||
fn on_bytes(&self, done: u64, total: u64) {
|
||||
self.0.lock().unwrap().push((done, total));
|
||||
}
|
||||
}
|
||||
let rec = Bytes(StdMutex::new(Vec::new()));
|
||||
let bytes_done = AtomicU64::new(100);
|
||||
let partial = AtomicU64::new(0);
|
||||
let out = with_byte_ticker(&rec, &bytes_done, &partial, 1000, || {
|
||||
partial.store(50, Ordering::Relaxed);
|
||||
std::thread::sleep(BYTE_TICK * 3);
|
||||
bytes_done.store(400, Ordering::Relaxed);
|
||||
partial.store(0, Ordering::Relaxed);
|
||||
7
|
||||
});
|
||||
assert_eq!(out, 7);
|
||||
let calls = rec.0.lock().unwrap().clone();
|
||||
assert!(calls.contains(&(150, 1000)), "in-flight bytes reported mid-run: {calls:?}");
|
||||
assert_eq!(calls.last(), Some(&(400, 1000)), "final report when the fetch returns");
|
||||
assert!(calls.windows(2).all(|w| w[0] != w[1] || w[1] == (400, 1000)), "no repeats while idle: {calls:?}");
|
||||
}
|
||||
}
|
||||
@@ -136,23 +136,6 @@ impl GogEvents for JniEvents {
|
||||
});
|
||||
}
|
||||
|
||||
fn on_bytes(&self, bytes_done: u64, bytes_total: u64) {
|
||||
// A listener without `onBytes` (an app built against the older contract) makes this a
|
||||
// NoSuchMethodError, which clear_exception drops: the run is unaffected.
|
||||
self.with_env(|env| {
|
||||
let _ = env.call_method(
|
||||
self.listener.as_obj(),
|
||||
"onBytes",
|
||||
"(JJ)V",
|
||||
&[
|
||||
JValue::Long(bytes_done as jlong),
|
||||
JValue::Long(bytes_total as jlong),
|
||||
],
|
||||
);
|
||||
Self::clear_exception(env);
|
||||
});
|
||||
}
|
||||
|
||||
fn on_log(&self, line: &str) {
|
||||
android_log(line);
|
||||
self.with_env(|env| {
|
||||
@@ -228,7 +211,7 @@ pub extern "system" fn Java_com_droiddeck_launcher_stores_gog_GogNative_nativeSt
|
||||
_class: JClass,
|
||||
kind: jint,
|
||||
depot_manifests: JObjectArray,
|
||||
cdn_bases: JObjectArray,
|
||||
cdn_base: JString,
|
||||
install_dir: JString,
|
||||
skip_paths: JObjectArray,
|
||||
ca_bundle_path: JString,
|
||||
@@ -253,7 +236,7 @@ pub extern "system" fn Java_com_droiddeck_launcher_stores_gog_GogNative_nativeSt
|
||||
let request = GogRequest {
|
||||
kind: PlanKind::from_i32(kind),
|
||||
depot_manifests: string_array_to_vec(&mut env, &depot_manifests),
|
||||
cdn_bases: string_array_to_vec(&mut env, &cdn_bases),
|
||||
cdn_base: jstring_to_string(&mut env, &cdn_base).unwrap_or_default(),
|
||||
install_dir: jstring_to_string(&mut env, &install_dir).unwrap_or_default(),
|
||||
skip_paths: string_array_to_vec(&mut env, &skip_paths),
|
||||
ca_bundle_path: jstring_to_string(&mut env, &ca_bundle_path).unwrap_or_default(),
|
||||
@@ -263,11 +246,11 @@ pub extern "system" fn Java_com_droiddeck_launcher_stores_gog_GogNative_nativeSt
|
||||
label: jstring_to_string(&mut env, &label).unwrap_or_else(|| "gog".to_string()),
|
||||
};
|
||||
let needs_base = request.kind == PlanKind::Gen2Chunks;
|
||||
if (needs_base && super::engine::distinct_bases(&request.cdn_bases).is_empty())
|
||||
if (needs_base && request.cdn_base.is_empty())
|
||||
|| request.install_dir.is_empty()
|
||||
|| request.depot_manifests.is_empty()
|
||||
{
|
||||
android_log("nativeStart: invalid request (no cdn base / empty install dir / no manifests)");
|
||||
android_log("nativeStart: invalid request (empty cdn base / install dir / manifests)");
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
@@ -87,65 +87,4 @@ class LogRedactorTest {
|
||||
assertEquals(once, LogRedactor.redact(once))
|
||||
}
|
||||
}
|
||||
|
||||
// The Steam UI's own login line (webhelper_js.txt), as the privacy scan found it.
|
||||
@Test fun loginStateLineLosesAnEmailAccount() {
|
||||
val line = "[2026-10-07 21:14:03] SteamUI: INFO: Login: OnLoginStateChange someone.masked@example.com 2 1 0 0"
|
||||
val out = LogRedactor.redact(line)
|
||||
assertFalse(out.contains("someone.masked"))
|
||||
assertFalse(out.contains("example.com"))
|
||||
assertEquals("[2026-10-07 21:14:03] SteamUI: INFO: Login: OnLoginStateChange <redacted:account> 2 1 0 0", out)
|
||||
assertEquals(out, LogRedactor.redactForShare(line))
|
||||
}
|
||||
|
||||
@Test fun loginStateLineLosesAPlainAccountName() {
|
||||
val line = "[2026-10-07 21:14:03] SteamUI: INFO: Login: OnLoginStateChange maskeduser42 2 1 0 0"
|
||||
val out = LogRedactor.redact(line)
|
||||
assertFalse(out.contains("maskeduser42"))
|
||||
assertEquals("[2026-10-07 21:14:03] SteamUI: INFO: Login: OnLoginStateChange <redacted:account> 2 1 0 0", out)
|
||||
assertEquals(out, LogRedactor.redactForShare(line))
|
||||
}
|
||||
|
||||
@Test fun loginStateWithoutAnAccountIsKept() {
|
||||
val line = "SteamUI: INFO: Login: OnLoginStateChange 0 1 0 0"
|
||||
assertEquals(line, LogRedactor.redact(line))
|
||||
}
|
||||
|
||||
@Test fun accountNameFieldsAreRedacted() {
|
||||
val lines = listOf(
|
||||
"\t\"AccountName\"\t\t\"maskeduser42\"",
|
||||
"account_name=maskeduser42 remember=1",
|
||||
"{\"login\":\"maskeduser42\",\"persist\":1}",
|
||||
"auth: login=maskeduser42&remember=1",
|
||||
"accountName: maskeduser42",
|
||||
"{\"username\": \"masked user 42\"}",
|
||||
)
|
||||
for (line in lines) {
|
||||
val out = LogRedactor.redactForShare(line)
|
||||
assertFalse(out, out.contains("maskeduser42") || out.contains("masked user"))
|
||||
assertTrue(out, out.contains("<redacted:account>"))
|
||||
assertEquals(out, LogRedactor.redactForShare(out))
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun loginAsAWordIsNotAField() {
|
||||
for (line in listOf("SteamUI: INFO: Login: OnLoginStateChange 0 1 0 0", "login refresh pending", "Login: state 5")) {
|
||||
assertEquals(line, LogRedactor.redact(line))
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun privateAddressesLeaveTheZipPublicOnesStay() {
|
||||
assertEquals("I/LinuxNetworkLink: resolver: <lan-address> <lan-address> 8.8.8.8",
|
||||
LogRedactor.redactForShare("I/LinuxNetworkLink: resolver: 192.168.1.1 10.0.0.138 8.8.8.8"))
|
||||
assertEquals("gateway <lan-address>:53 link <lan-address> lan <lan-address>",
|
||||
LogRedactor.redactForShare("gateway 172.16.4.20:53 link 169.254.10.2 lan 172.31.255.254"))
|
||||
for (line in listOf(
|
||||
"connecting to CM 162.254.193.47:27017",
|
||||
"public 172.32.0.1 and 11.0.0.1 and 193.168.1.1",
|
||||
"Windows 10.0.19041.1 build 10.0.19045",
|
||||
"Proton 10.0-3, driver 25.1.0.4",
|
||||
)) assertEquals(line, LogRedactor.redactForShare(line))
|
||||
val once = LogRedactor.redactForShare("resolver: 192.168.0.1")
|
||||
assertEquals(once, LogRedactor.redactForShare(once))
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Test
|
||||
|
||||
class SecretScrubTest {
|
||||
private fun share(line: String) = SecretScrub.scrub(line, SecretScrub.Urls.KEEP_PATH, "<redacted:token>")
|
||||
|
||||
@Test fun windowsExceptionCodesAreKept() {
|
||||
for (line in listOf(
|
||||
"0024:trace:seh:dispatch_exception code=406d1388 flags=0 addr=00006FFFFFC0A6E8",
|
||||
"0024:warn:seh:dispatch_exception code=c0000005 flags=0 addr=0000000140012345",
|
||||
"0030:trace:seh:handle_syscall_fault code=80000003 flags=0",
|
||||
"exception code=0xC0000005 at 0x140012345",
|
||||
// An exception code stays one even on a line that also carries OAuth keys.
|
||||
"client_id=abc code=c0000005",
|
||||
)) assertEquals(line, share(line))
|
||||
}
|
||||
|
||||
@Test fun anOAuthCodeIsBlanked() {
|
||||
assertEquals("redirect client_id=34a02cf8 redirect_uri=x state=1 code=<redacted:token>",
|
||||
share("redirect client_id=34a02cf8 redirect_uri=x state=1 code=AUTHCODE123"))
|
||||
assertEquals("GET /on_login_success?code=<redacted:token>&scope=",
|
||||
share("GET /on_login_success?code=AUTHCODE123&scope="))
|
||||
assertEquals("exchange_code=<redacted:token>", share("exchange_code=0123456789abcdef"))
|
||||
assertEquals("authorizationCode=<redacted:token>", share("authorizationCode=ABCD1234XYZ"))
|
||||
}
|
||||
|
||||
@Test fun aCodeWithoutOAuthAroundItIsKept() {
|
||||
for (line in listOf("exit code=1337", "status code=ERR_TIMEOUT", "code 403")) assertEquals(line, share(line))
|
||||
}
|
||||
|
||||
@Test fun scrubbingTwiceChangesNothing() {
|
||||
val once = share("client_id=1 code=AUTHCODE123 ?code=XYZW1234567")
|
||||
assertFalse(once.contains("AUTHCODE123"))
|
||||
assertEquals(once, share(once))
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,6 @@ class RuntimeRemovalTest {
|
||||
private lateinit var dir: File
|
||||
@Before fun setUp() { dir = Files.createTempDirectory("runtime-removal").toFile() }
|
||||
@After fun tearDown() {
|
||||
RuntimeFileTree.refuseForTest = null
|
||||
dir.setWritable(true)
|
||||
RuntimeFileTree.delete(dir, null)
|
||||
}
|
||||
@@ -161,40 +160,4 @@ class RuntimeRemovalTest {
|
||||
assertTrue(LinuxRuntimeInstaller.beginUninstall(null, root)!!.run(null))
|
||||
assertNull(LinuxRuntimeInstaller.removalError())
|
||||
}
|
||||
|
||||
@Test fun anEntryTheAppCannotDeleteIsSetAsideInsteadOfStrandingTheRemoval() {
|
||||
val root = runtime()
|
||||
File(root, "root/.steampath").writeText("made by su")
|
||||
RuntimeFileTree.refuseForTest = java.util.function.Predicate { it.fileName.toString() == ".steampath" }
|
||||
assertTrue(LinuxRuntimeInstaller.beginUninstall(null, root)!!.run(null))
|
||||
assertNull(LinuxRuntimeInstaller.removalError())
|
||||
assertFalse(root.exists())
|
||||
assertFalse(File(dir, "linuxfs.removing").exists())
|
||||
// Only the undeletable entry and its parents remain, out of the way.
|
||||
val trash = File(dir, LinuxRuntimeInstaller.TRASH)
|
||||
assertEquals(listOf(".steampath"), trash.walk().filter { it.isFile }.map { it.name }.toList())
|
||||
assertEquals(setOf(LinuxRuntimeInstaller.TRASH), dir.list()!!.toSet())
|
||||
|
||||
// Once it can be deleted, the next removal clears the trash too.
|
||||
RuntimeFileTree.refuseForTest = null
|
||||
assertTrue(LinuxRuntimeInstaller.beginUninstall(null, root)!!.run(null))
|
||||
assertFalse(trash.exists())
|
||||
}
|
||||
|
||||
@Test fun aStuckQuarantineFromAnEarlierBuildClearsOnTheNextRemoval() {
|
||||
val pending = File(dir, "linuxfs.removing").apply { File(this, "root").mkdirs() }
|
||||
File(pending, "root/.steampid").writeText("1")
|
||||
File(pending, "root/game").writeText("game")
|
||||
RuntimeFileTree.refuseForTest = java.util.function.Predicate { it.fileName.toString() == ".steampid" }
|
||||
assertTrue(LinuxRuntimeInstaller.beginUninstall(null, File(dir, "linuxfs"))!!.run(null))
|
||||
assertFalse(pending.exists())
|
||||
}
|
||||
|
||||
@Test fun deleteWhatCanKeepsGoingPastAnEntryItCannotDelete() {
|
||||
val root = runtime()
|
||||
RuntimeFileTree.refuseForTest = java.util.function.Predicate { it.fileName.toString() == "gamescope" }
|
||||
assertFalse(RuntimeFileTree.deleteWhatCan(root, null))
|
||||
assertEquals(listOf("gamescope"), root.walk().filter { it.isFile }.map { it.name }.toList())
|
||||
assertFalse(File(root, "root").exists())
|
||||
}
|
||||
}
|
||||
@@ -27,24 +27,15 @@ class SessionDisplayTest {
|
||||
|
||||
@Test fun optionsListTheHeightsThePanelCanShowThenThePanel() {
|
||||
val thor = SessionDisplay.resolutionOptions(1920 to 1080)
|
||||
assertEquals(listOf("720p", "900p", SessionDisplay.MATCH_SCREEN, SessionDisplay.FOLLOW_SCREEN), thor)
|
||||
assertEquals(listOf("720p", "900p", SessionDisplay.MATCH_SCREEN, SessionDisplay.FOLLOW_SCREEN),
|
||||
SessionDisplay.resolutionOptions(2400 to 1080))
|
||||
assertEquals(listOf("720p", "900p", "1080p", SessionDisplay.MATCH_SCREEN, SessionDisplay.FOLLOW_SCREEN),
|
||||
SessionDisplay.resolutionOptions(3120 to 1440))
|
||||
assertEquals(listOf("720p", "900p", SessionDisplay.MATCH_SCREEN), thor)
|
||||
assertEquals(listOf("720p", "900p", SessionDisplay.MATCH_SCREEN), SessionDisplay.resolutionOptions(2400 to 1080))
|
||||
assertEquals(listOf("720p", "900p", "1080p", SessionDisplay.MATCH_SCREEN), SessionDisplay.resolutionOptions(3120 to 1440))
|
||||
val small = SessionDisplay.resolutionOptions(1280 to 720)
|
||||
assertEquals(listOf(SessionDisplay.MATCH_SCREEN, SessionDisplay.FOLLOW_SCREEN), small)
|
||||
assertEquals(listOf(SessionDisplay.MATCH_SCREEN), small)
|
||||
assertEquals(1280 to 720, SessionDisplay.resolveChoice(1280 to 720, SessionDisplay.MATCH_SCREEN))
|
||||
assertEquals(2560 to 1440, SessionDisplay.resolveChoice(2560 to 1440, SessionDisplay.MATCH_SCREEN))
|
||||
}
|
||||
|
||||
@Test fun followScreenKeepsTheWindowShapeAndSkipsTinyWindows() {
|
||||
assertEquals(2520 to 1080, SessionDisplay.resolveChoice(1080 to 2520, SessionDisplay.FOLLOW_SCREEN))
|
||||
assertEquals(1968 to 2184, SessionDisplay.followSize(1968, 2184))
|
||||
assertEquals(2184 to 1968, SessionDisplay.followSize(2185, 1969))
|
||||
assertNull(SessionDisplay.followSize(640, 360))
|
||||
}
|
||||
|
||||
@Test fun resolutionCapsPreserveTheSelectedShapeWithoutExceedingPanelHeight() {
|
||||
assertEquals(1280 to 720, SessionDisplay.resolve(1920 to 1080, 720, SessionPrefs.SHAPE_AUTO))
|
||||
assertEquals(960 to 720, SessionDisplay.resolve(1440 to 1080, 720, SessionPrefs.SHAPE_EXACT))
|
||||
|
||||
@@ -33,13 +33,12 @@ class SessionLogShareTest {
|
||||
"rules $rules\n" + files.joinToString("") { val f = File(folder, it); "${f.length()}\t${f.lastModified()}\t$it\n" })
|
||||
}
|
||||
|
||||
@Test fun aRecordedUnchangedFileIsScrubbedAgainOnTheWayIntoTheZip() {
|
||||
@Test fun aRecordedUnchangedFileGoesInAsItIs() {
|
||||
val folder = tmp.newFolder("2026-10-06-01-steam")
|
||||
// A file the ending recorded as scrubbed still gets the share's final pass: the record
|
||||
// may predate a rule, and a zip is the one way a log leaves the device.
|
||||
// Stands in for a file the ending scrubbed; the share must not pass it through again.
|
||||
File(folder, "session.log").writeText("$secret\n")
|
||||
record(folder, "session.log")
|
||||
assertFalse(zip(folder).getValue("session.log").contains(leaked))
|
||||
assertTrue(zip(folder).getValue("session.log").contains(leaked))
|
||||
}
|
||||
|
||||
@Test fun anythingTheRecordDoesNotVouchForIsScrubbed() {
|
||||
|
||||
@@ -1,107 +0,0 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import java.io.File
|
||||
import java.util.zip.ZipFile
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
/** A shared zip is scrubbed on the way in, whatever the files on disk still hold. */
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [33])
|
||||
class SessionLogShareZipTest {
|
||||
private val app get() = RuntimeEnvironment.getApplication()
|
||||
|
||||
@Test fun everyTextFileInTheZipIsScrubbedAndTheStoresAndToolsLogsComeAlong() {
|
||||
val logs = LinuxRuntime.logDir(app)
|
||||
val session = File(logs, "2026-10-08-01-steam").apply { mkdirs() }
|
||||
// Written raw, as a file from before a rule existed would be.
|
||||
File(session, "session.log").writeText(
|
||||
"fetch https://gog-cdn-fastly.gog.com/token=nva=1791500000~dirs=/x~token=0a1b2c3d4e5f/content-system/v2/store/1/ab/cd/f\n" +
|
||||
"fetch https://epicgames-download1.akamaized.net/Builds/Org/a/ChunksV4/12/ABCD.chunk?__token__=exp=1~hmac=deadbeefcafe\n" +
|
||||
"login refresh_token=abcdef123456 user someone@example.com code=AUTHCODE123\n" +
|
||||
"Authorization: Bearer abc.def.ghi\n" +
|
||||
"kept: EResult 5, app 1086940, steamapps/common/Game\n"
|
||||
)
|
||||
File(logs, "stores").apply { mkdirs() }.resolve("stores-2026-10-08.log").writeText("epic: f_token=zzzzzzzz12 window 32\n")
|
||||
File(logs, SessionPaths.TOOLS_DIR).apply { mkdirs() }.resolve("flatpak-install.log").writeText("== install\nCookie: steamLoginSecure=76561198000000000%7C%7Ceyabc\n")
|
||||
|
||||
val zip = SessionLogShare.zipFolder(app, session)!!
|
||||
assertTrue(zip.path.startsWith(File(app.cacheDir, "share").path))
|
||||
val text = ZipFile(zip).use { z -> z.entries().toList().associate { e -> e.name to z.getInputStream(e).bufferedReader().readText() } }
|
||||
assertTrue(text.keys.containsAll(listOf("2026-10-08-01-steam/session.log", "stores/stores-2026-10-08.log", "tools/flatpak-install.log")))
|
||||
val all = text.values.joinToString("\n")
|
||||
for (secret in listOf("0a1b2c3d4e5f", "deadbeefcafe", "abcdef123456", "someone@example.com", "AUTHCODE123", "abc.def.ghi", "zzzzzzzz12", "eyabc")) {
|
||||
assertFalse("$secret survived", all.contains(secret))
|
||||
}
|
||||
// What makes a log worth reading stays.
|
||||
assertTrue(all.contains("kept: EResult 5, app 1086940, steamapps/common/Game"))
|
||||
assertTrue(all.contains("https://gog-cdn-fastly.gog.com/"))
|
||||
|
||||
SessionLogShare.clear(app)
|
||||
assertFalse(zip.exists())
|
||||
}
|
||||
|
||||
@Test fun theSharePassChangesNothingInACleanLine() {
|
||||
val line = "dxvk: Device 0x5 (Adreno 750) https://github.com/doitsujin/dxvk/releases code 403"
|
||||
assertEquals(line, com.droiddeck.launcher.core.LogRedactor.redactForShare(line))
|
||||
}
|
||||
|
||||
// Folders an earlier build scrubbed and marked under older rules, their copied Steam UI log
|
||||
// still naming the account: one app start (the move out of Download/, then the pass over
|
||||
// older folders) leaves every one scrubbed on disk under the current rules.
|
||||
private fun olderFolder(parent: File, name: String, marker: String = ".scrubbed-2"): File {
|
||||
val dir = File(parent, name).apply { mkdirs() }
|
||||
File(dir, marker).writeText("scrubbed earlier\n")
|
||||
File(dir, SessionArtifacts.SCRUBBED_TREE_MARKER).writeText("rules 2\n")
|
||||
File(dir, "steam").apply { mkdirs() }.resolve("webhelper_js.txt").writeText(
|
||||
"[2026-10-01 20:00:00] SteamUI: INFO: Login: OnLoginStateChange someone.masked@example.com 2 1 0 0\n" +
|
||||
"[2026-10-01 20:00:01] SteamUI: INFO: Login: OnLoginStateChange maskeduser42 2 1 0 0\n" +
|
||||
"[2026-10-01 20:00:02] SteamUI: INFO: Login: OnLoginStateChange 0 1 0 0\n" +
|
||||
"0024:trace:seh:dispatch_exception code=c0000005 flags=0\n"
|
||||
)
|
||||
return dir
|
||||
}
|
||||
|
||||
private fun assertScrubbed(dir: File) {
|
||||
val text = File(dir, "steam/webhelper_js.txt").readText()
|
||||
for (secret in listOf("someone.masked", "example.com", "maskeduser42")) assertFalse("$secret survived in $dir", text.contains(secret))
|
||||
assertTrue(text.contains("Login: OnLoginStateChange <redacted:account> 2 1 0 0"))
|
||||
assertTrue(text.contains("Login: OnLoginStateChange 0 1 0 0"))
|
||||
assertTrue(text.contains("code=c0000005"))
|
||||
val markers = dir.list()!!.filter { it.startsWith(".scrubbed-") && it != SessionArtifacts.SCRUBBED_TREE_MARKER }
|
||||
assertEquals("$dir", listOf(".scrubbed-r${com.droiddeck.launcher.core.LogRedactor.RULES_VERSION}"), markers)
|
||||
assertTrue(File(dir, SessionArtifacts.SCRUBBED_TREE_MARKER).readText()
|
||||
.startsWith("rules ${com.droiddeck.launcher.core.LogRedactor.RULES_VERSION}\n"))
|
||||
}
|
||||
|
||||
@Test fun aFolderMarkedUnderOlderRulesIsScrubbedAgainAtStart() {
|
||||
val dir = olderFolder(LinuxRuntime.logDir(app), "2026-10-01-01-steam")
|
||||
SessionArtifacts.scrubOlder(app)
|
||||
assertScrubbed(dir)
|
||||
}
|
||||
|
||||
@Test fun everyMigratedFolderIsScrubbedUnderTheCurrentRulesInOneStart() {
|
||||
val legacy = LinuxRuntime.legacyLogDir().apply { mkdirs() }
|
||||
val names = (1..9).map { "2026-10-0${it}-01-steam" }
|
||||
names.forEachIndexed { i, name ->
|
||||
// Old markers of every kind an earlier build left, one even claiming the current rules.
|
||||
olderFolder(legacy, name, marker = listOf(".scrubbed-2", ".scrubbed-1", ".scrubbed-r${com.droiddeck.launcher.core.LogRedactor.RULES_VERSION}")[i % 3])
|
||||
}
|
||||
File(legacy, "Saves").apply { mkdirs() }.resolve("keep.txt").writeText("save\n")
|
||||
|
||||
// What MainActivity runs at start.
|
||||
LogMigration.run(app)
|
||||
SessionArtifacts.scrubOlder(app)
|
||||
|
||||
val logs = LinuxRuntime.logDir(app)
|
||||
for (name in names) assertScrubbed(File(logs, name))
|
||||
assertEquals(listOf("Saves"), legacy.list()!!.toList())
|
||||
}
|
||||
}
|
||||
@@ -32,49 +32,15 @@ class WinComponentsSupportTest {
|
||||
step("install_msi", "url" to "$base/ps-x86.msi"), step("install_msi", "url" to "$base/ps-x64.msi"))))
|
||||
}
|
||||
|
||||
@Test fun installerWrappersInstallHere() {
|
||||
// A WiX bundle, a self-extracting cabinet or 7-Zip archive: the packages inside are laid out.
|
||||
assertEquals(Support.READY, support(component("vcredist2022",
|
||||
step("install_exe", "url" to "$base/vcredist2022__VC_redist.x86.exe", "file_name" to "VC_redist.x86.exe"),
|
||||
step("install_exe", "url" to "$base/vcredist2022__VC_redist.x64.exe", "file_name" to "VC_redist.x64.exe"),
|
||||
step("override_dll", "dll" to "vcruntime140", "type" to "native,builtin"))))
|
||||
// .NET Framework: "uninstall Wine Mono", the Windows version, the installer, a registry key.
|
||||
assertEquals(Support.READY, support(component("dotnet40",
|
||||
step("uninstall", "file_name" to "Wine Mono"), step("set_windows", "version" to "win7"),
|
||||
step("install_exe", "url" to "https://download.microsoft.com/x/dotNetFx40_Full_x86_x64.exe", "file_name" to "dotNetFx40_Full_x86_x64.exe"),
|
||||
step("set_windows", "version" to "win10"),
|
||||
step("set_register_key", "key" to "HKLM\\\\Software\\\\Microsoft\\\\NET Framework Setup\\\\NDP\\\\v4\\\\Full", "value" to "Install", "data" to "0001", "type" to "REG_DWORD"),
|
||||
step("override_dll", "dll" to "mscoree", "type" to "native"))))
|
||||
}
|
||||
|
||||
@Test fun nestedCatalogKeysAreRead() {
|
||||
// A few .NET entries keep url and file_name under "environment".
|
||||
val nested = WinComponents.Step("install_exe", JSONObject().put("environment", JSONObject()
|
||||
.put("WINEDLLOVERRIDES", "fusion=b").put("file_name", "ndp48-x86-x64-allos-enu.exe")
|
||||
.put("url", "https://download.visualstudio.microsoft.com/x/ndp48-x86-x64-allos-enu.exe")))
|
||||
assertEquals("ndp48-x86-x64-allos-enu.exe", nested.str("file_name"))
|
||||
assertEquals(Support.READY, support(component("dotnet48", nested)))
|
||||
}
|
||||
|
||||
@Test fun cabinetPicksInstallHere() {
|
||||
assertEquals(Support.READY, support(component("xact",
|
||||
step("download_archive", "url" to "$base/directx_Jun2010_redist.exe", "file_name" to "directx_Jun2010_redist.exe"),
|
||||
step("get_from_cab", "source" to "directx_Jun2010_redist.exe", "file_name" to "*XACT_x86*.cab", "dest" to "temp/XACT_x86/"),
|
||||
step("get_from_cab", "source" to "XACT_x86/*.cab", "file_name" to "xactengine*.dll", "dest" to "win32/"),
|
||||
step("override_dll", "dll" to "xactengine3_7", "type" to "native,builtin"),
|
||||
step("register_dll", "dlls" to ""))))
|
||||
}
|
||||
|
||||
@Test fun setupProgramsStillWait() {
|
||||
// NSIS / InnoSetup installers hold no package to lay out.
|
||||
assertEquals(Support.NEEDS_INSTALLER, support(component("K-Lite",
|
||||
step("install_exe", "url" to "$base/K-Lite.exe", "file_name" to "K-Lite_1960.exe"))))
|
||||
@Test fun otherInstallersStillWait() {
|
||||
assertEquals(Support.NEEDS_INSTALLER, support(component("dotnet48", step("install_exe", "url" to "$base/ndp48.exe"))))
|
||||
// An uninstall step first (wine-mono) is not something done here.
|
||||
assertEquals(Support.NEEDS_INSTALLER, support(component("mono", step("uninstall"),
|
||||
step("install_msi", "url" to "$base/mono.msi"))))
|
||||
assertEquals(Support.NEEDS_INSTALLER, support(component("plain", step("install_msi", "url" to "http://example.com/a.msi"))))
|
||||
}
|
||||
|
||||
@Test fun whatProtonShipsIsNotOffered() {
|
||||
assertEquals(Support.UNSUPPORTED, support(component("gecko", step("install_msi", "url" to "$base/gecko.msi"))))
|
||||
assertEquals(Support.UNSUPPORTED, support(component("mono", step("uninstall"), step("install_msi", "url" to "$base/mono.msi"))))
|
||||
assertEquals(Support.UNSUPPORTED, support(component("mono-10.4.1", step("install_msi", "url" to "$base/mono.msi"))))
|
||||
}
|
||||
}
|
||||
Loaded 100 of 182 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user