mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-06 04:55:44 +00:00
Compare commits
40
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8f3d8d0afa | ||
|
|
4ee3463c20 | ||
|
|
7b836d52c3 | ||
|
|
5530d8aa70 | ||
|
|
822ca6405f | ||
|
|
cca4ff3746 | ||
|
|
49f1ceaadc | ||
|
|
2d2ffd9d05 | ||
|
|
05d74c8a1f | ||
|
|
cb2334da4e | ||
|
|
8a89387ef8 | ||
|
|
47e528102d | ||
|
|
1d90448924 | ||
|
|
131ba72ee5 | ||
|
|
b2e3a3a5ea | ||
|
|
254e1db969 | ||
|
|
34e7191e02 | ||
|
|
5dfa6f43ed | ||
|
|
2ff30ab4bb | ||
|
|
aa27921dee | ||
|
|
581a7d1557 | ||
|
|
e07e436857 | ||
|
|
e0348adc02 | ||
|
|
a7b4d79c15 | ||
|
|
ae96d7fdaf | ||
|
|
e5145bfad5 | ||
|
|
b3c54e6cda | ||
|
|
a6a11cad54 | ||
|
|
615539dcd3 | ||
|
|
b121a89c8b | ||
|
|
d7b7193cbd | ||
|
|
ca166c670e | ||
|
|
42aa7692dc | ||
|
|
5786ddf81f | ||
|
|
ec3243a997 | ||
|
|
d5ef1c832a | ||
|
|
61ea96a9e8 | ||
|
|
ed2160c137 | ||
|
|
c9fb19b0cd | ||
|
|
9a6558d8b3 |
No files matched your search
@@ -0,0 +1,57 @@
|
||||
name: Build FEX (x86-64 Steam client experiment)
|
||||
|
||||
# FEX built for the runtime in an Arch Linux ARM container on an arm64 runner (tools/fex), for the
|
||||
# opt-in x86-64 Steam client (bannerlator-steam-x64). Published as a release asset that script
|
||||
# fetches; the runtime image and the default arm64 client are untouched.
|
||||
on:
|
||||
push:
|
||||
paths:
|
||||
- 'tools/fex/**'
|
||||
- '.github/workflows/build-fex.yml'
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: 'Release tag to publish as (e.g. fex-2609-r1); empty = artifact only'
|
||||
required: false
|
||||
default: ''
|
||||
thunks:
|
||||
description: 'Build the host thunks (Vulkan/GL/X11/... to the runtime arm64 libraries)'
|
||||
required: false
|
||||
default: 'false'
|
||||
cxxflags:
|
||||
description: 'Extra CXXFLAGS for a diagnostic build (e.g. -DDEBUG_STRACE); never published with a tag'
|
||||
required: false
|
||||
default: ''
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-24.04-arm
|
||||
timeout-minutes: 120
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Build in Arch Linux ARM
|
||||
run: |
|
||||
set -euo pipefail
|
||||
docker run --rm -e FEX_EXTRA_CXXFLAGS="${{ inputs.cxxflags }}" -e FEX_THUNKS="${{ inputs.thunks == 'true' && '1' || '0' }}" -v "$PWD:/work" -w /work menci/archlinuxarm:base-devel bash tools/fex/build-in-arch.sh
|
||||
sudo chown -R "$(id -u):$(id -g)" .
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: fex
|
||||
path: |
|
||||
fex.tzst
|
||||
fex.tzst.sha256
|
||||
fex-needed.txt
|
||||
fex-files.txt
|
||||
- name: Publish
|
||||
if: github.event_name == 'workflow_dispatch' && inputs.tag != '' && inputs.cxxflags == ''
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
gh release create "${{ inputs.tag }}" --latest=false --prerelease=false --title "${{ inputs.tag }}" --notes "FEX for the runtime (tools/fex/build-in-arch.sh); fetched by bannerlator-steam-x64. sha256 $(cut -d' ' -f1 fex.tzst.sha256)" fex.tzst fex.tzst.sha256 || gh release upload "${{ inputs.tag }}" fex.tzst fex.tzst.sha256 --clobber
|
||||
# A component the apk fetches by tag, never something users install: it must not
|
||||
# become the repo's Latest release or appear as a pre-release, also when re-uploaded.
|
||||
gh release edit "${{ inputs.tag }}" --latest=false --prerelease=false
|
||||
@@ -28,7 +28,7 @@ concurrency:
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
env:
|
||||
PRELOAD_CACHE_VERSION: v2
|
||||
PRELOAD_CACHE_VERSION: v5
|
||||
|
||||
jobs:
|
||||
build:
|
||||
@@ -157,7 +157,7 @@ jobs:
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: app/src/main/assets/linuxfs
|
||||
key: preloads-${{ env.PRELOAD_CACHE_VERSION }}-${{ hashFiles('app/src/main/cpp/fakeinput_steam.cpp', 'tools/linuxfs/preload/*.c', 'tools/linuxfs/clipboard/*.c', 'tools/proot/fastpath/*.c', 'tools/linuxfs/overlay/usr/local/bin/*', 'tools/linuxfs/overlay/usr/bin/**', 'tools/linuxfs/desktop/*', 'tools/gamescope/release.env', 'tools/wlroots/release.env', 'tools/mangoapp/*') }}
|
||||
key: preloads-${{ env.PRELOAD_CACHE_VERSION }}-${{ hashFiles('app/src/main/cpp/fakeinput_steam.cpp', 'tools/linuxfs/preload/*.c', 'tools/proot/fastpath/*.c', 'tools/linuxfs/overlay/usr/local/bin/*', 'tools/linuxfs/overlay/usr/bin/**', 'tools/linuxfs/desktop/*', 'tools/gamescope/release.env', 'tools/wlroots/release.env', 'tools/mangoapp/*') }}
|
||||
|
||||
- name: Build libfakeinput.so and libblsession.so (glibc aarch64)
|
||||
if: steps.preloads.outputs.cache-hit != 'true'
|
||||
@@ -176,12 +176,20 @@ jobs:
|
||||
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
|
||||
-o "$D/libblsession.so" tools/linuxfs/preload/*.c -ldl
|
||||
aarch64-linux-gnu-strip --strip-unneeded "$D/libblsession.so"
|
||||
# The same session shim for x86-64 programs under FEX (bannerlator-steam-x64): the x86
|
||||
# Steam client needs its System V semaphores just as the arm64 one does. Native gcc on
|
||||
# this runner; Ubuntu 24.04's glibc is the one in FEX's Ubuntu 24.04 rootfs.
|
||||
gcc -shared -fPIC -O2 -Wall -pthread \
|
||||
-o "$D/libblsession-x86_64.so" tools/linuxfs/preload/*.c -ldl
|
||||
strip --strip-unneeded "$D/libblsession-x86_64.so"
|
||||
# And the controller reader: the session's pads reach x86-64 programs the same way.
|
||||
g++ -shared -fPIC -O2 -Wall -Wno-attributes -Wno-nonnull-compare \
|
||||
-pthread -std=c++17 -static-libstdc++ -static-libgcc -Wl,--exclude-libs,ALL \
|
||||
-o "$D/libfakeinput-x86_64.so" app/src/main/cpp/fakeinput_steam.cpp -ldl
|
||||
strip --strip-unneeded "$D/libfakeinput-x86_64.so"
|
||||
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
|
||||
-o "$D/libblfastpath.so" tools/proot/fastpath/fastpath.c -ldl
|
||||
aarch64-linux-gnu-strip --strip-unneeded "$D/libblfastpath.so"
|
||||
mkdir -p "$D/usr/local/bin"
|
||||
aarch64-linux-gnu-gcc -O2 -Wall -Wextra -o "$D/usr/local/bin/droiddeck-clipboard" tools/linuxfs/clipboard/clipboard.c -ldl
|
||||
aarch64-linux-gnu-strip --strip-unneeded "$D/usr/local/bin/droiddeck-clipboard"
|
||||
for script in tools/linuxfs/overlay/usr/local/bin/bannerlator-*; do
|
||||
install -Dm644 "$script" "$D/usr/local/bin/$(basename "$script")"
|
||||
done
|
||||
@@ -232,7 +240,15 @@ jobs:
|
||||
install -Dm644 tools/linuxfs/desktop/panel.conf "$D/etc/xdg/lxqt/panel.conf"
|
||||
install -Dm644 tools/linuxfs/desktop/firefox-droiddeck.js "$D/usr/lib/firefox/defaults/pref/droiddeck.js"
|
||||
ls -lR "$D"
|
||||
|
||||
# And for 32-bit x86 programs (Left 4 Dead 2 and the other Source games are i386). Last:
|
||||
# gcc-multilib conflicts with the aarch64 cross compiler and removes it.
|
||||
sudo apt-get install -y -qq gcc-multilib g++-multilib >/dev/null
|
||||
gcc -m32 -shared -fPIC -O2 -Wall -pthread \
|
||||
-o "$D/libblsession-i386.so" tools/linuxfs/preload/*.c -ldl
|
||||
g++ -m32 -shared -fPIC -O2 -Wall -Wno-attributes -Wno-nonnull-compare \
|
||||
-pthread -std=c++17 -static-libstdc++ -static-libgcc -Wl,--exclude-libs,ALL \
|
||||
-o "$D/libfakeinput-i386.so" app/src/main/cpp/fakeinput_steam.cpp -ldl
|
||||
strip --strip-unneeded "$D/libblsession-i386.so" "$D/libfakeinput-i386.so"
|
||||
- name: Cache PulseAudio 13.0 source
|
||||
id: pa-src
|
||||
uses: actions/cache@v4
|
||||
|
||||
@@ -13,10 +13,6 @@
|
||||
download from being throttled to nothing by the radio's power-save. -->
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
|
||||
<!-- Optional Wi-Fi discovery: requested only from Steam settings after an explanation. -->
|
||||
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
|
||||
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
|
||||
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
|
||||
<uses-permission android:name="android.permission.VIBRATE" />
|
||||
<!-- Ends background processes of another app that holds the Steam login. GameHub starts
|
||||
itself with the phone via boot receivers and signs this client out seconds after every
|
||||
|
||||
@@ -47,7 +47,6 @@ import com.droiddeck.launcher.core.CpuCores
|
||||
import com.droiddeck.launcher.core.PhantomProcessLimit
|
||||
import com.droiddeck.launcher.core.PhantomProcessStatus
|
||||
import com.droiddeck.launcher.core.WirelessAdbFix
|
||||
import com.droiddeck.launcher.core.WifiDiscovery
|
||||
import com.droiddeck.launcher.core.WirelessAdbPairingService
|
||||
import com.droiddeck.launcher.ui.CoreRow
|
||||
import com.droiddeck.launcher.ui.PerformancePage
|
||||
@@ -150,24 +149,6 @@ class MainActivity : ComponentActivity() {
|
||||
private var launcherFullscreen by mutableStateOf(true)
|
||||
private var storeEnabled by mutableStateOf(false)
|
||||
private var mic by mutableStateOf(false)
|
||||
private var wifiDiscovery by mutableStateOf(false)
|
||||
private var wifiDiscoveryPermission by mutableStateOf(false)
|
||||
private var wifiDiscoveryLocation by mutableStateOf(false)
|
||||
private var wifiDiscoveryAsked by mutableStateOf(false)
|
||||
private var wifiDiscoveryBlocked by mutableStateOf(false)
|
||||
private val wifiLocationReceiver = object : android.content.BroadcastReceiver() {
|
||||
override fun onReceive(context: android.content.Context?, intent: Intent?) {
|
||||
refreshWifiDiscovery()
|
||||
}
|
||||
}
|
||||
private val wifiLocationPermission = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) {
|
||||
SessionPrefs.setWifiDiscoveryEnabled(this, WifiDiscovery.permissionGranted(this))
|
||||
refreshWifiDiscovery()
|
||||
}
|
||||
private val wifiPermissionSettings = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
|
||||
SessionPrefs.setWifiDiscoveryEnabled(this, WifiDiscovery.permissionGranted(this))
|
||||
refreshWifiDiscovery()
|
||||
}
|
||||
|
||||
// The app's own picker (files/), once per kind of pick: the two driver lists validate
|
||||
// differently, and the reason a zip is refused names the list it belongs in.
|
||||
@@ -195,28 +176,6 @@ class MainActivity : ComponentActivity() {
|
||||
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let(then)
|
||||
}
|
||||
|
||||
private fun refreshWifiDiscovery() {
|
||||
wifiDiscoveryPermission = WifiDiscovery.permissionGranted(this)
|
||||
wifiDiscoveryLocation = WifiDiscovery.locationEnabled(this)
|
||||
wifiDiscoveryAsked = SessionPrefs.wifiDiscoveryAsked(this)
|
||||
wifiDiscoveryBlocked = !wifiDiscoveryPermission && wifiDiscoveryAsked &&
|
||||
WifiDiscovery.permissions.none { shouldShowRequestPermissionRationale(it) }
|
||||
// A revoked grant must not leave an enabled switch behind.
|
||||
if (!wifiDiscoveryPermission && SessionPrefs.wifiDiscoveryEnabled(this)) {
|
||||
SessionPrefs.setWifiDiscoveryEnabled(this, false)
|
||||
}
|
||||
wifiDiscovery = SessionPrefs.wifiDiscoveryEnabled(this)
|
||||
}
|
||||
|
||||
private fun openWifiDiscoverySettings() {
|
||||
if (!WifiDiscovery.permissionGranted(this)) {
|
||||
wifiPermissionSettings.launch(Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
|
||||
Uri.parse("package:$packageName")))
|
||||
} else {
|
||||
startActivity(Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS))
|
||||
}
|
||||
}
|
||||
|
||||
/** Takes a new or updated Lossless Scaling from Steam and shows what LSFG can use. */
|
||||
private fun syncLossless() {
|
||||
Thread({
|
||||
@@ -299,6 +258,7 @@ class MainActivity : ComponentActivity() {
|
||||
private var customResolution by mutableStateOf<Pair<Int, Int>?>(null)
|
||||
private var fexPreset by mutableStateOf("")
|
||||
private var steamChannel by mutableStateOf("publicbeta")
|
||||
private var steamClientArch by mutableStateOf("arm64")
|
||||
private var runSteamAtStartup by mutableStateOf(false)
|
||||
private var theme by mutableStateOf("graphite")
|
||||
private var shapeMode by mutableStateOf(SessionPrefs.SHAPE_AUTO)
|
||||
@@ -320,6 +280,7 @@ class MainActivity : ComponentActivity() {
|
||||
private var emulatorList by mutableStateOf<List<Library.Emulator>>(emptyList())
|
||||
private var runningLabel by mutableStateOf<String?>(null)
|
||||
private var logsEnabled by mutableStateOf(true)
|
||||
private var vacDiagnostics by mutableStateOf(false)
|
||||
private var showRoms by mutableStateOf(false)
|
||||
private var homeAppSelected by mutableStateOf(false)
|
||||
private var homeScreenEnabled by mutableStateOf(false)
|
||||
@@ -404,7 +365,7 @@ class MainActivity : ComponentActivity() {
|
||||
busy = busy, stage = stage, percent = percent,
|
||||
desktopInstalled = desktopInstalled,
|
||||
offlineAccount = offlineAccount, offline = offline,
|
||||
frameGenLabel = frameGenLabel, romsDir = romsDir, logsEnabled = logsEnabled,
|
||||
frameGenLabel = frameGenLabel, romsDir = romsDir, logsEnabled = logsEnabled, vacDiagnostics = vacDiagnostics,
|
||||
steamGames = steamGames, emulators = emulatorList, running = runningLabel,
|
||||
frameGen = FrameGen.mode(this),
|
||||
lossless = lossless,
|
||||
@@ -502,6 +463,10 @@ class MainActivity : ComponentActivity() {
|
||||
SessionPrefs.setLogsEnabled(this, !SessionPrefs.logsEnabled(this))
|
||||
logsEnabled = SessionPrefs.logsEnabled(this)
|
||||
},
|
||||
onVacDiagnostics = {
|
||||
SessionPrefs.setVacDiagnostics(this, !SessionPrefs.vacDiagnostics(this))
|
||||
vacDiagnostics = SessionPrefs.vacDiagnostics(this)
|
||||
},
|
||||
onShareLogs = {
|
||||
Thread({
|
||||
val zip = runCatching { SessionLogShare.zipLatest(this) }.getOrNull()
|
||||
@@ -721,7 +686,6 @@ class MainActivity : ComponentActivity() {
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
refreshWifiDiscovery()
|
||||
com.droiddeck.launcher.ui.Motion.refresh(this)
|
||||
// Back from a session stopped behind a flood: open on its blue, before the first frame.
|
||||
com.droiddeck.launcher.ui.QuitFlood.take()?.let { c ->
|
||||
@@ -759,7 +723,6 @@ class MainActivity : ComponentActivity() {
|
||||
|
||||
override fun onStart() {
|
||||
super.onStart()
|
||||
registerReceiver(wifiLocationReceiver, android.content.IntentFilter(android.location.LocationManager.MODE_CHANGED_ACTION))
|
||||
displayManager.registerDisplayListener(secondScreenDisplayListener, ui)
|
||||
refreshSecondScreenDisplays()
|
||||
}
|
||||
@@ -770,7 +733,6 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
|
||||
override fun onStop() {
|
||||
unregisterReceiver(wifiLocationReceiver)
|
||||
displayManager.unregisterDisplayListener(secondScreenDisplayListener)
|
||||
// The session covers the page by now; coming back finds it as it was.
|
||||
flood = null
|
||||
@@ -1003,15 +965,11 @@ class MainActivity : ComponentActivity() {
|
||||
storageOptions = storageOptions,
|
||||
fexPreset = if (mode == SessionService.MODE_STEAM) fexPreset else null,
|
||||
steamChannel = if (mode == SessionService.MODE_STEAM) steamChannel else null,
|
||||
steamClientArch = if (mode == SessionService.MODE_STEAM) steamClientArch else null,
|
||||
steamDeckMode = mode == SessionService.MODE_STEAM && steamDeckMode,
|
||||
mangoapp = mangoapp,
|
||||
steamController = if (mode == SessionService.MODE_STEAM) steamController else null,
|
||||
runSteamAtStartup = mode == SessionService.MODE_STEAM && runSteamAtStartup,
|
||||
wifiDiscovery = if (mode == SessionService.MODE_STEAM) wifiDiscovery else null,
|
||||
wifiDiscoveryPermission = wifiDiscoveryPermission,
|
||||
wifiDiscoveryLocation = wifiDiscoveryLocation,
|
||||
wifiDiscoveryAsked = wifiDiscoveryAsked,
|
||||
wifiDiscoveryBlocked = wifiDiscoveryBlocked,
|
||||
addedGamesDirs = if (mode == SessionService.MODE_STEAM) addedGamesDirs else null,
|
||||
addedGames = if (mode == SessionService.MODE_STEAM) addedGames else emptyList(),
|
||||
addedGamesArt = addedGamesArt,
|
||||
@@ -1021,21 +979,6 @@ class MainActivity : ComponentActivity() {
|
||||
deckyEnabled = decky.deckySupervisor, deckySessionRunning = SessionState.running,
|
||||
),
|
||||
ModeSettingsActions(
|
||||
onWifiDiscovery = { on ->
|
||||
if (!on) {
|
||||
SessionPrefs.setWifiDiscoveryEnabled(this, false)
|
||||
refreshWifiDiscovery()
|
||||
} else if (WifiDiscovery.permissionGranted(this)) {
|
||||
SessionPrefs.setWifiDiscoveryEnabled(this, true)
|
||||
refreshWifiDiscovery()
|
||||
} else if (wifiDiscoveryBlocked) {
|
||||
openWifiDiscoverySettings()
|
||||
} else {
|
||||
SessionPrefs.setWifiDiscoveryAsked(this)
|
||||
wifiLocationPermission.launch(WifiDiscovery.permissions)
|
||||
}
|
||||
},
|
||||
onWifiDiscoverySettings = { openWifiDiscoverySettings() },
|
||||
onResolution = { cap -> SessionPrefs.setResolutionCap(this, mode, cap); resolutionCap = cap },
|
||||
onCustomResolution = { size -> SessionPrefs.setCustomResolution(this, mode, size); customResolution = size },
|
||||
onShape = { shape -> SessionPrefs.setShapeMode(this, shape); shapeMode = shape },
|
||||
@@ -1069,6 +1012,7 @@ class MainActivity : ComponentActivity() {
|
||||
},
|
||||
onFexPreset = { id -> SessionPrefs.setFexPreset(this, id); fexPreset = id },
|
||||
onSteamChannel = { id -> SessionPrefs.setSteamChannel(this, id); steamChannel = id },
|
||||
onSteamClientArch = { id -> SessionPrefs.setSteamClientArch(this, id); steamClientArch = id },
|
||||
onSteamDeckMode = { on ->
|
||||
SessionPrefs.setSteamDeckMode(this, on)
|
||||
steamDeckMode = on
|
||||
@@ -1172,6 +1116,7 @@ class MainActivity : ComponentActivity() {
|
||||
customResolution = SessionPrefs.customResolution(this, mode)
|
||||
fexPreset = SessionPrefs.fexPreset(this)
|
||||
steamChannel = SessionPrefs.steamChannel(this)
|
||||
steamClientArch = SessionPrefs.steamClientArch(this)
|
||||
steamDeckMode = SessionPrefs.steamDeckMode(this)
|
||||
mangoapp = SessionPrefs.mangoapp(this)
|
||||
steamController = SessionPrefs.steamController(this)
|
||||
@@ -1190,7 +1135,6 @@ class MainActivity : ComponentActivity() {
|
||||
forceFullscreen = SessionPrefs.forceFullscreen(this)
|
||||
stretch16x9 = SessionPrefs.stretch16x9(this)
|
||||
mic = SessionPrefs.micEnabled(this)
|
||||
refreshWifiDiscovery()
|
||||
renderer = SessionPrefs.desktopRenderer(this)
|
||||
gameStorage = SessionPrefs.gameStorage(this)
|
||||
settingsMode = mode
|
||||
@@ -1257,6 +1201,7 @@ class MainActivity : ComponentActivity() {
|
||||
frameGenLabel = FrameGen.label(this)
|
||||
romsDir = SessionPrefs.romsDir(this).takeIf { it.isNotEmpty() }
|
||||
logsEnabled = SessionPrefs.logsEnabled(this)
|
||||
vacDiagnostics = SessionPrefs.vacDiagnostics(this)
|
||||
runningLabel = if (SessionState.running) when (SessionState.mode) {
|
||||
SessionService.MODE_DESKTOP -> "Desktop"
|
||||
SessionService.MODE_RUN -> Library.nameForProgram(SessionState.program)
|
||||
|
||||
@@ -41,7 +41,6 @@ import com.droiddeck.launcher.gpu.Lossless
|
||||
import com.droiddeck.launcher.gpu.TurnipDriver
|
||||
import com.droiddeck.launcher.input.EvdevKeys
|
||||
import com.droiddeck.launcher.input.KeyboardHost
|
||||
import com.droiddeck.launcher.input.SessionClipboard
|
||||
import com.droiddeck.launcher.input.OnScreenControls
|
||||
import com.droiddeck.launcher.input.PadBridge
|
||||
import com.droiddeck.launcher.input.PointerGestures
|
||||
@@ -126,11 +125,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
private var onScreenControls: OnScreenControls? = null
|
||||
private var keyboard: KeyboardHost? = null
|
||||
private val sessionClipboard by lazy {
|
||||
SessionClipboard(this) {
|
||||
window.decorView.hasWindowFocus() || secondScreenPresentation?.window?.decorView?.hasWindowFocus() == true
|
||||
}
|
||||
}
|
||||
private var watching = true
|
||||
private lateinit var touchpad: TouchpadGestures
|
||||
private var touchMode by mutableStateOf(SessionPrefs.TOUCH_AUTO)
|
||||
@@ -1663,14 +1657,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
onScreenControls?.reload()
|
||||
updateOnScreenControls()
|
||||
resumed = true
|
||||
sessionClipboard.start()
|
||||
updatePadMotion()
|
||||
readPrefs()
|
||||
if (CompositorHost.isStarted) applyFrameGen()
|
||||
}
|
||||
|
||||
override fun onPause() {
|
||||
sessionClipboard.stop()
|
||||
// Do not carry transient session UI across an app/display transition. In particular, the
|
||||
// drawer's dim layer can otherwise remain over Steam when this activity returns.
|
||||
drawerOpen = false
|
||||
@@ -1695,15 +1687,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
|
||||
override fun onWindowFocusChanged(hasFocus: Boolean) {
|
||||
super.onWindowFocusChanged(hasFocus)
|
||||
if (hasFocus) {
|
||||
goFullscreen()
|
||||
refreshClipboard()
|
||||
}
|
||||
}
|
||||
|
||||
/** The keyboard/trackpad presentation can own focus instead of the main display. */
|
||||
fun refreshClipboard() {
|
||||
if (resumed) sessionClipboard.refresh()
|
||||
if (hasFocus) goFullscreen()
|
||||
}
|
||||
|
||||
private fun goFullscreen() {
|
||||
|
||||
@@ -14,8 +14,10 @@ import java.net.Inet6Address
|
||||
* `network.txt`: what the session was given to work with, for the reports that say "the client
|
||||
* thinks WiFi is off" or "Firefox cannot resolve anything".
|
||||
*
|
||||
* The runtime's NetworkManager bridge reports Android's active link. Include whether the phone
|
||||
* had a validated link and which DNS servers the app wrote into the runtime's `resolv.conf`.
|
||||
* The runtime has no NetworkManager, so the client's own network panel is blind by design and says
|
||||
* so in ways that read like a fault. What actually matters is further down: whether the phone had
|
||||
* a validated link, which DNS servers the app wrote into the runtime's `resolv.conf`, and whether
|
||||
* the session can reach a name and an address at all.
|
||||
*
|
||||
* **No network names.** The SSID is identifying and is deliberately not collected; the transport
|
||||
* type, the addresses' families and the DNS servers are what a diagnosis needs.
|
||||
@@ -98,7 +100,7 @@ object NetworkReport {
|
||||
}
|
||||
append("\nproot makes no network namespace, so the session uses the phone's connection\n")
|
||||
append("directly: IPv4 and IPv6 both pass through, and there is nothing to forward.\n")
|
||||
append("Steam reads Android's transport, connectivity and metering through the runtime's\n")
|
||||
append("NetworkManager D-Bus bridge. Android settings manage Wi-Fi and cellular connections.\n")
|
||||
append("The Steam client's own network panel drives NetworkManager over D-Bus, which this\n")
|
||||
append("runtime does not have - \"wifi is off\" there is cosmetic and not evidence.\n")
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import android.Manifest
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.location.LocationManager
|
||||
import android.os.Build
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
|
||||
/** Location is used only for Android's Wi-Fi names and scan results, never coordinates. */
|
||||
object WifiDiscovery {
|
||||
val permissions = arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION)
|
||||
|
||||
// targetSdk 28 accepts either grant for Wi-Fi scanning.
|
||||
fun permissionGranted(context: Context): Boolean = permissions.any {
|
||||
context.checkSelfPermission(it) == PackageManager.PERMISSION_GRANTED
|
||||
}
|
||||
|
||||
fun locationEnabled(context: Context): Boolean = Build.VERSION.SDK_INT < Build.VERSION_CODES.P ||
|
||||
(context.getSystemService(Context.LOCATION_SERVICE) as? LocationManager)?.isLocationEnabled == true
|
||||
|
||||
fun available(context: Context): Boolean = SessionPrefs.wifiDiscoveryEnabled(context) &&
|
||||
permissionGranted(context) && locationEnabled(context)
|
||||
}
|
||||
@@ -86,8 +86,6 @@ class OnScreenControls(context: Context, private val pad: PadBridge?, private va
|
||||
private val groups = controls.map { it.group }.distinct()
|
||||
|
||||
private var buttonsOnly = false
|
||||
private var quickHidden = false
|
||||
private var quickPressedBy = -1
|
||||
private var settings = ControllerPrefs.read(context)
|
||||
private var safe = Rect()
|
||||
private var selected: String? = null
|
||||
@@ -161,18 +159,9 @@ class OnScreenControls(context: Context, private val pad: PadBridge?, private va
|
||||
if (buttonsOnly == enabled) return
|
||||
releaseAll()
|
||||
buttonsOnly = enabled
|
||||
quickHidden = false
|
||||
relayout()
|
||||
}
|
||||
|
||||
/** Hide the full touch pad for an unobstructed screen while keeping its quick toggle available. */
|
||||
fun setQuickHidden(hidden: Boolean) {
|
||||
if (buttonsOnly || editing || quickHidden == hidden) return
|
||||
if (hidden) releaseAll()
|
||||
quickHidden = hidden
|
||||
invalidate()
|
||||
}
|
||||
|
||||
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
|
||||
super.onSizeChanged(w, h, oldw, oldh)
|
||||
relayout()
|
||||
@@ -359,7 +348,7 @@ class OnScreenControls(context: Context, private val pad: PadBridge?, private va
|
||||
}
|
||||
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
if (!quickHidden) for (control in controls) {
|
||||
for (control in controls) {
|
||||
if (!isVisible(control)) continue
|
||||
if (control.stick >= 0 && settings.adaptiveSticks && !editing && control.pressedBy == -1) continue
|
||||
val held = control.pressedBy != -1
|
||||
@@ -405,37 +394,15 @@ class OnScreenControls(context: Context, private val pad: PadBridge?, private va
|
||||
canvas.drawText(name, control.cx, control.cy + text.textSize * 0.35f, text)
|
||||
}
|
||||
}
|
||||
if (editing) {
|
||||
val group = selected ?: return
|
||||
val (x, y) = centre(group)
|
||||
stroke.color = heldStroke
|
||||
val single = members(group).singleOrNull()
|
||||
if (single?.wide == true) {
|
||||
val pad = dp(6f)
|
||||
box.set(x - single.halfW - pad, y - single.halfH - pad, x + single.halfW + pad, y + single.halfH + pad)
|
||||
canvas.drawRoundRect(box, single.halfH, single.halfH, stroke)
|
||||
} else canvas.drawCircle(x, y, extent(group) + dp(6f), stroke)
|
||||
} else if (!buttonsOnly) {
|
||||
val (x, y) = quickCenter()
|
||||
val radius = dp(18f)
|
||||
fill.color = Color.argb(190, Color.red(idleFill), Color.green(idleFill), Color.blue(idleFill))
|
||||
canvas.drawCircle(x, y, radius, fill)
|
||||
stroke.color = idleStroke
|
||||
canvas.drawCircle(x, y, radius, stroke)
|
||||
text.color = idleText
|
||||
text.textSize = dp(22f)
|
||||
canvas.drawText(if (quickHidden) "+" else "−", x, y + text.textSize * 0.35f, text)
|
||||
}
|
||||
}
|
||||
|
||||
private fun quickCenter() = (safe.left + dp(34f)) to (height - safe.bottom - dp(34f))
|
||||
|
||||
private fun quickContains(x: Float, y: Float): Boolean {
|
||||
val (cx, cy) = quickCenter()
|
||||
val radius = dp(26f)
|
||||
val dx = x - cx
|
||||
val dy = y - cy
|
||||
return dx * dx + dy * dy <= radius * radius
|
||||
val group = selected ?: return
|
||||
val (x, y) = centre(group)
|
||||
stroke.color = heldStroke
|
||||
val single = members(group).singleOrNull()
|
||||
if (single?.wide == true) {
|
||||
val pad = dp(6f)
|
||||
box.set(x - single.halfW - pad, y - single.halfH - pad, x + single.halfW + pad, y + single.halfH + pad)
|
||||
canvas.drawRoundRect(box, single.halfH, single.halfH, stroke)
|
||||
} else canvas.drawCircle(x, y, extent(group) + dp(6f), stroke)
|
||||
}
|
||||
|
||||
private fun drawArrow(canvas: Canvas, x: Float, y: Float, size: Float, direction: Int) {
|
||||
@@ -462,12 +429,6 @@ class OnScreenControls(context: Context, private val pad: PadBridge?, private va
|
||||
val index = event.actionIndex
|
||||
val x = event.getX(index)
|
||||
val y = event.getY(index)
|
||||
if (!buttonsOnly && event.actionMasked == MotionEvent.ACTION_DOWN && quickContains(x, y)) {
|
||||
quickPressedBy = event.getPointerId(index)
|
||||
return true
|
||||
}
|
||||
if (quickPressedBy != -1) return true
|
||||
if (quickHidden) return false
|
||||
val control = controlAt(x, y) ?: adaptiveStickAt(x, y) ?: return false
|
||||
if (control.pressedBy != -1) return true
|
||||
control.pressedBy = event.getPointerId(index)
|
||||
@@ -483,7 +444,6 @@ class OnScreenControls(context: Context, private val pad: PadBridge?, private va
|
||||
return true
|
||||
}
|
||||
MotionEvent.ACTION_MOVE -> {
|
||||
if (quickPressedBy != -1) return true
|
||||
var changed = false
|
||||
for (index in 0 until event.pointerCount) {
|
||||
val pointer = event.getPointerId(index)
|
||||
@@ -508,18 +468,6 @@ class OnScreenControls(context: Context, private val pad: PadBridge?, private va
|
||||
}
|
||||
MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP, MotionEvent.ACTION_CANCEL -> {
|
||||
val pointer = event.getPointerId(event.actionIndex)
|
||||
if (event.actionMasked == MotionEvent.ACTION_CANCEL) {
|
||||
quickPressedBy = -1
|
||||
releaseAll()
|
||||
return true
|
||||
}
|
||||
if (quickPressedBy == pointer) {
|
||||
val toggled = event.actionMasked == MotionEvent.ACTION_UP && quickContains(event.x, event.y)
|
||||
quickPressedBy = -1
|
||||
if (toggled) setQuickHidden(!quickHidden)
|
||||
return true
|
||||
}
|
||||
if (quickHidden) return false
|
||||
var changed = false
|
||||
for (control in controls) {
|
||||
if (control.pressedBy == pointer || event.actionMasked == MotionEvent.ACTION_CANCEL) {
|
||||
@@ -562,11 +510,11 @@ class OnScreenControls(context: Context, private val pad: PadBridge?, private va
|
||||
|
||||
private fun controlAt(x: Float, y: Float): Control? =
|
||||
controls.firstOrNull {
|
||||
!quickHidden && isVisible(it) && (editing || !settings.adaptiveSticks || it.stick < 0) && it.contains(x, y, it.radius)
|
||||
isVisible(it) && (editing || !settings.adaptiveSticks || it.stick < 0) && it.contains(x, y, it.radius)
|
||||
}
|
||||
|
||||
private fun adaptiveStickAt(x: Float, y: Float): Control? {
|
||||
if (!settings.adaptiveSticks || editing || buttonsOnly || quickHidden) return null
|
||||
if (!settings.adaptiveSticks || editing || buttonsOnly) return null
|
||||
if (x < safe.left || x >= width - safe.right || y < safe.top || y >= height - safe.bottom) return null
|
||||
if (controls.any { it.stick < 0 && isVisible(it) && it.contains(x, y, it.radius, 5f) }) return null
|
||||
return controls.filter {
|
||||
|
||||
@@ -1,81 +0,0 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.content.ClipData
|
||||
import android.content.ClipboardManager
|
||||
import android.content.Context
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.system.Os
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.wayland.WaylandCompositor
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
|
||||
/** Text selections shared by Android and the guest while the session is visible. */
|
||||
class SessionClipboard(context: Context, private val hasFocus: () -> Boolean) {
|
||||
private val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private val hostFile = File(context.filesDir, "session/android-clipboard")
|
||||
private var active = false
|
||||
private val androidListener = ClipboardManager.OnPrimaryClipChangedListener { refresh() }
|
||||
private val guestListener = object : WaylandCompositor.ClipboardListener {
|
||||
override fun onGuestClipboardText(text: String) {
|
||||
// Native callbacks arrive on the compositor thread. Do not publish a delayed callback
|
||||
// after this activity has paused or been replaced.
|
||||
handler.post {
|
||||
if (active && hasFocus() && WaylandCompositor.isClipboardListener(this)) {
|
||||
val current = clipboard.primaryClip?.takeIf { it.itemCount > 0 }?.getItemAt(0)?.text
|
||||
if (current?.toString() != text) {
|
||||
clipboard.setPrimaryClip(ClipData.newPlainText("DroidDeck", text))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun start() {
|
||||
if (active) return
|
||||
active = true
|
||||
clipboard.addPrimaryClipChangedListener(androidListener)
|
||||
WaylandCompositor.setClipboardListener(guestListener)
|
||||
refresh()
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
if (!active) return
|
||||
active = false
|
||||
clipboard.removePrimaryClipChangedListener(androidListener)
|
||||
WaylandCompositor.clearClipboardListener(guestListener)
|
||||
handler.removeCallbacksAndMessages(null)
|
||||
}
|
||||
|
||||
/** Android 10+ permits clipboard reads only with window focus. Resume can precede focus. */
|
||||
fun refresh() {
|
||||
if (!active || !hasFocus()) return
|
||||
val clip = clipboard.primaryClip
|
||||
// Only share literal text, never resolve content URIs or load copied files.
|
||||
if (clip == null) {
|
||||
publish(null)
|
||||
} else if (clip.itemCount > 0) {
|
||||
publish(clip.getItemAt(0).text?.toString())
|
||||
}
|
||||
}
|
||||
|
||||
private fun publish(text: String?) {
|
||||
WaylandCompositor.setClipboardText(text)
|
||||
// Gamescope needs the same selection in its own Xwayland. Rename complete UTF-8 text
|
||||
// into place so its helper never sees half a launch command. Kept in private app data.
|
||||
val pending = File(hostFile.parentFile, "android-clipboard.pending")
|
||||
try {
|
||||
hostFile.parentFile?.mkdirs()
|
||||
pending.writeText(text.orEmpty(), Charsets.UTF_8)
|
||||
Os.rename(pending.path, hostFile.path)
|
||||
} catch (e: IOException) {
|
||||
Log.w("SessionClipboard", "Could not share text with Xwayland", e)
|
||||
} catch (e: android.system.ErrnoException) {
|
||||
Log.w("SessionClipboard", "Could not publish text for Xwayland", e)
|
||||
} finally {
|
||||
pending.delete()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,30 +1,17 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.location.LocationManager
|
||||
import android.net.ConnectivityManager
|
||||
import android.net.LinkProperties
|
||||
import android.net.Network
|
||||
import android.net.NetworkCapabilities
|
||||
import android.net.wifi.WifiInfo
|
||||
import android.net.wifi.WifiManager
|
||||
import android.os.Build
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.SystemClock
|
||||
import android.provider.Settings
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.SessionPart
|
||||
import com.droiddeck.launcher.core.WifiDiscovery
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.net.Inet4Address
|
||||
import java.net.Inet6Address
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
|
||||
/**
|
||||
* The device's network link, published for the Linux runtime's processes.
|
||||
@@ -47,94 +34,20 @@ class LinuxNetworkLinkComponent(
|
||||
appContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
|
||||
private val lock = Any()
|
||||
private var callback: ConnectivityManager.NetworkCallback? = null
|
||||
private var currentNetwork: Network? = null
|
||||
private var currentProperties: LinkProperties? = null
|
||||
private var currentCapabilities: NetworkCapabilities? = null
|
||||
private val wifiManager = appContext.getSystemService(Context.WIFI_SERVICE) as? WifiManager
|
||||
private val scanHandler = Handler(Looper.getMainLooper())
|
||||
private var wifiReceiver: BroadcastReceiver? = null
|
||||
private var scanRequestStamp = 0L
|
||||
private var lastScanRequest = -SCAN_INTERVAL_MS
|
||||
@Volatile private var lastNamesAllowed = false
|
||||
private val scanRequests = object : Runnable {
|
||||
override fun run() {
|
||||
if (canReadWifiNames() != lastNamesAllowed) {
|
||||
synchronized(lock) { writeNetworkState(currentProperties, currentCapabilities) }
|
||||
requestWifiScan()
|
||||
}
|
||||
val stamp = File(rootDir, "etc/bannerlator-wifi-scan-request").lastModified()
|
||||
if (stamp != 0L && stamp != scanRequestStamp) {
|
||||
scanRequestStamp = stamp
|
||||
requestWifiScan()
|
||||
}
|
||||
if (wifiReceiver != null) scanHandler.postDelayed(this, 1000)
|
||||
}
|
||||
}
|
||||
|
||||
/** Called before the session starts, so its first process already sees the link. */
|
||||
fun publish() = synchronized(lock) {
|
||||
currentNetwork = connectivity.activeNetwork
|
||||
currentProperties = currentNetwork?.let(connectivity::getLinkProperties)
|
||||
currentCapabilities = currentNetwork?.let(connectivity::getNetworkCapabilities)
|
||||
write(currentProperties, currentCapabilities)
|
||||
}
|
||||
fun publish() = write(connectivity.activeNetwork?.let(connectivity::getLinkProperties))
|
||||
|
||||
override fun start() {
|
||||
val registered = object : ConnectivityManager.NetworkCallback() {
|
||||
override fun onAvailable(network: Network) = synchronized(lock) {
|
||||
currentNetwork = network
|
||||
currentProperties = null
|
||||
currentCapabilities = null
|
||||
}
|
||||
|
||||
override fun onCapabilitiesChanged(network: Network, capabilities: NetworkCapabilities) = synchronized(lock) {
|
||||
if (network == currentNetwork) {
|
||||
currentCapabilities = capabilities
|
||||
if (currentProperties != null) write(currentProperties, capabilities)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onLinkPropertiesChanged(network: Network, properties: LinkProperties) = synchronized(lock) {
|
||||
if (network == currentNetwork) {
|
||||
currentProperties = properties
|
||||
write(properties, currentCapabilities)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onLost(network: Network) = synchronized(lock) {
|
||||
// A handover can report the old link lost after the new default arrived.
|
||||
if (network == currentNetwork) {
|
||||
currentNetwork = null
|
||||
currentProperties = null
|
||||
currentCapabilities = null
|
||||
write(null, null)
|
||||
}
|
||||
}
|
||||
override fun onLinkPropertiesChanged(network: Network, properties: LinkProperties) = write(properties)
|
||||
override fun onLost(network: Network) = write(null)
|
||||
}
|
||||
synchronized(lock) { callback = registered }
|
||||
connectivity.registerDefaultNetworkCallback(registered)
|
||||
val receiver = object : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context?, intent: Intent?) {
|
||||
synchronized(lock) { writeNetworkState(currentProperties, currentCapabilities) }
|
||||
}
|
||||
}
|
||||
wifiReceiver = receiver
|
||||
appContext.registerReceiver(receiver, IntentFilter().apply {
|
||||
addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)
|
||||
addAction(WifiManager.RSSI_CHANGED_ACTION)
|
||||
addAction(WifiManager.WIFI_STATE_CHANGED_ACTION)
|
||||
addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION)
|
||||
addAction(LocationManager.MODE_CHANGED_ACTION)
|
||||
})
|
||||
scanRequestStamp = File(rootDir, "etc/bannerlator-wifi-scan-request").lastModified()
|
||||
scanHandler.post(scanRequests)
|
||||
requestWifiScan()
|
||||
}
|
||||
|
||||
override fun stop() {
|
||||
scanHandler.removeCallbacks(scanRequests)
|
||||
wifiReceiver?.let { appContext.unregisterReceiver(it) }
|
||||
wifiReceiver = null
|
||||
val registered = synchronized(lock) { callback.also { callback = null } } ?: return
|
||||
try {
|
||||
connectivity.unregisterNetworkCallback(registered)
|
||||
@@ -143,22 +56,7 @@ class LinuxNetworkLinkComponent(
|
||||
}
|
||||
}
|
||||
|
||||
private fun canReadWifiNames(): Boolean = WifiDiscovery.available(appContext)
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
private fun requestWifiScan() {
|
||||
val now = SystemClock.elapsedRealtime()
|
||||
if (!canReadWifiNames() || wifiManager?.isWifiEnabled != true || now - lastScanRequest < SCAN_INTERVAL_MS) return
|
||||
lastScanRequest = now
|
||||
try {
|
||||
Log.i(TAG, "Wi-Fi scan requested: accepted=${wifiManager.startScan()}")
|
||||
} catch (e: SecurityException) {
|
||||
Log.w(TAG, "Wi-Fi scan permission unavailable")
|
||||
}
|
||||
synchronized(lock) { writeNetworkState(currentProperties, currentCapabilities) }
|
||||
}
|
||||
|
||||
private fun write(properties: LinkProperties?, capabilities: NetworkCapabilities?) {
|
||||
private fun write(properties: LinkProperties?) {
|
||||
val file = File(rootDir, LINK_FILE)
|
||||
synchronized(lock) {
|
||||
try {
|
||||
@@ -169,99 +67,10 @@ class LinuxNetworkLinkComponent(
|
||||
} catch (e: IOException) {
|
||||
Log.w(TAG, "Could not publish the network link", e)
|
||||
}
|
||||
writeNetworkState(properties, capabilities)
|
||||
writeResolver(properties)
|
||||
}
|
||||
}
|
||||
|
||||
/** NetworkManager's view of Android. Kept separate from netif.c's legacy adapter format. */
|
||||
@Suppress("DEPRECATION")
|
||||
private fun writeNetworkState(properties: LinkProperties?, capabilities: NetworkCapabilities?) {
|
||||
val namesAllowed = canReadWifiNames()
|
||||
lastNamesAllowed = namesAllowed
|
||||
val scans = if (namesAllowed && wifiManager?.isWifiEnabled == true) {
|
||||
try { wifiManager.scanResults.orEmpty() } catch (e: SecurityException) { emptyList() }
|
||||
} else emptyList()
|
||||
val transport = when {
|
||||
capabilities == null -> "none"
|
||||
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> "wifi"
|
||||
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> "cellular"
|
||||
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> "ethernet"
|
||||
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN) -> "vpn"
|
||||
else -> "other"
|
||||
}
|
||||
val state = JSONObject().apply {
|
||||
put("transport", transport)
|
||||
put("interface", properties?.interfaceName ?: "android")
|
||||
put("mtu", properties?.mtu?.takeIf { it > 0 } ?: DEFAULT_MTU)
|
||||
put("connected", properties != null && capabilities != null)
|
||||
put("validated", capabilities?.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) == true)
|
||||
put("captivePortal", capabilities?.hasCapability(NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL) == true)
|
||||
put("metered", capabilities?.let { !it.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED) })
|
||||
put("wifiEnabled", wifiManager?.isWifiEnabled == true)
|
||||
put("scanAllowed", namesAllowed)
|
||||
put("lastScan", scans.maxOfOrNull { it.timestamp / 1000 } ?: -1L)
|
||||
put("accessPoints", JSONArray().apply {
|
||||
scans.filter { it.SSID.isNotEmpty() }.forEach {
|
||||
put(JSONObject().apply {
|
||||
put("ssid", it.SSID)
|
||||
put("bssid", it.BSSID)
|
||||
put("strength", WifiManager.calculateSignalLevel(it.level, 101))
|
||||
put("frequency", it.frequency)
|
||||
put("capabilities", it.capabilities)
|
||||
put("lastSeen", it.timestamp / 1_000_000)
|
||||
})
|
||||
}
|
||||
})
|
||||
put("addresses", JSONArray().apply {
|
||||
properties?.linkAddresses.orEmpty().forEach {
|
||||
put(JSONObject().put("address", it.address.hostAddress?.substringBefore('%')).put("prefix", it.prefixLength))
|
||||
}
|
||||
})
|
||||
put("gateways", JSONArray().apply {
|
||||
properties?.routes.orEmpty().filter { it.isDefaultRoute }.forEach {
|
||||
it.gateway?.takeUnless { address -> address.isAnyLocalAddress }?.let { address ->
|
||||
put(address.hostAddress?.substringBefore('%'))
|
||||
}
|
||||
}
|
||||
})
|
||||
put("dns", JSONArray().apply {
|
||||
properties?.dnsServers.orEmpty().filter { !it.isLinkLocalAddress }.forEach {
|
||||
put(it.hostAddress?.substringBefore('%'))
|
||||
}
|
||||
})
|
||||
if (transport == "wifi") {
|
||||
val connectionInfo = try { wifiManager?.connectionInfo } catch (e: SecurityException) { null }
|
||||
val info = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
(capabilities?.transportInfo as? WifiInfo) ?: connectionInfo
|
||||
} else {
|
||||
connectionInfo
|
||||
}
|
||||
if (info != null) {
|
||||
// SSIDs can be redacted by Android. No location permission is needed to
|
||||
// report the transport; a hidden name simply displays as Wi-Fi in Steam.
|
||||
if (namesAllowed) {
|
||||
val namedInfo = connectionInfo ?: info
|
||||
namedInfo.ssid?.takeUnless { it == WifiManager.UNKNOWN_SSID || it.isEmpty() }
|
||||
?.removeSurrounding("\"")?.let { put("ssid", it) }
|
||||
namedInfo.bssid?.takeUnless { it == "02:00:00:00:00:00" }?.let { put("bssid", it) }
|
||||
}
|
||||
put("strength", WifiManager.calculateSignalLevel(info.rssi, 101))
|
||||
put("frequency", info.frequency.coerceAtLeast(0))
|
||||
put("bitrate", info.linkSpeed.coerceAtLeast(0) * 1000)
|
||||
}
|
||||
}
|
||||
}
|
||||
try {
|
||||
val file = File(rootDir, "etc/bannerlator-network.json")
|
||||
val staged = File(file.path + ".staged")
|
||||
staged.writeText(state.toString())
|
||||
if (!staged.renameTo(file)) throw IOException("Could not replace network state")
|
||||
} catch (e: IOException) {
|
||||
Log.w(TAG, "Could not publish the network state", e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The guest's resolver, from the network it is actually on. glibc reads /etc/resolv.conf,
|
||||
* and the image ships two public servers there, which is why Steam resolves at all - but a
|
||||
@@ -340,6 +149,5 @@ class LinuxNetworkLinkComponent(
|
||||
private const val DEFAULT_MTU = 1500
|
||||
private const val OFFLINE_NAME = "eth0"
|
||||
private const val OFFLINE_ADDRESS = "10.0.0.2 24"
|
||||
private const val SCAN_INTERVAL_MS = 30_000L
|
||||
}
|
||||
}
|
||||
@@ -45,6 +45,7 @@ object SessionArtifacts {
|
||||
}
|
||||
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
|
||||
copySteamLogs(context, dir)
|
||||
VacDiagnostics.collect(context, dir)
|
||||
// A session the system killed leaves its trace here and nowhere else.
|
||||
SessionLogCapture.dumpCrashBuffer(File(dir, "crash.log"))
|
||||
scrubFolder(dir)
|
||||
@@ -145,6 +146,7 @@ object SessionArtifacts {
|
||||
)
|
||||
if (newest) {
|
||||
copySteamLogs(context, dir)
|
||||
VacDiagnostics.collect(context, dir)
|
||||
}
|
||||
SessionLogCapture.dumpCrashBuffer(File(dir, "crash.log"))
|
||||
SessionEvents.record("session.artifacts_recovered", mapOf("newest" to newest), dir)
|
||||
|
||||
@@ -29,10 +29,13 @@ object SessionFiles {
|
||||
val files = arrayOf(
|
||||
"usr/local/bin/bannerlator-game-env" to "usr/local/bin/bannerlator-game-env",
|
||||
"libblsession.so" to "usr/local/lib/libblsession.so",
|
||||
"libblsession-x86_64.so" to "usr/local/lib/x86_64-linux-gnu/libblsession.so",
|
||||
"libfakeinput-x86_64.so" to "usr/local/lib/x86_64-linux-gnu/libfakeinput.so",
|
||||
"libblsession-i386.so" to "usr/local/lib/i386-linux-gnu/libblsession.so",
|
||||
"libfakeinput-i386.so" to "usr/local/lib/i386-linux-gnu/libfakeinput.so",
|
||||
"libfakeinput.so" to "usr/local/lib/libfakeinput.so",
|
||||
"libblfastpath.so" to "usr/local/lib/libblfastpath.so",
|
||||
"usr/local/bin/bannerlator-session" to "usr/local/bin/bannerlator-session",
|
||||
"usr/local/bin/droiddeck-clipboard" to "usr/local/bin/droiddeck-clipboard",
|
||||
"usr/local/bin/bannerlator-steam-compat" to "usr/local/bin/bannerlator-steam-compat",
|
||||
"usr/local/bin/bannerlator-steam-install" to "usr/local/bin/bannerlator-steam-install",
|
||||
"usr/local/bin/bannerlator-steam-library" to "usr/local/bin/bannerlator-steam-library",
|
||||
@@ -40,6 +43,8 @@ object SessionFiles {
|
||||
"usr/local/bin/bannerlator-proton-extra" to "usr/local/bin/bannerlator-proton-extra",
|
||||
"usr/local/bin/bannerlator-netmanager" to "usr/local/bin/bannerlator-netmanager",
|
||||
"usr/local/bin/bannerlator-steam-launch" to "usr/local/bin/bannerlator-steam-launch",
|
||||
// Experimental: Valve's x86-64 client under FEX (desktop menu entry).
|
||||
"usr/local/bin/bannerlator-steam-x64" to "usr/local/bin/bannerlator-steam-x64",
|
||||
"usr/local/bin/bannerlator-desktop-games" to "usr/local/bin/bannerlator-desktop-games",
|
||||
"usr/local/bin/bannerlator-steam-shim" to "usr/local/bin/bannerlator-steam-shim",
|
||||
"usr/local/bin/bannerlator-steam-shortcuts" to "usr/local/bin/bannerlator-steam-shortcuts",
|
||||
|
||||
@@ -220,19 +220,6 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("mic", on).apply()
|
||||
}
|
||||
|
||||
/** Optional SSID reporting and scans. A Location grant alone never opts the user in. */
|
||||
fun wifiDiscoveryEnabled(context: Context): Boolean = prefs(context).getBoolean("wifiDiscovery", false)
|
||||
|
||||
fun setWifiDiscoveryEnabled(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("wifiDiscovery", on).apply()
|
||||
}
|
||||
|
||||
fun wifiDiscoveryAsked(context: Context): Boolean = prefs(context).getBoolean("wifiDiscoveryAsked", false)
|
||||
|
||||
fun setWifiDiscoveryAsked(context: Context) {
|
||||
prefs(context).edit().putBoolean("wifiDiscoveryAsked", true).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the client's own core pick is overridden. When on, BL_CLIENT_CPUS is sent even when
|
||||
* it names every core - unlike a game mask, the point here is to undo a pin Steam applies to
|
||||
@@ -437,6 +424,18 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("logs", on).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* VAC diagnostics (see [VacDiagnostics]): Source-engine games launched with -condebug and their
|
||||
* console plus the client's VAC lines summarised into vac.txt. Off by default: it changes a
|
||||
* game's command line.
|
||||
*/
|
||||
fun vacDiagnostics(context: Context): Boolean =
|
||||
prefs(context).getBoolean("vac_diagnostics", false)
|
||||
|
||||
fun setVacDiagnostics(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("vac_diagnostics", on).apply()
|
||||
}
|
||||
|
||||
// ── Per-mode display ────────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
@@ -486,6 +485,17 @@ object SessionPrefs {
|
||||
prefs(context).edit().putString("steamChannel", id).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* Which Steam client a Steam session runs: "arm64" (Valve's native ARM64 client, the default) or
|
||||
* "x86_64" (Valve's x86-64 client under FEX, bannerlator-steam-x64 - experimental, for what the
|
||||
* arm64 client cannot do: it never runs VAC). Each has its own sign-in and library.
|
||||
*/
|
||||
fun steamClientArch(context: Context): String = prefs(context).getString("steamClientArch", null) ?: "arm64"
|
||||
|
||||
fun setSteamClientArch(context: Context, id: String) {
|
||||
prefs(context).edit().putString("steamClientArch", id).apply()
|
||||
}
|
||||
|
||||
/** Whether opening DroidDeck starts a Steam session instead of showing the front end. */
|
||||
fun runSteamAtStartup(context: Context): Boolean = prefs(context).getBoolean("runSteamAtStartup", false)
|
||||
|
||||
|
||||
@@ -267,6 +267,7 @@ class SessionService : Service() {
|
||||
val runtimeDir = File(filesDir, ".wayland-rt").apply { mkdirs() }
|
||||
killStragglers()
|
||||
SessionFiles.stage(this, root)
|
||||
VacDiagnostics.arm(this)
|
||||
|
||||
val sessionDir = openSessionFolder()
|
||||
val sessionLog = File(sessionDir, "session.log")
|
||||
@@ -514,7 +515,6 @@ class SessionService : Service() {
|
||||
guest.add("XDG_RUNTIME_DIR=" + LinuxRuntime.GUEST_RUNTIME_DIR)
|
||||
guest.add("XDG_SESSION_TYPE=wayland")
|
||||
guest.add("WAYLAND_DISPLAY=wayland-0")
|
||||
guest.add("BL_ANDROID_CLIPBOARD=" + File(filesDir, "session/android-clipboard").path)
|
||||
guest.add("GAMESCOPE_FORCE_GENERAL_QUEUE=1")
|
||||
// Steam's CEF needs GL and the rootfs ships no native GL driver: route it through Zink.
|
||||
guest.add("MESA_LOADER_DRIVER_OVERRIDE=zink")
|
||||
@@ -560,6 +560,7 @@ class SessionService : Service() {
|
||||
if (SessionState.mode == MODE_STEAM) guest.add("BL_STEAMDECK=" + (if (SessionPrefs.steamDeckMode(this)) "1" else "0"))
|
||||
if (SessionState.mode == MODE_STEAM) guest.add("BL_MANGOAPP=" + (if (SessionPrefs.mangoapp(this)) "1" else "0"))
|
||||
if (steamHere) guest.add("BL_STEAM_CHANNEL=" + SessionPrefs.steamChannel(this))
|
||||
if (steamHere) guest.add("BL_STEAM_CLIENT_ARCH=" + SessionPrefs.steamClientArch(this))
|
||||
if (SessionState.mode == MODE_STEAM) {
|
||||
guest.add("BL_GAMESCOPE_FORCE_FULLSCREEN=" + (if (SessionPrefs.forceFullscreen(this)) "1" else "0"))
|
||||
guest.add("BL_GAMESCOPE_STRETCH_16X9=" + (if (SessionPrefs.stretch16x9(this)) "1" else "0"))
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.LogRedactor
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import java.io.File
|
||||
import java.io.RandomAccessFile
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* VAC diagnostics: what a session can show about whether a game ran VAC-secure, from the files
|
||||
* Valve's own software writes - nothing is inferred from our side of the launch.
|
||||
*
|
||||
* The verdict is the game's to give. A Source-engine game decides secure or insecure once, as it
|
||||
* starts, and says so only in its own console ("You are in insecure mode. You must restart before
|
||||
* you can connect to secure servers."). That console reaches a file only when the game runs with
|
||||
* -condebug, as console.log in the game's mod folder. With this on, the launch wrapper
|
||||
* (bannerlator-proton, bl_vacdiag) adds -condebug to Source titles and notes each launch; at the end
|
||||
* of the session this copies each console.log written during it into vac/, scrubbed, and writes
|
||||
* vac.txt: the game's own secure/insecure lines, any VAC lines in the client's logs, and which
|
||||
* client files are present.
|
||||
*
|
||||
* The SteamLite lesson applies: its "INSECURE - VAC may kick" warning was our own parser reading the
|
||||
* wrong log while the client was secure all along. So vac.txt quotes the lines it found and says
|
||||
* "inconclusive" when the game never reached a server, rather than guessing either way.
|
||||
*/
|
||||
object VacDiagnostics {
|
||||
private const val TAG = "VacDiagnostics"
|
||||
|
||||
/** In the guest's home; the launch wrapper checks for it. Holds the session's start, epoch seconds. */
|
||||
private const val MARKER = "root/.droiddeck-vac-diagnostics"
|
||||
|
||||
/** One line per game launch the wrapper saw: epoch, app id, -condebug added or not, the exe. */
|
||||
private const val LAUNCHES = "root/.droiddeck-vac-launches"
|
||||
|
||||
/** The console log grows across launches; the end of it is the session that just ran. */
|
||||
private const val CONSOLE_TAIL_BYTES = 4L * 1024 * 1024
|
||||
|
||||
private const val MAX_QUOTED = 40
|
||||
|
||||
private val INSECURE = Regex("insecure mode", RegexOption.IGNORE_CASE)
|
||||
// "Connecting to" is only an attempt: L4D2 logs it, retries, and then refuses a VAC server with a
|
||||
// dialog ("Connection Blocked: Please remove plug-ins before attempting to connect to a VAC
|
||||
// secured server") that never reaches the console. Only "Connected to" means the game got in.
|
||||
private val CONNECTED = Regex("^Connected to", RegexOption.IGNORE_CASE)
|
||||
private val ATTEMPTED = Regex("^Connecting to", RegexOption.IGNORE_CASE)
|
||||
private val NOTABLE = Regex("\\bVAC\\b|secure|Connected to|Connecting to|Disconnect|challenge|game coordinator", RegexOption.IGNORE_CASE)
|
||||
private val STEAM_VAC = Regex("\\bVAC\\b|anti-?cheat", RegexOption.IGNORE_CASE)
|
||||
|
||||
fun enabled(context: Context): Boolean = SessionPrefs.vacDiagnostics(context)
|
||||
|
||||
/**
|
||||
* At session start, after the scripts are staged: arms the wrapper for this session (or disarms
|
||||
* it) and starts a fresh launch list, so the summary names only games this session ran.
|
||||
*/
|
||||
fun arm(context: Context) {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
val marker = File(root, MARKER)
|
||||
try {
|
||||
File(root, LAUNCHES).delete()
|
||||
if (enabled(context)) marker.writeText("${System.currentTimeMillis() / 1000}\n")
|
||||
else marker.delete()
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not arm VAC diagnostics", e)
|
||||
}
|
||||
}
|
||||
|
||||
/** At the end of a session, into its folder. Does nothing unless the session was armed. */
|
||||
fun collect(context: Context, dir: File) {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
val marker = File(root, MARKER)
|
||||
if (!marker.isFile) return
|
||||
try {
|
||||
val since = (marker.readText().trim().toLongOrNull() ?: 0L) * 1000 - 5_000
|
||||
val out = File(dir, "vac").apply { mkdirs() }
|
||||
val consoles = consoleLogs(context).filter { it.lastModified() >= since }
|
||||
val report = StringBuilder()
|
||||
report.appendLine("VAC diagnostics - ${now()}")
|
||||
report.appendLine("Read from the game's own console (-condebug) and the Steam client's logs.")
|
||||
report.appendLine()
|
||||
report.appendLine("== Client")
|
||||
clientFiles(root).forEach { report.appendLine(" $it") }
|
||||
report.appendLine()
|
||||
report.appendLine("== Game launches this session (from the launch wrapper)")
|
||||
val launches = File(root, LAUNCHES).takeIf { it.isFile }?.readLines().orEmpty().filter { it.isNotBlank() }
|
||||
if (launches.isEmpty()) report.appendLine(" none - no Windows game was launched through the client")
|
||||
launches.forEach { report.appendLine(" " + LogRedactor.redact(it)) }
|
||||
report.appendLine()
|
||||
report.appendLine("== Game consoles")
|
||||
if (consoles.isEmpty()) {
|
||||
report.appendLine(" No console.log was written this session. Only Source-engine games write one,")
|
||||
report.appendLine(" and only when started with -condebug (this setting adds it).")
|
||||
}
|
||||
consoles.forEach { log ->
|
||||
val name = consoleName(log)
|
||||
val lines = tail(log)
|
||||
File(out, "$name-console.log").bufferedWriter().use { w ->
|
||||
lines.forEach { w.write(LogRedactor.redact(it)); w.newLine() }
|
||||
}
|
||||
report.appendLine("-- $name (vac/$name-console.log)")
|
||||
report.appendLine(" Verdict: " + verdict(lines))
|
||||
lines.filter { NOTABLE.containsMatchIn(it) }.takeLast(MAX_QUOTED)
|
||||
.forEach { report.appendLine(" | " + LogRedactor.redact(it.trim())) }
|
||||
report.appendLine()
|
||||
}
|
||||
report.appendLine("== VAC in the Steam client's logs")
|
||||
val steamHits = File(dir, "steam").listFiles { f -> f.isFile }?.sortedBy { it.name }.orEmpty()
|
||||
.flatMap { f -> runCatching { f.readLines() }.getOrDefault(emptyList()).filter { STEAM_VAC.containsMatchIn(it) }.map { "${f.name}: ${it.trim()}" } }
|
||||
if (steamHits.isEmpty()) report.appendLine(" none - the client logged no VAC activity this session")
|
||||
steamHits.takeLast(MAX_QUOTED).forEach { report.appendLine(" $it") }
|
||||
File(dir, "vac.txt").writeText(report.toString())
|
||||
Log.i(TAG, "VAC diagnostics: ${consoles.size} console log(s), ${steamHits.size} client VAC line(s), into $dir")
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "collecting VAC diagnostics", e)
|
||||
}
|
||||
}
|
||||
|
||||
private fun verdict(lines: List<String>): String = when {
|
||||
lines.any { INSECURE.containsMatchIn(it) } ->
|
||||
"INSECURE - the game started in insecure mode and cannot join VAC-secured servers until it restarts."
|
||||
lines.any { CONNECTED.containsMatchIn(it) } ->
|
||||
"No insecure notice, and the game connected to a server. Confirm with the server's own info that it is VAC-secured."
|
||||
lines.any { ATTEMPTED.containsMatchIn(it) } ->
|
||||
"NOT CONNECTED - the game tried a server and never got in. If the screen said \"Connection Blocked: " +
|
||||
"Please remove plug-ins ... VAC secured server\" (Left 4 Dead 2's wording), the game is insecure; " +
|
||||
"that dialog never reaches the console."
|
||||
else ->
|
||||
"Inconclusive - the game never connected to a server. Join a VAC-secured server, then check again."
|
||||
}
|
||||
|
||||
/** Every console.log in a Steam library: <game>/<mod>/console.log (Source) and <game>/game/<mod>/console.log (Source 2). */
|
||||
private fun consoleLogs(context: Context): List<File> {
|
||||
val found = LinkedHashMap<String, File>()
|
||||
for (library in libraryRoots(context)) {
|
||||
val games = File(library, "steamapps/common").listFiles { f -> f.isDirectory } ?: continue
|
||||
for (game in games) {
|
||||
val mods = (game.listFiles { f -> f.isDirectory }.orEmpty().toList() +
|
||||
File(game, "game").listFiles { f -> f.isDirectory }.orEmpty().toList())
|
||||
for (mod in mods) {
|
||||
val log = File(mod, "console.log")
|
||||
if (log.isFile) found[runCatching { log.canonicalPath }.getOrDefault(log.path)] = log
|
||||
}
|
||||
}
|
||||
}
|
||||
return found.values.toList()
|
||||
}
|
||||
|
||||
private fun libraryRoots(context: Context): List<File> {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
val steam = File(root, "root/.local/share/Steam")
|
||||
val roots = mutableListOf(steam)
|
||||
GameStorage.effective(context)?.let { roots.add(File(it.path)) }
|
||||
runCatching {
|
||||
Regex("\"path\"\\s+\"([^\"]+)\"").findAll(File(steam, "steamapps/libraryfolders.vdf").readText()).forEach {
|
||||
roots.add(File(root, it.groupValues[1].removePrefix("/")))
|
||||
}
|
||||
}
|
||||
return roots.filter { it.isDirectory }.distinctBy { runCatching { it.canonicalPath }.getOrDefault(it.path) }
|
||||
}
|
||||
|
||||
/** "Team Fortress 2-tf": the game folder and the mod, safe as a file name. */
|
||||
private fun consoleName(log: File): String {
|
||||
val mod = log.parentFile
|
||||
val game = mod?.parentFile?.let { if (it.name == "game") it.parentFile else it }
|
||||
return "${game?.name ?: "game"}-${mod?.name ?: "mod"}".replace(Regex("[^A-Za-z0-9._ +-]+"), "_")
|
||||
}
|
||||
|
||||
private fun tail(file: File): List<String> = try {
|
||||
RandomAccessFile(file, "r").use { raf ->
|
||||
val start = (raf.length() - CONSOLE_TAIL_BYTES).coerceAtLeast(0)
|
||||
raf.seek(start)
|
||||
val bytes = ByteArray((raf.length() - start).toInt())
|
||||
raf.readFully(bytes)
|
||||
String(bytes, Charsets.UTF_8).lines().let { if (start > 0) it.drop(1) else it }
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
emptyList()
|
||||
}
|
||||
|
||||
/** Which Steam client builds are on disk - the arm64 one has no VAC module of its own to run. */
|
||||
private fun clientFiles(root: File): List<String> {
|
||||
val steam = File(root, "root/.local/share/Steam")
|
||||
return listOf(
|
||||
"linuxarm64/steamclient.so" to "arm64 Linux client",
|
||||
"linux64/steamclient.so" to "x86-64 Linux client",
|
||||
"ubuntu12_64/steamclient.so" to "x86-64 Linux client (ubuntu12_64)",
|
||||
).map { (path, label) -> "$label: ${if (File(steam, path).isFile) "present" else "absent"} ($path)" }
|
||||
}
|
||||
|
||||
private fun now(): String = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).format(Date())
|
||||
}
|
||||
@@ -91,6 +91,7 @@ class FrontEndState(
|
||||
val frameGenLabel: String,
|
||||
val romsDir: String?,
|
||||
val logsEnabled: Boolean,
|
||||
val vacDiagnostics: Boolean = false,
|
||||
val steamGames: List<Library.SteamGame>,
|
||||
val emulators: List<Library.Emulator>,
|
||||
val running: String?,
|
||||
@@ -152,6 +153,7 @@ class FrontEndActions(
|
||||
val onFiles: () -> Unit,
|
||||
val onBrowseFiles: (File) -> Unit = {},
|
||||
val onLogs: () -> Unit,
|
||||
val onVacDiagnostics: () -> Unit = {},
|
||||
val onShareLogs: () -> Unit = {},
|
||||
val onClearLogs: () -> Unit = {},
|
||||
val onOffline: () -> Unit,
|
||||
|
||||
@@ -289,6 +289,7 @@ internal fun SetupPanel(
|
||||
}
|
||||
}
|
||||
ToggleRow(host, "logs", stringResource(R.string.setup_logs), stringResource(R.string.setup_logs_hint), s.logsEnabled) { a.onLogs() }
|
||||
ToggleRow(host, "vacdiag", stringResource(R.string.setup_vac_diag), stringResource(R.string.setup_vac_diag_hint), s.vacDiagnostics) { a.onVacDiagnostics() }
|
||||
ActionRow(stringResource(R.string.setup_latest_logs), stringResource(R.string.drawer_logs_hint), stringResource(R.string.drawer_share_logs), a.onShareLogs)
|
||||
ActionRow(stringResource(R.string.setup_saved_logs), stringResource(R.string.setup_saved_logs_hint, com.droiddeck.launcher.session.SessionPaths.KEEP_SESSIONS), stringResource(R.string.setup_clear_logs), a.onClearLogs)
|
||||
ToggleRow(
|
||||
|
||||
@@ -72,6 +72,7 @@ class ModeSettings(
|
||||
val stretch16x9: Boolean? = null,
|
||||
/** Steam only: the client branch forced on the command line. */
|
||||
val steamChannel: String? = null,
|
||||
val steamClientArch: String? = null,
|
||||
/** Steam only: enable the SteamOS client interface and its performance controls. */
|
||||
val steamDeckMode: Boolean = false,
|
||||
/** Steam, Deck mode: the QAM's performance overlay (mangoapp) is started. */
|
||||
@@ -80,12 +81,6 @@ class ModeSettings(
|
||||
val steamController: String? = null,
|
||||
/** Steam only: start a Steam session when DroidDeck opens. */
|
||||
val runSteamAtStartup: Boolean = false,
|
||||
/** Null outside Steam; the saved choice is separate from Android's access and device switch. */
|
||||
val wifiDiscovery: Boolean? = null,
|
||||
val wifiDiscoveryPermission: Boolean = false,
|
||||
val wifiDiscoveryLocation: Boolean = false,
|
||||
val wifiDiscoveryAsked: Boolean = false,
|
||||
val wifiDiscoveryBlocked: Boolean = false,
|
||||
/** Steam only: the user's chosen Games folders; null outside Steam. */
|
||||
val addedGamesDirs: List<String>? = null,
|
||||
val addedGames: List<AddedGameRow> = emptyList(),
|
||||
@@ -127,12 +122,11 @@ class ModeSettingsActions(
|
||||
val onForceFullscreen: (Boolean) -> Unit = {},
|
||||
val onStretch16x9: (Boolean) -> Unit = {},
|
||||
val onSteamChannel: (String) -> Unit = {},
|
||||
val onSteamClientArch: (String) -> Unit = {},
|
||||
val onSteamDeckMode: (Boolean) -> Unit = {},
|
||||
val onMangoapp: (Boolean) -> Unit = {},
|
||||
val onSteamController: (String) -> Unit = {},
|
||||
val onRunSteamAtStartup: (Boolean) -> Unit = {},
|
||||
val onWifiDiscovery: (Boolean) -> Unit = {},
|
||||
val onWifiDiscoverySettings: () -> Unit = {},
|
||||
val onPickAddedGamesDir: () -> Unit = {},
|
||||
val onForgetAddedGamesDir: (path: String) -> Unit = {},
|
||||
val onAddedGamesArt: (Boolean) -> Unit = {},
|
||||
@@ -150,7 +144,6 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
|
||||
val steam = s.mode == SessionService.MODE_STEAM
|
||||
val host = rememberMenuHost()
|
||||
var confirmDeckyRemoval by remember { mutableStateOf(false) }
|
||||
var explainWifiDiscovery by remember { mutableStateOf(false) }
|
||||
val pageScroll = androidx.compose.foundation.rememberScrollState()
|
||||
val firstChip = remember { androidx.compose.ui.focus.FocusRequester() }
|
||||
androidx.compose.runtime.LaunchedEffect(Unit) {
|
||||
@@ -334,25 +327,11 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
|
||||
note = stringResource(R.string.mode_branch_note),
|
||||
onPick = a.onSteamChannel,
|
||||
)
|
||||
}
|
||||
if (steam && s.wifiDiscovery != null) SettingsGroup(stringResource(R.string.mode_network)) {
|
||||
val hint = when {
|
||||
s.wifiDiscovery && !s.wifiDiscoveryLocation -> stringResource(R.string.mode_wifi_location_off)
|
||||
!s.wifiDiscoveryPermission && s.wifiDiscoveryAsked -> stringResource(R.string.mode_wifi_permission_denied)
|
||||
else -> stringResource(R.string.mode_wifi_discovery_hint)
|
||||
}
|
||||
SettingsRow(stringResource(R.string.mode_wifi_discovery), hint) {
|
||||
Row(verticalAlignment = androidx.compose.ui.Alignment.CenterVertically,
|
||||
horizontalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(8.dp)) {
|
||||
if (s.wifiDiscoveryBlocked || (s.wifiDiscovery && !s.wifiDiscoveryLocation)) {
|
||||
SecondaryButton(stringResource(R.string.mode_wifi_open_settings), onClick = a.onWifiDiscoverySettings)
|
||||
}
|
||||
ToggleSwitch(s.wifiDiscovery, label = stringResource(R.string.mode_wifi_discovery)) { on ->
|
||||
host.open = null
|
||||
if (on) explainWifiDiscovery = true else a.onWifiDiscovery(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (s.steamClientArch != null) ChoiceRow(
|
||||
host, "clientArch", stringResource(R.string.mode_client_arch), stringResource(R.string.mode_client_arch_hint),
|
||||
listOf("arm64" to stringResource(R.string.mode_client_arch_arm64), "x86_64" to stringResource(R.string.mode_client_arch_x64)), s.steamClientArch,
|
||||
onPick = a.onSteamClientArch,
|
||||
)
|
||||
}
|
||||
if (steam && s.addedGamesDirs != null) SettingsGroup(stringResource(R.string.mode_added_games)) {
|
||||
for (dir in s.addedGamesDirs) {
|
||||
@@ -446,19 +425,6 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
|
||||
)
|
||||
}
|
||||
}
|
||||
if (explainWifiDiscovery) AlertDialog(
|
||||
onDismissRequest = { explainWifiDiscovery = false },
|
||||
title = { Text(stringResource(R.string.mode_wifi_explain_title)) },
|
||||
text = { Text(stringResource(R.string.mode_wifi_explain_text)) },
|
||||
confirmButton = {
|
||||
TextButton(onClick = { explainWifiDiscovery = false; a.onWifiDiscovery(true) }) {
|
||||
Text(stringResource(if (s.wifiDiscoveryBlocked) R.string.mode_wifi_open_settings else R.string.mode_wifi_continue))
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { explainWifiDiscovery = false }) { Text(stringResource(R.string.common_cancel)) }
|
||||
},
|
||||
)
|
||||
if (confirmDeckyRemoval) AlertDialog(
|
||||
onDismissRequest = { confirmDeckyRemoval = false },
|
||||
title = { Text(stringResource(R.string.mode_decky_remove_title)) },
|
||||
|
||||
@@ -100,10 +100,7 @@ class SecondScreenPresentation(
|
||||
|
||||
override fun onWindowFocusChanged(hasFocus: Boolean) {
|
||||
super.onWindowFocusChanged(hasFocus)
|
||||
if (hasFocus) {
|
||||
applyImmersiveMode()
|
||||
sessionActivity.refreshClipboard()
|
||||
}
|
||||
if (hasFocus) applyImmersiveMode()
|
||||
}
|
||||
|
||||
private fun renderMode() {
|
||||
|
||||
@@ -132,13 +132,6 @@ public final class WaylandCompositor {
|
||||
|
||||
public static void setClipboardListener(ClipboardListener l) { clipboardListener = l; }
|
||||
|
||||
public static boolean isClipboardListener(ClipboardListener l) { return clipboardListener == l; }
|
||||
|
||||
/** A replaced activity must not unhook the clipboard listener of its successor. */
|
||||
public static void clearClipboardListener(ClipboardListener l) {
|
||||
if (clipboardListener == l) clipboardListener = null;
|
||||
}
|
||||
|
||||
/** Invoked from native (banner_on_clipboard_text) with UTF-8 bytes. */
|
||||
@SuppressWarnings("unused")
|
||||
static void onClipboardText(byte[] utf8) {
|
||||
|
||||
@@ -256,6 +256,10 @@
|
||||
<string name="mode_branch_public">Beta pública</string>
|
||||
<string name="mode_branch_deck_beta">Beta pública de Steam Deck</string>
|
||||
<string name="mode_branch_note">El modo Deck siempre usa la beta pública de Steam Deck.</string>
|
||||
<string name="mode_client_arch">Cliente de Steam</string>
|
||||
<string name="mode_client_arch_hint">Se aplica en la próxima sesión. El cliente x86-64 se ejecuta con FEX, con su propio inicio de sesión y biblioteca, y dibuja su interfaz sin la GPU.</string>
|
||||
<string name="mode_client_arch_arm64">ARM64 (recomendado)</string>
|
||||
<string name="mode_client_arch_x64">x86-64 (FEX, experimental)</string>
|
||||
<string name="mode_added_games">Juegos añadidos</string>
|
||||
<string name="mode_added_none">no hay carpetas de juegos con un .exe</string>
|
||||
<string name="mode_games_folder">Carpeta de juegos</string>
|
||||
@@ -483,6 +487,8 @@
|
||||
<string name="setup_session">Sesión</string>
|
||||
<string name="setup_logs">Registros de sesión</string>
|
||||
<string name="setup_logs_hint">Se guardan tras cada sesión</string>
|
||||
<string name="setup_vac_diag">Diagnóstico de VAC</string>
|
||||
<string name="setup_vac_diag_hint">Los juegos Source registran su consola (-condebug); vac.txt en los registros dice si es seguro o no</string>
|
||||
<string name="setup_latest_logs">Últimos registros de sesión</string>
|
||||
<string name="setup_saved_logs">Registros de sesión guardados</string>
|
||||
<string name="setup_saved_logs_hint">Conserva los %1$d más recientes</string>
|
||||
|
||||
@@ -269,6 +269,10 @@
|
||||
<string name="mode_branch_public">Public beta</string>
|
||||
<string name="mode_branch_deck_beta">Steam Deck public beta</string>
|
||||
<string name="mode_branch_note">Deck mode always uses Steam Deck public beta.</string>
|
||||
<string name="mode_client_arch">Steam client</string>
|
||||
<string name="mode_client_arch_hint">Applies next session. The x86-64 client runs under FEX with its own sign-in and library, and draws its interface without the GPU.</string>
|
||||
<string name="mode_client_arch_arm64">ARM64 (recommended)</string>
|
||||
<string name="mode_client_arch_x64">x86-64 (FEX, experimental)</string>
|
||||
<string name="mode_added_games">Added games</string>
|
||||
<string name="mode_added_none">no game folders with a .exe found</string>
|
||||
<string name="mode_games_folder">Games folder</string>
|
||||
@@ -292,15 +296,6 @@
|
||||
<string name="mode_client_audio_direct">DirectAudio</string>
|
||||
<string name="mode_mic">Microphone</string>
|
||||
<string name="mode_mic_hint">For voice chat.</string>
|
||||
<string name="mode_network">Network</string>
|
||||
<string name="mode_wifi_discovery">Wi-Fi discovery</string>
|
||||
<string name="mode_wifi_discovery_hint">Show Wi-Fi names and nearby networks in Steam.</string>
|
||||
<string name="mode_wifi_location_off">Location services are off.</string>
|
||||
<string name="mode_wifi_permission_denied">Location permission not granted.</string>
|
||||
<string name="mode_wifi_open_settings">Open settings</string>
|
||||
<string name="mode_wifi_continue">Continue</string>
|
||||
<string name="mode_wifi_explain_title">Enable Wi-Fi discovery?</string>
|
||||
<string name="mode_wifi_explain_text">Android requires Location permission to read Wi-Fi names and discover nearby networks. DroidDeck uses this access to show those networks in Steam. We don\'t track your location. Internet access works without this permission.</string>
|
||||
<string name="mode_storage">Game storage</string>
|
||||
<string name="mode_storage_auto">Automatic - the SD card when present</string>
|
||||
<string name="mode_storage_auto_none">Automatic - the SD card when present (none now)</string>
|
||||
@@ -517,6 +512,8 @@
|
||||
<string name="setup_session">Session</string>
|
||||
<string name="setup_logs">Session logs</string>
|
||||
<string name="setup_logs_hint">Saved after each session</string>
|
||||
<string name="setup_vac_diag">VAC diagnostics</string>
|
||||
<string name="setup_vac_diag_hint">Source games log their console (-condebug); vac.txt in the session logs says secure or insecure</string>
|
||||
<string name="setup_latest_logs">Latest session logs</string>
|
||||
<string name="setup_saved_logs">Saved session logs</string>
|
||||
<string name="setup_saved_logs_hint">Keeps the newest %1$d</string>
|
||||
|
||||
@@ -7,6 +7,75 @@ the timeline, then lessons and backlog. Companion to the README (what the app *d
|
||||
|
||||
---
|
||||
|
||||
## 2026-10-02 - `feat/x86-64-steam-client`: Valve's x86-64 Linux client under FEX (experiment)
|
||||
|
||||
Why: the arm64 Linux client never runs VAC. L4D2 (and TF2 in Bannerlator) are refused by VAC
|
||||
servers ("Connection Blocked ... VAC secured server") and no client log mentions VAC; VAC modules
|
||||
are x86 code. The question is whether Valve's x86-64 client under FEX gets a VAC module it can run.
|
||||
Branched from `feat/vac-diagnostics`. Opt-in: `bannerlator-steam-x64` (desktop menu "Steam x86-64
|
||||
(FEX, experimental)") runs the client in its own home (`~/.droiddeck-x64`) with its own rootfs,
|
||||
login and library. The arm64 client stays the default and is not touched.
|
||||
|
||||
Device-proven on the FIT (Genshin repack): **the x86-64 client runs, self-updates, renders its full
|
||||
UI (software GL), logs in, shows friends, and downloads games.** VAC itself is not tested yet.
|
||||
|
||||
What it took, in order (each step was the next failure on device):
|
||||
- **FEX for the guest** - `tools/fex/build-in-arch.sh` + `build-fex.yml` (FEX-2609, Arch Linux ARM
|
||||
container, no thunks), released as `fex-2609-r2` (not Latest). Rootfs: FEX's Ubuntu 24.04 image.
|
||||
- **openat2** - our proot answers it with ENOSYS; FEX opened every rootfs path with
|
||||
`openat2(RESOLVE_IN_ROOT)`, fell through to the arm64 guest on anything but EXDEV, and x86 bash
|
||||
could not find libtinfo. `tools/fex/patches/0001-openat2-enosys-fallback.patch`.
|
||||
- **FEXServer owns the rootfs** - a server started before `FEX_ROOTFS` (any earlier FEX run) answers
|
||||
every client with no rootfs. The launcher stops it first.
|
||||
- **32-bit x86 died with SIGILL** - libblfastpath (the proot fast path, preloaded into every guest
|
||||
process, FEX itself included) breaks FEX's 32-bit mode. `PROOT_FP_OFF=1` for FEX.
|
||||
- **"Steam now requires user namespaces"** - steam-runtime-check-requirements' bwrap probe; the
|
||||
arm64 client has no such probe. The SteamRT3 client (`steamrt64/steam`) is started directly, the
|
||||
way the session starts `steamrtarm64/steam`, with `STEAM_RUNTIME_STEAMRT` pointing at Valve's
|
||||
runtime linked file by file and only the probe replaced.
|
||||
- **tier0 assertion "Function not implemented"** - semget: Android has no System V IPC. Traced with
|
||||
a `-DDEBUG_STRACE` FEX (build-fex.yml `cxxflags` input, artifact only). The session shim
|
||||
(`preload/*.c`) is now also built natively as `libblsession-x86_64.so`, staged, and preloaded
|
||||
through the rootfs's own `/etc/ld.so.preload`.
|
||||
- **re-exec into pressure-vessel after self-update** - `STEAM_STEAMRT_RECURSION_GUARD=1`.
|
||||
- **libgtk-x11-2.0 missing / soname links / old glibc shadowing** - Valve's steamrt3c platform
|
||||
libraries linked into `~/.droiddeck-x64/steamrt-libs`, soname links from the rootfs `ldconfig`,
|
||||
and only libraries the rootfs lacks (LD_LIBRARY_PATH beats system folders whatever its order).
|
||||
- **GLX failed** - the desktop exports zink over the arm64 Turnip ICD; cleared, llvmpipe used.
|
||||
- **web helper died of SIGTRAP a second after start** - found with pid-tagged traces (FEX AppConfig
|
||||
`OutputLog=server` + a foreground FEXServer, `BL_FEXSERVER_LOG`; file logs overwrite each other):
|
||||
every web helper read `/proc/self/status` from libtier0_s.so, saw proot as a tracer, and tier0 broke
|
||||
into the "debugger" with int3. `preload/tracer.c` exempts the web helper on purpose (Chromium traps
|
||||
on a status fd that is not procfs); with `BL_WEBHELPER_HIDE_TRACER=1` only opens called from
|
||||
libtier0_s.so get the copy.
|
||||
- `SessionFiles` stages `bannerlator-steam-x64` and the x86-64 shim (they were missing from the list).
|
||||
|
||||
Dead ends worth remembering: headless VAC testing is impossible (current Steam starts the saved
|
||||
login from its UI); `-cef-*` switches are not forwarded to the x86 web helper; the KMS
|
||||
`CREATE_DUMB` errors are a red herring (40 fast ENOTTY per process); not an address-space problem
|
||||
(0 ENOMEM in 618k traced syscalls, although the device is 39-bit VA).
|
||||
|
||||
Later the same day (device-proven unless noted):
|
||||
- **Controllers**: libfakeinput is now also built for x86-64 and preloaded in the FEX rootfs; the
|
||||
client registers the pad, and **Big Picture works with it** (Xbox prompts, D-pad moves focus).
|
||||
- **Online**: the launcher starts the system bus and the NetworkManager stand-in like the session.
|
||||
- From an audit of `bannerlator-session`: stale lock cleanup, branch sync before every start, core
|
||||
re-pinning, path cache and `perms.c` for `steamrt64`, the app's FEX preset (PERFORMANCE_TSO).
|
||||
- **Play button (built, not yet device-tested)**: Steam settings > Client > "Steam client: ARM64 /
|
||||
x86-64 (FEX, experimental)" (`BL_STEAM_CLIENT_ARCH`). The session then starts the x86 client via
|
||||
`bannerlator-steam-x64 --prepare/--exec` and gives it everything it gives the arm64 one; steps
|
||||
only for the arm64 client (ARM64 Proton, mapping, seeding, Decky, steamclient.so probes) are
|
||||
skipped.
|
||||
- L4D2 hard-link reuse does not work: switching platform makes Steam redownload depot 551 anyway.
|
||||
|
||||
Open:
|
||||
- VAC test: L4D2's native Linux build in the x86 client's own library (hard-linked from the arm64
|
||||
copy, same filesystem, so only the Linux depots download). Native Linux games start inside the
|
||||
Steam Linux Runtime container (pressure-vessel) - expected to need the same treatment.
|
||||
- No x86 GPU driver: games render with llvmpipe. Playable needs FEX host thunks.
|
||||
- Windows games in the x86 client need x86 Proton = pressure-vessel.
|
||||
- One client per account: integration would be a per-title hand-off, not side by side.
|
||||
|
||||
## 2026-09-29 - `feat/controller-input`: the pad the way SteamOS has it
|
||||
|
||||
Device-tested on the AYN Thor (Katamari under Proton Experimental ARM64).
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
# Android clipboard text
|
||||
|
||||
Copy text in an Android app, return to DroidDeck, and paste into Steam with Ctrl+V.
|
||||
The session's PC keyboard supports this through its sticky Ctrl key and V.
|
||||
|
||||
Android clipboard reads follow window focus, including the secondary-display presentation.
|
||||
The existing Wayland text selection handles native guest clients. Gamescope does not relay
|
||||
that selection to its inner Xwayland, so a session helper publishes Android text there.
|
||||
It waits for file and X11 events, and exits when its parent session exits.
|
||||
|
||||
The Gamescope bridge currently supports Android-to-guest plain text up to 64 KiB.
|
||||
It does not transfer images/files or export Steam's copied text back to Android.
|
||||
Oversized text clears an earlier Android selection rather than pasting a truncated command.
|
||||
Clipboard text stays in private app data and is never included in session logs.
|
||||
|
||||
## Thor validation, 2026-10-02
|
||||
|
||||
AYN Thor, serial `d234a848`, Android 13, release APK installed in place.
|
||||
Built with `tools/build_local.sh`; shell syntax, workflow YAML, and diff checks passed.
|
||||
Installed APK SHA-256 matched the local artifact:
|
||||
`624782af4319af538a9ae5dba6e012ebb51c7fd43a3955c4f568d214f9c32c07`.
|
||||
|
||||
- The supplied launch-options string pasted through Ctrl+V into Steam's actual Launch Options field exactly. The field was restored to its original empty value.
|
||||
- Unicode (`café 日本語 😀`, quotes, dollar sign, and backslash) also pasted exactly into Steam. The field was restored again.
|
||||
- Final-build X11 selection checks passed for launch options, multiline text, Unicode, 8 KiB, clearing, and replacing the clipboard across Android app switches.
|
||||
- Copying on Thor's second display transferred the text while Steam remained visible on the first display.
|
||||
- Copying the same Android text after a guest owned the X11 selection restored the Android selection.
|
||||
- A 65,537-byte clipboard was rejected without truncation; a subsequent normal clipboard transferred correctly.
|
||||
- The helper exited during APK replacement. The temporary Android test app, guest probe, and local ADB forward were removed.
|
||||
|
||||
Local screenshots, field values, build log, and check results: `/tmp/droiddeck-clipboard-evidence`.
|
||||
|
||||
## Visible editor-to-Steam test
|
||||
|
||||
Typed the supplied launch command into a temporary native Android EditText editor
|
||||
using Android keyboard events, selected all, and copied with Android's standard
|
||||
Ctrl+C action. Returned to the running DroidDeck Steam session and pasted into
|
||||
The Sims Legacy Collection's Launch Options. Steam's persisted value matched the
|
||||
complete 126-byte command exactly. No clipboard-setting API was used by the editor.
|
||||
|
||||
Repeated with `DroidDeck Thor clipboard test 2026-10-02`, using Steam's on-screen
|
||||
keyboard Paste button. The whole value is visible in these unedited Thor screenshots:
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
The launch options were restored to their original empty value and verified in
|
||||
Steam's configuration. The temporary editor and ADB forward were removed.
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 97 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 287 KiB |
@@ -120,9 +120,6 @@ docker run --rm --platform linux/amd64 \
|
||||
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
|
||||
-o "$d/libblfastpath.so" tools/proot/fastpath/fastpath.c -ldl
|
||||
aarch64-linux-gnu-strip --strip-unneeded "$d/libblfastpath.so"
|
||||
mkdir -p "$d/usr/local/bin"
|
||||
aarch64-linux-gnu-gcc -O2 -Wall -Wextra -o "$d/usr/local/bin/droiddeck-clipboard" tools/linuxfs/clipboard/clipboard.c -ldl
|
||||
aarch64-linux-gnu-strip --strip-unneeded "$d/usr/local/bin/droiddeck-clipboard"
|
||||
for script in tools/linuxfs/overlay/usr/local/bin/bannerlator-*; do
|
||||
install -Dm644 "$script" "$d/usr/local/bin/$(basename "$script")"
|
||||
done
|
||||
|
||||
Executable
+79
@@ -0,0 +1,79 @@
|
||||
#!/usr/bin/bash
|
||||
# Runs INSIDE an Arch Linux ARM container (menci/archlinuxarm:base-devel) on an arm64 runner.
|
||||
# Builds FEX for the runtime, with tools/fex/patches, (Arch Linux ARM ships no package and FEX publishes no Linux
|
||||
# binaries), plus the runtime's own unsquashfs to unpack FEX's x86 rootfs image, and packs both
|
||||
# as fex.tzst (usr/local/...) for bannerlator-steam-x64 to stage. FEX_THUNKS=1 adds the host
|
||||
# thunks (see below).
|
||||
set -euxo pipefail
|
||||
VERSION=${FEX_VERSION:-FEX-2609}
|
||||
WORK=/work
|
||||
cd "$WORK"
|
||||
# Same pacman workarounds as tools/gamescope/build-in-arch.sh.
|
||||
grep -q '^DisableSandbox' /etc/pacman.conf || sed -i 's/^\[options\]/[options]\nDisableSandbox/' /etc/pacman.conf
|
||||
{ for m in https://ca.us.mirror.archlinuxarm.org https://fl.us.mirror.archlinuxarm.org https://de3.mirror.archlinuxarm.org https://nl.mirror.archlinuxarm.org; do echo "Server = $m/\$arch/\$repo"; done; cat /etc/pacman.d/mirrorlist; } > /etc/pacman.d/mirrorlist.new
|
||||
mv /etc/pacman.d/mirrorlist.new /etc/pacman.d/mirrorlist
|
||||
pacman -Syu --noconfirm --needed git zstd binutils cmake ninja clang lld llvm python squashfs-tools file
|
||||
|
||||
# FEX_THUNKS=1: host thunks too - an x86 program's libvulkan/libGL/libX11/... calls go to the
|
||||
# runtime's own arm64 libraries (Turnip, Mesa), so the x86-64 client draws on the GPU. The host
|
||||
# half is arm64 and needs the graphics dev packages; the guest half is cross-compiled with clang
|
||||
# against an x86 sysroot: Arch Linux x86_64 (and multilib i686) packages unpacked into a root of
|
||||
# their own by pacman - never run, so no scriptlets and no signature checks.
|
||||
THUNKS=${FEX_THUNKS:-0}
|
||||
X86ROOT=$WORK/x86root
|
||||
if [ "$THUNKS" = 1 ]; then
|
||||
pacman -S --noconfirm --needed pkgconf libx11 libxcb libxrandr libxrender libxext xorgproto \
|
||||
libglvnd mesa wayland libdrm alsa-lib libxshmfence vulkan-headers vulkan-icd-loader
|
||||
rm -rf "$X86ROOT" && mkdir -p "$X86ROOT/var/lib/pacman" "$WORK/x86-cache"
|
||||
cat > "$WORK/x86-pacman.conf" <<'CONF'
|
||||
[options]
|
||||
Architecture = x86_64
|
||||
SigLevel = Never
|
||||
DisableSandbox
|
||||
[core]
|
||||
Server = https://geo.mirror.pkgbuild.com/$repo/os/$arch
|
||||
[extra]
|
||||
Server = https://geo.mirror.pkgbuild.com/$repo/os/$arch
|
||||
[multilib]
|
||||
Server = https://geo.mirror.pkgbuild.com/$repo/os/$arch
|
||||
CONF
|
||||
pacman --config "$WORK/x86-pacman.conf" --root "$X86ROOT" --dbpath "$X86ROOT/var/lib/pacman" \
|
||||
--cachedir "$WORK/x86-cache" --noscriptlet --noconfirm --overwrite '*' -Sy \
|
||||
glibc linux-api-headers gcc gcc-libs libx11 libxcb xorgproto libxrandr libxrender libxext libxau \
|
||||
libxdmcp libglvnd mesa wayland libdrm alsa-lib libxshmfence \
|
||||
lib32-glibc lib32-gcc-libs lib32-libx11 lib32-libxcb lib32-libxrandr lib32-libxrender \
|
||||
lib32-libxext lib32-libglvnd lib32-mesa lib32-wayland lib32-libdrm lib32-alsa-lib lib32-libxshmfence
|
||||
ls "$X86ROOT/usr/include" | head -5
|
||||
fi
|
||||
|
||||
rm -rf fex-src out && git clone -q --depth 1 --branch "$VERSION" --recurse-submodules --shallow-submodules https://github.com/FEX-Emu/FEX.git fex-src
|
||||
# Our proot answers openat2 with ENOSYS (tools/proot/PATCHES.md, 0008); FEX opened every rootfs
|
||||
# path with openat2 and fell through to the arm64 guest's files on anything but EXDEV.
|
||||
for p in tools/fex/patches/*.patch; do patch -d fex-src -p1 --no-backup-if-mismatch < "$p"; done
|
||||
# FEX's x86 toolchain files assume an x86 build machine: on this arm64 one the guest thunks need the
|
||||
# x86 sysroot for their headers, C runtime objects and libgcc too, not just the generator.
|
||||
if [ "$THUNKS" = 1 ]; then
|
||||
for t in fex-src/Data/CMake/toolchain_x86_64.cmake fex-src/Data/CMake/toolchain_x86_32.cmake; do
|
||||
printf '\nif (X86_DEV_ROOTFS AND NOT X86_DEV_ROOTFS STREQUAL "/")\n set(CMAKE_SYSROOT "${X86_DEV_ROOTFS}")\nendif()\n' >> "$t"
|
||||
done
|
||||
fi
|
||||
# TUNE_CPU none: the default (native) would tune for the runner's Neoverse cores, not the device.
|
||||
cmake -S fex-src -B fex-build -G Ninja \
|
||||
-DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr/local \
|
||||
-DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++ -DUSE_LINKER=lld \
|
||||
-DTUNE_CPU=none -DTUNE_ARCH=armv8-a \
|
||||
-DBUILD_TESTING=OFF -DBUILD_FEXCONFIG=OFF -DENABLE_ASSERTIONS=OFF \
|
||||
$( [ "$THUNKS" = 1 ] && echo "-DBUILD_THUNKS=ON -DX86_DEV_ROOTFS=$X86ROOT" || echo "-DBUILD_THUNKS=OFF" ) \
|
||||
-DENABLE_CCACHE=OFF -DENABLE_OFFLINE_TELEMETRY=OFF \
|
||||
${FEX_EXTRA_CXXFLAGS:+-DCMAKE_CXX_FLAGS="$FEX_EXTRA_CXXFLAGS"}
|
||||
ninja -C fex-build
|
||||
DESTDIR="$WORK/out" ninja -C fex-build install
|
||||
install -Dm755 /usr/bin/unsquashfs out/usr/local/bin/unsquashfs
|
||||
# Nothing outside the runtime's own libraries: every needed soname must resolve in a stock guest.
|
||||
for f in out/usr/local/bin/*; do
|
||||
file "$f" | grep -q ELF || continue
|
||||
readelf -d "$f" | awk '/NEEDED/ { gsub(/[\[\]]/, "", $5); print $5 }'
|
||||
done | sort -u | tee fex-needed.txt
|
||||
(cd out && find . -type f -o -type l | sort) | tee fex-files.txt
|
||||
tar -C out -c . | zstd -19 -T0 -o fex.tzst
|
||||
sha256sum fex.tzst | tee fex.tzst.sha256
|
||||
@@ -0,0 +1,42 @@
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp
|
||||
index 7172460..d566e3b 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp
|
||||
@@ -674,9 +674,10 @@ uint64_t FileManager::Open(const char* pathname, int flags, uint32_t mode) {
|
||||
};
|
||||
fd = ::syscall(SYSCALL_DEF(openat2), Path.FD, Path.Path, &how, sizeof(how));
|
||||
|
||||
- if (fd == -1 && errno == EXDEV) {
|
||||
- // This means a magic symlink (/proc/foo) was involved. In this case we
|
||||
- // just punt and do the access without RESOLVE_IN_ROOT.
|
||||
+ if (fd == -1 && (errno == EXDEV || errno == ENOSYS)) {
|
||||
+ // EXDEV: a magic symlink (/proc/foo) was involved. ENOSYS: no openat2 here (proot).
|
||||
+ // Either way, do the access without RESOLVE_IN_ROOT; GetEmulatedFDPath has already
|
||||
+ // followed absolute symlinks inside the rootfs.
|
||||
fd = ::syscall(SYSCALL_DEF(openat), Path.FD, Path.Path, flags, mode);
|
||||
}
|
||||
}
|
||||
@@ -927,9 +928,10 @@ uint64_t FileManager::Openat([[maybe_unused]] int dirfs, const char* pathname, i
|
||||
.resolve = (Path.FD == AT_FDCWD) ? 0u : RESOLVE_IN_ROOT, // AT_FDCWD means it's a thunk and not via RootFS
|
||||
};
|
||||
fd = ::syscall(SYSCALL_DEF(openat2), Path.FD, Path.Path, &how, sizeof(how));
|
||||
- if (fd == -1 && errno == EXDEV) {
|
||||
- // This means a magic symlink (/proc/foo) was involved. In this case we
|
||||
- // just punt and do the access without RESOLVE_IN_ROOT.
|
||||
+ if (fd == -1 && (errno == EXDEV || errno == ENOSYS)) {
|
||||
+ // EXDEV: a magic symlink (/proc/foo) was involved. ENOSYS: no openat2 here (proot).
|
||||
+ // Either way, do the access without RESOLVE_IN_ROOT; GetEmulatedFDPath has already
|
||||
+ // followed absolute symlinks inside the rootfs.
|
||||
fd = ::syscall(SYSCALL_DEF(openat), Path.FD, Path.Path, flags, mode);
|
||||
}
|
||||
}
|
||||
@@ -967,6 +969,9 @@ uint64_t FileManager::Openat2(int dirfs, const char* pathname, FEX::HLE::open_ho
|
||||
// This means a magic symlink (/proc/foo) was involved. In this case we
|
||||
// just punt and do the access without RESOLVE_IN_ROOT.
|
||||
fd = ::syscall(SYSCALL_DEF(openat2), Path.FD, Path.Path, how, usize);
|
||||
+ } else if (fd == -1 && errno == ENOSYS && how->resolve == 0) {
|
||||
+ // No openat2 here (proot): the plain openat inside the rootfs, as above.
|
||||
+ fd = ::syscall(SYSCALL_DEF(openat), Path.FD, Path.Path, (int)how->flags, (int)how->mode);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,154 +0,0 @@
|
||||
/* Android text -> Gamescope's Xwayland selection. Gamescope's Wayland backend does not
|
||||
* relay the outer compositor's clipboard. libX11 is loaded from the guest at runtime;
|
||||
* the small stable Xlib ABI below keeps this helper independent of cross X11 headers.
|
||||
* The private host file is atomically replaced, never put in session logs. */
|
||||
#define _GNU_SOURCE
|
||||
#include <sys/inotify.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/prctl.h>
|
||||
#include <signal.h>
|
||||
#include <poll.h>
|
||||
#include <fcntl.h>
|
||||
#include <unistd.h>
|
||||
#include <dlfcn.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <errno.h>
|
||||
#include <limits.h>
|
||||
|
||||
typedef struct _XDisplay Display;
|
||||
typedef unsigned long Window, Atom, Time;
|
||||
typedef struct {
|
||||
int type; unsigned long serial; int send_event; Display *display;
|
||||
Window owner, requestor; Atom selection, target, property; Time time;
|
||||
} SelectionRequest;
|
||||
typedef struct {
|
||||
int type; unsigned long serial; int send_event; Display *display;
|
||||
Window requestor; Atom selection, target, property; Time time;
|
||||
} SelectionNotify;
|
||||
typedef union { int type; SelectionRequest request; SelectionNotify selection; long pad[24]; } Event;
|
||||
|
||||
#define API(ret, name, args) static ret (*name) args
|
||||
API(Display *, XOpenDisplay, (const char *));
|
||||
API(Window, XDefaultRootWindow, (Display *));
|
||||
API(Window, XCreateSimpleWindow, (Display *, Window, int, int, unsigned, unsigned, unsigned, unsigned long, unsigned long));
|
||||
API(Atom, XInternAtom, (Display *, const char *, int));
|
||||
API(int, XSetSelectionOwner, (Display *, Atom, Window, Time));
|
||||
API(Window, XGetSelectionOwner, (Display *, Atom));
|
||||
API(int, XChangeProperty, (Display *, Window, Atom, Atom, int, int, const unsigned char *, int));
|
||||
API(int, XSendEvent, (Display *, Window, int, long, Event *));
|
||||
API(int, XPending, (Display *));
|
||||
API(int, XNextEvent, (Display *, Event *));
|
||||
API(int, XFlush, (Display *));
|
||||
API(int, XConnectionNumber, (Display *));
|
||||
API(int, XCloseDisplay, (Display *));
|
||||
API(void *, XSetErrorHandler, (int (*)(Display *, void *)));
|
||||
|
||||
/* Stay below X11's normal maximum property request. Never paste a truncated command. */
|
||||
#define MAX_TEXT (64 * 1024)
|
||||
static int ignore_x_error(Display *d, void *event) { (void)d; (void)event; return 0; }
|
||||
|
||||
/* The host renames complete files into place. The inode distinguishes copying the same
|
||||
* text again after a guest program has taken ownership of the clipboard. */
|
||||
static int refresh(Display *d, Window w, Atom clipboard, const char *path,
|
||||
char **text, size_t *len, ino_t *inode) {
|
||||
int fd = open(path, O_RDONLY | O_CLOEXEC | O_NOFOLLOW);
|
||||
if (fd < 0) return 0;
|
||||
struct stat st;
|
||||
if (fstat(fd, &st) || !S_ISREG(st.st_mode) || st.st_ino == *inode) { close(fd); return 0; }
|
||||
*inode = st.st_ino;
|
||||
if (st.st_size < 0 || st.st_size > MAX_TEXT) {
|
||||
fprintf(stderr, "== clipboard: text exceeds %d bytes, not pasted\n", MAX_TEXT);
|
||||
if (XGetSelectionOwner(d, clipboard) == w) XSetSelectionOwner(d, clipboard, 0, 0);
|
||||
XFlush(d);
|
||||
free(*text); *text = NULL; *len = 0;
|
||||
close(fd); return 0;
|
||||
}
|
||||
char *copy = malloc((size_t)st.st_size + 1);
|
||||
if (!copy) { close(fd); return 0; }
|
||||
size_t got = 0;
|
||||
while (got < (size_t)st.st_size) {
|
||||
ssize_t n = read(fd, copy + got, (size_t)st.st_size - got);
|
||||
if (n > 0) got += n;
|
||||
else if (n < 0 && errno == EINTR) continue;
|
||||
else break;
|
||||
}
|
||||
close(fd);
|
||||
if (got != (size_t)st.st_size) { free(copy); return 0; }
|
||||
copy[got] = 0;
|
||||
free(*text); *text = copy; *len = got;
|
||||
if (got) XSetSelectionOwner(d, clipboard, w, 0);
|
||||
else if (XGetSelectionOwner(d, clipboard) == w) XSetSelectionOwner(d, clipboard, 0, 0);
|
||||
XFlush(d);
|
||||
fprintf(stderr, "== clipboard: Android text available in Xwayland (%zu bytes)\n", got);
|
||||
return 1;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
if (argc != 2 || !getenv("DISPLAY")) return 1;
|
||||
pid_t parent_pid = getppid();
|
||||
if (parent_pid == 1 || prctl(PR_SET_PDEATHSIG, SIGTERM) || getppid() != parent_pid) return 1;
|
||||
void *lib = dlopen("libX11.so.6", RTLD_NOW | RTLD_LOCAL);
|
||||
if (!lib) { fprintf(stderr, "== clipboard: libX11 unavailable\n"); return 1; }
|
||||
#define LOAD(name) do { *(void **)(&name) = dlsym(lib, #name); if (!name) return 1; } while (0)
|
||||
LOAD(XOpenDisplay); LOAD(XDefaultRootWindow); LOAD(XCreateSimpleWindow); LOAD(XInternAtom);
|
||||
LOAD(XSetSelectionOwner); LOAD(XGetSelectionOwner); LOAD(XChangeProperty); LOAD(XSendEvent);
|
||||
LOAD(XPending); LOAD(XNextEvent); LOAD(XFlush); LOAD(XConnectionNumber); LOAD(XCloseDisplay);
|
||||
LOAD(XSetErrorHandler);
|
||||
Display *d = XOpenDisplay(NULL);
|
||||
if (!d) { fprintf(stderr, "== clipboard: cannot open Xwayland\n"); return 1; }
|
||||
XSetErrorHandler(ignore_x_error); /* A paste requester can close its window at any time. */
|
||||
Window w = XCreateSimpleWindow(d, XDefaultRootWindow(d), 0, 0, 1, 1, 0, 0, 0);
|
||||
Atom clipboard = XInternAtom(d, "CLIPBOARD", 0);
|
||||
Atom targets = XInternAtom(d, "TARGETS", 0), utf8 = XInternAtom(d, "UTF8_STRING", 0);
|
||||
Atom plain = XInternAtom(d, "text/plain;charset=utf-8", 0), text_atom = XInternAtom(d, "TEXT", 0);
|
||||
Atom string = XInternAtom(d, "STRING", 0);
|
||||
char parent[PATH_MAX];
|
||||
if (strlen(argv[1]) >= sizeof(parent)) return 1;
|
||||
strcpy(parent, argv[1]); char *slash = strrchr(parent, '/');
|
||||
if (!slash) return 1;
|
||||
*slash = 0;
|
||||
int watch = inotify_init1(IN_CLOEXEC | IN_NONBLOCK);
|
||||
if (watch < 0 || inotify_add_watch(watch, parent, IN_MOVED_TO | IN_CLOSE_WRITE) < 0) return 1;
|
||||
char *text = NULL; size_t len = 0; ino_t inode = 0;
|
||||
refresh(d, w, clipboard, argv[1], &text, &len, &inode);
|
||||
struct pollfd fds[] = {{XConnectionNumber(d), POLLIN, 0}, {watch, POLLIN, 0}};
|
||||
for (;;) {
|
||||
while (XPending(d)) {
|
||||
Event e; XNextEvent(d, &e);
|
||||
if (e.type != 30) continue; /* SelectionRequest */
|
||||
SelectionRequest *r = &e.request;
|
||||
Atom property = r->property ? r->property : r->target;
|
||||
Event reply = {0};
|
||||
reply.selection = (SelectionNotify){31, 0, 1, d, r->requestor, r->selection, r->target, 0, r->time};
|
||||
if (r->selection == clipboard && text && len) {
|
||||
size_t ascii; for (ascii = 0; ascii < len && (unsigned char)text[ascii] < 128; ascii++) {}
|
||||
if (r->target == targets) {
|
||||
Atom supported[] = {targets, utf8, plain, text_atom, string};
|
||||
XChangeProperty(d, r->requestor, property, 4 /* XA_ATOM */, 32, 0,
|
||||
(const unsigned char *)supported, ascii == len ? 5 : 4);
|
||||
reply.selection.property = property;
|
||||
} else if (r->target == utf8 || r->target == plain || r->target == text_atom) {
|
||||
XChangeProperty(d, r->requestor, property, utf8, 8, 0, (const unsigned char *)text, (int)len);
|
||||
reply.selection.property = property;
|
||||
} else if (r->target == string) {
|
||||
/* STRING is Latin-1. Offer it only for ASCII rather than corrupt UTF-8. */
|
||||
if (ascii == len) {
|
||||
XChangeProperty(d, r->requestor, property, string, 8, 0, (const unsigned char *)text, (int)len);
|
||||
reply.selection.property = property;
|
||||
}
|
||||
}
|
||||
}
|
||||
XSendEvent(d, r->requestor, 0, 0, &reply); XFlush(d);
|
||||
}
|
||||
if (poll(fds, 2, -1) < 0) { if (errno == EINTR) continue; break; }
|
||||
if (fds[0].revents & (POLLERR | POLLHUP | POLLNVAL)) break;
|
||||
if (fds[1].revents & POLLIN) {
|
||||
char events[4096]; while (read(watch, events, sizeof(events)) > 0) {}
|
||||
refresh(d, w, clipboard, argv[1], &text, &len, &inode);
|
||||
}
|
||||
}
|
||||
free(text); close(watch); XCloseDisplay(d); dlclose(lib);
|
||||
return 0;
|
||||
}
|
||||
@@ -119,6 +119,17 @@ export BL_DESKTOP=1
|
||||
ln -sf /usr/local/bin/bannerlator-steam-launch /usr/local/bin/steamdeck-steam 2>/dev/null
|
||||
ln -sf /usr/local/bin/bannerlator-steam-shim /usr/local/bin/steam 2>/dev/null
|
||||
python3 /usr/local/bin/bannerlator-desktop-games 2>&1 | sed 's/^/[games] /'
|
||||
# EXPERIMENT: Valve's x86-64 client under FEX (bannerlator-steam-x64), in a terminal so its
|
||||
# first-run downloads show. Not a Game entry, so droiddeck-desktop-gpu leaves its Exec alone.
|
||||
cat > /usr/share/applications/droiddeck-steam-x64.desktop <<'ENTRY'
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=Steam x86-64 (FEX, experimental)
|
||||
Comment=Valve's x86-64 Linux client under FEX, in its own home with its own login
|
||||
Exec=qterminal -e /usr/local/bin/bannerlator-steam-x64
|
||||
Icon=steam
|
||||
Categories=System;
|
||||
ENTRY
|
||||
# Player 1 on the controller in every emulator that has no profile of its own yet - now, and again
|
||||
# every half minute: an emulator started for the first time writes its own config, which is then
|
||||
# given the controller for its next start without waiting for the next desktop.
|
||||
|
||||
@@ -1,17 +1,20 @@
|
||||
#!/usr/bin/python3
|
||||
# Based on WinNative (maxjivi05, feature/wayland-gamescope e7a224ae), GPL-3.0.
|
||||
# Steam speaks NetworkManager; Android owns the radios, routes and connection. Export the
|
||||
# app's live snapshot through that API, including nearby Wi-Fi access points. Requests to
|
||||
# scan are handed to Android; Android settings still handle joining networks.
|
||||
import ipaddress
|
||||
import json
|
||||
import re
|
||||
import time
|
||||
# Ported from WinNative (maxjivi05, feature/wayland-gamescope e7a224ae), GPL-3.0, with thanks.
|
||||
# Renamed again for this app; the answers themselves are his.
|
||||
#
|
||||
# Answers for NetworkManager on the runtime's system bus, for the Steam client:
|
||||
# bannerlator-netmanager
|
||||
#
|
||||
# The client's network page and its connection indicator are built on NetworkManager. It asks for
|
||||
# one over the system bus as it starts, and without an answer it leaves out half of what its
|
||||
# interface then calls: Settings > Internet stops with "StartScanningForNetworks is not a function"
|
||||
# and the header shows no connection while downloads run.
|
||||
#
|
||||
# The network here is Android's: the app has no say in Wi-Fi, and nothing in this runtime could
|
||||
# scan or join one. So this reports what is true and no more - one connection that is up while
|
||||
# Android has a route out, under the address the app was given - and refuses what it cannot do.
|
||||
import socket
|
||||
import struct
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from xml.sax.saxutils import escape
|
||||
|
||||
import gi
|
||||
|
||||
@@ -21,401 +24,207 @@ from gi.repository import Gio, GLib # noqa: E402
|
||||
NAME = "org.freedesktop.NetworkManager"
|
||||
ROOT = "/org/freedesktop/NetworkManager"
|
||||
SETTINGS = ROOT + "/Settings"
|
||||
DEVICE = ROOT + "/Devices/1"
|
||||
ACTIVE = ROOT + "/ActiveConnection/1"
|
||||
IP4 = ROOT + "/IP4Config/1"
|
||||
IP6 = ROOT + "/IP6Config/1"
|
||||
AP = ROOT + "/AccessPoint/1"
|
||||
PROFILE = SETTINGS + "/1"
|
||||
UUID = "b1d0c8e4-57f0-4c0e-9d60-77696e6e6174"
|
||||
SNAPSHOT = Path("/etc/bannerlator-network.json")
|
||||
SCAN_REQUEST = Path("/etc/bannerlator-wifi-scan-request")
|
||||
OBJECT_MANAGER = "org.freedesktop.DBus.ObjectManager"
|
||||
PROPERTIES = "org.freedesktop.DBus.Properties"
|
||||
CHECK_SECONDS = 10
|
||||
|
||||
METHODS = {
|
||||
OBJECT_MANAGER: '''
|
||||
<method name="GetManagedObjects"><arg type="a{oa{sa{sv}}}" direction="out"/></method>
|
||||
<signal name="InterfacesAdded"><arg type="o"/><arg type="a{sa{sv}}"/></signal>
|
||||
<signal name="InterfacesRemoved"><arg type="o"/><arg type="as"/></signal>''',
|
||||
NAME: '''
|
||||
<method name="GetPermissions"><arg type="a{ss}" direction="out"/></method>
|
||||
<method name="CheckConnectivity"><arg type="u" direction="out"/></method>
|
||||
<method name="GetDevices"><arg type="ao" direction="out"/></method>
|
||||
<method name="GetAllDevices"><arg type="ao" direction="out"/></method>
|
||||
<signal name="StateChanged"><arg type="u"/></signal>''',
|
||||
NAME + ".Settings": '<method name="ListConnections"><arg type="ao" direction="out"/></method>',
|
||||
NAME + ".Settings.Connection": '<method name="GetSettings"><arg type="a{sa{sv}}" direction="out"/></method><signal name="Updated"/>',
|
||||
NAME + ".Device": '<signal name="StateChanged"><arg type="u"/><arg type="u"/><arg type="u"/></signal>',
|
||||
NAME + ".Device.Wireless": '''
|
||||
<method name="GetAccessPoints"><arg type="ao" direction="out"/></method>
|
||||
<method name="GetAllAccessPoints"><arg type="ao" direction="out"/></method>
|
||||
<method name="RequestScan"><arg type="a{sv}" direction="in"/></method>
|
||||
<signal name="AccessPointAdded"><arg type="o"/></signal>
|
||||
<signal name="AccessPointRemoved"><arg type="o"/></signal>''',
|
||||
}
|
||||
# NetworkManager's own numbers.
|
||||
NM_STATE_DISCONNECTED, NM_STATE_CONNECTED_GLOBAL = 20, 70
|
||||
NM_CONNECTIVITY_NONE, NM_CONNECTIVITY_FULL = 1, 4
|
||||
NM_DEVICE_TYPE_ETHERNET = 1
|
||||
NM_DEVICE_STATE_DISCONNECTED, NM_DEVICE_STATE_ACTIVATED = 30, 100
|
||||
NM_ACTIVE_CONNECTION_STATE_ACTIVATED = 2
|
||||
|
||||
INTROSPECTION = """
|
||||
<node>
|
||||
<interface name="org.freedesktop.DBus.ObjectManager">
|
||||
<method name="GetManagedObjects">
|
||||
<arg type="a{oa{sa{sv}}}" direction="out"/>
|
||||
</method>
|
||||
</interface>
|
||||
<interface name="org.freedesktop.NetworkManager">
|
||||
<method name="GetPermissions"><arg type="a{ss}" direction="out"/></method>
|
||||
<method name="CheckConnectivity"><arg type="u" direction="out"/></method>
|
||||
<method name="GetDevices"><arg type="ao" direction="out"/></method>
|
||||
<method name="GetAllDevices"><arg type="ao" direction="out"/></method>
|
||||
<signal name="StateChanged"><arg type="u"/></signal>
|
||||
</interface>
|
||||
<interface name="org.freedesktop.NetworkManager.Settings.Connection">
|
||||
<method name="GetSettings"><arg type="a{sa{sv}}" direction="out"/></method>
|
||||
</interface>
|
||||
<interface name="org.freedesktop.NetworkManager.Device">
|
||||
<signal name="StateChanged"><arg type="u"/><arg type="u"/><arg type="u"/></signal>
|
||||
</interface>
|
||||
</node>
|
||||
"""
|
||||
|
||||
|
||||
def address():
|
||||
"""The address Android routes out by, or None without a route. Nothing is sent."""
|
||||
try:
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
|
||||
s.connect(("192.0.2.1", 9))
|
||||
return s.getsockname()[0]
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def v(signature, value):
|
||||
return GLib.Variant(signature, value)
|
||||
|
||||
|
||||
def read_snapshot():
|
||||
# Atomic replacement by the app means we never see a partially written handover.
|
||||
try:
|
||||
state = json.loads(SNAPSHOT.read_text())
|
||||
if not isinstance(state, dict) or not isinstance(state.get("connected"), bool):
|
||||
return None
|
||||
return state
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def legacy_snapshot():
|
||||
# Older APKs do not publish transport metadata. Never guess Wi-Fi from an interface name.
|
||||
try:
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
|
||||
sock.connect(("192.0.2.1", 9))
|
||||
ip = sock.getsockname()[0]
|
||||
return {"connected": True, "transport": "ethernet", "addresses": [{"address": ip, "prefix": 32}]}
|
||||
except OSError:
|
||||
return {"connected": False, "transport": "none"}
|
||||
|
||||
|
||||
def connection_type(state):
|
||||
return {"wifi": "802-11-wireless", "cellular": "gsm", "ethernet": "802-3-ethernet",
|
||||
"vpn": "tun"}.get(state.get("transport"), "generic")
|
||||
|
||||
|
||||
def device_path(state):
|
||||
transport = state.get("transport", "none")
|
||||
if not state["connected"] and state.get("wifiEnabled"):
|
||||
transport = "wifi"
|
||||
return ROOT + "/Devices/" + {"wifi": "Wifi", "cellular": "Cellular", "ethernet": "Ethernet",
|
||||
"vpn": "Vpn"}.get(transport, "Android")
|
||||
|
||||
|
||||
def connection_name(state):
|
||||
return {"wifi": state.get("ssid") or "Wi-Fi", "cellular": "Cellular", "ethernet": "Ethernet",
|
||||
"vpn": "VPN"}.get(state.get("transport"), "Android")
|
||||
|
||||
|
||||
def connectivity(state):
|
||||
if not state["connected"]:
|
||||
return 1 # NONE
|
||||
if state.get("validated"):
|
||||
return 4 # FULL
|
||||
return 2 if state.get("captivePortal") else 3 # PORTAL / LIMITED
|
||||
|
||||
|
||||
def metered(state):
|
||||
return {True: 1, False: 2}.get(state.get("metered"), 0)
|
||||
|
||||
|
||||
def family_addresses(state, version):
|
||||
return [entry for entry in state.get("addresses", [])
|
||||
if ipaddress.ip_address(entry["address"]).version == version]
|
||||
|
||||
|
||||
def ip_config(state, version):
|
||||
entries = family_addresses(state, version)
|
||||
gateways = [ip for ip in state.get("gateways", []) if ipaddress.ip_address(ip).version == version]
|
||||
dns = [ip for ip in state.get("dns", []) if ipaddress.ip_address(ip).version == version]
|
||||
gateway = gateways[0] if gateways else ""
|
||||
props = {
|
||||
"AddressData": v("aa{sv}", [{"address": v("s", a["address"]), "prefix": v("u", a["prefix"])} for a in entries]),
|
||||
"Gateway": v("s", gateway), "RouteData": v("aa{sv}", []),
|
||||
"Domains": v("as", []), "Searches": v("as", []), "DnsOptions": v("as", []), "DnsPriority": v("i", 0),
|
||||
}
|
||||
if version == 4:
|
||||
native = lambda ip: struct.unpack("=I", socket.inet_aton(ip))[0]
|
||||
props.update({
|
||||
"Addresses": v("aau", [[native(a["address"]), a["prefix"], native(gateway) if gateway else 0] for a in entries]),
|
||||
"Routes": v("aau", []),
|
||||
"NameserverData": v("aa{sv}", [{"address": v("s", ip)} for ip in dns]),
|
||||
"Nameservers": v("au", [native(ip) for ip in dns]),
|
||||
"WinsServerData": v("as", []), "WinsServers": v("au", []),
|
||||
})
|
||||
else:
|
||||
packed = lambda ip: list(socket.inet_pton(socket.AF_INET6, ip))
|
||||
props.update({
|
||||
"Addresses": v("a(ayuay)", [(packed(a["address"]), a["prefix"], packed(gateway) if gateway else [0] * 16) for a in entries]),
|
||||
"Routes": v("a(ayuayu)", []), "Nameservers": v("aay", [packed(ip) for ip in dns]),
|
||||
})
|
||||
return props
|
||||
|
||||
|
||||
def ap_path(bssid):
|
||||
if bssid and re.fullmatch(r"(?:[0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}", bssid):
|
||||
return ROOT + "/AccessPoint/" + bssid.replace(":", "").lower()
|
||||
return AP
|
||||
|
||||
|
||||
def active_ap(state):
|
||||
return ap_path(state.get("bssid")) if state["connected"] and state.get("transport") == "wifi" else "/"
|
||||
|
||||
|
||||
def ap_security(capabilities):
|
||||
# NetworkManager's cipher/key-management flags, from Android's beacon capabilities.
|
||||
wpa = rsn = 0
|
||||
for group in re.findall(r"\[([^]]+)\]", capabilities.upper()):
|
||||
flags = 0
|
||||
if "CCMP" in group:
|
||||
flags |= 0x08 | 0x80
|
||||
if "TKIP" in group:
|
||||
flags |= 0x04 | 0x40
|
||||
if "PSK" in group:
|
||||
flags |= 0x100
|
||||
if "EAP" in group:
|
||||
flags |= 0x200
|
||||
if "SAE" in group:
|
||||
flags |= 0x400
|
||||
if "OWE" in group:
|
||||
flags |= 0x800
|
||||
if "WPA2" in group or "RSN" in group or "SAE" in group or "OWE" in group:
|
||||
rsn |= flags
|
||||
elif "WPA" in group:
|
||||
wpa |= flags
|
||||
privacy = int(bool(wpa or rsn or "WEP" in capabilities.upper()))
|
||||
return privacy, wpa, rsn
|
||||
|
||||
|
||||
def access_points(state):
|
||||
result = {ap_path(ap.get("bssid")): dict(ap) for ap in state.get("accessPoints", []) if ap.get("ssid")}
|
||||
if active_ap(state) != "/":
|
||||
current = result.setdefault(active_ap(state), {})
|
||||
for key in ("ssid", "bssid", "strength", "frequency", "bitrate"):
|
||||
if key in state:
|
||||
current[key] = state[key]
|
||||
current.setdefault("ssid", "Wi-Fi")
|
||||
return result
|
||||
|
||||
|
||||
def ap_properties(ap):
|
||||
privacy, wpa, rsn = ap_security(ap.get("capabilities", ""))
|
||||
return {
|
||||
"Flags": v("u", privacy), "WpaFlags": v("u", wpa), "RsnFlags": v("u", rsn),
|
||||
"Ssid": v("ay", list(ap["ssid"].encode("utf-8"))),
|
||||
"Frequency": v("u", ap.get("frequency", 0)), "HwAddress": v("s", ap.get("bssid", "")), "Mode": v("u", 2),
|
||||
"MaxBitrate": v("u", ap.get("bitrate", 0)),
|
||||
"Strength": v("y", max(0, min(100, ap.get("strength", 0)))), "LastSeen": v("i", ap.get("lastSeen", -1)),
|
||||
}
|
||||
|
||||
|
||||
def objects(state):
|
||||
device = device_path(state)
|
||||
aps = access_points(state)
|
||||
current_ap = active_ap(state)
|
||||
up = state["connected"]
|
||||
transport = state.get("transport", "none")
|
||||
wifi = transport == "wifi" or (not up and state.get("wifiEnabled", False))
|
||||
cellular = transport == "cellular"
|
||||
kind = connection_type(state)
|
||||
ip4 = up and bool(family_addresses(state, 4))
|
||||
ip6 = up and bool(family_addresses(state, 6))
|
||||
device_state = 100 if up else 30
|
||||
def objects(ip):
|
||||
"""Every object NetworkManager would export, as its ObjectManager describes them."""
|
||||
up = ip is not None
|
||||
found = {
|
||||
ROOT: {NAME: {
|
||||
"Devices": v("ao", [device]), "AllDevices": v("ao", [device]),
|
||||
"Devices": v("ao", [DEVICE]),
|
||||
"AllDevices": v("ao", [DEVICE]),
|
||||
"ActiveConnections": v("ao", [ACTIVE] if up else []),
|
||||
"PrimaryConnection": v("o", ACTIVE if up else "/"),
|
||||
"PrimaryConnectionType": v("s", kind if up else ""), "ActivatingConnection": v("o", "/"),
|
||||
"PrimaryConnectionType": v("s", "802-3-ethernet" if up else ""),
|
||||
"ActivatingConnection": v("o", "/"),
|
||||
"NetworkingEnabled": v("b", True),
|
||||
"WirelessEnabled": v("b", bool(state.get("wifiEnabled", wifi))),
|
||||
"WirelessHardwareEnabled": v("b", bool(state.get("wifiEnabled", wifi))),
|
||||
"WwanEnabled": v("b", cellular), "WwanHardwareEnabled": v("b", cellular),
|
||||
"Startup": v("b", False), "Version": v("s", "1.46.0"),
|
||||
"State": v("u", (70 if state.get("validated") else 60) if up else 20),
|
||||
"Connectivity": v("u", connectivity(state)),
|
||||
"ConnectivityCheckAvailable": v("b", False), "ConnectivityCheckEnabled": v("b", False),
|
||||
"Metered": v("u", metered(state)),
|
||||
"WirelessEnabled": v("b", False),
|
||||
"WirelessHardwareEnabled": v("b", False),
|
||||
"WwanEnabled": v("b", False),
|
||||
"WwanHardwareEnabled": v("b", False),
|
||||
"Startup": v("b", False),
|
||||
"Version": v("s", "1.46.0"),
|
||||
"State": v("u", NM_STATE_CONNECTED_GLOBAL if up else NM_STATE_DISCONNECTED),
|
||||
"Connectivity": v("u", NM_CONNECTIVITY_FULL if up else NM_CONNECTIVITY_NONE),
|
||||
"ConnectivityCheckAvailable": v("b", False),
|
||||
"ConnectivityCheckEnabled": v("b", False),
|
||||
"Metered": v("u", 0),
|
||||
}},
|
||||
SETTINGS: {NAME + ".Settings": {
|
||||
"Connections": v("ao", [PROFILE]), "Hostname": v("s", socket.gethostname()), "CanModify": v("b", False),
|
||||
"Connections": v("ao", [PROFILE]),
|
||||
"Hostname": v("s", socket.gethostname()),
|
||||
"CanModify": v("b", False),
|
||||
}},
|
||||
PROFILE: {NAME + ".Settings.Connection": {
|
||||
"Unsaved": v("b", True), "Flags": v("u", 0), "Filename": v("s", ""),
|
||||
}},
|
||||
device: {NAME + ".Device": {
|
||||
"Interface": v("s", state.get("interface", "android")),
|
||||
"IpInterface": v("s", state.get("interface", "android") if up else ""),
|
||||
"Driver": v("s", "android"),
|
||||
"DeviceType": v("u", 2 if wifi else 8 if cellular else {"ethernet": 1, "vpn": 16}.get(transport, 14)),
|
||||
"State": v("u", device_state), "StateReason": v("(uu)", (device_state, 0)),
|
||||
"ActiveConnection": v("o", ACTIVE if up else "/"),
|
||||
"Ip4Config": v("o", IP4 if ip4 else "/"), "Ip6Config": v("o", IP6 if ip6 else "/"),
|
||||
"Dhcp4Config": v("o", "/"), "Dhcp6Config": v("o", "/"),
|
||||
"AvailableConnections": v("ao", [PROFILE]), "Managed": v("b", True),
|
||||
"Autoconnect": v("b", False), "Real": v("b", True), "Capabilities": v("u", 1),
|
||||
"Mtu": v("u", state.get("mtu", 1500)), "HwAddress": v("s", ""), "Metered": v("u", metered(state)),
|
||||
"Unsaved": v("b", False),
|
||||
"Flags": v("u", 0),
|
||||
"Filename": v("s", ""),
|
||||
}},
|
||||
DEVICE: {
|
||||
NAME + ".Device": {
|
||||
"Interface": v("s", "android"),
|
||||
"IpInterface": v("s", "android" if up else ""),
|
||||
"Driver": v("s", "android"),
|
||||
"DeviceType": v("u", NM_DEVICE_TYPE_ETHERNET),
|
||||
"State": v("u", NM_DEVICE_STATE_ACTIVATED if up else NM_DEVICE_STATE_DISCONNECTED),
|
||||
"StateReason": v("(uu)", (NM_DEVICE_STATE_ACTIVATED if up else NM_DEVICE_STATE_DISCONNECTED, 0)),
|
||||
"ActiveConnection": v("o", ACTIVE if up else "/"),
|
||||
"Ip4Config": v("o", IP4 if up else "/"),
|
||||
"Ip6Config": v("o", "/"),
|
||||
"Dhcp4Config": v("o", "/"),
|
||||
"Dhcp6Config": v("o", "/"),
|
||||
"AvailableConnections": v("ao", [PROFILE]),
|
||||
"Managed": v("b", True),
|
||||
"Autoconnect": v("b", True),
|
||||
"Real": v("b", True),
|
||||
"Capabilities": v("u", 1),
|
||||
"Mtu": v("u", 1500),
|
||||
"HwAddress": v("s", ""),
|
||||
},
|
||||
NAME + ".Device.Wired": {
|
||||
"HwAddress": v("s", ""),
|
||||
"PermHwAddress": v("s", ""),
|
||||
"Speed": v("u", 0),
|
||||
"Carrier": v("b", up),
|
||||
},
|
||||
},
|
||||
}
|
||||
if wifi:
|
||||
found[device][NAME + ".Device.Wireless"] = {
|
||||
"HwAddress": v("s", ""), "PermHwAddress": v("s", ""), "Mode": v("u", 2),
|
||||
"Bitrate": v("u", state.get("bitrate", 0)), "WirelessCapabilities": v("u", 0),
|
||||
"AccessPoints": v("ao", list(aps)), "ActiveAccessPoint": v("o", current_ap),
|
||||
"LastScan": v("x", state.get("lastScan", -1)),
|
||||
}
|
||||
for path, ap in aps.items():
|
||||
found[path] = {NAME + ".AccessPoint": ap_properties(ap)}
|
||||
elif cellular:
|
||||
found[device][NAME + ".Device.Modem"] = {
|
||||
"ModemCapabilities": v("u", 4), "CurrentCapabilities": v("u", 4),
|
||||
"DeviceId": v("s", "android"), "OperatorCode": v("s", ""), "Apn": v("s", ""),
|
||||
}
|
||||
elif transport == "ethernet":
|
||||
found[device][NAME + ".Device.Wired"] = {
|
||||
"HwAddress": v("s", ""), "PermHwAddress": v("s", ""), "Speed": v("u", 0), "Carrier": v("b", up),
|
||||
}
|
||||
if up:
|
||||
found[ACTIVE] = {NAME + ".Connection.Active": {
|
||||
"Connection": v("o", PROFILE), "SpecificObject": v("o", current_ap),
|
||||
"Id": v("s", connection_name(state)), "Uuid": v("s", UUID), "Type": v("s", kind),
|
||||
"Devices": v("ao", [device]), "State": v("u", 2), "StateFlags": v("u", 0),
|
||||
"Default": v("b", ip4), "Default6": v("b", ip6),
|
||||
"Ip4Config": v("o", IP4 if ip4 else "/"), "Ip6Config": v("o", IP6 if ip6 else "/"),
|
||||
"Dhcp4Config": v("o", "/"), "Dhcp6Config": v("o", "/"), "Vpn": v("b", False), "Master": v("o", "/"),
|
||||
"Connection": v("o", PROFILE),
|
||||
"SpecificObject": v("o", "/"),
|
||||
"Id": v("s", "Android"),
|
||||
"Uuid": v("s", UUID),
|
||||
"Type": v("s", "802-3-ethernet"),
|
||||
"Devices": v("ao", [DEVICE]),
|
||||
"State": v("u", NM_ACTIVE_CONNECTION_STATE_ACTIVATED),
|
||||
"StateFlags": v("u", 0),
|
||||
"Default": v("b", True),
|
||||
"Ip4Config": v("o", IP4),
|
||||
"Dhcp4Config": v("o", "/"),
|
||||
"Default6": v("b", False),
|
||||
"Ip6Config": v("o", "/"),
|
||||
"Dhcp6Config": v("o", "/"),
|
||||
"Vpn": v("b", False),
|
||||
"Master": v("o", "/"),
|
||||
}}
|
||||
found[IP4] = {NAME + ".IP4Config": {
|
||||
# The one address the app can see; the prefix says only that much is known.
|
||||
"AddressData": v("aa{sv}", [{"address": v("s", ip), "prefix": v("u", 32)}]),
|
||||
"Addresses": v("aau", []),
|
||||
"Gateway": v("s", ""),
|
||||
"RouteData": v("aa{sv}", []),
|
||||
"Routes": v("aau", []),
|
||||
"NameserverData": v("aa{sv}", []),
|
||||
"Nameservers": v("au", []),
|
||||
"Domains": v("as", []),
|
||||
"Searches": v("as", []),
|
||||
"DnsOptions": v("as", []),
|
||||
"DnsPriority": v("i", 0),
|
||||
"WinsServerData": v("as", []),
|
||||
"WinsServers": v("au", []),
|
||||
}}
|
||||
for version, present, path in ((4, ip4, IP4), (6, ip6, IP6)):
|
||||
if present:
|
||||
found[path] = {NAME + f".IP{version}Config": ip_config(state, version)}
|
||||
if up and not wifi and state.get("wifiEnabled"):
|
||||
# Android can keep its Wi-Fi radio available while cellular/VPN is the default route.
|
||||
wireless = objects(dict(state, connected=False, transport="none",
|
||||
interface=state.get("wifiInterface", "wlan0"), metered=None))
|
||||
wifi_device = ROOT + "/Devices/Wifi"
|
||||
found[wifi_device] = wireless[wifi_device]
|
||||
found[wifi_device][NAME + ".Device"]["AvailableConnections"] = v("ao", [])
|
||||
for path, interfaces in wireless.items():
|
||||
if NAME + ".AccessPoint" in interfaces:
|
||||
found[path] = interfaces
|
||||
found[ROOT][NAME]["Devices"] = v("ao", [device, wifi_device])
|
||||
found[ROOT][NAME]["AllDevices"] = v("ao", [device, wifi_device])
|
||||
return found
|
||||
|
||||
|
||||
def settings(state):
|
||||
result = {"connection": {
|
||||
"id": v("s", connection_name(state)), "uuid": v("s", UUID), "type": v("s", connection_type(state)),
|
||||
"interface-name": v("s", state.get("interface", "android")), "metered": v("u", metered(state)),
|
||||
}}
|
||||
if state.get("transport") == "wifi":
|
||||
result["802-11-wireless"] = {
|
||||
"ssid": v("ay", list((state.get("ssid") or "Wi-Fi").encode("utf-8"))), "mode": v("s", "infrastructure"),
|
||||
}
|
||||
elif state.get("transport") == "cellular":
|
||||
result["gsm"] = {} # Android owns the SIM/APN; no credentials are exported.
|
||||
return result
|
||||
|
||||
|
||||
def interface_info(interface, values):
|
||||
# Register properties on the actual objects as well as returning ObjectManager snapshots.
|
||||
# Steam/libnm also use Properties.Get/GetAll and introspect the wireless methods.
|
||||
props = "".join(f'<property name="{escape(key)}" type="{value.get_type_string()}" access="read"/>'
|
||||
for key, value in values.items())
|
||||
node = Gio.DBusNodeInfo.new_for_xml(f'<node><interface name="{interface}">{METHODS.get(interface, "")}{props}</interface></node>')
|
||||
return node.interfaces[0]
|
||||
|
||||
|
||||
class NetworkManager:
|
||||
def __init__(self, bus):
|
||||
self.bus = bus
|
||||
self.state = read_snapshot() or legacy_snapshot()
|
||||
self.objects = objects(self.state)
|
||||
self.registrations = {}
|
||||
for path in ("/org/freedesktop", ROOT):
|
||||
bus.register_object(path, interface_info(OBJECT_MANAGER, {}), self.call, None, None)
|
||||
self.register(self.objects)
|
||||
GLib.timeout_add_seconds(1, self.check)
|
||||
|
||||
def register(self, found):
|
||||
wanted = {(path, interface) for path, interfaces in found.items() for interface in interfaces}
|
||||
for key in self.registrations.keys() - wanted:
|
||||
self.bus.unregister_object(self.registrations.pop(key))
|
||||
for path, interface in wanted - self.registrations.keys():
|
||||
self.registrations[(path, interface)] = self.bus.register_object(
|
||||
path, interface_info(interface, found[path][interface]), self.call, self.get_property, None)
|
||||
|
||||
def get_property(self, bus, sender, path, interface, name):
|
||||
return self.objects.get(path, {}).get(interface, {}).get(name)
|
||||
self.ip = address()
|
||||
node = Gio.DBusNodeInfo.new_for_xml(INTROSPECTION)
|
||||
manager, root, profile, device = node.interfaces
|
||||
for path, interface in (("/org/freedesktop", manager), (ROOT, root), (PROFILE, profile), (DEVICE, device)):
|
||||
bus.register_object_with_closures2(path, interface, self.call, None, None)
|
||||
GLib.timeout_add_seconds(CHECK_SECONDS, self.check)
|
||||
|
||||
def call(self, bus, sender, path, interface, method, args, invocation):
|
||||
if method == "GetManagedObjects":
|
||||
invocation.return_value(v("(a{oa{sa{sv}}})", (self.objects,)))
|
||||
invocation.return_value(v("(a{oa{sa{sv}}})", (objects(self.ip),)))
|
||||
elif method == "GetPermissions":
|
||||
invocation.return_value(v("(a{ss})", ({},)))
|
||||
elif method == "CheckConnectivity":
|
||||
self.check()
|
||||
invocation.return_value(v("(u)", (connectivity(self.state),)))
|
||||
invocation.return_value(v("(u)", (NM_CONNECTIVITY_FULL if self.ip else NM_CONNECTIVITY_NONE,)))
|
||||
elif method == "GetSettings":
|
||||
invocation.return_value(v("(a{sa{sv}})", (settings(self.state),)))
|
||||
elif method == "ListConnections":
|
||||
invocation.return_value(v("(ao)", ([PROFILE],)))
|
||||
elif method in ("GetAccessPoints", "GetAllAccessPoints"):
|
||||
invocation.return_value(v("(ao)", (self.objects[path][NAME + ".Device.Wireless"]["AccessPoints"].unpack(),)))
|
||||
elif method == "RequestScan":
|
||||
if self.state.get("scanAllowed") is False:
|
||||
invocation.return_dbus_error(NAME + ".Device.NotAllowed", "Wi-Fi discovery requires Android Location permission and enabled Location services")
|
||||
return
|
||||
try:
|
||||
SCAN_REQUEST.write_text(str(time.monotonic_ns()))
|
||||
except OSError:
|
||||
invocation.return_dbus_error(NAME + ".Device.Failed", "Could not request an Android Wi-Fi scan")
|
||||
return
|
||||
self.check()
|
||||
invocation.return_value(v("()", ()))
|
||||
elif method in ("GetDevices", "GetAllDevices"):
|
||||
invocation.return_value(v("(ao)", (self.objects[ROOT][NAME]["Devices"].unpack(),)))
|
||||
# The name the client shows the connection under.
|
||||
invocation.return_value(v("(a{sa{sv}})", ({"connection": {
|
||||
"id": v("s", "Android"), "uuid": v("s", UUID), "type": v("s", "802-3-ethernet")}},)))
|
||||
else:
|
||||
invocation.return_dbus_error(NAME + ".NotSupported", "Manage this connection in Android settings")
|
||||
invocation.return_value(v("(ao)", ([DEVICE],)))
|
||||
|
||||
def check(self):
|
||||
state = read_snapshot()
|
||||
if state is None:
|
||||
return True # A transient read failure must not replace a known link with Ethernet.
|
||||
if state == self.state:
|
||||
return True
|
||||
before, after = self.objects, objects(state)
|
||||
old_state = self.state
|
||||
self.state, self.objects = state, after
|
||||
self.register(after)
|
||||
for path in before.keys() | after.keys():
|
||||
removed = before.get(path, {}).keys() - after.get(path, {}).keys()
|
||||
added = after.get(path, {}).keys() - before.get(path, {}).keys()
|
||||
if removed:
|
||||
self.announce("InterfacesRemoved", v("(oas)", (path, list(removed))))
|
||||
if added:
|
||||
self.announce("InterfacesAdded", v("(oa{sa{sv}})", (path, {i: after[path][i] for i in added})))
|
||||
for interface in before.get(path, {}).keys() & after.get(path, {}).keys():
|
||||
changed = {k: value for k, value in after[path][interface].items() if value != before[path][interface].get(k)}
|
||||
if changed:
|
||||
self.bus.emit_signal(None, path, PROPERTIES, "PropertiesChanged", v("(sa{sv}as)", (interface, changed, [])))
|
||||
wifi_device = ROOT + "/Devices/Wifi"
|
||||
wireless = NAME + ".Device.Wireless"
|
||||
old_aps = before.get(wifi_device, {}).get(wireless, {}).get("AccessPoints", v("ao", [])).unpack()
|
||||
new_aps = after.get(wifi_device, {}).get(wireless, {}).get("AccessPoints", v("ao", [])).unpack()
|
||||
if wifi_device in after:
|
||||
for path in set(old_aps) - set(new_aps):
|
||||
self.bus.emit_signal(None, wifi_device, wireless, "AccessPointRemoved", v("(o)", (path,)))
|
||||
for path in set(new_aps) - set(old_aps):
|
||||
self.bus.emit_signal(None, wifi_device, wireless, "AccessPointAdded", v("(o)", (path,)))
|
||||
was = before[ROOT][NAME]["State"]
|
||||
now = after[ROOT][NAME]["State"]
|
||||
if now != was:
|
||||
self.bus.emit_signal(None, ROOT, NAME, "StateChanged", v("(u)", (now.unpack(),)))
|
||||
device = device_path(state)
|
||||
if device in before:
|
||||
was = before[device][NAME + ".Device"]["State"]
|
||||
now = after[device][NAME + ".Device"]["State"]
|
||||
if now != was:
|
||||
self.bus.emit_signal(None, device, NAME + ".Device", "StateChanged", v("(uuu)", (now.unpack(), was.unpack(), 0)))
|
||||
if settings(old_state) != settings(state):
|
||||
self.bus.emit_signal(None, PROFILE, NAME + ".Settings.Connection", "Updated", v("()", ()))
|
||||
"""Tells the bus when Android gains or loses its route, as NetworkManager would."""
|
||||
ip = address()
|
||||
if (ip is None) != (self.ip is None) or (ip and ip != self.ip):
|
||||
before, after = objects(self.ip), objects(ip)
|
||||
self.ip = ip
|
||||
for path in before.keys() - after.keys():
|
||||
self.announce("InterfacesRemoved", path, v("(oas)", (path, list(before[path]))))
|
||||
for path in after.keys() - before.keys():
|
||||
self.announce("InterfacesAdded", path, v("(oa{sa{sv}})", (path, after[path])))
|
||||
for path in after.keys() & before.keys():
|
||||
for interface, values in after[path].items():
|
||||
self.bus.emit_signal(None, path, "org.freedesktop.DBus.Properties", "PropertiesChanged",
|
||||
v("(sa{sv}as)", (interface, values, [])))
|
||||
state = after[ROOT][NAME]["State"].unpack()
|
||||
device = after[DEVICE][NAME + ".Device"]["State"].unpack()
|
||||
was = before[DEVICE][NAME + ".Device"]["State"].unpack()
|
||||
self.bus.emit_signal(None, ROOT, NAME, "StateChanged", v("(u)", (state,)))
|
||||
self.bus.emit_signal(None, DEVICE, NAME + ".Device", "StateChanged", v("(uuu)", (device, was, 0)))
|
||||
return True
|
||||
|
||||
def announce(self, signal, body):
|
||||
for path in ("/org/freedesktop", ROOT):
|
||||
self.bus.emit_signal(None, path, OBJECT_MANAGER, signal, body)
|
||||
def announce(self, signal, path, body):
|
||||
self.bus.emit_signal(None, "/org/freedesktop", "org.freedesktop.DBus.ObjectManager", signal, body)
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
@@ -10,95 +10,32 @@
|
||||
# The client skips a "Run Process" block whose HasRunKey is already set, which is the same escape
|
||||
# WineUtils.seedVcRedistRegistryIfDllsPresent() takes for the app's own containers. The names and
|
||||
# versions come out of the install scripts rather than a list kept here, because Valve revises
|
||||
# them. Only the values a registry file does not already hold are added, so a file that is
|
||||
# already covered is not written at all.
|
||||
#
|
||||
# bannerlator-seed-redists STEAM_ROOT
|
||||
# Every template and prefix in both libraries. Run as the session starts.
|
||||
# bannerlator-seed-redists --launch TOOL_DIR
|
||||
# From the compatibility tool, before it hands a launch to Proton: the template of the
|
||||
# Proton in TOOL_DIR and the prefix of the title being launched, plus whichever of that
|
||||
# title's own install-script steps are redistributables.
|
||||
#
|
||||
# Seeding at launch is what closes the race. The client creates a new prefix from the template and
|
||||
# runs the title's install scripts in one go, so a template seeded on a timer was too late whenever
|
||||
# the client had just installed or updated that Proton.
|
||||
#
|
||||
# Whether a file is covered is read from the file itself rather than from a stamp beside it. A
|
||||
# stamp outlived the file it vouched for: the client replaces the template's system.reg when it
|
||||
# updates Proton and leaves a file it did not ship where it is, and a running wineserver writes its
|
||||
# own copy of a prefix's registry over values appended under it.
|
||||
# them; a prefix already carrying the same set is left alone.
|
||||
set -u
|
||||
steam_root=${1:?steam root}
|
||||
|
||||
launch=
|
||||
if [ "${1:-}" = --launch ]; then
|
||||
launch=1
|
||||
tool=${2:?tool dir}
|
||||
steam_root=${STEAM_COMPAT_CLIENT_INSTALL_PATH:-${XDG_DATA_HOME:-$HOME/.local/share}/Steam}
|
||||
else
|
||||
steam_root=${1:?steam root}
|
||||
fi
|
||||
libraries=("$steam_root" /mnt/droiddeck-sd)
|
||||
redist="$steam_root/steamapps/common/Steamworks Shared/_CommonRedist"
|
||||
|
||||
list=$(mktemp) || exit 0
|
||||
trap 'rm -f "$list"' EXIT
|
||||
|
||||
# "key<TAB>name" for every process an install script would run: the HasRunKey the client sets once
|
||||
# it has run it, and the name of its block, one level inside "Run Process". With only_redists set,
|
||||
# a block counts only when it is one of the common redistributables: a title's own script can also
|
||||
# hold its setup steps (a key, a launcher, a first-run tool), which have to run for real.
|
||||
entries() {
|
||||
local only_redists=$1
|
||||
shift
|
||||
[ "$#" -gt 0 ] || return 0
|
||||
awk -v only="$only_redists" '
|
||||
function flush() {
|
||||
if (name == "" || key == "")
|
||||
return
|
||||
if (only && index(tolower(key), "\\\\commonredist\\\\") == 0 && !redist)
|
||||
return
|
||||
# Every process an install script would run, as the registry key and value the client writes once
|
||||
# it has run it. Names sit one level inside "Run Process", the key they share a level further in.
|
||||
pairs=$(find "$redist" -name installscript.vdf -print0 2>/dev/null | sort -z | xargs -0 -r awk '
|
||||
FNR == 1 { depth = 0; name = ""; key = "" }
|
||||
/^[[:space:]]*\{/ { depth++; next }
|
||||
/^[[:space:]]*\}/ {
|
||||
if (depth == 3 && name != "" && key != "")
|
||||
printf "%s\t%s\n", key, name
|
||||
}
|
||||
FNR == 1 { depth = 0; section = ""; name = ""; key = ""; redist = 0 }
|
||||
/^[[:space:]]*\{/ { depth++; next }
|
||||
/^[[:space:]]*\}/ {
|
||||
if (depth == 3) {
|
||||
if (tolower(section) == "run process")
|
||||
flush()
|
||||
name = ""; key = ""; redist = 0
|
||||
}
|
||||
depth--
|
||||
next
|
||||
}
|
||||
{
|
||||
n = split($0, part, "\"")
|
||||
if (n < 3)
|
||||
next
|
||||
if (depth == 1) { section = part[2]; next }
|
||||
if (depth == 2) { name = part[2]; key = ""; redist = 0; next }
|
||||
if (depth == 3 && n >= 5) {
|
||||
field = tolower(part[2])
|
||||
if (field == "hasrunkey")
|
||||
key = part[4]
|
||||
else if (field ~ /^process/ && tolower(part[4]) ~ /vcredist|vc_redist|vcrun|directx|dxsetup|dotnet|ndp[0-9]|netfx|xna|physx|openal|oalinst/)
|
||||
redist = 1
|
||||
}
|
||||
}
|
||||
' "$@"
|
||||
}
|
||||
|
||||
# The install scripts every library shares.
|
||||
shared=()
|
||||
for library in "${libraries[@]}"; do
|
||||
redist="$library/steamapps/common/Steamworks Shared/_CommonRedist"
|
||||
[ -d "$redist" ] || continue
|
||||
while IFS= read -r -d '' f; do shared+=("$f"); done \
|
||||
< <(find "$redist" -iname 'installscript*.vdf' -print0 2>/dev/null | sort -z)
|
||||
done
|
||||
entries 0 "${shared[@]}" >"$list"
|
||||
depth--
|
||||
next
|
||||
}
|
||||
{
|
||||
n = split($0, part, "\"")
|
||||
if (n >= 5 && tolower(part[2]) == "hasrunkey") { key = part[4]; next }
|
||||
if (n >= 3 && depth == 2) { name = part[2]; key = "" }
|
||||
}
|
||||
')
|
||||
# The client downloads the scripts with the first game that wants them, which is too late for that
|
||||
# game; until then the set they held when this was written stands in. (WinNative's list.)
|
||||
[ -s "$list" ] || sed 's/^\([^ ]*\) /HKEY_LOCAL_MACHINE\\\\Software\\\\Valve\\\\Steam\\\\Apps\\\\CommonRedist\\\\\1\t/' >"$list" <<'KNOWN'
|
||||
[ -n "$pairs" ] || pairs=$(sed 's/^\([^ ]*\) /HKEY_LOCAL_MACHINE\\\\Software\\\\Valve\\\\Steam\\\\Apps\\\\CommonRedist\\\\\1\t/' <<'KNOWN'
|
||||
DirectX\\Jun2010 dxsetup
|
||||
.NET\\4.8 4.8
|
||||
vcredist\\2008 x86 SP1
|
||||
@@ -116,89 +53,42 @@ vcredist\\2019 x64 14.28.29334.0
|
||||
vcredist\\2022 x86 14.51.36247.0
|
||||
vcredist\\2022 x64 14.51.36247.0
|
||||
KNOWN
|
||||
)
|
||||
# The stamp is the set of names, taken before the block below dates its keys: stamped from the
|
||||
# dated block it never matched, and every prefix had the whole block appended again on every beat.
|
||||
stamp=$(printf '%s' "$pairs" | cksum)
|
||||
|
||||
# A title's own scripts, at launch, where the client says which title it is. They go into the
|
||||
# template as well: the title's prefix may not exist yet, and a key under another title's
|
||||
# HasRunKey is never read by anything else.
|
||||
if [ -n "$launch" ] && [ -d "${STEAM_COMPAT_INSTALL_PATH:-}" ]; then
|
||||
own=()
|
||||
while IFS= read -r -d '' f; do own+=("$f"); done \
|
||||
< <(find "$STEAM_COMPAT_INSTALL_PATH" -maxdepth 3 -iname 'installscript*.vdf' -print0 2>/dev/null | sort -z)
|
||||
entries 1 "${own[@]}" >>"$list"
|
||||
fi
|
||||
block=$(printf '%s\n' "$pairs" | awk -F'\t' -v now="$(date +%s)" '
|
||||
{
|
||||
path = $1
|
||||
sub(/^HKEY_LOCAL_MACHINE\\\\/, "", path)
|
||||
if (path == $1)
|
||||
next
|
||||
printf "\n[%s] %d\n\"%s\"=dword:00000001\n", path, now, $2
|
||||
# The client writes these from 32-bit steam.exe, so its own copy lands under Wow6432Node;
|
||||
# both spellings are seeded because the reader picks by its own word size.
|
||||
sub(/^Software\\\\/, "Software\\\\\\\\Wow6432Node\\\\\\\\", path)
|
||||
printf "\n[%s] %d\n\"%s\"=dword:00000001\n", path, now, $2
|
||||
}
|
||||
')
|
||||
[ -n "$block" ] || exit 0
|
||||
|
||||
# Appends to a registry file whichever of the listed values it lacks. The client writes these
|
||||
# from 32-bit steam.exe, so its own copy lands under Wow6432Node; both spellings are seeded
|
||||
# because the reader picks by its own word size. Only HKEY_LOCAL_MACHINE keys live in system.reg.
|
||||
seed() {
|
||||
local reg=$1 block dated
|
||||
[ -f "$reg" ] || return 0
|
||||
block=$(awk -F'\t' -v now="$(date +%s)" '
|
||||
function want(path, name, id) {
|
||||
id = tolower(path) SUBSEP name
|
||||
if (id in queued)
|
||||
return
|
||||
queued[id] = 1
|
||||
order[++count] = path
|
||||
value[count] = name
|
||||
}
|
||||
FNR == NR {
|
||||
path = $1
|
||||
if (tolower(substr(path, 1, 20)) != "hkey_local_machine\\\\")
|
||||
next
|
||||
path = substr(path, 21)
|
||||
want(path, $2)
|
||||
if (tolower(substr(path, 1, 10)) == "software\\\\" && tolower(substr(path, 11, 13)) != "wow6432node\\\\")
|
||||
want(substr(path, 1, 10) "Wow6432Node\\\\" substr(path, 11), $2)
|
||||
next
|
||||
}
|
||||
/^\[/ {
|
||||
current = substr($0, 2)
|
||||
sub(/\][^]]*$/, "", current)
|
||||
current = tolower(current)
|
||||
next
|
||||
}
|
||||
/^"/ {
|
||||
v = $0
|
||||
sub(/^"/, "", v)
|
||||
sub(/"=.*$/, "", v)
|
||||
have[current SUBSEP v] = 1
|
||||
}
|
||||
END {
|
||||
for (i = 1; i <= count; i++)
|
||||
if (!((tolower(order[i]) SUBSEP value[i]) in have))
|
||||
printf "\n[%s] %d\n\"%s\"=dword:00000001\n", order[i], now, value[i]
|
||||
}
|
||||
' "$list" "$reg")
|
||||
# The stamp an earlier seeder kept beside the file; nothing reads it now.
|
||||
rm -f "$(dirname "$reg")/.bannerlator-redists"
|
||||
[ -n "$block" ] || return 0
|
||||
# Its date is kept: Proton reads a changed one on a template as a new template and upgrades
|
||||
# every prefix made from the old. The client leaves some depot files read-only.
|
||||
dated=$(mktemp) || return 0
|
||||
# Proton builds a new prefix from its template, and the client runs the install scripts in that
|
||||
# prefix moments later, so the template carries the markers too. Its date is kept: Proton reads a
|
||||
# changed one as a new template and upgrades every prefix made from the old.
|
||||
for reg in "$steam_root"/steamapps/common/Proton*/files/share/default_pfx*/system.reg \
|
||||
"$steam_root"/compatibilitytools.d/*/files/share/default_pfx*/system.reg \
|
||||
"$steam_root"/steamapps/compatdata/*/pfx/system.reg \
|
||||
/mnt/droiddeck-sd/steamapps/compatdata/*/pfx/system.reg; do
|
||||
[ -f "$reg" ] || continue
|
||||
seeded=$(dirname "$reg")/.bannerlator-redists
|
||||
[ "$(cat "$seeded" 2>/dev/null)" = "$stamp" ] && continue
|
||||
dated=$(mktemp) || continue
|
||||
touch -r "$reg" "$dated"
|
||||
[ -w "$reg" ] || chmod u+w "$reg" 2>/dev/null
|
||||
if printf '%s\n' "$block" >>"$reg"; then
|
||||
printf '%s\n' "$stamp" >"$seeded"
|
||||
echo "== seeded redist markers into $reg"
|
||||
fi
|
||||
touch -r "$dated" "$reg"
|
||||
rm -f "$dated"
|
||||
}
|
||||
|
||||
if [ -n "$launch" ]; then
|
||||
for reg in "$tool"/files/share/default_pfx*/system.reg; do
|
||||
seed "$reg"
|
||||
done
|
||||
[ -n "${STEAM_COMPAT_DATA_PATH:-}" ] && seed "$STEAM_COMPAT_DATA_PATH/pfx/system.reg"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
for library in "${libraries[@]}"; do
|
||||
for reg in "$library"/steamapps/common/Proton*/files/share/default_pfx*/system.reg \
|
||||
"$library"/steamapps/compatdata/*/pfx/system.reg; do
|
||||
seed "$reg"
|
||||
done
|
||||
done
|
||||
for reg in "$steam_root"/compatibilitytools.d/*/files/share/default_pfx*/system.reg; do
|
||||
seed "$reg"
|
||||
done
|
||||
@@ -216,12 +216,6 @@ reap_orphans() {
|
||||
done
|
||||
}
|
||||
|
||||
# Gamescope's Wayland backend does not forward the outer clipboard into Xwayland.
|
||||
# This helper owns only Android text selections and exits with this guest session.
|
||||
if [ -n "${BL_ANDROID_CLIPBOARD:-}" ] && [ -x /usr/local/bin/droiddeck-clipboard ]; then
|
||||
/usr/local/bin/droiddeck-clipboard "$BL_ANDROID_CLIPBOARD" &
|
||||
fi
|
||||
|
||||
case $mode in
|
||||
desktop)
|
||||
exec pcmanfm
|
||||
@@ -252,10 +246,29 @@ case $mode in
|
||||
esac
|
||||
;;
|
||||
steam)
|
||||
step "checking the Steam client (first run downloads it, ~1-2 min with nothing on screen)"
|
||||
bannerlator-steam-install || exit $?
|
||||
step "Steam client ready"
|
||||
steam_root=$XDG_DATA_HOME/Steam
|
||||
# BL_STEAM_CLIENT_ARCH=x86_64 (the Steam page's Client setting): Valve's x86-64 client under FEX
|
||||
# instead of the arm64 one, in a home of its own (bannerlator-steam-x64), for what the arm64
|
||||
# client cannot do - VAC. Everything this session does around the client applies to it; what is
|
||||
# only for the arm64 client (its ARM64 Proton, the library mapping, the probes that load its
|
||||
# steamclient.so) is skipped.
|
||||
steam_x64=0
|
||||
[ "${BL_STEAM_CLIENT_ARCH:-}" = x86_64 ] && steam_x64=1
|
||||
if [ "$steam_x64" = 1 ]; then
|
||||
step "checking the x86-64 Steam client (FEX, experimental; the first run downloads ~2 GB)"
|
||||
bannerlator-steam-x64 --prepare || exit $?
|
||||
step "x86-64 Steam client ready"
|
||||
steam_root=${BL_X64_HOME:-$HOME/.droiddeck-x64}/.local/share/Steam
|
||||
steam_client=(bannerlator-steam-x64 --exec)
|
||||
# No x86 GPU driver: the interface renders in software.
|
||||
steam_cef=(-cef-disable-gpu)
|
||||
else
|
||||
step "checking the Steam client (first run downloads it, ~1-2 min with nothing on screen)"
|
||||
bannerlator-steam-install || exit $?
|
||||
step "Steam client ready"
|
||||
steam_root=$XDG_DATA_HOME/Steam
|
||||
steam_client=("$steam_root/steamrtarm64/steam")
|
||||
steam_cef=(-cef-force-gpu -cef-ozone-platform=x11 -cef-use-gl=angle -cef-use-angle=vulkan)
|
||||
fi
|
||||
# Register the card library (bound at /mnt/droiddeck-sd) with the client - internal storage is
|
||||
# its main library already - and the ARM64 Proton that lets it launch the Windows ones.
|
||||
# A request left in ~/.bl-proton-extra installs a third-party Proton before the client starts,
|
||||
@@ -263,7 +276,7 @@ case $mode in
|
||||
# arguments to bannerlator-proton-extra: "ge", "cachyos", "ge --tag GE-Proton11-7", or a URL.
|
||||
# Hundreds of megabytes each, so it is only ever done on request, and the line is dropped once
|
||||
# it has succeeded - a failed download stays and is retried next session.
|
||||
if [ -s "$HOME/.bl-proton-extra" ]; then
|
||||
if [ "$steam_x64" = 0 ] && [ -s "$HOME/.bl-proton-extra" ]; then
|
||||
_bl_left=$HOME/.bl-proton-extra.left
|
||||
: > "$_bl_left"
|
||||
while read -r _bl_extra || [ -n "$_bl_extra" ]; do
|
||||
@@ -307,7 +320,7 @@ case $mode in
|
||||
for ((_i = 0; _i < 720; _i++)); do
|
||||
for _d in /proc/[0-9]*; do
|
||||
IFS= read -r -d '' _c < "$_d/cmdline" 2>/dev/null || continue
|
||||
case $_c in *steamwebhelper*|*steamrtarm64/steam|*gamescope*) ;; *) continue ;; esac
|
||||
case $_c in *steamwebhelper*|*steamrtarm64/steam|*steamrt64/steam|*gamescope*) ;; *) continue ;; esac
|
||||
_t=("$_d"/task/*)
|
||||
_p=${_d#/proc/}
|
||||
[ "${_bl_pinned[$_p]:-}" = "${#_t[@]}" ] && continue
|
||||
@@ -319,6 +332,7 @@ case $mode in
|
||||
) &
|
||||
fi
|
||||
|
||||
if [ "$steam_x64" = 0 ]; then
|
||||
step "registering the app's game library with Steam"
|
||||
bannerlator-steam-library "$steam_root" || true
|
||||
step "setting up the ARM64 Proton compatibility tool"
|
||||
@@ -330,12 +344,12 @@ case $mode in
|
||||
bannerlator-steam-shortcuts "$steam_root" "$BL_ADDED_GAMES" || true
|
||||
fi
|
||||
# Steam runs a game's shared redistributables inside its prefix on first launch; marking
|
||||
# them as already run keeps those x86 installers from starting under emulation at all. This
|
||||
# pass covers the prefixes that already exist; new ones are covered at launch (see below).
|
||||
# them as already run keeps those x86 installers from starting under emulation at all.
|
||||
bannerlator-seed-redists "$steam_root" || true
|
||||
fi
|
||||
# The compatibility tool runs Valve's arm64 Proton, which the client fetches like any depot.
|
||||
# Asked for on the command line the first time, so a Windows title has it before it is needed.
|
||||
if [ ! -f "$steam_root/steamapps/appmanifest_4427310.acf" ]; then
|
||||
if [ "$steam_x64" = 0 ] && [ ! -f "$steam_root/steamapps/appmanifest_4427310.acf" ]; then
|
||||
step "asking the client to fetch the ARM64 Proton"
|
||||
set -- "$@" steam://install/4427310
|
||||
# Ported from Bannerlator (bannerlator-session, device-proven 2026-09-22). The client decides
|
||||
@@ -355,7 +369,7 @@ case $mode in
|
||||
bannerlator-steam-compat "$steam_root" >/dev/null 2>&1 || true
|
||||
step "compatibility layer installed: restarting the Steam client once"
|
||||
: > "$HOME/.bl-restart-once"
|
||||
"$steam_root/steamrtarm64/steam" -shutdown >/dev/null 2>&1 || true
|
||||
"${steam_client[@]}" -shutdown >/dev/null 2>&1 || true
|
||||
exit 0
|
||||
fi
|
||||
done
|
||||
@@ -390,7 +404,7 @@ case $mode in
|
||||
sleep 10
|
||||
[ -f "$_bl_acf" ] && exit 0
|
||||
step "signed in: asking the client again for the ARM64 Proton (try $_bl_try of 3)"
|
||||
"$steam_root/steamrtarm64/steam" steam://install/4427310 >/dev/null 2>&1 || true
|
||||
"${steam_client[@]}" steam://install/4427310 >/dev/null 2>&1 || true
|
||||
sleep 50
|
||||
done
|
||||
exit 0
|
||||
@@ -404,12 +418,18 @@ case $mode in
|
||||
# titles are installed: a title installed this session gets the client's own per-app Proton
|
||||
# choice, which it cannot start. Refresh the per-app entries every so often; the registrar is
|
||||
# idempotent, so a repeat costs nothing.
|
||||
# The seeder no longer rides this beat. A title launched for the first time has its prefix
|
||||
# created and its install scripts run moments apart, and a seeder on a timer lost that race
|
||||
# often enough: Need for Speed Payback sat on "Running install script" with vcredist_x86.exe
|
||||
# blocked in pipe_read, holding both ends of a pipe nobody would write to, while the client
|
||||
# waited for it to exit. The compatibility tool now seeds Proton's prefix template and the
|
||||
# title's prefix before every launch it hands to Proton, so a new prefix is born marked.
|
||||
# The seeder has the same problem and a worse consequence. It marks the shared redistributables
|
||||
# as already run in each prefix that exists, and a game's prefix is not created until the
|
||||
# client launches it - so a title played for the first time this session was never covered, and
|
||||
# its install scripts run for real. That is exactly the hang the seeder exists to prevent: Need
|
||||
# for Speed Payback sat on "Running install script" with vcredist_x86.exe blocked in pipe_read,
|
||||
# holding both ends of a pipe nobody would write to, while the client waited for it to exit.
|
||||
# Seeding again on the same beat covers a prefix the moment it appears.
|
||||
# The seeder runs on a shorter beat than the registrar because it is racing something. The
|
||||
# client creates a prefix when it launches a title and runs that title's install scripts
|
||||
# moments later, so the seeder has only that gap to mark the redistributables as already run.
|
||||
# It stamps each prefix it has covered and skips it thereafter, so the extra passes cost
|
||||
# almost nothing.
|
||||
# The drawer's "Stretch games to fill the screen" works live: the app writes its choice to
|
||||
# ~/.droiddeck-fill, and each change goes to gamescope as GAMESCOPE_FORCE_WINDOWS_FULLSCREEN on
|
||||
# the root window, which it watches. What gamescope was started with is where this begins.
|
||||
@@ -479,12 +499,14 @@ case $mode in
|
||||
esac
|
||||
done
|
||||
) &
|
||||
# The library beat. The compat registrar is a whole program under proot (a python start and a
|
||||
# parse of the client's config), and nearly every beat has nothing new for it. It runs when a
|
||||
# directory it reads from has changed since its last run - a new manifest, a new depot or
|
||||
# tool, the client rewriting config.vdf - which [ -nt ] answers without starting anything, and
|
||||
# once a minute regardless.
|
||||
(
|
||||
# The library beat. Both helpers are whole programs under proot (the compat one a python
|
||||
# start and a parse of the client's config), and nearly every beat has nothing new for them.
|
||||
# The seeder marks Proton's prefix template as well as the prefixes, so a new prefix is born
|
||||
# marked and every 15 s is soon enough for the rest. The compat pass runs when a directory it
|
||||
# reads from has changed since its last run - a new manifest, a new depot or tool, the client
|
||||
# rewriting config.vdf - which [ -nt ] answers without starting anything, and once a minute
|
||||
# regardless.
|
||||
[ "$steam_x64" = 0 ] && (
|
||||
beat=0
|
||||
compat_stamp=$HOME/.bl-compat-beat
|
||||
rm -f "$compat_stamp"
|
||||
@@ -497,13 +519,49 @@ case $mode in
|
||||
done
|
||||
return 1
|
||||
}
|
||||
# A title the compat pass maps while the client runs only takes that mapping at the client's
|
||||
# next start (see bannerlator-steam-compat): until then the client launches it its own way -
|
||||
# a Linux build stuck on "Downloading content (0%)" for a Steam Linux Runtime and FEX that
|
||||
# cannot run here (Left 4 Dead 2, 2026-10-02). So restart the client once for it, through the
|
||||
# same marker and -shutdown as the ARM64 Proton's restart: only when every new title has
|
||||
# finished installing (StateFlags 4) and no game is running; another download just resumes.
|
||||
# Once per title and three times per session at most, so a client that rewrites config.vdf
|
||||
# can never loop it.
|
||||
compat_pending=$HOME/.bl-compat-pending
|
||||
compat_restarted=$HOME/.bl-compat-restarted
|
||||
rm -f "$compat_pending"
|
||||
: > "$compat_restarted"
|
||||
compat_restarts=0
|
||||
compat_settled() {
|
||||
local app m flags
|
||||
while read -r app; do
|
||||
[ -n "$app" ] || continue
|
||||
m="$steam_root/steamapps/appmanifest_$app.acf"
|
||||
[ -f "$m" ] || m="/mnt/droiddeck-sd/steamapps/appmanifest_$app.acf"
|
||||
[ -f "$m" ] || return 1
|
||||
flags=$(sed -n 's/^[[:space:]]*"StateFlags"[[:space:]]*"\([0-9]*\)".*/\1/p' "$m" | head -n 1)
|
||||
[ "$flags" = 4 ] || return 1
|
||||
done < "$compat_pending"
|
||||
! pgrep -f 'reaper SteamLaunch' >/dev/null 2>&1
|
||||
}
|
||||
for ((_i = 0; _i < 720; _i++)); do
|
||||
nap 5
|
||||
beat=$((beat + 1))
|
||||
[ "$((beat % 3))" -eq 0 ] || continue
|
||||
bannerlator-seed-redists "$steam_root" >/dev/null 2>&1 || true
|
||||
if compat_due; then
|
||||
: > "$compat_stamp"
|
||||
bannerlator-steam-compat "$steam_root" >/dev/null 2>&1 || true
|
||||
bannerlator-steam-compat "$steam_root" --live >/dev/null 2>&1 || true
|
||||
fi
|
||||
if [ -s "$compat_pending" ] && compat_settled; then
|
||||
_bl_new=$(sort -u "$compat_pending" | grep -vxF -f "$compat_restarted" || true)
|
||||
rm -f "$compat_pending"
|
||||
[ -n "$_bl_new" ] && [ "$compat_restarts" -lt 3 ] || continue
|
||||
compat_restarts=$((compat_restarts + 1))
|
||||
printf '%s\n' $_bl_new >> "$compat_restarted"
|
||||
step "newly installed title(s) $(echo $_bl_new) set to the ARM64 Proton: restarting the Steam client once so it takes effect"
|
||||
: > "$HOME/.bl-restart-once"
|
||||
"${steam_client[@]}" -shutdown >/dev/null 2>&1 || true
|
||||
fi
|
||||
done
|
||||
) &
|
||||
@@ -576,7 +634,7 @@ BUSCONF
|
||||
# reaped with the client session. Native ARM64 runs directly. A legacy x86_64 asset is used
|
||||
# only when its recorded architecture and this guest's existing FEX installation agree.
|
||||
decky_loader=$HOME/homebrew/services/PluginLoader
|
||||
if [ -f "$HOME/.droiddeck-decky-enabled" ] && [ -x "$decky_loader" ]; then
|
||||
if [ "$steam_x64" = 0 ] && [ -f "$HOME/.droiddeck-decky-enabled" ] && [ -x "$decky_loader" ]; then
|
||||
decky_arch=$(cat "$HOME/homebrew/services/.droiddeck-decky-arch" 2>/dev/null || echo unknown)
|
||||
if [ "$decky_arch" = arm64 ] || { [ "$decky_arch" = x86_64 ] && [ -x /usr/bin/FEX ] && [ -n "${FEX_ROOTFS:-}" ]; }; then
|
||||
(
|
||||
@@ -621,7 +679,10 @@ BUSCONF
|
||||
# is an update that never installs: exit 42, a restart, for ever (Bannerlator 38996ea1). The
|
||||
# loop below puts package/beta back before every start. The SteamOS helpers the client calls
|
||||
# in this mode are staged as no-op stubs under /usr/bin.
|
||||
if [ "${BL_STEAMDECK:-0}" = 1 ] && [ "${BL_STEAM_UI:-}" != desktop ]; then
|
||||
# Not for the x86-64 client yet: with -steamos3 its SteamOS audio manager aborts on this runtime's
|
||||
# PulseAudio 13 server (pa_operation_get_state assertion) right after start. Big Picture without
|
||||
# the Deck flags runs.
|
||||
if [ "${BL_STEAMDECK:-0}" = 1 ] && [ "${BL_STEAM_UI:-}" != desktop ] && [ "$steam_x64" = 0 ]; then
|
||||
_bl_ui+=(-steamdeck -steamos3)
|
||||
# The QAM's Scaling Filter lists NVIDIA Image Scaling only when told gamescope has it (it does).
|
||||
export STEAM_GAMESCOPE_NIS_SUPPORTED=1
|
||||
@@ -631,7 +692,7 @@ BUSCONF
|
||||
# low-memory killer), and the client then finds .crash - opening its update UI on the spinner -
|
||||
# and the web helper's Singleton* locks in htmlcache, owned by a process that is gone, which can
|
||||
# leave the Gamepad UI blank. No client or helper is running at this point in a session.
|
||||
if ! pgrep -f 'steamwebhelper|steamrtarm64/steam' >/dev/null 2>&1; then
|
||||
if ! pgrep -f 'steamwebhelper|steamrtarm64/steam|steamrt64/steam' >/dev/null 2>&1; then
|
||||
_stale=""
|
||||
for _f in "$steam_root/.crash" "$steam_root/steam.pid" \
|
||||
"$steam_root/config/htmlcache/SingletonLock" "$steam_root/config/htmlcache/SingletonCookie" \
|
||||
@@ -650,14 +711,14 @@ BUSCONF
|
||||
# again on the branch it just wrote.
|
||||
steam_channel=${BL_STEAM_CHANNEL:-publicbeta}
|
||||
steam_beta=$steam_root/package/beta
|
||||
if [ -n "${BL_ADDED_GAMES:-}" ] && [ -f "$BL_ADDED_GAMES" ]; then
|
||||
if [ "$steam_x64" = 0 ] && [ -n "${BL_ADDED_GAMES:-}" ] && [ -f "$BL_ADDED_GAMES" ]; then
|
||||
bannerlator-steam-games watch "$steam_root" "$BL_ADDED_GAMES" &
|
||||
games_watcher=$!
|
||||
fi
|
||||
# Lossless Scaling (Steam app 993090): whether this account owns it, asked of the signed-in
|
||||
# client once a session until the answer is yes. From then on the app offers importing
|
||||
# Lossless.dll and passes BL_LOSSLESS_OWNED=1, so the question is never asked again.
|
||||
if [ "${BL_LOSSLESS_OWNED:-0}" != 1 ]; then
|
||||
if [ "$steam_x64" = 0 ] && [ "${BL_LOSSLESS_OWNED:-0}" != 1 ]; then
|
||||
(
|
||||
owned=$HOME/.config/droiddeck/lossless-owned
|
||||
for ((_i = 0; _i < 60; _i++)); do
|
||||
@@ -672,7 +733,7 @@ BUSCONF
|
||||
done
|
||||
) &
|
||||
fi
|
||||
echo "== steam args: ${_bl_ui[*]} -clientbeta $steam_channel -no-cef-sandbox -cef-force-gpu -cef-ozone-platform=x11 -cef-use-gl=angle -cef-use-angle=vulkan $*"
|
||||
echo "== steam args: ${_bl_ui[*]} -clientbeta $steam_channel -no-cef-sandbox ${steam_cef[*]} $*$([ "$steam_x64" = 1 ] && echo ' (x86-64 client under FEX)')"
|
||||
# An update that cannot install asks for a restart (rc=42) every time; the count is capped so a
|
||||
# session can never again loop in silence, which reads as a menu opening and closing by itself.
|
||||
steam_updates=0
|
||||
@@ -685,7 +746,7 @@ BUSCONF
|
||||
rm -f "$BL_LAUNCH_DIR/steam-stop"
|
||||
: > "$HOME/.bl-stop-requested"
|
||||
echo "== steam: the app asked for a clean exit"
|
||||
"$steam_root/steamrtarm64/steam" -shutdown >/dev/null 2>&1 || true
|
||||
"${steam_client[@]}" -shutdown >/dev/null 2>&1 || true
|
||||
exit 0
|
||||
fi
|
||||
nap 0.5
|
||||
@@ -700,13 +761,12 @@ BUSCONF
|
||||
echo "$steam_channel" > "$steam_beta"
|
||||
fi
|
||||
step "starting the Steam client${BL_STEAM_UI:+ ($BL_STEAM_UI UI)}"
|
||||
"$steam_root/steamrtarm64/steam" "${_bl_ui[@]}" -clientbeta "$steam_channel" \
|
||||
-no-cef-sandbox -cef-force-gpu -cef-ozone-platform=x11 \
|
||||
-cef-use-gl=angle -cef-use-angle=vulkan "$@"
|
||||
"${steam_client[@]}" "${_bl_ui[@]}" -clientbeta "$steam_channel" \
|
||||
-no-cef-sandbox "${steam_cef[@]}" "$@"
|
||||
rc=$?
|
||||
echo "== steam exited rc=$rc"
|
||||
collect_steam_logs
|
||||
if [ -n "${BL_ADDED_GAMES:-}" ] && [ -f "$BL_ADDED_GAMES" ]; then
|
||||
if [ "$steam_x64" = 0 ] && [ -n "${BL_ADDED_GAMES:-}" ] && [ -f "$BL_ADDED_GAMES" ]; then
|
||||
bannerlator-steam-shortcuts "$steam_root" "$BL_ADDED_GAMES" || true
|
||||
fi
|
||||
if [ -f "$HOME/.bl-stop-requested" ]; then
|
||||
@@ -717,6 +777,9 @@ BUSCONF
|
||||
# arguments, which were acted on. Not counted against the update cap.
|
||||
if [ -f "$HOME/.bl-restart-once" ]; then
|
||||
echo "== steam: restarting once so the new compatibility layer is in the client's lists"
|
||||
# The client wrote config.vdf back from its own memory as it exited, which can drop the
|
||||
# per-title entries written while it ran - the very ones this restart is for.
|
||||
bannerlator-steam-compat "$steam_root" >/dev/null 2>&1 || true
|
||||
set --
|
||||
continue
|
||||
fi
|
||||
|
||||
@@ -150,17 +150,6 @@ bl_game_cpus() {
|
||||
# the client, and a game inherits that: Wine then resolved gnutls, SDL, FFmpeg and the rest against
|
||||
# the client's private copies instead of the rootfs it was built for. Inside Steam's runtime
|
||||
# container that path never reaches Proton either. (WinNative's winnative-proton-launch.)
|
||||
BL_REDISTS_SETUP = """
|
||||
bl_redists() {
|
||||
# Steam's shared redistributables marked as already run in this Proton's prefix template and in
|
||||
# the title's prefix, before Proton is reached: the client creates a new prefix and runs the
|
||||
# title's install scripts in one go, and an x86 vcredist under FEX can hang that for good.
|
||||
# (bannerlator-seed-redists has the story.)
|
||||
[ -x /usr/local/bin/bannerlator-seed-redists ] || return 0
|
||||
/usr/local/bin/bannerlator-seed-redists --launch "$1" >&2 || true
|
||||
}
|
||||
"""
|
||||
|
||||
BL_LIBPATH_SETUP = """
|
||||
bl_libpath() {
|
||||
# A Proton built to prefer PipeWire (CachyOS's among the adopted ones) hung its audio thread
|
||||
@@ -200,6 +189,37 @@ bl_idtech3() {
|
||||
}
|
||||
"""
|
||||
|
||||
# VAC diagnostics (the app's Setup page): a Source-engine game says whether it started VAC-secure
|
||||
# only in its own console, and writes that console to <mod>/console.log only with -condebug. Armed
|
||||
# per session by the app (~/.droiddeck-vac-diagnostics); each launch is noted for its summary.
|
||||
# Nothing else about the launch changes - this only asks the game to keep its own log.
|
||||
BL_VACDIAG_SETUP = """
|
||||
bl_vacdiag() {
|
||||
[ -f "${HOME:-/root}/.droiddeck-vac-diagnostics" ] || return 0
|
||||
[ "${verb:-}" = waitforexitandrun ] || return 0
|
||||
local exe= a dir added=no app=${SteamAppId:-${STEAM_COMPAT_APP_ID:-0}}
|
||||
for a in "$@"; do case $a in *.exe|*.EXE) exe=$a ;; esac; done
|
||||
[ -n "$exe" ] || return 0
|
||||
dir=$(dirname "$exe")
|
||||
# Source: <game>/<mod>/gameinfo.txt beside the exe. Source 2: <game>/game/bin/win64/<exe> with
|
||||
# <game>/game/<mod>/gameinfo.gi.
|
||||
if ls "$dir"/*/gameinfo.txt >/dev/null 2>&1 || ls "$dir"/../../*/gameinfo.gi >/dev/null 2>&1; then
|
||||
case " $* " in
|
||||
*" -condebug "*) echo "bannerlator-proton: vac-diag: app $app already has -condebug" >&2 ;;
|
||||
*) BL_EXTRA_ARGS+=(-condebug); added=yes
|
||||
echo "bannerlator-proton: vac-diag: app $app is a Source title; launched with -condebug" >&2 ;;
|
||||
esac
|
||||
else
|
||||
added=not-source
|
||||
echo "bannerlator-proton: vac-diag: app $app is not a Source title; it keeps no console log to read" >&2
|
||||
fi
|
||||
case " $* " in
|
||||
*" -insecure "*) echo "bannerlator-proton: vac-diag: app $app has -insecure in its launch options - it can never be VAC-secure this way" >&2 ;;
|
||||
esac
|
||||
printf '%s\tapp %s\tcondebug %s\t%s\n' "$(date +%s)" "$app" "$added" "${exe##*/}" >> "${HOME:-/root}/.droiddeck-vac-launches"
|
||||
}
|
||||
"""
|
||||
|
||||
BL_DIRECTAUDIO_SETUP = """
|
||||
bl_directaudio() {
|
||||
base=$1
|
||||
@@ -279,10 +299,10 @@ for name in %s; do
|
||||
done
|
||||
if [ -n "$depot" ]; then
|
||||
bl_components "$depot"
|
||||
bl_redists "$depot"
|
||||
bl_directaudio "$depot"
|
||||
bl_game_cpus
|
||||
bl_idtech3 "$@"
|
||||
bl_vacdiag "$@"
|
||||
bl_libpath
|
||||
exec ${BL_TASKSET:-} /usr/local/bin/bannerlator-game-env "$depot/proton" "$verb" "$@" "${BL_EXTRA_ARGS[@]}"
|
||||
fi
|
||||
@@ -294,7 +314,7 @@ exit 1
|
||||
# something else.
|
||||
LAUNCHER_SH = LAUNCHER_SH.replace(
|
||||
"verb=$1; shift", "verb=$1; shift\n" + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP
|
||||
+ BL_COMPONENTS_SETUP + BL_REDISTS_SETUP + BL_LIBPATH_SETUP, 1)
|
||||
+ BL_VACDIAG_SETUP + BL_COMPONENTS_SETUP + BL_LIBPATH_SETUP, 1)
|
||||
|
||||
# A third-party Proton dropped into compatibilitytools.d - GE-Proton, proton-cachyos, anything of
|
||||
# that shape - is adopted rather than used as shipped, for the same two reasons Valve's ARM64 depot
|
||||
@@ -327,10 +347,10 @@ if [ -f "$fake" ]; then
|
||||
esac
|
||||
fi
|
||||
bl_components "$here"
|
||||
bl_redists "$here"
|
||||
bl_directaudio "$here"
|
||||
bl_game_cpus
|
||||
bl_idtech3 "$@"
|
||||
bl_vacdiag "$@"
|
||||
bl_libpath
|
||||
# Proton takes its base directory from dirname(sys.argv[0]) without resolving it, so it has to be
|
||||
# started from its own tree.
|
||||
@@ -516,7 +536,7 @@ def adopt_extras(tools):
|
||||
body = (EXTRA_WRAPPER_SH % entry_point).replace(
|
||||
'here=$(dirname "$0")',
|
||||
'here=$(dirname "$0")\n' + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP
|
||||
+ BL_COMPONENTS_SETUP + BL_REDISTS_SETUP + BL_LIBPATH_SETUP, 1)
|
||||
+ BL_VACDIAG_SETUP + BL_COMPONENTS_SETUP + BL_LIBPATH_SETUP, 1)
|
||||
write_changed(wrapper, body, 0o755)
|
||||
write_changed(manifest, EXTRA_MANIFEST_VDF)
|
||||
write_changed(compat_vdf, EXTRA_COMPAT_TOOL_VDF % (name, entry))
|
||||
@@ -559,7 +579,8 @@ def installed_apps(steam_root):
|
||||
|
||||
|
||||
def register_default(config_path, apps=(), name=None, protect=()):
|
||||
"""Writes the mapping. `name` defaults to our own tool; the first-run seed passes Valve's."""
|
||||
"""Writes the mapping. `name` defaults to our own tool; the first-run seed passes Valve's.
|
||||
Returns the app ids given a per-app entry by this call."""
|
||||
tool = name or TOOL
|
||||
# Tool names the user may deliberately have chosen (see adopt_extras); never repointed.
|
||||
keep = {n.lower() for n in protect}
|
||||
@@ -568,7 +589,8 @@ def register_default(config_path, apps=(), name=None, protect=()):
|
||||
tokens = tokenize(original)
|
||||
steam = find_block(tokens, ["InstallConfigStore", "Software", "Valve", "Steam"])
|
||||
if steam is None:
|
||||
return
|
||||
return []
|
||||
added = []
|
||||
mapping = find_block(tokens[steam + 1:], ["CompatToolMapping"])
|
||||
entry = ['"0"', "{", '"name"', '"%s"' % tool, '"config"', '""', '"priority"', '"75"', "}"]
|
||||
if mapping is None:
|
||||
@@ -592,10 +614,12 @@ def register_default(config_path, apps=(), name=None, protect=()):
|
||||
continue
|
||||
tokens[mapping + 1:mapping + 1] = [
|
||||
'"%s"' % app, "{", '"name"', '"%s"' % tool, '"config"', '""', '"priority"', '"250"', "}"]
|
||||
added.append(app)
|
||||
# Nothing to change is the usual case on the session's beat: the client's own file is left alone.
|
||||
text = serialize(tokens)
|
||||
if text != serialize(tokenize(original)):
|
||||
write_changed(config_path, text)
|
||||
return added
|
||||
|
||||
|
||||
def depot_build(depot):
|
||||
@@ -646,8 +670,18 @@ def main():
|
||||
config = os.path.join(steam_root, "config", "config.vdf")
|
||||
if os.path.isfile(config):
|
||||
apps = installed_apps(steam_root)
|
||||
register_default(config, apps, protect=extras)
|
||||
added = register_default(config, apps, protect=extras)
|
||||
print("bannerlator-steam-compat: default and %d installed title(s) set to %s" % (len(apps), TOOL))
|
||||
# The client reads config.vdf once, as it starts, and keeps its own decisions in memory for
|
||||
# the rest of its run: a title installed while it runs gets the client's own pick (native
|
||||
# for a Linux build, which then waits for Steam Linux Runtime + FEX it can never run here;
|
||||
# proton-stable for a Windows one), and the entry written here only counts from the next
|
||||
# start. Run from the session's beat (--live), the new entries are noted for the session,
|
||||
# which restarts the client once the install has settled (bannerlator-session).
|
||||
if added and "--live" in sys.argv[2:]:
|
||||
with open(os.path.join(os.path.expanduser("~"), ".bl-compat-pending"), "a") as f:
|
||||
f.write("".join("%s\n" % a for a in added))
|
||||
print("bannerlator-steam-compat: mapped while the client runs: %s" % " ".join(added))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
+406
@@ -0,0 +1,406 @@
|
||||
#!/bin/bash
|
||||
# EXPERIMENT, opt-in: Valve's x86-64 Linux Steam client under FEX, beside the default arm64 one.
|
||||
# bannerlator-steam-x64 [steam:// URL or client arguments] run it (the desktop menu entry)
|
||||
# bannerlator-steam-x64 --prepare install and set up, then exit
|
||||
# bannerlator-steam-x64 --exec ARGS... run the client binary with ARGS in
|
||||
# its environment (bannerlator-session
|
||||
# with BL_STEAM_CLIENT_ARCH=x86_64)
|
||||
#
|
||||
# Why: the arm64 Linux client never runs VAC (TF2, L4D2: "Connection Blocked ... VAC secured
|
||||
# server", no VAC line in any client log) - VAC modules are x86 code. The x86-64 client under FEX
|
||||
# has a module it can run, the way SteamLite does in Wine. This runs Valve's client unchanged.
|
||||
#
|
||||
# Everything lives in its own home ($X64_HOME): the x86 client gets its own ~/.steam links, its
|
||||
# own login, config and library, and never touches the arm64 client's. Only one client runs at a
|
||||
# time (same account), so the arm64 one is shut down first.
|
||||
#
|
||||
# First run downloads FEX (this repo's release), FEX's Ubuntu 24.04 x86 rootfs (~525 MB, unpacked
|
||||
# ~1.5 GB) and the x86 client (~600 MB). Log: $X64_HOME/steam-x64.log.
|
||||
set -eu
|
||||
FEX_TAG=fex-2609-r2
|
||||
FEX_SHA256=5c5fb5bfc2a78879fc4488d2b4cdea0d40d9268d9551bdc37c123e36da21b9c7
|
||||
FEX_URL=https://github.com/Droid-Deck/DroidDeck/releases/download/$FEX_TAG/fex.tzst
|
||||
ROOTFS_URL=https://rootfs.fex-emu.gg/Ubuntu_24_04/2026-08-11/Ubuntu_24_04.sqsh
|
||||
CDN=https://client-update.fastly.steamstatic.com
|
||||
MANIFEST=steam_client_publicbeta_ubuntu12
|
||||
|
||||
REAL_HOME=${HOME:-/root}
|
||||
X64_HOME=${BL_X64_HOME:-$REAL_HOME/.droiddeck-x64}
|
||||
ROOTFS=$X64_HOME/rootfs
|
||||
STEAM_X64=$X64_HOME/.local/share/Steam
|
||||
ARM_STEAM=${XDG_DATA_HOME:-$REAL_HOME/.local/share}/Steam
|
||||
LOG=$X64_HOME/steam-x64.log
|
||||
mkdir -p "$X64_HOME"
|
||||
step() { echo "== $(date -u +%H:%M:%S) $*" | tee -a "$LOG"; }
|
||||
|
||||
x64_prepare() {
|
||||
# --- FEX -------------------------------------------------------------------------------------
|
||||
if [ ! -x /usr/local/bin/FEX ] || [ "$(cat /usr/local/share/fex-emu/.droiddeck-tag 2>/dev/null)" != "$FEX_TAG" ]; then
|
||||
step "downloading FEX ($FEX_TAG)"
|
||||
tmp=$(mktemp -d)
|
||||
curl -fL --progress-bar "$FEX_URL" -o "$tmp/fex.tzst"
|
||||
if [ "$FEX_SHA256" != PENDING ]; then echo "$FEX_SHA256 $tmp/fex.tzst" | sha256sum -c --quiet; fi
|
||||
zstd -dc "$tmp/fex.tzst" | tar -C / -x
|
||||
rm -rf "$tmp"
|
||||
mkdir -p /usr/local/share/fex-emu && echo "$FEX_TAG" > /usr/local/share/fex-emu/.droiddeck-tag
|
||||
fi
|
||||
step "FEX ready ($FEX_TAG)"
|
||||
|
||||
# --- x86 rootfs --------------------------------------------------------------------------------
|
||||
if [ ! -f "$ROOTFS/.droiddeck-complete" ]; then
|
||||
step "downloading FEX's Ubuntu 24.04 x86 rootfs"
|
||||
# Resumes a part-done download; a finished one answers 416, which is not a failure here.
|
||||
curl -fL --progress-bar -C - "$ROOTFS_URL" -o "$X64_HOME/rootfs.sqsh" || {
|
||||
rc=$?
|
||||
[ "$rc" = 22 ] && [ -s "$X64_HOME/rootfs.sqsh" ] || { step "rootfs download failed (curl $rc)"; exit 1; }
|
||||
}
|
||||
step "unpacking the rootfs"
|
||||
rm -rf "$ROOTFS"
|
||||
# Ownership and xattrs mean nothing in this guest; device nodes cannot be made here and are not
|
||||
# needed (FEX passes /dev through from the host).
|
||||
/usr/local/bin/unsquashfs -no-xattrs -no-progress -ignore-errors -d "$ROOTFS" "$X64_HOME/rootfs.sqsh" >>"$LOG" 2>&1 || true
|
||||
[ -x "$ROOTFS/usr/bin/bash" ] || { step "rootfs unpack failed (no usr/bin/bash); see $LOG"; exit 1; }
|
||||
rm -f "$X64_HOME/rootfs.sqsh"
|
||||
touch "$ROOTFS/.droiddeck-complete"
|
||||
fi
|
||||
# The rootfs's own ld.so.preload: a path missing from the rootfs falls through to the guest, whose
|
||||
# list names the session's arm64 preloads. In it, the session shim built for x86-64 (System V IPC,
|
||||
# which Android kernels lack: the client's tier0 gives up on start without its semaphore).
|
||||
# Each architecture's copy under the rootfs's own multiarch folder, named once through glibc's $LIB
|
||||
# (lib/x86_64-linux-gnu or lib/i386-linux-gnu): every process loads the one built for it, so the
|
||||
# 32-bit games get them too. A missing copy is skipped by the loader.
|
||||
: > "$ROOTFS/etc/ld.so.preload"
|
||||
for lib in libblsession libfakeinput; do
|
||||
have=0
|
||||
for arch in x86_64 i386; do
|
||||
[ -f "/usr/local/lib/$arch-linux-gnu/$lib.so" ] || continue
|
||||
mkdir -p "$ROOTFS/usr/local/lib/$arch-linux-gnu"
|
||||
cp -f "/usr/local/lib/$arch-linux-gnu/$lib.so" "$ROOTFS/usr/local/lib/$arch-linux-gnu/$lib.so"
|
||||
have=1
|
||||
done
|
||||
if [ "$have" = 1 ]; then echo "/usr/local/\$LIB/$lib.so" >> "$ROOTFS/etc/ld.so.preload"
|
||||
else step "warning: no x86 build of $lib (/usr/local/lib/x86_64-linux-gnu/$lib.so)"; fi
|
||||
done
|
||||
rm -f "$ROOTFS/usr/local/lib/libblsession-x86_64.so" "$ROOTFS/usr/local/lib/libfakeinput-x86_64.so"
|
||||
# --- the x86-64 client -------------------------------------------------------------------------
|
||||
if [ ! -x "$STEAM_X64/steamrt64/steam" ] || [ ! -f "$STEAM_X64/package/droiddeck-installed" ]; then
|
||||
step "downloading the x86-64 Steam client ($MANIFEST)"
|
||||
work=$(mktemp -d)
|
||||
curl -fsSL "$CDN/$MANIFEST" -o "$work/manifest"
|
||||
version=$(awk -F'"' '$2 == "version" { print $4; exit }' "$work/manifest")
|
||||
# Same parsing as bannerlator-steam-install: every component block's plain zip and sha256.
|
||||
awk -F'"' '
|
||||
/^\t"/ && NF >= 3 && $4 == "" { block = $2 }
|
||||
$2 == "file" { file[block] = $4 }
|
||||
$2 == "sha2" { sha[block] = $4 }
|
||||
END { for (b in file) if (b ~ /_all$/ || b ~ /_ubuntu12$/) print b, file[b], sha[b] }
|
||||
' "$work/manifest" | sort > "$work/parts"
|
||||
[ -s "$work/parts" ] || { step "no client components in $MANIFEST"; exit 1; }
|
||||
mkdir -p "$STEAM_X64/package"
|
||||
total=$(grep -c . "$work/parts")
|
||||
i=0
|
||||
while read -r block file sum; do
|
||||
i=$((i + 1))
|
||||
step "client: $block ($i/$total)"
|
||||
curl -fsSL "$CDN/$file" -o "$work/$file"
|
||||
echo "$sum $work/$file" | sha256sum -c --quiet
|
||||
unzip -qo "$work/$file" -d "$STEAM_X64"
|
||||
rm -f "$work/$file"
|
||||
done < "$work/parts"
|
||||
rm -rf "$work"
|
||||
echo publicbeta > "$STEAM_X64/package/beta"
|
||||
echo "$version" > "$STEAM_X64/package/droiddeck-installed"
|
||||
chmod +x "$STEAM_X64/steam.sh" "$STEAM_X64/steamrt64/steam" "$STEAM_X64/ubuntu12_32/steam" 2>/dev/null || true
|
||||
fi
|
||||
# Its own library: the arm64 client's Windows installs are not what this client runs (it would
|
||||
# switch a shared install to the Linux build and the arm64 client would download it again).
|
||||
[ -L "$STEAM_X64/steamapps" ] && rm -f "$STEAM_X64/steamapps"
|
||||
mkdir -p "$STEAM_X64/steamapps"
|
||||
# They still enumerate /dev/dri, find the session's KGSL node there, and spin on it (x86 Turnip
|
||||
# "failed to query kernel driver version", KMS dumb-buffer ioctls in a loop) - the webhelper never
|
||||
# got a browser up. FEX looks in the rootfs first: an empty /dev/dri there hides the node.
|
||||
mkdir -p "$ROOTFS/dev/dri"
|
||||
# What steam.sh sets up before it runs the client, for the x86 tree.
|
||||
mkdir -p "$X64_HOME/.steam"
|
||||
ln -sfn "$STEAM_X64" "$X64_HOME/.steam/root"
|
||||
ln -sfn "$STEAM_X64" "$X64_HOME/.steam/steam"
|
||||
ln -sfn "$STEAM_X64/ubuntu12_32" "$X64_HOME/.steam/bin32"
|
||||
ln -sfn "$STEAM_X64/ubuntu12_64" "$X64_HOME/.steam/bin64"
|
||||
ln -sfn "$STEAM_X64/linux32" "$X64_HOME/.steam/sdk32"
|
||||
ln -sfn "$STEAM_X64/linux64" "$X64_HOME/.steam/sdk64"
|
||||
# Unlike the arm64 client, this one carries pressure-vessel (steamrt64/pv-runtime) and refuses to
|
||||
# start when steam-runtime-check-requirements' bwrap probe cannot make a user namespace, which no
|
||||
# Android app can. proot is the container here, as it is for the arm64 client, which has no such
|
||||
# probe. STEAM_RUNTIME_STEAMRT names the runtime the client takes the probe from: Valve's own,
|
||||
# linked file by file, with only the probe answering that the requirements are met.
|
||||
srt_real=$STEAM_X64/steamrt64/pv-runtime/steam-runtime-steamrt
|
||||
srt_shim=$X64_HOME/steamrt-shim
|
||||
if [ -d "$srt_real" ]; then
|
||||
rm -rf "$srt_shim"
|
||||
mkdir -p "$srt_shim/bin"
|
||||
for e in "$srt_real"/* "$srt_real"/.[!.]*; do
|
||||
[ -e "$e" ] || continue
|
||||
[ "$(basename "$e")" = bin ] || ln -s "$e" "$srt_shim/$(basename "$e")"
|
||||
done
|
||||
for e in "$srt_real"/bin/*; do ln -s "$e" "$srt_shim/bin/$(basename "$e")"; done
|
||||
rm -f "$srt_shim/bin/steam-runtime-check-requirements"
|
||||
printf '#!/bin/sh
|
||||
# bannerlator-steam-x64: proot stands in for user namespaces here.
|
||||
exit 0
|
||||
' > "$srt_shim/bin/steam-runtime-check-requirements"
|
||||
chmod 755 "$srt_shim/bin/steam-runtime-check-requirements"
|
||||
fi
|
||||
# The libraries the SteamRT container would give the client and the rootfs lacks (GTK 2 for
|
||||
# steamui.so, ...): Valve's own platform runtime files, for what the rootfs does not have.
|
||||
# They ship without their soname links (pressure-vessel makes those when it builds the container),
|
||||
# so they are linked into a folder of our own and the rootfs's ldconfig adds the soname links there.
|
||||
srt_libs=$X64_HOME/steamrt-libs
|
||||
rm -rf "$srt_libs"
|
||||
mkdir -p "$srt_libs"
|
||||
for d in "$STEAM_X64"/steamrt64/pv-runtime/steam-runtime-steamrt/steamrt3c_platform_*/files/lib/x86_64-linux-gnu \
|
||||
"$STEAM_X64"/steamrt64/pv-runtime/steam-runtime-steamrt/steamrt3c_platform_*/files/usr/lib/x86_64-linux-gnu; do
|
||||
[ -d "$d" ] || continue
|
||||
for f in "$d"/*.so*; do [ -e "$srt_libs/$(basename "$f")" ] || ln -s "$f" "$srt_libs/"; done
|
||||
done
|
||||
FEX_ROOTFS=$ROOTFS /usr/local/bin/FEX "$ROOTFS/usr/sbin/ldconfig.real" -n "$srt_libs" >>"$LOG" 2>&1 || step "ldconfig on $srt_libs failed"
|
||||
# LD_LIBRARY_PATH beats the system folders whatever its order, so only what the rootfs lacks stays:
|
||||
# the platform's own (older) glibc and the rest must not shadow the rootfs's.
|
||||
for f in "$srt_libs"/*; do
|
||||
n=$(basename "$f")
|
||||
if [ -e "$ROOTFS/usr/lib/x86_64-linux-gnu/$n" ] || [ -e "$ROOTFS/lib/x86_64-linux-gnu/$n" ]; then rm -f "$f"; fi
|
||||
done
|
||||
# Native Linux games: Steam runs them in the Steam Linux Runtime container (pressure-vessel), which
|
||||
# needs bwrap - no user namespaces here, as for the client. "DroidDeck direct" runs them with
|
||||
# Valve's scout library runtime instead, directly under FEX; the titles below are mapped to it.
|
||||
tool=$STEAM_X64/compatibilitytools.d/droiddeck-direct
|
||||
mkdir -p "$tool"
|
||||
cat > "$tool/compatibilitytool.vdf" <<'VDF'
|
||||
"compatibilitytools"
|
||||
{
|
||||
"compat_tools"
|
||||
{
|
||||
"droiddeck-direct"
|
||||
{
|
||||
"install_path" "."
|
||||
"display_name" "DroidDeck direct (no container)"
|
||||
"from_oslist" "linux"
|
||||
"to_oslist" "linux"
|
||||
}
|
||||
}
|
||||
}
|
||||
VDF
|
||||
cat > "$tool/toolmanifest.vdf" <<'VDF'
|
||||
"manifest"
|
||||
{
|
||||
"version" "2"
|
||||
"commandline" "/run %verb%"
|
||||
}
|
||||
VDF
|
||||
cat > "$tool/run" <<'RUN'
|
||||
#!/bin/sh
|
||||
# DroidDeck direct: a native Linux game with Valve's scout library runtime, no container.
|
||||
verb=$1; shift
|
||||
rt=$HOME/.local/share/Steam/ubuntu12_32/steam-runtime.old
|
||||
[ -x "$rt/run.sh" ] || rt=$HOME/.local/share/Steam/ubuntu12_32/steam-runtime
|
||||
case $verb in
|
||||
run|waitforexitandrun) exec "$rt/run.sh" "$@" ;;
|
||||
*) exec "$@" ;;
|
||||
esac
|
||||
RUN
|
||||
chmod 755 "$tool/run"
|
||||
# The mapping lives in config.vdf, which the client rewrites from memory as it exits: written
|
||||
# here, while no x86 client runs.
|
||||
if [ -f "$STEAM_X64/config/config.vdf" ] && ! pgrep -f 'steamrt64/steam( |$)' >/dev/null 2>&1; then
|
||||
python3 - "$STEAM_X64/config/config.vdf" ${BL_X64_DIRECT_APPS:-550} <<'PY' || step "could not map titles to DroidDeck direct"
|
||||
import re, sys
|
||||
path, apps = sys.argv[1], sys.argv[2:]
|
||||
s = open(path, encoding="utf-8", errors="surrogateescape").read()
|
||||
|
||||
def block(text, key):
|
||||
"""(start of the key, index after its opening brace, index of its closing brace) or None."""
|
||||
m = re.search(r'"%s"\s*\{' % re.escape(key), text)
|
||||
if not m:
|
||||
return None
|
||||
depth, k = 1, m.end()
|
||||
while depth:
|
||||
c = text[k]
|
||||
depth += c == "{"
|
||||
depth -= c == "}"
|
||||
k += 1
|
||||
return m.start(), m.end(), k - 1
|
||||
|
||||
if not block(s, "CompatToolMapping"):
|
||||
st = block(s, "Steam")
|
||||
if not st:
|
||||
sys.exit("no Steam section")
|
||||
s = s[:st[1]] + '\n\t\t\t\t"CompatToolMapping"\n\t\t\t\t{\n\t\t\t\t}' + s[st[1]:]
|
||||
for app in apps:
|
||||
_, open_, close = block(s, "CompatToolMapping")
|
||||
inner = s[open_:close]
|
||||
old = block(inner, app)
|
||||
if old:
|
||||
inner = inner[:old[0]] + inner[old[2] + 1:]
|
||||
entry = ('\n\t\t\t\t\t"%s"\n\t\t\t\t\t{\n\t\t\t\t\t\t"name"\t\t"droiddeck-direct"\n'
|
||||
'\t\t\t\t\t\t"config"\t\t""\n\t\t\t\t\t\t"priority"\t\t"250"\n\t\t\t\t\t}' % app)
|
||||
s = s[:open_] + entry + inner + s[close:]
|
||||
open(path, "w", encoding="utf-8", errors="surrogateescape").write(s)
|
||||
PY
|
||||
fi
|
||||
# A FEX process takes its rootfs from FEXServer, not from its own environment, and a server
|
||||
# started earlier without FEX_ROOTFS (any FEX run in this guest) answers with no rootfs at all:
|
||||
# every x86 library lookup then falls through to the arm64 guest. Stop it while no x86 client
|
||||
# runs, so the next FEX starts one with this rootfs.
|
||||
if ! pgrep -f 'steamrt64/steam( |$)' >/dev/null 2>&1; then
|
||||
FEX_ROOTFS=$ROOTFS /usr/local/bin/FEXServer -k >/dev/null 2>&1 || true
|
||||
fi
|
||||
}
|
||||
|
||||
# The environment the client and everything it starts run in.
|
||||
x64_env() {
|
||||
# The arm64 session's library paths and preloads are aarch64 and mean nothing to x86 processes.
|
||||
unset LD_LIBRARY_PATH LD_PRELOAD STEAM_RUNTIME STEAM_RUNTIME_PREFER_HOST_LIBRARIES
|
||||
# So are the desktop's GPU settings: zink over the arm64 Turnip ICD. x86 Mesa has no driver for
|
||||
# this GPU, so software: llvmpipe for GL (the client's own window needs GLX), and the rootfs's
|
||||
# own Vulkan ICDs (lavapipe) found by the x86 loader instead of the arm64 one.
|
||||
unset GALLIUM_DRIVER MESA_LOADER_DRIVER_OVERRIDE VK_ICD_FILENAMES VK_DRIVER_FILES LIBGL_KOPPER_DRI2 \
|
||||
ZINK_DEBUG ZINK_DESCRIPTORS TU_DEBUG MESA_NO_ERROR
|
||||
export LIBGL_ALWAYS_SOFTWARE=1 GALLIUM_DRIVER=llvmpipe
|
||||
# The X server hands out that node too (DRI3 open), and Mesa's software path then tries KMS dumb
|
||||
# buffers on it in a loop: present through plain X instead.
|
||||
export LIBGL_DRI3_DISABLE=1
|
||||
# The proot fast path (libblfastpath, preloaded into every guest process, FEX included) stands down
|
||||
# by itself when FEX is about to run a 32-bit program (it broke FEX's 32-bit mode: SIGILL at start);
|
||||
# 64-bit ones keep it. BL_X64_FP_OFF=1 turns it off for everything, as before.
|
||||
[ "${BL_X64_FP_OFF:-0}" = 1 ] && export PROOT_FP_OFF=1
|
||||
# FEX tuning: the app's default preset for games (core/FexPreset.kt PERFORMANCE_TSO, WinNative's
|
||||
# default) - FEX's own defaults keep half-barrier TSO and full-precision x87, which cost every x86
|
||||
# program time. A value already in the environment wins.
|
||||
export FEX_TSOENABLED=${FEX_TSOENABLED:-1} FEX_VECTORTSOENABLED=${FEX_VECTORTSOENABLED:-0} \
|
||||
FEX_MEMCPYSETTSOENABLED=${FEX_MEMCPYSETTSOENABLED:-0} FEX_HALFBARRIERTSOENABLED=${FEX_HALFBARRIERTSOENABLED:-0} \
|
||||
FEX_X87REDUCEDPRECISION=${FEX_X87REDUCEDPRECISION:-1} FEX_MULTIBLOCK=${FEX_MULTIBLOCK:-1}
|
||||
export HOME=$X64_HOME
|
||||
# The session points these at the arm64 client's home; this client has its own.
|
||||
export XDG_DATA_HOME=$X64_HOME/.local/share XDG_CONFIG_HOME=$X64_HOME/.config XDG_CACHE_HOME=$X64_HOME/.cache
|
||||
export FEX_ROOTFS=$ROOTFS
|
||||
export STEAM_EXTRA_COMPAT_TOOLS_PATHS=
|
||||
# Valve's 64-bit SteamRT3 client (steamrt64/steam), the x86 twin of the arm64 one, started the way
|
||||
# the session starts that one (bannerlator-session): directly, STEAM_RUNTIME=1, its own library
|
||||
# folders first. Through steam.sh it would first run steam-runtime-check-requirements, whose
|
||||
# bwrap probe needs user namespaces - proot has none. Software rendering: no x86 GPU driver.
|
||||
export STEAM_RUNTIME=1
|
||||
[ -d "$X64_HOME/steamrt-shim" ] && export STEAM_RUNTIME_STEAMRT=$X64_HOME/steamrt-shim
|
||||
# The client wraps the processes it starts with steam-runtime-launch-client, which the SteamRT
|
||||
# container has on its PATH ("Failed to wrap process item with launch client" without it).
|
||||
[ -d "$X64_HOME/steamrt-shim/bin" ] && export PATH=$X64_HOME/steamrt-shim/bin:$PATH
|
||||
export LD_LIBRARY_PATH=$STEAM_X64/steamrt64:$STEAM_X64/steamrt64/panorama:$X64_HOME/steamrt-libs
|
||||
# After an update the client re-executes itself inside the SteamRT container through
|
||||
# pressure-vessel-wrap, which needs bwrap. The FEX rootfs with the client's own steamrt64 libraries
|
||||
# is that container here; the client's recursion guard says it is already inside one.
|
||||
export STEAM_STEAMRT_RECURSION_GUARD=1
|
||||
# proot is a tracer, so tier0 believes a debugger is attached and breaks into it with int3 on the
|
||||
# first failed assertion: the web helper died of SIGTRAP a second after every start. The session
|
||||
# shim hides the tracer from the x86 web helper too (preload/tracer.c).
|
||||
export BL_WEBHELPER_HIDE_TRACER=1
|
||||
}
|
||||
|
||||
# The client binary under FEX, for the session: the starting arguments, or -shutdown / a steam://
|
||||
# URL handed to the running instance.
|
||||
x64_exec() {
|
||||
x64_env
|
||||
cd "$STEAM_X64"
|
||||
exec "${BL_FEX:-/usr/local/bin/FEX}" "$STEAM_X64/steamrt64/steam" "$@"
|
||||
}
|
||||
|
||||
case "${1:-}" in
|
||||
--prepare) x64_prepare; exit 0 ;;
|
||||
--exec) shift; x64_exec "$@" ;;
|
||||
esac
|
||||
|
||||
# --- standalone (the desktop menu entry) ------------------------------------------------------
|
||||
# --- one client at a time ----------------------------------------------------------------------
|
||||
if pgrep -f 'steamrtarm64/steam( |$)' >/dev/null 2>&1; then
|
||||
step "shutting down the arm64 client first"
|
||||
"$ARM_STEAM/steamrtarm64/steam" -shutdown >/dev/null 2>&1 || true
|
||||
for _ in $(seq 1 30); do pgrep -f 'steamrtarm64/steam( |$)' >/dev/null 2>&1 || break; sleep 1; done
|
||||
fi
|
||||
x64_prepare
|
||||
step "FEX, rootfs and client ready"
|
||||
# BL_FEXSERVER_LOG: a FEXServer of our own in the foreground, logging there - every FEX process that
|
||||
# logs to "server" (FEX_OUTPUTLOG, or an AppConfig) then has its lines tagged with its pid.
|
||||
if [ -n "${BL_FEXSERVER_LOG:-}" ]; then
|
||||
FEX_ROOTFS=$ROOTFS "$(dirname "${BL_FEX:-/usr/local/bin/FEX}")/FEXServer" -f -p 600 >"$BL_FEXSERVER_LOG" 2>&1 &
|
||||
sleep 1
|
||||
fi
|
||||
# --- what bannerlator-session gives the arm64 client ---------------------------------------
|
||||
# The client's connection header and Settings > Internet come from NetworkManager on the SYSTEM
|
||||
# bus; without them it shows no connection while downloads run. Same bus config and stand-in as the
|
||||
# session, started here when no system bus is up (a desktop has none), stopped with the client.
|
||||
x64_bus= x64_nm= x64_pin=
|
||||
x64_cleanup() {
|
||||
[ -n "$x64_pin" ] && kill "$x64_pin" 2>/dev/null
|
||||
[ -n "$x64_nm" ] && kill "$x64_nm" 2>/dev/null
|
||||
[ -n "$x64_bus" ] && kill "$x64_bus" 2>/dev/null
|
||||
return 0
|
||||
}
|
||||
trap x64_cleanup EXIT
|
||||
if ! pgrep -f 'dbus-daemon --config-file=/usr/local/share/bannerlator/system-bus.conf' >/dev/null 2>&1 \
|
||||
&& command -v dbus-daemon >/dev/null 2>&1 && command -v bannerlator-netmanager >/dev/null 2>&1; then
|
||||
mkdir -p /run/dbus /usr/local/share/bannerlator
|
||||
cat > /usr/local/share/bannerlator/system-bus.conf <<'BUSCONF'
|
||||
<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN"
|
||||
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
|
||||
<busconfig>
|
||||
<type>system</type>
|
||||
<listen>unix:path=/run/dbus/system_bus_socket</listen>
|
||||
<auth>EXTERNAL</auth>
|
||||
<policy context="default">
|
||||
<allow user="*"/>
|
||||
<allow own="*"/>
|
||||
<allow send_destination="*"/>
|
||||
<allow receive_sender="*"/>
|
||||
</policy>
|
||||
</busconfig>
|
||||
BUSCONF
|
||||
rm -f /run/dbus/system_bus_socket
|
||||
dbus-daemon --config-file=/usr/local/share/bannerlator/system-bus.conf --nofork --nopidfile &
|
||||
x64_bus=$!
|
||||
for _ in $(seq 1 50); do [ -S /run/dbus/system_bus_socket ] && break; sleep 0.1; done
|
||||
if [ -S /run/dbus/system_bus_socket ]; then
|
||||
bannerlator-netmanager &
|
||||
x64_nm=$!
|
||||
step "network: system bus up, NetworkManager stand-in running"
|
||||
else
|
||||
step "network: the system bus did not come up; the client will show no connection"
|
||||
fi
|
||||
fi
|
||||
# What a killed client leaves behind: .crash opens the update UI on its spinner, stale htmlcache
|
||||
# Singleton* locks can leave the UI blank (as in bannerlator-session).
|
||||
if ! pgrep -f 'steamrt64/steam( |$)' >/dev/null 2>&1; then
|
||||
for f in "$STEAM_X64/.crash" "$STEAM_X64/steam.pid" "$STEAM_X64/config/htmlcache/SingletonLock" \
|
||||
"$STEAM_X64/config/htmlcache/SingletonCookie" "$STEAM_X64/config/htmlcache/SingletonSocket"; do
|
||||
{ [ -e "$f" ] || [ -L "$f" ]; } && rm -f "$f"
|
||||
done
|
||||
fi
|
||||
# The session's CPU set for the client (BL_CLIENT_CPUS): Steam pins itself and its web helper to a
|
||||
# few cores; re-pin every 5 s as the session does for the arm64 client.
|
||||
if [ -n "${BL_CLIENT_CPUS:-}" ] && command -v taskset >/dev/null 2>&1; then
|
||||
(
|
||||
while sleep 5; do
|
||||
for pid in $(ps -A -o PID,ARGS | awk '$2=="FEX" && ($3 ~ /steamrt64\/steam$/ || $3 ~ /steamwebhelper$/) {print $1}'); do
|
||||
taskset -a -p -c "$BL_CLIENT_CPUS" "$pid" >/dev/null 2>&1
|
||||
done
|
||||
done
|
||||
) &
|
||||
x64_pin=$!
|
||||
fi
|
||||
# BL_FEX: another FEX build for the client and everything it starts (a DEBUG_STRACE one, say).
|
||||
# Restart on request (42, as steam.sh does), at most a few times.
|
||||
for attempt in 1 2 3 4 5; do
|
||||
# The branch on disk must match -clientbeta before every start, or the client loops on rc=42.
|
||||
echo publicbeta > "$STEAM_X64/package/beta"
|
||||
step "starting the x86-64 SteamRT3 client under FEX (attempt $attempt): $*"
|
||||
rc=0
|
||||
( x64_exec -clientbeta publicbeta -no-cef-sandbox -cef-disable-gpu "$@" ) >>"$LOG" 2>&1 || rc=$?
|
||||
step "client exited rc=$rc"
|
||||
[ "$rc" = 42 ] || break
|
||||
done
|
||||
@@ -483,12 +483,12 @@ static FILE *synthesize(const char *table) {
|
||||
}
|
||||
|
||||
/* tracer.c */
|
||||
int bl_status_without_tracer(const char *path, int flags) __attribute__((visibility("hidden")));
|
||||
int bl_status_without_tracer(const char *path, int flags, const void *caller) __attribute__((visibility("hidden")));
|
||||
|
||||
static FILE *open_stream(const char *symbol, const char *path, const char *mode) {
|
||||
typedef FILE *(*fopen_fn)(const char *, const char *);
|
||||
int status = mode && mode[0] == 'r' && !strchr(mode, '+')
|
||||
? bl_status_without_tracer(path, O_RDONLY | O_CLOEXEC) : -1;
|
||||
? bl_status_without_tracer(path, O_RDONLY | O_CLOEXEC, NULL) : -1;
|
||||
if (status >= 0) {
|
||||
FILE *copy = fdopen(status, "r");
|
||||
if (copy == NULL) close(status);
|
||||
|
||||
@@ -33,7 +33,7 @@
|
||||
#include <string.h>
|
||||
#include <sys/types.h>
|
||||
|
||||
int bl_status_without_tracer(const char *path, int flags) __attribute__((visibility("hidden")));
|
||||
int bl_status_without_tracer(const char *path, int flags, const void *caller) __attribute__((visibility("hidden")));
|
||||
int bl_writable_retry(int dirfd, const char *path, int flags) __attribute__((visibility("hidden")));
|
||||
|
||||
static int retry_without_noatime(int fd, int flags) {
|
||||
@@ -60,7 +60,7 @@ int open(const char *path, int flags, ...) {
|
||||
errno = EACCES;
|
||||
return -1;
|
||||
}
|
||||
if ((fd = bl_status_without_tracer(path, flags)) >= 0) return fd;
|
||||
if ((fd = bl_status_without_tracer(path, flags, __builtin_return_address(0))) >= 0) return fd;
|
||||
if (real_open == NULL) real_open = dlsym(RTLD_NEXT, "open");
|
||||
if (real_open == NULL) {
|
||||
errno = ENOSYS;
|
||||
@@ -86,7 +86,7 @@ int openat(int dirfd, const char *path, int flags, ...) {
|
||||
errno = EACCES;
|
||||
return -1;
|
||||
}
|
||||
if ((fd = bl_status_without_tracer(path, flags)) >= 0) return fd;
|
||||
if ((fd = bl_status_without_tracer(path, flags, __builtin_return_address(0))) >= 0) return fd;
|
||||
if (real_openat == NULL) real_openat = dlsym(RTLD_NEXT, "openat");
|
||||
if (real_openat == NULL) {
|
||||
errno = ENOSYS;
|
||||
|
||||
@@ -57,7 +57,8 @@ static int enabled(void) {
|
||||
if (cached >= 0) return cached;
|
||||
off = getenv("BL_NO_PATH_CACHE");
|
||||
cached = strcmp(program_invocation_short_name, "steam") == 0 &&
|
||||
strstr(program_invocation_name, "steamrtarm64") != NULL &&
|
||||
(strstr(program_invocation_name, "steamrtarm64") != NULL ||
|
||||
strstr(program_invocation_name, "steamrt64") != NULL) &&
|
||||
!(off != NULL && off[0] == '1');
|
||||
return cached;
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@
|
||||
#include <unistd.h>
|
||||
|
||||
static int in_steam_dirs(const char *path) {
|
||||
return path != NULL && (strstr(path, "/Steam/steamrtarm64/") != NULL
|
||||
return path != NULL && (strstr(path, "/Steam/steamrtarm64/") != NULL || strstr(path, "/Steam/steamrt64/") != NULL
|
||||
|| strstr(path, "/Steam/ubuntu12_64/") != NULL || strstr(path, "/Steam/linuxarm64/") != NULL);
|
||||
}
|
||||
|
||||
|
||||
@@ -18,8 +18,10 @@
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include <ctype.h>
|
||||
#include <dlfcn.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/syscall.h>
|
||||
@@ -47,9 +49,20 @@ static int is_status_path(const char *path) {
|
||||
}
|
||||
|
||||
/* Chromium stands its hang watchdogs down when it sees a tracer, and the client's web helper does
|
||||
* not come up within their patience here: it is left reading the truth. */
|
||||
static int is_web_helper(void) {
|
||||
return strcmp(program_invocation_short_name, "steamwebhelper") == 0;
|
||||
* not come up within their patience here: it is left reading the truth. Chromium also traps when a
|
||||
* status descriptor it opened turns out not to be procfs. The x86-64 client under FEX
|
||||
* (BL_WEBHELPER_HIDE_TRACER=1, set by bannerlator-steam-x64) still needs its tier0 told: tier0
|
||||
* reads the status, sees the tracer, and breaks into the supposed debugger with int3 on the first
|
||||
* failed assertion - the web helper died of SIGTRAP a second after it started. There tier0's own
|
||||
* opens (by caller) get the copy and Chromium's the real file. */
|
||||
static int is_web_helper(const void *caller) {
|
||||
if (strcmp(program_invocation_short_name, "steamwebhelper") != 0) return 0;
|
||||
const char *hide = getenv("BL_WEBHELPER_HIDE_TRACER");
|
||||
Dl_info info;
|
||||
if (hide && hide[0] == '1' && caller && dladdr(caller, &info) && info.dli_fname
|
||||
&& strstr(info.dli_fname, "libtier0_s.so"))
|
||||
return 0;
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int write_all(int fd, const char *data, size_t len) {
|
||||
@@ -65,13 +78,13 @@ static int write_all(int fd, const char *data, size_t len) {
|
||||
|
||||
/* The descriptor to hand back for a read-only open of a status file, or -1 with errno untouched
|
||||
* when the path is something else or the copy cannot be made, and the real open should run. */
|
||||
__attribute__((visibility("hidden"))) int bl_status_without_tracer(const char *path, int flags) {
|
||||
__attribute__((visibility("hidden"))) int bl_status_without_tracer(const char *path, int flags, const void *caller) {
|
||||
char text[STATUS_MAX];
|
||||
size_t len = 0;
|
||||
int saved = errno;
|
||||
int out = -1;
|
||||
|
||||
if ((flags & O_ACCMODE) != O_RDONLY || !is_status_path(path) || is_web_helper()) return -1;
|
||||
if ((flags & O_ACCMODE) != O_RDONLY || !is_status_path(path) || is_web_helper(caller)) return -1;
|
||||
int in = (int)syscall(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC);
|
||||
if (in < 0) goto done;
|
||||
for (;;) {
|
||||
|
||||
@@ -137,10 +137,37 @@ static int traced_by_match(const char *key) {
|
||||
return found;
|
||||
}
|
||||
|
||||
/*
|
||||
* FEX (the x86-64 Steam client's translator) loads this library into its own process. Its 32-bit
|
||||
* mode does not survive that: every i386 program died with SIGILL, FEX's fatal trap, at start. So
|
||||
* in FEX, only stay on when the program it is about to run (argv[1]) is a 64-bit ELF; a 32-bit
|
||||
* one, a script, or anything that cannot be read gets the real calls, as before.
|
||||
*/
|
||||
static int fex_runs_32bit(void) {
|
||||
if (strcmp(program_invocation_short_name, "FEX") != 0 && strcmp(program_invocation_short_name, "FEXInterpreter") != 0)
|
||||
return 0;
|
||||
char args[PATH_MAX + 64];
|
||||
long fd = syscall(SYS_openat, AT_FDCWD, "/proc/self/cmdline", O_RDONLY | O_CLOEXEC);
|
||||
if (fd < 0) return 1;
|
||||
long n = syscall(SYS_read, fd, args, sizeof args - 1);
|
||||
syscall(SYS_close, fd);
|
||||
if (n <= 0) return 1;
|
||||
args[n] = 0;
|
||||
const char *prog = args + strlen(args) + 1;
|
||||
if (prog >= args + n || !*prog) return 1;
|
||||
unsigned char ident[5];
|
||||
fd = syscall(SYS_openat, AT_FDCWD, prog, O_RDONLY | O_CLOEXEC);
|
||||
if (fd < 0) return 1;
|
||||
n = syscall(SYS_read, fd, ident, sizeof ident);
|
||||
syscall(SYS_close, fd);
|
||||
return !(n == 5 && memcmp(ident, "\x7f" "ELF", 4) == 0 && ident[4] == 2 /* ELFCLASS64 */);
|
||||
}
|
||||
|
||||
static void fp_init(void) {
|
||||
const char *r = getenv("PROOT_FP_ROOT"), *b = getenv("PROOT_FP_BINDS"), *t = getenv("PROOT_FP_TTL_MS");
|
||||
const char *key = getenv("PROOT_FP_KEY");
|
||||
if (!r || !*r || !key || !*key || getenv("PROOT_FP_OFF")) return;
|
||||
if (fex_runs_32bit()) return;
|
||||
void *p = mmap((void *)FP_STUB_ADDR, FP_STUB_SIZE, PROT_READ | PROT_WRITE,
|
||||
MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED_NOREPLACE, -1, 0);
|
||||
if (p != (void *)FP_STUB_ADDR) {
|
||||
|
||||
@@ -1,284 +0,0 @@
|
||||
"""NetworkManager contract and real D-Bus handovers (requires python3-gi and dbus).
|
||||
|
||||
Run on Linux: dbus-run-session -- python3 -m unittest discover -s tools/tests -p test_netmanager.py
|
||||
"""
|
||||
import importlib.machinery
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
|
||||
try:
|
||||
import gi
|
||||
gi.require_version("Gio", "2.0")
|
||||
from gi.repository import Gio, GLib
|
||||
except ImportError:
|
||||
Gio = GLib = None
|
||||
|
||||
SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/bannerlator-netmanager"
|
||||
if Gio:
|
||||
loader = importlib.machinery.SourceFileLoader("netmanager", str(SCRIPT))
|
||||
spec = importlib.util.spec_from_loader(loader.name, loader)
|
||||
nm = importlib.util.module_from_spec(spec)
|
||||
loader.exec_module(nm)
|
||||
|
||||
WIFI = {
|
||||
"connected": True, "transport": "wifi", "interface": "wlan0", "wifiEnabled": True,
|
||||
"validated": True, "captivePortal": False, "metered": False,
|
||||
"ssid": "Test \"Wi-Fi\" ☃", "strength": 73, "frequency": 5180, "bitrate": 866000,
|
||||
"addresses": [{"address": "192.0.2.2", "prefix": 24}, {"address": "2001:db8::2", "prefix": 64}],
|
||||
"gateways": ["192.0.2.1", "2001:db8::1"], "dns": ["192.0.2.1", "2001:db8::1"],
|
||||
}
|
||||
CELLULAR = {
|
||||
"connected": True, "transport": "cellular", "interface": "rmnet_data0", "wifiEnabled": True,
|
||||
"validated": True, "metered": True,
|
||||
"addresses": [{"address": "2001:db8:1::2", "prefix": 64}],
|
||||
"gateways": ["2001:db8:1::1"], "dns": ["2001:db8:1::1"],
|
||||
}
|
||||
OFFLINE = {"connected": False, "transport": "none", "wifiEnabled": True, "metered": None}
|
||||
|
||||
|
||||
@unittest.skipUnless(Gio, "requires PyGObject")
|
||||
class NetworkObjectsTest(unittest.TestCase):
|
||||
def test_wifi_graph(self):
|
||||
found = nm.objects(WIFI)
|
||||
manager = found[nm.ROOT][nm.NAME]
|
||||
device = found[nm.device_path(WIFI)]
|
||||
self.assertEqual(manager["PrimaryConnectionType"].unpack(), "802-11-wireless")
|
||||
self.assertTrue(manager["WirelessEnabled"].unpack())
|
||||
self.assertEqual(device[nm.NAME + ".Device"]["DeviceType"].unpack(), 2)
|
||||
self.assertEqual(device[nm.NAME + ".Device.Wireless"]["ActiveAccessPoint"].unpack(), nm.AP)
|
||||
ap = found[nm.AP][nm.NAME + ".AccessPoint"]
|
||||
self.assertEqual(bytes(ap["Ssid"].unpack()).decode(), WIFI["ssid"])
|
||||
self.assertEqual(ap["Strength"].unpack(), 73)
|
||||
self.assertEqual(manager["Metered"].unpack(), 2)
|
||||
for interfaces in found.values():
|
||||
for values in interfaces.values():
|
||||
for value in values.values():
|
||||
if value.get_type_string() == "o" and value.unpack() != "/":
|
||||
self.assertIn(value.unpack(), found)
|
||||
|
||||
def test_cellular_ipv6_only(self):
|
||||
found = nm.objects(CELLULAR)
|
||||
manager = found[nm.ROOT][nm.NAME]
|
||||
device = found[nm.device_path(CELLULAR)]
|
||||
active = found[nm.ACTIVE][nm.NAME + ".Connection.Active"]
|
||||
self.assertEqual(manager["PrimaryConnectionType"].unpack(), "gsm")
|
||||
self.assertEqual(manager["Metered"].unpack(), 1)
|
||||
self.assertEqual(device[nm.NAME + ".Device"]["DeviceType"].unpack(), 8)
|
||||
self.assertIn(nm.NAME + ".Device.Modem", device)
|
||||
self.assertNotIn(nm.AP, found)
|
||||
self.assertNotIn(nm.IP4, found)
|
||||
self.assertEqual(active["Ip4Config"].unpack(), "/")
|
||||
self.assertEqual(active["Ip6Config"].unpack(), nm.IP6)
|
||||
self.assertTrue(active["Default6"].unpack())
|
||||
self.assertFalse(active["Default"].unpack())
|
||||
self.assertNotEqual(nm.device_path(WIFI), nm.device_path(CELLULAR))
|
||||
|
||||
def test_offline_and_captive_portal(self):
|
||||
offline = nm.objects(OFFLINE)
|
||||
self.assertEqual(offline[nm.ROOT][nm.NAME]["State"].unpack(), 20)
|
||||
self.assertEqual(offline[nm.ROOT][nm.NAME]["ActiveConnections"].unpack(), [])
|
||||
self.assertNotIn(nm.AP, offline)
|
||||
self.assertEqual(nm.connectivity(dict(WIFI, validated=False, captivePortal=True)), 2)
|
||||
self.assertEqual(nm.connectivity(dict(WIFI, validated=False, captivePortal=False)), 3)
|
||||
self.assertEqual(nm.metered(OFFLINE), 0)
|
||||
|
||||
def test_redacted_name_and_wired_vpn(self):
|
||||
redacted = dict(WIFI)
|
||||
del redacted["ssid"]
|
||||
self.assertEqual(nm.connection_name(redacted), "Wi-Fi")
|
||||
self.assertEqual(bytes(nm.settings(redacted)["802-11-wireless"]["ssid"].unpack()), b"Wi-Fi")
|
||||
for transport, kind, device_type in (("ethernet", "802-3-ethernet", 1), ("vpn", "tun", 16)):
|
||||
state = dict(WIFI, transport=transport)
|
||||
found = nm.objects(state)
|
||||
self.assertEqual(found[nm.ROOT][nm.NAME]["PrimaryConnectionType"].unpack(), kind)
|
||||
self.assertEqual(found[nm.device_path(state)][nm.NAME + ".Device"]["DeviceType"].unpack(), device_type)
|
||||
self.assertNotIn(nm.AP, found)
|
||||
|
||||
def test_named_current_and_nearby_access_points(self):
|
||||
current = {"ssid": "Current Wi-Fi", "bssid": "00:11:22:33:44:55", "strength": 75,
|
||||
"capabilities": "[WPA2-PSK-CCMP][RSN-PSK+SAE-CCMP][ESS]"}
|
||||
other = {"ssid": "Other Wi-Fi", "bssid": "00:11:22:33:44:66", "strength": 42,
|
||||
"capabilities": "[ESS]"}
|
||||
state = dict(WIFI, ssid=current["ssid"], bssid=current["bssid"], accessPoints=[current, other], lastScan=123456)
|
||||
found = nm.objects(state)
|
||||
wireless = found[nm.device_path(state)][nm.NAME + ".Device.Wireless"]
|
||||
self.assertEqual(wireless["ActiveAccessPoint"].unpack(), nm.ap_path(current["bssid"]))
|
||||
self.assertEqual(set(wireless["AccessPoints"].unpack()), {nm.ap_path(current["bssid"]), nm.ap_path(other["bssid"])})
|
||||
self.assertEqual(wireless["LastScan"].unpack(), 123456)
|
||||
secured = found[nm.ap_path(current["bssid"])][nm.NAME + ".AccessPoint"]
|
||||
self.assertEqual(secured["Flags"].unpack(), 1)
|
||||
self.assertTrue(secured["RsnFlags"].unpack() & 0x100)
|
||||
self.assertTrue(secured["RsnFlags"].unpack() & 0x400)
|
||||
self.assertEqual(found[nm.ap_path(other["bssid"])][nm.NAME + ".AccessPoint"]["Flags"].unpack(), 0)
|
||||
# Keep nearby-network discovery while a cellular connection provides the default route.
|
||||
cellular = nm.objects(dict(CELLULAR, accessPoints=[other]))
|
||||
self.assertIn(nm.ap_path(other["bssid"]), cellular)
|
||||
self.assertEqual(cellular[nm.ROOT + "/Devices/Wifi"][nm.NAME + ".Device.Wireless"]["ActiveAccessPoint"].unpack(), "/")
|
||||
|
||||
|
||||
@unittest.skipUnless(Gio and os.environ.get("DBUS_SESSION_BUS_ADDRESS"), "requires dbus-run-session and PyGObject")
|
||||
class NetworkBusTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.snapshot = Path(self.temp.name) / "network.json"
|
||||
self.write(WIFI)
|
||||
self.bus = Gio.bus_get_sync(Gio.BusType.SESSION, None)
|
||||
env = dict(os.environ, DBUS_SYSTEM_BUS_ADDRESS=os.environ["DBUS_SESSION_BUS_ADDRESS"])
|
||||
# Use the production service and only redirect its input file for the fixture.
|
||||
launch = "import runpy,sys; from pathlib import Path; n=runpy.run_path(sys.argv[1]); g=n['main'].__globals__; g['SNAPSHOT']=Path(sys.argv[2]); g['SCAN_REQUEST']=Path(sys.argv[2]).with_suffix('.request'); n['main']()"
|
||||
self.process = subprocess.Popen([sys.executable, "-c", launch, str(SCRIPT), str(self.snapshot)], env=env,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
self.await_type("802-11-wireless")
|
||||
|
||||
def tearDown(self):
|
||||
self.process.terminate()
|
||||
_, stderr = self.process.communicate(timeout=5)
|
||||
self.temp.cleanup()
|
||||
self.assertEqual(stderr, b"", stderr.decode())
|
||||
|
||||
def write(self, state):
|
||||
staged = self.snapshot.with_suffix(".staged")
|
||||
staged.write_text(json.dumps(state))
|
||||
staged.replace(self.snapshot)
|
||||
|
||||
def call(self, path, interface, method, parameters=None):
|
||||
return self.bus.call_sync(nm.NAME, path, interface, method, parameters, None,
|
||||
Gio.DBusCallFlags.NONE, 1000, None).unpack()
|
||||
|
||||
def prop(self, path, interface, name):
|
||||
return self.call(path, nm.PROPERTIES, "Get", GLib.Variant("(ss)", (interface, name)))[0]
|
||||
|
||||
def await_type(self, expected):
|
||||
deadline = time.monotonic() + 6
|
||||
while time.monotonic() < deadline:
|
||||
if self.process.poll() is not None:
|
||||
self.fail(self.process.communicate()[1].decode())
|
||||
try:
|
||||
if self.prop(nm.ROOT, nm.NAME, "PrimaryConnectionType") == expected:
|
||||
return
|
||||
except GLib.Error:
|
||||
pass
|
||||
time.sleep(0.05)
|
||||
self.fail("network type did not change to " + expected)
|
||||
|
||||
def test_direct_properties_methods_and_handover(self):
|
||||
signals = []
|
||||
subscription = self.bus.signal_subscribe(
|
||||
nm.NAME, None, None, None, None, Gio.DBusSignalFlags.NONE,
|
||||
lambda bus, sender, path, interface, member, args: signals.append((path, interface, member, args.unpack())))
|
||||
self.addCleanup(self.bus.signal_unsubscribe, subscription)
|
||||
wifi_path = nm.device_path(WIFI)
|
||||
self.assertEqual(self.prop(wifi_path, nm.NAME + ".Device", "DeviceType"), 2)
|
||||
self.assertEqual(self.prop(nm.AP, nm.NAME + ".AccessPoint", "Strength"), 73)
|
||||
self.assertEqual(self.call(wifi_path, nm.NAME + ".Device.Wireless", "GetAccessPoints"), ([nm.AP],))
|
||||
self.assertEqual(self.call(wifi_path, nm.NAME + ".Device.Wireless", "RequestScan", GLib.Variant("(a{sv})", ({},))), ())
|
||||
all_props = self.call(nm.ROOT, nm.PROPERTIES, "GetAll", GLib.Variant("(s)", (nm.NAME,)))[0]
|
||||
self.assertTrue(all_props["WirelessEnabled"])
|
||||
introspection = self.call(wifi_path, "org.freedesktop.DBus.Introspectable", "Introspect")[0]
|
||||
self.assertIn("GetAllAccessPoints", introspection)
|
||||
self.write(dict(WIFI, strength=21, ssid="Other Wi-Fi"))
|
||||
deadline = time.monotonic() + 4
|
||||
while self.prop(nm.AP, nm.NAME + ".AccessPoint", "Strength") != 21 and time.monotonic() < deadline:
|
||||
time.sleep(0.05)
|
||||
self.assertEqual(self.prop(nm.AP, nm.NAME + ".AccessPoint", "Strength"), 21)
|
||||
self.assertEqual(self.call(nm.PROFILE, nm.NAME + ".Settings.Connection", "GetSettings")[0]["connection"]["id"], "Other Wi-Fi")
|
||||
self.write(CELLULAR)
|
||||
self.await_type("gsm")
|
||||
cell_path = nm.device_path(CELLULAR)
|
||||
self.assertEqual(self.call(nm.ROOT, nm.NAME, "GetDevices"), ([cell_path, nm.ROOT + "/Devices/Wifi"],))
|
||||
self.assertEqual(self.prop(cell_path, nm.NAME + ".Device", "DeviceType"), 8)
|
||||
self.assertEqual(self.prop(nm.ROOT, nm.NAME, "Metered"), 1)
|
||||
managed = self.call(nm.ROOT, nm.OBJECT_MANAGER, "GetManagedObjects")[0]
|
||||
self.assertIn(wifi_path, managed)
|
||||
self.assertEqual(managed[wifi_path][nm.NAME + ".Device"]["State"], 30)
|
||||
self.assertNotIn(nm.AP, managed)
|
||||
self.assertNotIn(nm.IP4, managed)
|
||||
self.assertIn(nm.IP6, managed)
|
||||
self.assertEqual(self.prop(wifi_path, nm.NAME + ".Device.Wireless", "ActiveAccessPoint"), "/")
|
||||
self.write(OFFLINE)
|
||||
self.await_type("")
|
||||
self.assertEqual(self.call(nm.ROOT, nm.NAME, "CheckConnectivity"), (1,))
|
||||
self.write(WIFI)
|
||||
self.await_type("802-11-wireless")
|
||||
self.assertEqual(self.prop(nm.AP, nm.NAME + ".AccessPoint", "Strength"), 73)
|
||||
context = GLib.MainContext.default()
|
||||
while context.pending():
|
||||
context.iteration(False)
|
||||
self.assertTrue(any(interface == nm.PROPERTIES and member == "PropertiesChanged" and
|
||||
args[1].get("PrimaryConnectionType") == "gsm"
|
||||
for _, interface, member, args in signals))
|
||||
self.assertTrue(any(interface == nm.OBJECT_MANAGER and member == "InterfacesRemoved" and args[0] == nm.AP
|
||||
for _, interface, member, args in signals))
|
||||
self.assertTrue(any(member == "AccessPointAdded" for _, _, member, _ in signals))
|
||||
# A missing/invalid snapshot is a transient input error, never a fake Ethernet handover.
|
||||
self.snapshot.write_text("{")
|
||||
time.sleep(1.2)
|
||||
self.assertEqual(self.prop(nm.ROOT, nm.NAME, "PrimaryConnectionType"), "802-11-wireless")
|
||||
|
||||
def test_scan_requests_and_live_results(self):
|
||||
wifi_path = nm.device_path(WIFI)
|
||||
self.call(wifi_path, nm.NAME + ".Device.Wireless", "RequestScan", GLib.Variant("(a{sv})", ({},)))
|
||||
self.assertTrue(self.snapshot.with_suffix(".request").is_file())
|
||||
current = {"ssid": "Named Current", "bssid": "00:11:22:33:44:55", "capabilities": "[WPA2-PSK-CCMP]"}
|
||||
other = {"ssid": "Nearby", "bssid": "00:11:22:33:44:66", "strength": 37, "capabilities": "[ESS]"}
|
||||
self.write(dict(WIFI, ssid=current["ssid"], bssid=current["bssid"], accessPoints=[current, other], scanAllowed=True))
|
||||
deadline = time.monotonic() + 4
|
||||
while time.monotonic() < deadline:
|
||||
aps = self.call(wifi_path, nm.NAME + ".Device.Wireless", "GetAllAccessPoints")[0]
|
||||
if nm.ap_path(other["bssid"]) in aps:
|
||||
break
|
||||
time.sleep(0.05)
|
||||
self.assertIn(nm.ap_path(other["bssid"]), aps)
|
||||
self.assertEqual(self.prop(wifi_path, nm.NAME + ".Device.Wireless", "ActiveAccessPoint"), nm.ap_path(current["bssid"]))
|
||||
self.assertEqual(bytes(self.prop(nm.ap_path(other["bssid"]), nm.NAME + ".AccessPoint", "Ssid")).decode(), "Nearby")
|
||||
self.assertEqual(self.call(nm.PROFILE, nm.NAME + ".Settings.Connection", "GetSettings")[0]["connection"]["id"], "Named Current")
|
||||
self.write(dict(WIFI, scanAllowed=False))
|
||||
time.sleep(1.2)
|
||||
with self.assertRaises(GLib.Error):
|
||||
self.call(wifi_path, nm.NAME + ".Device.Wireless", "RequestScan", GLib.Variant("(a{sv})", ({},)))
|
||||
|
||||
def test_libnm_client(self):
|
||||
try:
|
||||
gi.require_version("NM", "1.0")
|
||||
from gi.repository import NM
|
||||
except ValueError:
|
||||
self.skipTest("requires gir1.2-nm-1.0")
|
||||
# libnm is a real consumer of the same API Steam reads. It caches objects by path,
|
||||
# so the handover must replace the Wi-Fi device with a modem rather than mutate its type.
|
||||
previous = os.environ.get("DBUS_SYSTEM_BUS_ADDRESS")
|
||||
os.environ["DBUS_SYSTEM_BUS_ADDRESS"] = os.environ["DBUS_SESSION_BUS_ADDRESS"]
|
||||
try:
|
||||
client = NM.Client.new(None)
|
||||
self.assertTrue(client.get_nm_running())
|
||||
wifi = client.get_devices()[0]
|
||||
self.assertIsInstance(wifi, NM.DeviceWifi)
|
||||
self.assertEqual(wifi.get_active_access_point().get_strength(), 73)
|
||||
self.assertEqual(client.get_primary_connection().get_connection_type(), "802-11-wireless")
|
||||
self.write(CELLULAR)
|
||||
self.await_type("gsm")
|
||||
context = GLib.MainContext.default()
|
||||
deadline = time.monotonic() + 4
|
||||
while time.monotonic() < deadline:
|
||||
while context.pending():
|
||||
context.iteration(False)
|
||||
if client.get_devices() and isinstance(client.get_devices()[0], NM.DeviceModem):
|
||||
break
|
||||
time.sleep(0.05)
|
||||
self.assertIsInstance(client.get_devices()[0], NM.DeviceModem)
|
||||
self.assertEqual(client.get_primary_connection().get_connection_type(), "gsm")
|
||||
finally:
|
||||
if previous is None:
|
||||
os.environ.pop("DBUS_SYSTEM_BUS_ADDRESS", None)
|
||||
else:
|
||||
os.environ["DBUS_SYSTEM_BUS_ADDRESS"] = previous
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user