mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-06 13:05:47 +00:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3f4405931a | ||
|
|
a1078cb12f |
No files matched your search
+24
-13
@@ -44,19 +44,6 @@ jobs:
|
|||||||
ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
|
ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
|
|
||||||
- name: Check co-authors
|
|
||||||
if: github.event_name == 'pull_request'
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
git fetch --no-tags origin main
|
|
||||||
base=$(git merge-base origin/main HEAD)
|
|
||||||
messages=$(git log --format=%B "$base..HEAD")
|
|
||||||
messages+=$'\n'"$(jq -r '.pull_request.title, (.pull_request.body // "")' "$GITHUB_EVENT_PATH")"
|
|
||||||
if grep -Eiq '^[[:space:]]*Co-authored-by:.*(Claude|Anthropic|OpenAI|ChatGPT|GPT|Copilot|Cursor|Gemini|Codex|Devin|Windsurf|Codeium|Amazon Q|Tabnine|Cody|\[bot\])' <<<"$messages"; then
|
|
||||||
echo "::error::AI and bot identities cannot be co-authors; remove the Co-authored-by trailer."
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
- name: The packages a signed build ships as
|
- name: The packages a signed build ships as
|
||||||
id: variants
|
id: variants
|
||||||
run: echo "list=$(awk '!/^#/ && NF { print $1 }' tools/release/variants.txt | jq -R . | jq -sc .)" >> "$GITHUB_OUTPUT"
|
run: echo "list=$(awk '!/^#/ && NF { print $1 }' tools/release/variants.txt | jq -R . | jq -sc .)" >> "$GITHUB_OUTPUT"
|
||||||
@@ -501,6 +488,30 @@ jobs:
|
|||||||
- name: Unit tests
|
- name: Unit tests
|
||||||
run: ./gradlew testReleaseUnitTest --console=plain -PndkVersion="$NDK_VERSION"
|
run: ./gradlew testReleaseUnitTest --console=plain -PndkVersion="$NDK_VERSION"
|
||||||
|
|
||||||
|
- name: Render Compose previews
|
||||||
|
run: ./gradlew testDebugUnitTest --tests '*PreviewRenderTest' --console=plain -PndkVersion="$NDK_VERSION"
|
||||||
|
|
||||||
|
- name: Check the native dependency closure
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
APK=$(find app/build/outputs/apk -name '*.apk' | head -1)
|
||||||
|
WORK=$(mktemp -d)
|
||||||
|
unzip -q "$APK" 'lib/arm64-v8a/*' -d "$WORK"
|
||||||
|
cd "$WORK/lib/arm64-v8a"
|
||||||
|
SYSTEM="libc.so libm.so libdl.so liblog.so libandroid.so libz.so libvulkan.so libstdc++.so
|
||||||
|
libGLESv2.so libEGL.so libnativewindow.so libjnigraphics.so libaaudio.so
|
||||||
|
libOpenSLES.so libmediandk.so libcamera2ndk.so libsync.so libneuralnetworks.so"
|
||||||
|
fail=0
|
||||||
|
for so in *.so; do
|
||||||
|
for need in $(readelf -d "$so" | sed -n 's/.*NEEDED.*\[\(.*\)\]/\1/p'); do
|
||||||
|
[ -f "$need" ] && continue
|
||||||
|
case " $(echo $SYSTEM) " in *" $need "*) continue ;; esac
|
||||||
|
echo "::error::$so needs $need, which is neither in the apk nor a platform library"
|
||||||
|
fail=1
|
||||||
|
done
|
||||||
|
done
|
||||||
|
exit $fail
|
||||||
|
|
||||||
- name: Sign with the testkey (v1 + v2 + v3)
|
- name: Sign with the testkey (v1 + v2 + v3)
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|||||||
+6
-5
@@ -92,8 +92,8 @@ android {
|
|||||||
// file out of its own data directory, and this app's entire job is to exec a rootfs:
|
// file out of its own data directory, and this app's entire job is to exec a rootfs:
|
||||||
// proot, gamescope, the Steam client and everything it launches all live under files/.
|
// proot, gamescope, the Steam client and everything it launches all live under files/.
|
||||||
targetSdkVersion 28
|
targetSdkVersion 28
|
||||||
versionCode 13
|
versionCode 12
|
||||||
versionName "0.4.0"
|
versionName "0.3.2"
|
||||||
buildConfigField "String", "BUILD_LABEL", "\"${escapedBuildLabel}\""
|
buildConfigField "String", "BUILD_LABEL", "\"${escapedBuildLabel}\""
|
||||||
buildConfigField "String", "SOURCE_COMMIT", "\"${sourceCommit}\""
|
buildConfigField "String", "SOURCE_COMMIT", "\"${sourceCommit}\""
|
||||||
buildConfigField "int", "PR_NUMBER", "${prNumber}"
|
buildConfigField "int", "PR_NUMBER", "${prNumber}"
|
||||||
@@ -286,6 +286,10 @@ dependencies {
|
|||||||
// on-screen pad are Views underneath it, which is what they are in every Compose app.
|
// on-screen pad are Views underneath it, which is what they are in every Compose app.
|
||||||
implementation platform('androidx.compose:compose-bom:2024.02.00')
|
implementation platform('androidx.compose:compose-bom:2024.02.00')
|
||||||
implementation 'androidx.compose.ui:ui'
|
implementation 'androidx.compose.ui:ui'
|
||||||
|
debugImplementation 'androidx.compose.ui:ui-tooling-preview'
|
||||||
|
debugImplementation 'androidx.compose.ui:ui-tooling'
|
||||||
|
debugImplementation 'androidx.compose.ui:ui-test-manifest'
|
||||||
|
testImplementation 'androidx.compose.ui:ui-test-junit4'
|
||||||
implementation 'androidx.compose.material3:material3'
|
implementation 'androidx.compose.material3:material3'
|
||||||
implementation 'androidx.activity:activity-compose:1.8.2'
|
implementation 'androidx.activity:activity-compose:1.8.2'
|
||||||
// The File Manager, Bannerlator's: its icon set, image thumbnails and the coroutines it
|
// The File Manager, Bannerlator's: its icon set, image thumbnails and the coroutines it
|
||||||
@@ -302,7 +306,4 @@ dependencies {
|
|||||||
|
|
||||||
testImplementation 'junit:junit:4.13.2'
|
testImplementation 'junit:junit:4.13.2'
|
||||||
testImplementation 'org.robolectric:robolectric:4.16.1'
|
testImplementation 'org.robolectric:robolectric:4.16.1'
|
||||||
testImplementation 'androidx.compose.ui:ui-test-junit4'
|
|
||||||
// The Android archive does not include the host natives used by JVM archive tests.
|
|
||||||
testRuntimeOnly 'com.github.luben:zstd-jni:1.5.2-3@jar'
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
package com.droiddeck.launcher.files
|
||||||
|
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import com.droiddeck.launcher.ui.DroidDeckPreviews
|
||||||
|
import com.droiddeck.launcher.ui.PreviewCase
|
||||||
|
import com.droiddeck.launcher.ui.PreviewHost
|
||||||
|
import java.io.File
|
||||||
|
|
||||||
|
/** File metadata only: no files are created and no real directory is enumerated. */
|
||||||
|
private class SampleFile(path: String, private val directory: Boolean = false, private val bytes: Long = 0) : File(path) {
|
||||||
|
override fun isDirectory() = directory
|
||||||
|
override fun isFile() = !directory
|
||||||
|
override fun exists() = true
|
||||||
|
override fun canRead() = true
|
||||||
|
override fun canWrite() = false
|
||||||
|
override fun length() = bytes
|
||||||
|
override fun getUsableSpace() = 32_000_000_000L
|
||||||
|
override fun getFreeSpace() = 32_000_000_000L
|
||||||
|
override fun lastModified() = 1_791_331_200_000L
|
||||||
|
override fun getCanonicalPath() = absolutePath
|
||||||
|
override fun getCanonicalFile() = this
|
||||||
|
override fun listFiles(): Array<File> = emptyArray()
|
||||||
|
}
|
||||||
|
|
||||||
|
private val directory = SampleFile("/storage/emulated/0", directory = true)
|
||||||
|
private val entries = listOf(
|
||||||
|
SampleFile("/storage/emulated/0/Games", directory = true),
|
||||||
|
SampleFile("/storage/emulated/0/ROMs", directory = true),
|
||||||
|
SampleFile("/storage/emulated/0/Downloads", directory = true),
|
||||||
|
SampleFile("/storage/emulated/0/Portal 2.exe", bytes = 4_200_000),
|
||||||
|
SampleFile("/storage/emulated/0/session.log", bytes = 32_000),
|
||||||
|
SampleFile("/storage/emulated/0/save.zip", bytes = 12_000_000),
|
||||||
|
)
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun FileGridPreview() = PreviewHost {
|
||||||
|
FileManagerScreen(preview = FileManagerPreviewState(directory, entries))
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun FileListPreview() = PreviewHost {
|
||||||
|
FileManagerScreen(preview = FileManagerPreviewState(directory, entries, grid = false))
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun FileEmptyPreview() = PreviewHost {
|
||||||
|
FileManagerScreen(preview = FileManagerPreviewState(directory, emptyList()))
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun FilePickerPreview() = PreviewHost {
|
||||||
|
FileManagerScreen(pickMode = true, pickExtensions = listOf("exe"), pickerTitle = "Choose executable", onPick = {},
|
||||||
|
preview = FileManagerPreviewState(directory, entries.filter { it.isDirectory || it.extension == "exe" }))
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun FolderPickerPreview() = PreviewHost {
|
||||||
|
FileManagerScreen(pickMode = true, pickDirMode = true, onPick = {},
|
||||||
|
preview = FileManagerPreviewState(directory, entries.filter { it.isDirectory }))
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun FilePropertiesPreview() = PreviewHost {
|
||||||
|
FilePropertiesDialog(entries.last(), {}, {})
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun FavoritesPreview() = PreviewHost {
|
||||||
|
FileManagerScreen(preview = FileManagerPreviewState(directory, entries, favorites = true))
|
||||||
|
}
|
||||||
|
|
||||||
|
internal val filePreviewCases = listOf(
|
||||||
|
PreviewCase("Favorites") { FavoritesPreview() },
|
||||||
|
PreviewCase("FileGrid") { FileGridPreview() },
|
||||||
|
PreviewCase("FileList") { FileListPreview() },
|
||||||
|
PreviewCase("FileEmpty") { FileEmptyPreview() },
|
||||||
|
PreviewCase("FilePicker") { FilePickerPreview() },
|
||||||
|
PreviewCase("FolderPicker") { FolderPickerPreview() },
|
||||||
|
PreviewCase("FileProperties") { FilePropertiesPreview() },
|
||||||
|
)
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
package com.droiddeck.launcher.ui
|
||||||
|
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import com.droiddeck.launcher.core.PhantomProcessStatus
|
||||||
|
import com.droiddeck.launcher.runtime.UserApps
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun WirelessAdbPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
WirelessAdbFixPage({}, true, {}, { _, _, _, done -> done("Preview only") }, { _, done -> done(null) }, { _, _, _, done -> done("Preview only") })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun ProcessLimitPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
PhantomProcessGatePage(PhantomProcessStatus.ENABLED, {}, {}, {}, {}, {}, {})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun AddAppPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
AddAppDialog(true, {}) { _, _ -> }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun EditAppPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
EditAppDialog(UserApps.App("sample", UserApps.Kind.APPIMAGE, "Example app", null, "AppImage", "/preview/example.AppImage", emptyList()), {}) { _, _, _ -> }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun ConfirmationPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
ConfirmDialog("Remove runtime?", "Remove the installed Linux runtime.", "Remove", {}, {})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun CustomResolutionPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
CustomResolutionDialog(1280 to 720, {}, {})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun RomsFolderPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
RomsDialog("/preview/ROMs", {}, {}, {})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun GameEnvironmentPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
GameEnvironmentEditor(false, com.droiddeck.launcher.core.GameEnvironment.Config(shared = mapOf("DXVK_HUD" to "fps", "MANGOHUD" to "1"))) {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun WindowsComponentsPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
WinComponentsDialog("100", "Portal 2", null, false, onClose = {}, previewComponents = listOf(
|
||||||
|
com.droiddeck.launcher.session.WinComponents.Component("vcrun2022", "Visual C++ runtime", "Microsoft", "ready", emptyList(), emptyList()),
|
||||||
|
com.droiddeck.launcher.session.WinComponents.Component("d3dcompiler_47", "DirectX shader compiler", "Microsoft", "ready", emptyList(), emptyList()),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun DeveloperDisplayPreview() = PreviewHost {
|
||||||
|
DeveloperDisplayChoiceDialog(listOf(2 to "Secondary screen"), {}, {}, {})
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun AppDisplayPreview() = PreviewHost {
|
||||||
|
ChooseAppDisplayDialog(com.droiddeck.launcher.HomeApp.LaunchableApp("Files", "preview.files", "preview.files.Main", null),
|
||||||
|
com.droiddeck.launcher.input.SecondScreenDisplay(2, "Secondary screen"), {}, {}, {})
|
||||||
|
}
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
package com.droiddeck.launcher.ui
|
||||||
|
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.tooling.preview.Preview
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun LauncherPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
FrontEndScreen(PreviewData.front(), PreviewData.frontActions)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun RuntimeMissingPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
FrontEndScreen(PreviewData.front(ready = false), PreviewData.frontActions)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun RuntimeDownloadingPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
FrontEndScreen(PreviewData.front(ready = false, busy = true), PreviewData.frontActions)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun LibraryPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
FrontEndScreen(PreviewData.front(), PreviewData.frontActions, initialSelection = "games")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun EmptyLibraryPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
FrontEndScreen(PreviewData.front(empty = true), PreviewData.frontActions, initialSelection = "games")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun GameDetailsPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
FrontEndScreen(PreviewData.front(), PreviewData.frontActions, initialSelection = "app:100")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun DesktopPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
FrontEndScreen(PreviewData.front(), PreviewData.frontActions, initialSelection = "desktop")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun EmulatorPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
FrontEndScreen(PreviewData.front(), PreviewData.frontActions, initialSelection = "emu:dolphin")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun ArtPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
Column(Modifier.fillMaxSize().padding(24.dp)) {
|
||||||
|
ArtGrid(PreviewData.games.map { Tile(it.name, "Installed", null, it.gameIdString, onClick = {}) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun UpdatesPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
UpdatesPage(PreviewData.front(updates = UpdatesState(catalog = PreviewData.updatesCatalog)), PreviewData.frontActions, Modifier.fillMaxSize().padding(24.dp), installed = PreviewData.installed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun UpdatesDownloadingPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
UpdatesPage(PreviewData.front(updates = UpdatesState(catalog = PreviewData.updatesCatalog, stage = "Downloading", percent = 42)), PreviewData.frontActions, Modifier.fillMaxSize().padding(24.dp), installed = PreviewData.installed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun UpdatesErrorPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
UpdatesPage(PreviewData.front(updates = UpdatesState(error = "Could not check for updates")), PreviewData.frontActions, Modifier.fillMaxSize().padding(24.dp), installed = PreviewData.installed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Preview(name = "Paper theme", widthDp = 960, heightDp = 540, apiLevel = 34)
|
||||||
|
@Composable
|
||||||
|
internal fun AlternateThemePreview() {
|
||||||
|
PreviewHost(theme = Themes.PAPER) { FrontEndScreen(PreviewData.front(), PreviewData.frontActions) }
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun StorePreview() = PreviewHost {
|
||||||
|
val apps = listOf(
|
||||||
|
com.droiddeck.launcher.store.FlathubApi.AppSummary("org.videolan.VLC", "VLC", "Media player", null, "VideoLAN", true, 100_000),
|
||||||
|
com.droiddeck.launcher.store.FlathubApi.AppSummary("org.mozilla.firefox", "Firefox", "Web browser", null, "Mozilla", true, 100_000),
|
||||||
|
)
|
||||||
|
StorePage(PreviewData.front(), PreviewData.frontActions, Modifier.fillMaxSize(), previewSections = mapOf("popular" to apps, "trending" to apps))
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun AndroidAppsPreview() = PreviewHost {
|
||||||
|
FrontEndScreen(PreviewData.front(home = true), PreviewData.frontActions, initialSelection = "android-apps")
|
||||||
|
}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
package com.droiddeck.launcher.ui
|
||||||
|
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
|
||||||
|
internal class PreviewCase(val name: String, val content: @Composable () -> Unit) {
|
||||||
|
override fun toString() = name
|
||||||
|
}
|
||||||
|
|
||||||
|
internal val screenPreviewCases = listOf(
|
||||||
|
PreviewCase("AlternateTheme") { AlternateThemePreview() },
|
||||||
|
PreviewCase("Launcher") { LauncherPreview() },
|
||||||
|
PreviewCase("RuntimeMissing") { RuntimeMissingPreview() },
|
||||||
|
PreviewCase("RuntimeDownloading") { RuntimeDownloadingPreview() },
|
||||||
|
PreviewCase("Library") { LibraryPreview() },
|
||||||
|
PreviewCase("EmptyLibrary") { EmptyLibraryPreview() },
|
||||||
|
PreviewCase("GameDetails") { GameDetailsPreview() },
|
||||||
|
PreviewCase("Desktop") { DesktopPreview() },
|
||||||
|
PreviewCase("Emulator") { EmulatorPreview() },
|
||||||
|
PreviewCase("Setup") { SetupPreview() },
|
||||||
|
PreviewCase("ControllerMapping") { ControllerMappingPreview() },
|
||||||
|
PreviewCase("GpuDrivers") { GpuDriversPreview() },
|
||||||
|
PreviewCase("Protons") { ProtonsPreview() },
|
||||||
|
PreviewCase("ProtonDownload") { ProtonDownloadPreview() },
|
||||||
|
PreviewCase("ProtonsEmpty") { ProtonsEmptyPreview() },
|
||||||
|
PreviewCase("Drivers") { DriversPreview() },
|
||||||
|
PreviewCase("Loading") { LoadingPreview() },
|
||||||
|
PreviewCase("SessionStarting") { SessionStartingPreview() },
|
||||||
|
PreviewCase("SessionError") { SessionErrorPreview() },
|
||||||
|
PreviewCase("Keyboard") { KeyboardPreview() },
|
||||||
|
PreviewCase("Hud") { HudPreview() },
|
||||||
|
PreviewCase("WirelessAdb") { WirelessAdbPreview() },
|
||||||
|
PreviewCase("ProcessLimit") { ProcessLimitPreview() },
|
||||||
|
PreviewCase("AddApp") { AddAppPreview() },
|
||||||
|
PreviewCase("EditApp") { EditAppPreview() },
|
||||||
|
PreviewCase("Confirmation") { ConfirmationPreview() },
|
||||||
|
PreviewCase("CustomResolution") { CustomResolutionPreview() },
|
||||||
|
PreviewCase("RomsFolder") { RomsFolderPreview() },
|
||||||
|
PreviewCase("GameEnvironment") { GameEnvironmentPreview() },
|
||||||
|
PreviewCase("WindowsComponents") { WindowsComponentsPreview() },
|
||||||
|
PreviewCase("Controls") { ControlsPreview() },
|
||||||
|
PreviewCase("Widgets") { WidgetsPreview() },
|
||||||
|
PreviewCase("Art") { ArtPreview() },
|
||||||
|
PreviewCase("Cursor") { CursorPreview() },
|
||||||
|
PreviewCase("SteamDisplay") { SteamDisplayPreview() },
|
||||||
|
PreviewCase("SteamControls") { SteamControlsPreview() },
|
||||||
|
PreviewCase("SteamGames") { SteamGamesPreview() },
|
||||||
|
PreviewCase("SteamAudio") { SteamAudioPreview() },
|
||||||
|
PreviewCase("SteamSession") { SteamSessionPreview() },
|
||||||
|
PreviewCase("SteamSteam") { SteamSteamPreview() },
|
||||||
|
PreviewCase("DesktopSettings") { DesktopSettingsPreview() },
|
||||||
|
PreviewCase("DrawerController") { DrawerControllerPreview() },
|
||||||
|
PreviewCase("DrawerSecondScreen") { DrawerSecondScreenPreview() },
|
||||||
|
PreviewCase("DrawerDisplay") { DrawerDisplayPreview() },
|
||||||
|
PreviewCase("DrawerEffects") { DrawerEffectsPreview() },
|
||||||
|
PreviewCase("DrawerGames") { DrawerGamesPreview() },
|
||||||
|
PreviewCase("DrawerSession") { DrawerSessionPreview() },
|
||||||
|
PreviewCase("Performance") { PerformancePreview() },
|
||||||
|
PreviewCase("Components") { ComponentsPreview() },
|
||||||
|
PreviewCase("ComponentsLoading") { ComponentsLoadingPreview() },
|
||||||
|
PreviewCase("GpuComponents") { GpuComponentsPreview() },
|
||||||
|
PreviewCase("Updates") { UpdatesPreview() },
|
||||||
|
PreviewCase("UpdatesDownloading") { UpdatesDownloadingPreview() },
|
||||||
|
PreviewCase("UpdatesError") { UpdatesErrorPreview() },
|
||||||
|
PreviewCase("Store") { StorePreview() },
|
||||||
|
PreviewCase("DeveloperDisplay") { DeveloperDisplayPreview() },
|
||||||
|
PreviewCase("AppDisplay") { AppDisplayPreview() },
|
||||||
|
PreviewCase("AndroidApps") { AndroidAppsPreview() },
|
||||||
|
PreviewCase("SetupController") { SetupControllerPreview() },
|
||||||
|
PreviewCase("SetupSession") { SetupSessionPreview() },
|
||||||
|
PreviewCase("SetupLauncher") { SetupLauncherPreview() },
|
||||||
|
)
|
||||||
@@ -0,0 +1,143 @@
|
|||||||
|
package com.droiddeck.launcher.ui
|
||||||
|
|
||||||
|
import com.droiddeck.launcher.frontend.Library
|
||||||
|
import com.droiddeck.launcher.gpu.FrameGen
|
||||||
|
import com.droiddeck.launcher.gpu.Lossless
|
||||||
|
import com.droiddeck.launcher.input.ControllerPrefs
|
||||||
|
import com.droiddeck.launcher.input.SecondScreenMode
|
||||||
|
import com.droiddeck.launcher.input.SecondScreenDisplay
|
||||||
|
import com.droiddeck.launcher.session.ComponentsManager
|
||||||
|
import com.droiddeck.launcher.session.SessionPrefs
|
||||||
|
import com.droiddeck.launcher.session.SessionService
|
||||||
|
import com.droiddeck.launcher.update.AppUpdates
|
||||||
|
import java.io.File
|
||||||
|
|
||||||
|
/** Deterministic fixtures shared by Studio previews and the render smoke tests. */
|
||||||
|
internal object PreviewData {
|
||||||
|
val games = listOf("Portal 2", "Celeste", "Stardew Valley", "Hollow Knight", "A Short Hike", "Dead Cells")
|
||||||
|
.mapIndexed { i, name -> Library.SteamGame(100 + i, name, null, "/preview/steam") }
|
||||||
|
val controller = ControllerPrefs.Settings(0xFF1A9FFF.toInt(), 80, 100, true, true, true, true, true, true, false, emptyMap())
|
||||||
|
fun front(empty: Boolean = false, busy: Boolean = false, ready: Boolean = true, home: Boolean = false, updates: UpdatesState = UpdatesState()) = FrontEndState(
|
||||||
|
installed = if (ready) "2026.10.07" else null, ready = ready, available = "2026.10.07",
|
||||||
|
busy = busy, stage = if (busy) "Downloading runtime" else "", percent = if (busy) 42 else -1,
|
||||||
|
desktopInstalled = ready, offlineAccount = "Player", offline = false, frameGenLabel = "Off", romsDir = "/preview/ROMs", logsEnabled = true,
|
||||||
|
steamGames = if (empty) emptyList() else games,
|
||||||
|
emulators = listOf(Library.Emulator("dolphin", "Dolphin", "GameCube / Wii", "dolphin-emu", true, listOf(
|
||||||
|
Library.Rom("Wind Waker", File("/preview/ROMs/Wind Waker.iso"), "/root/ROMs/Wind Waker.iso", "dolphin"),
|
||||||
|
))), running = null, controller = controller, animationsEnabled = false, storeEnabled = true,
|
||||||
|
buildLabel = "Design preview", updates = updates, isHomeApp = home, homeScreenEnabled = home,
|
||||||
|
androidApps = if (home) listOf(com.droiddeck.launcher.HomeApp.LaunchableApp("Files", "preview.files", "preview.files.Main", null),
|
||||||
|
com.droiddeck.launcher.HomeApp.LaunchableApp("Settings", "preview.settings", "preview.settings.Main", null)) else emptyList(),
|
||||||
|
)
|
||||||
|
val frontActions = FrontEndActions(
|
||||||
|
onPlay = {},
|
||||||
|
onPlayDesktopUi = {},
|
||||||
|
onSteamGame = {},
|
||||||
|
onDesktop = {},
|
||||||
|
onEmulator = {},
|
||||||
|
onRom = {},
|
||||||
|
onResume = {},
|
||||||
|
onSteamSettings = {},
|
||||||
|
onDesktopSettings = {},
|
||||||
|
onInstallPackage = {},
|
||||||
|
onRemovePackage = {},
|
||||||
|
onRuntime = {},
|
||||||
|
onFrameGenPick = {},
|
||||||
|
onImportLossless = {},
|
||||||
|
onProtons = {},
|
||||||
|
onComponents = {},
|
||||||
|
onPerformance = {},
|
||||||
|
onRoms = {},
|
||||||
|
onFiles = {},
|
||||||
|
onLogs = {},
|
||||||
|
onOffline = {},
|
||||||
|
onWirelessAdbPair = { _, _, _, done -> done("Preview only") },
|
||||||
|
onWirelessAdbApply = { _, _, _, done -> done("Preview only") },
|
||||||
|
onSetPhantomProcessLimit = { _, done -> done("Preview only") },
|
||||||
|
controller = ControllerActions(
|
||||||
|
onOsc = {},
|
||||||
|
onTint = {},
|
||||||
|
onOpacity = {},
|
||||||
|
onSize = {},
|
||||||
|
onStickClick = {},
|
||||||
|
onAdaptiveSticks = {},
|
||||||
|
onRumble = {},
|
||||||
|
onSteamButton = {},
|
||||||
|
onQamButton = {},
|
||||||
|
onKeyboardButton = {},
|
||||||
|
onEditLayout = {},
|
||||||
|
onResetLayout = {},
|
||||||
|
onMapping = {},
|
||||||
|
onResetAll = {},
|
||||||
|
),
|
||||||
|
)
|
||||||
|
fun mode(steam: Boolean = true) = ModeSettings(
|
||||||
|
mode = if (steam) SessionService.MODE_STEAM else SessionService.MODE_DESKTOP, resolution = "1280x720",
|
||||||
|
hdr = false, hdrReason = "HDR is unavailable on this display", touchMode = SessionPrefs.TOUCH_AUTO,
|
||||||
|
suspendPolicy = SessionPrefs.SUSPEND_AUTO, oscMode = SessionPrefs.OSC_AUTO,
|
||||||
|
directAudio = true, mic = false, renderer = "vulkan", stretch16x9 = false,
|
||||||
|
pipSupported = true, syncBackend = "auto", steamChannel = "stable", steamController = "deck",
|
||||||
|
addedGamesDirs = listOf("/preview/Games"), deckyInstalled = "3.0.0", deckyEnabled = true,
|
||||||
|
)
|
||||||
|
val modeActions = ModeSettingsActions(
|
||||||
|
onResolution = {},
|
||||||
|
onHdr = {},
|
||||||
|
onTouch = {},
|
||||||
|
onSuspendPolicy = {},
|
||||||
|
onOsc = {},
|
||||||
|
onDirectAudio = {},
|
||||||
|
onMic = {},
|
||||||
|
onRenderer = {},
|
||||||
|
onDismiss = {},
|
||||||
|
)
|
||||||
|
val components = ComponentsManager.Snapshot(
|
||||||
|
protons = listOf(ComponentsManager.ProtonView(
|
||||||
|
ComponentsManager.Proton("ge-proton", "GE-Proton", File("/preview/proton"), "/opt/proton", "10-20", false),
|
||||||
|
mapOf("fex" to ComponentsManager.Component("FEX-2609", "FEX-2609", "Original", null, null),
|
||||||
|
"dxvk" to ComponentsManager.Component("2.7", "DXVK 2.7", "Original", null, null),
|
||||||
|
"vkd3d" to ComponentsManager.Component("2.14", "VKD3D-Proton 2.14", "Original", null, null)),
|
||||||
|
emptyList(), false,
|
||||||
|
)),
|
||||||
|
packages = listOf(ComponentsManager.Package("dxvk-2.7.tzst", "dxvk", "2.7", "DXVK 2.7", 24_000_000)),
|
||||||
|
)
|
||||||
|
val catalog = listOf(ComponentsManager.CatalogItem("dxvk-2.7.tzst", "dxvk", "2.7", "", 24_000_000, ""))
|
||||||
|
val drivers = listOf(DriverRow("auto", "Auto", "Recommended for this device", false),
|
||||||
|
DriverRow("turnip", "Turnip 25.3", "Android and Linux", true, DriverRow.BUNDLE))
|
||||||
|
val gpu = GpuDriversState(gpuName = "Adreno 740", gpuFamily = "Adreno 7xx", soc = "Snapdragon 8 Gen 2",
|
||||||
|
supportText = "Turnip supported", autoStatus = "Turnip 25.3", activeBundle = "Turnip 25.3",
|
||||||
|
pairs = listOf(PairRow("turnip", "Turnip", "25.3", "Android and Linux", true, true, true, true, true)),
|
||||||
|
androidRows = drivers, linuxRows = drivers)
|
||||||
|
val drawerActions = DrawerActions(
|
||||||
|
steam = true, isHomeApp = false, androidApps = emptyList(), hudOn = true,
|
||||||
|
frameGen = FrameGen.Mode.OFF, lossless = Lossless.State.NONE, oscMode = SessionPrefs.OSC_AUTO,
|
||||||
|
onScreenButtonsVisible = true, suspendPolicy = SessionPrefs.SUSPEND_AUTO, backActionsInverted = false,
|
||||||
|
touchMode = SessionPrefs.TOUCH_AUTO, touchAuto = "Touchpad", fexPreset = "balanced",
|
||||||
|
secondScreenMode = SecondScreenMode.NONE, secondScreenDisplays = listOf(SecondScreenDisplay(2, "Secondary screen")),
|
||||||
|
selectedSecondScreenDisplay = 2, controller = controller, components = components, pipSupported = true,
|
||||||
|
onHud = {},
|
||||||
|
onFrameGenPick = {},
|
||||||
|
onImportLossless = {},
|
||||||
|
onKeyboard = {},
|
||||||
|
onHardwareKeyboard = {},
|
||||||
|
onSteamMenu = {},
|
||||||
|
onQam = {},
|
||||||
|
onOsc = {},
|
||||||
|
onSuspendPolicy = {},
|
||||||
|
onBackActionsInverted = {},
|
||||||
|
onTouch = {},
|
||||||
|
onFexPreset = {},
|
||||||
|
onSecondScreenMode = {},
|
||||||
|
onSecondScreenDisplay = {},
|
||||||
|
onLaunchAndroidApp = { _, _ -> },
|
||||||
|
onBackground = {},
|
||||||
|
onShareLogs = {},
|
||||||
|
onStop = {},
|
||||||
|
onClose = {},
|
||||||
|
)
|
||||||
|
const val TIME = 1_791_331_200_000L
|
||||||
|
val installed = AppUpdates.Installed("preview-old", 0, "0.3.0", 10, true, TIME - 86_400_000, true)
|
||||||
|
val release = AppUpdates.Release("v0.3.1", "Improve handheld layouts", "Settings and library improvements.", "preview-new", 0, "0.3.1", 11, TIME,
|
||||||
|
"", AppUpdates.Apk("DroidDeck.apk", "", 200_000_000, "", "com.droiddeck.launcher", 11, com.droiddeck.launcher.BuildConfig.RELEASE_SIGNER))
|
||||||
|
val updatesCatalog = AppUpdates.Catalog(release, release, emptyList(), TIME,
|
||||||
|
listOf(AppUpdates.PreviewChange("preview-new", "Improve handheld layouts", "Settings and library improvements.", TIME)))
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
package com.droiddeck.launcher.ui
|
||||||
|
|
||||||
|
import androidx.activity.OnBackPressedDispatcher
|
||||||
|
import androidx.activity.OnBackPressedDispatcherOwner
|
||||||
|
import androidx.activity.compose.LocalActivityResultRegistryOwner
|
||||||
|
import androidx.activity.compose.LocalOnBackPressedDispatcherOwner
|
||||||
|
import androidx.activity.result.ActivityResultRegistry
|
||||||
|
import androidx.activity.result.ActivityResultRegistryOwner
|
||||||
|
import androidx.activity.result.contract.ActivityResultContract
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.CompositionLocalProvider
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.platform.LocalInspectionMode
|
||||||
|
import androidx.compose.ui.tooling.preview.Preview
|
||||||
|
import androidx.core.app.ActivityOptionsCompat
|
||||||
|
import androidx.lifecycle.Lifecycle
|
||||||
|
import androidx.lifecycle.LifecycleOwner
|
||||||
|
import androidx.lifecycle.LifecycleRegistry
|
||||||
|
|
||||||
|
@Preview(name = "Handheld", widthDp = 960, heightDp = 540, apiLevel = 34)
|
||||||
|
@Preview(name = "Compact", widthDp = 480, heightDp = 360, apiLevel = 34)
|
||||||
|
@Preview(name = "Portrait", widthDp = 400, heightDp = 700, apiLevel = 34)
|
||||||
|
@Preview(name = "Large text", widthDp = 960, heightDp = 540, fontScale = 1.3f, apiLevel = 34)
|
||||||
|
@Target(AnnotationTarget.FUNCTION)
|
||||||
|
@Retention(AnnotationRetention.BINARY)
|
||||||
|
annotation class DroidDeckPreviews
|
||||||
|
|
||||||
|
/** Every preview uses the production theme and inert Android navigation/picker owners. */
|
||||||
|
@Composable
|
||||||
|
internal fun PreviewHost(theme: String = Themes.GRAPHITE, content: @Composable () -> Unit) {
|
||||||
|
val owner = remember { PreviewOwner() }
|
||||||
|
CompositionLocalProvider(
|
||||||
|
LocalInspectionMode provides true,
|
||||||
|
LocalOnBackPressedDispatcherOwner provides owner,
|
||||||
|
LocalActivityResultRegistryOwner provides owner,
|
||||||
|
) {
|
||||||
|
DroidDeckTheme(theme = theme) {
|
||||||
|
Box(Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background)) { content() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private class PreviewOwner : OnBackPressedDispatcherOwner, ActivityResultRegistryOwner, LifecycleOwner {
|
||||||
|
override val lifecycle: Lifecycle = LifecycleRegistry(this).apply { currentState = Lifecycle.State.RESUMED }
|
||||||
|
override val onBackPressedDispatcher = OnBackPressedDispatcher()
|
||||||
|
override val activityResultRegistry = object : ActivityResultRegistry() {
|
||||||
|
override fun <I, O> onLaunch(requestCode: Int, contract: ActivityResultContract<I, O>, input: I, options: ActivityOptionsCompat?) = Unit
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
package com.droiddeck.launcher.ui
|
||||||
|
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun GpuDriversPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
GpuDriversPanel(PreviewData.gpu, GpuDriversActions()) {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun ProtonsPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
ProtonPage(listOf(ProtonRow("ge-proton", "GE-Proton 10-20", "10-20", false), ProtonRow("proton", "Proton Experimental", null, false)), null, null, -1, true, false, {}, {}, {}, {})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun ProtonDownloadPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
ProtonPage(listOf(ProtonRow("ge-proton", "GE-Proton 10-20", null, false)), "ge-proton", "Downloading", 42, true, false, {}, {}, {}, {})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun ProtonsEmptyPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
ProtonPage(emptyList(), null, null, -1, false, false, {}, {}, {}, {})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun DriversPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
DriverPage("GPU drivers", "Choose a driver", PreviewData.drivers, "auto",
|
||||||
|
listOf(DownloadRow("turnip", "Turnip 25.3", "Adreno 7xx", 42)), "Downloading", false, "Import driver", true,
|
||||||
|
{}, {}, {}, {}, {}, {}, {})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun ComponentsPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
ComponentsPage(PreviewData.components, PreviewData.catalog, PreviewData.TIME, "ge-proton", "dxvk", false, null, emptyMap(),
|
||||||
|
{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, requestInitialFocus = false, gpu = PreviewData.gpu)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun ComponentsLoadingPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
ComponentsPage(null, PreviewData.catalog, PreviewData.TIME, "ge-proton", "dxvk", true, null, emptyMap(),
|
||||||
|
{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, requestInitialFocus = false, gpu = PreviewData.gpu)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun GpuComponentsPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
ComponentsPage(PreviewData.components, PreviewData.catalog, PreviewData.TIME, "ge-proton", GPU_TAB, false, null, emptyMap(),
|
||||||
|
{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, requestInitialFocus = false, gpu = PreviewData.gpu)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
package com.droiddeck.launcher.ui
|
||||||
|
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.ui.geometry.Offset
|
||||||
|
import com.droiddeck.launcher.session.LoadingState
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun LoadingPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
LoadingOverlay("Downloading runtime", 42, "00:32", "", false, LoadingState.Topic.RUNTIME, true, onCancel = {})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun SessionStartingPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
LoadingOverlay("Starting Steam", -1, "00:08", "", false, LoadingState.Topic.STEAM_STARTING, true, onCancel = {})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun SessionErrorPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
LoadingOverlay("Steam stopped", -1, "00:08", "Try starting Steam again.", true, LoadingState.Topic.STEAM, true, endedDetail = "Exit code 1", onRetry = {}, onShareLogs = {}, onClose = {})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun KeyboardPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
PcKeyboard({ _, _ -> }, {}, {})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun HudPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
HudText("60 FPS • GPU 72% • CPU 38%")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun CursorPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
CursorOverlay(Offset(220f, 180f), true, 2f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun DrawerControllerPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
SessionDrawer(true, SessionDrawerPage.CONTROLLER, false, {}, PreviewData.drawerActions)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun DrawerSecondScreenPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
SessionDrawer(true, SessionDrawerPage.SECOND_SCREEN, false, {}, PreviewData.drawerActions)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun DrawerDisplayPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
SessionDrawer(true, SessionDrawerPage.DISPLAY, false, {}, PreviewData.drawerActions)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun DrawerEffectsPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
SessionDrawer(true, SessionDrawerPage.EFFECTS, false, {}, PreviewData.drawerActions)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun DrawerGamesPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
SessionDrawer(true, SessionDrawerPage.GAMES, false, {}, PreviewData.drawerActions)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun DrawerSessionPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
SessionDrawer(true, SessionDrawerPage.SESSION, false, {}, PreviewData.drawerActions)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,165 @@
|
|||||||
|
package com.droiddeck.launcher.ui
|
||||||
|
|
||||||
|
import androidx.compose.foundation.rememberScrollState
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun SetupPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
FrontEndScreen(PreviewData.front(), PreviewData.frontActions, initialSelection = "setup")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun ControllerMappingPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
ControllerMappingPage(mapOf("a" to "b"), { _, _ -> }, {}, {})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun ControlsPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
val host = rememberMenuHost()
|
||||||
|
SettingsPage(host, "Controller", {}, scroll = rememberScrollState()) {
|
||||||
|
ControllerRows(host, "auto", PreviewData.controller, PreviewData.frontActions.controller!!)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun WidgetsPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
val host = rememberMenuHost()
|
||||||
|
SettingsPage(host, "Settings controls", {}, scroll = rememberScrollState()) {
|
||||||
|
SettingsGroup("Display") {
|
||||||
|
ChoiceRow(host, "resolution", "Resolution", "Virtual screen size", listOf("720p" to "1280 × 720", "1080p" to "1920 × 1080"), "720p") {}
|
||||||
|
ToggleRow(host, "hdr", "HDR", "High dynamic range", true) {}
|
||||||
|
SliderRow("Sharpness", null, 75, 0..100) {}
|
||||||
|
ActionRow("GPU driver", null, "Manage", {})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun SteamDisplayPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
ModeSettingsPage(PreviewData.mode(), PreviewData.modeActions, initialTab = 0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun SteamControlsPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
ModeSettingsPage(PreviewData.mode(), PreviewData.modeActions, initialTab = 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun SteamGamesPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
ModeSettingsPage(PreviewData.mode(), PreviewData.modeActions, initialTab = 2)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun SteamAudioPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
ModeSettingsPage(PreviewData.mode(), PreviewData.modeActions, initialTab = 3)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun SteamSessionPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
ModeSettingsPage(PreviewData.mode(), PreviewData.modeActions, initialTab = 4)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun SteamSteamPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
ModeSettingsPage(PreviewData.mode(), PreviewData.modeActions, initialTab = 5)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun DesktopSettingsPreview() {
|
||||||
|
PreviewHost {
|
||||||
|
ModeSettingsPage(PreviewData.mode(steam = false), PreviewData.modeActions)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun PerformancePreview() {
|
||||||
|
PreviewHost {
|
||||||
|
PerformancePage(
|
||||||
|
cores = List(8) { CoreRow(it, if (it < 4) "Efficiency" else "Performance") },
|
||||||
|
clientOverride = false,
|
||||||
|
clientCores = setOf(0, 1, 2, 3),
|
||||||
|
gameCores = (0..7).toSet(),
|
||||||
|
tuSysmem = false,
|
||||||
|
zinkLazy = false,
|
||||||
|
glThread = false,
|
||||||
|
noGlError = false,
|
||||||
|
noXalia = false,
|
||||||
|
fastSync = false,
|
||||||
|
syncFallback = false,
|
||||||
|
fsyncFirst = false,
|
||||||
|
gamescopeRealtime = false,
|
||||||
|
gpuClockPin = false,
|
||||||
|
prootNoSeccomp = false,
|
||||||
|
prootFastPath = false,
|
||||||
|
guestHostname = "droiddeck",
|
||||||
|
phantomWarning = null,
|
||||||
|
onClientOverride = {},
|
||||||
|
onTuSysmem = {},
|
||||||
|
onZinkLazy = {},
|
||||||
|
onGlThread = {},
|
||||||
|
onNoGlError = {},
|
||||||
|
onNoXalia = {},
|
||||||
|
onFastSync = {},
|
||||||
|
onSyncFallback = {},
|
||||||
|
onFsyncFirst = {},
|
||||||
|
onGamescopeRealtime = {},
|
||||||
|
onGpuClockPin = {},
|
||||||
|
onProotNoSeccomp = {},
|
||||||
|
onProotFastPath = {},
|
||||||
|
onGuestHostname = {},
|
||||||
|
onClientCore = { _, _ -> },
|
||||||
|
onGameCore = { _, _ -> },
|
||||||
|
onDismiss = {},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun SetupControllerPreview() = PreviewHost {
|
||||||
|
SetupPanel(PreviewData.front(), PreviewData.frontActions, {}, {}, initialTab = 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun SetupSessionPreview() = PreviewHost {
|
||||||
|
SetupPanel(PreviewData.front(), PreviewData.frontActions, {}, {}, initialTab = 2)
|
||||||
|
}
|
||||||
|
|
||||||
|
@DroidDeckPreviews
|
||||||
|
@Composable
|
||||||
|
internal fun SetupLauncherPreview() = PreviewHost {
|
||||||
|
SetupPanel(PreviewData.front(), PreviewData.frontActions, {}, {}, initialTab = 3)
|
||||||
|
}
|
||||||
@@ -30,9 +30,6 @@
|
|||||||
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
||||||
<!-- Installs DroidDeck's own updates (Updates page) over itself, after the user allows it. -->
|
<!-- Installs DroidDeck's own updates (Updates page) over itself, after the user allows it. -->
|
||||||
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
|
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
|
||||||
<!-- A paired Steam Controller, read over Bluetooth LE out of lizard mode (SteamControllerBle).
|
|
||||||
Granted at install below targetSdk 31; no scan, so no location. -->
|
|
||||||
<uses-permission android:name="android.permission.BLUETOOTH" />
|
|
||||||
|
|
||||||
<uses-feature android:name="android.hardware.vulkan.version" android:version="0x401000" android:required="true" />
|
<uses-feature android:name="android.hardware.vulkan.version" android:version="0x401000" android:required="true" />
|
||||||
<uses-feature android:name="android.hardware.gamepad" android:required="false" />
|
<uses-feature android:name="android.hardware.gamepad" android:required="false" />
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -136,7 +136,6 @@ JNIEXPORT jint JNICALL Java_com_termux_terminal_JNI_createSubprocess(
|
|||||||
if (!arg_utf8) return throw_runtime_exception(env, "GetStringUTFChars() failed for argv");
|
if (!arg_utf8) return throw_runtime_exception(env, "GetStringUTFChars() failed for argv");
|
||||||
argv[i] = strdup(arg_utf8);
|
argv[i] = strdup(arg_utf8);
|
||||||
(*env)->ReleaseStringUTFChars(env, arg_java_string, arg_utf8);
|
(*env)->ReleaseStringUTFChars(env, arg_java_string, arg_utf8);
|
||||||
(*env)->DeleteLocalRef(env, arg_java_string);
|
|
||||||
}
|
}
|
||||||
argv[size] = NULL;
|
argv[size] = NULL;
|
||||||
}
|
}
|
||||||
@@ -152,7 +151,6 @@ JNIEXPORT jint JNICALL Java_com_termux_terminal_JNI_createSubprocess(
|
|||||||
if (!env_utf8) return throw_runtime_exception(env, "GetStringUTFChars() failed for env");
|
if (!env_utf8) return throw_runtime_exception(env, "GetStringUTFChars() failed for env");
|
||||||
envp[i] = strdup(env_utf8);
|
envp[i] = strdup(env_utf8);
|
||||||
(*env)->ReleaseStringUTFChars(env, env_java_string, env_utf8);
|
(*env)->ReleaseStringUTFChars(env, env_java_string, env_utf8);
|
||||||
(*env)->DeleteLocalRef(env, env_java_string);
|
|
||||||
}
|
}
|
||||||
envp[size] = NULL;
|
envp[size] = NULL;
|
||||||
}
|
}
|
||||||
@@ -162,7 +160,7 @@ JNIEXPORT jint JNICALL Java_com_termux_terminal_JNI_createSubprocess(
|
|||||||
char const* cmd_utf8 = (*env)->GetStringUTFChars(env, cmd, NULL);
|
char const* cmd_utf8 = (*env)->GetStringUTFChars(env, cmd, NULL);
|
||||||
int ptm = create_subprocess(env, cmd_utf8, cmd_cwd, argv, envp, &procId, rows, columns);
|
int ptm = create_subprocess(env, cmd_utf8, cmd_cwd, argv, envp, &procId, rows, columns);
|
||||||
(*env)->ReleaseStringUTFChars(env, cmd, cmd_utf8);
|
(*env)->ReleaseStringUTFChars(env, cmd, cmd_utf8);
|
||||||
(*env)->ReleaseStringUTFChars(env, cwd, cmd_cwd);
|
(*env)->ReleaseStringUTFChars(env, cmd, cmd_cwd);
|
||||||
|
|
||||||
if (argv) {
|
if (argv) {
|
||||||
for (char** tmp = argv; *tmp; ++tmp) free(*tmp);
|
for (char** tmp = argv; *tmp; ++tmp) free(*tmp);
|
||||||
|
|||||||
@@ -255,11 +255,7 @@ static void target_destroy(struct fx_target *t) {
|
|||||||
static int target_ensure(struct fx_target *t, int w, int h, const char *what) {
|
static int target_ensure(struct fx_target *t, int w, int h, const char *what) {
|
||||||
if (t->img && t->w == w && t->h == h) return 0;
|
if (t->img && t->w == w && t->h == h) return 0;
|
||||||
target_destroy(t);
|
target_destroy(t);
|
||||||
/* Unrestricted mutable views keep these render-then-blit targets uncompressed on Turnip.
|
VkImageCreateInfo ii = {.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, .imageType = VK_IMAGE_TYPE_2D,
|
||||||
* UBWC targets corrupt even a constant-colour pass on Adreno 740 (FSR becomes black).
|
|
||||||
* Only the chain's intermediate images need this; the scene and guest images stay unchanged. */
|
|
||||||
VkImageCreateInfo ii = {.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
|
|
||||||
.flags = VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT, .imageType = VK_IMAGE_TYPE_2D,
|
|
||||||
.format = g_fx_fmt, .extent = {(uint32_t)w, (uint32_t)h, 1}, .mipLevels = 1,
|
.format = g_fx_fmt, .extent = {(uint32_t)w, (uint32_t)h, 1}, .mipLevels = 1,
|
||||||
.arrayLayers = 1, .samples = VK_SAMPLE_COUNT_1_BIT, .tiling = VK_IMAGE_TILING_OPTIMAL,
|
.arrayLayers = 1, .samples = VK_SAMPLE_COUNT_1_BIT, .tiling = VK_IMAGE_TILING_OPTIMAL,
|
||||||
.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT |
|
.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT |
|
||||||
@@ -296,10 +292,6 @@ static void scene_release(void) {
|
|||||||
memset(&g_scene, 0, sizeof(g_scene));
|
memset(&g_scene, 0, sizeof(g_scene));
|
||||||
}
|
}
|
||||||
|
|
||||||
void vkp_effects_forget_image(VkImage img) {
|
|
||||||
if (img && g_scene.img == img) scene_release();
|
|
||||||
}
|
|
||||||
|
|
||||||
static int scene_ensure(VkImage img, int w, int h) {
|
static int scene_ensure(VkImage img, int w, int h) {
|
||||||
if (g_scene.img == img && g_scene.w == w && g_scene.h == h && g_scene.ds) return 0;
|
if (g_scene.img == img && g_scene.w == w && g_scene.h == h && g_scene.ds) return 0;
|
||||||
scene_release();
|
scene_release();
|
||||||
|
|||||||
@@ -55,10 +55,6 @@ VkImage vkp_effects_run(VkCommandBuffer cmd, VkImage scene, int scene_w, int sce
|
|||||||
/* Compositor thread: drop every Vulkan object (device teardown / device lost). */
|
/* Compositor thread: drop every Vulkan object (device teardown / device lost). */
|
||||||
void vkp_effects_destroy(void);
|
void vkp_effects_destroy(void);
|
||||||
|
|
||||||
/* Compositor thread: release the cached source view/descriptor before its owner destroys img.
|
|
||||||
* A later image can reuse the same Vulkan handle and dimensions; that is not the same resource. */
|
|
||||||
void vkp_effects_forget_image(VkImage img);
|
|
||||||
|
|
||||||
/* Compositor thread, before vkp_effects_run(): the format of the scene image it will be handed and the
|
/* Compositor thread, before vkp_effects_run(): the format of the scene image it will be handed and the
|
||||||
* format its own targets use. R8G8B8A8 / R8G8B8A8 for every SDR frame (the default); A2B10G10R10 /
|
* format its own targets use. R8G8B8A8 / R8G8B8A8 for every SDR frame (the default); A2B10G10R10 /
|
||||||
* A2B10G10R10 while an HDR picture runs through it (hdr_compose.h). A target-format change rebuilds the
|
* A2B10G10R10 while an HDR picture runs through it (hdr_compose.h). A target-format change rebuilds the
|
||||||
|
|||||||
@@ -1164,7 +1164,6 @@ static void record_draw(VkCommandBuffer cmd, const struct vkp_draw *d, const VkI
|
|||||||
}
|
}
|
||||||
|
|
||||||
static void destroy_scene_image(void) {
|
static void destroy_scene_image(void) {
|
||||||
if (g_scene.img) vkp_effects_forget_image(g_scene.img);
|
|
||||||
if (g_scene.img) hdrc_forget_image(g_scene.img); /* the HDR pass may have drawn into it */
|
if (g_scene.img) hdrc_forget_image(g_scene.img); /* the HDR pass may have drawn into it */
|
||||||
if (g_scene.img) blendp_forget_image(g_scene.img);
|
if (g_scene.img) blendp_forget_image(g_scene.img);
|
||||||
if (g_scene.img) g_vk.DestroyImage(g_dev, g_scene.img, NULL);
|
if (g_scene.img) g_vk.DestroyImage(g_dev, g_scene.img, NULL);
|
||||||
@@ -1204,7 +1203,6 @@ static int ensure_scene_image(int w, int h) {
|
|||||||
static int ensure_img(struct vkp_img_slot *s, int w, int h, VkFormat fmt, VkImageUsageFlags usage, const char *what) {
|
static int ensure_img(struct vkp_img_slot *s, int w, int h, VkFormat fmt, VkImageUsageFlags usage, const char *what) {
|
||||||
if (s->img && s->w == w && s->h == h && s->fmt == fmt) return 0;
|
if (s->img && s->w == w && s->h == h && s->fmt == fmt) return 0;
|
||||||
if (s->img) hdrc_forget_image(s->img);
|
if (s->img) hdrc_forget_image(s->img);
|
||||||
if (s->img) vkp_effects_forget_image(s->img);
|
|
||||||
if (s->img) blendp_forget_image(s->img);
|
if (s->img) blendp_forget_image(s->img);
|
||||||
if (s->img) g_vk.DestroyImage(g_dev, s->img, NULL);
|
if (s->img) g_vk.DestroyImage(g_dev, s->img, NULL);
|
||||||
if (s->mem) g_vk.FreeMemory(g_dev, s->mem, NULL);
|
if (s->mem) g_vk.FreeMemory(g_dev, s->mem, NULL);
|
||||||
|
|||||||
@@ -22,6 +22,8 @@ class App : Application() {
|
|||||||
override fun onCreate() {
|
override fun onCreate() {
|
||||||
super.onCreate()
|
super.onCreate()
|
||||||
CrashHandler.install(this)
|
CrashHandler.install(this)
|
||||||
|
// Before anything else touches the session prefs, so the first session already runs in Deck mode.
|
||||||
|
com.droiddeck.launcher.session.SessionPrefs.settleDeckModeDefault(this)
|
||||||
com.droiddeck.launcher.session.SessionPrefs.settleGpuDriverMode(this)
|
com.droiddeck.launcher.session.SessionPrefs.settleGpuDriverMode(this)
|
||||||
com.droiddeck.launcher.update.AppUpdates.init(this)
|
com.droiddeck.launcher.update.AppUpdates.init(this)
|
||||||
GpuClockPin.clearLeftover(this)
|
GpuClockPin.clearLeftover(this)
|
||||||
|
|||||||
@@ -14,7 +14,6 @@ class HomeActivity : Activity() {
|
|||||||
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
requestedOrientation = com.droiddeck.launcher.session.SessionPrefs.orientation(this)
|
|
||||||
routeHome()
|
routeHome()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -10,7 +10,6 @@ import java.io.File
|
|||||||
import android.content.pm.PackageManager
|
import android.content.pm.PackageManager
|
||||||
import android.hardware.display.DisplayManager
|
import android.hardware.display.DisplayManager
|
||||||
import android.net.Uri
|
import android.net.Uri
|
||||||
import android.os.Build
|
|
||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
import android.os.Handler
|
import android.os.Handler
|
||||||
import android.os.Looper
|
import android.os.Looper
|
||||||
@@ -18,7 +17,6 @@ import android.util.Log
|
|||||||
import android.view.Display
|
import android.view.Display
|
||||||
import android.view.KeyEvent
|
import android.view.KeyEvent
|
||||||
import android.view.View
|
import android.view.View
|
||||||
import android.view.WindowManager
|
|
||||||
import androidx.activity.ComponentActivity
|
import androidx.activity.ComponentActivity
|
||||||
import androidx.activity.compose.setContent
|
import androidx.activity.compose.setContent
|
||||||
import androidx.activity.result.contract.ActivityResultContracts
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
@@ -46,6 +44,7 @@ import com.droiddeck.launcher.session.GameSaves
|
|||||||
import com.droiddeck.launcher.session.SessionLogShare
|
import com.droiddeck.launcher.session.SessionLogShare
|
||||||
import com.droiddeck.launcher.session.SessionPrefs
|
import com.droiddeck.launcher.session.SessionPrefs
|
||||||
import com.droiddeck.launcher.session.SteamRepair
|
import com.droiddeck.launcher.session.SteamRepair
|
||||||
|
import com.droiddeck.launcher.ui.ProtonPage
|
||||||
import com.droiddeck.launcher.core.CpuCores
|
import com.droiddeck.launcher.core.CpuCores
|
||||||
import com.droiddeck.launcher.core.PhantomProcessLimit
|
import com.droiddeck.launcher.core.PhantomProcessLimit
|
||||||
import com.droiddeck.launcher.core.PhantomProcessStatus
|
import com.droiddeck.launcher.core.PhantomProcessStatus
|
||||||
@@ -54,6 +53,7 @@ import com.droiddeck.launcher.core.WifiDiscovery
|
|||||||
import com.droiddeck.launcher.core.WirelessAdbPairingService
|
import com.droiddeck.launcher.core.WirelessAdbPairingService
|
||||||
import com.droiddeck.launcher.ui.CoreRow
|
import com.droiddeck.launcher.ui.CoreRow
|
||||||
import com.droiddeck.launcher.ui.PerformancePage
|
import com.droiddeck.launcher.ui.PerformancePage
|
||||||
|
import com.droiddeck.launcher.ui.ModeSettingsPage
|
||||||
import com.droiddeck.launcher.ui.ModeSettings
|
import com.droiddeck.launcher.ui.ModeSettings
|
||||||
import com.droiddeck.launcher.ui.ModeSettingsActions
|
import com.droiddeck.launcher.ui.ModeSettingsActions
|
||||||
import com.droiddeck.launcher.ui.ConfirmDialog
|
import com.droiddeck.launcher.ui.ConfirmDialog
|
||||||
@@ -119,9 +119,11 @@ class MainActivity : ComponentActivity() {
|
|||||||
private var showNonAdreno by mutableStateOf<LinuxRuntimeInstaller.Release?>(null)
|
private var showNonAdreno by mutableStateOf<LinuxRuntimeInstaller.Release?>(null)
|
||||||
private var glThread by mutableStateOf(true)
|
private var glThread by mutableStateOf(true)
|
||||||
private var noGlError by mutableStateOf(true)
|
private var noGlError by mutableStateOf(true)
|
||||||
|
private var steamDeckMode by mutableStateOf(false)
|
||||||
private var steamRepairQueued by mutableStateOf(false)
|
private var steamRepairQueued by mutableStateOf(false)
|
||||||
private var mangoapp by mutableStateOf(true)
|
private var mangoapp by mutableStateOf(true)
|
||||||
private var steamController by mutableStateOf(SessionPrefs.CONTROLLER_DECK)
|
private var steamController by mutableStateOf(SessionPrefs.CONTROLLER_DECK)
|
||||||
|
private var showProtons by mutableStateOf(false)
|
||||||
// Components page: FEX / DXVK / VKD3D-Proton per Proton (ComponentsManager).
|
// Components page: FEX / DXVK / VKD3D-Proton per Proton (ComponentsManager).
|
||||||
private var showComponents by mutableStateOf(false)
|
private var showComponents by mutableStateOf(false)
|
||||||
private var focusComponentsContent by mutableStateOf(true)
|
private var focusComponentsContent by mutableStateOf(true)
|
||||||
@@ -160,10 +162,10 @@ class MainActivity : ComponentActivity() {
|
|||||||
private var showPhantomGate by mutableStateOf(false)
|
private var showPhantomGate by mutableStateOf(false)
|
||||||
private var directAudio by mutableStateOf(false)
|
private var directAudio by mutableStateOf(false)
|
||||||
private var stretch16x9 by mutableStateOf(false)
|
private var stretch16x9 by mutableStateOf(false)
|
||||||
private var orientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE)
|
|
||||||
private var launcherFullscreen by mutableStateOf(true)
|
private var launcherFullscreen by mutableStateOf(true)
|
||||||
private var animationsEnabled by mutableStateOf(true)
|
private var animationsEnabled by mutableStateOf(true)
|
||||||
private var gameStoresEnabled by mutableStateOf(true)
|
private var storeEnabled by mutableStateOf(false)
|
||||||
|
private var gameStoresEnabled by mutableStateOf(false)
|
||||||
private var gameStoresSpeedTier by mutableStateOf("fast")
|
private var gameStoresSpeedTier by mutableStateOf("fast")
|
||||||
private var storesOpenTab by mutableStateOf(SessionPrefs.STORES_OPEN_LIBRARY)
|
private var storesOpenTab by mutableStateOf(SessionPrefs.STORES_OPEN_LIBRARY)
|
||||||
/** A page a notification asked for ("stores:downloads", "app:<id>"), until the front end has gone there. */
|
/** A page a notification asked for ("stores:downloads", "app:<id>"), until the front end has gone there. */
|
||||||
@@ -334,11 +336,12 @@ class MainActivity : ComponentActivity() {
|
|||||||
romsDir = path
|
romsDir = path
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// The mode whose lifted sheet last read its settings, with what it shows; refreshed by loadModeSettings().
|
// The mode whose settings dialog is open, with what it shows; refreshed by openModeSettings().
|
||||||
private var settingsMode by mutableStateOf<String?>(null)
|
private var settingsMode by mutableStateOf<String?>(null)
|
||||||
private var resolution by mutableStateOf(com.droiddeck.launcher.session.SessionDisplay.DEFAULT_RESOLUTION)
|
private var resolution by mutableStateOf(com.droiddeck.launcher.session.SessionDisplay.DEFAULT_RESOLUTION)
|
||||||
private var fexPreset by mutableStateOf("")
|
private var fexPreset by mutableStateOf("")
|
||||||
private var forceSsbs by mutableStateOf(false)
|
private var forceSsbs by mutableStateOf(false)
|
||||||
|
private var steamChannel by mutableStateOf("steamdeck_publicbeta")
|
||||||
private var runSteamAtStartup by mutableStateOf(false)
|
private var runSteamAtStartup by mutableStateOf(false)
|
||||||
private var theme by mutableStateOf("graphite")
|
private var theme by mutableStateOf("graphite")
|
||||||
private var appScale by mutableStateOf(com.droiddeck.launcher.core.AppUiPrefs.DEFAULT_SCALE)
|
private var appScale by mutableStateOf(com.droiddeck.launcher.core.AppUiPrefs.DEFAULT_SCALE)
|
||||||
@@ -360,8 +363,6 @@ class MainActivity : ComponentActivity() {
|
|||||||
}
|
}
|
||||||
private var romsDir by mutableStateOf<String?>(null)
|
private var romsDir by mutableStateOf<String?>(null)
|
||||||
private var steamGames by mutableStateOf<List<Library.SteamGame>>(emptyList())
|
private var steamGames by mutableStateOf<List<Library.SteamGame>>(emptyList())
|
||||||
@Volatile private var componentSweepDone = false
|
|
||||||
@Volatile private var componentSweepSession: String? = null
|
|
||||||
private var emulatorList by mutableStateOf<List<Library.Emulator>>(emptyList())
|
private var emulatorList by mutableStateOf<List<Library.Emulator>>(emptyList())
|
||||||
private var runningLabel by mutableStateOf<String?>(null)
|
private var runningLabel by mutableStateOf<String?>(null)
|
||||||
private var logsEnabled by mutableStateOf(true)
|
private var logsEnabled by mutableStateOf(true)
|
||||||
@@ -531,10 +532,9 @@ class MainActivity : ComponentActivity() {
|
|||||||
// Last start's game list, so the Steam wall is up on the first frame; refresh() replaces it.
|
// Last start's game list, so the Steam wall is up on the first frame; refresh() replaces it.
|
||||||
steamGames = if (shortcutPicker) emptyList() else com.droiddeck.launcher.frontend.LibraryCache.load(this)
|
steamGames = if (shortcutPicker) emptyList() else com.droiddeck.launcher.frontend.LibraryCache.load(this)
|
||||||
backActionsInverted = SessionPrefs.backActionsInverted(this)
|
backActionsInverted = SessionPrefs.backActionsInverted(this)
|
||||||
orientation = SessionPrefs.orientation(this)
|
|
||||||
requestedOrientation = orientation
|
|
||||||
launcherFullscreen = SessionPrefs.launcherFullscreen(this)
|
launcherFullscreen = SessionPrefs.launcherFullscreen(this)
|
||||||
animationsEnabled = SessionPrefs.animationsEnabled(this)
|
animationsEnabled = SessionPrefs.animationsEnabled(this)
|
||||||
|
storeEnabled = SessionPrefs.storeEnabled(this)
|
||||||
gameStoresEnabled = SessionPrefs.gameStoresEnabled(this)
|
gameStoresEnabled = SessionPrefs.gameStoresEnabled(this)
|
||||||
gameStoresSpeedTier = SessionPrefs.gameStoresSpeedTier(this)
|
gameStoresSpeedTier = SessionPrefs.gameStoresSpeedTier(this)
|
||||||
storesOpenTab = SessionPrefs.storesOpenTab(this)
|
storesOpenTab = SessionPrefs.storesOpenTab(this)
|
||||||
@@ -544,8 +544,11 @@ class MainActivity : ComponentActivity() {
|
|||||||
setContent {
|
setContent {
|
||||||
DroidDeckTheme(theme, appScale = appScale) {
|
DroidDeckTheme(theme, appScale = appScale) {
|
||||||
com.droiddeck.launcher.ui.FocusGlideHost(androidx.compose.ui.Modifier.fillMaxSize().exposeTestTags()) {
|
com.droiddeck.launcher.ui.FocusGlideHost(androidx.compose.ui.Modifier.fillMaxSize().exposeTestTags()) {
|
||||||
|
val sm = settingsMode
|
||||||
val page: (@Composable () -> Unit)? = when {
|
val page: (@Composable () -> Unit)? = when {
|
||||||
|
sm != null -> { { ModeSettingsHost(sm) } }
|
||||||
showPerformance -> { { PerformanceHost() } }
|
showPerformance -> { { PerformanceHost() } }
|
||||||
|
showProtons -> { { ProtonHost() } }
|
||||||
showComponents -> { { ComponentsHost() } }
|
showComponents -> { { ComponentsHost() } }
|
||||||
showMapping -> { { MappingHost() } }
|
showMapping -> { { MappingHost() } }
|
||||||
else -> null
|
else -> null
|
||||||
@@ -564,7 +567,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
steamGames = steamGames, emulators = emulatorList, running = runningLabel,
|
steamGames = steamGames, emulators = emulatorList, running = runningLabel,
|
||||||
frameGen = FrameGen.mode(this),
|
frameGen = FrameGen.mode(this),
|
||||||
lossless = lossless,
|
lossless = lossless,
|
||||||
pageKey = if (showPerformance) "performance" else if (showComponents) "components" else if (showMapping) "controller-mapping" else null,
|
pageKey = sm?.let { "settings:$it" } ?: if (showPerformance) "performance" else if (showProtons) "protons" else if (showComponents) "components" else if (showMapping) "controller-mapping" else null,
|
||||||
theme = theme,
|
theme = theme,
|
||||||
language = com.droiddeck.launcher.core.AppLanguage.chosen(this),
|
language = com.droiddeck.launcher.core.AppLanguage.chosen(this),
|
||||||
appScale = appScale,
|
appScale = appScale,
|
||||||
@@ -586,9 +589,9 @@ class MainActivity : ComponentActivity() {
|
|||||||
updates = updates.state(),
|
updates = updates.state(),
|
||||||
phantomProcessStatus = phantomProcessStatus,
|
phantomProcessStatus = phantomProcessStatus,
|
||||||
showPhantomGate = showPhantomGate,
|
showPhantomGate = showPhantomGate,
|
||||||
orientation = orientation,
|
|
||||||
launcherFullscreen = launcherFullscreen,
|
launcherFullscreen = launcherFullscreen,
|
||||||
animationsEnabled = animationsEnabled,
|
animationsEnabled = animationsEnabled,
|
||||||
|
storeEnabled = storeEnabled,
|
||||||
gameStoresEnabled = gameStoresEnabled,
|
gameStoresEnabled = gameStoresEnabled,
|
||||||
gameStoresSpeedTier = gameStoresSpeedTier,
|
gameStoresSpeedTier = gameStoresSpeedTier,
|
||||||
storesOpenTab = storesOpenTab,
|
storesOpenTab = storesOpenTab,
|
||||||
@@ -607,15 +610,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
.putExtra(SessionService.EXTRA_STEAM_UI, "desktop"), steamSession = true)
|
.putExtra(SessionService.EXTRA_STEAM_UI, "desktop"), steamSession = true)
|
||||||
},
|
},
|
||||||
// A store game may need something done first (an Epic game its sign-in code).
|
// A store game may need something done first (an Epic game its sign-in code).
|
||||||
onSteamGame = { g ->
|
onSteamGame = { g -> if (shortcutPicker) chooseGameShortcut(g) else com.droiddeck.launcher.stores.StoreLaunch.prepare(this, g) { launchGame(g) } },
|
||||||
if (shortcutPicker) chooseGameShortcut(g)
|
|
||||||
else {
|
|
||||||
// The launch takes the Windows components already on; the game's list is
|
|
||||||
// looked at again in the background once the session is over.
|
|
||||||
com.droiddeck.launcher.frontend.AutoComponents.beforeLaunch(this, g)
|
|
||||||
com.droiddeck.launcher.stores.StoreLaunch.prepare(this, g) { launchGame(g) }
|
|
||||||
}
|
|
||||||
},
|
|
||||||
onGameShortcut = { g -> com.droiddeck.launcher.frontend.GameShortcuts.pin(this, g) },
|
onGameShortcut = { g -> com.droiddeck.launcher.frontend.GameShortcuts.pin(this, g) },
|
||||||
onExportGameFile = { g -> pickGameExport(g) },
|
onExportGameFile = { g -> pickGameExport(g) },
|
||||||
onSyncGameFiles = { pickGameExport(null) },
|
onSyncGameFiles = { pickGameExport(null) },
|
||||||
@@ -674,10 +669,9 @@ class MainActivity : ComponentActivity() {
|
|||||||
},
|
},
|
||||||
// The activity re-attaches to the session that is running; nothing restarts.
|
// The activity re-attaches to the session that is running; nothing restarts.
|
||||||
onResume = { startActivity(Intent(this, SessionActivity::class.java)) },
|
onResume = { startActivity(Intent(this, SessionActivity::class.java)) },
|
||||||
onSteamSettings = { loadModeSettings(SessionService.MODE_STEAM) },
|
onSteamSettings = { openModeSettings(SessionService.MODE_STEAM) },
|
||||||
onRemoveDesktop = { removeDesktop() },
|
onRemoveDesktop = { removeDesktop() },
|
||||||
onDesktopSettings = { loadModeSettings(SessionService.MODE_DESKTOP) },
|
onDesktopSettings = { openModeSettings(SessionService.MODE_DESKTOP) },
|
||||||
modeSheet = { mode, tab, extras -> ModeSheetHost(mode, tab, extras) },
|
|
||||||
onInstallPackage = { id -> installPackage(id) },
|
onInstallPackage = { id -> installPackage(id) },
|
||||||
onRemovePackage = { id -> removePackage(id) },
|
onRemovePackage = { id -> removePackage(id) },
|
||||||
onRuntime = { onRuntimeButton() },
|
onRuntime = { onRuntimeButton() },
|
||||||
@@ -690,11 +684,10 @@ class MainActivity : ComponentActivity() {
|
|||||||
},
|
},
|
||||||
onProtons = { openProtons() },
|
onProtons = { openProtons() },
|
||||||
onComponents = { focusContent -> openComponents(focusContent) },
|
onComponents = { focusContent -> openComponents(focusContent) },
|
||||||
onComponentsTab = { tab -> openComponents(focusContent = true, tab = tab) },
|
|
||||||
// A game page's Manage saves: the game's Proton and saves are read when the work runs, off the main thread.
|
// A game page's Manage saves: the game's Proton and saves are read when the work runs, off the main thread.
|
||||||
onSaveImport = { sg -> importSaves(sg.name) { GameSaves.game(sg) } },
|
onSaveImport = { sg -> importSaves(sg.name) { GameSaves.game(sg) } },
|
||||||
onSaveExport = { sg, layout -> exportSaves(sg.name, layout) { GameSaves.game(sg) } },
|
onSaveExport = { sg, layout -> exportSaves(sg.name, layout) { GameSaves.game(sg) } },
|
||||||
onPerformance = { refreshCores(); showComponents = false; showMapping = false; showPerformance = true },
|
onPerformance = { refreshCores(); showProtons = false; showComponents = false; showMapping = false; showPerformance = true },
|
||||||
onRoms = { showRoms = true },
|
onRoms = { showRoms = true },
|
||||||
onFiles = { startActivity(Intent(this, com.droiddeck.launcher.files.FileManagerActivity::class.java)) },
|
onFiles = { startActivity(Intent(this, com.droiddeck.launcher.files.FileManagerActivity::class.java)) },
|
||||||
onBrowseFiles = { dir ->
|
onBrowseFiles = { dir ->
|
||||||
@@ -729,8 +722,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
OfflineMode.setEnabled(this, !OfflineMode.enabled(this))
|
OfflineMode.setEnabled(this, !OfflineMode.enabled(this))
|
||||||
offline = OfflineMode.enabled(this)
|
offline = OfflineMode.enabled(this)
|
||||||
},
|
},
|
||||||
onPageBack = { showPerformance = false; showComponents = false; showMapping = false },
|
onPageBack = { settingsMode = null; showPerformance = false; showProtons = false; showComponents = false; showMapping = false },
|
||||||
onGameStoresEnabled = { on -> SessionPrefs.setGameStoresEnabled(this, on); gameStoresEnabled = on },
|
|
||||||
onTheme = { id -> SessionPrefs.setTheme(this, id); theme = id },
|
onTheme = { id -> SessionPrefs.setTheme(this, id); theme = id },
|
||||||
onLanguage = { tag ->
|
onLanguage = { tag ->
|
||||||
if (tag != com.droiddeck.launcher.core.AppLanguage.chosen(this)) {
|
if (tag != com.droiddeck.launcher.core.AppLanguage.chosen(this)) {
|
||||||
@@ -743,16 +735,13 @@ class MainActivity : ComponentActivity() {
|
|||||||
com.droiddeck.launcher.core.AppUiPrefs.setScale(this, percent)
|
com.droiddeck.launcher.core.AppUiPrefs.setScale(this, percent)
|
||||||
appScale = com.droiddeck.launcher.core.AppUiPrefs.scale(this)
|
appScale = com.droiddeck.launcher.core.AppUiPrefs.scale(this)
|
||||||
},
|
},
|
||||||
onOrientation = { value ->
|
|
||||||
SessionPrefs.setOrientation(this, value)
|
|
||||||
orientation = value
|
|
||||||
requestedOrientation = value
|
|
||||||
},
|
|
||||||
onLauncherFullscreen = { on ->
|
onLauncherFullscreen = { on ->
|
||||||
SessionPrefs.setLauncherFullscreen(this, on)
|
SessionPrefs.setLauncherFullscreen(this, on)
|
||||||
launcherFullscreen = on
|
launcherFullscreen = on
|
||||||
applyLauncherFullscreen()
|
applyLauncherFullscreen()
|
||||||
},
|
},
|
||||||
|
onStoreEnabled = { on -> SessionPrefs.setStoreEnabled(this, on); storeEnabled = on },
|
||||||
|
onGameStoresEnabled = { on -> SessionPrefs.setGameStoresEnabled(this, on); gameStoresEnabled = on; if (on) com.droiddeck.launcher.stores.StoresState.refresh(this) },
|
||||||
onGameStoresSpeedTier = { tier -> SessionPrefs.setGameStoresSpeedTier(this, tier); gameStoresSpeedTier = tier },
|
onGameStoresSpeedTier = { tier -> SessionPrefs.setGameStoresSpeedTier(this, tier); gameStoresSpeedTier = tier },
|
||||||
onStoresOpenTab = { tab -> SessionPrefs.setStoresOpenTab(this, tab); storesOpenTab = tab },
|
onStoresOpenTab = { tab -> SessionPrefs.setStoresOpenTab(this, tab); storesOpenTab = tab },
|
||||||
onNavigated = { navRequest = null },
|
onNavigated = { navRequest = null },
|
||||||
@@ -835,10 +824,9 @@ class MainActivity : ComponentActivity() {
|
|||||||
onSteamButton = { on -> ControllerPrefs.setSteamButton(this, on); refreshController() },
|
onSteamButton = { on -> ControllerPrefs.setSteamButton(this, on); refreshController() },
|
||||||
onQamButton = { on -> ControllerPrefs.setQamButton(this, on); refreshController() },
|
onQamButton = { on -> ControllerPrefs.setQamButton(this, on); refreshController() },
|
||||||
onKeyboardButton = { on -> ControllerPrefs.setKeyboardButton(this, on); refreshController() },
|
onKeyboardButton = { on -> ControllerPrefs.setKeyboardButton(this, on); refreshController() },
|
||||||
onSelectSteam = { on -> ControllerPrefs.setSelectSteam(this, on); refreshController() },
|
|
||||||
onEditLayout = { startActivity(Intent(this, ControllerEditorActivity::class.java)) },
|
onEditLayout = { startActivity(Intent(this, ControllerEditorActivity::class.java)) },
|
||||||
onResetLayout = { ControllerPrefs.resetAllLayouts(this); refreshController() },
|
onResetLayout = { ControllerPrefs.resetAllLayouts(this); refreshController() },
|
||||||
onMapping = { showPerformance = false; showComponents = false; showMapping = true },
|
onMapping = { settingsMode = null; showPerformance = false; showProtons = false; showComponents = false; showMapping = true },
|
||||||
onResetAll = { ControllerPrefs.resetAll(this); refreshController() },
|
onResetAll = { ControllerPrefs.resetAll(this); refreshController() },
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -905,7 +893,6 @@ class MainActivity : ComponentActivity() {
|
|||||||
// A session folder left without its ending - the process was killed - gets it now.
|
// A session folder left without its ending - the process was killed - gets it now.
|
||||||
if (!SessionState.running) Thread({
|
if (!SessionState.running) Thread({
|
||||||
com.droiddeck.launcher.session.LogMigration.run(this)
|
com.droiddeck.launcher.session.LogMigration.run(this)
|
||||||
com.droiddeck.launcher.frontend.GamesFolderMigration.run(this)
|
|
||||||
SessionLogShare.clear(this)
|
SessionLogShare.clear(this)
|
||||||
SessionArtifacts.finishAbandoned(this)
|
SessionArtifacts.finishAbandoned(this)
|
||||||
SessionArtifacts.scrubOlder(this)
|
SessionArtifacts.scrubOlder(this)
|
||||||
@@ -947,23 +934,16 @@ class MainActivity : ComponentActivity() {
|
|||||||
} else {
|
} else {
|
||||||
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
|
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
|
||||||
}
|
}
|
||||||
if (Build.VERSION.SDK_INT >= 28) {
|
|
||||||
window.attributes = window.attributes.apply {
|
|
||||||
layoutInDisplayCutoutMode = if (launcherFullscreen) {
|
|
||||||
WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
|
|
||||||
} else {
|
|
||||||
WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_DEFAULT
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** On the Components page the pad's LB / RB step through the stack's layers, wrapping around. */
|
/** On the Components page the pad's LB / RB step through GPU drivers, FEX, DXVK and VKD3D-Proton, wrapping around. */
|
||||||
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
|
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
|
||||||
if (event.keyCode == KeyEvent.KEYCODE_BUTTON_A) com.droiddeck.launcher.ui.HeldKeys.confirm = event.action == KeyEvent.ACTION_DOWN
|
if (event.keyCode == KeyEvent.KEYCODE_BUTTON_A) com.droiddeck.launcher.ui.HeldKeys.confirm = event.action == KeyEvent.ACTION_DOWN
|
||||||
if (showComponents && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) {
|
if (showComponents && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) {
|
||||||
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
|
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
|
||||||
components.compComp = com.droiddeck.launcher.ui.layerStep(components.compComp, if (event.keyCode == KeyEvent.KEYCODE_BUTTON_R1) 1 else -1)
|
val all = listOf(com.droiddeck.launcher.ui.GPU_TAB) + ComponentsManager.COMPONENTS
|
||||||
|
val step = if (event.keyCode == KeyEvent.KEYCODE_BUTTON_R1) 1 else all.size - 1
|
||||||
|
components.compComp = all[(all.indexOf(components.compComp).coerceAtLeast(0) + step) % all.size]
|
||||||
}
|
}
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
@@ -980,12 +960,10 @@ class MainActivity : ComponentActivity() {
|
|||||||
|
|
||||||
override fun onResume() {
|
override fun onResume() {
|
||||||
super.onResume()
|
super.onResume()
|
||||||
orientation = SessionPrefs.orientation(this)
|
|
||||||
requestedOrientation = orientation
|
|
||||||
refreshWifiDiscovery()
|
refreshWifiDiscovery()
|
||||||
// Back from a store's sign-in page: the Stores chips show the account at once. A store
|
// Back from a store's sign-in page: the Stores chips show the account at once. A store
|
||||||
// install finishing while this screen is up rebuilds the Games list through the listener.
|
// install finishing while this screen is up rebuilds the Games list through the listener.
|
||||||
com.droiddeck.launcher.stores.StoresState.refresh(this)
|
if (gameStoresEnabled) com.droiddeck.launcher.stores.StoresState.refresh(this)
|
||||||
com.droiddeck.launcher.stores.StoresState.libraryListener = { refreshAddedGames(); refresh() }
|
com.droiddeck.launcher.stores.StoresState.libraryListener = { refreshAddedGames(); refresh() }
|
||||||
com.droiddeck.launcher.ui.Motion.refresh(this)
|
com.droiddeck.launcher.ui.Motion.refresh(this)
|
||||||
// Back from a session stopped behind a flood: open on its blue, before the first frame.
|
// Back from a session stopped behind a flood: open on its blue, before the first frame.
|
||||||
@@ -998,8 +976,6 @@ class MainActivity : ComponentActivity() {
|
|||||||
updates.onResume()
|
updates.onResume()
|
||||||
// Auto keeps this GPU's recommended driver pair installed and set: once per app start.
|
// Auto keeps this GPU's recommended driver pair installed and set: once per app start.
|
||||||
drivers.ensureAuto(force = false)
|
drivers.ensureAuto(force = false)
|
||||||
// Newer GE-Proton / proton-cachyos / DroidDeck-Proton releases: looked up every few hours at most.
|
|
||||||
protons.checkUpdates()
|
|
||||||
// Swaps queued while a game ran on that Proton go in once nothing uses it (usually the
|
// Swaps queued while a game ran on that Proton go in once nothing uses it (usually the
|
||||||
// session has just ended). Cheap when nothing is queued.
|
// session has just ended). Cheap when nothing is queued.
|
||||||
if (!SessionState.running) Thread({
|
if (!SessionState.running) Thread({
|
||||||
@@ -1118,8 +1094,14 @@ class MainActivity : ComponentActivity() {
|
|||||||
}, "game-saves-action").start()
|
}, "game-saves-action").start()
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The Protons DroidDeck installs are the Components page's Proton layer. */
|
private fun openProtons() {
|
||||||
private fun openProtons() = openComponents(focusContent = true, tab = com.droiddeck.launcher.ui.PROTON_TAB)
|
settingsMode = null
|
||||||
|
showPerformance = false
|
||||||
|
showComponents = false
|
||||||
|
showMapping = false
|
||||||
|
showProtons = true
|
||||||
|
protons.refreshProtons()
|
||||||
|
}
|
||||||
|
|
||||||
private fun refreshController() {
|
private fun refreshController() {
|
||||||
controllerSettings = ControllerPrefs.read(this)
|
controllerSettings = ControllerPrefs.read(this)
|
||||||
@@ -1139,19 +1121,13 @@ class MainActivity : ComponentActivity() {
|
|||||||
private fun openComponents(focusContent: Boolean = true, tab: String? = null) {
|
private fun openComponents(focusContent: Boolean = true, tab: String? = null) {
|
||||||
focusComponentsContent = focusContent
|
focusComponentsContent = focusContent
|
||||||
if (tab != null) components.compComp = tab
|
if (tab != null) components.compComp = tab
|
||||||
|
settingsMode = null
|
||||||
showPerformance = false
|
showPerformance = false
|
||||||
|
showProtons = false
|
||||||
showMapping = false
|
showMapping = false
|
||||||
showComponents = true
|
showComponents = true
|
||||||
// The Proton layer's options for every Proton, as they are now.
|
|
||||||
fexPreset = SessionPrefs.fexPreset(this)
|
|
||||||
forceSsbs = SessionPrefs.forceSsbs(this)
|
|
||||||
fastSync = SessionPrefs.fastSync(this)
|
|
||||||
fsyncFirst = SessionPrefs.fsyncFirst(this)
|
|
||||||
syncFallback = SessionPrefs.syncFallback(this)
|
|
||||||
components.refreshComponents(snapshotFirst = true)
|
components.refreshComponents(snapshotFirst = true)
|
||||||
drivers.refreshDrivers()
|
drivers.refreshDrivers()
|
||||||
protons.refreshProtons()
|
|
||||||
protons.checkUpdates()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun importComponent(uri: Uri) {
|
private fun importComponent(uri: Uri) {
|
||||||
@@ -1185,11 +1161,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
onDownload = { components.downloadComponent(it) },
|
onDownload = { components.downloadComponent(it) },
|
||||||
onRefresh = { components.refreshComponentCatalog() },
|
onRefresh = { components.refreshComponentCatalog() },
|
||||||
onImport = { pickComponent.launch(InAppFilePicker.buildIntent(this, WCP_EXT, getString(R.string.comp_pick_wcp))) },
|
onImport = { pickComponent.launch(InAppFilePicker.buildIntent(this, WCP_EXT, getString(R.string.comp_pick_wcp))) },
|
||||||
// Reached by a hop (a game's Components card, Play's Graphics drivers): back the way it came.
|
onBack = { showComponents = false },
|
||||||
onBack = { if (!com.droiddeck.launcher.ui.Hops.back { showComponents = false }) showComponents = false },
|
|
||||||
games = steamGames,
|
|
||||||
generalFexPreset = fexPreset,
|
|
||||||
onGeneralFexPreset = { id -> SessionPrefs.setFexPreset(this, id); fexPreset = id },
|
|
||||||
gpu = drivers.state(),
|
gpu = drivers.state(),
|
||||||
gpuActions = com.droiddeck.launcher.ui.GpuDriversActions(
|
gpuActions = com.droiddeck.launcher.ui.GpuDriversActions(
|
||||||
onAuto = { on -> drivers.setMode(on) },
|
onAuto = { on -> drivers.setMode(on) },
|
||||||
@@ -1206,32 +1178,23 @@ class MainActivity : ComponentActivity() {
|
|||||||
onImportZip = { pickAnyDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, getString(R.string.drivers_pick_any))) },
|
onImportZip = { pickAnyDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, getString(R.string.drivers_pick_any))) },
|
||||||
onRestoreBundled = { TurnipDriver(this).restoreBundled(); drivers.refreshDrivers() },
|
onRestoreBundled = { TurnipDriver(this).restoreBundled(); drivers.refreshDrivers() },
|
||||||
),
|
),
|
||||||
protons = com.droiddeck.launcher.ui.ProtonsState(
|
|
||||||
rows = protons.protonRows, busyId = protons.protonBusyId, stage = protons.protonStage, percent = protons.protonPercent,
|
|
||||||
runtimeReady = ready && !busy, sessionRunning = SessionState.running,
|
|
||||||
),
|
|
||||||
protonActions = com.droiddeck.launcher.ui.ProtonsActions(
|
|
||||||
onInstall = { id -> protons.installProton(id) },
|
|
||||||
onCancel = { id -> ProtonExtras.tools.firstOrNull { it.id == id }?.let { ProtonExtras.unqueue(this, it) }; protons.refreshProtons() },
|
|
||||||
onRemove = { id, dir -> protons.removeProton(id, dir) },
|
|
||||||
onRemoveOlder = { id -> protons.removeProton(id, older = true) },
|
|
||||||
),
|
|
||||||
protonOptions = {
|
|
||||||
com.droiddeck.launcher.ui.ProtonOptions(
|
|
||||||
syncBackend = SessionPrefs.syncBackendOf(fastSync, fsyncFirst, syncFallback), fexPreset = fexPreset, forceSsbs = forceSsbs,
|
|
||||||
onSyncBackend = { id ->
|
|
||||||
SessionPrefs.setSyncBackend(this, id)
|
|
||||||
fastSync = SessionPrefs.fastSync(this)
|
|
||||||
fsyncFirst = SessionPrefs.fsyncFirst(this)
|
|
||||||
syncFallback = SessionPrefs.syncFallback(this)
|
|
||||||
},
|
|
||||||
onFexPreset = { id -> SessionPrefs.setFexPreset(this, id); fexPreset = id },
|
|
||||||
onForceSsbs = { on -> SessionPrefs.setForceSsbs(this, on); forceSsbs = on },
|
|
||||||
)
|
|
||||||
},
|
|
||||||
)
|
)
|
||||||
// A Proton installed or removed changes the stack's list of Protons.
|
}
|
||||||
androidx.compose.runtime.LaunchedEffect(protons.protonBusyId) { if (protons.protonBusyId == null) components.refreshComponents() }
|
|
||||||
|
@Composable
|
||||||
|
private fun ProtonHost() {
|
||||||
|
ProtonPage(
|
||||||
|
rows = protons.protonRows,
|
||||||
|
busyId = protons.protonBusyId,
|
||||||
|
stage = protons.protonStage,
|
||||||
|
percent = protons.protonPercent,
|
||||||
|
runtimeReady = ready && !busy,
|
||||||
|
sessionRunning = SessionState.running,
|
||||||
|
onInstall = { id -> protons.installProton(id) },
|
||||||
|
onCancel = { id -> ProtonExtras.tools.firstOrNull { it.id == id }?.let { ProtonExtras.unqueue(this, it) }; protons.refreshProtons() },
|
||||||
|
onRemove = { id -> protons.removeProton(id) },
|
||||||
|
onBack = { showProtons = false },
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun refreshPackages() {
|
private fun refreshPackages() {
|
||||||
@@ -1278,10 +1241,8 @@ class MainActivity : ComponentActivity() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
private fun ModeSheetHost(mode: String, tab: String, extras: com.droiddeck.launcher.ui.SheetExtras) {
|
private fun ModeSettingsHost(mode: String) {
|
||||||
// Read for the other mode last (or not yet): what this one shows is read as it opens.
|
ModeSettingsPage(
|
||||||
if (settingsMode != mode) return
|
|
||||||
com.droiddeck.launcher.ui.ModeSheetRows(
|
|
||||||
ModeSettings(
|
ModeSettings(
|
||||||
mode = mode, resolution = resolution,
|
mode = mode, resolution = resolution,
|
||||||
panelSize = com.droiddeck.launcher.session.SessionDisplay.panelSize(this),
|
panelSize = com.droiddeck.launcher.session.SessionDisplay.panelSize(this),
|
||||||
@@ -1293,8 +1254,6 @@ class MainActivity : ComponentActivity() {
|
|||||||
steamDownloadsInBackground = steamDownloadsInBackground,
|
steamDownloadsInBackground = steamDownloadsInBackground,
|
||||||
pipSupported = com.droiddeck.launcher.session.SessionPipController.supported(this),
|
pipSupported = com.droiddeck.launcher.session.SessionPipController.supported(this),
|
||||||
pipAutoEnter = pipAutoEnter,
|
pipAutoEnter = pipAutoEnter,
|
||||||
unfoldedControls = if (mode == SessionService.MODE_STEAM &&
|
|
||||||
com.droiddeck.launcher.session.SessionDisplay.foldable(this)) unfoldedControls else null,
|
|
||||||
oscMode = if (mode == SessionService.MODE_STEAM) oscMode else null,
|
oscMode = if (mode == SessionService.MODE_STEAM) oscMode else null,
|
||||||
backActionsInverted = backActionsInverted,
|
backActionsInverted = backActionsInverted,
|
||||||
directAudio = if (mode == SessionService.MODE_STEAM) directAudio else null,
|
directAudio = if (mode == SessionService.MODE_STEAM) directAudio else null,
|
||||||
@@ -1306,6 +1265,8 @@ class MainActivity : ComponentActivity() {
|
|||||||
fexPreset = if (mode == SessionService.MODE_STEAM) fexPreset else null,
|
fexPreset = if (mode == SessionService.MODE_STEAM) fexPreset else null,
|
||||||
forceSsbs = forceSsbs,
|
forceSsbs = forceSsbs,
|
||||||
syncBackend = if (mode == SessionService.MODE_STEAM) SessionPrefs.syncBackendOf(fastSync, fsyncFirst, syncFallback) else null,
|
syncBackend = if (mode == SessionService.MODE_STEAM) SessionPrefs.syncBackendOf(fastSync, fsyncFirst, syncFallback) else null,
|
||||||
|
steamChannel = if (mode == SessionService.MODE_STEAM) steamChannel else null,
|
||||||
|
steamDeckMode = mode == SessionService.MODE_STEAM && steamDeckMode,
|
||||||
steamRepairQueued = steamRepairQueued,
|
steamRepairQueued = steamRepairQueued,
|
||||||
mangoapp = mangoapp,
|
mangoapp = mangoapp,
|
||||||
steamController = if (mode == SessionService.MODE_STEAM) steamController else null,
|
steamController = if (mode == SessionService.MODE_STEAM) steamController else null,
|
||||||
@@ -1350,7 +1311,6 @@ class MainActivity : ComponentActivity() {
|
|||||||
steamDownloadsInBackground = enabled
|
steamDownloadsInBackground = enabled
|
||||||
},
|
},
|
||||||
onPipAutoEnter = { on -> SessionPrefs.setPipAutoEnter(this, on); pipAutoEnter = on },
|
onPipAutoEnter = { on -> SessionPrefs.setPipAutoEnter(this, on); pipAutoEnter = on },
|
||||||
onUnfoldedControls = { on -> SessionPrefs.setUnfoldedControls(this, on); unfoldedControls = on },
|
|
||||||
onOsc = { o -> SessionPrefs.setOscMode(this, o); oscMode = o },
|
onOsc = { o -> SessionPrefs.setOscMode(this, o); oscMode = o },
|
||||||
onBackActionsInverted = { inverted ->
|
onBackActionsInverted = { inverted ->
|
||||||
SessionPrefs.setBackActionsInverted(this, inverted)
|
SessionPrefs.setBackActionsInverted(this, inverted)
|
||||||
@@ -1383,7 +1343,13 @@ class MainActivity : ComponentActivity() {
|
|||||||
fsyncFirst = SessionPrefs.fsyncFirst(this)
|
fsyncFirst = SessionPrefs.fsyncFirst(this)
|
||||||
syncFallback = SessionPrefs.syncFallback(this)
|
syncFallback = SessionPrefs.syncFallback(this)
|
||||||
},
|
},
|
||||||
|
onSteamChannel = { id -> SessionPrefs.setSteamChannel(this, id); steamChannel = id },
|
||||||
onSteamRepair = { steamRepairQueued = SteamRepair.queue(this) },
|
onSteamRepair = { steamRepairQueued = SteamRepair.queue(this) },
|
||||||
|
onSteamDeckMode = { on ->
|
||||||
|
SessionPrefs.setSteamDeckMode(this, on)
|
||||||
|
steamDeckMode = on
|
||||||
|
steamChannel = SessionPrefs.steamChannel(this)
|
||||||
|
},
|
||||||
onMangoapp = { on -> SessionPrefs.setMangoapp(this, on); mangoapp = on },
|
onMangoapp = { on -> SessionPrefs.setMangoapp(this, on); mangoapp = on },
|
||||||
onSteamController = { id -> SessionPrefs.setSteamController(this, id); steamController = id },
|
onSteamController = { id -> SessionPrefs.setSteamController(this, id); steamController = id },
|
||||||
onRunSteamAtStartup = { on ->
|
onRunSteamAtStartup = { on ->
|
||||||
@@ -1401,9 +1367,8 @@ class MainActivity : ComponentActivity() {
|
|||||||
onPickDeckyPluginZip = {
|
onPickDeckyPluginZip = {
|
||||||
pickDeckyPluginZip.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, getString(R.string.main_pick_decky_zip)))
|
pickDeckyPluginZip.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, getString(R.string.main_pick_decky_zip)))
|
||||||
},
|
},
|
||||||
onDismiss = {},
|
onDismiss = { settingsMode = null },
|
||||||
),
|
),
|
||||||
tab, extras,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1455,8 +1420,6 @@ class MainActivity : ComponentActivity() {
|
|||||||
val fresh = folders.mapNotNull { f ->
|
val fresh = folders.mapNotNull { f ->
|
||||||
com.droiddeck.launcher.frontend.AddedGames.single(this, f)?.let { com.droiddeck.launcher.frontend.Library.addedGame(this, it) }
|
com.droiddeck.launcher.frontend.AddedGames.single(this, f)?.let { com.droiddeck.launcher.frontend.Library.addedGame(this, it) }
|
||||||
}
|
}
|
||||||
// An added or edited game's Windows components, from its source's list.
|
|
||||||
fresh.forEach { com.droiddeck.launcher.frontend.AutoComponents.refreshLater(this, it) }
|
|
||||||
ui.post {
|
ui.post {
|
||||||
val paths = folders.toSet()
|
val paths = folders.toSet()
|
||||||
steamGames = (steamGames.filterNot { it.library == Library.ADDED && it.gameFiles?.path in paths } + fresh).distinctBy { it.gameId }
|
steamGames = (steamGames.filterNot { it.library == Library.ADDED && it.gameFiles?.path in paths } + fresh).distinctBy { it.gameId }
|
||||||
@@ -1502,17 +1465,21 @@ class MainActivity : ComponentActivity() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private var pipAutoEnter by mutableStateOf(false)
|
private var pipAutoEnter by mutableStateOf(false)
|
||||||
private var unfoldedControls by mutableStateOf(false)
|
|
||||||
|
|
||||||
private fun loadModeSettings(mode: String) {
|
private fun openModeSettings(mode: String) {
|
||||||
pipAutoEnter = SessionPrefs.pipAutoEnter(this)
|
pipAutoEnter = SessionPrefs.pipAutoEnter(this)
|
||||||
unfoldedControls = SessionPrefs.unfoldedControls(this)
|
showPerformance = false
|
||||||
|
showProtons = false
|
||||||
|
showComponents = false
|
||||||
|
showMapping = false
|
||||||
resolution = SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this))
|
resolution = SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this))
|
||||||
fexPreset = SessionPrefs.fexPreset(this)
|
fexPreset = SessionPrefs.fexPreset(this)
|
||||||
forceSsbs = SessionPrefs.forceSsbs(this)
|
forceSsbs = SessionPrefs.forceSsbs(this)
|
||||||
fastSync = SessionPrefs.fastSync(this)
|
fastSync = SessionPrefs.fastSync(this)
|
||||||
fsyncFirst = SessionPrefs.fsyncFirst(this)
|
fsyncFirst = SessionPrefs.fsyncFirst(this)
|
||||||
syncFallback = SessionPrefs.syncFallback(this)
|
syncFallback = SessionPrefs.syncFallback(this)
|
||||||
|
steamChannel = SessionPrefs.steamChannel(this)
|
||||||
|
steamDeckMode = SessionPrefs.steamDeckMode(this)
|
||||||
steamRepairQueued = SteamRepair.queued(this)
|
steamRepairQueued = SteamRepair.queued(this)
|
||||||
mangoapp = SessionPrefs.mangoapp(this)
|
mangoapp = SessionPrefs.mangoapp(this)
|
||||||
steamController = SessionPrefs.steamController(this)
|
steamController = SessionPrefs.steamController(this)
|
||||||
@@ -1534,8 +1501,8 @@ class MainActivity : ComponentActivity() {
|
|||||||
gameStorage = SessionPrefs.gameStorage(this)
|
gameStorage = SessionPrefs.gameStorage(this)
|
||||||
storageDiagnostics = SessionPrefs.storageDiagnosticsEnabled(this)
|
storageDiagnostics = SessionPrefs.storageDiagnosticsEnabled(this)
|
||||||
settingsMode = mode
|
settingsMode = mode
|
||||||
// The sheet lifts at once, on what was last read; the slow part (driver files, a walk of the
|
// The page opens at once, on what was last read; the slow part (driver files, a walk of the
|
||||||
// added-games folders, the storage volumes) lands while it rises.
|
// added-games folders, the storage volumes) lands while it animates in.
|
||||||
Thread({
|
Thread({
|
||||||
drivers.refreshDrivers()
|
drivers.refreshDrivers()
|
||||||
val storage = GameStorage.options(this)
|
val storage = GameStorage.options(this)
|
||||||
@@ -1571,6 +1538,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
clientOverride = SessionPrefs.clientCpusOverride(this)
|
clientOverride = SessionPrefs.clientCpusOverride(this)
|
||||||
glThread = SessionPrefs.glThread(this)
|
glThread = SessionPrefs.glThread(this)
|
||||||
noGlError = SessionPrefs.noGlError(this)
|
noGlError = SessionPrefs.noGlError(this)
|
||||||
|
steamDeckMode = SessionPrefs.steamDeckMode(this)
|
||||||
clientCores = CpuCores.parse(SessionPrefs.clientCpus(this)).ifEmpty { CpuCores.all.toSet() }
|
clientCores = CpuCores.parse(SessionPrefs.clientCpus(this)).ifEmpty { CpuCores.all.toSet() }
|
||||||
gameCores = CpuCores.parse(SessionPrefs.gameCpus(this)).ifEmpty { CpuCores.all.toSet() }
|
gameCores = CpuCores.parse(SessionPrefs.gameCpus(this)).ifEmpty { CpuCores.all.toSet() }
|
||||||
tuSysmem = SessionPrefs.tuSysmem(this)
|
tuSysmem = SessionPrefs.tuSysmem(this)
|
||||||
@@ -1611,44 +1579,17 @@ class MainActivity : ComponentActivity() {
|
|||||||
val scanGeneration = ++libraryScanGeneration
|
val scanGeneration = ++libraryScanGeneration
|
||||||
if (shortcutPicker) shortcutLibraryScanning = true
|
if (shortcutPicker) shortcutLibraryScanning = true
|
||||||
Thread({
|
Thread({
|
||||||
// The emulators first: they need no walk of the games, and Desktop's dock is made of them.
|
// One update with the whole list: the wall places games by their position in it, so a
|
||||||
val emus = Library.emulators(this) { id -> DesktopCatalog.installed(this, id) != null }
|
// partial list first would shuffle every capsule when the rest arrived. LibraryCache
|
||||||
ui.post { if (scanGeneration == libraryScanGeneration) emulatorList = emus }
|
// covers the wait.
|
||||||
// Steam's own games next, from their manifests alone (quick), beside the added games
|
|
||||||
// already listed: a game Steam installed during the session shows as the session ends,
|
|
||||||
// without waiting for the added games' walk below. Its Windows components' list is
|
|
||||||
// queued then too, on the low-priority worker, so its page is usually ready.
|
|
||||||
if (ready) {
|
|
||||||
val quick = runCatching { Library.steamGames(this) }.getOrNull()
|
|
||||||
if (quick != null) ui.post {
|
|
||||||
if (scanGeneration == libraryScanGeneration && steamGames.isNotEmpty()) {
|
|
||||||
val before = steamGames.map { it.gameId }.toSet()
|
|
||||||
val fresh = quick.filter { it.gameId !in before }
|
|
||||||
if (fresh.isNotEmpty()) {
|
|
||||||
steamGames = (quick + steamGames.filter { it.library == Library.ADDED }).distinctBy { it.gameId }
|
|
||||||
fresh.forEach { com.droiddeck.launcher.frontend.AutoComponents.queueGame(this, it, asked = false) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Then one update with the whole list: the wall places games by their position in it,
|
|
||||||
// so a partial list first would shuffle every capsule when the rest arrived.
|
|
||||||
// LibraryCache covers the wait.
|
|
||||||
val games = if (ready) Library.launchableGames(this) else emptyList()
|
val games = if (ready) Library.launchableGames(this) else emptyList()
|
||||||
|
val emus = Library.emulators(this) { id -> DesktopCatalog.installed(this, id) != null }
|
||||||
val all = games.distinctBy { it.gameId }
|
val all = games.distinctBy { it.gameId }
|
||||||
if (ready) com.droiddeck.launcher.frontend.LibraryCache.save(this, all)
|
if (ready) com.droiddeck.launcher.frontend.LibraryCache.save(this, all)
|
||||||
// Once per app start: the Steam games' Windows components from Steam's lists.
|
|
||||||
// Queued only, after the launcher has been up a little; the worker takes them one at a time.
|
|
||||||
// And again after each session (a game installed in it, files changed).
|
|
||||||
val endedSession = SessionState.sessionId.takeIf { !SessionState.running && it != null && it != componentSweepSession }
|
|
||||||
if (ready && (!componentSweepDone || endedSession != null)) {
|
|
||||||
componentSweepDone = true
|
|
||||||
endedSession?.let { componentSweepSession = it }
|
|
||||||
ui.postDelayed({ Thread({ com.droiddeck.launcher.frontend.AutoComponents.sweep(this, all) }, "components-sweep").start() }, 10_000)
|
|
||||||
}
|
|
||||||
ui.post {
|
ui.post {
|
||||||
if (scanGeneration == libraryScanGeneration) {
|
if (scanGeneration == libraryScanGeneration) {
|
||||||
steamGames = all
|
steamGames = all
|
||||||
|
emulatorList = emus
|
||||||
shortcutLibraryScanning = false
|
shortcutLibraryScanning = false
|
||||||
handleGameLink(all)
|
handleGameLink(all)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,16 +10,14 @@ import com.droiddeck.launcher.ui.ProtonRow
|
|||||||
import com.droiddeck.launcher.session.SessionState
|
import com.droiddeck.launcher.session.SessionState
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The optional ARM64 Protons (GE-Proton, proton-cachyos, DroidDeck-Proton): the rows the page lists,
|
* The optional ARM64 Protons (GE-Proton, proton-cachyos): the rows the page lists and an install or
|
||||||
* an install or removal in progress, and whether a newer release is out. The launcher screen keeps
|
* removal in progress. The launcher screen keeps one and shows it.
|
||||||
* one and shows it.
|
|
||||||
*/
|
*/
|
||||||
internal class ProtonMenu(private val activity: android.app.Activity, private val ui: android.os.Handler) {
|
internal class ProtonMenu(private val activity: android.app.Activity, private val ui: android.os.Handler) {
|
||||||
var protonRows by mutableStateOf<List<ProtonRow>>(emptyList())
|
var protonRows by mutableStateOf<List<ProtonRow>>(emptyList())
|
||||||
var protonBusyId by mutableStateOf<String?>(null)
|
var protonBusyId by mutableStateOf<String?>(null)
|
||||||
var protonStage by mutableStateOf<String?>(null)
|
var protonStage by mutableStateOf<String?>(null)
|
||||||
var protonPercent by mutableIntStateOf(-1)
|
var protonPercent by mutableIntStateOf(-1)
|
||||||
private val checking = java.util.concurrent.atomic.AtomicBoolean(false)
|
|
||||||
|
|
||||||
fun installProton(id: String) {
|
fun installProton(id: String) {
|
||||||
val tool = ProtonExtras.tools.firstOrNull { it.id == id } ?: return
|
val tool = ProtonExtras.tools.firstOrNull { it.id == id } ?: return
|
||||||
@@ -42,15 +40,14 @@ internal class ProtonMenu(private val activity: android.app.Activity, private va
|
|||||||
}, "install-proton-$id").start()
|
}, "install-proton-$id").start()
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Removes the build in [dir], or with [older] every build of it but the newest. */
|
fun removeProton(id: String) {
|
||||||
fun removeProton(id: String, dir: String? = null, older: Boolean = false) {
|
|
||||||
val tool = ProtonExtras.tools.firstOrNull { it.id == id } ?: return
|
val tool = ProtonExtras.tools.firstOrNull { it.id == id } ?: return
|
||||||
if (protonBusyId != null || SessionState.running) return
|
if (protonBusyId != null || SessionState.running) return
|
||||||
protonBusyId = id
|
protonBusyId = id
|
||||||
protonStage = activity.getString(R.string.main_removing_named, dir ?: tool.name)
|
protonStage = activity.getString(R.string.main_removing_named, tool.name)
|
||||||
protonPercent = -1
|
protonPercent = -1
|
||||||
Thread({
|
Thread({
|
||||||
if (older) ProtonExtras.removeOlder(activity, tool) else ProtonExtras.remove(activity, tool, dir)
|
ProtonExtras.remove(activity, tool)
|
||||||
ui.post {
|
ui.post {
|
||||||
protonBusyId = null
|
protonBusyId = null
|
||||||
protonStage = null
|
protonStage = null
|
||||||
@@ -60,18 +57,6 @@ internal class ProtonMenu(private val activity: android.app.Activity, private va
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun refreshProtons() {
|
fun refreshProtons() {
|
||||||
protonRows = ProtonExtras.tools.map {
|
protonRows = ProtonExtras.tools.map { ProtonRow(it.id, it.name, ProtonExtras.installed(activity, it), ProtonExtras.queued(activity, it)) }
|
||||||
val all = ProtonExtras.installedAll(activity, it)
|
|
||||||
ProtonRow(it.id, it.name, all.lastOrNull(), ProtonExtras.queued(activity, it), all, ProtonExtras.update(activity, it))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Looks for newer releases, at most every few hours (see ProtonExtras.checkLatest); quiet offline. */
|
|
||||||
fun checkUpdates(force: Boolean = false) {
|
|
||||||
if (!checking.compareAndSet(false, true)) return
|
|
||||||
Thread({
|
|
||||||
val asked = try { ProtonExtras.checkLatest(activity, force) } catch (_: Throwable) { false } finally { checking.set(false) }
|
|
||||||
if (asked) ui.post { refreshProtons() }
|
|
||||||
}, "proton-updates").start()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -19,7 +19,6 @@ import android.view.MotionEvent
|
|||||||
import android.view.ViewConfiguration
|
import android.view.ViewConfiguration
|
||||||
import android.view.Display
|
import android.view.Display
|
||||||
import android.view.SurfaceHolder
|
import android.view.SurfaceHolder
|
||||||
import android.view.Gravity
|
|
||||||
import android.view.SurfaceView
|
import android.view.SurfaceView
|
||||||
import android.view.View
|
import android.view.View
|
||||||
import android.view.WindowManager
|
import android.view.WindowManager
|
||||||
@@ -40,7 +39,6 @@ import com.droiddeck.launcher.core.FileUtils
|
|||||||
import com.droiddeck.launcher.core.TextureFiltering
|
import com.droiddeck.launcher.core.TextureFiltering
|
||||||
import com.droiddeck.launcher.files.InAppFilePicker
|
import com.droiddeck.launcher.files.InAppFilePicker
|
||||||
import com.droiddeck.launcher.frontend.Library
|
import com.droiddeck.launcher.frontend.Library
|
||||||
import com.droiddeck.launcher.agent.AgentGuest
|
|
||||||
import com.droiddeck.launcher.gpu.FrameGen
|
import com.droiddeck.launcher.gpu.FrameGen
|
||||||
import com.droiddeck.launcher.gpu.ScreenEffectLooks
|
import com.droiddeck.launcher.gpu.ScreenEffectLooks
|
||||||
import com.droiddeck.launcher.gpu.ScreenEffects
|
import com.droiddeck.launcher.gpu.ScreenEffects
|
||||||
@@ -53,7 +51,6 @@ import com.droiddeck.launcher.input.ControllerPrefs
|
|||||||
import com.droiddeck.launcher.input.SessionClipboard
|
import com.droiddeck.launcher.input.SessionClipboard
|
||||||
import com.droiddeck.launcher.input.OnScreenControls
|
import com.droiddeck.launcher.input.OnScreenControls
|
||||||
import com.droiddeck.launcher.input.PadBridge
|
import com.droiddeck.launcher.input.PadBridge
|
||||||
import com.droiddeck.launcher.input.SteamControllerBle
|
|
||||||
import com.droiddeck.launcher.input.PointerGestures
|
import com.droiddeck.launcher.input.PointerGestures
|
||||||
import com.droiddeck.launcher.input.SecondScreenDisplay
|
import com.droiddeck.launcher.input.SecondScreenDisplay
|
||||||
import com.droiddeck.launcher.input.SecondScreenDisplays
|
import com.droiddeck.launcher.input.SecondScreenDisplays
|
||||||
@@ -65,9 +62,6 @@ import com.droiddeck.launcher.session.PerfHud
|
|||||||
import com.droiddeck.launcher.session.PerfMode
|
import com.droiddeck.launcher.session.PerfMode
|
||||||
import com.droiddeck.launcher.session.SteamRepair
|
import com.droiddeck.launcher.session.SteamRepair
|
||||||
import com.droiddeck.launcher.session.GameEnvironmentStore
|
import com.droiddeck.launcher.session.GameEnvironmentStore
|
||||||
import com.droiddeck.launcher.session.GameProfileFollowState
|
|
||||||
import com.droiddeck.launcher.session.GameProfileInventoryCache
|
|
||||||
import com.droiddeck.launcher.session.GameProfileRefreshState
|
|
||||||
import com.droiddeck.launcher.session.SessionPrefs
|
import com.droiddeck.launcher.session.SessionPrefs
|
||||||
import com.droiddeck.launcher.session.SessionEvents
|
import com.droiddeck.launcher.session.SessionEvents
|
||||||
import com.droiddeck.launcher.session.SessionArtifacts
|
import com.droiddeck.launcher.session.SessionArtifacts
|
||||||
@@ -77,9 +71,6 @@ import com.droiddeck.launcher.session.SessionPaths
|
|||||||
import com.droiddeck.launcher.wayland.HdrSupport
|
import com.droiddeck.launcher.wayland.HdrSupport
|
||||||
import com.droiddeck.launcher.session.SessionService
|
import com.droiddeck.launcher.session.SessionService
|
||||||
import com.droiddeck.launcher.session.SessionState
|
import com.droiddeck.launcher.session.SessionState
|
||||||
import com.droiddeck.launcher.session.ProtonDefault
|
|
||||||
import com.droiddeck.launcher.session.SelectedGameProfile
|
|
||||||
import com.droiddeck.launcher.session.WinComponents
|
|
||||||
import com.droiddeck.launcher.ui.CursorOverlay
|
import com.droiddeck.launcher.ui.CursorOverlay
|
||||||
import androidx.compose.ui.graphics.asImageBitmap
|
import androidx.compose.ui.graphics.asImageBitmap
|
||||||
import com.droiddeck.launcher.ui.DrawerActions
|
import com.droiddeck.launcher.ui.DrawerActions
|
||||||
@@ -93,7 +84,6 @@ import com.droiddeck.launcher.wayland.CompositorHost
|
|||||||
import com.droiddeck.launcher.wayland.WaylandCompositor
|
import com.droiddeck.launcher.wayland.WaylandCompositor
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import com.droiddeck.launcher.session.ComponentsManager
|
import com.droiddeck.launcher.session.ComponentsManager
|
||||||
import com.droiddeck.launcher.session.LatestRequestCoordinator
|
|
||||||
import com.droiddeck.launcher.ui.SessionDrawerPage
|
import com.droiddeck.launcher.ui.SessionDrawerPage
|
||||||
import com.droiddeck.launcher.ui.sessionDrawerPages
|
import com.droiddeck.launcher.ui.sessionDrawerPages
|
||||||
import com.droiddeck.launcher.ui.step
|
import com.droiddeck.launcher.ui.step
|
||||||
@@ -119,10 +109,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
private lateinit var pip: com.droiddeck.launcher.session.SessionPipController
|
private lateinit var pip: com.droiddeck.launcher.session.SessionPipController
|
||||||
private var pipUi by mutableStateOf(false)
|
private var pipUi by mutableStateOf(false)
|
||||||
private var pipAutoEnter by mutableStateOf(false)
|
private var pipAutoEnter by mutableStateOf(false)
|
||||||
/** Unfolded controls: the setting, and the Deck controls under the game while they show. */
|
|
||||||
private var unfoldedControls by mutableStateOf(false)
|
|
||||||
private var unfoldedPanel: com.droiddeck.launcher.ui.DeckControlsPanel? = null
|
|
||||||
private lateinit var sessionRoot: FrameLayout
|
|
||||||
private val guestKeysDown = mutableSetOf<Int>()
|
private val guestKeysDown = mutableSetOf<Int>()
|
||||||
private lateinit var surfaceView: SurfaceView
|
private lateinit var surfaceView: SurfaceView
|
||||||
private lateinit var sessionOverlay: ComposeView
|
private lateinit var sessionOverlay: ComposeView
|
||||||
@@ -133,7 +119,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
private var padMotion: com.droiddeck.launcher.input.PadMotion? = null
|
private var padMotion: com.droiddeck.launcher.input.PadMotion? = null
|
||||||
/** Between onResume and onPause. */
|
/** Between onResume and onPause. */
|
||||||
private var resumed = false
|
private var resumed = false
|
||||||
private val deckPadListener: () -> Unit = { uiHandler.post { updatePadMotion(); openDeckRing("deck pad changed"); applyUnfoldedControls() } }
|
private val deckPadListener: () -> Unit = { uiHandler.post { updatePadMotion(); openDeckRing("deck pad changed") } }
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A Deck's controller is there from the moment it boots, and the client looks for it once, as
|
* A Deck's controller is there from the moment it boots, and the client looks for it once, as
|
||||||
@@ -156,11 +142,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
/** Motion is read while the session shows and only if the pad is a Deck controller - which
|
/** Motion is read while the session shows and only if the pad is a Deck controller - which
|
||||||
* the service can decide after this activity has resumed (SessionState.deckPadListener). */
|
* the service can decide after this activity has resumed (SessionState.deckPadListener). */
|
||||||
private fun updatePadMotion() {
|
private fun updatePadMotion() {
|
||||||
// A Steam Controller brings its own gyro (SteamControllerBle); the phone's would fight it.
|
if (resumed && !pipUi && SessionState.deckPad) padMotion?.start() else padMotion?.stop()
|
||||||
if (resumed && !pipUi && SessionState.deckPad && !SteamControllerBle.connected) padMotion?.start()
|
|
||||||
else padMotion?.stop()
|
|
||||||
}
|
}
|
||||||
private var steamController: SteamControllerBle? = null
|
|
||||||
private var onScreenControls: OnScreenControls? = null
|
private var onScreenControls: OnScreenControls? = null
|
||||||
/** Steam's touch controls (SteamTouchControls), made once the session offers the device. */
|
/** Steam's touch controls (SteamTouchControls), made once the session offers the device. */
|
||||||
private var steamTouchControls: com.droiddeck.launcher.input.SteamTouchControls? = null
|
private var steamTouchControls: com.droiddeck.launcher.input.SteamTouchControls? = null
|
||||||
@@ -255,29 +238,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
private var closeAtOnce = false
|
private var closeAtOnce = false
|
||||||
/** The drawer's Components tab: the Protons as last read (ComponentsManager). */
|
/** The drawer's Components tab: the Protons as last read (ComponentsManager). */
|
||||||
private var drawerComponents by mutableStateOf<ComponentsManager.Snapshot?>(null)
|
private var drawerComponents by mutableStateOf<ComponentsManager.Snapshot?>(null)
|
||||||
private var drawerGameProfileId by mutableStateOf<Long?>(null)
|
|
||||||
private val drawerGameInventory = GameProfileInventoryCache<Library.SteamGame>()
|
|
||||||
private var drawerGameInventoryRevision = 0L
|
|
||||||
private var drawerGameFexPresetSaving by mutableStateOf(false)
|
|
||||||
private val drawerGameProfileFollowState = GameProfileFollowState()
|
|
||||||
private data class DrawerGameProfileRefresh(
|
|
||||||
val followsSteam: Boolean,
|
|
||||||
val requestedAppId: Long?,
|
|
||||||
val inventoryRevision: Long,
|
|
||||||
)
|
|
||||||
private data class DrawerGameProfileResult(
|
|
||||||
val profiles: List<Pair<Long, String>>,
|
|
||||||
val selectedAppId: Long?,
|
|
||||||
val profile: SelectedGameProfile?,
|
|
||||||
val error: Exception? = null,
|
|
||||||
)
|
|
||||||
private var drawerGameProfileRefresh by mutableStateOf(GameProfileRefreshState<DrawerGameProfileResult>())
|
|
||||||
private val drawerGameProfileRefreshes = LatestRequestCoordinator<DrawerGameProfileRefresh>()
|
|
||||||
private var drawerPage by mutableStateOf(SessionDrawerPage.CONTROLLER)
|
private var drawerPage by mutableStateOf(SessionDrawerPage.CONTROLLER)
|
||||||
private var drawerControllerActive by mutableStateOf(false)
|
private var drawerControllerActive by mutableStateOf(false)
|
||||||
private var backActionsInverted by mutableStateOf(false)
|
private var backActionsInverted by mutableStateOf(false)
|
||||||
/** What the pad is to the Steam client (SessionPrefs.CONTROLLER_*), switched from the drawer. */
|
|
||||||
private var padType by mutableStateOf(SessionPrefs.CONTROLLER_DECK)
|
|
||||||
/** The on-screen PC keyboard (ui/PcKeyboard): real key presses, Esc and F1 included. */
|
/** The on-screen PC keyboard (ui/PcKeyboard): real key presses, Esc and F1 included. */
|
||||||
private var pcKeyboardOpen by mutableStateOf(false)
|
private var pcKeyboardOpen by mutableStateOf(false)
|
||||||
private var hudOn by mutableStateOf(true)
|
private var hudOn by mutableStateOf(true)
|
||||||
@@ -286,8 +249,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
private var effects by mutableStateOf(ScreenEffects.OFF)
|
private var effects by mutableStateOf(ScreenEffects.OFF)
|
||||||
private var textureAnisotropy by mutableStateOf(0)
|
private var textureAnisotropy by mutableStateOf(0)
|
||||||
private var textureLodBias by mutableStateOf(TextureFiltering.LOD_BIAS_OFF)
|
private var textureLodBias by mutableStateOf(TextureFiltering.LOD_BIAS_OFF)
|
||||||
private var drawerTextureAnisotropy by mutableStateOf<Int?>(null)
|
|
||||||
private var drawerTextureLodBias by mutableStateOf<String?>(null)
|
|
||||||
private var lossless by mutableStateOf(Lossless.State.NONE)
|
private var lossless by mutableStateOf(Lossless.State.NONE)
|
||||||
private val pickLossless = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
|
private val pickLossless = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
|
||||||
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let { importLossless(it) }
|
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let { importLossless(it) }
|
||||||
@@ -338,7 +299,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
private val deviceListener = object : InputManager.InputDeviceListener {
|
private val deviceListener = object : InputManager.InputDeviceListener {
|
||||||
override fun onInputDeviceAdded(deviceId: Int) {
|
override fun onInputDeviceAdded(deviceId: Int) {
|
||||||
logInputDevice("connected", deviceId)
|
logInputDevice("connected", deviceId)
|
||||||
padBridge?.syncConnectedControllers()
|
|
||||||
updateOnScreenControls()
|
updateOnScreenControls()
|
||||||
updatePointerCapture()
|
updatePointerCapture()
|
||||||
}
|
}
|
||||||
@@ -355,7 +315,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
requestedOrientation = SessionPrefs.orientation(this)
|
|
||||||
if (com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.isRemoving() ||
|
if (com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.isRemoving() ||
|
||||||
com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.isMaintaining()) {
|
com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.isMaintaining()) {
|
||||||
runtimeRemovalBlocked = true
|
runtimeRemovalBlocked = true
|
||||||
@@ -411,22 +370,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
Log.i(TAG, "pointer capture " + if (hasCapture) "on" else "off")
|
Log.i(TAG, "pointer capture " + if (hasCapture) "on" else "off")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
sessionRoot = root
|
|
||||||
surfaceView = SurfaceView(this)
|
surfaceView = SurfaceView(this)
|
||||||
surfaceView.holder.addCallback(this)
|
surfaceView.holder.addCallback(this)
|
||||||
root.addView(surfaceView)
|
root.addView(surfaceView)
|
||||||
// The window's size is only known once laid out, and changes as the phone folds or turns.
|
|
||||||
root.addOnLayoutChangeListener { _, l, t, r, b, ol, ot, or, ob ->
|
|
||||||
if (r - l != or - ol || b - t != ob - ot) uiHandler.post { applyUnfoldedControls() }
|
|
||||||
}
|
|
||||||
|
|
||||||
val bridge = PadBridge(File(LinuxRuntime.sessionRoot(this), "dev/input"))
|
val bridge = PadBridge(File(LinuxRuntime.sessionRoot(this), "dev/input"))
|
||||||
bridge.setSelectSteam(ControllerPrefs.read(this).selectSteam)
|
|
||||||
padBridge = bridge
|
padBridge = bridge
|
||||||
SessionState.padBridge = bridge
|
SessionState.padBridge = bridge
|
||||||
// A paired Steam Controller is read over Bluetooth LE, out of lizard mode, as Steam Link reads it.
|
|
||||||
SteamControllerBle.listener = { uiHandler.post { updatePadMotion(); updateOnScreenControls() } }
|
|
||||||
steamController = SteamControllerBle(this).also { it.start() }
|
|
||||||
padMotion = com.droiddeck.launcher.input.PadMotion(this) {
|
padMotion = com.droiddeck.launcher.input.PadMotion(this) {
|
||||||
@Suppress("DEPRECATION")
|
@Suppress("DEPRECATION")
|
||||||
(if (Build.VERSION.SDK_INT >= 30) display else windowManager.defaultDisplay)?.rotation ?: android.view.Surface.ROTATION_0
|
(if (Build.VERSION.SDK_INT >= 30) display else windowManager.defaultDisplay)?.rotation ?: android.view.Surface.ROTATION_0
|
||||||
@@ -573,9 +523,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
androidApps = androidApps,
|
androidApps = androidApps,
|
||||||
hudOn = hudOn,
|
hudOn = hudOn,
|
||||||
upscaler = upscaler, upscaleSharpness = upscaleSharpness,
|
upscaler = upscaler, upscaleSharpness = upscaleSharpness,
|
||||||
effects = effects,
|
effects = effects, textureAnisotropy = textureAnisotropy, textureLodBias = textureLodBias,
|
||||||
textureAnisotropy = if (drawerGameProfileId == null) textureAnisotropy else drawerTextureAnisotropy,
|
|
||||||
textureLodBias = if (drawerGameProfileId == null) textureLodBias else drawerTextureLodBias,
|
|
||||||
frameGen = frameGen,
|
frameGen = frameGen,
|
||||||
lossless = lossless,
|
lossless = lossless,
|
||||||
oscMode = oscMode, onScreenButtonsVisible = onScreenButtonsVisible, suspendPolicy = suspendPolicy,
|
oscMode = oscMode, onScreenButtonsVisible = onScreenButtonsVisible, suspendPolicy = suspendPolicy,
|
||||||
@@ -600,24 +548,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
SessionPrefs.setScreenEffects(this@SessionActivity, e); effects = e
|
SessionPrefs.setScreenEffects(this@SessionActivity, e); effects = e
|
||||||
e.push(upscaler)
|
e.push(upscaler)
|
||||||
},
|
},
|
||||||
onTextureAnisotropy = { value ->
|
onTextureAnisotropy = { v -> SessionPrefs.setTextureAnisotropy(this@SessionActivity, v); textureAnisotropy = v },
|
||||||
drawerGameProfileId?.let { appId ->
|
onTextureLodBias = { v -> SessionPrefs.setTextureLodBias(this@SessionActivity, v); textureLodBias = v },
|
||||||
SessionPrefs.setGameTextureAnisotropy(this@SessionActivity, appId.toString(), value)
|
|
||||||
drawerTextureAnisotropy = value
|
|
||||||
} ?: value?.let {
|
|
||||||
SessionPrefs.setTextureAnisotropy(this@SessionActivity, it)
|
|
||||||
textureAnisotropy = it
|
|
||||||
}
|
|
||||||
},
|
|
||||||
onTextureLodBias = { value ->
|
|
||||||
drawerGameProfileId?.let { appId ->
|
|
||||||
SessionPrefs.setGameTextureLodBias(this@SessionActivity, appId.toString(), value)
|
|
||||||
drawerTextureLodBias = value
|
|
||||||
} ?: value?.let {
|
|
||||||
SessionPrefs.setTextureLodBias(this@SessionActivity, it)
|
|
||||||
textureLodBias = it
|
|
||||||
}
|
|
||||||
},
|
|
||||||
onFrameGenPick = { mode ->
|
onFrameGenPick = { mode ->
|
||||||
FrameGen.set(this@SessionActivity, mode)
|
FrameGen.set(this@SessionActivity, mode)
|
||||||
readPrefs()
|
readPrefs()
|
||||||
@@ -636,14 +568,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
onKeyboardButton = { on -> updateControllerPrefs { ControllerPrefs.setKeyboardButton(this@SessionActivity, on) } },
|
onKeyboardButton = { on -> updateControllerPrefs { ControllerPrefs.setKeyboardButton(this@SessionActivity, on) } },
|
||||||
onSteamMenu = if (SessionState.mode == SessionService.MODE_STEAM) ({ sendSteamGuide() }) else null,
|
onSteamMenu = if (SessionState.mode == SessionService.MODE_STEAM) ({ sendSteamGuide() }) else null,
|
||||||
onQam = if (SessionState.mode == SessionService.MODE_STEAM) ({ triggerSteamQam() }) else null,
|
onQam = if (SessionState.mode == SessionService.MODE_STEAM) ({ triggerSteamQam() }) else null,
|
||||||
// Only where the session set the pad up to be switched (SessionService: deckPad).
|
|
||||||
padType = if (SessionState.mode == SessionService.MODE_STEAM && SessionState.deckPad) padType else null,
|
|
||||||
onPadType = { id ->
|
|
||||||
SessionPrefs.setSteamController(this@SessionActivity, id)
|
|
||||||
com.droiddeck.launcher.session.SteamDeckPad.showPad(SessionPrefs.padType(id))
|
|
||||||
com.droiddeck.launcher.input.FakeInputWriter.setPadType(SessionPrefs.padType(id))
|
|
||||||
padType = id
|
|
||||||
},
|
|
||||||
backActionsInverted = backActionsInverted,
|
backActionsInverted = backActionsInverted,
|
||||||
onBackActionsInverted = { inverted ->
|
onBackActionsInverted = { inverted ->
|
||||||
SessionPrefs.setBackActionsInverted(this@SessionActivity, inverted)
|
SessionPrefs.setBackActionsInverted(this@SessionActivity, inverted)
|
||||||
@@ -696,8 +620,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
pipAutoEnter = on
|
pipAutoEnter = on
|
||||||
pip.refresh(true)
|
pip.refresh(true)
|
||||||
},
|
},
|
||||||
unfoldedControls = if (com.droiddeck.launcher.session.SessionDisplay.foldable(this@SessionActivity)) unfoldedControls else null,
|
|
||||||
onUnfoldedControls = ::chooseUnfoldedControls,
|
|
||||||
onBackground = { drawerOpen = false; pip.background(); moveTaskToBack(true) },
|
onBackground = { drawerOpen = false; pip.background(); moveTaskToBack(true) },
|
||||||
onShareLogs = { drawerOpen = false; shareCurrentSessionLogs() },
|
onShareLogs = { drawerOpen = false; shareCurrentSessionLogs() },
|
||||||
onStop = { drawerOpen = false; SessionService.stop(this@SessionActivity); finish() },
|
onStop = { drawerOpen = false; SessionService.stop(this@SessionActivity); finish() },
|
||||||
@@ -713,22 +635,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
onClose = { drawerOpen = false },
|
onClose = { drawerOpen = false },
|
||||||
components = drawerComponents,
|
components = drawerComponents,
|
||||||
onComponentsRefresh = { refreshDrawerComponents() },
|
onComponentsRefresh = { refreshDrawerComponents() },
|
||||||
gameProfiles = drawerGameProfileRefresh.data?.profiles.orEmpty(),
|
|
||||||
selectedGameProfileId = drawerGameProfileId,
|
|
||||||
selectedGameProfile = drawerGameProfileRefresh.data
|
|
||||||
?.takeIf { it.selectedAppId == drawerGameProfileId }?.profile,
|
|
||||||
gameProfilesLoaded = drawerGameProfileRefresh.loaded,
|
|
||||||
gameProfileRefreshFailed = drawerGameProfileRefresh.failed,
|
|
||||||
onSelectedGameProfile = ::selectDrawerGameProfile,
|
|
||||||
onGameProfilesPageOpened = {
|
|
||||||
drawerGameProfileFollowState.resumeFollowingSteam()
|
|
||||||
drawerGameInventoryRevision++
|
|
||||||
},
|
|
||||||
onSelectedGameProfileRefresh = ::refreshDrawerGameProfile,
|
|
||||||
gameFexPresetSaving = drawerGameFexPresetSaving,
|
|
||||||
onGameFexPreset = ::setDrawerGameFexPreset,
|
|
||||||
onComponentSwap = { pid, comp, value -> swapDrawerComponent(pid, comp, value) },
|
onComponentSwap = { pid, comp, value -> swapDrawerComponent(pid, comp, value) },
|
||||||
onGameComponent = ::setDrawerGameComponent,
|
|
||||||
))
|
))
|
||||||
if (SessionState.suspended) SessionPausedOverlay(
|
if (SessionState.suspended) SessionPausedOverlay(
|
||||||
title = pausedTitle(),
|
title = pausedTitle(),
|
||||||
@@ -825,107 +732,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
}, "drawer-components").start()
|
}, "drawer-components").start()
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun selectDrawerGameProfile(appId: Long?) {
|
|
||||||
drawerGameProfileFollowState.selectManually()
|
|
||||||
drawerGameProfileId = appId
|
|
||||||
drawerGameProfileRefresh = drawerGameProfileRefresh.retrying()
|
|
||||||
readDrawerTextureFiltering(appId)
|
|
||||||
refreshDrawerGameProfile()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun readDrawerTextureFiltering(appId: Long?) {
|
|
||||||
val choice = appId?.let { SessionPrefs.gameTextureFiltering(this, it.toString()) }
|
|
||||||
drawerTextureAnisotropy = choice?.anisotropy
|
|
||||||
drawerTextureLodBias = choice?.lodBias
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun refreshDrawerGameProfile() {
|
|
||||||
val refresh = DrawerGameProfileRefresh(
|
|
||||||
drawerGameProfileFollowState.followsSteam,
|
|
||||||
drawerGameProfileId,
|
|
||||||
drawerGameInventoryRevision,
|
|
||||||
)
|
|
||||||
if (!drawerGameProfileRefreshes.submit(refresh)) return
|
|
||||||
Thread({
|
|
||||||
var request = drawerGameProfileRefreshes.takeLatest()
|
|
||||||
while (request != null) {
|
|
||||||
val current = request
|
|
||||||
val result = resolveDrawerGameProfileRefresh(current.value)
|
|
||||||
uiHandler.post {
|
|
||||||
if (!drawerGameProfileRefreshes.isLatest(current)) return@post
|
|
||||||
applyDrawerGameProfileRefresh(current.value, result)
|
|
||||||
}
|
|
||||||
request = drawerGameProfileRefreshes.takeLatest()
|
|
||||||
}
|
|
||||||
}, "drawer-game-profile").start()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun resolveDrawerGameProfileRefresh(
|
|
||||||
refresh: DrawerGameProfileRefresh,
|
|
||||||
): DrawerGameProfileResult {
|
|
||||||
return try {
|
|
||||||
val games = drawerGameInventory.get(refresh.inventoryRevision) { Library.launchableGames(this) }
|
|
||||||
val options = games.mapNotNull { game ->
|
|
||||||
game.profileKey.toLongOrNull()?.let { it to game.name }
|
|
||||||
}.sortedBy { it.second.lowercase() }
|
|
||||||
val installedAppIds = options.mapTo(mutableSetOf()) { it.first }
|
|
||||||
val selectedAppId = if (refresh.followsSteam) {
|
|
||||||
val activeAppId = AgentGuest.activeSteamAppId(this, installedAppIds)
|
|
||||||
val selectedSteamAppId = runCatching { AgentGuest.selectedSteamAppId(this) }
|
|
||||||
AgentGuest.selectedOrActiveInstalledSteamAppId(selectedSteamAppId, activeAppId, installedAppIds)
|
|
||||||
?: refresh.requestedAppId
|
|
||||||
} else {
|
|
||||||
refresh.requestedAppId
|
|
||||||
}
|
|
||||||
val profile = selectedAppId?.let { resolveDrawerGameProfile(it, games) }
|
|
||||||
DrawerGameProfileResult(options, selectedAppId, profile)
|
|
||||||
} catch (error: Exception) {
|
|
||||||
DrawerGameProfileResult(emptyList(), refresh.requestedAppId, null, error)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun applyDrawerGameProfileRefresh(
|
|
||||||
refresh: DrawerGameProfileRefresh,
|
|
||||||
result: DrawerGameProfileResult,
|
|
||||||
) {
|
|
||||||
if (result.error != null) {
|
|
||||||
if (!drawerGameProfileRefresh.failed) {
|
|
||||||
Log.w(TAG, "Could not refresh the selected game profile", result.error)
|
|
||||||
}
|
|
||||||
drawerGameProfileRefresh = drawerGameProfileRefresh.failed()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
drawerGameProfileRefresh = drawerGameProfileRefresh.succeeded(result)
|
|
||||||
if (refresh.followsSteam) {
|
|
||||||
if (drawerGameProfileFollowState.followsSteam) {
|
|
||||||
drawerGameProfileId = result.selectedAppId
|
|
||||||
readDrawerTextureFiltering(result.selectedAppId)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun resolveDrawerGameProfile(
|
|
||||||
selectedAppId: Long,
|
|
||||||
games: List<Library.SteamGame>,
|
|
||||||
): SelectedGameProfile? {
|
|
||||||
val game = games.firstOrNull { it.profileKey == selectedAppId.toString() } ?: return null
|
|
||||||
val snapshot = drawerComponents ?: ComponentsManager.snapshot(this)
|
|
||||||
val protons = snapshot.protons.map { it.proton }
|
|
||||||
val gameChoice = ProtonDefault.gameChoice(this, game.profileKey)
|
|
||||||
return SelectedGameProfile.resolve(
|
|
||||||
selectedAppId = selectedAppId,
|
|
||||||
games = games,
|
|
||||||
generalFexPreset = SessionPrefs.fexPreset(this),
|
|
||||||
environment = GameEnvironmentStore.read(this),
|
|
||||||
snapshot = snapshot,
|
|
||||||
generalProtonId = ProtonDefault.selectedId(this, protons),
|
|
||||||
gameProtonChoice = gameChoice,
|
|
||||||
gameProtonId = ProtonDefault.gameSelectedId(this, game.profileKey, protons),
|
|
||||||
gameComponents = ComponentsManager.gameComponents(this, game.profileKey),
|
|
||||||
gameWindowsComponents = WinComponents.picks(this, game.profileKey),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun swapDrawerComponent(protonId: String, comp: String, value: String) {
|
private fun swapDrawerComponent(protonId: String, comp: String, value: String) {
|
||||||
Thread({
|
Thread({
|
||||||
val message = runCatching {
|
val message = runCatching {
|
||||||
@@ -947,43 +753,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
}, "drawer-components-swap").start()
|
}, "drawer-components-swap").start()
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun setDrawerGameComponent(appId: Long, comp: String, file: String?) {
|
|
||||||
val name = drawerGameProfileRefresh.data?.profiles?.firstOrNull { it.first == appId }?.second ?: appId.toString()
|
|
||||||
Thread({
|
|
||||||
val message = runCatching {
|
|
||||||
ComponentsManager.setGameComponent(this, appId.toString(), comp, file)
|
|
||||||
getString(R.string.comp_game_saved_next, name)
|
|
||||||
}.getOrElse { e ->
|
|
||||||
getString(R.string.session_profile_save_failed, e.message ?: e.javaClass.simpleName)
|
|
||||||
}
|
|
||||||
uiHandler.post {
|
|
||||||
android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_LONG).show()
|
|
||||||
refreshDrawerComponents()
|
|
||||||
refreshDrawerGameProfile()
|
|
||||||
}
|
|
||||||
}, "drawer-game-component").start()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun setDrawerGameFexPreset(appId: Long, preset: String?) {
|
|
||||||
if (drawerGameFexPresetSaving) return
|
|
||||||
drawerGameFexPresetSaving = true
|
|
||||||
val name = drawerGameProfileRefresh.data?.profiles?.firstOrNull { it.first == appId }?.second ?: appId.toString()
|
|
||||||
Thread({
|
|
||||||
val message = try {
|
|
||||||
GameEnvironmentStore.setGameFexPreset(this, appId.toString(), preset)
|
|
||||||
getString(R.string.comp_game_saved_next, name)
|
|
||||||
} catch (error: Exception) {
|
|
||||||
Log.w(TAG, "Could not save the game FEX preset for $appId", error)
|
|
||||||
getString(R.string.session_profile_save_failed, error.message ?: error.javaClass.simpleName)
|
|
||||||
}
|
|
||||||
uiHandler.post {
|
|
||||||
drawerGameFexPresetSaving = false
|
|
||||||
Toast.makeText(this, message, Toast.LENGTH_LONG).show()
|
|
||||||
refreshDrawerGameProfile()
|
|
||||||
}
|
|
||||||
}, "drawer-game-fex-preset").start()
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The session this screen is bringing up: the live one when re-attached, else the intent's. */
|
/** The session this screen is bringing up: the live one when re-attached, else the intent's. */
|
||||||
private fun loadingMode(): String =
|
private fun loadingMode(): String =
|
||||||
if (SessionState.running) SessionState.mode
|
if (SessionState.running) SessionState.mode
|
||||||
@@ -1031,7 +800,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
|
|
||||||
private fun readPrefs() {
|
private fun readPrefs() {
|
||||||
pipAutoEnter = SessionPrefs.pipAutoEnter(this)
|
pipAutoEnter = SessionPrefs.pipAutoEnter(this)
|
||||||
unfoldedControls = SessionPrefs.unfoldedControls(this)
|
|
||||||
hudOn = SessionPrefs.hudEnabled(this)
|
hudOn = SessionPrefs.hudEnabled(this)
|
||||||
upscaler = SessionPrefs.upscaler(this)
|
upscaler = SessionPrefs.upscaler(this)
|
||||||
upscaleSharpness = SessionPrefs.upscaleSharpness(this)
|
upscaleSharpness = SessionPrefs.upscaleSharpness(this)
|
||||||
@@ -1047,7 +815,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
WaylandCompositor.nativeSendSceneInput(3, it, 0)
|
WaylandCompositor.nativeSendSceneInput(3, it, 0)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (nextTouchMode == SessionPrefs.TOUCH_OFF || !usingTouchpad()) cursorVisible = false
|
if (nextTouchMode == SessionPrefs.TOUCH_OFF) cursorVisible = false
|
||||||
}
|
}
|
||||||
touchMode = nextTouchMode
|
touchMode = nextTouchMode
|
||||||
routedTouchMode = effectiveTouchMode()
|
routedTouchMode = effectiveTouchMode()
|
||||||
@@ -1057,7 +825,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
steamDownloadsInBackground = SessionPrefs.steamDownloadsInBackground(this)
|
steamDownloadsInBackground = SessionPrefs.steamDownloadsInBackground(this)
|
||||||
oscMode = SessionPrefs.oscMode(this)
|
oscMode = SessionPrefs.oscMode(this)
|
||||||
backActionsInverted = SessionPrefs.backActionsInverted(this)
|
backActionsInverted = SessionPrefs.backActionsInverted(this)
|
||||||
padType = SessionPrefs.steamController(this)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Compositor ──────────────────────────────────────────────────────────────────────────
|
// ── Compositor ──────────────────────────────────────────────────────────────────────────
|
||||||
@@ -1358,7 +1125,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
override fun onConfigurationChanged(newConfig: android.content.res.Configuration) {
|
override fun onConfigurationChanged(newConfig: android.content.res.Configuration) {
|
||||||
super.onConfigurationChanged(newConfig)
|
super.onConfigurationChanged(newConfig)
|
||||||
applyFollowOrientation(newConfig)
|
applyFollowOrientation(newConfig)
|
||||||
applyUnfoldedControls()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun surfaceDestroyed(holder: SurfaceHolder) {
|
override fun surfaceDestroyed(holder: SurfaceHolder) {
|
||||||
@@ -1586,7 +1352,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
return super.dispatchKeyEvent(event)
|
return super.dispatchKeyEvent(event)
|
||||||
}
|
}
|
||||||
if (pipUi) return true
|
if (pipUi) return true
|
||||||
val fromController = PadBridge.isControllerKeyEvent(event)
|
val fromController = PadBridge.isControllerKey(event)
|
||||||
if (fromController && event.action == KeyEvent.ACTION_DOWN) {
|
if (fromController && event.action == KeyEvent.ACTION_DOWN) {
|
||||||
if (drawerOpen && !drawerControllerActive) sessionOverlay.requestFocus()
|
if (drawerOpen && !drawerControllerActive) sessionOverlay.requestFocus()
|
||||||
drawerControllerActive = true
|
drawerControllerActive = true
|
||||||
@@ -1642,7 +1408,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
if (event.keyCode != KeyEvent.KEYCODE_BACK && padBridge?.onKeyEvent(event) == true) return true
|
if (event.keyCode != KeyEvent.KEYCODE_BACK && padBridge?.onKeyEvent(event) == true) return true
|
||||||
// A hardware keyboard, forwarded to the compositor's wl_keyboard. Back is left to the
|
// A hardware keyboard, forwarded to the compositor's wl_keyboard. Back is left to the
|
||||||
// activity, which opens the drawer.
|
// activity, which opens the drawer.
|
||||||
if (CompositorHost.isStarted && event.keyCode != KeyEvent.KEYCODE_BACK && !fromController) {
|
val fromPad = fromController
|
||||||
|
if (CompositorHost.isStarted && event.keyCode != KeyEvent.KEYCODE_BACK && !fromPad) {
|
||||||
val down = event.action == KeyEvent.ACTION_DOWN
|
val down = event.action == KeyEvent.ACTION_DOWN
|
||||||
if (down || event.action == KeyEvent.ACTION_UP) {
|
if (down || event.action == KeyEvent.ACTION_UP) {
|
||||||
var evdev = EvdevKeys.fromKeyCode(event.keyCode)
|
var evdev = EvdevKeys.fromKeyCode(event.keyCode)
|
||||||
@@ -1680,7 +1447,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
|
|
||||||
override fun dispatchGenericMotionEvent(event: MotionEvent): Boolean {
|
override fun dispatchGenericMotionEvent(event: MotionEvent): Boolean {
|
||||||
if (pipUi) return true
|
if (pipUi) return true
|
||||||
if (drawerOpen && PadBridge.isControllerMotionEvent(event)) {
|
if (drawerOpen && event.device != null && PadBridge.isFromController(event.device)) {
|
||||||
if (!drawerControllerActive) sessionOverlay.requestFocus()
|
if (!drawerControllerActive) sessionOverlay.requestFocus()
|
||||||
drawerControllerActive = true
|
drawerControllerActive = true
|
||||||
if (event.actionMasked == MotionEvent.ACTION_MOVE &&
|
if (event.actionMasked == MotionEvent.ACTION_MOVE &&
|
||||||
@@ -1691,7 +1458,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
if (drawerDirectionKey != KeyEvent.KEYCODE_UNKNOWN) releaseDrawerDirection()
|
if (drawerDirectionKey != KeyEvent.KEYCODE_UNKNOWN) releaseDrawerDirection()
|
||||||
if (pcKeyboardOpen && PadBridge.isControllerMotionEvent(event)) return super.dispatchGenericMotionEvent(event)
|
if (pcKeyboardOpen && event.device != null && PadBridge.isFromController(event.device)) return super.dispatchGenericMotionEvent(event)
|
||||||
if (padBridge?.onMotionEvent(event) == true) return true
|
if (padBridge?.onMotionEvent(event) == true) return true
|
||||||
if (event.isFromSource(android.view.InputDevice.SOURCE_MOUSE) && !drawerOpen && onMouse(event)) return true
|
if (event.isFromSource(android.view.InputDevice.SOURCE_MOUSE) && !drawerOpen && onMouse(event)) return true
|
||||||
return super.dispatchGenericMotionEvent(event)
|
return super.dispatchGenericMotionEvent(event)
|
||||||
@@ -1915,8 +1682,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
WaylandCompositor.nativeSendSceneInput(3, button, if (pressed) 1 else 0)
|
WaylandCompositor.nativeSendSceneInput(3, button, if (pressed) 1 else 0)
|
||||||
},
|
},
|
||||||
sendWheel = { steps -> WaylandCompositor.nativeSendSceneInput(4, steps, 0) },
|
sendWheel = { steps -> WaylandCompositor.nativeSendSceneInput(4, steps, 0) },
|
||||||
onSteamMenu = ::tapSteamButton,
|
onSteamMenu = {
|
||||||
onQam = ::tapQam,
|
if (SessionState.mode == SessionService.MODE_STEAM) {
|
||||||
|
padBridge?.applyTouch { st -> st.press(com.droiddeck.launcher.input.PadState.GUIDE, true) }
|
||||||
|
Handler(Looper.getMainLooper()).postDelayed({
|
||||||
|
padBridge?.applyTouch { st -> st.press(com.droiddeck.launcher.input.PadState.GUIDE, false) }
|
||||||
|
}, 90)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onQam = {
|
||||||
|
if (SessionState.mode == SessionService.MODE_STEAM) padBridge?.triggerQam()
|
||||||
|
},
|
||||||
onClose = { selectSecondScreenMode(SecondScreenMode.NONE) },
|
onClose = { selectSecondScreenMode(SecondScreenMode.NONE) },
|
||||||
)
|
)
|
||||||
secondScreenPresentation = presentation
|
secondScreenPresentation = presentation
|
||||||
@@ -1933,64 +1709,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun tapSteamButton() {
|
|
||||||
if (SessionState.mode == SessionService.MODE_STEAM) {
|
|
||||||
padBridge?.applyTouch { st -> st.press(com.droiddeck.launcher.input.PadState.GUIDE, true) }
|
|
||||||
Handler(Looper.getMainLooper()).postDelayed({
|
|
||||||
padBridge?.applyTouch { st -> st.press(com.droiddeck.launcher.input.PadState.GUIDE, false) }
|
|
||||||
}, 90)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun tapQam() {
|
|
||||||
if (SessionState.mode == SessionService.MODE_STEAM) padBridge?.triggerQam()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun chooseUnfoldedControls(on: Boolean) {
|
|
||||||
SessionPrefs.setUnfoldedControls(this, on)
|
|
||||||
unfoldedControls = on
|
|
||||||
applyUnfoldedControls()
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Unfolded controls: on a foldable's inner screen, the game above and the Steam Deck controller's
|
|
||||||
* trackpads and back grips below ([com.droiddeck.launcher.ui.DeckControlsPanel], as a second
|
|
||||||
* screen shows them, plus a whole gamepad). The on-screen pad is hidden meanwhile. The surface shrinks to the top part, so a Follow screen session resizes
|
|
||||||
* to it and any other is fitted into it. Folded onto the cover screen - a phone-sized panel -
|
|
||||||
* or in picture-in-picture, the game is full screen again.
|
|
||||||
*/
|
|
||||||
private fun applyUnfoldedControls() {
|
|
||||||
if (!::sessionRoot.isInitialized) return
|
|
||||||
val width = sessionRoot.width
|
|
||||||
val height = sessionRoot.height
|
|
||||||
val wanted = unfoldedControls && com.droiddeck.launcher.session.SessionDisplay.foldable(this) &&
|
|
||||||
SessionState.mode == SessionService.MODE_STEAM && SessionState.deckPad &&
|
|
||||||
!pipUi && !isInPictureInPictureMode && width > 0 && height > 0 &&
|
|
||||||
resources.configuration.smallestScreenWidthDp >= com.droiddeck.launcher.session.SessionDisplay.UNFOLDED_MIN_DP
|
|
||||||
val gameHeight = if (wanted) com.droiddeck.launcher.session.SessionDisplay.unfoldedGameHeight(width, height)
|
|
||||||
else FrameLayout.LayoutParams.MATCH_PARENT
|
|
||||||
val params = surfaceView.layoutParams as FrameLayout.LayoutParams
|
|
||||||
if (params.height != gameHeight) {
|
|
||||||
surfaceView.layoutParams = FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, gameHeight, Gravity.TOP)
|
|
||||||
Log.i(TAG, if (wanted) "unfolded controls: game ${width}x$gameHeight, controls ${width}x${height - gameHeight}"
|
|
||||||
else "unfolded controls: game full screen")
|
|
||||||
}
|
|
||||||
var panel = unfoldedPanel
|
|
||||||
if (!wanted) {
|
|
||||||
if (panel != null) { sessionRoot.removeView(panel); unfoldedPanel = null; updateOnScreenControls() }
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (panel == null) {
|
|
||||||
panel = com.droiddeck.launcher.ui.DeckControlsPanel(this, onClose = { chooseUnfoldedControls(false) },
|
|
||||||
onSteamMenu = ::tapSteamButton, onQam = ::tapQam, pad = padBridge)
|
|
||||||
// Just above the surface: the on-screen pad, keyboard and drawer still draw over it.
|
|
||||||
sessionRoot.addView(panel, sessionRoot.indexOfChild(surfaceView) + 1)
|
|
||||||
unfoldedPanel = panel
|
|
||||||
updateOnScreenControls()
|
|
||||||
}
|
|
||||||
panel.layoutParams = FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, height - gameHeight, Gravity.BOTTOM)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun moveSecondScreenPointer(x: Float, y: Float, width: Float, height: Float) {
|
private fun moveSecondScreenPointer(x: Float, y: Float, width: Float, height: Float) {
|
||||||
if (width <= 0f || height <= 0f) return
|
if (width <= 0f || height <= 0f) return
|
||||||
val nx = (x / width).coerceIn(0f, 1f)
|
val nx = (x / width).coerceIn(0f, 1f)
|
||||||
@@ -2218,9 +1936,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
?.let { FileUtils.readString(it)?.trim()?.lowercase() }
|
?.let { FileUtils.readString(it)?.trim()?.lowercase() }
|
||||||
?: SessionPrefs.oscMode(this)
|
?: SessionPrefs.oscMode(this)
|
||||||
val controls = onScreenControls ?: return
|
val controls = onScreenControls ?: return
|
||||||
// In picture-in-picture, or with the unfolded screen's gamepad below the game, the on-screen
|
if (pipUi) {
|
||||||
// pad would only cover the picture or that panel.
|
|
||||||
if (pipUi || unfoldedPanel != null) {
|
|
||||||
onScreenButtonsVisible = false
|
onScreenButtonsVisible = false
|
||||||
controls.releaseAll()
|
controls.releaseAll()
|
||||||
controls.visibility = View.GONE
|
controls.visibility = View.GONE
|
||||||
@@ -2255,8 +1971,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
// Auto: the touch pad when there is no controller - except on the desktop, where the
|
// Auto: the touch pad when there is no controller - except on the desktop, where the
|
||||||
// screen is a touchpad for the pointer and a pad over it would be in the way. A game
|
// screen is a touchpad for the pointer and a pad over it would be in the way. A game
|
||||||
// started from the rail, or Steam, gets it; the drawer turns it on anywhere.
|
// started from the rail, or Steam, gets it; the drawer turns it on anywhere.
|
||||||
else -> !PadBridge.anyControllerConnected() && !SteamControllerBle.connected &&
|
else -> !PadBridge.anyControllerConnected() && SessionState.mode != SessionService.MODE_DESKTOP
|
||||||
SessionState.mode != SessionService.MODE_DESKTOP
|
|
||||||
}
|
}
|
||||||
onScreenButtonsVisible = show
|
onScreenButtonsVisible = show
|
||||||
if (steam != null) {
|
if (steam != null) {
|
||||||
@@ -2341,7 +2056,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
if (::pip.isInitialized) pip.changed(inPip)
|
if (::pip.isInitialized) pip.changed(inPip)
|
||||||
// The panel may have changed while the session was a thumbnail (folded or unfolded in PiP).
|
// The panel may have changed while the session was a thumbnail (folded or unfolded in PiP).
|
||||||
if (!inPip && surfaceW > 0) followWindow(surfaceW, surfaceH)
|
if (!inPip && surfaceW > 0) followWindow(surfaceW, surfaceH)
|
||||||
applyUnfoldedControls()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun startActivityForResult(intent: Intent, requestCode: Int, options: Bundle?) {
|
override fun startActivityForResult(intent: Intent, requestCode: Int, options: Bundle?) {
|
||||||
@@ -2398,7 +2112,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
|
|
||||||
override fun onResume() {
|
override fun onResume() {
|
||||||
super.onResume()
|
super.onResume()
|
||||||
requestedOrientation = SessionPrefs.orientation(this)
|
|
||||||
if (runtimeRemovalBlocked) return
|
if (runtimeRemovalBlocked) return
|
||||||
com.droiddeck.launcher.ui.Motion.refresh(this)
|
com.droiddeck.launcher.ui.Motion.refresh(this)
|
||||||
refreshHomeApp()
|
refreshHomeApp()
|
||||||
@@ -2408,7 +2121,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
}
|
}
|
||||||
(getSystemService(INPUT_SERVICE) as? InputManager)
|
(getSystemService(INPUT_SERVICE) as? InputManager)
|
||||||
?.registerInputDeviceListener(deviceListener, Handler(Looper.getMainLooper()))
|
?.registerInputDeviceListener(deviceListener, Handler(Looper.getMainLooper()))
|
||||||
if (SessionState.guestPid > 1) padBridge?.syncConnectedControllers()
|
|
||||||
onScreenControls?.reload()
|
onScreenControls?.reload()
|
||||||
controllerSettings = ControllerPrefs.read(this)
|
controllerSettings = ControllerPrefs.read(this)
|
||||||
updateOnScreenControls()
|
updateOnScreenControls()
|
||||||
@@ -2506,7 +2218,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
closeSecondScreen(reset = false)
|
closeSecondScreen(reset = false)
|
||||||
if (::hud.isInitialized) hud.stop()
|
if (::hud.isInitialized) hud.stop()
|
||||||
padBridge?.stop()
|
padBridge?.stop()
|
||||||
steamController?.stop()
|
|
||||||
if (SessionState.padBridge === padBridge) SessionState.padBridge = null
|
if (SessionState.padBridge === padBridge) SessionState.padBridge = null
|
||||||
padMotion?.stop()
|
padMotion?.stop()
|
||||||
if (SessionState.deckPadListener === deckPadListener) SessionState.deckPadListener = null
|
if (SessionState.deckPadListener === deckPadListener) SessionState.deckPadListener = null
|
||||||
|
|||||||
@@ -85,63 +85,6 @@ object AgentGuest {
|
|||||||
fun focus(context: Context): JSONObject? =
|
fun focus(context: Context): JSONObject? =
|
||||||
if (SessionState.running) readJson(File(dir(context), "focus.json")) else null
|
if (SessionState.running) readJson(File(dir(context), "focus.json")) else null
|
||||||
|
|
||||||
/** The Steam library game whose tile currently has controller or keyboard focus. */
|
|
||||||
fun selectedSteamAppId(context: Context): Long? {
|
|
||||||
val result = call(context, JSONObject().put("kind", "steam-selection"), 6_000)
|
|
||||||
if (!result.optBoolean("ok") || result.isNull("appId")) return null
|
|
||||||
return result.optLong("appId").takeIf { it in 1..4_294_967_295L }
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The installed game Gamescope is presenting, including while Steam's overlay has focus. */
|
|
||||||
fun activeSteamAppId(context: Context, installedAppIds: Set<Long>): Long? {
|
|
||||||
val snapshot = focus(context) ?: return null
|
|
||||||
val focusedAppId = snapshot.optLong("focusedApp").takeIf { snapshot.has("focusedApp") }
|
|
||||||
val focusableAppIds = snapshot.optJSONArray("focusableApps")?.let { apps ->
|
|
||||||
buildList {
|
|
||||||
for (index in 0 until apps.length()) {
|
|
||||||
apps.optLong(index).takeIf { it > 0 }?.let(::add)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}.orEmpty()
|
|
||||||
val baselayerAppIds = snapshot.optJSONArray("baselayerAppIds")?.let { apps ->
|
|
||||||
buildList {
|
|
||||||
for (index in 0 until apps.length()) {
|
|
||||||
apps.optLong(index).takeIf { it > 0 }?.let(::add)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}.orEmpty()
|
|
||||||
return activeInstalledSteamAppId(focusedAppId, focusableAppIds, installedAppIds, baselayerAppIds)
|
|
||||||
}
|
|
||||||
|
|
||||||
internal fun focusedInstalledSteamAppId(focusedAppId: Long?, installedAppIds: Set<Long>): Long? =
|
|
||||||
focusedAppId?.takeIf { it in installedAppIds }
|
|
||||||
|
|
||||||
internal fun activeInstalledSteamAppId(
|
|
||||||
focusedAppId: Long?,
|
|
||||||
focusableAppIds: List<Long>,
|
|
||||||
installedAppIds: Set<Long>,
|
|
||||||
baselayerAppIds: List<Long> = emptyList(),
|
|
||||||
): Long? = focusedInstalledSteamAppId(focusedAppId, installedAppIds)
|
|
||||||
?: focusableAppIds.filter { it in installedAppIds }.distinct().singleOrNull()
|
|
||||||
?: baselayerAppIds.filter { it in installedAppIds }.distinct().singleOrNull()
|
|
||||||
|
|
||||||
internal fun preferredInstalledSteamAppId(
|
|
||||||
selectedAppId: Long?,
|
|
||||||
activeAppId: Long?,
|
|
||||||
installedAppIds: Set<Long>,
|
|
||||||
): Long? = selectedAppId?.takeIf { it in installedAppIds }
|
|
||||||
?: activeAppId?.takeIf { it in installedAppIds }
|
|
||||||
|
|
||||||
internal fun selectedOrActiveInstalledSteamAppId(
|
|
||||||
selectedAppId: Result<Long?>,
|
|
||||||
activeAppId: Long?,
|
|
||||||
installedAppIds: Set<Long>,
|
|
||||||
): Long? {
|
|
||||||
preferredInstalledSteamAppId(selectedAppId.getOrNull(), activeAppId, installedAppIds)?.let { return it }
|
|
||||||
selectedAppId.exceptionOrNull()?.let { throw it }
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Send one request and wait for its answer. Throws [AgentException] with a stable code. */
|
/** Send one request and wait for its answer. Throws [AgentException] with a stable code. */
|
||||||
fun call(context: Context, request: JSONObject, timeoutMs: Long): JSONObject {
|
fun call(context: Context, request: JSONObject, timeoutMs: Long): JSONObject {
|
||||||
if (request.optString("kind") in setOf("exec", "cdp")) AgentAccess.requireCommands(context)
|
if (request.optString("kind") in setOf("exec", "cdp")) AgentAccess.requireCommands(context)
|
||||||
|
|||||||
@@ -14,7 +14,6 @@ import org.json.JSONObject
|
|||||||
class AgentStartActivity : Activity() {
|
class AgentStartActivity : Activity() {
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
requestedOrientation = com.droiddeck.launcher.session.SessionPrefs.orientation(this)
|
|
||||||
val request = decodeRequest(intent.getStringExtra(EXTRA_REQUEST))
|
val request = decodeRequest(intent.getStringExtra(EXTRA_REQUEST))
|
||||||
if (request == null) {
|
if (request == null) {
|
||||||
finish()
|
finish()
|
||||||
|
|||||||
@@ -182,30 +182,26 @@ public class PulseAudioComponent extends SessionPart {
|
|||||||
* client is never left without an output. Says so in the audio log either way.
|
* client is never left without an output. Says so in the audio log either way.
|
||||||
*/
|
*/
|
||||||
private void ensureClientSink(java.io.PrintWriter out) {
|
private void ensureClientSink(java.io.PrintWriter out) {
|
||||||
try {
|
long deadline = System.currentTimeMillis() + 15000L;
|
||||||
long deadline = System.currentTimeMillis() + 15000L;
|
String sinks = null;
|
||||||
String sinks = null;
|
while (System.currentTimeMillis() < deadline && pid > 1) {
|
||||||
while (System.currentTimeMillis() < deadline && pid > 1) {
|
if (socket().exists() && (sinks = pactl("list", "short", "sinks")) != null) break;
|
||||||
if (socket().exists() && (sinks = pactl("list", "short", "sinks")) != null) break;
|
try { Thread.sleep(250L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; }
|
||||||
try { Thread.sleep(250L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; }
|
|
||||||
}
|
|
||||||
String line;
|
|
||||||
if (sinks == null) {
|
|
||||||
line = "== client sink: the daemon did not answer in 15 s; no fallback attempted";
|
|
||||||
} else if (sinks.contains("\tDirectAudio\t") || sinks.startsWith("DirectAudio\t") || sinks.contains("\tDirectAudio\n") || sinks.matches("(?s).*\\bDirectAudio\\b.*")) {
|
|
||||||
line = "== client sink: DirectAudio (module-directaudio-native-sink)";
|
|
||||||
} else {
|
|
||||||
boolean loaded = pactl("load-module", "module-aaudio-sink", "sink_name=AAudioSink", "performance_mode=1", "adaptive=1", "volume=1.0") != null
|
|
||||||
&& pactl("set-default-sink", "AAudioSink") != null;
|
|
||||||
line = loaded ? "== client sink: DirectAudio did not come up; FALLBACK to the plain AAudio sink (AAudioSink)"
|
|
||||||
: "== client sink: DirectAudio did not come up and the AAudio fallback failed too - no client sound";
|
|
||||||
Log.w(TAG, line);
|
|
||||||
}
|
|
||||||
Log.i(TAG, line);
|
|
||||||
if (out != null) synchronized (out) { out.println(line); out.flush(); }
|
|
||||||
} catch (Throwable t) {
|
|
||||||
Log.w(TAG, "ensureClientSink failed", t);
|
|
||||||
}
|
}
|
||||||
|
String line;
|
||||||
|
if (sinks == null) {
|
||||||
|
line = "== client sink: the daemon did not answer in 15 s; no fallback attempted";
|
||||||
|
} else if (sinks.contains("\tDirectAudio\t") || sinks.startsWith("DirectAudio\t") || sinks.contains("\tDirectAudio\n") || sinks.matches("(?s).*\\bDirectAudio\\b.*")) {
|
||||||
|
line = "== client sink: DirectAudio (module-directaudio-native-sink)";
|
||||||
|
} else {
|
||||||
|
boolean loaded = pactl("load-module", "module-aaudio-sink", "sink_name=AAudioSink", "performance_mode=1", "adaptive=1", "volume=1.0") != null
|
||||||
|
&& pactl("set-default-sink", "AAudioSink") != null;
|
||||||
|
line = loaded ? "== client sink: DirectAudio did not come up; FALLBACK to the plain AAudio sink (AAudioSink)"
|
||||||
|
: "== client sink: DirectAudio did not come up and the AAudio fallback failed too - no client sound";
|
||||||
|
Log.w(TAG, line);
|
||||||
|
}
|
||||||
|
Log.i(TAG, line);
|
||||||
|
if (out != null) synchronized (out) { out.println(line); out.flush(); }
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Runs pactl against this daemon; its stdout, or null when it failed or timed out. */
|
/** Runs pactl against this daemon; its stdout, or null when it failed or timed out. */
|
||||||
@@ -227,14 +223,8 @@ public class PulseAudioComponent extends SessionPart {
|
|||||||
builder.environment().put("PULSE_SERVER", "unix:" + socket().getAbsolutePath());
|
builder.environment().put("PULSE_SERVER", "unix:" + socket().getAbsolutePath());
|
||||||
process = builder.start();
|
process = builder.start();
|
||||||
String output;
|
String output;
|
||||||
try (InputStream in = process.getInputStream();
|
try (InputStream in = process.getInputStream()) {
|
||||||
java.io.ByteArrayOutputStream outStream = new java.io.ByteArrayOutputStream()) {
|
output = new String(in.readAllBytes(), java.nio.charset.StandardCharsets.UTF_8);
|
||||||
byte[] buf = new byte[4096];
|
|
||||||
int n;
|
|
||||||
while ((n = in.read(buf)) != -1) {
|
|
||||||
outStream.write(buf, 0, n);
|
|
||||||
}
|
|
||||||
output = outStream.toString(java.nio.charset.StandardCharsets.UTF_8.name());
|
|
||||||
}
|
}
|
||||||
if (!process.waitFor(5, TimeUnit.SECONDS)) {
|
if (!process.waitFor(5, TimeUnit.SECONDS)) {
|
||||||
process.destroyForcibly();
|
process.destroyForcibly();
|
||||||
@@ -244,7 +234,7 @@ public class PulseAudioComponent extends SessionPart {
|
|||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException e) {
|
||||||
Thread.currentThread().interrupt();
|
Thread.currentThread().interrupt();
|
||||||
return null;
|
return null;
|
||||||
} catch (Throwable t) {
|
} catch (Exception e) {
|
||||||
return null;
|
return null;
|
||||||
} finally {
|
} finally {
|
||||||
if (process != null && process.isAlive()) process.destroyForcibly();
|
if (process != null && process.isAlive()) process.destroyForcibly();
|
||||||
|
|||||||
@@ -152,6 +152,7 @@ object DeviceReport {
|
|||||||
k("Zink lazy descriptors", SessionPrefs.zinkLazy(context))
|
k("Zink lazy descriptors", SessionPrefs.zinkLazy(context))
|
||||||
k("Threaded GL (glthread)", SessionPrefs.glThread(context))
|
k("Threaded GL (glthread)", SessionPrefs.glThread(context))
|
||||||
k("No GL error checks", SessionPrefs.noGlError(context))
|
k("No GL error checks", SessionPrefs.noGlError(context))
|
||||||
|
k("Steam Deck mode", SessionPrefs.steamDeckMode(context))
|
||||||
k("Steam controller", SessionPrefs.steamController(context))
|
k("Steam controller", SessionPrefs.steamController(context))
|
||||||
k("Upscaler", (SessionPrefs.upscalerChoices.firstOrNull { it.first == SessionPrefs.upscaler(context) }?.second ?: "Off") +
|
k("Upscaler", (SessionPrefs.upscalerChoices.firstOrNull { it.first == SessionPrefs.upscaler(context) }?.second ?: "Off") +
|
||||||
" (sharpness ${SessionPrefs.upscaleSharpness(context)}%)")
|
" (sharpness ${SessionPrefs.upscaleSharpness(context)}%)")
|
||||||
|
|||||||
@@ -30,11 +30,4 @@ object FexPreset {
|
|||||||
|
|
||||||
/** Game-launch variables in KEY=VALUE form. */
|
/** Game-launch variables in KEY=VALUE form. */
|
||||||
fun env(id: String): List<String> = byId(id).env
|
fun env(id: String): List<String> = byId(id).env
|
||||||
|
|
||||||
val environmentKeys: Set<String> by lazy {
|
|
||||||
all.flatMap { it.env }.mapTo(linkedSetOf()) { it.substringBefore('=') }
|
|
||||||
}
|
|
||||||
|
|
||||||
fun environment(id: String): Map<String, String> =
|
|
||||||
env(id).associate { it.substringBefore('=') to it.substringAfter('=') }
|
|
||||||
}
|
}
|
||||||
@@ -31,8 +31,7 @@ object GameEnvironment {
|
|||||||
"VKD3D_SHADER_MODEL" to "6_9",
|
"VKD3D_SHADER_MODEL" to "6_9",
|
||||||
// .NET 7 and later reserve 256 GB of address space for the GC heap at startup, more than an
|
// .NET 7 and later reserve 256 GB of address space for the GC heap at startup, more than an
|
||||||
// Android process has free, and the runtime fails to start. 32 GB is plenty for a game.
|
// Android process has free, and the runtime fails to start. 32 GB is plenty for a game.
|
||||||
// Older NativeAOT runtimes require bare hex digits. CoreCLR accepts this form too.
|
"DOTNET_GCRegionRange" to "0x800000000",
|
||||||
"DOTNET_GCRegionRange" to "800000000",
|
|
||||||
// .NET's W^X writes JIT code through a second mapping that FEX does not watch, so FEX keeps
|
// .NET's W^X writes JIT code through a second mapping that FEX does not watch, so FEX keeps
|
||||||
// running the stale translation and the game hangs at startup.
|
// running the stale translation and the game hangs at startup.
|
||||||
"DOTNET_EnableWriteXorExecute" to "0",
|
"DOTNET_EnableWriteXorExecute" to "0",
|
||||||
@@ -46,37 +45,4 @@ object GameEnvironment {
|
|||||||
|
|
||||||
fun effective(config: Config, preset: String, scope: String, forceSsbs: Boolean = false): Map<String, String?> =
|
fun effective(config: Config, preset: String, scope: String, forceSsbs: Boolean = false): Map<String, String?> =
|
||||||
defaults(preset, forceSsbs) + config.shared + if (scope.isEmpty()) emptyMap() else config.games[scope].orEmpty()
|
defaults(preset, forceSsbs) + config.shared + if (scope.isEmpty()) emptyMap() else config.games[scope].orEmpty()
|
||||||
|
|
||||||
fun hasOverride(config: Config, scope: String, name: String): Boolean =
|
|
||||||
scope.isNotEmpty() && config.entries(scope).containsKey(name)
|
|
||||||
|
|
||||||
fun withScopeValue(config: Config, scope: String, name: String, value: String?): Config {
|
|
||||||
require(scope.isEmpty() || validScope(scope))
|
|
||||||
val entries = config.entries(scope).toMutableMap()
|
|
||||||
if (value == null) entries.remove(name) else entries[name] = value
|
|
||||||
return config.withEntries(scope, entries)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun gameFexPreset(config: Config, scope: String): String? {
|
|
||||||
require(scope.isNotEmpty() && validScope(scope))
|
|
||||||
val entries = config.games[scope].orEmpty()
|
|
||||||
if (FexPreset.environmentKeys.none(entries::containsKey)) return null
|
|
||||||
return FexPreset.all.firstOrNull { preset ->
|
|
||||||
val expected = FexPreset.environment(preset.id)
|
|
||||||
FexPreset.environmentKeys.all { key -> entries.containsKey(key) && entries[key] == expected[key] }
|
|
||||||
}?.id ?: CUSTOM_FEX_PRESET
|
|
||||||
}
|
|
||||||
|
|
||||||
fun withGameFexPreset(config: Config, scope: String, preset: String?): Config {
|
|
||||||
require(scope.isNotEmpty() && validScope(scope))
|
|
||||||
require(preset == null || FexPreset.all.any { it.id == preset })
|
|
||||||
val entries = config.entries(scope).filterKeys { it !in FexPreset.environmentKeys }.toMutableMap()
|
|
||||||
if (preset != null) {
|
|
||||||
val values = FexPreset.environment(preset)
|
|
||||||
FexPreset.environmentKeys.forEach { key -> entries[key] = values[key] }
|
|
||||||
}
|
|
||||||
return config.withEntries(scope, entries)
|
|
||||||
}
|
|
||||||
|
|
||||||
const val CUSTOM_FEX_PRESET = "__custom__"
|
|
||||||
}
|
}
|
||||||
@@ -93,12 +93,9 @@ object LogRedactor {
|
|||||||
"(?i)(?<![A-Za-z0-9_])(login)(\\s*=\\s*|[\"']\\s*[=:]\\s*|[\"']\\s+)" + ACCOUNT_VALUE
|
"(?i)(?<![A-Za-z0-9_])(login)(\\s*=\\s*|[\"']\\s*[=:]\\s*|[\"']\\s+)" + ACCOUNT_VALUE
|
||||||
)
|
)
|
||||||
|
|
||||||
/** A learned pattern and the text (lowercase) a line must hold for it to match; null when none can be said. */
|
|
||||||
private class Learned(val regex: Regex, val needs: String?)
|
|
||||||
|
|
||||||
/** The device's Steam accounts and persona names as patterns (see [learnAccounts]). */
|
/** The device's Steam accounts and persona names as patterns (see [learnAccounts]). */
|
||||||
@Volatile
|
@Volatile
|
||||||
private var accounts: List<Learned> = emptyList()
|
private var accounts: List<Regex> = emptyList()
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Learns every Steam account on the device from the client's loginusers.vdf - its AccountName
|
* Learns every Steam account on the device from the client's loginusers.vdf - its AccountName
|
||||||
@@ -106,13 +103,12 @@ object LogRedactor {
|
|||||||
* Names under three characters are skipped: blanking every "a" would ruin a log.
|
* Names under three characters are skipped: blanking every "a" would ruin a log.
|
||||||
*/
|
*/
|
||||||
fun learnAccounts(loginUsers: java.io.File) {
|
fun learnAccounts(loginUsers: java.io.File) {
|
||||||
val found = ArrayList<Learned>()
|
val found = ArrayList<Regex>()
|
||||||
try {
|
try {
|
||||||
if (loginUsers.isFile) {
|
if (loginUsers.isFile) {
|
||||||
val kv = Regex("\"(AccountName|PersonaName)\"\\s+\"([^\"]*)\"")
|
val kv = Regex("\"(AccountName|PersonaName)\"\\s+\"([^\"]*)\"")
|
||||||
kv.findAll(loginUsers.readText()).map { it.groupValues[2].trim() }.filter { it.length >= 3 }.distinct().forEach { name ->
|
kv.findAll(loginUsers.readText()).map { it.groupValues[2].trim() }.filter { it.length >= 3 }.distinct().forEach { name ->
|
||||||
val needs = name.lowercase().takeIf { name.all { it.code < 0x80 } }
|
found += Regex("(?i)(?<![A-Za-z0-9_])" + Regex.escape(name) + "(?![A-Za-z0-9_])")
|
||||||
found += Learned(Regex("(?i)(?<![A-Za-z0-9_])" + Regex.escape(name) + "(?![A-Za-z0-9_])"), needs)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
@@ -129,7 +125,7 @@ object LogRedactor {
|
|||||||
|
|
||||||
/** This device's public addresses as patterns (see [learnOwnAddresses]); empty until learned. */
|
/** This device's public addresses as patterns (see [learnOwnAddresses]); empty until learned. */
|
||||||
@Volatile
|
@Volatile
|
||||||
private var own: List<Learned> = emptyList()
|
private var own: List<Regex> = emptyList()
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Learns the device's addresses from the link file the app writes for the session
|
* Learns the device's addresses from the link file the app writes for the session
|
||||||
@@ -137,7 +133,7 @@ object LogRedactor {
|
|||||||
* private, link-local and loopback addresses identify nobody and are left out.
|
* private, link-local and loopback addresses identify nobody and are left out.
|
||||||
*/
|
*/
|
||||||
fun learnOwnAddresses(linkFile: java.io.File) {
|
fun learnOwnAddresses(linkFile: java.io.File) {
|
||||||
val found = ArrayList<Learned>()
|
val found = ArrayList<Regex>()
|
||||||
try {
|
try {
|
||||||
if (linkFile.isFile) linkFile.forEachLine { line ->
|
if (linkFile.isFile) linkFile.forEachLine { line ->
|
||||||
val addr = line.trim().takeIf { it.startsWith("addr ") }?.split(Regex("\\s+"))?.getOrNull(1) ?: return@forEachLine
|
val addr = line.trim().takeIf { it.startsWith("addr ") }?.split(Regex("\\s+"))?.getOrNull(1) ?: return@forEachLine
|
||||||
@@ -146,12 +142,9 @@ object LogRedactor {
|
|||||||
val groups = expand6(addr)?.take(4) ?: return@forEachLine
|
val groups = expand6(addr)?.take(4) ?: return@forEachLine
|
||||||
// Any spelling of an address in this /64: leading zeros dropped, :: anywhere after.
|
// Any spelling of an address in this /64: leading zeros dropped, :: anywhere after.
|
||||||
val prefix = groups.joinToString(":") { g -> "0{0,3}" + Regex.escape(g.trimStart('0').ifEmpty { "0" }) }
|
val prefix = groups.joinToString(":") { g -> "0{0,3}" + Regex.escape(g.trimStart('0').ifEmpty { "0" }) }
|
||||||
found += Learned(
|
found += Regex("(?i)(?<![0-9A-Fa-f:])$prefix(?::[0-9A-Fa-f]{0,4}){1,4}(?:%[A-Za-z0-9_.]+)?")
|
||||||
Regex("(?i)(?<![0-9A-Fa-f:])$prefix(?::[0-9A-Fa-f]{0,4}){1,4}(?:%[A-Za-z0-9_.]+)?"),
|
|
||||||
groups[0].trimStart('0').ifEmpty { "0" },
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
"public IPv4" -> found += Learned(Regex("(?<![0-9.])" + Regex.escape(addr) + "(?![0-9.])"), addr)
|
"public IPv4" -> found += Regex("(?<![0-9.])" + Regex.escape(addr) + "(?![0-9.])")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
@@ -270,87 +263,41 @@ object LogRedactor {
|
|||||||
return "$q<redacted:account>$q"
|
return "$q<redacted:account>$q"
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* A line on its way through [redact]. Each rule runs only on a line holding what it cannot match
|
|
||||||
* without - a word, enough separators, a long enough run: most of a Steam log is lines no rule
|
|
||||||
* touches, and a session's logs went through every rule at about a megabyte a second. A line with anything but ASCII in it goes through
|
|
||||||
* every case-insensitive rule, since Android's regex folds case more widely than lowercase().
|
|
||||||
*/
|
|
||||||
private class Line(var text: String) {
|
|
||||||
private val unfolded = text.any { it.code >= 0x80 }
|
|
||||||
private var lower: String? = null
|
|
||||||
|
|
||||||
fun has(vararg words: String): Boolean {
|
|
||||||
if (unfolded) return true
|
|
||||||
val folded = lower ?: text.lowercase().also { lower = it }
|
|
||||||
return words.any { folded.contains(it) }
|
|
||||||
}
|
|
||||||
|
|
||||||
fun set(next: String) {
|
|
||||||
if (next != text) {
|
|
||||||
text = next
|
|
||||||
lower = null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun holds(c: Char, times: Int): Boolean {
|
|
||||||
var n = 0
|
|
||||||
for (ch in text) if (ch == c && ++n >= times) return true
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
inline fun hasRun(length: Int, inRun: (Char) -> Boolean): Boolean {
|
|
||||||
var n = 0
|
|
||||||
for (ch in text) if (!inRun(ch)) n = 0 else if (++n >= length) return true
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun isHex(c: Char) = c in '0'..'9' || c in 'a'..'f' || c in 'A'..'F'
|
|
||||||
|
|
||||||
/** [line] with every credential shape replaced. Null- and exception-safe by construction. */
|
/** [line] with every credential shape replaced. Null- and exception-safe by construction. */
|
||||||
fun redact(line: String): String {
|
fun redact(line: String): String {
|
||||||
if (line.isEmpty()) return line
|
if (line.isEmpty()) return line
|
||||||
return try {
|
return try {
|
||||||
val out = Line(line)
|
var out = line
|
||||||
if (out.has("mac")) out.set(MAC_FIELD.replace(out.text) { "${it.groupValues[1]}<redacted:mac>" })
|
out = MAC_FIELD.replace(out) { "${it.groupValues[1]}<redacted:mac>" }
|
||||||
if (out.holds(':', 5) || out.holds('-', 5)) out.set(MAC.replace(out.text, "<redacted:mac>"))
|
out = MAC.replace(out, "<redacted:mac>")
|
||||||
if (out.has("serial", "android")) out.set(DEVICE_IDENTIFIER.replace(out.text) {
|
out = DEVICE_IDENTIFIER.replace(out) {
|
||||||
val value = it.groupValues[2]
|
val value = it.groupValues[2]
|
||||||
val quote = value.first().takeIf { char -> char == '\"' || char == '\'' }?.toString().orEmpty()
|
val quote = value.first().takeIf { char -> char == '\"' || char == '\'' }?.toString().orEmpty()
|
||||||
"${it.groupValues[1]}${quote}<redacted:serial>${quote}"
|
"${it.groupValues[1]}${quote}<redacted:serial>${quote}"
|
||||||
})
|
|
||||||
if (out.holds('-', 4)) out.set(GUID.replace(out.text, "<redacted:guid>"))
|
|
||||||
if (out.has("jwt")) out.set(JWT_LABELLED.replace(out.text) { "${it.groupValues[1]}<redacted:jwt>" })
|
|
||||||
if ("ey" in out.text) out.set(JWT_BASE64.replace(out.text, "<redacted:jwt>"))
|
|
||||||
if (out.has("token", "auth", "ticket", "sessionid", "steamloginsecure", "api", "machine", "pass", "pwd", "secret")) {
|
|
||||||
out.set(SECRET_KV.replace(out.text) { "${it.groupValues[1]}${it.groupValues[2]}<redacted:token>" })
|
|
||||||
}
|
}
|
||||||
if (out.has("guard", "factor", "2fa")) out.set(GUARD_CODE.replace(out.text) { "${it.groupValues[1]}<redacted:code>" })
|
out = GUID.replace(out, "<redacted:guid>")
|
||||||
if (out.hasRun(32, ::isHex)) out.set(WEBAPI_KEY.replace(out.text, "<redacted:key>"))
|
out = JWT_LABELLED.replace(out) { "${it.groupValues[1]}<redacted:jwt>" }
|
||||||
|
out = JWT_BASE64.replace(out, "<redacted:jwt>")
|
||||||
|
out = SECRET_KV.replace(out) { "${it.groupValues[1]}${it.groupValues[2]}<redacted:token>" }
|
||||||
|
out = GUARD_CODE.replace(out) { "${it.groupValues[1]}<redacted:code>" }
|
||||||
|
out = WEBAPI_KEY.replace(out, "<redacted:key>")
|
||||||
// Mask, not delete: the last four digits let a reader correlate lines to one account.
|
// Mask, not delete: the last four digits let a reader correlate lines to one account.
|
||||||
if ("76561" in out.text) out.set(STEAMID64.replace(out.text) { "${it.groupValues[1]}********${it.groupValues[3]}" })
|
out = STEAMID64.replace(out) { "${it.groupValues[1]}********${it.groupValues[3]}" }
|
||||||
if ("[U:1:" in out.text) out.set(STEAMID3.replace(out.text) { m ->
|
out = STEAMID3.replace(out) { m ->
|
||||||
val id = m.groupValues[1]
|
val id = m.groupValues[1]
|
||||||
"[U:1:${if (id.length > 4) "*".repeat(id.length - 4) + id.takeLast(4) else id}]"
|
"[U:1:${if (id.length > 4) "*".repeat(id.length - 4) + id.takeLast(4) else id}]"
|
||||||
})
|
|
||||||
if (out.has("external")) out.set(EXTERNAL_ADDR.replace(out.text) { "${it.groupValues[1]}<redacted:ip>" })
|
|
||||||
for (r in own) if (r.needs == null || out.has(r.needs)) out.set(r.regex.replace(out.text, "<redacted:ip>"))
|
|
||||||
if (out.has("onloginstatechange")) out.set(LOGIN_STATE.replace(out.text) { "${it.groupValues[1]}<redacted:account>" })
|
|
||||||
if ("OnLoginUsersChanged " in out.text) out.set(LOGIN_USERS.replace(out.text) { "${it.groupValues[1]}<redacted:account>" })
|
|
||||||
if (out.has("account", "user")) {
|
|
||||||
out.set(ACCOUNT_KV.replace(out.text) { "${it.groupValues[1]}${it.groupValues[2]}${quoted(it.groupValues[3])}" })
|
|
||||||
}
|
}
|
||||||
if (out.has("login")) out.set(LOGIN_KV.replace(out.text) { "${it.groupValues[1]}${it.groupValues[2]}${quoted(it.groupValues[3])}" })
|
out = EXTERNAL_ADDR.replace(out) { "${it.groupValues[1]}<redacted:ip>" }
|
||||||
for (r in accounts) if (r.needs == null || out.has(r.needs)) out.set(r.regex.replace(out.text, "<redacted:account>"))
|
for (r in own) out = r.replace(out, "<redacted:ip>")
|
||||||
if ('@' in out.text) out.set(EMAIL.replace(out.text, "<redacted:email>"))
|
out = LOGIN_STATE.replace(out) { "${it.groupValues[1]}<redacted:account>" }
|
||||||
if (out.has("jwt", "token", "ticket", "sessionid", "steamloginsecure", "machineauth")) {
|
out = LOGIN_USERS.replace(out) { "${it.groupValues[1]}<redacted:account>" }
|
||||||
out.set(RESIDUAL.replace(out.text) { "${it.groupValues[1]}=<redacted:token>" })
|
out = ACCOUNT_KV.replace(out) { "${it.groupValues[1]}${it.groupValues[2]}${quoted(it.groupValues[3])}" }
|
||||||
}
|
out = LOGIN_KV.replace(out) { "${it.groupValues[1]}${it.groupValues[2]}${quoted(it.groupValues[3])}" }
|
||||||
if (out.hasRun(88) { it in 'a'..'z' || it in 'A'..'Z' || it in '0'..'9' || it == '_' || it == '-' }) {
|
for (r in accounts) out = r.replace(out, "<redacted:account>")
|
||||||
out.set(LONG_TOKEN.replace(out.text, "<redacted:token>"))
|
out = EMAIL.replace(out, "<redacted:email>")
|
||||||
}
|
out = RESIDUAL.replace(out) { "${it.groupValues[1]}=<redacted:token>" }
|
||||||
out.text
|
out = LONG_TOKEN.replace(out, "<redacted:token>")
|
||||||
|
out
|
||||||
} catch (t: Throwable) {
|
} catch (t: Throwable) {
|
||||||
// A log line is never worth crashing a session over, but an unscrubbed one must not
|
// A log line is never worth crashing a session over, but an unscrubbed one must not
|
||||||
// reach the file either.
|
// reach the file either.
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.droiddeck.launcher.files
|
package com.droiddeck.launcher.files
|
||||||
|
|
||||||
|
import androidx.compose.ui.platform.LocalInspectionMode
|
||||||
import android.content.res.Configuration
|
import android.content.res.Configuration
|
||||||
import androidx.compose.animation.core.animateDpAsState
|
import androidx.compose.animation.core.animateDpAsState
|
||||||
import androidx.compose.foundation.background
|
import androidx.compose.foundation.background
|
||||||
@@ -122,7 +123,8 @@ class RailState internal constructor(
|
|||||||
fun rememberRailState(screenKey: String): RailState {
|
fun rememberRailState(screenKey: String): RailState {
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
// The same file the File Manager keeps its own browse settings in (no androidx.preference here).
|
// The same file the File Manager keeps its own browse settings in (no androidx.preference here).
|
||||||
val prefs = remember { context.getSharedPreferences("file_manager", android.content.Context.MODE_PRIVATE) }
|
val inspecting = LocalInspectionMode.current
|
||||||
|
val prefs = remember { if (inspecting) null else context.getSharedPreferences("file_manager", android.content.Context.MODE_PRIVATE) }
|
||||||
val isLandscape = LocalConfiguration.current.orientation == Configuration.ORIENTATION_LANDSCAPE
|
val isLandscape = LocalConfiguration.current.orientation == Configuration.ORIENTATION_LANDSCAPE
|
||||||
|
|
||||||
val choseKey = "rail_${screenKey}_userChose"
|
val choseKey = "rail_${screenKey}_userChose"
|
||||||
@@ -130,9 +132,9 @@ fun rememberRailState(screenKey: String): RailState {
|
|||||||
|
|
||||||
// Keep the landscape choice in saveable state regardless of orientation so portrait→landscape
|
// Keep the landscape choice in saveable state regardless of orientation so portrait→landscape
|
||||||
// restores it. In portrait we simply report collapsed+locked and ignore it.
|
// restores it. In portrait we simply report collapsed+locked and ignore it.
|
||||||
var userChose by rememberSaveable(screenKey) { mutableStateOf(prefs.getBoolean(choseKey, false)) }
|
var userChose by rememberSaveable(screenKey) { mutableStateOf((prefs?.getBoolean(choseKey, false) ?: false)) }
|
||||||
var landscapeCollapsed by rememberSaveable(screenKey) {
|
var landscapeCollapsed by rememberSaveable(screenKey) {
|
||||||
mutableStateOf(if (prefs.getBoolean(choseKey, false)) prefs.getBoolean(collapsedKey, false) else false)
|
mutableStateOf(if ((prefs?.getBoolean(choseKey, false) ?: false)) (prefs?.getBoolean(collapsedKey, false) ?: false) else false)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!isLandscape) {
|
if (!isLandscape) {
|
||||||
@@ -144,10 +146,7 @@ fun rememberRailState(screenKey: String): RailState {
|
|||||||
onToggle = {
|
onToggle = {
|
||||||
landscapeCollapsed = !landscapeCollapsed
|
landscapeCollapsed = !landscapeCollapsed
|
||||||
userChose = true
|
userChose = true
|
||||||
prefs.edit()
|
prefs?.edit()?.putBoolean(choseKey, true)?.putBoolean(collapsedKey, landscapeCollapsed)?.apply()
|
||||||
.putBoolean(choseKey, true)
|
|
||||||
.putBoolean(collapsedKey, landscapeCollapsed)
|
|
||||||
.apply()
|
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,7 +22,6 @@ class FileManagerActivity : ComponentActivity() {
|
|||||||
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
requestedOrientation = com.droiddeck.launcher.session.SessionPrefs.orientation(this)
|
|
||||||
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
|
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
|
||||||
requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1)
|
requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -69,6 +69,7 @@ import androidx.compose.ui.text.font.FontWeight
|
|||||||
import androidx.compose.ui.text.style.TextOverflow
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.compose.ui.unit.sp
|
import androidx.compose.ui.unit.sp
|
||||||
|
import androidx.compose.ui.platform.LocalInspectionMode
|
||||||
import com.droiddeck.launcher.R
|
import com.droiddeck.launcher.R
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
@@ -187,6 +188,7 @@ internal fun FileItemRow(
|
|||||||
) {
|
) {
|
||||||
val dateFormat = remember { SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()) }
|
val dateFormat = remember { SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()) }
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
|
val inspecting = LocalInspectionMode.current
|
||||||
val isDir = file.isDirectory
|
val isDir = file.isDirectory
|
||||||
val isExe = !isDir && file.name.lowercase().let { it.endsWith(".exe") || it.endsWith(".bat") || it.endsWith(".msi") || it.endsWith(".sh") }
|
val isExe = !isDir && file.name.lowercase().let { it.endsWith(".exe") || it.endsWith(".bat") || it.endsWith(".msi") || it.endsWith(".sh") }
|
||||||
// Image files show a real thumbnail instead of the generic file icon (handy when picking a
|
// Image files show a real thumbnail instead of the generic file icon (handy when picking a
|
||||||
@@ -195,7 +197,7 @@ internal fun FileItemRow(
|
|||||||
|
|
||||||
// For real PE executables, try to pull out the embedded application icon (async, off the main thread).
|
// For real PE executables, try to pull out the embedded application icon (async, off the main thread).
|
||||||
var exeIcon by remember(file.absolutePath) { mutableStateOf<ImageBitmap?>(null) }
|
var exeIcon by remember(file.absolutePath) { mutableStateOf<ImageBitmap?>(null) }
|
||||||
if (!isDir && file.name.lowercase().endsWith(".exe")) {
|
if (!inspecting && !isDir && file.name.lowercase().endsWith(".exe")) {
|
||||||
LaunchedEffect(file.absolutePath) {
|
LaunchedEffect(file.absolutePath) {
|
||||||
val bmp = withContext(Dispatchers.IO) { PeIconExtractor.extract(file) }
|
val bmp = withContext(Dispatchers.IO) { PeIconExtractor.extract(file) }
|
||||||
if (bmp != null) exeIcon = bmp.asImageBitmap()
|
if (bmp != null) exeIcon = bmp.asImageBitmap()
|
||||||
@@ -364,13 +366,15 @@ internal fun FavoritesList(
|
|||||||
onJump: (File) -> Unit,
|
onJump: (File) -> Unit,
|
||||||
onUnpin: (File) -> Unit,
|
onUnpin: (File) -> Unit,
|
||||||
modifier: Modifier = Modifier,
|
modifier: Modifier = Modifier,
|
||||||
|
previewFavorites: List<File> = emptyList(),
|
||||||
) {
|
) {
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
|
val inspecting = LocalInspectionMode.current
|
||||||
val favorites = remember(favTick) {
|
val favorites = remember(favTick) {
|
||||||
FavoritesStore.list(context).map(::File).filter { it.exists() }
|
if (inspecting) previewFavorites else FavoritesStore.list(context).map(::File).filter { it.exists() }
|
||||||
}
|
}
|
||||||
val currentAlreadyPinned = remember(favTick, currentDir.absolutePath) {
|
val currentAlreadyPinned = remember(favTick, currentDir.absolutePath) {
|
||||||
FavoritesStore.isFavorite(context, currentDir.absolutePath)
|
if (inspecting) currentDir in previewFavorites else FavoritesStore.isFavorite(context, currentDir.absolutePath)
|
||||||
}
|
}
|
||||||
|
|
||||||
LazyColumn(modifier = modifier) {
|
LazyColumn(modifier = modifier) {
|
||||||
@@ -545,10 +549,11 @@ internal fun FileGridTile(
|
|||||||
onToggleFavorite: () -> Unit = {},
|
onToggleFavorite: () -> Unit = {},
|
||||||
onProperties: () -> Unit = {},
|
onProperties: () -> Unit = {},
|
||||||
) {
|
) {
|
||||||
|
val inspecting = LocalInspectionMode.current
|
||||||
val isDir = file.isDirectory
|
val isDir = file.isDirectory
|
||||||
val isImage = !isDir && file.extension.lowercase() in IMAGE_THUMB_EXTS
|
val isImage = !isDir && file.extension.lowercase() in IMAGE_THUMB_EXTS
|
||||||
var exeIcon by remember(file.absolutePath) { mutableStateOf<ImageBitmap?>(null) }
|
var exeIcon by remember(file.absolutePath) { mutableStateOf<ImageBitmap?>(null) }
|
||||||
if (!isDir && file.name.lowercase().endsWith(".exe")) {
|
if (!inspecting && !isDir && file.name.lowercase().endsWith(".exe")) {
|
||||||
LaunchedEffect(file.absolutePath) {
|
LaunchedEffect(file.absolutePath) {
|
||||||
val bmp = withContext(Dispatchers.IO) { PeIconExtractor.extract(file) }
|
val bmp = withContext(Dispatchers.IO) { PeIconExtractor.extract(file) }
|
||||||
if (bmp != null) exeIcon = bmp.asImageBitmap()
|
if (bmp != null) exeIcon = bmp.asImageBitmap()
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
package com.droiddeck.launcher.files
|
||||||
|
|
||||||
|
import java.io.File
|
||||||
|
|
||||||
|
/** Metadata for design previews. [FileManagerScreen] ignores it outside inspection mode. */
|
||||||
|
class FileManagerPreviewState(val directory: File, val entries: List<File>, val grid: Boolean = true, val favorites: Boolean = false)
|
||||||
@@ -80,6 +80,7 @@ import androidx.compose.ui.platform.LocalConfiguration
|
|||||||
import androidx.compose.ui.platform.LocalContext
|
import androidx.compose.ui.platform.LocalContext
|
||||||
import androidx.compose.ui.res.pluralStringResource
|
import androidx.compose.ui.res.pluralStringResource
|
||||||
import androidx.compose.ui.res.stringResource
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import androidx.compose.ui.platform.LocalInspectionMode
|
||||||
import com.droiddeck.launcher.R
|
import com.droiddeck.launcher.R
|
||||||
import androidx.compose.ui.platform.LocalLifecycleOwner
|
import androidx.compose.ui.platform.LocalLifecycleOwner
|
||||||
import androidx.lifecycle.Lifecycle
|
import androidx.lifecycle.Lifecycle
|
||||||
@@ -109,8 +110,11 @@ fun FileManagerScreen(
|
|||||||
initialDir: File? = null,
|
initialDir: File? = null,
|
||||||
pickerTitle: String? = null,
|
pickerTitle: String? = null,
|
||||||
onPick: ((File) -> Unit)? = null,
|
onPick: ((File) -> Unit)? = null,
|
||||||
|
preview: FileManagerPreviewState? = null,
|
||||||
) {
|
) {
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
|
val inspecting = LocalInspectionMode.current
|
||||||
|
val sample = preview.takeIf { inspecting }
|
||||||
val scope = rememberCoroutineScope()
|
val scope = rememberCoroutineScope()
|
||||||
|
|
||||||
// Only matching files are shown in pick mode (directories are always shown). Empty = all files.
|
// Only matching files are shown in pick mode (directories are always shown). Empty = all files.
|
||||||
@@ -121,14 +125,15 @@ fun FileManagerScreen(
|
|||||||
return lowerExts.any { name.endsWith(".$it") }
|
return lowerExts.any { name.endsWith(".$it") }
|
||||||
}
|
}
|
||||||
|
|
||||||
val pickPrefs = remember { context.getSharedPreferences("file_manager", android.content.Context.MODE_PRIVATE) }
|
val pickPrefs = remember { if (inspecting) null else context.getSharedPreferences("file_manager", android.content.Context.MODE_PRIVATE) }
|
||||||
val browsePrefs = pickPrefs
|
val browsePrefs = pickPrefs
|
||||||
val rootDir = remember {
|
val rootDir = remember {
|
||||||
// Both modes: honour an explicit caller-supplied start dir (e.g. Log Manager's game-log
|
// Both modes: honour an explicit caller-supplied start dir (e.g. Log Manager's game-log
|
||||||
// folder), else open at the INTERNAL STORAGE ROOT. Selection screens (drive-folder pick,
|
// folder), else open at the INTERNAL STORAGE ROOT. Selection screens (drive-folder pick,
|
||||||
// local component pick, imports) previously defaulted to Download which - combined with the
|
// local component pick, imports) previously defaulted to Download which - combined with the
|
||||||
// currentRoot floor below - trapped users in Download with no way up (reported bug).
|
// currentRoot floor below - trapped users in Download with no way up (reported bug).
|
||||||
initialDir?.takeIf { it.isDirectory } ?: File("/storage/emulated/0")
|
if (inspecting) sample?.directory ?: File("/storage/emulated/0")
|
||||||
|
else initialDir?.takeIf { it.isDirectory } ?: File("/storage/emulated/0")
|
||||||
}
|
}
|
||||||
|
|
||||||
var currentDir by remember { mutableStateOf(rootDir) }
|
var currentDir by remember { mutableStateOf(rootDir) }
|
||||||
@@ -156,7 +161,7 @@ fun FileManagerScreen(
|
|||||||
}
|
}
|
||||||
mutableStateOf(vol)
|
mutableStateOf(vol)
|
||||||
}
|
}
|
||||||
var entries by remember { mutableStateOf(listOf<File>()) }
|
var entries by remember { mutableStateOf(sample?.entries.orEmpty()) }
|
||||||
var selectedEntry by remember { mutableStateOf<File?>(null) }
|
var selectedEntry by remember { mutableStateOf<File?>(null) }
|
||||||
var showMenuFor by remember { mutableStateOf<File?>(null) }
|
var showMenuFor by remember { mutableStateOf<File?>(null) }
|
||||||
// Clipboard holds a LIST so one paste can carry a whole selection. Cut/copy semantics are a
|
// Clipboard holds a LIST so one paste can carry a whole selection. Cut/copy semantics are a
|
||||||
@@ -177,9 +182,9 @@ fun FileManagerScreen(
|
|||||||
// Browse controls. Persisted so the list doesn't reset its order every time you open a folder.
|
// Browse controls. Persisted so the list doesn't reset its order every time you open a folder.
|
||||||
var searchQuery by remember { mutableStateOf("") }
|
var searchQuery by remember { mutableStateOf("") }
|
||||||
var showSearch by remember { mutableStateOf(false) }
|
var showSearch by remember { mutableStateOf(false) }
|
||||||
var sortBy by remember { mutableStateOf(browsePrefs.getString("fmSortBy", "name") ?: "name") }
|
var sortBy by remember { mutableStateOf(browsePrefs?.getString("fmSortBy", "name") ?: "name") }
|
||||||
var sortDesc by remember { mutableStateOf(browsePrefs.getBoolean("fmSortDesc", false)) }
|
var sortDesc by remember { mutableStateOf(browsePrefs?.getBoolean("fmSortDesc", false) ?: false) }
|
||||||
var showHidden by remember { mutableStateOf(browsePrefs.getBoolean("fmShowHidden", true)) }
|
var showHidden by remember { mutableStateOf(browsePrefs?.getBoolean("fmShowHidden", true) ?: true) }
|
||||||
var showSortMenu by remember { mutableStateOf(false) }
|
var showSortMenu by remember { mutableStateOf(false) }
|
||||||
// View mode: list of cards (default) or a thumbnail grid. Density applies to the list only -
|
// View mode: list of cards (default) or a thumbnail grid. Density applies to the list only -
|
||||||
// a grid tile has no second line to compact.
|
// a grid tile has no second line to compact.
|
||||||
@@ -187,9 +192,9 @@ fun FileManagerScreen(
|
|||||||
// choice persists across rotation). Grid is the default - most useful in landscape, and in
|
// choice persists across rotation). Grid is the default - most useful in landscape, and in
|
||||||
// portrait GridCells.Adaptive naturally renders fewer columns (~2). Do NOT force portrait to list:
|
// portrait GridCells.Adaptive naturally renders fewer columns (~2). Do NOT force portrait to list:
|
||||||
// that broke the toggle on-device (tapping it did nothing in portrait).
|
// that broke the toggle on-device (tapping it did nothing in portrait).
|
||||||
var gridView by remember { mutableStateOf(browsePrefs.getBoolean("fmGridView", true)) }
|
var gridView by remember { mutableStateOf(sample?.grid ?: (browsePrefs?.getBoolean("fmGridView", true) ?: true)) }
|
||||||
val showGrid = gridView
|
val showGrid = gridView
|
||||||
var compactRows by remember { mutableStateOf(browsePrefs.getBoolean("fmCompactRows", false)) }
|
var compactRows by remember { mutableStateOf(browsePrefs?.getBoolean("fmCompactRows", false) ?: false) }
|
||||||
var showNewFolderDialog by remember { mutableStateOf(false) }
|
var showNewFolderDialog by remember { mutableStateOf(false) }
|
||||||
var renameTarget by remember { mutableStateOf<File?>(null) }
|
var renameTarget by remember { mutableStateOf<File?>(null) }
|
||||||
// Properties sheet (basic info + Read-only / Hidden toggles) target; null when closed.
|
// Properties sheet (basic info + Read-only / Hidden toggles) target; null when closed.
|
||||||
@@ -203,7 +208,7 @@ fun FileManagerScreen(
|
|||||||
|
|
||||||
// Favorites view: when on, a dedicated bookmarks list replaces the file list.
|
// Favorites view: when on, a dedicated bookmarks list replaces the file list.
|
||||||
// favTick is bumped on any add/remove/toggle so the favorites view + per-row star recompute.
|
// favTick is bumped on any add/remove/toggle so the favorites view + per-row star recompute.
|
||||||
var showFavorites by remember { mutableStateOf(false) }
|
var showFavorites by remember { mutableStateOf(sample?.favorites == true) }
|
||||||
var favTick by remember { mutableIntStateOf(0) }
|
var favTick by remember { mutableIntStateOf(0) }
|
||||||
|
|
||||||
// resetScroll: jump to the top of the list (true for navigation; false for in-place reloads
|
// resetScroll: jump to the top of the list (true for navigation; false for in-place reloads
|
||||||
@@ -211,7 +216,8 @@ fun FileManagerScreen(
|
|||||||
fun loadDirectory(dir: File, resetScroll: Boolean = true) {
|
fun loadDirectory(dir: File, resetScroll: Boolean = true) {
|
||||||
currentDir = dir
|
currentDir = dir
|
||||||
// Remember the browsed directory so the next pick resumes here.
|
// Remember the browsed directory so the next pick resumes here.
|
||||||
if (pickMode) pickPrefs.edit().putString("lastFilePickerDir", dir.absolutePath).apply()
|
if (inspecting) return
|
||||||
|
if (pickMode) pickPrefs?.edit()?.putString("lastFilePickerDir", dir.absolutePath)?.apply()
|
||||||
scope.launch {
|
scope.launch {
|
||||||
val list = withContext(Dispatchers.IO) {
|
val list = withContext(Dispatchers.IO) {
|
||||||
dir.listFiles()?.toList()
|
dir.listFiles()?.toList()
|
||||||
@@ -281,6 +287,7 @@ fun FileManagerScreen(
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun performDelete(file: File) {
|
fun performDelete(file: File) {
|
||||||
|
if (inspecting) return
|
||||||
scope.launch {
|
scope.launch {
|
||||||
isOperationRunning = true
|
isOperationRunning = true
|
||||||
operationLabel = context.getString(R.string.fm_op_deleting)
|
operationLabel = context.getString(R.string.fm_op_deleting)
|
||||||
@@ -302,6 +309,7 @@ fun FileManagerScreen(
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun performPaste() {
|
fun performPaste() {
|
||||||
|
if (inspecting) return
|
||||||
val sources = clipboardFiles
|
val sources = clipboardFiles
|
||||||
if (sources.isEmpty()) return
|
if (sources.isEmpty()) return
|
||||||
val dstDir = currentDir
|
val dstDir = currentDir
|
||||||
@@ -387,6 +395,7 @@ fun FileManagerScreen(
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun performRename(file: File, newName: String) {
|
fun performRename(file: File, newName: String) {
|
||||||
|
if (inspecting) return
|
||||||
val target = File(file.parentFile, newName)
|
val target = File(file.parentFile, newName)
|
||||||
if (target.exists()) {
|
if (target.exists()) {
|
||||||
Toast.makeText(context, context.getString(R.string.fm_already_exists, newName), Toast.LENGTH_SHORT).show()
|
Toast.makeText(context, context.getString(R.string.fm_already_exists, newName), Toast.LENGTH_SHORT).show()
|
||||||
@@ -403,6 +412,7 @@ fun FileManagerScreen(
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun createFolder(parent: File, name: String) {
|
fun createFolder(parent: File, name: String) {
|
||||||
|
if (inspecting) return
|
||||||
val target = File(parent, name)
|
val target = File(parent, name)
|
||||||
if (target.exists()) {
|
if (target.exists()) {
|
||||||
Toast.makeText(context, context.getString(R.string.fm_already_exists, name), Toast.LENGTH_SHORT).show()
|
Toast.makeText(context, context.getString(R.string.fm_already_exists, name), Toast.LENGTH_SHORT).show()
|
||||||
@@ -430,9 +440,9 @@ fun FileManagerScreen(
|
|||||||
lifecycleOwner.lifecycle.addObserver(observer)
|
lifecycleOwner.lifecycle.addObserver(observer)
|
||||||
onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
|
onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
|
||||||
}
|
}
|
||||||
val drives = remember(storageTick) { StorageRoots.list(context) }
|
val drives = remember(storageTick) { if (inspecting) emptyList() else StorageRoots.list(context) }
|
||||||
val linuxRoot = remember(storageTick) {
|
val linuxRoot = remember(storageTick) {
|
||||||
com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context).takeIf { File(it, "usr").isDirectory }
|
if (inspecting) null else com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context).takeIf { File(it, "usr").isDirectory }
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Dialogs ──
|
// ── Dialogs ──
|
||||||
@@ -537,6 +547,7 @@ fun FileManagerScreen(
|
|||||||
pendingBulkDelete = emptyList()
|
pendingBulkDelete = emptyList()
|
||||||
selectionMode = false
|
selectionMode = false
|
||||||
selectedPaths = emptySet()
|
selectedPaths = emptySet()
|
||||||
|
if (inspecting) return@TextButton
|
||||||
operationJob = scope.launch {
|
operationJob = scope.launch {
|
||||||
isOperationRunning = true
|
isOperationRunning = true
|
||||||
var failed = 0
|
var failed = 0
|
||||||
@@ -754,7 +765,7 @@ fun FileManagerScreen(
|
|||||||
}
|
}
|
||||||
IconButton(onClick = {
|
IconButton(onClick = {
|
||||||
gridView = !gridView
|
gridView = !gridView
|
||||||
browsePrefs.edit().putBoolean("fmGridView", gridView).apply()
|
browsePrefs?.edit()?.putBoolean("fmGridView", gridView)?.apply()
|
||||||
}) {
|
}) {
|
||||||
Icon(
|
Icon(
|
||||||
if (gridView) Icons.Filled.ViewList else Icons.Filled.GridView,
|
if (gridView) Icons.Filled.ViewList else Icons.Filled.GridView,
|
||||||
@@ -780,8 +791,8 @@ fun FileManagerScreen(
|
|||||||
// Tapping the active field flips direction; a different
|
// Tapping the active field flips direction; a different
|
||||||
// field switches to it ascending.
|
// field switches to it ascending.
|
||||||
if (sortBy == key) sortDesc = !sortDesc else { sortBy = key; sortDesc = false }
|
if (sortBy == key) sortDesc = !sortDesc else { sortBy = key; sortDesc = false }
|
||||||
browsePrefs.edit().putString("fmSortBy", sortBy)
|
browsePrefs?.edit()?.putString("fmSortBy", sortBy)
|
||||||
.putBoolean("fmSortDesc", sortDesc).apply()
|
?.putBoolean("fmSortDesc", sortDesc)?.apply()
|
||||||
showSortMenu = false
|
showSortMenu = false
|
||||||
loadDirectory(currentDir, resetScroll = false)
|
loadDirectory(currentDir, resetScroll = false)
|
||||||
},
|
},
|
||||||
@@ -792,7 +803,7 @@ fun FileManagerScreen(
|
|||||||
text = { Text(if (compactRows) stringResource(R.string.fm_rows_comfortable) else stringResource(R.string.fm_rows_compact)) },
|
text = { Text(if (compactRows) stringResource(R.string.fm_rows_comfortable) else stringResource(R.string.fm_rows_compact)) },
|
||||||
onClick = {
|
onClick = {
|
||||||
compactRows = !compactRows
|
compactRows = !compactRows
|
||||||
browsePrefs.edit().putBoolean("fmCompactRows", compactRows).apply()
|
browsePrefs?.edit()?.putBoolean("fmCompactRows", compactRows)?.apply()
|
||||||
showSortMenu = false
|
showSortMenu = false
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
@@ -800,7 +811,7 @@ fun FileManagerScreen(
|
|||||||
text = { Text(if (showHidden) stringResource(R.string.fm_hide_hidden) else stringResource(R.string.fm_show_hidden)) },
|
text = { Text(if (showHidden) stringResource(R.string.fm_hide_hidden) else stringResource(R.string.fm_show_hidden)) },
|
||||||
onClick = {
|
onClick = {
|
||||||
showHidden = !showHidden
|
showHidden = !showHidden
|
||||||
browsePrefs.edit().putBoolean("fmShowHidden", showHidden).apply()
|
browsePrefs?.edit()?.putBoolean("fmShowHidden", showHidden)?.apply()
|
||||||
showSortMenu = false
|
showSortMenu = false
|
||||||
loadDirectory(currentDir, resetScroll = false)
|
loadDirectory(currentDir, resetScroll = false)
|
||||||
},
|
},
|
||||||
@@ -1016,15 +1027,15 @@ fun FileManagerScreen(
|
|||||||
linuxRoot?.let { add(locItem(stringResource(R.string.fm_drive_linux), Icons.Filled.Terminal, it)) }
|
linuxRoot?.let { add(locItem(stringResource(R.string.fm_drive_linux), Icons.Filled.Terminal, it)) }
|
||||||
}
|
}
|
||||||
val quickItems = buildList {
|
val quickItems = buildList {
|
||||||
File("/storage/emulated/0/Download").takeIf { it.isDirectory }?.let { add(locItem(stringResource(R.string.fm_rail_downloads), Icons.Filled.Download, it, stringResource(R.string.fm_rail_downloads_short))) }
|
File("/storage/emulated/0/Download").takeIf { !inspecting && it.isDirectory }?.let { add(locItem(stringResource(R.string.fm_rail_downloads), Icons.Filled.Download, it, stringResource(R.string.fm_rail_downloads_short))) }
|
||||||
// The ROMs folder chosen on the main screen: what the session shows as /root/ROMs.
|
// The ROMs folder chosen on the main screen: what the session shows as /root/ROMs.
|
||||||
SessionPrefs.romsDir(context).takeIf { it.isNotEmpty() }?.let(::File)?.takeIf { it.isDirectory }
|
(if (inspecting) "" else SessionPrefs.romsDir(context)).takeIf { it.isNotEmpty() }?.let(::File)?.takeIf { it.isDirectory }
|
||||||
?.let { add(locItem(stringResource(R.string.fm_rail_roms), Icons.Filled.SportsEsports, it)) }
|
?.let { add(locItem(stringResource(R.string.fm_rail_roms), Icons.Filled.SportsEsports, it)) }
|
||||||
// The app's own logs folder: private, which this file manager (the app itself) can read.
|
// The app's own logs folder: private, which this file manager (the app itself) can read.
|
||||||
com.droiddeck.launcher.runtime.LinuxRuntime.logDir(context).takeIf { it.isDirectory }?.let { add(locItem(stringResource(R.string.fm_rail_session_logs), Icons.Filled.Description, it)) }
|
com.droiddeck.launcher.runtime.LinuxRuntime.logDir(context).takeIf { !inspecting && it.isDirectory }?.let { add(locItem(stringResource(R.string.fm_rail_session_logs), Icons.Filled.Description, it)) }
|
||||||
File("/storage/emulated/0/Pictures").takeIf { it.isDirectory }?.let { add(locItem(stringResource(R.string.fm_rail_pictures), Icons.Filled.Image, it)) }
|
File("/storage/emulated/0/Pictures").takeIf { !inspecting && it.isDirectory }?.let { add(locItem(stringResource(R.string.fm_rail_pictures), Icons.Filled.Image, it)) }
|
||||||
}
|
}
|
||||||
val favItems = remember(favTick) { FavoritesStore.list(context).map(::File).filter { it.exists() } }
|
val favItems = remember(favTick) { if (inspecting) sample?.entries.orEmpty().filter { it.isDirectory } else FavoritesStore.list(context).map(::File).filter { it.exists() } }
|
||||||
.map { d -> RailItem(d.name, Icons.Filled.Star, false) { showFavorites = false; openDrive(d) } }
|
.map { d -> RailItem(d.name, Icons.Filled.Star, false) { showFavorites = false; openDrive(d) } }
|
||||||
val locationSections = buildList {
|
val locationSections = buildList {
|
||||||
add(RailSection(stringResource(R.string.fm_rail_storage), storageItems))
|
add(RailSection(stringResource(R.string.fm_rail_storage), storageItems))
|
||||||
@@ -1043,8 +1054,9 @@ fun FileManagerScreen(
|
|||||||
FavoritesList(
|
FavoritesList(
|
||||||
currentDir = currentDir,
|
currentDir = currentDir,
|
||||||
favTick = favTick,
|
favTick = favTick,
|
||||||
|
previewFavorites = sample?.entries.orEmpty().filter { it.isDirectory },
|
||||||
onPinCurrent = {
|
onPinCurrent = {
|
||||||
FavoritesStore.add(context, currentDir.absolutePath)
|
if (!inspecting) FavoritesStore.add(context, currentDir.absolutePath)
|
||||||
favTick++
|
favTick++
|
||||||
Toast.makeText(context, context.getString(R.string.fm_favorite_added, currentDir.name), Toast.LENGTH_SHORT).show()
|
Toast.makeText(context, context.getString(R.string.fm_favorite_added, currentDir.name), Toast.LENGTH_SHORT).show()
|
||||||
},
|
},
|
||||||
@@ -1053,7 +1065,7 @@ fun FileManagerScreen(
|
|||||||
openDrive(dir)
|
openDrive(dir)
|
||||||
},
|
},
|
||||||
onUnpin = { dir ->
|
onUnpin = { dir ->
|
||||||
FavoritesStore.remove(context, dir.absolutePath)
|
if (!inspecting) FavoritesStore.remove(context, dir.absolutePath)
|
||||||
favTick++
|
favTick++
|
||||||
Toast.makeText(context, context.getString(R.string.fm_favorite_removed, dir.name), Toast.LENGTH_SHORT).show()
|
Toast.makeText(context, context.getString(R.string.fm_favorite_removed, dir.name), Toast.LENGTH_SHORT).show()
|
||||||
},
|
},
|
||||||
@@ -1080,7 +1092,7 @@ fun FileManagerScreen(
|
|||||||
}
|
}
|
||||||
items(shownEntries, key = { it.absolutePath }) { file ->
|
items(shownEntries, key = { it.absolutePath }) { file ->
|
||||||
val isFav = remember(file.absolutePath, favTick) {
|
val isFav = remember(file.absolutePath, favTick) {
|
||||||
FavoritesStore.isFavorite(context, file.absolutePath)
|
(!inspecting && FavoritesStore.isFavorite(context, file.absolutePath))
|
||||||
}
|
}
|
||||||
FileGridTile(
|
FileGridTile(
|
||||||
file = file,
|
file = file,
|
||||||
@@ -1108,7 +1120,7 @@ fun FileManagerScreen(
|
|||||||
if (file.isDirectory) loadDirectory(file)
|
if (file.isDirectory) loadDirectory(file)
|
||||||
else if (pickMode) {
|
else if (pickMode) {
|
||||||
if (matchesPickExt(file)) {
|
if (matchesPickExt(file)) {
|
||||||
pickPrefs.edit().putString("lastFilePickerDir", currentDir.absolutePath).apply()
|
pickPrefs?.edit()?.putString("lastFilePickerDir", currentDir.absolutePath)?.apply()
|
||||||
onPick?.invoke(file)
|
onPick?.invoke(file)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1127,7 +1139,7 @@ fun FileManagerScreen(
|
|||||||
onCut = { clipboardFiles = listOf(file); isCutOperation = true; showMenuFor = null },
|
onCut = { clipboardFiles = listOf(file); isCutOperation = true; showMenuFor = null },
|
||||||
onDelete = { selectedEntry = file; showMenuFor = null },
|
onDelete = { selectedEntry = file; showMenuFor = null },
|
||||||
onToggleFavorite = {
|
onToggleFavorite = {
|
||||||
val nowFav = FavoritesStore.toggle(context, file.absolutePath)
|
val nowFav = if (inspecting) false else FavoritesStore.toggle(context, file.absolutePath)
|
||||||
favTick++
|
favTick++
|
||||||
showMenuFor = null
|
showMenuFor = null
|
||||||
Toast.makeText(
|
Toast.makeText(
|
||||||
@@ -1159,7 +1171,7 @@ fun FileManagerScreen(
|
|||||||
val shown = shownEntries
|
val shown = shownEntries
|
||||||
items(shown, key = { it.absolutePath }) { file ->
|
items(shown, key = { it.absolutePath }) { file ->
|
||||||
val isFav = remember(file.absolutePath, favTick) {
|
val isFav = remember(file.absolutePath, favTick) {
|
||||||
FavoritesStore.isFavorite(context, file.absolutePath)
|
(!inspecting && FavoritesStore.isFavorite(context, file.absolutePath))
|
||||||
}
|
}
|
||||||
FileItemRow(
|
FileItemRow(
|
||||||
file = file,
|
file = file,
|
||||||
@@ -1189,7 +1201,7 @@ fun FileManagerScreen(
|
|||||||
if (file.isDirectory) loadDirectory(file)
|
if (file.isDirectory) loadDirectory(file)
|
||||||
else if (pickMode) {
|
else if (pickMode) {
|
||||||
if (matchesPickExt(file)) {
|
if (matchesPickExt(file)) {
|
||||||
pickPrefs.edit().putString("lastFilePickerDir", currentDir.absolutePath).apply()
|
pickPrefs?.edit()?.putString("lastFilePickerDir", currentDir.absolutePath)?.apply()
|
||||||
onPick?.invoke(file)
|
onPick?.invoke(file)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1208,7 +1220,7 @@ fun FileManagerScreen(
|
|||||||
onRename = { renameTarget = file; showMenuFor = null },
|
onRename = { renameTarget = file; showMenuFor = null },
|
||||||
isFavorite = isFav,
|
isFavorite = isFav,
|
||||||
onToggleFavorite = {
|
onToggleFavorite = {
|
||||||
val nowFav = FavoritesStore.toggle(context, file.absolutePath)
|
val nowFav = if (inspecting) false else FavoritesStore.toggle(context, file.absolutePath)
|
||||||
favTick++
|
favTick++
|
||||||
showMenuFor = null
|
showMenuFor = null
|
||||||
Toast.makeText(
|
Toast.makeText(
|
||||||
|
|||||||
@@ -35,7 +35,6 @@ class FilePickerActivity : ComponentActivity() {
|
|||||||
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
requestedOrientation = com.droiddeck.launcher.session.SessionPrefs.orientation(this)
|
|
||||||
// targetSdk 28: the old storage permission is exactly what lets us list the card.
|
// targetSdk 28: the old storage permission is exactly what lets us list the card.
|
||||||
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
|
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
|
||||||
requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1)
|
requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1)
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ import androidx.compose.ui.Alignment
|
|||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.platform.LocalContext
|
import androidx.compose.ui.platform.LocalContext
|
||||||
import androidx.compose.ui.res.stringResource
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import androidx.compose.ui.platform.LocalInspectionMode
|
||||||
import com.droiddeck.launcher.R
|
import com.droiddeck.launcher.R
|
||||||
import androidx.compose.ui.text.font.FontWeight
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
import androidx.compose.ui.text.style.TextOverflow
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
@@ -58,11 +59,13 @@ internal fun FilePropertiesDialog(
|
|||||||
) {
|
) {
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
val scope = rememberCoroutineScope()
|
val scope = rememberCoroutineScope()
|
||||||
|
val inspecting = LocalInspectionMode.current
|
||||||
val dateFormat = remember { SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()) }
|
val dateFormat = remember { SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()) }
|
||||||
var attrs by remember(file.absolutePath) { mutableStateOf<FileAttrState?>(null) }
|
var attrs by remember(file.absolutePath) { mutableStateOf<FileAttrState?>(if (inspecting) FileAttrState(false, false, false) else null) }
|
||||||
// Guards against a second toggle landing while the first is still being applied off-thread.
|
// Guards against a second toggle landing while the first is still being applied off-thread.
|
||||||
var busy by remember(file.absolutePath) { mutableStateOf(false) }
|
var busy by remember(file.absolutePath) { mutableStateOf(false) }
|
||||||
LaunchedEffect(file.absolutePath) {
|
LaunchedEffect(file.absolutePath) {
|
||||||
|
if (inspecting) return@LaunchedEffect
|
||||||
attrs = withContext(Dispatchers.IO) { readFileAttrs(file) }
|
attrs = withContext(Dispatchers.IO) { readFileAttrs(file) }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -101,7 +104,11 @@ internal fun FilePropertiesDialog(
|
|||||||
description = stringResource(R.string.fm_read_only_hint),
|
description = stringResource(R.string.fm_read_only_hint),
|
||||||
checked = state?.readOnly == true,
|
checked = state?.readOnly == true,
|
||||||
enabled = state != null && !busy,
|
enabled = state != null && !busy,
|
||||||
onToggle = { want ->
|
onToggle = toggle@{ want ->
|
||||||
|
if (inspecting) {
|
||||||
|
attrs = attrs?.copy(readOnly = want)
|
||||||
|
return@toggle
|
||||||
|
}
|
||||||
busy = true
|
busy = true
|
||||||
scope.launch {
|
scope.launch {
|
||||||
val ok = withContext(Dispatchers.IO) { setReadOnly(file, want) }
|
val ok = withContext(Dispatchers.IO) { setReadOnly(file, want) }
|
||||||
@@ -125,7 +132,11 @@ internal fun FilePropertiesDialog(
|
|||||||
else stringResource(R.string.fm_hidden_hint),
|
else stringResource(R.string.fm_hidden_hint),
|
||||||
checked = state?.hidden == true,
|
checked = state?.hidden == true,
|
||||||
enabled = state != null && hiddenSupported && !busy,
|
enabled = state != null && hiddenSupported && !busy,
|
||||||
onToggle = { want ->
|
onToggle = toggle@{ want ->
|
||||||
|
if (inspecting) {
|
||||||
|
attrs = attrs?.copy(hidden = want)
|
||||||
|
return@toggle
|
||||||
|
}
|
||||||
busy = true
|
busy = true
|
||||||
scope.launch {
|
scope.launch {
|
||||||
val ok = withContext(Dispatchers.IO) { setHidden(file, want) }
|
val ok = withContext(Dispatchers.IO) { setHidden(file, want) }
|
||||||
|
|||||||
@@ -137,7 +137,8 @@ object AddedGameArt {
|
|||||||
val out = ArrayList<Option>()
|
val out = ArrayList<Option>()
|
||||||
folderImages(game.folder).forEach { out.add(Option(FOLDER, it.path, it.path)) }
|
folderImages(game.folder).forEach { out.add(Option(FOLDER, it.path, it.path)) }
|
||||||
val cache = cacheDir(context, game)
|
val cache = cacheDir(context, game)
|
||||||
val steamId = SteamMatch.resolve(context, game.folder.path, game.exe, game.name, legacy = File(cache, "steam-appid")).appId?.toString()
|
val steamId = runCatching { GameIdentifier.identify(game.exe).appId?.toString() }.getOrNull()
|
||||||
|
?: File(cache, "steam-appid").takeIf { it.isFile }?.readText()?.trim()?.takeIf { it.isNotEmpty() && it != "none" }
|
||||||
val remote = when (slot) { Slot.COVER -> "library_600x900.jpg"; Slot.BACKGROUND -> "library_hero.jpg"; Slot.LOGO -> "logo.png"; Slot.ICON -> null }
|
val remote = when (slot) { Slot.COVER -> "library_600x900.jpg"; Slot.BACKGROUND -> "library_hero.jpg"; Slot.LOGO -> "logo.png"; Slot.ICON -> null }
|
||||||
if (steamId != null && remote != null) {
|
if (steamId != null && remote != null) {
|
||||||
val url = "$CDN$steamId/$remote".takeIf { exists(it) } ?: steamAssetUrl(steamId, remote)
|
val url = "$CDN$steamId/$remote".takeIf { exists(it) } ?: steamAssetUrl(steamId, remote)
|
||||||
@@ -221,11 +222,10 @@ object AddedGameArt {
|
|||||||
val cache = cacheDir(context, game)
|
val cache = cacheDir(context, game)
|
||||||
if (File(cache, "p.jpg").isFile) continue
|
if (File(cache, "p.jpg").isFile) continue
|
||||||
cache.mkdirs()
|
cache.mkdirs()
|
||||||
val match = steamMatch(context, game) { name ->
|
val appId = runCatching { GameIdentifier.identify(game.exe).appId }.getOrNull()
|
||||||
runCatching { search(name) }.onFailure { Log.w(TAG, "${game.name}: store search failed (${it.message})") }.getOrNull()?.toIntOrNull()
|
val id = steamAppId(game.name, appId, File(cache, "steam-appid")) { name ->
|
||||||
|
runCatching { search(name) }.onFailure { Log.w(TAG, "${game.name}: store search failed (${it.message})") }.getOrNull()
|
||||||
}
|
}
|
||||||
val appId = match.appId?.takeIf { match.certainty == SteamMatch.Certainty.FILES }
|
|
||||||
val id = match.appId?.toString()
|
|
||||||
if (id != null && download(id, cache)) changed = true
|
if (id != null && download(id, cache)) changed = true
|
||||||
if (File(cache, "p.jpg").isFile || sgdbKey.isEmpty()) continue
|
if (File(cache, "p.jpg").isFile || sgdbKey.isEmpty()) continue
|
||||||
val gridId = remembered(File(cache, "sgdb-id")) {
|
val gridId = remembered(File(cache, "sgdb-id")) {
|
||||||
@@ -237,13 +237,16 @@ object AddedGameArt {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The game's Steam app, the one record its Windows components use too ([SteamMatch]): what its
|
* The game's Steam appid for its art: the one its files name ([appId]) as it is, else the
|
||||||
* files name, else a store search on its title ([search]) whose result has the same name.
|
* remembered or freshly searched one ([search] on [name]); null for none.
|
||||||
*/
|
*/
|
||||||
internal fun steamMatch(context: Context, game: AddedGames.Game, search: (String) -> Int?): SteamMatch.Match {
|
internal fun steamAppId(name: String, appId: Int?, lookup: File, search: (String) -> String?): String? {
|
||||||
val match = SteamMatch.resolve(context, game.folder.path, game.exe, game.name, legacy = File(cacheDir(context, game), "steam-appid"), search = search)
|
if (appId != null) {
|
||||||
match.appId?.let { Log.i(TAG, "${game.name}: Steam app $it (${match.certainty.name.lowercase()})") }
|
lookup.writeText(appId.toString())
|
||||||
return match
|
Log.i(TAG, "$name: Steam app $appId (from its files)")
|
||||||
|
return appId.toString()
|
||||||
|
}
|
||||||
|
return remembered(lookup) { search(name)?.also { Log.i(TAG, "$name: Steam app $it") } }
|
||||||
}
|
}
|
||||||
|
|
||||||
/** What [marker] remembers (an id, or "none" for a week), else [find]'s answer written to it. */
|
/** What [marker] remembers (an id, or "none" for a week), else [find]'s answer written to it. */
|
||||||
|
|||||||
@@ -43,17 +43,22 @@ object AddedGames {
|
|||||||
fun folderName(): String = folder.name
|
fun folderName(): String = folder.name
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A Games folder an earlier build had, and where the session sees it. */
|
/** One Games folder and where the session sees it. */
|
||||||
class Root(val host: File, val guest: String)
|
class Root(val host: File, val guest: String)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The Games folders earlier builds had, bound into the session at the guest paths they had
|
* The chosen folders with their guest paths: /root/Games/<folder name>, or with a short hash of
|
||||||
* then (/root/Games/<name>), so the games in them (entries now, [GamesFolderMigration]) keep
|
* the host path when two chosen folders share a name (so a folder's guest path, and with it
|
||||||
* their paths and shortcuts. Nothing adds one any more.
|
* every shortcut's appid, does not change when another folder is added or removed).
|
||||||
*/
|
*/
|
||||||
fun roots(context: Context): List<Root> {
|
fun roots(context: Context): List<Root> {
|
||||||
GamesFolderMigration.run(context)
|
val hosts = SessionPrefs.addedGamesDirs(context).map { File(it) }
|
||||||
return SessionPrefs.gameFolderBinds(context).map { (host, guest) -> Root(File(host), guest) }
|
val names = hosts.groupingBy { it.name.lowercase() }.eachCount()
|
||||||
|
return hosts.map { host ->
|
||||||
|
val name = host.name.ifEmpty { "games" }
|
||||||
|
val guestName = if ((names[name.lowercase()] ?: 0) > 1) name + "-" + "%08x".format(CRC32().apply { update(host.path.toByteArray()) }.value).take(4) else name
|
||||||
|
Root(host, "$GUEST_DIR/$guestName")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private val SKIP = Regex(
|
private val SKIP = Regex(
|
||||||
@@ -93,26 +98,18 @@ object AddedGames {
|
|||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The .exe files a game folder offers, best first ([GameExePicker]); declared Store exes lead. */
|
/** The .exe files a game folder offers, best first ([GameExePicker]); also what its exe box lists, in that order. */
|
||||||
fun candidates(folder: File): List<File> = rank(folder).exes
|
fun candidates(folder: File): List<File> = rank(folder).exes
|
||||||
|
|
||||||
/** [GameExePicker]'s ranking, with a Store-declared executable taking precedence when present. */
|
/** [GameExePicker]'s ranking of [folder], without the names this list never offers. */
|
||||||
fun rank(folder: File): GameExePicker.Ranking {
|
fun rank(folder: File): GameExePicker.Ranking {
|
||||||
val key = "${folder.path}|${folder.lastModified()}"
|
val key = "${folder.path}|${folder.lastModified()}"
|
||||||
val now = System.currentTimeMillis()
|
val now = System.currentTimeMillis()
|
||||||
ranked[key]?.takeIf { now - it.first < RANK_FRESH_MS }?.let { return it.second }
|
ranked[key]?.takeIf { now - it.first < RANK_FRESH_MS }?.let { return it.second }
|
||||||
val guessed = GameExePicker.rank(folder) { !SKIP.matches(it.name) }
|
return GameExePicker.rank(folder) { !SKIP.matches(it.name) }.also {
|
||||||
val declared = declaredExes(folder)
|
if (ranked.size > 256) ranked.clear()
|
||||||
val preferred = declared.map { it.path }.toSet()
|
ranked[key] = now to it
|
||||||
val result = if (declared.isEmpty()) guessed else GameExePicker.Ranking(
|
}
|
||||||
declared + guessed.exes.filter { it.path !in preferred },
|
|
||||||
List(declared.size) { Int.MAX_VALUE } + guessed.exes.zip(guessed.scores)
|
|
||||||
.filter { it.first.path !in preferred }.map { it.second },
|
|
||||||
uncertain = false,
|
|
||||||
)
|
|
||||||
if (ranked.size > 256) ranked.clear()
|
|
||||||
ranked[key] = now to result
|
|
||||||
return result
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A folder's ranking for a minute, so one add (rank, then the game built from it) walks it once. */
|
/** A folder's ranking for a minute, so one add (rank, then the game built from it) walks it once. */
|
||||||
@@ -163,29 +160,10 @@ object AddedGames {
|
|||||||
else -> peName
|
else -> peName
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/** The executables MicrosoftGame.config or appxmanifest.xml declares that exist inside [folder]. */
|
|
||||||
internal fun declaredExes(folder: File): List<File> {
|
|
||||||
val names = DECLARED.flatMap { (file, pattern) ->
|
|
||||||
runCatching { pattern.findAll(File(folder, file).readText()).map { it.groupValues[1] }.toList() }.getOrDefault(emptyList())
|
|
||||||
}
|
|
||||||
val root = runCatching { folder.canonicalPath + File.separator }.getOrNull() ?: return emptyList()
|
|
||||||
return names.asSequence()
|
|
||||||
.map { File(folder, it.trim().replace('\\', '/').trimStart('/')) }
|
|
||||||
.filter { it.name.endsWith(".exe", ignoreCase = true) && !SKIP.matches(it.name) && it.isFile }
|
|
||||||
.filter { runCatching { it.canonicalPath.startsWith(root) }.getOrDefault(false) }
|
|
||||||
.distinctBy { it.path }
|
|
||||||
.toList()
|
|
||||||
}
|
|
||||||
|
|
||||||
private val DECLARED = listOf(
|
|
||||||
"MicrosoftGame.config" to Regex("<Executable\\b[^>]*?\\bName\\s*=\\s*\"([^\"]+)\"", RegexOption.IGNORE_CASE),
|
|
||||||
"appxmanifest.xml" to Regex("<Application\\b[^>]*?\\bExecutable\\s*=\\s*\"([^\"]+)\"", RegexOption.IGNORE_CASE),
|
|
||||||
)
|
|
||||||
|
|
||||||
fun scan(context: Context): List<Game> {
|
fun scan(context: Context): List<Game> {
|
||||||
val out = ArrayList<Game>()
|
val out = ArrayList<Game>()
|
||||||
GamesFolderMigration.run(context)
|
val folders = roots(context).map { it.host } + listOfNotNull(
|
||||||
val folders = listOfNotNull(
|
|
||||||
GameStorage.effective(context)?.let { File(it.path) },
|
GameStorage.effective(context)?.let { File(it.path) },
|
||||||
GameStorage.effective(context)?.let { File(it.path, "steamapps/common") },
|
GameStorage.effective(context)?.let { File(it.path, "steamapps/common") },
|
||||||
)
|
)
|
||||||
@@ -259,19 +237,17 @@ object AddedGames {
|
|||||||
private fun inside(path: String, folder: String) = path.startsWith(folder.trimEnd('/') + "/")
|
private fun inside(path: String, folder: String) = path.startsWith(folder.trimEnd('/') + "/")
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The game folder [exe] belongs to, without a scan: an entry from the Games tab (Games folders
|
* The game folder [exe] belongs to, without a scan: an entry from the Games tab, a removed
|
||||||
* of earlier builds included), a removed game, a store install, or the first-level folder under
|
* game, a store install, or the first-level folder under a Games folder (or the Steam library)
|
||||||
* the Steam library that holds it. Null when it is in none.
|
* that holds it. Null when it is in none.
|
||||||
*/
|
*/
|
||||||
private fun ownerFolder(context: Context, exe: File): File? {
|
private fun ownerFolder(context: Context, exe: File): File? {
|
||||||
GamesFolderMigration.run(context)
|
|
||||||
val path = canonical(exe)
|
val path = canonical(exe)
|
||||||
fun holds(f: File) = inside(path, canonical(f))
|
fun holds(f: File) = inside(path, canonical(f))
|
||||||
AddedExes.list(context).map { File(it.folder) }.firstOrNull(::holds)?.let { return it }
|
AddedExes.list(context).map { File(it.folder) }.firstOrNull(::holds)?.let { return it }
|
||||||
SessionPrefs.removedAddedGames(context).map { File(it) }.firstOrNull(::holds)?.let { return it }
|
SessionPrefs.removedAddedGames(context).map { File(it) }.firstOrNull(::holds)?.let { return it }
|
||||||
StoreInstallRoot.gameFolders(context).firstOrNull(::holds)?.let { return it }
|
StoreInstallRoot.gameFolders(context).firstOrNull(::holds)?.let { return it }
|
||||||
// Games folders of earlier builds are entries now, found above.
|
val dirs = roots(context).map { it.host } + listOfNotNull(
|
||||||
val dirs = listOfNotNull(
|
|
||||||
GameStorage.effective(context)?.let { File(it.path, "steamapps/common") },
|
GameStorage.effective(context)?.let { File(it.path, "steamapps/common") },
|
||||||
GameStorage.effective(context)?.let { File(it.path) },
|
GameStorage.effective(context)?.let { File(it.path) },
|
||||||
)
|
)
|
||||||
@@ -345,13 +321,12 @@ object AddedGames {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* The game folders already listed, without building any game: the first-level folders of the
|
* The game folders already listed, without building any game: the first-level folders of the
|
||||||
* Steam library (as [scan] walks them), the Games tab's entries (Games folders of earlier builds
|
* Games folders and the Steam library (as [scan] walks them), the Games tab's entries and the
|
||||||
* included) and the store installs. Canonical paths; removed games are left out.
|
* store installs. Canonical paths; removed games are left out.
|
||||||
*/
|
*/
|
||||||
private fun listedFolders(context: Context, removed: Set<String>): List<String> {
|
private fun listedFolders(context: Context, removed: Set<String>): List<String> {
|
||||||
val out = ArrayList<String>()
|
val out = ArrayList<String>()
|
||||||
GamesFolderMigration.run(context)
|
val dirs = roots(context).map { it.host } + listOfNotNull(
|
||||||
val dirs = listOfNotNull(
|
|
||||||
GameStorage.effective(context)?.let { File(it.path) },
|
GameStorage.effective(context)?.let { File(it.path) },
|
||||||
GameStorage.effective(context)?.let { File(it.path, "steamapps/common") },
|
GameStorage.effective(context)?.let { File(it.path, "steamapps/common") },
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,419 +0,0 @@
|
|||||||
package com.droiddeck.launcher.frontend
|
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
import android.net.ConnectivityManager
|
|
||||||
import android.os.Build
|
|
||||||
import android.os.PowerManager
|
|
||||||
import android.util.AtomicFile
|
|
||||||
import android.util.Log
|
|
||||||
import androidx.annotation.VisibleForTesting
|
|
||||||
import com.droiddeck.launcher.session.SessionState
|
|
||||||
import com.droiddeck.launcher.session.WinComponents
|
|
||||||
import com.droiddeck.launcher.stores.StoreGameSidecar
|
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
|
||||||
import org.json.JSONArray
|
|
||||||
import org.json.JSONObject
|
|
||||||
import java.io.File
|
|
||||||
import java.util.concurrent.PriorityBlockingQueue
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Turns on, per game, the Windows components its source's list names ([WinCompSources]). Only the
|
|
||||||
* findings marked auto are turned on, only the ones that install here, and never one the user
|
|
||||||
* switched off: the user's switches are kept apart ([WinComponents.Selection.user]) and win.
|
|
||||||
*
|
|
||||||
* All the work is done by one background thread (low priority, so are the runtime helpers it
|
|
||||||
* starts), one job at a time from one queue: working out a game's list (kept, so a page opens on
|
|
||||||
* it) and downloading a component (each once, whichever games want it). The queue waits while a
|
|
||||||
* session runs; jobs nobody asked for (the start-up sweep, a game being launched) also wait on
|
|
||||||
* battery saver, a warm device or a metered network. Nothing here runs on the caller's thread.
|
|
||||||
*/
|
|
||||||
object AutoComponents {
|
|
||||||
private const val TAG = "AutoComponents"
|
|
||||||
|
|
||||||
/** The key a game's picks are kept under: the appid its prefix is named after. */
|
|
||||||
fun appKey(game: Library.SteamGame): String? =
|
|
||||||
if (game.library == Library.ADDED) Integer.toUnsignedString(game.appId) else game.appId.takeIf { it > 0 }?.toString()
|
|
||||||
|
|
||||||
/**
|
|
||||||
* What turns on by itself for [findings], given [catalog] and what is [installed]: the catalog
|
|
||||||
* name each auto finding installs as, with its reason. A component that needs a Windows
|
|
||||||
* installer, or is not in the catalog, stays out (the editor lists it as a suggestion).
|
|
||||||
*/
|
|
||||||
fun autoPicks(findings: List<WinCompSources.Finding>, catalog: Map<String, WinComponents.Component>): Map<String, WinComponents.AutoReason> {
|
|
||||||
val out = LinkedHashMap<String, WinComponents.AutoReason>()
|
|
||||||
for (f in findings) {
|
|
||||||
if (!f.auto || f.component == null) continue
|
|
||||||
val id = WinComponents.installable(f.component, catalog)
|
|
||||||
val c = catalog[id] ?: continue
|
|
||||||
if (WinComponents.support(c, catalog) != WinComponents.Support.READY) continue
|
|
||||||
if (id !in out) out[id] = WinComponents.AutoReason(f.origin.name, listOf(f.original) + f.args)
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- seams for tests ----
|
|
||||||
@VisibleForTesting internal var catalogOf: (Context, Boolean) -> List<WinComponents.Component>? =
|
|
||||||
{ c, network -> if (network) WinComponents.fetch(c) else WinComponents.cached(c) }
|
|
||||||
@VisibleForTesting internal var installedOf: (Context) -> Set<String> = { WinComponents.installedIds(it).toSet() }
|
|
||||||
@VisibleForTesting internal var installer: (Context, WinComponents.Component, Map<String, WinComponents.Component>, (WinComponents.Progress) -> Unit) -> String? =
|
|
||||||
{ c, comp, all, progress -> WinComponents.install(c, comp, all, progress) }
|
|
||||||
@VisibleForTesting internal var sessionRunning: () -> Boolean = { SessionState.running }
|
|
||||||
/** Battery saver, a warm device or a metered network: no work nobody asked for. */
|
|
||||||
@VisibleForTesting internal var unfavourable: (Context) -> Boolean = { c -> constrained(c) }
|
|
||||||
/** A usable network: a download waits for one. */
|
|
||||||
@VisibleForTesting internal var online: (Context) -> Boolean = { c -> isOnline(c) }
|
|
||||||
/** Tests run the queue on the caller's thread ([drain]) instead of the worker. */
|
|
||||||
@VisibleForTesting @Volatile internal var runNow = false
|
|
||||||
|
|
||||||
/** Bumped whenever a game's list or automatic components change, so an open page reads them again. */
|
|
||||||
val changes = MutableStateFlow(0)
|
|
||||||
|
|
||||||
/** The components downloading for an automatic pick right now, with their progress. */
|
|
||||||
val downloading = MutableStateFlow<Map<String, WinComponents.Progress>>(emptyMap())
|
|
||||||
|
|
||||||
/** Games (by [appKey]) whose list is queued or being worked out: a page waits on it. */
|
|
||||||
val pendingGames = MutableStateFlow<Set<String>>(emptySet())
|
|
||||||
|
|
||||||
/** Components queued for an automatic pick, not yet downloaded. */
|
|
||||||
val pendingComponents = MutableStateFlow<Set<String>>(emptySet())
|
|
||||||
|
|
||||||
private fun mark(job: Job, on: Boolean) {
|
|
||||||
if (job.pics != null) return
|
|
||||||
val flow = if (job.component != null) pendingComponents else pendingGames
|
|
||||||
val id = job.component ?: job.game?.let { appKey(it) } ?: return
|
|
||||||
flow.value = if (on) flow.value + id else flow.value - id
|
|
||||||
}
|
|
||||||
|
|
||||||
/** One piece of work: a game's list ([game]) or one component's download ([component]). [asked]: the user is waiting on it. */
|
|
||||||
internal class Job(
|
|
||||||
val game: Library.SteamGame?, val component: String?, val asked: Boolean, val seq: Long, val pics: List<Int>? = null,
|
|
||||||
/** For a game Steam installed during the running session: may run in it, unless a game is running. */
|
|
||||||
val inSession: Boolean = false,
|
|
||||||
) {
|
|
||||||
val key get() = when {
|
|
||||||
pics != null -> "pics"
|
|
||||||
component != null -> "c:$component"
|
|
||||||
else -> "g:" + (game?.let { appKey(it) } ?: "")
|
|
||||||
}
|
|
||||||
/** Needs the network: a download, or Steam asked anonymously. */
|
|
||||||
val online get() = component != null || pics != null
|
|
||||||
}
|
|
||||||
|
|
||||||
private val seq = java.util.concurrent.atomic.AtomicLong()
|
|
||||||
/** What the user asked for first, then in the order queued. */
|
|
||||||
private val jobs = PriorityBlockingQueue<Job>(16, compareByDescending<Job> { it.asked }.thenBy { it.seq })
|
|
||||||
@Volatile private var draining = false
|
|
||||||
private val queuedKeys = java.util.Collections.synchronizedSet(HashSet<String>())
|
|
||||||
/** The games waiting on a component's download, to turn it on for when it lands. */
|
|
||||||
private val waiting = HashMap<String, MutableList<Library.SteamGame>>()
|
|
||||||
@Volatile private var worker: Thread? = null
|
|
||||||
private const val PAUSE_MS = 15_000L
|
|
||||||
|
|
||||||
/**
|
|
||||||
* [game]'s list worked out again on the worker, and its components queued: [asked] when the
|
|
||||||
* user is waiting (its page is open, or they installed or added it).
|
|
||||||
*/
|
|
||||||
fun queueGame(context: Context, game: Library.SteamGame, asked: Boolean) {
|
|
||||||
if (appKey(game) == null) return
|
|
||||||
enqueue(context, Job(game, null, asked, seq.incrementAndGet()))
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun queueDownload(context: Context, id: String, asked: Boolean, inSession: Boolean = false) =
|
|
||||||
enqueue(context, Job(null, id, asked, seq.incrementAndGet(), inSession = inSession))
|
|
||||||
|
|
||||||
/** Adds [job] unless the same one is queued (a game or a component, once each). */
|
|
||||||
private fun enqueue(context: Context, job: Job) {
|
|
||||||
if (!queuedKeys.add(job.key)) {
|
|
||||||
// Asked for now: ahead of what nobody asked for, so the open page does not wait behind the sweep.
|
|
||||||
if (job.asked && jobs.removeIf { it.key == job.key && !it.asked }) jobs.add(job)
|
|
||||||
if (runNow && !draining) drain(context)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (job.component != null) Log.i(TAG, "wincomp: queued ${job.component}")
|
|
||||||
mark(job, true)
|
|
||||||
jobs.add(job)
|
|
||||||
if (runNow) { if (!draining) drain(context) } else ensureWorker(context.applicationContext)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Whether [job] has to wait: always while a session runs; one nobody asked for also when it is unfavourable. */
|
|
||||||
internal fun mustWait(context: Context, job: Job): Boolean =
|
|
||||||
if (job.inSession && sessionRunning()) gameRunning() || (job.online && !online(context))
|
|
||||||
else sessionRunning() || (job.online && !online(context)) || (!job.asked && unfavourable(context))
|
|
||||||
|
|
||||||
/** A game is running in the session (Steam's reaper, or Proton waiting on its game). */
|
|
||||||
@VisibleForTesting internal var gameRunning: () -> Boolean = { gameProcessRunning() }
|
|
||||||
|
|
||||||
private fun gameProcessRunning(): Boolean = File("/proc").listFiles()?.any { p ->
|
|
||||||
p.name.all(Char::isDigit) && runCatching { String(File(p, "cmdline").readBytes()).replace('\u0000', ' ') }.getOrNull()
|
|
||||||
?.let { it.contains("SteamLaunch AppId=") || it.contains("proton waitforexitandrun") } == true
|
|
||||||
} == true
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A game Steam installed during the running session: its list worked out and its components
|
|
||||||
* readied in the session (one job, low priority), so a launch right after finds them; it
|
|
||||||
* waits while a game runs. All other work stays paused until the session ends.
|
|
||||||
*/
|
|
||||||
fun queueInSession(context: Context, game: Library.SteamGame) {
|
|
||||||
if (appKey(game) == null) return
|
|
||||||
enqueue(context, Job(game, null, true, seq.incrementAndGet(), inSession = true))
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Runs the queued jobs on this thread until the queue is empty or the next one has to wait. Tests. */
|
|
||||||
@VisibleForTesting
|
|
||||||
internal fun drain(context: Context) {
|
|
||||||
draining = true
|
|
||||||
try {
|
|
||||||
while (true) {
|
|
||||||
val job = next(context) ?: return
|
|
||||||
queuedKeys.remove(job.key)
|
|
||||||
run(context, job)
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
draining = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The first job in order that may run now, taken off the queue; null when none may. */
|
|
||||||
private fun next(context: Context): Job? = synchronized(jobs) {
|
|
||||||
val job = jobs.sortedWith(order).firstOrNull { !mustWait(context, it) } ?: return null
|
|
||||||
jobs.remove(job)
|
|
||||||
job
|
|
||||||
}
|
|
||||||
|
|
||||||
private val order = compareByDescending<Job> { it.asked }.thenBy { it.seq }
|
|
||||||
|
|
||||||
@VisibleForTesting internal fun queued(): List<String> = jobs.sortedWith(compareByDescending<Job> { it.asked }.thenBy { it.seq }).map { it.key }
|
|
||||||
|
|
||||||
@Synchronized
|
|
||||||
private fun ensureWorker(app: Context) {
|
|
||||||
if (worker?.isAlive == true) return
|
|
||||||
worker = Thread({
|
|
||||||
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND)
|
|
||||||
while (true) {
|
|
||||||
// Something queued, then the first that may run (one for a game installed in the
|
|
||||||
// session goes ahead of paused work); else a look again in a while.
|
|
||||||
try { jobs.put(jobs.take()) } catch (e: InterruptedException) { return@Thread }
|
|
||||||
val job = next(app)
|
|
||||||
if (job == null) {
|
|
||||||
try { Thread.sleep(PAUSE_MS) } catch (e: InterruptedException) { return@Thread }
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
queuedKeys.remove(job.key)
|
|
||||||
WinComponents.background { run(app, job) }
|
|
||||||
}
|
|
||||||
}, "auto-components").apply { isDaemon = true; start() }
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun run(context: Context, job: Job) {
|
|
||||||
try {
|
|
||||||
when {
|
|
||||||
job.pics != null -> SteamAppInfo.lookup(context, job.pics)
|
|
||||||
job.component != null -> download(context, job.component, job.asked, job.inSession)
|
|
||||||
else -> job.game?.let { apply(context, it, job.asked, job.inSession) }
|
|
||||||
}
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Log.w(TAG, "wincomp: ${job.key}: ${e.javaClass.simpleName}: ${e.message}")
|
|
||||||
} finally {
|
|
||||||
mark(job, false)
|
|
||||||
changes.value = changes.value + 1
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* [game]'s list (worked out again only when what it is read from changed), its automatic
|
|
||||||
* components that are downloaded turned on, and the rest queued for download.
|
|
||||||
*/
|
|
||||||
private fun apply(context: Context, game: Library.SteamGame, asked: Boolean, inSession: Boolean = false) {
|
|
||||||
val key = appKey(game) ?: return
|
|
||||||
val folder = game.gameFiles
|
|
||||||
if (game.library == Library.ADDED && game.source == Library.ADDED && folder != null && SteamMatch.get(context, folder.path) == null) {
|
|
||||||
AddedGames.single(context, folder.path)?.let { SteamMatch.resolve(context, folder.path, it.exe, it.name) }
|
|
||||||
}
|
|
||||||
// A GOG or Epic game installed before its sidecar kept the store's list: read it once from the store.
|
|
||||||
val store = com.droiddeck.launcher.stores.Store.byId(game.source)
|
|
||||||
if (folder != null && (store == com.droiddeck.launcher.stores.Store.GOG || store == com.droiddeck.launcher.stores.Store.EPIC)) StoreListBackfill.fill(context, folder)
|
|
||||||
// Its Steam app, when the client never saw it: Steam asked anonymously now if the user is
|
|
||||||
// waiting on this game (a pass over every game asks for all of them in one go, [sweep]).
|
|
||||||
if (asked && online(context)) steamAppOf(context, game)?.let { SteamAppInfo.lookup(context, listOf(it)) }
|
|
||||||
val findings = findings(context, game)
|
|
||||||
val catalog = (catalogOf(context, false) ?: catalogOf(context, true))?.associateBy { it.name } ?: return
|
|
||||||
val wanted = autoPicks(findings, catalog)
|
|
||||||
val user = WinComponents.selection(context, key).user
|
|
||||||
val installed = installedOf(context)
|
|
||||||
val kept = LinkedHashMap<String, WinComponents.AutoReason>()
|
|
||||||
val missing = ArrayList<String>()
|
|
||||||
for ((id, reason) in wanted) {
|
|
||||||
if (user[id] == false) { kept[id] = reason; continue }
|
|
||||||
if (id in installed) { kept[id] = reason; continue }
|
|
||||||
synchronized(waiting) { waiting.getOrPut(id) { ArrayList() }.let { if (it.none { g -> appKey(g) == key }) it.add(game) } }
|
|
||||||
queueDownload(context, id, asked, inSession)
|
|
||||||
missing.add(id)
|
|
||||||
}
|
|
||||||
// In a session the launch waits a little for these (droiddeck-wincomponents reads the list).
|
|
||||||
if (inSession) Pending.set(context, key, missing)
|
|
||||||
val before = WinComponents.selection(context, key).auto
|
|
||||||
if (before.keys != kept.keys) {
|
|
||||||
WinComponents.setAuto(context, key, kept)
|
|
||||||
Log.i(TAG, "${game.name}: on by itself ${kept.keys.joinToString().ifEmpty { "(none)" }}")
|
|
||||||
}
|
|
||||||
changes.value = changes.value + 1
|
|
||||||
}
|
|
||||||
|
|
||||||
/** One component downloaded and installed, then turned on for every game waiting on it. */
|
|
||||||
private fun download(context: Context, id: String, asked: Boolean, inSession: Boolean = false) {
|
|
||||||
val catalog = catalogOf(context, true)?.associateBy { it.name } ?: run { Pending.drop(context, id); return }
|
|
||||||
if (id !in installedOf(context)) {
|
|
||||||
val c = catalog[id] ?: run { Pending.drop(context, id); return }
|
|
||||||
val started = System.currentTimeMillis()
|
|
||||||
downloading.value = downloading.value + (id to WinComponents.Progress(id, "", WinComponents.Phase.DOWNLOAD, -1))
|
|
||||||
val problem = try {
|
|
||||||
installer(context, c, catalog) { p -> downloading.value = downloading.value + (id to p) }
|
|
||||||
} finally {
|
|
||||||
downloading.value = downloading.value - id
|
|
||||||
}
|
|
||||||
if (problem != null) { Log.w(TAG, "wincomp: $id did not install: $problem"); Pending.drop(context, id); return }
|
|
||||||
Log.i(TAG, "wincomp: $id installed in ${System.currentTimeMillis() - started}ms")
|
|
||||||
}
|
|
||||||
val games = synchronized(waiting) { waiting.remove(id).orEmpty() }
|
|
||||||
games.forEach { apply(context, it, asked, inSession) }
|
|
||||||
Pending.drop(context, id)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The components still being readied for games installed in the session, where the launch
|
|
||||||
* reads them (~/.config/droiddeck/wincomponents-pending.json in the runtime).
|
|
||||||
*/
|
|
||||||
internal object Pending {
|
|
||||||
private fun file(context: Context) = File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context), "root/.config/droiddeck/wincomponents-pending.json")
|
|
||||||
|
|
||||||
@Synchronized fun read(context: Context): JSONObject =
|
|
||||||
runCatching { JSONObject(file(context).readText()) }.getOrDefault(JSONObject()).let { it.optJSONObject("games") ?: JSONObject() }
|
|
||||||
|
|
||||||
@Synchronized fun set(context: Context, key: String, ids: List<String>) {
|
|
||||||
val games = read(context)
|
|
||||||
if (ids.isEmpty()) games.remove(key) else games.put(key, JSONArray(ids))
|
|
||||||
write(context, games)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Synchronized fun drop(context: Context, id: String) {
|
|
||||||
val games = read(context)
|
|
||||||
for (k in games.keys().asSequence().toList()) {
|
|
||||||
val left = games.optJSONArray(k)?.let { a -> (0 until a.length()).map { a.optString(it) } }.orEmpty() - id
|
|
||||||
if (left.isEmpty()) games.remove(k) else games.put(k, JSONArray(left))
|
|
||||||
}
|
|
||||||
write(context, games)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun write(context: Context, games: JSONObject) {
|
|
||||||
val f = file(context)
|
|
||||||
runCatching {
|
|
||||||
f.parentFile?.mkdirs()
|
|
||||||
val tmp = File(f.path + ".tmp")
|
|
||||||
tmp.writeText(JSONObject().put("games", games).toString())
|
|
||||||
if (!tmp.renameTo(f)) { f.delete(); tmp.renameTo(f) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- the list, kept per game ----
|
|
||||||
|
|
||||||
private const val FINDINGS = "wincomp-findings.json"
|
|
||||||
|
|
||||||
/** What the list is read from, by modification time: a change means it is worked out again. */
|
|
||||||
internal fun signature(context: Context, game: Library.SteamGame): String {
|
|
||||||
val folder = game.gameFiles
|
|
||||||
val parts = listOfNotNull(
|
|
||||||
folder?.lastModified(),
|
|
||||||
folder?.let { SteamRedists.manifest(it, game.appId)?.lastModified() },
|
|
||||||
folder?.let { StoreGameSidecar.file(it).lastModified() },
|
|
||||||
folder?.let { File(it, "fuel.json").lastModified() },
|
|
||||||
SteamAppInfo.appinfoFile(context).lastModified(),
|
|
||||||
folder?.let { SteamMatch.get(context, it.path) }?.let { "${it.appId}/${it.certainty}" },
|
|
||||||
steamAppOf(context, game)?.let { SteamAppInfo.state(context, it) },
|
|
||||||
)
|
|
||||||
return parts.joinToString("|")
|
|
||||||
}
|
|
||||||
|
|
||||||
/** [game]'s list: the one kept when nothing it is read from changed, else worked out again and kept. Worker only. */
|
|
||||||
internal fun findings(context: Context, game: Library.SteamGame): List<WinCompSources.Finding> {
|
|
||||||
val key = appKey(game) ?: return emptyList()
|
|
||||||
val sig = signature(context, game)
|
|
||||||
val all = readFindings(context)
|
|
||||||
all.optJSONObject(key)?.takeIf { it.optString("sig") == sig }?.let { return decode(it.optJSONArray("findings")) }
|
|
||||||
val fresh = WinCompSources.forGame(context, game)
|
|
||||||
writeFindings(context, all.put(key, JSONObject().put("sig", sig).put("findings", encode(fresh))))
|
|
||||||
return fresh
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The list kept for [appKey], without working anything out; null before the first time. */
|
|
||||||
fun cachedFindings(context: Context, appKey: String): List<WinCompSources.Finding>? =
|
|
||||||
readFindings(context).optJSONObject(appKey)?.let { decode(it.optJSONArray("findings")) }
|
|
||||||
|
|
||||||
@Synchronized
|
|
||||||
private fun readFindings(context: Context): JSONObject =
|
|
||||||
runCatching { JSONObject(AtomicFile(File(context.filesDir, FINDINGS)).readFully().toString(Charsets.UTF_8)) }.getOrDefault(JSONObject())
|
|
||||||
|
|
||||||
@Synchronized
|
|
||||||
private fun writeFindings(context: Context, json: JSONObject) {
|
|
||||||
val atomic = AtomicFile(File(context.filesDir, FINDINGS))
|
|
||||||
val out = atomic.startWrite()
|
|
||||||
try { out.write(json.toString().toByteArray()); atomic.finishWrite(out) } catch (e: Exception) { atomic.failWrite(out) }
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun encode(list: List<WinCompSources.Finding>) = JSONArray().apply {
|
|
||||||
list.forEach { f ->
|
|
||||||
put(JSONObject().put("original", f.original).put("origin", f.origin.name).put("auto", f.auto).put("args", JSONArray(f.args))
|
|
||||||
.apply { f.component?.let { put("component", it) } })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun decode(arr: JSONArray?): List<WinCompSources.Finding> = if (arr == null) emptyList() else (0 until arr.length()).mapNotNull { i ->
|
|
||||||
val o = arr.optJSONObject(i) ?: return@mapNotNull null
|
|
||||||
val origin = runCatching { WinCompSources.Origin.valueOf(o.optString("origin")) }.getOrNull() ?: return@mapNotNull null
|
|
||||||
val args = o.optJSONArray("args")?.let { a -> (0 until a.length()).map { a.optString(it) } }.orEmpty()
|
|
||||||
WinCompSources.Finding(o.optString("component").takeIf { it.isNotEmpty() }, o.optString("original"), origin, o.optBoolean("auto"), args)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- when ----
|
|
||||||
|
|
||||||
/** Before a launch from DroidDeck: nothing but a queued look (it waits for the session to end). */
|
|
||||||
fun beforeLaunch(context: Context, game: Library.SteamGame) = queueGame(context, game, asked = false)
|
|
||||||
|
|
||||||
/** After an install or an add: the user did it, so it does not wait on a metered network. */
|
|
||||||
fun refreshLater(context: Context, game: Library.SteamGame) = queueGame(context, game, asked = true)
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Every game, whatever its source, at app start and after each session (Steam installs its
|
|
||||||
* games without a word to DroidDeck; older GOG and Epic installs get their list read once):
|
|
||||||
* only queued, one game at a time, behind anything asked for, under the same conditions. A
|
|
||||||
* game whose files did not change costs a look at their times.
|
|
||||||
*/
|
|
||||||
fun sweep(context: Context, games: List<Library.SteamGame>) {
|
|
||||||
// First every Steam app these games are that the client never saw, asked of Steam in one
|
|
||||||
// connection; then each game's list.
|
|
||||||
val apps = games.mapNotNull { steamAppOf(context, it) }.distinct()
|
|
||||||
if (apps.isNotEmpty() && SteamAppInfo.needLookup(context, apps).isNotEmpty()) enqueue(context, Job(null, null, false, seq.incrementAndGet(), pics = apps))
|
|
||||||
games.forEach { queueGame(context, it, asked = false) }
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The Steam app whose list a game takes: a Steam game's own, or an added game's match. */
|
|
||||||
private fun steamAppOf(context: Context, game: Library.SteamGame): Int? =
|
|
||||||
if (game.library != Library.ADDED) game.appId.takeIf { it > 0 }
|
|
||||||
else game.gameFiles?.let { SteamMatch.get(context, it.path) }?.appId
|
|
||||||
|
|
||||||
/** The default network is there and validated (reaches the internet). */
|
|
||||||
fun isOnline(context: Context): Boolean {
|
|
||||||
val cm = context.getSystemService(ConnectivityManager::class.java) ?: return false
|
|
||||||
val caps = cm.getNetworkCapabilities(cm.activeNetwork ?: return false) ?: return false
|
|
||||||
return caps.hasCapability(android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET) &&
|
|
||||||
caps.hasCapability(android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Battery saver, thermal status moderate or worse, or a metered network. */
|
|
||||||
private fun constrained(context: Context): Boolean {
|
|
||||||
val power = context.getSystemService(PowerManager::class.java)
|
|
||||||
if (power?.isPowerSaveMode == true) return true
|
|
||||||
if (Build.VERSION.SDK_INT >= 29 && (power?.currentThermalStatus ?: 0) >= PowerManager.THERMAL_STATUS_MODERATE) return true
|
|
||||||
return context.getSystemService(ConnectivityManager::class.java)?.isActiveNetworkMetered == true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -134,9 +134,6 @@ object DependencyDetector {
|
|||||||
val lower = f.name.lowercase(Locale.US)
|
val lower = f.name.lowercase(Locale.US)
|
||||||
if (f.isDirectory) {
|
if (f.isDirectory) {
|
||||||
if (SKIP_DIR_RE.matches(lower)) continue
|
if (SKIP_DIR_RE.matches(lower)) continue
|
||||||
// Unity's <Game>_Data/Managed holds the game's own Mono assemblies, not a .NET
|
|
||||||
// Framework to install.
|
|
||||||
if (lower == "managed" && dir.name.endsWith("_Data", ignoreCase = true)) continue
|
|
||||||
val isRedistDir = insideRedist || REDIST_DIR_RE.matches(lower)
|
val isRedistDir = insideRedist || REDIST_DIR_RE.matches(lower)
|
||||||
if (isRedistDir) consider(f, isDir = true, insideRedist = true)
|
if (isRedistDir) consider(f, isDir = true, insideRedist = true)
|
||||||
// Aggressive coverage: descend redist containers fully, and otherwise sweep the game
|
// Aggressive coverage: descend redist containers fully, and otherwise sweep the game
|
||||||
@@ -160,19 +157,6 @@ object DependencyDetector {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* The catalog components one installer stands for, by its path ("_CommonRedist/vcredist/2015/
|
|
||||||
* vc_redist.x64.exe", "DXSETUP.exe"): what a store's install list names. A VC++ installer
|
|
||||||
* with no year is the latest; empty for one that is none of ours.
|
|
||||||
*/
|
|
||||||
fun componentsFor(path: String): List<String> {
|
|
||||||
val p = path.replace('\\', '/').lowercase(Locale.US)
|
|
||||||
return classify(p, p.substringAfterLast('/'), isDir = false).map { if (it == VCREDIST_LOOSE) "vcredist2022" else it }
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The name the catalog component [name] goes by, for a reason line. */
|
|
||||||
fun label(name: String): String = LABELS[name] ?: name
|
|
||||||
|
|
||||||
/** A loose VC++ installer resolves to the latest 14.x only if no specific vcredistYYYY was found. */
|
/** A loose VC++ installer resolves to the latest 14.x only if no specific vcredistYYYY was found. */
|
||||||
private fun resolveLooseVcredist(hits: LinkedHashMap<String, Recommendation>) {
|
private fun resolveLooseVcredist(hits: LinkedHashMap<String, Recommendation>) {
|
||||||
val loose = hits.remove(VCREDIST_LOOSE) ?: return
|
val loose = hits.remove(VCREDIST_LOOSE) ?: return
|
||||||
|
|||||||
@@ -48,7 +48,7 @@ object GameFileSync {
|
|||||||
check(File(previousStorage).isDirectory) { context.getString(R.string.game_sync_err_previous_sd) }
|
check(File(previousStorage).isDirectory) { context.getString(R.string.game_sync_err_previous_sd) }
|
||||||
}
|
}
|
||||||
storage?.let { check(File(it.path).listFiles() != null) { context.getString(R.string.game_sync_err_game_storage) } }
|
storage?.let { check(File(it.path).listFiles() != null) { context.getString(R.string.game_sync_err_game_storage) } }
|
||||||
AddedGames.roots(context).forEach { check(it.host.listFiles() != null) { context.getString(R.string.game_sync_err_added_games) } }
|
SessionPrefs.addedGamesDirs(context).forEach { check(File(it).listFiles() != null) { context.getString(R.string.game_sync_err_added_games) } }
|
||||||
GameFiles.sync(context, folder, Library.launchableGames(context, strictRead = true))
|
GameFiles.sync(context, folder, Library.launchableGames(context, strictRead = true))
|
||||||
prefs(context).edit().putString("storageSetting", storageSetting).putString("storagePath", storage?.path).apply()
|
prefs(context).edit().putString("storageSetting", storageSetting).putString("storagePath", storage?.path).apply()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,66 +0,0 @@
|
|||||||
package com.droiddeck.launcher.frontend
|
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
import android.util.Log
|
|
||||||
import com.droiddeck.launcher.session.SessionPrefs
|
|
||||||
import com.droiddeck.launcher.stores.StoreGameSidecar
|
|
||||||
import com.droiddeck.launcher.stores.StoreInstallRoot
|
|
||||||
import java.io.File
|
|
||||||
import java.util.zip.CRC32
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Games folders (the roots earlier builds let the user add in Steam settings) become what the
|
|
||||||
* Games tab's "Add all games in this folder" makes: one entry per game ([AddedExes]). Everything
|
|
||||||
* a game had is keyed by its own folder and stays as it was - the chosen exe, the shortcut appid,
|
|
||||||
* the name, Start in, launch options, art choices, a removal. The roots stay bound into the
|
|
||||||
* session at the same guest paths ([SessionPrefs.gameFolderBinds]), so every exe keeps its path
|
|
||||||
* inside the session and every Steam shortcut its target; they are no longer Steam libraries.
|
|
||||||
* Runs whenever saved roots remain (so twice is the same as once) and clears them after.
|
|
||||||
*/
|
|
||||||
object GamesFolderMigration {
|
|
||||||
private const val TAG = "GamesFolderMigration"
|
|
||||||
|
|
||||||
@Synchronized
|
|
||||||
fun run(context: Context) {
|
|
||||||
val dirs = SessionPrefs.addedGamesDirs(context)
|
|
||||||
if (dirs.isEmpty()) return
|
|
||||||
val roots = legacyRoots(SessionPrefs.gameFolderBinds(context).map { it.first } + dirs)
|
|
||||||
.filter { root -> root.host.path in dirs }
|
|
||||||
// The binds first: a game's guest path (and with it the shortcut's appid) depends on them.
|
|
||||||
SessionPrefs.setGameFolderBinds(context, SessionPrefs.gameFolderBinds(context) + roots.map { it.host.path to it.guest })
|
|
||||||
val removed = SessionPrefs.removedAddedGames(context).toSet()
|
|
||||||
val entries = AddedExes.list(context).map { it.folder }.toMutableSet()
|
|
||||||
val storeRoots = StoreInstallRoot.roots(context).map { it.absolutePath }
|
|
||||||
for (root in roots) {
|
|
||||||
var n = 0
|
|
||||||
val steamInstalls = AddedGames.steamInstallDirs(root.host)
|
|
||||||
for (folder in root.host.listFiles { f -> f.isDirectory }?.sortedBy { it.name.lowercase() }.orEmpty()) {
|
|
||||||
if (folder.name.equals("steamapps", ignoreCase = true) || folder.name.lowercase() in steamInstalls) continue
|
|
||||||
if (folder.absolutePath in storeRoots || StoreGameSidecar.read(folder) != null) continue
|
|
||||||
if (folder.path in entries) continue
|
|
||||||
val picked = SessionPrefs.addedGameExe(context, folder.path).takeIf { it.isNotEmpty() }?.let { File(it) }?.takeIf { it.isFile }
|
|
||||||
val exe = picked ?: AddedGames.rank(folder).exes.firstOrNull() ?: continue
|
|
||||||
AddedExes.put(context, AddedExes.Entry(folder.path, exe.path, picked = picked != null))
|
|
||||||
entries.add(folder.path)
|
|
||||||
if (folder.path !in removed) n++
|
|
||||||
}
|
|
||||||
Log.i(TAG, "games: migrated ${root.host} → $n games")
|
|
||||||
}
|
|
||||||
SessionPrefs.setAddedGamesDirs(context, emptyList())
|
|
||||||
SessionPrefs.setGamesFoldersMigrated(context)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The guest paths earlier builds gave Games folders: /root/Games/<folder name>, with a short
|
|
||||||
* hash of the host path when two share a name. Kept exactly, so nothing moves in the session.
|
|
||||||
*/
|
|
||||||
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 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")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -31,8 +31,6 @@ object Library {
|
|||||||
) {
|
) {
|
||||||
/** Decimal form used by Steam links and Android shortcuts, including unsigned shortcut ids. */
|
/** Decimal form used by Steam links and Android shortcuts, including unsigned shortcut ids. */
|
||||||
val gameIdString: String get() = java.lang.Long.toUnsignedString(gameId)
|
val gameIdString: String get() = java.lang.Long.toUnsignedString(gameId)
|
||||||
/** Key used by per-game environment and Windows-component profiles. */
|
|
||||||
val profileKey: String get() = if (library == ADDED) java.lang.Integer.toUnsignedString(appId) else appId.toString()
|
|
||||||
}
|
}
|
||||||
/** The [SteamGame.library] of a game added to the library rather than installed by Steam, and the [SteamGame.source] of a plain added folder. */
|
/** The [SteamGame.library] of a game added to the library rather than installed by Steam, and the [SteamGame.source] of a plain added folder. */
|
||||||
const val ADDED = "added"
|
const val ADDED = "added"
|
||||||
|
|||||||
@@ -1,95 +0,0 @@
|
|||||||
package com.droiddeck.launcher.frontend
|
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
import android.util.Log
|
|
||||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
|
||||||
import com.droiddeck.launcher.session.GameStorage
|
|
||||||
import com.droiddeck.launcher.session.SessionState
|
|
||||||
import java.io.File
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A Steam game whose download finishes during a session, noticed by its appmanifest (a new one,
|
|
||||||
* or StateFlags turning to 4, fully installed) with a light look every five seconds while the
|
|
||||||
* session runs, and handed to [AutoComponents] as a single job that may run in the session, so its
|
|
||||||
* Windows components are in place when the user plays it right after the download.
|
|
||||||
*/
|
|
||||||
object SessionInstalls {
|
|
||||||
private const val TAG = "SessionInstalls"
|
|
||||||
private const val POLL_MS = 5_000L
|
|
||||||
|
|
||||||
/** One appmanifest as read: the app, its name and folder, whether it is fully installed. */
|
|
||||||
class Manifest(val appId: Int, val name: String, val installDir: String, val installed: Boolean, val steamapps: File)
|
|
||||||
|
|
||||||
private val APPID = Regex("\"appid\"\\s*\"(\\d+)\"", RegexOption.IGNORE_CASE)
|
|
||||||
private val NAME = Regex("\"name\"\\s*\"([^\"]*)\"", RegexOption.IGNORE_CASE)
|
|
||||||
private val DIR = Regex("\"installdir\"\\s*\"([^\"]*)\"", RegexOption.IGNORE_CASE)
|
|
||||||
private val STATE = Regex("\"StateFlags\"\\s*\"(\\d+)\"", RegexOption.IGNORE_CASE)
|
|
||||||
|
|
||||||
internal fun parse(file: File): Manifest? = runCatching {
|
|
||||||
val text = file.readText()
|
|
||||||
val id = APPID.find(text)?.groupValues?.get(1)?.toInt() ?: return null
|
|
||||||
Manifest(id, NAME.find(text)?.groupValues?.get(1).orEmpty(), DIR.find(text)?.groupValues?.get(1).orEmpty(),
|
|
||||||
STATE.find(text)?.groupValues?.get(1)?.toIntOrNull() == 4, file.parentFile!!)
|
|
||||||
}.getOrNull()
|
|
||||||
|
|
||||||
/** The libraries the session's client installs to, as host folders. */
|
|
||||||
internal fun steamappsDirs(context: Context): List<File> = listOfNotNull(
|
|
||||||
File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/steamapps"),
|
|
||||||
GameStorage.effective(context)?.let { File(it.path, "steamapps") },
|
|
||||||
).filter { it.isDirectory }
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Keeps what the libraries hold between looks: a manifest re-read only when its time changed.
|
|
||||||
* [poll] returns the apps that became fully installed since the last look (none on the first).
|
|
||||||
*/
|
|
||||||
internal class Watch(private val dirs: () -> List<File>) {
|
|
||||||
private val seen = HashMap<String, Pair<Long, Manifest?>>()
|
|
||||||
private var first = true
|
|
||||||
|
|
||||||
fun poll(): List<Manifest> {
|
|
||||||
val fresh = ArrayList<Manifest>()
|
|
||||||
for (dir in dirs()) for (f in dir.listFiles { x -> x.isFile && x.name.startsWith("appmanifest_") && x.name.endsWith(".acf") }.orEmpty()) {
|
|
||||||
val before = seen[f.path]
|
|
||||||
if (before != null && before.first == f.lastModified()) continue
|
|
||||||
val now = parse(f)
|
|
||||||
seen[f.path] = f.lastModified() to now
|
|
||||||
if (!first && now != null && now.installed && before?.second?.installed != true) fresh.add(now)
|
|
||||||
}
|
|
||||||
first = false
|
|
||||||
return fresh
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A finished install as the Games tab would list it. */
|
|
||||||
internal fun gameOf(m: Manifest): Library.SteamGame =
|
|
||||||
Library.SteamGame(m.appId, m.name.ifEmpty { m.appId.toString() }, null, m.steamapps.parentFile?.path ?: "steam",
|
|
||||||
gameFiles = File(m.steamapps, "common/${m.installDir}"), source = Library.SOURCE_STEAM)
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Looks every five seconds while the session runs, on a thread of its own at background
|
|
||||||
* priority; each finished install becomes one job for its Windows components.
|
|
||||||
*/
|
|
||||||
fun watch(context: Context) {
|
|
||||||
val app = context.applicationContext
|
|
||||||
Thread({
|
|
||||||
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND)
|
|
||||||
val watch = Watch { steamappsDirs(app) }
|
|
||||||
try {
|
|
||||||
// The session is still starting when this is called: up to two minutes for it.
|
|
||||||
var waited = 0L
|
|
||||||
while (!SessionState.running && waited < 120_000L) { Thread.sleep(POLL_MS); waited += POLL_MS }
|
|
||||||
watch.poll()
|
|
||||||
while (SessionState.running) {
|
|
||||||
for (m in watch.poll()) {
|
|
||||||
Log.i(TAG, "wincomp: ${m.name} (${m.appId}) finished installing in the session")
|
|
||||||
AutoComponents.queueInSession(app, gameOf(m))
|
|
||||||
}
|
|
||||||
Thread.sleep(POLL_MS)
|
|
||||||
}
|
|
||||||
} catch (e: InterruptedException) {
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Log.w(TAG, "install watch: ${e.message}")
|
|
||||||
}
|
|
||||||
}, "session-installs").apply { isDaemon = true }.start()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,202 +0,0 @@
|
|||||||
package com.droiddeck.launcher.frontend
|
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
import android.util.AtomicFile
|
|
||||||
import android.util.Log
|
|
||||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
|
||||||
import org.json.JSONArray
|
|
||||||
import org.json.JSONObject
|
|
||||||
import java.io.DataInputStream
|
|
||||||
import java.io.File
|
|
||||||
import java.io.RandomAccessFile
|
|
||||||
import java.nio.ByteBuffer
|
|
||||||
import java.nio.ByteOrder
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Steam's own data for an app, from the client in the runtime: its app-info cache
|
|
||||||
* (Steam/appcache/appinfo.vdf, the PICS data the client keeps for every app it has seen). What is
|
|
||||||
* read is which Steamworks Shared depots (the VC++, DirectX... redistributables of app 228980) the
|
|
||||||
* app's depots point at, and its name. Kept per appid in the app's files, so it works offline; an
|
|
||||||
* app the client has not seen is looked for again after a week.
|
|
||||||
*/
|
|
||||||
object SteamAppInfo {
|
|
||||||
private const val TAG = "SteamAppInfo"
|
|
||||||
private const val CACHE = "steam-appinfo.json"
|
|
||||||
private const val RETRY_AFTER_MS = 7L * 24 * 3600 * 1000
|
|
||||||
/** The Steamworks Shared app the redistributable depots belong to. */
|
|
||||||
const val SHARED_APP = "228980"
|
|
||||||
|
|
||||||
class Info(val name: String, val sharedDepots: List<String>)
|
|
||||||
|
|
||||||
fun appinfoFile(context: Context) = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/appcache/appinfo.vdf")
|
|
||||||
|
|
||||||
/** The shared depots for [appId]: from the cache, else the client's app-info file; null when unknown. */
|
|
||||||
@Synchronized
|
|
||||||
fun info(context: Context, appId: Int, appinfo: File = appinfoFile(context)): Info? {
|
|
||||||
val cacheFile = AtomicFile(File(context.filesDir, CACHE))
|
|
||||||
val cache = runCatching { JSONObject(cacheFile.readFully().toString(Charsets.UTF_8)) }.getOrDefault(JSONObject())
|
|
||||||
val now = System.currentTimeMillis()
|
|
||||||
val mtime = appinfo.lastModified()
|
|
||||||
val known = cache.optJSONObject(appId.toString())
|
|
||||||
known?.let { o ->
|
|
||||||
if (!o.optBoolean("miss")) return Info(o.optString("name"), o.optJSONArray("depots").strings())
|
|
||||||
// A miss is read again when the client has written its cache since (the user may have
|
|
||||||
// looked at the app in Steam), else a week later.
|
|
||||||
if (now - o.optLong("at") < RETRY_AFTER_MS && o.optLong("mtime") == mtime) return null
|
|
||||||
}
|
|
||||||
val read = runCatching { read(appinfo, appId) }.onFailure { Log.w(TAG, "appinfo: ${it.javaClass.simpleName}") }.getOrNull()
|
|
||||||
val entry = JSONObject().put("at", now).put("mtime", mtime)
|
|
||||||
// When Steam was last asked anonymously ([lookup]), kept across re-reads of the file.
|
|
||||||
known?.optLong("picsAt")?.takeIf { it > 0 }?.let { entry.put("picsAt", it) }
|
|
||||||
if (read == null) entry.put("miss", true) else entry.put("name", read.name).put("depots", JSONArray(read.sharedDepots))
|
|
||||||
cache.put(appId.toString(), entry)
|
|
||||||
val out = cacheFile.startWrite()
|
|
||||||
try { out.write(cache.toString().toByteArray()); cacheFile.finishWrite(out) } catch (e: Exception) { cacheFile.failWrite(out) }
|
|
||||||
return read
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Steam asked anonymously ([SteamPics]); a test stands in for it. */
|
|
||||||
@androidx.annotation.VisibleForTesting
|
|
||||||
internal var pics: (List<Int>) -> Map<Int, Info?>? = { SteamPics.lookup(it) }
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Of [appIds], those neither the client's cache (appinfo.vdf, read first: free) nor an earlier
|
|
||||||
* answer has, and that Steam was not asked about anonymously in the past week.
|
|
||||||
*/
|
|
||||||
fun needLookup(context: Context, appIds: List<Int>): List<Int> {
|
|
||||||
val wanted = appIds.distinct().filter { it > 0 && info(context, it) == null }
|
|
||||||
if (wanted.isEmpty()) return emptyList()
|
|
||||||
val cache = cache(context)
|
|
||||||
val now = System.currentTimeMillis()
|
|
||||||
return wanted.filter { now - (cache.optJSONObject(it.toString())?.optLong("picsAt") ?: 0L) >= RETRY_AFTER_MS }
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* [appIds] the client never saw, asked of Steam anonymously in one connection ([SteamPics], in
|
|
||||||
* batches) and every answer kept like the client's: an app's depots and name, or a miss tried
|
|
||||||
* again in a week. False when nothing needed asking or Steam could not be reached. Blocking.
|
|
||||||
*/
|
|
||||||
@Synchronized
|
|
||||||
fun lookup(context: Context, appIds: List<Int>): Boolean {
|
|
||||||
val need = needLookup(context, appIds)
|
|
||||||
if (need.isEmpty()) return false
|
|
||||||
val answers = pics(need) ?: return false
|
|
||||||
val cache = cache(context)
|
|
||||||
val now = System.currentTimeMillis()
|
|
||||||
val mtime = appinfoFile(context).lastModified()
|
|
||||||
for (id in need) {
|
|
||||||
val info = answers[id]
|
|
||||||
val entry = JSONObject().put("at", now).put("mtime", mtime).put("picsAt", now)
|
|
||||||
if (info == null) entry.put("miss", true) else entry.put("name", info.name).put("depots", JSONArray(info.sharedDepots)).put("source", "pics")
|
|
||||||
cache.put(id.toString(), entry)
|
|
||||||
}
|
|
||||||
val file = AtomicFile(File(context.filesDir, CACHE))
|
|
||||||
val out = file.startWrite()
|
|
||||||
try { out.write(cache.toString().toByteArray()); file.finishWrite(out) } catch (e: Exception) { file.failWrite(out) }
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
/** What is kept for [appId]: "hit", "miss" or "none" (part of a game's list fingerprint). */
|
|
||||||
fun state(context: Context, appId: Int): String = cache(context).optJSONObject(appId.toString())?.let { if (it.optBoolean("miss")) "miss" else "hit" } ?: "none"
|
|
||||||
|
|
||||||
private fun cache(context: Context): JSONObject =
|
|
||||||
runCatching { JSONObject(AtomicFile(File(context.filesDir, CACHE)).readFully().toString(Charsets.UTF_8)) }.getOrDefault(JSONObject())
|
|
||||||
|
|
||||||
private fun JSONArray?.strings(): List<String> = if (this == null) emptyList() else (0 until length()).map { optString(it) }
|
|
||||||
|
|
||||||
/**
|
|
||||||
* [appId]'s entry in an appinfo.vdf (versions 27, 28 and 29, the last with its keys in a string
|
|
||||||
* table), or null when the file does not have it.
|
|
||||||
*/
|
|
||||||
internal fun read(file: File, appId: Int): Info? {
|
|
||||||
if (!file.isFile) return null
|
|
||||||
RandomAccessFile(file, "r").use { raf ->
|
|
||||||
val head = ByteBuffer.allocate(16).order(ByteOrder.LITTLE_ENDIAN)
|
|
||||||
raf.readFully(head.array(), 0, 8)
|
|
||||||
val magic = head.getInt(0)
|
|
||||||
val version = magic and 0xFF
|
|
||||||
if (magic ushr 8 != 0x075644 || version !in 0x27..0x29) return null
|
|
||||||
var strings: List<String>? = null
|
|
||||||
var pos = 8L
|
|
||||||
if (version >= 0x29) {
|
|
||||||
raf.readFully(head.array(), 8, 8)
|
|
||||||
val tableAt = head.getLong(8)
|
|
||||||
strings = readStrings(raf, tableAt)
|
|
||||||
pos = 16L
|
|
||||||
}
|
|
||||||
val fixed = if (version >= 0x28) 4 + 4 + 8 + 20 + 4 + 20 else 4 + 4 + 8 + 20 + 4
|
|
||||||
val entry = ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN)
|
|
||||||
while (pos + 8 <= raf.length()) {
|
|
||||||
raf.seek(pos)
|
|
||||||
raf.readFully(entry.array(), 0, 8)
|
|
||||||
val id = entry.getInt(0)
|
|
||||||
val size = entry.getInt(4).toLong() and 0xFFFFFFFFL
|
|
||||||
if (id == 0) return null
|
|
||||||
if (id == appId) {
|
|
||||||
if (size > 64L * 1024 * 1024) return null
|
|
||||||
val body = ByteArray(size.toInt())
|
|
||||||
raf.readFully(body)
|
|
||||||
val kv = ByteBuffer.wrap(body, fixed, body.size - fixed).order(ByteOrder.LITTLE_ENDIAN)
|
|
||||||
val tree = readMap(kv, strings)
|
|
||||||
@Suppress("UNCHECKED_CAST")
|
|
||||||
val app = (tree["appinfo"] as? Map<String, Any>) ?: tree
|
|
||||||
return infoOf(app)
|
|
||||||
}
|
|
||||||
pos += 8 + size
|
|
||||||
}
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Suppress("UNCHECKED_CAST")
|
|
||||||
internal fun infoOf(app: Map<String, Any>): Info {
|
|
||||||
val name = (app["common"] as? Map<String, Any>)?.get("name") as? String ?: ""
|
|
||||||
val depots = (app["depots"] as? Map<String, Any>).orEmpty()
|
|
||||||
val shared = depots.mapNotNull { (key, value) ->
|
|
||||||
val depot = value as? Map<String, Any> ?: return@mapNotNull null
|
|
||||||
key.takeIf { (depot["depotfromapp"] as? String) == SHARED_APP || (key in SteamRedists.DEPOTS && depot["sharedinstall"] != null) }
|
|
||||||
}
|
|
||||||
return Info(name, shared)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun readStrings(raf: RandomAccessFile, at: Long): List<String> {
|
|
||||||
raf.seek(at)
|
|
||||||
val count = Integer.reverseBytes(raf.readInt())
|
|
||||||
val rest = ByteArray((raf.length() - at - 4).toInt().coerceAtLeast(0))
|
|
||||||
raf.readFully(rest)
|
|
||||||
val out = ArrayList<String>(count)
|
|
||||||
var start = 0
|
|
||||||
for (i in rest.indices) {
|
|
||||||
if (out.size == count) break
|
|
||||||
if (rest[i] == 0.toByte()) { out.add(String(rest, start, i - start, Charsets.UTF_8)); start = i + 1 }
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun cstring(b: ByteBuffer): String {
|
|
||||||
val start = b.position()
|
|
||||||
while (b.get() != 0.toByte()) { }
|
|
||||||
val bytes = ByteArray(b.position() - start - 1)
|
|
||||||
b.position(start); b.get(bytes); b.get()
|
|
||||||
return String(bytes, Charsets.UTF_8)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** One binary key-value map, to its end marker; keys by name, or by index into [strings]. */
|
|
||||||
private fun readMap(b: ByteBuffer, strings: List<String>?): Map<String, Any> {
|
|
||||||
val out = LinkedHashMap<String, Any>()
|
|
||||||
while (b.hasRemaining()) {
|
|
||||||
val type = b.get().toInt() and 0xFF
|
|
||||||
if (type == 0x08) return out
|
|
||||||
val key = if (strings != null) strings.getOrElse(b.int) { "" } else cstring(b)
|
|
||||||
when (type) {
|
|
||||||
0x00 -> out[key] = readMap(b, strings)
|
|
||||||
0x01 -> out[key] = cstring(b)
|
|
||||||
0x02 -> out[key] = b.int.toString()
|
|
||||||
0x03 -> out[key] = b.float.toString()
|
|
||||||
0x07, 0x0A -> out[key] = b.long.toString()
|
|
||||||
else -> return out
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,77 +0,0 @@
|
|||||||
package com.droiddeck.launcher.frontend
|
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
import android.util.AtomicFile
|
|
||||||
import org.json.JSONObject
|
|
||||||
import java.io.File
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Which Steam app a game added in DroidDeck is, kept once per game (by its folder) and used by
|
|
||||||
* everything that asks: its art ([AddedGameArt]) and its Windows components ([WinCompSources]),
|
|
||||||
* so the two never disagree.
|
|
||||||
*
|
|
||||||
* [Certainty.FILES]: the game's own files name the appid (steam_appid.txt, also under
|
|
||||||
* steam_settings/ or a parent folder; an emulator ini; Steam's appmanifest) - certain.
|
|
||||||
* [Certainty.NAME]: Steam's store search returned a game of the same name - a guess.
|
|
||||||
* [Certainty.NONE]: neither; a miss is tried again after a week.
|
|
||||||
*/
|
|
||||||
object SteamMatch {
|
|
||||||
enum class Certainty { FILES, NAME, NONE }
|
|
||||||
|
|
||||||
/** [source]: what gave the appid (GameIdentifier's source, or "store search"). */
|
|
||||||
class Match(val appId: Int?, val certainty: Certainty, val source: String, val checkedAt: Long)
|
|
||||||
|
|
||||||
private const val FILE = "steam-matches.json"
|
|
||||||
private const val RETRY_AFTER_MS = 7L * 24 * 3600 * 1000
|
|
||||||
|
|
||||||
private fun store(context: Context) = AtomicFile(File(context.filesDir, FILE))
|
|
||||||
|
|
||||||
@Synchronized
|
|
||||||
private fun all(context: Context): JSONObject =
|
|
||||||
runCatching { JSONObject(store(context).readFully().toString(Charsets.UTF_8)) }.getOrDefault(JSONObject())
|
|
||||||
|
|
||||||
@Synchronized
|
|
||||||
fun get(context: Context, key: String): Match? = all(context).optJSONObject(key)?.let { o ->
|
|
||||||
Match(
|
|
||||||
o.optInt("appId", 0).takeIf { it > 0 },
|
|
||||||
runCatching { Certainty.valueOf(o.optString("certainty")) }.getOrDefault(Certainty.NONE),
|
|
||||||
o.optString("source"), o.optLong("at"),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Synchronized
|
|
||||||
fun put(context: Context, key: String, match: Match) {
|
|
||||||
val json = all(context).put(
|
|
||||||
key, JSONObject().put("certainty", match.certainty.name).put("source", match.source).put("at", match.checkedAt)
|
|
||||||
.apply { match.appId?.let { put("appId", it) } },
|
|
||||||
)
|
|
||||||
val atomic = store(context)
|
|
||||||
val out = atomic.startWrite()
|
|
||||||
try { out.write(json.toString().toByteArray()); atomic.finishWrite(out) } catch (e: Exception) { atomic.failWrite(out) }
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The match for the game in [key] (its folder), [exe] its exe and [name] its title: its files
|
|
||||||
* first, always read again; else the one kept (a name match stays, a miss for a week); else
|
|
||||||
* [legacy], an appid an earlier build's art lookup kept; else [search] on the name, when given.
|
|
||||||
* Blocking ([search] asks the network).
|
|
||||||
*/
|
|
||||||
fun resolve(context: Context, key: String, exe: File, name: String, legacy: File? = null, search: ((String) -> Int?)? = null): Match {
|
|
||||||
val now = System.currentTimeMillis()
|
|
||||||
val identity = runCatching { GameIdentifier.identify(exe) }.getOrNull()
|
|
||||||
identity?.appId?.let { id ->
|
|
||||||
return Match(id, Certainty.FILES, identity.source.name.lowercase(), now).also { put(context, key, it) }
|
|
||||||
}
|
|
||||||
val known = get(context, key)
|
|
||||||
if (known != null && known.certainty == Certainty.NAME) return known
|
|
||||||
if (known != null && known.certainty == Certainty.NONE && now - known.checkedAt < RETRY_AFTER_MS) return known
|
|
||||||
legacy?.takeIf { it.isFile }?.let { runCatching { it.readText().trim().toInt() }.getOrNull() }?.takeIf { it > 0 }?.let { id ->
|
|
||||||
return Match(id, Certainty.NAME, "store search", now).also { put(context, key, it) }
|
|
||||||
}
|
|
||||||
if (search == null) return known?.takeIf { it.certainty != Certainty.FILES } ?: Match(null, Certainty.NONE, "", 0)
|
|
||||||
val id = runCatching { search(name) }.getOrNull()
|
|
||||||
val match = if (id != null && id > 0) Match(id, Certainty.NAME, "store search", now) else Match(null, Certainty.NONE, "", now)
|
|
||||||
put(context, key, match)
|
|
||||||
return match
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,334 +0,0 @@
|
|||||||
package com.droiddeck.launcher.frontend
|
|
||||||
|
|
||||||
import android.util.Log
|
|
||||||
import androidx.annotation.VisibleForTesting
|
|
||||||
import org.json.JSONObject
|
|
||||||
import java.io.ByteArrayInputStream
|
|
||||||
import java.io.ByteArrayOutputStream
|
|
||||||
import java.io.DataInputStream
|
|
||||||
import java.io.IOException
|
|
||||||
import java.io.InputStream
|
|
||||||
import java.io.OutputStream
|
|
||||||
import java.net.HttpURLConnection
|
|
||||||
import java.net.URL
|
|
||||||
import java.nio.ByteBuffer
|
|
||||||
import java.nio.ByteOrder
|
|
||||||
import java.security.SecureRandom
|
|
||||||
import java.util.zip.GZIPInputStream
|
|
||||||
import javax.net.ssl.SSLSocket
|
|
||||||
import javax.net.ssl.SSLSocketFactory
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Steam's own app info (PICS) for apps the client in the runtime has never seen, asked of Steam
|
|
||||||
* anonymously: a connection to one of Steam's connection managers (the list from Steam's public
|
|
||||||
* ISteamDirectory/GetCMListForConnect, the WebSocket transport Steam's web clients use), an
|
|
||||||
* anonymous logon - no account, nothing of the user's Steam sign-in - a request for the apps'
|
|
||||||
* access tokens and then their product info, the app KeyValues read for their Steamworks Shared
|
|
||||||
* depots and name, and the connection closed. What steamcmd's anonymous `app_info_print` sees.
|
|
||||||
*/
|
|
||||||
object SteamPics {
|
|
||||||
private const val TAG = "SteamPics"
|
|
||||||
private const val CM_LIST = "https://api.steampowered.com/ISteamDirectory/GetCMListForConnect/v1/?cellid=0&format=json"
|
|
||||||
/** At most this many apps per request. */
|
|
||||||
const val BATCH = 25
|
|
||||||
private const val PROTO = 0x80000000.toInt()
|
|
||||||
private const val EMSG_MULTI = 1
|
|
||||||
private const val EMSG_LOGON = 5514
|
|
||||||
private const val EMSG_LOGON_RESPONSE = 751
|
|
||||||
private const val EMSG_LOGOFF = 706
|
|
||||||
private const val EMSG_TOKENS_REQUEST = 8905
|
|
||||||
private const val EMSG_TOKENS_RESPONSE = 8906
|
|
||||||
private const val EMSG_INFO_REQUEST = 8903
|
|
||||||
private const val EMSG_INFO_RESPONSE = 8904
|
|
||||||
private const val PROTOCOL_VERSION = 65580
|
|
||||||
/** An anonymous user's SteamID: universe Public, account type AnonUser, instance 0. */
|
|
||||||
private const val ANON_STEAMID = (1L shl 56) or (10L shl 52)
|
|
||||||
|
|
||||||
/**
|
|
||||||
* [appIds]' info, one connection for all of them in batches of [BATCH]: each known app's
|
|
||||||
* info, null for an app Steam does not know. Null when Steam could not be reached. Blocking.
|
|
||||||
*/
|
|
||||||
fun lookup(appIds: List<Int>): Map<Int, SteamAppInfo.Info?>? {
|
|
||||||
if (appIds.isEmpty()) return emptyMap()
|
|
||||||
val host = runCatching { cmHost() }.getOrNull() ?: return null
|
|
||||||
return try {
|
|
||||||
Wss(host, 20_000).use { ws ->
|
|
||||||
ws.send(message(EMSG_LOGON, header(ANON_STEAMID, 0), Proto().varint(1, PROTOCOL_VERSION.toLong()).varint(7, 16).string(6, "english").bytes()))
|
|
||||||
var steamId = 0L
|
|
||||||
var session = 0
|
|
||||||
// The logon's answer (other messages before it are passed over).
|
|
||||||
loop@ while (true) for ((emsg, hdr, body) in messages(ws.receive() ?: return null)) if (emsg == EMSG_LOGON_RESPONSE) {
|
|
||||||
val h = fields(hdr); val b = fields(body)
|
|
||||||
if ((b[1]?.firstOrNull() as? Long ?: 0L) != 1L) { Log.w(TAG, "anonymous logon refused: ${b[1]}"); return null }
|
|
||||||
steamId = h[1]?.firstOrNull() as? Long ?: 0L
|
|
||||||
session = (h[2]?.firstOrNull() as? Long ?: 0L).toInt()
|
|
||||||
break@loop
|
|
||||||
}
|
|
||||||
val out = HashMap<Int, SteamAppInfo.Info?>()
|
|
||||||
for (batch in batches(appIds)) {
|
|
||||||
val tokens = HashMap<Int, Long>()
|
|
||||||
ws.send(message(EMSG_TOKENS_REQUEST, header(steamId, session), Proto().apply { batch.forEach { varint(2, it.toLong()) } }.bytes()))
|
|
||||||
tokens@ while (true) for ((emsg, _, body) in messages(ws.receive() ?: return null)) if (emsg == EMSG_TOKENS_RESPONSE) {
|
|
||||||
for (t in fields(body)[3].orEmpty()) {
|
|
||||||
val f = fields(t as ByteArray)
|
|
||||||
val id = (f[1]?.firstOrNull() as? Long)?.toInt() ?: continue
|
|
||||||
tokens[id] = f[2]?.firstOrNull() as? Long ?: 0L
|
|
||||||
}
|
|
||||||
break@tokens
|
|
||||||
}
|
|
||||||
ws.send(message(EMSG_INFO_REQUEST, header(steamId, session), Proto().apply {
|
|
||||||
batch.forEach { id -> bytes(2, Proto().varint(1, id.toLong()).apply { tokens[id]?.takeIf { it != 0L }?.let { varint(2, it) } }.bytes()) }
|
|
||||||
varint(3, 0)
|
|
||||||
}.bytes()))
|
|
||||||
var pending = true
|
|
||||||
while (pending) for ((emsg, _, body) in messages(ws.receive() ?: return null)) if (emsg == EMSG_INFO_RESPONSE) {
|
|
||||||
val r = parseInfoResponse(body)
|
|
||||||
out.putAll(r.apps)
|
|
||||||
r.unknown.forEach { out[it] = null }
|
|
||||||
pending = r.pending
|
|
||||||
}
|
|
||||||
batch.forEach { if (it !in out) out[it] = null }
|
|
||||||
}
|
|
||||||
runCatching { ws.send(message(EMSG_LOGOFF, header(steamId, session), ByteArray(0))) }
|
|
||||||
Log.i(TAG, "steam pics: ${out.size} apps, ${out.values.count { it?.sharedDepots?.isNotEmpty() == true }} with shared redists")
|
|
||||||
out
|
|
||||||
}
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Log.w(TAG, "steam pics: ${e.javaClass.simpleName}: ${e.message}")
|
|
||||||
null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** [appIds] in requests of at most [BATCH], each once. */
|
|
||||||
fun batches(appIds: List<Int>): List<List<Int>> = appIds.distinct().chunked(BATCH)
|
|
||||||
|
|
||||||
/** A connection manager for the WebSocket transport, least loaded first as Steam lists them. */
|
|
||||||
private fun cmHost(): String? {
|
|
||||||
val c = URL(CM_LIST).openConnection() as HttpURLConnection
|
|
||||||
c.connectTimeout = 10_000; c.readTimeout = 10_000
|
|
||||||
val body = try { c.inputStream.bufferedReader().readText() } finally { c.disconnect() }
|
|
||||||
val list = JSONObject(body).optJSONObject("response")?.optJSONArray("serverlist") ?: return null
|
|
||||||
return (0 until list.length()).mapNotNull { list.optJSONObject(it) }
|
|
||||||
.firstOrNull { it.optString("type") == "websockets" }?.optString("endpoint")?.substringBefore(':')
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- the product info answer ----
|
|
||||||
|
|
||||||
class InfoResponse(val apps: Map<Int, SteamAppInfo.Info>, val unknown: List<Int>, val pending: Boolean)
|
|
||||||
|
|
||||||
/** A CMsgClientPICSProductInfoResponse: each app's KeyValues read, the unknown ones, whether more follows. */
|
|
||||||
@VisibleForTesting
|
|
||||||
internal fun parseInfoResponse(body: ByteArray): InfoResponse {
|
|
||||||
val f = fields(body)
|
|
||||||
val apps = HashMap<Int, SteamAppInfo.Info>()
|
|
||||||
for (a in f[1].orEmpty()) {
|
|
||||||
val app = fields(a as ByteArray)
|
|
||||||
val id = (app[1]?.firstOrNull() as? Long)?.toInt() ?: continue
|
|
||||||
val buffer = app[5]?.firstOrNull() as? ByteArray ?: continue
|
|
||||||
val text = String(buffer, Charsets.UTF_8).trimEnd('\u0000')
|
|
||||||
infoFromKeyValues(text)?.let { apps[id] = it }
|
|
||||||
}
|
|
||||||
val unknown = f[2].orEmpty().mapNotNull { (it as? Long)?.toInt() } + f[2].orEmpty().filterIsInstance<ByteArray>().flatMap { packed(it) }
|
|
||||||
return InfoResponse(apps, unknown, (f[6]?.firstOrNull() as? Long ?: 0L) != 0L)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** An app's KeyValues text ("appinfo" { "common" {...} "depots" {...} }) to its name and shared depots. */
|
|
||||||
@VisibleForTesting
|
|
||||||
internal fun infoFromKeyValues(text: String): SteamAppInfo.Info? {
|
|
||||||
// The buffer ends in a NUL, kept or not by whoever handed it over.
|
|
||||||
val tree = runCatching { KeyValues(text.trimEnd('\u0000', ' ', '\n', '\r', '\t')).read() }.getOrNull() ?: return null
|
|
||||||
@Suppress("UNCHECKED_CAST")
|
|
||||||
val app = tree["appinfo"] as? Map<String, Any> ?: return null
|
|
||||||
return SteamAppInfo.infoOf(app)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Valve's text KeyValues: quoted keys and values, nested braces. */
|
|
||||||
private class KeyValues(private val s: String) {
|
|
||||||
private var i = 0
|
|
||||||
fun read(): Map<String, Any> = map(top = true)
|
|
||||||
private fun map(top: Boolean): Map<String, Any> {
|
|
||||||
val out = LinkedHashMap<String, Any>()
|
|
||||||
while (true) {
|
|
||||||
skip()
|
|
||||||
if (i >= s.length) { if (top) return out else throw IOException("unclosed") }
|
|
||||||
if (s[i] == '}') { i++; return out }
|
|
||||||
val key = token()
|
|
||||||
skip()
|
|
||||||
if (i < s.length && s[i] == '{') { i++; out[key] = map(top = false) } else out[key] = token()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
private fun skip() {
|
|
||||||
while (i < s.length) {
|
|
||||||
if (s[i].isWhitespace() || s[i] == '\u0000') i++
|
|
||||||
else if (s.startsWith("//", i)) { while (i < s.length && s[i] != '\n') i++ }
|
|
||||||
else break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
private fun token(): String {
|
|
||||||
if (i < s.length && s[i] == '"') {
|
|
||||||
i++
|
|
||||||
val b = StringBuilder()
|
|
||||||
while (i < s.length && s[i] != '"') {
|
|
||||||
if (s[i] == '\\' && i + 1 < s.length) { i++; b.append(when (s[i]) { 'n' -> '\n'; 't' -> '\t'; else -> s[i] }) } else b.append(s[i])
|
|
||||||
i++
|
|
||||||
}
|
|
||||||
i++
|
|
||||||
return b.toString()
|
|
||||||
}
|
|
||||||
val start = i
|
|
||||||
while (i < s.length && !s[i].isWhitespace() && s[i] != '{' && s[i] != '}') i++
|
|
||||||
if (start == i) throw IOException("token expected at $i")
|
|
||||||
return s.substring(start, i)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- messages ----
|
|
||||||
|
|
||||||
private fun header(steamId: Long, session: Int) = Proto().fixed64(1, steamId).varint(2, session.toLong()).bytes()
|
|
||||||
|
|
||||||
private fun message(emsg: Int, header: ByteArray, body: ByteArray): ByteArray =
|
|
||||||
ByteBuffer.allocate(8 + header.size + body.size).order(ByteOrder.LITTLE_ENDIAN)
|
|
||||||
.putInt(emsg or PROTO).putInt(header.size).put(header).put(body).array()
|
|
||||||
|
|
||||||
/** One message off the wire as (emsg, header, body); a Multi unpacked (gunzipped when it says so) into the ones inside. */
|
|
||||||
@VisibleForTesting
|
|
||||||
internal fun messages(data: ByteArray): List<Triple<Int, ByteArray, ByteArray>> {
|
|
||||||
if (data.size < 8) return emptyList()
|
|
||||||
val b = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN)
|
|
||||||
val raw = b.int
|
|
||||||
if (raw and PROTO == 0) return emptyList()
|
|
||||||
val emsg = raw and PROTO.inv()
|
|
||||||
val hl = b.int
|
|
||||||
if (hl < 0 || 8 + hl > data.size) return emptyList()
|
|
||||||
val header = data.copyOfRange(8, 8 + hl)
|
|
||||||
val body = data.copyOfRange(8 + hl, data.size)
|
|
||||||
if (emsg != EMSG_MULTI) return listOf(Triple(emsg, header, body))
|
|
||||||
val f = fields(body)
|
|
||||||
var inner = f[2]?.firstOrNull() as? ByteArray ?: return emptyList()
|
|
||||||
if ((f[1]?.firstOrNull() as? Long ?: 0L) > 0) inner = GZIPInputStream(ByteArrayInputStream(inner)).use { it.readBytes() }
|
|
||||||
val out = ArrayList<Triple<Int, ByteArray, ByteArray>>()
|
|
||||||
val ib = ByteBuffer.wrap(inner).order(ByteOrder.LITTLE_ENDIAN)
|
|
||||||
while (ib.remaining() >= 4) {
|
|
||||||
val len = ib.int
|
|
||||||
if (len < 0 || len > ib.remaining()) break
|
|
||||||
val one = ByteArray(len).also { ib.get(it) }
|
|
||||||
out.addAll(messages(one))
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- protobuf, the little needed ----
|
|
||||||
|
|
||||||
/** Writes protobuf fields. */
|
|
||||||
@VisibleForTesting
|
|
||||||
internal class Proto {
|
|
||||||
private val out = ByteArrayOutputStream()
|
|
||||||
private fun raw(v: Long) { var x = v; while (true) { val b = (x and 0x7F).toInt(); x = x ushr 7; if (x == 0L) { out.write(b); return }; out.write(b or 0x80) } }
|
|
||||||
fun varint(field: Int, v: Long) = apply { raw((field shl 3).toLong()); raw(v) }
|
|
||||||
fun fixed64(field: Int, v: Long) = apply { raw(((field shl 3) or 1).toLong()); for (k in 0 until 8) out.write(((v ushr (8 * k)) and 0xFF).toInt()) }
|
|
||||||
fun bytes(field: Int, b: ByteArray) = apply { raw(((field shl 3) or 2).toLong()); raw(b.size.toLong()); out.write(b) }
|
|
||||||
fun string(field: Int, s: String) = bytes(field, s.toByteArray())
|
|
||||||
fun bytes(): ByteArray = out.toByteArray()
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Reads protobuf fields: number to values (Long for varint and fixed, ByteArray for length-delimited). */
|
|
||||||
@VisibleForTesting
|
|
||||||
internal fun fields(b: ByteArray): Map<Int, List<Any>> {
|
|
||||||
val out = HashMap<Int, MutableList<Any>>()
|
|
||||||
var i = 0
|
|
||||||
fun varint(): Long { var v = 0L; var s = 0; while (true) { val c = b[i++].toInt() and 0xFF; v = v or ((c and 0x7F).toLong() shl s); s += 7; if (c < 0x80) return v } }
|
|
||||||
while (i < b.size) {
|
|
||||||
val key = varint()
|
|
||||||
val field = (key ushr 3).toInt()
|
|
||||||
val value: Any = when ((key and 7).toInt()) {
|
|
||||||
0 -> varint()
|
|
||||||
1 -> { var v = 0L; for (k in 0 until 8) v = v or ((b[i + k].toLong() and 0xFF) shl (8 * k)); i += 8; v }
|
|
||||||
5 -> { var v = 0L; for (k in 0 until 4) v = v or ((b[i + k].toLong() and 0xFF) shl (8 * k)); i += 4; v }
|
|
||||||
2 -> { val n = varint().toInt(); val v = b.copyOfRange(i, i + n); i += n; v }
|
|
||||||
else -> throw IOException("wire type ${key and 7}")
|
|
||||||
}
|
|
||||||
out.getOrPut(field) { ArrayList() }.add(value)
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun packed(b: ByteArray): List<Int> {
|
|
||||||
val out = ArrayList<Int>(); var i = 0
|
|
||||||
while (i < b.size) { var v = 0L; var s = 0; while (true) { val c = b[i++].toInt() and 0xFF; v = v or ((c and 0x7F).toLong() shl s); s += 7; if (c < 0x80) break }; out.add(v.toInt()) }
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- WebSocket over TLS, binary frames ----
|
|
||||||
|
|
||||||
private class Wss(host: String, timeoutMs: Int) : AutoCloseable {
|
|
||||||
// Made with the host name, so it goes out as SNI.
|
|
||||||
private val socket: SSLSocket = (SSLSocketFactory.getDefault().createSocket(host, 443) as SSLSocket).apply { soTimeout = timeoutMs }
|
|
||||||
private val out: OutputStream
|
|
||||||
private val input: DataInputStream
|
|
||||||
|
|
||||||
init {
|
|
||||||
// Host name checked against the certificate, as HTTPS does.
|
|
||||||
socket.sslParameters = socket.sslParameters.apply { endpointIdentificationAlgorithm = "HTTPS" }
|
|
||||||
socket.startHandshake()
|
|
||||||
out = socket.outputStream
|
|
||||||
input = DataInputStream(socket.inputStream)
|
|
||||||
val key = ByteArray(16).also { SecureRandom().nextBytes(it) }
|
|
||||||
out.write(("GET /cmsocket/ HTTP/1.1\r\nHost: $host\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" +
|
|
||||||
"Sec-WebSocket-Key: ${android.util.Base64.encodeToString(key, android.util.Base64.NO_WRAP)}\r\nSec-WebSocket-Version: 13\r\n\r\n").toByteArray())
|
|
||||||
out.flush()
|
|
||||||
val status = line(input) ?: throw IOException("no upgrade response")
|
|
||||||
if (!status.contains(" 101 ")) throw IOException("upgrade refused: $status")
|
|
||||||
while (true) { val l = line(input) ?: break; if (l.isEmpty()) break }
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun line(s: InputStream): String? {
|
|
||||||
val buf = ByteArrayOutputStream()
|
|
||||||
while (true) {
|
|
||||||
val b = s.read()
|
|
||||||
if (b < 0) return if (buf.size() == 0) null else buf.toString("UTF-8")
|
|
||||||
if (b == '\n'.code) return buf.toString("UTF-8").trimEnd('\r')
|
|
||||||
buf.write(b)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun send(payload: ByteArray) {
|
|
||||||
val mask = ByteArray(4).also { SecureRandom().nextBytes(it) }
|
|
||||||
val frame = ByteArrayOutputStream()
|
|
||||||
frame.write(0x82)
|
|
||||||
when {
|
|
||||||
payload.size < 126 -> frame.write(0x80 or payload.size)
|
|
||||||
payload.size < 65536 -> { frame.write(0x80 or 126); frame.write(payload.size ushr 8); frame.write(payload.size and 0xFF) }
|
|
||||||
else -> { frame.write(0x80 or 127); for (k in 7 downTo 0) frame.write(((payload.size.toLong() ushr (8 * k)) and 0xFF).toInt()) }
|
|
||||||
}
|
|
||||||
frame.write(mask)
|
|
||||||
for (k in payload.indices) frame.write((payload[k].toInt() xor mask[k % 4].toInt()) and 0xFF)
|
|
||||||
out.write(frame.toByteArray()); out.flush()
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The next binary message (fragments joined); null on close. */
|
|
||||||
fun receive(): ByteArray? {
|
|
||||||
val message = ByteArrayOutputStream()
|
|
||||||
while (true) {
|
|
||||||
val b0 = input.read(); if (b0 < 0) return null
|
|
||||||
val b1 = input.read(); if (b1 < 0) return null
|
|
||||||
val fin = b0 and 0x80 != 0
|
|
||||||
val opcode = b0 and 0x0F
|
|
||||||
var len = (b1 and 0x7F).toLong()
|
|
||||||
if (len == 126L) len = input.readUnsignedShort().toLong() else if (len == 127L) len = input.readLong()
|
|
||||||
if (len > 32L * 1024 * 1024) throw IOException("frame too large")
|
|
||||||
val data = ByteArray(len.toInt()).also { input.readFully(it) }
|
|
||||||
when (opcode) {
|
|
||||||
0x8 -> return null
|
|
||||||
0x9 -> { out.write(byteArrayOf(0x8A.toByte(), 0x80.toByte(), 0, 0, 0, 0)); out.flush() }
|
|
||||||
0x2, 0x0 -> { message.write(data); if (fin) return message.toByteArray() }
|
|
||||||
else -> {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun close() {
|
|
||||||
runCatching { out.write(byteArrayOf(0x88.toByte(), 0x80.toByte(), 0, 0, 0, 0)); out.flush() }
|
|
||||||
runCatching { socket.close() }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,98 +0,0 @@
|
|||||||
package com.droiddeck.launcher.frontend
|
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
import android.util.AtomicFile
|
|
||||||
import android.util.Log
|
|
||||||
import androidx.annotation.VisibleForTesting
|
|
||||||
import com.droiddeck.launcher.stores.Store
|
|
||||||
import com.droiddeck.launcher.stores.StoreGameSidecar
|
|
||||||
import com.droiddeck.launcher.stores.epic.EpicApiClient
|
|
||||||
import com.droiddeck.launcher.stores.epic.EpicCredentialStore
|
|
||||||
import com.droiddeck.launcher.stores.epic.EpicDownloadManager
|
|
||||||
import com.droiddeck.launcher.stores.gog.GogAuth
|
|
||||||
import com.droiddeck.launcher.stores.gog.GogDownloadManager
|
|
||||||
import org.json.JSONObject
|
|
||||||
import java.io.File
|
|
||||||
|
|
||||||
/**
|
|
||||||
* For a GOG or Epic game installed before its sidecar kept the store's list (GOG's build
|
|
||||||
* `dependencies`, Epic's manifest prerequisite): the list read once from the store's build
|
|
||||||
* manifest with the saved sign-in - the manifest alone, never a game file - and kept in the sidecar
|
|
||||||
* the way an install keeps it. Runs on the components' worker ([AutoComponents]). Without a
|
|
||||||
* sign-in or a network it is skipped quietly and tried again a week later.
|
|
||||||
*/
|
|
||||||
object StoreListBackfill {
|
|
||||||
private const val TAG = "StoreListBackfill"
|
|
||||||
private const val FILE = "store-list-backfill.json"
|
|
||||||
private const val RETRY_AFTER_MS = 7L * 24 * 3600 * 1000
|
|
||||||
|
|
||||||
/** The store's list for the game in a sidecar: GOG's dependency ids, or Epic's prerequisite {name, path}; null when it could not be had. */
|
|
||||||
fun interface Fetcher {
|
|
||||||
fun fetch(context: Context, sidecar: StoreGameSidecar): Map<String, String>?
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The store itself, with the saved sign-in. */
|
|
||||||
internal val storeFetcher = Fetcher { context, sidecar -> fromStore(context, sidecar) }
|
|
||||||
|
|
||||||
@VisibleForTesting internal var fetcher: Fetcher = storeFetcher
|
|
||||||
|
|
||||||
/** Whether [sidecar] was written before the list was kept. */
|
|
||||||
/**
|
|
||||||
* Whether [sidecar] has no list read whole: written before the list was kept, or by a build
|
|
||||||
* that could have written an empty one for a manifest it did not read right.
|
|
||||||
*/
|
|
||||||
fun needs(sidecar: StoreGameSidecar): Boolean =
|
|
||||||
(sidecar.store == Store.GOG || sidecar.store == Store.EPIC) && WinCompSources.LIST_READ !in sidecar.extra
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The list for the game in [folder], fetched and kept when its sidecar lacks one and it was not
|
|
||||||
* tried in the past week. True when the sidecar changed. Blocking (network).
|
|
||||||
*/
|
|
||||||
@Synchronized
|
|
||||||
fun fill(context: Context, folder: File): Boolean {
|
|
||||||
val sidecar = StoreGameSidecar.read(folder)?.takeIf { it.isInstalled && needs(it) } ?: return false
|
|
||||||
val tries = runCatching { JSONObject(AtomicFile(File(context.filesDir, FILE)).readFully().toString(Charsets.UTF_8)) }.getOrDefault(JSONObject())
|
|
||||||
val now = System.currentTimeMillis()
|
|
||||||
if (now - tries.optLong(folder.path, 0L) < RETRY_AFTER_MS) return false
|
|
||||||
// Offline is no try: it waits for a network rather than a week.
|
|
||||||
if (!AutoComponents.online(context)) return false
|
|
||||||
val list = runCatching { fetcher.fetch(context, sidecar) }.getOrNull()
|
|
||||||
if (list == null) {
|
|
||||||
tries.put(folder.path, now)
|
|
||||||
val atomic = AtomicFile(File(context.filesDir, FILE))
|
|
||||||
val out = atomic.startWrite()
|
|
||||||
try { out.write(tries.toString().toByteArray()); atomic.finishWrite(out) } catch (e: Exception) { atomic.failWrite(out) }
|
|
||||||
Log.i(TAG, "${sidecar.title}: the ${sidecar.store.label} list could not be had; again in a week")
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
// Read fresh and written whole, as an install writes it: only the list is added.
|
|
||||||
val current = StoreGameSidecar.read(folder) ?: return false
|
|
||||||
current.copy(extra = current.extra + list + (WinCompSources.LIST_READ to "1")).write(folder)
|
|
||||||
Log.i(TAG, "backfill: ${sidecar.title} " + when (sidecar.store) {
|
|
||||||
Store.GOG -> "gog deps=[${list[WinCompSources.GOG_DEPENDENCIES].orEmpty()}]"
|
|
||||||
else -> "epic prereq=" + (list[WinCompSources.EPIC_PREREQ_NAME].orEmpty().ifEmpty { list[WinCompSources.EPIC_PREREQ_PATH].orEmpty() }.ifEmpty { "none" })
|
|
||||||
})
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun fromStore(context: Context, sidecar: StoreGameSidecar): Map<String, String>? {
|
|
||||||
return when (sidecar.store) {
|
|
||||||
Store.GOG -> {
|
|
||||||
val token = GogAuth.validToken(context) ?: return null
|
|
||||||
GogDownloadManager.fetchDependencies(sidecar.id, sidecar.installVersion, token)
|
|
||||||
?.let { mapOf(WinCompSources.GOG_DEPENDENCIES to it.joinToString(",")) }
|
|
||||||
}
|
|
||||||
Store.EPIC -> {
|
|
||||||
val token = EpicCredentialStore.getValidAccessToken(context) ?: return null
|
|
||||||
val namespace = sidecar.extra["namespace"].orEmpty()
|
|
||||||
val catalogItemId = sidecar.extra["catalogItemId"].orEmpty()
|
|
||||||
if (namespace.isEmpty() || catalogItemId.isEmpty()) return null
|
|
||||||
val json = EpicApiClient.getManifestApiJson(token, namespace, catalogItemId, sidecar.extra["appName"] ?: sidecar.id) ?: return null
|
|
||||||
EpicDownloadManager.fetchPrereq(json)?.let { (name, path) ->
|
|
||||||
mapOf(WinCompSources.EPIC_PREREQ_NAME to name, WinCompSources.EPIC_PREREQ_PATH to path)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else -> null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,160 +0,0 @@
|
|||||||
package com.droiddeck.launcher.frontend
|
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
import com.droiddeck.launcher.stores.Store
|
|
||||||
import com.droiddeck.launcher.stores.StoreGameSidecar
|
|
||||||
import org.json.JSONObject
|
|
||||||
import java.io.File
|
|
||||||
import java.util.Locale
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Which Windows components a game needs, from the list its source keeps - the source badge decides
|
|
||||||
* which list is trusted:
|
|
||||||
*
|
|
||||||
* - **Steam**: the Steamworks Shared redistributables Steam installs with the game (its
|
|
||||||
* appmanifest's SharedDepots, else the client's app info) - turned on by themselves.
|
|
||||||
* - **GOG**: the build manifest's `dependencies`, kept in the sidecar at install - on by themselves.
|
|
||||||
* - **Epic Games**: the manifest's prerequisite (usually UE4/UE5's prerequisite setup: VC++ and the
|
|
||||||
* DirectX June 2010 runtime), kept in the sidecar at install - on by themselves.
|
|
||||||
* - **Amazon Games**: fuel.json's PostInstall installers - on by themselves.
|
|
||||||
* - **Custom** whose files name a Steam appid ([SteamMatch], certain): Steam's list for that app -
|
|
||||||
* on by themselves. Matched by name only: the same list as Recommended. No match: the folder scan
|
|
||||||
* ([DependencyDetector]) as Recommended.
|
|
||||||
*
|
|
||||||
* Every store entry is mapped to catalog names here, in one place; one that maps to nothing is a
|
|
||||||
* suggestion under its own name. The folder scan is offered as Recommended for every game.
|
|
||||||
*/
|
|
||||||
object WinCompSources {
|
|
||||||
/** Whose list a finding came from; the reason line says it. */
|
|
||||||
enum class Origin { STEAM, GOG, EPIC, AMAZON, STEAM_NAME, FOLDER }
|
|
||||||
|
|
||||||
/**
|
|
||||||
* One thing a list names: [component] the catalog name it maps to (null: none, a suggestion),
|
|
||||||
* [original] what the list called it, [auto] whether it is turned on by itself, [args] what
|
|
||||||
* the reason line names (Steam: the label, the game, the appid).
|
|
||||||
*/
|
|
||||||
data class Finding(val component: String?, val original: String, val origin: Origin, val auto: Boolean, val args: List<String> = emptyList())
|
|
||||||
|
|
||||||
// ---- mapping tables: a store's names -> catalog components ----
|
|
||||||
|
|
||||||
private val VC_YEAR = mapOf(
|
|
||||||
"2005" to "vcredist2005", "2008" to "vcredist2008", "2010" to "vcredist2010", "2012" to "vcredist2012",
|
|
||||||
"2013" to "vcredist2013", "2015" to "vcredist2015", "2017" to "vcredist2015", "2019" to "vcredist2019", "2022" to "vcredist2022",
|
|
||||||
)
|
|
||||||
private val DOTNET = mapOf(
|
|
||||||
"35" to "dotnet35", "40" to "dotnet40", "45" to "dotnet45", "451" to "dotnet452", "452" to "dotnet452",
|
|
||||||
"46" to "dotnet46", "461" to "dotnet46", "462" to "dotnet46", "47" to "dotnet472", "471" to "dotnet472",
|
|
||||||
"472" to "dotnet472", "48" to "dotnet48", "481" to "dotnet48",
|
|
||||||
)
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A GOG dependency id ("MSVC2017_x64", "DirectX", "DOTNET48", "PhysX", "OpenAL", "XNA4") to its
|
|
||||||
* components; empty for one that is none of ours (ISI scripts, GOG's own helpers).
|
|
||||||
*/
|
|
||||||
fun gog(id: String): List<String> {
|
|
||||||
val key = id.uppercase(Locale.US).replace(Regex("[^A-Z0-9]"), "")
|
|
||||||
Regex("""^(?:MSVC|VCREDIST|VC)(\d{4})""").find(key)?.let { m -> return listOfNotNull(VC_YEAR[m.groupValues[1]]) }
|
|
||||||
Regex("""^(?:DOTNET|NETFRAMEWORK|DOTNETFRAMEWORK)(\d{2,3})""").find(key)?.let { m -> return listOfNotNull(DOTNET[m.groupValues[1]]) }
|
|
||||||
return when {
|
|
||||||
key.startsWith("DIRECTX") || key.startsWith("DX9") || key == "DXSETUP" || key.startsWith("D3DX") -> listOf("d3dx9")
|
|
||||||
key.startsWith("PHYSX") -> listOf("physx")
|
|
||||||
key.startsWith("OPENAL") -> listOf("oalinst")
|
|
||||||
key == "XNA31" || key == "XNA3" -> listOf("xna31")
|
|
||||||
key.startsWith("XNA") -> listOf("xna40")
|
|
||||||
key.startsWith("XLIVE") || key.startsWith("GFWL") -> listOf("XLiveRedist")
|
|
||||||
key.startsWith("XACT") -> listOf("xact")
|
|
||||||
else -> emptyList()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Unreal's prerequisite setup (UE4PrereqSetup_x64.exe, UEPrereqSetup_x64.exe): VC++ 2015-2022 and DirectX June 2010. */
|
|
||||||
private val UE_PREREQ = Regex("""(?i)ue\d?prereqsetup""")
|
|
||||||
|
|
||||||
/** An Epic prerequisite ([path] the installer it runs, [name] what it is called) to its components. */
|
|
||||||
fun epic(path: String, name: String): List<String> = when {
|
|
||||||
UE_PREREQ.containsMatchIn(path) || name.contains("UE4 Prerequisites", true) || name.contains("UE5 Prerequisites", true) ||
|
|
||||||
name.contains("Unreal Engine Prerequisites", true) -> listOf("vcredist2022", "d3dx9")
|
|
||||||
else -> DependencyDetector.componentsFor(path).ifEmpty { if (path.isEmpty()) gog(name) else emptyList() }
|
|
||||||
}
|
|
||||||
|
|
||||||
/** An installer a store runs after an install (Amazon's PostInstall "Command") to its components. */
|
|
||||||
fun installer(path: String): List<String> = if (UE_PREREQ.containsMatchIn(path)) listOf("vcredist2022", "d3dx9") else DependencyDetector.componentsFor(path)
|
|
||||||
|
|
||||||
/** Steamworks Shared depot ids to (component, Steam's label). */
|
|
||||||
fun steamDepots(ids: List<String>): List<Pair<String, String>> = ids.mapNotNull { SteamRedists.DEPOTS[it] }.distinctBy { it.first }
|
|
||||||
|
|
||||||
// ---- what each store left at install ----
|
|
||||||
|
|
||||||
/** Sidecar keys the store installs fill. */
|
|
||||||
const val GOG_DEPENDENCIES = "dependencies"
|
|
||||||
const val EPIC_PREREQ_PATH = "prereqPath"
|
|
||||||
const val EPIC_PREREQ_NAME = "prereqName"
|
|
||||||
/** Set beside the list when it was read whole (an empty list then means the store lists none). */
|
|
||||||
const val LIST_READ = "listRead"
|
|
||||||
|
|
||||||
/** fuel.json's PostInstall commands. */
|
|
||||||
fun amazonPostInstall(folder: File): List<String> = runCatching {
|
|
||||||
val arr = JSONObject(File(folder, "fuel.json").readText()).optJSONArray("PostInstall") ?: return emptyList()
|
|
||||||
(0 until arr.length()).mapNotNull { arr.optJSONObject(it)?.optString("Command")?.takeIf { c -> c.isNotEmpty() } }
|
|
||||||
}.getOrDefault(emptyList())
|
|
||||||
|
|
||||||
// ---- per game ----
|
|
||||||
|
|
||||||
/** Steam's list for [appId]: the local appmanifest's SharedDepots, else the client's app info. */
|
|
||||||
fun steamList(context: Context, gameDir: File?, appId: Int, gameName: String, auto: Boolean): List<Finding> {
|
|
||||||
val local = SteamRedists.detect(gameDir, appId)
|
|
||||||
val pairs = if (local.isNotEmpty()) local.map { it.componentName to it.label }
|
|
||||||
else SteamAppInfo.info(context, appId)?.let { steamDepots(it.sharedDepots) }.orEmpty()
|
|
||||||
return pairs.map { (component, label) ->
|
|
||||||
Finding(component, label, if (auto) Origin.STEAM else Origin.STEAM_NAME, auto, listOf(label, gameName, appId.toString()))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Everything known for [game], blocking (files; the client's app info; no network). */
|
|
||||||
fun forGame(context: Context, game: Library.SteamGame): List<Finding> {
|
|
||||||
val folder = game.gameFiles
|
|
||||||
val out = ArrayList<Finding>()
|
|
||||||
val store = Store.byId(game.source)
|
|
||||||
val sidecar = folder?.let { StoreGameSidecar.read(it) }
|
|
||||||
when {
|
|
||||||
game.library != Library.ADDED -> if (game.appId > 0) out += steamList(context, folder, game.appId, game.name, auto = true)
|
|
||||||
store == Store.GOG -> sidecar?.extra?.get(GOG_DEPENDENCIES)?.split(',')?.map { it.trim() }?.filter { it.isNotEmpty() }?.forEach { id ->
|
|
||||||
val parts = gog(id)
|
|
||||||
if (parts.isEmpty()) out += Finding(null, id, Origin.GOG, false)
|
|
||||||
parts.forEach { out += Finding(it, id, Origin.GOG, true) }
|
|
||||||
}
|
|
||||||
store == Store.EPIC -> {
|
|
||||||
val path = sidecar?.extra?.get(EPIC_PREREQ_PATH).orEmpty()
|
|
||||||
val name = sidecar?.extra?.get(EPIC_PREREQ_NAME).orEmpty()
|
|
||||||
if (path.isNotEmpty() || name.isNotEmpty()) {
|
|
||||||
val parts = epic(path, name)
|
|
||||||
val original = name.ifEmpty { path.substringAfterLast('/') }
|
|
||||||
if (parts.isEmpty()) out += Finding(null, original, Origin.EPIC, false)
|
|
||||||
parts.forEach { out += Finding(it, original, Origin.EPIC, true) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
store == Store.AMAZON -> folder?.let { amazonPostInstall(it) }?.forEach { command ->
|
|
||||||
val parts = installer(command)
|
|
||||||
val original = command.replace('\\', '/').substringAfterLast('/')
|
|
||||||
if (parts.isEmpty()) out += Finding(null, original, Origin.AMAZON, false)
|
|
||||||
parts.forEach { out += Finding(it, original, Origin.AMAZON, true) }
|
|
||||||
}
|
|
||||||
else -> {}
|
|
||||||
}
|
|
||||||
// A game added in DroidDeck (Custom, or a store's) that is a Steam app: Steam's list for it,
|
|
||||||
// on by itself when its files say so, else only recommended.
|
|
||||||
if (game.library == Library.ADDED && folder != null) SteamMatch.get(context, folder.path)?.let { match ->
|
|
||||||
val id = match.appId ?: return@let
|
|
||||||
when (match.certainty) {
|
|
||||||
SteamMatch.Certainty.FILES -> out += steamList(context, folder, id, game.name, auto = true)
|
|
||||||
SteamMatch.Certainty.NAME -> out += steamList(context, folder, id, game.name, auto = false)
|
|
||||||
else -> {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// The folder scan, for every game: what it bundles, as Recommended.
|
|
||||||
folder?.let { DependencyDetector.detect(it) }?.forEach { rec ->
|
|
||||||
out += Finding(rec.componentName, rec.reason, Origin.FOLDER, false, listOf(rec.reason, rec.kind.name))
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -168,7 +168,7 @@ object Lossless {
|
|||||||
val libraries = listOfNotNull(
|
val libraries = listOfNotNull(
|
||||||
File(LinuxRuntime.rootDir(context), "root/.local/share/Steam"),
|
File(LinuxRuntime.rootDir(context), "root/.local/share/Steam"),
|
||||||
GameStorage.effective(context)?.path?.let(::File),
|
GameStorage.effective(context)?.path?.let(::File),
|
||||||
) + com.droiddeck.launcher.frontend.AddedGames.roots(context).map { it.host }
|
) + SessionPrefs.addedGamesDirs(context).map(::File)
|
||||||
return libraries.map { File(it, STEAM_DLL) }.filter { it.isFile }.maxByOrNull { it.lastModified() }
|
return libraries.map { File(it, STEAM_DLL) }.filter { it.isFile }.maxByOrNull { it.lastModified() }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -47,7 +47,6 @@ class ControllerEditorActivity : ComponentActivity() {
|
|||||||
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
requestedOrientation = com.droiddeck.launcher.session.SessionPrefs.orientation(this)
|
|
||||||
immersive()
|
immersive()
|
||||||
val root = FrameLayout(this)
|
val root = FrameLayout(this)
|
||||||
root.setBackgroundColor(0xFF0B0F14.toInt())
|
root.setBackgroundColor(0xFF0B0F14.toInt())
|
||||||
|
|||||||
@@ -46,7 +46,6 @@ object ControllerPrefs {
|
|||||||
val steamButton: Boolean,
|
val steamButton: Boolean,
|
||||||
val qamButton: Boolean,
|
val qamButton: Boolean,
|
||||||
val keyboardButton: Boolean,
|
val keyboardButton: Boolean,
|
||||||
val selectSteam: Boolean,
|
|
||||||
val snap: Boolean,
|
val snap: Boolean,
|
||||||
val customLayout: Boolean,
|
val customLayout: Boolean,
|
||||||
val mapping: Map<String, String>,
|
val mapping: Map<String, String>,
|
||||||
@@ -66,7 +65,6 @@ object ControllerPrefs {
|
|||||||
steamButton = p.getBoolean("steamButton", true),
|
steamButton = p.getBoolean("steamButton", true),
|
||||||
qamButton = p.getBoolean("qamButton", true),
|
qamButton = p.getBoolean("qamButton", true),
|
||||||
keyboardButton = p.getBoolean("keyboardButton", true),
|
keyboardButton = p.getBoolean("keyboardButton", true),
|
||||||
selectSteam = p.getBoolean("selectSteam", false),
|
|
||||||
snap = p.getBoolean("snap", true),
|
snap = p.getBoolean("snap", true),
|
||||||
customLayout = p.all.keys.any { it.startsWith("layout.") },
|
customLayout = p.all.keys.any { it.startsWith("layout.") },
|
||||||
mapping = mappable.associate { (id, _) -> id to target(context, id) },
|
mapping = mappable.associate { (id, _) -> id to target(context, id) },
|
||||||
@@ -123,11 +121,6 @@ object ControllerPrefs {
|
|||||||
prefs(context).edit().putBoolean("keyboardButton", on).apply()
|
prefs(context).edit().putBoolean("keyboardButton", on).apply()
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The physical Select button opens the Steam menu instead of View/Select. */
|
|
||||||
fun setSelectSteam(context: Context, on: Boolean) {
|
|
||||||
prefs(context).edit().putBoolean("selectSteam", on).apply()
|
|
||||||
}
|
|
||||||
|
|
||||||
fun setSnap(context: Context, on: Boolean) {
|
fun setSnap(context: Context, on: Boolean) {
|
||||||
prefs(context).edit().putBoolean("snap", on).apply()
|
prefs(context).edit().putBoolean("snap", on).apply()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -94,52 +94,18 @@ public class FakeInputWriter {
|
|||||||
private static final int RING_SNAPSHOT_SEQ_OFFSET = 32;
|
private static final int RING_SNAPSHOT_SEQ_OFFSET = 32;
|
||||||
private static final int RING_SNAPSHOT_BUTTONS_OFFSET = 40;
|
private static final int RING_SNAPSHOT_BUTTONS_OFFSET = 40;
|
||||||
private static final int RING_SNAPSHOT_AXES_OFFSET = 44; // short[8]
|
private static final int RING_SNAPSHOT_AXES_OFFSET = 44; // short[8]
|
||||||
// After the events - MUST match the blocks in fakeinput_steam.cpp. DeckImu carries the
|
// After the events - MUST match the block in fakeinput_steam.cpp (DeckImu): what a Deck has and
|
||||||
// Deck-only motion, grips and trackpads. TritonShared carries the paired Steam Controller's
|
// an Xbox pad does not - motion, back grips, trackpads - in the Steam Deck controller's axes and
|
||||||
// native BLE reports and output reports, so the Steam client can see it as its own device.
|
// units, under a seqlock like the snapshot's. Only libfakeinput's Deck controller reads it.
|
||||||
private static final int IMU_OFFSET = RING_SIZE;
|
private static final int IMU_OFFSET = RING_SIZE;
|
||||||
private static final int IMU_MAGIC = 0x31554D49; // IMU1
|
private static final int IMU_MAGIC = 0x31554D49; // IMU1
|
||||||
// Written by libfakeinput, not here: the client's SETTING_IMU_MODE | 0x80000000 (readImuMode).
|
|
||||||
private static final int IMU_MODE_OFFSET = IMU_OFFSET + 4;
|
|
||||||
private static final int IMU_SEQ_OFFSET = IMU_OFFSET + 8;
|
private static final int IMU_SEQ_OFFSET = IMU_OFFSET + 8;
|
||||||
private static final int IMU_ACCEL_OFFSET = IMU_OFFSET + 16; // short[3]
|
private static final int IMU_ACCEL_OFFSET = IMU_OFFSET + 16; // short[3]
|
||||||
private static final int IMU_GYRO_OFFSET = IMU_OFFSET + 22; // short[3]
|
private static final int IMU_GYRO_OFFSET = IMU_OFFSET + 22; // short[3]
|
||||||
private static final int DECK_PADS_OFFSET = IMU_OFFSET + 28; // short[4]: left X, Y, right X, Y
|
private static final int DECK_PADS_OFFSET = IMU_OFFSET + 28; // short[4]: left X, Y, right X, Y
|
||||||
private static final int DECK_PRESSURE_OFFSET = IMU_OFFSET + 36; // short[2]: left, right
|
private static final int DECK_PRESSURE_OFFSET = IMU_OFFSET + 36; // short[2]: left, right
|
||||||
private static final int DECK_CONTROLS_OFFSET = IMU_OFFSET + 40; // int: DeckControls bits
|
private static final int DECK_CONTROLS_OFFSET = IMU_OFFSET + 40; // int: DeckControls bits
|
||||||
// Slot 0 only: what the pad is to the Steam client (libfakeinput's PAD_TYPE_*), | PAD_TYPE_SET.
|
private static final int RING_FILE_SIZE = RING_SIZE + 64;
|
||||||
private static final int PAD_TYPE_OFFSET = IMU_OFFSET + 44;
|
|
||||||
private static final int PAD_TYPE_SET = 0x80000000;
|
|
||||||
public static final int PAD_TYPE_DECK = 0;
|
|
||||||
public static final int PAD_TYPE_STEAM = 1;
|
|
||||||
public static final int PAD_TYPE_XBOX = 2;
|
|
||||||
public static final int PAD_TYPE_DS4 = 3;
|
|
||||||
public static final int PAD_TYPE_DUALSENSE = 4;
|
|
||||||
/** The type chosen this process, written into a ring made after the choice too; -1 for none. */
|
|
||||||
private static volatile int padType = -1;
|
|
||||||
/** The paired controller's state, likewise written into a ring made after it connected. */
|
|
||||||
private static volatile boolean tritonConnected = false;
|
|
||||||
private static final int TRITON_OFFSET = RING_SIZE + 64;
|
|
||||||
private static final int TRITON_MAGIC = 0x4e525454; // TTRN
|
|
||||||
// Whether the paired controller is connected: libfakeinput offers its device only then.
|
|
||||||
private static final int TRITON_CONNECTED_OFFSET = TRITON_OFFSET + 4;
|
|
||||||
private static final int TRITON_INPUT_SEQ_OFFSET = TRITON_OFFSET + 8;
|
|
||||||
private static final int TRITON_REPORT_ID_OFFSET = TRITON_OFFSET + 16;
|
|
||||||
private static final int TRITON_REPORT_LENGTH_OFFSET = TRITON_OFFSET + 20;
|
|
||||||
private static final int TRITON_REPORT_OFFSET = TRITON_OFFSET + 24;
|
|
||||||
private static final int TRITON_OUTPUT_SEQ_OFFSET = TRITON_OFFSET + 88;
|
|
||||||
private static final int TRITON_OUTPUT_FEATURE_OFFSET = TRITON_OFFSET + 96;
|
|
||||||
private static final int TRITON_OUTPUT_LENGTH_OFFSET = TRITON_OFFSET + 100;
|
|
||||||
private static final int TRITON_OUTPUT_OFFSET = TRITON_OFFSET + 104;
|
|
||||||
// A feature read: libfakeinput bumps the request, the reply names the request it answers.
|
|
||||||
private static final int TRITON_GET_REQUEST_OFFSET = TRITON_OFFSET + 168;
|
|
||||||
private static final int TRITON_GET_REPLY_OFFSET = TRITON_OFFSET + 176;
|
|
||||||
private static final int TRITON_GET_REPORT_ID_OFFSET = TRITON_OFFSET + 184;
|
|
||||||
private static final int TRITON_GET_LENGTH_OFFSET = TRITON_OFFSET + 188;
|
|
||||||
private static final int TRITON_GET_OFFSET = TRITON_OFFSET + 192;
|
|
||||||
private static final int TRITON_REPORT_MAX = 64;
|
|
||||||
private static final int TRITON_BLOCK_SIZE = 256;
|
|
||||||
private static final int RING_FILE_SIZE = TRITON_OFFSET + TRITON_BLOCK_SIZE;
|
|
||||||
|
|
||||||
private static final Object RING_LOCK = new Object();
|
private static final Object RING_LOCK = new Object();
|
||||||
private static final RingSlot[] RING_SLOTS = new RingSlot[MAX_FAKE_INPUT_SLOTS];
|
private static final RingSlot[] RING_SLOTS = new RingSlot[MAX_FAKE_INPUT_SLOTS];
|
||||||
@@ -249,24 +215,11 @@ public class FakeInputWriter {
|
|||||||
data.putShort(RING_SNAPSHOT_AXES_OFFSET + (i * 2), (short) 0);
|
data.putShort(RING_SNAPSHOT_AXES_OFFSET + (i * 2), (short) 0);
|
||||||
}
|
}
|
||||||
data.putInt(IMU_OFFSET, 0);
|
data.putInt(IMU_OFFSET, 0);
|
||||||
data.putInt(IMU_MODE_OFFSET, 0);
|
|
||||||
data.putLong(IMU_SEQ_OFFSET, 0L);
|
data.putLong(IMU_SEQ_OFFSET, 0L);
|
||||||
for (int i = 0; i < 12; i++) {
|
for (int i = 0; i < 12; i++) {
|
||||||
data.putShort(IMU_ACCEL_OFFSET + (i * 2), (short) 0);
|
data.putShort(IMU_ACCEL_OFFSET + (i * 2), (short) 0);
|
||||||
}
|
}
|
||||||
data.putInt(DECK_CONTROLS_OFFSET, 0);
|
data.putInt(DECK_CONTROLS_OFFSET, 0);
|
||||||
int type = padType;
|
|
||||||
data.putInt(PAD_TYPE_OFFSET, type >= 0 ? PAD_TYPE_SET | type : 0);
|
|
||||||
data.putInt(TRITON_OFFSET, TRITON_MAGIC);
|
|
||||||
data.putInt(TRITON_CONNECTED_OFFSET, tritonConnected ? 1 : 0);
|
|
||||||
data.putLong(TRITON_INPUT_SEQ_OFFSET, 0L);
|
|
||||||
data.putInt(TRITON_REPORT_ID_OFFSET, 0);
|
|
||||||
data.putInt(TRITON_REPORT_LENGTH_OFFSET, 0);
|
|
||||||
data.putLong(TRITON_OUTPUT_SEQ_OFFSET, 0L);
|
|
||||||
data.putInt(TRITON_OUTPUT_FEATURE_OFFSET, 0);
|
|
||||||
data.putInt(TRITON_OUTPUT_LENGTH_OFFSET, 0);
|
|
||||||
data.putLong(TRITON_GET_REQUEST_OFFSET, 0L);
|
|
||||||
data.putLong(TRITON_GET_REPLY_OFFSET, 0L);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Lock order: RING_LOCK, then the slot. Every writer holds the slot while it touches data, and
|
// Lock order: RING_LOCK, then the slot. Every writer holds the slot while it touches data, and
|
||||||
@@ -523,23 +476,6 @@ public class FakeInputWriter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* The motion the Steam client asked the Deck controller of slot {@code slot} for: its
|
|
||||||
* SETTING_IMU_MODE (0 = off), or -1 until it has said. Safe from any thread.
|
|
||||||
*/
|
|
||||||
public static int readImuMode(int slot) {
|
|
||||||
RingSlot ringSlot;
|
|
||||||
synchronized (RING_LOCK) {
|
|
||||||
ringSlot = slot >= 0 && slot < RING_SLOTS.length ? RING_SLOTS[slot] : null;
|
|
||||||
}
|
|
||||||
if (ringSlot == null) return -1;
|
|
||||||
synchronized (ringSlot) {
|
|
||||||
ByteBuffer ring = ringSlot.data;
|
|
||||||
int value = ring == null ? 0 : ring.getInt(IMU_MODE_OFFSET);
|
|
||||||
return value < 0 ? value & 0xffff : -1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Publishes the Deck's back grips and trackpads for slot {@code slot} (see DeckControls):
|
* Publishes the Deck's back grips and trackpads for slot {@code slot} (see DeckControls):
|
||||||
* {@code controls} is the DeckControls bit set, {@code pads} left X, Y, right X, Y and
|
* {@code controls} is the DeckControls bit set, {@code pads} left X, Y, right X, Y and
|
||||||
@@ -566,121 +502,6 @@ public class FakeInputWriter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Switches what the pad is to the Steam client while the session runs ([PAD_TYPE_DECK],
|
|
||||||
* [PAD_TYPE_STEAM] or [PAD_TYPE_XBOX]); libfakeinput unplugs the old device and plugs in the new.
|
|
||||||
*/
|
|
||||||
public static void setPadType(int type) {
|
|
||||||
padType = type;
|
|
||||||
RingSlot ringSlot;
|
|
||||||
synchronized (RING_LOCK) {
|
|
||||||
ringSlot = RING_SLOTS[0];
|
|
||||||
}
|
|
||||||
if (ringSlot == null) return;
|
|
||||||
synchronized (ringSlot) {
|
|
||||||
ByteBuffer ring = ringSlot.data;
|
|
||||||
if (ring == null) return;
|
|
||||||
nativeStoreFence();
|
|
||||||
ring.putInt(PAD_TYPE_OFFSET, PAD_TYPE_SET | type);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The paired Steam Controller came or went (SteamControllerBle): its device is plugged in or out. */
|
|
||||||
public static void setTritonConnected(int slot, boolean connected) {
|
|
||||||
tritonConnected = connected;
|
|
||||||
RingSlot ringSlot = tritonSlot(slot);
|
|
||||||
if (ringSlot == null) return;
|
|
||||||
synchronized (ringSlot) {
|
|
||||||
ByteBuffer ring = ringSlot.data;
|
|
||||||
if (ring == null || ring.getInt(TRITON_OFFSET) != TRITON_MAGIC) return;
|
|
||||||
nativeStoreFence();
|
|
||||||
ring.putInt(TRITON_CONNECTED_OFFSET, connected ? 1 : 0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Publishes a native Triton input report (without the HID report ID byte). */
|
|
||||||
public static void writeTritonState(int slot, int reportId, byte[] report) {
|
|
||||||
if (report == null || report.length == 0 || report.length > TRITON_REPORT_MAX) return;
|
|
||||||
RingSlot ringSlot;
|
|
||||||
synchronized (RING_LOCK) {
|
|
||||||
ringSlot = slot >= 0 && slot < RING_SLOTS.length ? RING_SLOTS[slot] : null;
|
|
||||||
}
|
|
||||||
if (ringSlot == null) return;
|
|
||||||
synchronized (ringSlot) {
|
|
||||||
ByteBuffer ring = ringSlot.data;
|
|
||||||
if (ring == null || ring.getInt(TRITON_OFFSET) != TRITON_MAGIC) return;
|
|
||||||
long seq = ring.getLong(TRITON_INPUT_SEQ_OFFSET);
|
|
||||||
if ((seq & 1) != 0) seq++;
|
|
||||||
ring.putLong(TRITON_INPUT_SEQ_OFFSET, seq + 1);
|
|
||||||
nativeStoreFence();
|
|
||||||
ring.putInt(TRITON_REPORT_ID_OFFSET, reportId);
|
|
||||||
ring.putInt(TRITON_REPORT_LENGTH_OFFSET, report.length);
|
|
||||||
for (int i = 0; i < TRITON_REPORT_MAX; i++) {
|
|
||||||
ring.put(TRITON_REPORT_OFFSET + i, i < report.length ? report[i] : 0);
|
|
||||||
}
|
|
||||||
nativeStoreFence();
|
|
||||||
ring.putLong(TRITON_INPUT_SEQ_OFFSET, seq + 2);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Returns the newest Steam-client output report after {@code lastSequence}, or null. */
|
|
||||||
public static byte[] readTritonOutput(int slot, long lastSequence) {
|
|
||||||
RingSlot ringSlot;
|
|
||||||
synchronized (RING_LOCK) {
|
|
||||||
ringSlot = slot >= 0 && slot < RING_SLOTS.length ? RING_SLOTS[slot] : null;
|
|
||||||
}
|
|
||||||
if (ringSlot == null) return null;
|
|
||||||
synchronized (ringSlot) {
|
|
||||||
ByteBuffer ring = ringSlot.data;
|
|
||||||
if (ring == null || ring.getInt(TRITON_OFFSET) != TRITON_MAGIC) return null;
|
|
||||||
nativeStoreFence();
|
|
||||||
long seq = ring.getLong(TRITON_OUTPUT_SEQ_OFFSET);
|
|
||||||
if ((seq & 1) != 0 || seq <= lastSequence) return null;
|
|
||||||
int length = ring.getInt(TRITON_OUTPUT_LENGTH_OFFSET);
|
|
||||||
if (length <= 0 || length > TRITON_REPORT_MAX) return null;
|
|
||||||
byte[] output = new byte[9 + length];
|
|
||||||
ByteBuffer.wrap(output).order(ByteOrder.LITTLE_ENDIAN).putLong(seq);
|
|
||||||
output[8] = (byte) (ring.getInt(TRITON_OUTPUT_FEATURE_OFFSET) != 0 ? 1 : 0);
|
|
||||||
for (int i = 0; i < length; i++) output[9 + i] = ring.get(TRITON_OUTPUT_OFFSET + i);
|
|
||||||
nativeStoreFence();
|
|
||||||
return seq == ring.getLong(TRITON_OUTPUT_SEQ_OFFSET) ? output : null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The Steam client's newest unanswered feature read, or 0: its request number. */
|
|
||||||
public static long readTritonFeatureRequest(int slot) {
|
|
||||||
RingSlot ringSlot = tritonSlot(slot);
|
|
||||||
if (ringSlot == null) return 0L;
|
|
||||||
synchronized (ringSlot) {
|
|
||||||
ByteBuffer ring = ringSlot.data;
|
|
||||||
if (ring == null || ring.getInt(TRITON_OFFSET) != TRITON_MAGIC) return 0L;
|
|
||||||
nativeStoreFence();
|
|
||||||
long request = ring.getLong(TRITON_GET_REQUEST_OFFSET);
|
|
||||||
return request != ring.getLong(TRITON_GET_REPLY_OFFSET) ? request : 0L;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Answers feature read {@code request} with the controller's report, or a failure when null. */
|
|
||||||
public static void writeTritonFeatureReply(int slot, long request, byte[] report) {
|
|
||||||
RingSlot ringSlot = tritonSlot(slot);
|
|
||||||
if (ringSlot == null) return;
|
|
||||||
synchronized (ringSlot) {
|
|
||||||
ByteBuffer ring = ringSlot.data;
|
|
||||||
if (ring == null || ring.getInt(TRITON_OFFSET) != TRITON_MAGIC) return;
|
|
||||||
int length = report == null ? 0 : Math.min(report.length, TRITON_REPORT_MAX);
|
|
||||||
for (int i = 0; i < TRITON_REPORT_MAX; i++) ring.put(TRITON_GET_OFFSET + i, i < length ? report[i] : 0);
|
|
||||||
ring.putInt(TRITON_GET_LENGTH_OFFSET, length);
|
|
||||||
nativeStoreFence();
|
|
||||||
ring.putLong(TRITON_GET_REPLY_OFFSET, request);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static RingSlot tritonSlot(int slot) {
|
|
||||||
synchronized (RING_LOCK) {
|
|
||||||
return slot >= 0 && slot < RING_SLOTS.length ? RING_SLOTS[slot] : null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static short clampShort(int value) {
|
private static short clampShort(int value) {
|
||||||
if (value > Short.MAX_VALUE) {
|
if (value > Short.MAX_VALUE) {
|
||||||
return Short.MAX_VALUE;
|
return Short.MAX_VALUE;
|
||||||
|
|||||||
@@ -36,18 +36,6 @@ public final class PadBridge {
|
|||||||
/** Player slots: the session prepares a ring for each (SessionService). */
|
/** Player slots: the session prepares a ring for each (SessionService). */
|
||||||
public static final int SLOTS = 4;
|
public static final int SLOTS = 4;
|
||||||
private static final float DEAD_ZONE = 0.12f;
|
private static final float DEAD_ZONE = 0.12f;
|
||||||
private static final int[] JOYSTICK_AXES = {
|
|
||||||
MotionEvent.AXIS_X, MotionEvent.AXIS_Y, MotionEvent.AXIS_Z, MotionEvent.AXIS_RZ,
|
|
||||||
MotionEvent.AXIS_HAT_X, MotionEvent.AXIS_HAT_Y, MotionEvent.AXIS_LTRIGGER,
|
|
||||||
MotionEvent.AXIS_RTRIGGER, MotionEvent.AXIS_BRAKE, MotionEvent.AXIS_GAS
|
|
||||||
};
|
|
||||||
private static final int[] CONTROLLER_BUTTONS = {
|
|
||||||
KeyEvent.KEYCODE_BUTTON_A, KeyEvent.KEYCODE_BUTTON_B, KeyEvent.KEYCODE_BUTTON_X,
|
|
||||||
KeyEvent.KEYCODE_BUTTON_Y, KeyEvent.KEYCODE_BUTTON_L1, KeyEvent.KEYCODE_BUTTON_R1,
|
|
||||||
KeyEvent.KEYCODE_BUTTON_SELECT, KeyEvent.KEYCODE_BUTTON_START,
|
|
||||||
KeyEvent.KEYCODE_BUTTON_THUMBL, KeyEvent.KEYCODE_BUTTON_THUMBR,
|
|
||||||
KeyEvent.KEYCODE_BUTTON_MODE, KeyEvent.KEYCODE_BUTTON_L2, KeyEvent.KEYCODE_BUTTON_R2
|
|
||||||
};
|
|
||||||
// The client takes A as part of the chord only once it has had Guide held for a while, and a
|
// The client takes A as part of the chord only once it has had Guide held for a while, and a
|
||||||
// client starved of CPU needs longer. Too short, and it acts on A as well, selecting whatever it
|
// client starved of CPU needs longer. Too short, and it acts on A as well, selecting whatever it
|
||||||
// had focused before opening QAM: with 80 ms of lead that was 3 times in 20 at rest, and 250 ms
|
// had focused before opening QAM: with 80 ms of lead that was 3 times in 20 at rest, and 250 ms
|
||||||
@@ -77,7 +65,6 @@ public final class PadBridge {
|
|||||||
private final PadState effectiveState = new PadState();
|
private final PadState effectiveState = new PadState();
|
||||||
private final Handler mainHandler = new Handler(Looper.getMainLooper());
|
private final Handler mainHandler = new Handler(Looper.getMainLooper());
|
||||||
private boolean open;
|
private boolean open;
|
||||||
private volatile boolean selectSteam;
|
|
||||||
private boolean systemGuidePressed;
|
private boolean systemGuidePressed;
|
||||||
private boolean systemQamPressed;
|
private boolean systemQamPressed;
|
||||||
private boolean qamChordActive;
|
private boolean qamChordActive;
|
||||||
@@ -126,11 +113,6 @@ public final class PadBridge {
|
|||||||
for (int slot = 1; slot < SLOTS; slot++) playerStates[slot] = new PadState();
|
for (int slot = 1; slot < SLOTS; slot++) playerStates[slot] = new PadState();
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The physical Select button opens the Steam menu instead of View/Select (Setup → Controller). */
|
|
||||||
public void setSelectSteam(boolean on) {
|
|
||||||
selectSteam = on;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Opens the ring; safe to call more than once. */
|
/** Opens the ring; safe to call more than once. */
|
||||||
public synchronized boolean start() {
|
public synchronized boolean start() {
|
||||||
if (!open) {
|
if (!open) {
|
||||||
@@ -172,58 +154,8 @@ public final class PadBridge {
|
|||||||
// counting it would hide the on-screen controls with nothing to replace them.
|
// counting it would hide the on-screen controls with nothing to replace them.
|
||||||
if (device.isVirtual()) return false;
|
if (device.isVirtual()) return false;
|
||||||
int sources = device.getSources();
|
int sources = device.getSources();
|
||||||
if ((sources & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD) return true;
|
return (sources & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD
|
||||||
if ((sources & InputDevice.SOURCE_JOYSTICK) != InputDevice.SOURCE_JOYSTICK) return false;
|
|| (sources & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK;
|
||||||
if (device.getKeyboardType() != InputDevice.KEYBOARD_TYPE_ALPHABETIC) return true;
|
|
||||||
// Some composite keyboards advertise joystick input without any sticks or pad buttons.
|
|
||||||
// A keyboard's mouse ranges do not establish a joystick; a real hybrid's joystick ranges
|
|
||||||
// or physical controller buttons do. GAMEPAD above remains authoritative even with keys.
|
|
||||||
for (int axis : JOYSTICK_AXES) {
|
|
||||||
InputDevice.MotionRange range = device.getMotionRange(axis, InputDevice.SOURCE_JOYSTICK);
|
|
||||||
if (range != null && range.getMax() > range.getMin()) return true;
|
|
||||||
}
|
|
||||||
for (boolean present : device.hasKeys(CONTROLLER_BUTTONS)) {
|
|
||||||
if (present) return true;
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Whether this key belongs to the pad, rather than a keyboard on the same input device. */
|
|
||||||
public static boolean isControllerKeyEvent(KeyEvent event) {
|
|
||||||
InputDevice device = event.getDevice();
|
|
||||||
if (device == null || device.isVirtual()) return false;
|
|
||||||
// An explicit pad button is unambiguous even when a hybrid omits its capabilities.
|
|
||||||
if (KeyEvent.isGamepadButton(event.getKeyCode())) {
|
|
||||||
return device.supportsSource(InputDevice.SOURCE_GAMEPAD)
|
|
||||||
|| device.supportsSource(InputDevice.SOURCE_JOYSTICK);
|
|
||||||
}
|
|
||||||
switch (event.getKeyCode()) {
|
|
||||||
case KeyEvent.KEYCODE_DPAD_UP:
|
|
||||||
case KeyEvent.KEYCODE_DPAD_RIGHT:
|
|
||||||
case KeyEvent.KEYCODE_DPAD_DOWN:
|
|
||||||
case KeyEvent.KEYCODE_DPAD_LEFT:
|
|
||||||
case KeyEvent.KEYCODE_BACK:
|
|
||||||
case KeyEvent.KEYCODE_MENU:
|
|
||||||
case KeyEvent.KEYCODE_HOME:
|
|
||||||
if (!isFromController(device)) return false;
|
|
||||||
// Without GAMEPAD, an alphabetic hybrid's keyboard arrows remain keyboard keys.
|
|
||||||
// Its ambiguous navigation keys need explicit pad/joystick event provenance;
|
|
||||||
// DPAD alone also describes ordinary keyboard arrows.
|
|
||||||
return device.supportsSource(InputDevice.SOURCE_GAMEPAD)
|
|
||||||
|| device.getKeyboardType() != InputDevice.KEYBOARD_TYPE_ALPHABETIC
|
|
||||||
|| event.isFromSource(InputDevice.SOURCE_GAMEPAD)
|
|
||||||
|| event.isFromSource(InputDevice.SOURCE_JOYSTICK);
|
|
||||||
default: return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Mouse motion on a composite controller still belongs to the pointer, not its sticks. */
|
|
||||||
public static boolean isControllerMotionEvent(MotionEvent event) {
|
|
||||||
InputDevice device = event.getDevice();
|
|
||||||
// An actual joystick event, like a pad button, survives a hybrid's missing capabilities.
|
|
||||||
return event.isFromSource(InputDevice.SOURCE_JOYSTICK) && device != null && !device.isVirtual()
|
|
||||||
&& (device.supportsSource(InputDevice.SOURCE_GAMEPAD)
|
|
||||||
|| device.supportsSource(InputDevice.SOURCE_JOYSTICK));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A Bluetooth keyboard can share a device with a joystick. Classify the key, not just
|
/** A Bluetooth keyboard can share a device with a joystick. Classify the key, not just
|
||||||
@@ -257,14 +189,6 @@ public final class PadBridge {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Publishes every currently connected controller so the client can enumerate all players. */
|
|
||||||
public synchronized void syncConnectedControllers() {
|
|
||||||
for (int deviceId : InputDevice.getDeviceIds()) {
|
|
||||||
InputDevice device = InputDevice.getDevice(deviceId);
|
|
||||||
if (isFromController(device)) publish(slotFor(device));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Called (main thread) when a player presses a button, pushes a stick, trigger or d-pad past
|
* Called (main thread) when a player presses a button, pushes a stick, trigger or d-pad past
|
||||||
* halfway, or uses the on-screen controls - the session hides its mouse cursor then. Resting
|
* halfway, or uses the on-screen controls - the session hides its mouse cursor then. Resting
|
||||||
@@ -285,9 +209,10 @@ public final class PadBridge {
|
|||||||
|
|
||||||
/** @return true when the event was a pad button and has been consumed. */
|
/** @return true when the event was a pad button and has been consumed. */
|
||||||
public synchronized boolean onKeyEvent(KeyEvent event) {
|
public synchronized boolean onKeyEvent(KeyEvent event) {
|
||||||
if (!isControllerKeyEvent(event)) return false;
|
if (!isControllerKey(event)) return false;
|
||||||
int slot = slotFor(event.getDevice());
|
int slot = slotFor(event.getDevice());
|
||||||
PadState pad = stateFor(slot);
|
PadState pad = stateFor(slot);
|
||||||
|
noteDevice(event.getDevice(), slot);
|
||||||
boolean pressed = event.getAction() == KeyEvent.ACTION_DOWN;
|
boolean pressed = event.getAction() == KeyEvent.ACTION_DOWN;
|
||||||
switch (event.getKeyCode()) {
|
switch (event.getKeyCode()) {
|
||||||
case KeyEvent.KEYCODE_BUTTON_A: pad.press(0, pressed); break;
|
case KeyEvent.KEYCODE_BUTTON_A: pad.press(0, pressed); break;
|
||||||
@@ -297,11 +222,6 @@ public final class PadBridge {
|
|||||||
case KeyEvent.KEYCODE_BUTTON_L1: pad.press(4, pressed); break;
|
case KeyEvent.KEYCODE_BUTTON_L1: pad.press(4, pressed); break;
|
||||||
case KeyEvent.KEYCODE_BUTTON_R1: pad.press(5, pressed); break;
|
case KeyEvent.KEYCODE_BUTTON_R1: pad.press(5, pressed); break;
|
||||||
case KeyEvent.KEYCODE_BUTTON_SELECT:
|
case KeyEvent.KEYCODE_BUTTON_SELECT:
|
||||||
// Optionally (Setup → Controller) the physical Select button opens the Steam menu
|
|
||||||
// instead of View/Select: on some handhelds it sits next to the Steam button.
|
|
||||||
if (selectSteam) pad.press(PadState.GUIDE, pressed);
|
|
||||||
else pad.press(6, pressed);
|
|
||||||
break;
|
|
||||||
case KeyEvent.KEYCODE_BACK: pad.press(6, pressed); break;
|
case KeyEvent.KEYCODE_BACK: pad.press(6, pressed); break;
|
||||||
case KeyEvent.KEYCODE_BUTTON_START:
|
case KeyEvent.KEYCODE_BUTTON_START:
|
||||||
case KeyEvent.KEYCODE_MENU: pad.press(7, pressed); break;
|
case KeyEvent.KEYCODE_MENU: pad.press(7, pressed); break;
|
||||||
@@ -319,7 +239,6 @@ public final class PadBridge {
|
|||||||
case KeyEvent.KEYCODE_DPAD_LEFT: pad.left = pressed; break;
|
case KeyEvent.KEYCODE_DPAD_LEFT: pad.left = pressed; break;
|
||||||
default: return false;
|
default: return false;
|
||||||
}
|
}
|
||||||
noteDevice(event.getDevice(), slot);
|
|
||||||
if (pressed) notePlayerInput();
|
if (pressed) notePlayerInput();
|
||||||
statButtons++;
|
statButtons++;
|
||||||
scheduleStats();
|
scheduleStats();
|
||||||
@@ -329,7 +248,7 @@ public final class PadBridge {
|
|||||||
|
|
||||||
/** @return true when the event was a pad's sticks/triggers and has been consumed. */
|
/** @return true when the event was a pad's sticks/triggers and has been consumed. */
|
||||||
public synchronized boolean onMotionEvent(MotionEvent event) {
|
public synchronized boolean onMotionEvent(MotionEvent event) {
|
||||||
if (!isControllerMotionEvent(event)) return false;
|
if (!isFromController(event.getDevice())) return false;
|
||||||
if (event.getAction() != MotionEvent.ACTION_MOVE) return false;
|
if (event.getAction() != MotionEvent.ACTION_MOVE) return false;
|
||||||
int slot = slotFor(event.getDevice());
|
int slot = slotFor(event.getDevice());
|
||||||
PadState pad = stateFor(slot);
|
PadState pad = stateFor(slot);
|
||||||
@@ -377,23 +296,6 @@ public final class PadBridge {
|
|||||||
publish();
|
publish();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* A controller the app reads itself rather than through Android's input (the Steam Controller
|
|
||||||
* over Bluetooth, SteamControllerBle): its whole state, merged into the one exported slot as a
|
|
||||||
* physical pad's events are. Android has no device for it, so a game's rumble cannot reach it.
|
|
||||||
* It streams its state whether or not anything moved; {@code changed} is whether this one did.
|
|
||||||
*/
|
|
||||||
public synchronized void applyExternal(java.util.function.Consumer<PadState> mutation, boolean changed) {
|
|
||||||
mutation.accept(state);
|
|
||||||
if (changed) {
|
|
||||||
activeControllerId = NO_CONTROLLER;
|
|
||||||
notePlayerInput();
|
|
||||||
statButtons++;
|
|
||||||
scheduleStats();
|
|
||||||
}
|
|
||||||
publish();
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Touch-only Steam and QAM buttons, merged with physical input without changing its state. */
|
/** Touch-only Steam and QAM buttons, merged with physical input without changing its state. */
|
||||||
public synchronized void setSystemButtons(boolean guidePressed, boolean qamPressed) {
|
public synchronized void setSystemButtons(boolean guidePressed, boolean qamPressed) {
|
||||||
if (systemGuidePressed == guidePressed && systemQamPressed == qamPressed) return;
|
if (systemGuidePressed == guidePressed && systemQamPressed == qamPressed) return;
|
||||||
|
|||||||
@@ -20,10 +20,9 @@ import kotlin.math.roundToInt
|
|||||||
* and units as SDL's Deck driver undoes them (SDL_hidapi_steamdeck.c): X right, Y away from the
|
* and units as SDL's Deck driver undoes them (SDL_hidapi_steamdeck.c): X right, Y away from the
|
||||||
* player, Z up; 1 g = 16384, 2000 °/s = 32768. The Steam client calibrates the gyro itself.
|
* player, Z up; 1 g = 16384, 2000 °/s = 32768. The Steam client calibrates the gyro itself.
|
||||||
*
|
*
|
||||||
* Sensors run only while the session is on screen with the pad a Deck controller, and the client
|
* Sensors run only while the session is on screen with the pad a Deck controller, sampled as often
|
||||||
* wants motion (see [follow]), sampled as often as the Deck reports (4 ms); each reading goes
|
* as the Deck reports (4 ms); each reading goes straight into the pad's ring
|
||||||
* straight into the pad's ring ([FakeInputWriter.writeMotion]), where libfakeinput's 4 ms report
|
* ([FakeInputWriter.writeMotion]), where libfakeinput's 4 ms report picks up the latest.
|
||||||
* picks up the latest.
|
|
||||||
*/
|
*/
|
||||||
class PadMotion(private val context: Context, private val rotation: () -> Int) : SensorEventListener {
|
class PadMotion(private val context: Context, private val rotation: () -> Int) : SensorEventListener {
|
||||||
private val sensors = context.getSystemService(SensorManager::class.java)
|
private val sensors = context.getSystemService(SensorManager::class.java)
|
||||||
@@ -33,11 +32,6 @@ class PadMotion(private val context: Context, private val rotation: () -> Int) :
|
|||||||
// Touched only on the worker thread.
|
// Touched only on the worker thread.
|
||||||
private val accel = ShortArray(3)
|
private val accel = ShortArray(3)
|
||||||
private val gyro = ShortArray(3)
|
private val gyro = ShortArray(3)
|
||||||
private var reading = false
|
|
||||||
private var idlePolls = 0
|
|
||||||
// Asking the display costs more than the rest of a reading, which arrives every 2 ms.
|
|
||||||
private var turn = Surface.ROTATION_0
|
|
||||||
private var turnAt = 0L
|
|
||||||
|
|
||||||
fun start() {
|
fun start() {
|
||||||
if (thread != null || sensors == null) return
|
if (thread != null || sensors == null) return
|
||||||
@@ -51,13 +45,8 @@ class PadMotion(private val context: Context, private val rotation: () -> Int) :
|
|||||||
thread = worker
|
thread = worker
|
||||||
val handler = Handler(worker.looper)
|
val handler = Handler(worker.looper)
|
||||||
active = true
|
active = true
|
||||||
handler.post(object : Runnable {
|
gyroscope?.let { sensors.registerListener(this, it, SAMPLING_US, handler) }
|
||||||
override fun run() {
|
accelerometer?.let { sensors.registerListener(this, it, SAMPLING_US, handler) }
|
||||||
if (!active) return
|
|
||||||
follow(handler, gyroscope, accelerometer)
|
|
||||||
handler.postDelayed(this, POLL_MS)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
Log.i(TAG, "pad motion: gyro ${gyroscope?.name ?: "none"}, accelerometer ${accelerometer?.name ?: "none"}")
|
Log.i(TAG, "pad motion: gyro ${gyroscope?.name ?: "none"}, accelerometer ${accelerometer?.name ?: "none"}")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -65,71 +54,31 @@ class PadMotion(private val context: Context, private val rotation: () -> Int) :
|
|||||||
val worker = thread ?: return
|
val worker = thread ?: return
|
||||||
thread = null
|
thread = null
|
||||||
active = false
|
active = false
|
||||||
// On the worker, after any poll or reading already queued there, so nothing registers again
|
sensors?.unregisterListener(this)
|
||||||
// or overwrites the still controller.
|
// A still controller, not one frozen mid-turn - published on the worker, after any reading
|
||||||
|
// already queued there, so nothing can overwrite it.
|
||||||
Handler(worker.looper).post {
|
Handler(worker.looper).post {
|
||||||
sensors?.unregisterListener(this)
|
gyro.fill(0)
|
||||||
reading = false
|
FakeInputWriter.writeMotion(SLOT, accel, gyro)
|
||||||
idlePolls = 0
|
SteamTouchDevice.current?.setMotion(accel, gyro)
|
||||||
still()
|
|
||||||
}
|
}
|
||||||
worker.quitSafely()
|
worker.quitSafely()
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Reads the sensors while the client wants motion: the Deck's IMU mode (unknown counts as
|
|
||||||
* wanted), or Steam's touch controls asking for gyro. A game whose layout has no gyro turns the
|
|
||||||
* mode off; Steam's own menus keep it on. The client also turns it off and on again for a few
|
|
||||||
* ms whenever it re-applies a layout, so the sensors stop only after two polls without it.
|
|
||||||
*/
|
|
||||||
private fun follow(handler: Handler, gyroscope: Sensor?, accelerometer: Sensor?) {
|
|
||||||
val touch = SteamTouchDevice.current
|
|
||||||
val wanted = FakeInputWriter.readImuMode(SLOT) != 0 ||
|
|
||||||
touch != null && touch.plugged && touch.gyroRequested && touch.motionEnabled
|
|
||||||
idlePolls = if (wanted) 0 else idlePolls + 1
|
|
||||||
if (wanted && !reading) {
|
|
||||||
reading = true
|
|
||||||
turnAt = 0L
|
|
||||||
gyroscope?.let { sensors?.registerListener(this, it, SAMPLING_US, handler) }
|
|
||||||
accelerometer?.let { sensors?.registerListener(this, it, SAMPLING_US, handler) }
|
|
||||||
Log.i(TAG, "pad motion: reading")
|
|
||||||
} else if (reading && idlePolls >= 2) {
|
|
||||||
reading = false
|
|
||||||
sensors?.unregisterListener(this)
|
|
||||||
still()
|
|
||||||
Log.i(TAG, "pad motion: paused, the client wants none")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A still controller, not one frozen mid-turn. */
|
|
||||||
private fun still() {
|
|
||||||
gyro.fill(0)
|
|
||||||
FakeInputWriter.writeMotion(SLOT, accel, gyro)
|
|
||||||
SteamTouchDevice.current?.setMotion(accel, gyro)
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onSensorChanged(event: SensorEvent) {
|
override fun onSensorChanged(event: SensorEvent) {
|
||||||
if (!active) return
|
if (!active) return
|
||||||
val values = event.values
|
val values = event.values
|
||||||
if (event.timestamp - turnAt > ROTATION_REFRESH_NS) {
|
|
||||||
turn = rotation()
|
|
||||||
turnAt = event.timestamp
|
|
||||||
}
|
|
||||||
// Natural orientation to the screen's: Android's display-rotation transform.
|
// Natural orientation to the screen's: Android's display-rotation transform.
|
||||||
val x: Float
|
val (x, y) = when (rotation()) {
|
||||||
val y: Float
|
Surface.ROTATION_90 -> -values[1] to values[0]
|
||||||
when (turn) {
|
Surface.ROTATION_180 -> -values[0] to -values[1]
|
||||||
Surface.ROTATION_90 -> { x = -values[1]; y = values[0] }
|
Surface.ROTATION_270 -> values[1] to -values[0]
|
||||||
Surface.ROTATION_180 -> { x = -values[0]; y = -values[1] }
|
else -> values[0] to values[1]
|
||||||
Surface.ROTATION_270 -> { x = values[1]; y = -values[0] }
|
|
||||||
else -> { x = values[0]; y = values[1] }
|
|
||||||
}
|
}
|
||||||
val z = values[2]
|
val z = values[2]
|
||||||
val target: ShortArray
|
val (target, scale) = when (event.sensor.type) {
|
||||||
val scale: Float
|
Sensor.TYPE_GYROSCOPE -> gyro to GYRO_COUNTS_PER_RAD_S
|
||||||
when (event.sensor.type) {
|
Sensor.TYPE_ACCELEROMETER -> accel to ACCEL_COUNTS_PER_M_S2
|
||||||
Sensor.TYPE_GYROSCOPE -> { target = gyro; scale = GYRO_COUNTS_PER_RAD_S }
|
|
||||||
Sensor.TYPE_ACCELEROMETER -> { target = accel; scale = ACCEL_COUNTS_PER_M_S2 }
|
|
||||||
else -> return
|
else -> return
|
||||||
}
|
}
|
||||||
// Screen frame (right, up, towards the player) to the Deck's (right, away, up).
|
// Screen frame (right, up, towards the player) to the Deck's (right, away, up).
|
||||||
@@ -150,9 +99,6 @@ class PadMotion(private val context: Context, private val rotation: () -> Int) :
|
|||||||
private const val SLOT = 0
|
private const val SLOT = 0
|
||||||
/** The Deck controller's report interval (libfakeinput: DECK_REPORT_INTERVAL_US). */
|
/** The Deck controller's report interval (libfakeinput: DECK_REPORT_INTERVAL_US). */
|
||||||
private const val SAMPLING_US = 4000
|
private const val SAMPLING_US = 4000
|
||||||
/** How often [follow] checks whether the client wants motion. */
|
|
||||||
private const val POLL_MS = 500L
|
|
||||||
private const val ROTATION_REFRESH_NS = 250_000_000L
|
|
||||||
private const val ACCEL_COUNTS_PER_M_S2 = 16384f / SensorManager.GRAVITY_EARTH
|
private const val ACCEL_COUNTS_PER_M_S2 = 16384f / SensorManager.GRAVITY_EARTH
|
||||||
private const val GYRO_COUNTS_PER_RAD_S = (32768f / 2000f) * (180f / Math.PI.toFloat())
|
private const val GYRO_COUNTS_PER_RAD_S = (32768f / 2000f) * (180f / Math.PI.toFloat())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,362 +0,0 @@
|
|||||||
package com.droiddeck.launcher.input
|
|
||||||
|
|
||||||
import android.annotation.SuppressLint
|
|
||||||
import android.bluetooth.BluetoothAdapter
|
|
||||||
import android.bluetooth.BluetoothDevice
|
|
||||||
import android.bluetooth.BluetoothGatt
|
|
||||||
import android.bluetooth.BluetoothGattCallback
|
|
||||||
import android.bluetooth.BluetoothGattCharacteristic
|
|
||||||
import android.bluetooth.BluetoothGattDescriptor
|
|
||||||
import android.bluetooth.BluetoothManager
|
|
||||||
import android.bluetooth.BluetoothProfile
|
|
||||||
import android.content.Context
|
|
||||||
import android.os.Handler
|
|
||||||
import android.os.HandlerThread
|
|
||||||
import android.util.Log
|
|
||||||
import java.nio.ByteBuffer
|
|
||||||
import java.nio.ByteOrder
|
|
||||||
import java.util.ArrayDeque
|
|
||||||
import java.util.UUID
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Reads the Steam Controller (2025, Triton) through its Valve BLE service. State reports remain
|
|
||||||
* native Triton packets and are published to the session's separate 28DE:1303 HID device. Steam's
|
|
||||||
* output reports travel back to their matching BLE characteristics, preserving grip capacitance,
|
|
||||||
* trackpads, sensors, and controller haptics without folding the controller into the Deck target.
|
|
||||||
*
|
|
||||||
* Lizard mode is refreshed while connected; when a session ends, the controller restores it itself.
|
|
||||||
*/
|
|
||||||
@SuppressLint("MissingPermission") // BLUETOOTH is granted at install below targetSdk 31
|
|
||||||
class SteamControllerBle(private val context: Context) {
|
|
||||||
private val thread = HandlerThread("steam-controller-ble").apply { start() }
|
|
||||||
private val handler = Handler(thread.looper)
|
|
||||||
private val outputReports = mutableMapOf<Int, UUID>()
|
|
||||||
/** GATT allows one operation at a time: writes carry a value, a feature read none. */
|
|
||||||
private val queuedWrites = ArrayDeque<Pair<UUID, ByteArray?>>()
|
|
||||||
private var gatt: BluetoothGatt? = null
|
|
||||||
private var running = false
|
|
||||||
private var input: UUID? = null
|
|
||||||
private var reportId = 0
|
|
||||||
private var lizardOffSent = false
|
|
||||||
private var reportedNone = false
|
|
||||||
private var discoveries = 0
|
|
||||||
private var outputSequence = 0L
|
|
||||||
private var outputWritePending = false
|
|
||||||
/** The Steam client's feature read being answered, so the poll queues each one once. */
|
|
||||||
private var featureRead = 0L
|
|
||||||
|
|
||||||
/** Looks for a paired Steam Controller and keeps a connection to it until [stop]. */
|
|
||||||
fun start() = handler.post {
|
|
||||||
if (running) return@post
|
|
||||||
running = true
|
|
||||||
Log.i(TAG, "looking for a paired Steam Controller")
|
|
||||||
connect()
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Lets the controller go (it returns to lizard mode by itself); this object is done after. */
|
|
||||||
fun stop() = handler.post {
|
|
||||||
running = false
|
|
||||||
handler.removeCallbacksAndMessages(null)
|
|
||||||
disconnect("session ended")
|
|
||||||
thread.quitSafely()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun connect() {
|
|
||||||
if (!running || gatt != null) return
|
|
||||||
val adapter = (context.getSystemService(Context.BLUETOOTH_SERVICE) as? BluetoothManager)?.adapter
|
|
||||||
val bonded = runCatching { adapter?.takeIf(BluetoothAdapter::isEnabled)?.bondedDevices }
|
|
||||||
.onFailure { Log.w(TAG, "paired devices unreadable", it) }
|
|
||||||
.getOrNull()
|
|
||||||
val device = bonded?.firstOrNull(::isSteamController)
|
|
||||||
if (device == null) {
|
|
||||||
if (!reportedNone) {
|
|
||||||
reportedNone = true
|
|
||||||
Log.i(TAG, "no paired Steam Controller (Bluetooth ${if (adapter?.isEnabled == true) "on" else "off"}; paired: " +
|
|
||||||
(bonded?.joinToString { "\"${it.name}\" type ${it.type}" } ?: "unreadable") + "); looking again every ${RETRY_MS / 1000} s")
|
|
||||||
}
|
|
||||||
handler.postDelayed(::connect, RETRY_MS)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
Log.i(TAG, "connecting to \"${device.name}\"")
|
|
||||||
gatt = device.connectGatt(context, false, callback, BluetoothDevice.TRANSPORT_LE, BluetoothDevice.PHY_LE_1M_MASK, handler)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun disconnect(why: String) {
|
|
||||||
val g = gatt ?: return
|
|
||||||
gatt = null
|
|
||||||
discoveries = 0
|
|
||||||
input = null
|
|
||||||
lizardOffSent = false
|
|
||||||
outputWritePending = false
|
|
||||||
featureRead = 0L
|
|
||||||
queuedWrites.clear()
|
|
||||||
outputReports.clear()
|
|
||||||
connected = false
|
|
||||||
FakeInputWriter.setTritonConnected(SLOT, false)
|
|
||||||
g.disconnect()
|
|
||||||
g.close()
|
|
||||||
release()
|
|
||||||
Log.i(TAG, "disconnected: $why")
|
|
||||||
listener?.invoke()
|
|
||||||
}
|
|
||||||
|
|
||||||
private val callback = object : BluetoothGattCallback() {
|
|
||||||
override fun onConnectionStateChange(g: BluetoothGatt, status: Int, newState: Int) {
|
|
||||||
if (g !== gatt) return
|
|
||||||
if (newState == BluetoothProfile.STATE_CONNECTED) {
|
|
||||||
g.discoverServices()
|
|
||||||
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
|
|
||||||
disconnect("link lost (status $status)")
|
|
||||||
if (running) handler.postDelayed(::connect, RETRY_MS)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onServicesDiscovered(g: BluetoothGatt, status: Int) {
|
|
||||||
if (g !== gatt) return
|
|
||||||
if (status != BluetoothGatt.GATT_SUCCESS) {
|
|
||||||
disconnect("service discovery failed (status $status)")
|
|
||||||
if (running) handler.postDelayed(::connect, RETRY_MS)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
// The Triton needs data length extensions, which Android enables for a large MTU.
|
|
||||||
if (!g.requestMtu(517)) subscribe(g)
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onMtuChanged(g: BluetoothGatt, mtu: Int, status: Int) {
|
|
||||||
if (g === gatt) subscribe(g)
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onDescriptorWrite(g: BluetoothGatt, descriptor: BluetoothGattDescriptor, status: Int) {
|
|
||||||
if (g !== gatt || descriptor.characteristic.uuid != input) return
|
|
||||||
Log.i(TAG, "subscribed to report 0x%02x (status %d)".format(reportId, status))
|
|
||||||
connected = status == BluetoothGatt.GATT_SUCCESS
|
|
||||||
FakeInputWriter.setTritonConnected(SLOT, connected)
|
|
||||||
listener?.invoke()
|
|
||||||
if (connected) {
|
|
||||||
refreshLizardMode()
|
|
||||||
pollOutput()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onCharacteristicWrite(g: BluetoothGatt, characteristic: BluetoothGattCharacteristic, status: Int) {
|
|
||||||
if (g !== gatt) return
|
|
||||||
if (characteristic.uuid == REPORT && !lizardOffSent) {
|
|
||||||
lizardOffSent = true
|
|
||||||
Log.i(TAG, "lizard mode off (status $status)")
|
|
||||||
} else if (status != BluetoothGatt.GATT_SUCCESS) {
|
|
||||||
Log.w(TAG, "output report write failed for ${characteristic.uuid} (status $status)")
|
|
||||||
}
|
|
||||||
outputWritePending = false
|
|
||||||
writeNextOutput()
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onCharacteristicRead(g: BluetoothGatt, characteristic: BluetoothGattCharacteristic, value: ByteArray, status: Int) {
|
|
||||||
if (g === gatt) onFeatureRead(value.takeIf { status == BluetoothGatt.GATT_SUCCESS })
|
|
||||||
}
|
|
||||||
|
|
||||||
@Deprecated("Below Android 13 only", ReplaceWith(""))
|
|
||||||
override fun onCharacteristicRead(g: BluetoothGatt, characteristic: BluetoothGattCharacteristic, status: Int) {
|
|
||||||
@Suppress("DEPRECATION")
|
|
||||||
if (g === gatt) onFeatureRead(characteristic.value.takeIf { status == BluetoothGatt.GATT_SUCCESS })
|
|
||||||
}
|
|
||||||
|
|
||||||
// Android 13 hands the value over with the call; older ones only through the characteristic.
|
|
||||||
override fun onCharacteristicChanged(g: BluetoothGatt, characteristic: BluetoothGattCharacteristic, value: ByteArray) {
|
|
||||||
if (g === gatt && characteristic.uuid == input) onState(value)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Deprecated("Below Android 13 only", ReplaceWith(""))
|
|
||||||
override fun onCharacteristicChanged(g: BluetoothGatt, characteristic: BluetoothGattCharacteristic) {
|
|
||||||
@Suppress("DEPRECATION")
|
|
||||||
if (g === gatt && characteristic.uuid == input) onState(characteristic.value ?: return)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun subscribe(g: BluetoothGatt) {
|
|
||||||
val service = g.getService(SERVICE)
|
|
||||||
if (service == null) {
|
|
||||||
Log.w(TAG, "no Valve service on \"${g.device.name}\" (attempt ${discoveries + 1}); services: " +
|
|
||||||
g.services.joinToString { it.uuid.toString().take(8) })
|
|
||||||
// Android may answer from the service list its HID host cached, which can lack the
|
|
||||||
// vendor service: ask the controller again before giving up on it.
|
|
||||||
if (++discoveries < 3) {
|
|
||||||
refreshCache(g)
|
|
||||||
handler.postDelayed({ if (g === gatt) g.discoverServices() }, 500)
|
|
||||||
} else {
|
|
||||||
disconnect("no Valve service")
|
|
||||||
if (running) handler.postDelayed(::connect, RETRY_MS)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
val chr = service.getCharacteristic(INPUT_0X47)?.also { reportId = 0x47 }
|
|
||||||
?: service.getCharacteristic(INPUT_0X45)?.also { reportId = 0x45 }
|
|
||||||
if (chr == null) {
|
|
||||||
disconnect("no state report characteristic")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
outputReports.clear()
|
|
||||||
service.characteristics.forEach { characteristic ->
|
|
||||||
val uuid = characteristic.uuid.toString().lowercase()
|
|
||||||
if (uuid.startsWith(OUTPUT_UUID_PREFIX)) {
|
|
||||||
val characteristicId = uuid.substring(6, 8).toIntOrNull(16) ?: return@forEach
|
|
||||||
val outputId = characteristicId - OUTPUT_UUID_OFFSET
|
|
||||||
if (outputId in 0x80..0x85) outputReports[outputId] = characteristic.uuid
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Log.i(TAG, "found Triton haptic reports: ${outputReports.keys.sorted().joinToString { "0x%02x".format(it) }}")
|
|
||||||
input = chr.uuid
|
|
||||||
g.setCharacteristicNotification(chr, true)
|
|
||||||
val cccd = chr.getDescriptor(CCCD) ?: return disconnect("state report cannot notify")
|
|
||||||
@Suppress("DEPRECATION")
|
|
||||||
cccd.value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
|
|
||||||
@Suppress("DEPRECATION")
|
|
||||||
g.writeDescriptor(cccd)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** BluetoothGatt.refresh(): hidden, but used to drop stale service caches. */
|
|
||||||
private fun refreshCache(g: BluetoothGatt) {
|
|
||||||
runCatching { g.javaClass.getMethod("refresh").invoke(g) }
|
|
||||||
.onFailure { Log.w(TAG, "could not refresh the service cache", it) }
|
|
||||||
}
|
|
||||||
|
|
||||||
/** SDL's DisableSteamTritonLizardMode: ID_SET_SETTINGS_VALUES (0x87), setting 9 = off. */
|
|
||||||
private fun refreshLizardMode() {
|
|
||||||
if (!connected) return
|
|
||||||
val msg = ByteArray(FEATURE_BYTES)
|
|
||||||
msg[0] = 0x87.toByte(); msg[1] = 3; msg[2] = 9
|
|
||||||
enqueueOutput(REPORT, msg)
|
|
||||||
handler.postDelayed(::refreshLizardMode, LIZARD_REFRESH_MS)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Preserve the full 0x45 or 0x47 packet so Triton-only bits reach Steam's native driver. */
|
|
||||||
private fun onState(data: ByteArray) {
|
|
||||||
if (data.size < STATE_BYTES) return
|
|
||||||
FakeInputWriter.writeTritonState(SLOT, reportId, data)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A neutral report prevents a link lost mid-press from leaving controls held. */
|
|
||||||
private fun release() {
|
|
||||||
FakeInputWriter.writeTritonState(SLOT, if (reportId == 0x47) 0x47 else 0x45, ByteArray(STATE_BYTES))
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Drain Steam HID output reports and write each to Triton's matching BLE characteristic. */
|
|
||||||
private fun pollOutput() {
|
|
||||||
if (!running || !connected || gatt == null) return
|
|
||||||
FakeInputWriter.readTritonOutput(SLOT, outputSequence)?.let { output ->
|
|
||||||
outputSequence = ByteBuffer.wrap(output, 0, 8).order(ByteOrder.LITTLE_ENDIAN).long
|
|
||||||
sendOutputReport(output[8] != 0.toByte(), output.copyOfRange(9, output.size))
|
|
||||||
}
|
|
||||||
val request = FakeInputWriter.readTritonFeatureRequest(SLOT)
|
|
||||||
if (request != 0L && request != featureRead) {
|
|
||||||
featureRead = request
|
|
||||||
// Behind any queued write, so a read answers the feature report written before it.
|
|
||||||
queuedWrites.addLast(REPORT to null)
|
|
||||||
writeNextOutput()
|
|
||||||
}
|
|
||||||
handler.postDelayed(::pollOutput, OUTPUT_POLL_MS)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The controller's answer to a feature read (its info, for one), or null when the read failed. */
|
|
||||||
private fun onFeatureRead(value: ByteArray?) {
|
|
||||||
outputWritePending = false
|
|
||||||
if (featureRead != 0L) {
|
|
||||||
if (value == null) Log.w(TAG, "feature read failed")
|
|
||||||
FakeInputWriter.writeTritonFeatureReply(SLOT, featureRead, value)
|
|
||||||
}
|
|
||||||
writeNextOutput()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun sendOutputReport(feature: Boolean, report: ByteArray) {
|
|
||||||
if (report.size < 2) return
|
|
||||||
val characteristic = if (feature) {
|
|
||||||
REPORT
|
|
||||||
} else {
|
|
||||||
val id = report[0].toInt() and 0xff
|
|
||||||
outputReports[id] ?: run {
|
|
||||||
Log.w(TAG, "no BLE output characteristic for report 0x%02x".format(id))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// SDL's BLE driver removes the HID report ID and trailing padding byte before transmission.
|
|
||||||
enqueueOutput(characteristic, report.copyOfRange(1, report.size - 1))
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun enqueueOutput(characteristic: UUID, value: ByteArray?) {
|
|
||||||
queuedWrites.addLast(characteristic to value)
|
|
||||||
writeNextOutput()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun writeNextOutput() {
|
|
||||||
if (outputWritePending) return
|
|
||||||
val g = gatt ?: return
|
|
||||||
val (uuid, value) = queuedWrites.pollFirst() ?: return
|
|
||||||
val characteristic = g.getService(SERVICE)?.getCharacteristic(uuid)
|
|
||||||
if (characteristic == null) {
|
|
||||||
Log.w(TAG, "BLE output characteristic $uuid disappeared")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (value == null) {
|
|
||||||
if (g.readCharacteristic(characteristic)) {
|
|
||||||
outputWritePending = true
|
|
||||||
} else {
|
|
||||||
queuedWrites.addFirst(uuid to null)
|
|
||||||
handler.postDelayed(::writeNextOutput, OUTPUT_RETRY_MS)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
@Suppress("DEPRECATION")
|
|
||||||
characteristic.writeType = BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT
|
|
||||||
@Suppress("DEPRECATION")
|
|
||||||
characteristic.value = value
|
|
||||||
@Suppress("DEPRECATION")
|
|
||||||
if (!g.writeCharacteristic(characteristic)) {
|
|
||||||
queuedWrites.addFirst(uuid to value)
|
|
||||||
handler.postDelayed(::writeNextOutput, OUTPUT_RETRY_MS)
|
|
||||||
} else {
|
|
||||||
outputWritePending = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
companion object {
|
|
||||||
private const val TAG = "SteamControllerBle"
|
|
||||||
/** The paired controller's native Triton reports live in slot 0's extended ring. */
|
|
||||||
private const val SLOT = 0
|
|
||||||
private const val RETRY_MS = 5_000L
|
|
||||||
private const val LIZARD_REFRESH_MS = 3_000L
|
|
||||||
private const val OUTPUT_POLL_MS = 4L
|
|
||||||
private const val OUTPUT_RETRY_MS = 10L
|
|
||||||
/** SDL's 64-byte feature report less the report ID and the trailing byte. */
|
|
||||||
private const val FEATURE_BYTES = 62
|
|
||||||
private const val STATE_BYTES = 45
|
|
||||||
private const val OUTPUT_UUID_PREFIX = "100f6c"
|
|
||||||
private const val OUTPUT_UUID_OFFSET = 0x35
|
|
||||||
|
|
||||||
private val SERVICE = UUID.fromString("100F6C32-1735-4313-B402-38567131E5F3")
|
|
||||||
private val INPUT_0X45 = UUID.fromString("100F6C7A-1735-4313-B402-38567131E5F3")
|
|
||||||
private val INPUT_0X47 = UUID.fromString("100F6C7C-1735-4313-B402-38567131E5F3")
|
|
||||||
private val REPORT = UUID.fromString("100F6C34-1735-4313-B402-38567131E5F3")
|
|
||||||
private val CCCD = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb")
|
|
||||||
|
|
||||||
private fun isSteamController(device: BluetoothDevice): Boolean =
|
|
||||||
device.type and BluetoothDevice.DEVICE_TYPE_LE != 0 &&
|
|
||||||
(device.name ?: "").let { it.startsWith("Steam Ctrl") || it.startsWith("SteamController") }
|
|
||||||
|
|
||||||
/** Whether a session should expose a Triton HID node for a paired controller. */
|
|
||||||
@JvmStatic
|
|
||||||
fun hasPairedController(context: Context): Boolean {
|
|
||||||
val adapter = (context.getSystemService(Context.BLUETOOTH_SERVICE) as? BluetoothManager)?.adapter ?: return false
|
|
||||||
return runCatching { adapter.isEnabled && adapter.bondedDevices.any(::isSteamController) }
|
|
||||||
.onFailure { Log.w(TAG, "paired devices unreadable", it) }
|
|
||||||
.getOrDefault(false)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A Steam Controller is connected and feeding its native HID reports. */
|
|
||||||
@Volatile @JvmStatic
|
|
||||||
var connected = false
|
|
||||||
private set
|
|
||||||
|
|
||||||
/** Notifies the activity when [connected] changes. */
|
|
||||||
@Volatile @JvmStatic
|
|
||||||
var listener: (() -> Unit)? = null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -256,20 +256,6 @@ object AppImageManager {
|
|||||||
"Terminal=false\nCategories=$categories\nX-DroidDeck-AppImage=$id\n")
|
"Terminal=false\nCategories=$categories\nX-DroidDeck-AppImage=$id\n")
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The desktop's import of [key]; older ones of the image at [path], since replaced, are removed. */
|
|
||||||
fun desktopImport(context: Context, key: String, path: String): String? {
|
|
||||||
var found: String? = null
|
|
||||||
root(context).listFiles()?.forEach { dir ->
|
|
||||||
val asked = FileUtils.readString(File(dir, UserApps.DESKTOP_IMPORT))?.lines() ?: return@forEach
|
|
||||||
if (asked.firstOrNull() == key) {
|
|
||||||
if (File(dir, "app").isDirectory) found = dir.name
|
|
||||||
} else if (asked.getOrNull(1) == path) {
|
|
||||||
remove(context, dir.name)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return found
|
|
||||||
}
|
|
||||||
|
|
||||||
fun remove(context: Context, id: String) {
|
fun remove(context: Context, id: String) {
|
||||||
if (id.isEmpty() || '/' in id || id.startsWith(".")) return
|
if (id.isEmpty() || '/' in id || id.startsWith(".")) return
|
||||||
FileUtils.delete(File(root(context), id))
|
FileUtils.delete(File(root(context), id))
|
||||||
|
|||||||
@@ -20,12 +20,12 @@ import java.io.File
|
|||||||
*/
|
*/
|
||||||
object DesktopCatalog {
|
object DesktopCatalog {
|
||||||
private const val TAG = "DesktopCatalog"
|
private const val TAG = "DesktopCatalog"
|
||||||
const val CATALOG_URL = "https://raw.githubusercontent.com/Droid-Deck/DroidDeck-Components/main/desktop.json"
|
const val CATALOG_URL = "https://raw.githubusercontent.com/The412Banner/winlator-contents/main/desktop.json"
|
||||||
/**
|
/**
|
||||||
* Valve's Proton Experimental (ARM64) with its appmanifest, laid out as the client keeps it.
|
* Valve's Proton Experimental (ARM64) with its appmanifest, laid out as the client keeps it.
|
||||||
* In a catalog of its own so it never shows among the packages a user picks from.
|
* In a catalog of its own so it never shows among the packages a user picks from.
|
||||||
*/
|
*/
|
||||||
const val STEAM_SEED_URL = "https://raw.githubusercontent.com/Droid-Deck/DroidDeck-Components/main/steam-seed.json"
|
const val STEAM_SEED_URL = "https://raw.githubusercontent.com/The412Banner/winlator-contents/main/steam-seed.json"
|
||||||
const val PROTON_SEED_ID = "proton-arm64"
|
const val PROTON_SEED_ID = "proton-arm64"
|
||||||
|
|
||||||
class Entry(
|
class Entry(
|
||||||
@@ -110,9 +110,6 @@ object DesktopCatalog {
|
|||||||
return File(root, DesktopRemoval.PENDING).exists() || marker(context, DESKTOP_ID).exists()
|
return File(root, DesktopRemoval.PENDING).exists() || marker(context, DESKTOP_ID).exists()
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The installed desktop's size on disk; off the main thread. */
|
|
||||||
fun desktopSize(context: Context): Long = DesktopRemoval.installedSize(context)
|
|
||||||
|
|
||||||
fun cleanLegacy(context: Context, listener: LinuxRuntimeInstaller.ProgressListener? = null) =
|
fun cleanLegacy(context: Context, listener: LinuxRuntimeInstaller.ProgressListener? = null) =
|
||||||
DesktopRemoval.cleanLegacy(context, listener)
|
DesktopRemoval.cleanLegacy(context, listener)
|
||||||
|
|
||||||
|
|||||||
@@ -19,14 +19,6 @@ internal object DesktopRemoval {
|
|||||||
private fun protected(context: Context, root: File) =
|
private fun protected(context: Context, root: File) =
|
||||||
DesktopFileRemoval.runtimeFiles(root) + lines(context, "emulators-keep.txt.gzip")
|
DesktopFileRemoval.runtimeFiles(root) + lines(context, "emulators-keep.txt.gzip")
|
||||||
|
|
||||||
/**
|
|
||||||
* What the desktop's own files take on disk, from the same inventory its removal uses (each
|
|
||||||
* file's size); the bundled apps' and emulators' shared files are not counted. Reads an asset:
|
|
||||||
* call it off the main thread.
|
|
||||||
*/
|
|
||||||
fun installedSize(context: Context): Long =
|
|
||||||
lines(context, "kde-remove.tsv.gzip").sumOf { line -> line.split('\t').getOrNull(1)?.toLongOrNull() ?: 0L }
|
|
||||||
|
|
||||||
/** Called before a guest starts or just after KDE extraction; retries after a process death. */
|
/** Called before a guest starts or just after KDE extraction; retries after a process death. */
|
||||||
fun cleanLegacy(context: Context, listener: LinuxRuntimeInstaller.ProgressListener? = null) {
|
fun cleanLegacy(context: Context, listener: LinuxRuntimeInstaller.ProgressListener? = null) {
|
||||||
val root = LinuxRuntime.rootDir(context)
|
val root = LinuxRuntime.rootDir(context)
|
||||||
|
|||||||
@@ -41,7 +41,7 @@ public final class LinuxRuntimeInstaller {
|
|||||||
|
|
||||||
/** Catalog row, beside the other component catalogs in winlator-contents. */
|
/** Catalog row, beside the other component catalogs in winlator-contents. */
|
||||||
public static final String CATALOG_URL =
|
public static final String CATALOG_URL =
|
||||||
"https://raw.githubusercontent.com/Droid-Deck/DroidDeck-Components/main/linuxfs.json";
|
"https://raw.githubusercontent.com/The412Banner/winlator-contents/main/linuxfs.json";
|
||||||
|
|
||||||
private static final String VERSION_FILE = ".version";
|
private static final String VERSION_FILE = ".version";
|
||||||
|
|
||||||
|
|||||||
@@ -32,8 +32,6 @@ object UserApps {
|
|||||||
private const val TAG = "UserApps"
|
private const val TAG = "UserApps"
|
||||||
const val GUEST_DIR = "/opt/droiddeck-apps"
|
const val GUEST_DIR = "/opt/droiddeck-apps"
|
||||||
const val SCRIPT_LAUNCHER = "/usr/local/bin/droiddeck-script-run"
|
const val SCRIPT_LAUNCHER = "/usr/local/bin/droiddeck-script-run"
|
||||||
/** An app the desktop asked for (droiddeck-open): its key, then the path it was started from there. */
|
|
||||||
const val DESKTOP_IMPORT = "desktop-import"
|
|
||||||
private const val FLATPAK_OVERRIDES = ".flatpak"
|
private const val FLATPAK_OVERRIDES = ".flatpak"
|
||||||
private const val ICON_SIZE = 256
|
private const val ICON_SIZE = 256
|
||||||
private const val ELF_SCAN_LIMIT = 4000
|
private const val ELF_SCAN_LIMIT = 4000
|
||||||
@@ -74,8 +72,8 @@ object UserApps {
|
|||||||
class FlatpakBundle(val file: File) : Source()
|
class FlatpakBundle(val file: File) : Source()
|
||||||
}
|
}
|
||||||
|
|
||||||
/** [icon]: a picked file's path or a suggested icon's URL. [meta]: files written into the added app's folder. */
|
/** [icon]: a picked file's path or a suggested icon's URL. */
|
||||||
class Request(val source: Source, val name: String?, val icon: String?, val meta: Map<String, String> = emptyMap())
|
class Request(val source: Source, val name: String?, val icon: String?)
|
||||||
|
|
||||||
/** How a script's folder reaches the session: linked in place, or copied in ([bytes] to copy). */
|
/** How a script's folder reaches the session: linked in place, or copied in ([bytes] to copy). */
|
||||||
class ScriptPlan(val folder: File, val copy: Boolean, val bytes: Long)
|
class ScriptPlan(val folder: File, val copy: Boolean, val bytes: Long)
|
||||||
@@ -123,8 +121,8 @@ object UserApps {
|
|||||||
val name = request.name?.trim()?.takeIf { it.isNotEmpty() }
|
val name = request.name?.trim()?.takeIf { it.isNotEmpty() }
|
||||||
return withIcon(context, request.icon) { icon ->
|
return withIcon(context, request.icon) { icon ->
|
||||||
when (val s = request.source) {
|
when (val s = request.source) {
|
||||||
is Source.Script -> addScript(context, s.file, name, icon, request.meta, onProgress)
|
is Source.Script -> addScript(context, s.file, name, icon, onProgress)
|
||||||
is Source.AppImage -> AppImageManager.import(context, s.file, name, icon, request.meta) { onProgress(it, -1) }
|
is Source.AppImage -> AppImageManager.import(context, s.file, name, icon) { onProgress(it, -1) }
|
||||||
is Source.GitHub -> addFromGitHub(context, s.repo, name, icon, onProgress)
|
is Source.GitHub -> addFromGitHub(context, s.repo, name, icon, onProgress)
|
||||||
is Source.Flatpak -> addFlatpak(context, s.id, name, icon, onProgress)
|
is Source.Flatpak -> addFlatpak(context, s.id, name, icon, onProgress)
|
||||||
is Source.FlatpakBundle -> addFlatpakBundle(context, s.file, name, icon, onProgress)
|
is Source.FlatpakBundle -> addFlatpakBundle(context, s.file, name, icon, onProgress)
|
||||||
@@ -199,14 +197,6 @@ object UserApps {
|
|||||||
}.distinct()
|
}.distinct()
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The desktop's import of [key] as the session sees it: an added script's folder, or an AppImage's. */
|
|
||||||
fun desktopImport(context: Context, key: String, path: String): String? {
|
|
||||||
root(context).listFiles()?.firstOrNull { dir ->
|
|
||||||
File(dir, "entry").isFile && FileUtils.readString(File(dir, DESKTOP_IMPORT))?.lineSequence()?.firstOrNull() == key
|
|
||||||
}?.let { return "$GUEST_DIR/${it.name}" }
|
|
||||||
return AppImageManager.desktopImport(context, key, path)?.let { "${AppImageManager.GUEST_DIR}/$it" }
|
|
||||||
}
|
|
||||||
|
|
||||||
fun planScript(script: File): ScriptPlan {
|
fun planScript(script: File): ScriptPlan {
|
||||||
val folder = script.canonicalFile.parentFile ?: script.parentFile!!
|
val folder = script.canonicalFile.parentFile ?: script.parentFile!!
|
||||||
var scanned = 0
|
var scanned = 0
|
||||||
@@ -219,9 +209,7 @@ object UserApps {
|
|||||||
RandomAccessFile(f, "r").use { val b = ByteArray(4); it.read(b) == 4 && b[0] == 0x7f.toByte() && b[1] == 'E'.code.toByte() && b[2] == 'L'.code.toByte() && b[3] == 'F'.code.toByte() }
|
RandomAccessFile(f, "r").use { val b = ByteArray(4); it.read(b) == 4 && b[0] == 0x7f.toByte() && b[1] == 'E'.code.toByte() && b[2] == 'L'.code.toByte() && b[3] == 'F'.code.toByte() }
|
||||||
} catch (e: Exception) { false }
|
} catch (e: Exception) { false }
|
||||||
|
|
||||||
private fun addScript(
|
private fun addScript(context: Context, script: File, name: String?, icon: File?, onProgress: (String, Int) -> Unit): String? {
|
||||||
context: Context, script: File, name: String?, icon: File?, meta: Map<String, String>, onProgress: (String, Int) -> Unit,
|
|
||||||
): String? {
|
|
||||||
if (!script.isFile) return context.getString(R.string.user_apps_file_gone)
|
if (!script.isFile) return context.getString(R.string.user_apps_file_gone)
|
||||||
val plan = planScript(script)
|
val plan = planScript(script)
|
||||||
val base = root(context).apply { mkdirs() }
|
val base = root(context).apply { mkdirs() }
|
||||||
@@ -244,7 +232,6 @@ object UserApps {
|
|||||||
FileUtils.writeString(File(dir, "name"), title)
|
FileUtils.writeString(File(dir, "name"), title)
|
||||||
FileUtils.writeString(File(dir, "source"), script.canonicalPath)
|
FileUtils.writeString(File(dir, "source"), script.canonicalPath)
|
||||||
if (icon != null && !saveIcon(icon, File(dir, "icon.png"))) Log.w(TAG, "icon ${icon.path} could not be read")
|
if (icon != null && !saveIcon(icon, File(dir, "icon.png"))) Log.w(TAG, "icon ${icon.path} could not be read")
|
||||||
meta.forEach { (k, v) -> FileUtils.writeString(File(dir, k), v) }
|
|
||||||
writeScriptEntry(context, dir)
|
writeScriptEntry(context, dir)
|
||||||
return null
|
return null
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ import android.content.Context
|
|||||||
import android.util.Log
|
import android.util.Log
|
||||||
import com.droiddeck.launcher.core.Downloader
|
import com.droiddeck.launcher.core.Downloader
|
||||||
import com.droiddeck.launcher.core.FileUtils
|
import com.droiddeck.launcher.core.FileUtils
|
||||||
import com.droiddeck.launcher.core.GameEnvironment
|
|
||||||
import com.droiddeck.launcher.gpu.GpuInfo
|
import com.droiddeck.launcher.gpu.GpuInfo
|
||||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||||
import com.github.luben.zstd.ZstdInputStream
|
import com.github.luben.zstd.ZstdInputStream
|
||||||
@@ -80,14 +79,7 @@ object ComponentsManager {
|
|||||||
private const val PLUGIN_DATA = "root/homebrew/data/decky-components-manager"
|
private const val PLUGIN_DATA = "root/homebrew/data/decky-components-manager"
|
||||||
|
|
||||||
data class Proton(val id: String, val name: String, val dir: File, val guestPath: String, val version: String, val valve: Boolean)
|
data class Proton(val id: String, val name: String, val dir: File, val guestPath: String, val version: String, val valve: Boolean)
|
||||||
data class Component(
|
data class Component(val detected: String, val detail: String, val inUse: String, val activeFile: String?, val queued: String?)
|
||||||
val detected: String,
|
|
||||||
val detail: String,
|
|
||||||
val inUse: String,
|
|
||||||
val selected: String,
|
|
||||||
val activeFile: String?,
|
|
||||||
val queued: String?,
|
|
||||||
)
|
|
||||||
data class Original(val comp: String, val protonVersion: String, val label: String, val size: Long)
|
data class Original(val comp: String, val protonVersion: String, val label: String, val size: Long)
|
||||||
data class Package(val file: String, val comp: String, val version: String, val description: String, val size: Long)
|
data class Package(val file: String, val comp: String, val version: String, val description: String, val size: Long)
|
||||||
data class CatalogItem(val file: String, val comp: String, val release: String, val url: String, val size: Long, val digest: String)
|
data class CatalogItem(val file: String, val comp: String, val release: String, val url: String, val size: Long, val digest: String)
|
||||||
@@ -137,121 +129,23 @@ object ComponentsManager {
|
|||||||
|
|
||||||
// ------------------------------------------------------------------ state
|
// ------------------------------------------------------------------ state
|
||||||
|
|
||||||
private fun pendingStateFile(context: Context) = File(dataDir(context), "state.pending.json")
|
private fun loadState(context: Context): JSONObject =
|
||||||
|
runCatching { JSONObject(stateFile(context).readText()) }.getOrElse { JSONObject() }.apply {
|
||||||
private fun loadState(context: Context): JSONObject {
|
|
||||||
recoverState(context)
|
|
||||||
return runCatching { JSONObject(stateFile(context).readText()) }.getOrElse { JSONObject() }.apply {
|
|
||||||
if (!has("active")) put("active", JSONObject())
|
if (!has("active")) put("active", JSONObject())
|
||||||
if (!has("queued")) put("queued", JSONObject())
|
if (!has("queued")) put("queued", JSONObject())
|
||||||
if (!has("profiles")) put("profiles", JSONObject())
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
private fun writeStateFile(file: File, text: String) {
|
|
||||||
val tmp = File(file.parentFile, file.name + ".tmp")
|
|
||||||
try {
|
|
||||||
writeSynced(tmp, text)
|
|
||||||
check(tmp.renameTo(file)) { "Could not save component selections: ${file.name}" }
|
|
||||||
} finally {
|
|
||||||
tmp.delete()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun writeSynced(file: File, text: String) {
|
|
||||||
FileOutputStream(file).use {
|
|
||||||
it.write(text.toByteArray(Charsets.UTF_8))
|
|
||||||
it.fd.sync()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun recoverState(context: Context) {
|
|
||||||
val pending = pendingStateFile(context)
|
|
||||||
if (!pending.exists()) return
|
|
||||||
val transaction = JSONObject(pending.readText())
|
|
||||||
val state = transaction.getJSONObject("state")
|
|
||||||
val expected = transaction.getString("launchSha256")
|
|
||||||
val published = File(launchDir(context), "desired.tsv")
|
|
||||||
val staged = File(launchDir(context), "desired.tsv.tmp")
|
|
||||||
// The launch-table rename is the commit point. Never read stale app selections after it.
|
|
||||||
if (!staged.exists() && published.isFile && Hashes.sha256(published) == expected) {
|
|
||||||
writeStateFile(stateFile(context), state.toString(2))
|
|
||||||
Log.i(TAG, "recovered published component selections")
|
|
||||||
} else {
|
|
||||||
Log.i(TAG, "discarded unpublished component selections")
|
|
||||||
}
|
|
||||||
check(pending.delete()) { "Could not finish component selection recovery" }
|
|
||||||
if (staged.exists()) check(staged.delete()) { "Could not remove unpublished component selections" }
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun saveState(context: Context, state: JSONObject) {
|
private fun saveState(context: Context, state: JSONObject) {
|
||||||
val prepared = prepareLaunchState(context, state)
|
val f = stateFile(context)
|
||||||
val dir = launchDir(context)
|
val tmp = File(f.parentFile, f.name + ".tmp")
|
||||||
val tmp = File(dir, "desired.tsv.tmp")
|
tmp.writeText(state.toString(2))
|
||||||
try {
|
tmp.renameTo(f)
|
||||||
writeSynced(tmp, prepared.text)
|
// Every change of choice reaches the launch wrappers at once.
|
||||||
writeStateFile(pendingStateFile(context), JSONObject()
|
runCatching { syncLaunchState(context, state) }.onFailure { Log.w(TAG, "launch state", it) }
|
||||||
.put("state", state)
|
|
||||||
.put("launchSha256", Hashes.sha256(tmp))
|
|
||||||
.toString())
|
|
||||||
check(tmp.renameTo(File(dir, "desired.tsv"))) { "Could not publish component selections" }
|
|
||||||
writeStateFile(stateFile(context), state.toString(2))
|
|
||||||
check(pendingStateFile(context).delete()) { "Could not finish saving component selections" }
|
|
||||||
} finally {
|
|
||||||
if (!pendingStateFile(context).exists()) tmp.delete()
|
|
||||||
}
|
|
||||||
File(dir, "store").listFiles()?.filter { it.isDirectory && it.name !in prepared.keep }
|
|
||||||
?.forEach { it.deleteRecursively() }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun JSONObject.sub(key: String): JSONObject = optJSONObject(key) ?: JSONObject().also { put(key, it) }
|
private fun JSONObject.sub(key: String): JSONObject = optJSONObject(key) ?: JSONObject().also { put(key, it) }
|
||||||
|
|
||||||
// Keep launch-time restore rows after the last per-game selection is removed.
|
|
||||||
private fun rememberProfiledComponent(state: JSONObject, comp: String) {
|
|
||||||
val profiled = state.optJSONArray("profiledComponents")?.let { values ->
|
|
||||||
(0 until values.length()).mapNotNull { values.optString(it).takeIf(COMPONENTS::contains) }
|
|
||||||
}.orEmpty().toMutableSet()
|
|
||||||
if (profiled.add(comp)) state.put("profiledComponents", JSONArray(profiled.sorted()))
|
|
||||||
}
|
|
||||||
|
|
||||||
fun gameComponents(context: Context, scope: String): Map<String, String> = synchronized(lock) {
|
|
||||||
val profile = loadState(context).sub("profiles").optJSONObject(scope) ?: return emptyMap()
|
|
||||||
COMPONENTS.mapNotNull { comp -> profile.optString(comp).takeIf(String::isNotEmpty)?.let { comp to it } }.toMap()
|
|
||||||
}
|
|
||||||
|
|
||||||
fun setGameComponent(context: Context, scope: String, comp: String, file: String?) = synchronized(lock) {
|
|
||||||
require(scope.matches(Regex("[1-9][0-9]{0,9}")) && scope.toLong() <= 4294967295L)
|
|
||||||
require(comp in COMPONENTS)
|
|
||||||
val state = loadState(context)
|
|
||||||
val profiles = state.sub("profiles")
|
|
||||||
val profile = profiles.optJSONObject(scope) ?: JSONObject().also { profiles.put(scope, it) }
|
|
||||||
if (file == null) {
|
|
||||||
if (profile.optString(comp).isNotEmpty()) rememberProfiledComponent(state, comp)
|
|
||||||
profile.remove(comp)
|
|
||||||
if (profile.length() == 0) profiles.remove(scope)
|
|
||||||
} else {
|
|
||||||
val name = safeName(file)
|
|
||||||
val wcp = File(packagesDir(context), name)
|
|
||||||
require(packageInfo(context, wcp).comp == comp)
|
|
||||||
for (proton in protons(context)) ensureOriginal(context, proton, comp, state)
|
|
||||||
rememberProfiledComponent(state, comp)
|
|
||||||
profile.put(comp, name)
|
|
||||||
}
|
|
||||||
saveState(context, state)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun clearGameComponents(context: Context, scope: String) = synchronized(lock) {
|
|
||||||
require(GameEnvironment.validScope(scope))
|
|
||||||
val state = loadState(context)
|
|
||||||
val profiles = state.sub("profiles")
|
|
||||||
profiles.optJSONObject(scope)?.let { profile ->
|
|
||||||
COMPONENTS.filter { profile.optString(it).isNotEmpty() }
|
|
||||||
.forEach { rememberProfiledComponent(state, it) }
|
|
||||||
}
|
|
||||||
profiles.remove(scope)
|
|
||||||
saveState(context, state)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Takes over the Decky plugin's packages, originals and swap records, once. */
|
/** Takes over the Decky plugin's packages, originals and swap records, once. */
|
||||||
private fun migratePlugin(context: Context) {
|
private fun migratePlugin(context: Context) {
|
||||||
val marker = File(dataDir(context), ".plugin-imported")
|
val marker = File(dataDir(context), ".plugin-imported")
|
||||||
@@ -326,33 +220,24 @@ object ComponentsManager {
|
|||||||
* Is anything running on this Proton right now - a game, or the client's own start-up runs,
|
* Is anything running on this Proton right now - a game, or the client's own start-up runs,
|
||||||
* whose Wine processes can outlive them? Swaps wait while it is. Read from the command lines.
|
* whose Wine processes can outlive them? Swaps wait while it is. Read from the command lines.
|
||||||
*/
|
*/
|
||||||
fun inUse(context: Context, proton: Proton): Boolean =
|
fun inUse(context: Context, proton: Proton): Boolean = anyProcess(context, proton) { needle, text -> text.contains(needle + "proton ") || text.contains(needle + "files/bin") }
|
||||||
anyProcess(context, proton) { paths, text -> processUsesProton(paths, text, gameOnly = false) }
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Is a game running on this Proton? Only a launch runs proton with the verb waitforexitandrun
|
* Is a game running on this Proton? Only a launch runs proton with the verb waitforexitandrun
|
||||||
* (Proton's own script stays up until the game exits); the client's start-up runs do not.
|
* (Proton's own script stays up until the game exits); the client's start-up runs do not.
|
||||||
*/
|
*/
|
||||||
fun gameRunning(context: Context, proton: Proton): Boolean =
|
fun gameRunning(context: Context, proton: Proton): Boolean = anyProcess(context, proton) { needle, text -> text.contains(needle + "proton waitforexitandrun") }
|
||||||
anyProcess(context, proton) { paths, text -> processUsesProton(paths, text, gameOnly = true) }
|
|
||||||
|
|
||||||
internal fun processUsesProton(paths: List<String>, text: String, gameOnly: Boolean): Boolean =
|
private fun anyProcess(context: Context, proton: Proton, match: (String, String) -> Boolean): Boolean {
|
||||||
paths.any { path ->
|
val needles = (listOf(proton.guestPath) + EsyncPacks.distPathsFor(root(context), proton.guestPath))
|
||||||
val needle = path.trimEnd('/') + "/"
|
.map { it.trimEnd('/') + "/" }
|
||||||
if (gameOnly) text.contains(needle + "proton waitforexitandrun")
|
|
||||||
else text.contains(needle + "proton ") || text.contains(needle + "files/bin")
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun anyProcess(context: Context, proton: Proton, match: (List<String>, String) -> Boolean): Boolean {
|
|
||||||
val guestPaths = listOf(proton.guestPath) + EsyncPacks.distPathsFor(root(context), proton.guestPath)
|
|
||||||
val paths = (guestPaths + guestPaths.map { host(context, it).absolutePath } + proton.dir.absolutePath).distinct()
|
|
||||||
val procs = File("/proc").listFiles() ?: return false
|
val procs = File("/proc").listFiles() ?: return false
|
||||||
for (p in procs) {
|
for (p in procs) {
|
||||||
if (!p.name.all(Char::isDigit)) continue
|
if (!p.name.all(Char::isDigit)) continue
|
||||||
val cmd = runCatching { File(p, "cmdline").readBytes() }.getOrNull() ?: continue
|
val cmd = runCatching { File(p, "cmdline").readBytes() }.getOrNull() ?: continue
|
||||||
if (cmd.isEmpty()) continue
|
if (cmd.isEmpty()) continue
|
||||||
val text = String(cmd).replace('\u0000', ' ')
|
val text = String(cmd).replace('\u0000', ' ')
|
||||||
if (match(paths, text)) return true
|
if (needles.any { match(it, text) }) return true
|
||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
@@ -376,7 +261,7 @@ object ComponentsManager {
|
|||||||
private fun compFiles(dir: File, comp: String): List<String> {
|
private fun compFiles(dir: File, comp: String): List<String> {
|
||||||
if (comp == "fex") return FEX_FILES.filter { File(dir, it).isFile }
|
if (comp == "fex") return FEX_FILES.filter { File(dir, it).isFile }
|
||||||
val base = File(dir, COMP_DIR.getValue(comp))
|
val base = File(dir, COMP_DIR.getValue(comp))
|
||||||
return base.walkTopDown().filter { it.isFile }.map { it.relativeTo(dir).invariantSeparatorsPath }.sorted().toList()
|
return base.walkTopDown().filter { it.isFile }.map { it.relativeTo(dir).path }.sorted().toList()
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun owned(comp: String, rel: String) = comp == "fex" || PE_ARCHES.any { "/$it/" in rel }
|
private fun owned(comp: String, rel: String) = comp == "fex" || PE_ARCHES.any { "/$it/" in rel }
|
||||||
@@ -406,11 +291,9 @@ object ComponentsManager {
|
|||||||
return Package(f.name, comp, prof.optString("versionName", f.nameWithoutExtension), prof.optString("description"), f.length())
|
return Package(f.name, comp, prof.optString("versionName", f.nameWithoutExtension), prof.optString("description"), f.length())
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The stored packages, newest version first. */
|
|
||||||
fun packages(context: Context): List<Package> = packagesDir(context).listFiles()
|
fun packages(context: Context): List<Package> = packagesDir(context).listFiles()
|
||||||
?.filter { it.isFile && it.name.endsWith(".wcp") }
|
?.filter { it.isFile && it.name.endsWith(".wcp") }?.sortedBy { it.name }
|
||||||
?.mapNotNull { f -> runCatching { packageInfo(context, f) }.onFailure { Log.w(TAG, "skipping ${f.name}", it) }.getOrNull() }
|
?.mapNotNull { f -> runCatching { packageInfo(context, f) }.onFailure { Log.w(TAG, "skipping ${f.name}", it) }.getOrNull() }
|
||||||
?.sortedWith(newestFirst { it.version.ifEmpty { it.file } })
|
|
||||||
?: emptyList()
|
?: emptyList()
|
||||||
|
|
||||||
/** Unpacks a package's files/ into a Proton; for DXVK/VKD3D the component's own DLLs are replaced as a set. */
|
/** Unpacks a package's files/ into a Proton; for DXVK/VKD3D the component's own DLLs are replaced as a set. */
|
||||||
@@ -469,7 +352,7 @@ object ComponentsManager {
|
|||||||
tar.closeArchiveEntry()
|
tar.closeArchiveEntry()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
check(tmp.renameTo(dest)) { "Could not save original bundle ${dest.name}" }
|
tmp.renameTo(dest)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ------------------------------------------------------------------ originals
|
// ------------------------------------------------------------------ originals
|
||||||
@@ -497,18 +380,8 @@ object ComponentsManager {
|
|||||||
if (dest.isFile) return
|
if (dest.isFile) return
|
||||||
val active = state.sub("active").optJSONObject(p.id)?.optJSONObject(comp)
|
val active = state.sub("active").optJSONObject(p.id)?.optJSONObject(comp)
|
||||||
if (active != null && active.optString("protonVersion") == p.version) return
|
if (active != null && active.optString("protonVersion") == p.version) return
|
||||||
val published = File(launchDir(context), "desired.tsv")
|
|
||||||
if (published.isFile) {
|
|
||||||
val mayHaveOverride = published.useLines { rows ->
|
|
||||||
rows.any { row ->
|
|
||||||
val fields = row.split('\t')
|
|
||||||
fields.size == 7 && fields[0] != "*" && fields[1] == p.dir.name &&
|
|
||||||
fields[2] == p.version && fields[3] == comp
|
|
||||||
}
|
|
||||||
}
|
|
||||||
check(!mayHaveOverride) { context.getString(R.string.cmgr_original_missing) }
|
|
||||||
}
|
|
||||||
val rels = compFiles(p.dir, comp)
|
val rels = compFiles(p.dir, comp)
|
||||||
|
if (rels.isEmpty()) return
|
||||||
val current = if (comp == "fex") fexVersion(p.dir) else readVersionFile(File(p.dir, "${COMP_DIR.getValue(comp)}/version"))
|
val current = if (comp == "fex") fexVersion(p.dir) else readVersionFile(File(p.dir, "${COMP_DIR.getValue(comp)}/version"))
|
||||||
val profile = JSONObject()
|
val profile = JSONObject()
|
||||||
.put("type", TYPE_OF.getValue(comp))
|
.put("type", TYPE_OF.getValue(comp))
|
||||||
@@ -527,7 +400,7 @@ object ComponentsManager {
|
|||||||
for (p in protons(context)) for (comp in COMPONENTS) {
|
for (p in protons(context)) for (comp in COMPONENTS) {
|
||||||
runCatching { ensureOriginal(context, p, comp, state) }.onFailure { Log.w(TAG, "original $comp of ${p.name}", it) }
|
runCatching { ensureOriginal(context, p, comp, state) }.onFailure { Log.w(TAG, "original $comp of ${p.name}", it) }
|
||||||
}
|
}
|
||||||
runCatching { saveState(context, state) }.onFailure { Log.w(TAG, "launch state", it) }
|
runCatching { syncLaunchState(context, state) }.onFailure { Log.w(TAG, "launch state", it) }
|
||||||
}
|
}
|
||||||
|
|
||||||
// ------------------------------------------------------------------ view
|
// ------------------------------------------------------------------ view
|
||||||
@@ -558,14 +431,9 @@ object ComponentsManager {
|
|||||||
else context.getString(R.string.cmgr_changed_outside)
|
else context.getString(R.string.cmgr_changed_outside)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
val selectedLabel = when {
|
|
||||||
active == null || active.optString("protonVersion") != p.version ->
|
|
||||||
context.getString(R.string.comp_tag_original)
|
|
||||||
else -> originalLabel(context, active) ?: active.optString("label", active.optString("file"))
|
|
||||||
}
|
|
||||||
val q = state.sub("queued").optJSONObject(p.id)?.optJSONObject(comp)
|
val q = state.sub("queued").optJSONObject(p.id)?.optJSONObject(comp)
|
||||||
Component(
|
Component(
|
||||||
detected.ifEmpty { context.getString(R.string.cmgr_not_present) }, detail, inUseLabel, selectedLabel,
|
detected.ifEmpty { context.getString(R.string.cmgr_not_present) }, detail, inUseLabel,
|
||||||
active?.optString("file")?.takeIf { active.optString("protonVersion") == p.version },
|
active?.optString("file")?.takeIf { active.optString("protonVersion") == p.version },
|
||||||
q?.let { originalLabel(context, it) ?: it.optString("label") },
|
q?.let { originalLabel(context, it) ?: it.optString("label") },
|
||||||
)
|
)
|
||||||
@@ -587,111 +455,64 @@ object ComponentsManager {
|
|||||||
|
|
||||||
// ------------------------------------------------------------------ launch-time enforcement
|
// ------------------------------------------------------------------ launch-time enforcement
|
||||||
|
|
||||||
private data class PreparedLaunchState(val text: String, val keep: Set<String>)
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Stages what each Proton should use for the launch wrappers. General rows use scope `*`;
|
* Writes what each Proton should be using for the launch wrappers: desired.tsv, one line per
|
||||||
* per-game rows use the game's compatdata id and replace General for that component. Deletion
|
* file (tool dir, Proton build, component, file, sha256, source copy), and an unpacked copy of
|
||||||
* rows remove managed DLLs absent from the chosen package, so switching games cannot leave files
|
* every package or older-build original in use to copy from. Rebuilt whole after every change, so
|
||||||
* from the previous game's component set behind.
|
* a restored or deleted choice simply stops being enforced. The Proton's own current-build
|
||||||
|
* originals are not listed: the wrappers also give Steam's probe runs their own prefix, which is
|
||||||
|
* what overwrote files in the first place.
|
||||||
*/
|
*/
|
||||||
private fun prepareLaunchState(context: Context, state: JSONObject): PreparedLaunchState {
|
private fun syncLaunchState(context: Context, state: JSONObject) {
|
||||||
val dir = launchDir(context)
|
val dir = launchDir(context)
|
||||||
val store = File(dir, "store").apply { mkdirs() }
|
val store = File(dir, "store").apply { mkdirs() }
|
||||||
val all = protons(context)
|
val all = protons(context)
|
||||||
val lines = StringBuilder()
|
val lines = StringBuilder()
|
||||||
val keep = HashSet<String>()
|
val keep = HashSet<String>()
|
||||||
|
|
||||||
fun unpack(key: String, wcp: File, comp: String): File {
|
|
||||||
check(wcp.isFile) { context.getString(R.string.cmgr_not_stored) }
|
|
||||||
val unpacked = File(store, key)
|
|
||||||
if (!File(unpacked, ".complete").isFile) {
|
|
||||||
check(packageInfo(context, wcp).comp == comp) { "Wrong component in ${wcp.name}" }
|
|
||||||
unpacked.deleteRecursively()
|
|
||||||
check(unpacked.mkdirs()) { "Could not stage component bundle ${wcp.name}" }
|
|
||||||
readWcp(wcp) { tar ->
|
|
||||||
while (true) {
|
|
||||||
val e = tar.nextTarEntry ?: break
|
|
||||||
val rel = normalize(e.name)
|
|
||||||
if (e.isDirectory || !rel.startsWith("files/") || rel.split('/').any { it == ".." }) continue
|
|
||||||
val out = File(unpacked, rel)
|
|
||||||
out.parentFile?.mkdirs()
|
|
||||||
FileOutputStream(out).use { tar.copyTo(it) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
File(unpacked, ".complete").writeText("1\n")
|
|
||||||
}
|
|
||||||
keep += key
|
|
||||||
return unpacked
|
|
||||||
}
|
|
||||||
|
|
||||||
fun managed(comp: String): Set<String> = if (comp == "fex") FEX_FILES.toSet() else buildSet {
|
|
||||||
for (arch in PE_ARCHES) for (dll in COMP_DLLS.getValue(comp)) add("${COMP_DIR.getValue(comp)}/$arch/$dll")
|
|
||||||
}
|
|
||||||
|
|
||||||
fun append(scope: String, p: Proton, comp: String, key: String, wcp: File) {
|
|
||||||
val unpacked = unpack(key, wcp, comp)
|
|
||||||
val files = unpacked.let { base ->
|
|
||||||
File(base, "files").walkTopDown().filter { it.isFile }.map { it.relativeTo(base).invariantSeparatorsPath }
|
|
||||||
.filter { owned(comp, it) }.associateWith { File(base, it) }
|
|
||||||
}
|
|
||||||
for (rel in managed(comp) - files.keys) {
|
|
||||||
lines.append(scope).append('\t').append(p.dir.name).append('\t').append(p.version).append('\t').append(comp)
|
|
||||||
.append('\t').append(rel).append("\t-\t-\n")
|
|
||||||
}
|
|
||||||
for ((rel, src) in files) {
|
|
||||||
val guestSrc = "/" + src.relativeTo(root(context)).invariantSeparatorsPath
|
|
||||||
lines.append(scope).append('\t').append(p.dir.name).append('\t').append(p.version).append('\t').append(comp)
|
|
||||||
.append('\t').append(rel).append('\t').append(Hashes.sha256(src)).append('\t').append(guestSrc).append('\n')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun choice(p: Proton, comp: String, entry: JSONObject): Pair<String, File>? {
|
|
||||||
val file = entry.optString("file")
|
|
||||||
return if (file.startsWith("original ")) {
|
|
||||||
val version = safeName(file.removePrefix("original "))
|
|
||||||
"original-${p.id}-$version-$comp" to File(originalsDir(context), "${p.id}/$version/$comp.wcp")
|
|
||||||
} else {
|
|
||||||
safeName(file.removeSuffix(".wcp")) to File(packagesDir(context), file)
|
|
||||||
}.takeIf { it.second.isFile }
|
|
||||||
}
|
|
||||||
|
|
||||||
val profiles = state.sub("profiles")
|
|
||||||
val profiledComponents = buildSet {
|
|
||||||
state.optJSONArray("profiledComponents")?.let { stored ->
|
|
||||||
for (index in 0 until stored.length()) {
|
|
||||||
stored.optString(index).takeIf(COMPONENTS::contains)?.let(::add)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for (scope in profiles.keys()) {
|
|
||||||
val profile = profiles.optJSONObject(scope) ?: continue
|
|
||||||
COMPONENTS.filterTo(this) { profile.optString(it).isNotEmpty() }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
val active = state.sub("active")
|
val active = state.sub("active")
|
||||||
for (p in all) for (comp in COMPONENTS) {
|
for (pid in active.keys()) {
|
||||||
val entry = active.optJSONObject(p.id)?.optJSONObject(comp)
|
val p = all.firstOrNull { it.id == pid } ?: continue
|
||||||
val selected = entry?.takeIf { it.optString("protonVersion") == p.version }?.let { choice(p, comp, it) }
|
val comps = active.optJSONObject(pid) ?: continue
|
||||||
if (selected != null) append("*", p, comp, selected.first, selected.second)
|
for (comp in comps.keys()) {
|
||||||
else if (comp in profiledComponents) {
|
val a = comps.optJSONObject(comp) ?: continue
|
||||||
ensureOriginal(context, p, comp, state)
|
if (a.optString("protonVersion") != p.version) continue
|
||||||
val original = originalFile(context, p, comp)
|
val file = a.optString("file")
|
||||||
check(original.isFile) { context.getString(R.string.cmgr_original_missing) }
|
val (key, wcp) = if (file.startsWith("original ")) {
|
||||||
append("*", p, comp, "original-${p.id}-${safeName(p.version)}-$comp", original)
|
val v = file.removePrefix("original ")
|
||||||
}
|
"original-$pid-${safeName(v)}-$comp" to File(originalsDir(context), "$pid/${safeName(v)}/$comp.wcp")
|
||||||
}
|
} else safeName(file.removeSuffix(".wcp")) to File(packagesDir(context), file)
|
||||||
for (scope in profiles.keys()) {
|
|
||||||
val profile = profiles.optJSONObject(scope) ?: continue
|
|
||||||
for (comp in COMPONENTS) {
|
|
||||||
val file = profile.optString(comp)
|
|
||||||
if (file.isEmpty()) continue
|
|
||||||
val wcp = File(packagesDir(context), file)
|
|
||||||
if (!wcp.isFile) continue
|
if (!wcp.isFile) continue
|
||||||
val key = safeName(file.removeSuffix(".wcp"))
|
val unpacked = File(store, key)
|
||||||
for (p in all) append(scope, p, comp, key, wcp)
|
if (!File(unpacked, ".complete").isFile) {
|
||||||
|
unpacked.deleteRecursively()
|
||||||
|
readWcp(wcp) { tar ->
|
||||||
|
while (true) {
|
||||||
|
val e = tar.nextTarEntry ?: break
|
||||||
|
val rel = normalize(e.name)
|
||||||
|
if (e.isDirectory || !rel.startsWith("files/") || rel.split('/').any { it == ".." }) continue
|
||||||
|
val out = File(unpacked, rel)
|
||||||
|
out.parentFile?.mkdirs()
|
||||||
|
FileOutputStream(out).use { tar.copyTo(it) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
File(unpacked, ".complete").writeText("1\n")
|
||||||
|
}
|
||||||
|
keep += key
|
||||||
|
val files = a.optJSONObject("files") ?: continue
|
||||||
|
for (rel in files.keys()) {
|
||||||
|
val src = File(unpacked, rel)
|
||||||
|
if (!src.isFile) continue
|
||||||
|
val guestSrc = "/" + src.absolutePath.removePrefix(root(context).absolutePath.trimEnd('/')).trimStart('/')
|
||||||
|
lines.append(p.dir.name).append('\t').append(p.version).append('\t').append(comp).append('\t')
|
||||||
|
.append(rel).append('\t').append(files.optString(rel)).append('\t').append(guestSrc).append('\n')
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return PreparedLaunchState(lines.toString(), keep)
|
store.listFiles()?.filter { it.isDirectory && it.name !in keep }?.forEach { it.deleteRecursively() }
|
||||||
|
val list = File(dir, "desired.tsv")
|
||||||
|
val tmp = File(dir, "desired.tsv.tmp")
|
||||||
|
tmp.writeText(lines.toString())
|
||||||
|
tmp.renameTo(list)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ------------------------------------------------------------------ actions
|
// ------------------------------------------------------------------ actions
|
||||||
@@ -794,11 +615,6 @@ object ComponentsManager {
|
|||||||
val comps = active.optJSONObject(pid) ?: continue
|
val comps = active.optJSONObject(pid) ?: continue
|
||||||
for (comp in comps.keys()) check(comps.optJSONObject(comp)?.optString("file") != name) { context.getString(R.string.cmgr_package_in_use, name, pid) }
|
for (comp in comps.keys()) check(comps.optJSONObject(comp)?.optString("file") != name) { context.getString(R.string.cmgr_package_in_use, name, pid) }
|
||||||
}
|
}
|
||||||
val profiles = state.sub("profiles")
|
|
||||||
for (scope in profiles.keys()) {
|
|
||||||
val profile = profiles.optJSONObject(scope) ?: continue
|
|
||||||
check(COMPONENTS.none { profile.optString(it) == name }) { context.getString(R.string.cmgr_package_in_use, name, scope) }
|
|
||||||
}
|
|
||||||
val f = File(packagesDir(context), name)
|
val f = File(packagesDir(context), name)
|
||||||
check(f.isFile) { context.getString(R.string.cmgr_package_not_stored, name) }
|
check(f.isFile) { context.getString(R.string.cmgr_package_not_stored, name) }
|
||||||
f.delete()
|
f.delete()
|
||||||
@@ -854,14 +670,10 @@ object ComponentsManager {
|
|||||||
val arr = o.optJSONArray("items") ?: JSONArray()
|
val arr = o.optJSONArray("items") ?: JSONArray()
|
||||||
val items = (0 until arr.length()).map { arr.getJSONObject(it) }.map {
|
val items = (0 until arr.length()).map { arr.getJSONObject(it) }.map {
|
||||||
CatalogItem(it.optString("file"), it.optString("comp"), it.optString("release"), it.optString("url"), it.optLong("size"), it.optString("digest"))
|
CatalogItem(it.optString("file"), it.optString("comp"), it.optString("release"), it.optString("url"), it.optLong("size"), it.optString("digest"))
|
||||||
}.sortedWith(compareBy<CatalogItem> { it.comp }.then(newestFirst { it.file }))
|
}.sortedWith(compareBy({ it.comp }, { it.release }, { it.file }))
|
||||||
return Catalog(items, o.optLong("fetchedAt"))
|
return Catalog(items, o.optLong("fetchedAt"))
|
||||||
}
|
}
|
||||||
|
|
||||||
/** By the version in [of], highest first: the newest builds lead a list, as they are what is picked. */
|
|
||||||
private fun <T> newestFirst(of: (T) -> String): Comparator<T> =
|
|
||||||
Comparator { a, b -> ProtonExtras.compareVersions(of(b), of(a)) }
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A package Proton does not ship, required on the GPUs listed here. An empty [models] set
|
* A package Proton does not ship, required on the GPUs listed here. An empty [models] set
|
||||||
* means every model in [families]. A row the user already chose in Components is left alone;
|
* means every model in [families]. A row the user already chose in Components is left alone;
|
||||||
|
|||||||
@@ -13,7 +13,6 @@ object GameEnvironmentStore {
|
|||||||
private const val GUEST_FILE = "root/.config/droiddeck/game-environment.json"
|
private const val GUEST_FILE = "root/.config/droiddeck/game-environment.json"
|
||||||
/** The published file's extra DXVK options (droiddeck-game-env reads it; the app's own file has none). */
|
/** The published file's extra DXVK options (droiddeck-game-env reads it; the app's own file has none). */
|
||||||
const val DXVK_CONFIG = "dxvkConfig"
|
const val DXVK_CONFIG = "dxvkConfig"
|
||||||
const val DXVK_CONFIG_GAMES = "dxvkConfigGames"
|
|
||||||
|
|
||||||
@Synchronized
|
@Synchronized
|
||||||
fun read(context: Context): GameEnvironment.Config {
|
fun read(context: Context): GameEnvironment.Config {
|
||||||
@@ -58,13 +57,6 @@ object GameEnvironmentStore {
|
|||||||
publish(context, config)
|
publish(context, config)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Synchronized
|
|
||||||
fun setGameFexPreset(context: Context, scope: String, preset: String?): GameEnvironment.Config {
|
|
||||||
val config = GameEnvironment.withGameFexPreset(read(context), scope, preset)
|
|
||||||
save(context, config)
|
|
||||||
return config
|
|
||||||
}
|
|
||||||
|
|
||||||
@Synchronized
|
@Synchronized
|
||||||
fun publish(context: Context, config: GameEnvironment.Config = read(context)) {
|
fun publish(context: Context, config: GameEnvironment.Config = read(context)) {
|
||||||
val resolved = config.copy(shared = GameEnvironment.defaults(SessionPrefs.fexPreset(context), SessionPrefs.forceSsbs(context)) + config.shared)
|
val resolved = config.copy(shared = GameEnvironment.defaults(SessionPrefs.fexPreset(context), SessionPrefs.forceSsbs(context)) + config.shared)
|
||||||
@@ -76,21 +68,6 @@ object GameEnvironmentStore {
|
|||||||
TextureFiltering.autoLodBias(SessionState.upscaleRatio),
|
TextureFiltering.autoLodBias(SessionState.upscaleRatio),
|
||||||
)
|
)
|
||||||
if (dxvk.isNotEmpty()) json.put(DXVK_CONFIG, dxvk)
|
if (dxvk.isNotEmpty()) json.put(DXVK_CONFIG, dxvk)
|
||||||
val autoBias = TextureFiltering.autoLodBias(SessionState.upscaleRatio)
|
|
||||||
val generalAnisotropy = SessionPrefs.textureAnisotropy(context)
|
|
||||||
val generalLodBias = SessionPrefs.textureLodBias(context)
|
|
||||||
val gameDxvk = JSONObject()
|
|
||||||
SessionPrefs.gameTextureFiltering(context).forEach { (scope, choice) ->
|
|
||||||
gameDxvk.put(
|
|
||||||
scope,
|
|
||||||
TextureFiltering.dxvkOptions(
|
|
||||||
choice.anisotropy ?: generalAnisotropy,
|
|
||||||
choice.lodBias ?: generalLodBias,
|
|
||||||
autoBias,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
if (gameDxvk.length() > 0) json.put(DXVK_CONFIG_GAMES, gameDxvk)
|
|
||||||
write(File(LinuxRuntime.rootDir(context), GUEST_FILE), json.toString())
|
write(File(LinuxRuntime.rootDir(context), GUEST_FILE), json.toString())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,14 +0,0 @@
|
|||||||
package com.droiddeck.launcher.session
|
|
||||||
|
|
||||||
internal class GameProfileFollowState {
|
|
||||||
var followsSteam = true
|
|
||||||
private set
|
|
||||||
|
|
||||||
fun selectManually() {
|
|
||||||
followsSteam = false
|
|
||||||
}
|
|
||||||
|
|
||||||
fun resumeFollowingSteam() {
|
|
||||||
followsSteam = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
package com.droiddeck.launcher.session
|
|
||||||
|
|
||||||
internal class GameProfileInventoryCache<T : Any> {
|
|
||||||
private val lock = Any()
|
|
||||||
|
|
||||||
private var revision: Long? = null
|
|
||||||
private var value: List<T>? = null
|
|
||||||
|
|
||||||
// Called only by the refresh worker; the UI invalidates through request revisions.
|
|
||||||
fun get(requestedRevision: Long, load: () -> List<T>): List<T> = synchronized(lock) {
|
|
||||||
value?.takeIf { revision == requestedRevision } ?: load().toList().also {
|
|
||||||
value = it
|
|
||||||
revision = requestedRevision
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
package com.droiddeck.launcher.session
|
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
import com.droiddeck.launcher.core.GameEnvironment
|
|
||||||
|
|
||||||
object GameProfileManager {
|
|
||||||
@Synchronized
|
|
||||||
fun reset(context: Context, scope: String) {
|
|
||||||
require(scope.isNotEmpty() && GameEnvironment.validScope(scope))
|
|
||||||
val failures = mutableListOf<Pair<String, Throwable>>()
|
|
||||||
fun clear(name: String, action: () -> Unit) {
|
|
||||||
runCatching(action).onFailure { failures += name to it }
|
|
||||||
}
|
|
||||||
|
|
||||||
clear("environment") {
|
|
||||||
GameEnvironmentStore.save(
|
|
||||||
context,
|
|
||||||
GameEnvironmentStore.read(context).withEntries(scope, emptyMap()),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
clear("Proton") { ProtonDefault.requestGame(context, scope, null) }
|
|
||||||
clear("component packages") { ComponentsManager.clearGameComponents(context, scope) }
|
|
||||||
clear("texture filtering") { SessionPrefs.clearGameTextureFiltering(context, scope) }
|
|
||||||
clear("Windows components") { WinComponents.setPicks(context, scope, emptyList()) }
|
|
||||||
|
|
||||||
if (failures.isNotEmpty()) {
|
|
||||||
val names = failures.joinToString { it.first }
|
|
||||||
throw IllegalStateException("Could not clear: $names", failures.first().second)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
package com.droiddeck.launcher.session
|
|
||||||
|
|
||||||
internal data class GameProfileRefreshState<T>(
|
|
||||||
val data: T? = null,
|
|
||||||
val loaded: Boolean = false,
|
|
||||||
val failed: Boolean = false,
|
|
||||||
) {
|
|
||||||
fun succeeded(data: T) = GameProfileRefreshState(data, loaded = true)
|
|
||||||
|
|
||||||
fun failed() = copy(failed = true)
|
|
||||||
|
|
||||||
fun retrying() = copy(failed = false)
|
|
||||||
}
|
|
||||||
@@ -68,19 +68,12 @@ object GameStorage {
|
|||||||
|
|
||||||
class Library(val host: File, val guest: String, val label: String)
|
class Library(val host: File, val guest: String, val label: String)
|
||||||
|
|
||||||
/**
|
|
||||||
* Games folders an earlier build registered as Steam libraries that Steam has installed games
|
|
||||||
* into (an appmanifest in their steamapps/): those stay libraries, so the games are not lost.
|
|
||||||
* Any other Games folder is no longer one; the session's library list leaves it out and the
|
|
||||||
* runtime's droiddeck-steam-library forgets it.
|
|
||||||
*/
|
|
||||||
fun gamesFolderLibraries(context: Context): List<Library> {
|
fun gamesFolderLibraries(context: Context): List<Library> {
|
||||||
if (SessionPrefs.gameStorage(context).isNotEmpty()) return emptyList()
|
if (SessionPrefs.gameStorage(context).isNotEmpty()) return emptyList()
|
||||||
val card = effective(context)?.let { canonical(File(it.path)) }
|
val card = effective(context)?.let { canonical(File(it.path)) }
|
||||||
val sm = context.getSystemService(StorageManager::class.java)
|
val sm = context.getSystemService(StorageManager::class.java)
|
||||||
return AddedGames.roots(context).mapNotNull { root ->
|
return AddedGames.roots(context).mapNotNull { root ->
|
||||||
val host = canonical(root.host)
|
val host = canonical(root.host)
|
||||||
if (!hasInstalledGames(root.host)) return@mapNotNull null
|
|
||||||
if ('"' in root.guest || '\\' in root.guest || !root.host.isDirectory || !root.host.canWrite()) return@mapNotNull null
|
if ('"' in root.guest || '\\' in root.guest || !root.host.isDirectory || !root.host.canWrite()) return@mapNotNull null
|
||||||
if (card != null && (host == card || host.startsWith("$card/") || card.startsWith("$host/"))) return@mapNotNull null
|
if (card != null && (host == card || host.startsWith("$card/") || card.startsWith("$host/"))) return@mapNotNull null
|
||||||
val volume = try { sm?.getStorageVolume(root.host)?.getDescription(context) } catch (e: Exception) { null }
|
val volume = try { sm?.getStorageVolume(root.host)?.getDescription(context) } catch (e: Exception) { null }
|
||||||
@@ -90,10 +83,6 @@ object GameStorage {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Steam has installed a game into [root] as a library: a manifest in its steamapps/. */
|
|
||||||
internal fun hasInstalledGames(root: File): Boolean =
|
|
||||||
File(root, "steamapps").listFiles { f -> f.isFile && f.name.startsWith("appmanifest_") && f.name.endsWith(".acf") }?.isNotEmpty() == true
|
|
||||||
|
|
||||||
private fun canonical(file: File): String = runCatching { file.canonicalPath }.getOrDefault(file.absolutePath)
|
private fun canonical(file: File): String = runCatching { file.canonicalPath }.getOrDefault(file.absolutePath)
|
||||||
|
|
||||||
/** The label the client shows for a chosen folder: its last name, or the volume's. */
|
/** The label the client shows for a chosen folder: its last name, or the volume's. */
|
||||||
|
|||||||
@@ -1,33 +0,0 @@
|
|||||||
package com.droiddeck.launcher.session
|
|
||||||
|
|
||||||
internal class LatestRequestCoordinator<T> {
|
|
||||||
data class Request<T>(val generation: Long, val value: T)
|
|
||||||
|
|
||||||
private val lock = Any()
|
|
||||||
private var generation = 0L
|
|
||||||
private var running = false
|
|
||||||
private var latest: Request<T>? = null
|
|
||||||
private var pending: Request<T>? = null
|
|
||||||
|
|
||||||
fun submit(value: T): Boolean = synchronized(lock) {
|
|
||||||
if (latest?.value != value) generation++
|
|
||||||
pending = Request(generation, value).also { latest = it }
|
|
||||||
if (running) {
|
|
||||||
false
|
|
||||||
} else {
|
|
||||||
running = true
|
|
||||||
true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun takeLatest(): Request<T>? = synchronized(lock) {
|
|
||||||
pending.also {
|
|
||||||
pending = null
|
|
||||||
if (it == null) running = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun isLatest(request: Request<T>): Boolean = synchronized(lock) {
|
|
||||||
request.generation == latest?.generation
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -2,7 +2,6 @@ package com.droiddeck.launcher.session
|
|||||||
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
import com.droiddeck.launcher.core.GameEnvironment
|
|
||||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||||
import org.json.JSONObject
|
import org.json.JSONObject
|
||||||
import java.io.File
|
import java.io.File
|
||||||
@@ -10,12 +9,10 @@ import java.io.File
|
|||||||
object ProtonDefault {
|
object ProtonDefault {
|
||||||
private const val TAG = "ProtonDefault"
|
private const val TAG = "ProtonDefault"
|
||||||
private const val DIR = "root/.local/share/droiddeck-compat"
|
private const val DIR = "root/.local/share/droiddeck-compat"
|
||||||
private const val GAMES = "games.json"
|
|
||||||
|
|
||||||
data class Tool(val name: String, val display: String, val dir: String, val valve: Boolean)
|
data class Tool(val name: String, val display: String, val dir: String, val valve: Boolean)
|
||||||
data class Request(val seq: Long, val valve: Boolean, val dir: String)
|
data class Request(val seq: Long, val valve: Boolean, val dir: String)
|
||||||
data class State(val default: String?, val applied: Long, val live: Boolean, val pending: String?, val tools: List<Tool>)
|
data class State(val default: String?, val applied: Long, val live: Boolean, val pending: String?, val tools: List<Tool>)
|
||||||
data class GameChoice(val valve: Boolean, val dir: String)
|
|
||||||
|
|
||||||
enum class Outcome { LIVE, NEXT_START, NOT_RUNNABLE }
|
enum class Outcome { LIVE, NEXT_START, NOT_RUNNABLE }
|
||||||
|
|
||||||
@@ -63,33 +60,6 @@ object ProtonDefault {
|
|||||||
return protons.firstOrNull { it.valve == pick.first && it.dir.name == pick.second }?.id
|
return protons.firstOrNull { it.valve == pick.first && it.dir.name == pick.second }?.id
|
||||||
}
|
}
|
||||||
|
|
||||||
internal fun parseGames(text: String?): Map<String, GameChoice?> {
|
|
||||||
val root = runCatching { JSONObject(text ?: "") }.getOrNull() ?: return emptyMap()
|
|
||||||
if (root.optInt("version", 0) != 1) return emptyMap()
|
|
||||||
val games = root.optJSONObject("games") ?: return emptyMap()
|
|
||||||
return buildMap {
|
|
||||||
games.keys().forEach { id ->
|
|
||||||
if (!GameEnvironment.validScope(id)) return@forEach
|
|
||||||
if (games.isNull(id)) {
|
|
||||||
put(id, null)
|
|
||||||
} else {
|
|
||||||
val value = games.optJSONObject(id) ?: return@forEach
|
|
||||||
val gameDir = value.optString("dir")
|
|
||||||
val valve = value.opt("valve")
|
|
||||||
if (gameDir.isNotEmpty() && valve is Boolean) put(id, GameChoice(valve, gameDir))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun gameChoice(context: Context, scope: String): GameChoice? =
|
|
||||||
parseGames(read(File(dir(context), GAMES)))[scope]
|
|
||||||
|
|
||||||
fun gameSelectedId(context: Context, scope: String, protons: List<ComponentsManager.Proton>): String? {
|
|
||||||
val pick = gameChoice(context, scope) ?: return null
|
|
||||||
return protons.firstOrNull { it.valve == pick.valve && it.dir.name == pick.dir }?.id
|
|
||||||
}
|
|
||||||
|
|
||||||
internal fun nextSeq(now: Long, state: State, previous: Request?): Long =
|
internal fun nextSeq(now: Long, state: State, previous: Request?): Long =
|
||||||
maxOf(now, state.applied + 1, (previous?.seq ?: 0) + 1)
|
maxOf(now, state.applied + 1, (previous?.seq ?: 0) + 1)
|
||||||
|
|
||||||
@@ -113,33 +83,4 @@ object ProtonDefault {
|
|||||||
val tool = state.tools.firstOrNull { it.valve == proton.valve && it.dir == proton.dir.name }
|
val tool = state.tools.firstOrNull { it.valve == proton.valve && it.dir == proton.dir.name }
|
||||||
return if (SessionState.running && state.live && (tool == null || state.pending != tool.name)) Outcome.LIVE else Outcome.NEXT_START
|
return if (SessionState.running && state.live && (tool == null || state.pending != tool.name)) Outcome.LIVE else Outcome.NEXT_START
|
||||||
}
|
}
|
||||||
|
|
||||||
@Synchronized
|
|
||||||
fun requestGame(context: Context, scope: String, proton: ComponentsManager.Proton?): Outcome {
|
|
||||||
require(GameEnvironment.validScope(scope))
|
|
||||||
val d = dir(context)
|
|
||||||
val choices = parseGames(read(File(d, GAMES))).toMutableMap()
|
|
||||||
choices[scope] = proton?.let { GameChoice(it.valve, it.dir.name) }
|
|
||||||
val games = JSONObject()
|
|
||||||
choices.forEach { (id, choice) ->
|
|
||||||
games.put(id, choice?.let { JSONObject().put("valve", it.valve).put("dir", it.dir) } ?: JSONObject.NULL)
|
|
||||||
}
|
|
||||||
val staged = File(d, "$GAMES.staged")
|
|
||||||
try {
|
|
||||||
d.mkdirs()
|
|
||||||
staged.writeText(JSONObject().put("version", 1).put("games", games).toString(1) + "\n")
|
|
||||||
if (!staged.renameTo(File(d, GAMES))) throw java.io.IOException("rename failed")
|
|
||||||
} catch (e: Exception) {
|
|
||||||
staged.delete()
|
|
||||||
Log.w(TAG, "could not write the per-game Proton request", e)
|
|
||||||
throw e
|
|
||||||
}
|
|
||||||
val state = state(context)
|
|
||||||
val tool = proton?.let { selected -> state.tools.firstOrNull { it.valve == selected.valve && it.dir == selected.dir.name } }
|
|
||||||
return if (SessionState.running && state.live && (proton == null || tool != null && state.pending != tool.name)) {
|
|
||||||
Outcome.LIVE
|
|
||||||
} else {
|
|
||||||
Outcome.NEXT_START
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -10,15 +10,12 @@ import com.droiddeck.launcher.core.FileUtils
|
|||||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import org.json.JSONArray
|
import org.json.JSONArray
|
||||||
import org.json.JSONObject
|
|
||||||
|
|
||||||
/** Immediate download and installation of the optional ARM64 Proton builds. */
|
/** Immediate download and installation of the optional ARM64 Proton builds. */
|
||||||
object ProtonExtras {
|
object ProtonExtras {
|
||||||
private const val TAG = "ProtonExtras"
|
private const val TAG = "ProtonExtras"
|
||||||
private const val NEED_BYTES = 4L * 1024 * 1024 * 1024
|
private const val NEED_BYTES = 4L * 1024 * 1024 * 1024
|
||||||
private const val RELEASES = "https://api.github.com/repos/%s/releases?per_page=15"
|
private const val RELEASES = "https://api.github.com/repos/%s/releases?per_page=15"
|
||||||
/** How long a release check stands before the next one goes to GitHub. */
|
|
||||||
const val CHECK_EVERY_MS = 6L * 60 * 60 * 1000
|
|
||||||
@Volatile
|
@Volatile
|
||||||
var installInProgress = false
|
var installInProgress = false
|
||||||
private set
|
private set
|
||||||
@@ -26,122 +23,23 @@ object ProtonExtras {
|
|||||||
class Tool(val id: String, val name: String, val prefix: String, val repo: String, val assetPattern: Regex)
|
class Tool(val id: String, val name: String, val prefix: String, val repo: String, val assetPattern: Regex)
|
||||||
|
|
||||||
/** [sha256] from GitHub's asset digest; [sha512] the URL of a checksum file published beside it. */
|
/** [sha256] from GitHub's asset digest; [sha512] the URL of a checksum file published beside it. */
|
||||||
internal data class Asset(val tag: String, val name: String, val url: String, val sha512: String?, val size: Long,
|
private data class Asset(val tag: String, val name: String, val url: String, val sha512: String?, val size: Long,
|
||||||
val sha256: String? = null)
|
val sha256: String? = null)
|
||||||
|
|
||||||
val tools = listOf(
|
val tools = listOf(
|
||||||
Tool("ge", "GE-Proton", "GE-Proton", "GloriousEggroll/proton-ge-custom", Regex("aarch64\\.tar\\.(gz|xz)$")),
|
Tool("ge", "GE-Proton", "GE-Proton", "GloriousEggroll/proton-ge-custom", Regex("aarch64\\.tar\\.(gz|xz)$")),
|
||||||
Tool("cachyos", "proton-cachyos", "proton-cachyos", "CachyOS/proton-cachyos", Regex("arm64\\.tar\\.(gz|xz)$")),
|
Tool("cachyos", "proton-cachyos", "proton-cachyos", "CachyOS/proton-cachyos", Regex("arm64\\.tar\\.(gz|xz)$")),
|
||||||
Tool("droiddeck", "DroidDeck-Proton", "DroidDeck-Proton", "The412Banner/DroidDeck-Proton", Regex("aarch64\\.tar\\.(gz|xz)$")),
|
|
||||||
)
|
)
|
||||||
|
|
||||||
private fun home(context: Context) = File(LinuxRuntime.rootDir(context), "root")
|
private fun home(context: Context) = File(LinuxRuntime.rootDir(context), "root")
|
||||||
private fun requests(context: Context) = File(home(context), ".bl-proton-extra")
|
private fun requests(context: Context) = File(home(context), ".bl-proton-extra")
|
||||||
private fun toolsDir(context: Context) = File(home(context), ".local/share/Steam/compatibilitytools.d")
|
private fun toolsDir(context: Context) = File(home(context), ".local/share/Steam/compatibilitytools.d")
|
||||||
/** The release tag each build was installed from, by directory name. */
|
|
||||||
private fun releasesFile(context: Context) = File(context.filesDir, "proton-extras.json")
|
|
||||||
/** The newest release seen per source, and when it was looked up. */
|
|
||||||
private fun latestFile(context: Context) = File(context.filesDir, "proton-latest.json")
|
|
||||||
|
|
||||||
/** The installed build's directory name (e.g. GE-Proton11-7), the newest when there are several, or null. */
|
/** The installed build's directory name (e.g. GE-Proton11-7), or null. */
|
||||||
fun installed(context: Context, tool: Tool): String? = installedIn(toolsDir(context), tool).lastOrNull()
|
fun installed(context: Context, tool: Tool): String? =
|
||||||
|
toolsDir(context).listFiles()
|
||||||
/** Every installed build's directory name, oldest first. */
|
|
||||||
fun installedAll(context: Context, tool: Tool): List<String> = installedIn(toolsDir(context), tool)
|
|
||||||
|
|
||||||
internal fun installedIn(dir: File, tool: Tool): List<String> =
|
|
||||||
dir.listFiles()
|
|
||||||
?.filter { it.isDirectory && it.name.startsWith(tool.prefix) && File(it, "toolmanifest.vdf").isFile }
|
?.filter { it.isDirectory && it.name.startsWith(tool.prefix) && File(it, "toolmanifest.vdf").isFile }
|
||||||
?.map { it.name }
|
?.maxByOrNull { it.name }?.name
|
||||||
?.sortedWith { a, b -> compareVersions(a, b) }
|
|
||||||
?: emptyList()
|
|
||||||
|
|
||||||
// Architecture names carry digits (aarch64, x86_64) that are not part of a version.
|
|
||||||
private val ARCH = Regex("(?i)aarch64|arm64|x86_64|x86-64|amd64")
|
|
||||||
private val NUMBER = Regex("\\d+")
|
|
||||||
|
|
||||||
/** The numbers in a release tag or build folder, in order: GE-Proton11-10 is 11, 10. */
|
|
||||||
internal fun versionKey(name: String): List<Long> =
|
|
||||||
NUMBER.findAll(ARCH.replace(name, " ")).mapNotNull { it.value.toLongOrNull() }.toList()
|
|
||||||
|
|
||||||
/** Orders by those numbers, so 11-10 is after 11-9; the name itself only breaks a tie. */
|
|
||||||
internal fun compareVersions(a: String, b: String): Int {
|
|
||||||
val x = versionKey(a)
|
|
||||||
val y = versionKey(b)
|
|
||||||
for (i in 0 until minOf(x.size, y.size)) if (x[i] != y[i]) return x[i].compareTo(y[i])
|
|
||||||
return if (x.size != y.size) x.size.compareTo(y.size) else a.compareTo(b)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** [latest] when it is newer than every installed release, else null. Nothing installed is not an update. */
|
|
||||||
internal fun updateFor(installed: List<String>, latest: String?): String? {
|
|
||||||
if (latest == null || installed.isEmpty()) return null
|
|
||||||
val newest = installed.maxWithOrNull { a, b -> compareVersions(a, b) } ?: return null
|
|
||||||
val x = versionKey(latest)
|
|
||||||
val y = versionKey(newest)
|
|
||||||
for (i in 0 until minOf(x.size, y.size)) if (x[i] != y[i]) return if (x[i] > y[i]) latest else null
|
|
||||||
return if (x.size > y.size) latest else null
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The release each installed build came from: the tag recorded at install, else its folder name. */
|
|
||||||
fun installedTags(context: Context, tool: Tool): List<String> {
|
|
||||||
val recorded = readJson(releasesFile(context))
|
|
||||||
return installedAll(context, tool).map { recorded.optString(it).ifEmpty { it } }
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A newer release than the installed one, from the last check (no network), or null. */
|
|
||||||
fun update(context: Context, tool: Tool): String? = updateFor(installedTags(context, tool), cachedLatest(context, tool))
|
|
||||||
|
|
||||||
fun cachedLatest(context: Context, tool: Tool): String? =
|
|
||||||
readJson(latestFile(context)).optJSONObject(tool.id)?.optString("tag")?.ifEmpty { null }
|
|
||||||
|
|
||||||
/** Its own lock, not the install's: a check must not wait behind a download. */
|
|
||||||
private val checkLock = Any()
|
|
||||||
/** A failed look-up (offline) is not repeated on every resume, only after this long. */
|
|
||||||
private const val RETRY_MS = 15L * 60 * 1000
|
|
||||||
private var lastAttempt = 0L
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Looks up each source's newest release unless it was looked up within [CHECK_EVERY_MS] (or
|
|
||||||
* [force]). Offline or rate limited, the last answer stands. True when anything was asked.
|
|
||||||
*/
|
|
||||||
fun checkLatest(context: Context, force: Boolean = false, now: Long = System.currentTimeMillis()): Boolean {
|
|
||||||
synchronized(checkLock) {
|
|
||||||
val file = latestFile(context)
|
|
||||||
val cache = readJson(file)
|
|
||||||
val due = tools.filter { tool ->
|
|
||||||
val at = cache.optJSONObject(tool.id)?.optLong("at", 0L) ?: 0L
|
|
||||||
force || (now - at) !in 0 until CHECK_EVERY_MS
|
|
||||||
}
|
|
||||||
if (due.isEmpty() || !force && (now - lastAttempt) in 0 until RETRY_MS) return false
|
|
||||||
lastAttempt = now
|
|
||||||
for (tool in due) {
|
|
||||||
val tag = findLatestAsset(tool)?.tag ?: continue
|
|
||||||
cache.put(tool.id, JSONObject().put("tag", tag).put("at", now))
|
|
||||||
}
|
|
||||||
runCatching { file.writeText(cache.toString()) }
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun record(context: Context, tool: Tool, dir: String?, tag: String) {
|
|
||||||
runCatching {
|
|
||||||
val latest = readJson(latestFile(context))
|
|
||||||
val known = latest.optJSONObject(tool.id)?.optString("tag")
|
|
||||||
if (known.isNullOrEmpty() || compareVersions(tag, known) >= 0) {
|
|
||||||
latest.put(tool.id, JSONObject().put("tag", tag).put("at", System.currentTimeMillis()))
|
|
||||||
latestFile(context).writeText(latest.toString())
|
|
||||||
}
|
|
||||||
if (dir != null) {
|
|
||||||
val releases = readJson(releasesFile(context))
|
|
||||||
val present = toolsDir(context).list()?.toSet() ?: emptySet()
|
|
||||||
releases.keys().asSequence().toList().filter { it !in present }.forEach { releases.remove(it) }
|
|
||||||
releasesFile(context).writeText(releases.put(dir, tag).toString())
|
|
||||||
}
|
|
||||||
}.onFailure { Log.w(TAG, "record ${tool.id} $tag", it) }
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun readJson(file: File): JSONObject =
|
|
||||||
runCatching { JSONObject(FileUtils.readString(file) ?: "{}") }.getOrDefault(JSONObject())
|
|
||||||
|
|
||||||
/** A request left by an earlier app version, still consumed by the session shim. */
|
/** A request left by an earlier app version, still consumed by the session shim. */
|
||||||
fun queued(context: Context, tool: Tool): Boolean =
|
fun queued(context: Context, tool: Tool): Boolean =
|
||||||
@@ -154,15 +52,9 @@ object ProtonExtras {
|
|||||||
else file.writeText(lines.joinToString("\n") + "\n")
|
else file.writeText(lines.joinToString("\n") + "\n")
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Deletes one installed build ([dir], else the newest); Steam discovers its absence on its next start. */
|
/** Deletes the installed build; Steam discovers its absence on its next start. */
|
||||||
fun remove(context: Context, tool: Tool, dir: String? = null) {
|
fun remove(context: Context, tool: Tool) {
|
||||||
val name = if (dir != null) dir.takeIf { it in installedAll(context, tool) } ?: return else installed(context, tool) ?: return
|
installed(context, tool)?.let { File(toolsDir(context), it).deleteRecursively() }
|
||||||
File(toolsDir(context), name).deleteRecursively()
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Deletes every build but the newest. */
|
|
||||||
fun removeOlder(context: Context, tool: Tool) {
|
|
||||||
installedAll(context, tool).dropLast(1).forEach { File(toolsDir(context), it).deleteRecursively() }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Downloads, verifies and registers the latest build without waiting for another session. */
|
/** Downloads, verifies and registers the latest build without waiting for another session. */
|
||||||
@@ -253,12 +145,9 @@ object ProtonExtras {
|
|||||||
hostEnv["PROOT_TMP_DIR"] = context.cacheDir.path
|
hostEnv["PROOT_TMP_DIR"] = context.cacheDir.path
|
||||||
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { hostEnv["LD_LIBRARY_PATH"] = it }
|
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { hostEnv["LD_LIBRARY_PATH"] = it }
|
||||||
val child = process.start()
|
val child = process.start()
|
||||||
var placed: String? = null
|
|
||||||
child.inputStream.bufferedReader().useLines { lines ->
|
child.inputStream.bufferedReader().useLines { lines ->
|
||||||
lines.forEach { line ->
|
lines.forEach { line ->
|
||||||
Log.i(TAG, line)
|
Log.i(TAG, line)
|
||||||
// "droiddeck-proton-extra: installed <folder>", the folder as the tarball names it.
|
|
||||||
line.substringAfter("droiddeck-proton-extra: installed ", "").takeIf { it.isNotEmpty() }?.let { placed = it }
|
|
||||||
if (line.contains("unpacking", ignoreCase = true) || line.contains("adopted", ignoreCase = true)) {
|
if (line.contains("unpacking", ignoreCase = true) || line.contains("adopted", ignoreCase = true)) {
|
||||||
onProgress(installing, -1)
|
onProgress(installing, -1)
|
||||||
}
|
}
|
||||||
@@ -269,7 +158,6 @@ object ProtonExtras {
|
|||||||
else {
|
else {
|
||||||
archive.delete()
|
archive.delete()
|
||||||
unqueue(context, tool)
|
unqueue(context, tool)
|
||||||
record(context, tool, placed, asset.tag)
|
|
||||||
if (EsyncPacks.enabled(context)) {
|
if (EsyncPacks.enabled(context)) {
|
||||||
onProgress(context.getString(R.string.esync_fetching), -1)
|
onProgress(context.getString(R.string.esync_fetching), -1)
|
||||||
try {
|
try {
|
||||||
@@ -289,36 +177,32 @@ object ProtonExtras {
|
|||||||
private fun findLatestAsset(tool: Tool): Asset? {
|
private fun findLatestAsset(tool: Tool): Asset? {
|
||||||
val releases = Downloader.downloadString(RELEASES.format(tool.repo)) ?: return null
|
val releases = Downloader.downloadString(RELEASES.format(tool.repo)) ?: return null
|
||||||
return try {
|
return try {
|
||||||
pickAsset(tool, JSONArray(releases))
|
val array = JSONArray(releases)
|
||||||
|
for (i in 0 until array.length()) {
|
||||||
|
val release = array.getJSONObject(i)
|
||||||
|
if (release.optBoolean("draft", false)) continue
|
||||||
|
val assets = release.optJSONArray("assets") ?: continue
|
||||||
|
val entries = (0 until assets.length()).map { assets.getJSONObject(it) }
|
||||||
|
val archive = entries.sortedBy { it.optString("name") }.firstOrNull { tool.assetPattern.containsMatchIn(it.optString("name")) } ?: continue
|
||||||
|
val name = archive.optString("name")
|
||||||
|
val stem = name.substringBefore(".tar")
|
||||||
|
val checksum = entries.firstOrNull {
|
||||||
|
it.optString("name").startsWith(stem) && it.optString("name").contains("sha512", ignoreCase = true)
|
||||||
|
}?.optString("browser_download_url")?.takeIf { it.startsWith("http") }
|
||||||
|
return Asset(
|
||||||
|
release.optString("tag_name"), name,
|
||||||
|
archive.optString("browser_download_url").takeIf { it.startsWith("http") } ?: continue, checksum,
|
||||||
|
archive.optLong("size", 0L),
|
||||||
|
Hashes.githubSha256(archive.optString("digest")),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
null
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
Log.w(TAG, "release metadata for ${tool.id}", e)
|
Log.w(TAG, "release metadata for ${tool.id}", e)
|
||||||
null
|
null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The newest full release in GitHub's list (newest first) that carries [tool]'s ARM64 archive. */
|
|
||||||
internal fun pickAsset(tool: Tool, array: JSONArray): Asset? {
|
|
||||||
for (i in 0 until array.length()) {
|
|
||||||
val release = array.getJSONObject(i)
|
|
||||||
if (release.optBoolean("draft", false) || release.optBoolean("prerelease", false)) continue
|
|
||||||
val assets = release.optJSONArray("assets") ?: continue
|
|
||||||
val entries = (0 until assets.length()).map { assets.getJSONObject(it) }
|
|
||||||
val archive = entries.sortedBy { it.optString("name") }.firstOrNull { tool.assetPattern.containsMatchIn(it.optString("name")) } ?: continue
|
|
||||||
val name = archive.optString("name")
|
|
||||||
val stem = name.substringBefore(".tar")
|
|
||||||
val checksum = entries.firstOrNull {
|
|
||||||
it.optString("name").startsWith(stem) && it.optString("name").contains("sha512", ignoreCase = true)
|
|
||||||
}?.optString("browser_download_url")?.takeIf { it.startsWith("http") }
|
|
||||||
return Asset(
|
|
||||||
release.optString("tag_name"), name,
|
|
||||||
archive.optString("browser_download_url").takeIf { it.startsWith("http") } ?: continue, checksum,
|
|
||||||
archive.optLong("size", 0L),
|
|
||||||
Hashes.githubSha256(archive.optString("digest")),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun requestLines(context: Context): List<String> =
|
private fun requestLines(context: Context): List<String> =
|
||||||
FileUtils.readString(requests(context))?.lines()?.filter { it.isNotBlank() } ?: emptyList()
|
FileUtils.readString(requests(context))?.lines()?.filter { it.isNotBlank() } ?: emptyList()
|
||||||
}
|
}
|
||||||
@@ -4,7 +4,6 @@ import android.net.LocalServerSocket
|
|||||||
import android.content.SharedPreferences
|
import android.content.SharedPreferences
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
import android.os.CombinedVibration
|
import android.os.CombinedVibration
|
||||||
import android.os.SystemClock
|
|
||||||
import android.os.VibrationEffect
|
import android.os.VibrationEffect
|
||||||
import android.os.Vibrator
|
import android.os.Vibrator
|
||||||
import android.os.VibratorManager
|
import android.os.VibratorManager
|
||||||
@@ -34,8 +33,6 @@ class RumbleComponent : SessionPart() {
|
|||||||
private var phone: Motors? = null
|
private var phone: Motors? = null
|
||||||
/** Per slot, where its last effect went, so the next one (or a stop) can end it there. */
|
/** Per slot, where its last effect went, so the next one (or a stop) can end it there. */
|
||||||
private val playing = HashMap<Int, Motors>()
|
private val playing = HashMap<Int, Motors>()
|
||||||
/** Per slot, the last effect handed to the motors and when, to drop the repeats games stream. */
|
|
||||||
private val sent = HashMap<Int, Sent>()
|
|
||||||
/** Each controller's motors, looked up once; null when it has none. */
|
/** Each controller's motors, looked up once; null when it has none. */
|
||||||
private val controllers = HashMap<Int, Motors?>()
|
private val controllers = HashMap<Int, Motors?>()
|
||||||
private var preferences: SharedPreferences? = null
|
private var preferences: SharedPreferences? = null
|
||||||
@@ -98,21 +95,13 @@ class RumbleComponent : SessionPart() {
|
|||||||
val previous = playing[slot]
|
val previous = playing[slot]
|
||||||
if (target !== previous) {
|
if (target !== previous) {
|
||||||
previous?.cancel()
|
previous?.cancel()
|
||||||
sent.remove(slot)
|
|
||||||
if (target == null) playing.remove(slot) else playing[slot] = target
|
if (target == null) playing.remove(slot) else playing[slot] = target
|
||||||
target?.let { Log.i(TAG, "rumble: slot $slot playing on ${it.name}") }
|
target?.let { Log.i(TAG, "rumble: slot $slot playing on ${it.name}") }
|
||||||
}
|
}
|
||||||
if (target == null) return
|
if (target == null) return
|
||||||
if ((strong == 0 && weak == 0) || ms == 0) { target.cancel(); sent.remove(slot); return }
|
if ((strong == 0 && weak == 0) || ms == 0) { target.cancel(); return }
|
||||||
// Games re-send their effect every frame; restarting the motor that often floods the haptics
|
|
||||||
// driver. ponytail: a change inside MIN_GAP_MS is dropped, the game's next packet brings it.
|
|
||||||
val now = SystemClock.uptimeMillis()
|
|
||||||
val last = sent[slot]
|
|
||||||
if (last != null && (now - last.at < MIN_GAP_MS || (last.strong == strong && last.weak == weak && now < last.until))) return
|
|
||||||
val duration = ms.toLong().coerceIn(1L, 5000L)
|
|
||||||
try {
|
try {
|
||||||
target.play(strong, weak, duration)
|
target.play(strong, weak, ms.toLong().coerceIn(1L, 5000L))
|
||||||
sent[slot] = Sent(strong, weak, now, now + duration)
|
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
Log.w(TAG, "rumble: ${target.name}: $e")
|
Log.w(TAG, "rumble: ${target.name}: $e")
|
||||||
}
|
}
|
||||||
@@ -129,11 +118,8 @@ class RumbleComponent : SessionPart() {
|
|||||||
private fun cancelAll() {
|
private fun cancelAll() {
|
||||||
playing.values.toSet().forEach { it.cancel() }
|
playing.values.toSet().forEach { it.cancel() }
|
||||||
playing.clear()
|
playing.clear()
|
||||||
sent.clear()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private data class Sent(val strong: Int, val weak: Int, val at: Long, val until: Long)
|
|
||||||
|
|
||||||
/** One place an effect can play. Strengths are the evdev 0..65535 magnitudes. */
|
/** One place an effect can play. Strengths are the evdev 0..65535 magnitudes. */
|
||||||
internal interface Motors {
|
internal interface Motors {
|
||||||
val name: String
|
val name: String
|
||||||
@@ -174,8 +160,6 @@ class RumbleComponent : SessionPart() {
|
|||||||
private const val TAG = "SessionService"
|
private const val TAG = "SessionService"
|
||||||
/** Must match the fake evdev layer (fakeinput_steam.cpp). */
|
/** Must match the fake evdev layer (fakeinput_steam.cpp). */
|
||||||
const val NAME = "droiddeck-rumble"
|
const val NAME = "droiddeck-rumble"
|
||||||
/** The shortest time between two effects started on one slot's motors. */
|
|
||||||
const val MIN_GAP_MS = 50L
|
|
||||||
|
|
||||||
private fun oneShot(vibrator: Vibrator, strength: Int, ms: Long): VibrationEffect {
|
private fun oneShot(vibrator: Vibrator, strength: Int, ms: Long): VibrationEffect {
|
||||||
val amplitude = if (vibrator.hasAmplitudeControl()) (strength * 255L / 65535L).toInt().coerceIn(1, 255)
|
val amplitude = if (vibrator.hasAmplitudeControl()) (strength * 255L / 65535L).toInt().coerceIn(1, 255)
|
||||||
|
|||||||
@@ -1,70 +0,0 @@
|
|||||||
package com.droiddeck.launcher.session
|
|
||||||
|
|
||||||
import com.droiddeck.launcher.core.FexPreset
|
|
||||||
import com.droiddeck.launcher.core.GameEnvironment
|
|
||||||
import com.droiddeck.launcher.frontend.Library
|
|
||||||
|
|
||||||
data class ProfileValue(val value: String, val inherited: Boolean)
|
|
||||||
|
|
||||||
data class SelectedGameProfile(
|
|
||||||
val appId: Long,
|
|
||||||
val name: String,
|
|
||||||
val fexPreset: ProfileValue,
|
|
||||||
val proton: ProfileValue,
|
|
||||||
val protonId: String?,
|
|
||||||
val components: Map<String, ProfileValue>,
|
|
||||||
val componentFiles: Map<String, String>,
|
|
||||||
val environmentOverrides: Int,
|
|
||||||
val windowsComponentNames: List<String>,
|
|
||||||
) {
|
|
||||||
val hasOverrides: Boolean
|
|
||||||
get() = !fexPreset.inherited ||
|
|
||||||
!proton.inherited ||
|
|
||||||
components.values.any { !it.inherited } ||
|
|
||||||
environmentOverrides > 0 ||
|
|
||||||
windowsComponentNames.isNotEmpty()
|
|
||||||
|
|
||||||
companion object {
|
|
||||||
fun resolve(
|
|
||||||
selectedAppId: Long,
|
|
||||||
games: List<Library.SteamGame>,
|
|
||||||
generalFexPreset: String,
|
|
||||||
environment: GameEnvironment.Config,
|
|
||||||
snapshot: ComponentsManager.Snapshot,
|
|
||||||
generalProtonId: String?,
|
|
||||||
gameProtonChoice: ProtonDefault.GameChoice?,
|
|
||||||
gameProtonId: String?,
|
|
||||||
gameComponents: Map<String, String>,
|
|
||||||
gameWindowsComponents: List<String>,
|
|
||||||
): SelectedGameProfile? {
|
|
||||||
val game = games.firstOrNull { it.profileKey == selectedAppId.toString() } ?: return null
|
|
||||||
val fexOverride = GameEnvironment.gameFexPreset(environment, game.profileKey)
|
|
||||||
val selectedProtonId = if (gameProtonChoice == null) generalProtonId else gameProtonId
|
|
||||||
val selectedProton = snapshot.protons.firstOrNull { it.proton.id == selectedProtonId }
|
|
||||||
val packages = snapshot.packages.associateBy { it.file }
|
|
||||||
val components = ComponentsManager.COMPONENTS.associateWith { component ->
|
|
||||||
val override = gameComponents[component]
|
|
||||||
ProfileValue(
|
|
||||||
value = override?.let { packages[it]?.version ?: it }
|
|
||||||
?: selectedProton?.components?.get(component)?.selected.orEmpty(),
|
|
||||||
inherited = override == null,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
val otherEnvironment = environment.games[game.profileKey].orEmpty().keys - FexPreset.environmentKeys
|
|
||||||
return SelectedGameProfile(
|
|
||||||
appId = selectedAppId,
|
|
||||||
name = game.name,
|
|
||||||
fexPreset = ProfileValue(fexOverride ?: generalFexPreset, fexOverride == null),
|
|
||||||
proton = ProfileValue(
|
|
||||||
selectedProton?.proton?.name ?: gameProtonChoice?.dir.orEmpty(),
|
|
||||||
gameProtonChoice == null,
|
|
||||||
),
|
|
||||||
protonId = selectedProtonId,
|
|
||||||
components = components,
|
|
||||||
componentFiles = gameComponents,
|
|
||||||
environmentOverrides = otherEnvironment.size,
|
|
||||||
windowsComponentNames = gameWindowsComponents.map(WinComponentNames::of),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -52,26 +52,6 @@ object SessionDisplay {
|
|||||||
fun followSize(width: Int, height: Int): Pair<Int, Int>? =
|
fun followSize(width: Int, height: Int): Pair<Int, Int>? =
|
||||||
if (minOf(width, height) < FOLLOW_MIN_SIDE) null else (width and 1.inv()) to (height and 1.inv())
|
if (minOf(width, height) < FOLLOW_MIN_SIDE) null else (width and 1.inv()) to (height and 1.inv())
|
||||||
|
|
||||||
/** Unfolded controls: the most of the window the game may take, so a window near 16:9 itself
|
|
||||||
* still leaves the Deck controls room. */
|
|
||||||
const val UNFOLDED_MAX_GAME_SHARE = 0.8f
|
|
||||||
|
|
||||||
/** A foldable: Android 11's hinge angle sensor, which foldables report and slates do not. Unfolded
|
|
||||||
* controls are offered only there - untested on tablets, whose 16:10 landscape leaves them
|
|
||||||
* little room under a 16:9 game. */
|
|
||||||
fun foldable(context: Context): Boolean =
|
|
||||||
context.packageManager.hasSystemFeature("android.hardware.sensor.hinge_angle")
|
|
||||||
|
|
||||||
/** A panel at least this wide on its shortest side (dp) is a foldable's unfolded inner screen. */
|
|
||||||
const val UNFOLDED_MIN_DP = 600
|
|
||||||
|
|
||||||
/** Unfolded controls: the game's height in a window of this size - 16:9 across the full width,
|
|
||||||
* held either way, with even sides - and the Deck controls take the rest below it, laid out to
|
|
||||||
* whatever that leaves (DeckControlsPanel's GamepadLayout). */
|
|
||||||
fun unfoldedGameHeight(width: Int, height: Int): Int =
|
|
||||||
minOf(width * 9 / 16, (height * UNFOLDED_MAX_GAME_SHARE).toInt()) and 1.inv()
|
|
||||||
|
|
||||||
|
|
||||||
fun panelSize(context: Context): Pair<Int, Int> {
|
fun panelSize(context: Context): Pair<Int, Int> {
|
||||||
val manager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
|
val manager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
|
||||||
@Suppress("DEPRECATION")
|
@Suppress("DEPRECATION")
|
||||||
|
|||||||
@@ -72,7 +72,6 @@ object SessionFiles {
|
|||||||
"usr/local/bin/droiddeck-steam-desktop-ui" to "usr/local/bin/droiddeck-steam-desktop-ui",
|
"usr/local/bin/droiddeck-steam-desktop-ui" to "usr/local/bin/droiddeck-steam-desktop-ui",
|
||||||
"usr/local/bin/droiddeck-steam-library" to "usr/local/bin/droiddeck-steam-library",
|
"usr/local/bin/droiddeck-steam-library" to "usr/local/bin/droiddeck-steam-library",
|
||||||
"usr/local/bin/droiddeck-seed-redists" to "usr/local/bin/droiddeck-seed-redists",
|
"usr/local/bin/droiddeck-seed-redists" to "usr/local/bin/droiddeck-seed-redists",
|
||||||
"usr/local/bin/droiddeck-launcher-cores" to "usr/local/bin/droiddeck-launcher-cores",
|
|
||||||
"usr/local/bin/droiddeck-proton-extra" to "usr/local/bin/droiddeck-proton-extra",
|
"usr/local/bin/droiddeck-proton-extra" to "usr/local/bin/droiddeck-proton-extra",
|
||||||
"usr/local/bin/droiddeck-netmanager" to "usr/local/bin/droiddeck-netmanager",
|
"usr/local/bin/droiddeck-netmanager" to "usr/local/bin/droiddeck-netmanager",
|
||||||
"usr/local/bin/droiddeck-login1" to "usr/local/bin/droiddeck-login1",
|
"usr/local/bin/droiddeck-login1" to "usr/local/bin/droiddeck-login1",
|
||||||
@@ -95,10 +94,6 @@ object SessionFiles {
|
|||||||
// The user's own AppImages, extracted at import (AppImageManager).
|
// The user's own AppImages, extracted at import (AppImageManager).
|
||||||
"usr/local/bin/droiddeck-appimage-run" to "usr/local/bin/droiddeck-appimage-run",
|
"usr/local/bin/droiddeck-appimage-run" to "usr/local/bin/droiddeck-appimage-run",
|
||||||
"usr/local/bin/droiddeck-script-run" to "usr/local/bin/droiddeck-script-run",
|
"usr/local/bin/droiddeck-script-run" to "usr/local/bin/droiddeck-script-run",
|
||||||
// The desktop's Run entries and its exec fallback: Windows programs through Steam's Proton,
|
|
||||||
// x86 Linux programs through FEX.
|
|
||||||
"usr/local/bin/droiddeck-open" to "usr/local/bin/droiddeck-open",
|
|
||||||
"usr/local/bin/droiddeck-proton-run" to "usr/local/bin/droiddeck-proton-run",
|
|
||||||
// The SteamOS helpers the client calls in Deck mode: the two Armada found it needs, plus
|
// The SteamOS helpers the client calls in Deck mode: the two Armada found it needs, plus
|
||||||
// the three under /usr/bin, all no-ops that answer "nothing to do" (see each file).
|
// the three under /usr/bin, all no-ops that answer "nothing to do" (see each file).
|
||||||
"usr/bin/steamos-update" to "usr/bin/steamos-update",
|
"usr/bin/steamos-update" to "usr/bin/steamos-update",
|
||||||
@@ -134,8 +129,8 @@ object SessionFiles {
|
|||||||
.map { "usr/local/lib/droiddeck-msitools/$it" } +
|
.map { "usr/local/lib/droiddeck-msitools/$it" } +
|
||||||
listOf("NOTICE", "GPL-2", "GPL-3", "LGPL-2.1", "7zip-License", "7zip-unRarLicense").map { "usr/local/share/licenses/droiddeck-msitools/$it" }
|
listOf("NOTICE", "GPL-2", "GPL-3", "LGPL-2.1", "7zip-License", "7zip-unRarLicense").map { "usr/local/share/licenses/droiddeck-msitools/$it" }
|
||||||
val fexPreloads = listOf("x86_64", "i386").flatMap { arch ->
|
val fexPreloads = listOf("x86_64", "i386").flatMap { arch ->
|
||||||
listOf("libblsession.so", "libfakeinput.so", "libfaultreport.so").map { "$arch/$it" to "usr/local/lib/droiddeck-fex/$arch/$it" }
|
listOf("libblsession.so", "libfakeinput.so").map { "$arch/$it" to "usr/local/lib/droiddeck-fex/$arch/$it" }
|
||||||
} + listOf("libthunkaudit.so", "libvulkan-thunk.so").map { "x86_64/$it" to "usr/local/lib/droiddeck-fex/x86_64/$it" }
|
} + listOf("libfaultreport.so", "libthunkaudit.so", "libvulkan-thunk.so").map { "x86_64/$it" to "usr/local/lib/droiddeck-fex/x86_64/$it" }
|
||||||
val optional = (arrayOf(
|
val optional = (arrayOf(
|
||||||
"usr/local/bin/gamescope" to "usr/local/bin/gamescope",
|
"usr/local/bin/gamescope" to "usr/local/bin/gamescope",
|
||||||
"usr/local/lib/droiddeck/uruntime" to "usr/local/lib/droiddeck/uruntime",
|
"usr/local/lib/droiddeck/uruntime" to "usr/local/lib/droiddeck/uruntime",
|
||||||
|
|||||||
@@ -1,18 +1,14 @@
|
|||||||
package com.droiddeck.launcher.session
|
package com.droiddeck.launcher.session
|
||||||
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.content.pm.ActivityInfo
|
|
||||||
import androidx.annotation.StringRes
|
import androidx.annotation.StringRes
|
||||||
import com.droiddeck.launcher.R
|
import com.droiddeck.launcher.R
|
||||||
import com.droiddeck.launcher.core.GameEnvironment
|
|
||||||
import com.droiddeck.launcher.core.TextureFiltering
|
import com.droiddeck.launcher.core.TextureFiltering
|
||||||
import com.droiddeck.launcher.gpu.ScreenEffects
|
import com.droiddeck.launcher.gpu.ScreenEffects
|
||||||
import org.json.JSONObject
|
import org.json.JSONObject
|
||||||
|
|
||||||
/** The in-session switches: the HUD and how the on-screen controls decide to appear. */
|
/** The in-session switches: the HUD and how the on-screen controls decide to appear. */
|
||||||
object SessionPrefs {
|
object SessionPrefs {
|
||||||
data class GameTextureFiltering(val anisotropy: Int? = null, val lodBias: String? = null)
|
|
||||||
|
|
||||||
const val SUSPEND_AUTO = "auto"
|
const val SUSPEND_AUTO = "auto"
|
||||||
const val SUSPEND_NATIVE = "native"
|
const val SUSPEND_NATIVE = "native"
|
||||||
const val SUSPEND_MANUAL = "manual"
|
const val SUSPEND_MANUAL = "manual"
|
||||||
@@ -22,9 +18,6 @@ object SessionPrefs {
|
|||||||
|
|
||||||
const val CONTROLLER_DECK = "deck"
|
const val CONTROLLER_DECK = "deck"
|
||||||
const val CONTROLLER_XBOX360 = "xbox360"
|
const val CONTROLLER_XBOX360 = "xbox360"
|
||||||
const val CONTROLLER_STEAM = "steamcontroller"
|
|
||||||
const val CONTROLLER_DS4 = "dualshock4"
|
|
||||||
const val CONTROLLER_DUALSENSE = "dualsense"
|
|
||||||
const val OSC_AUTO = "auto"
|
const val OSC_AUTO = "auto"
|
||||||
const val OSC_ALWAYS = "always"
|
const val OSC_ALWAYS = "always"
|
||||||
const val OSC_STEAM_QAM = "steam-qam"
|
const val OSC_STEAM_QAM = "steam-qam"
|
||||||
@@ -42,22 +35,6 @@ object SessionPrefs {
|
|||||||
|
|
||||||
private fun prefs(context: Context) = context.getSharedPreferences("session", Context.MODE_PRIVATE)
|
private fun prefs(context: Context) = context.getSharedPreferences("session", Context.MODE_PRIVATE)
|
||||||
|
|
||||||
val orientationOptions = listOf(
|
|
||||||
ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE to R.string.setup_orientation_auto,
|
|
||||||
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE to R.string.setup_orientation_landscape,
|
|
||||||
ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE to R.string.setup_orientation_reverse,
|
|
||||||
)
|
|
||||||
|
|
||||||
fun orientation(context: Context): Int =
|
|
||||||
prefs(context).getInt("orientation", ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE)
|
|
||||||
.takeIf { value -> orientationOptions.any { it.first == value } }
|
|
||||||
?: ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
|
|
||||||
|
|
||||||
fun setOrientation(context: Context, orientation: Int) {
|
|
||||||
require(orientationOptions.any { it.first == orientation })
|
|
||||||
prefs(context).edit().putInt("orientation", orientation).apply()
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Whether the launcher hides Android's status and navigation bars. */
|
/** Whether the launcher hides Android's status and navigation bars. */
|
||||||
fun launcherFullscreen(context: Context): Boolean = prefs(context).getBoolean("launcherFullscreen", true)
|
fun launcherFullscreen(context: Context): Boolean = prefs(context).getBoolean("launcherFullscreen", true)
|
||||||
|
|
||||||
@@ -71,7 +48,15 @@ object SessionPrefs {
|
|||||||
prefs(context).edit().putBoolean("animations", on).apply()
|
prefs(context).edit().putBoolean("animations", on).apply()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun gameStoresEnabled(context: Context): Boolean = prefs(context).getBoolean("gameStoresEnabled", true)
|
/** The Flathub Store (beta): its rail item. Off by default. */
|
||||||
|
fun storeEnabled(context: Context): Boolean = prefs(context).getBoolean("storeEnabled", false)
|
||||||
|
|
||||||
|
fun setStoreEnabled(context: Context, on: Boolean) {
|
||||||
|
prefs(context).edit().putBoolean("storeEnabled", on).apply()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The Stores section (GOG, Epic Games, Amazon Games): its rail item. Off by default. */
|
||||||
|
fun gameStoresEnabled(context: Context): Boolean = prefs(context).getBoolean("gameStoresEnabled", false)
|
||||||
|
|
||||||
fun setGameStoresEnabled(context: Context, on: Boolean) {
|
fun setGameStoresEnabled(context: Context, on: Boolean) {
|
||||||
prefs(context).edit().putBoolean("gameStoresEnabled", on).apply()
|
prefs(context).edit().putBoolean("gameStoresEnabled", on).apply()
|
||||||
@@ -129,9 +114,9 @@ object SessionPrefs {
|
|||||||
|
|
||||||
private fun hudKey(context: Context) = if (mangoappSession(context)) "hudDeck" else "hud"
|
private fun hudKey(context: Context) = if (mangoappSession(context)) "hudDeck" else "hud"
|
||||||
|
|
||||||
/** A Steam session with Deck mode's performance overlay (mangoapp). */
|
/** A Steam session that runs Deck mode with its performance overlay (mangoapp). */
|
||||||
private fun mangoappSession(context: Context) =
|
private fun mangoappSession(context: Context) =
|
||||||
SessionState.mode == SessionService.MODE_STEAM && mangoapp(context)
|
SessionState.mode == SessionService.MODE_STEAM && steamDeckMode(context) && mangoapp(context)
|
||||||
|
|
||||||
/** When enabled, a single Back opens Steam QAM and a double Back opens the session menu. */
|
/** When enabled, a single Back opens Steam QAM and a double Back opens the session menu. */
|
||||||
fun backActionsInverted(context: Context): Boolean = prefs(context).getBoolean("backActionsInverted", false)
|
fun backActionsInverted(context: Context): Boolean = prefs(context).getBoolean("backActionsInverted", false)
|
||||||
@@ -447,21 +432,27 @@ object SessionPrefs {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* What the pad is to the Steam client: [CONTROLLER_DECK], a Steam Deck controller (Quick Access
|
* What the pad is to the Steam client: [CONTROLLER_DECK], a Steam Deck controller (Quick Access
|
||||||
* button, gyro, Steam Input's full treatment - SteamDeckPad), [CONTROLLER_STEAM], a 2025 Steam
|
* button, gyro, Steam Input's full treatment - SteamDeckPad), or [CONTROLLER_XBOX360], the plain
|
||||||
* Controller (the same, plus grip sense and its own haptics), [CONTROLLER_DS4] or
|
* Xbox 360 pad of earlier versions (QAM by the Guide+A chord).
|
||||||
* [CONTROLLER_DUALSENSE], a PlayStation pad with its touchpad fed by the trackpads, or
|
|
||||||
* [CONTROLLER_XBOX360], the plain Xbox 360 pad of earlier versions (QAM by the Guide+A chord).
|
|
||||||
*/
|
*/
|
||||||
fun steamController(context: Context): String =
|
fun steamController(context: Context): String =
|
||||||
prefs(context).getString("steamController", CONTROLLER_DECK) ?: CONTROLLER_DECK
|
prefs(context).getString("steamController", CONTROLLER_DECK) ?: CONTROLLER_DECK
|
||||||
fun setSteamController(context: Context, id: String) { prefs(context).edit().putString("steamController", id).apply() }
|
fun setSteamController(context: Context, id: String) { prefs(context).edit().putString("steamController", id).apply() }
|
||||||
/** [steamController]'s choice as libfakeinput's pad type (FakeInputWriter.PAD_TYPE_*). */
|
|
||||||
fun padType(id: String): Int = when (id) {
|
/** Runs the SteamOS gamepad client with its Quick Access performance controls. On by default (settleDeckModeDefault). */
|
||||||
CONTROLLER_STEAM -> com.droiddeck.launcher.input.FakeInputWriter.PAD_TYPE_STEAM
|
fun steamDeckMode(context: Context): Boolean = prefs(context).getBoolean("steamDeckMode", true)
|
||||||
CONTROLLER_XBOX360 -> com.droiddeck.launcher.input.FakeInputWriter.PAD_TYPE_XBOX
|
fun setSteamDeckMode(context: Context, on: Boolean) { prefs(context).edit().putBoolean("steamDeckMode", on).apply() }
|
||||||
CONTROLLER_DS4 -> com.droiddeck.launcher.input.FakeInputWriter.PAD_TYPE_DS4
|
|
||||||
CONTROLLER_DUALSENSE -> com.droiddeck.launcher.input.FakeInputWriter.PAD_TYPE_DUALSENSE
|
/**
|
||||||
else -> com.droiddeck.launcher.input.FakeInputWriter.PAD_TYPE_DECK
|
* Deck mode is the default: every install, new or from before, is moved to it once. An install
|
||||||
|
* from before 0.3.0 had off written down for it whether or not anyone chose it, so the move
|
||||||
|
* can't tell a choice from that default and moves everyone; turning it off afterwards sticks.
|
||||||
|
* Run once at process start, before anything reads or writes these prefs.
|
||||||
|
*/
|
||||||
|
fun settleDeckModeDefault(context: Context) {
|
||||||
|
val p = prefs(context)
|
||||||
|
if (p.getBoolean("deckModeMoved", false)) return
|
||||||
|
p.edit().putBoolean("steamDeckMode", true).putBoolean("deckModeMoved", true).apply()
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -595,6 +586,24 @@ object SessionPrefs {
|
|||||||
.onFailure { android.util.Log.e("GameEnvironment", "Could not update game environment", it) }
|
.onFailure { android.util.Log.e("GameEnvironment", "Could not update game environment", it) }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The Steam client branch used for the first download and forced on the command line:
|
||||||
|
* "steamdeck_publicbeta" by default, or "publicbeta" when chosen with Deck mode off.
|
||||||
|
* Deck mode always takes the Deck branch, whatever was chosen:
|
||||||
|
* with -steamos3 the client picks its own branch as SteamOS does, and on publicbeta it settled
|
||||||
|
* on steamdeck_stable - an older client it then offered as a "Software Update" in every session,
|
||||||
|
* which applying turns into the exit-42 restart loop (seen on device 2026-09-30). Earlier, Deck
|
||||||
|
* mode on publicbeta also reinstalled the same client at every start (2026-09-23). On
|
||||||
|
* steamdeck_publicbeta the client finds no update. The choice applies with Deck mode off.
|
||||||
|
*/
|
||||||
|
fun steamChannel(context: Context): String =
|
||||||
|
if (steamDeckMode(context)) "steamdeck_publicbeta"
|
||||||
|
else prefs(context).getString("steamChannel", null) ?: "steamdeck_publicbeta"
|
||||||
|
|
||||||
|
fun setSteamChannel(context: Context, id: String) {
|
||||||
|
prefs(context).edit().putString("steamChannel", id).apply()
|
||||||
|
}
|
||||||
|
|
||||||
/** Whether opening DroidDeck starts a Steam session instead of showing the front end. */
|
/** Whether opening DroidDeck starts a Steam session instead of showing the front end. */
|
||||||
fun runSteamAtStartup(context: Context): Boolean = prefs(context).getBoolean("runSteamAtStartup", false)
|
fun runSteamAtStartup(context: Context): Boolean = prefs(context).getBoolean("runSteamAtStartup", false)
|
||||||
|
|
||||||
@@ -603,9 +612,8 @@ object SessionPrefs {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The Games folders earlier builds let the user add (one game per subfolder); read only by
|
* The folders of the user's own Windows games (one game per subfolder), any number of them
|
||||||
* GamesFolderMigration, which turns them into entries and clears them. The single folder an
|
* from anywhere on the device. The single folder an earlier build kept is carried in.
|
||||||
* even earlier build kept is carried in.
|
|
||||||
*/
|
*/
|
||||||
fun addedGamesDirs(context: Context): List<String> {
|
fun addedGamesDirs(context: Context): List<String> {
|
||||||
val p = prefs(context)
|
val p = prefs(context)
|
||||||
@@ -619,26 +627,6 @@ object SessionPrefs {
|
|||||||
prefs(context).edit().putString("addedGamesDirs", dirs.distinct().joinToString("\n")).remove("addedGamesDir").apply()
|
prefs(context).edit().putString("addedGamesDirs", dirs.distinct().joinToString("\n")).remove("addedGamesDir").apply()
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* The Games folders earlier builds had (host path, guest path), still bound into the session so
|
|
||||||
* their games keep their paths; written once by GamesFolderMigration.
|
|
||||||
*/
|
|
||||||
fun gameFolderBinds(context: Context): List<Pair<String, String>> =
|
|
||||||
(prefs(context).getString("gameFolderBinds", "") ?: "").split('\n').mapNotNull { line ->
|
|
||||||
line.split('\t').takeIf { it.size == 2 && it[0].isNotEmpty() && it[1].isNotEmpty() }?.let { it[0] to it[1] }
|
|
||||||
}
|
|
||||||
|
|
||||||
fun setGameFolderBinds(context: Context, binds: List<Pair<String, String>>) {
|
|
||||||
prefs(context).edit().putString("gameFolderBinds", binds.distinctBy { it.first }.joinToString("\n") { "${it.first}\t${it.second}" }).apply()
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The Games folders were turned into entries (GamesFolderMigration); a record, not a gate. */
|
|
||||||
fun gamesFoldersMigrated(context: Context): Boolean = prefs(context).getBoolean("gamesFoldersMigrated", false)
|
|
||||||
|
|
||||||
fun setGamesFoldersMigrated(context: Context) {
|
|
||||||
prefs(context).edit().putBoolean("gamesFoldersMigrated", true).apply()
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Game folders (by path) the user removed from the added games: a scan skips them, so they
|
* Game folders (by path) the user removed from the added games: a scan skips them, so they
|
||||||
* stay off the Games tab and out of Steam until restored. Nothing on disk is touched.
|
* stay off the Games tab and out of Steam until restored. Nothing on disk is touched.
|
||||||
@@ -877,74 +865,6 @@ object SessionPrefs {
|
|||||||
publishGameEnvironment(context)
|
publishGameEnvironment(context)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun gameTextureFiltering(context: Context, scope: String): GameTextureFiltering {
|
|
||||||
require(GameEnvironment.validScope(scope))
|
|
||||||
return gameTextureFiltering(context)[scope] ?: GameTextureFiltering()
|
|
||||||
}
|
|
||||||
|
|
||||||
fun gameTextureFiltering(context: Context): Map<String, GameTextureFiltering> {
|
|
||||||
val json = runCatching {
|
|
||||||
JSONObject(prefs(context).getString("gameTextureFiltering", null) ?: "{}")
|
|
||||||
}.getOrElse { JSONObject() }
|
|
||||||
return buildMap {
|
|
||||||
json.keys().forEach { scope ->
|
|
||||||
if (!GameEnvironment.validScope(scope)) return@forEach
|
|
||||||
val entry = json.optJSONObject(scope) ?: return@forEach
|
|
||||||
val anisotropy = entry.optInt("anisotropy").takeIf {
|
|
||||||
entry.has("anisotropy") && it in TextureFiltering.ANISOTROPY
|
|
||||||
}
|
|
||||||
val lodBias = entry.optString("lodBias").takeIf {
|
|
||||||
entry.has("lodBias") && it in TextureFiltering.LOD_BIAS
|
|
||||||
}
|
|
||||||
if (anisotropy != null || lodBias != null) {
|
|
||||||
put(scope, GameTextureFiltering(anisotropy, lodBias))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun setGameTextureAnisotropy(context: Context, scope: String, value: Int?) {
|
|
||||||
require(value == null || value in TextureFiltering.ANISOTROPY)
|
|
||||||
updateGameTextureFiltering(context, scope) { it.copy(anisotropy = value) }
|
|
||||||
}
|
|
||||||
|
|
||||||
fun setGameTextureLodBias(context: Context, scope: String, choice: String?) {
|
|
||||||
require(choice == null || choice in TextureFiltering.LOD_BIAS)
|
|
||||||
updateGameTextureFiltering(context, scope) { it.copy(lodBias = choice) }
|
|
||||||
}
|
|
||||||
|
|
||||||
fun clearGameTextureFiltering(context: Context, scope: String) {
|
|
||||||
require(GameEnvironment.validScope(scope))
|
|
||||||
val choices = gameTextureFiltering(context).toMutableMap()
|
|
||||||
if (choices.remove(scope) == null) return
|
|
||||||
saveGameTextureFiltering(context, choices)
|
|
||||||
publishGameEnvironment(context)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun updateGameTextureFiltering(
|
|
||||||
context: Context,
|
|
||||||
scope: String,
|
|
||||||
change: (GameTextureFiltering) -> GameTextureFiltering,
|
|
||||||
) {
|
|
||||||
require(GameEnvironment.validScope(scope))
|
|
||||||
val choices = gameTextureFiltering(context).toMutableMap()
|
|
||||||
val next = change(choices[scope] ?: GameTextureFiltering())
|
|
||||||
if (next.anisotropy == null && next.lodBias == null) choices.remove(scope) else choices[scope] = next
|
|
||||||
saveGameTextureFiltering(context, choices)
|
|
||||||
publishGameEnvironment(context)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun saveGameTextureFiltering(context: Context, choices: Map<String, GameTextureFiltering>) {
|
|
||||||
val json = JSONObject()
|
|
||||||
choices.forEach { (id, choice) ->
|
|
||||||
json.put(id, JSONObject().apply {
|
|
||||||
choice.anisotropy?.let { put("anisotropy", it) }
|
|
||||||
choice.lodBias?.let { put("lodBias", it) }
|
|
||||||
})
|
|
||||||
}
|
|
||||||
prefs(context).edit().putString("gameTextureFiltering", json.toString()).apply()
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Hands the change to the next game launch (GameEnvironmentStore); the running game keeps its own. */
|
/** Hands the change to the next game launch (GameEnvironmentStore); the running game keeps its own. */
|
||||||
private fun publishGameEnvironment(context: Context) {
|
private fun publishGameEnvironment(context: Context) {
|
||||||
runCatching { GameEnvironmentStore.publish(context) }
|
runCatching { GameEnvironmentStore.publish(context) }
|
||||||
@@ -963,26 +883,6 @@ object SessionPrefs {
|
|||||||
prefs(context).edit().putBoolean("pipAutoEnter", enabled).apply()
|
prefs(context).edit().putBoolean("pipAutoEnter", enabled).apply()
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A foldable's unfolded panel shows the game above the Deck controls (SessionDisplay.unfoldedGameHeight). */
|
|
||||||
fun unfoldedControls(context: Context): Boolean = prefs(context).getBoolean("unfoldedControls", false)
|
|
||||||
|
|
||||||
fun setUnfoldedControls(context: Context, enabled: Boolean) {
|
|
||||||
prefs(context).edit().putBoolean("unfoldedControls", enabled).apply()
|
|
||||||
}
|
|
||||||
|
|
||||||
const val SURFACE_STICK = "stick"
|
|
||||||
const val SURFACE_TRACKPAD = "trackpad"
|
|
||||||
|
|
||||||
/** The Deck controls' gamepad tab: what each side is - an analog stick or a Steam trackpad.
|
|
||||||
* Left a stick and right a trackpad until changed, as a Deck is mostly played. */
|
|
||||||
fun gamepadSurface(context: Context, right: Boolean): String =
|
|
||||||
prefs(context).getString(if (right) "gamepadRight" else "gamepadLeft", null)
|
|
||||||
?: if (right) SURFACE_TRACKPAD else SURFACE_STICK
|
|
||||||
|
|
||||||
fun setGamepadSurface(context: Context, right: Boolean, surface: String) {
|
|
||||||
prefs(context).edit().putString(if (right) "gamepadRight" else "gamepadLeft", surface).apply()
|
|
||||||
}
|
|
||||||
|
|
||||||
fun suspendPolicy(context: Context, mode: String): String =
|
fun suspendPolicy(context: Context, mode: String): String =
|
||||||
prefs(context).getString("suspendPolicy.${prefMode(mode)}", SUSPEND_MANUAL)
|
prefs(context).getString("suspendPolicy.${prefMode(mode)}", SUSPEND_MANUAL)
|
||||||
?.let { if (it == LEGACY_SUSPEND_DOWNLOADS) SUSPEND_AUTO else it }
|
?.let { if (it == LEGACY_SUSPEND_DOWNLOADS) SUSPEND_AUTO else it }
|
||||||
|
|||||||
@@ -37,12 +37,9 @@ import com.droiddeck.launcher.core.FileUtils
|
|||||||
import com.droiddeck.launcher.core.HostProcess
|
import com.droiddeck.launcher.core.HostProcess
|
||||||
import com.droiddeck.launcher.frontend.GameLaunchLink
|
import com.droiddeck.launcher.frontend.GameLaunchLink
|
||||||
import com.droiddeck.launcher.input.FakeInputWriter
|
import com.droiddeck.launcher.input.FakeInputWriter
|
||||||
import com.droiddeck.launcher.input.SteamControllerBle
|
|
||||||
import com.droiddeck.launcher.runtime.BwrapSpawner
|
|
||||||
import com.droiddeck.launcher.runtime.LinuxNetworkLinkComponent
|
import com.droiddeck.launcher.runtime.LinuxNetworkLinkComponent
|
||||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||||
import com.droiddeck.launcher.runtime.ProotFastPath
|
import com.droiddeck.launcher.runtime.ProotFastPath
|
||||||
import com.droiddeck.launcher.runtime.UserApps
|
|
||||||
import com.droiddeck.launcher.wayland.WaylandCompositor
|
import com.droiddeck.launcher.wayland.WaylandCompositor
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.text.SimpleDateFormat
|
import java.text.SimpleDateFormat
|
||||||
@@ -381,12 +378,7 @@ class SessionService : Service() {
|
|||||||
val controllersOn = !File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()
|
val controllersOn = !File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()
|
||||||
SessionState.deckPad = false
|
SessionState.deckPad = false
|
||||||
deckBinds = emptyList()
|
deckBinds = emptyList()
|
||||||
if (controllersOn) {
|
if (controllersOn) addControllerEnvironment(guest, fakeInputDir, sessionDir)
|
||||||
addControllerEnvironment(guest, fakeInputDir, sessionDir)
|
|
||||||
// Steam enumerates /dev/input while it starts. Make every attached controller's
|
|
||||||
// discovery node exist after the rings and guest environment are ready.
|
|
||||||
SessionState.padBridge?.syncConnectedControllers()
|
|
||||||
}
|
|
||||||
// The user's own games, for the runtime's shortcuts writer to put in the client's library
|
// The user's own games, for the runtime's shortcuts writer to put in the client's library
|
||||||
// before the client starts (see frontend/AddedGames and droiddeck-steam-shortcuts).
|
// before the client starts (see frontend/AddedGames and droiddeck-steam-shortcuts).
|
||||||
if (steamHere) {
|
if (steamHere) {
|
||||||
@@ -415,8 +407,6 @@ class SessionService : Service() {
|
|||||||
guest.add(it)
|
guest.add(it)
|
||||||
Log.i(TAG, "steam: handing the client $it")
|
Log.i(TAG, "steam: handing the client $it")
|
||||||
}
|
}
|
||||||
// A game whose download finishes in this session gets its Windows components readied in it.
|
|
||||||
if (SessionState.mode == MODE_STEAM) com.droiddeck.launcher.frontend.SessionInstalls.watch(this)
|
|
||||||
// A program under gamescope: the script's run mode takes the path (an AppImage, a script
|
// A program under gamescope: the script's run mode takes the path (an AppImage, a script
|
||||||
// or a binary inside the runtime). This is how an emulator gets the GPU - the desktop's
|
// or a binary inside the runtime). This is how an emulator gets the GPU - the desktop's
|
||||||
// KWin composites in software and offers no dma-buf, so a Vulkan swapchain cannot exist
|
// KWin composites in software and offers no dma-buf, so a Vulkan swapchain cannot exist
|
||||||
@@ -630,7 +620,8 @@ class SessionService : Service() {
|
|||||||
guest.add("ZINK_DEBUG=compact")
|
guest.add("ZINK_DEBUG=compact")
|
||||||
}
|
}
|
||||||
// The rest of the client-interface switches (SessionPrefs): GL marshalled off the calling
|
// The rest of the client-interface switches (SessionPrefs): GL marshalled off the calling
|
||||||
// thread and no GL error checks.
|
// thread, no GL error checks, and the client run as SteamOS runs it (the script reads
|
||||||
|
// BL_STEAMDECK; it is the one that builds the command line).
|
||||||
if (SessionPrefs.glThread(this)) guest.add("mesa_glthread=true")
|
if (SessionPrefs.glThread(this)) guest.add("mesa_glthread=true")
|
||||||
if (SessionPrefs.noGlError(this)) guest.add("MESA_NO_ERROR=1")
|
if (SessionPrefs.noGlError(this)) guest.add("MESA_NO_ERROR=1")
|
||||||
// Mesa's shader cache as one database instead of a file per entry. Every lookup in the
|
// Mesa's shader cache as one database instead of a file per entry. Every lookup in the
|
||||||
@@ -643,7 +634,9 @@ class SessionService : Service() {
|
|||||||
// every thread start paid a SIGSYS that proot answers; the malloc top pad grows the heap
|
// every thread start paid a SIGSYS that proot answers; the malloc top pad grows the heap
|
||||||
// 16 MB at a time instead of 128 KB, and every brk(2) is a proot stop too.
|
// 16 MB at a time instead of 128 KB, and every brk(2) is a proot stop too.
|
||||||
guest.add("GLIBC_TUNABLES=glibc.pthread.rseq=0:glibc.malloc.top_pad=16777216")
|
guest.add("GLIBC_TUNABLES=glibc.pthread.rseq=0:glibc.malloc.top_pad=16777216")
|
||||||
|
if (SessionState.mode == MODE_STEAM) guest.add("BL_STEAMDECK=" + (if (SessionPrefs.steamDeckMode(this)) "1" else "0"))
|
||||||
if (SessionState.mode == MODE_STEAM) guest.add("BL_MANGOAPP=" + (if (SessionPrefs.mangoapp(this)) "1" else "0"))
|
if (SessionState.mode == MODE_STEAM) guest.add("BL_MANGOAPP=" + (if (SessionPrefs.mangoapp(this)) "1" else "0"))
|
||||||
|
if (steamHere) guest.add("BL_STEAM_CHANNEL=" + SessionPrefs.steamChannel(this))
|
||||||
if (SessionState.mode == MODE_STEAM) {
|
if (SessionState.mode == MODE_STEAM) {
|
||||||
guest.add("BL_GAMESCOPE_STRETCH_16X9=" + (if (SessionPrefs.stretch16x9(this)) "1" else "0"))
|
guest.add("BL_GAMESCOPE_STRETCH_16X9=" + (if (SessionPrefs.stretch16x9(this)) "1" else "0"))
|
||||||
}
|
}
|
||||||
@@ -687,9 +680,7 @@ class SessionService : Service() {
|
|||||||
// changes what games do and leaves the client alone. The microphone is its own opt-in on
|
// changes what games do and leaves the client alone. The microphone is its own opt-in on
|
||||||
// top, and the helper only opens an input stream when asked - so a user who wants game
|
// top, and the helper only opens an input stream when asked - so a user who wants game
|
||||||
// sound but no recording gets exactly that, and Android's recording indicator stays off.
|
// sound but no recording gets exactly that, and Android's recording indicator stays off.
|
||||||
// The desktop starts Windows programs through the same Proton wrappers (droiddeck-proton-run).
|
val wantsDirectAudio = SessionState.mode == MODE_STEAM && SessionPrefs.directAudio(this)
|
||||||
val wantsDirectAudio = (SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP) &&
|
|
||||||
SessionPrefs.directAudio(this)
|
|
||||||
val wantsMic = SessionPrefs.micEnabled(this) &&
|
val wantsMic = SessionPrefs.micEnabled(this) &&
|
||||||
checkSelfPermission(android.Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
|
checkSelfPermission(android.Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
|
||||||
// Both paths sit under the app's files directory, which the session binds at its own path,
|
// Both paths sit under the app's files directory, which the session binds at its own path,
|
||||||
@@ -747,18 +738,13 @@ class SessionService : Service() {
|
|||||||
// hidraw (SteamDeckPad), which only works with Steam Input's virtual pad for games to read.
|
// hidraw (SteamDeckPad), which only works with Steam Input's virtual pad for games to read.
|
||||||
// Decided only once its sysfs is in place: without it the client would find no Deck, and
|
// Decided only once its sysfs is in place: without it the client would find no Deck, and
|
||||||
// with the Deck asked for the pad's own nodes are withdrawn - no controller at all.
|
// with the Deck asked for the pad's own nodes are withdrawn - no controller at all.
|
||||||
// Set up whatever the pad is to be, so the drawer can switch it between a Deck, a Steam
|
|
||||||
// Controller and an Xbox 360 pad while the session runs (FakeInputWriter.setPadType).
|
|
||||||
val wantsDeck = uinput && SessionState.mode == MODE_STEAM &&
|
val wantsDeck = uinput && SessionState.mode == MODE_STEAM &&
|
||||||
SessionState.steamUi != "desktop" &&
|
SessionState.steamUi != "desktop" &&
|
||||||
|
SessionPrefs.steamController(this) == SessionPrefs.CONTROLLER_DECK &&
|
||||||
!File(Environment.getExternalStorageDirectory(), NO_DECK_PAD_SWITCH).exists()
|
!File(Environment.getExternalStorageDirectory(), NO_DECK_PAD_SWITCH).exists()
|
||||||
// Steam's touch controller rides on the Deck's sysfs and is offered only beside it.
|
// Steam's touch controller rides on the Deck's sysfs and is offered only beside it.
|
||||||
val wantsTouch = wantsDeck && !File(Environment.getExternalStorageDirectory(), NO_STEAM_TOUCH_SWITCH).exists()
|
val wantsTouch = wantsDeck && !File(Environment.getExternalStorageDirectory(), NO_STEAM_TOUCH_SWITCH).exists()
|
||||||
// A paired Triton is exposed as a second native Steam Controller HID, with its original
|
deckBinds = if (wantsDeck) SteamDeckPad.prepare(this, fakeInputDir.parentFile!!.parentFile!!, wantsTouch) else emptyList()
|
||||||
// report IDs and output path, beside whatever the handheld's own pad is.
|
|
||||||
val wantsTriton = wantsDeck && SteamControllerBle.hasPairedController(this)
|
|
||||||
deckBinds = if (wantsDeck) SteamDeckPad.prepare(this, fakeInputDir.parentFile!!.parentFile!!, wantsTouch, wantsTriton,
|
|
||||||
SessionPrefs.padType(SessionPrefs.steamController(this))) else emptyList()
|
|
||||||
SessionState.deckPad = deckBinds.isNotEmpty()
|
SessionState.deckPad = deckBinds.isNotEmpty()
|
||||||
if (wantsDeck && !SessionState.deckPad) Log.w(TAG, "deck pad: not available this session; the pad stays an Xbox 360 controller")
|
if (wantsDeck && !SessionState.deckPad) Log.w(TAG, "deck pad: not available this session; the pad stays an Xbox 360 controller")
|
||||||
logControllersAtStart()
|
logControllersAtStart()
|
||||||
@@ -768,11 +754,6 @@ class SessionService : Service() {
|
|||||||
guest.add("FAKE_EVDEV_UINPUT=1")
|
guest.add("FAKE_EVDEV_UINPUT=1")
|
||||||
if (SessionState.deckPad) {
|
if (SessionState.deckPad) {
|
||||||
guest.add("FAKE_EVDEV_DECK=1")
|
guest.add("FAKE_EVDEV_DECK=1")
|
||||||
if (wantsTriton) guest.add("FAKE_EVDEV_TRITON=1")
|
|
||||||
// What the pad starts as; the drawer's changes reach libfakeinput through the ring.
|
|
||||||
val padType = SessionPrefs.steamController(this)
|
|
||||||
guest.add("FAKE_EVDEV_PAD_TYPE=$padType")
|
|
||||||
com.droiddeck.launcher.input.FakeInputWriter.setPadType(SessionPrefs.padType(padType))
|
|
||||||
// Steam's touch controller (SteamTouchDevice): the file the app and libfakeinput share.
|
// Steam's touch controller (SteamTouchDevice): the file the app and libfakeinput share.
|
||||||
if (wantsTouch) com.droiddeck.launcher.input.SteamTouchDevice.prepare(fakeInputDir)?.let {
|
if (wantsTouch) com.droiddeck.launcher.input.SteamTouchDevice.prepare(fakeInputDir)?.let {
|
||||||
guest.add("FAKE_TOUCHCTL_RING=" + it.path)
|
guest.add("FAKE_TOUCHCTL_RING=" + it.path)
|
||||||
@@ -1233,13 +1214,6 @@ class SessionService : Service() {
|
|||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (path != null && path.startsWith("desktop-import-") && path.endsWith(".request")) {
|
|
||||||
val request = File(dir, path)
|
|
||||||
val text = runCatching { request.readText() }.getOrNull() ?: return
|
|
||||||
request.delete()
|
|
||||||
importForDesktop(dir, text)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (path != "steam-launch") return
|
if (path != "steam-launch") return
|
||||||
val file = File(dir, path)
|
val file = File(dir, path)
|
||||||
val text = try { file.readText() } catch (e: Exception) { return }
|
val text = try { file.readText() } catch (e: Exception) { return }
|
||||||
@@ -1269,48 +1243,6 @@ class SessionService : Service() {
|
|||||||
launchWatcher = watcher
|
launchWatcher = watcher
|
||||||
}
|
}
|
||||||
|
|
||||||
private val desktopImports = java.util.concurrent.ConcurrentHashMap<String, Any>()
|
|
||||||
|
|
||||||
/**
|
|
||||||
* What the desktop cannot run where it lies (droiddeck-open), added as Add an app adds it, menu entry
|
|
||||||
* included: an AppImage of sharun's, whose hard links Android denies apps and only the app's own proot
|
|
||||||
* (link2symlink) makes, or a script or program whose folder of Linux programs is on noexec shared
|
|
||||||
* storage, copied in. The answer goes beside the request, "ok <folder>" or "error <why>".
|
|
||||||
*/
|
|
||||||
private fun importForDesktop(dir: File, text: String) {
|
|
||||||
val fields = text.lineSequence().mapNotNull { line ->
|
|
||||||
line.split('=', limit = 2).takeIf { it.size == 2 }?.let { it[0] to it[1].trim() }
|
|
||||||
}.toMap()
|
|
||||||
val key = fields["id"]?.takeIf { it.matches(Regex("[0-9a-f]{16}")) } ?: return
|
|
||||||
val guestPath = fields["path"]?.takeIf { it.startsWith("/") && !it.contains("/../") } ?: return
|
|
||||||
val folder = fields["kind"] == "folder"
|
|
||||||
val binds = LinuxRuntime.lastBinds(this).map { BwrapSpawner.Bind.parse(it) }
|
|
||||||
val file = File(BwrapSpawner.hostPath(binds, LinuxRuntime.rootDir(this).path, guestPath))
|
|
||||||
val context = applicationContext
|
|
||||||
// A request for what is already being added waits for that, then finds it.
|
|
||||||
val lock = desktopImports.computeIfAbsent(key) { Any() }
|
|
||||||
Thread({
|
|
||||||
fun imported() = UserApps.desktopImport(context, key, guestPath)?.let { "ok $it" }
|
|
||||||
val request = UserApps.Request(
|
|
||||||
if (folder) UserApps.Source.Script(file) else UserApps.Source.AppImage(file),
|
|
||||||
if (folder) file.parentFile?.name else null, null, mapOf(UserApps.DESKTOP_IMPORT to "$key\n$guestPath"),
|
|
||||||
)
|
|
||||||
val answer = synchronized(lock) {
|
|
||||||
try {
|
|
||||||
imported() ?: UserApps.add(context, request) { _, _ -> }?.let { "error $it" }
|
|
||||||
?: imported() ?: "error " + context.getString(R.string.user_apps_failed)
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Log.e(TAG, "Desktop import of $guestPath", e)
|
|
||||||
"error " + (e.message ?: context.getString(R.string.user_apps_failed))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Log.i(TAG, "Desktop import of $guestPath: $answer")
|
|
||||||
val result = File(dir, "desktop-import-$key.result")
|
|
||||||
val partial = File(dir, result.name + ".tmp")
|
|
||||||
runCatching { partial.writeText(answer.replace('\n', ' ') + "\n"); partial.renameTo(result) }
|
|
||||||
}, "desktop-import").start()
|
|
||||||
}
|
|
||||||
|
|
||||||
@Volatile private var syncWatcher: android.os.FileObserver? = null
|
@Volatile private var syncWatcher: android.os.FileObserver? = null
|
||||||
|
|
||||||
private fun watchSyncWanted(root: File) {
|
private fun watchSyncWanted(root: File) {
|
||||||
@@ -1787,7 +1719,7 @@ class SessionService : Service() {
|
|||||||
pads.add(String.format(java.util.Locale.ROOT, "\"%s\" (%04x:%04x)", d.name, d.vendorId, d.productId))
|
pads.add(String.format(java.util.Locale.ROOT, "\"%s\" (%04x:%04x)", d.name, d.vendorId, d.productId))
|
||||||
}
|
}
|
||||||
Log.i(TAG, "controllers at start: " + (if (pads.isEmpty()) "none" else pads.joinToString(", ")) +
|
Log.i(TAG, "controllers at start: " + (if (pads.isEmpty()) "none" else pads.joinToString(", ")) +
|
||||||
"; presented to the guest as " + if (SessionState.deckPad) "switchable, starting as " + SessionPrefs.steamController(this) else "an Xbox 360 controller")
|
"; presented to the guest as " + if (SessionState.deckPad) "a Steam Deck controller" else "an Xbox 360 controller")
|
||||||
}
|
}
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
|
|||||||
@@ -44,36 +44,6 @@ object SteamDeckPad {
|
|||||||
private const val HIDRAW = "$HID/hidraw/$NODE"
|
private const val HIDRAW = "$HID/hidraw/$NODE"
|
||||||
private const val SERIAL = "DROIDDECK0001"
|
private const val SERIAL = "DROIDDECK0001"
|
||||||
|
|
||||||
// The paired Bluetooth Steam Controller is a separate Triton HID device. It must not inherit
|
|
||||||
// the Deck's identity or report format. Must match fakeinput_steam.cpp (TRITON_HIDRAW_*).
|
|
||||||
private const val TRITON_MINOR = 18
|
|
||||||
private const val TRITON_HID = "$GUEST_DEVICES/bluetooth/0005:28DE:1303.0003"
|
|
||||||
private const val TRITON_SERIAL = "DROIDDECKSC01"
|
|
||||||
// The handheld's own pad as the Steam Controller (SessionPrefs.CONTROLLER_STEAM): the wired
|
|
||||||
// controller (28de:1302) on a USB device of its own, since it is built in.
|
|
||||||
private const val TRITON_USB = "$GUEST_DEVICES/usb3"
|
|
||||||
private const val TRITON_INTERFACE = "$TRITON_USB/3-1:1.0"
|
|
||||||
private const val TRITON_WIRED_HID = "$TRITON_INTERFACE/0003:28DE:1302.0004"
|
|
||||||
/** Must match libfakeinput (DS4_HIDRAW_MINOR, DUALSENSE_HIDRAW_MINOR). */
|
|
||||||
private const val SONY_DS4_MINOR = 20
|
|
||||||
private const val SONY_DUALSENSE_MINOR = 21
|
|
||||||
/** Must match libfakeinput's kDs4ReportDescriptor and kDualSenseReportDescriptor. */
|
|
||||||
private val DS4_REPORT_DESCRIPTOR = intArrayOf(
|
|
||||||
0x05, 0x01, 0x09, 0x05, 0xa1, 0x01, 0x06, 0x00, 0xff, 0x15, 0x00, 0x26, 0xff, 0x00, 0x75, 0x08,
|
|
||||||
0x85, 0x01, 0x09, 0x20, 0x95, 0x3f, 0x81, 0x02, 0x85, 0x05, 0x09, 0x21, 0x95, 0x1f, 0x91, 0x02,
|
|
||||||
0x85, 0x02, 0x09, 0x24, 0x95, 0x24, 0xb1, 0x02, 0x85, 0x12, 0x09, 0x25, 0x95, 0x0f, 0xb1, 0x02,
|
|
||||||
0x85, 0xa3, 0x09, 0x26, 0x95, 0x30, 0xb1, 0x02, 0x85, 0x81, 0x09, 0x27, 0x95, 0x3f, 0xb1, 0x02,
|
|
||||||
0xc0,
|
|
||||||
).map { it.toByte() }.toByteArray()
|
|
||||||
private val DUALSENSE_REPORT_DESCRIPTOR = intArrayOf(
|
|
||||||
0x05, 0x01, 0x09, 0x05, 0xa1, 0x01, 0x06, 0x00, 0xff, 0x15, 0x00, 0x26, 0xff, 0x00, 0x75, 0x08,
|
|
||||||
0x85, 0x01, 0x09, 0x20, 0x95, 0x3f, 0x81, 0x02, 0x85, 0x02, 0x09, 0x21, 0x95, 0x2f, 0x91, 0x02,
|
|
||||||
0x85, 0x05, 0x09, 0x22, 0x95, 0x28, 0xb1, 0x02, 0x85, 0x09, 0x09, 0x23, 0x95, 0x13, 0xb1, 0x02,
|
|
||||||
0x85, 0x20, 0x09, 0x24, 0x95, 0x3f, 0xb1, 0x02, 0xc0,
|
|
||||||
).map { it.toByte() }.toByteArray()
|
|
||||||
/** Must match libfakeinput (TRITON_PAD_HIDRAW_*): its own node, so a paired controller keeps 18. */
|
|
||||||
private const val TRITON_PAD_MINOR = 19
|
|
||||||
|
|
||||||
// Steam's touch controller (SteamTouchDevice), a second device beside the Deck's: 0000:11fb,
|
// Steam's touch controller (SteamTouchDevice), a second device beside the Deck's: 0000:11fb,
|
||||||
// "Mobile Touch Control", on a USB device of its own. Must match libfakeinput (TOUCH_*).
|
// "Mobile Touch Control", on a USB device of its own. Must match libfakeinput (TOUCH_*).
|
||||||
private const val TOUCH_MINOR = 17
|
private const val TOUCH_MINOR = 17
|
||||||
@@ -99,65 +69,11 @@ object SteamDeckPad {
|
|||||||
0x15, 0x00, 0x26, 0xff, 0x00, 0x75, 0x08, 0x95, 0x40, 0xb1, 0x02, 0xc0,
|
0x15, 0x00, 0x26, 0xff, 0x00, 0x75, 0x08, 0x95, 0x40, 0xb1, 0x02, 0xc0,
|
||||||
).map { it.toByte() }.toByteArray()
|
).map { it.toByte() }.toByteArray()
|
||||||
|
|
||||||
/** Triton's native 0x45/0x47 input and 0x80-0x85 haptic output report IDs. */
|
|
||||||
private val TRITON_REPORT_DESCRIPTOR = intArrayOf(
|
|
||||||
0x06, 0x00, 0xff, 0x09, 0x01, 0xa1, 0x01,
|
|
||||||
0x15, 0x00, 0x26, 0xff, 0x00, 0x75, 0x08,
|
|
||||||
0x85, 0x45, 0x09, 0x02, 0x95, 0x2d, 0x81, 0x02,
|
|
||||||
0x85, 0x47, 0x09, 0x03, 0x95, 0x2d, 0x81, 0x02,
|
|
||||||
0x85, 0x80, 0x09, 0x04, 0x95, 0x09, 0x91, 0x02,
|
|
||||||
0x85, 0x81, 0x09, 0x05, 0x95, 0x07, 0x91, 0x02,
|
|
||||||
0x85, 0x82, 0x09, 0x06, 0x95, 0x03, 0x91, 0x02,
|
|
||||||
0x85, 0x83, 0x09, 0x07, 0x95, 0x09, 0x91, 0x02,
|
|
||||||
0x85, 0x84, 0x09, 0x08, 0x95, 0x08, 0x91, 0x02,
|
|
||||||
0x85, 0x85, 0x09, 0x09, 0x95, 0x03, 0x91, 0x02,
|
|
||||||
0x85, 0x01, 0x09, 0x0a, 0x95, 0x3f, 0xb1, 0x02,
|
|
||||||
0xc0,
|
|
||||||
).map { it.toByte() }.toByteArray()
|
|
||||||
|
|
||||||
/** The wired controller's: its 0x42 state report in place of the Bluetooth 0x45. */
|
|
||||||
private val TRITON_WIRED_REPORT_DESCRIPTOR = TRITON_REPORT_DESCRIPTOR.copyOf().also { it[15] = 0x42 }
|
|
||||||
|
|
||||||
/** Where [prepare] puts the stand-in listings; bound into the guest at the same path. */
|
/** Where [prepare] puts the stand-in listings; bound into the guest at the same path. */
|
||||||
fun listingDir(sessionRoot: File) = File(sessionRoot, "sys/deck/listing")
|
fun listingDir(sessionRoot: File) = File(sessionRoot, "sys/deck/listing")
|
||||||
|
|
||||||
/** Writes the tree and returns the `host:guest` binds for it, or none if it could not be made. */
|
/** Writes the tree and returns the `host:guest` binds for it, or none if it could not be made. */
|
||||||
/** The pad's own devices by minor (the Deck, its Steam Controller, the PlayStation pads): guest paths. */
|
fun prepare(context: Context, sessionRoot: File, touch: Boolean = false): List<String> {
|
||||||
private val padNodes = mutableMapOf<Int, String>()
|
|
||||||
@Volatile private var hidrawClassDir: File? = null
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Lists only the device the pad is now ([padType], FakeInputWriter.PAD_TYPE_*) in
|
|
||||||
* /sys/class/hidraw, none for an Xbox 360 pad. Device scans then find what is plugged in: SDL's
|
|
||||||
* (the PlayStation pads' driver) keeps a device it found and could not open, and never tries it
|
|
||||||
* again, while one that disappears from the listing is let go. Before the shim is told.
|
|
||||||
*/
|
|
||||||
@Synchronized
|
|
||||||
fun showPad(padType: Int) {
|
|
||||||
val dir = hidrawClassDir ?: return
|
|
||||||
val shown = when (padType) {
|
|
||||||
com.droiddeck.launcher.input.FakeInputWriter.PAD_TYPE_DECK -> MINOR
|
|
||||||
com.droiddeck.launcher.input.FakeInputWriter.PAD_TYPE_STEAM -> TRITON_PAD_MINOR
|
|
||||||
com.droiddeck.launcher.input.FakeInputWriter.PAD_TYPE_DS4 -> SONY_DS4_MINOR
|
|
||||||
com.droiddeck.launcher.input.FakeInputWriter.PAD_TYPE_DUALSENSE -> SONY_DUALSENSE_MINOR
|
|
||||||
else -> -1
|
|
||||||
}
|
|
||||||
for ((minor, target) in padNodes) {
|
|
||||||
val link = File(dir, "hidraw$minor")
|
|
||||||
try {
|
|
||||||
if (minor == shown) {
|
|
||||||
if (!link.exists()) { link.delete(); Os.symlink(target, link.path) }
|
|
||||||
} else {
|
|
||||||
link.delete()
|
|
||||||
}
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Log.w(TAG, "pad: could not list /dev/hidraw$minor: $e")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun prepare(context: Context, sessionRoot: File, touch: Boolean = false, triton: Boolean = false,
|
|
||||||
padType: Int = com.droiddeck.launcher.input.FakeInputWriter.PAD_TYPE_DECK): List<String> {
|
|
||||||
val base = File(sessionRoot, "sys/deck")
|
val base = File(sessionRoot, "sys/deck")
|
||||||
val devices = File(base, "devices")
|
val devices = File(base, "devices")
|
||||||
val hidrawClass = File(base, "class-hidraw")
|
val hidrawClass = File(base, "class-hidraw")
|
||||||
@@ -197,8 +113,7 @@ object SteamDeckPad {
|
|||||||
link(File(dir(HIDRAW), "device"), HID)
|
link(File(dir(HIDRAW), "device"), HID)
|
||||||
|
|
||||||
hidrawClass.mkdirs()
|
hidrawClass.mkdirs()
|
||||||
padNodes.clear()
|
link(File(hidrawClass, NODE), HIDRAW)
|
||||||
padNodes[MINOR] = HIDRAW
|
|
||||||
|
|
||||||
// Only the names matter: libudev reads a listing for the subsystems to descend into and
|
// Only the names matter: libudev reads a listing for the subsystems to descend into and
|
||||||
// then opens /sys/class/hidraw itself, which is the bind above.
|
// then opens /sys/class/hidraw itself, which is the bind above.
|
||||||
@@ -238,88 +153,6 @@ object SteamDeckPad {
|
|||||||
Log.i(TAG, "deck pad: /dev/$TOUCH_NODE described as Steam's touch controller (0000:11fb)")
|
Log.i(TAG, "deck pad: /dev/$TOUCH_NODE described as Steam's touch controller (0000:11fb)")
|
||||||
}
|
}
|
||||||
|
|
||||||
// A Steam Controller's HID device: the handheld's own pad as the wired one, or the paired
|
|
||||||
// one on Bluetooth. Both are always described; libfakeinput offers whichever is in use.
|
|
||||||
fun describeTriton(wired: Boolean) {
|
|
||||||
val hid = if (wired) TRITON_WIRED_HID else TRITON_HID
|
|
||||||
val product = if (wired) "1302" else "1303"
|
|
||||||
val bus = if (wired) "0003" else "0005"
|
|
||||||
val minor = if (wired) TRITON_PAD_MINOR else TRITON_MINOR
|
|
||||||
val node = "hidraw$minor"
|
|
||||||
if (wired) {
|
|
||||||
write(TRITON_USB, "uevent", "DEVTYPE=usb_device\nPRODUCT=28de/1302/100\nTYPE=0/0/0\nBUSNUM=003\nDEVNUM=002\n")
|
|
||||||
write(TRITON_USB, "idVendor", "28de\n")
|
|
||||||
write(TRITON_USB, "idProduct", "1302\n")
|
|
||||||
write(TRITON_USB, "bcdDevice", "0100\n")
|
|
||||||
write(TRITON_USB, "manufacturer", "Valve Software\n")
|
|
||||||
write(TRITON_USB, "product", "Steam Controller\n")
|
|
||||||
write(TRITON_USB, "serial", "$TRITON_SERIAL\n")
|
|
||||||
link(File(dir(TRITON_USB), "subsystem"), "/sys/bus/usb")
|
|
||||||
write(TRITON_INTERFACE, "uevent", "DEVTYPE=usb_interface\nPRODUCT=28de/1302/100\nINTERFACE=3/0/0\n")
|
|
||||||
write(TRITON_INTERFACE, "bInterfaceNumber", "00\n")
|
|
||||||
write(TRITON_INTERFACE, "bInterfaceClass", "03\n")
|
|
||||||
link(File(dir(TRITON_INTERFACE), "subsystem"), "/sys/bus/usb")
|
|
||||||
}
|
|
||||||
write(hid, "uevent", "DRIVER=hid-generic\nHID_ID=$bus:000028DE:0000$product\n" +
|
|
||||||
"HID_NAME=Valve Software Steam Controller\n" +
|
|
||||||
"HID_PHYS=${if (wired) "usb-droiddeck-3/input0" else "bluetooth-droiddeck-1"}\n" +
|
|
||||||
"HID_UNIQ=$TRITON_SERIAL\nMODALIAS=hid:b${bus}g0001v000028DEp0000$product\n")
|
|
||||||
File(dir(hid), "report_descriptor").writeBytes(if (wired) TRITON_WIRED_REPORT_DESCRIPTOR else TRITON_REPORT_DESCRIPTOR)
|
|
||||||
link(File(dir(hid), "subsystem"), "/sys/bus/hid")
|
|
||||||
val hidraw = "$hid/hidraw/$node"
|
|
||||||
write(hidraw, "uevent", "MAJOR=$MAJOR\nMINOR=$minor\nDEVNAME=$node\n")
|
|
||||||
write(hidraw, "dev", "$MAJOR:$minor\n")
|
|
||||||
link(File(dir(hidraw), "subsystem"), "/sys/class/hidraw")
|
|
||||||
link(File(dir(hidraw), "device"), hid)
|
|
||||||
if (wired) padNodes[minor] = hidraw else link(File(hidrawClass, node), hidraw)
|
|
||||||
link(File(context.cacheDir, "drm/sys/$MAJOR:$minor"), hidraw)
|
|
||||||
File(udevData, "c$MAJOR:$minor").writeText("I:1\nE:ID_INPUT=1\nE:ID_INPUT_JOYSTICK=1\n")
|
|
||||||
Log.i(TAG, "steam controller: /dev/$node described as Triton (28de:$product)")
|
|
||||||
}
|
|
||||||
// The handheld's own pad as a PlayStation controller, each a USB device of its own with
|
|
||||||
// the report descriptor libfakeinput serves (kDs4/kDualSenseReportDescriptor).
|
|
||||||
fun describeSony(dualSense: Boolean) {
|
|
||||||
val bus = if (dualSense) 5 else 4
|
|
||||||
val product = if (dualSense) "0ce6" else "09cc"
|
|
||||||
val minor = if (dualSense) SONY_DUALSENSE_MINOR else SONY_DS4_MINOR
|
|
||||||
val node = "hidraw$minor"
|
|
||||||
val name = if (dualSense) "DualSense Wireless Controller" else "Wireless Controller"
|
|
||||||
val usb = "$GUEST_DEVICES/usb$bus"
|
|
||||||
val iface = "$usb/$bus-1:1.3"
|
|
||||||
val hid = "$iface/0003:054C:${product.uppercase()}.000${bus + 1}"
|
|
||||||
write(usb, "uevent", "DEVTYPE=usb_device\nPRODUCT=54c/$product/100\nTYPE=0/0/0\nBUSNUM=00$bus\nDEVNUM=002\n")
|
|
||||||
write(usb, "idVendor", "054c\n")
|
|
||||||
write(usb, "idProduct", "$product\n")
|
|
||||||
write(usb, "bcdDevice", "0100\n")
|
|
||||||
write(usb, "manufacturer", "Sony Interactive Entertainment\n")
|
|
||||||
write(usb, "product", "$name\n")
|
|
||||||
link(File(dir(usb), "subsystem"), "/sys/bus/usb")
|
|
||||||
write(iface, "uevent", "DEVTYPE=usb_interface\nPRODUCT=54c/$product/100\nINTERFACE=3/0/0\n")
|
|
||||||
write(iface, "bInterfaceNumber", "03\n")
|
|
||||||
write(iface, "bInterfaceClass", "03\n")
|
|
||||||
link(File(dir(iface), "subsystem"), "/sys/bus/usb")
|
|
||||||
write(hid, "uevent", "DRIVER=hid-generic\nHID_ID=0003:0000054C:0000${product.uppercase()}\n" +
|
|
||||||
"HID_NAME=Sony Interactive Entertainment $name\nHID_PHYS=usb-droiddeck-$bus/input3\n" +
|
|
||||||
"HID_UNIQ=5e:43:4b:44:44:02\nMODALIAS=hid:b0003g0001v0000054Cp0000${product.uppercase()}\n")
|
|
||||||
File(dir(hid), "report_descriptor").writeBytes(if (dualSense) DUALSENSE_REPORT_DESCRIPTOR else DS4_REPORT_DESCRIPTOR)
|
|
||||||
link(File(dir(hid), "subsystem"), "/sys/bus/hid")
|
|
||||||
val hidraw = "$hid/hidraw/$node"
|
|
||||||
write(hidraw, "uevent", "MAJOR=$MAJOR\nMINOR=$minor\nDEVNAME=$node\n")
|
|
||||||
write(hidraw, "dev", "$MAJOR:$minor\n")
|
|
||||||
link(File(dir(hidraw), "subsystem"), "/sys/class/hidraw")
|
|
||||||
link(File(dir(hidraw), "device"), hid)
|
|
||||||
padNodes[minor] = hidraw
|
|
||||||
link(File(context.cacheDir, "drm/sys/$MAJOR:$minor"), hidraw)
|
|
||||||
File(udevData, "c$MAJOR:$minor").writeText("I:1\nE:ID_INPUT=1\nE:ID_INPUT_JOYSTICK=1\n")
|
|
||||||
Log.i(TAG, "playstation pad: /dev/$node described as 054c:$product")
|
|
||||||
}
|
|
||||||
describeSony(dualSense = false)
|
|
||||||
describeSony(dualSense = true)
|
|
||||||
describeTriton(wired = true)
|
|
||||||
if (triton) describeTriton(wired = false)
|
|
||||||
hidrawClassDir = hidrawClass
|
|
||||||
showPad(padType)
|
|
||||||
|
|
||||||
Log.i(TAG, "deck pad: /dev/$NODE described as a Steam Deck controller (28de:1205)")
|
Log.i(TAG, "deck pad: /dev/$NODE described as a Steam Deck controller (28de:1205)")
|
||||||
listOf(devices.path + ":" + GUEST_DEVICES, hidrawClass.path + ":/sys/class/hidraw")
|
listOf(devices.path + ":" + GUEST_DEVICES, hidrawClass.path + ":/sys/class/hidraw")
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ import java.util.zip.ZipInputStream
|
|||||||
*/
|
*/
|
||||||
object WinComponents {
|
object WinComponents {
|
||||||
private const val TAG = "WinComponents"
|
private const val TAG = "WinComponents"
|
||||||
const val CATALOG_URL = "https://raw.githubusercontent.com/Droid-Deck/DroidDeck-Components/main/components.json"
|
const val CATALOG_URL = "https://raw.githubusercontent.com/The412Banner/winlator-contents/main/components.json"
|
||||||
private const val SELECTION = "wincomponents.json"
|
private const val SELECTION = "wincomponents.json"
|
||||||
private const val GUEST_SELECTION = "root/.config/droiddeck/wincomponents.json"
|
private const val GUEST_SELECTION = "root/.config/droiddeck/wincomponents.json"
|
||||||
private const val STORE = "opt/droiddeck/wincomponents"
|
private const val STORE = "opt/droiddeck/wincomponents"
|
||||||
@@ -77,21 +77,6 @@ object WinComponents {
|
|||||||
|
|
||||||
fun validId(id: String): Boolean = ID.matches(id) && ".." !in id
|
fun validId(id: String): Boolean = ID.matches(id) && ".." !in id
|
||||||
|
|
||||||
private val BACKGROUND = ThreadLocal<Boolean>()
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Runs [block] as background work: the runtime helpers an install starts on this thread run
|
|
||||||
* at the lowest CPU and I/O priority (nice 19, ionice idle where the runtime has it).
|
|
||||||
*/
|
|
||||||
fun <T> background(block: () -> T): T {
|
|
||||||
BACKGROUND.set(true)
|
|
||||||
try { return block() } finally { BACKGROUND.remove() }
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun guest(argv: List<String>): List<String> = if (BACKGROUND.get() != true) argv else listOf(
|
|
||||||
"/bin/sh", "-c", "if command -v ionice >/dev/null 2>&1; then exec nice -n 19 ionice -c3 \"\$@\"; else exec nice -n 19 \"\$@\"; fi", "sh",
|
|
||||||
) + argv
|
|
||||||
|
|
||||||
class Step(val action: String, val json: JSONObject) {
|
class Step(val action: String, val json: JSONObject) {
|
||||||
fun str(key: String): String = json.optString(key, "").ifEmpty {
|
fun str(key: String): String = json.optString(key, "").ifEmpty {
|
||||||
if (key in NESTED_KEYS) json.optJSONObject("environment")?.optString(key, "").orEmpty() else ""
|
if (key in NESTED_KEYS) json.optJSONObject("environment")?.optString(key, "").orEmpty() else ""
|
||||||
@@ -133,13 +118,8 @@ object WinComponents {
|
|||||||
(step.action == "install_msi" || listOf(step.str("file_name"), step.str("url").substringBefore('?'))
|
(step.action == "install_msi" || listOf(step.str("file_name"), step.str("url").substringBefore('?'))
|
||||||
.any { it.endsWith(".msi", ignoreCase = true) || it.endsWith(".exe", ignoreCase = true) })
|
.any { it.endsWith(".msi", ignoreCase = true) || it.endsWith(".exe", ignoreCase = true) })
|
||||||
|
|
||||||
/**
|
/** Catalog entries nothing here can use: the IE8 security update patches a browser no prefix has. */
|
||||||
* Catalog entries nothing here can use: the IE8 security update patches a browser no prefix
|
private val POINTLESS = setOf("ie8_kb2936068")
|
||||||
* has; the OpenAL setup program is a twin of oalinst_dll, which copies the same DLLs; and
|
|
||||||
* WebView2 can only be installed by running Microsoft's installer in the prefix (its files
|
|
||||||
* sit in a container nothing opens and may not be hosted), which no runtime here does.
|
|
||||||
*/
|
|
||||||
private val POINTLESS = setOf("ie8_kb2936068", "oalinst", "webview2")
|
|
||||||
|
|
||||||
private fun protonProvides(name: String): Boolean = name in PROTON_PROVIDES || name in POINTLESS || name.startsWith("mono-")
|
private fun protonProvides(name: String): Boolean = name in PROTON_PROVIDES || name in POINTLESS || name.startsWith("mono-")
|
||||||
|
|
||||||
@@ -148,24 +128,8 @@ object WinComponents {
|
|||||||
/** The steps a recording makes redundant: everything that places files or edits the registry. */
|
/** The steps a recording makes redundant: everything that places files or edits the registry. */
|
||||||
private val SNAPSHOT_COVERS = INSTALLER_STEPS + setOf("download_archive", "archive_extract", "copy_dll", "copy_file") + OFFLINE_STEPS
|
private val SNAPSHOT_COVERS = INSTALLER_STEPS + setOf("download_archive", "archive_extract", "copy_dll", "copy_file") + OFFLINE_STEPS
|
||||||
|
|
||||||
fun fetch(): List<Component>? = Downloader.downloadString(CATALOG_URL)?.let { parse(it) }
|
fun fetch(): List<Component>? {
|
||||||
|
val body = Downloader.downloadString(CATALOG_URL) ?: return null
|
||||||
private const val CATALOG_CACHE = "wincomponents-catalog.json"
|
|
||||||
|
|
||||||
/** The catalog from the network, kept for later; the copy kept last time when offline. */
|
|
||||||
fun fetch(context: Context): List<Component>? {
|
|
||||||
val cache = File(context.filesDir, CATALOG_CACHE)
|
|
||||||
Downloader.downloadString(CATALOG_URL)?.let { body ->
|
|
||||||
parse(body)?.let { runCatching { write(cache, body) }; return it }
|
|
||||||
}
|
|
||||||
return runCatching { parse(cache.readText()) }.getOrNull()
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The copy of the catalog kept by [fetch], without asking the network; null before the first fetch. */
|
|
||||||
fun cached(context: Context): List<Component>? =
|
|
||||||
runCatching { parse(File(context.filesDir, CATALOG_CACHE).readText()) }.getOrNull()
|
|
||||||
|
|
||||||
private fun parse(body: String): List<Component>? {
|
|
||||||
return try {
|
return try {
|
||||||
val arr = JSONObject(body).getJSONArray("components")
|
val arr = JSONObject(body).getJSONArray("components")
|
||||||
(0 until arr.length()).mapNotNull { i ->
|
(0 until arr.length()).mapNotNull { i ->
|
||||||
@@ -186,16 +150,6 @@ object WinComponents {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* The catalog entry that installs [name] here: the detector names installers
|
|
||||||
* (vcredist2022, oalinst), and their DLL-copy twin (vcredist2022_dll, oalinst_dll) is the one
|
|
||||||
* that installs without running anything; [name] itself when there is no such twin.
|
|
||||||
*/
|
|
||||||
fun installable(name: String, all: Map<String, Component>): String {
|
|
||||||
val twin = all[if (name == "oalinst") "oalinst_dll" else "${name}_dll"]
|
|
||||||
return if (twin != null && support(twin, all) == Support.READY) twin.name else name
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Whether [c] can be installed here, its bundled components included. */
|
/** Whether [c] can be installed here, its bundled components included. */
|
||||||
fun support(c: Component, all: Map<String, Component>, depth: Int = 0): Support {
|
fun support(c: Component, all: Map<String, Component>, depth: Int = 0): Support {
|
||||||
if (c.status != "ready" || depth > 8 || protonProvides(c.name)) return Support.UNSUPPORTED
|
if (c.status != "ready" || depth > 8 || protonProvides(c.name)) return Support.UNSUPPORTED
|
||||||
@@ -547,7 +501,7 @@ object WinComponents {
|
|||||||
val inside = archive.relativeTo(root).path
|
val inside = archive.relativeTo(root).path
|
||||||
var problem: String? = null
|
var problem: String? = null
|
||||||
var ok = false
|
var ok = false
|
||||||
val status = GuestCommand.run(context, guest(listOf(MSI_INSTALL, "--unpack", "/$inside", "/$MSI_CACHE/${dir.name}")),
|
val status = GuestCommand.run(context, listOf(MSI_INSTALL, "--unpack", "/$inside", "/$MSI_CACHE/${dir.name}"),
|
||||||
logName = "wincomponents-${c.name}") { line ->
|
logName = "wincomponents-${c.name}") { line ->
|
||||||
when {
|
when {
|
||||||
line.startsWith("progress ") -> engineLine(line.removePrefix("progress ")).let { (text, _) -> onProgress(Progress(c.name, text, Phase.INSTALL, -1)) }
|
line.startsWith("progress ") -> engineLine(line.removePrefix("progress ")).let { (text, _) -> onProgress(Progress(c.name, text, Phase.INSTALL, -1)) }
|
||||||
@@ -586,7 +540,7 @@ object WinComponents {
|
|||||||
onProgress(Progress(c.name, "installing", Phase.INSTALL, 0))
|
onProgress(Progress(c.name, "installing", Phase.INSTALL, 0))
|
||||||
var result: JSONObject? = null
|
var result: JSONObject? = null
|
||||||
var problem: String? = null
|
var problem: String? = null
|
||||||
val status = GuestCommand.run(context, guest(listOf(MSI_INSTALL, "/$MSI_CACHE/${file.name}", "/$STORE/${staging.name}")),
|
val status = GuestCommand.run(context, listOf(MSI_INSTALL, "/$MSI_CACHE/${file.name}", "/$STORE/${staging.name}"),
|
||||||
logName = "wincomponents-${c.name}") { line ->
|
logName = "wincomponents-${c.name}") { line ->
|
||||||
when {
|
when {
|
||||||
line.startsWith("progress ") -> engineLine(line.removePrefix("progress ")).let { (text, pct) -> onProgress(Progress(c.name, text, Phase.INSTALL, pct)) }
|
line.startsWith("progress ") -> engineLine(line.removePrefix("progress ")).let { (text, pct) -> onProgress(Progress(c.name, text, Phase.INSTALL, pct)) }
|
||||||
@@ -663,101 +617,36 @@ object WinComponents {
|
|||||||
fun uninstall(context: Context, id: String) {
|
fun uninstall(context: Context, id: String) {
|
||||||
require(validId(id))
|
require(validId(id))
|
||||||
FileUtils.delete(File(LinuxRuntime.rootDir(context), "$STORE/$id"))
|
FileUtils.delete(File(LinuxRuntime.rootDir(context), "$STORE/$id"))
|
||||||
save(context, selections(context).mapValues { (_, sel) -> Selection(sel.auto - id, sel.user - id) })
|
save(context, read(context).mapValues { (_, ids) -> ids - id }.filterValues { it.isNotEmpty() })
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Why a component was turned on for a game by itself ([setAuto]): [kind] says whose list it came
|
|
||||||
* from (see AutoComponents), [args] what the reason line names. Kept beside the picks.
|
|
||||||
*/
|
|
||||||
class AutoReason(val kind: String, val args: List<String>)
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Everything kept per game, by the appid its prefix is named after: [auto] - turned on by
|
|
||||||
* itself, with its reason; [user] - a switch the user pressed (true on, false off), which wins
|
|
||||||
* over [auto] either way. What the launch reads is [effective].
|
|
||||||
*/
|
|
||||||
class Selection(val auto: Map<String, AutoReason>, val user: Map<String, Boolean>) {
|
|
||||||
val effective: List<String>
|
|
||||||
get() = (auto.keys.filter { user[it] != false } + user.filterValues { it }.keys).distinct()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Each game's picks, by the appid its prefix is named after. */
|
||||||
@Synchronized
|
@Synchronized
|
||||||
fun selections(context: Context): Map<String, Selection> = try {
|
fun read(context: Context): Map<String, List<String>> = try {
|
||||||
val json = JSONObject(AtomicFile(File(context.filesDir, SELECTION)).readFully().toString(Charsets.UTF_8))
|
val json = JSONObject(AtomicFile(File(context.filesDir, SELECTION)).readFully().toString(Charsets.UTF_8))
|
||||||
val games = json.optJSONObject("games") ?: JSONObject()
|
val games = json.optJSONObject("games") ?: JSONObject()
|
||||||
val autos = json.optJSONObject("auto") ?: JSONObject()
|
games.keys().asSequence().associateWith { app ->
|
||||||
val users = json.optJSONObject("user")
|
val ids = games.getJSONArray(app)
|
||||||
val keys = games.keys().asSequence().toSet() + autos.keys().asSequence().toSet() + (users?.keys()?.asSequence()?.toSet() ?: emptySet())
|
(0 until ids.length()).map { ids.getString(it) }.filter { validId(it) }
|
||||||
keys.associateWith { app ->
|
|
||||||
val auto = autos.optJSONObject(app)?.let { o ->
|
|
||||||
o.keys().asSequence().filter { validId(it) }.associateWith { id ->
|
|
||||||
val r = o.optJSONObject(id) ?: JSONObject()
|
|
||||||
val a = r.optJSONArray("args") ?: JSONArray()
|
|
||||||
AutoReason(r.optString("kind"), (0 until a.length()).map { a.optString(it) })
|
|
||||||
}
|
|
||||||
}.orEmpty()
|
|
||||||
// Before there were overrides, every pick was the user's own.
|
|
||||||
val user = if (users == null) games.optJSONArray(app)?.let { ids -> (0 until ids.length()).map { ids.getString(it) }.filter { validId(it) }.associateWith { true } }.orEmpty()
|
|
||||||
else users.optJSONObject(app)?.let { o -> o.keys().asSequence().filter { validId(it) }.associateWith { o.optBoolean(it) } }.orEmpty()
|
|
||||||
Selection(auto, user)
|
|
||||||
}
|
}
|
||||||
} catch (_: java.io.FileNotFoundException) {
|
} catch (_: java.io.FileNotFoundException) {
|
||||||
emptyMap()
|
emptyMap()
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Each game's picks as the launch takes them, by the appid its prefix is named after. */
|
fun picks(context: Context, appKey: String): List<String> = read(context)[appKey].orEmpty()
|
||||||
fun read(context: Context): Map<String, List<String>> =
|
|
||||||
selections(context).mapValues { it.value.effective }.filterValues { it.isNotEmpty() }
|
|
||||||
|
|
||||||
fun picks(context: Context, appKey: String): List<String> = selections(context)[appKey]?.effective.orEmpty()
|
|
||||||
|
|
||||||
fun selection(context: Context, appKey: String): Selection = selections(context)[appKey] ?: Selection(emptyMap(), emptyMap())
|
|
||||||
|
|
||||||
/** The user's own switch for [id] in [appKey]: on or off, over whatever was picked by itself. */
|
|
||||||
@Synchronized
|
|
||||||
fun setUser(context: Context, appKey: String, id: String, on: Boolean) {
|
|
||||||
require(validId(id))
|
|
||||||
val all = selections(context).toMutableMap()
|
|
||||||
val now = all[appKey] ?: Selection(emptyMap(), emptyMap())
|
|
||||||
all[appKey] = Selection(now.auto, now.user + (id to on))
|
|
||||||
save(context, all)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The components picked by themselves for [appKey], replacing the earlier ones; the user's switches stay. */
|
|
||||||
@Synchronized
|
|
||||||
fun setAuto(context: Context, appKey: String, auto: Map<String, AutoReason>) {
|
|
||||||
require(auto.keys.all { validId(it) })
|
|
||||||
val all = selections(context).toMutableMap()
|
|
||||||
val now = all[appKey] ?: Selection(emptyMap(), emptyMap())
|
|
||||||
all[appKey] = Selection(auto, now.user)
|
|
||||||
save(context, all)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The user's picks for [appKey] set outright (each listed on, every other user switch dropped). */
|
|
||||||
@Synchronized
|
@Synchronized
|
||||||
fun setPicks(context: Context, appKey: String, ids: List<String>) {
|
fun setPicks(context: Context, appKey: String, ids: List<String>) {
|
||||||
require(ids.all { validId(it) })
|
require(ids.all { validId(it) })
|
||||||
val all = selections(context).toMutableMap()
|
val all = read(context).toMutableMap()
|
||||||
val now = all[appKey] ?: Selection(emptyMap(), emptyMap())
|
if (ids.isEmpty()) all.remove(appKey) else all[appKey] = ids.distinct()
|
||||||
all[appKey] = Selection(now.auto, ids.distinct().associateWith { true } + now.auto.keys.filter { it !in ids }.associateWith { false })
|
|
||||||
save(context, all)
|
save(context, all)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun save(context: Context, games: Map<String, Selection>) {
|
private fun save(context: Context, games: Map<String, List<String>>) {
|
||||||
val kept = games.filterValues { it.auto.isNotEmpty() || it.user.isNotEmpty() }
|
val text = JSONObject().put("version", 1).put("games", JSONObject().apply {
|
||||||
// Version 1 still: droiddeck-wincomponents reads "games" and ignores the rest.
|
games.forEach { (app, ids) -> put(app, JSONArray(ids)) }
|
||||||
val text = JSONObject().put("version", 1)
|
}).toString()
|
||||||
.put("games", JSONObject().apply { kept.forEach { (app, sel) -> sel.effective.takeIf { it.isNotEmpty() }?.let { put(app, JSONArray(it)) } } })
|
|
||||||
.put("auto", JSONObject().apply {
|
|
||||||
kept.forEach { (app, sel) ->
|
|
||||||
if (sel.auto.isNotEmpty()) put(app, JSONObject().apply {
|
|
||||||
sel.auto.forEach { (id, r) -> put(id, JSONObject().put("kind", r.kind).put("args", JSONArray(r.args))) }
|
|
||||||
})
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.put("user", JSONObject().apply { kept.forEach { (app, sel) -> if (sel.user.isNotEmpty()) put(app, JSONObject(sel.user as Map<*, *>)) } })
|
|
||||||
.toString()
|
|
||||||
write(File(context.filesDir, SELECTION), text)
|
write(File(context.filesDir, SELECTION), text)
|
||||||
publish(context, text)
|
publish(context, text)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -48,9 +48,6 @@ object StoreState {
|
|||||||
private set
|
private set
|
||||||
var searching by mutableStateOf(false)
|
var searching by mutableStateOf(false)
|
||||||
private set
|
private set
|
||||||
|
|
||||||
/** An app whose Flathub page was asked for from outside the store (its card on Desktop), once. */
|
|
||||||
var openRequest by mutableStateOf<String?>(null)
|
|
||||||
private var searchSeq = 0
|
private var searchSeq = 0
|
||||||
|
|
||||||
val SECTIONS = listOf("popular" to R.string.store_section_popular, "trending" to R.string.store_section_trending, "recently-added" to R.string.store_section_new, "recently-updated" to R.string.store_section_updated)
|
val SECTIONS = listOf("popular" to R.string.store_section_popular, "trending" to R.string.store_section_trending, "recently-added" to R.string.store_section_new, "recently-updated" to R.string.store_section_updated)
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
package com.droiddeck.launcher.stores
|
package com.droiddeck.launcher.stores
|
||||||
|
|
||||||
import com.droiddeck.launcher.session.SessionPrefs
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
import com.droiddeck.launcher.frontend.AddedGames
|
import com.droiddeck.launcher.frontend.AddedGames
|
||||||
@@ -53,9 +52,6 @@ object StoreInstalls {
|
|||||||
try { StoreArt.fetchInto(folder, finished) } catch (e: Exception) { Log.w(TAG, "art for ${folder.name}: ${e.message}") }
|
try { StoreArt.fetchInto(folder, finished) } catch (e: Exception) { Log.w(TAG, "art for ${folder.name}: ${e.message}") }
|
||||||
onStep?.invoke(2, STEPS)
|
onStep?.invoke(2, STEPS)
|
||||||
register(app)
|
register(app)
|
||||||
// Its Windows components from the store's list (GOG's dependencies, Epic's prerequisite,
|
|
||||||
// Amazon's install steps), on a thread of their own.
|
|
||||||
AddedGames.single(app, folder.path)?.let { com.droiddeck.launcher.frontend.AutoComponents.refreshLater(app, Library.addedGame(app, it)) }
|
|
||||||
onStep?.invoke(STEPS, STEPS)
|
onStep?.invoke(STEPS, STEPS)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -77,26 +73,14 @@ object StoreInstalls {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Removes a store game: its folder with the sidecar, then the shortcut (the listing without
|
* Removes a store game: its folder with the sidecar, then the shortcut (the listing without
|
||||||
* it makes the writer drop the entry; the live client is asked too). Blocking. [removed] runs
|
* it makes the writer drop the entry; the live client is asked too). Blocking.
|
||||||
* once the files are gone, before the shortcut list is rebuilt (which reads every added game).
|
|
||||||
*/
|
*/
|
||||||
fun uninstall(context: Context, game: InstalledStoreGame, progress: (Float) -> Unit = {}, removed: () -> Unit = {}) {
|
fun uninstall(context: Context, game: InstalledStoreGame) {
|
||||||
val app = context.applicationContext
|
val app = context.applicationContext
|
||||||
// The shortcut's id as stored for the folder: scanning every added game for it first held
|
val appId = AddedGames.scan(app).firstOrNull { it.folder.absolutePath == game.folder.absolutePath }?.appId
|
||||||
// the bar at 0% for seconds before a file went.
|
|
||||||
val appId = SessionPrefs.addedGameStoredAppId(app, game.folder.path)
|
|
||||||
// File by file, deepest first, saying how far it has got: a big game takes a while to go.
|
|
||||||
val files = game.folder.walkBottomUp().toList()
|
|
||||||
val step = (files.size / 100).coerceAtLeast(1)
|
|
||||||
files.forEachIndexed { i, f ->
|
|
||||||
f.delete()
|
|
||||||
if (i % step == 0) progress((i + 1).toFloat() / files.size)
|
|
||||||
}
|
|
||||||
deleteTree(game.folder)
|
deleteTree(game.folder)
|
||||||
progress(1f)
|
|
||||||
// The scratch cache an install on a card may have left in the app's cache.
|
// The scratch cache an install on a card may have left in the app's cache.
|
||||||
deleteTree(StoreInstallRoot.scratchDir(app, game.sidecar.store, game.sidecar.id))
|
deleteTree(StoreInstallRoot.scratchDir(app, game.sidecar.store, game.sidecar.id))
|
||||||
removed()
|
|
||||||
register(app)
|
register(app)
|
||||||
if (appId != null) SteamLiveShortcuts.remove(app, appId)
|
if (appId != null) SteamLiveShortcuts.remove(app, appId)
|
||||||
StoresState.logLine("uninstalled \"${game.sidecar.title}\"")
|
StoresState.logLine("uninstalled \"${game.sidecar.title}\"")
|
||||||
|
|||||||
@@ -99,8 +99,6 @@ object StoresState {
|
|||||||
/** Reads what is on disk for every store: sign-ins, installed games, the engine probe. Off the main thread. */
|
/** Reads what is on disk for every store: sign-ins, installed games, the engine probe. Off the main thread. */
|
||||||
fun refresh(context: Context) {
|
fun refresh(context: Context) {
|
||||||
val app = context.applicationContext
|
val app = context.applicationContext
|
||||||
// The first refresh after the app starts brings back what was in the download queue.
|
|
||||||
com.droiddeck.launcher.stores.download.SavedQueue.restore(app)
|
|
||||||
Thread({
|
Thread({
|
||||||
val found = Store.entries.mapNotNull { store -> StoreAccounts.signedInAs(app, store)?.let { store to it } }
|
val found = Store.entries.mapNotNull { store -> StoreAccounts.signedInAs(app, store)?.let { store to it } }
|
||||||
val onDisk = StoreInstallRoot.gameFolders(app).mapNotNull { folder ->
|
val onDisk = StoreInstallRoot.gameFolders(app).mapNotNull { folder ->
|
||||||
@@ -219,30 +217,15 @@ object StoresState {
|
|||||||
fun install(context: Context, item: CatalogItem, root: java.io.File? = null) {
|
fun install(context: Context, item: CatalogItem, root: java.io.File? = null) {
|
||||||
val app = context.applicationContext
|
val app = context.applicationContext
|
||||||
val target = root ?: StoreInstallRoot.installRoot(app)
|
val target = root ?: StoreInstallRoot.installRoot(app)
|
||||||
com.droiddeck.launcher.stores.download.SavedQueue.remember(app, item, target)
|
|
||||||
backends[item.store]?.install(app, item, target) ?: logLine("${item.store.label}: this build cannot install yet")
|
backends[item.store]?.install(app, item, target) ?: logLine("${item.store.label}: this build cannot install yet")
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Games being removed, by key ("store:id"), and how far along (0..1): their page shows it. */
|
/** Removes the game's folder and its shortcut, then [onDone] on the main thread. */
|
||||||
val uninstalling = mutableStateMapOf<String, Float>()
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Removes the game's folder and its shortcut, then [onDone] on the main thread. The game reads
|
|
||||||
* as removed the moment it is gone (its page shows Install, its card its size), not once the
|
|
||||||
* whole library has been read again.
|
|
||||||
*/
|
|
||||||
fun uninstall(context: Context, game: InstalledStoreGame, onDone: () -> Unit = {}) {
|
fun uninstall(context: Context, game: InstalledStoreGame, onDone: () -> Unit = {}) {
|
||||||
val app = context.applicationContext
|
val app = context.applicationContext
|
||||||
val key = "${game.sidecar.store.id}:${game.sidecar.id}"
|
|
||||||
uninstalling[key] = 0f
|
|
||||||
Thread({
|
Thread({
|
||||||
runCatching { backends[game.sidecar.store]?.uninstall(app, game) }
|
runCatching { backends[game.sidecar.store]?.uninstall(app, game) }
|
||||||
StoreInstalls.uninstall(app, game, progress = { f -> main.post { if (key in uninstalling) uninstalling[key] = f } }, removed = {
|
StoreInstalls.uninstall(app, game)
|
||||||
main.post {
|
|
||||||
installed = installed.filterNot { it.folder.absolutePath == game.folder.absolutePath }
|
|
||||||
uninstalling.remove(key)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
main.post(onDone)
|
main.post(onDone)
|
||||||
}, "stores-uninstall").start()
|
}, "stores-uninstall").start()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -137,11 +137,6 @@ object DownloadQueue {
|
|||||||
|
|
||||||
private val lock = Any()
|
private val lock = Any()
|
||||||
private val items = LinkedHashMap<String, Item>()
|
private val items = LinkedHashMap<String, Item>()
|
||||||
/** Keys a restart brings back paused: queued as paused, not started. */
|
|
||||||
private val heldPaused = HashSet<String>()
|
|
||||||
|
|
||||||
/** [key]'s next [enqueue] comes in paused (a paused download restored after a restart). */
|
|
||||||
fun holdPaused(key: String) = synchronized(lock) { heldPaused.add(key) }
|
|
||||||
private var running = 0
|
private var running = 0
|
||||||
|
|
||||||
fun parallel(context: Context): Int = SessionPrefs.gameStoresParallel(context)
|
fun parallel(context: Context): Int = SessionPrefs.gameStoresParallel(context)
|
||||||
@@ -176,8 +171,7 @@ object DownloadQueue {
|
|||||||
synchronized(lock) {
|
synchronized(lock) {
|
||||||
items[entry.key]?.let { if (it.entry.isActive) { Log.i(TAG, "${entry.key}: already queued"); return } }
|
items[entry.key]?.let { if (it.entry.isActive) { Log.i(TAG, "${entry.key}: already queued"); return } }
|
||||||
items.remove(entry.key)
|
items.remove(entry.key)
|
||||||
val state = if (heldPaused.remove(entry.key)) DownloadState.PAUSED else DownloadState.QUEUED
|
items[entry.key] = Item(entry.copy(state = DownloadState.QUEUED, stage = DownloadStage.MANIFEST, startedAt = System.currentTimeMillis()), factory)
|
||||||
items[entry.key] = Item(entry.copy(state = state, stage = DownloadStage.MANIFEST, startedAt = System.currentTimeMillis()), factory)
|
|
||||||
renumber()
|
renumber()
|
||||||
}
|
}
|
||||||
StoresState.logLine("${entry.store.label}: queued \"${entry.name}\"" + if (entry.bytesTotal > 0) " (${com.droiddeck.launcher.stores.formatBytes(entry.bytesTotal)})" else "")
|
StoresState.logLine("${entry.store.label}: queued \"${entry.name}\"" + if (entry.bytesTotal > 0) " (${com.droiddeck.launcher.stores.formatBytes(entry.bytesTotal)})" else "")
|
||||||
@@ -312,8 +306,6 @@ object DownloadQueue {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
lastPublishAt = now
|
lastPublishAt = now
|
||||||
// A state change (not progress) is written down, so the queue outlives the app.
|
|
||||||
if (!progressOnly) SavedQueue.save(items.values.map { it.entry })
|
|
||||||
val list = items.values.map { it.entry }.sortedByDescending { it.startedAt }
|
val list = items.values.map { it.entry }.sortedByDescending { it.startedAt }
|
||||||
StoresState.post { StoresState.publishDownloads(list) }
|
StoresState.post { StoresState.publishDownloads(list) }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,108 +0,0 @@
|
|||||||
package com.droiddeck.launcher.stores.download
|
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
import android.util.Log
|
|
||||||
import com.droiddeck.launcher.stores.CatalogItem
|
|
||||||
import com.droiddeck.launcher.stores.Store
|
|
||||||
import com.droiddeck.launcher.stores.StoresState
|
|
||||||
import org.json.JSONArray
|
|
||||||
import org.json.JSONObject
|
|
||||||
import java.io.File
|
|
||||||
import java.util.concurrent.Executors
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The download queue kept on disk, so what was queued, running or paused comes back after the app
|
|
||||||
* closes or is killed: the queue itself lives in memory, and a queued game that never started has
|
|
||||||
* nothing on disk to find. Each install records the game and where it goes ([remember]); every
|
|
||||||
* change of state writes the active rows in queue order ([save]); the first refresh after the app
|
|
||||||
* starts asks the stores for them again ([restore]) - running and queued ones carry on, paused ones
|
|
||||||
* come back paused.
|
|
||||||
*/
|
|
||||||
object SavedQueue {
|
|
||||||
private const val TAG = "StoreDownloads"
|
|
||||||
private const val FILE = "store-queue.json"
|
|
||||||
|
|
||||||
private class Wanted(val item: CatalogItem, val root: File?)
|
|
||||||
|
|
||||||
private val wanted = HashMap<String, Wanted>()
|
|
||||||
private val writer = Executors.newSingleThreadExecutor { r -> Thread(r, "store-queue-save") }
|
|
||||||
@Volatile private var app: Context? = null
|
|
||||||
private var restored = false
|
|
||||||
|
|
||||||
private fun key(item: CatalogItem) = "${item.store.id}:${item.id}"
|
|
||||||
|
|
||||||
/** An install is asked for: what to ask the store for again after a restart. */
|
|
||||||
@Synchronized
|
|
||||||
fun remember(context: Context, item: CatalogItem, root: File?) {
|
|
||||||
app = context.applicationContext
|
|
||||||
wanted[key(item)] = Wanted(item, root)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The active rows, in queue order, as they are now. Any thread; written off it. */
|
|
||||||
fun save(entries: List<DownloadEntry>) {
|
|
||||||
val context = app ?: return
|
|
||||||
val rows = synchronized(this) {
|
|
||||||
entries.filter { it.isActive }.mapNotNull { e -> wanted[e.key]?.let { e to it } }
|
|
||||||
}
|
|
||||||
val out = JSONArray()
|
|
||||||
for ((e, w) in rows) out.put(JSONObject().apply {
|
|
||||||
put("paused", e.state == DownloadState.PAUSED)
|
|
||||||
put("root", w.root?.absolutePath ?: "")
|
|
||||||
put("item", itemJson(w.item))
|
|
||||||
})
|
|
||||||
writer.execute {
|
|
||||||
runCatching {
|
|
||||||
val f = File(context.filesDir, FILE)
|
|
||||||
val tmp = File(context.filesDir, "$FILE.tmp")
|
|
||||||
tmp.writeText(out.toString())
|
|
||||||
tmp.renameTo(f)
|
|
||||||
}.onFailure { Log.w(TAG, "could not save the queue", it) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Once per process: queues again what was in the queue when the app last closed. */
|
|
||||||
fun restore(context: Context) {
|
|
||||||
synchronized(this) { if (restored) return; restored = true }
|
|
||||||
val app = context.applicationContext
|
|
||||||
// Read before anything may write it: an install started at once must not save over it.
|
|
||||||
val rows = runCatching { JSONArray(File(app.filesDir, FILE).readText()) }.getOrNull()
|
|
||||||
this.app = app
|
|
||||||
rows ?: return
|
|
||||||
Thread({
|
|
||||||
val back = (0 until rows.length()).mapNotNull { i ->
|
|
||||||
runCatching {
|
|
||||||
val o = rows.getJSONObject(i)
|
|
||||||
Triple(itemOf(o.getJSONObject("item")), o.optString("root").takeIf { it.isNotEmpty() }?.let(::File), o.optBoolean("paused"))
|
|
||||||
}.getOrNull()
|
|
||||||
}
|
|
||||||
if (back.isEmpty()) return@Thread
|
|
||||||
StoresState.post {
|
|
||||||
for ((item, root, paused) in back) {
|
|
||||||
if (DownloadQueue.entry(key(item)) != null) continue
|
|
||||||
if (paused) DownloadQueue.holdPaused(key(item))
|
|
||||||
StoresState.install(app, item, root)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}, "store-queue-restore").start()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun itemJson(i: CatalogItem) = JSONObject().apply {
|
|
||||||
put("store", i.store.id); put("id", i.id); put("title", i.title)
|
|
||||||
put("image", i.imageUrl ?: ""); put("tall", i.tallImageUrl ?: "")
|
|
||||||
put("tags", i.tags); put("developer", i.developer); put("description", i.description)
|
|
||||||
put("size", i.sizeBytes); put("owned", i.owned)
|
|
||||||
put("extra", JSONObject(i.extra))
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun itemOf(o: JSONObject): CatalogItem {
|
|
||||||
val extra = o.optJSONObject("extra")
|
|
||||||
return CatalogItem(
|
|
||||||
store = Store.byId(o.getString("store")) ?: error("unknown store"),
|
|
||||||
id = o.getString("id"), title = o.getString("title"),
|
|
||||||
imageUrl = o.optString("image").ifEmpty { null }, tallImageUrl = o.optString("tall").ifEmpty { null },
|
|
||||||
tags = o.optString("tags"), developer = o.optString("developer"), description = o.optString("description"),
|
|
||||||
owned = o.optBoolean("owned", true), sizeBytes = o.optLong("size"),
|
|
||||||
extra = extra?.keys()?.asSequence()?.associateWith { extra.getString(it) } ?: emptyMap(),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -156,11 +156,7 @@ object EpicBackend : StoreBackend, EpicLaunchSupport {
|
|||||||
Store.EPIC, item.id, item.title, exe = exe.ifEmpty { "game.exe" }, args = args,
|
Store.EPIC, item.id, item.title, exe = exe.ifEmpty { "game.exe" }, args = args,
|
||||||
installVersion = result.buildVersion, installedAt = System.currentTimeMillis(),
|
installVersion = result.buildVersion, installedAt = System.currentTimeMillis(),
|
||||||
cover = item.tallImageUrl ?: item.imageUrl, hero = item.imageUrl,
|
cover = item.tallImageUrl ?: item.imageUrl, hero = item.imageUrl,
|
||||||
// Both kept even when empty: the manifest was read, and names no prerequisite.
|
extra = EpicLaunchData.extras(item.id, namespace, catalogItemId, deploymentId),
|
||||||
extra = EpicLaunchData.extras(item.id, namespace, catalogItemId, deploymentId) + mapOf(
|
|
||||||
com.droiddeck.launcher.frontend.WinCompSources.EPIC_PREREQ_PATH to result.prereqPath,
|
|
||||||
com.droiddeck.launcher.frontend.WinCompSources.EPIC_PREREQ_NAME to result.prereqName,
|
|
||||||
) + (if (result.prereqRead) mapOf(com.droiddeck.launcher.frontend.WinCompSources.LIST_READ to "1") else emptyMap()),
|
|
||||||
)
|
)
|
||||||
StoreInstalls.complete(app, folder, sidecar)
|
StoreInstalls.complete(app, folder, sidecar)
|
||||||
return folder.path
|
return folder.path
|
||||||
|
|||||||
@@ -107,11 +107,6 @@ public final class EpicDownloadManager {
|
|||||||
public String launchExe = "";
|
public String launchExe = "";
|
||||||
public String launchCommand = "";
|
public String launchCommand = "";
|
||||||
public String buildVersion = "";
|
public String buildVersion = "";
|
||||||
/** The prerequisite the launcher runs first (UE4PrereqSetup_x64.exe...): what it is called and its path in the install. */
|
|
||||||
public String prereqName = "";
|
|
||||||
public String prereqPath = "";
|
|
||||||
/** The prerequisite fields were read (an empty name and path then mean the build names none). */
|
|
||||||
public boolean prereqRead = false;
|
|
||||||
public List<CdnUrl> cdnUrls = new ArrayList<>();
|
public List<CdnUrl> cdnUrls = new ArrayList<>();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -120,12 +115,7 @@ public final class EpicDownloadManager {
|
|||||||
public final String launchExe;
|
public final String launchExe;
|
||||||
public final String buildVersion;
|
public final String buildVersion;
|
||||||
public final long bytes;
|
public final long bytes;
|
||||||
/** The manifest's prerequisite, for Windows components; "" when it names none. */
|
|
||||||
public String prereqName = "";
|
|
||||||
public String prereqPath = "";
|
|
||||||
Result(String launchExe, String buildVersion, long bytes) { this.launchExe = launchExe; this.buildVersion = buildVersion; this.bytes = bytes; }
|
Result(String launchExe, String buildVersion, long bytes) { this.launchExe = launchExe; this.buildVersion = buildVersion; this.bytes = bytes; }
|
||||||
public boolean prereqRead = false;
|
|
||||||
Result withPrereq(Manifest m) { prereqName = m.prereqName; prereqPath = m.prereqPath; prereqRead = m.prereqRead; return this; }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static final class InstallException extends Exception {
|
public static final class InstallException extends Exception {
|
||||||
@@ -188,7 +178,7 @@ public final class EpicDownloadManager {
|
|||||||
if (pending.isEmpty()) {
|
if (pending.isEmpty()) {
|
||||||
deleteDir(chunkCacheDir);
|
deleteDir(chunkCacheDir);
|
||||||
cb.onProgress("Complete", 100);
|
cb.onProgress("Complete", 100);
|
||||||
return new Result(manifest.launchExe, manifest.buildVersion, planned).withPrereq(manifest);
|
return new Result(manifest.launchExe, manifest.buildVersion, planned);
|
||||||
}
|
}
|
||||||
List<ChunkInfo> needed = uniqueChunksForFiles(manifest, pending);
|
List<ChunkInfo> needed = uniqueChunksForFiles(manifest, pending);
|
||||||
// The cache holds whole chunk windows (~1 MiB each), and a window is shared with files
|
// The cache holds whole chunk windows (~1 MiB each), and a window is shared with files
|
||||||
@@ -275,7 +265,7 @@ public final class EpicDownloadManager {
|
|||||||
if (r.cancelled) return null;
|
if (r.cancelled) return null;
|
||||||
if (!r.success) throw new InstallException(r.error.isEmpty() ? "assembly failed" : r.error);
|
if (!r.success) throw new InstallException(r.error.isEmpty() ? "assembly failed" : r.error);
|
||||||
cb.onProgress("Complete", 100);
|
cb.onProgress("Complete", 100);
|
||||||
return new Result(manifest.launchExe, manifest.buildVersion, planned).withPrereq(manifest);
|
return new Result(manifest.launchExe, manifest.buildVersion, planned);
|
||||||
}
|
}
|
||||||
cb.onLog("epic: assembler not started (" + r.error + "); writing the files here");
|
cb.onLog("epic: assembler not started (" + r.error + "); writing the files here");
|
||||||
}
|
}
|
||||||
@@ -303,7 +293,7 @@ public final class EpicDownloadManager {
|
|||||||
}
|
}
|
||||||
deleteDir(chunkCacheDir);
|
deleteDir(chunkCacheDir);
|
||||||
cb.onProgress("Complete", 100);
|
cb.onProgress("Complete", 100);
|
||||||
return new Result(manifest.launchExe, manifest.buildVersion, planned).withPrereq(manifest);
|
return new Result(manifest.launchExe, manifest.buildVersion, planned);
|
||||||
} catch (InstallException e) {
|
} catch (InstallException e) {
|
||||||
throw e;
|
throw e;
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
@@ -480,13 +470,6 @@ public final class EpicDownloadManager {
|
|||||||
m.buildVersion = readFString(b);
|
m.buildVersion = readFString(b);
|
||||||
m.launchExe = readFString(b).replace('\\', '/');
|
m.launchExe = readFString(b).replace('\\', '/');
|
||||||
m.launchCommand = readFString(b);
|
m.launchCommand = readFString(b);
|
||||||
// PrereqIds (an array), PrereqName, PrereqPath, PrereqArgs.
|
|
||||||
int prereqIds = b.getInt();
|
|
||||||
for (int i = 0; i < prereqIds && i < 64; i++) readFString(b);
|
|
||||||
m.prereqName = readFString(b);
|
|
||||||
m.prereqPath = readFString(b).replace('\\', '/');
|
|
||||||
readFString(b); // PrereqArgs
|
|
||||||
m.prereqRead = true;
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
Log.w(TAG, "manifest meta: " + e.getClass().getSimpleName());
|
Log.w(TAG, "manifest meta: " + e.getClass().getSimpleName());
|
||||||
}
|
}
|
||||||
@@ -548,15 +531,12 @@ public final class EpicDownloadManager {
|
|||||||
try {
|
try {
|
||||||
JSONObject root = new JSONObject(new String(bytes, StandardCharsets.UTF_8));
|
JSONObject root = new JSONObject(new String(bytes, StandardCharsets.UTF_8));
|
||||||
int manifestVersion = 0;
|
int manifestVersion = 0;
|
||||||
try { manifestVersion = (int) blobToNum(root.optString("ManifestFileVersion", "0")); } catch (NumberFormatException ignored) {}
|
try { manifestVersion = Integer.parseInt(root.optString("ManifestFileVersion", "0")); } catch (NumberFormatException ignored) {}
|
||||||
Manifest m = new Manifest();
|
Manifest m = new Manifest();
|
||||||
m.chunkDir = manifestVersion >= 15 ? "ChunksV4" : manifestVersion >= 6 ? "ChunksV3" : manifestVersion >= 3 ? "ChunksV2" : "ChunksV4";
|
m.chunkDir = manifestVersion >= 15 ? "ChunksV4" : manifestVersion >= 6 ? "ChunksV3" : manifestVersion >= 3 ? "ChunksV2" : "ChunksV4";
|
||||||
m.launchExe = root.optString("LaunchExeString", root.optString("LaunchExe", "")).replace('\\', '/');
|
m.launchExe = root.optString("LaunchExe", "").replace('\\', '/');
|
||||||
m.launchCommand = root.optString("LaunchCommand", "");
|
m.launchCommand = root.optString("LaunchCommand", "");
|
||||||
m.buildVersion = root.optString("BuildVersionString", "");
|
m.buildVersion = root.optString("BuildVersionString", "");
|
||||||
m.prereqName = root.optString("PrereqName", "");
|
|
||||||
m.prereqPath = root.optString("PrereqPath", "").replace('\\', '/');
|
|
||||||
m.prereqRead = true;
|
|
||||||
JSONObject chunkHashList = root.optJSONObject("ChunkHashList");
|
JSONObject chunkHashList = root.optJSONObject("ChunkHashList");
|
||||||
JSONObject dataGroupList = root.optJSONObject("DataGroupList");
|
JSONObject dataGroupList = root.optJSONObject("DataGroupList");
|
||||||
JSONObject chunkFilesizeList = root.optJSONObject("ChunkFilesizeList");
|
JSONObject chunkFilesizeList = root.optJSONObject("ChunkFilesizeList");
|
||||||
@@ -568,9 +548,10 @@ public final class EpicDownloadManager {
|
|||||||
if (guidHex.length() < 32) continue;
|
if (guidHex.length() < 32) continue;
|
||||||
ChunkInfo c = new ChunkInfo();
|
ChunkInfo c = new ChunkInfo();
|
||||||
for (int k = 0; k < 4; k++) c.guid[k] = (int) Long.parseLong(guidHex.substring(k * 8, k * 8 + 8), 16);
|
for (int k = 0; k < 4; k++) c.guid[k] = (int) Long.parseLong(guidHex.substring(k * 8, k * 8 + 8), 16);
|
||||||
try { c.hash = blobToNum(chunkHashList.getString(guidHex)); } catch (NumberFormatException ignored) {}
|
String hashHex = chunkHashList.getString(guidHex);
|
||||||
if (dataGroupList != null) { try { c.groupNum = (int) blobToNum(dataGroupList.optString(guidHex, "0")); } catch (NumberFormatException ignored) {} }
|
if (hashHex != null && hashHex.length() >= 16) { try { c.hash = Long.parseUnsignedLong(hashHex.substring(0, 16), 16); } catch (Exception ignored) {} }
|
||||||
if (chunkFilesizeList != null) { try { c.fileSize = blobToNum(chunkFilesizeList.optString(guidHex, "0")); } catch (NumberFormatException ignored) {} }
|
if (dataGroupList != null) { try { c.groupNum = Integer.parseInt(dataGroupList.optString(guidHex, "0")); } catch (NumberFormatException ignored) {} }
|
||||||
|
if (chunkFilesizeList != null) { try { c.fileSize = Long.parseLong(chunkFilesizeList.optString(guidHex, "0"), 16); } catch (NumberFormatException ignored) {} }
|
||||||
chunkMap.put(guidHex, c);
|
chunkMap.put(guidHex, c);
|
||||||
}
|
}
|
||||||
JSONArray fileList = root.optJSONArray("FileManifestList");
|
JSONArray fileList = root.optJSONArray("FileManifestList");
|
||||||
@@ -588,8 +569,8 @@ public final class EpicDownloadManager {
|
|||||||
ChunkPart part = new ChunkPart();
|
ChunkPart part = new ChunkPart();
|
||||||
String g = po.optString("Guid", "");
|
String g = po.optString("Guid", "");
|
||||||
if (g.length() >= 32) for (int k = 0; k < 4; k++) part.guid[k] = (int) Long.parseLong(g.substring(k * 8, k * 8 + 8), 16);
|
if (g.length() >= 32) for (int k = 0; k < 4; k++) part.guid[k] = (int) Long.parseLong(g.substring(k * 8, k * 8 + 8), 16);
|
||||||
try { part.offset = (int) blobToNum(po.optString("Offset", "0")); } catch (NumberFormatException ignored) {}
|
try { part.offset = Integer.parseInt(po.optString("Offset", "0")); } catch (NumberFormatException ignored) {}
|
||||||
try { part.size = (int) blobToNum(po.optString("Size", "0")); } catch (NumberFormatException ignored) {}
|
try { part.size = Integer.parseInt(po.optString("Size", "0")); } catch (NumberFormatException ignored) {}
|
||||||
fi.parts.add(part);
|
fi.parts.add(part);
|
||||||
}
|
}
|
||||||
files.add(fi);
|
files.add(fi);
|
||||||
@@ -603,24 +584,6 @@ public final class EpicDownloadManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* A JSON manifest writes every number as a "blob": each byte as three decimal digits, least
|
|
||||||
* significant first ("013000000000" = 13), as Legendary's blob_to_num reads it. Bits past 64
|
|
||||||
* are dropped; a group that is not digits throws.
|
|
||||||
*/
|
|
||||||
static long blobToNum(String blob) {
|
|
||||||
long num = 0;
|
|
||||||
for (int i = 0, shift = 0; i < blob.length(); i += 3, shift += 8) {
|
|
||||||
String group = blob.substring(i, Math.min(i + 3, blob.length()));
|
|
||||||
for (int k = 0; k < group.length(); k++) {
|
|
||||||
char ch = group.charAt(k);
|
|
||||||
if (ch < '0' || ch > '9') throw new NumberFormatException("not a blob: " + blob);
|
|
||||||
}
|
|
||||||
if (shift < 64) num += Long.parseLong(group) << shift;
|
|
||||||
}
|
|
||||||
return num;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static String readFString(ByteBuffer buf) {
|
public static String readFString(ByteBuffer buf) {
|
||||||
int length = buf.getInt();
|
int length = buf.getInt();
|
||||||
if (length == 0) return "";
|
if (length == 0) return "";
|
||||||
@@ -790,22 +753,6 @@ public final class EpicDownloadManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The manifest's prerequisite as {name, path}, from the manifest alone; null on failure. Blocking. */
|
|
||||||
public static String[] fetchPrereq(String manifestApiJson) {
|
|
||||||
try {
|
|
||||||
List<CdnUrl> cdnUrls = parseCdnUrls(manifestApiJson);
|
|
||||||
if (cdnUrls.isEmpty()) return null;
|
|
||||||
byte[] bytes = downloadManifest(manifestApiJson, cdnUrls);
|
|
||||||
if (bytes == null) return null;
|
|
||||||
Manifest m = parseManifest(bytes);
|
|
||||||
if (m == null || !m.prereqRead) { Log.w(TAG, "manifest prerequisite not read"); return null; }
|
|
||||||
Log.i(TAG, "manifest " + m.buildVersion + ": " + m.files.size() + " files, prerequisite " + (m.prereqName.isEmpty() && m.prereqPath.isEmpty() ? "none" : m.prereqName + " (" + m.prereqPath + ")"));
|
|
||||||
return new String[] { m.prereqName, m.prereqPath };
|
|
||||||
} catch (Exception e) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The install size for the tags (null = every file), from the manifest alone; -1 on failure. Blocking. */
|
/** The install size for the tags (null = every file), from the manifest alone; -1 on failure. Blocking. */
|
||||||
public static long fetchInstallSizeBytes(String manifestApiJson, List<String> installTags) {
|
public static long fetchInstallSizeBytes(String manifestApiJson, List<String> installTags) {
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -111,9 +111,6 @@ object GogBackend : StoreBackend {
|
|||||||
Store.GOG, game.gameId, game.title, exe = result.exeRelative.ifEmpty { "" },
|
Store.GOG, game.gameId, game.title, exe = result.exeRelative.ifEmpty { "" },
|
||||||
installVersion = result.buildId, installedAt = System.currentTimeMillis(),
|
installVersion = result.buildId, installedAt = System.currentTimeMillis(),
|
||||||
cover = item.tallImageUrl ?: item.imageUrl, hero = item.imageUrl,
|
cover = item.tallImageUrl ?: item.imageUrl, hero = item.imageUrl,
|
||||||
// Kept even when empty: the build was read, and lists none.
|
|
||||||
extra = mapOf(com.droiddeck.launcher.frontend.WinCompSources.GOG_DEPENDENCIES to result.dependencies.joinToString(","))
|
|
||||||
+ (if (result.dependenciesRead) mapOf(com.droiddeck.launcher.frontend.WinCompSources.LIST_READ to "1") else emptyMap()),
|
|
||||||
)
|
)
|
||||||
if (sidecar.exe.isEmpty()) handle.log("gog: no exe found in ${folder.name}; pick one in Steam settings › Added games")
|
if (sidecar.exe.isEmpty()) handle.log("gog: no exe found in ${folder.name}; pick one in Steam settings › Added games")
|
||||||
StoreInstalls.complete(app, folder, onStep = { done, steps -> handle.stageProgress(done.toLong(), steps.toLong()) }, sidecar = if (sidecar.exe.isEmpty()) sidecar.copy(exe = "game.exe") else sidecar)
|
StoreInstalls.complete(app, folder, onStep = { done, steps -> handle.stageProgress(done.toLong(), steps.toLong()) }, sidecar = if (sidecar.exe.isEmpty()) sidecar.copy(exe = "game.exe") else sidecar)
|
||||||
|
|||||||
@@ -79,10 +79,6 @@ public final class GogDownloadManager {
|
|||||||
public final String exeRelative;
|
public final String exeRelative;
|
||||||
public final String buildId;
|
public final String buildId;
|
||||||
public final long bytes;
|
public final long bytes;
|
||||||
/** The build manifest's "dependencies" (GOG's redistributable ids: MSVC2017_x64, DirectX...), for Windows components. */
|
|
||||||
public List<String> dependencies = new ArrayList<>();
|
|
||||||
/** The dependencies come from a gen2 build manifest read whole (gen1 builds and installers have none). */
|
|
||||||
public boolean dependenciesRead = false;
|
|
||||||
Result(String exeRelative, String buildId, long bytes) { this.exeRelative = exeRelative; this.buildId = buildId; this.bytes = bytes; }
|
Result(String exeRelative, String buildId, long bytes) { this.exeRelative = exeRelative; this.buildId = buildId; this.bytes = bytes; }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -154,12 +150,10 @@ public final class GogDownloadManager {
|
|||||||
if ((baseProductId == null || baseProductId.isEmpty()) && products != null && products.length() > 0)
|
if ((baseProductId == null || baseProductId.isEmpty()) && products != null && products.length() > 0)
|
||||||
baseProductId = products.getJSONObject(0).optString("productId", null);
|
baseProductId = products.getJSONObject(0).optString("productId", null);
|
||||||
if (baseProductId == null || baseProductId.isEmpty()) baseProductId = game.gameId;
|
if (baseProductId == null || baseProductId.isEmpty()) baseProductId = game.gameId;
|
||||||
// The build's required redistributables (MSVC, DirectX, ...): logged, and kept in the
|
// The build's required redistributables (MSVC, DirectX, ...) are recorded for the engine
|
||||||
// sidecar, where Windows components take them as this game's list (WinCompSources).
|
// log; Steam's shared redistributables run in the prefix on first launch as for any shortcut.
|
||||||
JSONArray deps = manifest.optJSONArray("dependencies");
|
JSONArray deps = manifest.optJSONArray("dependencies");
|
||||||
List<String> dependencies = new ArrayList<>();
|
if (deps != null && deps.length() > 0) cb.onLog("gog: build lists dependencies " + deps);
|
||||||
if (deps != null) for (int i = 0; i < deps.length(); i++) { String d = deps.optString(i, ""); if (!d.isEmpty()) dependencies.add(d); }
|
|
||||||
if (!dependencies.isEmpty()) cb.onLog("gog: build lists dependencies " + deps);
|
|
||||||
|
|
||||||
cb.onProgress("Reading depot manifests…", 10);
|
cb.onProgress("Reading depot manifests…", 10);
|
||||||
List<DepotFile> files = new ArrayList<>();
|
List<DepotFile> files = new ArrayList<>();
|
||||||
@@ -268,8 +262,6 @@ public final class GogDownloadManager {
|
|||||||
String clientSecret = manifest.optString("clientSecret", null);
|
String clientSecret = manifest.optString("clientSecret", null);
|
||||||
if (clientSecret != null && !clientSecret.isEmpty()) GogPrefs.get(ctx).edit().putString("client_secret_" + game.gameId, clientSecret).apply();
|
if (clientSecret != null && !clientSecret.isEmpty()) GogPrefs.get(ctx).edit().putString("client_secret_" + game.gameId, clientSecret).apply();
|
||||||
out.result = new Result(pickExe(installPath, tempExe, game.title), gm.buildId, planned);
|
out.result = new Result(pickExe(installPath, tempExe, game.title), gm.buildId, planned);
|
||||||
out.result.dependencies = dependencies;
|
|
||||||
out.result.dependenciesRead = true;
|
|
||||||
return out;
|
return out;
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
out.error = "exception: " + e.getClass().getSimpleName() + (e.getMessage() != null ? ": " + e.getMessage() : "");
|
out.error = "exception: " + e.getClass().getSimpleName() + (e.getMessage() != null ? ": " + e.getMessage() : "");
|
||||||
@@ -1039,48 +1031,6 @@ public final class GogDownloadManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** The install size of the Windows build (English / all-language depots), or -1. Blocking. */
|
/** The install size of the Windows build (English / all-language depots), or -1. Blocking. */
|
||||||
/**
|
|
||||||
* The "dependencies" of the build [buildId] of [gameId] (else the newest Windows build), from
|
|
||||||
* its build manifest alone: no game file is fetched. Null when the builds or the manifest
|
|
||||||
* could not be had; empty when the build lists none. Blocking.
|
|
||||||
*/
|
|
||||||
public static List<String> fetchDependencies(String gameId, String buildId, String token) {
|
|
||||||
try {
|
|
||||||
String buildsUrl = "https://content-system.gog.com/products/" + gameId + "/os/windows/builds?generation=2";
|
|
||||||
String buildsJson = httpGet(buildsUrl, null);
|
|
||||||
if (buildsJson == null) buildsJson = httpGet(buildsUrl, token);
|
|
||||||
if (buildsJson == null) return null;
|
|
||||||
JSONArray items = new JSONObject(buildsJson).optJSONArray("items");
|
|
||||||
if (items == null || items.length() == 0) return null;
|
|
||||||
String manifestUrl = null;
|
|
||||||
for (int i = 0; i < items.length(); i++) {
|
|
||||||
JSONObject item = items.getJSONObject(i);
|
|
||||||
if (!"windows".equals(item.optString("os"))) continue;
|
|
||||||
String link = item.optString("link");
|
|
||||||
if (link == null || link.isEmpty()) link = item.optString("meta_url");
|
|
||||||
if (manifestUrl == null) manifestUrl = link;
|
|
||||||
if (buildId != null && !buildId.isEmpty() && buildId.equals(item.optString("build_id"))) { manifestUrl = link; break; }
|
|
||||||
}
|
|
||||||
if (manifestUrl == null || manifestUrl.isEmpty()) return null;
|
|
||||||
byte[] raw = fetchBytes(manifestUrl, token);
|
|
||||||
if (raw == null) return null;
|
|
||||||
String manifestStr = decompressBytes(raw);
|
|
||||||
if (manifestStr == null) return null;
|
|
||||||
JSONObject manifest = new JSONObject(manifestStr);
|
|
||||||
// A manifest without depots is not one this reads right: no list rather than an empty one.
|
|
||||||
JSONArray depots = manifest.optJSONArray("depots");
|
|
||||||
if (depots == null) { Log.w(TAG, "gog: build manifest for " + gameId + " has no depots; keys " + manifest.names()); return null; }
|
|
||||||
JSONArray deps = manifest.optJSONArray("dependencies");
|
|
||||||
List<String> out = new ArrayList<>();
|
|
||||||
if (deps != null) for (int i = 0; i < deps.length(); i++) { String d = deps.optString(i, ""); if (!d.isEmpty()) out.add(d); }
|
|
||||||
Log.i(TAG, "gog: build " + manifest.optString("buildId", buildId) + " of " + gameId + ": " + depots.length() + " depots, dependencies "
|
|
||||||
+ (manifest.has("dependencies") ? String.valueOf(deps) : "(none listed)"));
|
|
||||||
return out;
|
|
||||||
} catch (Exception e) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public static long fetchInstallSizeBytes(String gameId, String token) {
|
public static long fetchInstallSizeBytes(String gameId, String token) {
|
||||||
try {
|
try {
|
||||||
String buildsUrl = "https://content-system.gog.com/products/" + gameId + "/os/windows/builds?generation=2";
|
String buildsUrl = "https://content-system.gog.com/products/" + gameId + "/os/windows/builds?generation=2";
|
||||||
|
|||||||
@@ -90,6 +90,7 @@ import androidx.compose.ui.window.Dialog
|
|||||||
import androidx.compose.ui.window.DialogProperties
|
import androidx.compose.ui.window.DialogProperties
|
||||||
import coil.compose.AsyncImage
|
import coil.compose.AsyncImage
|
||||||
import coil.request.ImageRequest
|
import coil.request.ImageRequest
|
||||||
|
import androidx.compose.ui.platform.LocalInspectionMode
|
||||||
import com.droiddeck.launcher.R
|
import com.droiddeck.launcher.R
|
||||||
import com.droiddeck.launcher.core.FileUtils
|
import com.droiddeck.launcher.core.FileUtils
|
||||||
import com.droiddeck.launcher.files.InAppFilePicker
|
import com.droiddeck.launcher.files.InAppFilePicker
|
||||||
@@ -302,7 +303,8 @@ internal fun EditAppDialog(app: UserApps.App, onDismiss: () -> Unit, onSave: (St
|
|||||||
/** Open from the first frame; [onDismiss] once the closing animation has run. */
|
/** Open from the first frame; [onDismiss] once the closing animation has run. */
|
||||||
@Composable
|
@Composable
|
||||||
internal fun rememberShown(onDismiss: () -> Unit): MutableTransitionState<Boolean> {
|
internal fun rememberShown(onDismiss: () -> Unit): MutableTransitionState<Boolean> {
|
||||||
val shown = remember { MutableTransitionState(false).apply { targetState = true } }
|
val inspecting = LocalInspectionMode.current
|
||||||
|
val shown = remember { MutableTransitionState(inspecting).apply { targetState = true } }
|
||||||
LaunchedEffect(shown.currentState, shown.isIdle) { if (shown.isIdle && !shown.currentState && !shown.targetState) onDismiss() }
|
LaunchedEffect(shown.currentState, shown.isIdle) { if (shown.isIdle && !shown.currentState && !shown.targetState) onDismiss() }
|
||||||
return shown
|
return shown
|
||||||
}
|
}
|
||||||
@@ -507,7 +509,9 @@ private fun IconActions(onChoose: () -> Unit, clear: Pair<Int, () -> Unit>?) {
|
|||||||
/** Icons found in [repo], looked up off the main thread once the name has settled; [selected] is ringed. */
|
/** Icons found in [repo], looked up off the main thread once the name has settled; [selected] is ringed. */
|
||||||
@Composable
|
@Composable
|
||||||
private fun IconSuggestions(repo: String, selected: String?, onPick: (String) -> Unit) {
|
private fun IconSuggestions(repo: String, selected: String?, onPick: (String) -> Unit) {
|
||||||
|
val inspecting = LocalInspectionMode.current
|
||||||
val found by produceState<List<String>?>(null, repo) {
|
val found by produceState<List<String>?>(null, repo) {
|
||||||
|
if (inspecting) { value = emptyList(); return@produceState }
|
||||||
value = null
|
value = null
|
||||||
delay(500)
|
delay(500)
|
||||||
value = withContext(Dispatchers.IO) { runCatching { UserApps.githubIcons(repo) }.getOrDefault(emptyList()) }
|
value = withContext(Dispatchers.IO) { runCatching { UserApps.githubIcons(repo) }.getOrDefault(emptyList()) }
|
||||||
@@ -570,8 +574,10 @@ private fun FileRow(path: String?, onChoose: () -> Unit) {
|
|||||||
/** Whether the script's folder will be linked or copied in, worked out off the main thread. */
|
/** Whether the script's folder will be linked or copied in, worked out off the main thread. */
|
||||||
@Composable
|
@Composable
|
||||||
private fun FolderNote(scriptPath: String) {
|
private fun FolderNote(scriptPath: String) {
|
||||||
|
val inspecting = LocalInspectionMode.current
|
||||||
var plan by remember(scriptPath) { mutableStateOf<UserApps.ScriptPlan?>(null) }
|
var plan by remember(scriptPath) { mutableStateOf<UserApps.ScriptPlan?>(null) }
|
||||||
LaunchedEffect(scriptPath) {
|
LaunchedEffect(scriptPath) {
|
||||||
|
if (inspecting) return@LaunchedEffect
|
||||||
plan = withContext(Dispatchers.IO) { runCatching { UserApps.planScript(File(scriptPath)) }.getOrNull() }
|
plan = withContext(Dispatchers.IO) { runCatching { UserApps.planScript(File(scriptPath)) }.getOrNull() }
|
||||||
}
|
}
|
||||||
val p = plan
|
val p = plan
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -28,7 +28,6 @@ class ControllerActions(
|
|||||||
val onSteamButton: (Boolean) -> Unit,
|
val onSteamButton: (Boolean) -> Unit,
|
||||||
val onQamButton: (Boolean) -> Unit,
|
val onQamButton: (Boolean) -> Unit,
|
||||||
val onKeyboardButton: (Boolean) -> Unit,
|
val onKeyboardButton: (Boolean) -> Unit,
|
||||||
val onSelectSteam: (Boolean) -> Unit,
|
|
||||||
val onEditLayout: () -> Unit,
|
val onEditLayout: () -> Unit,
|
||||||
val onResetLayout: () -> Unit,
|
val onResetLayout: () -> Unit,
|
||||||
val onMapping: () -> Unit,
|
val onMapping: () -> Unit,
|
||||||
@@ -71,7 +70,6 @@ fun ColumnScope.ControllerRows(host: MenuHost, oscMode: String, c: ControllerPre
|
|||||||
ToggleRow(host, "controller-steam", stringResource(R.string.ctrl_steam_button), null, c.steamButton, onChange = a.onSteamButton)
|
ToggleRow(host, "controller-steam", stringResource(R.string.ctrl_steam_button), null, c.steamButton, onChange = a.onSteamButton)
|
||||||
ToggleRow(host, "controller-qam", stringResource(R.string.ctrl_qam_button), null, c.qamButton, onChange = a.onQamButton)
|
ToggleRow(host, "controller-qam", stringResource(R.string.ctrl_qam_button), null, c.qamButton, onChange = a.onQamButton)
|
||||||
ToggleRow(host, "controller-keyboard", stringResource(R.string.ctrl_keyboard_button), null, c.keyboardButton, onChange = a.onKeyboardButton)
|
ToggleRow(host, "controller-keyboard", stringResource(R.string.ctrl_keyboard_button), null, c.keyboardButton, onChange = a.onKeyboardButton)
|
||||||
ToggleRow(host, "controller-select-steam", stringResource(R.string.ctrl_select_steam), stringResource(R.string.ctrl_select_steam_hint), c.selectSteam, onChange = a.onSelectSteam)
|
|
||||||
SettingsRow(stringResource(R.string.ctrl_layout), if (c.customLayout) stringResource(R.string.ctrl_layout_custom) else stringResource(R.string.ctrl_layout_default)) {
|
SettingsRow(stringResource(R.string.ctrl_layout), if (c.customLayout) stringResource(R.string.ctrl_layout_custom) else stringResource(R.string.ctrl_layout_default)) {
|
||||||
Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||||
SecondaryButton(stringResource(R.string.ctrl_edit)) { a.onEditLayout() }
|
SecondaryButton(stringResource(R.string.ctrl_edit)) { a.onEditLayout() }
|
||||||
|
|||||||
@@ -15,16 +15,10 @@ import android.view.Gravity
|
|||||||
import android.view.HapticFeedbackConstants
|
import android.view.HapticFeedbackConstants
|
||||||
import android.view.MotionEvent
|
import android.view.MotionEvent
|
||||||
import android.view.View
|
import android.view.View
|
||||||
import android.view.ViewGroup
|
|
||||||
import android.widget.FrameLayout
|
import android.widget.FrameLayout
|
||||||
import android.widget.LinearLayout
|
import android.widget.LinearLayout
|
||||||
import android.widget.TextView
|
import android.widget.TextView
|
||||||
import com.droiddeck.launcher.input.DeckControls
|
import com.droiddeck.launcher.input.DeckControls
|
||||||
import com.droiddeck.launcher.input.PadBridge
|
|
||||||
import com.droiddeck.launcher.input.PadState
|
|
||||||
import com.droiddeck.launcher.session.SessionPrefs
|
|
||||||
import kotlin.math.atan2
|
|
||||||
import kotlin.math.hypot
|
|
||||||
import kotlin.math.min
|
import kotlin.math.min
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -32,8 +26,7 @@ import kotlin.math.min
|
|||||||
*
|
*
|
||||||
* Four tabs: the grips as a 2x2 grid (left grips on the left, upper above lower, as they sit on a
|
* Four tabs: the grips as a 2x2 grid (left grips on the left, upper above lower, as they sit on a
|
||||||
* Deck); either trackpad on its own with a bar to click it; and both trackpads with the grips in a
|
* Deck); either trackpad on its own with a bar to click it; and both trackpads with the grips in a
|
||||||
* row beneath. Given the [pad] (the unfolded screen's panel), a fifth: a whole gamepad, each side
|
* row beneath. A trackpad clicks from its bar or from a second finger while the first is down.
|
||||||
* an analog stick or a trackpad as the player picks. A trackpad clicks from its bar or from a second finger while the first is down.
|
|
||||||
* Drawn for OLED: true black, with outlines rather than filled surfaces, and the Steam blue only
|
* Drawn for OLED: true black, with outlines rather than filled surfaces, and the Steam blue only
|
||||||
* where something is being touched.
|
* where something is being touched.
|
||||||
*/
|
*/
|
||||||
@@ -43,29 +36,18 @@ class DeckControlsPanel(
|
|||||||
private val onClose: () -> Unit,
|
private val onClose: () -> Unit,
|
||||||
private val onSteamMenu: () -> Unit,
|
private val onSteamMenu: () -> Unit,
|
||||||
private val onQam: () -> Unit,
|
private val onQam: () -> Unit,
|
||||||
private val pad: PadBridge? = null,
|
|
||||||
) : LinearLayout(context) {
|
) : LinearLayout(context) {
|
||||||
private enum class Tab(val label: Int) { GAMEPAD(R.string.deck_tab_gamepad), GRIPS(R.string.deck_tab_grips), LEFT(R.string.deck_tab_left), RIGHT(R.string.deck_tab_right), BOTH(R.string.deck_tab_both) }
|
private enum class Tab(val label: Int) { GRIPS(R.string.deck_tab_grips), LEFT(R.string.deck_tab_left), RIGHT(R.string.deck_tab_right), BOTH(R.string.deck_tab_both) }
|
||||||
|
|
||||||
private val content = FrameLayout(context)
|
private val content = FrameLayout(context)
|
||||||
private val tabViews = HashMap<Tab, TextView>()
|
private val tabViews = HashMap<Tab, TextView>()
|
||||||
private val topBar: View by lazy { topBar() }
|
|
||||||
|
|
||||||
init {
|
init {
|
||||||
orientation = VERTICAL
|
orientation = VERTICAL
|
||||||
setBackgroundColor(Color.BLACK)
|
setBackgroundColor(Color.BLACK)
|
||||||
addView(topBar, LayoutParams(LayoutParams.MATCH_PARENT, dp(64)))
|
addView(topBar(), LayoutParams(LayoutParams.MATCH_PARENT, dp(64)))
|
||||||
addView(content, LayoutParams(LayoutParams.MATCH_PARENT, 0, 1f))
|
addView(content, LayoutParams(LayoutParams.MATCH_PARENT, 0, 1f))
|
||||||
select(if (pad != null) selectedWithPad else selected)
|
select(selected)
|
||||||
}
|
|
||||||
|
|
||||||
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
|
|
||||||
super.onSizeChanged(w, h, oldw, oldh)
|
|
||||||
// Held flat the gamepad has no Panels button, so another tab would have no way back:
|
|
||||||
// turning the phone from upright onto its side returns to the gamepad.
|
|
||||||
if (pad != null && selectedWithPad != Tab.GAMEPAD && !GamepadGeometry.tall(w.toFloat(), h.toFloat())) {
|
|
||||||
post { if (selectedWithPad != Tab.GAMEPAD) select(Tab.GAMEPAD) }
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onDetachedFromWindow() {
|
override fun onDetachedFromWindow() {
|
||||||
@@ -83,7 +65,6 @@ class DeckControlsPanel(
|
|||||||
background = outline(CORNER_PILL, SURFACE)
|
background = outline(CORNER_PILL, SURFACE)
|
||||||
setPadding(dp(4), dp(4), dp(4), dp(4))
|
setPadding(dp(4), dp(4), dp(4), dp(4))
|
||||||
for (tab in Tab.values()) {
|
for (tab in Tab.values()) {
|
||||||
if (tab == Tab.GAMEPAD && pad == null) continue
|
|
||||||
val view = TextView(context).apply {
|
val view = TextView(context).apply {
|
||||||
text = context.getString(tab.label)
|
text = context.getString(tab.label)
|
||||||
textSize = 14f
|
textSize = 14f
|
||||||
@@ -107,7 +88,7 @@ class DeckControlsPanel(
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun select(tab: Tab) {
|
private fun select(tab: Tab) {
|
||||||
if (pad != null) selectedWithPad = tab else selected = tab
|
selected = tab
|
||||||
DeckControls.releaseAll()
|
DeckControls.releaseAll()
|
||||||
for ((each, view) in tabViews) {
|
for ((each, view) in tabViews) {
|
||||||
val on = each == tab
|
val on = each == tab
|
||||||
@@ -115,15 +96,12 @@ class DeckControlsPanel(
|
|||||||
view.setTextColor(if (on) ON_ACCENT else TEXT_DIM)
|
view.setTextColor(if (on) ON_ACCENT else TEXT_DIM)
|
||||||
}
|
}
|
||||||
content.removeAllViews()
|
content.removeAllViews()
|
||||||
// The gamepad needs every row of the panel; held upright its Panels button brings the tabs back.
|
|
||||||
topBar.visibility = if (tab == Tab.GAMEPAD) View.GONE else View.VISIBLE
|
|
||||||
content.addView(
|
content.addView(
|
||||||
when (tab) {
|
when (tab) {
|
||||||
Tab.GRIPS -> gripsGrid()
|
Tab.GRIPS -> gripsGrid()
|
||||||
Tab.LEFT -> singlePad(right = false)
|
Tab.LEFT -> singlePad(right = false)
|
||||||
Tab.RIGHT -> singlePad(right = true)
|
Tab.RIGHT -> singlePad(right = true)
|
||||||
Tab.BOTH -> bothPads()
|
Tab.BOTH -> bothPads()
|
||||||
Tab.GAMEPAD -> gamepad(pad ?: return)
|
|
||||||
},
|
},
|
||||||
FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT),
|
FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT),
|
||||||
)
|
)
|
||||||
@@ -173,79 +151,6 @@ class DeckControlsPanel(
|
|||||||
addView(grips, LayoutParams(LayoutParams.MATCH_PARENT, dp(84)))
|
addView(grips, LayoutParams(LayoutParams.MATCH_PARENT, dp(84)))
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* A whole pad, placed for two thumbs rather than in columns (see [GamepadGeometry]): on each side
|
|
||||||
* a surface where the thumb rests - most of play is on the sticks or trackpads - and a short
|
|
||||||
* slide inward along its arc, the d-pad on the left and the face buttons on the right; the bumpers and triggers above, at the top of the arc; View, Steam, QAM and Menu in the
|
|
||||||
* middle, which a thumb only reaches on purpose. Each surface is an analog stick or a Steam
|
|
||||||
* trackpad, switched from its corner and remembered (SessionPrefs.gamepadSurface). Its tab bar
|
|
||||||
* is hidden; held upright, a Panels button brings the other tabs back, and held flat there is no
|
|
||||||
* room for one.
|
|
||||||
*/
|
|
||||||
private fun gamepad(pad: PadBridge): View = GamepadLayout(context).apply {
|
|
||||||
fun pill(label: String, write: (PadState, Boolean) -> Unit) = PadButton(context, pad, label, write)
|
|
||||||
place(surfaceSlot(pad, right = false), GamepadGeometry.Slot.LEFT_MAIN)
|
|
||||||
place(DirectionPad(context, pad), GamepadGeometry.Slot.LEFT_SECOND)
|
|
||||||
place(surfaceSlot(pad, right = true), GamepadGeometry.Slot.RIGHT_MAIN)
|
|
||||||
place(FaceButtons(context, pad), GamepadGeometry.Slot.RIGHT_SECOND)
|
|
||||||
place(pill("LT") { st, d -> st.leftTrigger = if (d) 1f else 0f }, GamepadGeometry.Slot.LEFT_OUTER_SHOULDER)
|
|
||||||
place(pill("LB") { st, d -> st.press(PadState.LB, d) }, GamepadGeometry.Slot.LEFT_INNER_SHOULDER)
|
|
||||||
place(pill("RB") { st, d -> st.press(PadState.RB, d) }, GamepadGeometry.Slot.RIGHT_INNER_SHOULDER)
|
|
||||||
place(pill("RT") { st, d -> st.rightTrigger = if (d) 1f else 0f }, GamepadGeometry.Slot.RIGHT_OUTER_SHOULDER)
|
|
||||||
place(pill("VIEW") { st, d -> st.press(PadState.SELECT, d) }, GamepadGeometry.Slot.VIEW)
|
|
||||||
place(centreTap("STEAM", context.getString(R.string.deck_open_steam_menu), onSteamMenu), GamepadGeometry.Slot.STEAM)
|
|
||||||
place(centreTap("\u2022\u2022\u2022", context.getString(R.string.drawer_open_qam), onQam), GamepadGeometry.Slot.QAM)
|
|
||||||
place(pill("MENU") { st, d -> st.press(PadState.START, d) }, GamepadGeometry.Slot.MENU)
|
|
||||||
place(centreTap("\u25a6 " + context.getString(R.string.deck_panels), context.getString(R.string.deck_more_controls)) { select(Tab.BOTH) },
|
|
||||||
GamepadGeometry.Slot.PANELS)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun centreTap(label: String, description: String, onClick: () -> Unit) = TextView(context).apply {
|
|
||||||
text = label
|
|
||||||
contentDescription = description
|
|
||||||
textSize = 13f
|
|
||||||
typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
|
|
||||||
letterSpacing = 0.08f
|
|
||||||
gravity = Gravity.CENTER
|
|
||||||
setTextColor(TEXT)
|
|
||||||
background = outline(CORNER_PILL, SURFACE)
|
|
||||||
setOnClickListener {
|
|
||||||
performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
|
|
||||||
onClick()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** One side's stick or trackpad, with a chip in its outer corner that swaps the two. */
|
|
||||||
private fun surfaceSlot(pad: PadBridge, right: Boolean): View = FrameLayout(context).apply {
|
|
||||||
val slot = this
|
|
||||||
fun show() {
|
|
||||||
slot.removeAllViews()
|
|
||||||
val stick = SessionPrefs.gamepadSurface(context, right) == SessionPrefs.SURFACE_STICK
|
|
||||||
// No caption: the switch in its corner says which it is.
|
|
||||||
slot.addView(if (stick) StickView(context, pad, right) else TrackpadView(context, right, captioned = false),
|
|
||||||
FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT))
|
|
||||||
val chip = TextView(context).apply {
|
|
||||||
text = "\u21c4"
|
|
||||||
contentDescription = context.getString(R.string.deck_surface_switch)
|
|
||||||
textSize = 14f
|
|
||||||
typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
|
|
||||||
gravity = Gravity.CENTER
|
|
||||||
setTextColor(TEXT_DIM)
|
|
||||||
background = outline(CORNER_PILL, SURFACE)
|
|
||||||
setOnClickListener {
|
|
||||||
performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
|
|
||||||
SessionPrefs.setGamepadSurface(context, right,
|
|
||||||
if (stick) SessionPrefs.SURFACE_TRACKPAD else SessionPrefs.SURFACE_STICK)
|
|
||||||
show()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// In the corner away from the thumb, so play does not swap it by accident.
|
|
||||||
slot.addView(chip, FrameLayout.LayoutParams(dp(30), dp(30),
|
|
||||||
(if (right) Gravity.START else Gravity.END) or Gravity.TOP).apply { setMargins(dp(6), dp(6), dp(6), dp(6)) })
|
|
||||||
}
|
|
||||||
show()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun roundButton(label: String, description: String, onClick: () -> Unit, wide: Boolean = false) =
|
private fun roundButton(label: String, description: String, onClick: () -> Unit, wide: Boolean = false) =
|
||||||
TextView(context).apply {
|
TextView(context).apply {
|
||||||
text = label
|
text = label
|
||||||
@@ -357,7 +262,7 @@ class DeckControlsPanel(
|
|||||||
* One trackpad: where the first finger is, as the Deck reports it (-1..1, y up), and a click
|
* One trackpad: where the first finger is, as the Deck reports it (-1..1, y up), and a click
|
||||||
* while a second finger is down.
|
* while a second finger is down.
|
||||||
*/
|
*/
|
||||||
private class TrackpadView(context: Context, private val right: Boolean, private val captioned: Boolean = true) : Surface(context) {
|
private class TrackpadView(context: Context, private val right: Boolean) : Surface(context) {
|
||||||
private var touching = false
|
private var touching = false
|
||||||
private var clicked = false
|
private var clicked = false
|
||||||
private var fingerX = 0f
|
private var fingerX = 0f
|
||||||
@@ -378,7 +283,7 @@ class DeckControlsPanel(
|
|||||||
canvas.drawLine(cx, cy - reach, cx, cy + reach, guide)
|
canvas.drawLine(cx, cy - reach, cx, cy + reach, guide)
|
||||||
captionPaint.textSize = 12 * density
|
captionPaint.textSize = 12 * density
|
||||||
captionPaint.color = if (touching) ACCENT else TEXT_DIM
|
captionPaint.color = if (touching) ACCENT else TEXT_DIM
|
||||||
if (captioned) canvas.drawText((if (right) context.getString(R.string.deck_right_trackpad) else context.getString(R.string.deck_left_trackpad)).uppercase(), cx, 28 * density, captionPaint)
|
canvas.drawText((if (right) context.getString(R.string.deck_right_trackpad) else context.getString(R.string.deck_left_trackpad)).uppercase(), cx, 28 * density, captionPaint)
|
||||||
if (touching) {
|
if (touching) {
|
||||||
val radius = 56 * density
|
val radius = 56 * density
|
||||||
glow.shader = RadialGradient(fingerX, fingerY, radius, ACCENT_GLOW, Color.TRANSPARENT, Shader.TileMode.CLAMP)
|
glow.shader = RadialGradient(fingerX, fingerY, radius, ACCENT_GLOW, Color.TRANSPARENT, Shader.TileMode.CLAMP)
|
||||||
@@ -428,271 +333,9 @@ class DeckControlsPanel(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A pad button held while a finger is on it, written into the shared pad as the on-screen pad does. */
|
|
||||||
private class PadButton(
|
|
||||||
context: Context,
|
|
||||||
private val pad: PadBridge,
|
|
||||||
label: String,
|
|
||||||
private val write: (PadState, Boolean) -> Unit,
|
|
||||||
) : HoldButton(context, label, null, { down -> pad.applyTouch { write(it, down) } }) {
|
|
||||||
override fun onDetachedFromWindow() {
|
|
||||||
pad.applyTouch { write(it, false) }
|
|
||||||
super.onDetachedFromWindow()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* An analog stick that centres where the thumb lands, so it is never missed: the knob follows
|
|
||||||
* the finger from there out to the ring. Tapping it again and holding (within [CLICK_MS]) is
|
|
||||||
* the stick's click - L3 or R3 - for as long as the thumb stays down.
|
|
||||||
*/
|
|
||||||
private class StickView(context: Context, private val pad: PadBridge, private val right: Boolean) : Surface(context) {
|
|
||||||
private var touching = false
|
|
||||||
private var clicking = false
|
|
||||||
private var lastUp = 0L
|
|
||||||
private var originX = 0f
|
|
||||||
private var originY = 0f
|
|
||||||
private var knobX = 0f
|
|
||||||
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 fun reach() = min(width, height) * 0.30f
|
|
||||||
|
|
||||||
override fun onDraw(canvas: Canvas) {
|
|
||||||
drawSurface(canvas, clicking)
|
|
||||||
val cx = if (touching) originX else width / 2f
|
|
||||||
val cy = if (touching) originY else height / 2f
|
|
||||||
ring.strokeWidth = 2 * density
|
|
||||||
ring.color = if (touching) ACCENT else LINE
|
|
||||||
canvas.drawCircle(cx, cy, reach(), ring)
|
|
||||||
knob.color = if (touching) ACCENT else KNOB
|
|
||||||
canvas.drawCircle(cx + knobX, cy + knobY, reach() * 0.45f, knob)
|
|
||||||
}
|
|
||||||
|
|
||||||
@SuppressLint("ClickableViewAccessibility")
|
|
||||||
override fun onTouchEvent(event: MotionEvent): Boolean {
|
|
||||||
val r = reach().coerceAtLeast(1f)
|
|
||||||
when (event.actionMasked) {
|
|
||||||
MotionEvent.ACTION_DOWN -> {
|
|
||||||
// Centred where the thumb lands, but kept far enough in for the ring to fit.
|
|
||||||
originX = event.x.coerceIn(r, (width - r).coerceAtLeast(r))
|
|
||||||
originY = event.y.coerceIn(r, (height - r).coerceAtLeast(r))
|
|
||||||
touching = true
|
|
||||||
performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
|
|
||||||
if (event.eventTime - lastUp < CLICK_MS) setClick(true)
|
|
||||||
follow(event.x, event.y, r)
|
|
||||||
}
|
|
||||||
MotionEvent.ACTION_MOVE -> follow(event.getX(0), event.getY(0), r)
|
|
||||||
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
|
|
||||||
touching = false
|
|
||||||
lastUp = event.eventTime
|
|
||||||
setClick(false)
|
|
||||||
move(0f, 0f, 1f)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun follow(x: Float, y: Float, r: Float) {
|
|
||||||
var dx = x - originX
|
|
||||||
var dy = y - originY
|
|
||||||
val length = hypot(dx, dy)
|
|
||||||
if (length > r) { dx *= r / length; dy *= r / length }
|
|
||||||
move(dx, dy, r)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun move(dx: Float, dy: Float, r: Float) {
|
|
||||||
knobX = dx
|
|
||||||
knobY = dy
|
|
||||||
pad.applyTouch { s ->
|
|
||||||
if (right) { s.rightX = dx / r; s.rightY = dy / r } else { s.leftX = dx / r; s.leftY = dy / r }
|
|
||||||
}
|
|
||||||
invalidate()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun setClick(down: Boolean) {
|
|
||||||
if (clicking == down) return
|
|
||||||
clicking = down
|
|
||||||
if (down) performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
|
|
||||||
pad.applyTouch { s -> s.press(if (right) PadState.R3 else PadState.L3, down) }
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onDetachedFromWindow() {
|
|
||||||
setClick(false)
|
|
||||||
if (knobX != 0f || knobY != 0f) move(0f, 0f, 1f)
|
|
||||||
super.onDetachedFromWindow()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The d-pad: the direction is the finger's angle from the centre, diagonals included. */
|
|
||||||
private class DirectionPad(context: Context, private val pad: PadBridge) : View(context) {
|
|
||||||
private val density = resources.displayMetrics.density
|
|
||||||
private var held = 0 // bits: 1 up, 2 right, 4 down, 8 left
|
|
||||||
private val arm = Paint(Paint.ANTI_ALIAS_FLAG)
|
|
||||||
private val rect = RectF()
|
|
||||||
|
|
||||||
override fun onDraw(canvas: Canvas) {
|
|
||||||
val size = min(width, height) * 0.86f
|
|
||||||
val cx = width / 2f
|
|
||||||
val cy = height / 2f
|
|
||||||
val half = size / 2f
|
|
||||||
val thick = size / 3f / 2f
|
|
||||||
fun armRect(bit: Int, l: Float, t: Float, r: Float, b: Float) {
|
|
||||||
arm.color = if (held and bit != 0) ACCENT else KNOB
|
|
||||||
rect.set(l, t, r, b)
|
|
||||||
canvas.drawRoundRect(rect, 8 * density, 8 * density, arm)
|
|
||||||
}
|
|
||||||
armRect(1, cx - thick, cy - half, cx + thick, cy - thick)
|
|
||||||
armRect(4, cx - thick, cy + thick, cx + thick, cy + half)
|
|
||||||
armRect(8, cx - half, cy - thick, cx - thick, cy + thick)
|
|
||||||
armRect(2, cx + thick, cy - thick, cx + half, cy + thick)
|
|
||||||
arm.color = KNOB
|
|
||||||
canvas.drawRect(cx - thick, cy - thick, cx + thick, cy + thick, arm)
|
|
||||||
}
|
|
||||||
|
|
||||||
@SuppressLint("ClickableViewAccessibility")
|
|
||||||
override fun onTouchEvent(event: MotionEvent): Boolean {
|
|
||||||
val bits = when (event.actionMasked) {
|
|
||||||
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_MOVE -> {
|
|
||||||
val dx = event.getX(0) - width / 2f
|
|
||||||
val dy = event.getY(0) - height / 2f
|
|
||||||
if (hypot(dx, dy) < min(width, height) * 0.08f) 0 else {
|
|
||||||
// Eight sectors of 45 degrees, starting with right and going clockwise.
|
|
||||||
val sector = ((Math.toDegrees(atan2(dy.toDouble(), dx.toDouble())) + 360 + 22.5) % 360 / 45).toInt()
|
|
||||||
intArrayOf(2, 2 or 4, 4, 4 or 8, 8, 8 or 1, 1, 1 or 2)[sector]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else -> 0
|
|
||||||
}
|
|
||||||
set(bits)
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun set(bits: Int) {
|
|
||||||
if (bits == held) return
|
|
||||||
if (bits and held.inv() != 0) performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
|
|
||||||
held = bits
|
|
||||||
pad.applyTouch { s ->
|
|
||||||
s.up = bits and 1 != 0; s.right = bits and 2 != 0; s.down = bits and 4 != 0; s.left = bits and 8 != 0
|
|
||||||
}
|
|
||||||
invalidate()
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onDetachedFromWindow() {
|
|
||||||
set(0)
|
|
||||||
super.onDetachedFromWindow()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A, B, X and Y in a diamond, as on a Deck; several fingers can hold several at once. */
|
|
||||||
private class FaceButtons(context: Context, private val pad: PadBridge) : View(context) {
|
|
||||||
private val buttons = listOf(PadState.Y to "Y", PadState.B to "B", PadState.A to "A", PadState.X to "X")
|
|
||||||
private var held = emptySet<Int>()
|
|
||||||
private val fill = Paint(Paint.ANTI_ALIAS_FLAG)
|
|
||||||
private val text = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
|
||||||
textAlign = Paint.Align.CENTER
|
|
||||||
typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Top, right, bottom, left - the centre of each, and the radius of all. */
|
|
||||||
private fun layout(): Pair<List<Pair<Float, Float>>, Float> {
|
|
||||||
val cx = width / 2f
|
|
||||||
val cy = height / 2f
|
|
||||||
val spread = min(width, height) * 0.30f
|
|
||||||
val radius = min(width, height) * 0.16f
|
|
||||||
return listOf(cx to cy - spread, cx + spread to cy, cx to cy + spread, cx - spread to cy) to radius
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onDraw(canvas: Canvas) {
|
|
||||||
val (centres, radius) = layout()
|
|
||||||
text.textSize = radius * 0.9f
|
|
||||||
buttons.forEachIndexed { i, (button, label) ->
|
|
||||||
val (x, y) = centres[i]
|
|
||||||
val down = button in held
|
|
||||||
fill.color = if (down) ACCENT else KNOB
|
|
||||||
canvas.drawCircle(x, y, radius, fill)
|
|
||||||
text.color = if (down) ON_ACCENT else TEXT
|
|
||||||
canvas.drawText(label, x, y + text.textSize * 0.35f, text)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@SuppressLint("ClickableViewAccessibility")
|
|
||||||
override fun onTouchEvent(event: MotionEvent): Boolean {
|
|
||||||
val (centres, radius) = layout()
|
|
||||||
val now = HashSet<Int>()
|
|
||||||
val ending = event.actionMasked == MotionEvent.ACTION_UP || event.actionMasked == MotionEvent.ACTION_CANCEL
|
|
||||||
if (!ending) for (p in 0 until event.pointerCount) {
|
|
||||||
if (event.actionMasked == MotionEvent.ACTION_POINTER_UP && p == event.actionIndex) continue
|
|
||||||
val x = event.getX(p)
|
|
||||||
val y = event.getY(p)
|
|
||||||
// The nearest button within reach, so a thumb between two still lands on one.
|
|
||||||
val nearest = centres.indices.minByOrNull { hypot(centres[it].first - x, centres[it].second - y) } ?: continue
|
|
||||||
if (hypot(centres[nearest].first - x, centres[nearest].second - y) <= radius * 1.6f) now.add(buttons[nearest].first)
|
|
||||||
}
|
|
||||||
set(now)
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun set(now: Set<Int>) {
|
|
||||||
if (now == held) return
|
|
||||||
if ((now - held).isNotEmpty()) performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
|
|
||||||
val before = held
|
|
||||||
held = now
|
|
||||||
pad.applyTouch { s -> for (b in before + now) s.press(b, b in now) }
|
|
||||||
invalidate()
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onDetachedFromWindow() {
|
|
||||||
set(emptySet())
|
|
||||||
super.onDetachedFromWindow()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Lays its controls out where [GamepadGeometry] puts them for the panel's size. */
|
|
||||||
private class GamepadLayout(context: Context) : ViewGroup(context) {
|
|
||||||
private val slots = LinkedHashMap<View, GamepadGeometry.Slot>()
|
|
||||||
|
|
||||||
fun place(view: View, slot: GamepadGeometry.Slot) {
|
|
||||||
slots[view] = slot
|
|
||||||
addView(view)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun boxes(w: Int, h: Int) = GamepadGeometry.layout(w.toFloat(), h.toFloat(), resources.displayMetrics.density)
|
|
||||||
|
|
||||||
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
|
|
||||||
val w = MeasureSpec.getSize(widthMeasureSpec)
|
|
||||||
val h = MeasureSpec.getSize(heightMeasureSpec)
|
|
||||||
setMeasuredDimension(w, h)
|
|
||||||
val boxes = boxes(w, h)
|
|
||||||
for ((view, slot) in slots) {
|
|
||||||
val box = boxes[slot]
|
|
||||||
view.visibility = if (box == null) View.GONE else View.VISIBLE
|
|
||||||
if (box == null) continue
|
|
||||||
view.measure(MeasureSpec.makeMeasureSpec(box.width.toInt().coerceAtLeast(1), MeasureSpec.EXACTLY),
|
|
||||||
MeasureSpec.makeMeasureSpec(box.height.toInt().coerceAtLeast(1), MeasureSpec.EXACTLY))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
|
|
||||||
val boxes = boxes(r - l, b - t)
|
|
||||||
for ((view, slot) in slots) {
|
|
||||||
val box = boxes[slot] ?: continue
|
|
||||||
val left = box.left.toInt()
|
|
||||||
val top = box.top.toInt()
|
|
||||||
view.layout(left, top, left + box.width.toInt().coerceAtLeast(1), top + box.height.toInt().coerceAtLeast(1))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
/** A second press on a stick this soon after the last is its click (L3, R3). */
|
|
||||||
private const val CLICK_MS = 300L
|
|
||||||
|
|
||||||
/** The tab last shown, kept for the session so reopening the panel lands where it was. */
|
/** The tab last shown, kept for the session so reopening the panel lands where it was. */
|
||||||
private var selected = Tab.BOTH
|
private var selected = Tab.BOTH
|
||||||
/** The same for the unfolded screen's panel, which opens on the gamepad. */
|
|
||||||
private var selectedWithPad = Tab.GAMEPAD
|
|
||||||
|
|
||||||
private const val CORNER = 20f
|
private const val CORNER = 20f
|
||||||
private const val CORNER_PILL = 22f
|
private const val CORNER_PILL = 22f
|
||||||
@@ -705,6 +348,5 @@ class DeckControlsPanel(
|
|||||||
private val GUIDE = Color.rgb(0x16, 0x18, 0x1B)
|
private val GUIDE = Color.rgb(0x16, 0x18, 0x1B)
|
||||||
private val TEXT = Color.rgb(0xF2, 0xF4, 0xF7)
|
private val TEXT = Color.rgb(0xF2, 0xF4, 0xF7)
|
||||||
private val TEXT_DIM = Color.rgb(0x7A, 0x80, 0x8A)
|
private val TEXT_DIM = Color.rgb(0x7A, 0x80, 0x8A)
|
||||||
private val KNOB = Color.rgb(0x2A, 0x2D, 0x33)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,455 +0,0 @@
|
|||||||
package com.droiddeck.launcher.ui
|
|
||||||
|
|
||||||
import android.os.Build
|
|
||||||
import androidx.compose.animation.AnimatedVisibility
|
|
||||||
import androidx.compose.animation.core.MutableTransitionState
|
|
||||||
import androidx.compose.animation.core.Spring
|
|
||||||
import androidx.compose.animation.core.animateFloatAsState
|
|
||||||
import androidx.compose.animation.expandHorizontally
|
|
||||||
import androidx.compose.animation.fadeIn
|
|
||||||
import androidx.compose.animation.fadeOut
|
|
||||||
import androidx.compose.animation.slideInVertically
|
|
||||||
import androidx.compose.animation.slideOutVertically
|
|
||||||
import androidx.compose.foundation.Image
|
|
||||||
import androidx.compose.foundation.LocalIndication
|
|
||||||
import androidx.compose.foundation.background
|
|
||||||
import androidx.compose.foundation.border
|
|
||||||
import androidx.compose.foundation.clickable
|
|
||||||
import androidx.compose.foundation.horizontalScroll
|
|
||||||
import androidx.compose.foundation.hoverable
|
|
||||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
|
||||||
import androidx.compose.foundation.interaction.collectIsPressedAsState
|
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
|
||||||
import androidx.compose.foundation.layout.Box
|
|
||||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
|
||||||
import androidx.compose.foundation.layout.Column
|
|
||||||
import androidx.compose.foundation.layout.Row
|
|
||||||
import androidx.compose.foundation.layout.Spacer
|
|
||||||
import androidx.compose.foundation.layout.fillMaxSize
|
|
||||||
import androidx.compose.foundation.layout.fillMaxWidth
|
|
||||||
import androidx.compose.foundation.layout.height
|
|
||||||
import androidx.compose.foundation.layout.heightIn
|
|
||||||
import androidx.compose.foundation.layout.padding
|
|
||||||
import androidx.compose.foundation.layout.size
|
|
||||||
import androidx.compose.foundation.layout.width
|
|
||||||
import androidx.compose.foundation.rememberScrollState
|
|
||||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
|
||||||
import androidx.compose.foundation.verticalScroll
|
|
||||||
import androidx.compose.material.icons.Icons
|
|
||||||
import androidx.compose.material.icons.filled.Add
|
|
||||||
import androidx.compose.material.icons.outlined.Apps
|
|
||||||
import androidx.compose.material.icons.outlined.DesktopWindows
|
|
||||||
import androidx.compose.material.icons.outlined.Storefront
|
|
||||||
import androidx.compose.material.icons.outlined.Terminal
|
|
||||||
import androidx.compose.material3.CircularProgressIndicator
|
|
||||||
import androidx.compose.material3.Icon
|
|
||||||
import androidx.compose.material3.MaterialTheme
|
|
||||||
import androidx.compose.material3.Text
|
|
||||||
import androidx.compose.runtime.Composable
|
|
||||||
import androidx.compose.runtime.LaunchedEffect
|
|
||||||
import androidx.compose.runtime.getValue
|
|
||||||
import androidx.compose.runtime.key
|
|
||||||
import androidx.compose.runtime.mutableStateOf
|
|
||||||
import androidx.compose.runtime.produceState
|
|
||||||
import androidx.compose.runtime.remember
|
|
||||||
import androidx.compose.runtime.saveable.rememberSaveable
|
|
||||||
import androidx.compose.runtime.setValue
|
|
||||||
import androidx.compose.ui.Alignment
|
|
||||||
import androidx.compose.ui.Modifier
|
|
||||||
import androidx.compose.ui.draw.blur
|
|
||||||
import androidx.compose.ui.draw.clip
|
|
||||||
import androidx.compose.ui.draw.clipToBounds
|
|
||||||
import androidx.compose.ui.zIndex
|
|
||||||
import androidx.compose.ui.focus.focusRequester
|
|
||||||
import androidx.compose.ui.geometry.Offset
|
|
||||||
import androidx.compose.ui.geometry.Rect
|
|
||||||
import androidx.compose.ui.graphics.Brush
|
|
||||||
import androidx.compose.ui.graphics.Color
|
|
||||||
import androidx.compose.ui.graphics.graphicsLayer
|
|
||||||
import androidx.compose.ui.layout.ContentScale
|
|
||||||
import androidx.compose.ui.layout.boundsInRoot
|
|
||||||
import androidx.compose.ui.layout.onGloballyPositioned
|
|
||||||
import androidx.compose.ui.platform.LocalContext
|
|
||||||
import androidx.compose.ui.platform.LocalDensity
|
|
||||||
import androidx.compose.ui.res.painterResource
|
|
||||||
import androidx.compose.ui.res.pluralStringResource
|
|
||||||
import androidx.compose.ui.res.stringResource
|
|
||||||
import androidx.compose.ui.semantics.Role
|
|
||||||
import androidx.compose.ui.semantics.contentDescription
|
|
||||||
import androidx.compose.ui.semantics.semantics
|
|
||||||
import androidx.compose.ui.text.font.FontWeight
|
|
||||||
import androidx.compose.ui.text.style.TextOverflow
|
|
||||||
import androidx.compose.ui.unit.Dp
|
|
||||||
import androidx.compose.ui.unit.dp
|
|
||||||
import androidx.compose.ui.unit.sp
|
|
||||||
import coil.compose.AsyncImage
|
|
||||||
import com.droiddeck.launcher.R
|
|
||||||
import com.droiddeck.launcher.core.FileUtils
|
|
||||||
import com.droiddeck.launcher.frontend.Library
|
|
||||||
import com.droiddeck.launcher.runtime.UserApps
|
|
||||||
import com.droiddeck.launcher.session.SessionService
|
|
||||||
import com.droiddeck.launcher.store.UserAppsState
|
|
||||||
import kotlinx.coroutines.Dispatchers
|
|
||||||
import kotlinx.coroutines.launch
|
|
||||||
import kotlinx.coroutines.withContext
|
|
||||||
|
|
||||||
// The Desktop tab in the Steam tab's shape: a tilted wall of little windows behind the word and
|
|
||||||
// one big Open desktop, with Play's lip and lifted sheet under it (Display, Controls, Session and
|
|
||||||
// Files). Under the hero the page scrolls to two shelves - the apps that run in the desktop, and
|
|
||||||
// what can be added - and the hero folds into a slim header as it goes.
|
|
||||||
|
|
||||||
/** The desktop's own chips: its session settings, then Files. */
|
|
||||||
private val DESKTOP_TABS = modeSheetTabs(steam = false) + SheetTab.FILES
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
internal fun DesktopPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier, onSelect: (String) -> Unit) {
|
|
||||||
val ctx = LocalContext.current
|
|
||||||
val density = LocalDensity.current
|
|
||||||
val narrow = LocalNarrowPane.current
|
|
||||||
val colors = MaterialTheme.colorScheme
|
|
||||||
LaunchedEffect(Unit) { UserAppsState.refresh(ctx) }
|
|
||||||
// Flathub's installed apps sit with the others on the dock.
|
|
||||||
LaunchedEffect(s.ready) { com.droiddeck.launcher.store.StoreState.refresh(ctx) }
|
|
||||||
val installed = s.emulators.filter { it.installed }
|
|
||||||
val apps = UserAppsState.items
|
|
||||||
var adding by rememberSaveable { mutableStateOf(false) }
|
|
||||||
val mode = SessionService.MODE_DESKTOP
|
|
||||||
val tabs = DESKTOP_TABS.map { it to sheetTabLabel(it) }
|
|
||||||
val open = if (s.desktopInstalled) stringResource(R.string.content_open_desktop) else stringResource(R.string.content_install_open_desktop)
|
|
||||||
// Opened from a card: the page floods out of it, its picture on the tile.
|
|
||||||
fun openFrom(at: Rect?, art: Any?, page: String) {
|
|
||||||
at?.let { PageOrigin.mark(Origin(it, 16f * density.density, art = art)) }
|
|
||||||
onSelect(page)
|
|
||||||
}
|
|
||||||
|
|
||||||
// The Steam tab's shape, the whole pane: the dock of apps along the top of the wall, the word
|
|
||||||
// and Open desktop at the foot, and nothing under the settings sheet but the hero itself.
|
|
||||||
LiftHero(
|
|
||||||
key = "desktop", tabs = tabs,
|
|
||||||
onOpen = a.onDesktopSettings, onPrimary = a.onDesktop,
|
|
||||||
modifier = modifier.clipToBounds(),
|
|
||||||
start = if (narrow) 20.dp else 44.dp, bottom = if (narrow) 20.dp else 44.dp,
|
|
||||||
background = {
|
|
||||||
DesktopWall(installed.map { it.iconRes } + apps.mapNotNull { it.icon })
|
|
||||||
},
|
|
||||||
scrim = { lifted ->
|
|
||||||
WallFade()
|
|
||||||
// Over the fades, so the cards read at full strength; gone as the sheet lifts, so
|
|
||||||
// nothing but the wall is behind it.
|
|
||||||
Box(Modifier.graphicsLayer { val v = lifted(); alpha = 1f - v; translationY = -12.dp.toPx() * v }) {
|
|
||||||
DesktopDock(s, a, installed, apps, openFrom = ::openFrom)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
words = {
|
|
||||||
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
|
||||||
// The word at the wordmark's size.
|
|
||||||
Text(
|
|
||||||
stringResource(R.string.rail_desktop), fontSize = if (narrow) 30.sp else 42.sp, lineHeight = if (narrow) 34.sp else 46.sp,
|
|
||||||
fontWeight = FontWeight.Black, color = colors.onBackground,
|
|
||||||
)
|
|
||||||
BusyChip(s)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
button = { click ->
|
|
||||||
// Enabled without a runtime or the desktop: the session's loading screen installs them first.
|
|
||||||
PrimaryButton(open, enabled = !s.busy, main = true, large = true, icon = Icons.Outlined.DesktopWindows, onClick = click)
|
|
||||||
},
|
|
||||||
beside = {
|
|
||||||
// Flathub, whose apps run in the desktop: its storefront floods out of this button.
|
|
||||||
HeroIconButton(Icons.Outlined.Storefront, stringResource(R.string.flathub_name), FlathubTeal, "desktop:flathub") { at -> openFrom(at, null, "store") }
|
|
||||||
// Add your own app or game.
|
|
||||||
HeroIconButton(Icons.Filled.Add, stringResource(R.string.user_apps_add), null, "desktop:add") { if (!s.busy) adding = true }
|
|
||||||
},
|
|
||||||
rows = { tab ->
|
|
||||||
if (tab == SheetTab.FILES) DesktopFiles(s, a)
|
|
||||||
else a.modeSheet(mode, tab, SheetExtras())
|
|
||||||
},
|
|
||||||
)
|
|
||||||
if (adding && !s.busy) AddAppDialog(s.ready, onDismiss = { adding = false }) { request, label -> UserAppsState.add(ctx, request, label) }
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The dock along the top of the Desktop hero: what runs in the desktop (emulators installed, apps
|
|
||||||
* added, Flathub's installed apps), then the emulators that can be added - one
|
|
||||||
* row of cards that scrolls sideways, over the wall. It sinks back with the wall as the sheet lifts.
|
|
||||||
*/
|
|
||||||
@Composable
|
|
||||||
private fun DesktopDock(
|
|
||||||
s: FrontEndState, a: FrontEndActions, installed: List<Library.Emulator>, apps: List<UserApps.App>,
|
|
||||||
openFrom: (Rect?, Any?, String) -> Unit,
|
|
||||||
) {
|
|
||||||
val colors = MaterialTheme.colorScheme
|
|
||||||
val pal = LocalPalette.current
|
|
||||||
val narrow = LocalNarrowPane.current
|
|
||||||
val available = s.emulators.filter { !it.installed }
|
|
||||||
val flatpaks = com.droiddeck.launcher.store.StoreState.installed
|
|
||||||
val keys = installed.map { "emu:${it.id}" } + apps.map { "user:${it.key}" } + flatpaks.map { "flatpak:${it.id}" }
|
|
||||||
// Where the last of your apps sits, for a new emulator's dot to land after it.
|
|
||||||
var lastAt by remember { mutableStateOf<Rect?>(null) }
|
|
||||||
var dockAt by remember { mutableStateOf<Rect?>(null) }
|
|
||||||
val seen = remember { mutableSetOf<String>() }
|
|
||||||
val mounted = remember { booleanArrayOf(false) }
|
|
||||||
LaunchedEffect(Unit) { mounted[0] = true }
|
|
||||||
val scroll = rememberScrollState()
|
|
||||||
// Nothing yet (the emulators' catalog still on its way): no heading over an empty row.
|
|
||||||
if (keys.isEmpty() && available.isEmpty() && UserAppsState.working == null && UserAppsState.lastError == null) return
|
|
||||||
Column(Modifier.fillMaxWidth().padding(top = if (narrow) 14.dp else 22.dp)) {
|
|
||||||
Text(
|
|
||||||
stringResource(R.string.user_apps_section).uppercase(), fontSize = 11.sp, fontWeight = FontWeight.Bold, letterSpacing = 1.6.sp,
|
|
||||||
color = colors.onSurfaceVariant, modifier = Modifier.padding(start = if (narrow) 20.dp else 44.dp, bottom = 8.dp),
|
|
||||||
)
|
|
||||||
Row(
|
|
||||||
horizontalArrangement = Arrangement.spacedBy(10.dp), verticalAlignment = Alignment.Top,
|
|
||||||
modifier = Modifier.fillMaxWidth().onGloballyPositioned { dockAt = it.boundsInRoot() }
|
|
||||||
.edgeFade(scroll).horizontalScroll(scroll).padding(start = if (narrow) 20.dp else 44.dp, end = 20.dp, top = 2.dp, bottom = 4.dp),
|
|
||||||
) {
|
|
||||||
keys.forEachIndexed { i, k ->
|
|
||||||
key(k) {
|
|
||||||
// A card that arrives after the dock is up (an emulator just installed) opens in.
|
|
||||||
val state = remember { MutableTransitionState(!mounted[0] || k in seen) }.apply { targetState = true }
|
|
||||||
LaunchedEffect(Unit) { seen += k }
|
|
||||||
AnimatedVisibility(state, enter = expandHorizontally(Motion.sp(0.75f)) + fadeIn(Motion.tw(300, 80))) {
|
|
||||||
Box(if (i == keys.lastIndex) Modifier.onGloballyPositioned { lastAt = it.boundsInRoot() } else Modifier) {
|
|
||||||
val e = installed.firstOrNull { "emu:${it.id}" == k }
|
|
||||||
val flatpak = flatpaks.firstOrNull { "flatpak:${it.id}" == k }
|
|
||||||
val app = apps.firstOrNull { "user:${it.key}" == k }
|
|
||||||
if (e != null) {
|
|
||||||
val system = if (e.systemRes != 0) stringResource(e.systemRes) else e.system.replaceFirstChar { c -> c.uppercase() }
|
|
||||||
DesktopCard(
|
|
||||||
k, e.name,
|
|
||||||
if (e.id == "retroarch") system else "$system · " + pluralStringResource(R.plurals.mode_added_count, e.games.size, e.games.size),
|
|
||||||
art = e.iconRes, first = i == 0,
|
|
||||||
) { at -> openFrom(at, e.iconRes, k) }
|
|
||||||
} else if (flatpak != null) DesktopCard(
|
|
||||||
k, flatpak.name, flatpak.summary ?: stringResource(R.string.flathub_name),
|
|
||||||
art = flatpak.icon ?: com.droiddeck.launcher.store.FlathubApi.iconUrl(flatpak.id), first = i == 0,
|
|
||||||
) { at ->
|
|
||||||
// Its page on Flathub: open, update or remove it there.
|
|
||||||
com.droiddeck.launcher.store.StoreState.openRequest = flatpak.id
|
|
||||||
openFrom(at, flatpak.icon, "store")
|
|
||||||
} else if (app != null) DesktopCard(k, app.name, stringResource(app.kind.label()), art = app.icon, fallback = if (app.kind == UserApps.Kind.SCRIPT) Icons.Outlined.Terminal else Icons.Outlined.Apps, first = i == 0) { at ->
|
|
||||||
openFrom(at, app.icon, k)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Between yours and what can be added: a thin rule.
|
|
||||||
if (keys.isNotEmpty()) Box(Modifier.padding(horizontal = 4.dp).width(1.dp).height(120.dp).background(pal.line2))
|
|
||||||
available.forEach { e ->
|
|
||||||
key(e.id) {
|
|
||||||
val pkg = Library.packageId(e.id)?.let { id -> s.packages?.firstOrNull { it.id == id } }
|
|
||||||
val busyHere = pkg != null && s.packageBusyId == pkg.id
|
|
||||||
val canGet = pkg != null && !s.busy && s.packageBusyId == null && s.ready && !s.packageCatalogLoading && !s.sessionRunning
|
|
||||||
val system = if (e.systemRes != 0) stringResource(e.systemRes) else e.system.replaceFirstChar { c -> c.uppercase() }
|
|
||||||
DesktopCard(
|
|
||||||
"emu:${e.id}", e.name, if (busyHere) (s.packageStage ?: stringResource(R.string.store_installing)) else system,
|
|
||||||
art = e.iconRes, badge = if (busyHere) null else stringResource(R.string.comp_get),
|
|
||||||
progress = if (busyHere) s.packagePercent else null, first = keys.isEmpty() && e == available.first(),
|
|
||||||
) { at ->
|
|
||||||
// Get installs it there and then, and a dot flies to where its card will be;
|
|
||||||
// when it cannot (no runtime, a session running), its page says why.
|
|
||||||
if (canGet && pkg != null && at != null) {
|
|
||||||
a.onInstallPackage(pkg.id)
|
|
||||||
val end = lastAt
|
|
||||||
val row = dockAt
|
|
||||||
Flights.fly(Flight(at, to = {
|
|
||||||
val r = row ?: return@Flight null
|
|
||||||
Offset((end?.right ?: r.left) + 70.dp.toPx(), r.center.y)
|
|
||||||
}))
|
|
||||||
} else openFrom(at, e.iconRes, "emu:${e.id}")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (UserAppsState.working != null || UserAppsState.lastError != null) {
|
|
||||||
Box(Modifier.padding(start = if (narrow) 20.dp else 44.dp, end = 20.dp, top = 6.dp)) { UserAppsProgressLine() }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A square button the big one's height beside it on the hero: an icon in [tint] (the palette's
|
|
||||||
* signal when null). [onClick] gets its bounds, for a page to flood out of.
|
|
||||||
*/
|
|
||||||
@Composable
|
|
||||||
private fun HeroIconButton(icon: androidx.compose.ui.graphics.vector.ImageVector, description: String, tint: Color?, id: String, onClick: (Rect?) -> Unit) {
|
|
||||||
val colors = MaterialTheme.colorScheme
|
|
||||||
val pal = LocalPalette.current
|
|
||||||
val src = remember { MutableInteractionSource() }
|
|
||||||
val hot = rememberHot(src)
|
|
||||||
val pressed by src.collectIsPressedAsState()
|
|
||||||
val scale by animateFloatAsState(if (pressed) 0.95f else if (hot) 1.04f else 1f, Motion.sp(0.5f, Spring.StiffnessMedium), label = "heroIcon")
|
|
||||||
val shape = RoundedCornerShape(12.dp)
|
|
||||||
val accent = tint ?: pal.signal
|
|
||||||
var at by remember { mutableStateOf<Rect?>(null) }
|
|
||||||
Box(
|
|
||||||
contentAlignment = Alignment.Center,
|
|
||||||
modifier = Modifier.size(56.dp).paneItem("btn:$id").onGloballyPositioned { at = it.boundsInRoot() }
|
|
||||||
.graphicsLayer { scaleX = scale; scaleY = scale }
|
|
||||||
.clip(shape).background(if (hot) accent.copy(alpha = 0.18f) else colors.surface.copy(alpha = 0.92f))
|
|
||||||
.glideBorder(hot, shape, accent, pal.line2)
|
|
||||||
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button) { onClick(at) }
|
|
||||||
.controllerConfirm { onClick(at) }
|
|
||||||
.semantics { contentDescription = description },
|
|
||||||
) { Icon(icon, null, tint = accent, modifier = Modifier.size(26.dp)) }
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The hero's wall: little windows tilted and drifting as Steam's capsules do, each a window with a
|
|
||||||
* bar along its foot and an emulator's or app's icon inside; blank windows when there are none.
|
|
||||||
*/
|
|
||||||
@Composable
|
|
||||||
private fun DesktopWall(icons: List<Any>) {
|
|
||||||
val pal = LocalPalette.current
|
|
||||||
val ground = remember(pal) { Brush.linearGradient(listOf(pal.surfaceVariant, pal.surface)) }
|
|
||||||
TiltedWall(icons.size, if (icons.isEmpty()) 75_000 else 50_000, capW = 132.dp, capH = 84.dp, gap = 14.dp, corner = 8.dp) { i ->
|
|
||||||
WallCapsule(ground, edge = pal.line2, icon = icons.getOrNull(i), bar = pal.background.copy(alpha = 0.7f))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* One thing that runs in the desktop: its icon over a blurred, darkened copy of itself, a status on
|
|
||||||
* the art (Get, or how far an install is), and under it its name on up to two lines and what it
|
|
||||||
* is. [onClick] gets the art's bounds, for a page to flood out of or a dot to fly from.
|
|
||||||
*/
|
|
||||||
@Composable
|
|
||||||
private fun DesktopCard(
|
|
||||||
key: String, name: String, detail: String, art: Any?,
|
|
||||||
fallback: androidx.compose.ui.graphics.vector.ImageVector = Icons.Outlined.Apps,
|
|
||||||
first: Boolean = false, badge: String? = null, progress: Int? = null, accent: Boolean = false, tint: Color? = null,
|
|
||||||
onClick: (Rect?) -> Unit,
|
|
||||||
) {
|
|
||||||
val colors = MaterialTheme.colorScheme
|
|
||||||
val pal = LocalPalette.current
|
|
||||||
val src = remember { MutableInteractionSource() }
|
|
||||||
val hot = rememberHot(src)
|
|
||||||
val pressed by src.collectIsPressedAsState()
|
|
||||||
val scale by animateFloatAsState(if (pressed) 0.96f else if (hot) 1.03f else 1f, Motion.sp(0.5f, Spring.StiffnessMedium), label = "deskCard")
|
|
||||||
val shape = RoundedCornerShape(16.dp)
|
|
||||||
var artAt by remember { mutableStateOf<Rect?>(null) }
|
|
||||||
val width = if (LocalNarrowPane.current) 116.dp else 132.dp
|
|
||||||
val artH = width * 0.62f
|
|
||||||
val ground = tint?.copy(alpha = 0.25f) ?: if (accent) pal.signal.copy(alpha = 0.12f) else colors.surfaceVariant
|
|
||||||
Column(
|
|
||||||
Modifier.width(width).paneItem("tile:desktop:$key").then(if (first) Modifier.firstTile() else Modifier)
|
|
||||||
.graphicsLayer { scaleX = scale; scaleY = scale }
|
|
||||||
.clip(shape).background(if (hot) pal.signal.copy(alpha = 0.10f) else colors.surface)
|
|
||||||
.glideBorder(hot, shape, pal.signal, pal.line)
|
|
||||||
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button) { onClick(artAt) }
|
|
||||||
.controllerConfirm { onClick(artAt) }
|
|
||||||
.semantics { contentDescription = name },
|
|
||||||
) {
|
|
||||||
Box(
|
|
||||||
contentAlignment = Alignment.Center,
|
|
||||||
modifier = Modifier.fillMaxWidth().height(artH).onGloballyPositioned { artAt = it.boundsInRoot() }
|
|
||||||
.clip(RoundedCornerShape(topStart = 16.dp, topEnd = 16.dp)).background(ground),
|
|
||||||
) {
|
|
||||||
when (art) {
|
|
||||||
is Int -> {
|
|
||||||
Image(
|
|
||||||
painterResource(art), null, contentScale = ContentScale.Crop,
|
|
||||||
modifier = Modifier.fillMaxSize().graphicsLayer { scaleX = 1.8f; scaleY = 1.8f; alpha = 0.5f }
|
|
||||||
.then(if (Build.VERSION.SDK_INT >= 31) Modifier.blur(18.dp) else Modifier),
|
|
||||||
)
|
|
||||||
Box(Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.35f)))
|
|
||||||
Image(painterResource(art), null, modifier = Modifier.size(artH * 0.6f))
|
|
||||||
}
|
|
||||||
null -> Icon(fallback, null, tint = tint ?: if (accent) pal.signal else colors.onSurfaceVariant, modifier = Modifier.size(artH * 0.42f))
|
|
||||||
else -> {
|
|
||||||
AsyncImage(
|
|
||||||
model = art, contentDescription = null, contentScale = ContentScale.Crop,
|
|
||||||
modifier = Modifier.fillMaxSize().graphicsLayer { scaleX = 1.8f; scaleY = 1.8f; alpha = 0.5f }
|
|
||||||
.then(if (Build.VERSION.SDK_INT >= 31) Modifier.blur(18.dp) else Modifier),
|
|
||||||
)
|
|
||||||
Box(Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.35f)))
|
|
||||||
AsyncImage(model = art, contentDescription = null, contentScale = ContentScale.Fit, modifier = Modifier.size(artH * 0.6f))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Box(Modifier.align(Alignment.TopEnd).padding(6.dp)) {
|
|
||||||
if (progress != null) Box(Modifier.clip(RoundedCornerShape(99.dp)).background(Color.Black.copy(alpha = 0.55f)).padding(4.dp)) {
|
|
||||||
if (progress >= 0) CircularProgressIndicator(progress = { progress / 100f }, strokeWidth = 2.dp, color = pal.signal, trackColor = pal.signal.copy(alpha = 0.25f), modifier = Modifier.size(16.dp))
|
|
||||||
else CircularProgressIndicator(strokeWidth = 2.dp, color = pal.signal, modifier = Modifier.size(16.dp))
|
|
||||||
}
|
|
||||||
else if (badge != null) Text(
|
|
||||||
badge, fontSize = 11.sp, fontWeight = FontWeight.Bold, color = pal.onSignal, maxLines = 1,
|
|
||||||
modifier = Modifier.clip(RoundedCornerShape(99.dp)).background(pal.signal).padding(horizontal = 8.dp, vertical = 2.dp),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Column(Modifier.fillMaxWidth().padding(start = 10.dp, end = 10.dp, top = 8.dp, bottom = 10.dp)) {
|
|
||||||
Text(name, fontSize = 13.5.sp, fontWeight = FontWeight.SemiBold, lineHeight = 17.sp, color = colors.onBackground, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
|
||||||
Text(detail, fontSize = 12.sp, lineHeight = 15.sp, color = colors.onSurfaceVariant, minLines = 2, maxLines = 2, overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(top = 3.dp))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The desktop sheet's Files chip: the file manager and the ROMs folder (both from Setup's old
|
|
||||||
* tools), how much the desktop takes, and Uninstall - its only home - which asks in red first.
|
|
||||||
*/
|
|
||||||
@Composable
|
|
||||||
private fun DesktopFiles(s: FrontEndState, a: FrontEndActions) {
|
|
||||||
val ctx = LocalContext.current
|
|
||||||
SettingsGroup(stringResource(R.string.setup_tool_files)) {
|
|
||||||
SettingsRow(stringResource(R.string.setup_tool_files), stringResource(R.string.setup_tool_files_hint)) {
|
|
||||||
SecondaryButton(stringResource(R.string.store_open), compact = true, onClick = a.onFiles)
|
|
||||||
}
|
|
||||||
SettingsRow(stringResource(R.string.setup_tool_roms), s.romsDir ?: stringResource(R.string.setup_tool_roms_hint)) {
|
|
||||||
SecondaryButton(stringResource(R.string.setup_choose), compact = true, onClick = a.onRoms)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (s.desktopPresent) SettingsGroup(stringResource(R.string.content_linux_desktop)) {
|
|
||||||
val size by produceState<Long?>(null) { value = withContext(Dispatchers.IO) { runCatching { com.droiddeck.launcher.runtime.DesktopCatalog.desktopSize(ctx) }.getOrNull() } }
|
|
||||||
SettingsRow(stringResource(R.string.desktop_size), size?.let { FileUtils.sizeToString(it) } ?: "…") {}
|
|
||||||
SettingsRow(stringResource(R.string.desktop_remove_title), stringResource(R.string.desktop_remove_text)) {
|
|
||||||
UninstallDesktop(enabled = !s.runtimeActionsBlocked, onUninstall = a.onRemoveDesktop)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Uninstall the desktop: are you sure steps out of it in red, Keep first and focused. */
|
|
||||||
@Composable
|
|
||||||
private fun UninstallDesktop(enabled: Boolean, onUninstall: () -> Unit) {
|
|
||||||
val colors = MaterialTheme.colorScheme
|
|
||||||
val label = stringResource(R.string.common_uninstall)
|
|
||||||
val title = stringResource(R.string.desktop_uninstall_title)
|
|
||||||
val note = stringResource(R.string.desktop_remove_text)
|
|
||||||
val keep = stringResource(R.string.flathub_keep)
|
|
||||||
var at by remember { mutableStateOf<Rect?>(null) }
|
|
||||||
Box(Modifier.onGloballyPositioned { at = it.boundsInRoot() }) {
|
|
||||||
SecondaryButton(label, enabled = enabled, compact = true) {
|
|
||||||
val from = at ?: return@SecondaryButton
|
|
||||||
Steps.ask(StepAsk(
|
|
||||||
anchor = from, side = StepSide.Left, accent = colors.error, pillCorner = 12.dp, items = 3,
|
|
||||||
handle = { Text(label, fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = colors.error, maxLines = 1) },
|
|
||||||
) {
|
|
||||||
StepTitle(title)
|
|
||||||
Text(note, fontSize = 13.sp, color = colors.onSurfaceVariant, modifier = Modifier.stepItem(1).padding(start = 4.dp, bottom = 12.dp))
|
|
||||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End), modifier = Modifier.fillMaxWidth().stepItem(2)) {
|
|
||||||
StepChoice(keep, enabled = open, modifier = Modifier.focusRequester(first)) { Steps.fold() }
|
|
||||||
StepChoice(label, danger = true, enabled = open) { Steps.fold(); onUninstall() }
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The add or remove under way, or why the last one failed. */
|
|
||||||
@Composable
|
|
||||||
private fun UserAppsProgressLine() {
|
|
||||||
val colors = MaterialTheme.colorScheme
|
|
||||||
val working = UserAppsState.working
|
|
||||||
Column(verticalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp)) {
|
|
||||||
if (working != null) {
|
|
||||||
val stage = UserAppsState.stage ?: stringResource(R.string.user_apps_starting)
|
|
||||||
val percent = UserAppsState.percent
|
|
||||||
Text(
|
|
||||||
if (percent >= 0) stringResource(R.string.user_apps_progress_percent, working, stage, percent) else stringResource(R.string.user_apps_progress, working, stage),
|
|
||||||
fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
|
|
||||||
)
|
|
||||||
if (percent >= 0) androidx.compose.material3.LinearProgressIndicator(progress = { percent / 100f }, modifier = Modifier.fillMaxWidth().height(4.dp))
|
|
||||||
else androidx.compose.material3.LinearProgressIndicator(modifier = Modifier.fillMaxWidth().height(4.dp))
|
|
||||||
} else UserAppsState.lastError?.let { Note(it) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -3,7 +3,6 @@ package com.droiddeck.launcher.ui
|
|||||||
import com.droiddeck.launcher.R
|
import com.droiddeck.launcher.R
|
||||||
import androidx.compose.ui.res.stringResource
|
import androidx.compose.ui.res.stringResource
|
||||||
import androidx.activity.compose.BackHandler
|
import androidx.activity.compose.BackHandler
|
||||||
import androidx.compose.foundation.focusGroup
|
|
||||||
import androidx.compose.foundation.background
|
import androidx.compose.foundation.background
|
||||||
import androidx.compose.foundation.hoverable
|
import androidx.compose.foundation.hoverable
|
||||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||||
@@ -43,11 +42,6 @@ import androidx.compose.runtime.remember
|
|||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.focus.onFocusChanged
|
|
||||||
import androidx.compose.ui.input.InputMode
|
|
||||||
import androidx.compose.ui.platform.LocalInputModeManager
|
|
||||||
import androidx.compose.runtime.snapshotFlow
|
|
||||||
import kotlinx.coroutines.flow.first
|
|
||||||
import androidx.compose.ui.draw.clip
|
import androidx.compose.ui.draw.clip
|
||||||
import androidx.compose.ui.graphics.Color
|
import androidx.compose.ui.graphics.Color
|
||||||
import androidx.compose.ui.text.font.FontWeight
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
@@ -90,19 +84,11 @@ fun DriverPage(
|
|||||||
// D-pad: up from the first driver lands on refresh; the page opens with the driver in use focused.
|
// D-pad: up from the first driver lands on refresh; the page opens with the driver in use focused.
|
||||||
val refreshFocus = remember { FocusRequester() }
|
val refreshFocus = remember { FocusRequester() }
|
||||||
val selectedFocus = remember { FocusRequester() }
|
val selectedFocus = remember { FocusRequester() }
|
||||||
val inputMode = LocalInputModeManager.current
|
LaunchedEffect(Unit) { runCatching { selectedFocus.requestFocus() } }
|
||||||
var pageFocused by remember { mutableStateOf(false) }
|
|
||||||
LaunchedEffect(inputMode.inputMode) {
|
|
||||||
if (inputMode.inputMode != InputMode.Keyboard) return@LaunchedEffect
|
|
||||||
// The chooser holds controller focus until its closing animation finishes.
|
|
||||||
snapshotFlow { Steps.step }.first { it == null }
|
|
||||||
focusWithinFrames({ pageFocused }) { selectedFocus }
|
|
||||||
}
|
|
||||||
val refreshSrc = remember { MutableInteractionSource() }
|
val refreshSrc = remember { MutableInteractionSource() }
|
||||||
val refreshHot = refreshSrc.collectIsFocusedAsState().value || refreshSrc.collectIsHoveredAsState().value
|
val refreshHot = refreshSrc.collectIsFocusedAsState().value || refreshSrc.collectIsHoveredAsState().value
|
||||||
SettingsPage(
|
SettingsPage(
|
||||||
host, title = title, onBack = onBack, lede = "$hint\n$status",
|
host, title = title, onBack = onBack, lede = "$hint\n$status",
|
||||||
modifier = Modifier.onFocusChanged { pageFocused = it.hasFocus }.focusGroup(),
|
|
||||||
action = {
|
action = {
|
||||||
Box(
|
Box(
|
||||||
contentAlignment = Alignment.Center,
|
contentAlignment = Alignment.Center,
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package com.droiddeck.launcher.ui
|
|||||||
import android.view.View
|
import android.view.View
|
||||||
import androidx.compose.animation.animateColorAsState
|
import androidx.compose.animation.animateColorAsState
|
||||||
import androidx.compose.animation.core.Animatable
|
import androidx.compose.animation.core.Animatable
|
||||||
|
import androidx.compose.animation.core.AnimationSpec
|
||||||
import androidx.compose.animation.core.FastOutSlowInEasing
|
import androidx.compose.animation.core.FastOutSlowInEasing
|
||||||
import androidx.compose.foundation.border
|
import androidx.compose.foundation.border
|
||||||
import androidx.compose.foundation.layout.Box
|
import androidx.compose.foundation.layout.Box
|
||||||
@@ -22,7 +23,6 @@ import androidx.compose.runtime.staticCompositionLocalOf
|
|||||||
import androidx.compose.runtime.withFrameNanos
|
import androidx.compose.runtime.withFrameNanos
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.draw.drawWithContent
|
import androidx.compose.ui.draw.drawWithContent
|
||||||
import androidx.compose.ui.focus.focusRequester
|
|
||||||
import androidx.compose.ui.geometry.CornerRadius
|
import androidx.compose.ui.geometry.CornerRadius
|
||||||
import androidx.compose.ui.geometry.Offset
|
import androidx.compose.ui.geometry.Offset
|
||||||
import androidx.compose.ui.geometry.Rect
|
import androidx.compose.ui.geometry.Rect
|
||||||
@@ -58,8 +58,6 @@ internal class GlideSource {
|
|||||||
var shape: Shape by mutableStateOf<Shape>(androidx.compose.ui.graphics.RectangleShape)
|
var shape: Shape by mutableStateOf<Shape>(androidx.compose.ui.graphics.RectangleShape)
|
||||||
var color by mutableStateOf(Color.Transparent)
|
var color by mutableStateOf(Color.Transparent)
|
||||||
var width by mutableStateOf(2.dp)
|
var width by mutableStateOf(2.dp)
|
||||||
/** Focuses the control again: a step-out hands focus back to the control it came out of. */
|
|
||||||
val requester = androidx.compose.ui.focus.FocusRequester()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
internal class FocusGlide(val view: View) {
|
internal class FocusGlide(val view: View) {
|
||||||
@@ -137,18 +135,15 @@ internal fun Modifier.glideBorder(
|
|||||||
onDispose { glide.release(src) }
|
onDispose { glide.release(src) }
|
||||||
}
|
}
|
||||||
val base = if (restColor.alpha > 0f) border(restWidth, restColor, shape) else this
|
val base = if (restColor.alpha > 0f) border(restWidth, restColor, shape) else this
|
||||||
return base.focusRequester(src.requester).onGloballyPositioned { src.coords = it; glide.moved(src) }
|
return base.onGloballyPositioned { src.coords = it; glide.moved(src) }
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Leading edge on a focus move: quick and a little loose. */
|
/** Leading edge on a focus move: quick and a little loose. */
|
||||||
/** A spring an edge chases its target on: damping ratio and stiffness, as Compose's. */
|
private fun lead(): AnimationSpec<Float> = Motion.sp(0.62f, 700f)
|
||||||
private class Edge(val damping: Float, val stiffness: Float)
|
|
||||||
|
|
||||||
private fun lead() = Edge(0.62f, 700f)
|
|
||||||
/** Trailing edge: slower, settles without a bounce to speak of. */
|
/** Trailing edge: slower, settles without a bounce to speak of. */
|
||||||
private fun trail() = Edge(0.78f, 360f)
|
private fun trail(): AnimationSpec<Float> = Motion.sp(0.78f, 360f)
|
||||||
/** Following a control that moves under the ring (a scroll): tight, no wobble. */
|
/** Following a control that moves under the ring (a scroll): tight, no wobble. */
|
||||||
private fun follow() = Edge(1f, 2400f)
|
private fun follow(): AnimationSpec<Float> = Motion.sp(1f, 2400f)
|
||||||
|
|
||||||
/** How long after a focus move the ring keeps its stretchy springs and keeps checking where it is. */
|
/** How long after a focus move the ring keeps its stretchy springs and keeps checking where it is. */
|
||||||
private const val SETTLE_MS = 450L
|
private const val SETTLE_MS = 450L
|
||||||
@@ -157,9 +152,6 @@ private const val STILL_MS = 120L
|
|||||||
/** The longest the ring keeps checking after a move, for a control that never stands still. */
|
/** The longest the ring keeps checking after a move, for a control that never stands still. */
|
||||||
private const val TRACK_MAX_MS = 2_000L
|
private const val TRACK_MAX_MS = 2_000L
|
||||||
|
|
||||||
/** How strongly the ring tints what it holds. */
|
|
||||||
private const val RING_FILL = 0.14f
|
|
||||||
|
|
||||||
/** Moves closer together than this are a held direction: the ring runs along as one, no stretch. */
|
/** Moves closer together than this are a held direction: the ring runs along as one, no stretch. */
|
||||||
private const val REPEAT_MS = 180L
|
private const val REPEAT_MS = 180L
|
||||||
|
|
||||||
@@ -182,16 +174,8 @@ internal fun FocusGlideHost(modifier: Modifier = Modifier, content: @Composable
|
|||||||
val solid = remember { Animatable(0f) }
|
val solid = remember { Animatable(0f) }
|
||||||
val alpha = remember { Animatable(0f) }
|
val alpha = remember { Animatable(0f) }
|
||||||
val scope = rememberCoroutineScope()
|
val scope = rememberCoroutineScope()
|
||||||
// An edge each, the corner, a droplet carrying all of them, its solid fill, and the chase.
|
// An edge each, the corner, and a droplet carrying all of them.
|
||||||
val jobs = remember { arrayOfNulls<Job>(8) }
|
val jobs = remember { arrayOfNulls<Job>(6) }
|
||||||
// The chase: each edge on a spring of its own toward where focus is now. A new target only
|
|
||||||
// moves where it is heading - restarting an animation on every focus move started it from
|
|
||||||
// its first frame (which does not move), so a held direction over a busy page (each rail item
|
|
||||||
// swaps the page) left the ring standing while focus ran on ahead.
|
|
||||||
val target = remember { FloatArray(4) }
|
|
||||||
val vel = remember { FloatArray(4) }
|
|
||||||
val springs = remember { Array(4) { follow() } }
|
|
||||||
val startAt = remember { LongArray(4) }
|
|
||||||
val cur = glide.current
|
val cur = glide.current
|
||||||
var lastColor by remember { mutableStateOf(Color.Transparent) }
|
var lastColor by remember { mutableStateOf(Color.Transparent) }
|
||||||
if (cur != null) lastColor = cur.color
|
if (cur != null) lastColor = cur.color
|
||||||
@@ -202,53 +186,20 @@ internal fun FocusGlideHost(modifier: Modifier = Modifier, content: @Composable
|
|||||||
LaunchedEffect(glide, Motion.scale) {
|
LaunchedEffect(glide, Motion.scale) {
|
||||||
var shown: GlideSource? = null
|
var shown: GlideSource? = null
|
||||||
var movedAt = 0L
|
var movedAt = 0L
|
||||||
var dirSpecs: List<Edge> = List(4) { follow() }
|
var dirSpecs: List<AnimationSpec<Float>> = List(4) { follow() }
|
||||||
var delays = LongArray(4)
|
var delays = LongArray(4)
|
||||||
var lastMove = 0L
|
var lastMove = 0L
|
||||||
fun go(i: Int, v: Float, spec: Edge, wait: Long) {
|
fun go(i: Int, v: Float, spec: AnimationSpec<Float>, wait: Long) {
|
||||||
// A drop cut short by another move turns back into an outline on the way.
|
// A drop cut short by another move turns back into an outline on the way.
|
||||||
if (jobs[5]?.isActive == true || solid.targetValue > 0f) {
|
if (jobs[5]?.isActive == true || solid.targetValue > 0f) scope.launch { solid.animateTo(0f, Motion.tw(120)) }
|
||||||
jobs[5]?.cancel()
|
jobs[5]?.cancel()
|
||||||
jobs[6]?.cancel()
|
// Picks up the speed it is going at: restarting from rest on every step of a held
|
||||||
jobs[6] = scope.launch { solid.animateTo(0f, Motion.tw(120)) }
|
// direction is what made it stutter.
|
||||||
}
|
val speed = edges[i].velocity
|
||||||
val chasing = jobs[7]?.isActive == true
|
jobs[i]?.cancel()
|
||||||
// An edge some other animation was moving (the appear, a drop's opening) is taken over
|
jobs[i] = scope.launch {
|
||||||
// at the speed it was going.
|
if (wait > 0) delay(Motion.ms(wait.toInt()).toLong())
|
||||||
jobs[i]?.let { if (it.isActive) { it.cancel(); vel[i] = edges[i].velocity } }
|
edges[i].animateTo(v, spec, initialVelocity = if (wait > 0) 0f else speed)
|
||||||
if (!chasing) for (j in 0..3) if (jobs[j]?.isActive != true) vel[j] = edges[j].velocity
|
|
||||||
target[i] = v
|
|
||||||
springs[i] = spec
|
|
||||||
startAt[i] = System.nanoTime() + Motion.ms(wait.toInt()) * 1_000_000L
|
|
||||||
if (chasing) return
|
|
||||||
jobs[7] = scope.launch {
|
|
||||||
var last = withFrameNanos { it }
|
|
||||||
while (true) {
|
|
||||||
val frame = withFrameNanos { it }
|
|
||||||
// Real time, however long the frame took, in small steps so a stiff spring holds.
|
|
||||||
val dt = ((frame - last) / 1e9f).coerceAtMost(0.1f) / Motion.scale.coerceAtLeast(0.01f)
|
|
||||||
last = frame
|
|
||||||
val now = System.nanoTime()
|
|
||||||
var settled = true
|
|
||||||
for (j in 0..3) {
|
|
||||||
if (now < startAt[j]) { settled = false; continue }
|
|
||||||
val k = springs[j].stiffness
|
|
||||||
val c = 2f * springs[j].damping * kotlin.math.sqrt(k)
|
|
||||||
var x = edges[j].value
|
|
||||||
var u = vel[j]
|
|
||||||
var left = dt
|
|
||||||
while (left > 0f) {
|
|
||||||
val h = minOf(left, 0.004f)
|
|
||||||
u += (-k * (x - target[j]) - c * u) * h
|
|
||||||
x += u * h
|
|
||||||
left -= h
|
|
||||||
}
|
|
||||||
if (abs(x - target[j]) < 0.3f && abs(u) < 3f) { x = target[j]; u = 0f } else settled = false
|
|
||||||
vel[j] = u
|
|
||||||
edges[j].snapTo(x)
|
|
||||||
}
|
|
||||||
if (settled) break
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/** Pinch into a solid dot where it is, carry it over, and open it into [b] as it arrives. */
|
/** Pinch into a solid dot where it is, carry it over, and open it into [b] as it arrives. */
|
||||||
@@ -319,8 +270,6 @@ internal fun FocusGlideHost(modifier: Modifier = Modifier, content: @Composable
|
|||||||
// Focus passing between two controls can let go of one a moment before the next
|
// Focus passing between two controls can let go of one a moment before the next
|
||||||
// takes it: wait a beat, so that reads as a move and not a fade out and back in.
|
// takes it: wait a beat, so that reads as a move and not a fade out and back in.
|
||||||
delay(60)
|
delay(60)
|
||||||
jobs.forEach { it?.cancel() }
|
|
||||||
solid.snapTo(0f)
|
|
||||||
scope.launch { alpha.animateTo(0f, Motion.tw(140)) }
|
scope.launch { alpha.animateTo(0f, Motion.tw(140)) }
|
||||||
shown = null
|
shown = null
|
||||||
return@collectLatest
|
return@collectLatest
|
||||||
@@ -347,7 +296,7 @@ internal fun FocusGlideHost(modifier: Modifier = Modifier, content: @Composable
|
|||||||
val grown = listOf(b.left - out, b.top - out, b.right + out, b.bottom + out)
|
val grown = listOf(b.left - out, b.top - out, b.right + out, b.bottom + out)
|
||||||
jobs.forEach { it?.cancel() }
|
jobs.forEach { it?.cancel() }
|
||||||
scope.launch { solid.snapTo(0f); edges.forEachIndexed { i, e -> e.snapTo(grown[i]) } }.join()
|
scope.launch { solid.snapTo(0f); edges.forEachIndexed { i, e -> e.snapTo(grown[i]) } }.join()
|
||||||
dirSpecs = List(4) { Edge(0.6f, 700f) }
|
dirSpecs = List(4) { Motion.sp(0.6f, 700f) }
|
||||||
delays = LongArray(4)
|
delays = LongArray(4)
|
||||||
cornerTo(src, b, snap = true)
|
cornerTo(src, b, snap = true)
|
||||||
scope.launch { alpha.animateTo(1f, Motion.tw(140)) }
|
scope.launch { alpha.animateTo(1f, Motion.tw(140)) }
|
||||||
@@ -366,8 +315,8 @@ internal fun FocusGlideHost(modifier: Modifier = Modifier, content: @Composable
|
|||||||
if (dropped) droplet(src, b)
|
if (dropped) droplet(src, b)
|
||||||
else {
|
else {
|
||||||
// A held direction runs along as one piece; a single press stretches.
|
// A held direction runs along as one piece; a single press stretches.
|
||||||
dirSpecs = if (held) List(4) { Edge(0.9f, 900f) }
|
dirSpecs = if (held) List(4) { Motion.sp(0.9f, 900f) }
|
||||||
else List(4) { i -> when (i) { leadIdx -> lead(); trailIdx -> trail(); else -> Edge(0.7f, 520f) } }
|
else List(4) { i -> when (i) { leadIdx -> lead(); trailIdx -> trail(); else -> Motion.sp(0.7f, 520f) } }
|
||||||
delays = LongArray(4) { i -> if (i == trailIdx && !held) 30L else 0L }
|
delays = LongArray(4) { i -> if (i == trailIdx && !held) 30L else 0L }
|
||||||
cornerTo(src, b, snap = false)
|
cornerTo(src, b, snap = false)
|
||||||
}
|
}
|
||||||
@@ -410,18 +359,10 @@ internal fun FocusGlideHost(modifier: Modifier = Modifier, content: @Composable
|
|||||||
color, topLeft = Offset(l, t), size = Size(r - l, b - t),
|
color, topLeft = Offset(l, t), size = Size(r - l, b - t),
|
||||||
cornerRadius = CornerRadius(corner.value), alpha = a * f,
|
cornerRadius = CornerRadius(corner.value), alpha = a * f,
|
||||||
)
|
)
|
||||||
if (f < 0.99f) {
|
if (f < 0.99f) drawRoundRect(
|
||||||
// The ring's own infill: the only fill a pad sees, so it is always exactly what
|
color, topLeft = Offset(l + w / 2f, t + w / 2f), size = Size(sw, sh),
|
||||||
// the ring holds and moves with it (a row's own sliding fill trailed it).
|
cornerRadius = CornerRadius(rad), style = Stroke(w), alpha = a,
|
||||||
drawRoundRect(
|
)
|
||||||
color, topLeft = Offset(l + w / 2f, t + w / 2f), size = Size(sw, sh),
|
|
||||||
cornerRadius = CornerRadius(rad), alpha = a * (1f - f) * RING_FILL,
|
|
||||||
)
|
|
||||||
drawRoundRect(
|
|
||||||
color, topLeft = Offset(l + w / 2f, t + w / 2f), size = Size(sw, sh),
|
|
||||||
cornerRadius = CornerRadius(rad), style = Stroke(w), alpha = a,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
) {
|
) {
|
||||||
CompositionLocalProvider(LocalFocusGlide provides glide) { content() }
|
CompositionLocalProvider(LocalFocusGlide provides glide) { content() }
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.droiddeck.launcher.ui
|
package com.droiddeck.launcher.ui
|
||||||
|
|
||||||
|
import androidx.compose.ui.platform.LocalInspectionMode
|
||||||
import android.graphics.Bitmap
|
import android.graphics.Bitmap
|
||||||
import androidx.compose.animation.animateColorAsState
|
import androidx.compose.animation.animateColorAsState
|
||||||
import androidx.compose.animation.core.Animatable
|
import androidx.compose.animation.core.Animatable
|
||||||
@@ -56,21 +57,9 @@ import androidx.compose.ui.unit.sp
|
|||||||
import androidx.compose.ui.zIndex
|
import androidx.compose.ui.zIndex
|
||||||
import coil.compose.AsyncImage
|
import coil.compose.AsyncImage
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import androidx.compose.ui.layout.boundsInRoot
|
|
||||||
import androidx.compose.ui.layout.onGloballyPositioned
|
|
||||||
|
|
||||||
// Cover art: posters, the art grid and its tiles.
|
// Cover art: posters, the art grid and its tiles.
|
||||||
|
|
||||||
/** Where each art tile sits, root px, by its key: a page opened from one floods out of it. */
|
|
||||||
internal object TileBounds {
|
|
||||||
val at = HashMap<String, androidx.compose.ui.geometry.Rect>()
|
|
||||||
|
|
||||||
/** The page about to open came from tile [key] (its art or icon for the flood), if it is on screen. */
|
|
||||||
fun mark(key: String, art: Any?, corner: Float) {
|
|
||||||
at[key]?.let { PageOrigin.mark(Origin(it, corner, art = art)) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
internal class Tile(
|
internal class Tile(
|
||||||
val title: String, val sub: String?, val art: File?, val key: String,
|
val title: String, val sub: String?, val art: File?, val key: String,
|
||||||
val iconRes: Int? = null, val dim: Boolean = false, val iconBitmap: Bitmap? = null,
|
val iconRes: Int? = null, val dim: Boolean = false, val iconBitmap: Bitmap? = null,
|
||||||
@@ -81,7 +70,8 @@ internal class Tile(
|
|||||||
@Composable
|
@Composable
|
||||||
internal fun Poster(art: File?, name: String, modifier: Modifier) {
|
internal fun Poster(art: File?, name: String, modifier: Modifier) {
|
||||||
val colors = MaterialTheme.colorScheme
|
val colors = MaterialTheme.colorScheme
|
||||||
val t = remember { Animatable(0f) }
|
val inspecting = LocalInspectionMode.current
|
||||||
|
val t = remember { Animatable(if (inspecting) 1f else 0f) }
|
||||||
LaunchedEffect(Unit) { t.animateTo(1f, Motion.sp(0.6f, Spring.StiffnessLow)) }
|
LaunchedEffect(Unit) { t.animateTo(1f, Motion.sp(0.6f, Spring.StiffnessLow)) }
|
||||||
Box(
|
Box(
|
||||||
modifier = modifier.padding(start = 16.dp).aspectRatio(2f / 3f)
|
modifier = modifier.padding(start = 16.dp).aspectRatio(2f / 3f)
|
||||||
@@ -114,7 +104,6 @@ internal fun ArtGrid(tiles: List<Tile>, wide: Boolean = false) {
|
|||||||
val src = remember { MutableInteractionSource() }
|
val src = remember { MutableInteractionSource() }
|
||||||
val hot = rememberHot(src)
|
val hot = rememberHot(src)
|
||||||
val track = Modifier.paneItem("tile:" + t.key).then(if (t === tiles.first()) Modifier.firstTile() else Modifier)
|
val track = Modifier.paneItem("tile:" + t.key).then(if (t === tiles.first()) Modifier.firstTile() else Modifier)
|
||||||
.onGloballyPositioned { TileBounds.at[t.key] = it.boundsInRoot() }
|
|
||||||
Box(modifier = Modifier.width(tileWidth).zIndex(if (hot) 1f else 0f)) { GameTile(t, wide, square, src, hot, track) }
|
Box(modifier = Modifier.width(tileWidth).zIndex(if (hot) 1f else 0f)) { GameTile(t, wide, square, src, hot, track) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -76,8 +76,6 @@ import androidx.compose.ui.Modifier
|
|||||||
import androidx.compose.ui.draw.alpha
|
import androidx.compose.ui.draw.alpha
|
||||||
import androidx.compose.ui.draw.blur
|
import androidx.compose.ui.draw.blur
|
||||||
import androidx.compose.ui.draw.clip
|
import androidx.compose.ui.draw.clip
|
||||||
import androidx.compose.ui.focus.focusRequester
|
|
||||||
import androidx.compose.ui.layout.boundsInRoot
|
|
||||||
import androidx.compose.ui.geometry.Offset
|
import androidx.compose.ui.geometry.Offset
|
||||||
import androidx.compose.ui.graphics.Brush
|
import androidx.compose.ui.graphics.Brush
|
||||||
import androidx.compose.ui.graphics.Color
|
import androidx.compose.ui.graphics.Color
|
||||||
@@ -93,6 +91,7 @@ import androidx.compose.ui.unit.dp
|
|||||||
import androidx.compose.ui.unit.sp
|
import androidx.compose.ui.unit.sp
|
||||||
import coil.compose.AsyncImage
|
import coil.compose.AsyncImage
|
||||||
import com.droiddeck.launcher.HomeApp
|
import com.droiddeck.launcher.HomeApp
|
||||||
|
import androidx.compose.ui.platform.LocalInspectionMode
|
||||||
import com.droiddeck.launcher.R
|
import com.droiddeck.launcher.R
|
||||||
import com.droiddeck.launcher.frontend.Library
|
import com.droiddeck.launcher.frontend.Library
|
||||||
import com.droiddeck.launcher.runtime.UserApps
|
import com.droiddeck.launcher.runtime.UserApps
|
||||||
@@ -126,30 +125,15 @@ internal fun Pane(
|
|||||||
val paneAt = remember { arrayOf(Offset.Zero) }
|
val paneAt = remember { arrayOf(Offset.Zero) }
|
||||||
val livePage by rememberUpdatedState(s.pageKey)
|
val livePage by rememberUpdatedState(s.pageKey)
|
||||||
// Picking another game changes the detail beside the list, not the whole page.
|
// Picking another game changes the detail beside the list, not the whole page.
|
||||||
val railContent = if (selected.startsWith("app:")) "games" else selected
|
val target = if (page != null && s.pageKey != null) s.pageKey else if (selected.startsWith("app:")) "games" else selected
|
||||||
val target = if (page != null && s.pageKey != null) s.pageKey else railContent
|
|
||||||
// The game the Games page shows. It must outlive the selection: while the page animates out,
|
// The game the Games page shows. It must outlive the selection: while the page animates out,
|
||||||
// drawing it with what is selected now (another rail item) turned it into a copy of that page.
|
// drawing it with what is selected now (another rail item) turned it into a copy of that page.
|
||||||
val gameShown = remember { arrayOf("games") }
|
val gameShown = remember { arrayOf("games") }
|
||||||
if (selected == "games" || selected.startsWith("app:")) gameShown[0] = selected
|
if (selected == "games" || selected.startsWith("app:")) gameShown[0] = selected
|
||||||
// What the pane showed before this change: the content a page opened over belongs to it.
|
|
||||||
val before = remember { arrayOf(target) }
|
|
||||||
if (page != null && s.pageKey != null) {
|
if (page != null && s.pageKey != null) {
|
||||||
pages[s.pageKey] = page
|
pages[s.pageKey] = page
|
||||||
if (s.pageKey !in origins) PageOrigin.take()?.let { o ->
|
if (s.pageKey !in origins) PageOrigin.take()?.let { origins[s.pageKey] = it.translate(-paneAt[0]) }
|
||||||
// A hop's page came out of its own rail item, and is that item's content.
|
|
||||||
origins[s.pageKey] = inPane(o.translate(-paneAt[0])).let { if (it.owner == null) it.ownedBy(railContent) else it }
|
|
||||||
}
|
|
||||||
} else if (target != before[0] && target !in origins) {
|
|
||||||
// A section's own page opened from a control in it (an emulator's card, a ROM's) floods
|
|
||||||
// out of that control and belongs to what was showing; a hop's comes out of its rail item.
|
|
||||||
PageOrigin.take()?.let { o -> origins[target] = inPane(o.translate(-paneAt[0])).let { if (it.owner == null) it.ownedBy(before[0]) else it } }
|
|
||||||
}
|
}
|
||||||
before[0] = target
|
|
||||||
val targetNow by rememberUpdatedState(target)
|
|
||||||
// A page leaving through a hop's link is not coming back to its control.
|
|
||||||
val leave = if (Hops.linking) PageLeave.Link else PageLeave.Ordinary
|
|
||||||
LaunchedEffect(target) { Hops.linking = false }
|
|
||||||
AnimatedContent(
|
AnimatedContent(
|
||||||
targetState = target,
|
targetState = target,
|
||||||
modifier = Modifier.onGloballyPositioned { paneAt[0] = it.positionInRoot() },
|
modifier = Modifier.onGloballyPositioned { paneAt[0] = it.positionInRoot() },
|
||||||
@@ -160,14 +144,9 @@ internal fun Pane(
|
|||||||
.togetherWith(fadeOut(Motion.tw(320, 80)) + scaleOut(Motion.tw(480), targetScale = 0.95f))
|
.togetherWith(fadeOut(Motion.tw(320, 80)) + scaleOut(Motion.tw(480), targetScale = 0.95f))
|
||||||
.apply { targetContentZIndex = 1f }
|
.apply { targetContentZIndex = 1f }
|
||||||
// Back out of it: the flood draws back into the control as the pane comes forward again.
|
// Back out of it: the flood draws back into the control as the pane comes forward again.
|
||||||
initialState in origins && pageExit(origins[initialState]?.owner, targetState, leave) == PageExit.Drain ->
|
initialState in origins -> (fadeIn(Motion.tw(300, 100)) + scaleIn(Motion.tw(460, 40), initialScale = 0.95f))
|
||||||
(fadeIn(Motion.tw(300, 100)) + scaleIn(Motion.tw(460, 40), initialScale = 0.95f))
|
.togetherWith(ExitTransition.None)
|
||||||
.togetherWith(ExitTransition.None)
|
.apply { targetContentZIndex = -1f }
|
||||||
.apply { targetContentZIndex = -1f }
|
|
||||||
// Away to something else: the control is not coming back, so the page sinks with the pane.
|
|
||||||
initialState in origins -> (fadeIn(Motion.tw(300, 80)) + slideInVertically(Motion.tw(420, 80)) { it / 24 })
|
|
||||||
.togetherWith(fadeOut(Motion.tw(170)) + scaleOut(Motion.tw(170), targetScale = 0.95f))
|
|
||||||
.apply { targetContentZIndex = 1f }
|
|
||||||
else -> (fadeIn(Motion.tw(300, 80)) + slideInVertically(Motion.tw(420, 80)) { it / 24 })
|
else -> (fadeIn(Motion.tw(300, 80)) + slideInVertically(Motion.tw(420, 80)) { it / 24 })
|
||||||
.togetherWith(fadeOut(Motion.tw(170)) + slideOutVertically(Motion.tw(170)) { -it / 40 })
|
.togetherWith(fadeOut(Motion.tw(170)) + slideOutVertically(Motion.tw(170)) { -it / 40 })
|
||||||
.apply { targetContentZIndex = 1f }
|
.apply { targetContentZIndex = 1f }
|
||||||
@@ -175,51 +154,26 @@ internal fun Pane(
|
|||||||
},
|
},
|
||||||
label = "pane",
|
label = "pane",
|
||||||
) { key ->
|
) { key ->
|
||||||
val drawn = (if (page != null && key == s.pageKey) page else pages[key])
|
val shown = if (page != null && key == s.pageKey) page else pages[key]
|
||||||
?: { Content(s, if (key == "games") gameShown[0] else key, a, Modifier.fillMaxSize(), onSelect, onAndroidAppClick, onOpenDeveloperOptions, onRequestWirelessAdb) }
|
if (shown != null) {
|
||||||
// A hop leaving this content: it sinks back as the dot leaves it (and comes forward
|
DisposableEffect(key) { onDispose { if (key != livePage) { pages.remove(key); origins.remove(key) } } }
|
||||||
// again, freshly drawn, when the hop is undone).
|
|
||||||
val hopSink by androidx.compose.animation.core.animateFloatAsState(
|
|
||||||
if (Hops.sinking == key) 1f else 0f, Motion.tw(260), label = "hopSink",
|
|
||||||
)
|
|
||||||
val shown: @Composable () -> Unit = {
|
|
||||||
Box(Modifier.fillMaxSize().graphicsLayer { val k = 1f - 0.05f * hopSink; scaleX = k; scaleY = k; alpha = 1f - 0.35f * hopSink }) { drawn() }
|
|
||||||
}
|
|
||||||
run {
|
|
||||||
DisposableEffect(key) { onDispose { if (key != livePage && key != targetNow) { pages.remove(key); origins.remove(key) } } }
|
|
||||||
val from = origins[key]
|
val from = origins[key]
|
||||||
if (from == null) shown()
|
if (from == null) shown()
|
||||||
else {
|
else {
|
||||||
// The control's own picture (a card's art, an emulator's icon) on the tile as it grows.
|
|
||||||
val art = when (val m = from.art) {
|
|
||||||
null -> null
|
|
||||||
is Int -> androidx.compose.ui.res.painterResource(m)
|
|
||||||
else -> coil.compose.rememberAsyncImagePainter(m)
|
|
||||||
}
|
|
||||||
val leaving = transition.targetState == EnterExitState.PostExit
|
|
||||||
// Settled as the page starts to leave, from what is coming in, not from where it came in.
|
|
||||||
val drains = remember(leaving) { !leaving || pageExit(from.owner, target, leave) == PageExit.Drain }
|
|
||||||
// Keeps a leaving page on screen while its flood draws back into the control.
|
// Keeps a leaving page on screen while its flood draws back into the control.
|
||||||
transition.animateFloat(
|
transition.animateFloat(
|
||||||
transitionSpec = { if (targetState == EnterExitState.PostExit && drains) Motion.tw(PAGE_RETURN_MS) else snap() },
|
transitionSpec = { if (targetState == EnterExitState.PostExit) Motion.tw(PAGE_RETURN_MS) else snap() },
|
||||||
label = "pageReturn",
|
label = "pageReturn",
|
||||||
) { if (it == EnterExitState.PostExit) 1f else 0f }
|
) { if (it == EnterExitState.PostExit) 1f else 0f }
|
||||||
PageFlood(from, leaving = leaving, art = art, sinks = !drains) { shown() }
|
PageFlood(from, leaving = transition.targetState == EnterExitState.PostExit) { shown() }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
else Content(s, if (key == "games") gameShown[0] else key, a, Modifier.fillMaxSize(), onSelect, onAndroidAppClick, onOpenDeveloperOptions, onRequestWirelessAdb)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* An origin left of the pane (a rail item a hop flew to) starts half inside it, at the item's
|
|
||||||
* height: the page swells out of the pane's edge beside the item. Wholly outside, its tile was a
|
|
||||||
* bar that raced across from the far edge.
|
|
||||||
*/
|
|
||||||
internal fun inPane(o: Origin): Origin =
|
|
||||||
if (o.bounds.right > 0f) o else o.translate(Offset(-o.bounds.right + o.bounds.width / 2f, 0f))
|
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
private fun Backdrop(art: File?) {
|
private fun Backdrop(art: File?) {
|
||||||
val colors = MaterialTheme.colorScheme
|
val colors = MaterialTheme.colorScheme
|
||||||
@@ -254,7 +208,6 @@ private fun Content(
|
|||||||
val colors = MaterialTheme.colorScheme
|
val colors = MaterialTheme.colorScheme
|
||||||
val detailPosterWidth = if (LocalConfiguration.current.screenHeightDp < 600) 72.dp else 120.dp
|
val detailPosterWidth = if (LocalConfiguration.current.screenHeightDp < 600) 72.dp else 120.dp
|
||||||
val narrow = LocalNarrowPane.current
|
val narrow = LocalNarrowPane.current
|
||||||
val density = androidx.compose.ui.platform.LocalDensity.current.density
|
|
||||||
val padH = if (narrow) 16.dp else 22.dp
|
val padH = if (narrow) 16.dp else 22.dp
|
||||||
val padV = if (narrow) 12.dp else 18.dp
|
val padV = if (narrow) 12.dp else 18.dp
|
||||||
// Setup scrolls inside itself, under its tabs.
|
// Setup scrolls inside itself, under its tabs.
|
||||||
@@ -274,12 +227,12 @@ private fun Content(
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
// The Store scrolls and navigates inside itself (its tabs and an app's page).
|
// The Store scrolls and navigates inside itself (its tabs and an app's page).
|
||||||
if (selected == "store") {
|
if (selected == "store" && s.storeEnabled) {
|
||||||
StorePage(s, a, modifier)
|
StorePage(s, a, modifier)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
// Stores (GOG, Epic, Amazon) takes the whole pane: chips, shelves and a game's page inside it.
|
// Stores (GOG, Epic, Amazon) takes the whole pane: chips, shelves and a game's page inside it.
|
||||||
if (selected == "stores") {
|
if (selected == "stores" && s.gameStoresEnabled) {
|
||||||
StoresPage(s, a, modifier)
|
StoresPage(s, a, modifier)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -288,11 +241,6 @@ private fun Content(
|
|||||||
GamesPage(s, a, selected, onSelect, modifier)
|
GamesPage(s, a, selected, onSelect, modifier)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
// Desktop is the Steam tab's shape: a hero with its lifted sheet, and shelves under it.
|
|
||||||
if (selected == "desktop") {
|
|
||||||
DesktopPage(s, a, modifier, onSelect)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
// Every other page scrolls as one - header, hero and grid - so a short screen reaches the grid
|
// Every other page scrolls as one - header, hero and grid - so a short screen reaches the grid
|
||||||
// instead of showing a sliver of it under a fixed hero. A focused tile scrolls itself into view.
|
// instead of showing a sliver of it under a fixed hero. A focused tile scrolls itself into view.
|
||||||
Column(modifier = modifier.verticalScroll(rememberScrollState()).padding(horizontal = padH, vertical = padV)) {
|
Column(modifier = modifier.verticalScroll(rememberScrollState()).padding(horizontal = padH, vertical = padV)) {
|
||||||
@@ -313,6 +261,38 @@ private fun Content(
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
selected == "desktop" -> {
|
||||||
|
val installed = s.emulators.filter { it.installed }
|
||||||
|
val available = s.emulators.filter { !it.installed }
|
||||||
|
val ctx = LocalContext.current
|
||||||
|
val inspecting = LocalInspectionMode.current
|
||||||
|
LaunchedEffect(Unit) { if (!inspecting) UserAppsState.refresh(ctx) }
|
||||||
|
val apps = UserAppsState.items
|
||||||
|
var adding by rememberSaveable { mutableStateOf(false) }
|
||||||
|
Rise(0) {
|
||||||
|
PageHeader(stringResource(R.string.drawer_desktop)) {
|
||||||
|
if (s.desktopInstalled) Chip(stringResource(R.string.content_desktop_installed), ok = true) else Chip(stringResource(R.string.content_desktop_first_open), ok = false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Rise(2) { DesktopCard(s, a) }
|
||||||
|
// Add closes the last grid: the installable emulators, or the installed ones once none are left.
|
||||||
|
val ready = installed.map { GridItem.Emu(it) } + apps.map { GridItem.User(it) }
|
||||||
|
val addAfterReady = available.isEmpty()
|
||||||
|
if (ready.isNotEmpty() || addAfterReady) {
|
||||||
|
Rise(3) { SectionTitle(stringResource(R.string.user_apps_section), ready.size.takeIf { it > 0 }?.toString()) }
|
||||||
|
Rise(4) {
|
||||||
|
LauncherGrid(if (addAfterReady) ready + GridItem.Add else ready, first = true, onSelect = onSelect, onAdd = { if (!s.busy) adding = true })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (UserAppsState.working != null || UserAppsState.lastError != null) Rise(5) { UserAppsProgress() }
|
||||||
|
if (!addAfterReady) {
|
||||||
|
Rise(5) { SectionTitle(stringResource(R.string.content_available), available.size.toString()) }
|
||||||
|
Rise(6) {
|
||||||
|
LauncherGrid(available.map { GridItem.Emu(it) } + GridItem.Add, first = ready.isEmpty(), onSelect = onSelect, onAdd = { if (!s.busy) adding = true })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (adding && !s.busy) AddAppDialog(s.ready, onDismiss = { adding = false }) { request, label -> UserAppsState.add(ctx, request, label) }
|
||||||
|
}
|
||||||
selected.startsWith("user:") -> {
|
selected.startsWith("user:") -> {
|
||||||
val app = UserAppsState.items.firstOrNull { "user:${it.key}" == selected }
|
val app = UserAppsState.items.firstOrNull { "user:${it.key}" == selected }
|
||||||
if (app == null) Note(stringResource(R.string.user_apps_gone)) else UserAppPage(app, s, a, onSelect)
|
if (app == null) Note(stringResource(R.string.user_apps_gone)) else UserAppPage(app, s, a, onSelect)
|
||||||
@@ -322,26 +302,21 @@ private fun Content(
|
|||||||
if (e == null) Note(stringResource(R.string.content_not_installed)) else {
|
if (e == null) Note(stringResource(R.string.content_not_installed)) else {
|
||||||
val pkgId = Library.packageId(e.id)
|
val pkgId = Library.packageId(e.id)
|
||||||
val pkg = pkgId?.let { id -> s.packages?.firstOrNull { it.id == id } }
|
val pkg = pkgId?.let { id -> s.packages?.firstOrNull { it.id == id } }
|
||||||
// Out of its card on Desktop, with the card's icon; B draws it back in.
|
Rise(0) {
|
||||||
|
BackLink(stringResource(R.string.drawer_desktop)) { onSelect("desktop") }
|
||||||
|
}
|
||||||
Rise(1) {
|
Rise(1) {
|
||||||
Row(
|
Row(
|
||||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(16.dp),
|
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(14.dp),
|
||||||
modifier = Modifier.padding(top = 4.dp, bottom = 12.dp),
|
modifier = Modifier.padding(top = 12.dp, bottom = 12.dp),
|
||||||
) {
|
) {
|
||||||
Image(painterResource(e.iconRes), null, modifier = Modifier.size(64.dp))
|
Image(painterResource(e.iconRes), null, modifier = Modifier.size(52.dp))
|
||||||
Column {
|
Column {
|
||||||
Text(e.name, fontSize = if (narrow) 24.sp else 30.sp, fontWeight = FontWeight.Black, color = colors.onBackground)
|
Text(e.name, fontSize = if (narrow) 22.sp else 26.sp, fontWeight = FontWeight.Bold, color = colors.onBackground)
|
||||||
Text(
|
Text(
|
||||||
systemLabel(e).let { if (e.installed) it else stringResource(R.string.content_not_installed_suffix, it) },
|
systemLabel(e).let { if (e.installed) it else stringResource(R.string.content_not_installed_suffix, it) },
|
||||||
fontSize = 14.sp, color = colors.onSurfaceVariant,
|
fontSize = 14.sp, color = colors.onSurfaceVariant,
|
||||||
)
|
)
|
||||||
if (e.installed) Text(
|
|
||||||
listOfNotNull(
|
|
||||||
pluralStringResource(R.plurals.mode_added_count, e.games.size, e.games.size).takeIf { e.id != "retroarch" || e.games.isNotEmpty() },
|
|
||||||
s.romsDir,
|
|
||||||
).joinToString(" · "),
|
|
||||||
fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -366,24 +341,7 @@ private fun Content(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
else Rise(5, Modifier.fillMaxWidth()) {
|
else Rise(5, Modifier.fillMaxWidth()) {
|
||||||
Column {
|
ArtGrid(e.games.mapIndexed { index, g -> Tile(g.name, if (g.art != null) stringResource(R.string.content_rom_installed) else g.hostPath.extension.uppercase().ifEmpty { stringResource(R.string.content_rom_folder) }, g.art, "rom:${e.id}:$index", e.iconRes) { onSelect("rom:${e.id}:$index") } }, wide = e.games.none { it.art != null })
|
||||||
// RetroArch's games come from many systems: chips filter them, one
|
|
||||||
// selection gliding between them.
|
|
||||||
val systems = remember(e.games) { e.games.map { romSystem(it) }.distinct() }
|
|
||||||
var system by rememberSaveable(e.id) { mutableStateOf<String?>(null) }
|
|
||||||
if (systems.size > 1) Box(Modifier.padding(top = 10.dp)) {
|
|
||||||
val labels = listOf(stringResource(R.string.desktop_all_systems)) + systems
|
|
||||||
SheetChips(labels, if (system == null) 0 else systems.indexOf(system) + 1) { i -> system = if (i == 0) null else systems[i - 1] }
|
|
||||||
}
|
|
||||||
val shown = e.games.withIndex().filter { system == null || romSystem(it.value) == system }
|
|
||||||
ArtGrid(shown.map { (index, g) ->
|
|
||||||
val key = "rom:${e.id}:$index"
|
|
||||||
Tile(g.name, if (g.art != null) stringResource(R.string.content_rom_installed) else g.hostPath.extension.uppercase().ifEmpty { stringResource(R.string.content_rom_folder) }, g.art, key, e.iconRes) {
|
|
||||||
TileBounds.mark(key, g.art ?: e.iconRes, 12f * density)
|
|
||||||
onSelect(key)
|
|
||||||
}
|
|
||||||
}, wide = e.games.none { it.art != null })
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if (pkg != null) Rise(2) {
|
if (pkg != null) Rise(2) {
|
||||||
@@ -425,7 +383,12 @@ private fun Content(
|
|||||||
val pair = romFor(s, selected)
|
val pair = romFor(s, selected)
|
||||||
if (pair == null) Note(stringResource(R.string.content_rom_gone)) else {
|
if (pair == null) Note(stringResource(R.string.content_rom_gone)) else {
|
||||||
val (e, g) = pair
|
val (e, g) = pair
|
||||||
Rise(0) { Eyebrow(stringResource(R.string.content_desktop_system, systemLabel(e))) }
|
Rise(0) {
|
||||||
|
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||||
|
BackLink(e.name) { onSelect("emu:${e.id}") }
|
||||||
|
Eyebrow(stringResource(R.string.content_desktop_system, systemLabel(e)))
|
||||||
|
}
|
||||||
|
}
|
||||||
Rise(1) { Title(g.name) }
|
Rise(1) { Title(g.name) }
|
||||||
Rise(2) {
|
Rise(2) {
|
||||||
Row {
|
Row {
|
||||||
@@ -447,10 +410,7 @@ private fun Content(
|
|||||||
Rise(4, Modifier.fillMaxWidth()) {
|
Rise(4, Modifier.fillMaxWidth()) {
|
||||||
ArtGrid(others.map { x ->
|
ArtGrid(others.map { x ->
|
||||||
val index = e.games.indexOf(x)
|
val index = e.games.indexOf(x)
|
||||||
Tile(x.name, if (x.art != null) stringResource(R.string.content_rom_installed) else x.hostPath.extension.uppercase().ifEmpty { stringResource(R.string.content_rom_folder) }, x.art, "rom:${e.id}:$index", e.iconRes) {
|
Tile(x.name, if (x.art != null) stringResource(R.string.content_rom_installed) else x.hostPath.extension.uppercase().ifEmpty { stringResource(R.string.content_rom_folder) }, x.art, "rom:${e.id}:$index", e.iconRes) { onSelect("rom:${e.id}:$index") }
|
||||||
TileBounds.mark("rom:${e.id}:$index", x.art ?: e.iconRes, 12f * density)
|
|
||||||
onSelect("rom:${e.id}:$index")
|
|
||||||
}
|
|
||||||
}, wide = others.none { it.art != null })
|
}, wide = others.none { it.art != null })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -461,6 +421,122 @@ private fun Content(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The Linux desktop itself, above the emulators that run in it. */
|
||||||
|
@Composable
|
||||||
|
private fun DesktopCard(s: FrontEndState, a: FrontEndActions) {
|
||||||
|
val colors = MaterialTheme.colorScheme
|
||||||
|
val pal = LocalPalette.current
|
||||||
|
var confirmRemove by rememberSaveable { mutableStateOf(false) }
|
||||||
|
if (confirmRemove) ConfirmDialog(
|
||||||
|
stringResource(R.string.desktop_remove_title), stringResource(R.string.desktop_remove_text),
|
||||||
|
stringResource(R.string.common_uninstall), a.onRemoveDesktop, { confirmRemove = false },
|
||||||
|
)
|
||||||
|
val actions: @Composable () -> Unit = {
|
||||||
|
Actions {
|
||||||
|
// Enabled without a runtime or the desktop: the session's loading screen installs them first.
|
||||||
|
PrimaryButton(if (s.desktopInstalled) stringResource(R.string.content_open_desktop) else stringResource(R.string.content_install_open_desktop), enabled = !s.busy, main = true, onClick = a.onDesktop)
|
||||||
|
Cog(onClick = a.onDesktopSettings)
|
||||||
|
if (s.desktopPresent) SecondaryButton(stringResource(R.string.common_uninstall),
|
||||||
|
enabled = !s.runtimeActionsBlocked) { confirmRemove = true }
|
||||||
|
BusyChip(s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// The button goes under the title unless the card is wide enough for both side by side: in some
|
||||||
|
// languages its label alone takes half a small phone's pane.
|
||||||
|
BoxWithConstraints(Modifier.fillMaxWidth()) {
|
||||||
|
val narrow = LocalNarrowPane.current || maxWidth < DesktopCardInlineWidth
|
||||||
|
Column(
|
||||||
|
verticalArrangement = Arrangement.spacedBy(14.dp),
|
||||||
|
modifier = Modifier.fillMaxWidth().clip(Shape16).background(colors.surface).border(1.dp, pal.line, Shape16).padding(16.dp),
|
||||||
|
) {
|
||||||
|
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(14.dp)) {
|
||||||
|
Box(
|
||||||
|
contentAlignment = Alignment.Center,
|
||||||
|
modifier = Modifier.size(52.dp).clip(Shape14).background(colors.surfaceVariant).border(1.dp, pal.line2, Shape14),
|
||||||
|
) { Icon(Icons.Outlined.DesktopWindows, contentDescription = null, tint = colors.onBackground, modifier = Modifier.size(26.dp)) }
|
||||||
|
Column(modifier = Modifier.weight(1f)) {
|
||||||
|
Text(stringResource(R.string.content_linux_desktop), fontSize = 18.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
|
||||||
|
Text(stringResource(R.string.content_linux_desktop_hint), fontSize = 14.sp, color = colors.onSurfaceVariant, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
||||||
|
}
|
||||||
|
if (!narrow) actions()
|
||||||
|
}
|
||||||
|
if (narrow) actions()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** How wide the desktop card must be to keep its button beside the title. */
|
||||||
|
private val DesktopCardInlineWidth = 640.dp
|
||||||
|
|
||||||
|
/** What the Desktop page's grids hold: emulators, the user's own apps, and Add at the end. */
|
||||||
|
private sealed class GridItem(val key: String) {
|
||||||
|
class Emu(val e: Library.Emulator) : GridItem("emu:${e.id}")
|
||||||
|
class User(val app: UserApps.App) : GridItem("user:${app.key}")
|
||||||
|
data object Add : GridItem("add")
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Wide tiles - three across, two on a small phone, or a list on a narrow page. */
|
||||||
|
@Composable
|
||||||
|
private fun LauncherGrid(items: List<GridItem>, first: Boolean, onSelect: (String) -> Unit, onAdd: () -> Unit = {}) {
|
||||||
|
BoxWithConstraints(Modifier.fillMaxWidth()) {
|
||||||
|
// A tile holds an icon, a name and an Install button: one much under 230dp wide leaves the
|
||||||
|
// name no room at all.
|
||||||
|
val columns = when {
|
||||||
|
LocalNarrowPane.current -> 1
|
||||||
|
maxWidth < 720.dp -> 2
|
||||||
|
else -> 3
|
||||||
|
}
|
||||||
|
Column(verticalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth().padding(top = 4.dp, bottom = 8.dp)) {
|
||||||
|
items.chunked(columns).forEachIndexed { r, row ->
|
||||||
|
Row(horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth().height(IntrinsicSize.Min)) {
|
||||||
|
row.forEachIndexed { i, item ->
|
||||||
|
key(item.key) {
|
||||||
|
val m = Modifier.weight(1f).fillMaxHeight()
|
||||||
|
val isFirst = first && r == 0 && i == 0
|
||||||
|
when (item) {
|
||||||
|
is GridItem.Emu -> EmulatorTile(item.e, m, isFirst) { onSelect(item.key) }
|
||||||
|
is GridItem.User -> UserAppTile(item.app, m, isFirst) { onSelect(item.key) }
|
||||||
|
GridItem.Add -> AddTile(m, isFirst, onAdd)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
repeat(columns - row.size) { Spacer(Modifier.weight(1f)) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A grid tile's frame: the emulator tiles' look, focus glide and press. */
|
||||||
|
@Composable
|
||||||
|
private fun TileFrame(id: String, modifier: Modifier, isFirst: Boolean, filled: Boolean, onClick: () -> Unit, content: @Composable RowScope.() -> Unit) {
|
||||||
|
val colors = MaterialTheme.colorScheme
|
||||||
|
val pal = LocalPalette.current
|
||||||
|
val src = remember { MutableInteractionSource() }
|
||||||
|
val hot = rememberHot(src)
|
||||||
|
val pressed by src.collectIsPressedAsState()
|
||||||
|
val scale by animateFloatAsState(if (pressed) 0.97f else 1f, Motion.sp(0.5f, Spring.StiffnessMedium), label = "tileScale")
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||||
|
modifier = modifier.paneItem("tile:$id").then(if (isFirst) Modifier.firstTile() else Modifier)
|
||||||
|
.graphicsLayer { scaleX = scale; scaleY = scale }
|
||||||
|
.clip(Shape14)
|
||||||
|
.background(if (hot) pal.signal.copy(alpha = 0.10f) else if (filled) colors.surface else Color.Transparent)
|
||||||
|
.glideBorder(hot, Shape14, pal.signal, pal.line)
|
||||||
|
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onClick)
|
||||||
|
.padding(horizontal = 12.dp, vertical = 10.dp),
|
||||||
|
) { content() }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun TileText(title: String, detail: String, modifier: Modifier) {
|
||||||
|
val colors = MaterialTheme.colorScheme
|
||||||
|
Column(modifier = modifier) {
|
||||||
|
Text(title, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||||
|
Text(detail, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
internal fun UserApps.Kind.label() = when (this) {
|
internal fun UserApps.Kind.label() = when (this) {
|
||||||
UserApps.Kind.SCRIPT -> R.string.user_apps_kind_script
|
UserApps.Kind.SCRIPT -> R.string.user_apps_kind_script
|
||||||
UserApps.Kind.APPIMAGE -> R.string.user_apps_kind_appimage
|
UserApps.Kind.APPIMAGE -> R.string.user_apps_kind_appimage
|
||||||
@@ -482,6 +558,26 @@ private fun UserAppIcon(app: UserApps.App, size: Int) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun UserAppTile(app: UserApps.App, modifier: Modifier, isFirst: Boolean, onClick: () -> Unit) =
|
||||||
|
TileFrame("user:${app.key}", modifier, isFirst, filled = true, onClick = onClick) {
|
||||||
|
UserAppIcon(app, 44)
|
||||||
|
TileText(app.name, stringResource(app.kind.label()), Modifier.weight(1f))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The grid's last tile: opens the Add dialog. */
|
||||||
|
@Composable
|
||||||
|
private fun AddTile(modifier: Modifier, isFirst: Boolean, onClick: () -> Unit) {
|
||||||
|
val pal = LocalPalette.current
|
||||||
|
TileFrame("add", modifier, isFirst, filled = false, onClick = onClick) {
|
||||||
|
Box(
|
||||||
|
contentAlignment = Alignment.Center,
|
||||||
|
modifier = Modifier.size(44.dp).clip(Shape12).background(pal.signal.copy(alpha = 0.12f)).border(1.dp, pal.signal.copy(alpha = 0.35f), Shape12),
|
||||||
|
) { Icon(Icons.Filled.Add, null, tint = pal.signal, modifier = Modifier.size(24.dp)) }
|
||||||
|
TileText(stringResource(R.string.user_apps_add), stringResource(R.string.user_apps_add_detail), Modifier.weight(1f))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** The add or remove under way, or why the last one failed. */
|
/** The add or remove under way, or why the last one failed. */
|
||||||
@Composable
|
@Composable
|
||||||
private fun UserAppsProgress() {
|
private fun UserAppsProgress() {
|
||||||
@@ -501,17 +597,20 @@ private fun UserAppsProgress() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** An added app's page: open it, change its name and icon, update one added from GitHub, or remove it (asked first). */
|
/** An added app's page: open it, change its name and icon, update one added from GitHub, or remove it (pressed twice). */
|
||||||
@Composable
|
@Composable
|
||||||
private fun UserAppPage(app: UserApps.App, s: FrontEndState, a: FrontEndActions, onSelect: (String) -> Unit) {
|
private fun UserAppPage(app: UserApps.App, s: FrontEndState, a: FrontEndActions, onSelect: (String) -> Unit) {
|
||||||
val colors = MaterialTheme.colorScheme
|
val colors = MaterialTheme.colorScheme
|
||||||
val ctx = LocalContext.current
|
val ctx = LocalContext.current
|
||||||
val narrow = LocalNarrowPane.current
|
val narrow = LocalNarrowPane.current
|
||||||
|
var confirm by remember(app.key) { mutableStateOf(false) }
|
||||||
var editing by rememberSaveable(app.key) { mutableStateOf(false) }
|
var editing by rememberSaveable(app.key) { mutableStateOf(false) }
|
||||||
val x86 = (app.arch == "x86_64" || app.arch == "i386") && app.fex != com.droiddeck.launcher.runtime.LinuxFex.OFF
|
val x86 = (app.arch == "x86_64" || app.arch == "i386") && app.fex != com.droiddeck.launcher.runtime.LinuxFex.OFF
|
||||||
val fexReady by produceState<Boolean?>(null, app.key, x86, s.sessionRunning) {
|
val fexReady by produceState<Boolean?>(null, app.key, x86, s.sessionRunning) {
|
||||||
value = if (x86) kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { com.droiddeck.launcher.runtime.LinuxFex.ready(ctx) } else true
|
value = if (x86) kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { com.droiddeck.launcher.runtime.LinuxFex.ready(ctx) } else true
|
||||||
}
|
}
|
||||||
|
LaunchedEffect(confirm) { if (confirm) { kotlinx.coroutines.delay(4000); confirm = false } }
|
||||||
|
Rise(0) { BackLink(stringResource(R.string.user_apps_back)) { onSelect("desktop") } }
|
||||||
Rise(1) {
|
Rise(1) {
|
||||||
Row(
|
Row(
|
||||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(14.dp),
|
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(14.dp),
|
||||||
@@ -534,8 +633,12 @@ private fun UserAppPage(app: UserApps.App, s: FrontEndState, a: FrontEndActions,
|
|||||||
BusyChip(s)
|
BusyChip(s)
|
||||||
SecondaryButton(stringResource(R.string.user_apps_edit), enabled = UserAppsState.working == null) { editing = true }
|
SecondaryButton(stringResource(R.string.user_apps_edit), enabled = UserAppsState.working == null) { editing = true }
|
||||||
if (app.repo != null) UpdateButton(app, s)
|
if (app.repo != null) UpdateButton(app, s)
|
||||||
RemoveAppButton(app, enabled = !s.busy && !s.sessionRunning && UserAppsState.working == null) {
|
SecondaryButton(
|
||||||
UserAppsState.remove(ctx, app); onSelect("desktop")
|
stringResource(if (confirm) R.string.user_apps_remove_confirm else R.string.user_apps_remove),
|
||||||
|
enabled = !s.busy && !s.sessionRunning && UserAppsState.working == null,
|
||||||
|
) {
|
||||||
|
if (!confirm) confirm = true
|
||||||
|
else { confirm = false; UserAppsState.remove(ctx, app); onSelect("desktop") }
|
||||||
}
|
}
|
||||||
if (s.sessionRunning) ActionChip(stringResource(R.string.user_apps_stop_session), ok = false)
|
if (s.sessionRunning) ActionChip(stringResource(R.string.user_apps_stop_session), ok = false)
|
||||||
}
|
}
|
||||||
@@ -556,31 +659,6 @@ private fun UserAppPage(app: UserApps.App, s: FrontEndState, a: FrontEndActions,
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Remove, which asks first: are you sure steps out of it in red, Keep first and focused. */
|
|
||||||
@Composable
|
|
||||||
private fun RemoveAppButton(app: UserApps.App, enabled: Boolean, onRemove: () -> Unit) {
|
|
||||||
val colors = MaterialTheme.colorScheme
|
|
||||||
val label = stringResource(R.string.user_apps_remove)
|
|
||||||
val title = stringResource(R.string.flathub_remove_title, app.name)
|
|
||||||
val keep = stringResource(R.string.flathub_keep)
|
|
||||||
var at by remember { mutableStateOf<androidx.compose.ui.geometry.Rect?>(null) }
|
|
||||||
Box(Modifier.onGloballyPositioned { at = it.boundsInRoot() }) {
|
|
||||||
SecondaryButton(label, enabled = enabled) {
|
|
||||||
val from = at ?: return@SecondaryButton
|
|
||||||
Steps.ask(StepAsk(
|
|
||||||
anchor = from, side = StepSide.Right, accent = colors.error, pillCorner = 12.dp, items = 2,
|
|
||||||
handle = { Text(label, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.error, maxLines = 1) },
|
|
||||||
) {
|
|
||||||
StepTitle(title)
|
|
||||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.stepItem(1)) {
|
|
||||||
StepChoice(keep, enabled = open, modifier = Modifier.focusRequester(first)) { Steps.fold() }
|
|
||||||
StepChoice(label, danger = true, enabled = open) { Steps.fold(); onRemove() }
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Looks up a newer release of an app added from GitHub, then installs it. */
|
/** Looks up a newer release of an app added from GitHub, then installs it. */
|
||||||
@Composable
|
@Composable
|
||||||
private fun UpdateButton(app: UserApps.App, s: FrontEndState) {
|
private fun UpdateButton(app: UserApps.App, s: FrontEndState) {
|
||||||
@@ -612,5 +690,21 @@ private fun UpdateButton(app: UserApps.App, s: FrontEndState) {
|
|||||||
private fun systemLabel(e: Library.Emulator): String =
|
private fun systemLabel(e: Library.Emulator): String =
|
||||||
if (e.systemRes != 0) stringResource(e.systemRes) else e.system.replaceFirstChar { it.uppercase() }
|
if (e.systemRes != 0) stringResource(e.systemRes) else e.system.replaceFirstChar { it.uppercase() }
|
||||||
|
|
||||||
/** The system a ROM belongs to: the folder it sits in under the ROMs folder. */
|
@Composable
|
||||||
private fun romSystem(rom: Library.Rom): String = rom.hostPath.parentFile?.name.orEmpty()
|
private fun EmulatorTile(e: Library.Emulator, modifier: Modifier, isFirst: Boolean, onClick: () -> Unit) {
|
||||||
|
val colors = MaterialTheme.colorScheme
|
||||||
|
val pal = LocalPalette.current
|
||||||
|
val system = systemLabel(e)
|
||||||
|
val detail = if (e.installed && e.id != "retroarch") "$system · " + pluralStringResource(R.plurals.mode_added_count, e.games.size, e.games.size) else system
|
||||||
|
TileFrame("emu:${e.id}", modifier, isFirst, filled = e.installed, onClick = onClick) {
|
||||||
|
Image(painterResource(e.iconRes), contentDescription = null, modifier = Modifier.size(if (e.installed) 44.dp else 36.dp))
|
||||||
|
Column(modifier = Modifier.weight(1f)) {
|
||||||
|
Text(e.name, fontSize = if (e.installed) 15.sp else 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||||
|
Text(detail, fontSize = if (e.installed) 13.sp else 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||||
|
}
|
||||||
|
if (!e.installed) Text(
|
||||||
|
stringResource(R.string.setup_install), fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = pal.signal,
|
||||||
|
modifier = Modifier.clip(RoundedCornerShape(8.dp)).border(1.dp, pal.line2, RoundedCornerShape(8.dp)).padding(horizontal = 10.dp, vertical = 6.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -322,18 +322,8 @@ private fun GameList(
|
|||||||
modifier = modifier.verticalScroll(rememberScrollState()).padding(start = 12.dp, end = 10.dp, top = 16.dp, bottom = 16.dp),
|
modifier = modifier.verticalScroll(rememberScrollState()).padding(start = 12.dp, end = 10.dp, top = 16.dp, bottom = 16.dp),
|
||||||
) {
|
) {
|
||||||
GamesHeader(games.size, onAdd, Modifier.padding(start = 6.dp, bottom = 10.dp))
|
GamesHeader(games.size, onAdd, Modifier.padding(start = 6.dp, bottom = 10.dp))
|
||||||
// A game that arrives while the list is up (Steam installed it in the session that just
|
|
||||||
// ended, or it was added) eases in; the ones there when the page opened are simply there.
|
|
||||||
val seen = remember { HashSet<Int>() }
|
|
||||||
var settled by remember { androidx.compose.runtime.mutableStateOf(false) }
|
|
||||||
for (g in games) key(g.appId) {
|
for (g in games) key(g.appId) {
|
||||||
Box(Modifier.arriveIn(settled && g.appId !in seen)) {
|
GameRow(g, g.appId == current.appId, onSelect = { onSelect(g) }, onLaunch = { onLaunch(g) })
|
||||||
GameRow(g, g.appId == current.appId, onSelect = { onSelect(g) }, onLaunch = { onLaunch(g) })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
androidx.compose.runtime.SideEffect {
|
|
||||||
seen.addAll(games.map { it.appId })
|
|
||||||
if (games.isNotEmpty()) settled = true
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -452,14 +442,6 @@ private fun AddGameButton(onClick: () -> Unit) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Fades and slides a row in once when [arriving]; nothing for one already there (or with animations off). */
|
|
||||||
@Composable
|
|
||||||
internal fun Modifier.arriveIn(arriving: Boolean): Modifier {
|
|
||||||
val t = remember { androidx.compose.animation.core.Animatable(if (arriving) 0f else 1f) }
|
|
||||||
LaunchedEffect(Unit) { if (t.value < 1f) t.animateTo(1f, Motion.tw(280)) }
|
|
||||||
return graphicsLayer { alpha = t.value; translationY = (1f - t.value) * 12.dp.toPx() }
|
|
||||||
}
|
|
||||||
|
|
||||||
/** One game in the list. Moving onto it with the pad shows it; A launches it, a tap only shows it. */
|
/** One game in the list. Moving onto it with the pad shows it; A launches it, a tap only shows it. */
|
||||||
@Composable
|
@Composable
|
||||||
private fun GameRow(g: Library.SteamGame, selected: Boolean, onSelect: () -> Unit, onLaunch: () -> Unit) {
|
private fun GameRow(g: Library.SteamGame, selected: Boolean, onSelect: () -> Unit, onLaunch: () -> Unit) {
|
||||||
|
|||||||
@@ -77,9 +77,6 @@ import androidx.compose.ui.text.style.TextOverflow
|
|||||||
import androidx.compose.ui.unit.Dp
|
import androidx.compose.ui.unit.Dp
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.compose.ui.unit.sp
|
import androidx.compose.ui.unit.sp
|
||||||
import androidx.compose.ui.layout.boundsInParent
|
|
||||||
import androidx.compose.ui.layout.boundsInRoot
|
|
||||||
import androidx.compose.ui.layout.onGloballyPositioned
|
|
||||||
import com.droiddeck.launcher.core.PhantomProcessLimit
|
import com.droiddeck.launcher.core.PhantomProcessLimit
|
||||||
|
|
||||||
// The front end's side rail: the page list and the resume entry under it.
|
// The front end's side rail: the page list and the resume entry under it.
|
||||||
@@ -106,53 +103,27 @@ internal fun SideRail(
|
|||||||
modifier = modifier.width(if (iconOnly) 64.dp else 92.dp).background(colors.surface).padding(vertical = if (compact) 8.dp else 12.dp),
|
modifier = modifier.width(if (iconOnly) 64.dp else 92.dp).background(colors.surface).padding(vertical = if (compact) 8.dp else 12.dp),
|
||||||
) {
|
) {
|
||||||
// Every section on screen at once: items shrink (to 44dp, still a touch target) before the rail scrolls.
|
// Every section on screen at once: items shrink (to 44dp, still a touch target) before the rail scrolls.
|
||||||
val count = 6 + (if (s.gameStoresEnabled) 1 else 0) + (if (s.isHomeApp) 1 else 0)
|
val count = 6 + (if (s.storeEnabled) 1 else 0) + (if (s.gameStoresEnabled) 1 else 0) + (if (s.isHomeApp) 1 else 0)
|
||||||
BoxWithConstraints(Modifier.weight(1f).fillMaxWidth()) {
|
BoxWithConstraints(Modifier.weight(1f).fillMaxWidth()) {
|
||||||
val fit = (maxHeight / count - 4.dp).coerceIn(44.dp, if (iconOnly) 48.dp else if (compact) 52.dp else 60.dp)
|
val fit = (maxHeight / count - 4.dp).coerceIn(44.dp, if (iconOnly) 48.dp else if (compact) 52.dp else 60.dp)
|
||||||
// A hop in flight moves the selection ahead of the page it is bringing.
|
|
||||||
val shown = Hops.railPreview ?: selected
|
|
||||||
val keys = buildList {
|
|
||||||
add("steam"); add("games")
|
|
||||||
if (s.gameStoresEnabled) add("stores")
|
|
||||||
add("desktop")
|
|
||||||
add("components")
|
|
||||||
if (s.isHomeApp) add("android-apps")
|
|
||||||
add("setup"); add("updates")
|
|
||||||
}
|
|
||||||
// Where each item sits in the column, for the selection that glides between them.
|
|
||||||
val bounds = remember { androidx.compose.runtime.mutableStateMapOf<String, androidx.compose.ui.geometry.Rect>() }
|
|
||||||
val tint = androidx.compose.runtime.rememberUpdatedState(LocalPalette.current.signal)
|
|
||||||
var railAt by remember { mutableStateOf(androidx.compose.ui.geometry.Offset.Zero) }
|
|
||||||
Box(Modifier.fillMaxSize().verticalScroll(rememberScrollState()).onGloballyPositioned { railAt = it.boundsInRoot().topLeft }) {
|
|
||||||
// One selection for the whole rail, under the items: it glides from item to item as the
|
|
||||||
// chips' does, its leading edge first, and a jump of more than one item goes as a drop.
|
|
||||||
if (shown in keys) ChipGlide(keys.indexOf(shown), bounds[shown]?.translate(-railAt), tint, GlideAxis.Vertical, corner = 14.dp, fill = 0.14f, outline = 0f)
|
|
||||||
Column(
|
Column(
|
||||||
horizontalAlignment = Alignment.CenterHorizontally,
|
horizontalAlignment = Alignment.CenterHorizontally,
|
||||||
verticalArrangement = Arrangement.spacedBy(4.dp),
|
verticalArrangement = Arrangement.spacedBy(4.dp),
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxSize().verticalScroll(rememberScrollState()),
|
||||||
) {
|
) {
|
||||||
val place: (String) -> Modifier = { key ->
|
RailItem(stringResource(R.string.rail_steam), Icons.Outlined.SportsEsports, "steam", selected == "steam", compact, iconOnly, fit, onFocus = { onFocusSelect("steam") }) { onSelect("steam") }
|
||||||
// In root px: an item that comes and goes sits in its own wrapper, not the column.
|
|
||||||
Modifier.onGloballyPositioned {
|
|
||||||
bounds[key] = it.boundsInRoot()
|
|
||||||
Hops.railBounds[key] = it.boundsInRoot()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
RailItem(stringResource(R.string.rail_steam), Icons.Outlined.SportsEsports, "steam", shown == "steam", compact, iconOnly, fit, place = place, onFocus = { onFocusSelect("steam") }) { onSelect("steam") }
|
|
||||||
// Always there, so the items below it never move; an empty library says how to fill it.
|
// Always there, so the items below it never move; an empty library says how to fill it.
|
||||||
RailItem(stringResource(R.string.rail_games), Icons.Outlined.VideoLibrary, "games", shown == "games", compact, iconOnly, fit, place = place, onFocus = { onFocusSelect("games") }) { onSelect("games") }
|
RailItem(stringResource(R.string.rail_games), Icons.Outlined.VideoLibrary, "games", selected == "games", compact, iconOnly, fit, onFocus = { onFocusSelect("games") }) { onSelect("games") }
|
||||||
// The game stores, right under Games: what they install lands there. Its badge counts
|
// The game stores, right under Games: what they install lands there. Its badge counts
|
||||||
// the downloads in flight, so a download started here is never out of sight.
|
// the downloads in flight, so a download started here is never out of sight.
|
||||||
// A section switched on in Setup comes in as the rail's own entrance; off, it folds away.
|
if (s.gameStoresEnabled) RailItem(stringResource(R.string.rail_stores), Icons.Outlined.LocalMall, "stores", selected == "stores", compact, iconOnly, fit, count = s.storeDownloadsActive, onFocus = { onFocusSelect("stores") }) { onSelect("stores") }
|
||||||
if (s.gameStoresEnabled) RailItem(stringResource(R.string.rail_stores), Icons.Outlined.LocalMall, "stores", shown == "stores", compact, iconOnly, fit, count = s.storeDownloadsActive, place = place, onFocus = { onFocusSelect("stores") }) { onSelect("stores") }
|
RailItem(stringResource(R.string.rail_desktop), Icons.Outlined.DesktopWindows, "desktop", selected == "desktop", compact, iconOnly, fit, onFocus = { onFocusSelect("desktop") }) { onSelect("desktop") }
|
||||||
RailItem(stringResource(R.string.rail_desktop), Icons.Outlined.DesktopWindows, "desktop", shown == "desktop", compact, iconOnly, fit, place = place, onFocus = { onFocusSelect("desktop") }) { onSelect("desktop") }
|
if (s.storeEnabled) RailItem(stringResource(R.string.rail_store), Icons.Outlined.Storefront, "store", selected == "store", compact, iconOnly, fit, onFocus = { onFocusSelect("store") }) { onSelect("store") }
|
||||||
RailItem(stringResource(R.string.rail_components), Icons.Outlined.Layers, "components", shown == "components", compact, iconOnly, fit, place = place, onFocus = { onFocusSelect("components") }) { onSelect("components") }
|
RailItem(stringResource(R.string.rail_components), Icons.Outlined.Layers, "components", selected == "components", compact, iconOnly, fit, onFocus = { onFocusSelect("components") }) { onSelect("components") }
|
||||||
// Home mode's extra section goes last, so it shifts nothing above it.
|
// Home mode's extra section goes last, so it shifts nothing above it.
|
||||||
if (s.isHomeApp) RailItem(stringResource(R.string.rail_apps), Icons.Outlined.Apps, "android-apps", shown == "android-apps", compact, iconOnly, fit, place = place, onFocus = { onFocusSelect("android-apps") }) { onSelect("android-apps") }
|
if (s.isHomeApp) RailItem(stringResource(R.string.rail_apps), Icons.Outlined.Apps, "android-apps", selected == "android-apps", compact, iconOnly, fit, onFocus = { onFocusSelect("android-apps") }) { onSelect("android-apps") }
|
||||||
RailItem(stringResource(R.string.rail_setup), Icons.Outlined.Tune, "setup", shown == "setup", compact, iconOnly, fit, badge = setupNeedsAttention, place = place, onFocus = { onFocusSelect("setup") }) { onSelect("setup") }
|
RailItem(stringResource(R.string.rail_setup), Icons.Outlined.Tune, "setup", selected == "setup", compact, iconOnly, fit, badge = setupNeedsAttention, onFocus = { onFocusSelect("setup") }) { onSelect("setup") }
|
||||||
RailItem(stringResource(R.string.rail_updates), Icons.Outlined.SystemUpdate, "updates", shown == "updates", compact, iconOnly, fit, badge = s.updates.hasUpdate, place = place, onFocus = { onFocusSelect("updates") }) { onSelect("updates") }
|
RailItem(stringResource(R.string.rail_updates), Icons.Outlined.SystemUpdate, "updates", selected == "updates", compact, iconOnly, fit, badge = s.updates.hasUpdate, onFocus = { onFocusSelect("updates") }) { onSelect("updates") }
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
var lastRunning by remember { mutableStateOf("") }
|
var lastRunning by remember { mutableStateOf("") }
|
||||||
@@ -171,8 +142,6 @@ private fun RailItem(
|
|||||||
badge: Boolean = false,
|
badge: Boolean = false,
|
||||||
/** A number on the item (downloads in flight); 0 shows nothing. */
|
/** A number on the item (downloads in flight); 0 shows nothing. */
|
||||||
count: Int = 0,
|
count: Int = 0,
|
||||||
/** Reports where the item sits, for the rail's gliding selection and a hop's dot. */
|
|
||||||
place: (String) -> Modifier = { Modifier },
|
|
||||||
onFocus: () -> Unit = {}, onClick: () -> Unit,
|
onFocus: () -> Unit = {}, onClick: () -> Unit,
|
||||||
) {
|
) {
|
||||||
val colors = MaterialTheme.colorScheme
|
val colors = MaterialTheme.colorScheme
|
||||||
@@ -193,9 +162,8 @@ private fun RailItem(
|
|||||||
if (current) pal.signal else if (focused || hovered) colors.onBackground else colors.onSurfaceVariant,
|
if (current) pal.signal else if (focused || hovered) colors.onBackground else colors.onSurfaceVariant,
|
||||||
Motion.tw(220), label = "railFg",
|
Motion.tw(220), label = "railFg",
|
||||||
)
|
)
|
||||||
// The selected look is the rail's glide under the item, so the item draws only hover here.
|
|
||||||
val fill by animateColorAsState(
|
val fill by animateColorAsState(
|
||||||
if (current) Color.Transparent else if (focused || hovered) Color.White.copy(alpha = 0.05f) else Color.Transparent,
|
if (current) pal.signal.copy(alpha = 0.14f) else if (focused || hovered) Color.White.copy(alpha = 0.05f) else Color.Transparent,
|
||||||
Motion.tw(220), label = "railFill",
|
Motion.tw(220), label = "railFill",
|
||||||
)
|
)
|
||||||
val scale by animateFloatAsState(if (pressed) 0.95f else 1f, Motion.sp(0.5f, Spring.StiffnessMedium), label = "railScale")
|
val scale by animateFloatAsState(if (pressed) 0.95f else 1f, Motion.sp(0.5f, Spring.StiffnessMedium), label = "railScale")
|
||||||
@@ -204,9 +172,6 @@ private fun RailItem(
|
|||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.then(if (frontFocus != null) Modifier.focusRequester(frontFocus.railFor(key)) else Modifier)
|
.then(if (frontFocus != null) Modifier.focusRequester(frontFocus.railFor(key)) else Modifier)
|
||||||
.testTag("rail-$key")
|
.testTag("rail-$key")
|
||||||
.then(place(key))
|
|
||||||
// Pops as a hop's dot lands on it.
|
|
||||||
.landingPop(Hops.railLanded[key] ?: 0)
|
|
||||||
.graphicsLayer { scaleX = scale; scaleY = scale }
|
.graphicsLayer { scaleX = scale; scaleY = scale }
|
||||||
.size(width = if (iconOnly) 52.dp else 80.dp, height = height)
|
.size(width = if (iconOnly) 52.dp else 80.dp, height = height)
|
||||||
.clip(Shape14)
|
.clip(Shape14)
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package com.droiddeck.launcher.ui
|
|||||||
|
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import androidx.compose.ui.res.stringResource
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import androidx.compose.ui.platform.LocalInspectionMode
|
||||||
import com.droiddeck.launcher.R
|
import com.droiddeck.launcher.R
|
||||||
|
|
||||||
import androidx.compose.runtime.staticCompositionLocalOf
|
import androidx.compose.runtime.staticCompositionLocalOf
|
||||||
@@ -33,16 +34,13 @@ import androidx.compose.foundation.layout.Box
|
|||||||
import androidx.compose.runtime.key
|
import androidx.compose.runtime.key
|
||||||
import androidx.compose.foundation.layout.Column
|
import androidx.compose.foundation.layout.Column
|
||||||
import androidx.compose.foundation.layout.Row
|
import androidx.compose.foundation.layout.Row
|
||||||
import androidx.compose.foundation.layout.WindowInsets
|
|
||||||
import androidx.compose.foundation.layout.displayCutout
|
|
||||||
import androidx.compose.foundation.layout.fillMaxHeight
|
import androidx.compose.foundation.layout.fillMaxHeight
|
||||||
import androidx.compose.foundation.layout.fillMaxSize
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
import androidx.compose.foundation.layout.fillMaxWidth
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
import androidx.compose.foundation.layout.height
|
import androidx.compose.foundation.layout.height
|
||||||
import androidx.compose.foundation.layout.size
|
import androidx.compose.foundation.layout.size
|
||||||
import androidx.compose.foundation.layout.systemBars
|
import androidx.compose.foundation.layout.systemBarsPadding
|
||||||
import androidx.compose.foundation.layout.width
|
import androidx.compose.foundation.layout.width
|
||||||
import androidx.compose.foundation.layout.windowInsetsPadding
|
|
||||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
import androidx.compose.material.icons.filled.Settings
|
import androidx.compose.material.icons.filled.Settings
|
||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
@@ -70,8 +68,6 @@ import androidx.compose.ui.platform.LocalInputModeManager
|
|||||||
import androidx.compose.ui.input.InputMode
|
import androidx.compose.ui.input.InputMode
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.compose.ui.unit.sp
|
import androidx.compose.ui.unit.sp
|
||||||
import androidx.compose.ui.layout.onGloballyPositioned
|
|
||||||
import androidx.compose.ui.layout.positionInRoot
|
|
||||||
import com.droiddeck.launcher.HomeApp
|
import com.droiddeck.launcher.HomeApp
|
||||||
import com.droiddeck.launcher.frontend.Library
|
import com.droiddeck.launcher.frontend.Library
|
||||||
import com.droiddeck.launcher.gpu.FrameGen
|
import com.droiddeck.launcher.gpu.FrameGen
|
||||||
@@ -131,10 +127,12 @@ class FrontEndState(
|
|||||||
val controller: com.droiddeck.launcher.input.ControllerPrefs.Settings? = null,
|
val controller: com.droiddeck.launcher.input.ControllerPrefs.Settings? = null,
|
||||||
val phantomProcessStatus: PhantomProcessStatus = PhantomProcessStatus.NOT_APPLICABLE,
|
val phantomProcessStatus: PhantomProcessStatus = PhantomProcessStatus.NOT_APPLICABLE,
|
||||||
val showPhantomGate: Boolean = false,
|
val showPhantomGate: Boolean = false,
|
||||||
val orientation: Int = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE,
|
|
||||||
val launcherFullscreen: Boolean = true,
|
val launcherFullscreen: Boolean = true,
|
||||||
val animationsEnabled: Boolean = true,
|
val animationsEnabled: Boolean = true,
|
||||||
val gameStoresEnabled: Boolean = true,
|
/** The Flathub Store, a beta the user turns on in Setup. */
|
||||||
|
val storeEnabled: Boolean = false,
|
||||||
|
/** The Stores section (GOG, Epic Games, Amazon Games), turned on in Setup. */
|
||||||
|
val gameStoresEnabled: Boolean = false,
|
||||||
/** Setup › Stores: the download engine's speed tier (stores/download/StoreDownloadTier ids). */
|
/** Setup › Stores: the download engine's speed tier (stores/download/StoreDownloadTier ids). */
|
||||||
val gameStoresSpeedTier: String = "fast",
|
val gameStoresSpeedTier: String = "fast",
|
||||||
/** Setup › Stores: the tab a signed-in store opens on (SessionPrefs.STORES_OPEN_LIBRARY / STORE). */
|
/** Setup › Stores: the tab a signed-in store opens on (SessionPrefs.STORES_OPEN_LIBRARY / STORE). */
|
||||||
@@ -177,12 +175,8 @@ class FrontEndActions(
|
|||||||
val onUserApp: (com.droiddeck.launcher.runtime.UserApps.App) -> Unit = {},
|
val onUserApp: (com.droiddeck.launcher.runtime.UserApps.App) -> Unit = {},
|
||||||
val onRom: (Library.Rom) -> Unit,
|
val onRom: (Library.Rom) -> Unit,
|
||||||
val onResume: () -> Unit,
|
val onResume: () -> Unit,
|
||||||
/** Reads Steam's session settings for its lifted sheet (under Play). */
|
|
||||||
val onSteamSettings: () -> Unit,
|
val onSteamSettings: () -> Unit,
|
||||||
/** Reads the desktop's session settings for its lifted sheet (under Open desktop). */
|
|
||||||
val onDesktopSettings: () -> Unit,
|
val onDesktopSettings: () -> Unit,
|
||||||
/** A lifted sheet's rows for one tab of [mode]'s settings, as last read. */
|
|
||||||
val modeSheet: @Composable (mode: String, tab: String, extras: SheetExtras) -> Unit = { _, _, _ -> },
|
|
||||||
val onRemoveDesktop: () -> Unit = {},
|
val onRemoveDesktop: () -> Unit = {},
|
||||||
val onInstallPackage: (String) -> Unit,
|
val onInstallPackage: (String) -> Unit,
|
||||||
val onRemovePackage: (String) -> Unit,
|
val onRemovePackage: (String) -> Unit,
|
||||||
@@ -192,8 +186,6 @@ class FrontEndActions(
|
|||||||
val onProtons: () -> Unit,
|
val onProtons: () -> Unit,
|
||||||
/** The Components page: FEX / DXVK / VKD3D-Proton per Proton. */
|
/** The Components page: FEX / DXVK / VKD3D-Proton per Proton. */
|
||||||
val onComponents: (focusContent: Boolean) -> Unit,
|
val onComponents: (focusContent: Boolean) -> Unit,
|
||||||
/** The Components page on one layer ([GPU_TAB], a component id): a hop's destination. */
|
|
||||||
val onComponentsTab: (String) -> Unit = {},
|
|
||||||
/** A game page's Manage saves: import a save zip into this game, or export its saves in a layout. */
|
/** A game page's Manage saves: import a save zip into this game, or export its saves in a layout. */
|
||||||
val onSaveImport: (Library.SteamGame) -> Unit = {},
|
val onSaveImport: (Library.SteamGame) -> Unit = {},
|
||||||
val onSaveExport: (Library.SteamGame, com.droiddeck.launcher.session.GameSaves.Layout) -> Unit = { _, _ -> },
|
val onSaveExport: (Library.SteamGame, com.droiddeck.launcher.session.GameSaves.Layout) -> Unit = { _, _ -> },
|
||||||
@@ -210,9 +202,9 @@ class FrontEndActions(
|
|||||||
val onTheme: (String) -> Unit = {},
|
val onTheme: (String) -> Unit = {},
|
||||||
val onLanguage: (String) -> Unit = {},
|
val onLanguage: (String) -> Unit = {},
|
||||||
val onAppScale: (Int) -> Unit = {},
|
val onAppScale: (Int) -> Unit = {},
|
||||||
val onOrientation: (Int) -> Unit = {},
|
|
||||||
val onLauncherFullscreen: (Boolean) -> Unit = {},
|
val onLauncherFullscreen: (Boolean) -> Unit = {},
|
||||||
val onAnimationsEnabled: (Boolean) -> Unit = {},
|
val onAnimationsEnabled: (Boolean) -> Unit = {},
|
||||||
|
val onStoreEnabled: (Boolean) -> Unit = {},
|
||||||
val onGameStoresEnabled: (Boolean) -> Unit = {},
|
val onGameStoresEnabled: (Boolean) -> Unit = {},
|
||||||
val onGameStoresSpeedTier: (String) -> Unit = {},
|
val onGameStoresSpeedTier: (String) -> Unit = {},
|
||||||
val onStoresOpenTab: (String) -> Unit = {},
|
val onStoresOpenTab: (String) -> Unit = {},
|
||||||
@@ -268,7 +260,8 @@ internal fun artBrush(h: Float) = Brush.linearGradient(listOf(tint(h), tint((h +
|
|||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
internal fun Rise(i: Int, modifier: Modifier = Modifier, content: @Composable () -> Unit) {
|
internal fun Rise(i: Int, modifier: Modifier = Modifier, content: @Composable () -> Unit) {
|
||||||
val state = remember { MutableTransitionState(false) }.apply { targetState = true }
|
val inspecting = LocalInspectionMode.current
|
||||||
|
val state = remember { MutableTransitionState(inspecting) }.apply { targetState = true }
|
||||||
AnimatedVisibility(
|
AnimatedVisibility(
|
||||||
visibleState = state, modifier = modifier,
|
visibleState = state, modifier = modifier,
|
||||||
enter = fadeIn(Motion.tw(450, i * 60)) + slideInVertically(Motion.tw(450, i * 60)) { it / 3 },
|
enter = fadeIn(Motion.tw(450, i * 60)) + slideInVertically(Motion.tw(450, i * 60)) { it / 3 },
|
||||||
@@ -279,6 +272,7 @@ internal fun Rise(i: Int, modifier: Modifier = Modifier, content: @Composable ()
|
|||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
private fun Modifier.staggerIn(i: Int): Modifier {
|
private fun Modifier.staggerIn(i: Int): Modifier {
|
||||||
|
if (LocalInspectionMode.current) return this
|
||||||
val t = remember { Animatable(0f) }
|
val t = remember { Animatable(0f) }
|
||||||
LaunchedEffect(Unit) { t.animateTo(1f, Motion.tw(360, i * 30)) }
|
LaunchedEffect(Unit) { t.animateTo(1f, Motion.tw(360, i * 30)) }
|
||||||
return graphicsLayer { alpha = t.value; translationY = (1f - t.value) * 10.dp.toPx() }
|
return graphicsLayer { alpha = t.value; translationY = (1f - t.value) * 10.dp.toPx() }
|
||||||
@@ -341,8 +335,6 @@ internal class FrontFocus {
|
|||||||
/** Down from this button goes to the first tile of the page's grid, when there is one. */
|
/** Down from this button goes to the first tile of the page's grid, when there is one. */
|
||||||
@Composable
|
@Composable
|
||||||
internal fun Modifier.downToFirstTile(): Modifier {
|
internal fun Modifier.downToFirstTile(): Modifier {
|
||||||
// Sheet rows walk their settings; Desktop's dock stays composed behind the sheet.
|
|
||||||
if (LocalSheetBeat.current != null) return this
|
|
||||||
val ff = LocalFrontFocus.current ?: return this
|
val ff = LocalFrontFocus.current ?: return this
|
||||||
return this.focusProperties { down = if (ff.firstTileAttached > 0) ff.firstTile else FocusRequester.Default }
|
return this.focusProperties { down = if (ff.firstTileAttached > 0) ff.firstTile else FocusRequester.Default }
|
||||||
}
|
}
|
||||||
@@ -388,28 +380,17 @@ internal suspend fun focusWithinFrames(done: () -> Boolean, target: () -> FocusR
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Asks [target] for focus on the next frames until a request lands (a control can take focus only
|
|
||||||
* once it is laid out), for at most half a second; then leaves focus alone, so a press right after
|
|
||||||
* is never pulled back.
|
|
||||||
*/
|
|
||||||
internal suspend fun focusSoon(target: () -> FocusRequester) {
|
|
||||||
repeat(30) {
|
|
||||||
androidx.compose.runtime.withFrameNanos { }
|
|
||||||
if (runCatching { target().requestFocus() }.isSuccess) return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
fun FrontEndScreen(s: FrontEndState, a: FrontEndActions, page: (@Composable () -> Unit)? = null) {
|
fun FrontEndScreen(s: FrontEndState, a: FrontEndActions, page: (@Composable () -> Unit)? = null, initialSelection: String = if (s.shortcutPicker) "games" else "steam") {
|
||||||
val frontFocus = remember { FrontFocus() }
|
val frontFocus = remember { FrontFocus() }
|
||||||
CompositionLocalProvider(LocalFrontFocus provides frontFocus) { FrontEndScreenBody(s, a, page, frontFocus) }
|
CompositionLocalProvider(LocalFrontFocus provides frontFocus) { FrontEndScreenBody(s, a, page, frontFocus, initialSelection) }
|
||||||
}
|
}
|
||||||
|
|
||||||
@OptIn(ExperimentalComposeUiApi::class)
|
@OptIn(ExperimentalComposeUiApi::class)
|
||||||
@Composable
|
@Composable
|
||||||
private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Composable () -> Unit)?, frontFocus: FrontFocus) {
|
private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Composable () -> Unit)?, frontFocus: FrontFocus, initialSelection: String) {
|
||||||
var selected by rememberSaveable { mutableStateOf(if (s.shortcutPicker) "games" else "steam") }
|
val inspecting = LocalInspectionMode.current
|
||||||
|
var selected by rememberSaveable { mutableStateOf(initialSelection) }
|
||||||
LaunchedEffect(s.shortcutPicker) { if (s.shortcutPicker) selected = "games" }
|
LaunchedEffect(s.shortcutPicker) { if (s.shortcutPicker) selected = "games" }
|
||||||
LaunchedEffect(s.navigate) {
|
LaunchedEffect(s.navigate) {
|
||||||
val target = s.navigate ?: return@LaunchedEffect
|
val target = s.navigate ?: return@LaunchedEffect
|
||||||
@@ -441,42 +422,31 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// A page reached by a hop goes back the way it came; any other page just closes.
|
BackHandler(enabled = !processSettingsPageVisible && s.pageKey != null && page != null) { a.onPageBack() }
|
||||||
val pageBack = { if (!Hops.back(a.onPageBack)) a.onPageBack() }
|
// Back (and B) from a ROM, an emulator or an added app steps out one level, as its "‹" link
|
||||||
BackHandler(enabled = !processSettingsPageVisible && s.pageKey != null && page != null) { pageBack() }
|
// does, instead of leaving the app: a ROM -> its emulator, the others -> Desktop.
|
||||||
// Left any other way, the hop's page has no way back to keep.
|
|
||||||
LaunchedEffect(s.pageKey, selected) { Hops.forget(s.pageKey ?: selected) }
|
|
||||||
// A section reached by a hop (Desktop's Flathub card to the Store) goes back the way it came.
|
|
||||||
BackHandler(enabled = !processSettingsPageVisible && s.pageKey == null && Hops.origin?.page == selected) {
|
|
||||||
val rail = Hops.origin?.rail ?: return@BackHandler
|
|
||||||
Hops.back { selected = rail }
|
|
||||||
}
|
|
||||||
val density = androidx.compose.ui.platform.LocalDensity.current.density
|
|
||||||
remember(density) { Hops.density = density; true }
|
|
||||||
// Back (and B) from a ROM, an emulator, an added app or Flathub steps out one level instead
|
|
||||||
// of leaving the app: a ROM -> its emulator, the others -> Desktop.
|
|
||||||
BackHandler(
|
BackHandler(
|
||||||
enabled = !processSettingsPageVisible && (s.pageKey == null || page == null) &&
|
enabled = !processSettingsPageVisible && (s.pageKey == null || page == null) &&
|
||||||
(selected.startsWith("emu:") || selected.startsWith("rom:") || selected.startsWith("user:") || selected == "store"),
|
(selected.startsWith("emu:") || selected.startsWith("rom:") || selected.startsWith("user:")),
|
||||||
) {
|
) {
|
||||||
selected = if (selected.startsWith("rom:")) "emu:" + selected.removePrefix("rom:").substringBefore(':') else "desktop"
|
selected = if (selected.startsWith("rom:")) "emu:" + selected.removePrefix("rom:").substringBefore(':') else "desktop"
|
||||||
}
|
}
|
||||||
LaunchedEffect(s.isHomeApp) { if (!s.isHomeApp && selected == "android-apps") selected = "steam" }
|
LaunchedEffect(s.isHomeApp) { if (!s.isHomeApp && selected == "android-apps") selected = "steam" }
|
||||||
|
// The Store turned off in Setup takes its page with it; so does Stores.
|
||||||
|
LaunchedEffect(s.storeEnabled) { if (!s.storeEnabled && selected == "store") selected = "steam" }
|
||||||
|
LaunchedEffect(s.gameStoresEnabled) { if (!s.gameStoresEnabled && selected == "stores") selected = "games" }
|
||||||
// The last game uninstalled leaves the Games tab on its empty state.
|
// The last game uninstalled leaves the Games tab on its empty state.
|
||||||
LaunchedEffect(s.steamGames.isEmpty()) {
|
LaunchedEffect(s.steamGames.isEmpty()) {
|
||||||
if (s.steamGames.isEmpty() && selected.startsWith("app:")) selected = "games"
|
if (s.steamGames.isEmpty() && selected.startsWith("app:")) selected = "games"
|
||||||
}
|
}
|
||||||
remember { Motion.refresh(ctx); true }
|
remember { if (!inspecting) Motion.refresh(ctx); true }
|
||||||
|
|
||||||
val railSelection = when {
|
val railSelection = when {
|
||||||
// A hop's page belongs to the rail item it flew to.
|
s.pageKey == "performance" || s.pageKey == "protons" || s.pageKey == "controller-mapping" -> "setup"
|
||||||
Hops.origin != null && s.pageKey == Hops.origin?.page -> Hops.origin!!.dest
|
s.pageKey?.startsWith("settings:steam") == true -> "steam"
|
||||||
// Performance opens from Play's sheet, and is Steam's.
|
s.pageKey?.startsWith("settings:") == true -> "desktop"
|
||||||
s.pageKey == "performance" -> "steam"
|
|
||||||
s.pageKey == "controller-mapping" -> "setup"
|
|
||||||
selected.startsWith("app:") -> "games"
|
selected.startsWith("app:") -> "games"
|
||||||
// Flathub is a page of Desktop's, as an emulator's is.
|
selected.startsWith("emu:") || selected.startsWith("rom:") || selected.startsWith("user:") -> "desktop"
|
||||||
selected.startsWith("emu:") || selected.startsWith("rom:") || selected.startsWith("user:") || selected == "store" -> "desktop"
|
|
||||||
else -> s.pageKey ?: selected
|
else -> s.pageKey ?: selected
|
||||||
}
|
}
|
||||||
// Bumped each time a rail item is picked, so a controller moves on into the new page.
|
// Bumped each time a rail item is picked, so a controller moves on into the new page.
|
||||||
@@ -487,10 +457,6 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
|||||||
if (key == "components") a.onComponents(focusContent)
|
if (key == "components") a.onComponents(focusContent)
|
||||||
else {
|
else {
|
||||||
if (s.pageKey != null) a.onPageBack()
|
if (s.pageKey != null) a.onPageBack()
|
||||||
// Another section: no way back to keep, and no sheet to put back.
|
|
||||||
Hops.origin = null
|
|
||||||
Hops.restore = null
|
|
||||||
Hops.sinking = null
|
|
||||||
selected = key
|
selected = key
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -503,11 +469,10 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
|||||||
}
|
}
|
||||||
val inputModeManager = LocalInputModeManager.current
|
val inputModeManager = LocalInputModeManager.current
|
||||||
val window = LocalWindowInfo.current
|
val window = LocalWindowInfo.current
|
||||||
val androidContext = androidx.compose.ui.platform.LocalContext.current
|
|
||||||
var anyFocused by remember { mutableStateOf(false) }
|
var anyFocused by remember { mutableStateOf(false) }
|
||||||
Box(
|
Box(
|
||||||
modifier = Modifier.fillMaxSize().background(colors.background)
|
modifier = Modifier.fillMaxSize().background(colors.background)
|
||||||
.windowInsetsPadding(if (s.launcherFullscreen) WindowInsets.displayCutout else WindowInsets.systemBars)
|
.then(if (s.launcherFullscreen) Modifier else Modifier.systemBarsPadding())
|
||||||
.onFocusChanged { anyFocused = it.hasFocus },
|
.onFocusChanged { anyFocused = it.hasFocus },
|
||||||
) {
|
) {
|
||||||
// Start controllers on the current page's main action, else on the rail.
|
// Start controllers on the current page's main action, else on the rail.
|
||||||
@@ -535,15 +500,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
|||||||
if (processSettingsPageVisible) return@LaunchedEffect
|
if (processSettingsPageVisible) return@LaunchedEffect
|
||||||
// Past the old page's exit (170ms), then the first frame the new page takes focus.
|
// Past the old page's exit (170ms), then the first frame the new page takes focus.
|
||||||
kotlinx.coroutines.delay(Motion.ms(PAGE_EXIT_MS).toLong())
|
kotlinx.coroutines.delay(Motion.ms(PAGE_EXIT_MS).toLong())
|
||||||
if (inputModeManager.inputMode != InputMode.Keyboard) return@LaunchedEffect
|
if (anyFocused || inputModeManager.inputMode != InputMode.Keyboard) return@LaunchedEffect
|
||||||
if (s.pageKey == "performance") {
|
|
||||||
val back = "back:${androidContext.getString(R.string.mode_back)}"
|
|
||||||
focusWithinFrames({ frontFocus.last == back && anyFocused && frontFocus.focusedRail == null }) {
|
|
||||||
frontFocus.items[back] ?: FocusRequester.Default
|
|
||||||
}
|
|
||||||
return@LaunchedEffect
|
|
||||||
}
|
|
||||||
if (anyFocused) return@LaunchedEffect
|
|
||||||
focusWithinFrames({ anyFocused }) { if (frontFocus.primaryAttached > 0) frontFocus.primary else frontFocus.railFor(railSelection) }
|
focusWithinFrames({ anyFocused }) { if (frontFocus.primaryAttached > 0) frontFocus.primary else frontFocus.railFor(railSelection) }
|
||||||
}
|
}
|
||||||
// A rail item picked with a controller moves on into its page, once the page is in.
|
// A rail item picked with a controller moves on into its page, once the page is in.
|
||||||
@@ -561,22 +518,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
|||||||
val railFocus = Modifier
|
val railFocus = Modifier
|
||||||
.focusProperties { enter = { frontFocus.railFor(railSelection) } }
|
.focusProperties { enter = { frontFocus.railFor(railSelection) } }
|
||||||
.focusGroup()
|
.focusGroup()
|
||||||
// Back from a hop onto a surface that is not a sheet (a game's Components card, Desktop's
|
Row(modifier = Modifier.fillMaxSize()) {
|
||||||
// Flathub card): focus
|
|
||||||
// goes back to the control that asked, once the page has gone.
|
|
||||||
LaunchedEffect(Hops.restore) {
|
|
||||||
val r = Hops.restore ?: return@LaunchedEffect
|
|
||||||
if (r.surface == HOP_SURFACE_SHEET) return@LaunchedEffect
|
|
||||||
Hops.restore = null
|
|
||||||
if (r.rail != selected && !(r.rail == "games" && selected.startsWith("app:"))) selected = r.rail
|
|
||||||
kotlinx.coroutines.delay(Motion.ms(PAGE_EXIT_MS).toLong())
|
|
||||||
if (inputModeManager.inputMode != InputMode.Keyboard) return@LaunchedEffect
|
|
||||||
frontFocus.last = r.control
|
|
||||||
focusWithinFrames({ frontFocus.last == r.control && anyFocused }) { frontFocus.items[r.control] ?: frontFocus.paneEntry() }
|
|
||||||
}
|
|
||||||
var screenAt by remember { mutableStateOf(Offset.Zero) }
|
|
||||||
CompositionLocalProvider(LocalShowSection provides { key -> selected = key }) {
|
|
||||||
Row(modifier = Modifier.fillMaxSize().onGloballyPositioned { screenAt = it.positionInRoot() }) {
|
|
||||||
SideRail(s, railSelection, onRailSelect, onRailFocus, a, railFocus.fillMaxHeight())
|
SideRail(s, railSelection, onRailSelect, onRailFocus, a, railFocus.fillMaxHeight())
|
||||||
Box(Modifier.width(1.dp).fillMaxHeight().background(pal.line))
|
Box(Modifier.width(1.dp).fillMaxHeight().background(pal.line))
|
||||||
Column(modifier = Modifier.weight(1f).fillMaxHeight()) {
|
Column(modifier = Modifier.weight(1f).fillMaxHeight()) {
|
||||||
@@ -592,12 +534,6 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
|
||||||
// Dots on their way somewhere: a hop to another section and back, a swap flying home.
|
|
||||||
FlightsLayer(screenAt)
|
|
||||||
// A confirm stepping out of the control that asked for it.
|
|
||||||
StepsLayer(screenAt)
|
|
||||||
|
|
||||||
appToChooseDisplay?.let { app ->
|
appToChooseDisplay?.let { app ->
|
||||||
val secondaryDisplay = s.secondScreenDisplays.firstOrNull()
|
val secondaryDisplay = s.secondScreenDisplays.firstOrNull()
|
||||||
ChooseAppDisplayDialog(
|
ChooseAppDisplayDialog(
|
||||||
@@ -660,10 +596,8 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
val hasBackTarget = (s.pageKey != null && page != null) ||
|
val hasBackTarget = (s.pageKey != null && page != null) ||
|
||||||
// A section reached by a hop goes back to where it came from, not to the rail.
|
|
||||||
(s.pageKey == null && Hops.origin?.page == selected) ||
|
|
||||||
((s.pageKey == null || page == null) &&
|
((s.pageKey == null || page == null) &&
|
||||||
(selected.startsWith("emu:") || selected.startsWith("rom:") || selected.startsWith("user:") || selected == "store"))
|
(selected.startsWith("emu:") || selected.startsWith("rom:") || selected.startsWith("user:")))
|
||||||
// At the top of a section, Back goes to the rail - the launcher itself is never backed out of.
|
// At the top of a section, Back goes to the rail - the launcher itself is never backed out of.
|
||||||
BackHandler(enabled = !processSettingsPageVisible && !hasBackTarget) {
|
BackHandler(enabled = !processSettingsPageVisible && !hasBackTarget) {
|
||||||
if (inputModeManager.inputMode != InputMode.Keyboard) inputModeManager.requestInputMode(InputMode.Keyboard)
|
if (inputModeManager.inputMode != InputMode.Keyboard) inputModeManager.requestInputMode(InputMode.Keyboard)
|
||||||
|
|||||||
Loaded 100 of 264 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user