mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-06 04:55:44 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d584d2cadc | ||
|
|
486b1d3758 | ||
|
|
72a7c18797 |
No files matched your search
@@ -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:
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -70,7 +70,7 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V
|
||||
|
||||
- Runtime, shim, input and controller work build on WinNative and Bannerlator by maxjivi05.
|
||||
- mmap ring buffer controller input by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)).
|
||||
- [FEX](https://github.com/FEX-Emu/FEX) (MIT) runs x86 code. DroidDeck's build puts the platform name under `AT_PLATFORM` so [sharun](https://github.com/VHSgunzo/sharun) AppImages by VHSgunzo (MIT) start through its [userland-execve](https://crates.io/crates/userland-execve) loader (MIT), and its GL thunk hands X errors to the program's own error handler. FEX's code disk cache was checked in its source. The fix for host stack left behind when a program leaves a signal handler without returning follows the approach suggested in [FEX-Emu/FEX#2487](https://github.com/FEX-Emu/FEX/issues/2487). The host stack fix for system calls that end a block is a backport of Ryan Houdek's [FEX-Emu/FEX#6122](https://github.com/FEX-Emu/FEX/pull/6122).
|
||||
- [FEX](https://github.com/FEX-Emu/FEX) (MIT) runs x86 code. DroidDeck's build puts the platform name under `AT_PLATFORM` so [sharun](https://github.com/VHSgunzo/sharun) AppImages by VHSgunzo (MIT) start through its [userland-execve](https://crates.io/crates/userland-execve) loader (MIT), and its GL thunk hands X errors to the program's own error handler. FEX's code disk cache was checked in its source.
|
||||
- x86 AppImages, and arm64 ones whose runtime can't unpack on Android, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence.
|
||||
- x86 programs linking OpenSSL 3 use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt). x86 Linux games get the `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes.
|
||||
- `WriteProcessMemory` hooks fall back to `/proc/<pid>/mem` the way [Wine](https://gitlab.winehq.org/wine/wine)'s `server/ptrace.c` did before Wine 11.
|
||||
|
||||
@@ -15,7 +15,6 @@ private fun Launcher(tab: String, games: List<com.droiddeck.launcher.frontend.Li
|
||||
PreviewHost { FrontEndScreen(sampleState(games = games, navigate = tab, ready = ready), sampleActions) }
|
||||
|
||||
@DroidDeckPreviews @Composable private fun SteamTabPreview() = Launcher("steam")
|
||||
@DroidDeckPreviews @Composable private fun SteamEmptyPreview() = Launcher("steam", games = emptyList())
|
||||
@DroidDeckPreviews @Composable private fun LibraryPreview() = Launcher("games")
|
||||
@DroidDeckPreviews @Composable private fun LibraryEmptyPreview() = Launcher("games", games = emptyList())
|
||||
@DroidDeckPreviews @Composable private fun StoresPreview() = Launcher("stores")
|
||||
|
||||
@@ -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
|
||||
@@ -187,7 +184,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
private var gpuClockPin by mutableStateOf(false)
|
||||
private var prootNoSeccomp by mutableStateOf(false)
|
||||
private var prootFastPath by mutableStateOf(true)
|
||||
private var nativeUserland by mutableStateOf(true)
|
||||
private var nativeUserland by mutableStateOf(false)
|
||||
private var cursorComposite by mutableStateOf(false)
|
||||
private var guestHostname by mutableStateOf(SessionPrefs.DEFAULT_GUEST_HOSTNAME)
|
||||
private var phantomWarning by mutableStateOf<String?>(null)
|
||||
@@ -1531,7 +1528,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
onAddonImport = { sg, target -> importAddons(sg.name, target) },
|
||||
onAddonDelete = { target, name ->
|
||||
saveAction(getString(R.string.main_addons_deleting, name)) {
|
||||
com.droiddeck.launcher.ui.deleteAddon(this, target, name)
|
||||
com.droiddeck.launcher.runtime.WowAddons.delete(target, name)
|
||||
getString(R.string.main_addons_deleted, name)
|
||||
}
|
||||
},
|
||||
@@ -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()
|
||||
|
||||
@@ -4476,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,293 +1,10 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.stores.battlenet.BattleNetInstall
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.time.Instant
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import java.util.concurrent.LinkedBlockingQueue
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
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"
|
||||
internal const val AGENT = "/usr/local/bin/droiddeck-agent"
|
||||
private const val READY_MS = 120_000L
|
||||
private const val INSTALL_MS = 300_000L
|
||||
private const val OUT_OF_DATE = 2
|
||||
|
||||
enum class Start { READY, BUSY, FAILED }
|
||||
|
||||
class Started(val state: Start, val inspector: String? = null)
|
||||
|
||||
class Project(val id: String, val installedModId: String, val folders: List<String>, val update: Boolean)
|
||||
|
||||
internal 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("/") }
|
||||
|
||||
internal fun helperArgv(command: String, dir: String): List<String> = listOf(HELPER, command, dir)
|
||||
|
||||
internal fun evalArgv(inspector: String, expression: String, timeoutMs: Long): List<String> =
|
||||
listOf(AGENT, "--cdp-inspector", inspector, (timeoutMs / 1000.0).toString(), expression)
|
||||
|
||||
internal fun lastJson(lines: List<String>): JSONObject? =
|
||||
lines.asReversed().firstNotNullOfOrNull { line -> runCatching { JSONObject(line.trim()) }.getOrNull() }
|
||||
|
||||
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
|
||||
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 parseProjects(value: Any?): List<Project> {
|
||||
val list = value as? JSONArray ?: return emptyList()
|
||||
return (0 until list.length()).mapNotNull { list.optJSONObject(it) }.mapNotNull { p ->
|
||||
val id = p.optString("id").takeIf { it.isNotBlank() && it != "null" } ?: return@mapNotNull null
|
||||
val folders = p.optJSONArray("folders")?.let { f -> (0 until f.length()).mapNotNull { f.optString(it).takeIf(String::isNotBlank) } }.orEmpty()
|
||||
Project(id, p.optString("installedModId"), folders, p.optInt("status") == OUT_OF_DATE && !p.optBoolean("locked"))
|
||||
}
|
||||
}
|
||||
|
||||
internal fun owner(projects: List<Project>, folder: String): Project? =
|
||||
projects.firstOrNull { project -> project.folders.any { it.equals(folder, ignoreCase = true) } }
|
||||
|
||||
internal fun byFolder(projects: List<Project>): Map<String, Project> = projects.flatMap { project -> project.folders.map { it.lowercase() to project } }.toMap()
|
||||
|
||||
internal fun onDisk(projects: List<Project>, addOns: File): List<Project> {
|
||||
val names = addOns.listFiles().orEmpty().filter { it.isDirectory && !it.name.startsWith(".") }.map { it.name.lowercase() }.toSet()
|
||||
return projects.filter { project -> WowAddons.present(project.folders) { it.lowercase() in names } }
|
||||
}
|
||||
|
||||
internal var guest: (Context, List<String>, AtomicBoolean?, (String) -> Unit) -> Int = { context, argv, cancelled, onLine ->
|
||||
GuestCommand.run(context, argv, logName = "curseforge", extraBinds = BattleNetInstall.binds(context), fastPath = true,
|
||||
cancelled = cancelled, redact = INSPECTOR, onLine = onLine)
|
||||
}
|
||||
|
||||
private val holds = ConcurrentHashMap<String, AtomicBoolean>()
|
||||
|
||||
private fun lines(context: Context, argv: List<String>): List<String> {
|
||||
val out = ArrayList<String>()
|
||||
guest(context, argv, null) { out += it }
|
||||
return out
|
||||
}
|
||||
|
||||
private fun call(context: Context, inspector: String, service: String, method: String, args: JSONArray?, timeoutMs: Long, pick: String = "r => r"): Any? =
|
||||
unwrap(lastJson(lines(context, evalArgv(inspector, expression(service, method, args, pick), timeoutMs))) ?: throw Failure("CurseForge gave no answer"))
|
||||
|
||||
private sealed class Launch {
|
||||
class Url(val inspector: String) : Launch()
|
||||
class Exit(val code: Int) : Launch()
|
||||
}
|
||||
|
||||
private fun launch(context: Context, dir: String, hold: AtomicBoolean): Launch? {
|
||||
val first = LinkedBlockingQueue<Launch>()
|
||||
Thread({
|
||||
val code = runCatching {
|
||||
guest(context, helperArgv("start", dir), hold) { line -> inspectorUrl(line)?.let { first.offer(Launch.Url(it)) } }
|
||||
}.getOrDefault(-1)
|
||||
first.offer(Launch.Exit(code))
|
||||
}, "curseforge-headless").apply { isDaemon = true; start() }
|
||||
return first.poll(READY_MS, TimeUnit.MILLISECONDS)
|
||||
}
|
||||
|
||||
fun start(context: Context, app: UserApps.App, hold: AtomicBoolean): Started {
|
||||
val dir = dir(app) ?: return Started(Start.FAILED)
|
||||
if (hold.get()) return Started(Start.FAILED)
|
||||
holds.put(dir, hold)?.takeIf { it !== hold }?.let {
|
||||
it.set(true)
|
||||
runCatching { lines(context, helperArgv("stop", dir)) }
|
||||
}
|
||||
val inspector = when (val first = launch(context, dir, hold)) {
|
||||
is Launch.Url -> first.inspector
|
||||
is Launch.Exit -> if (startState(first.code) == Start.BUSY) {
|
||||
holds.remove(dir, hold)
|
||||
return Started(Start.BUSY)
|
||||
} else null
|
||||
null -> null
|
||||
}
|
||||
if (inspector == null) {
|
||||
stop(context, app, null, hold)
|
||||
return Started(Start.FAILED)
|
||||
}
|
||||
val deadline = System.currentTimeMillis() + READY_MS
|
||||
while (System.currentTimeMillis() < deadline && !hold.get()) {
|
||||
if (runCatching { call(context, inspector, "InstalledProjectsAppService", "installAddon", null, 10_000) }.isSuccess) return Started(Start.READY, inspector)
|
||||
Thread.sleep(1_000)
|
||||
}
|
||||
stop(context, app, inspector, hold)
|
||||
return Started(Start.FAILED)
|
||||
}
|
||||
|
||||
fun stop(context: Context, app: UserApps.App, inspector: String?, hold: AtomicBoolean) {
|
||||
val dir = dir(app) ?: return
|
||||
if (holds[dir] !== hold) {
|
||||
hold.set(true)
|
||||
return
|
||||
}
|
||||
if (inspector != null) runCatching { call(context, inspector, "CoreService", "shutdown", JSONArray(), 30_000, "r => true") }
|
||||
hold.set(true)
|
||||
if (holds.remove(dir, hold)) runCatching { lines(context, helperArgv("stop", dir)) }
|
||||
}
|
||||
|
||||
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 projects(context: Context, inspector: String, guid: String, rescan: Boolean = false): List<Project> {
|
||||
connect(context, inspector)
|
||||
if (rescan) call(context, inspector, "GameDetectionAppService", "scanGameInstance", JSONArray().put(guid), 120_000)
|
||||
return parseProjects(call(context, inspector, "InstalledProjectsAppService", "getProjects", JSONArray().put(guid), 30_000, PROJECTS))
|
||||
}
|
||||
|
||||
private const val PROJECTS = "r => (r || []).map(p => ({ id: String(p.id), installedModId: p.installedModId, status: p.status, " +
|
||||
"locked: !!(p.installedVersion && p.installedVersion.isLocked), " +
|
||||
"folders: ((p.installedVersion && p.installedVersion.addonFolders) || []).map(f => f.name) }))"
|
||||
|
||||
private fun settle(context: Context, inspector: String, guid: String, done: (List<Project>) -> Boolean): Boolean {
|
||||
val deadline = System.currentTimeMillis() + INSTALL_MS
|
||||
while (System.currentTimeMillis() < deadline) {
|
||||
val listed = runCatching { projects(context, inspector, guid) }
|
||||
val error = listed.exceptionOrNull()
|
||||
if (error is Failure && error.gone) throw error
|
||||
listed.getOrNull()?.let { if (done(it)) return true }
|
||||
Thread.sleep(1_000)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
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
|
||||
return settle(context, inspector, guid) { list -> list.any { it.id == projectId } }
|
||||
}
|
||||
|
||||
fun update(context: Context, inspector: String, guid: String, projectId: String): Boolean {
|
||||
connect(context, inspector)
|
||||
if (call(context, inspector, "InstalledProjectsAppService", "updateMod", JSONArray().put(guid).put(projectId.toLong()), 300_000) != true) return false
|
||||
return settle(context, inspector, guid) { list -> list.any { it.id == projectId && !it.update } }
|
||||
}
|
||||
|
||||
fun uninstall(context: Context, inspector: String, guid: String, project: Project): Boolean {
|
||||
connect(context, inspector)
|
||||
val failed = call(context, inspector, "InstalledProjectsAppService", "deleteMods", JSONArray().put(guid).put(JSONArray().put(project.installedModId)), 120_000) as? JSONArray
|
||||
if (failed == null || failed.length() > 0) return false
|
||||
return settle(context, inspector, guid) { list -> list.none { it.id == project.id } }
|
||||
}
|
||||
}
|
||||
@@ -14,22 +14,20 @@ import java.util.concurrent.atomic.AtomicBoolean
|
||||
object GuestCommand {
|
||||
fun run(context: Context, argv: List<String>, fakeRoot: Boolean = false, logName: String? = null,
|
||||
linkDir: File? = null, extraBinds: List<String>? = null, fastPath: Boolean = false, cancelled: AtomicBoolean? = null,
|
||||
redact: Regex? = null, onLine: (String) -> Unit): Int {
|
||||
onLine: (String) -> Unit): Int {
|
||||
val log = logName?.let {
|
||||
try {
|
||||
File(File(LinuxRuntime.logDir(context), SessionPaths.TOOLS_DIR).apply { mkdirs() }, "$it.log").printWriter()
|
||||
} catch (e: Exception) { null }
|
||||
}
|
||||
log?.println("== ${java.util.Date()} ${redacted(argv.joinToString(" "), redact)}")
|
||||
log?.println("== ${java.util.Date()} ${argv.joinToString(" ")}")
|
||||
try {
|
||||
return runLogged(context, argv, fakeRoot, linkDir, extraBinds, fastPath, cancelled) { line -> log?.println(redacted(line, redact)); log?.flush(); onLine(line) }
|
||||
return runLogged(context, argv, fakeRoot, linkDir, extraBinds, fastPath, cancelled) { line -> log?.println(line); log?.flush(); onLine(line) }
|
||||
} finally {
|
||||
log?.close()
|
||||
}
|
||||
}
|
||||
|
||||
internal fun redacted(text: String, redact: Regex?): String = redact?.replace(text, "<redacted>") ?: text
|
||||
|
||||
private fun runLogged(context: Context, argv: List<String>, fakeRoot: Boolean, linkDir: File?, extraBinds: List<String>?,
|
||||
fastPath: Boolean, cancelled: AtomicBoolean?, onLine: (String) -> Unit): Int {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
|
||||
@@ -29,7 +29,6 @@ object WowAddonCatalog {
|
||||
val downloads: Long,
|
||||
val updated: Long,
|
||||
val thumb: String?,
|
||||
val folders: List<String> = emptyList(),
|
||||
)
|
||||
|
||||
class Page(val items: List<Addon>, val more: Boolean)
|
||||
@@ -94,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 =
|
||||
@@ -115,11 +115,9 @@ object WowAddonCatalog {
|
||||
}
|
||||
val thumbs = o.optJSONArray("UIIMG_Thumbs")
|
||||
val thumb = if (thumbs != null && thumbs.length() > 0) thumbs.optString(0).ifEmpty { null } else null
|
||||
val dirs = o.optJSONArray("UIDir")
|
||||
val folders = if (dirs == null) emptyList() else (0 until dirs.length()).map { dirs.optString(it).trim() }.filter { it.isNotEmpty() }
|
||||
val addon = Addon(
|
||||
id, o.optString("UIName"), o.optString("UIAuthorName"), o.optString("UIVersion"),
|
||||
o.optString("UIDownloadTotal").toLongOrNull() ?: 0L, o.optLong("UIDate"), thumb, folders,
|
||||
o.optString("UIDownloadTotal").toLongOrNull() ?: 0L, o.optLong("UIDate"), thumb,
|
||||
)
|
||||
out.add(Entry(addon, o.optString("UICATID"), flavors, o.optString("UIDownloadMonthly").toLongOrNull() ?: 0L))
|
||||
}
|
||||
@@ -244,32 +242,9 @@ object WowAddonCatalog {
|
||||
return details.version
|
||||
}
|
||||
|
||||
private fun normVersion(v: String) = v.trim().removePrefix("v").removePrefix("V").trim().lowercase()
|
||||
|
||||
internal fun sameVersion(a: String, b: String): Boolean = normVersion(a) == normVersion(b)
|
||||
|
||||
private val NUMERIC_VERSION = Regex("""^(\d+(?:\.\d+)*)(.*)$""")
|
||||
|
||||
private fun numericVersion(v: String): Pair<List<Long>, String>? {
|
||||
val match = NUMERIC_VERSION.matchEntire(normVersion(v)) ?: return null
|
||||
val parts = match.groupValues[1].split('.').map { it.toLongOrNull() ?: return null }
|
||||
return parts to match.groupValues[2]
|
||||
}
|
||||
|
||||
internal fun newer(have: String, latest: String): Boolean? {
|
||||
val (a, aRest) = numericVersion(have) ?: return null
|
||||
val (b, bRest) = numericVersion(latest) ?: return null
|
||||
for (i in 0 until maxOf(a.size, b.size)) {
|
||||
val x = a.getOrElse(i) { 0L }
|
||||
val y = b.getOrElse(i) { 0L }
|
||||
if (x != y) return y > x
|
||||
}
|
||||
return if (aRest == bRest) false else null
|
||||
}
|
||||
|
||||
internal fun offersUpdate(have: String?, latest: String, sameSource: Boolean): Boolean {
|
||||
if (have.isNullOrBlank() || latest.isBlank() || sameVersion(have, latest)) return false
|
||||
return newer(have, latest) ?: sameSource
|
||||
internal fun sameVersion(a: String, b: String): Boolean {
|
||||
fun norm(v: String) = v.trim().removePrefix("v").removePrefix("V").trim().lowercase()
|
||||
return norm(a) == norm(b)
|
||||
}
|
||||
|
||||
internal fun findUpdates(entries: List<Entry>, installed: List<WowAddons.Installed>): Map<String, Addon> {
|
||||
@@ -279,7 +254,7 @@ object WowAddonCatalog {
|
||||
val id = item.wowiId ?: return@mapNotNull null
|
||||
val version = item.version ?: return@mapNotNull null
|
||||
val latest = byId[id]?.addon?.takeIf { it.summary.isNotBlank() } ?: return@mapNotNull null
|
||||
if (!offersUpdate(version, latest.summary, sameSource = true) || !seen.add(id)) null else item.name to latest
|
||||
if (sameVersion(version, latest.summary) || !seen.add(id)) null else item.name to latest
|
||||
}.toMap()
|
||||
}
|
||||
|
||||
|
||||
@@ -28,27 +28,15 @@ 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)
|
||||
|
||||
class Installed(val name: String, val version: String?, val wowiId: String?, val curseId: String? = null)
|
||||
class Installed(val name: String, val version: String?, val wowiId: String?)
|
||||
|
||||
class Origin(val id: String, val version: String)
|
||||
|
||||
private const val ORIGINS = ".droiddeck-sources"
|
||||
private const val TOC_VERSION = "Version"
|
||||
private const val TOC_WOWI_ID = "X-WoWI-ID"
|
||||
private const val TOC_CURSE_ID = "X-Curse-Project-ID"
|
||||
private val TOC_KEYS = setOf(TOC_VERSION, TOC_WOWI_ID, TOC_CURSE_ID)
|
||||
|
||||
internal const val MAX_EXPANDED_BYTES = 4L * 1024 * 1024 * 1024
|
||||
|
||||
@@ -73,52 +61,33 @@ object WowAddons {
|
||||
target.addOns.listFiles().orEmpty().filter { it.isDirectory && !it.name.startsWith(".") }
|
||||
.map { it.name }.sortedBy { it.lowercase() }
|
||||
|
||||
fun present(folders: List<String>, exists: (String) -> Boolean): Boolean = folders.isNotEmpty() && folders.all(exists)
|
||||
|
||||
fun folder(addOns: File, name: String): File? {
|
||||
val dirs = addOns.listFiles().orEmpty().filter { it.isDirectory && !it.name.startsWith(".") }
|
||||
return dirs.firstOrNull { it.name == name } ?: dirs.firstOrNull { it.name.equals(name, ignoreCase = true) }
|
||||
}
|
||||
|
||||
fun details(target: Target): List<Installed> {
|
||||
val origins = origins(target)
|
||||
return installed(target).map { name ->
|
||||
val toc = toc(File(target.addOns, name))
|
||||
val origin = origins[name]
|
||||
Installed(name, origin?.version ?: toc[TOC_VERSION], origin?.id ?: toc[TOC_WOWI_ID], toc[TOC_CURSE_ID])
|
||||
Installed(name, origin?.version ?: toc["Version"], origin?.id ?: toc["X-WoWI-ID"])
|
||||
}
|
||||
}
|
||||
|
||||
internal fun tocFields(lines: Sequence<String>, keys: Set<String> = TOC_KEYS): Map<String, String> {
|
||||
internal fun tocFields(text: String): Map<String, String> {
|
||||
val out = LinkedHashMap<String, String>()
|
||||
for (raw in lines) {
|
||||
for (raw in text.lineSequence()) {
|
||||
val line = raw.trim().removePrefix("\uFEFF")
|
||||
if (!line.startsWith("##") || ':' !in line) continue
|
||||
val key = line.removePrefix("##").substringBefore(':').trim()
|
||||
if (key !in keys || key in out) continue
|
||||
val value = line.substringAfter(':').trim()
|
||||
if (value.isNotEmpty() && '@' !in value) out[key] = value
|
||||
if (out.size == keys.size) break
|
||||
if (key.isNotEmpty() && value.isNotEmpty() && '@' !in value) out.putIfAbsent(key, value)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
private fun toc(folder: File): Map<String, String> {
|
||||
val tocs = folder.listFiles().orEmpty().filter { it.isFile && it.name.endsWith(".toc", ignoreCase = true) }.sortedWith(
|
||||
compareBy<File>(
|
||||
{ !it.name.dropLast(4).equals(folder.name, ignoreCase = true) },
|
||||
{ !it.name.dropLast(4).replace(SUFFIX, "").equals(folder.name, ignoreCase = true) },
|
||||
{ it.name.length },
|
||||
{ it.name },
|
||||
),
|
||||
)
|
||||
val out = LinkedHashMap<String, String>()
|
||||
for (file in tocs) {
|
||||
if (out.size == TOC_KEYS.size) break
|
||||
val missing = TOC_KEYS - out.keys
|
||||
runCatching { file.bufferedReader().useLines { tocFields(it, missing) } }.getOrNull()?.let(out::putAll)
|
||||
}
|
||||
return out
|
||||
val tocs = folder.listFiles().orEmpty().filter { it.isFile && it.name.endsWith(".toc", ignoreCase = true) }
|
||||
val main = tocs.firstOrNull { it.name.dropLast(4).equals(folder.name, ignoreCase = true) }
|
||||
?: tocs.firstOrNull { it.name.dropLast(4).replace(SUFFIX, "").equals(folder.name, ignoreCase = true) }
|
||||
?: tocs.minByOrNull { it.name.length } ?: return emptyMap()
|
||||
return runCatching { tocFields(main.readText()) }.getOrDefault(emptyMap())
|
||||
}
|
||||
|
||||
internal fun parseOrigins(text: String): Map<String, Origin> = text.lineSequence().mapNotNull { line ->
|
||||
|
||||
@@ -180,8 +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-headless" to "usr/local/bin/droiddeck-headless",
|
||||
"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",
|
||||
|
||||
@@ -1011,7 +1011,7 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("prootNoSeccomp", on).apply()
|
||||
}
|
||||
|
||||
fun nativeUserland(context: Context): Boolean = prefs(context).getBoolean("nativeUserland", true)
|
||||
fun nativeUserland(context: Context): Boolean = prefs(context).getBoolean("nativeUserland", false)
|
||||
|
||||
fun setNativeUserland(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("nativeUserland", on).apply()
|
||||
|
||||
@@ -330,7 +330,7 @@ public final class GogDownloadManager {
|
||||
rc = GuestCommand.INSTANCE.run(ctx, Arrays.asList(
|
||||
"/usr/local/bin/droiddeck-innoextract", "--gog", "--silent",
|
||||
"-d", guestDir, guestSetup),
|
||||
false, "gog-innoextract", null, null, false, cancelled, null,
|
||||
false, "gog-innoextract", null, null, false, cancelled,
|
||||
line -> { cb.onLog("gog innoextract: " + line); return kotlin.Unit.INSTANCE; });
|
||||
} catch (Exception e) {
|
||||
throw new InstallException("The installer could not be extracted: " + e.getClass().getSimpleName());
|
||||
|
||||
@@ -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
|
||||
@@ -37,7 +37,6 @@ import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.produceState
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.withFrameNanos
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.snapshotFlow
|
||||
import androidx.compose.ui.Alignment
|
||||
@@ -54,7 +53,6 @@ import androidx.compose.ui.input.InputMode
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalInputModeManager
|
||||
import androidx.compose.ui.platform.LocalLifecycleOwner
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
@@ -62,28 +60,16 @@ import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleEventObserver
|
||||
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.SessionState
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import java.util.concurrent.atomic.AtomicReference
|
||||
|
||||
private class AddonResults {
|
||||
val items = mutableStateListOf<WowAddonCatalog.Addon>()
|
||||
@@ -93,157 +79,12 @@ private class AddonResults {
|
||||
var more by mutableStateOf(false)
|
||||
}
|
||||
|
||||
internal enum class AddonStatus { INSTALL, UPDATE, INSTALLED }
|
||||
|
||||
private enum class AddonSource { WOWI, CURSE }
|
||||
|
||||
internal class CurseState(val notice: Int? = null) : Exception()
|
||||
|
||||
internal class CurseLink(val app: UserApps.App) {
|
||||
class Linked(val inspector: String, val guid: String)
|
||||
|
||||
private val lock = Object()
|
||||
private val work = SupervisorJob()
|
||||
@Volatile private var closed = false
|
||||
@Volatile private var hold: AtomicBoolean? = null
|
||||
@Volatile private var inspector: String? = null
|
||||
private val guids = HashMap<String, String>()
|
||||
private val scanLock = Object()
|
||||
private val scans = HashMap<String, Pair<Any, List<CurseForgeApp.Project>>>()
|
||||
var generation by mutableIntStateOf(0)
|
||||
private set
|
||||
|
||||
fun refresh() {
|
||||
generation++
|
||||
}
|
||||
|
||||
fun installed(context: Context, target: WowAddons.Target, key: Any): List<CurseForgeApp.Project> = CurseForgeApp.onDisk(
|
||||
synchronized(scanLock) {
|
||||
scans[target.addOns.path]?.takeIf { it.first == key }?.second
|
||||
?: call(context, target) { CurseForgeApp.projects(context, it.inspector, it.guid, rescan = true) }.also {
|
||||
scans[target.addOns.path] = key to it
|
||||
report(target, it)
|
||||
}
|
||||
},
|
||||
target.addOns,
|
||||
)
|
||||
|
||||
fun marks(context: Context, target: WowAddons.Target, key: Any): Map<String, String?> =
|
||||
runCatching { installed(context, target, key).associate { it.id to curseMark(it) } }.getOrElse { lastReported(target) }
|
||||
|
||||
fun <T> call(context: Context, target: WowAddons.Target, launch: Boolean = true, block: (Linked) -> T): T {
|
||||
val linked = synchronized(lock) { link(context, target, launch) }
|
||||
try {
|
||||
return block(linked)
|
||||
} catch (e: CurseForgeApp.Failure) {
|
||||
if (e.gone) synchronized(lock) {
|
||||
if (inspector == linked.inspector) {
|
||||
inspector = null
|
||||
guids.clear()
|
||||
current.compareAndSet(this, null)
|
||||
}
|
||||
}
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
private fun link(context: Context, target: WowAddons.Target, launch: Boolean): Linked {
|
||||
if (closed) throw CurseState()
|
||||
val url = inspector ?: run {
|
||||
if (!launch) throw CurseState()
|
||||
val hold = AtomicBoolean(false)
|
||||
this.hold = hold
|
||||
if (closed) throw CurseState()
|
||||
val done = CurseForgeApp.start(context, app, hold)
|
||||
when (done.state) {
|
||||
CurseForgeApp.Start.READY -> {
|
||||
inspector = done.inspector
|
||||
if (!closed) current.set(this)
|
||||
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 uninstall(context: Context, target: WowAddons.Target, folder: String): Boolean = call(context, target, launch = false) { linked ->
|
||||
val projects = CurseForgeApp.onDisk(CurseForgeApp.projects(context, linked.inspector, linked.guid), target.addOns)
|
||||
val project = CurseForgeApp.owner(projects, folder) ?: return@call false
|
||||
if (!CurseForgeApp.uninstall(context, linked.inspector, linked.guid, project)) throw CurseState()
|
||||
true
|
||||
}
|
||||
|
||||
internal val stopped: Job get() = work
|
||||
|
||||
fun close(context: Context): Job {
|
||||
closed = true
|
||||
current.compareAndSet(this, null)
|
||||
val launch = hold
|
||||
return CoroutineScope(work + Dispatchers.IO).launch {
|
||||
if (launch != null) CurseForgeApp.stop(context, app, inspector, launch)
|
||||
synchronized(lock) {
|
||||
hold = null
|
||||
inspector = null
|
||||
}
|
||||
}.also { work.complete() }
|
||||
}
|
||||
|
||||
companion object {
|
||||
private val current = AtomicReference<CurseLink?>()
|
||||
private val reported = ConcurrentHashMap<String, List<CurseForgeApp.Project>>()
|
||||
|
||||
fun lastReported(target: WowAddons.Target, disk: () -> List<WowAddons.Installed> = { WowAddons.details(target) }): Map<String, String?> {
|
||||
val last = reported[target.addOns.path] ?: return disk().mapNotNull { it.curseId }.associateWith { null }
|
||||
return CurseForgeApp.onDisk(last, target.addOns).associate { it.id to null }
|
||||
}
|
||||
|
||||
internal fun report(target: WowAddons.Target, projects: List<CurseForgeApp.Project>) {
|
||||
reported[target.addOns.path] = projects
|
||||
}
|
||||
|
||||
fun live(): CurseLink? = current.get()
|
||||
}
|
||||
}
|
||||
private enum class AddonStatus { INSTALL, UPDATE, INSTALLED }
|
||||
|
||||
private const val PAGES_AHEAD = 8
|
||||
private const val CURSE_UPDATE = "update"
|
||||
private const val UNINSTALLING = -1
|
||||
|
||||
private fun curseMark(project: CurseForgeApp.Project): String? = CURSE_UPDATE.takeIf { project.update }
|
||||
|
||||
private class Present(val curse: Map<String, String?> = emptyMap(), val disk: Map<String, WowAddons.Installed> = emptyMap())
|
||||
|
||||
@Composable
|
||||
internal fun rememberCurseLink(app: UserApps.App?, sessionRunning: Boolean): CurseLink? {
|
||||
val context = LocalContext.current.applicationContext
|
||||
val owner = LocalLifecycleOwner.current
|
||||
var visible by remember(owner) { mutableStateOf(owner.lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) }
|
||||
DisposableEffect(owner) {
|
||||
val observer = LifecycleEventObserver { _, event ->
|
||||
if (event == Lifecycle.Event.ON_START) visible = true
|
||||
if (event == Lifecycle.Event.ON_STOP) visible = false
|
||||
}
|
||||
owner.lifecycle.addObserver(observer)
|
||||
onDispose { owner.lifecycle.removeObserver(observer) }
|
||||
}
|
||||
val active = visible && !sessionRunning
|
||||
val link = remember(app?.key, active) { app?.takeIf { active }?.let(::CurseLink) }
|
||||
DisposableEffect(link) {
|
||||
onDispose { link?.close(context) }
|
||||
}
|
||||
return link
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAddons.Target, curseForge: UserApps.App?, link: CurseLink?, 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)
|
||||
@@ -252,33 +93,20 @@ 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 && link != null) curseForge else null
|
||||
LaunchedEffect(link) { link?.refresh() }
|
||||
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 scanKey = link?.generation to WowAddons.imports
|
||||
val snapshot by produceState(presentKey to Present(), target.addOns, scanKey, curse, curseInstalls, curse == null && results.items.isEmpty()) {
|
||||
val into = target
|
||||
val key = curse to into.addOns
|
||||
if (curse != null && link != null && value.first != key) value = key to withContext(Dispatchers.IO) { Present(curse = CurseLink.lastReported(into)) }
|
||||
value = key to withContext(Dispatchers.IO) {
|
||||
if (curse != null && link != null) Present(curse = link.marks(context, into, scanKey))
|
||||
else Present(disk = WowAddons.details(into).associateBy { it.name.lowercase() })
|
||||
}
|
||||
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 } ?: Present()
|
||||
fun status(addon: WowAddonCatalog.Addon): AddonStatus {
|
||||
if (curse != null) return if (addon.id !in present.curse) AddonStatus.INSTALL else if (present.curse[addon.id] == CURSE_UPDATE) AddonStatus.UPDATE else AddonStatus.INSTALLED
|
||||
if (addon.id !in present) return AddonStatus.INSTALL
|
||||
val have = present[addon.id]
|
||||
val latest = installed[installKey(addon, target)]?.takeIf { it.first == addon.summary }?.second ?: addon.summary
|
||||
return diskStatus(addon.folders, present.disk, latest, addon.id)
|
||||
return if (have == null || latest.isBlank() || WowAddonCatalog.sameVersion(have, latest)) AddonStatus.INSTALLED else AddonStatus.UPDATE
|
||||
}
|
||||
fun load(page: Int) {
|
||||
if (results.loading) return
|
||||
@@ -288,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 } })
|
||||
@@ -314,34 +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
|
||||
val updating = status(addon) == AddonStatus.UPDATE
|
||||
installing[key] = 0
|
||||
scope.launch {
|
||||
val done = withContext(Dispatchers.IO) {
|
||||
runCatching {
|
||||
via.call(context, into) {
|
||||
if (updating) CurseForgeApp.update(context, it.inspector, it.guid, addon.id)
|
||||
else CurseForgeApp.install(context, it.inspector, it.guid, addon.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
installing.remove(key)
|
||||
val ok = done.getOrNull() == true
|
||||
WowAddons.changed()
|
||||
curseInstalls++
|
||||
val message = when {
|
||||
ok && updating -> context.getString(R.string.user_apps_updated, addon.name)
|
||||
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
|
||||
@@ -355,33 +149,7 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
|
||||
Toast.makeText(context, message.first, Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}
|
||||
fun uninstall(addon: WowAddonCatalog.Addon) {
|
||||
val key = installKey(addon, target)
|
||||
if (key in installing) return
|
||||
if (SessionState.running) {
|
||||
Toast.makeText(context, R.string.main_addons_close_session, Toast.LENGTH_LONG).show()
|
||||
return
|
||||
}
|
||||
val into = target
|
||||
val via = link?.takeIf { curse != null }
|
||||
installing[key] = UNINSTALLING
|
||||
scope.launch {
|
||||
val done = withContext(Dispatchers.IO) {
|
||||
runCatching {
|
||||
val folders = if (via != null) curseFolders(into, addon.id, via.call(context, into) { linked ->
|
||||
CurseForgeApp.projects(context, linked.inspector, linked.guid).firstOrNull { it.id == addon.id }?.folders.orEmpty()
|
||||
}) else addon.folders
|
||||
deleteAddons(context, into, folders, link)
|
||||
}
|
||||
}
|
||||
installing.remove(key)
|
||||
installed.remove(key)
|
||||
WowAddons.changed()
|
||||
curseInstalls++
|
||||
if (done.isFailure) Toast.makeText(context, R.string.fm_delete_failed, 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) ->
|
||||
@@ -394,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 ->
|
||||
@@ -402,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() } }
|
||||
}
|
||||
@@ -433,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()
|
||||
@@ -447,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()
|
||||
@@ -462,16 +222,12 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
|
||||
) {
|
||||
items(results.items, key = { it.id }) { addon ->
|
||||
val key = installKey(addon, target)
|
||||
AddonRow(addon, status(addon), installing[key], if (addon.id == results.items.firstOrNull()?.id) Modifier.focusRequester(firstAction) else Modifier, { uninstall(addon) }) { install(addon) }
|
||||
AddonRow(addon, status(addon), installing[key], if (addon.id == results.items.firstOrNull()?.id) Modifier.focusRequester(firstAction) else Modifier) { install(addon) }
|
||||
}
|
||||
item(span = { GridItemSpan(maxLineSpan) }) {
|
||||
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) }
|
||||
@@ -485,22 +241,7 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun AddonRow(addon: WowAddonCatalog.Addon, status: AddonStatus, progress: Int?, action: Modifier, onUninstall: () -> Unit, onInstall: () -> Unit) {
|
||||
var asking by remember(addon.id) { mutableStateOf(false) }
|
||||
val first = remember(addon.id) { FocusRequester() }
|
||||
var refocus by remember(addon.id) { mutableStateOf(false) }
|
||||
val inputMode = LocalInputModeManager.current
|
||||
LaunchedEffect(status, progress) {
|
||||
if (!refocus) return@LaunchedEffect
|
||||
withFrameNanos { }
|
||||
runCatching { first.requestFocus() }
|
||||
if (progress == null) refocus = false
|
||||
}
|
||||
fun act(block: () -> Unit) {
|
||||
refocus = inputMode.inputMode == InputMode.Keyboard
|
||||
block()
|
||||
}
|
||||
val lead = action.focusRequester(first)
|
||||
private fun AddonRow(addon: WowAddonCatalog.Addon, status: AddonStatus, progress: Int?, action: Modifier, onInstall: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
Row(
|
||||
@@ -518,24 +259,13 @@ internal fun AddonRow(addon: WowAddonCatalog.Addon, status: AddonStatus, progres
|
||||
fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
val uninstall = stringResource(R.string.common_uninstall)
|
||||
val size = Modifier.widthIn(min = 104.dp).then(action)
|
||||
when {
|
||||
progress == UNINSTALLING -> SecondaryButton(stringResource(R.string.stores_uninstalling), compact = true, modifier = lead) {}
|
||||
progress != null -> SecondaryButton(stringResource(R.string.store_installing), compact = true, modifier = lead, progress = progress / 100f, onClick = onInstall)
|
||||
status == AddonStatus.INSTALL -> PrimaryButton(stringResource(R.string.store_install), compact = true, modifier = lead) { act(onInstall) }
|
||||
else -> {
|
||||
if (status == AddonStatus.UPDATE) PrimaryButton(stringResource(R.string.common_update), compact = true, modifier = lead) { act(onInstall) }
|
||||
SecondaryButton(uninstall, compact = true, modifier = if (status == AddonStatus.UPDATE) Modifier else lead) { asking = true }
|
||||
}
|
||||
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) {}
|
||||
else -> PrimaryButton(stringResource(if (status == AddonStatus.UPDATE) R.string.common_update else R.string.store_install), compact = true, modifier = size, onClick = onInstall)
|
||||
}
|
||||
}
|
||||
if (asking) ConfirmDialog(
|
||||
title = stringResource(R.string.stores_uninstall_title, addon.name),
|
||||
text = stringResource(R.string.games_delete_addon_body),
|
||||
confirm = stringResource(R.string.common_uninstall),
|
||||
onConfirm = { asking = false; act(onUninstall) },
|
||||
onDismiss = { asking = false },
|
||||
)
|
||||
}
|
||||
|
||||
private fun Modifier.scrollThumb(state: LazyGridState, color: Color): Modifier = drawWithContent {
|
||||
@@ -584,25 +314,4 @@ internal fun installAddon(context: Context, addon: WowAddonCatalog.Addon, target
|
||||
}
|
||||
}
|
||||
|
||||
internal fun diskStatus(folders: List<String>, onDisk: Map<String, WowAddons.Installed>, latest: String, id: String): AddonStatus {
|
||||
if (!WowAddons.present(folders) { it.lowercase() in onDisk }) return AddonStatus.INSTALL
|
||||
val have = onDisk.getValue(folders.first().lowercase())
|
||||
return if (WowAddonCatalog.offersUpdate(have.version, latest, sameSource = have.wowiId == id)) AddonStatus.UPDATE else AddonStatus.INSTALLED
|
||||
}
|
||||
|
||||
internal fun curseFolders(target: WowAddons.Target, id: String, listed: List<String>): List<String> =
|
||||
listed.ifEmpty { WowAddons.details(target).filter { it.curseId == id }.map { it.name } }
|
||||
|
||||
internal fun deleteAddons(context: Context, target: WowAddons.Target, folders: List<String>, link: CurseLink?) {
|
||||
val found = folders.mapNotNull { WowAddons.folder(target.addOns, it) }
|
||||
if (found.isEmpty()) throw IOException("No addon folder to delete")
|
||||
found.forEach { deleteAddon(context, target, it.name, link) }
|
||||
}
|
||||
|
||||
internal fun deleteAddon(context: Context, target: WowAddons.Target, folder: String, link: CurseLink? = CurseLink.live()) {
|
||||
val managed = link?.let { runCatching { it.uninstall(context, target, folder) }.getOrDefault(false) } == true
|
||||
val left = WowAddons.folder(target.addOns, folder)
|
||||
if (managed || left == null) WowAddons.changed() else WowAddons.delete(target, left.name)
|
||||
}
|
||||
|
||||
private fun installKey(addon: WowAddonCatalog.Addon, target: WowAddons.Target) = addon.id + "|" + target.addOns.path
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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) }
|
||||
|
||||
@@ -33,9 +33,7 @@ import androidx.compose.ui.graphics.drawscope.translate
|
||||
import androidx.compose.ui.graphics.lerp
|
||||
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.layout.onGloballyPositioned
|
||||
import androidx.compose.ui.layout.onSizeChanged
|
||||
import androidx.compose.ui.layout.positionInRoot
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.platform.LocalHapticFeedback
|
||||
import androidx.compose.ui.unit.dp
|
||||
@@ -49,30 +47,21 @@ import kotlin.math.sin
|
||||
|
||||
@Composable
|
||||
internal fun EmptyLibrary(avoid: Rect?, wall: (@Composable () -> Unit)? = null, fade: @Composable () -> Unit) {
|
||||
var origin by remember { mutableStateOf(Offset.Zero) }
|
||||
val clock = rememberMarkClock(avoid?.translate(-origin.x, -origin.y))
|
||||
Box(
|
||||
Modifier.fillMaxSize()
|
||||
.onGloballyPositioned { origin = it.positionInRoot() }
|
||||
.onSizeChanged { clock.page = Size(it.width.toFloat(), it.height.toFloat()) },
|
||||
) {
|
||||
val clock = rememberMarkClock(avoid)
|
||||
Box(Modifier.fillMaxSize().onSizeChanged { clock.page = Size(it.width.toFloat(), it.height.toFloat()) }) {
|
||||
if (wall != null) wall() else EmptyWall(clock)
|
||||
fade()
|
||||
Mark(clock)
|
||||
}
|
||||
}
|
||||
|
||||
private const val TRACE_MS = 1250f
|
||||
private const val FILL_FROM = 450f
|
||||
private const val POP_FROM = 900f
|
||||
private const val IMPACT = 2200f
|
||||
private const val RIPPLE_MS = 1250f
|
||||
private const val HIT_MS = 900f
|
||||
private const val END = 3600f
|
||||
private const val REVEAL_MS = 2300f
|
||||
private const val TRACE_DRAW_MS = 900f
|
||||
private const val TRACE_FADE_MS = 500f
|
||||
private const val REVEAL_FILL_FROM = 600f
|
||||
private const val REVEAL_FILL_MS = 450f
|
||||
private const val REVEAL_FADE_FROM = 1700f
|
||||
private const val POKE = 880f
|
||||
private const val DRIFT_MS = 75_000f
|
||||
|
||||
@@ -93,7 +82,8 @@ private fun rememberMarkClock(avoid: Rect?): MarkClock {
|
||||
val haptics = LocalHapticFeedback.current
|
||||
val keepOff by rememberUpdatedState(avoid)
|
||||
val speed = with(LocalDensity.current) { 64.dp.toPx() }
|
||||
val clearance = with(LocalDensity.current) { 4.dp.toPx() }
|
||||
val inset = with(LocalDensity.current) { 10.dp.toPx() }
|
||||
val clearance = with(LocalDensity.current) { 16.dp.toPx() }
|
||||
LaunchedEffect(clock) {
|
||||
var last = -1L
|
||||
var vx = speed * 0.8f
|
||||
@@ -119,28 +109,16 @@ private fun rememberMarkClock(avoid: Rect?): MarkClock {
|
||||
|
||||
var x = clock.at.x + vx * dt / 1000f
|
||||
var y = clock.at.y + vy * dt / 1000f
|
||||
val hw = f.ball
|
||||
val hh = f.ball
|
||||
if (x - hw < 0f) { x = hw; vx = abs(vx) }
|
||||
if (x + hw > clock.page.width) { x = clock.page.width - hw; vx = -abs(vx) }
|
||||
if (y - hh < 0f) { y = hh; vy = abs(vy) }
|
||||
if (y + hh > clock.page.height) { y = clock.page.height - hh; vy = -abs(vy) }
|
||||
val hw = f.halfWidth
|
||||
val hh = f.halfHeight
|
||||
if (x - hw < inset) { x = inset + hw; vx = abs(vx) }
|
||||
if (x + hw > clock.page.width - inset) { x = clock.page.width - inset - hw; vx = -abs(vx) }
|
||||
if (y - hh < inset) { y = inset + hh; vy = abs(vy) }
|
||||
if (y + hh > clock.page.height - inset) { y = clock.page.height - inset - hh; vy = -abs(vy) }
|
||||
keepOff?.inflate(clearance)?.let { r ->
|
||||
val nearX = x.coerceIn(r.left, r.right)
|
||||
val nearY = y.coerceIn(r.top, r.bottom)
|
||||
val gapX = x - nearX
|
||||
val gapY = y - nearY
|
||||
val gap = hypot(gapX, gapY)
|
||||
if (gap in 0.0001f..f.ball) {
|
||||
val nx = gapX / gap
|
||||
val ny = gapY / gap
|
||||
x = nearX + nx * f.ball
|
||||
y = nearY + ny * f.ball
|
||||
val into = vx * nx + vy * ny
|
||||
if (into < 0f) { vx -= 2f * into * nx; vy -= 2f * into * ny }
|
||||
} else if (gap <= 0.0001f) {
|
||||
val outX = if (x < r.center.x) r.left - f.ball - x else r.right + f.ball - x
|
||||
val outY = if (y < r.center.y) r.top - f.ball - y else r.bottom + f.ball - y
|
||||
if (x + hw > r.left && x - hw < r.right && y + hh > r.top && y - hh < r.bottom) {
|
||||
val outX = if (x < r.center.x) r.left - (x + hw) else r.right - (x - hw)
|
||||
val outY = if (y < r.center.y) r.top - (y + hh) else r.bottom - (y - hh)
|
||||
if (abs(outX) < abs(outY)) { x += outX; vx = if (outX < 0) -abs(vx) else abs(vx) }
|
||||
else { y += outY; vy = if (outY < 0) -abs(vy) else abs(vy) }
|
||||
}
|
||||
@@ -316,33 +294,30 @@ private fun Mark(clock: MarkClock) {
|
||||
} else 0f
|
||||
|
||||
translate(0f, shake) {
|
||||
val since = t - IMPACT
|
||||
if (since in 0f..REVEAL_MS) {
|
||||
val fade = 1f - clamp01((since - REVEAL_FADE_FROM) / (REVEAL_MS - REVEAL_FADE_FROM))
|
||||
val fill = Out.transform(clamp01((since - REVEAL_FILL_FROM) / REVEAL_FILL_MS)) * fade
|
||||
if (fill > 0f) {
|
||||
val lift = 8f * k * (1f - fill / fade)
|
||||
val edge = 5f * f.s
|
||||
LogoShape.left(left, 0f) { x, y -> f.px(x, y) + Offset(0f, lift + edge) }
|
||||
LogoShape.right(right) { x, y -> f.px(x, y) + Offset(0f, lift + edge) }
|
||||
drawPath(left, slabEdge.copy(alpha = fill))
|
||||
drawPath(right, slabEdge.copy(alpha = fill))
|
||||
LogoShape.left(left, 0f) { x, y -> f.px(x, y) + Offset(0f, lift) }
|
||||
LogoShape.right(right) { x, y -> f.px(x, y) + Offset(0f, lift) }
|
||||
drawPath(left, ink.copy(alpha = fill))
|
||||
drawPath(right, ink.copy(alpha = fill))
|
||||
}
|
||||
val drawn = TraceEase.transform(clamp01(since / TRACE_DRAW_MS))
|
||||
val alpha = (if (since < TRACE_DRAW_MS) 1f else 1f - (since - TRACE_DRAW_MS) / TRACE_FADE_MS).coerceIn(0f, 1f) * fade
|
||||
if (alpha > 0f) {
|
||||
LogoShape.left(left, 0f, f::px)
|
||||
LogoShape.right(right, f::px)
|
||||
for (half in listOf(left, right)) {
|
||||
measure.setPath(half, false)
|
||||
piece.reset()
|
||||
measure.getSegment(0f, measure.length * drawn, piece, true)
|
||||
drawPath(piece, pal.signal.copy(alpha = alpha), style = Stroke(3f * f.s))
|
||||
}
|
||||
val fill = Out.transform(clamp01((intro - FILL_FROM) / 450f))
|
||||
if (fill > 0f) {
|
||||
val lift = 8f * k * (1f - fill)
|
||||
val edge = 5f * f.s
|
||||
LogoShape.left(left, 0f) { x, y -> f.px(x, y) + Offset(0f, lift + edge) }
|
||||
LogoShape.right(right) { x, y -> f.px(x, y) + Offset(0f, lift + edge) }
|
||||
drawPath(left, slabEdge.copy(alpha = fill))
|
||||
drawPath(right, slabEdge.copy(alpha = fill))
|
||||
LogoShape.left(left, 0f) { x, y -> f.px(x, y) + Offset(0f, lift) }
|
||||
LogoShape.right(right) { x, y -> f.px(x, y) + Offset(0f, lift) }
|
||||
drawPath(left, ink.copy(alpha = fill))
|
||||
drawPath(right, ink.copy(alpha = fill))
|
||||
}
|
||||
|
||||
if (intro < TRACE_MS) {
|
||||
val drawn = TraceEase.transform(clamp01(intro / 775f))
|
||||
val alpha = if (intro < 775f) 1f else 1f - (intro - 775f) / 475f
|
||||
LogoShape.left(left, 0f, f::px)
|
||||
LogoShape.right(right, f::px)
|
||||
for (half in listOf(left, right)) {
|
||||
measure.setPath(half, false)
|
||||
piece.reset()
|
||||
measure.getSegment(0f, measure.length * drawn, piece, true)
|
||||
drawPath(piece, pal.signal.copy(alpha = alpha), style = Stroke(2f * f.s))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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, s.sessionRunning, 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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1047,11 +962,9 @@ private fun SavesTab(g: Library.SteamGame, prefix: File, a: FrontEndActions) {
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AddonsTab(g: Library.SteamGame, targets: List<WowAddons.Target>, sessionRunning: Boolean, a: FrontEndActions) {
|
||||
private fun AddonsTab(g: Library.SteamGame, targets: List<WowAddons.Target>, a: FrontEndActions) {
|
||||
var browsing by remember(g.gameId) { mutableStateOf<WowAddons.Target?>(null) }
|
||||
val curseForge = CurseForgeApp.find(UserAppsState.items)
|
||||
val link = rememberCurseLink(curseForge, sessionRunning)
|
||||
browsing?.let { AddonBrowserDialog(targets, it, curseForge, link) { browsing = null } }
|
||||
browsing?.let { AddonBrowserDialog(targets, it) { browsing = null } }
|
||||
Column(Modifier.fillMaxWidth().tabPanel(), verticalArrangement = Arrangement.spacedBy(2.dp)) {
|
||||
CurseForgeEntry(a)
|
||||
targets.forEach { target ->
|
||||
@@ -1062,12 +975,6 @@ private fun AddonsTab(g: Library.SteamGame, targets: List<WowAddons.Target>, ses
|
||||
val updates by produceState(emptyMap<String, WowAddonCatalog.Addon>(), names) {
|
||||
value = withContext(Dispatchers.IO) { WowAddonCatalog.updates(context, names, target) }
|
||||
}
|
||||
val scanKey = link?.generation to WowAddons.imports
|
||||
val managed by produceState(emptyMap<String, CurseForgeApp.Project>(), link, target.addOns, scanKey) {
|
||||
value = if (link == null) emptyMap() else withContext(Dispatchers.IO) {
|
||||
runCatching { CurseForgeApp.byFolder(link.installed(context, target, scanKey)) }.getOrDefault(emptyMap())
|
||||
}
|
||||
}
|
||||
if (targets.size > 1) SectionLabel(target.flavor)
|
||||
MenuItem(stringResource(R.string.addons_download), checked = false) { browsing = target }
|
||||
MenuItem(
|
||||
@@ -1078,7 +985,7 @@ private fun AddonsTab(g: Library.SteamGame, targets: List<WowAddons.Target>, ses
|
||||
target.addOns.mkdirs()
|
||||
a.onBrowseFiles(target.addOns)
|
||||
}
|
||||
names.forEach { item -> key(target.addOns, item.name) { AddonRow(item, updates[item.name], target, a, link?.let { l -> managed[item.name.lowercase()]?.let { it to l } }) } }
|
||||
names.forEach { item -> key(target.addOns, item.name) { AddonRow(item, updates[item.name], target, a) } }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1132,10 +1039,8 @@ private fun CurseForgeEntry(a: FrontEndActions) {
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun AddonRow(item: WowAddons.Installed, wowiUpdate: WowAddonCatalog.Addon?, target: WowAddons.Target, a: FrontEndActions, curse: Pair<CurseForgeApp.Project, CurseLink>? = null) {
|
||||
private fun AddonRow(item: WowAddons.Installed, update: WowAddonCatalog.Addon?, target: WowAddons.Target, a: FrontEndActions) {
|
||||
val name = item.name
|
||||
val update = wowiUpdate.takeIf { curse == null }
|
||||
val outdated = update != null || curse?.first?.update == true
|
||||
var asking by remember(target.addOns, name) { mutableStateOf(false) }
|
||||
var progress by remember(target.addOns, name) { mutableStateOf<Int?>(null) }
|
||||
val context = LocalContext.current
|
||||
@@ -1145,33 +1050,26 @@ internal fun AddonRow(item: WowAddons.Installed, wowiUpdate: WowAddonCatalog.Add
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(start = 16.dp, top = 2.dp, bottom = 2.dp)) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(name, fontSize = 14.sp, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
val detail = listOfNotNull(item.version, if (outdated) stringResource(R.string.upd_available) else null).joinToString(" · ")
|
||||
val detail = listOfNotNull(item.version, update?.let { stringResource(R.string.upd_available) }).joinToString(" · ")
|
||||
if (detail.isNotEmpty()) Text(
|
||||
progress?.let { stringResource(R.string.ctrl_percent, it) } ?: detail, fontSize = 12.sp,
|
||||
color = if (outdated) LocalPalette.current.signal else colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
|
||||
color = if (update != null) LocalPalette.current.signal else colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
if (outdated && !SessionState.running) IconAction(Icons.Outlined.Download, stringResource(R.string.common_update), "addon:update:${target.flavor}:$name", enabled = progress == null) {
|
||||
if (update != null && !SessionState.running) IconAction(Icons.Outlined.Download, stringResource(R.string.common_update), "addon:update:${target.flavor}:$name", enabled = progress == null) {
|
||||
progress = 0
|
||||
scope.launch {
|
||||
val message = withContext(Dispatchers.IO) {
|
||||
if (curse != null) {
|
||||
val (project, link) = curse
|
||||
val done = runCatching { link.call(context, target) { CurseForgeApp.update(context, it.inspector, it.guid, project.id) } }.getOrDefault(false)
|
||||
WowAddons.changed()
|
||||
if (done) context.getString(R.string.user_apps_updated, name) else context.getString(R.string.stores_dl_failed_reason, name)
|
||||
} else update?.let { installAddon(context, it, target) { pct -> scope.launch { progress = pct } }.first }
|
||||
}
|
||||
val message = withContext(Dispatchers.IO) { installAddon(context, update, target) { pct -> scope.launch { progress = pct } } }
|
||||
progress = null
|
||||
if (message != null) android.widget.Toast.makeText(context, message, android.widget.Toast.LENGTH_LONG).show()
|
||||
android.widget.Toast.makeText(context, message.first, android.widget.Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}
|
||||
if (!SessionState.running) IconAction(Icons.Outlined.Delete, if (curse != null) stringResource(R.string.common_uninstall) else delete, "addon:delete:${target.flavor}:$name", danger = true) { asking = true }
|
||||
if (!SessionState.running) IconAction(Icons.Outlined.Delete, delete, "addon:delete:${target.flavor}:$name", danger = true) { asking = true }
|
||||
}
|
||||
if (asking) ConfirmDialog(
|
||||
title = if (curse != null) stringResource(R.string.stores_uninstall_title, name) else stringResource(R.string.games_delete_addon_title, name),
|
||||
title = stringResource(R.string.games_delete_addon_title, name),
|
||||
text = stringResource(R.string.games_delete_addon_body),
|
||||
confirm = if (curse != null) stringResource(R.string.common_uninstall) else delete,
|
||||
confirm = delete,
|
||||
onConfirm = { a.onAddonDelete(target, name) },
|
||||
onDismiss = { asking = false },
|
||||
)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -189,7 +189,6 @@ internal fun LiftHero(
|
||||
onOpenChange: (Boolean) -> Unit = {},
|
||||
start: Dp = 44.dp,
|
||||
bottom: Dp = 44.dp,
|
||||
onTextBounds: (Rect) -> Unit = {},
|
||||
drop: DropSheetState? = null,
|
||||
overlay: @Composable BoxWithConstraintsScope.(lifted: () -> Float) -> Unit = {},
|
||||
) {
|
||||
@@ -574,7 +573,7 @@ internal fun LiftHero(
|
||||
}
|
||||
}
|
||||
|
||||
Column(Modifier.align(Alignment.BottomStart).padding(start = start, bottom = bottom, end = 20.dp).onGloballyPositioned { onTextBounds(it.boundsInRoot()) }) {
|
||||
Column(Modifier.align(Alignment.BottomStart).padding(start = start, bottom = bottom, end = 20.dp)) {
|
||||
Box(Modifier.graphicsLayer { alpha = 1f - wallSink() }) { words() }
|
||||
Spacer(Modifier.height(18.dp))
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
|
||||
@@ -140,7 +140,6 @@ internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier)
|
||||
onOpen = a.onSteamSettings, onPrimary = a.onPlay,
|
||||
modifier = modifier.clipToBounds(),
|
||||
start = if (narrow) 20.dp else 44.dp, bottom = 44.dp,
|
||||
onTextBounds = { words = it },
|
||||
background = {
|
||||
when {
|
||||
games.isEmpty() -> EmptyLibrary(
|
||||
@@ -161,12 +160,13 @@ internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier)
|
||||
IntegrationSuggestion(s.integration, { a.onSteamIntegration(null) }, a.onDismissIntegration)
|
||||
}
|
||||
if (narrow) Column(
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp), modifier = Modifier.onPlaced { words = it.boundsInParent() },
|
||||
) {
|
||||
Wordmark(30.dp)
|
||||
runtimeStatus()
|
||||
} else Row(
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
modifier = Modifier.onPlaced { words = it.boundsInParent() },
|
||||
) {
|
||||
Wordmark(if (narrow) 30.dp else 40.dp)
|
||||
runtimeStatus()
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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">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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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,570 +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.After
|
||||
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 original = CurseForgeApp.guest
|
||||
private val url = "ws://127.0.0.1:43117/0f8fad5b-d9cb-469f-a165-70867728950e"
|
||||
private val app = UserApps.App("appimage:c", UserApps.Kind.APPIMAGE, "CurseForge", null, null, AppImageManager.LAUNCHER, listOf("/root/apps/curseforge"), feed = CurseForgeApp.FEED)
|
||||
|
||||
@After
|
||||
fun restoreGuest() {
|
||||
val context = org.robolectric.RuntimeEnvironment.getApplication()
|
||||
launches.forEach { CurseForgeApp.stop(context, app, null, it) }
|
||||
holder.get()?.set(true)
|
||||
CurseForgeApp.guest = original
|
||||
}
|
||||
|
||||
private val launches = mutableListOf<java.util.concurrent.atomic.AtomicBoolean>()
|
||||
|
||||
private fun launch(): java.util.concurrent.atomic.AtomicBoolean = java.util.concurrent.atomic.AtomicBoolean(false).also { launches += it }
|
||||
|
||||
private val holder = java.util.concurrent.atomic.AtomicReference<java.util.concurrent.atomic.AtomicBoolean?>()
|
||||
private val released = java.util.concurrent.CountDownLatch(1)
|
||||
|
||||
private fun fakeGuest(startExit: Int, ready: Boolean = true): MutableList<List<String>> {
|
||||
val calls = java.util.Collections.synchronizedList(mutableListOf<List<String>>())
|
||||
CurseForgeApp.guest = { _, argv, cancelled, onLine ->
|
||||
calls += argv
|
||||
when {
|
||||
argv[0] == CurseForgeApp.HELPER && argv[1] == "start" -> {
|
||||
if (startExit == 0) {
|
||||
holder.set(cancelled)
|
||||
onLine(url)
|
||||
while (cancelled?.get() != true) Thread.sleep(10)
|
||||
released.countDown()
|
||||
} else onLine("busy")
|
||||
startExit
|
||||
}
|
||||
argv[0] == CurseForgeApp.HELPER -> 0
|
||||
ready -> { onLine(JSONObject().put("ok", true).put("value", """{"value":true}""").toString()); 0 }
|
||||
else -> { onLine(JSONObject().put("ok", false).put("error", JSONObject().put("code", "DEVTOOLS_UNREACHABLE").put("message", "no")).toString()); 0 }
|
||||
}
|
||||
}
|
||||
return calls
|
||||
}
|
||||
|
||||
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 installedProjectsAndExitCodes() {
|
||||
val projects = CurseForgeApp.parseProjects(JSONArray("""[
|
||||
{"id":"486246","installedModId":"a_486246","status":3,"locked":false,"folders":["RXPGuides","RXPGuides_Extra"]},
|
||||
{"id":"2","installedModId":"b_2","status":2,"locked":true,"folders":[]},
|
||||
{"id":null}]"""))
|
||||
assertEquals(listOf("486246", "2"), projects.map { it.id })
|
||||
assertEquals("486246", CurseForgeApp.owner(projects, "RXPGuides_Extra")?.id)
|
||||
assertNull(CurseForgeApp.owner(projects, "TomTom"))
|
||||
assertFalse(projects[1].update)
|
||||
assertTrue(CurseForgeApp.parseProjects(JSONObject()).isEmpty())
|
||||
assertEquals(CurseForgeApp.Start.READY, CurseForgeApp.startState(0))
|
||||
assertEquals(CurseForgeApp.Start.BUSY, CurseForgeApp.startState(3))
|
||||
assertEquals(CurseForgeApp.Start.FAILED, 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))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theAppStartsInTheGuestWithoutASessionAndIsAskedThroughItsInspector() {
|
||||
val calls = fakeGuest(0)
|
||||
val started = CurseForgeApp.start(org.robolectric.RuntimeEnvironment.getApplication(), app, launch())
|
||||
assertEquals(CurseForgeApp.Start.READY, started.state)
|
||||
assertEquals(url, started.inspector)
|
||||
assertEquals(listOf(CurseForgeApp.HELPER, "start", "/root/apps/curseforge"), calls.first())
|
||||
val probe = calls[1]
|
||||
assertEquals(listOf(CurseForgeApp.AGENT, "--cdp-inspector", url), probe.take(3))
|
||||
assertEquals("10.0", probe[3])
|
||||
assertTrue(probe[4].contains("InstalledProjectsAppService"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theLaunchLivesUntilItIsStopped() {
|
||||
fakeGuest(0)
|
||||
val context = org.robolectric.RuntimeEnvironment.getApplication()
|
||||
val hold = launch()
|
||||
assertEquals(CurseForgeApp.Start.READY, CurseForgeApp.start(context, app, hold).state)
|
||||
assertEquals(false, holder.get()?.get())
|
||||
assertEquals(1L, released.count)
|
||||
CurseForgeApp.stop(context, app, url, hold)
|
||||
assertTrue(released.await(5, java.util.concurrent.TimeUnit.SECONDS))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anAppThatIsAlreadyOpenIsNeitherUsedNorStopped() {
|
||||
val calls = fakeGuest(3)
|
||||
assertEquals(CurseForgeApp.Start.BUSY, CurseForgeApp.start(org.robolectric.RuntimeEnvironment.getApplication(), app, launch()).state)
|
||||
assertEquals(listOf(listOf(CurseForgeApp.HELPER, "start", "/root/apps/curseforge")), calls)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun stoppingAsksTheAppToQuitThenStopsItsHeadlessLaunchOnce() {
|
||||
val calls = fakeGuest(0)
|
||||
val context = org.robolectric.RuntimeEnvironment.getApplication()
|
||||
val hold = launch()
|
||||
CurseForgeApp.start(context, app, hold)
|
||||
calls.clear()
|
||||
CurseForgeApp.stop(context, app, url, hold)
|
||||
assertEquals(CurseForgeApp.AGENT, calls[0][0])
|
||||
assertTrue(calls[0][4].contains("shutdown"))
|
||||
assertEquals(listOf(CurseForgeApp.HELPER, "stop", "/root/apps/curseforge"), calls[1])
|
||||
assertTrue(hold.get())
|
||||
calls.clear()
|
||||
CurseForgeApp.stop(context, app, url, hold)
|
||||
assertTrue(calls.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aLateStopLeavesTheNewerLaunchRunning() {
|
||||
val calls = fakeGuest(0)
|
||||
val context = org.robolectric.RuntimeEnvironment.getApplication()
|
||||
val old = launch()
|
||||
val newer = launch()
|
||||
CurseForgeApp.start(context, app, old)
|
||||
CurseForgeApp.start(context, app, newer)
|
||||
assertTrue(old.get())
|
||||
calls.clear()
|
||||
CurseForgeApp.stop(context, app, url, old)
|
||||
assertTrue(calls.isEmpty())
|
||||
assertEquals(false, newer.get())
|
||||
CurseForgeApp.stop(context, app, null, newer)
|
||||
assertEquals(listOf(listOf(CurseForgeApp.HELPER, "stop", "/root/apps/curseforge")), calls)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aStoppedLaunchNeverStarts() {
|
||||
val calls = fakeGuest(0)
|
||||
val hold = launch().apply { set(true) }
|
||||
assertEquals(CurseForgeApp.Start.FAILED, CurseForgeApp.start(org.robolectric.RuntimeEnvironment.getApplication(), app, hold).state)
|
||||
assertTrue(calls.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anAppWithoutADirectoryIsNeverLaunched() {
|
||||
val calls = fakeGuest(0)
|
||||
val bare = UserApps.App("appimage:d", UserApps.Kind.APPIMAGE, "CurseForge", null, null, AppImageManager.LAUNCHER, emptyList(), feed = CurseForgeApp.FEED)
|
||||
val hold = launch()
|
||||
assertEquals(CurseForgeApp.Start.FAILED, CurseForgeApp.start(org.robolectric.RuntimeEnvironment.getApplication(), bare, hold).state)
|
||||
CurseForgeApp.stop(org.robolectric.RuntimeEnvironment.getApplication(), bare, url, hold)
|
||||
assertTrue(calls.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theInspectorUrlIsRedactedFromCommandLogs() {
|
||||
val line = CurseForgeApp.evalArgv(url, "x", 1_000).joinToString(" ")
|
||||
assertTrue(line.contains(url))
|
||||
assertTrue(!GuestCommand.redacted(line, CurseForgeApp.INSPECTOR).contains("127.0.0.1"))
|
||||
assertTrue(!GuestCommand.redacted(url, CurseForgeApp.INSPECTOR).contains(url))
|
||||
}
|
||||
|
||||
private class Curse(val addOns: File, val flavor: String = "") {
|
||||
val projects = java.util.concurrent.CopyOnWriteArrayList<JSONObject>()
|
||||
val methods = java.util.Collections.synchronizedList(mutableListOf<String>())
|
||||
@Volatile var unreachableAfterDelete = false
|
||||
@Volatile var unreachable = false
|
||||
|
||||
fun add(id: String, folder: String, status: Int) = add(id, listOf(folder), status)
|
||||
|
||||
fun add(id: String, folders: List<String>, status: Int, onDisk: List<String> = folders) {
|
||||
onDisk.forEach { File(addOns, it).mkdirs() }
|
||||
projects += JSONObject().put("id", id).put("installedModId", "m_$id").put("status", status).put("locked", false).put("folders", JSONArray(folders))
|
||||
}
|
||||
|
||||
private fun folders(p: JSONObject) = (0 until p.getJSONArray("folders").length()).map { p.getJSONArray("folders").getString(it) }
|
||||
|
||||
fun answer(expression: String): Any? {
|
||||
val method = Regex("s\\[\\\\\"(\\w+)\\\\\"\\]").find(expression)?.groupValues?.get(1) ?: return true
|
||||
methods += method
|
||||
return when (method) {
|
||||
"scanGameInstance" -> {
|
||||
projects.removeAll { p -> !File(addOns, p.getJSONArray("folders").getString(0)).isDirectory }
|
||||
true
|
||||
}
|
||||
"getProjects" -> JSONArray(projects.map { JSONObject(it.toString()) })
|
||||
"updateMod" -> {
|
||||
projects.forEach { it.put("status", 1) }
|
||||
true
|
||||
}
|
||||
"detectGameFromPath" -> JSONObject().put("gameInstanceGuid", "g")
|
||||
"getGameInstances" -> JSONArray().put(JSONObject().put("guid", "g").put("installPath", flavor))
|
||||
"deleteMods" -> {
|
||||
projects.removeAll { p ->
|
||||
(p.getString("installedModId") in expression).also { gone ->
|
||||
if (gone) folders(p).forEach { name -> WowAddons.folder(addOns, name)?.deleteRecursively() }
|
||||
}
|
||||
}
|
||||
if (unreachableAfterDelete) unreachable = true
|
||||
JSONArray()
|
||||
}
|
||||
else -> true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun fakeCurse(addOns: File = temp.newFolder("AddOns"), flavor: String = "", calls: MutableList<List<String>> = mutableListOf()): Curse {
|
||||
val curse = Curse(addOns, flavor)
|
||||
CurseForgeApp.guest = { _, argv, cancelled, onLine ->
|
||||
calls += argv
|
||||
when {
|
||||
argv[0] == CurseForgeApp.HELPER && argv[1] == "start" -> {
|
||||
onLine(url)
|
||||
while (cancelled?.get() != true) Thread.sleep(10)
|
||||
0
|
||||
}
|
||||
argv[0] == CurseForgeApp.HELPER -> 0
|
||||
curse.unreachable -> {
|
||||
onLine(JSONObject().put("ok", false).put("error", JSONObject().put("code", "DEVTOOLS_UNREACHABLE").put("message", "gone")).toString())
|
||||
0
|
||||
}
|
||||
else -> {
|
||||
val value = JSONObject().put("value", curse.answer(argv[4]) ?: JSONObject.NULL)
|
||||
onLine(JSONObject().put("ok", true).put("value", value.toString()).toString())
|
||||
0
|
||||
}
|
||||
}
|
||||
}
|
||||
return curse
|
||||
}
|
||||
|
||||
private fun wow(): WowAddons.Target {
|
||||
val context = org.robolectric.RuntimeEnvironment.getApplication()
|
||||
val games = temp.newFolder("Games")
|
||||
val addOns = File(games, "World of Warcraft/_retail_/Interface/AddOns").apply { mkdirs() }
|
||||
com.droiddeck.launcher.session.SessionPrefs.setGameFolderBinds(context, listOf(games.absolutePath to "/root/Games"))
|
||||
return WowAddons.Target("_retail_", addOns)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anEntryCurseForgeStillListsShowsAsNotInstalledOnceItsFolderIsGone() {
|
||||
val curse = fakeCurse()
|
||||
val context = org.robolectric.RuntimeEnvironment.getApplication()
|
||||
curse.add("298842", "Leatrix_Maps", 1)
|
||||
curse.add("18808", "TomTom", 1)
|
||||
assertTrue(File(curse.addOns, "Leatrix_Maps").deleteRecursively())
|
||||
val listed = CurseForgeApp.projects(context, url, "g")
|
||||
assertEquals(listOf("298842", "18808"), listed.map { it.id })
|
||||
assertEquals(listOf("18808"), CurseForgeApp.onDisk(listed, curse.addOns).map { it.id })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aProjectWithAnyFolderMissingOrNoFoldersIsNotInstalled() {
|
||||
val addOns = temp.newFolder("Split")
|
||||
File(addOns, "DBM-Core").mkdirs()
|
||||
val split = CurseForgeApp.Project("3358", "m_3358", listOf("DBM-Core", "DBM-StatusBarTimers"), false)
|
||||
val bare = CurseForgeApp.Project("1", "m_1", emptyList(), false)
|
||||
assertTrue(CurseForgeApp.onDisk(listOf(split, bare), addOns).isEmpty())
|
||||
File(addOns, "DBM-StatusBarTimers").mkdirs()
|
||||
assertEquals(listOf("3358"), CurseForgeApp.onDisk(listOf(split, bare), addOns).map { it.id })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aDeleteWhileCurseForgeIsLinkedGoesThroughItsUninstall() {
|
||||
val context = org.robolectric.RuntimeEnvironment.getApplication()
|
||||
val target = wow()
|
||||
val curse = fakeCurse(target.addOns, "/root/Games/World of Warcraft/_retail_")
|
||||
curse.add("298842", "Leatrix_Maps", 1)
|
||||
curse.add("18808", "TomTom", 1)
|
||||
val link = com.droiddeck.launcher.ui.CurseLink(app)
|
||||
try {
|
||||
link.call(context, target) { CurseForgeApp.projects(context, it.inspector, it.guid) }
|
||||
assertTrue(com.droiddeck.launcher.ui.CurseLink.live() === link)
|
||||
com.droiddeck.launcher.ui.deleteAddon(context, target, "Leatrix_Maps")
|
||||
assertTrue("deleteMods" in curse.methods)
|
||||
assertFalse(File(target.addOns, "Leatrix_Maps").exists())
|
||||
assertEquals(listOf("18808"), CurseForgeApp.projects(context, url, "g").map { it.id })
|
||||
} finally {
|
||||
link.close(context)
|
||||
}
|
||||
assertNull(com.droiddeck.launcher.ui.CurseLink.live())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aDeleteWithoutALiveLinkRemovesTheFolderAtOnceWithoutStartingCurseForge() {
|
||||
val context = org.robolectric.RuntimeEnvironment.getApplication()
|
||||
val target = wow()
|
||||
val calls = java.util.Collections.synchronizedList(mutableListOf<List<String>>())
|
||||
val curse = fakeCurse(target.addOns, "/root/Games/World of Warcraft/_retail_", calls)
|
||||
curse.add("298842", "Leatrix_Maps", 1)
|
||||
assertNull(com.droiddeck.launcher.ui.CurseLink.live())
|
||||
com.droiddeck.launcher.ui.deleteAddon(context, target, "Leatrix_Maps")
|
||||
assertFalse(File(target.addOns, "Leatrix_Maps").exists())
|
||||
assertTrue(calls.isEmpty())
|
||||
assertTrue(CurseForgeApp.projects(context, url, "g", rescan = true).none { it.id == "298842" })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aLinkThatNeverStartedIsNotUsedToDelete() {
|
||||
val context = org.robolectric.RuntimeEnvironment.getApplication()
|
||||
val target = wow()
|
||||
val calls = java.util.Collections.synchronizedList(mutableListOf<List<String>>())
|
||||
val curse = fakeCurse(target.addOns, "/root/Games/World of Warcraft/_retail_", calls)
|
||||
curse.add("298842", "Leatrix_Maps", 1)
|
||||
com.droiddeck.launcher.ui.deleteAddon(context, target, "Leatrix_Maps", com.droiddeck.launcher.ui.CurseLink(app))
|
||||
assertFalse(File(target.addOns, "Leatrix_Maps").exists())
|
||||
assertTrue(calls.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anAddonWhoseFolderWasDeletedShowsAsNotInstalledAfterTheRescan() {
|
||||
val curse = fakeCurse()
|
||||
val context = org.robolectric.RuntimeEnvironment.getApplication()
|
||||
curse.add("298842", "Leatrix_Maps", 1)
|
||||
assertEquals(listOf("298842"), CurseForgeApp.projects(context, url, "g", rescan = true).map { it.id })
|
||||
assertTrue(File(curse.addOns, "Leatrix_Maps").deleteRecursively())
|
||||
assertTrue(CurseForgeApp.projects(context, url, "g").isNotEmpty())
|
||||
assertTrue(CurseForgeApp.projects(context, url, "g", rescan = true).isEmpty())
|
||||
assertTrue("scanGameInstance" in curse.methods)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aNewerFileShowsAsAnUpdateUntilCurseForgeUpdatesIt() {
|
||||
val curse = fakeCurse()
|
||||
val context = org.robolectric.RuntimeEnvironment.getApplication()
|
||||
curse.add("298842", "Leatrix_Maps", 2)
|
||||
curse.add("18808", "TomTom", 1)
|
||||
val before = CurseForgeApp.projects(context, url, "g", rescan = true).associate { it.id to it.update }
|
||||
assertEquals(mapOf("298842" to true, "18808" to false), before)
|
||||
assertTrue(CurseForgeApp.update(context, url, "g", "298842"))
|
||||
assertTrue("updateMod" in curse.methods)
|
||||
assertTrue(CurseForgeApp.projects(context, url, "g").none { it.update })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun uninstallingThroughCurseForgeClearsItsListAndTheFolder() {
|
||||
val curse = fakeCurse()
|
||||
val context = org.robolectric.RuntimeEnvironment.getApplication()
|
||||
curse.add("298842", "Leatrix_Maps", 1)
|
||||
curse.add("18808", "TomTom", 1)
|
||||
val project = CurseForgeApp.owner(CurseForgeApp.projects(context, url, "g"), "Leatrix_Maps")!!
|
||||
assertTrue(CurseForgeApp.uninstall(context, url, "g", project))
|
||||
assertEquals(listOf("18808"), CurseForgeApp.projects(context, url, "g").map { it.id })
|
||||
assertFalse(File(curse.addOns, "Leatrix_Maps").exists())
|
||||
assertTrue(File(curse.addOns, "TomTom").isDirectory)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anUninstallThatRemovedTheFolderBeforeCurseForgeWentAwayCountsAsDeleted() {
|
||||
val context = org.robolectric.RuntimeEnvironment.getApplication()
|
||||
val target = wow()
|
||||
val curse = fakeCurse(target.addOns, "/root/Games/World of Warcraft/_retail_")
|
||||
curse.add("298842", "Leatrix_Maps", 1)
|
||||
curse.unreachableAfterDelete = true
|
||||
val link = com.droiddeck.launcher.ui.CurseLink(app)
|
||||
try {
|
||||
link.call(context, target) { CurseForgeApp.projects(context, it.inspector, it.guid) }
|
||||
val before = WowAddons.imports
|
||||
com.droiddeck.launcher.ui.deleteAddon(context, target, "Leatrix_Maps")
|
||||
assertTrue("deleteMods" in curse.methods)
|
||||
assertFalse(File(target.addOns, "Leatrix_Maps").exists())
|
||||
assertTrue(WowAddons.imports > before)
|
||||
} finally {
|
||||
kotlinx.coroutines.runBlocking { link.close(context).join() }
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aLocalDeleteInAProjectWithAMissingFolderKeepsItsOtherFolders() {
|
||||
val context = org.robolectric.RuntimeEnvironment.getApplication()
|
||||
val target = wow()
|
||||
val curse = fakeCurse(target.addOns, "/root/Games/World of Warcraft/_retail_")
|
||||
curse.add("3358", listOf("DBM-Core", "DBM-GUI", "DBM-StatusBarTimers"), 1, onDisk = listOf("DBM-Core", "DBM-GUI"))
|
||||
curse.add("298842", "Leatrix_Maps", 1)
|
||||
val link = com.droiddeck.launcher.ui.CurseLink(app)
|
||||
try {
|
||||
link.call(context, target) { CurseForgeApp.projects(context, it.inspector, it.guid) }
|
||||
com.droiddeck.launcher.ui.deleteAddon(context, target, "DBM-Core")
|
||||
assertFalse("deleteMods" in curse.methods)
|
||||
assertFalse(File(target.addOns, "DBM-Core").exists())
|
||||
assertTrue(File(target.addOns, "DBM-GUI").isDirectory)
|
||||
com.droiddeck.launcher.ui.deleteAddon(context, target, "Leatrix_Maps")
|
||||
assertTrue("deleteMods" in curse.methods)
|
||||
assertFalse(File(target.addOns, "Leatrix_Maps").exists())
|
||||
} finally {
|
||||
kotlinx.coroutines.runBlocking { link.close(context).join() }
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun foldersMatchCurseForgesNamesWhateverTheirCase() {
|
||||
val context = org.robolectric.RuntimeEnvironment.getApplication()
|
||||
val target = wow()
|
||||
val curse = fakeCurse(target.addOns, "/root/Games/World of Warcraft/_retail_")
|
||||
curse.add("12345", listOf("Questie"), 1, onDisk = listOf("questie"))
|
||||
val listed = CurseForgeApp.projects(context, url, "g")
|
||||
assertEquals(listOf("12345"), CurseForgeApp.onDisk(listed, target.addOns).map { it.id })
|
||||
assertEquals("12345", CurseForgeApp.byFolder(listed)["questie"]?.id)
|
||||
assertEquals("questie", WowAddons.folder(target.addOns, "Questie")?.name)
|
||||
val link = com.droiddeck.launcher.ui.CurseLink(app)
|
||||
try {
|
||||
link.call(context, target) { CurseForgeApp.projects(context, it.inspector, it.guid) }
|
||||
com.droiddeck.launcher.ui.deleteAddon(context, target, "Questie")
|
||||
assertTrue("deleteMods" in curse.methods)
|
||||
assertNull(WowAddons.folder(target.addOns, "Questie"))
|
||||
} finally {
|
||||
kotlinx.coroutines.runBlocking { link.close(context).join() }
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aLocalDeleteFindsTheFolderWhateverItsCaseAndAnAbsentFolderIsAlreadyDeleted() {
|
||||
val context = org.robolectric.RuntimeEnvironment.getApplication()
|
||||
val target = wow()
|
||||
File(target.addOns, "questie").mkdirs()
|
||||
File(target.addOns, "TomTom").mkdirs()
|
||||
com.droiddeck.launcher.ui.deleteAddon(context, target, "Questie", null)
|
||||
assertNull(WowAddons.folder(target.addOns, "Questie"))
|
||||
assertTrue(File(target.addOns, "TomTom").isDirectory)
|
||||
val before = WowAddons.imports
|
||||
com.droiddeck.launcher.ui.deleteAddon(context, target, "Gone", null)
|
||||
assertTrue(WowAddons.imports > before)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theAgentAnswerIsTheLastJsonLine() {
|
||||
assertEquals("a", CurseForgeApp.lastJson(listOf("noise", """{"v":"a"}""", "== done"))?.getString("v"))
|
||||
assertNull(CurseForgeApp.lastJson(listOf("noise")))
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,7 @@ class WowAddonCatalogTest {
|
||||
private val context get() = RuntimeEnvironment.getApplication()
|
||||
|
||||
private val files = """[
|
||||
{"UID":"1","UICATID":"19","UIVersion":"1.0","UIDate":300,"UIName":"Bartender","UIAuthorName":"Nevcairiel","UIDownloadTotal":"500","UICompatibility":[{"version":"12.0.0","name":"Midnight"}],"UIIMG_Thumbs":["https://cdn.example/a.jpg"],"UIDir":["Bartender4"," Bartender4_Options "]},
|
||||
{"UID":"1","UICATID":"19","UIVersion":"1.0","UIDate":300,"UIName":"Bartender","UIAuthorName":"Nevcairiel","UIDownloadTotal":"500","UICompatibility":[{"version":"12.0.0","name":"Midnight"}],"UIIMG_Thumbs":["https://cdn.example/a.jpg"]},
|
||||
{"UID":"2","UICATID":"20","UIVersion":"2.0","UIDate":100,"UIName":"Zygor","UIAuthorName":"Kappa","UIDownloadTotal":"900","UICompatibility":[{"version":"1.15.7","name":"Classic"},{"version":"4.4.2","name":"Cataclysm Classic"}],"UIIMG_Thumbs":null},
|
||||
{"UID":"3","UICATID":"21","UIVersion":"3.0","UIDate":200,"UIName":"Alpha","UIAuthorName":"bartuser","UIDownloadTotal":"10","UIDownloadMonthly":"9","UICompatibility":null},
|
||||
{"UID":"4","UICATID":"19","UIVersion":"4.0","UIDate":400,"UIName":"TBCOnly","UIAuthorName":"x","UIDownloadTotal":"20","UIDownloadMonthly":"5","UICompatibility":[{"version":"2.5.4","name":"The Burning Crusade Classic"}]}
|
||||
@@ -44,12 +44,6 @@ class WowAddonCatalogTest {
|
||||
assertEquals("19", e[0].category)
|
||||
}
|
||||
|
||||
@Test fun fileListEntriesCarryTheirAddonFolders() {
|
||||
val e = WowAddonCatalog.parseWowiFiles(files)
|
||||
assertEquals(listOf("Bartender4", "Bartender4_Options"), e[0].addon.folders)
|
||||
assertEquals(emptyList<String>(), e[1].addon.folders)
|
||||
}
|
||||
|
||||
@Test fun versionsMapToFlavors() {
|
||||
assertEquals("_retail_", WowAddonCatalog.flavorOf("12.1.0"))
|
||||
assertEquals("_retail_", WowAddonCatalog.flavorOf("11.0.5"))
|
||||
@@ -204,32 +198,6 @@ us|1|aa|bb|cc||tpr/wow|h|s|t||1|12.1.0.65000|kk|wowf
|
||||
assertFalse(WowAddonCatalog.sameVersion("1.2.3", "1.2.4"))
|
||||
}
|
||||
|
||||
@Test fun versionsCompareNumericSegmentsFirst() {
|
||||
assertEquals(true, WowAddonCatalog.newer("v4.11.38-7-ge56e9d8", "4.11.39"))
|
||||
assertEquals(true, WowAddonCatalog.newer("1.9", "1.10"))
|
||||
assertEquals(true, WowAddonCatalog.newer("2", "2.0.1"))
|
||||
assertEquals(false, WowAddonCatalog.newer("11.2.0", "6.2.5"))
|
||||
assertEquals(false, WowAddonCatalog.newer("2.0", "2"))
|
||||
assertNull(WowAddonCatalog.newer("11.4.10-beta1", "11.4.10"))
|
||||
assertNull(WowAddonCatalog.newer("release", "1.0"))
|
||||
}
|
||||
|
||||
@Test fun anUpdateIsOfferedOnlyForANewerVersionOrTheSameSourcesCurrentFile() {
|
||||
assertTrue(WowAddonCatalog.offersUpdate("1.9", "1.10", sameSource = false))
|
||||
assertFalse(WowAddonCatalog.offersUpdate("11.2.0", "6.2.5", sameSource = true))
|
||||
assertFalse(WowAddonCatalog.offersUpdate("v1.2", "1.2", sameSource = true))
|
||||
assertTrue(WowAddonCatalog.offersUpdate("11.4.10-beta1", "11.4.10", sameSource = true))
|
||||
assertFalse(WowAddonCatalog.offersUpdate("11.4.10-beta1", "11.4.10", sameSource = false))
|
||||
assertFalse(WowAddonCatalog.offersUpdate(null, "1.0", sameSource = true))
|
||||
assertFalse(WowAddonCatalog.offersUpdate("1.0", "", sameSource = true))
|
||||
}
|
||||
|
||||
@Test fun findUpdatesNeverOffersADowngrade() {
|
||||
val installed = listOf(WowAddons.Installed("Ahead", "3.0", "10"), WowAddons.Installed("Tagged", "r55-alpha", "20"))
|
||||
val updates = WowAddonCatalog.findUpdates(listOf(entry("10", "2.9"), entry("20", "r56")), installed)
|
||||
assertEquals(setOf("Tagged"), updates.keys)
|
||||
}
|
||||
|
||||
@Test fun md5Check() {
|
||||
val f = File(context.cacheDir, "wowaddon-md5-test.zip")
|
||||
f.writeText("hello")
|
||||
|
||||
@@ -220,74 +220,24 @@ class WowAddonsTest {
|
||||
}
|
||||
|
||||
@Test fun tocFieldsReadVersionAndSourceIds() {
|
||||
val fields = WowAddons.tocFields("\uFEFF## Interface: 110002\n## Title: Foo\n## Version: 1.4.2\n## X-WoWI-ID: 1234\n## Version: 9\n## X-Curse-Project-ID: @curse-id@\nFoo.lua\n".lineSequence(), setOf("Version", "X-WoWI-ID", "X-Curse-Project-ID"))
|
||||
val fields = WowAddons.tocFields("\uFEFF## Interface: 110002\n## Title: Foo\n## Version: 1.4.2\n## X-WoWI-ID: 1234\n## Version: 9\n## X-Curse-Project-ID: @curse-id@\nFoo.lua\n")
|
||||
assertEquals("1.4.2", fields["Version"])
|
||||
assertEquals("1234", fields["X-WoWI-ID"])
|
||||
assertEquals(null, fields["X-Curse-Project-ID"])
|
||||
}
|
||||
|
||||
@Test fun tocFieldsKeepOnlyTheRequestedKeysAndStopOnceFound() {
|
||||
var read = 0
|
||||
val lines = sequence {
|
||||
yield("## Version: 2.0")
|
||||
yield("## X-WoWI-ID: 5")
|
||||
yield("## X-Curse-Project-ID: 9")
|
||||
repeat(100_000) { read++; yield("## X-Data-$it: payload") }
|
||||
}
|
||||
val fields = WowAddons.tocFields(lines)
|
||||
assertEquals(mapOf("Version" to "2.0", "X-WoWI-ID" to "5", "X-Curse-Project-ID" to "9"), fields)
|
||||
assertEquals(0, read)
|
||||
}
|
||||
|
||||
@Test fun detailsSkipDataRowsInLargeTocs() {
|
||||
val target = target()
|
||||
val db = File(target.addOns, "BigDB").apply { mkdirs() }
|
||||
File(db, "BigDB_Mists.toc").bufferedWriter().use { w ->
|
||||
w.write("## Title: BigDB\nsrc\\main.lua\n")
|
||||
repeat(50_000) { w.write("## X-Data-$it: ${"x".repeat(200)}\n") }
|
||||
w.write("## Version: 3.1\n")
|
||||
}
|
||||
val details = WowAddons.details(target).single()
|
||||
assertEquals("3.1", details.version)
|
||||
assertEquals(null, details.wowiId)
|
||||
}
|
||||
|
||||
@Test fun detailsUseTheTocAndTheRecordedSource() {
|
||||
val target = target()
|
||||
val foo = File(target.addOns, "Foo").apply { mkdirs() }
|
||||
File(foo, "Foo_Mainline.toc").writeText("## Version: 1.0\n## X-WoWI-ID: 77\n## X-Curse-Project-ID: 334372\n")
|
||||
File(foo, "Foo_Mainline.toc").writeText("## Version: 1.0\n## X-WoWI-ID: 77\n")
|
||||
File(target.addOns, "Bar").mkdirs()
|
||||
val details = WowAddons.details(target).associateBy { it.name }
|
||||
assertEquals(setOf("Bar", "Foo"), details.keys)
|
||||
assertEquals("1.0", details.getValue("Foo").version)
|
||||
assertEquals("77", details.getValue("Foo").wowiId)
|
||||
assertEquals("334372", details.getValue("Foo").curseId)
|
||||
assertEquals(null, details.getValue("Bar").curseId)
|
||||
assertEquals(null, details.getValue("Bar").version)
|
||||
}
|
||||
|
||||
@Test fun detailsFillFieldsTheMainTocLacksFromTheFlavourTocs() {
|
||||
val target = target()
|
||||
val questie = File(target.addOns, "Questie").apply { mkdirs() }
|
||||
File(questie, "Questie.toc").writeText("## Interface: 00000\n## Title: Questie\n")
|
||||
File(questie, "Questie_Vanilla.toc").writeText("## Version: 12.6.4\n## X-Curse-Project-ID: 334372\n")
|
||||
File(questie, "Questie_Wrath.toc").writeText("## Version: 12.6.4\n")
|
||||
val questieDetails = WowAddons.details(target).single()
|
||||
assertEquals("12.6.4", questieDetails.version)
|
||||
assertEquals("334372", questieDetails.curseId)
|
||||
}
|
||||
|
||||
@Test fun detailsKeepTheMainTocWhenItHasTheFields() {
|
||||
val target = target()
|
||||
val foo = File(target.addOns, "Foo").apply { mkdirs() }
|
||||
File(foo, "Foo.toc").writeText("## Version: 2.0\n## X-Curse-Project-ID: 5\n")
|
||||
File(foo, "Foo_Classic.toc").writeText("## Version: 1.0\n## X-Curse-Project-ID: 6\n## X-WoWI-ID: 7\n")
|
||||
val fooDetails = WowAddons.details(target).single()
|
||||
assertEquals("2.0", fooDetails.version)
|
||||
assertEquals("5", fooDetails.curseId)
|
||||
assertEquals("7", fooDetails.wowiId)
|
||||
}
|
||||
|
||||
@Test fun importRecordsTheSourceAndPlainImportsClearIt() {
|
||||
val target = target()
|
||||
WowAddons.import(zip("Foo/Foo.toc" to "## Version: 1.0\n"), target, WowAddons.Origin("55", "2.0"))
|
||||
|
||||
@@ -1,94 +0,0 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.test.assertCountEquals
|
||||
import androidx.compose.ui.test.onAllNodesWithText
|
||||
import androidx.compose.ui.test.onNodeWithText
|
||||
import androidx.compose.ui.test.performClick
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.runtime.WowAddonCatalog
|
||||
import com.droiddeck.launcher.runtime.WowAddons
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28], qualifiers = "w960dp-h540dp-land", application = android.app.Application::class)
|
||||
class AddonRowTest {
|
||||
@get:Rule val compose = createRobolectricComposeRule()
|
||||
|
||||
private val addon = WowAddonCatalog.Addon("298842", "Leatrix Maps", "Leatrix", "", 0, 0, null)
|
||||
private fun text(id: Int) = RuntimeEnvironment.getApplication().getString(id)
|
||||
|
||||
private fun show(status: AddonStatus, uninstalls: MutableList<String> = mutableListOf(), installs: MutableList<String> = mutableListOf()) {
|
||||
val state = mutableStateOf(status)
|
||||
compose.setContent {
|
||||
DroidDeckTheme {
|
||||
AddonRow(addon, state.value, null, Modifier, { uninstalls += addon.id }) { installs += addon.id }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun aMissingAddonOffersOnlyInstall() {
|
||||
val installs = mutableListOf<String>()
|
||||
show(AddonStatus.INSTALL, installs = installs)
|
||||
compose.onAllNodesWithText(text(R.string.common_uninstall)).assertCountEquals(0)
|
||||
compose.onAllNodesWithText(text(R.string.common_update)).assertCountEquals(0)
|
||||
compose.onNodeWithText(text(R.string.store_install)).performClick()
|
||||
assertEquals(listOf("298842"), installs)
|
||||
}
|
||||
|
||||
@Test fun aCurrentAddonOffersOnlyUninstallAfterAConfirm() {
|
||||
val uninstalls = mutableListOf<String>()
|
||||
show(AddonStatus.INSTALLED, uninstalls)
|
||||
compose.onAllNodesWithText(text(R.string.store_install)).assertCountEquals(0)
|
||||
compose.onAllNodesWithText(text(R.string.common_update)).assertCountEquals(0)
|
||||
compose.onAllNodesWithText(text(R.string.stores_installed_chip)).assertCountEquals(0)
|
||||
compose.onNodeWithText(text(R.string.common_uninstall)).performClick()
|
||||
assertEquals(emptyList<String>(), uninstalls)
|
||||
compose.onAllNodesWithText(text(R.string.common_uninstall))[1].performClick()
|
||||
assertEquals(listOf("298842"), uninstalls)
|
||||
}
|
||||
|
||||
@Test fun anOutdatedAddonOffersUpdateAndUninstall() {
|
||||
val installs = mutableListOf<String>()
|
||||
show(AddonStatus.UPDATE, installs = installs)
|
||||
compose.onAllNodesWithText(text(R.string.common_uninstall)).assertCountEquals(1)
|
||||
compose.onNodeWithText(text(R.string.common_update)).performClick()
|
||||
assertEquals(listOf("298842"), installs)
|
||||
}
|
||||
|
||||
private fun disk(vararg addons: WowAddons.Installed) = addons.associateBy { it.name.lowercase() }
|
||||
|
||||
@Test fun anotherSourcesAddonOnDiskIsUpdatableOnlyToANewerVersion() {
|
||||
val onDisk = disk(WowAddons.Installed("Questie", "11.2.0", null), WowAddons.Installed("QuestieDB", null, null))
|
||||
assertEquals(AddonStatus.INSTALLED, diskStatus(listOf("Questie"), onDisk, "6.2.5", "1"))
|
||||
assertEquals(AddonStatus.UPDATE, diskStatus(listOf("Questie"), onDisk, "11.3.0", "1"))
|
||||
assertEquals(AddonStatus.INSTALLED, diskStatus(listOf("Questie"), onDisk, "v11.2.0", "1"))
|
||||
assertEquals(AddonStatus.INSTALLED, diskStatus(listOf("QuestieDB"), onDisk, "1.0", "1"))
|
||||
}
|
||||
|
||||
@Test fun anIncomparableVersionIsAnUpdateOnlyFromTheSameSource() {
|
||||
val onDisk = disk(WowAddons.Installed("TomTom", "v4.0.1-release", "12"))
|
||||
assertEquals(AddonStatus.UPDATE, diskStatus(listOf("TomTom"), onDisk, "v4.0.1-beta", "12"))
|
||||
assertEquals(AddonStatus.INSTALLED, diskStatus(listOf("TomTom"), onDisk, "v4.0.1-beta", "99"))
|
||||
assertEquals(AddonStatus.INSTALLED, diskStatus(listOf("TomTom"), onDisk, "4.0.0", "12"))
|
||||
}
|
||||
|
||||
@Test fun foldersOnDiskMatchWhateverTheirCase() {
|
||||
val onDisk = disk(WowAddons.Installed("questie", "11.2.0", null))
|
||||
assertEquals(AddonStatus.INSTALLED, diskStatus(listOf("Questie"), onDisk, "11.2.0", "1"))
|
||||
}
|
||||
|
||||
@Test fun anAddonCountsAsInstalledOnlyWhenEveryFolderIsOnDisk() {
|
||||
val onDisk = disk(WowAddons.Installed("Bartender4", "4.19.2", null))
|
||||
assertEquals(AddonStatus.INSTALL, diskStatus(listOf("Bartender4", "Bartender4_Options"), onDisk, "4.19.2", "1"))
|
||||
assertEquals(AddonStatus.INSTALL, diskStatus(emptyList(), onDisk, "4.19.2", "1"))
|
||||
assertEquals(AddonStatus.INSTALL, diskStatus(listOf("TomTom"), onDisk, "4.4.1", "1"))
|
||||
}
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import com.droiddeck.launcher.runtime.CurseForgeApp
|
||||
import com.droiddeck.launcher.runtime.WowAddons
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
|
||||
class CurseLinkReportTest {
|
||||
@get:Rule val temp = TemporaryFolder()
|
||||
|
||||
private fun target(vararg folders: String): WowAddons.Target {
|
||||
val addOns = temp.newFolder("AddOns")
|
||||
folders.forEach { java.io.File(addOns, it).mkdirs() }
|
||||
return WowAddons.Target("_retail_", addOns)
|
||||
}
|
||||
|
||||
private fun project(id: String, vararg folders: String, update: Boolean = false) = CurseForgeApp.Project(id, "m$id", folders.toList(), update)
|
||||
|
||||
@Test fun beforeAnyReportNothingIsKnown() {
|
||||
assertEquals(emptyMap<String, String?>(), CurseLink.lastReported(target("Questie")))
|
||||
}
|
||||
|
||||
@Test fun beforeCurseForgeReportsAddonsWhoseFoldersAreAllOnDiskShowAsInstalled() {
|
||||
val target = target("questie", "QuestieDB", "Auctionator")
|
||||
CurseLink.report(target, listOf(
|
||||
project("334372", "Questie", "QuestieDB", update = true),
|
||||
project("1", "Auctionator"),
|
||||
project("2", "Details", "Details_Streamer"),
|
||||
project("3", "Auctionator", "Auctionator_Extra"),
|
||||
))
|
||||
assertEquals(mapOf<String, String?>("334372" to null, "1" to null), CurseLink.lastReported(target))
|
||||
}
|
||||
|
||||
@Test fun anAddonRemovedFromDiskSinceTheLastReportIsNotInstalled() {
|
||||
val target = target("Questie")
|
||||
CurseLink.report(target, listOf(project("334372", "Questie")))
|
||||
java.io.File(target.addOns, "Questie").delete()
|
||||
assertEquals(emptyMap<String, String?>(), CurseLink.lastReported(target))
|
||||
}
|
||||
|
||||
private fun toc(target: WowAddons.Target, folder: String, curseId: String) {
|
||||
val dir = java.io.File(target.addOns, folder).apply { mkdirs() }
|
||||
java.io.File(dir, "$folder.toc").writeText("## Interface: 110207\n## Title: $folder\n## X-Curse-Project-ID: $curseId\n$folder.lua\n")
|
||||
}
|
||||
|
||||
@Test fun beforeAnyReportAnAddonWhoseTocNamesTheProjectShowsAsInstalled() {
|
||||
val target = target()
|
||||
toc(target, "Questie", "334372")
|
||||
toc(target, "Auctionator", "@project-id@")
|
||||
assertEquals(mapOf<String, String?>("334372" to null), CurseLink.lastReported(target))
|
||||
}
|
||||
|
||||
@Test fun aPlaceholderProjectIdIsIgnored() {
|
||||
val target = target()
|
||||
toc(target, "Auctionator", "@project-id@")
|
||||
assertEquals(emptyMap<String, String?>(), CurseLink.lastReported(target))
|
||||
}
|
||||
|
||||
@Test fun curseForgesReportOverridesTheTocProjectId() {
|
||||
val target = target()
|
||||
toc(target, "Questie", "334372")
|
||||
toc(target, "Auctionator", "1")
|
||||
CurseLink.report(target, listOf(project("1", "Auctionator", update = true)))
|
||||
assertEquals(mapOf<String, String?>("1" to null), CurseLink.lastReported(target))
|
||||
}
|
||||
}
|
||||
@@ -1,253 +0,0 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.ui.test.assertCountEquals
|
||||
import androidx.compose.ui.test.onAllNodesWithContentDescription
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.runtime.AppImageManager
|
||||
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.SessionPrefs
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import kotlinx.coroutines.withTimeout
|
||||
import kotlinx.coroutines.withContext
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import org.junit.After
|
||||
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.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.LinkOption
|
||||
import java.util.Collections
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28], qualifiers = "w960dp-h540dp-land", application = android.app.Application::class)
|
||||
class CurseLinkTabTest {
|
||||
@get:Rule val compose = createRobolectricComposeRule()
|
||||
@get:Rule val temp = TemporaryFolder()
|
||||
|
||||
private val original = CurseForgeApp.guest
|
||||
private val url = "ws://127.0.0.1:43117/0f8fad5b-d9cb-469f-a165-70867728950e"
|
||||
private val app = UserApps.App("appimage:c", UserApps.Kind.APPIMAGE, "CurseForge", null, null, AppImageManager.LAUNCHER, listOf("/root/apps/curseforge"), feed = CurseForgeApp.FEED)
|
||||
private val helper = Collections.synchronizedList(mutableListOf<String>())
|
||||
private val methods = Collections.synchronizedList(mutableListOf<String>())
|
||||
private val context get() = RuntimeEnvironment.getApplication()
|
||||
|
||||
@After
|
||||
fun restore() {
|
||||
CurseForgeApp.guest = original
|
||||
}
|
||||
|
||||
private fun text(id: Int) = context.getString(id)
|
||||
|
||||
private fun wow(): WowAddons.Target {
|
||||
val games = temp.newFolder("Games")
|
||||
val addOns = File(games, "World of Warcraft/_retail_/Interface/AddOns").apply { mkdirs() }
|
||||
File(addOns, "Leatrix_Maps").mkdirs()
|
||||
SessionPrefs.setGameFolderBinds(context, listOf(games.absolutePath to "/root/Games"))
|
||||
CurseForgeApp.guest = { _, argv, cancelled, onLine ->
|
||||
if (argv[0] == CurseForgeApp.HELPER) {
|
||||
helper += argv[1]
|
||||
if (argv[1] == "start") {
|
||||
onLine(url)
|
||||
while (cancelled?.get() != true) Thread.sleep(10)
|
||||
}
|
||||
0
|
||||
} else {
|
||||
val method = Regex("s\\[\\\\\"(\\w+)\\\\\"\\]").find(argv[4])?.groupValues?.get(1)
|
||||
method?.let { methods += it }
|
||||
val answer: Any = when (method) {
|
||||
"detectGameFromPath" -> JSONObject().put("gameInstanceGuid", "g")
|
||||
"getGameInstances" -> JSONArray().put(JSONObject().put("guid", "g").put("installPath", "/root/Games/World of Warcraft/_retail_"))
|
||||
"getProjects" -> JSONArray().put(JSONObject().put("id", "298842").put("installedModId", "m").put("status", 1).put("locked", false).put("folders", JSONArray().put("Leatrix_Maps")))
|
||||
else -> true
|
||||
}
|
||||
onLine(JSONObject().put("ok", true).put("value", JSONObject().put("value", answer).toString()).toString())
|
||||
0
|
||||
}
|
||||
}
|
||||
return WowAddons.Target("_retail_", addOns)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theTabAndItsDialogShareOneCurseForgeThatStopsWhenTheTabLeaves() {
|
||||
val target = wow()
|
||||
val shown = mutableStateOf(true)
|
||||
val seen = Collections.synchronizedList(mutableListOf<List<String>>())
|
||||
var opened: CurseLink? = null
|
||||
compose.setContent {
|
||||
if (shown.value) {
|
||||
val link = rememberCurseLink(app, sessionRunning = false)
|
||||
opened = link
|
||||
LaunchedEffect(link) { withContext(Dispatchers.IO) { link?.let { seen += it.installed(context, target, 0).map { p -> p.id } } } }
|
||||
LaunchedEffect(link) { withContext(Dispatchers.IO) { link?.let { seen += it.installed(context, target, 0).map { p -> p.id } } } }
|
||||
}
|
||||
}
|
||||
compose.waitUntil(20_000) { seen.size == 2 }
|
||||
assertEquals(listOf(listOf("298842"), listOf("298842")), seen.toList())
|
||||
assertEquals(listOf("start"), helper.toList())
|
||||
assertEquals(1, methods.count { it == "scanGameInstance" })
|
||||
assertTrue(CurseLink.live() != null)
|
||||
compose.runOnIdle { shown.value = false }
|
||||
compose.waitForIdle()
|
||||
compose.waitUntil(20_000) { "stop" in helper }
|
||||
assertNull(CurseLink.live())
|
||||
assertTrue("shutdown" in methods)
|
||||
assertEquals(1, helper.count { it == "start" })
|
||||
runBlocking { withTimeout(20_000) { opened!!.stopped.join() } }
|
||||
compose.waitUntil(5_000) { Thread.getAllStackTraces().keys.none { it.isAlive && it.name.startsWith("curseforge") } }
|
||||
val calls = helper.size + methods.size
|
||||
Thread.sleep(1_500)
|
||||
assertEquals(calls, helper.size + methods.size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aNewGenerationRescansButReusesTheRunningCurseForge() {
|
||||
val target = wow()
|
||||
val link = CurseLink(app)
|
||||
try {
|
||||
link.installed(context, target, 0)
|
||||
link.installed(context, target, 0)
|
||||
link.refresh()
|
||||
link.installed(context, target, link.generation)
|
||||
assertEquals(2, methods.count { it == "scanGameInstance" })
|
||||
assertEquals(1, helper.count { it == "start" })
|
||||
} finally {
|
||||
runBlocking { link.close(context).join() }
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aFailedScanKeepsTheLastReportInsteadOfClearingIt() {
|
||||
val target = wow()
|
||||
val link = CurseLink(app)
|
||||
try {
|
||||
val reported = link.marks(context, target, 0)
|
||||
assertTrue(reported.isNotEmpty())
|
||||
runBlocking { link.close(context).join() }
|
||||
assertEquals(reported.mapValues { null }, link.marks(context, target, 1))
|
||||
} finally {
|
||||
runBlocking { link.close(context).join() }
|
||||
}
|
||||
}
|
||||
|
||||
private fun tocFolder(addOns: File, name: String, curseId: String) =
|
||||
File(addOns, name).apply { mkdirs(); File(this, "$name.toc").writeText("## X-Curse-Project-ID: $curseId\n") }
|
||||
|
||||
@Test
|
||||
fun anAddonTheManagerDoesNotListIsFoundByItsTocProjectId() {
|
||||
val target = WowAddons.Target("_retail_", temp.newFolder("AddOns"))
|
||||
tocFolder(target.addOns, "Questie", "334372")
|
||||
tocFolder(target.addOns, "Other", "1")
|
||||
assertEquals(listOf("Questie"), curseFolders(target, "334372", emptyList()))
|
||||
assertEquals(listOf("Listed"), curseFolders(target, "334372", listOf("Listed")))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun uninstallingByTocProjectIdDeletesOnlyTheMatchedFolders() {
|
||||
val target = WowAddons.Target("_retail_", temp.newFolder("AddOns"))
|
||||
tocFolder(target.addOns, "Questie", "334372")
|
||||
tocFolder(target.addOns, "Other", "1")
|
||||
deleteAddons(context, target, curseFolders(target, "334372", emptyList()), null)
|
||||
assertEquals(listOf("Other"), WowAddons.installed(target))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun uninstallingALinkedAddonLeavesTheLinkTargetAlone() {
|
||||
val target = WowAddons.Target("_retail_", temp.newFolder("AddOns"))
|
||||
val outside = tocFolder(temp.newFolder("outside"), "Questie", "334372")
|
||||
File(outside, "keep.lua").writeText("keep")
|
||||
Files.createSymbolicLink(File(target.addOns, "Questie").toPath(), outside.toPath())
|
||||
deleteAddons(context, target, curseFolders(target, "334372", emptyList()), null)
|
||||
assertFalse(Files.exists(File(target.addOns, "Questie").toPath(), LinkOption.NOFOLLOW_LINKS))
|
||||
assertEquals("keep", File(outside, "keep.lua").readText())
|
||||
assertTrue(File(outside, "Questie.toc").isFile)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun uninstallingWithNothingToDeleteFails() {
|
||||
val target = WowAddons.Target("_retail_", temp.newFolder("AddOns"))
|
||||
tocFolder(target.addOns, "Other", "1")
|
||||
assertThrows(IOException::class.java) { deleteAddons(context, target, curseFolders(target, "334372", emptyList()), null) }
|
||||
assertEquals(listOf("Other"), WowAddons.installed(target))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun noCurseForgeStartsWhileASessionRuns() {
|
||||
wow()
|
||||
var link: CurseLink? = CurseLink(app)
|
||||
compose.setContent { link = rememberCurseLink(app, sessionRunning = true) }
|
||||
compose.waitForIdle()
|
||||
assertNull(link)
|
||||
assertTrue(helper.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aStaleEntryWhoseFolderIsGoneIsNotManaged() {
|
||||
val target = wow()
|
||||
assertTrue(File(target.addOns, "Leatrix_Maps").deleteRecursively())
|
||||
val link = CurseLink(app)
|
||||
try {
|
||||
assertTrue(link.installed(context, target, 0).isEmpty())
|
||||
} finally {
|
||||
runBlocking { link.close(context).join() }
|
||||
}
|
||||
}
|
||||
|
||||
private val actions = FrontEndActions(
|
||||
onPlay = {}, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {},
|
||||
onRom = {}, onResume = {}, onSteamSettings = {}, onDesktopSettings = {},
|
||||
onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {},
|
||||
onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {},
|
||||
onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {},
|
||||
onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> },
|
||||
onSetPhantomProcessLimit = { _, _ -> },
|
||||
)
|
||||
|
||||
private fun row(update: Boolean?, wowi: Boolean) {
|
||||
val target = WowAddons.Target("_retail_", temp.newFolder("AddOns"))
|
||||
val item = WowAddons.Installed("Leatrix_Maps", "1.60.35", null)
|
||||
val newer = WowAddonCatalog.Addon("1", "Leatrix Maps", "Leatrix", "1.60.36", 0, 0, null).takeIf { wowi }
|
||||
val curse = update?.let { CurseForgeApp.Project("298842", "m", listOf("Leatrix_Maps"), it) to CurseLink(app) }
|
||||
compose.setContent { DroidDeckTheme { AddonRow(item, newer, target, actions, curse) } }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aManagedRowWithAnUpdateOffersUpdateAndUninstall() {
|
||||
row(update = true, wowi = false)
|
||||
compose.onAllNodesWithContentDescription(text(R.string.common_update)).assertCountEquals(1)
|
||||
compose.onAllNodesWithContentDescription(text(R.string.common_uninstall)).assertCountEquals(1)
|
||||
compose.onAllNodesWithContentDescription(text(R.string.common_delete)).assertCountEquals(0)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aCurrentManagedRowIgnoresOtherSourcesAndOffersOnlyUninstall() {
|
||||
row(update = false, wowi = true)
|
||||
compose.onAllNodesWithContentDescription(text(R.string.common_update)).assertCountEquals(0)
|
||||
compose.onAllNodesWithContentDescription(text(R.string.common_uninstall)).assertCountEquals(1)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anUnmanagedRowKeepsTheLocalUpdateAndDelete() {
|
||||
row(update = null, wowi = true)
|
||||
compose.onAllNodesWithContentDescription(text(R.string.common_update)).assertCountEquals(1)
|
||||
compose.onAllNodesWithContentDescription(text(R.string.common_delete)).assertCountEquals(1)
|
||||
compose.onAllNodesWithContentDescription(text(R.string.common_uninstall)).assertCountEquals(0)
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
|
||||
@@ -1,15 +1,11 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.content.ComponentName
|
||||
import android.os.Handler
|
||||
import android.view.Choreographer
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.compose.ui.platform.AndroidUiDispatcher
|
||||
import androidx.compose.ui.test.junit4.createComposeRule
|
||||
import androidx.compose.runtime.snapshots.Snapshot
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.Shadows.shadowOf
|
||||
import kotlin.coroutines.ContinuationInterceptor
|
||||
|
||||
fun createRobolectricComposeRule() = createComposeRule().also {
|
||||
RingVeil.reset()
|
||||
@@ -17,46 +13,5 @@ fun createRobolectricComposeRule() = createComposeRule().also {
|
||||
shadowOf(context.packageManager).addActivityIfNotPresent(
|
||||
ComponentName(context, ComponentActivity::class.java),
|
||||
)
|
||||
resumeDroppedUiDispatch()
|
||||
Snapshot.sendApplyNotifications()
|
||||
}
|
||||
|
||||
internal class UiDispatch {
|
||||
private val type = AndroidUiDispatcher::class.java
|
||||
private val dispatcher = AndroidUiDispatcher.Main[ContinuationInterceptor] as AndroidUiDispatcher
|
||||
private fun field(name: String) = type.getDeclaredField(name).apply { isAccessible = true }
|
||||
val lock: Any = field("lock").get(dispatcher)!!
|
||||
val handler = field("handler").get(dispatcher) as Handler
|
||||
val choreographer = field("choreographer").get(dispatcher) as Choreographer
|
||||
val callback: Any = field("dispatchCallback").get(dispatcher)!!
|
||||
private val trampolineFlag = field("scheduledTrampolineDispatch")
|
||||
private val frameFlag = field("scheduledFrameDispatch")
|
||||
|
||||
fun trampolineDropped() = trampolineFlag.getBoolean(dispatcher) && !handler.hasMessages(0)
|
||||
|
||||
fun frameDropped() = frameFlag.getBoolean(dispatcher) && !frameQueued()
|
||||
|
||||
private fun frameQueued(): Boolean {
|
||||
val queues = Choreographer::class.java.getDeclaredField("mCallbackQueues").apply { isAccessible = true }.get(choreographer) as Array<*>
|
||||
return queues.any { queue ->
|
||||
var record = queue?.let { q -> q.javaClass.getDeclaredField("mHead").apply { isAccessible = true }.get(q) }
|
||||
var found = false
|
||||
while (record != null && !found) {
|
||||
val recordType = record.javaClass
|
||||
found = recordType.getDeclaredField("action").apply { isAccessible = true }.get(record) === callback
|
||||
record = recordType.getDeclaredField("next").apply { isAccessible = true }.get(record)
|
||||
}
|
||||
found
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal fun uiDispatchDropped(): Boolean = UiDispatch().run { synchronized(lock) { trampolineDropped() || frameDropped() } }
|
||||
|
||||
internal fun resumeDroppedUiDispatch() {
|
||||
val ui = UiDispatch()
|
||||
synchronized(ui.lock) {
|
||||
if (ui.trampolineDropped()) ui.handler.post(ui.callback as Runnable)
|
||||
if (ui.frameDropped()) ui.choreographer.postFrameCallback(ui.callback as Choreographer.FrameCallback)
|
||||
}
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.os.Looper
|
||||
import android.view.Choreographer
|
||||
import androidx.compose.runtime.MutableIntState
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.withFrameNanos
|
||||
import androidx.compose.ui.platform.AndroidUiDispatcher
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.launch
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.Shadows.shadowOf
|
||||
import org.robolectric.annotation.Config
|
||||
import java.time.Duration
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [34], application = android.app.Application::class)
|
||||
class RobolectricComposeRuleTest {
|
||||
private fun dropPendingUiDispatch() {
|
||||
val ui = UiDispatch()
|
||||
ui.handler.removeCallbacksAndMessages(null)
|
||||
dropPendingFrame()
|
||||
}
|
||||
|
||||
private fun dropPendingFrame() {
|
||||
val ui = UiDispatch()
|
||||
ui.choreographer.removeFrameCallback(ui.callback as Choreographer.FrameCallback)
|
||||
}
|
||||
|
||||
private fun awaitFrameAfterTrampoline(ran: MutableIntState) {
|
||||
CoroutineScope(AndroidUiDispatcher.Main).launch { withFrameNanos { ran.intValue++ } }
|
||||
shadowOf(Looper.getMainLooper()).runOneTask()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun uiWorkDroppedByAnEarlierTestsLooperResetRunsAgainForTheNextComposeTest() {
|
||||
val ran = mutableIntStateOf(0)
|
||||
CoroutineScope(AndroidUiDispatcher.Main).launch { ran.intValue++ }
|
||||
dropPendingUiDispatch()
|
||||
shadowOf(Looper.getMainLooper()).idle()
|
||||
assertEquals(0, ran.intValue)
|
||||
assertTrue(uiDispatchDropped())
|
||||
createRobolectricComposeRule()
|
||||
shadowOf(Looper.getMainLooper()).idle()
|
||||
assertEquals(1, ran.intValue)
|
||||
assertFalse(uiDispatchDropped())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aDispatchStillQueuedIsLeftAlone() {
|
||||
val ran = mutableIntStateOf(0)
|
||||
CoroutineScope(AndroidUiDispatcher.Main).launch { ran.intValue++ }
|
||||
assertFalse(uiDispatchDropped())
|
||||
resumeDroppedUiDispatch()
|
||||
shadowOf(Looper.getMainLooper()).idle()
|
||||
assertEquals(1, ran.intValue)
|
||||
assertFalse(uiDispatchDropped())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aFrameDroppedAfterTheTrampolineDrainedRunsAgainForTheNextComposeTest() {
|
||||
val ran = mutableIntStateOf(0)
|
||||
awaitFrameAfterTrampoline(ran)
|
||||
dropPendingFrame()
|
||||
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(1))
|
||||
assertEquals(0, ran.intValue)
|
||||
assertTrue(uiDispatchDropped())
|
||||
createRobolectricComposeRule()
|
||||
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(1))
|
||||
assertEquals(1, ran.intValue)
|
||||
assertFalse(uiDispatchDropped())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aFrameStillQueuedIsLeftAlone() {
|
||||
val ran = mutableIntStateOf(0)
|
||||
awaitFrameAfterTrampoline(ran)
|
||||
assertEquals(0, ran.intValue)
|
||||
assertFalse(uiDispatchDropped())
|
||||
resumeDroppedUiDispatch()
|
||||
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(1))
|
||||
assertEquals(1, ran.intValue)
|
||||
assertFalse(uiDispatchDropped())
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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,114 +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.
|
||||
- `0008-signal-return-restores-syscall-state`: a guest `rt_sigreturn` is a system call, so FEX's
|
||||
syscall stub marks every static register as spilled (`InSyscallInfo = 0xFFFF`). When the handler
|
||||
left RIP alone, the return resumed the interrupted JIT code without passing the stub's reset, and
|
||||
the mark stayed. Every asynchronous signal after that (until the next system call ended) skipped the
|
||||
register spill and handed the guest handler stale registers from the last system call: only RIP was
|
||||
right. CoreCLR suspends threads for the GC with such signals and reads or redirects the interrupted
|
||||
context, so x86-64 .NET programs failed at random (`AccessViolationException` in whatever code ran
|
||||
next, then SIGABRT). `tools/fex/probes/async-signal-context.c` shows it: under FEX-2611.1 one signal in
|
||||
2000 carried the interrupted registers, natively all of them. The return now restores the value saved
|
||||
when the signal arrived, and only when the signal interrupted JIT code, which is the only case that
|
||||
saves it. Restoring it for a signal that interrupted a system call cleared the mark while that call
|
||||
was still running, so the next signal in the call's return path spilled clobbered registers:
|
||||
`setitimer` at 100 Hz around `time()` crashed in 15 of 15 runs, and with the guard as often as the
|
||||
same build without the patch (about half; a separate crash that FEX-2611.1 also shows).
|
||||
- `0009-signal-handler-escape-frees-host-stack`: FEX keeps each signal's host context on the host
|
||||
stack and frees it only on `rt_sigreturn`. A guest that leaves its handler another way (`siglongjmp`,
|
||||
or CoreCLR resuming a `catch` after a NullReferenceException) left that 2 KB block and one
|
||||
`SignalHandlerRefCounter` count behind. About 3500 such exceptions on one thread overran the 8 MB
|
||||
host stack, which has no guard page, and the CurseForge agent died with "Internal CLR error.
|
||||
(0x80131506)" and "Stack overflow occurred on the same thread again!" at the start of its second
|
||||
addon scan. FEX now chains each thread's signal frames with the guest frame range and alternate
|
||||
stack they used. When a signal arrives in JIT code that runs at the host level of the newest frame
|
||||
and the guest stack pointer shows the guest has left that frame (above its frame, or back off the
|
||||
alternate stack above where the outermost frame on it interrupted), the left frames are dropped and
|
||||
the new context is stored where the newest live frame (or the dispatcher entry) left the host stack.
|
||||
`rt_sigreturn` pops its frame and any newer ones it skips. Signals that arrive inside system calls or
|
||||
thunk callbacks are left alone. `tools/fex/probes/signal-handler-escape.c` leaves handlers on and
|
||||
off the alternate stack, mixes them with handlers that return, and leaves nested handlers: FEX-2611.1
|
||||
with 0001 to 0008 crashed (SIGSEGV) before 2000 iterations of it, and `siglongjmp` out of a SIGSEGV
|
||||
handler died after about 3500; with this patch 350000 escapes and 200000 straight `siglongjmp`s
|
||||
finish, as natively. The approach is the one suggested in FEX-Emu/FEX#2487.
|
||||
- `0010-syscall-exit-resets-host-stack` (`Fixed-upstream: FEX-2612`): a backport of FEX's
|
||||
"JIT: Ensure IR ops that jump out of the JIT reset the stack" (FEX-Emu/FEX#6122). A system call or
|
||||
code-entry removal that ends a block jumps to the dispatcher without dropping the block's spill
|
||||
slots, and the syscall handler's fast path branches straight into the next block, so every such
|
||||
exit leaked up to 32 bytes per spill slot of host stack. AVX and MMX code keeps enough values live to
|
||||
spill, and `tools/fex/probes/syscall-host-stack.c` overran the 8 MB host stack after about 65000
|
||||
system calls; with the patch 2000000 finish, as natively. The CPUID hunk of the upstream commit is
|
||||
left out, since CPUID returns to the JIT in 2611.
|
||||
- `0011-thunk-calls-mark-spilled-state`: a thunk call (every vDSO `clock_gettime`, `gettimeofday`
|
||||
and `time`, and the host library thunks) spills the static registers to the guest frame and calls
|
||||
host code, which clobbers the caller-saved host registers. A signal that arrived in the JIT code
|
||||
after the host call returned and before the registers were refilled took the interrupted state from
|
||||
those clobbered host registers: the guest handler got garbage registers, and the interrupted code
|
||||
resumed with them, or FEX built the signal frame at a garbage stack pointer and crashed. The thunk
|
||||
call now marks every static register as spilled (`InSyscallInfo = 0xFFFF`, as the system call
|
||||
handler does) until the refill ends, and a fully spilled mark takes only RIP from the host PC and
|
||||
leaves the frame's GPRs, vector registers and flags alone (the 16-bit mask could not name the
|
||||
x16/x17 and v16 to v31 registers the host call clobbers). Every guest signal now saves and clears the
|
||||
mark, so guest handlers and nested signals never inherit it, and every return puts back the value it
|
||||
saved; 0008 restored it only for JIT code because the other paths saved none. A handler that changes
|
||||
RIP restarts at the dispatcher with no mark, and thunk callbacks into guest code run with none.
|
||||
`tools/fex/probes/vdso-signal-state.c` calls `clock_gettime` under a 1 kHz `SIGALRM` and checks the
|
||||
values held across each call: FEX-2611 crashed in 3 of 8 runs, with 0001 to 0010 in 7 of 8; with
|
||||
this patch 0 of 28, as natively. This was the "separate crash" noted under 0008.
|
||||
- `0012-signal-return-applies-guest-registers`: a signal return that kept RIP threw away every
|
||||
register change the guest handler made in its `ucontext`; only a changed RIP made FEX reload the
|
||||
guest state from it. CoreCLR suspends threads for garbage collection with a signal and, in fully
|
||||
interruptible code, runs the collection from that handler and writes the moved object references
|
||||
back into the interrupted registers, so under FEX the thread resumed with pointers into the old heap.
|
||||
The CurseForge agent's crashes during parallel addon scans (an `AccessViolationException` in
|
||||
`Curse.Hashing.MurmurHash2.ComputeHash` or `RegexInterpreter`, or "Internal CLR error. (0x80131506)"
|
||||
with a stack overflow) look like this, but they still happen with this patch, so it is not a fix for
|
||||
them. When RIP is
|
||||
unchanged, each guest GPR the handler changed is now written where the resumed code reads it: the
|
||||
guest frame for registers the interrupted code had spilled (all of them inside a system call or
|
||||
thunk call), otherwise the static host register. Unchanged registers are left alone, signals that
|
||||
interrupted code outside the JIT (and not inside a system call or thunk call) keep the old
|
||||
behaviour, and 32-bit frames compare and write only the low 32 bits. `tools/fex/probes/signal-register-update.c`
|
||||
spins until a `SIGALRM` handler sets a register (R12, or ESI in 32-bit `rt` and legacy frames):
|
||||
FEX-2611.1 with 0001 to 0011 never sees it in any of the three frame types, with this patch all
|
||||
three see it on the first signal, as natively.
|
||||
- `0013-signal-context-matches-host-pc`: the guest RIP in a signal frame is rebuilt from the host PC,
|
||||
but FEX recorded a RIP only for instructions that might touch memory, and nothing for the code
|
||||
that ends a block. A signal there reported the RIP of the `ret`, `call`, `push` or `pop` while RSP
|
||||
and the stack already held the result, so a handler that reads or rewrites the return address
|
||||
(CoreCLR's return-address hijack for GC suspension does both) saw a frame torn between two
|
||||
instructions and, after `sigreturn`, ran the instruction again or returned through a stale slot. The
|
||||
patch makes the reported state one real instruction boundary: every guest instruction now gets a
|
||||
RIP entry; each block records where its exit code starts, and a host PC inside it reports the
|
||||
branch target (the constant, or the host register holding it), which is the state after the
|
||||
instruction; a PC at a block entry before the block has stored its own header takes that header from
|
||||
the `adr`/`adrp` it is about to store instead of the previous block's; and dispatcher code that
|
||||
still holds the guest registers in host registers (loop top and the exit linker) counts as JIT code,
|
||||
with the exit linker's target read from its link data. Dispatcher PCs never read the block header,
|
||||
which may point into a code buffer freed by a cache clear. `tools/fex/probes/signal-return-hijack.c`
|
||||
rewrites the return address and RIP from a signal handler at every point of a call/ret frame: with
|
||||
0001 to 0012 all three modes fail; with this patch 60 of 60 runs pass (20 per mode), as natively,
|
||||
and the other probes give the same results as before.
|
||||
- **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
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
#!/usr/bin/bash
|
||||
set -euxo pipefail
|
||||
VERSION=${FEX_VERSION:?FEX_VERSION must name a FEX release tag, e.g. FEX-2611.1}
|
||||
RELEASE=${VERSION#FEX-}
|
||||
RELEASE=${RELEASE%%.*}
|
||||
VERSION=${FEX_VERSION:-FEX-2610}
|
||||
WORK=/work
|
||||
cd "$WORK"
|
||||
grep -q '^DisableSandbox' /etc/pacman.conf || sed -i 's/^\[options\]/[options]\nDisableSandbox/' /etc/pacman.conf
|
||||
@@ -40,7 +38,7 @@ fi
|
||||
rm -rf fex-src out && git clone -q --depth 1 --branch "$VERSION" --recurse-submodules --shallow-submodules https://github.com/FEX-Emu/FEX.git fex-src
|
||||
for p in tools/fex/patches/*.patch; do
|
||||
upstream=$(sed -n 's/^Fixed-upstream: FEX-\([0-9]\{4\}\)$/\1/p' "$p")
|
||||
if [ -n "$upstream" ] && [ "$RELEASE" -ge "$upstream" ]; then
|
||||
if [ -n "$upstream" ] && [ "${VERSION#FEX-}" -ge "$upstream" ]; then
|
||||
echo "$(basename "$p"): already in FEX-$upstream, skipped for $VERSION"
|
||||
continue
|
||||
fi
|
||||
@@ -58,8 +56,7 @@ cmake -S fex-src -B fex-build -G Ninja \
|
||||
-DTUNE_CPU=none -DTUNE_ARCH=armv8-a \
|
||||
-DBUILD_TESTING=OFF -DBUILD_FEXCONFIG=OFF -DENABLE_ASSERTIONS=OFF \
|
||||
$( [ "$THUNKS" = 1 ] && echo "-DBUILD_THUNKS=ON -DX86_DEV_ROOTFS=$X86ROOT" || echo "-DBUILD_THUNKS=OFF" ) \
|
||||
-DENABLE_CCACHE=OFF -DENABLE_OFFLINE_TELEMETRY=OFF -DFMT_MODULE=OFF \
|
||||
-DCMAKE_CXX_MODULE_STD=OFF -DCMAKE_CXX_SCAN_FOR_MODULES=OFF \
|
||||
-DENABLE_CCACHE=OFF -DENABLE_OFFLINE_TELEMETRY=OFF \
|
||||
${FEX_EXTRA_CXXFLAGS:+-DCMAKE_CXX_FLAGS="$FEX_EXTRA_CXXFLAGS"}
|
||||
ninja -C fex-build
|
||||
DESTDIR="$WORK/out" ninja -C fex-build install
|
||||
|
||||
@@ -1,81 +0,0 @@
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.h
|
||||
index d720866..f55bce4 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.h
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.h
|
||||
@@ -288,6 +288,7 @@ public:
|
||||
///// VMA (Virtual Memory Area) tracking /////
|
||||
static bool HandleSegfault(FEXCore::Core::InternalThreadState* Thread, int Signal, void* info, void* ucontext);
|
||||
void MarkGuestExecutableRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length) override;
|
||||
+ void ProtectWritableAliasOfCode(uint64_t Base, uint64_t Length);
|
||||
void InvalidateGuestCodeRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length) override;
|
||||
std::optional<FEXCore::ExecutableFileSectionInfo>
|
||||
LookupExecutableFileSection(FEXCore::Core::InternalThreadState* Thread, uint64_t GuestAddr) final override;
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp
|
||||
index 94bdd37..5d6c850 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp
|
||||
@@ -196,6 +196,44 @@ void SyscallHandler::MarkGuestExecutableRange(FEXCore::Core::InternalThreadState
|
||||
}
|
||||
}
|
||||
|
||||
+void SyscallHandler::ProtectWritableAliasOfCode(uint64_t Base, uint64_t Length) {
|
||||
+ if (SMCChecks != FEXCore::Config::CONFIG_SMC_MTRACK) {
|
||||
+ return;
|
||||
+ }
|
||||
+
|
||||
+ const auto End = Base + Length;
|
||||
+ auto Mapping = VMATracking.FindVMAEntry(Base);
|
||||
+ if (Mapping == VMATracking.VMAs.end()) {
|
||||
+ Mapping = VMATracking.VMAs.lower_bound(Base);
|
||||
+ }
|
||||
+
|
||||
+ for (; Mapping != VMATracking.VMAs.end() && Mapping->first < End; ++Mapping) {
|
||||
+ if (!Mapping->second.Flags.Shared || !Mapping->second.Prot.Writable || !Mapping->second.Resource) {
|
||||
+ continue;
|
||||
+ }
|
||||
+
|
||||
+ const auto MapBase = std::max(Base, Mapping->first);
|
||||
+ const auto MapTop = std::min(End, Mapping->first + Mapping->second.Length);
|
||||
+ if (MapTop <= MapBase) {
|
||||
+ continue;
|
||||
+ }
|
||||
+
|
||||
+ const auto OffsetBase = Mapping->second.Offset + (MapBase - Mapping->first);
|
||||
+ const auto OffsetTop = OffsetBase + (MapTop - MapBase);
|
||||
+
|
||||
+ for (auto VMA = Mapping->second.Resource->FirstVMA; VMA; VMA = VMA->ResourceNextVMA) {
|
||||
+ if (!VMA->Prot.Executable || VMA->Offset >= OffsetTop || VMA->Offset + VMA->Length <= OffsetBase) {
|
||||
+ continue;
|
||||
+ }
|
||||
+
|
||||
+ const auto OverlapBase = std::max(VMA->Offset, OffsetBase);
|
||||
+ const auto OverlapTop = std::min(VMA->Offset + VMA->Length, OffsetTop);
|
||||
+ auto rv = mprotect((void*)(MapBase + (OverlapBase - OffsetBase)), OverlapTop - OverlapBase, PROT_READ);
|
||||
+ LogMan::Throw::AFmt(rv == 0, "mprotect({}, {}) failed", OverlapBase, OverlapTop - OverlapBase);
|
||||
+ }
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
void SyscallHandler::InvalidateGuestCodeRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length) {
|
||||
InvalidateCodeRangeIfNecessary(Thread, Start, Length, false);
|
||||
}
|
||||
@@ -334,6 +372,9 @@ void* SyscallHandler::GuestMmap(bool Is64Bit, FEXCore::Core::InternalThreadState
|
||||
}
|
||||
|
||||
LateMetadata = TrackMmap(Thread, Result, length, prot, flags, fd, offset, CachedSection);
|
||||
+ if (prot & PROT_WRITE) {
|
||||
+ ProtectWritableAliasOfCode(Result, Size);
|
||||
+ }
|
||||
PendingResourceDeletion = VMATracking.HasPendingResourceDeletions();
|
||||
}
|
||||
|
||||
@@ -479,6 +520,9 @@ uint64_t SyscallHandler::GuestMprotect(FEXCore::Core::InternalThreadState* Threa
|
||||
}
|
||||
|
||||
TrackMprotect(Thread, addr, len, prot);
|
||||
+ if (prot & PROT_WRITE) {
|
||||
+ ProtectWritableAliasOfCode(reinterpret_cast<uint64_t>(addr), FEXCore::AlignUp(len, FEXCore::Utils::FEX_PAGE_SIZE));
|
||||
+ }
|
||||
}
|
||||
|
||||
InvalidateCodeRangeIfNecessary(Thread, reinterpret_cast<uint64_t>(addr), len, false);
|
||||
@@ -1,20 +0,0 @@
|
||||
diff --git a/CMakeLists.txt b/CMakeLists.txt
|
||||
index 8976588..3ae54f4 100644
|
||||
--- a/CMakeLists.txt
|
||||
+++ b/CMakeLists.txt
|
||||
@@ -776,7 +776,6 @@ if (BUILD_THUNKS)
|
||||
CODE "
|
||||
execute_process(COMMAND ${CMAKE_COMMAND} --build . --target install
|
||||
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/Guest)"
|
||||
- DEPENDS guest-libs
|
||||
COMPONENT Runtime)
|
||||
|
||||
install(
|
||||
@@ -784,7 +783,6 @@ if (BUILD_THUNKS)
|
||||
CODE "
|
||||
execute_process(COMMAND ${CMAKE_COMMAND} --build . --target install
|
||||
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/Guest_32)"
|
||||
- DEPENDS guest-libs-32
|
||||
COMPONENT Runtime)
|
||||
|
||||
add_custom_target(uninstall_guest-libs
|
||||
@@ -1,18 +0,0 @@
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
|
||||
index b4c7b24..643185d 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
|
||||
@@ -264,12 +264,13 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr
|
||||
auto Frame = Thread->CurrentFrame;
|
||||
|
||||
if (Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT) {
|
||||
// XXX: Unsupported since it needs state reconstruction
|
||||
// If we are in the JIT then SRA might need to be restored to values from the context
|
||||
// We can't currently support this since it might result in tearing without real state reconstruction
|
||||
+ Frame->InSyscallInfo = Context->InSyscallInfo;
|
||||
}
|
||||
|
||||
if (Is64BitMode) {
|
||||
RestoreFrame_x64(Thread, Context, Frame, ucontext);
|
||||
} else {
|
||||
if (Type == RestoreType::TYPE_NONREALTIME) {
|
||||
@@ -1,174 +0,0 @@
|
||||
diff --git a/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h b/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h
|
||||
index 02bb6bf..2e72492 100644
|
||||
--- a/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h
|
||||
+++ b/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h
|
||||
@@ -49,6 +49,11 @@ struct X86ContextBackup {
|
||||
uint64_t FPStateLocation;
|
||||
uint64_t UContextLocation;
|
||||
uint64_t SigInfoLocation;
|
||||
+ uint64_t PrevGuestFrame;
|
||||
+ uint64_t GuestFrameEnd;
|
||||
+ uint64_t GuestInterruptedSP;
|
||||
+ uint64_t GuestAltBase;
|
||||
+ uint64_t GuestAltEnd;
|
||||
FEXCore::Core::CPUState GuestState;
|
||||
static constexpr int RedZoneSize = 128;
|
||||
};
|
||||
@@ -76,6 +81,11 @@ struct ArmContextBackup {
|
||||
uint64_t FPStateLocation;
|
||||
uint64_t UContextLocation;
|
||||
uint64_t SigInfoLocation;
|
||||
+ uint64_t PrevGuestFrame;
|
||||
+ uint64_t GuestFrameEnd;
|
||||
+ uint64_t GuestInterruptedSP;
|
||||
+ uint64_t GuestAltBase;
|
||||
+ uint64_t GuestAltEnd;
|
||||
FEXCore::Core::CPUState GuestState;
|
||||
|
||||
// Arm64 doesn't have a red zone
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
|
||||
index 643185d..53179c4 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
|
||||
@@ -136,6 +136,31 @@ void SignalDelegator::SpillSRA(FEXCore::Core::InternalThreadState* Thread, void*
|
||||
#endif
|
||||
}
|
||||
|
||||
+namespace {
|
||||
+ bool OnGuestAltStack(const ArchHelpers::Context::ContextBackup* Backup, uint64_t SP) {
|
||||
+ return Backup->GuestAltEnd != 0 && SP >= Backup->GuestAltBase && SP <= Backup->GuestAltEnd;
|
||||
+ }
|
||||
+
|
||||
+ bool GuestLeftFrame(const ArchHelpers::Context::ContextBackup* Backup, uint64_t GuestSP, uint32_t Limit) {
|
||||
+ const bool SPOnAlt = OnGuestAltStack(Backup, GuestSP);
|
||||
+ if (SPOnAlt == OnGuestAltStack(Backup, Backup->GuestFrameEnd)) {
|
||||
+ return GuestSP >= Backup->GuestFrameEnd;
|
||||
+ }
|
||||
+ if (SPOnAlt) {
|
||||
+ return false;
|
||||
+ }
|
||||
+ auto Entry = Backup;
|
||||
+ while (OnGuestAltStack(Backup, Entry->GuestInterruptedSP)) {
|
||||
+ if (--Limit == 0 || !Entry->PrevGuestFrame) {
|
||||
+ return false;
|
||||
+ }
|
||||
+ Entry = reinterpret_cast<const ArchHelpers::Context::ContextBackup*>(Entry->PrevGuestFrame);
|
||||
+ }
|
||||
+ return OnGuestAltStack(Backup, Entry->GuestFrameEnd) && Entry->GuestAltBase == Backup->GuestAltBase &&
|
||||
+ Entry->GuestAltEnd == Backup->GuestAltEnd && GuestSP >= Entry->GuestInterruptedSP;
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
ArchHelpers::Context::ContextBackup* SignalDelegator::StoreThreadState(FEXCore::Core::InternalThreadState* Thread, int Signal, void* ucontext) {
|
||||
// We can end up getting a signal at any point in our host state
|
||||
// Jump to a handler that saves all state so we can safely return
|
||||
@@ -249,6 +274,19 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr
|
||||
}
|
||||
|
||||
OldSP = *reinterpret_cast<uint64_t*>(GuestSP);
|
||||
+
|
||||
+ auto& SignalInfo = FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread)->SignalInfo;
|
||||
+ uint64_t Entry = SignalInfo.GuestFrames;
|
||||
+ for (uint32_t Depth = 1; Entry && Depth <= SignalInfo.GuestFrameCount; ++Depth) {
|
||||
+ auto EntryBackup = reinterpret_cast<ArchHelpers::Context::ContextBackup*>(Entry);
|
||||
+ if (Entry == OldSP) {
|
||||
+ SignalInfo.GuestFrames = EntryBackup->PrevGuestFrame;
|
||||
+ SignalInfo.GuestFrameCount -= Depth;
|
||||
+ Thread->CurrentFrame->SignalHandlerRefCounter -= Depth - 1;
|
||||
+ break;
|
||||
+ }
|
||||
+ Entry = EntryBackup->PrevGuestFrame;
|
||||
+ }
|
||||
}
|
||||
|
||||
uintptr_t NewSP = OldSP;
|
||||
@@ -287,6 +325,7 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
|
||||
auto ContextBackup = StoreThreadState(Thread, Signal, ucontext);
|
||||
|
||||
auto Frame = Thread->CurrentFrame;
|
||||
+ auto& SignalInfo = FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread)->SignalInfo;
|
||||
|
||||
// Ref count our faults
|
||||
// We use this to track if it is safe to clear cache
|
||||
@@ -336,6 +375,8 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
|
||||
|
||||
uint64_t OldGuestSP = Frame->State.gregs[FEXCore::X86State::REG_RSP];
|
||||
uint64_t NewGuestSP = OldGuestSP;
|
||||
+ uint64_t GuestAltBase = 0;
|
||||
+ uint64_t GuestAltEnd = 0;
|
||||
|
||||
// altstack is only used if the signal handler was setup with SA_ONSTACK
|
||||
if (GuestAction->sa_flags & SA_ONSTACK) {
|
||||
@@ -345,6 +386,8 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
|
||||
// Then that means we are hitting recursive signals and we need to walk back the stack correctly
|
||||
uint64_t AltStackBase = reinterpret_cast<uint64_t>(GuestStack->ss_sp);
|
||||
uint64_t AltStackEnd = AltStackBase + GuestStack->ss_size;
|
||||
+ GuestAltBase = AltStackBase;
|
||||
+ GuestAltEnd = AltStackEnd;
|
||||
if (OldGuestSP >= AltStackBase && OldGuestSP <= AltStackEnd) {
|
||||
// We are already in the alt stack, the rest of the code will handle adjusting this
|
||||
} else {
|
||||
@@ -353,6 +396,40 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
|
||||
}
|
||||
}
|
||||
|
||||
+#ifdef ARCHITECTURE_arm64
|
||||
+ auto Newest = reinterpret_cast<ArchHelpers::Context::ContextBackup*>(SignalInfo.GuestFrames);
|
||||
+ if (WasInJIT && Newest && ContextBackup->PrevSP == SignalInfo.GuestFrames &&
|
||||
+ Frame->SignalHandlerRefCounter == SignalInfo.GuestFrameCount + 1 && GuestLeftFrame(Newest, OldGuestSP, SignalInfo.GuestFrameCount)) {
|
||||
+ uint32_t LeftFrames = 0;
|
||||
+ while (Newest && LeftFrames < SignalInfo.GuestFrameCount &&
|
||||
+ GuestLeftFrame(Newest, OldGuestSP, SignalInfo.GuestFrameCount - LeftFrames)) {
|
||||
+ Newest = reinterpret_cast<ArchHelpers::Context::ContextBackup*>(Newest->PrevGuestFrame);
|
||||
+ ++LeftFrames;
|
||||
+ }
|
||||
+
|
||||
+ const uint64_t HostTop = Newest ? reinterpret_cast<uint64_t>(Newest) : Frame->ReturningStackLocation;
|
||||
+ const uint64_t MovedBackup = FEXCore::AlignDown(
|
||||
+ HostTop - ArchHelpers::Context::ContextBackup::RedZoneSize - sizeof(ArchHelpers::Context::ContextBackup), 16);
|
||||
+ if (MovedBackup > reinterpret_cast<uint64_t>(ContextBackup)) {
|
||||
+ memmove(reinterpret_cast<void*>(MovedBackup), ContextBackup, sizeof(ArchHelpers::Context::ContextBackup));
|
||||
+ ContextBackup = reinterpret_cast<ArchHelpers::Context::ContextBackup*>(MovedBackup);
|
||||
+ ContextBackup->PrevSP = HostTop;
|
||||
+ ArchHelpers::Context::SetSp(ucontext, MovedBackup);
|
||||
+ SignalInfo.GuestFrames = reinterpret_cast<uint64_t>(Newest);
|
||||
+ SignalInfo.GuestFrameCount -= LeftFrames;
|
||||
+ Frame->SignalHandlerRefCounter -= LeftFrames;
|
||||
+ }
|
||||
+ }
|
||||
+#endif
|
||||
+
|
||||
+ ContextBackup->GuestFrameEnd = NewGuestSP;
|
||||
+ ContextBackup->GuestInterruptedSP = OldGuestSP;
|
||||
+ ContextBackup->GuestAltBase = GuestAltBase;
|
||||
+ ContextBackup->GuestAltEnd = GuestAltEnd;
|
||||
+ ContextBackup->PrevGuestFrame = SignalInfo.GuestFrames;
|
||||
+ SignalInfo.GuestFrames = reinterpret_cast<uint64_t>(ContextBackup);
|
||||
+ ++SignalInfo.GuestFrameCount;
|
||||
+
|
||||
// siginfo_t
|
||||
siginfo_t* HostSigInfo = reinterpret_cast<siginfo_t*>(info);
|
||||
|
||||
@@ -491,6 +568,8 @@ bool SignalDelegator::HandleSignalPause(FEXCore::Core::InternalThreadState* Thre
|
||||
|
||||
// Our ref counting doesn't matter anymore
|
||||
Thread->CurrentFrame->SignalHandlerRefCounter = 0;
|
||||
+ ThreadObject->SignalInfo.GuestFrames = 0;
|
||||
+ ThreadObject->SignalInfo.GuestFrameCount = 0;
|
||||
|
||||
// Set the new PC
|
||||
if (CTX->IsAddressInCodeBuffer(Thread, ArchHelpers::Context::GetPc(ucontext))) {
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h
|
||||
index dfcd4b0..e4a86a9 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h
|
||||
@@ -83,6 +83,9 @@ struct ThreadStateObject : public FEXCore::Allocator::FEXAllocOperators {
|
||||
// Queue of thread local signal frames that have been deferred.
|
||||
// Async signals aren't guaranteed to be delivered in any particular order, but FEX treats them as FILO.
|
||||
fextl::vector<DeferredSignalState> DeferredSignalFrames;
|
||||
+
|
||||
+ uint64_t GuestFrames {};
|
||||
+ uint32_t GuestFrameCount {};
|
||||
} SignalInfo {};
|
||||
|
||||
// Seccomp thread specific data.
|
||||
@@ -1,23 +0,0 @@
|
||||
Fixed-upstream: FEX-2612
|
||||
diff --git a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp
|
||||
index c2b1d8e287..fcdf261484 100644
|
||||
--- a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp
|
||||
+++ b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp
|
||||
@@ -285,6 +285,8 @@ DEF_OP(CondJump) {
|
||||
DEF_OP(Syscall) {
|
||||
SpillStaticRegs(TMP1);
|
||||
|
||||
+ ResetStack();
|
||||
+
|
||||
// Jump to the syscall dispatch handler. We won't return after this.
|
||||
ldr(TMP1, STATE, offsetof(FEXCore::Core::CpuStateFrame, Pointers.ThreadDispatchSyscallHandler));
|
||||
br(TMP1);
|
||||
@@ -376,6 +378,8 @@ DEF_OP(ThreadRemoveCodeEntry) {
|
||||
|
||||
SpillStaticRegs(TMP1);
|
||||
|
||||
+ ResetStack();
|
||||
+
|
||||
// Store the new RIP to go to.
|
||||
str(GetReg(Op->NewRIP).X(), STATE, offsetof(FEXCore::Core::CpuStateFrame, State.rip));
|
||||
|
||||
@@ -1,109 +0,0 @@
|
||||
diff --git a/FEXCore/Source/Interface/Core/Core.cpp b/FEXCore/Source/Interface/Core/Core.cpp
|
||||
--- a/FEXCore/Source/Interface/Core/Core.cpp
|
||||
+++ b/FEXCore/Source/Interface/Core/Core.cpp
|
||||
@@ -383,7 +383,11 @@
|
||||
}
|
||||
|
||||
void ContextImpl::HandleCallback(FEXCore::Core::InternalThreadState* Thread, uint64_t RIP) {
|
||||
- static_cast<ContextImpl*>(Thread->CTX)->Dispatcher->ExecuteJITCallback(Thread->CurrentFrame, RIP);
|
||||
+ auto Frame = Thread->CurrentFrame;
|
||||
+ const auto InSyscallInfo = Frame->InSyscallInfo;
|
||||
+ Frame->InSyscallInfo = 0;
|
||||
+ static_cast<ContextImpl*>(Thread->CTX)->Dispatcher->ExecuteJITCallback(Frame, RIP);
|
||||
+ Frame->InSyscallInfo = InSyscallInfo;
|
||||
}
|
||||
|
||||
void ContextImpl::ExecuteThread(FEXCore::Core::InternalThreadState* Thread) {
|
||||
diff --git a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp
|
||||
--- a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp
|
||||
+++ b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp
|
||||
@@ -305,6 +305,9 @@
|
||||
|
||||
PushDynamicRegs(TMP1);
|
||||
|
||||
+ LoadConstant(ARMEmitter::Size::i64Bit, TMP1, 0xFFFF);
|
||||
+ str(TMP1, STATE, offsetof(FEXCore::Core::CpuStateFrame, InSyscallInfo));
|
||||
+
|
||||
mov(ARMEmitter::Size::i64Bit, ARMEmitter::Reg::r0, GetReg(Op->ArgPtr));
|
||||
|
||||
InsertNamedThunkRelocation(ARMEmitter::Reg::r2, Op->ThunkNameHash);
|
||||
@@ -320,6 +323,8 @@
|
||||
FillStaticRegs({
|
||||
.NZCV = false,
|
||||
});
|
||||
+
|
||||
+ str(ARMEmitter::XReg::zr, STATE, offsetof(FEXCore::Core::CpuStateFrame, InSyscallInfo));
|
||||
}
|
||||
|
||||
DEF_OP(ValidateCode) {
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
|
||||
@@ -107,6 +107,10 @@
|
||||
#ifdef ARCHITECTURE_arm64
|
||||
Thread->CurrentFrame->State.rip = CTX->RestoreRIPFromHostPC(Thread, ArchHelpers::Context::GetPc(ucontext));
|
||||
|
||||
+ if ((IgnoreMask & 0xFFFF) == 0xFFFF) {
|
||||
+ return;
|
||||
+ }
|
||||
+
|
||||
for (size_t i = 0; i < Config.SRAGPRCount; i++) {
|
||||
const uint8_t SRAIdxMap = Config.SRAGPRMapping[i];
|
||||
if (IgnoreMask & (1U << SRAIdxMap)) {
|
||||
@@ -301,12 +305,10 @@
|
||||
if (Context->UContextLocation) {
|
||||
auto Frame = Thread->CurrentFrame;
|
||||
|
||||
- if (Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT) {
|
||||
- // XXX: Unsupported since it needs state reconstruction
|
||||
- // If we are in the JIT then SRA might need to be restored to values from the context
|
||||
- // We can't currently support this since it might result in tearing without real state reconstruction
|
||||
- Frame->InSyscallInfo = Context->InSyscallInfo;
|
||||
- }
|
||||
+ // XXX: Unsupported since it needs state reconstruction
|
||||
+ // If we are in the JIT then SRA might need to be restored to values from the context
|
||||
+ // We can't currently support this since it might result in tearing without real state reconstruction
|
||||
+ Frame->InSyscallInfo = Context->InSyscallInfo;
|
||||
|
||||
if (Is64BitMode) {
|
||||
RestoreFrame_x64(Thread, Context, Frame, ucontext);
|
||||
@@ -361,6 +363,9 @@
|
||||
ContextBackup->InSyscallInfo = Thread->CurrentFrame->InSyscallInfo;
|
||||
Thread->CurrentFrame->InSyscallInfo = 0;
|
||||
} else {
|
||||
+ ContextBackup->InSyscallInfo = Frame->InSyscallInfo;
|
||||
+ Frame->InSyscallInfo = 0;
|
||||
+
|
||||
if (!IsAddressInDispatcher(OldPC)) {
|
||||
// This is likely to cause issues but in some cases it isn't fatal
|
||||
// This can also happen if we have put a signal on hold, then we just reenabled the signal
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
|
||||
@@ -131,7 +131,7 @@
|
||||
if (Context->OriginalRIP != guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_RIP] || Context->FaultToTopAndGeneratedException) {
|
||||
|
||||
// Restore previous `InSyscallInfo` structure.
|
||||
- Frame->InSyscallInfo = Context->InSyscallInfo;
|
||||
+ Frame->InSyscallInfo = 0;
|
||||
|
||||
// Hack! Go back to the top of the dispatcher top
|
||||
// This is only safe inside the JIT rather than anything outside of it
|
||||
@@ -211,7 +211,7 @@
|
||||
// If the guest modified the RIP then we need to take special precautions here
|
||||
if (Context->OriginalRIP != guest_uctx->sc.ip || Context->FaultToTopAndGeneratedException) {
|
||||
// Restore previous `InSyscallInfo` structure.
|
||||
- Frame->InSyscallInfo = Context->InSyscallInfo;
|
||||
+ Frame->InSyscallInfo = 0;
|
||||
|
||||
// Hack! Go back to the top of the dispatcher top
|
||||
// This is only safe inside the JIT rather than anything outside of it
|
||||
@@ -290,7 +290,7 @@
|
||||
if (Context->OriginalRIP != guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_EIP] || Context->FaultToTopAndGeneratedException) {
|
||||
|
||||
// Restore previous `InSyscallInfo` structure.
|
||||
- Frame->InSyscallInfo = Context->InSyscallInfo;
|
||||
+ Frame->InSyscallInfo = 0;
|
||||
|
||||
// Hack! Go back to the top of the dispatcher top
|
||||
// This is only safe inside the JIT rather than anything outside of it
|
||||
@@ -1,112 +0,0 @@
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h
|
||||
@@ -263,6 +263,8 @@
|
||||
FEXCore::Core::CpuStateFrame* Frame, void* ucontext);
|
||||
void RestoreRTFrame_ia32(FEXCore::Core::InternalThreadState* Thread, ArchHelpers::Context::ContextBackup* Context,
|
||||
FEXCore::Core::CpuStateFrame* Frame, void* ucontext);
|
||||
+ void ResumeWithGuestGPRs(ArchHelpers::Context::ContextBackup* Context, FEXCore::Core::CpuStateFrame* Frame, void* ucontext,
|
||||
+ const uint64_t* GuestGPRs, size_t Count, uint64_t Mask);
|
||||
|
||||
///< Setup the signal frame for x64.
|
||||
uint64_t SetupFrame_x64(FEXCore::Core::InternalThreadState* Thread, ArchHelpers::Context::ContextBackup* ContextBackup,
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
|
||||
@@ -122,6 +122,32 @@
|
||||
}
|
||||
}
|
||||
|
||||
+void SignalDelegator::ResumeWithGuestGPRs(ArchHelpers::Context::ContextBackup* Context, FEXCore::Core::CpuStateFrame* Frame, void* ucontext,
|
||||
+ const uint64_t* GuestGPRs, size_t Count, uint64_t Mask) {
|
||||
+#ifdef ARCHITECTURE_arm64
|
||||
+ const uint32_t Spilled = Context->InSyscallInfo & 0xFFFF;
|
||||
+ const bool AllSpilled = Spilled == 0xFFFF;
|
||||
+ if (!AllSpilled && !(Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT)) {
|
||||
+ return;
|
||||
+ }
|
||||
+
|
||||
+ for (size_t i = 0; i < Count && i < Config.SRAGPRCount; i++) {
|
||||
+ const uint8_t HostReg = Config.SRAGPRMapping[i];
|
||||
+ const bool InFrame = AllSpilled || (Spilled & (1U << HostReg));
|
||||
+ const uint64_t Delivered = InFrame ? Frame->State.gregs[i] : ArchHelpers::Context::GetArmReg(ucontext, HostReg);
|
||||
+ if (((Delivered ^ GuestGPRs[i]) & Mask) == 0) {
|
||||
+ continue;
|
||||
+ }
|
||||
+
|
||||
+ if (InFrame) {
|
||||
+ Frame->State.gregs[i] = GuestGPRs[i];
|
||||
+ } else {
|
||||
+ ArchHelpers::Context::SetArmReg(ucontext, HostReg, GuestGPRs[i]);
|
||||
+ }
|
||||
+ }
|
||||
+#endif
|
||||
+}
|
||||
+
|
||||
void SignalDelegator::RestoreFrame_x64(FEXCore::Core::InternalThreadState* Thread, ArchHelpers::Context::ContextBackup* Context,
|
||||
FEXCore::Core::CpuStateFrame* Frame, void* ucontext) {
|
||||
auto* guest_uctx = reinterpret_cast<FEXCore::x86_64::ucontext_t*>(Context->UContextLocation);
|
||||
@@ -202,6 +228,27 @@
|
||||
const auto modulo_i = (i + CurrentOffset) % 8;
|
||||
memcpy(&Frame->State.mm[modulo_i], &fpstate->_st[i], sizeof(Frame->State.mm[0]));
|
||||
}
|
||||
+ } else {
|
||||
+ uint64_t GuestGPRs[FEXCore::Core::CPUState::NUM_GPRS];
|
||||
+#define COPY_REG(x) GuestGPRs[FEXCore::X86State::REG_##x] = guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_##x];
|
||||
+ COPY_REG(R8);
|
||||
+ COPY_REG(R9);
|
||||
+ COPY_REG(R10);
|
||||
+ COPY_REG(R11);
|
||||
+ COPY_REG(R12);
|
||||
+ COPY_REG(R13);
|
||||
+ COPY_REG(R14);
|
||||
+ COPY_REG(R15);
|
||||
+ COPY_REG(RDI);
|
||||
+ COPY_REG(RSI);
|
||||
+ COPY_REG(RBP);
|
||||
+ COPY_REG(RBX);
|
||||
+ COPY_REG(RDX);
|
||||
+ COPY_REG(RAX);
|
||||
+ COPY_REG(RCX);
|
||||
+ COPY_REG(RSP);
|
||||
+#undef COPY_REG
|
||||
+ ResumeWithGuestGPRs(Context, Frame, ucontext, GuestGPRs, FEXCore::Core::CPUState::NUM_GPRS, ~0ULL);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -280,6 +327,17 @@
|
||||
const auto modulo_i = (i + CurrentOffset) % 8;
|
||||
memcpy(&Frame->State.mm[modulo_i], &fpstate->_st[i], 10);
|
||||
}
|
||||
+ } else {
|
||||
+ uint64_t GuestGPRs[8];
|
||||
+ GuestGPRs[FEXCore::X86State::REG_RAX] = guest_uctx->sc.ax;
|
||||
+ GuestGPRs[FEXCore::X86State::REG_RCX] = guest_uctx->sc.cx;
|
||||
+ GuestGPRs[FEXCore::X86State::REG_RDX] = guest_uctx->sc.dx;
|
||||
+ GuestGPRs[FEXCore::X86State::REG_RBX] = guest_uctx->sc.bx;
|
||||
+ GuestGPRs[FEXCore::X86State::REG_RSP] = guest_uctx->sc.sp;
|
||||
+ GuestGPRs[FEXCore::X86State::REG_RBP] = guest_uctx->sc.bp;
|
||||
+ GuestGPRs[FEXCore::X86State::REG_RSI] = guest_uctx->sc.si;
|
||||
+ GuestGPRs[FEXCore::X86State::REG_RDI] = guest_uctx->sc.di;
|
||||
+ ResumeWithGuestGPRs(Context, Frame, ucontext, GuestGPRs, 8, 0xFFFF'FFFFULL);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -359,6 +417,17 @@
|
||||
const auto modulo_i = (i + CurrentOffset) % 8;
|
||||
memcpy(&Frame->State.mm[modulo_i], &fpstate->_st[i], 10);
|
||||
}
|
||||
+ } else {
|
||||
+ uint64_t GuestGPRs[8];
|
||||
+ GuestGPRs[FEXCore::X86State::REG_RAX] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RAX];
|
||||
+ GuestGPRs[FEXCore::X86State::REG_RCX] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RCX];
|
||||
+ GuestGPRs[FEXCore::X86State::REG_RDX] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RDX];
|
||||
+ GuestGPRs[FEXCore::X86State::REG_RBX] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RBX];
|
||||
+ GuestGPRs[FEXCore::X86State::REG_RSP] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RSP];
|
||||
+ GuestGPRs[FEXCore::X86State::REG_RBP] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RBP];
|
||||
+ GuestGPRs[FEXCore::X86State::REG_RSI] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RSI];
|
||||
+ GuestGPRs[FEXCore::X86State::REG_RDI] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RDI];
|
||||
+ ResumeWithGuestGPRs(Context, Frame, ucontext, GuestGPRs, 8, 0xFFFF'FFFFULL);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,463 +0,0 @@
|
||||
diff --git a/FEXCore/Source/Interface/Core/CPUBackend.h b/FEXCore/Source/Interface/Core/CPUBackend.h
|
||||
--- a/FEXCore/Source/Interface/Core/CPUBackend.h
|
||||
+++ b/FEXCore/Source/Interface/Core/CPUBackend.h
|
||||
@@ -96,8 +96,22 @@
|
||||
bool SingleInst;
|
||||
|
||||
uint8_t _Pad[3];
|
||||
+
|
||||
+ uint32_t NumberOfExitEntries;
|
||||
+
|
||||
+ uint32_t OffsetToExitEntries;
|
||||
};
|
||||
|
||||
+ struct JITExitEntry {
|
||||
+ uint32_t HostBegin;
|
||||
+ uint32_t HostEnd;
|
||||
+ int64_t TargetOffset;
|
||||
+ uint32_t TargetReg;
|
||||
+ uint32_t _Pad;
|
||||
+ };
|
||||
+
|
||||
+ static constexpr uint32_t ExitTargetConstant = ~0U;
|
||||
+
|
||||
/**
|
||||
* @brief Tells this CPUBackend to compile code for the provided IR and DebugData
|
||||
*
|
||||
diff --git a/FEXCore/Source/Interface/Core/Core.cpp b/FEXCore/Source/Interface/Core/Core.cpp
|
||||
--- a/FEXCore/Source/Interface/Core/Core.cpp
|
||||
+++ b/FEXCore/Source/Interface/Core/Core.cpp
|
||||
@@ -132,6 +132,54 @@
|
||||
return {InlineHeader, nullptr};
|
||||
}
|
||||
|
||||
+static uint64_t BlockHeaderAtEntryPoint(uint64_t HostPC) {
|
||||
+ constexpr uint32_t Rd = FEXCore::CPU::TMP1.Idx();
|
||||
+ constexpr uint32_t HeaderStore =
|
||||
+ 0xF9000000U | ((offsetof(FEXCore::Core::CPUState, InlineJITBlockHeader) / 8) << 10) | (FEXCore::CPU::STATE.Idx() << 5) | Rd;
|
||||
+ const auto IsAdr = [](uint32_t Inst) {
|
||||
+ return (Inst & 0x9F00001FU) == (0x10000000U | Rd);
|
||||
+ };
|
||||
+ const auto IsAdrp = [](uint32_t Inst) {
|
||||
+ return (Inst & 0x9F00001FU) == (0x90000000U | Rd);
|
||||
+ };
|
||||
+ const auto IsAdd = [](uint32_t Inst) {
|
||||
+ return (Inst & 0xFFC003FFU) == (0x91000000U | (Rd << 5) | Rd);
|
||||
+ };
|
||||
+ const auto Imm21 = [](uint32_t Inst) {
|
||||
+ const uint64_t Raw = (static_cast<uint64_t>((Inst >> 5) & 0x7FFFF) << 2) | ((Inst >> 29) & 3);
|
||||
+ return static_cast<int64_t>(Raw << 43) >> 43;
|
||||
+ };
|
||||
+
|
||||
+ const auto Code = reinterpret_cast<const uint32_t*>(HostPC);
|
||||
+ for (uint64_t Ahead = 0; Ahead < 3; ++Ahead) {
|
||||
+ if (Code[Ahead] != HeaderStore) {
|
||||
+ continue;
|
||||
+ }
|
||||
+ const uint64_t Store = HostPC + Ahead * 4;
|
||||
+ const uint64_t Prev = Store - 4;
|
||||
+ const auto PrevInst = *reinterpret_cast<const uint32_t*>(Prev);
|
||||
+ uint64_t Start {};
|
||||
+ uint64_t Header {};
|
||||
+ if (IsAdr(PrevInst)) {
|
||||
+ Start = Prev;
|
||||
+ Header = Prev + Imm21(PrevInst);
|
||||
+ } else if (IsAdrp(PrevInst)) {
|
||||
+ Start = Prev;
|
||||
+ Header = (Prev & ~0xFFFULL) + (Imm21(PrevInst) << 12);
|
||||
+ } else if (IsAdd(PrevInst) && IsAdrp(*reinterpret_cast<const uint32_t*>(Prev - 4))) {
|
||||
+ Start = Prev - 4;
|
||||
+ Header = (Start & ~0xFFFULL) + (Imm21(*reinterpret_cast<const uint32_t*>(Start)) << 12) + ((PrevInst >> 10) & 0xFFF);
|
||||
+ }
|
||||
+ if (!Header || HostPC < Start || Header >= Start) {
|
||||
+ return 0;
|
||||
+ }
|
||||
+ const auto InlineHeader = reinterpret_cast<const CPU::CPUBackend::JITCodeHeader*>(Header);
|
||||
+ const auto InlineTail = reinterpret_cast<const CPU::CPUBackend::JITCodeTail*>(Header + InlineHeader->OffsetToBlockTail);
|
||||
+ return HostPC < Header + InlineTail->Size ? Header : 0;
|
||||
+ }
|
||||
+ return 0;
|
||||
+}
|
||||
+
|
||||
bool ContextImpl::IsAddressInCurrentBlock(FEXCore::Core::InternalThreadState* Thread, uint64_t Address, uint64_t Size) {
|
||||
auto [_, InlineTail] = GetFrameBlockInfo(Thread->CurrentFrame);
|
||||
return InlineTail && (Address + Size > InlineTail->RIP && Address < InlineTail->RIP + InlineTail->GuestSize);
|
||||
@@ -147,8 +195,20 @@
|
||||
return InlineTail ? InlineTail->RIP : 0;
|
||||
}
|
||||
|
||||
-uint64_t ContextImpl::RestoreRIPFromHostPC(FEXCore::Core::InternalThreadState* Thread, uint64_t HostPC) {
|
||||
+uint64_t ContextImpl::RestoreRIPFromHostPC(FEXCore::Core::InternalThreadState* Thread, uint64_t HostPC, const uint64_t* HostGPRs) {
|
||||
const auto Frame = Thread->CurrentFrame;
|
||||
+
|
||||
+ if (IsAddressInCodeBuffer(Thread, HostPC)) {
|
||||
+ if (const auto Header = BlockHeaderAtEntryPoint(HostPC)) {
|
||||
+ Frame->State.InlineJITBlockHeader = Header;
|
||||
+ }
|
||||
+ } else {
|
||||
+ if (HostGPRs && HostPC >= Dispatcher->GetExitFunctionLinkerAddress() && HostPC < Dispatcher->GetExitFunctionLinkerGuardedAddress()) {
|
||||
+ return reinterpret_cast<const ExitFunctionLinkData*>(HostGPRs[30])->GuestRIP;
|
||||
+ }
|
||||
+ return Frame->State.rip;
|
||||
+ }
|
||||
+
|
||||
const uint64_t BlockBegin = Frame->State.InlineJITBlockHeader;
|
||||
auto [InlineHeader, InlineTail] = GetFrameBlockInfo(Thread->CurrentFrame);
|
||||
|
||||
@@ -157,6 +217,21 @@
|
||||
// If it is then RIP can be reconstructed from the beginning of the code block.
|
||||
// This is currently as close as FEX can get RIP reconstructions.
|
||||
if (HostPC >= reinterpret_cast<uint64_t>(BlockBegin) && HostPC < reinterpret_cast<uint64_t>(BlockBegin + InlineTail->Size)) {
|
||||
+ auto Exits = reinterpret_cast<const CPU::CPUBackend::JITExitEntry*>(Frame->State.InlineJITBlockHeader + InlineHeader->OffsetToBlockTail +
|
||||
+ InlineTail->OffsetToExitEntries);
|
||||
+ const uint64_t HostOffset = HostPC - BlockBegin;
|
||||
+ for (uint32_t i = 0; i < InlineTail->NumberOfExitEntries; ++i) {
|
||||
+ if (HostOffset < Exits[i].HostBegin || HostOffset >= Exits[i].HostEnd) {
|
||||
+ continue;
|
||||
+ }
|
||||
+ if (Exits[i].TargetReg == CPU::CPUBackend::ExitTargetConstant) {
|
||||
+ return InlineTail->RIP + Exits[i].TargetOffset;
|
||||
+ }
|
||||
+ if (HostGPRs) {
|
||||
+ return HostGPRs[Exits[i].TargetReg];
|
||||
+ }
|
||||
+ break;
|
||||
+ }
|
||||
|
||||
auto RIPEntry =
|
||||
reinterpret_cast<const uint8_t*>(Frame->State.InlineJITBlockHeader + InlineHeader->OffsetToBlockTail + InlineTail->OffsetToRIPEntries);
|
||||
@@ -523,7 +598,7 @@
|
||||
}
|
||||
|
||||
ContextImpl::GenerateIRResult
|
||||
-ContextImpl::GenerateIR(FEXCore::Core::InternalThreadState* Thread, uint64_t GuestRIP, bool ExtendedDebugInfo, uint64_t MaxInst) {
|
||||
+ContextImpl::GenerateIR(FEXCore::Core::InternalThreadState* Thread, uint64_t GuestRIP, uint64_t MaxInst) {
|
||||
FEXCORE_PROFILE_SCOPED("GenerateIR");
|
||||
|
||||
Thread->OpDispatcher->ResetWorkingList();
|
||||
@@ -641,9 +716,7 @@
|
||||
// that more explicitly later.
|
||||
Thread->OpDispatcher->FlushRegisterCache(true);
|
||||
|
||||
- if (ExtendedDebugInfo || Thread->OpDispatcher->CanHaveSideEffects(TableInfo, DecodedInfo)) {
|
||||
- Thread->OpDispatcher->_GuestOpcode(InstAddress - GuestRIP);
|
||||
- }
|
||||
+ Thread->OpDispatcher->_GuestOpcode(InstAddress - GuestRIP);
|
||||
|
||||
if (Config.SMCChecks == FEXCore::Config::CONFIG_SMC_FULL || Block.ForceFullSMCDetection) {
|
||||
auto ExistingCodePtr = reinterpret_cast<uint8_t*>(Block.Entry + BlockInstructionsLength);
|
||||
@@ -810,7 +883,7 @@
|
||||
|
||||
// Generate IR + Meta Info
|
||||
auto [IRView, TotalInstructions, TotalInstructionsLength, StartAddr, Length, NeedsAddGuestCodeRanges] =
|
||||
- GenerateIR(Thread, GuestRIP, Config.GDBSymbols(), MaxInst);
|
||||
+ GenerateIR(Thread, GuestRIP, MaxInst);
|
||||
if (!IRView) {
|
||||
Thread->FrontendDecoder->ValidateDisownedOrFree();
|
||||
Thread->OpDispatcher->ValidateDisownedOrFree();
|
||||
diff --git a/FEXCore/Source/Interface/Context/Context.h b/FEXCore/Source/Interface/Context/Context.h
|
||||
--- a/FEXCore/Source/Interface/Context/Context.h
|
||||
+++ b/FEXCore/Source/Interface/Context/Context.h
|
||||
@@ -151,7 +151,7 @@
|
||||
bool IsCurrentBlockSingleInst(FEXCore::Core::InternalThreadState* Thread) override;
|
||||
uint64_t GetGuestBlockEntry(FEXCore::Core::InternalThreadState* Thread) override;
|
||||
|
||||
- uint64_t RestoreRIPFromHostPC(FEXCore::Core::InternalThreadState* Thread, uint64_t HostPC) override;
|
||||
+ uint64_t RestoreRIPFromHostPC(FEXCore::Core::InternalThreadState* Thread, uint64_t HostPC, const uint64_t* HostGPRs = nullptr) override;
|
||||
uint32_t ReconstructCompactedEFLAGS(FEXCore::Core::InternalThreadState* Thread, bool WasInJIT, const uint64_t* HostGPRs, uint64_t PSTATE) override;
|
||||
void SetFlagsFromCompactedEFLAGS(FEXCore::Core::InternalThreadState* Thread, uint32_t EFLAGS) override;
|
||||
|
||||
@@ -416,7 +416,7 @@
|
||||
bool NeedsAddGuestCodeRanges;
|
||||
};
|
||||
[[nodiscard]]
|
||||
- GenerateIRResult GenerateIR(FEXCore::Core::InternalThreadState* Thread, uint64_t GuestRIP, bool ExtendedDebugInfo, uint64_t MaxInst);
|
||||
+ GenerateIRResult GenerateIR(FEXCore::Core::InternalThreadState* Thread, uint64_t GuestRIP, uint64_t MaxInst);
|
||||
|
||||
struct CompileCodeResult {
|
||||
CPU::CPUBackend::CompiledCode CompiledCode;
|
||||
diff --git a/FEXCore/include/FEXCore/Core/Context.h b/FEXCore/include/FEXCore/Core/Context.h
|
||||
--- a/FEXCore/include/FEXCore/Core/Context.h
|
||||
+++ b/FEXCore/include/FEXCore/Core/Context.h
|
||||
@@ -85,7 +85,7 @@
|
||||
|
||||
///< State reconstruction helpers
|
||||
///< Reconstructs the guest RIP from the passed in thread context and related Host PC.
|
||||
- FEX_DEFAULT_VISIBILITY virtual uint64_t RestoreRIPFromHostPC(FEXCore::Core::InternalThreadState* Thread, uint64_t HostPC) = 0;
|
||||
+ FEX_DEFAULT_VISIBILITY virtual uint64_t RestoreRIPFromHostPC(FEXCore::Core::InternalThreadState* Thread, uint64_t HostPC, const uint64_t* HostGPRs = nullptr) = 0;
|
||||
/**
|
||||
* @brief Reconstructs a compacted EFLAGS from FEX's internal EFLAG representation.
|
||||
*
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
|
||||
@@ -105,7 +105,8 @@
|
||||
|
||||
void SignalDelegator::SpillSRA(FEXCore::Core::InternalThreadState* Thread, void* ucontext, uint32_t IgnoreMask) {
|
||||
#ifdef ARCHITECTURE_arm64
|
||||
- Thread->CurrentFrame->State.rip = CTX->RestoreRIPFromHostPC(Thread, ArchHelpers::Context::GetPc(ucontext));
|
||||
+ Thread->CurrentFrame->State.rip =
|
||||
+ CTX->RestoreRIPFromHostPC(Thread, ArchHelpers::Context::GetPc(ucontext), ArchHelpers::Context::GetArmGPRs(ucontext));
|
||||
|
||||
if ((IgnoreMask & 0xFFFF) == 0xFFFF) {
|
||||
return;
|
||||
@@ -334,7 +335,7 @@
|
||||
++Thread->CurrentFrame->SignalHandlerRefCounter;
|
||||
|
||||
uint64_t OldPC = ArchHelpers::Context::GetPc(ucontext);
|
||||
- const bool WasInJIT = CTX->IsAddressInCodeBuffer(Thread, OldPC);
|
||||
+ const bool WasInJIT = CTX->IsAddressInCodeBuffer(Thread, OldPC) || IsAddressInDispatcherWithLiveSRA(Frame, OldPC);
|
||||
|
||||
// Spill the SRA regardless of signal handler type
|
||||
// We are going to be returning to the top of the dispatcher which will fill again
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h
|
||||
@@ -224,6 +224,13 @@
|
||||
return Address >= Config.DispatcherBegin && Address < Config.DispatcherEnd;
|
||||
}
|
||||
|
||||
+ bool IsAddressInDispatcherWithLiveSRA(const FEXCore::Core::CpuStateFrame* Frame, uint64_t Address) const {
|
||||
+ if (Address >= Config.AbsoluteLoopTopAddress && Address < Config.ThreadStopHandlerAddressSpillSRA) {
|
||||
+ return true;
|
||||
+ }
|
||||
+ return Address >= Frame->Pointers.ExitFunctionLinker && Address < Config.SignalHandlerReturnAddress;
|
||||
+ }
|
||||
+
|
||||
/*
|
||||
* Signal frames on 32-bit architecture needs to match exactly how the kernel generates the frame.
|
||||
* This is because large parts of the signal frame definition is part of the UAPI.
|
||||
diff --git a/FEXCore/Source/Interface/Core/Dispatcher/Dispatcher.cpp b/FEXCore/Source/Interface/Core/Dispatcher/Dispatcher.cpp
|
||||
--- a/FEXCore/Source/Interface/Core/Dispatcher/Dispatcher.cpp
|
||||
+++ b/FEXCore/Source/Interface/Core/Dispatcher/Dispatcher.cpp
|
||||
@@ -291,6 +291,7 @@
|
||||
{
|
||||
ExitFunctionLinkerAddress = GetCursorAddress<uint64_t>();
|
||||
EmitSignalGuardedRegion([&]() {
|
||||
+ ExitFunctionLinkerGuardedAddress = GetCursorAddress<uint64_t>();
|
||||
SpillStaticRegs(TMP1);
|
||||
|
||||
mov(ARMEmitter::XReg::x0, STATE);
|
||||
diff --git a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp
|
||||
--- a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp
|
||||
+++ b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp
|
||||
@@ -8,6 +8,7 @@
|
||||
#include "Interface/Context/Context.h"
|
||||
#include "FEXCore/IR/IR.h"
|
||||
#include "Interface/Core/LookupCache.h"
|
||||
+#include "Interface/Core/JIT/DebugData.h"
|
||||
|
||||
#include "Interface/Core/JIT/JITClass.h"
|
||||
|
||||
@@ -45,6 +46,12 @@
|
||||
|
||||
DEF_OP(ExitFunction) {
|
||||
auto Op = IROp->C<IR::IROp_ExitFunction>();
|
||||
+ const auto ExitBegin = GetCursorAddress<uint8_t*>() - CodeData.BlockBegin;
|
||||
+ uint64_t ExitTarget = 0;
|
||||
+ uint32_t ExitTargetReg = CPU::CPUBackend::ExitTargetConstant;
|
||||
+ const auto RecordExit = [&] {
|
||||
+ DebugData->Exits.push_back({ExitBegin, GetCursorAddress<uint8_t*>() - CodeData.BlockBegin, ExitTarget, ExitTargetReg});
|
||||
+ };
|
||||
|
||||
ResetStack();
|
||||
|
||||
@@ -71,6 +78,13 @@
|
||||
br(TMP2);
|
||||
|
||||
if (IsInlineRIP) {
|
||||
+ ExitTarget = NewRIP;
|
||||
+ } else {
|
||||
+ ExitTargetReg = GetReg(Op->NewRIP).Idx();
|
||||
+ }
|
||||
+ RecordExit();
|
||||
+
|
||||
+ if (IsInlineRIP) {
|
||||
BindOrRestart(&l_ExitLink);
|
||||
dc64(NewRIP);
|
||||
}
|
||||
@@ -79,6 +93,7 @@
|
||||
}
|
||||
|
||||
if (IsInlineConstant(Op->NewRIP, &NewRIP) || IsInlineEntrypointOffset(Op->NewRIP, &NewRIP)) {
|
||||
+ ExitTarget = NewRIP;
|
||||
#ifdef ARCHITECTURE_arm64ec
|
||||
if (NewRIP < EC_CODE_BITMAP_MAX_ADDRESS && RtlIsEcCode(NewRIP)) {
|
||||
str(REG_CALLRET_SP, STATE_PTR(CpuStateFrame, State.callret_sp));
|
||||
@@ -194,6 +209,7 @@
|
||||
} else {
|
||||
ARMEmitter::ForwardLabel SkipFullLookup;
|
||||
auto RipReg = GetReg(Op->NewRIP);
|
||||
+ ExitTargetReg = RipReg.Idx();
|
||||
|
||||
if (Op->Hint == IR::BranchHint::Return) {
|
||||
// First try to pop from the call-ret stack, otherwise follow the normal path (but ending in a ret)
|
||||
@@ -237,6 +253,7 @@
|
||||
br(TMP2);
|
||||
}
|
||||
}
|
||||
+ RecordExit();
|
||||
}
|
||||
|
||||
DEF_OP(Jump) {
|
||||
diff --git a/FEXCore/Source/Interface/Core/JIT/JIT.cpp b/FEXCore/Source/Interface/Core/JIT/JIT.cpp
|
||||
--- a/FEXCore/Source/Interface/Core/JIT/JIT.cpp
|
||||
+++ b/FEXCore/Source/Interface/Core/JIT/JIT.cpp
|
||||
@@ -542,6 +542,7 @@
|
||||
bool TFSet = Thread->CurrentFrame->State.flags[X86State::RFLAG_TF_RAW_LOC];
|
||||
uintptr_t HostCode {};
|
||||
auto GuestRip = Record->GuestRIP;
|
||||
+ Frame->State.rip = GuestRip;
|
||||
|
||||
if (TFSet) {
|
||||
// If TF is set, the cache must be skipped as different code needs to be generated.
|
||||
@@ -883,6 +884,7 @@
|
||||
JumpTargets.clear();
|
||||
CallReturnTargets.clear();
|
||||
PendingJumpThunks.clear();
|
||||
+ DebugData->Exits.clear();
|
||||
JumpTargets.resize(IR->GetHeader()->BlockCount, {});
|
||||
Relocations.resize(PrevNumAllocations, FEXCore::CPU::Relocation::Default()); // Discard any relocations generated from a previous attempt
|
||||
|
||||
@@ -1022,12 +1024,15 @@
|
||||
|
||||
ARMEmitter::ForwardLabel l_DoLink;
|
||||
uint64_t ThunkAddress = GetCursorAddress<uint64_t>();
|
||||
+ const auto ThunkBegin = GetCursorAddress<uint8_t*>() - CodeData.BlockBegin;
|
||||
BindOrRestart(&PendingJumpThunk.Label);
|
||||
b_OrRestart(&l_DoLink);
|
||||
br(TMP1);
|
||||
BindOrRestart(&l_DoLink);
|
||||
ldr(TMP1, &l_ExitLink);
|
||||
blr(TMP1);
|
||||
+ DebugData->Exits.push_back(
|
||||
+ {ThunkBegin, GetCursorAddress<uint8_t*>() - CodeData.BlockBegin, PendingJumpThunk.GuestRIP, CPU::CPUBackend::ExitTargetConstant});
|
||||
|
||||
// This is a ExitFunctionLinkData struct
|
||||
BindOrRestart(&l_ExitLink);
|
||||
@@ -1098,6 +1103,24 @@
|
||||
}
|
||||
}
|
||||
|
||||
+ {
|
||||
+ auto JITExitEntriesLocation = reinterpret_cast<uint8_t*>(AlignUp(reinterpret_cast<uintptr_t>(JITRIPEntriesLocation), alignof(JITExitEntry)));
|
||||
+ JITBlockTail.NumberOfExitEntries = DebugData->Exits.size();
|
||||
+ JITBlockTail.OffsetToExitEntries = JITExitEntriesLocation - JITBlockTailLocation;
|
||||
+ for (const auto& Exit : DebugData->Exits) {
|
||||
+ const JITExitEntry Record {
|
||||
+ .HostBegin = static_cast<uint32_t>(Exit.HostBegin),
|
||||
+ .HostEnd = static_cast<uint32_t>(Exit.HostEnd),
|
||||
+ .TargetOffset = static_cast<int64_t>(Exit.Target - Entry),
|
||||
+ .TargetReg = Exit.TargetReg,
|
||||
+ ._Pad = 0,
|
||||
+ };
|
||||
+ memcpy(JITExitEntriesLocation, &Record, sizeof(Record));
|
||||
+ JITExitEntriesLocation += sizeof(Record);
|
||||
+ }
|
||||
+ JITRIPEntriesLocation = JITExitEntriesLocation;
|
||||
+ }
|
||||
+
|
||||
SetCursorOffset(JITRIPEntriesLocation - CodeData.BlockBegin);
|
||||
// Make sure code is 16B aligned on the tail.
|
||||
// Can't use Align16B here as vl64pair can cause non-4byte alignment.
|
||||
diff --git a/FEXCore/Source/Interface/Core/JIT/DebugData.h b/FEXCore/Source/Interface/Core/JIT/DebugData.h
|
||||
--- a/FEXCore/Source/Interface/Core/JIT/DebugData.h
|
||||
+++ b/FEXCore/Source/Interface/Core/JIT/DebugData.h
|
||||
@@ -21,6 +21,13 @@
|
||||
ptrdiff_t HostEntryOffset;
|
||||
};
|
||||
|
||||
+struct DebugDataExit {
|
||||
+ ptrdiff_t HostBegin;
|
||||
+ ptrdiff_t HostEnd;
|
||||
+ uint64_t Target;
|
||||
+ uint32_t TargetReg;
|
||||
+};
|
||||
+
|
||||
/**
|
||||
* @brief Contains debug data for a block of code for later debugger analysis
|
||||
*
|
||||
@@ -30,6 +37,7 @@
|
||||
uint64_t HostCodeSize; ///< The size of the code generated in the host JIT
|
||||
fextl::vector<DebugDataSubblock> Subblocks;
|
||||
fextl::vector<DebugDataGuestOpcode> GuestOpcodes;
|
||||
+ fextl::vector<DebugDataExit> Exits;
|
||||
fextl::vector<FEXCore::CPU::Relocation>* Relocations;
|
||||
};
|
||||
} // namespace FEXCore::Core
|
||||
diff --git a/FEXCore/Source/Interface/Core/OpcodeDispatcher.h b/FEXCore/Source/Interface/Core/OpcodeDispatcher.h
|
||||
--- a/FEXCore/Source/Interface/Core/OpcodeDispatcher.h
|
||||
+++ b/FEXCore/Source/Interface/Core/OpcodeDispatcher.h
|
||||
@@ -251,38 +251,6 @@
|
||||
return false;
|
||||
}
|
||||
|
||||
- static bool CanHaveSideEffects(const FEXCore::X86Tables::X86InstInfo* TableInfo, FEXCore::X86Tables::DecodedOp Op) {
|
||||
- if (TableInfo) {
|
||||
- if (TableInfo->Flags & X86Tables::InstFlags::FLAGS_DEBUG_MEM_ACCESS) {
|
||||
- // If it is marked as having memory access then always say it has a side-effect.
|
||||
- // Not always true but better to be safe.
|
||||
- return true;
|
||||
- }
|
||||
-
|
||||
- if (TableInfo->Flags & (X86Tables::InstFlags::FLAGS_SETS_RIP | X86Tables::InstFlags::FLAGS_BLOCK_END)) {
|
||||
- // Cooperative suspend interrupts can be triggered at any back-edge, the RIP must be reconstructed correctly in such cases
|
||||
- return true;
|
||||
- }
|
||||
- }
|
||||
-
|
||||
- auto CanHaveSideEffects = false;
|
||||
-
|
||||
- auto HasPotentialMemoryAccess = [](const X86Tables::DecodedOperand& Operand) -> bool {
|
||||
- if (Operand.IsNone()) {
|
||||
- return false;
|
||||
- }
|
||||
-
|
||||
- // This isn't guaranteed that all of these types will access memory, but be safe.
|
||||
- return Operand.IsGPRDirect() || Operand.IsGPRIndirect() || Operand.IsRIPRelative() || Operand.IsSIB();
|
||||
- };
|
||||
-
|
||||
- CanHaveSideEffects |= HasPotentialMemoryAccess(Op->Dest);
|
||||
- CanHaveSideEffects |= HasPotentialMemoryAccess(Op->Src[0]);
|
||||
- CanHaveSideEffects |= HasPotentialMemoryAccess(Op->Src[1]);
|
||||
- CanHaveSideEffects |= HasPotentialMemoryAccess(Op->Src[2]);
|
||||
- return CanHaveSideEffects;
|
||||
- }
|
||||
-
|
||||
template<typename F>
|
||||
void ForeachDirection(F&& Routine) {
|
||||
// Otherwise, prepare to branch.
|
||||
diff --git a/FEXCore/Source/Interface/Core/CodeCache.cpp b/FEXCore/Source/Interface/Core/CodeCache.cpp
|
||||
--- a/FEXCore/Source/Interface/Core/CodeCache.cpp
|
||||
+++ b/FEXCore/Source/Interface/Core/CodeCache.cpp
|
||||
@@ -468,7 +468,7 @@
|
||||
if (i == 1) {
|
||||
if (tail->RIP >= Section.BeginVA && tail->RIP < Section.EndVA) {
|
||||
auto [IRView, TotalInstructions, TotalInstructionsLength, StartAddr, Length, _] =
|
||||
- ValidationCTX->GenerateIR(ValidationThread.get(), tail->RIP, false, FEXCore::Config::Get_MAXINST());
|
||||
+ ValidationCTX->GenerateIR(ValidationThread.get(), tail->RIP, FEXCore::Config::Get_MAXINST());
|
||||
fextl::ostringstream ss;
|
||||
FEXCore::IR::Dump(&ss, &*IRView);
|
||||
LogMan::Msg::EFmt("IR:\n{}", ss.str());
|
||||
diff --git a/FEXCore/Source/Interface/Core/Dispatcher/Dispatcher.h b/FEXCore/Source/Interface/Core/Dispatcher/Dispatcher.h
|
||||
--- a/FEXCore/Source/Interface/Core/Dispatcher/Dispatcher.h
|
||||
+++ b/FEXCore/Source/Interface/Core/Dispatcher/Dispatcher.h
|
||||
@@ -59,6 +59,10 @@
|
||||
return ExitFunctionLinkerAddress;
|
||||
}
|
||||
|
||||
+ uint64_t GetExitFunctionLinkerGuardedAddress() const {
|
||||
+ return ExitFunctionLinkerGuardedAddress;
|
||||
+ }
|
||||
+
|
||||
SignalDelegatorConfig MakeSignalDelegatorConfig() const;
|
||||
|
||||
protected:
|
||||
@@ -84,6 +88,7 @@
|
||||
uint64_t ThreadDispatchSyscallHandler {};
|
||||
uint64_t ThreadDispatchRemoveCodeEntry {};
|
||||
uint64_t ExitFunctionLinkerAddress {};
|
||||
+ uint64_t ExitFunctionLinkerGuardedAddress {};
|
||||
uint64_t SignalHandlerReturnAddress {};
|
||||
uint64_t SignalHandlerReturnAddressRT {};
|
||||
uint64_t GuestSignal_SIGILL {};
|
||||
@@ -1,84 +0,0 @@
|
||||
#define _GNU_SOURCE
|
||||
#include <pthread.h>
|
||||
#include <signal.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <ucontext.h>
|
||||
#include <unistd.h>
|
||||
|
||||
volatile long base;
|
||||
static volatile long hits, matched, stale, stop;
|
||||
static long want;
|
||||
static pid_t target;
|
||||
extern char probe_loop_start[], probe_loop_end[];
|
||||
|
||||
static void handler(int sig, siginfo_t *info, void *context) {
|
||||
greg_t *g = ((ucontext_t *)context)->uc_mcontext.gregs;
|
||||
(void)sig;
|
||||
(void)info;
|
||||
if (g[REG_RIP] >= (greg_t)probe_loop_start && g[REG_RIP] < (greg_t)probe_loop_end) {
|
||||
long below = base - g[REG_RSP];
|
||||
if (g[REG_RBX] == 0x1111111111111111L && g[REG_R12] == 0x2222222222222222L && g[REG_R13] == 0x3333333333333333L &&
|
||||
g[REG_R14] == 0x4444444444444444L && g[REG_R15] == 0x5555555555555555L && (unsigned long)g[REG_RCX] <= 4096 &&
|
||||
(below == 0 || below == 8))
|
||||
matched++;
|
||||
else
|
||||
stale++;
|
||||
}
|
||||
hits++;
|
||||
}
|
||||
|
||||
static void *sender(void *arg) {
|
||||
(void)arg;
|
||||
while (!stop) {
|
||||
syscall(SYS_tgkill, getpid(), target, SIGUSR1);
|
||||
usleep(50);
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
struct sigaction action = {0};
|
||||
pthread_t thread;
|
||||
want = argc > 1 ? atol(argv[1]) : 2000;
|
||||
action.sa_sigaction = handler;
|
||||
action.sa_flags = SA_SIGINFO | SA_RESTART;
|
||||
sigaction(SIGUSR1, &action, NULL);
|
||||
sigset_t usr1;
|
||||
sigemptyset(&usr1);
|
||||
sigaddset(&usr1, SIGUSR1);
|
||||
pthread_sigmask(SIG_UNBLOCK, &usr1, NULL);
|
||||
target = syscall(SYS_gettid);
|
||||
if (pthread_create(&thread, NULL, sender, NULL) != 0) {
|
||||
fprintf(stderr, "cannot start the signal sender\n");
|
||||
return 2;
|
||||
}
|
||||
while (matched + stale < want) {
|
||||
__asm__ volatile("mov $0x1111111111111111, %%rbx\n"
|
||||
"mov $0x2222222222222222, %%r12\n"
|
||||
"mov $0x3333333333333333, %%r13\n"
|
||||
"mov $0x4444444444444444, %%r14\n"
|
||||
"mov $0x5555555555555555, %%r15\n"
|
||||
"mov %%rsp, base(%%rip)\n"
|
||||
"mov $4096, %%ecx\n"
|
||||
".globl probe_loop_start\n"
|
||||
"probe_loop_start:\n"
|
||||
"push %%rax\n"
|
||||
"1: dec %%ecx\n"
|
||||
"jnz 1b\n"
|
||||
"pop %%rax\n"
|
||||
"mov $4096, %%ecx\n"
|
||||
"2: dec %%ecx\n"
|
||||
"jnz 2b\n"
|
||||
".globl probe_loop_end\n"
|
||||
"probe_loop_end:\n"
|
||||
:
|
||||
:
|
||||
: "rbx", "rcx", "r12", "r13", "r14", "r15", "memory");
|
||||
}
|
||||
stop = 1;
|
||||
pthread_join(thread, NULL);
|
||||
printf("signals=%ld matched=%ld stale=%ld\n", hits, matched, stale);
|
||||
return stale ? 1 : 0;
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
#define _GNU_SOURCE
|
||||
#include <setjmp.h>
|
||||
#include <signal.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
static sigjmp_buf main_env, inner_env;
|
||||
static volatile int depth, nested_mode;
|
||||
static volatile long escapes, nested, returns, wrong;
|
||||
|
||||
static void fault(long i) {
|
||||
*(volatile int *)(long)(8 + (i & 7)) = 1;
|
||||
}
|
||||
|
||||
static void segv(int sig, siginfo_t *info, void *context) {
|
||||
(void)sig;
|
||||
(void)info;
|
||||
(void)context;
|
||||
if (!nested_mode) {
|
||||
escapes++;
|
||||
siglongjmp(main_env, 1);
|
||||
}
|
||||
if (depth == 1) {
|
||||
nested++;
|
||||
siglongjmp(inner_env, 1);
|
||||
}
|
||||
depth = 1;
|
||||
for (volatile int k = 0; k < 3; k++)
|
||||
if (sigsetjmp(inner_env, 0) == 0)
|
||||
fault(k);
|
||||
depth = 0;
|
||||
escapes++;
|
||||
siglongjmp(main_env, 1);
|
||||
}
|
||||
|
||||
static void trap(int sig, siginfo_t *info, void *context) {
|
||||
(void)sig;
|
||||
(void)info;
|
||||
(void)context;
|
||||
returns++;
|
||||
}
|
||||
|
||||
static void install(int onstack) {
|
||||
struct sigaction action;
|
||||
memset(&action, 0, sizeof(action));
|
||||
action.sa_sigaction = segv;
|
||||
action.sa_flags = SA_SIGINFO | SA_NODEFER | (onstack ? SA_ONSTACK : 0);
|
||||
sigaction(SIGSEGV, &action, NULL);
|
||||
}
|
||||
|
||||
static long run(long count, int with_trap) {
|
||||
long start = escapes;
|
||||
for (volatile long i = 0; i < count; i++) {
|
||||
if (with_trap) {
|
||||
volatile long before = i * 3;
|
||||
__asm__ volatile("int3" ::: "memory");
|
||||
if (before != i * 3)
|
||||
wrong++;
|
||||
}
|
||||
if (sigsetjmp(main_env, 1) == 0)
|
||||
fault(i);
|
||||
}
|
||||
return escapes - start;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
long want = argc > 1 ? atol(argv[1]) : 50000;
|
||||
stack_t ss = {.ss_sp = malloc(262144), .ss_size = 262144};
|
||||
struct sigaction action;
|
||||
sigaltstack(&ss, NULL);
|
||||
memset(&action, 0, sizeof(action));
|
||||
action.sa_sigaction = trap;
|
||||
action.sa_flags = SA_SIGINFO;
|
||||
sigaction(SIGTRAP, &action, NULL);
|
||||
|
||||
install(1);
|
||||
long onstack = run(want, 0);
|
||||
install(0);
|
||||
long offstack = run(want, 0);
|
||||
install(1);
|
||||
long mixed = run(want, 1);
|
||||
nested_mode = 1;
|
||||
long outer = run(want, 0);
|
||||
|
||||
printf("onstack=%ld offstack=%ld mixed=%ld returns=%ld outer=%ld nested=%ld wrong=%ld\n", onstack, offstack, mixed, returns,
|
||||
outer, nested, wrong);
|
||||
return onstack == want && offstack == want && mixed == want && returns == want && outer == want && nested == 3 * want && !wrong ? 0
|
||||
: 1;
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
#define _GNU_SOURCE
|
||||
#include <signal.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <sys/time.h>
|
||||
#include <ucontext.h>
|
||||
|
||||
#define MARK 0x5eed
|
||||
|
||||
static volatile sig_atomic_t alarms;
|
||||
static volatile sig_atomic_t give_up;
|
||||
|
||||
static void count_alarm(void) {
|
||||
if (++alarms > 100) {
|
||||
give_up = 1;
|
||||
}
|
||||
}
|
||||
|
||||
static void on_alarm(int sig, siginfo_t *si, void *ctx) {
|
||||
(void)sig;
|
||||
(void)si;
|
||||
ucontext_t *uc = ctx;
|
||||
count_alarm();
|
||||
#ifdef __x86_64__
|
||||
uc->uc_mcontext.gregs[REG_R12] = MARK;
|
||||
#else
|
||||
uc->uc_mcontext.gregs[REG_ESI] = MARK;
|
||||
#endif
|
||||
}
|
||||
|
||||
#ifdef __i386__
|
||||
static void on_alarm_legacy(int sig, struct sigcontext sc) {
|
||||
(void)sig;
|
||||
count_alarm();
|
||||
((volatile struct sigcontext *)&sc)->esi = MARK;
|
||||
}
|
||||
#endif
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
int legacy = argc > 1 && strcmp(argv[1], "legacy") == 0;
|
||||
struct sigaction sa;
|
||||
memset(&sa, 0, sizeof(sa));
|
||||
sa.sa_flags = SA_RESTART;
|
||||
#ifdef __i386__
|
||||
if (legacy) {
|
||||
sa.sa_handler = (void (*)(int))on_alarm_legacy;
|
||||
} else
|
||||
#endif
|
||||
{
|
||||
legacy = 0;
|
||||
sa.sa_sigaction = on_alarm;
|
||||
sa.sa_flags |= SA_SIGINFO;
|
||||
}
|
||||
sigaction(SIGALRM, &sa, NULL);
|
||||
struct itimerval it = {{0, 20000}, {0, 20000}};
|
||||
setitimer(ITIMER_REAL, &it, NULL);
|
||||
|
||||
unsigned long spins, seen;
|
||||
#ifdef __x86_64__
|
||||
__asm__ volatile("xor %%r12, %%r12\n"
|
||||
"xor %0, %0\n"
|
||||
"1: inc %0\n"
|
||||
"test %%r12, %%r12\n"
|
||||
"jnz 2f\n"
|
||||
"cmpl $0, %2\n"
|
||||
"je 1b\n"
|
||||
"2: mov %%r12, %1\n"
|
||||
: "=&r"(spins), "=&r"(seen)
|
||||
: "m"(give_up)
|
||||
: "r12", "cc");
|
||||
#else
|
||||
__asm__ volatile("xor %%esi, %%esi\n"
|
||||
"xor %0, %0\n"
|
||||
"1: inc %0\n"
|
||||
"test %%esi, %%esi\n"
|
||||
"jnz 2f\n"
|
||||
"cmpl $0, %2\n"
|
||||
"je 1b\n"
|
||||
"2: mov %%esi, %1\n"
|
||||
: "=&r"(spins), "=&r"(seen)
|
||||
: "m"(give_up)
|
||||
: "esi", "cc");
|
||||
#endif
|
||||
struct itimerval off = {{0, 0}, {0, 0}};
|
||||
setitimer(ITIMER_REAL, &off, NULL);
|
||||
printf("frame=%s seen=%d alarms=%d spins=%lu\n", legacy ? "legacy" : "rt", seen == MARK, (int)alarms, spins);
|
||||
return seen == MARK ? 0 : 1;
|
||||
}
|
||||
@@ -1,236 +0,0 @@
|
||||
#define _GNU_SOURCE
|
||||
#include <sched.h>
|
||||
#include <signal.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <ucontext.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#define REGIONS 11
|
||||
|
||||
extern char victim[], v_e1[], v_e2[], v_e3[], v_e4[], v_body[], v_x0[], v_x1[], v_x2[], v_x3[], v_x4[], v_end[];
|
||||
extern char caller_ret[], hijack_stub[], redirect_stub[];
|
||||
extern uint64_t caller_loop(uint64_t n);
|
||||
|
||||
volatile uint64_t saved_ret, saved_rip, stub_hits, redirect_hits;
|
||||
volatile uint64_t pending_hijack, pending_redirect, started;
|
||||
volatile uint64_t bad_rbp, bad_rbx, bad_r15;
|
||||
|
||||
__asm__(
|
||||
".text\n"
|
||||
".globl victim\n"
|
||||
"victim:\n"
|
||||
" push %rbp\n"
|
||||
".globl v_e1\nv_e1:\n push %r15\n"
|
||||
".globl v_e2\nv_e2:\n push %rbx\n"
|
||||
".globl v_e3\nv_e3:\n sub $0x18, %rsp\n"
|
||||
".globl v_e4\nv_e4:\n lea 0x28(%rsp), %rbp\n"
|
||||
".globl v_body\nv_body:\n"
|
||||
" mov $0x5a5a5a5a, %rbx\n"
|
||||
" mov $0xa5a5a5a5, %r15\n"
|
||||
" mov $24, %ecx\n"
|
||||
"1:\n"
|
||||
" mov %rcx, (%rsp)\n"
|
||||
" mov %rbx, 8(%rsp)\n"
|
||||
" push %rcx\n"
|
||||
" push %rbx\n"
|
||||
" pop %rbx\n"
|
||||
" pop %rcx\n"
|
||||
" mov -0x20(%rbp), %rdx\n"
|
||||
" add %rdx, %rbx\n"
|
||||
" dec %ecx\n"
|
||||
" jnz 1b\n"
|
||||
".globl v_x0\nv_x0:\n add $0x18, %rsp\n"
|
||||
".globl v_x1\nv_x1:\n pop %rbx\n"
|
||||
".globl v_x2\nv_x2:\n pop %r15\n"
|
||||
".globl v_x3\nv_x3:\n pop %rbp\n"
|
||||
".globl v_x4\nv_x4:\n ret\n"
|
||||
".globl v_end\nv_end:\n"
|
||||
" int3\n"
|
||||
|
||||
".globl caller_loop\n"
|
||||
"caller_loop:\n"
|
||||
" push %rbp\n push %rbx\n push %r15\n push %r12\n"
|
||||
" mov %rdi, %r12\n"
|
||||
" movq $1, started(%rip)\n"
|
||||
" movabs $0x1122334455667788, %rbp\n"
|
||||
" movabs $0x2233445566778899, %rbx\n"
|
||||
" movabs $0x33445566778899aa, %r15\n"
|
||||
"2:\n"
|
||||
" call victim\n"
|
||||
".globl caller_ret\ncaller_ret:\n"
|
||||
" movabs $0x1122334455667788, %rax\n"
|
||||
" cmp %rax, %rbp\n jne 3f\n"
|
||||
" movabs $0x2233445566778899, %rax\n"
|
||||
" cmp %rax, %rbx\n jne 3f\n"
|
||||
" movabs $0x33445566778899aa, %rax\n"
|
||||
" cmp %rax, %r15\n jne 3f\n"
|
||||
" dec %r12\n jnz 2b\n"
|
||||
" xor %eax, %eax\n jmp 4f\n"
|
||||
"3:\n"
|
||||
" mov %rbp, bad_rbp(%rip)\n mov %rbx, bad_rbx(%rip)\n mov %r15, bad_r15(%rip)\n"
|
||||
" mov %r12, %rax\n"
|
||||
"4:\n"
|
||||
" pop %r12\n pop %r15\n pop %rbx\n pop %rbp\n ret\n"
|
||||
|
||||
".globl hijack_stub\n"
|
||||
"hijack_stub:\n"
|
||||
" push saved_ret(%rip)\n"
|
||||
" pushfq\n"
|
||||
" lock incq stub_hits(%rip)\n"
|
||||
" movq $0, pending_hijack(%rip)\n"
|
||||
" popfq\n"
|
||||
" ret\n"
|
||||
|
||||
".globl redirect_stub\n"
|
||||
"redirect_stub:\n"
|
||||
" push saved_rip(%rip)\n"
|
||||
" pushfq\n"
|
||||
" lock incq redirect_hits(%rip)\n"
|
||||
" movq $0, pending_redirect(%rip)\n"
|
||||
" popfq\n"
|
||||
" ret\n");
|
||||
|
||||
struct region {
|
||||
char *at;
|
||||
char *end;
|
||||
long slot;
|
||||
const char *name;
|
||||
};
|
||||
|
||||
static struct region regions[REGIONS];
|
||||
static volatile uint64_t seen[REGIONS], mismatch[REGIONS], frame_bad, outside, handled, hijacks, redirects;
|
||||
static int mode;
|
||||
static volatile pid_t worker_tid;
|
||||
static volatile int done;
|
||||
static uint64_t iters, result;
|
||||
|
||||
static void setup_regions(void) {
|
||||
struct region r[REGIONS] = {
|
||||
{victim, v_e1, 0, "e0"}, {v_e1, v_e2, 8, "e1"}, {v_e2, v_e3, 16, "e2"}, {v_e3, v_e4, 24, "e3"},
|
||||
{v_e4, v_body, 48, "e4"}, {v_body, v_x0, 48, "body"}, {v_x0, v_x1, 48, "x0"}, {v_x1, v_x2, 24, "x1"},
|
||||
{v_x2, v_x3, 16, "x2"}, {v_x3, v_x4, 8, "x3"}, {v_x4, v_end, 0, "x4"}};
|
||||
memcpy(regions, r, sizeof(r));
|
||||
}
|
||||
|
||||
static void on_signal(int sig, siginfo_t *si, void *ctx) {
|
||||
(void)sig;
|
||||
(void)si;
|
||||
handled++;
|
||||
greg_t *g = ((ucontext_t *)ctx)->uc_mcontext.gregs;
|
||||
char *rip = (char *)g[REG_RIP];
|
||||
uint64_t rsp = g[REG_RSP];
|
||||
int i;
|
||||
for (i = 0; i < REGIONS; i++) {
|
||||
if (rip >= regions[i].at && rip < regions[i].end) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if ((mode & 2) && !pending_redirect && ((handled & 1) || !(mode & 1))) {
|
||||
pending_redirect = 1;
|
||||
saved_rip = (uint64_t)rip;
|
||||
g[REG_RIP] = (greg_t)redirect_stub;
|
||||
redirects++;
|
||||
if (i == REGIONS) {
|
||||
outside++;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (i == REGIONS) {
|
||||
outside++;
|
||||
return;
|
||||
}
|
||||
seen[i]++;
|
||||
uint64_t *slot = (uint64_t *)(rsp + regions[i].slot);
|
||||
if (i == 5) {
|
||||
uint64_t rbp = g[REG_RBP];
|
||||
slot = (uint64_t *)(rbp + 8);
|
||||
if (rsp != rbp - 0x28 && rsp != rbp - 0x30 && rsp != rbp - 0x38) {
|
||||
frame_bad++;
|
||||
}
|
||||
}
|
||||
uint64_t val = *slot;
|
||||
if (val != (uint64_t)caller_ret && val != (uint64_t)hijack_stub) {
|
||||
mismatch[i]++;
|
||||
return;
|
||||
}
|
||||
if ((mode & 1) && !pending_hijack && val == (uint64_t)caller_ret) {
|
||||
pending_hijack = 1;
|
||||
saved_ret = val;
|
||||
*slot = (uint64_t)hijack_stub;
|
||||
hijacks++;
|
||||
}
|
||||
}
|
||||
|
||||
static void on_fault(int sig, siginfo_t *si, void *ctx) {
|
||||
greg_t *g = ((ucontext_t *)ctx)->uc_mcontext.gregs;
|
||||
char line[256];
|
||||
int n = snprintf(line, sizeof(line), "fault sig=%d addr=%p rip=%#llx rsp=%#llx victim=%p saved_rip=%#llx saved_ret=%#llx\n", sig, si->si_addr,
|
||||
(unsigned long long)g[REG_RIP], (unsigned long long)g[REG_RSP], (void *)victim, (unsigned long long)saved_rip,
|
||||
(unsigned long long)saved_ret);
|
||||
if (n > 0 && write(1, line, (size_t)n) < 0) {
|
||||
_exit(4);
|
||||
}
|
||||
_exit(3);
|
||||
}
|
||||
|
||||
static int worker(void *arg) {
|
||||
(void)arg;
|
||||
worker_tid = syscall(SYS_gettid);
|
||||
result = caller_loop(iters);
|
||||
done = 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
iters = argc > 1 ? strtoull(argv[1], 0, 0) : 300000;
|
||||
mode = argc > 2 ? atoi(argv[2]) : 3;
|
||||
setup_regions();
|
||||
struct sigaction sa;
|
||||
memset(&sa, 0, sizeof(sa));
|
||||
sa.sa_sigaction = on_signal;
|
||||
sa.sa_flags = SA_SIGINFO | SA_RESTART;
|
||||
sigemptyset(&sa.sa_mask);
|
||||
sigaction(SIGRTMIN, &sa, NULL);
|
||||
sa.sa_sigaction = on_fault;
|
||||
sigaction(SIGSEGV, &sa, NULL);
|
||||
sigaction(SIGBUS, &sa, NULL);
|
||||
sigaction(SIGILL, &sa, NULL);
|
||||
sigaction(SIGTRAP, &sa, NULL);
|
||||
static char stack[1 << 20] __attribute__((aligned(16)));
|
||||
if (clone(worker, stack + sizeof(stack), CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_THREAD | CLONE_SYSVSEM, NULL) < 0) {
|
||||
perror("clone");
|
||||
return 2;
|
||||
}
|
||||
while (!worker_tid || !started) {
|
||||
}
|
||||
uint64_t sent = 0, seed = 88172645463325252ULL;
|
||||
pid_t pid = getpid();
|
||||
while (!done) {
|
||||
uint64_t before = handled;
|
||||
syscall(SYS_tgkill, pid, worker_tid, SIGRTMIN);
|
||||
sent++;
|
||||
while (handled == before && !done) {
|
||||
}
|
||||
seed = seed * 6364136223846793005ULL + 1442695040888963407ULL;
|
||||
for (volatile int k = (int)((seed >> 33) % 4000); k > 0; k--) {
|
||||
}
|
||||
}
|
||||
uint64_t bad = 0;
|
||||
for (int i = 0; i < REGIONS; i++) {
|
||||
printf("%s seen=%llu mismatch=%llu\n", regions[i].name, (unsigned long long)seen[i], (unsigned long long)mismatch[i]);
|
||||
bad += mismatch[i];
|
||||
}
|
||||
printf("sent=%llu outside=%llu hijacks=%llu stub_hits=%llu redirects=%llu redirect_hits=%llu frame_bad=%llu left=%llu\n",
|
||||
(unsigned long long)sent, (unsigned long long)outside, (unsigned long long)hijacks, (unsigned long long)stub_hits,
|
||||
(unsigned long long)redirects, (unsigned long long)redirect_hits, (unsigned long long)frame_bad, (unsigned long long)result);
|
||||
int fail = result || bad || frame_bad || hijacks > stub_hits + 1 || redirects > redirect_hits + 1;
|
||||
if (result) {
|
||||
printf("corrupt rbp=%#llx rbx=%#llx r15=%#llx\n", (unsigned long long)bad_rbp, (unsigned long long)bad_rbx, (unsigned long long)bad_r15);
|
||||
}
|
||||
printf("%s\n", fail ? "FAIL" : "PASS");
|
||||
return fail;
|
||||
}
|
||||
Loaded 100 of 131 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user