mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-05 12:35:42 +00:00
Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
62b61e64bb | ||
|
|
03812bb3b7 | ||
|
|
a0cd5b0cad | ||
|
|
97c6229e85 | ||
|
|
0ff1bebdf6 | ||
|
|
e5824dabab | ||
|
|
8276b29b7d |
No files matched your search
@@ -0,0 +1,39 @@
|
||||
name: Community controls pack
|
||||
description: Submit on-screen controls for the community catalog.
|
||||
title: "[Controls]: "
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: Export a ZIP from Controller settings → Community controls. Attach the ZIP and a screenshot below. Submissions are reviewed before inclusion in the catalog.
|
||||
- type: input
|
||||
id: name
|
||||
attributes:
|
||||
label: Pack name and author
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
id: game
|
||||
attributes:
|
||||
label: Game (optional)
|
||||
description: Include the store and game ID if these controls target a specific game.
|
||||
- type: textarea
|
||||
id: files
|
||||
attributes:
|
||||
label: Controls ZIP and screenshot
|
||||
description: Drag the exported .ddcontrols.zip and a preview screenshot here. Describe the screen orientation and bindings.
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
id: license
|
||||
attributes:
|
||||
label: License and artwork credits
|
||||
description: Specify a license that permits redistribution, and credit any third-party artwork with its source and license.
|
||||
validations:
|
||||
required: true
|
||||
- type: checkboxes
|
||||
id: permission
|
||||
attributes:
|
||||
label: Distribution permission
|
||||
options:
|
||||
- label: I have permission to share this pack and all included artwork under the stated license.
|
||||
required: true
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"version": 1,
|
||||
"controls": [
|
||||
{
|
||||
"name": "Compact gamepad",
|
||||
"author": "DroidDeck",
|
||||
"game": "",
|
||||
"license": "GPL-3.0",
|
||||
"file": "packs/compact-gamepad.ddcontrols.zip",
|
||||
"sha256": "8b747e86268a1f607e312f2c39dd67402658bd5cf9e4e4ff524a4640417c9f3e",
|
||||
"screen": "BOTH",
|
||||
"preview": "previews/compact-gamepad.png"
|
||||
}
|
||||
]
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
|
After Width: | Height: | Size: 21 KiB |
@@ -294,7 +294,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
private lateinit var threeFingerTap: com.droiddeck.launcher.input.ThreeFingerTap
|
||||
private lateinit var touchscreenGestures: TouchscreenGestures
|
||||
private var gestureConfig = com.droiddeck.launcher.input.TouchGestureConfig()
|
||||
private var gestureGame: String? = null
|
||||
private var gestureGame by mutableStateOf<String?>(null)
|
||||
private var gameStarts by mutableIntStateOf(0)
|
||||
private var gestureSettingsOpen by mutableStateOf(false)
|
||||
private var steamImportAsk by mutableStateOf<com.droiddeck.launcher.session.SteamImportPrompt.Ask?>(null)
|
||||
@@ -1197,8 +1197,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
}
|
||||
if (nextGame != gestureGame) {
|
||||
if (nextGame != null) gameStarts++
|
||||
val previousControls = com.droiddeck.launcher.input.GameInputControls.profile(this@SessionActivity, inputGameScope())
|
||||
gestureGame = nextGame
|
||||
refreshGestureConfig()
|
||||
if (previousControls != com.droiddeck.launcher.input.GameInputControls.profile(this@SessionActivity, inputGameScope())) {
|
||||
releasePads()
|
||||
refreshInputProfile()
|
||||
}
|
||||
}
|
||||
if (
|
||||
SessionState.mode == SessionService.MODE_STEAM &&
|
||||
@@ -4221,9 +4226,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
if (started && displayId !in inputWindowDisplays && secondScreenMode != SecondScreenMode.NONE && secondScreenPresentation == null) showSecondScreen(secondScreenMode)
|
||||
}
|
||||
|
||||
fun inputGameScope(): String? = if (loadingMode() == SessionService.MODE_RUN) {
|
||||
(if (SessionState.running) SessionState.gameId else null)
|
||||
?: intent.getStringExtra(SessionService.EXTRA_GAME_ID) ?: gestureGame
|
||||
} else gestureGame
|
||||
|
||||
private fun refreshInputProfile() {
|
||||
val library = com.droiddeck.launcher.input.InputLibraries.read(this)
|
||||
val desktop = loadingMode() == SessionService.MODE_DESKTOP
|
||||
val game = inputGameScope()
|
||||
val library = com.droiddeck.launcher.input.GameInputControls.resolve(this,
|
||||
com.droiddeck.launcher.input.InputLibraries.read(this), desktop, game)
|
||||
inputProfile = library.compileActive(desktop, secondScreenMode.panel(this))
|
||||
primaryInputLayout = library.activeLayout(desktop, InputRole.PRIMARY)
|
||||
adaptiveSticks = primaryInputLayout?.adaptiveSticks
|
||||
|
||||
@@ -13,7 +13,6 @@ object GamesFolderMigration {
|
||||
|
||||
@Synchronized
|
||||
fun run(context: Context) {
|
||||
repathInternalGuest(context)
|
||||
val dirs = SessionPrefs.addedGamesDirs(context)
|
||||
if (dirs.isEmpty()) return
|
||||
val roots = legacyRoots(SessionPrefs.gameFolderBinds(context).map { it.first } + dirs)
|
||||
@@ -59,30 +58,12 @@ object GamesFolderMigration {
|
||||
SessionPrefs.setGamesFoldersMigrated(context)
|
||||
}
|
||||
|
||||
private fun repathInternalGuest(context: Context) {
|
||||
val binds = SessionPrefs.gameFolderBinds(context)
|
||||
if (binds.none { it.second == StoreInstallRoot.INTERNAL_GUEST }) return
|
||||
val hosts = binds.map { it.first }
|
||||
val roots = legacyRoots(hosts).associateBy { it.host.path }
|
||||
val taken = binds.map { it.second }.filter { it != StoreInstallRoot.INTERNAL_GUEST }.toMutableSet()
|
||||
SessionPrefs.setGameFolderBinds(context, binds.map { (host, guest) ->
|
||||
if (guest != StoreInstallRoot.INTERNAL_GUEST) return@map host to guest
|
||||
val base = roots.getValue(host).guest
|
||||
var next = base
|
||||
var n = 2
|
||||
while (next in taken) next = "$base-${n++}"
|
||||
taken.add(next)
|
||||
host to next
|
||||
})
|
||||
}
|
||||
|
||||
internal fun legacyRoots(paths: List<String>): List<AddedGames.Root> {
|
||||
val hosts = paths.distinct().map { File(it) }
|
||||
val names = hosts.groupingBy { it.name.lowercase() }.eachCount()
|
||||
return hosts.map { host ->
|
||||
val name = host.name.ifEmpty { "games" }
|
||||
val clash = (names[name.lowercase()] ?: 0) > 1 || "${AddedGames.GUEST_DIR}/$name" == StoreInstallRoot.INTERNAL_GUEST
|
||||
val guestName = if (clash) name + "-" + "%08x".format(CRC32().apply { update(host.path.toByteArray()) }.value).take(4) else name
|
||||
val guestName = if ((names[name.lowercase()] ?: 0) > 1) name + "-" + "%08x".format(CRC32().apply { update(host.path.toByteArray()) }.value).take(4) else name
|
||||
AddedGames.Root(host, "${AddedGames.GUEST_DIR}/$guestName")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import java.io.ByteArrayInputStream
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.util.zip.ZipInputStream
|
||||
|
||||
internal object ArmsControlSkins {
|
||||
private val buttons = mapOf(
|
||||
InputControl.A to "cross", InputControl.B to "circle", InputControl.X to "square", InputControl.Y to "triangle",
|
||||
InputControl.LB to "l1", InputControl.RB to "r1", InputControl.LT to "l2", InputControl.RT to "r2",
|
||||
InputControl.L3 to "l3", InputControl.R3 to "r3", InputControl.SELECT to "select", InputControl.START to "start",
|
||||
InputControl.UP to "up", InputControl.DOWN to "down", InputControl.LEFT to "left", InputControl.RIGHT to "right")
|
||||
private val keys = buttons.values.toSet() + setOf("analog_base", "analog_stick", "analog_base_left", "analog_base_right",
|
||||
"analog_stick_left", "analog_stick_right")
|
||||
|
||||
fun parse(context: android.content.Context, bytes: ByteArray, original: SavedInputLayout, actions: SavedInputBindings, name: String, nativeFailure: Exception? = null): CommunityControls.Pack {
|
||||
require(bytes.size <= 32 * 1024 * 1024 && original.editable && actions.compatible(original))
|
||||
val art = linkedMapOf<String, ByteArray>()
|
||||
var total = 0
|
||||
var entries = 0
|
||||
ZipInputStream(ByteArrayInputStream(bytes)).use { zip ->
|
||||
while (true) {
|
||||
val entry = zip.nextEntry ?: break
|
||||
require(++entries <= 256 && ControlSources.validPath(entry.name.trimEnd('/'))) { "Invalid skin archive path or file count." }
|
||||
if (entry.isDirectory) continue
|
||||
val data = CommunityControls.readLimited(zip, minOf(8 * 1024 * 1024, 64 * 1024 * 1024 - total))
|
||||
total += data.size
|
||||
if (entry.name == "controls.json") throw (nativeFailure ?: IllegalArgumentException("Import this file as a DroidDeck controls pack."))
|
||||
val file = entry.name.substringAfterLast('/').lowercase()
|
||||
if (file.startsWith("._") || !file.endsWith(".png")) continue
|
||||
val key = file.removeSuffix(".png").removePrefix("ic_controller_").removeSuffix("_button")
|
||||
if (key !in keys) continue
|
||||
require(key !in art) { "Duplicate skin button artwork." }
|
||||
art[key] = normalize(data)
|
||||
}
|
||||
}
|
||||
require(art.isNotEmpty()) { "No supported controller PNGs found in this skin." }
|
||||
val used = linkedMapOf<String, ByteArray>()
|
||||
fun image(key: String): String? = art[key]?.let { data ->
|
||||
val file = "skin_$key.png"
|
||||
used[file] = data
|
||||
file
|
||||
}
|
||||
var matched = 0
|
||||
val elements = original.elements.map { e ->
|
||||
val action = actions.action(e) as? InputAction.Native ?: return@map e
|
||||
val control = action.target ?: e.control
|
||||
if (e.kind == InputElementKind.STICK && (control == InputControl.LS || control == InputControl.RS)) {
|
||||
val side = if (control == InputControl.LS) "left" else "right"
|
||||
val base = image("analog_base_$side") ?: image("analog_base")
|
||||
val stick = image("analog_stick_$side") ?: image("analog_stick")
|
||||
if (base == null && stick == null) e else {
|
||||
matched++
|
||||
e.copy(image = base ?: e.image, stickImage = stick ?: e.stickImage, showLabel = false)
|
||||
}
|
||||
} else if (e.kind == InputElementKind.BUTTON || e.kind == InputElementKind.TRIGGER) {
|
||||
val file = buttons[control]?.let(::image)
|
||||
if (file == null) e else { matched++; e.copy(image = file, icon = 0, showLabel = false) }
|
||||
} else e
|
||||
}
|
||||
require(matched > 0) { "This layout has no matching gamepad controls. Choose a gamepad profile and screen." }
|
||||
val id = newInputId()
|
||||
val label = name.trim().take(80).ifBlank { "Imported controller skin" }
|
||||
val layout = original.copy(id = id, name = label, origin = null, elements = elements)
|
||||
for (file in elements.flatMap { listOf(it.image, it.stickImage) }.filter { it.isNotEmpty() }.distinct()) {
|
||||
if (file !in used) used[file] = requireNotNull(InputButtonImages.file(context, file)).inputStream().use {
|
||||
CommunityControls.readLimited(it, 1024 * 1024)
|
||||
}
|
||||
}
|
||||
return CommunityControls.Pack(layout, actions.copy(id = newInputId(), name = label, layoutId = id), used)
|
||||
}
|
||||
|
||||
fun export(context: android.content.Context, layout: SavedInputLayout, actions: SavedInputBindings): ByteArray {
|
||||
val images = linkedMapOf<String, String>()
|
||||
for (element in layout.elements) {
|
||||
val action = actions.action(element) as? InputAction.Native ?: continue
|
||||
val control = action.target ?: element.control
|
||||
if (element.kind == InputElementKind.STICK && (control == InputControl.LS || control == InputControl.RS)) {
|
||||
val side = if (control == InputControl.LS) "left" else "right"
|
||||
if (element.image.isNotEmpty()) images["ic_controller_analog_base_$side.png"] = element.image
|
||||
if (element.stickImage.isNotEmpty()) images["ic_controller_analog_stick_$side.png"] = element.stickImage
|
||||
} else if (element.image.isNotEmpty()) {
|
||||
buttons[control]?.let { images["ic_controller_${it}_button.png"] = element.image }
|
||||
}
|
||||
}
|
||||
require(images.isNotEmpty()) { "This layout has no controller skin artwork to export." }
|
||||
val output = ByteArrayOutputStream()
|
||||
java.util.zip.ZipOutputStream(output).use { zip ->
|
||||
for ((name, local) in images) {
|
||||
val bytes = requireNotNull(InputButtonImages.file(context, local)).inputStream().use {
|
||||
CommunityControls.readLimited(it, 1024 * 1024)
|
||||
}
|
||||
zip.putNextEntry(java.util.zip.ZipEntry(name)); zip.write(bytes); zip.closeEntry()
|
||||
}
|
||||
}
|
||||
return output.toByteArray().also { require(it.size <= 32 * 1024 * 1024) }
|
||||
}
|
||||
|
||||
private fun normalize(data: ByteArray): ByteArray {
|
||||
require(data.take(8) == listOf<Byte>(-119, 80, 78, 71, 13, 10, 26, 10)) { "Invalid skin PNG." }
|
||||
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
BitmapFactory.decodeByteArray(data, 0, data.size, bounds)
|
||||
require(bounds.outWidth in 1..8192 && bounds.outHeight in 1..8192) { "Invalid skin image dimensions." }
|
||||
val options = BitmapFactory.Options().apply {
|
||||
inSampleSize = 1
|
||||
while (maxOf(bounds.outWidth, bounds.outHeight) / inSampleSize > 512) inSampleSize *= 2
|
||||
}
|
||||
val bitmap = requireNotNull(BitmapFactory.decodeByteArray(data, 0, data.size, options)) { "Unreadable skin image." }
|
||||
return try {
|
||||
ByteArrayOutputStream().also { check(bitmap.compress(Bitmap.CompressFormat.PNG, 100, it)) }.toByteArray()
|
||||
} finally { bitmap.recycle() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.BitmapFactory
|
||||
import org.json.JSONObject
|
||||
import java.io.ByteArrayInputStream
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.io.InputStream
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.security.MessageDigest
|
||||
import java.util.zip.ZipEntry
|
||||
import java.util.zip.ZipInputStream
|
||||
import java.util.zip.ZipOutputStream
|
||||
|
||||
internal object CommunityControls {
|
||||
const val MAX_BYTES = 16 * 1024 * 1024
|
||||
const val BASE = "https://raw.githubusercontent.com/Droid-Deck/DroidDeck/main/community/controls/"
|
||||
const val SUBMIT = "https://github.com/Droid-Deck/DroidDeck/issues/new?template=community-controls.yml"
|
||||
data class Pack(val layout: SavedInputLayout, val bindings: SavedInputBindings, val images: Map<String, ByteArray>)
|
||||
data class Entry(val name: String, val author: String, val game: String, val license: String,
|
||||
val path: String, val sha256: String, val screen: InputLayoutScreen, val preview: String? = null, val bundled: Boolean = false,
|
||||
val source: ControlSources.Source = ControlSources.DROIDDECK, val skin: Boolean = false) {
|
||||
val key get() = source.id + "/" + path
|
||||
}
|
||||
|
||||
fun readLimited(input: InputStream, limit: Int = MAX_BYTES): ByteArray {
|
||||
val output = ByteArrayOutputStream()
|
||||
val buffer = ByteArray(8192)
|
||||
while (true) {
|
||||
val count = input.read(buffer)
|
||||
if (count < 0) break
|
||||
require(output.size() + count <= limit) { "Controls file is too large." }
|
||||
output.write(buffer, 0, count)
|
||||
}
|
||||
return output.toByteArray()
|
||||
}
|
||||
|
||||
fun export(context: Context, layout: SavedInputLayout, bindings: SavedInputBindings): ByteArray {
|
||||
require(layout.editable && bindings.compatible(layout))
|
||||
val library = InputLibraries.read(context).withLayout(layout).withPreset(bindings)
|
||||
val doc = JSONObject(InputLibraries.encode(library))
|
||||
fun item(key: String, id: String): JSONObject {
|
||||
val array = doc.getJSONArray(key)
|
||||
return (0 until array.length()).map { array.getJSONObject(it) }.first { it.getString("id") == id }
|
||||
}
|
||||
val manifest = JSONObject().put("format", "droiddeck-controls").put("version", 1)
|
||||
.put("layout", item("layouts", layout.id)).put("bindings", item("bindings", bindings.id))
|
||||
val output = ByteArrayOutputStream()
|
||||
ZipOutputStream(output).use { zip ->
|
||||
fun add(name: String, bytes: ByteArray) {
|
||||
zip.putNextEntry(ZipEntry(name)); zip.write(bytes); zip.closeEntry()
|
||||
}
|
||||
add("controls.json", manifest.toString().toByteArray(Charsets.UTF_8))
|
||||
for (name in layout.elements.flatMap { listOf(it.image, it.stickImage) }.filter { it.isNotEmpty() }.distinct()) {
|
||||
val file = requireNotNull(InputButtonImages.file(context, name))
|
||||
add("images/$name", file.inputStream().use { readLimited(it, 1024 * 1024) })
|
||||
}
|
||||
}
|
||||
return output.toByteArray().also { parse(context, it) }
|
||||
}
|
||||
|
||||
fun parse(context: Context, bytes: ByteArray): Pack {
|
||||
require(bytes.size <= MAX_BYTES)
|
||||
val files = linkedMapOf<String, ByteArray>()
|
||||
var total = 0
|
||||
ZipInputStream(ByteArrayInputStream(bytes)).use { zip ->
|
||||
while (true) {
|
||||
val entry = zip.nextEntry ?: break
|
||||
require(!entry.isDirectory && files.size < 65 && entry.name !in files)
|
||||
require(entry.name == "controls.json" || entry.name.matches(Regex("images/[A-Za-z0-9_-][A-Za-z0-9_.-]{0,127}")))
|
||||
val data = readLimited(zip, minOf(if (entry.name == "controls.json") 2_000_000 else 1024 * 1024, MAX_BYTES - total))
|
||||
total += data.size
|
||||
files[entry.name] = data
|
||||
}
|
||||
}
|
||||
val manifest = JSONObject(requireNotNull(files.remove("controls.json")).toString(Charsets.UTF_8))
|
||||
require(manifest.getString("format") == "droiddeck-controls" && manifest.getInt("version") == 1)
|
||||
val layout = manifest.getJSONObject("layout")
|
||||
val bindings = manifest.getJSONObject("bindings")
|
||||
val layoutId = newInputId()
|
||||
val bindingId = newInputId()
|
||||
layout.put("id", layoutId).remove("origin")
|
||||
require(layout.getString("template") == InputLayoutTemplate.CUSTOM.name)
|
||||
bindings.put("id", bindingId).put("layout", layoutId)
|
||||
require(!bindings.getBoolean("physical") && bindings.getJSONArray("keys").length() == 0)
|
||||
val doc = JSONObject(InputLibraries.encode(InputLibraries.read(context)))
|
||||
doc.getJSONArray("layouts").put(layout)
|
||||
doc.getJSONArray("bindings").put(bindings)
|
||||
val decoded = requireNotNull(InputLibraries.decode(doc.toString())) { "Invalid controls or bindings." }
|
||||
val saved = decoded.layouts.first { it.id == layoutId }
|
||||
val names = saved.elements.flatMap { listOf(it.image, it.stickImage) }.filter { it.isNotEmpty() }.toSet()
|
||||
require(files.keys == names.map { "images/$it" }.toSet()) { "Missing or unexpected button images." }
|
||||
var pixels = 0L
|
||||
val images = names.associateWith { name ->
|
||||
val data = files.getValue("images/$name")
|
||||
require(data.take(8) == listOf<Byte>(-119, 80, 78, 71, 13, 10, 26, 10))
|
||||
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
BitmapFactory.decodeByteArray(data, 0, data.size, bounds)
|
||||
require(bounds.outWidth in 1..1024 && bounds.outHeight in 1..1024)
|
||||
pixels += bounds.outWidth.toLong() * bounds.outHeight
|
||||
require(pixels <= 16_777_216)
|
||||
val bitmap = requireNotNull(BitmapFactory.decodeByteArray(data, 0, data.size))
|
||||
bitmap.recycle()
|
||||
data
|
||||
}
|
||||
return Pack(saved, decoded.preset(bindingId), images)
|
||||
}
|
||||
|
||||
fun importFile(context: Context, bytes: ByteArray, layout: SavedInputLayout, bindings: SavedInputBindings): Pack =
|
||||
try { parse(context, bytes) } catch (nativeFailure: Exception) {
|
||||
ArmsControlSkins.parse(context, bytes, layout, bindings, "Imported skin", nativeFailure)
|
||||
}
|
||||
|
||||
fun install(context: Context, pack: Pack, profile: String, role: InputRole): InputLibrary {
|
||||
require(pack.layout.supports(role))
|
||||
val written = mutableListOf<java.io.File>()
|
||||
try {
|
||||
val names = pack.images.mapValues { (_, bytes) ->
|
||||
val name = "key_${newInputId()}.png"
|
||||
val file = requireNotNull(InputButtonImages.file(context, name))
|
||||
file.parentFile!!.mkdirs()
|
||||
written += file
|
||||
file.writeBytes(bytes)
|
||||
name
|
||||
}
|
||||
val layout = pack.layout.copy(elements = pack.layout.elements.map { e -> e.copy(image = names[e.image] ?: "", stickImage = names[e.stickImage] ?: "") })
|
||||
return InputLibraries.update(context) {
|
||||
it.withLayout(layout).withPreset(pack.bindings).chooseLayout(profile, role, layout.id)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
written.forEach { it.delete() }
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
fun catalog(raw: String, source: ControlSources.Source = ControlSources.DROIDDECK): List<Entry> {
|
||||
require(raw.length <= 1_000_000)
|
||||
val doc = JSONObject(raw)
|
||||
val skin = doc.has("skins") && !doc.has("controls")
|
||||
require(skin || doc.getInt("version") == 1)
|
||||
val list = doc.getJSONArray(if (skin) "skins" else "controls")
|
||||
require(list.length() <= 256)
|
||||
return (0 until list.length()).map { index ->
|
||||
val e = list.getJSONObject(index)
|
||||
fun text(key: String) = e.getString(key).also { require(it.isNotBlank() && it.length <= 160) }
|
||||
val path = text("file")
|
||||
require(ControlSources.validPath(path) && path.endsWith(".zip", ignoreCase = true))
|
||||
val sha = e.optString("sha256").also { require(if (skin) it.isEmpty() || it.matches(Regex("[a-f0-9]{64}")) else it.matches(Regex("[a-f0-9]{64}"))) }
|
||||
Entry(text("name"), e.optString("author").take(160), e.optString("game").take(160), e.optString("license").take(160), path, sha,
|
||||
if (skin) InputLayoutScreen.BOTH else InputLayoutScreen.valueOf(e.getString("screen")), e.optString("preview").takeIf { it.isNotEmpty() }?.also {
|
||||
require(ControlSources.validPath(it) && it.endsWith(".png", ignoreCase = true))
|
||||
}, source = source, skin = skin)
|
||||
}.also { require(it.map { e -> e.path }.distinct().size == it.size) }
|
||||
}
|
||||
|
||||
fun bundled(context: Context): List<Entry> = context.assets.open("community-controls/catalog.json").use {
|
||||
catalog(readLimited(it, 1_000_000).toString(Charsets.UTF_8)).map { e -> e.copy(bundled = true) }
|
||||
}
|
||||
|
||||
fun fetchCatalog(source: ControlSources.Source = ControlSources.DROIDDECK): List<Entry> =
|
||||
catalog(get(source.manifest, 1_000_000).toString(Charsets.UTF_8), source)
|
||||
fun preview(context: Context, entry: Entry): android.graphics.Bitmap? {
|
||||
val path = entry.preview ?: return null
|
||||
val bytes = if (entry.bundled) context.assets.open("community-controls/$path").use { readLimited(it, 512 * 1024) }
|
||||
else get(entry.source.url(path), 2 * 1024 * 1024)
|
||||
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)
|
||||
require(bounds.outWidth in 1..4096 && bounds.outHeight in 1..4096)
|
||||
val options = BitmapFactory.Options().apply {
|
||||
inSampleSize = 1
|
||||
while (maxOf(bounds.outWidth, bounds.outHeight) / inSampleSize > 256) inSampleSize *= 2
|
||||
}
|
||||
return BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options)
|
||||
}
|
||||
|
||||
fun download(context: Context, entry: Entry, layout: SavedInputLayout? = null, bindings: SavedInputBindings? = null): Pack {
|
||||
val bytes = if (entry.bundled) context.assets.open("community-controls/${entry.path}").use { readLimited(it) }
|
||||
else get(entry.source.url(entry.path), if (entry.skin) 32 * 1024 * 1024 else MAX_BYTES)
|
||||
val sha = MessageDigest.getInstance("SHA-256").digest(bytes).joinToString("") { "%02x".format(it) }
|
||||
require(entry.sha256.isEmpty() && entry.skin || sha == entry.sha256) { "Controls download failed verification." }
|
||||
return if (entry.skin) ArmsControlSkins.parse(context, bytes, requireNotNull(layout), requireNotNull(bindings), entry.name)
|
||||
else parse(context, bytes).also { require(it.layout.screen == entry.screen) }
|
||||
}
|
||||
|
||||
private fun get(url: String, limit: Int): ByteArray {
|
||||
val connection = URL(url).openConnection() as HttpURLConnection
|
||||
connection.connectTimeout = 15_000
|
||||
connection.readTimeout = 30_000
|
||||
connection.instanceFollowRedirects = false
|
||||
return try {
|
||||
require(connection.responseCode == 200) { "Could not download community controls (${connection.responseCode})." }
|
||||
require(connection.contentLengthLong <= limit)
|
||||
connection.inputStream.use { readLimited(it, limit) }
|
||||
} finally { connection.disconnect() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.content.Context
|
||||
import org.json.JSONArray
|
||||
import java.net.URI
|
||||
import java.net.URLEncoder
|
||||
|
||||
internal object ControlSources {
|
||||
data class Source(val name: String, val manifest: String, val submit: String? = null, val builtIn: Boolean = false) {
|
||||
val id get() = manifest
|
||||
fun url(path: String): String {
|
||||
require(validPath(path)) { "Invalid controls source path." }
|
||||
return manifest.substringBeforeLast('/') + "/" + path.split('/').joinToString("/") {
|
||||
URLEncoder.encode(it, "UTF-8").replace("+", "%20")
|
||||
}
|
||||
}
|
||||
}
|
||||
val DROIDDECK = Source("DroidDeck", CommunityControls.BASE + "catalog.json", CommunityControls.SUBMIT, true)
|
||||
val ARMSX2 = Source("ARMSX2 community", "https://raw.githubusercontent.com/bagasromadon/ARMSX2-CustomControllerSkins/main/manifest.json",
|
||||
"https://github.com/bagasromadon/ARMSX2-CustomControllerSkins/issues/new", true)
|
||||
private fun prefs(context: Context) = context.getSharedPreferences("community-control-sources", Context.MODE_PRIVATE)
|
||||
|
||||
fun validPath(path: String) = path.length in 1..512 && path.split('/').all { it.isNotBlank() && it != "." && it != ".." } &&
|
||||
path.none { it.isISOControl() || it in "\\:%?#" } && !path.startsWith('/')
|
||||
|
||||
private fun https(raw: String): URI {
|
||||
require(raw.length <= 2048)
|
||||
val uri = URI(raw.trim())
|
||||
require(uri.scheme == "https" && !uri.host.isNullOrBlank() && uri.userInfo == null && uri.fragment == null && uri.query == null && !uri.path.isNullOrBlank() && !uri.path.endsWith('/')) {
|
||||
"Enter an HTTPS catalog URL or a GitHub repository URL."
|
||||
}
|
||||
return uri
|
||||
}
|
||||
|
||||
fun candidates(raw: String): List<Source> {
|
||||
val uri = https(raw)
|
||||
val parts = uri.path.trim('/').split('/')
|
||||
if (uri.host.equals("github.com", true)) {
|
||||
require(parts.size == 2 || parts.size >= 5 && parts[2] == "blob") { "Use a GitHub repository or manifest file URL." }
|
||||
require(parts.take(2).all { it.matches(Regex("[A-Za-z0-9_.-]+")) && it != "." && it != ".." })
|
||||
val repo = parts.take(2).joinToString("/")
|
||||
val submit = "https://github.com/$repo/issues/new"
|
||||
val base = "https://raw.githubusercontent.com/$repo/"
|
||||
return if (parts.size == 2) listOf("catalog.json", "manifest.json").map { Source(repo, base + "main/" + it, submit) }
|
||||
else listOf(Source(repo, base + parts.drop(3).joinToString("/"), submit))
|
||||
}
|
||||
val submit = if (uri.host.equals("raw.githubusercontent.com", true) && parts.size >= 4)
|
||||
"https://github.com/${parts[0]}/${parts[1]}/issues/new" else null
|
||||
return listOf(Source(if (submit != null) parts.take(2).joinToString("/") else uri.host, uri.toASCIIString(), submit))
|
||||
}
|
||||
|
||||
fun read(context: Context): List<Source> {
|
||||
val custom = runCatching {
|
||||
val raw = prefs(context).getString("sources", "[]")!!
|
||||
require(raw.length <= 32_000)
|
||||
val array = JSONArray(raw)
|
||||
require(array.length() <= 16)
|
||||
(0 until array.length()).map { candidates(array.getString(it)).single() }
|
||||
}.getOrDefault(emptyList())
|
||||
return (listOf(DROIDDECK, ARMSX2) + custom).distinctBy { it.id }
|
||||
}
|
||||
|
||||
fun add(context: Context, source: Source) {
|
||||
val list = read(context)
|
||||
require(list.none { it.id == source.id }) { "This source is already connected." }
|
||||
require(list.size < 18) { "Remove a source before adding another." }
|
||||
save(context, list + source)
|
||||
}
|
||||
fun remove(context: Context, source: Source) {
|
||||
require(!source.builtIn)
|
||||
save(context, read(context).filterNot { it.id == source.id })
|
||||
}
|
||||
private fun save(context: Context, sources: List<Source>) {
|
||||
check(prefs(context).edit().putString("sources", JSONArray(sources.filterNot { it.builtIn }.map { it.manifest }).toString()).commit()) {
|
||||
"Could not save controls sources."
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.content.Context
|
||||
|
||||
object GameInputControls {
|
||||
private fun prefs(context: Context) = context.getSharedPreferences("input-game-controls", Context.MODE_PRIVATE)
|
||||
fun profile(context: Context, game: String?): String? = game?.let { prefs(context).getString(it, null) }
|
||||
fun set(context: Context, game: String, profile: String?) {
|
||||
require(game.isNotBlank() && game.length <= 512)
|
||||
require(profile == null || InputLibraries.read(context).profiles.any { it.id == profile })
|
||||
val edit = prefs(context).edit()
|
||||
if (profile == null) edit.remove(game) else edit.putString(game, profile)
|
||||
check(edit.commit()) { "Could not save game controls." }
|
||||
}
|
||||
fun resolve(context: Context, library: InputLibrary, desktop: Boolean, game: String?): InputLibrary {
|
||||
val selection = library.selection(desktop)
|
||||
if (game == null || selection.profile != InputProfiles.AUTO) return library
|
||||
val target = profile(context, game)?.let { id -> library.profiles.firstOrNull { it.id == id } } ?: return library
|
||||
var result = library
|
||||
for (role in listOf(InputRole.PRIMARY, InputRole.SECONDARY)) {
|
||||
if (role !in selection.parts) result = result.selectPart(desktop, role, target.binding(role))
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@ import org.json.JSONObject
|
||||
import java.util.UUID
|
||||
|
||||
object InputLibraries {
|
||||
private const val VERSION = 14
|
||||
private const val VERSION = 15
|
||||
private const val KEY = "library"
|
||||
private const val RECOVERY = "library-recovery."
|
||||
const val OVERLAY = "builtin.overlay"
|
||||
@@ -304,7 +304,7 @@ object InputLibraries {
|
||||
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))
|
||||
.put("elementOpacity", e.opacity.toDouble()).put("buttonShape", e.buttonShape.name).put("showLabel", e.showLabel).put("alwaysShown", e.alwaysShown).put("stickImage", e.stickImage))
|
||||
layouts.put(JSONObject().put("id", layout.id).put("name", layout.name).put("template", layout.template.name).put("elements", elements)
|
||||
.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))
|
||||
@@ -345,7 +345,7 @@ object InputLibraries {
|
||||
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))
|
||||
e.optDouble("elementOpacity", 1.0).toFloat(), InputButtonShape.valueOf(e.optString("buttonShape", InputButtonShape.ROUNDED.name)), e.optBoolean("showLabel", true), e.optBoolean("alwaysShown", false), e.optString("stickImage", ""))
|
||||
}
|
||||
SavedInputLayout(layout.getString("id"), layout.getString("name"), elements, InputLayoutTemplate.valueOf(layout.getString("template")),
|
||||
InputSurfaceStyle(if (!layout.has("tint")) ControllerPrefs.STEAM_BLUE else if (layout.isNull("tint")) null else layout.getInt("tint"), layout.optInt("opacity", 100),
|
||||
|
||||
@@ -244,7 +244,8 @@ data class InputLibrary(
|
||||
for (e in layout.elements) {
|
||||
inputName(e.name)
|
||||
require(e.icon == 0 || InputButtonIcons.has(e.icon))
|
||||
require(e.image.isEmpty() || e.image.matches(Regex("[A-Za-z0-9_.-]{1,128}")) && e.image != "." && e.image != "..")
|
||||
for (image in listOf(e.image, e.stickImage))
|
||||
require(image.isEmpty() || image.matches(Regex("[A-Za-z0-9_.-]{1,128}")) && image != "." && image != "..")
|
||||
require(e.opacity.isFinite() && e.opacity in 0.01f..1f)
|
||||
require(!e.toggle || e.kind == InputElementKind.BUTTON || e.kind == InputElementKind.TRIGGER)
|
||||
require(listOf(e.x, e.y, e.width, e.height).all { it.isFinite() })
|
||||
|
||||
@@ -35,6 +35,7 @@ data class InputSurfaceElement(
|
||||
val buttonShape: InputButtonShape = InputButtonShape.ROUNDED,
|
||||
val showLabel: Boolean = true,
|
||||
val alwaysShown: Boolean = false,
|
||||
val stickImage: String = "",
|
||||
) {
|
||||
val hasClick get() = kind == InputElementKind.STICK || kind == InputElementKind.TRACKPAD
|
||||
|
||||
|
||||
@@ -150,8 +150,37 @@ object BootMovie {
|
||||
folder.listFiles()?.forEach { if (it.name != keep) it.delete() }
|
||||
}
|
||||
|
||||
internal fun syncShuffleFromSteam(context: Context, config: File) = syncShuffleFromSteam(context, listOf(config))
|
||||
|
||||
// Staging writes Shuffle and its baseline under the same lock, so a poll never reads a half-staged value as Steam's.
|
||||
internal fun syncShuffleFromSteam(context: Context, configs: List<File>) = synchronized(SessionFiles.STEAM_CONFIG) {
|
||||
val read = configs.mapNotNull { config -> SessionFiles.startupMovieShuffle(config)?.let { config to it } }
|
||||
val (known, unseen) = read.partition { (config, _) -> SessionPrefs.bootMovieShuffleSeen(context, config) != null }
|
||||
var changed = false
|
||||
known.forEach { (config, steam) ->
|
||||
if (SessionPrefs.bootMovieShuffleSeen(context, config) != steam) {
|
||||
SessionPrefs.setBootMovieShuffle(context, steam)
|
||||
changed = true
|
||||
}
|
||||
SessionPrefs.setBootMovieShuffleSeen(context, config, steam)
|
||||
}
|
||||
// A config read for the first time only sets the choice when no known config changed, so it cannot undo a change.
|
||||
unseen.forEach { (config, steam) ->
|
||||
if (!changed && SessionPrefs.bootMovieShuffle(context) != steam) {
|
||||
SessionPrefs.setBootMovieShuffle(context, steam)
|
||||
changed = true
|
||||
}
|
||||
SessionPrefs.setBootMovieShuffleSeen(context, config, steam)
|
||||
}
|
||||
}
|
||||
|
||||
fun syncFromSteam(context: Context): Boolean {
|
||||
val named = SessionFiles.startupMovieLocalPath(BootMovieLibrary.steamConfig(context)) ?: return false
|
||||
val active = BootMovieLibrary.steamConfig(context)
|
||||
syncShuffleFromSteam(
|
||||
context,
|
||||
BootMovieLibrary.steamRoots(context).map { File(it, "config/config.vdf") }.filter { it != active } + active,
|
||||
)
|
||||
val named = SessionFiles.startupMovieLocalPath(active) ?: return false
|
||||
val seen = SessionPrefs.bootMovieSteamSeen(context)
|
||||
if (named == seen) return false
|
||||
SessionPrefs.setBootMovieSteamSeen(context, named)
|
||||
|
||||
@@ -20,6 +20,7 @@ object GameProfileManager {
|
||||
}
|
||||
clear("Proton") { ProtonDefault.requestGame(context, scope, null) }
|
||||
clear("component packages") { ComponentsManager.clearGameComponents(context, scope) }
|
||||
clear("on-screen controls") { com.droiddeck.launcher.input.GameInputControls.set(context, scope, null) }
|
||||
clear("texture filtering") { SessionPrefs.clearGameTextureFiltering(context, scope) }
|
||||
clear("Windows components") { WinComponents.setPicks(context, scope, emptyList()) }
|
||||
|
||||
|
||||
@@ -14,6 +14,9 @@ import com.droiddeck.launcher.runtime.ProotFastPath
|
||||
import java.io.File
|
||||
|
||||
object SessionFiles {
|
||||
// Session start and Flatpak staging can both rewrite Steam's config.vdf; one writer at a time.
|
||||
internal val STEAM_CONFIG = Any()
|
||||
|
||||
private const val TAG = "SessionFiles"
|
||||
private const val NO_PAD_SWITCH = "Download/droiddeck-no-pad"
|
||||
const val DIRECTAUDIO_DIR = "usr/local/lib/directaudio"
|
||||
@@ -357,6 +360,11 @@ object SessionFiles {
|
||||
"staged=$bigPictureMovieInstalled done=$done steam=${home.path} config: $before -> ${startupMoviePath(config)}",
|
||||
)
|
||||
if (startsSession) {
|
||||
synchronized(STEAM_CONFIG) {
|
||||
val shuffle = SessionPrefs.bootMovieShuffle(context)
|
||||
setStartupMovieShuffle(config, shuffle)
|
||||
if (startupMovieShuffle(config) == shuffle) SessionPrefs.setBootMovieShuffleSeen(context, config, shuffle)
|
||||
}
|
||||
disableIdleSleep(home)
|
||||
seedUserDefaults(home)
|
||||
}
|
||||
@@ -369,28 +377,30 @@ object SessionFiles {
|
||||
}
|
||||
|
||||
internal fun resetMissingStartupMovie(config: File, force: Boolean): Boolean {
|
||||
if (!config.isFile) return true
|
||||
val text = runCatching { config.readText() }.getOrElse {
|
||||
Log.w(TAG, "could not read Steam config to reset the startup movie", it)
|
||||
return false
|
||||
}
|
||||
val movie = activeStartupMovie(text) ?: return true
|
||||
val block = text.substring(movie.keyStart, movie.close + 1)
|
||||
val path = scalar(block, "LocalPath").orEmpty()
|
||||
if (path.isEmpty()) return true
|
||||
val missing = File(config.parentFile, "uioverrides/movies/" + path.removePrefix(BOOT_MOVIES_DIR))
|
||||
val gone = path.startsWith(BOOT_MOVIES_DIR) && !missing.isFile && (force || path == BOOT_MOVIE_PATH)
|
||||
if (!gone) return false
|
||||
val newline = if (text.contains("\r\n")) "\r\n" else "\n"
|
||||
val updated = setScalar(setScalar(block, "MovieID", "0", newline), "LocalPath", "", newline)
|
||||
val staged = File(config.parentFile, config.name + ".staged")
|
||||
return try {
|
||||
staged.writeText(text.replaceRange(movie.keyStart, movie.close + 1, updated))
|
||||
(staged.renameTo(config)).also { if (!it) staged.delete() }
|
||||
} catch (e: Exception) {
|
||||
staged.delete()
|
||||
Log.w(TAG, "could not reset Steam startup movie selection", e)
|
||||
false
|
||||
synchronized(STEAM_CONFIG) {
|
||||
if (!config.isFile) return true
|
||||
val text = runCatching { config.readText() }.getOrElse {
|
||||
Log.w(TAG, "could not read Steam config to reset the startup movie", it)
|
||||
return false
|
||||
}
|
||||
val movie = activeStartupMovie(text) ?: return true
|
||||
val block = text.substring(movie.keyStart, movie.close + 1)
|
||||
val path = scalar(block, "LocalPath").orEmpty()
|
||||
if (path.isEmpty()) return true
|
||||
val missing = File(config.parentFile, "uioverrides/movies/" + path.removePrefix(BOOT_MOVIES_DIR))
|
||||
val gone = path.startsWith(BOOT_MOVIES_DIR) && !missing.isFile && (force || path == BOOT_MOVIE_PATH)
|
||||
if (!gone) return false
|
||||
val newline = if (text.contains("\r\n")) "\r\n" else "\n"
|
||||
val updated = setScalar(setScalar(block, "MovieID", "0", newline), "LocalPath", "", newline)
|
||||
val staged = File(config.parentFile, config.name + ".staged")
|
||||
return try {
|
||||
staged.writeText(text.replaceRange(movie.keyStart, movie.close + 1, updated))
|
||||
(staged.renameTo(config)).also { if (!it) staged.delete() }
|
||||
} catch (e: Exception) {
|
||||
staged.delete()
|
||||
Log.w(TAG, "could not reset Steam startup movie selection", e)
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -491,6 +501,42 @@ object SessionFiles {
|
||||
return scalar(text.substring(movie.keyStart, movie.close + 1), "LocalPath")
|
||||
}
|
||||
|
||||
internal fun startupMovieShuffle(config: File): Boolean? {
|
||||
val text = runCatching { config.readText() }.getOrNull() ?: return null
|
||||
val movie = activeStartupMovie(text) ?: return false
|
||||
return scalar(text.substring(movie.keyStart, movie.close + 1), "Shuffle") == "1"
|
||||
}
|
||||
|
||||
internal fun withStartupMovieShuffle(text: String, on: Boolean): String {
|
||||
val newline = if (text.contains("\r\n")) "\r\n" else "\n"
|
||||
val value = if (on) "1" else "0"
|
||||
return listOfNotNull(customizationMovie(text), olderMovie(text)).sortedByDescending { it.keyStart }.fold(text) { acc, movie ->
|
||||
val block = acc.substring(movie.keyStart, movie.close + 1)
|
||||
if (!on && scalar(block, "Shuffle") == null) acc else acc.replaceRange(movie.keyStart, movie.close + 1, setScalar(block, "Shuffle", value, newline))
|
||||
}
|
||||
}
|
||||
|
||||
internal fun setStartupMovieShuffle(config: File, on: Boolean): Boolean {
|
||||
synchronized(STEAM_CONFIG) {
|
||||
if (!config.isFile) return false
|
||||
val text = runCatching { config.readText() }.getOrElse {
|
||||
Log.w(TAG, "could not read Steam config to set the startup movie shuffle", it)
|
||||
return false
|
||||
}
|
||||
val updated = withStartupMovieShuffle(text, on)
|
||||
if (updated == text) return true
|
||||
val staged = File(config.parentFile, config.name + ".staged")
|
||||
return try {
|
||||
staged.writeText(updated)
|
||||
staged.renameTo(config).also { if (!it) staged.delete() }
|
||||
} catch (e: Exception) {
|
||||
staged.delete()
|
||||
Log.w(TAG, "could not set Steam startup movie shuffle", e)
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal fun startupMovieBlock(config: File): String? {
|
||||
val text = runCatching { config.readText() }.getOrNull() ?: return null
|
||||
val parts = listOfNotNull(
|
||||
@@ -513,69 +559,71 @@ object SessionFiles {
|
||||
}
|
||||
|
||||
internal fun ensureStartupMovieDefault(config: File, force: Boolean = false): Boolean {
|
||||
val path = BOOT_MOVIE_PATH
|
||||
val legacyPath = "/uioverrides/movies/droiddeck-startup.webm"
|
||||
var text = if (config.isFile) runCatching { config.readText() }.getOrElse {
|
||||
Log.w(TAG, "could not read Steam config for startup movie", it)
|
||||
return false
|
||||
} else ""
|
||||
val newline = if (text.contains("\r\n")) "\r\n" else "\n"
|
||||
val custom = customizationMovie(text)
|
||||
val active = custom ?: olderMovie(text)
|
||||
if (active != null) {
|
||||
val block = text.substring(active.keyStart, active.close + 1)
|
||||
val selectedId = scalar(block, "MovieID")
|
||||
val selectedPath = scalar(block, "LocalPath")
|
||||
if (selectedPath == path && custom != null) {
|
||||
Log.i(TAG, "Steam startup movie is set to DroidDeck")
|
||||
return true
|
||||
}
|
||||
val legacyDefault = selectedId == "0" && selectedPath == legacyPath
|
||||
val hasExplicitSelection =
|
||||
(!selectedId.isNullOrEmpty() && selectedId != "0") || !selectedPath.isNullOrEmpty()
|
||||
if (!force && !legacyDefault && hasExplicitSelection && selectedPath != path) {
|
||||
Log.i(TAG, "Steam startup movie selection preserved")
|
||||
synchronized(STEAM_CONFIG) {
|
||||
val path = BOOT_MOVIE_PATH
|
||||
val legacyPath = "/uioverrides/movies/droiddeck-startup.webm"
|
||||
var text = if (config.isFile) runCatching { config.readText() }.getOrElse {
|
||||
Log.w(TAG, "could not read Steam config for startup movie", it)
|
||||
return false
|
||||
}
|
||||
}
|
||||
val targets = listOfNotNull(customizationMovie(text), olderMovie(text)).sortedByDescending { it.keyStart }
|
||||
for (target in targets) text = pointAt(text, target, path, newline)
|
||||
if (olderMovie(text) == null) {
|
||||
val steam = findSteamBlock(text)
|
||||
if (steam == null) {
|
||||
if (text.isNotBlank() && customizationMovie(text) == null) {
|
||||
Log.w(TAG, "Steam config has no Steam settings block; startup movie default not set")
|
||||
} else ""
|
||||
val newline = if (text.contains("\r\n")) "\r\n" else "\n"
|
||||
val custom = customizationMovie(text)
|
||||
val active = custom ?: olderMovie(text)
|
||||
if (active != null) {
|
||||
val block = text.substring(active.keyStart, active.close + 1)
|
||||
val selectedId = scalar(block, "MovieID")
|
||||
val selectedPath = scalar(block, "LocalPath")
|
||||
if (selectedPath == path && custom != null) {
|
||||
Log.i(TAG, "Steam startup movie is set to DroidDeck")
|
||||
return true
|
||||
}
|
||||
val legacyDefault = selectedId == "0" && selectedPath == legacyPath
|
||||
val hasExplicitSelection =
|
||||
(!selectedId.isNullOrEmpty() && selectedId != "0") || !selectedPath.isNullOrEmpty()
|
||||
if (!force && !legacyDefault && hasExplicitSelection && selectedPath != path) {
|
||||
Log.i(TAG, "Steam startup movie selection preserved")
|
||||
return false
|
||||
}
|
||||
if (text.isBlank()) {
|
||||
text = "\"InstallConfigStore\"${newline}{${newline}\t\"Software\"${newline}\t{${newline}\t\t\"Valve\"${newline}\t\t{${newline}\t\t\t\"Steam\"${newline}\t\t\t{${newline}"
|
||||
val section = startupMovieSection("\t\t\t\t", path, newline)
|
||||
text += section + newline + "\t\t\t}" + newline + "\t\t}" + newline + "\t}" + newline + "}"
|
||||
}
|
||||
val targets = listOfNotNull(customizationMovie(text), olderMovie(text)).sortedByDescending { it.keyStart }
|
||||
for (target in targets) text = pointAt(text, target, path, newline)
|
||||
if (olderMovie(text) == null) {
|
||||
val steam = findSteamBlock(text)
|
||||
if (steam == null) {
|
||||
if (text.isNotBlank() && customizationMovie(text) == null) {
|
||||
Log.w(TAG, "Steam config has no Steam settings block; startup movie default not set")
|
||||
return false
|
||||
}
|
||||
if (text.isBlank()) {
|
||||
text = "\"InstallConfigStore\"${newline}{${newline}\t\"Software\"${newline}\t{${newline}\t\t\"Valve\"${newline}\t\t{${newline}\t\t\t\"Steam\"${newline}\t\t\t{${newline}"
|
||||
val section = startupMovieSection("\t\t\t\t", path, newline)
|
||||
text += section + newline + "\t\t\t}" + newline + "\t\t}" + newline + "\t}" + newline + "}"
|
||||
}
|
||||
} else {
|
||||
val lineStart = text.lastIndexOf('\n', steam.close).let { if (it < 0) 0 else it + 1 }
|
||||
val indent = text.substring(lineStart, steam.close).takeWhile { it == '\t' || it == ' ' }
|
||||
val section = startupMovieSection(indent + "\t", path, newline)
|
||||
text = text.substring(0, lineStart) + section + newline + indent + text.substring(lineStart)
|
||||
}
|
||||
} else {
|
||||
val lineStart = text.lastIndexOf('\n', steam.close).let { if (it < 0) 0 else it + 1 }
|
||||
val indent = text.substring(lineStart, steam.close).takeWhile { it == '\t' || it == ' ' }
|
||||
val section = startupMovieSection(indent + "\t", path, newline)
|
||||
text = text.substring(0, lineStart) + section + newline + indent + text.substring(lineStart)
|
||||
}
|
||||
}
|
||||
if (customizationMovie(text) == null) text = withCustomization(text, path, newline)
|
||||
val staged = File(config.parentFile, config.name + ".staged")
|
||||
return try {
|
||||
config.parentFile?.mkdirs()
|
||||
staged.writeText(text)
|
||||
if (!staged.renameTo(config)) {
|
||||
if (customizationMovie(text) == null) text = withCustomization(text, path, newline)
|
||||
val staged = File(config.parentFile, config.name + ".staged")
|
||||
return try {
|
||||
config.parentFile?.mkdirs()
|
||||
staged.writeText(text)
|
||||
if (!staged.renameTo(config)) {
|
||||
staged.delete()
|
||||
Log.e(TAG, "could not write Steam startup movie selection")
|
||||
false
|
||||
} else {
|
||||
Log.i(TAG, "Steam startup movie default selected")
|
||||
true
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
staged.delete()
|
||||
Log.e(TAG, "could not write Steam startup movie selection")
|
||||
Log.w(TAG, "could not write Steam startup movie selection", e)
|
||||
false
|
||||
} else {
|
||||
Log.i(TAG, "Steam startup movie default selected")
|
||||
true
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
staged.delete()
|
||||
Log.w(TAG, "could not write Steam startup movie selection", e)
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -661,32 +709,34 @@ object SessionFiles {
|
||||
private val IDLE_SLEEP_TIMERS = listOf("IdleSuspendBatterySeconds", "IdleSuspendACSeconds")
|
||||
|
||||
internal fun disableIdleSleep(steamHome: File): Boolean {
|
||||
val config = File(steamHome, "config/config.vdf")
|
||||
val text = runCatching { config.readText() }.getOrNull() ?: return false
|
||||
val newline = if (text.contains("\r\n")) "\r\n" else "\n"
|
||||
val steam = findSteamBlock(text) ?: return false
|
||||
val system = findObject(text, "system", steam.open + 1, steam.close)
|
||||
val updated = if (system != null) {
|
||||
val block = text.substring(system.keyStart, system.close + 1)
|
||||
text.replaceRange(system.keyStart, system.close + 1, IDLE_SLEEP_TIMERS.fold(block) { acc, key -> setScalar(acc, key, "0", newline) })
|
||||
} else {
|
||||
val lineStart = text.lastIndexOf('\n', steam.close).let { if (it < 0) 0 else it + 1 }
|
||||
val indent = text.substring(lineStart, steam.close).takeWhile { it == '\t' || it == ' ' } + "\t"
|
||||
val section = (listOf(indent + "\"system\"", indent + "{") +
|
||||
IDLE_SLEEP_TIMERS.map { "$indent\t\"$it\"\t\t\"0\"" } + (indent + "}")).joinToString(newline) + newline
|
||||
text.substring(0, lineStart) + section + text.substring(lineStart)
|
||||
}
|
||||
val staged = File(config.parentFile, config.name + ".staged")
|
||||
return try {
|
||||
if (updated != text) {
|
||||
staged.writeText(updated)
|
||||
if (!staged.renameTo(config)) { staged.delete(); return false }
|
||||
synchronized(STEAM_CONFIG) {
|
||||
val config = File(steamHome, "config/config.vdf")
|
||||
val text = runCatching { config.readText() }.getOrNull() ?: return false
|
||||
val newline = if (text.contains("\r\n")) "\r\n" else "\n"
|
||||
val steam = findSteamBlock(text) ?: return false
|
||||
val system = findObject(text, "system", steam.open + 1, steam.close)
|
||||
val updated = if (system != null) {
|
||||
val block = text.substring(system.keyStart, system.close + 1)
|
||||
text.replaceRange(system.keyStart, system.close + 1, IDLE_SLEEP_TIMERS.fold(block) { acc, key -> setScalar(acc, key, "0", newline) })
|
||||
} else {
|
||||
val lineStart = text.lastIndexOf('\n', steam.close).let { if (it < 0) 0 else it + 1 }
|
||||
val indent = text.substring(lineStart, steam.close).takeWhile { it == '\t' || it == ' ' } + "\t"
|
||||
val section = (listOf(indent + "\"system\"", indent + "{") +
|
||||
IDLE_SLEEP_TIMERS.map { "$indent\t\"$it\"\t\t\"0\"" } + (indent + "}")).joinToString(newline) + newline
|
||||
text.substring(0, lineStart) + section + text.substring(lineStart)
|
||||
}
|
||||
val staged = File(config.parentFile, config.name + ".staged")
|
||||
return try {
|
||||
if (updated != text) {
|
||||
staged.writeText(updated)
|
||||
if (!staged.renameTo(config)) { staged.delete(); return false }
|
||||
}
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
staged.delete()
|
||||
Log.w(TAG, "could not disable Steam's idle sleep", e)
|
||||
false
|
||||
}
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
staged.delete()
|
||||
Log.w(TAG, "could not disable Steam's idle sleep", e)
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -738,7 +788,7 @@ object SessionFiles {
|
||||
}
|
||||
|
||||
private fun setScalar(block: String, key: String, value: String, newline: String): String {
|
||||
val pattern = Regex("(?m)^([\\t ]*\"${Regex.escape(key)}\"[\\t ]+)\"[^\"\\r\\n]*\"([\\t ]*)$")
|
||||
val pattern = Regex("(?m)^([\\t ]*\"${Regex.escape(key)}\"[\\t ]+)\"[^\"\\r\\n]*\"([\\t ]*(?://[^\\r\\n]*)?)$")
|
||||
val match = pattern.find(block)
|
||||
if (match != null) return block.replaceRange(match.range, match.groupValues[1] + "\"" + value + "\"" + match.groupValues[2])
|
||||
val close = block.lastIndexOf('}')
|
||||
|
||||
@@ -1229,6 +1229,13 @@ object SessionPrefs {
|
||||
fun setBootMovieApplyNext(context: Context, on: Boolean) { prefs(context).edit().putBoolean("bootMovieApplyNext", on).apply() }
|
||||
fun bootMovieSteamSeen(context: Context): String? = prefs(context).getString("bootMovieSteamSeen", null)
|
||||
fun setBootMovieSteamSeen(context: Context, path: String) { prefs(context).edit().putString("bootMovieSteamSeen", path).apply() }
|
||||
fun bootMovieShuffle(context: Context): Boolean = prefs(context).getBoolean("bootMovieShuffle", false)
|
||||
fun setBootMovieShuffle(context: Context, on: Boolean) { prefs(context).edit().putBoolean("bootMovieShuffle", on).apply() }
|
||||
fun bootMovieShuffleSeen(context: Context, config: java.io.File): Boolean? {
|
||||
val key = "bootMovieShuffleSeen:${config.path}"
|
||||
return prefs(context).takeIf { it.contains(key) }?.getBoolean(key, false)
|
||||
}
|
||||
fun setBootMovieShuffleSeen(context: Context, config: java.io.File, on: Boolean) { prefs(context).edit().putBoolean("bootMovieShuffleSeen:${config.path}", on).apply() }
|
||||
fun bootMovieCustomName(context: Context): String? = prefs(context).getString("bootMovieCustomName", null)
|
||||
fun setBootMovieCustomName(context: Context, name: String?) {
|
||||
prefs(context).edit().apply { if (name == null) remove("bootMovieCustomName") else putString("bootMovieCustomName", name) }.apply()
|
||||
|
||||
@@ -26,7 +26,7 @@ object SettingsReset {
|
||||
"guestHostname", "fexPreset", "forceSsbs", "logs", "gameDebugLogsEnabled", "enhancedDiagnosticsNext", "storageDiagnostics", "buildWatermark",
|
||||
"upscaler", "upscaleSharpness", "screenEffects", "textureAnisotropy", "textureLodBias",
|
||||
"steamDownloadsInBackground", "steam_offline", "bootMovie", "bootMovieSound", "bootMovieVolume", "bootMovieSeconds", "skipBootMovie",
|
||||
"bootMovieApplyNext", "bootMovieSteamSeen",
|
||||
"bootMovieApplyNext", "bootMovieSteamSeen", "bootMovieShuffle",
|
||||
"questDefaultsV1", "telemetryAuto", "telemetryOff", "statsStrip", "statsHud", "bottomHud", "bottomStripMetrics", "bottomStripTabs", "statsDash", "statsSpeedUnit",
|
||||
)
|
||||
|
||||
|
||||
@@ -3,10 +3,8 @@ package com.droiddeck.launcher.stores
|
||||
import android.content.Context
|
||||
import android.os.StatFs
|
||||
import android.os.storage.StorageManager
|
||||
import com.droiddeck.launcher.frontend.AddedGames
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.session.GameStorage
|
||||
import com.droiddeck.launcher.session.SecondaryLibrary
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import java.io.File
|
||||
import java.util.zip.CRC32
|
||||
@@ -14,7 +12,6 @@ import java.util.zip.CRC32
|
||||
object StoreInstallRoot {
|
||||
const val SPACE_UNKNOWN = -1L
|
||||
private const val INTERNAL = "root/Games/Stores"
|
||||
const val INTERNAL_GUEST = "/$INTERNAL"
|
||||
private const val ON_VOLUME = "Games"
|
||||
const val GUEST_EXTERNAL = "/mnt/droiddeck-stores"
|
||||
|
||||
@@ -182,24 +179,6 @@ object StoreInstallRoot {
|
||||
fun externalBindSpecsForXodus(context: Context): List<String> =
|
||||
externalBindSpecs(externalRootsForXodus(context), LinuxRuntime.rootDir(context))
|
||||
|
||||
fun guestBinds(context: Context): List<String> {
|
||||
val out = ArrayList<String>(externalBindSpecs(context))
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
GameStorage.effective(context)?.takeIf { File(it.path).isDirectory }?.let { library ->
|
||||
val content = SecondaryLibrary.contentPath(File(library.path)).path
|
||||
for (guest in SecondaryLibrary.CARD_GUESTS) {
|
||||
File(root, guest.removePrefix("/")).mkdirs()
|
||||
out += "$content:$guest"
|
||||
}
|
||||
}
|
||||
for (folder in AddedGames.roots(context)) {
|
||||
if (!folder.host.isDirectory || !folder.host.canRead()) continue
|
||||
File(root, folder.guest.removePrefix("/")).mkdirs()
|
||||
out += folder.host.path + ":" + folder.guest
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
internal fun externalBindSpecs(roots: List<Pair<File, String>>, guestRoot: File): List<String> =
|
||||
roots.mapNotNull { (host, guest) ->
|
||||
if (!host.isDirectory || !host.canRead()) return@mapNotNull null
|
||||
|
||||
@@ -7,7 +7,9 @@ import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.frontend.AddedGames
|
||||
import com.droiddeck.launcher.runtime.BattleNet
|
||||
import com.droiddeck.launcher.runtime.GuestCommand
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.session.GameStorage
|
||||
import com.droiddeck.launcher.session.SecondaryLibrary
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.InstalledStoreGame
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
@@ -73,10 +75,22 @@ object BattleNetInstall {
|
||||
}
|
||||
|
||||
internal fun binds(context: Context): List<String> {
|
||||
val out = ArrayList<String>(StoreInstallRoot.externalBindSpecs(context))
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
GameStorage.effective(context)?.let { library ->
|
||||
if (!File(library.path).isDirectory) throw IllegalStateException(context.getString(R.string.game_sync_err_game_storage))
|
||||
val content = SecondaryLibrary.contentPath(File(library.path)).path
|
||||
for (guest in SecondaryLibrary.CARD_GUESTS) {
|
||||
File(root, guest.removePrefix("/")).mkdirs()
|
||||
out += "$content:$guest"
|
||||
}
|
||||
}
|
||||
return StoreInstallRoot.guestBinds(context)
|
||||
for (folder in AddedGames.roots(context)) {
|
||||
if (!folder.host.isDirectory || !folder.host.canRead()) continue
|
||||
File(root, folder.guest.removePrefix("/")).mkdirs()
|
||||
out += folder.host.path + ":" + folder.guest
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
internal fun run(context: Context, args: List<String>, cancelled: AtomicBoolean?, onLine: (String) -> Unit): Int =
|
||||
|
||||
@@ -4,6 +4,7 @@ import android.content.Context;
|
||||
import android.util.Log;
|
||||
|
||||
import com.droiddeck.launcher.frontend.AddedGames;
|
||||
import com.droiddeck.launcher.runtime.GuestCommand;
|
||||
import com.droiddeck.launcher.stores.StoreLanguage;
|
||||
import com.droiddeck.launcher.stores.StoreLog;
|
||||
import com.droiddeck.launcher.stores.download.StoreDownloadTier;
|
||||
@@ -270,10 +271,11 @@ public final class GogDownloadManager {
|
||||
long planned = 0;
|
||||
boolean sized = true;
|
||||
for (InstallerPart part : parts) { planned += part.size; if (part.size <= 0) sized = false; }
|
||||
long needed = installerBytesNeeded(knownPartBytes(parts), GogLibrary.INSTANCE.sizeOf(ctx, game.gameId));
|
||||
long usable = com.droiddeck.launcher.stores.StoreInstallRoot.availableBytes(installPath) + reclaimableInstallerBytes(installPath, parts);
|
||||
if (com.droiddeck.launcher.stores.StoreInstallRoot.insufficientSpace(needed, usable)) {
|
||||
throw new InstallException("Not enough free space: need " + formatBytes(needed) + ", only " + formatBytes(usable) + " free");
|
||||
if (sized) {
|
||||
long usable = com.droiddeck.launcher.stores.StoreInstallRoot.availableBytes(installPath);
|
||||
if (com.droiddeck.launcher.stores.StoreInstallRoot.insufficientSpace(planned, usable)) {
|
||||
throw new InstallException("Not enough free space: need " + formatBytes(planned) + ", only " + formatBytes(usable) + " free");
|
||||
}
|
||||
}
|
||||
long total = 0;
|
||||
for (InstallerPart part : parts) {
|
||||
@@ -325,7 +327,10 @@ public final class GogDownloadManager {
|
||||
cb.onProgress("Extracting installer…", 95);
|
||||
int rc;
|
||||
try {
|
||||
rc = GogInnoextract.extract(ctx, guestSetup, guestDir, "gog-innoextract", cancelled,
|
||||
rc = GuestCommand.INSTANCE.run(ctx, Arrays.asList(
|
||||
"/usr/local/bin/droiddeck-innoextract", "--gog", "--silent",
|
||||
"-d", guestDir, guestSetup),
|
||||
false, "gog-innoextract", null, null, false, cancelled,
|
||||
line -> { cb.onLog("gog innoextract: " + line); return kotlin.Unit.INSTANCE; });
|
||||
} catch (Exception e) {
|
||||
throw new InstallException("The installer could not be extracted: " + e.getClass().getSimpleName());
|
||||
@@ -334,28 +339,6 @@ public final class GogDownloadManager {
|
||||
if (rc != 0) throw new InstallException("The installer could not be extracted (innoextract exit " + rc + ")");
|
||||
}
|
||||
|
||||
static long knownPartBytes(List<InstallerPart> parts) {
|
||||
long known = 0;
|
||||
for (InstallerPart part : parts) if (part.size > 0) known += part.size;
|
||||
return known;
|
||||
}
|
||||
|
||||
static long reclaimableInstallerBytes(File installPath, List<InstallerPart> parts) {
|
||||
long reclaimed = 0;
|
||||
for (InstallerPart part : parts) {
|
||||
try {
|
||||
File existing = installerDestination(installPath, part.filename);
|
||||
if (existing.isFile()) reclaimed += existing.length();
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
}
|
||||
return reclaimed;
|
||||
}
|
||||
|
||||
static long installerBytesNeeded(long downloadBytes, long installedBytes) {
|
||||
return Math.max(0, downloadBytes) + Math.max(0, installedBytes);
|
||||
}
|
||||
|
||||
static final class InstallerPart {
|
||||
final String url;
|
||||
final String filename;
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
package com.droiddeck.launcher.stores.gog
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.runtime.GuestCommand
|
||||
import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
internal object GogInnoextract {
|
||||
private const val PROGRAM = "/usr/local/bin/droiddeck-innoextract"
|
||||
|
||||
@JvmStatic
|
||||
fun extract(context: Context, setup: String, target: String, logName: String, cancelled: AtomicBoolean, onLine: (String) -> Unit): Int =
|
||||
GuestCommand.run(context, argv(setup, target), logName = logName,
|
||||
extraBinds = StoreInstallRoot.guestBinds(context), cancelled = cancelled, onLine = onLine)
|
||||
|
||||
internal fun argv(setup: String, target: String): List<String> = listOf(PROGRAM, "--gog", "--silent", "-d", target, setup)
|
||||
}
|
||||
@@ -3,9 +3,11 @@ package com.droiddeck.launcher.stores.gog
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.agent.AgentGuest
|
||||
import com.droiddeck.launcher.frontend.AddedGames
|
||||
import com.droiddeck.launcher.runtime.GuestCommand
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import com.droiddeck.launcher.stores.StoreGameSidecar
|
||||
import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||
import com.droiddeck.launcher.stores.download.DownloadQueue
|
||||
import com.droiddeck.launcher.stores.download.DownloadStage
|
||||
import org.json.JSONArray
|
||||
@@ -69,7 +71,8 @@ internal object GogOffline {
|
||||
val source = AddedGames.guestPath(context, installer) ?: error("The GOG installer is not visible to Linux")
|
||||
val target = AddedGames.guestPath(context, extracted) ?: error("The GOG staging folder is not visible to Linux")
|
||||
handle.stage(DownloadStage.INSTALL, "Extracting the full offline installer")
|
||||
val rc = GogInnoextract.extract(context, source, target, "gog-refresh", stop, handle::log)
|
||||
val rc = GuestCommand.run(context, listOf("/usr/local/bin/droiddeck-innoextract", "--gog", "--silent", "-d", target, source),
|
||||
extraBinds = StoreInstallRoot.externalBindSpecs(context), cancelled = stop, logName = "gog-refresh", onLine = handle::log)
|
||||
if (stop.get()) return
|
||||
check(rc == 0) { "GOG installer extraction failed (exit $rc)" }
|
||||
applyRefresh(proposal, extracted, handle, stop)
|
||||
|
||||
@@ -160,7 +160,7 @@ internal fun BootMovieGroup(s: ModeSettings, a: ModeSettingsActions, host: MenuH
|
||||
TabChip(stringResource(R.string.boot_movie_tab_sound), tab == MovieTab.SOUND, Modifier.weight(1f)) { tab = MovieTab.SOUND }
|
||||
}
|
||||
when (tab) {
|
||||
MovieTab.INSTALLED -> InstalledTab(a)
|
||||
MovieTab.INSTALLED -> InstalledTab(a, host)
|
||||
MovieTab.IMPORT -> ImportTab(s, a)
|
||||
MovieTab.REPO -> RepoTab(a)
|
||||
MovieTab.SOUND -> SoundTab(s, a, host)
|
||||
@@ -170,7 +170,7 @@ internal fun BootMovieGroup(s: ModeSettings, a: ModeSettingsActions, host: MenuH
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun InstalledTab(a: ModeSettingsActions) {
|
||||
private fun InstalledTab(a: ModeSettingsActions, host: MenuHost) {
|
||||
var browsing by remember { mutableStateOf(false) }
|
||||
val snapshot = rememberMovies(0, a.onBootMovieChanged)
|
||||
val current = snapshot?.let { snap -> snap.entries.firstOrNull { it.id == snap.selected }?.title }
|
||||
@@ -183,6 +183,12 @@ private fun InstalledTab(a: ModeSettingsActions) {
|
||||
modifier = Modifier.padding(horizontal = 14.dp).padding(bottom = 12.dp),
|
||||
)
|
||||
val app = LocalContext.current.applicationContext
|
||||
var shuffle by remember { mutableStateOf(SessionPrefs.bootMovieShuffle(app)) }
|
||||
LaunchedEffect(snapshot) { shuffle = SessionPrefs.bootMovieShuffle(app) }
|
||||
ToggleRow(
|
||||
host, "boot-movie-shuffle", stringResource(R.string.boot_movie_shuffle),
|
||||
stringResource(R.string.common_applies_next_session), shuffle,
|
||||
) { on -> shuffle = on; SessionPrefs.setBootMovieShuffle(app, on) }
|
||||
val scope = rememberCoroutineScope()
|
||||
var saving by remember { mutableStateOf(false) }
|
||||
val debugging = remember { com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(app) }
|
||||
|
||||
@@ -911,7 +911,15 @@ internal fun GameSettingsMenus(host: MenuHost, game: com.droiddeck.launcher.fron
|
||||
val ready = current != null && !state.saving
|
||||
val launcher = game.library == com.droiddeck.launcher.frontend.Library.EPIC_LAUNCHER
|
||||
fun save(change: (android.content.Context) -> com.droiddeck.launcher.core.GameEnvironment.Config?) = state.save(change)
|
||||
var controlsProfile by remember(scope) { mutableStateOf(com.droiddeck.launcher.input.GameInputControls.profile(appContext, scope)) }
|
||||
val controlsKey = "game-settings-controls"
|
||||
val key = GAME_SETTINGS_MENU
|
||||
val controlsMenuOpen = host.open == key || host.open == controlsKey
|
||||
val inputLibrary by androidx.compose.runtime.produceState<com.droiddeck.launcher.input.InputLibrary?>(null, controlsMenuOpen) {
|
||||
value = if (controlsMenuOpen) kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
|
||||
com.droiddeck.launcher.input.InputLibraries.read(appContext)
|
||||
} else null
|
||||
}
|
||||
val fexKey = "game-settings-fex"
|
||||
val syncKey = "game-settings-sync"
|
||||
val syncLabels = mapOf(
|
||||
@@ -978,10 +986,13 @@ internal fun GameSettingsMenus(host: MenuHost, game: com.droiddeck.launcher.fron
|
||||
trailing = { Text("›", fontSize = 16.sp, color = colors.onSurfaceVariant) },
|
||||
) { host.open = syncKey }
|
||||
}
|
||||
MenuItem(stringResource(R.string.community_game_controls), checked = false,
|
||||
detail = inputLibrary?.profiles?.firstOrNull { it.id == controlsProfile }?.name ?: useDefault) { host.open = controlsKey }
|
||||
MenuItem(stringResource(R.string.game_settings_default), checked = false, enabled = ready,
|
||||
detail = stringResource(R.string.game_settings_default_detail)) {
|
||||
save {
|
||||
val failure = runCatching { com.droiddeck.launcher.session.GameProfileManager.reset(it, scope) }.exceptionOrNull()
|
||||
if (failure == null) controlsProfile = null
|
||||
com.droiddeck.launcher.stores.StoresState.post {
|
||||
android.widget.Toast.makeText(
|
||||
it,
|
||||
@@ -993,6 +1004,20 @@ internal fun GameSettingsMenus(host: MenuHost, game: com.droiddeck.launcher.fron
|
||||
}
|
||||
}
|
||||
}
|
||||
AnchoredMenu(host.open == controlsKey, onDismiss = { if (host.open == controlsKey) host.open = null },
|
||||
title = stringResource(R.string.community_game_controls)) { first ->
|
||||
MenuItem(useDefault, checked = controlsProfile == null, focusRequester = first) {
|
||||
runCatching { com.droiddeck.launcher.input.GameInputControls.set(appContext, scope, null) }
|
||||
.onSuccess { controlsProfile = null; host.open = key }
|
||||
.onFailure { android.widget.Toast.makeText(appContext, it.message, android.widget.Toast.LENGTH_SHORT).show() }
|
||||
}
|
||||
for (profile in inputLibrary?.profiles.orEmpty()) MenuItem(profile.name, checked = profile.id == controlsProfile,
|
||||
detail = stringResource(R.string.community_game_controls_hint)) {
|
||||
runCatching { com.droiddeck.launcher.input.GameInputControls.set(appContext, scope, profile.id) }
|
||||
.onSuccess { controlsProfile = profile.id; host.open = key }
|
||||
.onFailure { android.widget.Toast.makeText(appContext, it.message, android.widget.Toast.LENGTH_SHORT).show() }
|
||||
}
|
||||
}
|
||||
AnchoredMenu(host.open == resKey, onDismiss = { if (host.open == resKey) host.open = null }, title = stringResource(R.string.game_res_title)) { first ->
|
||||
MenuItem(matchScreen, checked = resolution == null, enabled = ready, focusRequester = first) { pickResolution(null) }
|
||||
com.droiddeck.launcher.core.GameResolution.scales.forEach { scale ->
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.input.*
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
@Composable
|
||||
internal fun InputCommunityPage(library: InputLibrary, profile: String, initialRole: InputRole, initialEntries: List<CommunityControls.Entry>? = null,
|
||||
onInstalled: (InputLibrary) -> Unit) {
|
||||
val context = LocalContext.current
|
||||
var targetProfile by remember { mutableStateOf(profile) }
|
||||
val scope = rememberCoroutineScope()
|
||||
val host = rememberMenuHost()
|
||||
var role by remember { mutableStateOf(initialRole.takeUnless { it == InputRole.PHYSICAL } ?: InputRole.PRIMARY) }
|
||||
var sources by remember { mutableStateOf(ControlSources.read(context)) }
|
||||
var selectedSource by remember { mutableStateOf(sources.first()) }
|
||||
var addingSource by remember { mutableStateOf(false) }
|
||||
var sourceUrl by remember { mutableStateOf("") }
|
||||
var entries by remember { mutableStateOf(initialEntries ?: CommunityControls.bundled(context)) }
|
||||
var busy by remember { mutableStateOf(false) }
|
||||
var status by remember { mutableStateOf<String?>(null) }
|
||||
var pending by remember { mutableStateOf<CommunityControls.Pack?>(null) }
|
||||
var exporting by remember { mutableStateOf<ByteArray?>(null) }
|
||||
var search by remember { mutableStateOf("") }
|
||||
val filtered = remember(entries, search, role) { entries.filter { it.screen.supports(role) &&
|
||||
(search.isBlank() || "${it.name} ${it.author} ${it.game}".contains(search, ignoreCase = true)) } }
|
||||
var page by remember(selectedSource.id, entries, search, role) { mutableIntStateOf(0) }
|
||||
val pageCount = ((filtered.size + 11) / 12).coerceAtLeast(1)
|
||||
val pageEntries = filtered.drop(page * 12).take(12)
|
||||
val previews = remember(selectedSource.id, pageEntries) { mutableStateMapOf<String, android.graphics.Bitmap>() }
|
||||
LaunchedEffect(previews, pageEntries) {
|
||||
for (entry in pageEntries) {
|
||||
if (entry.preview == null || entry.key in previews) continue
|
||||
var decoded: android.graphics.Bitmap? = null
|
||||
try {
|
||||
withContext(Dispatchers.IO) { decoded = runCatching { CommunityControls.preview(context, entry) }.getOrNull() }
|
||||
decoded?.let { previews[entry.key] = it; decoded = null }
|
||||
} finally { decoded?.recycle() }
|
||||
}
|
||||
}
|
||||
fun task(action: suspend () -> Unit) {
|
||||
if (busy) return
|
||||
busy = true
|
||||
status = null
|
||||
scope.launch {
|
||||
try { action() } catch (e: kotlinx.coroutines.CancellationException) { throw e }
|
||||
catch (e: Exception) { status = e.message ?: context.getString(R.string.community_failed) }
|
||||
finally { busy = false }
|
||||
}
|
||||
}
|
||||
fun load(source: ControlSources.Source) {
|
||||
task {
|
||||
val remote = withContext(Dispatchers.IO) { CommunityControls.fetchCatalog(source) }
|
||||
val bundled = if (source.id == ControlSources.DROIDDECK.id) CommunityControls.bundled(context) else emptyList()
|
||||
entries = (remote + bundled).distinctBy { it.path }
|
||||
status = context.getString(R.string.community_refreshed)
|
||||
}
|
||||
}
|
||||
val importer = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
|
||||
if (uri != null) task {
|
||||
pending = withContext(Dispatchers.IO) {
|
||||
val bytes = requireNotNull(context.contentResolver.openInputStream(uri)).use { CommunityControls.readLimited(it, 32 * 1024 * 1024) }
|
||||
CommunityControls.importFile(context, bytes, requireNotNull(library.layout(targetProfile, role)),
|
||||
library.preset(library.profile(targetProfile).binding(role)))
|
||||
}
|
||||
}
|
||||
}
|
||||
val exporter = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("application/zip")) { uri ->
|
||||
val bytes = exporting
|
||||
exporting = null
|
||||
if (uri != null && bytes != null) task {
|
||||
withContext(Dispatchers.IO) {
|
||||
requireNotNull(context.contentResolver.openOutputStream(uri, "wt")).use { it.write(bytes) }
|
||||
}
|
||||
status = context.getString(R.string.community_exported)
|
||||
}
|
||||
}
|
||||
InputHint(stringResource(R.string.community_description))
|
||||
SettingsGroup(stringResource(R.string.community_sources)) {
|
||||
ChoiceRow(host, "community-source", stringResource(R.string.community_source), null,
|
||||
sources.map { it.id to it.name }, selectedSource.id) { id ->
|
||||
if (!busy) {
|
||||
selectedSource = sources.first { it.id == id }
|
||||
entries = if (id == ControlSources.DROIDDECK.id) CommunityControls.bundled(context) else emptyList()
|
||||
load(selectedSource)
|
||||
}
|
||||
}
|
||||
PadTextButton(enabled = !busy, onClick = { sourceUrl = ""; addingSource = true }, modifier = Modifier.padding(8.dp).testTag("community-add-source")) {
|
||||
Text(stringResource(R.string.community_add_source))
|
||||
}
|
||||
if (!selectedSource.builtIn) PadTextButton(enabled = !busy, onClick = { task {
|
||||
ControlSources.remove(context, selectedSource)
|
||||
sources = ControlSources.read(context)
|
||||
selectedSource = sources.first()
|
||||
entries = CommunityControls.bundled(context)
|
||||
} }, modifier = Modifier.padding(8.dp)) { Text(stringResource(R.string.community_remove_source)) }
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.community_target)) {
|
||||
ChoiceRow(host, "community-profile", stringResource(R.string.input_profile), null,
|
||||
library.profiles.map { it.id to it.name }, targetProfile) { if (!busy) targetProfile = it }
|
||||
ChoiceRow(host, "community-screen", stringResource(R.string.community_screen), null,
|
||||
listOf(InputRole.PRIMARY, InputRole.SECONDARY).map { it to roleLabel(it) }, role) { if (!busy) role = it }
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.community_title)) {
|
||||
OutlinedTextField(search, { search = it.take(160) }, singleLine = true,
|
||||
label = { Text(stringResource(R.string.community_search)) }, modifier = Modifier.fillMaxWidth().padding(12.dp))
|
||||
for (entry in pageEntries) {
|
||||
InputNavigationRow(entry.name, listOf(entry.author, entry.game, entry.license).filter { it.isNotEmpty() }.joinToString(" · "),
|
||||
Modifier.testTag("community-pack-${entry.path}"), leading = {
|
||||
previews[entry.key]?.let { Image(it.asImageBitmap(), null, Modifier.width(112.dp).height(76.dp).testTag("community-preview-${entry.path}"), contentScale = ContentScale.Fit) }
|
||||
}) {
|
||||
task { pending = withContext(Dispatchers.IO) { CommunityControls.download(context, entry, library.layout(targetProfile, role),
|
||||
library.preset(library.profile(targetProfile).binding(role))) } }
|
||||
}
|
||||
}
|
||||
if (pageCount > 1) Row(Modifier.fillMaxWidth().padding(8.dp), horizontalArrangement = Arrangement.SpaceBetween) {
|
||||
PadTextButton(enabled = page > 0 && !busy, onClick = { page-- }, modifier = Modifier.testTag("community-previous")) { Text(stringResource(R.string.community_previous)) }
|
||||
Text(stringResource(R.string.community_page, page + 1, pageCount), Modifier.align(androidx.compose.ui.Alignment.CenterVertically))
|
||||
PadTextButton(enabled = page + 1 < pageCount && !busy, onClick = { page++ }, modifier = Modifier.testTag("community-next")) { Text(stringResource(R.string.community_next)) }
|
||||
}
|
||||
if (filtered.isEmpty())
|
||||
InputHint(stringResource(R.string.community_empty))
|
||||
PadTextButton(enabled = !busy, onClick = { load(selectedSource) }, modifier = Modifier.padding(8.dp)) { Text(stringResource(R.string.community_refresh)) }
|
||||
PadTextButton(enabled = !busy, onClick = { importer.launch(arrayOf("application/zip", "application/octet-stream", "application/x-zip-compressed")) },
|
||||
modifier = Modifier.padding(8.dp).testTag("community-import")) { Text(stringResource(R.string.community_import)) }
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.community_share)) {
|
||||
InputHint(stringResource(R.string.community_submit_hint))
|
||||
val layout = library.layout(targetProfile, role)
|
||||
if (layout?.editable == true) PadTextButton(enabled = !busy, onClick = { task {
|
||||
exporting = withContext(Dispatchers.IO) { CommunityControls.export(context, layout, library.preset(library.profile(targetProfile).binding(role))) }
|
||||
exporter.launch(layout.name.replace(Regex("[^A-Za-z0-9_-]"), "_").take(60) + ".ddcontrols.zip")
|
||||
} }, modifier = Modifier.padding(8.dp).testTag("community-export")) { Text(stringResource(R.string.community_export)) }
|
||||
if (layout?.editable == true && layout.elements.any { it.image.isNotEmpty() || it.stickImage.isNotEmpty() })
|
||||
PadTextButton(enabled = !busy, onClick = { task {
|
||||
exporting = withContext(Dispatchers.IO) { ArmsControlSkins.export(context, layout,
|
||||
library.preset(library.profile(targetProfile).binding(role))) }
|
||||
exporter.launch(layout.name.replace(Regex("[^A-Za-z0-9_-]"), "_").take(60) + ".skin.zip")
|
||||
} }, modifier = Modifier.padding(8.dp).testTag("community-export-skin")) { Text(stringResource(R.string.community_export_skin)) }
|
||||
PadTextButton(onClick = {
|
||||
runCatching { context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(selectedSource.submit ?: selectedSource.manifest))) }
|
||||
.onFailure { status = context.getString(R.string.community_failed) }
|
||||
}, modifier = Modifier.padding(8.dp)) { Text(stringResource(R.string.community_submit)) }
|
||||
}
|
||||
if (busy) LinearProgressIndicator(Modifier.fillMaxWidth().padding(12.dp))
|
||||
status?.let { InputHint(it) }
|
||||
if (addingSource) AlertDialog(onDismissRequest = { if (!busy) addingSource = false },
|
||||
title = { Text(stringResource(R.string.community_add_source)) }, text = { Column {
|
||||
Text(stringResource(R.string.community_source_hint))
|
||||
OutlinedTextField(sourceUrl, { sourceUrl = it.take(2048) }, singleLine = true,
|
||||
label = { Text(stringResource(R.string.community_source_url)) }, modifier = Modifier.testTag("community-source-url"))
|
||||
status?.let { Text(it) }
|
||||
} }, confirmButton = {
|
||||
PadTextButton(enabled = !busy && sourceUrl.isNotBlank(), onClick = { task {
|
||||
val (source, remote) = withContext(Dispatchers.IO) {
|
||||
var failure: Exception? = null
|
||||
var found: Pair<ControlSources.Source, List<CommunityControls.Entry>>? = null
|
||||
for (candidate in ControlSources.candidates(sourceUrl)) {
|
||||
try { found = candidate to CommunityControls.fetchCatalog(candidate); break }
|
||||
catch (e: Exception) { failure = e }
|
||||
}
|
||||
found ?: throw (failure ?: IllegalArgumentException(context.getString(R.string.community_failed)))
|
||||
}
|
||||
ControlSources.add(context, source)
|
||||
sources = ControlSources.read(context)
|
||||
selectedSource = sources.first { it.id == source.id }
|
||||
entries = remote
|
||||
addingSource = false
|
||||
} }) { Text(stringResource(R.string.community_connect)) }
|
||||
}, dismissButton = { PadTextButton(enabled = !busy, onClick = { addingSource = false }) { Text(stringResource(R.string.common_cancel)) } })
|
||||
pending?.let { pack ->
|
||||
AlertDialog(onDismissRequest = { if (!busy) pending = null }, title = { Text(pack.layout.name) },
|
||||
text = { Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
InputLayoutThumbnail(pack.layout, role, pack.images, Modifier.fillMaxWidth().height(180.dp))
|
||||
Text(stringResource(R.string.community_apply_hint, pack.layout.elements.size, library.profile(targetProfile).name, roleLabel(role)))
|
||||
} }, confirmButton = {
|
||||
PadTextButton(enabled = !busy && pack.layout.supports(role), onClick = { task {
|
||||
val installed = withContext(Dispatchers.IO) { CommunityControls.install(context, pack, targetProfile, role) }
|
||||
onInstalled(installed)
|
||||
pending = null
|
||||
status = context.getString(R.string.community_installed)
|
||||
} }) { Text(stringResource(R.string.community_apply)) }
|
||||
}, dismissButton = { PadTextButton(enabled = !busy, onClick = { pending = null }) { Text(stringResource(R.string.common_cancel)) } })
|
||||
}
|
||||
}
|
||||
@@ -36,13 +36,17 @@ internal fun InputLayoutRow(layout: SavedInputLayout, role: InputRole, detail: S
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun InputLayoutThumbnail(layout: SavedInputLayout, role: InputRole) {
|
||||
AndroidView(factory = { InputLayoutPreviewView(it) }, modifier = Modifier.width(112.dp).height(76.dp).testTag("layout-preview-${layout.id}"),
|
||||
update = { it.update(layout, role) })
|
||||
internal fun InputLayoutThumbnail(layout: SavedInputLayout, role: InputRole, images: Map<String, ByteArray> = emptyMap(),
|
||||
modifier: Modifier = Modifier.width(112.dp).height(76.dp)) {
|
||||
val bitmaps = remember(images) { images.mapValues { (_, bytes) -> android.graphics.BitmapFactory.decodeByteArray(bytes, 0, bytes.size) } }
|
||||
key(bitmaps) {
|
||||
AndroidView(factory = { InputLayoutPreviewView(it, bitmaps.filterValues { it != null }.mapValues { it.value!! }) },
|
||||
modifier = modifier.testTag("layout-preview-${layout.id}"), update = { it.update(layout, role) })
|
||||
}
|
||||
}
|
||||
|
||||
internal class InputLayoutPreviewView(context: Context) : View(context) {
|
||||
private val renderer = InputSurfaceView(context)
|
||||
internal class InputLayoutPreviewView(context: Context, images: Map<String, android.graphics.Bitmap> = emptyMap()) : View(context) {
|
||||
private val renderer = InputSurfaceView(context, previewImages = images)
|
||||
private var sourceHeight = 563
|
||||
fun update(layout: SavedInputLayout, role: InputRole) {
|
||||
sourceHeight = if (role == InputRole.PRIMARY) 563 else 870
|
||||
|
||||
@@ -33,7 +33,10 @@ internal fun InputQuickSettings(host: MenuHost, desktop: Boolean, onChanged: (In
|
||||
runCatching { InputLibraries.update(context, change) }.onSuccess { library = it; onChanged(role) }
|
||||
.onFailure { failure = it.message ?: context.getString(R.string.input_save_failed) }
|
||||
}
|
||||
val selection = library.selection(desktop)
|
||||
val game = (context.findActivity() as? com.droiddeck.launcher.SessionActivity)?.inputGameScope()
|
||||
fun effective(value: InputLibrary) = GameInputControls.resolve(context, value, desktop, game)
|
||||
val resolved = effective(library)
|
||||
val selection = resolved.selection(desktop)
|
||||
val mixed = selection.parts.isNotEmpty()
|
||||
val active = library.profile(library.activeId(desktop))
|
||||
val profiles = listOf(InputProfiles.AUTO to stringResource(R.string.input_quick_auto, if (desktop) library.profile(library.desktop).name else library.profile(library.steam).name)) +
|
||||
@@ -61,7 +64,7 @@ internal fun InputQuickSettings(host: MenuHost, desktop: Boolean, onChanged: (In
|
||||
if (role == InputRole.PHYSICAL) binding.physical
|
||||
else !binding.physical && library.layouts.any { it.id == binding.layoutId && it.supports(role) }
|
||||
}.map { it.id to it.name }
|
||||
ChoiceRow(host, "input-part-${role.name}", roleLabel(role), null, options, library.activePart(desktop, role).bindings,
|
||||
ChoiceRow(host, "input-part-${role.name}", roleLabel(role), null, options, resolved.activePart(desktop, role).bindings,
|
||||
chipModifier = track("input-part-${role.name}")) { id -> update(role) { it.selectPart(desktop, role, id) } }
|
||||
}
|
||||
if (mixed) SecondaryButton(stringResource(R.string.input_save_combination)) { naming = true }
|
||||
@@ -73,7 +76,7 @@ internal fun InputQuickSettings(host: MenuHost, desktop: Boolean, onChanged: (In
|
||||
var name by remember { mutableStateOf("") }
|
||||
AlertDialog(onDismissRequest = { naming = false }, title = { Text(stringResource(R.string.input_save_combination)) },
|
||||
text = { OutlinedTextField(name, { name = it.take(80) }, singleLine = true, label = { Text(stringResource(R.string.input_name)) }) },
|
||||
confirmButton = { PadTextButton(enabled = name.isNotBlank(), onClick = { update(null) { it.saveSelection(desktop, name) }; naming = false }) { Text(stringResource(R.string.gesture_save_changes)) } },
|
||||
confirmButton = { PadTextButton(enabled = name.isNotBlank(), onClick = { update(null) { effective(it).saveSelection(desktop, name) }; naming = false }) { Text(stringResource(R.string.gesture_save_changes)) } },
|
||||
dismissButton = { PadTextButton(onClick = { naming = false }) { Text(stringResource(R.string.common_cancel)) } })
|
||||
}
|
||||
failure?.let { message -> AlertDialog(onDismissRequest = { failure = null }, title = { Text(stringResource(R.string.input_save_failed)) },
|
||||
|
||||
@@ -65,7 +65,7 @@ private fun InputSettingsPane(onBack: () -> Unit, onChanged: () -> Unit) {
|
||||
}
|
||||
}
|
||||
|
||||
private enum class InputPage { HOME, PROFILE, SOURCE, LAYOUTS, REUSE }
|
||||
private enum class InputPage { HOME, PROFILE, SOURCE, LAYOUTS, REUSE, COMMUNITY }
|
||||
private data class InputBindingEdit(val preset: String, val control: InputControl, val element: InputSurfaceElement? = null, val key: PhysicalInputKey? = null, val click: Boolean = false)
|
||||
private data class InputNameRequest(val title: Int, val initial: String, val sources: List<Pair<String, String>> = emptyList(),
|
||||
val source: String = "", val offerSharing: Boolean = false, val save: (String, String, Boolean) -> Unit)
|
||||
@@ -85,6 +85,7 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
|
||||
val host = rememberMenuHost()
|
||||
var library by remember { mutableStateOf(InputLibraries.read(context)) }
|
||||
var page by remember { mutableStateOf(InputPage.HOME) }
|
||||
var communityBack by remember { mutableStateOf(InputPage.HOME) }
|
||||
var bindingsTab by remember { mutableIntStateOf(0) }
|
||||
var profileId by remember { mutableStateOf(InputProfile.GAME) }
|
||||
var role by remember { mutableStateOf(InputRole.PHYSICAL) }
|
||||
@@ -104,12 +105,13 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
|
||||
var oscMode by remember { mutableStateOf(SessionPrefs.oscMode(context)) }
|
||||
fun update(change: (InputLibrary) -> InputLibrary): Boolean = runCatching { InputLibraries.update(context, change) }
|
||||
.onSuccess { library = it; onChanged() }.onFailure { error = it.message ?: context.getString(R.string.input_save_failed) }.isSuccess
|
||||
fun go(next: InputPage) { page = next; host.open = null }
|
||||
fun go(next: InputPage) { if (next == InputPage.COMMUNITY) communityBack = page; page = next; host.open = null }
|
||||
fun back() {
|
||||
when {
|
||||
edit != null -> edit = null
|
||||
page == InputPage.HOME -> onBack()
|
||||
page == InputPage.PROFILE -> go(InputPage.HOME)
|
||||
page == InputPage.COMMUNITY -> go(communityBack)
|
||||
page == InputPage.SOURCE -> go(InputPage.PROFILE)
|
||||
else -> go(InputPage.SOURCE)
|
||||
}
|
||||
@@ -191,6 +193,7 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
|
||||
InputPage.SOURCE -> roleLabel(role)
|
||||
InputPage.LAYOUTS -> stringResource(R.string.input_saved_layouts)
|
||||
InputPage.REUSE -> stringResource(R.string.input_use_settings_from)
|
||||
InputPage.COMMUNITY -> stringResource(R.string.community_title)
|
||||
}, eyebrow = when (page) {
|
||||
InputPage.SOURCE -> profile.name
|
||||
InputPage.LAYOUTS, InputPage.REUSE -> "${profile.name} · ${roleLabel(role)}"
|
||||
@@ -198,7 +201,12 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
|
||||
},
|
||||
onBack = ::back, showBack = !(embedded && page == InputPage.HOME), compactLayout = true) {
|
||||
when (page) {
|
||||
InputPage.COMMUNITY -> InputCommunityPage(library, profileId, role) { installed -> library = installed; onChanged() }
|
||||
InputPage.HOME -> {
|
||||
SettingsGroup(stringResource(R.string.community_title)) {
|
||||
InputNavigationRow(stringResource(R.string.community_title), stringResource(R.string.community_home_hint),
|
||||
Modifier.testTag("input-community")) { go(InputPage.COMMUNITY) }
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.input_default_profiles)) {
|
||||
ChoiceRow(host, "auto-desktop", stringResource(R.string.input_desktop_mode), null,
|
||||
library.profiles.map { it.id to it.name }, library.desktop) { id -> update { it.copy(desktop = id) } }
|
||||
@@ -284,6 +292,7 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
|
||||
for (button in layout.quickButtons) ToggleRow(host, "quick-${button.name.lowercase()}", stringResource(quickButtonLabel(button)), null,
|
||||
button !in layout.style.hidden) { on -> update { it.withLayout(layout.withQuickButton(button, on)) } }
|
||||
}
|
||||
InputNavigationRow(stringResource(R.string.community_title), stringResource(R.string.community_home_hint)) { go(InputPage.COMMUNITY) }
|
||||
if (role == InputRole.SECONDARY) InputHint(stringResource(R.string.input_second_screen_enable))
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.input_assign_actions)) {
|
||||
@@ -449,7 +458,7 @@ private fun InputControlGrid(preset: SavedInputBindings, available: List<InputCo
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun InputNavigationRow(title: String, detail: String?, modifier: Modifier = Modifier, leading: (@Composable () -> Unit)? = null, onClick: () -> Unit) {
|
||||
internal fun InputNavigationRow(title: String, detail: String?, modifier: Modifier = Modifier, leading: (@Composable () -> Unit)? = null, onClick: () -> Unit) {
|
||||
Row(modifier.fillMaxWidth().focusRow(RoundedCornerShape(0.dp), onClick = onClick).heightIn(min = 64.dp).padding(14.dp),
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
leading?.invoke()
|
||||
@@ -499,6 +508,6 @@ internal fun roleLabel(role: InputRole) = stringResource(when (role) {
|
||||
})
|
||||
|
||||
@Composable
|
||||
private fun InputHint(text: String) {
|
||||
internal fun InputHint(text: String) {
|
||||
Text(text, Modifier.padding(14.dp), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
@@ -51,6 +51,7 @@ class InputSurfaceView(
|
||||
private val inputRole: InputRole = InputRole.SECONDARY,
|
||||
private var surfaceStyle: InputSurfaceStyle = InputSurfaceStyle(),
|
||||
private val haptics: Boolean = inputRole != InputRole.PRIMARY,
|
||||
private val previewImages: Map<String, android.graphics.Bitmap> = emptyMap(),
|
||||
) : FrameLayout(context) {
|
||||
private val content = FrameLayout(context)
|
||||
private val elementSources = ArrayList<InputSurfaceSource>()
|
||||
@@ -326,13 +327,7 @@ class InputSurfaceView(
|
||||
protected fun textColor(lit: Boolean) = if (lit) Color.WHITE else tint?.let { light(it, 210, 0.75f) } ?: TEXT
|
||||
}
|
||||
|
||||
private inner class HoldButton(context: Context, private val element: InputSurfaceElement, private val source: InputSurfaceSource?) : Surface(context) {
|
||||
private var down = false
|
||||
private val pointers = HashSet<Int>()
|
||||
val round get() = element.buttonShape == InputButtonShape.CIRCLE
|
||||
val gamepad get() = round || element.buttonShape == InputButtonShape.PILL
|
||||
private val symbol = InputButtonIcons.drawable(context, element.icon)
|
||||
private val bitmap = InputButtonImages.file(context, element.image)?.let { file ->
|
||||
private fun imageBitmap(name: String): android.graphics.Bitmap? = previewImages[name] ?: InputButtonImages.file(context, name)?.let { file ->
|
||||
val size = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
BitmapFactory.decodeFile(file.path, size)
|
||||
val options = BitmapFactory.Options().apply {
|
||||
@@ -341,6 +336,14 @@ class InputSurfaceView(
|
||||
}
|
||||
if (file.isFile) BitmapFactory.decodeFile(file.path, options) else null
|
||||
}
|
||||
|
||||
private inner class HoldButton(context: Context, private val element: InputSurfaceElement, private val source: InputSurfaceSource?) : Surface(context) {
|
||||
private var down = false
|
||||
private val pointers = HashSet<Int>()
|
||||
val round get() = element.buttonShape == InputButtonShape.CIRCLE
|
||||
val gamepad get() = round || element.buttonShape == InputButtonShape.PILL
|
||||
private val symbol = InputButtonIcons.drawable(context, element.icon)
|
||||
private val bitmap = imageBitmap(element.image)
|
||||
private val imageRect = RectF()
|
||||
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
@@ -511,6 +514,17 @@ class InputSurfaceView(
|
||||
private var knobY = 0f
|
||||
private val ring = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE }
|
||||
private val knob = Paint(Paint.ANTI_ALIAS_FLAG)
|
||||
private val baseImage = imageBitmap(element.image)
|
||||
private val stickImage = imageBitmap(element.stickImage)
|
||||
private val imagePaint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG)
|
||||
private val imageBounds = RectF()
|
||||
|
||||
private fun drawImage(canvas: Canvas, image: android.graphics.Bitmap, x: Float, y: Float, radius: Float) {
|
||||
val scale = min(radius * 2 / image.width, radius * 2 / image.height)
|
||||
imageBounds.set(x - image.width * scale / 2, y - image.height * scale / 2,
|
||||
x + image.width * scale / 2, y + image.height * scale / 2)
|
||||
canvas.drawBitmap(image, null, imageBounds, imagePaint)
|
||||
}
|
||||
|
||||
val adaptive get() = adaptive(element)
|
||||
|
||||
@@ -534,6 +548,14 @@ class InputSurfaceView(
|
||||
val cx = if (touching) originX else centreX()
|
||||
val cy = if (touching) originY else height / 2f
|
||||
val color = tint
|
||||
if (baseImage != null || stickImage != null) {
|
||||
val radius = min(width, height) / 2f - .75f * density
|
||||
if (baseImage != null) drawImage(canvas, baseImage, cx, cy, radius)
|
||||
else { ring.color = LINE; ring.strokeWidth = 2 * density; canvas.drawCircle(cx, cy, radius, ring) }
|
||||
if (stickImage != null) drawImage(canvas, stickImage, cx + knobX, cy + knobY, radius * .46f)
|
||||
else { knob.color = if (touching) ACCENT else KNOB; canvas.drawCircle(cx + knobX, cy + knobY, radius * .46f, knob) }
|
||||
return
|
||||
}
|
||||
if (classic(element) && color != null) {
|
||||
val radius = min(width, height) / 2f - 0.75f * density
|
||||
drawCircle(canvas, cx, cy, radius,
|
||||
|
||||
@@ -306,8 +306,12 @@ class SecondScreenPresentation(
|
||||
}
|
||||
}
|
||||
|
||||
private fun panelLayout(mode: SecondScreenMode) = com.droiddeck.launcher.input.InputLibraries.read(context)
|
||||
.panelLayout(SessionState.mode == SessionService.MODE_DESKTOP, mode.panel(context))
|
||||
private fun panelLayout(mode: SecondScreenMode): com.droiddeck.launcher.input.SavedInputLayout? {
|
||||
val desktop = SessionState.mode == SessionService.MODE_DESKTOP
|
||||
return com.droiddeck.launcher.input.GameInputControls.resolve(context,
|
||||
com.droiddeck.launcher.input.InputLibraries.read(context), desktop, sessionActivity.inputGameScope())
|
||||
.panelLayout(desktop, mode.panel(context))
|
||||
}
|
||||
|
||||
private fun bar(mode: SecondScreenMode) {
|
||||
val first = barModel(mode) ?: return
|
||||
|
||||
@@ -3563,6 +3563,7 @@
|
||||
<string name="boot_movie_sound">الصوت</string>
|
||||
<string name="boot_movie_skip">تخطي مقطع بدء التشغيل</string>
|
||||
<string name="boot_movie_skip_hint">استخدم مقطعًا أسود مدته 0.1 ثانية كمقطع بدء تشغيل Steam. يسري في الجلسة التالية.</string>
|
||||
<string name="boot_movie_shuffle">عشوائي</string>
|
||||
<string name="boot_movie_custom">فيديو خاص بك</string>
|
||||
<string name="boot_movie_custom_hint">MP4 أو MOV أو MKV أو WebM. تُحوَّل الصيغ الأخرى والملفات الأكبر من %1$d ميغابايت إلى WebM بدقة 720p على الجهاز، حتى %2$d ثانية.</string>
|
||||
<string name="boot_movie_import">استيراد</string>
|
||||
|
||||
@@ -3385,6 +3385,7 @@
|
||||
<string name="boot_movie_sound">Sonido</string>
|
||||
<string name="boot_movie_skip">Omitir el video de inicio</string>
|
||||
<string name="boot_movie_skip_hint">Usa un clip negro de 0.1 segundos como video de inicio de Steam. Se aplica en la próxima sesión.</string>
|
||||
<string name="boot_movie_shuffle">Aleatorio</string>
|
||||
<string name="boot_movie_custom">Tu propio video</string>
|
||||
<string name="boot_movie_custom_hint">MP4, MOV, MKV o WebM. Otros formatos y archivos de más de %1$d MB se convierten a WebM 720p en el dispositivo, hasta %2$d segundos.</string>
|
||||
<string name="boot_movie_import">Importar</string>
|
||||
|
||||
@@ -3407,6 +3407,7 @@
|
||||
<string name="boot_movie_sound">Звук</string>
|
||||
<string name="boot_movie_skip">Пропусни стартовото видео</string>
|
||||
<string name="boot_movie_skip_hint">Използвай 0,1-секунден черен клип като стартовото видео на Steam. Влиза в сила при следващата сесия.</string>
|
||||
<string name="boot_movie_shuffle">Разбъркване</string>
|
||||
<string name="boot_movie_custom">Собствено видео</string>
|
||||
<string name="boot_movie_custom_hint">MP4, MOV, MKV или WebM. Други формати и файлове над %1$d MB се конвертират на устройството до WebM 720p, до %2$d секунди.</string>
|
||||
<string name="boot_movie_import">Импортиране</string>
|
||||
|
||||
@@ -3485,6 +3485,7 @@
|
||||
<string name="boot_movie_sound">Zvuk</string>
|
||||
<string name="boot_movie_skip">Přeskočit úvodní video</string>
|
||||
<string name="boot_movie_skip_hint">Použije se 0,1sekundový černý klip jako úvodní video při spuštění aplikace Steam. Projeví se v příští relaci.</string>
|
||||
<string name="boot_movie_shuffle">Náhodné pořadí</string>
|
||||
<string name="boot_movie_custom">Vlastní video</string>
|
||||
<string name="boot_movie_custom_hint">MP4, MOV, MKV nebo WebM. Jiné formáty a soubory nad %1$d MB se v zařízení převedou na WebM 720p, nejvýše %2$d sekund.</string>
|
||||
<string name="boot_movie_import">Importovat</string>
|
||||
|
||||
@@ -3407,6 +3407,7 @@
|
||||
<string name="boot_movie_sound">Lyd</string>
|
||||
<string name="boot_movie_skip">Spring opstartsfilmen over</string>
|
||||
<string name="boot_movie_skip_hint">Brug et sort klip på 0,1 sekund som opstartsfilm i Steam. Gælder fra næste session.</string>
|
||||
<string name="boot_movie_shuffle">Bland</string>
|
||||
<string name="boot_movie_custom">Din egen video</string>
|
||||
<string name="boot_movie_custom_hint">MP4, MOV, MKV eller WebM. Andre formater og filer over %1$d MB konverteres til 720p-WebM på enheden, op til %2$d sekunder.</string>
|
||||
<string name="boot_movie_import">Importér</string>
|
||||
|
||||
@@ -3407,6 +3407,7 @@
|
||||
<string name="boot_movie_sound">Ton</string>
|
||||
<string name="boot_movie_skip">Startvideo überspringen</string>
|
||||
<string name="boot_movie_skip_hint">Ein schwarzes Video von 0,1 Sekunden als Steam-Startvideo verwenden. Gilt ab der nächsten Sitzung.</string>
|
||||
<string name="boot_movie_shuffle">Zufallswiedergabe</string>
|
||||
<string name="boot_movie_custom">Eigenes Video</string>
|
||||
<string name="boot_movie_custom_hint">MP4, MOV, MKV oder WebM. Andere Formate und Dateien über %1$d MB werden auf dem Gerät in 720p-WebM umgewandelt, bis %2$d Sekunden.</string>
|
||||
<string name="boot_movie_import">Importieren</string>
|
||||
|
||||
@@ -3407,6 +3407,7 @@
|
||||
<string name="boot_movie_sound">Ήχος</string>
|
||||
<string name="boot_movie_skip">Παράλειψη ταινίας εκκίνησης</string>
|
||||
<string name="boot_movie_skip_hint">Χρησιμοποιεί ένα μαύρο κλιπ 0,1 δευτερολέπτου ως ταινία εκκίνησης του Steam. Εφαρμόζεται στην επόμενη συνεδρία.</string>
|
||||
<string name="boot_movie_shuffle">Τυχαία σειρά</string>
|
||||
<string name="boot_movie_custom">Δικό σας βίντεο</string>
|
||||
<string name="boot_movie_custom_hint">MP4, MOV, MKV ή WebM. Άλλες μορφές και αρχεία πάνω από %1$d MB μετατρέπονται στη συσκευή σε WebM 720p, έως %2$d δευτερόλεπτα.</string>
|
||||
<string name="boot_movie_import">Εισαγωγή</string>
|
||||
|
||||
@@ -3446,6 +3446,7 @@
|
||||
<string name="boot_movie_sound">Sonido</string>
|
||||
<string name="boot_movie_skip">Omitir vídeo de inicio</string>
|
||||
<string name="boot_movie_skip_hint">Usa un clip negro de 0,1 segundos como vídeo de inicio de Steam. Se aplicará en la próxima sesión.</string>
|
||||
<string name="boot_movie_shuffle">Aleatorio</string>
|
||||
<string name="boot_movie_custom">Tu propio vídeo</string>
|
||||
<string name="boot_movie_custom_hint">MP4, MOV, MKV o WebM. Otros formatos y archivos de más de %1$d MB se convierten a WebM 720p en el dispositivo, hasta %2$d segundos.</string>
|
||||
<string name="boot_movie_import">Importar</string>
|
||||
|
||||
@@ -3407,6 +3407,7 @@
|
||||
<string name="boot_movie_sound">Ääni</string>
|
||||
<string name="boot_movie_skip">Ohita käynnistysvideo</string>
|
||||
<string name="boot_movie_skip_hint">Käytä 0,1 sekunnin mustaa leikettä Steam-käynnistysvideona. Otetaan käyttöön seuraavassa istunnossa.</string>
|
||||
<string name="boot_movie_shuffle">Satunnainen</string>
|
||||
<string name="boot_movie_custom">Oma video</string>
|
||||
<string name="boot_movie_custom_hint">MP4, MOV, MKV tai WebM. Muut muodot ja yli %1$d Mt:n tiedostot muunnetaan laitteella 720p-WebM-muotoon, enintään %2$d sekuntia.</string>
|
||||
<string name="boot_movie_import">Tuo</string>
|
||||
|
||||
@@ -3445,6 +3445,7 @@
|
||||
<string name="boot_movie_sound">Son</string>
|
||||
<string name="boot_movie_skip">Ignorer la vidéo de démarrage</string>
|
||||
<string name="boot_movie_skip_hint">Utilise un clip noir de 0,1 seconde comme vidéo de démarrage de Steam. S’applique à la prochaine session.</string>
|
||||
<string name="boot_movie_shuffle">Aléatoire</string>
|
||||
<string name="boot_movie_custom">Votre propre vidéo</string>
|
||||
<string name="boot_movie_custom_hint">MP4, MOV, MKV ou WebM. Les autres formats et les fichiers de plus de %1$d Mo sont convertis en WebM 720p sur l\'appareil, jusqu\'à %2$d secondes.</string>
|
||||
<string name="boot_movie_import">Importer</string>
|
||||
|
||||
@@ -3407,6 +3407,7 @@
|
||||
<string name="boot_movie_sound">आवाज़</string>
|
||||
<string name="boot_movie_skip">बूट मूवी छोड़ें</string>
|
||||
<string name="boot_movie_skip_hint">Steam की स्टार्टअप मूवी के रूप में 0.1 सेकंड की काली क्लिप इस्तेमाल करें। अगले सत्र से लागू होगा।</string>
|
||||
<string name="boot_movie_shuffle">शफ़ल</string>
|
||||
<string name="boot_movie_custom">अपना वीडियो</string>
|
||||
<string name="boot_movie_custom_hint">MP4, MOV, MKV या WebM. दूसरे फ़ॉर्मैट और %1$d MB से बड़ी फ़ाइलें डिवाइस पर 720p WebM में बदली जाती हैं, %2$d सेकंड तक।</string>
|
||||
<string name="boot_movie_import">इंपोर्ट करें</string>
|
||||
|
||||
@@ -3407,6 +3407,7 @@
|
||||
<string name="boot_movie_sound">Hang</string>
|
||||
<string name="boot_movie_skip">Indítási videó kihagyása</string>
|
||||
<string name="boot_movie_skip_hint">Egy 0,1 másodperces fekete klipet használ a Steam indítási videójaként. A következő munkamenetben lép érvénybe.</string>
|
||||
<string name="boot_movie_shuffle">Véletlen sorrend</string>
|
||||
<string name="boot_movie_custom">Saját videó</string>
|
||||
<string name="boot_movie_custom_hint">MP4, MOV, MKV vagy WebM. Más formátumokat és a %1$d MB-nál nagyobb fájlokat az eszköz 720p WebM-re alakítja, legfeljebb %2$d másodpercig.</string>
|
||||
<string name="boot_movie_import">Importálás</string>
|
||||
|
||||
@@ -3378,6 +3378,7 @@
|
||||
<string name="boot_movie_sound">Suara</string>
|
||||
<string name="boot_movie_skip">Lewati video pembukaan</string>
|
||||
<string name="boot_movie_skip_hint">Gunakan klip hitam berdurasi 0,1 detik sebagai video pembukaan Steam. Berlaku pada sesi berikutnya.</string>
|
||||
<string name="boot_movie_shuffle">Acak</string>
|
||||
<string name="boot_movie_custom">Video sendiri</string>
|
||||
<string name="boot_movie_custom_hint">MP4, MOV, MKV, atau WebM. Format lain dan file di atas %1$d MB dikonversi ke WebM 720p di perangkat, hingga %2$d detik.</string>
|
||||
<string name="boot_movie_import">Impor</string>
|
||||
|
||||
@@ -3445,6 +3445,7 @@
|
||||
<string name="boot_movie_sound">Audio</string>
|
||||
<string name="boot_movie_skip">Salta il video di avvio</string>
|
||||
<string name="boot_movie_skip_hint">Usa una clip nera di 0,1 secondi come video di avvio di Steam. Dalla sessione successiva.</string>
|
||||
<string name="boot_movie_shuffle">Casuale</string>
|
||||
<string name="boot_movie_custom">Il tuo video</string>
|
||||
<string name="boot_movie_custom_hint">MP4, MOV, MKV o WebM. Altri formati e file oltre %1$d MB vengono convertiti in WebM 720p sul dispositivo, fino a %2$d secondi.</string>
|
||||
<string name="boot_movie_import">Importa</string>
|
||||
|
||||
@@ -3378,6 +3378,7 @@
|
||||
<string name="boot_movie_sound">サウンド</string>
|
||||
<string name="boot_movie_skip">起動ムービーをスキップ</string>
|
||||
<string name="boot_movie_skip_hint">0.1 秒の黒いクリップを Steam の起動ムービーとして使用します。次回セッションから適用されます。</string>
|
||||
<string name="boot_movie_shuffle">シャッフル</string>
|
||||
<string name="boot_movie_custom">自分のムービー</string>
|
||||
<string name="boot_movie_custom_hint">MP4、MOV、MKV、WebM。その他の形式や %1$d MB を超えるファイルは、端末上で 720p の WebM に変換されます(%2$d 秒まで)。</string>
|
||||
<string name="boot_movie_import">インポート</string>
|
||||
|
||||
@@ -3378,6 +3378,7 @@
|
||||
<string name="boot_movie_sound">소리</string>
|
||||
<string name="boot_movie_skip">시작 동영상 건너뛰기</string>
|
||||
<string name="boot_movie_skip_hint">0.1초짜리 검은 화면 클립을 Steam 시작 동영상으로 사용합니다. 다음 세션부터 적용됩니다.</string>
|
||||
<string name="boot_movie_shuffle">셔플</string>
|
||||
<string name="boot_movie_custom">내 동영상</string>
|
||||
<string name="boot_movie_custom_hint">MP4, MOV, MKV 또는 WebM. 다른 형식과 %1$d MB를 넘는 파일은 기기에서 720p WebM으로 변환됩니다(최대 %2$d초).</string>
|
||||
<string name="boot_movie_import">가져오기</string>
|
||||
|
||||
@@ -3378,6 +3378,7 @@
|
||||
<string name="boot_movie_sound">Bunyi</string>
|
||||
<string name="boot_movie_skip">Langkau filem permulaan</string>
|
||||
<string name="boot_movie_skip_hint">Gunakan klip hitam 0.1 saat sebagai filem permulaan Steam. Berkuat kuasa pada sesi seterusnya.</string>
|
||||
<string name="boot_movie_shuffle">Rawak</string>
|
||||
<string name="boot_movie_custom">Video anda sendiri</string>
|
||||
<string name="boot_movie_custom_hint">MP4, MOV, MKV atau WebM. Format lain dan fail melebihi %1$d MB ditukar kepada WebM 720p pada peranti, sehingga %2$d saat.</string>
|
||||
<string name="boot_movie_import">Import</string>
|
||||
|
||||
@@ -3407,6 +3407,7 @@
|
||||
<string name="boot_movie_sound">Lyd</string>
|
||||
<string name="boot_movie_skip">Hopp over oppstartsfilmen</string>
|
||||
<string name="boot_movie_skip_hint">Bruk et svart klipp på 0,1 sekunder som oppstartsfilmen til Steam. Trer i kraft neste økt.</string>
|
||||
<string name="boot_movie_shuffle">Tilfeldig rekkefølge</string>
|
||||
<string name="boot_movie_custom">Din egen video</string>
|
||||
<string name="boot_movie_custom_hint">MP4, MOV, MKV eller WebM. Andre formater og filer over %1$d MB konverteres til 720p-WebM på enheten, opptil %2$d sekunder.</string>
|
||||
<string name="boot_movie_import">Importer</string>
|
||||
|
||||
@@ -3407,6 +3407,7 @@
|
||||
<string name="boot_movie_sound">Geluid</string>
|
||||
<string name="boot_movie_skip">Opstartvideo overslaan</string>
|
||||
<string name="boot_movie_skip_hint">Gebruik een zwart fragment van 0,1 seconde als opstartvideo van Steam. Wordt toegepast in de volgende sessie.</string>
|
||||
<string name="boot_movie_shuffle">Willekeurig</string>
|
||||
<string name="boot_movie_custom">Eigen video</string>
|
||||
<string name="boot_movie_custom_hint">MP4, MOV, MKV of WebM. Andere formaten en bestanden boven %1$d MB worden op het apparaat omgezet naar 720p-WebM, tot %2$d seconden.</string>
|
||||
<string name="boot_movie_import">Importeren</string>
|
||||
|
||||
@@ -3485,6 +3485,7 @@
|
||||
<string name="boot_movie_sound">Dźwięk</string>
|
||||
<string name="boot_movie_skip">Pomiń film startowy</string>
|
||||
<string name="boot_movie_skip_hint">Użyj 0,1-sekundowego czarnego klipu jako filmu startowego Steam. Zacznie obowiązywać w następnej sesji.</string>
|
||||
<string name="boot_movie_shuffle">Losowo</string>
|
||||
<string name="boot_movie_custom">Własny film</string>
|
||||
<string name="boot_movie_custom_hint">MP4, MOV, MKV lub WebM. Inne formaty i pliki powyżej %1$d MB są konwertowane na urządzeniu do WebM 720p, do %2$d sekund.</string>
|
||||
<string name="boot_movie_import">Importuj</string>
|
||||
|
||||
@@ -3445,6 +3445,7 @@
|
||||
<string name="boot_movie_sound">Som</string>
|
||||
<string name="boot_movie_skip">Ignorar o vídeo de arranque</string>
|
||||
<string name="boot_movie_skip_hint">Utilizar um clipe preto de 0,1 segundos como vídeo de arranque do Steam. Aplica-se na próxima sessão.</string>
|
||||
<string name="boot_movie_shuffle">Aleatório</string>
|
||||
<string name="boot_movie_custom">O seu próprio vídeo</string>
|
||||
<string name="boot_movie_custom_hint">MP4, MOV, MKV ou WebM. Outros formatos e ficheiros acima de %1$d MB são convertidos para WebM 720p no dispositivo, até %2$d segundos.</string>
|
||||
<string name="boot_movie_import">Importar</string>
|
||||
|
||||
@@ -3453,6 +3453,7 @@
|
||||
<string name="boot_movie_sound">Som</string>
|
||||
<string name="boot_movie_skip">Pular vídeo de inicialização</string>
|
||||
<string name="boot_movie_skip_hint">Use um clipe preto de 0,1 segundo como vídeo de inicialização do Steam. Aplica-se na próxima sessão.</string>
|
||||
<string name="boot_movie_shuffle">Aleatório</string>
|
||||
<string name="boot_movie_custom">Seu próprio vídeo</string>
|
||||
<string name="boot_movie_custom_hint">MP4, MOV, MKV ou WebM. Outros formatos e arquivos acima de %1$d MB são convertidos para WebM 720p no aparelho, até %2$d segundos.</string>
|
||||
<string name="boot_movie_import">Importar</string>
|
||||
|
||||
@@ -3446,6 +3446,7 @@
|
||||
<string name="boot_movie_sound">Sunet</string>
|
||||
<string name="boot_movie_skip">Omite filmul de pornire</string>
|
||||
<string name="boot_movie_skip_hint">Folosește un clip negru de 0,1 secunde ca film de pornire pentru Steam. Se aplică la următoarea sesiune.</string>
|
||||
<string name="boot_movie_shuffle">Aleatoriu</string>
|
||||
<string name="boot_movie_custom">Videoclipul tău</string>
|
||||
<string name="boot_movie_custom_hint">MP4, MOV, MKV sau WebM. Alte formate și fișierele de peste %1$d MB sunt convertite pe dispozitiv în WebM 720p, până la %2$d secunde.</string>
|
||||
<string name="boot_movie_import">Importă</string>
|
||||
|
||||
@@ -3485,6 +3485,7 @@
|
||||
<string name="boot_movie_sound">Звук</string>
|
||||
<string name="boot_movie_skip">Пропускать стартовое видео</string>
|
||||
<string name="boot_movie_skip_hint">Использовать 0,1-секундный чёрный клип в качестве стартового видео Steam. Применится в следующем сеансе.</string>
|
||||
<string name="boot_movie_shuffle">Случайный порядок</string>
|
||||
<string name="boot_movie_custom">Своё видео</string>
|
||||
<string name="boot_movie_custom_hint">MP4, MOV, MKV или WebM. Другие форматы и файлы больше %1$d МБ преобразуются на устройстве в WebM 720p, до %2$d секунд.</string>
|
||||
<string name="boot_movie_import">Импорт</string>
|
||||
|
||||
@@ -3407,6 +3407,7 @@
|
||||
<string name="boot_movie_sound">Ljud</string>
|
||||
<string name="boot_movie_skip">Hoppa över uppstartsfilmen</string>
|
||||
<string name="boot_movie_skip_hint">Använd ett svart klipp på 0,1 sekunder som uppstartsfilm för Steam. Tillämpas nästa session.</string>
|
||||
<string name="boot_movie_shuffle">Blanda</string>
|
||||
<string name="boot_movie_custom">Egen video</string>
|
||||
<string name="boot_movie_custom_hint">MP4, MOV, MKV eller WebM. Andra format och filer över %1$d MB konverteras till 720p-WebM på enheten, upp till %2$d sekunder.</string>
|
||||
<string name="boot_movie_import">Importera</string>
|
||||
|
||||
@@ -3378,6 +3378,7 @@
|
||||
<string name="boot_movie_sound">เสียง</string>
|
||||
<string name="boot_movie_skip">ข้ามวิดีโอเริ่มต้น</string>
|
||||
<string name="boot_movie_skip_hint">ใช้คลิปสีดำความยาว 0.1 วินาทีเป็นวิดีโอเริ่มต้นของ Steam มีผลในเซสชันถัดไป</string>
|
||||
<string name="boot_movie_shuffle">สุ่ม</string>
|
||||
<string name="boot_movie_custom">วิดีโอของคุณเอง</string>
|
||||
<string name="boot_movie_custom_hint">MP4, MOV, MKV หรือ WebM รูปแบบอื่นและไฟล์ที่ใหญ่กว่า %1$d MB จะถูกแปลงเป็น WebM 720p บนอุปกรณ์ ความยาวไม่เกิน %2$d วินาที</string>
|
||||
<string name="boot_movie_import">นำเข้า</string>
|
||||
|
||||
@@ -3407,6 +3407,7 @@
|
||||
<string name="boot_movie_sound">Ses</string>
|
||||
<string name="boot_movie_skip">Açılış videosunu atla</string>
|
||||
<string name="boot_movie_skip_hint">Steam\'in açılış videosu olarak 0,1 saniyelik siyah bir klip kullanılır. Sonraki oturumda geçerli olur.</string>
|
||||
<string name="boot_movie_shuffle">Karıştır</string>
|
||||
<string name="boot_movie_custom">Kendi videon</string>
|
||||
<string name="boot_movie_custom_hint">MP4, MOV, MKV veya WebM. Diğer biçimler ve %1$d MB üzeri dosyalar cihazda 720p WebM\'e dönüştürülür, en fazla %2$d saniye.</string>
|
||||
<string name="boot_movie_import">İçe aktar</string>
|
||||
|
||||
@@ -3485,6 +3485,7 @@
|
||||
<string name="boot_movie_sound">Звук</string>
|
||||
<string name="boot_movie_skip">Пропускати відео запуску</string>
|
||||
<string name="boot_movie_skip_hint">Використовувати 0,1-секундний чорний кліп як вступне відео Steam. Застосовується з наступного сеансу.</string>
|
||||
<string name="boot_movie_shuffle">Випадковий порядок</string>
|
||||
<string name="boot_movie_custom">Власне відео</string>
|
||||
<string name="boot_movie_custom_hint">MP4, MOV, MKV або WebM. Інші формати й файли понад %1$d МБ перетворюються на пристрої на WebM 720p, до %2$d секунд.</string>
|
||||
<string name="boot_movie_import">Імпорт</string>
|
||||
|
||||
@@ -3378,6 +3378,7 @@
|
||||
<string name="boot_movie_sound">Âm thanh</string>
|
||||
<string name="boot_movie_skip">Bỏ qua phim khởi động</string>
|
||||
<string name="boot_movie_skip_hint">Dùng đoạn clip đen 0,1 giây làm phim khởi động của Steam. Áp dụng trong phiên chạy tiếp theo.</string>
|
||||
<string name="boot_movie_shuffle">Ngẫu nhiên</string>
|
||||
<string name="boot_movie_custom">Video của bạn</string>
|
||||
<string name="boot_movie_custom_hint">MP4, MOV, MKV hoặc WebM. Định dạng khác và tệp trên %1$d MB được chuyển sang WebM 720p ngay trên thiết bị, tối đa %2$d giây.</string>
|
||||
<string name="boot_movie_import">Nhập</string>
|
||||
|
||||
@@ -3378,6 +3378,7 @@
|
||||
<string name="boot_movie_sound">声音</string>
|
||||
<string name="boot_movie_skip">跳过启动影片</string>
|
||||
<string name="boot_movie_skip_hint">用一段 0.1 秒的黑色片段作为 Steam 的启动影片。下次会话生效。</string>
|
||||
<string name="boot_movie_shuffle">随机播放</string>
|
||||
<string name="boot_movie_custom">自定义视频</string>
|
||||
<string name="boot_movie_custom_hint">MP4、MOV、MKV 或 WebM。其他格式及超过 %1$d MB 的文件会在设备上转换为 720p WebM,最长 %2$d 秒。</string>
|
||||
<string name="boot_movie_import">导入</string>
|
||||
|
||||
@@ -3375,6 +3375,7 @@
|
||||
<string name="boot_movie_sound">聲音</string>
|
||||
<string name="boot_movie_skip">跳過啟動影片</string>
|
||||
<string name="boot_movie_skip_hint">以 0.1 秒全黑片段作為 Steam 的啟動影片。下次工作階段生效。</string>
|
||||
<string name="boot_movie_shuffle">隨機播放</string>
|
||||
<string name="boot_movie_custom">自訂影片</string>
|
||||
<string name="boot_movie_custom_hint">MP4、MOV、MKV 或 WebM。其他格式及超過 %1$d MB 的檔案會在裝置上轉換為 720p WebM,最長 %2$d 秒。</string>
|
||||
<string name="boot_movie_import">匯入</string>
|
||||
|
||||
@@ -3375,6 +3375,7 @@
|
||||
<string name="boot_movie_sound">聲音</string>
|
||||
<string name="boot_movie_skip">跳過啟動影片</string>
|
||||
<string name="boot_movie_skip_hint">使用 0.1 秒的黑色影片片段作為 Steam 的啟動影片。將於下次工作階段生效。</string>
|
||||
<string name="boot_movie_shuffle">隨機播放</string>
|
||||
<string name="boot_movie_custom">自訂影片</string>
|
||||
<string name="boot_movie_custom_hint">MP4、MOV、MKV 或 WebM。其他格式及超過 %1$d MB 的檔案會在裝置上轉換為 720p WebM,最長 %2$d 秒。</string>
|
||||
<string name="boot_movie_import">匯入</string>
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
<resources>
|
||||
<string name="community_title">Community controls</string>
|
||||
<string name="community_home_hint">Browse, import, and share on-screen controls</string>
|
||||
<string name="community_description">Discover controls made by the community. Packs include button artwork, layout, and actions. Review a pack before applying it to a profile.</string>
|
||||
<string name="community_target">Apply to</string>
|
||||
<string name="community_search">Search name, author, or game</string>
|
||||
<string name="community_empty">No controls match this screen and search.</string>
|
||||
<string name="community_refresh">Check for community packs</string>
|
||||
<string name="community_refreshed">Community catalog updated.</string>
|
||||
<string name="community_import">Import controls or skin (.zip)</string>
|
||||
<string name="community_export">Export this layout and actions</string>
|
||||
<string name="community_share">Share your controls</string>
|
||||
<string name="community_submit_hint">Export your controls and share the ZIP directly, or submit it through the selected source’s website. Each source manages its own uploads and catalog. GitHub sources require a GitHub account.</string>
|
||||
<string name="community_submit">Open source submissions</string>
|
||||
<string name="community_exported">Pack exported. You can share the ZIP directly or attach it to a community submission.</string>
|
||||
<string name="community_apply_hint">%1$d controls. Apply layout and actions to %2$s · %3$s? This selects a new local copy. Other profiles keep their controls.</string>
|
||||
<string name="community_apply">Apply controls</string>
|
||||
<string name="community_installed">Controls installed and selected for this profile.</string>
|
||||
<string name="community_failed">Could not load or save community controls.</string>
|
||||
<string name="community_game_controls">On-screen controls profile</string>
|
||||
<string name="community_game_controls_hint">Use this profile’s screen layouts and actions. Physical controls follow your general settings.</string>
|
||||
<string name="community_sources">Sources</string>
|
||||
<string name="community_source">Source</string>
|
||||
<string name="community_screen">Screen</string>
|
||||
<string name="community_add_source">Connect another source</string>
|
||||
<string name="community_remove_source">Remove source</string>
|
||||
<string name="community_source_url">Repository or catalog URL</string>
|
||||
<string name="community_source_hint">Enter a public GitHub repository or an HTTPS catalog.json or manifest.json URL. Supports DroidDeck controls packs and ARMSX2 controller skins. Downloads come directly from the source.</string>
|
||||
<string name="community_connect">Connect</string>
|
||||
<string name="community_export_skin">Export skin artwork (.zip)</string>
|
||||
<string name="community_previous">Previous</string>
|
||||
<string name="community_next">Next</string>
|
||||
<string name="community_page">Page %1$d of %2$d</string>
|
||||
</resources>
|
||||
@@ -3621,6 +3621,7 @@
|
||||
<string name="boot_movie_sound">Sound</string>
|
||||
<string name="boot_movie_skip">Skip boot movie</string>
|
||||
<string name="boot_movie_skip_hint">Use a 0.1-second black clip as Steam’s startup movie. Applies next session.</string>
|
||||
<string name="boot_movie_shuffle">Shuffle</string>
|
||||
<string name="boot_movie_custom">Your own movie</string>
|
||||
<string name="boot_movie_custom_hint">MP4, MOV, MKV or WebM. Other formats and files over %1$d MB are converted to 720p WebM on the device, up to %2$d seconds.</string>
|
||||
<string name="boot_movie_import">Import</string>
|
||||
|
||||
@@ -3,7 +3,6 @@ package com.droiddeck.launcher.frontend
|
||||
import com.droiddeck.launcher.assumeFilePermissionsEnforced
|
||||
import android.os.Environment
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||
import java.io.File
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
@@ -367,15 +366,6 @@ class AddedExesTest {
|
||||
assertEquals("$clash-2", guests.last())
|
||||
}
|
||||
|
||||
@Test fun aFolderNamedStoresIsNotBoundOverTheInternalStoreRoot() {
|
||||
noGamesFolders()
|
||||
val stores = File(tmp.newFolder("card"), "Stores").apply { exe(File(this, "One/One.exe")) }
|
||||
val result = AddedGames.addFolder(app, stores)
|
||||
val guest = SessionPrefs.gameFolderBinds(app).single().second
|
||||
assertTrue(guest != StoreInstallRoot.INTERNAL_GUEST && guest.startsWith("${AddedGames.GUEST_DIR}/Stores-"))
|
||||
assertEquals("$guest/One/One.exe", result.added.single().guestExe)
|
||||
}
|
||||
|
||||
@Test fun aRemovedSingleExeGameStaysOffUntilPickedAgain() {
|
||||
noGamesFolders()
|
||||
val pick = onStorage("Download/Celeste/Celeste.exe")
|
||||
|
||||
@@ -3,7 +3,6 @@ package com.droiddeck.launcher.frontend
|
||||
import com.droiddeck.launcher.session.GameStorage
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.stores.StoreGameSidecar
|
||||
import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||
import java.io.File
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
@@ -183,41 +182,6 @@ class GamesFolderMigrationTest {
|
||||
assertEquals(listOf(pc.path to AddedGames.GUEST_DIR + "/PC"), binds)
|
||||
}
|
||||
|
||||
@Test fun aMigratedFolderNamedStoresDoesNotTakeTheInternalStoreGuest() {
|
||||
val stores = File(tmp.newFolder("card"), "Stores").apply { exe(this, "One/One.exe") }
|
||||
val pc = tmp.newFolder("PC").apply { exe(this, "Two/Two.exe") }
|
||||
SessionPrefs.setAddedGamesDirs(app, listOf(stores.path, pc.path))
|
||||
GamesFolderMigration.run(app)
|
||||
val binds = SessionPrefs.gameFolderBinds(app).toMap()
|
||||
assertTrue(binds.getValue(stores.path) != StoreInstallRoot.INTERNAL_GUEST)
|
||||
assertEquals(AddedGames.GUEST_DIR + "/PC", binds.getValue(pc.path))
|
||||
val games = AddedGames.scan(app).associateBy { it.name }
|
||||
assertEquals(binds.getValue(stores.path) + "/One/One.exe", games.getValue("One").guestExe)
|
||||
}
|
||||
|
||||
@Test fun aSavedBindAtTheInternalStoreGuestIsRepathed() {
|
||||
val stores = File(tmp.newFolder("card"), "Stores").apply { exe(this, "One/One.exe") }
|
||||
val pc = tmp.newFolder("PC").apply { exe(this, "Two/Two.exe") }
|
||||
SessionPrefs.setGameFolderBinds(
|
||||
app,
|
||||
listOf(stores.path to StoreInstallRoot.INTERNAL_GUEST, pc.path to AddedGames.GUEST_DIR + "/PC"),
|
||||
)
|
||||
GamesFolderMigration.run(app)
|
||||
val binds = SessionPrefs.gameFolderBinds(app).toMap()
|
||||
assertTrue(binds.getValue(stores.path) != StoreInstallRoot.INTERNAL_GUEST)
|
||||
assertTrue(binds.getValue(stores.path).startsWith("${AddedGames.GUEST_DIR}/Stores-"))
|
||||
assertEquals(AddedGames.GUEST_DIR + "/PC", binds.getValue(pc.path))
|
||||
assertTrue(binds.values.none { it == StoreInstallRoot.INTERNAL_GUEST })
|
||||
assertEquals(binds.getValue(stores.path) + "/One/One.exe", AddedGames.guestPath(app, File(stores, "One/One.exe")))
|
||||
val installer = File(stores, "GOG/Game/setup_1.exe").apply { parentFile?.mkdirs(); writeText("MZ") }
|
||||
val guestInstaller = AddedGames.guestPath(app, installer)!!
|
||||
val extractorBinds = StoreInstallRoot.guestBinds(app).map { it.substringBeforeLast(':') to it.substringAfterLast(':') }
|
||||
val covering = extractorBinds.filter { (_, mount) -> guestInstaller.startsWith("$mount/") }.maxByOrNull { it.second.length }!!
|
||||
assertEquals(installer.canonicalFile, File(covering.first + guestInstaller.removePrefix(covering.second)).canonicalFile)
|
||||
val internalInstaller = "${StoreInstallRoot.INTERNAL_GUEST}/GOG/Game/setup_1.exe"
|
||||
assertTrue(extractorBinds.none { (_, mount) -> internalInstaller == mount || internalInstaller.startsWith("$mount/") })
|
||||
}
|
||||
|
||||
@Test fun twoFoldersOfOneNameKeepTheirOwnGuestPaths() {
|
||||
val a = File(tmp.newFolder("a"), "Games").apply { mkdirs() }
|
||||
val b = File(tmp.newFolder("b"), "Games").apply { mkdirs() }
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import android.graphics.Color
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.annotation.GraphicsMode
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.util.zip.ZipEntry
|
||||
import java.util.zip.ZipOutputStream
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28])
|
||||
@GraphicsMode(GraphicsMode.Mode.NATIVE)
|
||||
class ArmsControlSkinsTest {
|
||||
private val context get() = RuntimeEnvironment.getApplication()
|
||||
@Before fun reset() { context.getSharedPreferences("input-profiles", Context.MODE_PRIVATE).edit().clear().commit() }
|
||||
private fun base() = CommunityControls.parse(context, context.assets.open("community-controls/packs/compact-gamepad.ddcontrols.zip").use { it.readBytes() })
|
||||
private fun png(color: Int, size: Int = 16): ByteArray {
|
||||
val bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888).apply { eraseColor(color) }
|
||||
return ByteArrayOutputStream().also { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it); bitmap.recycle() }.toByteArray()
|
||||
}
|
||||
private fun zip(vararg files: Pair<String, ByteArray>): ByteArray {
|
||||
val bytes = ByteArrayOutputStream()
|
||||
ZipOutputStream(bytes).use { z -> files.forEach { (name, data) -> z.putNextEntry(ZipEntry(name)); z.write(data); z.closeEntry() } }
|
||||
return bytes.toByteArray()
|
||||
}
|
||||
@Test fun skinAppliesToNativeTargetsAndPreservesBindingsAndGeometry() {
|
||||
val old = base()
|
||||
val skin = ArmsControlSkins.parse(context, zip("folder/ic_controller_cross_button.png" to png(Color.RED),
|
||||
"square.png" to png(Color.BLUE)), old.layout, old.bindings, "Community skin")
|
||||
assertEquals(old.bindings.elements, skin.bindings.elements)
|
||||
assertEquals(old.layout.elements.map { it.x to it.y }, skin.layout.elements.map { it.x to it.y })
|
||||
assertEquals("skin_cross.png", skin.layout.elements.first { it.id == "a" }.image)
|
||||
assertEquals("skin_square.png", skin.layout.elements.first { it.id == "x" }.image)
|
||||
assertEquals("", skin.layout.elements.first { it.id == "b" }.image)
|
||||
assertNotEquals(old.layout.id, skin.layout.id)
|
||||
}
|
||||
@Test fun separateStickArtworkSurvivesInstallExportAndReimport() {
|
||||
val old = base()
|
||||
val skin = ArmsControlSkins.parse(context, zip("analog_base.png" to png(Color.RED),
|
||||
"analog_stick_left.png" to png(Color.GREEN), "analog_stick_right.png" to png(Color.BLUE)), old.layout, old.bindings, "Stick skin")
|
||||
val left = skin.layout.elements.first { it.id == "left-stick" }
|
||||
val right = skin.layout.elements.first { it.id == "right-stick" }
|
||||
assertEquals(left.image, right.image)
|
||||
assertNotEquals(left.stickImage, right.stickImage)
|
||||
val installed = CommunityControls.install(context, skin, InputProfile.GAME, InputRole.PRIMARY)
|
||||
val layout = installed.layout(InputProfile.GAME, InputRole.PRIMARY)!!
|
||||
val bindings = installed.preset(installed.profile(InputProfile.GAME).binding(InputRole.PRIMARY))
|
||||
val pack = CommunityControls.parse(context, CommunityControls.export(context, layout, bindings))
|
||||
assertEquals(3, pack.images.size)
|
||||
assertNotEquals("", pack.layout.elements.first { it.id == "left-stick" }.stickImage)
|
||||
val artwork = ArmsControlSkins.export(context, layout, bindings)
|
||||
val imported = ArmsControlSkins.parse(context, artwork, old.layout, old.bindings, "Shared skin")
|
||||
assertEquals(4, imported.images.size)
|
||||
assertEquals(old.bindings.elements, imported.bindings.elements)
|
||||
}
|
||||
@Test fun partialStickSkinsKeepExistingBaseOrThumbArtwork() {
|
||||
val old = base()
|
||||
val full = ArmsControlSkins.parse(context, zip("analog_base.png" to png(Color.RED),
|
||||
"analog_stick.png" to png(Color.GREEN)), old.layout, old.bindings, "Full skin")
|
||||
val library = CommunityControls.install(context, full, InputProfile.GAME, InputRole.PRIMARY)
|
||||
val layout = library.layout(InputProfile.GAME, InputRole.PRIMARY)!!
|
||||
val bindings = library.preset(library.profile(InputProfile.GAME).binding(InputRole.PRIMARY))
|
||||
val original = layout.elements.first { it.id == "left-stick" }
|
||||
for (thumbOnly in listOf(true, false)) {
|
||||
val key = if (thumbOnly) "analog_stick.png" else "analog_base.png"
|
||||
val partial = ArmsControlSkins.parse(context, zip(key to png(Color.BLUE)), layout, bindings, "Partial skin")
|
||||
val element = partial.layout.elements.first { it.id == "left-stick" }
|
||||
val retained = if (thumbOnly) original.image else original.stickImage
|
||||
assertEquals(retained, if (thumbOnly) element.image else element.stickImage)
|
||||
assertArrayEquals(InputButtonImages.file(context, retained)!!.readBytes(), partial.images.getValue(retained))
|
||||
assertEquals(bindings.elements, partial.bindings.elements)
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun downsamplesLargeImagesBeforeStoringThem() {
|
||||
val old = base()
|
||||
val skin = ArmsControlSkins.parse(context, zip("cross.png" to png(Color.RED, 2048)), old.layout, old.bindings, "Large skin")
|
||||
val bytes = skin.images.values.single()
|
||||
val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
|
||||
assertTrue(bitmap.width <= 512 && bitmap.height <= 512)
|
||||
bitmap.recycle()
|
||||
}
|
||||
@Test fun rejectsTraversalDuplicateButtonsAndArchivesWithoutMatchingImages() {
|
||||
val old = base()
|
||||
for (files in listOf(arrayOf("../cross.png" to png(Color.RED)),
|
||||
arrayOf("cross.png" to png(Color.RED), "ic_controller_cross_button.png" to png(Color.RED)),
|
||||
arrayOf("readme.txt" to byteArrayOf()), arrayOf("cross.png" to byteArrayOf(1, 2))))
|
||||
assertThrows(IllegalArgumentException::class.java) { ArmsControlSkins.parse(context, zip(*files), old.layout, old.bindings, "Invalid") }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
import java.io.ByteArrayInputStream
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.util.zip.ZipEntry
|
||||
import java.util.zip.ZipInputStream
|
||||
import java.util.zip.ZipOutputStream
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28])
|
||||
class CommunityControlsTest {
|
||||
private val context get() = RuntimeEnvironment.getApplication()
|
||||
private fun starter() = context.assets.open("community-controls/packs/compact-gamepad.ddcontrols.zip").use { it.readBytes() }
|
||||
@Before fun reset() {
|
||||
context.getSharedPreferences("input-profiles", Context.MODE_PRIVATE).edit().clear().commit()
|
||||
}
|
||||
private fun archive(vararg entries: Pair<String, ByteArray>): ByteArray {
|
||||
val out = ByteArrayOutputStream()
|
||||
ZipOutputStream(out).use { zip -> entries.forEach { (name, data) ->
|
||||
zip.putNextEntry(ZipEntry(name)); zip.write(data); zip.closeEntry()
|
||||
} }
|
||||
return out.toByteArray()
|
||||
}
|
||||
private fun manifest(): JSONObject = ZipInputStream(ByteArrayInputStream(starter())).use {
|
||||
it.nextEntry; JSONObject(it.readBytes().toString(Charsets.UTF_8))
|
||||
}
|
||||
private fun rejects(action: () -> Unit) {
|
||||
try { action(); fail("Expected rejected controls") } catch (_: IllegalArgumentException) { }
|
||||
}
|
||||
|
||||
@Test fun starterInstallsIndependentNativeGamepadWithoutChangingOtherParts() {
|
||||
val original = InputLibraries.read(context)
|
||||
val pack = CommunityControls.parse(context, starter())
|
||||
val second = CommunityControls.parse(context, starter())
|
||||
assertNotEquals(pack.layout.id, second.layout.id)
|
||||
assertNotEquals(pack.bindings.id, second.bindings.id)
|
||||
val changed = CommunityControls.install(context, pack, InputProfile.GAME, InputRole.PRIMARY)
|
||||
assertEquals(pack.layout, changed.layout(InputProfile.GAME, InputRole.PRIMARY))
|
||||
assertEquals(InputAction.Native(InputControl.A), changed.preset(changed.profile(InputProfile.GAME).binding(InputRole.PRIMARY)).elements["a"])
|
||||
assertEquals(original.profile(InputProfile.DESKTOP), changed.profile(InputProfile.DESKTOP))
|
||||
assertEquals(original.profile(InputProfile.GAME).parts[InputRole.PHYSICAL], changed.profile(InputProfile.GAME).parts[InputRole.PHYSICAL])
|
||||
assertEquals(original.profile(InputProfile.GAME).parts[InputRole.SECONDARY], changed.profile(InputProfile.GAME).parts[InputRole.SECONDARY])
|
||||
assertEquals(changed, InputLibraries.read(context))
|
||||
}
|
||||
|
||||
@Test fun packRoundTripPreservesImagesStyleActionsAndClicks() {
|
||||
val base = CommunityControls.parse(context, starter())
|
||||
val imageName = "roundtrip.png"
|
||||
val bitmap = Bitmap.createBitmap(8, 8, Bitmap.Config.ARGB_8888)
|
||||
val png = ByteArrayOutputStream().also { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }.toByteArray()
|
||||
bitmap.recycle()
|
||||
val layout = base.layout.copy(elements = base.layout.elements.map { if (it.id == "a") it.copy(image = imageName, showLabel = false, toggle = true) else it })
|
||||
val bindings = base.bindings.copy(elements = base.bindings.elements + ("a" to InputAction.Keys(listOf(29, 30))),
|
||||
clicks = mapOf("left-stick" to InputAction.MouseButton(272)))
|
||||
val installed = CommunityControls.install(context, CommunityControls.Pack(layout, bindings, mapOf(imageName to png)), InputProfile.GAME, InputRole.PRIMARY)
|
||||
val saved = installed.layout(InputProfile.GAME, InputRole.PRIMARY)!!
|
||||
val exported = CommunityControls.export(context, saved, installed.preset(installed.profile(InputProfile.GAME).binding(InputRole.PRIMARY)))
|
||||
val imported = CommunityControls.parse(context, exported)
|
||||
assertEquals(saved.copy(id = imported.layout.id), imported.layout)
|
||||
assertEquals(bindings.elements, imported.bindings.elements)
|
||||
assertEquals(bindings.clicks, imported.bindings.clicks)
|
||||
assertArrayEquals(png, imported.images.values.single())
|
||||
assertNotEquals(imageName, saved.elements.first { it.id == "a" }.image)
|
||||
}
|
||||
|
||||
@Test fun parserDoesNotChangePreferences() {
|
||||
val before = InputLibraries.read(context)
|
||||
CommunityControls.parse(context, starter())
|
||||
assertEquals(before, InputLibraries.read(context))
|
||||
}
|
||||
|
||||
@Test fun rejectsTraversalAndUnexpectedEntries() {
|
||||
rejects { CommunityControls.parse(context, archive("../controls.json" to byteArrayOf())) }
|
||||
rejects { CommunityControls.parse(context, archive("images/../x.png" to byteArrayOf())) }
|
||||
rejects { CommunityControls.parse(context, archive("unrelated" to byteArrayOf())) }
|
||||
}
|
||||
|
||||
@Test fun rejectsMissingAndUnreferencedImages() {
|
||||
val doc = manifest()
|
||||
doc.getJSONObject("layout").getJSONArray("elements").getJSONObject(0).put("image", "missing.png")
|
||||
rejects { CommunityControls.parse(context, archive("controls.json" to doc.toString().toByteArray())) }
|
||||
rejects { CommunityControls.parse(context, archive("controls.json" to manifest().toString().toByteArray(), "images/unused.png" to byteArrayOf())) }
|
||||
}
|
||||
|
||||
@Test fun rejectsFutureFormatsAndInvalidActions() {
|
||||
val doc = manifest().put("version", 99)
|
||||
rejects { CommunityControls.parse(context, archive("controls.json" to doc.toString().toByteArray())) }
|
||||
doc.put("version", 1).getJSONObject("bindings").getJSONObject("elements").put("a", JSONObject().put("type", "shell").put("command", "bad"))
|
||||
rejects { CommunityControls.parse(context, archive("controls.json" to doc.toString().toByteArray())) }
|
||||
}
|
||||
|
||||
@Test fun importingInvalidNativePackPreservesItsOriginalError() {
|
||||
val doc = manifest()
|
||||
doc.getJSONObject("layout").getJSONArray("elements").getJSONObject(0).put("image", "missing.png")
|
||||
val old = CommunityControls.parse(context, starter())
|
||||
val error = assertThrows(IllegalArgumentException::class.java) {
|
||||
CommunityControls.importFile(context, archive("controls.json" to doc.toString().toByteArray()), old.layout, old.bindings)
|
||||
}
|
||||
assertEquals("Missing or unexpected button images.", error.message)
|
||||
}
|
||||
|
||||
@Test fun rejectsCorruptImages() {
|
||||
val doc = manifest()
|
||||
doc.getJSONObject("layout").getJSONArray("elements").getJSONObject(0).put("image", "invalid.png")
|
||||
rejects { CommunityControls.parse(context, archive("controls.json" to doc.toString().toByteArray(), "images/invalid.png" to byteArrayOf(0, 1, 2))) }
|
||||
}
|
||||
|
||||
@Test fun boundedReaderRejectsOversizeBeforeBufferingAllInput() {
|
||||
rejects { CommunityControls.readLimited(ByteArrayInputStream(ByteArray(8192)), 16) }
|
||||
assertEquals(16, CommunityControls.readLimited(ByteArrayInputStream(ByteArray(16)), 16).size)
|
||||
rejects { CommunityControls.parse(context, archive("controls.json" to ByteArray(2_000_001))) }
|
||||
}
|
||||
|
||||
@Test fun bundledCatalogMatchesPackAndRejectsExternalPaths() {
|
||||
val entries = CommunityControls.bundled(context)
|
||||
assertTrue(entries.isNotEmpty())
|
||||
entries.forEach {
|
||||
assertEquals(it.name, CommunityControls.download(context, it).layout.name)
|
||||
val preview = requireNotNull(CommunityControls.preview(context, it))
|
||||
assertTrue(maxOf(preview.width, preview.height) <= 256)
|
||||
preview.recycle()
|
||||
}
|
||||
rejects { CommunityControls.download(context, entries.first().copy(sha256 = "0".repeat(64))) }
|
||||
val doc = JSONObject(context.assets.open("community-controls/catalog.json").bufferedReader().use { it.readText() })
|
||||
doc.getJSONArray("controls").getJSONObject(0).put("file", "https://example.com/pack.zip")
|
||||
rejects { CommunityControls.catalog(doc.toString()) }
|
||||
doc.getJSONArray("controls").getJSONObject(0).put("file", "packs/../../other.ddcontrols.zip")
|
||||
rejects { CommunityControls.catalog(doc.toString()) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.content.Context
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28])
|
||||
class ControlSourcesTest {
|
||||
private val context get() = RuntimeEnvironment.getApplication()
|
||||
@Before fun reset() { context.getSharedPreferences("community-control-sources", Context.MODE_PRIVATE).edit().clear().commit() }
|
||||
@Test fun hasRemoteArmsSourceWithoutBundlingItsArtwork() {
|
||||
assertEquals(listOf(ControlSources.DROIDDECK, ControlSources.ARMSX2), ControlSources.read(context))
|
||||
assertTrue(ControlSources.ARMSX2.manifest.contains("bagasromadon/ARMSX2-CustomControllerSkins"))
|
||||
}
|
||||
@Test fun githubRepositoriesAndFileLinksResolveToManifests() {
|
||||
val repo = ControlSources.candidates("https://github.com/example/controls")
|
||||
assertEquals(listOf("https://raw.githubusercontent.com/example/controls/main/catalog.json",
|
||||
"https://raw.githubusercontent.com/example/controls/main/manifest.json"), repo.map { it.manifest })
|
||||
assertEquals("https://raw.githubusercontent.com/example/controls/dev/skins/manifest.json",
|
||||
ControlSources.candidates("https://github.com/example/controls/blob/dev/skins/manifest.json").single().manifest)
|
||||
}
|
||||
@Test fun customSourcesPersistAndCanBeRemovedWithoutLosingDefaults() {
|
||||
val source = ControlSources.candidates("https://example.com/controls/catalog.json").single()
|
||||
ControlSources.add(context, source)
|
||||
assertEquals(source, ControlSources.read(context).last())
|
||||
assertThrows(IllegalArgumentException::class.java) { ControlSources.add(context, source) }
|
||||
ControlSources.remove(context, source)
|
||||
assertEquals(2, ControlSources.read(context).size)
|
||||
}
|
||||
@Test fun pathsStayWithinSourceAndEncodeSpaces() {
|
||||
assertEquals("https://raw.githubusercontent.com/bagasromadon/ARMSX2-CustomControllerSkins/main/Skins/Black%20Gold.zip",
|
||||
ControlSources.ARMSX2.url("Skins/Black Gold.zip"))
|
||||
for (path in listOf("../other.zip", "packs/../x.zip", "https://other.com/x", "/x", "x%2f..zip", "x?bad", "x\\bad"))
|
||||
assertThrows(IllegalArgumentException::class.java) { ControlSources.ARMSX2.url(path) }
|
||||
for (url in listOf("http://example.com/catalog.json", "https://user:secret@example.com/catalog.json", "file:///tmp/catalog.json", "https://example.com"))
|
||||
assertThrows(IllegalArgumentException::class.java) { ControlSources.candidates(url) }
|
||||
}
|
||||
@Test fun parsesArmsCatalogAndKeepsSourceAndOptionalLicenseSeparate() {
|
||||
val raw = """{"skins":[{"name":"Black Gold", "author":"maker", "file":"Skins/Black Gold.zip", "preview":"Previews/Black_Gold.png"}]}"""
|
||||
val entry = CommunityControls.catalog(raw, ControlSources.ARMSX2).single()
|
||||
assertTrue(entry.skin)
|
||||
assertEquals("", entry.license)
|
||||
assertEquals("", entry.sha256)
|
||||
assertEquals(ControlSources.ARMSX2, entry.source)
|
||||
assertNotEquals(entry.key, entry.copy(source = ControlSources.DROIDDECK).key)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.content.Context
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28])
|
||||
class GameInputControlsTest {
|
||||
private val context get() = RuntimeEnvironment.getApplication()
|
||||
@Before fun reset() {
|
||||
for (name in listOf("input-profiles", "input-game-controls"))
|
||||
context.getSharedPreferences(name, Context.MODE_PRIVATE).edit().clear().commit()
|
||||
}
|
||||
private fun library(): InputLibrary {
|
||||
val result = InputLibraries.update(context) { it.duplicateProfile(InputProfile.GAME, "My game", "my-game") }
|
||||
GameInputControls.set(context, "42", "my-game")
|
||||
return result
|
||||
}
|
||||
@Test fun directLaunchResolvesTheGameBeforeSessionServiceStarts() {
|
||||
val original = library()
|
||||
val state = com.droiddeck.launcher.session.SessionState
|
||||
val previousRunning = state.running
|
||||
val previousMode = state.mode
|
||||
val previousGame = state.gameId
|
||||
try {
|
||||
state.running = false
|
||||
state.mode = com.droiddeck.launcher.session.SessionService.MODE_STEAM
|
||||
state.gameId = null
|
||||
val intent = android.content.Intent(context, com.droiddeck.launcher.SessionActivity::class.java)
|
||||
.putExtra(com.droiddeck.launcher.session.SessionService.EXTRA_MODE, com.droiddeck.launcher.session.SessionService.MODE_RUN)
|
||||
.putExtra(com.droiddeck.launcher.session.SessionService.EXTRA_GAME_ID, "42")
|
||||
val activity = org.robolectric.Robolectric.buildActivity(com.droiddeck.launcher.SessionActivity::class.java, intent).get()
|
||||
assertEquals("42", activity.inputGameScope())
|
||||
assertEquals(original.profile("my-game").binding(InputRole.PRIMARY),
|
||||
GameInputControls.resolve(context, original, false, activity.inputGameScope()).activePart(false, InputRole.PRIMARY).bindings)
|
||||
} finally { state.running = previousRunning; state.mode = previousMode; state.gameId = previousGame }
|
||||
}
|
||||
@Test fun gameOverridesOnlyScreenPartsAndRestoresGeneralControlsOnExit() {
|
||||
val original = library()
|
||||
val game = GameInputControls.resolve(context, original, false, "42")
|
||||
for (role in listOf(InputRole.PRIMARY, InputRole.SECONDARY))
|
||||
assertEquals(original.profile("my-game").binding(role), game.activePart(false, role).bindings)
|
||||
assertEquals(original.activePart(false, InputRole.PHYSICAL), game.activePart(false, InputRole.PHYSICAL))
|
||||
assertEquals(original, GameInputControls.resolve(context, original, false, null))
|
||||
assertEquals(original, GameInputControls.resolve(context, original, false, "43"))
|
||||
assertEquals(original, InputLibraries.read(context))
|
||||
}
|
||||
@Test fun manualProfileAndScreenChoicesTakePriority() {
|
||||
val original = library()
|
||||
val manual = original.selectProfile(false, InputProfile.DESKTOP)
|
||||
assertEquals(manual, GameInputControls.resolve(context, manual, false, "42"))
|
||||
val role = InputRole.PRIMARY
|
||||
val chosen = original.profile(InputProfile.DESKTOP).binding(role)
|
||||
val mixed = original.selectPart(false, role, chosen)
|
||||
val effective = GameInputControls.resolve(context, mixed, false, "42")
|
||||
assertEquals(chosen, effective.activePart(false, role).bindings)
|
||||
assertEquals(original.profile("my-game").binding(InputRole.SECONDARY), effective.activePart(false, InputRole.SECONDARY).bindings)
|
||||
}
|
||||
@Test fun gameResetClearsOnlyTheSelectedControlsMapping() {
|
||||
library()
|
||||
GameInputControls.set(context, "43", InputProfile.DESKTOP)
|
||||
com.droiddeck.launcher.session.GameProfileManager.reset(context, "42")
|
||||
assertNull(GameInputControls.profile(context, "42"))
|
||||
assertEquals(InputProfile.DESKTOP, GameInputControls.profile(context, "43"))
|
||||
}
|
||||
@Test fun deletedProfileAndClearedOverridesFallBackToGeneral() {
|
||||
val original = library()
|
||||
val removed = original.removeProfile("my-game")
|
||||
assertEquals(removed, GameInputControls.resolve(context, removed, false, "42"))
|
||||
GameInputControls.set(context, "42", null)
|
||||
assertNull(GameInputControls.profile(context, "42"))
|
||||
assertEquals(original, GameInputControls.resolve(context, original, false, "42"))
|
||||
}
|
||||
}
|
||||
@@ -94,6 +94,7 @@ class BootMovieTest {
|
||||
@Test fun resetCoversTheChoiceButNotTheImportedName() {
|
||||
assertTrue(SettingsReset.isSessionSetting("bootMovie"))
|
||||
assertTrue(SettingsReset.isSessionSetting("bootMovieSound"))
|
||||
assertTrue(SettingsReset.isSessionSetting("bootMovieShuffle"))
|
||||
assertFalse(SettingsReset.isSessionSetting("bootMovieCustomName"))
|
||||
}
|
||||
}
|
||||
@@ -63,4 +63,140 @@ class StartupMovieConfigTest {
|
||||
assertTrue(SessionFiles.resetMissingStartupMovie(file, false))
|
||||
assertNull(SessionFiles.startupMoviePath(file))
|
||||
}
|
||||
|
||||
@Test fun shuffleIsWrittenIntoBothMovieSectionsAndReadBack() {
|
||||
val file = config(SessionFiles.BOOT_MOVIE_PATH, "0", SessionFiles.BOOT_MOVIE_PATH)
|
||||
assertEquals(false, SessionFiles.startupMovieShuffle(file))
|
||||
assertTrue(SessionFiles.setStartupMovieShuffle(file, true))
|
||||
assertEquals(true, SessionFiles.startupMovieShuffle(file))
|
||||
assertEquals(2, Regex("\"Shuffle\"\\s+\"1\"").findAll(file.readText()).count())
|
||||
assertEquals(SessionFiles.BOOT_MOVIE_PATH, SessionFiles.startupMoviePath(file))
|
||||
}
|
||||
|
||||
@Test fun turningShuffleOffKeepsTheSelectedMovie() {
|
||||
val file = config(SessionFiles.BOOT_MOVIE_PATH, "0", "/uioverrides/movies/Undertale.webm")
|
||||
SessionFiles.setStartupMovieShuffle(file, true)
|
||||
assertTrue(SessionFiles.setStartupMovieShuffle(file, false))
|
||||
assertEquals(false, SessionFiles.startupMovieShuffle(file))
|
||||
assertEquals("/uioverrides/movies/Undertale.webm", SessionFiles.startupMoviePath(file))
|
||||
}
|
||||
|
||||
@Test fun shuffleOffLeavesAConfigWithoutTheKeyUntouched() {
|
||||
val file = config(SessionFiles.BOOT_MOVIE_PATH, "0", SessionFiles.BOOT_MOVIE_PATH)
|
||||
val before = file.readText()
|
||||
assertTrue(SessionFiles.setStartupMovieShuffle(file, false))
|
||||
assertEquals(before, file.readText())
|
||||
}
|
||||
|
||||
@Test fun shuffleDoesNotChangeOtherProgramSettings() {
|
||||
val file = config(SessionFiles.BOOT_MOVIE_PATH, "0", SessionFiles.BOOT_MOVIE_PATH)
|
||||
val text = file.readText().replace(
|
||||
"\t\t\t}\n\t\t}\n\t}\n",
|
||||
"\t\t\t}\n\t\t}\n\t\t\"OtherProgram\"\n\t\t{\n\t\t\t\"Shuffle\"\t\t\"0\"\n\t\t}\n\t}\n",
|
||||
)
|
||||
file.writeText(text)
|
||||
assertTrue(SessionFiles.setStartupMovieShuffle(file, true))
|
||||
val updated = file.readText()
|
||||
assertEquals(2, Regex("\"Shuffle\"\\s+\"1\"").findAll(updated).count())
|
||||
assertEquals(1, Regex("\"Shuffle\"\\s+\"0\"").findAll(updated).count())
|
||||
}
|
||||
|
||||
@Test fun shuffleIsNotAddedWhenThereIsNoMovieSection() {
|
||||
val file = folder.newFile().also { it.writeText("\"InstallConfigStore\"\n{\n}\n") }
|
||||
val before = file.readText()
|
||||
assertTrue(SessionFiles.setStartupMovieShuffle(file, true))
|
||||
assertEquals(before, file.readText())
|
||||
assertEquals(false, SessionFiles.startupMovieShuffle(file))
|
||||
}
|
||||
|
||||
@Test fun aShuffleChangedInSteamIsTakenOverAndOtherwiseTheChoiceIsKept() {
|
||||
val app = org.robolectric.RuntimeEnvironment.getApplication()
|
||||
app.getSharedPreferences("session", android.content.Context.MODE_PRIVATE).edit().clear().commit()
|
||||
val file = config(SessionFiles.BOOT_MOVIE_PATH, "0", SessionFiles.BOOT_MOVIE_PATH)
|
||||
BootMovie.syncShuffleFromSteam(app, file)
|
||||
assertFalse(SessionPrefs.bootMovieShuffle(app))
|
||||
SessionPrefs.setBootMovieShuffle(app, true)
|
||||
BootMovie.syncShuffleFromSteam(app, file)
|
||||
assertTrue(SessionPrefs.bootMovieShuffle(app))
|
||||
SessionFiles.setStartupMovieShuffle(file, true)
|
||||
BootMovie.syncShuffleFromSteam(app, file)
|
||||
SessionFiles.setStartupMovieShuffle(file, false)
|
||||
BootMovie.syncShuffleFromSteam(app, file)
|
||||
assertFalse(SessionPrefs.bootMovieShuffle(app))
|
||||
}
|
||||
|
||||
@Test fun anUnreadableConfigKeepsTheSavedShuffleChoice() {
|
||||
val app = org.robolectric.RuntimeEnvironment.getApplication()
|
||||
app.getSharedPreferences("session", android.content.Context.MODE_PRIVATE).edit().clear().commit()
|
||||
val file = config(SessionFiles.BOOT_MOVIE_PATH, "0", SessionFiles.BOOT_MOVIE_PATH)
|
||||
SessionPrefs.setBootMovieShuffle(app, true)
|
||||
SessionPrefs.setBootMovieShuffleSeen(app, file, true)
|
||||
val missing = File(folder.root, "missing.vdf")
|
||||
assertNull(SessionFiles.startupMovieShuffle(missing))
|
||||
BootMovie.syncShuffleFromSteam(app, missing)
|
||||
assertTrue(SessionPrefs.bootMovieShuffle(app))
|
||||
assertEquals(true, SessionPrefs.bootMovieShuffleSeen(app, file))
|
||||
}
|
||||
|
||||
@Test fun resetLeavesShuffleOffEvenWhenSteamStillHasItOn() {
|
||||
val app = org.robolectric.RuntimeEnvironment.getApplication()
|
||||
app.getSharedPreferences("session", android.content.Context.MODE_PRIVATE).edit().clear().commit()
|
||||
val file = config(SessionFiles.BOOT_MOVIE_PATH, "0", SessionFiles.BOOT_MOVIE_PATH)
|
||||
SessionFiles.setStartupMovieShuffle(file, true)
|
||||
SessionPrefs.setBootMovieShuffle(app, true)
|
||||
BootMovie.syncShuffleFromSteam(app, file)
|
||||
assertFalse(SettingsReset.isSessionSetting("bootMovieShuffleSeen:${file.path}"))
|
||||
app.getSharedPreferences("session", android.content.Context.MODE_PRIVATE).edit().remove("bootMovieShuffle").commit()
|
||||
BootMovie.syncShuffleFromSteam(app, file)
|
||||
assertFalse(SessionPrefs.bootMovieShuffle(app))
|
||||
}
|
||||
|
||||
@Test fun eachSteamHomeKeepsItsOwnShuffleBaseline() {
|
||||
val app = org.robolectric.RuntimeEnvironment.getApplication()
|
||||
app.getSharedPreferences("session", android.content.Context.MODE_PRIVATE).edit().clear().commit()
|
||||
val arm = config(SessionFiles.BOOT_MOVIE_PATH, "0", SessionFiles.BOOT_MOVIE_PATH)
|
||||
val x64 = config(SessionFiles.BOOT_MOVIE_PATH, "0", SessionFiles.BOOT_MOVIE_PATH)
|
||||
BootMovie.syncShuffleFromSteam(app, arm)
|
||||
BootMovie.syncShuffleFromSteam(app, x64)
|
||||
SessionFiles.setStartupMovieShuffle(arm, true)
|
||||
BootMovie.syncShuffleFromSteam(app, arm)
|
||||
assertTrue(SessionPrefs.bootMovieShuffle(app))
|
||||
BootMovie.syncShuffleFromSteam(app, x64)
|
||||
assertTrue(SessionPrefs.bootMovieShuffle(app))
|
||||
}
|
||||
|
||||
@Test fun aShuffleChangedInAnInactiveSteamHomeIsTakenOverBeforeTheActiveHome() {
|
||||
val app = org.robolectric.RuntimeEnvironment.getApplication()
|
||||
app.getSharedPreferences("session", android.content.Context.MODE_PRIVATE).edit().clear().commit()
|
||||
val inactive = config(SessionFiles.BOOT_MOVIE_PATH, "0", SessionFiles.BOOT_MOVIE_PATH)
|
||||
val active = config(SessionFiles.BOOT_MOVIE_PATH, "0", SessionFiles.BOOT_MOVIE_PATH)
|
||||
BootMovie.syncShuffleFromSteam(app, listOf(inactive, active))
|
||||
SessionFiles.setStartupMovieShuffle(inactive, true)
|
||||
BootMovie.syncShuffleFromSteam(app, listOf(inactive, active))
|
||||
assertTrue(SessionPrefs.bootMovieShuffle(app))
|
||||
}
|
||||
|
||||
@Test fun aChangeInAnInactiveHomeIsNotUndoneByAnActiveHomeReadForTheFirstTime() {
|
||||
val app = org.robolectric.RuntimeEnvironment.getApplication()
|
||||
app.getSharedPreferences("session", android.content.Context.MODE_PRIVATE).edit().clear().commit()
|
||||
val inactive = config(SessionFiles.BOOT_MOVIE_PATH, "0", SessionFiles.BOOT_MOVIE_PATH)
|
||||
val active = File(folder.root, "unreadable.vdf")
|
||||
BootMovie.syncShuffleFromSteam(app, listOf(inactive, active))
|
||||
SessionFiles.setStartupMovieShuffle(inactive, true)
|
||||
active.writeText(inactive.readText())
|
||||
SessionFiles.setStartupMovieShuffle(active, false)
|
||||
BootMovie.syncShuffleFromSteam(app, listOf(inactive, active))
|
||||
assertTrue(SessionPrefs.bootMovieShuffle(app))
|
||||
assertEquals(false, SessionPrefs.bootMovieShuffleSeen(app, active))
|
||||
}
|
||||
|
||||
@Test fun aShuffleLineWithATrailingCommentIsReplacedNotDuplicated() {
|
||||
val file = config(SessionFiles.BOOT_MOVIE_PATH, "0", SessionFiles.BOOT_MOVIE_PATH)
|
||||
file.writeText(file.readText().replace("\t\t\t\"LocalPath\"", "\t\t\t\"Shuffle\"\t\t\"1\" // set in Steam\n\t\t\t\"LocalPath\""))
|
||||
assertEquals(true, SessionFiles.startupMovieShuffle(file))
|
||||
assertTrue(SessionFiles.setStartupMovieShuffle(file, false))
|
||||
assertEquals(false, SessionFiles.startupMovieShuffle(file))
|
||||
assertEquals(1, Regex("\"Shuffle\"").findAll(file.readText().substringAfter("Customization")).count())
|
||||
assertTrue(file.readText().contains("\"0\" // set in Steam"))
|
||||
}
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
package com.droiddeck.launcher.stores.gog
|
||||
|
||||
import com.droiddeck.launcher.frontend.AddedGames
|
||||
import com.droiddeck.launcher.session.SecondaryLibrary
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||
import java.io.File
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertNull
|
||||
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.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [33])
|
||||
class GogInnoextractTest {
|
||||
private val app get() = RuntimeEnvironment.getApplication()
|
||||
|
||||
@Before @After fun resetStorage() {
|
||||
SessionPrefs.setDefaultStorageFolder(app, "", "")
|
||||
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
|
||||
}
|
||||
|
||||
private fun installer(folder: File, names: List<String>) = names.map { File(folder, it).apply { parentFile?.mkdirs(); writeText("MZ") } }
|
||||
|
||||
private fun hostOf(guest: String, binds: List<String>): File? = binds
|
||||
.map { it.substringBeforeLast(':') to it.substringAfterLast(':') }
|
||||
.filter { (_, mount) -> guest == mount || guest.startsWith("$mount/") }
|
||||
.maxByOrNull { it.second.length }
|
||||
?.let { (host, mount) -> File(host + guest.removePrefix(mount)) }
|
||||
|
||||
private fun assertExtractorSeesEveryPart(folder: File, parts: List<String>) {
|
||||
val files = installer(folder, parts)
|
||||
val guestDir = AddedGames.guestPath(app, folder)
|
||||
assertNotNull(guestDir)
|
||||
val argv = GogInnoextract.argv("$guestDir/${parts.first()}", guestDir!!)
|
||||
assertEquals("$guestDir/${parts.first()}", argv.last())
|
||||
assertEquals(guestDir, argv[argv.indexOf("-d") + 1])
|
||||
assertTrue(argv.contains("--gog"))
|
||||
val binds = StoreInstallRoot.guestBinds(app)
|
||||
assertEquals(folder.canonicalFile, hostOf(guestDir, binds)?.canonicalFile)
|
||||
for (file in files) assertEquals(file.canonicalFile, hostOf("$guestDir/${file.name}", binds)?.canonicalFile)
|
||||
assertNull(hostOf("$guestDir/${parts.first()}", emptyList()))
|
||||
}
|
||||
|
||||
@Test fun singleFileAndMultiPartInstallersOnAChosenFolderAreVisibleToTheExtractor() {
|
||||
val drive = File(app.filesDir, "usb/SSD").apply { mkdirs() }
|
||||
SessionPrefs.setDefaultStorageFolder(app, drive.path, "SSD")
|
||||
val single = File(drive, "Games/GOG/Single")
|
||||
assertTrue(AddedGames.guestPath(app, single)!!.startsWith(StoreInstallRoot.GUEST_EXTERNAL + "/"))
|
||||
assertExtractorSeesEveryPart(single, listOf("setup_1207658930.exe"))
|
||||
assertExtractorSeesEveryPart(File(drive, "Games/GOG/Multi Part"), listOf("setup_1207658931.exe", "setup_1207658931-1.bin", "setup_1207658931-2.bin"))
|
||||
}
|
||||
|
||||
@Test fun installersOnTheGameStorageCardAreVisibleToTheExtractor() {
|
||||
val card = File(app.filesDir, "card/steam").apply { mkdirs() }
|
||||
SessionPrefs.setGameStorage(app, card.path, "Card")
|
||||
val folder = File(card, "Games/GOG/Multi Part")
|
||||
assertTrue(SecondaryLibrary.CARD_GUESTS.any { AddedGames.guestPath(app, folder)!!.startsWith("$it/") })
|
||||
assertExtractorSeesEveryPart(folder, listOf("setup_1207658932.exe", "setup_1207658932-1.bin"))
|
||||
}
|
||||
|
||||
@Test fun anUnpluggedGameStorageCardDoesNotStopAnInternalExtraction() {
|
||||
SessionPrefs.setGameStorage(app, File(app.filesDir, "unplugged/steam").path, "Card")
|
||||
val folder = File(StoreInstallRoot.internalRoot(app), "GOG/Internal")
|
||||
installer(folder, listOf("setup_1207658933.exe"))
|
||||
val binds = StoreInstallRoot.guestBinds(app)
|
||||
assertTrue(binds.none { bind -> SecondaryLibrary.CARD_GUESTS.any { bind.endsWith(":$it") } })
|
||||
assertTrue(AddedGames.guestPath(app, folder)!!.startsWith("/root/Games/Stores/GOG/"))
|
||||
}
|
||||
|
||||
@Test fun anAddedFolderNamedStoresIsMountedWithoutHidingTheInternalInstallRoot() {
|
||||
val drive = File(app.filesDir, "usb/Stores").apply { mkdirs() }
|
||||
AddedGames.bindFolder(app, drive)
|
||||
val guest = AddedGames.guestPath(app, drive)!!
|
||||
assertTrue(guest != StoreInstallRoot.INTERNAL_GUEST && !guest.startsWith(StoreInstallRoot.INTERNAL_GUEST + "/"))
|
||||
SessionPrefs.setDefaultStorageFolder(app, drive.path, "Stores")
|
||||
val chosen = File(drive, "Games/GOG/Chosen")
|
||||
assertTrue(AddedGames.guestPath(app, chosen)!!.startsWith("$guest/"))
|
||||
assertExtractorSeesEveryPart(chosen, listOf("setup_1207658934.exe", "setup_1207658934-1.bin"))
|
||||
val internal = File(StoreInstallRoot.internalRoot(app), "GOG/Internal")
|
||||
installer(internal, listOf("setup_1207658935.exe"))
|
||||
val internalGuest = AddedGames.guestPath(app, internal)!!
|
||||
assertTrue(internalGuest.startsWith(StoreInstallRoot.INTERNAL_GUEST + "/GOG/"))
|
||||
assertNull(hostOf("$internalGuest/setup_1207658935.exe", StoreInstallRoot.guestBinds(app)))
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,10 @@
|
||||
package com.droiddeck.launcher.stores.gog
|
||||
|
||||
import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.nio.file.Files
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
@@ -85,97 +83,6 @@ class GogInstallerPartsTest {
|
||||
}
|
||||
}
|
||||
|
||||
private val gib = 1024L * 1024 * 1024
|
||||
|
||||
@Test fun anInstallerThatFitsOnlyBeforeExtractionIsRefusedBeforeItDownloads() {
|
||||
val download = 1_048_576L + 17 * (7 * gib / 2)
|
||||
val installed = 699 * gib / 10
|
||||
val free = 944 * gib / 10
|
||||
assertFalse(StoreInstallRoot.insufficientSpace(download, free))
|
||||
val needed = GogDownloadManager.installerBytesNeeded(download, installed)
|
||||
assertEquals(download + installed, needed)
|
||||
assertTrue(StoreInstallRoot.insufficientSpace(needed, free))
|
||||
}
|
||||
|
||||
@Test fun anInstallerThatFitsWithItsExtractedFilesIsAllowed() {
|
||||
val download = 1_048_576L + 3_786_407_936L
|
||||
assertFalse(StoreInstallRoot.insufficientSpace(GogDownloadManager.installerBytesNeeded(download, 6 * gib), 944 * gib / 10))
|
||||
}
|
||||
|
||||
@Test fun anUnknownInstalledSizeKeepsTheDownloadOnlyCheck() {
|
||||
val download = 1_048_576L + 3_786_407_936L
|
||||
assertEquals(download, GogDownloadManager.installerBytesNeeded(download, 0L))
|
||||
assertEquals(download, GogDownloadManager.installerBytesNeeded(download, -1L))
|
||||
assertEquals(5 * gib, GogDownloadManager.installerBytesNeeded(0L, 5 * gib))
|
||||
assertEquals(0L, GogDownloadManager.installerBytesNeeded(0L, -1L))
|
||||
}
|
||||
|
||||
@Test fun aPartWithoutASizeStillCountsTheKnownBytesOfTheOthers() {
|
||||
val parts = listOf(
|
||||
GogDownloadManager.InstallerPart("u0", "setup.exe", 0L),
|
||||
GogDownloadManager.InstallerPart("u1", "setup-1.bin", 60 * gib),
|
||||
)
|
||||
val needed = GogDownloadManager.installerBytesNeeded(GogDownloadManager.knownPartBytes(parts), 70 * gib)
|
||||
assertEquals(130 * gib, needed)
|
||||
assertTrue(StoreInstallRoot.insufficientSpace(needed, 95 * gib))
|
||||
assertEquals(0L, GogDownloadManager.knownPartBytes(emptyList()))
|
||||
}
|
||||
|
||||
private fun installDir(): File = Files.createTempDirectory("gog-parts").toFile()
|
||||
|
||||
@Test fun partsKeptFromACancelledInstallCountAsFreeSpaceOnRetry() {
|
||||
val dir = installDir()
|
||||
try {
|
||||
File(dir, "setup.exe").writeBytes(ByteArray(1000))
|
||||
File(dir, "setup-1.bin").writeBytes(ByteArray(500))
|
||||
val parts = listOf(
|
||||
GogDownloadManager.InstallerPart("u0", "setup.exe", 1000L),
|
||||
GogDownloadManager.InstallerPart("u1", "setup-1.bin", 1000L),
|
||||
)
|
||||
val reclaimed = GogDownloadManager.reclaimableInstallerBytes(dir, parts)
|
||||
assertEquals(1500L, reclaimed)
|
||||
val needed = GogDownloadManager.installerBytesNeeded(GogDownloadManager.knownPartBytes(parts), 0L)
|
||||
val free = 600L
|
||||
assertTrue(StoreInstallRoot.insufficientSpace(needed, free))
|
||||
assertFalse(StoreInstallRoot.insufficientSpace(needed, free + reclaimed))
|
||||
} finally {
|
||||
dir.deleteRecursively()
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun aMissingPartOrADirectoryReclaimsNothing() {
|
||||
val dir = installDir()
|
||||
try {
|
||||
File(dir, "folder.bin").mkdir()
|
||||
val parts = listOf(
|
||||
GogDownloadManager.InstallerPart("u0", "setup.exe", 1000L),
|
||||
GogDownloadManager.InstallerPart("u1", "folder.bin", 1000L),
|
||||
)
|
||||
assertEquals(0L, GogDownloadManager.reclaimableInstallerBytes(dir, parts))
|
||||
assertEquals(0L, GogDownloadManager.reclaimableInstallerBytes(dir, emptyList()))
|
||||
} finally {
|
||||
dir.deleteRecursively()
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun aLinkedPartOrAnEscapingNameReclaimsNothing() {
|
||||
val dir = installDir()
|
||||
val outside = installDir()
|
||||
try {
|
||||
val target = File(outside, "big.bin").apply { writeBytes(ByteArray(4000)) }
|
||||
Files.createSymbolicLink(File(dir, "setup.exe").toPath(), target.toPath())
|
||||
File(dir.parentFile, "escape.bin").also { it.writeBytes(ByteArray(4000)); it.deleteOnExit() }
|
||||
val parts = listOf(
|
||||
GogDownloadManager.InstallerPart("u0", "setup.exe", 1000L),
|
||||
GogDownloadManager.InstallerPart("u1", "../escape.bin", 1000L),
|
||||
)
|
||||
assertEquals(0L, GogDownloadManager.reclaimableInstallerBytes(dir, parts))
|
||||
} finally {
|
||||
dir.deleteRecursively()
|
||||
outside.deleteRecursively()
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun anotherPlatformOrNoDownloadsAddsNothing() {
|
||||
assertEquals(0, GogDownloadManager.installerParts(downloads("""{"installers":[{"os":"linux","manualUrl":"https://example.invalid/x"}]}"""), "1").size)
|
||||
assertEquals(0, GogDownloadManager.installerParts(downloads("{}"), "1").size)
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.Canvas
|
||||
import android.view.View
|
||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.ui.platform.LocalView
|
||||
import androidx.compose.ui.test.*
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.input.*
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Before
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.annotation.GraphicsMode
|
||||
import java.io.File
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28], qualifiers = "w1000dp-h900dp")
|
||||
@GraphicsMode(GraphicsMode.Mode.NATIVE)
|
||||
class InputCommunityPageTest {
|
||||
@get:Rule val compose = createRobolectricComposeRule()
|
||||
private val context get() = RuntimeEnvironment.getApplication()
|
||||
private lateinit var root: View
|
||||
@Before fun reset() {
|
||||
for (name in listOf("input-profiles", "input-surfaces", "controller", "input-game-controls"))
|
||||
context.getSharedPreferences(name, Context.MODE_PRIVATE).edit().clear().commit()
|
||||
}
|
||||
private fun open() {
|
||||
compose.setContent { root = LocalView.current; DroidDeckTheme { Surface { BoxWithConstraints {
|
||||
CompositionLocalProvider(LocalNarrowPane provides (maxWidth < 600.dp)) { InputSettingsPage({}) }
|
||||
} } } }
|
||||
compose.onNodeWithTag("input-community").performScrollTo().performClick()
|
||||
}
|
||||
@Test fun communityRequiresReviewBeforeApplyingAndPreservesOtherProfiles() {
|
||||
val before = InputLibraries.read(context)
|
||||
open()
|
||||
compose.onNodeWithText("Compact gamepad").performScrollTo().performClick()
|
||||
compose.waitUntil(10_000) { compose.onAllNodesWithText(context.getString(R.string.community_apply)).fetchSemanticsNodes().isNotEmpty() }
|
||||
assertEquals(before, InputLibraries.read(context))
|
||||
screenshot("community-review", org.robolectric.shadows.ShadowDialog.getLatestDialog().window!!.decorView)
|
||||
compose.onNodeWithText(context.getString(R.string.community_apply)).performClick()
|
||||
compose.waitUntil(10_000) { InputLibraries.read(context).layout(InputProfile.GAME, InputRole.PRIMARY)?.name == "Compact gamepad" }
|
||||
val after = InputLibraries.read(context)
|
||||
assertEquals(before.profile(InputProfile.DESKTOP), after.profile(InputProfile.DESKTOP))
|
||||
compose.onNodeWithText(context.getString(R.string.community_export)).performScrollTo().assertIsDisplayed()
|
||||
}
|
||||
@Test @Config(qualifiers = "w360dp-h800dp")
|
||||
fun phoneCanBrowseSearchAndReachImportAndSubmission() {
|
||||
open()
|
||||
compose.waitUntil(10_000) { compose.onAllNodesWithTag("community-preview-packs/compact-gamepad.ddcontrols.zip", useUnmergedTree = true).fetchSemanticsNodes().isNotEmpty() }
|
||||
screenshot("community-phone")
|
||||
compose.onNodeWithText(context.getString(R.string.community_search)).performTextInput("absent-game")
|
||||
compose.onNodeWithText(context.getString(R.string.community_empty)).performScrollTo().assertIsDisplayed()
|
||||
compose.onNodeWithTag("community-import").performScrollTo().assertIsDisplayed()
|
||||
compose.onNodeWithText(context.getString(R.string.community_submit)).performScrollTo().assertIsDisplayed()
|
||||
}
|
||||
@Test fun largeCatalogIsPagedAndSearchResetsToMatchingResults() {
|
||||
val library = InputLibraries.read(context)
|
||||
val starter = CommunityControls.bundled(context).first()
|
||||
val entries = (1..25).map { starter.copy(name = "Pack $it", path = "packs/pack-$it.ddcontrols.zip", preview = null) }
|
||||
compose.setContent { DroidDeckTheme { Column(Modifier.verticalScroll(rememberScrollState())) {
|
||||
InputCommunityPage(library, InputProfile.GAME, InputRole.PRIMARY, initialEntries = entries, onInstalled = {})
|
||||
} } }
|
||||
compose.onNodeWithText("Pack 1").assertExists()
|
||||
compose.onNodeWithText("Pack 13").assertDoesNotExist()
|
||||
compose.onNodeWithTag("community-next").performScrollTo().performClick()
|
||||
compose.onNodeWithText("Pack 13").performScrollTo().assertIsDisplayed()
|
||||
compose.onNodeWithText("Pack 1").assertDoesNotExist()
|
||||
compose.onNodeWithText(context.getString(R.string.community_search)).performScrollTo().performTextInput("Pack 25")
|
||||
compose.onNodeWithTag("community-pack-packs/pack-25.ddcontrols.zip").performScrollTo().assertIsDisplayed()
|
||||
compose.onNodeWithTag("community-next").assertDoesNotExist()
|
||||
compose.onNodeWithTag("community-import").performScrollTo().assertIsDisplayed()
|
||||
}
|
||||
|
||||
@Test fun starterPreviewUsesTheSameRendererAsInstalledControls() {
|
||||
val bytes = context.assets.open("community-controls/packs/compact-gamepad.ddcontrols.zip").use { it.readBytes() }
|
||||
val pack = CommunityControls.parse(context, bytes)
|
||||
val view = InputLayoutPreviewView(context)
|
||||
view.update(pack.layout, InputRole.PRIMARY)
|
||||
view.measure(View.MeasureSpec.makeMeasureSpec(640, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(360, View.MeasureSpec.EXACTLY))
|
||||
view.layout(0, 0, 640, 360)
|
||||
screenshot("compact-gamepad", view)
|
||||
}
|
||||
private fun screenshot(name: String, view: View = root) {
|
||||
compose.runOnIdle {
|
||||
val image = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888)
|
||||
view.draw(Canvas(image))
|
||||
val file = File("build/reports/community-controls/$name.png").apply { parentFile?.mkdirs() }
|
||||
file.outputStream().use { image.compress(Bitmap.CompressFormat.PNG, 100, it) }
|
||||
image.recycle()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
# Community controls
|
||||
|
||||
Controller settings → Community controls browses source catalogs and imports or exports `.ddcontrols.zip` packs and controller-skin ZIPs. A DroidDeck starter gamepad is bundled for offline use. The ARMSX2 community catalog is a remote source: none of its artwork is shipped in this repository or the APK. Selecting it fetches its manifest and previews; selecting a skin downloads it directly from that source for local installation.
|
||||
|
||||
## Sources and sharing
|
||||
|
||||
The Source selector includes DroidDeck and [bagasromadon/ARMSX2-CustomControllerSkins](https://github.com/bagasromadon/ARMSX2-CustomControllerSkins). **Connect another source** accepts a public GitHub repository URL, a GitHub manifest file link, or a direct HTTPS catalog URL. Repository URLs try `main/catalog.json`, then `main/manifest.json`; use a file URL for another branch or a catalog in a subdirectory. Connected sources persist locally and can be removed. Results are filtered before pagination, with at most 12 entries and their previews loaded per page. Previews are sampled to at most 256 pixels. Page/filter/source changes discard the old cache; Android reclaims displayed bitmaps after rendering references are released. Native manifests use `controls`; ARMSX2 manifests use `skins`. Relative paths stay within the manifest directory, with spaces encoded when downloading. No account credentials are stored in DroidDeck.
|
||||
|
||||
**Export this layout and actions** creates a portable DroidDeck pack. **Export skin artwork** creates an ARMSX2-compatible PNG-only ZIP when the selected layout has suitable artwork. Share either ZIP directly, or use **Open source submissions** to visit the selected source's issue page and attach it there. GitHub requires an account. Source owners manage submissions and publication; the app does not automatically publish uploads. For other HTTPS hosts, the button opens the catalog URL; use that host's own upload process. A native controls pack includes layouts and bindings, while an artwork ZIP includes only controller images.
|
||||
|
||||
The DroidDeck issue template accepts exported packs and screenshots for review. Maintainers add approved packs to `packs/` and entries to `catalog.json`, with name, author, optional game, license, relative file path, SHA-256, optional preview path, and screen (`MAIN`, `SECONDARY`, or `BOTH`). Keep the bundled starter copies under `app/src/main/assets/community-controls` in sync. Remote entries are namespaced by source. Native pack downloads require the manifest's SHA-256; ARMSX2 manifests may omit it, so their files are obtained over HTTPS and validated as bounded PNG archives. Do not infer artwork redistribution rights from the application's code license.
|
||||
|
||||
## Applying controls
|
||||
|
||||
Native controls packs create an independent copy for the chosen profile and screen. ARMSX2/iOS skin archives match image names to the selected layout's native controller actions (cross → A, circle → B, square → X, triangle → Y, shoulders, triggers, system and directional buttons). Positions, actions, and stick-click bindings are preserved. Generic and separate left/right analog base/thumb images are supported. Unsupported images are ignored, missing artwork keeps the existing appearance, and a skin with no matching controls is rejected. Source images are sampled to at most 512 pixels before storage. Skin ZIPs can also be imported locally.
|
||||
|
||||
For game-specific controls, create a named input profile and apply the pack or skin to it. Select that profile in the game's settings under **On-screen controls profile**. Automatic selection follows the focused Steam game, or the launched game for direct launches. Returning to Steam restores general controls. Explicit quick-menu profile or screen choices take priority until Auto is restored. Physical controller bindings follow the general selection. Missing/deleted profiles fall back to general controls. Use Profile controls mode for the second display.
|
||||
|
||||
## Native pack format
|
||||
|
||||
A ZIP contains `controls.json` and the exact `images/<filename>` PNGs referenced by the layout. The JSON has `format: "droiddeck-controls"`, `version: 1`, and `layout` / `bindings` objects using the input library serialization. All supported actions, stick clicks, geometry, style, and artwork (including separate moving-stick images) are retained. Local IDs and image names are regenerated on import. Import validates the library, image dimensions, file count, byte limits, and entry paths before offering Apply; saving uses the library recovery path. Legacy `.icp` import/export remains in Saved layouts.
|
||||
|
||||
## Upstream inspiration
|
||||
|
||||
The source catalog flow and controller-skin filename conventions were researched directly from [ARMSX2](https://github.com/ARMSX2/ARMSX2) commit `9144e4ff1fed43756809d8e68b3efc2505a51078`, particularly `SkinRepo.kt`, `ControllerSkinStore.kt`, and `ui/settings/SkinsTab.kt`. ARMSX2's `COPYING.GPLv3` and `pcsx2/Docs/License.txt` license its program under GPLv3 or later, compatible with DroidDeck's GPLv3. This implementation uses DroidDeck's input model and renderer. No upstream source or artwork files are copied into the source tree. The bundled starter is original DroidDeck data under GPL-3.0.
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"version": 1,
|
||||
"controls": [
|
||||
{
|
||||
"name": "Compact gamepad",
|
||||
"author": "DroidDeck",
|
||||
"game": "",
|
||||
"license": "GPL-3.0",
|
||||
"file": "packs/compact-gamepad.ddcontrols.zip",
|
||||
"sha256": "8b747e86268a1f607e312f2c39dd67402658bd5cf9e4e4ff524a4640417c9f3e",
|
||||
"screen": "BOTH",
|
||||
"preview": "previews/compact-gamepad.png"
|
||||
}
|
||||
]
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
|
After Width: | Height: | Size: 21 KiB |
@@ -4,7 +4,9 @@ Settings → Boot movie has four tabs.
|
||||
|
||||
- **Installed**: "Browse" lists every movie Steam can play: DroidDeck's two, plus every `.webm` in Steam's
|
||||
`config/uioverrides/movies` folder (imported, installed from SteamDeckRepo, or put there by Steam). The list is re-read
|
||||
every two seconds, so a movie picked or removed inside Steam shows up, and a movie picked inside Steam becomes the choice.
|
||||
every two seconds, so a movie picked or removed inside Steam shows up, and a movie picked inside Steam becomes the choice. The Shuffle switch is Steam's own `Shuffle` setting (`startup_movie_shuffle` in
|
||||
Steam's client settings, `Shuffle` next to `MovieID` and `LocalPath`): it is written at the next session start, a change made in Steam is
|
||||
taken over, and with it off the selected movie plays as before.
|
||||
- **Import**: the same importer as before (copy, remux or on-device transcode to VP8/Opus). The result is written into
|
||||
Steam's movies folder, so Steam lists it as well.
|
||||
- **SteamDeckRepo**: browses `https://steamdeckrepo.com/api/posts` (`sort`, `device`, `search`, `page`; 12 posts a page).
|
||||
|
||||
Reference in new issue
Block a user