Compare commits

...
Author SHA1 Message Date
The412Banner 2c6ac10509 fix(gamescope): present only to a shown SDL window so KWin never drops a windowed game 2026-11-23 00:28:11 +00:00
DeathKhan 6ef8e2274e fix(ui): focused cards keep their solid ground under the highlight tint (#2909) 2026-11-22 17:11:29 -05:00
Kurt Himebauch 00525cde15 fix(session): picking a bottom-screen mode clears the menu restore left by a teardown (#3007) 2026-11-22 17:07:23 -05:00
MaxsTechReview 210c127446 feat(addons): add a CurseForge source to the addon browser (#3028)
* feat(addons): add a CurseForge source to the addon browser

Search and install CurseForge addons from the Download addons window by
driving the installed CurseForge app in the background: it starts minimized
on the session's X display with its inspector bound to 127.0.0.1, and the
window's own renderer services handle game detection, search, install and
shutdown. Sign-in stays inside the CurseForge app.

The Install buttons in the addon list now size to their label, so the label
is centered and the button matches the other compact buttons.

* fix(curseforge): secret inspector URL, hold mode and serialised starts

- Start CurseForge with its Node inspector on 127.0.0.1:0 and publish only
  the UUID websocket URL, kept in the 0700 state directory, so no fixed
  unauthenticated debug port is exposed.
- The agent evaluates through that URL instead of a fixed port.
- Add a hold mode that runs as a session program and stops the app on
  exit, and a lock so hold and start never launch twice.

* feat(addons): run CurseForge in a hidden session when none is running

- Opening the CurseForge source with no session starts one headlessly
  (offscreen compositor output, shared start path with SessionActivity via
  CompositorHost) running the CurseForge hold helper; leaving the dialog
  stops the app and that session. A session the user already had is
  reused and left running.
- Drop the "start a session" notice from every locale.
- Addon browser link: cleanup shares the link's lock off the UI thread,
  stops the app at once on close, refuses work after close and stops a
  launch that finishes after close.
- CurseForgeApp.start stops the app before every failed return.
- instanceFor returns no instance when the populated list has no match.

* Harden headless CurseForge session and helper lifecycle

Scope the hidden session to its id, roll back partial starts, release the
offscreen reader once the session ends, re-acquire the inspector when its
endpoint goes away, bound DevTools calls by one deadline, key the installed
snapshot by target, track the helper launch by pid start time and directory,
fail on lock errors, and update the HDR gate test to its new location.

* Map DevTools send failures and recheck the hidden session id

* fix(addons): bind the hidden session to the id it claims at launch

* Keep the CurseForge helper quiet when no launch is recorded
2026-11-22 17:02:35 -05:00
Tushar Gandhe 234e40157e feat(launcher): LT and RT step between the main tabs from anywhere in the launcher (#3035)
* feat(launcher): LT and RT step between the main tabs from anywhere in the launcher

LT and RT move to the previous and next main tab on every layout. The activity handles them before any page sees the key, so a focused control, an embedded Android view such as the terminal, or nothing being focused no longer swallows them; dialogs and popups keep their own keys. Pads that report the triggers only as axes, like the Xbox Wireless Controller, get an L2/R2 press when a trigger passes 60% of its travel; pads that send their own trigger keys are left alone.

* fix(launcher): trigger tab steps tick, drop a pending press on focus loss, and move once per pull

Controller haptics now ticks for L2 and R2. A synthetic trigger press waiting its 40 ms is cancelled when the launcher loses window focus or is destroyed, so a dialog that opens in between keeps the page behind it. Each pull is tracked: when a synthetic press has gone out, the pad's own trigger key for the same pull is swallowed instead of stepping a second tab.
2026-11-22 16:59:01 -05:00
Tushar Gandhe c3809c0a75 fix(ui): keep the Agent composer above the keyboard and release search fields on tap (#2852)
* fix(agent): keep the composer above the keyboard outside fullscreen

* fix(ui): release a search field when another control is tapped

* fix(ui): release the add-on search field in its dialog, and let a reopened search take focus

* fix(ui): a drag that returns to where it began does not release the search field
2026-11-22 16:58:57 -05:00
Tushar Gandhe 71b7b6efad fix(library): put the store accounts button on the right of the source chips, as on other pages (#2929) 2026-11-22 16:58:53 -05:00
Tushar Gandhe a0e7c1715a fix(ui): smaller game page link pills with a gap between rows (#2973) 2026-11-22 16:58:49 -05:00
MaxsTechReview 2c2d55058e fix(preload): open synthesized socket tables when the fd reopen is denied (#3034) 2026-11-22 16:20:34 -05:00
MaxsTechReview 7f61e514e6 chore: pin gamescope to the release with the opacity focus fix (#3031) 2026-11-22 14:27:08 -05:00
MaxsTechReview b891019b87 fix(steam-x64): keep the session's GL thunk for the x86 web helper (#3027)
* fix(steam-x64): keep the session's GL thunk for the x86 web helper

FEX's global AppConfig for steamwebhelper turns the GL thunk off and is
read after FEX_THUNKCONFIG, so the x86 helper used the rootfs's x86 Mesa.
Steam's browser compositor creates its window through SDL3 and GLX in
the helper's browser process, x86 Mesa faulted in driCreateNewScreen3
(SIGSEGV) about 11 s after each start, and the client restarted the
helper every 12 s.

For every global FEX AppConfig that turns off a thunk the session uses,
the launcher writes a local AppConfig with the session's thunk set. It
leaves local files with other content alone and removes its own files
when the client runs in software.

* fix(steam-x64): write FEX AppConfig overrides atomically

* fix(steam-x64): stage AppConfig overrides in a unique temporary file

* fix(steam-x64): publish AppConfig overrides without replacing a newer file
2026-11-22 14:16:34 -05:00
MaxsTechReview 1a29c65d4f fix(gamescope): choose focus again when a window's opacity crosses zero (#3030)
A window is a focus candidate only while _NET_WM_WINDOW_OPACITY is above
zero, but a change of that property never re-ran focus selection. A
layered window that maps fully transparent and fades in was skipped at
map time and stayed skipped once opaque, so a nested desktop session
hid its gamescope window and the game ran with nothing on screen.
2026-11-22 13:47:22 -05:00
MaxsTechReview ff5e4c7ac7 fix(preload): accept NETLINK_ROUTE multicast subscriptions (#3015)
* fix(preload): accept NETLINK_ROUTE multicast subscriptions

Programs that watch for network changes bind their route socket with
multicast groups or join them with NETLINK_ADD_MEMBERSHIP. The emulated
socket refused both with EACCES, and .NET's NetworkChange treats that as
fatal: CurseForge's Mods Agent failed to initialise with "Permission
denied" from NetworkChange.CreateSocket(), so the app never loaded its
library.

Real Linux lets unprivileged sockets join rtnetlink groups. Accept the
groups at bind and through ADD/DROP_MEMBERSHIP, report them from
getsockname(), and keep queries on the same socket working. No change
events are generated yet; queries still return the current snapshot.

* fix(preload): keep netlink group membership in the shared socket state

Memberships now live in the peer metadata the kernel holds for the socket, next to the port and cap ack, so they survive exec and a change made by one process after fork is seen by every process holding the socket.

* fix(session): answer denied /proc/net socket tables

Android's SELinux policy denies app processes every file under /proc/net.
.NET lists TCP listeners from /proc/net/tcp and tcp6 before it binds a
server port, so the CurseForge Mods Agent failed on every port with
"An error was encountered while querying information from the operating
system" on stock firmware. Denied tcp, tcp6, udp and udp6 reads now get a
header-only table, through open and openat as well as fopen, the same way
the route and interface tables already are.

* fix(session): keep synthesized socket tables read-only and file-only

Reopen the populated table read-only instead of duplicating its writable
descriptor, and leave O_DIRECTORY opens with their original failure.
2026-11-22 13:37:44 -05:00
MaxsTechReview 2d38f11b36 Build FEX's latest release, point releases included (#3026)
The FEX build pinned FEX-2610 and its tag checks only accepted four
digits, so FEX-2611.1 was never picked up. The build now takes the
latest release tag, and Fixed-upstream compares the four-digit release.
CMake 4.5 rejects DEPENDS in install(CODE), which stopped host thunk
builds; patch 0007 drops it.
2026-11-22 13:03:43 -05:00
MaxsTechReview fd2e1652ad fix(fex): invalidate translated code written through a later writable alias (#3020)
* fix(fex): invalidate translated code written through a later writable alias

x86-64 CoreCLR maps its W^X memfd writable after the executable view was
translated. Under SMCChecks=mtrack the new alias was never write-protected,
so writes through it did not invalidate stale translations. Protect the
overlapping part of an executable alias on mmap and mprotect.

* fix(fex): protect every writable alias in one mprotect range and build fmt without modules

* fix(fex): build without C++ module scanning or import std
2026-11-22 12:22:11 -05:00
84 changed files with 2548 additions and 144 deletions

No files matched your search

+4 -1
View File
@@ -29,11 +29,14 @@ 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
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
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
sudo chown -R "$(id -u):$(id -g)" .
- uses: actions/upload-artifact@v4
with:
@@ -17,8 +17,11 @@ 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
@@ -2013,6 +2016,7 @@ 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()
@@ -2042,6 +2046,36 @@ 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) {
@@ -2052,6 +2086,14 @@ 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)) {
@@ -2069,9 +2111,12 @@ 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)
}
@@ -2201,6 +2246,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
override fun onDestroy() {
triggerKeys.cancel()
gameLaunchRequest.incrementAndGet()
cancelCompatLaunch()
updates.unregister()
@@ -2846,17 +2846,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (!SessionState.running) {
SessionEvents.transition(SessionPhase.STARTING_COMPOSITOR, "compositor.starting")
}
val runtimeDir = File(filesDir, ".wayland-rt").apply { mkdirs() }
FileUtils.copyAsset(this, "wayland/keymap.xkb", File(runtimeDir, "keymap.xkb"))
com.droiddeck.launcher.input.VrControllers.publish(this)
val turnip = TurnipDriver(this)
com.droiddeck.launcher.gpu.DriverSetupLog.write(this, "surface.driver-setup")
if (!CompositorHost.isStarted) {
CompositorHost.displayChoice = SessionPrefs.androidDriver(this)
com.droiddeck.launcher.gpu.AutoDriverTrial.displayStarting(this, SessionPrefs.androidDriver(this))
}
val driverId = if (CompositorHost.isStarted) null else turnip.install()
val output = CompositorHost.prepare(this)
val previous = SessionState.outputSize
val live = windowOutputSize(holder.surfaceFrame.width(), holder.surfaceFrame.height())
@@ -2883,15 +2873,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
pushCardboard(activeCardboard)
WaylandCompositor.nativeSetCardboardPoseFile(File(filesDir, ".wayland-rt/droiddeck-headpose").path)
com.droiddeck.launcher.glasses.SpatialTracking.attachPublisher(File(filesDir, ".wayland-rt/droiddeck-spatialpose").path)
if (!SessionState.running) {
val waylandLog = File(SessionPaths.beginOrCurrent(this), "wayland.log")
WaylandCompositor.setSessionLogFile(waylandLog)
try {
android.system.Os.setenv("DD_WAYLAND_LOG", waylandLog.path, true)
} catch (e: Exception) {
Log.w(TAG, "could not point the compositor's log at $waylandLog", e)
}
}
if (!SessionState.running) CompositorHost.logToSession(this)
val mode = hdrPrefMode()
if (probe != null) {
WaylandCompositor.nativeSetHdrDisplay(
@@ -2911,19 +2893,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
)
Log.i(TAG, "hdr: " + (if (tonemap) "tone-mapped (${probe.reason})" else if (capable) "available" else "unavailable") + " · display ${probe.formats.ifEmpty { "SDR" }}")
}
if (!SessionState.running) {
val on = SessionState.hdrCapable && SessionPrefs.hdr(this, mode)
SessionState.hdr = on
WaylandCompositor.nativeSetHdrOutput(on)
WaylandCompositor.nativeSetZeroCopy(on || SessionPrefs.zeroCopy(this, mode))
Log.i(TAG, "hdr: " + (if (on) "on" else "off") + " for this $mode session")
}
com.droiddeck.launcher.gpu.DriverSetupLog.write(this, "compositor.start driver=$driverId")
CompositorHost.startOrAttach(
this, holder.surface, runtimeDir.path,
driverId?.let { turnip.driverPath(it) }, driverId?.let { turnip.libraryName(it) },
applicationInfo.nativeLibraryDir, size.first, size.second, refreshHz(holder), outputFpsLimit(),
)
if (!SessionState.running) CompositorHost.applyHdr(this, mode)
CompositorHost.start(this, output, holder.surface, size, refreshHz(holder), outputFpsLimit())
onOutputAttached(holder)
if (SessionState.running && size != previous) {
Log.i(TAG, "output resized: ${previous.first}x${previous.second} -> ${size.first}x${size.second} on a new surface")
@@ -4476,6 +4447,7 @@ 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)
}
@@ -0,0 +1,81 @@
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,10 +1,216 @@
package com.droiddeck.launcher.runtime
import android.content.Context
import com.droiddeck.launcher.agent.AgentException
import com.droiddeck.launcher.agent.AgentGuest
import org.json.JSONArray
import org.json.JSONObject
import java.time.Instant
object CurseForgeApp {
const val NAME = "CurseForge"
const val FEED = "https://curseforge.overwolf.com/electron/linux/latest-linux.yml"
internal const val WOW = 1
const val HELPER = "/usr/local/bin/droiddeck-curseforge"
private const val READY_MS = 120_000L
private const val INSTALL_MS = 300_000L
enum class Start { READY, BUSY, NO_DISPLAY, FAILED }
class Started(val state: Start, val inspector: String? = null)
private val INSPECTOR = Regex("ws://127\\.0\\.0\\.1:[0-9]{4,5}/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
class Failure(message: String, val code: String? = null) : Exception(message) {
val gone get() = code == "DEVTOOLS_UNREACHABLE"
}
fun find(apps: List<UserApps.App>): UserApps.App? = apps.firstOrNull { it.feed == FEED }
fun request(): UserApps.Request = UserApps.Request(UserApps.Source.Feed(FEED), NAME, null)
internal fun dir(app: UserApps.App): String? = app.args.firstOrNull()?.takeIf { it.startsWith("/") }
fun holdArgs(app: UserApps.App): List<String>? = dir(app)?.let { listOf("hold", it) }
internal fun inspectorUrl(stdout: String): String? = stdout.lineSequence().map { it.trim() }.lastOrNull { INSPECTOR.matches(it) }
internal fun startState(exitCode: Int): Start = when (exitCode) {
0 -> Start.READY
3 -> Start.BUSY
4 -> Start.NO_DISPLAY
else -> Start.FAILED
}
internal fun sortOf(sort: WowAddonCatalog.Sort): Pair<Int, Int> = when (sort) {
WowAddonCatalog.Sort.POPULAR -> 8 to 2
WowAddonCatalog.Sort.UPDATED -> 16 to 2
WowAddonCatalog.Sort.NAME -> 1 to 1
WowAddonCatalog.Sort.DOWNLOADS -> 7 to 2
}
internal fun searchRequest(guid: String, text: String, sort: WowAddonCatalog.Sort, page: Int): JSONObject {
val (column, order) = sortOf(sort)
return JSONObject().put("gameId", WOW).put("searchText", text.trim()).put("page", page + 1)
.put("sortColumn", column).put("sortOrder", order).put("gameInstanceGuid", guid)
}
internal fun installRequest(guid: String, projectId: String): JSONObject =
JSONObject().put("instanceId", guid).put("projectId", projectId.toLong()).put("categoryClassId", 1)
.put("installLatestFile", true).put("installSource", 4)
private const val SERVICES = """(() => {
const seen = new Set(), out = {};
const walk = (o, d) => {
if (!o || typeof o !== 'object' || seen.has(o) || d > 4) return;
seen.add(o);
if (typeof o._nameOfService === 'string') { out[o._nameOfService] = o; return; }
let keys; try { keys = Object.keys(o); } catch (e) { return; }
for (const k of keys.slice(0, 4000)) {
let v; try { v = o[k]; } catch (e) { continue; }
if (v instanceof Map) { for (const x of v.values()) walk(x, d + 1); } else walk(v, d + 1);
}
};
walk(window, 0);
return out;
})()"""
internal fun expression(service: String, method: String, args: JSONArray?, pick: String = "r => r"): String {
val name = JSONObject.quote(method)
val run = if (args == null) "true" else "($pick)(await s[$name](...$args))"
val inner = "(async () => { const s = $SERVICES[${JSONObject.quote(service)}]; " +
"if (!s || typeof s[$name] !== 'function') return { missing: true }; " +
"return { value: $run }; })()"
return "(() => { const w = require('electron').BrowserWindow.getAllWindows()" +
".find(w => !w.isDestroyed() && w.webContents.getURL().includes('desktop.html')); " +
"if (!w) return JSON.stringify({ missing: true }); " +
"return w.webContents.executeJavaScript(${JSONObject.quote(inner)}).then(v => JSON.stringify(v)); })()"
}
internal fun unwrap(answer: JSONObject): Any? {
if (!answer.optBoolean("ok")) {
val error = answer.optJSONObject("error")
throw Failure(error?.optString("message")?.takeIf { it.isNotBlank() } ?: answer.toString(), error?.optString("code")?.takeIf { it.isNotBlank() })
}
val text = answer.opt("value") as? String ?: throw Failure("CurseForge gave no answer")
val reply = JSONObject(text)
if (reply.optBoolean("missing")) throw Failure("CurseForge is not ready")
return reply.opt("value")
}
internal fun parseSearch(value: Any?): WowAddonCatalog.Page {
val reply = value as? JSONObject ?: throw Failure("CurseForge search failed")
if (reply.has("success") && !reply.optBoolean("success")) throw Failure("CurseForge search failed")
val mods = reply.optJSONArray("mods") ?: JSONArray()
val items = (0 until mods.length()).mapNotNull { mods.optJSONObject(it) }.mapNotNull { mod ->
val id = mod.optLong("id", 0L).takeIf { it > 0 } ?: return@mapNotNull null
val name = mod.optString("name").takeIf { it.isNotBlank() } ?: return@mapNotNull null
val author = mod.optJSONObject("primaryAuthor")?.optString("name")?.takeIf { it.isNotBlank() }
?: mod.optJSONArray("authors")?.optJSONObject(0)?.optString("name").orEmpty()
val date = mod.optJSONObject("updateVersion")?.optString("fileDate")?.takeIf { it.isNotBlank() }
?: mod.optString("projectLatestReleaseDate")
WowAddonCatalog.Addon(
id.toString(), name, author, "", mod.optLong("downloads", 0L).coerceAtLeast(0L),
runCatching { Instant.parse(date).toEpochMilli() }.getOrDefault(0L),
mod.optString("thumbnailUrl").takeIf { WowAddonCatalog.isHttps(it) },
)
}
val page = reply.optJSONObject("pagination")
val more = page != null && page.optInt("index") + page.optInt("resultCount") < page.optInt("totalCount")
return WowAddonCatalog.Page(items, more)
}
internal fun samePath(a: String, b: String) = a.trimEnd('/') == b.trimEnd('/')
internal fun instanceFor(instances: Any?, flavorDir: String, detected: String?): String? {
val list = instances as? JSONArray
val match = list?.let { all ->
(0 until all.length()).mapNotNull { all.optJSONObject(it) }
.firstOrNull { samePath(it.optString("installPath"), flavorDir) }?.optString("guid")
}
if (list != null && list.length() > 0) return match?.takeIf { it.isNotBlank() }
return detected?.takeIf { it.isNotBlank() }
}
internal fun projectIds(value: Any?): Set<String> {
val list = value as? JSONArray ?: return emptySet()
return (0 until list.length()).mapNotNull { list.opt(it)?.toString()?.takeIf { id -> id.isNotBlank() && id != "null" } }.toSet()
}
private fun call(context: Context, inspector: String, service: String, method: String, args: JSONArray?, timeoutMs: Long, pick: String = "r => r"): Any? {
val request = JSONObject().put("kind", "cdp").put("inspector", inspector).put("commandLineApi", true)
.put("expression", expression(service, method, args, pick)).put("timeout", timeoutMs / 1000.0)
return unwrap(AgentGuest.call(context, request, timeoutMs + 3_000, trusted = true))
}
private fun helper(context: Context, command: String, dir: String, timeoutMs: Long): JSONObject? {
val request = JSONObject().put("kind", "exec").put("argv", JSONArray(listOf(HELPER, command, dir))).put("timeout", timeoutMs / 1000.0)
return runCatching { AgentGuest.call(context, request, timeoutMs + 5_000, trusted = true) }.getOrNull()
}
fun start(context: Context, app: UserApps.App): Started {
val dir = dir(app) ?: return Started(Start.FAILED)
val answer = helper(context, "start", dir, 90_000)
if (answer == null || !answer.optBoolean("ok") || answer.optBoolean("timedOut")) {
stop(context, app, null)
return Started(Start.FAILED)
}
val state = startState(answer.optInt("exitCode", -1))
if (state == Start.BUSY || state == Start.NO_DISPLAY) return Started(state)
val inspector = inspectorUrl(answer.optJSONObject("stdout")?.optString("text").orEmpty())
if (state != Start.READY || inspector == null) {
stop(context, app, null)
return Started(Start.FAILED)
}
val deadline = System.currentTimeMillis() + READY_MS
while (System.currentTimeMillis() < deadline) {
val ready = runCatching { call(context, inspector, "InstalledProjectsAppService", "installAddon", null, 10_000) }
if (ready.isSuccess) return Started(Start.READY, inspector)
val error = ready.exceptionOrNull()
if (error is AgentException && error.code == "NO_ACTIVE_SESSION") break
Thread.sleep(1_000)
}
stop(context, app, inspector)
return Started(Start.FAILED)
}
fun stop(context: Context, app: UserApps.App, inspector: String?) {
val dir = dir(app) ?: return
if (inspector != null) runCatching { call(context, inspector, "CoreService", "shutdown", JSONArray(), 30_000, "r => true") }
helper(context, "stop", dir, 30_000)
}
private fun connect(context: Context, inspector: String) {
call(context, inspector, "CoreService", "connect", JSONArray(), 120_000, "r => true")
}
fun instance(context: Context, inspector: String, root: String, flavorDir: String): String {
connect(context, inspector)
val detected = call(context, inspector, "GameDetectionAppService", "detectGameFromPath", JSONArray().put(root).put(WOW), 60_000) as? JSONObject
val instances = call(context, inspector, "GameAppService", "getGameInstances", JSONArray().put(WOW), 30_000,
"r => (r || []).map(i => ({ guid: i.guid, installPath: i.installPath }))")
return instanceFor(instances, flavorDir, detected?.optString("gameInstanceGuid")) ?: throw Failure("CurseForge did not find $flavorDir")
}
fun search(context: Context, inspector: String, guid: String, text: String, sort: WowAddonCatalog.Sort, page: Int): WowAddonCatalog.Page =
parseSearch(call(context, inspector, "ProjectAppService", "search", JSONArray().put(searchRequest(guid, text, sort, page)), 60_000))
fun installed(context: Context, inspector: String, guid: String): Set<String> {
connect(context, inspector)
return projectIds(call(context, inspector, "InstalledProjectsAppService", "getProjects", JSONArray().put(guid), 30_000, "r => (r || []).map(p => String(p.id))"))
}
fun install(context: Context, inspector: String, guid: String, projectId: String): Boolean {
connect(context, inspector)
if (call(context, inspector, "InstalledProjectsAppService", "installAddon", JSONArray().put(installRequest(guid, projectId)), 300_000) != true) return false
val deadline = System.currentTimeMillis() + INSTALL_MS
while (System.currentTimeMillis() < deadline) {
val listed = runCatching { installed(context, inspector, guid) }
val error = listed.exceptionOrNull()
if (error is Failure && error.gone || error is AgentException && error.code == "NO_ACTIVE_SESSION") throw error
if (projectId in listed.getOrDefault(emptySet())) return true
Thread.sleep(1_000)
}
return false
}
}
@@ -93,8 +93,7 @@ object WowAddonCatalog {
Client(folder, version?.let(::flavorOf) ?: folderFamily(folder))
fun client(target: WowAddons.Target): Client {
val dir = target.addOns.parentFile?.parentFile
return client(target.flavor, dir?.let(::clientVersion))
return client(target.flavor, WowAddons.flavorDir(target)?.let(::clientVersion))
}
internal fun flavorMatches(flavors: Set<String>?, family: String?): Boolean =
@@ -28,6 +28,14 @@ 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)
@@ -0,0 +1,119 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.graphics.PixelFormat
import android.media.ImageReader
import android.os.Handler
import android.os.Looper
import android.util.Log
import com.droiddeck.launcher.agent.AgentGuest
import com.droiddeck.launcher.runtime.LinuxRuntimeInstaller
import com.droiddeck.launcher.storage.StorageState
import com.droiddeck.launcher.wayland.CompositorHost
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
object BackgroundSession {
private const val TAG = "BackgroundSession"
private const val WIDTH = 1280
private const val HEIGHT = 720
private const val REFRESH_HZ = 60f
private const val BEGIN_MS = 30_000L
private const val AGENT_MS = 120_000L
private const val STOP_MS = 30_000L
private val ended = setOf(SessionPhase.IDLE, SessionPhase.FAILED)
private val main by lazy { Handler(Looper.getMainLooper()) }
private var reader: ImageReader? = null
fun start(context: Context, program: String, args: List<String>): String? {
val app = context.applicationContext
val claim = AtomicBoolean(false)
val began = CountDownLatch(1)
var own: String? = null
main.post {
if (claim.compareAndSet(false, true)) {
own = runCatching { begin(app, program, args) }
.onFailure { Log.w(TAG, "could not start a hidden session for $program", it) }
.getOrNull()
}
began.countDown()
}
if (!began.await(BEGIN_MS, TimeUnit.MILLISECONDS) && claim.compareAndSet(false, true)) return null
began.await()
val session = own ?: return null
val deadline = System.currentTimeMillis() + AGENT_MS
val settle = System.currentTimeMillis() + 5_000
while (System.currentTimeMillis() < deadline) {
if (SessionState.sessionId != session) return null
if (SessionState.running && AgentGuest.hello(app) != null && SessionState.sessionId == session) return session
if (SessionState.phase == SessionPhase.FAILED) break
if (!SessionState.running && SessionState.phase in ended && System.currentTimeMillis() > settle) break
Thread.sleep(250)
}
stop(app, session)
return null
}
fun stop(context: Context, session: String) {
val app = context.applicationContext
if (SessionState.sessionId != session) return
main.post { if (SessionState.sessionId == session) SessionService.stop(app) }
val deadline = System.currentTimeMillis() + STOP_MS
while (live(session) && System.currentTimeMillis() < deadline) Thread.sleep(250)
if (!live(session)) {
main.post { release() }
return
}
Thread {
while (live(session)) Thread.sleep(1_000)
main.post { release() }
}.start()
}
private fun live(session: String) =
SessionState.sessionId == session && (SessionState.running || SessionState.phase !in ended)
private fun begin(context: Context, program: String, args: List<String>): String? {
if (SessionState.running || SessionState.phase !in ended || LinuxRuntimeInstaller.isBusy() ||
SessionState.installing != null || StorageState.cleaning) return null
release()
SessionEvents.begin(context, SessionService.MODE_RUN, SessionPaths.label(SessionService.MODE_RUN, program))
val session = SessionState.sessionId ?: return null
SessionState.stopRequested = false
SessionEvents.transition(SessionPhase.STARTING_COMPOSITOR, "compositor.starting")
var requested = false
try {
val output = CompositorHost.prepare(context)
val size = WIDTH to HEIGHT
SessionState.outputSize = size
SessionState.refreshHz = REFRESH_HZ
CompositorHost.logToSession(context)
CompositorHost.applyHdr(context, SessionPrefs.prefMode(SessionService.MODE_RUN))
val offscreen = ImageReader.newInstance(WIDTH, HEIGHT, PixelFormat.RGBA_8888, 2)
reader = offscreen
offscreen.setOnImageAvailableListener({ it.acquireLatestImage()?.close() }, main)
CompositorHost.start(context, output, offscreen.surface, size, REFRESH_HZ, 0)
CompositorHost.detach(offscreen.surface)
SessionEvents.record("compositor.started")
SessionEvents.transition(SessionPhase.STARTING_GUEST, "guest.starting")
requested = true
SessionService.start(context, SessionService.MODE_RUN, program, programArgs = args.toTypedArray())
return session
} catch (e: Exception) {
if (requested) SessionService.stop(context)
if (!SessionState.running) {
reader?.close()
reader = null
SessionEvents.transition(SessionPhase.FAILED, "hidden.failed", mapOf("error" to e.toString()))
}
throw e
}
}
private fun release() {
if (SessionState.running) return
reader?.close()
reader = null
}
}
@@ -180,6 +180,7 @@ object SessionFiles {
"usr/local/bin/droiddeck-flatpak-run" to "usr/local/bin/droiddeck-flatpak-run",
"usr/local/bin/droiddeck-appimage-run" to "usr/local/bin/droiddeck-appimage-run",
"usr/local/bin/droiddeck-appimage-exec" to "usr/local/bin/droiddeck-appimage-exec",
"usr/local/bin/droiddeck-curseforge" to "usr/local/bin/droiddeck-curseforge",
"usr/local/bin/droiddeck-script-run" to "usr/local/bin/droiddeck-script-run",
"usr/local/bin/droiddeck-open" to "usr/local/bin/droiddeck-open",
"usr/local/bin/droiddeck-proton-run" to "usr/local/bin/droiddeck-proton-run",
@@ -14,7 +14,6 @@ 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
@@ -28,6 +27,7 @@ import androidx.compose.material3.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
@@ -62,8 +62,13 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.AddedGames
import com.droiddeck.launcher.runtime.CurseForgeApp
import com.droiddeck.launcher.runtime.UserApps
import com.droiddeck.launcher.runtime.WowAddonCatalog
import com.droiddeck.launcher.runtime.WowAddons
import com.droiddeck.launcher.session.BackgroundSession
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
@@ -81,10 +86,101 @@ private class AddonResults {
private enum class AddonStatus { INSTALL, UPDATE, INSTALLED }
private enum class AddonSource { WOWI, CURSE }
private class CurseState(val notice: Int? = null) : Exception()
private class CurseLink(val app: UserApps.App) {
class Linked(val inspector: String, val guid: String)
private val lock = Object()
@Volatile private var closed = false
private var held = false
private var ownSession: String? = null
private var started = false
@Volatile private var launching = false
@Volatile private var inspector: String? = null
private val guids = HashMap<String, String>()
fun <T> call(context: Context, target: WowAddons.Target, block: (Linked) -> T): T {
val linked = synchronized(lock) { link(context, target) }
try {
return block(linked)
} catch (e: CurseForgeApp.Failure) {
if (e.gone) synchronized(lock) {
if (inspector == linked.inspector) {
inspector = null
guids.clear()
}
}
throw e
}
}
private fun link(context: Context, target: WowAddons.Target): Linked {
if (closed) throw CurseState()
if (!SessionState.running) {
started = false
launching = false
held = false
ownSession = null
inspector = null
guids.clear()
val args = CurseForgeApp.holdArgs(app) ?: throw CurseState()
ownSession = BackgroundSession.start(context, CurseForgeApp.HELPER, args) ?: throw CurseState()
}
if (closed) throw CurseState()
if (!held) {
held = true
SessionService.holdForSignIn(context, true)
}
val awake = System.currentTimeMillis() + 30_000
while ((SessionState.suspended || SessionState.suspending) && System.currentTimeMillis() < awake) Thread.sleep(250)
val url = inspector ?: run {
launching = true
val done = CurseForgeApp.start(context, app)
when (done.state) {
CurseForgeApp.Start.READY -> {
started = true
inspector = done.inspector
done.inspector ?: throw CurseState()
}
CurseForgeApp.Start.BUSY -> throw CurseState(R.string.addons_curse_busy)
else -> throw CurseState()
}
}
if (closed) throw CurseState()
guids[target.addOns.path]?.let { return Linked(url, it) }
val root = WowAddons.root(target)?.let { AddedGames.guestPath(context, it) } ?: throw CurseState()
val flavor = WowAddons.flavorDir(target)?.let { AddedGames.guestPath(context, it) } ?: throw CurseState()
val guid = CurseForgeApp.instance(context, url, root, flavor)
guids[target.addOns.path] = guid
return Linked(url, guid)
}
fun close(context: Context) {
closed = true
Thread {
if (launching) CurseForgeApp.stop(context, app, inspector)
synchronized(lock) {
if (started) CurseForgeApp.stop(context, app, inspector)
val owned = ownSession
if (owned != null) BackgroundSession.stop(context, owned)
else if (held) SessionService.holdForSignIn(context, false)
started = false
launching = false
ownSession = null
held = false
inspector = null
}
}.start()
}
}
private const val PAGES_AHEAD = 8
@Composable
internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAddons.Target, onDismiss: () -> Unit) {
internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAddons.Target, curseForge: UserApps.App?, onDismiss: () -> Unit) {
val context = LocalContext.current.applicationContext
val scope = rememberCoroutineScope()
val shown = rememberShown(onDismiss)
@@ -93,15 +189,30 @@ 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) }
val results = remember(text, category, sort, target) { AddonResults() }
var source by remember { mutableStateOf(AddonSource.WOWI) }
val curse = if (source == AddonSource.CURSE) curseForge else null
val link = remember(curseForge?.key) { curseForge?.let(::CurseLink) }
DisposableEffect(link) {
onDispose { link?.close(context) }
}
var notice by remember { mutableStateOf<Int?>(null) }
var curseInstalls by remember { mutableIntStateOf(0) }
val results = remember(text, category, sort, target, curse) { AddonResults() }
val 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 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 presentKey = curse to target.addOns
val snapshot by produceState(presentKey to emptyMap<String, String?>(), target.addOns, WowAddons.imports, curse, curseInstalls, results.items.isEmpty()) {
val into = target
val key = curse to into.addOns
value = key to withContext(Dispatchers.IO) {
if (curse != null && link != null) runCatching { link.call(context, into) { CurseForgeApp.installed(context, it.inspector, it.guid) }.associateWith { null } }.getOrDefault(emptyMap())
else WowAddons.details(into).mapNotNull { item -> item.wowiId?.let { it to item.version } }.toMap()
}
}
val present = snapshot.second.takeIf { snapshot.first == presentKey } ?: emptyMap()
fun status(addon: WowAddonCatalog.Addon): AddonStatus {
if (addon.id !in present) return AddonStatus.INSTALL
val have = present[addon.id]
@@ -116,10 +227,16 @@ 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 { WowAddonCatalog.search(context, WowAddonCatalog.Query(words, cat, WowAddonCatalog.client(into), order), page) }
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)
}
}
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 } })
@@ -136,6 +253,27 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
fun install(addon: WowAddonCatalog.Addon) {
val key = installKey(addon, target)
if (key in installing) return
val via = link?.takeIf { curse != null }
if (via != null) {
val into = target
installing[key] = 0
scope.launch {
val done = withContext(Dispatchers.IO) { runCatching { via.call(context, into) { CurseForgeApp.install(context, it.inspector, it.guid, addon.id) } } }
installing.remove(key)
val ok = done.getOrNull() == true
if (ok) {
WowAddons.changed()
curseInstalls++
}
val message = when {
ok -> context.resources.getQuantityString(R.plurals.main_addons_imported, 1, 1, into.flavor)
else -> (done.exceptionOrNull() as? CurseState)?.notice?.let(context::getString)
?: context.getString(R.string.stores_dl_failed_reason, done.exceptionOrNull()?.message ?: addon.name)
}
Toast.makeText(context, message, Toast.LENGTH_LONG).show()
}
return
}
if (SessionState.running) {
Toast.makeText(context, R.string.main_addons_close_session, Toast.LENGTH_LONG).show()
return
@@ -149,7 +287,7 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
Toast.makeText(context, message.first, Toast.LENGTH_LONG).show()
}
}
val sourceName = stringResource(R.string.addons_source_wowi)
val sourceName = stringResource(if (curse != null) R.string.addons_source_curse else R.string.addons_source_wowi)
val grid = rememberLazyGridState()
LaunchedEffect(results, grid) {
snapshotFlow { grid.layoutInfo.visibleItemsInfo.lastOrNull()?.index to grid.layoutInfo.totalItemsCount }.collect { (last, total) ->
@@ -162,7 +300,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) {
AppDialog(shown, close, "addonBrowser", wide = true, maxWidth = 980.dp, scrollable = false, fillHeight = true, modifier = Modifier.releaseTextFieldOnTap()) {
val sortChip: @Composable () -> Unit = {
BrowseDropdown(sortLabel(sort)) { first, done ->
WowAddonCatalog.Sort.entries.forEachIndexed { index, option ->
@@ -170,8 +308,14 @@ 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 (categories.isNotEmpty()) BrowseDropdown(category?.name ?: stringResource(R.string.addons_category_all)) { first, done ->
if (curse == null && 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() } }
}
@@ -195,6 +339,7 @@ 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()
@@ -208,6 +353,7 @@ 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()
@@ -228,6 +374,10 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
Column(Modifier.fillMaxWidth().padding(vertical = 8.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp)) {
when {
results.loading -> LinearProgressIndicator(Modifier.fillMaxWidth())
results.failed != null && notice != null -> {
Text(stringResource(notice!!), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
BrowseChip(stringResource(R.string.stores_dl_retry), false) { load(0) }
}
results.failed != null -> {
Text(stringResource(R.string.addons_unreachable, sourceName), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
BrowseChip(stringResource(R.string.stores_dl_retry), false) { load(if (results.items.isEmpty()) 0 else results.page + 1) }
@@ -259,7 +409,7 @@ private fun AddonRow(addon: WowAddonCatalog.Addon, status: AddonStatus, progress
fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
)
}
val size = Modifier.widthIn(min = 104.dp).then(action)
val size = action
when {
progress != null -> SecondaryButton(stringResource(R.string.store_installing), compact = true, modifier = size, progress = progress / 100f, onClick = onInstall)
status == AddonStatus.INSTALLED -> SecondaryButton(stringResource(R.string.stores_installed_chip), enabled = false, compact = true, modifier = size) {}
@@ -2,6 +2,7 @@ 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
@@ -184,7 +185,11 @@ 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(if (hot) pal.signal.copy(alpha = 0.14f) else colors.surface)
.background(colors.surface).then(if (hot) Modifier.background(pal.signal.copy(alpha = 0.14f)) else Modifier)
.glideBorder(hot, shape, pal.signal, pal.line)
.hoverable(src).clickable(interactionSource = src, indication = null, role = Role.Button, onClick = open)
.controllerConfirm(onClick = open)
@@ -12,6 +12,7 @@ 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(if (hot) pal.signal.copy(alpha = 0.10f) else colors.surface)
.clip(shape).background(colors.surface).then(if (hot) Modifier.background(pal.signal.copy(alpha = 0.10f)) else Modifier)
.glideBorder(hot, shape, pal.signal, pal.line)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button) { onClick(artAt) }
.controllerConfirm { onClick(artAt) }
@@ -761,6 +761,20 @@ 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 } }
@@ -768,19 +782,7 @@ 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 (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),
.then(if (openTab == "agent") Modifier.imePadding() else Modifier),
navigation = {
if (s.dualScreen || (bottomNavigation && agentKeyboardOpen)) Unit
else if (bottomNavigation) BottomBar(s, railSelection, onRailSelect, onRailFocus, a, railFocus)
@@ -902,3 +904,7 @@ 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(if (hot) pal.signal.copy(alpha = 0.10f) else colors.surface))
.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))
.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)
@@ -1049,7 +1049,7 @@ private fun SavesTab(g: Library.SteamGame, prefix: File, a: FrontEndActions) {
@Composable
private fun AddonsTab(g: Library.SteamGame, targets: List<WowAddons.Target>, a: FrontEndActions) {
var browsing by remember(g.gameId) { mutableStateOf<WowAddons.Target?>(null) }
browsing?.let { AddonBrowserDialog(targets, it) { browsing = null } }
browsing?.let { AddonBrowserDialog(targets, it, CurseForgeApp.find(UserAppsState.items)) { browsing = null } }
Column(Modifier.fillMaxWidth().tabPanel(), verticalArrangement = Arrangement.spacedBy(2.dp)) {
CurseForgeEntry(a)
targets.forEach { target ->
@@ -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(10.dp)) {
FlowRow(modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.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 = 44.dp).clip(shape)
modifier = Modifier.paneItem("resource:${link.label}").heightIn(min = 34.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) 14.dp else 8.dp),
.controllerConfirm(onClick = open).padding(horizontal = if (glass) 11.dp else 8.dp),
) {
Text(label, fontSize = if (glass) 13.sp else 12.sp, fontWeight = FontWeight.Medium, color = if (glass && !hot) MaterialTheme.colorScheme.onBackground else tint, maxLines = 1)
Text(label, fontSize = 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))
}
}
@@ -914,7 +914,6 @@ 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) {
@@ -946,6 +945,7 @@ 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()
}
}
}
@@ -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(if (hot) pal.signal.copy(alpha = 0.12f) else colors.surface)
.background(colors.surface).then(if (hot) Modifier.background(pal.signal.copy(alpha = 0.12f)) else Modifier)
.glideBorder(hot, shape, pal.signal, pal.line)
.hoverable(src)
.clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Tab, onClick = onClick)
@@ -0,0 +1,76 @@
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,6 +49,12 @@ 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) {
@@ -73,15 +79,18 @@ 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,
placeholder = stringResource(R.string.settings_search), compact = true, showLabel = false, focusOnShow = focusOnOpen, focusAtTap = focusTap,
clearFocus = !searching,
onFocusChange = { focused -> if (!focused && query.isEmpty() && searching) { focusOnOpen = false; onClose() } },
onFocusChange = { focused ->
fieldFocused = 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)) { focusOnOpen = true; onOpen() } }
Box(Modifier.focusRequester(icon)) { SearchIcon(stringResource(R.string.settings_search)) { focusTap = ScreenTaps.count; focusOnOpen = true; onOpen() } }
}
}
}
@@ -453,7 +453,7 @@ private fun BucketCard(
modifier = modifier.paneItem("storage:${bucket.name}")
.graphicsLayer { scaleX = scale; scaleY = scale }
.clip(Shape14)
.background(if (hot) pal.signal.copy(alpha = 0.10f) else colors.surface)
.background(colors.surface).then(if (hot) Modifier.background(pal.signal.copy(alpha = 0.10f)) else Modifier)
.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(if (hot) pal.signal.copy(alpha = 0.10f) else colors.surface)
.background(colors.surface).then(if (hot) Modifier.background(pal.signal.copy(alpha = 0.10f)) else Modifier)
.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(if (hot) pal.signal.copy(alpha = 0.14f) else colors.surface)
.background(colors.surface).then(if (hot) Modifier.background(pal.signal.copy(alpha = 0.14f)) else Modifier)
.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(if (hot) pal.signal.copy(alpha = 0.10f) else colors.surface)
.clip(shape).background(colors.surface).then(if (hot) Modifier.background(pal.signal.copy(alpha = 0.10f)) else Modifier)
.glideBorder(hot, shape, pal.signal, pal.line)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onClick)
.controllerConfirm(onClick = onClick)
@@ -925,6 +925,12 @@ 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() }
@@ -955,9 +961,12 @@ 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,
placeholder = placeholder, compact = true, showLabel = false, focusOnShow = focusOnOpen, focusAtTap = focusTap,
clearFocus = clearSearchFocus || !searching,
onFocusChange = { focused -> if (!focused && query.isEmpty()) { searching = false; focusOnOpen = false } },
onFocusChange = { focused ->
fieldFocused = 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)
@@ -965,7 +974,7 @@ internal fun ModeHeader(
}
}
val searchButton: @Composable () -> Unit = {
Box(Modifier.focusRequester(searchIcon)) { SearchIcon(stringResource(R.string.stores_search_open)) { searching = true; focusOnOpen = true } }
Box(Modifier.focusRequester(searchIcon)) { SearchIcon(stringResource(R.string.stores_search_open)) { focusTap = ScreenTaps.count; searching = true; focusOnOpen = true } }
}
BoxWithConstraints(Modifier.fillMaxWidth()) {
val stacked = maxWidth < NarrowPaneWidth
@@ -365,11 +365,13 @@ 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)
@@ -502,9 +504,12 @@ internal fun AdbTextField(
},
update = { editText ->
editText.showSoftInputOnFocus = !bottomTyping
if (focusOnShow && !focusAsked[0]) {
focusAsked[0] = true
// 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
editText.post {
if (focusAtTap != null && focusAtTap != ScreenTaps.count) return@post
editText.requestFocus()
if (!bottomTypingLatest.value) (editText.context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE) as? android.view.inputmethod.InputMethodManager)
?.showSoftInput(editText, android.view.inputmethod.InputMethodManager.SHOW_IMPLICIT)
@@ -10,6 +10,8 @@ import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionState
object CompositorHost {
private const val TAG = "DroidDeck"
@Volatile
private var started = false
@@ -55,6 +57,52 @@ object CompositorHost {
}
}
class Output internal constructor(
internal val runtimeDir: java.io.File,
internal val turnip: com.droiddeck.launcher.gpu.TurnipDriver,
internal val driverId: String?,
)
fun prepare(context: android.content.Context): Output {
val runtimeDir = java.io.File(context.filesDir, ".wayland-rt").apply { mkdirs() }
com.droiddeck.launcher.core.FileUtils.copyAsset(context, "wayland/keymap.xkb", java.io.File(runtimeDir, "keymap.xkb"))
com.droiddeck.launcher.input.VrControllers.publish(context)
val turnip = com.droiddeck.launcher.gpu.TurnipDriver(context)
com.droiddeck.launcher.gpu.DriverSetupLog.write(context, "surface.driver-setup")
if (!started) {
displayChoice = SessionPrefs.androidDriver(context)
com.droiddeck.launcher.gpu.AutoDriverTrial.displayStarting(context, SessionPrefs.androidDriver(context))
}
return Output(runtimeDir, turnip, if (started) null else turnip.install())
}
fun logToSession(context: android.content.Context) {
val waylandLog = java.io.File(com.droiddeck.launcher.session.SessionPaths.beginOrCurrent(context), "wayland.log")
WaylandCompositor.setSessionLogFile(waylandLog)
try {
android.system.Os.setenv("DD_WAYLAND_LOG", waylandLog.path, true)
} catch (e: Exception) {
android.util.Log.w(TAG, "could not point the compositor's log at $waylandLog", e)
}
}
fun applyHdr(context: android.content.Context, mode: String) {
val on = SessionState.hdrCapable && SessionPrefs.hdr(context, mode)
SessionState.hdr = on
WaylandCompositor.nativeSetHdrOutput(on)
WaylandCompositor.nativeSetZeroCopy(on || SessionPrefs.zeroCopy(context, mode))
android.util.Log.i(TAG, "hdr: " + (if (on) "on" else "off") + " for this $mode session")
}
fun start(context: android.content.Context, output: Output, surface: Surface, size: Pair<Int, Int>, refreshHz: Float, fpsLimit: Int): Boolean {
com.droiddeck.launcher.gpu.DriverSetupLog.write(context, "compositor.start driver=${output.driverId}")
return startOrAttach(
context, surface, output.runtimeDir.path,
output.driverId?.let { output.turnip.driverPath(it) }, output.driverId?.let { output.turnip.libraryName(it) },
context.applicationInfo.nativeLibraryDir, size.first, size.second, refreshHz, fpsLimit,
)
}
@Synchronized
fun startOrAttach(
context: android.content.Context,
+1
View File
@@ -4177,6 +4177,7 @@
<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,6 +4057,7 @@
<string name="addons_sort_downloads">Más descargados</string>
<string name="addons_category_all">Todas las categorías</string>
<string name="addons_none_found">No se encontraron complementos</string>
<string name="addons_curse_busy">Cierra CurseForge primero</string>
<string name="addons_unreachable">No se pudo conectar con %1$s</string>
<string name="addons_no_file">No hay archivo para esta versión del juego</string>
<string name="input_reset_positions">Restablecer posiciones</string>
+1
View File
@@ -4017,6 +4017,7 @@
<string name="addons_sort_downloads">Най-изтегляни</string>
<string name="addons_category_all">Всички категории</string>
<string name="addons_none_found">Няма намерени добавки</string>
<string name="addons_curse_busy">Първо затворете CurseForge</string>
<string name="addons_unreachable">Няма връзка с %1$s</string>
<string name="addons_no_file">Няма файл за тази версия на играта</string>
<string name="input_reset_positions">Нулиране на позициите</string>
+1
View File
@@ -4097,6 +4097,7 @@
<string name="addons_sort_downloads">Nejstahovanější</string>
<string name="addons_category_all">Všechny kategorie</string>
<string name="addons_none_found">Nenalezeny žádné doplňky</string>
<string name="addons_curse_busy">Nejprve zavřete CurseForge</string>
<string name="addons_unreachable">Nelze se připojit k %1$s</string>
<string name="addons_no_file">Pro tuto verzi hry není k dispozici soubor</string>
<string name="input_reset_positions">Obnovit pozice</string>
+1
View File
@@ -4017,6 +4017,7 @@
<string name="addons_sort_downloads">Mest downloadet</string>
<string name="addons_category_all">Alle kategorier</string>
<string name="addons_none_found">Ingen tilføjelser fundet</string>
<string name="addons_curse_busy">Luk CurseForge først</string>
<string name="addons_unreachable">Kunne ikke nå %1$s</string>
<string name="addons_no_file">Ingen fil til denne spilversion</string>
<string name="input_reset_positions">Nulstil placeringer</string>
+1
View File
@@ -4017,6 +4017,7 @@
<string name="addons_sort_downloads">Meistgeladen</string>
<string name="addons_category_all">Alle Kategorien</string>
<string name="addons_none_found">Keine Addons gefunden</string>
<string name="addons_curse_busy">Schließe zuerst CurseForge</string>
<string name="addons_unreachable">%1$s ist nicht erreichbar</string>
<string name="addons_no_file">Keine Datei für diese Spielversion</string>
<string name="input_reset_positions">Positionen zurücksetzen</string>
+1
View File
@@ -4017,6 +4017,7 @@
<string name="addons_sort_downloads">Περισσότερες λήψεις</string>
<string name="addons_category_all">Όλες οι κατηγορίες</string>
<string name="addons_none_found">Δεν βρέθηκαν πρόσθετα</string>
<string name="addons_curse_busy">Κλείστε πρώτα το CurseForge</string>
<string name="addons_unreachable">Δεν ήταν δυνατή η σύνδεση με %1$s</string>
<string name="addons_no_file">Δεν υπάρχει αρχείο για αυτή την έκδοση του παιχνιδιού</string>
<string name="input_reset_positions">Επαναφορά θέσεων</string>
+1
View File
@@ -4057,6 +4057,7 @@
<string name="addons_sort_downloads">Más descargados</string>
<string name="addons_category_all">Todas las categorías</string>
<string name="addons_none_found">No se han encontrado complementos</string>
<string name="addons_curse_busy">Cierra CurseForge primero</string>
<string name="addons_unreachable">No se pudo conectar con %1$s</string>
<string name="addons_no_file">No hay ningún archivo para esta versión del juego</string>
<string name="input_reset_positions">Restablecer posiciones</string>
+1
View File
@@ -4017,6 +4017,7 @@
<string name="addons_sort_downloads">Ladatuimmat</string>
<string name="addons_category_all">Kaikki luokat</string>
<string name="addons_none_found">Lisäosia ei löytynyt</string>
<string name="addons_curse_busy">Sulje CurseForge ensin</string>
<string name="addons_unreachable">Yhteyttä palveluun %1$s ei saatu</string>
<string name="addons_no_file">Tälle peliversiolle ei ole tiedostoa</string>
<string name="input_reset_positions">Palauta sijainnit</string>
+1
View File
@@ -4056,6 +4056,7 @@
<string name="addons_sort_downloads">Les plus téléchargés</string>
<string name="addons_category_all">Toutes les catégories</string>
<string name="addons_none_found">Aucun addon trouvé</string>
<string name="addons_curse_busy">Fermez d\'abord CurseForge</string>
<string name="addons_unreachable">Impossible de joindre %1$s</string>
<string name="addons_no_file">Aucun fichier pour cette version du jeu</string>
<string name="input_reset_positions">Réinitialiser les positions</string>
+1
View File
@@ -4017,6 +4017,7 @@
<string name="addons_sort_downloads">सबसे ज़्यादा डाउनलोड</string>
<string name="addons_category_all">सभी श्रेणियाँ</string>
<string name="addons_none_found">कोई ऐडऑन नहीं मिला</string>
<string name="addons_curse_busy">पहले CurseForge बंद करें</string>
<string name="addons_unreachable">%1$s तक नहीं पहुँच सके</string>
<string name="addons_no_file">गेम के इस संस्करण के लिए कोई फ़ाइल नहीं है</string>
<string name="input_reset_positions">स्थितियाँ रीसेट करें</string>
+1
View File
@@ -4017,6 +4017,7 @@
<string name="addons_sort_downloads">Legtöbbet letöltött</string>
<string name="addons_category_all">Minden kategória</string>
<string name="addons_none_found">Nem található kiegészítő</string>
<string name="addons_curse_busy">Előbb zárd be a CurseForge-ot</string>
<string name="addons_unreachable">A(z) %1$s nem érhető el</string>
<string name="addons_no_file">Nincs fájl ehhez a játékverzióhoz</string>
<string name="input_reset_positions">Pozíciók visszaállítása</string>
+1
View File
@@ -3987,6 +3987,7 @@
<string name="addons_sort_downloads">Paling banyak diunduh</string>
<string name="addons_category_all">Semua kategori</string>
<string name="addons_none_found">Tidak ada addon ditemukan</string>
<string name="addons_curse_busy">Tutup CurseForge terlebih dahulu</string>
<string name="addons_unreachable">Tidak dapat menjangkau %1$s</string>
<string name="addons_no_file">Tidak ada file untuk versi game ini</string>
<string name="input_reset_positions">Atur ulang posisi</string>
+1
View File
@@ -4056,6 +4056,7 @@
<string name="addons_sort_downloads">Più scaricati</string>
<string name="addons_category_all">Tutte le categorie</string>
<string name="addons_none_found">Nessun addon trovato</string>
<string name="addons_curse_busy">Chiudi prima CurseForge</string>
<string name="addons_unreachable">Impossibile raggiungere %1$s</string>
<string name="addons_no_file">Nessun file per questa versione del gioco</string>
<string name="input_reset_positions">Ripristina posizioni</string>
+1
View File
@@ -3987,6 +3987,7 @@
<string name="addons_sort_downloads">ダウンロード数順</string>
<string name="addons_category_all">すべてのカテゴリ</string>
<string name="addons_none_found">アドオンが見つかりません</string>
<string name="addons_curse_busy">先に CurseForge を閉じてください</string>
<string name="addons_unreachable">%1$s に接続できませんでした</string>
<string name="addons_no_file">このゲームバージョン用のファイルがありません</string>
<string name="input_reset_positions">位置をリセット</string>
+1
View File
@@ -3987,6 +3987,7 @@
<string name="addons_sort_downloads">다운로드 많은 순</string>
<string name="addons_category_all">모든 카테고리</string>
<string name="addons_none_found">애드온을 찾을 수 없음</string>
<string name="addons_curse_busy">먼저 CurseForge를 닫으세요</string>
<string name="addons_unreachable">%1$s에 연결할 수 없습니다</string>
<string name="addons_no_file">이 게임 버전용 파일이 없습니다</string>
<string name="input_reset_positions">위치 초기화</string>
+1
View File
@@ -3987,6 +3987,7 @@
<string name="addons_sort_downloads">Paling banyak dimuat turun</string>
<string name="addons_category_all">Semua kategori</string>
<string name="addons_none_found">Tiada addon ditemui</string>
<string name="addons_curse_busy">Tutup CurseForge dahulu</string>
<string name="addons_unreachable">Tidak dapat mencapai %1$s</string>
<string name="addons_no_file">Tiada fail untuk versi permainan ini</string>
<string name="input_reset_positions">Tetapkan semula kedudukan</string>
+1
View File
@@ -4017,6 +4017,7 @@
<string name="addons_sort_downloads">Mest nedlastet</string>
<string name="addons_category_all">Alle kategorier</string>
<string name="addons_none_found">Fant ingen tillegg</string>
<string name="addons_curse_busy">Lukk CurseForge først</string>
<string name="addons_unreachable">Fikk ikke kontakt med %1$s</string>
<string name="addons_no_file">Ingen fil for denne spillversjonen</string>
<string name="input_reset_positions">Tilbakestill plasseringer</string>
+1
View File
@@ -4017,6 +4017,7 @@
<string name="addons_sort_downloads">Meest gedownload</string>
<string name="addons_category_all">Alle categorieën</string>
<string name="addons_none_found">Geen add-ons gevonden</string>
<string name="addons_curse_busy">Sluit eerst CurseForge</string>
<string name="addons_unreachable">Kan %1$s niet bereiken</string>
<string name="addons_no_file">Geen bestand voor deze gameversie</string>
<string name="input_reset_positions">Posities herstellen</string>
+1
View File
@@ -4097,6 +4097,7 @@
<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,6 +4070,7 @@
<string name="addons_sort_downloads">Mais transferidos</string>
<string name="addons_category_all">Todas as categorias</string>
<string name="addons_none_found">Nenhum addon encontrado</string>
<string name="addons_curse_busy">Feche primeiro o CurseForge</string>
<string name="addons_unreachable">Não foi possível contactar %1$s</string>
<string name="addons_no_file">Não há ficheiro para esta versão do jogo</string>
<string name="input_reset_positions">Repor posições</string>
+1
View File
@@ -4078,6 +4078,7 @@
<string name="addons_sort_downloads">Mais baixados</string>
<string name="addons_category_all">Todas as categorias</string>
<string name="addons_none_found">Nenhum addon encontrado</string>
<string name="addons_curse_busy">Feche o CurseForge primeiro</string>
<string name="addons_unreachable">Não foi possível acessar %1$s</string>
<string name="addons_no_file">Não há arquivo para esta versão do jogo</string>
<string name="input_reset_positions">Redefinir posições</string>
+1
View File
@@ -4057,6 +4057,7 @@
<string name="addons_sort_downloads">Cele mai descărcate</string>
<string name="addons_category_all">Toate categoriile</string>
<string name="addons_none_found">Nu s-au găsit suplimente</string>
<string name="addons_curse_busy">Închide mai întâi CurseForge</string>
<string name="addons_unreachable">Nu s-a putut accesa %1$s</string>
<string name="addons_no_file">Nu există fișier pentru această versiune a jocului</string>
<string name="input_reset_positions">Resetează pozițiile</string>
+1
View File
@@ -4097,6 +4097,7 @@
<string name="addons_sort_downloads">Самые скачиваемые</string>
<string name="addons_category_all">Все категории</string>
<string name="addons_none_found">Аддоны не найдены</string>
<string name="addons_curse_busy">Сначала закройте CurseForge</string>
<string name="addons_unreachable">Не удалось подключиться к %1$s</string>
<string name="addons_no_file">Нет файла для этой версии игры</string>
<string name="input_reset_positions">Сбросить положение</string>
+1
View File
@@ -4017,6 +4017,7 @@
<string name="addons_sort_downloads">Mest nedladdade</string>
<string name="addons_category_all">Alla kategorier</string>
<string name="addons_none_found">Inga tillägg hittades</string>
<string name="addons_curse_busy">Stäng CurseForge först</string>
<string name="addons_unreachable">Kunde inte nå %1$s</string>
<string name="addons_no_file">Ingen fil för den här spelversionen</string>
<string name="input_reset_positions">Återställ positioner</string>
+1
View File
@@ -3987,6 +3987,7 @@
<string name="addons_sort_downloads">ดาวน์โหลดมากที่สุด</string>
<string name="addons_category_all">ทุกหมวดหมู่</string>
<string name="addons_none_found">ไม่พบแอดออน</string>
<string name="addons_curse_busy">ปิด CurseForge ก่อน</string>
<string name="addons_unreachable">ไม่สามารถเชื่อมต่อ %1$s ได้</string>
<string name="addons_no_file">ไม่มีไฟล์สำหรับเกมเวอร์ชันนี้</string>
<string name="input_reset_positions">รีเซ็ตตำแหน่ง</string>
+1
View File
@@ -4017,6 +4017,7 @@
<string name="addons_sort_downloads">En çok indirilen</string>
<string name="addons_category_all">Tüm kategoriler</string>
<string name="addons_none_found">Eklenti bulunamadı</string>
<string name="addons_curse_busy">Önce CurseForge\'u kapatın</string>
<string name="addons_unreachable">%1$s adresine ulaşılamadı</string>
<string name="addons_no_file">Bu oyun sürümü için dosya yok</string>
<string name="input_reset_positions">Konumları sıfırla</string>
+1
View File
@@ -4097,6 +4097,7 @@
<string name="addons_sort_downloads">Найбільше завантажень</string>
<string name="addons_category_all">Усі категорії</string>
<string name="addons_none_found">Аддонів не знайдено</string>
<string name="addons_curse_busy">Спочатку закрийте CurseForge</string>
<string name="addons_unreachable">Не вдалося під’єднатися до %1$s</string>
<string name="addons_no_file">Немає файлу для цієї версії гри</string>
<string name="input_reset_positions">Скинути розташування</string>
+1
View File
@@ -3987,6 +3987,7 @@
<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,6 +3987,7 @@
<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,6 +3987,7 @@
<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,6 +3987,7 @@
<string name="addons_sort_downloads">下載最多</string>
<string name="addons_category_all">所有類別</string>
<string name="addons_none_found">找不到插件</string>
<string name="addons_curse_busy">請先關閉 CurseForge</string>
<string name="addons_unreachable">無法連線至 %1$s</string>
<string name="addons_no_file">沒有適用於此遊戲版本的檔案</string>
<string name="input_reset_positions">重設位置</string>
+1
View File
@@ -4202,6 +4202,7 @@
<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>
@@ -108,6 +108,15 @@ 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 ->
@@ -0,0 +1,161 @@
package com.droiddeck.launcher.runtime
import android.app.Application
import org.json.JSONArray
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import java.io.File
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33], manifest = Config.NONE, application = Application::class)
class CurseForgeAppTest {
@get:Rule val temp = TemporaryFolder()
private val search = """{"success":true,"injectedCount":0,
"pagination":{"index":0,"pageSize":20,"resultCount":20,"totalCount":150},
"mods":[
{"id":486246,"name":"RestedXP Guide","summary":"Leveling guide","downloads":12345678,
"thumbnailUrl":"https://media.forgecdn.net/avatars/rxp.png","authors":[{"name":"RestedXP"}],
"updateVersion":{"id":7,"filename":"RXPGuides.zip","fileDate":"2026-11-20T10:00:00.000Z"}},
{"id":2,"name":"Plain","downloads":5,"thumbnailUrl":"http://insecure/x.png","primaryAuthor":{"name":"Main"},
"authors":[{"name":"Other"}],"projectLatestReleaseDate":"2026-01-01T00:00:00Z"},
{"id":0,"name":"No id"},
{"id":3,"name":""}
]}"""
@Test
fun searchResultsBecomeCatalogEntries() {
val page = CurseForgeApp.parseSearch(JSONObject(search))
assertEquals(listOf("486246", "2"), page.items.map { it.id })
val rxp = page.items[0]
assertEquals("RestedXP Guide", rxp.name)
assertEquals("RestedXP", rxp.author)
assertEquals(12345678L, rxp.downloads)
assertEquals(java.time.Instant.parse("2026-11-20T10:00:00Z").toEpochMilli(), rxp.updated)
assertEquals("https://media.forgecdn.net/avatars/rxp.png", rxp.thumb)
assertEquals("Main", page.items[1].author)
assertNull(page.items[1].thumb)
assertTrue(page.more)
}
@Test
fun theLastPageHasNoMore() {
val last = JSONObject(search).put("pagination", JSONObject("""{"index":140,"resultCount":10,"totalCount":150}"""))
assertFalse(CurseForgeApp.parseSearch(last).more)
assertThrows(CurseForgeApp.Failure::class.java) { CurseForgeApp.parseSearch(JSONObject("""{"success":false}""")) }
assertThrows(CurseForgeApp.Failure::class.java) { CurseForgeApp.parseSearch(null) }
}
@Test
fun searchRequestsUseTheInstanceAndOneBasedPages() {
val request = CurseForgeApp.searchRequest("guid-1", " Rested ", WowAddonCatalog.Sort.NAME, 0)
assertEquals(1, request.getInt("gameId"))
assertEquals("Rested", request.getString("searchText"))
assertEquals(1, request.getInt("page"))
assertEquals(1, request.getInt("sortColumn"))
assertEquals(1, request.getInt("sortOrder"))
assertEquals("guid-1", request.getString("gameInstanceGuid"))
assertEquals(2, CurseForgeApp.searchRequest("g", "", WowAddonCatalog.Sort.DOWNLOADS, 1).getInt("page"))
assertEquals(WowAddonCatalog.Sort.entries.size, WowAddonCatalog.Sort.entries.map(CurseForgeApp::sortOf).toSet().size)
}
@Test
fun installRequestsInstallTheLatestFileIntoTheInstance() {
val request = CurseForgeApp.installRequest("guid-1", "486246")
assertEquals("guid-1", request.getString("instanceId"))
assertEquals(486246L, request.getLong("projectId"))
assertTrue(request.getBoolean("installLatestFile"))
}
@Test
fun theInstanceIsPickedByItsFlavorFolder() {
val instances = JSONArray("""[
{"guid":"retail","installPath":"/root/Games/WoW/_retail_/"},
{"guid":"forever","installPath":"/root/Games/WoW/_forever_/"}
]""")
assertEquals("forever", CurseForgeApp.instanceFor(instances, "/root/Games/WoW/_forever_", "retail"))
assertEquals("retail", CurseForgeApp.instanceFor(instances, "/root/Games/WoW/_retail_", null))
assertNull(CurseForgeApp.instanceFor(instances, "/root/Games/WoW/_classic_", "retail"))
val single = JSONArray("""[{"guid":"retail","installPath":"/root/Games/WoW/_retail_/"}]""")
assertNull(CurseForgeApp.instanceFor(single, "/root/Games/WoW/_classic_", "retail"))
assertEquals("retail", CurseForgeApp.instanceFor(single, "/root/Games/WoW/_retail_", "other"))
assertEquals("only", CurseForgeApp.instanceFor(JSONArray(), "/x/_forever_", "only"))
assertEquals("only", CurseForgeApp.instanceFor(null, "/x/_forever_", "only"))
assertNull(CurseForgeApp.instanceFor(JSONArray(), "/x/_forever_", ""))
}
@Test
fun answersAreUnwrapped() {
val ok = JSONObject().put("ok", true).put("value", """{"value":{"resultStatus":3,"gameInstanceGuid":"g"}}""")
assertEquals("g", (CurseForgeApp.unwrap(ok) as JSONObject).getString("gameInstanceGuid"))
assertEquals(true, CurseForgeApp.unwrap(JSONObject().put("ok", true).put("value", """{"value":true}""")))
val missing = JSONObject().put("ok", true).put("value", """{"missing":true}""")
assertThrows(CurseForgeApp.Failure::class.java) { CurseForgeApp.unwrap(missing) }
val failed = JSONObject().put("ok", false).put("error", JSONObject().put("code", "NO_TARGET").put("message", "no node"))
val failure = assertThrows(CurseForgeApp.Failure::class.java) { CurseForgeApp.unwrap(failed) }
assertEquals("no node", failure.message)
assertEquals("NO_TARGET", failure.code)
assertFalse(failure.gone)
val lost = JSONObject().put("ok", false).put("error", JSONObject().put("code", "DEVTOOLS_UNREACHABLE").put("message", "refused"))
assertTrue(assertThrows(CurseForgeApp.Failure::class.java) { CurseForgeApp.unwrap(lost) }.gone)
}
@Test
fun expressionsDriveTheHiddenDesktopWindow() {
val text = CurseForgeApp.expression("ProjectAppService", "search", JSONArray().put(JSONObject().put("searchText", "it's \"x\"")))
assertTrue(text.startsWith("(() => { const w = require('electron').BrowserWindow.getAllWindows()"))
assertTrue(text.contains("desktop.html"))
assertTrue(text.contains("executeJavaScript("))
assertFalse(text.contains("show()"))
val probe = CurseForgeApp.expression("InstalledProjectsAppService", "installAddon", null)
assertFalse(probe.contains("await s["))
val connect = CurseForgeApp.expression("CoreService", "connect", JSONArray(), "r => true")
assertTrue(connect.contains("(r => true)(await s[\\\"connect\\\"](...[]))"))
}
@Test
fun installedIdsAndExitCodes() {
assertEquals(setOf("486246", "2"), CurseForgeApp.projectIds(JSONArray("""["486246","2",null]""")))
assertEquals(emptySet<String>(), CurseForgeApp.projectIds(JSONObject()))
assertEquals(CurseForgeApp.Start.READY, CurseForgeApp.startState(0))
assertEquals(CurseForgeApp.Start.BUSY, CurseForgeApp.startState(3))
assertEquals(CurseForgeApp.Start.NO_DISPLAY, CurseForgeApp.startState(4))
assertEquals(CurseForgeApp.Start.FAILED, CurseForgeApp.startState(5))
}
@Test
fun onlyASecretInspectorUrlIsTaken() {
val url = "ws://127.0.0.1:43117/0f8fad5b-d9cb-469f-a165-70867728950e"
assertEquals(url, CurseForgeApp.inspectorUrl("noise\n$url\n"))
assertNull(CurseForgeApp.inspectorUrl("ready\n"))
assertNull(CurseForgeApp.inspectorUrl("ws://127.0.0.1:9229/\n"))
assertNull(CurseForgeApp.inspectorUrl("ws://10.0.0.2:43117/0f8fad5b-d9cb-469f-a165-70867728950e"))
assertNull(CurseForgeApp.inspectorUrl("$url/json"))
}
@Test
fun theWowRootIsTheParentOfEveryFlavor() {
val root = temp.newFolder("World of Warcraft")
for (flavor in listOf("_classic_", "_classic_era_")) {
File(root, "$flavor/Interface/AddOns").mkdirs()
File(root, "$flavor/.flavor.info").writeText("x")
}
val title = BattleNet.TITLES.first { it.flavor == "_classic_" }
val targets = WowAddons.targets(title, File(root, "_classic_"))
assertEquals(listOf("_classic_", "_classic_era_"), targets.map { it.flavor }.sorted())
for (target in targets) {
assertEquals(root, WowAddons.root(target))
assertEquals(File(root, target.flavor), WowAddons.flavorDir(target))
}
}
}
+25 -1
View File
@@ -131,6 +131,18 @@ 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.
@@ -197,13 +209,25 @@ alone would then read as an installed client.
restarted from the top forever (found with `perf_event_open` IP sampling, since proot holds
ptrace). Such a range is now skipped whole and a second exhausted scan returns `-ENOMEM`, as the
kernel does (`fex-2610-r3`).
- `0006-smc-alias-of-code-created-after-translation`: a JIT with a double-mapped memfd (CoreCLR's
W^X allocator) maps its writable alias after the executable alias was translated. Under
`SMCChecks=mtrack` the new alias was not write-protected, so writes through it never faulted and
never invalidated the translated code; x86-64 .NET programs ran stale code (access violations,
NullReferenceException, internal CLR errors). A writable mapping or mprotect now write-protects the
overlapping part of any alias that is already executable, so the first write faults and invalidates.
`FEX_SMCCHECKS=full` was the only workaround; no setting is needed with the patch.
- `0007-cmake-install-code-without-depends`: CMake 4.5 rejects the `DEPENDS` argument FEX passes to
`install(CODE ...)` for the guest thunk libraries, so builds with host thunks stopped at configure.
The guest libraries are external projects in the default build, which `install` already follows.
- **Building and publishing.** Droid-Deck/DroidDeck-Components' `build-fex.yml` builds `tools/fex` from
this repository at a chosen ref (default `main`) with host thunks, in the same Arch Linux ARM container
with a read-only token, then a separate job replaces `fex.tzst` on Components' single `fex` release,
checks the digest GitHub stored, and records the build's version, sha256 and size in its `fex.json`
(in that order: a device that reads the old `fex.json` meanwhile gets a mismatching archive and keeps
its FEX). This repository's `build-fex.yml` only builds `tools/fex` when it changes (and on dispatch,
for diagnostic builds such as `-DDEBUG_STRACE`); nothing is published from it.
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`.
- 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
+6 -3
View File
@@ -1,6 +1,8 @@
#!/usr/bin/bash
set -euxo pipefail
VERSION=${FEX_VERSION:-FEX-2610}
VERSION=${FEX_VERSION:?FEX_VERSION must name a FEX release tag, e.g. FEX-2611.1}
RELEASE=${VERSION#FEX-}
RELEASE=${RELEASE%%.*}
WORK=/work
cd "$WORK"
grep -q '^DisableSandbox' /etc/pacman.conf || sed -i 's/^\[options\]/[options]\nDisableSandbox/' /etc/pacman.conf
@@ -38,7 +40,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" ] && [ "${VERSION#FEX-}" -ge "$upstream" ]; then
if [ -n "$upstream" ] && [ "$RELEASE" -ge "$upstream" ]; then
echo "$(basename "$p"): already in FEX-$upstream, skipped for $VERSION"
continue
fi
@@ -56,7 +58,8 @@ 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 \
-DENABLE_CCACHE=OFF -DENABLE_OFFLINE_TELEMETRY=OFF -DFMT_MODULE=OFF \
-DCMAKE_CXX_MODULE_STD=OFF -DCMAKE_CXX_SCAN_FOR_MODULES=OFF \
${FEX_EXTRA_CXXFLAGS:+-DCMAKE_CXX_FLAGS="$FEX_EXTRA_CXXFLAGS"}
ninja -C fex-build
DESTDIR="$WORK/out" ninja -C fex-build install
@@ -0,0 +1,81 @@
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);
@@ -0,0 +1,20 @@
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
+22
View File
@@ -406,3 +406,25 @@ carried `DXVK_HDR=0`. Whether the display can show HDR now comes from the host's
either direction. The 10-bit output format is chosen only while HDR is enabled, so an SDR session keeps the 8-bit
output it had, and the output images are made again in the other format when the setting changes. On a display that can show HDR, a session that starts with HDR off leaves `DXVK_HDR` unset instead of
forcing it to 0, so a game started after HDR is switched on finds it.
## 0140 Focus is chosen again when a window turns visible or fully transparent
A window is a focus candidate only while its `_NET_WM_WINDOW_OPACITY` is above zero, but a change of that property
did not ask for focus to be chosen again. Wine sets the property for layered windows, and a window that fades in maps
fully transparent, so it was skipped when it mapped and stayed skipped once it was opaque until something else
changed focus. In a nested session with no other window the SDL window stayed hidden, and the game ran with nothing
on screen. Focus is now chosen again whenever a window's opacity crosses zero in either direction; a change between
two visible opacities leaves focus alone. `tools/tests/test_gamescope_focus_opacity.py` compiles the rule from this
patch and checks the property handler applies it.
## 0141 The SDL backend presents only to a shown window
SDL hides its window when gamescope has no focus window and shows it again when one appears, for example between a
launcher closing and its game mapping. On Wayland, showing the window gives its surface a new xdg_surface, commits it
and waits for the first configure, while gamescope's paint thread kept presenting into the same surface. A present
that landed in that gap attached a buffer before the configure, the host compositor (KWin in the Desktop session)
disconnected gamescope with `xdg_surface: error 3: attached a buffer before configure event`, every later present
failed and the swapchain was rebuilt in a loop, so the game ran with nothing on screen. Showing and hiding now hold a
lock that presenting also takes, and a present is skipped while the window is hidden or being shown instead of waiting
for it. `tools/tests/test_gamescope_sdl_show_present.py` runs the patch's show, hide and present code against a stub
that records presents made while the window waits for its configure or is hidden.
@@ -0,0 +1,32 @@
diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp
index cfec551..e98d320 100644
--- a/src/steamcompmgr.cpp
+++ b/src/steamcompmgr.cpp
@@ -6945,6 +6945,12 @@ handle_system_tray_opcode(xwayland_ctx_t *ctx, XClientMessageEvent *ev)
}
}
+static bool
+opacity_changes_focus_candidacy( unsigned int oldOpacity, unsigned int newOpacity )
+{
+ return ( oldOpacity > TRANSLUCENT ) != ( newOpacity > TRANSLUCENT );
+}
+
/* See http://tronche.com/gui/x/icccm/sec-4.html#s-4.1.4 */
static void
handle_wm_change_state(xwayland_ctx_t *ctx, steamcompmgr_win_t *w, XClientMessageEvent *ev)
@@ -7329,8 +7335,14 @@ handle_property_notify(xwayland_ctx_t *ctx, XPropertyEvent *ev)
if (newOpacity != w->opacity)
{
+ const bool bFocusCandidacyChanged = opacity_changes_focus_candidacy( w->opacity, newOpacity );
w->opacity = newOpacity;
+ if ( bFocusCandidacyChanged )
+ {
+ MakeFocusDirty();
+ }
+
if ( gameFocused && ( w == ctx->focus.overlayWindow || w == ctx->focus.notificationWindow ) )
{
hasRepaintNonBasePlane = true;
@@ -0,0 +1,55 @@
diff --git a/src/Backends/SDLBackend.cpp b/src/Backends/SDLBackend.cpp
--- a/src/Backends/SDLBackend.cpp
+++ b/src/Backends/SDLBackend.cpp
@@ -130,9 +130,12 @@ namespace gamescope
SDL_Window *GetSDLWindow() const { return m_pWindow; }
VkSurfaceKHR GetVulkanSurface() const { return m_pVkSurface; }
+ void SetWindowShown( bool bShown );
private:
CSDLBackend *m_pBackend = nullptr;
SDL_Window *m_pWindow = nullptr;
+ std::mutex m_WindowShownMutex;
+ bool m_bWindowShown = false;
VkSurfaceKHR m_pVkSurface = VK_NULL_HANDLE;
BackendConnectorHDRInfo m_HDRInfo{};
};
@@ -354,8 +357,22 @@ namespace gamescope
}
}
+ void CSDLConnector::SetWindowShown( bool bShown )
+ {
+ std::scoped_lock lock( m_WindowShownMutex );
+ if ( bShown )
+ SDL_ShowWindow( m_pWindow );
+ else
+ SDL_HideWindow( m_pWindow );
+ m_bWindowShown = bShown;
+ }
+
int CSDLConnector::Present( const FrameInfo_t *pFrameInfo, bool bAsync )
{
+ std::unique_lock lock( m_WindowShownMutex, std::try_to_lock );
+ if ( !lock.owns_lock() || !m_bWindowShown )
+ return 0;
+
// TODO: Resolve const crap
std::optional oCompositeResult = vulkan_composite( (FrameInfo_t *)pFrameInfo, nullptr, false );
if ( !oCompositeResult )
@@ -929,14 +946,7 @@ namespace gamescope
{
m_bShown = bVisible;
- if ( m_bShown )
- {
- SDL_ShowWindow( m_Connector.GetSDLWindow() );
- }
- else
- {
- SDL_HideWindow( m_Connector.GetSDLWindow() );
- }
+ m_Connector.SetWindowShown( m_bShown );
}
}
else if ( event.type == GetUserEventIndex( GAMESCOPE_SDL_EVENT_WINDOW_MODE ) )
+2 -2
View File
@@ -1,3 +1,3 @@
GAMESCOPE_REPO=Droid-Deck/DroidDeck-Components
GAMESCOPE_TAG=gamescope-3.16.29-zerocopy-8df683f1-qa
GAMESCOPE_SHA256=609198c39b125094a65e1703ffcfd6538e88c9784a1a6596bf673f2e5dc7af80
GAMESCOPE_TAG=gamescope-3.16.29-1a29c65d
GAMESCOPE_SHA256=18620dfedb65860da00003e965cc09784a650ef6ecc9a17056405fe0a1392a02
@@ -432,7 +432,7 @@ class FocusWatcher(threading.Thread):
class WebSocket:
def __init__(self, url, timeout):
def __init__(self, url, timeout, bounded=False):
target = urllib.parse.urlsplit(url)
if (target.scheme != "ws" or target.hostname not in ("127.0.0.1", "::1", "localhost")
or target.username is not None or target.password is not None or target.fragment):
@@ -442,6 +442,7 @@ class WebSocket:
if target.query:
path += "?" + target.query
host = "127.0.0.1" if target.hostname == "localhost" else target.hostname
self.deadline = time.monotonic() + timeout if bounded else None
self.s = socket.create_connection((host, target.port or 80), timeout=timeout)
try:
self._handshake(path, hostport)
@@ -457,6 +458,7 @@ class WebSocket:
).encode())
head = b""
while b"\r\n\r\n" not in head:
self._wait()
chunk = self.s.recv(4096)
if not chunk:
raise OSError("DevTools closed the connection during the handshake")
@@ -468,8 +470,17 @@ class WebSocket:
raise OSError("DevTools refused the WebSocket: " + status.decode(errors="replace"))
self.buffer = head.split(b"\r\n\r\n", 1)[1]
def _wait(self):
if self.deadline is None:
return
left = self.deadline - time.monotonic()
if left <= 0:
raise socket.timeout("DevTools did not answer in time")
self.s.settimeout(left)
def _read(self, n):
while len(self.buffer) < n:
self._wait()
chunk = self.s.recv(65536)
if not chunk:
raise OSError("DevTools closed the connection")
@@ -547,22 +558,51 @@ def cdp_targets(agent_dir, timeout=5):
raise AgentError("DEVTOOLS_UNREACHABLE", "Could not reach the client's DevTools at %s: %s" % (url, e))
def cdp_eval(agent_dir, expression, target=None, await_promise=True, timeout=15):
targets = [t for t in cdp_targets(agent_dir) if t.get("webSocketDebuggerUrl")]
want = target or "SharedJSContext"
match = [t for t in targets if want in (t.get("title") or "") or want in (t.get("url") or "")]
if not match:
names = ", ".join(sorted({t.get("title") or t.get("url") or "?" for t in targets}))
raise AgentError("NO_TARGET", "No DevTools target matches '%s' (have: %s)" % (want, names))
ws = WebSocket(match[0]["webSocketDebuggerUrl"], timeout)
INSPECTOR_URL = re.compile(r"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}")
def inspector_url(url):
found = INSPECTOR_URL.fullmatch(url) if isinstance(url, str) else None
if not found or not 1024 <= int(found.group(1)) <= 65535:
raise AgentError("INVALID_REQUEST", "inspector must be a ws://127.0.0.1 inspector URL with its session id")
return url
def cdp_eval(agent_dir, expression, target=None, await_promise=True, timeout=15, inspector=None,
command_line_api=False):
if inspector is not None:
url, name = inspector_url(inspector), "inspector"
else:
targets = [t for t in cdp_targets(agent_dir) if t.get("webSocketDebuggerUrl")]
want = target or "SharedJSContext"
match = [t for t in targets if want in (t.get("title") or "") or want in (t.get("url") or "")]
if not match:
names = ", ".join(sorted({t.get("title") or t.get("url") or "?" for t in targets}))
raise AgentError("NO_TARGET", "No DevTools target matches '%s' (have: %s)" % (want, names))
url, name = match[0]["webSocketDebuggerUrl"], match[0].get("title")
try:
ws.send(json.dumps({"id": 1, "method": "Runtime.evaluate", "params": {
"expression": expression, "returnByValue": True, "awaitPromise": await_promise,
"userGesture": True,
}}))
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
message = json.loads(ws.recv())
ws = WebSocket(url, timeout, bounded=True)
except socket.timeout:
raise AgentError("TIMEOUT", "No answer from DevTools in %ss" % timeout)
except OSError as e:
raise AgentError("DEVTOOLS_UNREACHABLE", "Could not reach DevTools: %s" % e)
try:
try:
ws.send(json.dumps({"id": 1, "method": "Runtime.evaluate", "params": {
"expression": expression, "returnByValue": True, "awaitPromise": await_promise,
"userGesture": True, "includeCommandLineAPI": command_line_api,
}}))
except socket.timeout:
raise AgentError("TIMEOUT", "No answer from DevTools in %ss" % timeout)
except OSError as e:
raise AgentError("DEVTOOLS_UNREACHABLE", "DevTools went away: %s" % e)
while True:
try:
message = json.loads(ws.recv())
except socket.timeout:
raise AgentError("TIMEOUT", "No answer from DevTools in %ss" % timeout)
except OSError as e:
raise AgentError("DEVTOOLS_UNREACHABLE", "DevTools went away: %s" % e)
if message.get("id") != 1:
continue
if "error" in message:
@@ -573,9 +613,8 @@ def cdp_eval(agent_dir, expression, target=None, await_promise=True, timeout=15)
text = (details.get("exception") or {}).get("description") or details.get("text") or "exception"
raise AgentError("JS_EXCEPTION", text)
value = result.get("result", {})
return {"target": match[0].get("title"), "type": value.get("type"),
return {"target": name, "type": value.get("type"),
"value": value.get("value"), "description": value.get("description")}
raise AgentError("TIMEOUT", "No answer from DevTools in %ss" % timeout)
finally:
ws.close()
@@ -1157,7 +1196,7 @@ def handle(agent_dir, req):
if not isinstance(expression, str) or not expression:
raise AgentError("INVALID_REQUEST", "cdp eval needs an expression")
return cdp_eval(agent_dir, expression, req.get("target"), bool(req.get("awaitPromise", True)),
request_timeout(req, 15))
request_timeout(req, 15), req.get("inspector"), req.get("commandLineApi") is True)
if kind == "steam-selection":
return steam_selection(agent_dir, request_timeout(req, 5))
if kind == "quit":
+150
View File
@@ -0,0 +1,150 @@
#!/bin/bash
set -u
umask 077
self=${BASH_SOURCE[0]}
proc=${DD_PROC:-/proc}
state=${DD_CURSEFORGE_STATE:-${XDG_RUNTIME_DIR:-/tmp}/droiddeck-curseforge}
runner=${DD_APPIMAGE_RUN:-${self%/*}/droiddeck-appimage-run}
wait_s=${DD_CURSEFORGE_WAIT:-60}
cmd=${1:-}
dir=${2:-}
flag=--inspect-publish-uid=stderr
case $cmd in start|hold|stop|display) ;; *) echo "usage: droiddeck-curseforge start|hold|stop|display <imported AppImage directory>" >&2; exit 2 ;; esac
if [ "$cmd" != display ] && [ ! -d "$dir/app" ]; then
echo "droiddeck-curseforge: $dir is not an imported AppImage" >&2
exit 2
fi
x_display() {
if [ -n "${DISPLAY:-}" ]; then
printf '%s\n%s\n' "$DISPLAY" "${XAUTHORITY:-}"
return 0
fi
local p name a prev display auth
for p in "$proc"/[0-9]*; do
name=$(tr '\0' '\n' 2>/dev/null < "$p/cmdline" | head -n 1)
case ${name##*/} in Xwayland|Xorg|Xvfb) ;; *) continue ;; esac
display= auth= prev=
while IFS= read -r a; do
case $a in :[0-9]*) [ -z "$display" ] && display=$a ;; esac
[ "$prev" = -auth ] && auth=$a
prev=$a
done < <(tr '\0' '\n' 2>/dev/null < "$p/cmdline")
if [ -n "$display" ]; then
printf '%s\n%s\n' "$display" "$auth"
return 0
fi
done
return 1
}
running() {
local p
for p in "$proc"/[0-9]*; do
tr '\0' '\n' 2>/dev/null < "$p/cmdline" | grep -qF -- "$dir/app/" && return 0
done
return 1
}
started_at() {
local stat
stat=$(cat "/proc/$1/stat" 2>/dev/null) || return 1
stat=${stat##*) }
set -- $stat
echo "${20}"
}
tracked() {
local pid at launched
read -r pid at launched 2>/dev/null < "$state/pid" || return 1
case $pid in ''|*[!0-9]*) return 1 ;; esac
kill -0 "$pid" 2>/dev/null && [ "$(started_at "$pid")" = "$at" ] || return 1
printf '%s %s\n' "$pid" "$launched"
}
ours() {
local pid launched
read -r pid launched <<<"$(tracked)"
[ -n "$pid" ] && [ "$launched" = "$dir" ] && echo "$pid"
}
lock() {
mkdir -p "$state" && chmod 700 "$state" || return 1
exec 9>"$state/lock" || return 1
flock 9
}
inspector() {
grep -aom1 'ws://127\.0\.0\.1:[0-9]*/[0-9a-f]\{8\}-[0-9a-f]\{4\}-[0-9a-f]\{4\}-[0-9a-f]\{4\}-[0-9a-f]\{12\}' "$state/log" 2>/dev/null
}
start() {
local shown display auth url pid
lock || { echo "droiddeck-curseforge: cannot lock $state" >&2; return 5; }
if ! ours >/dev/null; then
if tracked >/dev/null || running; then
exec 9>&-
echo busy
return 3
fi
shown=$(x_display) || { exec 9>&-; echo "no X display" >&2; return 4; }
display=$(sed -n 1p <<<"$shown")
auth=$(sed -n 2p <<<"$shown")
env -u DBUS_SESSION_BUS_ADDRESS -u WAYLAND_DISPLAY -u GAMESCOPE_WAYLAND_DISPLAY DISPLAY="$display" ${auth:+XAUTHORITY="$auth"} \
setsid "$runner" "$dir" --minimized --inspect=127.0.0.1:0 "$flag" </dev/null >"$state/log" 2>&1 9>&- &
pid=$!
printf '%s %s %s\n' "$pid" "$(started_at "$pid")" "$dir" > "$state/pid"
fi
exec 9>&-
for _ in $(seq 1 $((wait_s * 2))); do
if url=$(inspector); then
echo "$url"
return 0
fi
ours >/dev/null || break
sleep 0.5
done
tail -n 20 "$state/log" >&2
return 5
}
stop() {
local pid p
lock || return 1
pid=$(ours) || { tracked >/dev/null || rm -f "$state/pid"; exec 9>&-; return 0; }
kill -TERM -- "-$pid" 2>/dev/null
for _ in $(seq 1 20); do
kill -0 -- "-$pid" 2>/dev/null || break
sleep 0.5
done
kill -KILL -- "-$pid" 2>/dev/null
for p in "$proc"/[0-9]*; do
tr '\0' '\n' 2>/dev/null < "$p/cmdline" | grep -qF -- "$dir/app/" && kill -KILL "${p##*/}" 2>/dev/null
done
rm -f "$state/pid"
exec 9>&-
return 0
}
case $cmd in
display)
x_display || exit 4
;;
start)
start
exit $?
;;
hold)
start >/dev/null || exit $?
trap 'stop; exit 0' TERM INT HUP
while ours >/dev/null; do
sleep 1 &
wait $!
done
exit 0
;;
stop)
stop
exit 0
;;
esac
@@ -713,14 +713,67 @@ x64_webhelper_gpu() {
x64_gpu && [ "${DD_X64_CLIENT_SOFTWARE:-0}" != 1 ] && [ "${DD_X64_CEF_GPU:-1}" != 0 ]
}
x64_thunk_appconfigs() {
python3 - "$1" "$2" "$3" "$4" <<'PY' || true
import json, os, sys, tempfile
src, dst, cfg, on = sys.argv[1:5]
want = json.loads(cfg)
try:
names = sorted(os.listdir(src))
except OSError:
names = []
for name in names:
if not name.endswith(".json"):
continue
try:
db = json.load(open(os.path.join(src, name), encoding="utf-8")).get("ThunksDB") or {}
if not any(k in want["ThunksDB"] and not v for k, v in db.items()):
continue
except (OSError, ValueError, AttributeError):
continue
path = os.path.join(dst, name)
try:
cur = json.load(open(path, encoding="utf-8"))
except FileNotFoundError:
cur = None
except (OSError, ValueError):
continue
if cur is not None and cur != want:
continue
if on == "1" and cur is None:
try:
os.makedirs(dst, exist_ok=True)
fd, tmp = tempfile.mkstemp(dir=dst, prefix=".fex", suffix=".tmp")
except OSError:
continue
try:
with os.fdopen(fd, "w", encoding="utf-8") as f:
f.write(cfg + "\n")
os.link(tmp, path)
except OSError:
pass
finally:
try:
os.remove(tmp)
except OSError:
pass
elif on != "1" and cur is not None:
try:
os.remove(path)
except OSError:
pass
PY
}
x64_env() {
export -p | grep -v -E '^declare -x (PWD|OLDPWD|SHLVL|_)=' > "$X64_HOME/arm-session.env.new" || true
mv -f "$X64_HOME/arm-session.env.new" "$X64_HOME/arm-session.env"
unset LD_LIBRARY_PATH LD_PRELOAD STEAM_RUNTIME STEAM_RUNTIME_PREFER_HOST_LIBRARIES
gpu_vars="GALLIUM_DRIVER MESA_LOADER_DRIVER_OVERRIDE VK_ICD_FILENAMES VK_DRIVER_FILES LIBGL_KOPPER_DRI2 ZINK_DEBUG ZINK_DESCRIPTORS TU_DEBUG MESA_NO_ERROR mesa_glthread"
thunk_cfg='{"ThunksDB": {"GL": 1, "Vulkan": 1}}'
rm -f "$X64_HOME/game-gpu.env"
if x64_gpu; then
printf '{"ThunksDB": {"GL": 1, "Vulkan": 1}}\n' > "$X64_HOME/thunks.json"
printf '%s\n' "$thunk_cfg" > "$X64_HOME/thunks.json"
{
echo "export FEX_THUNKCONFIG='$X64_HOME/thunks.json'"
echo "unset LIBGL_ALWAYS_SOFTWARE LIBGL_DRI3_DISABLE GALLIUM_DRIVER"
@@ -729,7 +782,10 @@ if x64_gpu; then
done
} > "$X64_HOME/game-gpu.env"
fi
if x64_gpu && [ "${DD_X64_CLIENT_SOFTWARE:-0}" != 1 ]; then
client_thunks=0
x64_gpu && [ "${DD_X64_CLIENT_SOFTWARE:-0}" != 1 ] && client_thunks=1
x64_thunk_appconfigs /usr/local/share/fex-emu/AppConfig "$X64_HOME/.config/fex-emu/AppConfig" "$thunk_cfg" "$client_thunks"
if [ "$client_thunks" = 1 ]; then
export FEX_THUNKCONFIG=$X64_HOME/thunks.json
unset LIBGL_ALWAYS_SOFTWARE LIBGL_DRI3_DISABLE
else
+111 -27
View File
@@ -22,6 +22,7 @@
#include <stdarg.h>
#include <stddef.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
@@ -520,6 +521,13 @@ static void write_table(FILE *out, const char *table, const struct link *link) {
fprintf(out, "%6s: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n", link->name);
} else if (strcmp(table, "arp") == 0) {
fprintf(out, "IP address HW type Flags HW address Mask Device\n");
} else if (strcmp(table, "tcp") == 0 || strcmp(table, "udp") == 0) {
fprintf(out, " sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode%s\n",
table[0] == 'u' ? " ref pointer drops" : "");
} else if (strcmp(table, "tcp6") == 0 || strcmp(table, "udp6") == 0) {
fprintf(out, " sl local_address remote_address "
"st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode%s\n",
table[0] == 'u' ? " ref pointer drops" : "");
} else {
fprintf(out, "1\n");
}
@@ -527,7 +535,10 @@ static void write_table(FILE *out, const char *table, const struct link *link) {
#define CARRIER_TABLE 5
static const char *const net_tables[] = { "route", "ipv6_route", "if_inet6", "dev", "arp", "carrier" };
#define SOCKET_TABLES 6
static const char *const net_tables[] = { "route", "ipv6_route", "if_inet6", "dev", "arp", "carrier",
"tcp", "tcp6", "udp", "udp6" };
static long long net_denied_at[sizeof(net_tables) / sizeof(net_tables[0])];
#define CARRIER_SLOTS 8
@@ -564,8 +575,8 @@ static void remember_denial(int table, const char *path) {
static int denied_table(const char *path) {
if (strncmp(path, "/proc/net/", 10) == 0) {
for (int i = 0; i < CARRIER_TABLE; i++) {
if (strcmp(path + 10, net_tables[i]) == 0) return i;
for (int i = 0; i < (int) (sizeof(net_tables) / sizeof(net_tables[0])); i++) {
if (i != CARRIER_TABLE && strcmp(path + 10, net_tables[i]) == 0) return i;
}
return -1;
}
@@ -576,17 +587,17 @@ static int denied_table(const char *path) {
return -1;
}
static FILE *synthesize(const char *table) {
static FILE *synthesize(int table) {
struct link link;
if (!load_link(&link)) return NULL;
int fd = memfd_create("droiddeck-net", MFD_CLOEXEC);
if (!load_link(&link) && table < SOCKET_TABLES) return NULL;
int fd = memfd_create("droiddeck-net", MFD_CLOEXEC | MFD_ALLOW_SEALING);
if (fd < 0) return NULL;
FILE *out = fdopen(fd, "w+");
if (out == NULL) {
close(fd);
return NULL;
}
write_table(out, table, &link);
write_table(out, net_tables[table], &link);
if (fflush(out) != 0) {
fclose(out);
return NULL;
@@ -610,11 +621,11 @@ static FILE *open_stream(fopen_fn real, const char *path, const char *mode, cons
path = dd_oom_adj_redirect(path, mode && (mode[0] == 'w' || mode[0] == 'a' || strchr(mode, '+')));
int table = path && mode && mode[0] == 'r' ? denied_table(path) : -1;
FILE *f;
if (table >= 0 && denied_recently(table, path) && (f = synthesize(net_tables[table])) != NULL) return f;
if (table >= 0 && denied_recently(table, path) && (f = synthesize(table)) != NULL) return f;
f = real(path, mode);
if (f || table < 0) return f;
int saved = errno;
if ((f = synthesize(net_tables[table])) != NULL) {
if ((f = synthesize(table)) != NULL) {
if (saved == EACCES) remember_denial(table, path);
return f;
}
@@ -622,6 +633,33 @@ static FILE *open_stream(fopen_fn real, const char *path, const char *mode, cons
return NULL;
}
int dd_net_open(const char *path, int flags, int fd) __attribute__((visibility("hidden")));
int dd_net_open(const char *path, int flags, int fd) {
if (fd >= 0 || path == NULL || (flags & O_ACCMODE) != O_RDONLY || (flags & O_DIRECTORY)) return fd;
int table = denied_table(path);
if (table < 0) return fd;
int saved = errno;
FILE *f = synthesize(table);
if (f == NULL) {
errno = saved;
return fd;
}
char self[32];
snprintf(self, sizeof(self), "/proc/self/fd/%d", fileno(f));
int copy = open(self, O_RDONLY | (flags & O_CLOEXEC));
if (copy < 0 && fcntl(fileno(f), F_ADD_SEALS, F_SEAL_SHRINK | F_SEAL_GROW | F_SEAL_WRITE | F_SEAL_SEAL) == 0) {
copy = fcntl(fileno(f), flags & O_CLOEXEC ? F_DUPFD_CLOEXEC : F_DUPFD, 0);
}
fclose(f);
if (copy < 0) {
errno = saved;
return fd;
}
if (saved == EACCES) remember_denial(table, path);
return copy;
}
FILE *fopen(const char *path, const char *mode) {
static fopen_fn real;
if (real == NULL) real = (fopen_fn) dlsym(RTLD_NEXT, "fopen");
@@ -664,6 +702,7 @@ struct nl_socket {
unsigned references;
int type;
int cap_ack;
uint64_t groups;
struct nl_socket *next;
};
@@ -685,13 +724,14 @@ struct nl_fd_page {
struct nl_metadata {
uint64_t nonce;
uint64_t groups;
uint32_t port;
uint32_t type;
uint32_t cap_ack;
char magic[12];
};
_Static_assert(sizeof(struct nl_metadata) == 32, "netlink socket metadata ABI");
_Static_assert(sizeof(struct nl_metadata) == 40, "netlink socket metadata ABI");
struct nl_packet {
struct nl_packet *next;
@@ -705,9 +745,9 @@ struct nl_reply {
int overflow;
};
static const char nl_client_magic[12] = "dd-nl-c-v1";
static const char nl_peer_magic[12] = "dd-nl-p-v1";
static const char nl_reservation_magic[12] = "dd-nl-r-v1";
static const char nl_client_magic[12] = "dd-nl-c-v2";
static const char nl_peer_magic[12] = "dd-nl-p-v2";
static const char nl_reservation_magic[12] = "dd-nl-r-v2";
static struct nl_socket *nl_sockets;
static struct nl_fd *nl_fds;
static struct nl_fd_page *nl_fd_pages[NL_FD_BUCKETS];
@@ -910,13 +950,13 @@ static int nl_save_packets(int fd, struct nl_packet **packets) {
}
}
static int nl_replace_peer(int fd, struct nl_socket *socket, unsigned port, int capped) {
static int nl_replace_peer(int fd, struct nl_socket *socket, unsigned port, int capped, uint64_t groups) {
static int (*real_socket)(int, int, int);
static int (*real_close)(int);
if (real_socket == NULL) real_socket = (int (*)(int, int, int)) dlsym(RTLD_NEXT, "socket");
if (real_close == NULL) real_close = (int (*)(int)) dlsym(RTLD_NEXT, "close");
struct sockaddr_un client_addr, peer_addr;
struct nl_metadata client, peer = { .port = port, .type = socket->type, .cap_ack = capped };
struct nl_metadata client, peer = { .groups = groups, .port = port, .type = socket->type, .cap_ack = capped };
if (!nl_address(fd, 0, &client_addr, &client, nl_client_magic)) {
errno = EINVAL;
return -1;
@@ -955,6 +995,7 @@ static int nl_replace_peer(int fd, struct nl_socket *socket, unsigned port, int
socket->peer_inode = status.st_ino;
socket->port = port;
socket->cap_ack = capped;
socket->groups = groups;
errno = saved;
return replayed;
failed: {
@@ -1025,7 +1066,7 @@ static struct nl_fd *nl_restore(int fd) {
socket->device = status.st_dev;
socket->inode = status.st_ino;
socket->type = peer.type;
if (nl_replace_peer(fd, socket, peer.port, peer.cap_ack) != 0) {
if (nl_replace_peer(fd, socket, peer.port, peer.cap_ack, peer.groups) != 0) {
free(socket);
free(entry);
return NULL;
@@ -1159,7 +1200,7 @@ static int nl_peer_of(int fd) {
if (nl_address(fd, 1, &addr, &metadata, nl_peer_magic)) {
if ((metadata.nonce == socket->peer_inode
&& nl_identity(socket->peer, socket->device, socket->peer_inode))
|| nl_replace_peer(fd, socket, metadata.port, metadata.cap_ack) == 0) {
|| nl_replace_peer(fd, socket, metadata.port, metadata.cap_ack, metadata.groups) == 0) {
if (socket->port != 0 && (socket->reservation < 0
|| !nl_identity(socket->reservation, socket->device, socket->reservation_inode)))
nl_reserve_port(socket, socket->port);
@@ -1317,7 +1358,7 @@ static int nl_bind_port(int fd, unsigned requested, int automatic) {
}
if (other == NULL) {
if (nl_reserve_port(socket, port) == 0) {
result = nl_replace_peer(fd, socket, port, socket->cap_ack);
result = nl_replace_peer(fd, socket, port, socket->cap_ack, socket->groups);
if (result != 0) nl_close_reservation(socket);
break;
}
@@ -1342,6 +1383,23 @@ static int nl_autobind(int fd) {
return nl_bind_port(fd, 0, 1);
}
static int nl_set_groups(int fd, uint64_t keep, uint64_t add) {
int result = 0;
pthread_mutex_lock(&nl_sockets_lock);
struct nl_fd *entry = nl_find(fd);
if (entry) {
struct nl_socket *socket = entry->socket;
struct sockaddr_un addr;
struct nl_metadata metadata;
uint64_t current = nl_address(fd, 1, &addr, &metadata, nl_peer_magic) ? metadata.groups : socket->groups;
uint64_t groups = (current & keep) | add;
if (groups != current || groups != socket->groups)
result = nl_replace_peer(fd, socket, socket->port, socket->cap_ack, groups);
}
pthread_mutex_unlock(&nl_sockets_lock);
return result;
}
int dd_nl_bind(int fd, const struct sockaddr *addr, socklen_t len, int *rc) {
const struct sockaddr_nl *nl;
if (addr && len >= sizeof(sa_family_t) && addr->sa_family == AF_NETLINK) nl_discover(fd);
@@ -1352,15 +1410,39 @@ int dd_nl_bind(int fd, const struct sockaddr *addr, socklen_t len, int *rc) {
return 1;
}
nl = (const struct sockaddr_nl *) addr;
if (nl->nl_groups != 0) {
errno = EACCES;
*rc = -1;
return 1;
}
*rc = nl_bind_port(fd, nl->nl_pid, 0);
if (*rc == 0) *rc = nl_set_groups(fd, ~(uint64_t) UINT32_MAX, nl->nl_groups);
return 1;
}
static unsigned nl_groups_of(int fd) {
struct sockaddr_un addr;
struct nl_metadata metadata;
if (nl_address(fd, 1, &addr, &metadata, nl_peer_magic)) return (unsigned) metadata.groups;
unsigned groups = 0;
pthread_mutex_lock(&nl_sockets_lock);
struct nl_fd *entry = nl_find(fd);
if (entry) groups = (unsigned) entry->socket->groups;
pthread_mutex_unlock(&nl_sockets_lock);
return groups;
}
static int nl_membership(int fd, int option, const void *value, socklen_t len) {
unsigned group;
if (value == NULL || len < sizeof(group)) {
errno = value == NULL ? EFAULT : EINVAL;
return -1;
}
memcpy(&group, value, sizeof(group));
if (group == 0 || group > RTNLGRP_MAX) {
errno = EINVAL;
return -1;
}
if (group > 64) return 0;
uint64_t bit = (uint64_t) 1 << (group - 1);
return nl_set_groups(fd, ~bit, option == NETLINK_ADD_MEMBERSHIP ? bit : 0);
}
int dd_nl_getsockname(int fd, struct sockaddr *addr, socklen_t *len, int *rc) {
struct sockaddr_nl nl;
socklen_t size;
@@ -1373,6 +1455,7 @@ int dd_nl_getsockname(int fd, struct sockaddr *addr, socklen_t *len, int *rc) {
memset(&nl, 0, sizeof(nl));
nl.nl_family = AF_NETLINK;
nl.nl_pid = nl_port_of(fd);
nl.nl_groups = nl_groups_of(fd);
size = *len < sizeof(nl) ? *len : (socklen_t) sizeof(nl);
memcpy(addr, &nl, size);
*len = sizeof(nl);
@@ -1517,9 +1600,10 @@ int dd_nl_setsockopt(int fd, int level, int option, const void *value, socklen_t
*rc = real(peer, level, option, value, len);
return 1;
}
if (option != NETLINK_CAP_ACK && option != NETLINK_EXT_ACK) {
errno = option == NETLINK_ADD_MEMBERSHIP || option == NETLINK_DROP_MEMBERSHIP
? EACCES : ENOPROTOOPT;
if (option == NETLINK_ADD_MEMBERSHIP || option == NETLINK_DROP_MEMBERSHIP) {
*rc = nl_membership(fd, option, value, len);
} else if (option != NETLINK_CAP_ACK && option != NETLINK_EXT_ACK) {
errno = ENOPROTOOPT;
*rc = -1;
} else if (value == NULL || len < sizeof(int)) {
errno = value == NULL ? EFAULT : EINVAL;
@@ -1530,7 +1614,7 @@ int dd_nl_setsockopt(int fd, int level, int option, const void *value, socklen_t
memcpy(&enabled, value, sizeof(enabled));
pthread_mutex_lock(&nl_sockets_lock);
struct nl_fd *entry = nl_find(fd);
if (entry && nl_replace_peer(fd, entry->socket, entry->socket->port, enabled != 0) != 0) {
if (entry && nl_replace_peer(fd, entry->socket, entry->socket->port, enabled != 0, entry->socket->groups) != 0) {
pthread_mutex_unlock(&nl_sockets_lock);
*rc = -1;
return 1;
+3 -2
View File
@@ -17,6 +17,7 @@ int dd_ntsync_open(const char *path, int flags) __attribute__((visibility("hidde
const char *dd_oom_adj_redirect(const char *path, int writing) __attribute__((visibility("hidden")));
int dd_venc_open(const char *path, int flags) __attribute__((visibility("hidden")));
int dd_vdec_open(const char *path, int flags) __attribute__((visibility("hidden")));
int dd_net_open(const char *path, int flags, int fd) __attribute__((visibility("hidden")));
int dd_dircache_create(int dirfd, const char *path, int flags, mode_t mode,
int (*real)(int, const char *, int, mode_t)) __attribute__((visibility("hidden")));
@@ -62,7 +63,7 @@ static int open_from(const char *path, int flags, mode_t mode, const void *calle
fd = dd_dircache_create(AT_FDCWD, path, flags, mode, via_open);
if (retry_without_noatime(fd, flags)) fd = real_open(path, flags & ~O_NOATIME, mode);
if (fd < 0 && dd_writable_retry(AT_FDCWD, path, flags)) fd = real_open(path, flags & ~O_NOATIME, mode);
return fd;
return dd_net_open(path, flags, fd);
}
static int openat_from(int dirfd, const char *path, int flags, mode_t mode, const void *caller) {
@@ -85,7 +86,7 @@ static int openat_from(int dirfd, const char *path, int flags, mode_t mode, cons
fd = dd_dircache_create(dirfd, path, flags, mode, via_openat);
if (retry_without_noatime(fd, flags)) fd = real_openat(dirfd, path, flags & ~O_NOATIME, mode);
if (fd < 0 && dd_writable_retry(dirfd, path, flags)) fd = real_openat(dirfd, path, flags & ~O_NOATIME, mode);
return fd;
return dd_net_open(path, flags, fd);
}
int open(const char *path, int flags, ...) {
+173
View File
@@ -0,0 +1,173 @@
import os
import shlex
import shutil
import signal
import subprocess
import tempfile
import time
import unittest
from pathlib import Path
HELPER = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-curseforge"
URL = "ws://127.0.0.1:43117/0f8fad5b-d9cb-469f-a165-70867728950e"
class CurseForgeHelperTest(unittest.TestCase):
def setUp(self):
self.tmp = Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, self.tmp, True)
self.proc = self.tmp / "proc"
self.proc.mkdir()
self.dir = self.tmp / "curseforge"
(self.dir / "app").mkdir(parents=True)
self.state = self.tmp / "state"
self.runner = self.tmp / "runner"
self.seen = self.tmp / "seen"
self.runner.write_text(
"#!/bin/bash\n"
"printf '%%s\\n' \"DISPLAY=$DISPLAY\" \"XAUTHORITY=${XAUTHORITY-}\" \"WAYLAND=${WAYLAND_DISPLAY-}\" "
"\"DBUS=${DBUS_SESSION_BUS_ADDRESS-}\" \"$@\" > %s\n"
"mkdir -p %s/$$ && printf '%%s\\0' bash \"$0\" \"$@\" > %s/$$/cmdline\n"
"echo 'Debugger listening on %s'\n"
"echo 'For help, see: https://nodejs.org/en/docs/inspector'\n"
"exec sleep 60\n"
% (shlex.quote(str(self.seen)), shlex.quote(str(self.proc)), shlex.quote(str(self.proc)), URL))
self.runner.chmod(0o755)
def fake(self, pid, *argv):
d = self.proc / str(pid)
d.mkdir()
(d / "cmdline").write_bytes(b"".join(a.encode() + b"\0" for a in argv))
def env(self, extra=None):
base = {k: v for k, v in os.environ.items() if k not in ("DISPLAY", "XAUTHORITY")}
base.update(DD_PROC=str(self.proc), DD_CURSEFORGE_STATE=str(self.state), DD_APPIMAGE_RUN=str(self.runner),
DD_CURSEFORGE_WAIT="10", WAYLAND_DISPLAY="wayland-0", DBUS_SESSION_BUS_ADDRESS="unix:path=/x")
base.update(extra or {})
return base
def run_helper(self, *args, env=None):
return subprocess.run(["bash", str(HELPER), *args], env=self.env(env), capture_output=True, text=True, timeout=60)
def stop(self):
self.run_helper("stop", str(self.dir))
def pid(self):
return int((self.state / "pid").read_text().split()[0])
def gone(self, pid):
for _ in range(50):
try:
os.kill(pid, 0)
except ProcessLookupError:
return True
time.sleep(0.1)
return False
def test_the_desktop_x_display_is_found_from_xwayland(self):
self.fake(40, "/usr/bin/kwin_wayland", ":9")
self.fake(41, "/usr/bin/Xwayland", ":0", "-rootless", "-auth", "/run/droiddeck/xauth_abc", "-listenfd", "5")
out = self.run_helper("display", "")
self.assertEqual(0, out.returncode, out.stderr)
self.assertEqual([":0", "/run/droiddeck/xauth_abc"], out.stdout.splitlines())
def test_the_session_display_wins(self):
self.fake(41, "/usr/bin/Xwayland", ":3")
out = self.run_helper("display", "", env={"DISPLAY": ":0"})
self.assertEqual(":0", out.stdout.splitlines()[0])
def test_no_display_is_reported(self):
out = self.run_helper("start", str(self.dir))
self.assertEqual(4, out.returncode)
def test_a_running_instance_without_the_inspector_is_busy(self):
self.fake(50, "/usr/bin/FEX", str(self.dir) + "/app/curseforge", "--no-sandbox")
out = self.run_helper("start", str(self.dir), env={"DISPLAY": ":0"})
self.assertEqual(3, out.returncode)
self.assertEqual("busy", out.stdout.strip())
self.stop()
self.assertTrue((self.proc / "50").exists())
def test_start_uses_a_random_port_and_a_secret_inspector_url_kept_private(self):
self.fake(41, "/usr/bin/Xwayland", ":0", "-auth", "/run/droiddeck/xauth_abc")
out = self.run_helper("start", str(self.dir))
self.addCleanup(self.stop)
self.assertEqual(0, out.returncode, out.stderr)
self.assertEqual(URL, out.stdout.strip())
seen = self.seen.read_text().splitlines()
self.assertEqual(["DISPLAY=:0", "XAUTHORITY=/run/droiddeck/xauth_abc", "WAYLAND=", "DBUS=", str(self.dir),
"--minimized", "--inspect=127.0.0.1:0", "--inspect-publish-uid=stderr"], seen)
self.assertEqual(0o700, self.state.stat().st_mode & 0o777)
self.assertEqual(0o600, (self.state / "log").stat().st_mode & 0o777)
again = self.run_helper("start", str(self.dir))
self.assertEqual(URL, again.stdout.strip())
pid = self.pid()
self.stop()
self.assertFalse((self.state / "pid").exists())
self.assertTrue(self.gone(pid), "the started instance is still running")
def test_hold_keeps_the_app_until_it_is_signalled(self):
held = subprocess.Popen(["bash", str(HELPER), "hold", str(self.dir)], env=self.env({"DISPLAY": ":0"}),
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
self.addCleanup(self.end, held)
for _ in range(100):
if (self.state / "pid").exists() and self.seen.exists():
break
time.sleep(0.1)
pid = self.pid()
time.sleep(1)
self.assertIsNone(held.poll())
held.send_signal(signal.SIGTERM)
self.assertEqual(0, held.wait(timeout=30))
self.assertTrue(self.gone(pid), "hold left the app running")
self.assertFalse((self.state / "pid").exists())
def end(self, held):
if held.poll() is None:
held.send_signal(signal.SIGTERM)
try:
held.wait(timeout=15)
except subprocess.TimeoutExpired:
held.kill()
held.wait()
record = self.state / "pid"
if record.exists():
try:
os.killpg(self.pid(), signal.SIGKILL)
except (ProcessLookupError, PermissionError):
pass
def test_a_launch_for_another_directory_is_busy(self):
other = self.tmp / "other"
(other / "app").mkdir(parents=True)
first = self.run_helper("start", str(self.dir), env={"DISPLAY": ":0"})
self.addCleanup(self.stop)
self.assertEqual(0, first.returncode, first.stderr)
out = self.run_helper("start", str(other), env={"DISPLAY": ":0"})
self.assertEqual(3, out.returncode)
self.assertEqual("busy", out.stdout.strip())
pid = self.pid()
self.run_helper("stop", str(other))
self.assertEqual(pid, self.pid())
os.kill(pid, 0)
def test_hold_ends_when_the_app_exits(self):
proc = shlex.quote(str(self.proc))
self.runner.write_text("#!/bin/bash\nmkdir -p %s/$$ && printf '%%s\\0' bash \"$0\" \"$@\" > %s/$$/cmdline\n"
"echo 'Debugger listening on %s'\nsleep 2\nrm -r %s/$$\n" % (proc, proc, URL, proc))
out = subprocess.run(["bash", str(HELPER), "hold", str(self.dir)], env=self.env({"DISPLAY": ":0"}),
capture_output=True, text=True, timeout=60)
self.assertEqual(0, out.returncode, out.stderr)
def test_stop_without_a_launch_is_quiet(self):
out = self.run_helper("stop", str(self.dir))
self.assertEqual(0, out.returncode)
self.assertEqual("", out.stderr)
def test_bad_arguments_are_refused(self):
self.assertEqual(2, self.run_helper("start", str(self.tmp / "missing")).returncode)
self.assertEqual(2, self.run_helper("launch", str(self.dir)).returncode)
if __name__ == "__main__":
unittest.main()
+33
View File
@@ -348,6 +348,23 @@ class AgentTest(unittest.TestCase):
self.assertEqual("INVALID_TARGET", caught.exception.code)
connect.assert_not_called()
def test_a_devtools_endpoint_lost_while_sending_is_reported_as_gone(self):
class Lost:
def __init__(self, *args, **kwargs):
pass
def send(self, text):
raise BrokenPipeError("closed")
def close(self):
pass
with patch.object(agent, "WebSocket", Lost), patch.object(
agent, "cdp_targets", return_value=[{"title": "SharedJSContext", "webSocketDebuggerUrl": "ws://127.0.0.1:1/x"}]):
with self.assertRaises(agent.AgentError) as caught:
agent.cdp_eval(str(self.dir), "1")
self.assertEqual("DEVTOOLS_UNREACHABLE", caught.exception.code)
def test_cdp_without_a_port(self):
os.environ.pop("DD_CDP_PORT", None)
self.assertEqual("NO_DEVTOOLS", self.ask({"kind": "cdp", "expression": "1"})["error"]["code"])
@@ -368,6 +385,22 @@ class AgentTest(unittest.TestCase):
missing = self.ask({"kind": "cdp", "expression": "1", "target": "Nope"})
self.assertEqual("NO_TARGET", missing["error"]["code"])
def test_cdp_eval_on_a_secret_inspector_url(self):
server = FakeDevTools({"result": {"result": {"type": "string", "value": "ok"}}})
server.start()
self.addCleanup(server.server.close)
os.environ.pop("DD_CDP_PORT", None)
url = "ws://127.0.0.1:%d/0f8fad5b-d9cb-469f-a165-70867728950e" % server.port
answer = self.ask({"kind": "cdp", "expression": "require('electron')", "inspector": url, "commandLineApi": True})
self.assertTrue(answer["ok"], answer)
self.assertEqual("inspector", answer["target"])
self.assertTrue(server.seen[0]["params"]["includeCommandLineAPI"])
def test_cdp_refuses_inspector_urls_without_a_session_id(self):
for url in ("ws://127.0.0.1:9229/", "ws://127.0.0.1:9229/json/list", "ws://10.0.0.2:9229/0f8fad5b-d9cb-469f-a165-70867728950e",
"ws://127.0.0.1:80/0f8fad5b-d9cb-469f-a165-70867728950e", "ws://127.0.0.1:9229/0f8fad5b-d9cb-469f-a165-70867728950e/x", 9229):
self.assertEqual("INVALID_REQUEST", self.ask({"kind": "cdp", "expression": "1", "inspector": url})["error"]["code"])
def test_steam_selection(self):
with patch.object(agent, "cdp_eval", return_value={"value": "3180310"}) as evaluate:
answer = self.ask({"kind": "steam-selection"})
+211
View File
@@ -0,0 +1,211 @@
import re
import shutil
import subprocess
import tempfile
import unittest
from pathlib import Path
PATCH = Path(__file__).resolve().parents[1] / "fex/patches/0006-smc-alias-of-code-created-after-translation.patch"
HARNESS = r"""
#include <algorithm>
#include <cstdint>
#include <cstdio>
#include <map>
#include <string>
#include <sys/mman.h>
namespace FEXCore::Config {
enum { CONFIG_SMC_NONE, CONFIG_SMC_MTRACK, CONFIG_SMC_FULL };
}
namespace LogMan::Throw {
template<typename... Args> void AFmt(bool, const char*, Args...) {}
}
union VMAProt {
struct { bool Readable : 1; bool Writable : 1; bool Executable : 1; };
};
struct VMAFlags { bool Shared : 1; };
struct MappedResource;
struct VMAEntry {
MappedResource* Resource;
VMAEntry* ResourcePrevVMA;
VMAEntry* ResourceNextVMA;
uint64_t Base, Offset, Length;
VMAFlags Flags;
VMAProt Prot;
};
struct MappedResource { VMAEntry* FirstVMA; };
struct VMATrackingT {
std::map<uint64_t, VMAEntry> VMAs;
std::map<uint64_t, VMAEntry>::const_iterator FindVMAEntry(uint64_t Addr) const {
auto it = VMAs.upper_bound(Addr);
if (it == VMAs.begin()) return VMAs.end();
--it;
return Addr < it->first + it->second.Length ? it : VMAs.end();
}
};
struct Recorded { uint64_t Address, Length; int Prot; };
static Recorded calls[16];
static int count;
static int fake_mprotect(void* address, size_t length, int prot) {
calls[count++] = {(uint64_t)address, length, prot};
return 0;
}
#define mprotect fake_mprotect
struct SyscallHandler {
int SMCChecks = FEXCore::Config::CONFIG_SMC_MTRACK;
VMATrackingT VMATracking;
void ProtectWritableAliasOfCode(uint64_t Base, uint64_t Length);
};
#include "extracted.inc"
static MappedResource resource, other;
int main(int argc, char** argv) {
std::string scenario = argc > 1 ? argv[1] : "";
SyscallHandler handler;
VMAEntry code{}, alias{};
code.Resource = &resource;
code.Base = 0x100000;
code.Offset = 0x10000;
code.Length = 0x4000;
code.Flags.Shared = true;
code.Prot.Readable = true;
code.Prot.Executable = true;
alias.Resource = &resource;
alias.Base = 0x700000;
alias.Offset = 0x10000;
alias.Length = 0x4000;
alias.Flags.Shared = true;
alias.Prot.Readable = true;
alias.Prot.Writable = true;
uint64_t base = alias.Base, length = alias.Length;
if (scenario == "disjoint") {
code.Offset = 0x80000;
} else if (scenario == "partial") {
code.Offset = 0x12000;
code.Length = 0x1000;
} else if (scenario == "tail") {
base += 0x2000;
length = 0x10000;
} else if (scenario == "gap") {
base -= 0x2000;
length = 0x6000;
} else if (scenario == "two") {
length = 0x6000;
} else if (scenario == "no_code") {
code.Prot.Executable = false;
} else if (scenario == "private") {
alias.Flags.Shared = false;
} else if (scenario == "read_only") {
alias.Prot.Writable = false;
} else if (scenario == "full") {
handler.SMCChecks = FEXCore::Config::CONFIG_SMC_FULL;
} else if (scenario == "none") {
handler.SMCChecks = FEXCore::Config::CONFIG_SMC_NONE;
}
code.ResourceNextVMA = &alias;
alias.ResourcePrevVMA = &code;
resource.FirstVMA = &code;
handler.VMATracking.VMAs[code.Base] = code;
handler.VMATracking.VMAs[alias.Base] = alias;
handler.VMATracking.VMAs[code.Base].ResourceNextVMA = &handler.VMATracking.VMAs[alias.Base];
handler.VMATracking.VMAs[alias.Base].ResourcePrevVMA = &handler.VMATracking.VMAs[code.Base];
resource.FirstVMA = &handler.VMATracking.VMAs[code.Base];
handler.VMATracking.VMAs[code.Base].Resource = &resource;
handler.VMATracking.VMAs[alias.Base].Resource = &resource;
if (scenario == "two") {
VMAEntry& next_code = handler.VMATracking.VMAs[0x200000];
VMAEntry& next_alias = handler.VMATracking.VMAs[0x704000];
next_code = {};
next_code.Resource = &other;
next_code.Base = 0x200000;
next_code.Length = 0x2000;
next_code.Flags.Shared = true;
next_code.Prot.Readable = true;
next_code.Prot.Executable = true;
next_alias = {};
next_alias.Resource = &other;
next_alias.Base = 0x704000;
next_alias.Length = 0x2000;
next_alias.Flags.Shared = true;
next_alias.Prot.Readable = true;
next_alias.Prot.Writable = true;
next_code.ResourceNextVMA = &next_alias;
next_alias.ResourcePrevVMA = &next_code;
other.FirstVMA = &next_code;
}
handler.ProtectWritableAliasOfCode(base, length);
printf("%d", count);
for (int i = 0; i < count; i++) printf(" %llx+%llx:%d", (unsigned long long)calls[i].Address, (unsigned long long)calls[i].Length, calls[i].Prot);
printf("\n");
return 0;
}
"""
def extracted():
text = PATCH.read_text()
section = re.search(r"^diff --git a/\S*SyscallsSMCTracking\.cpp .*?(?=^diff --git |\Z)", text, re.S | re.M).group(0)
added = [line[1:] for line in section.splitlines() if line.startswith("+") and not line.startswith("+++")]
body = "\n".join(added)
start = body.index("void SyscallHandler::ProtectWritableAliasOfCode")
end = body.index("\n}\n", start) + 3
return body[start:end]
class SmcAliasTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
compiler = shutil.which("g++") or shutil.which("c++")
if not compiler:
raise unittest.SkipTest("no C++ compiler")
cls.tmp = Path(tempfile.mkdtemp(prefix="fex-smc-alias-"))
(cls.tmp / "extracted.inc").write_text(extracted())
(cls.tmp / "harness.cpp").write_text(HARNESS)
subprocess.run([compiler, "-std=c++20", "-fno-strict-aliasing", "-I", str(cls.tmp), "-o", str(cls.tmp / "harness"), str(cls.tmp / "harness.cpp")],
check=True, capture_output=True, text=True)
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.tmp, ignore_errors=True)
def run_scenario(self, name=""):
return subprocess.run([str(self.tmp / "harness"), name], check=True, capture_output=True, text=True).stdout.strip()
def test_writable_alias_of_translated_code_is_read_only_until_it_faults(self):
self.assertEqual(self.run_scenario(), "1 700000+4000:1")
def test_only_the_overlapping_part_of_the_alias_is_protected(self):
self.assertEqual(self.run_scenario("partial"), "1 702000+1000:1")
def test_alias_beyond_the_mapping_end_is_clamped(self):
self.assertEqual(self.run_scenario("tail"), "1 702000+2000:1")
def test_range_starting_in_a_gap_reaches_the_alias_after_it(self):
self.assertEqual(self.run_scenario("gap"), "1 700000+4000:1")
def test_every_alias_in_one_range_is_protected(self):
self.assertEqual(self.run_scenario("two"), "2 700000+4000:1 704000+2000:1")
def test_alias_of_another_file_range_is_untouched(self):
self.assertEqual(self.run_scenario("disjoint"), "0")
def test_alias_without_an_executable_mirror_is_untouched(self):
self.assertEqual(self.run_scenario("no_code"), "0")
def test_private_and_read_only_mappings_are_untouched(self):
self.assertEqual(self.run_scenario("private"), "0")
self.assertEqual(self.run_scenario("read_only"), "0")
def test_explicit_smc_check_settings_are_respected(self):
self.assertEqual(self.run_scenario("full"), "0")
self.assertEqual(self.run_scenario("none"), "0")
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,70 @@
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[2]
PATCH = ROOT / "tools/gamescope/patches/0140-focus-follows-window-opacity.patch"
def added_lines():
return [line[1:] for line in PATCH.read_text().splitlines() if line.startswith("+") and not line.startswith("+++")]
def patched_rule():
text = "\n".join(added_lines())
start = text.index("static bool")
return text[start:text.index("\n}\n", start) + 3]
PREAMBLE = r'''
#include <cassert>
#include <cstdio>
#define TRANSLUCENT 0x00000000
#define OPAQUE 0xffffffff
'''
MAIN = r'''
int main() {
assert(opacity_changes_focus_candidacy(TRANSLUCENT, OPAQUE));
assert(opacity_changes_focus_candidacy(TRANSLUCENT, 0x01010101u));
assert(opacity_changes_focus_candidacy(OPAQUE, TRANSLUCENT));
assert(opacity_changes_focus_candidacy(0x80808080u, TRANSLUCENT));
assert(!opacity_changes_focus_candidacy(0x40404040u, 0xc0c0c0c0u));
assert(!opacity_changes_focus_candidacy(OPAQUE, 0x80808080u));
assert(!opacity_changes_focus_candidacy(TRANSLUCENT, TRANSLUCENT));
assert(!opacity_changes_focus_candidacy(OPAQUE, OPAQUE));
puts("ok");
return 0;
}
'''
@unittest.skipUnless(shutil.which("c++"), "needs a C++ compiler")
class FocusOpacityRuleTest(unittest.TestCase):
def test_only_crossing_fully_transparent_changes_focus_candidacy(self):
with tempfile.TemporaryDirectory() as tmp:
source = Path(tmp) / "opacity.cpp"
binary = Path(tmp) / "opacity"
source.write_text(PREAMBLE + patched_rule() + MAIN)
subprocess.run(["c++", "-std=c++17", "-Wall", "-Werror", str(source), "-o", str(binary)], check=True)
self.assertEqual(subprocess.run([str(binary)], capture_output=True, text=True, check=True).stdout.strip(), "ok")
class FocusOpacityHandlerTest(unittest.TestCase):
def test_opacity_property_change_reevaluates_focus_when_candidacy_changes(self):
hunks = PATCH.read_text().split("\n@@ ")
handler = next(hunk for hunk in hunks if "handle_property_notify(" in hunk.split("\n", 1)[0])
added = [line[1:].strip() for line in handler.splitlines() if line.startswith("+")]
self.assertIn("const bool bFocusCandidacyChanged = opacity_changes_focus_candidacy( w->opacity, newOpacity );", added)
self.assertIn("MakeFocusDirty();", added)
context = [line[1:].strip() for line in handler.splitlines() if line.startswith(" ")]
self.assertIn("w->opacity = newOpacity;", context)
self.assertLess(added.index("const bool bFocusCandidacyChanged = opacity_changes_focus_candidacy( w->opacity, newOpacity );"), added.index("MakeFocusDirty();"))
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,168 @@
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[2]
PATCH = ROOT / "tools/gamescope/patches/0141-sdl-present-only-to-a-shown-window.patch"
def hunks():
return PATCH.read_text().split("\n@@ ")[1:]
def hunk_with(text):
return next(hunk for hunk in hunks() if text in hunk)
def added(hunk):
return [line[1:] for line in hunk.splitlines() if line.startswith("+") and not line.startswith("+++")]
def removed(hunk):
return [line[1:] for line in hunk.splitlines() if line.startswith("-") and not line.startswith("---")]
def set_window_shown():
text = "\n".join(added(hunk_with("CSDLConnector::SetWindowShown( bool bShown )\n")))
start = text.index("void CSDLConnector::SetWindowShown")
return text[start:text.index("\n\t}", start) + 3] + "\n"
def present_gate():
lines = hunk_with("int CSDLConnector::Present(").splitlines()
body = lines[next(i for i, line in enumerate(lines) if "int CSDLConnector::Present(" in line) + 1:]
return "\n".join(line[1:] for line in body if line.startswith("+")) + "\n"
HARNESS = r'''
#include <atomic>
#include <chrono>
#include <cstdio>
#include <mutex>
#include <thread>
struct SDL_Window {};
static std::atomic<bool> g_bAwaitingConfigure{ false };
static std::atomic<bool> g_bMapped{ false };
static std::atomic<int> g_nPresentsBeforeConfigure{ 0 };
static std::atomic<int> g_nPresentsWhileHidden{ 0 };
static std::atomic<int> g_nPresents{ 0 };
static void SDL_ShowWindow( SDL_Window * )
{
g_bAwaitingConfigure = true;
std::this_thread::sleep_for( std::chrono::milliseconds( 3 ) );
g_bAwaitingConfigure = false;
g_bMapped = true;
}
static void SDL_HideWindow( SDL_Window * )
{
g_bMapped = false;
}
static void vulkan_present_to_window()
{
for ( int i = 0; i < 2; i++ )
{
if ( g_bAwaitingConfigure )
g_nPresentsBeforeConfigure++;
if ( !g_bMapped )
g_nPresentsWhileHidden++;
std::this_thread::sleep_for( std::chrono::microseconds( 100 ) );
}
g_nPresents++;
}
struct CSDLConnector
{
void SetWindowShown( bool bShown );
int Present();
SDL_Window *m_pWindow = nullptr;
std::mutex m_WindowShownMutex;
bool m_bWindowShown = false;
};
SET_WINDOW_SHOWN
int CSDLConnector::Present()
{
PRESENT_GATE
vulkan_present_to_window();
return 0;
}
int main()
{
CSDLConnector connector;
std::atomic<bool> bStop{ false };
std::thread paint( [&] { while ( !bStop ) connector.Present(); } );
for ( int i = 0; i < 150; i++ )
{
connector.SetWindowShown( true );
std::this_thread::sleep_for( std::chrono::milliseconds( 1 ) );
connector.SetWindowShown( false );
std::this_thread::sleep_for( std::chrono::milliseconds( 1 ) );
}
connector.SetWindowShown( true );
std::this_thread::sleep_for( std::chrono::milliseconds( 5 ) );
bStop = true;
paint.join();
printf( "%d %d %d\n", g_nPresentsBeforeConfigure.load(), g_nPresentsWhileHidden.load(), g_nPresents.load() );
return 0;
}
'''
def run_harness(gate):
with tempfile.TemporaryDirectory() as tmp:
source = Path(tmp) / "show_present.cpp"
binary = Path(tmp) / "show_present"
source.write_text(HARNESS.replace("SET_WINDOW_SHOWN", set_window_shown()).replace("PRESENT_GATE", gate))
subprocess.run(["c++", "-std=c++17", "-Wall", "-Werror", "-pthread", str(source), "-o", str(binary)], check=True)
output = subprocess.run([str(binary)], capture_output=True, text=True, check=True, timeout=60).stdout
return [int(value) for value in output.split()]
@unittest.skipUnless(shutil.which("c++"), "needs a C++ compiler")
class ShowPresentRaceTest(unittest.TestCase):
def test_no_present_reaches_the_surface_while_it_waits_for_configure_or_is_hidden(self):
before_configure, while_hidden, presents = run_harness(present_gate())
self.assertEqual(0, before_configure)
self.assertEqual(0, while_hidden)
self.assertGreater(presents, 0)
def test_without_the_gate_the_harness_sees_presents_before_configure(self):
before_configure, while_hidden, presents = run_harness("")
self.assertGreater(before_configure, 0)
self.assertGreater(while_hidden, 0)
self.assertGreater(presents, 0)
class ShowPresentWiringTest(unittest.TestCase):
def test_visibility_event_shows_and_hides_through_the_connector(self):
hunk = hunk_with("m_Connector.SetWindowShown( m_bShown );")
self.assertIn("\t\t\t\t\t\t\tm_Connector.SetWindowShown( m_bShown );", added(hunk))
self.assertTrue(any("SDL_ShowWindow( m_Connector.GetSDLWindow() );" in line for line in removed(hunk)))
self.assertTrue(any("SDL_HideWindow( m_Connector.GetSDLWindow() );" in line for line in removed(hunk)))
def test_only_the_connector_calls_sdl_show_and_hide(self):
lines = [line for hunk in hunks() for line in added(hunk)]
self.assertEqual(["\t\t\tSDL_ShowWindow( m_pWindow );"], [line for line in lines if "SDL_ShowWindow" in line])
self.assertEqual(["\t\t\tSDL_HideWindow( m_pWindow );"], [line for line in lines if "SDL_HideWindow" in line])
def test_gate_comes_before_composition(self):
hunk = hunk_with("int CSDLConnector::Present(")
lines = hunk.splitlines()
gate = lines.index("+\t\tif ( !lock.owns_lock() || !m_bWindowShown )")
composite = next(i for i, line in enumerate(lines) if "vulkan_composite(" in line)
self.assertTrue(lines[composite].startswith(" "))
self.assertLess(gate, composite)
if __name__ == "__main__":
unittest.main()
+7 -3
View File
@@ -43,11 +43,15 @@ class HdrLiveSwitchTest(unittest.TestCase):
def test_the_gate_follows_the_display_not_the_setting(self):
text = (APP / "SessionActivity.kt").read_text()
start = text.index("val attached = CompositorHost.isStarted")
block = text[start:text.index("DriverSetupLog.write", start)]
block = text[start:text.index("CompositorHost.start(", start)]
request = block[block.index("nativeSetHdrRequest("):block.index("Log.i", block.index("nativeSetHdrRequest("))]
self.assertNotIn("SessionPrefs.hdr", block[:block.index("if (!SessionState.running)")])
self.assertNotIn("SessionPrefs.hdr", block)
self.assertIn("capable, false", request)
self.assertIn("SessionState.hdrCapable && SessionPrefs.hdr(this, mode)", block)
self.assertIn("if (!SessionState.running) CompositorHost.applyHdr(this, mode)", block)
host = (APP / "wayland/CompositorHost.kt").read_text()
gate = host[host.index("fun applyHdr("):]
gate = gate[:gate.index("\n }")]
self.assertIn("SessionState.hdrCapable && SessionPrefs.hdr(context, mode)", gate)
def test_both_switches_apply_to_the_running_session(self):
helper = (APP / "session/SessionHdr.kt").read_text()
+146 -4
View File
@@ -12,7 +12,10 @@ PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
SHIM = r"""
#define _GNU_SOURCE
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -92,6 +95,46 @@ FILE *fopen(const char *path, const char *mode) {
return real(path, mode);
}
static int denied(const char *path) {
const char *prefixes = getenv("NETLINK_TEST_DENIED");
if (!prefixes || !path) return 0;
for (const char *prefix = prefixes; *prefix;) {
size_t length = strcspn(prefix, ":");
if (length && !strncmp(path, prefix, length)) {
errno = EACCES;
return 1;
}
prefix += length + (prefix[length] == ':');
}
return 0;
}
int open(const char *path, int flags, ...) {
static int (*real)(const char *, int, ...);
if (!real) real = dlsym(RTLD_NEXT, "open");
va_list ap;
va_start(ap, flags);
mode_t mode = va_arg(ap, mode_t);
va_end(ap);
return denied(path) ? -1 : real(path, flags, mode);
}
int __open_2(const char *path, int flags) {
static int (*real)(const char *, int);
if (!real) real = dlsym(RTLD_NEXT, "__open_2");
return denied(path) ? -1 : real(path, flags);
}
int openat(int dirfd, const char *path, int flags, ...) {
static int (*real)(int, const char *, int, ...);
if (!real) real = dlsym(RTLD_NEXT, "openat");
va_list ap;
va_start(ap, flags);
mode_t mode = va_arg(ap, mode_t);
va_end(ap);
return denied(path) ? -1 : real(dirfd, path, flags, mode);
}
int close_range(unsigned int first, unsigned int last, int flags) {
return syscall(SYS_close_range, (long)first, (long)last, (long)flags, 0L, 0L, 0L);
}
@@ -137,6 +180,40 @@ static int route_socket(void) {
return descriptor;
}
static void proc_net_test(int denied, int sealed) {
static const char *const tables[] = {"/proc/net/tcp", "/proc/net/tcp6", "/proc/net/udp", "/proc/net/udp6"};
char text[512], target[128], link[64];
for (unsigned i = 0; i < sizeof(tables) / sizeof(tables[0]); i++) {
int descriptor = i % 2 ? openat(AT_FDCWD, tables[i], O_RDONLY | O_CLOEXEC) : open(tables[i], O_RDONLY | O_CLOEXEC);
require(descriptor >= 0, "socket table opens");
require(fcntl(descriptor, F_GETFD) & FD_CLOEXEC, "socket table keeps close-on-exec");
snprintf(link, sizeof(link), "/proc/self/fd/%d", descriptor);
ssize_t length = readlink(link, target, sizeof(target) - 1);
require(length > 0, "socket table target");
target[length] = 0;
require((strncmp(target, "/memfd:droiddeck-net", 20) == 0) == denied, "synthesized only when denied");
if (denied) {
if (sealed) {
require(fcntl(descriptor, F_GET_SEALS) & F_SEAL_WRITE, "socket table is sealed");
require(write(descriptor, "x", 1) < 0 && errno == EPERM, "sealed socket table rejects writes");
} else {
require((fcntl(descriptor, F_GETFL) & O_ACCMODE) == O_RDONLY, "socket table is read-only");
require(write(descriptor, "x", 1) < 0 && errno == EBADF, "socket table rejects writes");
}
ssize_t total = read(descriptor, text, sizeof(text) - 1);
require(total > 0, "socket table read");
text[total] = 0;
require(strstr(text, "local_address") && strchr(text, '\n') == text + total - 1, "header without sockets");
}
close(descriptor);
}
if (denied) {
require(open("/proc/net/tcp", O_WRONLY) < 0 && errno == EACCES, "socket table writes stay denied");
require(open("/proc/net/netstat", O_RDONLY) < 0 && errno == EACCES, "other tables stay denied");
require(open("/proc/net/tcp", O_RDONLY | O_DIRECTORY) < 0 && errno == EACCES, "directory opens stay denied");
}
}
static unsigned port_of(int descriptor) {
struct sockaddr_nl address;
socklen_t length = sizeof(address);
@@ -609,6 +686,13 @@ static void batch_test(int oversized) {
close(descriptor);
}
static unsigned groups_of(int descriptor) {
struct sockaddr_nl address;
socklen_t length = sizeof(address);
require(getsockname(descriptor, (struct sockaddr *)&address, &length) == 0, "getsockname");
return address.nl_groups;
}
static void inherited_test(int argc, char **argv) {
require(argc == 6, "inherited arguments");
int descriptor = atoi(argv[2]), closed = atoi(argv[4]), datagram = atoi(argv[5]);
@@ -616,6 +700,7 @@ static void inherited_test(int argc, char **argv) {
require(fcntl(closed, F_GETFD) == -1 && errno == EBADF, "cloexec descriptor closed");
require(port_of(descriptor) == port && !(fcntl(descriptor, F_GETFD) & FD_CLOEXEC),
"inherited bound port");
require(groups_of(descriptor) == RTMGRP_LINK, "membership survives exec");
socket_info(descriptor, SOCK_RAW);
socket_info(datagram, SOCK_DGRAM);
require(fcntl(datagram, F_GETFL) & O_NONBLOCK, "inherited nonblocking flag");
@@ -640,6 +725,9 @@ static void exec_test(const char *program, int forked) {
int enabled = 1;
require(setsockopt(descriptor, SOL_NETLINK, NETLINK_CAP_ACK, &enabled, sizeof(enabled)) == 0,
"inherited cap ack");
int group = RTNLGRP_LINK;
require(setsockopt(descriptor, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP, &group, sizeof(group)) == 0,
"inherited membership");
unsigned port = port_of(descriptor);
int alias = fcntl(descriptor, F_DUPFD, 100);
int closed = fcntl(descriptor, F_DUPFD_CLOEXEC, 200);
@@ -718,8 +806,8 @@ static void ack_test(const char *mode) {
static void options_test(void) {
int descriptor = route_socket();
int group = RTNLGRP_LINK;
require(setsockopt(descriptor, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP, &group, sizeof(group)) == -1
&& errno == EACCES, "membership denied");
require(setsockopt(descriptor, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP, &group, sizeof(group)) == 0,
"membership accepted");
require(setsockopt(descriptor, SOL_NETLINK, NETLINK_PKTINFO, &group, sizeof(group)) == -1
&& errno == ENOPROTOOPT, "unsupported option");
require(setsockopt(descriptor, SOL_NETLINK, NETLINK_EXT_ACK, &group, sizeof(group)) == 0, "ext ack");
@@ -735,6 +823,44 @@ static void options_test(void) {
close(descriptor);
}
static void subscribe_test(void) {
unsigned wanted = RTMGRP_LINK | RTMGRP_IPV4_IFADDR | RTMGRP_IPV6_IFADDR;
int descriptor = socket(AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_ROUTE);
struct sockaddr_nl address = {.nl_family = AF_NETLINK, .nl_groups = wanted};
require(descriptor >= 0, "socket");
require(bind(descriptor, (struct sockaddr *)&address, sizeof(address)) == 0, "bind with groups");
require(groups_of(descriptor) == wanted, "bound groups");
int group = RTNLGRP_IPV4_ROUTE;
require(setsockopt(descriptor, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP, &group, sizeof(group)) == 0,
"add membership");
require(groups_of(descriptor) == (wanted | RTMGRP_IPV4_ROUTE), "added group");
group = RTNLGRP_LINK;
require(setsockopt(descriptor, SOL_NETLINK, NETLINK_DROP_MEMBERSHIP, &group, sizeof(group)) == 0,
"drop membership");
require(groups_of(descriptor) == ((wanted & ~RTMGRP_LINK) | RTMGRP_IPV4_ROUTE), "dropped group");
pid_t child = fork();
require(child >= 0, "membership fork");
if (child == 0) {
group = RTNLGRP_IPV4_ROUTE;
_exit(setsockopt(descriptor, SOL_NETLINK, NETLINK_DROP_MEMBERSHIP, &group, sizeof(group)) == 0
&& groups_of(descriptor) == (wanted & ~RTMGRP_LINK) ? 0 : 1);
}
int status;
require(waitpid(child, &status, 0) == child && WIFEXITED(status) && WEXITSTATUS(status) == 0,
"membership child");
require(groups_of(descriptor) == (wanted & ~RTMGRP_LINK), "membership shared after fork");
group = 0;
require(setsockopt(descriptor, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP, &group, sizeof(group)) == -1
&& errno == EINVAL, "group zero refused");
struct timeval timeout = {.tv_usec = 30000};
require(setsockopt(descriptor, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) == 0, "receive timeout");
unsigned char buffer[4096];
require(recv(descriptor, buffer, sizeof(buffer), 0) == -1
&& (errno == EAGAIN || errno == EWOULDBLOCK), "no unsolicited events");
usable(descriptor);
close(descriptor);
}
static void dump_test(void) {
int descriptor = route_socket();
send_link(descriptor, 0, NLM_F_DUMP | NLM_F_ACK);
@@ -1040,6 +1166,7 @@ int main(int argc, char **argv) {
if (!strcmp(argv[1], "ack") || !strcmp(argv[1], "error") || !strcmp(argv[1], "capped"))
ack_test(argv[1]);
else if (!strcmp(argv[1], "options")) options_test();
else if (!strcmp(argv[1], "subscribe")) subscribe_test();
else if (!strcmp(argv[1], "dump")) dump_test();
else if (!strcmp(argv[1], "send_timeout")) send_timeout_test(0);
else if (!strcmp(argv[1], "nonblocking")) send_timeout_test(1);
@@ -1082,6 +1209,7 @@ int main(int argc, char **argv) {
}
else if (!strcmp(argv[1], "range") || !strcmp(argv[1], "cloexec") || !strcmp(argv[1], "closefrom"))
close_range_test(argv[1]);
else if (!strcmp(argv[1], "proc_net")) proc_net_test(argc > 2 && strcmp(argv[2], "allowed"), argc > 2 && !strcmp(argv[2], "sealed"));
else if (!strcmp(argv[1], "route")) {
require(argc >= 3, "route destination");
route_test(argv[2]);
@@ -1129,10 +1257,12 @@ class NetlinkPreloadTest(unittest.TestCase):
def tearDownClass(cls):
cls.temp.cleanup()
def run_program(self, mode, *arguments, snapshot=None):
def run_program(self, mode, *arguments, snapshot=None, denied=None):
env = dict(os.environ, LD_PRELOAD=f"{self.preload}:{self.shim}",
NETLINK_TEST_SNAPSHOT=str(snapshot or self.snapshot),
DD_SYSV_DIR=str(self.directory / "sysv"))
if denied:
env["NETLINK_TEST_DENIED"] = denied
result = subprocess.run([str(self.program), mode, *arguments], env=env,
capture_output=True, text=True, timeout=5)
self.assertEqual(0, result.returncode, result.stdout + result.stderr)
@@ -1207,9 +1337,12 @@ class NetlinkPreloadTest(unittest.TestCase):
def test_cloexec_sockets_release_their_ports_after_exec(self):
self.run_program("all_cloexec")
def test_subscription_is_denied_and_receive_timeout_is_applied(self):
def test_membership_is_accepted_and_receive_timeout_is_applied(self):
self.run_program("options")
def test_change_listeners_subscribe_and_still_query(self):
self.run_program("subscribe")
def test_dump_keeps_multipart_completion(self):
self.run_program("dump")
@@ -1249,6 +1382,15 @@ class NetlinkPreloadTest(unittest.TestCase):
with self.subTest(mode=mode):
self.run_program(mode)
def test_denied_socket_tables_open_as_empty_tables(self):
self.run_program("proc_net", "denied", denied="/proc/net/")
def test_denied_socket_tables_open_when_fd_reopen_is_denied(self):
self.run_program("proc_net", "sealed", denied="/proc/net/:/proc/self/fd/")
def test_readable_socket_tables_stay_real(self):
self.run_program("proc_net")
def test_loopback_and_own_addresses_are_local_routes(self):
for destination, source in (("127.0.0.2", "127.0.0.1"), ("::1", "::1"),
("192.168.1.10", "192.168.1.10"), ("2001:db8::10", "2001:db8::10")):
@@ -0,0 +1,89 @@
import json
import os
from pathlib import Path
import re
import subprocess
import tempfile
import unittest
SCRIPT = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-steam-x64'
SOURCE = SCRIPT.read_text()
FUNCTION = re.search(r'^x64_thunk_appconfigs\(\) \{\n.*?^\}\n', SOURCE, re.M | re.S).group()
CFG = '{"ThunksDB": {"GL": 1, "Vulkan": 1}}'
class SteamX64ThunkAppConfigsTest(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
root = Path(self.temp.name)
self.src = root / 'global'
self.dst = root / 'local'
self.src.mkdir()
def write_global(self, name, data):
(self.src / name).write_text(json.dumps(data))
def run_fn(self, on):
shell = FUNCTION + 'x64_thunk_appconfigs "$SRC" "$DST" "$CFG" "$ON"\n'
env = dict(os.environ, SRC=str(self.src), DST=str(self.dst), CFG=CFG, ON=on)
result = subprocess.run(['bash', '-eu', '-c', shell], env=env, capture_output=True, text=True, timeout=20)
self.assertEqual(0, result.returncode, result.stderr)
def test_program_with_a_disabled_thunk_gets_the_session_thunks(self):
self.write_global('anyprogram.json', {'Comment': 'x', 'ThunksDB': {'GL': 0}})
self.run_fn('1')
self.assertEqual(json.loads(CFG), json.loads((self.dst / 'anyprogram.json').read_text()))
def test_disabled_vulkan_counts_too(self):
self.write_global('other.json', {'ThunksDB': {'Vulkan': 0}})
self.run_fn('1')
self.assertTrue((self.dst / 'other.json').exists())
def test_programs_without_a_thunk_opt_out_are_untouched(self):
self.write_global('client.json', {'Config': {'HideHypervisorBit': '1'}})
self.write_global('enabled.json', {'ThunksDB': {'GL': 1}})
self.write_global('unrelated.json', {'ThunksDB': {'asound': 0}})
self.run_fn('1')
self.assertFalse(self.dst.exists())
def test_user_override_is_kept(self):
self.write_global('anyprogram.json', {'ThunksDB': {'GL': 0}})
self.dst.mkdir()
user = {'ThunksDB': {'GL': 0}, 'Config': {'Multiblock': '0'}}
(self.dst / 'anyprogram.json').write_text(json.dumps(user))
self.run_fn('1')
self.assertEqual(user, json.loads((self.dst / 'anyprogram.json').read_text()))
self.run_fn('0')
self.assertEqual(user, json.loads((self.dst / 'anyprogram.json').read_text()))
def test_software_mode_removes_only_the_written_file(self):
self.write_global('anyprogram.json', {'ThunksDB': {'GL': 0}})
self.run_fn('1')
self.run_fn('0')
self.assertFalse((self.dst / 'anyprogram.json').exists())
def test_software_mode_writes_nothing(self):
self.write_global('anyprogram.json', {'ThunksDB': {'GL': 0}})
self.run_fn('0')
self.assertFalse(self.dst.exists())
def test_broken_global_configs_do_not_fail(self):
(self.src / 'broken.json').write_text('{')
self.write_global('list.json', [1, 2])
self.run_fn('1')
self.assertFalse(self.dst.exists())
def test_missing_global_dir_does_not_fail(self):
self.src = self.src / 'missing'
self.run_fn('1')
self.assertFalse(self.dst.exists())
def test_launcher_applies_it_to_the_fex_app_config_dirs(self):
self.assertIn('x64_thunk_appconfigs /usr/local/share/fex-emu/AppConfig "$X64_HOME/.config/fex-emu/AppConfig" "$thunk_cfg" "$client_thunks"', SOURCE)
self.assertIn('''printf '%s\\n' "$thunk_cfg" > "$X64_HOME/thunks.json"''', SOURCE)
if __name__ == '__main__':
unittest.main()