Compare commits

..
144 changed files with 900 additions and 6098 deletions

No files matched your search

@@ -1,35 +0,0 @@
name: Build bionic runtime pack and DroidDeck-Bionic tool
on:
push:
paths:
- 'tools/bionic-runtime/**'
- 'tools/gamescope/patches/0117-wsi-cache-present-bypass-check.patch'
- 'tools/gamescope/patches/0119-wsi-default-images-under-limiter.patch'
- 'app/src/main/cpp/fakeinput_steam.cpp'
- 'tools/gpuload/**'
- '.github/workflows/build-bionic-runtime.yml'
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-24.04
timeout-minutes: 45
steps:
- uses: actions/checkout@v4
- name: Host tools
run: |
set -euo pipefail
sudo apt-get update -qq
sudo apt-get install -y -qq --no-install-recommends libwayland-bin libwayland-dev libx11-dev libx11-xcb-dev \
libxcb1-dev libxcb-composite0-dev libglm-dev zstd
- name: Build
run: |
set -euo pipefail
export NDK="${ANDROID_NDK_LATEST_HOME:-${ANDROID_NDK_HOME:-$ANDROID_NDK_ROOT}}"
export BUILD_NUMBER=${{ github.run_number }}
tools/bionic-runtime/build.sh "$RUNNER_TEMP/bionic-runtime" "$PWD/out"
- uses: actions/upload-artifact@v4
with:
name: droiddeck-bionic-runtime-${{ github.sha }}
path: out/*
+1 -4
View File
@@ -29,14 +29,11 @@ jobs:
persist-credentials: false
- name: Build in Arch Linux ARM
env:
GH_TOKEN: ${{ github.token }}
FEX_EXTRA_CXXFLAGS: ${{ inputs.cxxflags }}
FEX_THUNKS: ${{ inputs.thunks == 'true' && '1' || '0' }}
run: |
set -euo pipefail
FEX_VERSION=$(gh api repos/FEX-Emu/FEX/releases/latest --jq .tag_name)
echo "Building $FEX_VERSION, FEX's latest release"
docker run --rm -e FEX_VERSION="$FEX_VERSION" -e FEX_EXTRA_CXXFLAGS="$FEX_EXTRA_CXXFLAGS" -e FEX_THUNKS="$FEX_THUNKS" -v "$PWD:/work" -w /work menci/archlinuxarm:base-devel bash tools/fex/build-in-arch.sh
docker run --rm -e FEX_EXTRA_CXXFLAGS="$FEX_EXTRA_CXXFLAGS" -e FEX_THUNKS="$FEX_THUNKS" -v "$PWD:/work" -w /work menci/archlinuxarm:base-devel bash tools/fex/build-in-arch.sh
sudo chown -R "$(id -u):$(id -g)" .
- uses: actions/upload-artifact@v4
with:
+2
View File
@@ -73,6 +73,8 @@ jobs:
set -euo pipefail
git fetch --no-tags origin main
echo "base-sha=$(git rev-parse origin/main)" >> "$GITHUB_OUTPUT"
- name: Verify checked-in binary provenance
run: python3 tools/provenance/check.py
- name: Record pinned source tree
id: source
run: echo "tree-sha=$(git rev-parse 'HEAD^{tree}')" >> "$GITHUB_OUTPUT"
+1 -32
View File
@@ -205,11 +205,6 @@ static void controller_fork_prepare();
static void controller_fork_parent();
static void controller_fork_child();
// bionic: libc's own start-up calls hooked functions (access) before environ is set. Settings read
// then would be empty and cached for good, so until environ exists hooks see defaults, uncached.
extern "C" char **environ;
static bool env_ready() { return environ != nullptr; }
struct FakeConfig {
const char *hook_dir;
const char *udev_data_dir;
@@ -223,10 +218,6 @@ struct FakeConfig {
// would throw a recursive-init error there, so the fields are filled without allocating, and a
// reentry on the initializing thread gets them while other threads wait for the fork handlers.
static FakeConfig &config() {
if (!env_ready()) {
static FakeConfig early = {"/data/data/com.termux/files/home/fake-input", nullptr, false, false, false};
return early;
}
static FakeConfig cfg;
static std::atomic<int> state{0};
static __thread bool initializing __attribute__((tls_model("initial-exec")));
@@ -596,7 +587,7 @@ get_fake_input_rdev(const char *event) {
__attribute__((visibility("hidden"))) static void load_ring_paths() {
std::lock_guard<std::recursive_mutex> guard(controller_mutex());
if (ring_paths_loaded || !env_ready())
if (ring_paths_loaded)
return;
const char *spec = getenv("FAKE_EVDEV_MEMFD_PATHS");
@@ -816,25 +807,12 @@ __attribute__((visibility("hidden"))) static bool is_steam_client() {
__attribute__((visibility("hidden"))) static bool presents_steam_virtual() {
static int known;
if (known == 0) {
if (!env_ready()) return false;
const char *enabled = getenv("FAKE_EVDEV_STEAM_VIRTUAL");
known = enabled && atoi(enabled) && !is_steam_client() ? 1 : -1;
}
return known == 1;
}
// The bionic Proton layer's winebus has no udev bus, and its SDL bus skips 28de:11ff (Proton reads Steam's virtual
// pad through udev/evdev), so with FAKE_EVDEV_STEAM_PAD_AS_X360=1 other processes see that pad as a plain Xbox 360 pad.
__attribute__((visibility("hidden"))) static bool steam_pad_as_x360() {
static int known;
if (known == 0) {
if (!env_ready()) return false;
const char *v = getenv("FAKE_EVDEV_STEAM_PAD_AS_X360");
known = v && atoi(v) && !is_steam_client() ? 1 : -1;
}
return known == 1;
}
__attribute__((visibility("hidden"))) static bool
presents_xbox_triggers(const FakeController &fake) {
return fake.uinput || !is_steam_client();
@@ -1413,7 +1391,6 @@ static std::unordered_map<int, std::shared_ptr<DeckHidraw>> &deck_map() {
static bool fake_deck_enabled() {
static int enabled = -1;
if (enabled < 0 && !env_ready()) return false;
if (enabled < 0) enabled = getenv("FAKE_EVDEV_DECK") && atoi(getenv("FAKE_EVDEV_DECK")) ? 1 : 0;
return enabled == 1;
}
@@ -1421,7 +1398,6 @@ static bool fake_deck_enabled() {
__attribute__((visibility("hidden"))) static uint32_t session_pad_type() {
static int type = -1;
if (type < 0) {
if (!env_ready()) return PAD_TYPE_DECK;
const char *env = getenv("FAKE_EVDEV_PAD_TYPE");
type = env && !strcmp(env, "steamcontroller") ? PAD_TYPE_STEAM
: env && !strcmp(env, "xbox360") ? PAD_TYPE_XBOX
@@ -1494,7 +1470,6 @@ __attribute__((visibility("hidden"))) static uint64_t monotonic_us() {
static bool fake_triton_enabled() {
static int enabled = -1;
if (enabled < 0 && !env_ready()) return false;
if (enabled < 0)
enabled = fake_deck_enabled() && getenv("FAKE_EVDEV_TRITON") && atoi(getenv("FAKE_EVDEV_TRITON")) ? 1 : 0;
return enabled == 1;
@@ -2116,7 +2091,6 @@ static_assert(sizeof(TouchRingFile) <= TOUCH_RING_SIZE, "TouchRingFile layout");
__attribute__((visibility("hidden"))) static TouchRingFile *touch_ring() {
static TouchRingFile *ring = nullptr;
if (!env_ready()) return nullptr;
static std::once_flag once;
std::call_once(once, [] {
const char *path = getenv("FAKE_TOUCHCTL_RING");
@@ -2460,7 +2434,6 @@ __attribute__((constructor)) static void start_touch_controller() {
static constexpr long SYSFS_FS_MAGIC = 0x62656572;
__attribute__((visibility("hidden"))) static const char *deck_listing_dir() {
if (!env_ready()) return nullptr;
static const char *dir = getenv("FAKE_DECK_SYSFS_LISTING");
return dir && *dir ? dir : nullptr;
}
@@ -3716,10 +3689,6 @@ EXPORT int ioctl(int fd, ioctl_request_t op, ...) {
id.bustype = 0x03;
if (made) {
id = made->id;
if (steam_pad_as_x360() && id.vendor == STEAM_VIRTUAL_VENDOR_ID && id.product == STEAM_VIRTUAL_PRODUCT_ID) {
id.vendor = X360_VENDOR_ID;
id.product = X360_PRODUCT_ID;
}
} else if (presents_steam_virtual()) {
id.vendor = STEAM_VIRTUAL_VENDOR_ID;
id.product = STEAM_VIRTUAL_PRODUCT_ID;
@@ -17,11 +17,8 @@ import android.os.Looper
import android.util.Log
import android.view.Display
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
import android.view.WindowManager
import android.widget.EditText
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
@@ -2016,7 +2013,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
if (!hasFocus) triggerKeys.cancel()
if (hasFocus) {
com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false)
applyLauncherFullscreen()
@@ -2046,36 +2042,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
}
private var touchDownX = 0f
private var touchDownY = 0f
private var touchDragged = false
override fun dispatchTouchEvent(event: MotionEvent): Boolean {
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
com.droiddeck.launcher.ui.ScreenTaps.count++
touchDownX = event.rawX
touchDownY = event.rawY
touchDragged = false
}
// A drag that wanders back to where it began is still a drag, not a tap.
MotionEvent.ACTION_MOVE -> if (!touchDragged &&
kotlin.math.hypot(event.rawX - touchDownX, event.rawY - touchDownY) > ViewConfiguration.get(this).scaledTouchSlop
) touchDragged = true
MotionEvent.ACTION_CANCEL -> touchDragged = true
}
val handled = super.dispatchTouchEvent(event)
if (event.actionMasked == MotionEvent.ACTION_UP) leaveTextFieldOnOutsideTap(event)
return handled
}
private fun leaveTextFieldOnOutsideTap(event: MotionEvent) {
val field = currentFocus as? EditText ?: return
val slop = ViewConfiguration.get(this).scaledTouchSlop
if (touchDragged || kotlin.math.hypot(event.rawX - touchDownX, event.rawY - touchDownY) > slop) return
com.droiddeck.launcher.ui.releaseTextField(field, IntArray(2).also(field::getLocationOnScreen), event.rawX, event.rawY)
}
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
if (com.droiddeck.launcher.ui.AgentPet.handleBack(this, event)) return true
if (compatLaunch != null) {
@@ -2086,14 +2052,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
if (!compatLaunch!!.loading.ended && event.keyCode !in listOf(
KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE)) return true
}
if (!triggerKeys.synthesizing && triggerKeys.nativeKey(event)) return true
val tabStep = com.droiddeck.launcher.ui.dualPageStep(event)
val tabs = com.droiddeck.launcher.ui.MainTabSteps.handler
if (tabStep != null && tabs != null) {
if (controllerHaptics) com.droiddeck.launcher.ui.ControllerHaptics.onKey(this, event)
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) tabs(tabStep)
return true
}
if (controllerHaptics) com.droiddeck.launcher.ui.ControllerHaptics.onKey(this, event)
if (event.keyCode == KeyEvent.KEYCODE_BUTTON_A) com.droiddeck.launcher.ui.HeldKeys.confirm = event.action == KeyEvent.ACTION_DOWN
if (showComponents && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) {
@@ -2111,12 +2069,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
}
private val triggerKeys = com.droiddeck.launcher.input.TriggerKeys { dispatchKeyEvent(it) }
override fun dispatchGenericMotionEvent(event: android.view.MotionEvent): Boolean {
if (compatLaunch != null && !compatLaunch!!.loading.ended &&
com.droiddeck.launcher.input.PadBridge.isControllerMotionEvent(event)) return true
triggerKeys.onMotion(event)
return super.dispatchGenericMotionEvent(event)
}
@@ -2246,7 +2201,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
override fun onDestroy() {
triggerKeys.cancel()
gameLaunchRequest.incrementAndGet()
cancelCompatLaunch()
updates.unregister()
@@ -149,7 +149,7 @@ internal class ProtonMenu(
fun refreshProtons() {
refreshExperimental()
protonRows = ProtonExtras.offered(activity).map {
protonRows = ProtonExtras.tools.map {
val all = ProtonExtras.installedAll(activity, it)
ProtonRow(it.id, it.name, all.lastOrNull(), ProtonExtras.queued(activity, it), all, ProtonExtras.update(activity, it))
}
@@ -2846,7 +2846,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (!SessionState.running) {
SessionEvents.transition(SessionPhase.STARTING_COMPOSITOR, "compositor.starting")
}
val output = CompositorHost.prepare(this)
val runtimeDir = File(filesDir, ".wayland-rt").apply { mkdirs() }
FileUtils.copyAsset(this, "wayland/keymap.xkb", File(runtimeDir, "keymap.xkb"))
com.droiddeck.launcher.input.VrControllers.publish(this)
val turnip = TurnipDriver(this)
com.droiddeck.launcher.gpu.DriverSetupLog.write(this, "surface.driver-setup")
if (!CompositorHost.isStarted) {
CompositorHost.displayChoice = SessionPrefs.androidDriver(this)
com.droiddeck.launcher.gpu.AutoDriverTrial.displayStarting(this, SessionPrefs.androidDriver(this))
}
val driverId = if (CompositorHost.isStarted) null else turnip.install()
val previous = SessionState.outputSize
val live = windowOutputSize(holder.surfaceFrame.width(), holder.surfaceFrame.height())
@@ -2873,7 +2883,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
pushCardboard(activeCardboard)
WaylandCompositor.nativeSetCardboardPoseFile(File(filesDir, ".wayland-rt/droiddeck-headpose").path)
com.droiddeck.launcher.glasses.SpatialTracking.attachPublisher(File(filesDir, ".wayland-rt/droiddeck-spatialpose").path)
if (!SessionState.running) CompositorHost.logToSession(this)
if (!SessionState.running) {
val waylandLog = File(SessionPaths.beginOrCurrent(this), "wayland.log")
WaylandCompositor.setSessionLogFile(waylandLog)
try {
android.system.Os.setenv("DD_WAYLAND_LOG", waylandLog.path, true)
} catch (e: Exception) {
Log.w(TAG, "could not point the compositor's log at $waylandLog", e)
}
}
val mode = hdrPrefMode()
if (probe != null) {
WaylandCompositor.nativeSetHdrDisplay(
@@ -2893,8 +2911,19 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
)
Log.i(TAG, "hdr: " + (if (tonemap) "tone-mapped (${probe.reason})" else if (capable) "available" else "unavailable") + " · display ${probe.formats.ifEmpty { "SDR" }}")
}
if (!SessionState.running) CompositorHost.applyHdr(this, mode)
CompositorHost.start(this, output, holder.surface, size, refreshHz(holder), outputFpsLimit())
if (!SessionState.running) {
val on = SessionState.hdrCapable && SessionPrefs.hdr(this, mode)
SessionState.hdr = on
WaylandCompositor.nativeSetHdrOutput(on)
WaylandCompositor.nativeSetZeroCopy(on || SessionPrefs.zeroCopy(this, mode))
Log.i(TAG, "hdr: " + (if (on) "on" else "off") + " for this $mode session")
}
com.droiddeck.launcher.gpu.DriverSetupLog.write(this, "compositor.start driver=$driverId")
CompositorHost.startOrAttach(
this, holder.surface, runtimeDir.path,
driverId?.let { turnip.driverPath(it) }, driverId?.let { turnip.libraryName(it) },
applicationInfo.nativeLibraryDir, size.first, size.second, refreshHz(holder), outputFpsLimit(),
)
onOutputAttached(holder)
if (SessionState.running && size != previous) {
Log.i(TAG, "output resized: ${previous.first}x${previous.second} -> ${size.first}x${size.second} on a new surface")
@@ -4447,7 +4476,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun pickSecondScreenMode(mode: SecondScreenMode) {
typingReturnMode = null
automaticPanel = false
SessionState.bottomMenu = false
if (mode != SecondScreenMode.NONE) SessionPrefs.setSecondScreenPanel(this, desktopSession, mode.id)
selectSecondScreenMode(mode)
}
@@ -31,20 +31,17 @@ object OnScreenLayout {
private const val TOLERANCE = .01f
private const val KEYBOARD_ID = "builtin:keyboard"
private val REAR = setOf(InputControl.L4, InputControl.L5, InputControl.R4, InputControl.R5)
private val BAR = setOf(InputControl.GUIDE, InputControl.QAM)
fun elements(context: Context, saved: SavedInputLayout?, width: Int, height: Int, safe: Rect,
buttonsOnly: Boolean = false, dock: Dock? = null, rearButtons: Boolean? = null,
trackpads: Boolean? = null): List<InputSurfaceElement> {
if (saved == null) return emptyList()
if (width <= 0 || height <= 0) return saved.elements
val layout = oriented(saved, dock?.portrait ?: (height > width))
val layout = oriented(saved, width, height)
val stored = layout.elements
val generator = LegacyGamepadLayout(context, width, height, safe, layout.scale)
val (reference, matched) = reference(context, layout, width, height)
if (buttonsOnly && dock == null) return generator.buttonsOnly(stored) + fit(stored.filter { it.alwaysShown }, reference.first, reference.second, width, height, safe)
if (dock?.portrait == true && !dock.grips && !matched && layout.aspect > 0f && layout.aspect < 1f && stored.any(::isGamepad))
return cluster(stored.filterNot { it.alwaysShown || isGamepad(it) && (it.id == KEYBOARD_ID || it.control in BAR) }, layout.aspect, width, height, safe)
val generated = matched || PadKit.forOverlay(context, layout) != null && stored.any(::isGamepad) &&
(dock != null || height > width && layout.aspect >= 1f || height <= width && layout.aspect > 0f && layout.aspect < 1f)
val gamepad = if (generated) stored.filter(::isGamepad) else emptyList()
@@ -73,9 +70,8 @@ object OnScreenLayout {
.place(ordered, lowerShortcuts = generated, rearButtons = rearButtons, trackpads = trackpads)
}
fun oriented(layout: SavedInputLayout, width: Int, height: Int): SavedInputLayout = oriented(layout, height > width)
private fun oriented(layout: SavedInputLayout, portrait: Boolean): SavedInputLayout {
fun oriented(layout: SavedInputLayout, width: Int, height: Int): SavedInputLayout {
val portrait = height > width
if (layout.rotated.isEmpty() || layout.aspect <= 0f || (layout.aspect < 1f) == portrait || (layout.rotatedAspect < 1f) != portrait) return layout
val rotated = layout.rotated.associateBy { it.id }
return layout.copy(elements = layout.elements.map { e -> rotated[e.id]?.let { e.copy(x = it.x, y = it.y, width = it.width, height = it.height) } ?: e } +
@@ -135,23 +131,6 @@ object OnScreenLayout {
}
}
private fun cluster(elements: List<InputSurfaceElement>, aspect: Float, width: Int, height: Int, safe: Rect): List<InputSurfaceElement> {
if (elements.isEmpty()) return elements
val left = elements.minOf { it.x } * aspect
val top = elements.minOf { it.y }
val spanX = (elements.maxOf { it.x + it.width } * aspect - left).coerceAtLeast(.0001f)
val spanY = (elements.maxOf { it.y + it.height } - top).coerceAtLeast(.0001f)
val w = (width - safe.left - safe.right).toFloat().coerceAtLeast(1f)
val h = (height - safe.top - safe.bottom).toFloat().coerceAtLeast(1f)
val scale = minOf(w / aspect, w / spanX, h / spanY)
val originX = safe.left + (w - spanX * scale) / 2f - left * scale
val originY = safe.top + (h - spanY * scale) / 2f - top * scale
return elements.map { e ->
e.copy(x = (originX + e.x * aspect * scale) / width, y = (originY + e.y * scale) / height,
width = e.width * aspect * scale / width, height = e.height * scale / height)
}
}
private fun anchor(start: Float, size: Float, reference: Float, actual: Float, scale: Float): Float {
val centre = start + size / 2f
val scaled = size * reference * scale
@@ -1,81 +0,0 @@
package com.droiddeck.launcher.input
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import android.view.InputDevice
import android.view.KeyEvent
import android.view.MotionEvent
internal class TriggerKeys(private val dispatch: (KeyEvent) -> Unit) {
private class Pull {
val held = BooleanArray(2)
val sent = BooleanArray(2)
}
private val handler = Handler(Looper.getMainLooper())
private val keyed = HashSet<Int>()
private val pulls = HashMap<Int, Pull>()
var synthesizing = false
private set
/** True when this real trigger key belongs to a pull that already went out as a synthetic press. */
fun nativeKey(event: KeyEvent): Boolean {
val i = index(event.keyCode) ?: return false
keyed += event.deviceId
val pull = pulls[event.deviceId] ?: return false
if (!pull.sent[i]) return false
if (event.action == KeyEvent.ACTION_UP) pull.sent[i] = false
return true
}
fun onMotion(event: MotionEvent) {
if (event.source and InputDevice.SOURCE_JOYSTICK != InputDevice.SOURCE_JOYSTICK || event.action != MotionEvent.ACTION_MOVE) return
val device = event.deviceId
if (device in keyed) return
val pull = pulls.getOrPut(device) { Pull() }
update(pull, 0, maxOf(event.getAxisValue(MotionEvent.AXIS_LTRIGGER), event.getAxisValue(MotionEvent.AXIS_BRAKE)), event)
update(pull, 1, maxOf(event.getAxisValue(MotionEvent.AXIS_RTRIGGER), event.getAxisValue(MotionEvent.AXIS_GAS)), event)
}
fun cancel() {
handler.removeCallbacksAndMessages(null)
pulls.clear()
}
private fun update(pull: Pull, i: Int, value: Float, event: MotionEvent) {
if (!pull.held[i] && value >= PRESS) {
pull.held[i] = true
pull.sent[i] = false
val device = event.deviceId
val source = event.source
// A pad that also sends trigger keys delivers them close to the axis; waiting lets that key win.
handler.postDelayed({
if (device !in keyed && pulls[device] === pull) {
pull.sent[i] = true
press(CODES[i], device, source)
}
}, KEY_WAIT_MS)
} else if (pull.held[i] && value <= RELEASE) pull.held[i] = false
}
private fun press(code: Int, device: Int, source: Int) {
val now = SystemClock.uptimeMillis()
synthesizing = true
try {
dispatch(KeyEvent(now, now, KeyEvent.ACTION_DOWN, code, 0, 0, device, 0, 0, source))
dispatch(KeyEvent(now, now, KeyEvent.ACTION_UP, code, 0, 0, device, 0, 0, source))
} finally {
synthesizing = false
}
}
private fun index(code: Int): Int? = CODES.indexOf(code).takeIf { it >= 0 }
private companion object {
val CODES = intArrayOf(KeyEvent.KEYCODE_BUTTON_L2, KeyEvent.KEYCODE_BUTTON_R2)
const val PRESS = 0.6f
const val RELEASE = 0.3f
const val KEY_WAIT_MS = 40L
}
}
@@ -1,216 +1,10 @@
package com.droiddeck.launcher.runtime
import android.content.Context
import com.droiddeck.launcher.agent.AgentException
import com.droiddeck.launcher.agent.AgentGuest
import org.json.JSONArray
import org.json.JSONObject
import java.time.Instant
object CurseForgeApp {
const val NAME = "CurseForge"
const val FEED = "https://curseforge.overwolf.com/electron/linux/latest-linux.yml"
internal const val WOW = 1
const val HELPER = "/usr/local/bin/droiddeck-curseforge"
private const val READY_MS = 120_000L
private const val INSTALL_MS = 300_000L
enum class Start { READY, BUSY, NO_DISPLAY, FAILED }
class Started(val state: Start, val inspector: String? = null)
private val INSPECTOR = Regex("ws://127\\.0\\.0\\.1:[0-9]{4,5}/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
class Failure(message: String, val code: String? = null) : Exception(message) {
val gone get() = code == "DEVTOOLS_UNREACHABLE"
}
fun find(apps: List<UserApps.App>): UserApps.App? = apps.firstOrNull { it.feed == FEED }
fun request(): UserApps.Request = UserApps.Request(UserApps.Source.Feed(FEED), NAME, null)
internal fun dir(app: UserApps.App): String? = app.args.firstOrNull()?.takeIf { it.startsWith("/") }
fun holdArgs(app: UserApps.App): List<String>? = dir(app)?.let { listOf("hold", it) }
internal fun inspectorUrl(stdout: String): String? = stdout.lineSequence().map { it.trim() }.lastOrNull { INSPECTOR.matches(it) }
internal fun startState(exitCode: Int): Start = when (exitCode) {
0 -> Start.READY
3 -> Start.BUSY
4 -> Start.NO_DISPLAY
else -> Start.FAILED
}
internal fun sortOf(sort: WowAddonCatalog.Sort): Pair<Int, Int> = when (sort) {
WowAddonCatalog.Sort.POPULAR -> 8 to 2
WowAddonCatalog.Sort.UPDATED -> 16 to 2
WowAddonCatalog.Sort.NAME -> 1 to 1
WowAddonCatalog.Sort.DOWNLOADS -> 7 to 2
}
internal fun searchRequest(guid: String, text: String, sort: WowAddonCatalog.Sort, page: Int): JSONObject {
val (column, order) = sortOf(sort)
return JSONObject().put("gameId", WOW).put("searchText", text.trim()).put("page", page + 1)
.put("sortColumn", column).put("sortOrder", order).put("gameInstanceGuid", guid)
}
internal fun installRequest(guid: String, projectId: String): JSONObject =
JSONObject().put("instanceId", guid).put("projectId", projectId.toLong()).put("categoryClassId", 1)
.put("installLatestFile", true).put("installSource", 4)
private const val SERVICES = """(() => {
const seen = new Set(), out = {};
const walk = (o, d) => {
if (!o || typeof o !== 'object' || seen.has(o) || d > 4) return;
seen.add(o);
if (typeof o._nameOfService === 'string') { out[o._nameOfService] = o; return; }
let keys; try { keys = Object.keys(o); } catch (e) { return; }
for (const k of keys.slice(0, 4000)) {
let v; try { v = o[k]; } catch (e) { continue; }
if (v instanceof Map) { for (const x of v.values()) walk(x, d + 1); } else walk(v, d + 1);
}
};
walk(window, 0);
return out;
})()"""
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)}]; " +
"if (!s || typeof s[$name] !== 'function') return { missing: true }; " +
"return { value: $run }; })()"
return "(() => { const w = require('electron').BrowserWindow.getAllWindows()" +
".find(w => !w.isDestroyed() && w.webContents.getURL().includes('desktop.html')); " +
"if (!w) return JSON.stringify({ missing: true }); " +
"return w.webContents.executeJavaScript(${JSONObject.quote(inner)}).then(v => JSON.stringify(v)); })()"
}
internal fun unwrap(answer: JSONObject): Any? {
if (!answer.optBoolean("ok")) {
val error = answer.optJSONObject("error")
throw Failure(error?.optString("message")?.takeIf { it.isNotBlank() } ?: answer.toString(), error?.optString("code")?.takeIf { it.isNotBlank() })
}
val text = answer.opt("value") as? String ?: throw Failure("CurseForge gave no answer")
val reply = JSONObject(text)
if (reply.optBoolean("missing")) throw Failure("CurseForge is not ready")
return reply.opt("value")
}
internal fun parseSearch(value: Any?): WowAddonCatalog.Page {
val reply = value as? JSONObject ?: throw Failure("CurseForge search failed")
if (reply.has("success") && !reply.optBoolean("success")) throw Failure("CurseForge search failed")
val mods = reply.optJSONArray("mods") ?: JSONArray()
val items = (0 until mods.length()).mapNotNull { mods.optJSONObject(it) }.mapNotNull { mod ->
val id = mod.optLong("id", 0L).takeIf { it > 0 } ?: return@mapNotNull null
val name = mod.optString("name").takeIf { it.isNotBlank() } ?: return@mapNotNull null
val author = mod.optJSONObject("primaryAuthor")?.optString("name")?.takeIf { it.isNotBlank() }
?: mod.optJSONArray("authors")?.optJSONObject(0)?.optString("name").orEmpty()
val date = mod.optJSONObject("updateVersion")?.optString("fileDate")?.takeIf { it.isNotBlank() }
?: mod.optString("projectLatestReleaseDate")
WowAddonCatalog.Addon(
id.toString(), name, author, "", mod.optLong("downloads", 0L).coerceAtLeast(0L),
runCatching { Instant.parse(date).toEpochMilli() }.getOrDefault(0L),
mod.optString("thumbnailUrl").takeIf { WowAddonCatalog.isHttps(it) },
)
}
val page = reply.optJSONObject("pagination")
val more = page != null && page.optInt("index") + page.optInt("resultCount") < page.optInt("totalCount")
return WowAddonCatalog.Page(items, more)
}
internal fun samePath(a: String, b: String) = a.trimEnd('/') == b.trimEnd('/')
internal fun instanceFor(instances: Any?, flavorDir: String, detected: String?): String? {
val list = instances as? JSONArray
val match = list?.let { all ->
(0 until all.length()).mapNotNull { all.optJSONObject(it) }
.firstOrNull { samePath(it.optString("installPath"), flavorDir) }?.optString("guid")
}
if (list != null && list.length() > 0) return match?.takeIf { it.isNotBlank() }
return detected?.takeIf { it.isNotBlank() }
}
internal fun projectIds(value: Any?): Set<String> {
val list = value as? JSONArray ?: return emptySet()
return (0 until list.length()).mapNotNull { list.opt(it)?.toString()?.takeIf { id -> id.isNotBlank() && id != "null" } }.toSet()
}
private fun call(context: Context, inspector: String, service: String, method: String, args: JSONArray?, timeoutMs: Long, pick: String = "r => r"): Any? {
val request = JSONObject().put("kind", "cdp").put("inspector", inspector).put("commandLineApi", true)
.put("expression", expression(service, method, args, pick)).put("timeout", timeoutMs / 1000.0)
return unwrap(AgentGuest.call(context, request, timeoutMs + 3_000, trusted = true))
}
private fun helper(context: Context, command: String, dir: String, timeoutMs: Long): JSONObject? {
val request = JSONObject().put("kind", "exec").put("argv", JSONArray(listOf(HELPER, command, dir))).put("timeout", timeoutMs / 1000.0)
return runCatching { AgentGuest.call(context, request, timeoutMs + 5_000, trusted = true) }.getOrNull()
}
fun start(context: Context, app: UserApps.App): Started {
val dir = dir(app) ?: return Started(Start.FAILED)
val answer = helper(context, "start", dir, 90_000)
if (answer == null || !answer.optBoolean("ok") || answer.optBoolean("timedOut")) {
stop(context, app, null)
return Started(Start.FAILED)
}
val state = startState(answer.optInt("exitCode", -1))
if (state == Start.BUSY || state == Start.NO_DISPLAY) return Started(state)
val inspector = inspectorUrl(answer.optJSONObject("stdout")?.optString("text").orEmpty())
if (state != Start.READY || inspector == null) {
stop(context, app, null)
return Started(Start.FAILED)
}
val deadline = System.currentTimeMillis() + READY_MS
while (System.currentTimeMillis() < deadline) {
val ready = runCatching { call(context, inspector, "InstalledProjectsAppService", "installAddon", null, 10_000) }
if (ready.isSuccess) return Started(Start.READY, inspector)
val error = ready.exceptionOrNull()
if (error is AgentException && error.code == "NO_ACTIVE_SESSION") break
Thread.sleep(1_000)
}
stop(context, app, inspector)
return Started(Start.FAILED)
}
fun stop(context: Context, app: UserApps.App, inspector: String?) {
val dir = dir(app) ?: return
if (inspector != null) runCatching { call(context, inspector, "CoreService", "shutdown", JSONArray(), 30_000, "r => true") }
helper(context, "stop", dir, 30_000)
}
private fun connect(context: Context, inspector: String) {
call(context, inspector, "CoreService", "connect", JSONArray(), 120_000, "r => true")
}
fun instance(context: Context, inspector: String, root: String, flavorDir: String): String {
connect(context, inspector)
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")
}
fun search(context: Context, inspector: String, guid: String, text: String, sort: WowAddonCatalog.Sort, page: Int): WowAddonCatalog.Page =
parseSearch(call(context, inspector, "ProjectAppService", "search", JSONArray().put(searchRequest(guid, text, sort, page)), 60_000))
fun installed(context: Context, inspector: String, guid: String): Set<String> {
connect(context, inspector)
return projectIds(call(context, inspector, "InstalledProjectsAppService", "getProjects", JSONArray().put(guid), 30_000, "r => (r || []).map(p => String(p.id))"))
}
fun install(context: Context, inspector: String, guid: String, projectId: String): Boolean {
connect(context, inspector)
if (call(context, inspector, "InstalledProjectsAppService", "installAddon", JSONArray().put(installRequest(guid, projectId)), 300_000) != true) return false
val deadline = System.currentTimeMillis() + INSTALL_MS
while (System.currentTimeMillis() < deadline) {
val listed = runCatching { installed(context, inspector, guid) }
val error = listed.exceptionOrNull()
if (error is Failure && error.gone || error is AgentException && error.code == "NO_ACTIVE_SESSION") throw error
if (projectId in listed.getOrDefault(emptySet())) return true
Thread.sleep(1_000)
}
return false
}
}
@@ -93,7 +93,8 @@ object WowAddonCatalog {
Client(folder, version?.let(::flavorOf) ?: folderFamily(folder))
fun client(target: WowAddons.Target): Client {
return client(target.flavor, WowAddons.flavorDir(target)?.let(::clientVersion))
val dir = target.addOns.parentFile?.parentFile
return client(target.flavor, dir?.let(::clientVersion))
}
internal fun flavorMatches(flavors: Set<String>?, family: String?): Boolean =
@@ -28,14 +28,6 @@ object WowAddons {
class TooLarge : IOException()
fun changed() {
imports++
}
fun flavorDir(target: Target): File? = target.addOns.parentFile?.parentFile
fun root(target: Target): File? = flavorDir(target)?.parentFile
class Target(val flavor: String, val addOns: File)
class Addon(val name: String, val root: String)
@@ -1,119 +0,0 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.graphics.PixelFormat
import android.media.ImageReader
import android.os.Handler
import android.os.Looper
import android.util.Log
import com.droiddeck.launcher.agent.AgentGuest
import com.droiddeck.launcher.runtime.LinuxRuntimeInstaller
import com.droiddeck.launcher.storage.StorageState
import com.droiddeck.launcher.wayland.CompositorHost
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
object BackgroundSession {
private const val TAG = "BackgroundSession"
private const val WIDTH = 1280
private const val HEIGHT = 720
private const val REFRESH_HZ = 60f
private const val BEGIN_MS = 30_000L
private const val AGENT_MS = 120_000L
private const val STOP_MS = 30_000L
private val ended = setOf(SessionPhase.IDLE, SessionPhase.FAILED)
private val main by lazy { Handler(Looper.getMainLooper()) }
private var reader: ImageReader? = null
fun start(context: Context, program: String, args: List<String>): String? {
val app = context.applicationContext
val claim = AtomicBoolean(false)
val began = CountDownLatch(1)
var own: String? = null
main.post {
if (claim.compareAndSet(false, true)) {
own = runCatching { begin(app, program, args) }
.onFailure { Log.w(TAG, "could not start a hidden session for $program", it) }
.getOrNull()
}
began.countDown()
}
if (!began.await(BEGIN_MS, TimeUnit.MILLISECONDS) && claim.compareAndSet(false, true)) return null
began.await()
val session = own ?: return null
val deadline = System.currentTimeMillis() + AGENT_MS
val settle = System.currentTimeMillis() + 5_000
while (System.currentTimeMillis() < deadline) {
if (SessionState.sessionId != session) return null
if (SessionState.running && AgentGuest.hello(app) != null && SessionState.sessionId == session) return session
if (SessionState.phase == SessionPhase.FAILED) break
if (!SessionState.running && SessionState.phase in ended && System.currentTimeMillis() > settle) break
Thread.sleep(250)
}
stop(app, session)
return null
}
fun stop(context: Context, session: String) {
val app = context.applicationContext
if (SessionState.sessionId != session) return
main.post { if (SessionState.sessionId == session) SessionService.stop(app) }
val deadline = System.currentTimeMillis() + STOP_MS
while (live(session) && System.currentTimeMillis() < deadline) Thread.sleep(250)
if (!live(session)) {
main.post { release() }
return
}
Thread {
while (live(session)) Thread.sleep(1_000)
main.post { release() }
}.start()
}
private fun live(session: String) =
SessionState.sessionId == session && (SessionState.running || SessionState.phase !in ended)
private fun begin(context: Context, program: String, args: List<String>): String? {
if (SessionState.running || SessionState.phase !in ended || LinuxRuntimeInstaller.isBusy() ||
SessionState.installing != null || StorageState.cleaning) return null
release()
SessionEvents.begin(context, SessionService.MODE_RUN, SessionPaths.label(SessionService.MODE_RUN, program))
val session = SessionState.sessionId ?: return null
SessionState.stopRequested = false
SessionEvents.transition(SessionPhase.STARTING_COMPOSITOR, "compositor.starting")
var requested = false
try {
val output = CompositorHost.prepare(context)
val size = WIDTH to HEIGHT
SessionState.outputSize = size
SessionState.refreshHz = REFRESH_HZ
CompositorHost.logToSession(context)
CompositorHost.applyHdr(context, SessionPrefs.prefMode(SessionService.MODE_RUN))
val offscreen = ImageReader.newInstance(WIDTH, HEIGHT, PixelFormat.RGBA_8888, 2)
reader = offscreen
offscreen.setOnImageAvailableListener({ it.acquireLatestImage()?.close() }, main)
CompositorHost.start(context, output, offscreen.surface, size, REFRESH_HZ, 0)
CompositorHost.detach(offscreen.surface)
SessionEvents.record("compositor.started")
SessionEvents.transition(SessionPhase.STARTING_GUEST, "guest.starting")
requested = true
SessionService.start(context, SessionService.MODE_RUN, program, programArgs = args.toTypedArray())
return session
} catch (e: Exception) {
if (requested) SessionService.stop(context)
if (!SessionState.running) {
reader?.close()
reader = null
SessionEvents.transition(SessionPhase.FAILED, "hidden.failed", mapOf("error" to e.toString()))
}
throw e
}
}
private fun release() {
if (SessionState.running) return
reader?.close()
reader = null
}
}
@@ -88,8 +88,8 @@ object ComponentUpdater {
logLines(context).mapNotNull { STAMP.find(it)?.groupValues?.get(1) }.maxOrNull() ?: "0"
private fun lineOf(context: Context, state: JSONObject, p: ComponentsManager.Proton, comp: String): ComponentUpdates.Line? {
if (!ComponentUpdates.autoFollows(p, comp) || !ComponentsManager.supports(p, comp)) return null
if (comp == "fex") return ComponentUpdates.fexLine(p)
if (!ComponentUpdates.follows(p) || !ComponentsManager.supports(p, comp)) return null
if (comp == "fex") return ComponentUpdates.line("fex", false)
val key = "${p.id}|${p.version}"
val flavors = state.obj("flavors").obj(key)
val arm64ec = if (flavors.has(comp)) flavors.optBoolean(comp) else ComponentsManager.arm64ec(context, p, comp)?.also { flavors.put(comp, it) }
@@ -13,7 +13,7 @@ object ComponentUpdates {
const val BOOTED_SECONDS = 60L
const val FAILED_BOOTS_BEFORE_ROLLBACK = 2
data class Line(val key: String, val comp: String, val prefix: String, val release: String = ComponentsManager.DD_NIGHTLY)
data class Line(val key: String, val comp: String, val prefix: String)
val LINES = listOf(
Line("dxvk", "dxvk", "DD-dxvk-"),
@@ -21,19 +21,12 @@ object ComponentUpdates {
Line("vkd3d", "vkd3d", "DD-vkd3d-proton-"),
Line("vkd3d-arm64ec", "vkd3d", "DD-vkd3d-proton-arm64ec-"),
Line("fex", "fex", "DD-FEXCore-"),
Line("fex-bionic", "fex", "FEXCore-", ComponentsManager.DD_BIONIC),
)
private val OWN_PREFIX = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }.prefix
fun follows(p: ComponentsManager.Proton): Boolean = !p.valve && p.dir.name.startsWith(OWN_PREFIX)
fun autoFollows(p: ComponentsManager.Proton, comp: String): Boolean =
follows(p) || (comp == "fex" && !p.valve && ComponentsManager.bionicTool(p.dir.name))
fun fexLine(p: ComponentsManager.Proton): Line =
if (ComponentsManager.bionicTool(p.dir.name)) LINES.first { it.release == ComponentsManager.DD_BIONIC } else line("fex", false)
fun ownId(protonId: String): Boolean = protonId.startsWith(ComponentsManager.safeName(OWN_PREFIX))
fun strays(
@@ -41,8 +34,8 @@ object ComponentUpdates {
choices: Map<String, Map<String, ComponentsManager.Choice>>,
placed: Set<String>,
): List<Pair<ComponentsManager.Proton, String>> =
protons.flatMap { p ->
choices[p.id].orEmpty().filter { (comp, c) -> !autoFollows(p, comp) && !c.auto && c.protonVersion == p.version && c.file in placed }.keys.map { p to it }
protons.filterNot(::follows).flatMap { p ->
choices[p.id].orEmpty().filter { (_, c) -> !c.auto && c.protonVersion == p.version && c.file in placed }.keys.map { p to it }
}
fun unseen(
@@ -60,14 +53,13 @@ object ComponentUpdates {
fun pick(items: List<ComponentsManager.CatalogItem>, line: Line, bad: Set<String>): ComponentsManager.CatalogItem? {
val newestBad = bad.filter { belongs(it, line) }.maxWithOrNull { a, b -> ProtonExtras.compareVersions(a, b) }
return items.filter { it.release == line.release && it.comp == line.comp && belongs(it.file, line) }
return items.filter { it.release == ComponentsManager.DD_NIGHTLY && it.comp == line.comp && belongs(it.file, line) }
.filter { newestBad == null || ProtonExtras.compareVersions(it.file, newestBad) > 0 }
.maxWithOrNull { a, b -> ProtonExtras.compareVersions(a.file, b.file) }
}
fun belongs(file: String, line: Line): Boolean =
file.startsWith(line.prefix) && file.removePrefix(line.prefix).firstOrNull()?.isDigit() == true &&
(line.comp != "fex" || ComponentsManager.bionicFex(file) == (line.release == ComponentsManager.DD_BIONIC))
file.startsWith(line.prefix) && file.removePrefix(line.prefix).firstOrNull()?.isDigit() == true
fun arm64ec(pe: ByteArray): Boolean? = runCatching {
val b = ByteBuffer.wrap(pe).order(ByteOrder.LITTLE_ENDIAN)
@@ -169,7 +161,7 @@ object ComponentUpdates {
fun stale(line: Line?, owned: Set<String>, stored: List<String>, keep: Set<String>, current: String, bad: Set<String> = emptySet()): List<String> {
val ranked = line?.takeIf { belongs(current, it) }
fun newer(file: String) = ranked != null && belongs(file, ranked) && ProtonExtras.compareVersions(file, current) > 0
return (owned + stored.filter { ranked != null && ranked.release == ComponentsManager.DD_NIGHTLY && belongs(it, ranked) })
return (owned + stored.filter { ranked != null && belongs(it, ranked) })
.filter { it !in keep && ((it in bad && it in owned) || !newer(it)) }.distinct()
}
}
@@ -29,7 +29,6 @@ object ComponentsManager {
private const val NIGHTLIES = "The412Banner/Nightlies"
private const val DD_COMPONENTS = "Droid-Deck/DroidDeck-Components"
internal const val DD_NIGHTLY = "linux-nightly"
internal const val DD_BIONIC = "bionic-stable"
private val RELEASES = linkedMapOf(
"FexCore-Linux" to "fex",
"Dxvk-Linux" to "dxvk",
@@ -38,9 +37,9 @@ object ComponentsManager {
"Vkd3d-proton-Linux" to "vkd3d",
)
private val NIGHTLY_PREFIXES = linkedMapOf("DD-dxvk-" to "dxvk", "DD-vkd3d-proton-" to "vkd3d", "DD-FEXCore-" to "fex")
private val SOURCES = RELEASES.keys.map { NIGHTLIES to it } + (DD_COMPONENTS to DD_NIGHTLY) + (DD_COMPONENTS to DD_BIONIC)
private val SOURCES = RELEASES.keys.map { NIGHTLIES to it } + (DD_COMPONENTS to DD_NIGHTLY)
private val DOWNLOAD_REPOS = listOf(NIGHTLIES, DD_COMPONENTS)
private val TYPES = mapOf("FEXCore-Linux" to "fex", "FEXCore-Bionic" to "fex", "DXVK-Linux" to "dxvk", "VKD3D-Linux" to "vkd3d")
private val TYPES = mapOf("FEXCore-Linux" to "fex", "DXVK-Linux" to "dxvk", "VKD3D-Linux" to "vkd3d")
private val TYPE_OF = mapOf("fex" to "FEXCore-Linux", "dxvk" to "DXVK-Linux", "vkd3d" to "VKD3D-Linux")
val COMPONENTS = listOf("fex", "dxvk", "vkd3d")
val LABEL = mapOf("fex" to "FEX", "dxvk" to "DXVK", "vkd3d" to "VKD3D-Proton")
@@ -202,34 +201,8 @@ object ComponentsManager {
COMPONENTS.mapNotNull { comp -> profile.optString(comp).takeIf(String::isNotEmpty)?.let { comp to it } }.toMap()
}
fun setGameComponent(context: Context, scope: String, comp: String, file: String?) {
fun setGameComponent(context: Context, scope: String, comp: String, file: String?) =
setGameComponent(context, scope, comp, file) { runtimeManaged(context, it) }
if (comp == "fex" && file != null) fetchFexTwin(context, safeName(file))
}
// Twin downloads in flight: one worker per name, so two profile changes cannot share one partial download.
private val twinDownloads = HashSet<String>()
private fun fetchFexTwin(context: Context, file: String) {
val twin = fexTwin(file) ?: return
if (protons(context).all { fexFits(it.dir.name, file) }) return
synchronized(lock) { if (isStored(context, twin) || !twinDownloads.add(twin)) return }
val app = context.applicationContext
Thread({
try {
runCatching {
val item = catalogItem(app, twin, if (bionicFex(twin)) DD_BIONIC else "FexCore-Linux")
if (item == null) Log.i(TAG, "$twin is not listed")
else {
download(app, item) {}
republish(app)
}
}.onFailure { Log.w(TAG, "download $twin", it) }
} finally {
synchronized(lock) { twinDownloads.remove(twin) }
}
}, "fex-twin").start()
}
internal fun setGameComponent(context: Context, scope: String, comp: String, file: String?, managed: (String) -> Boolean) = synchronized(lock) {
require(scope.matches(Regex("[1-9][0-9]{0,9}")) && scope.toLong() <= 4294967295L)
@@ -440,7 +413,7 @@ object ComponentsManager {
}
}
require(File(staged, "files").isDirectory) { "${wcp.name} has no files/" }
if (comp == "fex" && !bionicTool(dir.name)) FEX_FILES.filter { it.endsWith(".so") && !File(staged, it).isFile }.forEach { File(dir, it).delete() }
if (comp == "fex") FEX_FILES.filter { it.endsWith(".so") && !File(staged, it).isFile }.forEach { File(dir, it).delete() }
COMP_DIR[comp]?.let { compDir ->
for (arch in PE_ARCHES) {
val target = File(dir, "$compDir/$arch")
@@ -630,9 +603,7 @@ object ComponentsManager {
File(base, "files").walkTopDown().filter { it.isFile }.map { it.relativeTo(base).invariantSeparatorsPath }
.filter { owned(comp, it) }.associateWith { File(base, it) }
}
// A bionic tool never loses a FEX file: its launch.sh would put the whole bundled FEX back.
val removed = if (comp == "fex" && bionicTool(p.dir.name)) emptySet() else managed(comp) - files.keys
for (rel in removed) {
for (rel in managed(comp) - files.keys) {
lines.append(scope).append('\t').append(p.dir.name).append('\t').append(p.version).append('\t').append(comp)
.append('\t').append(rel).append("\t-\t-\n")
}
@@ -649,8 +620,7 @@ object ComponentsManager {
val version = safeName(file.removePrefix("original "))
"original-${p.id}-$version-$comp" to File(originalsDir(context), "${p.id}/$version/$comp.wcp")
} else {
val fit = (if (comp == "fex") launchFex(p.dir.name, file) { File(packagesDir(context), it).isFile } else file) ?: return null
safeName(fit.removeSuffix(".wcp")) to File(packagesDir(context), fit)
safeName(file.removeSuffix(".wcp")) to File(packagesDir(context), file)
}.takeIf { it.second.isFile }
}
@@ -681,14 +651,12 @@ object ComponentsManager {
for (scope in profiles.keys()) {
val profile = profiles.optJSONObject(scope) ?: continue
for (comp in COMPONENTS) {
val chosen = profile.optString(comp)
if (chosen.isEmpty()) continue
for (p in all) {
val file = (if (comp == "fex") launchFex(p.dir.name, chosen) { File(packagesDir(context), it).isFile } else chosen) ?: continue
val wcp = File(packagesDir(context), file)
if (!wcp.isFile) continue
append(scope, p, comp, safeName(file.removeSuffix(".wcp")), wcp)
}
val file = profile.optString(comp)
if (file.isEmpty()) continue
val wcp = File(packagesDir(context), file)
if (!wcp.isFile) continue
val key = safeName(file.removeSuffix(".wcp"))
for (p in all) append(scope, p, comp, key, wcp)
}
}
return PreparedLaunchState(lines.toString(), keep)
@@ -709,7 +677,6 @@ object ComponentsManager {
val wcp = File(packagesDir(context), safeName(file))
val info = packageInfo(context, wcp)
requireSelectable(context, info.comp)
requireFits(p, info)
val state = loadState(context)
if (inUse(context, p)) {
state.sub("queued").sub(p.id).put(info.comp, JSONObject().put("kind", "package").put("file", wcp.name).put("label", info.version)
@@ -723,11 +690,7 @@ object ComponentsManager {
context.getString(R.string.cmgr_swap_done, LABEL[info.comp], info.version, p.name)
}
private fun requireFits(p: Proton, info: Package) =
check(info.comp != "fex" || fexFits(p.dir.name, info.file)) { "${info.file} is not a FEX build for ${p.name}" }
private fun applyPackage(context: Context, p: Proton, info: Package, wcp: File, state: JSONObject, auto: Boolean = false) {
requireFits(p, info)
ensureOriginal(context, p, info.comp, state)
val hashes = installFiles(context, p.dir, info.comp, wcp)
state.sub("active").sub(p.id).put(info.comp, JSONObject()
@@ -840,18 +803,6 @@ object ComponentsManager {
internal fun liveOnAny(key: String, entry: JSONObject, installs: List<Proton>?): Boolean =
installs?.any { liveSelection(key, entry, it) } == true
// An installed tool that launches with `name` as the stored twin of a game's FEX choice (a Linux choice on
// DroidDeck-Bionic, a -bionic one on another Proton): deleting the twin would drop that choice for that tool.
internal fun twinUser(state: JSONObject, installed: List<Proton>, name: String): Proton? {
val profiles = state.optJSONObject("profiles") ?: return null
for (scope in profiles.keys()) {
val chosen = profiles.optJSONObject(scope)?.optString("fex")?.takeIf { it.isNotEmpty() } ?: continue
if (fexTwin(chosen) != name) continue
installed.firstOrNull { !fexFits(it.dir.name, chosen) }?.let { return it }
}
return null
}
internal fun packagesInUse(state: JSONObject, installed: List<Proton>): Set<String> {
val byId = installed.groupBy { it.id }
val names = HashSet<String>()
@@ -868,11 +819,7 @@ object ComponentsManager {
val profiles = state.optJSONObject("profiles")
for (scope in profiles?.keys() ?: emptyList<String>().iterator()) {
val profile = profiles?.optJSONObject(scope) ?: continue
COMPONENTS.forEach { comp ->
val file = profile.optString(comp).takeIf { it.isNotEmpty() } ?: return@forEach
names.add(file)
if (comp == "fex" && installed.any { !fexFits(it.dir.name, file) }) fexTwin(file)?.let(names::add)
}
COMPONENTS.forEach { comp -> profile.optString(comp).takeIf { it.isNotEmpty() }?.let(names::add) }
}
return names
}
@@ -943,7 +890,6 @@ object ComponentsManager {
val queued = state.sub("queued").sub(target.id)
var changed = false
wanted.forEach { (comp, entry) ->
if (comp == "fex" && !fexFits(target.dir.name, entry.optString("file"))) return@forEach
if (active?.has(comp) != true && !queued.has(comp)) {
queued.put(comp, entry)
changed = true
@@ -1024,8 +970,6 @@ object ComponentsManager {
fun deletePackage(context: Context, file: String): String = synchronized(lock) {
val name = safeName(file)
val state = loadState(context)
val twinTool = twinUser(state, protons(context), name)
check(twinTool == null) { context.getString(R.string.cmgr_package_in_use, name, twinTool?.name ?: "") }
val installed = protons(context).groupBy { it.id }
var changed = false
for (key in listOf("queued", "active")) {
@@ -1122,11 +1066,8 @@ object ComponentsManager {
return Catalog(items, o.optLong("fetchedAt"))
}
internal fun assetComp(release: String, name: String): String? = RELEASES[release] ?: when (release) {
DD_NIGHTLY -> NIGHTLY_PREFIXES.entries.firstOrNull { name.startsWith(it.key) }?.value
DD_BIONIC -> "fex"
else -> null
}
internal fun assetComp(release: String, name: String): String? =
RELEASES[release] ?: if (release == DD_NIGHTLY) NIGHTLY_PREFIXES.entries.firstOrNull { name.startsWith(it.key) }?.value else null
internal val CATALOG_ORDER: Comparator<CatalogItem> =
compareBy<CatalogItem> { it.comp }.thenBy { it.release == DD_NIGHTLY }.then(newestFirst { it.file })
@@ -1214,25 +1155,6 @@ object ComponentsManager {
return runCatching { readWcpEntry(original, rel) }.getOrNull()
}
// DroidDeck-Bionic loads only Android builds of FEX's unix libraries; other Protons only glibc builds.
internal fun bionicTool(dirName: String?): Boolean = dirName?.startsWith("DroidDeck-Bionic") == true
internal fun bionicFex(file: String): Boolean = file.endsWith("-bionic.wcp", ignoreCase = true)
internal fun fexFits(toolDir: String?, file: String): Boolean = bionicTool(toolDir) == bionicFex(file)
internal fun fexTwin(file: String): String? = when {
file.endsWith("-linux.wcp", ignoreCase = true) -> file.dropLast("-linux.wcp".length) + "-bionic.wcp"
file.endsWith("-bionic.wcp", ignoreCase = true) -> file.dropLast("-bionic.wcp".length) + "-linux.wcp"
else -> null
}
internal fun launchFex(toolDir: String, file: String, stored: (String) -> Boolean): String? =
if (fexFits(toolDir, file)) file else fexTwin(file)?.takeIf(stored)
internal fun <T> forTool(comp: String, toolDir: String?, items: List<T>, selected: String? = null, file: (T) -> String): List<T> =
if (comp != "fex") items else items.filter { file(it) == selected || fexFits(toolDir, file(it)) }
fun supports(p: Proton, comp: String): Boolean =
if (comp == "fex") File(p.dir, FEX_FILES.first()).isFile else File(p.dir, "${COMP_DIR.getValue(comp)}/aarch64-windows").isDirectory
@@ -937,7 +937,7 @@ internal object EnhancedSessionLogShare {
val value = entry.lowercase(Locale.US)
if (value.startsWith("battlenet/") || value.startsWith("stores/") || value.startsWith("tools/") ||
value.contains("droiddeck-esync/") || GAME_LOG.matches(value.substringAfterLast('/')) ||
listOf("proton", "wine", "dxvk", "vkd3d", "battle.net", "game-debug", "bionic").any(value::contains)) return Category.GAMES
listOf("proton", "wine", "dxvk", "vkd3d", "battle.net", "game-debug").any(value::contains)) return Category.GAMES
if (listOf("wayland", "gamescope", "xwayland", "vulkan", "gpu", "mesa", "egl", "glx", "drm", "compositor", "frame-trace").any(value::contains)) return Category.GRAPHICS
return Category.SESSION
}
@@ -948,7 +948,7 @@ internal object EnhancedSessionLogShare {
"droiddeck", "droiddeck-esync", "session.log", "app.log", "wayland.log", "audio.log",
"device.txt", "network.txt", "events.jsonl", "memory.csv", "capture.json", "crash.log",
"frame-trace.log", "process-trace.log", "game-lifecycle.log", "launches.log", "tools.tsv", "wanted.tsv", "prefixes.json",
"battlenet.log", "spawned.log", "flatpak-install.log", "cef_log.txt", "cef_log.previous.txt", "droiddeck-bionic.log",
"battlenet.log", "spawned.log", "flatpak-install.log", "cef_log.txt", "cef_log.previous.txt",
"console_log.txt", "webhelper_js.txt", "controller_support.txt", "systemperfmanager.txt",
)
private val KNOWN_COMPONENT_PATTERNS = listOf(
@@ -74,16 +74,10 @@ object ExperimentalProtons {
return PREFIX + base + (tag?.let { "-$it" } ?: "")
}
/** DroidDeck-Bionic test builds are prereleases of the same repository and have their own row in the Proton list. */
internal fun listed(assets: List<ProtonExtras.Asset>): List<ProtonExtras.Asset> {
val bionic = ProtonExtras.tools.first { it.id == ProtonExtras.BIONIC }
return assets.filterNot { bionic.assetPattern.containsMatchIn(it.name) }
}
fun refresh(context: Context): List<Release>? {
val tool = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }
val fetched = ProtonExtras.releasesForRemoval(tool) ?: return null
val assets = listed(ProtonExtras.assets(tool, fetched.releases, prerelease = true))
val assets = ProtonExtras.assets(tool, fetched.releases, prerelease = true)
val rows = assets.map { Release(it.tag, it.name, it.url, it.sha512, it.size, it.releaseName) }.distinctBy { it.tag }
if (!SessionState.running) {
reconcile(context, fetched)
@@ -14,8 +14,7 @@ object ProtonDefault {
data class Tool(val name: String, val display: String, val dir: String, val valve: Boolean)
data class Request(val seq: Long, val valve: Boolean, val dir: String)
data class State(val default: String?, val applied: Long, val live: Boolean, val pending: String?, val tools: List<Tool>,
val source: String? = null)
data class State(val default: String?, val applied: Long, val live: Boolean, val pending: String?, val tools: List<Tool>)
data class GameChoice(val valve: Boolean, val dir: String)
enum class Outcome { LIVE, NEXT_START, NOT_RUNNABLE }
@@ -35,7 +34,6 @@ object ProtonDefault {
Tool(t.optString("name"), t.optString("display"), t.optString("dir"), t.optBoolean("valve"))
}?.takeIf { it.name.isNotEmpty() }
},
source = o.optString("source").ifEmpty { null },
)
}
@@ -101,13 +99,7 @@ object ProtonDefault {
if (!runnable(state, proton)) return Outcome.NOT_RUNNABLE
val d = dir(context)
val seq = nextSeq(System.currentTimeMillis(), state, parseRequest(read(File(d, "request.json"))))
writeRequest(d, Request(seq, proton.valve, proton.dir.name))
val tool = state.tools.firstOrNull { it.valve == proton.valve && it.dir == proton.dir.name }
return if (SessionState.running && state.live && (tool == null || state.pending != tool.name)) Outcome.LIVE else Outcome.NEXT_START
}
private fun writeRequest(d: File, request: Request) {
val body = JSONObject().put("seq", request.seq).put("valve", request.valve).put("dir", request.dir).toString(1) + "\n"
val body = JSONObject().put("seq", seq).put("valve", proton.valve).put("dir", proton.dir.name).toString(1) + "\n"
val staged = File(d, "request.json.staged")
try {
d.mkdirs()
@@ -118,45 +110,8 @@ object ProtonDefault {
Log.w(TAG, "could not write the Proton request", e)
throw e
}
}
// The default that names a tool an update replaces moves to the new one, as the per-game picks do: otherwise the guest
// no longer finds it and falls back to DroidDeck-Proton.
internal fun movedDefault(state: State, request: Request?, from: Set<String>, to: String, now: Long): Request? {
val (valve, dir) = chosen(state, request) ?: return null
if (valve || dir !in from) return null
return Request(nextSeq(now, state, request), false, to)
}
@Synchronized
fun moveDefault(context: Context, from: Set<String>, to: String) {
val d = dir(context)
val moved = movedDefault(state(context), parseRequest(read(File(d, "request.json"))), from, to, System.currentTimeMillis()) ?: return
writeRequest(d, moved)
}
// DroidDeck-Bionic keeps one build. A default naming another one moves to the installed build: an app from before
// updates carried the default over left it, or the guest fell back to its own tool when that build was gone (the
// request the app last wrote still names it).
internal fun bionicDefault(state: State, request: Request?, prefix: String, newest: String, now: Long): Request? {
val current = chosen(state, request)
val stale = when {
current != null && !current.first && current.second.startsWith(prefix) -> current.second
state.source == "fallback" && request != null && !request.valve && request.dir.startsWith(prefix) -> request.dir
else -> return null
}
return if (stale == newest) null else Request(nextSeq(now, state, request), false, newest)
}
/** The default and the per-game picks that name a DroidDeck-Bionic build other than [newest] move to it. */
@Synchronized
fun keepBionicCurrent(context: Context, prefix: String, newest: String) {
val d = dir(context)
bionicDefault(state(context), parseRequest(read(File(d, "request.json"))), prefix, newest, System.currentTimeMillis())
?.let { writeRequest(d, it) }
val games = parseGames(read(File(d, GAMES)))
val stale = games.values.filterNotNull().filter { !it.valve && it.dir.startsWith(prefix) && it.dir != newest }.map { it.dir }.toSet()
if (stale.isNotEmpty()) movedGames(games, stale, newest)?.let { writeGames(d, it) }
val tool = state.tools.firstOrNull { it.valve == proton.valve && it.dir == proton.dir.name }
return if (SessionState.running && state.live && (tool == null || state.pending != tool.name)) Outcome.LIVE else Outcome.NEXT_START
}
internal fun movedGames(choices: Map<String, GameChoice?>, from: Set<String>, to: String): Map<String, GameChoice?>? {
@@ -8,7 +8,6 @@ import android.util.Log
import com.droiddeck.launcher.core.Downloader
import com.droiddeck.launcher.core.FileUtils
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.runtime.NativeGuest
import java.io.File
import java.util.Locale
import org.json.JSONArray
@@ -28,27 +27,20 @@ object ProtonExtras {
@Volatile
private var replacing = false
class Tool(val id: String, val name: String, val prefix: String, val repo: String, val assetPattern: Regex,
val prereleases: Boolean = false)
class Tool(val id: String, val name: String, val prefix: String, val repo: String, val assetPattern: Regex)
internal data class Asset(val tag: String, val name: String, val url: String, val sha512: String?, val size: Long,
val sha256: String? = null, val releaseName: String = tag)
internal data class ReleaseFetch(val releases: JSONArray, val complete: Boolean)
const val OWN = "droiddeck"
const val BIONIC = "bionic"
val tools = listOf(
Tool("ge", "GE-Proton", "GE-Proton", "GloriousEggroll/proton-ge-custom", Regex("aarch64\\.tar\\.(gz|xz)$")),
Tool("cachyos", "proton-cachyos", "proton-cachyos", "CachyOS/proton-cachyos", Regex("arm64\\.tar\\.(gz|xz)$")),
Tool("droiddeck", "DroidDeck-Proton", "DroidDeck-Proton", "Droid-Deck/DroidDeck-Proton", Regex("^DroidDeck-Proton-.*aarch64\\.tar\\.(gz|xz)$")),
// Bionic (Android libc) Proton started outside the Linux userland; test builds are prereleases. No-proot only.
Tool(BIONIC, "DroidDeck-Bionic", "DroidDeck-Bionic", "Droid-Deck/DroidDeck-Proton", Regex("^DroidDeck-Bionic-.*aarch64\\.tar\\.(gz|xz)$"), prereleases = true),
Tool("droiddeck", "DroidDeck-Proton", "DroidDeck-Proton", "Droid-Deck/DroidDeck-Proton", Regex("aarch64\\.tar\\.(gz|xz)$")),
)
/** The sources offered on this device: DroidDeck-Bionic only with Run without proot on. */
fun offered(context: Context): List<Tool> = tools.filter { it.id != BIONIC || NativeGuest.enabled(context) }
private fun home(context: Context) = File(LinuxRuntime.rootDir(context), "root")
private fun requests(context: Context) = File(home(context), ".dd-proton-extra")
private fun toolsDir(context: Context) = File(home(context), ".local/share/Steam/compatibilitytools.d")
@@ -123,11 +115,10 @@ object ProtonExtras {
private var lastAttempt = 0L
fun checkLatest(context: Context, force: Boolean = false, now: Long = System.currentTimeMillis()): Boolean {
keepBionicCurrent(context)
synchronized(checkLock) {
val file = latestFile(context)
val cache = readJson(file)
val due = offered(context).filter { tool ->
val due = tools.filter { tool ->
val at = cache.optJSONObject(tool.id)?.optLong("at", 0L) ?: 0L
force || (now - at) !in 0 until CHECK_EVERY_MS
}
@@ -177,32 +168,15 @@ object ProtonExtras {
fun remove(context: Context, tool: Tool, dir: String? = null) {
val name = if (dir != null) dir.takeIf { it in installedAll(context, tool) } ?: return else installed(context, tool) ?: return
if (deleteTool(context, name)) ComponentsManager.forgetProton(context, name)
}
// A tool folder can hold links that point out of it (a prefix template's dosdevices/z: -> /), and
// File.deleteRecursively() follows links into directories: remove each link itself, never what it points to.
private fun deleteTool(context: Context, name: String): Boolean {
val dir = File(toolsDir(context), name)
FileUtils.delete(dir)
return !dir.exists() && !java.nio.file.Files.isSymbolicLink(dir.toPath())
if (File(toolsDir(context), name).deleteRecursively()) ComponentsManager.forgetProton(context, name)
}
fun removeOlder(context: Context, tool: Tool) {
installedAll(context, tool).dropLast(1).forEach {
if (deleteTool(context, it)) ComponentsManager.forgetProton(context, it)
if (File(toolsDir(context), it).deleteRecursively()) ComponentsManager.forgetProton(context, it)
}
}
// DroidDeck-Bionic: the default and the game picks name the installed build, also when they were left on one an
// older app deleted without moving them.
private fun keepBionicCurrent(context: Context) {
if (SessionState.running) return
val tool = tools.firstOrNull { it.id == BIONIC } ?: return
val newest = installedAll(context, tool).lastOrNull() ?: return
runCatching { ProtonDefault.keepBionicCurrent(context, tool.prefix, newest) }.onFailure { Log.w(TAG, "bionic default and picks", it) }
}
private fun replaceOlder(context: Context, tool: Tool) {
val all = installedAll(context, tool)
val newest = all.lastOrNull() ?: return
@@ -215,9 +189,7 @@ object ProtonExtras {
if (runCatching { ComponentsManager.carryOver(context, old, newest) }.onFailure { Log.w(TAG, "components of $old", it) }.isFailure) continue
if (runCatching { keepUserSettings(context, old, newest) }.onFailure { Log.w(TAG, "user settings of $old", it) }.isFailure) continue
if (runCatching { ProtonDefault.moveGames(context, setOf(old), newest) }.onFailure { Log.w(TAG, "per-game picks of $old", it) }.isFailure) continue
// DroidDeck-Bionic only: the guest finds no default for a deleted Bionic build and falls back to DroidDeck-Proton
if (tool.id == BIONIC && runCatching { ProtonDefault.moveDefault(context, setOf(old), newest) }.onFailure { Log.w(TAG, "default pick of $old", it) }.isFailure) continue
if (deleteTool(context, old)) ComponentsManager.forgetProton(context, old)
if (File(toolsDir(context), old).deleteRecursively()) ComponentsManager.forgetProton(context, old)
else Log.w(TAG, "could not remove $old")
}
} finally {
@@ -336,7 +308,7 @@ object ProtonExtras {
archive.delete()
unqueue(context, tool)
record(context, tool, placed, asset.tag)
if (tool.id == OWN || tool.id == BIONIC) replaceOlder(context, tool)
if (tool.id == OWN) replaceOlder(context, tool)
if (EsyncPacks.enabled(context)) {
onProgress(context.getString(R.string.esync_fetching), -1)
try {
@@ -421,7 +393,7 @@ object ProtonExtras {
internal fun pickAsset(tool: Tool, array: JSONArray): Asset? {
val candidates = (0 until array.length()).asSequence()
.mapNotNull { array.optJSONObject(it) }
.filter { !it.optBoolean("draft", false) && (tool.prereleases || !it.optBoolean("prerelease", false)) }
.filter { !it.optBoolean("draft", false) && !it.optBoolean("prerelease", false) }
return candidates.firstNotNullOfOrNull { assetOf(tool, it) }
}
@@ -180,7 +180,6 @@ object SessionFiles {
"usr/local/bin/droiddeck-flatpak-run" to "usr/local/bin/droiddeck-flatpak-run",
"usr/local/bin/droiddeck-appimage-run" to "usr/local/bin/droiddeck-appimage-run",
"usr/local/bin/droiddeck-appimage-exec" to "usr/local/bin/droiddeck-appimage-exec",
"usr/local/bin/droiddeck-curseforge" to "usr/local/bin/droiddeck-curseforge",
"usr/local/bin/droiddeck-script-run" to "usr/local/bin/droiddeck-script-run",
"usr/local/bin/droiddeck-open" to "usr/local/bin/droiddeck-open",
"usr/local/bin/droiddeck-proton-run" to "usr/local/bin/droiddeck-proton-run",
@@ -1033,9 +1033,6 @@ class SessionService : Service() {
)
(if (bridge || venus) null else LinuxVulkanDriver.resolveIcdPath(this, linuxDriverId))
?.let { guest.add(LinuxVulkanDriver.ENV + "=" + it) }
// DroidDeck-Bionic games load an Android driver build; this is the one the display uses, for a runtime driver
// that has none.
guest.add("DROIDDECK_DISPLAY_DRIVER=" + com.droiddeck.launcher.gpu.TurnipDriver(this).effectiveId())
if (!com.droiddeck.launcher.core.DeviceSupport.adreno() && lastXwaylandCrashed()) {
guest.add("XWAYLAND_NO_GLAMOR=1")
Log.w(TAG, "xwayland: the last session's Xwayland crashed; glamor off for this one (XWAYLAND_NO_GLAMOR=1)")
@@ -12,11 +12,8 @@ object StoreLaunch {
const val EPIC_CODE = ".droiddeck-epic-code"
const val EPIC_ARGS = ".droiddeck-epic-args"
const val UBISOFT_LAUNCH = ".droiddeck-ubisoft.json"
/** DroidDeck-Bionic's Wine has Android's root on Z:; that tool sets this to the guest's root as its Wine names it. */
const val GUEST_ROOT = "DROIDDECK_GUEST_ROOT"
private const val ROOT_VAR = "DD_R"
private const val UBISOFT_SERVICE = "%$ROOT_VAR%\\usr\\local\\lib\\droiddeck-ubisoft\\droiddeck-upc.exe"
const val EPIC_PARENT = "%$ROOT_VAR%\\usr\\local\\lib\\droiddeck-epic\\EpicGamesLauncher.exe"
private const val UBISOFT_SERVICE = "Z:\\usr\\local\\lib\\droiddeck-ubisoft\\droiddeck-upc.exe"
const val EPIC_PARENT = "Z:\\usr\\local\\lib\\droiddeck-epic\\EpicGamesLauncher.exe"
/** Per-game environment switch: 1 starts any Epic game under [EPIC_PARENT], 0 never does. */
const val EPIC_PARENT_SWITCH = "DD_EPIC_PARENT"
/** Epic app names whose launchers treat the game as unowned unless a process named EpicGamesLauncher.exe started it. */
@@ -50,10 +47,6 @@ object StoreLaunch {
for ((k, v) in sidecar.env) if (ENV_NAME.matches(k)) lines += "set \"$k=${v.replace("\"", "")}\""
val args = sidecar.args.joinToString(" ") { if (sidecar.store == Store.ROCKSTAR) batchArg(it) else quoteArg(it) }
val run = "\"%~dp0$exe\"" + (if (args.isNotEmpty()) " $args" else "")
if (sidecar.store == Store.EPIC || sidecar.store == Store.UBISOFT) {
lines += "set \"$ROOT_VAR=Z:\""
lines += "if defined $GUEST_ROOT set \"$ROOT_VAR=%$GUEST_ROOT%\""
}
if (sidecar.store == Store.EPIC) {
lines += "set \"$PARENT_VAR=${if (sidecar.id in EPIC_PARENT_TITLES) "1" else ""}\""
lines += "if \"%$EPIC_PARENT_SWITCH%\"==\"1\" set \"$PARENT_VAR=1\""
@@ -144,6 +137,7 @@ object StoreLaunch {
if (sidecar.store !in listOf(Store.UBISOFT, Store.ROCKSTAR) || !sidecar.isInstalled) return sidecar
if (sidecar.store == Store.ROCKSTAR && java.nio.file.Files.isSymbolicLink(File(folder, LAUNCHER).toPath())) return sidecar.copy(launcher = null)
val wrongExe = !sidecar.exeFile(folder).isFile || sidecar.exe.contains("installer", ignoreCase = true) || sidecar.exe.contains("autorun", ignoreCase = true)
if (sidecar.store == Store.UBISOFT && sidecar.launcher == LAUNCHER && !wrongExe) return sidecar
val metadataExe = if (sidecar.store == Store.ROCKSTAR) com.droiddeck.launcher.stores.rockstar.RockstarMetadata.find(folder)?.exe
?.takeIf { File(folder, it).isFile && File(folder, it).canonicalPath.startsWith(folder.canonicalPath + File.separator) } else null
val exe = metadataExe ?: if (wrongExe) StoreExe.pick(folder, null, sidecar.title).ifEmpty { sidecar.exe } else sidecar.exe
@@ -360,7 +360,7 @@ internal fun AppDialog(
.then(if (scrollable) Modifier.verticalScroll(scrollState) else Modifier)
.padding(horizontal = 18.dp, vertical = 16.dp),
) {
androidx.compose.runtime.CompositionLocalProvider(LocalRevealChecked provides true) { content() }
content()
if (side != null && !beside) side()
}
}
@@ -14,6 +14,7 @@ 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.layout.widthIn
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.LazyGridState
@@ -27,7 +28,6 @@ import androidx.compose.material3.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
@@ -62,13 +62,8 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.AddedGames
import com.droiddeck.launcher.runtime.CurseForgeApp
import com.droiddeck.launcher.runtime.UserApps
import com.droiddeck.launcher.runtime.WowAddonCatalog
import com.droiddeck.launcher.runtime.WowAddons
import com.droiddeck.launcher.session.BackgroundSession
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
@@ -86,101 +81,10 @@ private class AddonResults {
private enum class AddonStatus { INSTALL, UPDATE, INSTALLED }
private enum class AddonSource { WOWI, CURSE }
private class CurseState(val notice: Int? = null) : Exception()
private class CurseLink(val app: UserApps.App) {
class Linked(val inspector: String, val guid: String)
private val lock = Object()
@Volatile private var closed = false
private var held = false
private var ownSession: String? = null
private var started = false
@Volatile private var launching = false
@Volatile private var inspector: String? = null
private val guids = HashMap<String, String>()
fun <T> call(context: Context, target: WowAddons.Target, block: (Linked) -> T): T {
val linked = synchronized(lock) { link(context, target) }
try {
return block(linked)
} catch (e: CurseForgeApp.Failure) {
if (e.gone) synchronized(lock) {
if (inspector == linked.inspector) {
inspector = null
guids.clear()
}
}
throw e
}
}
private fun link(context: Context, target: WowAddons.Target): Linked {
if (closed) throw CurseState()
if (!SessionState.running) {
started = false
launching = false
held = false
ownSession = null
inspector = null
guids.clear()
val args = CurseForgeApp.holdArgs(app) ?: throw CurseState()
ownSession = BackgroundSession.start(context, CurseForgeApp.HELPER, args) ?: throw CurseState()
}
if (closed) throw CurseState()
if (!held) {
held = true
SessionService.holdForSignIn(context, true)
}
val awake = System.currentTimeMillis() + 30_000
while ((SessionState.suspended || SessionState.suspending) && System.currentTimeMillis() < awake) Thread.sleep(250)
val url = inspector ?: run {
launching = true
val done = CurseForgeApp.start(context, app)
when (done.state) {
CurseForgeApp.Start.READY -> {
started = true
inspector = done.inspector
done.inspector ?: throw CurseState()
}
CurseForgeApp.Start.BUSY -> throw CurseState(R.string.addons_curse_busy)
else -> throw CurseState()
}
}
if (closed) throw CurseState()
guids[target.addOns.path]?.let { return Linked(url, it) }
val root = WowAddons.root(target)?.let { AddedGames.guestPath(context, it) } ?: throw CurseState()
val flavor = WowAddons.flavorDir(target)?.let { AddedGames.guestPath(context, it) } ?: throw CurseState()
val guid = CurseForgeApp.instance(context, url, root, flavor)
guids[target.addOns.path] = guid
return Linked(url, guid)
}
fun close(context: Context) {
closed = true
Thread {
if (launching) CurseForgeApp.stop(context, app, inspector)
synchronized(lock) {
if (started) CurseForgeApp.stop(context, app, inspector)
val owned = ownSession
if (owned != null) BackgroundSession.stop(context, owned)
else if (held) SessionService.holdForSignIn(context, false)
started = false
launching = false
ownSession = null
held = false
inspector = null
}
}.start()
}
}
private const val PAGES_AHEAD = 8
@Composable
internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAddons.Target, curseForge: UserApps.App?, onDismiss: () -> Unit) {
internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAddons.Target, onDismiss: () -> Unit) {
val context = LocalContext.current.applicationContext
val scope = rememberCoroutineScope()
val shown = rememberShown(onDismiss)
@@ -189,30 +93,15 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
var text by remember { mutableStateOf("") }
var category by remember { mutableStateOf<WowAddonCatalog.Category?>(null) }
var sort by remember { mutableStateOf(WowAddonCatalog.Sort.POPULAR) }
var source by remember { mutableStateOf(AddonSource.WOWI) }
val curse = if (source == AddonSource.CURSE) curseForge else null
val link = remember(curseForge?.key) { curseForge?.let(::CurseLink) }
DisposableEffect(link) {
onDispose { link?.close(context) }
}
var notice by remember { mutableStateOf<Int?>(null) }
var curseInstalls by remember { mutableIntStateOf(0) }
val results = remember(text, category, sort, target, curse) { AddonResults() }
val results = remember(text, category, sort, target) { AddonResults() }
val installing = remember { mutableStateMapOf<String, Int>() }
val installed = remember { mutableStateMapOf<String, Pair<String, String>>() }
val categories by produceState(emptyList<WowAddonCatalog.Category>()) {
value = withContext(Dispatchers.IO) { runCatching { WowAddonCatalog.categories(context) }.getOrDefault(emptyList()) }
}
val presentKey = curse to target.addOns
val snapshot by produceState(presentKey to emptyMap<String, String?>(), target.addOns, WowAddons.imports, curse, curseInstalls, results.items.isEmpty()) {
val into = target
val key = curse to into.addOns
value = key to withContext(Dispatchers.IO) {
if (curse != null && link != null) runCatching { link.call(context, into) { CurseForgeApp.installed(context, it.inspector, it.guid) }.associateWith { null } }.getOrDefault(emptyMap())
else WowAddons.details(into).mapNotNull { item -> item.wowiId?.let { it to item.version } }.toMap()
}
val present by produceState(emptyMap<String, String?>(), target.addOns, WowAddons.imports) {
value = withContext(Dispatchers.IO) { WowAddons.details(target).mapNotNull { item -> item.wowiId?.let { it to item.version } }.toMap() }
}
val present = snapshot.second.takeIf { snapshot.first == presentKey } ?: emptyMap()
fun status(addon: WowAddonCatalog.Addon): AddonStatus {
if (addon.id !in present) return AddonStatus.INSTALL
val have = present[addon.id]
@@ -227,16 +116,10 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
val words = text
val cat = category?.id
val order = sort
val via = link?.takeIf { curse != null }
notice = null
scope.launch {
val got = withContext(Dispatchers.IO) {
runCatching {
if (via != null) via.call(context, into) { CurseForgeApp.search(context, it.inspector, it.guid, words, order, page) }
else WowAddonCatalog.search(context, WowAddonCatalog.Query(words, cat, WowAddonCatalog.client(into), order), page)
}
runCatching { WowAddonCatalog.search(context, WowAddonCatalog.Query(words, cat, WowAddonCatalog.client(into), order), page) }
}
if (results.items.isEmpty()) notice = (got.exceptionOrNull() as? CurseState)?.notice
got.onSuccess {
if (page == 0) results.items.clear()
results.items.addAll(it.items.filter { addon -> results.items.none { seen -> seen.id == addon.id } })
@@ -253,27 +136,6 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
fun install(addon: WowAddonCatalog.Addon) {
val key = installKey(addon, target)
if (key in installing) return
val via = link?.takeIf { curse != null }
if (via != null) {
val into = target
installing[key] = 0
scope.launch {
val done = withContext(Dispatchers.IO) { runCatching { via.call(context, into) { CurseForgeApp.install(context, it.inspector, it.guid, addon.id) } } }
installing.remove(key)
val ok = done.getOrNull() == true
if (ok) {
WowAddons.changed()
curseInstalls++
}
val message = when {
ok -> context.resources.getQuantityString(R.plurals.main_addons_imported, 1, 1, into.flavor)
else -> (done.exceptionOrNull() as? CurseState)?.notice?.let(context::getString)
?: context.getString(R.string.stores_dl_failed_reason, done.exceptionOrNull()?.message ?: addon.name)
}
Toast.makeText(context, message, Toast.LENGTH_LONG).show()
}
return
}
if (SessionState.running) {
Toast.makeText(context, R.string.main_addons_close_session, Toast.LENGTH_LONG).show()
return
@@ -287,7 +149,7 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
Toast.makeText(context, message.first, Toast.LENGTH_LONG).show()
}
}
val sourceName = stringResource(if (curse != null) R.string.addons_source_curse else R.string.addons_source_wowi)
val sourceName = stringResource(R.string.addons_source_wowi)
val grid = rememberLazyGridState()
LaunchedEffect(results, grid) {
snapshotFlow { grid.layoutInfo.visibleItemsInfo.lastOrNull()?.index to grid.layoutInfo.totalItemsCount }.collect { (last, total) ->
@@ -300,7 +162,7 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
LaunchedEffect(results, results.items.isNotEmpty()) {
if (results.items.isNotEmpty() && !searching && inputMode.inputMode == InputMode.Keyboard) focusSoon { firstAction }
}
AppDialog(shown, close, "addonBrowser", wide = true, maxWidth = 980.dp, scrollable = false, fillHeight = true, modifier = Modifier.releaseTextFieldOnTap()) {
AppDialog(shown, close, "addonBrowser", wide = true, maxWidth = 980.dp, scrollable = false, fillHeight = true) {
val sortChip: @Composable () -> Unit = {
BrowseDropdown(sortLabel(sort)) { first, done ->
WowAddonCatalog.Sort.entries.forEachIndexed { index, option ->
@@ -308,14 +170,8 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
}
}
}
val sourceChip: @Composable () -> Unit = {
if (curseForge != null) BrowseDropdown(sourceName) { first, done ->
MenuItem(stringResource(R.string.addons_source_wowi), source == AddonSource.WOWI, focusRequester = first) { source = AddonSource.WOWI; done() }
MenuItem(stringResource(R.string.addons_source_curse), source == AddonSource.CURSE) { source = AddonSource.CURSE; done() }
}
}
val categoryChip: @Composable () -> Unit = {
if (curse == null && categories.isNotEmpty()) BrowseDropdown(category?.name ?: stringResource(R.string.addons_category_all)) { first, done ->
if (categories.isNotEmpty()) BrowseDropdown(category?.name ?: stringResource(R.string.addons_category_all)) { first, done ->
MenuItem(stringResource(R.string.addons_category_all), category == null, focusRequester = first) { category = null; done() }
categories.forEach { option -> MenuItem(option.name, category?.id == option.id) { category = option; done() } }
}
@@ -339,7 +195,6 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
BoxWithConstraints(Modifier.fillMaxWidth()) {
if (maxWidth >= 640.dp) Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
search(Modifier.weight(1f))
sourceChip()
sortChip()
categoryChip()
flavorChip()
@@ -353,7 +208,6 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp),
modifier = Modifier.horizontalScroll(rememberScrollState()),
) {
sourceChip()
sortChip()
categoryChip()
flavorChip()
@@ -374,10 +228,6 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
Column(Modifier.fillMaxWidth().padding(vertical = 8.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp)) {
when {
results.loading -> LinearProgressIndicator(Modifier.fillMaxWidth())
results.failed != null && notice != null -> {
Text(stringResource(notice!!), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
BrowseChip(stringResource(R.string.stores_dl_retry), false) { load(0) }
}
results.failed != null -> {
Text(stringResource(R.string.addons_unreachable, sourceName), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
BrowseChip(stringResource(R.string.stores_dl_retry), false) { load(if (results.items.isEmpty()) 0 else results.page + 1) }
@@ -409,7 +259,7 @@ private fun AddonRow(addon: WowAddonCatalog.Addon, status: AddonStatus, progress
fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
)
}
val size = action
val size = Modifier.widthIn(min = 104.dp).then(action)
when {
progress != null -> SecondaryButton(stringResource(R.string.store_installing), compact = true, modifier = size, progress = progress / 100f, onClick = onInstall)
status == AddonStatus.INSTALLED -> SecondaryButton(stringResource(R.string.stores_installed_chip), enabled = false, compact = true, modifier = size) {}
@@ -2,7 +2,6 @@ package com.droiddeck.launcher.ui
import android.app.Activity
import android.content.ContextWrapper
import android.os.Build
import android.view.KeyEvent
import android.view.WindowManager
import androidx.activity.compose.LocalActivityResultRegistryOwner
@@ -185,11 +184,7 @@ private fun AgentPageContent(
?: generateSequence(view.context) { (it as? ContextWrapper)?.baseContext }
.filterIsInstance<Activity>().firstOrNull()?.window
val previousMode = window?.attributes?.softInputMode
// A window fitted to the system bars with ADJUST_NOTHING reports no keyboard height to Compose.
// It stays unfitted after the page leaves: fitting it again insets the other pages twice.
val edgeToEdge = visible && hidesPet && !drawer && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R
if (visible) window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING)
if (edgeToEdge) window?.setDecorFitsSystemWindows(false)
onDispose {
if (visible && previousMode != null) window?.setSoftInputMode(previousMode)
}
@@ -526,11 +526,11 @@ fun ComponentsPage(
val availableTitle: @Composable (String) -> String = { l ->
when (l) {
PROTON_TAB -> stringResource(R.string.comp_available_count, protons.rows.count(ProtonRow::available))
else -> stringResource(R.string.comp_nightlies_count, availableRows(l, catalog, snapshot, view?.proton?.dir?.name).size)
else -> stringResource(R.string.comp_nightlies_count, availableRows(l, catalog, snapshot).size)
}
}
val followed: (String) -> Boolean = { l -> view?.proton?.let { ComponentUpdates.autoFollows(it, l) } == true }
val moded: (String) -> Boolean = { followed(it) && it in compModes && it !in compAutoHeld && !ComponentsManager.runtimeManaged(it, gpu.systemPowerVr) }
val followed = view?.proton?.let(ComponentUpdates::follows) == true
val moded: (String) -> Boolean = { followed && it in compModes && it !in compAutoHeld && !ComponentsManager.runtimeManaged(it, gpu.systemPowerVr) }
val automatic: (String) -> Boolean = { moded(it) && compModes[it] == ComponentUpdates.AUTO }
val installedRows: @Composable ColumnScope.(String, Boolean) -> Unit = { l, right ->
when (l) {
@@ -614,7 +614,7 @@ fun ComponentsPage(
}
}
else -> {
val available = availableRows(l, catalog, snapshot, view?.proton?.dir?.name)
val available = availableRows(l, catalog, snapshot)
if (available.isEmpty()) EmptyLine(if (catalogAt == 0L) stringResource(R.string.comp_refresh_to_list) else stringResource(R.string.comp_nothing_new))
for ((stable, nightly) in available) {
val d = if (nightly != null && nightlyPicked[stable.file] == true) nightly else stable
@@ -974,18 +974,18 @@ private fun installedFor(l: String, view: ComponentsManager.ProtonView?, snapsho
o.label.substringAfterLast(" · ", "").ifEmpty { o.label }.let { if (isCurrent) stringResource(R.string.comp_this_build, it) else stringResource(R.string.comp_earlier_build, it) },
"ORIGINAL", activeIsOriginal && isCurrent, !isCurrent, null, o.protonVersion,
)
} + ComponentsManager.forTool(l, view.proton.dir.name, (snapshot?.packages ?: emptyList()).filter { it.comp == l }, st.activeFile) { it.file }.map { s ->
} + (snapshot?.packages ?: emptyList()).filter { it.comp == l }.map { s ->
InstalledItem(s.version, stringResource(R.string.common_size_mb, s.size / 1048576.0), "STORED", !runtimeManaged && s.file == st.activeFile, true, s.file, null)
}
}
private fun availableFor(l: String, catalog: List<CatalogItem>, snapshot: Snapshot?, toolDir: String?): List<CatalogItem> {
private fun availableFor(l: String, catalog: List<CatalogItem>, snapshot: Snapshot?): List<CatalogItem> {
val stored = (snapshot?.packages ?: emptyList()).map { it.file }.toSet()
return ComponentsManager.forTool(l, toolDir, catalog.filter { it.comp == l && ComponentsManager.safeName(it.file) !in stored }) { it.file }
return catalog.filter { it.comp == l && ComponentsManager.safeName(it.file) !in stored }
}
private fun availableRows(l: String, catalog: List<CatalogItem>, snapshot: Snapshot?, toolDir: String?): List<Pair<CatalogItem, CatalogItem?>> {
val available = availableFor(l, catalog, snapshot, toolDir)
private fun availableRows(l: String, catalog: List<CatalogItem>, snapshot: Snapshot?): List<Pair<CatalogItem, CatalogItem?>> {
val available = availableFor(l, catalog, snapshot)
val pairs = ComponentsManager.nightlyPairs(available)
val paired = pairs.values.toSet()
return available.filter { it !in paired }.map { it to pairs[it] }
@@ -1201,7 +1201,7 @@ private fun GameComponentOverrides(
}
GamePackageRow(
comp = "fex",
packages = ComponentsManager.forTool("fex", protonChoice?.dir ?: generalProton?.dir?.name, packages, componentChoices["fex"]) { it.file },
packages = packages,
selectedFile = componentChoices["fex"],
open = componentMenu == "fex",
busy = busy,
@@ -1629,7 +1629,7 @@ private fun DeviceChip(s: GpuDriversState) {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.onGloballyPositioned { at = it.boundsInRoot() }.heightIn(min = 44.dp).paneItem("gpu-device").clip(shape)
.background(colors.surface).then(if (hot) Modifier.background(pal.signal.copy(alpha = 0.14f)) else Modifier)
.background(if (hot) pal.signal.copy(alpha = 0.14f) else colors.surface)
.glideBorder(hot, shape, pal.signal, pal.line)
.hoverable(src).clickable(interactionSource = src, indication = null, role = Role.Button, onClick = open)
.controllerConfirm(onClick = open)
@@ -12,7 +12,6 @@ object ControllerHaptics {
private val navKeys = setOf(
KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN, KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT,
KeyEvent.KEYCODE_BUTTON_A, KeyEvent.KEYCODE_BUTTON_L1, KeyEvent.KEYCODE_BUTTON_R1,
KeyEvent.KEYCODE_BUTTON_L2, KeyEvent.KEYCODE_BUTTON_R2,
)
fun onKey(context: Context, event: KeyEvent) {
@@ -309,7 +309,7 @@ private fun DesktopCard(
Column(
Modifier.width(width).paneItem("tile:desktop:$key").then(if (first) Modifier.firstTile() else Modifier)
.graphicsLayer { scaleX = scale; scaleY = scale }
.clip(shape).background(colors.surface).then(if (hot) Modifier.background(pal.signal.copy(alpha = 0.10f)) else Modifier)
.clip(shape).background(if (hot) pal.signal.copy(alpha = 0.10f) else colors.surface)
.glideBorder(hot, shape, pal.signal, pal.line)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button) { onClick(artAt) }
.controllerConfirm { onClick(artAt) }
@@ -761,20 +761,6 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
focusManager.clearFocus(force = true)
onRailSelect(key)
}, a)
val tabStep = androidx.compose.runtime.rememberUpdatedState { step: Int ->
if (!processSettingsPageVisible) {
val keys = navigationKeys(s)
keys.getOrNull(keys.indexOf(railSelectionNow.value) + step)?.let { key ->
PageSwipe.direction = step
onRailSelect(key)
}
}
}
DisposableEffect(Unit) {
val handler: (Int) -> Unit = { tabStep.value(it) }
MainTabSteps.handler = handler
onDispose { if (MainTabSteps.handler === handler) MainTabSteps.handler = null }
}
CompositionLocalProvider(LocalShowSection provides { key -> selected = key }) {
val swipeContext = androidx.compose.ui.platform.LocalContext.current
remember { com.droiddeck.launcher.core.AppUiPrefs.pageSwipe(swipeContext).also { PageSwipe.on = it } }
@@ -782,7 +768,19 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
LauncherLayout(
bottomNavigation && !s.dualScreen, pal.line,
Modifier.fillMaxSize().onGloballyPositioned { screenAt = it.positionInRoot() }
.then(if (openTab == "agent") Modifier.imePadding() else Modifier),
.then(if (openTab == "agent") Modifier.imePadding() else Modifier)
.then(if (s.dualScreen) Modifier.onKeyEvent { event ->
val step = dualPageStep(event.nativeKeyEvent) ?: return@onKeyEvent false
if (event.type == KeyEventType.KeyDown && !processSettingsPageVisible) {
val keys = navigationKeys(s)
val at = keys.indexOf(railSelectionNow.value)
keys.getOrNull(at + step)?.let { key ->
PageSwipe.direction = step
onRailSelect(key)
}
}
true
} else Modifier),
navigation = {
if (s.dualScreen || (bottomNavigation && agentKeyboardOpen)) Unit
else if (bottomNavigation) BottomBar(s, railSelection, onRailSelect, onRailFocus, a, railFocus)
@@ -904,7 +902,3 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
}
}
}
internal object MainTabSteps {
@Volatile var handler: ((Int) -> Unit)? = null
}
@@ -1166,7 +1166,7 @@ private fun SettingCard(label: String, value: String, id: String, modifier: Modi
verticalArrangement = Arrangement.spacedBy(3.dp),
modifier = modifier.paneItem(id)
.graphicsLayer { scaleX = scale; scaleY = scale }
.then(if (LocalGlass.current != null) Modifier.glass(Shape14, if (hot) 0.04f else 0f) else Modifier.clip(Shape14).background(colors.surface).then(if (hot) Modifier.background(pal.signal.copy(alpha = 0.10f)) else Modifier))
.then(if (LocalGlass.current != null) Modifier.glass(Shape14, if (hot) 0.04f else 0f) else Modifier.clip(Shape14).background(if (hot) pal.signal.copy(alpha = 0.10f) else colors.surface))
.glideBorder(hot, Shape14, pal.signal, if (LocalGlass.current != null) Color.Transparent else pal.line2)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onClick)
.controllerConfirm(onClick = onClick)
@@ -211,7 +211,6 @@ internal fun PrimaryButton(
val pal = LocalPalette.current
val pillMode = LocalPillButtons.current
val btnShape = if (pillMode) CircleShape else Shape12
val outlined = LocalGradientOutline.current && enabled
val frontFocus = if (main) LocalFrontFocus.current else null
if (frontFocus != null) DisposableEffect(Unit) {
frontFocus.primaryAttached++
@@ -235,7 +234,6 @@ internal fun PrimaryButton(
.clip(btnShape)
.background(if (enabled) Brush.linearGradient(listOf(colors.primary, pal.primary2)) else Brush.linearGradient(listOf(colors.surfaceVariant, colors.surfaceVariant)))
.then(if (enabled) Modifier else Modifier.border(1.dp, pal.line2, btnShape))
.then(if (outlined) Modifier.border(2.dp, Brush.linearGradient(listOf(pal.primary2, colors.primary)), btnShape) else Modifier)
.glideBorder(hot, btnShape, pal.signal, hotFillAlpha = 0f)
.hoverable(src).clickable(role = Role.Button, interactionSource = src, indication = null, enabled = enabled) {
placed[0]?.takeIf { it.isAttached }?.let { LaunchOrigin.mark(it.boundsInRoot(), placed) }
@@ -75,7 +75,6 @@ import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.boundsInRoot
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.positionInParent
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.layout.positionInRoot
import androidx.compose.ui.platform.LocalDensity
@@ -132,9 +131,6 @@ import kotlinx.coroutines.withContext
import java.io.File
import androidx.compose.runtime.setValue
import androidx.compose.runtime.getValue
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.layout.offset
internal class GameRef(val appId: Int?, val store: Store?, val storeId: String?) {
fun game(games: List<Library.SteamGame>): Library.SteamGame? = when {
@@ -258,18 +254,12 @@ internal fun GameDetail(
color = MaterialTheme.colorScheme.error, maxLines = 3, overflow = TextOverflow.Ellipsis,
)
Spacer(Modifier.height(2.dp))
Column {
CompositionLocalProvider(LocalPillButtons provides true, LocalGradientOutline provides true) {
GameActions(store, id, game, item, installed, s, a, Modifier.focusRequester(lead), compactMenu = stacked, inStore = inStore, part = ActionPart.LEAD)
}
Spacer(Modifier.height(LeadGap - ActionGap))
GameCapsule(scores) { GameActions(store, id, game, item, installed, s, a, Modifier, compactMenu = stacked, inStore = inStore, part = ActionPart.REST) }
}
GameCapsule(scores) { GameActions(store, id, game, item, installed, s, a, Modifier.focusRequester(lead), compactMenu = stacked, inStore = inStore) }
}
}
if (StoresMotion.heroLands) header() else Rise(1) { header() }
if (tab != null) Rise(2) {
Column(Modifier.fillMaxWidth().padding(top = ActionGap), verticalArrangement = Arrangement.spacedBy(ActionGap)) {
Column(Modifier.fillMaxWidth().padding(top = 14.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
val labels = tabs.map { t ->
when (t) {
GameTab.ABOUT -> stringResource(R.string.game_tab_about)
@@ -287,17 +277,15 @@ internal fun GameDetail(
focusRequesters = tabs.map { tabFocus.getValue(it) }, bumpers = tabs.size > 1, compact = stacked,
)
Box(Modifier.fillMaxWidth().onFocusChanged { if (inPanel && !it.hasFocus) dropped++; inPanel = it.hasFocus }.testTag("game-tab-${tab.name.lowercase()}")) {
CompositionLocalProvider(LocalRevealChecked provides false) {
when (tab) {
GameTab.ABOUT -> AboutTab(developer, publisher, releaseDate, description, scores, stacked) {
if (!s.shortcutPicker) GameResourcesRow(title.takeUnless { it == id }.orEmpty(), game)
}
GameTab.ACHIEVEMENTS -> achievementState?.let { st -> AchievementsTab(StoreAchievements.forSource(store?.id)?.label.orEmpty(), st) }
GameTab.LAUNCH -> if (game != null) LaunchTab(game, s, a, hopRail)
GameTab.SAVES -> if (game != null && prefix != null) SavesTab(game, prefix, a)
GameTab.ADDONS -> if (game != null) AddonsTab(game, addonTargets, a)
GameTab.INSTALL -> InstallTab(game, installed, item, store)
when (tab) {
GameTab.ABOUT -> AboutTab(developer, publisher, releaseDate, description, scores, stacked) {
if (!s.shortcutPicker) GameResourcesRow(title.takeUnless { it == id }.orEmpty(), game)
}
GameTab.ACHIEVEMENTS -> achievementState?.let { st -> AchievementsTab(StoreAchievements.forSource(store?.id)?.label.orEmpty(), st) }
GameTab.LAUNCH -> if (game != null) LaunchTab(game, s, a, hopRail)
GameTab.SAVES -> if (game != null && prefix != null) SavesTab(game, prefix, a)
GameTab.ADDONS -> if (game != null) AddonsTab(game, addonTargets, a)
GameTab.INSTALL -> InstallTab(game, installed, item, store)
}
}
}
@@ -360,22 +348,14 @@ private fun StatusChip(text: String, icon: androidx.compose.ui.graphics.vector.I
}
}
private val ActionGap = 12.dp
private val LeadGap = 20.dp
@Composable
private fun GameCapsule(scores: GameScores?, actions: @Composable () -> Unit) {
var noActions by remember { mutableStateOf(false) }
val shown = scores?.takeIf { it.metacritic != Lookup.None || it.hltb != Lookup.None }
val empty = noActions && shown == null
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().then(if (empty) Modifier else Modifier.padding(top = ActionGap).glass(RoundedCornerShape(30.dp)).padding(6.dp)),
modifier = Modifier.fillMaxWidth().glass(RoundedCornerShape(30.dp)).padding(6.dp),
) {
CompositionLocalProvider(LocalPillButtons provides true) {
Box(Modifier.weight(1f).onSizeChanged { noActions = it.height == 0 }) { actions() }
}
shown?.let { CapsuleScores(it, Modifier.padding(start = 8.dp, end = 10.dp)) }
CompositionLocalProvider(LocalPillButtons provides true) { Box(Modifier.weight(1f)) { actions() } }
if (scores != null) CapsuleScores(scores, Modifier.padding(start = 8.dp, end = 10.dp))
}
}
@@ -387,95 +367,41 @@ private fun GameTabBar(
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val scroll = rememberScrollState()
val spans = remember(tabs.size) { androidx.compose.runtime.mutableStateListOf<IntRange?>(*arrayOfNulls<IntRange>(tabs.size)) }
var tabHeight by remember { mutableStateOf(0) }
var viewport by remember { mutableStateOf(0) }
LaunchedEffect(selected, viewport) {
val span = spans.getOrNull(selected) ?: return@LaunchedEffect
if (viewport > 0) scroll.animateScrollTo((span.first + span.last) / 2 - viewport / 2)
}
Row(modifier.fillMaxWidth().glass(CircleShape).padding(4.dp), verticalAlignment = Alignment.CenterVertically) {
if (bumpers) TabBarBumper("LB", stringResource(R.string.widgets_prev_tab), leading = true) { onSelect((selected + tabs.size - 1) % tabs.size) }
androidx.compose.foundation.layout.BoxWithConstraints(Modifier.weight(1f).clip(if (bumpers) RoundedCornerShape(BumperFlat) else CircleShape).onSizeChanged { viewport = it.width }) {
val share = maxWidth / tabs.size.coerceAtLeast(1)
Box(Modifier.horizontalScroll(scroll)) {
spans.getOrNull(selected)?.takeIf { tabHeight > 0 }?.let { span ->
TabHighlight(span, tabHeight, flatStart = bumpers && selected == 0, flatEnd = bumpers && selected == tabs.lastIndex)
}
Row(verticalAlignment = Alignment.CenterVertically) {
tabs.forEachIndexed { i, label ->
val on = i == selected
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val pick = { onSelect(i) }
val shape = tabShape(flatStart = bumpers && i == 0, flatEnd = bumpers && i == tabs.lastIndex)
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.widthIn(min = share)
.onGloballyPositioned { c -> val x = c.positionInParent().x.toInt(); val r = x..(x + c.size.width); if (spans[i] != r) spans[i] = r; tabHeight = c.size.height }
.testTag("tab-$i")
.then(focusRequesters?.getOrNull(i)?.let { Modifier.focusRequester(it) } ?: Modifier)
.clip(shape)
.background(if (hot && !on) pal.signal.copy(alpha = 0.14f) else Color.Transparent)
.glideBorder(hot, shape, pal.signal)
.hoverable(src).selectable(selected = on, interactionSource = src, indication = null, role = Role.Tab, onClick = pick)
.controllerConfirm(onClick = pick)
.padding(horizontal = 12.dp, vertical = if (compact) 8.dp else 10.dp),
) {
Text(
label, fontSize = if (compact) 13.sp else 14.sp, fontWeight = if (on) FontWeight.Bold else FontWeight.SemiBold, maxLines = 1, overflow = TextOverflow.Ellipsis,
color = if (on || hot) colors.onBackground else colors.onSurfaceVariant,
)
}
}
}
tabs.forEachIndexed { i, label ->
val on = i == selected
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val pick = { onSelect(i) }
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.weight(1f)
.testTag("tab-$i")
.then(focusRequesters?.getOrNull(i)?.let { Modifier.focusRequester(it) } ?: Modifier)
.clip(CircleShape)
.background(if (on) pal.signal.copy(alpha = 0.3f) else if (hot) pal.signal.copy(alpha = 0.14f) else Color.Transparent)
.glideBorder(hot, CircleShape, pal.signal, if (on) pal.signal.copy(alpha = 0.5f) else Color.Transparent)
.hoverable(src).selectable(selected = on, interactionSource = src, indication = null, role = Role.Tab, onClick = pick)
.controllerConfirm(onClick = pick)
.padding(horizontal = 6.dp, vertical = if (compact) 8.dp else 10.dp),
) {
Text(
label, fontSize = if (compact) 13.sp else 14.sp, fontWeight = if (on) FontWeight.Bold else FontWeight.SemiBold, maxLines = 1, overflow = TextOverflow.Ellipsis,
color = if (on || hot) colors.onBackground else colors.onSurfaceVariant,
)
}
}
if (bumpers) TabBarBumper("RB", stringResource(R.string.widgets_next_tab), leading = false) { onSelect((selected + 1) % tabs.size) }
}
}
private val BumperFlat = 7.dp
@Composable
private fun TabHighlight(span: IntRange, height: Int, flatStart: Boolean, flatEnd: Boolean) {
val pal = LocalPalette.current
val density = LocalDensity.current
val spring = Motion.sp<Float>(0.8f, Spring.StiffnessMediumLow)
val x by animateFloatAsState(span.first.toFloat(), spring, label = "tabX")
val width by animateFloatAsState((span.last - span.first).toFloat(), spring, label = "tabWidth")
val start by animateFloatAsState(if (flatStart) 1f else 0f, spring, label = "tabFlatStart")
val end by animateFloatAsState(if (flatEnd) 1f else 0f, spring, label = "tabFlatEnd")
with(density) {
val round = (height / 2f).toDp()
val shape = RoundedCornerShape(
topStart = androidx.compose.ui.unit.lerp(round, BumperFlat, start), topEnd = androidx.compose.ui.unit.lerp(round, BumperFlat, end),
bottomEnd = androidx.compose.ui.unit.lerp(round, BumperFlat, end), bottomStart = androidx.compose.ui.unit.lerp(round, BumperFlat, start),
)
Box(
Modifier.offset { androidx.compose.ui.unit.IntOffset(x.toInt(), 0) }
.size(width.toDp(), height.toDp())
.clip(shape).background(pal.signal.copy(alpha = 0.3f)).border(1.dp, pal.signal.copy(alpha = 0.5f), shape),
)
}
}
private fun tabShape(flatStart: Boolean, flatEnd: Boolean): androidx.compose.ui.graphics.Shape {
if (!flatStart && !flatEnd) return CircleShape
val flat = androidx.compose.foundation.shape.CornerSize(BumperFlat)
val round = androidx.compose.foundation.shape.CornerSize(50)
val start = if (flatStart) flat else round
val end = if (flatEnd) flat else round
return RoundedCornerShape(topStart = start, topEnd = end, bottomEnd = end, bottomStart = start)
}
@Composable
private fun TabBarBumper(label: String, description: String, leading: Boolean, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val round = 22.dp
val flat = BumperFlat
val flat = 7.dp
val cap = if (leading) RoundedCornerShape(round, flat, flat, round) else RoundedCornerShape(flat, round, round, flat)
Box(
contentAlignment = Alignment.Center,
@@ -507,17 +433,12 @@ private fun GameTitle(title: String, logo: Any?, titleSize: TextUnit) {
)
}
internal enum class ActionPart { ALL, LEAD, REST }
@Composable
internal fun GameActions(
store: Store?, id: String?, game: Library.SteamGame?, item: CatalogItem?, installed: InstalledStoreGame?,
s: FrontEndState, a: FrontEndActions, leadOn: Modifier, compactMenu: Boolean = false, inStore: Boolean = false,
part: ActionPart = ActionPart.ALL,
) {
val ctx = LocalContext.current
val lead = part != ActionPart.REST
val rest = part != ActionPart.LEAD
val storeKey = if (store != null && id != null) "${store.id}:$id" else null
val rawDownload = storeKey?.let { StoresState.download(it) }
val download = rawDownload?.takeIf { it.isActive }
@@ -527,133 +448,127 @@ internal fun GameActions(
Actions {
when {
s.shortcutPicker && game != null -> {
if (lead) PrimaryButton(stringResource(R.string.game_shortcut_choose), enabled = !s.busy, main = true, icon = Icons.Filled.PlayArrow, modifier = leadOn) { a.onSteamGame(game) }
if (rest) FileButtons(game, a)
PrimaryButton(stringResource(R.string.game_shortcut_choose), enabled = !s.busy, main = true, icon = Icons.Filled.PlayArrow, modifier = leadOn) { a.onSteamGame(game) }
FileButtons(game, a)
}
!cloud && (game != null || installed != null) -> {
val gone = storeKey?.let { StoresState.uninstalling[it] }
val xboxBusy = store == Store.XBOX && id != null && XboxContent.busy(id)
val preparing = (game?.launchKey ?: storeKey)?.let { it in s.preparingGames } == true
if (lead) PrimaryButton(
PrimaryButton(
stringResource(if (preparing) R.string.store_starting else R.string.stores_play),
enabled = !s.busy && !preparing && gone == null && download == null && !xboxBusy && (store != Store.GOG || installed?.sidecar?.isInstalled != false),
main = true, icon = Icons.Filled.PlayArrow, modifier = leadOn,
) {
if (game != null) a.onSteamGame(game) else if (store != null && id != null) launchStoreGame(store, id, s, a)
}
if (rest) {
if (game != null) {
if (compactMenu) GameMoreMenu(game, a) else {
FileButtons(game, a)
GameShortcutMenu(game, a)
if (game != null) {
if (compactMenu) GameMoreMenu(game, a) else {
FileButtons(game, a)
GameShortcutMenu(game, a)
}
}
if (store == Store.ITCH && installed != null) ItchUpdateButton(installed, download == null && StoresState.uninstalling[installed.key] == null)
if (store == Store.GAMEJOLT && installed != null) GameJoltUpdateButton(installed, download == null && StoresState.uninstalling[installed.key] == null)
if (store == Store.GAMEJOLT && installed != null) GameJoltVersionButton(installed, download == null && StoresState.uninstalling[installed.key] == null)
if (inStore && store == Store.GAMEJOLT && installed != null) {
SecondaryButton(stringResource(R.string.stores_view_on, Store.GAMEJOLT.shortLabel)) {
openUrl(ctx, item?.storeUrl.orEmpty().ifBlank { GameJoltApi.pageUrl("game", installed.sidecar.id) })
}
}
if (store == Store.EA && installed != null) EaUpdateButton(installed, download == null && StoresState.uninstalling[installed.key] == null)
if (store == Store.GOG && installed != null) GogMaintenanceActions(installed)
if (store == Store.XBOX && id != null) XboxInstalledStream(id, game?.name ?: item?.title.orEmpty(), item)
if (store == Store.XBOX && installed != null && id != null) {
SecondaryButton(stringResource(R.string.stores_xbox_update), enabled = download == null && !XboxRuntime.isActive(id)) {
runCatching { XboxBackend.update(ctx, installed) }
.onFailure { StoresState.problems[Store.XBOX] = it.message ?: ctx.getString(R.string.stores_xbox_close_first) }
}
SecondaryButton(stringResource(R.string.stores_xbox_manage), enabled = download == null) { XboxContent.manage(ctx, installed) }
}
if (store == Store.BATTLENET) {
if (installed != null && id != null) {
LaunchedEffect(id) { BattleNetInstall.checkUpdate(ctx, installed) }
if (download != null) {
SteadyDownloadChip(download)
if (download.state != DownloadState.PAUSED) SecondaryButton(stringResource(R.string.stores_dl_pause)) { DownloadQueue.pause(download.key) }
else SecondaryButton(stringResource(R.string.stores_dl_resume)) { DownloadQueue.resume(ctx, download.key) }
} else if (BattleNetInstall.updates[id] == true) {
SecondaryButton(stringResource(R.string.bnet_update)) { BattleNetInstall.update(ctx, installed) }
}
}
if (store == Store.ITCH && installed != null) ItchUpdateButton(installed, download == null && StoresState.uninstalling[installed.key] == null)
if (store == Store.GAMEJOLT && installed != null) GameJoltUpdateButton(installed, download == null && StoresState.uninstalling[installed.key] == null)
if (store == Store.GAMEJOLT && installed != null) GameJoltVersionButton(installed, download == null && StoresState.uninstalling[installed.key] == null)
if (inStore && store == Store.GAMEJOLT && installed != null) {
SecondaryButton(stringResource(R.string.stores_view_on, Store.GAMEJOLT.shortLabel)) {
openUrl(ctx, item?.storeUrl.orEmpty().ifBlank { GameJoltApi.pageUrl("game", installed.sidecar.id) })
}
}
if (store == Store.EA && installed != null) EaUpdateButton(installed, download == null && StoresState.uninstalling[installed.key] == null)
if (store == Store.GOG && installed != null) GogMaintenanceActions(installed)
if (store == Store.XBOX && id != null) XboxInstalledStream(id, game?.name ?: item?.title.orEmpty(), item)
if (store == Store.XBOX && installed != null && id != null) {
SecondaryButton(stringResource(R.string.stores_xbox_update), enabled = download == null && !XboxRuntime.isActive(id)) {
runCatching { XboxBackend.update(ctx, installed) }
.onFailure { StoresState.problems[Store.XBOX] = it.message ?: ctx.getString(R.string.stores_xbox_close_first) }
}
SecondaryButton(stringResource(R.string.stores_xbox_manage), enabled = download == null) { XboxContent.manage(ctx, installed) }
}
if (store == Store.BATTLENET) {
if (installed != null && id != null) {
LaunchedEffect(id) { BattleNetInstall.checkUpdate(ctx, installed) }
if (download != null) {
SteadyDownloadChip(download)
if (download.state != DownloadState.PAUSED) SecondaryButton(stringResource(R.string.stores_dl_pause)) { DownloadQueue.pause(download.key) }
else SecondaryButton(stringResource(R.string.stores_dl_resume)) { DownloadQueue.resume(ctx, download.key) }
} else if (BattleNetInstall.updates[id] == true) {
SecondaryButton(stringResource(R.string.bnet_update)) { BattleNetInstall.update(ctx, installed) }
}
}
SecondaryButton(stringResource(R.string.bnet_open)) { a.onBattleNet() }
}
if (game != null && !compactMenu) {
HideButton(hideKey(game), game)
EditArtButton(game)
}
SecondaryButton(stringResource(R.string.bnet_open)) { a.onBattleNet() }
}
if (game != null && !compactMenu) {
HideButton(hideKey(game), game)
EditArtButton(game)
}
}
download != null -> {
if (rest) SteadyDownloadChip(download)
if (lead) {
if (download.state != DownloadState.PAUSED) SecondaryButton(stringResource(R.string.stores_dl_pause), modifier = leadOn) { DownloadQueue.pause(download.key) }
else PrimaryButton(stringResource(R.string.stores_dl_resume), main = true, modifier = leadOn) { DownloadQueue.resume(ctx, download.key) }
}
if (rest) ConfirmButton(stringResource(R.string.stores_dl_cancel), stringResource(R.string.stores_dl_cancel_confirm)) { DownloadQueue.cancel(ctx, download.key) }
SteadyDownloadChip(download)
if (download.state != DownloadState.PAUSED) SecondaryButton(stringResource(R.string.stores_dl_pause), modifier = leadOn) { DownloadQueue.pause(download.key) }
else PrimaryButton(stringResource(R.string.stores_dl_resume), main = true, modifier = leadOn) { DownloadQueue.resume(ctx, download.key) }
ConfirmButton(stringResource(R.string.stores_dl_cancel), stringResource(R.string.stores_dl_cancel_confirm)) { DownloadQueue.cancel(ctx, download.key) }
}
failed != null -> {
if (rest) ActionChip(stringResource(R.string.stores_dl_failed), ok = false)
if (lead) PrimaryButton(stringResource(R.string.stores_dl_resume), main = true, modifier = leadOn) {
ActionChip(stringResource(R.string.stores_dl_failed), ok = false)
PrimaryButton(stringResource(R.string.stores_dl_resume), main = true, modifier = leadOn) {
if (item != null) StoresState.requestInstall(ctx, item) else DownloadQueue.retry(ctx, failed.key)
}
if (rest) ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) { DownloadQueue.clear(ctx, failed.key) }
ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) { DownloadQueue.clear(ctx, failed.key) }
}
cloud -> {
val cloudId = game.storeId.orEmpty()
if (lead) XboxStreamButton(cloudId, game.name, main = true, modifier = leadOn)
if (rest && item?.installable == true && item.xboxPc) {
XboxStreamButton(cloudId, game.name, main = true, modifier = leadOn)
if (item?.installable == true && item.xboxPc) {
SecondaryButton(
if (StoresState.isUnfinished(item)) stringResource(R.string.stores_resume_install)
else if (downloadBytes > 0) stringResource(R.string.stores_install_size, formatBytes(downloadBytes))
else stringResource(R.string.stores_install),
) { StoresState.requestInstall(ctx, item) }
}
if (rest && item != null && StoresState.isUnfinished(item)) ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) { StoresState.clearUnfinished(ctx, item) }
if (rest) XboxLibraryButton(cloudId, item)
if (item != null && StoresState.isUnfinished(item)) ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) { StoresState.clearUnfinished(ctx, item) }
XboxLibraryButton(cloudId, item)
}
store == Store.BATTLENET && item != null -> if (lead) InstallButton(stringResource(R.string.stores_install), leadOn) { StoresState.requestInstall(ctx, item) }
store == Store.BATTLENET && item != null -> InstallButton(stringResource(R.string.stores_install), leadOn) { StoresState.requestInstall(ctx, item) }
store == Store.XBOX && item != null && !item.xboxPc && item.xboxCloud -> {
if (lead) XboxStreamButton(item.id, item.title, main = true, modifier = leadOn)
if (rest) XboxLibraryButton(item.id, item)
XboxStreamButton(item.id, item.title, main = true, modifier = leadOn)
XboxLibraryButton(item.id, item)
}
item?.installable == true && StoresState.isUnfinished(item) -> {
if (lead) InstallButton(stringResource(R.string.stores_resume_install), leadOn) { StoresState.requestInstall(ctx, item) }
if (rest) ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) { StoresState.clearUnfinished(ctx, item) }
InstallButton(stringResource(R.string.stores_resume_install), leadOn) { StoresState.requestInstall(ctx, item) }
ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) { StoresState.clearUnfinished(ctx, item) }
}
item?.installable == true -> {
if (lead) InstallButton(
InstallButton(
if (downloadBytes > 0) stringResource(R.string.stores_install_size, formatBytes(downloadBytes)) else stringResource(R.string.stores_install),
leadOn,
) { StoresState.requestInstall(ctx, item) }
if (rest && store == Store.XBOX && item.xboxCloud) {
if (store == Store.XBOX && item.xboxCloud) {
XboxStreamButton(item.id, item.title)
XboxLibraryButton(item.id, item)
}
if (rest && !item.accessible) SecondaryButton(buyLabel(item)) { openStoreUrl(ctx, item) }
if (!item.accessible) SecondaryButton(buyLabel(item)) { openStoreUrl(ctx, item) }
}
item != null && (item.store == Store.ITCH || item.store == Store.GAMEJOLT) && item.isFree -> {
if (lead) InstallButton(stringResource(R.string.stores_install), leadOn) { StoresState.requestInstall(ctx, item) }
if (rest) SecondaryButton(stringResource(R.string.stores_view_on, item.store.shortLabel)) { openStoreUrl(ctx, item) }
InstallButton(stringResource(R.string.stores_install), leadOn) { StoresState.requestInstall(ctx, item) }
SecondaryButton(stringResource(R.string.stores_view_on, item.store.shortLabel)) { openStoreUrl(ctx, item) }
}
item != null && item.isFree -> if (lead) {
item != null && item.isFree -> {
val adding = StoresState.claiming[item.key] == true
PrimaryButton(stringResource(if (adding) R.string.stores_claiming else R.string.stores_get_free), enabled = !adding, main = true, modifier = leadOn) {
if (StoresState.canClaim(item)) StoresState.claim(ctx, item) { openStoreUrl(ctx, item) } else openStoreUrl(ctx, item)
}
}
item != null -> if (lead) PrimaryButton(buyLabel(item), main = true, modifier = leadOn) { openStoreUrl(ctx, item) }
item != null -> PrimaryButton(buyLabel(item), main = true, modifier = leadOn) { openStoreUrl(ctx, item) }
}
if (rest) {
val entryKey = game?.let(::hideKey) ?: storeKey
if (!s.shortcutPicker && entryKey != null && (game == null || cloud)) HideButton(entryKey, game)
if (cloud && (download != null || failed != null)) {
XboxStreamButton(game.storeId.orEmpty(), game.name)
XboxLibraryButton(game.storeId.orEmpty(), item)
}
BusyChip(s)
val entryKey = game?.let(::hideKey) ?: storeKey
if (!s.shortcutPicker && entryKey != null && (game == null || cloud)) HideButton(entryKey, game)
if (cloud && (download != null || failed != null)) {
XboxStreamButton(game.storeId.orEmpty(), game.name)
XboxLibraryButton(game.storeId.orEmpty(), item)
}
BusyChip(s)
}
}
@@ -1049,7 +964,7 @@ private fun SavesTab(g: Library.SteamGame, prefix: File, a: FrontEndActions) {
@Composable
private fun AddonsTab(g: Library.SteamGame, targets: List<WowAddons.Target>, a: FrontEndActions) {
var browsing by remember(g.gameId) { mutableStateOf<WowAddons.Target?>(null) }
browsing?.let { AddonBrowserDialog(targets, it, CurseForgeApp.find(UserAppsState.items)) { browsing = null } }
browsing?.let { AddonBrowserDialog(targets, it) { browsing = null } }
Column(Modifier.fillMaxWidth().tabPanel(), verticalArrangement = Arrangement.spacedBy(2.dp)) {
CurseForgeEntry(a)
targets.forEach { target ->
@@ -58,7 +58,6 @@ import coil.size.Precision
import kotlin.math.max
internal val LocalPillButtons = compositionLocalOf { false }
internal val LocalGradientOutline = compositionLocalOf { false }
internal class GlassBackdrop {
var painter: Painter? = null
@@ -60,7 +60,7 @@ internal fun gameResources(title: String, game: Library.SteamGame?): List<GameRe
internal fun GameResourcesRow(title: String, game: Library.SteamGame?, modifier: Modifier = Modifier) {
val links = remember(title, game) { gameResources(title, game) }
if (links.isEmpty()) return
FlowRow(modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
FlowRow(modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(10.dp)) {
links.forEach { ResourceLink(it) }
}
}
@@ -79,14 +79,14 @@ private fun ResourceLink(link: GameResource) {
val tint = if (hot) pal.signal else pal.onSurfaceVariant
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(5.dp),
modifier = Modifier.paneItem("resource:${link.label}").heightIn(min = 34.dp).clip(shape)
modifier = Modifier.paneItem("resource:${link.label}").heightIn(min = 44.dp).clip(shape)
.background(if (hot) pal.signal.copy(alpha = 0.14f) else if (glass) Color.White.copy(alpha = 0.07f) else Color.Transparent)
.glideBorder(hot, shape, pal.signal, restColor = if (glass) Color.White.copy(alpha = 0.12f) else Color.Transparent)
.semantics { contentDescription = description }
.hoverable(source).clickable(interactionSource = source, indication = LocalIndication.current, role = Role.Button, onClick = open)
.controllerConfirm(onClick = open).padding(horizontal = if (glass) 11.dp else 8.dp),
.controllerConfirm(onClick = open).padding(horizontal = if (glass) 14.dp else 8.dp),
) {
Text(label, fontSize = 12.sp, fontWeight = FontWeight.Medium, color = if (glass && !hot) MaterialTheme.colorScheme.onBackground else tint, maxLines = 1)
Text(label, fontSize = if (glass) 13.sp else 12.sp, fontWeight = FontWeight.Medium, color = if (glass && !hot) MaterialTheme.colorScheme.onBackground else tint, maxLines = 1)
Icon(Icons.AutoMirrored.Filled.OpenInNew, contentDescription = null, tint = tint.copy(alpha = 0.65f), modifier = Modifier.size(11.dp))
}
}
@@ -267,6 +267,12 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
}
}
InputPage.SOURCE -> {
if (role == InputRole.PRIMARY) SettingsGroup(stringResource(R.string.input_screen_visibility)) {
ChoiceRow(host, "controller-osc", stringResource(R.string.mode_osc), stringResource(R.string.input_visibility_shared),
listOf(SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto), SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always),
SessionPrefs.OSC_STEAM_TOUCH to stringResource(R.string.osc_steam_touch), SessionPrefs.OSC_STEAM_QAM to stringResource(R.string.mode_osc_qam), SessionPrefs.OSC_NEVER to stringResource(R.string.common_never)),
oscMode) { SessionPrefs.setOscMode(context, it); oscMode = it; onChanged() }
}
if (layout != null) SettingsGroup(stringResource(R.string.ctrl_layout)) {
if (layout.editable) InputNavigationRow(stringResource(R.string.input_edit_layout), layout.name, Modifier.testTag("input-surface-${role.name.lowercase()}")) { surface = true }
else InputHint(layout.name)
@@ -282,12 +288,6 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
}
if (role == InputRole.SECONDARY) InputHint(stringResource(R.string.input_second_screen_enable))
}
if (role == InputRole.PRIMARY) SettingsGroup(stringResource(R.string.input_screen_visibility)) {
ChoiceRow(host, "controller-osc", stringResource(R.string.mode_osc), stringResource(R.string.input_visibility_shared),
listOf(SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto), SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always),
SessionPrefs.OSC_STEAM_TOUCH to stringResource(R.string.osc_steam_touch), SessionPrefs.OSC_STEAM_QAM to stringResource(R.string.mode_osc_qam), SessionPrefs.OSC_NEVER to stringResource(R.string.common_never)),
oscMode) { SessionPrefs.setOscMode(context, it); oscMode = it; onChanged() }
}
SettingsGroup(stringResource(R.string.input_assign_actions)) {
val users = library.usersOfBindings(preset.id)
if (users.size > 1) InputHint(stringResource(R.string.input_shared_with, users.filterNot { it.id == profileId }.joinToString { it.name }))
@@ -90,7 +90,6 @@ import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.boundsInRoot
import androidx.compose.ui.layout.layout
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalContext
@@ -914,6 +913,7 @@ private fun LibraryFilters(sources: List<String>, source: String, onSource: (Str
horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().padding(top = 4.dp, bottom = 2.dp),
) {
if (manage) ManageStoresChip()
Box(Modifier.weight(1f).edgeFade(scroll).horizontalScroll(scroll)) {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.focusGroup()) {
for (id in keys) {
@@ -945,7 +945,6 @@ private fun LibraryFilters(sources: List<String>, source: String, onSource: (Str
}
if (highlighted in keys) ChipGlide(keys.indexOf(highlighted), bounds[highlighted], tint, visible = fillShown)
}
if (manage) ManageStoresChip()
}
}
}
@@ -1122,22 +1121,14 @@ internal fun ArtCard(
}
val showName = LibraryDisplay.title || hot
val showDetail = LibraryDisplay.size || hot
if (showName || showDetail) {
val top = with(androidx.compose.ui.platform.LocalDensity.current) { 20.dp.roundToPx() }
val bottom = with(androidx.compose.ui.platform.LocalDensity.current) { (if (download != null) 14.dp else 6.dp).roundToPx() }
Column(
verticalArrangement = Arrangement.spacedBy(1.dp),
modifier = Modifier.align(Alignment.BottomCenter).fillMaxWidth()
.background(Brush.verticalGradient(0f to Color.Transparent, 0.6f to Color.Black.copy(alpha = 0.78f), 1f to Color.Black.copy(alpha = 0.92f)))
.layout { measurable, constraints ->
val inner = measurable.measure(constraints)
if (inner.height == 0) layout(inner.width, 0) {} else layout(inner.width, inner.height + top + bottom) { inner.place(0, top) }
}
.padding(horizontal = 8.dp),
) {
if (showName) Text(title, fontSize = 11.sp, fontWeight = FontWeight.Bold, color = Color.White, maxLines = if (hot) 2 else 1, overflow = TextOverflow.Ellipsis, lineHeight = 13.sp)
if (showDetail) detail()
}
if (showName || showDetail) Column(
verticalArrangement = Arrangement.spacedBy(1.dp),
modifier = Modifier.align(Alignment.BottomCenter).fillMaxWidth()
.background(Brush.verticalGradient(0f to Color.Transparent, 0.6f to Color.Black.copy(alpha = 0.78f), 1f to Color.Black.copy(alpha = 0.92f)))
.padding(start = 8.dp, end = 8.dp, top = 20.dp, bottom = if (download != null) 14.dp else 6.dp),
) {
if (showName) Text(title, fontSize = 11.sp, fontWeight = FontWeight.Bold, color = Color.White, maxLines = if (hot) 2 else 1, overflow = TextOverflow.Ellipsis, lineHeight = 13.sp)
if (showDetail) detail()
}
if (download != null) Box(Modifier.align(Alignment.BottomCenter).padding(start = 6.dp, end = 6.dp, bottom = 5.dp)) {
ProgressBarThin(download.fraction, paused = download.state == DownloadState.PAUSED, verify = download.stage == DownloadStage.VERIFY)
@@ -81,7 +81,7 @@ private fun MoreTile(s: FrontEndState, key: String, first: Boolean, modifier: Mo
.then(if (first) Modifier.paneEntry() else Modifier.paneItem("more:$key"))
.testTag("more-$key")
.height(112.dp).clip(shape)
.background(colors.surface).then(if (hot) Modifier.background(pal.signal.copy(alpha = 0.12f)) else Modifier)
.background(if (hot) pal.signal.copy(alpha = 0.12f) else colors.surface)
.glideBorder(hot, shape, pal.signal, pal.line)
.hoverable(src)
.clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Tab, onClick = onClick)
@@ -1,76 +0,0 @@
package com.droiddeck.launcher.ui
import android.content.Context
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.input.pointer.PointerEventPass
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.LayoutCoordinates
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalView
import kotlinx.coroutines.flow.first
internal object ScreenTaps {
var count by mutableStateOf(0)
}
/** A field that opens on a heavy page can take focus after the next tap has already finished. */
@Composable
internal fun CancelPendingFocus(pending: Boolean, askedAtTap: Int, focused: Boolean, cancel: () -> Unit) {
val focusedNow by rememberUpdatedState(focused)
val cancelNow by rememberUpdatedState(cancel)
LaunchedEffect(pending, askedAtTap) {
if (!pending) return@LaunchedEffect
snapshotFlow { ScreenTaps.count }.first { it != askedAtTap }
if (!focusedNow) cancelNow()
}
}
/**
* Tapped controls do not take focus in touch mode, so a text field would otherwise keep it, and its highlight.
* [x] and [y] share coordinates with [origin], the field's own position.
*/
internal fun releaseTextField(field: EditText, origin: IntArray, x: Float, y: Float) {
val margin = 12 * field.resources.displayMetrics.density
val insideX = x >= origin[0] - margin && x <= origin[0] + field.width + margin
val insideY = y >= origin[1] - margin && y <= origin[1] + field.height + margin
if (insideX && insideY) return
field.clearFocus()
(field.context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager)?.hideSoftInputFromWindow(field.windowToken, 0)
}
/** A dialog's touches never reach the activity, so a dialog holding a search field counts its taps and releases the field itself. */
internal fun Modifier.releaseTextFieldOnTap(): Modifier = composed {
val view = LocalView.current
val placed = remember { arrayOfNulls<LayoutCoordinates>(1) }
onGloballyPositioned { placed[0] = it }.pointerInput(view) {
awaitEachGesture {
val down = awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial)
ScreenTaps.count++
var up: Offset? = null
while (true) {
val change = awaitPointerEvent(PointerEventPass.Final).changes.firstOrNull { it.id == down.id } ?: break
if ((change.position - down.position).getDistance() > viewConfiguration.touchSlop) break
if (!change.pressed) { up = change.position; break }
}
val at = up?.let { placed[0]?.takeIf { c -> c.isAttached }?.localToWindow(it) } ?: return@awaitEachGesture
view.post {
val field = view.findFocus() as? EditText ?: return@post
releaseTextField(field, IntArray(2).also(field::getLocationInWindow), at.x, at.y)
}
}
}
}
@@ -1608,15 +1608,12 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
chipModifier = track("cmp-proton"),
onPick = { id -> a.onGameProton(gameProfile.appId, id) },
)
val gameTool = snap.protons.firstOrNull { it.proton.id == gameProfile.protonId }?.proton?.dir?.name
for (comp in ComponentsManager.COMPONENTS) {
val value = gameProfile.components.getValue(comp)
val managedDxvk = ComponentsManager.runtimeManaged(comp, a.systemPowerVr)
val options: List<Pair<String?, String>> =
listOf(null to stringResource(R.string.comp_game_use_general)) +
if (managedDxvk) emptyList() else ComponentsManager.forTool(
comp, gameTool, snap.packages.filter { it.comp == comp }, gameProfile.componentFiles[comp],
) { it.file }.map { it.file to it.version }
if (managedDxvk) emptyList() else snap.packages.filter { it.comp == comp }.map { it.file to it.version }
DrawerStackedChoice(
host = host,
key = "game-cmp-$comp",
@@ -1699,7 +1696,7 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
val managedDxvk = ComponentsManager.runtimeManaged(comp, a.systemPowerVr)
val originals = view.originals.filter { it.comp == comp }
val options = originals.map { "orig:${it.protonVersion}" to (if (it.protonVersion == build) originalLabel else stringResource(R.string.comp_original, it.protonVersion)) } +
ComponentsManager.forTool(comp, p.dir.name, snap.packages.filter { it.comp == comp }, st.activeFile) { it.file }.map { it.file to it.version }
snap.packages.filter { it.comp == comp }.map { it.file to it.version }
if (options.isEmpty() && !managedDxvk) continue
val current = st.activeFile ?: "orig:$build"
val shown = options.firstOrNull { it.first == current }?.second
@@ -49,12 +49,6 @@ internal fun SettingsPillSearch(
val icon = remember { FocusRequester() }
var toIcon by remember { mutableStateOf(false) }
var focusOnOpen by remember { mutableStateOf(false) }
var focusTap by remember { mutableStateOf(0) }
var fieldFocused by remember { mutableStateOf(false) }
CancelPendingFocus(focusOnOpen, focusTap, fieldFocused) {
focusOnOpen = false
if (query.isEmpty()) onClose()
}
val close = { toIcon = true; focusOnOpen = false; onClose() }
BackHandler(enabled = searching) { close() }
LaunchedEffect(toIcon, searching, open <= 0.01f) {
@@ -79,18 +73,15 @@ internal fun SettingsPillSearch(
Box(Modifier.width(w).graphicsLayer { alpha = (open * 1.6f).coerceAtMost(1f) }) {
AdbTextField(
value = query, onValueChange = onQuery, label = "", keyboardType = KeyboardType.Text, imeAction = ImeAction.Search,
placeholder = stringResource(R.string.settings_search), compact = true, showLabel = false, focusOnShow = focusOnOpen, focusAtTap = focusTap,
placeholder = stringResource(R.string.settings_search), compact = true, showLabel = false, focusOnShow = focusOnOpen,
clearFocus = !searching,
onFocusChange = { focused ->
fieldFocused = focused
if (!focused && query.isEmpty() && searching) { focusOnOpen = false; onClose() }
},
onFocusChange = { focused -> if (!focused && query.isEmpty() && searching) { focusOnOpen = false; onClose() } },
)
}
SmallIconButton(Icons.Filled.Close, stringResource(R.string.settings_search_clear), tint = colors.onSurfaceVariant) { close() }
}
} else {
Box(Modifier.focusRequester(icon)) { SearchIcon(stringResource(R.string.settings_search)) { focusTap = ScreenTaps.count; focusOnOpen = true; onOpen() } }
Box(Modifier.focusRequester(icon)) { SearchIcon(stringResource(R.string.settings_search)) { focusOnOpen = true; onOpen() } }
}
}
}
@@ -163,8 +163,6 @@ internal fun Modifier.bumpers(onPrevious: () -> Unit, onNext: () -> Unit): Modif
}
}
internal val LocalRevealChecked = androidx.compose.runtime.compositionLocalOf { true }
@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
@Composable
internal fun TabStrip(
@@ -349,7 +347,7 @@ fun AnchoredMenu(
}
}
.verticalScroll(scroll),
) { androidx.compose.runtime.CompositionLocalProvider(LocalRevealChecked provides true) { content(firstItemFocus) } }
) { content(firstItemFocus) }
if (scroll.canScrollForward) Icon(
Icons.Filled.KeyboardArrowDown, contentDescription = null, tint = colors.onSurfaceVariant,
modifier = Modifier.align(Alignment.BottomCenter).size(20.dp),
@@ -379,7 +377,7 @@ fun MenuItem(
val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value
val shift by animateFloatAsState(if (hot) 2f else 0f, Motion.sp(0.5f), label = "miShift")
val reveal = remember { androidx.compose.foundation.relocation.BringIntoViewRequester() }
if (checked && LocalRevealChecked.current) LaunchedEffect(Unit) { reveal.bringIntoView() }
if (checked) LaunchedEffect(Unit) { reveal.bringIntoView() }
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = modifier.fillMaxWidth()
@@ -453,7 +453,7 @@ private fun BucketCard(
modifier = modifier.paneItem("storage:${bucket.name}")
.graphicsLayer { scaleX = scale; scaleY = scale }
.clip(Shape14)
.background(colors.surface).then(if (hot) Modifier.background(pal.signal.copy(alpha = 0.10f)) else Modifier)
.background(if (hot) pal.signal.copy(alpha = 0.10f) else colors.surface)
.glideBorder(hot, Shape14, pal.signal, pal.line)
.then(if (onClick != null) Modifier.hoverable(src)
.clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onClick)
@@ -174,7 +174,7 @@ internal fun AchievementRow(a: Achievement, compact: Boolean, modifier: Modifier
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = modifier.fillMaxWidth().clip(shape)
.background(colors.surface).then(if (hot) Modifier.background(pal.signal.copy(alpha = 0.10f)) else Modifier)
.background(if (hot) pal.signal.copy(alpha = 0.10f) else colors.surface)
.glideBorder(hot, shape, pal.signal, pal.line)
.focusable(interactionSource = interaction)
.padding(if (compact) 8.dp else 10.dp),
@@ -369,7 +369,7 @@ internal fun DrawerAchievementsRow(progress: Pair<Int, Int>?, modifier: Modifier
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp),
modifier = modifier.fillMaxWidth().height(44.dp).clip(shape)
.background(colors.surface).then(if (hot) Modifier.background(pal.signal.copy(alpha = 0.14f)) else Modifier)
.background(if (hot) pal.signal.copy(alpha = 0.14f) else colors.surface)
.glideBorder(hot, shape, pal.signal, pal.line)
.clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = interaction, indication = LocalIndication.current, onClick = onClick)
.controllerConfirm(onClick = onClick)
@@ -533,7 +533,7 @@ private fun AppCard(app: CardApp, size: Dp, first: Boolean, cards: HashMap<Strin
Column(
Modifier.width(size).paneItem("tile:store:${app.id}").then(if (first) Modifier.firstTile() else Modifier)
.graphicsLayer { scaleX = scale; scaleY = scale }
.clip(shape).background(colors.surface).then(if (hot) Modifier.background(pal.signal.copy(alpha = 0.10f)) else Modifier)
.clip(shape).background(if (hot) pal.signal.copy(alpha = 0.10f) else colors.surface)
.glideBorder(hot, shape, pal.signal, pal.line)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onClick)
.controllerConfirm(onClick = onClick)
@@ -925,12 +925,6 @@ internal fun ModeHeader(
val pal = LocalPalette.current
var searching by remember { mutableStateOf(query.isNotEmpty()) }
var focusOnOpen by remember { mutableStateOf(false) }
var focusTap by remember { mutableStateOf(0) }
var fieldFocused by remember { mutableStateOf(false) }
CancelPendingFocus(focusOnOpen, focusTap, fieldFocused) {
focusOnOpen = false
if (query.isEmpty()) searching = false
}
val open by animateFloatAsState(if (searching) 1f else 0f, Motion.sp(0.75f, 420f), label = "searchOpen")
// Closing takes the field away with focus still in it; the search button gets it once it is back on screen.
val searchIcon = remember { FocusRequester() }
@@ -961,12 +955,9 @@ internal fun ModeHeader(
Box(Modifier.width(w).graphicsLayer { alpha = (open * 1.6f).coerceAtMost(1f) }) {
AdbTextField(
value = query, onValueChange = onQuery, label = "", keyboardType = KeyboardType.Text, imeAction = ImeAction.Search,
placeholder = placeholder, compact = true, showLabel = false, focusOnShow = focusOnOpen, focusAtTap = focusTap,
placeholder = placeholder, compact = true, showLabel = false, focusOnShow = focusOnOpen,
clearFocus = clearSearchFocus || !searching,
onFocusChange = { focused ->
fieldFocused = focused
if (!focused && query.isEmpty()) { searching = false; focusOnOpen = false }
},
onFocusChange = { focused -> if (!focused && query.isEmpty()) { searching = false; focusOnOpen = false } },
)
}
if (searching && closable) SmallIconButton(Icons.Filled.Close, stringResource(R.string.common_close), tint = colors.onSurfaceVariant, onClick = close)
@@ -974,7 +965,7 @@ internal fun ModeHeader(
}
}
val searchButton: @Composable () -> Unit = {
Box(Modifier.focusRequester(searchIcon)) { SearchIcon(stringResource(R.string.stores_search_open)) { focusTap = ScreenTaps.count; searching = true; focusOnOpen = true } }
Box(Modifier.focusRequester(searchIcon)) { SearchIcon(stringResource(R.string.stores_search_open)) { searching = true; focusOnOpen = true } }
}
BoxWithConstraints(Modifier.fillMaxWidth()) {
val stacked = maxWidth < NarrowPaneWidth
@@ -365,13 +365,11 @@ internal fun AdbTextField(
onDone: (() -> Unit)? = null,
focusOnShow: Boolean = false,
showLabel: Boolean = true,
focusAtTap: Int? = null,
onBack: (() -> Unit)? = null,
) {
val context = LocalContext.current
val onBackLatest = rememberUpdatedState(onBack)
val focusAsked = remember { booleanArrayOf(false) }
val focusTapAsked = remember { arrayOfNulls<Int>(1) }
val palette = LocalPalette.current
val onValueChangeLatest = rememberUpdatedState(onValueChange)
val onNextLatest = rememberUpdatedState(onNext)
@@ -504,12 +502,9 @@ internal fun AdbTextField(
},
update = { editText ->
editText.showSoftInputOnFocus = !bottomTyping
// A new tap may ask again: a field still on screen while it closes can be opened once more.
val fresh = if (focusAtTap != null) focusTapAsked[0] != focusAtTap else !focusAsked[0]
if (focusOnShow && fresh) {
if (focusAtTap != null) focusTapAsked[0] = focusAtTap else focusAsked[0] = true
if (focusOnShow && !focusAsked[0]) {
focusAsked[0] = true
editText.post {
if (focusAtTap != null && focusAtTap != ScreenTaps.count) return@post
editText.requestFocus()
if (!bottomTypingLatest.value) (editText.context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE) as? android.view.inputmethod.InputMethodManager)
?.showSoftInput(editText, android.view.inputmethod.InputMethodManager.SHOW_IMPLICIT)
@@ -10,8 +10,6 @@ import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionState
object CompositorHost {
private const val TAG = "DroidDeck"
@Volatile
private var started = false
@@ -57,52 +55,6 @@ object CompositorHost {
}
}
class Output internal constructor(
internal val runtimeDir: java.io.File,
internal val turnip: com.droiddeck.launcher.gpu.TurnipDriver,
internal val driverId: String?,
)
fun prepare(context: android.content.Context): Output {
val runtimeDir = java.io.File(context.filesDir, ".wayland-rt").apply { mkdirs() }
com.droiddeck.launcher.core.FileUtils.copyAsset(context, "wayland/keymap.xkb", java.io.File(runtimeDir, "keymap.xkb"))
com.droiddeck.launcher.input.VrControllers.publish(context)
val turnip = com.droiddeck.launcher.gpu.TurnipDriver(context)
com.droiddeck.launcher.gpu.DriverSetupLog.write(context, "surface.driver-setup")
if (!started) {
displayChoice = SessionPrefs.androidDriver(context)
com.droiddeck.launcher.gpu.AutoDriverTrial.displayStarting(context, SessionPrefs.androidDriver(context))
}
return Output(runtimeDir, turnip, if (started) null else turnip.install())
}
fun logToSession(context: android.content.Context) {
val waylandLog = java.io.File(com.droiddeck.launcher.session.SessionPaths.beginOrCurrent(context), "wayland.log")
WaylandCompositor.setSessionLogFile(waylandLog)
try {
android.system.Os.setenv("DD_WAYLAND_LOG", waylandLog.path, true)
} catch (e: Exception) {
android.util.Log.w(TAG, "could not point the compositor's log at $waylandLog", e)
}
}
fun applyHdr(context: android.content.Context, mode: String) {
val on = SessionState.hdrCapable && SessionPrefs.hdr(context, mode)
SessionState.hdr = on
WaylandCompositor.nativeSetHdrOutput(on)
WaylandCompositor.nativeSetZeroCopy(on || SessionPrefs.zeroCopy(context, mode))
android.util.Log.i(TAG, "hdr: " + (if (on) "on" else "off") + " for this $mode session")
}
fun start(context: android.content.Context, output: Output, surface: Surface, size: Pair<Int, Int>, refreshHz: Float, fpsLimit: Int): Boolean {
com.droiddeck.launcher.gpu.DriverSetupLog.write(context, "compositor.start driver=${output.driverId}")
return startOrAttach(
context, surface, output.runtimeDir.path,
output.driverId?.let { output.turnip.driverPath(it) }, output.driverId?.let { output.turnip.libraryName(it) },
context.applicationInfo.nativeLibraryDir, size.first, size.second, refreshHz, fpsLimit,
)
}
@Synchronized
fun startOrAttach(
context: android.content.Context,
-1
View File
@@ -4177,7 +4177,6 @@
<string name="addons_sort_downloads">الأكثر تنزيلًا</string>
<string name="addons_category_all">كل الفئات</string>
<string name="addons_none_found">لم يتم العثور على إضافات</string>
<string name="addons_curse_busy">أغلق CurseForge أولاً</string>
<string name="addons_unreachable">تعذّر الوصول إلى %1$s</string>
<string name="addons_no_file">لا يوجد ملف لإصدار اللعبة هذا</string>
<string name="input_reset_positions">إعادة تعيين المواضع</string>
@@ -4057,7 +4057,6 @@
<string name="addons_sort_downloads">Más descargados</string>
<string name="addons_category_all">Todas las categorías</string>
<string name="addons_none_found">No se encontraron complementos</string>
<string name="addons_curse_busy">Cierra CurseForge primero</string>
<string name="addons_unreachable">No se pudo conectar con %1$s</string>
<string name="addons_no_file">No hay archivo para esta versión del juego</string>
<string name="input_reset_positions">Restablecer posiciones</string>
-1
View File
@@ -4017,7 +4017,6 @@
<string name="addons_sort_downloads">Най-изтегляни</string>
<string name="addons_category_all">Всички категории</string>
<string name="addons_none_found">Няма намерени добавки</string>
<string name="addons_curse_busy">Първо затворете CurseForge</string>
<string name="addons_unreachable">Няма връзка с %1$s</string>
<string name="addons_no_file">Няма файл за тази версия на играта</string>
<string name="input_reset_positions">Нулиране на позициите</string>
-1
View File
@@ -4097,7 +4097,6 @@
<string name="addons_sort_downloads">Nejstahovanější</string>
<string name="addons_category_all">Všechny kategorie</string>
<string name="addons_none_found">Nenalezeny žádné doplňky</string>
<string name="addons_curse_busy">Nejprve zavřete CurseForge</string>
<string name="addons_unreachable">Nelze se připojit k %1$s</string>
<string name="addons_no_file">Pro tuto verzi hry není k dispozici soubor</string>
<string name="input_reset_positions">Obnovit pozice</string>
-1
View File
@@ -4017,7 +4017,6 @@
<string name="addons_sort_downloads">Mest downloadet</string>
<string name="addons_category_all">Alle kategorier</string>
<string name="addons_none_found">Ingen tilføjelser fundet</string>
<string name="addons_curse_busy">Luk CurseForge først</string>
<string name="addons_unreachable">Kunne ikke nå %1$s</string>
<string name="addons_no_file">Ingen fil til denne spilversion</string>
<string name="input_reset_positions">Nulstil placeringer</string>
-1
View File
@@ -4017,7 +4017,6 @@
<string name="addons_sort_downloads">Meistgeladen</string>
<string name="addons_category_all">Alle Kategorien</string>
<string name="addons_none_found">Keine Addons gefunden</string>
<string name="addons_curse_busy">Schließe zuerst CurseForge</string>
<string name="addons_unreachable">%1$s ist nicht erreichbar</string>
<string name="addons_no_file">Keine Datei für diese Spielversion</string>
<string name="input_reset_positions">Positionen zurücksetzen</string>
-1
View File
@@ -4017,7 +4017,6 @@
<string name="addons_sort_downloads">Περισσότερες λήψεις</string>
<string name="addons_category_all">Όλες οι κατηγορίες</string>
<string name="addons_none_found">Δεν βρέθηκαν πρόσθετα</string>
<string name="addons_curse_busy">Κλείστε πρώτα το CurseForge</string>
<string name="addons_unreachable">Δεν ήταν δυνατή η σύνδεση με %1$s</string>
<string name="addons_no_file">Δεν υπάρχει αρχείο για αυτή την έκδοση του παιχνιδιού</string>
<string name="input_reset_positions">Επαναφορά θέσεων</string>
-1
View File
@@ -4057,7 +4057,6 @@
<string name="addons_sort_downloads">Más descargados</string>
<string name="addons_category_all">Todas las categorías</string>
<string name="addons_none_found">No se han encontrado complementos</string>
<string name="addons_curse_busy">Cierra CurseForge primero</string>
<string name="addons_unreachable">No se pudo conectar con %1$s</string>
<string name="addons_no_file">No hay ningún archivo para esta versión del juego</string>
<string name="input_reset_positions">Restablecer posiciones</string>
-1
View File
@@ -4017,7 +4017,6 @@
<string name="addons_sort_downloads">Ladatuimmat</string>
<string name="addons_category_all">Kaikki luokat</string>
<string name="addons_none_found">Lisäosia ei löytynyt</string>
<string name="addons_curse_busy">Sulje CurseForge ensin</string>
<string name="addons_unreachable">Yhteyttä palveluun %1$s ei saatu</string>
<string name="addons_no_file">Tälle peliversiolle ei ole tiedostoa</string>
<string name="input_reset_positions">Palauta sijainnit</string>
-1
View File
@@ -4056,7 +4056,6 @@
<string name="addons_sort_downloads">Les plus téléchargés</string>
<string name="addons_category_all">Toutes les catégories</string>
<string name="addons_none_found">Aucun addon trouvé</string>
<string name="addons_curse_busy">Fermez d\'abord CurseForge</string>
<string name="addons_unreachable">Impossible de joindre %1$s</string>
<string name="addons_no_file">Aucun fichier pour cette version du jeu</string>
<string name="input_reset_positions">Réinitialiser les positions</string>
-1
View File
@@ -4017,7 +4017,6 @@
<string name="addons_sort_downloads">सबसे ज़्यादा डाउनलोड</string>
<string name="addons_category_all">सभी श्रेणियाँ</string>
<string name="addons_none_found">कोई ऐडऑन नहीं मिला</string>
<string name="addons_curse_busy">पहले CurseForge बंद करें</string>
<string name="addons_unreachable">%1$s तक नहीं पहुँच सके</string>
<string name="addons_no_file">गेम के इस संस्करण के लिए कोई फ़ाइल नहीं है</string>
<string name="input_reset_positions">स्थितियाँ रीसेट करें</string>
-1
View File
@@ -4017,7 +4017,6 @@
<string name="addons_sort_downloads">Legtöbbet letöltött</string>
<string name="addons_category_all">Minden kategória</string>
<string name="addons_none_found">Nem található kiegészítő</string>
<string name="addons_curse_busy">Előbb zárd be a CurseForge-ot</string>
<string name="addons_unreachable">A(z) %1$s nem érhető el</string>
<string name="addons_no_file">Nincs fájl ehhez a játékverzióhoz</string>
<string name="input_reset_positions">Pozíciók visszaállítása</string>
-1
View File
@@ -3987,7 +3987,6 @@
<string name="addons_sort_downloads">Paling banyak diunduh</string>
<string name="addons_category_all">Semua kategori</string>
<string name="addons_none_found">Tidak ada addon ditemukan</string>
<string name="addons_curse_busy">Tutup CurseForge terlebih dahulu</string>
<string name="addons_unreachable">Tidak dapat menjangkau %1$s</string>
<string name="addons_no_file">Tidak ada file untuk versi game ini</string>
<string name="input_reset_positions">Atur ulang posisi</string>
-1
View File
@@ -4056,7 +4056,6 @@
<string name="addons_sort_downloads">Più scaricati</string>
<string name="addons_category_all">Tutte le categorie</string>
<string name="addons_none_found">Nessun addon trovato</string>
<string name="addons_curse_busy">Chiudi prima CurseForge</string>
<string name="addons_unreachable">Impossibile raggiungere %1$s</string>
<string name="addons_no_file">Nessun file per questa versione del gioco</string>
<string name="input_reset_positions">Ripristina posizioni</string>
-1
View File
@@ -3987,7 +3987,6 @@
<string name="addons_sort_downloads">ダウンロード数順</string>
<string name="addons_category_all">すべてのカテゴリ</string>
<string name="addons_none_found">アドオンが見つかりません</string>
<string name="addons_curse_busy">先に CurseForge を閉じてください</string>
<string name="addons_unreachable">%1$s に接続できませんでした</string>
<string name="addons_no_file">このゲームバージョン用のファイルがありません</string>
<string name="input_reset_positions">位置をリセット</string>
-1
View File
@@ -3987,7 +3987,6 @@
<string name="addons_sort_downloads">다운로드 많은 순</string>
<string name="addons_category_all">모든 카테고리</string>
<string name="addons_none_found">애드온을 찾을 수 없음</string>
<string name="addons_curse_busy">먼저 CurseForge를 닫으세요</string>
<string name="addons_unreachable">%1$s에 연결할 수 없습니다</string>
<string name="addons_no_file">이 게임 버전용 파일이 없습니다</string>
<string name="input_reset_positions">위치 초기화</string>
-1
View File
@@ -3987,7 +3987,6 @@
<string name="addons_sort_downloads">Paling banyak dimuat turun</string>
<string name="addons_category_all">Semua kategori</string>
<string name="addons_none_found">Tiada addon ditemui</string>
<string name="addons_curse_busy">Tutup CurseForge dahulu</string>
<string name="addons_unreachable">Tidak dapat mencapai %1$s</string>
<string name="addons_no_file">Tiada fail untuk versi permainan ini</string>
<string name="input_reset_positions">Tetapkan semula kedudukan</string>
-1
View File
@@ -4017,7 +4017,6 @@
<string name="addons_sort_downloads">Mest nedlastet</string>
<string name="addons_category_all">Alle kategorier</string>
<string name="addons_none_found">Fant ingen tillegg</string>
<string name="addons_curse_busy">Lukk CurseForge først</string>
<string name="addons_unreachable">Fikk ikke kontakt med %1$s</string>
<string name="addons_no_file">Ingen fil for denne spillversjonen</string>
<string name="input_reset_positions">Tilbakestill plasseringer</string>
-1
View File
@@ -4017,7 +4017,6 @@
<string name="addons_sort_downloads">Meest gedownload</string>
<string name="addons_category_all">Alle categorieën</string>
<string name="addons_none_found">Geen add-ons gevonden</string>
<string name="addons_curse_busy">Sluit eerst CurseForge</string>
<string name="addons_unreachable">Kan %1$s niet bereiken</string>
<string name="addons_no_file">Geen bestand voor deze gameversie</string>
<string name="input_reset_positions">Posities herstellen</string>
-1
View File
@@ -4097,7 +4097,6 @@
<string name="addons_sort_downloads">Najczęściej pobierane</string>
<string name="addons_category_all">Wszystkie kategorie</string>
<string name="addons_none_found">Nie znaleziono dodatków</string>
<string name="addons_curse_busy">Najpierw zamknij CurseForge</string>
<string name="addons_unreachable">Nie można połączyć się z %1$s</string>
<string name="addons_no_file">Brak pliku dla tej wersji gry</string>
<string name="input_reset_positions">Resetuj położenie</string>
@@ -4070,7 +4070,6 @@
<string name="addons_sort_downloads">Mais transferidos</string>
<string name="addons_category_all">Todas as categorias</string>
<string name="addons_none_found">Nenhum addon encontrado</string>
<string name="addons_curse_busy">Feche primeiro o CurseForge</string>
<string name="addons_unreachable">Não foi possível contactar %1$s</string>
<string name="addons_no_file">Não há ficheiro para esta versão do jogo</string>
<string name="input_reset_positions">Repor posições</string>
-1
View File
@@ -4078,7 +4078,6 @@
<string name="addons_sort_downloads">Mais baixados</string>
<string name="addons_category_all">Todas as categorias</string>
<string name="addons_none_found">Nenhum addon encontrado</string>
<string name="addons_curse_busy">Feche o CurseForge primeiro</string>
<string name="addons_unreachable">Não foi possível acessar %1$s</string>
<string name="addons_no_file">Não há arquivo para esta versão do jogo</string>
<string name="input_reset_positions">Redefinir posições</string>
-1
View File
@@ -4057,7 +4057,6 @@
<string name="addons_sort_downloads">Cele mai descărcate</string>
<string name="addons_category_all">Toate categoriile</string>
<string name="addons_none_found">Nu s-au găsit suplimente</string>
<string name="addons_curse_busy">Închide mai întâi CurseForge</string>
<string name="addons_unreachable">Nu s-a putut accesa %1$s</string>
<string name="addons_no_file">Nu există fișier pentru această versiune a jocului</string>
<string name="input_reset_positions">Resetează pozițiile</string>
-1
View File
@@ -4097,7 +4097,6 @@
<string name="addons_sort_downloads">Самые скачиваемые</string>
<string name="addons_category_all">Все категории</string>
<string name="addons_none_found">Аддоны не найдены</string>
<string name="addons_curse_busy">Сначала закройте CurseForge</string>
<string name="addons_unreachable">Не удалось подключиться к %1$s</string>
<string name="addons_no_file">Нет файла для этой версии игры</string>
<string name="input_reset_positions">Сбросить положение</string>
-1
View File
@@ -4017,7 +4017,6 @@
<string name="addons_sort_downloads">Mest nedladdade</string>
<string name="addons_category_all">Alla kategorier</string>
<string name="addons_none_found">Inga tillägg hittades</string>
<string name="addons_curse_busy">Stäng CurseForge först</string>
<string name="addons_unreachable">Kunde inte nå %1$s</string>
<string name="addons_no_file">Ingen fil för den här spelversionen</string>
<string name="input_reset_positions">Återställ positioner</string>
-1
View File
@@ -3987,7 +3987,6 @@
<string name="addons_sort_downloads">ดาวน์โหลดมากที่สุด</string>
<string name="addons_category_all">ทุกหมวดหมู่</string>
<string name="addons_none_found">ไม่พบแอดออน</string>
<string name="addons_curse_busy">ปิด CurseForge ก่อน</string>
<string name="addons_unreachable">ไม่สามารถเชื่อมต่อ %1$s ได้</string>
<string name="addons_no_file">ไม่มีไฟล์สำหรับเกมเวอร์ชันนี้</string>
<string name="input_reset_positions">รีเซ็ตตำแหน่ง</string>
-1
View File
@@ -4017,7 +4017,6 @@
<string name="addons_sort_downloads">En çok indirilen</string>
<string name="addons_category_all">Tüm kategoriler</string>
<string name="addons_none_found">Eklenti bulunamadı</string>
<string name="addons_curse_busy">Önce CurseForge\'u kapatın</string>
<string name="addons_unreachable">%1$s adresine ulaşılamadı</string>
<string name="addons_no_file">Bu oyun sürümü için dosya yok</string>
<string name="input_reset_positions">Konumları sıfırla</string>
-1
View File
@@ -4097,7 +4097,6 @@
<string name="addons_sort_downloads">Найбільше завантажень</string>
<string name="addons_category_all">Усі категорії</string>
<string name="addons_none_found">Аддонів не знайдено</string>
<string name="addons_curse_busy">Спочатку закрийте CurseForge</string>
<string name="addons_unreachable">Не вдалося під’єднатися до %1$s</string>
<string name="addons_no_file">Немає файлу для цієї версії гри</string>
<string name="input_reset_positions">Скинути розташування</string>
-1
View File
@@ -3987,7 +3987,6 @@
<string name="addons_sort_downloads">Tải nhiều nhất</string>
<string name="addons_category_all">Tất cả danh mục</string>
<string name="addons_none_found">Không tìm thấy addon</string>
<string name="addons_curse_busy">Hãy đóng CurseForge trước</string>
<string name="addons_unreachable">Không thể kết nối tới %1$s</string>
<string name="addons_no_file">Không có tệp cho phiên bản trò chơi này</string>
<string name="input_reset_positions">Đặt lại vị trí</string>
@@ -3987,7 +3987,6 @@
<string name="addons_sort_downloads">下载最多</string>
<string name="addons_category_all">所有类别</string>
<string name="addons_none_found">未找到插件</string>
<string name="addons_curse_busy">请先关闭 CurseForge</string>
<string name="addons_unreachable">无法连接到 %1$s</string>
<string name="addons_no_file">没有适用于此游戏版本的文件</string>
<string name="input_reset_positions">重置位置</string>
@@ -3987,7 +3987,6 @@
<string name="addons_sort_downloads">下載最多</string>
<string name="addons_category_all">所有類別</string>
<string name="addons_none_found">找不到插件</string>
<string name="addons_curse_busy">請先關閉 CurseForge</string>
<string name="addons_unreachable">無法連接 %1$s</string>
<string name="addons_no_file">沒有適用於此遊戲版本的檔案</string>
<string name="input_reset_positions">重設位置</string>
@@ -3987,7 +3987,6 @@
<string name="addons_sort_downloads">下載最多</string>
<string name="addons_category_all">所有類別</string>
<string name="addons_none_found">找不到插件</string>
<string name="addons_curse_busy">請先關閉 CurseForge</string>
<string name="addons_unreachable">無法連線至 %1$s</string>
<string name="addons_no_file">沒有適用於此遊戲版本的檔案</string>
<string name="input_reset_positions">重設位置</string>
-1
View File
@@ -4202,7 +4202,6 @@
<string name="addons_sort_downloads">Most downloaded</string>
<string name="addons_category_all">All categories</string>
<string name="addons_none_found">No addons found</string>
<string name="addons_curse_busy">Close CurseForge first</string>
<string name="addons_unreachable">Could not reach %1$s</string>
<string name="addons_no_file">No file for this game version</string>
<string name="addons_source_wowi" translatable="false">WoWInterface</string>
@@ -307,51 +307,6 @@ class OnScreenLayoutTest {
assertEquals(.1f * 2208f / 1768 / .2f, fitted.width * 2208 / (fitted.height * 800), .01f)
}
@Test fun controlsEditedInPortraitKeepTheirPlacesInThePanelBelowTheGame() {
SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_NONE)
val (w, h) = 1080 to 2400
val stock = gamepad()
val shown = OnScreenLayout.editorElements(context, stock, w, h)
val moved = shown.map { if (it.id == "legacy:a") it.copy(x = .05f) else if (it.id == "legacy:ls") it.copy(x = .6f) else it }
val edited = OnScreenLayout.withFrame(context, stock, OnScreenLayout.editorFrame(stock, moved), w.toFloat() / h)
val shownA = shown.first { it.id == "legacy:a" }
for (panelHeight in listOf(1100, 800)) {
val placed = OnScreenLayout.elements(context, edited, w, panelHeight, Rect(), dock = OnScreenLayout.Dock(true, false))
val a = placed.first { it.id == "legacy:a" }
val ls = placed.first { it.id == "legacy:ls" }
val b = placed.first { it.id == "legacy:b" }
assertTrue(a.x < .2f)
assertTrue(ls.x > .5f)
assertTrue(b.x > a.x)
assertNull(placed.firstOrNull { it.id == "builtin:keyboard" || it.control == InputControl.GUIDE || it.control == InputControl.QAM })
assertInside(placed, w, panelHeight)
assertEquals(shownA.width * w / (shownA.height * h), a.width * w / (a.height * panelHeight), .01f)
val untouched = OnScreenLayout.elements(context, stock, w, panelHeight, Rect(), dock = OnScreenLayout.Dock(true, false))
assertTrue(untouched.first { it.id == "legacy:a" }.x > .5f)
assertTrue(untouched.first { it.id == "legacy:ls" }.x < .5f)
}
val landscape = OnScreenLayout.elements(context, edited, 2400, 1080, Rect())
assertTrue(landscape.first { it.id == "legacy:a" }.x > .5f)
SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_DECK)
val deck = OnScreenLayout.elements(context, edited, w, 1100, Rect(), dock = OnScreenLayout.Dock.deck(true, null), trackpads = true)
assertTrue(deck.none { it.id == "legacy:rs" })
assertTrue(deck.any { it.kind == InputElementKind.TRACKPAD && it.x + it.width / 2f > .5f })
SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_NONE)
val tiny = stock.copy(aspect = .45f, elements = stock.elements.map {
when (it.id) {
"legacy:a" -> it.copy(x = .05f, y = .05f, width = .1f, height = .045f)
"legacy:b" -> it.copy(x = .16f, y = .05f, width = .1f, height = .045f)
"legacy:ls" -> it.copy(x = .8f, y = .85f, width = .15f, height = .1f)
else -> it
}
}, rotated = emptyList())
val short = OnScreenLayout.elements(context, tiny, w, 385, Rect(), dock = OnScreenLayout.Dock(true, false))
val sa = short.first { it.id == "legacy:a" }
val sb = short.first { it.id == "legacy:b" }
assertTrue(sa.x + sa.width <= sb.x)
assertEquals(1f, sa.width * w / (sa.height * 385), .01f)
}
@Test fun thePortraitAndBelowGameKitsKeepDirectionalArtClearOfTheSticksAndFaceButtons() {
val directions = setOf(InputControl.UP, InputControl.RIGHT, InputControl.DOWN, InputControl.LEFT)
val face = setOf(InputControl.A, InputControl.B, InputControl.X, InputControl.Y)
@@ -108,15 +108,6 @@ class SecondScreenProfileMigrationTest {
}
}
@Test fun pickingAnotherModeClearsTheMenuRestoreLeftByATeardown() {
customLibrary(desktop = false)
SessionState.bottomMenu = true
ReflectionHelpers.callInstanceMethod<Unit>(activity, "pickSecondScreenMode",
ReflectionHelpers.ClassParameter.from(SecondScreenMode::class.java, SecondScreenMode.KEYBOARD_TRACKPAD))
assertFalse(SessionState.bottomMenu)
assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD.id, SessionPrefs.secondScreenPanel(activity, false))
}
private fun customLibrary(desktop: Boolean): InputLibrary {
session(desktop)
return InputLibraries.update(activity) { library ->
@@ -1,161 +0,0 @@
package com.droiddeck.launcher.runtime
import android.app.Application
import org.json.JSONArray
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import java.io.File
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33], manifest = Config.NONE, application = Application::class)
class CurseForgeAppTest {
@get:Rule val temp = TemporaryFolder()
private val search = """{"success":true,"injectedCount":0,
"pagination":{"index":0,"pageSize":20,"resultCount":20,"totalCount":150},
"mods":[
{"id":486246,"name":"RestedXP Guide","summary":"Leveling guide","downloads":12345678,
"thumbnailUrl":"https://media.forgecdn.net/avatars/rxp.png","authors":[{"name":"RestedXP"}],
"updateVersion":{"id":7,"filename":"RXPGuides.zip","fileDate":"2026-11-20T10:00:00.000Z"}},
{"id":2,"name":"Plain","downloads":5,"thumbnailUrl":"http://insecure/x.png","primaryAuthor":{"name":"Main"},
"authors":[{"name":"Other"}],"projectLatestReleaseDate":"2026-01-01T00:00:00Z"},
{"id":0,"name":"No id"},
{"id":3,"name":""}
]}"""
@Test
fun searchResultsBecomeCatalogEntries() {
val page = CurseForgeApp.parseSearch(JSONObject(search))
assertEquals(listOf("486246", "2"), page.items.map { it.id })
val rxp = page.items[0]
assertEquals("RestedXP Guide", rxp.name)
assertEquals("RestedXP", rxp.author)
assertEquals(12345678L, rxp.downloads)
assertEquals(java.time.Instant.parse("2026-11-20T10:00:00Z").toEpochMilli(), rxp.updated)
assertEquals("https://media.forgecdn.net/avatars/rxp.png", rxp.thumb)
assertEquals("Main", page.items[1].author)
assertNull(page.items[1].thumb)
assertTrue(page.more)
}
@Test
fun theLastPageHasNoMore() {
val last = JSONObject(search).put("pagination", JSONObject("""{"index":140,"resultCount":10,"totalCount":150}"""))
assertFalse(CurseForgeApp.parseSearch(last).more)
assertThrows(CurseForgeApp.Failure::class.java) { CurseForgeApp.parseSearch(JSONObject("""{"success":false}""")) }
assertThrows(CurseForgeApp.Failure::class.java) { CurseForgeApp.parseSearch(null) }
}
@Test
fun searchRequestsUseTheInstanceAndOneBasedPages() {
val request = CurseForgeApp.searchRequest("guid-1", " Rested ", WowAddonCatalog.Sort.NAME, 0)
assertEquals(1, request.getInt("gameId"))
assertEquals("Rested", request.getString("searchText"))
assertEquals(1, request.getInt("page"))
assertEquals(1, request.getInt("sortColumn"))
assertEquals(1, request.getInt("sortOrder"))
assertEquals("guid-1", request.getString("gameInstanceGuid"))
assertEquals(2, CurseForgeApp.searchRequest("g", "", WowAddonCatalog.Sort.DOWNLOADS, 1).getInt("page"))
assertEquals(WowAddonCatalog.Sort.entries.size, WowAddonCatalog.Sort.entries.map(CurseForgeApp::sortOf).toSet().size)
}
@Test
fun installRequestsInstallTheLatestFileIntoTheInstance() {
val request = CurseForgeApp.installRequest("guid-1", "486246")
assertEquals("guid-1", request.getString("instanceId"))
assertEquals(486246L, request.getLong("projectId"))
assertTrue(request.getBoolean("installLatestFile"))
}
@Test
fun theInstanceIsPickedByItsFlavorFolder() {
val instances = JSONArray("""[
{"guid":"retail","installPath":"/root/Games/WoW/_retail_/"},
{"guid":"forever","installPath":"/root/Games/WoW/_forever_/"}
]""")
assertEquals("forever", CurseForgeApp.instanceFor(instances, "/root/Games/WoW/_forever_", "retail"))
assertEquals("retail", CurseForgeApp.instanceFor(instances, "/root/Games/WoW/_retail_", null))
assertNull(CurseForgeApp.instanceFor(instances, "/root/Games/WoW/_classic_", "retail"))
val single = JSONArray("""[{"guid":"retail","installPath":"/root/Games/WoW/_retail_/"}]""")
assertNull(CurseForgeApp.instanceFor(single, "/root/Games/WoW/_classic_", "retail"))
assertEquals("retail", CurseForgeApp.instanceFor(single, "/root/Games/WoW/_retail_", "other"))
assertEquals("only", CurseForgeApp.instanceFor(JSONArray(), "/x/_forever_", "only"))
assertEquals("only", CurseForgeApp.instanceFor(null, "/x/_forever_", "only"))
assertNull(CurseForgeApp.instanceFor(JSONArray(), "/x/_forever_", ""))
}
@Test
fun answersAreUnwrapped() {
val ok = JSONObject().put("ok", true).put("value", """{"value":{"resultStatus":3,"gameInstanceGuid":"g"}}""")
assertEquals("g", (CurseForgeApp.unwrap(ok) as JSONObject).getString("gameInstanceGuid"))
assertEquals(true, CurseForgeApp.unwrap(JSONObject().put("ok", true).put("value", """{"value":true}""")))
val missing = JSONObject().put("ok", true).put("value", """{"missing":true}""")
assertThrows(CurseForgeApp.Failure::class.java) { CurseForgeApp.unwrap(missing) }
val failed = JSONObject().put("ok", false).put("error", JSONObject().put("code", "NO_TARGET").put("message", "no node"))
val failure = assertThrows(CurseForgeApp.Failure::class.java) { CurseForgeApp.unwrap(failed) }
assertEquals("no node", failure.message)
assertEquals("NO_TARGET", failure.code)
assertFalse(failure.gone)
val lost = JSONObject().put("ok", false).put("error", JSONObject().put("code", "DEVTOOLS_UNREACHABLE").put("message", "refused"))
assertTrue(assertThrows(CurseForgeApp.Failure::class.java) { CurseForgeApp.unwrap(lost) }.gone)
}
@Test
fun expressionsDriveTheHiddenDesktopWindow() {
val text = CurseForgeApp.expression("ProjectAppService", "search", JSONArray().put(JSONObject().put("searchText", "it's \"x\"")))
assertTrue(text.startsWith("(() => { const w = require('electron').BrowserWindow.getAllWindows()"))
assertTrue(text.contains("desktop.html"))
assertTrue(text.contains("executeJavaScript("))
assertFalse(text.contains("show()"))
val probe = CurseForgeApp.expression("InstalledProjectsAppService", "installAddon", null)
assertFalse(probe.contains("await s["))
val connect = CurseForgeApp.expression("CoreService", "connect", JSONArray(), "r => true")
assertTrue(connect.contains("(r => true)(await s[\\\"connect\\\"](...[]))"))
}
@Test
fun installedIdsAndExitCodes() {
assertEquals(setOf("486246", "2"), CurseForgeApp.projectIds(JSONArray("""["486246","2",null]""")))
assertEquals(emptySet<String>(), CurseForgeApp.projectIds(JSONObject()))
assertEquals(CurseForgeApp.Start.READY, CurseForgeApp.startState(0))
assertEquals(CurseForgeApp.Start.BUSY, CurseForgeApp.startState(3))
assertEquals(CurseForgeApp.Start.NO_DISPLAY, CurseForgeApp.startState(4))
assertEquals(CurseForgeApp.Start.FAILED, CurseForgeApp.startState(5))
}
@Test
fun onlyASecretInspectorUrlIsTaken() {
val url = "ws://127.0.0.1:43117/0f8fad5b-d9cb-469f-a165-70867728950e"
assertEquals(url, CurseForgeApp.inspectorUrl("noise\n$url\n"))
assertNull(CurseForgeApp.inspectorUrl("ready\n"))
assertNull(CurseForgeApp.inspectorUrl("ws://127.0.0.1:9229/\n"))
assertNull(CurseForgeApp.inspectorUrl("ws://10.0.0.2:43117/0f8fad5b-d9cb-469f-a165-70867728950e"))
assertNull(CurseForgeApp.inspectorUrl("$url/json"))
}
@Test
fun theWowRootIsTheParentOfEveryFlavor() {
val root = temp.newFolder("World of Warcraft")
for (flavor in listOf("_classic_", "_classic_era_")) {
File(root, "$flavor/Interface/AddOns").mkdirs()
File(root, "$flavor/.flavor.info").writeText("x")
}
val title = BattleNet.TITLES.first { it.flavor == "_classic_" }
val targets = WowAddons.targets(title, File(root, "_classic_"))
assertEquals(listOf("_classic_", "_classic_era_"), targets.map { it.flavor }.sorted())
for (target in targets) {
assertEquals(root, WowAddons.root(target))
assertEquals(File(root, target.flavor), WowAddons.flavorDir(target))
}
}
}
@@ -1,139 +0,0 @@
package com.droiddeck.launcher.session
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import java.io.File
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class ComponentsBionicFexTest {
private val bionicTool = "DroidDeck-Bionic-12.8-r24"
private val ownTool = "DroidDeck-Proton-11-12.8"
private fun proton(dir: String, valve: Boolean = false) =
ComponentsManager.Proton(dir, dir, File("/steam/compatibilitytools.d/$dir"), "/p/$dir", "$dir-1", valve)
private fun item(file: String, release: String) = ComponentsManager.CatalogItem(file, "fex", release, "", 1, "")
@Test fun onlyBionicNamedPackagesFitDroidDeckBionic() {
assertTrue(ComponentsManager.bionicFex("FEXCore-2611.1-bionic.wcp"))
assertTrue(ComponentsManager.bionicFex("FEXCore-2611.1-PPA-BIONIC.WCP"))
assertFalse(ComponentsManager.bionicFex("FEXCore-2611.1-linux.wcp"))
assertFalse(ComponentsManager.bionicFex("DD-FEXCore-2611+51-nightly.wcp"))
assertFalse(ComponentsManager.bionicFex("bionic-FEXCore-2611.wcp"))
assertTrue(ComponentsManager.bionicTool(bionicTool))
assertFalse(ComponentsManager.bionicTool(ownTool))
assertFalse(ComponentsManager.bionicTool("GE-Proton10-25"))
assertFalse(ComponentsManager.bionicTool(null))
assertTrue(ComponentsManager.fexFits(bionicTool, "FEXCore-2611-bionic.wcp"))
assertFalse(ComponentsManager.fexFits(bionicTool, "FEXCore-2611-linux.wcp"))
assertFalse(ComponentsManager.fexFits(bionicTool, "DD-FEXCore-2611+51-nightly.wcp"))
assertTrue(ComponentsManager.fexFits(ownTool, "DD-FEXCore-2611+51-nightly.wcp"))
assertTrue(ComponentsManager.fexFits(ownTool, "FEXCore-2611-linux.wcp"))
assertFalse(ComponentsManager.fexFits(ownTool, "FEXCore-2611-bionic.wcp"))
assertFalse(ComponentsManager.fexFits(null, "FEXCore-2611-bionic.wcp"))
}
@Test fun aTwinSwapsTheLinuxAndBionicEnding() {
assertEquals("FEXCore-2611.1-bionic.wcp", ComponentsManager.fexTwin("FEXCore-2611.1-linux.wcp"))
assertEquals("FEXCore-2611.1-linux.wcp", ComponentsManager.fexTwin("FEXCore-2611.1-bionic.wcp"))
assertEquals("FEXCore-2611-PPA-bionic.wcp", ComponentsManager.fexTwin("FEXCore-2611-PPA-linux.wcp"))
assertNull(ComponentsManager.fexTwin("DD-FEXCore-2611+51-nightly.wcp"))
assertNull(ComponentsManager.fexTwin("my-fex.wcp"))
}
@Test fun aLaunchTakesTheChoiceOrItsStoredTwinForEachFlavor() {
val stored = setOf("FEXCore-2611.1-linux.wcp", "FEXCore-2611.1-bionic.wcp", "FEXCore-2610-linux.wcp")
val has: (String) -> Boolean = { it in stored }
assertEquals("FEXCore-2611.1-bionic.wcp", ComponentsManager.launchFex(bionicTool, "FEXCore-2611.1-linux.wcp", has))
assertEquals("FEXCore-2611.1-bionic.wcp", ComponentsManager.launchFex(bionicTool, "FEXCore-2611.1-bionic.wcp", has))
assertEquals("FEXCore-2611.1-linux.wcp", ComponentsManager.launchFex(ownTool, "FEXCore-2611.1-bionic.wcp", has))
assertEquals("FEXCore-2610-linux.wcp", ComponentsManager.launchFex(ownTool, "FEXCore-2610-linux.wcp", has))
assertEquals("DD-FEXCore-2611+51-nightly.wcp", ComponentsManager.launchFex(ownTool, "DD-FEXCore-2611+51-nightly.wcp", has))
assertNull(ComponentsManager.launchFex(bionicTool, "FEXCore-2610-linux.wcp", has))
assertNull(ComponentsManager.launchFex(bionicTool, "DD-FEXCore-2611+51-nightly.wcp", has))
}
@Test fun fexListsShowTheProtonsFlavorAndTheCurrentChoice() {
val files = listOf("FEXCore-2611.1-linux.wcp", "FEXCore-2611.1-bionic.wcp", "DD-FEXCore-2611+51-nightly.wcp", "FEXCore-2610-bionic.wcp")
assertEquals(listOf("FEXCore-2611.1-bionic.wcp", "FEXCore-2610-bionic.wcp"), ComponentsManager.forTool("fex", bionicTool, files) { it })
assertEquals(listOf("FEXCore-2611.1-linux.wcp", "DD-FEXCore-2611+51-nightly.wcp"), ComponentsManager.forTool("fex", ownTool, files) { it })
assertEquals(listOf("FEXCore-2611.1-linux.wcp", "DD-FEXCore-2611+51-nightly.wcp"), ComponentsManager.forTool("fex", null, files) { it })
assertEquals(listOf("FEXCore-2611.1-linux.wcp", "FEXCore-2611.1-bionic.wcp", "FEXCore-2610-bionic.wcp"),
ComponentsManager.forTool("fex", bionicTool, files, selected = "FEXCore-2611.1-linux.wcp") { it })
assertEquals(files, ComponentsManager.forTool("dxvk", bionicTool, files) { it })
}
@Test fun bionicStableAssetsAreFex() {
assertEquals("fex", ComponentsManager.assetComp(ComponentsManager.DD_BIONIC, "FEXCore-2611.1-bionic.wcp"))
assertEquals("fex", ComponentsManager.assetComp(ComponentsManager.DD_BIONIC, "FEXCore-2610-PPA-bionic.wcp"))
assertEquals("fex", ComponentsManager.assetComp("FexCore-Linux", "FEXCore-2611.1-linux.wcp"))
}
@Test fun aGameFexChoiceKeepsItsTwinInUseWhileTheOtherFlavorIsInstalled() {
val state = JSONObject().put("profiles", JSONObject().put("42", JSONObject().put("fex", "FEXCore-2611.1-linux.wcp")))
assertEquals(setOf("FEXCore-2611.1-linux.wcp"), ComponentsManager.packagesInUse(state, listOf(proton(ownTool))))
assertEquals(setOf("FEXCore-2611.1-linux.wcp", "FEXCore-2611.1-bionic.wcp"),
ComponentsManager.packagesInUse(state, listOf(proton(ownTool), proton(bionicTool))))
}
@Test fun aTwinAGameChoiceStillNeedsCannotBeDeletedAsUnused() {
val state = JSONObject().put("profiles", JSONObject().put("42", JSONObject().put("fex", "FEXCore-2611.1-linux.wcp")))
assertEquals(bionicTool, ComponentsManager.twinUser(state, listOf(proton(ownTool), proton(bionicTool)), "FEXCore-2611.1-bionic.wcp")?.dir?.name)
assertEquals(null, ComponentsManager.twinUser(state, listOf(proton(ownTool)), "FEXCore-2611.1-bionic.wcp"))
assertEquals(null, ComponentsManager.twinUser(state, listOf(proton(ownTool), proton(bionicTool)), "FEXCore-2610-bionic.wcp"))
assertEquals(null, ComponentsManager.twinUser(JSONObject(), listOf(proton(bionicTool)), "FEXCore-2611.1-bionic.wcp"))
}
@Test fun droidDeckBionicFollowsTheNewestBionicFexAndNothingElse() {
val bionic = proton(bionicTool)
val own = proton(ownTool)
assertTrue(ComponentUpdates.autoFollows(bionic, "fex"))
assertFalse(ComponentUpdates.autoFollows(bionic, "dxvk"))
assertFalse(ComponentUpdates.autoFollows(bionic, "vkd3d"))
assertFalse(ComponentUpdates.autoFollows(proton(bionicTool, valve = true), "fex"))
assertFalse(ComponentUpdates.follows(bionic))
assertTrue(ComponentUpdates.autoFollows(own, "dxvk"))
assertFalse(ComponentUpdates.autoFollows(proton("GE-Proton10-25"), "fex"))
assertEquals("fex-bionic", ComponentUpdates.fexLine(bionic).key)
assertEquals("fex", ComponentUpdates.fexLine(own).key)
assertEquals("fex", ComponentUpdates.line("fex", false).key)
val catalog = listOf(
item("DD-FEXCore-2611+51-nightly.wcp", ComponentsManager.DD_NIGHTLY),
item("DD-FEXCore-2611+52-bionic.wcp", ComponentsManager.DD_NIGHTLY),
item("FEXCore-2611.1-linux.wcp", "FexCore-Linux"),
item("FEXCore-2610-bionic.wcp", ComponentsManager.DD_BIONIC),
item("FEXCore-2611-PPA-bionic.wcp", ComponentsManager.DD_BIONIC),
item("FEXCore-2611.1-bionic.wcp", ComponentsManager.DD_BIONIC),
)
assertEquals("FEXCore-2611.1-bionic.wcp", ComponentUpdates.pick(catalog, ComponentUpdates.fexLine(bionic), emptySet())?.file)
assertNull(ComponentUpdates.pick(catalog, ComponentUpdates.fexLine(bionic), setOf("FEXCore-2611.1-bionic.wcp")))
assertEquals("DD-FEXCore-2611+51-nightly.wcp", ComponentUpdates.pick(catalog, ComponentUpdates.fexLine(own), emptySet())?.file)
}
@Test fun pruningTheBionicLineKeepsBionicPackagesTheUserDownloaded() {
val line = ComponentUpdates.fexLine(proton(bionicTool))
val current = "FEXCore-2611.1-bionic.wcp"
val stored = listOf("FEXCore-2610-bionic.wcp", "FEXCore-2611-PPA-bionic.wcp", current, "FEXCore-2610-linux.wcp")
assertEquals(listOf("FEXCore-2610-bionic.wcp"),
ComponentUpdates.stale(line, setOf("FEXCore-2610-bionic.wcp", current), stored, setOf(current), current))
}
@Test fun aBionicProtonsOwnFexChoiceIsNotHandedBack() {
val bionic = proton(bionicTool)
val choices = mapOf(bionic.id to mapOf(
"fex" to ComponentsManager.Choice("FEXCore-2611.1-bionic.wcp", false, bionic.version),
"dxvk" to ComponentsManager.Choice("DD-dxvk-3.1.1+190-nightly.wcp", false, bionic.version),
))
assertEquals(listOf(bionic to "dxvk"),
ComponentUpdates.strays(listOf(bionic), choices, setOf("FEXCore-2611.1-bionic.wcp", "DD-dxvk-3.1.1+190-nightly.wcp")))
}
}
@@ -8,7 +8,6 @@ import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
@@ -24,7 +23,6 @@ class ComponentsRepublishTest {
private val fex = "FEXCore-2610-d2rfix28-linux.wcp"
private val scope = "2596113170"
private val dll = "files/lib/wine/aarch64-windows/libwow64fex.dll"
private val so = "files/lib/wine/aarch64-unix/libwow64fex.so"
private lateinit var context: Context
@Before fun setUp() {
@@ -50,61 +48,6 @@ class ComponentsRepublishTest {
assertEquals(fex, ComponentsManager.gameComponents(context, scope)["fex"])
}
@Test fun aGlibcGameFexChoiceWithoutItsTwinLeavesDroidDeckBionicOnItsOwnFex() {
proton("DroidDeck-Proton 11-12.8", "DroidDeck-Proton-11-12.8")
proton("DroidDeck-Bionic-12.8-r6", "DroidDeck-Bionic-12.8-r6")
packageFile()
ComponentsManager.setGameComponent(context, scope, "fex", fex) { false }
assertEquals(setOf("DroidDeck-Proton 11-12.8"), scopedTools())
val bionic = rows().filter { it[1] == "DroidDeck-Bionic-12.8-r6" && it[3] == "fex" }
assertTrue(bionic.isNotEmpty())
assertTrue(bionic.all { it[0] == "*" && "/store/original-DroidDeck-Bionic-12.8-r6-" in it[6] })
}
@Test fun aGameFexChoiceReachesEachProtonAsTheBuildOfItsFlavor() {
proton("DroidDeck-Proton-11-12.8", "DroidDeck-Proton-11-12.8")
proton("DroidDeck-Bionic-12.8-r24", "DroidDeck-Bionic-12.8-r24")
val linux = "FEXCore-2611.1-linux.wcp"
val bionic = "FEXCore-2611.1-bionic.wcp"
packageFile(linux, "FEXCore-Linux", "glibc wow64")
packageFile(bionic, "FEXCore-Bionic", "android wow64")
for (choice in listOf(linux, bionic)) {
ComponentsManager.setGameComponent(context, scope, "fex", choice) { false }
val scoped = rows().filter { it[0] == scope && it[3] == "fex" }
val own = scoped.single { it[1] == "DroidDeck-Proton-11-12.8" && it[4] == dll }
val android = scoped.single { it[1] == "DroidDeck-Bionic-12.8-r24" && it[4] == dll }
assertEquals("glibc wow64", File(LinuxRuntime.rootDir(context), own[6].removePrefix("/")).readText())
assertEquals("android wow64", File(LinuxRuntime.rootDir(context), android[6].removePrefix("/")).readText())
assertTrue(scoped.any { it[1] == "DroidDeck-Proton-11-12.8" && it[6] == "-" })
assertTrue(scoped.none { it[1] == "DroidDeck-Bionic-12.8-r24" && it[6] == "-" })
assertEquals(choice, ComponentsManager.gameComponents(context, scope)["fex"])
}
}
@Test fun aProtonsFexIsOnlyEverSwappedToABuildOfItsFlavor() {
proton("DroidDeck-Proton-11-12.8", "DroidDeck-Proton-11-12.8")
proton("DroidDeck-Bionic-12.8-r24", "DroidDeck-Bionic-12.8-r24")
val linux = "FEXCore-2611.1-linux.wcp"
val bionic = "FEXCore-2611.1-bionic.wcp"
packageFile(linux, "FEXCore-Linux", "glibc wow64")
packageFile(bionic, "FEXCore-Bionic", "android wow64")
val bionicDll = File(protonDir("DroidDeck-Bionic-12.8-r24"), dll)
val ownDll = File(protonDir("DroidDeck-Proton-11-12.8"), dll)
assertThrows(IllegalStateException::class.java) { ComponentsManager.swap(context, "DroidDeck-Bionic-12.8-r24", linux) }
assertThrows(IllegalStateException::class.java) { ComponentsManager.swap(context, "DroidDeck-Proton-11-12.8", bionic) }
assertEquals("bundled FEX DroidDeck-Bionic-12.8-r24", bionicDll.readText())
assertEquals("bundled FEX DroidDeck-Proton-11-12.8", ownDll.readText())
ComponentsManager.swap(context, "DroidDeck-Bionic-12.8-r24", bionic)
ComponentsManager.swap(context, "DroidDeck-Proton-11-12.8", linux)
assertEquals("android wow64", bionicDll.readText())
assertEquals("glibc wow64", ownDll.readText())
assertTrue(File(protonDir("DroidDeck-Bionic-12.8-r24"), so).isFile)
assertTrue(rows().none { it[1] == "DroidDeck-Bionic-12.8-r24" && it[3] == "fex" && it[6] == "-" })
}
@Test fun nothingIsRewrittenWhileTheToolsAreUnchanged() {
proton("DroidDeck-Proton 11-11.8", "DroidDeck-Proton-11-11.8")
packageFile()
@@ -174,21 +117,18 @@ class ComponentsRepublishTest {
private fun launchState() = File(LinuxRuntime.rootDir(context), "root/.local/share/droiddeck-components/desired.tsv")
private fun protonDir(name: String) = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/steamapps/common/$name")
private fun proton(name: String, version: String) {
val dir = protonDir(name)
val dir = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/steamapps/common/$name")
File(dir, "files/lib/wine").mkdirs()
File(dir, "proton").writeText("#!/bin/sh\n")
File(dir, "version").writeText("1 $version\n")
File(dir, dll).apply { parentFile!!.mkdirs(); writeText("bundled FEX $version") }
File(dir, so).apply { parentFile!!.mkdirs(); writeText("bundled unix FEX $version") }
}
private fun packageFile(name: String = fex, type: String = "FEXCore-Linux", text: String = "d2rfix28 wow64") {
val out = File(context.filesDir, "components/packages/$name").apply { parentFile!!.mkdirs() }
val profile = JSONObject().put("type", type).put("versionName", name.removeSuffix(".wcp")).toString().toByteArray()
val body = text.toByteArray()
private fun packageFile() {
val out = File(context.filesDir, "components/packages/$fex").apply { parentFile!!.mkdirs() }
val profile = JSONObject().put("type", "FEXCore-Linux").put("versionName", "2610-d2rfix28").toString().toByteArray()
val body = "d2rfix28 wow64".toByteArray()
TarArchiveOutputStream(ZstdOutputStream(out.outputStream())).use { tar ->
tar.putArchiveEntry(TarArchiveEntry("profile.json").apply { size = profile.size.toLong() })
tar.write(profile)
@@ -98,22 +98,6 @@ class EnhancedSessionLogShareTest {
SessionLogShare.clear(app)
}
@Test fun aBionicGameLogIsSharedWithTheGamesUnderItsName() {
val session = tmp.newFolder("2026-11-22-09-steam")
session.resolve("session.log").writeText("startup ok\n")
val launch = session.resolve("games/2026-11-22-201105-bionic-341940").apply { mkdirs() }
launch.resolve("droiddeck-bionic.log").writeText("20:11:05 waitforexitandrun Hatred.exe\n")
val games = EnhancedSessionLogShare.create(app, session).single { it.name.endsWith("-games.zip") }
ZipFile(games).use { archive ->
val entry = archive.getEntry("${session.name}/games/2026-11-22-201105-bionic-341940/droiddeck-bionic.log")
assertTrue(entry != null)
assertEquals("20:11:05 waitforexitandrun Hatred.exe\n", archive.getInputStream(entry).bufferedReader().readText())
}
SessionLogShare.clear(app)
}
@Test fun oversizedFilesKeepBoundedBeginningAndTailAndDeclareTruncation() {
val session = tmp.newFolder("2026-11-04-02-game")
session.resolve("steam-7.log").writeText("begin\n" + "middle\n".repeat(100) + "tail\n")
@@ -68,19 +68,6 @@ class ExperimentalProtonsTest {
assertEquals(listOf("pre"), ProtonExtras.assets(tool, releases, true).map { it.tag })
}
@Test
fun bionicBuildsKeepTheirOwnRow() {
val tool = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }
val releases = JSONArray("""
[{"tag_name":"DroidDeck-Proton-11-12.8","prerelease":false,"published_at":"2026-11-14T00:00:00Z","assets":[{"name":"DroidDeck-Proton-11-12.8-aarch64.tar.gz","browser_download_url":"https://example/stable"}]},
{"tag_name":"DroidDeck-Bionic-12.8-r37","prerelease":true,"published_at":"2026-11-19T00:00:00Z","assets":[{"name":"DroidDeck-Bionic-12.8-r37-aarch64.tar.xz","browser_download_url":"https://example/bionic"}]},
{"tag_name":"DroidDeck-Proton-11-12.9-test1","prerelease":true,"published_at":"2026-11-19T01:00:00Z","assets":[{"name":"DroidDeck-Proton-11-12.9-test1-aarch64.tar.xz","browser_download_url":"https://example/test"}]}]
""".trimIndent())
val assets = ProtonExtras.assets(tool, releases, true)
assertEquals(listOf("DroidDeck-Bionic-12.8-r37", "DroidDeck-Proton-11-12.9-test1"), assets.map { it.tag })
assertEquals(listOf("DroidDeck-Proton-11-12.9-test1"), ExperimentalProtons.listed(assets).map { it.tag })
}
@Test
fun markerRoundTripKeepsReleaseTag() {
val dir = File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(activity), "root/.local/share/Steam/compatibilitytools.d/Experimental-pre").apply { mkdirs() }
@@ -127,90 +127,4 @@ class ProtonDefaultTest {
assertTrue(games.containsKey("43"))
assertNull(games["43"])
}
@Test
fun anUpdateMovesTheDefaultThatNamesTheReplacedTool() {
val bionic = """
{"default": "DroidDeck-Bionic-12.8-r30-Proton", "applied": 7, "live": false,
"tools": [{"name": "DroidDeck-Bionic-12.8-r30-Proton", "display": "r30", "dir": "DroidDeck-Bionic-12.8-r30", "valve": false},
{"name": "DroidDeck-Proton-11-12.8", "display": "DD", "dir": "DroidDeck-Proton 11-12.8", "valve": false}]}
""".trimIndent()
val parsed = ProtonDefault.parseState(bionic)
val from = setOf("DroidDeck-Bionic-12.8-r30")
// applied default, no request yet
assertEquals(ProtonDefault.Request(100, false, "DroidDeck-Bionic-12.8-r31"),
ProtonDefault.movedDefault(parsed, null, from, "DroidDeck-Bionic-12.8-r31", 100))
// a pending request for the replaced tool wins over the applied default and the new seq is above both
assertEquals(ProtonDefault.Request(51, false, "DroidDeck-Bionic-12.8-r31"),
ProtonDefault.movedDefault(parsed, ProtonDefault.Request(50, false, "DroidDeck-Bionic-12.8-r30"), from, "DroidDeck-Bionic-12.8-r31", 3))
// a default on another tool stays as it is
assertNull(ProtonDefault.movedDefault(parsed, ProtonDefault.Request(50, false, "DroidDeck-Proton 11-12.8"), from, "DroidDeck-Bionic-12.8-r31", 100))
assertNull(ProtonDefault.movedDefault(ProtonDefault.parseState(state), null, from, "DroidDeck-Bionic-12.8-r31", 100))
// an applied request (seq not above "applied") no longer decides: the applied default does
assertEquals("DroidDeck-Bionic-12.8-r31",
ProtonDefault.movedDefault(parsed, ProtonDefault.Request(7, false, "DroidDeck-Proton 11-12.8"), from, "DroidDeck-Bionic-12.8-r31", 1)?.dir)
}
@Test
fun aBionicDefaultOnAnotherBuildMovesToTheInstalledOne() {
val r37 = "DroidDeck-Bionic-12.8-r37"
val applied = ProtonDefault.parseState("""{"default": "DroidDeck-Bionic-12.8-r30-Proton", "applied": 7,
"tools": [{"name": "DroidDeck-Bionic-12.8-r30-Proton", "display": "r30", "dir": "DroidDeck-Bionic-12.8-r30", "valve": false},
{"name": "droiddeck-proton-arm64", "display": "Proton ARM64", "dir": "Proton Experimental (ARM64)", "valve": true}]}""")
// the applied default is an older build
assertEquals(ProtonDefault.Request(100, false, r37), ProtonDefault.bionicDefault(applied, null, "DroidDeck-Bionic", r37, 100))
// the guest fell back to its own tool because the requested build was gone: the request still names it
val fallback = ProtonDefault.parseState("""{"default": "droiddeck-proton-arm64", "applied": 50, "source": "fallback",
"tools": [{"name": "droiddeck-proton-arm64", "display": "Proton ARM64", "dir": "Proton Experimental (ARM64)", "valve": true}]}""")
assertEquals(ProtonDefault.Request(51, false, r37),
ProtonDefault.bionicDefault(fallback, ProtonDefault.Request(50, false, "DroidDeck-Bionic-12.8-r24"), "DroidDeck-Bionic", r37, 3))
// already the installed build, another tool, or a fallback the request did not cause: left as it is
assertNull(ProtonDefault.bionicDefault(fallback, ProtonDefault.Request(50, false, r37), "DroidDeck-Bionic", r37, 3))
assertNull(ProtonDefault.bionicDefault(fallback, ProtonDefault.Request(50, false, "DroidDeck-Proton 11-12.8"), "DroidDeck-Bionic", r37, 3))
assertNull(ProtonDefault.bionicDefault(ProtonDefault.parseState(state), null, "DroidDeck-Bionic", r37, 100))
val steam = ProtonDefault.parseState("""{"default": "droiddeck-proton-arm64", "applied": 50, "source": "steam",
"tools": [{"name": "droiddeck-proton-arm64", "display": "Proton ARM64", "dir": "Proton Experimental (ARM64)", "valve": true}]}""")
assertNull(ProtonDefault.bionicDefault(steam, ProtonDefault.Request(50, false, "DroidDeck-Bionic-12.8-r24"), "DroidDeck-Bionic", r37, 3))
}
@Test
fun keepingBionicCurrentRewritesTheDefaultAndThePicks() {
val context = RuntimeEnvironment.getApplication()
val d = File(LinuxRuntime.rootDir(context), "root/.local/share/droiddeck-compat").apply { deleteRecursively(); mkdirs() }
File(d, "state.json").writeText("""{"default": "droiddeck-proton-arm64", "applied": 9, "source": "fallback",
"tools": [{"name": "droiddeck-proton-arm64", "display": "Proton ARM64", "dir": "Proton Experimental (ARM64)", "valve": true}]}""")
File(d, "request.json").writeText("""{"seq": 9, "valve": false, "dir": "DroidDeck-Bionic-12.8-r24"}""")
ProtonDefault.requestGame(context, "42", proton("DroidDeck-Bionic-12.8-r29", false))
ProtonDefault.requestGame(context, "43", proton("DroidDeck-Proton 11-12.8", false))
ProtonDefault.requestGame(context, "44", null)
ProtonDefault.keepBionicCurrent(context, "DroidDeck-Bionic", "DroidDeck-Bionic-12.8-r37")
val request = ProtonDefault.parseRequest(File(d, "request.json").readText())
assertEquals("DroidDeck-Bionic-12.8-r37", request?.dir)
assertTrue(request!!.seq > 9)
val games = ProtonDefault.parseGames(File(d, "games.json").readText())
assertEquals(ProtonDefault.GameChoice(false, "DroidDeck-Bionic-12.8-r37"), games["42"])
assertEquals(ProtonDefault.GameChoice(false, "DroidDeck-Proton 11-12.8"), games["43"])
assertTrue(games.containsKey("44"))
assertNull(games["44"])
val before = File(d, "request.json").readText() + File(d, "games.json").readText()
ProtonDefault.keepBionicCurrent(context, "DroidDeck-Bionic", "DroidDeck-Bionic-12.8-r37")
assertEquals(before, File(d, "request.json").readText() + File(d, "games.json").readText())
}
@Test
fun moveDefaultRewritesTheRequestFile() {
val context = RuntimeEnvironment.getApplication()
val d = File(LinuxRuntime.rootDir(context), "root/.local/share/droiddeck-compat").apply { mkdirs() }
File(d, "state.json").writeText("""{"default": "DroidDeck-Bionic-12.8-r30-Proton", "applied": 7,
"tools": [{"name": "DroidDeck-Bionic-12.8-r30-Proton", "display": "r30", "dir": "DroidDeck-Bionic-12.8-r30", "valve": false}]}""")
File(d, "request.json").delete()
ProtonDefault.moveDefault(context, setOf("DroidDeck-Bionic-12.8-r30"), "DroidDeck-Bionic-12.8-r31")
val written = ProtonDefault.parseRequest(File(d, "request.json").readText())
assertEquals("DroidDeck-Bionic-12.8-r31", written?.dir)
assertFalse(written!!.valve)
assertTrue(written.seq > 7)
val before = File(d, "request.json").readText()
ProtonDefault.moveDefault(context, setOf("DroidDeck-Bionic-12.8-r29"), "DroidDeck-Bionic-12.8-r31")
assertEquals(before, File(d, "request.json").readText())
}
}
@@ -77,8 +77,8 @@ class ProtonExtrasTest {
}
@Test
fun theSourcesInOrder() {
assertEquals(listOf("ge", "cachyos", "droiddeck", "bionic"), ProtonExtras.tools.map { it.id })
fun theThreeSourcesInOrder() {
assertEquals(listOf("ge", "cachyos", "droiddeck"), ProtonExtras.tools.map { it.id })
val droiddeck = tool("droiddeck")
assertEquals("DroidDeck-Proton", droiddeck.name)
assertEquals("DroidDeck-Proton", droiddeck.prefix)
@@ -90,29 +90,6 @@ class ProtonExtrasTest {
assertFalse(tool("cachyos").assetPattern.containsMatchIn("proton-cachyos-11.0-20261005-slr-x86_64.tar.xz"))
}
@Test
fun bionicAndDroidDeckProtonShareTheReleasesButNotTheirArchives() {
val bionic = tool("bionic")
assertEquals("DroidDeck-Bionic", bionic.prefix)
assertEquals("Droid-Deck/DroidDeck-Proton", bionic.repo)
assertTrue(bionic.assetPattern.containsMatchIn("DroidDeck-Bionic-12.8-r3-aarch64.tar.xz"))
assertFalse(bionic.assetPattern.containsMatchIn("DroidDeck-Proton-11-12.8-aarch64.tar.gz"))
assertFalse(bionic.assetPattern.containsMatchIn("DroidDeck-Bionic-12.8-r3-aarch64.sha512sum"))
assertFalse(tool("droiddeck").assetPattern.containsMatchIn("DroidDeck-Bionic-12.8-r3-aarch64.tar.xz"))
}
@Test
fun bionicTakesItsPrereleaseAndDroidDeckProtonSkipsIt() {
val releases = JSONArray()
.put(release("DroidDeck-Bionic-12.8-r3", asset("DroidDeck-Bionic-12.8-r3-aarch64.sha512sum"),
asset("DroidDeck-Bionic-12.8-r3-aarch64.tar.xz"), prerelease = true))
.put(droiddeckRelease("11-12.8"))
val bionic = ProtonExtras.pickAsset(tool("bionic"), releases)!!
assertEquals("DroidDeck-Bionic-12.8-r3-aarch64.tar.xz", bionic.name)
assertTrue(bionic.sha512!!.endsWith("DroidDeck-Bionic-12.8-r3-aarch64.sha512sum"))
assertEquals("DroidDeck-Proton-11-12.8-aarch64.tar.gz", ProtonExtras.pickAsset(tool("droiddeck"), releases)!!.name)
}
@Test
fun theTarballAndItsSha512FileArePicked() {
val picked = ProtonExtras.pickAsset(tool("droiddeck"), JSONArray().put(droiddeckRelease("11-7.5")))!!
@@ -229,22 +206,6 @@ class ProtonExtrasTest {
assertNull(ProtonExtras.update(context, tool("droiddeck")))
}
@Test
fun removingDeletesLinksButNeverWhatTheyPointTo() {
val context = RuntimeEnvironment.getApplication()
val tools = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/compatibilitytools.d")
val outside = temp.newFolder("outside").apply { File(this, "keep.txt").writeText("x") }
for (name in listOf("DroidDeck-Bionic-12.8-r3", "DroidDeck-Bionic-12.8-r5")) {
val dosdevices = File(installTool(tools, name), "files/default_pfx/dosdevices").apply { mkdirs() }
java.nio.file.Files.createSymbolicLink(File(dosdevices, "z:").toPath(), outside.toPath())
}
ProtonExtras.removeOlder(context, tool("bionic"))
ProtonExtras.remove(context, tool("bionic"), "DroidDeck-Bionic-12.8-r5")
assertFalse(File(tools, "DroidDeck-Bionic-12.8-r3").exists())
assertFalse(File(tools, "DroidDeck-Bionic-12.8-r5").exists())
assertTrue(File(outside, "keep.txt").isFile)
}
@Test
fun removingDeletesOneBuildOrEveryOlderOne() {
val context = RuntimeEnvironment.getApplication()
@@ -168,8 +168,8 @@ class StoreGameSidecarTest {
"if \"%DD_EPIC_PARENT%\"==\"1\" set \"DD_P=1\"",
"if \"%DD_EPIC_PARENT%\"==\"0\" set \"DD_P=\"",
"if defined DD_P set \"SteamAppId=\"",
"if defined DD_P if not exist \"%DD_R%\\usr\\local\\lib\\droiddeck-epic\\EpicGamesLauncher.exe\" set \"DD_P=\"",
"if defined DD_P set DD_P=\"%DD_R%\\usr\\local\\lib\\droiddeck-epic\\EpicGamesLauncher.exe\"",
"if defined DD_P if not exist \"Z:\\usr\\local\\lib\\droiddeck-epic\\EpicGamesLauncher.exe\" set \"DD_P=\"",
"if defined DD_P set DD_P=\"Z:\\usr\\local\\lib\\droiddeck-epic\\EpicGamesLauncher.exe\"",
)
@Test fun epicTitlesThatCheckTheirParentStartUnderTheStandIn() {
@@ -105,28 +105,11 @@ class UbisoftTest {
val text = StoreLaunch.launcherText(StoreGameSidecar(Store.UBISOFT, "space-sc", "Splinter Cell", "system/SplinterCell.exe"))
val lines = text.trimEnd().split("\r\n")
assertTrue(lines.contains("if not exist \"%~dp0.droiddeck-ubisoft.json\" goto direct"))
val service = lines.indexOf("\"%DD_R%\\usr\\local\\lib\\droiddeck-ubisoft\\droiddeck-upc.exe\" \"%~dp0.droiddeck-ubisoft.json\"")
assertTrue(service in 0 until lines.indexOf(":direct"))
assertTrue(lines.indexOf("set \"DD_R=Z:\"") in 0 until lines.indexOf("if defined DROIDDECK_GUEST_ROOT set \"DD_R=%DROIDDECK_GUEST_ROOT%\""))
assertTrue(lines.indexOf("if defined DROIDDECK_GUEST_ROOT set \"DD_R=%DROIDDECK_GUEST_ROOT%\"") < service)
assertTrue(lines.contains("\"Z:\\usr\\local\\lib\\droiddeck-ubisoft\\droiddeck-upc.exe\" \"%~dp0.droiddeck-ubisoft.json\""))
assertEquals("\"%~dp0system\\SplinterCell.exe\"", lines.last())
assertTrue(lines.indexOf(":direct") < lines.lastIndex)
}
@Test fun anInstalledGamesOlderLauncherIsRewritten() {
val folder = java.nio.file.Files.createTempDirectory("ubisoft-adopt").toFile()
try {
File(folder, "system").mkdirs()
File(folder, "system/SplinterCell.exe").writeText("exe")
val sidecar = StoreGameSidecar(Store.UBISOFT, "space-sc", "Splinter Cell", "system/SplinterCell.exe", launcher = StoreLaunch.LAUNCHER)
File(folder, StoreLaunch.LAUNCHER).writeText("@echo off\r\nif not exist \"Z:\\usr\\local\\lib\\droiddeck-ubisoft\\droiddeck-upc.exe\" goto direct\r\n")
StoreLaunch.adopt(folder, sidecar)
assertEquals(StoreLaunch.launcherText(sidecar), File(folder, StoreLaunch.LAUNCHER).readText())
} finally {
folder.deleteRecursively()
}
}
@Test fun activationPayloadsSurviveTheHexHop() {
val bytes = byteArrayOf(0, 1, 0x7f, -1, -128, 42)
assertEquals("00017fff802a", UbisoftActivation.hex(bytes))
@@ -258,18 +258,6 @@ class InputSettingsTest {
compose.onNodeWithTag("input-layout-canvas").assertExists()
}
@Test fun everyScreenOpensWithItsEditorFirst() {
compose.setContent { DroidDeckTheme { InputSettingsPage({}) } }
compose.onNodeWithTag("input-profile-game").performScrollTo().performClick()
val tops = listOf("primary", "secondary").map { screen ->
compose.onNodeWithTag("input-part-$screen").performScrollTo().performClick()
val top = compose.onNodeWithTag("input-surface-$screen").assertIsDisplayed().fetchSemanticsNode().boundsInRoot.top
compose.onNodeWithText(context.getString(R.string.mode_back)).performClick()
top
}
assertEquals(tops[1], tops[0])
}
@Test fun deviceSettingsAreInlineBelowProfiles() {
compose.setContent { DroidDeckTheme { InputSettingsPage({}) } }
compose.onNodeWithTag("input-more").assertDoesNotExist()
-6
View File
@@ -293,12 +293,6 @@ configuration falls back to the inherited environment without evaluating its
contents. Both component and environment selection normalize signed non-Steam
prefix IDs to unsigned IDs.
A Dragon's Dogma 2 launch (Steam app 2054970) appends the game's own
`/WineDetectionEnabled:False` switch: the game checks for Wine and its Wine path
does not start. The switch is added only at launch, never to Steam's stored
Launch Options, and a user's own `/WineDetectionEnabled:` value in Launch
Options keeps priority and is not repeated.
The published file also carries generated `dxvkConfig` and `dxvkConfigGames`
values the app's own file never has. The session menu's texture filtering
(`core/TextureFiltering`) becomes `d3d9/d3d11.samplerAnisotropy` and
+1 -25
View File
@@ -131,18 +131,6 @@ The client's web helper draws its whole UI. There are two:
blank. `LinuxRuntime` binds an empty folder over `/sys/bus/pci/devices` on such devices; device:
0 GPU process exits, ANGLE on zink and Turnip.
FEX ships per-program AppConfigs, and `/usr/local/share/fex-emu/AppConfig/steamwebhelper.json` turns
the GL thunk off for every program named `steamwebhelper`. A program's AppConfig is read after
`FEX_THUNKCONFIG`, so the x86 helper got the rootfs's x86 Mesa while the client next to it had the
thunk. Steam's browser compositor creates its output window through SDL3 and GLX in the helper's
browser process, and x86 Mesa's `driCreateNewScreen3` (kisak libgallium 26.1.6) faulted there
(SIGSEGV, exit 139) about 11 s after every start; the client restarted it each time (device: 57
restarts in 11 minutes). `x64_env` therefore writes, for every global AppConfig that turns off a
thunk the session uses, a local AppConfig (`$X64_HOME/.config/fex-emu/AppConfig/<name>.json`, read
after the global one) with the session's thunk set. It never touches a local file with other content,
so a user's own AppConfig wins, and removes its own files when the client runs in software. Device:
helper up for over 10 minutes with no restart, ANGLE on zink and Turnip through the thunk.
The session shim (`preload/net.c`) turns `steamrt64/steamwebhelper.sh`'s exec of `./steamwebhelper`
into `DD_X64_ARM_WEBHELPER`. Nothing in the client's folder is edited: the client checksums its files
as it starts and reinstalled itself over an edited launcher (2-3 minutes) on every start.
@@ -209,25 +197,13 @@ alone would then read as an installed client.
restarted from the top forever (found with `perf_event_open` IP sampling, since proot holds
ptrace). Such a range is now skipped whole and a second exhausted scan returns `-ENOMEM`, as the
kernel does (`fex-2610-r3`).
- `0006-smc-alias-of-code-created-after-translation`: a JIT with a double-mapped memfd (CoreCLR's
W^X allocator) maps its writable alias after the executable alias was translated. Under
`SMCChecks=mtrack` the new alias was not write-protected, so writes through it never faulted and
never invalidated the translated code; x86-64 .NET programs ran stale code (access violations,
NullReferenceException, internal CLR errors). A writable mapping or mprotect now write-protects the
overlapping part of any alias that is already executable, so the first write faults and invalidates.
`FEX_SMCCHECKS=full` was the only workaround; no setting is needed with the patch.
- `0007-cmake-install-code-without-depends`: CMake 4.5 rejects the `DEPENDS` argument FEX passes to
`install(CODE ...)` for the guest thunk libraries, so builds with host thunks stopped at configure.
The guest libraries are external projects in the default build, which `install` already follows.
- **Building and publishing.** Droid-Deck/DroidDeck-Components' `build-fex.yml` builds `tools/fex` from
this repository at a chosen ref (default `main`) with host thunks, in the same Arch Linux ARM container
with a read-only token, then a separate job replaces `fex.tzst` on Components' single `fex` release,
checks the digest GitHub stored, and records the build's version, sha256 and size in its `fex.json`
(in that order: a device that reads the old `fex.json` meanwhile gets a mismatching archive and keeps
its FEX). This repository's `build-fex.yml` only builds `tools/fex` when it changes (and on dispatch,
for diagnostic builds such as `-DDEBUG_STRACE`); nothing is published from it. It builds FEX's latest
release, point releases (`FEX-2611.1`) included; `build-in-arch.sh` takes the tag from `FEX_VERSION`
and compares only its four-digit release against a patch's `Fixed-upstream`.
for diagnostic builds such as `-DDEBUG_STRACE`); nothing is published from it.
- Releases so far: `fex-2609-r2` (no thunks), `fex-2609-r3` (thunks), `fex-2610-r1`, `fex-2610-r2`,
`fex-2610-r3`, `fex-2610-r4` (in-root resolution when openat2 is missing, exact MAP_32BIT
marking), `fex-2610-r5` (current: bundles libxxhash, which the Linux runtime does not ship; the
-45
View File
@@ -1,45 +0,0 @@
DroidDeck bionic runtime pack: sources, credits and licences
Built by DroidDeck's CI with tools/bionic-runtime/build.sh (GPL-3.0, like DroidDeck). Exact pins and the
sha256 of every file are in MANIFEST.txt.
Built from source in this pack:
- layer/libVkLayer_FROG_gamescope_wsi_aarch64.so: gamescope's Vulkan WSI layer (Valve Corporation, BSD-2-Clause,
https://github.com/ValveSoftware/gamescope) at the pinned tag with DroidDeck's patches 0117 and 0119
(tools/gamescope/patches), using vkroots by Joshua Ashton (vkroots.h: Apache-2.0 OR MIT,
https://github.com/Joshua-Ashton/vkroots) and the Khronos Vulkan-Headers (Apache-2.0 / MIT).
- preload/libfakeinput.so: DroidDeck's app/src/main/cpp/fakeinput_steam.cpp, taken from WinNative by maxjivi05
(GPL-3.0, https://github.com/WinNative-Emu/WinNative), mmap ring controller input by ribbit384 (WinNative #345).
- preload/libnotag.so, bin/gstag: DroidDeck (GPL-3.0).
- layer/libVkLayer_droiddeck_gpuload.so: DroidDeck's HUD GPU-load Vulkan layer (tools/gpuload, GPL-3.0), built for the
bionic userland.
Taken unchanged from The412Banner's Bannerlator (GPL-3.0, https://github.com/The412Banner/Bannerlator):
- lib/: Android builds of open-source libraries from Bannerlator's base imagefs
(https://github.com/The412Banner/winlator-contents, release base-assets-v1), among them X.Org libX11/libXext/...
and libxcb (MIT/X11), Wayland (MIT), SDL2 (zlib), GStreamer and its plugins, GLib, PulseAudio, GnuTLS, libsndfile,
alsa-lib, libiconv (LGPL-2.1 or later), FreeType (FTL or GPL-2.0), Fontconfig (MIT), libxml2 (MIT), libffi (MIT),
PCRE2 (BSD-3-Clause), zlib (zlib), and FFmpeg 8 libraries (LGPL-2.1 or later) from Bannerlator's ffmpeg8.tzst.
share/X11 and etc/ (fonts, tls) come from the same imagefs.
From The412Banner/Banners-Turnip (https://github.com/The412Banner/Banners-Turnip, release
fastgl-x11egl-mesa-d8cfbe8-r1):
- egl/: Mesa (MIT, https://gitlab.freedesktop.org/mesa/mesa) EGL, GLX and Gallium with Zink at Mesa main d8cfbe82766,
built for the bionic userland with the x11 and wayland platforms (branch fix/fastgl-zink-readback, the
exp/egl-x11-platform recipe that builds Bannerlator's Fast OpenGL set), with libwayland-client (MIT) and libarchive
(BSD-2-Clause); egl/x11egl.json records the build. Newer Mesa brings Zink's kopper front-buffer readback fixes by
Mike Blumenkrantz.
From The412Banner/bionic-vulkan-wrapper (https://github.com/The412Banner/bionic-vulkan-wrapper, release
wayland-adapter-placed-export-r1):
- adapter/libvulkan_wrapper.so: the Wayland adapter Bannerlator ships (branch banner/wayland-wsi-bgra-native) plus
placed-mapping fixes for 32-bit OpenGL / WineD3D (branch banner/wayland-wsi-placed-export), a Mesa tree (MIT) in
the line of Pipetto-crypto's wrapper and leegao's bionic Vulkan wrapper. adapter/adapter.json records the build.
Taken unchanged from DroidDeck-Proton (https://github.com/Droid-Deck/DroidDeck-Proton, release DroidDeck-Proton-11-12.8):
- d7vk/ddraw.dll: D7VK by WinterSnowfall (zlib, https://github.com/WinterSnowfall/d7vk, commit 06656b9e), Direct3D 7
and older on Vulkan, based on DXVK by Philip Rebohle and contributors (zlib, https://github.com/doitsujin/dxvk);
32-bit build from DroidDeck-Proton's CI.
Not in this pack: the bionic DroidDeck-Proton layer (The412Banner/proton-wine releases), GPU drivers, DXVK/VKD3D
and FEX (DroidDeck components).
@@ -1,14 +0,0 @@
{
"file_format_version" : "1.0.0",
"layer" : {
"name": "VK_LAYER_FROG_gamescope_wsi_aarch64",
"type": "GLOBAL",
"api_version": "1.3.221",
"library_path": "./libVkLayer_FROG_gamescope_wsi_aarch64.so",
"implementation_version": "1",
"description": "Gamescope WSI (XWayland Bypass) Layer (aarch64), bionic build",
"functions": { "vkNegotiateLoaderLayerInterfaceVersion": "vkNegotiateLoaderLayerInterfaceVersion" },
"enable_environment": { "ENABLE_GAMESCOPE_WSI": "1" },
"disable_environment": { "DISABLE_GAMESCOPE_WSI": "1" }
}
}
-9
View File
@@ -1,9 +0,0 @@
// glibc's program_invocation_name is __progname in Android's libc (exported, set from argv[0]).
#pragma once
#ifdef __cplusplus
extern "C" char *__progname;
#else
extern char *__progname;
#endif
#define program_invocation_name __progname
#define program_invocation_short_name __progname
-272
View File
@@ -1,272 +0,0 @@
#!/usr/bin/env bash
# Builds DroidDeck's bionic runtime pack: the Android-side (bionic libc) pieces a bionic DroidDeck-Proton layer
# needs inside DroidDeck's gamescope session. The Proton layer itself comes from The412Banner/proton-wine releases;
# GPU drivers, DXVK/VKD3D and FEX stay app options. Binaries target Android 11+ (API 30: the fake-input
# library hooks statx).
#
# usage: NDK=<Android NDK root> tools/bionic-runtime/build.sh <work dir> <out dir>
# host needs: curl git tar zstd python3, wayland-scanner, and the X11/xcb/wayland/glm headers
# (Debian/Ubuntu: libwayland-bin libwayland-dev libx11-dev libx11-xcb-dev libxcb1-dev libxcb-composite0-dev libglm-dev)
set -euo pipefail
HERE=$(cd "$(dirname "$0")" && pwd)
ROOT=$(cd "$HERE/../.." && pwd)
WORK=${1:?usage: build.sh <work dir> <out dir>}
OUT=${2:?usage: build.sh <work dir> <out dir>}
: "${NDK:?set NDK to the Android NDK root}"
API=30
# Pinned inputs (bump together with their sha256).
IMAGEFS_URL=https://github.com/The412Banner/winlator-contents/releases/download/base-assets-v1/imagefs.tar.zst
IMAGEFS_SHA256=7838756e6a05c91afff68f4bf12aa2780f815877753f8dd354e203e99b9caf8a # same pin as Bannerlator app/build.gradle
BL_COMMIT=410c969dfe37ed0c687d6a5ee3327ea21a53e0f8 # The412Banner/Bannerlator
BL_ASSETS=https://raw.githubusercontent.com/The412Banner/Bannerlator/$BL_COMMIT/app/src/main/assets
# The Wayland adapter: Bannerlator's (bionic-vulkan-wrapper banner/wayland-wsi-bgra-native f970b6c) plus the placed-
# mapping fixes 32-bit OpenGL / WineD3D need (branch banner/wayland-wsi-placed-export), from that repository's release.
ADAPTER_URL=https://github.com/The412Banner/bionic-vulkan-wrapper/releases/download/wayland-adapter-placed-export-r1
ADAPTER_SHA256=653791c2c2ea904a5122909f01d26689553e91cc4dc7a981478c1303adc96ea5 # libvulkan_wrapper.so
ADAPTER_JSON_SHA256=5448fd64f15fa13ca3c805967c2b4788eb5f86d29a2d2755e15498130cdef9b3
# OpenGL: the Fast OpenGL Mesa set (EGL + GLX + Zink) rebuilt from Mesa main d8cfbe82766 for Zink's kopper readback
# fixes (Banners-Turnip fix/fastgl-zink-readback e07e94d0, run 44232301491); Bannerlator's copy is the 7cda7850 build.
FASTGL_URL=https://github.com/The412Banner/Banners-Turnip/releases/download/fastgl-x11egl-mesa-d8cfbe8-r1
FFMPEG8_SHA256=34ca9076b6b69bc96ee0d53fcb7b9d0d8df869b9f1255dd686bf89cc590b1b08 # ffmpeg8.tzst
GAMESCOPE_TAG=3.16.29
GAMESCOPE_COMMIT=8f212644c46460549035971ab914421180f61a7c
GAMESCOPE_PATCHES="0117-wsi-cache-present-bypass-check.patch 0119-wsi-default-images-under-limiter.patch"
VULKAN_HEADERS_TAG=v1.4.341
# The bionic DroidDeck-Proton layer the pack is made for: linked against (libwayland-client) and checked against, not packed.
# Layer v16 (067c719d) plus the ARM64EC code-map fix for 39-bit hosts (d4c9ffa7, run 44291095238).
LAYER_URL=https://github.com/The412Banner/proton-wine/releases/download/build-bionic-layers-20261118-v16-unwind/DroidDeck-Proton-11.0-12.8-arm64ec.wcp
LAYER_SHA256=3cc74b877bc8707d75aa2cc22e335373b6a6c0b6b1937c7b3c2cd98e55de2e89 # proton-wine d48e30a1 (a188791d + fecf7376 on d4c9ffa7)
LAYER_VERSION=12.8
# Packed into the DroidDeck-Bionic tool next to the layer: FEX with Android-built unix libraries, and default
# DXVK / VKD3D-Proton (DroidDeck components can swap these in files/lib/wine/{dxvk,vkd3d-proton} later).
FEX_URL=https://github.com/The412Banner/Nightlies/releases/download/FEXCore-2611.1/FEXCore-2611.1-unix.wcp
FEX_SHA256=caca997e5e077feb5d9b7cf0f2c680cd93b442278903e3f3e7b1bd9cd544770c
DXVK_URL=https://github.com/The412Banner/Nightlies/releases/download/Dxvk-gplasync-Linux/dxvk-gplasync-2.4.1-1-pre-reg-linux.wcp
DXVK_SHA256=379b5dcde331de45a5f0ac7775d2c657c9c1510616afb9143ab8cdfbfa8e5342
# VKD3D-Proton from DroidDeck-Components' stable release: the linux-nightly files are replaced as nightlies land.
VKD3D_URL=https://github.com/Droid-Deck/DroidDeck-Components/releases/download/linux-stable/DD-vkd3d-proton-arm64ec-3.1.wcp
VKD3D_SHA256=bd458d8adb08631d7d5da93c51ad02ce224178127d3408ca693b2947bf85bdd0
# D7VK's 32-bit ddraw.dll (PROTON_USE_D7VK): the same file DroidDeck-Proton 11-12.8 ships, built there from
# WinterSnowfall/d7vk; only that file is taken out of the release archive.
D7VK_FROM=https://github.com/Droid-Deck/DroidDeck-Proton/releases/download/DroidDeck-Proton-11-12.8/DroidDeck-Proton-11-12.8-aarch64.tar.gz
D7VK_MEMBER="DroidDeck-Proton 11-12.8/files/lib/wine/d7vk/i386-windows/ddraw.dll"
D7VK_SHA256=aaf28d3dee147fd359d14bb08228f9d21335fb5fec334415e396353a967574aa
D7VK_COMMIT=06656b9e94bf275854e3d83d6426517253937738
case "$(uname -s):$(uname -m)" in
Linux:x86_64) NDK_HOST=linux-x86_64 ;;
Linux:aarch64|Linux:arm64) NDK_HOST=linux-aarch64 ;;
Darwin:arm64) NDK_HOST=darwin-arm64 ;;
Darwin:x86_64) NDK_HOST=darwin-x86_64 ;;
*) echo "unsupported host $(uname -s):$(uname -m)" >&2; exit 1 ;;
esac
TC="$NDK/toolchains/llvm/prebuilt/$NDK_HOST/bin"
[[ -d "$TC" ]] || TC="$NDK/toolchains/llvm/prebuilt/linux-x86_64/bin"
CC="$TC/aarch64-linux-android${API}-clang"
CXX="$TC/aarch64-linux-android${API}-clang++"
READELF="$TC/llvm-readelf"
STRIP="$TC/llvm-strip"
[[ -x "$CC" && -x "$CXX" ]] || { echo "no NDK clang under $TC" >&2; exit 1; }
fetch() { # url sha256 dest
curl -fsSL --retry 5 --retry-delay 3 --retry-connrefused -o "$3" "$1"
echo "$2 $3" | sha256sum -c -
}
rm -rf "$WORK"; mkdir -p "$WORK" "$OUT"
PACK="$WORK/droiddeck-bionic-runtime"
mkdir -p "$PACK"/{lib,layer,preload,bin,adapter,share,etc}
echo "== imagefs (Bannerlator base, pinned)"
fetch "$IMAGEFS_URL" "$IMAGEFS_SHA256" "$WORK/imagefs.tar.zst"
mkdir -p "$WORK/imagefs"
tar --zstd -xf "$WORK/imagefs.tar.zst" -C "$WORK/imagefs"
IMG="$WORK/imagefs/usr/lib"
[[ -d "$IMG" ]] || { echo "imagefs has no usr/lib" >&2; exit 1; }
echo "== bionic DroidDeck-Proton layer (pinned; its lib/ is on the library path at run time)"
fetch "$LAYER_URL" "$LAYER_SHA256" "$WORK/layer.wcp"
mkdir -p "$WORK/layer"
tar --zstd -xf "$WORK/layer.wcp" -C "$WORK/layer" lib
LAYERLIB="$WORK/layer/lib"
echo "== Wayland adapter (pinned release)"
fetch "$ADAPTER_URL/libvulkan_wrapper.so" "$ADAPTER_SHA256" "$PACK/adapter/libvulkan_wrapper.so"
fetch "$ADAPTER_URL/adapter.json" "$ADAPTER_JSON_SHA256" "$PACK/adapter/adapter.json"
echo "== Bannerlator assets (pinned): FFmpeg 8"
fetch "$BL_ASSETS/ffmpeg8.tzst" "$FFMPEG8_SHA256" "$WORK/ffmpeg8.tzst"
echo "== D7VK ddraw.dll (DroidDeck-Proton 11-12.8 release, that file only)"
mkdir -p "$PACK/d7vk"
curl -fsSL --retry 5 --retry-delay 3 --retry-connrefused "$D7VK_FROM" | tar -xzO -f - "$D7VK_MEMBER" > "$PACK/d7vk/ddraw.dll"
echo "$D7VK_SHA256 $PACK/d7vk/ddraw.dll" | sha256sum -c -
# OpenGL: bionic Mesa (EGL + GLX + Zink, x11 and wayland platforms) for winex11's EGL backend, the set Bannerlator's
# Fast OpenGL uses, from the newer Mesa build pinned in FASTGL_URL
mkdir -p "$PACK/egl"
for e in libEGL.so.1:7d1febabcb0cb6348128bc44885886fba6a2edc103fcfc91f5f858e460b33fd6 \
libGL.so.1:8de5c26d4de6dcac4dd2605d8742622711adcdb76d9fe5f5848894e439bb3826 \
libGLESv2.so.2:2136442182ed8d724f80b2d69ee89f654694fd84439fdeb14010034c14f57658 \
libgallium-27.0.0-devel.so:392ca9d6d3127b2ac5fc232d25830111c759dc672f437794731fc2778ff0eb34 \
libwayland-client.so:fa49c2f119b84a0cf54669de1706a6bc427bb8a7f147c977328575ccbb920126 \
libarchive.so:eb3b13634bd2c188d71e886f8c690ef32f6b4a2a0e8a7197a7f974b2d341b7ab \
x11egl.json:90c1dcebb746625b81b4cf5335e177a4b7cbe608b359c9be5eaa43d8f0de499b; do
fetch "$FASTGL_URL/${e%%:*}" "${e#*:}" "$PACK/egl/${e%%:*}"
done
cp "$HERE/icd.json" "$PACK/adapter/icd.json"
echo "== libraries from the imagefs"
copy_lib() { # name: copies the file and every link on the way to it, as links (Android's own libraries are skipped)
local name=$1 src=$IMG/$1 target
[[ -e "$src" || -L "$src" ]] || { echo "missing in imagefs: $name" >&2; return 1; }
[[ -L "$src" && "$(readlink "$src")" == /* ]] && return 0
while [[ -L "$src" ]]; do
target=$(readlink "$src")
[[ -e "$PACK/lib/$(basename "$src")" || -L "$PACK/lib/$(basename "$src")" ]] || ln -s "$(basename "$target")" "$PACK/lib/$(basename "$src")"
src="$(dirname "$src")/$target"
done
[[ -e "$PACK/lib/$(basename "$src")" ]] || cp "$src" "$PACK/lib/"
}
grep -v -e '^#' -e '^$' "$HERE/runtime-libs.txt" | while read -r name; do copy_lib "$name"; done
[[ -e "$PACK/lib/libSDL2-2.0.so.0" ]] || ln -s libSDL2-2.0.so "$PACK/lib/libSDL2-2.0.so.0"
mkdir -p "$PACK/lib/gstreamer-1.0"
grep -v -e '^#' -e '^$' "$HERE/gst-plugins.txt" | while read -r p; do cp "$IMG/gstreamer-1.0/libgst$p.so" "$PACK/lib/gstreamer-1.0/"; done
tar --zstd -xf "$WORK/ffmpeg8.tzst" -C "$PACK/lib"
for f in "$PACK"/lib/libav*.so.* "$PACK"/lib/libsw*.so.*; do # soname links for the FFmpeg 8 files
[[ -L "$f" ]] && continue
so=$("$READELF" -d "$f" | sed -n 's/.*(SONAME).*\[\(.*\)\]/\1/p')
[[ -n "$so" && ! -e "$PACK/lib/$so" ]] && ln -s "$(basename "$f")" "$PACK/lib/$so"
done
# GStreamer plugins: add the libraries they need from the imagefs; drop plugins needing something it lacks
python3 "$HERE/check-needed.py" "$READELF" "$PACK" --available "$LAYERLIB" --fill "$IMG" --prune lib/gstreamer-1.0
cp -a "$WORK/imagefs/usr/share/X11" "$PACK/share/"
cp -a "$WORK/imagefs/etc/fonts" "$WORK/imagefs/etc/tls" "$PACK/etc/"
echo "== gamescope $GAMESCOPE_TAG WSI layer (+ DroidDeck patches: $GAMESCOPE_PATCHES)"
GS="$WORK/gamescope"
git clone -q --depth 1 --branch "$GAMESCOPE_TAG" https://github.com/ValveSoftware/gamescope "$GS"
[[ "$(git -C "$GS" rev-parse HEAD)" == "$GAMESCOPE_COMMIT" ]] || { echo "gamescope $GAMESCOPE_TAG is not $GAMESCOPE_COMMIT" >&2; exit 1; }
git -C "$GS" submodule update -q --init --depth 1 subprojects/vkroots || git -C "$GS" submodule update -q --init subprojects/vkroots
for p in $GAMESCOPE_PATCHES; do git -C "$GS" apply "$ROOT/tools/gamescope/patches/$p"; done
git clone -q --depth 1 --branch "$VULKAN_HEADERS_TAG" https://github.com/KhronosGroup/Vulkan-Headers "$WORK/vulkan-headers"
INC="$WORK/inc"; GEN="$WORK/gen"; mkdir -p "$INC" "$GEN"
cp -r "$WORK/vulkan-headers/include/vulkan" "$WORK/vulkan-headers/include/vk_video" "$INC/"
cp -r /usr/include/X11 /usr/include/xcb /usr/include/glm "$INC/"
cp /usr/include/wayland-*.h "$INC/"
for p in gamescope-swapchain gamescope-limiter; do
wayland-scanner client-header "$GS/protocol/$p.xml" "$GEN/$p-client-protocol.h"
wayland-scanner private-code "$GS/protocol/$p.xml" "$GEN/$p-protocol.c"
"$CC" -O2 -fPIC -c -I"$INC" "$GEN/$p-protocol.c" -o "$GEN/$p-protocol.o"
done
LINK=(-L"$PACK/lib" -Wl,-rpath-link,"$PACK/lib" -L"$LAYERLIB" -Wl,-rpath-link,"$LAYERLIB")
"$CXX" -std=c++20 -O2 -fPIC -shared -DWLR_USE_UNSTABLE -D_GNU_SOURCE -include "$HERE/bionic_compat.h" \
-I"$GS/subprojects/vkroots" -I"$GEN" -I"$INC" -I"$GS/layer" -I"$GS/src" \
"$GS/layer/VkLayer_FROG_gamescope_wsi.cpp" "$GEN"/*.o "${LINK[@]}" \
-lwayland-client -lX11-xcb -lX11 -lxcb -lxcb-composite -static-libstdc++ -Wl,--no-undefined \
-o "$PACK/layer/libVkLayer_FROG_gamescope_wsi_aarch64.so"
cp "$HERE/VkLayer_FROG_gamescope_wsi.aarch64.json" "$PACK/layer/"
echo "== DroidDeck GPU-load layer (tools/gpuload), off unless its DroidDeck variables are set"
for l in gpuload; do
"$CC" -std=c11 -shared -fPIC -O2 -Wall -Wno-unused-parameter -Wno-missing-field-initializers -fvisibility=hidden \
-pthread -Wl,-z,defs -include "$HERE/bionic_compat.h" -I"$INC" -I"$ROOT/tools/gpuload/src" \
"$ROOT/tools/gpuload/src/vk_layer_droiddeck_$l.c" -o "$PACK/layer/libVkLayer_droiddeck_$l.so"
done
for j in gpu_load:gpuload; do
sed 's#"library_path": *"[^"]*"#"library_path": "./libVkLayer_droiddeck_'"${j#*:}"'.so"#' \
"$ROOT/tools/gpuload/layer/VK_LAYER_DROIDDECK_${j%%:*}.json" > "$PACK/layer/VK_LAYER_DROIDDECK_${j%%:*}.json"
grep -q '"library_path": "./libVkLayer_droiddeck_' "$PACK/layer/VK_LAYER_DROIDDECK_${j%%:*}.json"
done
echo "== DroidDeck fake input (app/src/main/cpp/fakeinput_steam.cpp), heap-tagging off, window tagger"
"$CXX" -shared -fPIC -O2 -Wall -Wno-attributes -pthread -std=c++17 "$ROOT/app/src/main/cpp/fakeinput_steam.cpp" \
-ldl -static-libstdc++ -o "$PACK/preload/libfakeinput.so"
"$CC" -shared -fPIC -O2 -Wall "$HERE/notag.c" -ldl -o "$PACK/preload/libnotag.so"
"$CC" -shared -fPIC -O2 -Wall "$HERE/execshim.c" -ldl -o "$PACK/preload/libexecshim.so"
"$CC" -shared -fPIC -O2 -Wall -Wextra -fvisibility=hidden "$HERE/steamshm.c" -ldl -o "$PACK/preload/libsteamshm.so"
"$CC" -O2 -Wall "$HERE/gstag.c" -o "$PACK/bin/gstag"
"$STRIP" --strip-unneeded "$PACK/layer/"*.so "$PACK/preload/"*.so "$PACK/bin/gstag"
echo "== every library a pack file needs must be in the pack or on Android"
python3 "$HERE/check-needed.py" "$READELF" "$PACK" --available "$LAYERLIB"
echo "== manifest"
REV=$(git -C "$ROOT" rev-parse --short=8 HEAD)
cp "$HERE/NOTICE" "$PACK/NOTICE"
{
echo "droiddeck-bionic-runtime $REV ($(date -u +%Y-%m-%dT%H:%M:%SZ), Android API $API, NDK $(basename "$NDK"))"
echo "imagefs $IMAGEFS_URL sha256 $IMAGEFS_SHA256"
echo "bannerlator $BL_COMMIT (ffmpeg8.tzst)"
echo "fastgl $FASTGL_URL (egl/: Mesa EGL + GLX + Zink, Mesa main d8cfbe82766)"
echo "adapter $ADAPTER_URL (libvulkan_wrapper.so sha256 $ADAPTER_SHA256)"
echo "layer $LAYER_URL sha256 $LAYER_SHA256 (not packed)"
echo "d7vk $D7VK_COMMIT: i386 ddraw.dll from $D7VK_FROM"
echo "gamescope $GAMESCOPE_TAG $GAMESCOPE_COMMIT + $GAMESCOPE_PATCHES; vkroots $(git -C "$GS/subprojects/vkroots" rev-parse HEAD); Vulkan-Headers $VULKAN_HEADERS_TAG"
echo
(cd "$PACK" && find . -type f ! -name MANIFEST.txt | sort | xargs sha256sum)
} > "$PACK/MANIFEST.txt"
tar --zstd -cf "$OUT/droiddeck-bionic-runtime-$REV.tar.zst" -C "$WORK" droiddeck-bionic-runtime
(cd "$OUT" && sha256sum "droiddeck-bionic-runtime-$REV.tar.zst" > "droiddeck-bionic-runtime-$REV.tar.zst.sha256")
du -sh "$PACK" "$OUT"/*.tar.zst
echo "== DroidDeck-Bionic tool: layer + this pack + FEX + DXVK/VKD3D + tool scripts, in Proton's layout"
NAME="DroidDeck-Bionic-$LAYER_VERSION-r${BUILD_NUMBER:-0}"
T="$WORK/tool/$NAME"
mkdir -p "$T/files" "$T/bionic"
tar --zstd -xf "$WORK/layer.wcp" -C "$T/files" bin lib share prefixPack.txz
mkdir -p "$WORK/pfx" && tar -xJf "$T/files/prefixPack.txz" -C "$WORK/pfx" && rm "$T/files/prefixPack.txz"
mv "$WORK/pfx/.wine" "$T/files/default_pfx"
# No drives in the template: its links point into Winlator, and a Z: -> / link here once let DroidDeck's tool delete
# walk the whole device. launch.sh makes C: and Z: in each game's own prefix.
rm -rf "$T/files/default_pfx/dosdevices"
for c in FEX:"$FEX_URL":"$FEX_SHA256" DXVK:"$DXVK_URL":"$DXVK_SHA256" VKD3D:"$VKD3D_URL":"$VKD3D_SHA256"; do
n=${c%%:*}; rest=${c#*:}; sha=${rest##*:}; url=${rest%:*}
fetch "$url" "$sha" "$WORK/$n.wcp"
mkdir -p "$WORK/$n" && tar --zstd -xf "$WORK/$n.wcp" -C "$WORK/$n"
done
cp "$WORK/FEX/aarch64-unix/"*.so "$T/files/lib/wine/aarch64-unix/"
cp "$WORK/FEX/system32/"*.dll "$T/files/lib/wine/aarch64-windows/"
cp -r "$WORK/DXVK/files/lib/wine/dxvk" "$WORK/VKD3D/files/lib/wine/vkd3d-proton" "$T/files/lib/wine/"
cp -a "$PACK" "$T/files/runtime"
# a spare copy of the tool's FEX for launch.sh, which puts it back if DroidDeck's component check swapped in its
# own FEX (glibc unix libraries) for a game with a per-game FEX choice
mkdir -p "$T/files/runtime/fex/aarch64-unix" "$T/files/runtime/fex/aarch64-windows"
cp "$WORK/FEX/aarch64-unix/"*.so "$T/files/runtime/fex/aarch64-unix/"
cp "$WORK/FEX/system32/"*.dll "$T/files/runtime/fex/aarch64-windows/"
install -m 755 "$HERE/tool/proton" "$T/proton"
install -m 755 "$HERE/tool/launch.sh" "$T/bionic/launch.sh"
cp "$HERE/tool/desktop.reg" "$HERE/tool/Xdefaults" "$T/bionic/"
cp "$HERE/tool/toolmanifest.vdf" "$T/"
# The name Steam registers the tool under ends in -Proton: Steam maps Windows save folders (WinAppDataLocal, WinMyDocuments
# ...) into compatdata/<app>/pfx only for tools whose name contains "proton" (a case-insensitive search in
# steamclient.so's compat manager); without it Steam Cloud skipped every such save rule. The folder, the version file and
# the release keep $NAME, which is what DroidDeck matches on.
sed -e "s/@NAME@/$NAME-Proton/" -e "s/@DISPLAY@/DroidDeck-Bionic $LAYER_VERSION r${BUILD_NUMBER:-0}/" "$HERE/tool/compatibilitytool.vdf.in" > "$T/compatibilitytool.vdf"
echo "$(date -u +%s) $NAME" > "$T/version"
{
echo "$NAME: DroidDeck runtime pack $REV + layer + FEX/DXVK/VKD3D"
echo "fex $FEX_URL sha256 $FEX_SHA256"
echo "dxvk $DXVK_URL sha256 $DXVK_SHA256"
echo "vkd3d $VKD3D_URL sha256 $VKD3D_SHA256"
} > "$T/SOURCES.txt"
python3 "$HERE/check-needed.py" "$READELF" "$T/files" --available "$T/files/lib"
echo "== no link may point out of the tool (DroidDeck deletes old tool folders)"
python3 - "$T" <<'PY'
import os, sys
root = os.path.realpath(sys.argv[1])
bad = []
for d, dirs, files in os.walk(root):
for n in dirs + files:
p = os.path.join(d, n)
if os.path.islink(p):
t = os.path.realpath(p)
if t != root and not t.startswith(root + os.sep):
bad.append("%s -> %s" % (os.path.relpath(p, root), os.readlink(p)))
if bad:
sys.exit("links out of the tool:\n" + "\n".join(bad))
print("no links out of the tool")
PY
tar -C "$WORK/tool" -cf - "$NAME" | xz -T0 -6 > "$OUT/$NAME-aarch64.tar.xz"
(cd "$OUT" && sha512sum "$NAME-aarch64.tar.xz" > "$NAME-aarch64.sha512sum")
du -sh "$T" "$OUT/$NAME-aarch64.tar.xz"
-126
View File
@@ -1,126 +0,0 @@
#!/usr/bin/env python3
"""Checks that every library an ELF file in the bionic runtime pack needs is in the pack, in --available
(the Proton layer's lib/, on the library path at run time) or on Android.
usage: check-needed.py <llvm-readelf> <pack dir> [--available DIR]... [--fill IMAGEFS_LIB] [--prune SUBDIR]
--fill copies missing libraries (and the links on the way to them) from IMAGEFS_LIB into <pack>/lib, repeatedly
--prune deletes ELF files under <pack>/SUBDIR that still miss a library (plugins nothing else links to)
Exits 1 when anything is still missing."""
import argparse
import os
import shutil
import subprocess
import sys
# Android's own libraries (/system/lib64, /apex) the pack may rely on.
ANDROID = {
"libc.so", "libm.so", "libdl.so", "liblog.so", "libz.so", "libandroid.so", "libnativewindow.so", "libsync.so",
"libEGL.so", "libGLESv1_CM.so", "libGLESv2.so", "libGLESv3.so", "libvulkan.so", "libaaudio.so", "libOpenSLES.so",
"libmediandk.so", "libjnigraphics.so", "libcamera2ndk.so", "libbinder_ndk.so", "ld-android.so",
}
# Known gaps, loaded only for features the first version does not cover.
OPTIONAL = {
"libGL.so.1", # OpenGL games; a dangling link in the pinned imagefs
"libodbc.so", # odbc32
}
def elf_files(pack):
for root, _, files in os.walk(pack):
for f in files:
path = os.path.join(root, f)
if os.path.islink(path) or not os.path.isfile(path):
continue
with open(path, "rb") as fh:
if fh.read(4) == b"\x7fELF":
yield path
def needed(readelf, path):
run = subprocess.run([readelf, "-d", path], capture_output=True, text=True)
if run.returncode != 0: # a damaged ELF must fail the check, not pass with no dependencies
raise SystemExit("check-needed: %s -d %s failed (%d): %s" % (readelf, path, run.returncode, run.stderr.strip()))
return [l.split("[", 1)[1].split("]", 1)[0] for l in run.stdout.splitlines() if "(NEEDED)" in l]
def names_in(*dirs):
names = set()
for d in dirs:
for root, _, files in os.walk(d):
# a link whose target is missing provides nothing
names.update(f for f in files if os.path.isfile(os.path.join(root, f)))
return names
def missing_map(readelf, pack, available):
have = names_in(pack, *available)
missing = {}
for path in elf_files(pack):
for lib in needed(readelf, path):
if lib not in have and lib not in ANDROID and lib not in OPTIONAL:
missing.setdefault(lib, []).append(path)
return missing
def copy_from(img, name, dest):
"""Copies img/name into dest, keeping relative links; False when absent or one of Android's (absolute link)."""
src = os.path.join(img, name)
if not os.path.lexists(src):
return False
while os.path.islink(src):
target = os.readlink(src)
if target.startswith("/"):
return False
link = os.path.join(dest, os.path.basename(src))
if not os.path.lexists(link):
os.symlink(os.path.basename(target), link)
src = os.path.join(os.path.dirname(src), target)
if not os.path.exists(src):
return False
out = os.path.join(dest, os.path.basename(src))
if not os.path.exists(out):
shutil.copy2(src, out)
return True
def main():
ap = argparse.ArgumentParser()
ap.add_argument("readelf")
ap.add_argument("pack")
ap.add_argument("--available", action="append", default=[])
ap.add_argument("--fill")
ap.add_argument("--prune")
a = ap.parse_args()
if a.fill:
added = []
while True:
missing = missing_map(a.readelf, a.pack, a.available)
new = [lib for lib in sorted(missing) if copy_from(a.fill, lib, os.path.join(a.pack, "lib"))]
if not new:
break
added += new
print(f"added from the imagefs: {len(added)} ({', '.join(added)})" if added else "added from the imagefs: none")
if a.prune:
prune_root = os.path.join(a.pack, a.prune)
while True:
missing = missing_map(a.readelf, a.pack, a.available)
doomed = {p for users in missing.values() for p in users if p.startswith(prune_root + os.sep)}
if not doomed:
break
for p in sorted(doomed):
libs = sorted(l for l, users in missing.items() if p in users)
print(f"pruned {os.path.relpath(p, a.pack)}: missing {', '.join(libs)}")
os.remove(p)
missing = missing_map(a.readelf, a.pack, a.available)
for lib, users in sorted(missing.items()):
print(f"missing {lib}: needed by {', '.join(sorted(os.path.relpath(u, a.pack) for u in users)[:5])}")
if missing:
sys.exit(1)
print("all needed libraries present")
if __name__ == "__main__":
main()
Loaded 100 of 144 files, more files were not shown because too many files have changed in this diff. Show more