Compare commits

..
Author SHA1 Message Date
The412Banner e2043a2405 Merge branch 'main' into fix/resume-zram-thrash 2026-11-21 23:36:18 -05:00
Kurt Himebauch b2687701c1 build: run the local macOS build natively, with no emulation (#2999)
build: make the local macOS build run natively, with no emulation

On an arm64 Mac the x86/i386 session preloads were built in a linux/amd64
container under emulation, and the Rockstar launcher failed to link against
Homebrew's SJLJ i686 mingw. Both now build on the host's own architecture.

- build_local.sh: on arm64 build the x86 preloads in a native arm64 Debian
  bullseye container with the x86_64/i686 cross toolchains (glibc 2.31, as
  before); x86 hosts keep the native gcc-multilib path.
- build-x86-preloads.sh: X86_CROSS=1 selects the cross toolchains.
- rockstar-launcher/build-container.sh: build the launcher in a native
  Ubuntu container with a DWARF2 mingw, used on macOS only.
- vr/build.sh: stop aborting silently when ANDROID_NDK_HOME names an NDK
  that is not installed.
- build_local.sh: expand the empty stores_check array safely on bash 3.2 so
  the script reaches its signing step.
2026-11-21 22:51:27 -05:00
The412Banner 7b7a3bd673 Merge branch 'main' into fix/resume-zram-thrash 2026-11-22 03:27:10 +00:00
MaxsTechReviewandKurt Himebauch 378175c6ac feat(input): controller-specific on-screen controls with editor, rotation and tablet fixes (#2988)
* feat(input): restore controller-specific overlay designs

* fix(input): restore portrait controller layouts

* fix(input): fix duplicates, rotation and tablet placement in the controller overlays

- Hide the below-game controls while the layout editor is open, and give the
  editor the same cutout insets and optional Steam controls as the game view,
  so the editor never shows a second copy of a control.
- Keep a separate portrait frame for layouts edited in portrait. A layout
  edited in one orientation keeps the stock kit positions in the other instead
  of being stretched across.
- Anchor the overlay to the bottom of the screen and cap the portrait panel's
  physical size, so tablets keep the controls in the lower half.
- Put L2/L1 and R1/R2 side by side in every kit.
- List deleted stock controls in the editor's Add dialog so they can be
  restored, and keep removed rear buttons and trackpads removed.

* fix(input): scale edited overlay layouts around the controller artwork positions

* fix(input): keep stock landscape controls, color setting, keyboard action and displayed frame edits consistent

* fix(input): draw the layout editor with the kit artwork at the size it will be saved

The editor placed its controls in onSizeChanged, which runs during layout, so
the preview canvas was rebuilt or remeasured too late: new controls were laid
out at 0x0 and existing ones kept stale sizes, losing the kit D-pad artwork.
Placement now happens in onMeasure, before the canvas measures its children.

The editor preview used the saved button size instead of the slider value, so
the slider showed a different layout from the one Done saved.

D-pad pieces that joined or left the kit cross were never redrawn, so moving
one piece hid all four.

* fix(input): keep portrait rear buttons and trackpads where they were saved

A portrait save stores the rear buttons and trackpads only in the rotated
frame, but loading that frame only moved controls that already existed in the
main frame, so they were regenerated at the screen edges.

* fix(input): adopt the displayed portrait frame for layouts edited only in landscape

Button size and reset positions now switch to the frame on screen whenever the edited layout's
orientation differs from the editor, not only when a rotated frame exists, so a portrait change
is saved as the portrait frame instead of overwriting the landscape edits. The tools panel stays
open while that happens.

* fix(input): keep a separate button size for the rotated frame

* fix(input): take the shown frame's button size whenever editing switches orientation

---------

Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
2026-11-21 20:11:21 -05:00
MaxsTechReview 183cbd9351 fix(preload): start apps that check for a single thread and stop the first-call allocation hang (#2995)
* fix(preload): look up the native glibc symbol version first so wrapped calls never allocate

On x86 the first dlvsym lookup asked for GLIBC_2.17, which only exists on arm64. The failed lookup makes glibc allocate, which deadlocks when the first wrapped call happens inside a program's own allocator setup. Each architecture now asks for its base version first.

* fix(zram): start the page-out worker per request instead of keeping a thread in every process

Every process that loaded the session preload carried a resident zr-worker thread from its constructor on. Programs that check they are single-threaded before forking or before unshare(CLONE_NEWUSER) failed, for example Chromium's zygote, which could not start its GPU process.

The signal handler now starts the worker with a raw clone on a stack the preload maps itself. The worker makes only raw system calls and exits when no request is left, so starting it from the handler is safe and idle processes stay single-threaded. When the worker cannot be started, the process trims inline in small steps as before.

* fix(preload): start the page-out worker with the same clone flags as a thread

Programs that filter clone to the flag set threads use, as browser
sandboxes do, now accept the worker. The kernel clears the stack-busy
word and wakes waiters when the worker exits.

* fix(preload): page out inline in single-threaded and self-sandboxed processes

A process with one thread may be about to check that it is single-threaded
before fork or unshare, and a process that added a seccomp filter after it
started may trap system calls into its own handler. Neither gets a worker
thread now; both trim inline in small steps as before.

* fix(preload): check the signalled thread's own seccomp filters before starting the worker

Read Seccomp_filters from /proc/thread-self/status so a thread that installed its own filter
without TSYNC trims inline instead of calling clone under that filter, and fall back to the
inline path when the signal mask cannot be changed.

* test(preload): start parked threads with SIGURG already blocked

* test(preload): count only page-out workers when checking for leftover threads
2026-11-21 20:11:18 -05:00
Kurt Himebauch 6af598b25e feat(launcher): tick haptics for controller navigation (#2993)
* feat(launcher): tick haptics for controller navigation, off for touch

* docs: regenerate settings map for controller haptics

* fix(launcher): tick for hat and stick navigation, which arrive as joystick-source keys

* fix(launcher): tick before the Components tab consumes L1/R1
2026-11-21 16:31:58 -05:00
MaxsTechReview 088c8ff1cf fix(battlenet): follow the selected FEX instead of pinning an old build (#2987)
* fix(battlenet): follow the selected FEX instead of pinning a d2rfix build

The Battle.net prefix forced the newest FEXCore d2rfix package from the Nightlies listing, which stopped updating. Its fixes are in the bundled and nightly FEX, so the prefix now uses whatever FEX is selected. Existing d2rfix selections for the Battle.net profile are cleared once; any other choice is kept. The DXVK memory cap and Start without Steam defaults are now applied when a session starts.

* fix(battlenet): import the legacy plugin state before unpinning the Battle.net FEX
2026-11-21 15:31:18 -05:00
Kurt Himebauch 31dd8f9987 feat(session): arrange and hide in-session menu pages, round pinned end-session button (#2989)
* feat(session): arrange and hide the in-session menu pages

* fix(session): the end-session button is a true circle pinned to the right of the menu header

* fix(session): arrange-pages drag reads the current list; reset reloads the page layout even if the activity was recreated

* fix(session): Back leaves Arrange pages first; UI zoo previews don't save page layout

* fix(session): Back on a grabbed page row restores its order before anything else
2026-11-21 15:25:45 -05:00
The412Banner f5fdc408aa fix(session): retry a deferred re-stop that does not settle 2026-11-21 05:36:37 +00:00
The412Banner 0d7175ea9a fix(session): keep a suspended session resident until memory runs short 2026-11-21 04:46:04 +00:00
The412Banner 3dac3ed47c fix(session): scope the post-resume read-back to the chosen processes 2026-11-20 20:39:33 +00:00
The412Banner a3470dbf6d Merge branch 'main' into fix/resume-zram-thrash 2026-11-20 08:29:35 -05:00
The412Banner 10aafd1079 Merge branch 'main' into fix/resume-zram-thrash 2026-11-20 02:08:38 -05:00
The412Banner 7323183580 Merge branch 'main' into fix/resume-zram-thrash 2026-11-20 00:10:32 -05:00
The412Banner 4cf766afb9 fix(session): merge main into the budgeted read-back
Main removed the RAM cap setting (#2853), so the read-back budget no
longer takes a cap; the RAM cap tests are replaced by one that checks a
process too large for the budget does not block the smaller ones.
2026-11-20 04:36:07 +00:00
The412Banner 6fbca0b6d1 fix(session): budget the post-resume read-back instead of skipping it 2026-11-16 15:53:07 +00:00
55 changed files with 2037 additions and 552 deletions

No files matched your search

@@ -46,6 +46,7 @@ class App : Application() {
com.droiddeck.launcher.input.ShortcutsRelay.Holder.install(this)
com.droiddeck.launcher.agent.AgentHost.refresh(this)
com.droiddeck.launcher.ui.NavTabs.load(this)
com.droiddeck.launcher.ui.DrawerPages.load(this)
com.droiddeck.launcher.ui.DeveloperTools.load(this)
com.droiddeck.launcher.ui.AgentPet.install(this)
if (com.droiddeck.launcher.agent.AgentTab.visible) com.droiddeck.launcher.lab.LabNotice.openOnInstall = "agent"
@@ -199,6 +199,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private var launcherOrientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER)
private var homePage by mutableStateOf(com.droiddeck.launcher.core.AppUiPrefs.HOME_PAGE_STEAM)
private var launcherFullscreen by mutableStateOf(true)
private var controllerHaptics by mutableStateOf(true)
private var downloadSource by mutableStateOf(DownloadSource.MODE_AUTO)
private var downloadMirror by mutableStateOf("")
private var downloadPrefix by mutableStateOf("")
@@ -1264,6 +1265,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
requestedOrientation = launcherOrientation
homePage = com.droiddeck.launcher.core.AppUiPrefs.homePage(this)
launcherFullscreen = SessionPrefs.launcherFullscreen(this)
controllerHaptics = SessionPrefs.controllerHaptics(this)
downloadSource = DownloadSource.mode(this)
downloadMirror = DownloadSource.mirror(this)
downloadPrefix = DownloadSource.custom(this)
@@ -1363,6 +1365,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
launcherOrientation = launcherOrientation,
homePage = homePage,
launcherFullscreen = launcherFullscreen,
controllerHaptics = controllerHaptics,
downloadSource = downloadSource,
downloadMirror = downloadMirror,
downloadPrefix = downloadPrefix,
@@ -1679,6 +1682,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
com.droiddeck.launcher.core.AppUiPrefs.setHomePage(this, value)
homePage = value
},
onControllerHaptics = { on -> SessionPrefs.setControllerHaptics(this, on); controllerHaptics = on },
onLauncherFullscreen = { on ->
SessionPrefs.setLauncherFullscreen(this, on)
launcherFullscreen = on
@@ -2047,6 +2051,7 @@ 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 (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)) {
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
@@ -3343,6 +3348,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
Thread({
val ok = com.droiddeck.launcher.session.SettingsReset.resetAll(this, gameProfiles, scopes)
ui.post {
com.droiddeck.launcher.ui.DrawerPages.load(applicationContext)
if (isDestroyed) return@post
com.droiddeck.launcher.core.AppLanguage.setChosen(this, com.droiddeck.launcher.core.AppLanguage.SYSTEM)
if (!ok) android.widget.Toast.makeText(this, R.string.setup_reset_settings_partial, android.widget.Toast.LENGTH_LONG).show()
@@ -5514,6 +5514,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
.takeIf { it.isFile }
?.let { FileUtils.readString(it)?.trim()?.lowercase() }
?: SessionPrefs.oscMode(this, SessionState.mode == SessionService.MODE_STEAM)
unfoldedColumn?.let { column ->
val shown = if (inputSettingsOpen) View.INVISIBLE else View.VISIBLE
if (column.visibility != shown) { unfoldedPanel?.releaseAll(); unfoldedDeckSurface?.releaseInputs(); column.visibility = shown }
}
val controls = onScreenControls ?: return
fun showPinned() {
controls.setPinnedOnly(true)
@@ -31,7 +31,7 @@ internal class ControllerOverlayGeometry(
private fun x(ref: Float) = anchor(ref, 1600f, w, safe.left, safe.right)
private fun y(ref: Float) = anchor(ref, 900f, h, safe.top, safe.bottom)
private fun y(ref: Float) = max(safe.top + ref * unit, h - safe.bottom - (900f - ref) * unit)
fun place(elements: List<InputSurfaceElement>, kit: PadKit, rearButtons: Boolean, trackpads: Boolean): List<InputSurfaceElement> {
if (!kit.steam) return placeStandardPad(elements, kit)
@@ -75,8 +75,9 @@ internal class ControllerOverlayGeometry(
else -> positions[element.control]?.place(element) ?: element
}
}
val chosen = placed.filter { it.id == "legacy:${it.control.id}" }.map { it.control }
return placed + optional.mapNotNull { (control, box) ->
if (placed.any { it.id == "legacy:${control.id}" }) null else box.place(InputSurfaceElement(control,
if (chosen.any { if (control in rear) it in rear else it in pads }) null else box.place(InputSurfaceElement(control,
0f, 0f, 0f, 0f, floating = false, buttonShape = InputButtonShape.PILL, showLabel = !control.isTrackpad))
}
}
@@ -123,10 +124,10 @@ internal class ControllerOverlayGeometry(
}
private fun shoulders() = mapOf(
InputControl.LT to Box(x(140f), y(66f), 88f, 34f),
InputControl.LB to Box(x(140f), y(148f), 88f, 30f),
InputControl.RT to Box(x(1460f), y(66f), 88f, 34f),
InputControl.RB to Box(x(1460f), y(148f), 88f, 30f),
InputControl.LT to Box(x(120f), y(96f), 80f, 34f),
InputControl.LB to Box(x(310f), y(96f), 80f, 34f),
InputControl.RB to Box(x(1290f), y(96f), 80f, 34f),
InputControl.RT to Box(x(1480f), y(96f), 80f, 34f),
)
private fun face(cx: Float, cy: Float, offset: Float) = mapOf(
@@ -22,15 +22,15 @@ internal class ControllerPortraitGeometry(
val rear = presented.filter { it.control in REAR && isStock(it) }
val pads = presented.filter { it.control.isTrackpad && isStock(it) }
if (!docked && kit.steam) {
if (rearButtons) REAR.forEach { addOptional(presented, it) } else presented.removeAll(rear)
if (trackpads) {
if (!rearButtons) presented.removeAll(rear) else if (rear.isEmpty()) REAR.forEach { addOptional(presented, it) }
if (!trackpads) presented.removeAll(pads) else if (pads.isEmpty()) {
addOptional(presented, InputControl.LEFT_PAD)
addOptional(presented, InputControl.RIGHT_PAD)
} else presented.removeAll(pads)
}
}
fun put(control: InputControl, box: Box) { buttons["legacy:${control.id}"] = box }
val reserve = if (docked) 0f else min(60f * density, h * .15f)
val panel = if (docked) h else min(min(h * .60f, w * 1.15f) * scale, h - reserve)
val panel = if (docked) h else min(minOf(h * .60f, w * 1.15f, PANEL_DP * density) * scale, h - reserve)
val top = height - safe.bottom - reserve - panel
val unit = min(density, min(w / 275f, panel / 300f))
val pad = 8f * unit
@@ -121,6 +121,7 @@ internal class ControllerPortraitGeometry(
private companion object {
const val KEYBOARD = "builtin:keyboard"
const val PANEL_DP = 504f
val REAR = listOf(InputControl.L4, InputControl.L5, InputControl.R5, InputControl.R4)
}
}
@@ -27,8 +27,9 @@ internal class FloatingSteamOverlay(width: Int, height: Int, safe: Rect, density
val lowered = if (lowerShortcuts) lower(visible) else visible
if (rearButtons != true && trackpads != true) return lowered
val placed = lowered.toMutableList()
val chosen = lowered.filter(::isStock).map { it.control }
fun add(control: InputControl, x: Float, y: List<Float>, widthDp: Int, heightDp: Int, shape: InputButtonShape) {
if (placed.any { it.id == "legacy:${control.id}" }) return
if (chosen.any { if (control in rear) it in rear else it.isTrackpad }) return
val element = InputSurfaceElement(control, 0f, 0f, (widthDp * dp / w).coerceAtLeast(.03f),
(heightDp * dp / h).coerceAtLeast(.03f), floating = false, buttonShape = shape, showLabel = !control.isTrackpad)
findSpace(element, x, y, placed)?.let(placed::add)
@@ -324,15 +324,27 @@ object InputLibraries {
layout.copy(screen = screen)
})
private fun encodeElements(list: List<InputSurfaceElement>) = JSONArray().also { elements ->
for (e in list) elements.put(JSONObject().put("id", e.id).put("kind", e.kind.name)
.put("control", e.control.id).put("name", e.name).put("x", e.x.toDouble()).put("y", e.y.toDouble())
.put("width", e.width.toDouble()).put("height", e.height.toDouble()).put("floating", e.floating).put("hideWhenIdle", e.hideWhenIdle).put("mouseGestures", e.mouseGestures).put("toggle", e.toggle).put("icon", e.icon).put("image", e.image)
.put("elementOpacity", e.opacity.toDouble()).put("buttonShape", e.buttonShape.name).put("showLabel", e.showLabel).put("alwaysShown", e.alwaysShown))
}
private fun decodeElements(array: JSONArray) = array.objects(64).map { e ->
InputSurfaceElement(requireNotNull(InputControl.fromId(e.getString("control"))), e.getDouble("x").toFloat(),
e.getDouble("y").toFloat(), e.getDouble("width").toFloat(), e.getDouble("height").toFloat(),
e.getString("id"), InputElementKind.valueOf(e.getString("kind")), e.getString("name"),
e.optBoolean("floating", true), e.optBoolean("hideWhenIdle", false), e.optBoolean("mouseGestures", false), e.optBoolean("toggle", false), e.optInt("icon", 0), e.optString("image", ""),
e.optDouble("elementOpacity", 1.0).toFloat(), InputButtonShape.valueOf(e.optString("buttonShape", InputButtonShape.ROUNDED.name)), e.optBoolean("showLabel", true), e.optBoolean("alwaysShown", false))
}
internal fun encode(library: InputLibrary): String {
val layouts = JSONArray()
for (layout in library.layouts) {
val elements = JSONArray()
for (e in layout.elements) elements.put(JSONObject().put("id", e.id).put("kind", e.kind.name)
.put("control", e.control.id).put("name", e.name).put("x", e.x.toDouble()).put("y", e.y.toDouble())
.put("width", e.width.toDouble()).put("height", e.height.toDouble()).put("floating", e.floating).put("hideWhenIdle", e.hideWhenIdle).put("mouseGestures", e.mouseGestures).put("toggle", e.toggle).put("icon", e.icon).put("image", e.image)
.put("elementOpacity", e.opacity.toDouble()).put("buttonShape", e.buttonShape.name).put("showLabel", e.showLabel).put("alwaysShown", e.alwaysShown))
layouts.put(JSONObject().put("id", layout.id).put("name", layout.name).put("template", layout.template.name).put("elements", elements)
val encoded = JSONObject().put("id", layout.id).put("name", layout.name).put("template", layout.template.name).put("elements", encodeElements(layout.elements))
if (layout.rotated.isNotEmpty()) encoded.put("rotated", encodeElements(layout.rotated)).put("rotatedAspect", layout.rotatedAspect.toDouble()).put("rotatedScale", layout.rotatedScale.toDouble())
layouts.put(encoded
.put("tint", layout.style.tint ?: JSONObject.NULL).put("opacity", layout.style.opacity).put("screen", layout.screen.name).put("aspect", layout.aspect.toDouble()).put("scale", layout.scale.toDouble())
.put("hidden", JSONArray(layout.style.hidden.map { it.name }.sorted())).put("origin", layout.origin ?: JSONObject.NULL))
}
@@ -371,13 +383,7 @@ object InputLibraries {
require(version in 2..VERSION || restore)
val generated = mutableSetOf<String>()
val layouts = doc.getJSONArray("layouts").objects(256).map { layout ->
val stored = layout.getJSONArray("elements").objects(64).map { e ->
InputSurfaceElement(requireNotNull(InputControl.fromId(e.getString("control"))), e.getDouble("x").toFloat(),
e.getDouble("y").toFloat(), e.getDouble("width").toFloat(), e.getDouble("height").toFloat(),
e.getString("id"), InputElementKind.valueOf(e.getString("kind")), e.getString("name"),
e.optBoolean("floating", true), e.optBoolean("hideWhenIdle", false), e.optBoolean("mouseGestures", false), e.optBoolean("toggle", false), e.optInt("icon", 0), e.optString("image", ""),
e.optDouble("elementOpacity", 1.0).toFloat(), InputButtonShape.valueOf(e.optString("buttonShape", InputButtonShape.ROUNDED.name)), e.optBoolean("showLabel", true), e.optBoolean("alwaysShown", false))
}
val stored = decodeElements(layout.getJSONArray("elements"))
val id = layout.getString("id")
val origin = layout.optionalString("origin")
val followsGamepad = restore && !layout.optBoolean("kitless") &&
@@ -388,7 +394,8 @@ object InputLibraries {
InputSurfaceStyle(if (!layout.has("tint")) ControllerPrefs.STEAM_BLUE else if (layout.isNull("tint")) null else layout.getInt("tint"), layout.optInt("opacity", 100),
layout.optJSONArray("hidden")?.let { hidden -> (0 until hidden.length()).map { InputCommand.valueOf(hidden.getString(it)) }.toSet() }.orEmpty()),
InputLayoutScreen.valueOf(layout.optString("screen", InputLayoutScreen.BOTH.name)), layout.optDouble("aspect", 0.0).toFloat(), origin,
layout.optDouble("scale", 1.0).toFloat())
layout.optDouble("scale", 1.0).toFloat(), layout.optJSONArray("rotated")?.let(::decodeElements).orEmpty(),
layout.optDouble("rotatedAspect", 0.0).toFloat(), layout.optDouble("rotatedScale", layout.optDouble("scale", 1.0)).toFloat())
}
val bindings = doc.getJSONArray("bindings").objects(512).map { b ->
val controls = b.getJSONObject("controls").actions(28).mapKeys { requireNotNull(InputControl.fromId(it.key)) }
@@ -22,6 +22,9 @@ data class SavedInputLayout(
val aspect: Float = 0f,
val origin: String? = null,
val scale: Float = 1f,
val rotated: List<InputSurfaceElement> = emptyList(),
val rotatedAspect: Float = 0f,
val rotatedScale: Float = 1f,
) {
val editable get() = template == InputLayoutTemplate.CUSTOM
val quickButtons get() = QUICK_BUTTONS.filter { button -> elements.any { it.quickButton == button } }
@@ -249,6 +252,8 @@ data class InputLibrary(
for (layout in layouts) {
require(layout.style.opacity in 1..100 && layout.style.hidden.all { it in QUICK_BUTTONS })
require(layout.aspect == 0f || layout.aspect.isFinite() && layout.aspect in .05f..20f)
require(layout.rotated.isEmpty() || layout.rotatedAspect.isFinite() && layout.rotatedAspect in .05f..20f && layout.rotatedScale.isFinite() && layout.rotatedScale in .5f..2f)
require(layout.rotated.size <= 64 && layout.rotated.all { r -> listOf(r.x, r.y, r.width, r.height).all { it.isFinite() } })
require(layout.scale.isFinite() && layout.scale in .5f..2f)
inputName(layout.name); require(layout.elements.size <= 64); unique(layout.elements.map { it.id })
for (e in layout.elements) {
@@ -197,19 +197,8 @@ internal class LegacyGamepadLayout(private val context: Context, private val wid
fun regenerate(stored: List<InputSurfaceElement>): List<InputSurfaceElement> = withGeometry(stored, elements())
fun rescale(stored: List<InputSurfaceElement>, from: LegacyGamepadLayout): List<InputSurfaceElement> {
val before = from.elements().associateBy { it.id }
val after = elements().associateBy { it.id }
return stored.map { e ->
val b = before[e.id] ?: return@map e
val a = after[e.id] ?: return@map e
val w = (a.width * e.width / b.width).coerceIn(.03f, 1f)
val h = (a.height * e.height / b.height).coerceIn(.03f, 1f)
val cx = a.x + a.width / 2 + (e.x + e.width / 2 - b.x - b.width / 2)
val cy = a.y + a.height / 2 + (e.y + e.height / 2 - b.y - b.height / 2)
e.copy(x = (cx - w / 2).coerceIn(0f, 1f - w), y = (cy - h / 2).coerceIn(0f, 1f - h), width = w, height = h).bounded()
}
}
fun rescale(stored: List<InputSurfaceElement>, from: LegacyGamepadLayout): List<InputSurfaceElement> =
rescaleBetween(stored, from.elements(), elements())
fun buttonsOnly(stored: List<InputSurfaceElement>): List<InputSurfaceElement> {
val inset = dp(BUTTONS_ONLY_INSET_DP)
@@ -360,3 +349,22 @@ internal class LegacyGamepadLayout(private val context: Context, private val wid
InputControl.R5 to GamepadGeometry.Slot.R5, InputControl.R4 to GamepadGeometry.Slot.R4)
}
}
internal fun rescaleBetween(stored: List<InputSurfaceElement>, from: List<InputSurfaceElement>, to: List<InputSurfaceElement>,
sizeFrom: List<InputSurfaceElement> = from, sizeTo: List<InputSurfaceElement> = to): List<InputSurfaceElement> {
val before = from.associateBy { it.id }
val after = to.associateBy { it.id }
val smaller = sizeFrom.associateBy { it.id }
val larger = sizeTo.associateBy { it.id }
return stored.map { e ->
val b = before[e.id] ?: return@map e
val a = after[e.id] ?: return@map e
val sb = smaller[e.id] ?: b
val sa = larger[e.id] ?: a
val w = (sa.width * e.width / sb.width).coerceIn(.03f, 1f)
val h = (sa.height * e.height / sb.height).coerceIn(.03f, 1f)
val cx = a.x + a.width / 2 + (e.x + e.width / 2 - b.x - b.width / 2)
val cy = a.y + a.height / 2 + (e.y + e.height / 2 - b.y - b.height / 2)
e.copy(x = (cx - w / 2).coerceIn(0f, 1f - w), y = (cy - h / 2).coerceIn(0f, 1f - h), width = w, height = h).bounded()
}
}
@@ -14,9 +14,6 @@ import android.view.View
import android.view.WindowInsets
import android.widget.FrameLayout
import com.droiddeck.launcher.ui.InputSurfaceView
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayout.Dock? = null) : FrameLayout(context) {
private val surface = InputSurfaceView(context, pad, inputRole = InputRole.PRIMARY, haptics = dock != null)
@@ -75,15 +72,15 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo
render()
}
private data class Placement(val layout: SavedInputLayout?, val width: Int, val height: Int, val safe: Rect, val buttonsOnly: Boolean)
private data class Placement(val layout: SavedInputLayout?, val width: Int, val height: Int, val safe: Rect, val buttonsOnly: Boolean,
val kit: PadKit?, val optional: Pair<Boolean?, Boolean?>)
private fun placed(): List<InputSurfaceElement> {
val key = Placement(layout, viewWidth, viewHeight, Rect(safe), isButtonsOnly)
val optional = OnScreenLayout.optionalControls(context)
val key = Placement(layout, viewWidth, viewHeight, Rect(safe), isButtonsOnly, PadKit.forOverlay(context, layout), optional)
return placements.getOrPut(key) {
val steam = SessionState.mode == SessionService.MODE_STEAM && SessionState.deckPad
OnScreenLayout.elements(context, layout, viewWidth, viewHeight, safe, isButtonsOnly, dock,
rearButtons = SessionPrefs.oscRearButtons(context).takeIf { steam },
trackpads = SessionPrefs.oscTrackpads(context).takeIf { steam })
rearButtons = optional.first, trackpads = optional.second)
}
}
@@ -136,7 +133,7 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo
params.bottomMargin = bottom
quickToggle.layoutParams = params
}
val fresh = Rect(cutout?.safeInsetLeft ?: 0, if (dock == null) cutout?.safeInsetTop ?: 0 else 0, cutout?.safeInsetRight ?: 0, cutout?.safeInsetBottom ?: 0)
val fresh = OnScreenLayout.safeInsets(insets, dock != null)
if (fresh != safe) {
safe.set(fresh)
render()
@@ -3,6 +3,8 @@ package com.droiddeck.launcher.input
import android.content.Context
import android.graphics.Rect
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
@@ -28,22 +30,28 @@ object OnScreenLayout {
private const val TOLERANCE = .01f
private const val KEYBOARD_ID = "builtin:keyboard"
private val REAR = setOf(InputControl.L4, InputControl.L5, InputControl.R4, InputControl.R5)
fun elements(context: Context, layout: SavedInputLayout?, width: Int, height: Int, safe: Rect,
fun elements(context: Context, saved: SavedInputLayout?, width: Int, height: Int, safe: Rect,
buttonsOnly: Boolean = false, dock: Dock? = null, rearButtons: Boolean? = null,
trackpads: Boolean? = null): List<InputSurfaceElement> {
val stored = layout?.elements ?: return emptyList()
if (width <= 0 || height <= 0) return stored
if (saved == null) return emptyList()
if (width <= 0 || height <= 0) return saved.elements
val layout = oriented(saved, width, height)
val stored = layout.elements
val generator = LegacyGamepadLayout(context, width, height, safe, layout.scale)
val (reference, generated) = reference(context, layout, width, height)
val (reference, matched) = reference(context, layout, width, height)
if (buttonsOnly && dock == null) return generator.buttonsOnly(stored) + fit(stored.filter { it.alwaysShown }, reference.first, reference.second, width, height, safe)
val generated = matched || PadKit.forOverlay(context, layout) != null && stored.any(::isGamepad) &&
(dock != null || height > width && layout.aspect >= 1f || height <= width && layout.aspect > 0f && layout.aspect < 1f)
val gamepad = if (generated) stored.filter(::isGamepad) else emptyList()
val others = fit(stored.filterNot { generated && isGamepad(it) || dock != null && it.alwaysShown }, reference.first, reference.second, width, height, safe)
val placed = when {
val regenerated = when {
gamepad.isEmpty() -> emptyList()
dock != null -> generator.dock(gamepad, dock.portrait, dock.grips, dock.left, dock.right)
else -> generator.regenerate(gamepad)
}
val placed = regenerated + gamepad.filter { g -> dock == null && optional(g) && regenerated.none { it.id == g.id } }
val byId = (placed + others).associateBy { it.id }
val ordered = stored.mapNotNull { byId[it.id] } + placed.filter { p -> stored.none { it.id == p.id } }
val kit = PadKit.forOverlay(context, layout) ?: return ordered
@@ -62,12 +70,52 @@ object OnScreenLayout {
.place(ordered, lowerShortcuts = generated, rearButtons = rearButtons, trackpads = trackpads)
}
fun editorElements(context: Context, layout: SavedInputLayout, width: Int, height: Int, edited: Boolean = false): List<InputSurfaceElement> =
elements(context, if (edited && width > 0 && height > 0) layout.copy(aspect = width.toFloat() / height) else layout, width, height, Rect())
fun oriented(layout: SavedInputLayout, width: Int, height: Int): SavedInputLayout {
val portrait = height > width
if (layout.rotated.isEmpty() || layout.aspect <= 0f || (layout.aspect < 1f) == portrait || (layout.rotatedAspect < 1f) != portrait) return layout
val rotated = layout.rotated.associateBy { it.id }
return layout.copy(elements = layout.elements.map { e -> rotated[e.id]?.let { e.copy(x = it.x, y = it.y, width = it.width, height = it.height) } ?: e } +
layout.rotated.filter { r -> optional(r) && layout.elements.none { it.id == r.id } },
aspect = layout.rotatedAspect, scale = layout.rotatedScale, rotated = emptyList(), rotatedAspect = 0f, rotatedScale = 1f)
}
fun withFrame(context: Context, saved: SavedInputLayout, elements: List<InputSurfaceElement>, aspect: Float, scale: Float = saved.scale): SavedInputLayout {
val (_, metrics) = InputLibraries.primaryDisplay(context)
val generated = generatedSize(context, saved, metrics.widthPixels, metrics.heightPixels) != null
val portraitMain = saved.aspect > 0f && saved.aspect < 1f
if (aspect <= 0f || aspect >= 1f || portraitMain && !generated) {
val rotated = if (aspect >= 1f && portraitMain && !generated) Triple(saved.elements, saved.aspect, saved.scale) else Triple(saved.rotated, saved.rotatedAspect, saved.rotatedScale)
return saved.copy(elements = elements, aspect = aspect, scale = scale, rotated = rotated.first,
rotatedAspect = if (rotated.first.isEmpty()) 0f else rotated.second, rotatedScale = if (rotated.first.isEmpty()) 1f else rotated.third)
}
val main = if (portraitMain) 1f / saved.aspect else saved.aspect.takeIf { it > 0f } ?: (1f / aspect)
val ids = elements.associateBy { it.id }
val kept = saved.elements.mapNotNull { e -> ids[e.id]?.copy(x = e.x, y = e.y, width = e.width, height = e.height) }
val added = fit(elements.filter { d -> !optional(d) && saved.elements.none { it.id == d.id } }, aspect, 1f, (main * 1000).roundToInt().coerceAtLeast(1), 1000, Rect())
return saved.copy(elements = kept + added, aspect = main, rotated = elements, rotatedAspect = aspect, rotatedScale = scale)
}
fun optionalControls(context: Context): Pair<Boolean?, Boolean?> {
val steam = SessionState.mode == SessionService.MODE_STEAM && SessionState.deckPad
return SessionPrefs.oscRearButtons(context).takeIf { steam } to SessionPrefs.oscTrackpads(context).takeIf { steam }
}
fun editorElements(context: Context, layout: SavedInputLayout, width: Int, height: Int, edited: Boolean = false, safe: Rect = Rect()): List<InputSurfaceElement> {
val (rear, pads) = optionalControls(context)
return elements(context, if (edited && width > 0 && height > 0) layout.copy(aspect = width.toFloat() / height) else layout, width, height, safe,
rearButtons = rear, trackpads = pads)
}
fun editorFrame(layout: SavedInputLayout, displayed: List<InputSurfaceElement>): List<InputSurfaceElement> {
val byId = displayed.associateBy { it.id }
return layout.elements.map { byId[it.id] ?: it }
return layout.elements.map { byId[it.id] ?: it } + displayed.filter { d ->
optional(d) && layout.elements.none { it.id == d.id }
}
}
fun safeInsets(insets: android.view.WindowInsets?, docked: Boolean): Rect {
val cutout = if (android.os.Build.VERSION.SDK_INT >= 28) insets?.displayCutout else null
return Rect(cutout?.safeInsetLeft ?: 0, if (docked) 0 else cutout?.safeInsetTop ?: 0, cutout?.safeInsetRight ?: 0, cutout?.safeInsetBottom ?: 0)
}
fun fit(elements: List<InputSurfaceElement>, referenceWidth: Float, referenceHeight: Float, width: Int, height: Int, safe: Rect): List<InputSurfaceElement> {
@@ -93,6 +141,8 @@ object OnScreenLayout {
}
}
private fun optional(e: InputSurfaceElement) = e.id == "legacy:${e.control.id}" && (e.control.isTrackpad || e.control in REAR)
private fun isGamepad(e: InputSurfaceElement) = e.id.startsWith("legacy:") || e.id == KEYBOARD_ID
fun generatedSize(context: Context, layout: SavedInputLayout, width: Int, height: Int): Pair<Int, Int>? =
@@ -34,6 +34,12 @@ internal enum class PadKit(val face: FaceGlyphs, val dpad: DpadStyle, val stick:
else -> label(control)
}
fun native(element: InputSurfaceElement) = element.id == "legacy:${element.control.id}" && element.icon == 0 &&
(element.name == element.control.label || element.name == name(element.control))
fun artwork(element: InputSurfaceElement) = element.image.isEmpty() && element.showLabel &&
(native(element) || element.id == "builtin:keyboard" && element.icon == InputButtonIcons.KEYBOARD)
companion object {
fun forOverlay(context: Context, layout: SavedInputLayout?): PadKit? =
if (layout?.id != InputLibraries.OVERLAY) null else when (SessionPrefs.steamController(context)) {
@@ -12,9 +12,6 @@ object BattleNet {
const val APP_ID = 2596113170L
const val FEX_REQUEST = "battlenet-fex.request"
const val FEX_RESULT = "battlenet-fex.result"
const val PROGRAM = "/usr/local/bin/droiddeck-battlenet"
class Title(val uid: String, val name: String, val code: String, val steam: Int? = null, val shop: String? = null, val product: String? = null, val flavor: String? = null)
@@ -162,8 +159,6 @@ object BattleNet {
source = com.droiddeck.launcher.stores.Store.BATTLENET.id,
)
fun fexInUse(context: Context): String? = ComponentsManager.gameComponents(context, APP_ID.toString())["fex"]
internal fun title(uid: String): Title? {
val id = uid.lowercase()
TITLES.firstOrNull { it.uid == id }?.let { return it }
@@ -391,54 +386,6 @@ object BattleNet {
Log.i(TAG, "removed")
}
private val D2RFIX = Regex("""(?i)FEXCore-(\d+(?:\.\d+)*)-d2rfix(\d+)-linux\.wcp""")
private const val LISTING_MAX_AGE = 6 * 3600L
private val NEWEST = Comparator<Pair<List<Long>, Long>> { a, b ->
for (i in 0 until minOf(a.first.size, b.first.size)) if (a.first[i] != b.first[i]) return@Comparator a.first[i].compareTo(b.first[i])
if (a.first.size != b.first.size) a.first.size.compareTo(b.first.size) else a.second.compareTo(b.second)
}
internal fun d2rfix(file: String): Pair<List<Long>, Long>? {
val m = D2RFIX.matchEntire(file) ?: return null
val version = m.groupValues[1].split('.').map { it.toLongOrNull() ?: return null }
return version to (m.groupValues[2].toLongOrNull() ?: return null)
}
internal fun newestD2rFix(items: List<ComponentsManager.CatalogItem>): ComponentsManager.CatalogItem? =
items.filter { it.comp == "fex" }.mapNotNull { item -> d2rfix(item.file)?.let { item to it } }
.maxWithOrNull { a, b -> NEWEST.compare(a.second, b.second) }?.first
fun ensureFex(context: Context): String = ensureFex(context) { ComponentsManager.catalog(it, true).items }
@Synchronized
internal fun ensureFex(context: Context, refresh: (Context) -> List<ComponentsManager.CatalogItem>): String {
val item = newestD2rFix(listing(context, refresh)) ?: error("no d2rfix FEXCore build in the Nightlies listing")
val file = ComponentsManager.safeName(item.file)
if (ComponentsManager.packages(context).none { it.file == file }) {
Log.i(TAG, "downloading ${item.file}")
ComponentsManager.download(context, item) {}
}
val scope = APP_ID.toString()
if (ComponentsManager.gameComponents(context, scope)["fex"] != file) {
ComponentsManager.setGameComponent(context, scope, "fex", file)
Log.i(TAG, "FEX for the Battle.net prefix: $file")
} else if (ComponentsManager.republish(context)) {
Log.i(TAG, "FEX for the Battle.net prefix: $file, now in every installed Proton")
}
return file
}
private fun listing(context: Context, refresh: (Context) -> List<ComponentsManager.CatalogItem>): List<ComponentsManager.CatalogItem> {
val cached = ComponentsManager.catalog(context, false)
val age = System.currentTimeMillis() / 1000 - cached.fetchedAt
if (age in 0 until LISTING_MAX_AGE && newestD2rFix(cached.items) != null) return cached.items
val fetched = runCatching { refresh(context) }
.onFailure { Log.w(TAG, "Nightlies listing: ${it.message}") }.getOrNull().orEmpty()
return if (newestD2rFix(fetched) != null) fetched else cached.items
}
internal fun videoMemory(totalMb: Long): Int = (totalMb / 5 / 512 * 512).coerceIn(1536, 3584).toInt()
internal fun videoMemoryOptions(megabytes: Int): String =
@@ -464,21 +411,9 @@ object BattleNet {
return true
}
fun answerFexRequest(context: Context, dir: File) {
val app = context.applicationContext
Thread({
runCatching { ensureVideoMemory(app) }.onFailure { Log.w(TAG, "video memory cap for the Battle.net profile", it) }
runCatching { ensureNoSteam(app) }.onFailure { Log.w(TAG, "Start without Steam for the Battle.net profile", it) }
val answer = try {
"ok " + ensureFex(app)
} catch (e: Exception) {
Log.w(TAG, "FEX for the Battle.net prefix", e)
"error " + (e.message ?: e.javaClass.simpleName)
}
Log.i(TAG, "FEX request: $answer")
val result = File(dir, FEX_RESULT)
val partial = File(dir, "$FEX_RESULT.tmp")
runCatching { partial.writeText(answer.replace('\n', ' ') + "\n"); partial.renameTo(result) }
}, "battlenet-fex").start()
fun ensureDefaults(context: Context, program: String?) {
if (program != PROGRAM && !installed(context)) return
runCatching { ensureVideoMemory(context) }.onFailure { Log.w(TAG, "video memory cap for the Battle.net profile", it) }
runCatching { ensureNoSteam(context) }.onFailure { Log.w(TAG, "Start without Steam for the Battle.net profile", it) }
}
}
@@ -238,6 +238,20 @@ object ComponentsManager {
saveState(context, state)
}
private val UNPINNED_FEX = Regex("""(?i)FEXCore-\d+(?:\.\d+)*-d2rfix\d+-linux\.wcp""")
fun migrateBattleNetFex(context: Context) = synchronized(lock) {
val marker = File(dataDir(context), ".battlenet-fex-unpinned")
if (marker.isFile) return@synchronized
migratePlugin(context)
val scope = com.droiddeck.launcher.runtime.BattleNet.APP_ID.toString()
if (gameComponents(context, scope)["fex"]?.let(UNPINNED_FEX::matches) == true) {
setGameComponent(context, scope, "fex", null)
Log.i(TAG, "Battle.net follows the selected FEX again")
}
marker.writeText("1\n")
}
private fun migratePlugin(context: Context) {
val marker = File(dataDir(context), ".plugin-imported")
if (marker.isFile) return
@@ -487,6 +501,7 @@ object ComponentsManager {
fun snapshotAll(context: Context) = synchronized(lock) {
migratePlugin(context)
runCatching { migrateBattleNetFex(context) }.onFailure { Log.w(TAG, "Battle.net FEX selection", it) }
val state = loadState(context)
for (p in protons(context)) for (comp in COMPONENTS) {
runCatching { ensureOriginal(context, p, comp, state) }.onFailure { Log.w(TAG, "original $comp of ${p.name}", it) }
@@ -497,6 +512,7 @@ object ComponentsManager {
fun snapshot(context: Context): Snapshot = synchronized(lock) {
migratePlugin(context)
runCatching { migrateBattleNetFex(context) }.onFailure { Log.w(TAG, "Battle.net FEX selection", it) }
val state = loadState(context)
val reapplied = HashMap<String, Long>()
runCatching {
@@ -287,6 +287,7 @@ object SessionFiles {
File(root, "usr/share/vulkan/implicit_layer.d/droiddeck_vram_cap.json").delete()
LegacyNames.migrateRootfs(root)
ComponentsManager.migrateLaunchDir(context)
runCatching { ComponentsManager.migrateBattleNetFex(context) }.onFailure { Log.w(TAG, "Battle.net FEX selection", it) }
EsyncPacks.stageBundled(context, root)
val directAudio = arrayOf(
"aarch64-unix/winedirectaudio.so",
@@ -85,6 +85,12 @@ object SessionPrefs {
prefs(context).edit().putBoolean("launcherFullscreen", on).apply()
}
fun controllerHaptics(context: Context): Boolean = prefs(context).getBoolean("controllerHaptics", true)
fun setControllerHaptics(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("controllerHaptics", on).apply()
}
fun blackFrameInsertion(context: Context): Boolean = prefs(context).getBoolean("blackFrameInsertion", false)
fun setBlackFrameInsertion(context: Context, on: Boolean) {
@@ -419,6 +425,18 @@ object SessionPrefs {
e.remove("gameStoresEnabled").remove("soundtracksEnabled").remove("agentTab").putInt("navTabLayout", version).apply()
}
fun drawerPageOrder(context: Context): List<String> = idList(prefs(context).getString("drawerPageOrder", null))
fun setDrawerPageOrder(context: Context, order: List<String>) {
prefs(context).edit().putString("drawerPageOrder", order.joinToString(",")).apply()
}
fun drawerPageHidden(context: Context): Set<String> = idList(prefs(context).getString("drawerPageHidden", null)).toSet()
fun setDrawerPageHidden(context: Context, keys: Set<String>) {
prefs(context).edit().putString("drawerPageHidden", keys.joinToString(",")).apply()
}
fun setNavTabHidden(context: Context, keys: Set<String>) {
prefs(context).edit().putString("navTabHidden", keys.joinToString(",")).apply()
}
@@ -589,7 +589,10 @@ class SessionService : Service() {
val sessionDir = openSessionFolder()
try {
SessionEvents.step("game-environment") { GameEnvironmentStore.publish(this) }
SessionEvents.step("game-environment") {
com.droiddeck.launcher.runtime.BattleNet.ensureDefaults(this, SessionState.program)
GameEnvironmentStore.publish(this)
}
} catch (e: Exception) {
Log.e(TAG, "could not publish the game environment", e)
failSession(gen, "GAME_ENVIRONMENT_FAILED", getString(R.string.session_game_environment_failed), -1)
@@ -926,6 +929,7 @@ class SessionService : Service() {
))
}
},
schedule = { delay, task -> mainHandler.postDelayed({ task() }, delay) },
)
updateDownloadMonitoring()
mainHandler.post { updateSuspendPolicy() }
@@ -1951,11 +1955,6 @@ class SessionService : Service() {
}
return
}
if (path == com.droiddeck.launcher.runtime.BattleNet.FEX_REQUEST) {
File(dir, path).delete()
com.droiddeck.launcher.runtime.BattleNet.answerFexRequest(this@SessionService, dir)
return
}
if (path != null && path.startsWith("desktop-import-") && path.endsWith(".request")) {
val request = File(dir, path)
val text = runCatching { request.readText() }.getOrNull() ?: return
@@ -29,6 +29,7 @@ internal class SessionSuspendController(
{ _, _, _, _, _, _ -> },
private val pagedIn: (processes: Int, swapKb: Long, swapBeforeKb: Long, availableKb: Long, millis: Long) -> Unit =
{ _, _, _, _, _ -> },
private val schedule: (Long, () -> Unit) -> Unit = { _, _ -> },
) {
private enum class Role { SESSION_ROOT, SESSION_CHILD, HELPER_ROOT, HELPER_CHILD }
@@ -53,6 +54,7 @@ internal class SessionSuspendController(
private var frozen = emptyList<ProcessRecord>()
private var frozenSince: Long? = null
private var pagedOutTargets = emptyList<ProcessRecord>()
private var pageOutChecks = 0
fun freeze(pageOut: Boolean = false, completion: (Boolean) -> Unit) {
cancelled = false
@@ -60,6 +62,7 @@ internal class SessionSuspendController(
val records = frozen.associateByTo(LinkedHashMap()) { it.pid to it.started }
var complete = false
var interrupted = false
var deferred = false
try {
val root = records.values.firstOrNull { it.role == Role.SESSION_ROOT }
?: readProcess(sessionRoot())?.takeIf { it.pid > 1 }?.let {
@@ -74,29 +77,10 @@ internal class SessionSuspendController(
records[it.pid to it.started] = ProcessRecord(it.pid, it.started, Role.HELPER_ROOT)
}
}
if (pageOut) pageOut(records, root.pid, helpers)
val deadline = nowMillis() + FREEZE_TIMEOUT_MS
var previous: Map<TaskIdentity, Long>? = null
for (pass in 0 until FREEZE_MAX_PASSES) {
if (closing || cancelled || nowMillis() >= deadline) break
try {
if (readProcess(root.pid)?.started != root.started) break
addSnapshot(records, root.pid, helpers)
if (readProcess(root.pid)?.started != root.started) break
stop(records.values.toList())
sleep(if (pass == 0) 70L else 35L)
if (closing || cancelled || nowMillis() >= deadline) break
val current = stoppedSnapshot(records.values.toList(), root)
if (current != null && current == previous) {
complete = true
break
}
previous = current
} catch (_: IOException) {
previous = null
sleep(35L)
}
}
val pageOutNow = pageOut && memoryShort()
if (pageOutNow) pageOut(records, root.pid, helpers)
deferred = pageOut && !pageOutNow && zramControl?.isFile == true
complete = stopUntilStable(records, root, helpers)
} catch (_: InterruptedException) {
interrupted = true
Thread.interrupted()
@@ -111,16 +95,89 @@ internal class SessionSuspendController(
if (interrupted) Thread.currentThread().interrupt()
}
completion(complete)
if (complete && deferred) checkPageOut(++pageOutChecks)
if (!complete && frozen.isEmpty() && !interrupted) readBack()
}, { completion(false) })
}
private fun stopUntilStable(
records: MutableMap<Pair<Int, Long>, ProcessRecord>,
root: ProcessRecord,
helpers: List<Int>,
): Boolean {
val deadline = nowMillis() + FREEZE_TIMEOUT_MS
var previous: Map<TaskIdentity, Long>? = null
for (pass in 0 until FREEZE_MAX_PASSES) {
if (closing || cancelled || nowMillis() >= deadline) return false
try {
if (readProcess(root.pid)?.started != root.started) return false
addSnapshot(records, root.pid, helpers)
if (readProcess(root.pid)?.started != root.started) return false
stop(records.values.toList())
sleep(if (pass == 0) 70L else 35L)
if (closing || cancelled || nowMillis() >= deadline) return false
val current = stoppedSnapshot(records.values.toList(), root)
if (current != null && current == previous) return true
previous = current
} catch (_: IOException) {
previous = null
sleep(35L)
}
}
return false
}
private fun checkPageOut(check: Int) = later(check, ::pageOutIfShort)
private fun later(check: Int, task: (Int) -> Unit) {
schedule(PAGE_OUT_CHECK_MS) { submit({ task(check) }, {}) }
}
private fun pageOutIfShort(check: Int) {
if (check != pageOutChecks || closing || cancelled || frozen.isEmpty()) return
if (!memoryShort()) return checkPageOut(check)
restopUntilStable(++pageOutChecks, pageOut = true)
}
private fun restopUntilStable(check: Int, pageOut: Boolean = false) {
if (check != pageOutChecks || closing || cancelled || frozen.isEmpty()) return
val records = frozen.associateByTo(LinkedHashMap()) { it.pid to it.started }
val root = records.values.firstOrNull { it.role == Role.SESSION_ROOT }?.takeUnless { isGone(it) } ?: return
val helpers = records.values.filter { it.role == Role.HELPER_ROOT }.map { it.pid }
if (pageOut) advanceClock()
var stable = false
try {
if (pageOut) {
restore(records.values.toList())
pageOut(records, root.pid, helpers)
}
stable = stopUntilStable(records, root, helpers)
} catch (_: InterruptedException) {
Thread.currentThread().interrupt()
} catch (_: Exception) {
} finally {
stop(records.values.toList())
frozen = records.values.toList()
if (pageOut) frozenSince = nowNanos()
}
if (!stable) later(check, ::restopUntilStable)
}
private fun memoryShort(): Boolean {
val (total, available) = meminfoKb()
return available < reserveKb(total) * PAGE_OUT_RESERVES
}
private fun reserveKb(totalKb: Long) = maxOf(READ_BACK_HEADROOM_KB, totalKb / READ_BACK_TOTAL_SHARE)
fun cancelFreeze() {
cancelled = true
}
fun resume(completion: (Boolean) -> Unit) {
cancelled = true
submit({
pageOutChecks++
val records = frozen
advanceClock()
runAudio(resumeAudio)
@@ -330,27 +387,32 @@ internal class SessionSuspendController(
pagedOutTargets = emptyList()
val control = zramControl?.takeIf { it.isFile } ?: return
if (targets.isEmpty() || closing) return
val before = memoryKb(targets).second
val swapKb = targets.associateWith { memoryKb(listOf(it)).second }
val before = swapKb.values.sum()
val (total, available) = meminfoKb()
if (!canTake(before, total, available)) {
val chosen = readBackTargets(swapKb, total, available)
if (chosen.isEmpty()) {
pagedIn(0, before, before, available, 0)
return
}
val hold = holdFile(control)
val requests = chosen.map { File(control.parentFile, "${hold.name}.${it.pid}") }
try {
hold.writeText(READ_BACK_REQUEST)
hold.writeText(NO_REQUEST)
requests.forEach { it.writeText(READ_BACK_REQUEST) }
} catch (_: IOException) {
requests.forEach { it.delete() }
hold.delete()
return
}
val start = nowMillis()
for (record in targets) send(record, SIGURG)
var swap = before
for (record in chosen) send(record, SIGURG)
var swap = memoryKb(chosen).second
var unchanged = 0
try {
while (!closing && nowMillis() - start < READ_BACK_TIMEOUT_MS) {
sleep(READ_BACK_POLL_MS)
val current = memoryKb(targets).second
val current = memoryKb(chosen).second
unchanged = if (current == swap) unchanged + 1 else 0
swap = current
if (swap == 0L || unchanged >= READ_BACK_STABLE_POLLS) break
@@ -358,14 +420,25 @@ internal class SessionSuspendController(
} catch (_: InterruptedException) {
Thread.currentThread().interrupt()
} finally {
requests.forEach { it.delete() }
hold.delete()
}
pagedIn(targets.size, swap, before, available, nowMillis() - start)
pagedIn(chosen.size, memoryKb(targets).second, before, available, nowMillis() - start)
}
private fun canTake(swapKb: Long, totalKb: Long, availableKb: Long): Boolean =
availableKb >= swapKb * READ_BACK_AVAILABLE_FACTOR &&
availableKb - swapKb >= maxOf(READ_BACK_HEADROOM_KB, totalKb / READ_BACK_TOTAL_SHARE)
private fun readBackTargets(swapKb: Map<ProcessRecord, Long>, totalKb: Long, availableKb: Long): List<ProcessRecord> {
var budget = minOf(
availableKb / READ_BACK_AVAILABLE_FACTOR,
availableKb - reserveKb(totalKb),
)
val chosen = ArrayList<ProcessRecord>()
for ((record, swap) in swapKb.entries.sortedByDescending { it.value }) {
if (swap > budget) continue
chosen += record
budget -= swap
}
return chosen
}
private fun meminfoKb(): Pair<Long, Long> = try {
val values = HashMap<String, Long>()
@@ -477,9 +550,12 @@ internal class SessionSuspendController(
const val PAGE_OUT_ACK = "1"
const val PAGE_OUT_REQUEST = "1"
const val READ_BACK_REQUEST = "0"
const val NO_REQUEST = "2 0"
const val PAGE_OUT_POLL_MS = 100L
const val PAGE_OUT_START_MS = 2_000L
const val PAGE_OUT_TIMEOUT_MS = 12_000L
const val PAGE_OUT_CHECK_MS = 10_000L
const val PAGE_OUT_RESERVES = 2L
const val READ_BACK_POLL_MS = 100L
const val READ_BACK_STABLE_POLLS = 5
const val READ_BACK_TIMEOUT_MS = 5_000L
@@ -12,13 +12,13 @@ object SettingsReset {
private const val TAG = "SettingsReset"
internal val SESSION_KEYS = setOf(
"orientation", "launcherFullscreen", "animations", "lowStorageWarning", "theme", "runSteamAtStartup", "startupSession", "addedGamesArt",
"orientation", "launcherFullscreen", "controllerHaptics", "animations", "lowStorageWarning", "theme", "runSteamAtStartup", "startupSession", "addedGamesArt",
"dualScreenMode", "dualScreenSessionMode", "dualScreenLauncher", "dualScreenSessionControls", "androidTextFieldKeyboard",
"soundtracksIngame", "gameStoresSpeedTier", "gameStoresParallel", "storesOpenTab", "storesShowMature",
"storesInstallLanguage",
"hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "__KEEP_droidDeckHud__", "__KEEP_droidDeckHudPos__", "backHold", "backActionsInverted", "backDoubleTapMs", "touch", "pen", "penButton", "osc", "shape", "steamController",
"gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "unfoldedControlsWithController",
"stretch16x9", "avoidNotch", "picturePosition", "integerScaling", "railLabels", "developerTools", "navTabOrder", "navTabShelved", "navTabHidden", "pcKeyboardSize", "pcKeyboardOpacity", "pcKeyboardHiddenKeys",
"stretch16x9", "avoidNotch", "picturePosition", "integerScaling", "railLabels", "developerTools", "navTabOrder", "navTabShelved", "navTabHidden", "drawerPageOrder", "drawerPageHidden", "pcKeyboardSize", "pcKeyboardOpacity", "pcKeyboardHiddenKeys",
"gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop",
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "paceCores",
"directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus",
@@ -0,0 +1,41 @@
package com.droiddeck.launcher.ui
import android.content.Context
import android.os.Build
import android.os.VibrationEffect
import android.os.Vibrator
import android.os.VibratorManager
import android.view.InputDevice
import android.view.KeyEvent
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,
)
fun onKey(context: Context, event: KeyEvent) {
if (event.action != KeyEvent.ACTION_DOWN || event.keyCode !in navKeys) return
if (event.keyCode == KeyEvent.KEYCODE_BUTTON_A && event.repeatCount > 0) return
val fromController = event.isFromSource(InputDevice.SOURCE_GAMEPAD) ||
event.isFromSource(InputDevice.SOURCE_DPAD) || event.isFromSource(InputDevice.SOURCE_JOYSTICK)
if (!fromController) return
tick(context)
}
fun tick(context: Context) {
val vibrator = if (Build.VERSION.SDK_INT >= 31) {
context.getSystemService(VibratorManager::class.java)?.defaultVibrator
} else {
@Suppress("DEPRECATION") context.getSystemService(Context.VIBRATOR_SERVICE) as? Vibrator
} ?: return
if (!vibrator.hasVibrator()) return
if (Build.VERSION.SDK_INT >= 29) {
vibrator.vibrate(VibrationEffect.createPredefined(VibrationEffect.EFFECT_TICK))
} else if (Build.VERSION.SDK_INT >= 26) {
vibrator.vibrate(VibrationEffect.createOneShot(10, VibrationEffect.DEFAULT_AMPLITUDE))
} else {
@Suppress("DEPRECATION") vibrator.vibrate(10)
}
}
}
@@ -174,6 +174,7 @@ class FrontEndState(
val launcherOrientation: Int = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER,
val homePage: String = com.droiddeck.launcher.core.AppUiPrefs.HOME_PAGE_STEAM,
val launcherFullscreen: Boolean = true,
val controllerHaptics: Boolean = true,
val downloadSource: String = DownloadSource.MODE_AUTO,
val downloadMirror: String = "",
val downloadPrefix: String = "",
@@ -279,6 +280,7 @@ class FrontEndActions(
val onLauncherOrientation: (Int) -> Unit = {},
val onHomePage: (String) -> Unit = {},
val onLauncherFullscreen: (Boolean) -> Unit = {},
val onControllerHaptics: (Boolean) -> Unit = {},
val onAnimationsEnabled: (Boolean) -> Unit = {},
val onLowStorageWarning: (Boolean) -> Unit = {},
val onDualScreenMode: (String) -> Unit = {},
@@ -516,6 +516,11 @@ internal fun SetupPanel(
if (s.launcherFullscreen) stringResource(R.string.setup_fullscreen_on) else stringResource(R.string.setup_fullscreen_off),
s.launcherFullscreen,
) { a.onLauncherFullscreen(it) }
ToggleRow(
host, "controller-haptics", stringResource(R.string.setup_controller_haptics),
stringResource(R.string.setup_controller_haptics_hint),
s.controllerHaptics,
) { a.onControllerHaptics(it) }
if (s.dualScreenDevice) {
val dualModes = listOf(
com.droiddeck.launcher.input.DualScreen.MODE_AUTO to stringResource(R.string.setup_dual_screen_auto),
@@ -278,7 +278,7 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
else InputHint(layout.name)
InputNavigationRow(stringResource(R.string.input_saved_layouts), stringResource(R.string.input_saved_layouts_hint)) { go(InputPage.LAYOUTS) }
if (layout.editable) {
if (role != InputRole.PRIMARY || PadKit.forOverlay(context, layout) == null) {
if (PadKit.forOverlay(context, layout).let { kit -> role != InputRole.PRIMARY || kit == null || layout.elements.any { !kit.artwork(it) } }) {
InputColorRow(host, layout.style.tint) { color -> update { it.withLayout(layout.copy(style = layout.style.copy(tint = color))) } }
}
SliderRow(stringResource(R.string.ctrl_opacity), null, layout.style.opacity, 1..100, step = 1,
@@ -63,10 +63,17 @@ import com.droiddeck.launcher.session.SessionState
private data class SurfaceSnapshot(val elements: List<InputSurfaceElement>, val actions: Map<String, InputAction>,
val clicks: Map<String, InputAction>, val scale: Float, val aspect: Float)
private class GamepadScaler(private val context: android.content.Context, private val width: Int, private val height: Int) {
private class GamepadScaler(private val context: android.content.Context, private val width: Int, private val height: Int,
private val layout: SavedInputLayout) {
private fun generator(scale: Float) = LegacyGamepadLayout(context, width, height, scale = scale)
val ids = generator(1f).elements().map { it.id }.toSet()
fun rescale(stored: List<InputSurfaceElement>, from: Float, to: Float) = generator(to).rescale(stored, generator(from))
fun stock(scale: Float) = generator(scale).elements()
private fun placed(scale: Float) = OnScreenLayout.editorElements(context,
layout.copy(elements = stock(scale), aspect = 0f, rotated = emptyList(), scale = scale), width, height)
fun rescale(stored: List<InputSurfaceElement>, from: Float, to: Float) =
if (PadKit.forOverlay(context, layout) == null || OnScreenLayout.generatedSize(context, layout.copy(elements = stored, scale = from), width, height) != null)
generator(to).rescale(stored, generator(from))
else rescaleBetween(stored, placed(from), placed(to), stock(from), stock(to))
fun reset(stored: List<InputSurfaceElement>) = generator(1f).regenerate(stored).associateBy { it.id }.let { placed -> stored.map { placed[it.id] ?: it } }
}
@@ -78,13 +85,14 @@ private class SurfaceDraft(val layout: SavedInputLayout, val preset: SavedInputB
var clicks by mutableStateOf(preset.clicks)
var selected by mutableStateOf<String?>(null)
var toolsExpanded by mutableStateOf(false)
var toolsX by mutableFloatStateOf(.02f)
var toolsX by mutableFloatStateOf(-1f)
var toolsY by mutableFloatStateOf(.02f)
var snap by mutableStateOf(snap)
var adding by mutableStateOf(false)
var properties by mutableStateOf(false)
var clickProperties by mutableStateOf(false)
var history by mutableStateOf<List<SurfaceSnapshot>>(emptyList())
var canvas by mutableStateOf(IntSize.Zero)
var layoutScale by mutableFloatStateOf(layout.scale)
var aspect by mutableFloatStateOf(layout.aspect)
private var scaleBase by mutableStateOf<Triple<List<InputSurfaceElement>, List<InputSurfaceElement>, Float>?>(null)
@@ -92,7 +100,8 @@ private class SurfaceDraft(val layout: SavedInputLayout, val preset: SavedInputB
private val rescales get() = gamepad?.let { pad -> elements.any { it.id in pad.ids } } == true
val scale get() = when {
scaleBase?.second == elements -> scaleValue
rescales -> (layoutScale * 100).roundToInt()
rescales -> ((if (canvas.width > 0 && canvas.height > 0 && aspect > 0f && (aspect < 1f) != (canvasAspect < 1f))
OnScreenLayout.oriented(layout, canvas.width, canvas.height).scale else layoutScale) * 100).roundToInt()
else -> 100
}
val positioned get() = (if (rescales) gamepad!!.reset(elements) else defaults?.let { elements.withPositionsOf(refit(it, defaultsFrame)) })
@@ -102,18 +111,29 @@ private class SurfaceDraft(val layout: SavedInputLayout, val preset: SavedInputB
if (from <= 0f || aspect <= 0f || abs(from / aspect - 1f) < .01f) return placed
return OnScreenLayout.fit(placed, from, 1f, (aspect * 1000).roundToInt().coerceAtLeast(1), 1000, Rect())
}
val element get() = elements.firstOrNull { it.id == selected }
val element get() = elements.firstOrNull { it.id == selected } ?: shown.firstOrNull { it.id == selected }
val dirty get() = elements != layout.elements || actions != preset.elements || clicks != preset.clicks || layoutScale != layout.scale || aspect != layout.aspect
fun checkpoint() { history = (history + SurfaceSnapshot(elements, actions, clicks, layoutScale, aspect)).takeLast(40) }
fun undo() { history.lastOrNull()?.let { elements = it.elements; actions = it.actions; clicks = it.clicks; layoutScale = it.scale; aspect = it.aspect; history = history.dropLast(1) } }
private fun adoptDisplayedFrame(context: android.content.Context): Boolean {
if (canvas.width <= 0 || canvas.height <= 0 || shown.isEmpty() || aspect <= 0f || (aspect < 1f) == (canvasAspect < 1f)) return false
val open = toolsExpanded
beginEdit(shown, canvasAspect, gamepad?.let { GamepadScaler(context, canvas.width, canvas.height, layout) })
toolsExpanded = open
return true
}
fun beginEdit(displayed: List<InputSurfaceElement>, aspect: Float, scaler: GamepadScaler? = gamepad) {
checkpoint()
toolsExpanded = false
elements = OnScreenLayout.editorFrame(layout.copy(elements = elements), displayed)
if (this.aspect > 0f && aspect > 0f && (this.aspect < 1f) != (aspect < 1f)) layoutScale = OnScreenLayout.oriented(layout, (aspect * 1000).roundToInt(), 1000).scale
this.aspect = aspect
scaler?.let { gamepad = it }
}
fun scaleAll(percent: Int) {
val base = scaleBase?.takeIf { it.second == elements } ?: Triple(elements, elements, if (rescales) layoutScale else 0f).also { checkpoint() }
fun scaleAll(context: android.content.Context, percent: Int) {
val adopted = adoptDisplayedFrame(context)
val base = scaleBase?.takeIf { it.second == elements } ?: Triple(elements, elements, if (rescales) layoutScale else 0f).also { if (!adopted) checkpoint() }
val factor = percent / 100f
val pad = gamepad
elements = if (base.third > 0f && pad != null) {
@@ -123,7 +143,47 @@ private class SurfaceDraft(val layout: SavedInputLayout, val preset: SavedInputB
} else base.first.scaled(factor)
scaleValue = percent; scaleBase = Triple(base.first, elements, base.third)
}
fun resetPositions() { positioned?.let { checkpoint(); elements = it; if (rescales) layoutScale = 1f } }
var shown by mutableStateOf<List<InputSurfaceElement>>(emptyList())
private val canvasAspect get() = canvas.width.toFloat() / canvas.height.coerceAtLeast(1)
private fun stored(id: String): Boolean {
if (elements.any { it.id == id }) return true
if (shown.none { it.id == id }) return false
beginEdit(shown, canvasAspect)
return true
}
fun missing(context: android.content.Context): List<InputSurfaceElement> {
val pad = gamepad ?: return emptyList()
if (canvas.width <= 0 || canvas.height <= 0) return emptyList()
val ids = shown.map { it.id }.toSet()
return OnScreenLayout.editorElements(context, layout.copy(elements = pad.stock(layoutScale), aspect = 0f, rotated = emptyList(), scale = layoutScale),
canvas.width, canvas.height).filter { it.id !in ids }
}
fun restore(context: android.content.Context, element: InputSurfaceElement) {
val legacy = gamepad?.stock(layoutScale)?.firstOrNull { it.id == element.id }
val generated = OnScreenLayout.generatedSize(context, layout.copy(elements = elements), canvas.width, canvas.height) != null
if (generated && legacy != null) { checkpoint(); elements = elements + legacy }
else { beginEdit(shown, canvasAspect); elements = elements + element }
if (element.id == "builtin:keyboard" && actions[element.id] == null) actions = actions + (element.id to InputAction.Command(InputCommand.KEYBOARD))
selected = element.id
}
fun remove(id: String) {
if (elements.any { it.id == id }) checkpoint() else stored(id)
elements = elements.filterNot { it.id == id }; actions = actions - id; clicks = clicks - id; selected = null
}
fun update(element: InputSurfaceElement) {
stored(element.id)
elements = elements.map { if (it.id == element.id) element else it }
}
fun resetPositions(context: android.content.Context) {
val adopted = adoptDisplayedFrame(context)
positioned?.let { if (!adopted) checkpoint(); elements = it; if (rescales) layoutScale = 1f }
}
fun action(e: InputSurfaceElement) = preset.copy(elements = actions).action(e)
fun clickAction(e: InputSurfaceElement) = preset.copy(elements = actions, clicks = clicks).clickAction(e)
}
@@ -142,7 +202,7 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () ->
val (display, metrics) = InputLibraries.primaryDisplay(context)
val gamepad = savedLayout.elements.takeIf { e -> e.any { it.id.startsWith("legacy:") } }?.let {
val (w, h) = OnScreenLayout.generatedSize(context, savedLayout, metrics.widthPixels, metrics.heightPixels) ?: (metrics.widthPixels to metrics.heightPixels)
GamepadScaler(display, w, h)
GamepadScaler(display, w, h, savedLayout)
}
val defaults = InputLibraries.defaultPositions(context, library, savedLayout)
SurfaceDraft(savedLayout, savedBindings, defaults?.first, defaults?.second ?: 0f, gamepad, ControllerPrefs.snap(context))
@@ -166,7 +226,7 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () ->
InputLibraries.update(context) { latest ->
val l = latest.layouts.first { it.id == savedLayout.id }
val p = latest.preset(savedBindings.id)
latest.withLayout(l.copy(elements = draft.elements, aspect = draft.aspect, scale = draft.layoutScale)).withPreset(p.copy(elements = draft.actions.filterKeys { id -> draft.elements.any { it.id == id } },
latest.withLayout(OnScreenLayout.withFrame(context, l, draft.elements, draft.aspect, draft.layoutScale)).withPreset(p.copy(elements = draft.actions.filterKeys { id -> draft.elements.any { it.id == id } },
clicks = draft.clicks.filterKeys { id -> draft.elements.any { it.id == id && it.hasClick } }))
}
}.onSuccess { onChanged(); onDismiss() }.onFailure { failure = it.message ?: context.getString(R.string.input_save_failed) }
@@ -225,7 +285,7 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () ->
else "${library.profile(profile).name} · ${roleLabel(role)}", onSave = { action ->
draft.checkpoint()
if (draft.clickProperties) draft.clicks = draft.clicks + (element.id to action) else draft.actions = draft.actions + (element.id to action)
draft.elements = draft.elements.map { if (it.id == element.id) properties.copy(name = properties.name.trim().ifBlank { element.name }) else it }
draft.update(properties.copy(name = properties.name.trim().ifBlank { element.name }))
draft.properties = false
})
}
@@ -245,7 +305,7 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () ->
}
}
}
if (draft.adding) AlertDialog(onDismissRequest = { draft.adding = false }, title = { Text(stringResource(R.string.input_add_element)) }, confirmButton = {}, text = { Column {
if (draft.adding) AlertDialog(onDismissRequest = { draft.adding = false }, title = { Text(stringResource(R.string.input_add_element)) }, confirmButton = {}, text = { Column(Modifier.verticalScroll(rememberScrollState())) {
for (kind in InputElementKind.entries) PadTextButton(onClick = { draft.checkpoint()
val w = if (kind.control.dimensions == 2) .4f else .2f
val h = .3f
@@ -253,6 +313,11 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () ->
val element = InputSurfaceElement(kind.control, (1f - w) / 2, (1f - h) / 2, w, h, newInputId(), kind, name)
draft.elements = draft.elements + element; draft.selected = element.id
draft.adding = false; draft.toolsExpanded = false }) { Text(stringResource(kind.label())) }
val missing = remember(draft.elements, draft.canvas) { draft.missing(context) }
if (missing.isNotEmpty()) HorizontalDivider()
for (element in missing) PadTextButton(onClick = { draft.restore(context, element); draft.adding = false; draft.toolsExpanded = false }) {
Text(PadKit.forOverlay(context, savedLayout)?.name(element.control)?.takeIf { element.name == element.control.label } ?: element.name)
}
} })
if (discard) AlertDialog(onDismissRequest = { discard = false }, title = { Text(stringResource(R.string.input_editor_discard)) },
confirmButton = { PadTextButton(onClick = onDismiss) { Text(stringResource(R.string.common_ok)) } },
@@ -266,10 +331,12 @@ private fun SurfaceCanvas(draft: SurfaceDraft, transparent: Boolean = false) {
AndroidView(factory = { InputSurfaceEditorView(it) }, modifier = Modifier.fillMaxSize().testTag("input-layout-canvas"),
update = { view ->
view.setBackgroundColor(if (transparent) android.graphics.Color.TRANSPARENT else android.graphics.Color.rgb(10, 11, 13))
view.style = draft.layout.style.copy(hidden = emptySet()); view.sourceLayout = draft.layout; view.aspect = draft.aspect; view.elements = draft.elements; view.selected = draft.selected; view.snap = draft.snap
view.style = draft.layout.style.copy(hidden = emptySet()); view.sourceLayout = draft.layout.copy(scale = draft.layoutScale); view.aspect = draft.aspect; view.elements = draft.elements; view.selected = draft.selected; view.snap = draft.snap
view.isEnabled = !draft.properties && !draft.adding
view.onSelect = { if (!draft.properties) draft.selected = it }
view.onBeginEdit = { e, w, h -> draft.beginEdit(e, w.toFloat() / h, if (draft.hasGamepad) GamepadScaler(view.context, w, h) else null) }
view.onBeginEdit = { e, w, h -> draft.beginEdit(e, w.toFloat() / h, if (draft.hasGamepad) GamepadScaler(view.context, w, h, draft.layout) else null) }
view.onResize = { w, h -> draft.canvas = IntSize(w, h) }
view.onDisplayed = { draft.shown = it }
view.onChange = { e -> if (!draft.properties) draft.elements = draft.elements.map { if (it.id == e.id) e else it } }
})
@@ -283,7 +350,8 @@ private fun FloatingSurfaceTools(draft: SurfaceDraft, onSave: () -> Unit, onLeav
val screenHeight = with(density) { maxHeight.toPx() }
val margin = with(density) { 8.dp.toPx() }
var panelSize by remember { mutableStateOf(IntSize.Zero) }
val x = (draft.toolsX * screenWidth).coerceIn(margin, (screenWidth - panelSize.width - margin).coerceAtLeast(margin))
val x = (if (draft.toolsX < 0f) (screenWidth - panelSize.width) / 2f else draft.toolsX * screenWidth)
.coerceIn(margin, (screenWidth - panelSize.width - margin).coerceAtLeast(margin))
val y = (draft.toolsY * screenHeight).coerceIn(margin, (screenHeight - panelSize.height - margin).coerceAtLeast(margin))
val position by rememberUpdatedState(Offset(x, y))
val expandedWidth = minOf(420.dp, maxWidth - 16.dp)
@@ -332,7 +400,7 @@ private fun SurfaceToolbar(draft: SurfaceDraft, onSave: () -> Unit, onLeave: ()
SecondaryButton(stringResource(R.string.common_cancel), compact = true, onClick = onLeave)
SecondaryButton(stringResource(R.string.input_editor_add), enabled = draft.elements.size < 64, compact = true) { draft.adding = true }
SecondaryButton(stringResource(R.string.input_editor_undo), enabled = draft.history.isNotEmpty(), compact = true) { draft.undo() }
if (draft.defaults != null) SecondaryButton(stringResource(R.string.input_reset_positions), enabled = draft.positioned != null, compact = true) { draft.resetPositions() }
if (draft.defaults != null) SecondaryButton(stringResource(R.string.input_reset_positions), enabled = draft.positioned != null, compact = true) { draft.resetPositions(context) }
Row(verticalAlignment = Alignment.CenterVertically) {
Checkbox(draft.snap, { draft.snap = it; ControllerPrefs.setSnap(context, it) })
Text(stringResource(R.string.ctrl_editor_snap))
@@ -340,7 +408,7 @@ private fun SurfaceToolbar(draft: SurfaceDraft, onSave: () -> Unit, onLeave: ()
PrimaryButton(stringResource(R.string.input_editor_done), compact = true, onClick = onSave)
}
if (draft.elements.isNotEmpty()) SliderRow(stringResource(R.string.ctrl_size), null, draft.scale, 80..125, step = 5,
format = { "$it%" }, modifier = Modifier.testTag("input-editor-scale")) { draft.scaleAll(it) }
format = { "$it%" }, modifier = Modifier.testTag("input-editor-scale")) { draft.scaleAll(context, it) }
}
@OptIn(ExperimentalLayoutApi::class)
@@ -352,9 +420,7 @@ private fun SurfaceSelection(draft: SurfaceDraft) {
FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
PrimaryButton(stringResource(R.string.input_properties), compact = true) { draft.clickProperties = false; draft.properties = true }
if (e.hasClick) SecondaryButton(stringResource(R.string.input_click_properties), compact = true) { draft.clickProperties = true; draft.properties = true }
SecondaryButton(stringResource(R.string.input_remove_element), compact = true) {
draft.checkpoint(); draft.elements = draft.elements.filterNot { it.id == e.id }; draft.actions = draft.actions - e.id; draft.clicks = draft.clicks - e.id; draft.selected = null
}
SecondaryButton(stringResource(R.string.input_remove_element), compact = true) { draft.remove(e.id) }
}
} ?: Text(stringResource(R.string.input_editor_hint))
}
@@ -5,9 +5,11 @@ import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.view.HapticFeedbackConstants
import android.view.MotionEvent
import android.view.ViewConfiguration
import android.view.WindowInsets
import android.widget.FrameLayout
import com.droiddeck.launcher.input.OnScreenLayout
import com.droiddeck.launcher.input.PadKit
@@ -40,6 +42,8 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) {
var onSelect: (String?) -> Unit = {}
var onBeginEdit: (List<InputSurfaceElement>, Int, Int) -> Unit = { _, _, _ -> }
var onChange: (InputSurfaceElement) -> Unit = {}
var onResize: (Int, Int) -> Unit = { _, _ -> }
var onDisplayed: (List<InputSurfaceElement>) -> Unit = {}
private val preview = InputSurfaceView(context)
private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = Color.rgb(26, 159, 255); strokeWidth = 2 * resources.displayMetrics.density }
private val radius = 14 * resources.displayMetrics.density
@@ -60,16 +64,35 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) {
preview.updateStyle(style, PadKit.forOverlay(context, sourceLayout))
}
private var safe = Rect()
private var frameWidth = 0
private var frameHeight = 0
private fun refreshElements() {
visibleElements = sourceLayout?.let { layout ->
OnScreenLayout.editorElements(context, layout.copy(elements = elements, aspect = aspect), width, height)
OnScreenLayout.editorElements(context, layout.copy(elements = elements, aspect = aspect), frameWidth, frameHeight, safe = safe)
} ?: elements
preview.updateCustomLayout(visibleElements)
onDisplayed(visibleElements)
}
override fun onApplyWindowInsets(insets: WindowInsets): WindowInsets {
val fresh = OnScreenLayout.safeInsets(insets, false)
if (fresh != safe) { safe = fresh; refreshElements(); invalidate() }
return super.onApplyWindowInsets(insets)
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
if (measuredWidth == frameWidth && measuredHeight == frameHeight) return
frameWidth = measuredWidth; frameHeight = measuredHeight
refreshElements()
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
refreshElements()
onResize(w, h)
}
override fun dispatchDraw(canvas: Canvas) {
@@ -223,7 +223,7 @@ class InputSurfaceView(
canvas.addView(when (element.kind) {
InputElementKind.STICK -> StickView(context, element, source, element.floating, element.hideWhenIdle && pad != null)
InputElementKind.TRACKPAD -> TrackpadView(context, element.control == InputControl.RIGHT_PAD, captioned = element.showLabel,
stock = element.id == "legacy:${element.control.id}" && element.name == element.control.label, source = source)
stock = element.id == "legacy:${element.control.id}", source = source)
InputElementKind.DPAD -> DirectionPad(context, element, source)
else -> HoldButton(context, element, source)
}.apply { tag = element; contentDescription = element.name; styleElement(this); source?.onStateChanged = { postInvalidate() } })
@@ -241,8 +241,13 @@ class InputSurfaceView(
}
canvas.getChildAt(index) as? HoldButton
}
artworkDpad = emptyList()
if (buttons.size != DIRECTIONS.size) return
val previous = artworkDpad
artworkDpad = if (crossed(buttons)) buttons else emptyList()
if (artworkDpad != previous) (previous + artworkDpad).forEach { it.invalidate() }
}
private fun crossed(buttons: List<HoldButton>): Boolean {
if (buttons.size != DIRECTIONS.size) return false
val (up, right, down, left) = buttons
val centerX = (left.left + right.right) / 2f
val centerY = (up.top + down.bottom) / 2f
@@ -250,9 +255,9 @@ class InputSurfaceView(
kotlin.math.abs((down.left + down.right) / 2f - centerX) > 2f ||
kotlin.math.abs((left.top + left.bottom) / 2f - centerY) > 2f ||
kotlin.math.abs((right.top + right.bottom) / 2f - centerY) > 2f ||
up.bottom >= down.top || left.right >= right.left) return
up.bottom >= down.top || left.right >= right.left) return false
artworkDpadBounds.set(left.left.toFloat(), up.top.toFloat(), right.right.toFloat(), down.bottom.toFloat())
artworkDpad = buttons
return true
}
override fun onAttachedToWindow() {
@@ -405,11 +410,7 @@ class InputSurfaceView(
art.system(canvas, width.toFloat(), height.toFloat(), PadArt.Shape.ROUND, PadArt.Icon.KEYBOARD, lit)
return
}
val control = element.control
val native = element.id == "legacy:${control.id}" && element.icon == 0 &&
(element.name == control.label || element.name == kit.name(control)) &&
usesStockShape(control, element.buttonShape)
if (native && art.button(canvas, width, height, control, kit, lit)) return
if (kit.native(element) && art.button(canvas, width, height, element.control, kit, lit)) return
}
drawSurface(canvas, lit, element.buttonShape, classic)
val cx = width / 2f
@@ -605,7 +606,7 @@ class InputSurfaceView(
val cx = if (touching) originX else centreX()
val cy = if (touching) originY else height / 2f
val kit = artwork
if (kit != null && classic(element) && element.name == element.control.label) {
if (kit != null && classic(element)) {
val radius = min(width, height) / 2f - 2f * density
if (radius > 0f) {
art.stick(canvas, cx, cy, radius, kit, knobX, knobY, touching || clicking)
@@ -790,12 +791,6 @@ class InputSurfaceView(
private fun classic(element: InputSurfaceElement) = (element.id == "legacy:${element.control.id}" || element.id == "builtin:keyboard") &&
(element.buttonShape == InputButtonShape.CIRCLE || element.buttonShape == InputButtonShape.PILL)
private fun usesStockShape(control: InputControl, shape: InputButtonShape): Boolean = when (control) {
InputControl.LT, InputControl.LB, InputControl.RB, InputControl.RT -> shape == InputButtonShape.PILL
InputControl.L4, InputControl.L5, InputControl.R4, InputControl.R5 -> shape == InputButtonShape.PILL || shape == InputButtonShape.ROUNDED
else -> shape == InputButtonShape.CIRCLE
}
private val DIRECTIONS = listOf(InputControl.UP, InputControl.RIGHT, InputControl.DOWN, InputControl.LEFT)
internal fun shade(tint: Int, alpha: Int, f: Float) =
@@ -0,0 +1,93 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.DragHandle
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.activity.compose.BackHandler
import com.droiddeck.launcher.R
@Composable
internal fun ManageDrawerPages(offeredNow: List<SessionDrawerPage>, modifier: Modifier = Modifier, releaseSignal: Int = 0, onDone: () -> Unit) {
val ctx = LocalContext.current
val current by rememberUpdatedState(offeredNow)
val previewing = DevPreview.drawer != null
DisposableEffect(Unit) { onDispose { DrawerPages.heldFrom = null } }
DisposableEffect(previewing) { onDispose { if (previewing) DrawerPages.load(ctx) } }
val colors = MaterialTheme.colorScheme
BackHandler { onDone() }
Column(modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(8.dp)) {
Row(verticalAlignment = Alignment.CenterVertically) {
Text(
stringResource(R.string.drawer_manage_pages), fontSize = 15.sp, fontWeight = FontWeight.SemiBold,
color = colors.onBackground, modifier = Modifier.weight(1f),
)
if (!DrawerPages.isDefault()) DrawerOutlineButton(stringResource(R.string.drawer_pages_reset)) { DrawerPages.reset(ctx) }
Spacer(Modifier.width(8.dp))
DrawerOutlineButton(stringResource(R.string.drawer_pages_done), onClick = onDone)
}
SortableRows(
rows = { current.map { it.name } },
commit = { names -> DrawerPages.rearrange(ctx, names.mapNotNull { n -> current.firstOrNull { it.name == n } }) },
movable = { true },
rowHeight = STORE_ROW, handleWidth = STORE_HANDLE,
releaseSignal = releaseSignal,
onGrab = { before -> DrawerPages.heldFrom = before?.mapNotNull { n -> current.firstOrNull { it.name == n } } },
onActivate = { name ->
current.firstOrNull { it.name == name }?.let { DrawerPages.setHidden(ctx, it, it !in DrawerPages.hidden) }
},
) { name, held, offset, hint, rowModifier, onFocus ->
val page = current.first { it.name == name }
val shown = page !in DrawerPages.hidden
val pal = LocalPalette.current
val label = stringResource(page.title)
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
SortRowFrame(held, offset, rowModifier.testTag("drawer-page-row-$name"), hot, src, onFocus) {
Box(contentAlignment = Alignment.Center, modifier = Modifier.size(width = STORE_HANDLE, height = STORE_ROW)) {
Icon(Icons.Filled.DragHandle, null, tint = if (held) pal.signal else colors.onSurfaceVariant, modifier = Modifier.size(20.dp))
}
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
modifier = Modifier.weight(1f).alpha(if (shown) 1f else 0.5f),
) {
Icon(page.icon, null, tint = colors.onSurfaceVariant, modifier = Modifier.size(20.dp))
Text(label, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
if (hint != null) KeyHint("Y", hint)
ToggleSwitch(
shown, DrawerPages.hideable(page), label,
Modifier.testTag("drawer-page-shown-$name").focusProperties { canFocus = false },
) { DrawerPages.setHidden(ctx, page, !it) }
}
}
}
}
@@ -221,8 +221,8 @@ internal fun SideSheet(open: Boolean, onClose: () -> Unit, returnFocus: FocusReq
}
}
private val STORE_ROW = 60.dp
private val STORE_HANDLE = 44.dp
internal val STORE_ROW = 60.dp
internal val STORE_HANDLE = 44.dp
@Composable
internal fun ManageStoresSheet() {
@@ -302,7 +302,7 @@ private fun StoreSortRow(
}
@Composable
private fun SortRowFrame(
internal fun SortRowFrame(
held: Boolean, offset: Float, modifier: Modifier, hot: Boolean, src: MutableInteractionSource, onFocus: (Boolean) -> Unit,
content: @Composable androidx.compose.foundation.layout.RowScope.() -> Unit,
) {
@@ -1,5 +1,11 @@
package com.droiddeck.launcher.ui
import android.content.Context
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.session.SessionPrefs
internal enum class SessionDrawerPage(val firstControl: String) {
CONTROLLER("input-profile"),
GLASSES("glasses-game"),
@@ -12,14 +18,69 @@ internal enum class SessionDrawerPage(val firstControl: String) {
SESSION("suspend"),
}
internal fun sessionDrawerPages(
internal object DrawerPages {
var order by mutableStateOf(SessionDrawerPage.entries.toList())
private set
var hidden by mutableStateOf(emptySet<SessionDrawerPage>())
private set
/** The order captured when a page row was grabbed in Arrange pages; Back restores it. */
var heldFrom: List<SessionDrawerPage>? = null
fun hideable(page: SessionDrawerPage) = page != SessionDrawerPage.SESSION
fun load(context: Context) {
order = arrange(SessionPrefs.drawerPageOrder(context))
hidden = SessionPrefs.drawerPageHidden(context).mapNotNull { name -> SessionDrawerPage.entries.firstOrNull { it.name == name } }
.filter(::hideable).toSet()
}
fun arrange(saved: List<String>): List<SessionDrawerPage> {
val all = SessionDrawerPage.entries
val out = saved.mapNotNull { name -> all.firstOrNull { it.name == name } }.distinct().toMutableList()
for (page in all.filterNot { it in out }) {
val before = all.subList(0, all.indexOf(page)).lastOrNull { it in out }
out.add(if (before == null) 0 else out.indexOf(before) + 1, page)
}
return out
}
fun setHidden(context: Context, page: SessionDrawerPage, hide: Boolean) {
hidden = if (hide && hideable(page)) hidden + page else hidden - page
if (DevPreview.drawer == null) SessionPrefs.setDrawerPageHidden(context, hidden.map { it.name }.toSet())
}
/** [placed] holds the pages on offer in their new order; pages not on offer keep their slots. */
fun rearrange(context: Context, placed: List<SessionDrawerPage>) {
if (placed.isEmpty() || !order.containsAll(placed)) return
val next = placed.iterator()
order = order.map { if (it in placed) next.next() else it }
if (DevPreview.drawer == null) SessionPrefs.setDrawerPageOrder(context, order.map { it.name })
}
fun reset(context: Context) {
order = SessionDrawerPage.entries.toList()
hidden = emptySet()
if (DevPreview.drawer != null) return
SessionPrefs.setDrawerPageOrder(context, order.map { it.name })
SessionPrefs.setDrawerPageHidden(context, emptySet())
}
fun isDefault() = order == SessionDrawerPage.entries.toList() && hidden.isEmpty()
}
internal fun offeredDrawerPages(
hasGlasses: Boolean = false, hasAgent: Boolean = com.droiddeck.launcher.agent.AgentTab.shown,
): List<SessionDrawerPage> =
SessionDrawerPage.entries.filter {
DrawerPages.order.filter {
(hasGlasses || it != SessionDrawerPage.GLASSES) &&
(hasAgent || it != SessionDrawerPage.AGENT)
}
internal fun sessionDrawerPages(
hasGlasses: Boolean = false, hasAgent: Boolean = com.droiddeck.launcher.agent.AgentTab.shown,
): List<SessionDrawerPage> = offeredDrawerPages(hasGlasses, hasAgent).filter { it !in DrawerPages.hidden }
internal fun List<SessionDrawerPage>.step(current: SessionDrawerPage, direction: Int): SessionDrawerPage {
val index = indexOf(current).coerceAtLeast(0)
return this[Math.floorMod(index + direction, size)]
@@ -47,6 +47,7 @@ import androidx.compose.material.icons.outlined.Pause
import androidx.compose.material.icons.outlined.PictureInPictureAlt
import androidx.compose.material.icons.automirrored.outlined.ExitToApp
import androidx.compose.material.icons.outlined.Settings
import androidx.compose.material.icons.outlined.Tune
import androidx.compose.material.icons.outlined.Speed
import androidx.compose.material.icons.outlined.SportsEsports
import androidx.compose.material3.Icon
@@ -162,7 +163,7 @@ import com.droiddeck.launcher.input.TouchGestureConfig.Companion.MOUSE_BEHAVIOR_
import kotlinx.coroutines.flow.collect
import java.util.Locale
private val SessionDrawerPage.title: Int get() = when (this) {
internal val SessionDrawerPage.title: Int get() = when (this) {
SessionDrawerPage.CONTROLLER -> R.string.drawer_page_controller
SessionDrawerPage.GLASSES -> R.string.drawer_page_glasses
SessionDrawerPage.DISPLAY -> R.string.drawer_page_display
@@ -174,7 +175,7 @@ private val SessionDrawerPage.title: Int get() = when (this) {
SessionDrawerPage.SESSION -> R.string.mode_session
}
private val SessionDrawerPage.icon get() = when (this) {
internal val SessionDrawerPage.icon get() = when (this) {
SessionDrawerPage.CONTROLLER -> Icons.Outlined.SportsEsports
SessionDrawerPage.GLASSES -> GlassesIcon
SessionDrawerPage.DISPLAY -> Icons.Outlined.DesktopWindows
@@ -392,7 +393,10 @@ class DrawerActions(
internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, controllerActive: Boolean, onPageChange: (SessionDrawerPage) -> Unit, a: DrawerActions, docked: Boolean = false,
backRequest: Int = 0, onLayerChange: (Boolean) -> Unit = {}) {
val pages = sessionDrawerPages(a.glassesPresent)
val page = requestedPage.takeIf { it in pages } ?: SessionDrawerPage.CONTROLLER
val page = requestedPage.takeIf { it in pages } ?: pages.first()
var managing by rememberSaveable { mutableStateOf(false) }
var releaseSignal by remember { mutableStateOf(0) }
val drawerContext = androidx.compose.ui.platform.LocalContext.current
LaunchedEffect(requestedPage, pages) { if (page != requestedPage) onPageChange(page) }
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
@@ -509,16 +513,24 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
.blockTouches()
.focusGroup()
.controllerBack {
if (host.open != null) host.open = null else a.onClose()
when {
host.open != null -> host.open = null
managing -> DrawerPages.heldFrom?.let { held ->
DrawerPages.rearrange(drawerContext, held)
releaseSignal++
} ?: run { managing = false }
else -> a.onClose()
}
}
.padding(12.dp),
) {
val showPicker = a.secondScreenDisplays.isNotEmpty()
val roomyHeader = sheetWidth >= if (showPicker) 560.dp else 408.dp
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth()) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(6.dp),
modifier = Modifier.fillMaxWidth().heightIn(min = 44.dp)
modifier = Modifier.weight(1f).heightIn(min = 44.dp)
.then(if (roomyHeader) Modifier else Modifier.horizontalScroll(rememberScrollState())),
) {
SteamActionPill(
@@ -540,7 +552,6 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
if (a.pipSupported) SteamActionPill(
stringResource(R.string.pip_title), Icons.Outlined.PictureInPictureAlt, focus.track(page, "pip"),
) { host.open = null; a.onPip() }
if (docked) StopSessionButton(modifier = focus.track(page, "stop").onGloballyPositioned { stopCoords = it }) { host.open = null; confirmStop = true }
val steamActions = a.steam && a.onSteamMenu != null && a.onQam != null
val qamInteraction = remember { MutableInteractionSource() }
var qamStartedOnPress by remember { mutableStateOf(false) }
@@ -570,7 +581,8 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
onQamConfirm = { host.open = null; a.onQam?.invoke() },
showShortcuts = !docked,
)
if (!docked) StopSessionButton(modifier = focus.track(page, "stop").onGloballyPositioned { stopCoords = it }) { host.open = null; confirmStop = true }
}
StopSessionButton(modifier = focus.track(page, "stop").onGloballyPositioned { stopCoords = it }) { host.open = null; confirmStop = true }
}
a.onAchievements?.let { show ->
DrawerAchievementsRow(a.achievementsProgress, Modifier.padding(top = if (short) 6.dp else 10.dp).then(focus.track(page, "achievements"))) {
@@ -589,7 +601,15 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
DrawerBumper("RB", stringResource(R.string.drawer_next_page), modifier = focus.track(page, "next")) {
host.open = null; onPageChange(pages.step(page, 1))
}
SmallIconButton(
Icons.Outlined.Tune, stringResource(R.string.drawer_manage_pages), colors.onSurfaceVariant,
) { host.open = null; managing = !managing }
}
if (managing) ManageDrawerPages(
offeredDrawerPages(a.glassesPresent),
Modifier.weight(1f).fillMaxWidth().padding(top = 8.dp, start = 14.dp, end = 14.dp),
releaseSignal,
) { managing = false } else {
if (page == SessionDrawerPage.GLASSES) SegmentedTabs(
glassesPages, glassesTab, modifier = Modifier.fillMaxWidth().padding(top = 8.dp),
tabModifier = { key -> focus.track(page, "glasses-tab-$key").testTag("glasses-tab-$key") },
@@ -926,6 +946,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
}
}
} }
}
}
StopConfirm(
open = confirmStop,
@@ -983,7 +1004,7 @@ private fun DrawerActionButton(text: String, icon: androidx.compose.ui.graphics.
}
@Composable
private fun DrawerOutlineButton(text: String, modifier: Modifier = Modifier, progress: Float? = null, onClick: () -> Unit) {
internal fun DrawerOutlineButton(text: String, modifier: Modifier = Modifier, progress: Float? = null, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val source = remember { MutableInteractionSource() }
@@ -1005,15 +1026,14 @@ private fun StopSessionButton(modifier: Modifier = Modifier, onClick: () -> Unit
val src = remember { MutableInteractionSource() }
val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value
val fill by animateColorAsState(if (hot) colors.error.copy(alpha = 0.18f) else Color.Transparent, Motion.tw(220), label = "dangerFill")
val shape = RoundedCornerShape(20.dp)
val shape = androidx.compose.foundation.shape.CircleShape
val stopDescription = stringResource(R.string.stop_session)
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center,
modifier = modifier.heightIn(min = 44.dp).widthIn(min = 44.dp).semantics { contentDescription = stopDescription }.testTag("drawer-stop")
modifier = modifier.size(44.dp).semantics { contentDescription = stopDescription }.testTag("drawer-stop")
.clip(shape).background(fill).glideBorder(hot, shape, colors.error.copy(alpha = 0.9f), colors.error.copy(alpha = 0.55f))
.hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, onClick = onClick)
.controllerConfirm(onClick = onClick)
.padding(horizontal = 12.dp),
.controllerConfirm(onClick = onClick),
) {
Icon(Icons.Outlined.PowerSettingsNew, contentDescription = null, tint = colors.error, modifier = Modifier.size(18.dp))
}
@@ -108,6 +108,7 @@ internal object SettingsIndex {
s(SettingsSection.LAUNCHER, R.string.setup_launcher_orientation, "rotate", "portrait"),
s(SettingsSection.LAUNCHER, R.string.setup_session_orientation, "rotate", "portrait"),
s(SettingsSection.LAUNCHER, R.string.setup_fullscreen),
s(SettingsSection.LAUNCHER, R.string.setup_controller_haptics, "vibration", "rumble"),
s(SettingsSection.LAUNCHER, R.string.setup_dual_screen_launcher, "thor", "second screen", "bottom screen"),
s(SettingsSection.LAUNCHER, R.string.setup_low_storage_warning),
s(SettingsSection.LAUNCHER, R.string.mode_sgdb_key, "artwork", "steamgriddb"),
@@ -118,6 +118,8 @@ internal fun SortableRows(
rowHeight: androidx.compose.ui.unit.Dp,
handleWidth: androidx.compose.ui.unit.Dp,
onActivate: (String) -> Unit,
onGrab: (before: List<String>?) -> Unit = {},
releaseSignal: Int = 0,
row: @Composable (key: String, held: Boolean, offset: Float, hint: String?, modifier: Modifier, onFocus: (Boolean) -> Unit) -> Unit,
) {
val pad = LocalInputModeManager.current.inputMode == InputMode.Keyboard
@@ -129,6 +131,9 @@ internal fun SortableRows(
val rowPx = with(LocalDensity.current) { rowHeight.toPx() }
val handlePx = with(LocalDensity.current) { handleWidth.toPx() }
val list = rows()
val grab by rememberUpdatedState(onGrab)
LaunchedEffect(grabbed) { grab(if (grabbed != null) before else null) }
LaunchedEffect(releaseSignal) { if (releaseSignal > 0) grabbed = null }
Column(
Modifier.fillMaxWidth().pointerInput(Unit) {
awaitEachGesture {
+5
View File
@@ -708,6 +708,9 @@
<string name="drawer_open_qam">Open Quick Access Menu</string>
<string name="drawer_prev_page">Previous page</string>
<string name="drawer_next_page">Next page</string>
<string name="drawer_manage_pages">Arrange pages</string>
<string name="drawer_pages_reset">Reset</string>
<string name="drawer_pages_done">Done</string>
<string name="drawer_hud">Performance HUD</string>
<string name="drawer_hud_fps">Frame rate</string>
<string name="drawer_hud_battery">Battery temperature</string>
@@ -1032,6 +1035,8 @@
<string name="setup_fullscreen">Fullscreen</string>
<string name="setup_fullscreen_on">Hides the Android status and navigation bars</string>
<string name="setup_fullscreen_off">Shows the Android status and navigation bars</string>
<string name="setup_controller_haptics">Controller haptics</string>
<string name="setup_controller_haptics_hint">A light tick when the D-pad, A or the shoulder buttons move or select in the launcher. Touch stays silent</string>
<string name="setup_dual_screen_launcher">Dual screen launcher</string>
<string name="setup_dual_screen_launcher_hint">Automatic puts the launcher sections (Steam, Library, Stores and the rest) on the second screen of handhelds with a built-in one. On uses any second display. Off keeps the launcher on one screen.</string>
<string name="setup_dual_screen_sessions">Dual screen sessions</string>
@@ -14,7 +14,7 @@ import org.robolectric.annotation.Config
class InputLayoutToolsTest {
private val context: Context get() = RuntimeEnvironment.getApplication()
@Before fun reset() {
for (name in listOf("input-profiles", "input-surfaces", "controller", "session")) context.getSharedPreferences(name, Context.MODE_PRIVATE).edit().clear().commit()
for (name in listOf("input-profiles", "input-surfaces", "controller")) context.getSharedPreferences(name, Context.MODE_PRIVATE).edit().clear().commit()
}
@Test fun scaleAllResizesEveryElementAroundItsCentreInsideTheScreen() {
@@ -132,6 +132,7 @@ class InputLayoutToolsTest {
}
@Test fun aScaledGamepadStaysGeneratedAndRegeneratesOnRotation() {
com.droiddeck.launcher.session.SessionPrefs.setSteamController(context, com.droiddeck.launcher.session.SessionPrefs.CONTROLLER_NONE)
val (display, metrics) = InputLibraries.primaryDisplay(context)
val long = maxOf(metrics.widthPixels, metrics.heightPixels)
val short = minOf(metrics.widthPixels, metrics.heightPixels)
@@ -139,9 +140,7 @@ class InputLayoutToolsTest {
val scaled = gamepad.copy(scale = 1.25f, elements = LegacyGamepadLayout(display, long, short, scale = 1.25f).regenerate(gamepad.elements))
assertEquals(long to short, OnScreenLayout.generatedSize(context, scaled, long, short))
val rotated = OnScreenLayout.elements(context, scaled, short, long, android.graphics.Rect())
val stock = OnScreenLayout.elements(context, gamepad, short, long, android.graphics.Rect())
assertEquals(stock.map { it.id }, rotated.map { it.id })
assertTrue(rotated.first { it.control == InputControl.LS }.width > stock.first { it.control == InputControl.LS }.width)
assertEquals(LegacyGamepadLayout(context, short, long, scale = 1.25f).regenerate(scaled.elements), rotated)
assertNull(OnScreenLayout.generatedSize(context, scaled.copy(scale = 1f), long, short))
InputLibraries.update(context) { it.withLayout(scaled) }
assertEquals(1.25f, InputLibraries.read(context).layouts.first { it.id == gamepad.id }.scale)
@@ -79,7 +79,7 @@ class OnScreenLayoutTest {
assertEquals(original.map { it.id }, placed(true, true).map { it.id })
assertEquals(placed(false, false), placed(true, true))
SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_DECK)
val edited = layout.copy(elements = layout.elements.map { e -> if (e.control == InputControl.START) e.copy(y = .3f) else e })
val edited = layout.copy(elements = layout.elements.map { e -> if (e.control == InputControl.START) e.copy(y = .3f) else e }, aspect = w.toFloat() / h)
val fitted = OnScreenLayout.elements(context, edited, w, h, safe)
assertTrue(fitted.single { it.control == InputControl.START }.y < .5f)
}
@@ -197,8 +197,10 @@ class OnScreenLayoutTest {
assertEquals(control.id, x, cx, .01f)
assertEquals(control.id, y, cy, .01f)
}
assertCenter(InputControl.LT, 140f, 66f)
assertCenter(InputControl.LB, 140f, 148f)
assertCenter(InputControl.LT, 120f, 96f)
assertCenter(InputControl.LB, 310f, 96f)
assertCenter(InputControl.RB, 1290f, 96f)
assertCenter(InputControl.RT, 1480f, 96f)
assertCenter(InputControl.UP, 220f, 242.5f)
assertCenter(InputControl.RIGHT, 322.5f, 345f)
assertCenter(InputControl.LS, 290f, 640f)
@@ -492,4 +494,138 @@ class OnScreenLayoutTest {
assertEquals(InputStockLayouts.layouts().filter { it.id != DeckPanel.GAMEPAD.layout }.map { it.elements },
others.filter { l -> InputStockLayouts.layouts().any { it.id == l.id } }.map { it.elements })
}
private val kits = listOf(SessionPrefs.CONTROLLER_DECK, SessionPrefs.CONTROLLER_STEAM, SessionPrefs.CONTROLLER_XBOX360,
SessionPrefs.CONTROLLER_DS4, SessionPrefs.CONTROLLER_DUALSENSE)
private fun List<InputSurfaceElement>.at(control: InputControl) = single { it.id == "legacy:${control.id}" }
@Test @Config(qualifiers = "w800dp-h450dp-land-320dpi")
fun everyKitPutsTriggersBesideTheirBumpers() {
for (kit in kits) {
SessionPrefs.setSteamController(context, kit)
val placed = OnScreenLayout.elements(context, gamepad(), 1600, 900, Rect(), rearButtons = true, trackpads = true)
val lt = placed.at(InputControl.LT); val lb = placed.at(InputControl.LB)
val rb = placed.at(InputControl.RB); val rt = placed.at(InputControl.RT)
for ((outer, inner) in listOf(lt to lb, rt to rb)) assertEquals(kit, outer.y + outer.height / 2f, inner.y + inner.height / 2f, .001f)
assertTrue(kit, lt.x + lt.width <= lb.x)
assertTrue(kit, rb.x + rb.width <= rt.x)
assertInside(placed, 1600, 900)
}
}
@Test @Config(qualifiers = "w1280dp-h800dp-land-mdpi")
fun tabletOverlaysStayInTheLowerHalfOfTheScreen() {
for (kit in kits) {
SessionPrefs.setSteamController(context, kit)
val placed = OnScreenLayout.elements(context, gamepad(), 1280, 800, Rect(), rearButtons = true, trackpads = true)
for (e in placed) assertTrue("$kit ${e.id}", e.y >= .45f)
assertInside(placed, 1280, 800)
}
}
@Test @Config(qualifiers = "w800dp-h450dp-land-320dpi")
fun phoneOverlaysStillUseTheFullHeight() {
SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_DECK)
val placed = OnScreenLayout.elements(context, gamepad(), 1600, 900, Rect())
assertTrue(placed.at(InputControl.LT).y < .15f)
assertTrue(placed.at(InputControl.START).let { it.y + it.height } > .9f)
}
@Test @Config(qualifiers = "w800dp-h450dp-land-320dpi")
fun aLayoutEditedInOneOrientationKeepsTheKitInTheOther() {
for (kit in kits) {
SessionPrefs.setSteamController(context, kit)
val layout = gamepad()
val landscape = OnScreenLayout.elements(context, layout, 1600, 900, Rect())
val moved = landscape.map { if (it.control == InputControl.A) it.copy(x = .5f, y = .5f) else it }
val edited = layout.copy(elements = moved, aspect = 1600f / 900f)
assertEquals(kit, .5f, OnScreenLayout.elements(context, edited, 1600, 900, Rect()).at(InputControl.A).x, .001f)
val kitPortrait = OnScreenLayout.elements(context, layout, 900, 1600, Rect())
val editedPortrait = OnScreenLayout.elements(context, edited, 900, 1600, Rect())
for (control in listOf(InputControl.A, InputControl.LT, InputControl.RB, InputControl.LS, InputControl.UP))
assertEquals("$kit ${control.id}", kitPortrait.at(control), editedPortrait.at(control))
}
}
@Test @Config(qualifiers = "w800dp-h450dp-land-320dpi")
fun eachOrientationKeepsItsOwnEdits() {
SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_XBOX360)
val layout = gamepad()
val landscape = OnScreenLayout.elements(context, layout, 1600, 900, Rect()).map { if (it.control == InputControl.A) it.copy(x = .5f, y = .5f) else it }
val edited = OnScreenLayout.withFrame(context, layout, landscape, 1600f / 900f)
val portrait = OnScreenLayout.elements(context, edited, 900, 1600, Rect()).map { if (it.control == InputControl.B) it.copy(x = .1f, y = .2f) else it }
val both = OnScreenLayout.withFrame(context, edited, portrait, 900f / 1600f)
assertEquals(landscape.map { it.id to floatArrayOf(it.x, it.y).toList() }, both.elements.map { it.id to floatArrayOf(it.x, it.y).toList() })
val wide = OnScreenLayout.elements(context, both, 1600, 900, Rect())
val tall = OnScreenLayout.elements(context, both, 900, 1600, Rect())
assertEquals(.5f, wide.at(InputControl.A).x, .001f)
assertEquals(.1f, tall.at(InputControl.B).x, .001f)
assertEquals(.2f, tall.at(InputControl.B).y, .001f)
val renamed = OnScreenLayout.withFrame(context, both, both.elements.map { if (it.control == InputControl.A) it.copy(name = "Jump") else it }, both.aspect)
assertEquals("Jump", OnScreenLayout.elements(context, renamed, 900, 1600, Rect()).at(InputControl.A).name)
assertEquals(.1f, OnScreenLayout.elements(context, renamed, 900, 1600, Rect()).at(InputControl.B).x, .001f)
val library = InputLibraries.read(context).withLayout(both)
assertEquals(both, InputLibraries.decode(InputLibraries.encode(library))!!.layouts.first { it.id == both.id })
}
@Test @Config(qualifiers = "w800dp-h450dp-land-320dpi")
fun aRemovedRearButtonStaysRemovedWhileTheOthersRemain() {
SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_DECK)
val layout = gamepad()
val displayed = OnScreenLayout.elements(context, layout, 1600, 900, Rect(), rearButtons = true, trackpads = true)
val frozen = OnScreenLayout.editorFrame(layout, displayed).filterNot { it.control == InputControl.L4 || it.control == InputControl.LEFT_PAD }
val edited = layout.copy(elements = frozen, aspect = 1600f / 900f)
for ((w, h) in listOf(1600 to 900, 900 to 1600)) {
val placed = OnScreenLayout.elements(context, edited, w, h, Rect(), rearButtons = true, trackpads = true).map { it.control }
assertFalse(InputControl.L4 in placed)
assertFalse(InputControl.LEFT_PAD in placed)
assertTrue(InputControl.R5 in placed)
assertTrue(InputControl.RIGHT_PAD in placed)
}
val hidden = OnScreenLayout.elements(context, edited, 1600, 900, Rect(), rearButtons = false, trackpads = false).map { it.control }
assertFalse(InputControl.R5 in hidden)
assertFalse(InputControl.RIGHT_PAD in hidden)
}
@Test @Config(qualifiers = "w800dp-h450dp-land-320dpi")
fun aPortraitMainLayoutUsesTheStockControlsInLandscape() {
SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_XBOX360)
val layout = gamepad()
val portrait = OnScreenLayout.elements(context, layout, 900, 1600, Rect()).map { if (it.control == InputControl.A) it.copy(x = .1f, y = .1f) else it }
val edited = layout.copy(elements = portrait, aspect = 900f / 1600f)
assertEquals(OnScreenLayout.elements(context, layout, 1600, 900, Rect()), OnScreenLayout.elements(context, edited, 1600, 900, Rect()))
assertEquals(.1f, OnScreenLayout.elements(context, edited, 900, 1600, Rect()).at(InputControl.A).x, .001f)
}
@Test @Config(qualifiers = "w800dp-h450dp-land-320dpi")
fun aPortraitSaveKeepsOptionalControlsInThePortraitFrameOnly() {
SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_DECK)
val layout = gamepad()
val landscape = OnScreenLayout.elements(context, layout, 1600, 900, Rect())
val edited = OnScreenLayout.withFrame(context, layout, landscape, 1600f / 900f)
val portrait = OnScreenLayout.elements(context, edited, 900, 1600, Rect(), rearButtons = true, trackpads = true)
.map { if (it.control == InputControl.B) it.copy(x = .1f, y = .2f) else it }
assertTrue(portrait.any { it.control == InputControl.L4 })
val both = OnScreenLayout.withFrame(context, edited, portrait, 900f / 1600f)
assertTrue(both.elements.none { it.control == InputControl.L4 || it.control == InputControl.LEFT_PAD })
assertTrue(both.rotated.any { it.control == InputControl.L4 })
assertEquals(OnScreenLayout.elements(context, edited, 1600, 900, Rect(), rearButtons = true, trackpads = true),
OnScreenLayout.elements(context, both, 1600, 900, Rect(), rearButtons = true, trackpads = true))
val tall = OnScreenLayout.elements(context, both, 900, 1600, Rect(), rearButtons = true, trackpads = true)
for (control in listOf(InputControl.L4, InputControl.LEFT_PAD, InputControl.B)) assertEquals(control.id, portrait.at(control), tall.at(control))
assertTrue(OnScreenLayout.elements(context, both, 900, 1600, Rect(), rearButtons = false, trackpads = false)
.none { it.control == InputControl.L4 || it.control == InputControl.LEFT_PAD })
}
@Test fun stockControlsUseTheKitArtworkWhileAddedAndTrackpadControlsStillUseTheTint() {
for (kit in listOf(PadKit.XBOX, PadKit.DUALSENSE)) {
SessionPrefs.setSteamController(context, if (kit == PadKit.XBOX) SessionPrefs.CONTROLLER_XBOX360 else SessionPrefs.CONTROLLER_DUALSENSE)
val layout = gamepad()
assertTrue(kit.name, layout.elements.all { kit.artwork(it) })
val added = InputSurfaceElement(InputControl.A, 0f, 0f, .1f, .1f, "custom", name = "Fire")
assertFalse(kit.artwork(added))
assertFalse(kit.artwork(layout.elements.first { it.control == InputControl.A }.copy(image = "picture")))
}
}
}
@@ -73,72 +73,6 @@ class BattleNetTest {
assertEquals(crc or 0x80000000L, BattleNet.APP_ID)
}
@Test fun theNewestD2rfixIsTheHighestFexThenTheHighestFix() {
val items = listOf(
item("FEXCore-2610-linux.wcp"),
item("FEXCore-2609-d2rfix25-linux.wcp"),
item("FEXCore-2610-d2rfix9-linux.wcp"),
item("FEXCore-2610-d2rfix28-linux.wcp"),
item("FEXCore-2509.1-d2rfix40-linux.wcp"),
)
assertEquals("FEXCore-2610-d2rfix28-linux.wcp", BattleNet.newestD2rFix(items)?.file)
assertEquals("FEXCore-2610.1-d2rfix1-linux.wcp", BattleNet.newestD2rFix(items + item("FEXCore-2610.1-d2rfix1-linux.wcp"))?.file)
assertEquals("FexCore-2611-D2RFIX2-linux.wcp", BattleNet.newestD2rFix(items + item("FexCore-2611-D2RFIX2-linux.wcp"))?.file)
}
@Test fun onlyFexD2rfixPackagesCount() {
assertNull(BattleNet.newestD2rFix(listOf(item("FEXCore-2610-linux.wcp"), item("FEXCore-2610-d2rfix28-linux.wcp", comp = "dxvk"))))
assertNull(BattleNet.d2rfix("FEXCore-2610-d2rfix28-linux.wcp.part"))
assertNull(BattleNet.d2rfix("FEXCore-2610-d2rfix-linux.wcp"))
assertEquals(listOf(2610L) to 28L, BattleNet.d2rfix("FEXCore-2610-d2rfix28-linux.wcp"))
}
@Test fun theNewestStoredBuildIsSetForThePrefix() {
catalog("FEXCore-2609-d2rfix25-linux.wcp", "FEXCore-2610-d2rfix28-linux.wcp", "FEXCore-2610-linux.wcp")
store("FEXCore-2610-d2rfix28-linux.wcp")
assertEquals("FEXCore-2610-d2rfix28-linux.wcp", BattleNet.ensureFex(context, ::noRefresh))
assertEquals(mapOf("fex" to "FEXCore-2610-d2rfix28-linux.wcp"), ComponentsManager.gameComponents(context, BattleNet.APP_ID.toString()))
assertEquals("FEXCore-2610-d2rfix28-linux.wcp", BattleNet.ensureFex(context, ::noRefresh))
}
@Test fun aNewerBuildReplacesTheOldOne() {
catalog("FEXCore-2609-d2rfix25-linux.wcp")
store("FEXCore-2609-d2rfix25-linux.wcp")
BattleNet.ensureFex(context, ::noRefresh)
catalog("FEXCore-2609-d2rfix25-linux.wcp", "FEXCore-2610-d2rfix28-linux.wcp")
store("FEXCore-2610-d2rfix28-linux.wcp")
BattleNet.ensureFex(context, ::noRefresh)
assertEquals("FEXCore-2610-d2rfix28-linux.wcp", ComponentsManager.gameComponents(context, BattleNet.APP_ID.toString())["fex"])
}
@Test fun aStaleListingIsFetchedAgain() {
catalog("FEXCore-2609-d2rfix25-linux.wcp", fetchedAt = 1)
store("FEXCore-2610-d2rfix28-linux.wcp")
BattleNet.ensureFex(context) { listOf(item("FEXCore-2609-d2rfix25-linux.wcp"), item("FEXCore-2610-d2rfix28-linux.wcp")) }
assertEquals("FEXCore-2610-d2rfix28-linux.wcp", ComponentsManager.gameComponents(context, BattleNet.APP_ID.toString())["fex"])
}
@Test fun aFailedFetchFallsBackOnTheCachedListing() {
catalog("FEXCore-2609-d2rfix25-linux.wcp", fetchedAt = 1)
store("FEXCore-2609-d2rfix25-linux.wcp")
assertEquals("FEXCore-2609-d2rfix25-linux.wcp", BattleNet.ensureFex(context) { error("offline") })
}
@Test fun aListingWithoutD2rfixIsAnError() {
catalog("FEXCore-2610-linux.wcp")
var refreshed = 0
assertThrows(IllegalStateException::class.java) { BattleNet.ensureFex(context) { refreshed++; emptyList() } }
assertEquals(1, refreshed)
assertEquals(emptyMap<String, String>(), ComponentsManager.gameComponents(context, BattleNet.APP_ID.toString()))
}
@Test fun installedIsTheLauncherInThePrefix() {
assertFalse(BattleNet.installed(context))
launcher().apply { parentFile!!.mkdirs(); writeText("MZ") }
@@ -152,9 +86,9 @@ class BattleNetTest {
}
@Test fun removeTakesThePrefixItsMenuEntryAndCacheButNothingItLinksTo() {
catalog("FEXCore-2610-d2rfix28-linux.wcp")
store("FEXCore-2610-d2rfix28-linux.wcp")
BattleNet.ensureFex(context, ::noRefresh)
store("FEXCore-2610-linux.wcp")
ComponentsManager.setGameComponent(context, BattleNet.APP_ID.toString(), "fex", "FEXCore-2610-linux.wcp")
assertEquals(mapOf("fex" to "FEXCore-2610-linux.wcp"), ComponentsManager.gameComponents(context, BattleNet.APP_ID.toString()))
val root = LinuxRuntime.rootDir(context)
fun put(relative: String) = File(root, relative).apply { parentFile!!.mkdirs(); writeText("x") }
launcher().apply { parentFile!!.mkdirs(); writeText("MZ") }
@@ -176,7 +110,7 @@ class BattleNetTest {
assertTrue(otherMenu.isFile)
assertFalse(log.parentFile!!.exists())
assertTrue(otherPrefix.isFile)
assertNull(BattleNet.fexInUse(context))
assertEquals(emptyMap<String, String>(), ComponentsManager.gameComponents(context, BattleNet.APP_ID.toString()))
outside.deleteRecursively()
}
@@ -481,6 +415,22 @@ class BattleNetTest {
assertTrue(BattleNet.ensureVideoMemory(context))
}
@Test fun theProfileDefaultsAreSetForTheBattleNetProgramOrOnceInstalledAndNeverForAnythingElse() {
File(context.filesDir, "game-environment.json").delete()
val manager = context.getSystemService(android.app.ActivityManager::class.java)
org.robolectric.Shadows.shadowOf(manager).setMemoryInfo(android.app.ActivityManager.MemoryInfo().apply { totalMem = 11113L shl 20 })
val scope = BattleNet.APP_ID.toString()
BattleNet.ensureDefaults(context, null)
assertNull(GameEnvironmentStore.read(context).games[scope]?.get("DXVK_CONFIG"))
BattleNet.ensureDefaults(context, BattleNet.PROGRAM)
assertEquals(BattleNet.videoMemoryOptions(2048), GameEnvironmentStore.read(context).games[scope]?.get("DXVK_CONFIG"))
assertTrue(com.droiddeck.launcher.session.SessionPrefs.battleNetNoSteamSet(context))
File(context.filesDir, "game-environment.json").delete()
launcher().apply { parentFile!!.mkdirs(); writeText("MZ") }
BattleNet.ensureDefaults(context, null)
assertEquals(BattleNet.videoMemoryOptions(2048), GameEnvironmentStore.read(context).games[scope]?.get("DXVK_CONFIG"))
}
private fun launcher() = File(BattleNet.prefix(context), "pfx/drive_c/Program Files (x86)/Battle.net/Battle.net Launcher.exe")
private fun varint(value: Long): ByteArray {
@@ -496,21 +446,6 @@ class BattleNetTest {
private fun varintField(number: Int, value: Long) = varint((number shl 3).toLong()) + varint(value)
private fun message(vararg fields: ByteArray) = fields.fold(ByteArray(0)) { all, f -> all + f }
private fun noRefresh(context: Context): List<ComponentsManager.CatalogItem> = error("the cached listing was fresh")
private fun item(file: String, comp: String = "fex") = ComponentsManager.CatalogItem(
file, comp, "FexCore-Linux", "https://github.com/The412Banner/Nightlies/releases/download/FexCore-Linux/$file", 4, "sha256:" + "ab".repeat(32),
)
private fun catalog(vararg files: String, fetchedAt: Long = System.currentTimeMillis() / 1000) {
val cache = File(context.filesDir, "components/catalog.json")
cache.parentFile!!.mkdirs()
val items = JSONArray()
for (file in files) items.put(JSONObject().put("file", file).put("comp", "fex").put("release", "FexCore-Linux")
.put("url", item(file).url).put("size", 4).put("digest", item(file).digest))
cache.writeText(JSONObject().put("items", items).put("fetchedAt", fetchedAt).toString())
}
private fun store(file: String) {
val wcp = File(context.filesDir, "components/packages/$file")
wcp.parentFile!!.mkdirs()
@@ -82,6 +82,37 @@ class ComponentsRepublishTest {
private fun scopedTools() = rows().filter { it[0] == scope }.map { it[1] }.toSet()
@Test fun battleNetDropsAnOldPinnedFexOnceAndKeepsAnyOtherChoice() {
proton("DroidDeck-Proton 11-11.8", "DroidDeck-Proton-11-11.8")
packageFile()
ComponentsManager.setGameComponent(context, scope, "fex", fex)
ComponentsManager.setGameComponent(context, "123", "fex", fex)
assertTrue(rows().any { it[0] == scope })
ComponentsManager.migrateBattleNetFex(context)
assertEquals(emptyMap<String, String>(), ComponentsManager.gameComponents(context, scope))
assertEquals(fex, ComponentsManager.gameComponents(context, "123")["fex"])
assertTrue(rows().none { it[0] == scope })
assertTrue(rows().any { it[0] == "123" })
ComponentsManager.setGameComponent(context, scope, "fex", fex)
ComponentsManager.migrateBattleNetFex(context)
assertEquals(fex, ComponentsManager.gameComponents(context, scope)["fex"])
}
@Test fun battleNetKeepsAFexTheUserChoseThemselves() {
proton("DroidDeck-Proton 11-11.8", "DroidDeck-Proton-11-11.8")
val own = "FEXCore-2612-linux.wcp"
packageFile()
File(context.filesDir, "components/packages/$fex").copyTo(File(context.filesDir, "components/packages/$own"))
ComponentsManager.setGameComponent(context, scope, "fex", own)
ComponentsManager.migrateBattleNetFex(context)
assertEquals(own, ComponentsManager.gameComponents(context, scope)["fex"])
}
private fun rows() = launchState().readLines().filter { it.isNotEmpty() }.map { it.split('\t') }
private fun launchState() = File(LinuxRuntime.rootDir(context), "root/.local/share/droiddeck-components/desired.tsv")
@@ -8,6 +8,7 @@ import java.util.concurrent.RejectedExecutionException
import java.util.concurrent.TimeUnit
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
@@ -132,7 +133,132 @@ class SessionSuspendControllerTest {
assertFalse(hold.exists())
fixture.controller.resume { assertTrue(it) }
assertFalse(hold.exists())
assertFalse(File(fixture.control.parentFile, ".dd-zram.hold.$GAME").exists())
assertEquals(listOf<String?>("1", "0"), fixture.held)
assertEquals(listOf<String?>("1", "2 0"), fixture.shared)
}
@Test fun aSuspendWithMemoryToSpareKeepsTheSessionResident() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.availableWhileSuspendedKb = 8_000_000L
fixture.controller.freeze(pageOut = true) { assertTrue(it) }
assertFalse(fixture.signals.any { it.signal == URG })
assertTrue(fixture.pagedOut.isEmpty())
assertTrue(fixture.game.threads.all { it.state == 't' })
assertEquals(listOf(10_000L), fixture.scheduled.map { it.first })
fixture.runScheduled()
assertFalse(fixture.signals.any { it.signal == URG || it.signal == CONT })
assertEquals(1, fixture.scheduled.size)
fixture.controller.resume { assertTrue(it) }
assertFalse(fixture.signals.any { it.signal == URG })
assertTrue(fixture.pagedIn.isEmpty())
fixture.runScheduled()
assertTrue(fixture.scheduled.isEmpty())
assertTrue(fixture.game.threads.all { it.state == 'S' })
}
@Test fun aSuspendedSessionIsPagedOutOnceMemoryRunsShort() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.clock.writeBytes(shift(0L))
fixture.availableWhileSuspendedKb = 8_000_000L
fixture.controller.freeze(pageOut = true) { assertTrue(it) }
fixture.now += 60_000L
fixture.availableWhileSuspendedKb = 3_000_000L
fixture.sync()
val before = fixture.signals.size
fixture.runScheduled()
val relieved = fixture.signals.drop(before)
assertEquals(listOf(GAME), relieved.filter { it.signal == URG }.map { it.pid })
assertTrue(relieved.indexOfFirst { it.signal == CONT } < relieved.indexOfFirst { it.signal == URG })
assertTrue(relieved.indexOfFirst { it.signal == URG } < relieved.indexOfLast { it.signal == STOP })
assertEquals(60_000L * 1_000_000L, fixture.clockAtContinue)
assertEquals(listOf(Triple(1, 1_000_000L, 3_000_000L)), fixture.pagedOut)
assertTrue(fixture.game.threads.all { it.state == 't' })
assertEquals(1, fixture.audioSuspends)
assertEquals(0, fixture.audioResumes)
assertTrue(fixture.scheduled.isEmpty())
fixture.controller.resume { assertTrue(it) }
assertEquals(listOf(Triple(1, 0L, 3_000_000L)), fixture.pagedIn)
assertTrue(fixture.game.threads.all { it.state == 'S' })
}
@Test fun anUnsettledStopAfterADeferredPageOutIsRetriedUntilTheSessionStops() {
val fixture = fixture(17)
fixture.control.writeText("0")
val results = mutableListOf<Boolean>()
fixture.availableWhileSuspendedKb = 8_000_000L
fixture.controller.freeze(pageOut = true) { results += it }
fixture.availableWhileSuspendedKb = 3_000_000L
fixture.neverStop = true
fixture.sync()
fixture.runScheduled()
assertEquals(listOf(1), fixture.pagedOut.map { it.first })
assertEquals('T', fixture.root.threads.single().state)
assertEquals('S', fixture.game.threads.last().state)
assertEquals(listOf(10_000L), fixture.scheduled.map { it.first })
fixture.runScheduled()
assertEquals('S', fixture.game.threads.last().state)
assertEquals(1, fixture.scheduled.size)
fixture.neverStop = false
val before = fixture.signals.size
fixture.runScheduled()
assertFalse(fixture.signals.drop(before).any { it.signal == CONT || it.signal == URG })
assertTrue(fixture.game.threads.all { it.state == 't' })
assertTrue(fixture.scheduled.isEmpty())
assertEquals(listOf(true), results)
assertEquals(1, fixture.audioSuspends)
assertEquals(0, fixture.audioResumes)
assertEquals(listOf(1), fixture.pagedOut.map { it.first })
fixture.controller.resume { assertTrue(it) }
assertEquals(listOf(1), fixture.pagedIn.map { it.first })
assertTrue(fixture.game.threads.all { it.state == 'S' })
}
@Test fun aResumeEndsTheRetriedStop() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.availableWhileSuspendedKb = 8_000_000L
fixture.controller.freeze(pageOut = true) { assertTrue(it) }
fixture.availableWhileSuspendedKb = 3_000_000L
fixture.neverStop = true
fixture.sync()
fixture.runScheduled()
assertEquals(1, fixture.scheduled.size)
fixture.controller.resume { assertTrue(it) }
val before = fixture.signals.size
fixture.runScheduled()
assertFalse(fixture.signals.drop(before).any { it.signal == STOP })
assertTrue(fixture.scheduled.isEmpty())
assertTrue(fixture.game.threads.all { it.state == 'S' })
}
@Test fun aResumeEndsThePageOutChecks() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.availableWhileSuspendedKb = 8_000_000L
val executor = QueueExecutor()
val queued = fixture(17, executor).apply {
control.writeText("0")
availableWhileSuspendedKb = 8_000_000L
}
fixture.controller.freeze(pageOut = true) { assertTrue(it) }
fixture.controller.resume { assertTrue(it) }
fixture.availableWhileSuspendedKb = 1_000_000L
fixture.availableKb = 1_000_000L
fixture.sync()
fixture.runScheduled()
assertFalse(fixture.signals.any { it.signal == URG })
queued.controller.freeze(pageOut = true) { assertTrue(it) }
executor.drain()
queued.availableWhileSuspendedKb = 1_000_000L
queued.sync()
queued.runScheduled()
queued.controller.resume { assertTrue(it) }
executor.drain()
assertFalse(queued.signals.any { it.signal == URG })
assertTrue(queued.game.threads.all { it.state == 'S' })
}
@Test fun noReadBackAfterAFreezeWithoutPageOut() {
@@ -191,6 +317,61 @@ class SessionSuspendControllerTest {
assertEquals(listOf(Triple(0, 3_000_000L, 3_000_000L)), fixture.pagedIn)
}
@Test fun readBackTakesTheLargestProcessesThatFitTheAvailableMemory() {
val fixture = fixture(17)
fixture.addService(2_000_000L)
fixture.control.writeText("0")
fixture.availableKb = 7_000_000L
fixture.controller.freeze(pageOut = true) { assertTrue(it) }
assertEquals(2, fixture.pagedOut.single().first)
val before = fixture.signals.size
fixture.controller.resume { assertTrue(it) }
assertEquals(listOf(GAME), fixture.signals.drop(before).filter { it.signal == URG }.map { it.pid })
assertEquals(listOf(Triple(1, 1_000_000L, 4_000_000L)), fixture.pagedIn)
assertEquals(0L, fixture.swapKb(GAME))
assertEquals(1_000_000L, fixture.swapKb(SERVICE))
}
@Test fun aProcessTooLargeForTheBudgetDoesNotBlockTheOthers() {
val fixture = fixture(17)
fixture.addService(2_000_000L)
fixture.control.writeText("0")
fixture.availableKb = 5_000_000L
fixture.controller.freeze(pageOut = true) { assertTrue(it) }
val before = fixture.signals.size
fixture.controller.resume { assertTrue(it) }
assertEquals(listOf(SERVICE), fixture.signals.drop(before).filter { it.signal == URG }.map { it.pid })
assertEquals(listOf<String?>("1", "1", "0"), fixture.held)
assertEquals(listOf(Triple(1, 3_000_000L, 4_000_000L)), fixture.pagedIn)
assertEquals(3_000_000L, fixture.swapKb(GAME))
assertEquals(0L, fixture.swapKb(SERVICE))
}
@Test fun aPendingPageOutRequestOfAProcessLeftOutDoesNotReadItBack() {
val fixture = fixture(17)
fixture.addService(2_000_000L)
fixture.control.writeText("0")
fixture.availableKb = 5_000_000L
fixture.controller.freeze(pageOut = true) { assertTrue(it) }
fixture.lateRequest = GAME
fixture.controller.resume { assertTrue(it) }
assertNull(fixture.lateRequest)
assertEquals(3_000_000L, fixture.swapKb(GAME))
assertEquals(0L, fixture.swapKb(SERVICE))
assertEquals(listOf(Triple(1, 3_000_000L, 4_000_000L)), fixture.pagedIn)
}
@Test fun everyPagedOutProcessIsReadBackWhenMemoryAllows() {
val fixture = fixture(17)
fixture.addService(2_000_000L)
fixture.control.writeText("0")
fixture.controller.freeze(pageOut = true) { assertTrue(it) }
val before = fixture.signals.size
fixture.controller.resume { assertTrue(it) }
assertEquals(setOf(GAME, SERVICE), fixture.signals.drop(before).filter { it.signal == URG }.map { it.pid }.toSet())
assertEquals(listOf(Triple(2, 0L, 4_000_000L)), fixture.pagedIn)
}
@Test fun cancelledFreezeReadsBackWhatThePageOutAlreadyMoved() {
val fixture = fixture(17)
fixture.control.writeText("0")
@@ -488,6 +669,7 @@ class SessionSuspendControllerTest {
private data class Task(val tid: Int, var started: Long, var state: Char, var cpu: Long = 0)
private data class Group(val pid: Int, var parent: Int, var tracer: Int, val threads: MutableList<Task>)
private data class SentSignal(val pid: Int, val signal: Int)
private class Paging(var resident: Long, var swap: Long = 0L, var out: Boolean = false, var into: Boolean = false)
private class Fixture(val proc: File, tmp: File, count: Int, executor: QueueExecutor) {
val root = Group(ROOT, 9000, 0, mutableListOf(Task(ROOT, 1000, 'S')))
@@ -496,6 +678,8 @@ class SessionSuspendControllerTest {
val helpers = mutableListOf<Int>()
val signals = mutableListOf<SentSignal>()
val held = mutableListOf<String?>()
val shared = mutableListOf<String?>()
var lateRequest: Int? = null
var rootPid = ROOT
var now = 0L
var audioSuspends = 0
@@ -514,17 +698,16 @@ class SessionSuspendControllerTest {
val pagedOut = mutableListOf<Triple<Int, Long, Long>>()
val pagedIn = mutableListOf<Triple<Int, Long, Long>>()
var availableKb = 8_000_000L
var availableWhileSuspendedKb = 2_000_000L
var totalKb = 16_000_000L
private var gameResidentKb = 4_000_000L
private var gameSwapKb = 0L
private var pagingOut = false
private var pagingIn = false
val scheduled = mutableListOf<Pair<Long, () -> Unit>>()
private val paging = linkedMapOf(GAME to Paging(4_000_000L))
var unacknowledged = -1
var handlerStalls = false
var handlerReplaced = false
private var continuing = false
val controller = SessionSuspendController(
{ rootPid }, { helpers }, { audioSuspends++ }, { audioResumes++ },
{ rootPid }, { helpers }, { audioSuspends++; meminfo() }, { audioResumes++; meminfo() },
proc, ::signal, ::threadSignal, ::sleep, { now }, executor,
zramControl = control,
clockControl = clock,
@@ -535,14 +718,32 @@ class SessionSuspendControllerTest {
this.unacknowledged = unacknowledged
},
pagedIn = { processes, swap, swapBefore, _, _ -> pagedIn += Triple(processes, swap, swapBefore) },
schedule = { delay, task -> scheduled += delay to task },
)
init { sync() }
fun addService(residentKb: Long) {
groups += Group(SERVICE, ROOT, 0, mutableListOf(Task(SERVICE, 3000, 'S')))
paging[SERVICE] = Paging(residentKb)
sync()
}
fun swapKb(pid: Int) = paging.getValue(pid).swap
fun runScheduled() {
val tasks = scheduled.toList()
scheduled.clear()
tasks.forEach { it.second() }
}
private fun signal(pid: Int, signal: Int) {
signals += SentSignal(pid, signal)
val request = if (signal == URG) File(control.parentFile, "${control.name}.hold").takeIf { it.isFile }?.readText() else null
if (signal == URG) held += request
val request = if (signal == URG) request(pid) else null
if (signal == URG) {
held += request
shared += sharedHold().takeIf { it.isFile }?.readText()
}
val group = groups.first { it.pid == pid }
if (signal == STOP) {
continuing = false
@@ -551,7 +752,7 @@ class SessionSuspendControllerTest {
it.state !in listOf('T', 't', 'Z', 'X') && !(neverStop && it == game.threads.last())
}?.state = 't'
} else if (signal == URG) {
if (request == "0") { pagingOut = false; pagingIn = true } else pagingOut = true
take(pid, request)
} else if (signal == CONT) {
if (clockAtContinue == null && clock.isFile) {
clockAtContinue = ByteBuffer.wrap(clock.readBytes()).order(ByteOrder.LITTLE_ENDIAN).long
@@ -562,6 +763,20 @@ class SessionSuspendControllerTest {
sync()
}
private fun sharedHold() = File(control.parentFile, "${control.name}.hold")
private fun request(pid: Int): String? =
File(control.parentFile, "${control.name}.hold.$pid").takeIf { it.isFile }?.readText()
?: sharedHold().takeIf { it.isFile }?.readText()
private fun take(pid: Int, request: String?) {
val memory = paging.getValue(pid)
when (request) {
"0" -> { memory.out = false; memory.into = true }
"1", null -> memory.out = true
}
}
private fun threadSignal(pid: Int, tid: Int, signal: Int) {
signals += SentSignal(pid, signal)
val task = groups.first { it.pid == pid }.threads.first { it.tid == tid }
@@ -573,23 +788,29 @@ class SessionSuspendControllerTest {
private fun sleep(millis: Long) {
now += millis
if (pagingOut && !handlerReplaced) {
File(control.parentFile, "${control.name}.ack.$GAME").apply { if (!exists()) writeText("") }
lateRequest?.takeIf { sharedHold().isFile }?.let { pid ->
lateRequest = null
take(pid, request(pid))
}
if (pagingOut && !handlerStalls && !handlerReplaced) {
if (gameResidentKb > 1_000_000L) {
gameResidentKb -= 1_000_000L
gameSwapKb += 1_000_000L
} else {
File(control.parentFile, "${control.name}.ack.$GAME").writeText("1")
pagingOut = false
for ((pid, memory) in paging) {
if (memory.out && !handlerReplaced) {
File(control.parentFile, "${control.name}.ack.$pid").apply { if (!exists()) writeText("") }
}
if (memory.out && !handlerStalls && !handlerReplaced) {
if (memory.resident > 1_000_000L) {
memory.resident -= 1_000_000L
memory.swap += 1_000_000L
} else {
File(control.parentFile, "${control.name}.ack.$pid").writeText("1")
memory.out = false
}
}
if (memory.into) {
val moved = minOf(memory.swap, 1_000_000L)
memory.swap -= moved
memory.resident += moved
if (memory.swap == 0L) memory.into = false
}
}
if (pagingIn) {
val moved = minOf(gameSwapKb, 1_000_000L)
gameSwapKb -= moved
gameResidentKb += moved
if (gameSwapKb == 0L) pagingIn = false
}
if (root.threads.first().state != 'T' && !continuing) game.threads.forEach {
if (it.state != 'Z') { it.state = 'S'; it.cpu++ }
@@ -598,8 +819,13 @@ class SessionSuspendControllerTest {
sync()
}
private fun meminfo() {
val available = if (audioSuspends > audioResumes) availableWhileSuspendedKb else availableKb
File(proc, "meminfo").writeText("MemTotal:\t$totalKb kB\nMemFree:\t1000 kB\nMemAvailable:\t$available kB\n")
}
fun sync() {
File(proc, "meminfo").writeText("MemTotal:\t$totalKb kB\nMemFree:\t1000 kB\nMemAvailable:\t$availableKb kB\n")
meminfo()
for (group in groups) {
val dir = File(proc, group.pid.toString())
if (group == root && rootGone) { dir.deleteRecursively(); continue }
@@ -607,11 +833,12 @@ class SessionSuspendControllerTest {
val stat = File(dir, "stat")
if (group == game && missingGameStat) stat.delete()
else stat.writeText(stat(group, group.threads.first()))
val memory = paging[group.pid]
File(dir, "status").writeText(
"TracerPid: ${group.tracer}\n" +
if (group == game) "VmRSS:\t$gameResidentKb kB\nVmSwap:\t$gameSwapKb kB\n" else "",
if (memory != null) "VmRSS:\t${memory.resident} kB\nVmSwap:\t${memory.swap} kB\n" else "",
)
if (group == game) File(dir, "maps").writeText("7f00000000-7f00001000 r-xp 00000000 fe:05 42 /usr/local/lib/libddsession.so\n")
if (memory != null) File(dir, "maps").writeText("7f00000000-7f00001000 r-xp 00000000 fe:05 42 /usr/local/lib/libddsession.so\n")
val taskDir = File(dir, "task")
if (group == game && missingGameTasks) { taskDir.deleteRecursively(); continue }
taskDir.mkdirs()
@@ -658,6 +885,7 @@ class SessionSuspendControllerTest {
private companion object {
const val ROOT = 100
const val GAME = 200
const val SERVICE = 300
const val STOP = 19
const val CONT = 18
const val URG = 23
@@ -31,8 +31,7 @@ class BattleNetRequestTest {
BattleNetClient.request(root, listOf("launch", "WTCG"))
java.io.File(root, "battlenet-request").writeText("launch\nPro\n")
java.io.File(root, "battlenet-request.1.tmp").writeText("launch\nPro\n")
java.io.File(root, "battlenet-fex.request").writeText("x")
BattleNetClient.clearRequests(root)
assertEquals(listOf("battlenet-fex.request"), root.list()!!.toList())
assertEquals(0, root.list()!!.size)
}
}
@@ -522,6 +522,64 @@ class InputSettingsTest {
}
}
@Test fun buttonSizeShowsTheGamepadWhereItWillBeSaved() {
val library = InputLibraries.read(context)
val layout = library.layout("game", InputRole.PRIMARY)!!
assertEquals(InputLibraries.OVERLAY, layout.id)
val round = mutableStateOf(0)
compose.setContent { DroidDeckTheme { androidx.compose.runtime.key(round.value) { InputSurfaceDialog("game", {}, {}, role = InputRole.PRIMARY,
layoutId = layout.id, bindingsId = library.profile("game").binding(InputRole.PRIMARY)) } } }
fun editor() = generateSequence(listOf<android.view.View>(ShadowDialog.getLatestDialog().window!!.decorView)) { views ->
views.filterIsInstance<android.view.ViewGroup>().flatMap { g -> (0 until g.childCount).map(g::getChildAt) }.ifEmpty { null }
}.flatten().filterIsInstance<InputSurfaceEditorView>().first()
val stock = compose.runOnIdle { editor().rendered() }
compose.onNodeWithTag("input-editor-tools").performClick()
compose.onNodeWithTag("input-editor-scale").performScrollTo().performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.SetProgress) { it(95f) }
val scaled = compose.runOnIdle { editor().rendered() }
assertNotEquals(stock, scaled)
compose.onNodeWithText(context.getString(R.string.input_editor_done)).performScrollTo().performClick()
compose.runOnIdle { assertEquals(.95f, InputLibraries.read(context).layouts.first { it.id == layout.id }.scale) }
compose.runOnIdle { round.value = 1 }
compose.runOnIdle { assertEquals(scaled, editor().rendered()) }
}
@Test @Config(qualifiers = "w468dp-h833dp-port-369dpi")
fun buttonSizeInPortraitKeepsLandscapeEditsWithoutARotatedFrame() {
val face = setOf("legacy:a", "legacy:b", "legacy:x", "legacy:y")
val gamepad = InputLibraries.read(context).layout("game", InputRole.PRIMARY)!!
val landscape = gamepad.copy(elements = gamepad.elements.map { if (it.id in face) it.copy(x = it.x + .012f, y = it.y + .017f) else it },
aspect = 1600f / 900f, rotated = emptyList(), rotatedAspect = 0f)
InputLibraries.update(context) { it.withLayout(landscape) }
val library = InputLibraries.read(context)
val round = mutableStateOf(0)
compose.setContent { DroidDeckTheme { androidx.compose.runtime.key(round.value) { InputSurfaceDialog("game", {}, {}, role = InputRole.PRIMARY,
layoutId = landscape.id, bindingsId = library.profile("game").binding(InputRole.PRIMARY)) } } }
compose.onNodeWithTag("input-editor-tools").performClick()
compose.onNodeWithTag("input-editor-scale").performScrollTo().performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.SetProgress) { it(90f) }
compose.onNodeWithText(context.getString(R.string.input_editor_done)).performScrollTo().performClick()
compose.runOnIdle {
val saved = InputLibraries.read(context).layouts.first { it.id == landscape.id }
assertEquals(landscape.aspect, saved.aspect)
for (id in face) assertEquals(landscape.elements.first { it.id == id }.let { it.x to it.y }, saved.elements.first { it.id == id }.let { it.x to it.y })
assertTrue(saved.rotated.isNotEmpty() && saved.rotatedAspect < 1f)
assertEquals(landscape.scale, saved.scale)
assertEquals(.9f, saved.rotatedScale)
assertEquals(.9f, OnScreenLayout.oriented(saved, 900, 1600).scale)
assertEquals(landscape.scale, OnScreenLayout.oriented(saved, 1600, 900).scale)
}
compose.runOnIdle { round.value = 1 }
compose.onNodeWithTag("input-editor-tools").performClick()
val slider = compose.onNodeWithTag("input-editor-scale").performScrollTo()
assertEquals(90f, slider.fetchSemanticsNode().config[androidx.compose.ui.semantics.SemanticsProperties.ProgressBarRangeInfo].current, .5f)
slider.performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.SetProgress) { it(80f) }
compose.onNodeWithText(context.getString(R.string.input_editor_done)).performScrollTo().performClick()
compose.runOnIdle {
val saved = InputLibraries.read(context).layouts.first { it.id == landscape.id }
assertEquals(landscape.scale, saved.scale)
assertEquals(.8f, saved.rotatedScale)
}
}
@Test @Config(qualifiers = "w833dp-h468dp-land-369dpi")
fun buttonSizeKeepsMovedGamepadGroupsInShape() {
val face = setOf("legacy:a", "legacy:b", "legacy:x", "legacy:y")
@@ -1,15 +1,29 @@
package com.droiddeck.launcher.ui
import android.content.Context
import android.view.InputDevice
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import com.droiddeck.launcher.input.InputControl
import com.droiddeck.launcher.input.InputLibraries
import com.droiddeck.launcher.input.InputSurfaceElement
import com.droiddeck.launcher.input.OnScreenLayout
import com.droiddeck.launcher.input.PadKit
import com.droiddeck.launcher.input.SavedInputLayout
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@@ -18,8 +32,17 @@ class InputSurfaceEditorViewTest {
private val context get() = RuntimeEnvironment.getApplication()
private val layout = SavedInputLayout("custom", "Custom", listOf(InputSurfaceElement(InputControl.A, .1f, .2f, .2f, .2f)), aspect = 2f)
@Before fun reset() {
for (name in listOf("input-profiles", "input-surfaces", "controller", "session")) context.getSharedPreferences(name, Context.MODE_PRIVATE).edit().clear().commit()
}
@After fun restoreSession() {
SessionState.deckPad = false
SessionState.mode = SessionService.MODE_STEAM
}
private fun view() = InputSurfaceEditorView(context).apply {
layout(0, 0, 1000, 1000)
place(1000, 1000)
sourceLayout = layout
aspect = layout.aspect
elements = layout.elements
@@ -27,13 +50,47 @@ class InputSurfaceEditorViewTest {
}
private fun center() = OnScreenLayout.editorElements(context, layout, 1000, 1000).first().let { (it.x + it.width / 2) * 1000 to (it.y + it.height / 2) * 1000 }
@Suppress("UNCHECKED_CAST")
private fun InputSurfaceEditorView.rendered() = javaClass.getDeclaredField("visibleElements").also { it.isAccessible = true }.get(this) as List<InputSurfaceElement>
private fun overlay() = InputLibraries.read(context).layouts.first { it.id == InputLibraries.OVERLAY }
private fun editor(layout: SavedInputLayout, w: Int, h: Int) = InputSurfaceEditorView(context).apply {
sourceLayout = layout
aspect = layout.aspect
elements = layout.elements
snap = false
place(w, h)
}
private fun field(target: Any, name: String) = target.javaClass.getDeclaredField(name).also { it.isAccessible = true }.get(target)
private fun InputSurfaceEditorView.controls() = (field(field(this, "preview")!!, "customCanvas") as ViewGroup).let { canvas -> (0 until canvas.childCount).map(canvas::getChildAt) }
private fun InputSurfaceEditorView.artworkDpad() = field(field(this, "preview")!!, "artworkDpad") as List<*>
private fun InputSurfaceEditorView.rects() = controls().map { listOf(it.left, it.top, it.width, it.height) }
private fun InputSurfaceEditorView.assertControlsDrawnWhereDisplayed() {
val shown = rendered()
val views = controls()
assertEquals(shown.size, views.size)
for ((e, v) in shown.zip(views)) {
assertEquals(e.id, e.x * width, v.left.toFloat(), 1f)
assertEquals(e.id, e.y * height, v.top.toFloat(), 1f)
assertEquals(e.id, e.width * width, v.width.toFloat(), 1f)
assertEquals(e.id, e.height * height, v.height.toFloat(), 1f)
}
}
private fun InputSurfaceEditorView.touch(action: Int, x: Float, y: Float) {
MotionEvent.obtain(0, 10, action, x, y, 0).also { onTouchEvent(it); it.recycle() }
}
private fun InputSurfaceEditorView.mouse(action: Int, x: Float, y: Float) {
val properties = MotionEvent.PointerProperties().apply { id = 0; toolType = MotionEvent.TOOL_TYPE_MOUSE }
val coords = MotionEvent.PointerCoords().apply { this.x = x; this.y = y; pressure = 1f }
val buttons = if (action == MotionEvent.ACTION_UP) 0 else MotionEvent.BUTTON_PRIMARY
MotionEvent.obtain(0, 10, action, 1, arrayOf(properties), arrayOf(coords), 0, buttons, 1f, 1f, 0, 0, InputDevice.SOURCE_MOUSE, 0)
.also { dispatchTouchEvent(it); it.recycle() }
}
private fun InputSurfaceEditorView.centre(id: String) = rendered().first { it.id == id }.let { (it.x + it.width / 2) * width to (it.y + it.height / 2) * height }
@Test fun editingStartsInTheDisplayedFrame() {
val view = view()
var started: Pair<List<InputSurfaceElement>, Float>? = null
@@ -70,7 +127,112 @@ class InputSurfaceEditorViewTest {
view.elements = renamed
view.aspect = 2f
assertEquals(OnScreenLayout.editorElements(context, layout.copy(elements = renamed, aspect = 2f), 1000, 1000), view.rendered())
view.layout(0, 0, 800, 1000)
view.place(800, 1000)
assertEquals(OnScreenLayout.editorElements(context, layout.copy(elements = renamed, aspect = 2f), 800, 1000), view.rendered())
}
@Test fun theOverlayEditorDrawsTheKitArtworkWhereTheSessionPlacesIt() {
val layout = overlay()
assertNotNull(PadKit.forOverlay(context, layout))
val view = editor(layout, 2400, 1504)
assertEquals(OnScreenLayout.editorElements(context, layout, 2400, 1504), view.rendered())
view.assertControlsDrawnWhereDisplayed()
assertEquals(4, view.artworkDpad().size)
}
@Config(qualifiers = "xhdpi")
@Test fun controlsAddedForTheScreenAreDrawnOnTheFirstFrameInBothOrientations() {
SessionState.mode = SessionService.MODE_STEAM
SessionState.deckPad = true
SessionPrefs.setOscRearButtons(context, true)
SessionPrefs.setOscTrackpads(context, true)
val layout = overlay()
for ((w, h) in listOf(2400 to 1504, 1504 to 2400)) {
val view = editor(layout, w, h)
assertTrue(view.rendered().size > layout.elements.size)
view.assertControlsDrawnWhereDisplayed()
assertEquals(4, view.artworkDpad().size)
}
}
@Test fun displayedControlsStayPutAcrossRepeatedRefreshesAndResizes() {
val view = editor(overlay(), 2400, 1504)
val first = view.rendered()
val drawn = view.rects()
repeat(3) {
view.elements = view.elements
view.aspect = view.aspect
view.sourceLayout = view.sourceLayout
view.place(1504, 2400)
view.assertControlsDrawnWhereDisplayed()
view.place(2400, 1504)
assertEquals(first, view.rendered())
assertEquals(drawn, view.rects())
assertEquals(4, view.artworkDpad().size)
}
}
@Test fun dpadPiecesRedrawWhenTheyLeaveOrRejoinTheKitCross() {
val view = editor(overlay(), 2400, 1504)
val stock = view.rendered()
view.aspect = 2400f / 1504
val pieces = view.controls().filter { (it.tag as InputSurfaceElement).id in setOf("legacy:up", "legacy:right", "legacy:down", "legacy:left") }
assertEquals(4, pieces.size)
for ((moved, expected) in listOf(stock.map { if (it.id == "legacy:up") it.copy(y = it.y - .2f) else it } to 0, stock to 4)) {
pieces.forEach { shadowOf(it).clearWasInvalidated() }
view.elements = moved
view.place(2400, 1504)
assertEquals(expected, view.artworkDpad().size)
pieces.forEach { assertTrue((it.tag as InputSurfaceElement).id, shadowOf(it).wasInvalidated()) }
}
}
@Test fun draggingMovesTheTouchedControlByTheDragDistance() {
val view = editor(overlay(), 2400, 1504)
val a = view.rendered().first { it.id == "legacy:a" }
val changes = mutableListOf<InputSurfaceElement>()
view.onChange = { changes += it }
val (x, y) = view.centre(a.id)
view.touch(MotionEvent.ACTION_DOWN, x, y)
view.touch(MotionEvent.ACTION_MOVE, x - 240f, y - 150f)
view.touch(MotionEvent.ACTION_UP, x - 240f, y - 150f)
val moved = changes.last()
assertEquals(a.id, moved.id)
assertEquals(a.x - 240f / 2400, moved.x, .0001f)
assertEquals(a.y - 150f / 1504, moved.y, .0001f)
assertEquals(a.width, moved.width, .0001f)
}
@Test fun aMouseSelectsDragsAndResizesLikeATouch() {
val view = editor(overlay(), 2400, 1504)
val a = view.rendered().first { it.id == "legacy:a" }
val changes = mutableListOf<InputSurfaceElement>()
var selection: String? = null
view.onSelect = { selection = it }
view.onChange = { changes += it }
val (x, y) = view.centre(a.id)
view.mouse(MotionEvent.ACTION_DOWN, x, y)
view.mouse(MotionEvent.ACTION_UP, x, y)
assertEquals(a.id, selection)
view.mouse(MotionEvent.ACTION_DOWN, x, y)
view.mouse(MotionEvent.ACTION_MOVE, x - 240f, y)
view.mouse(MotionEvent.ACTION_UP, x - 240f, y)
assertEquals(a.x - 240f / 2400, changes.last().x, .0001f)
val right = (a.x + a.width) * 2400; val bottom = (a.y + a.height) * 1504
view.mouse(MotionEvent.ACTION_DOWN, right, bottom)
view.mouse(MotionEvent.ACTION_MOVE, right + 60f, bottom + 60f)
view.mouse(MotionEvent.ACTION_UP, right + 60f, bottom + 60f)
val resized = changes.last()
assertEquals(a.id, resized.id)
assertEquals(a.width + 60f / 2400, resized.width, .0001f)
assertEquals(a.height + 60f / 1504, resized.height, .0001f)
}
}
internal fun InputSurfaceEditorView.place(w: Int, h: Int) {
measure(View.MeasureSpec.makeMeasureSpec(w, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(h, View.MeasureSpec.EXACTLY))
layout(0, 0, w, h)
}
@Suppress("UNCHECKED_CAST")
internal fun InputSurfaceEditorView.rendered() = javaClass.getDeclaredField("visibleElements").also { it.isAccessible = true }.get(this) as List<InputSurfaceElement>
@@ -29,4 +29,17 @@ class SessionDrawerPageTest {
assertEquals(SessionDrawerPage.SESSION, with.step(SessionDrawerPage.AGENT, 1))
assertFalse(SessionDrawerPage.AGENT in sessionDrawerPages(hasAgent = false))
}
@Test fun arrangeKeepsSavedOrderAndSlotsNewPagesAfterTheirNeighbour() {
val saved = listOf("SESSION", "HUD", "CONTROLLER")
val out = DrawerPages.arrange(saved)
assertEquals(SessionDrawerPage.entries.toSet(), out.toSet())
assertEquals(listOf(SessionDrawerPage.SESSION, SessionDrawerPage.HUD), out.filter { it in setOf(SessionDrawerPage.SESSION, SessionDrawerPage.HUD) })
assertTrue(out.indexOf(SessionDrawerPage.HUD) < out.indexOf(SessionDrawerPage.CONTROLLER))
}
@Test fun sessionPageCannotBeHidden() {
assertFalse(DrawerPages.hideable(SessionDrawerPage.SESSION))
assertTrue(DrawerPages.hideable(SessionDrawerPage.HUD))
}
}
+37 -8
View File
@@ -72,10 +72,13 @@ has waited five seconds in total or six seconds have gone by since it began, is
minute, and a late answer from it is discarded. A process is known by its number and start time, so a new process that got the
number of a skipped one is asked. Processes with less
than 8 MiB of anonymous memory are skipped. While the app pages the session out for suspend, or
reads it back on resume, it holds the monitor off with `/tmp/.dd-zram.hold` and writes its own
request (`1` to page out, `0` to read back) into that file. A signalled process reads the hold
file first and the control file only when the hold file is missing or empty, so a trim request
the monitor wrote at the same moment cannot replace the app's. The suspend page-out answers `1`
reads it back on resume, it holds the monitor off with `/tmp/.dd-zram.hold`. A page-out writes
`1` into that file. A read-back writes `2 0`, which asks for nothing, and puts `0` into
`/tmp/.dd-zram.hold.<pid>` for each process it chose. A signalled process reads its own hold file
first, then the shared one, and the control file only when both are missing or empty. A trim
request the monitor wrote at the same moment cannot replace the app's, and a process that was
not chosen does not read back, even if it only now starts the page-out request it was sent
before the suspend. The suspend page-out answers `1`
in `/tmp/.dd-zram.ack.<pid>` and a trim answers its kB in `/tmp/.dd-zram.trim.<pid>`, so the
monitor never removes or reads an answer the app is waiting for, and the app never takes a
trim's answer for its own. A trim budget smaller than a chunk covers the stretch of the chunk
@@ -99,10 +102,16 @@ available.
## Threads
Page-out never runs on a thread of the game. The preload's signal handler only wakes its
`zr-worker` thread, which does the `madvise` calls. A forked process
without a worker trims inline in steps of at most 32 MiB per request and looks at no more
than 512 MiB of its address space each time. The page-out for a suspend and the read-back
When a worker can be started, page-out runs outside the game's threads. The preload's signal
handler starts a `zr-worker` thread for the request, which does the `madvise` calls and exits once no request
is left, so a process that is not paging out has no thread the preload added. Programs that
check they are single-threaded before they fork or call `unshare(CLONE_NEWUSER)`, such as
Chromium's zygote, keep working. The worker is a bare `clone` with the flags of a normal
thread, on a stack the preload maps itself, and makes only raw system calls, so starting it
from the signal handler is safe and seccomp filters that only allow thread clones accept it. A
process that has a single thread, or whose signalled thread added a seccomp filter after the
process started, as browser sandboxes do, gets no worker. When there is no worker, the process trims inline in steps of at most 32 MiB per request and
looks at no more than 512 MiB of its address space each time. The page-out for a suspend and the read-back
after it are not limited there: they run once, while the process is being stopped or
started, and cover all of it. The monitor is a
shell loop in the session, outside every game process.
@@ -150,6 +159,26 @@ Without root an app cannot write its memory cgroup's `memory.reclaim` (owned by
and KGSL's per-process GPU reclaim `state` is root-only. Page-out therefore runs inside each
process through the preload, and GPU memory itself cannot be compressed from userspace.
## Page-out and read-back around a suspend
A hidden or screen-off suspend stops the session at once. It pages the session out first only
when `MemAvailable` is below twice the reserve, the larger of 1 GiB and a tenth of RAM. Otherwise
the session stays resident while it is stopped, and every ten seconds of uptime the app reads
`MemAvailable` again. Once it falls below that level, the app moves the guest clock forward by
the stopped time, continues the session with audio still suspended, pages it out and stops it
again. If the session does not settle in that stop, the app stops it again every ten seconds
until it does, so it stays suspended as the service reports. A resume ends the checks and the
retries and cuts a running page-out short. A short screen-off with memory
to spare therefore moves nothing into zram, and nothing has to come back when the screen turns on.
Getting it back costs much more on some phones than on others: after a 12 s screen-off a Poco F7
read 690 MB back in 6.7 s while the phone was waking up.
After the resume, the processes that were paged out are read back largest first, as long as
their swap fits the budget: half of `MemAvailable`, while leaving the reserve available.
Only the chosen processes get a read-back request. Processes that do not fit keep their memory
in zram and fault it back on demand, so one large process no longer stops the read-back of every
other one.
## CRAM and the bounded pager experiment
[Meta's CRAM proposal](https://lpc.events/event/20/contributions/2424/) uses memory compression
+1
View File
@@ -44,6 +44,7 @@ Links of the form `droiddeck://settings/<section>` open a Settings section direc
| Launcher orientation | Settings › Launcher (`droiddeck://settings/launcher`) | rotate, portrait |
| Session orientation | Settings › Launcher (`droiddeck://settings/launcher`) | rotate, portrait |
| Fullscreen | Settings › Launcher (`droiddeck://settings/launcher`) | |
| Controller haptics | Settings › Launcher (`droiddeck://settings/launcher`) | vibration, rumble |
| Dual screen launcher | Settings › Launcher (`droiddeck://settings/launcher`) | thor, second screen, bottom screen |
| Warn when storage is low | Settings › Launcher (`droiddeck://settings/launcher`) | |
| SteamGridDB API key | Settings › Launcher (`droiddeck://settings/launcher`) | artwork, steamgriddb |
+17 -5
View File
@@ -171,12 +171,20 @@ x86_key=$(inputs_hash bullseye tools/linuxfs/build-x86-preloads.sh tools/linuxfs
app/src/main/cpp/fakeinput_steam.cpp)
x86_stage="${staging_dir}/x86-preloads"
if restore_step x86-preloads "${x86_key}" "${linuxfs_dir}"; then :; else
docker run --rm --platform linux/amd64 \
x86_platform=linux/amd64
x86_packages="gcc g++ gcc-multilib g++-multilib binutils"
x86_cross=0
if [[ "${docker_platform}" == linux/arm64 ]]; then
x86_platform=linux/arm64
x86_packages="gcc-x86-64-linux-gnu g++-x86-64-linux-gnu gcc-i686-linux-gnu g++-i686-linux-gnu libc6-dev-amd64-cross libc6-dev-i386-cross binutils-x86-64-linux-gnu binutils-i686-linux-gnu"
x86_cross=1
fi
docker run --rm --platform "${x86_platform}" -e X86_CROSS="${x86_cross}" -e X86_PACKAGES="${x86_packages}" \
-v "${repo_root}:/src" -v "${git_common}:${git_common}" -w /src public.ecr.aws/docker/library/debian:bullseye bash -c '
set -euo pipefail
printf "deb http://archive.debian.org/debian bullseye main\ndeb http://archive.debian.org/debian-security bullseye-security main\n" > /etc/apt/sources.list
apt-get -o Acquire::Check-Valid-Until=false update -qq
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends gcc g++ gcc-multilib g++-multilib binutils >/dev/null
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends $X86_PACKAGES >/dev/null
tools/linuxfs/build-x86-preloads.sh app/src/main/assets/linuxfs
chown -R '"$(id -u):$(id -g)"' app/src/main/assets/linuxfs
'
@@ -436,8 +444,12 @@ if [[ "${DROIDDECK_SKIP_RUST:-0}" != 1 ]]; then
rockstar_out="${linuxfs_dir}/usr/local/lib/droiddeck-rockstar"
rockstar_key=$(inputs_hash "windows-gnu" tools/rockstar-launcher/src tools/rockstar-launcher/Cargo.toml tools/rockstar-launcher/Cargo.lock tools/rockstar-launcher/build.sh)
if ! restore_step rockstar "${rockstar_key}" "${rockstar_out}"; then
command -v i686-w64-mingw32-gcc >/dev/null 2>&1 || { echo "i686-w64-mingw32-gcc is required for the Rockstar launcher service." >&2; exit 1; }
CARGO_TARGET_DIR="${cache_dir}/rockstar-target" bash tools/rockstar-launcher/build.sh "${rockstar_out}"
if [[ "$(uname -s)" == Darwin ]]; then
bash tools/rockstar-launcher/build-container.sh "${rockstar_out}"
else
command -v i686-w64-mingw32-gcc >/dev/null 2>&1 || { echo "i686-w64-mingw32-gcc is required for the Rockstar launcher service." >&2; exit 1; }
CARGO_TARGET_DIR="${cache_dir}/rockstar-target" bash tools/rockstar-launcher/build.sh "${rockstar_out}"
fi
save_step rockstar "${rockstar_key}" "${rockstar_out}"
fi
epic_out="${linuxfs_dir}/usr/local/lib/droiddeck-epic"
@@ -473,7 +485,7 @@ readelf_path=$(find "${NDK}/toolchains/llvm/prebuilt" -name llvm-readelf | head
[[ -x "${readelf_path}" ]] || { echo "NDK llvm-readelf is missing" >&2; exit 1; }
stores_check=()
[[ "${DROIDDECK_SKIP_RUST:-0}" != 1 ]] || stores_check+=(--without-stores)
python3 tools/release/check_android_libraries.py "${apk}" --readelf "${readelf_path}" "${stores_check[@]}"
python3 tools/release/check_android_libraries.py "${apk}" --readelf "${readelf_path}" ${stores_check[@]+"${stores_check[@]}"}
git diff --exit-code -- app/src/main/rust/stores/Cargo.lock
build_tools=$(find "${sdk_dir}/build-tools" -mindepth 1 -maxdepth 1 -type d -print | sort -V | tail -1)
+27 -17
View File
@@ -1,26 +1,34 @@
#!/bin/sh
set -eu
out=${1:?usage: build-x86-preloads.sh <linuxfs asset directory>}
tools() {
prefix=
if [ "${X86_CROSS:-}" = 1 ]; then
case $1 in i386) prefix=i686-linux-gnu- ;; *) prefix=x86_64-linux-gnu- ;; esac
fi
GCC=${prefix}gcc GXX=${prefix}g++ STRIP=${prefix}strip OBJDUMP=${prefix}objdump NM=${prefix}nm
}
for arch in x86_64 i386; do
tools $arch
case $arch in
x86_64) bits=-m64 ;;
i386) bits=-m32 ;;
esac
mkdir -p "$out/$arch"
gcc $bits -shared -fPIC -O2 -Wall -pthread \
$GCC $bits -shared -fPIC -O2 -Wall -pthread \
-o "$out/$arch/libddsession.so" tools/linuxfs/preload/*.c -ldl
g++ $bits -shared -fPIC -O2 -Wall -Wno-attributes -Wno-nonnull-compare \
$GXX $bits -shared -fPIC -O2 -Wall -Wno-attributes -Wno-nonnull-compare \
-pthread -std=c++17 -static-libstdc++ -static-libgcc -Wl,--exclude-libs,ALL \
-o "$out/$arch/libfakeinput.so" app/src/main/cpp/fakeinput_steam.cpp -ldl
strip --strip-unneeded "$out/$arch/libddsession.so" "$out/$arch/libfakeinput.so"
$STRIP --strip-unneeded "$out/$arch/libddsession.so" "$out/$arch/libfakeinput.so"
for lib in "$out/$arch/libddsession.so" "$out/$arch/libfakeinput.so"; do
newest=$(objdump -T "$lib" | grep -o 'GLIBC_2\.[0-9]*' | sort -u -t. -k2,2n | tail -1)
newest=$($OBJDUMP -T "$lib" | grep -o 'GLIBC_2\.[0-9]*' | sort -u -t. -k2,2n | tail -1)
minor=${newest#GLIBC_2.}
if [ "$minor" -gt 31 ]; then
echo "$lib needs $newest; Steam Linux Runtime 3.0 has glibc 2.31" >&2
exit 1
fi
if objdump -p "$lib" | grep -q 'NEEDED.*lib\(stdc++\|gcc_s\)'; then
if $OBJDUMP -p "$lib" | grep -q 'NEEDED.*lib\(stdc++\|gcc_s\)'; then
echo "$lib links the C++ runtime dynamically" >&2
exit 1
fi
@@ -28,37 +36,39 @@ for arch in x86_64 i386; do
done
for target in x86_64/faultreport i386/faultreport; do
arch=${target%/*} name=${target#*/}
tools $arch
case $arch in
x86_64) bits=-m64 ;;
i386) bits=-m32 ;;
esac
lib=$out/$arch/lib$name.so
gcc $bits -shared -fPIC -O2 -Wall -Wextra -nostdlib -fno-stack-protector -fno-builtin -fvisibility=hidden \
$GCC $bits -shared -fPIC -O2 -Wall -Wextra -nostdlib -fno-stack-protector -fno-builtin -fvisibility=hidden \
-o "$lib" tools/linuxfs/fex/$name.c
strip --strip-unneeded "$lib"
if objdump -p "$lib" | grep -q NEEDED || [ -n "$(nm -D --undefined-only "$lib" 2>/dev/null)" ]; then
$STRIP --strip-unneeded "$lib"
if $OBJDUMP -p "$lib" | grep -q NEEDED || [ -n "$($NM -D --undefined-only "$lib" 2>/dev/null)" ]; then
echo "$lib must not need any library" >&2
exit 1
fi
done
tools x86_64
lib=$out/x86_64/libwebkitinput.so
gcc -m64 -shared -fPIC -O2 -Wall -Wextra -nostdlib -fno-stack-protector -fno-builtin -fvisibility=hidden \
$GCC -m64 -shared -fPIC -O2 -Wall -Wextra -nostdlib -fno-stack-protector -fno-builtin -fvisibility=hidden \
-o "$lib" tools/linuxfs/fex/webkitinput.c
strip --strip-unneeded "$lib"
if objdump -p "$lib" | grep -q NEEDED || [ "$(nm -D --undefined-only "$lib" | awk '{print $1 $2}' | LC_ALL=C sort | tr '\n' ' ')" != "wdlsym wg_getenv wg_object_get_data wg_object_set wg_object_set_data wg_type_check_instance_is_a wgtk_container_forall wgtk_container_get_type wgtk_key_snooper_install wgtk_widget_get_toplevel wwebkit_user_script_new wwebkit_user_script_unref wwebkit_web_view_get_type wwebkit_web_view_get_uri wwebkit_web_view_run_javascript " ]; then
$STRIP --strip-unneeded "$lib"
if $OBJDUMP -p "$lib" | grep -q NEEDED || [ "$($NM -D --undefined-only "$lib" | awk '{print $1 $2}' | LC_ALL=C sort | tr '\n' ' ')" != "wdlsym wg_getenv wg_object_get_data wg_object_set wg_object_set_data wg_type_check_instance_is_a wgtk_container_forall wgtk_container_get_type wgtk_key_snooper_install wgtk_widget_get_toplevel wwebkit_user_script_new wwebkit_user_script_unref wwebkit_web_view_get_type wwebkit_web_view_get_uri wwebkit_web_view_run_javascript " ]; then
echo "$lib must need nothing but weak GLib, GTK and WebKit calls" >&2
exit 1
fi
stub=$(mktemp -d)
gcc -m64 -shared -nostdlib -Wl,-soname,/usr/lib/x86_64-linux-gnu/libvulkan.so.1 -o "$stub/libvulkan.so.1" -x c /dev/null
$GCC -m64 -shared -nostdlib -Wl,-soname,/usr/lib/x86_64-linux-gnu/libvulkan.so.1 -o "$stub/libvulkan.so.1" -x c /dev/null
lib=$out/x86_64/libvulkan-thunk.so
gcc -m64 -shared -fPIC -O2 -Wall -Wextra -fvisibility=hidden -Wl,-soname,libvulkan.so.1 -Wl,-z,nodelete -Wl,--no-as-needed \
$GCC -m64 -shared -fPIC -O2 -Wall -Wextra -fvisibility=hidden -Wl,-soname,libvulkan.so.1 -Wl,-z,nodelete -Wl,--no-as-needed \
-o "$lib" tools/linuxfs/fex/vulkanpin.c "$stub/libvulkan.so.1" -ldl
rm -rf "$stub"
strip --strip-unneeded "$lib"
newest=$(objdump -T "$lib" | grep -o 'GLIBC_2\.[0-9]*' | sort -u -t. -k2,2n | tail -1)
if ! objdump -p "$lib" | grep -q 'NEEDED *\/usr/lib/x86_64-linux-gnu/libvulkan\.so\.1$' \
|| ! objdump -p "$lib" | grep -q 'FLAGS_1 *0x0*8$' || [ "${newest#GLIBC_2.}" -gt 31 ]; then
$STRIP --strip-unneeded "$lib"
newest=$($OBJDUMP -T "$lib" | grep -o 'GLIBC_2\.[0-9]*' | sort -u -t. -k2,2n | tail -1)
if ! $OBJDUMP -p "$lib" | grep -q 'NEEDED *\/usr/lib/x86_64-linux-gnu/libvulkan\.so\.1$' \
|| ! $OBJDUMP -p "$lib" | grep -q 'FLAGS_1 *0x0*8$' || [ "${newest#GLIBC_2.}" -gt 31 ]; then
echo "$lib must be nodelete, need the Vulkan thunk and run on glibc 2.31" >&2
exit 1
fi
@@ -37,9 +37,6 @@ USER_PREFERENCES = "UserPreferencesMask"
WINE_USER_PREFERENCES = bytes((0x10, 0x00, 0x00, 0x80, 0x12, 0x00, 0x00, 0x00))
CLIENT_AREA_ANIMATION = (4, 0x02)
WALLPAPER_MAX = (1280, 720)
FEX_REQUEST = "battlenet-fex.request"
FEX_RESULT = "battlenet-fex.result"
FEX_WAIT = 120
START_GRACE = 90
POLL = 2
STOP_WAIT = 5
@@ -779,32 +776,6 @@ def write_menu(path=MENU):
say("menu entry not written: %s" % error)
def ask_fex(launch_dir, wait=FEX_WAIT):
if not launch_dir or not os.path.isdir(launch_dir):
say("not inside a DroidDeck session; FEX stays as Components has it")
return None
result = os.path.join(launch_dir, FEX_RESULT)
request = os.path.join(launch_dir, FEX_REQUEST)
try:
os.unlink(result)
except OSError:
pass
with open(request + ".tmp", "w", encoding="utf-8") as f:
f.write("appid=%s\n" % APP_ID)
os.replace(request + ".tmp", request)
deadline = time.monotonic() + wait
while time.monotonic() < deadline:
try:
with open(result, encoding="utf-8") as f:
answer = f.read().strip()
except OSError:
time.sleep(0.5)
continue
os.unlink(result)
return answer
return None
def wine_processes(pfx, proc="/proc"):
want = os.path.realpath(pfx).rstrip("/")
found = []
@@ -1148,8 +1119,6 @@ def stop_leftovers(pfx):
def open_client(root, reinstall=False):
pfx = os.path.join(prefix(root), "pfx")
write_menu()
answer = ask_fex(os.environ.get("DD_LAUNCH_DIR"))
say("FEX: %s" % (answer or "no answer from the app; Components' choice stays"))
if running(pfx):
say("Battle.net is already running in its prefix; waiting for it to close")
wait_while_open(pfx, grace=0)
@@ -1238,8 +1207,6 @@ def launch(root, code):
try:
own = None
if lock is not None and not running(pfx):
answer = ask_fex(os.environ.get("DD_LAUNCH_DIR"))
say("FEX: %s" % (answer or "no answer from the app; Components' choice stays"))
verb = None if stop_leftovers(pfx) else "run"
configure(root, LIBRARY)
own = start(launcher(root), verb)
@@ -132,7 +132,7 @@ clear_stale_tmp() {
[ -z "${DD_INSIDE:-}" ] && clear_stale_tmp
if [ -z "${DD_INSIDE:-}" ]; then
if [ "${DD_ZRAM:-0}" = 1 ]; then printf 0 > /tmp/.dd-zram; else rm -f /tmp/.dd-zram; fi
rm -f /tmp/.dd-zram.hold
rm -f /tmp/.dd-zram.hold /tmp/.dd-zram.hold.*
dd if=/dev/zero of=/tmp/.dd-clock bs=8 count=1 conv=notrunc status=none
fi
+8
View File
@@ -1045,7 +1045,15 @@ static void *own_udev_symbol(const char *name) {
}
static void *dlvsym_any(const char *name) {
#if defined(__aarch64__)
static const char *versions[] = {"GLIBC_2.17", "GLIBC_2.34"};
#elif defined(__x86_64__)
static const char *versions[] = {"GLIBC_2.2.5", "GLIBC_2.34"};
#elif defined(__i386__)
static const char *versions[] = {"GLIBC_2.0", "GLIBC_2.34"};
#else
static const char *versions[] = {"GLIBC_2.17", "GLIBC_2.2.5", "GLIBC_2.0", "GLIBC_2.34"};
#endif
size_t i;
void *resolved = NULL;
+286 -75
View File
@@ -1,8 +1,9 @@
#define _GNU_SOURCE
#include <dlfcn.h>
#pragma GCC optimize("no-stack-protector", "no-tree-loop-distribute-patterns")
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <sched.h>
#include <signal.h>
#include <stdint.h>
#include <string.h>
@@ -10,6 +11,9 @@
#include <sys/prctl.h>
#include <sys/syscall.h>
#include <sys/uio.h>
#if defined(__i386__)
#include <asm/ldt.h>
#endif
#include <unistd.h>
@@ -31,13 +35,157 @@
#define ZR_INLINE_CHUNKS 512UL
#define ZR_FAILED (~0UL)
#define ZR_FUTEX_WAIT 0
#define ZR_FUTEX_WAKE 1
#define ZR_PATH (sizeof(ZR_CTL) + sizeof(".hold.") + 20)
#define ZR_STACK (128UL << 10)
#define ZR_THREAD (CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_THREAD | CLONE_SYSVSEM | \
CLONE_SETTLS | CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID)
#define ZR_TEXT(x) #x
#define ZR_NR(x) ZR_TEXT(x)
#define ZR_CALL(n, a, b, c, d, e, f, ...) \
zr_call((long)(n), (long)(a), (long)(b), (long)(c), (long)(d), (long)(e), (long)(f))
#define zr_sys(...) ZR_CALL(__VA_ARGS__, 0, 0, 0, 0, 0, 0, 0)
#if defined(__aarch64__)
#define ZR_MMAP SYS_mmap
__asm__(".pushsection .text\n"
".p2align 2\n"
".hidden zr_call\n"
".type zr_call, %function\n"
"zr_call:\n"
" mov x8, x0\n"
" mov x0, x1\n"
" mov x1, x2\n"
" mov x2, x3\n"
" mov x3, x4\n"
" mov x4, x5\n"
" mov x5, x6\n"
" svc #0\n"
" ret\n"
".size zr_call, . - zr_call\n"
".hidden zr_clone\n"
".type zr_clone, %function\n"
"zr_clone:\n"
" mov x5, x2\n"
" mov x2, x3\n"
" mov x3, x4\n"
" mov x4, x5\n"
" mov x8, #" ZR_NR(SYS_clone) "\n"
" svc #0\n"
" cbnz x0, 1f\n"
" mov x29, xzr\n"
" mov x30, xzr\n"
" bl zr_thread\n"
" mov x0, xzr\n"
" mov x8, #" ZR_NR(SYS_exit) "\n"
" svc #0\n"
" brk #0\n"
"1:\n"
" ret\n"
".size zr_clone, . - zr_clone\n"
".popsection\n");
#elif defined(__x86_64__)
#define ZR_MMAP SYS_mmap
__asm__(".pushsection .text\n"
".p2align 4\n"
".hidden zr_call\n"
".type zr_call, @function\n"
"zr_call:\n"
" mov %rdi, %rax\n"
" mov %rsi, %rdi\n"
" mov %rdx, %rsi\n"
" mov %rcx, %rdx\n"
" mov %r8, %r10\n"
" mov %r9, %r8\n"
" mov 8(%rsp), %r9\n"
" syscall\n"
" ret\n"
".size zr_call, . - zr_call\n"
".hidden zr_clone\n"
".type zr_clone, @function\n"
"zr_clone:\n"
" mov %rdx, %r10\n"
" mov %rcx, %rdx\n"
" mov $" ZR_NR(SYS_clone) ", %eax\n"
" syscall\n"
" test %rax, %rax\n"
" jnz 1f\n"
" xor %ebp, %ebp\n"
" call zr_thread\n"
" xor %edi, %edi\n"
" mov $" ZR_NR(SYS_exit) ", %eax\n"
" syscall\n"
" hlt\n"
"1:\n"
" ret\n"
".size zr_clone, . - zr_clone\n"
".popsection\n");
#elif defined(__i386__)
#define ZR_MMAP SYS_mmap2
__asm__(".pushsection .text\n"
".p2align 4\n"
".hidden zr_call\n"
".type zr_call, @function\n"
"zr_call:\n"
" push %ebp\n"
" push %edi\n"
" push %esi\n"
" push %ebx\n"
" mov 20(%esp), %eax\n"
" mov 24(%esp), %ebx\n"
" mov 28(%esp), %ecx\n"
" mov 32(%esp), %edx\n"
" mov 36(%esp), %esi\n"
" mov 40(%esp), %edi\n"
" mov 44(%esp), %ebp\n"
" int $0x80\n"
" pop %ebx\n"
" pop %esi\n"
" pop %edi\n"
" pop %ebp\n"
" ret\n"
".size zr_call, . - zr_call\n"
".hidden zr_clone\n"
".type zr_clone, @function\n"
"zr_clone:\n"
" push %ebx\n"
" push %esi\n"
" push %edi\n"
" mov 16(%esp), %ebx\n"
" mov 20(%esp), %ecx\n"
" mov 24(%esp), %edi\n"
" mov 28(%esp), %edx\n"
" mov 32(%esp), %esi\n"
" mov $" ZR_NR(SYS_clone) ", %eax\n"
" int $0x80\n"
" test %eax, %eax\n"
" jnz 1f\n"
" xor %ebp, %ebp\n"
" call zr_thread\n"
" xor %ebx, %ebx\n"
" mov $" ZR_NR(SYS_exit) ", %eax\n"
" int $0x80\n"
" hlt\n"
"1:\n"
" pop %edi\n"
" pop %esi\n"
" pop %ebx\n"
" ret\n"
".size zr_clone, . - zr_clone\n"
".popsection\n");
#else
#error "zram.c needs a raw system call for this architecture"
#endif
long zr_call(long n, long a, long b, long c, long d, long e, long f) __attribute__((visibility("hidden")));
long zr_clone(long flags, char *stack, int *child, int *parent, void *tls) __attribute__((visibility("hidden")));
void zr_thread(void) __attribute__((visibility("hidden")));
static long (*zr_sys)(long, ...);
static unsigned long zr_page;
static int zr_busy;
static int zr_pending;
static int zr_worker;
static unsigned zr_requests;
static int zr_stack_busy;
static int zr_tid;
static long zr_filters;
static char *zr_stack;
static char zr_maps[8192];
static uint64_t zr_entries[ZR_BATCH];
static struct iovec zr_iov[ZR_BATCH];
@@ -54,24 +202,48 @@ static uint16_t zr_gen = 1;
static unsigned long zr_cursor;
static unsigned long zr_visits;
static int zr_prefix(const char *text, const char *prefix) {
while (*prefix)
if (*text++ != *prefix++) return 0;
return 1;
}
static char *zr_find(char *text, char c, size_t n) {
for (; n > 0; n--, text++)
if (*text == c) return text;
return NULL;
}
static int zr_open(const char *path) {
return (int)zr_sys(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC, 0);
}
static void zr_path(char *path, const char *suffix) {
char digits[20];
size_t n = 0, d = 0;
for (const char *p = ZR_CTL; *p; p++) path[n++] = *p;
for (const char *p = suffix; *p; p++) path[n++] = *p;
long pid = zr_sys(SYS_getpid);
do digits[d++] = (char)('0' + pid % 10); while ((pid /= 10) > 0);
while (d > 0) path[n++] = digits[--d];
path[n] = 0;
}
static long zr_read_text(const char *path, char *text, size_t size) {
int fd = zr_open(path);
if (fd < 0) return 0;
long n = zr_sys(SYS_read, fd, text, size);
zr_sys(SYS_close, fd);
return n;
}
static int zr_mode(unsigned long *want) {
char text[24];
long n = 0;
int fd = zr_open(ZR_CTL ".hold");
if (fd >= 0) {
n = zr_sys(SYS_read, fd, text, sizeof(text));
zr_sys(SYS_close, fd);
}
if (n < 1) {
fd = zr_open(ZR_CTL);
if (fd < 0) return -1;
n = zr_sys(SYS_read, fd, text, sizeof(text));
zr_sys(SYS_close, fd);
}
char own[ZR_PATH];
zr_path(own, ".hold.");
long n = zr_read_text(own, text, sizeof(text));
if (n < 1) n = zr_read_text(ZR_CTL ".hold", text, sizeof(text));
if (n < 1) n = zr_read_text(ZR_CTL, text, sizeof(text));
if (n < 1 || text[0] < '0' || text[0] > '3') return -1;
unsigned long kb = 0;
for (long i = 2; i < n && text[i] >= '0' && text[i] <= '9'; i++)
@@ -103,7 +275,7 @@ static int zr_eligible(const char *line, int compress, unsigned long *start, uns
while (*p && *p != ' ') p++;
while (*p == ' ') p++;
}
return *p == 0 || strncmp(p, "[heap]", 6) == 0 || strncmp(p, "[anon:", 6) == 0;
return *p == 0 || zr_prefix(p, "[heap]") || zr_prefix(p, "[anon:");
}
static void zr_read_back(int pagemap, unsigned long start, unsigned long end) {
@@ -137,7 +309,7 @@ static unsigned long zr_count(int pagemap, unsigned long start, unsigned long en
do {
if (zr_sys(SYS_lseek, pagemap, (long)(start / zr_page * sizeof(uint64_t)), SEEK_SET) < 0) return ZR_FAILED;
got = zr_sys(SYS_read, pagemap, zr_entries, size);
} while (got < 0 && errno == EINTR);
} while (got == -EINTR);
if (got != size) return ZR_FAILED;
for (long i = 0; i < got / (long)sizeof(uint64_t); i++)
if (zr_entries[i] & bit) count++;
@@ -157,8 +329,7 @@ static struct zr_slot *zr_slot(unsigned long addr, int create) {
}
}
if (!create) return NULL;
memset(&zr_slots[home], 0, sizeof(zr_slots[home]));
zr_slots[home].key = key;
zr_slots[home] = (struct zr_slot){.key = key};
return &zr_slots[home];
}
@@ -228,13 +399,13 @@ static unsigned long zr_walk(int mode, unsigned long want, unsigned long lo, uns
size_t have = 0;
while (done < want && zr_visits > 0) {
long n = zr_sys(SYS_read, maps, zr_maps + have, sizeof(zr_maps) - 1 - have);
if (n < 0 && errno == EINTR) continue;
if (n == -EINTR) continue;
if (n <= 0) break;
have += (size_t)n;
zr_maps[have] = 0;
char *line = zr_maps;
char *nl;
while (done < want && zr_visits > 0 && (nl = memchr(line, '\n', have - (size_t)(line - zr_maps))) != NULL) {
while (done < want && zr_visits > 0 && (nl = zr_find(line, '\n', have - (size_t)(line - zr_maps))) != NULL) {
*nl = 0;
unsigned long s, e;
if (zr_eligible(line, mode != 0, &s, &e) && e > s) {
@@ -245,7 +416,7 @@ static unsigned long zr_walk(int mode, unsigned long want, unsigned long lo, uns
line = nl + 1;
}
have -= (size_t)(line - zr_maps);
memmove(zr_maps, line, have);
for (size_t i = 0; i < have; i++) zr_maps[i] = line[i];
if (have == sizeof(zr_maps) - 1) have = 0;
}
if (pagemap >= 0) zr_sys(SYS_close, pagemap);
@@ -254,16 +425,10 @@ static unsigned long zr_walk(int mode, unsigned long want, unsigned long lo, uns
}
static void zr_ack(long value, int trim) {
const char *suffix = trim ? ".trim." : ".ack.";
char path[sizeof(ZR_CTL) + sizeof(".trim.") + 20];
char path[ZR_PATH];
char digits[20];
size_t n = 0, d = 0;
for (const char *p = ZR_CTL; *p; p++) path[n++] = *p;
for (const char *p = suffix; *p; p++) path[n++] = *p;
long pid = zr_sys(SYS_getpid);
do digits[d++] = (char)('0' + pid % 10); while ((pid /= 10) > 0);
while (d > 0) path[n++] = digits[--d];
path[n] = 0;
size_t n, d;
zr_path(path, trim ? ".trim." : ".ack.");
int fd = (int)zr_sys(SYS_openat, AT_FDCWD, path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600);
if (fd < 0) return;
for (d = 0; value >= 0 && (d == 0 || value > 0); value /= 10) digits[d++] = (char)('0' + value % 10);
@@ -291,15 +456,88 @@ static void zr_request(int worker) {
zr_ack((long)(done * (zr_page / 1024)), 1);
}
static void *zr_worker_main(void *unused) {
(void)unused;
prctl(PR_SET_NAME, "zr-worker", 0, 0, 0);
for (;;) {
while (!__atomic_exchange_n(&zr_pending, 0, __ATOMIC_SEQ_CST))
zr_sys(SYS_futex, &zr_pending, ZR_FUTEX_WAIT, 0, NULL, NULL, 0);
zr_request(1);
static void zr_drain(int worker) {
unsigned seen;
do {
seen = __atomic_load_n(&zr_requests, __ATOMIC_ACQUIRE);
zr_request(worker);
} while (!__atomic_compare_exchange_n(&zr_requests, &seen, 0, 0, __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE));
}
void zr_thread(void) {
zr_sys(SYS_prctl, PR_SET_NAME, "zr-worker");
zr_drain(1);
}
static void *zr_tls(void *desc) {
#if defined(__aarch64__)
(void)desc;
return __builtin_thread_pointer();
#elif defined(__x86_64__)
(void)desc;
void *self;
__asm__("mov %%fs:0, %0" : "=r"(self));
return self;
#else
struct user_desc *entry = desc;
unsigned short selector;
__asm__("mov %%gs, %0" : "=r"(selector));
entry->entry_number = selector >> 3;
return zr_sys(SYS_get_thread_area, entry) == 0 ? entry : NULL;
#endif
}
static long zr_field(const char *text, const char *key) {
for (const char *line = text; *line; line++) {
if ((line == text || line[-1] == '\n') && zr_prefix(line, key)) {
long value = 0;
for (const char *k = key; *k; k++) line++;
while (*line == ' ' || *line == '\t') line++;
for (; *line >= '0' && *line <= '9'; line++) value = value * 10 + (*line - '0');
return value;
}
}
return NULL;
return -1;
}
static int zr_status(long *threads, long *filters) {
int fd = zr_open("/proc/thread-self/status");
if (fd < 0) return 0;
long have = 0, n;
while (have < (long)sizeof(zr_maps) - 1 &&
((n = zr_sys(SYS_read, fd, zr_maps + have, sizeof(zr_maps) - 1 - (size_t)have)) > 0 || n == -EINTR))
if (n > 0) have += n;
zr_sys(SYS_close, fd);
zr_maps[have] = 0;
*threads = zr_field(zr_maps, "Threads:");
*filters = zr_field(zr_maps, "Seccomp_filters:");
return have > 0;
}
static int zr_start(void) {
long threads, filters;
if (!zr_status(&threads, &filters) || threads < 2 || filters > zr_filters) return 0;
if (zr_stack == NULL) {
long base = zr_sys(ZR_MMAP, 0, ZR_STACK, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK | MAP_NORESERVE, -1, 0);
if ((unsigned long)base > -4096UL) return 0;
zr_stack = (char *)base;
}
struct { long sec, nsec; } wait = {0, 5000000};
for (int i = 0; i < 20 && __atomic_load_n(&zr_stack_busy, __ATOMIC_ACQUIRE); i++)
zr_sys(SYS_futex, &zr_stack_busy, ZR_FUTEX_WAIT, 1, &wait, NULL, 0);
if (__atomic_load_n(&zr_stack_busy, __ATOMIC_ACQUIRE)) return 0;
uint64_t desc[4] = {0};
void *tls = zr_tls(desc);
if (tls == NULL) return 0;
uint64_t all = ~0ULL, previous;
if (zr_sys(SYS_rt_sigprocmask, SIG_SETMASK, &all, &previous, sizeof(all)) != 0) return 0;
__atomic_store_n(&zr_stack_busy, 1, __ATOMIC_RELEASE);
long tid = zr_clone(ZR_THREAD, zr_stack + ZR_STACK, &zr_stack_busy, &zr_tid, tls);
zr_sys(SYS_rt_sigprocmask, SIG_SETMASK, &previous, NULL, sizeof(previous));
if (tid > 0) return 1;
__atomic_store_n(&zr_stack_busy, 0, __ATOMIC_RELEASE);
return 0;
}
static void zr_handler(int sig, siginfo_t *info, void *context) {
@@ -307,34 +545,23 @@ static void zr_handler(int sig, siginfo_t *info, void *context) {
(void)context;
if (info == NULL || info->si_code != SI_USER) return;
int saved = errno;
__atomic_store_n(&zr_pending, 1, __ATOMIC_SEQ_CST);
if (__atomic_load_n(&zr_worker, __ATOMIC_ACQUIRE)) {
zr_sys(SYS_futex, &zr_pending, ZR_FUTEX_WAKE, 1, NULL, NULL, 0);
} else while (__atomic_load_n(&zr_pending, __ATOMIC_SEQ_CST)
&& !__atomic_exchange_n(&zr_busy, 1, __ATOMIC_SEQ_CST)) {
__atomic_store_n(&zr_pending, 0, __ATOMIC_SEQ_CST);
zr_request(0);
__atomic_store_n(&zr_busy, 0, __ATOMIC_SEQ_CST);
}
if (__atomic_fetch_add(&zr_requests, 1, __ATOMIC_ACQ_REL) == 0 && !zr_start()) zr_drain(0);
errno = saved;
}
static void zr_child(void) {
__atomic_store_n(&zr_busy, 0, __ATOMIC_SEQ_CST);
__atomic_store_n(&zr_pending, 0, __ATOMIC_SEQ_CST);
__atomic_store_n(&zr_worker, 0, __ATOMIC_RELEASE);
__atomic_store_n(&zr_requests, 0, __ATOMIC_RELEASE);
__atomic_store_n(&zr_stack_busy, 0, __ATOMIC_RELEASE);
}
__attribute__((constructor)) static void zr_init(void) {
void *libc = dlopen("libc.so.6", RTLD_LAZY | RTLD_NOLOAD);
if (libc == NULL) return;
zr_sys = (long (*)(long, ...))dlsym(libc, "syscall");
if (zr_sys == NULL) return;
int fd = zr_open(ZR_CTL);
if (fd < 0) return;
zr_sys(SYS_close, fd);
long page = sysconf(_SC_PAGESIZE);
zr_page = page > 0 ? (unsigned long)page : 4096UL;
long threads;
if (!zr_status(&threads, &zr_filters)) zr_filters = -1;
struct sigaction old;
if (sigaction(SIGURG, NULL, &old) != 0) return;
if ((old.sa_flags & SA_SIGINFO) || old.sa_handler != SIG_DFL) return;
@@ -343,21 +570,5 @@ __attribute__((constructor)) static void zr_init(void) {
sa.sa_sigaction = zr_handler;
sa.sa_flags = SA_SIGINFO | SA_RESTART;
sigemptyset(&sa.sa_mask);
if (sigaction(SIGURG, &sa, NULL) == 0) {
pthread_atfork(NULL, NULL, zr_child);
pthread_attr_t attr;
if (pthread_attr_init(&attr) == 0) {
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
pthread_t thread;
sigset_t blocked;
sigset_t previous;
if (sigfillset(&blocked) == 0 &&
pthread_sigmask(SIG_SETMASK, &blocked, &previous) == 0) {
if (pthread_create(&thread, &attr, zr_worker_main, NULL) == 0)
__atomic_store_n(&zr_worker, 1, __ATOMIC_RELEASE);
pthread_sigmask(SIG_SETMASK, &previous, NULL);
}
pthread_attr_destroy(&attr);
}
}
if (sigaction(SIGURG, &sa, NULL) == 0) pthread_atfork(NULL, NULL, zr_child);
}
+28
View File
@@ -0,0 +1,28 @@
#!/usr/bin/env bash
# Builds the Rockstar launcher in a container, on the host's own architecture. Rust's
# i686-pc-windows-gnu target needs a DWARF2 mingw; Homebrew's i686 mingw uses SJLJ and fails to link.
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
repo=$(cd "$here/../.." && pwd)
out=${1:?usage: build-container.sh <output directory>}
. "$repo/tools/docker_platform.sh"
cache=${DROIDDECK_BUILD_CACHE:-$HOME/.cache/droiddeck-build}/rockstar-container
mkdir -p "$out" "$cache/cargo" "$cache/target"
out=$(cd "$out" && pwd)
image=droiddeck-rockstar-build:v2-${docker_platform#linux/}
if ! docker image inspect "$image" >/dev/null 2>&1; then
docker build --platform "$docker_platform" -t "$image" - <<'EOF'
FROM public.ecr.aws/docker/library/ubuntu:24.04
ENV DEBIAN_FRONTEND=noninteractive RUSTUP_HOME=/opt/rustup CARGO_HOME=/opt/cargo PATH=/opt/cargo/bin:$PATH
RUN apt-get update -qq && apt-get install -y -qq --no-install-recommends ca-certificates curl gcc libc6-dev \
gcc-mingw-w64-i686-posix gcc-mingw-w64-x86-64-posix >/dev/null
RUN curl -sSf https://sh.rustup.rs | sh -s -- -y -q --profile minimal --default-toolchain stable \
-t i686-pc-windows-gnu -t x86_64-pc-windows-gnu && chmod -R a+rX /opt/rustup /opt/cargo
EOF
fi
docker run --rm --platform "$docker_platform" --user "$(id -u):$(id -g)" \
-e CARGO_HOME=/cache/cargo -e CARGO_TARGET_DIR=/cache/target -e HOME=/tmp \
-v "$repo:/src" -v "$out:/out" -v "$cache:/cache" -w /src "$image" \
bash tools/rockstar-launcher/build.sh /out
+2 -37
View File
@@ -6,7 +6,6 @@ import re
import runpy
import shutil
import tempfile
import threading
import time
import unittest
from unittest import mock
@@ -93,8 +92,6 @@ class IdTest(unittest.TestCase):
self.assertEqual(int(BNET["APP_ID"]), zlib.crc32(b'"droiddeck-battlenet"Battle.net') | 0x80000000)
found = re.search(r"const val APP_ID = (\d+)L", KOTLIN.read_text())
self.assertEqual(found.group(1), BNET["APP_ID"])
for name in ("FEX_REQUEST", "FEX_RESULT"):
self.assertIn('const val %s = "%s"' % (name, BNET[name]), KOTLIN.read_text())
class ProtonRunOptionsTest(Temp):
@@ -761,36 +758,6 @@ class TidyTest(unittest.TestCase):
self.assertEqual(self.stopped, [])
class FexRequestTest(Temp):
def answer(self, text, delay=0.2):
def respond():
request = self.tmp / BNET["FEX_REQUEST"]
deadline = time.monotonic() + 5
while not request.exists() and time.monotonic() < deadline:
time.sleep(0.02)
self.requested = request.read_text()
request.unlink()
time.sleep(delay)
(self.tmp / (BNET["FEX_RESULT"] + ".tmp")).write_text(text + "\n")
os.replace(self.tmp / (BNET["FEX_RESULT"] + ".tmp"), self.tmp / BNET["FEX_RESULT"])
thread = threading.Thread(target=respond)
thread.start()
self.addCleanup(thread.join)
def test_the_apps_answer_comes_back(self):
(self.tmp / BNET["FEX_RESULT"]).write_text("ok an-old-answer\n")
self.answer("ok FEXCore-2610-d2rfix28-linux.wcp")
self.assertEqual(BNET["ask_fex"](str(self.tmp), wait=5), "ok FEXCore-2610-d2rfix28-linux.wcp")
self.assertEqual(self.requested, "appid=%s\n" % BNET["APP_ID"])
self.assertFalse((self.tmp / BNET["FEX_RESULT"]).exists())
def test_no_answer_or_no_session_starts_without_one(self):
with mock.patch.dict(BNET, {"say": lambda message: None}):
self.assertIsNone(BNET["ask_fex"](str(self.tmp), wait=0.3))
self.assertIsNone(BNET["ask_fex"](None))
self.assertIsNone(BNET["ask_fex"](str(self.tmp / "gone")))
class OpenTest(Temp):
def setUp(self):
super().setUp()
@@ -799,7 +766,6 @@ class OpenTest(Temp):
self.alive = []
self.menu = self.tmp / "droiddeck-battlenet.desktop"
patcher = mock.patch.dict(BNET, {
"ask_fex": lambda launch_dir, wait=0: "ok fex.wcp",
"say": lambda message: None, "notify": lambda *a, **k: self.calls.append(("notify", a[0])),
"wine_processes": lambda pfx, proc="/proc": list(self.alive),
"stop": lambda processes, wait=0: self.calls.append(("stop", [pid for pid, _ in processes])) or self.alive.clear(),
@@ -988,7 +954,6 @@ class Harness(Temp):
self.states = []
self.last = []
patcher = mock.patch.dict(BNET, {
"ask_fex": lambda launch_dir, wait=0: self.calls.append(("fex",)) or "ok fex.wcp",
"say": lambda message: None, "notify": lambda *a, **k: self.calls.append(("notify", a[0])),
"wine_processes": self.processes,
"stop": lambda processes, wait=0: self.calls.append(("stop", sorted(pid for pid, _ in processes))),
@@ -1019,7 +984,7 @@ class LaunchTest(Harness):
self.states = [[], [], up, up + [(40, self.GAME)], up, up]
self.assertEqual(BNET["launch"](self.root, "Fen"), 0)
self.assertEqual(self.calls, [
("fex",), ("start", "Battle.net Launcher.exe", None),
("start", "Battle.net Launcher.exe", None),
("spawn", "Battle.net.exe", "run", ["--exec=launch Fen"]),
("stop", [10, 11, 12, 13, 14, 30]),
])
@@ -1034,7 +999,7 @@ class LaunchTest(Harness):
with mock.patch.dict(BNET, {"GAME_SETTLE": 0}):
self.assertEqual(BNET["launch"](self.root, "Fen"), 0)
self.assertEqual(self.calls, [
("fex",), ("start", "Battle.net Launcher.exe", None),
("start", "Battle.net Launcher.exe", None),
("spawn", "Battle.net.exe", "run", ["--exec=launch Fen"]),
("stop", [10, 11, 12, 13, 14, 30]),
("stop", [50]),
+72 -1
View File
@@ -77,6 +77,66 @@ char *realpath(const char *path, char *resolved) {
}
"""
LOCKED = r"""
#include <sys/syscall.h>
#include <unistd.h>
extern int busy;
__attribute__((constructor)) static void start(void) {
busy = 1;
syscall(SYS_getpid);
busy = 0;
}
"""
ARENA = r"""
#include <stdint.h>
#include <stdio.h>
#include <string.h>
static _Alignas(64) unsigned char arena[1 << 23];
static size_t used;
int busy;
static int busy_allocations;
void *memalign(size_t align, size_t size) {
uintptr_t start;
if (busy) busy_allocations++;
if (align < 16) align = 16;
start = ((uintptr_t)(arena + used) + 16 + align - 1) & ~(uintptr_t)(align - 1);
if (start + size > (uintptr_t)(arena + sizeof(arena))) return NULL;
((size_t *)start)[-1] = size;
used = start + size - (uintptr_t)arena;
return (void *)start;
}
void *malloc(size_t size) { return memalign(16, size); }
void *aligned_alloc(size_t align, size_t size) { return memalign(align, size); }
int posix_memalign(void **out, size_t align, size_t size) { return (*out = memalign(align, size)) ? 0 : 12; }
void free(void *p) { (void)p; }
void *calloc(size_t n, size_t size) {
void *p = malloc(n * size);
if (p) memset(p, 0, n * size);
return p;
}
void *realloc(void *p, size_t size) {
void *q = malloc(size);
if (p && q) {
size_t old = ((size_t *)p)[-1];
memcpy(q, p, old < size ? old : size);
}
return q;
}
int main(void) {
printf("allocations %d\n", busy_allocations);
return 0;
}
"""
UDEV = r"""
#include <stdio.h>
#include <stdlib.h>
@@ -414,7 +474,7 @@ class InputUdevPreloadTest(unittest.TestCase):
if "__GLIBC__" not in compile_c("-dM", "-E", "-x", "c", "-include", "limits.h", "/dev/null"):
raise unittest.SkipTest("needs a glibc toolchain")
sources = (("once.c", ONCE), ("first.c", FIRST), ("second.c", SECOND), ("chain.c", CHAIN), ("mark.c", MARK),
("udev.c", UDEV), ("program.c", PROGRAM))
("udev.c", UDEV), ("program.c", PROGRAM), ("locked.c", LOCKED), ("arena.c", ARENA))
for name, text in sources:
(build / name).write_text(text)
cls.lib = cls.dir / "libddsession.so"
@@ -427,6 +487,11 @@ class InputUdevPreloadTest(unittest.TestCase):
compile_c("-shared", "-fPIC", "-O2", "-o", str(cls.udev), str(build / "udev.c"))
cls.program = cls.dir / "program"
compile_c("-O0", "-o", str(cls.program), str(build / "program.c"), str(cls.dir / "libfirst.so"), "-ldl")
compile_c("-shared", "-fPIC", "-O0", "-o", str(cls.dir / "liblocked.so"), str(build / "locked.c"))
cls.arena = cls.dir / "arena"
compile_c("-O0", "-rdynamic", "-o", str(cls.arena), str(build / "arena.c"), "-Wl,--no-as-needed",
str(cls.dir / "liblocked.so"),
f"-Wl,-rpath,{cls.dir}")
cls.pads = cls.pad_dir("pads", "event0")
@classmethod
@@ -449,6 +514,12 @@ class InputUdevPreloadTest(unittest.TestCase):
def test_a_lookup_from_another_preloads_initialiser_does_not_reenter_it(self):
self.assertEqual(self.run_program("once", "libonce.so"), ["readlink 1"])
def test_a_first_wrapped_call_inside_the_programs_allocator_does_not_allocate(self):
result = subprocess.run([str(self.arena)], env=dict(os.environ, LD_PRELOAD=str(self.lib)), capture_output=True,
text=True, timeout=20)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(result.stdout.splitlines(), ["allocations 0"])
def test_the_real_lookup_still_sees_the_original_caller(self):
self.assertEqual(self.run_program("next", "libfirst.so", "libsecond.so"), ["next 2"])
+201 -28
View File
@@ -18,7 +18,14 @@ PROGRAM = r"""
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <linux/filter.h>
#include <linux/seccomp.h>
#include <sched.h>
#include <stddef.h>
#include <sys/mman.h>
#include <sys/prctl.h>
#include <sys/resource.h>
#include <sys/syscall.h>
#include <sys/wait.h>
#include <time.h>
@@ -31,14 +38,15 @@ static unsigned char *shared;
static volatile sig_atomic_t urg_tid;
static volatile sig_atomic_t usr_tid;
static int urg_count, usr_count;
static int worker_tid;
static int worker_delivery;
_Static_assert(__atomic_always_lock_free(sizeof(int), 0), "signal state must be lock-free");
static void signal_tid(int sig) {
sig_atomic_t tid = (sig_atomic_t)syscall(SYS_gettid);
if (tid == __atomic_load_n(&worker_tid, __ATOMIC_RELAXED))
char name[16] = {0};
prctl(PR_GET_NAME, name, 0, 0, 0);
if (!strcmp(name, "zr-worker"))
__atomic_store_n(&worker_delivery, 1, __ATOMIC_RELAXED);
if (sig == SIGURG) {
__atomic_store_n(&urg_tid, tid, __ATOMIC_RELAXED);
@@ -123,6 +131,75 @@ static long trim(char mode, long kb) {
exit(5);
}
static int workers(void) {
DIR *dir = opendir("/proc/self/task");
struct dirent *entry;
int count = 0;
while (dir && (entry = readdir(dir)) != NULL) {
if (entry->d_name[0] == '.') continue;
char path[64], name[32] = {0};
snprintf(path, sizeof(path), "/proc/self/task/%s/comm", entry->d_name);
FILE *comm = fopen(path, "r");
if (comm && fgets(name, sizeof(name), comm) && !strcmp(name, "zr-worker\n")) count++;
if (comm) fclose(comm);
}
if (dir) closedir(dir);
return count;
}
static void without_threads(void) {
struct rlimit limit;
if (getrlimit(RLIMIT_NPROC, &limit)) _exit(15);
limit.rlim_cur = 0;
if (setrlimit(RLIMIT_NPROC, &limit)) _exit(15);
}
static void *park(void *arg) {
(void)arg;
for (;;) pause();
return NULL;
}
static void parked(void) {
pthread_t thread;
sigset_t urg, previous;
sigemptyset(&urg);
sigaddset(&urg, SIGURG);
pthread_sigmask(SIG_BLOCK, &urg, &previous);
if (pthread_create(&thread, NULL, park, NULL)) _exit(16);
pthread_sigmask(SIG_SETMASK, &previous, NULL);
}
static void filter_clone(unsigned long allowed) {
struct sock_filter rules[] = {
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, nr)),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SYS_clone, 0, 3),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, args[0])),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, allowed, 1, 0),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_KILL_PROCESS),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
};
struct sock_fprog program = {sizeof(rules) / sizeof(rules[0]), rules};
if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) || prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &program)) _exit(17);
}
static volatile int sandbox_ready;
static void *sandbox(void *arg) {
(void)arg;
sigset_t urg;
sigemptyset(&urg);
sigaddset(&urg, SIGURG);
filter_clone(0);
pthread_sigmask(SIG_UNBLOCK, &urg, NULL);
sandbox_ready = 1;
for (;;) pause();
return NULL;
}
static const unsigned long thread_clone = CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_THREAD |
CLONE_SYSVSEM | CLONE_SETTLS | CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID;
static uint64_t sum(const unsigned char *p, size_t n) {
uint64_t s = 0;
for (size_t i = 0; i < n; i += 64) s = s * 31 + p[i];
@@ -155,6 +232,7 @@ int main(int argc, char **argv) {
memset(shared, 0, size);
pthread_t t[2];
for (uintptr_t i = 0; i < 2; i++) pthread_create(&t[i], NULL, writer, (void *)i);
parked();
struct sigaction sa;
sigaction(SIGURG, NULL, &sa);
printf("handler %d\n", (sa.sa_flags & SA_SIGINFO) ? 1 : 0);
@@ -164,27 +242,21 @@ int main(int argc, char **argv) {
memset(&signal_action, 0, sizeof(signal_action));
signal_action.sa_handler = signal_tid;
sigemptyset(&signal_action.sa_mask);
sigaction(SIGURG, &signal_action, NULL);
sigaction(SIGUSR1, &signal_action, NULL);
int fd = open(ctl, O_WRONLY | O_TRUNC);
if (fd < 0 || write(fd, "1", 1) != 1) return 10;
close(fd);
printf("ready %d\n", getpid());
fflush(stdout);
int id;
if (scanf("%d", &id) != 1) return 10;
__atomic_store_n(&worker_tid, id, __ATOMIC_RELAXED);
printf("armed 1\n");
fflush(stdout);
for (int round = 1; round <= 100; round++) {
int i;
for (i = 0; i < 5000 &&
(__atomic_load_n(&urg_count, __ATOMIC_ACQUIRE) < round ||
__atomic_load_n(&usr_count, __ATOMIC_ACQUIRE) < round); i++) usleep(1000);
for (i = 0; i < 5000 && __atomic_load_n(&usr_count, __ATOMIC_ACQUIRE) < round; i++) usleep(1000);
if (i == 5000) return 11;
printf("received %d\n", round);
fflush(stdout);
}
stop = 1;
for (int i = 0; i < 2; i++) pthread_join(t[i], NULL);
printf("urg %d\n", __atomic_load_n(&urg_tid, __ATOMIC_RELAXED));
printf("usr %d\n", __atomic_load_n(&usr_tid, __ATOMIC_RELAXED));
printf("worker %d\n", __atomic_load_n(&worker_delivery, __ATOMIC_RELAXED));
return 0;
@@ -199,6 +271,13 @@ int main(int argc, char **argv) {
int status_code;
waitpid(child, &status_code, 0);
printf("childack %d\n", WIFEXITED(status_code) && WEXITSTATUS(status_code) == 0);
} else if (!strcmp(argv[4], "threads")) {
stop = 1;
for (int i = 0; i < 2; i++) pthread_join(t[i], NULL);
printf("idle %d\n", workers());
request('1');
printf("after %d\n", workers());
return 0;
} else if (!strcmp(argv[4], "trim")) {
stop = 1;
for (int i = 0; i < 2; i++) pthread_join(t[i], NULL);
@@ -258,6 +337,36 @@ int main(int argc, char **argv) {
printf("held %ld\n", status("VmSwap:"));
unlink(hold);
return 0;
} else if (!strcmp(argv[4], "scoped")) {
stop = 1;
for (int i = 0; i < 2; i++) pthread_join(t[i], NULL);
request('1');
printf("out %ld\n", status("VmSwap:"));
char hold[256], own[256];
snprintf(hold, sizeof(hold), "%s.hold", ctl);
snprintf(own, sizeof(own), "%s.hold.%d", ctl, getpid());
FILE *f = fopen(ctl, "w");
if (!f) exit(3);
fputs("0", f);
fclose(f);
f = fopen(hold, "w");
if (!f) exit(3);
fputs("2 0", f);
fclose(f);
kill(getpid(), SIGURG);
usleep(1000000);
printf("shared %ld\n", status("VmSwap:"));
f = fopen(own, "w");
if (!f) exit(3);
fputs("0", f);
fclose(f);
kill(getpid(), SIGURG);
usleep(1000000);
printf("own %ld\n", status("VmSwap:"));
unlink(own);
unlink(hold);
printf("intact %d\n", sum(data, size) == before);
return 0;
} else if (!strcmp(argv[4], "trim-fork")) {
stop = 1;
for (int i = 0; i < 2; i++) pthread_join(t[i], NULL);
@@ -271,8 +380,47 @@ int main(int argc, char **argv) {
_exit(0);
}
waitpid(child, NULL, 0);
child = fork();
if (child < 0) exit(6);
if (child == 0) {
parked();
without_threads();
for (size_t i = 0; i < size; i += page) data[i]++;
printf("nothread_trim %ld\n", trim('2', 1L << 30));
fflush(stdout);
_exit(0);
}
waitpid(child, NULL, 0);
printf("worker_trim %ld\n", trim('2', 1L << 30));
return 0;
} else if (!strcmp(argv[4], "sandboxed")) {
stop = 1;
for (int i = 0; i < 2; i++) pthread_join(t[i], NULL);
filter_clone(thread_clone);
printf("sandboxed_trim %ld\n", trim('2', 1L << 30));
return 0;
} else if (!strcmp(argv[4], "thread-sandboxed")) {
stop = 1;
for (int i = 0; i < 2; i++) pthread_join(t[i], NULL);
sigset_t urg;
sigemptyset(&urg);
sigaddset(&urg, SIGURG);
pthread_sigmask(SIG_BLOCK, &urg, NULL);
pthread_t thread;
if (pthread_create(&thread, NULL, sandbox, NULL)) exit(16);
while (!sandbox_ready) usleep(1000);
printf("thread_sandboxed_trim %ld\n", trim('2', 1L << 30));
return 0;
} else if (!strcmp(argv[4], "filtered")) {
fflush(stdout);
filter_clone(thread_clone);
execl("/proc/self/exe", argv[0], argv[1], argv[2], "0", "filtered-trim", (char *)NULL);
return 18;
} else if (!strcmp(argv[4], "filtered-trim")) {
stop = 1;
for (int i = 0; i < 2; i++) pthread_join(t[i], NULL);
printf("filtered_trim %ld\n", trim('2', 1L << 30));
return 0;
} else if (!strcmp(argv[4], "burst")) {
send_request('0');
usleep(10000);
@@ -283,6 +431,7 @@ int main(int argc, char **argv) {
pid_t child = fork();
if (child < 0) exit(8);
if (child == 0) {
without_threads();
if (!strcmp(argv[4], "timed-inline-single")) {
if (munmap(data, size) || munmap(shared, size)) _exit(12);
data = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
@@ -389,6 +538,8 @@ class ZramPreloadTest(unittest.TestCase):
for ack in [*self.dir.glob("ctl.ack.*"), *self.dir.glob("ctl.trim.*")]:
ack.unlink()
(self.dir / "ctl.hold").unlink(missing_ok=True)
for hold in self.dir.glob("ctl.hold.*"):
hold.unlink()
def run_program(self, program=None, mb=48, cycles=1, *extra):
environment = dict(os.environ, LD_PRELOAD=str(self.lib))
@@ -431,6 +582,11 @@ class ZramPreloadTest(unittest.TestCase):
self.assertEqual([1], out["intact"])
self.assertEqual(6, len(out["out"]))
def test_a_process_keeps_no_extra_thread_while_nothing_is_paged_out(self):
out = self.run_program(None, 8, 0, "threads")
self.assertEqual([0], out["idle"])
self.assertEqual([0], out["after"])
def test_process_signals_do_not_reach_zram_worker(self):
environment = dict(os.environ, LD_PRELOAD=str(self.lib))
process = subprocess.Popen([str(self.steam), str(self.ctl), "1", "0", "signals"],
@@ -439,30 +595,16 @@ class ZramPreloadTest(unittest.TestCase):
process.stdout.readline()
ready = process.stdout.readline().split()
self.assertEqual("ready", ready[0])
worker = None
task_dir = Path("/proc") / ready[1] / "task"
for task in task_dir.iterdir():
if (task / "comm").read_text().strip() == "zr-worker":
worker = int(task.name)
break
self.assertIsNotNone(worker)
self.assertEqual(os.sched_getscheduler(process.pid), os.sched_getscheduler(worker))
process.stdin.write(f"{worker}\n")
process.stdin.flush()
self.assertEqual("armed 1", process.stdout.readline().strip())
for _ in range(100):
for round in range(100):
os.kill(process.pid, signal.SIGURG)
os.kill(process.pid, signal.SIGUSR1)
self.assertEqual(f"received {_ + 1}", process.stdout.readline().strip())
self.assertEqual(f"received {round + 1}", process.stdout.readline().strip())
process.stdin.close()
process.wait(timeout=10)
output = process.stdout.read()
values = dict(line.split() for line in output.splitlines())
self.assertNotEqual(0, int(values["urg"]))
self.assertNotEqual(0, int(values["usr"]))
self.assertEqual(0, int(values["worker"]))
self.assertNotEqual(worker, int(values["urg"]))
self.assertNotEqual(worker, int(values["usr"]))
finally:
if process.poll() is None:
process.kill()
@@ -535,12 +677,43 @@ class ZramPreloadTest(unittest.TestCase):
self.assertTrue(0 < out["empty"][0] <= 512, out)
self.assertGreater(out["held"][0], 40 * 1024, out)
@unittest.skipUnless(swap_total_kb() > 256 * 1024, "needs swap")
def test_a_read_back_reaches_only_the_process_it_names(self):
out = self.run_program(None, 48, 0, "scoped")
self.assertGreater(out["out"][0], 32 * 1024, out)
self.assertGreater(out["shared"][0], out["out"][0] * 3 // 4, out)
self.assertLess(out["own"][0], out["out"][0] // 4, out)
self.assertEqual([1], out["intact"])
@unittest.skipUnless(swap_total_kb() > 256 * 1024, "needs swap")
def test_process_without_a_worker_trims_in_small_steps(self):
if os.geteuid() == 0:
self.skipTest("the thread limit does not apply to root")
out = self.run_program(None, 48, 0, "trim-fork")
self.assertTrue(16 * 1024 < out["nothread_trim"][0] <= 32 * 1024, out)
self.assertGreater(out["worker_trim"][0], 64 * 1024, out)
@unittest.skipUnless(swap_total_kb() > 256 * 1024, "needs swap")
def test_a_single_threaded_process_trims_without_starting_a_thread(self):
out = self.run_program(None, 48, 0, "trim-fork")
self.assertTrue(16 * 1024 < out["inline_trim"][0] <= 32 * 1024, out)
self.assertGreater(out["worker_trim"][0], 64 * 1024, out)
@unittest.skipUnless(swap_total_kb() > 256 * 1024, "needs swap")
def test_a_process_that_sandboxed_itself_trims_without_starting_a_thread(self):
out = self.run_program(None, 48, 0, "sandboxed")
self.assertTrue(16 * 1024 < out["sandboxed_trim"][0] <= 32 * 1024, out)
@unittest.skipUnless(swap_total_kb() > 256 * 1024, "needs swap")
def test_a_thread_that_sandboxed_itself_trims_without_starting_a_thread(self):
out = self.run_program(None, 48, 0, "thread-sandboxed")
self.assertTrue(16 * 1024 < out["thread_sandboxed_trim"][0] <= 32 * 1024, out)
@unittest.skipUnless(swap_total_kb() > 256 * 1024, "needs swap")
def test_the_worker_passes_a_filter_that_only_allows_thread_clones(self):
out = self.run_program(None, 48, 0, "filtered")
self.assertGreater(out["filtered_trim"][0], 40 * 1024, out)
def test_worker_acknowledges_back_to_back_requests(self):
out = self.run_program(None, 48, 0, "burst")
self.assertEqual([1], out["burstack"])
+1 -1
View File
@@ -14,7 +14,7 @@ if [ -z "$vkinc" ]; then
for ndk in "${ANDROID_NDK_HOME:-}" "${ANDROID_NDK_LATEST_HOME:-}" \
$(ls -d "${ANDROID_HOME:-$HOME/Library/Android/sdk}"/ndk/* 2>/dev/null | sort -r); do
[ -n "$ndk" ] || continue
cand=$(ls -d "$ndk"/toolchains/llvm/prebuilt/*/sysroot/usr/include 2>/dev/null | head -1)
cand=$(ls -d "$ndk"/toolchains/llvm/prebuilt/*/sysroot/usr/include 2>/dev/null | head -1 || true)
if [ -n "$cand" ] && [ -f "$cand/vulkan/vk_layer.h" ]; then vkinc=$cand; break; fi
done
fi