mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-05 12:35:42 +00:00
Compare commits
54
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
33ebc24647 | ||
|
|
7905e2f8ba | ||
|
|
f6c6e73a6b | ||
|
|
309893b722 | ||
|
|
9b800ceb5e | ||
|
|
a03ec8eb57 | ||
|
|
e349d2544e | ||
|
|
5f2699e56b | ||
|
|
cd87718ac2 | ||
|
|
f9304f41c7 | ||
|
|
95aab3703f | ||
|
|
fcaaf4dde0 | ||
|
|
d967dd03a3 | ||
|
|
366afa6b73 | ||
|
|
5cb8e7fdf3 | ||
|
|
8ee80aa20f | ||
|
|
78f942313d | ||
|
|
8576652fb6 | ||
|
|
f539660650 | ||
|
|
ba3f840b8d | ||
|
|
ec31c9e2b6 | ||
|
|
59e98afae7 | ||
|
|
15b1e196af | ||
|
|
b0a8c0898e | ||
|
|
e3b1b60914 | ||
|
|
86ad1544a6 | ||
|
|
db80e7592a | ||
|
|
6ecc5a22d3 | ||
|
|
963af6df8e | ||
|
|
f683e97172 | ||
|
|
5df25c77ca | ||
|
|
3502b43cea | ||
|
|
4b8c3b158d | ||
|
|
f9729d10e4 | ||
|
|
c98be87383 | ||
|
|
e854bf8403 | ||
|
|
bdb240b640 | ||
|
|
0a6060d409 | ||
|
|
81d2643a88 | ||
|
|
1099b82044 | ||
|
|
dae53c29e0 | ||
|
|
d168705954 | ||
|
|
8ba8b12e78 | ||
|
|
aade03b7cf | ||
|
|
eaa12a3594 | ||
|
|
b3fc6b9a2c | ||
|
|
643496ae70 | ||
|
|
1288874810 | ||
|
|
2510b5e113 | ||
|
|
38cda8131d | ||
|
|
4cebd09aa6 | ||
|
|
fce3daaf45 | ||
|
|
88a648c273 | ||
|
|
6ead4af37e |
No files matched your search
@@ -164,6 +164,9 @@ jobs:
|
||||
!/docs/releases/media/
|
||||
sparse-checkout-cone-mode: false
|
||||
persist-credentials: false
|
||||
- name: Clear scratch earlier runs left behind
|
||||
if: runner.environment == 'self-hosted'
|
||||
run: bash tools/ci/clear-runner-scratch.sh "$GITHUB_WORKSPACE"
|
||||
- name: Merge the pinned APK base
|
||||
if: github.event_name == 'pull_request'
|
||||
env:
|
||||
@@ -367,6 +370,10 @@ jobs:
|
||||
persist-credentials: false
|
||||
submodules: recursive
|
||||
|
||||
- name: Clear scratch earlier runs left behind
|
||||
if: runner.environment == 'self-hosted'
|
||||
run: bash tools/ci/clear-runner-scratch.sh "$GITHUB_WORKSPACE"
|
||||
|
||||
- name: Check human authorship
|
||||
env:
|
||||
EVENT_NAME: ${{ github.event_name }}
|
||||
@@ -685,6 +692,16 @@ jobs:
|
||||
if-no-files-found: ignore
|
||||
overwrite: true
|
||||
|
||||
- name: Resolve the Robolectric version
|
||||
id: robolectric
|
||||
run: |
|
||||
echo "version=$(grep -o "org.robolectric:robolectric:[0-9.]*" app/build.gradle | cut -d: -f3)" >> "$GITHUB_OUTPUT"
|
||||
# Robolectric downloads these from Maven Central on first use without retrying, and 429s fail whole test classes.
|
||||
- name: Cache Robolectric's Android jars
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.m2/repository/org/robolectric/android-all-instrumented
|
||||
key: robolectric-android-all-${{ steps.robolectric.outputs.version }}
|
||||
- name: Unit tests
|
||||
id: unit-tests
|
||||
env:
|
||||
|
||||
@@ -2,7 +2,41 @@
|
||||
|
||||
- Comments should be rare, factual, and explain only non-obvious external constraints or business invariants.
|
||||
|
||||
# Working on the device
|
||||
# Building and testing
|
||||
|
||||
- For an install-and-look iteration, use `tools/quick_deploy.sh` (build without lint, sign, install, about 30 s). Run `tools/build_local.sh` once to prepare the runtime and again only before a PR. It is not a per-change step.
|
||||
- `tools/build_local.sh` reuses the components a main CI run prepared when every recipe identity matches the local tree (it prints `components: … reusing`). It builds them locally when no usable CI artifact matches (after you change their inputs, or when the lookup fails) or with `DROIDDECK_CI_COMPONENTS=0`.
|
||||
- Helper scripts (`tools/linuxfs/overlay`, `tools/linuxfs/desktop`) are staged on every Gradle build, so editing them needs no `build_local.sh`. After preloads or other runtime components change, the fast loop warns and reuses the old binaries; run `tools/build_local.sh` when those matter. "Missing or changed runtime input" means the prepared files themselves changed: run `tools/build_local.sh` once. Do not revert scripts or copy `app/build` between checkouts; `tools/seed_worktree.sh` seeds a new worktree from the main checkout.
|
||||
- Every build defaults to the NDK in `tools/ci/toolchains.env`, as CI does. CI runs `testReleaseUnitTest`; when a test fails only in CI, run the release variant locally.
|
||||
- Run the tests that cover what you changed, including unchanged tests of code you edited: `./gradlew -PskipRust=true :app:testDebugUnitTest --tests '<class>'` and `python3 -m unittest discover -s tools/tests -p 'test_<area>*.py'`. The full Python suite takes about 9 minutes, and some preload tests fail on any host without zram/ntsync. Leave full runs to CI.
|
||||
- For UI screenshots without a device, run `./gradlew -PskipRust=true :app:testDebugUnitTest --tests '*PreviewRenderTest'` and read `app/build/preview-renders/{handheld,portrait}/`. Add cases per `docs/compose-previews.md`. Check portrait, not just landscape.
|
||||
- After changing `SettingsIndex`, regenerate the doc: `UPDATE_SETTINGS_MAP=1 ./gradlew -PskipRust=true :app:testDebugUnitTest --tests '*SettingsMapTest*'`.
|
||||
- Compile errors in code you didn't touch, after switching branches, are usually stale incremental state. Rebuild once before you change anything.
|
||||
|
||||
# Worktrees and shared machines
|
||||
|
||||
- After `git worktree add`, run `git submodule update --init --recursive`. Without it, `buildVkBridgeServer` fails on missing `external/MaliBridge`. Do not commit the `tools/syncthing/syncthing-android` pointer the build dirties.
|
||||
- Other agents may be building on the same machine. Never run `./gradlew --stop` or kill Gradle/Kotlin daemons you did not start. If you need isolation, use `GRADLE_USER_HOME=<own dir> GRADLE_RO_DEP_CACHE=$HOME/.gradle/caches`.
|
||||
|
||||
# Driving the app and device
|
||||
|
||||
- Do it yourself with `tools/droiddeckctl` (see `docs/agent-control.md`) instead of asking the user: `cdp eval` for Steam's UI (`SteamClient.Apps.TerminateApp('<appid>', false)` quits a game, including on a Remote Play host), `input`, `quit`, `displays`, `screenshot --display <id>`.
|
||||
- A stream has started only when the session state reads `Streaming`. `SteamClient.Apps.StreamGame` alone can leave Steam on its menu, so open the game page and press Stream.
|
||||
- Test controller navigation with `tools/droiddeckctl input gamepad ...`, a real uinput pad. `adb shell input keyevent DPAD_*` does not arrive as a joystick event and hides d-pad/stick bugs.
|
||||
- A release-signed build installs over a release-signed install with `adb install -r`. Don't back up, uninstall or clear data to update. Scope `pm` and permission resets to `com.droiddeck.launcher`, never the whole device.
|
||||
|
||||
# CI
|
||||
|
||||
- CI builds the PR merged onto `main`. Before pushing, merge or rebase onto `origin/main` and compile: most "works locally" Kotlin failures come from that merge.
|
||||
- Before a PR that touches strings or resources, run `./gradlew :app:lintVitalRelease`. The fast loop skips lint, and lint catches `ExtraTranslation` and missing-locale errors.
|
||||
- Commit messages and PR bodies must not carry `Co-Authored-By` or other bot trailers. `tools/release/check_authorship.py` fails the build on them.
|
||||
- `gh run view --log-failed` truncates the unit-test log, so the failing test may not show. Read the whole job log with `gh api repos/Droid-Deck/DroidDeck/actions/jobs/<job-id>/logs`, or `gh run download <run> -n unit-test-results`. Don't call a failure a runner problem until you have read it.
|
||||
- Only these are known flakes worth a `gh run rerun <run> --failed`: `ProtonMenuAutoTest` "Proton work did not finish", Robolectric `HTTP response code: 429` from Maven, `Gradle Test Executor N finished with non-zero exit value 2`, apt mirror and GitHub API rate-limit errors. Treat any other failure as real.
|
||||
- A workflow step that names a script your branch lacks means the branch predates a CI change. Rebase onto `main`.
|
||||
|
||||
# Agents running on the device (DroidDeck's in-app agent)
|
||||
|
||||
These apply only where `dd-lab-build` exists. Agents on a dev host use `tools/quick_deploy.sh` instead.
|
||||
|
||||
- `dd-lab-build` builds only committed work. Check `git status` and `gh api user` for the identity before committing; if `git config user.name` is empty, use the `gh` login's name and noreply email for this repo, never a guess.
|
||||
- Do not commit or start a build in the same step: a build started next to a failed commit fails too. Commit first, check it, then build.
|
||||
|
||||
+8
-6
@@ -125,7 +125,8 @@ def variantSuffixes = rootProject.file('tools/release/variants.txt').readLines()
|
||||
android {
|
||||
namespace 'com.droiddeck.launcher'
|
||||
compileSdk 34
|
||||
ndkVersion project.findProperty('ndkVersion') ?: '27.3.13750724'
|
||||
ndkVersion project.findProperty('ndkVersion') ?: providers.fileContents(rootProject.layout.projectDirectory.file('tools/ci/toolchains.env'))
|
||||
.asText.get().readLines().find { it.startsWith('CI_ANDROID_NDK_VERSION=') }.split('=', 2)[1].trim()
|
||||
|
||||
defaultConfig {
|
||||
applicationId "com.droiddeck.launcher"
|
||||
@@ -232,6 +233,9 @@ android {
|
||||
}
|
||||
maxHeapSize = '2g'
|
||||
maxParallelForks = 2
|
||||
def jvmTemp = new File(temporaryDir, 'jvm')
|
||||
systemProperty 'java.io.tmpdir', jvmTemp.absolutePath
|
||||
doFirst { jvmTemp.mkdirs() }
|
||||
def logTarget = providers.systemProperty('robolectric.logging').orNull
|
||||
if (logTarget != null) systemProperty 'robolectric.logging', logTarget
|
||||
}
|
||||
@@ -261,11 +265,9 @@ if (vitureSdkDir) {
|
||||
tasks.named('preBuild').configure { dependsOn(stageVitureNotices) }
|
||||
}
|
||||
|
||||
def stageSessionScripts = tasks.register('stageSessionScripts', Copy) {
|
||||
from(rootProject.file('tools/linuxfs/overlay')) {
|
||||
include 'usr/local/bin/droiddeck-*', 'usr/local/bin/steam-compatibility', 'usr/bin/**'
|
||||
}
|
||||
into(layout.projectDirectory.dir('src/main/assets/linuxfs'))
|
||||
def stageSessionScripts = tasks.register('stageSessionScripts', Exec) {
|
||||
workingDir rootProject.projectDir
|
||||
commandLine pythonExecutable, 'tools/release/check_session_assets.py', '--stage'
|
||||
}
|
||||
tasks.named('preBuild').configure { dependsOn(stageSessionScripts) }
|
||||
|
||||
|
||||
@@ -57,7 +57,10 @@
|
||||
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
|
||||
<uses-permission android:name="android.permission.REQUEST_DELETE_PACKAGES" />
|
||||
<uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" />
|
||||
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30" />
|
||||
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
|
||||
<uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
|
||||
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
|
||||
<uses-permission android:name="android.permission.CAMERA" />
|
||||
|
||||
<uses-feature android:name="android.hardware.vulkan.version" android:version="0x401000" android:required="true" />
|
||||
@@ -118,6 +121,14 @@
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name=".BtControllerActivity"
|
||||
android:exported="false"
|
||||
android:launchMode="singleTask"
|
||||
android:resizeableActivity="true"
|
||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density|keyboard|keyboardHidden|navigation|uiMode"
|
||||
android:theme="@style/AppTheme" />
|
||||
|
||||
<activity
|
||||
android:name=".DeviceCodeActivity"
|
||||
android:exported="false"
|
||||
|
||||
@@ -21,6 +21,7 @@ class App : Application() {
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
com.droiddeck.launcher.runtime.NativeGuest.init(this)
|
||||
com.droiddeck.launcher.session.Onboarding.attach(this)
|
||||
Thread({ runCatching { EnhancedSessionLogShare.cleanupAbandonedStages(this) } }, "diagnostic-stage-cleanup").start()
|
||||
com.droiddeck.launcher.ui.Themes.loadGradient(this)
|
||||
com.droiddeck.launcher.ui.BuildWatermark.install(this)
|
||||
|
||||
@@ -0,0 +1,589 @@
|
||||
package com.droiddeck.launcher
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.view.InputDevice
|
||||
import android.view.KeyEvent
|
||||
import android.view.MotionEvent
|
||||
import android.view.WindowManager
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.gestures.awaitEachGesture
|
||||
import androidx.compose.foundation.gestures.awaitFirstDown
|
||||
import androidx.compose.foundation.gestures.waitForUpOrCancellation
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxHeight
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.offset
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.IntOffset
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.core.AppLanguage
|
||||
import com.droiddeck.launcher.input.bt.BtGamepad
|
||||
import com.droiddeck.launcher.input.bt.BtPadProfile
|
||||
import com.droiddeck.launcher.input.bt.BtPadState
|
||||
import com.droiddeck.launcher.ui.DroidDeckTheme
|
||||
import com.droiddeck.launcher.ui.LocalPalette
|
||||
import com.droiddeck.launcher.ui.PrimaryButton
|
||||
import com.droiddeck.launcher.ui.SecondaryButton
|
||||
import kotlin.math.hypot
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
class BtControllerActivity : ComponentActivity() {
|
||||
private val physical = BtPadState()
|
||||
private val touch = BtPadState()
|
||||
private val merged = BtPadState()
|
||||
private var keyButtons = 0
|
||||
private var hatButtons = 0
|
||||
private var touchEpoch by mutableStateOf(0)
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
private val exitHold = Runnable { finish() }
|
||||
private var exitArmed = false
|
||||
private var profile by mutableStateOf(BtPadProfile.GENERIC)
|
||||
private var showTouch by mutableStateOf(true)
|
||||
private var permissionDenied by mutableStateOf(false)
|
||||
private var locationDenied by mutableStateOf(false)
|
||||
|
||||
override fun attachBaseContext(newBase: Context) = super.attachBaseContext(AppLanguage.wrap(newBase))
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
|
||||
val prefs = prefs(this)
|
||||
profile = BtPadProfile.byId(prefs.getString(KEY_PROFILE, null))
|
||||
showTouch = prefs.getBoolean(KEY_TOUCH, true)
|
||||
val wanted = if (Build.VERSION.SDK_INT >= 31) NEARBY + LOCATION else LOCATION
|
||||
val missing = wanted.filter { checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED }
|
||||
if (missing.isEmpty()) startPad() else requestPermissions(missing.toTypedArray(), REQUEST_NEARBY)
|
||||
setContent { DroidDeckTheme { Screen() } }
|
||||
}
|
||||
|
||||
private fun openAppInfo() {
|
||||
runCatching {
|
||||
startActivity(Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS, android.net.Uri.fromParts("package", packageName, null)))
|
||||
}
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
locationDenied = LOCATION.any { checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED }
|
||||
if (permissionDenied && Build.VERSION.SDK_INT >= 31 && NEARBY.all { checkSelfPermission(it) == PackageManager.PERMISSION_GRANTED }) {
|
||||
permissionDenied = false
|
||||
startPad()
|
||||
}
|
||||
}
|
||||
|
||||
private fun startPad() {
|
||||
BtGamepad.start(this, profile)
|
||||
BtGamepad.openPairingWindow()
|
||||
}
|
||||
|
||||
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
|
||||
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
|
||||
if (requestCode != REQUEST_NEARBY) return
|
||||
val nearbyDenied = Build.VERSION.SDK_INT >= 31 && NEARBY.any { checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED }
|
||||
permissionDenied = nearbyDenied
|
||||
locationDenied = LOCATION.any { checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED }
|
||||
if (!nearbyDenied) startPad()
|
||||
}
|
||||
|
||||
override fun onWindowFocusChanged(hasFocus: Boolean) {
|
||||
super.onWindowFocusChanged(hasFocus)
|
||||
if (hasFocus) return
|
||||
physical.set(BtPadState())
|
||||
touch.set(BtPadState())
|
||||
touchEpoch++
|
||||
keyButtons = 0
|
||||
hatButtons = 0
|
||||
push()
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
main.removeCallbacks(exitHold)
|
||||
if (isFinishing) BtGamepad.stop()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
private fun pickProfile(p: BtPadProfile) {
|
||||
if (p == profile) return
|
||||
profile = p
|
||||
prefs(this).edit().putString(KEY_PROFILE, p.id).apply()
|
||||
BtGamepad.switchProfile(p)
|
||||
}
|
||||
|
||||
private fun push() {
|
||||
physical.buttons = keyButtons or hatButtons
|
||||
merged.merge(physical, touch)
|
||||
BtGamepad.update(merged)
|
||||
val combo = BtPadState.SELECT or BtPadState.START
|
||||
val held = physical.buttons and combo == combo
|
||||
if (held && !exitArmed) main.postDelayed(exitHold, EXIT_HOLD_MS)
|
||||
else if (!held && exitArmed) main.removeCallbacks(exitHold)
|
||||
exitArmed = held
|
||||
}
|
||||
|
||||
private fun isPad(event: KeyEvent): Boolean {
|
||||
val s = event.source
|
||||
return s and InputDevice.SOURCE_GAMEPAD == InputDevice.SOURCE_GAMEPAD ||
|
||||
s and InputDevice.SOURCE_JOYSTICK == InputDevice.SOURCE_JOYSTICK ||
|
||||
KeyEvent.isGamepadButton(event.keyCode)
|
||||
}
|
||||
|
||||
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
|
||||
val bit = KEYS[event.keyCode]
|
||||
if (bit == null || event.keyCode in DPAD_KEYS && !isPad(event) && event.source and InputDevice.SOURCE_DPAD != InputDevice.SOURCE_DPAD) {
|
||||
return super.dispatchKeyEvent(event)
|
||||
}
|
||||
when (event.action) {
|
||||
KeyEvent.ACTION_DOWN -> keyButtons = keyButtons or bit
|
||||
KeyEvent.ACTION_UP -> keyButtons = keyButtons and bit.inv()
|
||||
}
|
||||
push()
|
||||
return true
|
||||
}
|
||||
|
||||
override fun dispatchGenericMotionEvent(event: MotionEvent): Boolean {
|
||||
if (event.source and InputDevice.SOURCE_JOYSTICK != InputDevice.SOURCE_JOYSTICK || event.action != MotionEvent.ACTION_MOVE) {
|
||||
return super.dispatchGenericMotionEvent(event)
|
||||
}
|
||||
val device = event.device
|
||||
fun axis(code: Int): Float {
|
||||
val range = device?.getMotionRange(code, event.source) ?: return 0f
|
||||
val v = event.getAxisValue(code)
|
||||
return if (Math.abs(v) > maxOf(range.flat, 0.04f)) v else 0f
|
||||
}
|
||||
val hasZ = device?.getMotionRange(MotionEvent.AXIS_Z, event.source) != null
|
||||
physical.lx = axis(MotionEvent.AXIS_X); physical.ly = axis(MotionEvent.AXIS_Y)
|
||||
physical.rx = axis(if (hasZ) MotionEvent.AXIS_Z else MotionEvent.AXIS_RX)
|
||||
physical.ry = axis(if (hasZ) MotionEvent.AXIS_RZ else MotionEvent.AXIS_RY)
|
||||
physical.lt = maxOf(axis(MotionEvent.AXIS_LTRIGGER), axis(MotionEvent.AXIS_BRAKE))
|
||||
physical.rt = maxOf(axis(MotionEvent.AXIS_RTRIGGER), axis(MotionEvent.AXIS_GAS))
|
||||
val hx = event.getAxisValue(MotionEvent.AXIS_HAT_X)
|
||||
val hy = event.getAxisValue(MotionEvent.AXIS_HAT_Y)
|
||||
hatButtons = (if (hy < -0.5f) BtPadState.UP else 0) or (if (hy > 0.5f) BtPadState.DOWN else 0) or
|
||||
(if (hx < -0.5f) BtPadState.LEFT else 0) or (if (hx > 0.5f) BtPadState.RIGHT else 0)
|
||||
push()
|
||||
return true
|
||||
}
|
||||
|
||||
private fun touchButton(bit: Int, down: Boolean) {
|
||||
touch.buttons = if (down) touch.buttons or bit else touch.buttons and bit.inv()
|
||||
if (bit == BtPadState.LT) touch.lt = if (down) 1f else 0f
|
||||
if (bit == BtPadState.RT) touch.rt = if (down) 1f else 0f
|
||||
push()
|
||||
}
|
||||
|
||||
private fun touchStick(left: Boolean, x: Float, y: Float) {
|
||||
if (left) { touch.lx = x; touch.ly = y } else { touch.rx = x; touch.ry = y }
|
||||
push()
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Screen() {
|
||||
val status by BtGamepad.status.collectAsState()
|
||||
val colors = MaterialTheme.colorScheme
|
||||
Column(Modifier.fillMaxSize().background(colors.background).padding(horizontal = 12.dp, vertical = 8.dp)) {
|
||||
Panel(status)
|
||||
if (showTouch) {
|
||||
TouchPad(Modifier.weight(1f).fillMaxWidth().padding(top = 6.dp), status)
|
||||
} else {
|
||||
Column(Modifier.weight(1f).fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(12.dp, Alignment.CenterVertically),
|
||||
horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Instructions(status, Modifier.widthIn(max = 480.dp))
|
||||
Text(stringResource(R.string.btpad_physical_hint), fontSize = 15.sp, color = colors.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Panel(status: BtGamepad.Status) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val connected = status.phase == BtGamepad.Phase.CONNECTED
|
||||
BoxWithConstraints(Modifier.fillMaxWidth()) {
|
||||
val narrow = maxWidth < 600.dp
|
||||
val types: @Composable (Modifier) -> Unit = { m ->
|
||||
Row(m.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
BtPadProfile.entries.forEach { p -> Chip(profileLabel(p), p == profile) { pickProfile(p) } }
|
||||
Chip(stringResource(R.string.btpad_touch), showTouch) {
|
||||
showTouch = !showTouch
|
||||
prefs(this@BtControllerActivity).edit().putBoolean(KEY_TOUCH, showTouch).apply()
|
||||
}
|
||||
}
|
||||
}
|
||||
Column {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Box(Modifier.size(10.dp).clip(CircleShape).background(status.lightbar?.let { Color(it) } ?: if (connected) pal.signal else colors.onSurfaceVariant.copy(alpha = 0.4f)))
|
||||
Column(if (narrow) Modifier.weight(1f) else Modifier.widthIn(max = 220.dp)) {
|
||||
Text(shortStatus(status), fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(stringResource(if (connected) R.string.btpad_exit_hint else R.string.btpad_switch_hint), fontSize = 11.sp,
|
||||
color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
if (!narrow) types(Modifier.weight(1f))
|
||||
if (locationDenied && !permissionDenied && !connected) SecondaryButton(stringResource(R.string.btpad_permission_open), compact = true) { openAppInfo() }
|
||||
if (permissionDenied) PrimaryButton(stringResource(R.string.btpad_permission_open), compact = true) { openAppInfo() }
|
||||
else if (connected) SecondaryButton(stringResource(R.string.btpad_disconnect), compact = true) { BtGamepad.disconnect() }
|
||||
else PrimaryButton(stringResource(R.string.btpad_pair), compact = true, enabled = status.phase == BtGamepad.Phase.READY) { BtGamepad.openPairingWindow() }
|
||||
SecondaryButton(stringResource(R.string.btpad_close), compact = true) { finish() }
|
||||
}
|
||||
if (narrow) types(Modifier.padding(top = 6.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun shortStatus(status: BtGamepad.Status): String =
|
||||
if (status.phase == BtGamepad.Phase.READY && !permissionDenied) stringResource(R.string.btpad_status_waiting) else statusText(status)
|
||||
|
||||
@Composable
|
||||
private fun Instructions(status: BtGamepad.Status, modifier: Modifier, size: androidx.compose.ui.unit.TextUnit = 14.sp) {
|
||||
if (status.phase == BtGamepad.Phase.CONNECTED) return
|
||||
val text = statusText(status) + if (locationDenied && !permissionDenied) "\n\n" + stringResource(R.string.btpad_location_hint) else ""
|
||||
Text(text, fontSize = size, color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
textAlign = androidx.compose.ui.text.style.TextAlign.Center, modifier = modifier)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun statusText(status: BtGamepad.Status): String = if (permissionDenied) stringResource(R.string.btpad_status_permission) else when (status.phase) {
|
||||
BtGamepad.Phase.OFF, BtGamepad.Phase.STARTING -> stringResource(R.string.btpad_status_starting)
|
||||
BtGamepad.Phase.BLUETOOTH_OFF -> stringResource(R.string.btpad_status_bt_off)
|
||||
BtGamepad.Phase.UNSUPPORTED -> stringResource(R.string.btpad_status_unsupported)
|
||||
BtGamepad.Phase.READY -> stringResource(R.string.btpad_status_ready, status.name ?: "")
|
||||
BtGamepad.Phase.CONNECTING -> stringResource(R.string.btpad_status_connecting, status.host ?: "")
|
||||
BtGamepad.Phase.CONNECTED -> stringResource(R.string.btpad_status_connected, status.host ?: "")
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun profileLabel(p: BtPadProfile) = stringResource(when (p) {
|
||||
BtPadProfile.GENERIC -> R.string.btpad_profile_generic
|
||||
BtPadProfile.XBOX -> R.string.btpad_profile_xbox
|
||||
BtPadProfile.DUALSHOCK4 -> R.string.btpad_profile_ds4
|
||||
BtPadProfile.DUALSENSE -> R.string.btpad_profile_dualsense
|
||||
BtPadProfile.STEAM -> R.string.btpad_profile_steam
|
||||
})
|
||||
|
||||
@Composable
|
||||
private fun Chip(label: String, on: Boolean, enabled: Boolean = true, onClick: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
Text(label, fontSize = 13.sp, fontWeight = FontWeight.SemiBold,
|
||||
color = if (on) colors.background else if (enabled) colors.onBackground else colors.onSurfaceVariant,
|
||||
modifier = Modifier.clip(CircleShape).background(if (on) pal.signal else colors.surface)
|
||||
.border(1.dp, if (on) pal.signal else pal.line2, CircleShape)
|
||||
.clickable(enabled = enabled, onClick = onClick).padding(horizontal = 12.dp, vertical = 6.dp))
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TouchPad(modifier: Modifier, status: BtGamepad.Status) {
|
||||
val lightbar = status.lightbar
|
||||
val sony = profile == BtPadProfile.DUALSHOCK4 || profile == BtPadProfile.DUALSENSE
|
||||
val steam = profile == BtPadProfile.STEAM
|
||||
BoxWithConstraints(modifier) {
|
||||
val w = maxWidth
|
||||
val h = maxHeight
|
||||
val stick = minOf(h * (if (steam) 0.38f else 0.46f), w * 0.2f)
|
||||
val face = stick * 0.4f
|
||||
val cluster = face * 3f
|
||||
val shoulderW = minOf(w * 0.09f, stick * 0.75f)
|
||||
val shoulderH = minOf(h * 0.13f, 44.dp)
|
||||
val small = shoulderH * 0.85f
|
||||
@Composable
|
||||
fun at(fx: Float, fy: Float, bw: Dp, bh: Dp, content: @Composable () -> Unit) {
|
||||
val x = (w * fx - bw / 2).coerceIn(0.dp, w - bw)
|
||||
val y = (h * fy - bh / 2).coerceIn(0.dp, h - bh)
|
||||
Box(Modifier.offset(x, y).size(bw, bh), contentAlignment = Alignment.Center) { content() }
|
||||
}
|
||||
val shoulderY = shoulderH / h / 2f
|
||||
at(0.0f, shoulderY, shoulderW, shoulderH) { PadButton(if (sony) "L2" else "LT", BtPadState.LT, shoulderW, shoulderH) }
|
||||
val second = (shoulderW * 1.5f + 8.dp) / w
|
||||
at(second, shoulderY, shoulderW, shoulderH) { PadButton(if (sony) "L1" else "LB", BtPadState.LB, shoulderW, shoulderH) }
|
||||
at(1f - second, shoulderY, shoulderW, shoulderH) { PadButton(if (sony) "R1" else "RB", BtPadState.RB, shoulderW, shoulderH) }
|
||||
at(1.0f, shoulderY, shoulderW, shoulderH) { PadButton(if (sony) "R2" else "RT", BtPadState.RT, shoulderW, shoulderH) }
|
||||
val menuW = shoulderW * 0.95f
|
||||
val menu = listOfNotNull(
|
||||
Triple(if (sony) "Share" else "View", BtPadState.SELECT, null),
|
||||
Triple(if (sony) "PS" else if (steam) "Steam" else "Home", BtPadState.GUIDE, lightbar),
|
||||
if (steam) Triple("···", BtPadState.SHARE, null) else null,
|
||||
Triple(if (sony) "Options" else "Menu", BtPadState.START, null),
|
||||
)
|
||||
menu.forEachIndexed { i, (label, bit, tint) ->
|
||||
val fx = 0.5f + (i - (menu.size - 1) / 2f) * ((menuW + 8.dp) / w)
|
||||
at(fx, shoulderY, menuW, small) { PadButton(label, bit, menuW, small, tint = tint?.let { Color(it) }) }
|
||||
}
|
||||
val steamPad = minOf(h * 0.4f, w * 0.2f)
|
||||
val infoW = if (steam) w * 0.4f - steamPad - 12.dp else w * 0.3f
|
||||
val infoH = if (steam) h * 0.3f else h * 0.22f
|
||||
at(0.5f, if (steam) 0.72f else 0.3f, infoW, infoH) { Instructions(status, Modifier.fillMaxWidth(), if (steam) 12.sp else 14.sp) }
|
||||
if (steam) {
|
||||
val rearY = (shoulderH * 1.6f) / h
|
||||
at(0.0f, rearY, shoulderW, small) { PadButton("L5", BtPadState.L5, shoulderW, small) }
|
||||
at(second, rearY, shoulderW, small) { PadButton("L4", BtPadState.L4, shoulderW, small) }
|
||||
at(1f - second, rearY, shoulderW, small) { PadButton("R4", BtPadState.R4, shoulderW, small) }
|
||||
at(1.0f, rearY, shoulderW, small) { PadButton("R5", BtPadState.R5, shoulderW, small) }
|
||||
val pad = steamPad
|
||||
at(0.11f, 0.5f, stick, stick) { Stick(stick, left = true) }
|
||||
at(0.89f, 0.5f, stick, stick) { Stick(stick, left = false) }
|
||||
at(0.3f, 0.34f, cluster, cluster) { Cross(face) }
|
||||
at(0.7f, 0.34f, cluster, cluster) { Diamond(face, false) }
|
||||
at(0.3f, 1f, pad, pad) { Trackpad(pad, left = true) }
|
||||
at(0.7f, 1f, pad, pad) { Trackpad(pad, left = false) }
|
||||
at(0.44f, 0.94f, menuW, small) { PadButton("L3", BtPadState.L3, menuW, small) }
|
||||
at(0.56f, 0.94f, menuW, small) { PadButton("R3", BtPadState.R3, menuW, small) }
|
||||
} else {
|
||||
at(0.12f, 0.45f, stick, stick) { Stick(stick, left = true) }
|
||||
at(0.88f, 0.45f, cluster, cluster) { Diamond(face, sony) }
|
||||
at(0.32f, 0.78f, cluster, cluster) { Cross(face) }
|
||||
at(0.68f, 0.78f, stick, stick) { Stick(stick, left = false) }
|
||||
at(0.42f, 0.5f, menuW, small) { PadButton("L3", BtPadState.L3, menuW, small) }
|
||||
at(0.58f, 0.5f, menuW, small) { PadButton("R3", BtPadState.R3, menuW, small) }
|
||||
if (sony) at(0.5f, 0.68f, menuW * 1.6f, small * 1.4f) { PadButton("Touchpad", BtPadState.TOUCHPAD, menuW * 1.6f, small * 1.4f) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Trackpad(size: Dp, left: Boolean) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
var dot by remember { mutableStateOf<Offset?>(null) }
|
||||
val px = with(LocalDensity.current) { size.toPx() }
|
||||
Box(
|
||||
Modifier.size(size).clip(RoundedCornerShape(18.dp)).background(colors.surface).border(1.dp, pal.line2, RoundedCornerShape(18.dp))
|
||||
.pointerInput(left, touchEpoch) {
|
||||
awaitEachGesture {
|
||||
val first = awaitFirstDown(requireUnconsumed = false)
|
||||
val started = first.uptimeMillis
|
||||
fun norm(p: Offset) = Offset((p.x / this.size.width * 2f - 1f).coerceIn(-1f, 1f), (p.y / this.size.height * 2f - 1f).coerceIn(-1f, 1f))
|
||||
var moved = 0f
|
||||
var last = norm(first.position)
|
||||
dot = last
|
||||
touchPad(left, last, true)
|
||||
var upTime = started
|
||||
try {
|
||||
while (true) {
|
||||
val change = awaitPointerEvent().changes.firstOrNull { it.id == first.id } ?: break
|
||||
if (!change.pressed) { upTime = change.uptimeMillis; break }
|
||||
change.consume()
|
||||
val p = norm(change.position)
|
||||
moved += (p - last).getDistance()
|
||||
last = p
|
||||
dot = p
|
||||
touchPad(left, p, true)
|
||||
}
|
||||
} catch (e: kotlinx.coroutines.CancellationException) {
|
||||
dot = null
|
||||
touchPad(left, last, false)
|
||||
throw e
|
||||
}
|
||||
dot = null
|
||||
if (upTime - started < TAP_MS && moved < 0.15f) clickPad(left, last)
|
||||
else touchPad(left, last, false)
|
||||
}
|
||||
},
|
||||
) {
|
||||
dot?.let { d ->
|
||||
val r = px * 0.08f
|
||||
Box(Modifier.offset { IntOffset(((d.x + 1f) / 2f * px - r).roundToInt(), ((d.y + 1f) / 2f * px - r).roundToInt()) }
|
||||
.size(size * 0.16f).clip(CircleShape).background(pal.signal))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun touchPad(left: Boolean, p: Offset, down: Boolean) {
|
||||
val bit = if (left) BtPadState.LPAD_TOUCH else BtPadState.RPAD_TOUCH
|
||||
touch.buttons = if (down) touch.buttons or bit else touch.buttons and bit.inv()
|
||||
if (left) { touch.lpx = p.x; touch.lpy = p.y } else { touch.rpx = p.x; touch.rpy = p.y }
|
||||
push()
|
||||
}
|
||||
|
||||
private fun clickPad(left: Boolean, p: Offset) {
|
||||
val click = if (left) BtPadState.LPAD_CLICK else BtPadState.RPAD_CLICK
|
||||
touch.buttons = touch.buttons or click
|
||||
touchPad(left, p, true)
|
||||
main.postDelayed({
|
||||
touch.buttons = touch.buttons and click.inv()
|
||||
touchPad(left, p, false)
|
||||
}, CLICK_MS)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Cross(size: Dp) {
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
PadButton("▲", BtPadState.UP, size, size)
|
||||
Row {
|
||||
PadButton("◀", BtPadState.LEFT, size, size)
|
||||
Spacer(Modifier.size(size))
|
||||
PadButton("▶", BtPadState.RIGHT, size, size)
|
||||
}
|
||||
PadButton("▼", BtPadState.DOWN, size, size)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Diamond(size: Dp, sony: Boolean) {
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
PadButton(if (sony) "△" else "Y", BtPadState.Y, size, size, round = true)
|
||||
Row {
|
||||
PadButton(if (sony) "□" else "X", BtPadState.X, size, size, round = true)
|
||||
Spacer(Modifier.size(size))
|
||||
PadButton(if (sony) "○" else "B", BtPadState.B, size, size, round = true)
|
||||
}
|
||||
PadButton(if (sony) "✕" else "A", BtPadState.A, size, size, round = true)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PadButton(label: String, bit: Int, width: Dp, height: Dp, round: Boolean = false, tint: Color? = null) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
var down by remember { mutableStateOf(false) }
|
||||
val shape = if (round) CircleShape else RoundedCornerShape(10.dp)
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.size(width, height).clip(shape)
|
||||
.background(if (down) pal.signal else tint?.copy(alpha = 0.35f) ?: colors.surface)
|
||||
.border(1.dp, pal.line2, shape)
|
||||
.pointerInput(bit, touchEpoch) {
|
||||
awaitEachGesture {
|
||||
awaitFirstDown(requireUnconsumed = false)
|
||||
down = true; touchButton(bit, true)
|
||||
try {
|
||||
waitForUpOrCancellation()
|
||||
} finally {
|
||||
down = false; touchButton(bit, false)
|
||||
}
|
||||
}
|
||||
},
|
||||
) {
|
||||
Text(label, fontSize = 14.sp, fontWeight = FontWeight.Bold, color = if (down) colors.background else colors.onBackground)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Stick(size: Dp, left: Boolean) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
var knob by remember { mutableStateOf(Offset.Zero) }
|
||||
val px = with(LocalDensity.current) { size.toPx() }
|
||||
val knobSize = size * 0.42f
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.size(size).clip(CircleShape).background(colors.surface).border(1.dp, pal.line2, CircleShape)
|
||||
.pointerInput(left, touchEpoch) {
|
||||
awaitEachGesture {
|
||||
val first = awaitFirstDown(requireUnconsumed = false)
|
||||
val radius = this.size.width / 2f
|
||||
val center = Offset(radius, this.size.height / 2f)
|
||||
fun move(p: Offset) {
|
||||
var d = (p - center) / (radius * 0.8f)
|
||||
val len = hypot(d.x, d.y)
|
||||
if (len > 1f) d /= len
|
||||
knob = d
|
||||
touchStick(left, d.x, d.y)
|
||||
}
|
||||
move(first.position)
|
||||
try {
|
||||
while (true) {
|
||||
val change = awaitPointerEvent().changes.firstOrNull { it.id == first.id } ?: break
|
||||
if (!change.pressed) break
|
||||
change.consume()
|
||||
move(change.position)
|
||||
}
|
||||
} finally {
|
||||
knob = Offset.Zero
|
||||
touchStick(left, 0f, 0f)
|
||||
}
|
||||
}
|
||||
},
|
||||
) {
|
||||
val travel = px * 0.29f
|
||||
Box(Modifier.offset { IntOffset((knob.x * travel).roundToInt(), (knob.y * travel).roundToInt()) }
|
||||
.size(knobSize).clip(CircleShape).background(if (knob != Offset.Zero) pal.signal else colors.onSurfaceVariant.copy(alpha = 0.5f)))
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val EXIT_HOLD_MS = 1_500L
|
||||
private const val TAP_MS = 200L
|
||||
private const val CLICK_MS = 90L
|
||||
private const val REQUEST_NEARBY = 41
|
||||
private val NEARBY = listOf("android.permission.BLUETOOTH_ADVERTISE", "android.permission.BLUETOOTH_CONNECT", "android.permission.BLUETOOTH_SCAN")
|
||||
private val LOCATION = listOf("android.permission.ACCESS_FINE_LOCATION")
|
||||
private const val KEY_PROFILE = "btpad_profile"
|
||||
private const val KEY_TOUCH = "btpad_touch"
|
||||
|
||||
private fun prefs(c: Context) = c.getSharedPreferences("trinkets", Context.MODE_PRIVATE)
|
||||
|
||||
private val DPAD_KEYS = setOf(KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN, KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT)
|
||||
|
||||
private val KEYS = mapOf(
|
||||
KeyEvent.KEYCODE_BUTTON_A to BtPadState.A,
|
||||
KeyEvent.KEYCODE_BUTTON_B to BtPadState.B,
|
||||
KeyEvent.KEYCODE_BUTTON_X to BtPadState.X,
|
||||
KeyEvent.KEYCODE_BUTTON_Y to BtPadState.Y,
|
||||
KeyEvent.KEYCODE_BUTTON_L1 to BtPadState.LB,
|
||||
KeyEvent.KEYCODE_BUTTON_R1 to BtPadState.RB,
|
||||
KeyEvent.KEYCODE_BUTTON_L2 to BtPadState.LT,
|
||||
KeyEvent.KEYCODE_BUTTON_R2 to BtPadState.RT,
|
||||
KeyEvent.KEYCODE_BUTTON_SELECT to BtPadState.SELECT,
|
||||
KeyEvent.KEYCODE_BUTTON_START to BtPadState.START,
|
||||
KeyEvent.KEYCODE_BUTTON_MODE to BtPadState.GUIDE,
|
||||
KeyEvent.KEYCODE_BUTTON_THUMBL to BtPadState.L3,
|
||||
KeyEvent.KEYCODE_BUTTON_THUMBR to BtPadState.R3,
|
||||
KeyEvent.KEYCODE_BUTTON_C to BtPadState.L4,
|
||||
KeyEvent.KEYCODE_BUTTON_Z to BtPadState.R4,
|
||||
KeyEvent.KEYCODE_BUTTON_1 to BtPadState.L4,
|
||||
KeyEvent.KEYCODE_BUTTON_2 to BtPadState.R4,
|
||||
KeyEvent.KEYCODE_BUTTON_3 to BtPadState.L5,
|
||||
KeyEvent.KEYCODE_BUTTON_4 to BtPadState.R5,
|
||||
KeyEvent.KEYCODE_DPAD_UP to BtPadState.UP,
|
||||
KeyEvent.KEYCODE_DPAD_DOWN to BtPadState.DOWN,
|
||||
KeyEvent.KEYCODE_DPAD_LEFT to BtPadState.LEFT,
|
||||
KeyEvent.KEYCODE_DPAD_RIGHT to BtPadState.RIGHT,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -79,7 +79,7 @@ internal class ComponentsMenu(private val activity: android.app.Activity, privat
|
||||
checkAgain = null
|
||||
checkComponentUpdates(again)
|
||||
}
|
||||
if (notes.isNotEmpty()) android.widget.Toast.makeText(activity, notes.joinToString("\n"), android.widget.Toast.LENGTH_LONG).show()
|
||||
if (notes.isNotEmpty()) Log.i(TAG, notes.joinToString("; "))
|
||||
refreshComponents()
|
||||
}
|
||||
}, "component-updates").start()
|
||||
|
||||
@@ -254,6 +254,12 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
SessionPrefs.setWifiDiscoveryEnabled(this, WifiDiscovery.permissionGranted(this))
|
||||
refreshWifiDiscovery()
|
||||
}
|
||||
private val bluetoothPermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
|
||||
if (!granted && !shouldShowRequestPermissionRationale(android.Manifest.permission.BLUETOOTH_CONNECT)) {
|
||||
integrationSettings(SteamIntegration.appInfo(this))
|
||||
}
|
||||
integrationState = readIntegration()
|
||||
}
|
||||
private val cameraPermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) {
|
||||
com.droiddeck.launcher.handtracking.HandTracking.refreshPermission(this)
|
||||
}
|
||||
@@ -375,6 +381,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
SteamIntegration.Feature.SHORTCUTS -> {
|
||||
if (integrationState.shortcuts) openShortcutSettings() else installShortcuts()
|
||||
}
|
||||
SteamIntegration.Feature.BLUETOOTH -> {
|
||||
if (SteamIntegration.bluetoothAllowed(this)) integrationSettings(SteamIntegration.appInfo(this))
|
||||
else bluetoothPermission.launch(android.Manifest.permission.BLUETOOTH_CONNECT)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2166,9 +2176,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
if (!OfflineMode.enabled(this)) {
|
||||
val updated = runCatching { ComponentUpdater.ensure(this, force = false) }
|
||||
.onFailure { android.util.Log.w("ComponentUpdater", "automatic component updates", it) }.getOrDefault(emptyList())
|
||||
if (updated.isNotEmpty()) ui.post {
|
||||
android.widget.Toast.makeText(this, updated.joinToString("\n"), android.widget.Toast.LENGTH_LONG).show()
|
||||
}
|
||||
if (updated.isNotEmpty()) android.util.Log.i("ComponentUpdater", updated.joinToString("; "))
|
||||
}
|
||||
ui.post {
|
||||
componentsQueueBusy = false
|
||||
@@ -3209,6 +3217,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
bridgeProtonDxvk = SessionPrefs.bridgeProtonDxvk(this)
|
||||
removalPending = LinuxRuntimeInstaller.hasRemovalPending(this)
|
||||
ui.post { autoUpdateRuntime() }
|
||||
Thread({ com.droiddeck.launcher.session.Onboarding.recheck(this) }, "onboarding-recheck").start()
|
||||
frameGenLabel = FrameGen.label(this)
|
||||
romsDir = SessionPrefs.romsDir(this).takeIf { it.isNotEmpty() }
|
||||
logsEnabled = SessionPrefs.logsEnabled(this)
|
||||
@@ -3430,18 +3439,24 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
|
||||
private fun install(release: LinuxRuntimeInstaller.Release) {
|
||||
com.droiddeck.launcher.runtime.RuntimeInstallService.start(this, release)
|
||||
followRuntimeOperation { listener -> LinuxRuntimeInstaller.install(this, release, listener) }
|
||||
followRuntimeOperation(onboarding = true) { listener -> LinuxRuntimeInstaller.install(this, release, listener) }
|
||||
}
|
||||
|
||||
private fun followRuntimeOperation(run: (LinuxRuntimeInstaller.ProgressListener) -> Boolean?) {
|
||||
private fun followRuntimeOperation(onboarding: Boolean = false, run: (LinuxRuntimeInstaller.ProgressListener) -> Boolean?) {
|
||||
busy = true
|
||||
failed = false
|
||||
stage = getString(if (LinuxRuntimeInstaller.isMaintaining()) R.string.desktop_removing else if (LinuxRuntimeInstaller.isRemoving()) R.string.main_removing_runtime else R.string.store_starting)
|
||||
percent = -1
|
||||
Thread({
|
||||
val ok = run(LinuxRuntimeInstaller.ProgressListener { s, p ->
|
||||
if (onboarding) com.droiddeck.launcher.session.Onboarding.report(com.droiddeck.launcher.session.Onboarding.Step.RUNTIME, s, p)
|
||||
ui.post { stage = s; percent = p }
|
||||
})
|
||||
if (onboarding) {
|
||||
if (ok == false) com.droiddeck.launcher.session.Onboarding.fail(com.droiddeck.launcher.session.Onboarding.Step.RUNTIME, LinuxRuntimeInstaller.removalError() ?: "")
|
||||
else com.droiddeck.launcher.session.Onboarding.finish(com.droiddeck.launcher.session.Onboarding.Step.RUNTIME)
|
||||
}
|
||||
com.droiddeck.launcher.session.Onboarding.recheck(this)
|
||||
ui.post {
|
||||
busy = false
|
||||
if (ok != null) failed = !ok
|
||||
@@ -3450,7 +3465,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
}
|
||||
refresh()
|
||||
com.droiddeck.launcher.agent.AgentHost.refresh(this)
|
||||
if (ok == true && LinuxRuntime.isInstalled(this)) protons.checkUpdates()
|
||||
if (ok == true && LinuxRuntime.isInstalled(this)) { protons.checkUpdates(); protons.ensureSteamClient() }
|
||||
}
|
||||
}, "runtime-operation").start()
|
||||
}
|
||||
@@ -3461,9 +3476,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
if (installed != null) com.droiddeck.launcher.runtime.RuntimeAutoUpdate.seed(this)
|
||||
if (release.version == installed) return
|
||||
if (installed == null && (OfflineMode.enabled(this) || !com.droiddeck.launcher.core.DeviceSupport.canDraw(this) ||
|
||||
!com.droiddeck.launcher.frontend.AutoComponents.online(this) || com.droiddeck.launcher.frontend.AutoComponents.unfavourable(this))) return
|
||||
!com.droiddeck.launcher.frontend.AutoComponents.online(this) || com.droiddeck.launcher.frontend.AutoComponents.firstRunHeldBack(this))) return
|
||||
if (com.droiddeck.launcher.runtime.RuntimeAutoUpdate.claim(this, installed, release.version)) {
|
||||
Log.i(TAG, "runtime: installing ${release.version} over ${installed ?: "nothing"} by itself")
|
||||
if (installed == null) protons.prefetchOwn()
|
||||
install(release)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,9 @@ import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import com.droiddeck.launcher.session.ExperimentalProtons
|
||||
import com.droiddeck.launcher.session.Onboarding
|
||||
import com.droiddeck.launcher.session.ProtonExtras
|
||||
import com.droiddeck.launcher.session.SteamClientPrefetch
|
||||
import com.droiddeck.launcher.ui.ProtonRow
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import com.droiddeck.launcher.session.SessionPhase
|
||||
@@ -60,10 +62,15 @@ internal class ProtonMenu(
|
||||
Thread({
|
||||
val problem = runCatching {
|
||||
installer(tool) { label, value ->
|
||||
if (tool.id == ProtonExtras.OWN) Onboarding.report(Onboarding.Step.PROTON, label, value)
|
||||
ui.post { protonStage = label; protonPercent = value }
|
||||
}
|
||||
}.getOrElse { it.message ?: it.javaClass.simpleName }
|
||||
if (problem == null && !automatic && tool.id == ProtonExtras.OWN) ProtonExtras.setDeclined(activity, false)
|
||||
if (tool.id == ProtonExtras.OWN) {
|
||||
if (problem == null) Onboarding.finish(Onboarding.Step.PROTON) else Onboarding.fail(Onboarding.Step.PROTON, problem)
|
||||
Onboarding.recheck(activity)
|
||||
}
|
||||
ui.post {
|
||||
protonProblem = problem
|
||||
protonBusyId = null
|
||||
@@ -170,16 +177,46 @@ internal class ProtonMenu(
|
||||
Operation.checking.set(false)
|
||||
}
|
||||
ensureAutoUpdates()
|
||||
ensureSteamClient()
|
||||
}
|
||||
if (!published) Operation.checking.set(false)
|
||||
}, "proton-updates").start()
|
||||
}
|
||||
|
||||
/** Downloads the DroidDeck Proton archive while the runtime installs; the install step later finds it whole. */
|
||||
fun prefetchOwn() {
|
||||
val tool = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }
|
||||
if (ProtonExtras.declined(activity) || ProtonExtras.installedAll(activity, tool).isNotEmpty() ||
|
||||
ProtonExtras.installInProgress || !AutoComponents.online(activity) || AutoComponents.firstRunHeldBack(activity)) return
|
||||
Thread({
|
||||
val problem = runCatching {
|
||||
ProtonExtras.prefetch(activity, tool) { label, value -> Onboarding.report(Onboarding.Step.PROTON, label, value) }
|
||||
}.getOrElse { it.message ?: it.javaClass.simpleName }
|
||||
if (problem == null) Onboarding.finish(Onboarding.Step.PROTON) else Onboarding.fail(Onboarding.Step.PROTON, problem)
|
||||
Onboarding.recheck(activity)
|
||||
ui.post { ensureAutoUpdates() }
|
||||
}, "proton-prefetch").start()
|
||||
}
|
||||
|
||||
/** Fetches Steam's client in the background once the runtime exists, so the first Play does not wait for it. */
|
||||
fun ensureSteamClient() {
|
||||
if (activity.isFinishing || activity.isDestroyed || !idle() || SessionState.running || LinuxRuntimeInstaller.isBusy() ||
|
||||
SessionState.phase !in setOf(SessionPhase.IDLE, SessionPhase.FAILED) || !LinuxRuntime.isInstalled(activity) ||
|
||||
!AutoComponents.online(activity) || AutoComponents.firstRunHeldBack(activity) || SteamClientPrefetch.running()) return
|
||||
SteamClientPrefetch.start(
|
||||
activity,
|
||||
{ mb -> activity.getString(if (mb > 0) R.string.onboarding_steam_downloading_mb else R.string.onboarding_steam_downloading, mb) },
|
||||
activity.getString(R.string.onboarding_steam_failed),
|
||||
)
|
||||
}
|
||||
|
||||
internal fun ensureAutoUpdates(now: Long = System.currentTimeMillis()) {
|
||||
if (activity.isFinishing || activity.isDestroyed || !idle() || protonBusyId != null ||
|
||||
ProtonExtras.installInProgress || SessionState.running || LinuxRuntimeInstaller.isBusy() ||
|
||||
ProtonExtras.installInProgress || ProtonExtras.prefetching || SessionState.running || LinuxRuntimeInstaller.isBusy() ||
|
||||
SessionState.phase !in setOf(SessionPhase.IDLE, SessionPhase.FAILED) ||
|
||||
!LinuxRuntime.isInstalled(activity) || !AutoComponents.online(activity) || AutoComponents.unfavourable(activity)) return
|
||||
!LinuxRuntime.isInstalled(activity) || !AutoComponents.online(activity)) return
|
||||
val firstInstall = !ProtonExtras.declined(activity) && ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == ProtonExtras.OWN }).isEmpty()
|
||||
if (if (firstInstall) AutoComponents.firstRunHeldBack(activity) else AutoComponents.unfavourable(activity)) return
|
||||
if (ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == ProtonExtras.OWN }).size > 1) {
|
||||
protonBusyId = ProtonExtras.OWN
|
||||
protonProblem = null
|
||||
|
||||
@@ -154,6 +154,8 @@ import com.droiddeck.launcher.session.ComponentsManager
|
||||
import com.droiddeck.launcher.session.LatestRequestCoordinator
|
||||
import com.droiddeck.launcher.ui.SessionDrawerPage
|
||||
import com.droiddeck.launcher.ui.sessionDrawerPages
|
||||
import com.droiddeck.launcher.ui.strip
|
||||
import com.droiddeck.launcher.ui.tabFor
|
||||
import com.droiddeck.launcher.ui.step
|
||||
import kotlin.math.abs
|
||||
|
||||
@@ -594,6 +596,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
private var backHold by mutableStateOf(true)
|
||||
private var dockedMenuController by mutableStateOf(false)
|
||||
private var sessionOrientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE)
|
||||
private var dualScreenSessionMode by mutableStateOf(com.droiddeck.launcher.input.DualScreen.MODE_AUTO)
|
||||
private var backActionsInverted by mutableStateOf(false)
|
||||
private var backDoubleTapMs by mutableStateOf(500)
|
||||
private var lowLatency by mutableStateOf(true)
|
||||
@@ -933,11 +936,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
}
|
||||
SteamControllerBle.listener = { uiHandler.post { updatePadMotion(); refreshControls() } }
|
||||
steamController = SteamControllerBle(this, inputRouter).also { it.start() }
|
||||
if (Build.VERSION.SDK_INT >= 31 && checkSelfPermission(BLUETOOTH_CONNECT) != android.content.pm.PackageManager.PERMISSION_GRANTED &&
|
||||
!SessionPrefs.bluetoothAsked(this)) {
|
||||
SessionPrefs.setBluetoothAsked(this)
|
||||
requestPermissions(arrayOf(BLUETOOTH_CONNECT), REQUEST_BLUETOOTH)
|
||||
}
|
||||
padMotion = com.droiddeck.launcher.input.PadMotion(this) {
|
||||
@Suppress("DEPRECATION")
|
||||
(if (Build.VERSION.SDK_INT >= 30) display else windowManager.defaultDisplay)?.rotation ?: android.view.Surface.ROTATION_0
|
||||
@@ -1535,6 +1533,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
fexPreset = fexPreset,
|
||||
secondScreenMode = secondScreenMode,
|
||||
secondScreenNone = !bottomOutputActive && !dockDrawer(),
|
||||
dualScreenMode = dualScreenSessionMode,
|
||||
onDualScreenMode = ::chooseDualScreenSessionMode,
|
||||
gameOnBottom = bottomOutputActive,
|
||||
gameSwapAvailable = bottomSwapAvailable,
|
||||
gameSwapBuiltIn = !::displayManager.isInitialized || displayManager.getDisplay(selectedSecondScreenDisplay)
|
||||
@@ -2659,6 +2659,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
backHold = SessionPrefs.backHold(this)
|
||||
dockedMenuController = SessionPrefs.dockedMenuController(this)
|
||||
sessionOrientation = SessionPrefs.orientation(this)
|
||||
dualScreenSessionMode = SessionPrefs.dualScreenSessionMode(this)
|
||||
backActionsInverted = SessionPrefs.backActionsInverted(this)
|
||||
physicalShortcuts.bindings = PhysicalShortcuts.read(this)
|
||||
backDoubleTapMs = SessionPrefs.backDoubleTapMs(this)
|
||||
@@ -3664,8 +3665,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
if (drawerOpen && (menuOwnsController || (!fromController && !(dockedTouchOnly && event.keyCode == KeyEvent.KEYCODE_BACK)))) {
|
||||
if (fromController && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) {
|
||||
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
|
||||
drawerPage = sessionDrawerPages(glasses.present)
|
||||
.step(drawerPage, if (event.keyCode == KeyEvent.KEYCODE_BUTTON_R1) 1 else -1)
|
||||
// The bumpers walk the tabs on the strip; a page kept inside More counts as the More tab.
|
||||
val pages = sessionDrawerPages(glasses.present)
|
||||
drawerPage = pages.strip().step(pages.tabFor(drawerPage), if (event.keyCode == KeyEvent.KEYCODE_BUTTON_R1) 1 else -1)
|
||||
releaseDrawerDirection()
|
||||
}
|
||||
return true
|
||||
@@ -4396,6 +4398,27 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
} else if (wanted != secondScreenMode) selectSecondScreenMode(wanted) else secondScreenPresentation?.retryTerminal()
|
||||
}
|
||||
|
||||
private fun chooseDualScreenSessionMode(mode: String) {
|
||||
if (mode !in com.droiddeck.launcher.input.DualScreen.modes || mode == dualScreenSessionMode) return
|
||||
SessionPrefs.setDualScreenSessionMode(this, mode)
|
||||
dualScreenSessionMode = mode
|
||||
SessionState.secondScreenAutoOpened = false
|
||||
val menuOnBottom = drawerDocked
|
||||
val menuOnTop = drawerOpenState && !drawerDocked
|
||||
if (mode == com.droiddeck.launcher.input.DualScreen.MODE_OFF) {
|
||||
if (gameOnBottom) putGameOnBottom(false)
|
||||
if (secondScreenMode != SecondScreenMode.NONE || menuOnBottom) closeSecondScreen(reset = true)
|
||||
if (menuOnBottom) drawerOpen = true
|
||||
} else if (menuOnTop) {
|
||||
// The menu moves to the second screen as the menu itself, not as one of the control panels.
|
||||
SessionState.secondScreenAutoOpened = true
|
||||
refreshSecondScreenDisplays()
|
||||
pinDockedMenu()
|
||||
return
|
||||
}
|
||||
refreshSecondScreenDisplays()
|
||||
}
|
||||
|
||||
private fun selectSecondScreenDisplay(displayId: Int) {
|
||||
if (secondScreenDisplays.none { it.id == displayId }) return
|
||||
selectedSecondScreenDisplay = displayId
|
||||
@@ -5958,7 +5981,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
if (secondScreenPresentation == null) showSecondScreen(secondScreenMode)
|
||||
if (com.droiddeck.launcher.input.DualScreen.menuReturnsOnStart(openingPanel(), SessionState.bottomMenu, menuShownOnBottom())) pinDockedMenu()
|
||||
SessionState.bottomMenu = false
|
||||
} else openDualScreenControls()
|
||||
} else {
|
||||
if (SessionState.bottomMenu && !menuShownOnBottom()) pinDockedMenu()
|
||||
SessionState.bottomMenu = false
|
||||
if (!menuShownOnBottom()) openDualScreenControls()
|
||||
}
|
||||
startedScreens++
|
||||
SessionService.setActivityVisible(this, true, sessionActivityDisplayId)
|
||||
Glasses.rescan()
|
||||
|
||||
@@ -16,7 +16,7 @@ object SteamIntegration {
|
||||
const val EXTRA_FEATURE = "integration_feature"
|
||||
const val SHORTCUTS_STATUS = "com.droiddeck.launcher.SHORTCUTS_INSTALL_STATUS"
|
||||
private const val SHORTCUTS_ASSET = "shortcuts.apk"
|
||||
enum class Feature { WIFI, BRIGHTNESS, HOME, SHORTCUTS }
|
||||
enum class Feature { WIFI, BRIGHTNESS, HOME, SHORTCUTS, BLUETOOTH }
|
||||
|
||||
data class State(
|
||||
val wifi: Boolean = false,
|
||||
@@ -28,6 +28,7 @@ object SteamIntegration {
|
||||
val shortcuts: Boolean = false,
|
||||
val shortcutsRestricted: Boolean = false,
|
||||
val shortcutsTried: Boolean = false,
|
||||
val bluetooth: Boolean = false,
|
||||
val suggested: Boolean = true,
|
||||
)
|
||||
|
||||
@@ -39,9 +40,16 @@ object SteamIntegration {
|
||||
home = HomeApp.isDefault(context),
|
||||
shortcuts = shortcutsEnabled(context) && shortcutsCurrent(context),
|
||||
shortcutsRestricted = restrictedSettings(context),
|
||||
bluetooth = bluetoothAllowed(context),
|
||||
suggested = !SessionPrefs.sessionPrefs(context).getBoolean("steam_integration_seen", false),
|
||||
)
|
||||
|
||||
fun bluetoothAllowed(context: Context): Boolean =
|
||||
android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.S ||
|
||||
context.checkSelfPermission(android.Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED
|
||||
|
||||
fun appInfo(context: Context) = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:${context.packageName}"))
|
||||
|
||||
private fun restrictedSettings(context: Context): Boolean {
|
||||
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.TIRAMISU) return false
|
||||
val mode = runCatching {
|
||||
|
||||
@@ -47,6 +47,7 @@ object AutoComponents {
|
||||
{ c, comp, all, progress -> WinComponents.install(c, comp, all, progress) }
|
||||
@VisibleForTesting internal var sessionRunning: () -> Boolean = { SessionState.running }
|
||||
@VisibleForTesting internal var unfavourable: (Context) -> Boolean = { c -> constrained(c) }
|
||||
@VisibleForTesting internal var firstRunHeldBack: (Context) -> Boolean = { c -> powerSaveOrMetered(c) }
|
||||
@VisibleForTesting internal var online: (Context) -> Boolean = { c -> isOnline(c) }
|
||||
@VisibleForTesting @Volatile internal var runNow = false
|
||||
|
||||
@@ -533,6 +534,10 @@ object AutoComponents {
|
||||
caps.hasCapability(android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED)
|
||||
}
|
||||
|
||||
fun powerSaveOrMetered(context: Context): Boolean =
|
||||
context.getSystemService(PowerManager::class.java)?.isPowerSaveMode == true ||
|
||||
context.getSystemService(ConnectivityManager::class.java)?.isActiveNetworkMetered == true
|
||||
|
||||
fun constrained(context: Context): Boolean {
|
||||
val power = context.getSystemService(PowerManager::class.java)
|
||||
if (power?.isPowerSaveMode == true) return true
|
||||
|
||||
@@ -0,0 +1,609 @@
|
||||
package com.droiddeck.launcher.input.bt
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.bluetooth.BluetoothAdapter
|
||||
import android.bluetooth.BluetoothDevice
|
||||
import android.bluetooth.BluetoothGatt
|
||||
import android.bluetooth.BluetoothGattCallback
|
||||
import android.bluetooth.BluetoothGattCharacteristic
|
||||
import android.bluetooth.BluetoothGattDescriptor
|
||||
import android.bluetooth.BluetoothGattServer
|
||||
import android.bluetooth.BluetoothGattServerCallback
|
||||
import android.bluetooth.BluetoothGattService
|
||||
import android.bluetooth.BluetoothManager
|
||||
import android.bluetooth.BluetoothProfile
|
||||
import android.bluetooth.le.AdvertiseData
|
||||
import android.bluetooth.le.AdvertisingSet
|
||||
import android.bluetooth.le.AdvertisingSetCallback
|
||||
import android.bluetooth.le.AdvertisingSetParameters
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.os.Build
|
||||
import android.os.Handler
|
||||
import android.os.HandlerThread
|
||||
import android.os.ParcelUuid
|
||||
import android.os.SystemClock
|
||||
import android.os.VibrationEffect
|
||||
import android.os.Vibrator
|
||||
import android.util.Log
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import java.util.ArrayDeque
|
||||
import java.util.UUID
|
||||
|
||||
@SuppressLint("MissingPermission")
|
||||
object BtGamepad {
|
||||
enum class Phase { OFF, STARTING, BLUETOOTH_OFF, UNSUPPORTED, READY, CONNECTING, CONNECTED }
|
||||
|
||||
data class Status(val phase: Phase, val host: String? = null, val lightbar: Int? = null, val name: String? = null)
|
||||
|
||||
private const val TAG = "BtGamepad"
|
||||
|
||||
private val _status = MutableStateFlow(Status(Phase.OFF))
|
||||
val status: StateFlow<Status> = _status
|
||||
|
||||
private var handler: Handler? = null
|
||||
private var app: Context? = null
|
||||
private var server: BluetoothGattServer? = null
|
||||
private var advertising = false
|
||||
private var profile = BtPadProfile.GENERIC
|
||||
private var encoder: BtPadEncoder = profile.encoder()
|
||||
private val pendingServices = ArrayDeque<BluetoothGattService>()
|
||||
private val reportRefs = HashMap<BluetoothGattCharacteristic, Pair<Int, Int>>()
|
||||
private val inputChars = HashMap<Int, BluetoothGattCharacteristic>()
|
||||
private val longReads = HashMap<Pair<String, BluetoothGattCharacteristic>, ByteArray>()
|
||||
private val preparedWrites = HashMap<BluetoothGattCharacteristic, ByteArray>()
|
||||
private var host: BluetoothDevice? = null
|
||||
private var priorityLink: BluetoothGatt? = null
|
||||
private var notifyPending = false
|
||||
private var dirty = false
|
||||
private var mtu = 23
|
||||
private val latest = BtPadState()
|
||||
private val sent = BtPadState()
|
||||
private var sentOnce = false
|
||||
private var vibrator: Vibrator? = null
|
||||
@Volatile private var running = false
|
||||
private var pairingUntil = 0L
|
||||
private var pendingHost: BluetoothDevice? = null
|
||||
private var fastLinkPending = false
|
||||
private var notifiedAt = 0L
|
||||
private const val NOTIFY_TIMEOUT_MS = 100L
|
||||
private const val PAIRING_WINDOW_MS = 120_000L
|
||||
private const val MAX_MTU = 517
|
||||
private const val FAST_LINK_DELAY_MS = 1_500L
|
||||
|
||||
fun start(context: Context, p: BtPadProfile) {
|
||||
val h = handler ?: init(context)
|
||||
h.post {
|
||||
running = true
|
||||
if (server != null && p == profile) {
|
||||
val attached = host
|
||||
if (attached != null) publish(Phase.CONNECTED, attached) else publish(Phase.READY)
|
||||
startAdvertising()
|
||||
} else {
|
||||
close()
|
||||
profile = p
|
||||
publish(Phase.STARTING)
|
||||
open()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun init(context: Context): Handler {
|
||||
val ctx = context.applicationContext
|
||||
app = ctx
|
||||
vibrator = ctx.getSystemService(Vibrator::class.java)
|
||||
val t = HandlerThread("bt-gamepad").apply { start() }
|
||||
val h = Handler(t.looper)
|
||||
handler = h
|
||||
val receiver = object : BroadcastReceiver() {
|
||||
override fun onReceive(c: Context, intent: Intent) {
|
||||
when (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1)) {
|
||||
BluetoothAdapter.STATE_ON -> h.post { if (running) open() }
|
||||
BluetoothAdapter.STATE_TURNING_OFF, BluetoothAdapter.STATE_OFF -> h.post {
|
||||
close()
|
||||
publish(Phase.BLUETOOTH_OFF)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ctx.registerReceiver(receiver, IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED), null, h)
|
||||
val bonds = object : BroadcastReceiver() {
|
||||
override fun onReceive(c: Context, intent: Intent) {
|
||||
if (intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, -1) != BluetoothDevice.BOND_BONDED) return
|
||||
h.post {
|
||||
val waiting = pendingHost ?: return@post
|
||||
if (waiting.bondState == BluetoothDevice.BOND_BONDED) attach(waiting)
|
||||
}
|
||||
}
|
||||
}
|
||||
ctx.registerReceiver(bonds, IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED), null, h)
|
||||
return h
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
val h = handler ?: return
|
||||
h.post {
|
||||
running = false
|
||||
rumble(0, 0)
|
||||
pairingUntil = 0
|
||||
keepScanning()
|
||||
stopAdvertising()
|
||||
h.removeCallbacks(periodic)
|
||||
dropFastLink()
|
||||
pendingHost?.let { d -> runCatching { server?.cancelConnection(d) } }
|
||||
pendingHost = null
|
||||
host?.let { d -> runCatching { server?.cancelConnection(d) } }
|
||||
host = null
|
||||
longReads.clear()
|
||||
_status.value = Status(Phase.OFF)
|
||||
}
|
||||
}
|
||||
|
||||
fun switchProfile(p: BtPadProfile) {
|
||||
val h = handler ?: return
|
||||
h.post {
|
||||
if (p == profile && server != null) return@post
|
||||
profile = p
|
||||
close()
|
||||
publish(Phase.STARTING)
|
||||
h.postDelayed(::open, 300)
|
||||
}
|
||||
}
|
||||
|
||||
fun update(s: BtPadState) {
|
||||
val h = handler ?: return
|
||||
synchronized(latest) { latest.set(s) }
|
||||
h.post(::sendIfChanged)
|
||||
}
|
||||
|
||||
fun openPairingWindow() {
|
||||
val h = handler ?: return
|
||||
h.post {
|
||||
pairingUntil = System.currentTimeMillis() + PAIRING_WINDOW_MS
|
||||
keepScanning()
|
||||
if (host == null) {
|
||||
stopAdvertising()
|
||||
startAdvertising()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun keepScanning() {
|
||||
val adapter = adapter() ?: return
|
||||
val h = handler ?: return
|
||||
h.removeCallbacks(scanTick)
|
||||
if (host != null || System.currentTimeMillis() > pairingUntil) {
|
||||
runCatching { if (adapter.isDiscovering) adapter.cancelDiscovery() }
|
||||
return
|
||||
}
|
||||
runCatching { if (!adapter.isDiscovering) adapter.startDiscovery() }
|
||||
h.postDelayed(scanTick, 2_000)
|
||||
}
|
||||
|
||||
private val scanTick = Runnable { keepScanning() }
|
||||
|
||||
fun disconnect() {
|
||||
handler?.post { host?.let { d -> server?.cancelConnection(d) } }
|
||||
}
|
||||
|
||||
private fun manager() = app?.getSystemService(Context.BLUETOOTH_SERVICE) as? BluetoothManager
|
||||
|
||||
private fun adapter(): BluetoothAdapter? = manager()?.adapter
|
||||
|
||||
private fun open() {
|
||||
val ctx = app ?: return
|
||||
if (server != null || !running) return
|
||||
val manager = manager()
|
||||
val adapter = manager?.adapter
|
||||
if (adapter == null || !ctx.packageManager.hasSystemFeature("android.hardware.bluetooth_le")) {
|
||||
publish(Phase.UNSUPPORTED)
|
||||
return
|
||||
}
|
||||
if (!adapter.isEnabled) {
|
||||
publish(Phase.BLUETOOTH_OFF)
|
||||
return
|
||||
}
|
||||
if (adapter.bluetoothLeAdvertiser == null) {
|
||||
publish(Phase.UNSUPPORTED)
|
||||
return
|
||||
}
|
||||
encoder = profile.encoder()
|
||||
sentOnce = false
|
||||
val s = runCatching { manager.openGattServer(ctx, serverCallback) }
|
||||
.onFailure { Log.w(TAG, "no GATT server", it) }.getOrNull()
|
||||
if (s == null) {
|
||||
publish(Phase.UNSUPPORTED)
|
||||
return
|
||||
}
|
||||
server = s
|
||||
pendingServices.clear()
|
||||
pendingServices.add(deviceInfoService())
|
||||
pendingServices.add(hidService())
|
||||
addNextService()
|
||||
}
|
||||
|
||||
private fun close() {
|
||||
stopAdvertising()
|
||||
pairingUntil = 0
|
||||
keepScanning()
|
||||
dropFastLink()
|
||||
server?.let { s ->
|
||||
runCatching { manager()?.getConnectedDevices(BluetoothProfile.GATT_SERVER)?.forEach { s.cancelConnection(it) } }
|
||||
runCatching { s.clearServices(); s.close() }
|
||||
}
|
||||
server = null
|
||||
host = null
|
||||
pendingHost = null
|
||||
notifyPending = false
|
||||
dirty = false
|
||||
reportRefs.clear()
|
||||
inputChars.clear()
|
||||
longReads.clear()
|
||||
preparedWrites.clear()
|
||||
}
|
||||
|
||||
private fun addNextService() {
|
||||
val s = server ?: return
|
||||
val next = pendingServices.pollFirst()
|
||||
if (next == null) {
|
||||
Log.i(TAG, "${profile.id}: services ready")
|
||||
startAdvertising()
|
||||
return
|
||||
}
|
||||
if (!s.addService(next)) {
|
||||
Log.w(TAG, "addService ${next.uuid} refused")
|
||||
publish(Phase.UNSUPPORTED)
|
||||
}
|
||||
}
|
||||
|
||||
private fun deviceInfoService(): BluetoothGattService {
|
||||
val service = BluetoothGattService(uuid16(0x180A), BluetoothGattService.SERVICE_TYPE_PRIMARY)
|
||||
val pnp = BtPadEncoder.bytes(0x02, profile.vendorId and 0xFF, profile.vendorId shr 8,
|
||||
profile.productId and 0xFF, profile.productId shr 8, profile.version and 0xFF, profile.version shr 8)
|
||||
service.addCharacteristic(readOnly(0x2A50, pnp))
|
||||
service.addCharacteristic(readOnly(0x2A29, "DroidDeck".toByteArray()))
|
||||
return service
|
||||
}
|
||||
|
||||
private fun hidService(): BluetoothGattService {
|
||||
val service = BluetoothGattService(uuid16(0x1812), BluetoothGattService.SERVICE_TYPE_PRIMARY)
|
||||
service.addCharacteristic(readOnly(0x2A4A, BtPadEncoder.bytes(0x11, 0x01, 0x00, 0x02)))
|
||||
service.addCharacteristic(readOnly(0x2A4B, encoder.descriptor))
|
||||
service.addCharacteristic(BluetoothGattCharacteristic(uuid16(0x2A4C),
|
||||
BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE, BluetoothGattCharacteristic.PERMISSION_WRITE))
|
||||
for ((id, type) in encoder.reports) {
|
||||
val props = when (type) {
|
||||
BtPadEncoder.INPUT -> BluetoothGattCharacteristic.PROPERTY_READ or BluetoothGattCharacteristic.PROPERTY_NOTIFY
|
||||
BtPadEncoder.OUTPUT -> BluetoothGattCharacteristic.PROPERTY_READ or BluetoothGattCharacteristic.PROPERTY_WRITE or
|
||||
BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE
|
||||
else -> BluetoothGattCharacteristic.PROPERTY_READ or BluetoothGattCharacteristic.PROPERTY_WRITE
|
||||
}
|
||||
val chr = BluetoothGattCharacteristic(uuid16(0x2A4D), props,
|
||||
BluetoothGattCharacteristic.PERMISSION_READ or BluetoothGattCharacteristic.PERMISSION_WRITE)
|
||||
if (type == BtPadEncoder.INPUT) {
|
||||
chr.addDescriptor(cccd())
|
||||
inputChars[id] = chr
|
||||
}
|
||||
val ref = BluetoothGattDescriptor(uuid16(0x2908), BluetoothGattDescriptor.PERMISSION_READ)
|
||||
@Suppress("DEPRECATION")
|
||||
ref.value = BtPadEncoder.bytes(id, type)
|
||||
chr.addDescriptor(ref)
|
||||
reportRefs[chr] = id to type
|
||||
service.addCharacteristic(chr)
|
||||
}
|
||||
return service
|
||||
}
|
||||
|
||||
private fun readOnly(uuid: Int, value: ByteArray): BluetoothGattCharacteristic {
|
||||
val chr = BluetoothGattCharacteristic(uuid16(uuid), BluetoothGattCharacteristic.PROPERTY_READ, BluetoothGattCharacteristic.PERMISSION_READ)
|
||||
@Suppress("DEPRECATION")
|
||||
chr.value = value
|
||||
return chr
|
||||
}
|
||||
|
||||
private fun cccd() = BluetoothGattDescriptor(uuid16(0x2902),
|
||||
BluetoothGattDescriptor.PERMISSION_READ or BluetoothGattDescriptor.PERMISSION_WRITE)
|
||||
|
||||
private fun uuid16(v: Int): UUID = UUID.fromString("%08x-0000-1000-8000-00805f9b34fb".format(v))
|
||||
|
||||
private fun startAdvertising() {
|
||||
val advertiser = adapter()?.bluetoothLeAdvertiser ?: return
|
||||
if (advertising || server == null || host != null || !running) return
|
||||
val params = AdvertisingSetParameters.Builder()
|
||||
.setLegacyMode(true)
|
||||
.setConnectable(true)
|
||||
.setScannable(true)
|
||||
.setInterval(AdvertisingSetParameters.INTERVAL_LOW)
|
||||
.setTxPowerLevel(AdvertisingSetParameters.TX_POWER_HIGH)
|
||||
.build()
|
||||
val data = AdvertiseData.Builder()
|
||||
.addServiceUuid(ParcelUuid(uuid16(0x1812)))
|
||||
.setIncludeDeviceName(true)
|
||||
.build()
|
||||
advertising = runCatching { advertiser.startAdvertisingSet(params, data, null, null, null, advertiseCallback); true }
|
||||
.onFailure { Log.w(TAG, "advertising refused", it) }.getOrDefault(false)
|
||||
if (!advertising) publish(Phase.UNSUPPORTED)
|
||||
}
|
||||
|
||||
private fun stopAdvertising() {
|
||||
if (!advertising) return
|
||||
advertising = false
|
||||
runCatching { adapter()?.bluetoothLeAdvertiser?.stopAdvertisingSet(advertiseCallback) }
|
||||
}
|
||||
|
||||
private val advertiseCallback = object : AdvertisingSetCallback() {
|
||||
override fun onAdvertisingSetStarted(set: AdvertisingSet?, txPower: Int, status: Int) {
|
||||
Log.i(TAG, "advertising status $status")
|
||||
handler?.post {
|
||||
if (status == ADVERTISE_SUCCESS) {
|
||||
if (host == null) publish(Phase.READY)
|
||||
} else {
|
||||
advertising = false
|
||||
publish(Phase.UNSUPPORTED)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private val serverCallback = object : BluetoothGattServerCallback() {
|
||||
override fun onServiceAdded(status: Int, service: BluetoothGattService) {
|
||||
handler?.post {
|
||||
if (status != BluetoothGatt.GATT_SUCCESS) {
|
||||
Log.w(TAG, "service ${service.uuid} failed: $status")
|
||||
publish(Phase.UNSUPPORTED)
|
||||
} else addNextService()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onConnectionStateChange(device: BluetoothDevice, status: Int, newState: Int) {
|
||||
handler?.post {
|
||||
Log.i(TAG, "${device.address}: state $newState status $status bond ${device.bondState}")
|
||||
if (newState == BluetoothProfile.STATE_CONNECTED) {
|
||||
stopAdvertising()
|
||||
if (!running) {
|
||||
server?.cancelConnection(device)
|
||||
return@post
|
||||
}
|
||||
mtu = 23
|
||||
if (device.bondState == BluetoothDevice.BOND_BONDED) attach(device)
|
||||
else if (host == null) publish(Phase.CONNECTING, device)
|
||||
} else if (newState == BluetoothProfile.STATE_DISCONNECTED && pendingHost == device && host == null) {
|
||||
pendingHost = null
|
||||
publish(Phase.READY)
|
||||
startAdvertising()
|
||||
} else if (newState == BluetoothProfile.STATE_DISCONNECTED && host == device) {
|
||||
host = null
|
||||
rumble(0, 0)
|
||||
dropFastLink()
|
||||
publish(Phase.READY)
|
||||
startAdvertising()
|
||||
} else if (newState == BluetoothProfile.STATE_DISCONNECTED && host == null) {
|
||||
publish(Phase.READY)
|
||||
startAdvertising()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onMtuChanged(device: BluetoothDevice, newMtu: Int) {
|
||||
handler?.post {
|
||||
mtu = newMtu
|
||||
Log.i(TAG, "mtu $newMtu")
|
||||
}
|
||||
}
|
||||
|
||||
override fun onCharacteristicReadRequest(device: BluetoothDevice, requestId: Int, offset: Int, chr: BluetoothGattCharacteristic) {
|
||||
handler?.post {
|
||||
val key = device.address to chr
|
||||
val value = if (offset > 0) longReads[key] ?: valueOf(chr, device) else valueOf(chr, device).also { longReads[key] = it }
|
||||
val reply = if (offset >= value.size) ByteArray(0) else value.copyOfRange(offset, value.size)
|
||||
server?.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, reply)
|
||||
if (chr.uuid == uuid16(0x2A4B)) attach(device)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onDescriptorReadRequest(device: BluetoothDevice, requestId: Int, offset: Int, descriptor: BluetoothGattDescriptor) {
|
||||
handler?.post {
|
||||
@Suppress("DEPRECATION")
|
||||
val value = descriptor.value ?: if (descriptor.uuid == uuid16(0x2902)) BtPadEncoder.bytes(1, 0) else ByteArray(0)
|
||||
val reply = if (offset >= value.size) ByteArray(0) else value.copyOfRange(offset, value.size)
|
||||
server?.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, reply)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onDescriptorWriteRequest(device: BluetoothDevice, requestId: Int, descriptor: BluetoothGattDescriptor,
|
||||
preparedWrite: Boolean, responseNeeded: Boolean, offset: Int, value: ByteArray) {
|
||||
handler?.post {
|
||||
if (responseNeeded) server?.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, value)
|
||||
if (descriptor.uuid == uuid16(0x2902) && descriptor.characteristic in reportRefs && value.isNotEmpty() &&
|
||||
value[0].toInt() and 1 != 0) {
|
||||
attach(device)
|
||||
handler?.postDelayed({ startFastLink(device) }, FAST_LINK_DELAY_MS)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onCharacteristicWriteRequest(device: BluetoothDevice, requestId: Int, chr: BluetoothGattCharacteristic,
|
||||
preparedWrite: Boolean, responseNeeded: Boolean, offset: Int, value: ByteArray) {
|
||||
handler?.post {
|
||||
if (device == host && preparedWrite) {
|
||||
val old = preparedWrites[chr] ?: ByteArray(0)
|
||||
val merged = old.copyOf(maxOf(old.size, offset + value.size))
|
||||
value.copyInto(merged, offset)
|
||||
preparedWrites[chr] = merged
|
||||
} else if (device == host) written(chr, value)
|
||||
if (responseNeeded) server?.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, value)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onExecuteWrite(device: BluetoothDevice, requestId: Int, execute: Boolean) {
|
||||
handler?.post {
|
||||
if (execute && device == host) preparedWrites.forEach { (chr, v) -> written(chr, v) }
|
||||
preparedWrites.clear()
|
||||
server?.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, 0, null)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onNotificationSent(device: BluetoothDevice, status: Int) {
|
||||
handler?.post {
|
||||
notifyPending = false
|
||||
if (dirty) sendNow()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun valueOf(chr: BluetoothGattCharacteristic, device: BluetoothDevice): ByteArray {
|
||||
val ref = reportRefs[chr]
|
||||
if (ref == null) {
|
||||
@Suppress("DEPRECATION")
|
||||
return chr.value ?: ByteArray(0)
|
||||
}
|
||||
val (id, type) = ref
|
||||
return when (type) {
|
||||
BtPadEncoder.INPUT -> if (id == encoder.inputId() && device == host) encoder.input(current()) else ByteArray(0)
|
||||
BtPadEncoder.FEATURE -> {
|
||||
host?.let { d -> handler?.postDelayed({ startFastLink(d) }, FAST_LINK_DELAY_MS) }
|
||||
encoder.feature(id).also { Log.i(TAG, "feature 0x%02x read -> %d".format(id, it?.size ?: -1)) } ?: ByteArray(0)
|
||||
}
|
||||
else -> ByteArray(0)
|
||||
}
|
||||
}
|
||||
|
||||
private fun written(chr: BluetoothGattCharacteristic, value: ByteArray) {
|
||||
val (id, type) = reportRefs[chr] ?: return
|
||||
when (type) {
|
||||
BtPadEncoder.FEATURE -> {
|
||||
Log.i(TAG, "feature 0x%02x write %d bytes".format(id, value.size))
|
||||
encoder.setFeature(id, value)
|
||||
}
|
||||
BtPadEncoder.OUTPUT -> feedback(encoder.output(id, value))
|
||||
}
|
||||
}
|
||||
|
||||
private fun attach(device: BluetoothDevice) {
|
||||
if (host != null || !running) return
|
||||
if (device.bondState != BluetoothDevice.BOND_BONDED) {
|
||||
pendingHost = device
|
||||
publish(Phase.CONNECTING, device)
|
||||
return
|
||||
}
|
||||
pendingHost = null
|
||||
host = device
|
||||
stopAdvertising()
|
||||
pairingUntil = 0
|
||||
keepScanning()
|
||||
sentOnce = false
|
||||
notifyPending = false
|
||||
Log.i(TAG, "host ${device.address} attached")
|
||||
publish(Phase.CONNECTED, device)
|
||||
fastLinkPending = true
|
||||
handler?.removeCallbacks(periodic)
|
||||
handler?.post(periodic)
|
||||
}
|
||||
|
||||
private fun startFastLink(device: BluetoothDevice) {
|
||||
if (host != device || !fastLinkPending) return
|
||||
fastLinkPending = false
|
||||
requestFastLink(device)
|
||||
}
|
||||
|
||||
private fun requestFastLink(device: BluetoothDevice) {
|
||||
val ctx = app ?: return
|
||||
dropFastLink()
|
||||
priorityLink = runCatching {
|
||||
device.connectGatt(ctx, false, object : BluetoothGattCallback() {
|
||||
override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {
|
||||
if (newState == BluetoothProfile.STATE_CONNECTED && !gatt.requestMtu(MAX_MTU)) {
|
||||
gatt.requestConnectionPriority(BluetoothGatt.CONNECTION_PRIORITY_HIGH)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onMtuChanged(gatt: BluetoothGatt, newMtu: Int, status: Int) {
|
||||
handler?.post {
|
||||
if (newMtu > mtu) mtu = newMtu
|
||||
Log.i(TAG, "link mtu $newMtu")
|
||||
}
|
||||
gatt.requestConnectionPriority(BluetoothGatt.CONNECTION_PRIORITY_HIGH)
|
||||
}
|
||||
}, BluetoothDevice.TRANSPORT_LE)
|
||||
}.getOrNull()
|
||||
}
|
||||
|
||||
private fun dropFastLink() {
|
||||
priorityLink?.let { runCatching { it.disconnect(); it.close() } }
|
||||
priorityLink = null
|
||||
}
|
||||
|
||||
private fun current(): BtPadState = BtPadState().also { s -> synchronized(latest) { s.set(latest) } }
|
||||
|
||||
private fun sendIfChanged() {
|
||||
if (encoder.periodMs > 0) return
|
||||
if (sentOnce && current().sameAs(sent)) return
|
||||
sendNow()
|
||||
}
|
||||
|
||||
private fun sendNow() {
|
||||
val s = server ?: return
|
||||
val device = host ?: return
|
||||
if (notifyPending && SystemClock.elapsedRealtime() - notifiedAt < NOTIFY_TIMEOUT_MS) {
|
||||
dirty = true
|
||||
return
|
||||
}
|
||||
val state = current()
|
||||
val (id, value) = encoder.report(state, mtu - 3)
|
||||
val chr = inputChars[id] ?: return
|
||||
val ok = runCatching {
|
||||
if (Build.VERSION.SDK_INT >= 33) {
|
||||
s.notifyCharacteristicChanged(device, chr, false, value) == BluetoothGatt.GATT_SUCCESS
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
chr.value = value
|
||||
@Suppress("DEPRECATION")
|
||||
s.notifyCharacteristicChanged(device, chr, false)
|
||||
}
|
||||
}.getOrDefault(false)
|
||||
dirty = !ok
|
||||
notifyPending = ok
|
||||
notifiedAt = SystemClock.elapsedRealtime()
|
||||
if (ok) {
|
||||
sent.set(state)
|
||||
sentOnce = true
|
||||
}
|
||||
}
|
||||
|
||||
private val periodic: Runnable = object : Runnable {
|
||||
override fun run() {
|
||||
val h = handler ?: return
|
||||
if (host == null) return
|
||||
if (encoder.periodMs > 0 || dirty) sendNow()
|
||||
h.postDelayed(this, if (encoder.periodMs > 0) encoder.periodMs else 50)
|
||||
}
|
||||
}
|
||||
|
||||
private fun feedback(f: BtFeedback?) {
|
||||
f ?: return
|
||||
if (f.strong >= 0) rumble(f.strong, f.weak)
|
||||
if (f.lightbar != null) _status.value = _status.value.copy(lightbar = f.lightbar)
|
||||
}
|
||||
|
||||
private fun rumble(strong: Int, weak: Int) {
|
||||
val v = vibrator ?: return
|
||||
val amplitude = maxOf(strong, weak * 2 / 3).coerceIn(0, 255)
|
||||
runCatching {
|
||||
if (amplitude == 0) v.cancel()
|
||||
else v.vibrate(VibrationEffect.createOneShot(1_000, amplitude))
|
||||
}
|
||||
}
|
||||
|
||||
private fun publish(phase: Phase, device: BluetoothDevice? = null) {
|
||||
if (!running) {
|
||||
_status.value = Status(Phase.OFF)
|
||||
return
|
||||
}
|
||||
val name = device?.let { runCatching { it.name }.getOrNull() ?: it.address }
|
||||
val own = runCatching { adapter()?.name }.getOrNull()
|
||||
_status.value = Status(phase, name, _status.value.lightbar.takeIf { phase == Phase.CONNECTED }, own)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,559 @@
|
||||
package com.droiddeck.launcher.input.bt
|
||||
|
||||
import java.util.zip.CRC32
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
class BtPadState {
|
||||
@JvmField var buttons = 0
|
||||
@JvmField var lx = 0f
|
||||
@JvmField var ly = 0f
|
||||
@JvmField var rx = 0f
|
||||
@JvmField var ry = 0f
|
||||
@JvmField var lt = 0f
|
||||
@JvmField var rt = 0f
|
||||
@JvmField var lpx = 0f
|
||||
@JvmField var lpy = 0f
|
||||
@JvmField var rpx = 0f
|
||||
@JvmField var rpy = 0f
|
||||
|
||||
fun isDown(bit: Int) = buttons and bit != 0
|
||||
|
||||
fun set(other: BtPadState) {
|
||||
buttons = other.buttons; lx = other.lx; ly = other.ly; rx = other.rx; ry = other.ry; lt = other.lt; rt = other.rt
|
||||
lpx = other.lpx; lpy = other.lpy; rpx = other.rpx; rpy = other.rpy
|
||||
}
|
||||
|
||||
fun merge(a: BtPadState, b: BtPadState) {
|
||||
buttons = a.buttons or b.buttons
|
||||
lx = stronger(a.lx, b.lx); ly = stronger(a.ly, b.ly)
|
||||
rx = stronger(a.rx, b.rx); ry = stronger(a.ry, b.ry)
|
||||
lt = maxOf(a.lt, b.lt, if (isDown(LT)) 1f else 0f)
|
||||
rt = maxOf(a.rt, b.rt, if (isDown(RT)) 1f else 0f)
|
||||
val left = if (b.isDown(LPAD_TOUCH)) b else a
|
||||
lpx = left.lpx; lpy = left.lpy
|
||||
val right = if (b.isDown(RPAD_TOUCH)) b else a
|
||||
rpx = right.rpx; rpy = right.rpy
|
||||
}
|
||||
|
||||
fun sameAs(o: BtPadState) = buttons == o.buttons && lx == o.lx && ly == o.ly && rx == o.rx && ry == o.ry && lt == o.lt && rt == o.rt &&
|
||||
lpx == o.lpx && lpy == o.lpy && rpx == o.rpx && rpy == o.rpy
|
||||
|
||||
fun hat(): Int {
|
||||
val x = (if (isDown(RIGHT)) 1 else 0) - (if (isDown(LEFT)) 1 else 0)
|
||||
val y = (if (isDown(DOWN)) 1 else 0) - (if (isDown(UP)) 1 else 0)
|
||||
return when {
|
||||
x == 0 && y == -1 -> 0
|
||||
x == 1 && y == -1 -> 1
|
||||
x == 1 && y == 0 -> 2
|
||||
x == 1 && y == 1 -> 3
|
||||
x == 0 && y == 1 -> 4
|
||||
x == -1 && y == 1 -> 5
|
||||
x == -1 && y == 0 -> 6
|
||||
x == -1 && y == -1 -> 7
|
||||
else -> -1
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val A = 1 shl 0
|
||||
const val B = 1 shl 1
|
||||
const val X = 1 shl 2
|
||||
const val Y = 1 shl 3
|
||||
const val LB = 1 shl 4
|
||||
const val RB = 1 shl 5
|
||||
const val LT = 1 shl 6
|
||||
const val RT = 1 shl 7
|
||||
const val SELECT = 1 shl 8
|
||||
const val START = 1 shl 9
|
||||
const val GUIDE = 1 shl 10
|
||||
const val L3 = 1 shl 11
|
||||
const val R3 = 1 shl 12
|
||||
const val UP = 1 shl 13
|
||||
const val DOWN = 1 shl 14
|
||||
const val LEFT = 1 shl 15
|
||||
const val RIGHT = 1 shl 16
|
||||
const val L4 = 1 shl 17
|
||||
const val R4 = 1 shl 18
|
||||
const val L5 = 1 shl 19
|
||||
const val R5 = 1 shl 20
|
||||
const val TOUCHPAD = 1 shl 21
|
||||
const val SHARE = 1 shl 22
|
||||
const val LPAD_TOUCH = 1 shl 23
|
||||
const val RPAD_TOUCH = 1 shl 24
|
||||
const val LPAD_CLICK = 1 shl 25
|
||||
const val RPAD_CLICK = 1 shl 26
|
||||
|
||||
private fun stronger(a: Float, b: Float) = if (Math.abs(b) > Math.abs(a)) b else a
|
||||
}
|
||||
}
|
||||
|
||||
class BtFeedback(val strong: Int, val weak: Int, val lightbar: Int? = null)
|
||||
|
||||
enum class BtPadProfile(val id: String, val vendorId: Int, val productId: Int, val version: Int) {
|
||||
GENERIC("generic", 0x1209, 0x0001, 0x0100),
|
||||
XBOX("xbox", 0x045E, 0x0B13, 0x0509),
|
||||
DUALSHOCK4("dualshock4", 0x054C, 0x09CC, 0x0100),
|
||||
DUALSENSE("dualsense", 0x054C, 0x0CE6, 0x0100),
|
||||
STEAM("steam", 0x28DE, 0x1303, 0x0100);
|
||||
|
||||
fun encoder(): BtPadEncoder = when (this) {
|
||||
GENERIC -> GenericEncoder()
|
||||
XBOX -> XboxEncoder()
|
||||
DUALSHOCK4 -> DualShock4Encoder()
|
||||
DUALSENSE -> DualSenseEncoder()
|
||||
STEAM -> SteamControllerEncoder()
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun byId(id: String?) = entries.firstOrNull { it.id == id } ?: GENERIC
|
||||
}
|
||||
}
|
||||
|
||||
abstract class BtPadEncoder {
|
||||
abstract val descriptor: ByteArray
|
||||
abstract val reports: List<Pair<Int, Int>>
|
||||
abstract fun inputId(): Int
|
||||
abstract fun input(s: BtPadState): ByteArray
|
||||
open val periodMs = 0L
|
||||
|
||||
open fun report(s: BtPadState, limit: Int): Pair<Int, ByteArray> {
|
||||
val v = input(s)
|
||||
return inputId() to if (v.size > limit) v.copyOf(limit) else v
|
||||
}
|
||||
open fun feature(id: Int): ByteArray? = null
|
||||
open fun setFeature(id: Int, data: ByteArray) {}
|
||||
open fun output(id: Int, data: ByteArray): BtFeedback? = null
|
||||
|
||||
protected fun axis8(v: Float) = ((v.coerceIn(-1f, 1f) + 1f) * 127.5f).roundToInt().coerceIn(0, 255)
|
||||
protected fun trigger8(v: Float) = (v.coerceIn(0f, 1f) * 255f).roundToInt()
|
||||
|
||||
protected fun ByteArray.le16(at: Int, v: Int) { this[at] = v.toByte(); this[at + 1] = (v shr 8).toByte() }
|
||||
protected fun ByteArray.le32(at: Int, v: Long) { for (i in 0 until 4) this[at + i] = (v shr (8 * i)).toByte() }
|
||||
|
||||
protected fun ByteArray.sealCrc(seed: Int, id: Int): ByteArray {
|
||||
val crc = CRC32()
|
||||
crc.update(seed)
|
||||
crc.update(id)
|
||||
crc.update(this, 0, size - 4)
|
||||
le32(size - 4, crc.value)
|
||||
return this
|
||||
}
|
||||
|
||||
|
||||
companion object {
|
||||
const val INPUT = 1
|
||||
const val OUTPUT = 2
|
||||
const val FEATURE = 3
|
||||
|
||||
fun bytes(vararg v: Int) = ByteArray(v.size) { v[it].toByte() }
|
||||
}
|
||||
}
|
||||
|
||||
private class GenericEncoder : BtPadEncoder() {
|
||||
override val reports = listOf(1 to INPUT)
|
||||
|
||||
override val descriptor = bytes(
|
||||
0x05, 0x01, 0x09, 0x05, 0xA1, 0x01, 0x85, 0x01,
|
||||
0x05, 0x09, 0x19, 0x01, 0x29, 0x18, 0x15, 0x00, 0x25, 0x01, 0x75, 0x01, 0x95, 0x18, 0x81, 0x02,
|
||||
0x05, 0x01, 0x09, 0x39, 0x15, 0x00, 0x25, 0x07, 0x35, 0x00, 0x46, 0x3B, 0x01, 0x65, 0x14, 0x75, 0x04, 0x95, 0x01, 0x81, 0x42,
|
||||
0x65, 0x00, 0x75, 0x04, 0x95, 0x01, 0x81, 0x03,
|
||||
0x09, 0x30, 0x09, 0x31, 0x09, 0x32, 0x09, 0x35, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x04, 0x81, 0x02,
|
||||
0x05, 0x02, 0x09, 0xC5, 0x09, 0xC4, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x02, 0x81, 0x02,
|
||||
0xC0,
|
||||
)
|
||||
|
||||
override fun inputId() = 1
|
||||
|
||||
override fun input(s: BtPadState): ByteArray {
|
||||
var b = 0
|
||||
GENERIC_ORDER.forEachIndexed { i, bit -> if (s.isDown(bit)) b = b or (1 shl i) }
|
||||
val hat = s.hat().let { if (it < 0) 8 else it }
|
||||
return bytes(
|
||||
b and 0xFF, (b shr 8) and 0xFF, (b shr 16) and 0xFF, hat,
|
||||
axis8(s.lx), axis8(s.ly), axis8(s.rx), axis8(s.ry), trigger8(s.lt), trigger8(s.rt),
|
||||
)
|
||||
}
|
||||
|
||||
companion object {
|
||||
private val GENERIC_ORDER = intArrayOf(
|
||||
BtPadState.A, BtPadState.B, 0, BtPadState.X, BtPadState.Y, 0, BtPadState.LB, BtPadState.RB,
|
||||
BtPadState.LT, BtPadState.RT, BtPadState.SELECT, BtPadState.START, BtPadState.GUIDE, BtPadState.L3, BtPadState.R3, 0,
|
||||
BtPadState.L4, BtPadState.R4, BtPadState.L5, BtPadState.R5, BtPadState.TOUCHPAD, BtPadState.SHARE, 0, 0,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private class XboxEncoder : BtPadEncoder() {
|
||||
override val reports = listOf(1 to INPUT, 3 to OUTPUT)
|
||||
|
||||
override val descriptor = bytes(
|
||||
0x05, 0x01, 0x09, 0x05, 0xA1, 0x01, 0x85, 0x01,
|
||||
0x09, 0x01, 0xA1, 0x00, 0x09, 0x30, 0x09, 0x31, 0x15, 0x00, 0x27, 0xFF, 0xFF, 0x00, 0x00, 0x95, 0x02, 0x75, 0x10, 0x81, 0x02, 0xC0,
|
||||
0x09, 0x01, 0xA1, 0x00, 0x09, 0x32, 0x09, 0x35, 0x15, 0x00, 0x27, 0xFF, 0xFF, 0x00, 0x00, 0x95, 0x02, 0x75, 0x10, 0x81, 0x02, 0xC0,
|
||||
0x05, 0x02, 0x09, 0xC5, 0x15, 0x00, 0x26, 0xFF, 0x03, 0x95, 0x01, 0x75, 0x0A, 0x81, 0x02, 0x15, 0x00, 0x25, 0x00, 0x75, 0x06, 0x95, 0x01, 0x81, 0x03,
|
||||
0x05, 0x02, 0x09, 0xC4, 0x15, 0x00, 0x26, 0xFF, 0x03, 0x95, 0x01, 0x75, 0x0A, 0x81, 0x02, 0x15, 0x00, 0x25, 0x00, 0x75, 0x06, 0x95, 0x01, 0x81, 0x03,
|
||||
0x05, 0x01, 0x09, 0x39, 0x15, 0x01, 0x25, 0x08, 0x35, 0x00, 0x46, 0x3B, 0x01, 0x66, 0x14, 0x00, 0x75, 0x04, 0x95, 0x01, 0x81, 0x42,
|
||||
0x75, 0x04, 0x95, 0x01, 0x15, 0x00, 0x25, 0x00, 0x35, 0x00, 0x45, 0x00, 0x65, 0x00, 0x81, 0x03,
|
||||
0x05, 0x09, 0x19, 0x01, 0x29, 0x0F, 0x15, 0x00, 0x25, 0x01, 0x75, 0x01, 0x95, 0x0F, 0x81, 0x02,
|
||||
0x15, 0x00, 0x25, 0x00, 0x75, 0x01, 0x95, 0x01, 0x81, 0x03,
|
||||
0x05, 0x0C, 0x0A, 0xB2, 0x00, 0x15, 0x00, 0x25, 0x01, 0x95, 0x01, 0x75, 0x01, 0x81, 0x02,
|
||||
0x15, 0x00, 0x25, 0x00, 0x75, 0x07, 0x95, 0x01, 0x81, 0x03,
|
||||
0x05, 0x0F, 0x09, 0x21, 0x85, 0x03, 0xA1, 0x02,
|
||||
0x09, 0x97, 0x15, 0x00, 0x25, 0x01, 0x75, 0x04, 0x95, 0x01, 0x91, 0x02,
|
||||
0x15, 0x00, 0x25, 0x00, 0x75, 0x04, 0x95, 0x01, 0x91, 0x03,
|
||||
0x09, 0x70, 0x15, 0x00, 0x25, 0x64, 0x75, 0x08, 0x95, 0x04, 0x91, 0x02,
|
||||
0x09, 0x50, 0x66, 0x01, 0x10, 0x55, 0x0E, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x01, 0x91, 0x02,
|
||||
0x09, 0xA7, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x01, 0x91, 0x02,
|
||||
0x65, 0x00, 0x55, 0x00, 0x09, 0x7C, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x01, 0x91, 0x02,
|
||||
0xC0, 0xC0,
|
||||
)
|
||||
|
||||
override fun inputId() = 1
|
||||
|
||||
override fun input(s: BtPadState): ByteArray {
|
||||
val r = ByteArray(16)
|
||||
r.le16(0, axis16(s.lx)); r.le16(2, axis16(s.ly)); r.le16(4, axis16(s.rx)); r.le16(6, axis16(s.ry))
|
||||
r.le16(8, (s.lt.coerceIn(0f, 1f) * 1023f).roundToInt())
|
||||
r.le16(10, (s.rt.coerceIn(0f, 1f) * 1023f).roundToInt())
|
||||
r[12] = (s.hat() + 1).toByte()
|
||||
var b = 0
|
||||
XBOX_ORDER.forEachIndexed { i, bit -> if (bit != 0 && s.isDown(bit)) b = b or (1 shl i) }
|
||||
r.le16(13, b)
|
||||
r[15] = if (s.isDown(BtPadState.SHARE)) 1 else 0
|
||||
return r
|
||||
}
|
||||
|
||||
override fun output(id: Int, data: ByteArray): BtFeedback? {
|
||||
if (id != 3) return null
|
||||
val d = data
|
||||
if (d.size < 5) return null
|
||||
val enable = d[0].toInt()
|
||||
val strong = if (enable and 0x02 != 0) d[3].toInt() and 0xFF else 0
|
||||
val weak = if (enable and 0x01 != 0) d[4].toInt() and 0xFF else 0
|
||||
return BtFeedback(strong * 255 / 100, weak * 255 / 100)
|
||||
}
|
||||
|
||||
private fun axis16(v: Float) = ((v.coerceIn(-1f, 1f) + 1f) * 32767.5f).roundToInt().coerceIn(0, 65535)
|
||||
|
||||
companion object {
|
||||
private val XBOX_ORDER = intArrayOf(
|
||||
BtPadState.A, BtPadState.B, 0, BtPadState.X, BtPadState.Y, 0, BtPadState.LB, BtPadState.RB,
|
||||
0, 0, BtPadState.SELECT, BtPadState.START, BtPadState.GUIDE, BtPadState.L3, BtPadState.R3,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private abstract class SonyEncoder : BtPadEncoder() {
|
||||
@Volatile protected var enhanced = false
|
||||
protected var counter = 0
|
||||
protected var timestamp = 0L
|
||||
|
||||
override val periodMs = 8L
|
||||
|
||||
protected fun buttons(s: BtPadState): IntArray {
|
||||
val hat = s.hat().let { if (it < 0) 8 else it }
|
||||
var b0 = hat
|
||||
if (s.isDown(BtPadState.X)) b0 = b0 or 0x10
|
||||
if (s.isDown(BtPadState.A)) b0 = b0 or 0x20
|
||||
if (s.isDown(BtPadState.B)) b0 = b0 or 0x40
|
||||
if (s.isDown(BtPadState.Y)) b0 = b0 or 0x80
|
||||
var b1 = 0
|
||||
if (s.isDown(BtPadState.LB)) b1 = b1 or 0x01
|
||||
if (s.isDown(BtPadState.RB)) b1 = b1 or 0x02
|
||||
if (s.lt > 0.05f) b1 = b1 or 0x04
|
||||
if (s.rt > 0.05f) b1 = b1 or 0x08
|
||||
if (s.isDown(BtPadState.SELECT) || s.isDown(BtPadState.SHARE)) b1 = b1 or 0x10
|
||||
if (s.isDown(BtPadState.START)) b1 = b1 or 0x20
|
||||
if (s.isDown(BtPadState.L3)) b1 = b1 or 0x40
|
||||
if (s.isDown(BtPadState.R3)) b1 = b1 or 0x80
|
||||
var b2 = 0
|
||||
if (s.isDown(BtPadState.GUIDE)) b2 = b2 or 0x01
|
||||
if (s.isDown(BtPadState.TOUCHPAD)) b2 = b2 or 0x02
|
||||
return intArrayOf(b0, b1, b2)
|
||||
}
|
||||
|
||||
override fun report(s: BtPadState, limit: Int): Pair<Int, ByteArray> {
|
||||
val full = input(s)
|
||||
return if (full.size <= limit) inputId() to full else 1 to simple(s)
|
||||
}
|
||||
|
||||
protected fun simple(s: BtPadState): ByteArray {
|
||||
val b = buttons(s)
|
||||
counter = (counter + 1) and 0x3F
|
||||
return bytes(axis8(s.lx), axis8(s.ly), axis8(s.rx), axis8(s.ry), b[0], b[1], b[2] or (counter shl 2), trigger8(s.lt), trigger8(s.rt))
|
||||
}
|
||||
|
||||
protected fun calibration(): ByteArray {
|
||||
val r = ByteArray(40)
|
||||
val v = intArrayOf(0, 0, 0, GYRO, -GYRO, GYRO, -GYRO, GYRO, -GYRO, GYRO_SPEED, GYRO_SPEED, ACCEL, -ACCEL, ACCEL, -ACCEL, ACCEL, -ACCEL)
|
||||
v.forEachIndexed { i, x -> r.le16(i * 2, x) }
|
||||
return r.sealCrc(FEATURE_SEED, 0x05)
|
||||
}
|
||||
|
||||
override fun feature(id: Int): ByteArray? {
|
||||
val reply = reply(id) ?: return null
|
||||
enhanced = true
|
||||
return reply
|
||||
}
|
||||
|
||||
protected abstract fun reply(id: Int): ByteArray?
|
||||
|
||||
companion object {
|
||||
const val INPUT_SEED = 0xA1
|
||||
const val OUTPUT_SEED = 0xA2
|
||||
const val FEATURE_SEED = 0xA3
|
||||
const val GYRO = 8800
|
||||
const val GYRO_SPEED = 540
|
||||
const val ACCEL = 8192
|
||||
}
|
||||
}
|
||||
|
||||
private class DualShock4Encoder : SonyEncoder() {
|
||||
override val reports = listOf(0x01 to INPUT, 0x11 to INPUT, 0x11 to OUTPUT, 0x02 to FEATURE, 0xA3 to FEATURE, 0x05 to FEATURE, 0x12 to FEATURE)
|
||||
|
||||
override val descriptor = bytes(
|
||||
0x05, 0x01, 0x09, 0x05, 0xA1, 0x01, 0x85, 0x01,
|
||||
0x09, 0x30, 0x09, 0x31, 0x09, 0x32, 0x09, 0x35, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x04, 0x81, 0x02,
|
||||
0x09, 0x39, 0x15, 0x00, 0x25, 0x07, 0x35, 0x00, 0x46, 0x3B, 0x01, 0x65, 0x14, 0x75, 0x04, 0x95, 0x01, 0x81, 0x42, 0x65, 0x00,
|
||||
0x05, 0x09, 0x19, 0x01, 0x29, 0x0E, 0x15, 0x00, 0x25, 0x01, 0x75, 0x01, 0x95, 0x0E, 0x81, 0x02,
|
||||
0x06, 0x00, 0xFF, 0x09, 0x20, 0x75, 0x06, 0x95, 0x01, 0x15, 0x00, 0x25, 0x7F, 0x81, 0x02,
|
||||
0x05, 0x01, 0x09, 0x33, 0x09, 0x34, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x02, 0x81, 0x02,
|
||||
0x06, 0x04, 0xFF,
|
||||
0x85, 0x02, 0x09, 0x24, 0x95, 0x24, 0xB1, 0x02,
|
||||
0x85, 0xA3, 0x09, 0x25, 0x95, 0x30, 0xB1, 0x02,
|
||||
0x85, 0x05, 0x09, 0x26, 0x95, 0x28, 0xB1, 0x02,
|
||||
0x85, 0x12, 0x09, 0x27, 0x95, 0x0F, 0xB1, 0x02,
|
||||
0x85, 0x11, 0x09, 0x22, 0x95, 0x4D, 0x81, 0x02,
|
||||
0x09, 0x23, 0x95, 0x4D, 0x91, 0x02,
|
||||
0xC0,
|
||||
)
|
||||
|
||||
override fun inputId() = if (enhanced) 0x11 else 0x01
|
||||
|
||||
override fun input(s: BtPadState): ByteArray {
|
||||
if (!enhanced) return simple(s)
|
||||
val r = ByteArray(77)
|
||||
r[0] = 0xC0.toByte()
|
||||
val b = buttons(s)
|
||||
counter = (counter + 1) and 0x3F
|
||||
timestamp += 1500
|
||||
val c = 2
|
||||
r[c] = axis8(s.lx).toByte(); r[c + 1] = axis8(s.ly).toByte(); r[c + 2] = axis8(s.rx).toByte(); r[c + 3] = axis8(s.ry).toByte()
|
||||
r[c + 4] = b[0].toByte(); r[c + 5] = b[1].toByte(); r[c + 6] = (b[2] or (counter shl 2)).toByte()
|
||||
r[c + 7] = trigger8(s.lt).toByte(); r[c + 8] = trigger8(s.rt).toByte()
|
||||
r.le16(c + 9, timestamp.toInt())
|
||||
r.le16(c + 20, ACCEL)
|
||||
r[c + 29] = 0x09
|
||||
r[c + 32] = 1
|
||||
r[c + 34] = 0x80.toByte()
|
||||
r[c + 38] = 0x80.toByte()
|
||||
return r.sealCrc(INPUT_SEED, 0x11)
|
||||
}
|
||||
|
||||
override fun reply(id: Int): ByteArray? = when (id) {
|
||||
0x02 -> ByteArray(36).also { r ->
|
||||
val v = intArrayOf(0, 0, 0, GYRO, GYRO, GYRO, -GYRO, -GYRO, -GYRO, GYRO_SPEED, GYRO_SPEED, ACCEL, -ACCEL, ACCEL, -ACCEL, ACCEL, -ACCEL)
|
||||
v.forEachIndexed { i, x -> r.le16(i * 2, x) }
|
||||
}
|
||||
0x05 -> calibration()
|
||||
0xA3 -> ByteArray(48).also { r ->
|
||||
"Sep 21 2018".toByteArray().copyInto(r, 0)
|
||||
"04:50:51".toByteArray().copyInto(r, 16)
|
||||
r.le16(34, 0x0100)
|
||||
r.le16(40, 0xA00A)
|
||||
}
|
||||
0x12 -> ByteArray(15).also { r -> FAKE_MAC.copyInto(r, 0); r[6] = 0x08; r[7] = 0x25 }
|
||||
else -> null
|
||||
}
|
||||
|
||||
override fun output(id: Int, data: ByteArray): BtFeedback? {
|
||||
if (id != 0x11) return null
|
||||
enhanced = true
|
||||
val d = data
|
||||
if (d.size < 10) return null
|
||||
val flags = d[2].toInt()
|
||||
val light = if (flags and 0x02 != 0) rgb(d[7], d[8], d[9]) else null
|
||||
return BtFeedback(d[6].toInt() and 0xFF, d[5].toInt() and 0xFF, light)
|
||||
}
|
||||
}
|
||||
|
||||
private class DualSenseEncoder : SonyEncoder() {
|
||||
override val reports = listOf(0x01 to INPUT, 0x31 to INPUT, 0x31 to OUTPUT, 0x05 to FEATURE, 0x09 to FEATURE, 0x20 to FEATURE)
|
||||
|
||||
override val descriptor = bytes(
|
||||
0x05, 0x01, 0x09, 0x05, 0xA1, 0x01, 0x85, 0x01,
|
||||
0x09, 0x30, 0x09, 0x31, 0x09, 0x32, 0x09, 0x35, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x04, 0x81, 0x02,
|
||||
0x09, 0x39, 0x15, 0x00, 0x25, 0x07, 0x35, 0x00, 0x46, 0x3B, 0x01, 0x65, 0x14, 0x75, 0x04, 0x95, 0x01, 0x81, 0x42, 0x65, 0x00,
|
||||
0x05, 0x09, 0x19, 0x01, 0x29, 0x0E, 0x15, 0x00, 0x25, 0x01, 0x75, 0x01, 0x95, 0x0E, 0x81, 0x02,
|
||||
0x06, 0x00, 0xFF, 0x09, 0x20, 0x75, 0x06, 0x95, 0x01, 0x15, 0x00, 0x25, 0x7F, 0x81, 0x02,
|
||||
0x05, 0x01, 0x09, 0x33, 0x09, 0x34, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x02, 0x81, 0x02,
|
||||
0x06, 0x00, 0xFF,
|
||||
0x85, 0x31, 0x09, 0x31, 0x95, 0x4D, 0x81, 0x02,
|
||||
0x09, 0x32, 0x95, 0x4D, 0x91, 0x02,
|
||||
0x85, 0x05, 0x09, 0x33, 0x95, 0x28, 0xB1, 0x02,
|
||||
0x85, 0x09, 0x09, 0x34, 0x95, 0x13, 0xB1, 0x02,
|
||||
0x85, 0x20, 0x09, 0x35, 0x95, 0x3F, 0xB1, 0x02,
|
||||
0xC0,
|
||||
)
|
||||
|
||||
private var sequence = 0
|
||||
|
||||
override fun inputId() = if (enhanced) 0x31 else 0x01
|
||||
|
||||
override fun input(s: BtPadState): ByteArray {
|
||||
if (!enhanced) return simple(s)
|
||||
val r = ByteArray(77)
|
||||
sequence = (sequence + 1) and 0xFF
|
||||
timestamp += 24000
|
||||
r[0] = 0x10
|
||||
val c = 1
|
||||
r[c] = axis8(s.lx).toByte(); r[c + 1] = axis8(s.ly).toByte(); r[c + 2] = axis8(s.rx).toByte(); r[c + 3] = axis8(s.ry).toByte()
|
||||
r[c + 4] = trigger8(s.lt).toByte(); r[c + 5] = trigger8(s.rt).toByte()
|
||||
r[c + 6] = sequence.toByte()
|
||||
val b = buttons(s)
|
||||
r[c + 7] = b[0].toByte(); r[c + 8] = b[1].toByte(); r[c + 9] = b[2].toByte()
|
||||
r.le16(c + 23, ACCEL)
|
||||
r.le32(c + 27, timestamp)
|
||||
r[c + 32] = 0x80.toByte()
|
||||
r[c + 36] = 0x80.toByte()
|
||||
r[c + 52] = 0x09
|
||||
return r.sealCrc(INPUT_SEED, 0x31)
|
||||
}
|
||||
|
||||
override fun reply(id: Int): ByteArray? = when (id) {
|
||||
0x05 -> calibration()
|
||||
0x09 -> ByteArray(19).also { r -> FAKE_MAC.copyInto(r, 0) }.sealCrc(FEATURE_SEED, 0x09)
|
||||
0x20 -> ByteArray(63).also { r ->
|
||||
"Jun 19 2023".toByteArray().copyInto(r, 0)
|
||||
"14:47:34".toByteArray().copyInto(r, 11)
|
||||
r.le16(19, 0x0003)
|
||||
r.le32(23, 0x00000615L)
|
||||
r.le32(27, 0x0110002AL)
|
||||
r.le16(43, 0x0630)
|
||||
}.sealCrc(FEATURE_SEED, 0x20)
|
||||
else -> null
|
||||
}
|
||||
|
||||
override fun output(id: Int, data: ByteArray): BtFeedback? {
|
||||
if (id != 0x31) return null
|
||||
enhanced = true
|
||||
val d = data
|
||||
if (d.size < 49) return null
|
||||
val flags0 = d[2].toInt()
|
||||
val flags1 = d[3].toInt()
|
||||
val light = if (flags1 and 0x04 != 0) rgb(d[46], d[47], d[48]) else null
|
||||
return if (flags0 and 0x03 != 0) BtFeedback(d[5].toInt() and 0xFF, d[4].toInt() and 0xFF, light)
|
||||
else if (light != null) BtFeedback(-1, -1, light) else null
|
||||
}
|
||||
}
|
||||
|
||||
private class SteamControllerEncoder : BtPadEncoder() {
|
||||
override val descriptor = bytes(
|
||||
0x06, 0x00, 0xFF, 0x09, 0x01, 0xA1, 0x01, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08,
|
||||
0x85, 0x45, 0x09, 0x02, 0x95, 0x2D, 0x81, 0x02, 0x85, 0x47, 0x09, 0x03, 0x95, 0x2D, 0x81, 0x02,
|
||||
0x85, 0x80, 0x09, 0x04, 0x95, 0x09, 0x91, 0x02, 0x85, 0x81, 0x09, 0x05, 0x95, 0x07, 0x91, 0x02,
|
||||
0x85, 0x82, 0x09, 0x06, 0x95, 0x03, 0x91, 0x02, 0x85, 0x83, 0x09, 0x07, 0x95, 0x09, 0x91, 0x02,
|
||||
0x85, 0x84, 0x09, 0x08, 0x95, 0x08, 0x91, 0x02, 0x85, 0x85, 0x09, 0x09, 0x95, 0x03, 0x91, 0x02,
|
||||
0x85, 0x01, 0x09, 0x0A, 0x95, 0x3F, 0xB1, 0x02, 0xC0,
|
||||
)
|
||||
override val reports = listOf(0x45 to INPUT, 0x47 to INPUT, 0x80 to OUTPUT, 0x81 to OUTPUT, 0x82 to OUTPUT,
|
||||
0x83 to OUTPUT, 0x84 to OUTPUT, 0x85 to OUTPUT, 0x01 to FEATURE)
|
||||
override val periodMs = 8L
|
||||
|
||||
@Volatile private var pending = 0
|
||||
private var packet = 0
|
||||
private val start = System.nanoTime()
|
||||
|
||||
override fun inputId() = 0x45
|
||||
|
||||
override fun input(s: BtPadState): ByteArray {
|
||||
val r = ByteArray(45)
|
||||
packet++
|
||||
r[0] = packet.toByte()
|
||||
var b = LGRIP_TOUCH or RGRIP_TOUCH
|
||||
BUTTONS.forEach { (mine, theirs) -> if (s.isDown(mine)) b = b or theirs }
|
||||
if (s.lt >= 0.98f) b = b or LTRIGGER_CLICK
|
||||
if (s.rt >= 0.98f) b = b or RTRIGGER_CLICK
|
||||
if (Math.abs(s.lx) > 0.06f || Math.abs(s.ly) > 0.06f) b = b or LSTICK_TOUCH
|
||||
if (Math.abs(s.rx) > 0.06f || Math.abs(s.ry) > 0.06f) b = b or RSTICK_TOUCH
|
||||
r.le32(1, b.toLong())
|
||||
r.le16(5, (s.lt.coerceIn(0f, 1f) * 32767f).roundToInt())
|
||||
r.le16(7, (s.rt.coerceIn(0f, 1f) * 32767f).roundToInt())
|
||||
r.le16(9, stick(s.lx)); r.le16(11, stick(-s.ly)); r.le16(13, stick(s.rx)); r.le16(15, stick(-s.ry))
|
||||
if (s.isDown(BtPadState.LPAD_TOUCH)) {
|
||||
r.le16(17, stick(s.lpx)); r.le16(19, stick(-s.lpy))
|
||||
r.le16(21, if (s.isDown(BtPadState.LPAD_CLICK)) 32767 else 4000)
|
||||
}
|
||||
if (s.isDown(BtPadState.RPAD_TOUCH)) {
|
||||
r.le16(23, stick(s.rpx)); r.le16(25, stick(-s.rpy))
|
||||
r.le16(27, if (s.isDown(BtPadState.RPAD_CLICK)) 32767 else 4000)
|
||||
}
|
||||
r.le32(29, (System.nanoTime() - start) / 1000)
|
||||
r.le16(37, 16384)
|
||||
return r
|
||||
}
|
||||
|
||||
override fun setFeature(id: Int, data: ByteArray) {
|
||||
val d = data
|
||||
if (id == 1 && d.isNotEmpty()) pending = d[0].toInt() and 0xFF
|
||||
}
|
||||
|
||||
override fun feature(id: Int): ByteArray? {
|
||||
if (id != 1) return null
|
||||
val r = ByteArray(63)
|
||||
r[0] = pending.toByte()
|
||||
when (pending) {
|
||||
0x83 -> {
|
||||
val ids = intArrayOf(0x01, 0x02, 0x04, 0x09, 0x0A, 0x0B)
|
||||
val values = longArrayOf(0x1303, 0, FW_TIMESTAMP, 72, 0, 4000)
|
||||
r[1] = (ids.size * 5).toByte()
|
||||
ids.forEachIndexed { i, a -> r[2 + i * 5] = a.toByte(); r.le32(3 + i * 5, values[i]) }
|
||||
}
|
||||
0xAE -> { r[1] = 0x14; r[2] = 0x01; SERIAL.toByteArray().copyInto(r, 3) }
|
||||
0xBA -> { r[1] = 0x11; "DROIDDECKCHIP02".toByteArray().copyInto(r, 3) }
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
override fun output(id: Int, data: ByteArray): BtFeedback? {
|
||||
val d = data
|
||||
return when (id) {
|
||||
0x80 -> if (d.size >= 8) {
|
||||
val left = (d[3].toInt() and 0xFF) or ((d[4].toInt() and 0xFF) shl 8)
|
||||
val right = (d[6].toInt() and 0xFF) or ((d[7].toInt() and 0xFF) shl 8)
|
||||
BtFeedback(left shr 8, right shr 8)
|
||||
} else null
|
||||
in 0x81..0x85 -> BtFeedback(0, 120)
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
private fun stick(v: Float) = (v.coerceIn(-1f, 1f) * 32767f).roundToInt()
|
||||
|
||||
companion object {
|
||||
private const val LGRIP_TOUCH = 0x20000000
|
||||
private const val RGRIP_TOUCH = 0x10000000
|
||||
private const val LTRIGGER_CLICK = 0x08000000
|
||||
private const val RTRIGGER_CLICK = 0x00800000
|
||||
private const val LSTICK_TOUCH = 0x01000000
|
||||
private const val RSTICK_TOUCH = 0x00100000
|
||||
private const val FW_TIMESTAMP = 0x6AC686B3L
|
||||
private const val SERIAL = "DROIDDECKSC01"
|
||||
private val BUTTONS = listOf(
|
||||
BtPadState.A to 0x00000001, BtPadState.B to 0x00000002, BtPadState.X to 0x00000004, BtPadState.Y to 0x00000008,
|
||||
BtPadState.SHARE to 0x00000010, BtPadState.R3 to 0x00000020, BtPadState.SELECT to 0x00000040,
|
||||
BtPadState.R4 to 0x00000080, BtPadState.R5 to 0x00000100, BtPadState.RB to 0x00000200,
|
||||
BtPadState.DOWN to 0x00000400, BtPadState.RIGHT to 0x00000800, BtPadState.LEFT to 0x00001000,
|
||||
BtPadState.UP to 0x00002000, BtPadState.START to 0x00004000, BtPadState.L3 to 0x00008000,
|
||||
BtPadState.GUIDE to 0x00010000, BtPadState.L4 to 0x00020000, BtPadState.L5 to 0x00040000,
|
||||
BtPadState.LB to 0x00080000,
|
||||
BtPadState.RPAD_TOUCH to 0x00200000, BtPadState.RPAD_CLICK to 0x00400000,
|
||||
BtPadState.LPAD_TOUCH to 0x02000000, BtPadState.LPAD_CLICK to 0x04000000,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private val FAKE_MAC = BtPadEncoder.bytes(0x5D, 0x44, 0x33, 0x22, 0x11, 0xD0)
|
||||
|
||||
private fun rgb(r: Byte, g: Byte, b: Byte) =
|
||||
(0xFF shl 24) or ((r.toInt() and 0xFF) shl 16) or ((g.toInt() and 0xFF) shl 8) or (b.toInt() and 0xFF)
|
||||
@@ -72,6 +72,8 @@ object CurseForgeApp {
|
||||
JSONObject().put("instanceId", guid).put("projectId", projectId.toLong()).put("categoryClassId", 1)
|
||||
.put("installLatestFile", true).put("installSource", 4)
|
||||
|
||||
private const val CACHE = "__droiddeckServices"
|
||||
|
||||
private const val SERVICES = """(() => {
|
||||
const seen = new Set(), out = {};
|
||||
const walk = (o, d) => {
|
||||
@@ -91,7 +93,8 @@ object CurseForgeApp {
|
||||
internal fun expression(service: String, method: String, args: JSONArray?, pick: String = "r => r"): String {
|
||||
val name = JSONObject.quote(method)
|
||||
val run = if (args == null) "true" else "($pick)(await s[$name](...$args))"
|
||||
val inner = "(async () => { const s = $SERVICES[${JSONObject.quote(service)}]; " +
|
||||
val key = JSONObject.quote(service)
|
||||
val inner = "(async () => { let m = globalThis.$CACHE; if (!m || !m[$key]) m = globalThis.$CACHE = $SERVICES; const s = m[$key]; " +
|
||||
"if (!s || typeof s[$name] !== 'function') return { missing: true }; " +
|
||||
"return { value: $run }; })()"
|
||||
return "(() => { const w = require('electron').BrowserWindow.getAllWindows()" +
|
||||
@@ -170,6 +173,7 @@ object CurseForgeApp {
|
||||
}
|
||||
|
||||
private val holds = ConcurrentHashMap<String, AtomicBoolean>()
|
||||
private val connected = ConcurrentHashMap.newKeySet<String>()
|
||||
|
||||
private fun lines(context: Context, argv: List<String>): List<String> {
|
||||
val out = ArrayList<String>()
|
||||
@@ -232,19 +236,25 @@ object CurseForgeApp {
|
||||
}
|
||||
if (inspector != null) runCatching { call(context, inspector, "CoreService", "shutdown", JSONArray(), 30_000, "r => true") }
|
||||
hold.set(true)
|
||||
inspector?.let(connected::remove)
|
||||
if (holds.remove(dir, hold)) runCatching { lines(context, helperArgv("stop", dir)) }
|
||||
}
|
||||
|
||||
private fun connect(context: Context, inspector: String) {
|
||||
if (inspector in connected) return
|
||||
call(context, inspector, "CoreService", "connect", JSONArray(), 120_000, "r => true")
|
||||
connected += inspector
|
||||
}
|
||||
|
||||
private fun instances(context: Context, inspector: String): Any? =
|
||||
call(context, inspector, "GameAppService", "getGameInstances", JSONArray().put(WOW), 30_000,
|
||||
"r => (r || []).map(i => ({ guid: i.guid, installPath: i.installPath }))")
|
||||
|
||||
fun instance(context: Context, inspector: String, root: String, flavorDir: String): String {
|
||||
connect(context, inspector)
|
||||
instanceFor(instances(context, inspector), flavorDir, null)?.let { return it }
|
||||
val detected = call(context, inspector, "GameDetectionAppService", "detectGameFromPath", JSONArray().put(root).put(WOW), 60_000) as? JSONObject
|
||||
val instances = call(context, inspector, "GameAppService", "getGameInstances", JSONArray().put(WOW), 30_000,
|
||||
"r => (r || []).map(i => ({ guid: i.guid, installPath: i.installPath }))")
|
||||
return instanceFor(instances, flavorDir, detected?.optString("gameInstanceGuid")) ?: throw Failure("CurseForge did not find $flavorDir")
|
||||
return instanceFor(instances(context, inspector), flavorDir, detected?.optString("gameInstanceGuid")) ?: throw Failure("CurseForge did not find $flavorDir")
|
||||
}
|
||||
|
||||
fun search(context: Context, inspector: String, guid: String, text: String, sort: WowAddonCatalog.Sort, page: Int): WowAddonCatalog.Page =
|
||||
@@ -260,34 +270,34 @@ object CurseForgeApp {
|
||||
"locked: !!(p.installedVersion && p.installedVersion.isLocked), " +
|
||||
"folders: ((p.installedVersion && p.installedVersion.addonFolders) || []).map(f => f.name) }))"
|
||||
|
||||
private fun settle(context: Context, inspector: String, guid: String, done: (List<Project>) -> Boolean): Boolean {
|
||||
private fun settle(context: Context, inspector: String, guid: String, done: (List<Project>) -> Boolean): List<Project>? {
|
||||
val deadline = System.currentTimeMillis() + INSTALL_MS
|
||||
while (System.currentTimeMillis() < deadline) {
|
||||
val listed = runCatching { projects(context, inspector, guid) }
|
||||
val error = listed.exceptionOrNull()
|
||||
if (error is Failure && error.gone) throw error
|
||||
listed.getOrNull()?.let { if (done(it)) return true }
|
||||
listed.getOrNull()?.let { if (done(it)) return it }
|
||||
Thread.sleep(1_000)
|
||||
}
|
||||
return false
|
||||
return null
|
||||
}
|
||||
|
||||
fun install(context: Context, inspector: String, guid: String, projectId: String): Boolean {
|
||||
fun install(context: Context, inspector: String, guid: String, projectId: String): List<Project>? {
|
||||
connect(context, inspector)
|
||||
if (call(context, inspector, "InstalledProjectsAppService", "installAddon", JSONArray().put(installRequest(guid, projectId)), 300_000) != true) return false
|
||||
if (call(context, inspector, "InstalledProjectsAppService", "installAddon", JSONArray().put(installRequest(guid, projectId)), 300_000) != true) return null
|
||||
return settle(context, inspector, guid) { list -> list.any { it.id == projectId } }
|
||||
}
|
||||
|
||||
fun update(context: Context, inspector: String, guid: String, projectId: String): Boolean {
|
||||
fun update(context: Context, inspector: String, guid: String, projectId: String): List<Project>? {
|
||||
connect(context, inspector)
|
||||
if (call(context, inspector, "InstalledProjectsAppService", "updateMod", JSONArray().put(guid).put(projectId.toLong()), 300_000) != true) return false
|
||||
if (call(context, inspector, "InstalledProjectsAppService", "updateMod", JSONArray().put(guid).put(projectId.toLong()), 300_000) != true) return null
|
||||
return settle(context, inspector, guid) { list -> list.any { it.id == projectId && !it.update } }
|
||||
}
|
||||
|
||||
fun uninstall(context: Context, inspector: String, guid: String, project: Project): Boolean {
|
||||
fun uninstall(context: Context, inspector: String, guid: String, project: Project): List<Project>? {
|
||||
connect(context, inspector)
|
||||
val failed = call(context, inspector, "InstalledProjectsAppService", "deleteMods", JSONArray().put(guid).put(JSONArray().put(project.installedModId)), 120_000) as? JSONArray
|
||||
if (failed == null || failed.length() > 0) return false
|
||||
if (failed == null || failed.length() > 0) return null
|
||||
return settle(context, inspector, guid) { list -> list.none { it.id == project.id } }
|
||||
}
|
||||
}
|
||||
@@ -275,12 +275,15 @@ class LinuxNetworkLinkComponent(
|
||||
* crash or power cut can keep the rename and lose the data, leaving a file of NUL bytes.
|
||||
*/
|
||||
private fun replace(file: File, text: String) {
|
||||
val staged = File(file.path + ".staged")
|
||||
java.io.FileOutputStream(staged).use { out ->
|
||||
out.write(text.toByteArray())
|
||||
out.fd.sync()
|
||||
synchronized(WRITES) {
|
||||
if (runCatching { file.isFile && file.readText() == text }.getOrDefault(false)) return
|
||||
val staged = File(file.path + ".staged")
|
||||
java.io.FileOutputStream(staged).use { out ->
|
||||
out.write(text.toByteArray())
|
||||
out.fd.sync()
|
||||
}
|
||||
if (!staged.renameTo(file)) throw IOException("Could not replace $file")
|
||||
}
|
||||
if (!staged.renameTo(file)) throw IOException("Could not replace $file")
|
||||
}
|
||||
|
||||
private fun writeResolver(properties: LinkProperties?) {
|
||||
@@ -333,6 +336,8 @@ class LinuxNetworkLinkComponent(
|
||||
seededMac { Settings.Secure.getString(appContext.contentResolver, Settings.Secure.ANDROID_ID) }
|
||||
|
||||
companion object {
|
||||
private val WRITES = Any()
|
||||
|
||||
internal fun gateways(properties: LinkProperties?, capabilities: NetworkCapabilities?): List<InetAddress> =
|
||||
listOf(Inet4Address::class.java, Inet6Address::class.java).mapNotNull { family ->
|
||||
properties?.routes.orEmpty()
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntimeInstaller
|
||||
import com.droiddeck.launcher.runtime.RuntimeInstallService
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
|
||||
/** What first run installs by itself, in the order it is needed, and how far each part has got. */
|
||||
object Onboarding {
|
||||
enum class Step { RUNTIME, PROTON, STEAM }
|
||||
|
||||
data class Progress(val label: String, val percent: Int)
|
||||
|
||||
data class Facts(val runtime: Boolean = true, val proton: Boolean = true, val steam: Boolean = true)
|
||||
|
||||
enum class State { DONE, ACTIVE, WAITING, FAILED }
|
||||
|
||||
data class Row(val step: Step, val state: State, val label: String?, val percent: Int)
|
||||
|
||||
val active = MutableStateFlow<Map<Step, Progress>>(emptyMap())
|
||||
val failed = MutableStateFlow<Map<Step, String>>(emptyMap())
|
||||
val facts = MutableStateFlow(Facts())
|
||||
|
||||
@Volatile private var appContext: Context? = null
|
||||
private var hold: (() -> Unit)? = null
|
||||
|
||||
fun attach(context: Context) {
|
||||
appContext = context.applicationContext
|
||||
}
|
||||
|
||||
/** Keeps the process in the foreground, with one notification, while a step downloads and the runtime installer is not already doing so. */
|
||||
@Synchronized private fun keepAlive() {
|
||||
val context = appContext ?: return
|
||||
val running = active.value
|
||||
if (running.isNotEmpty() && !LinuxRuntimeInstaller.isBusy()) {
|
||||
if (hold == null) hold = RuntimeInstallService.holdForPackage(context, context.getString(R.string.onboarding_title))
|
||||
val rows = rows(running, failed.value, facts.value)
|
||||
RuntimeInstallService.packageProgress(running.values.first().label, overall(rows))
|
||||
} else {
|
||||
hold?.invoke()
|
||||
hold = null
|
||||
}
|
||||
}
|
||||
|
||||
@Synchronized fun recheck(context: Context) {
|
||||
val runtime = LinuxRuntime.isInstalled(context)
|
||||
val own = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }
|
||||
facts.value = Facts(
|
||||
runtime = runtime,
|
||||
proton = ProtonExtras.declined(context) || ProtonExtras.installedAll(context, own).isNotEmpty(),
|
||||
steam = runtime && !SteamClientPrefetch.pending(context),
|
||||
)
|
||||
}
|
||||
|
||||
fun report(step: Step, label: String, percent: Int) {
|
||||
failed.value = failed.value - step
|
||||
active.value = active.value + (step to Progress(label, percent))
|
||||
keepAlive()
|
||||
}
|
||||
|
||||
fun finish(step: Step) {
|
||||
active.value = active.value - step
|
||||
failed.value = failed.value - step
|
||||
keepAlive()
|
||||
}
|
||||
|
||||
fun fail(step: Step, message: String) {
|
||||
active.value = active.value - step
|
||||
failed.value = failed.value + (step to message)
|
||||
keepAlive()
|
||||
}
|
||||
|
||||
fun rows(active: Map<Step, Progress>, failed: Map<Step, String>, facts: Facts): List<Row> = Step.entries.map { step ->
|
||||
val ready = when (step) { Step.RUNTIME -> facts.runtime; Step.PROTON -> facts.proton; Step.STEAM -> facts.steam }
|
||||
val progress = active[step]
|
||||
when {
|
||||
progress != null -> Row(step, State.ACTIVE, progress.label, progress.percent)
|
||||
failed[step] != null -> Row(step, State.FAILED, failed[step], -1)
|
||||
ready -> Row(step, State.DONE, null, 100)
|
||||
else -> Row(step, State.WAITING, null, -1)
|
||||
}
|
||||
}
|
||||
|
||||
fun pending(rows: List<Row>): Boolean = rows.any { it.state != State.DONE }
|
||||
|
||||
/** The aggregate fraction of the whole first-run work, weighting each step by what it downloads. */
|
||||
fun overall(rows: List<Row>): Int {
|
||||
val weights = mapOf(Step.RUNTIME to 60, Step.PROTON to 15, Step.STEAM to 25)
|
||||
val total = weights.values.sum()
|
||||
val got = rows.sumOf { row ->
|
||||
val w = weights.getValue(row.step)
|
||||
when (row.state) {
|
||||
State.DONE -> w
|
||||
State.ACTIVE -> if (row.percent >= 0) w * row.percent / 100 else 0
|
||||
else -> 0
|
||||
}
|
||||
}
|
||||
return got * 100 / total
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,7 @@ object ProtonExtras {
|
||||
const val CHECK_EVERY_MS = 60L * 60 * 1000
|
||||
@Volatile
|
||||
var installInProgress = false
|
||||
@Volatile var prefetching = false
|
||||
private set
|
||||
@Volatile
|
||||
private var replacing = false
|
||||
@@ -217,24 +218,12 @@ object ProtonExtras {
|
||||
|
||||
@Synchronized
|
||||
fun install(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
|
||||
if (installInProgress) return context.getString(R.string.pextra_busy)
|
||||
if (installInProgress || prefetching) return context.getString(R.string.pextra_busy)
|
||||
installInProgress = true
|
||||
return try { installNow(context, tool, onProgress) } finally { installInProgress = false }
|
||||
}
|
||||
|
||||
private fun installNow(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
|
||||
if (SessionState.running) return context.getString(R.string.pextra_stop_session)
|
||||
if (!LinuxRuntime.isInstalled(context)) return context.getString(R.string.user_apps_runtime_required)
|
||||
|
||||
val asset = releases(tool)?.let { pickAsset(tool, it) } ?: return context.getString(R.string.pextra_no_release, tool.name)
|
||||
val downloads = File(context.filesDir, "proton-downloads").apply { mkdirs() }
|
||||
val archive = File(downloads, "${tool.id}-${asset.name}")
|
||||
if (asset.size > 0 && archive.length() > asset.size) archive.delete()
|
||||
val missing = (asset.size - archive.length()).coerceAtLeast(0L)
|
||||
if (StatFs(LinuxRuntime.rootDir(context).path).availableBytes < NEED_BYTES + missing) {
|
||||
return context.getString(R.string.pextra_no_space, tool.name)
|
||||
}
|
||||
|
||||
private fun fetchArchive(context: Context, tool: Tool, asset: Asset, archive: File, onProgress: (String, Int) -> Unit): String? {
|
||||
val downloading = context.getString(R.string.pextra_downloading, tool.name, asset.tag)
|
||||
onProgress(downloading, 0)
|
||||
var downloaded = false
|
||||
@@ -252,6 +241,41 @@ object ProtonExtras {
|
||||
}
|
||||
}
|
||||
if (!downloaded) return context.getString(R.string.pextra_download_failed)
|
||||
return null
|
||||
}
|
||||
|
||||
/** Downloads the newest build of [tool] ahead of the runtime it installs into; [install] verifies and unpacks it later. */
|
||||
@Synchronized
|
||||
fun prefetch(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
|
||||
if (installInProgress) return context.getString(R.string.pextra_busy)
|
||||
prefetching = true
|
||||
try { return prefetchNow(context, tool, onProgress) } finally { prefetching = false }
|
||||
}
|
||||
|
||||
private fun prefetchNow(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
|
||||
val asset = releases(tool)?.let { pickAsset(tool, it) } ?: return context.getString(R.string.pextra_no_release, tool.name)
|
||||
val downloads = File(context.filesDir, "proton-downloads").apply { mkdirs() }
|
||||
val archive = File(downloads, "${tool.id}-${asset.name}")
|
||||
if (asset.size > 0 && archive.length() > asset.size) archive.delete()
|
||||
val missing = (asset.size - archive.length()).coerceAtLeast(0L)
|
||||
if (StatFs(context.filesDir.path).availableBytes < NEED_BYTES + missing) return context.getString(R.string.pextra_no_space, tool.name)
|
||||
return fetchArchive(context, tool, asset, archive, onProgress)
|
||||
}
|
||||
|
||||
private fun installNow(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
|
||||
if (SessionState.running) return context.getString(R.string.pextra_stop_session)
|
||||
if (!LinuxRuntime.isInstalled(context)) return context.getString(R.string.user_apps_runtime_required)
|
||||
|
||||
val asset = releases(tool)?.let { pickAsset(tool, it) } ?: return context.getString(R.string.pextra_no_release, tool.name)
|
||||
val downloads = File(context.filesDir, "proton-downloads").apply { mkdirs() }
|
||||
val archive = File(downloads, "${tool.id}-${asset.name}")
|
||||
if (asset.size > 0 && archive.length() > asset.size) archive.delete()
|
||||
val missing = (asset.size - archive.length()).coerceAtLeast(0L)
|
||||
if (StatFs(LinuxRuntime.rootDir(context).path).availableBytes < NEED_BYTES + missing) {
|
||||
return context.getString(R.string.pextra_no_space, tool.name)
|
||||
}
|
||||
|
||||
fetchArchive(context, tool, asset, archive, onProgress)?.let { return it }
|
||||
if (asset.size > 0 && archive.length() != asset.size) {
|
||||
if (archive.length() > asset.size) {
|
||||
archive.delete()
|
||||
|
||||
@@ -95,7 +95,11 @@ object SessionFiles {
|
||||
return all
|
||||
}
|
||||
|
||||
fun stage(context: Context, root: File, startsSession: Boolean = false) {
|
||||
private val STAGE_LOCK = Any()
|
||||
|
||||
fun stage(context: Context, root: File, startsSession: Boolean = false) = synchronized(STAGE_LOCK) { stageNow(context, root, startsSession) }
|
||||
|
||||
private fun stageNow(context: Context, root: File, startsSession: Boolean) {
|
||||
if (DesktopCatalog.desktopInstalled(root) && !DesktopCatalog.desktopFromPack(root)) try { DesktopCatalog.cleanLegacy(context) }
|
||||
catch (e: Exception) { Log.w(TAG, "LXQt cleanup will retry next session", e) }
|
||||
GameEnvironmentStore.publish(context)
|
||||
@@ -660,6 +664,7 @@ object SessionFiles {
|
||||
private const val UI_STATE = "UIStoreLocalSteamUIState"
|
||||
private const val SORT_RECENT_OFF = "\\\"bSortedByRecent\\\":false"
|
||||
private const val SORT_RECENT_ON = "\\\"bSortedByRecent\\\":true"
|
||||
private const val LIBRARY_BIG_ART = "LibraryHomeBigArt"
|
||||
private const val BATTERY_PERCENT_ON = "{\\\"bShowBatteryPercentage\\\":true}"
|
||||
|
||||
/**
|
||||
@@ -709,7 +714,12 @@ object SessionFiles {
|
||||
val block = out.substring(web.keyStart, web.close + 1)
|
||||
out = out.replaceRange(web.keyStart, web.close + 1, setScalar(block, BATTERY_PREFERENCES, BATTERY_PERCENT_ON, newline))
|
||||
}
|
||||
return seedRecentSort(out, newline)
|
||||
out = seedRecentSort(out, newline)
|
||||
val last = findObject(out, "UserLocalConfigStore", 0, out.length) ?: return out
|
||||
if (!hasKey(out.substring(last.open + 1, last.close), LIBRARY_BIG_ART)) {
|
||||
out = insertInto(out, last, listOf("\"$LIBRARY_BIG_ART\"\t\t\"1\""), newline)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// The library sort lives inside a JSON string; Steam writes bSortedByRecent:false until the player picks a sort,
|
||||
@@ -729,9 +739,11 @@ object SessionFiles {
|
||||
|
||||
private fun insertInto(text: String, parent: VdfBlock, lines: List<String>, newline: String): String {
|
||||
val lineStart = text.lastIndexOf('\n', parent.close).let { if (it < 0) 0 else it + 1 }
|
||||
val indent = text.substring(lineStart, parent.close).takeWhile { it == '\t' || it == ' ' } + "\t"
|
||||
val before = text.substring(lineStart, parent.close)
|
||||
val indent = before.takeWhile { it == '\t' || it == ' ' } + "\t"
|
||||
val section = lines.joinToString(newline) { indent + it } + newline
|
||||
return text.substring(0, lineStart) + section + text.substring(lineStart)
|
||||
if (before.isBlank()) return text.substring(0, lineStart) + section + text.substring(lineStart)
|
||||
return text.substring(0, parent.close) + newline + section + text.substring(parent.close)
|
||||
}
|
||||
|
||||
private val IDLE_SLEEP_TIMERS = listOf("IdleSuspendBatterySeconds", "IdleSuspendACSeconds")
|
||||
|
||||
@@ -63,6 +63,13 @@ object SessionPrefs {
|
||||
.takeIf { value -> orientationOptions.any { it.first == value } }
|
||||
?: ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
|
||||
|
||||
/** The session menu's width in dp the user dragged it to; null keeps the default. */
|
||||
fun drawerWidthDp(context: Context): Int? = prefs(context).getInt("drawerWidthDp", 0).takeIf { it > 0 }
|
||||
|
||||
fun setDrawerWidthDp(context: Context, dp: Int) {
|
||||
prefs(context).edit().putInt("drawerWidthDp", dp).apply()
|
||||
}
|
||||
|
||||
fun setOrientation(context: Context, orientation: Int) {
|
||||
require(orientationOptions.any { it.first == orientation })
|
||||
prefs(context).edit().putInt("orientation", orientation).apply()
|
||||
|
||||
@@ -2705,6 +2705,7 @@ class SessionService : Service() {
|
||||
gameId: String? = null,
|
||||
displayId: Int = Display.DEFAULT_DISPLAY,
|
||||
) {
|
||||
SteamClientPrefetch.cancel()
|
||||
SessionState.activityDisplayId = displayId
|
||||
val intent = Intent(context, SessionService::class.java).putExtra(EXTRA_MODE, mode)
|
||||
.putExtra(EXTRA_DISPLAY_ID, displayId)
|
||||
|
||||
@@ -13,7 +13,7 @@ object SettingsReset {
|
||||
|
||||
internal val SESSION_KEYS = setOf(
|
||||
"orientation", "launcherFullscreen", "controllerHaptics", "animations", "lowStorageWarning", "theme", "runSteamAtStartup", "startupSession", "addedGamesArt",
|
||||
"dualScreenMode", "dualScreenSessionMode", "dualScreenLauncher", "dualScreenSessionControls", "androidTextFieldKeyboard",
|
||||
"drawerWidthDp", "dualScreenMode", "dualScreenSessionMode", "dualScreenLauncher", "dualScreenSessionControls", "androidTextFieldKeyboard",
|
||||
"soundtracksIngame", "gameStoresSpeedTier", "gameStoresParallel", "storesOpenTab", "storesShowMature",
|
||||
"storesInstallLanguage",
|
||||
"hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "__KEEP_droidDeckHud__", "__KEEP_droidDeckHudPos__", "backHold", "dockedMenuController", "backActionsInverted", "backDoubleTapMs", "touch", "pen", "penButton", "osc", "shape", "steamController",
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import java.io.File
|
||||
import kotlinx.coroutines.flow.update
|
||||
|
||||
/**
|
||||
* Downloads Valve's Steam client while the session is stopped, so the first Play does not wait on it.
|
||||
* It runs the same droiddeck-steam-install the session runs, which keeps what arrived when it is cut
|
||||
* short and resumes from there.
|
||||
*/
|
||||
object SteamClientPrefetch {
|
||||
private const val TAG = "SteamClientPrefetch"
|
||||
private val DOWNLOADING = Regex("""downloading Steam: .*, (\d+) of (\d+) MB""")
|
||||
|
||||
private const val CANCELLED = "cancelled"
|
||||
private val lock = Any()
|
||||
private var process: Process? = null
|
||||
private var cancelled = false
|
||||
@Volatile private var thread: Thread? = null
|
||||
|
||||
internal fun parse(line: String): Pair<Int, Int>? {
|
||||
val match = DOWNLOADING.find(line) ?: return null
|
||||
val done = match.groupValues[1].toLongOrNull() ?: return null
|
||||
val total = match.groupValues[2].toLongOrNull()?.takeIf { it > 0 } ?: return null
|
||||
return (done * 100 / total).toInt().coerceIn(0, 100) to total.toInt()
|
||||
}
|
||||
|
||||
fun running(): Boolean = thread?.isAlive == true
|
||||
|
||||
private const val CACHED = "root/.local/share/Steam/package/droiddeck-cached"
|
||||
|
||||
fun installPending(context: Context): Boolean = SteamDownloadMonitor.clientInstallPending(LinuxRuntime.rootDir(context))
|
||||
|
||||
fun pending(context: Context): Boolean =
|
||||
installPending(context) || !File(LinuxRuntime.rootDir(context), CACHED).isFile
|
||||
|
||||
/** Stops a running download so a session can take over; the script resumes the partial files. */
|
||||
fun cancel() {
|
||||
synchronized(lock) {
|
||||
cancelled = true
|
||||
process?.destroy()
|
||||
}
|
||||
}
|
||||
|
||||
private fun isCancelled() = synchronized(lock) { cancelled }
|
||||
|
||||
@Synchronized
|
||||
fun start(context: Context, label: (Int) -> String, failedLabel: String) {
|
||||
if (running() || SessionState.running || !LinuxRuntime.isInstalled(context) || !pending(context)) return
|
||||
val app = context.applicationContext
|
||||
synchronized(lock) { cancelled = false }
|
||||
thread = Thread({
|
||||
Onboarding.report(Onboarding.Step.STEAM, label(-1), -1)
|
||||
val problem = runCatching { run(app, label) }.getOrElse { it.message ?: it.javaClass.simpleName }
|
||||
synchronized(lock) { process = null }
|
||||
if (problem == null && !pending(app)) Onboarding.finish(Onboarding.Step.STEAM)
|
||||
else if (SessionState.running || problem == CANCELLED || isCancelled()) Onboarding.finish(Onboarding.Step.STEAM)
|
||||
else Onboarding.fail(Onboarding.Step.STEAM, problem ?: failedLabel)
|
||||
val steamReady = !pending(app)
|
||||
Onboarding.facts.update { it.copy(steam = steamReady) }
|
||||
}, "steam-client-prefetch").also { it.start() }
|
||||
}
|
||||
|
||||
private fun run(context: Context, label: (Int) -> String): String? {
|
||||
if (isCancelled()) return CANCELLED
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
LinuxRuntime.writeAccounts(context)
|
||||
SessionFiles.stage(context, root)
|
||||
val install = installPending(context)
|
||||
if (install) {
|
||||
val problem = script(context, emptyList(), label, 0, 35)
|
||||
if (problem != null) return problem
|
||||
}
|
||||
return script(context, listOf("--cache"), label, if (install) 35 else 0, 100)
|
||||
}
|
||||
|
||||
private fun script(context: Context, args: List<String>, label: (Int) -> String, from: Int, to: Int): String? {
|
||||
val guest = listOf(
|
||||
"/usr/bin/env", "-i", "HOME=/root", "USER=root", "PATH=/usr/local/bin:/usr/bin:/bin",
|
||||
"LANG=C.UTF-8", "XDG_DATA_HOME=/root/.local/share", "/usr/local/bin/droiddeck-steam-install",
|
||||
) + args
|
||||
if (isCancelled()) return CANCELLED
|
||||
val child = ProtonExtras.guestProcess(context, guest).start()
|
||||
synchronized(lock) {
|
||||
if (cancelled) {
|
||||
child.destroy()
|
||||
return CANCELLED
|
||||
}
|
||||
process = child
|
||||
}
|
||||
child.inputStream.bufferedReader().useLines { lines ->
|
||||
lines.forEach { line ->
|
||||
Log.i(TAG, line)
|
||||
val progress = parse(line)
|
||||
if (progress != null) Onboarding.report(Onboarding.Step.STEAM, label(progress.second), from + progress.first * (to - from) / 100)
|
||||
}
|
||||
}
|
||||
val status = child.waitFor()
|
||||
return if (status == 0) null else "droiddeck-steam-install exited $status"
|
||||
}
|
||||
}
|
||||
@@ -103,7 +103,9 @@ internal class XboxInstaller(private val app: Context, private val item: Catalog
|
||||
XboxContent.complete(app, item, folder)
|
||||
return folder.path
|
||||
}
|
||||
val exe = executable(folder)
|
||||
val exe = runCatching { executable(folder) }.onFailure {
|
||||
StoresState.logLine("Xbox: install folder holds ${folder.list().orEmpty().sorted().take(MAX_ERROR_LINES).joinToString()}")
|
||||
}.getOrThrow()
|
||||
StoreInstalls.complete(app, folder, StoreGameSidecar(Store.XBOX, item.id, item.title, exe,
|
||||
installVersion = XboxManifest.read(folder).version, installedAt = System.currentTimeMillis(), cover = item.tallImageUrl, hero = item.imageUrl,
|
||||
extra = item.extra + mapOf("contentId" to selected, "market" to market)))
|
||||
|
||||
@@ -21,8 +21,9 @@ internal object XboxManifest {
|
||||
val files = folder.listFiles().orEmpty()
|
||||
val config = files.filter { it.name.equals(GAME_CONFIG, true) && it.isFile }
|
||||
val legacy = files.filter { it.name.equals(APPX_MANIFEST, true) && it.isFile }
|
||||
require(config.size + legacy.size == 1) { "Missing or ambiguous game manifest." }
|
||||
val manifest = (config + legacy).single()
|
||||
val manifests = config.ifEmpty { legacy }
|
||||
require(manifests.size == 1) { "Missing or ambiguous game manifest." }
|
||||
val manifest = manifests.single()
|
||||
val rootTag = if (config.isEmpty()) "Package" else "Game"
|
||||
require(manifest.length() <= 1_048_576)
|
||||
val parser = android.util.Xml.newPullParser().apply { setFeature(XmlPullParser.FEATURE_PROCESS_DOCDECL, false) }
|
||||
|
||||
@@ -110,6 +110,9 @@ internal class CurseLink(val app: UserApps.App) {
|
||||
private val guids = HashMap<String, String>()
|
||||
private val scanLock = Object()
|
||||
private val scans = HashMap<String, Pair<Any, List<CurseForgeApp.Project>>>()
|
||||
private val settleLock = Object()
|
||||
private val settled = HashMap<String, Pair<Int, List<CurseForgeApp.Project>>>()
|
||||
private val turns = HashMap<String, Int>()
|
||||
var generation by mutableIntStateOf(0)
|
||||
private set
|
||||
|
||||
@@ -120,7 +123,7 @@ internal class CurseLink(val app: UserApps.App) {
|
||||
fun installed(context: Context, target: WowAddons.Target, key: Any): List<CurseForgeApp.Project> = CurseForgeApp.onDisk(
|
||||
synchronized(scanLock) {
|
||||
scans[target.addOns.path]?.takeIf { it.first == key }?.second
|
||||
?: call(context, target) { CurseForgeApp.projects(context, it.inspector, it.guid, rescan = true) }.also {
|
||||
?: (settledFor(target) ?: call(context, target) { CurseForgeApp.projects(context, it.inspector, it.guid, rescan = true) }).also {
|
||||
scans[target.addOns.path] = key to it
|
||||
report(target, it)
|
||||
}
|
||||
@@ -131,6 +134,26 @@ internal class CurseLink(val app: UserApps.App) {
|
||||
fun marks(context: Context, target: WowAddons.Target, key: Any): Map<String, String?> =
|
||||
runCatching { installed(context, target, key).associate { it.id to curseMark(it) } }.getOrElse { lastReported(target) }
|
||||
|
||||
private fun settledFor(target: WowAddons.Target): List<CurseForgeApp.Project>? = synchronized(settleLock) {
|
||||
settled.remove(target.addOns.path)?.takeIf { it.first == generation }?.second
|
||||
}
|
||||
|
||||
fun change(context: Context, target: WowAddons.Target, launch: Boolean = true, block: (Linked) -> List<CurseForgeApp.Project>?): Boolean {
|
||||
val path = target.addOns.path
|
||||
val turn = synchronized(settleLock) {
|
||||
settled.remove(path)
|
||||
((turns[path] ?: 0) + 1).also { turns[path] = it }
|
||||
}
|
||||
val projects = call(context, target, launch, block) ?: return false
|
||||
synchronized(settleLock) {
|
||||
if (turns[path] == turn) {
|
||||
settled[path] = generation to projects
|
||||
report(target, projects)
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
fun <T> call(context: Context, target: WowAddons.Target, launch: Boolean = true, block: (Linked) -> T): T {
|
||||
val linked = synchronized(lock) { link(context, target, launch) }
|
||||
try {
|
||||
@@ -174,11 +197,9 @@ internal class CurseLink(val app: UserApps.App) {
|
||||
return Linked(url, guid)
|
||||
}
|
||||
|
||||
fun uninstall(context: Context, target: WowAddons.Target, folder: String): Boolean = call(context, target, launch = false) { linked ->
|
||||
fun uninstall(context: Context, target: WowAddons.Target, folder: String): Boolean = change(context, target, launch = false) { linked ->
|
||||
val projects = CurseForgeApp.onDisk(CurseForgeApp.projects(context, linked.inspector, linked.guid), target.addOns)
|
||||
val project = CurseForgeApp.owner(projects, folder) ?: return@call false
|
||||
if (!CurseForgeApp.uninstall(context, linked.inspector, linked.guid, project)) throw CurseState()
|
||||
true
|
||||
CurseForgeApp.owner(projects, folder)?.let { CurseForgeApp.uninstall(context, linked.inspector, linked.guid, it) ?: throw CurseState() }
|
||||
}
|
||||
|
||||
internal val stopped: Job get() = work
|
||||
@@ -322,7 +343,7 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
|
||||
scope.launch {
|
||||
val done = withContext(Dispatchers.IO) {
|
||||
runCatching {
|
||||
via.call(context, into) {
|
||||
via.change(context, into) {
|
||||
if (updating) CurseForgeApp.update(context, it.inspector, it.guid, addon.id)
|
||||
else CurseForgeApp.install(context, it.inspector, it.guid, addon.id)
|
||||
}
|
||||
|
||||
@@ -175,7 +175,7 @@ internal fun SessionDrawerPreview(secondScreens: List<SecondScreenDisplay>) {
|
||||
val code = e.nativeKeyEvent.keyCode
|
||||
if (code != android.view.KeyEvent.KEYCODE_BUTTON_L1 && code != android.view.KeyEvent.KEYCODE_BUTTON_R1) return@onPreviewKeyEvent false
|
||||
if (e.type == KeyEventType.KeyDown && e.nativeKeyEvent.repeatCount == 0) {
|
||||
page = sessionDrawerPages().step(page, if (code == android.view.KeyEvent.KEYCODE_BUTTON_R1) 1 else -1)
|
||||
page = sessionDrawerPages().let { it.strip().step(it.tabFor(page), if (code == android.view.KeyEvent.KEYCODE_BUTTON_R1) 1 else -1) }
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
@@ -33,6 +33,8 @@ import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.Outline
|
||||
import androidx.compose.ui.graphics.Shape
|
||||
import androidx.compose.ui.graphics.drawscope.Stroke
|
||||
import androidx.compose.ui.graphics.Path
|
||||
import androidx.compose.ui.geometry.RoundRect
|
||||
import androidx.compose.ui.layout.LayoutCoordinates
|
||||
import androidx.compose.ui.layout.onGloballyPositioned
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
@@ -109,13 +111,21 @@ internal fun VeilRing() {
|
||||
}
|
||||
}
|
||||
|
||||
private fun cornerOf(shape: Shape, size: Size, dir: LayoutDirection, density: Density): Float =
|
||||
private fun cornersOf(shape: Shape, size: Size, dir: LayoutDirection, density: Density): FloatArray =
|
||||
when (val o = shape.createOutline(size, dir, density)) {
|
||||
is Outline.Rounded -> o.roundRect.topLeftCornerRadius.x
|
||||
is Outline.Rectangle -> 0f
|
||||
is Outline.Generic -> minOf(size.width, size.height) / 2f
|
||||
is Outline.Rounded -> o.roundRect.run {
|
||||
floatArrayOf(topLeftCornerRadius.x, topRightCornerRadius.x, bottomRightCornerRadius.x, bottomLeftCornerRadius.x)
|
||||
}
|
||||
is Outline.Rectangle -> FloatArray(4)
|
||||
is Outline.Generic -> FloatArray(4) { minOf(size.width, size.height) / 2f }
|
||||
}
|
||||
|
||||
private fun ringRect(l: Float, t: Float, w: Float, h: Float, radii: FloatArray, inset: Float): Path {
|
||||
// Radii are not capped one by one: the path scales corners whose neighbours overlap, as the outline does.
|
||||
fun r(i: Int) = CornerRadius((radii[i] - inset).coerceAtLeast(0f))
|
||||
return Path().apply { addRoundRect(RoundRect(Rect(l, t, l + w, t + h), r(0), r(1), r(2), r(3))) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun Modifier.glideBorder(
|
||||
hot: Boolean,
|
||||
@@ -190,7 +200,7 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier {
|
||||
val density = LocalDensity.current
|
||||
val dir = LocalLayoutDirection.current
|
||||
val edges = remember { List(4) { Animatable(0f) } }
|
||||
val corner = remember { Animatable(0f) }
|
||||
val corners = remember { List(4) { Animatable(0f) } }
|
||||
val solid = remember { Animatable(0f) }
|
||||
val alpha = remember { Animatable(0f) }
|
||||
val scope = rememberCoroutineScope()
|
||||
@@ -259,14 +269,14 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier {
|
||||
fun droplet(s: GlideSource, b: Rect) {
|
||||
jobs.forEach { it?.cancel() }
|
||||
val size = s.coords?.size?.let { Size(it.width.toFloat(), it.height.toFloat()) } ?: b.size
|
||||
val endCorner = cornerOf(s.shape, size, dir, density)
|
||||
val endCorners = cornersOf(s.shape, size, dir, density)
|
||||
jobs[5] = scope.launch {
|
||||
val r = with(density) { 6.dp.toPx() }
|
||||
fun dot(c: Offset) = listOf(c.x - r, c.y - r, c.x + r, c.y + r)
|
||||
val here = Offset((edges[0].value + edges[2].value) / 2f, (edges[1].value + edges[3].value) / 2f)
|
||||
coroutineScope {
|
||||
launch { solid.animateTo(1f, Motion.tw(80)) }
|
||||
launch { corner.animateTo(r, Motion.tw(90)) }
|
||||
corners.forEach { c -> launch { c.animateTo(r, Motion.tw(90)) } }
|
||||
dot(here).forEachIndexed { i, v -> launch { edges[i].animateTo(v, Motion.tw(90)) } }
|
||||
}
|
||||
val distance = hypot(b.center.x - here.x, b.center.y - here.y) / density.density
|
||||
@@ -281,7 +291,9 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier {
|
||||
flight.cancel()
|
||||
val at = glide.boundsOf(s) ?: b
|
||||
launch { solid.animateTo(0f, Motion.tw(150)) }
|
||||
launch { corner.animateTo(endCorner, Motion.sp(0.8f, 600f)) }
|
||||
// The droplet job is cancelled by the next move, so the shape settles on the corner job instead.
|
||||
jobs[4]?.cancel()
|
||||
jobs[4] = scope.launch { corners.forEachIndexed { i, c -> launch { c.animateTo(endCorners[i], Motion.sp(0.8f, 600f)) } } }
|
||||
listOf(at.left, at.top, at.right, at.bottom).forEachIndexed { i, v ->
|
||||
jobs[i] = launch { edges[i].animateTo(v, Motion.sp(0.7f, 750f)) }
|
||||
}
|
||||
@@ -289,9 +301,11 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier {
|
||||
}
|
||||
fun cornerTo(s: GlideSource, b: Rect, snap: Boolean) {
|
||||
val size = s.coords?.size?.let { Size(it.width.toFloat(), it.height.toFloat()) } ?: b.size
|
||||
val r = cornerOf(s.shape, size, dir, density)
|
||||
val r = cornersOf(s.shape, size, dir, density)
|
||||
jobs[4]?.cancel()
|
||||
jobs[4] = scope.launch { if (snap) corner.snapTo(r) else corner.animateTo(r, Motion.sp(0.8f, 500f)) }
|
||||
jobs[4] = scope.launch {
|
||||
corners.forEachIndexed { i, c -> launch { if (snap) c.snapTo(r[i]) else c.animateTo(r[i], Motion.sp(0.8f, 500f)) } }
|
||||
}
|
||||
}
|
||||
snapshotFlow { Triple(glide.current, glide.moves, glide.hidden || RingVeil.count > 0) }.collectLatest { (src, _, hidden) ->
|
||||
if (Motion.scale == 0f) {
|
||||
@@ -302,7 +316,7 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier {
|
||||
else {
|
||||
listOf(b.left, b.top, b.right, b.bottom).forEachIndexed { i, v -> edges[i].snapTo(v) }
|
||||
val size = src.coords?.size?.let { Size(it.width.toFloat(), it.height.toFloat()) } ?: b.size
|
||||
corner.snapTo(cornerOf(src.shape, size, dir, density))
|
||||
cornersOf(src.shape, size, dir, density).forEachIndexed { i, v -> corners[i].snapTo(v) }
|
||||
alpha.snapTo(1f)
|
||||
}
|
||||
shown = src
|
||||
@@ -343,10 +357,11 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier {
|
||||
val out = with(density) { 3.dp.toPx() }
|
||||
val grown = listOf(b.left - out, b.top - out, b.right + out, b.bottom + out)
|
||||
jobs.forEach { it?.cancel() }
|
||||
// Set before the join: a move of the target restarts this block there, after shown is already set.
|
||||
cornerTo(src, b, snap = true)
|
||||
scope.launch { solid.snapTo(0f); edges.forEachIndexed { i, e -> e.snapTo(grown[i]) } }.join()
|
||||
dirSpecs = List(4) { Edge(0.6f, 700f) }
|
||||
delays = LongArray(4)
|
||||
cornerTo(src, b, snap = true)
|
||||
scope.launch { alpha.animateTo(1f, Motion.tw(140)) }
|
||||
} else {
|
||||
val dx = b.center.x - (edges[0].value + edges[2].value) / 2f
|
||||
@@ -394,21 +409,13 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier {
|
||||
val l = edges[0].value; val t = edges[1].value; val r = edges[2].value; val b = edges[3].value
|
||||
val sw = (r - l - w).coerceAtLeast(0f)
|
||||
val sh = (b - t - w).coerceAtLeast(0f)
|
||||
val rad = (corner.value - w / 2f).coerceIn(0f, minOf(sw, sh) / 2f)
|
||||
val radii = FloatArray(4) { corners[it].value }
|
||||
val f = solid.value
|
||||
if (f > 0.01f) drawRoundRect(
|
||||
color, topLeft = Offset(l, t), size = Size(r - l, b - t),
|
||||
cornerRadius = CornerRadius(corner.value), alpha = a * f,
|
||||
)
|
||||
if (f > 0.01f) drawPath(ringRect(l, t, r - l, b - t, radii, 0f), color, alpha = a * f)
|
||||
if (f < 0.99f) {
|
||||
drawRoundRect(
|
||||
color, topLeft = Offset(l + w / 2f, t + w / 2f), size = Size(sw, sh),
|
||||
cornerRadius = CornerRadius(rad), alpha = a * (1f - f) * fillAlpha,
|
||||
)
|
||||
drawRoundRect(
|
||||
color, topLeft = Offset(l + w / 2f, t + w / 2f), size = Size(sw, sh),
|
||||
cornerRadius = CornerRadius(rad), style = Stroke(w), alpha = a,
|
||||
)
|
||||
val inner = ringRect(l + w / 2f, t + w / 2f, sw, sh, radii, w / 2f)
|
||||
drawPath(inner, color, alpha = a * (1f - f) * fillAlpha)
|
||||
drawPath(inner, color, style = Stroke(w), alpha = a)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -271,6 +271,10 @@ private fun Content(
|
||||
UpdatesPage(s, a, modifier.padding(horizontal = padH).padding(top = padV))
|
||||
return
|
||||
}
|
||||
if (selected == "trinkets") {
|
||||
TrinketsPage(modifier.padding(horizontal = padH).padding(top = padV))
|
||||
return
|
||||
}
|
||||
if (selected == "steam") {
|
||||
SteamHome(s, a, modifier)
|
||||
return
|
||||
|
||||
@@ -59,6 +59,7 @@ import androidx.compose.material.icons.filled.SdStorage
|
||||
import androidx.compose.material.icons.filled.Movie
|
||||
import androidx.compose.material.icons.filled.Sync
|
||||
import androidx.compose.material.icons.filled.MoreHoriz
|
||||
import androidx.compose.material.icons.filled.Toys
|
||||
import androidx.compose.material.icons.automirrored.outlined.ArrowBack
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.material3.Icon
|
||||
@@ -205,6 +206,7 @@ internal fun railLabelIcon(key: String): Pair<Int, ImageVector> = when (key) {
|
||||
"agent" -> R.string.rail_agent to Icons.Filled.Terminal
|
||||
"android-apps" -> R.string.rail_apps to Icons.Filled.Apps
|
||||
"setup" -> R.string.rail_setup to Icons.Filled.Settings
|
||||
"trinkets" -> R.string.rail_trinkets to Icons.Filled.Toys
|
||||
"storage" -> R.string.rail_storage to Icons.Filled.SdStorage
|
||||
"sync" -> R.string.rail_sync to Icons.Filled.Sync
|
||||
"decky" -> R.string.rail_decky to DeckyIcon
|
||||
|
||||
@@ -51,6 +51,7 @@ import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
@@ -248,6 +249,7 @@ internal fun SetupPanel(
|
||||
if (listing) SettingsSearchResults(query) { section -> pick(section.ordinal) }
|
||||
else when (tab) {
|
||||
OVERVIEW_TAB -> {
|
||||
OnboardingCard(limitBlocks, a.onShowPhantomGate)
|
||||
// Setup's "Safe mode" row, under the GPU row while the bridge is on and can be used here.
|
||||
val bridgeModeRow = !s.adreno && s.vkBridge && com.droiddeck.launcher.core.DeviceSupport.bridgeUsable()
|
||||
val gpuCheck: @Composable (Boolean) -> Unit = { divider ->
|
||||
@@ -1273,3 +1275,65 @@ private fun CustomColorRows() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun OnboardingCard(limitBlocks: Boolean = false, onSetUpLimit: () -> Unit = {}) {
|
||||
val active by com.droiddeck.launcher.session.Onboarding.active.collectAsState()
|
||||
val failed by com.droiddeck.launcher.session.Onboarding.failed.collectAsState()
|
||||
val facts by com.droiddeck.launcher.session.Onboarding.facts.collectAsState()
|
||||
val rows = com.droiddeck.launcher.session.Onboarding.rows(active, failed, facts)
|
||||
val settling = com.droiddeck.launcher.session.Onboarding.pending(rows)
|
||||
if (!settling) return
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val overall = com.droiddeck.launcher.session.Onboarding.overall(rows)
|
||||
Column(Modifier.fillMaxWidth().padding(top = 8.dp).clip(Shape14).background(colors.surface).border(1.dp, pal.line, Shape14)) {
|
||||
Column(Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 12.dp)) {
|
||||
Text(stringResource(R.string.onboarding_title), fontSize = 17.sp, fontWeight = FontWeight.Bold, color = colors.onBackground)
|
||||
Text(stringResource(R.string.onboarding_summary, overall), fontSize = 13.sp, color = colors.onSurfaceVariant)
|
||||
LinearProgressIndicator(progress = { overall / 100f }, modifier = Modifier.fillMaxWidth().padding(top = 8.dp).height(4.dp))
|
||||
}
|
||||
rows.forEach { row ->
|
||||
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 10.dp),
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(
|
||||
stringResource(when (row.step) {
|
||||
com.droiddeck.launcher.session.Onboarding.Step.RUNTIME -> R.string.onboarding_step_runtime
|
||||
com.droiddeck.launcher.session.Onboarding.Step.PROTON -> R.string.onboarding_step_proton
|
||||
com.droiddeck.launcher.session.Onboarding.Step.STEAM -> R.string.onboarding_step_steam
|
||||
}),
|
||||
fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground,
|
||||
)
|
||||
val detail = when (row.state) {
|
||||
com.droiddeck.launcher.session.Onboarding.State.ACTIVE -> row.label.orEmpty()
|
||||
com.droiddeck.launcher.session.Onboarding.State.FAILED -> stringResource(R.string.onboarding_failed)
|
||||
com.droiddeck.launcher.session.Onboarding.State.WAITING -> stringResource(R.string.onboarding_waiting)
|
||||
com.droiddeck.launcher.session.Onboarding.State.DONE -> stringResource(R.string.onboarding_done)
|
||||
}
|
||||
Text(detail, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
if (row.state == com.droiddeck.launcher.session.Onboarding.State.ACTIVE) {
|
||||
if (row.percent >= 0) LinearProgressIndicator(progress = { row.percent / 100f }, modifier = Modifier.fillMaxWidth().padding(top = 6.dp).height(3.dp))
|
||||
else LinearProgressIndicator(modifier = Modifier.fillMaxWidth().padding(top = 6.dp).height(3.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (limitBlocks) {
|
||||
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 10.dp),
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(stringResource(R.string.setup_limit), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
|
||||
Text(stringResource(R.string.onboarding_limit_reason), fontSize = 13.sp, color = colors.onSurfaceVariant)
|
||||
}
|
||||
PrimaryButton(stringResource(R.string.onboarding_limit_action), compact = true, onClick = onSetUpLimit)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1157,7 +1157,7 @@ internal fun AddonRow(item: WowAddons.Installed, wowiUpdate: WowAddonCatalog.Add
|
||||
val message = withContext(Dispatchers.IO) {
|
||||
if (curse != null) {
|
||||
val (project, link) = curse
|
||||
val done = runCatching { link.call(context, target) { CurseForgeApp.update(context, it.inspector, it.guid, project.id) } }.getOrDefault(false)
|
||||
val done = runCatching { link.change(context, target) { CurseForgeApp.update(context, it.inspector, it.guid, project.id) } }.getOrDefault(false)
|
||||
WowAddons.changed()
|
||||
if (done) context.getString(R.string.user_apps_updated, name) else context.getString(R.string.stores_dl_failed_reason, name)
|
||||
} else update?.let { installAddon(context, it, target) { pct -> scope.launch { progress = pct } }.first }
|
||||
|
||||
@@ -57,7 +57,7 @@ internal fun ManageDrawerPages(offeredNow: List<SessionDrawerPage>, modifier: Mo
|
||||
SortableRows(
|
||||
rows = { current.map { it.name } },
|
||||
commit = { names -> DrawerPages.rearrange(ctx, names.mapNotNull { n -> current.firstOrNull { it.name == n } }) },
|
||||
movable = { true },
|
||||
movable = { it != SessionDrawerPage.MORE.name },
|
||||
rowHeight = STORE_ROW, handleWidth = STORE_HANDLE,
|
||||
releaseSignal = releaseSignal,
|
||||
onGrab = { before -> DrawerPages.heldFrom = before?.mapNotNull { n -> current.firstOrNull { it.name == n } } },
|
||||
@@ -66,6 +66,8 @@ internal fun ManageDrawerPages(offeredNow: List<SessionDrawerPage>, modifier: Mo
|
||||
},
|
||||
) { name, held, offset, hint, rowModifier, onFocus ->
|
||||
val page = current.first { it.name == name }
|
||||
// The same divider the launcher's Edit tabs uses: pages above it are tabs, pages below it are kept in More.
|
||||
if (page == SessionDrawerPage.MORE) { MoreLine(STORE_ROW); return@SortableRows }
|
||||
val shown = page !in DrawerPages.hidden
|
||||
val pal = LocalPalette.current
|
||||
val label = stringResource(page.title)
|
||||
|
||||
@@ -202,7 +202,7 @@ internal fun SideSheet(open: Boolean, onClose: () -> Unit, returnFocus: FocusReq
|
||||
if (!pad) return@LaunchedEffect
|
||||
repeat(60) {
|
||||
androidx.compose.runtime.withFrameNanos { }
|
||||
if (holds || !open) return@LaunchedEffect
|
||||
if (holds || !open || Steps.open) return@LaunchedEffect
|
||||
runCatching { inside.requestFocus() }
|
||||
}
|
||||
}
|
||||
@@ -210,7 +210,7 @@ internal fun SideSheet(open: Boolean, onClose: () -> Unit, returnFocus: FocusReq
|
||||
Modifier.width(width).fillMaxHeight()
|
||||
.onFocusChanged { holds = it.hasFocus }
|
||||
.focusRequester(inside)
|
||||
.focusProperties { exit = { if (open) FocusRequester.Cancel else FocusRequester.Default } }
|
||||
.focusProperties { exit = { if (open && !Steps.open) FocusRequester.Cancel else FocusRequester.Default } }
|
||||
.focusGroup()
|
||||
.background(MaterialTheme.colorScheme.background)
|
||||
.border(1.dp, pal.line).padding(horizontal = 18.dp, vertical = 16.dp).testTag(tag),
|
||||
|
||||
@@ -26,8 +26,8 @@ internal object DeveloperTools {
|
||||
|
||||
internal object NavTabs {
|
||||
const val MORE = "more"
|
||||
val ALL = listOf("steam", "desktop", "games", "downloads", "setup", "updates", "stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent")
|
||||
val DEFAULT_SHELVED = setOf("stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent")
|
||||
val ALL = listOf("steam", "desktop", "games", "downloads", "setup", "updates", "trinkets", "stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent")
|
||||
val DEFAULT_SHELVED = setOf("soundtracks", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent")
|
||||
val DEFAULT_HIDDEN = setOf("android-apps", "agent")
|
||||
private val SHELVED_WHEN_NEW = setOf("storage", "sync", "decky", "boot-movies", "android-apps", "agent")
|
||||
private val OLD_ORDER = listOf("steam", "games", "soundtracks", "stores", "downloads", "desktop", "agent", "components", "android-apps", "storage", "sync", "setup", "updates")
|
||||
|
||||
@@ -12,10 +12,11 @@ internal enum class SessionDrawerPage(val firstControl: String) {
|
||||
DISPLAY("fg"),
|
||||
HUD("hud"),
|
||||
EFFECTS("look"),
|
||||
VR("steamvr"),
|
||||
GAMES("anisotropy"),
|
||||
AGENT("agent-input"),
|
||||
SESSION("suspend"),
|
||||
MORE("more-edit"),
|
||||
VR("steamvr"),
|
||||
}
|
||||
|
||||
internal object DrawerPages {
|
||||
@@ -27,7 +28,7 @@ internal object DrawerPages {
|
||||
/** The order captured when a page row was grabbed in Arrange pages; Back restores it. */
|
||||
var heldFrom: List<SessionDrawerPage>? = null
|
||||
|
||||
fun hideable(page: SessionDrawerPage) = page != SessionDrawerPage.SESSION
|
||||
fun hideable(page: SessionDrawerPage) = page != SessionDrawerPage.SESSION && page != SessionDrawerPage.MORE
|
||||
|
||||
fun load(context: Context) {
|
||||
order = arrange(SessionPrefs.drawerPageOrder(context))
|
||||
@@ -81,6 +82,22 @@ internal fun sessionDrawerPages(
|
||||
hasGlasses: Boolean = false, hasAgent: Boolean = com.droiddeck.launcher.agent.AgentTab.shown,
|
||||
): List<SessionDrawerPage> = offeredDrawerPages(hasGlasses, hasAgent).filter { it !in DrawerPages.hidden }
|
||||
|
||||
/** The pages shown as tabs: everything up to and including the More tab. */
|
||||
internal fun List<SessionDrawerPage>.strip(): List<SessionDrawerPage> {
|
||||
val more = indexOf(SessionDrawerPage.MORE)
|
||||
return if (more < 0) this else subList(0, more + 1)
|
||||
}
|
||||
|
||||
/** The pages kept inside More: those after the More tab. */
|
||||
internal fun List<SessionDrawerPage>.inMore(): List<SessionDrawerPage> {
|
||||
val more = indexOf(SessionDrawerPage.MORE)
|
||||
return if (more < 0) emptyList() else subList(more + 1, size)
|
||||
}
|
||||
|
||||
/** The tab that stands for [page]: the More tab for a page kept inside More. */
|
||||
internal fun List<SessionDrawerPage>.tabFor(page: SessionDrawerPage): SessionDrawerPage =
|
||||
if (page in inMore()) SessionDrawerPage.MORE else page
|
||||
|
||||
internal fun List<SessionDrawerPage>.step(current: SessionDrawerPage, direction: Int): SessionDrawerPage {
|
||||
val index = indexOf(current).coerceAtLeast(0)
|
||||
return this[Math.floorMod(index + direction, size)]
|
||||
|
||||
@@ -39,6 +39,7 @@ import androidx.compose.material.icons.outlined.AutoFixHigh
|
||||
import androidx.compose.material.icons.outlined.ExpandMore
|
||||
import androidx.compose.material.icons.outlined.Home
|
||||
import androidx.compose.material.icons.outlined.MoreHoriz
|
||||
import androidx.compose.material.icons.automirrored.outlined.ArrowBack
|
||||
import androidx.compose.material.icons.outlined.PowerSettingsNew
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.material.icons.outlined.DesktopWindows
|
||||
@@ -95,6 +96,14 @@ import androidx.compose.ui.ExperimentalComposeUiApi
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.runtime.rememberUpdatedState
|
||||
import android.view.KeyEvent
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.foundation.gestures.awaitEachGesture
|
||||
import androidx.compose.foundation.gestures.awaitFirstDown
|
||||
import androidx.compose.ui.layout.positionInRoot
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.HomeApp
|
||||
@@ -174,6 +183,7 @@ internal val SessionDrawerPage.title: Int get() = when (this) {
|
||||
SessionDrawerPage.GAMES -> R.string.game_settings_title
|
||||
SessionDrawerPage.AGENT -> R.string.rail_agent
|
||||
SessionDrawerPage.SESSION -> R.string.mode_session
|
||||
SessionDrawerPage.MORE -> R.string.drawer_page_more
|
||||
}
|
||||
|
||||
internal val SessionDrawerPage.icon get() = when (this) {
|
||||
@@ -186,6 +196,7 @@ internal val SessionDrawerPage.icon get() = when (this) {
|
||||
SessionDrawerPage.GAMES -> Icons.Outlined.Layers
|
||||
SessionDrawerPage.AGENT -> Icons.Outlined.Terminal
|
||||
SessionDrawerPage.SESSION -> Icons.Outlined.Settings
|
||||
SessionDrawerPage.MORE -> Icons.Outlined.MoreHoriz
|
||||
}
|
||||
|
||||
private class DrawerFocus {
|
||||
@@ -261,6 +272,8 @@ class DrawerActions(
|
||||
val textureLodBias: String? = TextureFiltering.LOD_BIAS_OFF,
|
||||
val secondScreenMode: SecondScreenMode,
|
||||
val secondScreenNone: Boolean = true,
|
||||
val dualScreenMode: String = com.droiddeck.launcher.input.DualScreen.MODE_AUTO,
|
||||
val onDualScreenMode: (String) -> Unit = {},
|
||||
val gameOnBottom: Boolean = false,
|
||||
val gameSwapAvailable: Boolean = false,
|
||||
val gameSwapBuiltIn: Boolean = true,
|
||||
@@ -418,6 +431,8 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
var appToChooseDisplay by remember { mutableStateOf<HomeApp.LaunchableApp?>(null) }
|
||||
var confirmStop by remember { mutableStateOf(false) }
|
||||
var sheetCoords by remember { mutableStateOf<LayoutCoordinates?>(null) }
|
||||
val widthContext = LocalContext.current
|
||||
var savedWidth by remember { mutableStateOf(SessionPrefs.drawerWidthDp(widthContext)) }
|
||||
var stopCoords by remember { mutableStateOf<LayoutCoordinates?>(null) }
|
||||
val pageScroll = remember { SessionDrawerPage.entries.associateWith { ScrollState(0) } }
|
||||
LaunchedEffect(glassesTab) {
|
||||
@@ -428,11 +443,17 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
val focus = remember { DrawerFocus() }
|
||||
val inputModeManager = LocalInputModeManager.current
|
||||
val focusManager = LocalFocusManager.current
|
||||
// A page kept inside More is one step deeper than the strip: back returns to More before it closes the menu.
|
||||
val insideMore = page in pages.inMore()
|
||||
BackHandler(enabled = open) {
|
||||
if (host.open != null) host.open = null else a.onClose()
|
||||
when {
|
||||
host.open != null -> host.open = null
|
||||
insideMore -> onPageChange(SessionDrawerPage.MORE)
|
||||
else -> a.onClose()
|
||||
}
|
||||
}
|
||||
BackHandler(enabled = open && confirmStop) { confirmStop = false }
|
||||
val layerOpen = open && (host.open != null || appToChooseDisplay != null || confirmStop)
|
||||
val layerOpen = open && (host.open != null || appToChooseDisplay != null || confirmStop || insideMore)
|
||||
LaunchedEffect(layerOpen) { onLayerChange(layerOpen) }
|
||||
var seenBackRequest by remember { mutableStateOf(backRequest) }
|
||||
LaunchedEffect(backRequest) {
|
||||
@@ -442,9 +463,10 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
confirmStop -> confirmStop = false
|
||||
appToChooseDisplay != null -> appToChooseDisplay = null
|
||||
host.open != null -> host.open = null
|
||||
insideMore -> onPageChange(SessionDrawerPage.MORE)
|
||||
}
|
||||
}
|
||||
LaunchedEffect(page) { host.open = null; appToChooseDisplay = null }
|
||||
LaunchedEffect(page) { host.open = null; appToChooseDisplay = null; managing = false }
|
||||
LaunchedEffect(a.selectedGameProfileId) {
|
||||
if (host.open == "fex") host.open = null
|
||||
}
|
||||
@@ -506,17 +528,22 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
}
|
||||
androidx.compose.foundation.layout.BoxWithConstraints(modifier = Modifier.fillMaxSize().exposeTestTags(), contentAlignment = Alignment.CenterEnd) {
|
||||
val short = maxHeight < 440.dp
|
||||
val sheetWidth = if (docked) maxWidth else minOf(420.dp, maxWidth * 0.92f)
|
||||
// The handle keeps a strip on the left free, so a sheet dragged wide can always be dragged back.
|
||||
val maxSheet = (maxWidth - DRAWER_EDGE_GAP).coerceAtLeast(0.dp)
|
||||
val minSheet = minOf(DRAWER_MIN_WIDTH, maxSheet)
|
||||
val defaultSheet = minOf(420.dp, maxWidth * 0.92f)
|
||||
val sheetWidth = if (docked) maxWidth else (savedWidth?.dp ?: defaultSheet).coerceIn(minSheet, maxSheet)
|
||||
val narrow = sheetWidth < 320.dp
|
||||
AnimatedVisibility(
|
||||
open,
|
||||
enter = if (docked) fadeIn(Motion.tw(160)) else slideInHorizontally(Motion.sp(0.8f, Spring.StiffnessLow)) { it } + fadeIn(Motion.tw(220)),
|
||||
exit = if (docked) fadeOut(Motion.tw(140)) else slideOutHorizontally(Motion.tw(240)) { it } + fadeOut(Motion.tw(200)),
|
||||
) {
|
||||
FocusGlideHost(Modifier.fillMaxHeight().width(sheetWidth)) { Box(Modifier.fillMaxSize().onGloballyPositioned { sheetCoords = it }) {
|
||||
FocusGlideHost(Modifier.fillMaxHeight().width(if (docked) sheetWidth else sheetWidth + DRAWER_HANDLE_STRIP)) { Box(Modifier.fillMaxSize().onGloballyPositioned { sheetCoords = it }) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(start = if (docked) 0.dp else DRAWER_HANDLE_STRIP)
|
||||
.background(if (docked) pal.background else pal.background.copy(alpha = 0.97f))
|
||||
.blockTouches()
|
||||
.focusGroup()
|
||||
@@ -527,6 +554,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
DrawerPages.rearrange(drawerContext, held)
|
||||
releaseSignal++
|
||||
} ?: run { managing = false }
|
||||
insideMore -> onPageChange(SessionDrawerPage.MORE)
|
||||
else -> a.onClose()
|
||||
}
|
||||
}
|
||||
@@ -604,16 +632,14 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 6.dp),
|
||||
) {
|
||||
DrawerBumper("LB", stringResource(R.string.drawer_prev_page), modifier = focus.track(page, "prev")) {
|
||||
host.open = null; onPageChange(pages.step(page, -1))
|
||||
host.open = null; onPageChange(pages.strip().step(pages.tabFor(page), -1))
|
||||
}
|
||||
DrawerPageTabs(page = page, pages = pages, compact = true, modifier = Modifier.weight(1f)) { index -> host.open = null; onPageChange(index) }
|
||||
DrawerPageTabs(page = pages.tabFor(page), pages = pages.strip(), compact = true, modifier = Modifier.weight(1f)) { index -> host.open = null; onPageChange(index) }
|
||||
DrawerBumper("RB", stringResource(R.string.drawer_next_page), modifier = focus.track(page, "next")) {
|
||||
host.open = null; onPageChange(pages.step(page, 1))
|
||||
host.open = null; onPageChange(pages.strip().step(pages.tabFor(page), 1))
|
||||
}
|
||||
SmallIconButton(
|
||||
Icons.Outlined.Tune, stringResource(R.string.drawer_manage_pages), colors.onSurfaceVariant,
|
||||
) { host.open = null; managing = !managing }
|
||||
}
|
||||
if (insideMore && !managing) DrawerMoreBack(stringResource(page.title), focus.track(page, "more-back")) { host.open = null; onPageChange(SessionDrawerPage.MORE) }
|
||||
if (managing) ManageDrawerPages(
|
||||
offeredDrawerPages(a.glassesPresent),
|
||||
Modifier.weight(1f).fillMaxWidth().padding(top = 8.dp, start = 14.dp, end = 14.dp),
|
||||
@@ -888,6 +914,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
)
|
||||
}
|
||||
SessionDrawerPage.AGENT -> Unit
|
||||
SessionDrawerPage.MORE -> DrawerMorePage(host, pages.inMore(), { host.open = null; onPageChange(it) }, { host.open = null; managing = true }) { key -> focus.track(page, key) }
|
||||
SessionDrawerPage.SESSION -> {
|
||||
SettingsGroup(stringResource(R.string.drawer_support)) {
|
||||
SettingsRow(stringResource(R.string.report_problem), stringResource(R.string.report_problem_hint)) {
|
||||
@@ -965,6 +992,12 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
} }
|
||||
}
|
||||
}
|
||||
if (!docked) DrawerResizeHandle(
|
||||
width = sheetWidth, min = minSheet, max = maxSheet,
|
||||
onWidth = { savedWidth = it.value.roundToInt() },
|
||||
onCommit = { savedWidth?.let { SessionPrefs.setDrawerWidthDp(widthContext, it) } },
|
||||
modifier = Modifier.align(Alignment.CenterStart).then(focus.track(page, "resize")),
|
||||
)
|
||||
StopConfirm(
|
||||
open = confirmStop,
|
||||
pill = sheetCoords?.let { sc -> stopCoords?.takeIf { it.isAttached && sc.isAttached }?.let { sc.localBoundingBoxOf(it, clipBounds = false) } },
|
||||
@@ -1152,6 +1185,70 @@ private fun DrawerPageTabs(page: SessionDrawerPage, pages: List<SessionDrawerPag
|
||||
|
||||
private const val LOOK_CUSTOM = "custom"
|
||||
|
||||
/** The row above a page kept inside More that goes back to the More list. */
|
||||
@Composable
|
||||
private fun DrawerMoreBack(title: String, modifier: Modifier, onBack: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val source = remember { MutableInteractionSource() }
|
||||
val hot = source.collectIsFocusedAsState().value || source.collectIsHoveredAsState().value
|
||||
val shape = RoundedCornerShape(12.dp)
|
||||
val label = stringResource(R.string.drawer_more_back, stringResource(R.string.drawer_page_more))
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
modifier = modifier.padding(top = 8.dp, start = 14.dp, end = 14.dp).fillMaxWidth().heightIn(min = 44.dp).clip(shape)
|
||||
.background(if (hot) pal.signal.copy(alpha = 0.12f) else Color.Transparent)
|
||||
.glideBorder(hot, shape, pal.signal)
|
||||
.testTag("drawer-more-back")
|
||||
.hoverable(source)
|
||||
.clickable(interactionSource = source, indication = null, role = androidx.compose.ui.semantics.Role.Button, onClick = onBack)
|
||||
.controllerConfirm(onClick = onBack)
|
||||
.semantics { contentDescription = label }
|
||||
.padding(horizontal = 8.dp),
|
||||
) {
|
||||
Icon(Icons.AutoMirrored.Outlined.ArrowBack, null, tint = colors.onSurfaceVariant, modifier = Modifier.size(22.dp))
|
||||
Text(stringResource(R.string.drawer_page_more), fontSize = 13.sp, color = colors.onSurfaceVariant)
|
||||
Text("·", fontSize = 13.sp, color = colors.onSurfaceVariant)
|
||||
Text(title, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1)
|
||||
}
|
||||
}
|
||||
|
||||
/** The pages kept inside More, and the way into arranging which pages sit on the strip and which here. */
|
||||
@Composable
|
||||
private fun DrawerMorePage(host: MenuHost, pages: List<SessionDrawerPage>, onOpen: (SessionDrawerPage) -> Unit, onEdit: () -> Unit, track: (String) -> Modifier) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
SettingsGroup(stringResource(R.string.drawer_page_more)) {
|
||||
if (pages.isEmpty()) Text(
|
||||
stringResource(R.string.drawer_more_empty), fontSize = 13.sp, color = colors.onSurfaceVariant,
|
||||
modifier = Modifier.padding(horizontal = 14.dp, vertical = 12.dp),
|
||||
)
|
||||
for (item in pages) {
|
||||
val source = remember { MutableInteractionSource() }
|
||||
val hot = source.collectIsFocusedAsState().value || source.collectIsHoveredAsState().value
|
||||
val shape = RoundedCornerShape(12.dp)
|
||||
val open = { onOpen(item) }
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp).clip(shape)
|
||||
.background(if (hot) pal.signal.copy(alpha = 0.12f) else Color.Transparent)
|
||||
.glideBorder(hot, shape, pal.signal)
|
||||
.then(track("more-${item.name.lowercase()}"))
|
||||
.testTag("drawer-more-${item.name.lowercase()}")
|
||||
.hoverable(source)
|
||||
.clickable(interactionSource = source, indication = null, role = androidx.compose.ui.semantics.Role.Button, onClick = open)
|
||||
.controllerConfirm(onClick = open)
|
||||
.padding(horizontal = 14.dp),
|
||||
) {
|
||||
Icon(item.icon, null, tint = colors.onSurfaceVariant, modifier = Modifier.size(22.dp))
|
||||
Text(stringResource(item.title), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, modifier = Modifier.weight(1f))
|
||||
}
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(10.dp))
|
||||
DrawerOutlineButton(stringResource(R.string.drawer_manage_pages), modifier = track("more-edit").testTag("drawer-more-edit"), onClick = onEdit)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ScreenEffectsGroup(
|
||||
host: MenuHost, a: DrawerActions, advancedExpanded: Boolean, onAdvancedToggle: () -> Unit,
|
||||
@@ -1338,12 +1435,92 @@ internal fun secondScreenModes(none: Boolean, deckPad: Boolean, dashboard: Boole
|
||||
(if (dashboard) listOf(SecondScreenMode.DASHBOARD) else emptyList()) +
|
||||
(if (desktop) listOf(SecondScreenMode.DESKTOP) else emptyList())
|
||||
|
||||
private val DRAWER_MIN_WIDTH = 300.dp
|
||||
private val DRAWER_HANDLE_STRIP = 24.dp
|
||||
private val DRAWER_EDGE_GAP = 80.dp
|
||||
|
||||
/** A grip on the sheet's left edge: dragging it, or pressing left and right on a controller, resizes the sheet. */
|
||||
@Composable
|
||||
private fun DrawerResizeHandle(width: Dp, min: Dp, max: Dp, onWidth: (Dp) -> Unit, onCommit: () -> Unit, modifier: Modifier) {
|
||||
val pal = LocalPalette.current
|
||||
val density = LocalDensity.current
|
||||
val source = remember { MutableInteractionSource() }
|
||||
val focused by source.collectIsFocusedAsState()
|
||||
var dragging by remember { mutableStateOf(false) }
|
||||
var coords by remember { mutableStateOf<LayoutCoordinates?>(null) }
|
||||
val current by rememberUpdatedState(width)
|
||||
val lower by rememberUpdatedState(min)
|
||||
val upper by rememberUpdatedState(max)
|
||||
val change by rememberUpdatedState(onWidth)
|
||||
val commit by rememberUpdatedState(onCommit)
|
||||
val hot = focused || dragging
|
||||
val label = stringResource(R.string.drawer_resize)
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = modifier.width(24.dp).height(96.dp)
|
||||
.onGloballyPositioned { coords = it }
|
||||
.focusable(true, source)
|
||||
.onPreviewKeyEvent { event ->
|
||||
val key = event.nativeKeyEvent
|
||||
val wider = key.keyCode == KeyEvent.KEYCODE_DPAD_LEFT
|
||||
if (!wider && key.keyCode != KeyEvent.KEYCODE_DPAD_RIGHT) false
|
||||
else {
|
||||
if (key.action == KeyEvent.ACTION_DOWN) {
|
||||
change((current + if (wider) 24.dp else (-24).dp).coerceIn(lower, upper))
|
||||
commit()
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
// The handle moves with the finger as the sheet resizes, so the drag is measured on the screen.
|
||||
.pointerInput(Unit) {
|
||||
awaitEachGesture {
|
||||
val down = awaitFirstDown(requireUnconsumed = false)
|
||||
var last = (coords?.positionInRoot()?.x ?: 0f) + down.position.x
|
||||
// Several moves can arrive before the sheet recomposes, so the width is accumulated here.
|
||||
var live = current
|
||||
dragging = true
|
||||
do {
|
||||
val event = awaitPointerEvent()
|
||||
val pointer = event.changes.firstOrNull() ?: break
|
||||
val x = (coords?.positionInRoot()?.x ?: 0f) + pointer.position.x
|
||||
val delta = with(density) { (x - last).toDp() }
|
||||
last = x
|
||||
if (delta != 0.dp) {
|
||||
live = (live - delta).coerceIn(lower, upper)
|
||||
change(live)
|
||||
}
|
||||
pointer.consume()
|
||||
} while (event.changes.any { it.pressed })
|
||||
dragging = false
|
||||
commit()
|
||||
}
|
||||
}
|
||||
.semantics {
|
||||
contentDescription = label
|
||||
stateDescription = "${width.value.roundToInt()} dp"
|
||||
},
|
||||
) {
|
||||
Box(
|
||||
Modifier.width(if (hot) 6.dp else 4.dp).height(56.dp).clip(CircleShape)
|
||||
.background(if (hot) pal.signal else pal.onSurfaceVariant.copy(alpha = 0.55f)),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SecondScreenGroup(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) {
|
||||
val choosesDisplay = a.secondScreenDisplays.size > 1
|
||||
val swapsGame = a.gameSwapAvailable || a.gameOnBottom
|
||||
if (!choosesDisplay && !swapsGame) return
|
||||
val hasSecondScreen = a.secondScreenDisplays.isNotEmpty()
|
||||
if (!hasSecondScreen && !choosesDisplay && !swapsGame) return
|
||||
SettingsGroup(stringResource(R.string.drawer_second_screen)) {
|
||||
if (hasSecondScreen) ChoiceRow(host, "dual-screen-mode", stringResource(R.string.setup_dual_screen_sessions), null,
|
||||
listOf(
|
||||
com.droiddeck.launcher.input.DualScreen.MODE_AUTO to stringResource(R.string.setup_dual_screen_auto),
|
||||
com.droiddeck.launcher.input.DualScreen.MODE_ON to stringResource(R.string.setup_dual_screen_on),
|
||||
com.droiddeck.launcher.input.DualScreen.MODE_OFF to stringResource(R.string.setup_dual_screen_off),
|
||||
), a.dualScreenMode, chipModifier = track("dual-screen-mode"), onPick = a.onDualScreenMode)
|
||||
if (swapsGame) ChoiceRow(host, "game-screen", stringResource(R.string.swap_game_screen), null,
|
||||
if (a.gameSwapBuiltIn) listOf(false to stringResource(R.string.swap_game_screen_top), true to stringResource(R.string.swap_game_screen_bottom))
|
||||
else listOf(false to stringResource(R.string.main_primary), true to stringResource(R.string.main_secondary)),
|
||||
|
||||
@@ -31,6 +31,7 @@ import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.PlayArrow
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.produceState
|
||||
@@ -154,8 +155,24 @@ internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier)
|
||||
scrim = { if (games.size >= WALL_MIN_GAMES) WallFade() },
|
||||
words = {
|
||||
val runtimeStatus: @Composable () -> Unit = {
|
||||
if (s.busy || (s.available != null && s.available != s.installed)) RuntimeChip(s)
|
||||
else if (setupNeedsAttention(s)) SecondaryButton(stringResource(R.string.play_needs_you), compact = true,
|
||||
val onboardingActive by com.droiddeck.launcher.session.Onboarding.active.collectAsState()
|
||||
val onboardingFailed by com.droiddeck.launcher.session.Onboarding.failed.collectAsState()
|
||||
val onboardingFacts by com.droiddeck.launcher.session.Onboarding.facts.collectAsState()
|
||||
val onboardingRows = com.droiddeck.launcher.session.Onboarding.rows(onboardingActive, onboardingFailed, onboardingFacts)
|
||||
val settling = onboardingActive.isNotEmpty() && com.droiddeck.launcher.session.Onboarding.pending(onboardingRows)
|
||||
if (settling || s.busy || (s.available != null && s.available != s.installed)) {
|
||||
if (settling) {
|
||||
val overall = com.droiddeck.launcher.session.Onboarding.overall(onboardingRows)
|
||||
Chip(
|
||||
stringResource(R.string.onboarding_chip, overall, onboardingRows.firstOrNull { it.state == com.droiddeck.launcher.session.Onboarding.State.ACTIVE }?.label.orEmpty()),
|
||||
ok = false, fraction = overall / 100f,
|
||||
)
|
||||
} else RuntimeChip(s)
|
||||
if (com.droiddeck.launcher.core.PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)) {
|
||||
SecondaryButton(stringResource(R.string.onboarding_limit_while_waiting), compact = true,
|
||||
modifier = Modifier.testTag("setup-while-waiting"), onClick = a.onShowPhantomGate)
|
||||
}
|
||||
} else if (setupNeedsAttention(s)) SecondaryButton(stringResource(R.string.play_needs_you), compact = true,
|
||||
modifier = Modifier.testTag("play-needs-you")) { SetupTabs.openSection = SettingsSection.OVERVIEW }
|
||||
else if (s.integration.suggested && signedIn && !com.droiddeck.launcher.core.PhantomProcessLimit.blocksSteam(s.phantomProcessStatus))
|
||||
IntegrationSuggestion(s.integration, { a.onSteamIntegration(null) }, a.onDismissIntegration)
|
||||
|
||||
@@ -23,6 +23,7 @@ import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.AutoAwesome
|
||||
import androidx.compose.material.icons.outlined.Close
|
||||
import androidx.compose.material.icons.outlined.Bluetooth
|
||||
import androidx.compose.material.icons.outlined.Home
|
||||
import androidx.compose.material.icons.outlined.KeyboardCommandKey
|
||||
import androidx.compose.material.icons.outlined.LightMode
|
||||
@@ -61,6 +62,7 @@ internal fun SteamIntegration.State.enabled(feature: Feature) = when (feature) {
|
||||
Feature.BRIGHTNESS -> brightness
|
||||
Feature.HOME -> home
|
||||
Feature.SHORTCUTS -> shortcuts
|
||||
Feature.BLUETOOTH -> bluetooth
|
||||
}
|
||||
|
||||
internal fun SteamIntegration.State.enabledCount() = Feature.entries.count { enabled(it) }
|
||||
@@ -116,6 +118,7 @@ private fun IntegrationRow(
|
||||
feature == Feature.WIFI -> if (on) R.string.integration_wifi_on else R.string.integration_wifi_hint
|
||||
feature == Feature.BRIGHTNESS -> R.string.integration_brightness_hint
|
||||
feature == Feature.HOME -> R.string.integration_home_hint
|
||||
feature == Feature.BLUETOOTH -> R.string.integration_bluetooth_hint
|
||||
else -> R.string.integration_shortcuts_hint
|
||||
})
|
||||
Row(
|
||||
@@ -164,6 +167,7 @@ private fun featureIcon(feature: Feature) = when (feature) {
|
||||
Feature.BRIGHTNESS -> Icons.Outlined.LightMode
|
||||
Feature.HOME -> Icons.Outlined.Home
|
||||
Feature.SHORTCUTS -> Icons.Outlined.KeyboardCommandKey
|
||||
Feature.BLUETOOTH -> Icons.Outlined.Bluetooth
|
||||
}
|
||||
|
||||
private fun featureTitle(feature: Feature) = when (feature) {
|
||||
@@ -171,6 +175,7 @@ private fun featureTitle(feature: Feature) = when (feature) {
|
||||
Feature.BRIGHTNESS -> R.string.integration_brightness
|
||||
Feature.HOME -> R.string.integration_home
|
||||
Feature.SHORTCUTS -> R.string.integration_shortcuts
|
||||
Feature.BLUETOOTH -> R.string.integration_bluetooth
|
||||
}
|
||||
|
||||
@Composable
|
||||
|
||||
@@ -45,6 +45,7 @@ import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusProperties
|
||||
import androidx.compose.ui.focus.onFocusChanged
|
||||
import androidx.compose.ui.geometry.Rect
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.Matrix
|
||||
@@ -174,6 +175,7 @@ internal fun StepOut(
|
||||
var grown by remember { mutableStateOf(false) }
|
||||
var measured by remember { mutableStateOf<IntSize?>(null) }
|
||||
val first = remember { FocusRequester() }
|
||||
var holdsFocus by remember { mutableStateOf(false) }
|
||||
val glide = LocalFocusGlide.current
|
||||
val opener = remember { arrayOfNulls<GlideSource>(1) }
|
||||
val openNow = androidx.compose.runtime.rememberUpdatedState(open)
|
||||
@@ -241,8 +243,12 @@ internal fun StepOut(
|
||||
LaunchedEffect(open, measured) {
|
||||
if (!open || measured == null || inputMode.inputMode != InputMode.Keyboard) return@LaunchedEffect
|
||||
delay(Motion.ms(300).toLong())
|
||||
withFrameNanos { }
|
||||
runCatching { first.requestFocus() }
|
||||
// Another focus group can hold on to focus for a few frames, so the request is repeated until it lands.
|
||||
repeat(30) {
|
||||
withFrameNanos { }
|
||||
if (holdsFocus) return@LaunchedEffect
|
||||
runCatching { first.requestFocus() }
|
||||
}
|
||||
}
|
||||
|
||||
LaunchedEffect(open, grown, inputMode.inputMode) {
|
||||
@@ -289,6 +295,7 @@ internal fun StepOut(
|
||||
.heightIn(max = availableHeight)
|
||||
.onSizeChanged { if (measured != it) measured = it }
|
||||
.controllerBack(onDismiss)
|
||||
.onFocusChanged { holdsFocus = it.hasFocus }
|
||||
.focusProperties { exit = { if (openNow.value) FocusRequester.Cancel else FocusRequester.Default } }
|
||||
.focusGroup()
|
||||
.verticalScroll(rememberScrollState())
|
||||
|
||||
@@ -213,10 +213,10 @@ internal fun SortableRows(
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun MoreLine() {
|
||||
internal fun MoreLine(height: androidx.compose.ui.unit.Dp = TAB_ROW) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
Column(Modifier.fillMaxWidth().height(TAB_ROW).testTag("tab-more-line")) {
|
||||
Column(Modifier.fillMaxWidth().height(height).testTag("tab-more-line")) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp),
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.content.Intent
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.BluetoothConnected
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.BtControllerActivity
|
||||
import com.droiddeck.launcher.R
|
||||
|
||||
@Composable
|
||||
internal fun TrinketsPage(modifier: Modifier) {
|
||||
val context = LocalContext.current
|
||||
Column(modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Text(stringResource(R.string.trinkets_intro), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
Trinket(Icons.Outlined.BluetoothConnected, stringResource(R.string.btpad_title), stringResource(R.string.btpad_summary)) {
|
||||
context.startActivity(Intent(context, BtControllerActivity::class.java))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Trinket(icon: ImageVector, title: String, summary: String, onOpen: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(14.dp),
|
||||
modifier = Modifier.fillMaxWidth().clip(Shape14).background(colors.surface).border(1.dp, pal.line2, Shape14).padding(14.dp),
|
||||
) {
|
||||
Box(Modifier.size(44.dp).clip(Shape12).background(pal.signal.copy(alpha = 0.14f)), contentAlignment = Alignment.Center) {
|
||||
Icon(icon, null, tint = pal.signal)
|
||||
}
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(title, fontSize = 16.sp, fontWeight = FontWeight.Bold, color = colors.onBackground)
|
||||
Text(summary, fontSize = 13.sp, color = colors.onSurfaceVariant)
|
||||
}
|
||||
PrimaryButton(stringResource(R.string.trinkets_open), compact = true, onClick = onOpen)
|
||||
}
|
||||
}
|
||||
@@ -36,7 +36,7 @@
|
||||
<string name="wall_settings_match" translatable="false">Match screen</string>
|
||||
<string name="wall_settings_speed" translatable="false">Scroll speed</string>
|
||||
<string-array name="loading_hints">
|
||||
<item>First run downloads Steam. This may take a few minutes.</item>
|
||||
<item>DroidDeck downloads Steam in the background while you set up, so your first launch is quicker.</item>
|
||||
<item>Your controller shows up to Steam as a Steam Deck controller. Switch it to a Steam Controller, DualShock 4, DualSense or Xbox 360 pad in the session settings; it applies next session.</item>
|
||||
<item>Hold Back on your controller to open Steam\'s Quick Access menu. Hold Back for Steam shortcuts must be on in the session settings.</item>
|
||||
<item>Background behavior decides what happens when you leave the app: Native readies Steam for sleep, Auto pauses it, Manual waits for Resume, Never keeps it running.</item>
|
||||
@@ -704,6 +704,9 @@
|
||||
<string name="drawer_prev_page">Previous page</string>
|
||||
<string name="drawer_next_page">Next page</string>
|
||||
<string name="drawer_manage_pages">Arrange pages</string>
|
||||
<string name="drawer_page_more">More</string>
|
||||
<string name="drawer_more_back">Back to %1$s</string>
|
||||
<string name="drawer_more_empty">Nothing is kept here. Arrange pages and move one below the More row.</string>
|
||||
<string name="drawer_pages_reset">Reset</string>
|
||||
<string name="drawer_pages_done">Done</string>
|
||||
<string name="drawer_hud">Performance HUD</string>
|
||||
@@ -864,6 +867,7 @@
|
||||
<string name="drawer_pc_keyboard">PC keyboard</string>
|
||||
<string name="drawer_android_keyboard">Android</string>
|
||||
<string name="drawer_second_screen">Second screen</string>
|
||||
<string name="drawer_resize">Resize the menu</string>
|
||||
<string name="drawer_second_screen_shows">Shows</string>
|
||||
<string name="drawer_android_apps">Android apps</string>
|
||||
<string name="drawer_launch_app">Launch an app</string>
|
||||
@@ -1697,6 +1701,7 @@
|
||||
<string name="rail_apps">Apps</string>
|
||||
<string name="rail_setup">Settings</string>
|
||||
<string name="rail_updates">Updates</string>
|
||||
<string name="rail_trinkets">Trinkets</string>
|
||||
<string name="rail_more">More</string>
|
||||
<string name="more_edit_tabs">Edit tabs</string>
|
||||
<string name="setup_group_tabs">Tabs</string>
|
||||
@@ -4148,6 +4153,8 @@
|
||||
<string name="integration_wifi_denied">Location denied · allow it in App info</string>
|
||||
<string name="integration_brightness_hint">Steam’s slider sets screen brightness</string>
|
||||
<string name="integration_home_hint">Home opens the Steam menu in a session</string>
|
||||
<string name="integration_bluetooth">Bluetooth controllers</string>
|
||||
<string name="integration_bluetooth_hint">Lets DroidDeck connect to Steam Controllers and other Bluetooth pads</string>
|
||||
<string name="integration_shortcuts_hint">Alt+Tab, Win key and Home button stay in the session</string>
|
||||
<string name="integration_shortcuts_maybe_restricted">Greyed out in Android? App info → ⋮ → Allow restricted settings</string>
|
||||
<string name="integration_shortcuts_install_failed">System keys didn\'t install</string>
|
||||
@@ -4201,6 +4208,32 @@
|
||||
<string name="stores_gamejolt_filter_status">Status</string>
|
||||
<string name="stores_gamejolt_filter_partners">Partners</string>
|
||||
<string name="stores_gamejolt_followed">Followed games</string>
|
||||
<string name="trinkets_intro">Odds and ends that don\'t fit anywhere else.</string>
|
||||
<string name="trinkets_open">Open</string>
|
||||
<string name="btpad_title">Bluetooth controller</string>
|
||||
<string name="btpad_summary">Use this device as a wireless gamepad for a PC, phone, or another handheld.</string>
|
||||
<string name="btpad_exit_hint">Hold Select + Start to stop</string>
|
||||
<string name="btpad_disconnect">Disconnect</string>
|
||||
<string name="btpad_pair">Pair new</string>
|
||||
<string name="btpad_permission_open">App info</string>
|
||||
<string name="btpad_location_hint">Location is off for DroidDeck, so pairing requests show up as a notification instead of a prompt here. Allow Location in App info to fix that.</string>
|
||||
<string name="btpad_status_permission">Allow Nearby devices for DroidDeck in App info to use this.</string>
|
||||
<string name="btpad_close">Stop</string>
|
||||
<string name="btpad_touch">Touch controls</string>
|
||||
<string name="btpad_physical_hint">The built-in buttons and sticks are sent to the paired device.</string>
|
||||
<string name="btpad_switch_hint">After changing the type, remove this device from the other side\'s Bluetooth list and pair again.</string>
|
||||
<string name="btpad_status_starting">Starting Bluetooth controller…</string>
|
||||
<string name="btpad_status_bt_off">Turn on Bluetooth to continue</string>
|
||||
<string name="btpad_status_unsupported">This device\'s Bluetooth can\'t act as a controller</string>
|
||||
<string name="btpad_status_ready">On the other device, add a Bluetooth device and pick %1$s. If it takes over 2 minutes, tap Pair new.</string>
|
||||
<string name="btpad_status_waiting">Waiting for a device to pair</string>
|
||||
<string name="btpad_status_connecting">Pairing with %1$s. Accept the request on this device.</string>
|
||||
<string name="btpad_status_connected">Connected to %1$s</string>
|
||||
<string name="btpad_profile_generic">Generic</string>
|
||||
<string name="btpad_profile_xbox">Xbox</string>
|
||||
<string name="btpad_profile_ds4">DualShock 4</string>
|
||||
<string name="btpad_profile_dualsense">DualSense</string>
|
||||
<string name="btpad_profile_steam">Steam Controller</string>
|
||||
<string name="wow_chat_title">Chat input</string>
|
||||
<string name="wow_chat_voice">Voice type</string>
|
||||
<string name="wow_chat_remember">Remember this selection</string>
|
||||
@@ -4395,4 +4428,19 @@
|
||||
<string name="tabs_reset_title">Reset tabs</string>
|
||||
<string name="tabs_reset_hint">Steam, Desktop, Library, Downloads, Settings and Updates on the bar, the rest under More.</string>
|
||||
<string name="tabs_reset_body">Your tab order and what sits under More or is hidden go back to the defaults.</string>
|
||||
<string name="onboarding_title">Getting DroidDeck ready</string>
|
||||
<string name="onboarding_summary">%1$d%% · you can keep using the app</string>
|
||||
<string name="onboarding_step_runtime">Linux runtime</string>
|
||||
<string name="onboarding_step_proton">DroidDeck Proton</string>
|
||||
<string name="onboarding_step_steam">Steam client</string>
|
||||
<string name="onboarding_waiting">Waiting</string>
|
||||
<string name="onboarding_done">Ready</string>
|
||||
<string name="onboarding_failed">Will retry</string>
|
||||
<string name="onboarding_steam_downloading">Downloading the Steam client</string>
|
||||
<string name="onboarding_steam_downloading_mb">Downloading the Steam client (%1$d MB)</string>
|
||||
<string name="onboarding_steam_failed">The Steam client download will retry</string>
|
||||
<string name="onboarding_limit_reason">Android can close Steam’s helper processes. Turn that off now, while the downloads run, and Play is ready the moment they finish.</string>
|
||||
<string name="onboarding_limit_action">Do it for me</string>
|
||||
<string name="onboarding_limit_while_waiting">Set up while you wait</string>
|
||||
<string name="onboarding_chip">Getting ready · %1$d%% · %2$s</string>
|
||||
</resources>
|
||||
@@ -35,6 +35,7 @@ import java.util.concurrent.atomic.AtomicInteger
|
||||
class ProtonMenuAutoTest {
|
||||
private val online = AutoComponents.online
|
||||
private val constrained = AutoComponents.unfavourable
|
||||
private val firstRunHeldBack = AutoComponents.firstRunHeldBack
|
||||
private lateinit var activity: Activity
|
||||
private lateinit var menu: ProtonMenu
|
||||
private lateinit var root: File
|
||||
@@ -49,6 +50,7 @@ class ProtonMenuAutoTest {
|
||||
}
|
||||
AutoComponents.online = { true }
|
||||
AutoComponents.unfavourable = { false }
|
||||
AutoComponents.firstRunHeldBack = { false }
|
||||
SessionState.running = false
|
||||
SessionState.phase = SessionPhase.IDLE
|
||||
SessionState.stopRequested = false
|
||||
@@ -63,6 +65,7 @@ class ProtonMenuAutoTest {
|
||||
menu.protonProblem = null
|
||||
menu.protonStage = null
|
||||
menu.protonPercent = -1
|
||||
menu.experimentalRefresh = { emptyList() }
|
||||
menu.installer = { tool, progress ->
|
||||
progress("Installing ${tool.name}", 50)
|
||||
install("${tool.prefix}-11-12")
|
||||
@@ -77,6 +80,7 @@ class ProtonMenuAutoTest {
|
||||
menu.protonPercent = -1
|
||||
AutoComponents.online = online
|
||||
AutoComponents.unfavourable = constrained
|
||||
AutoComponents.firstRunHeldBack = firstRunHeldBack
|
||||
SessionState.running = false
|
||||
SessionState.phase = SessionPhase.IDLE
|
||||
SessionState.stopRequested = false
|
||||
|
||||
@@ -11,13 +11,13 @@ class AgentStorageTest {
|
||||
@Test fun removingAFolderKeepsWhatItsLinksPointAt() {
|
||||
val base = Files.createTempDirectory("agent-storage")
|
||||
val outside = Files.createDirectories(base.resolve("sdcard"))
|
||||
Files.write(outside.resolve("save.dat"), ByteArray(100))
|
||||
Files.write(outside.resolve("save.dat"), ByteArray(1 shl 20))
|
||||
val item = Files.createDirectories(base.resolve("rootfs/android-sdk"))
|
||||
Files.write(item.resolve("a.jar"), ByteArray(10))
|
||||
val linked = runCatching { Files.createSymbolicLink(item.resolve("saves"), outside) }.isSuccess
|
||||
assumeTrue("symbolic links need privileges on this OS", linked)
|
||||
|
||||
assertTrue(AgentStorage.size(item) < 100)
|
||||
assertTrue(AgentStorage.size(item) < 1 shl 20)
|
||||
AgentStorage.delete(item)
|
||||
assertFalse(Files.exists(item))
|
||||
assertTrue(Files.exists(outside.resolve("save.dat")))
|
||||
|
||||
@@ -5,6 +5,7 @@ import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Assert.assertTrue
|
||||
@@ -158,6 +159,7 @@ class CurseForgeAppTest {
|
||||
assertTrue(text.startsWith("(() => { const w = require('electron').BrowserWindow.getAllWindows()"))
|
||||
assertTrue(text.contains("desktop.html"))
|
||||
assertTrue(text.contains("executeJavaScript("))
|
||||
assertTrue(text.contains("let m = globalThis.__droiddeckServices; if (!m || !m[\\\"ProjectAppService\\\"]) m = globalThis.__droiddeckServices = "))
|
||||
assertFalse(text.contains("show()"))
|
||||
val probe = CurseForgeApp.expression("InstalledProjectsAppService", "installAddon", null)
|
||||
assertFalse(probe.contains("await s["))
|
||||
@@ -292,6 +294,37 @@ class CurseForgeAppTest {
|
||||
assertTrue(calls.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aGameFolderCurseForgeAlreadyKnowsSkipsTheFolderDetection() {
|
||||
val flavor = "/root/Games/World of Warcraft/_retail_"
|
||||
val curse = fakeCurse(flavor = flavor)
|
||||
val context = org.robolectric.RuntimeEnvironment.getApplication()
|
||||
assertEquals("g", CurseForgeApp.instance(context, url, "/root/Games/World of Warcraft", flavor))
|
||||
assertFalse("detectGameFromPath" in curse.methods)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aGameFolderCurseForgeDoesNotKnowIsDetectedOnce() {
|
||||
val flavor = "/root/Games/World of Warcraft/_retail_"
|
||||
val curse = fakeCurse(flavor = flavor)
|
||||
curse.known = false
|
||||
val context = org.robolectric.RuntimeEnvironment.getApplication()
|
||||
assertEquals("g", CurseForgeApp.instance(context, url, "/root/Games/World of Warcraft", flavor))
|
||||
assertEquals(1, curse.methods.count { it == "detectGameFromPath" })
|
||||
assertEquals(listOf("getGameInstances", "detectGameFromPath", "getGameInstances"), curse.methods.filter { it != "connect" })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun curseForgeConnectsOncePerLaunch() {
|
||||
val curse = fakeCurse()
|
||||
val context = org.robolectric.RuntimeEnvironment.getApplication()
|
||||
val launched = "ws://127.0.0.1:43118/${java.util.UUID.randomUUID()}"
|
||||
CurseForgeApp.projects(context, launched, "g")
|
||||
CurseForgeApp.projects(context, launched, "g")
|
||||
CurseForgeApp.instance(context, launched, "/root", "")
|
||||
assertEquals(1, curse.methods.count { it == "connect" })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theInspectorUrlIsRedactedFromCommandLogs() {
|
||||
val line = CurseForgeApp.evalArgv(url, "x", 1_000).joinToString(" ")
|
||||
@@ -305,6 +338,7 @@ class CurseForgeAppTest {
|
||||
val methods = java.util.Collections.synchronizedList(mutableListOf<String>())
|
||||
@Volatile var unreachableAfterDelete = false
|
||||
@Volatile var unreachable = false
|
||||
@Volatile var known = true
|
||||
|
||||
fun add(id: String, folder: String, status: Int) = add(id, listOf(folder), status)
|
||||
|
||||
@@ -328,8 +362,11 @@ class CurseForgeAppTest {
|
||||
projects.forEach { it.put("status", 1) }
|
||||
true
|
||||
}
|
||||
"detectGameFromPath" -> JSONObject().put("gameInstanceGuid", "g")
|
||||
"getGameInstances" -> JSONArray().put(JSONObject().put("guid", "g").put("installPath", flavor))
|
||||
"detectGameFromPath" -> {
|
||||
known = true
|
||||
JSONObject().put("gameInstanceGuid", "g")
|
||||
}
|
||||
"getGameInstances" -> if (known) JSONArray().put(JSONObject().put("guid", "g").put("installPath", flavor)) else JSONArray()
|
||||
"deleteMods" -> {
|
||||
projects.removeAll { p ->
|
||||
(p.getString("installedModId") in expression).also { gone ->
|
||||
@@ -467,7 +504,7 @@ class CurseForgeAppTest {
|
||||
curse.add("18808", "TomTom", 1)
|
||||
val before = CurseForgeApp.projects(context, url, "g", rescan = true).associate { it.id to it.update }
|
||||
assertEquals(mapOf("298842" to true, "18808" to false), before)
|
||||
assertTrue(CurseForgeApp.update(context, url, "g", "298842"))
|
||||
assertNotNull(CurseForgeApp.update(context, url, "g", "298842"))
|
||||
assertTrue("updateMod" in curse.methods)
|
||||
assertTrue(CurseForgeApp.projects(context, url, "g").none { it.update })
|
||||
}
|
||||
@@ -479,7 +516,7 @@ class CurseForgeAppTest {
|
||||
curse.add("298842", "Leatrix_Maps", 1)
|
||||
curse.add("18808", "TomTom", 1)
|
||||
val project = CurseForgeApp.owner(CurseForgeApp.projects(context, url, "g"), "Leatrix_Maps")!!
|
||||
assertTrue(CurseForgeApp.uninstall(context, url, "g", project))
|
||||
assertNotNull(CurseForgeApp.uninstall(context, url, "g", project))
|
||||
assertEquals(listOf("18808"), CurseForgeApp.projects(context, url, "g").map { it.id })
|
||||
assertFalse(File(curse.addOns, "Leatrix_Maps").exists())
|
||||
assertTrue(File(curse.addOns, "TomTom").isDirectory)
|
||||
|
||||
@@ -155,4 +155,37 @@ class LinuxNetworkLinkComponentTest {
|
||||
})
|
||||
assertEquals(before, link)
|
||||
}
|
||||
|
||||
@Test fun parallelPublishersFromSeparateComponentsAllLandAndLeaveNoStagedCopy() {
|
||||
val context = ApplicationProvider.getApplicationContext<Context>()
|
||||
val link = properties("10.0.0.1/24").route("1.0.0.0", 8).route("128.0.0.0", 1)
|
||||
val failures = java.util.concurrent.atomic.AtomicInteger()
|
||||
val threads = (0 until 8).map {
|
||||
Thread {
|
||||
val component = LinuxNetworkLinkComponent(context, temporary.root)
|
||||
repeat(25) {
|
||||
runCatching {
|
||||
ReflectionHelpers.callInstanceMethod<Unit>(component, "replace",
|
||||
from(java.io.File::class.java, temporary.root.resolve("etc/droiddeck-net").apply { parentFile!!.mkdirs() }),
|
||||
from(String::class.java, "if tun0 $it\n"))
|
||||
}.onFailure { failures.incrementAndGet() }
|
||||
}
|
||||
}.apply { start() }
|
||||
}
|
||||
threads.forEach { it.join() }
|
||||
assertEquals(0, failures.get())
|
||||
assertFalse(temporary.root.resolve("etc/droiddeck-net.staged").exists())
|
||||
assertEquals("if tun0 24\n", temporary.root.resolve("etc/droiddeck-net").readText())
|
||||
}
|
||||
|
||||
@Test fun anUnchangedFileIsNotRewritten() {
|
||||
val context = ApplicationProvider.getApplicationContext<Context>()
|
||||
val component = LinuxNetworkLinkComponent(context, temporary.root)
|
||||
val file = temporary.root.resolve("etc/resolv.conf").apply { parentFile!!.mkdirs(); writeText("nameserver 1.1.1.1\n") }
|
||||
assertTrue(file.setLastModified(1_000_000L))
|
||||
ReflectionHelpers.callInstanceMethod<Unit>(component, "replace", from(java.io.File::class.java, file), from(String::class.java, "nameserver 1.1.1.1\n"))
|
||||
assertEquals(1_000_000L, file.lastModified())
|
||||
ReflectionHelpers.callInstanceMethod<Unit>(component, "replace", from(java.io.File::class.java, file), from(String::class.java, "nameserver 8.8.8.8\n"))
|
||||
assertEquals("nameserver 8.8.8.8\n", file.readText())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import com.droiddeck.launcher.session.Onboarding.Facts
|
||||
import com.droiddeck.launcher.session.Onboarding.Progress
|
||||
import com.droiddeck.launcher.session.Onboarding.State
|
||||
import com.droiddeck.launcher.session.Onboarding.Step
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class OnboardingTest {
|
||||
private val none = Facts(runtime = false, proton = false, steam = false)
|
||||
|
||||
@Test fun everythingReadyShowsNothing() {
|
||||
val rows = Onboarding.rows(emptyMap(), emptyMap(), Facts())
|
||||
assertFalse(Onboarding.pending(rows))
|
||||
assertEquals(100, Onboarding.overall(rows))
|
||||
}
|
||||
|
||||
@Test fun stepsAreActiveFailedOrWaiting() {
|
||||
val rows = Onboarding.rows(mapOf(Step.RUNTIME to Progress("x", 50)), mapOf(Step.PROTON to "no"), none)
|
||||
assertEquals(listOf(State.ACTIVE, State.FAILED, State.WAITING), rows.map { it.state })
|
||||
assertTrue(Onboarding.pending(rows))
|
||||
}
|
||||
|
||||
@Test fun anActiveStepStaysActiveWhenItsFactIsAlreadyTrue() {
|
||||
val rows = Onboarding.rows(mapOf(Step.STEAM to Progress("x", -1)), emptyMap(), Facts())
|
||||
assertEquals(State.ACTIVE, rows.first { it.step == Step.STEAM }.state)
|
||||
}
|
||||
|
||||
@Test fun overallWeighsDownloadsBySize() {
|
||||
val rows = Onboarding.rows(mapOf(Step.RUNTIME to Progress("x", 50)), emptyMap(), Facts(runtime = false))
|
||||
assertEquals(30 + 15 + 25, Onboarding.overall(rows))
|
||||
}
|
||||
|
||||
@Test fun reportingClearsAPriorFailure() {
|
||||
Onboarding.fail(Step.STEAM, "boom")
|
||||
Onboarding.report(Step.STEAM, "again", 3)
|
||||
assertTrue(Onboarding.failed.value[Step.STEAM] == null)
|
||||
Onboarding.finish(Step.STEAM)
|
||||
assertTrue(Onboarding.active.value[Step.STEAM] == null)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Test
|
||||
|
||||
class SteamClientPrefetchTest {
|
||||
@Test fun readsPercentAndTotalFromTheInstallersStepLine() {
|
||||
val line = "== STEP 14:21:07 downloading Steam: bins_linuxarm64.zip (2/5), 120 of 480 MB"
|
||||
assertEquals(25 to 480, SteamClientPrefetch.parse(line))
|
||||
}
|
||||
|
||||
@Test fun aRetryNoteDoesNotChangeTheReading() {
|
||||
val line = "== STEP 14:21:07 downloading Steam: x.zip (1/3), 10 of 40 MB - retrying in 5s"
|
||||
assertEquals(25 to 40, SteamClientPrefetch.parse(line))
|
||||
}
|
||||
|
||||
@Test fun otherLinesAreIgnored() {
|
||||
assertNull(SteamClientPrefetch.parse("== STEP 14:21:07 the Steam client now follows steamdeck_stable"))
|
||||
assertNull(SteamClientPrefetch.parse("downloading Steam: x (1/1), 5 of 0 MB"))
|
||||
}
|
||||
}
|
||||
@@ -59,6 +59,27 @@ class SteamUserDefaultsTest {
|
||||
assertFalse(File(home, "userdata/123/config/droiddeck-user-defaults-initialized").exists())
|
||||
}
|
||||
|
||||
@Test fun libraryHomeUsesBigArtUnlessChosenOtherwise() {
|
||||
val fresh = home("")
|
||||
SessionFiles.seedUserDefaults(fresh)
|
||||
assertTrue(text(fresh).contains("\"LibraryHomeBigArt\"\t\t\"1\""))
|
||||
val chosen = home("\t\"LibraryHomeBigArt\"\t\t\"0\"\n")
|
||||
SessionFiles.seedUserDefaults(chosen)
|
||||
assertTrue(text(chosen).contains("\"LibraryHomeBigArt\"\t\t\"0\""))
|
||||
assertEquals(1, Regex("LibraryHomeBigArt").findAll(text(chosen)).count())
|
||||
}
|
||||
|
||||
@Test fun bigArtLandsInTheRootWhenNestedStoresCloseOnItsLastLine() {
|
||||
val home = home("")
|
||||
File(home, "userdata/123/config/localconfig.vdf").writeText(
|
||||
"\"UserLocalConfigStore\"\n{\n\t\"WebStorage\"\n\t{\n\t\t\"Other\"\t\t\"x\"\n\t}}\n")
|
||||
SessionFiles.seedUserDefaults(home)
|
||||
val t = text(home)
|
||||
val beforeBigArt = t.substring(0, t.indexOf("\"LibraryHomeBigArt\""))
|
||||
assertEquals(beforeBigArt.count { it == '{' }, beforeBigArt.count { it == '}' } + 1)
|
||||
assertTrue(t.indexOf("\"CachedBatteryPreferences\"") < t.indexOf("\"LibraryHomeBigArt\""))
|
||||
}
|
||||
|
||||
@Test fun librarySortsByRecentlyPlayed() {
|
||||
val fresh = home("")
|
||||
SessionFiles.seedUserDefaults(fresh)
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import org.robolectric.pluginapi.TestEnvironmentLifecyclePlugin
|
||||
|
||||
/**
|
||||
* A plain JVM has no default uncaught-exception handler, so CrashHandler's fallback halts the test JVM (exit 2)
|
||||
* on any background-thread error. Each test starts from a handler that only prints, like the JVM's own.
|
||||
*/
|
||||
class TestJvmUncaughtHandler : TestEnvironmentLifecyclePlugin {
|
||||
override fun onSetupApplicationState() {
|
||||
Thread.setDefaultUncaughtExceptionHandler { thread, error ->
|
||||
System.err.print("Exception in thread \"${thread.name}\" ")
|
||||
error.printStackTrace(System.err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import com.droiddeck.launcher.App
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [34])
|
||||
class UncaughtBackgroundErrorTest {
|
||||
@Test fun anUncaughtErrorOnABackgroundThreadDoesNotEndTheTestRun() {
|
||||
assertTrue(RuntimeEnvironment.getApplication() is App)
|
||||
Thread({ throw IllegalStateException("expected by the test") }, "uncaught-background-error").apply {
|
||||
start()
|
||||
join()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -87,6 +87,34 @@ class XboxManifestTest {
|
||||
assertEquals(listOf("Retail.exe"), info.executables)
|
||||
assertEquals("Retail.exe", XboxManifest.executable(root))
|
||||
}
|
||||
@Test fun aGameCorePackageIsReadFromItsConfigBesideTheGeneratedAppxManifest() {
|
||||
val root = temporary.newFolder()
|
||||
java.io.File(root, "Game.exe").writeText("encrypted")
|
||||
java.io.File(root, "Other.exe").writeText("encrypted")
|
||||
java.io.File(root, "MicrosoftGame.config").writeText("""<Game configVersion="1"><Identity Name="Test.Game" Publisher="CN=Test" Version="1.2.3.0"/>
|
||||
<ExecutableList><Executable Name="Game.exe" TargetDeviceFamily="PC"/></ExecutableList><StoreId>9AAAAAAAAAAA</StoreId></Game>""")
|
||||
java.io.File(root, "appxmanifest.xml").writeText("""<?xml version="1.0" encoding="utf-8"?>
|
||||
<Package xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10">
|
||||
<Identity Name="Generated.Game" Publisher="CN=Generated" Version="9.9.9.0"/>
|
||||
<Applications><Application Id="Game" Executable="Other.exe" EntryPoint="Game.App"/></Applications></Package>""")
|
||||
val info = XboxManifest.read(root)
|
||||
assertEquals("Test.Game", info.name)
|
||||
assertEquals("1.2.3.0", info.version)
|
||||
assertEquals("9AAAAAAAAAAA", info.storeId)
|
||||
assertEquals("Game.exe", XboxInstaller.executable(root))
|
||||
assertFalse(XboxManifest.needsAppModel(root))
|
||||
}
|
||||
@Test fun aFolderWithoutOneManifestIsStillRefused() {
|
||||
val empty = temporary.newFolder()
|
||||
java.io.File(empty, "Game.exe").writeText("encrypted")
|
||||
assertThrows(IllegalArgumentException::class.java) { XboxManifest.read(empty) }
|
||||
val twice = temporary.newFolder()
|
||||
java.io.File(twice, "Game.exe").writeText("encrypted")
|
||||
java.io.File(twice, "MicrosoftGame.config").writeText("<Game><Executable Name=\"Game.exe\"/></Game>")
|
||||
java.io.File(twice, "microsoftgame.CONFIG").writeText("<Game><Executable Name=\"Game.exe\"/></Game>")
|
||||
org.junit.Assume.assumeTrue(twice.list().orEmpty().size == 3)
|
||||
assertThrows(IllegalArgumentException::class.java) { XboxManifest.read(twice) }
|
||||
}
|
||||
@Test fun legacyPackageManifestNamesItsExecutableTheSameWay() {
|
||||
// A legacy EAppx package carries AppxManifest.xml and has no config; the
|
||||
// launcher must still find the identity and the launch path, or an install
|
||||
|
||||
@@ -133,6 +133,88 @@ class CurseLinkTabTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anInstallHandsCurseForgesSettledListToTheNextReadWithoutARescan() {
|
||||
val target = wow()
|
||||
val link = CurseLink(app)
|
||||
try {
|
||||
link.installed(context, target, 0)
|
||||
assertTrue(link.change(context, target) { CurseForgeApp.install(context, it.inspector, it.guid, "298842") })
|
||||
assertEquals(listOf("298842"), link.installed(context, target, 1).map { it.id })
|
||||
assertEquals(1, methods.count { it == "scanGameInstance" })
|
||||
link.installed(context, target, 2)
|
||||
assertEquals(2, methods.count { it == "scanGameInstance" })
|
||||
} finally {
|
||||
runBlocking { link.close(context).join() }
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aFailedInstallLeavesTheNextReadToRescan() {
|
||||
val target = wow()
|
||||
val link = CurseLink(app)
|
||||
try {
|
||||
link.installed(context, target, 0)
|
||||
assertFalse(link.change(context, target) { null })
|
||||
link.installed(context, target, 1)
|
||||
assertEquals(2, methods.count { it == "scanGameInstance" })
|
||||
} finally {
|
||||
runBlocking { link.close(context).join() }
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aRefreshAfterAnInstallStillRescans() {
|
||||
val target = wow()
|
||||
val link = CurseLink(app)
|
||||
try {
|
||||
link.installed(context, target, 0)
|
||||
assertTrue(link.change(context, target) { CurseForgeApp.install(context, it.inspector, it.guid, "298842") })
|
||||
link.refresh()
|
||||
link.installed(context, target, 1)
|
||||
assertEquals(2, methods.count { it == "scanGameInstance" })
|
||||
} finally {
|
||||
runBlocking { link.close(context).join() }
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aFailedChangeDropsAnEarlierSettledList() {
|
||||
val target = wow()
|
||||
val link = CurseLink(app)
|
||||
try {
|
||||
link.installed(context, target, 0)
|
||||
assertTrue(link.change(context, target) { CurseForgeApp.install(context, it.inspector, it.guid, "298842") })
|
||||
assertFalse(link.change(context, target) { null })
|
||||
link.installed(context, target, 1)
|
||||
assertEquals(2, methods.count { it == "scanGameInstance" })
|
||||
} finally {
|
||||
runBlocking { link.close(context).join() }
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anOlderChangeFinishingLastDoesNotReplaceTheNewerList() {
|
||||
val target = wow()
|
||||
tocFolder(target.addOns, "Older", "1")
|
||||
tocFolder(target.addOns, "Newer", "2")
|
||||
val older = CurseForgeApp.Project("1", "11", listOf("Older"), false)
|
||||
val newer = CurseForgeApp.Project("2", "22", listOf("Newer"), false)
|
||||
val link = CurseLink(app)
|
||||
try {
|
||||
link.installed(context, target, 0)
|
||||
assertTrue(link.change(context, target) {
|
||||
assertTrue(link.change(context, target) { listOf(older, newer) })
|
||||
listOf(older)
|
||||
})
|
||||
assertEquals(setOf("1", "2"), CurseLink.lastReported(target).keys)
|
||||
assertEquals(listOf("1", "2"), link.installed(context, target, 1).map { it.id })
|
||||
assertEquals(1, methods.count { it == "scanGameInstance" })
|
||||
} finally {
|
||||
runBlocking { link.close(context).join() }
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aFailedScanKeepsTheLastReportInsteadOfClearingIt() {
|
||||
val target = wow()
|
||||
|
||||
@@ -40,8 +40,8 @@ class NavTabsTest {
|
||||
}
|
||||
|
||||
@Test fun aFreshInstallShowsTheDefaultBarMoreAndHiddenTabs() {
|
||||
assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", NavTabs.MORE), navigationKeys(state()))
|
||||
assertEquals(listOf("stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies"), NavTabs.more(state()))
|
||||
assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", "trinkets", "stores", NavTabs.MORE), navigationKeys(state()))
|
||||
assertEquals(listOf("soundtracks", "components", "storage", "sync", "decky", "boot-movies"), NavTabs.more(state()))
|
||||
assertEquals(TabPlace.HIDDEN, NavTabs.place(state(), "android-apps"))
|
||||
assertEquals(TabPlace.HIDDEN, NavTabs.place(state(), "agent"))
|
||||
assertFalse(com.droiddeck.launcher.agent.AgentTab.shown)
|
||||
@@ -51,13 +51,13 @@ class NavTabsTest {
|
||||
@Test fun showingMusicOnceKeepsItShownAfterReload() {
|
||||
place("soundtracks", TabPlace.BAR)
|
||||
NavTabs.load(ctx)
|
||||
assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", "soundtracks", NavTabs.MORE), navigationKeys(state()))
|
||||
assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", "trinkets", "stores", "soundtracks", NavTabs.MORE), navigationKeys(state()))
|
||||
}
|
||||
|
||||
@Test fun shelvedTabsLeaveTheBarAndAddMoreAtTheEnd() {
|
||||
place("desktop", TabPlace.MORE)
|
||||
val s = state()
|
||||
assertEquals(listOf("desktop", "stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies"), NavTabs.more(s))
|
||||
assertEquals(listOf("desktop", "soundtracks", "components", "storage", "sync", "decky", "boot-movies"), NavTabs.more(s))
|
||||
assertEquals(NavTabs.MORE, navigationKeys(s).last())
|
||||
assertFalse("desktop" in navigationKeys(s))
|
||||
}
|
||||
@@ -70,14 +70,14 @@ class NavTabsTest {
|
||||
}
|
||||
|
||||
@Test fun resettingPutsBackTheDefaultLayout() {
|
||||
place("stores", TabPlace.BAR)
|
||||
place("stores", TabPlace.MORE)
|
||||
place("updates", TabPlace.HIDDEN)
|
||||
moveTab("downloads", -1)
|
||||
assertFalse(NavTabs.isDefault())
|
||||
NavTabs.reset(ctx)
|
||||
NavTabs.load(ctx)
|
||||
assertTrue(NavTabs.isDefault())
|
||||
assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", NavTabs.MORE), navigationKeys(state()))
|
||||
assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", "trinkets", "stores", NavTabs.MORE), navigationKeys(state()))
|
||||
}
|
||||
|
||||
@Test fun anOldLayoutKeepsWhatItsSwitchesShowed() {
|
||||
@@ -85,7 +85,7 @@ class NavTabsTest {
|
||||
.putBoolean("gameStoresEnabled", false).putBoolean("soundtracksEnabled", false).commit()
|
||||
NavTabs.load(ctx)
|
||||
val s = state()
|
||||
assertEquals(listOf("steam", "games", "desktop", "components", "setup", "updates", NavTabs.MORE), navigationKeys(s))
|
||||
assertEquals(listOf("steam", "games", "desktop", "components", "setup", "updates", "trinkets", NavTabs.MORE), navigationKeys(s))
|
||||
assertEquals(listOf("storage", "sync", "decky", "boot-movies"), NavTabs.more(s))
|
||||
listOf("stores", "downloads", "soundtracks", "android-apps", "agent").forEach { assertEquals(it, TabPlace.HIDDEN, NavTabs.place(s, it)) }
|
||||
val prefs = ctx.getSharedPreferences("session", Context.MODE_PRIVATE)
|
||||
@@ -119,9 +119,9 @@ class NavTabsTest {
|
||||
}
|
||||
|
||||
@Test fun tabsMissingFromASavedOrderSlotInAfterTheirDefaultNeighbour() {
|
||||
assertEquals(listOf("updates", "stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent", "steam", "desktop", "games", "downloads", "setup"),
|
||||
assertEquals(listOf("updates", "trinkets", "stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent", "steam", "desktop", "games", "downloads", "setup"),
|
||||
NavTabs.arrange(listOf("updates", "steam")))
|
||||
assertEquals(listOf("games", "downloads", "steam", "setup", "stores", "soundtracks", "desktop", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent", "updates"),
|
||||
assertEquals(listOf("games", "downloads", "steam", "setup", "stores", "soundtracks", "desktop", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent", "updates", "trinkets"),
|
||||
NavTabs.arrange(listOf("games", "steam", "setup", "stores", "desktop", "components", "android-apps", "updates", "bogus")))
|
||||
}
|
||||
|
||||
|
||||
@@ -8,15 +8,45 @@ class SessionDrawerPageTest {
|
||||
val pages = sessionDrawerPages(hasAgent = false)
|
||||
assertEquals(SessionDrawerPage.CONTROLLER, pages.first())
|
||||
assertEquals(SessionDrawerPage.DISPLAY, pages.step(SessionDrawerPage.CONTROLLER, 1))
|
||||
assertEquals(SessionDrawerPage.SESSION, pages.step(SessionDrawerPage.CONTROLLER, -1))
|
||||
assertEquals(SessionDrawerPage.CONTROLLER, pages.step(SessionDrawerPage.SESSION, 1))
|
||||
assertEquals(SessionDrawerPage.VR, pages.step(SessionDrawerPage.CONTROLLER, -1))
|
||||
assertEquals(SessionDrawerPage.HUD, pages.step(SessionDrawerPage.DISPLAY, 1))
|
||||
assertEquals(SessionDrawerPage.EFFECTS, pages.step(SessionDrawerPage.HUD, 1))
|
||||
assertEquals(SessionDrawerPage.VR, pages.step(SessionDrawerPage.EFFECTS, 1))
|
||||
assertEquals(SessionDrawerPage.GAMES, pages.step(SessionDrawerPage.VR, 1))
|
||||
assertEquals(SessionDrawerPage.GAMES, pages.step(SessionDrawerPage.EFFECTS, 1))
|
||||
assertEquals(SessionDrawerPage.SESSION, pages.step(SessionDrawerPage.GAMES, 1))
|
||||
}
|
||||
|
||||
@Test fun moreKeepsSteamVrByDefaultAndStandsInForThePagesInsideIt() {
|
||||
val pages = sessionDrawerPages(hasAgent = false)
|
||||
assertEquals(listOf(SessionDrawerPage.VR), pages.inMore())
|
||||
assertEquals(SessionDrawerPage.MORE, pages.strip().last())
|
||||
assertFalse(SessionDrawerPage.VR in pages.strip())
|
||||
assertEquals(SessionDrawerPage.MORE, pages.tabFor(SessionDrawerPage.VR))
|
||||
assertEquals(SessionDrawerPage.GAMES, pages.tabFor(SessionDrawerPage.GAMES))
|
||||
val strip = pages.strip()
|
||||
assertEquals(SessionDrawerPage.MORE, strip.step(SessionDrawerPage.SESSION, 1))
|
||||
assertEquals(SessionDrawerPage.CONTROLLER, strip.step(SessionDrawerPage.MORE, 1))
|
||||
assertEquals(SessionDrawerPage.SESSION, strip.step(pages.tabFor(SessionDrawerPage.VR), -1))
|
||||
}
|
||||
|
||||
@Test fun anOlderSavedOrderKeepsItsPagesAndGetsAMoreTabAfterSession() {
|
||||
val saved = listOf("CONTROLLER", "DISPLAY", "HUD", "EFFECTS", "VR", "GAMES", "AGENT", "SESSION")
|
||||
val out = DrawerPages.arrange(saved)
|
||||
assertEquals(SessionDrawerPage.MORE, out[out.indexOf(SessionDrawerPage.SESSION) + 1])
|
||||
assertTrue(out.indexOf(SessionDrawerPage.VR) < out.indexOf(SessionDrawerPage.EFFECTS) + 2)
|
||||
assertTrue(out.inMore().isEmpty())
|
||||
}
|
||||
|
||||
@Test fun sessionCanBeKeptInsideMore() {
|
||||
val saved = listOf("CONTROLLER", "DISPLAY", "HUD", "EFFECTS", "GAMES", "AGENT", "MORE", "SESSION", "VR")
|
||||
val out = DrawerPages.arrange(saved)
|
||||
assertEquals(listOf(SessionDrawerPage.SESSION, SessionDrawerPage.VR), out.inMore())
|
||||
assertFalse(SessionDrawerPage.SESSION in out.strip())
|
||||
}
|
||||
|
||||
@Test fun moreAndSessionCannotBeHidden() {
|
||||
assertFalse(DrawerPages.hideable(SessionDrawerPage.MORE))
|
||||
}
|
||||
|
||||
@Test fun glassesAddTheirPageAfterController() {
|
||||
val pages = sessionDrawerPages(hasGlasses = true, hasAgent = false)
|
||||
assertEquals(SessionDrawerPage.GLASSES, pages.step(SessionDrawerPage.CONTROLLER, 1))
|
||||
|
||||
@@ -41,7 +41,8 @@ class SteamIntegrationGroupTest {
|
||||
compose.onNodeWithTag("integration-action-brightness").performClick()
|
||||
compose.onNodeWithTag("integration-action-home").performClick()
|
||||
compose.onNodeWithTag("integration-action-shortcuts").performClick()
|
||||
assertEquals(listOf(Feature.BRIGHTNESS, Feature.HOME, Feature.SHORTCUTS), requests)
|
||||
compose.onNodeWithTag("integration-action-bluetooth").performClick()
|
||||
assertEquals(listOf(Feature.BRIGHTNESS, Feature.HOME, Feature.SHORTCUTS, Feature.BLUETOOTH), requests)
|
||||
}
|
||||
|
||||
@Test fun switchesReflectAndroidGrants() {
|
||||
@@ -50,7 +51,8 @@ class SteamIntegrationGroupTest {
|
||||
compose.onNodeWithTag("integration-action-brightness").assert(stateIs("On"))
|
||||
compose.onNodeWithTag("integration-action-shortcuts").assert(stateIs("On"))
|
||||
compose.onNodeWithTag("integration-action-wifi").assert(stateIs("Off"))
|
||||
compose.onNodeWithText("3 of 4 on").assertExists()
|
||||
compose.onNodeWithTag("integration-action-bluetooth").assert(stateIs("Off"))
|
||||
compose.onNodeWithText("3 of 5 on").assertExists()
|
||||
}
|
||||
|
||||
@Test fun shortcutsDoNotNeedHome() {
|
||||
|
||||
+1
@@ -0,0 +1 @@
|
||||
com.droiddeck.launcher.session.TestJvmUncaughtHandler
|
||||
@@ -4,6 +4,5 @@ org.gradle.configuration-cache=true
|
||||
org.gradle.parallel=true
|
||||
android.useAndroidX=true
|
||||
android.nonTransitiveRClass=true
|
||||
ndkVersion=27.3.13750724
|
||||
|
||||
org.gradle.tooling.parallel=true
|
||||
+308
-236
@@ -24,6 +24,7 @@ java_dir="${JAVA_HOME:-/opt/homebrew/opt/openjdk@17/libexec/openjdk.jdk/Contents
|
||||
[[ -x "$java_dir/bin/java" ]] || java_dir="${HOME}/.local/share/mise/installs/java/temurin-17"
|
||||
[[ "$java_dir" == */homebrew/* ]] && echo "using homebrew java path: $java_dir"
|
||||
[[ "$java_dir" == */mise/* ]] && echo "using mise java path: $java_dir"
|
||||
requested_image=${DROIDDECK_BUILD_IMAGE:-}
|
||||
. "${repo_root}/tools/docker_platform.sh"
|
||||
image_name=${DROIDDECK_BUILD_IMAGE}
|
||||
build_variant=${DROIDDECK_BUILD_VARIANT:-release}
|
||||
@@ -63,6 +64,11 @@ fi
|
||||
|
||||
ndk_version=${DROIDDECK_NDK_VERSION:-}
|
||||
if [[ -z "${ndk_version}" ]]; then
|
||||
. "${repo_root}/tools/ci/toolchains.env"
|
||||
[[ -d "${sdk_dir}/ndk/${CI_ANDROID_NDK_VERSION}" ]] && ndk_version=${CI_ANDROID_NDK_VERSION}
|
||||
fi
|
||||
if [[ -z "${ndk_version}" ]]; then
|
||||
echo "NDK ${CI_ANDROID_NDK_VERSION} (tools/ci/toolchains.env) is not installed; using the newest NDK instead, so native caches will not match CI." >&2
|
||||
ndk_path=$(find "${sdk_dir}/ndk" -mindepth 2 -maxdepth 2 -name source.properties -print | xargs -n1 dirname | sort -V | tail -1)
|
||||
ndk_version=${ndk_path##*/}
|
||||
fi
|
||||
@@ -112,101 +118,6 @@ save_step() {
|
||||
|
||||
python3 "${repo_root}/tools/docker_preflight.py" "${image_name}"
|
||||
image_id=$(docker image inspect --format '{{.Id}}' "${image_name}")
|
||||
rm -rf -- "${linuxfs_dir}"
|
||||
mkdir -p "${linuxfs_dir}"
|
||||
|
||||
git_common=$(git -C "${repo_root}" rev-parse --path-format=absolute --git-common-dir)
|
||||
docker run --rm --platform "${docker_platform}" \
|
||||
--user "$(id -u):$(id -g)" \
|
||||
-v "${repo_root}:/src" -v "${git_common}:${git_common}" -w /src "${image_name}" bash -lc '
|
||||
set -euo pipefail
|
||||
d=app/src/main/assets/linuxfs
|
||||
mkdir -p "$d"
|
||||
put() { mkdir -p "$(dirname "$2")" && cat "$1" > "$2"; }
|
||||
aarch64-linux-gnu-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.so" app/src/main/cpp/fakeinput_steam.cpp -ldl
|
||||
aarch64-linux-gnu-strip --strip-unneeded "$d/libfakeinput.so"
|
||||
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
|
||||
-o "$d/libddsession.so" tools/linuxfs/preload/*.c -ldl
|
||||
aarch64-linux-gnu-strip --strip-unneeded "$d/libddsession.so"
|
||||
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
|
||||
-o "$d/libddfastpath.so" tools/proot/fastpath/fastpath.c -ldl
|
||||
aarch64-linux-gnu-strip --strip-unneeded "$d/libddfastpath.so"
|
||||
bash tools/nativeguest/build.sh "$d/libddnatv-hook.so"
|
||||
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -nostdlib -ffreestanding -fno-stack-protector \
|
||||
-fno-tree-loop-distribute-patterns -Wl,-z,defs -o "$d/libddaudit.so" tools/proot/fastpath/audit.c
|
||||
aarch64-linux-gnu-strip --strip-unneeded "$d/libddaudit.so"
|
||||
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
|
||||
-o "$d/libssbs.so" tools/linuxfs/ssbs/ssbs_adapter.c -ldl
|
||||
aarch64-linux-gnu-strip --strip-unneeded "$d/libssbs.so"
|
||||
mkdir -p "$d/usr/local/lib/droiddeck-xclipse"
|
||||
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -Wextra -Wno-unused-parameter -fvisibility=hidden -pthread \
|
||||
-o "$d/usr/local/lib/droiddeck-xclipse/libVkLayer_droiddeck_xclipse.so" tools/linuxfs/xclipse-layer/xclipse_layer.c -ldl
|
||||
aarch64-linux-gnu-strip --strip-unneeded "$d/usr/local/lib/droiddeck-xclipse/libVkLayer_droiddeck_xclipse.so"
|
||||
install -m644 tools/linuxfs/xclipse-layer/VkLayer_droiddeck_xclipse.json "$d/usr/local/lib/droiddeck-xclipse/"
|
||||
mkdir -p "$d/usr/local/bin"
|
||||
external/MaliBridge/scripts/build-client-linux.sh "$d" aarch64-linux-gnu-gcc
|
||||
aarch64-linux-gnu-gcc -O2 -Wall -o "$d/usr/local/bin/droiddeck-glprobe" tools/venus/glprobe.c -ldl
|
||||
aarch64-linux-gnu-strip --strip-unneeded "$d/usr/local/bin/droiddeck-glprobe"
|
||||
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/droiddeck-* tools/linuxfs/overlay/usr/local/bin/steam-compatibility; do
|
||||
put "$script" "$d/usr/local/bin/$(basename "$script")"
|
||||
done
|
||||
for f in tools/linuxfs/overlay/usr/bin/* tools/linuxfs/overlay/usr/bin/steamos-polkit-helpers/*; do
|
||||
[ -f "$f" ] && put "$f" "$d/${f#tools/linuxfs/overlay/}"
|
||||
done
|
||||
put tools/linuxfs/desktop/droiddeck-desktop "$d/usr/local/bin/droiddeck-desktop"
|
||||
put tools/linuxfs/desktop/droiddeck-gpu "$d/usr/local/bin/droiddeck-gpu"
|
||||
put tools/linuxfs/desktop/droiddeck-desktop-gpu "$d/usr/local/bin/droiddeck-desktop-gpu"
|
||||
put tools/linuxfs/desktop/kwin_wayland_wrapper "$d/usr/local/bin/kwin_wayland_wrapper"
|
||||
put tools/linuxfs/desktop/firefox-droiddeck.js \
|
||||
"$d/usr/lib/firefox/defaults/pref/droiddeck.js"
|
||||
|
||||
READELF=aarch64-linux-gnu-readelf bash tools/linuxfs/check-preloads.sh "$d"
|
||||
'
|
||||
|
||||
x86_key=$(inputs_hash bullseye tools/linuxfs/build-x86-preloads.sh tools/linuxfs/preload tools/linuxfs/fex \
|
||||
app/src/main/cpp/fakeinput_steam.cpp)
|
||||
x86_stage="${staging_dir}/x86-preloads"
|
||||
if restore_step x86-preloads "${x86_key}" "${linuxfs_dir}"; then :; else
|
||||
x86_platform=linux/amd64
|
||||
x86_packages="gcc g++ gcc-multilib g++-multilib binutils"
|
||||
x86_cross=0
|
||||
if [[ "${docker_platform}" == linux/arm64 ]]; then
|
||||
x86_platform=linux/arm64
|
||||
x86_packages="gcc-x86-64-linux-gnu g++-x86-64-linux-gnu gcc-i686-linux-gnu g++-i686-linux-gnu libc6-dev-amd64-cross libc6-dev-i386-cross binutils-x86-64-linux-gnu binutils-i686-linux-gnu"
|
||||
x86_cross=1
|
||||
fi
|
||||
docker run --rm --platform "${x86_platform}" -e X86_CROSS="${x86_cross}" -e X86_PACKAGES="${x86_packages}" \
|
||||
-v "${repo_root}:/src" -v "${git_common}:${git_common}" -w /src public.ecr.aws/docker/library/debian:bullseye bash -c '
|
||||
set -euo pipefail
|
||||
printf "deb http://archive.debian.org/debian bullseye main\ndeb http://archive.debian.org/debian-security bullseye-security main\n" > /etc/apt/sources.list
|
||||
apt-get -o Acquire::Check-Valid-Until=false update -qq
|
||||
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends $X86_PACKAGES >/dev/null
|
||||
tools/linuxfs/build-x86-preloads.sh app/src/main/assets/linuxfs
|
||||
chown -R '"$(id -u):$(id -g)"' app/src/main/assets/linuxfs
|
||||
'
|
||||
mkdir -p "${x86_stage}"
|
||||
cp -R "${linuxfs_dir}/x86_64" "${linuxfs_dir}/i386" "${x86_stage}/"
|
||||
save_step x86-preloads "${x86_key}" "${x86_stage}"
|
||||
fi
|
||||
|
||||
vr_out="${linuxfs_dir}/usr/local/lib/droiddeck-vr"
|
||||
vr_key=$(inputs_hash "${image_id} ${ndk_version} ${VK_INCLUDE:-}" tools/vr app/src/main/cpp/waylandcomp/generated/xdg-shell-protocol.c)
|
||||
if ! restore_step vr "${vr_key}" "${vr_out}"; then
|
||||
DROIDDECK_BUILD_IMAGE="${image_name}" "${repo_root}/tools/vr/build.sh" "${vr_out}"
|
||||
save_step vr "${vr_key}" "${vr_out}"
|
||||
fi
|
||||
|
||||
gpuload_out="${linuxfs_dir}/usr/local/lib/droiddeck-gpuload"
|
||||
gpuload_key=$(inputs_hash "${image_id} ${ndk_version} ${VK_INCLUDE:-}" tools/gpuload)
|
||||
if ! restore_step gpuload "${gpuload_key}" "${gpuload_out}"; then
|
||||
DROIDDECK_BUILD_IMAGE="${image_name}" "${repo_root}/tools/gpuload/build.sh" "${gpuload_out}"
|
||||
save_step gpuload "${gpuload_key}" "${gpuload_out}"
|
||||
fi
|
||||
|
||||
github_repo=${DROIDDECK_GITHUB_REPOSITORY:-}
|
||||
if [[ -z "${github_repo}" ]]; then
|
||||
origin_url=$(git -C "${repo_root}" remote get-url origin)
|
||||
@@ -223,46 +134,289 @@ if [[ -z "${github_repo}" ]]; then
|
||||
github_repo=${github_repo%.git}
|
||||
fi
|
||||
|
||||
cached() {
|
||||
local sha=$1 name=$2 out
|
||||
shift 2
|
||||
out="${cache_dir}/${sha}-${name}"
|
||||
if [[ -f "${out}" ]] && printf '%s %s\n' "${sha}" "${out}" | shasum -a 256 -c - >/dev/null 2>&1; then
|
||||
echo "${out}"
|
||||
return 0
|
||||
ci_components=0
|
||||
ci_run=
|
||||
ci_cache="${cache_dir}/ci-components"
|
||||
reuse_ci_components() {
|
||||
[[ "${DROIDDECK_CI_COMPONENTS:-1}" == 1 ]] && command -v gh >/dev/null 2>&1 || return 1
|
||||
# CI prepares with the pinned NDK, its own build image and PulseAudio source, and the system Vulkan headers.
|
||||
. "${repo_root}/tools/ci/toolchains.env"
|
||||
[[ "${ndk_version}" == "${CI_ANDROID_NDK_VERSION}" && -z "${DROIDDECK_PA13_SOURCE_DIR:-}" && -z "${VK_INCLUDE:-}" \
|
||||
&& -z "${requested_image}" ]] || return 1
|
||||
local base candidates run artifact archive part
|
||||
base=$(git -C "${repo_root}" merge-base HEAD origin/main 2>/dev/null || true)
|
||||
# Only runs of this repository's own main: a fork's pull request can also name its branch main.
|
||||
candidates=$(gh api "repos/${github_repo}/actions/artifacts?name=prepared-components&per_page=100" \
|
||||
-q "[.artifacts[] | select(.expired | not) | select(.workflow_run.head_branch == \"main\")
|
||||
| select(.workflow_run.head_repository_id == .workflow_run.repository_id)]
|
||||
| sort_by(.workflow_run.head_sha != \"${base}\") | .[:3][] | \"\(.workflow_run.id):\(.id)\"" 2>/dev/null) || return 1
|
||||
mkdir -p "${ci_cache}"
|
||||
# CI keeps these artifacts for 14 days.
|
||||
find "${ci_cache}" -mindepth 1 -maxdepth 1 -mtime +14 -exec rm -rf {} +
|
||||
for candidate in ${candidates}; do
|
||||
run=${candidate%%:*}
|
||||
artifact=${candidate#*:}
|
||||
archive="${ci_cache}/${artifact}.tar.gz"
|
||||
if [[ ! -f "${archive}" ]]; then
|
||||
part=$(mktemp -d "${ci_cache}/${run}.part.XXXXXX")
|
||||
if gh run download "${run}" -R "${github_repo}" -n prepared-components -D "${part}" >/dev/null 2>&1; then
|
||||
mv "${part}/prepared-components.tar.gz" "${archive}"
|
||||
fi
|
||||
rm -rf "${part}"
|
||||
[[ -f "${archive}" ]] || continue
|
||||
fi
|
||||
if python3 "${repo_root}/tools/components/reuse.py" "${archive}"; then
|
||||
ci_run=${run}
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
return 1
|
||||
}
|
||||
fetch_ci_xbox() {
|
||||
local stored="${ci_cache}/${ci_run}-xbox" part
|
||||
if [[ ! -d "${stored}" ]]; then
|
||||
part=$(mktemp -d "${ci_cache}/${ci_run}-xbox.part.XXXXXX")
|
||||
gh run download "${ci_run}" -R "${github_repo}" -n xbox-arm64 -D "${part}" >/dev/null 2>&1 || { rm -rf "${part}"; return 1; }
|
||||
# rename(2) refuses a non-empty destination, so a copy another build published first wins.
|
||||
python3 -c 'import os, sys; os.rename(sys.argv[1], sys.argv[2])' "${part}" "${stored}" 2>/dev/null || rm -rf "${part}"
|
||||
fi
|
||||
rm -f "${out}.part"
|
||||
out="${out}.part" "$@" >&2
|
||||
printf '%s %s\n' "${sha}" "${out}.part" | shasum -a 256 -c - >&2
|
||||
mv "${out}.part" "${out}"
|
||||
echo "${out}"
|
||||
rm -rf "${xbox_out}" && mkdir -p "${xbox_out}" && cp -R "${stored}/." "${xbox_out}/"
|
||||
}
|
||||
|
||||
if [[ -f "${repo_root}/tools/gamescope/release.env" ]]; then
|
||||
. "${repo_root}/tools/gamescope/release.env"
|
||||
gamescope_archive=$(cached "${GAMESCOPE_SHA256}" gamescope.tzst \
|
||||
bash -c 'gh release download "$0" -R "$1" -p gamescope.tzst -O "$out"' "${GAMESCOPE_TAG}" "${GAMESCOPE_REPO:-${github_repo}}")
|
||||
zstd -dc "${gamescope_archive}" | tar -xf - -C "${linuxfs_dir}"
|
||||
test -f "${linuxfs_dir}/usr/local/bin/gamescope"
|
||||
fi
|
||||
git_common=$(git -C "${repo_root}" rev-parse --path-format=absolute --git-common-dir)
|
||||
proot_out="${repo_root}/app/src/main/jniLibs/arm64-v8a"
|
||||
if reuse_ci_components; then
|
||||
ci_components=1
|
||||
echo "components: every recipe identity matches main CI run ${ci_run}; reusing its prepared components (DROIDDECK_CI_COMPONENTS=0 builds them here)"
|
||||
else
|
||||
rm -rf -- "${linuxfs_dir}"
|
||||
mkdir -p "${linuxfs_dir}"
|
||||
|
||||
. "${repo_root}/tools/linuxfs/uruntime.env"
|
||||
uruntime_binary=$(cached "${URUNTIME_SHA256}" "${URUNTIME_ASSET}" \
|
||||
bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "https://github.com/VHSgunzo/uruntime/releases/download/${URUNTIME_VERSION}/${URUNTIME_ASSET}")
|
||||
mkdir -p "${linuxfs_dir}/usr/local/lib/droiddeck" "${linuxfs_dir}/usr/local/share/licenses/uruntime"
|
||||
install -m644 "${uruntime_binary}" "${linuxfs_dir}/usr/local/lib/droiddeck/uruntime"
|
||||
install -m644 "${repo_root}/tools/linuxfs/licenses/uruntime-LICENSE" "${linuxfs_dir}/usr/local/share/licenses/uruntime/LICENSE"
|
||||
docker run --rm --platform "${docker_platform}" \
|
||||
--user "$(id -u):$(id -g)" \
|
||||
-v "${repo_root}:/src" -v "${git_common}:${git_common}" -w /src "${image_name}" bash -lc '
|
||||
set -euo pipefail
|
||||
d=app/src/main/assets/linuxfs
|
||||
mkdir -p "$d"
|
||||
put() { mkdir -p "$(dirname "$2")" && cat "$1" > "$2"; }
|
||||
aarch64-linux-gnu-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.so" app/src/main/cpp/fakeinput_steam.cpp -ldl
|
||||
aarch64-linux-gnu-strip --strip-unneeded "$d/libfakeinput.so"
|
||||
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
|
||||
-o "$d/libddsession.so" tools/linuxfs/preload/*.c -ldl
|
||||
aarch64-linux-gnu-strip --strip-unneeded "$d/libddsession.so"
|
||||
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
|
||||
-o "$d/libddfastpath.so" tools/proot/fastpath/fastpath.c -ldl
|
||||
aarch64-linux-gnu-strip --strip-unneeded "$d/libddfastpath.so"
|
||||
bash tools/nativeguest/build.sh "$d/libddnatv-hook.so"
|
||||
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -nostdlib -ffreestanding -fno-stack-protector \
|
||||
-fno-tree-loop-distribute-patterns -Wl,-z,defs -o "$d/libddaudit.so" tools/proot/fastpath/audit.c
|
||||
aarch64-linux-gnu-strip --strip-unneeded "$d/libddaudit.so"
|
||||
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
|
||||
-o "$d/libssbs.so" tools/linuxfs/ssbs/ssbs_adapter.c -ldl
|
||||
aarch64-linux-gnu-strip --strip-unneeded "$d/libssbs.so"
|
||||
mkdir -p "$d/usr/local/lib/droiddeck-xclipse"
|
||||
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -Wextra -Wno-unused-parameter -fvisibility=hidden -pthread \
|
||||
-o "$d/usr/local/lib/droiddeck-xclipse/libVkLayer_droiddeck_xclipse.so" tools/linuxfs/xclipse-layer/xclipse_layer.c -ldl
|
||||
aarch64-linux-gnu-strip --strip-unneeded "$d/usr/local/lib/droiddeck-xclipse/libVkLayer_droiddeck_xclipse.so"
|
||||
install -m644 tools/linuxfs/xclipse-layer/VkLayer_droiddeck_xclipse.json "$d/usr/local/lib/droiddeck-xclipse/"
|
||||
mkdir -p "$d/usr/local/bin"
|
||||
external/MaliBridge/scripts/build-client-linux.sh "$d" aarch64-linux-gnu-gcc
|
||||
aarch64-linux-gnu-gcc -O2 -Wall -o "$d/usr/local/bin/droiddeck-glprobe" tools/venus/glprobe.c -ldl
|
||||
aarch64-linux-gnu-strip --strip-unneeded "$d/usr/local/bin/droiddeck-glprobe"
|
||||
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/droiddeck-* tools/linuxfs/overlay/usr/local/bin/steam-compatibility; do
|
||||
put "$script" "$d/usr/local/bin/$(basename "$script")"
|
||||
done
|
||||
for f in tools/linuxfs/overlay/usr/bin/* tools/linuxfs/overlay/usr/bin/steamos-polkit-helpers/*; do
|
||||
[ -f "$f" ] && put "$f" "$d/${f#tools/linuxfs/overlay/}"
|
||||
done
|
||||
put tools/linuxfs/desktop/droiddeck-desktop "$d/usr/local/bin/droiddeck-desktop"
|
||||
put tools/linuxfs/desktop/droiddeck-gpu "$d/usr/local/bin/droiddeck-gpu"
|
||||
put tools/linuxfs/desktop/droiddeck-desktop-gpu "$d/usr/local/bin/droiddeck-desktop-gpu"
|
||||
put tools/linuxfs/desktop/kwin_wayland_wrapper "$d/usr/local/bin/kwin_wayland_wrapper"
|
||||
put tools/linuxfs/desktop/firefox-droiddeck.js \
|
||||
"$d/usr/lib/firefox/defaults/pref/droiddeck.js"
|
||||
|
||||
READELF=aarch64-linux-gnu-readelf bash tools/linuxfs/check-preloads.sh "$d"
|
||||
'
|
||||
|
||||
x86_key=$(inputs_hash bullseye tools/linuxfs/build-x86-preloads.sh tools/linuxfs/preload tools/linuxfs/fex \
|
||||
app/src/main/cpp/fakeinput_steam.cpp)
|
||||
x86_stage="${staging_dir}/x86-preloads"
|
||||
if restore_step x86-preloads "${x86_key}" "${linuxfs_dir}"; then :; else
|
||||
x86_platform=linux/amd64
|
||||
x86_packages="gcc g++ gcc-multilib g++-multilib binutils"
|
||||
x86_cross=0
|
||||
if [[ "${docker_platform}" == linux/arm64 ]]; then
|
||||
x86_platform=linux/arm64
|
||||
x86_packages="gcc-x86-64-linux-gnu g++-x86-64-linux-gnu gcc-i686-linux-gnu g++-i686-linux-gnu libc6-dev-amd64-cross libc6-dev-i386-cross binutils-x86-64-linux-gnu binutils-i686-linux-gnu"
|
||||
x86_cross=1
|
||||
fi
|
||||
docker run --rm --platform "${x86_platform}" -e X86_CROSS="${x86_cross}" -e X86_PACKAGES="${x86_packages}" \
|
||||
-v "${repo_root}:/src" -v "${git_common}:${git_common}" -w /src public.ecr.aws/docker/library/debian:bullseye bash -c '
|
||||
set -euo pipefail
|
||||
printf "deb http://archive.debian.org/debian bullseye main\ndeb http://archive.debian.org/debian-security bullseye-security main\n" > /etc/apt/sources.list
|
||||
apt-get -o Acquire::Check-Valid-Until=false update -qq
|
||||
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends $X86_PACKAGES >/dev/null
|
||||
tools/linuxfs/build-x86-preloads.sh app/src/main/assets/linuxfs
|
||||
chown -R '"$(id -u):$(id -g)"' app/src/main/assets/linuxfs
|
||||
'
|
||||
mkdir -p "${x86_stage}"
|
||||
cp -R "${linuxfs_dir}/x86_64" "${linuxfs_dir}/i386" "${x86_stage}/"
|
||||
save_step x86-preloads "${x86_key}" "${x86_stage}"
|
||||
fi
|
||||
|
||||
vr_out="${linuxfs_dir}/usr/local/lib/droiddeck-vr"
|
||||
vr_key=$(inputs_hash "${image_id} ${ndk_version} ${VK_INCLUDE:-}" tools/vr app/src/main/cpp/waylandcomp/generated/xdg-shell-protocol.c)
|
||||
if ! restore_step vr "${vr_key}" "${vr_out}"; then
|
||||
DROIDDECK_BUILD_IMAGE="${image_name}" "${repo_root}/tools/vr/build.sh" "${vr_out}"
|
||||
save_step vr "${vr_key}" "${vr_out}"
|
||||
fi
|
||||
|
||||
gpuload_out="${linuxfs_dir}/usr/local/lib/droiddeck-gpuload"
|
||||
gpuload_key=$(inputs_hash "${image_id} ${ndk_version} ${VK_INCLUDE:-}" tools/gpuload)
|
||||
if ! restore_step gpuload "${gpuload_key}" "${gpuload_out}"; then
|
||||
DROIDDECK_BUILD_IMAGE="${image_name}" "${repo_root}/tools/gpuload/build.sh" "${gpuload_out}"
|
||||
save_step gpuload "${gpuload_key}" "${gpuload_out}"
|
||||
fi
|
||||
|
||||
cached() {
|
||||
local sha=$1 name=$2 out
|
||||
shift 2
|
||||
out="${cache_dir}/${sha}-${name}"
|
||||
if [[ -f "${out}" ]] && printf '%s %s\n' "${sha}" "${out}" | shasum -a 256 -c - >/dev/null 2>&1; then
|
||||
echo "${out}"
|
||||
return 0
|
||||
fi
|
||||
rm -f "${out}.part"
|
||||
out="${out}.part" "$@" >&2
|
||||
printf '%s %s\n' "${sha}" "${out}.part" | shasum -a 256 -c - >&2
|
||||
mv "${out}.part" "${out}"
|
||||
echo "${out}"
|
||||
}
|
||||
|
||||
if [[ -f "${repo_root}/tools/gamescope/release.env" ]]; then
|
||||
. "${repo_root}/tools/gamescope/release.env"
|
||||
gamescope_archive=$(cached "${GAMESCOPE_SHA256}" gamescope.tzst \
|
||||
bash -c 'gh release download "$0" -R "$1" -p gamescope.tzst -O "$out"' "${GAMESCOPE_TAG}" "${GAMESCOPE_REPO:-${github_repo}}")
|
||||
zstd -dc "${gamescope_archive}" | tar -xf - -C "${linuxfs_dir}"
|
||||
test -f "${linuxfs_dir}/usr/local/bin/gamescope"
|
||||
fi
|
||||
|
||||
. "${repo_root}/tools/linuxfs/uruntime.env"
|
||||
uruntime_binary=$(cached "${URUNTIME_SHA256}" "${URUNTIME_ASSET}" \
|
||||
bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "https://github.com/VHSgunzo/uruntime/releases/download/${URUNTIME_VERSION}/${URUNTIME_ASSET}")
|
||||
mkdir -p "${linuxfs_dir}/usr/local/lib/droiddeck" "${linuxfs_dir}/usr/local/share/licenses/uruntime"
|
||||
install -m644 "${uruntime_binary}" "${linuxfs_dir}/usr/local/lib/droiddeck/uruntime"
|
||||
install -m644 "${repo_root}/tools/linuxfs/licenses/uruntime-LICENSE" "${linuxfs_dir}/usr/local/share/licenses/uruntime/LICENSE"
|
||||
|
||||
sync_assets="${repo_root}/app/src/main/assets/droiddeck-esync"
|
||||
if [[ -f "${repo_root}/tools/droiddeck-esync/release.env" ]]; then
|
||||
. "${repo_root}/tools/droiddeck-esync/release.env"
|
||||
sync_archive=$(cached "${SYNC_BUNDLE_SHA256}" "${SYNC_BUNDLE_ASSET}" \
|
||||
bash -c 'gh release download "$0" -R "$2" -p "$1" -O "$out"' "${SYNC_BUNDLE_TAG}" "${SYNC_BUNDLE_ASSET}" "${SYNC_BUNDLE_REPO}")
|
||||
rm -rf "${sync_assets}"
|
||||
mkdir -p "${sync_assets}"
|
||||
zstd -dc "${sync_archive}" | tar -xf - -C "${sync_assets}"
|
||||
test -f "${sync_assets}/index.json"
|
||||
test -f "${sync_assets}/index.json.sig"
|
||||
elif [[ -d "${sync_assets}" ]]; then
|
||||
echo "No tools/droiddeck-esync/release.env: the APK bundles the droiddeck-esync packs already in ${sync_assets}." >&2
|
||||
fi
|
||||
|
||||
msi_pkgs="${staging_dir}/msi-pkgs"
|
||||
msi_dir="${linuxfs_dir}/usr/local/lib/droiddeck-msitools"
|
||||
mkdir -p "${msi_pkgs}" "${msi_dir}"
|
||||
while read -r package_sha256 package_url; do
|
||||
[[ -n "${package_url}" ]] || continue
|
||||
package_archive=$(cached "${package_sha256}" "$(basename "${package_url}")" \
|
||||
bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "${package_url}")
|
||||
tar -xJf "${package_archive}" -C "${msi_pkgs}"
|
||||
done < <(grep -v '^#' "${repo_root}/tools/msitools/packages.txt")
|
||||
for tool in msiinfo cabextract; do install -m644 "${msi_pkgs}/usr/bin/${tool}" "${msi_dir}/${tool}"; done
|
||||
for tool in 7z 7z.so; do install -m644 "${msi_pkgs}/usr/lib/7zip/${tool}" "${msi_dir}/${tool}"; done
|
||||
for library in libmsi-1.0.so.0 libgsf-1.so.114 libgcab-1.0.so.0; do
|
||||
cp -L "${msi_pkgs}/usr/lib/${library}" "${msi_dir}/${library}"
|
||||
done
|
||||
mkdir -p "${linuxfs_dir}/usr/local/share/licenses/droiddeck-msitools"
|
||||
for license in NOTICE GPL-2 GPL-3 LGPL-2.1 7zip-License 7zip-unRarLicense; do
|
||||
install -m644 "${repo_root}/tools/msitools/licenses/${license}" \
|
||||
"${linuxfs_dir}/usr/local/share/licenses/droiddeck-msitools/${license}"
|
||||
done
|
||||
|
||||
mango_dir="${linuxfs_dir}/usr/local/lib/mangoapp"
|
||||
mango_pkgs="${staging_dir}/mango-pkgs"
|
||||
mkdir -p "${mango_dir}" "${mango_pkgs}"
|
||||
while read -r package_sha256 package_url; do
|
||||
[[ -n "${package_url}" ]] || continue
|
||||
package_archive=$(cached "${package_sha256}" "$(basename "${package_url}")" \
|
||||
bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "${package_url}")
|
||||
zstd -dc "${package_archive}" | tar -xf - -C "${mango_pkgs}"
|
||||
done < <(grep -v '^#' "${repo_root}/tools/mangoapp/packages.txt")
|
||||
install -m644 "${mango_pkgs}/usr/bin/mangoapp" "${mango_dir}/mangoapp"
|
||||
for library in libfmt.so.10 libspdlog.so.1.13 libglfw.so.3 libtraceevent.so.1; do
|
||||
cp -L "${mango_pkgs}/usr/lib/${library}" "${mango_dir}/${library}"
|
||||
done
|
||||
docker run --rm --platform "${docker_platform}" --user "$(id -u):$(id -g)" -v "${repo_root}:/src" -w /src "${image_name}" \
|
||||
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -Wl,-soname,libtracefs.so.1 \
|
||||
-o app/src/main/assets/linuxfs/usr/local/lib/mangoapp/libtracefs.so.1 tools/mangoapp/libtracefs-shim.c
|
||||
mkdir -p "${linuxfs_dir}/usr/local/bin"
|
||||
install -m644 "${repo_root}/tools/mangoapp/mangoapp" "${linuxfs_dir}/usr/local/bin/mangoapp"
|
||||
|
||||
pw_pkgs="${staging_dir}/pw-pkgs"
|
||||
mkdir -p "${pw_pkgs}"
|
||||
while read -r package_sha256 package_url; do
|
||||
[[ -n "${package_url}" ]] || continue
|
||||
package_archive=$(cached "${package_sha256}" "$(basename "${package_url}")" \
|
||||
bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "${package_url}")
|
||||
zstd -dc "${package_archive}" | tar -xf - -C "${pw_pkgs}"
|
||||
done < <(grep -v '^#' "${repo_root}/tools/pipewire/packages.txt")
|
||||
"${repo_root}/tools/pipewire/assemble.sh" "${pw_pkgs}" "${linuxfs_dir}/usr/local/lib/droiddeck-pipewire.tzst"
|
||||
|
||||
pa_source=${DROIDDECK_PA13_SOURCE_DIR:-"${staging_dir}/pulseaudio-13.0"}
|
||||
if [[ -z "${DROIDDECK_PA13_SOURCE_DIR:-}" ]]; then
|
||||
pa_tarball="${cache_dir}/pulseaudio-13.0.tar.gz"
|
||||
if [[ ! -s "${pa_tarball}" ]] || ! tar -tzf "${pa_tarball}" >/dev/null 2>&1; then
|
||||
curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "${pa_tarball}.part" \
|
||||
https://github.com/pulseaudio/pulseaudio/archive/refs/tags/v13.0.tar.gz
|
||||
mv "${pa_tarball}.part" "${pa_tarball}"
|
||||
fi
|
||||
mkdir -p "${pa_source}"
|
||||
tar -xzf "${pa_tarball}" -C "${pa_source}" --strip-components=1
|
||||
fi
|
||||
if [[ ! -f "${pa_source}/src/pulse/version.h.in" ]]; then
|
||||
echo "PulseAudio 13.0 source not found at ${pa_source}; set DROIDDECK_PA13_SOURCE_DIR." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
sink_output="${staging_dir}/sink-out"
|
||||
"${repo_root}/tools/directaudio/fetch.sh" "${repo_root}" "${sink_output}"
|
||||
"${repo_root}/tools/aaudio-sink/build.sh" "${pa_source}" "${sink_output}"
|
||||
proot_sources=$(cd "${repo_root}/tools/proot" && find . -type f ! -name '*.pyc' | LC_ALL=C sort | xargs shasum -a 256 | shasum -a 256 | cut -d' ' -f1)
|
||||
proot_inputs=$(printf '%s\n' "${proot_sources}" "${ndk_version}" | shasum -a 256 | cut -d' ' -f1)
|
||||
if [[ -f "${proot_out}/libproot.so" && -f "${proot_out}/libproot-loader.so" \
|
||||
&& "$(cat "${proot_out}/.proot-inputs" 2>/dev/null)" = "${proot_inputs}" ]] \
|
||||
&& (cd "${proot_out}" && shasum -a 256 -c .proot-outputs >/dev/null 2>&1); then
|
||||
echo "proot: sources unchanged, keeping ${proot_out}/libproot.so"
|
||||
else
|
||||
proot_stage="${staging_dir}/proot"
|
||||
if ! restore_step proot "${proot_inputs}" "${proot_stage}"; then
|
||||
"${repo_root}/tools/proot/build.sh" "${proot_stage}"
|
||||
save_step proot "${proot_inputs}" "${proot_stage}"
|
||||
fi
|
||||
install -m755 "${proot_stage}/libproot.so" "${proot_stage}/libproot-loader.so" "${proot_out}/"
|
||||
echo "${proot_inputs}" > "${proot_out}/.proot-inputs"
|
||||
(cd "${proot_out}" && shasum -a 256 libproot.so libproot-loader.so > .proot-outputs)
|
||||
fi
|
||||
fi
|
||||
|
||||
sync_assets="${repo_root}/app/src/main/assets/droiddeck-esync"
|
||||
if [[ -f "${repo_root}/tools/droiddeck-esync/release.env" ]]; then
|
||||
# Packs revoked after a bundle was published are dropped from local and CI-prepared bundles alike.
|
||||
. "${repo_root}/tools/droiddeck-esync/release.env"
|
||||
sync_archive=$(cached "${SYNC_BUNDLE_SHA256}" "${SYNC_BUNDLE_ASSET}" \
|
||||
bash -c 'gh release download "$0" -R "$2" -p "$1" -O "$out"' "${SYNC_BUNDLE_TAG}" "${SYNC_BUNDLE_ASSET}" "${SYNC_BUNDLE_REPO}")
|
||||
rm -rf "${sync_assets}"
|
||||
mkdir -p "${sync_assets}"
|
||||
zstd -dc "${sync_archive}" | tar -xf - -C "${sync_assets}"
|
||||
test -f "${sync_assets}/index.json"
|
||||
test -f "${sync_assets}/index.json.sig"
|
||||
sync_index=$(mktemp)
|
||||
gh release download "${SYNC_BUNDLE_TAG}" -R "${SYNC_BUNDLE_REPO}" -p index.json -O "${sync_index}" --clobber
|
||||
revoked=$(python3 -c 'import json, sys; print(" ".join(p["id"] for p in json.load(open(sys.argv[1]))["packs"] if p.get("revoked") is True))' "${sync_index}")
|
||||
@@ -273,94 +427,6 @@ if [[ -f "${repo_root}/tools/droiddeck-esync/release.env" ]]; then
|
||||
fi
|
||||
done
|
||||
rm -f "${sync_index}"
|
||||
elif [[ -d "${sync_assets}" ]]; then
|
||||
echo "No tools/droiddeck-esync/release.env: the APK bundles the droiddeck-esync packs already in ${sync_assets}." >&2
|
||||
fi
|
||||
|
||||
msi_pkgs="${staging_dir}/msi-pkgs"
|
||||
msi_dir="${linuxfs_dir}/usr/local/lib/droiddeck-msitools"
|
||||
mkdir -p "${msi_pkgs}" "${msi_dir}"
|
||||
while read -r package_sha256 package_url; do
|
||||
[[ -n "${package_url}" ]] || continue
|
||||
package_archive=$(cached "${package_sha256}" "$(basename "${package_url}")" \
|
||||
bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "${package_url}")
|
||||
tar -xJf "${package_archive}" -C "${msi_pkgs}"
|
||||
done < <(grep -v '^#' "${repo_root}/tools/msitools/packages.txt")
|
||||
for tool in msiinfo cabextract; do install -m644 "${msi_pkgs}/usr/bin/${tool}" "${msi_dir}/${tool}"; done
|
||||
for tool in 7z 7z.so; do install -m644 "${msi_pkgs}/usr/lib/7zip/${tool}" "${msi_dir}/${tool}"; done
|
||||
for library in libmsi-1.0.so.0 libgsf-1.so.114 libgcab-1.0.so.0; do
|
||||
cp -L "${msi_pkgs}/usr/lib/${library}" "${msi_dir}/${library}"
|
||||
done
|
||||
mkdir -p "${linuxfs_dir}/usr/local/share/licenses/droiddeck-msitools"
|
||||
for license in NOTICE GPL-2 GPL-3 LGPL-2.1 7zip-License 7zip-unRarLicense; do
|
||||
install -m644 "${repo_root}/tools/msitools/licenses/${license}" \
|
||||
"${linuxfs_dir}/usr/local/share/licenses/droiddeck-msitools/${license}"
|
||||
done
|
||||
|
||||
mango_dir="${linuxfs_dir}/usr/local/lib/mangoapp"
|
||||
mango_pkgs="${staging_dir}/mango-pkgs"
|
||||
mkdir -p "${mango_dir}" "${mango_pkgs}"
|
||||
while read -r package_sha256 package_url; do
|
||||
[[ -n "${package_url}" ]] || continue
|
||||
package_archive=$(cached "${package_sha256}" "$(basename "${package_url}")" \
|
||||
bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "${package_url}")
|
||||
zstd -dc "${package_archive}" | tar -xf - -C "${mango_pkgs}"
|
||||
done < <(grep -v '^#' "${repo_root}/tools/mangoapp/packages.txt")
|
||||
install -m644 "${mango_pkgs}/usr/bin/mangoapp" "${mango_dir}/mangoapp"
|
||||
for library in libfmt.so.10 libspdlog.so.1.13 libglfw.so.3 libtraceevent.so.1; do
|
||||
cp -L "${mango_pkgs}/usr/lib/${library}" "${mango_dir}/${library}"
|
||||
done
|
||||
docker run --rm --platform "${docker_platform}" --user "$(id -u):$(id -g)" -v "${repo_root}:/src" -w /src "${image_name}" \
|
||||
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -Wl,-soname,libtracefs.so.1 \
|
||||
-o app/src/main/assets/linuxfs/usr/local/lib/mangoapp/libtracefs.so.1 tools/mangoapp/libtracefs-shim.c
|
||||
mkdir -p "${linuxfs_dir}/usr/local/bin"
|
||||
install -m644 "${repo_root}/tools/mangoapp/mangoapp" "${linuxfs_dir}/usr/local/bin/mangoapp"
|
||||
|
||||
pw_pkgs="${staging_dir}/pw-pkgs"
|
||||
mkdir -p "${pw_pkgs}"
|
||||
while read -r package_sha256 package_url; do
|
||||
[[ -n "${package_url}" ]] || continue
|
||||
package_archive=$(cached "${package_sha256}" "$(basename "${package_url}")" \
|
||||
bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "${package_url}")
|
||||
zstd -dc "${package_archive}" | tar -xf - -C "${pw_pkgs}"
|
||||
done < <(grep -v '^#' "${repo_root}/tools/pipewire/packages.txt")
|
||||
"${repo_root}/tools/pipewire/assemble.sh" "${pw_pkgs}" "${linuxfs_dir}/usr/local/lib/droiddeck-pipewire.tzst"
|
||||
|
||||
pa_source=${DROIDDECK_PA13_SOURCE_DIR:-"${staging_dir}/pulseaudio-13.0"}
|
||||
if [[ -z "${DROIDDECK_PA13_SOURCE_DIR:-}" ]]; then
|
||||
pa_tarball="${cache_dir}/pulseaudio-13.0.tar.gz"
|
||||
if [[ ! -s "${pa_tarball}" ]] || ! tar -tzf "${pa_tarball}" >/dev/null 2>&1; then
|
||||
curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "${pa_tarball}.part" \
|
||||
https://github.com/pulseaudio/pulseaudio/archive/refs/tags/v13.0.tar.gz
|
||||
mv "${pa_tarball}.part" "${pa_tarball}"
|
||||
fi
|
||||
mkdir -p "${pa_source}"
|
||||
tar -xzf "${pa_tarball}" -C "${pa_source}" --strip-components=1
|
||||
fi
|
||||
if [[ ! -f "${pa_source}/src/pulse/version.h.in" ]]; then
|
||||
echo "PulseAudio 13.0 source not found at ${pa_source}; set DROIDDECK_PA13_SOURCE_DIR." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
sink_output="${staging_dir}/sink-out"
|
||||
"${repo_root}/tools/directaudio/fetch.sh" "${repo_root}" "${sink_output}"
|
||||
"${repo_root}/tools/aaudio-sink/build.sh" "${pa_source}" "${sink_output}"
|
||||
proot_out="${repo_root}/app/src/main/jniLibs/arm64-v8a"
|
||||
proot_sources=$(cd "${repo_root}/tools/proot" && find . -type f ! -name '*.pyc' | LC_ALL=C sort | xargs shasum -a 256 | shasum -a 256 | cut -d' ' -f1)
|
||||
proot_inputs=$(printf '%s\n' "${proot_sources}" "${ndk_version}" | shasum -a 256 | cut -d' ' -f1)
|
||||
if [[ -f "${proot_out}/libproot.so" && -f "${proot_out}/libproot-loader.so" \
|
||||
&& "$(cat "${proot_out}/.proot-inputs" 2>/dev/null)" = "${proot_inputs}" ]] \
|
||||
&& (cd "${proot_out}" && shasum -a 256 -c .proot-outputs >/dev/null 2>&1); then
|
||||
echo "proot: sources unchanged, keeping ${proot_out}/libproot.so"
|
||||
else
|
||||
proot_stage="${staging_dir}/proot"
|
||||
if ! restore_step proot "${proot_inputs}" "${proot_stage}"; then
|
||||
"${repo_root}/tools/proot/build.sh" "${proot_stage}"
|
||||
save_step proot "${proot_inputs}" "${proot_stage}"
|
||||
fi
|
||||
install -m755 "${proot_stage}/libproot.so" "${proot_stage}/libproot-loader.so" "${proot_out}/"
|
||||
echo "${proot_inputs}" > "${proot_out}/.proot-inputs"
|
||||
(cd "${proot_out}" && shasum -a 256 libproot.so libproot-loader.so > .proot-outputs)
|
||||
fi
|
||||
|
||||
syncthing_src="${repo_root}/tools/syncthing/syncthing-android/syncthing/src/github.com/syncthing/syncthing"
|
||||
@@ -384,21 +450,23 @@ else
|
||||
echo "${syncthing_inputs}" > "${proot_out}/.syncthing-inputs"
|
||||
fi
|
||||
|
||||
bundle_dir="${staging_dir}/pulseaudio-bundle"
|
||||
mkdir -p "${bundle_dir}"
|
||||
zstd -dc "${bundle_asset}" | tar -xf - -C "${bundle_dir}"
|
||||
if [[ -e "${bundle_dir}/modules/arm64/module-aaudio-sink.so" \
|
||||
|| -e "${bundle_dir}/modules/arm64/module-directaudio-native-sink.so" ]]; then
|
||||
echo "The committed audio bundle already contains a built ARM64 sink." >&2
|
||||
exit 1
|
||||
if [[ "${ci_components}" != 1 ]]; then
|
||||
bundle_dir="${staging_dir}/pulseaudio-bundle"
|
||||
mkdir -p "${bundle_dir}"
|
||||
zstd -dc "${bundle_asset}" | tar -xf - -C "${bundle_dir}"
|
||||
if [[ -e "${bundle_dir}/modules/arm64/module-aaudio-sink.so" \
|
||||
|| -e "${bundle_dir}/modules/arm64/module-directaudio-native-sink.so" ]]; then
|
||||
echo "The committed audio bundle already contains a built ARM64 sink." >&2
|
||||
exit 1
|
||||
fi
|
||||
install -m755 "${sink_output}/module-aaudio-sink.so" \
|
||||
"${bundle_dir}/modules/arm64/module-aaudio-sink.so"
|
||||
install -m755 "${sink_output}/module-directaudio-native-sink.so" \
|
||||
"${bundle_dir}/modules/arm64/module-directaudio-native-sink.so"
|
||||
tar -cf - -C "${bundle_dir}" . | zstd -19 -T0 -c > "${staging_dir}/pulseaudio.tzst"
|
||||
mkdir -p "${repo_root}/app/build/prepared-assets"
|
||||
mv "${staging_dir}/pulseaudio.tzst" "${repo_root}/app/build/prepared-assets/pulseaudio.tzst"
|
||||
fi
|
||||
install -m755 "${sink_output}/module-aaudio-sink.so" \
|
||||
"${bundle_dir}/modules/arm64/module-aaudio-sink.so"
|
||||
install -m755 "${sink_output}/module-directaudio-native-sink.so" \
|
||||
"${bundle_dir}/modules/arm64/module-directaudio-native-sink.so"
|
||||
tar -cf - -C "${bundle_dir}" . | zstd -19 -T0 -c > "${staging_dir}/pulseaudio.tzst"
|
||||
mkdir -p "${repo_root}/app/build/prepared-assets"
|
||||
mv "${staging_dir}/pulseaudio.tzst" "${repo_root}/app/build/prepared-assets/pulseaudio.tzst"
|
||||
|
||||
gradle_rust_arg=""
|
||||
if [[ "${DROIDDECK_SKIP_RUST:-0}" == 1 ]]; then
|
||||
@@ -419,19 +487,23 @@ else
|
||||
fi
|
||||
|
||||
cd "${repo_root}"
|
||||
python3 tools/quest/build-driver.py "${NDK}"
|
||||
[[ "${ci_components}" == 1 ]] || python3 tools/quest/build-driver.py "${NDK}"
|
||||
xbox_out="${linuxfs_dir}/usr/local/lib/droiddeck-xbox"
|
||||
xbox_key=$(inputs_hash "native-arm64-ubuntu24.04" tools/xbox)
|
||||
if ! restore_step xbox "${xbox_key}" "${xbox_out}"; then
|
||||
if [[ "${ci_components}" == 1 ]] && fetch_ci_xbox; then
|
||||
echo "xbox: reused main CI run ${ci_run}"
|
||||
elif ! restore_step xbox "${xbox_key}" "${xbox_out}"; then
|
||||
bash tools/xbox/build-local.sh
|
||||
save_step xbox "${xbox_key}" "${xbox_out}"
|
||||
fi
|
||||
|
||||
comet_out="${linuxfs_dir}/usr/local/lib/droiddeck-comet"
|
||||
comet_key=$(inputs_hash "${image_id}" tools/comet)
|
||||
if ! restore_step comet "${comet_key}" "${comet_out}"; then
|
||||
DROIDDECK_BUILD_IMAGE="${image_name}" bash tools/comet/build-local.sh
|
||||
save_step comet "${comet_key}" "${comet_out}"
|
||||
if [[ "${ci_components}" != 1 ]]; then
|
||||
comet_out="${linuxfs_dir}/usr/local/lib/droiddeck-comet"
|
||||
comet_key=$(inputs_hash "${image_id}" tools/comet)
|
||||
if ! restore_step comet "${comet_key}" "${comet_out}"; then
|
||||
DROIDDECK_BUILD_IMAGE="${image_name}" bash tools/comet/build-local.sh
|
||||
save_step comet "${comet_key}" "${comet_out}"
|
||||
fi
|
||||
fi
|
||||
if [[ "${DROIDDECK_SKIP_RUST:-0}" != 1 ]]; then
|
||||
upc_out="${linuxfs_dir}/usr/local/lib/droiddeck-ubisoft"
|
||||
|
||||
Executable
+14
@@ -0,0 +1,14 @@
|
||||
#!/usr/bin/env bash
|
||||
set -uo pipefail
|
||||
workspace="${1:?}"
|
||||
find /tmp -maxdepth 1 -user "$(id -u)" \( -name 'robolectric-*' -o -name 'junit*' -o -name 'gradle-*' -o -name 'kotlin-*' \) -mmin +180 -print0 |
|
||||
while IFS= read -r -d '' entry; do
|
||||
recent=$(find "$entry" -xdev -mmin -180 -print -quit 2>/dev/null) && [ -z "$recent" ] && rm -rf --one-file-system --preserve-root=all -- "$entry"
|
||||
done
|
||||
free=$(df --output=avail -k "$workspace" | tail -1)
|
||||
if [ "$free" -lt 20971520 ]; then
|
||||
rm -rf --one-file-system --preserve-root=all -- "${HOME:?}/.gradle/caches/build-cache-1" "${HOME:?}/.gradle/.tmp"
|
||||
fi
|
||||
df -h /tmp "$workspace"
|
||||
du -xsh /tmp "${HOME:?}/.gradle" "${HOME:?}/.cargo" "${HOME:?}/.m2" "$(dirname "$workspace")" 2>/dev/null | sort -h
|
||||
exit 0
|
||||
@@ -0,0 +1,150 @@
|
||||
"""Install the components a main CI run prepared when they match this tree.
|
||||
|
||||
The run's prepared-components archive is used only when every recipe identity it records equals
|
||||
the identity of the local tree, the inputs CI builds outside the recipes are unchanged from the
|
||||
run's source tree, and no recipe submodule has local edits. Files are verified in a staging
|
||||
directory before any local output is replaced.
|
||||
"""
|
||||
import argparse
|
||||
from contextlib import contextmanager
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path, PurePosixPath
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
import prepare # noqa: E402
|
||||
|
||||
# CI records identities under its runner labels and pinned NDK, not this host's.
|
||||
RUNNER_ARCHITECTURES = ('X64', 'ARM64')
|
||||
# The components job builds these outside the recipe registry.
|
||||
UNREGISTERED_INPUTS = ['.github/workflows/build.yml', 'tools/linuxfs/xclipse-layer', 'tools/venus/glprobe.c',
|
||||
'tools/quest']
|
||||
|
||||
|
||||
def ci_environment(architecture, root):
|
||||
ndk = next(line.split('=', 1)[1].strip()
|
||||
for line in (root / 'tools/ci/toolchains.env').read_text().splitlines()
|
||||
if line.startswith('CI_ANDROID_NDK_VERSION='))
|
||||
return dict(RUNNER_OS='Linux', RUNNER_ARCH=architecture, NDK_VERSION=ndk)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def environ(values):
|
||||
saved = {key: os.environ.get(key) for key in values}
|
||||
os.environ.update(values)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
for key, value in saved.items():
|
||||
if value is None:
|
||||
os.environ.pop(key, None)
|
||||
else:
|
||||
os.environ[key] = value
|
||||
|
||||
|
||||
def identities(environment, root):
|
||||
with environ(environment):
|
||||
return {name: prepare.identity(name, root) for name in prepare.registry(root)}
|
||||
|
||||
|
||||
def git(root, *args):
|
||||
return subprocess.run(['git', *args], cwd=root, capture_output=True, text=True)
|
||||
|
||||
|
||||
def unregistered_changes(source_tree, root):
|
||||
if git(root, 'cat-file', '-e', source_tree + '^{tree}').returncode:
|
||||
return ['source tree ' + source_tree + ' (fetch origin main)']
|
||||
changed = git(root, 'diff', '--name-only', source_tree, '--', *UNREGISTERED_INPUTS).stdout.split()
|
||||
changed += git(root, 'ls-files', '--others', '--exclude-standard', '--', *UNREGISTERED_INPUTS).stdout.split()
|
||||
return sorted(set(changed))
|
||||
|
||||
|
||||
def edited_submodules(root):
|
||||
inputs = [path for spec in prepare.registry(root).values()
|
||||
for path in spec.get('inputs', []) + spec.get('source_inputs', [])]
|
||||
staged = git(root, 'ls-files', '--stage', '--', *inputs).stdout.splitlines()
|
||||
links = [line.split('\t', 1)[1] for line in staged if line.startswith('160000 ')]
|
||||
return [link for link in links
|
||||
if git(root, 'diff', '--quiet', '--ignore-submodules=none', '--', link).returncode]
|
||||
|
||||
|
||||
def extract(archive_path, stage):
|
||||
allowed = set(prepare.LIBRARIES + [prepare.MANIFEST])
|
||||
total = 0
|
||||
with tarfile.open(archive_path, mode='r:gz') as archive:
|
||||
for entry in archive:
|
||||
name = PurePosixPath(entry.name)
|
||||
total += entry.size
|
||||
if (not entry.isfile() or name.is_absolute() or '..' in name.parts or '\\' in entry.name
|
||||
or name.as_posix() != entry.name or total > 2 * 1024**3
|
||||
or not (entry.name in allowed or any(entry.name.startswith(t + '/') for t in prepare.TREES))):
|
||||
raise ValueError('Unsafe prepared component archive: ' + entry.name)
|
||||
path = stage / entry.name
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with path.open('xb') as output:
|
||||
shutil.copyfileobj(archive.extractfile(entry), output)
|
||||
path.chmod(entry.mode & 0o777)
|
||||
|
||||
|
||||
def digest(path):
|
||||
with path.open('rb') as stream:
|
||||
return hashlib.file_digest(stream, 'sha256').hexdigest()
|
||||
|
||||
|
||||
def install(stage, root):
|
||||
for name in prepare.TREES:
|
||||
shutil.rmtree(root / name, ignore_errors=True)
|
||||
(root / name).parent.mkdir(parents=True, exist_ok=True)
|
||||
os.replace(stage / name, root / name)
|
||||
for name in prepare.LIBRARIES + [prepare.MANIFEST]:
|
||||
(root / name).parent.mkdir(parents=True, exist_ok=True)
|
||||
os.replace(stage / name, root / name)
|
||||
|
||||
|
||||
def reuse(archive_path, root=prepare.ROOT):
|
||||
with tarfile.open(archive_path, mode='r:gz') as archive:
|
||||
data = json.load(archive.extractfile(prepare.MANIFEST))
|
||||
if data.get('version') != 1:
|
||||
raise ValueError('Unknown prepared component archive version')
|
||||
recorded = data.get('recipes') or {}
|
||||
environment = next((ci_environment(a, root) for a in RUNNER_ARCHITECTURES
|
||||
if identities(ci_environment(a, root), root) == recorded), None)
|
||||
if environment is None:
|
||||
local = identities(ci_environment(RUNNER_ARCHITECTURES[0], root), root)
|
||||
changed = sorted(name for name in local.keys() | recorded.keys() if local.get(name) != recorded.get(name))
|
||||
print('CI run ' + str(data.get('run')) + ' prepared different components: ' + ', '.join(changed))
|
||||
return False
|
||||
differences = unregistered_changes(data['source_tree'], root) + edited_submodules(root)
|
||||
if differences:
|
||||
print('CI run ' + str(data.get('run')) + ' built from other sources: ' + ', '.join(differences))
|
||||
return False
|
||||
(root / 'app/build').mkdir(parents=True, exist_ok=True)
|
||||
with tempfile.TemporaryDirectory(dir=root / 'app/build', prefix='.reuse-') as stage:
|
||||
stage = Path(stage)
|
||||
extract(archive_path, stage)
|
||||
files = sorted(path.relative_to(stage).as_posix() for path in stage.rglob('*')
|
||||
if path.is_file() and path.relative_to(stage).as_posix() != prepare.MANIFEST)
|
||||
if data.get('files') != {name: digest(stage / name) for name in files}:
|
||||
raise ValueError('Prepared components do not match their recorded file hashes')
|
||||
missing = [name for name in prepare.TREES if not (stage / name).is_dir()]
|
||||
missing += [name for name in prepare.LIBRARIES + [prepare.MANIFEST] if not (stage / name).is_file()]
|
||||
if missing:
|
||||
raise ValueError('Prepared component archive is missing ' + ', '.join(missing))
|
||||
install(stage, root)
|
||||
return True
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('archive', type=Path)
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
sys.exit(0 if reuse(args.archive) else 3)
|
||||
except (ValueError, OSError, KeyError, tarfile.TarError) as error:
|
||||
sys.exit('Cannot reuse CI components: ' + str(error))
|
||||
@@ -1,5 +1,5 @@
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp
|
||||
index 11ff163..085a621 100644
|
||||
index 11ff163..4c3be85 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp
|
||||
@@ -209,6 +209,41 @@ uint64_t SyscallPassthrough7(FEXCore::Core::CpuStateFrame* Frame, uint64_t arg1,
|
||||
@@ -44,6 +44,20 @@ index 11ff163..085a621 100644
|
||||
static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) {
|
||||
REGISTER_SYSCALL_IMPL(read, SyscallPassthrough3<SYSCALL_DEF(read)>);
|
||||
REGISTER_SYSCALL_IMPL(write, SyscallPassthrough3<SYSCALL_DEF(write)>);
|
||||
@@ -220,11 +255,11 @@ static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) {
|
||||
REGISTER_SYSCALL_IMPL(shmctl, SyscallPassthrough3<SYSCALL_DEF(shmctl)>);
|
||||
REGISTER_SYSCALL_IMPL(getpid, SyscallPassthrough0<SYSCALL_DEF(getpid)>);
|
||||
REGISTER_SYSCALL_IMPL(socket, SyscallPassthrough3<SYSCALL_DEF(socket)>);
|
||||
- REGISTER_SYSCALL_IMPL(connect, SyscallPassthrough3<SYSCALL_DEF(connect)>);
|
||||
+ REGISTER_SYSCALL_IMPL(connect, SyscallPathPassthrough3<SYSCALL_DEF(connect)>);
|
||||
REGISTER_SYSCALL_IMPL(sendto, SyscallPassthrough6<SYSCALL_DEF(sendto)>);
|
||||
REGISTER_SYSCALL_IMPL(recvfrom, SyscallPassthrough6<SYSCALL_DEF(recvfrom)>);
|
||||
REGISTER_SYSCALL_IMPL(shutdown, SyscallPassthrough2<SYSCALL_DEF(shutdown)>);
|
||||
- REGISTER_SYSCALL_IMPL(bind, SyscallPassthrough3<SYSCALL_DEF(bind)>);
|
||||
+ REGISTER_SYSCALL_IMPL(bind, SyscallPathPassthrough3<SYSCALL_DEF(bind)>);
|
||||
REGISTER_SYSCALL_IMPL(listen, SyscallPassthrough2<SYSCALL_DEF(listen)>);
|
||||
REGISTER_SYSCALL_IMPL(getsockname, SyscallPassthrough3<SYSCALL_DEF(getsockname)>);
|
||||
REGISTER_SYSCALL_IMPL(getpeername, SyscallPassthrough3<SYSCALL_DEF(getpeername)>);
|
||||
@@ -238,9 +273,9 @@ static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) {
|
||||
REGISTER_SYSCALL_IMPL(flock, SyscallPassthrough2<SYSCALL_DEF(flock)>);
|
||||
REGISTER_SYSCALL_IMPL(fsync, SyscallPassthrough1<SYSCALL_DEF(fsync)>);
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
diff --git a/Source/Tools/FEXInterpreter/ELFCodeLoader.h b/Source/Tools/FEXInterpreter/ELFCodeLoader.h
|
||||
index e1f601b..cebf1f5 100644
|
||||
--- a/Source/Tools/FEXInterpreter/ELFCodeLoader.h
|
||||
+++ b/Source/Tools/FEXInterpreter/ELFCodeLoader.h
|
||||
@@ -222,6 +222,32 @@ class ELFCodeLoader final : public FEX::CodeLoader {
|
||||
|
||||
public:
|
||||
|
||||
+ static fextl::string GuestPreload(const char* List, const fextl::string& RootFS) {
|
||||
+ fextl::string Result;
|
||||
+ for (const char* Start = List; *Start; Start += *Start ? 1 : 0) {
|
||||
+ size_t Length = strcspn(Start, ": ");
|
||||
+ fextl::string Entry(Start, Length);
|
||||
+ Start += Length;
|
||||
+ if (Entry.empty()) {
|
||||
+ continue;
|
||||
+ }
|
||||
+ if (Entry[0] == '/') {
|
||||
+ auto Type = ::ELFLoader::ELFContainer::GetELFType(ResolveRootfsFile(Entry, RootFS));
|
||||
+ if (Type == ::ELFLoader::ELFContainer::TYPE_NONE) {
|
||||
+ Type = ::ELFLoader::ELFContainer::GetELFType(Entry);
|
||||
+ }
|
||||
+ if (Type == ::ELFLoader::ELFContainer::TYPE_OTHER_ELF) {
|
||||
+ continue;
|
||||
+ }
|
||||
+ }
|
||||
+ if (!Result.empty()) {
|
||||
+ Result += ':';
|
||||
+ }
|
||||
+ Result += Entry;
|
||||
+ }
|
||||
+ return Result;
|
||||
+ }
|
||||
+
|
||||
static fextl::string ResolveRootfsFile(const fextl::string& File, fextl::string RootFS) {
|
||||
// If the path is relative then just run that
|
||||
if (File[0] != '/') {
|
||||
@@ -330,6 +356,13 @@ public:
|
||||
if (envp[i] == nullptr) {
|
||||
break;
|
||||
}
|
||||
+ if (strncmp(envp[i], "LD_PRELOAD=", 11) == 0) {
|
||||
+ auto Preload = GuestPreload(envp[i] + 11, RootFS);
|
||||
+ if (!Preload.empty()) {
|
||||
+ EnvironmentVariables.emplace_back("LD_PRELOAD=" + Preload);
|
||||
+ }
|
||||
+ continue;
|
||||
+ }
|
||||
EnvironmentVariables.emplace_back(envp[i]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
diff --git a/Data/ThunksDB.json b/Data/ThunksDB.json
|
||||
index d52ff04..886379a 100644
|
||||
--- a/Data/ThunksDB.json
|
||||
+++ b/Data/ThunksDB.json
|
||||
@@ -6,7 +6,9 @@
|
||||
"@PREFIX_LIB@/libGL.so",
|
||||
"@PREFIX_LIB@/libGL.so.1",
|
||||
"@PREFIX_LIB@/libGL.so.1.2.0",
|
||||
- "@PREFIX_LIB@/libGL.so.1.7.0"
|
||||
+ "@PREFIX_LIB@/libGL.so.1.7.0",
|
||||
+ "@PREFIX_LIB@/libOpenGL.so.0",
|
||||
+ "@PREFIX_LIB@/libOpenGL.so.0.0.0"
|
||||
]
|
||||
},
|
||||
"Vulkan": {
|
||||
@@ -0,0 +1,106 @@
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp
|
||||
index 4c3be85..e287cd2 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp
|
||||
@@ -209,6 +209,13 @@ uint64_t SyscallPassthrough7(FEXCore::Core::CpuStateFrame* Frame, uint64_t arg1,
|
||||
}
|
||||
#endif
|
||||
|
||||
+template<int syscall_num>
|
||||
+requires (syscall_num != -1)
|
||||
+uint64_t SyscallPathPassthrough0(FEXCore::Core::CpuStateFrame* Frame) {
|
||||
+ uint64_t Result = ::syscall(syscall_num);
|
||||
+ SYSCALL_ERRNO();
|
||||
+}
|
||||
+
|
||||
template<int syscall_num>
|
||||
requires (syscall_num != -1)
|
||||
uint64_t SyscallPathPassthrough1(FEXCore::Core::CpuStateFrame* Frame, uint64_t arg1) {
|
||||
@@ -278,29 +285,29 @@ static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) {
|
||||
REGISTER_SYSCALL_IMPL(chdir, SyscallPathPassthrough1<SYSCALL_DEF(chdir)>);
|
||||
REGISTER_SYSCALL_IMPL(fchdir, SyscallPassthrough1<SYSCALL_DEF(fchdir)>);
|
||||
REGISTER_SYSCALL_IMPL(fchmod, SyscallPassthrough2<SYSCALL_DEF(fchmod)>);
|
||||
- REGISTER_SYSCALL_IMPL(fchown, SyscallPassthrough3<SYSCALL_DEF(fchown)>);
|
||||
+ REGISTER_SYSCALL_IMPL(fchown, SyscallPathPassthrough3<SYSCALL_DEF(fchown)>);
|
||||
REGISTER_SYSCALL_IMPL(umask, SyscallPassthrough1<SYSCALL_DEF(umask)>);
|
||||
- REGISTER_SYSCALL_IMPL(getuid, SyscallPassthrough0<SYSCALL_DEF(getuid)>);
|
||||
+ REGISTER_SYSCALL_IMPL(getuid, SyscallPathPassthrough0<SYSCALL_DEF(getuid)>);
|
||||
REGISTER_SYSCALL_IMPL(syslog, SyscallPassthrough3<SYSCALL_DEF(syslog)>);
|
||||
- REGISTER_SYSCALL_IMPL(getgid, SyscallPassthrough0<SYSCALL_DEF(getgid)>);
|
||||
- REGISTER_SYSCALL_IMPL(setuid, SyscallPassthrough1<SYSCALL_DEF(setuid)>);
|
||||
- REGISTER_SYSCALL_IMPL(setgid, SyscallPassthrough1<SYSCALL_DEF(setgid)>);
|
||||
- REGISTER_SYSCALL_IMPL(geteuid, SyscallPassthrough0<SYSCALL_DEF(geteuid)>);
|
||||
- REGISTER_SYSCALL_IMPL(getegid, SyscallPassthrough0<SYSCALL_DEF(getegid)>);
|
||||
+ REGISTER_SYSCALL_IMPL(getgid, SyscallPathPassthrough0<SYSCALL_DEF(getgid)>);
|
||||
+ REGISTER_SYSCALL_IMPL(setuid, SyscallPathPassthrough1<SYSCALL_DEF(setuid)>);
|
||||
+ REGISTER_SYSCALL_IMPL(setgid, SyscallPathPassthrough1<SYSCALL_DEF(setgid)>);
|
||||
+ REGISTER_SYSCALL_IMPL(geteuid, SyscallPathPassthrough0<SYSCALL_DEF(geteuid)>);
|
||||
+ REGISTER_SYSCALL_IMPL(getegid, SyscallPathPassthrough0<SYSCALL_DEF(getegid)>);
|
||||
REGISTER_SYSCALL_IMPL(setpgid, SyscallPassthrough2<SYSCALL_DEF(setpgid)>);
|
||||
REGISTER_SYSCALL_IMPL(getppid, SyscallPassthrough0<SYSCALL_DEF(getppid)>);
|
||||
REGISTER_SYSCALL_IMPL(setsid, SyscallPassthrough0<SYSCALL_DEF(setsid)>);
|
||||
- REGISTER_SYSCALL_IMPL(setreuid, SyscallPassthrough2<SYSCALL_DEF(setreuid)>);
|
||||
- REGISTER_SYSCALL_IMPL(setregid, SyscallPassthrough2<SYSCALL_DEF(setregid)>);
|
||||
- REGISTER_SYSCALL_IMPL(getgroups, SyscallPassthrough2<SYSCALL_DEF(getgroups)>);
|
||||
- REGISTER_SYSCALL_IMPL(setgroups, SyscallPassthrough2<SYSCALL_DEF(setgroups)>);
|
||||
- REGISTER_SYSCALL_IMPL(setresuid, SyscallPassthrough3<SYSCALL_DEF(setresuid)>);
|
||||
- REGISTER_SYSCALL_IMPL(getresuid, SyscallPassthrough3<SYSCALL_DEF(getresuid)>);
|
||||
- REGISTER_SYSCALL_IMPL(setresgid, SyscallPassthrough3<SYSCALL_DEF(setresgid)>);
|
||||
- REGISTER_SYSCALL_IMPL(getresgid, SyscallPassthrough3<SYSCALL_DEF(getresgid)>);
|
||||
+ REGISTER_SYSCALL_IMPL(setreuid, SyscallPathPassthrough2<SYSCALL_DEF(setreuid)>);
|
||||
+ REGISTER_SYSCALL_IMPL(setregid, SyscallPathPassthrough2<SYSCALL_DEF(setregid)>);
|
||||
+ REGISTER_SYSCALL_IMPL(getgroups, SyscallPathPassthrough2<SYSCALL_DEF(getgroups)>);
|
||||
+ REGISTER_SYSCALL_IMPL(setgroups, SyscallPathPassthrough2<SYSCALL_DEF(setgroups)>);
|
||||
+ REGISTER_SYSCALL_IMPL(setresuid, SyscallPathPassthrough3<SYSCALL_DEF(setresuid)>);
|
||||
+ REGISTER_SYSCALL_IMPL(getresuid, SyscallPathPassthrough3<SYSCALL_DEF(getresuid)>);
|
||||
+ REGISTER_SYSCALL_IMPL(setresgid, SyscallPathPassthrough3<SYSCALL_DEF(setresgid)>);
|
||||
+ REGISTER_SYSCALL_IMPL(getresgid, SyscallPathPassthrough3<SYSCALL_DEF(getresgid)>);
|
||||
REGISTER_SYSCALL_IMPL(getpgid, SyscallPassthrough1<SYSCALL_DEF(getpgid)>);
|
||||
- REGISTER_SYSCALL_IMPL(setfsuid, SyscallPassthrough1<SYSCALL_DEF(setfsuid)>);
|
||||
- REGISTER_SYSCALL_IMPL(setfsgid, SyscallPassthrough1<SYSCALL_DEF(setfsgid)>);
|
||||
+ REGISTER_SYSCALL_IMPL(setfsuid, SyscallPathPassthrough1<SYSCALL_DEF(setfsuid)>);
|
||||
+ REGISTER_SYSCALL_IMPL(setfsgid, SyscallPathPassthrough1<SYSCALL_DEF(setfsgid)>);
|
||||
REGISTER_SYSCALL_IMPL(getsid, SyscallPassthrough1<SYSCALL_DEF(getsid)>);
|
||||
REGISTER_SYSCALL_IMPL(capget, SyscallPassthrough2<SYSCALL_DEF(capget)>);
|
||||
REGISTER_SYSCALL_IMPL(capset, SyscallPassthrough2<SYSCALL_DEF(capset)>);
|
||||
@@ -537,23 +544,23 @@ namespace x64 {
|
||||
namespace x32 {
|
||||
void RegisterPassthrough(FEX::HLE::SyscallHandler* Handler) {
|
||||
RegisterCommon(Handler);
|
||||
- REGISTER_SYSCALL_IMPL_X32(getuid32, SyscallPassthrough0<SYSCALL_DEF(getuid)>);
|
||||
- REGISTER_SYSCALL_IMPL_X32(getgid32, SyscallPassthrough0<SYSCALL_DEF(getgid)>);
|
||||
- REGISTER_SYSCALL_IMPL_X32(geteuid32, SyscallPassthrough0<SYSCALL_DEF(geteuid)>);
|
||||
- REGISTER_SYSCALL_IMPL_X32(getegid32, SyscallPassthrough0<SYSCALL_DEF(getegid)>);
|
||||
- REGISTER_SYSCALL_IMPL_X32(setreuid32, SyscallPassthrough2<SYSCALL_DEF(setreuid)>);
|
||||
- REGISTER_SYSCALL_IMPL_X32(setregid32, SyscallPassthrough2<SYSCALL_DEF(setregid)>);
|
||||
- REGISTER_SYSCALL_IMPL_X32(getgroups32, SyscallPassthrough2<SYSCALL_DEF(getgroups)>);
|
||||
- REGISTER_SYSCALL_IMPL_X32(setgroups32, SyscallPassthrough2<SYSCALL_DEF(setgroups)>);
|
||||
- REGISTER_SYSCALL_IMPL_X32(fchown32, SyscallPassthrough3<SYSCALL_DEF(fchown)>);
|
||||
- REGISTER_SYSCALL_IMPL_X32(setresuid32, SyscallPassthrough3<SYSCALL_DEF(setresuid)>);
|
||||
- REGISTER_SYSCALL_IMPL_X32(getresuid32, SyscallPassthrough3<SYSCALL_DEF(getresuid)>);
|
||||
- REGISTER_SYSCALL_IMPL_X32(setresgid32, SyscallPassthrough3<SYSCALL_DEF(setresgid)>);
|
||||
- REGISTER_SYSCALL_IMPL_X32(getresgid32, SyscallPassthrough3<SYSCALL_DEF(getresgid)>);
|
||||
- REGISTER_SYSCALL_IMPL_X32(setuid32, SyscallPassthrough1<SYSCALL_DEF(setuid)>);
|
||||
- REGISTER_SYSCALL_IMPL_X32(setgid32, SyscallPassthrough1<SYSCALL_DEF(setgid)>);
|
||||
- REGISTER_SYSCALL_IMPL_X32(setfsuid32, SyscallPassthrough1<SYSCALL_DEF(setfsuid)>);
|
||||
- REGISTER_SYSCALL_IMPL_X32(setfsgid32, SyscallPassthrough1<SYSCALL_DEF(setfsgid)>);
|
||||
+ REGISTER_SYSCALL_IMPL_X32(getuid32, SyscallPathPassthrough0<SYSCALL_DEF(getuid)>);
|
||||
+ REGISTER_SYSCALL_IMPL_X32(getgid32, SyscallPathPassthrough0<SYSCALL_DEF(getgid)>);
|
||||
+ REGISTER_SYSCALL_IMPL_X32(geteuid32, SyscallPathPassthrough0<SYSCALL_DEF(geteuid)>);
|
||||
+ REGISTER_SYSCALL_IMPL_X32(getegid32, SyscallPathPassthrough0<SYSCALL_DEF(getegid)>);
|
||||
+ REGISTER_SYSCALL_IMPL_X32(setreuid32, SyscallPathPassthrough2<SYSCALL_DEF(setreuid)>);
|
||||
+ REGISTER_SYSCALL_IMPL_X32(setregid32, SyscallPathPassthrough2<SYSCALL_DEF(setregid)>);
|
||||
+ REGISTER_SYSCALL_IMPL_X32(getgroups32, SyscallPathPassthrough2<SYSCALL_DEF(getgroups)>);
|
||||
+ REGISTER_SYSCALL_IMPL_X32(setgroups32, SyscallPathPassthrough2<SYSCALL_DEF(setgroups)>);
|
||||
+ REGISTER_SYSCALL_IMPL_X32(fchown32, SyscallPathPassthrough3<SYSCALL_DEF(fchown)>);
|
||||
+ REGISTER_SYSCALL_IMPL_X32(setresuid32, SyscallPathPassthrough3<SYSCALL_DEF(setresuid)>);
|
||||
+ REGISTER_SYSCALL_IMPL_X32(getresuid32, SyscallPathPassthrough3<SYSCALL_DEF(getresuid)>);
|
||||
+ REGISTER_SYSCALL_IMPL_X32(setresgid32, SyscallPathPassthrough3<SYSCALL_DEF(setresgid)>);
|
||||
+ REGISTER_SYSCALL_IMPL_X32(getresgid32, SyscallPathPassthrough3<SYSCALL_DEF(getresgid)>);
|
||||
+ REGISTER_SYSCALL_IMPL_X32(setuid32, SyscallPathPassthrough1<SYSCALL_DEF(setuid)>);
|
||||
+ REGISTER_SYSCALL_IMPL_X32(setgid32, SyscallPathPassthrough1<SYSCALL_DEF(setgid)>);
|
||||
+ REGISTER_SYSCALL_IMPL_X32(setfsuid32, SyscallPathPassthrough1<SYSCALL_DEF(setfsuid)>);
|
||||
+ REGISTER_SYSCALL_IMPL_X32(setfsgid32, SyscallPathPassthrough1<SYSCALL_DEF(setfsgid)>);
|
||||
REGISTER_SYSCALL_IMPL_X32(sendfile64, SyscallPassthrough4<SYSCALL_DEF(sendfile)>);
|
||||
REGISTER_SYSCALL_IMPL_X32(clock_gettime64, SyscallPassthrough2<SYSCALL_DEF(clock_gettime)>);
|
||||
REGISTER_SYSCALL_IMPL_X32(clock_settime64, SyscallPassthrough2<SYSCALL_DEF(clock_settime)>);
|
||||
@@ -1,7 +1,6 @@
|
||||
#!/usr/bin/python3
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
|
||||
HOME = os.environ.get("HOME", "/root")
|
||||
SYSTEM_DIR = "/usr/share/applications"
|
||||
@@ -10,8 +9,6 @@ FLATPAK_DIR = os.path.join(HOME, ".local/share/flatpak/exports/share/application
|
||||
USER_DIR = os.path.join(HOME, ".local/share/applications")
|
||||
MARK = "X-DroidDeck-GPU=1"
|
||||
SKIP = re.compile(r"^(steam|droiddeck-game-|droiddeck-steam|steamdeck-)", re.I)
|
||||
CHROMIUM_ENV = "env -u WAYLAND_DISPLAY XDG_SESSION_TYPE=x11 ELECTRON_DISABLE_SANDBOX=1 "
|
||||
CHROMIUM_FLAGS = " --no-sandbox --ozone-platform=x11"
|
||||
|
||||
|
||||
def enabled():
|
||||
@@ -27,33 +24,6 @@ def main_group(text):
|
||||
return lines[:start + 1], lines[start + 1:end], lines[end:]
|
||||
|
||||
|
||||
def split_program(exec_line):
|
||||
if exec_line.startswith('"'):
|
||||
end = exec_line.find('"', 1)
|
||||
if end < 0:
|
||||
return None, None
|
||||
return exec_line[:end + 1], exec_line[end + 1:]
|
||||
program, _, rest = exec_line.partition(" ")
|
||||
return program, (" " + rest) if rest else ""
|
||||
|
||||
|
||||
def chromium(exec_line):
|
||||
program, _ = split_program(exec_line)
|
||||
if not program:
|
||||
return False
|
||||
program = program.strip('"')
|
||||
path = program if os.path.isabs(program) else shutil.which(program)
|
||||
if not path:
|
||||
return False
|
||||
here = os.path.dirname(os.path.realpath(path))
|
||||
return any(os.path.exists(os.path.join(d, "chrome-sandbox")) for d in (here, os.path.dirname(here)))
|
||||
|
||||
|
||||
def chromium_exec(exec_line):
|
||||
program, rest = split_program(exec_line)
|
||||
return CHROMIUM_ENV + program + CHROMIUM_FLAGS + rest
|
||||
|
||||
|
||||
def gpu_exec(exec_line):
|
||||
if exec_line.startswith("/usr/bin/flatpak run ") or exec_line.startswith("flatpak run "):
|
||||
exec_line = "/usr/local/bin/droiddeck-flatpak-run " + exec_line.split(" run ", 1)[1]
|
||||
@@ -75,24 +45,8 @@ def wrap(text, gpu_on=True):
|
||||
if not exec_line or exec_line.startswith("droiddeck-gpu "):
|
||||
return None
|
||||
cats = set(filter(None, keys.get("Categories", "").split(";")))
|
||||
gpu = gpu_on and bool(cats & {"Game", "Emulator"})
|
||||
browser = chromium(exec_line)
|
||||
if not gpu and not browser:
|
||||
if not (gpu_on and cats & {"Game", "Emulator"}):
|
||||
return None
|
||||
if browser:
|
||||
exec_line = chromium_exec(exec_line)
|
||||
if not gpu:
|
||||
def fix(lines):
|
||||
return ["Exec=" + chromium_exec(l[5:].strip()) if l.startswith("Exec=") and chromium(l[5:].strip()) else l
|
||||
for l in lines]
|
||||
out_group = fix(group)
|
||||
while out_group and not out_group[-1].strip():
|
||||
out_group.pop()
|
||||
out_group.append(MARK)
|
||||
out_rest = fix(rest)
|
||||
if out_rest and out_rest[0].strip():
|
||||
out_rest.insert(0, "")
|
||||
return "\n".join(head + out_group + out_rest) + "\n"
|
||||
out_group = []
|
||||
actions = keys.get("Actions", "")
|
||||
for l in group:
|
||||
@@ -111,8 +65,7 @@ def wrap(text, gpu_on=True):
|
||||
wrapped_rest = []
|
||||
for l in rest:
|
||||
if l.startswith("Exec=") and not l[5:].startswith("droiddeck-gpu "):
|
||||
action = l[5:].strip()
|
||||
l = "Exec=" + gpu_exec(chromium_exec(action) if chromium(action) else action)
|
||||
l = "Exec=" + gpu_exec(l[5:].strip())
|
||||
wrapped_rest.append(l)
|
||||
if wrapped_rest and wrapped_rest[0].strip():
|
||||
wrapped_rest.insert(0, "")
|
||||
|
||||
@@ -45,11 +45,20 @@ if [ "$qt" = wayland ] && [ -n "$wayland" ]; then
|
||||
elif [ "$qt" = xcb ] && [ -n "${DISPLAY:-}" ]; then
|
||||
export QT_QPA_PLATFORM=xcb
|
||||
fi
|
||||
arch=$(cat "$dir/arch" 2>/dev/null)
|
||||
if [ "$arch" = arm64 ]; then
|
||||
find -H "$APPDIR" -maxdepth 6 ! -type d \( -name libGL.so.1 -o -name libGLX.so.0 -o -name libEGL.so.1 -o -name libGLESv2.so.2 \
|
||||
-o -name libOpenGL.so.0 -o -name libGLdispatch.so.0 \) -print 2>/dev/null |
|
||||
while IFS= read -r lib; do
|
||||
kept=$dir/bundled-gl/${lib#"$APPDIR"/}
|
||||
mkdir -p "${kept%/*}" && mv -f "$lib" "$kept" && echo "== appimage: the session's ${lib##*/} replaces the bundled one"
|
||||
done
|
||||
fi
|
||||
fex=$(cat "$dir/fex" 2>/dev/null)
|
||||
case $fex in on|off) ;; *) fex=auto ;; esac
|
||||
run=("$APPDIR/AppRun")
|
||||
if [ -x /usr/local/bin/droiddeck-fex ]; then
|
||||
case $fex:$(cat "$dir/arch" 2>/dev/null) in
|
||||
case $fex:$arch in
|
||||
auto:x86_64|auto:i386) run=(/usr/local/bin/droiddeck-fex run --mode on -- "$APPDIR/AppRun") ;;
|
||||
auto:arm64) ;;
|
||||
*) run=(/usr/local/bin/droiddeck-fex run --mode "$fex" --for "$APPDIR" -- "$APPDIR/AppRun") ;;
|
||||
|
||||
@@ -51,7 +51,7 @@ PROVIDED = frozenset((
|
||||
"libssl.so.3", "libcrypto.so.3",
|
||||
"libfreetype.so.6", "libpng16.so.16", "libbrotlidec.so.1", "libbrotlicommon.so.1", "libbz2.so.1.0", "libz.so.1",
|
||||
"libwayland-client.so.0", "libwayland-egl.so.1", "libwayland-server.so.0", "libffi.so.8",
|
||||
"libgbm.so.1", "libdrm.so.2", "libexpat.so.1",
|
||||
"libgbm.so.1", "libdrm.so.2", "libexpat.so.1", "libOpenGL.so.0",
|
||||
))
|
||||
PROVIDED_NEEDS = {
|
||||
"libwayland-client.so.0": ("libffi.so.8",),
|
||||
@@ -670,6 +670,8 @@ def guest_environment(fex, env):
|
||||
result.setdefault("FEX_SILENTLOG", "0")
|
||||
result.setdefault("FEX_OUTPUTLOG", "stderr")
|
||||
result.pop("GLIBC_TUNABLES", None)
|
||||
if "aarch64" in result.get("GCONV_PATH", ""):
|
||||
result["GCONV_PATH"] = ""
|
||||
result.setdefault("GC_DISABLE_INCREMENTAL", "1")
|
||||
if fex["portable"]:
|
||||
result["FEX_PORTABLE"] = "1"
|
||||
|
||||
@@ -65,12 +65,14 @@ if [ -n "$repair" ]; then
|
||||
[ "$(sha1sum "$part" | cut -d' ' -f1)" = "$sum" ] || rm -f "$part"
|
||||
done
|
||||
fi
|
||||
cache_only=
|
||||
[ "${1:-}" = --cache ] && cache_only=1
|
||||
sync=
|
||||
if [ "${1:-}" = --sync ]; then
|
||||
case "${2:-}" in publicbeta|steamdeck_publicbeta) sync=$2 ;; *) sync=$steam_channel ;; esac
|
||||
manifest=steam_client_${sync}_linuxarm64
|
||||
fi
|
||||
[ -z "$sync" ] && [ -x "$steam_root/steamrtarm64/steam" ] && [ -f "$stamp" ] && exit 0
|
||||
[ -z "$sync" ] && [ -z "$cache_only" ] && [ -x "$steam_root/steamrtarm64/steam" ] && [ -f "$stamp" ] && exit 0
|
||||
|
||||
work=$(mktemp -d)
|
||||
trap 'rm -rf "$work"' EXIT
|
||||
@@ -167,6 +169,46 @@ if ! fetch_manifest; then
|
||||
fallback=1
|
||||
fetch_manifest || exit 1
|
||||
fi
|
||||
if [ -n "$cache_only" ]; then
|
||||
cache=$steam_root/package
|
||||
cached=$cache/droiddeck-cached
|
||||
[ "$(cat "$cached" 2>/dev/null)" = "$version" ] && exit 0
|
||||
awk -F'"' '
|
||||
/^\t"/ && NF >= 3 && $4 == "" { block = $2 }
|
||||
$2 == "file" { file[block] = $4 }
|
||||
$2 == "sha2" { sha[block] = $4 }
|
||||
$2 == "size" { size[block] = $4 }
|
||||
$2 == "zipvz" { vz[block] = $4 }
|
||||
$2 == "sha2vz" { vzsha[block] = $4 }
|
||||
END {
|
||||
for (b in file) {
|
||||
f = file[b]; h = sha[b]; n = size[b] + 0
|
||||
if (b in vz) { f = vz[b]; h = vzsha[b]; k = split(f, bits, "_"); n = bits[k] + 0 }
|
||||
print b, f, h, n
|
||||
}
|
||||
}
|
||||
' "$work/manifest" | sort > "$work/cache"
|
||||
mkdir -p "$cache"
|
||||
total=$(grep -c . "$work/cache" 2>/dev/null || echo 0)
|
||||
total_bytes=$(awk '{ n += $4 } END { print n + 0 }' "$work/cache")
|
||||
done_bytes=0
|
||||
i=0
|
||||
while read -r block file sum size; do
|
||||
i=$((i + 1))
|
||||
progress "$cache/$file" "$block"
|
||||
fetched=""
|
||||
for host in "${cdn_order[@]}"; do
|
||||
if fetch "$host/$file" "$cache/$file" "$size" "$sum" "$block"; then
|
||||
fetched=$host
|
||||
break
|
||||
fi
|
||||
done
|
||||
[ -n "$fetched" ] || { echo "droiddeck-steam-install: $file failed on every CDN" >&2; exit 1; }
|
||||
done_bytes=$((done_bytes + size))
|
||||
done < "$work/cache"
|
||||
echo "$version" > "$cached"
|
||||
exit 0
|
||||
fi
|
||||
if [ -n "$sync" ]; then
|
||||
installed=$(awk -F'"' '$2 == "version" { print $4; exit }' "$steam_root/package/$manifest.manifest" 2>/dev/null || true)
|
||||
if [ -x "$steam_root/steamrtarm64/steam" ] && [ "$installed" = "$version" ]; then
|
||||
|
||||
@@ -10,6 +10,7 @@ import tempfile
|
||||
DISPLAY = "External: gamescope|||Windowed"
|
||||
NATIVE_RESOLUTION = "EnableSteamNativeExternalResolution"
|
||||
SCREENSAVER_IN_GAME = ("Customization", "Screensaver", "WhileInGame")
|
||||
SCREENSAVER_CURRENT = ("Customization", "Screensaver", "CurrentScreensaver")
|
||||
TOKEN = re.compile(r'\s+|//[^\n]*|"(?:\\.|[^"\\])*"|[{}]')
|
||||
|
||||
|
||||
@@ -137,6 +138,10 @@ def seed_no_screensaver_in_game(text):
|
||||
return seed_value(text, SCREENSAVER_IN_GAME, '0')
|
||||
|
||||
|
||||
def seed_bouncing_logo(text):
|
||||
return seed_value(text, SCREENSAVER_CURRENT, 'steam-bouncinglogo')
|
||||
|
||||
|
||||
def atomic_write(path, text):
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
fd, temporary = tempfile.mkstemp(prefix='.' + path.name, dir=path.parent)
|
||||
@@ -179,6 +184,11 @@ def initialize_screensaver(steam_root):
|
||||
'== steam: no screensaver over a running game')
|
||||
|
||||
|
||||
def initialize_screensaver_choice(steam_root):
|
||||
return seed_once(steam_root, 'droiddeck-screensaver-choice-initialized', seed_bouncing_logo,
|
||||
'== steam: bouncing logo screensaver')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
status = 0
|
||||
try:
|
||||
@@ -186,7 +196,7 @@ if __name__ == '__main__':
|
||||
except (OSError, ValueError, RecursionError) as error:
|
||||
print('== steam: left UI scale unchanged: ' + str(error), file=sys.stderr)
|
||||
status = 1
|
||||
for what, step in (('native resolution', initialize_native_resolution), ('screensaver', initialize_screensaver)):
|
||||
for what, step in (('native resolution', initialize_native_resolution), ('screensaver', initialize_screensaver), ('screensaver choice', initialize_screensaver_choice)):
|
||||
try:
|
||||
step(sys.argv[1])
|
||||
except (OSError, ValueError, RecursionError) as error:
|
||||
|
||||
@@ -21,6 +21,29 @@ typedef int (*spawn_fn)(pid_t *, const char *, const posix_spawn_file_actions_t
|
||||
__attribute__((visibility("hidden")))
|
||||
char *const *dd_webhelper_argv(const char *path, char *const argv[], char *const envp[]);
|
||||
|
||||
__attribute__((visibility("hidden"))) int dd_program_lookup(const char *file, char *out, size_t size) {
|
||||
if (!file || !*file) return 0;
|
||||
if (strchr(file, '/')) return snprintf(out, size, "%s", file) < (int)size;
|
||||
const char *paths = getenv("PATH");
|
||||
if (!paths) paths = "/bin:/usr/bin";
|
||||
char candidate[PATH_MAX];
|
||||
int found = 0;
|
||||
for (const char *p = paths;; ) {
|
||||
const char *end = strchrnul(p, ':');
|
||||
int n = end > p ? snprintf(candidate, sizeof candidate, "%.*s/%s", (int)(end - p), p, file)
|
||||
: snprintf(candidate, sizeof candidate, "%s", file);
|
||||
struct stat st;
|
||||
if (n > 0 && n < (int)sizeof candidate && n < (int)size && stat(candidate, &st) == 0 && S_ISREG(st.st_mode)) {
|
||||
int runs = access(candidate, X_OK) == 0;
|
||||
if (runs || !found) memcpy(out, candidate, (size_t)n + 1);
|
||||
found = 1;
|
||||
if (runs) return 1;
|
||||
}
|
||||
if (!*end) return found;
|
||||
p = end + 1;
|
||||
}
|
||||
}
|
||||
|
||||
#if defined(__aarch64__) || defined(BINFMT_TEST)
|
||||
|
||||
static int flag(const char *name) {
|
||||
@@ -32,17 +55,26 @@ static int handing_off(void) {
|
||||
return flag("DD_DESKTOP") || flag("DD_BINFMT");
|
||||
}
|
||||
|
||||
static int appimage(int fd, const unsigned char *head, ssize_t n) {
|
||||
Elf64_Ehdr eh;
|
||||
if (n < (ssize_t)sizeof eh || head[EI_CLASS] != ELFCLASS64 || memcmp(head + EI_ABIVERSION, "AI\x02", 3)) return 0;
|
||||
memcpy(&eh, head, sizeof eh);
|
||||
char magic[6];
|
||||
off_t at = (off_t)eh.e_shoff + (off_t)eh.e_shentsize * eh.e_shnum;
|
||||
return pread(fd, magic, sizeof magic, at) == (ssize_t)sizeof magic && (!memcmp(magic, "hsqs", 4) || !memcmp(magic, "DWARFS", 6));
|
||||
}
|
||||
|
||||
static int foreign(const char *path, int error) {
|
||||
if (!path || !strcmp(path, BINFMT_HANDLER)) return 0;
|
||||
int fd = open(path, O_RDONLY | O_CLOEXEC);
|
||||
if (fd < 0) return 0;
|
||||
struct stat st;
|
||||
unsigned char head[20];
|
||||
unsigned char head[sizeof(Elf64_Ehdr)];
|
||||
ssize_t n = fstat(fd, &st) == 0 && S_ISREG(st.st_mode) ? read(fd, head, sizeof head) : -1;
|
||||
int kind = 0;
|
||||
if (n >= 20 && !memcmp(head, ELFMAG, SELFMAG)) {
|
||||
unsigned machine = head[EI_DATA] == ELFDATA2MSB ? (unsigned)head[18] << 8 | head[19] : head[18] | (unsigned)head[19] << 8;
|
||||
kind = machine == EM_X86_64 || machine == EM_386 || error == EACCES ? 1 : 0;
|
||||
kind = machine == EM_X86_64 || machine == EM_386 || appimage(fd, head, n) || error == EACCES ? 1 : 0;
|
||||
} else if (n >= 2 && head[0] == 'M' && head[1] == 'Z') {
|
||||
kind = 2;
|
||||
} else if (n >= 2 && head[0] == '#' && head[1] == '!' && error == EACCES) {
|
||||
@@ -58,21 +90,6 @@ static int wanted(const char *path, int error) {
|
||||
return (error == ENOEXEC || error == ENOENT || error == EACCES) && handing_off() && foreign(path, error);
|
||||
}
|
||||
|
||||
static int lookup(const char *file, char *out, size_t size) {
|
||||
if (!file || !*file) return 0;
|
||||
if (strchr(file, '/')) return snprintf(out, size, "%s", file) < (int)size;
|
||||
const char *paths = getenv("PATH");
|
||||
if (!paths) paths = "/bin:/usr/bin";
|
||||
for (const char *p = paths;; ) {
|
||||
const char *end = strchrnul(p, ':');
|
||||
int n = end > p ? snprintf(out, size, "%.*s/%s", (int)(end - p), p, file) : snprintf(out, size, "%s", file);
|
||||
struct stat st;
|
||||
if (n > 0 && n < (int)size && stat(out, &st) == 0 && S_ISREG(st.st_mode)) return 1;
|
||||
if (!*end) return 0;
|
||||
p = end + 1;
|
||||
}
|
||||
}
|
||||
|
||||
static int count(char *const argv[]) {
|
||||
int n = 0;
|
||||
while (argv && argv[n]) n++;
|
||||
@@ -117,12 +134,12 @@ __attribute__((visibility("hidden"))) int dd_binfmt_retry(const char *path, char
|
||||
|
||||
__attribute__((visibility("hidden"))) void dd_binfmt_before_search(const char *file, char *const argv[], char *const envp[]) {
|
||||
char path[PATH_MAX];
|
||||
if (handing_off() && lookup(file, path, sizeof path)) dd_binfmt_before(path, argv, envp);
|
||||
if (handing_off() && dd_program_lookup(file, path, sizeof path)) dd_binfmt_before(path, argv, envp);
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) int dd_binfmt_after_search(const char *file, char *const argv[], char *const envp[], int error) {
|
||||
char path[PATH_MAX];
|
||||
if (handing_off() && lookup(file, path, sizeof path)) return dd_binfmt_retry(path, argv, envp, error);
|
||||
if (handing_off() && dd_program_lookup(file, path, sizeof path)) return dd_binfmt_retry(path, argv, envp, error);
|
||||
errno = error;
|
||||
return -1;
|
||||
}
|
||||
@@ -144,7 +161,7 @@ __attribute__((visibility("hidden"))) int dd_binfmt_spawn(pid_t *pid, const char
|
||||
|
||||
int execvpe(const char *file, char *const argv[], char *const envp[]) {
|
||||
char resolved[PATH_MAX];
|
||||
const char *path = lookup(file, resolved, sizeof resolved) ? resolved : file;
|
||||
const char *path = dd_program_lookup(file, resolved, sizeof resolved) ? resolved : file;
|
||||
char *const *adjusted = dd_webhelper_argv(path, argv, envp);
|
||||
static int (*real)(const char *, char *const[], char *const[]);
|
||||
if (!real) real = (int (*)(const char *, char *const[], char *const[]))dlsym(RTLD_NEXT, "execvpe");
|
||||
@@ -156,7 +173,7 @@ int execvpe(const char *file, char *const argv[], char *const envp[]) {
|
||||
int posix_spawnp(pid_t *pid, const char *file, const posix_spawn_file_actions_t *fa, const posix_spawnattr_t *attr,
|
||||
char *const argv[], char *const envp[]) {
|
||||
char path[PATH_MAX];
|
||||
int found = lookup(file, path, sizeof path);
|
||||
int found = dd_program_lookup(file, path, sizeof path);
|
||||
char *const *adjusted = dd_webhelper_argv(found ? path : file, argv, envp);
|
||||
static spawn_fn real, spawn;
|
||||
if (!real) real = (spawn_fn)dlsym(RTLD_NEXT, "posix_spawnp");
|
||||
|
||||
@@ -277,6 +277,7 @@ __attribute__((visibility("hidden"))) void dd_binfmt_before_search(const char *f
|
||||
__attribute__((visibility("hidden"))) int dd_binfmt_after_search(const char *file, char *const argv[], char *const envp[], int error);
|
||||
__attribute__((visibility("hidden")))
|
||||
char *const *dd_webhelper_argv(const char *path, char *const argv[], char *const envp[]);
|
||||
__attribute__((visibility("hidden"))) int dd_program_lookup(const char *file, char *out, size_t size);
|
||||
__attribute__((visibility("hidden"))) int dd_binfmt_spawn(pid_t *pid, const char *path, const posix_spawn_file_actions_t *fa,
|
||||
const posix_spawnattr_t *attr, char *const argv[], char *const envp[],
|
||||
spawn_fn real);
|
||||
@@ -377,7 +378,8 @@ static int answer_lsof_via_spawn(const char *path, char *const argv[], pid_t *pi
|
||||
}
|
||||
|
||||
int execvp(const char *file, char *const argv_in[]) {
|
||||
char *const *argv = dd_webhelper_argv(file, argv_in, environ);
|
||||
char resolved[PATH_MAX];
|
||||
char *const *argv = dd_webhelper_argv(dd_program_lookup(file, resolved, sizeof resolved) ? resolved : file, argv_in, environ);
|
||||
static int (*real)(const char *, char *const[]);
|
||||
if (!real) real = (int (*)(const char *, char *const[]))dlsym(RTLD_NEXT, "execvp");
|
||||
maybe_answer_lsof(file, argv);
|
||||
|
||||
@@ -29,6 +29,8 @@
|
||||
#define VDEC_BITSTREAM_SIZE (4u << 20)
|
||||
#define VDEC_PADDING 64
|
||||
#define VDEC_DUMB 64
|
||||
#define VDEC_CAP_MIN_WIDTH 4096u
|
||||
#define VDEC_CAP_MIN_HEIGHT 2304u
|
||||
|
||||
struct vd_dma_heap_alloc {
|
||||
uint64_t len;
|
||||
@@ -135,6 +137,8 @@ struct vdec {
|
||||
uint32_t n_cap_done;
|
||||
int out_on, cap_on;
|
||||
int sock, hw, hw_failed;
|
||||
int resizing;
|
||||
uint32_t stream_w, stream_h;
|
||||
int64_t pts;
|
||||
void *ctx, *packet, *frame;
|
||||
uint8_t *packet_data;
|
||||
@@ -318,7 +322,8 @@ static int vd_open_hardware(struct vdec *v) {
|
||||
if (sock < 0) return -1;
|
||||
struct vdec_config c = {
|
||||
.type = VDEC_CONFIG, .codec = v->fourcc == V4L2_PIX_FMT_HEVC ? VENC_HEVC : VENC_H264,
|
||||
.width = v->width ? v->width : v->cap_width, .height = v->height ? v->height : v->cap_height,
|
||||
.width = v->stream_w ? v->stream_w : v->width ? v->width : v->cap_width,
|
||||
.height = v->stream_h ? v->stream_h : v->height ? v->height : v->cap_height,
|
||||
.stride = v->bpl, .rows = v->cap_height, .bitstreams = v->out_count, .bitstream_size = VDEC_BITSTREAM_SIZE,
|
||||
};
|
||||
struct vdec_result r;
|
||||
@@ -563,8 +568,12 @@ static int vd_set_format(struct vdec *v, struct v4l2_format *f, int apply) {
|
||||
t.fourcc = p->pixelformat;
|
||||
t.width = p->width;
|
||||
t.height = p->height;
|
||||
t.stream_w = p->width;
|
||||
t.stream_h = p->height;
|
||||
} else {
|
||||
uint32_t w = p->width > t.width ? p->width : t.width, h = p->height > t.height ? p->height : t.height;
|
||||
if (w < VDEC_CAP_MIN_WIDTH) w = VDEC_CAP_MIN_WIDTH;
|
||||
if (h < VDEC_CAP_MIN_HEIGHT) h = VDEC_CAP_MIN_HEIGHT;
|
||||
if (w < 16 || h < 16 || w > 8192 || h > 8192) return -EINVAL;
|
||||
t.cap_width = (w + 15) & ~15u;
|
||||
t.cap_height = (h + 15) & ~15u;
|
||||
@@ -574,6 +583,7 @@ static int vd_set_format(struct vdec *v, struct v4l2_format *f, int apply) {
|
||||
if (apply) {
|
||||
if (t.fourcc != v->fourcc || (t.hw && (t.bpl != v->bpl || t.cap_height != v->cap_height))) vd_close_decoder(&t);
|
||||
*v = t;
|
||||
if (v->cap_width >= v->width && v->cap_height >= v->height) v->resizing = 0;
|
||||
}
|
||||
vd_fill_format(&t, f);
|
||||
return 0;
|
||||
@@ -615,13 +625,184 @@ static int vd_querybuf(struct vdec *v, struct v4l2_buffer *b) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
struct vd_bits {
|
||||
const uint8_t *data;
|
||||
size_t size, pos;
|
||||
};
|
||||
|
||||
static uint32_t vd_get_bits(struct vd_bits *b, unsigned count) {
|
||||
uint32_t value = 0;
|
||||
while (count--) {
|
||||
size_t byte = b->pos >> 3;
|
||||
value = value << 1 | (byte < b->size ? (b->data[byte] >> (7 - (b->pos & 7))) & 1u : 0u);
|
||||
b->pos++;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
static uint32_t vd_get_ue(struct vd_bits *b) {
|
||||
unsigned zeros = 0;
|
||||
while (zeros < 32 && vd_get_bits(b, 1) == 0 && (b->pos >> 3) < b->size) zeros++;
|
||||
if (zeros >= 32) return 0;
|
||||
return ((1u << zeros) - 1) + (zeros ? vd_get_bits(b, zeros) : 0);
|
||||
}
|
||||
|
||||
static int32_t vd_get_se(struct vd_bits *b) {
|
||||
uint32_t k = vd_get_ue(b);
|
||||
return (k & 1) ? (int32_t)((k + 1) / 2) : -(int32_t)(k / 2);
|
||||
}
|
||||
|
||||
static int vd_skip_scaling_list(struct vd_bits *b, unsigned size) {
|
||||
int32_t last = 8, next = 8;
|
||||
for (unsigned i = 0; i < size; i++) {
|
||||
if (next != 0) {
|
||||
int32_t delta = vd_get_se(b);
|
||||
if (delta < -128 || delta > 127) return -1;
|
||||
next = (last + delta + 256) % 256;
|
||||
}
|
||||
last = next == 0 ? last : next;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* The coded size an H.264 SPS announces, rounded up to whole macroblocks, as a V4L2 decoder reports it. */
|
||||
static int vd_parse_sps_h264(const uint8_t *rbsp, size_t size, uint32_t *width, uint32_t *height) {
|
||||
uint8_t buf[512];
|
||||
size_t n = 0;
|
||||
for (size_t i = 0; i < size && n < sizeof buf; i++) {
|
||||
if (i >= 2 && rbsp[i] == 3 && rbsp[i - 1] == 0 && rbsp[i - 2] == 0) continue;
|
||||
buf[n++] = rbsp[i];
|
||||
}
|
||||
struct vd_bits b = { buf, n, 0 };
|
||||
uint32_t profile = vd_get_bits(&b, 8);
|
||||
vd_get_bits(&b, 16);
|
||||
vd_get_ue(&b);
|
||||
uint32_t chroma = 1;
|
||||
if (profile == 100 || profile == 110 || profile == 122 || profile == 244 || profile == 44 || profile == 83 ||
|
||||
profile == 86 || profile == 118 || profile == 128 || profile == 138 || profile == 139 || profile == 134 || profile == 135) {
|
||||
chroma = vd_get_ue(&b);
|
||||
if (chroma == 3) vd_get_bits(&b, 1);
|
||||
vd_get_ue(&b);
|
||||
vd_get_ue(&b);
|
||||
vd_get_bits(&b, 1);
|
||||
if (vd_get_bits(&b, 1)) {
|
||||
for (unsigned i = 0; i < (chroma != 3 ? 8u : 12u); i++)
|
||||
if (vd_get_bits(&b, 1) && vd_skip_scaling_list(&b, i < 6 ? 16 : 64) != 0) return -1;
|
||||
}
|
||||
}
|
||||
vd_get_ue(&b);
|
||||
uint32_t poc = vd_get_ue(&b);
|
||||
if (poc == 0) {
|
||||
vd_get_ue(&b);
|
||||
} else if (poc == 1) {
|
||||
vd_get_bits(&b, 1);
|
||||
vd_get_se(&b);
|
||||
vd_get_se(&b);
|
||||
uint32_t cycle = vd_get_ue(&b);
|
||||
for (uint32_t i = 0; i < cycle && i < 256; i++) vd_get_se(&b);
|
||||
}
|
||||
vd_get_ue(&b);
|
||||
vd_get_bits(&b, 1);
|
||||
uint32_t mbs_wide = vd_get_ue(&b) + 1, map_units_high = vd_get_ue(&b) + 1;
|
||||
if (b.pos > b.size * 8 || mbs_wide > 1024 || map_units_high > 1024) return -1;
|
||||
uint32_t frame_mbs_only = vd_get_bits(&b, 1);
|
||||
if (b.pos > b.size * 8) return -1;
|
||||
*width = mbs_wide * 16;
|
||||
*height = map_units_high * 16 * (2 - frame_mbs_only);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Finds the first SPS in an Annex B access unit; returns its size in the stream through the out parameters. */
|
||||
static int vd_stream_size_h264(const uint8_t *data, size_t size, uint32_t *width, uint32_t *height) {
|
||||
for (size_t i = 0; i + 4 < size; i++) {
|
||||
if (data[i] != 0 || data[i + 1] != 0 || data[i + 2] != 1 || (data[i + 3] & 0x1f) != 7) continue;
|
||||
size_t start = i + 4, end = start;
|
||||
while (end + 2 < size && !(data[end] == 0 && data[end + 1] == 0 && (data[end + 2] == 1 || data[end + 2] == 0))) end++;
|
||||
if (end + 2 >= size) end = size;
|
||||
return vd_parse_sps_h264(data + start, end - start, width, height);
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* The same for an H.265 SPS: the luma size in samples, rounded up to 16 as the client asks for it. */
|
||||
static int vd_parse_sps_h265(const uint8_t *rbsp, size_t size, uint32_t *width, uint32_t *height) {
|
||||
uint8_t buf[512];
|
||||
size_t n = 0;
|
||||
for (size_t i = 0; i < size && n < sizeof buf; i++) {
|
||||
if (i >= 2 && rbsp[i] == 3 && rbsp[i - 1] == 0 && rbsp[i - 2] == 0) continue;
|
||||
buf[n++] = rbsp[i];
|
||||
}
|
||||
struct vd_bits b = { buf, n, 0 };
|
||||
vd_get_bits(&b, 4);
|
||||
uint32_t sub_layers = vd_get_bits(&b, 3);
|
||||
vd_get_bits(&b, 1);
|
||||
for (unsigned i = 0; i < 88; i += 8) vd_get_bits(&b, 8);
|
||||
vd_get_bits(&b, 8);
|
||||
uint32_t profile_present = 0, level_present = 0;
|
||||
for (uint32_t i = 0; i < sub_layers && i < 8; i++) {
|
||||
profile_present |= vd_get_bits(&b, 1) << i;
|
||||
level_present |= vd_get_bits(&b, 1) << i;
|
||||
}
|
||||
if (sub_layers > 0) for (uint32_t i = sub_layers; i < 8; i++) vd_get_bits(&b, 2);
|
||||
for (uint32_t i = 0; i < sub_layers && i < 8; i++) {
|
||||
if (profile_present >> i & 1) for (unsigned k = 0; k < 88; k += 8) vd_get_bits(&b, 8);
|
||||
if (level_present >> i & 1) vd_get_bits(&b, 8);
|
||||
}
|
||||
vd_get_ue(&b);
|
||||
if (vd_get_ue(&b) == 3) vd_get_bits(&b, 1);
|
||||
uint32_t w = vd_get_ue(&b), h = vd_get_ue(&b);
|
||||
if (b.pos > b.size * 8 || w < 16 || h < 16 || w > 16384 || h > 16384) return -1;
|
||||
*width = (w + 15) & ~15u;
|
||||
*height = (h + 15) & ~15u;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int vd_stream_size_h265(const uint8_t *data, size_t size, uint32_t *width, uint32_t *height) {
|
||||
for (size_t i = 0; i + 5 < size; i++) {
|
||||
if (data[i] != 0 || data[i + 1] != 0 || data[i + 2] != 1 || ((data[i + 3] >> 1) & 0x3f) != 33) continue;
|
||||
size_t start = i + 5, end = start;
|
||||
while (end + 2 < size && !(data[end] == 0 && data[end + 1] == 0 && (data[end + 2] == 1 || data[end + 2] == 0))) end++;
|
||||
if (end + 2 >= size) end = size;
|
||||
return vd_parse_sps_h265(data + start, end - start, width, height);
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/*
|
||||
* A stream can change its picture size without telling the client: the host switches games or the window
|
||||
* becomes fullscreen. A V4L2 decoder reports the new size through the format of its bitstream queue, which
|
||||
* the client polls; the capture buffers it already allocated stay at the old size until it reconfigures.
|
||||
*/
|
||||
static int vd_follow_stream_size(struct vdec *v, const uint8_t *data, size_t size) {
|
||||
uint32_t width, height;
|
||||
int found = v->fourcc == V4L2_PIX_FMT_HEVC ? vd_stream_size_h265(data, size, &width, &height)
|
||||
: vd_stream_size_h264(data, size, &width, &height);
|
||||
if (found != 0) return 0;
|
||||
uint32_t known_w = v->stream_w ? v->stream_w : v->width, known_h = v->stream_h ? v->stream_h : v->height;
|
||||
if (width == known_w && height == known_h) return 0;
|
||||
vd_log("the stream is now %ux%u, was %ux%u", width, height, known_w, known_h);
|
||||
if (width <= v->cap_width && height <= v->cap_height) {
|
||||
/* The client's capture buffers already hold the new size, so only the app decoder is reopened for it. */
|
||||
v->stream_w = width;
|
||||
v->stream_h = height;
|
||||
if (v->hw) vd_close_decoder(v);
|
||||
return 1;
|
||||
}
|
||||
v->width = v->stream_w = width;
|
||||
v->height = v->stream_h = height;
|
||||
v->resizing = 1;
|
||||
v->n_cap_done = 0;
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int vd_qbuf(struct vdec *v, struct v4l2_buffer *b) {
|
||||
if (b->m.planes == NULL || b->length < 1) return -EINVAL;
|
||||
if (b->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) {
|
||||
if (b->index >= v->out_count || v->n_out_done >= VDEC_BUFFERS) return -EINVAL;
|
||||
uint32_t bytes = b->m.planes[0].bytesused;
|
||||
if (bytes > VDEC_BITSTREAM_SIZE) bytes = VDEC_BITSTREAM_SIZE;
|
||||
if (v->out_on && bytes) vd_decode(v, b->index, bytes, b->timestamp);
|
||||
if (v->out_on && v->bitstream && bytes) vd_follow_stream_size(v, v->bitstream + (size_t)b->index * VDEC_BITSTREAM_SIZE, bytes);
|
||||
if (v->out_on && bytes && !v->resizing) vd_decode(v, b->index, bytes, b->timestamp);
|
||||
v->out_done[v->n_out_done++] = b->index;
|
||||
} else if (b->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) {
|
||||
if (b->index >= v->cap_count || v->cap_size == 0) return -EINVAL;
|
||||
@@ -652,9 +833,15 @@ static int vd_dqbuf(struct vdec *v, struct v4l2_buffer *b) {
|
||||
return 0;
|
||||
}
|
||||
if (b->type != V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) return -EINVAL;
|
||||
if (v->n_cap_done == 0) return -EAGAIN;
|
||||
struct vd_done d = v->cap_done[0];
|
||||
memmove(v->cap_done, v->cap_done + 1, --v->n_cap_done * sizeof d);
|
||||
struct vd_done d;
|
||||
for (;;) {
|
||||
if (v->n_cap_done == 0) return -EAGAIN;
|
||||
d = v->cap_done[0];
|
||||
memmove(v->cap_done, v->cap_done + 1, --v->n_cap_done * sizeof d);
|
||||
struct stat st;
|
||||
struct vd_capture *c = &v->cap[d.index];
|
||||
if (c->map && c->fd >= 0 && fstat(c->fd, &st) == 0 && st.st_ino == c->ino) break;
|
||||
}
|
||||
b->index = d.index;
|
||||
b->memory = V4L2_MEMORY_DMABUF;
|
||||
b->flags = V4L2_BUF_FLAG_DONE | V4L2_BUF_FLAG_TIMESTAMP_COPY;
|
||||
|
||||
@@ -26,40 +26,83 @@ static char *join_features(const char *have, const char *add) {
|
||||
return strcat(out, add);
|
||||
}
|
||||
|
||||
static int electron_node_mode(char *const envp[]) {
|
||||
static const char variable[] = "ELECTRON_RUN_AS_NODE=";
|
||||
static const char *env_value(char *const envp[], const char *variable) {
|
||||
size_t n = strlen(variable);
|
||||
for (int i = 0; envp && envp[i]; i++)
|
||||
if (!strncmp(envp[i], variable, sizeof variable - 1))
|
||||
return envp[i][sizeof variable - 1] != 0;
|
||||
return 0;
|
||||
if (!strncmp(envp[i], variable, n) && envp[i][n] == '=') return envp[i] + n + 1;
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static char *const *chromium_argv(const char *path, char *const argv[]) {
|
||||
const char *slash = path ? strrchr(path, '/') : NULL;
|
||||
if (!slash || !argv || !argv[0]) return argv;
|
||||
int argc = 0;
|
||||
for (; argv[argc]; argc++)
|
||||
if (argc && (!strncmp(argv[argc], "--type=", 7) || !strcmp(argv[argc], "--no-sandbox"))) return argv;
|
||||
size_t dir = (size_t)(slash - path) + 1;
|
||||
char *sandbox = malloc(dir + sizeof "chrome-sandbox");
|
||||
if (!sandbox) return argv;
|
||||
memcpy(sandbox, path, dir);
|
||||
strcpy(sandbox + dir, "chrome-sandbox");
|
||||
int chromium = access(sandbox, F_OK) == 0;
|
||||
free(sandbox);
|
||||
if (!chromium) return argv;
|
||||
char **out = calloc((size_t)argc + 2, sizeof *out);
|
||||
static int electron_node_mode(char *const envp[]) {
|
||||
const char *mode = env_value(envp, "ELECTRON_RUN_AS_NODE");
|
||||
return mode && *mode;
|
||||
}
|
||||
|
||||
static int beside_chrome_sandbox(const char *path) {
|
||||
char *real = realpath(path, NULL);
|
||||
if (!real) return 0;
|
||||
int found = 0;
|
||||
for (int up = 0; up < 2 && !found; up++) {
|
||||
char *slash = strrchr(real, '/');
|
||||
if (!slash) break;
|
||||
*slash = 0;
|
||||
size_t dir = strlen(real);
|
||||
char *sandbox = malloc(dir + sizeof "/chrome-sandbox");
|
||||
if (!sandbox) break;
|
||||
memcpy(sandbox, real, dir);
|
||||
strcpy(sandbox + dir, "/chrome-sandbox");
|
||||
found = access(sandbox, F_OK) == 0;
|
||||
free(sandbox);
|
||||
}
|
||||
free(real);
|
||||
return found;
|
||||
}
|
||||
|
||||
static char *folder_of(const char *path) {
|
||||
char *real = realpath(path, NULL);
|
||||
char *slash = real ? strrchr(real, '/') : NULL;
|
||||
if (slash) *slash = 0;
|
||||
return real;
|
||||
}
|
||||
|
||||
static int started_by_its_own_app(const char *path) {
|
||||
char self[4096];
|
||||
ssize_t n = readlink("/proc/self/exe", self, sizeof self - 1);
|
||||
if (n <= 0) return 0;
|
||||
self[n] = 0;
|
||||
char *mine = folder_of(self), *theirs = folder_of(path);
|
||||
int same = mine && theirs && !strcmp(mine, theirs) && beside_chrome_sandbox(self);
|
||||
free(mine);
|
||||
free(theirs);
|
||||
return same;
|
||||
}
|
||||
|
||||
static char *const *chromium_argv(const char *path, char *const argv[], char *const envp[]) {
|
||||
if (!path || !argv || !argv[0]) return argv;
|
||||
int argc = 0, sandbox = 1, ozone = 0;
|
||||
for (; argv[argc]; argc++) {
|
||||
if (!argc) continue;
|
||||
if (!strncmp(argv[argc], "--type=", 7)) return argv;
|
||||
if (!strcmp(argv[argc], "--no-sandbox")) sandbox = 0;
|
||||
if (!strncmp(argv[argc], "--ozone-platform=", 17)) ozone = 1;
|
||||
}
|
||||
const char *display = env_value(envp, "DISPLAY");
|
||||
int x11 = !ozone && display && *display;
|
||||
if ((!sandbox && !x11) || !beside_chrome_sandbox(path) || started_by_its_own_app(path)) return argv;
|
||||
char **out = calloc((size_t)argc + 3, sizeof *out);
|
||||
if (!out) return argv;
|
||||
out[0] = argv[0];
|
||||
out[1] = (char *)"--no-sandbox";
|
||||
for (int i = 1; i < argc; i++) out[i + 1] = argv[i];
|
||||
int n = 0;
|
||||
out[n++] = argv[0];
|
||||
if (sandbox) out[n++] = (char *)"--no-sandbox";
|
||||
if (x11) out[n++] = (char *)"--ozone-platform=x11";
|
||||
for (int i = 1; i < argc; i++) out[n++] = argv[i];
|
||||
return out;
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden")))
|
||||
char *const *dd_webhelper_argv(const char *path, char *const argv[], char *const envp[]) {
|
||||
if (electron_node_mode(envp)) return argv;
|
||||
if (!is_webhelper_browser(path, argv)) return chromium_argv(path, argv);
|
||||
if (!is_webhelper_browser(path, argv)) return chromium_argv(path, argv, envp);
|
||||
const char *spec = getenv("DD_WEBHELPER_ARGS");
|
||||
if (!spec || !*spec) spec = WEBHELPER_DEFAULT;
|
||||
if (!strcmp(spec, "stock")) return argv;
|
||||
|
||||
@@ -41,6 +41,7 @@
|
||||
#include <elf.h>
|
||||
#include <sys/sendfile.h>
|
||||
#include <sys/mman.h>
|
||||
#include <semaphore.h>
|
||||
#include <sched.h>
|
||||
#include <time.h>
|
||||
#include <sys/xattr.h>
|
||||
|
||||
@@ -476,7 +476,7 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e
|
||||
return -1;
|
||||
}
|
||||
int ret;
|
||||
if (is_host_interpreter(rewritten_interp)) {
|
||||
if (is_host_interpreter(interp, rewritten_interp)) {
|
||||
char **sys_env = clean_env_for_system(envp);
|
||||
ret = run_execve(orig_execve, rewritten_interp, new_argv, sys_env);
|
||||
int saved_errno = errno;
|
||||
@@ -829,7 +829,7 @@ static int spawn_script(pid_t *pid, const char *script, struct exec_probe *probe
|
||||
char **new_argv = build_script_argv(rewritten_interp, interp_arg, script, argv);
|
||||
if (!new_argv) return ENOMEM;
|
||||
int ret;
|
||||
if (is_host_interpreter(rewritten_interp)) {
|
||||
if (is_host_interpreter(interp, rewritten_interp)) {
|
||||
orig_posix_spawn_f_type orig_posix_spawn = real_posix_spawn();
|
||||
char **sys_env = clean_env_for_system(envp);
|
||||
ret = orig_posix_spawn ? orig_posix_spawn(pid, rewritten_interp, file_actions, attrp, new_argv, sys_env) : ENOSYS;
|
||||
|
||||
@@ -10,6 +10,13 @@
|
||||
// PT_INTERP) literally and failed with "bad interpreter: No such file or directory".
|
||||
// getcwd() is not virtualised, so cwd + path is a real path that starts with DDNATV_ROOT.
|
||||
static const char *absolutize_exec_path(const char *path, char *buffer, size_t bufsize) {
|
||||
if (is_proc_self_exe(path)) {
|
||||
ssize_t n = handle_proc_self_exe(buffer, bufsize - 1);
|
||||
if (n > 0 && buffer[0] == '/') {
|
||||
buffer[n] = '\0';
|
||||
return buffer;
|
||||
}
|
||||
}
|
||||
if (!path || path[0] == '\0' || path[0] == '/') return path;
|
||||
char cwd[PATH_MAX];
|
||||
static char *(*real_getcwd)(char *, size_t) = NULL;
|
||||
@@ -966,10 +973,14 @@ static void parse_shebang(char *hdr, char **interp, char **interp_arg) {
|
||||
*interp_arg = arg;
|
||||
}
|
||||
|
||||
// Interpreters outside the rootfs (Android's /system/bin/sh) run with Android's environment.
|
||||
static int is_host_interpreter(const char *interp) {
|
||||
return strncmp(interp, "/system", 7) == 0 ||
|
||||
(g_ddnatv_root[0] != '\0' && strncmp(interp, g_ddnatv_root, g_ddnatv_root_len) != 0);
|
||||
// Interpreters outside the rootfs and its binds (Android's /system/bin/sh) run with Android's environment.
|
||||
static int is_host_interpreter(const char *interp, const char *rewritten) {
|
||||
if (strncmp(rewritten, "/system", 7) == 0) return 1;
|
||||
if (g_ddnatv_root[0] == '\0' || get_rootfs_subpath(rewritten)) return 0;
|
||||
if (!is_mapped_guest_path(interp)) return 1;
|
||||
struct exec_probe probe;
|
||||
probe_exec_file(rewritten, &probe);
|
||||
return probe.android_interp;
|
||||
}
|
||||
|
||||
// argv for running `script` with its interpreter: interp [arg] script args... (the script's own
|
||||
|
||||
@@ -21,7 +21,7 @@ int setresuid(uid_t ruid, uid_t euid, uid_t suid) { (void)ruid; (void)euid; (voi
|
||||
int setresgid(gid_t rgid, gid_t egid, gid_t sgid) { (void)rgid; (void)egid; (void)sgid; return 0; }
|
||||
|
||||
int getgroups(int size, gid_t list[]) {
|
||||
if (size > 0 && list != NULL) list[0] = 0;
|
||||
if (size > 0 && list != NULL && syscall(__NR_getresgid, list, list, list) != 0) return -1;
|
||||
return 1;
|
||||
}
|
||||
// What programs built with _FORTIFY_SOURCE call when the buffer's size is known (the check is
|
||||
|
||||
@@ -82,7 +82,7 @@ static void ddnatv_load_binds(const char *spec) {
|
||||
char kernel_src[PATH_MAX];
|
||||
if (strcmp(src, dst) != 0) {
|
||||
ddnatv_kernel_path(src, strlen(src), kernel_src, sizeof(kernel_src));
|
||||
src = kernel_src;
|
||||
if (strncmp(kernel_src, "/proc/", 6) != 0 || kernel_src[6] < '0' || kernel_src[6] > '9') src = kernel_src;
|
||||
}
|
||||
b->src = strdup(src);
|
||||
b->dst = strdup(dst);
|
||||
@@ -188,6 +188,25 @@ static __thread int t_bind_link_depth = 0;
|
||||
|
||||
static void normalize_path(char *path);
|
||||
|
||||
static int climbs_past_root(const char *dir, const char *target) {
|
||||
long depth = 0;
|
||||
for (const char *p = dir; *p; p++)
|
||||
if (*p != '/' && (p == dir || p[-1] == '/')) depth++;
|
||||
for (const char *p = target; *p;) {
|
||||
while (*p == '/') p++;
|
||||
const char *end = p;
|
||||
while (*end && *end != '/') end++;
|
||||
size_t len = (size_t)(end - p);
|
||||
if (len == 2 && p[0] == '.' && p[1] == '.') {
|
||||
if (--depth < 0) return 1;
|
||||
} else if (len > 0 && !(len == 1 && p[0] == '.')) {
|
||||
depth++;
|
||||
}
|
||||
p = end;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
#if defined(__aarch64__)
|
||||
static long raw_link_dir(const char *link, char *out, size_t size) {
|
||||
const char *slash = strrchr(link, '/');
|
||||
@@ -215,25 +234,6 @@ static long raw_link_dir(const char *link, char *out, size_t size) {
|
||||
return n;
|
||||
}
|
||||
|
||||
static int climbs_past_root(const char *dir, const char *target) {
|
||||
long depth = 0;
|
||||
for (const char *p = dir; *p; p++)
|
||||
if (*p != '/' && (p == dir || p[-1] == '/')) depth++;
|
||||
for (const char *p = target; *p;) {
|
||||
while (*p == '/') p++;
|
||||
const char *end = p;
|
||||
while (*end && *end != '/') end++;
|
||||
size_t len = (size_t)(end - p);
|
||||
if (len == 2 && p[0] == '.' && p[1] == '.') {
|
||||
if (--depth < 0) return 1;
|
||||
} else if (len > 0 && !(len == 1 && p[0] == '.')) {
|
||||
depth++;
|
||||
}
|
||||
p = end;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static size_t guest_path_of_mount_source(char *buf, size_t len, size_t cap, int *converted);
|
||||
|
||||
static const char *guest_path_of_host_dir(const char *dir, char *out, size_t size) {
|
||||
@@ -335,6 +335,15 @@ static const char *resolve_drive_links(const char *host, char *buffer, size_t bu
|
||||
|
||||
// Maps an absolute Ubuntu path into the rootfs. Returns `path` (possibly advanced past
|
||||
// redundant leading "/" and "/." components) when it needs no change, else `buffer`.
|
||||
static const char *rewrite_normalized_in_root(const char *path, char *buffer, size_t bufsize) {
|
||||
char normalized[PATH_MAX];
|
||||
ddnatv_copy_cstr(normalized, sizeof(normalized), path);
|
||||
normalize_path(normalized);
|
||||
const char *mapped = rewrite_path_in_root(normalized, buffer, bufsize);
|
||||
if (mapped != buffer) ddnatv_copy_cstr(buffer, bufsize, mapped);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
static const char *rewrite_path_in_root(const char *path, char *buffer, size_t bufsize) {
|
||||
if (!path) return NULL;
|
||||
if (path[0] != '/' || g_ddnatv_root_len == 0) return path;
|
||||
@@ -354,6 +363,8 @@ static const char *rewrite_path_in_root(const char *path, char *buffer, size_t b
|
||||
}
|
||||
}
|
||||
|
||||
if (strstr(path, "/..") && climbs_past_root("", path)) return rewrite_normalized_in_root(path, buffer, bufsize);
|
||||
|
||||
// Root directory
|
||||
if (path[1] == '\0') {
|
||||
ddnatv_append(buffer, bufsize, 0, g_ddnatv_root, g_ddnatv_root_len);
|
||||
@@ -364,6 +375,8 @@ static const char *rewrite_path_in_root(const char *path, char *buffer, size_t b
|
||||
const struct ddnatv_bind *b = &g_binds[i];
|
||||
if (path[1] == b->dst[1] && is_path_prefix(path, b->dst, b->dst_len)) {
|
||||
if (b->identity) return path;
|
||||
if (strstr(path + b->dst_len, "/..") && climbs_past_root("", path + b->dst_len))
|
||||
return rewrite_normalized_in_root(path, buffer, bufsize);
|
||||
size_t n = ddnatv_append(buffer, bufsize, 0, b->src, b->src_len);
|
||||
ddnatv_append(buffer, bufsize, n, path + b->dst_len, strlen(path + b->dst_len));
|
||||
return resolve_bind_links(buffer, b->src_len, buffer, bufsize);
|
||||
@@ -806,10 +819,36 @@ static void ddnatv_build_at_dirs(void) {
|
||||
}
|
||||
}
|
||||
|
||||
#if defined(__aarch64__)
|
||||
static const char *map_parent_walk(int dirfd, const char *rel, char *buf, size_t size) {
|
||||
char link[32], host[PATH_MAX], dir_buf[PATH_MAX], guest[PATH_MAX];
|
||||
if (dirfd == AT_FDCWD) ddnatv_copy_cstr(link, sizeof(link), "/proc/self/cwd");
|
||||
else snprintf(link, sizeof(link), "/proc/self/fd/%d", dirfd);
|
||||
long n = raw_readlinkat(AT_FDCWD, link, host, sizeof(host) - 1);
|
||||
if (n <= 0 || host[0] != '/') return NULL;
|
||||
host[n] = '\0';
|
||||
const char *dir = guest_path_of_host_dir(host, dir_buf, sizeof(dir_buf));
|
||||
if (!dir || strcmp(dir, host) == 0) return NULL;
|
||||
if (get_rootfs_subpath(host) && !climbs_past_root(dir, rel)) return NULL;
|
||||
size_t used = ddnatv_append(guest, sizeof(guest), 0, dir, strlen(dir));
|
||||
used = ddnatv_append(guest, sizeof(guest), used, "/", 1);
|
||||
used = ddnatv_append(guest, sizeof(guest), used, rel, strlen(rel));
|
||||
if (used + 1 >= sizeof(guest)) return NULL;
|
||||
const char *mapped = rewrite_path_in_root(guest, buf, size);
|
||||
if (mapped != buf) ddnatv_copy_cstr(buf, size, mapped);
|
||||
return buf;
|
||||
}
|
||||
#endif
|
||||
|
||||
// The absolute host path for `rel` given relative to `dirfd`, or NULL when the call needs no change.
|
||||
static const char *map_at(int dirfd, const char *rel, char *buf, size_t size) {
|
||||
#if defined(__aarch64__)
|
||||
if (dirfd == AT_FDCWD || !rel || rel[0] == '\0' || rel[0] == '/' || g_nbinds == 0) return NULL;
|
||||
if (!rel || rel[0] == '\0' || rel[0] == '/') return NULL;
|
||||
if (strstr(rel, "..")) {
|
||||
const char *walked = map_parent_walk(dirfd, rel, buf, size);
|
||||
if (walked || dirfd == AT_FDCWD) return walked;
|
||||
}
|
||||
if (dirfd == AT_FDCWD || g_nbinds == 0) return NULL;
|
||||
pthread_once(&g_at_once, ddnatv_build_at_dirs);
|
||||
if (g_n_at_dirs == 0) return NULL;
|
||||
struct stat st;
|
||||
@@ -818,6 +857,7 @@ static const char *map_at(int dirfd, const char *rel, char *buf, size_t size) {
|
||||
if (g_at_dirs[i].ino != (unsigned long)st.st_ino || g_at_dirs[i].dev != (unsigned long)st.st_dev) continue;
|
||||
char guest[PATH_MAX];
|
||||
const char *base = g_at_dirs[i].guest;
|
||||
if (base[1] && climbs_past_root(base, rel)) return NULL;
|
||||
size_t used = ddnatv_append(guest, sizeof(guest), 0, base, strlen(base));
|
||||
if (used > 1) used = ddnatv_append(guest, sizeof(guest), used, "/", 1);
|
||||
ddnatv_append(guest, sizeof(guest), used, rel, strlen(rel));
|
||||
|
||||
@@ -1,32 +1,148 @@
|
||||
// Part of libddnatv-hook.so, included by ddnatv-hook.c.
|
||||
//
|
||||
// shm_open() and shm_unlink() of glibc open /dev/shm/NAME with a system call of their own, which
|
||||
// the path hooks never see and Android has no /dev/shm for. They go through open() and unlink()
|
||||
// here, which map /dev/shm.
|
||||
// shm_open(), shm_unlink() and the named semaphores of glibc open /dev/shm/NAME with system calls
|
||||
// of their own, which the path hooks never see and Android has no /dev/shm for. They go through
|
||||
// open(), renameat2() and unlink() here, which map /dev/shm.
|
||||
|
||||
#ifndef DDNATV_HOST_TEST
|
||||
|
||||
static int posix_shm_path(const char *name, char *path, size_t size) {
|
||||
static int posix_shm_path(const char *name, const char *prefix, char *path, size_t size) {
|
||||
if (!name) { errno = EINVAL; return -1; }
|
||||
while (*name == '/') name++;
|
||||
size_t len = strlen(name);
|
||||
if (len == 0 || len > NAME_MAX || strchr(name, '/') || strcmp(name, ".") == 0 || strcmp(name, "..") == 0) {
|
||||
size_t len = strlen(name) + strlen(prefix);
|
||||
if (len == strlen(prefix) || len > NAME_MAX || strchr(name, '/') || strcmp(name, ".") == 0 || strcmp(name, "..") == 0) {
|
||||
errno = len > NAME_MAX ? ENAMETOOLONG : EINVAL;
|
||||
return -1;
|
||||
}
|
||||
if (snprintf(path, size, "/dev/shm/%s", name) >= (int)size) { errno = ENAMETOOLONG; return -1; }
|
||||
if (snprintf(path, size, "/dev/shm/%s%s", prefix, name) >= (int)size) { errno = ENAMETOOLONG; return -1; }
|
||||
return 0;
|
||||
}
|
||||
|
||||
int shm_open(const char *name, int oflag, mode_t mode) {
|
||||
char path[PATH_MAX];
|
||||
if (posix_shm_path(name, path, sizeof(path)) < 0) return -1;
|
||||
if (posix_shm_path(name, "", path, sizeof(path)) < 0) return -1;
|
||||
return open(path, (oflag & (O_ACCMODE | O_CREAT | O_EXCL | O_TRUNC)) | O_NOFOLLOW | O_CLOEXEC, mode);
|
||||
}
|
||||
|
||||
int shm_unlink(const char *name) {
|
||||
char path[PATH_MAX];
|
||||
if (posix_shm_path(name, path, sizeof(path)) < 0) return -1;
|
||||
if (posix_shm_path(name, "", path, sizeof(path)) < 0) return -1;
|
||||
return unlink(path);
|
||||
}
|
||||
|
||||
struct posix_sem {
|
||||
dev_t dev;
|
||||
ino_t ino;
|
||||
sem_t *addr;
|
||||
unsigned int refs;
|
||||
struct posix_sem *next;
|
||||
};
|
||||
static struct posix_sem *g_posix_sems;
|
||||
static pthread_mutex_t g_posix_sems_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
|
||||
static void posix_sems_unlock(void) { pthread_mutex_unlock(&g_posix_sems_lock); }
|
||||
|
||||
static void posix_sems_hold(void) { pthread_mutex_lock(&g_posix_sems_lock); }
|
||||
|
||||
__attribute__((constructor)) static void posix_sems_across_fork(void) {
|
||||
pthread_atfork(posix_sems_hold, posix_sems_unlock, posix_sems_unlock);
|
||||
}
|
||||
|
||||
static void close_keeping_errno(int fd) {
|
||||
int saved = errno;
|
||||
close(fd);
|
||||
errno = saved;
|
||||
}
|
||||
|
||||
static sem_t *posix_sem_map(int fd) {
|
||||
struct stat st;
|
||||
if (fstat(fd, &st) < 0) return SEM_FAILED;
|
||||
sem_t *sem = SEM_FAILED;
|
||||
posix_sems_hold();
|
||||
struct posix_sem *e = g_posix_sems;
|
||||
while (e && (e->dev != st.st_dev || e->ino != st.st_ino)) e = e->next;
|
||||
if (e) {
|
||||
e->refs++;
|
||||
sem = e->addr;
|
||||
} else {
|
||||
void *addr = mmap(NULL, sizeof(sem_t), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
|
||||
e = addr == MAP_FAILED ? NULL : malloc(sizeof(*e));
|
||||
if (e) {
|
||||
*e = (struct posix_sem){st.st_dev, st.st_ino, addr, 1, g_posix_sems};
|
||||
g_posix_sems = e;
|
||||
sem = addr;
|
||||
} else if (addr != MAP_FAILED) {
|
||||
munmap(addr, sizeof(sem_t));
|
||||
errno = ENOMEM;
|
||||
}
|
||||
}
|
||||
posix_sems_unlock();
|
||||
return sem;
|
||||
}
|
||||
|
||||
static sem_t *posix_sem_open_fd(int fd) {
|
||||
if (fd < 0) return SEM_FAILED;
|
||||
sem_t *sem = posix_sem_map(fd);
|
||||
close_keeping_errno(fd);
|
||||
return sem;
|
||||
}
|
||||
|
||||
sem_t *sem_open(const char *name, int oflag, ...) {
|
||||
char path[PATH_MAX];
|
||||
if (posix_shm_path(name, "sem.", path, sizeof(path)) < 0) return SEM_FAILED;
|
||||
if (!(oflag & O_CREAT)) return posix_sem_open_fd(open(path, O_RDWR | O_NOFOLLOW | O_CLOEXEC));
|
||||
va_list args;
|
||||
va_start(args, oflag);
|
||||
mode_t mode = va_arg(args, mode_t);
|
||||
unsigned int value = va_arg(args, unsigned int);
|
||||
va_end(args);
|
||||
static unsigned int serial;
|
||||
for (;;) {
|
||||
if (!(oflag & O_EXCL)) {
|
||||
int fd = open(path, O_RDWR | O_NOFOLLOW | O_CLOEXEC);
|
||||
if (fd >= 0 || errno != ENOENT) return posix_sem_open_fd(fd);
|
||||
}
|
||||
if (value > SEM_VALUE_MAX) { errno = EINVAL; return SEM_FAILED; }
|
||||
sem_t initial;
|
||||
memset(&initial, 0, sizeof(initial));
|
||||
sem_init(&initial, 1, value);
|
||||
char temp[PATH_MAX];
|
||||
int fd;
|
||||
do {
|
||||
snprintf(temp, sizeof(temp), "/dev/shm/.sem-%d-%u", (int)getpid(), __atomic_fetch_add(&serial, 1, __ATOMIC_RELAXED));
|
||||
fd = open(temp, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, mode);
|
||||
} while (fd < 0 && errno == EEXIST);
|
||||
if (fd < 0) return SEM_FAILED;
|
||||
errno = EIO;
|
||||
sem_t *sem = write(fd, &initial, sizeof(initial)) == (ssize_t)sizeof(initial) ? posix_sem_map(fd) : SEM_FAILED;
|
||||
close_keeping_errno(fd);
|
||||
if (sem != SEM_FAILED && renameat2(AT_FDCWD, temp, AT_FDCWD, path, RENAME_NOREPLACE) == 0) return sem;
|
||||
int saved = errno;
|
||||
if (sem != SEM_FAILED) sem_close(sem);
|
||||
unlink(temp);
|
||||
errno = saved;
|
||||
if (errno != EEXIST || (oflag & O_EXCL)) return SEM_FAILED;
|
||||
}
|
||||
}
|
||||
|
||||
int sem_close(sem_t *sem) {
|
||||
posix_sems_hold();
|
||||
struct posix_sem **link = &g_posix_sems;
|
||||
while (*link && (*link)->addr != sem) link = &(*link)->next;
|
||||
struct posix_sem *e = *link;
|
||||
if (e && --e->refs == 0) {
|
||||
*link = e->next;
|
||||
munmap(e->addr, sizeof(sem_t));
|
||||
free(e);
|
||||
}
|
||||
posix_sems_unlock();
|
||||
if (!e) { errno = EINVAL; return -1; }
|
||||
return 0;
|
||||
}
|
||||
|
||||
int sem_unlink(const char *name) {
|
||||
char path[PATH_MAX];
|
||||
if (posix_shm_path(name, "sem.", path, sizeof(path)) < 0) return -1;
|
||||
return unlink(path);
|
||||
}
|
||||
|
||||
|
||||
@@ -526,6 +526,12 @@ static long nested_path_syscall(long number, unsigned long dirfd, unsigned long
|
||||
return call_orig_syscall(number, dirfd, (unsigned long)path, arg3, arg4, 0, 0);
|
||||
}
|
||||
|
||||
static long fake_root_ids(long number, unsigned int *real, unsigned int *effective, unsigned int *saved) {
|
||||
long rc = call_orig_syscall(number, (unsigned long)real, (unsigned long)effective, (unsigned long)saved, 0, 0, 0);
|
||||
if (rc == 0) *real = *effective = *saved = 0;
|
||||
return rc;
|
||||
}
|
||||
|
||||
long syscall(long number, ...) {
|
||||
va_list ap;
|
||||
va_start(ap, number);
|
||||
@@ -708,6 +714,16 @@ long syscall(long number, ...) {
|
||||
return (long)utimensat((int)arg1, (const char *)arg2, (const struct timespec *)arg3, (int)arg4);
|
||||
}
|
||||
#endif
|
||||
#if defined(__NR_connect)
|
||||
if (number == __NR_connect) {
|
||||
return (long)connect((int)arg1, (const struct sockaddr *)arg2, (socklen_t)arg3);
|
||||
}
|
||||
#endif
|
||||
#if defined(__NR_bind)
|
||||
if (number == __NR_bind) {
|
||||
return (long)bind((int)arg1, (const struct sockaddr *)arg2, (socklen_t)arg3);
|
||||
}
|
||||
#endif
|
||||
#if defined(__NR_truncate)
|
||||
if (number == __NR_truncate) {
|
||||
return (long)truncate((const char *)arg1, (off_t)arg2);
|
||||
@@ -867,48 +883,22 @@ long syscall(long number, ...) {
|
||||
if (number == __NR_getegid32) return 0;
|
||||
#endif
|
||||
#if defined(__NR_getresuid)
|
||||
if (number == __NR_getresuid) {
|
||||
uid_t *ruid = (uid_t *)arg1;
|
||||
uid_t *euid = (uid_t *)arg2;
|
||||
uid_t *suid = (uid_t *)arg3;
|
||||
if (ruid) *ruid = 0;
|
||||
if (euid) *euid = 0;
|
||||
if (suid) *suid = 0;
|
||||
return 0;
|
||||
}
|
||||
if (number == __NR_getresuid) return fake_root_ids(number, (unsigned int *)arg1, (unsigned int *)arg2, (unsigned int *)arg3);
|
||||
#endif
|
||||
#if defined(__NR_getresuid32)
|
||||
if (number == __NR_getresuid32) {
|
||||
uid_t *ruid = (uid_t *)arg1;
|
||||
uid_t *euid = (uid_t *)arg2;
|
||||
uid_t *suid = (uid_t *)arg3;
|
||||
if (ruid) *ruid = 0;
|
||||
if (euid) *euid = 0;
|
||||
if (suid) *suid = 0;
|
||||
return 0;
|
||||
}
|
||||
if (number == __NR_getresuid32) return fake_root_ids(number, (unsigned int *)arg1, (unsigned int *)arg2, (unsigned int *)arg3);
|
||||
#endif
|
||||
#if defined(__NR_getresgid)
|
||||
if (number == __NR_getresgid) {
|
||||
gid_t *rgid = (gid_t *)arg1;
|
||||
gid_t *egid = (gid_t *)arg2;
|
||||
gid_t *sgid = (gid_t *)arg3;
|
||||
if (rgid) *rgid = 0;
|
||||
if (egid) *egid = 0;
|
||||
if (sgid) *sgid = 0;
|
||||
return 0;
|
||||
}
|
||||
if (number == __NR_getresgid) return fake_root_ids(number, (unsigned int *)arg1, (unsigned int *)arg2, (unsigned int *)arg3);
|
||||
#endif
|
||||
#if defined(__NR_getresgid32)
|
||||
if (number == __NR_getresgid32) {
|
||||
gid_t *rgid = (gid_t *)arg1;
|
||||
gid_t *egid = (gid_t *)arg2;
|
||||
gid_t *sgid = (gid_t *)arg3;
|
||||
if (rgid) *rgid = 0;
|
||||
if (egid) *egid = 0;
|
||||
if (sgid) *sgid = 0;
|
||||
return 0;
|
||||
}
|
||||
if (number == __NR_getresgid32) return fake_root_ids(number, (unsigned int *)arg1, (unsigned int *)arg2, (unsigned int *)arg3);
|
||||
#endif
|
||||
#if defined(__NR_getgroups)
|
||||
if (number == __NR_getgroups) return (long)getgroups((int)arg1, (gid_t *)arg2);
|
||||
#endif
|
||||
#if defined(__NR_fchown)
|
||||
if (number == __NR_fchown) return (long)fchown((int)arg1, (uid_t)arg2, (gid_t)arg3);
|
||||
#endif
|
||||
|
||||
return call_orig_syscall(number, arg1, arg2, arg3, arg4, arg5, arg6);
|
||||
|
||||
@@ -84,6 +84,19 @@ static void init_ddnatv_hook(void) {
|
||||
setenv("TZDIR", tzdir_buf, 0);
|
||||
}
|
||||
|
||||
const char *curr_locpath = getenv("LOCPATH");
|
||||
if (!curr_locpath || curr_locpath[0] == '\0') {
|
||||
char locpath_buf[PATH_MAX];
|
||||
snprintf(locpath_buf, sizeof(locpath_buf), "%s/usr/lib/locale", g_ddnatv_root);
|
||||
setenv("LOCPATH", locpath_buf, 1);
|
||||
}
|
||||
|
||||
if (!getenv("GCONV_PATH")) {
|
||||
char gconv_buf[PATH_MAX];
|
||||
snprintf(gconv_buf, sizeof(gconv_buf), "%s/usr/lib/aarch64-linux-gnu/gconv", g_ddnatv_root);
|
||||
setenv("GCONV_PATH", gconv_buf, 0);
|
||||
}
|
||||
|
||||
const char *curr_cert = getenv("SSL_CERT_FILE");
|
||||
if (!curr_cert || curr_cert[0] == '\0' || strcmp(curr_cert, "/etc/ssl/certs/ca-certificates.crt") == 0) {
|
||||
char cert_buf[PATH_MAX];
|
||||
@@ -190,15 +203,10 @@ static void exe_from_cmdline(const char *cmdline_path, char *out, size_t outsz)
|
||||
}
|
||||
|
||||
static ssize_t copy_guest_exe(const char *real_exe, char *buf, size_t bufsiz) {
|
||||
const char *out_path = real_exe;
|
||||
if (g_ddnatv_root[0] != '\0') {
|
||||
size_t rlen = g_ddnatv_root_len;
|
||||
if (strncmp(real_exe, g_ddnatv_root, rlen) == 0 &&
|
||||
(real_exe[rlen] == '/' || real_exe[rlen] == '\0')) {
|
||||
out_path = real_exe + rlen;
|
||||
if (out_path[0] == '\0') out_path = "/";
|
||||
}
|
||||
}
|
||||
char guest[PATH_MAX];
|
||||
char back[PATH_MAX];
|
||||
const char *out_path = guest_path_of_host_dir(real_exe, guest, sizeof(guest));
|
||||
if (!out_path || strcmp(rewrite_path_in_root(out_path, back, sizeof(back)), real_exe) != 0) out_path = real_exe;
|
||||
size_t len = strlen(out_path);
|
||||
size_t copy_len = (len < bufsiz) ? len : bufsiz;
|
||||
memcpy(buf, out_path, copy_len);
|
||||
@@ -350,8 +358,11 @@ static ssize_t handle_proc_exe_at(int dirfd, const char *pathname, char *buf, si
|
||||
static const char *rewrite_path(const char *path, char *buffer, size_t bufsize) {
|
||||
if (!path) return NULL;
|
||||
// Relative paths must NEVER be rewritten to rootfs root
|
||||
if (path[0] != '/') return path;
|
||||
init_ddnatv_hook();
|
||||
if (path[0] != '/') {
|
||||
const char *walked = map_at(AT_FDCWD, path, buffer, bufsize);
|
||||
return walked ? walked : path;
|
||||
}
|
||||
return rewrite_path_in_root(path, buffer, bufsize);
|
||||
}
|
||||
|
||||
@@ -361,7 +372,7 @@ static const char *rewrite_path(const char *path, char *buffer, size_t bufsize)
|
||||
// followed in the guest's view first. The rootfs's own links were made relative already.
|
||||
static const char *rewrite_path_follow(const char *path, char *buffer, size_t bufsize) {
|
||||
if (!path) return NULL;
|
||||
if (path[0] != '/') return path;
|
||||
if (path[0] != '/') return rewrite_path(path, buffer, bufsize);
|
||||
init_ddnatv_hook();
|
||||
int moved = 0;
|
||||
for (int i = 0; i < g_nbinds; i++) {
|
||||
|
||||
@@ -94,6 +94,13 @@ int listen(int sockfd, int backlog) {
|
||||
return ret;
|
||||
}
|
||||
|
||||
static void copy_unix_path(const struct sockaddr_un *sun, socklen_t addrlen, char *out) {
|
||||
size_t max = addrlen - offsetof(struct sockaddr_un, sun_path);
|
||||
if (max > sizeof(sun->sun_path)) max = sizeof(sun->sun_path);
|
||||
memcpy(out, sun->sun_path, max);
|
||||
out[max] = '\0';
|
||||
}
|
||||
|
||||
int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen) {
|
||||
static int (*orig_bind)(int, const struct sockaddr *, socklen_t) = NULL;
|
||||
if (!orig_bind) orig_bind = (int (*)(int, const struct sockaddr *, socklen_t))dlsym(RTLD_NEXT, "bind");
|
||||
@@ -104,7 +111,9 @@ int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen) {
|
||||
struct sockaddr_un mod_sun;
|
||||
memset(&mod_sun, 0, sizeof(mod_sun));
|
||||
mod_sun.sun_family = AF_UNIX;
|
||||
rewrite_unix_socket_path(sun->sun_path, mod_sun.sun_path, sizeof(mod_sun.sun_path));
|
||||
char guest[sizeof(sun->sun_path) + 1];
|
||||
copy_unix_path(sun, addrlen, guest);
|
||||
rewrite_unix_socket_path(guest, mod_sun.sun_path, sizeof(mod_sun.sun_path));
|
||||
return orig_bind ? orig_bind(sockfd, (struct sockaddr *)&mod_sun, sizeof(mod_sun)) : -1;
|
||||
}
|
||||
}
|
||||
@@ -133,10 +142,7 @@ int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen) {
|
||||
memset(&mod_sun, 0, sizeof(mod_sun));
|
||||
mod_sun.sun_family = AF_UNIX;
|
||||
char guest[sizeof(sun->sun_path) + 1];
|
||||
size_t max = addrlen - offsetof(struct sockaddr_un, sun_path);
|
||||
if (max > sizeof(sun->sun_path)) max = sizeof(sun->sun_path);
|
||||
memcpy(guest, sun->sun_path, max);
|
||||
guest[max] = '\0';
|
||||
copy_unix_path(sun, addrlen, guest);
|
||||
char followed[PATH_MAX];
|
||||
const char *path = guest[0] == '/' ? follow_guest_link(guest, followed, sizeof(followed)) : guest;
|
||||
rewrite_unix_socket_path(path, mod_sun.sun_path, sizeof(mod_sun.sun_path));
|
||||
|
||||
@@ -23,7 +23,8 @@ while IFS= read -r dir; do
|
||||
done < <(ls -d "${sdk_dir}"/build-tools/* 2>/dev/null | sort -rV)
|
||||
[[ -n "${build_tools}" ]] || { echo "No build-tools with aapt, zipalign and apksigner under ${sdk_dir}." >&2; exit 1; }
|
||||
|
||||
./gradlew -q -PallowStaleRuntime=true :app:assembleRelease
|
||||
# Lint vital is most of an incremental build and CI runs it.
|
||||
./gradlew -q -PallowStaleRuntime=true :app:assembleRelease -x lintVitalAnalyzeRelease
|
||||
(
|
||||
cd "$(dirname "${signing_env}")"
|
||||
set -a; . "${signing_env}"; set +a
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
from pathlib import Path
|
||||
import importlib.util
|
||||
import re
|
||||
import shutil
|
||||
import sys
|
||||
from zipfile import ZipFile
|
||||
|
||||
@@ -34,6 +35,14 @@ def source_assets(overlay=OVERLAY):
|
||||
return result
|
||||
|
||||
|
||||
def stage(target=OVERLAY.parents[2] / 'app/src/main', overlay=OVERLAY):
|
||||
for source, asset in source_assets(overlay).items():
|
||||
path = target / asset
|
||||
if not path.is_file() or path.read_bytes() != source.read_bytes():
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copyfile(source, path)
|
||||
|
||||
|
||||
def check(apk, overlay=OVERLAY):
|
||||
errors = check_extraction(overlay, SESSION_FILES.read_text()) if overlay == OVERLAY else []
|
||||
with ZipFile(apk) as package:
|
||||
@@ -60,6 +69,9 @@ def check(apk, overlay=OVERLAY):
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if sys.argv[1:] == ['--stage']:
|
||||
stage()
|
||||
sys.exit()
|
||||
errors = check(sys.argv[1])
|
||||
if errors:
|
||||
sys.exit('\n'.join(errors))
|
||||
|
||||
@@ -48,8 +48,19 @@ def digest(path):
|
||||
return result.hexdigest()
|
||||
|
||||
|
||||
def copied(root):
|
||||
# Helper scripts are staged verbatim on every Gradle build and checked against the APK by
|
||||
# check_session_assets.py, so they are neither preparation inputs nor prepared outputs.
|
||||
if str(Path(__file__).resolve().parent) not in sys.path:
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
from check_session_assets import OVERLAY, source_assets
|
||||
found = source_assets() if root == ROOT else source_assets(root / OVERLAY.relative_to(ROOT))
|
||||
return {source.relative_to(root).as_posix(): 'app/src/main/' + asset for source, asset in found.items()}
|
||||
|
||||
|
||||
def sources(root):
|
||||
files, builds = [], set()
|
||||
skipped = set(copied(root))
|
||||
for name in SOURCE_PATHS:
|
||||
path = root / name
|
||||
files.extend(path.rglob('*') if path.is_dir() else [path])
|
||||
@@ -57,14 +68,18 @@ def sources(root):
|
||||
builds.update(manifest.parent / 'target' for manifest in path.rglob('Cargo.toml'))
|
||||
return {path.relative_to(root).as_posix(): digest(path) for path in sorted(set(files))
|
||||
if path.is_file() and '__pycache__' not in path.parts and path.suffix != '.pyc'
|
||||
and path.relative_to(root).as_posix() not in skipped
|
||||
and not any(build in path.parents for build in builds)}
|
||||
|
||||
|
||||
def outputs(root):
|
||||
result = {}
|
||||
skipped = set(copied(root).values())
|
||||
for tree in ['linuxfs', 'directaudio', 'droiddeck-esync', 'desktop-removal', 'hybris']:
|
||||
base = root / 'app/src/main/assets' / tree
|
||||
for path in base.rglob('*'):
|
||||
if path.relative_to(root).as_posix() in skipped:
|
||||
continue
|
||||
if path.is_file() and not any(part.startswith('.') for part in path.relative_to(base).parts):
|
||||
result['assets/' + tree + '/' + path.relative_to(base).as_posix()] = path.relative_to(root).as_posix()
|
||||
for library in ['libproot.so', 'libproot-loader.so', 'libdirectaudiorelay.so']:
|
||||
@@ -84,7 +99,6 @@ def required():
|
||||
for name in ['turnip26.3.0-a6xx', 'turnip26.3.0-quest2']]
|
||||
paths += ['assets/linuxfs/' + name for name in ['libfakeinput.so', 'libddsession.so',
|
||||
'libddfastpath.so', 'libddnatv-hook.so', 'libssbs.so', 'usr/local/bin/droiddeck-clipboard',
|
||||
'usr/local/bin/droiddeck-gog-maintenance',
|
||||
'usr/local/bin/gamescope', 'usr/local/lib/droiddeck/uruntime',
|
||||
'usr/local/lib/droiddeck-pipewire.tzst']]
|
||||
for arch in ['x86_64', 'i386']:
|
||||
@@ -178,6 +192,10 @@ def verify(root=ROOT, stale_sources_ok=False):
|
||||
raise ValueError('Runtime inputs have not been prepared. Run tools/build_local.sh.')
|
||||
if data.get('version') != 1:
|
||||
raise ValueError('Runtime sources changed since preparation. Run tools/build_local.sh.')
|
||||
copies = copied(root)
|
||||
data['sources'] = {name: value for name, value in (data.get('sources') or {}).items() if name not in copies}
|
||||
data['outputs'] = {name: output for name, output in (data.get('outputs') or {}).items()
|
||||
if output.get('path') not in copies.values()}
|
||||
current = sources(root)
|
||||
if data.get('sources') != current:
|
||||
if not stale_sources_ok:
|
||||
@@ -195,6 +213,11 @@ def verify(root=ROOT, stale_sources_ok=False):
|
||||
raise ValueError('Missing or changed runtime input: ' + name + '. Run tools/build_local.sh.')
|
||||
if outputs(root) != {name: output['path'] for name, output in data['outputs'].items()}:
|
||||
raise ValueError('Runtime file set changed. Run tools/build_local.sh.')
|
||||
for source, asset in copies.items():
|
||||
path = root / asset
|
||||
if not path.is_file() or path.read_bytes() != (root / source).read_bytes():
|
||||
raise ValueError(asset + ' is not a current copy of ' + source
|
||||
+ '. Run python3 tools/release/check_session_assets.py --stage.')
|
||||
return data
|
||||
|
||||
|
||||
|
||||
@@ -10,14 +10,19 @@ paths=(
|
||||
app/build/packs app/build/localPackAssets app/build/packs-local-aside app/build/quest-inputs
|
||||
app/build/rustJniLibs app/build/vkbridgeJniLibs
|
||||
app/src/main/assets/directaudio app/src/main/assets/droiddeck-esync app/src/main/assets/linuxfs
|
||||
app/src/main/assets/desktop-removal
|
||||
app/src/main/assets/desktop-removal app/src/main/assets/hybris
|
||||
app/src/main/jniLibs/arm64-v8a
|
||||
app/src/main/rust/stores/target
|
||||
)
|
||||
for path in "${paths[@]}"; do
|
||||
[[ -e "${main_root}/${path}" ]] || continue
|
||||
if [[ -d "${main_root}/${path}" ]]; then
|
||||
[[ -z "$(ls -A "${repo_root}/${path}" 2>/dev/null)" ]] || continue
|
||||
if [[ -n "$(ls -A "${repo_root}/${path}" 2>/dev/null)" ]]; then
|
||||
# A directory holding only tracked files (jniLibs) still lacks every built library.
|
||||
[[ -z "$(git -C "${repo_root}" ls-files --others -- "${path}")" ]] || continue
|
||||
cp -Rn "${main_root}/${path}/." "${repo_root}/${path}/"
|
||||
continue
|
||||
fi
|
||||
mkdir -p "$(dirname "${repo_root}/${path}")"
|
||||
staged=$(mktemp -d "${repo_root}/${path}.seed.XXXXXX")
|
||||
trap 'rm -rf "${staged}"' EXIT
|
||||
|
||||
@@ -146,6 +146,24 @@ class AppImageRunTest(unittest.TestCase):
|
||||
env, _ = self.launch(dict(RUN_MODE, TU_DEBUG="sysmem"))
|
||||
self.assertEqual("sysmem", env["TU_DEBUG"])
|
||||
|
||||
def test_an_arm64_app_uses_the_sessions_gl_libraries(self):
|
||||
(self.dir / "arch").write_text("arm64")
|
||||
self.bundle("usr/lib/libGLESv2.so.2", "usr/lib/libEGL.so.1", "usr/lib/libglfw.so.3", "usr/lib/libGLESv2.so.2.1.0")
|
||||
_, log = self.launch(RUN_MODE)
|
||||
lib = self.dir / "app/usr/lib"
|
||||
self.assertEqual(["libGLESv2.so.2.1.0", "libglfw.so.3"], sorted(p.name for p in lib.iterdir()))
|
||||
self.assertEqual(["libEGL.so.1", "libGLESv2.so.2"], sorted(p.name for p in (self.dir / "bundled-gl/usr/lib").iterdir()))
|
||||
self.assertIn("the session's libGLESv2.so.2 replaces the bundled one", log)
|
||||
_, log = self.launch(RUN_MODE)
|
||||
self.assertNotIn("replaces the bundled one", log)
|
||||
|
||||
def test_other_architectures_keep_their_gl_libraries(self):
|
||||
(self.dir / "arch").write_text("x86_64")
|
||||
self.bundle("usr/lib/libGLESv2.so.2")
|
||||
self.launch(RUN_MODE)
|
||||
self.assertTrue((self.dir / "app/usr/lib/libGLESv2.so.2").exists())
|
||||
self.assertFalse((self.dir / "bundled-gl").exists())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -138,6 +138,27 @@ class BinfmtPreloadTest(unittest.TestCase):
|
||||
program = self.file("arm64", bytes(arm64))
|
||||
self.assertEqual(self.run_program("execve", program), (3, "errno %d" % errno.ENOEXEC, None))
|
||||
|
||||
def arm64_appimage(self, name, filesystem):
|
||||
image = bytearray(128)
|
||||
image[0:4], image[4], image[5], image[8:11], image[18] = b"\x7fELF", 2, 1, b"AI\x02", 183
|
||||
image[0x28:0x30] = (64).to_bytes(8, "little")
|
||||
image[0x3A:0x3C], image[0x3C:0x3E] = (32).to_bytes(2, "little"), (1).to_bytes(2, "little")
|
||||
image[96:102] = filesystem
|
||||
return self.file(name, bytes(image))
|
||||
|
||||
def test_an_arm64_appimage_goes_to_the_handler(self):
|
||||
program = self.arm64_appimage("App.AppImage", b"hsqs\0\0")
|
||||
for how in ("execve", "execvp"):
|
||||
self.log.unlink(missing_ok=True)
|
||||
target = program if how == "execve" else program.name
|
||||
self.assertEqual(self.run_program(how, target, "--x"), (7, "", ["--exec", str(program), "--x"]))
|
||||
self.log.unlink()
|
||||
self.assertEqual(self.run_program("spawn", program, "y"), (0, "exit 7", ["--exec", str(program), "y"]))
|
||||
|
||||
def test_an_appimage_runtime_without_a_filesystem_keeps_its_error(self):
|
||||
runtime = self.arm64_appimage("uruntime", bytes(6))
|
||||
self.assertEqual(self.run_program("execve", runtime), (3, "errno %d" % errno.ENOEXEC, None))
|
||||
|
||||
def test_a_script_runs_as_itself(self):
|
||||
script = self.file("script.sh", b"#!/bin/sh\nexit 5\n")
|
||||
self.assertEqual(self.run_program("execve", script), (5, "", None))
|
||||
@@ -188,6 +209,24 @@ class BinfmtPreloadTest(unittest.TestCase):
|
||||
code = self.chromium_script()
|
||||
self.assertEqual(self.run_program("execve", code, "--version"), (0, "--no-sandbox\n--version", None))
|
||||
|
||||
def test_a_chromium_app_named_on_path_receives_no_sandbox(self):
|
||||
(self.dir / "code").symlink_to(self.chromium_script())
|
||||
for how in ("execvp", "execvpe", "spawnp"):
|
||||
out = self.run_program(how, "code", "--version")
|
||||
self.assertEqual(out[1].splitlines()[:2], ["--no-sandbox", "--version"], how)
|
||||
|
||||
def test_a_path_match_that_cannot_run_does_not_decide_the_flags(self):
|
||||
stale = self.dir / "stale"
|
||||
stale.mkdir()
|
||||
(stale / "util").write_text("#!/bin/sh\n")
|
||||
(stale / "chrome-sandbox").touch()
|
||||
util = self.dir / "util"
|
||||
util.write_text("#!/bin/sh\nprintf '%s\\n' \"$@\"\n")
|
||||
util.chmod(0o755)
|
||||
for how in ("execvp", "execvpe", "spawnp"):
|
||||
out = self.run_program(how, "util", "--version", PATH=f"{stale}:{self.dir}:/usr/bin:/bin")
|
||||
self.assertEqual(out[1].splitlines()[:1], ["--version"], how)
|
||||
|
||||
def test_the_hand_off_switch_works_without_the_desktop(self):
|
||||
tool = self.x86()
|
||||
for how in ("execve", "execvp"):
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
COMPONENTS = Path(__file__).resolve().parents[1] / 'components'
|
||||
sys.path.insert(0, str(COMPONENTS))
|
||||
spec = importlib.util.spec_from_file_location('component_reuse', COMPONENTS / 'reuse.py')
|
||||
reuse = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(reuse)
|
||||
prepare = reuse.prepare
|
||||
|
||||
|
||||
class ComponentReuseTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.root = Path(self.temp.name)
|
||||
(self.root / 'tools/ci').mkdir(parents=True)
|
||||
(self.root / 'tools/ci/toolchains.env').write_text('CI_ANDROID_NDK_VERSION=30.0.1\n')
|
||||
self.local = {'runtime': 'a', 'proot': 'b'}
|
||||
self.unregistered, self.submodules = [], []
|
||||
for patcher in [mock.patch.object(prepare, 'registry', lambda root: dict.fromkeys(self.local)),
|
||||
mock.patch.object(prepare, 'identity', lambda name, root: self.local[name]),
|
||||
mock.patch.object(reuse, 'unregistered_changes', lambda tree, root: self.unregistered),
|
||||
mock.patch.object(reuse, 'edited_submodules', lambda root: self.submodules)]:
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
self.archive = self.root / 'prepared-components.tar.gz'
|
||||
self.contents = {name + '/file': name.encode() for name in prepare.TREES}
|
||||
self.contents.update({name: b'library' for name in prepare.LIBRARIES})
|
||||
|
||||
def write_archive(self, recipes, contents=None):
|
||||
contents = contents or self.contents
|
||||
manifest = dict(version=1, source_tree='tree', run='42', recipes=recipes,
|
||||
files={name: hashlib.sha256(data).hexdigest() for name, data in self.contents.items()})
|
||||
with tarfile.open(self.archive, 'w:gz') as archive:
|
||||
for name, data in list(contents.items()) + [(prepare.MANIFEST, json.dumps(manifest).encode())]:
|
||||
entry = tarfile.TarInfo(name)
|
||||
entry.size = len(data)
|
||||
entry.mode = 0o644
|
||||
archive.addfile(entry, io.BytesIO(data))
|
||||
|
||||
def test_matching_components_replace_local_ones(self):
|
||||
stale = self.root / prepare.TREES[0] / 'left-over'
|
||||
stale.parent.mkdir(parents=True)
|
||||
stale.write_text('from an older local build')
|
||||
self.write_archive(dict(self.local))
|
||||
self.assertTrue(reuse.reuse(self.archive, self.root))
|
||||
self.assertEqual(b'library', (self.root / prepare.LIBRARIES[0]).read_bytes())
|
||||
self.assertFalse(stale.exists())
|
||||
|
||||
def test_a_changed_component_is_not_reused(self):
|
||||
self.write_archive(dict(self.local, proot='other'))
|
||||
with mock.patch('sys.stdout', new_callable=io.StringIO) as stdout:
|
||||
self.assertFalse(reuse.reuse(self.archive, self.root))
|
||||
self.assertIn('proot', stdout.getvalue())
|
||||
self.assertFalse((self.root / prepare.LIBRARIES[0]).exists())
|
||||
|
||||
def test_a_tampered_file_is_rejected_and_local_outputs_survive(self):
|
||||
local = self.root / prepare.LIBRARIES[0]
|
||||
local.parent.mkdir(parents=True)
|
||||
local.write_bytes(b'local build')
|
||||
self.write_archive(dict(self.local), dict(self.contents, **{prepare.LIBRARIES[0]: b'tampered'}))
|
||||
with self.assertRaisesRegex(ValueError, 'do not match'):
|
||||
reuse.reuse(self.archive, self.root)
|
||||
self.assertEqual(b'local build', local.read_bytes())
|
||||
|
||||
def test_changed_sources_ci_builds_outside_recipes_are_not_reused(self):
|
||||
self.unregistered = ['tools/linuxfs/xclipse-layer/xclipse_layer.c']
|
||||
self.write_archive(dict(self.local))
|
||||
with mock.patch('sys.stdout', new_callable=io.StringIO) as stdout:
|
||||
self.assertFalse(reuse.reuse(self.archive, self.root))
|
||||
self.assertIn('xclipse_layer.c', stdout.getvalue())
|
||||
|
||||
def test_an_edited_submodule_is_not_reused(self):
|
||||
self.submodules = ['external/MaliBridge']
|
||||
self.write_archive(dict(self.local))
|
||||
with mock.patch('sys.stdout', new_callable=io.StringIO):
|
||||
self.assertFalse(reuse.reuse(self.archive, self.root))
|
||||
|
||||
def test_identities_use_the_ci_runner_and_ndk(self):
|
||||
seen = {}
|
||||
with mock.patch.object(prepare, 'identity', lambda name, root: seen.update(
|
||||
arch=reuse.os.environ['RUNNER_ARCH'], ndk=reuse.os.environ['NDK_VERSION']) or 'x'):
|
||||
reuse.identities(reuse.ci_environment('X64', self.root), self.root)
|
||||
self.assertEqual({'arch': 'X64', 'ndk': '30.0.1'}, seen)
|
||||
@@ -1,11 +1,8 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/desktop/droiddeck-desktop-gpu"
|
||||
PREFIX = "env -u WAYLAND_DISPLAY XDG_SESSION_TYPE=x11 ELECTRON_DISABLE_SANDBOX=1 "
|
||||
FLAGS = " --no-sandbox --ozone-platform=x11"
|
||||
|
||||
|
||||
def load():
|
||||
@@ -24,12 +21,6 @@ class DesktopChromiumAppsTest(unittest.TestCase):
|
||||
self.gpu = load()
|
||||
self.electron = self.app("lib/chat/chat", sandbox=True)
|
||||
self.plain = self.app("lib/editor/editor", sandbox=False)
|
||||
bin_dir = self.root / "bin"
|
||||
bin_dir.mkdir()
|
||||
(bin_dir / "chat").symlink_to(self.electron)
|
||||
old_path = os.environ.get("PATH", "")
|
||||
os.environ["PATH"] = "%s:%s" % (bin_dir, old_path)
|
||||
self.addCleanup(os.environ.__setitem__, "PATH", old_path)
|
||||
|
||||
def app(self, relative, sandbox):
|
||||
path = self.root / relative
|
||||
@@ -49,34 +40,17 @@ class DesktopChromiumAppsTest(unittest.TestCase):
|
||||
def exec_lines(self, text):
|
||||
return [l[5:] for l in text.splitlines() if l.startswith("Exec=")]
|
||||
|
||||
def test_an_electron_app_starts_without_the_sandbox_on_x11(self):
|
||||
out = self.gpu["wrap"](self.entry("%s %%U" % self.electron, actions="%s --new" % self.electron))
|
||||
self.assertEqual(self.exec_lines(out), [PREFIX + str(self.electron) + FLAGS + " %U",
|
||||
PREFIX + str(self.electron) + FLAGS + " --new"])
|
||||
self.assertIn("X-DroidDeck-GPU=1", out)
|
||||
self.assertIn("Actions=new;", out)
|
||||
self.assertNotIn("droiddeck-window", out)
|
||||
def test_electron_apps_keep_their_own_entries(self):
|
||||
self.assertIsNone(self.gpu["wrap"](self.entry("%s %%U" % self.electron, actions="%s --new" % self.electron)))
|
||||
self.assertIsNone(self.gpu["wrap"](self.entry(str(self.plain))))
|
||||
|
||||
def test_a_command_on_the_path_is_followed_to_its_install_folder(self):
|
||||
out = self.gpu["wrap"](self.entry("chat %U"))
|
||||
self.assertEqual(self.exec_lines(out), [PREFIX + "chat" + FLAGS + " %U"])
|
||||
def test_an_electron_game_goes_to_the_gpu_as_installed(self):
|
||||
out = self.gpu["wrap"](self.entry(str(self.electron), categories="Game;", actions="%s --new" % self.electron))
|
||||
self.assertEqual(self.exec_lines(out), ["droiddeck-gpu " + str(self.electron), str(self.electron),
|
||||
"droiddeck-gpu %s --new" % self.electron])
|
||||
|
||||
def test_a_quoted_program_keeps_its_quotes(self):
|
||||
out = self.gpu["wrap"](self.entry('"%s" %%U' % self.electron))
|
||||
self.assertEqual(self.exec_lines(out), [PREFIX + '"%s"' % self.electron + FLAGS + " %U"])
|
||||
|
||||
def test_other_apps_are_left_alone(self):
|
||||
self.assertIsNone(self.gpu["wrap"](self.entry("%s %%F" % self.plain)))
|
||||
self.assertIsNone(self.gpu["wrap"](self.entry("missing-program %F")))
|
||||
|
||||
def test_an_electron_game_goes_to_the_gpu_and_keeps_a_window_action(self):
|
||||
out = self.gpu["wrap"](self.entry(str(self.electron), categories="Game;"))
|
||||
fixed = PREFIX + str(self.electron) + FLAGS
|
||||
self.assertEqual(self.exec_lines(out), ["droiddeck-gpu " + fixed, fixed])
|
||||
|
||||
def test_with_the_gpu_off_electron_apps_are_still_fixed(self):
|
||||
out = self.gpu["wrap"](self.entry(str(self.electron), categories="Game;"), False)
|
||||
self.assertEqual(self.exec_lines(out), [PREFIX + str(self.electron) + FLAGS])
|
||||
def test_with_the_gpu_off_no_entry_is_written(self):
|
||||
self.assertIsNone(self.gpu["wrap"](self.entry(str(self.electron), categories="Game;"), False))
|
||||
self.assertIsNone(self.gpu["wrap"](self.entry(str(self.plain), categories="Game;"), False))
|
||||
|
||||
def test_games_that_are_not_chromium_are_unchanged(self):
|
||||
|
||||
@@ -526,6 +526,21 @@ class PrepareTest(FexTestCase):
|
||||
for name in names:
|
||||
self.assertEqual((Path(fex["rootfs"]) / "lib" / arch / name).read_bytes(), b"new ABI " + name.encode())
|
||||
|
||||
def test_opengl_dispatch_library_comes_from_the_newer_runtime_when_the_base_lacks_it(self):
|
||||
self.fex_tool()
|
||||
sniper = self.runtime()
|
||||
FEX["materialize"](str(sniper))
|
||||
provider = self.graphics(sniper)
|
||||
for arch in ("x86_64-linux-gnu", "i386-linux-gnu"):
|
||||
self.write(sniper / "files/lib" / arch / "libGLdispatch.so.0", b"base dispatch")
|
||||
self.write(provider / "files/lib" / arch / "libOpenGL.so.0.0.0", b"opengl " + arch.encode())
|
||||
os.symlink("libOpenGL.so.0.0.0", provider / "files/lib" / arch / "libOpenGL.so.0")
|
||||
fex, _ = self.quiet(FEX["prepare"])
|
||||
for arch in ("x86_64-linux-gnu", "i386-linux-gnu"):
|
||||
root = Path(fex["rootfs"]) / "lib" / arch
|
||||
self.assertEqual((root / "libOpenGL.so.0").read_bytes(), b"opengl " + arch.encode())
|
||||
self.assertEqual((root / "libGLdispatch.so.0").read_bytes(), b"base dispatch")
|
||||
|
||||
def test_gbm_requires_usable_provider_dependencies_on_both_architectures(self):
|
||||
self.fex_tool()
|
||||
sniper = self.runtime()
|
||||
@@ -1055,6 +1070,12 @@ class LaunchTest(FexTestCase):
|
||||
guest = FEX["guest_environment"]({"portable": True}, {"GLIBC_TUNABLES": "glibc.pthread.rseq=0"})
|
||||
self.assertNotIn("GLIBC_TUNABLES", guest)
|
||||
|
||||
def test_host_iconv_modules_stay_on_the_host(self):
|
||||
guest = FEX["guest_environment"]({"portable": True}, {"GCONV_PATH": "/r/usr/lib/aarch64-linux-gnu/gconv"})
|
||||
self.assertEqual(guest["GCONV_PATH"], "")
|
||||
own = FEX["guest_environment"]({"portable": True}, {"GCONV_PATH": "/opt/gconv"})
|
||||
self.assertEqual(own["GCONV_PATH"], "/opt/gconv")
|
||||
|
||||
def test_proton_runs_in_the_runtime_its_manifest_requires(self):
|
||||
self.fex_tool()
|
||||
self.runtime()
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
from pathlib import Path
|
||||
import re
|
||||
import unittest
|
||||
|
||||
PATCH = Path(__file__).resolve().parents[1] / "fex/patches/0015-gl-thunk-overlays-libopengl.patch"
|
||||
|
||||
|
||||
def hunk(sign):
|
||||
lines = [line for line in PATCH.read_text().splitlines() if not line.startswith(("diff ", "index ", "--- ", "+++ ", "@@"))]
|
||||
return re.findall(r'"([^"]+)"', "\n".join(line[1:] for line in lines if line[:1] in (" ", sign)))
|
||||
|
||||
|
||||
class FexGlThunkOverlayTest(unittest.TestCase):
|
||||
def test_libopengl_joins_the_gl_overlay(self):
|
||||
before, after = hunk("-"), hunk("+")
|
||||
self.assertNotIn("@PREFIX_LIB@/libOpenGL.so.0", before)
|
||||
self.assertIn("@PREFIX_LIB@/libOpenGL.so.0", after)
|
||||
self.assertIn("@PREFIX_LIB@/libOpenGL.so.0.0.0", after)
|
||||
self.assertEqual([path for path in before if path.startswith("@PREFIX_LIB@/libGL.")],
|
||||
[path for path in after if path.startswith("@PREFIX_LIB@/libGL.")])
|
||||
self.assertLess(after.index("@PREFIX_LIB@/libGL.so.1.7.0"), after.index("Vulkan"))
|
||||
self.assertLess(after.index("@PREFIX_LIB@/libOpenGL.so.0.0.0"), after.index("Vulkan"))
|
||||
|
||||
def test_patch_touches_only_the_thunks_database(self):
|
||||
self.assertEqual(["Data/ThunksDB.json"], re.findall(r"^diff --git a/(\S+) ", PATCH.read_text(), re.M))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,120 @@
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
PATCH = Path(__file__).resolve().parents[1] / "fex/patches/0014-guest-preload-drops-host-libraries.patch"
|
||||
|
||||
HARNESS = r"""
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <elf.h>
|
||||
#include <fcntl.h>
|
||||
#include <string>
|
||||
#include <unistd.h>
|
||||
namespace fextl { using string = std::string; }
|
||||
namespace ELFLoader {
|
||||
struct ELFContainer {
|
||||
enum ELFType { TYPE_NONE, TYPE_X86_64, TYPE_X86_32, TYPE_OTHER_ELF };
|
||||
static ELFType GetELFType(const std::string& Filename) {
|
||||
int FD = open(Filename.c_str(), O_RDONLY | O_CLOEXEC);
|
||||
if (FD == -1) return TYPE_NONE;
|
||||
Elf64_Ehdr Header {};
|
||||
ssize_t Read = pread(FD, &Header, sizeof(Header), 0);
|
||||
close(FD);
|
||||
if (Read < (ssize_t)sizeof(Header) || memcmp(Header.e_ident, ELFMAG, SELFMAG) != 0) return TYPE_NONE;
|
||||
if (Header.e_machine == EM_X86_64) return TYPE_X86_64;
|
||||
if (Header.e_machine == EM_386) return TYPE_X86_32;
|
||||
return TYPE_OTHER_ELF;
|
||||
}
|
||||
};
|
||||
}
|
||||
struct Loader {
|
||||
static fextl::string ResolveRootfsFile(const fextl::string& File, fextl::string RootFS) { return RootFS + File; }
|
||||
GUEST_PRELOAD
|
||||
};
|
||||
int main(int argc, char** argv) {
|
||||
std::printf("%s", Loader::GuestPreload(argv[1], argv[2]).c_str());
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def x86_compiler():
|
||||
for name in ("x86_64-linux-gnu-gcc", "gcc"):
|
||||
path = shutil.which(name)
|
||||
if path and subprocess.run([path, "-dumpmachine"], capture_output=True, text=True).stdout.startswith("x86_64"):
|
||||
return path
|
||||
return None
|
||||
|
||||
|
||||
X86_CC = x86_compiler()
|
||||
|
||||
|
||||
def patch_function():
|
||||
lines = [line[1:] for line in PATCH.read_text().splitlines() if line.startswith("+") and not line.startswith("+++")]
|
||||
body = "\n".join(lines)
|
||||
first = body.index(" static fextl::string GuestPreload(")
|
||||
last = body.index("\n }\n", first) + len("\n }\n")
|
||||
return body[first:last]
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which("g++") and X86_CC and shutil.which("aarch64-linux-gnu-gcc"), "needs g++, an x86-64 gcc and aarch64-linux-gnu-gcc")
|
||||
class FexGuestPreloadTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.tmp = tempfile.TemporaryDirectory()
|
||||
cls.dir = Path(cls.tmp.name)
|
||||
source = cls.dir / "harness.cpp"
|
||||
source.write_text(HARNESS.replace("GUEST_PRELOAD", patch_function()))
|
||||
cls.binary = cls.dir / "harness"
|
||||
subprocess.run(["g++", "-std=c++20", "-O1", "-o", str(cls.binary), str(source)], check=True)
|
||||
stub = cls.dir / "stub.c"
|
||||
stub.write_text("int stub(void) { return 0; }\n")
|
||||
cls.host = cls.dir / "host"
|
||||
cls.rootfs = cls.dir / "rootfs"
|
||||
cls.shadow = cls.host / "lib/libshadow.so"
|
||||
cls.rootfs_shadow = Path(str(cls.rootfs) + str(cls.shadow))
|
||||
for folder in (cls.host / "lib", cls.rootfs_shadow.parent):
|
||||
folder.mkdir(parents=True)
|
||||
cls.compile("aarch64-linux-gnu-gcc", stub, cls.host / "lib/libhost.so")
|
||||
cls.compile(X86_CC, stub, cls.host / "lib/libguest.so")
|
||||
cls.compile("aarch64-linux-gnu-gcc", stub, cls.shadow)
|
||||
cls.compile(X86_CC, stub, cls.rootfs_shadow)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.tmp.cleanup()
|
||||
|
||||
@staticmethod
|
||||
def compile(compiler, source, output):
|
||||
subprocess.run([compiler, "-shared", "-fPIC", "-o", str(output), str(source)], check=True)
|
||||
|
||||
def preload(self, value, rootfs=None):
|
||||
root = str(self.rootfs) if rootfs is None else rootfs
|
||||
return subprocess.run([str(self.binary), value, root], check=True, capture_output=True, text=True).stdout
|
||||
|
||||
def test_host_libraries_leave_the_guest_list(self):
|
||||
host, guest = self.host / "lib/libhost.so", self.host / "lib/libguest.so"
|
||||
self.assertEqual(str(guest), self.preload(f"{host}:{guest}"))
|
||||
self.assertEqual("", self.preload(str(host)))
|
||||
|
||||
def test_rootfs_copy_decides_before_the_host_path(self):
|
||||
self.assertEqual(str(self.shadow), self.preload(str(self.shadow)))
|
||||
self.assertEqual("", self.preload(str(self.shadow), ""))
|
||||
|
||||
def test_names_missing_files_and_separators_are_kept(self):
|
||||
missing = str(self.dir / "missing.so")
|
||||
guest = str(self.host / "lib/libguest.so")
|
||||
self.assertEqual(f"libgamemodeauto.so.0:{missing}:{guest}",
|
||||
self.preload(f" libgamemodeauto.so.0::{missing} {guest}:"))
|
||||
|
||||
def test_patch_adds_no_comments(self):
|
||||
added = [line[1:].strip() for line in PATCH.read_text().splitlines() if line.startswith("+") and not line.startswith("+++")]
|
||||
self.assertFalse([line for line in added if line.startswith(("//", "/*"))])
|
||||
self.assertEqual(["Source/Tools/FEXInterpreter/ELFCodeLoader.h"], re.findall(r"^diff --git a/(\S+) ", PATCH.read_text(), re.M))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,148 @@
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from tools.tests.test_usr2_preload import runner
|
||||
|
||||
REPO = Path(__file__).resolve().parents[2]
|
||||
PATCH = REPO / "tools/fex/patches/0016-identity-syscalls-through-libc.patch"
|
||||
HOOK = REPO / "tools/nativeguest/hook/privileged.c"
|
||||
HOOK_BUILD = REPO / "tools/nativeguest/build.sh"
|
||||
PASSTHROUGH = "Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp"
|
||||
REGISTER = re.compile(r"REGISTER_SYSCALL_IMPL(?:_X64|_X32)?\((\w+), (\w+?)(\d)<SYSCALL_DEF\((\w+)\)>\);")
|
||||
IDENTITY = {"getuid", "getgid", "geteuid", "getegid", "setuid", "setgid", "setreuid", "setregid", "getgroups",
|
||||
"setgroups", "setresuid", "getresuid", "setresgid", "getresgid", "setfsuid", "setfsgid", "fchown"}
|
||||
|
||||
|
||||
def changed():
|
||||
removed, added = {}, {}
|
||||
for line in PATCH.read_text().splitlines():
|
||||
found = REGISTER.search(line)
|
||||
if found and line[:1] in "+-":
|
||||
(added if line[0] == "+" else removed)[found.group(1)] = found.groups()[1:]
|
||||
return removed, added
|
||||
|
||||
|
||||
class FexIdentitySyscallsTest(unittest.TestCase):
|
||||
def test_only_the_passthrough_table_changes(self):
|
||||
self.assertEqual(re.findall(r"^diff --git a/(\S+) ", PATCH.read_text(), re.M), [PASSTHROUGH])
|
||||
|
||||
def test_each_identity_syscall_keeps_its_arity_and_goes_through_libc(self):
|
||||
removed, added = changed()
|
||||
self.assertEqual(sorted(removed), sorted(added))
|
||||
self.assertEqual(IDENTITY, {number for _, _, number in added.values()})
|
||||
for name, (template, arity, number) in added.items():
|
||||
with self.subTest(name=name):
|
||||
self.assertEqual(("SyscallPassthrough", arity, number), removed[name])
|
||||
self.assertEqual("SyscallPathPassthrough", template)
|
||||
|
||||
def test_the_new_template_calls_the_libc_syscall(self):
|
||||
added = [line[1:] for line in PATCH.read_text().splitlines() if line.startswith("+") and not line.startswith("+++")]
|
||||
self.assertEqual([" uint64_t Result = ::syscall(syscall_num);"], [line for line in added if "Result =" in line])
|
||||
self.assertFalse([line for line in added if line.strip().startswith(("//", "/*"))])
|
||||
|
||||
def test_every_routed_syscall_is_answered_by_the_hook(self):
|
||||
hook = HOOK.read_text()
|
||||
for number in IDENTITY:
|
||||
with self.subTest(number=number):
|
||||
self.assertIn(f"number == __NR_{number})", hook)
|
||||
|
||||
|
||||
PROBE = r"""
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <stdio.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
unsigned int r = 7, e = 7, s = 7;
|
||||
long rc = syscall(SYS_getresuid, &r, &e, &s);
|
||||
printf("getresuid %ld %u %u %u\n", rc, r, e, s);
|
||||
errno = 0;
|
||||
rc = syscall(SYS_getresuid, NULL, &e, &s);
|
||||
printf("getresuid-null %ld %d\n", rc, errno);
|
||||
r = e = s = 7;
|
||||
rc = syscall(SYS_getresgid, &r, &e, &s);
|
||||
printf("getresgid %ld %u %u %u\n", rc, r, e, s);
|
||||
errno = 0;
|
||||
rc = syscall(SYS_getresgid, &r, NULL, &s);
|
||||
printf("getresgid-null %ld %d\n", rc, errno);
|
||||
unsigned int *locked = mmap(NULL, 4096, PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
|
||||
errno = 0;
|
||||
rc = syscall(SYS_getresuid, &r, &e, locked);
|
||||
printf("getresuid-readonly %ld %d\n", rc, errno);
|
||||
errno = 0;
|
||||
rc = syscall(SYS_getresgid, locked, &e, &s);
|
||||
printf("getresgid-readonly %ld %d\n", rc, errno);
|
||||
gid_t groups[8];
|
||||
rc = syscall(SYS_getgroups, 8, groups);
|
||||
printf("getgroups %ld %u\n", rc, rc > 0 ? groups[0] : 99u);
|
||||
errno = 0;
|
||||
rc = syscall(SYS_getgroups, 8, locked);
|
||||
printf("getgroups-readonly %ld %d\n", rc, errno);
|
||||
int fd = open(argv[1], O_RDONLY);
|
||||
printf("fchown %ld\n", syscall(SYS_fchown, fd, 4321, 4321));
|
||||
printf("getuid %ld\n", syscall(SYS_getuid));
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
class NativeHookIdentityTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.cc, cls.prefix = runner()
|
||||
if cls.cc is None:
|
||||
raise unittest.SkipTest("no aarch64 compiler and runner")
|
||||
cls.tmp = tempfile.TemporaryDirectory()
|
||||
tmp = Path(cls.tmp.name)
|
||||
cls.hook = tmp / "hook.so"
|
||||
subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True)
|
||||
(tmp / "probe.c").write_text(PROBE)
|
||||
subprocess.run([cls.cc, "-O1", "-o", str(tmp / "probe"), str(tmp / "probe.c")], check=True)
|
||||
(tmp / "root").mkdir()
|
||||
cls.file = tmp / "owned"
|
||||
cls.file.write_text("")
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.tmp.cleanup()
|
||||
|
||||
def probe(self):
|
||||
hook_env = {"DDNATV_ROOT": str(Path(self.tmp.name) / "root"), "LD_PRELOAD": str(self.hook)}
|
||||
env = {k: v for k, v in os.environ.items() if k != "LD_PRELOAD"}
|
||||
if self.prefix:
|
||||
cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
|
||||
else:
|
||||
cmd = []
|
||||
env.update(hook_env)
|
||||
out = subprocess.run(cmd + [str(Path(self.tmp.name) / "probe"), str(self.file)], env=env,
|
||||
capture_output=True, text=True, timeout=120)
|
||||
self.assertEqual(0, out.returncode, out.stderr)
|
||||
return {line.split(" ", 1)[0]: line.split(" ", 1)[1] for line in out.stdout.splitlines()}
|
||||
|
||||
def test_the_hook_answers_identity_syscalls_as_root(self):
|
||||
result = self.probe()
|
||||
self.assertEqual("0 0 0 0", result["getresuid"])
|
||||
self.assertEqual("0 0 0 0", result["getresgid"])
|
||||
self.assertEqual("1 0", result["getgroups"])
|
||||
self.assertEqual("-1 14", result["getgroups-readonly"])
|
||||
self.assertEqual("0", result["fchown"])
|
||||
self.assertEqual("0", result["getuid"])
|
||||
|
||||
def test_a_missing_pointer_still_faults(self):
|
||||
result = self.probe()
|
||||
self.assertEqual("-1 14", result["getresuid-null"])
|
||||
self.assertEqual("-1 14", result["getresgid-null"])
|
||||
self.assertEqual("-1 14", result["getresuid-readonly"])
|
||||
self.assertEqual("-1 14", result["getresgid-readonly"])
|
||||
self.assertEqual(os.stat(self.file).st_uid, os.getuid())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -10,6 +10,9 @@ from tools.tests.test_usr2_preload import runner
|
||||
HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh"
|
||||
GUEST_LDSO = "/usr/lib/ld-linux-aarch64.so.1"
|
||||
GUEST_TOOL = "/usr/local/bin/tool"
|
||||
BOUND_DIR = "/opt/runtime"
|
||||
ANDROID_DIR = "/opt/android"
|
||||
HOST_SHELL = "/data/local/tmp/droiddeck-hook-probe-sh"
|
||||
|
||||
RECORDER = r"""
|
||||
#define _GNU_SOURCE
|
||||
@@ -102,13 +105,31 @@ class NativeHookLdsoSpawnTest(unittest.TestCase):
|
||||
shutil.copy(source, host)
|
||||
host.chmod(0o755)
|
||||
(cls.root / "usr/lib/aarch64-linux-gnu").mkdir(parents=True, exist_ok=True)
|
||||
cls.runtime = tmp / "runtime"
|
||||
cls.runtime.mkdir()
|
||||
shutil.copy(cls.probe, cls.runtime / "bash")
|
||||
(cls.runtime / "bash").chmod(0o755)
|
||||
cls.android = tmp / "root-android"
|
||||
cls.android.mkdir()
|
||||
subprocess.run([cls.cc, "-O1", "-Wl,--dynamic-linker=/system/bin/linker64", "-o", str(cls.android / "sh"),
|
||||
str(tmp / "probe.c")], check=True)
|
||||
for name, interpreter in (("bound.sh", f"{BOUND_DIR}/bash"), ("host.sh", HOST_SHELL),
|
||||
("android.sh", f"{ANDROID_DIR}/sh")):
|
||||
script = cls.root / "opt" / name
|
||||
script.parent.mkdir(exist_ok=True)
|
||||
script.write_text(f"#!{interpreter}\n")
|
||||
script.chmod(0o755)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.tmp.cleanup()
|
||||
|
||||
def call(self, how, *argv):
|
||||
def call(self, how, *argv, binds=None, real_exe=None):
|
||||
hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": f"{self.hook}:{self.recorder}"}
|
||||
if binds:
|
||||
hook_env["DDNATV_BINDS"] = binds
|
||||
if real_exe:
|
||||
hook_env["DDNATV_REAL_EXE"] = real_exe
|
||||
env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_EXEC", "LD_LIBRARY_PATH")}
|
||||
if self.prefix:
|
||||
cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
|
||||
@@ -158,6 +179,42 @@ class NativeHookLdsoSpawnTest(unittest.TestCase):
|
||||
self.call(how, GUEST_LDSO, "--list", GUEST_TOOL)
|
||||
self.assertEqual([], self.library_paths)
|
||||
|
||||
def test_a_program_from_a_bind_starts_itself_again_through_proc_self_exe(self):
|
||||
bash = str(self.runtime / "bash")
|
||||
for how in ("exec", "spawn"):
|
||||
with self.subTest(how=how):
|
||||
call = self.call(how, "/proc/self/exe", "x", binds=f"/proc:/proc|{self.runtime}:{BOUND_DIR}", real_exe=bash)
|
||||
self.assertEqual(str(self.root / GUEST_LDSO.lstrip("/")), call[0])
|
||||
self.assertEqual([bash, "x"], call[-2:])
|
||||
|
||||
def test_a_rootfs_program_starts_itself_again_through_proc_self_exe(self):
|
||||
tool = str(self.root / GUEST_TOOL.lstrip("/"))
|
||||
for how in ("exec", "spawn"):
|
||||
with self.subTest(how=how):
|
||||
call = self.call(how, "/proc/self/exe", "x", binds="/proc:/proc", real_exe=tool)
|
||||
self.assertEqual(str(self.root / GUEST_LDSO.lstrip("/")), call[0])
|
||||
self.assertEqual([tool, "x"], call[-2:])
|
||||
|
||||
def test_a_script_interpreter_from_a_bind_runs_as_a_guest_program(self):
|
||||
for how in ("exec", "spawn"):
|
||||
with self.subTest(how=how):
|
||||
call = self.call(how, "/opt/bound.sh", "x", binds=f"{self.runtime}:{BOUND_DIR}")
|
||||
self.assertEqual(str(self.root / GUEST_LDSO.lstrip("/")), call[0])
|
||||
self.assertEqual([str(self.runtime / "bash"), str(self.root / "opt/bound.sh"), "x"], call[-3:])
|
||||
|
||||
def test_a_script_interpreter_outside_the_rootfs_and_its_binds_stays_on_the_host(self):
|
||||
for how in ("exec", "spawn"):
|
||||
with self.subTest(how=how):
|
||||
call = self.call(how, "/opt/host.sh", "x", binds=f"{self.runtime}:{BOUND_DIR}")
|
||||
self.assertEqual([HOST_SHELL, HOST_SHELL, str(self.root / "opt/host.sh"), "x"], call)
|
||||
|
||||
def test_an_android_interpreter_reached_through_a_bind_stays_on_the_host(self):
|
||||
sh = str(self.android / "sh")
|
||||
for how in ("exec", "spawn"):
|
||||
with self.subTest(how=how):
|
||||
call = self.call(how, "/opt/android.sh", "x", binds=f"{self.android}:{ANDROID_DIR}")
|
||||
self.assertEqual([sh, sh, str(self.root / "opt/android.sh"), "x"], call)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -12,14 +12,54 @@ PROBE = r"""
|
||||
#include <dirent.h>
|
||||
#include <fcntl.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
char cwd[4096];
|
||||
for (int i = 1; i < argc; i++) {
|
||||
struct stat st;
|
||||
if (strncmp(argv[i], "env:", 4) == 0) {
|
||||
const char *value = getenv(argv[i] + 4);
|
||||
printf("%s\t%s\n", argv[i], value ? value : "-");
|
||||
continue;
|
||||
}
|
||||
if (strncmp(argv[i], "parent:", 7) == 0) {
|
||||
char dir[4096];
|
||||
snprintf(dir, sizeof(dir), "%s", argv[i] + 7);
|
||||
char *rel = strchr(dir, '|'), *want = NULL;
|
||||
if (rel) *rel++ = 0;
|
||||
if (rel && (want = strchr(rel, '|'))) *want++ = 0;
|
||||
int fd = open(dir, O_RDONLY | O_DIRECTORY);
|
||||
struct stat expected;
|
||||
int ok = fd >= 0 && fstatat(fd, rel ? rel : "..", &st, 0) == 0 && stat(want ? want : "/", &expected) == 0;
|
||||
printf("%s\t%d\n", argv[i], ok && st.st_dev == expected.st_dev && st.st_ino == expected.st_ino);
|
||||
if (fd >= 0) close(fd);
|
||||
continue;
|
||||
}
|
||||
if (strncmp(argv[i], "fork:", 5) == 0) {
|
||||
fflush(stdout);
|
||||
pid_t pid = fork();
|
||||
if (pid == 0) {
|
||||
int p[2];
|
||||
char path[64], data[8] = "-";
|
||||
if (pipe(p) == 0 && write(p[1], "x", 1) == 1 && dup2(p[0], 63) == 63) {
|
||||
snprintf(path, sizeof(path), "%s/63", argv[i] + 5);
|
||||
int fd = open(path, O_RDONLY);
|
||||
ssize_t n = fd >= 0 ? read(fd, data, sizeof(data) - 1) : -1;
|
||||
if (n > 0) data[n] = 0;
|
||||
if (fd >= 0) close(fd);
|
||||
}
|
||||
printf("%s\t%s\n", argv[i], data);
|
||||
fflush(stdout);
|
||||
_exit(0);
|
||||
}
|
||||
waitpid(pid, NULL, 0);
|
||||
continue;
|
||||
}
|
||||
if (strncmp(argv[i], "cd:", 3) == 0) {
|
||||
int ok = chdir(argv[i] + 3) == 0 && getcwd(cwd, sizeof(cwd)) != NULL;
|
||||
printf("%s\t%s\n", argv[i], ok ? cwd : "-");
|
||||
@@ -76,6 +116,8 @@ class NativeHookMountTest(unittest.TestCase):
|
||||
cls.root = tmp / "root"
|
||||
cls.library = tmp / "storage/PC GAMES"
|
||||
(cls.root / "etc").mkdir(parents=True)
|
||||
(cls.root / "deep/er/est").mkdir(parents=True)
|
||||
(cls.root / "linked").symlink_to("deep/er/est")
|
||||
(cls.root / "etc/hostname").write_text("rootfs")
|
||||
(cls.root / "mnt/library/Some Game").mkdir(parents=True)
|
||||
(cls.root / "mnt/library/Some Game/game.txt").write_text("mount point")
|
||||
@@ -117,10 +159,11 @@ class NativeHookMountTest(unittest.TestCase):
|
||||
def tearDownClass(cls):
|
||||
cls.tmp.cleanup()
|
||||
|
||||
def run_probe(self, *args):
|
||||
binds = f"{self.library}:/mnt/library|{self.private}:/mnt/private|{self.eqlen_src}:{self.eqlen_dst}"
|
||||
def run_probe(self, *args, binds=None):
|
||||
if binds is None:
|
||||
binds = f"{self.library}:/mnt/library|{self.private}:/mnt/private|{self.eqlen_src}:{self.eqlen_dst}"
|
||||
hook_env = {"DDNATV_ROOT": str(self.root), "DDNATV_BINDS": binds, "LD_PRELOAD": str(self.hook)}
|
||||
env = {k: v for k, v in os.environ.items() if k != "LD_PRELOAD"}
|
||||
env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "LOCPATH", "GCONV_PATH")}
|
||||
if self.prefix:
|
||||
cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
|
||||
else:
|
||||
@@ -131,6 +174,18 @@ class NativeHookMountTest(unittest.TestCase):
|
||||
self.assertEqual(out.returncode, 0, out.stderr)
|
||||
return {line.split("\t")[0]: line.split("\t")[1:] for line in out.stdout.splitlines()}
|
||||
|
||||
def test_dev_fd_in_a_forked_child_names_the_child_descriptors(self):
|
||||
out = self.run_probe("fork:/dev/fd", binds="/proc/self/fd:/dev/fd")
|
||||
self.assertEqual(["x"], out["fork:/dev/fd"])
|
||||
|
||||
def test_a_mount_named_through_proc_self_root_reports_its_guest_path(self):
|
||||
arg = f"cd:{GAME}/"
|
||||
self.assertEqual(self.run_probe(arg, binds=f"/proc/self/root{self.library}:/mnt/library")[arg], [GAME])
|
||||
|
||||
def test_a_proc_mount_that_names_no_process_reports_its_guest_path(self):
|
||||
arg = "cd:/mnt/sys/kernel/"
|
||||
self.assertEqual(self.run_probe(arg, binds="/proc/self/root/proc/sys:/mnt/sys")[arg], ["/mnt/sys/kernel"])
|
||||
|
||||
def test_drive_link_stored_as_rootfs_path_reaches_the_mount(self):
|
||||
path = f"/pfx/native/dosdevices/z:{GAME}/game.txt"
|
||||
self.assertEqual(self.run_probe(path)[path], ["1", "library"])
|
||||
@@ -147,6 +202,42 @@ class NativeHookMountTest(unittest.TestCase):
|
||||
path = f"/pfx/guest/dosdevices/z:{GAME}/game.txt"
|
||||
self.assertEqual(self.run_probe(path)[path], ["1", "library"])
|
||||
|
||||
def test_glibc_locale_and_iconv_data_come_from_the_rootfs(self):
|
||||
result = self.run_probe("env:LOCPATH", "env:GCONV_PATH")
|
||||
self.assertEqual(result["env:LOCPATH"], [f"{self.root}/usr/lib/locale"])
|
||||
self.assertEqual(result["env:GCONV_PATH"], [f"{self.root}/usr/lib/aarch64-linux-gnu/gconv"])
|
||||
|
||||
def test_parent_of_root_stays_at_root(self):
|
||||
self.assertEqual(self.run_probe("parent:/")["parent:/"], ["1"])
|
||||
|
||||
def test_parent_of_root_without_mounts_stays_at_root(self):
|
||||
self.assertEqual(self.run_probe("parent:/", binds="")["parent:/"], ["1"])
|
||||
|
||||
def test_parent_of_mount_ancestor_is_guest_root(self):
|
||||
self.assertEqual(self.run_probe("parent:/mnt")["parent:/mnt"], ["1"])
|
||||
|
||||
def test_parent_walks_from_any_directory_stay_at_root(self):
|
||||
cases = ["parent:/etc|../..", "parent:/mnt/library|../../..", "parent:/|../etc/.."]
|
||||
self.assertEqual(self.run_probe(*cases), {case: ["1"] for case in cases})
|
||||
|
||||
def test_parent_walk_from_a_linked_mount_ancestor_follows_the_real_directory(self):
|
||||
binds = f"{self.library}:/linked/library"
|
||||
case = "parent:/linked|../..|/deep"
|
||||
self.assertEqual(self.run_probe(case, binds=binds)[case], ["1"])
|
||||
|
||||
def test_absolute_paths_above_root_stay_at_root(self):
|
||||
result = self.run_probe("cd:/..", "cd:/etc/../..", "/../etc/hostname")
|
||||
self.assertEqual(result["cd:/.."], [str(self.root)])
|
||||
self.assertEqual(result["cd:/etc/../.."], [str(self.root)])
|
||||
self.assertEqual(result["/../etc/hostname"], ["1", "rootfs"])
|
||||
|
||||
def test_relative_parent_of_cwd_stays_in_guest(self):
|
||||
result = self.run_probe("cd:/", "cd:..", "cd:./../..", "../etc/hostname", f"cd:{GAME}", "cd:../..")
|
||||
self.assertEqual(result["cd:.."], [str(self.root)])
|
||||
self.assertEqual(result["cd:./../.."], [str(self.root)])
|
||||
self.assertEqual(result["cd:../.."], [str(self.root / "mnt")])
|
||||
self.assertEqual(result["../etc/hostname"], ["1", "rootfs"])
|
||||
|
||||
def test_rootfs_paths_outside_mounts_are_unchanged(self):
|
||||
paths = ["/pfx/native/dosdevices/z:/etc/hostname", f"{self.root}/etc/hostname", "/etc/hostname"]
|
||||
result = self.run_probe(*paths)
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
from pathlib import Path
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from tools.tests.test_usr2_preload import runner
|
||||
|
||||
HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh"
|
||||
|
||||
PROBE = r"""
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <limits.h>
|
||||
#include <semaphore.h>
|
||||
#include <stdio.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static void show(const char *name, int ok) { printf("%s\t%d\n", name, ok); fflush(stdout); }
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
const char *name = argv[1];
|
||||
sem_t *sem = sem_open(name, O_CREAT | O_EXCL, 0600, 1);
|
||||
show("create", sem != SEM_FAILED);
|
||||
show("exclusive", sem_open(name, O_CREAT | O_EXCL, 0600, 1) == SEM_FAILED && errno == EEXIST);
|
||||
sem_t *again = sem_open(name, O_CREAT, 0600, (unsigned int)SEM_VALUE_MAX + 1);
|
||||
int value = -1;
|
||||
show("existing", again == sem && sem_getvalue(again, &value) == 0 && value == 1);
|
||||
show("too-large", sem_open("/ddsem-absent", O_CREAT, 0600, (unsigned int)SEM_VALUE_MAX + 1) == SEM_FAILED && errno == EINVAL);
|
||||
show("wait", sem_wait(sem) == 0 && sem_trywait(again) == -1 && errno == EAGAIN);
|
||||
pid_t child = fork();
|
||||
if (child == 0) {
|
||||
sem_t *other = sem_open(name, 0);
|
||||
_exit(other != SEM_FAILED && sem_post(other) == 0 && sem_close(other) == 0 ? 0 : 1);
|
||||
}
|
||||
int status = 0;
|
||||
waitpid(child, &status, 0);
|
||||
show("shared", WIFEXITED(status) && WEXITSTATUS(status) == 0 && sem_trywait(sem) == 0);
|
||||
show("close", sem_close(again) == 0 && sem_post(sem) == 0 && sem_close(sem) == 0 && sem_close(sem) == -1 && errno == EINVAL);
|
||||
show("unlink", sem_unlink(name) == 0);
|
||||
show("gone", sem_open(name, 0) == SEM_FAILED && errno == ENOENT);
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
KEEP = r"""
|
||||
#include <fcntl.h>
|
||||
#include <semaphore.h>
|
||||
int main(int argc, char **argv) { return sem_open(argv[1], O_CREAT | O_EXCL, 0640, 3) == SEM_FAILED; }
|
||||
"""
|
||||
|
||||
FORKER = r"""
|
||||
#include <fcntl.h>
|
||||
#include <pthread.h>
|
||||
#include <semaphore.h>
|
||||
#include <stdio.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static const char *name;
|
||||
static _Atomic int done;
|
||||
|
||||
static void *churn(void *arg) {
|
||||
while (!done) {
|
||||
sem_t *sem = sem_open(name, O_CREAT, 0600, 0);
|
||||
if (sem != SEM_FAILED) sem_close(sem);
|
||||
}
|
||||
return arg;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
name = argv[1];
|
||||
pthread_t thread;
|
||||
if (pthread_create(&thread, NULL, churn, NULL) != 0) return 1;
|
||||
int finished = 0;
|
||||
for (int i = 0; i < 200; i++) {
|
||||
pid_t pid = fork();
|
||||
if (pid < 0) break;
|
||||
if (pid == 0) {
|
||||
alarm(10);
|
||||
sem_t *sem = sem_open(name, O_CREAT, 0600, 0);
|
||||
_exit(sem == SEM_FAILED || sem_close(sem) != 0);
|
||||
}
|
||||
int status;
|
||||
if (waitpid(pid, &status, 0) == pid && WIFEXITED(status) && WEXITSTATUS(status) == 0) finished++;
|
||||
}
|
||||
done = 1;
|
||||
pthread_join(thread, NULL);
|
||||
sem_unlink(name);
|
||||
printf("finished\t%d\n", finished);
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
CALLS = ("create", "exclusive", "existing", "too-large", "wait", "shared", "close", "unlink", "gone")
|
||||
|
||||
|
||||
class NativeHookNamedSemaphoresTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.cc, cls.prefix = runner()
|
||||
if cls.cc is None:
|
||||
raise unittest.SkipTest("no aarch64 compiler and runner")
|
||||
cls.tmp = tempfile.TemporaryDirectory(dir="/tmp")
|
||||
tmp = Path(cls.tmp.name)
|
||||
cls.hook = tmp / "hook.so"
|
||||
subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True)
|
||||
(tmp / "probe.c").write_text(PROBE)
|
||||
cls.probe = tmp / "probe"
|
||||
subprocess.run([cls.cc, "-O1", "-pthread", "-o", str(cls.probe), str(tmp / "probe.c")], check=True)
|
||||
cls.shm = tmp / "root/tmp/shm"
|
||||
cls.shm.mkdir(parents=True)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.tmp.cleanup()
|
||||
|
||||
def run_hooked(self, program, *args):
|
||||
hook_env = {"DDNATV_ROOT": str(self.shm.parent.parent), "LD_PRELOAD": str(self.hook)}
|
||||
env = {k: v for k, v in os.environ.items() if k != "LD_PRELOAD"}
|
||||
if self.prefix:
|
||||
cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
|
||||
else:
|
||||
cmd = []
|
||||
env.update(hook_env)
|
||||
out = subprocess.run(cmd + [str(program), *args], env=env, capture_output=True, text=True, timeout=120)
|
||||
self.assertEqual(out.returncode, 0, out.stderr)
|
||||
return dict(line.split("\t") for line in out.stdout.splitlines())
|
||||
|
||||
def test_a_named_semaphore_lives_in_the_rootfs_and_is_shared_between_processes(self):
|
||||
name = f"/ddsem-{os.getpid()}"
|
||||
self.assertEqual({call: "1" for call in CALLS}, self.run_hooked(self.probe, name))
|
||||
self.assertFalse(Path(f"/dev/shm/sem.{name[1:]}").exists())
|
||||
self.assertEqual([], list(self.shm.iterdir()))
|
||||
|
||||
def test_a_child_forked_while_another_thread_opens_a_semaphore_can_open_one(self):
|
||||
source = self.probe.with_name("forker.c")
|
||||
source.write_text(FORKER)
|
||||
forker = self.probe.with_name("forker")
|
||||
subprocess.run([self.cc, "-O1", "-pthread", "-o", str(forker), str(source)], check=True)
|
||||
self.assertEqual({"finished": "200"}, self.run_hooked(forker, f"/ddsem-fork-{os.getpid()}"))
|
||||
|
||||
def test_a_created_semaphore_keeps_its_name_and_mode(self):
|
||||
name = f"ddsem-kept-{os.getpid()}"
|
||||
source = self.probe.with_name("keep.c")
|
||||
source.write_text(KEEP)
|
||||
keep = self.probe.with_name("keep")
|
||||
subprocess.run([self.cc, "-O1", "-pthread", "-o", str(keep), str(source)], check=True)
|
||||
self.run_hooked(keep, name)
|
||||
made = self.shm / f"sem.{name}"
|
||||
self.addCleanup(made.unlink)
|
||||
umask = os.umask(0)
|
||||
os.umask(umask)
|
||||
self.assertEqual([made.name], [p.name for p in self.shm.iterdir()])
|
||||
self.assertEqual(0o640 & ~umask, made.stat().st_mode & 0o777)
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -12,9 +12,12 @@ PROBE = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <fcntl.h>
|
||||
#include <limits.h>
|
||||
#include <stddef.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <sys/un.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static void show(const char *name, long ret) { printf("%s\t%d\n", name, ret >= 0); }
|
||||
@@ -40,6 +43,29 @@ int main(int argc, char **argv) {
|
||||
snprintf(q, sizeof(q), "%s/made/link", dir);
|
||||
show("symlinkat", syscall(SYS_symlinkat, "file", AT_FDCWD, q));
|
||||
show("unlinkat", syscall(SYS_unlinkat, AT_FDCWD, q, 0));
|
||||
snprintf(q, sizeof(q), "%s/made/sock", dir);
|
||||
struct sockaddr_un addr = {.sun_family = AF_UNIX}, extra = {.sun_family = AF_UNIX};
|
||||
size_t len = strlen(q);
|
||||
int fits = len + sizeof("-extra") <= sizeof(addr.sun_path);
|
||||
if (fits) {
|
||||
memcpy(addr.sun_path, q, len);
|
||||
memcpy(extra.sun_path, q, len);
|
||||
memcpy(extra.sun_path + len, "-extra", sizeof("-extra"));
|
||||
}
|
||||
int server = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0), client = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
|
||||
show("bind", fits ? syscall(SYS_bind, server, &addr, sizeof(addr)) : -1);
|
||||
listen(server, 1);
|
||||
show("connect", fits ? syscall(SYS_connect, client, &addr, sizeof(addr)) : -1);
|
||||
close(client);
|
||||
close(server);
|
||||
syscall(SYS_unlinkat, AT_FDCWD, q, 0);
|
||||
server = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0), client = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
|
||||
show("bind-length", fits ? syscall(SYS_bind, server, &extra, offsetof(struct sockaddr_un, sun_path) + len) : -1);
|
||||
listen(server, 1);
|
||||
show("connect-length", fits ? syscall(SYS_connect, client, &addr, sizeof(addr)) : -1);
|
||||
close(client);
|
||||
close(server);
|
||||
syscall(SYS_unlinkat, AT_FDCWD, q, 0);
|
||||
snprintf(q, sizeof(q), "%s/made", dir);
|
||||
show("chdir", syscall(SYS_chdir, q));
|
||||
show("cwd", getcwd(cwd, sizeof(cwd)) && strstr(cwd, "/made") ? 0 : -1);
|
||||
@@ -88,7 +114,7 @@ __attribute__((constructor)) static void early(void) { free(malloc(1)); }
|
||||
"""
|
||||
|
||||
CALLS = ("mkdirat", "openat", "truncate", "fchmodat", "utimensat", "futimens", "renameat", "renameat2", "symlinkat", "unlinkat",
|
||||
"chdir", "cwd", "unlinkat-file", "unlinkat-dir")
|
||||
"bind", "connect", "bind-length", "connect-length", "chdir", "cwd", "unlinkat-file", "unlinkat-dir")
|
||||
|
||||
|
||||
class NativeHookPathSyscallsTest(unittest.TestCase):
|
||||
@@ -97,7 +123,7 @@ class NativeHookPathSyscallsTest(unittest.TestCase):
|
||||
cls.cc, cls.prefix = runner()
|
||||
if cls.cc is None:
|
||||
raise unittest.SkipTest("no aarch64 compiler and runner")
|
||||
cls.tmp = tempfile.TemporaryDirectory()
|
||||
cls.tmp = tempfile.TemporaryDirectory(dir="/tmp")
|
||||
tmp = Path(cls.tmp.name)
|
||||
cls.hook = tmp / "hook.so"
|
||||
subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True)
|
||||
|
||||
Loaded 100 of 108 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user