Compare commits

...
Author SHA1 Message Date
maxjivi05 dff9e6a640 fix(proot): revalidate cached directory paths before every reuse 2026-11-30 23:22:32 -05:00
maxjivi05 b676448e0a fix(proot): close cached folder handles whose folder was renamed or deleted 2026-11-09 18:28:13 -05:00
maxjivi05 ad24943155 perf(proot): look up files on FUSE libraries relative to held folder handles
Android's FUSE daemon re-resolves every path component of an absolute path,
so each fast-path syscall on the SD card or shared storage paid about 0.35 ms
per folder, and a full walk paid that for every prefix. The fast path now
keeps O_PATH handles to folders under FUSE-backed binds (checked against
/proc/self/fd before each use) and issues *at() calls relative to them.
Renaming a plain file no longer flushes the folder cache.
2026-11-09 18:04:57 -05:00
MaxsTechReview 836340f3a2 fix(session): no endless loading screen after a game exits back to Steam (#2359)
* fix(session): avoid stale relaunch loading overlay

* fix(session): keep the loading screen while the runtime installs
2026-11-09 17:09:27 -05:00
Kurt Himebauch 1b19837fc6 fix(native): a guest's own seccomp filter gets its SIGSYS, so Firefox tabs stop crashing (#2360) 2026-11-09 16:42:38 -05:00
Kurt Himebauch c85b84a964 fix(input): fakeinput no longer aborts programs whose allocator calls a hooked function at startup (#2361)
* fix(input): fakeinput no longer aborts programs whose allocator calls a hooked function at startup

* fix(ctl): screenshot finds display ids that the device name carries inline

* fix(input): fakeinput registers its fork handlers before other threads see its config
2026-11-09 16:41:26 -05:00
MaxsTechReview 75a0230304 fix(input): Auto relative mouse stays off for direct touch without a mouse (#2305)
* fix(input): Auto relative mouse stays off for direct touch without a mouse

* fix(input): re-check relative mouse when an input device changes

* fix(input): reapply relative mouse after agent readiness

* fix(input): only the current session clears the agent-ready hook and readiness resets relative mouse retries
2026-11-09 15:02:12 -05:00
Kurt Himebauch 7c89c14a84 fix(dual-screen): drop the Dashboard notifications page and its notification listener (#2342)
* fix(dual-screen): drop the Dashboard notifications page and its notification listener

* test(session): freeze the clock in the memory-pressure policy harness
2026-11-09 12:48:00 -05:00
Kurt Himebauch b837611efe fix(ctl): a full disk no longer crashes the app when an agent call cannot write its answer (#2325) 2026-11-09 12:33:26 -05:00
Kurt Himebauch bf434b2652 fix(hud): steady frame graph on the bottom screen dashboard (#2345) 2026-11-09 12:30:41 -05:00
GiovanniCarbinatti 35941bb9e7 chore: update README.md (#2311) 2026-11-09 06:45:24 -05:00
MaxsTechReview 96a12465e0 fix(session): stop re-compressing game memory every 30 s when the game reads it straight back (#2312)
* fix(session): stop re-compressing game memory every 30 s when the game reads it straight back

On devices with 13 GB or less, the low-memory page-out skipped its
read-back backoff whenever memory was nearly exhausted. When the game
was actively using what was compressed, it read it straight back, so
the session pushed and re-read gigabytes every 30 seconds, pinning all
cores and freezing the game for 5-10 s each time. The read-back check
now applies on that path too: an effective page-out still repeats every
30 s, an ineffective one backs off as on the normal path.

* zRAM: keep the read-back backoff on the nearly-out-of-memory path

* zRAM: retry a skipped page-out after 30 s when nearly out of memory
2026-11-09 02:08:40 -05:00
Kurt Himebauch 88d6b70881 fix(ctl): reach the agent bridge by broadcast when the shell has no content command (#2321) 2026-11-09 00:00:20 -05:00
MaxsTechReview 29823bb1bf fix(steam): Linux-only tools keep their native platform (#2313)
* fix(steam): reconcile tool dependencies by supported platform

* fix(steam): refresh tool metadata and clear stale GE mappings

* fix(steam): clear any Proton mapping from Linux-only tools

* fix(steam): watch folders the client creates after the helper starts

* Watch each missing directory level as it appears

* Make the watcher level test wait on inotify readiness
2026-11-08 22:22:22 -05:00
MaxsTechReview 92a7124589 fix(gpu): skip system Vulkan pruning when the runtime pack is absent (#2316)
fix: skip pruning system Vulkan runtimes when the runtime pack is not installed
2026-11-08 22:07:39 -05:00
Kurt Himebauch bf95a40e3e fix(ci): post new Discord notice for each PR build (#2314)
Post a fresh signed test-build notice for each new PR commit, retire the
previous notice, and include the latest commit subject.
2026-11-08 21:19:22 -05:00
Kurt Himebauch 1355cb3a2b fix(ci): handle empty commit lookup responses 2026-11-08 21:13:53 -05:00
Kurt Himebauch 51407155fc fix(ci): keep commit lookup failures from blocking notices 2026-11-08 21:12:58 -05:00
Kurt Himebauch b4a953c659 fix(ci): post new Discord notice for each PR build 2026-11-08 21:08:22 -05:00
MaxsTechReview 5e438e9248 fix(gog): owned games the listing leaves out stay owned, and search reaches GOG's catalog (#2296)
* fix(gog): owned games the library listing leaves out stay owned

Since the GOG library is read from account/getFilteredProducts, a game
that listing does not return (one hidden in GOG Galaxy, for example)
dropped out of the library, and with it out of the GOG tab, which shows
owned games and the shelves. 0.5.0 read every owned id from
user/data/games and showed them.

The sync now takes the union of the listing and user/data/games. The
listing still names most games at once, and an owned id it lacks is
fetched like any other.

* fix(gog): the GOG tab's search reaches GOG's catalog

GogStoreCatalog.search was never wired to the backend, so searching the
GOG tab only filtered the owned library and the featured shelves; a game
that is neither could not be found. GogBackend now answers search from
GOG's catalog, like the other stores.

* fix(gog): keep cached owned games when the account list is unavailable
2026-11-08 19:37:20 -05:00
MaxsTechReview 6b110581ac fix(gog): install scripts' support files reach the prefix (#2294)
* fix(gog): install scripts' support files reach the prefix

A goggame-<id>.script can copy files into the prefix with supportData
actions: default INI files, Plugins.txt and other settings that mods such
as one-click editions need. Only setRegistry actions were applied, so
those games started without their configuration and ran as the base game.

droiddeck-store-launch now applies supportData after the registry, once
per script revision: copies from {app} and {supportDir} into {userdocs}
and {localappdata}, matching paths without regard to case. Links are
copied as links, paths outside those folders are refused, and existing
files are replaced only when the action asks for it.

* Keep GOG support data copies inside the game and prefix folders

* Copy linked GOG support sources as links and keep a player's own links
2026-11-08 18:45:53 -05:00
MaxsTechReview 92742f37c1 fix(preload): answer netlink requests sent with write and writev (#2304) 2026-11-08 18:40:57 -05:00
MaxsTechReview ecd916d43f fix(input): show the panel tabs under the controls-below-the-game bar (#2302)
* fix(input): show the panel tabs under the controls-below-the-game bar

* fix(input): take the tab row out of the game, not the controls below it
2026-11-08 18:32:40 -05:00
Kurt Himebauch a7c10e3f51 fix(session): give Steam a session bus so launches stop hanging at the install script (#2303) 2026-11-08 16:53:01 -05:00
MaxsTechReview 1760f008ae fix(desktop): Flatpak and Snap apps get the game GPU setting (#2295)
The session's TU_DEBUG=sysmem is meant for the Steam client and
Chromium-based apps. Flatpak and Snap apps inherited it, so emulators
and other programs installed that way rendered through system memory.

droiddeck-game-env now holds the Chromium check next to game_gpu, and a
small droiddeck-game-gpu wrapper applies both to any program. The
AppImage, Flatpak and Snap launchers use it, so the rule lives in one
place.
2026-11-08 14:39:31 -05:00
MaxsTechReview 3bb279f635 fix(appimage): emulators and other AppImage programs get the game GPU setting (#2288)
The session sets TU_DEBUG=sysmem for the Steam client's interface and hands
games their own value in DROIDDECK_GAME_TU_DEBUG, which droiddeck-game-env
applies to Steam launches (#1188). droiddeck-appimage-run never did, so
emulators and other AppImage programs rendered every pass through system
memory instead of Turnip's per render pass choice.

Apply the game value in droiddeck-appimage-run the same way: an empty
value unsets TU_DEBUG, any other value replaces it. Chromium-based apps,
like the Steam client's own interface, keep the session's setting.
2026-11-08 12:23:30 -05:00
MaxsTechReview 3fef1f3fa1 fix(proton): a Proton picked for a game in Steam is kept (#2284)
fix(proton): a Valve Proton picked for a game in Steam stays on the ARM64 build made from it

Steam lists Valve's own Proton Experimental and Proton 11.0 next to the
DroidDeck tools. They are not runnable here, so a per-game pick of one was
replaced with the default. That used to be Proton Experimental ARM64, so the
pick looked kept; since an installed DroidDeck-Proton became the default, the
game is moved to DroidDeck-Proton instead.

When Steam records one of those tools for a title the sync already knows
(a title it mapped or one with a recorded pick), the title now gets the
DroidDeck tool built from the same Valve depot, stops following the default
and the choice is mirrored into the app's per-game setting. The same applies
to Steam's default. Titles nobody picked anything for still follow the
default, and Valve tools with no ARM64 build still fall back to it.
2026-11-08 12:03:21 -05:00
MaxsTechReview a4f26799ab fix(mesa): Zink on PowerVR shows colour again instead of grayscale (#2287)
Mesa 26.0.8, which the Ubuntu runtime builds, carries the backport of
"zink: create views for samplers lazily", which dropped the depth/stencil
aspect check in init_sampler_view(). On drivers with
needs_zs_shader_swizzle (Imagination) every colour view with a constant-1
alpha, such as RGBX/BGRX textures, then got the red-only depth swizzle
view, so Steam's interface and games showed red as R=G=B.

Carry Icenowy Zheng's upstream fix d55418dae7 (Mesa MR 41923), which
restores the aspect check. It applies on top of patch 0004.
2026-11-08 11:48:11 -05:00
MaxsTechReview 08a6a3cba8 ci: run approved fork PR compile jobs on the disposable fork runner (#2246)
* ci: run approved fork PR compile jobs on the disposable fork runner

* ci: ignore fork runner heartbeats from the future

* ci: target the fork runner by its own label

* Read the fork runner heartbeat from a public gist

* Fall back to an anonymous read of the fork runner heartbeat
2026-11-08 11:40:12 -05:00
MaxsTechReview 005fec2125 chore: pin gamescope to the DroidDeck-Components p23 release (#2285) 2026-11-08 11:37:54 -05:00
MaxsTechReview 2e70b8ed73 fix(gamescope): taps reach dialogs and windows away from the screen origin (#2280) 2026-11-08 10:44:00 -05:00
MaxsTechReview 74c0f2127a fix(proot): lay out ARM64 programs like the kernel so large reservations fit (#2279) 2026-11-08 10:43:57 -05:00
102 changed files with 2668 additions and 648 deletions

No files matched your search

+23 -1
View File
@@ -17,7 +17,7 @@ jobs:
runs-on: ubuntu-24.04
timeout-minutes: 2
outputs:
labels: ${{ steps.runner.outputs.labels || '"ubuntu-24.04"' }}
labels: ${{ steps.runner.outputs.labels || steps.fork.outputs.labels || '"ubuntu-24.04"' }}
steps:
- name: Pick the compile runner
id: runner
@@ -36,3 +36,25 @@ jobs:
fi
echo "labels=$labels" >> "$GITHUB_OUTPUT"
echo "Compile runner: \`$labels\`" >> "$GITHUB_STEP_SUMMARY"
- name: Pick the fork runner
id: fork
if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository
continue-on-error: true
env:
GH_TOKEN: ${{ github.token }}
run: |
set -euo pipefail
labels='"ubuntu-24.04"'
gist=https://api.github.com/gists/0c7ed7ad6d6493de84f5123689c64ae6
body=$(curl -fsS --max-time 15 -H "Authorization: Bearer $GH_TOKEN" "$gist" 2>/dev/null || curl -fsS --max-time 15 "$gist" 2>/dev/null || echo '{}')
IDLE_AT=$(jq -r 'select(.owner.login == "maxjivi05") | .files["idle-at"].content // "0"' <<< "$body" 2>/dev/null || echo 0)
echo "Heartbeat: ${IDLE_AT:-none}"
age=-1
if [[ "${IDLE_AT:-0}" =~ ^[0-9]+$ ]] && [ "${IDLE_AT:-0}" -gt 0 ]; then
age=$(( $(date +%s) - IDLE_AT ))
fi
if [ "$age" -ge 0 ] && [ "$age" -lt 180 ]; then
labels='"droiddeck-fork"'
fi
echo "labels=$labels" >> "$GITHUB_OUTPUT"
echo "Compile runner: \`$labels\`" >> "$GITHUB_STEP_SUMMARY"
+5 -4
View File
@@ -10,7 +10,7 @@ DroidDeck brings the SteamOS experience to Android: Steam Gaming Mode, full Linu
<p align="center"><b>100% open source. No ads. No telemetry. No proprietary components. No source withheld.</b></p>
<p align="center">
<a href="https://github.com/Droid-Deck/DroidDeck/releases/download/0.6.9/DroidDeck-0.6.9.apk"><img src="https://img.shields.io/badge/Download-DroidDeck%200.6.9%20APK-3DDC84?style=for-the-badge&logo=android&logoColor=white" alt="Download DroidDeck 0.6.9"></a>
<a href="https://github.com/Droid-Deck/DroidDeck/releases/download/0.7.0/DroidDeck-0.7.0.apk"><img src="https://img.shields.io/badge/Download-DroidDeck%200.7.0%20APK-3DDC84?style=for-the-badge&logo=android&logoColor=white" alt="Download DroidDeck 0.7.0"></a>
<a href="https://discord.gg/JRGAvawjsm"><img src="https://img.shields.io/badge/Discord-Join%20us-5865F2?style=for-the-badge&logo=discord&logoColor=white" alt="Join the DroidDeck Discord"></a>
</p>
@@ -36,9 +36,9 @@ DroidDeck brings the SteamOS experience to Android: Steam Gaming Mode, full Linu
## Install
1. Android 9 or newer on Adreno 730 or newer, or any 8xx. Adreno 6xx is experimental. Mali, Xclipse, PowerVR and Adreno 710 are unsupported. No root needed.
1. Android 9 or newer on Adreno 730 or newer, or any 8xx. Adreno 6xx, Mali, Xclipse and PowerVR are experimental. Adreno 710 is currently unsupported. No root needed.
2. About 3 GB free for the runtime, plus 1.1 GB for the desktop and emulators.
3. Install the [APK](https://github.com/Droid-Deck/DroidDeck/releases/download/0.6.9/DroidDeck-0.6.9.apk), install the Linux runtime, press **Play** and sign in to Steam.
3. Install the [APK](https://github.com/Droid-Deck/DroidDeck/releases/download/0.7.0/DroidDeck-0.7.0.apk), install the Linux runtime, press **Play** and sign in to Steam.
4. On Android 14 and newer, turn on **Disable child process restrictions** in Developer options. On Android 12 and 13, Steam's first launch shows a **Fix it for me** button that walks you through it.
Smart glasses setup is in the [support matrix](docs/smart-glasses-support.md). Release notes are in [docs/releases](docs/releases).
@@ -79,7 +79,8 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V
- droiddeck-ntsync follows the [Linux](https://github.com/torvalds/linux) ntsync semantics in `Documentation/userspace-api/ntsync.rst` (GPL-2.0).
- The proot fast path orders bindings like [PRoot](https://github.com/proot-me/proot)'s `path/binding.c` (GPL-2.0-or-later).
- DiRT 3 and DiRT Showdown keep their telemetry socket the way RoccoC's DiRTTelemetryErrorFix (MIT) does, based on the fix by Carsten Gottschling.
- Games use [Mesa](https://gitlab.freedesktop.org/mesa/mesa) Turnip's per render pass memory choice. The Steam client keeps `TU_DEBUG=sysmem`.
- Zink on PowerVR keeps colour textures in colour with Icenowy Zheng's upstream [Mesa](https://gitlab.freedesktop.org/mesa/mesa) fix d55418dae7 (MIT), carried as a runtime patch.
- Games and AppImage, Flatpak and Snap programs such as emulators use [Mesa](https://gitlab.freedesktop.org/mesa/mesa) Turnip's per render pass memory choice. The Steam client and Chromium-based apps keep `TU_DEBUG=sysmem`.
- Black Ops III and Dark Souls Remastered start without [umu-protonfixes](https://github.com/Open-Wine-Components/umu-protonfixes) (BSD-2-Clause), whose `311210.py` and `570940.py` fail under ARM64 Proton.
- [ReSkate](https://github.com/Dingo-Shenanigans/ReSkate) (GPL-3.0) by Dingo Shenanigans uses the launch option from its README and D3D12 feature level 12_1.
- The arm64 client's sign in was checked by reading Steam's saved token with the `ConnectCache` format from [deadlock-api-ingest](https://github.com/deadlock-api/deadlock-api-ingest).
+8 -8
View File
@@ -91,14 +91,6 @@
</intent-filter>
<meta-data android:name="android.accessibilityservice" android:resource="@xml/home_button_service" />
</service>
<service android:name=".session.BottomNotificationListener"
android:label="@string/bottom_notifications_listener"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE"
android:exported="true">
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>
<receiver android:name=".core.ShortcutsListingReceiver" android:exported="false"
android:process=":shortcuts_sync">
<intent-filter>
@@ -352,6 +344,14 @@
<action android:name="android.content.action.DOCUMENTS_PROVIDER" />
</intent-filter>
</provider>
<receiver
android:name=".agent.AgentCallReceiver"
android:exported="true"
android:permission="android.permission.DUMP">
<intent-filter>
<action android:name="${applicationId}.AGENT_CALL" />
</intent-filter>
</receiver>
<provider
android:name=".agent.AgentBridgeProvider"
android:authorities="${applicationId}.agent"
+27 -16
View File
@@ -30,6 +30,7 @@
#include <linux/uinput.h>
#include <poll.h>
#include <pthread.h>
#include <sched.h>
#include <signal.h>
#include <stdarg.h>
#include <stdbool.h>
@@ -208,23 +209,33 @@ struct FakeConfig {
bool uinput_enabled;
};
// The first allocation here can start the host program's own allocator, which may call a hooked
// function (mimalloc probes NUMA nodes with access()) and land back in config(). A guarded static
// would throw a recursive-init error there, so the fields are filled without allocating, and a
// reentry on the initializing thread gets them while other threads wait for the fork handlers.
static FakeConfig &config() {
static FakeConfig *cfg = [] {
auto *c = new FakeConfig();
const char *dir = getenv("FAKE_EVDEV_DIR");
c->hook_dir = dir ? dir : "/data/data/com.termux/files/home/fake-input";
c->udev_data_dir = getenv("FAKE_UDEV_DATA_DIR");
c->vibration_enabled =
getenv("FAKE_EVDEV_VIBRATION") && atoi(getenv("FAKE_EVDEV_VIBRATION"));
const char *identity = getenv("FAKE_EVDEV_IDENTITY");
c->xbox360_identity = identity && !strcmp(identity, "xbox360");
c->uinput_enabled = getenv("FAKE_EVDEV_UINPUT") && atoi(getenv("FAKE_EVDEV_UINPUT"));
pthread_atfork(controller_fork_prepare, controller_fork_parent,
controller_fork_child);
Logger::init();
return c;
}();
return *cfg;
static FakeConfig cfg;
static std::atomic<int> state{0};
static __thread bool initializing __attribute__((tls_model("initial-exec")));
if (state.load(std::memory_order_acquire) == 2 || initializing) return cfg;
int expected = 0;
if (!state.compare_exchange_strong(expected, 1, std::memory_order_acq_rel)) {
while (state.load(std::memory_order_acquire) != 2) sched_yield();
return cfg;
}
initializing = true;
const char *dir = getenv("FAKE_EVDEV_DIR");
cfg.hook_dir = dir ? dir : "/data/data/com.termux/files/home/fake-input";
cfg.udev_data_dir = getenv("FAKE_UDEV_DATA_DIR");
cfg.vibration_enabled = getenv("FAKE_EVDEV_VIBRATION") && atoi(getenv("FAKE_EVDEV_VIBRATION"));
const char *identity = getenv("FAKE_EVDEV_IDENTITY");
cfg.xbox360_identity = identity && !strcmp(identity, "xbox360");
cfg.uinput_enabled = getenv("FAKE_EVDEV_UINPUT") && atoi(getenv("FAKE_EVDEV_UINPUT"));
pthread_atfork(controller_fork_prepare, controller_fork_parent, controller_fork_child);
Logger::init();
state.store(2, std::memory_order_release);
initializing = false;
return cfg;
}
static std::recursive_mutex &controller_mutex() {
@@ -121,6 +121,7 @@ import com.droiddeck.launcher.session.SessionArtifacts
import com.droiddeck.launcher.session.SessionLogShare
import com.droiddeck.launcher.session.SessionPhase
import com.droiddeck.launcher.session.SessionPaths
import com.droiddeck.launcher.session.SessionLoadingDecision
import com.droiddeck.launcher.wayland.HdrSupport
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
@@ -286,6 +287,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private var directHoldBehavior by mutableStateOf(com.droiddeck.launcher.input.TouchGestureConfig.MOUSE_BEHAVIOR_CLICK)
private var relativeMouseMode by mutableIntStateOf(0)
@Volatile private var appliedRelativeMouseMode: Int? = null
private val agentReadyListener: () -> Unit = { relativeMouseRetries = 0; requestRelativeMouse() }
private val appTextFocus get() = wowChat.request != null
private val wowChat by lazy { com.droiddeck.launcher.ui.WowChat(this, ::sendWowChat, ::cancelWowChat, ::readGameField) }
private var wowChatBottom: SecondScreenPresentation? = null
@@ -636,6 +638,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
padBridge?.syncConnectedControllers()
refreshControls()
updatePointerCapture()
requestRelativeMouse()
updateHandCamera()
refreshSecondScreenDisplays()
}
@@ -651,12 +654,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (::padMouse.isInitialized) padMouse.reset()
refreshControls()
updatePointerCapture()
requestRelativeMouse()
updateHandCamera()
refreshSecondScreenDisplays()
}
override fun onInputDeviceChanged(deviceId: Int) {
joyConVr?.refresh()
refreshControls()
requestRelativeMouse()
refreshSecondScreenDisplays()
}
}
@@ -665,6 +670,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
AgentGuest.readyListener = agentReadyListener
if (com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.isRemoving() ||
com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.isMaintaining()) {
runtimeRemovalBlocked = true
@@ -1960,6 +1966,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
val nextRoutedTouchMode = effectiveTouchMode()
if (routedTouchMode != nextRoutedTouchMode) gestureTouchStreamGate.reset()
routedTouchMode = nextRoutedTouchMode
requestRelativeMouse()
frameGen = FrameGen.mode(this)
fexPreset = SessionPrefs.fexPreset(this)
suspendPolicy = SessionPrefs.suspendPolicy(this, SessionState.mode)
@@ -2429,6 +2436,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun watchSession() {
val handler = Handler(Looper.getMainLooper())
var ticks = 0
val loadingStartedAt = SystemClock.elapsedRealtime()
val poll = object : Runnable {
override fun run() {
if (!watching) return
@@ -2441,6 +2449,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
finish()
return
}
if (loading.visible && !loading.ended && !SessionState.running && !installingRuntime &&
SessionLoadingDecision.shouldReturnToLauncher(
loadingStartedAt, SystemClock.elapsedRealtime(), SessionState.running, SessionState.phase)) {
finish()
return
}
if (loading.visible && !loading.ended) {
if (!installingRuntime) loading.update(this@SessionActivity, SessionState.logFile)
if (ticks++ % 2 == 0) loading.tick()
@@ -2465,8 +2479,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
val hint = sessionExitHint(status)
runOnUiThread {
if (isFinishing || isDestroyed) return@runOnUiThread
if (status == 0) SessionState.relaunch?.let { next ->
SessionState.relaunch = null
if (status == 0) SessionState.takeRelaunch()?.let { next ->
next.putExtra(EXTRA_RETURN_HOME, intent.getBooleanExtra(EXTRA_RETURN_HOME, false))
next.putExtra(EXTRA_LINK_TASK, intent.getIntExtra(EXTRA_LINK_TASK, -1))
setIntent(next)
@@ -2981,7 +2994,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
private fun applyRelativeMouse() {
val mode = desiredRelativeMouseMode
val wanted = desiredRelativeMouseMode
val touchpadRoute = com.droiddeck.launcher.input.TouchRouter.decide(com.droiddeck.launcher.input.TouchRouter.Snapshot(
uiBlocking = false,
mode = routedTouchMode,
scrollLayer = false,
steamSession = SessionState.mode == SessionService.MODE_STEAM,
steamDesktopUi = SessionState.steamUi == "desktop",
)) == com.droiddeck.launcher.input.TouchRouter.Route.TOUCHPAD
val mode = com.droiddeck.launcher.input.TouchGestureConfig.gamescopeRelativeMouse(wanted, mouseAttached(), touchpadRoute)
if (appliedRelativeMouseMode == mode) return
val request = org.json.JSONObject()
.put("kind", "exec")
@@ -2997,7 +3018,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
Log.w(TAG, "gamescope did not take relative mouse $mode: ${result.exceptionOrNull() ?: answer}")
if (relativeMouseRetries++ < RELATIVE_MOUSE_MAX_RETRIES) uiHandler.postDelayed({ requestRelativeMouse() }, 2_000)
}
if (desiredRelativeMouseMode != mode) requestRelativeMouse()
if (desiredRelativeMouseMode != wanted) requestRelativeMouse()
}
private fun refreshGestureConfig() {
@@ -3445,50 +3466,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun bottomPages(): List<BottomPage> = sessionBottomPages(BottomPageActions(
takeScreenshot = ::captureScreenshot,
fps = { if (::hud.isInitialized) hud.liveFps else null },
openSettings = ::openSettingsBelow,
runningGame = { gestureGame },
))
private fun openSettingsBelow(intent: android.content.Intent, done: () -> Boolean) {
val presentation = secondScreenPresentation
if (presentation == null) {
if (!bottomOutputActive) return
listOf(intent, android.content.Intent(android.provider.Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS)).any {
runCatching { startActivity(android.content.Intent(it)) }
.onFailure { e -> Log.w(TAG, "could not open ${it.action}", e) }
.isSuccess
}
return
}
val options = android.app.ActivityOptions.makeBasic().setLaunchDisplayId(presentation.display.displayId)
val opened = listOf(intent, android.content.Intent(android.provider.Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS)).any {
runCatching { startActivity(android.content.Intent(it).addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK), options.toBundle()) }
.onFailure { e -> Log.w(TAG, "could not open ${it.action} on display ${presentation.display.displayId}", e) }
.isSuccess
}
if (!opened) return
presentation.hide()
var checks = 0
fun showAgain() {
try {
presentation.show()
} catch (e: Exception) {
Log.w(TAG, "could not show the dashboard again", e)
if (secondScreenPresentation === presentation) closeSecondScreen(reset = true)
}
}
uiHandler.postDelayed(object : Runnable {
override fun run() {
if (secondScreenPresentation !== presentation || presentation.isShowing) return
if (done()) {
showAgain()
return
}
if (++checks < SETTINGS_WATCH_CHECKS) uiHandler.postDelayed(this, SETTINGS_WATCH_MS) else showAgain()
}
}, SETTINGS_WATCH_MS)
}
private fun captureScreenshot(onDone: (Boolean) -> Unit) {
val source = if (glassesOutputActive) glassesScreen?.surfaceView else if (bottomOutputActive) bottomGame?.surfaceView
else if (::surfaceView.isInitialized) surfaceView else null
@@ -3609,7 +3589,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
val width = sessionRoot.width
val height = sessionRoot.height
val wanted = controlsBelowWanted()
val gameHeight = if (wanted) com.droiddeck.launcher.session.SessionDisplay.unfoldedGameHeight(width, height)
val tabRow = unfoldedColumn?.getChildAt(0)?.height?.let {
it - (com.droiddeck.launcher.ui.BAR_HEIGHT.value * resources.displayMetrics.density + 0.5f).toInt()
} ?: 0
val gameHeight = if (wanted) com.droiddeck.launcher.session.SessionDisplay.unfoldedGameHeight(width, height, tabRow)
else FrameLayout.LayoutParams.MATCH_PARENT
val params = surfaceView.layoutParams as FrameLayout.LayoutParams
if (params.height != gameHeight) {
@@ -3635,8 +3618,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
panel = OnScreenControls(this, padBridge, dock).also { it.updateLayout(primaryInputLayout) }
val column = android.widget.LinearLayout(this).apply {
orientation = android.widget.LinearLayout.VERTICAL
addView(unfoldedBar(), android.widget.LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.MATCH_PARENT,
(com.droiddeck.launcher.ui.BAR_HEIGHT.value * resources.displayMetrics.density + 0.5f).toInt()))
addView(unfoldedBar().apply {
addOnLayoutChangeListener { _, _, top, _, bottom, _, oldTop, _, oldBottom ->
if (bottom - top != oldBottom - oldTop) post { applyUnfoldedControls() }
}
}, android.widget.LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.MATCH_PARENT,
android.widget.LinearLayout.LayoutParams.WRAP_CONTENT))
addView(panel, android.widget.LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f))
}
sessionRoot.addView(column, sessionRoot.indexOfChild(surfaceView) + 1)
@@ -3847,6 +3834,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (next == SessionPrefs.TOUCH_OFF) cursorVisible = false
gestureTouchStreamGate.reset()
routedTouchMode = next
requestRelativeMouse()
if (directTouchCursorHidden()) cursorVisible = false
}
@@ -5353,6 +5341,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
override fun onDestroy() {
if (AgentGuest.readyListener === agentReadyListener) AgentGuest.readyListener = null
com.droiddeck.launcher.input.HomeButtonShortcuts.detach(this)
relativeMouseRequests.shutdownNow()
backQamInput.cancel()
@@ -5463,8 +5452,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private const val TEXT_FIELD_TAP_MS = 1_000L
private const val PAUSED_FRAME_MAX_EDGE = 1920f
private const val PAUSED_FRAME_REDRAW_MS = 150L
private const val SETTINGS_WATCH_MS = 1_000L
private const val SETTINGS_WATCH_CHECKS = 600
private const val BOTTOM_RECOVERY_MS = 1_000L
private const val BOTTOM_RECOVERY_TRIES = 3
private const val TAG = "SessionActivity"
@@ -0,0 +1,41 @@
package com.droiddeck.launcher.agent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Bundle
import java.io.File
/**
* The agent bridge for devices whose shell has no `content` command: the same calls as
* [AgentBridgeProvider], answered in a file under the app's external files folder.
*/
class AgentCallReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val method = intent.getStringExtra("method") ?: return
val id = intent.getStringExtra("id")?.takeIf { it.matches(Regex("[A-Za-z0-9_-]{1,64}")) } ?: return
val arg = intent.getStringExtra("arg")
val request = intent.getStringExtra(AgentBridgeProvider.EXTRA_REQUEST)
val pending = goAsync()
Thread({
val json = try {
val extras = Bundle().apply { putString(AgentBridgeProvider.EXTRA_REQUEST, request) }
context.contentResolver.call("${context.packageName}.agent", method, arg, extras)
?.getString(AgentBridgeProvider.RESULT_JSON) ?: """{"ok":false,"error":{"code":"NO_RESPONSE","message":"no response"}}"""
} catch (e: Exception) {
org.json.JSONObject().put("ok", false)
.put("error", org.json.JSONObject().put("code", "COMMAND_FAILED").put("message", e.message ?: e.javaClass.simpleName)).toString()
}
try {
val dir = File(context.getExternalFilesDir(null), "agent-calls").apply { mkdirs() }
File(dir, "$id.json.part").writeText(json)
File(dir, "$id.json.part").renameTo(File(dir, "$id.json"))
} catch (e: Exception) {
android.util.Log.w("AgentCallReceiver", "could not write the answer to $method: ${e.message}")
} finally {
pending.finish()
}
}, "agent-call-$id").start()
}
}
@@ -33,6 +33,7 @@ object AgentGuest {
var keyboardDismissals by mutableIntStateOf(0)
private set
@Volatile private var keyboardRoute = false
@Volatile var readyListener: (() -> Unit)? = null
@Volatile private var routeDir: File? = null
private const val TAG = "AgentGuest"
private const val POLL_MS = 50L
@@ -59,6 +60,7 @@ object AgentGuest {
when (path) {
"hello.json" -> readJson(File(dir, path))?.let {
SessionEvents.record("agent.ready", mapOf("pid" to it.optInt("pid"), "focus" to it.optBoolean("focus")))
readyListener?.invoke()
}
"focus.json" -> readJson(File(dir, path))?.let(::recordFocus)
"keyboard.json" -> readJson(File(dir, path))?.let { recordKeyboard(this, it) }
@@ -191,6 +191,7 @@ public final class SystemVulkanDriver {
/** Collect abandoned stages, and obsolete versions once older guests can no longer load them. */
public static synchronized void pruneUnused(Context context, boolean guestsStopped) throws IOException {
if (!AddonPack.POWERVR.installed(context)) return;
pruneUnused(runtimeDirectory(context), guestsStopped);
}
@@ -6,6 +6,7 @@ import kotlin.math.roundToInt
internal class FrameStats {
private val graph = FloatArray(GRAPH_FRAMES)
private var graphHead = 0
private var graphFrames = 0L
private var lastPresentNs = 0L
private var lastFpsUpdateNs = 0L
private var framesSinceUpdate = 0
@@ -38,6 +39,7 @@ internal class FrameStats {
if (lastPresentNs != 0L) {
graph[graphHead] = frametimeNs / 1e6f
graphHead = (graphHead + 1) % GRAPH_FRAMES
graphFrames++
}
val elapsed = timeNs - lastFpsUpdateNs
if (elapsed >= FPS_PERIOD_NS) {
@@ -68,6 +70,7 @@ internal class FrameStats {
fun reset() {
graph.fill(0f)
graphHead = 0
graphFrames = 0L
lastPresentNs = 0L
lastFpsUpdateNs = 0L
framesSinceUpdate = 0
@@ -86,8 +89,9 @@ internal class FrameStats {
fun frametimeMs(): Float = 1000f / maxOf(fps, 1f)
@Synchronized
fun graph(out: FloatArray) {
fun graph(out: FloatArray): Long {
for (i in 0 until GRAPH_FRAMES) out[i] = graph[(graphHead + i) % GRAPH_FRAMES]
return graphFrames
}
@Synchronized
@@ -213,6 +213,9 @@ data class TouchGestureConfig(
return if (value == MOUSE_BEHAVIOR_CLICK) MOUSE_BEHAVIOR_CLICK else MOUSE_BEHAVIOR_HOLD
}
fun gamescopeRelativeMouse(mode: Int, mouseAttached: Boolean, touchpad: Boolean): Int =
if (mode == RELATIVE_MOUSE_AUTO && !mouseAttached && !touchpad) RELATIVE_MOUSE_OFF else mode
private fun normalizeRelativeMouseMode(mode: Int): Int {
return if (mode in RELATIVE_MOUSE_AUTO..RELATIVE_MOUSE_OFF) mode else RELATIVE_MOUSE_AUTO
}
@@ -1,60 +0,0 @@
package com.droiddeck.launcher.session
import android.app.Notification
import android.content.Context
import android.service.notification.NotificationListenerService
import android.service.notification.StatusBarNotification
import androidx.compose.runtime.mutableStateListOf
import androidx.core.app.NotificationManagerCompat
data class BottomNotification(val key: String, val app: String, val title: String, val text: String, val postedAt: Long)
object BottomNotifications {
val items = mutableStateListOf<BottomNotification>()
fun granted(context: Context): Boolean =
context.packageName in NotificationManagerCompat.getEnabledListenerPackages(context)
internal fun keep(own: String, pkg: String, ongoing: Boolean, groupSummary: Boolean, title: String, text: String): Boolean =
pkg != own && !ongoing && !groupSummary && (title.isNotBlank() || text.isNotBlank())
internal fun add(list: MutableList<BottomNotification>, item: BottomNotification) {
list.removeAll { it.key == item.key }
list.add(0, item)
while (list.size > MAX_ITEMS) list.removeAt(list.lastIndex)
}
fun clear() = items.clear()
internal fun post(context: Context, sbn: StatusBarNotification) {
val n = sbn.notification ?: return
val extras = n.extras
val title = extras?.getCharSequence(Notification.EXTRA_TITLE)?.toString().orEmpty()
val text = (extras?.getCharSequence(Notification.EXTRA_BIG_TEXT) ?: extras?.getCharSequence(Notification.EXTRA_TEXT))?.toString().orEmpty()
if (!keep(context.packageName, sbn.packageName, sbn.isOngoing, (n.flags and Notification.FLAG_GROUP_SUMMARY) != 0, title, text)) return
val app = runCatching {
val pm = context.packageManager
pm.getApplicationLabel(pm.getApplicationInfo(sbn.packageName, 0)).toString()
}.getOrDefault(sbn.packageName)
add(items, BottomNotification(sbn.key, app, title, text, sbn.postTime))
}
internal fun remove(key: String) {
items.removeAll { it.key == key }
}
private const val MAX_ITEMS = 30
}
class BottomNotificationListener : NotificationListenerService() {
override fun onListenerConnected() {
BottomNotifications.clear()
runCatching { activeNotifications }.getOrNull()?.sortedBy { it.postTime }?.forEach { BottomNotifications.post(this, it) }
}
override fun onNotificationPosted(sbn: StatusBarNotification) = BottomNotifications.post(this, sbn)
override fun onNotificationRemoved(sbn: StatusBarNotification) = BottomNotifications.remove(sbn.key)
override fun onListenerDisconnected() = BottomNotifications.clear()
}
@@ -69,8 +69,8 @@ object SessionDisplay {
const val UNFOLDED_MIN_DP = 600
fun unfoldedGameHeight(width: Int, height: Int): Int =
minOf(width * 9 / 16, (height * UNFOLDED_MAX_GAME_SHARE).toInt()) and 1.inv()
fun unfoldedGameHeight(width: Int, height: Int, tabRow: Int = 0): Int =
(minOf(width * 9 / 16, (height * UNFOLDED_MAX_GAME_SHARE).toInt()) - tabRow.coerceAtLeast(0)).coerceAtLeast(0) and 1.inv()
fun unfoldedControlsWanted(
enabled: Boolean,
@@ -14,6 +14,7 @@ object SessionEvents {
SessionPaths.take()
val dir = SessionPaths.beginOrCurrent(context, label ?: SessionPaths.label(mode, null))
synchronized(SessionState) {
SessionState.clearRelaunch()
SessionState.phase = SessionPhase.PREPARING
SessionState.mode = mode
SessionState.sessionId = dir.name
@@ -40,6 +40,7 @@ object SessionFiles {
WinComponents.publish(context)
val files = arrayOf(
"usr/local/bin/droiddeck-game-env" to "usr/local/bin/droiddeck-game-env",
"usr/local/bin/droiddeck-game-gpu" to "usr/local/bin/droiddeck-game-gpu",
"usr/local/bin/droiddeck-diagnostic-inventory" to "usr/local/bin/droiddeck-diagnostic-inventory",
"usr/local/bin/droiddeck-wincomponents" to "usr/local/bin/droiddeck-wincomponents",
"usr/local/bin/droiddeck-msi-install" to "usr/local/bin/droiddeck-msi-install",
@@ -0,0 +1,8 @@
package com.droiddeck.launcher.session
internal object SessionLoadingDecision {
const val TIMEOUT_MS = 10_000L
fun shouldReturnToLauncher(startedAt: Long, now: Long, running: Boolean, phase: SessionPhase): Boolean =
!running && phase in setOf(SessionPhase.IDLE, SessionPhase.FAILED) && now - startedAt >= TIMEOUT_MS
}
@@ -1697,8 +1697,8 @@ class SessionService : Service() {
.putExtra(EXTRA_STEAM_UI, ui)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
if (url.isNotEmpty()) next.putExtra(EXTRA_STEAM_URL, url)
SessionState.relaunch = next
android.os.Handler(android.os.Looper.getMainLooper()).post { stopSession(0) }
SessionState.queueRelaunch(next)
android.os.Handler(android.os.Looper.getMainLooper()).post { stopSession(0, relaunch = true) }
}
}
watcher.startWatching()
@@ -2013,7 +2013,7 @@ class SessionService : Service() {
}
}
private fun stopSession(status: Int, gen: Int? = null) {
private fun stopSession(status: Int, gen: Int? = null, relaunch: Boolean = false) {
if (gen != null && gen != sessionGen) {
Log.i(TAG, "ignoring a stop from session $gen; session $sessionGen is current")
return
@@ -2024,6 +2024,7 @@ class SessionService : Service() {
cancelQueuedSteamGame()
gameExitWatchToken++
if (!SessionState.running) return
if (relaunch) SessionState.confirmRelaunchStop()
SessionEvents.record("guest.exited", mapOf("status" to status))
SessionEvents.transition(SessionPhase.STOPPING, "session.stopping", mapOf("status" to status))
SessionState.running = false
@@ -73,7 +73,44 @@ object SessionState {
@Volatile
var steamClientArch: String? = null
var steamVr by mutableStateOf(false)
@Volatile
var relaunch: android.content.Intent? = null
@Volatile
private var relaunchSessionId: String? = null
@Volatile
private var relaunchStopRequested = false
fun queueRelaunch(intent: android.content.Intent) {
synchronized(this) {
relaunch = intent
relaunchSessionId = sessionId
relaunchStopRequested = false
}
}
fun confirmRelaunchStop() {
synchronized(this) {
relaunchStopRequested = relaunch != null && relaunchSessionId == sessionId
}
}
fun takeRelaunch(): android.content.Intent? = synchronized(this) {
val next = relaunch
val valid = relaunchStopRequested && relaunchSessionId == sessionId
relaunch = null
relaunchSessionId = null
relaunchStopRequested = false
next.takeIf { valid }
}
fun clearRelaunch() {
synchronized(this) {
relaunch = null
relaunchSessionId = null
relaunchStopRequested = false
}
}
@JvmStatic var hdr = false
@Volatile private var deckPadValue = false
@@ -64,6 +64,8 @@ object GogBackend : StoreBackend {
}, "gog-sync").start()
}
override fun search(context: Context, query: String): List<CatalogItem> = GogStoreCatalog.search(query)
override fun loadShelves(context: Context, force: Boolean) {
val app = context.applicationContext
GogStoreCatalog.cachedFeatured(app)?.let { StoresState.post { StoresState.shelves[store] = it } }
@@ -58,16 +58,17 @@ object GogLibrary {
val token = GogAuth.validToken(app) ?: return SyncResult.NotLoggedIn
onStatus(app.getString(R.string.stores_sync_game_list))
val listing = ownedListing(token)
val account = ownedIds(token)
val listed: List<GogGame> = listing?.games
?: ownedIds(token)?.map { GogGame(it, "", "", "", "", "", 1, null, "", "") }
?: account?.map { GogGame(it, "", "", "", "", "", 1, null, "", "") }
?: return SyncResult.Failed(app.getString(R.string.stores_sync_gog_unreachable))
val named = listing != null
StoresState.logLine(if (named) "GOG: listing ${listed.size} games" else "GOG: listing unreadable, ${listed.size} owned ids")
val ownedSet = listing?.owned ?: listed.mapTo(HashSet()) { it.gameId }
val cachedList = cached(app)
val cachedIds = cachedList.mapTo(HashSet()) { it.gameId }
val ownedSet = ownedSet(listing?.owned ?: listed.mapTo(HashSet()) { it.gameId }, account, cachedIds)
StoresState.logLine(if (named) "GOG: listing ${listed.size} games, ${ownedSet.size} owned ids" else "GOG: listing unreadable, ${listed.size} owned ids")
val stale = System.currentTimeMillis() - p.getLong(LAST_SYNC_KEY, 0L) >= THROTTLE_MS
val heavy = force || cachedList.isEmpty() || stale
val cachedIds = cachedList.mapTo(HashSet()) { it.gameId }
val skipped = java.util.Collections.newSetFromMap(java.util.concurrent.ConcurrentHashMap<String, Boolean>())
skipped.addAll(p.getStringSet(SKIPPED_KEY, emptySet()).orEmpty())
val idsToFetch = if (heavy) ownedSet.toList() else ownedSet.filter { it !in cachedIds && it !in skipped }
@@ -133,6 +134,9 @@ object GogLibrary {
return all.ifEmpty { null }?.let { Listing(it, owned) }
}
fun ownedSet(listed: Set<String>, account: List<String>?, cached: Set<String> = emptySet()): Set<String> =
if (account == null) listed + cached else listed + account
private fun ownedIds(token: String): List<String>? {
val json = StoreNet.get(OWNED_URL, bearer = token, userAgent = GogAuth.GALAXY_UA) ?: return null
val owned = runCatching { JSONObject(json).optJSONArray("owned") }.getOrNull() ?: return null
@@ -1,116 +0,0 @@
package com.droiddeck.launcher.ui
import android.content.Intent
import android.provider.Settings
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.session.BottomNotifications
import kotlinx.coroutines.delay
internal fun notificationAccessIntent(context: android.content.Context): Intent =
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
Intent(Settings.ACTION_NOTIFICATION_LISTENER_DETAIL_SETTINGS).putExtra(
Settings.EXTRA_NOTIFICATION_LISTENER_COMPONENT_NAME,
android.content.ComponentName(context, com.droiddeck.launcher.session.BottomNotificationListener::class.java).flattenToString(),
)
} else Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS)
@Composable
fun BottomNotificationsPage(openSettings: ((Intent, () -> Boolean) -> Unit)?) {
val context = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
var granted by remember { mutableStateOf(BottomNotifications.granted(context)) }
LaunchedEffect(Unit) {
while (true) {
granted = BottomNotifications.granted(context)
delay(2_000L)
}
}
if (!granted) {
Column(Modifier.fillMaxSize().padding(24.dp), horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically)) {
Text(stringResource(R.string.bottom_notifications_why), fontSize = 15.sp, color = colors.onBackground, textAlign = TextAlign.Center)
BottomPillButton(stringResource(R.string.bottom_notifications_allow), "bottom-notifications-allow") {
val intent = notificationAccessIntent(context)
if (openSettings != null) openSettings(intent) { BottomNotifications.granted(context) }
else runCatching { context.startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) }
}
}
return
}
val shown = BottomNotifications.items
if (shown.isEmpty()) {
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
Text(stringResource(R.string.bottom_notifications_none), fontSize = 15.sp, color = colors.onSurfaceVariant)
}
return
}
val timeFormat = remember { android.text.format.DateFormat.getTimeFormat(context) }
Column(Modifier.fillMaxSize(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
Text(stringResource(R.string.bottom_notifications_count, shown.size), fontSize = 13.sp, color = colors.onSurfaceVariant,
modifier = Modifier.weight(1f))
BottomPillButton(stringResource(R.string.bottom_notifications_clear), "bottom-notifications-clear") { BottomNotifications.clear() }
}
LazyColumn(Modifier.weight(1f).fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
items(shown.toList(), key = { it.key }) { n ->
Column(Modifier.fillMaxWidth().clip(RoundedCornerShape(14.dp)).background(pal.surface).padding(horizontal = 14.dp, vertical = 10.dp),
verticalArrangement = Arrangement.spacedBy(4.dp)) {
Row(verticalAlignment = Alignment.CenterVertically) {
Text(n.app, fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = pal.signal, maxLines = 1,
overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
Text(timeFormat.format(java.util.Date(n.postedAt)), fontSize = 12.sp, color = colors.onSurfaceVariant)
}
if (n.title.isNotBlank()) Text(n.title, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground,
maxLines = 1, overflow = TextOverflow.Ellipsis)
if (n.text.isNotBlank()) Text(n.text, fontSize = 14.sp, color = colors.onBackground, maxLines = 4, overflow = TextOverflow.Ellipsis)
}
}
}
}
}
@Composable
internal fun BottomPillButton(label: String, tag: String, onClick: () -> Unit) {
val pal = LocalPalette.current
Box(
Modifier.height(40.dp).clip(RoundedCornerShape(20.dp)).background(pal.signal.copy(alpha = 0.16f))
.clickable(role = Role.Button, onClick = onClick).testTag(tag).padding(horizontal = 16.dp),
contentAlignment = Alignment.Center,
) {
Text(label, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = pal.signal, maxLines = 1)
}
}
@@ -1,17 +1,31 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Download
import androidx.compose.material.icons.outlined.Forum
import androidx.compose.material.icons.outlined.Speed
import androidx.compose.material.icons.outlined.Notifications
import androidx.compose.material.icons.outlined.PhotoLibrary
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.R
class BottomPageActions(
val takeScreenshot: ((onDone: (Boolean) -> Unit) -> Unit)? = null,
val fps: () -> Float? = { null },
val openSettings: ((intent: android.content.Intent, done: () -> Boolean) -> Unit)? = null,
val runningGame: () -> String? = { null },
)
@@ -20,7 +34,18 @@ internal const val BOTTOM_PAGE_TELEMETRY = "telemetry"
fun sessionBottomPages(actions: BottomPageActions): List<BottomPage> = listOf(
BottomPage(BOTTOM_PAGE_TELEMETRY, R.string.bottom_page_telemetry, Icons.Outlined.Speed) { BottomTelemetryPage(actions.fps, actions.runningGame) },
BottomPage("downloads", R.string.bottom_page_downloads, Icons.Outlined.Download) { BottomDownloadsPage() },
BottomPage("notifications", R.string.bottom_page_notifications, Icons.Outlined.Notifications) { BottomNotificationsPage(actions.openSettings) },
BottomPage("screenshots", R.string.bottom_page_screenshots, Icons.Outlined.PhotoLibrary) { BottomScreenshotsPage(actions.takeScreenshot) },
BottomPage("chat", R.string.bottom_page_chat, Icons.Outlined.Forum) { BottomChatPage() },
)
@Composable
internal fun BottomPillButton(label: String, tag: String, onClick: () -> Unit) {
val pal = LocalPalette.current
Box(
Modifier.height(40.dp).clip(RoundedCornerShape(20.dp)).background(pal.signal.copy(alpha = 0.16f))
.clickable(role = Role.Button, onClick = onClick).testTag(tag).padding(horizontal = 16.dp),
contentAlignment = Alignment.Center,
) {
Text(label, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = pal.signal, maxLines = 1)
}
}
@@ -304,7 +304,8 @@ fun BottomTelemetryPage(fps: () -> Float?, runningGame: () -> String? = { null }
val now = System.nanoTime()
val live = frames.live
val stats = frames.stats
val graph = FloatArray(FrameStats.GRAPH_FRAMES).also { if (live) stats.graph(it) }
val graph = FloatArray(FrameStats.GRAPH_FRAMES)
val graphEnd = if (live) stats.graph(graph) else 0L
val hz = (frames.refreshMilliHz + 499) / 1000
val data = HudData(
fps = fpsNow, avgFps = if (live) stats.averageFps() else null, lows = if (live) stats.lows(now) else FrameStats.Lows.EMPTY,
@@ -317,6 +318,7 @@ fun BottomTelemetryPage(fps: () -> Float?, runningGame: () -> String? = { null }
title = title, cover = cover, played = playedSeconds?.let(::playedText), clock = clock,
fpsHistory = fpsHistory.snapshot(), cpuHistory = cpuHistory.snapshot(), gpuHistory = gpuHistory.snapshot(),
historySeconds = maxOf(fpsHistory.spanSeconds(), cpuHistory.spanSeconds(), gpuHistory.spanSeconds()),
graphEnd = graphEnd,
coreGroups = coreGroups, gameCores = gameCores, fahrenheit = tempDisplay.fahrenheit,
tempColor = { sensor, c ->
thresholds[sensor]?.let { Color(HudMetrics.tempColor(c.toFloat(), it, tempDisplay, TEMP_PLAIN)) } ?: Color(TEMP_PLAIN)
@@ -98,6 +98,7 @@ internal class HudData(
val tempColor: (HudMetrics.TempSensor, Int) -> Color,
val redC: (HudMetrics.TempSensor) -> Int?,
val historySeconds: Int = 0,
val graphEnd: Long = 0L,
) {
val frametimeMs: Float? get() = fps?.takeIf { it > 0f }?.let { 1000f / it }
val hz: Int get() = if (refreshHz > 0) refreshHz else 60
@@ -268,18 +269,26 @@ private fun lowsText(d: HudData, size: TextUnit, accent: Color, deep: Boolean =
private val GRAPH_MIN_GAP = 3.dp
@Composable
private fun Graph(values: List<Float>, lo: Float, hi: Float, color: Color, modifier: Modifier) {
private fun Graph(values: List<Float>, lo: Float, hi: Float, color: Color, modifier: Modifier, end: Long = 0L) {
Canvas(modifier) {
if (values.size < 2 || hi <= lo) return@Canvas
val stride = ceil(GRAPH_MIN_GAP.toPx() * (values.size - 1) / size.width).toInt().coerceAtLeast(1)
val points = if (stride == 1) values else values.chunked(stride) { it.average().toFloat() }
if (points.size < 2) return@Canvas
// Buckets start at multiples of stride counted from the first sample ever drawn, so a sample keeps
// its bucket as the window scrolls; counted from the window's start, every new frame re-paired them.
val skip = Math.floorMod(values.size.toLong() - end, stride.toLong()).toInt()
val path = Path()
points.forEachIndexed { i, v ->
val x = i / (points.size - 1f) * size.width
val y = size.height - ((v - lo) / (hi - lo)).coerceIn(0f, 1f) * size.height
if (i == 0) path.moveTo(x, y) else path.lineTo(x, y)
var drawn = 0
var start = skip
while (start < values.size) {
val stop = minOf(start + stride, values.size)
var sum = 0f
for (i in start until stop) sum += values[i]
val x = (start + stop - 1) / 2f / (values.size - 1f) * size.width
val y = size.height - ((sum / (stop - start) - lo) / (hi - lo)).coerceIn(0f, 1f) * size.height
if (drawn++ == 0) path.moveTo(x, y) else path.lineTo(x, y)
start = stop
}
if (drawn < 2) return@Canvas
drawPath(path, color.copy(alpha = 0.22f), style = Stroke(width = 6.dp.toPx(), cap = StrokeCap.Round, join = StrokeJoin.Round))
drawPath(path, color, style = Stroke(width = 2.2f.dp.toPx(), cap = StrokeCap.Round, join = StrokeJoin.Round))
}
@@ -287,7 +296,7 @@ private fun Graph(values: List<Float>, lo: Float, hi: Float, color: Color, modif
@Composable
private fun FrameGraph(d: HudData, accent: Color, height: Dp) {
Graph(d.graph.toList(), 0f, FrameStats.GRAPH_MAX_MS, lerp(accent, Color.White, 0.3f), Modifier.fillMaxWidth().height(height))
Graph(d.graph.toList(), 0f, FrameStats.GRAPH_MAX_MS, lerp(accent, Color.White, 0.3f), Modifier.fillMaxWidth().height(height), d.graphEnd)
}
@Composable
@@ -589,7 +598,7 @@ private fun ColumnScope.Pacing(d: HudData, accent: Color) {
drawLine(color, Offset(0f, y), Offset(size.width, y), 1.dp.toPx(), pathEffect = dash)
}
}
Graph(d.graph.toList(), 0f, FrameStats.GRAPH_MAX_MS, graphColor, Modifier.fillMaxSize())
Graph(d.graph.toList(), 0f, FrameStats.GRAPH_MAX_MS, graphColor, Modifier.fillMaxSize(), d.graphEnd)
for ((ms, color) in listOf(target to HudInk.dim, target * 2 to HudInk.amber)) {
Small("%.1f ms · %d fps".format(ms, (1000f / ms).roundToInt()), 11.sp, color,
Modifier.align(Alignment.TopEnd).offset(y = maxHeight * (1f - ms / FrameStats.GRAPH_MAX_MS) - 17.dp))
-7
View File
@@ -1873,13 +1873,6 @@
<string name="bottom_downloads_shader">جارٍ تنزيل ذاكرة المظلِّلات المؤقتة</string>
<string name="bottom_downloads_paused">متوقف مؤقتًا</string>
<string name="bottom_downloads_queued">بانتظار البدء</string>
<string name="bottom_page_notifications">الإشعارات</string>
<string name="bottom_notifications_listener">الشاشة السفلية لـ DroidDeck</string>
<string name="bottom_notifications_why">اعرض الرسائل والإشعارات الأخرى هنا أثناء اللعب. تبقى على هذه الشاشة فقط ولا تُحفظ. يطلب Android الإذن مرة واحدة: تُفتح صفحة الوصول إلى الإشعارات على هذه الشاشة؛ فعِّل DroidDeck هناك وستعود هذه الصفحة تلقائيًا.</string>
<string name="bottom_notifications_allow">السماح بالوصول إلى الإشعارات</string>
<string name="bottom_notifications_none">لا توجد إشعارات.</string>
<string name="bottom_notifications_count">الإشعارات: %1$d</string>
<string name="bottom_notifications_clear">مسح</string>
<string name="bottom_page_screenshots">لقطات الشاشة</string>
<string name="stats_fps_needs_hud">يتطلب FPS تشغيل واجهة الأداء</string>
<string name="stats_speed">السرعة</string>
@@ -1865,13 +1865,6 @@
<string name="bottom_downloads_shader">Descargando caché de shaders</string>
<string name="bottom_downloads_paused">En pausa</string>
<string name="bottom_downloads_queued">Esperando para empezar</string>
<string name="bottom_page_notifications">Notificaciones</string>
<string name="bottom_notifications_listener">DroidDeck – pantalla inferior</string>
<string name="bottom_notifications_why">Muestra aquí los mensajes y otras notificaciones mientras juegas. Solo permanecen en esta pantalla y no se guardan. Android lo pregunta una vez: su página de acceso a notificaciones se abre en esta pantalla; activa DroidDeck ahí y esta página volverá sola.</string>
<string name="bottom_notifications_allow">Permitir acceso a notificaciones</string>
<string name="bottom_notifications_none">No hay notificaciones.</string>
<string name="bottom_notifications_count">%1$d notificaciones</string>
<string name="bottom_notifications_clear">Borrar</string>
<string name="bottom_page_screenshots">Capturas de pantalla</string>
<string name="stats_fps_needs_hud">Los FPS requieren el HUD activado</string>
<string name="stats_speed">Velocidad</string>
-7
View File
@@ -1777,13 +1777,6 @@
<string name="bottom_downloads_shader">Изтегляне на кеша на шейдърите</string>
<string name="bottom_downloads_paused">На пауза</string>
<string name="bottom_downloads_queued">Изчаква стартиране</string>
<string name="bottom_page_notifications">Известия</string>
<string name="bottom_notifications_listener">Долен екран на DroidDeck</string>
<string name="bottom_notifications_why">Показвайте тук съобщения и други известия, докато играете. Те остават само на този екран и не се запазват. Android пита веднъж: страницата за достъп до известията се отваря на този екран; включете DroidDeck там и тази страница ще се върне сама.</string>
<string name="bottom_notifications_allow">Разрешаване на достъпа до известията</string>
<string name="bottom_notifications_none">Няма известия.</string>
<string name="bottom_notifications_count">Известия: %1$d</string>
<string name="bottom_notifications_clear">Изчисти</string>
<string name="bottom_page_screenshots">Екранни снимки</string>
<string name="stats_fps_needs_hud">За FPS трябва HUD да е включен</string>
<string name="stats_speed">Скорост</string>
-7
View File
@@ -1825,13 +1825,6 @@
<string name="bottom_downloads_shader">Stahování mezipaměti shaderů</string>
<string name="bottom_downloads_paused">Pozastaveno</string>
<string name="bottom_downloads_queued">Čeká na spuštění</string>
<string name="bottom_page_notifications">Oznámení</string>
<string name="bottom_notifications_listener">Spodní obrazovka DroidDeck</string>
<string name="bottom_notifications_why">Zobrazujte zde zprávy a další oznámení během hraní. Zůstávají jen na této obrazovce a neukládají se. Android se zeptá jednou: na této obrazovce se otevře jeho stránka přístupu k oznámením; zapněte tam DroidDeck a tato stránka se sama vrátí.</string>
<string name="bottom_notifications_allow">Povolit přístup k oznámením</string>
<string name="bottom_notifications_none">Žádná oznámení.</string>
<string name="bottom_notifications_count">Oznámení: %1$d</string>
<string name="bottom_notifications_clear">Vymazat</string>
<string name="bottom_page_screenshots">Snímky obrazovky</string>
<string name="stats_fps_needs_hud">FPS vyžaduje zapnutý HUD</string>
<string name="stats_speed">Rychlost</string>
-7
View File
@@ -1777,13 +1777,6 @@
<string name="bottom_downloads_shader">Downloader shader-cache</string>
<string name="bottom_downloads_paused">På pause</string>
<string name="bottom_downloads_queued">Venter på at starte</string>
<string name="bottom_page_notifications">Notifikationer</string>
<string name="bottom_notifications_listener">DroidDecks nederste skærm</string>
<string name="bottom_notifications_why">Vis beskeder og andre notifikationer her, mens du spiller. De bliver kun på denne skærm og gemmes ikke. Android spørger én gang: siden for notifikationsadgang åbnes på denne skærm; slå DroidDeck til der, så vender denne side selv tilbage.</string>
<string name="bottom_notifications_allow">Tillad notifikationsadgang</string>
<string name="bottom_notifications_none">Ingen notifikationer.</string>
<string name="bottom_notifications_count">%1$d notifikationer</string>
<string name="bottom_notifications_clear">Ryd</string>
<string name="bottom_page_screenshots">Skærmbilleder</string>
<string name="stats_fps_needs_hud">FPS kræver, at HUD er slået til</string>
<string name="stats_speed">Hastighed</string>
-7
View File
@@ -1769,13 +1769,6 @@
<string name="bottom_downloads_shader">Shader-Cache wird heruntergeladen</string>
<string name="bottom_downloads_paused">Pausiert</string>
<string name="bottom_downloads_queued">Wartet auf Start</string>
<string name="bottom_page_notifications">Benachrichtigungen</string>
<string name="bottom_notifications_listener">DroidDeck – unterer Bildschirm</string>
<string name="bottom_notifications_why">Zeigt Nachrichten und andere Benachrichtigungen hier an, während du spielst. Sie bleiben nur auf diesem Bildschirm und werden nicht gespeichert. Android fragt einmal: Die Seite für den Benachrichtigungszugriff öffnet sich auf diesem Bildschirm; aktiviere dort DroidDeck, dann kehrt diese Seite von selbst zurück.</string>
<string name="bottom_notifications_allow">Benachrichtigungszugriff erlauben</string>
<string name="bottom_notifications_none">Keine Benachrichtigungen.</string>
<string name="bottom_notifications_count">%1$d Benachrichtigungen</string>
<string name="bottom_notifications_clear">Löschen</string>
<string name="bottom_page_screenshots">Screenshots</string>
<string name="stats_fps_needs_hud">FPS benötigt das aktive HUD</string>
<string name="stats_speed">Geschwindigkeit</string>
-7
View File
@@ -1777,13 +1777,6 @@
<string name="bottom_downloads_shader">Λήψη cache shader</string>
<string name="bottom_downloads_paused">Σε παύση</string>
<string name="bottom_downloads_queued">Αναμονή για έναρξη</string>
<string name="bottom_page_notifications">Ειδοποιήσεις</string>
<string name="bottom_notifications_listener">DroidDeck – κάτω οθόνη</string>
<string name="bottom_notifications_why">Εμφάνιση μηνυμάτων και άλλων ειδοποιήσεων εδώ ενώ παίζετε. Παραμένουν μόνο σε αυτή την οθόνη και δεν αποθηκεύονται. Το Android ρωτά μία φορά: η σελίδα πρόσβασης ειδοποιήσεων ανοίγει σε αυτή την οθόνη· ενεργοποιήστε εκεί το DroidDeck και αυτή η σελίδα επιστρέφει μόνη της.</string>
<string name="bottom_notifications_allow">Αποδοχή πρόσβασης ειδοποιήσεων</string>
<string name="bottom_notifications_none">Δεν υπάρχουν ειδοποιήσεις.</string>
<string name="bottom_notifications_count">%1$d ειδοποιήσεις</string>
<string name="bottom_notifications_clear">Απαλοιφή</string>
<string name="bottom_page_screenshots">Στιγμιότυπα οθόνης</string>
<string name="stats_fps_needs_hud">Τα FPS απαιτούν ενεργό HUD</string>
<string name="stats_speed">Ταχύτητα</string>
-7
View File
@@ -1801,13 +1801,6 @@
<string name="bottom_downloads_shader">Descargando caché de shaders</string>
<string name="bottom_downloads_paused">En pausa</string>
<string name="bottom_downloads_queued">Esperando para empezar</string>
<string name="bottom_page_notifications">Notificaciones</string>
<string name="bottom_notifications_listener">DroidDeck – pantalla inferior</string>
<string name="bottom_notifications_why">Muestra aquí los mensajes y otras notificaciones mientras juegas. Solo permanecen en esta pantalla y no se guardan. Android lo pregunta una vez: su página de acceso a notificaciones se abre en esta pantalla; activa DroidDeck ahí y esta página volverá sola.</string>
<string name="bottom_notifications_allow">Permitir acceso a notificaciones</string>
<string name="bottom_notifications_none">No hay notificaciones.</string>
<string name="bottom_notifications_count">%1$d notificaciones</string>
<string name="bottom_notifications_clear">Borrar</string>
<string name="bottom_page_screenshots">Capturas de pantalla</string>
<string name="stats_fps_needs_hud">Los FPS requieren el HUD activado</string>
<string name="stats_speed">Velocidad</string>
-7
View File
@@ -1777,13 +1777,6 @@
<string name="bottom_downloads_shader">Ladataan sävytinvälimuistia</string>
<string name="bottom_downloads_paused">Keskeytetty</string>
<string name="bottom_downloads_queued">Odottaa alkamista</string>
<string name="bottom_page_notifications">Ilmoitukset</string>
<string name="bottom_notifications_listener">DroidDeckin alanäyttö</string>
<string name="bottom_notifications_why">Näytä viestit ja muut ilmoitukset täällä pelatessasi. Ne näkyvät vain tällä näytöllä, eikä niitä tallenneta. Android kysyy kerran: sen ilmoitusten käyttöoikeussivu avautuu tälle näytölle; kytke DroidDeck siellä päälle, niin tämä sivu palaa itsestään.</string>
<string name="bottom_notifications_allow">Salli ilmoitusten käyttö</string>
<string name="bottom_notifications_none">Ei ilmoituksia.</string>
<string name="bottom_notifications_count">Ilmoituksia: %1$d</string>
<string name="bottom_notifications_clear">Tyhjennä</string>
<string name="bottom_page_screenshots">Kuvakaappaukset</string>
<string name="stats_fps_needs_hud">FPS vaatii HUD:n päälle</string>
<string name="stats_speed">Nopeus</string>
-7
View File
@@ -1801,13 +1801,6 @@
<string name="bottom_downloads_shader">Téléchargement du cache de shaders</string>
<string name="bottom_downloads_paused">En pause</string>
<string name="bottom_downloads_queued">En attente de démarrage</string>
<string name="bottom_page_notifications">Notifications</string>
<string name="bottom_notifications_listener">Écran inférieur DroidDeck</string>
<string name="bottom_notifications_why">Affichez ici les messages et autres notifications pendant que vous jouez. Ils restent uniquement sur cet écran et ne sont pas enregistrés. Android ne le demande qu\'une fois : sa page d\'accès aux notifications s\'ouvre sur cet écran ; activez-y DroidDeck et cette page reviendra d\'elle-même.</string>
<string name="bottom_notifications_allow">Autoriser l\'accès aux notifications</string>
<string name="bottom_notifications_none">Aucune notification.</string>
<string name="bottom_notifications_count">%1$d notifications</string>
<string name="bottom_notifications_clear">Effacer</string>
<string name="bottom_page_screenshots">Captures d\'écran</string>
<string name="stats_fps_needs_hud">Les FPS nécessitent d\'activer le HUD</string>
<string name="stats_speed">Vitesse</string>
-7
View File
@@ -1777,13 +1777,6 @@
<string name="bottom_downloads_shader">शेडर कैश डाउनलोड हो रहा है</string>
<string name="bottom_downloads_paused">रुका हुआ</string>
<string name="bottom_downloads_queued">शुरू होने का इंतज़ार</string>
<string name="bottom_page_notifications">नोटिफ़िकेशन</string>
<string name="bottom_notifications_listener">DroidDeck नीचे की स्क्रीन</string>
<string name="bottom_notifications_why">खेलते समय मैसेज और अन्य नोटिफ़िकेशन यहां दिखाएं। वे सिर्फ़ इसी स्क्रीन पर रहते हैं और सेव नहीं होते। Android एक बार पूछता है: उसका नोटिफ़िकेशन ऐक्सेस पेज इसी स्क्रीन पर खुलता है; वहां DroidDeck चालू करें और यह पेज अपने-आप वापस आ जाएगा।</string>
<string name="bottom_notifications_allow">नोटिफ़िकेशन ऐक्सेस की अनुमति दें</string>
<string name="bottom_notifications_none">कोई नोटिफ़िकेशन नहीं।</string>
<string name="bottom_notifications_count">%1$d नोटिफ़िकेशन</string>
<string name="bottom_notifications_clear">साफ़ करें</string>
<string name="bottom_page_screenshots">स्क्रीनशॉट</string>
<string name="stats_fps_needs_hud">FPS के लिए HUD चालू होना चाहिए</string>
<string name="stats_speed">स्पीड</string>
-7
View File
@@ -1777,13 +1777,6 @@
<string name="bottom_downloads_shader">Shader-gyorsítótár letöltése</string>
<string name="bottom_downloads_paused">Szüneteltetve</string>
<string name="bottom_downloads_queued">Indításra vár</string>
<string name="bottom_page_notifications">Értesítések</string>
<string name="bottom_notifications_listener">DroidDeck alsó képernyő</string>
<string name="bottom_notifications_why">Itt jelenítheti meg az üzeneteket és más értesítéseket játék közben. Csak ezen a képernyőn láthatók, és nem kerülnek mentésre. Az Android egyszer kérdez rá: az értesítési hozzáférés oldala ezen a képernyőn nyílik meg; kapcsolja be ott a DroidDecket, és ez az oldal magától visszatér.</string>
<string name="bottom_notifications_allow">Értesítési hozzáférés engedélyezése</string>
<string name="bottom_notifications_none">Nincsenek értesítések.</string>
<string name="bottom_notifications_count">%1$d értesítés</string>
<string name="bottom_notifications_clear">Törlés</string>
<string name="bottom_page_screenshots">Képernyőképek</string>
<string name="stats_fps_needs_hud">Az FPS-hez be kell kapcsolni a HUD-ot</string>
<string name="stats_speed">Sebesség</string>
-7
View File
@@ -1753,13 +1753,6 @@
<string name="bottom_downloads_shader">Mengunduh cache shader</string>
<string name="bottom_downloads_paused">Dijeda</string>
<string name="bottom_downloads_queued">Menunggu dimulai</string>
<string name="bottom_page_notifications">Notifikasi</string>
<string name="bottom_notifications_listener">Layar bawah DroidDeck</string>
<string name="bottom_notifications_why">Tampilkan pesan dan notifikasi lain di sini saat Anda bermain. Notifikasi hanya muncul di layar ini dan tidak disimpan. Android hanya meminta sekali: halaman akses notifikasinya terbuka di layar ini; aktifkan DroidDeck di sana dan halaman ini akan kembali dengan sendirinya.</string>
<string name="bottom_notifications_allow">Izinkan akses notifikasi</string>
<string name="bottom_notifications_none">Tidak ada notifikasi.</string>
<string name="bottom_notifications_count">%1$d notifikasi</string>
<string name="bottom_notifications_clear">Hapus</string>
<string name="bottom_page_screenshots">Tangkapan layar</string>
<string name="stats_fps_needs_hud">FPS memerlukan HUD aktif</string>
<string name="stats_speed">Kecepatan</string>
-7
View File
@@ -1793,13 +1793,6 @@
<string name="bottom_downloads_shader">Download della cache degli shader</string>
<string name="bottom_downloads_paused">In pausa</string>
<string name="bottom_downloads_queued">In attesa di avvio</string>
<string name="bottom_page_notifications">Notifiche</string>
<string name="bottom_notifications_listener">Schermo inferiore DroidDeck</string>
<string name="bottom_notifications_why">Mostra qui messaggi e altre notifiche mentre giochi. Restano solo su questo schermo e non vengono salvate. Android lo chiede una sola volta: la sua pagina di accesso alle notifiche si apre su questo schermo; attiva DroidDeck lì e questa pagina torna da sola.</string>
<string name="bottom_notifications_allow">Consenti accesso alle notifiche</string>
<string name="bottom_notifications_none">Nessuna notifica.</string>
<string name="bottom_notifications_count">%1$d notifiche</string>
<string name="bottom_notifications_clear">Cancella</string>
<string name="bottom_page_screenshots">Screenshot</string>
<string name="stats_fps_needs_hud">Gli FPS richiedono l\'HUD attivo</string>
<string name="stats_speed">Velocità</string>
-7
View File
@@ -1753,13 +1753,6 @@
<string name="bottom_downloads_shader">シェーダーキャッシュをダウンロード中</string>
<string name="bottom_downloads_paused">一時停止中</string>
<string name="bottom_downloads_queued">開始待ち</string>
<string name="bottom_page_notifications">通知</string>
<string name="bottom_notifications_listener">DroidDeck下部画面</string>
<string name="bottom_notifications_why">プレイ中、メッセージなどの通知をここに表示します。通知はこの画面にのみ表示され、保存されません。Androidによる確認は一度だけです。この画面に通知へのアクセスのページが開くので、そこでDroidDeckをオンにすると、このページに自動的に戻ります。</string>
<string name="bottom_notifications_allow">通知へのアクセスを許可</string>
<string name="bottom_notifications_none">通知はありません。</string>
<string name="bottom_notifications_count">%1$d件の通知</string>
<string name="bottom_notifications_clear">クリア</string>
<string name="bottom_page_screenshots">スクリーンショット</string>
<string name="stats_fps_needs_hud">FPSの表示にはHUDをオンにする必要があります</string>
<string name="stats_speed">速度</string>
-7
View File
@@ -1753,13 +1753,6 @@
<string name="bottom_downloads_shader">셰이더 캐시 다운로드 중</string>
<string name="bottom_downloads_paused">일시 중지됨</string>
<string name="bottom_downloads_queued">시작 대기 중</string>
<string name="bottom_page_notifications">알림</string>
<string name="bottom_notifications_listener">DroidDeck 하단 화면</string>
<string name="bottom_notifications_why">플레이하는 동안 메시지와 기타 알림을 여기에 표시합니다. 알림은 이 화면에만 표시되며 저장되지 않습니다. Android에서 한 번만 묻습니다. 이 화면에 알림 접근 권한 페이지가 열리면 DroidDeck을 켜세요. 그러면 이 페이지로 자동으로 돌아옵니다.</string>
<string name="bottom_notifications_allow">알림 접근 허용</string>
<string name="bottom_notifications_none">알림이 없습니다.</string>
<string name="bottom_notifications_count">알림 %1$d개</string>
<string name="bottom_notifications_clear">지우기</string>
<string name="bottom_page_screenshots">스크린샷</string>
<string name="stats_fps_needs_hud">FPS를 보려면 HUD를 켜야 합니다</string>
<string name="stats_speed">속도</string>
-7
View File
@@ -1753,13 +1753,6 @@
<string name="bottom_downloads_shader">Memuat turun cache shader</string>
<string name="bottom_downloads_paused">Dijeda</string>
<string name="bottom_downloads_queued">Menunggu untuk bermula</string>
<string name="bottom_page_notifications">Pemberitahuan</string>
<string name="bottom_notifications_listener">Skrin bawah DroidDeck</string>
<string name="bottom_notifications_why">Paparkan mesej dan pemberitahuan lain di sini semasa anda bermain. Ia hanya kekal pada skrin ini dan tidak disimpan. Android bertanya sekali sahaja: halaman akses pemberitahuannya dibuka pada skrin ini; hidupkan DroidDeck di sana dan halaman ini akan kembali dengan sendirinya.</string>
<string name="bottom_notifications_allow">Benarkan akses pemberitahuan</string>
<string name="bottom_notifications_none">Tiada pemberitahuan.</string>
<string name="bottom_notifications_count">%1$d pemberitahuan</string>
<string name="bottom_notifications_clear">Kosongkan</string>
<string name="bottom_page_screenshots">Tangkapan skrin</string>
<string name="stats_fps_needs_hud">FPS memerlukan HUD dihidupkan</string>
<string name="stats_speed">Kelajuan</string>
-7
View File
@@ -1777,13 +1777,6 @@
<string name="bottom_downloads_shader">Laster ned shaderbuffer</string>
<string name="bottom_downloads_paused">Pauset</string>
<string name="bottom_downloads_queued">Venter på å starte</string>
<string name="bottom_page_notifications">Varslinger</string>
<string name="bottom_notifications_listener">DroidDeck nedre skjerm</string>
<string name="bottom_notifications_why">Vis meldinger og andre varslinger her mens du spiller. De vises bare på denne skjermen og lagres ikke. Android spør én gang: siden for varseltilgang åpnes på denne skjermen; slå på DroidDeck der, så kommer denne siden tilbake av seg selv.</string>
<string name="bottom_notifications_allow">Tillat varseltilgang</string>
<string name="bottom_notifications_none">Ingen varslinger.</string>
<string name="bottom_notifications_count">%1$d varslinger</string>
<string name="bottom_notifications_clear">Fjern</string>
<string name="bottom_page_screenshots">Skjermbilder</string>
<string name="stats_fps_needs_hud">FPS krever at HUD-en er på</string>
<string name="stats_speed">Fart</string>
-7
View File
@@ -1777,13 +1777,6 @@
<string name="bottom_downloads_shader">Shadercache downloaden</string>
<string name="bottom_downloads_paused">Gepauzeerd</string>
<string name="bottom_downloads_queued">Wacht om te starten</string>
<string name="bottom_page_notifications">Meldingen</string>
<string name="bottom_notifications_listener">DroidDeck onderste scherm</string>
<string name="bottom_notifications_why">Toon berichten en andere meldingen hier terwijl je speelt. Ze blijven alleen op dit scherm en worden niet opgeslagen. Android vraagt dit één keer: de pagina voor meldingstoegang opent op dit scherm; zet DroidDeck daar aan en deze pagina komt vanzelf terug.</string>
<string name="bottom_notifications_allow">Meldingstoegang toestaan</string>
<string name="bottom_notifications_none">Geen meldingen.</string>
<string name="bottom_notifications_count">%1$d meldingen</string>
<string name="bottom_notifications_clear">Wissen</string>
<string name="bottom_page_screenshots">Screenshots</string>
<string name="stats_fps_needs_hud">Voor FPS moet de HUD aan staan</string>
<string name="stats_speed">Snelheid</string>
-7
View File
@@ -1825,13 +1825,6 @@
<string name="bottom_downloads_shader">Pobieranie pamięci podręcznej shaderów</string>
<string name="bottom_downloads_paused">Wstrzymano</string>
<string name="bottom_downloads_queued">Oczekuje na rozpoczęcie</string>
<string name="bottom_page_notifications">Powiadomienia</string>
<string name="bottom_notifications_listener">Dolny ekran DroidDeck</string>
<string name="bottom_notifications_why">Wyświetlaj tu wiadomości i inne powiadomienia podczas gry. Pozostają tylko na tym ekranie i nie są zapisywane. Android zapyta raz: na tym ekranie otworzy się jego strona dostępu do powiadomień; włącz tam DroidDeck, a ta strona wróci sama.</string>
<string name="bottom_notifications_allow">Zezwól na dostęp do powiadomień</string>
<string name="bottom_notifications_none">Brak powiadomień.</string>
<string name="bottom_notifications_count">Powiadomienia: %1$d</string>
<string name="bottom_notifications_clear">Wyczyść</string>
<string name="bottom_page_screenshots">Zrzuty ekranu</string>
<string name="stats_fps_needs_hud">FPS wymaga włączonego HUD</string>
<string name="stats_speed">Prędkość</string>
@@ -1793,13 +1793,6 @@
<string name="bottom_downloads_shader">A transferir a cache de shaders</string>
<string name="bottom_downloads_paused">Em pausa</string>
<string name="bottom_downloads_queued">A aguardar início</string>
<string name="bottom_page_notifications">Notificações</string>
<string name="bottom_notifications_listener">Ecrã inferior do DroidDeck</string>
<string name="bottom_notifications_why">Mostre aqui mensagens e outras notificações enquanto joga. Ficam apenas neste ecrã e não são guardadas. O Android pergunta uma vez: a página de acesso às notificações abre neste ecrã; ative lá o DroidDeck e esta página volta automaticamente.</string>
<string name="bottom_notifications_allow">Permitir acesso às notificações</string>
<string name="bottom_notifications_none">Sem notificações.</string>
<string name="bottom_notifications_count">%1$d notificações</string>
<string name="bottom_notifications_clear">Limpar</string>
<string name="bottom_page_screenshots">Capturas de ecrã</string>
<string name="stats_fps_needs_hud">O FPS requer o HUD ativado</string>
<string name="stats_speed">Velocidade</string>
-7
View File
@@ -1793,13 +1793,6 @@
<string name="bottom_downloads_shader">Baixando o cache de shaders</string>
<string name="bottom_downloads_paused">Pausado</string>
<string name="bottom_downloads_queued">Aguardando para começar</string>
<string name="bottom_page_notifications">Notificações</string>
<string name="bottom_notifications_listener">Tela inferior do DroidDeck</string>
<string name="bottom_notifications_why">Mostre aqui mensagens e outras notificações enquanto você joga. Elas ficam só nesta tela e não são salvas. O Android pergunta uma vez: a página de acesso a notificações dele abre nesta tela; ative o DroidDeck lá e esta página volta sozinha.</string>
<string name="bottom_notifications_allow">Permitir acesso a notificações</string>
<string name="bottom_notifications_none">Nenhuma notificação.</string>
<string name="bottom_notifications_count">%1$d notificações</string>
<string name="bottom_notifications_clear">Limpar</string>
<string name="bottom_page_screenshots">Capturas de tela</string>
<string name="stats_fps_needs_hud">O FPS precisa do HUD ativado</string>
<string name="stats_speed">Velocidade</string>
-7
View File
@@ -1801,13 +1801,6 @@
<string name="bottom_downloads_shader">Se descarcă cache-ul de shadere</string>
<string name="bottom_downloads_paused">Întrerupt</string>
<string name="bottom_downloads_queued">Așteaptă să înceapă</string>
<string name="bottom_page_notifications">Notificări</string>
<string name="bottom_notifications_listener">Ecranul de jos DroidDeck</string>
<string name="bottom_notifications_why">Afișează aici mesajele și alte notificări în timp ce te joci. Rămân doar pe acest ecran și nu sunt salvate. Android întreabă o singură dată: pagina sa de acces la notificări se deschide pe acest ecran; activează DroidDeck acolo, iar această pagină revine singură.</string>
<string name="bottom_notifications_allow">Permite accesul la notificări</string>
<string name="bottom_notifications_none">Nicio notificare.</string>
<string name="bottom_notifications_count">Notificări: %1$d</string>
<string name="bottom_notifications_clear">Șterge</string>
<string name="bottom_page_screenshots">Capturi de ecran</string>
<string name="stats_fps_needs_hud">FPS necesită HUD-ul activat</string>
<string name="stats_speed">Viteză</string>
-7
View File
@@ -1888,13 +1888,6 @@
<string name="bottom_downloads_shader">Загрузка кэша шейдеров</string>
<string name="bottom_downloads_paused">Приостановлено</string>
<string name="bottom_downloads_queued">Ожидает начала</string>
<string name="bottom_page_notifications">Уведомления</string>
<string name="bottom_notifications_listener">Нижний экран DroidDeck</string>
<string name="bottom_notifications_why">Показывает сообщения и другие уведомления здесь, пока вы играете. Они отображаются только на этом экране и не сохраняются. Android спросит один раз: на этом экране откроется страница доступа к уведомлениям; включите там DroidDeck, и эта страница вернется сама.</string>
<string name="bottom_notifications_allow">Разрешить доступ к уведомлениям</string>
<string name="bottom_notifications_none">Нет уведомлений.</string>
<string name="bottom_notifications_count">Уведомлений: %1$d</string>
<string name="bottom_notifications_clear">Очистить</string>
<string name="bottom_page_screenshots">Скриншоты</string>
<string name="stats_fps_needs_hud">Для FPS нужно включить HUD</string>
<string name="stats_speed">Скорость</string>
-7
View File
@@ -1777,13 +1777,6 @@
<string name="bottom_downloads_shader">Laddar ned shadercache</string>
<string name="bottom_downloads_paused">Pausad</string>
<string name="bottom_downloads_queued">Väntar på att starta</string>
<string name="bottom_page_notifications">Aviseringar</string>
<string name="bottom_notifications_listener">DroidDecks nedre skärm</string>
<string name="bottom_notifications_why">Visa meddelanden och andra aviseringar här medan du spelar. De visas bara på den här skärmen och sparas inte. Android frågar en gång: sidan för aviseringsåtkomst öppnas på den här skärmen; slå på DroidDeck där så kommer den här sidan tillbaka av sig själv.</string>
<string name="bottom_notifications_allow">Tillåt aviseringsåtkomst</string>
<string name="bottom_notifications_none">Inga aviseringar.</string>
<string name="bottom_notifications_count">%1$d aviseringar</string>
<string name="bottom_notifications_clear">Rensa</string>
<string name="bottom_page_screenshots">Skärmbilder</string>
<string name="stats_fps_needs_hud">FPS kräver att HUD:en är på</string>
<string name="stats_speed">Hastighet</string>
-7
View File
@@ -1753,13 +1753,6 @@
<string name="bottom_downloads_shader">กำลังดาวน์โหลดแคชเชเดอร์</string>
<string name="bottom_downloads_paused">หยุดชั่วคราว</string>
<string name="bottom_downloads_queued">กำลังรอเริ่ม</string>
<string name="bottom_page_notifications">การแจ้งเตือน</string>
<string name="bottom_notifications_listener">หน้าจอล่างของ DroidDeck</string>
<string name="bottom_notifications_why">แสดงข้อความและการแจ้งเตือนอื่นๆ ที่นี่ขณะที่คุณเล่น การแจ้งเตือนจะแสดงบนหน้าจอนี้เท่านั้นและจะไม่ถูกบันทึก Android จะถามเพียงครั้งเดียว: หน้าการเข้าถึงการแจ้งเตือนจะเปิดขึ้นบนหน้าจอนี้ เปิด DroidDeck ที่นั่น แล้วหน้านี้จะกลับมาเอง</string>
<string name="bottom_notifications_allow">อนุญาตการเข้าถึงการแจ้งเตือน</string>
<string name="bottom_notifications_none">ไม่มีการแจ้งเตือน</string>
<string name="bottom_notifications_count">การแจ้งเตือน %1$d รายการ</string>
<string name="bottom_notifications_clear">ล้าง</string>
<string name="bottom_page_screenshots">ภาพหน้าจอ</string>
<string name="stats_fps_needs_hud">ต้องเปิด HUD เพื่อแสดง FPS</string>
<string name="stats_speed">ความเร็ว</string>
-7
View File
@@ -1769,13 +1769,6 @@
<string name="bottom_downloads_shader">Gölgelendirici önbelleği indiriliyor</string>
<string name="bottom_downloads_paused">Duraklatıldı</string>
<string name="bottom_downloads_queued">Başlamayı bekliyor</string>
<string name="bottom_page_notifications">Bildirimler</string>
<string name="bottom_notifications_listener">DroidDeck alt ekranı</string>
<string name="bottom_notifications_why">Oynarken mesajları ve diğer bildirimleri burada görün. Yalnızca bu ekranda kalırlar ve kaydedilmezler. Android bunu bir kez sorar: bildirim erişimi sayfası bu ekranda açılır; orada DroidDeck\'i açın, bu sayfa kendiliğinden geri gelir.</string>
<string name="bottom_notifications_allow">Bildirim erişimine izin ver</string>
<string name="bottom_notifications_none">Bildirim yok.</string>
<string name="bottom_notifications_count">%1$d bildirim</string>
<string name="bottom_notifications_clear">Temizle</string>
<string name="bottom_page_screenshots">Ekran görüntüleri</string>
<string name="stats_fps_needs_hud">FPS için HUD açık olmalı</string>
<string name="stats_speed">Hız</string>
-7
View File
@@ -1825,13 +1825,6 @@
<string name="bottom_downloads_shader">Завантаження кешу шейдерів</string>
<string name="bottom_downloads_paused">Призупинено</string>
<string name="bottom_downloads_queued">Очікує початку</string>
<string name="bottom_page_notifications">Сповіщення</string>
<string name="bottom_notifications_listener">Нижній екран DroidDeck</string>
<string name="bottom_notifications_why">Показуйте тут повідомлення та інші сповіщення під час гри. Вони лишаються лише на цьому екрані й не зберігаються. Android запитає один раз: сторінка доступу до сповіщень відкриється на цьому екрані; увімкніть там DroidDeck, і ця сторінка повернеться сама.</string>
<string name="bottom_notifications_allow">Дозволити доступ до сповіщень</string>
<string name="bottom_notifications_none">Немає сповіщень.</string>
<string name="bottom_notifications_count">Сповіщень: %1$d</string>
<string name="bottom_notifications_clear">Очистити</string>
<string name="bottom_page_screenshots">Знімки екрана</string>
<string name="stats_fps_needs_hud">Для FPS потрібно ввімкнути HUD</string>
<string name="stats_speed">Швидкість</string>
-7
View File
@@ -1753,13 +1753,6 @@
<string name="bottom_downloads_shader">Đang tải bộ nhớ đệm shader</string>
<string name="bottom_downloads_paused">Đã tạm dừng</string>
<string name="bottom_downloads_queued">Đang chờ bắt đầu</string>
<string name="bottom_page_notifications">Thông báo</string>
<string name="bottom_notifications_listener">Màn hình dưới DroidDeck</string>
<string name="bottom_notifications_why">Hiển thị tin nhắn và các thông báo khác ở đây khi bạn chơi. Chúng chỉ ở trên màn hình này và không được lưu. Android chỉ hỏi một lần: trang quyền truy cập thông báo sẽ mở trên màn hình này; hãy bật DroidDeck ở đó và trang này sẽ tự quay lại.</string>
<string name="bottom_notifications_allow">Cho phép truy cập thông báo</string>
<string name="bottom_notifications_none">Không có thông báo.</string>
<string name="bottom_notifications_count">%1$d thông báo</string>
<string name="bottom_notifications_clear">Xóa</string>
<string name="bottom_page_screenshots">Ảnh chụp màn hình</string>
<string name="stats_fps_needs_hud">Cần bật HUD để xem FPS</string>
<string name="stats_speed">Tốc độ</string>
@@ -1831,13 +1831,6 @@
<string name="bottom_downloads_shader">正在下载着色器缓存</string>
<string name="bottom_downloads_paused">已暂停</string>
<string name="bottom_downloads_queued">等待开始</string>
<string name="bottom_page_notifications">通知</string>
<string name="bottom_notifications_listener">DroidDeck 底部屏幕</string>
<string name="bottom_notifications_why">在游戏时于此处显示消息和其他通知。通知只显示在此屏幕上,不会被保存。Android 只会询问一次:其通知使用权页面会在此屏幕上打开,在那里开启 DroidDeck 后,会自动返回此页面。</string>
<string name="bottom_notifications_allow">允许通知使用权</string>
<string name="bottom_notifications_none">没有通知。</string>
<string name="bottom_notifications_count">%1$d 条通知</string>
<string name="bottom_notifications_clear">清除</string>
<string name="bottom_page_screenshots">截图</string>
<string name="stats_fps_needs_hud">显示 FPS 需要开启 HUD</string>
<string name="stats_speed">速度</string>
@@ -1753,13 +1753,6 @@
<string name="bottom_downloads_shader">正在下載著色器快取</string>
<string name="bottom_downloads_paused">已暫停</string>
<string name="bottom_downloads_queued">等待開始</string>
<string name="bottom_page_notifications">通知</string>
<string name="bottom_notifications_listener">DroidDeck 下方螢幕</string>
<string name="bottom_notifications_why">在遊玩時於此處顯示訊息和其他通知。通知只會顯示在這個螢幕上,不會儲存。Android 只會詢問一次:通知存取權頁面會在這個螢幕上開啟,在那裡開啟 DroidDeck 後,就會自動回到此頁面。</string>
<string name="bottom_notifications_allow">允許通知存取權</string>
<string name="bottom_notifications_none">沒有通知。</string>
<string name="bottom_notifications_count">%1$d 則通知</string>
<string name="bottom_notifications_clear">清除</string>
<string name="bottom_page_screenshots">螢幕截圖</string>
<string name="stats_fps_needs_hud">顯示 FPS 需要開啟 HUD</string>
<string name="stats_speed">速度</string>
@@ -1753,13 +1753,6 @@
<string name="bottom_downloads_shader">正在下載著色器快取</string>
<string name="bottom_downloads_paused">已暫停</string>
<string name="bottom_downloads_queued">等待開始</string>
<string name="bottom_page_notifications">通知</string>
<string name="bottom_notifications_listener">DroidDeck 底部螢幕</string>
<string name="bottom_notifications_why">在遊玩時於此處顯示訊息和其他通知。通知只會顯示在這個螢幕上,不會儲存。Android 只會詢問一次:通知存取權頁面會在這個螢幕上開啟,在那裡開啟 DroidDeck 後,就會自動回到此頁面。</string>
<string name="bottom_notifications_allow">允許通知存取權</string>
<string name="bottom_notifications_none">沒有通知。</string>
<string name="bottom_notifications_count">%1$d 則通知</string>
<string name="bottom_notifications_clear">清除</string>
<string name="bottom_page_screenshots">螢幕擷取畫面</string>
<string name="stats_fps_needs_hud">顯示 FPS 需要開啟 HUD</string>
<string name="stats_speed">速度</string>
-7
View File
@@ -1965,13 +1965,6 @@
<string name="bottom_downloads_shader">Downloading shader cache</string>
<string name="bottom_downloads_paused">Paused</string>
<string name="bottom_downloads_queued">Waiting to start</string>
<string name="bottom_page_notifications">Notifications</string>
<string name="bottom_notifications_listener">DroidDeck bottom screen</string>
<string name="bottom_notifications_why">Show messages and other notifications here while you play. They stay on this screen only and are not saved. Android asks once: its notification access page opens on this screen; turn DroidDeck on there and this page comes back by itself.</string>
<string name="bottom_notifications_allow">Allow notification access</string>
<string name="bottom_notifications_none">No notifications.</string>
<string name="bottom_notifications_count">%1$d notifications</string>
<string name="bottom_notifications_clear">Clear</string>
<string name="bottom_page_screenshots">Screenshots</string>
<string name="stats_fps_needs_hud">FPS needs the HUD on</string>
<string name="stats_speed">Speed</string>
@@ -0,0 +1,26 @@
package com.droiddeck.launcher.gpu
import android.content.Context
import java.io.File
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
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class SystemVulkanPruneAbsentRuntimeTest {
@Test fun pruningWithoutTheRuntimeDoesNotThrowAndLeavesFilesAlone() {
val context: Context = RuntimeEnvironment.getApplication()
val base = File(context.filesDir, "system_vulkan").apply { mkdirs() }
val stage = File(base, ".stage-" + java.util.UUID.randomUUID()).apply { mkdir() }
val version = File(base, "a".repeat(64)).apply { mkdir() }
SystemVulkanDriver.pruneUnused(context, true)
assertTrue(stage.exists())
assertTrue(version.exists())
}
}
@@ -17,6 +17,19 @@ class GesturePrefsTest {
assertEquals(TouchGestureConfig.RELATIVE_MOUSE_AUTO, TouchGestureConfig.fromJson("{}").relativeMouseMode)
}
@Test fun autoNeverGoesRelativeForDirectTouchWithoutAMouse() {
val auto = TouchGestureConfig.RELATIVE_MOUSE_AUTO
assertEquals(TouchGestureConfig.RELATIVE_MOUSE_OFF, TouchGestureConfig.gamescopeRelativeMouse(auto, mouseAttached = false, touchpad = false))
assertEquals(auto, TouchGestureConfig.gamescopeRelativeMouse(auto, mouseAttached = true, touchpad = false))
assertEquals(auto, TouchGestureConfig.gamescopeRelativeMouse(auto, mouseAttached = false, touchpad = true))
}
@Test fun aChosenRelativeMouseModeIsSentAsIs() {
for (mode in listOf(TouchGestureConfig.RELATIVE_MOUSE_ON, TouchGestureConfig.RELATIVE_MOUSE_OFF))
for (mouse in listOf(false, true)) for (pad in listOf(false, true))
assertEquals(mode, TouchGestureConfig.gamescopeRelativeMouse(mode, mouse, pad))
}
@Test fun removedOptionsAreIgnoredWhenLoadingExistingSettings() {
val old = """{"holdMouseButtonWhileTouchingEnabled":true,"holdMouseButtonWhileTouchingAction":"right_click",
"showClickHighlight":true,"showCursorInTouchscreenMode":true,"tapAction":"key_E","longPressDelay":650}"""
@@ -0,0 +1,23 @@
package com.droiddeck.launcher.input
import com.droiddeck.launcher.session.SessionPrefs
import org.junit.Assert.assertEquals
import org.junit.Test
class TouchRouterTest {
@Test fun gesturesAndOffAreNotTouchpadRoutes() {
for (mode in listOf(SessionPrefs.TOUCH_GESTURES, SessionPrefs.TOUCH_OFF)) {
assertEquals(TouchRouter.Route.GESTURES.takeIf { mode == SessionPrefs.TOUCH_GESTURES } ?: TouchRouter.Route.OFF,
TouchRouter.decide(TouchRouter.Snapshot(false, mode, false, false, false)))
assertEquals(TouchRouter.Route.GESTURES.takeIf { mode == SessionPrefs.TOUCH_GESTURES } ?: TouchRouter.Route.OFF,
TouchRouter.decide(TouchRouter.Snapshot(false, mode, false, true, true)))
}
}
@Test fun autoUsesTouchpadOnlyWhenRouterSelectsTouchpad() {
assertEquals(TouchRouter.Route.TOUCHPAD,
TouchRouter.decide(TouchRouter.Snapshot(false, SessionPrefs.TOUCH_AUTO, false, false, false)))
assertEquals(TouchRouter.Route.DIRECT,
TouchRouter.decide(TouchRouter.Snapshot(false, SessionPrefs.TOUCH_AUTO, false, true, false)))
}
}
@@ -1,38 +0,0 @@
package com.droiddeck.launcher.session
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class BottomNotificationsTest {
private val own = "com.droiddeck.launcher"
@Test fun messagesFromOtherAppsAreKept() {
assertTrue(BottomNotifications.keep(own, "com.discord", ongoing = false, groupSummary = false, title = "Kurt", text = "ready?"))
}
@Test fun ownOngoingSummaryAndEmptyNotificationsAreSkipped() {
assertFalse(BottomNotifications.keep(own, own, ongoing = false, groupSummary = false, title = "Session", text = "running"))
assertFalse(BottomNotifications.keep(own, "com.spotify", ongoing = true, groupSummary = false, title = "Song", text = "Artist"))
assertFalse(BottomNotifications.keep(own, "com.discord", ongoing = false, groupSummary = true, title = "2 messages", text = ""))
assertFalse(BottomNotifications.keep(own, "com.discord", ongoing = false, groupSummary = false, title = " ", text = ""))
}
@Test fun anUpdatedNotificationMovesToTheTopOnce() {
val list = mutableListOf(
BottomNotification("a", "App", "one", "", 1L),
BottomNotification("b", "App", "two", "", 2L),
)
BottomNotifications.add(list, BottomNotification("b", "App", "two again", "", 3L))
assertEquals(listOf("b", "a"), list.map { it.key })
assertEquals("two again", list.first().title)
}
@Test fun theListKeepsTheNewestThirty() {
val list = mutableListOf<BottomNotification>()
repeat(35) { BottomNotifications.add(list, BottomNotification("k$it", "App", "t$it", "", it.toLong())) }
assertEquals(30, list.size)
assertEquals("k34", list.first().key)
}
}
@@ -60,6 +60,13 @@ class SessionDisplayTest {
assertEquals(864, SessionDisplay.unfoldedGameHeight(1920, 1080))
}
@Test fun aTabRowUnderTheBarComesOutOfTheGameNotTheControls() {
assertEquals(1376, SessionDisplay.unfoldedGameHeight(2448, 1848, 0))
assertEquals(1240, SessionDisplay.unfoldedGameHeight(2448, 1848, 136))
assertEquals(1376, SessionDisplay.unfoldedGameHeight(2448, 1848, -20))
assertEquals(0, SessionDisplay.unfoldedGameHeight(200, 100, 500))
}
private fun unfoldedWanted(
enabled: Boolean = true,
controller: Boolean = false,
@@ -0,0 +1,53 @@
package com.droiddeck.launcher.session
import android.content.Intent
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Before
import org.junit.Test
class SessionLoadingDecisionTest {
private var previousSessionId: String? = null
private var previousRelaunch: Intent? = null
@Before
fun setUp() {
previousSessionId = SessionState.sessionId
previousRelaunch = SessionState.relaunch
SessionState.clearRelaunch()
}
@After
fun tearDown() {
SessionState.sessionId = previousSessionId
SessionState.relaunch = previousRelaunch
SessionState.clearRelaunch()
if (previousRelaunch != null) SessionState.queueRelaunch(previousRelaunch!!)
}
@Test
fun loadingTimesOutOnlyWhenNoSessionStarted() {
assertEquals(false, SessionLoadingDecision.shouldReturnToLauncher(100L, 10_099L, false, SessionPhase.IDLE))
assertEquals(true, SessionLoadingDecision.shouldReturnToLauncher(100L, 10_100L, false, SessionPhase.IDLE))
assertEquals(false, SessionLoadingDecision.shouldReturnToLauncher(100L, 10_100L, true, SessionPhase.IDLE))
assertEquals(false, SessionLoadingDecision.shouldReturnToLauncher(100L, 10_100L, false, SessionPhase.PREPARING))
}
@Test
fun relaunchRequiresTheCurrentSessionToHaveRequestedTheStop() {
SessionState.sessionId = "session-a"
val next = Intent().apply { action = "next" }
SessionState.queueRelaunch(next)
assertNull(SessionState.takeRelaunch())
SessionState.queueRelaunch(next)
SessionState.confirmRelaunchStop()
assertEquals(next, SessionState.takeRelaunch())
assertNull(SessionState.takeRelaunch())
SessionState.queueRelaunch(next)
SessionState.confirmRelaunchStop()
SessionState.sessionId = "session-b"
assertNull(SessionState.takeRelaunch())
}
}
@@ -24,6 +24,23 @@ class GogListingTest {
assertEquals("", shadowrun.description)
}
@Test
fun ownedGamesTheListingLeavesOutStayOwned() {
assertEquals(setOf("1", "2", "1086370078"), GogLibrary.ownedSet(setOf("1", "2"), listOf("2", "1086370078")))
}
@Test
fun withoutTheAccountListTheListingStillCounts() {
assertEquals(setOf("1", "2"), GogLibrary.ownedSet(setOf("1", "2"), null))
assertEquals(setOf("3"), GogLibrary.ownedSet(emptySet(), listOf("3")))
}
@Test
fun cachedGamesStayWhenTheAccountListIsUnavailable() {
assertEquals(setOf("1", "2", "1086370078"), GogLibrary.ownedSet(setOf("1", "2"), null, setOf("1086370078")))
assertEquals(setOf("1", "2", "3"), GogLibrary.ownedSet(setOf("1"), listOf("2", "3"), setOf("1086370078")))
}
@Test
fun moviesOtherPlatformsAndGalaxysOwnEntryAreLeftOut() {
assertEquals(listOf("1207660413", "1207664663"), GogLibrary.parseListing(PAGE)!!.games.map { it.gameId })
@@ -16,7 +16,7 @@ class BottomDashboardTest {
}
@Test fun withNothingPickedTheStatsOpen() {
val ids = listOf("telemetry", "downloads", "notifications", "screenshots", "chat")
val ids = listOf("telemetry", "downloads", "screenshots", "chat")
assertEquals("telemetry", pickBottomPage(null, ids))
assertEquals("telemetry", pickBottomPage("gone", ids))
assertEquals("chat", pickBottomPage("chat", ids))
+9
View File
@@ -244,6 +244,15 @@ self-extractor stops at "Path not found", so the values it installs are applied
`witcher.exe` exits during startup. The language comes from the installed product's
`goggame-<id>.info`, and a script's own `setRegistry` entries always win over the built-in table.
The script's `supportData` actions run right after: files and folders from the game folder
(`{app}`) or its support files (`{supportDir}`, `support/<id>/`) are copied to `{userdocs}` and
`{localappdata}` in the prefix, and `type: folder` without a source creates the folder. Mods such
as one-click editions ship their `Plugins.txt` and INI files this way. Paths match without regard
to case, links are copied as links, and a path outside those folders is refused. A file the
player already has is replaced only when the action says `overwrite`. `.droiddeck-gog-support` in
the prefix holds the actions' hash, so they run once per script revision and a player's later
edits stay.
A GOG game's exe comes from its own manifest first: `goggame-<id>.info`'s play task in category
`game` (`isPrimary` first), or a primary `launcher` task for launcher games, whose `path` stays
inside the folder; any other `goggame-*.info` in the folder supplies the task only when the
+32 -1
View File
@@ -9,6 +9,7 @@ import gzip
import json
import os
import re
import shlex
import shutil
import subprocess
import struct
@@ -98,6 +99,29 @@ def encode_request(request: dict) -> str:
return encoded
def receiver_call(adb: str, serial: str, method: str, arg: str | None, request: dict | None, timeout: float) -> dict:
"""The agent bridge through a broadcast, for shells without the `content` command."""
call_id = uuid.uuid4().hex[:16]
remote = f"/sdcard/Android/data/{PACKAGE}/files/agent-calls/{call_id}.json"
command = ["shell", "am", "broadcast", "-a", f"{PACKAGE}.AGENT_CALL", "-p", PACKAGE,
"--es", "method", method, "--es", "id", call_id]
if arg is not None:
command += ["--es", "arg", shlex.quote(arg)]
if request is not None:
command += ["--es", "request", encode_request(request)]
started = run_adb(adb, serial, *command, timeout=timeout + 30)
if started.returncode != 0:
raise ControlError((started.stdout + started.stderr).decode(errors="replace").strip() or "ADB broadcast failed", "ADB_FAILED")
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
result = run_adb(adb, serial, "shell", f"cat {remote} 2>/dev/null && rm -f {remote}", timeout=30)
text = result.stdout.decode(errors="replace").strip()
if result.returncode == 0 and text:
return json.loads(text)
time.sleep(0.25)
raise ControlError(f"No answer to {method} within {timeout:g} s", "TIMEOUT")
def provider_call(adb: str, serial: str, method: str, arg: str | None = None, request: dict | None = None,
timeout: float = 30) -> dict:
command = ["shell", "content", "call", "--uri", AUTHORITY, "--method", method]
@@ -108,6 +132,8 @@ def provider_call(adb: str, serial: str, method: str, arg: str | None = None, re
command.extend(["--extra", f"request:s:{encoded}"])
result = run_adb(adb, serial, *command, timeout=timeout)
output = (result.stdout + result.stderr).decode(errors="replace")
if "content: inaccessible or not found" in output:
return receiver_call(adb, serial, method, arg, request, timeout)
response = _content_result(output)
if result.returncode != 0 and response.get("ok") is not False:
raise ControlError(output.strip() or "ADB content call failed", "ADB_FAILED")
@@ -237,10 +263,15 @@ def displays(adb: str, serial: str) -> list[dict]:
device = re.search(r"mPrimaryDisplayDevice=(.+)", block)
size = re.search(r"real (\d+) x (\d+)", block)
name = device.group(1).strip() if device else None
physical = devices.get(name) if name else None
if name and not physical:
# Some ROMs (Retroid Pocket Duo) print the device as "Built-in Screen(local:<id>)"
inline = re.search(r"\(local:(\d+)\)$", name)
physical = inline.group(1) if inline else None
out.append({
"display": logical,
"name": name,
"physicalId": devices.get(name) if name else None,
"physicalId": physical,
"size": [int(size.group(1)), int(size.group(2))] if size else None,
})
return out
+6
View File
@@ -327,6 +327,12 @@ each frame's motion to the X pointer itself until the game stops warping. Absolu
motion, as a real compositor does, so XInput2 raw motion reaches games that read only that. A touch moves the
pointer without relative motion, so tapping the screen does not turn the camera.
The X pointer is read in root coordinates and the seat position is local to the focused window, so the X pointer
is moved into the focused window's coordinates before the two are compared. Without that, any window not at the
root origin (a dialog, or a windowed program) looked like a game warping the pointer, following started, and the
pointer was pinned to the window's corner. A touch always lands where the finger is and ends following, so taps
work in every window.
## 0132 sdl, steamcompmgr: follow a game's window mode
With `--follow-game-window-mode`, the outer window of a nested SDL gamescope follows the focused game window. A window
asking for `_NET_WM_STATE_FULLSCREEN`, or a Steam game covering the X screen without minimise or maximise functions or
@@ -1,5 +1,5 @@
diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp
index 17bae3a..c468fb3 100644
index 17bae3a..91ec0be 100644
--- a/src/steamcompmgr.cpp
+++ b/src/steamcompmgr.cpp
@@ -32,6 +32,7 @@
@@ -18,7 +18,7 @@ index 17bae3a..c468fb3 100644
static bool relative_mouse_forced();
void MouseCursor::checkSuspension()
@@ -3083,12 +3085,89 @@ static gamescope::ConVar<int> cv_relative_mouse( "relative_mouse", 0,
@@ -3083,12 +3085,101 @@ static gamescope::ConVar<int> cv_relative_mouse( "relative_mouse", 0,
"0 = Leave it to the game and the nested hints. 1 = Send host pointer motion as relative movement, for games that confine the cursor and warp it back to read movement. 2 = Never go relative." );
static bool relative_mouse_forced()
{
@@ -34,16 +34,28 @@ index 17bae3a..c468fb3 100644
+ static double s_flLastX = 0.0;
+ static double s_flLastY = 0.0;
+
+ int nRootX = 0;
+ int nRootY = 0;
+ int nClientX = 0;
+ int nClientY = 0;
+ if ( bAllowed && pFocus->cursor )
+ pFocus->cursor->QueryRootPosition( &nRootX, &nRootY );
+ pFocus->cursor->QueryRootPosition( &nClientX, &nClientY );
+ else
+ bAllowed = false;
+
+ steamcompmgr_win_t *pInputWindow = pFocus->inputFocusWindow;
+ if ( pInputWindow && pInputWindow->type == steamcompmgr_win_type_t::XWAYLAND )
+ {
+ nClientX -= pInputWindow->xwayland().a.x;
+ nClientY -= pInputWindow->xwayland().a.y;
+ }
+
+ wlserver_lock();
+ const double flX = wlserver.mouse_surface_cursorx;
+ const double flY = wlserver.mouse_surface_cursory;
+ if ( s_bFollowClientPointer && !wlserver.bFollowClientPointer )
+ {
+ s_nAwayFrames = 0;
+ s_bFollowClientPointer = false;
+ }
+ if ( !bAllowed )
+ {
+ s_nAwayFrames = 0;
@@ -53,7 +65,7 @@ index 17bae3a..c468fb3 100644
+ else if ( !s_bFollowClientPointer )
+ {
+ const bool bMoved = flX != s_flLastX || flY != s_flLastY;
+ if ( bMoved && ( std::abs( nRootX - flX ) > 48.0 || std::abs( nRootY - flY ) > 48.0 ) )
+ if ( bMoved && ( std::abs( nClientX - flX ) > 48.0 || std::abs( nClientY - flY ) > 48.0 ) )
+ {
+ const uint64_t ulNow = get_time_in_nanos();
+ if ( ulNow - s_ulLastAway > 500'000'000ul )
@@ -70,12 +82,12 @@ index 17bae3a..c468fb3 100644
+ wlserver.bFollowClientPointer = true;
+ wlserver.flFollowDX = 0.0;
+ wlserver.flFollowDY = 0.0;
+ wlserver_mousewarp( nRootX, nRootY, 0, true );
+ wlserver_mousewarp( nClientX, nClientY, 0, true );
+ }
+ }
+ else
+ {
+ const bool bWarped = std::abs( nRootX - flX ) > 2.0 || std::abs( nRootY - flY ) > 2.0;
+ const bool bWarped = std::abs( nClientX - flX ) > 2.0 || std::abs( nClientY - flY ) > 2.0;
+ const double flDX = std::trunc( wlserver.flFollowDX );
+ const double flDY = std::trunc( wlserver.flFollowDY );
+ if ( bWarped )
@@ -87,9 +99,9 @@ index 17bae3a..c468fb3 100644
+ {
+ wlserver.flFollowDX -= flDX;
+ wlserver.flFollowDY -= flDY;
+ wlserver_mousewarp( nRootX, nRootY, 0, true );
+ wlserver_mousewarp( nClientX, nClientY, 0, true );
+ if ( flDX != 0.0 || flDY != 0.0 )
+ wlserver_mousewarp( nRootX + flDX, nRootY + flDY, 0, true );
+ wlserver_mousewarp( nClientX + flDX, nClientY + flDY, 0, true );
+ }
+
+ if ( s_nQuietFrames >= 60 )
@@ -110,7 +122,7 @@ index 17bae3a..c468fb3 100644
return true;
global_focus_t *pFocus = GetCurrentFocus();
@@ -10892,9 +10971,15 @@ steamcompmgr_main(int argc, char **argv)
@@ -10892,9 +10983,15 @@ steamcompmgr_main(int argc, char **argv)
const int nRelativeMouse = cv_relative_mouse.Get();
const bool bForcedRelativeMouse = nRelativeMouse == 1 && !window_is_steam( pPaintFocus->inputFocusWindow );
@@ -128,7 +140,7 @@ index 17bae3a..c468fb3 100644
static bool s_bRelativeMouseMode = false;
if ( s_bRelativeMouseMode && !bRelativeMouseMode && pPaintFocus->cursor &&
diff --git a/src/wlserver.cpp b/src/wlserver.cpp
index 5733871..cc75f8a 100644
index 5733871..df23f8a 100644
--- a/src/wlserver.cpp
+++ b/src/wlserver.cpp
@@ -1,3 +1,4 @@
@@ -153,7 +165,7 @@ index 5733871..cc75f8a 100644
if ( !wlserver_apply_constraint( &dx, &dy ) )
{
wlr_seat_pointer_notify_frame( wlserver.wlr.seat );
@@ -3110,10 +3121,18 @@ void wlserver_mousemotion( double dx, double dy, uint32_t time )
@@ -3110,10 +3121,22 @@ void wlserver_mousemotion( double dx, double dy, uint32_t time )
wlr_seat_pointer_notify_frame( wlserver.wlr.seat );
}
@@ -163,7 +175,11 @@ index 5733871..cc75f8a 100644
assert( wlserver_is_lock_held() );
+ if ( !bSynthetic && wlserver.bFollowClientPointer )
+ return;
+ {
+ if ( !bFromTouch )
+ return;
+ wlserver.bFollowClientPointer = false;
+ }
+
+ const double flStepX = x - wlserver.mouse_surface_cursorx;
+ const double flStepY = y - wlserver.mouse_surface_cursory;
@@ -173,7 +189,7 @@ index 5733871..cc75f8a 100644
wlserver.mouse_surface_cursorx = x;
wlserver.mouse_surface_cursory = y;
@@ -3304,7 +3323,7 @@ void wlserver_touchmotion( double x, double y, int touch_id, uint32_t time, bool
@@ -3304,7 +3327,7 @@ void wlserver_touchmotion( double x, double y, int touch_id, uint32_t time, bool
{
g_bPendingTouchMovement = true;
@@ -182,7 +198,7 @@ index 5733871..cc75f8a 100644
}
}
@@ -3352,7 +3371,7 @@ void wlserver_touchdown( double x, double y, int touch_id, uint32_t time, gamesc
@@ -3352,7 +3375,7 @@ void wlserver_touchdown( double x, double y, int touch_id, uint32_t time, gamesc
if ( eMode != gamescope::TouchClickModes::Trackpad )
{
+2 -2
View File
@@ -1,3 +1,3 @@
GAMESCOPE_REPO=Droid-Deck/DroidDeck-Components
GAMESCOPE_TAG=gamescope-3.16.29-p22
GAMESCOPE_SHA256=2b7e7481df5f5f7355d224d3a0d4205557367172653dff1d7206a230b6c78b46
GAMESCOPE_TAG=gamescope-3.16.29-p23
GAMESCOPE_SHA256=f5f2b8f658234ad2910a1be53c238188db7e7b2a9079f8cc5fa9ea006bebbe7e
@@ -55,6 +55,9 @@ if [ -x /usr/local/bin/droiddeck-fex ]; then
*) run=(/usr/local/bin/droiddeck-fex run --mode "$fex" --for "$APPDIR" -- "$APPDIR/AppRun") ;;
esac
fi
gpu=("${BASH_SOURCE[0]%/*}/droiddeck-game-gpu")
[ ${#flags[@]} -gt 0 ] && gpu+=(--chromium)
run=("${gpu[@]}" -- "${run[@]}")
echo "== appimage $ARGV0 ($APPDIR) ${flags[*]} FEX $fex Qt $qt${QT_QPA_PLATFORM:+ ($QT_QPA_PLATFORM)}"
cd "$APPDIR" || exit 1
started=$(mktemp "${TMPDIR:-/tmp}/droiddeck-appimage.XXXXXX")
@@ -11,8 +11,16 @@ if [ -n "${BL_INSIDE:-}" ] || [ -n "${GAMESCOPE_WAYLAND_DISPLAY:-}" ]; then
export XDG_SESSION_TYPE=x11
socket=(--nosocket=wayland --socket=x11)
fi
app=
for arg in "$@"; do
case $arg in -*) ;; *) app=$arg; break ;; esac
done
gpu=("${BASH_SOURCE[0]%/*}/droiddeck-game-gpu")
location=
[ -n "$app" ] && location=$(flatpak info --show-location "$app" 2>/dev/null)
[ -n "$location" ] && gpu+=(--for "$location/files")
echo "== flatpak run ${socket[*]} $*"
if [ -z "${DBUS_SESSION_BUS_ADDRESS:-}" ] && command -v dbus-run-session >/dev/null 2>&1; then
exec dbus-run-session -- flatpak run "${socket[@]}" "$@"
exec "${gpu[@]}" -- dbus-run-session -- flatpak run "${socket[@]}" "$@"
fi
exec flatpak run "${socket[@]}" "$@"
exec "${gpu[@]}" -- flatpak run "${socket[@]}" "$@"
@@ -11,6 +11,7 @@ import tempfile
from pathlib import Path
GAME_TU_DEBUG = "DROIDDECK_GAME_TU_DEBUG"
CHROMIUM_FILES = {"chrome-sandbox", "chrome_100_percent.pak", "v8_context_snapshot.bin"}
SYNC_KEYS = ("BL_SYNC", "BL_SYNC_FALLBACK", "BL_FSYNC_FIRST", "BL_SYNC_MIN_NOFILE", "PROTON_NO_ESYNC", "PROTON_NO_FSYNC", "PROTON_NO_NTSYNC", "WINEESYNC")
SEED_REDISTS = "/usr/local/bin/droiddeck-seed-redists"
PACK_KEYS = ("WINESERVER", "BL_SYNC_PACK", "WINEESYNC", "PROTON_NO_ESYNC", "PROTON_NO_FSYNC")
@@ -346,11 +347,23 @@ def win_components(compat, app_id):
return ""
def game_gpu(env):
def chromium_app(folder):
root = os.path.realpath(folder)
for top, dirs, files in os.walk(root):
if CHROMIUM_FILES.intersection(files) or CHROMIUM_FILES.intersection(dirs):
return True
if os.path.relpath(top, root).count(os.sep) >= 2:
dirs[:] = []
return False
def game_gpu(env, keep=False):
if GAME_TU_DEBUG not in env:
return env
result = env.copy()
value = result.pop(GAME_TU_DEBUG)
if keep:
return result
if value:
result["TU_DEBUG"] = value
else:
+42
View File
@@ -0,0 +1,42 @@
#!/usr/bin/python3
import os
import runpy
import sys
BIN_DIR = os.path.dirname(os.path.abspath(__file__))
def main(argv):
keep = False
folder = None
while argv and argv[0] != "--":
if argv[0] == "--chromium":
keep = True
argv = argv[1:]
elif argv[0] == "--for" and len(argv) > 1:
folder = argv[1]
argv = argv[2:]
else:
break
if argv and argv[0] == "--":
argv = argv[1:]
if not argv:
print("usage: droiddeck-game-gpu [--chromium] [--for FOLDER] -- PROGRAM [ARGS...]", file=sys.stderr)
return 2
env = dict(os.environ)
try:
game_env = runpy.run_path(os.path.join(BIN_DIR, "droiddeck-game-env"))
if folder and not keep:
keep = game_env["chromium_app"](folder)
env = game_env["game_gpu"](env, keep)
except Exception as error:
print("droiddeck-game-gpu: the game GPU setting was not applied (%s)" % error, file=sys.stderr)
try:
os.execvpe(argv[0], argv, env)
except OSError as error:
print("droiddeck-game-gpu: %s: %s" % (argv[0], error.strerror), file=sys.stderr)
return 127
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
@@ -902,21 +902,21 @@ case $mode in
bl_session_pressure() {
bl_memory_read
[ "$_bl_game" = 1 ] && bl_low_ram && bl_memory_critical || return 0
local _wait=$_bl_tier_backoff _urgent=0 _before _pids _targets
[ "$_bl_available" -ge $((_bl_headroom / 2)) ] || _urgent=1 _wait=30
local _wait=$_bl_tier_backoff _before _pids _targets
[ "$_bl_available" -ge $((_bl_headroom / 2)) ] || [ "$_bl_tier_pushed" -lt 0 ] || _wait=30
[ "$_bl_tier_at" -lt 0 ] || [ $((SECONDS - _bl_tier_at)) -ge "$_wait" ] || return 0
if [ "$_bl_tier_at" -ge 0 ] && [ "$_bl_tier_pushed" -gt 0 ]; then
bl_tier_readback
if [ "$_bl_tier_back" -le $((_bl_tier_pushed / 2)) ]; then
_bl_tier_backoff=30
elif [ "$_urgent" = 0 ]; then
else
_bl_tier_backoff=$((_bl_tier_backoff * 2 > 300 ? 300 : _bl_tier_backoff * 2))
_bl_tier_at=$SECONDS _bl_tier_pushed=0
_bl_tier_at=$SECONDS _bl_tier_pushed=-1
step "zRAM: the game read back most of its last page-out, next try in ${_bl_tier_backoff} s"
return 0
fi
fi
_bl_tier_at=$SECONDS
_bl_tier_at=$SECONDS _bl_tier_pushed=0
bl_zram_pick game
bl_zram_usage "${_pids[@]}" > /dev/null
[ "$_bl_rss" -ge $((256 * 1024)) ] || return 0
@@ -1338,6 +1338,23 @@ case $mode in
echo "== network: no dbus-daemon or netmanager in this runtime; the client will show no connection"
exit 69
fi
# Without a session bus libdbus autolaunches one under the game; it never exits and Steam's
# reaper waits on it, so the launch or exit never finishes.
if [ -z "${DBUS_SESSION_BUS_ADDRESS:-}" ]; then
_bl_bus=${XDG_RUNTIME_DIR:-/run/droiddeck}/bus
rm -f "$_bl_bus"
dbus-daemon --session --address="unix:path=$_bl_bus" --nofork --nopidfile &
for _ in $(seq 1 50); do
[ -S "$_bl_bus" ] && break
nap 0.1
done
if [ -S "$_bl_bus" ]; then
export DBUS_SESSION_BUS_ADDRESS="unix:path=$_bl_bus"
echo "== session bus up at $_bl_bus"
else
echo "== session bus did not come up; programs may start their own"
fi
fi
_bl_compat_env=(env -u LD_LIBRARY_PATH -u STEAM_RUNTIME -u STEAM_STEAMRT_RECURSION_GUARD)
[ "${LD_LIBRARY_PATH+x}" ] && _bl_compat_env+=("LD_LIBRARY_PATH=$LD_LIBRARY_PATH")
@@ -1,11 +1,13 @@
#!/usr/bin/python3
import os
import re
import runpy
import shlex
import sys
import yaml
BIN_DIR = os.path.dirname(os.path.abspath(__file__))
SNAP_DIR = "/snap"
HOST_DIRS = ("/etc", "/home", "/root", "/tmp", "/run", "/var/snap", "/var/lib/snapd", "/var/tmp", "/var/log",
"/media", "/mnt", "/snap", "/usr/src", "/lib/modules")
@@ -59,6 +61,15 @@ def content_binds(name, meta, env):
return out
def game_gpu(env, snap):
try:
game_env = runpy.run_path(os.path.join(BIN_DIR, "droiddeck-game-env"))
return game_env["game_gpu"](env, game_env["chromium_app"](snap))
except Exception as error:
print(f"droiddeck-snap-run: the game GPU setting was not applied ({error})", file=sys.stderr)
return env
def main(argv):
if len(argv) < 3:
print("usage: droiddeck-snap-run SNAP APP [ARG...]", file=sys.stderr)
@@ -72,7 +83,7 @@ def main(argv):
revision = os.path.basename(os.path.realpath(f"{SNAP_DIR}/{name}/current"))
home = os.environ.get("HOME", "/root")
snap = f"{SNAP_DIR}/{name}/{revision}"
env = dict(os.environ)
env = game_gpu(dict(os.environ), snap)
for k in ("LD_PRELOAD", "LD_LIBRARY_PATH"):
env.pop(k, None)
env.update({
@@ -760,18 +760,50 @@ class Watcher:
def __init__(self, files):
self.files = files
self.fd = -1
self.libc = None
wanted = {os.path.dirname(f) for f in files}
self.missing = {d for d in wanted if not os.path.isdir(d)}
self.watched = set()
try:
libc = ctypes.CDLL(None, use_errno=True)
fd = libc.inotify_init1(os.O_NONBLOCK | os.O_CLOEXEC)
dirs = sorted({os.path.dirname(f) for f in files if os.path.isdir(os.path.dirname(f))})
dirs = sorted((wanted - self.missing) | {self.existing_parent(d) for d in self.missing} - {""})
if fd >= 0 and dirs and all(libc.inotify_add_watch(fd, d.encode(), self.MASK) >= 0 for d in dirs):
self.watched = set(dirs)
self.fd = fd
self.libc = libc
elif fd >= 0:
os.close(fd)
except (OSError, AttributeError):
self.fd = -1
self.stamp = self.snapshot()
@staticmethod
def existing_parent(path):
while path and not os.path.isdir(path):
parent = os.path.dirname(path)
if parent == path:
return ""
path = parent
return path
def watch_new_dirs(self):
appeared = False
progressed = True
while progressed:
progressed = False
for d in sorted(self.missing):
parent = d if os.path.isdir(d) else self.existing_parent(d)
if not parent or parent in self.watched:
continue
if self.libc.inotify_add_watch(self.fd, parent.encode(), self.MASK) >= 0:
self.watched.add(parent)
progressed = True
appeared = appeared or parent == d
for d in [d for d in self.missing if d in self.watched]:
self.missing.discard(d)
return appeared
def snapshot(self):
stamp = []
for f in self.files:
@@ -803,8 +835,9 @@ class Watcher:
at += 16 + size
except BlockingIOError:
pass
appeared = self.watch_new_dirs() if self.missing else False
wanted = {os.path.basename(f) for f in self.files}
return any(n in wanted or n.startswith("appmanifest_") for n in names)
return appeared or any(n in wanted or n.startswith("appmanifest_") for n in names)
class XMessage(ctypes.Structure):
@@ -1078,11 +1111,13 @@ class Helper:
wanted = COMPAT["requested_tool"](request, catalog)
newer = isinstance(request.get("seq"), int) and request["seq"] > int(state.get("applied", 0) or 0)
waiting = newer and wanted is not None and wanted not in self.known
default, state = COMPAT["choose_default"](top["selected"], state, request, catalog, apply_request=not waiting,
listed=[t["name"] for t in live])
listed = [t["name"] for t in live]
default, state = COMPAT["choose_default"](COMPAT["built_from"](top["selected"], catalog, listed) or top["selected"],
state, request, catalog, apply_request=not waiting, listed=listed)
installed = COMPAT["installed_apps"](self.steam_root)
self.installed = installed
picks = COMPAT["valve_picks"](self.steam_root)
tools = COMPAT["tool_platforms"](self.steam_root)
prior_auto = state.get("auto", {})
if not isinstance(prior_auto, dict):
prior_auto = {}
@@ -1090,7 +1125,7 @@ class Helper:
native_choices = set(prior_native if isinstance(prior_native, (list, tuple, set)) else ())
picked = COMPAT["picked_apps"](state)
runnable = {t["name"].lower() for t in live}
apps = sorted(set(installed) | set(picks) | set(prior_auto) | native_choices, key=COMPAT["app_order"])
apps = sorted(set(installed) | set(picks) | set(prior_auto) | native_choices | set(tools), key=COMPAT["app_order"])
asked = [app for app, request in COMPAT["game_requests"]().items() if COMPAT["valid_game_request"](app, request)]
apps = sorted(set(apps) | set(asked), key=COMPAT["app_order"])
current = dict(page.compat("many(%s)" % json.dumps(apps)) or {})
@@ -1104,6 +1139,7 @@ class Helper:
if isinstance(state.get("auto"), dict):
state["auto"] = prior_auto
native_choices -= refused
tools = {app: platforms for app, platforms in tools.items() if app not in refused}
current["0"] = top["selected"]
native = COMPAT["native_targets"](self.steam_root, apps)
raw_mapping = COMPAT["read_config_mapping"](
@@ -1124,13 +1160,20 @@ class Helper:
current[app] = ""
elif not current.get(app):
current.pop(app, None)
moved = COMPAT["rebuilt_picks"](current, catalog, set(prior_auto) | picked, listed)
if moved:
following = COMPAT["followers"](state, current)
state["auto"] = {app: name for app, name in following.items() if app not in moved} if isinstance(following, dict) else {}
prior_auto = {app: name for app, name in prior_auto.items() if app not in moved}
current.update(moved)
requests = COMPAT["settled_game_requests"](state, current, catalog)
overrides = COMPAT["requested_games"](requests or {}, catalog, [t["name"] for t in live])
overrides = COMPAT["requested_games"](requests or {}, catalog, listed)
overrides = {app: tool for app, tool in overrides.items() if app not in refused}
changes, auto = COMPAT["plan_mapping"](
current, installed, [t["name"] for t in live], default,
current, installed, listed, default,
COMPAT["followers"](state, current), native, picks, overrides,
prior_auto.keys(), native_choices)
prior_auto.keys(), native_choices, tools)
changes = dict(moved, **changes)
for app, tool in sorted(changes.items(), key=lambda item: COMPAT["app_order"](item[0])):
page.compat("set(%d, %s)" % (int(app), json.dumps(tool if tool is not None else "")))
say("%s -> %s" % ("default" if app == "0" else "app %s" % app,
@@ -1293,7 +1336,8 @@ def main():
failures += 1
time.sleep(min(2 * max(failures, 1), 10))
os.makedirs(COMPAT["COMPAT_DIR"], exist_ok=True)
watcher = Watcher([COMPAT["state_path"]("request.json"), COMPAT["state_path"]("games.json")] +
watcher = Watcher([COMPAT["state_path"]("request.json"), COMPAT["state_path"]("games.json"),
os.path.join(steam_root, "appcache", "appinfo.vdf")] +
[os.path.join(lib, "steamapps", "libraryfolders.vdf") for lib in (steam_root, COMPAT["LIBRARY"] + "-sd")])
steamos = os.environ.get("BL_STEAMDECK") == "1" and os.environ.get("BL_STEAM_UI") != "desktop"
helper = Helper(steam_root, port, steamos)
@@ -5,6 +5,7 @@ import binascii
import json
import os
import re
import shutil
import sys
import time
import subprocess
@@ -352,6 +353,7 @@ def prepare_gog(sidecar, compat_data, launch_dir):
GOG_SCRIPTS = "goggame-*.script"
GOG_REGISTRY_MARK = ".droiddeck-gog-registry"
GOG_SUPPORT_MARK = ".droiddeck-gog-support"
GOG_ROOTS = {"HKEY_LOCAL_MACHINE": "HKEY_LOCAL_MACHINE", "HKLM": "HKEY_LOCAL_MACHINE",
"HKEY_CURRENT_USER": "HKEY_CURRENT_USER", "HKCU": "HKEY_CURRENT_USER",
"HKEY_CLASSES_ROOT": "HKEY_CLASSES_ROOT", "HKCR": "HKEY_CLASSES_ROOT"}
@@ -611,6 +613,120 @@ def apply_gog_registry(folder, compat_data, proton, timeout=90, installation=Non
return "import-failed" + note
def gog_support_actions(folder):
found = []
for script in sorted(Path(folder).glob(GOG_SCRIPTS)):
product = script.name[len("goggame-"):-len(".script")]
try:
actions = json.loads(script.read_text(encoding="utf-8-sig")).get("actions")
except (OSError, ValueError, AttributeError):
continue
for action in actions if isinstance(actions, list) else []:
install = action.get("install") if isinstance(action, dict) else None
if isinstance(install, dict) and install.get("action") == "supportData" \
and isinstance(install.get("arguments"), dict):
found.append((product, install["arguments"]))
return found
def gog_support_bases(folder, product, pfx):
user = Path(pfx) / "drive_c" / "users" / "steamuser"
support = Path(folder) / "support" / product
return {"app": Path(folder), "supportdir": support, "support": support,
"userdocs": user / "Documents", "localappdata": user / "AppData" / "Local"}
def gog_inside(path, base):
root = os.path.realpath(base)
real = os.path.realpath(path)
return real == root or real.startswith(root + os.sep)
def gog_support_path(text, bases):
match = re.fullmatch(r"\{(\w+)\}(.*)", text) if isinstance(text, str) else None
if not match or match.group(1).lower() not in bases:
return None
parts = [part for part in re.split(r"[\\/]+", match.group(2)) if part]
if any(part in (".", "..") for part in parts):
return None
base = bases[match.group(1).lower()]
path = base
for part in parts:
exact = path / part
if not exact.exists() and path.is_dir():
exact = next((child for child in path.iterdir() if child.name.lower() == part.lower()), exact)
path = exact
if path != base and not gog_inside(path.parent, base):
return None
return path, base
def gog_copy_file(source, target, root):
if not gog_inside(target.parent, root):
raise OSError("outside " + str(root))
target.parent.mkdir(parents=True, exist_ok=True)
if target.is_symlink():
target.unlink()
shutil.copy2(source, target, follow_symlinks=False)
def gog_support_data(folder, compat_data, proton):
actions = gog_support_actions(folder)
if not actions:
return "none"
pfx = Path(compat_data) / "pfx" if compat_data else None
if not pfx or not (pfx / "drive_c" / "users" / "steamuser").is_dir():
made = create_prefix(compat_data, proton)
if made not in ("present", "created") or not (pfx / "drive_c" / "users" / "steamuser").is_dir():
return "no-prefix"
stamp = hashlib.sha256(json.dumps(actions, sort_keys=True).encode("utf-8")).hexdigest()
marker = pfx / GOG_SUPPORT_MARK
try:
if marker.is_file() and marker.read_text() == stamp:
return "ready"
except OSError:
pass
copied = skipped = missing = 0
for product, arguments in actions:
bases = gog_support_bases(folder, product, pfx)
found = gog_support_path(arguments.get("target"), bases)
origin = gog_support_path(arguments["source"], bases) if "source" in arguments else None
if found is None or ("source" in arguments and origin is None):
skipped += 1
continue
target, root = found
source = origin[0] if origin else None
try:
if source is None:
target.mkdir(parents=True, exist_ok=True)
elif not source.exists():
missing += 1
elif source.is_dir() and not source.is_symlink():
for top, dirs, files in os.walk(source):
for name in sorted(files + [d for d in dirs if (Path(top) / d).is_symlink()]):
item = Path(top) / name
destination = target / item.relative_to(source)
if (destination.exists() or destination.is_symlink()) and not arguments.get("overwrite"):
continue
gog_copy_file(item, destination, root)
copied += 1
target.mkdir(parents=True, exist_ok=True)
elif (target.exists() or target.is_symlink()) and not arguments.get("overwrite"):
continue
else:
gog_copy_file(source, target, root)
copied += 1
except OSError:
skipped += 1
note = "".join(" %s=%d" % (name, count) for name, count in (("skipped", skipped), ("missing", missing)) if count)
if not skipped:
try:
marker.write_text(stamp)
except OSError:
pass
return "copied=%d%s" % (copied, note)
def main(argv):
if os.environ.get("DROIDDECK_GOG_MAINTENANCE") == "1":
return 0
@@ -654,6 +770,7 @@ def main(argv):
if store == "gog":
prepare_gog(sidecar, compat_data, launch_dir)
log("gog registry: " + apply_gog_registry(folder, compat_data, os.environ.get("BL_STORE_PROTON", "")))
log("gog support data: " + gog_support_data(folder, compat_data, os.environ.get("BL_STORE_PROTON", "")))
if store == "epic":
handled = os.environ.get(EPIC_HANDLED) == "1" and (folder / EPIC_ARGS).is_file()
if not handled:
@@ -16,6 +16,8 @@ LEGACY_LAUNCHER = "bannerlator-proton"
LIBRARY = "/mnt/droiddeck"
SOURCES = ("Proton Experimental (ARM64)", "Proton 11.0 (ARM64)")
OWN_TOOLS = ((TOOL, SOURCES), (TOOL_11, ("Proton 11.0 (ARM64)",)))
VALVE_DEPOTS = {"proton_experimental": SOURCES[0], "proton-experimental-arm64": SOURCES[0],
"proton_11": SOURCES[1], "proton_11-arm64": SOURCES[1]}
FEX_TOOL = "droiddeck-fex"
FEX_LAUNCHER = "droiddeck-fex-tool"
FEX_FILES = ("toolmanifest.vdf", "compatibilitytool.vdf", FEX_LAUNCHER)
@@ -732,6 +734,7 @@ def libraries(steam_root):
def installed_apps(steam_root):
entries = appinfo_entries(os.path.join(steam_root, "appcache", "appinfo.vdf"))
apps = set()
for library in libraries(steam_root):
steamapps = os.path.join(library, "steamapps")
@@ -741,7 +744,7 @@ def installed_apps(steam_root):
continue
for name in names:
m = re.fullmatch(r"appmanifest_(\d+)\.acf", name)
if m and m.group(1) not in NOT_GAMES:
if m and m.group(1) not in NOT_GAMES and entries.get(m.group(1), {}).get("type") != "tool":
apps.add(m.group(1))
return sorted(apps, key=int)
@@ -925,6 +928,12 @@ def valve_picks(steam_root):
return sorted(picks, key=int)
def tool_platforms(steam_root):
entries = appinfo_entries(os.path.join(steam_root, "appcache", "appinfo.vdf"))
return {app: entry["oslist"] for app, entry in entries.items()
if entry["type"] == "tool" and entry["oslist"] & {"linux", "windows"}}
def native_targets(steam_root, apps):
wanted = {str(app) for app in apps if str(app) not in NOT_GAMES}
if not wanted:
@@ -1062,10 +1071,11 @@ NATIVE_CHOICE = object()
def plan_mapping(current, installed, runnable, default, auto, native=None, picks=(), overrides=None, managed=None,
native_choices=()):
native_choices=(), tools=None):
tools = tools or {}
runnable = {n.lower() for n in runnable}
installed = set(installed)
picks = set(picks)
picks = set(picks) | {app for app, platforms in tools.items() if "linux" not in platforms}
native = native or {}
overrides = overrides or {}
managed = set(auto) if managed is None else set(managed)
@@ -1073,8 +1083,12 @@ def plan_mapping(current, installed, runnable, default, auto, native=None, picks
changes, kept = {}, {}
if current.get("0", "") != default:
changes["0"] = default
for app in sorted((set(current) | installed | picks | set(auto) | set(overrides) | native_choices) - {"0"}, key=app_order):
for app in sorted((set(current) | installed | picks | set(auto) | set(overrides) | native_choices | set(tools)) - {"0"}, key=app_order):
name = current.get(app, "")
if app in tools and "linux" in tools[app] and "windows" not in tools[app]:
if name and (name.lower() in runnable or "proton" in name.lower()):
changes[app] = None
continue
if app in overrides:
target = overrides[app]
if target is DEFERRED_GAME_TOOL:
@@ -1160,6 +1174,18 @@ def tool_catalog(steam_root, extras=None):
return catalog
def built_from(name, catalog, runnable=None):
depot = VALVE_DEPOTS.get(name)
tools = [t["name"] for t in catalog if depot and t["valve"] and t["dir"] == depot and
(runnable is None or t["name"] in runnable)]
return tools[-1] if tools else None
def rebuilt_picks(current, catalog, known, runnable=None):
picks = {app: built_from(name, catalog, runnable) for app, name in current.items() if app in known}
return {app: tool for app, tool in picks.items() if tool}
def requested_tool(request, catalog):
name = request.get("name")
if isinstance(name, str) and any(t["name"] == name for t in catalog):
@@ -1513,7 +1539,8 @@ def register_default(config_path, apps=(), protect=(), default=None, catalog=Non
state["owned"] = sorted(set(owned), key=app_order)
if default is None:
if settle:
default, state = choose_default(current.get("0", ""), state, read_json(state_path("request.json", directory)), catalog)
default, state = choose_default(built_from(current.get("0", ""), catalog) or current.get("0", ""), state,
read_json(state_path("request.json", directory)), catalog)
else:
default = state.get("default") if state.get("default") in names else TOOL
if settle and newest and default == TOOL and state.get("source") not in ("app", "steam"):
@@ -1526,6 +1553,13 @@ def register_default(config_path, apps=(), protect=(), default=None, catalog=Non
current.update(replacements)
if isinstance(state.get("auto"), dict):
state["auto"] = {app: newest if name in gone else name for app, name in state["auto"].items()}
following = followers(state, current)
following = following if isinstance(following, dict) else {}
moved = rebuilt_picks(current, catalog, set(following) | picked_apps(state))
if moved:
state["auto"] = {app: name for app, name in following.items() if app not in moved}
set_mappings(tokens, mapping, moved)
current.update(moved)
steam_root = os.path.dirname(os.path.dirname(os.path.abspath(config_path)))
requests = settled_game_requests(state, current, catalog, not steam_running(), directory)
overrides = requested_games(requests or {}, catalog)
@@ -1538,7 +1572,7 @@ def register_default(config_path, apps=(), protect=(), default=None, catalog=Non
current.setdefault(app, "")
changes, auto = plan_mapping(
current, apps, names, default, followers(state, current), native, picks,
overrides, managed, native_choices)
overrides, managed, native_choices, tool_platforms(steam_root))
set_mappings(tokens, mapping, changes)
text = serialize(tokens)
if text != serialize(tokenize(original)):
+28
View File
@@ -29,6 +29,7 @@
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/uio.h>
#include <sys/un.h>
#include <time.h>
#include <unistd.h>
@@ -1655,6 +1656,7 @@ static void reply_attr(struct nl_reply *out, unsigned char *message, int type,
return;
}
attr = (struct rtattr *) (message + offset);
memset(attr, 0, total);
attr->rta_type = (unsigned short) type;
attr->rta_len = (unsigned short) RTA_LENGTH(len);
if (len > 0) memcpy(RTA_DATA(attr), data, len);
@@ -2155,3 +2157,29 @@ ssize_t send(int fd, const void *buffer, size_t length, int flags) {
}
return real(fd, buffer, length, flags);
}
ssize_t write(int fd, const void *buffer, size_t length) {
static ssize_t (*real)(int, const void *, size_t);
ssize_t rc;
if (bl_nl_owns(fd) && deliver(fd, buffer, length, 0, &rc)) return rc;
if (real == NULL) real = (ssize_t (*)(int, const void *, size_t)) dlsym(RTLD_NEXT, "write");
if (real == NULL) {
errno = ENOSYS;
return -1;
}
return real(fd, buffer, length);
}
ssize_t writev(int fd, const struct iovec *iov, int iovcnt) {
static ssize_t (*real)(int, const struct iovec *, int);
if (iovcnt >= 0 && bl_nl_owns(fd)) {
struct msghdr msg = { .msg_iov = (struct iovec *) iov, .msg_iovlen = (size_t) iovcnt };
return sendmsg_request(fd, &msg, 0);
}
if (real == NULL) real = (ssize_t (*)(int, const struct iovec *, int)) dlsym(RTLD_NEXT, "writev");
if (real == NULL) {
errno = ENOSYS;
return -1;
}
return real(fd, iov, iovcnt);
}
+20
View File
@@ -142,6 +142,26 @@ Prototype (inert unless `PROOT_FASTPATH` is set; see `docs/development/proot-per
`statx` (`newfstatat`) and `memfd_create`. Syscalls outside the trampoline and sessions
without `PROOT_FASTPATH` are unchanged. `bench/statx-trap.c` traps `statx` and checks an
existing directory still reads as one.
- `0026-arm64-kernel-program-layout.patch` - on ARM64, PRoot put its loader at 128 GiB, a PIE
program at 192 GiB and its interpreter at 252 GiB. Android kernels give a process a 39-bit
(512 GiB) address space, so those three split the low half into holes of 64 GiB or less, and a
program that reserves one large contiguous range there could not get it. The Linux kernel loads
a PIE program at two thirds of the address space (`ELF_ET_DYN_BASE`, 0x5555555000 with 39 bits)
and keeps the range below it free; the loader, program and interpreter now sit there too, which
leaves 64 GiB to 336 GiB free as on a native kernel. Switch emulators that run guest code
natively reserve 256 GiB above 64 GiB for guest memory: under PRoot the reservation failed and
the first guest instruction faulted forever. 48-bit address spaces and 32-bit programs are
unchanged in practice.
- `0027-guest-seccomp-sigsys.patch` - PRoot treated every seccomp `SIGSYS` as Android's app policy
refusing a call: it emulated the few it knows and answered the rest with `ENOSYS`, so a filter
the guest installs itself never reached its own handler. Firefox's content sandbox traps
`openat` and opens files through a broker in the parent; every font open came back `ENOSYS`,
and each tab crashed in `gfxFontGroup::GetDefaultFont`. Android's policy traps with
`SECCOMP_RET_DATA` 0, while Firefox's and Chromium's filters tag their traps, so a tagged
`SIGSYS` is now delivered to the guest. A trap from the fast path's trampoline still gets
`ENOSYS`, because its arguments are host paths; the fast path then stops for that process and
repeats the call through a plain `svc`, which the guest's filter traps with the guest path.
`bench/guest-trap.c` installs a tagged `openat` trap and checks its handler answers the call.
Old kernel fixes:
+49
View File
@@ -0,0 +1,49 @@
// Run inside a session, with and without the fast path: a seccomp filter the guest installs
// itself must reach its own SIGSYS handler, which answers the trapped openat.
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <linux/filter.h>
#include <linux/seccomp.h>
#include <signal.h>
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include <sys/prctl.h>
#include <sys/syscall.h>
#include <ucontext.h>
#include <unistd.h>
#define ANSWER 4242
static volatile int traps, data;
static void on_sigsys(int sig, siginfo_t *info, void *context) {
(void)sig;
ucontext_t *uc = context;
traps++;
data = info->si_errno;
uc->uc_mcontext.regs[0] = ANSWER;
}
int main(void) {
struct sigaction sa;
memset(&sa, 0, sizeof sa);
sa.sa_sigaction = on_sigsys;
sa.sa_flags = SA_SIGINFO;
sigaction(SIGSYS, &sa, NULL);
struct sock_filter code[] = {
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, nr)),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SYS_openat, 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_TRAP | 7),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
};
struct sock_fprog filter = {.len = sizeof code / sizeof *code, .filter = code};
if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) || prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &filter, 0, 0)) {
perror("seccomp");
return 77;
}
int fd = open("/etc/hostname", O_RDONLY);
int err = errno;
printf("open=%d errno=%d traps=%d data=%d\n", fd, fd < 0 ? err : 0, traps, data);
return fd == ANSWER && traps == 1 && data == 7 ? 0 : 1;
}
+274 -33
View File
@@ -41,7 +41,7 @@ typedef long (*stub_fn)(long nr, long a, long b, long c, long d, long e, long f)
static stub_fn fp_sys;
static int fp_on;
struct bind { char *host; size_t hlen; char *guest; size_t glen; int canon; int dropped; };
struct bind { char *host; size_t hlen; char *guest; size_t glen; int canon; int dropped; int fuse; };
static struct bind binds[MAX_BINDS];
static int nbinds;
static char root[PATH_MAX];
@@ -49,7 +49,30 @@ static size_t rootlen;
static long long ttl_ns = 2000000000LL;
static unsigned long hits, misses;
static long sc(long nr, long a, long b, long c, long d, long e) { return fp_sys(nr, a, b, c, d, e, 0); }
// A seccomp filter the guest installs itself (Firefox's content sandbox) can trap a trampoline
// syscall that the host allows; proot answers those with ENOSYS. The call is then repeated
// through libc, where the guest's own SIGSYS handler sees the guest path, and the process stops
// using the fast path.
static __thread int fp_refused;
static int optional_syscall(long nr) {
return nr == SYS_statx || nr == SYS_memfd_create || nr == SYS_faccessat2 || nr == SYS_close_range ||
nr == SYS_openat2 || nr == SYS_renameat2;
}
static long sc(long nr, long a, long b, long c, long d, long e) {
if (fp_refused && nr != SYS_close) return -ENOSYS;
long r = fp_sys(nr, a, b, c, d, e, 0);
if (r == -ENOSYS && !optional_syscall(nr)) {
if (fp_sys(nr, -1, -1, -1, -1, -1, 0) == -ENOSYS) __atomic_store_n(&fp_on, 0, __ATOMIC_RELAXED);
fp_refused = 1;
}
return r;
}
static inline int refused(void) {
if (!fp_refused) return 0;
fp_refused = 0;
return 1;
}
static inline int answered(long r) { return !refused() && r != FP_SLOW; }
static void fp_init(void);
static pthread_once_t init_once = PTHREAD_ONCE_INIT;
static inline int fp_ready(void) {
@@ -110,7 +133,8 @@ static long tracer;
static pthread_mutex_t cache_lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t bind_lock;
static pthread_mutex_t long_lock;
static void after_fork(void) { pthread_mutex_init(&cache_lock, NULL); pthread_mutex_init(&bind_lock, NULL); pthread_mutex_init(&long_lock, NULL); }
static pthread_mutex_t dir_lock = PTHREAD_MUTEX_INITIALIZER;
static void after_fork(void) { pthread_mutex_init(&cache_lock, NULL); pthread_mutex_init(&bind_lock, NULL); pthread_mutex_init(&long_lock, NULL); pthread_mutex_init(&dir_lock, NULL); }
static int traced_by_match(const char *key) {
static char buf[32768];
@@ -391,6 +415,207 @@ static int host_bind(const char *h) {
return -1;
}
static unsigned hash_of(const char *s);
#define DIRS 64
#define DIR_FD_FLOOR 1000
struct dirslot { unsigned hash, epoch; int fd, refs; dev_t dev; ino_t ino; long tag; char path[PATH_MAX]; char seen[PATH_MAX]; };
static struct dirslot dirs[DIRS];
static unsigned dir_epoch;
struct near { long fd; int slot, own; const char *name; };
static int fuse_bind(const char *h) {
int i = host_bind(h);
if (i < 0) return -1;
int f = __atomic_load_n(&binds[i].fuse, __ATOMIC_ACQUIRE);
if (!f) {
struct statfs fs;
f = sc(SYS_statfs, (long)binds[i].host, (long)&fs, 0, 0, 0) == 0 && fs.f_type == 0x65735546 ? 1 : 2;
__atomic_store_n(&binds[i].fuse, f, __ATOMIC_RELEASE);
}
return f == 1 ? i : -1;
}
static long fd_path(long fd, char *out) {
char link[40];
snprintf(link, sizeof link, "/proc/self/fd/%ld", fd);
long n = sc(SYS_readlinkat, AT_FDCWD, (long)link, (long)out, PATH_MAX - 1, 0);
if (n <= 0 || n >= PATH_MAX - 1) return -1;
out[n] = 0;
return 0;
}
static int fd_id(long fd, dev_t *dev, ino_t *ino) {
struct stat st;
if (sc(SYS_newfstatat, fd, (long)"", (long)&st, AT_EMPTY_PATH, 0) != 0) return -1;
*dev = st.st_dev;
*ino = st.st_ino;
return 0;
}
static long dir_tag(void) {
static uint64_t state;
uint64_t z = __atomic_add_fetch(&state, 0x9e3779b97f4a7c15ULL, __ATOMIC_RELAXED), seed = 0;
const void *random = (const void *)getauxval(AT_RANDOM);
if (random) memcpy(&seed, random, sizeof seed);
z += seed;
z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ULL;
z = (z ^ (z >> 27)) * 0x94d049bb133111ebULL;
return (long)((z ^ (z >> 31)) & 0xffffffffffULL) + 1;
}
static int dir_owned(const struct dirslot *e) {
dev_t dev;
ino_t ino;
return e->fd > 0 && sc(SYS_lseek, e->fd, 0, SEEK_CUR, 0, 0) == e->tag
&& fd_id(e->fd, &dev, &ino) == 0 && dev == e->dev && ino == e->ino;
}
static int dir_fresh(const struct dirslot *e, const char *dir) {
struct stat st;
if (sc(SYS_newfstatat, AT_FDCWD, (long)dir, (long)&st, 0, 0) != 0 || st.st_dev != e->dev || st.st_ino != e->ino) {
__atomic_add_fetch(&dir_epoch, 1, __ATOMIC_RELEASE);
return 0;
}
return 1;
}
static void dirs_drop(const char *host) {
size_t len = strlen(host);
if (pthread_mutex_trylock(&dir_lock) != 0) {
__atomic_add_fetch(&dir_epoch, 1, __ATOMIC_RELEASE);
return;
}
for (int i = 0; i < DIRS; i++)
if (dirs[i].path[0] && under(dirs[i].path, host, len)) dirs[i].path[0] = 0;
pthread_mutex_unlock(&dir_lock);
}
static void near_put(struct near *n) {
if (n->own) sc(SYS_close, n->fd, 0, 0, 0, 0);
else if (n->slot >= 0) __atomic_sub_fetch(&dirs[n->slot].refs, 1, __ATOMIC_RELEASE);
n->fd = AT_FDCWD;
n->slot = -1;
n->own = 0;
}
static int dir_cached(const char *dir, struct near *n) {
unsigned h = hash_of(dir);
struct dirslot *e = &dirs[h % DIRS];
if (pthread_mutex_trylock(&dir_lock) != 0) return 0;
int hit = e->fd >= 0 && e->hash == h && e->path[0] && strcmp(e->path, dir) == 0
&& e->epoch == __atomic_load_n(&dir_epoch, __ATOMIC_ACQUIRE);
if (hit) __atomic_add_fetch(&e->refs, 1, __ATOMIC_ACQUIRE);
pthread_mutex_unlock(&dir_lock);
if (!hit) return 0;
char now[PATH_MAX];
if (fd_path(e->fd, now) == 0 && strcmp(now, e->seen) == 0 && dir_fresh(e, dir)) {
n->fd = e->fd;
n->slot = (int)(e - dirs);
n->own = 0;
return 1;
}
__atomic_sub_fetch(&e->refs, 1, __ATOMIC_RELEASE);
if (pthread_mutex_trylock(&dir_lock) == 0) {
if (e->hash == h && strcmp(e->path, dir) == 0) e->path[0] = 0;
pthread_mutex_unlock(&dir_lock);
}
return 0;
}
static int dir_keep(const char *dir, long fd, struct near *n) {
long high = sc(SYS_fcntl, fd, F_DUPFD_CLOEXEC, DIR_FD_FLOOR, 0, 0);
sc(SYS_close, fd, 0, 0, 0, 0);
if (high < 0) return -1;
n->fd = high;
n->slot = -1;
n->own = 1;
char seen[PATH_MAX];
dev_t dev;
ino_t ino;
long tag = dir_tag();
struct stat st;
if (fd_id(high, &dev, &ino) < 0 || strlen(dir) >= PATH_MAX
|| sc(SYS_newfstatat, AT_FDCWD, (long)dir, (long)&st, 0, 0) != 0 || st.st_dev != dev || st.st_ino != ino) {
near_put(n);
return -1;
}
if (fd_path(high, seen) < 0 || sc(SYS_lseek, high, tag, SEEK_SET, 0, 0) != tag) return 0;
unsigned h = hash_of(dir);
struct dirslot *e = &dirs[h % DIRS];
if (pthread_mutex_trylock(&dir_lock) != 0) return 0;
if (__atomic_load_n(&e->refs, __ATOMIC_ACQUIRE) == 0) {
if (dir_owned(e)) sc(SYS_close, e->fd, 0, 0, 0, 0);
e->hash = h;
e->epoch = __atomic_load_n(&dir_epoch, __ATOMIC_ACQUIRE);
e->tag = tag;
e->fd = (int)high;
e->dev = dev;
e->ino = ino;
e->refs = 1;
strcpy(e->path, dir);
strcpy(e->seen, seen);
n->slot = (int)(e - dirs);
n->own = 0;
}
pthread_mutex_unlock(&dir_lock);
return 0;
}
static int dir_get(char *dir, size_t floor, struct near *n) {
size_t len = strlen(dir), at = len;
while (!dir_cached(dir, n)) {
if (at <= floor) {
long fd = sc(SYS_openat, AT_FDCWD, (long)dir, O_RDONLY | O_DIRECTORY | O_CLOEXEC, 0, 0);
if (fd < 0 || dir_keep(dir, fd, n) < 0) return -1;
break;
}
char *slash = strrchr(dir, '/');
if (!slash || (size_t)(slash - dir) < floor) return -1;
*slash = 0;
at = slash - dir;
}
while (at < len) {
dir[at] = '/';
const char *name = dir + at + 1;
size_t next = at + 1 + strlen(name);
long fd = sc(SYS_openat, n->fd, (long)name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC, 0, 0);
near_put(n);
if (fd < 0 || dir_keep(dir, fd, n) < 0) return -1;
at = next;
}
return 0;
}
static long near_get(const char *host, struct near *n) {
n->fd = AT_FDCWD;
n->slot = -1;
n->own = 0;
n->name = host;
if (ttl_ns <= 0 || host[0] != '/') return n->fd;
int i = fuse_bind(host);
if (i < 0) return n->fd;
const char *slash = strrchr(host, '/');
size_t plen = slash - host;
if (plen < binds[i].hlen || !slash[1] || plen >= PATH_MAX) return n->fd;
char dir[PATH_MAX];
memcpy(dir, host, plen);
dir[plen] = 0;
if (dir_get(dir, binds[i].hlen, n) < 0) {
near_put(n);
return n->fd;
}
n->name = slash + 1;
return n->fd;
}
static long hsc(long nr, const char *host, long a, long b, long c) {
struct near n;
long fd = near_get(host, &n);
long rs = sc(nr, fd, (long)n.name, a, b, c);
near_put(&n);
return rs;
}
static int guest_text(const char *h, char *g) {
if (h[0] == '/' && under(h, root, rootlen)) return to_guest(h, g, PATH_MAX);
int i = h[0] == '/' ? host_bind(h) : -1;
@@ -533,7 +758,7 @@ static long proc_readlink(const struct res *r, char *text, size_t size, int *cha
return name[0] == 'e' ? own_exe(text) : own_cwd(text);
}
char h[PATH_MAX];
long t = sc(SYS_readlinkat, AT_FDCWD, (long)r->host, (long)h, sizeof h - 1, 0);
long t = hsc(SYS_readlinkat, r->host, (long)h, sizeof h - 1, 0);
if (t < 0) return t;
if (t >= (long)sizeof h - 1) return FP_SLOW;
if (size && (size_t)t > size) t = size;
@@ -556,7 +781,7 @@ static long proc_link(struct res *r, char *text, int final) {
if (!under(r->host, "/proc", 5)) return FP_SLOW;
r->moving = 1;
if (!strcmp(r->guest, "/proc/self") || !strcmp(r->guest, "/proc/thread-self")) {
long t = sc(SYS_readlinkat, AT_FDCWD, (long)r->host, (long)text, PATH_MAX - 1, 0);
long t = hsc(SYS_readlinkat, r->host, (long)text, PATH_MAX - 1, 0);
if (t <= 0 || t >= PATH_MAX - 1) return FP_SLOW;
text[t] = 0;
return t;
@@ -605,7 +830,7 @@ static long walk(struct res *r, const char *text, int follow, int last) {
if (reserved(r->guest)) return FP_SLOW;
struct bind *through;
if (to_host(r->guest, r->host, &through) < 0) return FP_SLOW;
long s = sc(SYS_newfstatat, AT_FDCWD, (long)r->host, (long)&r->st, AT_SYMLINK_NOFOLLOW, 0);
long s = hsc(SYS_newfstatat, r->host, (long)&r->st, AT_SYMLINK_NOFOLLOW, 0);
if (s < 0) {
int glue = glue_above_binding(r->guest, glen + n);
if (glue < 0) return FP_SLOW;
@@ -625,13 +850,13 @@ static long walk(struct res *r, const char *text, int follow, int last) {
t = proc_link(r, target, final && last);
if (t == FP_SLOW) return FP_SLOW;
if (t == 0) {
if (sc(SYS_newfstatat, AT_FDCWD, (long)r->host, (long)&r->st, 0, 0) < 0) return FP_SLOW;
if (hsc(SYS_newfstatat, r->host, (long)&r->st, 0, 0) < 0) return FP_SLOW;
r->magic = 1;
r->exists = 1;
return 0;
}
} else {
t = sc(SYS_readlinkat, AT_FDCWD, (long)r->host, (long)target, sizeof target - 1, 0);
t = hsc(SYS_readlinkat, r->host, (long)target, sizeof target - 1, 0);
if (t <= 0 || t >= (long)sizeof target - 1) return FP_SLOW;
target[t] = 0;
if (detranslated(target, r->host) == FP_SLOW) return FP_SLOW;
@@ -653,7 +878,7 @@ static long walk(struct res *r, const char *text, int follow, int last) {
}
if (!stated) {
if (to_host(r->guest, r->host, NULL) < 0) return FP_SLOW;
long s = sc(SYS_newfstatat, AT_FDCWD, (long)r->host, (long)&r->st, AT_SYMLINK_NOFOLLOW, 0);
long s = hsc(SYS_newfstatat, r->host, (long)&r->st, AT_SYMLINK_NOFOLLOW, 0);
if (s < 0 && strcmp(r->guest, "/") != 0 && glue_above_binding(r->guest, strlen(r->guest))) return FP_SLOW;
if (s < 0) return s == -ENOENT ? FP_SLOW : s;
}
@@ -676,7 +901,7 @@ static long bound_literal(const char *literal, struct res *r) {
struct bind *bd;
if (reserved(literal) || bind_of(literal, &bd) < 0 || !bd || bd->glen != strlen(literal) || bd->glen < 2) return FP_SLOW;
if (snprintf(r->host, PATH_MAX, "%s", bd->host) >= PATH_MAX) return FP_SLOW;
if (sc(SYS_newfstatat, AT_FDCWD, (long)r->host, (long)&r->st, AT_SYMLINK_NOFOLLOW, 0) < 0 || S_ISLNK(r->st.st_mode)) return FP_SLOW;
if (hsc(SYS_newfstatat, r->host, (long)&r->st, AT_SYMLINK_NOFOLLOW, 0) < 0 || S_ISLNK(r->st.st_mode)) return FP_SLOW;
snprintf(r->guest, PATH_MAX, "%s", literal);
r->exists = 1;
r->moving = 0;
@@ -788,7 +1013,7 @@ static int ret(long r) {
if (!real_##name) real_##name = (type)dlsym(RTLD_NEXT, #name)
#define ANSWER(r, dirfd, path, real_call) \
do { long r_ = (r); if (r_ != FP_SLOW) { hits++; return ret(r_); } missed(__func__, dirfd, path); return real_call; } while (0)
do { long r_ = (r); if (answered(r_)) { hits++; return ret(r_); } missed(__func__, dirfd, path); return real_call; } while (0)
static long fp_open(int dirfd, const char *path, int flags, mode_t mode) {
@@ -799,13 +1024,13 @@ static long fp_open(int dirfd, const char *path, int flags, mode_t mode) {
long rs = resolve(dirfd, path, follow | MAY_BE_UNSEEN, &r);
if (rs < 0) return rs;
if (rs == 1 && !(flags & O_CREAT)) return -ENOENT;
if (rs == UNSEEN) return sc(SYS_openat, AT_FDCWD, (long)r.host, flags, (flags & O_CREAT) ? mode : 0, 0);
return sc(SYS_openat, AT_FDCWD, (long)r.host, flags | (follow && !r.magic ? O_NOFOLLOW : 0), (flags & O_CREAT) ? mode : 0, 0);
if (rs == UNSEEN) return hsc(SYS_openat, r.host, flags, (flags & O_CREAT) ? mode : 0, 0);
return hsc(SYS_openat, r.host, flags | (follow && !r.magic ? O_NOFOLLOW : 0), (flags & O_CREAT) ? mode : 0, 0);
}
static int do_openat(int dirfd, const char *path, int flags, mode_t mode, int (*real)(int, const char *, int, ...)) {
long r = fp_open(dirfd, path, flags, mode);
if (r != FP_SLOW) { hits++; return ret(r); }
if (answered(r)) { hits++; return ret(r); }
missed(__func__, dirfd, path);
return real(dirfd, path, flags, mode);
}
@@ -841,7 +1066,7 @@ static long fp_stat(int dirfd, const char *path, int flags, struct stat *st) {
long rs = resolve(dirfd, path, (flags & AT_SYMLINK_NOFOLLOW ? 0 : 1) | MAY_BE_UNSEEN, &r);
if (rs < 0) return rs;
if (rs == 1) return -ENOENT;
if (rs == UNSEEN) return sc(SYS_newfstatat, AT_FDCWD, (long)r.host, (long)st, flags, 0);
if (rs == UNSEEN) return hsc(SYS_newfstatat, r.host, (long)st, flags, 0);
*st = r.st;
return 0;
}
@@ -870,8 +1095,10 @@ int lstat64(const char *p, struct stat64 *st) { return lstat(p, (struct stat *)s
int fstat(int fd, struct stat *st) {
REAL(fstat, int (*)(int, struct stat *));
if (!fp_ready()) return real_fstat(fd, st);
long r = sc(SYS_fstat, fd, (long)st, 0, 0, 0);
if (!answered(r)) return real_fstat(fd, st);
hits++;
return ret(sc(SYS_fstat, fd, (long)st, 0, 0, 0));
return ret(r);
}
int fstat64(int fd, struct stat64 *st) { return fstat(fd, (struct stat *)st); }
@@ -982,14 +1209,14 @@ static long fp_access(int dirfd, const char *path, int mode, int flags) {
? resolve(dirfd, path, (flags & AT_SYMLINK_NOFOLLOW ? 0 : 1) | MAY_BE_UNSEEN, &r) : FP_SLOW;
if (rs == 1) rs = -ENOENT;
if (rs == 0 && S_ISLNK(r.st.st_mode)) rs = FP_SLOW;
if (rs == 0 || rs == UNSEEN) rs = sc(SYS_faccessat, AT_FDCWD, (long)r.host, mode, 0, 0);
if (rs == 0 || rs == UNSEEN) rs = hsc(SYS_faccessat, r.host, mode, 0, 0);
return rs;
}
static int access_common(int dirfd, const char *path, int mode, int flags) {
REAL(faccessat, int (*)(int, const char *, int, int));
long rs = fp_access(dirfd, path, mode, flags);
if (rs != FP_SLOW) { hits++; return ret(rs); }
if (answered(rs)) { hits++; return ret(rs); }
missed(__func__, dirfd, path);
if (flags == 0) return (int)syscall(SYS_faccessat, dirfd, path, mode);
return real_faccessat(dirfd, path, mode, flags);
@@ -1005,7 +1232,7 @@ static long link_text(const struct res *r, char *text, size_t size, int *changed
*changed = 0;
if (in_proc != under(r->host, "/proc", 5)) return FP_SLOW;
if (in_proc) return proc_readlink(r, text, size, changed);
long t = sc(SYS_readlinkat, AT_FDCWD, (long)r->host, (long)text, PATH_MAX - 1, 0);
long t = hsc(SYS_readlinkat, r->host, (long)text, PATH_MAX - 1, 0);
if (t < 0) return t;
if (t >= PATH_MAX - 1) return FP_SLOW;
if (size && (size_t)t > size) t = size;
@@ -1087,7 +1314,7 @@ char *canonicalize_file_name(const char *path) { return realpath(path, NULL); }
char *getcwd(char *buf, size_t size) {
REAL(getcwd, char *(*)(char *, size_t));
char g[PATH_MAX];
if (!fp_ready() || own_cwd(g) == FP_SLOW) { missed(__func__, AT_FDCWD, "."); return real_getcwd(buf, size); }
if (!fp_ready() || own_cwd(g) == FP_SLOW || refused()) { missed(__func__, AT_FDCWD, "."); return real_getcwd(buf, size); }
hits++;
size_t need = strlen(g) + 1;
if (buf && size == 0) { errno = EINVAL; return NULL; }
@@ -1110,7 +1337,7 @@ char *__getcwd_chk(char *buf, size_t size, size_t room) {
static long fp_mkdir(int dirfd, const char *path, mode_t mode) {
struct res r;
long rs = resolve(dirfd, path, MAY_BE_UNSEEN, &r);
if (rs == 0 || rs == 1 || rs == UNSEEN) rs = sc(SYS_mkdirat, AT_FDCWD, (long)r.host, mode, 0, 0);
if (rs == 0 || rs == 1 || rs == UNSEEN) rs = hsc(SYS_mkdirat, r.host, mode, 0, 0);
return rs;
}
int mkdirat(int dirfd, const char *path, mode_t mode) {
@@ -1147,7 +1374,7 @@ static long fp_unlink(int dirfd, const char *path, int flags) {
if (rs == 0 && (flags & AT_REMOVEDIR) && strcmp(r.guest, "/") == 0) rs = FP_SLOW;
if (rs == 0 || rs == UNSEEN) {
int changes_paths = (flags & AT_REMOVEDIR) || rs == UNSEEN || S_ISLNK(r.st.st_mode);
rs = sc(SYS_unlinkat, AT_FDCWD, (long)r.host, flags, 0, 0);
rs = hsc(SYS_unlinkat, r.host, flags, 0, 0);
if (rs == 0 && changes_paths) forget();
}
return rs;
@@ -1171,9 +1398,14 @@ static long fp_rename(int olddirfd, const char *old, int newdirfd, const char *n
if (rt < 0) rs = rt;
else if (rt == 0 && S_ISDIR(to.st.st_mode)) rs = FP_SLOW;
else {
rs = flags ? sc(SYS_renameat2, AT_FDCWD, (long)from.host, AT_FDCWD, (long)to.host, flags)
: sc(SYS_renameat, AT_FDCWD, (long)from.host, AT_FDCWD, (long)to.host, 0);
if (rs == 0) forget();
struct near a, b;
near_get(from.host, &a);
near_get(to.host, &b);
rs = flags ? sc(SYS_renameat2, a.fd, (long)a.name, b.fd, (long)b.name, flags)
: sc(SYS_renameat, a.fd, (long)a.name, b.fd, (long)b.name, 0);
near_put(&a);
near_put(&b);
if (rs == 0 && (S_ISLNK(from.st.st_mode) || (rt == 0 && S_ISLNK(to.st.st_mode)))) forget();
}
}
return rs;
@@ -1181,7 +1413,7 @@ static long fp_rename(int olddirfd, const char *old, int newdirfd, const char *n
static int rename_common(int olddirfd, const char *old, int newdirfd, const char *new, unsigned flags) {
REAL(renameat2, int (*)(int, const char *, int, const char *, unsigned));
long rs = fp_rename(olddirfd, old, newdirfd, new, flags);
if (rs != FP_SLOW) { hits++; return ret(rs); }
if (answered(rs)) { hits++; return ret(rs); }
missed(__func__, olddirfd, old);
if (!flags) return (int)syscall(SYS_renameat, olddirfd, old, newdirfd, new);
return real_renameat2(olddirfd, old, newdirfd, new, flags);
@@ -1211,7 +1443,10 @@ static long fp_chmod(int dirfd, const char *path, mode_t mode, int flags) {
struct res r;
long rs = flags ? FP_SLOW : resolve(dirfd, path, 1 | MAY_BE_UNSEEN, &r);
if (rs == 1) rs = -ENOENT;
if (rs == 0 || rs == UNSEEN) rs = sc(SYS_fchmodat, AT_FDCWD, (long)r.host, mode, 0, 0);
if (rs == 0 || rs == UNSEEN) {
rs = hsc(SYS_fchmodat, r.host, mode, 0, 0);
if (rs == 0) dirs_drop(r.host);
}
return rs;
}
int fchmodat(int dirfd, const char *path, mode_t mode, int flags) {
@@ -1224,7 +1459,10 @@ static long fp_chown(int dirfd, const char *path, uid_t uid, gid_t gid, int flag
struct res r;
long rs = flags & ~AT_SYMLINK_NOFOLLOW ? FP_SLOW : resolve(dirfd, path, (flags & AT_SYMLINK_NOFOLLOW ? 0 : 1) | MAY_BE_UNSEEN, &r);
if (rs == 1) rs = -ENOENT;
if (rs == 0 || rs == UNSEEN) rs = sc(SYS_fchownat, AT_FDCWD, (long)r.host, (long)uid, (long)gid, flags);
if (rs == 0 || rs == UNSEEN) {
rs = hsc(SYS_fchownat, r.host, (long)uid, (long)gid, flags);
if (rs == 0) dirs_drop(r.host);
}
return rs;
}
int fchownat(int dirfd, const char *path, uid_t uid, gid_t gid, int flags) {
@@ -1242,7 +1480,7 @@ static long fp_utimens(int dirfd, const char *path, const struct timespec times[
} else {
rs = flags & ~AT_SYMLINK_NOFOLLOW ? FP_SLOW : resolve(dirfd, path, (flags & AT_SYMLINK_NOFOLLOW ? 0 : 1) | MAY_BE_UNSEEN, &r);
if (rs == 1) rs = -ENOENT;
if (rs == 0 || rs == UNSEEN) rs = sc(SYS_utimensat, AT_FDCWD, (long)r.host, (long)times, flags, 0);
if (rs == 0 || rs == UNSEEN) rs = hsc(SYS_utimensat, r.host, (long)times, flags, 0);
}
return rs;
}
@@ -1355,7 +1593,7 @@ static long fp_getxattr(const char *path, const char *name, void *value, size_t
static ssize_t getxattr_common(const char *path, const char *name, void *value, size_t size, int follow,
ssize_t (*real)(const char *, const char *, void *, size_t)) {
long rs = fp_getxattr(path, name, value, size, follow);
if (rs != FP_SLOW) { hits++; return rs < 0 ? ret(rs) : rs; }
if (answered(rs)) { hits++; return rs < 0 ? ret(rs) : rs; }
missed(__func__, AT_FDCWD, path);
return real(path, name, value, size);
}
@@ -1378,7 +1616,7 @@ static long fp_listxattr(const char *path, char *list, size_t size, int follow)
static ssize_t listxattr_common(const char *path, char *list, size_t size, int follow,
ssize_t (*real)(const char *, char *, size_t)) {
long rs = fp_listxattr(path, list, size, follow);
if (rs != FP_SLOW) { hits++; return rs < 0 ? ret(rs) : rs; }
if (answered(rs)) { hits++; return rs < 0 ? ret(rs) : rs; }
missed(__func__, AT_FDCWD, path);
return real(path, list, size);
}
@@ -1484,7 +1722,7 @@ static long socket_address(const struct sockaddr *addr, socklen_t len, int follo
char *slash = strrchr(r.host, '/');
if (!slash || slash == r.host) return FP_SLOW;
*slash = 0;
*dir = sc(SYS_openat, AT_FDCWD, (long)r.host, O_PATH | O_DIRECTORY | O_CLOEXEC, 0, 0);
*dir = hsc(SYS_openat, r.host, O_PATH | O_DIRECTORY | O_CLOEXEC, 0, 0);
if (*dir < 0) return FP_SLOW;
hlen = snprintf(out->sun_path, room, "/proc/self/fd/%ld/%s", *dir, slash + 1);
if (hlen >= room) { sc(SYS_close, *dir, 0, 0, 0, 0); *dir = -1; return FP_SLOW; }
@@ -1581,6 +1819,7 @@ static int accept_common(int fd, struct sockaddr *addr, socklen_t *len, int flag
struct sockaddr_storage got;
socklen_t got_len = sizeof got;
long r = sc(SYS_accept4, fd, addr ? (long)&got : 0, addr ? (long)&got_len : 0, flags, 0);
if (refused()) return real_accept4(fd, addr, len, flags);
if (r >= 0) inherit_long_name(fd, (int)r);
if (!addr) return ret(r);
if (r >= 0) report_address((int)r, LONG_PEER, &got, got_len, addr, len);
@@ -1595,6 +1834,7 @@ static int name_common(long nr, int fd, struct sockaddr *addr, socklen_t *len, i
struct sockaddr_storage got;
socklen_t got_len = sizeof got;
long r = sc(nr, fd, (long)&got, (long)&got_len, 0, 0);
if (refused()) return real(fd, addr, len);
if (r == 0) report_address(fd, nr == SYS_getsockname ? LONG_SELF : LONG_PEER, &got, got_len, addr, len);
return ret(r);
}
@@ -1687,7 +1927,7 @@ static int online_cpus(void) {
int get_nprocs(void) {
REAL(get_nprocs, int (*)(void));
int n = fp_ready() ? online_cpus() : -1;
if (n > 0) { hits++; return n; }
if (n > 0 && !refused()) { hits++; return n; }
missed(__func__, AT_FDCWD, "(nprocs)");
return real_get_nprocs();
}
@@ -1743,6 +1983,7 @@ int isatty(int fd) {
if (!fp_ready()) return real_isatty(fd);
hits++;
long r = sc(SYS_ioctl, fd, TCGETS, (long)&k, 0, 0);
if (refused()) return real_isatty(fd);
if (r < 0) { errno = (int)-r; return 0; }
return r == 0;
}
+6 -3
View File
@@ -74,11 +74,14 @@ long fp_svc_dispatch(const long *r) {
int saved_errno = errno;
long result = svc_blocked(r);
uintptr_t frame = (uintptr_t)r;
if (result == FP_SLOW && (!svc_busy || frame >= svc_busy)) {
if (result == FP_SLOW && __atomic_load_n(&fp_on, __ATOMIC_RELAXED) && (!svc_busy || frame >= svc_busy)) {
uintptr_t previous = svc_busy;
svc_busy = frame;
if (svc_stack_room(frame)) { result = svc_path_call(r); svc_busy = 0; }
else svc_busy = previous;
if (svc_stack_room(frame)) {
result = svc_path_call(r);
if (refused()) result = FP_SLOW;
svc_busy = 0;
} else svc_busy = previous;
}
if (result == FP_SLOW) {
__atomic_fetch_add(&svc_slow, 1, __ATOMIC_RELAXED);
@@ -0,0 +1,17 @@
diff --git a/src/arch.h b/src/arch.h
index 06b7f1b..db129a9 100644
--- a/src/arch.h
+++ b/src/arch.h
@@ -135,9 +135,9 @@ typedef unsigned char byte_t;
#define OFFSETOF_STAT_UID_32 24
#define OFFSETOF_STAT_GID_32 28
- #define LOADER_ADDRESS 0x2000000000
- #define EXEC_PIC_ADDRESS 0x3000000000
- #define INTERP_PIC_ADDRESS 0x3f00000000
+ #define LOADER_ADDRESS 0x5400000000
+ #define EXEC_PIC_ADDRESS 0x5555000000
+ #define INTERP_PIC_ADDRESS 0x5f00000000
#define HAS_POKEDATA_WORKAROUND true
#define HAS_LOADER_32BIT true
@@ -0,0 +1,59 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Kurt Himebauch
Date: Mon, 9 Nov 2026 15:30:00 -0500
Subject: [PATCH] seccomp: hand a guest filter's own SIGSYS back to the guest
---
--- a/src/tracee/seccomp.h
+++ b/src/tracee/seccomp.h
@@ -1,3 +1,4 @@
+#include <signal.h>
#include "tracee/tracee.h"
#include "sys/vfs.h"
@@ -18,5 +19,5 @@
void restart_syscall_after_seccomp(Tracee* tracee);
void set_result_after_seccomp(Tracee *tracee, word_t result);
-int handle_seccomp_event(Tracee* tracee);
+int handle_seccomp_event(Tracee* tracee, const siginfo_t *siginfo);
void fix_and_restart_enosys_syscall(Tracee* tracee);
--- a/src/tracee/seccomp.c
+++ b/src/tracee/seccomp.c
@@ -68,7 +68,7 @@
*
* Return 0 to swallow signal or SIGSYS to deliver it to process.
*/
-int handle_seccomp_event(Tracee* tracee)
+int handle_seccomp_event(Tracee* tracee, const siginfo_t *siginfo)
{
int ret;
@@ -100,6 +100,16 @@
print_current_regs(tracee, 3, "seccomp SIGSYS");
+ /* Android's app policy traps with SECCOMP_RET_DATA 0. A filter the guest
+ * installed itself (Firefox's and Chromium's sandboxes) tags its traps, and
+ * its own SIGSYS handler answers them, usually through a broker process.
+ * A trap from the fast path's trampoline still gets ENOSYS: its arguments
+ * are host paths, and the fast path repeats the call through libc. */
+ if (siginfo->si_errno != 0 && !from_fastpath_stub(tracee)) {
+ VERBOSE(tracee, 4, "SIGSYS from the guest's own seccomp filter (data %d)", siginfo->si_errno);
+ return SIGSYS;
+ }
+
return handle_seccomp_event_common(tracee);
}
--- a/src/tracee/event.c
+++ b/src/tracee/event.c
@@ -676,7 +676,7 @@
tracee->skip_next_seccomp_signal = false;
signal = 0;
} else {
- signal = handle_seccomp_event(tracee);
+ signal = handle_seccomp_event(tracee, &siginfo);
}
} else {
VERBOSE(tracee, 1, "non-seccomp SIGSYS");
+46 -8
View File
@@ -101,23 +101,31 @@ def description_excerpt(body):
return ""
def build_content(repo, number, title, sha, apk, release, description=None):
def commit_subject(message):
subject = (message or "").splitlines()[0].strip() if message else ""
return plain_title(subject[:300])
def build_content(repo, number, title, sha, apk, release, description=None, commit_message=None):
excerpt = description_excerpt(description)
subject = commit_subject(commit_message)
return (f"**Signed test build** `pr-{number}` · `{sha[:7]}`\n"
f"[#{number}](https://github.com/{repo}/pull/{number}): {plain_title(title)}\n"
+ (f"Latest commit: {subject}\n" if subject else "")
+ (f"\n{excerpt}\n\n" if excerpt else "") +
"_Not merged — for testing._\n"
f"In the app: **Updates → Test builds → #{number}**\n"
f"Download: [standard APK](<{apk}>) · [all variants](<{release}>)")
def retired_content(content, merged):
label = "Merged" if merged else "Closed"
if content.startswith(("**Merged** —", "**Closed** —")):
def retired_content(content, merged=False, superseded_by=None):
label = f"Superseded by `{superseded_by[:7]}`" if superseded_by else ("Merged" if merged else "Closed")
if content.startswith(("**Merged** —", "**Closed** —", "**Superseded by `")):
content = "\n".join(line[2:-2] if line.startswith("~~") and line.endswith("~~") else line
for line in content.splitlines()[2:])
struck = "\n".join(f"~~{line}~~" if line else "" for line in content.splitlines())
return f"**{label}** — this test build is no longer available.\n\n{struck}"
note = "This test build has been replaced." if superseded_by else "This test build is no longer available."
return f"**{label}** — {note}\n\n{struck}"
def sync(mode, repo, number, discord, sha="", apk="", release=""):
@@ -136,6 +144,11 @@ def sync(mode, repo, number, discord, sha="", apk="", release=""):
return
raise RuntimeError("Signed build report comment is missing")
message_id = saved_message(comment["body"], discord.id)
state_match = STATE.search(comment["body"])
try:
old_state = json.loads(state_match.group(1)) if state_match else {}
except ValueError:
old_state = {}
if mode == "retire":
if message_id:
message = discord.request("GET", f"/messages/{message_id}")
@@ -144,16 +157,41 @@ def sync(mode, repo, number, discord, sha="", apk="", release=""):
{"content": retired_content(message["content"], pull.get("merged", False)),
"allowed_mentions": {"parse": []}, "flags": 4})
return
content = build_content(repo, number, pull["title"], sha, apk, release, pull.get("body"))
try:
commit = github(f"repos/{repo}/commits/{sha}") or {}
except RuntimeError:
commit = {}
commit_message = (commit.get("commit") or {}).get("message", "")
content = build_content(repo, number, pull["title"], sha, apk, release, pull.get("body"), commit_message)
if len(content) > 1800:
raise RuntimeError("Discord announcement is too long")
payload = {"content": content, "allowed_mentions": {"parse": []}, "flags": 4}
message = discord.request("PATCH", f"/messages/{message_id}", payload) if message_id else None
old_message = None
previous_sha = old_state.get("sha")
if message_id and not previous_sha:
old_message = discord.request("GET", f"/messages/{message_id}")
if old_message:
match = re.search(r"`([0-9a-f]{7})`", old_message.get("content", ""))
previous_sha = match.group(1) if match else None
if message_id and (previous_sha == sha or previous_sha == sha[:7]):
message = discord.request("PATCH", f"/messages/{message_id}", payload)
else:
if message_id and old_state.get("sha"):
previous = discord.request("GET", f"/messages/{message_id}")
if previous:
discord.request("PATCH", f"/messages/{message_id}",
{"content": retired_content(previous["content"], superseded_by=sha),
"allowed_mentions": {"parse": []}, "flags": 4})
elif message_id and old_message:
discord.request("PATCH", f"/messages/{message_id}",
{"content": retired_content(old_message["content"], superseded_by=sha),
"allowed_mentions": {"parse": []}, "flags": 4})
message = None
if message is None:
message = discord.request("POST", "?wait=true", payload)
if message is None:
raise RuntimeError("Discord webhook no longer exists")
state = {"webhook_id": discord.id, "message_id": message["id"]}
state = {"webhook_id": discord.id, "message_id": message["id"], "sha": sha}
latest = github(f"repos/{repo}/issues/comments/{comment['id']}")
body = STATE.sub("", latest["body"]).rstrip() + f"\n<!-- droiddeck-discord: {json.dumps(state)} -->"
github(f"repos/{repo}/issues/comments/{comment['id']}", "PATCH", {"body": body})
+20 -1
View File
@@ -6,7 +6,7 @@ import unittest
from pathlib import Path
RUN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-appimage-run"
KEYS = ("QT_QPA_PLATFORM", "WAYLAND_DISPLAY", "SDL_VIDEODRIVER", "XDG_SESSION_TYPE", "QT_WAYLAND_DISABLE_WINDOWDECORATION", "DISABLE_GAMESCOPE_WSI")
KEYS = ("TU_DEBUG", "DROIDDECK_GAME_TU_DEBUG", "QT_QPA_PLATFORM", "WAYLAND_DISPLAY", "SDL_VIDEODRIVER", "XDG_SESSION_TYPE", "QT_WAYLAND_DISABLE_WINDOWDECORATION", "DISABLE_GAMESCOPE_WSI")
QUICK = ("usr/lib/libQt6Quick.so.6", "usr/lib/libvulkan.so.1", "usr/plugins/platforms/libqwayland-generic.so")
RUN_MODE = {"GAMESCOPE_WAYLAND_DISPLAY": "gamescope-0", "WAYLAND_DISPLAY": "gamescope-0", "DISPLAY": ":0",
"QT_QPA_PLATFORM": "xcb", "SDL_VIDEODRIVER": "x11", "XDG_SESSION_TYPE": "x11"}
@@ -128,5 +128,24 @@ class AppImageRunTest(unittest.TestCase):
self.assertEqual("wayland;xcb", env["QT_QPA_PLATFORM"])
def test_a_program_drops_the_sessions_sysmem_like_a_steam_game(self):
env, _ = self.launch(dict(RUN_MODE, TU_DEBUG="sysmem", DROIDDECK_GAME_TU_DEBUG=""))
self.assertEqual("unset", env["TU_DEBUG"])
self.assertEqual("unset", env["DROIDDECK_GAME_TU_DEBUG"])
def test_a_program_gets_the_game_driver_setting(self):
env, _ = self.launch(dict(RUN_MODE, TU_DEBUG="sysmem", DROIDDECK_GAME_TU_DEBUG="gmem"))
self.assertEqual("gmem", env["TU_DEBUG"])
def test_a_chromium_app_keeps_the_session_setting(self):
self.bundle("chrome_100_percent.pak")
env, _ = self.launch(dict(RUN_MODE, TU_DEBUG="sysmem", DROIDDECK_GAME_TU_DEBUG=""))
self.assertEqual("sysmem", env["TU_DEBUG"])
def test_without_the_game_setting_the_session_value_stays(self):
env, _ = self.launch(dict(RUN_MODE, TU_DEBUG="sysmem"))
self.assertEqual("sysmem", env["TU_DEBUG"])
if __name__ == "__main__":
unittest.main()
+36 -1
View File
@@ -10,7 +10,8 @@ COMPAT = runpy.run_path(str(BIN / "steam-compatibility"))
TOOL = COMPAT["TOOL"]
OLD = {"name": "DroidDeck-Proton-11-11.2", "display": "DroidDeck-Proton 11-11.2", "dir": "DroidDeck-Proton 11-11.2", "valve": False}
NEW = {"name": "DroidDeck-Proton-11-11.4", "display": "DroidDeck-Proton 11-11.4", "dir": "DroidDeck-Proton 11-11.4", "valve": False}
VALVE = {"name": TOOL, "display": "Proton Experimental ARM64", "dir": "Proton - Experimental (ARM64)", "valve": True}
VALVE = {"name": TOOL, "display": "Proton Experimental ARM64", "dir": COMPAT["SOURCES"][0], "valve": True}
VALVE_11 = {"name": COMPAT["TOOL_11"], "display": "Proton 11.0 ARM64", "dir": COMPAT["SOURCES"][1], "valve": True}
GE = {"name": "GE-Proton11-7", "display": "GE-Proton11-7", "dir": "GE-Proton11-7", "valve": False}
GE10 = {"name": "GE-Proton10-3", "display": "GE-Proton10-3", "dir": "GE-Proton10-3", "valve": False}
NEWER = {"name": "DroidDeck-Proton-11-12.1", "display": "DroidDeck-Proton 11-12.1", "dir": "DroidDeck-Proton 11-12.1", "valve": False}
@@ -164,6 +165,40 @@ class DroidDeckProtonDefaultTest(unittest.TestCase):
self.assertEqual(mapping, {"0": GE10["name"], "3000000001": TOOL, "3000000002": GE10["name"],
"3000000003": GE["name"], "3000000004": GE10["name"], "42": GE["name"], "44": GE["name"]})
def test_proton_experimental_picked_for_a_game_in_steam_stays(self):
default, mapping, state = self.run_default(
{"default": NEW["name"], "written": NEW["name"], "source": "update",
"auto": {"42": NEW["name"], "43": NEW["name"], "45": NEW["name"]}},
[("0", NEW["name"]), ("42", "proton_experimental"), ("43", NEW["name"]), ("45", TOOL)], [VALVE, NEW],
["42", "43", "44", "45"])
self.assertEqual(default, NEW["name"])
self.assertEqual(mapping, {"0": NEW["name"], "42": TOOL, "43": NEW["name"], "44": NEW["name"], "45": TOOL})
self.assertEqual(state["auto"], {"43": NEW["name"], "44": NEW["name"]})
self.assertTrue({"42", "45"} <= set(state["picked"]))
default, mapping, state = self.run_default(state, sorted(mapping.items()), [VALVE, NEWER], ["42", "43", "44", "45"])
self.assertEqual(default, NEWER["name"])
self.assertEqual(mapping, {"0": NEWER["name"], "42": TOOL, "43": NEWER["name"], "44": NEWER["name"], "45": TOOL})
def test_a_steam_pick_of_a_valve_proton_moves_to_the_build_made_from_it(self):
catalog = [VALVE, VALVE_11, NEW]
default, mapping, state = self.run_default(
{"default": NEW["name"], "written": NEW["name"], "source": "update", "auto": {"42": TOOL, "43": NEW["name"]},
"picked": ["44"]},
[("0", NEW["name"]), ("42", "proton-experimental-arm64"), ("43", "proton_11"), ("44", "proton_11-arm64"),
("45", "proton_9")], catalog, ["42", "43", "44", "45"])
self.assertEqual(mapping, {"0": NEW["name"], "42": TOOL, "43": VALVE_11["name"], "44": VALVE_11["name"], "45": NEW["name"]})
self.assertEqual(state["auto"], {"45": NEW["name"]})
_, mapping, _ = self.run_default(state, sorted(mapping.items()), catalog, ["42", "43", "44", "45"],
request={"seq": 1, "valve": False, "dir": GE["dir"]})
self.assertEqual(mapping, {"0": NEW["name"], "42": TOOL, "43": VALVE_11["name"], "44": VALVE_11["name"], "45": NEW["name"]})
def test_proton_experimental_picked_as_steams_default_stays(self):
default, mapping, state = self.run_default(
{"default": NEW["name"], "written": NEW["name"], "source": "update"}, [("0", "proton_experimental")], [VALVE, NEW])
self.assertEqual((default, mapping, state["source"]), (TOOL, {"0": TOOL}, "steam"))
default, mapping, state = self.run_default(state, [("0", TOOL)], [VALVE, NEW, NEWER])
self.assertEqual((default, mapping), (TOOL, {"0": TOOL}))
def test_the_newest_build_is_found_by_version(self):
newest, gone = COMPAT["own_proton_moves"]({"tools": [OLD]}, [dict(NEW, name="a", dir="DroidDeck-Proton 11-9.10"), dict(NEW, name="b", dir="DroidDeck-Proton 11-11.1")])
self.assertEqual(newest, "b")
+31
View File
@@ -328,6 +328,15 @@ class DroiddeckctlTest(FakeAdbTest):
self.assertEqual("222", out["displays"][1]["physicalId"])
self.assertEqual([1080, 1240], out["displays"][1]["size"])
def test_displays_named_with_their_unique_id(self):
text = DUMPSYS_DISPLAY.replace("mPrimaryDisplayDevice=Screen-2",
"mPrimaryDisplayDevice=Screen-2(local:222)")
self.configure({}, dumpsys_display=text)
code, out = self.run_ctl("screenshot", str(self.dir / "shot.png"), "--display", "4")
self.assertEqual(0, code)
shot = [c for c in self.calls() if c["args"][:2] == ["exec-out", "screencap"]][0]
self.assertEqual(["exec-out", "screencap", "-p", "-d", "222"], shot["args"])
def test_unknown_display_is_an_error(self):
self.configure({}, dumpsys_display=DUMPSYS_DISPLAY)
code, out = self.run_ctl("screenshot", str(self.dir / "x.png"), "--display", "9")
@@ -398,6 +407,28 @@ class DroiddeckctlTest(FakeAdbTest):
self.assertEqual(4, code)
self.assertEqual("NO_FRAMES", out["error"]["code"])
def test_provider_call_falls_back_to_a_broadcast_without_content(self):
calls = []
answers = iter([b"", b'{"ok": true, "command": "state"}'])
def adb(_adb, _serial, *args, timeout=30):
calls.append(args)
if args[:2] == ("shell", "content"):
return ctl.subprocess.CompletedProcess(args, 127, b"", b"/system/bin/sh: content: inaccessible or not found")
if args[:2] == ("shell", "am"):
return ctl.subprocess.CompletedProcess(args, 0, b"Broadcast completed: result=0", b"")
return ctl.subprocess.CompletedProcess(args, 0, next(answers), b"")
with unittest.mock.patch.object(ctl, "run_adb", adb), unittest.mock.patch.object(ctl.time, "sleep"):
answer = ctl.provider_call("adb", "fake-1", "state", arg="a b", request={"x": 1})
self.assertEqual({"ok": True, "command": "state"}, answer)
broadcast = calls[1]
self.assertEqual(("shell", "am", "broadcast", "-a", ctl.PACKAGE + ".AGENT_CALL", "-p", ctl.PACKAGE), broadcast[:7])
self.assertIn("'a b'", broadcast)
self.assertEqual(ctl.encode_request({"x": 1}), broadcast[broadcast.index("request") + 1])
call_id = broadcast[broadcast.index("id") + 1]
self.assertIn("agent-calls/%s.json" % call_id, calls[-1][1])
def test_pacing_turns_timestats_off_when_the_dump_fails(self):
calls = []
+58
View File
@@ -0,0 +1,58 @@
from pathlib import Path
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
SOURCE = Path(__file__).resolve().parents[2] / "app/src/main/cpp/fakeinput_steam.cpp"
# Stands in for an allocator like mimalloc that calls access() while it starts up (Claude Code
# probes /sys/devices/system/node/node1 on its first allocation, which comes from fakeinput's
# constructor when it is preloaded).
PROGRAM = r"""
#define _GNU_SOURCE
#include <stddef.h>
#include <stdio.h>
#include <unistd.h>
extern void *__libc_malloc(size_t);
static int started;
void *malloc(size_t size) {
if (!started) {
started = 1;
access("/sys/devices/system/node/node1", R_OK);
}
return __libc_malloc(size);
}
int main(void) {
puts("ok");
return 0;
}
"""
@unittest.skipUnless(sys.platform == "linux" and shutil.which("gcc") and shutil.which("g++"),
"needs Linux, gcc and g++")
class FakeinputReentryTest(unittest.TestCase):
def test_allocator_calling_hooks_during_first_allocation_survives_preload(self):
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp)
(path / "program.c").write_text(PROGRAM)
subprocess.run(["gcc", "-rdynamic", "-o", str(path / "program"), str(path / "program.c")], check=True)
subprocess.run(["g++", "-shared", "-fPIC", "-O2", "-Wno-attributes", "-pthread",
"-std=c++17", "-static-libstdc++", "-static-libgcc",
"-Wl,--exclude-libs,ALL", "-o", str(path / "libfakeinput.so"),
str(SOURCE), "-ldl"], check=True)
result = subprocess.run([str(path / "program")],
env=dict(os.environ, LD_PRELOAD=str(path / "libfakeinput.so")),
capture_output=True, text=True, timeout=10)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(result.stdout, "ok\n")
if __name__ == "__main__":
unittest.main()
+355
View File
@@ -0,0 +1,355 @@
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
USERNS = shutil.which("unshare") is not None and subprocess.run(["unshare", "-Urm", "true"], capture_output=True).returncode == 0
FASTPATH = Path(__file__).resolve().parents[1] / "proot/fastpath/fastpath.c"
PROGRAM = r"""
#include "FASTPATH"
#include <sys/mount.h>
static const char *race_from, *race_to;
static dev_t race_dev;
static ino_t race_ino;
static long trapped_nr = -1, unsupported_nr = -1;
static long host_sys(long nr, long a, long b, long c, long d, long e, long f) {
if (nr == trapped_nr || (nr == unsupported_nr && a != -1)) return -ENOSYS;
long r = syscall(nr, a, b, c, d, e, f);
struct stat fs;
if (r >= 0 && nr == SYS_fcntl && b == F_DUPFD_CLOEXEC && c == DIR_FD_FLOOR && race_from
&& syscall(SYS_fstat, a, &fs) == 0 && fs.st_dev == race_dev && fs.st_ino == race_ino) {
syscall(SYS_renameat, AT_FDCWD, race_from, AT_FDCWD, race_to);
race_from = NULL;
}
return r < 0 ? -errno : r;
}
static void show(long r) {
if (r == FP_SLOW) puts("SLOW");
else if (r < 0) printf("E%ld\n", -r);
else puts("ok");
}
static int high_fds(void) {
int n = 0;
for (int fd = DIR_FD_FLOOR; fd < DIR_FD_FLOOR + 4 * DIRS; fd++)
if (fcntl(fd, F_GETFD) >= 0) n++;
return n;
}
int main(int argc, char **argv) {
static char hosts[MAX_BINDS][PATH_MAX], guests[MAX_BINDS][512];
static int taken[DIRS];
int ntaken = 0;
fp_sys = host_sys;
snprintf(root, sizeof root, "%s", argv[1]);
rootlen = strlen(root);
int i = 2;
for (; i + 1 < argc && strcmp(argv[i], "--"); i += 2) {
struct bind *bd = &binds[nbinds];
bd->host = hosts[nbinds];
bd->guest = guests[nbinds];
snprintf(bd->host, PATH_MAX, "%s", argv[i]);
snprintf(bd->guest, sizeof guests[0], "%s", argv[i + 1]);
bd->hlen = strlen(bd->host);
bd->glen = strlen(bd->guest);
nbinds++;
}
pthread_once(&init_once, fp_init);
fp_on = 1;
for (i++; i < argc; i++) {
const char *op = argv[i];
if (!strcmp(op, "fuse")) {
for (int b = 0; b < nbinds; b++) binds[b].fuse = 1;
} else if (!strcmp(op, "touch")) {
long fd = fp_open(AT_FDCWD, argv[++i], O_CREAT | O_WRONLY | O_CLOEXEC, 0644);
if (fd >= 0) close((int)fd);
show(fd);
} else if (!strcmp(op, "stat")) {
struct stat st;
show(fp_stat(AT_FDCWD, argv[++i], AT_SYMLINK_NOFOLLOW, &st));
} else if (!strcmp(op, "symlink")) {
long r = fp_symlink("target", AT_FDCWD, argv[++i]);
if (refused()) puts("REFUSED");
else show(r);
} else if (!strcmp(op, "trap-symlink")) {
trapped_nr = SYS_symlinkat;
} else if (!strcmp(op, "no-symlinks")) {
unsupported_nr = SYS_symlinkat;
} else if (!strcmp(op, "on")) {
printf("%d\n", fp_ready());
} else if (!strcmp(op, "no-folders")) {
unsupported_nr = SYS_mkdirat;
} else if (!strcmp(op, "busy-cache")) {
pthread_mutex_lock(&dir_lock);
} else if (!strcmp(op, "mkdir")) {
long r = fp_mkdir(AT_FDCWD, argv[++i], 0755);
if (refused()) puts("REFUSED");
else show(r);
} else if (!strcmp(op, "mv")) {
show(fp_rename(AT_FDCWD, argv[i + 1], AT_FDCWD, argv[i + 2], 0));
i += 2;
} else if (!strcmp(op, "rm")) {
show(fp_unlink(AT_FDCWD, argv[++i], 0));
} else if (!strcmp(op, "host-mv")) {
show(host_sys(SYS_renameat, AT_FDCWD, (long)argv[i + 1], AT_FDCWD, (long)argv[i + 2], 0, 0));
i += 2;
} else if (!strcmp(op, "race-mv")) {
struct stat rs;
race_from = argv[i + 1];
race_to = argv[i + 2];
i += 2;
show(host_sys(SYS_newfstatat, AT_FDCWD, (long)race_from, (long)&rs, 0, 0, 0));
race_dev = rs.st_dev;
race_ino = rs.st_ino;
} else if (!strcmp(op, "host-rmdir")) {
show(host_sys(SYS_unlinkat, AT_FDCWD, (long)argv[++i], AT_REMOVEDIR, 0, 0, 0));
} else if (!strcmp(op, "host-mkdir")) {
show(host_sys(SYS_mkdirat, AT_FDCWD, (long)argv[++i], 0755, 0, 0, 0));
} else if (!strcmp(op, "clobber")) {
long null = host_sys(SYS_openat, AT_FDCWD, (long)"/dev/null", O_RDONLY, 0, 0, 0);
for (int fd = DIR_FD_FLOOR; fd < DIR_FD_FLOOR + DIRS; fd++) host_sys(SYS_dup3, null, fd, 0, 0, 0, 0);
host_sys(SYS_close, null, 0, 0, 0, 0, 0);
puts("ok");
} else if (!strcmp(op, "same-dir-takeover")) {
const char *dir = argv[++i];
struct near first, second;
long fd = host_sys(SYS_openat, AT_FDCWD, (long)dir, O_RDONLY | O_DIRECTORY | O_CLOEXEC, 0, 0, 0);
if (fd < 0 || dir_keep(dir, fd, &first) < 0 || first.slot < 0) return 2;
int target = (int)first.fd;
near_put(&first);
fd = host_sys(SYS_openat, AT_FDCWD, (long)dir, O_RDONLY | O_DIRECTORY | O_CLOEXEC, 0, 0, 0);
if (fd < 0 || host_sys(SYS_dup3, fd, target, O_CLOEXEC, 0, 0, 0) < 0) return 3;
host_sys(SYS_close, fd, 0, 0, 0, 0, 0);
fd = host_sys(SYS_openat, AT_FDCWD, (long)dir, O_RDONLY | O_DIRECTORY | O_CLOEXEC, 0, 0, 0);
if (fd < 0 || dir_keep(dir, fd, &second) < 0) return 4;
puts(fcntl(target, F_GETFD) < 0 ? "closed" : "open");
near_put(&second);
} else if (!strcmp(op, "first-fd")) {
char link[40], out[PATH_MAX];
snprintf(link, sizeof link, "/proc/self/fd/%d", DIR_FD_FLOOR);
long n = host_sys(SYS_readlinkat, AT_FDCWD, (long)link, (long)out, sizeof out - 1, 0, 0);
out[n > 0 ? n : 0] = 0;
puts(out);
} else if (!strcmp(op, "fds")) {
printf("%d\n", high_fds());
} else if (!strcmp(op, "ttl")) {
ttl_ns = atoll(argv[++i]) * 1000000LL;
} else if (!strcmp(op, "sleep")) {
usleep(atoi(argv[++i]) * 1000);
} else if (!strcmp(op, "chmod")) {
show(fp_chmod(AT_FDCWD, argv[i + 1], strtol(argv[i + 2], NULL, 8), 0));
i += 2;
} else if (!strcmp(op, "host-chmod")) {
show(host_sys(SYS_fchmodat, AT_FDCWD, (long)argv[i + 1], strtol(argv[i + 2], NULL, 8), 0, 0, 0));
i += 2;
} else if (!strcmp(op, "host-mount")) {
show(mount("tmpfs", argv[++i], "tmpfs", 0, NULL) == 0 ? 0 : -errno);
} else if (!strcmp(op, "take-over")) {
for (int fd = DIR_FD_FLOOR; fd < DIR_FD_FLOOR + DIRS; fd++) {
char link[40], out[PATH_MAX];
snprintf(link, sizeof link, "/proc/self/fd/%d", fd);
long n = host_sys(SYS_readlinkat, AT_FDCWD, (long)link, (long)out, sizeof out - 1, 0, 0);
if (n <= 0) continue;
out[n] = 0;
long mine = host_sys(SYS_openat, AT_FDCWD, (long)out, O_RDONLY | O_DIRECTORY, 0, 0, 0);
host_sys(SYS_dup3, mine, fd, 0, 0, 0, 0);
host_sys(SYS_close, mine, 0, 0, 0, 0, 0);
taken[ntaken++] = fd;
}
puts("ok");
} else if (!strcmp(op, "taken")) {
int open_fds = 0;
for (int t = 0; t < ntaken; t++)
if (lseek(taken[t], 0, SEEK_CUR) == 0) open_fds++;
printf("%d/%d\n", open_fds, ntaken);
}
}
return 0;
}
"""
class FastPathFuseDirsTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
if shutil.which("gcc") is None:
raise unittest.SkipTest("gcc is not available")
cls.build = tempfile.TemporaryDirectory()
source = Path(cls.build.name) / "fuse_dirs.c"
source.write_text(PROGRAM.replace("FASTPATH", str(FASTPATH)))
cls.program = Path(cls.build.name) / "fuse_dirs"
subprocess.run(["gcc", "-O1", "-Wall", "-Wextra", "-Werror", "-Wno-format-truncation", "-pthread", "-o", str(cls.program), str(source), "-ldl"], check=True)
@classmethod
def tearDownClass(cls):
cls.build.cleanup()
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
base = Path(self.temp.name)
self.root = base / "root"
(self.root / "mnt").mkdir(parents=True)
self.card = base / "card"
(self.card / "Games/steamapps/common/Game/Data").mkdir(parents=True)
def ask(self, *ops, wrap=()):
argv = [*wrap, str(self.program), str(self.root), str(self.card), "/mnt/card", "--", *ops]
return subprocess.run(argv, capture_output=True, text=True, timeout=20, check=True).stdout.split()
def test_files_deep_in_a_fuse_library_are_created_renamed_and_removed(self):
data = "/mnt/card/Games/steamapps/common/Game/Data"
out = self.ask("fuse", "touch", f"{data}/a.tmp", "mv", f"{data}/a.tmp", f"{data}/a.idx",
"stat", f"{data}/a.idx", "stat", f"{data}/a.tmp", "rm", f"{data}/a.idx",
"stat", f"{data}/a.idx", "fds")
self.assertEqual(["ok", "ok", "ok", "E2", "ok", "E2"], out[:-1])
self.assertGreater(int(out[-1]), 0)
self.assertEqual([], list((self.card / "Games/steamapps/common/Game/Data").iterdir()))
def test_a_folder_renamed_behind_the_cache_is_not_reused(self):
game = self.card / "Games/steamapps/common/Game"
(game / "Data/keep").write_text("x")
out = self.ask("fuse", "stat", "/mnt/card/Games/steamapps/common/Game/Data/keep",
"host-mv", str(game), str(game.parent / "Moved"),
"stat", "/mnt/card/Games/steamapps/common/Game/Data/keep",
"stat", "/mnt/card/Games/steamapps/common/Moved/Data/keep")
self.assertEqual(["ok", "ok", "E2", "ok"], out)
def test_a_folder_renamed_while_it_is_opened_is_not_used_under_its_old_name(self):
game = self.card / "Games/steamapps/common/Game"
(game / "Data/keep").write_text("x")
out = self.ask("fuse", "race-mv", str(game / "Data"), str(game / "Moved"),
"stat", "/mnt/card/Games/steamapps/common/Game/Data/keep",
"touch", "/mnt/card/Games/steamapps/common/Game/Data/new", "fds")
self.assertEqual(["ok", "E2", "E2"], out[:3])
self.assertEqual(["keep"], [p.name for p in (game / "Moved").iterdir()])
self.assertLessEqual(int(out[-1]), 64)
def test_a_folder_deleted_and_made_again_is_looked_up_fresh(self):
data = self.card / "Games/steamapps/common/Game/Data"
out = self.ask("fuse", "touch", "/mnt/card/Games/steamapps/common/Game/Data/old",
"rm", "/mnt/card/Games/steamapps/common/Game/Data/old",
"host-rmdir", str(data), "host-mkdir", str(data),
"touch", "/mnt/card/Games/steamapps/common/Game/Data/new")
self.assertEqual(["ok"] * 5, out)
self.assertEqual(["new"], [p.name for p in data.iterdir()])
def test_folders_deleted_and_made_again_many_times_keep_descriptors_bounded(self):
data = self.card / "Games/steamapps/common/Game/Data"
ops = ["fuse"]
for _ in range(200):
ops += ["touch", "/mnt/card/Games/steamapps/common/Game/Data/x",
"rm", "/mnt/card/Games/steamapps/common/Game/Data/x",
"host-rmdir", str(data), "host-mkdir", str(data)]
out = self.ask(*ops, "fds")
self.assertEqual(["ok"] * 800, out[:-1])
self.assertLessEqual(int(out[-1]), 64)
def test_descriptors_the_program_takes_over_are_left_alone(self):
data = "/mnt/card/Games/steamapps/common/Game/Data"
out = self.ask("fuse", "touch", f"{data}/a", "clobber", "touch", f"{data}/b",
"stat", f"{data}/a", "first-fd")
self.assertEqual(["ok", "ok", "ok", "ok", "/dev/null"], out)
self.assertEqual({"a", "b"}, {p.name for p in (self.card / "Games/steamapps/common/Game/Data").iterdir()})
def test_a_folder_the_program_opened_itself_stays_open_when_the_cache_moves_on(self):
data = self.card / "Games/steamapps/common/Game/Data"
ops = ["fuse", "touch", "/mnt/card/Games/steamapps/common/Game/Data/a", "take-over"]
for n in range(200):
(data / f"d{n}").mkdir()
ops += ["touch", f"/mnt/card/Games/steamapps/common/Game/Data/d{n}/x"]
out = self.ask(*ops, "taken")
self.assertEqual(["ok"] * 202, out[:-1])
opened, total = map(int, out[-1].split("/"))
self.assertGreater(total, 0)
self.assertEqual(total, opened)
self.assertEqual(200, len(list(data.glob("d*/x"))))
@unittest.skipIf(os.geteuid() == 0, "root passes folder permissions")
def test_a_parent_folder_closed_by_the_program_stops_cached_access_at_once(self):
game = self.card / "Games/steamapps/common/Game"
(game / "Data/keep").write_text("x")
self.addCleanup(os.chmod, game, 0o755)
out = self.ask("fuse", "stat", "/mnt/card/Games/steamapps/common/Game/Data/keep",
"chmod", "/mnt/card/Games/steamapps/common/Game", "000",
"stat", "/mnt/card/Games/steamapps/common/Game/Data/keep",
"touch", "/mnt/card/Games/steamapps/common/Game/Data/new")
self.assertEqual(["ok", "ok"], out[:2])
self.assertNotIn("ok", out[2:])
os.chmod(game, 0o755)
self.assertEqual(["keep"], [p.name for p in (game / "Data").iterdir()])
@unittest.skipIf(os.geteuid() == 0, "root passes folder permissions")
def test_external_permission_change_stops_access_before_ttl_expires(self):
game = self.card / "Games/steamapps/common/Game"
(game / "Data/keep").write_text("x")
self.addCleanup(os.chmod, game, 0o755)
out = self.ask("fuse", "ttl", "60000", "stat", "/mnt/card/Games/steamapps/common/Game/Data/keep",
"host-chmod", str(game), "000",
"stat", "/mnt/card/Games/steamapps/common/Game/Data/keep",
"touch", "/mnt/card/Games/steamapps/common/Game/Data/new",
"host-chmod", str(game), "755",
"stat", "/mnt/card/Games/steamapps/common/Game/Data/keep",
"touch", "/mnt/card/Games/steamapps/common/Game/Data/new")
self.assertEqual(["ok", "ok", "E13", "E13", "ok", "ok", "ok"], out)
self.assertEqual({"keep", "new"}, {p.name for p in (game / "Data").iterdir()})
@unittest.skipUnless(USERNS, "mount namespaces are not available")
def test_a_mount_placed_over_a_cached_folder_receives_later_writes(self):
data = self.card / "Games/steamapps/common/Game/Data"
out = self.ask("fuse", "ttl", "60000", "touch", "/mnt/card/Games/steamapps/common/Game/Data/under",
"host-mount", str(data),
"touch", "/mnt/card/Games/steamapps/common/Game/Data/over",
"stat", "/mnt/card/Games/steamapps/common/Game/Data/under", wrap=("unshare", "-Urm"))
self.assertEqual(["ok", "ok", "ok", "E2"], out)
self.assertEqual(["under"], [p.name for p in data.iterdir()])
def test_a_call_the_filesystem_does_not_implement_leaves_the_fast_path_on(self):
data = "/mnt/card/Games/steamapps/common/Game/Data"
out = self.ask("fuse", "no-symlinks", "touch", f"{data}/a", "symlink", f"{data}/link", "on",
"stat", f"{data}/a", "symlink", f"{data}/link", "on", "touch", f"{data}/b")
self.assertEqual(["ok", "REFUSED", "1", "ok", "REFUSED", "1", "ok"], out)
self.assertEqual(["a", "b"], sorted(p.name for p in (self.card / "Games/steamapps/common/Game/Data").iterdir()))
def test_repeated_unsupported_calls_close_the_folders_they_opened(self):
data = "/mnt/card/Games/steamapps/common/Game/Data"
ops = [op for n in range(40) for op in ("mkdir", f"{data}/new{n}")]
out = self.ask("fuse", "no-folders", "busy-cache", *ops, "on", "fds")
self.assertEqual(["REFUSED"] * 40 + ["1", "0"], out)
def test_a_trapped_call_still_stops_the_fast_path_for_the_process(self):
data = "/mnt/card/Games/steamapps/common/Game/Data"
out = self.ask("fuse", "trap-symlink", "symlink", f"{data}/link", "on")
self.assertEqual(["REFUSED", "0"], out)
def test_a_symlink_is_made_where_the_filesystem_allows_it(self):
data = "/mnt/card/Games/steamapps/common/Game/Data"
out = self.ask("fuse", "symlink", f"{data}/link", "on")
self.assertEqual(["ok", "1"], out)
self.assertEqual("target", os.readlink(self.card / "Games/steamapps/common/Game/Data/link"))
def test_same_directory_takeover_survives_slot_reuse(self):
self.assertEqual(["open"], self.ask("same-dir-takeover", str(self.card)))
def test_disabling_the_cache_keeps_absolute_paths_and_opens_no_folders(self):
data = "/mnt/card/Games/steamapps/common/Game/Data"
out = self.ask("fuse", "ttl", "0", "touch", f"{data}/a", "mv", f"{data}/a", f"{data}/b",
"stat", f"{data}/b", "rm", f"{data}/b", "fds")
self.assertEqual(["ok", "ok", "ok", "ok", "0"], out)
def test_other_filesystems_keep_absolute_paths_and_open_no_folders(self):
data = "/mnt/card/Games/steamapps/common/Game/Data"
out = self.ask("touch", f"{data}/a", "mv", f"{data}/a", f"{data}/b", "rm", f"{data}/b", "fds")
self.assertEqual(["ok", "ok", "ok", "0"], out)
if __name__ == "__main__":
unittest.main()
+41 -1
View File
@@ -902,6 +902,46 @@ class GameEnvironmentTest(unittest.TestCase):
self.assertEqual(MODULE["apply_config"](env, config, "42")["TU_DEBUG"], "sysmem")
self.assertNotIn("TU_DEBUG", MODULE["apply_config"](env, config, "43"))
def test_a_chromium_app_keeps_the_sessions_turnip_debug(self):
gpu = MODULE["game_gpu"]
self.assertEqual(gpu({"TU_DEBUG": "sysmem", "DROIDDECK_GAME_TU_DEBUG": "", "KEEP": "1"}, True),
{"TU_DEBUG": "sysmem", "KEEP": "1"})
self.assertEqual(gpu({"TU_DEBUG": "sysmem", "DROIDDECK_GAME_TU_DEBUG": "nolrz"}, True), {"TU_DEBUG": "sysmem"})
self.assertEqual(gpu({"TU_DEBUG": "sysmem"}, True), {"TU_DEBUG": "sysmem"})
def test_chromium_files_are_found_four_levels_deep_and_no_further(self):
chromium = MODULE["chromium_app"]
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp) / "app"
(root / "usr/lib/tool").mkdir(parents=True)
(root / "usr/lib/tool/libtool.so").write_bytes(b"")
self.assertFalse(chromium(str(root)))
for name in ("chrome-sandbox", "chrome_100_percent.pak", "v8_context_snapshot.bin"):
found = root / "a/b/c" / name
found.parent.mkdir(parents=True, exist_ok=True)
found.write_bytes(b"")
self.assertTrue(chromium(str(root)), name)
found.unlink()
deep = root / "a/b/c/d/chrome-sandbox"
deep.parent.mkdir(parents=True)
deep.write_bytes(b"")
self.assertFalse(chromium(str(root)))
self.assertFalse(chromium(str(Path(tmp) / "missing")))
def test_chromium_detection_does_not_follow_links_inside_the_app(self):
chromium = MODULE["chromium_app"]
with tempfile.TemporaryDirectory() as tmp:
other = Path(tmp) / "other"
other.mkdir()
(other / "chrome-sandbox").write_bytes(b"")
root = Path(tmp) / "app"
root.mkdir()
(root / "linked").symlink_to(other, target_is_directory=True)
self.assertFalse(chromium(str(root)))
link = Path(tmp) / "app-link"
link.symlink_to(other, target_is_directory=True)
self.assertTrue(chromium(str(link)))
def test_the_vram_cap_comes_before_the_games_own_dxvk_settings(self):
cap = MODULE["vram_cap"]
self.assertEqual(cap({"BL_VRAM_MB": "4096"})["DXVK_CONFIG"], "dxgi.maxDeviceMemory = 4096")
@@ -2024,7 +2064,7 @@ class ProtonDefaultTest(unittest.TestCase):
self.assertEqual(mapping_of(config.read_text()), {"0": self.TOOL, "427520": self.TOOL})
saved = json.loads((Path(tmp) / "state.json").read_text())
self.assertEqual(saved["native_choices"], [])
self.assertEqual(saved["auto"], {"427520": self.TOOL})
self.assertEqual(saved["auto"], {})
finally:
globals_["appinfo_platforms"] = original_platforms
+98
View File
@@ -0,0 +1,98 @@
import os
import runpy
import shutil
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
KEYS = ("TU_DEBUG", "DROIDDECK_GAME_TU_DEBUG")
SESSION = {"TU_DEBUG": "sysmem", "DROIDDECK_GAME_TU_DEBUG": ""}
class GameGpuLaunchersTest(unittest.TestCase):
def setUp(self):
self.tmp = Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, self.tmp, True)
self.out = self.tmp / "env"
self.tools = self.tmp / "tools"
self.tools.mkdir()
self.app = self.tmp / "deploy"
(self.app / "files/bin").mkdir(parents=True)
self.report = self.tools / "report"
self.report.write_text("#!/bin/sh\nfor k in %s; do eval \"echo $k=\\${$k-unset}\"; done > %s\n"
% (" ".join(KEYS), self.out))
self.report.chmod(0o755)
flatpak = self.tools / "flatpak"
flatpak.write_text("#!/bin/sh\n"
"if [ \"$1\" = info ]; then [ \"$3\" = org.example.App ] && echo %s; exit 0; fi\n"
"exec %s\n" % (self.app, self.report))
flatpak.chmod(0o755)
def chromium(self):
(self.app / "files/lib/browser").mkdir(parents=True)
(self.app / "files/lib/browser/chrome_100_percent.pak").write_bytes(b"")
def run_env(self, command, session):
env = {k: v for k, v in os.environ.items() if k not in KEYS + ("DBUS_SESSION_BUS_ADDRESS", "GAMESCOPE_WAYLAND_DISPLAY")}
env.update(session, PATH="%s:%s" % (self.tools, env.get("PATH", "/usr/bin:/bin")),
DBUS_SESSION_BUS_ADDRESS="unix:path=/dev/null")
result = subprocess.run(command, env=env, capture_output=True, text=True, timeout=30)
self.assertEqual(0, result.returncode, result.stderr)
return dict(line.split("=", 1) for line in self.out.read_text().splitlines())
def wrapper(self, *args, session=SESSION):
return self.run_env([sys.executable, str(BIN / "droiddeck-game-gpu"), *args, "--", str(self.report)], session)
def flatpak(self, session=SESSION):
return self.run_env(["bash", str(BIN / "droiddeck-flatpak-run"), "--command=app", "org.example.App"], session)
def test_the_wrapper_gives_a_program_the_game_setting(self):
self.assertEqual({"TU_DEBUG": "unset", "DROIDDECK_GAME_TU_DEBUG": "unset"}, self.wrapper())
self.assertEqual("gmem", self.wrapper(session={"TU_DEBUG": "sysmem", "DROIDDECK_GAME_TU_DEBUG": "gmem"})["TU_DEBUG"])
def test_the_wrapper_keeps_the_session_setting_for_chromium(self):
self.assertEqual({"TU_DEBUG": "sysmem", "DROIDDECK_GAME_TU_DEBUG": "unset"}, self.wrapper("--chromium"))
self.assertEqual("unset", self.wrapper("--for", str(self.app / "files"))["TU_DEBUG"])
self.chromium()
self.assertEqual("sysmem", self.wrapper("--for", str(self.app / "files"))["TU_DEBUG"])
def test_without_the_game_setting_the_wrapper_changes_nothing(self):
self.assertEqual("sysmem", self.wrapper(session={"TU_DEBUG": "sysmem"})["TU_DEBUG"])
self.assertEqual("unset", self.wrapper(session={})["TU_DEBUG"])
def test_the_wrapper_reports_a_missing_program(self):
result = subprocess.run([sys.executable, str(BIN / "droiddeck-game-gpu"), "--", str(self.tmp / "missing")],
capture_output=True, text=True, timeout=30)
self.assertEqual(127, result.returncode)
self.assertEqual(2, subprocess.run([sys.executable, str(BIN / "droiddeck-game-gpu")], capture_output=True,
timeout=30).returncode)
def test_a_flatpak_app_gets_the_game_setting(self):
self.assertEqual({"TU_DEBUG": "unset", "DROIDDECK_GAME_TU_DEBUG": "unset"}, self.flatpak())
self.assertEqual("nolrz", self.flatpak({"TU_DEBUG": "sysmem", "DROIDDECK_GAME_TU_DEBUG": "nolrz"})["TU_DEBUG"])
def test_a_chromium_flatpak_keeps_the_session_setting(self):
self.chromium()
self.assertEqual({"TU_DEBUG": "sysmem", "DROIDDECK_GAME_TU_DEBUG": "unset"}, self.flatpak())
def test_a_flatpak_without_the_game_setting_is_unchanged(self):
self.assertEqual("sysmem", self.flatpak({"TU_DEBUG": "sysmem"})["TU_DEBUG"])
def test_a_snap_gets_the_game_setting_unless_it_is_chromium(self):
try:
snap_run = runpy.run_path(str(BIN / "droiddeck-snap-run"))
except ImportError:
self.skipTest("PyYAML is not installed")
gpu = snap_run["game_gpu"]
snap = self.app / "files"
self.assertEqual({"KEEP": "1"}, gpu(dict(SESSION, KEEP="1"), str(snap)))
self.assertEqual({"TU_DEBUG": "nolrz"}, gpu({"TU_DEBUG": "sysmem", "DROIDDECK_GAME_TU_DEBUG": "nolrz"}, str(snap)))
self.chromium()
self.assertEqual({"TU_DEBUG": "sysmem"}, gpu(dict(SESSION), str(snap)))
if __name__ == "__main__":
unittest.main()
+28 -3
View File
@@ -32,7 +32,7 @@ step() { :; }
bl_zram_usage() { _bl_rss=$rss _bl_swap=$client_swap; }
bl_zram_send() { echo "send:$1:$3"; rss=$((rss - reclaimed)); _bl_pageout_complete=${pageout_complete:-1}; }
''' + functions + '\nbl_memory_read\n' + body
result = run_bash(harness)
result = run_bash('NOW=0\n' + harness.replace('SECONDS', 'NOW'))
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual('', result.stderr)
return result.stdout.splitlines()
@@ -168,7 +168,7 @@ bl_session_others() { _bl_session=(321 654); }
bl_zram_usage() { _bl_rss=$rss _bl_swap=$swap; }
bl_zram_send() { echo "send:$1:$3"; rss=$((rss - pushed)); swap=$((swap + pushed)); _bl_pageout_complete=$complete; }
''' + functions + '\nbl_memory_read\n' + body
result = run_bash(harness)
result = run_bash('NOW=0\n' + harness.replace('SECONDS', 'NOW'))
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual('', result.stderr)
return result.stdout.splitlines()
@@ -229,9 +229,34 @@ echo "backoff:$_bl_tier_backoff"
self.assertEqual(['send:1:game', 'send:1:game'], self.run_policy('''
_bl_tier_backoff=300
SECONDS=0; bl_session_pressure
swap=0
SECONDS=20; bl_session_pressure
SECONDS=30; bl_session_pressure
'''))
def test_nearly_out_of_memory_still_backs_off_when_the_game_reads_its_pageout_back(self):
self.memory(available=512)
self.assertEqual(['send:1:game', 'backoff:60', 'send:1:game'], self.run_policy('''
SECONDS=0; bl_session_pressure
swap=0
SECONDS=30; bl_session_pressure
echo "backoff:$_bl_tier_backoff"
SECONDS=59; bl_session_pressure
SECONDS=60; bl_session_pressure
SECONDS=90; bl_session_pressure
'''))
def test_nearly_out_of_memory_retries_a_skipped_pageout_after_30_seconds(self):
self.memory(available=512)
self.assertEqual(['send:1:game', 'send:1:game'], self.run_policy('''
SECONDS=0; bl_session_pressure
swap=0
SECONDS=30; bl_session_pressure
_bl_tier_backoff=300
saved=$rss; rss=$((128 * 1024))
SECONDS=330; bl_session_pressure
rss=$saved
SECONDS=359; bl_session_pressure
SECONDS=360; bl_session_pressure
'''))
def test_small_swap_headroom_skips_the_pageout(self):
+64
View File
@@ -118,6 +118,7 @@ PROGRAM = r"""
#include <sys/resource.h>
#include <sys/socket.h>
#include <sys/syscall.h>
#include <sys/uio.h>
#include <sys/wait.h>
#include <unistd.h>
@@ -317,6 +318,8 @@ static void *ordinary_traffic(void *argument) {
probe_end(counts);
require(counts[0] == 0, "ordinary setup avoids netlink lock");
int pipes[2];
require(pipe(pipes) == 0, "ordinary pipe setup");
probe_begin(0);
const int rounds = 32;
for (int round = 0; round < rounds; round++) {
@@ -338,6 +341,15 @@ static void *ordinary_traffic(void *argument) {
message.msg_name = &source;
message.msg_namelen = sizeof(source);
require(recvmsg(server, &message, 0) == 1 && buffer == 'z', "ordinary recvmsg");
require(write(client, "w", 1) == 1, "ordinary write");
require(read(server, &buffer, 1) == 1 && buffer == 'w', "ordinary read");
char pair[2];
struct iovec pieces[2] = {{.iov_base = "v", .iov_len = 1}, {.iov_base = "u", .iov_len = 1}};
require(writev(client, pieces, 2) == 2, "ordinary writev");
require(recv(server, pair, 2, MSG_WAITALL) == 2 && pair[0] == 'v' && pair[1] == 'u',
"ordinary writev data");
require(write(pipes[1], "p", 1) == 1 && read(pipes[0], &buffer, 1) == 1 && buffer == 'p',
"ordinary pipe");
length = sizeof(source);
require(getpeername(client, (struct sockaddr *)&source, &length) == 0, "ordinary peer");
const int options[] = {SO_TYPE, SO_DOMAIN, SO_PROTOCOL};
@@ -368,6 +380,8 @@ static void *ordinary_traffic(void *argument) {
require(counts[2] == (unsigned)rounds, "ordinary traffic has only requested getpeername");
require(counts[3] == 0, "ordinary traffic avoids restoration fstat");
require(counts[4] == (unsigned)rounds * 3, "ordinary socket options use one syscall each");
close(pipes[0]);
close(pipes[1]);
close(client);
close(server);
if (server != listener) close(listener);
@@ -798,6 +812,52 @@ static void connect_test(void) {
close(descriptor);
}
static ssize_t link_reply(int descriptor, const char *path, unsigned char *buffer, size_t capacity) {
struct {
struct nlmsghdr header;
struct ifinfomsg info;
} query = {
.header = {.nlmsg_len = sizeof(query), .nlmsg_type = RTM_GETLINK,
.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK, .nlmsg_seq = 42},
.info = {.ifi_index = 1}
};
struct iovec parts[2] = {{.iov_base = &query.header, .iov_len = sizeof(query.header)},
{.iov_base = &query.info, .iov_len = sizeof(query.info)}};
struct msghdr message = {.msg_iov = parts, .msg_iovlen = 2};
ssize_t sent;
if (!strcmp(path, "send")) sent = send(descriptor, &query, sizeof(query), 0);
else if (!strcmp(path, "sendmsg")) sent = sendmsg(descriptor, &message, 0);
else if (!strcmp(path, "write")) sent = write(descriptor, &query, sizeof(query));
else sent = writev(descriptor, parts, 2);
require(sent == sizeof(query), path);
ssize_t received = read(descriptor, buffer, capacity);
require(received > 0, "read reply");
return received;
}
static void write_test(void) {
const char *paths[] = {"send", "sendmsg", "write", "writev"};
unsigned char expected[4096];
int descriptor = route_socket();
ssize_t expected_length = link_reply(descriptor, paths[0], expected, sizeof(expected));
struct nlmsghdr *header = (struct nlmsghdr *)expected;
require(header->nlmsg_type == RTM_NEWLINK && header->nlmsg_seq == 42
&& header->nlmsg_pid == port_of(descriptor), "send reply");
require(expected_length > (ssize_t)NLMSG_ALIGN(header->nlmsg_len), "acknowledged reply");
struct nlmsghdr *acknowledgement = (struct nlmsghdr *)(expected + NLMSG_ALIGN(header->nlmsg_len));
require(acknowledgement->nlmsg_type == NLMSG_ERROR
&& ((struct nlmsgerr *)NLMSG_DATA(acknowledgement))->error == 0, "send acknowledgement");
for (size_t index = 1; index < sizeof(paths) / sizeof(paths[0]); index++) {
unsigned char buffer[4096];
ssize_t length = link_reply(descriptor, paths[index], buffer, sizeof(buffer));
require(length == expected_length, "reply length");
require(!memcmp(buffer, expected, length), "reply bytes");
}
require(recv(descriptor, expected, sizeof(expected), MSG_DONTWAIT) == -1 && errno == EAGAIN,
"no extra replies");
close(descriptor);
}
static void receive_test(void) {
int descriptor = route_socket();
send_link(descriptor, 1, 0);
@@ -985,6 +1045,7 @@ int main(int argc, char **argv) {
else if (!strcmp(argv[1], "nonblocking")) send_timeout_test(1);
else if (!strcmp(argv[1], "connect")) connect_test();
else if (!strcmp(argv[1], "receive")) receive_test();
else if (!strcmp(argv[1], "write")) write_test();
else if (!strcmp(argv[1], "replace")) replacement_test(0);
else if (!strcmp(argv[1], "raw_replace")) replacement_test(1);
else if (!strcmp(argv[1], "shared")) shared_test(0);
@@ -1160,6 +1221,9 @@ class NetlinkPreloadTest(unittest.TestCase):
def test_kernel_connect_and_disconnect(self):
self.run_program("connect")
def test_write_and_writev_requests_get_the_same_replies_as_send(self):
self.run_program("write")
def test_receive_sources_and_truncation(self):
self.run_program("receive")
+109 -5
View File
@@ -14,17 +14,30 @@ class PrDiscordTest(unittest.TestCase):
self.discord.request.return_value = {"id": "1557547293375332465"}
self.github = patch.object(module, "github").start()
self.addCleanup(patch.stopall)
self.github.side_effect = lambda path, method="GET", body=None: self.pull if "/pulls/" in path else self.comment
def github_request(path, method="GET", body=None):
if "/pulls/" in path:
return self.pull
if "/commits/" in path:
return {"commit": {"message": "Fix reconnect behavior\n\nMore details"}}
if path.endswith("/issues/comments/10"):
if method == "PATCH":
self.comment["body"] = body["body"]
return self.comment
return self.comment
self.github.side_effect = github_request
patch.object(module, "report_comment", return_value=self.comment).start()
def publish(self):
module.sync("publish", "Droid-Deck/DroidDeck", "410", self.discord, "a" * 40,
def publish(self, sha=None):
if sha is not None:
self.pull["head"]["sha"] = sha
sha = sha or "a" * 40
module.sync("publish", "Droid-Deck/DroidDeck", "410", self.discord, sha,
"https://github.com/Droid-Deck/DroidDeck-CI/releases/download/pr-410/build.apk",
"https://github.com/Droid-Deck/DroidDeck-CI/releases/tag/pr-410")
def save_state(self):
self.comment["body"] += '\n<!-- droiddeck-discord: ' + json.dumps({
"webhook_id": self.discord.id, "message_id": "1557547293375332465"}) + ' -->'
"webhook_id": self.discord.id, "message_id": "1557547293375332465", "sha": "a" * 40}) + ' -->'
def test_create_confirmed_message_and_persist_reference(self):
self.publish()
@@ -36,12 +49,76 @@ class PrDiscordTest(unittest.TestCase):
self.assertEqual("1557547293375332465", module.saved_message(saved, self.discord.id))
self.assertIn("Build download", saved)
def test_new_build_updates_existing_message(self):
def test_same_build_updates_existing_message_without_duplicate(self):
self.save_state()
self.publish()
self.assertEqual("PATCH", self.discord.request.call_args.args[0])
saved = self.github.call_args.args[2]["body"]
self.assertEqual(1, len(module.STATE.findall(saved)))
self.assertIn('"sha": "' + "a" * 40 + '"', saved)
def test_new_commit_retires_old_message_and_posts_replacement(self):
self.save_state()
old_content = module.build_content("Droid-Deck/DroidDeck", "410", self.pull["title"], "a" * 40,
"apk", "release")
self.discord.request.side_effect = [
{"content": old_content}, {"id": "1557547293375332465"}, {"id": "1557547293375332466"}]
self.publish("b" * 40)
calls = self.discord.request.call_args_list
self.assertEqual(["GET", "PATCH", "POST"], [call.args[0] for call in calls])
self.assertIn("**Superseded by `bbbbbbb`**", calls[1].args[2]["content"])
self.assertIn("~~Download:", calls[1].args[2]["content"])
self.assertIn("Latest commit: Fix reconnect behavior", calls[2].args[2]["content"])
saved = self.github.call_args.args[2]["body"]
self.assertEqual("1557547293375332466", module.saved_message(saved, self.discord.id))
self.assertIn('"sha": "' + "b" * 40 + '"', saved)
def test_publish_supersede_rerun_and_close_lifecycle(self):
messages = {}
created = []
next_id = 1
def discord_request(method, suffix="", body=None):
nonlocal next_id
if method == "POST":
message_id = str(1557547293375332465 + next_id)
next_id += 1
messages[message_id] = {"id": message_id, "content": body["content"]}
created.append(message_id)
return messages[message_id]
message_id = suffix.split("/")[-1]
if method == "GET":
return messages.get(message_id)
if method == "PATCH":
if message_id not in messages:
return None
messages[message_id].update(body)
return messages[message_id]
self.fail(f"Unexpected Discord method: {method}")
self.discord.request.side_effect = discord_request
self.publish("a" * 40)
first_id = created[-1]
self.publish("b" * 40)
second_id = created[-1]
self.publish("b" * 40)
self.assertEqual(2, len(created))
self.assertIn("**Superseded by `bbbbbbb`**", messages[first_id]["content"])
self.assertIn("`bbbbbbb`", messages[second_id]["content"])
self.pull.update(state="closed", merged=True)
module.sync("retire", "Droid-Deck/DroidDeck", "410", self.discord)
self.assertTrue(messages[second_id]["content"].startswith("**Merged**"))
self.assertIn("~~Latest commit:", messages[second_id]["content"])
def test_legacy_state_uses_embedded_short_sha_to_supersede(self):
self.save_state()
self.comment["body"] = self.comment["body"].replace(', "sha": "' + "a" * 40 + '"', '')
old_content = "**Signed test build** `pr-410` · `aaaaaaa`\nold build"
self.discord.request.side_effect = [
{"content": old_content}, {"id": "1557547293375332465"}, {"id": "1557547293375332466"}]
self.publish("b" * 40)
self.assertEqual(["GET", "PATCH", "POST"], [call.args[0] for call in self.discord.request.call_args_list])
def test_deleted_message_is_recreated(self):
self.save_state()
@@ -78,6 +155,10 @@ class PrDiscordTest(unittest.TestCase):
module.sync("retire", "Droid-Deck/DroidDeck", "410", self.discord)
self.discord.request.assert_not_called()
def test_superseded_content_is_idempotent(self):
once = module.retired_content("first\n\nlast", superseded_by="a" * 40)
self.assertEqual(once, module.retired_content(once, superseded_by="a" * 40))
def test_old_build_without_saved_id_is_not_guessed(self):
self.pull["state"] = "closed"
module.sync("retire", "Droid-Deck/DroidDeck", "410", self.discord)
@@ -153,6 +234,29 @@ class PrDiscordTest(unittest.TestCase):
self.assertLessEqual(len(content), 1800)
self.assertLessEqual(len(module.retired_content(content, True)), 2000)
def test_commit_subject_is_sanitized_and_uses_only_first_line(self):
content = module.build_content("Droid-Deck/DroidDeck", "410", "title", "a" * 40,
"apk", "release", commit_message="Fix *input* @everyone\nDetails")
self.assertIn(r"Latest commit: Fix \*input\* @everyone", content)
self.assertNotIn("Details", content)
def test_commit_lookup_failure_does_not_block_announcement(self):
def unavailable_commit(path, method="GET", body=None):
if "/commits/" in path:
raise RuntimeError("GitHub request failed")
return self.pull if "/pulls/" in path else self.comment
self.github.side_effect = unavailable_commit
self.publish()
self.assertEqual("POST", self.discord.request.call_args.args[0])
self.assertNotIn("Latest commit:", self.discord.request.call_args.args[2]["content"])
def test_empty_commit_response_does_not_block_announcement(self):
self.github.side_effect = lambda path, method="GET", body=None: (
self.pull if "/pulls/" in path else None if "/commits/" in path else self.comment)
self.publish()
self.assertEqual("POST", self.discord.request.call_args.args[0])
self.assertNotIn("Latest commit:", self.discord.request.call_args.args[2]["content"])
original_report = module.report_comment
+55
View File
@@ -0,0 +1,55 @@
import re
import shutil
import subprocess
import tempfile
import unittest
from pathlib import Path
SESSION = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-session"
FAKE_DAEMON = """#!/usr/bin/env python3
import socket, sys, time
address = next(a for a in sys.argv if a.startswith("--address="))
path = address.split("unix:path=", 1)[1]
open(sys.argv[0] + ".args", "w").write(" ".join(sys.argv[1:]))
s = socket.socket(socket.AF_UNIX)
s.bind(path)
time.sleep(5)
"""
class SessionBusTest(unittest.TestCase):
def setUp(self):
self.root = Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, self.root, True)
self.bin = self.root / "bin"
self.bin.mkdir()
self.runtime = self.root / "run"
self.runtime.mkdir()
daemon = self.bin / "dbus-daemon"
daemon.write_text(FAKE_DAEMON)
daemon.chmod(0o755)
def run_block(self, env_address=""):
match = re.search(r'^ *if \[ -z "\$\{DBUS_SESSION_BUS_ADDRESS:-\}" \]; then\n.*?^ *fi\n *fi\n',
SESSION.read_text(), re.M | re.S)
self.assertIsNotNone(match)
script = "nap() { sleep \"$1\"; }\n" + match.group(0) + 'echo "ADDRESS=$DBUS_SESSION_BUS_ADDRESS"\nkill %1 2>/dev/null\n'
env = {"PATH": "%s:/usr/bin:/bin" % self.bin, "XDG_RUNTIME_DIR": str(self.runtime)}
if env_address:
env["DBUS_SESSION_BUS_ADDRESS"] = env_address
return subprocess.run(["bash", "-c", script], env=env, capture_output=True, text=True, timeout=30).stdout
def test_steam_mode_exports_its_own_session_bus(self):
out = self.run_block()
self.assertIn("ADDRESS=unix:path=%s/bus" % self.runtime, out)
self.assertIn("--session", (self.bin / "dbus-daemon.args").read_text())
def test_an_existing_session_bus_is_kept(self):
out = self.run_block("unix:path=/somewhere/else")
self.assertIn("ADDRESS=unix:path=/somewhere/else", out)
self.assertFalse((self.bin / "dbus-daemon.args").exists())
if __name__ == "__main__":
unittest.main()
+28
View File
@@ -769,6 +769,34 @@ class ReconcileTest(unittest.TestCase):
self.assertEqual(default, build)
self.assertEqual(COMPAT["read_config_mapping"](str(config)), {"0": build, "10": build, "11": build})
def test_proton_experimental_picked_for_a_game_in_steam_is_kept_and_mirrored(self):
build = "DroidDeck-Proton 11-12.3"
(self.steam / "compatibilitytools.d" / build).mkdir(parents=True)
(self.steam / "compatibilitytools.d" / build / COMPAT["EXTRA_WRAPPER"]).write_text("")
(self.state / "state.json").write_text(json.dumps(
{"default": build, "written": build, "source": "update", "auto": {"11": build}, "picked": ["10", "11"], "tools": [],
"games_applied": {"10": {"valve": False, "dir": build}}}))
self.write_games({"10": {"valve": False, "dir": build}})
page = FakePage({"0": build, "10": "proton_experimental", "11": build}, [TOOL, TOOL_11, build, "proton_experimental"])
state = self.reconcile(page)
self.assertEqual(page.sets, [("10", TOOL)])
self.assertEqual(state["auto"], {"11": build})
self.assertEqual(self.games(), {"10": {"valve": True, "dir": COMPAT["SOURCES"][0]}})
config = self.steam / "config/config.vdf"
config.parent.mkdir(parents=True)
vdf = '"InstallConfigStore" { "Software" { "Valve" { "Steam" { "CompatToolMapping" { %s } } } } }'
entry = '"%s" { "name" "%s" "config" "" "priority" "250" }'
config.write_text(vdf % "".join(entry % (app, page.mapping[app]) for app in ("0", "10", "11")))
with mock.patch.dict(COMPAT["register_default"].__globals__, steam_running=lambda: False):
default = COMPAT["register_default"](str(config), ["10", "11"], catalog=COMPAT["tool_catalog"](str(self.steam)),
directory=str(self.state), settle=True)
self.assertEqual(default, build)
self.assertEqual(COMPAT["read_config_mapping"](str(config)), {"0": build, "10": TOOL, "11": build})
page.sets.clear()
self.write_games({"10": {"valve": True, "dir": COMPAT["SOURCES"][1]}})
self.reconcile(page)
self.assertEqual(page.sets, [("10", TOOL_11)])
def test_file_mode_defers_to_the_live_helper(self):
(self.state / "live.pid").write_text("%d\n" % os.getpid())
self.assertTrue(COMPAT["live_helper_running"]())
+215
View File
@@ -0,0 +1,215 @@
import json
import os
from pathlib import Path
import select
import tempfile
import unittest
from unittest import mock
from tools.tests import test_droiddeck_fex as fixtures
from tools.tests import test_steam_compat_live as live
from tools.tests.test_steam_compat_mapping import config_text
COMPAT = live.COMPAT
TOOL = COMPAT["TOOL"]
class ToolPlatformsTest(unittest.TestCase):
def setUp(self):
temporary = tempfile.TemporaryDirectory()
self.addCleanup(temporary.cleanup)
self.root = Path(temporary.name)
self.steam = self.root / "Steam"
self.state = self.root / "state"
self.config = self.steam / "config/config.vdf"
self.config.parent.mkdir(parents=True)
self.state.mkdir()
(self.steam / "appcache").mkdir()
(self.steam / "steamapps").mkdir()
self.entries = {
976730: ("windows", "64", "game"),
1826330: ("linux", "", "tool"),
1161040: ("linux", "", "tool"),
900001: ("windows", "64", "tool"),
900002: ("linux", "arm64", "tool"),
900003: ("osx", "64", "tool"),
900004: ("", "", "tool"),
900005: ("linux,windows", "64", "tool"),
}
self.write_appinfo()
self.catalog = [{"name": TOOL, "display": "Proton", "dir": "Proton", "valve": True}]
self.config.write_text(config_text('"0" { "name" "%s" }' % TOOL))
patcher = mock.patch.dict(COMPAT["register_default"].__globals__, COMPAT_DIR=str(self.state))
patcher.start()
self.addCleanup(patcher.stop)
def write_appinfo(self, magic=0x07564429):
(self.steam / "appcache/appinfo.vdf").write_bytes(fixtures.AppInfoTest.appinfo(self.entries, magic))
def platforms(self):
return COMPAT["tool_platforms"](str(self.steam))
def plan(self, current, auto=None, **kwargs):
return COMPAT["plan_mapping"](current, ["976730"], [TOOL], TOOL, auto or {},
tools=self.platforms(), **kwargs)
def test_metadata_selects_tools_across_cache_formats(self):
for magic in (0x07564427, 0x07564428, 0x07564429):
with self.subTest(magic=magic):
self.write_appinfo(magic)
self.assertEqual(set(self.platforms()), {"1826330", "1161040", "900001", "900002", "900005"})
def test_tools_are_not_installed_games(self):
for app in self.entries:
(self.steam / ("steamapps/appmanifest_%s.acf" % app)).write_text("")
self.assertEqual(COMPAT["installed_apps"](str(self.steam)), ["976730"])
def test_linux_tools_clear_proton_and_windows_tools_get_default_before_install(self):
current = {"0": TOOL, "976730": TOOL, "1826330": TOOL, "1161040": "proton_experimental"}
changes, auto = self.plan(current, {"1826330": TOOL, "976730": TOOL})
self.assertEqual(changes, {"1826330": None, "1161040": None, "900001": TOOL})
self.assertNotIn("1826330", auto)
self.assertEqual(auto["900001"], TOOL)
self.assertEqual(auto["976730"], TOOL)
def test_removed_ge_proton_is_cleared_with_or_without_saved_ownership(self):
for saved in ({}, {"1826330": "GE-Proton11-7"}):
with self.subTest(saved=saved):
changes, auto = self.plan({"0": TOOL, "1826330": "GE-Proton11-7"}, saved)
self.assertIsNone(changes["1826330"])
self.assertNotIn("1826330", auto)
def test_removed_ge_proton_game_selection_survives(self):
changes, auto = self.plan({"0": TOOL, "976730": "GE-Proton11-7"})
self.assertNotIn("976730", changes)
self.assertNotIn("976730", auto)
def test_saved_native_selections_survive(self):
for name in (COMPAT["FEX_TOOL"], "custom-native"):
with self.subTest(name=name):
changes, auto = self.plan({"0": TOOL, "1826330": name}, {"1826330": name})
self.assertNotIn("1826330", changes)
self.assertNotIn("1826330", auto)
def test_main_watches_cache_updates_and_replacements(self):
class StopWatching(BaseException):
pass
watchers = []
def capture(files):
watcher = live.LIVE["Watcher"](files)
watchers.append(watcher)
raise StopWatching()
namespace = live.LIVE["main"].__globals__
with mock.patch.dict(namespace, Watcher=capture), mock.patch.dict(os.environ, BL_CDP_PORT="1"), \
mock.patch.object(live.LIVE["sys"], "argv", ["compat", str(self.steam)]):
with self.assertRaises(StopWatching):
live.LIVE["main"]()
watcher = watchers[0]
if watcher.fd >= 0:
self.addCleanup(os.close, watcher.fd)
self.assertFalse(watcher.changed())
self.entries[900006] = ("linux", "", "tool")
self.write_appinfo()
self.assertTrue(watcher.changed())
self.assertIn("900006", self.platforms())
cache = self.steam / "appcache/appinfo.vdf"
replacement = cache.with_suffix(".tmp")
replacement.write_bytes(cache.read_bytes())
replacement.replace(cache)
self.assertTrue(watcher.changed())
def test_watcher_follows_an_appcache_created_after_startup(self):
root = self.root / "late"
(root / "state").mkdir(parents=True)
watcher = live.LIVE["Watcher"]([str(root / "state/request.json"), str(root / "appcache/appinfo.vdf")])
self.assertGreaterEqual(watcher.fd, 0)
self.addCleanup(os.close, watcher.fd)
self.assertFalse(watcher.changed())
(root / "appcache").mkdir()
self.assertTrue(watcher.changed())
(root / "appcache/appinfo.vdf").write_bytes(b"x")
self.assertTrue(watcher.changed())
def test_watcher_follows_each_missing_directory_level(self):
root = self.root / "levels"
root.mkdir()
target = root / "sd/steamapps/appmanifest_1.acf"
watcher = live.LIVE["Watcher"]([str(target)])
self.assertGreaterEqual(watcher.fd, 0)
self.addCleanup(os.close, watcher.fd)
(root / "sd").mkdir()
self.assertTrue(select.select([watcher.fd], [], [], 1)[0])
self.assertFalse(watcher.changed())
(root / "sd/steamapps").mkdir()
self.assertTrue(select.select([watcher.fd], [], [], 1)[0])
self.assertTrue(watcher.changed())
target.write_bytes(b"x")
self.assertTrue(watcher.changed())
def test_linux_tool_requests_cannot_restore_windows_platform(self):
changes, auto = self.plan({"0": TOOL, "1826330": TOOL}, overrides={"1826330": TOOL})
self.assertIsNone(changes["1826330"])
self.assertNotIn("1826330", auto)
def test_linux_execution_tools_and_custom_selections_survive(self):
current = {"0": TOOL, "1826330": COMPAT["FEX_TOOL"], "900002": "custom-native",
"900001": "custom-windows", "900005": TOOL}
changes, auto = self.plan(current)
self.assertEqual(changes, {"976730": TOOL})
self.assertNotIn("1826330", auto)
def test_missing_or_malformed_cache_does_not_invent_platforms(self):
cache = self.steam / "appcache/appinfo.vdf"
cache.unlink()
self.assertEqual(self.platforms(), {})
cache.write_bytes(b"invalid")
self.assertEqual(self.platforms(), {})
def test_offline_repair_is_idempotent_and_preserves_game_and_neighbor_fields(self):
self.config.write_text(config_text(
'"0" { "name" "%s" } "976730" { "name" "custom-game" } '
'"1826330" { "name" "%s" }' % (TOOL, TOOL)))
for _ in range(2):
COMPAT["register_default"](str(self.config), ["976730"], catalog=self.catalog,
directory=str(self.state), default=TOOL)
self.assertEqual(COMPAT["read_config_mapping"](str(self.config)),
{"0": TOOL, "976730": "custom-game", "900001": TOOL})
self.assertIn('"outside"', self.config.read_text())
state = json.loads((self.state / "state.json").read_text())
self.assertNotIn("1826330", state["auto"])
def reconcile(self, page):
helper = live.LIVE["Helper"](str(self.steam), 1)
helper.page = page
with mock.patch.dict(COMPAT, tool_catalog=lambda root: self.catalog):
helper.reconcile()
return json.loads((self.state / "state.json").read_text())
def test_live_repair_covers_uninstalled_dependencies_and_stays_idempotent(self):
page = live.FakePage({"0": TOOL, "1826330": TOOL, "976730": "custom-game"}, [TOOL])
state = self.reconcile(page)
self.assertEqual(page.sets, [("900001", TOOL), ("1826330", "")])
self.assertNotIn("1826330", state["auto"])
page.sets.clear()
self.reconcile(page)
self.assertEqual(page.sets, [])
self.assertEqual(page.mapping["976730"], "custom-game")
def test_live_removed_ge_proton_is_cleared_and_stays_cleared(self):
page = live.FakePage({"0": TOOL, "1826330": "GE-Proton11-7"}, [TOOL])
(self.state / "state.json").write_text(json.dumps({"auto": {"1826330": "GE-Proton11-7"}}))
state = self.reconcile(page)
self.assertIn(("1826330", ""), page.sets)
self.assertNotIn("1826330", state["auto"])
page.sets.clear()
self.reconcile(page)
self.assertEqual(page.sets, [])
def test_live_refused_tools_are_not_written(self):
page = live.FakePage({"0": TOOL, "1826330": TOOL}, [TOOL], refused={"1826330", "900001"})
self.reconcile(page)
self.assertEqual(page.sets, [])
+190 -1
View File
@@ -387,6 +387,193 @@ def set_registry(**arguments):
return {'install': {'action': 'setRegistry', 'arguments': arguments}, 'name': 'setRegistry'}
def support_data(**arguments):
return {'install': {'action': 'supportData', 'arguments': arguments}, 'name': 'supportData'}
class GogSupportData(unittest.TestCase):
def prefix(self, root):
user = Path(root) / 'compat/pfx/drive_c/users/steamuser'
user.mkdir(parents=True)
return user
def test_support_files_reach_the_prefix_once(self):
with tempfile.TemporaryDirectory() as root:
folder = game(root, store_id='gog', ident='9')
user = self.prefix(root)
support = folder / 'support/9'
(support / 'Docs').mkdir(parents=True)
(support / 'Docs/Fallout4.ini').write_text('[Archive]\n')
(support / 'Plugins.txt').write_text('*LondonWorldSpace.esm\n')
(folder / '__AppData/Saves').mkdir(parents=True)
(folder / '__AppData/Saves/a.txt').write_text('a')
gog_script(folder, '9', [
set_registry(root='HKLM', subkey='Software\\Game', valueName='a', valueData='b', valueType='string'),
support_data(type='folder', target='{userdocs}/My Games/Fallout4'),
support_data(type='file', overwrite=True, source='{supportDir}/docs/Fallout4.ini',
target='{userdocs}/My Games/Fallout4/Fallout4.ini'),
support_data(type='file', overwrite=True, source='{supportDir}/Plugins.txt',
target='{localappdata}/Fallout4/Plugins.txt'),
support_data(type='folder', overwrite=True, source='{app}/__AppData', target='{localappdata}/Fallout4'),
])
with patch.object(store, 'create_prefix') as create:
self.assertEqual('copied=3', store.gog_support_data(folder, root + '/compat', '/proton'))
create.assert_not_called()
self.assertTrue((user / 'Documents/My Games/Fallout4').is_dir())
self.assertEqual('[Archive]\n', (user / 'Documents/My Games/Fallout4/Fallout4.ini').read_text())
self.assertEqual('*LondonWorldSpace.esm\n', (user / 'AppData/Local/Fallout4/Plugins.txt').read_text())
self.assertEqual('a', (user / 'AppData/Local/Fallout4/Saves/a.txt').read_text())
(user / 'AppData/Local/Fallout4/Plugins.txt').write_text('player order')
self.assertEqual('ready', store.gog_support_data(folder, root + '/compat', '/proton'))
self.assertEqual('player order', (user / 'AppData/Local/Fallout4/Plugins.txt').read_text())
def test_a_source_the_build_lacks_does_not_recopy_the_rest_every_launch(self):
with tempfile.TemporaryDirectory() as root:
folder = game(root, store_id='gog', ident='9')
user = self.prefix(root)
(folder / 'support/9').mkdir(parents=True)
(folder / 'support/9/Plugins.txt').write_text('x')
gog_script(folder, '9', [
support_data(type='file', overwrite=True, source='{supportDir}/Plugins.txt', target='{localappdata}/G/Plugins.txt'),
support_data(type='folder', overwrite=True, source='{app}/__AppData', target='{localappdata}/G'),
])
self.assertEqual('copied=1 missing=1', store.gog_support_data(folder, root + '/compat', '/proton'))
(user / 'AppData/Local/G/Plugins.txt').write_text('player order')
self.assertEqual('ready', store.gog_support_data(folder, root + '/compat', '/proton'))
self.assertEqual('player order', (user / 'AppData/Local/G/Plugins.txt').read_text())
def test_a_link_never_carries_a_copy_outside(self):
with tempfile.TemporaryDirectory() as root:
folder = game(root, store_id='gog', ident='9')
user = self.prefix(root)
outside = Path(root) / 'outside'
outside.mkdir()
(outside / 'secret.ini').write_text('s')
(folder / '__AppData').mkdir()
(folder / '__AppData/linked').symlink_to(outside)
(folder / 'support/9').mkdir(parents=True)
(folder / 'support/9/a.ini').write_text('a')
gog_script(folder, '9', [
support_data(type='folder', overwrite=True, source='{app}/__AppData', target='{localappdata}/G'),
support_data(type='file', overwrite=True, source='{supportDir}/a.ini', target='{localappdata}/G/linked/a.ini'),
support_data(type='file', overwrite=True, source='{app}/__AppData/linked/secret.ini', target='{userdocs}/secret.ini'),
])
self.assertEqual('copied=1 skipped=2', store.gog_support_data(folder, root + '/compat', '/proton'))
self.assertTrue((user / 'AppData/Local/G/linked').is_symlink())
self.assertEqual(['secret.ini'], sorted(p.name for p in outside.iterdir()))
self.assertFalse((user / 'Documents/secret.ini').exists())
def test_a_linked_source_folder_is_copied_as_a_link(self):
with tempfile.TemporaryDirectory() as root:
folder = game(root, store_id='gog', ident='9')
user = self.prefix(root)
outside = Path(root) / 'outside'
outside.mkdir()
(outside / 'secret.ini').write_text('s')
(folder / 'linked').symlink_to(outside)
gog_script(folder, '9', [support_data(type='folder', overwrite=True, source='{app}/linked', target='{userdocs}/G')])
store.gog_support_data(folder, root + '/compat', '/proton')
self.assertTrue((user / 'Documents/G').is_symlink())
self.assertEqual(outside, Path(os.readlink(user / 'Documents/G')))
def test_a_players_own_links_stay_without_overwrite(self):
with tempfile.TemporaryDirectory() as root:
folder = game(root, store_id='gog', ident='9')
user = self.prefix(root)
(folder / 'support/9/Saves').mkdir(parents=True)
(folder / 'support/9/a.ini').write_text('a')
(folder / 'support/9/Saves/b.ini').write_text('b')
(user / 'Documents/G').mkdir(parents=True)
(user / 'Documents/a.ini').symlink_to(user / 'mine.ini')
(user / 'Documents/G/b.ini').symlink_to(user / 'gone.ini')
gog_script(folder, '9', [
support_data(type='file', source='{supportDir}/a.ini', target='{userdocs}/a.ini'),
support_data(type='folder', source='{supportDir}/Saves', target='{userdocs}/G'),
])
self.assertEqual('copied=0', store.gog_support_data(folder, root + '/compat', '/proton'))
self.assertEqual(user / 'mine.ini', Path(os.readlink(user / 'Documents/a.ini')))
self.assertEqual(user / 'gone.ini', Path(os.readlink(user / 'Documents/G/b.ini')))
def test_a_changed_script_applies_again(self):
with tempfile.TemporaryDirectory() as root:
folder = game(root, store_id='gog', ident='9')
user = self.prefix(root)
(folder / 'support/9').mkdir(parents=True)
(folder / 'support/9/a.ini').write_text('1')
action = support_data(type='file', overwrite=True, source='{supportDir}/a.ini', target='{userdocs}/a.ini')
gog_script(folder, '9', [action])
self.assertEqual('copied=1', store.gog_support_data(folder, root + '/compat', '/proton'))
(folder / 'support/9/b.ini').write_text('2')
gog_script(folder, '9', [action, support_data(type='file', overwrite=True, source='{supportDir}/b.ini',
target='{userdocs}/b.ini')])
self.assertEqual('copied=2', store.gog_support_data(folder, root + '/compat', '/proton'))
self.assertEqual('2', (user / 'Documents/b.ini').read_text())
def test_a_players_file_is_kept_unless_the_script_overwrites_it(self):
with tempfile.TemporaryDirectory() as root:
folder = game(root, store_id='gog', ident='9')
user = self.prefix(root)
(folder / 'support/9').mkdir(parents=True)
(folder / 'support/9/a.ini').write_text('default')
(user / 'Documents').mkdir()
(user / 'Documents/a.ini').write_text('mine')
gog_script(folder, '9', [support_data(type='file', source='{supportDir}/a.ini', target='{userdocs}/a.ini')])
self.assertEqual('copied=0', store.gog_support_data(folder, root + '/compat', '/proton'))
self.assertEqual('mine', (user / 'Documents/a.ini').read_text())
def test_paths_outside_the_known_folders_are_refused(self):
with tempfile.TemporaryDirectory() as root:
folder = game(root, store_id='gog', ident='9')
self.prefix(root)
(folder / 'support/9').mkdir(parents=True)
(folder / 'support/9/a.ini').write_text('x')
gog_script(folder, '9', [
support_data(type='file', overwrite=True, source='{supportDir}/a.ini', target='{userdocs}/../../../../escape.ini'),
support_data(type='file', overwrite=True, source='{supportDir}/a.ini', target='C:/escape.ini'),
support_data(type='folder', target='{windir}/x'),
])
self.assertEqual('copied=0 skipped=3', store.gog_support_data(folder, root + '/compat', '/proton'))
self.assertEqual([], list(Path(root).rglob('escape.ini')))
self.assertFalse((Path(root) / 'compat/pfx' / store.GOG_SUPPORT_MARK).exists())
def test_links_in_a_support_folder_are_copied_as_links(self):
with tempfile.TemporaryDirectory() as root:
folder = game(root, store_id='gog', ident='9')
user = self.prefix(root)
outside = Path(root) / 'outside'
outside.mkdir()
(outside / 'secret.txt').write_text('s')
(folder / '__AppData').mkdir()
(folder / '__AppData/linked').symlink_to(outside, target_is_directory=True)
gog_script(folder, '9', [support_data(type='folder', overwrite=True, source='{app}/__AppData', target='{localappdata}/G')])
self.assertEqual('copied=1', store.gog_support_data(folder, root + '/compat', '/proton'))
self.assertTrue((user / 'AppData/Local/G/linked').is_symlink())
self.assertEqual('s', (outside / 'secret.txt').read_text())
def test_without_support_data_no_prefix_is_made(self):
with tempfile.TemporaryDirectory() as root:
folder = game(root, store_id='gog', ident='9')
gog_script(folder, '9', [set_registry(root='HKLM', subkey='Software\\Game', valueName='a', valueData='b', valueType='string')])
with patch.object(store, 'create_prefix') as create:
self.assertEqual('none', store.gog_support_data(folder, root + '/compat', '/proton'))
create.assert_not_called()
def test_a_missing_prefix_is_made_first(self):
with tempfile.TemporaryDirectory() as root:
folder = game(root, store_id='gog', ident='9')
gog_script(folder, '9', [support_data(type='folder', target='{userdocs}/My Games/G')])
with patch.object(store, 'create_prefix', return_value='failed') as create:
self.assertEqual('no-prefix', store.gog_support_data(folder, root + '/compat', '/proton'))
create.assert_called_once_with(root + '/compat', '/proton')
def made(compat_data, proton):
self.prefix(root)
return 'created'
with patch.object(store, 'create_prefix', side_effect=made):
self.assertEqual('copied=0', store.gog_support_data(folder, root + '/compat', '/proton'))
self.assertTrue((Path(root) / 'compat/pfx/drive_c/users/steamuser/Documents/My Games/G').is_dir())
class GogRegistry(unittest.TestCase):
def test_patch_registration_uses_authentic_build_and_the_prefix_registry_executable(self):
with tempfile.TemporaryDirectory() as root:
@@ -605,6 +792,8 @@ class GogRegistry(unittest.TestCase):
folder = game(root, store_id='gog')
with patch.dict(os.environ, {'BL_LAUNCH_DIR': root, 'STEAM_COMPAT_DATA_PATH': root + '/compat/', 'BL_STORE_PROTON': '/chosen/proton'}), \
patch.object(store, 'prepare_gog', return_value=False), patch.object(store, 'ask', return_value=None), \
patch.object(store, 'apply_gog_registry', return_value='ready') as apply:
patch.object(store, 'apply_gog_registry', return_value='ready') as apply, \
patch.object(store, 'gog_support_data', return_value='ready') as support:
store.main([str(folder / store.LAUNCHER)])
apply.assert_called_once_with(folder, root + '/compat', '/chosen/proton')
support.assert_called_once_with(folder, root + '/compat', '/chosen/proton')
Loaded 100 of 102 files, more files were not shown because too many files have changed in this diff. Show more