diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 8612604928..091811b040 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -30,6 +30,7 @@ + @@ -81,6 +82,17 @@ + + + + + + + + + dmabuf == buffer && s->dmabuf_buf == b; if (!repeat) { + if (!s->dmabuf && s->last_dmabuf == buffer) g_pace.reattaches++; + s->last_dmabuf = buffer; + pace_note_buffer(buffer); drop_dmabuf(s, 1); s->dmabuf = buffer; s->dmabuf_buf = b; @@ -919,12 +944,15 @@ static void feedback_resource_destroy(struct wl_resource *r) { wl_list_remove(wl_resource_get_link(r)); } -static void feedback_discard_all(struct wl_list *list) { +static unsigned feedback_discard_all(struct wl_list *list) { struct wl_resource *fb, *tmp; + unsigned n = 0; wl_resource_for_each_safe(fb, tmp, list) { wp_presentation_feedback_send_discarded(fb); wl_resource_destroy(fb); + n++; } + return n; } static uint32_t nominal_refresh_ns(void) { @@ -953,6 +981,7 @@ static void feedback_present_all(struct wl_list *list, int64_t t) { nominal_refresh_ns(), 0, 0, WP_PRESENTATION_FEEDBACK_KIND_VSYNC); wl_resource_destroy(fb); + g_pace.presented++; } } @@ -1119,7 +1148,9 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) { struct wl_shm_buffer *shm = buffer && !db ? wl_shm_buffer_get(buffer) : NULL; uint8_t pixel[4]; - feedback_discard_all(&s->feedback); + g_pace.replaced += feedback_discard_all(&s->feedback); + if (!buffer) g_pace.null_attaches++; + else if (!db) s->last_dmabuf = NULL; if (buffer) { wl_list_remove(&s->pending_buffer_destroy.link); @@ -2092,14 +2123,23 @@ void droiddeck_stream_frame(AHardwareBuffer *ahb) { unsigned droiddeck_stream_frames(void) { return atomic_load(&g_stream_frames); } static void render_scene(void) { - if (atomic_load(&g_stream_on)) { render_stream(); return; } + if (atomic_load(&g_stream_on)) { g_dirty_since_ns = 0; render_stream(); return; } struct draw_list dl = {0}; struct surface *s; int w, h; const int64_t t_scene = now_ns(); int copy = 0; + if (g_dirty_since_ns) { + const int64_t wait = t_scene - g_dirty_since_ns; + g_pace.wait_ns += wait; + if (wait > g_pace.wait_max_ns) g_pace.wait_max_ns = wait; + g_pace.renders++; + g_dirty_since_ns = 0; + } g_dirty = 0; + g_rendered_tick_ns = g_tick_vsync_ns; + g_tick_held = 0; g_hud_fresh = 0; g_hdr_unimported = NULL; wl_list_for_each(s, &g_surfaces, link) s->drawn = 0; @@ -2239,7 +2279,7 @@ static void render_scene(void) { } wl_list_for_each(s, &g_surfaces, link) { if (s->drawn) feedback_present_all(&s->feedback, t); - else feedback_discard_all(&s->feedback); + else g_pace.undrawn += feedback_discard_all(&s->feedback); } fire_all_frames(); } else { @@ -2264,10 +2304,25 @@ static int on_fallback_timer(void *data) { return 0; } +/* A new frame is drawn when it arrives instead of at the next screen tick, at most once per refresh, + while frames go straight back to the game (no compositor limit), without streaming or frame generation. */ +static int commit_renders_on(void) { + return g_render_on_commit && g_release_unpaced && !atomic_load(&g_stream_on) && !vkp_framegen_active(); +} + +static int render_on_commit(void) { + return commit_renders_on() && !g_render_idle && g_rendered_tick_ns != g_tick_vsync_ns; +} + static void schedule_render(void) { + if (!g_dirty && !g_dirty_since_ns) g_dirty_since_ns = now_ns(); g_dirty = 1; if (!g_display) return; - if (g_last_vsync_ns && now_ns() - g_last_vsync_ns < 100000000LL) return; + if (g_last_vsync_ns && now_ns() - g_last_vsync_ns < 100000000LL) { + if (render_on_commit()) + g_render_idle = wl_event_loop_add_idle(wl_display_get_event_loop(g_display), on_commit_idle, NULL); + return; + } if (g_fallback_armed) return; if (!g_fallback_timer) g_fallback_timer = wl_event_loop_add_timer(wl_display_get_event_loop(g_display), @@ -2281,18 +2336,45 @@ static int scene_waits_for_game(int64_t now) { return g_hud_surface && !g_hud_fresh && now - g_hud_last_ns < 100000000LL && vkp_framegen_active(); } +static void on_commit_idle(void *data) { + g_render_idle = NULL; + if (!g_dirty || !commit_renders_on() || g_rendered_tick_ns == g_tick_vsync_ns || scene_waits_for_game(now_ns())) return; + g_pace.commit_renders++; + render_scene(); +} + static void on_vsync(int64_t frame_time_ns) { int64_t now = now_ns(); g_perf.ticks++; + if (frame_time_ns > 0 && now >= frame_time_ns) { + const int64_t late = now - frame_time_ns; + g_pace.ticks++; + g_pace.tick_late_ns += late; + if (late > g_pace.tick_late_max_ns) g_pace.tick_late_max_ns = late; + if (late > 2000000LL) g_pace.ticks_late_2ms++; + } if (g_last_vsync_ns) { int64_t d = now - g_last_vsync_ns; if (d > 3000000LL && d < 40000000LL) g_refresh_ns = (g_refresh_ns * 7 + d) / 8; } g_last_vsync_ns = now; g_tick_vsync_ns = frame_time_ns; - if (vkp_apply_window_request()) g_dirty = 1; - if (vkp_effects_sync()) g_dirty = 1; - if (vkp_cardboard_pose_changed()) g_dirty = 1; + int tick_change = 0; + if (vkp_apply_window_request()) tick_change = 1; + if (vkp_effects_sync()) tick_change = 1; + if (vkp_cardboard_pose_changed()) tick_change = 1; + if (tick_change) g_dirty = 1; + /* A frame that arrived after this refresh was already drawn is left for the next arrival to draw; + drawing it here would block that arrival too and keep every frame waiting for the tick. A client + that draws again only after its frame callback sends no such arrival: once a held frame is still + waiting at the next tick, the tick draws every frame for a second before holding one again. */ + if (g_tick_held && g_dirty) g_hold_missed_ns = now; + g_tick_held = 0; + if (!tick_change && commit_renders_on() && g_dirty_since_ns && now - g_dirty_since_ns < g_refresh_ns && + now - g_hold_missed_ns >= HOLD_RETRY_NS) { + g_tick_held = 1; + return; + } if (g_dirty && !scene_waits_for_game(now)) render_scene(); } @@ -3396,6 +3478,24 @@ static int on_stats_timer(void *data) { #undef PERF_MS memset(&g_perf, 0, sizeof(g_perf)); } + const uint64_t game = g_game_frames - g_pace.game_frames_seen; + if (g_pace.ticks || g_pace.renders || game || g_pace.reattaches || g_pace.null_attaches || g_pace.distinct || + g_pace.presented || g_pace.replaced || g_pace.undrawn) { + droiddeck_log("pacing", "last 10 s: tick reaches compositor %.2f/%.2f ms late (%u ticks, %u over 2 ms) | " + "new frame waits %.2f/%.2f ms to be drawn (%u scenes, %u on arrival) | %llu game frames, %u re-attached after an " + "empty attach, %u empty attaches, %u distinct buffers | feedback %u shown, %u replaced before drawing, " + "%u not drawn", + g_pace.ticks ? (double)g_pace.tick_late_ns / 1e6 / g_pace.ticks : 0.0, (double)g_pace.tick_late_max_ns / 1e6, + g_pace.ticks, g_pace.ticks_late_2ms, + g_pace.renders ? (double)g_pace.wait_ns / 1e6 / g_pace.renders : 0.0, (double)g_pace.wait_max_ns / 1e6, + g_pace.renders, g_pace.commit_renders, (unsigned long long)game, g_pace.reattaches, g_pace.null_attaches, g_pace.distinct, + g_pace.presented, g_pace.replaced, g_pace.undrawn); + } + { + const uint64_t seen = g_game_frames; + memset(&g_pace, 0, sizeof(g_pace)); + g_pace.game_frames_seen = seen; + } g_stat_frames = g_stat_dmabuf = g_stat_shm = 0; droiddeck_color_stats_tick(); diff --git a/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c b/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c index 675d4ac2ce..fad36f2823 100644 --- a/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c +++ b/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c @@ -36,6 +36,7 @@ extern void droiddeck_wayland_output_resized(void); extern void droiddeck_wayland_set_output_refresh_rate(int mhz); extern volatile int g_fps_limit; extern volatile int g_release_unpaced; +extern volatile int g_render_on_commit; extern volatile int g_hide_shell; extern volatile int g_zero_copy; extern volatile unsigned g_zero_copy_last; @@ -587,6 +588,12 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetLookName(JNIEnv * free(s); } +JNIEXPORT void JNICALL +Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetRenderOnCommit(JNIEnv *env, jclass clazz, jboolean on) { + g_render_on_commit = on ? 1 : 0; + __android_log_print(ANDROID_LOG_INFO, TAG, "render on commit %s", on ? "on" : "off"); +} + JNIEXPORT void JNICALL Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetFpsLimit(JNIEnv *env, jclass clazz, jint fps) { g_fps_limit = fps > 0 ? fps : 0; diff --git a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt index e7bb8e8e05..0d42c9a202 100644 --- a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt @@ -44,6 +44,7 @@ import com.droiddeck.launcher.session.ComponentsManager import com.droiddeck.launcher.ui.ComponentsPage import com.droiddeck.launcher.session.GameSaves import com.droiddeck.launcher.session.SessionLogShare +import com.droiddeck.launcher.session.SessionPaths import com.droiddeck.launcher.session.SessionPrefs import com.droiddeck.launcher.session.SteamRepair import com.droiddeck.launcher.core.CpuCores @@ -99,6 +100,7 @@ class FrontEndActivity : ComponentActivity() { private class PendingFlood(val from: androidx.compose.ui.geometry.Rect, val intent: Intent) private class CompatLaunch(val intent: Intent, val loading: com.droiddeck.launcher.session.LoadingState, var menuInstall: Boolean) private var compatLaunch by mutableStateOf(null) + private var compatFlood by mutableStateOf(null) private var compatLaunchPoll: Runnable? = null private var compatLaunchVisible = false private var returning by mutableStateOf(null) @@ -482,6 +484,8 @@ class FrontEndActivity : ComponentActivity() { private var emulatorList by mutableStateOf>(emptyList()) private var runningLabel by mutableStateOf(null) private var logsEnabled by mutableStateOf(true) + private var gameDebugLogsEnabled by mutableStateOf(false) + private var gameDebugLogsNeedsRestart by mutableStateOf(false) private var vacDiagnostics by mutableStateOf(false) private var agentCommands by mutableStateOf(false) private var clearCachedApps by mutableStateOf(false) @@ -493,6 +497,21 @@ class FrontEndActivity : ComponentActivity() { private var homeScreenEnabled by mutableStateOf(false) private var defaultHomeLabel by mutableStateOf(null) private var androidApps by mutableStateOf>(emptyList()) + private var androidAppsListing = 0 + private val packageCallback = object : android.content.pm.LauncherApps.Callback() { + private fun changed() { + refreshAndroidApps() + if (HomeWidgets.providers != null) HomeWidgets.refreshProviders(this@FrontEndActivity) + } + override fun onPackageRemoved(packageName: String, user: android.os.UserHandle) = changed() + override fun onPackageAdded(packageName: String, user: android.os.UserHandle) = changed() + override fun onPackageChanged(packageName: String, user: android.os.UserHandle) = changed() + override fun onPackagesAvailable(packageNames: Array, user: android.os.UserHandle, replacing: Boolean) = changed() + override fun onPackagesUnavailable(packageNames: Array, user: android.os.UserHandle, replacing: Boolean) = changed() + override fun onShortcutsChanged(packageName: String, shortcuts: MutableList, user: android.os.UserHandle) { + if (homeAppSelected) HomePins.refresh(this@FrontEndActivity) + } + } private var secondScreenDisplays by mutableStateOf>(emptyList()) private lateinit var displayManager: DisplayManager private val secondScreenDisplayListener = object : DisplayManager.DisplayListener { @@ -506,6 +525,7 @@ class FrontEndActivity : ComponentActivity() { } override fun startActivity(intent: Intent?) { + val compat = protons.protonBusyId != null || ProtonExtras.installInProgress if (intent?.component?.className == SessionActivity::class.java.name) { if (compatLaunch != null) return when { @@ -513,10 +533,7 @@ class FrontEndActivity : ComponentActivity() { android.widget.Toast.makeText(this, R.string.main_wait_runtime, android.widget.Toast.LENGTH_SHORT).show() return } - protons.protonBusyId != null || ProtonExtras.installInProgress -> { - waitForCompat(intent) - return - } + compat -> Unit pkgStage != null -> { android.widget.Toast.makeText(this, R.string.main_wait_desktop_install, android.widget.Toast.LENGTH_SHORT).show() return @@ -531,6 +548,10 @@ class FrontEndActivity : ComponentActivity() { return } com.droiddeck.launcher.ui.LaunchOrigin.flooding = null + if (compat) { + waitForCompat(intent) + return + } } super.startActivity(intent) if (intent?.component?.className == SessionActivity::class.java.name) overridePendingTransition(R.anim.session_rise, R.anim.session_hold) @@ -542,8 +563,11 @@ class FrontEndActivity : ComponentActivity() { flood = null floodProgress = 0f com.droiddeck.launcher.ui.LaunchOrigin.flooding = null - if (!busy && !LinuxRuntimeInstaller.isBusy() && pkgStage == null && - (protons.protonBusyId != null || ProtonExtras.installInProgress)) waitForCompat(f.intent) + if (!busy && !LinuxRuntimeInstaller.isBusy() && + (protons.protonBusyId != null || ProtonExtras.installInProgress)) { + compatFlood = com.droiddeck.launcher.ui.Themes.byId(theme).signal + waitForCompat(f.intent) + } return } val signal = com.droiddeck.launcher.ui.Themes.byId(theme).signal @@ -597,6 +621,7 @@ class FrontEndActivity : ComponentActivity() { compatLaunchPoll?.let(ui::removeCallbacks) compatLaunchPoll = null compatLaunch = null + compatFlood = null } private fun restoreCompatLaunch(state: Bundle) { @@ -952,6 +977,7 @@ class FrontEndActivity : ComponentActivity() { desktopInstalled = desktopInstalled, desktopPresent = desktopPresent, offlineAccount = offlineAccount, offline = offline, frameGenLabel = frameGenLabel, romsDir = romsDir, logsEnabled = logsEnabled, + gameDebugLogsEnabled = gameDebugLogsEnabled, gameDebugLogsNeedsRestart = gameDebugLogsNeedsRestart, vacDiagnostics = vacDiagnostics, agentCommands = agentCommands, clearCachedApps = clearCachedApps, adbPaired = adbPaired, memoryHud = memoryHud, backgroundAppLimit = backgroundAppLimit, steamGames = steamGames, steamGamesX64 = steamGamesX64, emulators = emulatorList, running = runningLabel, @@ -1108,8 +1134,21 @@ class FrontEndActivity : ComponentActivity() { .putExtra(com.droiddeck.launcher.files.FileManagerActivity.EXTRA_START_DIR, dir.absolutePath)) }, onLogs = { - SessionPrefs.setLogsEnabled(this, !SessionPrefs.logsEnabled(this)) + val changed = SessionPrefs.setLogsEnabled(this, !SessionPrefs.logsEnabled(this)) + if (!changed) android.widget.Toast.makeText( + this, R.string.setup_logging_update_failed, android.widget.Toast.LENGTH_LONG, + ).show() logsEnabled = SessionPrefs.logsEnabled(this) + gameDebugLogsEnabled = SessionPrefs.gameDebugLogsEnabled(this) + gameDebugLogsNeedsRestart = gameDebugLogsNeedsRestart() + }, + onGameDebugLogs = { + val changed = SessionPrefs.setGameDebugLogsEnabled(this, !SessionPrefs.gameDebugLogsEnabled(this)) + if (!changed) android.widget.Toast.makeText( + this, R.string.setup_logging_update_failed, android.widget.Toast.LENGTH_LONG, + ).show() + gameDebugLogsEnabled = SessionPrefs.gameDebugLogsEnabled(this) + gameDebugLogsNeedsRestart = gameDebugLogsNeedsRestart() }, onVacDiagnostics = { SessionPrefs.setVacDiagnostics(this, !SessionPrefs.vacDiagnostics(this)) @@ -1266,7 +1305,12 @@ class FrontEndActivity : ComponentActivity() { android.widget.Toast.makeText(this, R.string.main_adb_copied, android.widget.Toast.LENGTH_SHORT).show() }, onDismissPhantomGate = { showPhantomGate = false }, + onShowPhantomGate = { + refreshPhantomStatus() + showPhantomGate = true + }, onStartWirelessAdbPairing = { WirelessAdbPairingService.start(this) }, + onStartPairingGuide = { displayId -> PairingGuideActivity.start(this, displayId) }, onOpenNotificationSettings = { startActivity(Intent(android.provider.Settings.ACTION_APP_NOTIFICATION_SETTINGS) .putExtra(android.provider.Settings.EXTRA_APP_PACKAGE, packageName) @@ -1363,10 +1407,12 @@ class FrontEndActivity : ComponentActivity() { } androidx.activity.compose.BackHandler(compatLaunch != null) { cancelCompatLaunch() } compatLaunch?.loading?.let { loading -> + if (!loading.ended) com.droiddeck.launcher.ui.VeilRing() com.droiddeck.launcher.ui.LoadingOverlay( loading.step, loading.percent, loading.elapsed, getString(R.string.load_compat_hint), loading.ended, loading.topic, loading.readable, title = getString(R.string.load_compat_title), onCancel = ::cancelCompatLaunch, onClose = ::cancelCompatLaunch, + flood = compatFlood, onFlooded = { compatFlood = null }, ) } } @@ -1552,6 +1598,15 @@ class FrontEndActivity : ComponentActivity() { }) displayManager.registerDisplayListener(secondScreenDisplayListener, ui) refreshSecondScreenDisplays() + getSystemService(android.content.pm.LauncherApps::class.java).registerCallback(packageCallback, ui) + HomeWidgets.startListening(this) + } + + @Suppress("OVERRIDE_DEPRECATION") + override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { + if (HomeWidgets.onActivityResult(this, requestCode, resultCode)) return + @Suppress("DEPRECATION") + super.onActivityResult(requestCode, resultCode, data) } override fun onSaveInstanceState(outState: Bundle) { @@ -1577,6 +1632,8 @@ class FrontEndActivity : ComponentActivity() { override fun onStop() { unregisterReceiver(wifiLocationReceiver) unregisterReceiver(mediaReceiver) + getSystemService(android.content.pm.LauncherApps::class.java).unregisterCallback(packageCallback) + HomeWidgets.stopListening(this) ui.removeCallbacks(mediaRefresh) com.droiddeck.launcher.stores.StoresState.libraryListener = null com.droiddeck.launcher.stores.battlenet.BattleNetClient.opener = null @@ -1592,10 +1649,24 @@ class FrontEndActivity : ComponentActivity() { homeScreenEnabled = HomeApp.isHomeScreenEnabled(this) homeAppSelected = homeScreenEnabled && HomeApp.isDefault(this) defaultHomeLabel = HomeApp.defaultLabel(this) - androidApps = if (homeAppSelected) HomeApp.launchableApps(this) else emptyList() + refreshAndroidApps() integrationState = readIntegration() } + private fun refreshAndroidApps() { + if (!homeAppSelected) { + ++androidAppsListing + androidApps = emptyList() + return + } + val seq = ++androidAppsListing + HomePins.refresh(this) + Thread({ + val apps = runCatching { HomeApp.launchableApps(this) }.getOrDefault(emptyList()) + ui.post { if (seq == androidAppsListing) androidApps = apps } + }, "home-apps").start() + } + private fun refreshSecondScreenDisplays() { if (!::displayManager.isInitialized) return // The launcher can itself be shown on a non-default display (DeX, an external monitor); that one is not a "second screen". @@ -2245,6 +2316,10 @@ class FrontEndActivity : ComponentActivity() { refreshPhantomStatus() } + private fun gameDebugLogsNeedsRestart(): Boolean = + SessionPrefs.logsEnabled(this) && SessionPrefs.gameDebugLogsEnabled(this) && + !SessionPaths.currentSessionLogsRetained(this) + private fun refresh() { // Until the scan finishes, the other client's games would launch in this one. val listX64 = SessionPrefs.activeSteamClientArch(this) == "x86_64" @@ -2266,6 +2341,8 @@ class FrontEndActivity : ComponentActivity() { frameGenLabel = FrameGen.label(this) romsDir = SessionPrefs.romsDir(this).takeIf { it.isNotEmpty() } logsEnabled = SessionPrefs.logsEnabled(this) + gameDebugLogsEnabled = SessionPrefs.gameDebugLogsEnabled(this) + gameDebugLogsNeedsRestart = gameDebugLogsNeedsRestart() vacDiagnostics = SessionPrefs.vacDiagnostics(this) agentCommands = com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(this) clearCachedApps = SessionPrefs.clearCachedApps(this) diff --git a/app/src/main/java/com/droiddeck/launcher/HomeApp.kt b/app/src/main/java/com/droiddeck/launcher/HomeApp.kt index 74b49821c5..9d0ae53c1c 100644 --- a/app/src/main/java/com/droiddeck/launcher/HomeApp.kt +++ b/app/src/main/java/com/droiddeck/launcher/HomeApp.kt @@ -6,20 +6,41 @@ import android.graphics.Bitmap import android.content.ComponentName import android.content.Context import android.content.Intent +import android.content.pm.ApplicationInfo +import android.content.pm.LauncherApps +import android.content.pm.ShortcutInfo +import android.graphics.Rect +import android.os.Process +import android.os.UserHandle +import android.os.UserManager import android.content.pm.PackageManager +import android.net.Uri import android.os.Build import android.provider.Settings import androidx.core.graphics.drawable.toBitmap import com.droiddeck.launcher.session.SessionService import com.droiddeck.launcher.session.SessionState +import kotlin.math.roundToInt object HomeApp { + private const val ICON_DP = 72 + data class LaunchableApp( val label: String, val packageName: String, val className: String, val icon: Bitmap?, - ) + val system: Boolean = false, + val game: Boolean = false, + val installedAt: Long = 0L, + val updatedAt: Long = 0L, + val user: UserHandle? = null, + val userSerial: Long = 0L, + ) { + val component get() = ComponentName(packageName, className) + val key get() = "$packageName/$className" + if (userSerial != 0L) "#$userSerial" else "" + val work get() = userSerial != 0L + } fun isHomeScreenEnabled(context: Context): Boolean = context.packageManager.getComponentEnabledSetting(ComponentName(context, HomeActivity::class.java)) == @@ -69,33 +90,79 @@ object HomeApp { fun settingsIntent(): Intent = Intent(Settings.ACTION_HOME_SETTINGS) fun launchableApps(context: Context): List { + val launcher = context.getSystemService(LauncherApps::class.java) + val users = context.getSystemService(UserManager::class.java) val pm = context.packageManager - val launch = Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER) - val apps = pm.queryIntentActivities(launch, 0) - .asSequence() - .mapNotNull { result -> - val activity = result.activityInfo ?: return@mapNotNull null - if (!activity.exported || activity.packageName == context.packageName) return@mapNotNull null - val label = result.loadLabel(pm)?.toString()?.trim().orEmpty().ifEmpty { activity.packageName } - val icon = runCatching { result.loadIcon(pm).toBitmap(48, 48) }.getOrNull() - LaunchableApp(label, activity.packageName, activity.name, icon) + val own = Process.myUserHandle() + val iconPx = (ICON_DP * context.resources.displayMetrics.density).roundToInt() + val apps = users.userProfiles.flatMap { user -> + val serial = if (user == own) 0L else users.getSerialNumberForUser(user) + runCatching { launcher.getActivityList(null, user) }.getOrDefault(emptyList()).mapNotNull { info -> + val component = info.componentName + if (component.packageName == context.packageName && user == own) return@mapNotNull null + val label = info.label?.toString()?.trim().orEmpty().ifEmpty { component.packageName } + val icon = runCatching { info.getBadgedIcon(0).toBitmap(iconPx, iconPx) }.getOrNull() + val app = info.applicationInfo + val updated = if (user == own) runCatching { pm.getPackageInfo(component.packageName, 0).lastUpdateTime }.getOrNull() else null + @Suppress("DEPRECATION") + val game = app.category == ApplicationInfo.CATEGORY_GAME || app.flags and ApplicationInfo.FLAG_IS_GAME != 0 + LaunchableApp( + label, component.packageName, component.className, icon, + system = app.flags and (ApplicationInfo.FLAG_SYSTEM or ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0, + game = game, + installedAt = info.firstInstallTime, + updatedAt = updated ?: info.firstInstallTime, + user = user, + userSerial = serial, + ) } - .distinctBy { it.packageName } - .toList() - return apps.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.label }) + } + return apps.distinctBy { it.key }.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.label }) } - fun launch(context: Context, app: LaunchableApp, displayId: Int? = null) { - val intent = Intent(Intent.ACTION_MAIN) - .addCategory(Intent.CATEGORY_LAUNCHER) - .setComponent(ComponentName(app.packageName, app.className)) - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) - if (displayId == null) { - context.startActivity(intent) - return - } - val options = ActivityOptions.makeBasic().setLaunchDisplayId(displayId) - context.startActivity(intent, options.toBundle()) + fun launch(context: Context, app: LaunchableApp, displayId: Int? = null, bounds: Rect? = null) { + val options = displayId?.let { ActivityOptions.makeBasic().setLaunchDisplayId(it).toBundle() } + val launcher = context.getSystemService(LauncherApps::class.java) + launcher.startMainActivity(app.component, app.user ?: Process.myUserHandle(), bounds, options) + } + + fun canUseShortcuts(context: Context): Boolean = + runCatching { context.getSystemService(LauncherApps::class.java).hasShortcutHostPermission() }.getOrDefault(false) + + fun shortcuts(context: Context, app: LaunchableApp): List { + if (!canUseShortcuts(context)) return emptyList() + val query = LauncherApps.ShortcutQuery() + .setPackage(app.packageName) + .setActivity(app.component) + .setQueryFlags(LauncherApps.ShortcutQuery.FLAG_MATCH_DYNAMIC or LauncherApps.ShortcutQuery.FLAG_MATCH_MANIFEST) + return runCatching { context.getSystemService(LauncherApps::class.java).getShortcuts(query, app.user ?: Process.myUserHandle()) } + .getOrNull().orEmpty() + .filter { it.isEnabled } + .sortedWith(compareBy { if (it.isDeclaredInManifest) 0 else 1 }.thenBy { it.rank }) + .take(5) + } + + fun shortcutIcon(context: Context, info: ShortcutInfo, px: Int = (ICON_DP * context.resources.displayMetrics.density).roundToInt()): Bitmap? = runCatching { + context.getSystemService(LauncherApps::class.java) + .getShortcutIconDrawable(info, context.resources.displayMetrics.densityDpi)?.toBitmap(px, px) + }.getOrNull() + + fun startShortcut(context: Context, info: ShortcutInfo) { + context.getSystemService(LauncherApps::class.java).startShortcut(info, null, null) + } + + fun openAppInfo(context: Context, app: LaunchableApp) { + context.getSystemService(LauncherApps::class.java) + .startAppDetailsActivity(app.component, app.user ?: Process.myUserHandle(), null, null) + } + + fun canUninstall(app: LaunchableApp): Boolean = !app.system && !app.work + + fun uninstall(context: Context, app: LaunchableApp) { + context.startActivity( + Intent(Intent.ACTION_DELETE, Uri.fromParts("package", app.packageName, null)) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), + ) } fun isActiveSteamSession(): Boolean = diff --git a/app/src/main/java/com/droiddeck/launcher/HomeFolders.kt b/app/src/main/java/com/droiddeck/launcher/HomeFolders.kt new file mode 100644 index 0000000000..dc1f0bca47 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/HomeFolders.kt @@ -0,0 +1,65 @@ +package com.droiddeck.launcher + +import android.content.Context +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import org.json.JSONArray +import org.json.JSONObject +import java.util.UUID + +object HomeFolders { + data class Folder(val id: String, val name: String, val apps: List) + + private const val PREFS = "home_launcher" + private const val KEY = "folders" + + var folders by mutableStateOf>(emptyList()) + private set + private var loaded = false + + fun load(context: Context) { + if (loaded) return + loaded = true + val raw = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(KEY, null) ?: return + folders = runCatching { + val array = JSONArray(raw) + (0 until array.length()).map { i -> + val o = array.getJSONObject(i) + val apps = o.getJSONArray("apps") + Folder(o.getString("id"), o.getString("name"), (0 until apps.length()).map { apps.getString(it) }) + } + }.getOrDefault(emptyList()) + } + + fun create(context: Context, name: String, appKey: String): Folder { + val folder = Folder(UUID.randomUUID().toString(), name, listOf(appKey)) + update(context, without(appKey) + folder) + return folder + } + + fun add(context: Context, folderId: String, appKey: String) = + update(context, without(appKey).map { if (it.id == folderId) it.copy(apps = it.apps + appKey) else it }) + + fun remove(context: Context, appKey: String) = update(context, without(appKey)) + + fun rename(context: Context, folderId: String, name: String) = + update(context, folders.map { if (it.id == folderId) it.copy(name = name) else it }) + + fun delete(context: Context, folderId: String) = update(context, folders.filterNot { it.id == folderId }) + + fun migrateMembers(context: Context, keyFor: (String) -> String?) { + if (folders.none { f -> f.apps.any { '/' !in it } }) return + update(context, folders.map { f -> f.copy(apps = f.apps.map { if ('/' in it) it else keyFor(it) ?: it }.distinct()) }) + } + + private fun without(appKey: String): List = + folders.map { it.copy(apps = it.apps - appKey) }.filter { it.apps.isNotEmpty() } + + private fun update(context: Context, next: List) { + folders = next + val array = JSONArray() + for (f in next) array.put(JSONObject().put("id", f.id).put("name", f.name).put("apps", JSONArray(f.apps))) + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putString(KEY, array.toString()).apply() + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/HomeHidden.kt b/app/src/main/java/com/droiddeck/launcher/HomeHidden.kt new file mode 100644 index 0000000000..70f98f4843 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/HomeHidden.kt @@ -0,0 +1,26 @@ +package com.droiddeck.launcher + +import android.content.Context +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue + +object HomeHidden { + private const val PREFS = "home_launcher" + private const val KEY = "hidden" + + var keys by mutableStateOf>(emptySet()) + private set + private var loaded = false + + fun load(context: Context) { + if (loaded) return + loaded = true + keys = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getStringSet(KEY, emptySet()).orEmpty().toSet() + } + + fun set(context: Context, key: String, hidden: Boolean) { + keys = if (hidden) keys + key else keys - key + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putStringSet(KEY, keys).apply() + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/HomePins.kt b/app/src/main/java/com/droiddeck/launcher/HomePins.kt new file mode 100644 index 0000000000..1040995e87 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/HomePins.kt @@ -0,0 +1,75 @@ +package com.droiddeck.launcher + +import android.content.Context +import android.content.pm.LauncherApps +import android.content.pm.ShortcutInfo +import android.graphics.Bitmap +import android.os.Handler +import android.os.Looper +import android.os.Process +import android.os.UserManager +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue + +/** Shortcuts other apps asked to put on the home screen. The system keeps the pinned set per launcher. */ +object HomePins { + class Pinned(val info: ShortcutInfo, val icon: Bitmap?, val appLabel: String, val userSerial: Long) { + val key get() = "pin:${info.`package`}/${info.id}" + if (userSerial != 0L) "#$userSerial" else "" + val label get() = info.shortLabel?.toString()?.trim().orEmpty().ifEmpty { appLabel } + val work get() = userSerial != 0L + } + + var pinned by mutableStateOf>(emptyList()) + private set + private val main = Handler(Looper.getMainLooper()) + private var listing = 0 + + fun refresh(context: Context) { + val app = context.applicationContext + val seq = ++listing + Thread({ + val list = runCatching { load(app) }.getOrDefault(emptyList()) + main.post { if (seq == listing) pinned = list } + }, "home-pins").start() + } + + private fun load(context: Context): List { + if (!HomeApp.canUseShortcuts(context)) return emptyList() + val launcher = context.getSystemService(LauncherApps::class.java) + val users = context.getSystemService(UserManager::class.java) + val pm = context.packageManager + val own = Process.myUserHandle() + val query = LauncherApps.ShortcutQuery().setQueryFlags(LauncherApps.ShortcutQuery.FLAG_MATCH_PINNED) + return users.userProfiles.flatMap { user -> + val serial = if (user == own) 0L else users.getSerialNumberForUser(user) + runCatching { launcher.getShortcuts(query, user) }.getOrNull().orEmpty() + .filter { it.isEnabled && it.isPinned } + .map { info -> + val appLabel = runCatching { pm.getApplicationLabel(pm.getApplicationInfo(info.`package`, 0)).toString() } + .getOrDefault(info.`package`) + Pinned(info, HomeApp.shortcutIcon(context, info), appLabel, serial) + } + } + } + + fun accept(context: Context, request: LauncherApps.PinItemRequest): Boolean { + val ok = runCatching { request.isValid && request.accept() }.getOrDefault(false) + if (ok) refresh(context) + return ok + } + + fun unpin(context: Context, pinned: Pinned) { + val info = pinned.info + val launcher = context.getSystemService(LauncherApps::class.java) + val query = LauncherApps.ShortcutQuery().setPackage(info.`package`).setQueryFlags(LauncherApps.ShortcutQuery.FLAG_MATCH_PINNED) + val unpinned = runCatching { + val current = checkNotNull(launcher.getShortcuts(query, info.userHandle)) + val keep = current.map { it.id } - info.id + launcher.pinShortcuts(info.`package`, keep, info.userHandle) + }.isSuccess + if (!unpinned) return + listing++ + this.pinned = this.pinned.filterNot { it.key == pinned.key } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/HomeWidgets.kt b/app/src/main/java/com/droiddeck/launcher/HomeWidgets.kt new file mode 100644 index 0000000000..8f79f4354b --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/HomeWidgets.kt @@ -0,0 +1,317 @@ +package com.droiddeck.launcher + +import android.app.Activity +import android.appwidget.AppWidgetHost +import android.appwidget.AppWidgetHostView +import android.appwidget.AppWidgetManager +import android.appwidget.AppWidgetProviderInfo +import android.content.Context +import android.content.Intent +import android.content.pm.LauncherApps +import android.graphics.Bitmap +import android.os.Build +import android.os.Bundle +import android.os.Handler +import android.os.Looper +import android.util.SizeF +import android.view.HapticFeedbackConstants +import android.view.MotionEvent +import android.view.ViewConfiguration +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.core.graphics.drawable.toBitmap +import org.json.JSONArray +import org.json.JSONObject +import kotlin.math.hypot +import kotlin.math.roundToInt + +object HomeWidgets { + data class Placed(val id: Int, val widthDp: Int, val heightDp: Int) + + data class Provider( + val info: AppWidgetProviderInfo, + val label: String, + val appLabel: String, + val preview: Bitmap?, + val widthDp: Int, + val heightDp: Int, + ) + + private const val HOST_ID = 0x0DDE + private const val PREFS = "home_launcher" + private const val KEY = "widgets" + private const val REQUEST_BIND = 0x0DD1 + private const val REQUEST_CONFIGURE = 0x0DD2 + private const val REQUEST_RECONFIGURE = 0x0DD3 + const val MIN_WIDTH_DP = 96 + const val MIN_HEIGHT_DP = 56 + + var widgets by mutableStateOf>(emptyList()) + private set + var providers by mutableStateOf?>(null) + private set + private var loaded = false + private var host: Host? = null + private var pending: AppWidgetProviderInfo? = null + private var pendingId = AppWidgetManager.INVALID_APPWIDGET_ID + private var pinRequest: LauncherApps.PinItemRequest? = null + private val main = Handler(Looper.getMainLooper()) + + private class Host(context: Context) : AppWidgetHost(context, HOST_ID) { + override fun onCreateView(context: Context, appWidgetId: Int, appWidget: AppWidgetProviderInfo?): AppWidgetHostView = + HomeWidgetView(context) + } + + class HomeWidgetView(context: Context) : AppWidgetHostView(context) { + var onLongPress: (() -> Unit)? = null + private var fired = false + private var downX = 0f + private var downY = 0f + private val slop = ViewConfiguration.get(context).scaledTouchSlop + private val longPress = Runnable { + fired = true + performHapticFeedback(HapticFeedbackConstants.LONG_PRESS) + onLongPress?.invoke() + } + + override fun onInterceptTouchEvent(ev: MotionEvent): Boolean { + when (ev.actionMasked) { + MotionEvent.ACTION_DOWN -> { + fired = false + downX = ev.x + downY = ev.y + postDelayed(longPress, ViewConfiguration.getLongPressTimeout().toLong()) + } + MotionEvent.ACTION_MOVE -> if (hypot(ev.x - downX, ev.y - downY) > slop) removeCallbacks(longPress) + MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_POINTER_DOWN -> removeCallbacks(longPress) + } + return fired + } + + override fun onTouchEvent(event: MotionEvent): Boolean { + if (fired) { + if (event.actionMasked == MotionEvent.ACTION_UP || event.actionMasked == MotionEvent.ACTION_CANCEL) fired = false + return true + } + return super.onTouchEvent(event) + } + } + + private fun host(context: Context): Host = host ?: Host(context.applicationContext).also { host = it } + + fun load(context: Context) { + if (loaded) return + loaded = true + val raw = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(KEY, null) ?: return + val manager = AppWidgetManager.getInstance(context) + val parsed = runCatching { + val array = JSONArray(raw) + (0 until array.length()).map { i -> + val o = array.getJSONObject(i) + Placed(o.getInt("id"), o.getInt("w"), o.getInt("h")) + } + }.getOrDefault(emptyList()) + val live = parsed.filter { manager.getAppWidgetInfo(it.id) != null } + parsed.filterNot { it in live }.forEach { host(context).deleteAppWidgetId(it.id) } + widgets = live + if (live.size != parsed.size) save(context) + } + + fun startListening(context: Context) { + load(context) + runCatching { host(context).startListening() } + } + + fun stopListening(context: Context) { + runCatching { host(context).stopListening() } + } + + fun info(context: Context, id: Int): AppWidgetProviderInfo? = AppWidgetManager.getInstance(context).getAppWidgetInfo(id) + + fun createView(context: Context, id: Int): HomeWidgetView? { + val info = info(context, id) ?: return null + return host(context).createView(context, id, info) as? HomeWidgetView + } + + fun applySize(view: AppWidgetHostView, widthDp: Int, heightDp: Int) { + if (Build.VERSION.SDK_INT >= 31) { + view.updateAppWidgetSize(Bundle(), listOf(SizeF(widthDp.toFloat(), heightDp.toFloat()))) + } else { + @Suppress("DEPRECATION") + view.updateAppWidgetSize(null, widthDp, heightDp, widthDp, heightDp) + } + } + + fun loadProviders(context: Context) { + if (providers != null) return + val app = context.applicationContext + Thread({ + val pm = app.packageManager + val manager = AppWidgetManager.getInstance(app) + val dpi = app.resources.displayMetrics.densityDpi + val list = manager.installedProviders.mapNotNull { info -> + runCatching { + val appLabel = runCatching { pm.getApplicationLabel(pm.getApplicationInfo(info.provider.packageName, 0)).toString() } + .getOrDefault(info.provider.packageName) + val drawable = info.loadPreviewImage(app, dpi) ?: info.loadIcon(app, dpi) + val preview = drawable?.let { d -> + val w = d.intrinsicWidth.takeIf { it > 0 } ?: 192 + val h = d.intrinsicHeight.takeIf { it > 0 } ?: 192 + val scale = minOf(1f, 360f / maxOf(w, h)) + d.toBitmap((w * scale).roundToInt().coerceAtLeast(1), (h * scale).roundToInt().coerceAtLeast(1)) + } + val (w, h) = defaultSize(app, info) + Provider(info, info.loadLabel(pm)?.toString()?.trim().orEmpty().ifEmpty { appLabel }, appLabel, preview, w, h) + }.getOrNull() + }.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER, Provider::appLabel).thenBy(String.CASE_INSENSITIVE_ORDER, Provider::label)) + main.post { providers = list } + }, "widget-providers").start() + } + + fun refreshProviders(context: Context) { + providers = null + loadProviders(context) + } + + private fun defaultSize(context: Context, info: AppWidgetProviderInfo): Pair { + val density = context.resources.displayMetrics.density + var w = (info.minWidth / density).roundToInt() + var h = (info.minHeight / density).roundToInt() + if (Build.VERSION.SDK_INT >= 31) { + if (info.targetCellWidth > 0) w = maxOf(w, info.targetCellWidth * 80) + if (info.targetCellHeight > 0) h = maxOf(h, info.targetCellHeight * 80) + } + return w.coerceIn(160, 560) to h.coerceIn(MIN_HEIGHT_DP, 360) + } + + fun minSize(context: Context, id: Int): Pair { + val info = info(context, id) ?: return MIN_WIDTH_DP to MIN_HEIGHT_DP + val density = context.resources.displayMetrics.density + val w = (if (info.minResizeWidth > 0) info.minResizeWidth else info.minWidth) / density + val h = (if (info.minResizeHeight > 0) info.minResizeHeight else info.minHeight) / density + return w.roundToInt().coerceAtLeast(MIN_WIDTH_DP) to h.roundToInt().coerceAtLeast(MIN_HEIGHT_DP) + } + + fun add(activity: Activity, provider: Provider) { + if (pendingId == AppWidgetManager.INVALID_APPWIDGET_ID) add(activity, provider.info, null) + } + + /** Places a widget another app asked for; its own app has already configured it. */ + fun addPinned(activity: Activity, request: LauncherApps.PinItemRequest): Boolean { + if (pendingId != AppWidgetManager.INVALID_APPWIDGET_ID) return false + val info = request.getAppWidgetProviderInfo(activity) ?: return false + load(activity) + add(activity, info, request) + return pending != null + } + + private fun add(activity: Activity, info: AppWidgetProviderInfo, request: LauncherApps.PinItemRequest?) { + val h = host(activity) + val id = h.allocateAppWidgetId() + pending = info + pendingId = id + pinRequest = request + val manager = AppWidgetManager.getInstance(activity) + val bound = runCatching { manager.bindAppWidgetIdIfAllowed(id, info.profile, info.provider, null) }.getOrDefault(false) + if (bound) { + bound(activity, id, info) + return + } + val bind = Intent(AppWidgetManager.ACTION_APPWIDGET_BIND) + .putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, id) + .putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER, info.provider) + .putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER_PROFILE, info.profile) + @Suppress("DEPRECATION") + runCatching { activity.startActivityForResult(bind, REQUEST_BIND) }.onFailure { abandon(activity) } + } + + private fun bound(activity: Activity, id: Int, info: AppWidgetProviderInfo) { + val request = pinRequest + if (request == null) { + configure(activity, id, info) + return + } + val accepted = runCatching { request.isValid && request.accept(Bundle().apply { putInt(AppWidgetManager.EXTRA_APPWIDGET_ID, id) }) } + .getOrDefault(false) + if (accepted) place(activity, id, info) else abandon(activity) + } + + private fun configure(activity: Activity, id: Int, info: AppWidgetProviderInfo) { + val optional = Build.VERSION.SDK_INT >= 31 && + info.widgetFeatures and AppWidgetProviderInfo.WIDGET_FEATURE_CONFIGURATION_OPTIONAL != 0 + if (info.configure == null || optional) { + place(activity, id, info) + return + } + runCatching { host(activity).startAppWidgetConfigureActivityForResult(activity, id, 0, REQUEST_CONFIGURE, null) } + .onFailure { place(activity, id, info) } + } + + fun canReconfigure(context: Context, id: Int): Boolean { + val info = info(context, id) ?: return false + if (info.configure == null) return false + return Build.VERSION.SDK_INT < 28 || info.widgetFeatures and AppWidgetProviderInfo.WIDGET_FEATURE_RECONFIGURABLE != 0 + } + + fun reconfigure(activity: Activity, id: Int) { + runCatching { host(activity).startAppWidgetConfigureActivityForResult(activity, id, 0, REQUEST_RECONFIGURE, null) } + } + + fun onActivityResult(activity: Activity, requestCode: Int, resultCode: Int): Boolean { + when (requestCode) { + REQUEST_BIND -> { + val info = pending + if (resultCode == Activity.RESULT_OK && info != null) bound(activity, pendingId, info) else abandon(activity) + } + REQUEST_CONFIGURE -> { + val info = pending + if (resultCode == Activity.RESULT_OK && info != null) place(activity, pendingId, info) else abandon(activity) + } + REQUEST_RECONFIGURE -> Unit + else -> return false + } + return true + } + + private fun abandon(context: Context) { + if (pendingId != AppWidgetManager.INVALID_APPWIDGET_ID) host(context).deleteAppWidgetId(pendingId) + pending = null + pinRequest = null + pendingId = AppWidgetManager.INVALID_APPWIDGET_ID + } + + private fun place(context: Context, id: Int, info: AppWidgetProviderInfo) { + val (w, h) = defaultSize(context, info) + pending = null + pinRequest = null + pendingId = AppWidgetManager.INVALID_APPWIDGET_ID + widgets = widgets + Placed(id, w, h) + save(context) + } + + fun resize(context: Context, id: Int, widthDp: Int, heightDp: Int) { + widgets = widgets.map { if (it.id == id) it.copy(widthDp = widthDp, heightDp = heightDp) else it } + save(context) + } + + fun move(context: Context, id: Int, by: Int) { + val i = widgets.indexOfFirst { it.id == id } + val j = i + by + if (i < 0 || j !in widgets.indices) return + widgets = widgets.toMutableList().apply { add(j, removeAt(i)) } + save(context) + } + + fun remove(context: Context, id: Int) { + host(context).deleteAppWidgetId(id) + widgets = widgets.filterNot { it.id == id } + save(context) + } + + private fun save(context: Context) { + val array = JSONArray() + for (w in widgets) array.put(JSONObject().put("id", w.id).put("w", w.widthDp).put("h", w.heightDp)) + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putString(KEY, array.toString()).apply() + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/PairingGuideActivity.kt b/app/src/main/java/com/droiddeck/launcher/PairingGuideActivity.kt new file mode 100644 index 0000000000..44fce026a9 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/PairingGuideActivity.kt @@ -0,0 +1,328 @@ +package com.droiddeck.launcher + +import android.app.ActivityOptions +import android.app.AppOpsManager +import android.app.PictureInPictureParams +import android.content.Context +import android.content.Intent +import android.content.pm.PackageManager +import android.content.res.Configuration +import android.os.Build +import android.os.Bundle +import android.os.Process +import android.provider.Settings +import android.util.Rational +import androidx.activity.ComponentActivity +import androidx.activity.compose.BackHandler +import androidx.activity.compose.setContent +import androidx.compose.animation.core.LinearEasing +import androidx.compose.animation.core.RepeatMode +import androidx.compose.animation.core.animateFloat +import androidx.compose.animation.core.infiniteRepeatable +import androidx.compose.animation.core.rememberInfiniteTransition +import androidx.compose.animation.core.tween +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.produceState +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha +import androidx.compose.ui.draw.scale +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import com.droiddeck.launcher.core.AppLanguage +import com.droiddeck.launcher.core.GlobalSettings +import com.droiddeck.launcher.core.WirelessAdbPairingService +import com.droiddeck.launcher.core.WirelessAdbPairingService.Stage +import com.droiddeck.launcher.ui.DroidDeckTheme +import com.droiddeck.launcher.ui.LocalPalette +import com.droiddeck.launcher.ui.PrimaryButton +import com.droiddeck.launcher.ui.SecondaryButton +import kotlinx.coroutines.delay + +class PairingGuideActivity : ComponentActivity() { + enum class Step { BUILD_NUMBER, WIRELESS_DEBUGGING, PAIR, CODE, WORKING, DONE, FAILED } + + private var settingsDisplay: Int? = null + private var inPip by mutableStateOf(false) + private var launchPending = false + + override fun attachBaseContext(newBase: Context) = super.attachBaseContext(AppLanguage.wrap(newBase)) + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + settingsDisplay = intent.getIntExtra(EXTRA_DISPLAY, -1).takeIf { it >= 0 } + setContent { DroidDeckTheme { Guide() } } + launchPending = savedInstanceState == null + } + + override fun onNewIntent(intent: Intent) { + super.onNewIntent(intent) + setIntent(intent) + settingsDisplay = intent.getIntExtra(EXTRA_DISPLAY, -1).takeIf { it >= 0 } + launchPending = true + } + + override fun onResume() { + super.onResume() + if (!launchPending) return + if (inPip || settingsDisplay != null) { + launchSettings() + return + } + enterPip() + if (!inPip) launchSettings() + } + + override fun onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean, newConfig: Configuration) { + super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig) + inPip = isInPictureInPictureMode + if (isInPictureInPictureMode && launchPending) launchSettings() + } + + private fun launchSettings() { + launchPending = false + openSettings(stepFor(this, WirelessAdbPairingService.stage.value)) + } + + private fun enterPip() { + inPip = runCatching { + enterPictureInPictureMode(PictureInPictureParams.Builder().setAspectRatio(Rational(4, 3)).build()) + }.getOrDefault(false) + } + + private fun openSettings(step: Step) { + val intent = if (step == Step.BUILD_NUMBER) { + Intent(Settings.ACTION_DEVICE_INFO_SETTINGS).putExtra(HIGHLIGHT_KEY, "build_number") + } else { + Intent(Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS).putExtra(HIGHLIGHT_KEY, "toggle_adb_wireless") + }.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + val display = settingsDisplay + runCatching { + if (display == null) startActivity(intent) + else startActivity(intent, ActivityOptions.makeBasic().setLaunchDisplayId(display).toBundle()) + }.onFailure { + runCatching { startActivity(Intent(Settings.ACTION_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) } + } + } + + private fun returnToApp() { + startActivity(Intent(this, FrontEndActivity::class.java) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)) + finish() + } + + @Composable + private fun Guide() { + val stage by WirelessAdbPairingService.stage.collectAsState() + val settingsState by produceState(SettingsState.read(this)) { + while (true) { + value = SettingsState.read(this@PairingGuideActivity) + delay(500) + } + } + val step = stepFor(settingsState, stage) + var previous by remember { mutableStateOf(step) } + LaunchedEffect(step) { + if (previous == Step.BUILD_NUMBER && step == Step.WIRELESS_DEBUGGING) openSettings(step) + previous = step + when (step) { + Step.DONE -> { delay(1_500); returnToApp() } + Step.FAILED -> { delay(3_000); returnToApp() } + else -> Unit + } + } + LaunchedEffect(stage) { if (stage == Stage.Idle) finish() } + BackHandler(enabled = !inPip && settingsDisplay == null) { enterPip() } + + Box(Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background), contentAlignment = Alignment.Center) { + if (inPip) CompactStep(step, stage) + else FullGuide(step, stage) + } + } + + @Composable + private fun CompactStep(step: Step, stage: Stage) { + Column(Modifier.fillMaxSize().padding(10.dp), verticalArrangement = Arrangement.SpaceBetween) { + Text( + instruction(step, stage), style = MaterialTheme.typography.labelLarge, fontWeight = FontWeight.SemiBold, + color = MaterialTheme.colorScheme.onBackground, maxLines = 3, overflow = TextOverflow.Ellipsis, + ) + StepVisual(step, compact = true) + StepDots(step) + } + } + + @Composable + private fun FullGuide(step: Step, stage: Stage) { + Column( + Modifier.widthIn(max = 520.dp).fillMaxWidth().padding(24.dp), + verticalArrangement = Arrangement.spacedBy(16.dp), + ) { + Text(stringResource(R.string.gate_title), style = MaterialTheme.typography.headlineSmall, + fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.onBackground) + Text(instruction(step, stage), style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.onBackground) + StepVisual(step, compact = false) + StepDots(step) + Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) { + if (step == Step.DONE || step == Step.FAILED) { + PrimaryButton(stringResource(R.string.common_back), onClick = ::returnToApp) + } else { + PrimaryButton(stringResource(R.string.gate_open_dev), onClick = { + if (settingsDisplay == null) enterPip() + openSettings(step) + }) + SecondaryButton(stringResource(R.string.common_cancel), onClick = { + WirelessAdbPairingService.cancel(this@PairingGuideActivity) + returnToApp() + }) + } + } + } + } + + @Composable + private fun instruction(step: Step, stage: Stage): String = when (step) { + Step.BUILD_NUMBER -> stringResource(R.string.pairguide_build_number) + Step.WIRELESS_DEBUGGING -> stringResource(R.string.pairguide_wireless) + Step.PAIR -> stringResource(R.string.pairguide_pair) + Step.CODE -> (stage as? Stage.CodeNeeded)?.error ?: stringResource(R.string.gate_step3) + Step.WORKING -> (stage as? Stage.Working)?.step ?: stringResource(R.string.adbpair_title_working) + Step.DONE -> stringResource(R.string.adbpair_title_done) + Step.FAILED -> (stage as? Stage.Failed)?.error ?: stringResource(R.string.adbpair_title_failed) + } + + @Composable + private fun StepVisual(step: Step, compact: Boolean) { + val colors = MaterialTheme.colorScheme + val accent = LocalPalette.current.signal + val pulse = rememberInfiniteTransition(label = "guidePulse") + val beat by pulse.animateFloat(0f, 1f, infiniteRepeatable(tween(900, easing = LinearEasing), RepeatMode.Restart), label = "beat") + val label = when (step) { + Step.BUILD_NUMBER -> stringResource(R.string.pairguide_row_build_number) + Step.WIRELESS_DEBUGGING -> stringResource(R.string.pairguide_row_wireless) + Step.PAIR -> stringResource(R.string.pairguide_row_pair) + Step.CODE -> stringResource(R.string.adbpair_enter_code) + Step.WORKING, Step.DONE, Step.FAILED -> return + } + val rowHeight = if (compact) 34.dp else 56.dp + Row( + Modifier.fillMaxWidth().height(rowHeight).background(colors.surfaceVariant, RoundedCornerShape(10.dp)) + .border(1.dp, accent.copy(alpha = 0.35f), RoundedCornerShape(10.dp)).padding(horizontal = 10.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text(label, style = if (compact) MaterialTheme.typography.labelMedium else MaterialTheme.typography.bodyLarge, + color = colors.onSurface, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f)) + when (step) { + Step.WIRELESS_DEBUGGING -> Toggle(on = beat > 0.5f, accent = accent, compact = compact) + else -> Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) { + if (step == Step.BUILD_NUMBER) Text("×7", style = MaterialTheme.typography.labelLarge, color = accent) + Box(contentAlignment = Alignment.Center) { + Box(Modifier.size(if (compact) 18.dp else 26.dp).scale(0.6f + beat * 0.8f).alpha(1f - beat) + .background(accent, CircleShape)) + Box(Modifier.size(if (compact) 8.dp else 12.dp).background(accent, CircleShape)) + } + } + } + } + } + + @Composable + private fun Toggle(on: Boolean, accent: Color, compact: Boolean) { + val width = if (compact) 26.dp else 40.dp + val knob = if (compact) 12.dp else 18.dp + Box( + Modifier.width(width).height(knob + 4.dp) + .background(if (on) accent.copy(alpha = 0.6f) else MaterialTheme.colorScheme.outline, CircleShape).padding(2.dp), + contentAlignment = if (on) Alignment.CenterEnd else Alignment.CenterStart, + ) { Box(Modifier.size(knob).background(Color.White, CircleShape)) } + } + + @Composable + private fun StepDots(step: Step) { + val accent = LocalPalette.current.signal + val shown = listOf(Step.BUILD_NUMBER, Step.WIRELESS_DEBUGGING, Step.PAIR, Step.CODE) + val at = shown.indexOf(step).takeIf { it >= 0 } ?: shown.size + Row(horizontalArrangement = Arrangement.spacedBy(5.dp), verticalAlignment = Alignment.CenterVertically) { + shown.forEachIndexed { index, _ -> + Box(Modifier.size(if (index == at) 8.dp else 6.dp) + .background(if (index <= at) accent else MaterialTheme.colorScheme.outline, CircleShape)) + } + Spacer(Modifier.width(2.dp)) + } + } + + private data class SettingsState(val developerOptions: Boolean, val wirelessDebugging: Boolean) { + companion object { + fun read(context: Context) = SettingsState( + GlobalSettings.developerOptionsOn(context), + GlobalSettings.wirelessDebuggingOn(context), + ) + } + } + + companion object { + private const val EXTRA_DISPLAY = "settingsDisplay" + private const val HIGHLIGHT_KEY = ":settings:fragment_args_key" + + private fun stepFor(context: Context, stage: Stage) = stepFor(SettingsState.read(context), stage) + + private fun stepFor(settings: SettingsState, stage: Stage): Step = when (stage) { + is Stage.Working -> Step.WORKING + Stage.Done -> Step.DONE + is Stage.Failed -> Step.FAILED + is Stage.CodeNeeded -> Step.CODE + else -> when { + !settings.developerOptions -> Step.BUILD_NUMBER + !settings.wirelessDebugging -> Step.WIRELESS_DEBUGGING + else -> Step.PAIR + } + } + + fun canFloat(context: Context): Boolean { + if (!context.packageManager.hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE)) return false + val ops = context.getSystemService(AppOpsManager::class.java) ?: return true + val mode = if (Build.VERSION.SDK_INT >= 29) { + ops.unsafeCheckOpNoThrow(AppOpsManager.OPSTR_PICTURE_IN_PICTURE, Process.myUid(), context.packageName) + } else { + @Suppress("DEPRECATION") + ops.checkOpNoThrow(AppOpsManager.OPSTR_PICTURE_IN_PICTURE, Process.myUid(), context.packageName) + } + return mode == AppOpsManager.MODE_ALLOWED + } + + fun start(context: Context, settingsDisplay: Int?): Boolean { + if (settingsDisplay == null && !canFloat(context)) return false + context.startActivity(Intent(context, PairingGuideActivity::class.java) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + .apply { if (settingsDisplay != null) putExtra(EXTRA_DISPLAY, settingsDisplay) }) + return true + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/PinRequestActivity.kt b/app/src/main/java/com/droiddeck/launcher/PinRequestActivity.kt new file mode 100644 index 0000000000..ca8d382fee --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/PinRequestActivity.kt @@ -0,0 +1,82 @@ +package com.droiddeck.launcher + +import android.content.Intent +import android.content.pm.LauncherApps +import android.graphics.Bitmap +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.core.graphics.drawable.toBitmap +import com.droiddeck.launcher.core.AppUiPrefs +import com.droiddeck.launcher.ui.DroidDeckTheme +import com.droiddeck.launcher.ui.PinRequestPrompt + +class PinRequestActivity : ComponentActivity() { + override fun attachBaseContext(newBase: android.content.Context) { + super.attachBaseContext(newBase) + com.droiddeck.launcher.core.AppLanguage.applyTo(this, newBase) + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + val request = runCatching { getSystemService(LauncherApps::class.java).getPinItemRequest(intent) }.getOrNull() + if (request == null || !request.isValid) { + finish() + return + } + val prompt = when (request.requestType) { + LauncherApps.PinItemRequest.REQUEST_TYPE_SHORTCUT -> request.shortcutInfo?.let { info -> + val appLabel = appLabel(info.`package`) + Triple(info.shortLabel?.toString().orEmpty().ifEmpty { appLabel }, appLabel, HomeApp.shortcutIcon(this, info)) + } + LauncherApps.PinItemRequest.REQUEST_TYPE_APPWIDGET -> request.getAppWidgetProviderInfo(this)?.let { info -> + val appLabel = appLabel(info.provider.packageName) + val dpi = resources.displayMetrics.densityDpi + val icon = runCatching { (info.loadPreviewImage(this, dpi) ?: info.loadIcon(this, dpi))?.let(::scaled) }.getOrNull() + Triple(info.loadLabel(packageManager)?.toString().orEmpty().ifEmpty { appLabel }, appLabel, icon) + } + else -> null + } + if (prompt == null) { + finish() + return + } + val (label, appLabel, icon) = prompt + val widget = request.requestType == LauncherApps.PinItemRequest.REQUEST_TYPE_APPWIDGET + setContent { + DroidDeckTheme(appScale = AppUiPrefs.scale(this)) { + PinRequestPrompt( + label = label, appLabel = appLabel, icon = icon, wide = widget, + onAdd = { + if (!widget) { + HomePins.accept(this, request) + finish() + } else if (!HomeWidgets.addPinned(this, request)) finish() + }, + onCancel = { finish() }, + ) + } + } + } + + @Suppress("OVERRIDE_DEPRECATION") + override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { + if (HomeWidgets.onActivityResult(this, requestCode, resultCode)) { + finish() + return + } + @Suppress("DEPRECATION") + super.onActivityResult(requestCode, resultCode, data) + } + + private fun appLabel(packageName: String): String = + runCatching { packageManager.getApplicationLabel(packageManager.getApplicationInfo(packageName, 0)).toString() } + .getOrDefault(packageName) + + private fun scaled(d: android.graphics.drawable.Drawable): Bitmap { + val w = d.intrinsicWidth.takeIf { it > 0 } ?: 192 + val h = d.intrinsicHeight.takeIf { it > 0 } ?: 192 + val k = minOf(1f, 480f / maxOf(w, h)) + return d.toBitmap((w * k).toInt().coerceAtLeast(1), (h * k).toInt().coerceAtLeast(1)) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index c133da3b5b..b03e847112 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -68,6 +68,7 @@ import com.droiddeck.launcher.gpu.ScreenEffects import com.droiddeck.launcher.gpu.Lossless import com.droiddeck.launcher.gpu.TurnipDriver import com.droiddeck.launcher.input.EvdevKeys +import com.droiddeck.launcher.input.HomeGuideInput import com.droiddeck.launcher.input.InputSpace import com.droiddeck.launcher.input.KeyboardHost import com.droiddeck.launcher.input.ControllerPrefs @@ -399,6 +400,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { private var glassesOutputActive by mutableStateOf(false) private var pausedFrame by mutableStateOf(null) private var pausedFrameWanted = false + private var pauseAnimated by mutableStateOf(false) private var trackingRecovery by mutableStateOf(null) private var glasses3dForVr = false private var ended = false @@ -1154,6 +1156,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { pipSupported = com.droiddeck.launcher.session.SessionPipController.supported(this@SessionActivity), pipAutoEnter = pipAutoEnter, onPip = { pip.enter() }, + onPause = ::pauseNow, onPipAutoEnter = { on -> SessionPrefs.setPipAutoEnter(this@SessionActivity, on) pipAutoEnter = on @@ -1223,17 +1226,22 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { com.droiddeck.launcher.ui.AchievementNotificationOverlay() // Auto and Native resume on their own as the session comes back; only a failed resume needs the button. val autoResume = suspendPolicy == SessionPrefs.SUSPEND_AUTO || suspendPolicy == SessionPrefs.SUSPEND_NATIVE + LaunchedEffect(SessionState.manualPause, SessionState.suspended) { + if (!SessionState.manualPause && !SessionState.suspended) pauseAnimated = false + } SessionPausedOverlay( - suspended = SessionState.suspended && (!autoResume || SessionState.resumeFailed), + suspended = SessionState.suspended && (!autoResume || SessionState.resumeFailed || SessionState.manualPause), engaged = SessionState.resumeRequested || SessionState.resuming, failures = SessionState.resumeFailures, frame = pausedFrame, + animateIn = pauseAnimated, title = pausedTitle(), onResume = { SessionService.resume(this@SessionActivity) }, onFrameNeeded = ::requestPausedFrame, onHidden = { pausedFrame = null pausedFrameWanted = false + pauseAnimated = false }, ) if (leaving) com.droiddeck.launcher.ui.FloodSpread( @@ -1371,7 +1379,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { if (incoming?.action != SessionService.ACTION_HOME_GUIDE) return incoming.action = null setIntent(incoming) - if (SessionState.running && SessionState.mode == SessionService.MODE_STEAM) sendSteamGuide() + if (SessionState.suspended) SessionService.resume(this) + else if (SessionState.running && SessionState.mode == SessionService.MODE_STEAM) sendSteamGuide() } @@ -2233,9 +2242,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { if (line.contains(FEX_MISSING)) fexMissing = true } val steamSetup = com.droiddeck.launcher.session.SteamClientSetupFailure.find(text.lineSequence()) + val launchFailure = com.droiddeck.launcher.session.SessionLaunchFailure.find(text.lineSequence()) if (steamSetup != null) { val message = getString(if (steamSetup.download) R.string.session_end_steam_download else R.string.session_end_steam_setup) EndHint(listOfNotNull(message, steamSetup.curlError).joinToString("\n")) + } else if (launchFailure == com.droiddeck.launcher.session.SessionLaunchFailure.STEAM_ILLEGAL_INSTRUCTION) { + val message = getString(R.string.session_end_steam_sigill) + val fallback = if (SessionState.steamClientArch == "arm64") getString(R.string.session_end_steam_try_x64) else null + EndHint(listOfNotNull(message, fallback).joinToString("\n")) + } else if (launchFailure == com.droiddeck.launcher.session.SessionLaunchFailure.VULKAN_DEVICE_MISSING) { + val adreno = com.droiddeck.launcher.gpu.GpuInfo.detect().family != com.droiddeck.launcher.gpu.GpuInfo.Family.NOT_ADRENO + EndHint(getString(if (adreno) R.string.session_end_vulkan_device else R.string.session_end_gpu_unsupported)) } else if (fexMissing) { val what = com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) ?: getString(R.string.session_end_program) EndHint(getString(R.string.session_end_fex_missing, what), evenOnSuccess = true) @@ -2251,8 +2268,20 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { override fun dispatchKeyEvent(event: KeyEvent): Boolean { when (event.keyCode) { - KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE -> + KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE -> { + val steamVolume = + SessionState.mode == SessionService.MODE_STEAM && SessionState.running && + SessionState.firstFrameSeen && !SessionState.suspended && !ended && + !pipUi && !drawerOpen && !pcKeyboardOpen && !achievementsOpen && + !gestureSettingsOpen && !inputSettingsOpen && !screenKeyTextFocus && window.decorView.hasWindowFocus() + if (steamVolume) { + val audio = getSystemService(android.media.AudioManager::class.java) + if (com.droiddeck.launcher.input.SteamVolumeKeys.dispatch(event, !audio.isVolumeFixed) { direction -> + audio.adjustStreamVolume(android.media.AudioManager.STREAM_MUSIC, direction, 0) + }) return true + } return super.dispatchKeyEvent(event) + } } if (!pipUi && !screenKeyTextFocus) { val pad = com.droiddeck.launcher.input.JoyCon.normalize(event) @@ -2328,7 +2357,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { return true } val resumeKey = event.keyCode == KeyEvent.KEYCODE_BUTTON_A || event.keyCode == KeyEvent.KEYCODE_BUTTON_START || - event.keyCode == KeyEvent.KEYCODE_BUTTON_MODE || event.keyCode == KeyEvent.KEYCODE_HOME + event.keyCode == KeyEvent.KEYCODE_BUTTON_MODE || HomeGuideInput.isHome(event.keyCode) val resumeKeyId = event.deviceId to event.keyCode if (fromController && resumeKey && (SessionState.suspended || resumeKeyId in resumeKeysDown)) { if (event.action == KeyEvent.ACTION_DOWN) { @@ -3190,10 +3219,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { } // The frozen game cannot draw again, so the paused overlay shows a copy taken while the surface still holds its frame. - private fun capturePausedFrame() { + private fun capturePausedFrame(manual: Boolean = false) { if (!SessionState.running || pipUi || isInPictureInPictureMode || glassesOutputActive) return if (SessionState.suspended && pausedFrame != null) return - if (suspendPolicy == SessionPrefs.SUSPEND_NEVER || !::surfaceView.isInitialized) return + if ((suspendPolicy == SessionPrefs.SUSPEND_NEVER && !manual && !SessionState.manualPause) || !::surfaceView.isInitialized) return if (surfaceView.holder.surface?.isValid != true) return val width = surfaceView.width val height = surfaceView.height @@ -3225,6 +3254,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { } } + private fun pauseNow() { + if (!SessionState.running || SessionState.suspended) return + pauseAnimated = true + drawerOpen = false + pausedFrame = null + capturePausedFrame(manual = true) + SessionService.pause(this) + } + // Sessions that froze from picture-in-picture, or before onPause could copy a frame, have none; the // compositor shows the frozen frame again once its output is back, so copy it from there. private fun requestPausedFrame() { @@ -3390,7 +3428,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { enabled = { resumed && window.decorView.hasWindowFocus() && !ended && !drawerOpen && !pcKeyboardOpen && !achievementsOpen && !gestureSettingsOpen && !inputSettingsOpen && !pipUi && SessionState.running && !SessionState.suspended && - SessionState.mode == SessionService.MODE_STEAM && padBridge?.canHoldGuide() == true + SessionState.mode == SessionService.MODE_STEAM && padBridge != null }, setPressed = { padBridge?.setHomeGuidePressed(it) }, onCancel = { padBridge?.cancelHomeGuide() }, diff --git a/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt b/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt index d587ecb7cc..4163eb4a3e 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt @@ -29,6 +29,11 @@ import java.util.Locale object DeviceReport { private const val TAG = "DeviceReport" + internal fun cpuFeaturesSummary(cpuInfo: String): String = cpuInfo.lineSequence() + .filter { it.substringBefore(':').trim() == "Features" } + .map { it.substringAfter(':').trim().split(Regex("\\s+")).filter(String::isNotEmpty).joinToString(" ") } + .filter(String::isNotEmpty).distinct().joinToString(" | ").ifEmpty { "not reported" } + fun write(context: Context, target: File, mode: String) { try { target.writeText(build(context, mode)) @@ -141,6 +146,7 @@ object DeviceReport { h("CPU and memory") k("Cores", CpuCores.all.size) + k("CPU features", cpuFeaturesSummary(FileUtils.readString(File("/proc/cpuinfo")).orEmpty())) b.append("Core ceilings ") b.append(CpuCores.all.joinToString(", ") { c -> "cpu$c " + (CpuCores.maxGhz(c)?.let { String.format(Locale.US, "%.2f GHz", it) } ?: "?") diff --git a/app/src/main/java/com/droiddeck/launcher/core/GlobalSettings.kt b/app/src/main/java/com/droiddeck/launcher/core/GlobalSettings.kt new file mode 100644 index 0000000000..8cbf9bf39d --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/core/GlobalSettings.kt @@ -0,0 +1,24 @@ +package com.droiddeck.launcher.core + +import android.content.Context +import android.net.Uri +import android.provider.Settings + +object GlobalSettings { + // Settings.Global caches values in-process and misses deletions made over adb; ask the provider directly. + fun read(context: Context, name: String): String? { + val uri = Uri.withAppendedPath(Settings.Global.CONTENT_URI, name) + context.contentResolver.query(uri, arrayOf(Settings.NameValueTable.VALUE), null, null, null)?.use { cursor -> + return if (cursor.moveToFirst()) cursor.getString(0) else null + } + return Settings.Global.getString(context.contentResolver, name) + } + + fun isOn(context: Context, name: String): Boolean = + runCatching { read(context, name)?.trim() == "1" }.getOrDefault(false) + + fun developerOptionsOn(context: Context): Boolean = isOn(context, Settings.Global.DEVELOPMENT_SETTINGS_ENABLED) + + // Settings.Global.ADB_WIFI_ENABLED is hidden; the key is stable since Android 11. + fun wirelessDebuggingOn(context: Context): Boolean = isOn(context, "adb_wifi_enabled") +} diff --git a/app/src/main/java/com/droiddeck/launcher/core/LogRedactor.kt b/app/src/main/java/com/droiddeck/launcher/core/LogRedactor.kt index 20073c4ca3..f579adff00 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/LogRedactor.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/LogRedactor.kt @@ -1,21 +1,59 @@ package com.droiddeck.launcher.core object LogRedactor { - private val EMAIL = Regex("[A-Za-z0-9._%+\\-]+@[A-Za-z0-9.\\-]+\\.[A-Za-z]{2,}") - private val HIDL_SHARED_LIBRARY = Regex( - "(?:android\\.(?:hardware|frameworks|hidl|system)|vendor\\.[A-Za-z0-9_]+\\.hardware)" + - "(?:\\.[A-Za-z0-9_]+)+@[0-9]+\\.[0-9]+(?:-[A-Za-z0-9_]+)*\\.so" - ) - private val hidlMatcher = object : ThreadLocal() { - override fun initialValue(): java.util.regex.Matcher = HIDL_SHARED_LIBRARY.toPattern().matcher("") + internal const val MAX_LINE_LENGTH = 64 * 1024 + internal const val OVERSIZED_LINE = "" + + private data class MatcherKey(val pattern: String, val options: Set) + + private class MatcherCache : LinkedHashMap(32, 0.75f, true) { + override fun removeEldestEntry(eldest: MutableMap.MutableEntry?): Boolean = + size > 32 } - private fun isHidlLoaderDiagnostic(input: String, match: MatchResult): Boolean { - val matcher = hidlMatcher.get()!! - val isLibrary = try { matcher.reset(match.value).matches() } finally { matcher.reset("") } - if (!isLibrary) return false - val start = match.range.first - val end = match.range.last + 1 + // Android matchers own native state, so reuse them instead of creating one for every log line. + private val matchers = object : ThreadLocal() { + override fun initialValue(): MatcherCache = MatcherCache() + } + + private fun withMatcher( + regex: Regex, + input: CharSequence, + action: (java.util.regex.Matcher) -> T, + ): T { + val key = MatcherKey(regex.pattern, regex.options) + val matcher = matchers.get()!!.getOrPut(key) { regex.toPattern().matcher("") } + return try { + action(matcher.reset(input)) + } finally { + matcher.reset("") + } + } + + private fun replaceMatches(input: String, regex: Regex, replacement: String): String = + replaceMatches(input, regex) { replacement } + + private fun replaceMatches( + input: String, + regex: Regex, + replacement: (java.util.regex.Matcher) -> String, + ): String = withMatcher(regex, input) { matcher -> + if (!matcher.find()) return@withMatcher input + val out = StringBuffer(input.length) + do { + matcher.appendReplacement(out, java.util.regex.Matcher.quoteReplacement(replacement(matcher))) + } while (matcher.find()) + matcher.appendTail(out) + out.toString() + } + + private fun matchesEntire(input: String, regex: Regex): Boolean = + withMatcher(regex, input) { it.matches() } + + private fun isHidlLoaderDiagnostic(input: String, match: java.util.regex.Matcher): Boolean { + if (!matchesEntire(match.group(), HIDL_SHARED_LIBRARY)) return false + val start = match.start() + val end = match.end() val prefix = "library \"" val suffix = "\" not found" val earliestQuote = (start - 4096).coerceAtLeast(0) @@ -39,6 +77,12 @@ object LogRedactor { (suffixEnd == input.length || !(input[suffixEnd].isLetterOrDigit() || input[suffixEnd] == '_')) } + private val EMAIL = Regex("[A-Za-z0-9._%+\\-]+@[A-Za-z0-9.\\-]+\\.[A-Za-z]{2,}") + private val HIDL_SHARED_LIBRARY = Regex( + "(?:android\\.(?:hardware|frameworks|hidl|system)|vendor\\.[A-Za-z0-9_]+\\.hardware)" + + "(?:\\.[A-Za-z0-9_]+)+@[0-9]+\\.[0-9]+(?:-[A-Za-z0-9_]+)*\\.so" + ) + private val JWT_LABELLED = Regex("(?i)(\\bJWT[\\s=:]+)(\\d{8,})") private val JWT_BASE64 = Regex("ey[A-Za-z0-9_\\-]{6,}\\.[A-Za-z0-9_\\-]{6,}\\.[A-Za-z0-9_\\-]{6,}") private val GUID = Regex("\\b[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}\\b") @@ -111,6 +155,7 @@ object LogRedactor { java.io.File(root, "root/.local/share/Steam/config/loginusers.vdf"), java.io.File(root, "root/.droiddeck-x64/.local/share/Steam/config/loginusers.vdf"), ) + matchers.remove() } @Volatile @@ -178,8 +223,8 @@ object LogRedactor { } fun describeAddresses(text: String): String { - var out = IPV6.replace(text) { m -> kind(m.value)?.let { "<$it>" } ?: m.value } - out = IPV4.replace(out) { m -> kind(m.value)?.let { "<$it>" } ?: m.value } + var out = replaceMatches(text, IPV6) { m -> kind(m.group())?.let { "<$it>" } ?: m.group() } + out = replaceMatches(out, IPV4) { m -> kind(m.group())?.let { "<$it>" } ?: m.group() } return out } @@ -204,23 +249,28 @@ object LogRedactor { "(? out.write(redact(line)); out.write("\n") } - } + fun scrubTo( + src: java.io.File, + out: java.io.Writer, + shouldStop: () -> Boolean = { false }, + ): Boolean = scrubLines(src, out, ::redact, shouldStop) fun redactForShare(line: String): String { if (line.isEmpty()) return line + if (line.length > MAX_LINE_LENGTH) return OVERSIZED_LINE return try { val out = SecretScrub.scrub(redact(line), SecretScrub.Urls.KEEP_PATH, "") - LAN_IPV4.replace(out, "") + replaceMatches(out, LAN_IPV4, "") } catch (t: Throwable) { "" } } - private const val SHARE_LINE_MAX = 64 * 1024 - - fun scrubForShare(src: java.io.File, out: java.io.Writer) { + fun scrubForShare( + src: java.io.File, + out: java.io.Writer, + shouldStop: () -> Boolean = { false }, + ): Boolean { src.inputStream().buffered().use { input -> input.mark(2) val first = input.read() @@ -228,27 +278,30 @@ object LogRedactor { input.reset() if ((first == 0xff && second == 0xfe) || (first == 0xfe && second == 0xff)) { out.write("\n") - return + return true } val decoder = Charsets.UTF_8.newDecoder() .onMalformedInput(java.nio.charset.CodingErrorAction.REPORT) .onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT) java.io.InputStreamReader(input, decoder).use { reader -> val buffer = CharArray(8192) - val line = StringBuilder() - var withheld = false + val line = StringBuilder(4096) + var withheld: String? = null var afterCr = false fun emit() { - out.write(if (withheld) "" else redactForShare(line.toString())) + out.write(withheld ?: redactForShare(line.toString())) out.write("\n") line.setLength(0) - withheld = false + withheld = null } try { while (true) { + if (shouldStop()) return false val size = reader.read(buffer) if (size < 0) break + if (shouldStop()) return false for (i in 0 until size) { + if (shouldStop()) return false val ch = buffer[i] if (afterCr) { afterCr = false @@ -257,23 +310,79 @@ object LogRedactor { if (ch == '\r' || ch == '\n') { emit() afterCr = ch == '\r' - } else if (!withheld) { - // Splitting a line can separate a credential from its label. - if (ch == '\u0000' || line.length == SHARE_LINE_MAX) { - withheld = true + } else if (withheld == null) { + if (ch == '\u0000' || line.length == MAX_LINE_LENGTH) { + withheld = if (ch == '\u0000') "" else OVERSIZED_LINE line.setLength(0) - } else { - line.append(ch) - } + } else line.append(ch) } } } - if (withheld || line.isNotEmpty()) emit() + if (withheld != null || line.isNotEmpty()) emit() } catch (_: java.nio.charset.CharacterCodingException) { out.write("\n") } } } + return true + } + + + private fun scrubLines( + src: java.io.File, + out: java.io.Writer, + scrub: (String) -> String, + shouldStop: () -> Boolean, + ): Boolean { + src.bufferedReader().use { input -> + val chunk = CharArray(8192) + val line = StringBuilder(4096) + var oversized = false + var pendingContent = false + var pendingCarriageReturn = false + + fun emit() { + out.write(if (oversized) OVERSIZED_LINE else scrub(line.toString())) + out.write("\n") + line.setLength(0) + oversized = false + pendingContent = false + } + + while (true) { + if (shouldStop()) return false + val count = input.read(chunk) + if (count < 0) break + if (shouldStop()) return false + for (i in 0 until count) { + val char = chunk[i] + if (pendingCarriageReturn) { + emit() + pendingCarriageReturn = false + if (char == '\n') continue + } + when (char) { + '\r' -> pendingCarriageReturn = true + '\n' -> emit() + else -> { + pendingContent = true + if (!oversized) { + if (line.length < MAX_LINE_LENGTH) line.append(char) + else { + line.setLength(0) + oversized = true + } + } + } + } + } + } + if (pendingCarriageReturn || pendingContent) { + if (shouldStop()) return false + emit() + } + } + return true } private fun quoted(value: String): String { @@ -315,45 +424,51 @@ object LogRedactor { fun redact(line: String): String { if (line.isEmpty()) return line + if (line.length > MAX_LINE_LENGTH) return OVERSIZED_LINE return try { val out = Line(line) - if (out.has("mac")) out.set(MAC_FIELD.replace(out.text) { "${it.groupValues[1]}" }) - if (out.holds(':', 5) || out.holds('-', 5)) out.set(MAC.replace(out.text, "")) - if (out.has("serial", "android")) out.set(DEVICE_IDENTIFIER.replace(out.text) { - val value = it.groupValues[2] + if (out.has("mac")) out.set(replaceMatches(out.text, MAC_FIELD) { "${it.group(1)}" }) + if (out.holds(':', 5) || out.holds('-', 5)) out.set(replaceMatches(out.text, MAC, "")) + if (out.has("serial", "android")) out.set(replaceMatches(out.text, DEVICE_IDENTIFIER) { + val value = it.group(2) val quote = value.first().takeIf { char -> char == '\"' || char == '\'' }?.toString().orEmpty() - "${it.groupValues[1]}${quote}${quote}" + "${it.group(1)}${quote}${quote}" }) - if (out.holds('-', 4)) out.set(GUID.replace(out.text, "")) - if (out.has("jwt")) out.set(JWT_LABELLED.replace(out.text) { "${it.groupValues[1]}" }) - if ("ey" in out.text) out.set(JWT_BASE64.replace(out.text, "")) + if (out.holds('-', 4)) out.set(replaceMatches(out.text, GUID, "")) + if (out.has("jwt")) out.set(replaceMatches(out.text, JWT_LABELLED) { "${it.group(1)}" }) + if ("ey" in out.text) out.set(replaceMatches(out.text, JWT_BASE64, "")) 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]}${it.groupValues[2]}" }) + out.set(replaceMatches(out.text, SECRET_KV) { + val quote = it.group(2).orEmpty() + "${it.group(1)}${quote}${quote}" + }) + } - if (out.has("guard", "factor", "2fa")) out.set(GUARD_CODE.replace(out.text) { "${it.groupValues[1]}" }) - if (out.hasRun(32, ::isHex)) out.set(WEBAPI_KEY.replace(out.text, "")) - if ("76561" in out.text) out.set(STEAMID64.replace(out.text) { "${it.groupValues[1]}********${it.groupValues[3]}" }) - if ("[U:1:" in out.text) out.set(STEAMID3.replace(out.text) { m -> - val id = m.groupValues[1] + if (out.has("guard", "factor", "2fa")) out.set(replaceMatches(out.text, GUARD_CODE) { "${it.group(1)}" }) + if (out.hasRun(32, ::isHex)) out.set(replaceMatches(out.text, WEBAPI_KEY, "")) + if ("76561" in out.text) out.set(replaceMatches(out.text, STEAMID64) { "${it.group(1)}********${it.group(3)}" }) + if ("[U:1:" in out.text) out.set(replaceMatches(out.text, STEAMID3) { m -> + val id = m.group(1) "[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]}" }) - for (r in own) if (r.needs == null || out.has(r.needs)) out.set(r.regex.replace(out.text, "")) - if (out.has("onloginstatechange")) out.set(LOGIN_STATE.replace(out.text) { "${it.groupValues[1]}" }) - if ("OnLoginUsersChanged " in out.text) out.set(LOGIN_USERS.replace(out.text) { "${it.groupValues[1]}" }) + if (out.has("external")) out.set(replaceMatches(out.text, EXTERNAL_ADDR) { "${it.group(1)}" }) + for (r in own) if (r.needs == null || out.has(r.needs)) out.set(replaceMatches(out.text, r.regex, "")) + if (out.has("onloginstatechange")) out.set(replaceMatches(out.text, LOGIN_STATE) { "${it.group(1)}" }) + if ("OnLoginUsersChanged " in out.text) out.set(replaceMatches(out.text, LOGIN_USERS) { "${it.group(1)}" }) if (out.has("account", "user")) { - out.set(ACCOUNT_KV.replace(out.text) { "${it.groupValues[1]}${it.groupValues[2]}${quoted(it.groupValues[3])}" }) + out.set(replaceMatches(out.text, ACCOUNT_KV) { "${it.group(1)}${it.group(2)}${quoted(it.group(3))}" }) } - if (out.has("login")) out.set(LOGIN_KV.replace(out.text) { "${it.groupValues[1]}${it.groupValues[2]}${quoted(it.groupValues[3])}" }) - for (r in accounts) if (r.needs == null || out.has(r.needs)) out.set(r.regex.replace(out.text, "")) - if ('@' in out.text) out.set(EMAIL.replace(out.text) { m -> - m.value.takeIf { isHidlLoaderDiagnostic(out.text, m) } ?: "" + if (out.has("login")) out.set(replaceMatches(out.text, LOGIN_KV) { "${it.group(1)}${it.group(2)}${quoted(it.group(3))}" }) + for (r in accounts) if (r.needs == null || out.has(r.needs)) out.set(replaceMatches(out.text, r.regex, "")) + if ('@' in out.text) out.set(replaceMatches(out.text, EMAIL) { m -> + m.group().takeIf { isHidlLoaderDiagnostic(out.text, m) } ?: "" + }) if (out.has("jwt", "token", "ticket", "sessionid", "steamloginsecure", "machineauth")) { - out.set(RESIDUAL.replace(out.text) { "${it.groupValues[1]}=" }) + out.set(replaceMatches(out.text, RESIDUAL) { "${it.group(1)}=" }) } if (out.hasRun(88) { it in 'a'..'z' || it in 'A'..'Z' || it in '0'..'9' || it == '_' || it == '-' }) { - out.set(LONG_TOKEN.replace(out.text, "")) + out.set(replaceMatches(out.text, LONG_TOKEN, "")) } out.text } catch (t: Throwable) { diff --git a/app/src/main/java/com/droiddeck/launcher/core/PhantomProcessLimit.kt b/app/src/main/java/com/droiddeck/launcher/core/PhantomProcessLimit.kt index 6ad5f89b64..6e67ff495d 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/PhantomProcessLimit.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/PhantomProcessLimit.kt @@ -60,14 +60,14 @@ object PhantomProcessLimit { if (usesDeviceConfig(sdk)) { val off = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getBoolean(PREF_ANDROID_12_OFF, false) val global = try { - Settings.Global.getString(context.contentResolver, SETTING) + GlobalSettings.read(context, SETTING) } catch (_: Exception) { null } return android12Status(off, global, systemProperty(OVERRIDE_PROPERTY)) } val global = try { - Settings.Global.getString(context.contentResolver, SETTING) + GlobalSettings.read(context, SETTING) } catch (_: Exception) { return PhantomProcessStatus.UNREADABLE } diff --git a/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbPairingService.kt b/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbPairingService.kt index c924f85329..2d6adb902b 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbPairingService.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbPairingService.kt @@ -184,12 +184,15 @@ class WirelessAdbPairingService : Service() { setSound(null, null) enableVibration(false) }) + manager?.createNotificationChannel(NotificationChannel(PROGRESS_CHANNEL_ID, getString(R.string.adbpair_progress_channel_name), + NotificationManager.IMPORTANCE_LOW).apply { setShowBadge(false) }) val open = PendingIntent.getActivity(this, 0, Intent(this, FrontEndActivity::class.java).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT), PendingIntent.FLAG_IMMUTABLE) val cancel = PendingIntent.getService(this, 1, Intent(this, WirelessAdbPairingService::class.java).setAction(ACTION_CANCEL), PendingIntent.FLAG_IMMUTABLE) - val builder = Notification.Builder(this, CHANNEL_ID) + val quiet = stage == Stage.Waiting || stage == Stage.Idle || stage is Stage.Working + val builder = Notification.Builder(this, if (quiet) PROGRESS_CHANNEL_ID else CHANNEL_ID) .setSmallIcon(R.drawable.ic_stat_session) .setContentIntent(open) .setShowWhen(false) @@ -239,6 +242,7 @@ class WirelessAdbPairingService : Service() { companion object { private const val CHANNEL_ID = "wireless-adb-pairing" + private const val PROGRESS_CHANNEL_ID = "wireless-adb-pairing-progress" private const val NOTIFICATION_ID = 3 private const val PAIRING_TYPE = "_adb-tls-pairing._tcp" private const val ACTION_CODE = "com.droiddeck.launcher.action.WIRELESS_ADB_CODE" diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/TurnipDriver.java b/app/src/main/java/com/droiddeck/launcher/gpu/TurnipDriver.java index 9978409c5f..9bae92e42a 100644 --- a/app/src/main/java/com/droiddeck/launcher/gpu/TurnipDriver.java +++ b/app/src/main/java/com/droiddeck/launcher/gpu/TurnipDriver.java @@ -22,6 +22,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; +import java.util.function.Supplier; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; @@ -47,10 +48,16 @@ public final class TurnipDriver { private final Context context; private final File contentDir; + private final Supplier gpuDetector; public TurnipDriver(Context context) { + this(context, GpuInfo.Companion::detect); + } + + TurnipDriver(Context context, Supplier gpuDetector) { this.context = context; this.contentDir = new File(context.getFilesDir(), "graphics_driver"); + this.gpuDetector = gpuDetector; } public String driverPath(String driverId) { @@ -284,7 +291,12 @@ public final class TurnipDriver { } String quest = QuestExperimental.INSTANCE.defaultAndroidDriver(); if (quest != null) return quest; - int model = GpuInfo.Companion.detect().getModel(); + GpuInfo gpu = gpuDetector.get(); + if (gpu.getFamily() == GpuInfo.Family.NOT_ADRENO) { + Log.i(TAG, "not an Adreno GPU; leaving the display driver to the system"); + return null; + } + int model = gpu.getModel(); Log.i(TAG, "gpu model: " + (model == 0 ? "unknown" : model)); return chooseByModel(model, android.os.Build.VERSION.SDK_INT); } diff --git a/app/src/main/java/com/droiddeck/launcher/input/HomeButtonService.kt b/app/src/main/java/com/droiddeck/launcher/input/HomeButtonService.kt index 874d8fe583..b85fecb120 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/HomeButtonService.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/HomeButtonService.kt @@ -38,7 +38,7 @@ object HomeButtonShortcuts { fun onKeyEvent(context: Context, event: KeyEvent): Boolean { // AYN maps its system-assistant key (gpio-keys KEY_F24) to HOME too; only the pad's Home is Guide. - if (event.keyCode != KeyEvent.KEYCODE_HOME || !PadBridge.isControllerKeyEvent(event)) return false + if (!HomeGuideInput.isHome(event.keyCode) || !PadBridge.isControllerKeyEvent(event)) return false return input.onKeyEvent(event, enabled() && HomeApp.isDefault(context)) } diff --git a/app/src/main/java/com/droiddeck/launcher/input/HomeGuideInput.kt b/app/src/main/java/com/droiddeck/launcher/input/HomeGuideInput.kt index dfb7dbb0a1..785f7c1a13 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/HomeGuideInput.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/HomeGuideInput.kt @@ -7,7 +7,7 @@ class HomeGuideInput(private val setPressed: (Boolean) -> Unit, private val onCa private val cancelled = mutableSetOf() fun onKeyEvent(event: KeyEvent, enabled: Boolean): Boolean { - if (event.keyCode != KeyEvent.KEYCODE_HOME) return false + if (!isHome(event.keyCode)) return false if (!enabled) cancel() val device = event.deviceId return when (event.action) { @@ -39,4 +39,9 @@ class HomeGuideInput(private val setPressed: (Boolean) -> Unit, private val onCa cancelled.remove(device) if (presses.remove(device) && presses.isEmpty()) { onCancel(); setPressed(false) } } + + companion object { + // The Retroid Nova pad falls back to Generic.kl, which maps its Home scan code to MOVE_HOME. + fun isHome(keyCode: Int) = keyCode == KeyEvent.KEYCODE_HOME || keyCode == KeyEvent.KEYCODE_MOVE_HOME + } } diff --git a/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java b/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java index 140582d9a8..a31e52dbe4 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java +++ b/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java @@ -53,6 +53,7 @@ public final class PadBridge { private final FakeInputWriter[] playerWriters = new FakeInputWriter[SLOTS]; private final PadState[] playerStates = new PadState[SLOTS]; private final PadState effectiveState = new PadState(); + private final PadState homeGuideReport = new PadState(); private final PadState combinedState = new PadState(); private InputRouter inputRouter; private final InputRouter.PadSource[] physicalRoutes = new InputRouter.PadSource[SLOTS]; @@ -76,6 +77,7 @@ public final class PadBridge { private boolean systemQamPressed; private boolean backQamPressed; private boolean homeGuidePressed; + private int homeGuideSlot = -1; private final PadState lastBackQamReport = new PadState(); private final PadState lastWrittenReport = new PadState(); private final PadState liveReport = new PadState(); @@ -225,6 +227,7 @@ public final class PadBridge { Arrays.fill(physicalRoutes, null); inputRouter = null; homeGuidePressed = false; + homeGuideSlot = -1; clearBackQamWrites(); releaseBackPaddles(); activeControllerId = NO_CONTROLLER; @@ -292,6 +295,7 @@ public final class PadBridge { case KeyEvent.KEYCODE_BACK: case KeyEvent.KEYCODE_MENU: case KeyEvent.KEYCODE_HOME: + case KeyEvent.KEYCODE_MOVE_HOME: if (!isFromController(device)) return false; return device.supportsSource(InputDevice.SOURCE_GAMEPAD) || device.getKeyboardType() != InputDevice.KEYBOARD_TYPE_ALPHABETIC @@ -390,7 +394,8 @@ public final class PadBridge { case KeyEvent.KEYCODE_BUTTON_THUMBL: pad.press(8, pressed); break; case KeyEvent.KEYCODE_BUTTON_THUMBR: pad.press(9, pressed); break; case KeyEvent.KEYCODE_BUTTON_MODE: - case KeyEvent.KEYCODE_HOME: pad.press(PadState.GUIDE, pressed); break; + case KeyEvent.KEYCODE_HOME: + case KeyEvent.KEYCODE_MOVE_HOME: pad.press(PadState.GUIDE, pressed); break; case KeyEvent.KEYCODE_BUTTON_Z: if (isPrimary(event)) DeckControls.INSTANCE.setGrip(isNovaController(event.getDevice()) ? DeckControls.R4 : DeckControls.L4, pressed); break; @@ -568,6 +573,7 @@ public final class PadBridge { DeckControls.INSTANCE.suspend(); if (inputRouter == null) state.clear(); homeGuidePressed = false; + homeGuideSlot = -1; clearBackQamWrites(); backQamPressed = false; if (inputRouter == null) releaseBackPaddles(); @@ -593,18 +599,24 @@ public final class PadBridge { return builtinPad && nativeQam(); } - public boolean canHoldGuide() { - return builtinPad; - } - public synchronized void setHomeGuidePressed(boolean pressed) { - if (pressed && !canHoldGuide()) return; + int slot = pressed ? firstPlayerSlot() : homeGuideSlot; + if (slot > 0) { + homeGuideSlot = pressed ? slot : -1; + publish(slot); + return; + } if (homeGuidePressed == pressed) return; homeGuidePressed = pressed; updateHeldModifier(PadState.GUIDE, pressed); } public synchronized void cancelHomeGuide() { + int slot = homeGuideSlot; + if (slot > 0) { + homeGuideSlot = -1; + publish(slot); + } if (!homeGuidePressed) return; clearBackQamWrites(); homeGuidePressed = false; @@ -903,6 +915,7 @@ public final class PadBridge { partners[slot] = NO_CONTROLLER; clearJoyCons(slot); slotControllers.set(slot, NO_CONTROLLER); + if (slot == homeGuideSlot) homeGuideSlot = -1; if (slot == firstPlayerSlot()) releaseBackPaddles(); if (slot == 0) { state.clear(); @@ -960,6 +973,11 @@ public final class PadBridge { } playerWriters[slot] = player; } + if (slot == homeGuideSlot) { + homeGuideReport.copyFrom(output); + homeGuideReport.press(PadState.GUIDE, true); + output = homeGuideReport; + } player.writePad(output); } diff --git a/app/src/main/java/com/droiddeck/launcher/input/SteamVolumeKeys.kt b/app/src/main/java/com/droiddeck/launcher/input/SteamVolumeKeys.kt new file mode 100644 index 0000000000..3e0ca925aa --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/input/SteamVolumeKeys.kt @@ -0,0 +1,22 @@ +package com.droiddeck.launcher.input + +import android.media.AudioManager +import android.view.KeyEvent + +/** Use Steam's PulseAudio bridge for feedback instead of requesting Android's volume UI. */ +internal object SteamVolumeKeys { + fun dispatch(event: KeyEvent, enabled: Boolean, adjust: (Int) -> Unit): Boolean { + val direction = when (event.keyCode) { + KeyEvent.KEYCODE_VOLUME_UP -> AudioManager.ADJUST_RAISE + KeyEvent.KEYCODE_VOLUME_DOWN -> AudioManager.ADJUST_LOWER + KeyEvent.KEYCODE_VOLUME_MUTE -> AudioManager.ADJUST_TOGGLE_MUTE + else -> return false + } + if (!enabled) return false + if (event.action == KeyEvent.ACTION_DOWN && + (event.keyCode != KeyEvent.KEYCODE_VOLUME_MUTE || event.repeatCount == 0)) { + adjust(direction) + } + return event.action == KeyEvent.ACTION_DOWN || event.action == KeyEvent.ACTION_UP + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/DeviceControlsComponent.kt b/app/src/main/java/com/droiddeck/launcher/runtime/DeviceControlsComponent.kt index f5780da94f..cf0d3d7f63 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/DeviceControlsComponent.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/DeviceControlsComponent.kt @@ -1,7 +1,9 @@ package com.droiddeck.launcher.runtime +import android.content.BroadcastReceiver import android.content.Context import android.content.Intent +import android.content.IntentFilter import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager @@ -34,6 +36,9 @@ class DeviceControlsComponent(context: Context, root: File, private val activity private val observer = object : ContentObserver(handler) { override fun onChange(selfChange: Boolean) { if (running) publish() } } + private val volumeSteps = object : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { if (running) publishVolume() } + } private val requests = object : FileObserver(directory.path, CLOSE_WRITE or MOVED_TO) { override fun onEvent(event: Int, path: String?) { if (path in REQUESTS) handler.post { if (running) consume() } @@ -50,13 +55,22 @@ class DeviceControlsComponent(context: Context, root: File, private val activity } } - fun publish(force: Boolean = false) { + private fun publishVolume() { try { directory.mkdirs() val level = audio.getStreamVolume(AudioManager.STREAM_MUSIC) val maximum = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC).coerceAtLeast(1) val muted = audio.isStreamMute(AudioManager.STREAM_MUSIC) write("volume.state", "$level $maximum ${if (muted) 1 else 0}\n") + } catch (e: Exception) { + Log.w(TAG, "Could not publish Android volume", e) + } + } + + fun publish(force: Boolean = false) { + publishVolume() + try { + directory.mkdirs() val value = Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS, 128) write("backlight/droiddeck/brightness", "$value\n") write("backlight/droiddeck/actual_brightness", "$value\n") @@ -81,6 +95,10 @@ class DeviceControlsComponent(context: Context, root: File, private val activity permissionNotified = false context.contentResolver.registerContentObserver(Settings.System.CONTENT_URI, true, observer) requests.startWatching() + context.registerReceiver(volumeSteps, IntentFilter().apply { + addAction(VOLUME_CHANGED_ACTION) + addAction(STREAM_MUTE_CHANGED_ACTION) + }, null, handler) refresh.run() } } @@ -90,6 +108,7 @@ class DeviceControlsComponent(context: Context, root: File, private val activity running = false handler.removeCallbacks(refresh) requests.stopWatching() + try { context.unregisterReceiver(volumeSteps) } catch (e: IllegalArgumentException) { } context.contentResolver.unregisterContentObserver(observer) context.getSystemService(NotificationManager::class.java).cancel(PERMISSION_NOTIFICATION) } @@ -170,6 +189,9 @@ class DeviceControlsComponent(context: Context, root: File, private val activity companion object { private const val TAG = "DeviceControls" + // AudioService sends these on every stream step; the Settings observer and 250 ms poll lag a held volume key. + private const val VOLUME_CHANGED_ACTION = "android.media.VOLUME_CHANGED_ACTION" + private const val STREAM_MUTE_CHANGED_ACTION = "android.media.STREAM_MUTE_CHANGED_ACTION" private const val PERMISSION_CHANNEL = "brightness_permission" private const val PERMISSION_NOTIFICATION = 0x4442 private val REQUESTS = setOf("brightness.request", "volume.request", "mute.request") diff --git a/app/src/main/java/com/droiddeck/launcher/session/GameEnvironmentStore.kt b/app/src/main/java/com/droiddeck/launcher/session/GameEnvironmentStore.kt index 4d1ae8de21..27882ebcf1 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/GameEnvironmentStore.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/GameEnvironmentStore.kt @@ -13,6 +13,7 @@ object GameEnvironmentStore { private const val GUEST_FILE = "root/.config/droiddeck/game-environment.json" const val DXVK_CONFIG = "dxvkConfig" const val DXVK_CONFIG_GAMES = "dxvkConfigGames" + const val GAME_DEBUG_LOGS = "gameDebugLogs" @Synchronized fun read(context: Context): GameEnvironment.Config { @@ -87,7 +88,11 @@ object GameEnvironmentStore { } @Synchronized - fun publish(context: Context, config: GameEnvironment.Config = read(context)) { + fun publish( + context: Context, + config: GameEnvironment.Config = read(context), + gameDebugLogsOverride: Boolean? = null, + ) { val resolved = config.copy(shared = GameEnvironment.defaults(SessionPrefs.fexPreset(context), SessionPrefs.forceSsbs(context)) + config.shared) val json = encode(resolved) val dxvk = TextureFiltering.dxvkOptions( @@ -110,6 +115,11 @@ object GameEnvironmentStore { ) } if (gameDxvk.length() > 0) json.put(DXVK_CONFIG_GAMES, gameDxvk) + json.put( + GAME_DEBUG_LOGS, + gameDebugLogsOverride ?: (SessionPrefs.logsEnabled(context) && + SessionPrefs.gameDebugLogsEnabled(context) && SessionPaths.currentSessionLogsRetained(context)), + ) write(File(LinuxRuntime.rootDir(context), GUEST_FILE), json.toString()) } diff --git a/app/src/main/java/com/droiddeck/launcher/session/NoSteamLaunch.kt b/app/src/main/java/com/droiddeck/launcher/session/NoSteamLaunch.kt index b8dab5de11..8d8070f875 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/NoSteamLaunch.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/NoSteamLaunch.kt @@ -51,7 +51,8 @@ object NoSteamLaunch { fun addedGame(context: Context, game: Library.SteamGame): AddedGames.Game? { val id = game.appId.toLong() and 0xFFFFFFFFL - return AddedGames.scan(context).firstOrNull { settingsId(it) == id } + val one = game.gameFiles?.let { AddedGames.single(context, it.path) } + return one?.takeIf { settingsId(it) == id } ?: AddedGames.scan(context).firstOrNull { settingsId(it) == id } } fun nameFor(program: String?, args: List): String? = when (program) { diff --git a/app/src/main/java/com/droiddeck/launcher/session/RumbleComponent.kt b/app/src/main/java/com/droiddeck/launcher/session/RumbleComponent.kt index f2b1c0a1e6..5826db97ab 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/RumbleComponent.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/RumbleComponent.kt @@ -30,6 +30,7 @@ class RumbleComponent : SessionPart() { private val joyConPairs = HashMap() private var preferences: SharedPreferences? = null private var enabled = false + private var quiet = false private var motorThread: HandlerThread? = null private var handler: Handler? = null private val preferenceListener = SharedPreferences.OnSharedPreferenceChangeListener { _, key -> @@ -44,6 +45,11 @@ class RumbleComponent : SessionPart() { if (!enabled) cancelAll() } + @Synchronized fun quiet(on: Boolean) { + quiet = on + if (on) cancelAll() + } + override fun start() { val ctx = app() ?: return val s = try { LocalServerSocket(NAME) } catch (e: Exception) { Log.w(TAG, "rumble: no listener ($e)"); return } @@ -89,7 +95,7 @@ class RumbleComponent : SessionPart() { private fun u16(b: ByteArray, at: Int): Int = (b[at].toInt() and 0xFF) or ((b[at + 1].toInt() and 0xFF) shl 8) @Synchronized private fun buzz(strong: Int, weak: Int, ms: Int, slot: Int) { - if (!enabled) return + if (!enabled || quiet) return val target = target(slot) val previous = playing[slot] if (target !== previous) { diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionArtifacts.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionArtifacts.kt index c356bf0d04..b4408c48b9 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionArtifacts.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionArtifacts.kt @@ -7,6 +7,9 @@ import com.droiddeck.launcher.core.SessionLogCapture import com.droiddeck.launcher.runtime.LinuxRuntime import com.droiddeck.launcher.wayland.WaylandCompositor import java.io.File +import java.io.Writer +import java.nio.file.Files +import java.nio.file.StandardCopyOption import java.text.SimpleDateFormat import java.util.Date import java.util.Locale @@ -16,6 +19,9 @@ object SessionArtifacts { const val COMPLETE_MARKER = ".complete" + private const val RECOVERY_RUNTIME_CAPTURED_MARKER = ".recovery-runtime-captured" + private const val RECOVERY_RUNTIME_EXPIRED_MARKER = ".recovery-runtime-expired" + private val SCRUBBED_MARKER = ".scrubbed-r${LogRedactor.RULES_VERSION}" private val OLD_SCRUBBED_MARKER = Regex("""\.scrubbed-(r?\d+)""") @@ -72,9 +78,9 @@ object SessionArtifacts { copySteamLogs(context, dir, record, steamArch) VacDiagnostics.collect(context, dir) SessionLogCapture.dumpCrashBuffer(File(dir, "crash.log")) - markScrubbed(scrubTree(record)) + val scrubbed = markScrubbed(scrubTree(record)) SessionEvents.record("session.artifacts_collected", mapOf("reason" to reason), dir) - File(dir, COMPLETE_MARKER).writeText("collected: $reason at ${now()}\n") + if (scrubbed) File(dir, COMPLETE_MARKER).writeText("collected: $reason at ${now()}\n") } catch (e: Exception) { Log.w(TAG, "collecting session artifacts", e) } @@ -88,15 +94,10 @@ object SessionArtifacts { }?.toList() ?: return if (dirs.isEmpty()) return LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context)) - val workers = (Runtime.getRuntime().availableProcessors() / 2).coerceIn(1, 4) - val pool = java.util.concurrent.Executors.newFixedThreadPool(workers) { r -> - Thread({ android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND); r.run() }, "scrub-logs") - } - val done = try { - pool.invokeAll(dirs.map { dir -> java.util.concurrent.Callable { scrubAndMark(dir) } }) - .count { f -> try { f.get() } catch (e: Exception) { false } } - } finally { - pool.shutdown() + var done = 0 + for (dir in dirs) { + if (SessionState.running) break + if (scrubAndMark(dir, stopWhenSessionStarts = true)) done++ } val failed = dirs.size - done Log.i(TAG, "logs: scrubbed $done folders under r${LogRedactor.RULES_VERSION}" + @@ -114,35 +115,121 @@ object SessionArtifacts { private class Record(val dir: File) { val files = HashMap() var failed = false + var deferred = false } - private fun scrubFolder(dir: File, record: Record) { - dir.listFiles { f -> f.isFile && !f.name.startsWith(".") && f !in record.files }?.forEach { f -> - if (LogRedactor.isBinary(f)) return@forEach - // Too large to rewrite in memory: the folder must not be recorded as scrubbed. - if (!LogRedactor.isText(f)) { record.failed = true; return@forEach } - val done = scrubFile(dir, f) - if (done == null) record.failed = true else record.files[f] = done + private sealed class ScrubResult { + class Done(val scrubbed: Scrubbed) : ScrubResult() + object Failed : ScrubResult() + object Deferred : ScrubResult() + } + + private fun scrubFolder( + dir: File, + record: Record, + shouldStop: () -> Boolean, + beforeReplace: (File) -> Unit, + listFiles: (File) -> Array?, + ): Boolean { + val files = listFiles(dir)?.filter { f -> f.isFile && !f.name.startsWith(".") && f !in record.files } + if (files == null) { + record.failed = true + return true } + for (f in files) { + if (shouldStop()) return false + if (LogRedactor.isBinary(f)) continue + when (val result = scrubFile(dir, f, shouldStop, beforeReplace)) { + is ScrubResult.Done -> record.files[f] = result.scrubbed + ScrubResult.Failed -> record.failed = true + ScrubResult.Deferred -> { + record.failed = true + record.deferred = true + return false + } + } + } + return true } - - private fun scrubFile(dir: File, f: File): Scrubbed? { + private fun scrubFile( + dir: File, + f: File, + shouldStop: () -> Boolean, + beforeReplace: (File) -> Unit, + ): ScrubResult { val tmp = File(dir, ".${f.name}.scrub") return try { val before = Scrubbed(f.length(), f.lastModified()) - tmp.bufferedWriter().use { w -> LogRedactor.scrubTo(f, w) } - val scrubbed = tmp.readBytes() - if (scrubbed.contentEquals(f.readBytes())) { + val scrubbed = tmp.bufferedWriter().use { w -> LogRedactor.scrubTo(f, w, shouldStop) } + if (!scrubbed) { tmp.delete() - before.takeIf { f.length() == it.length && f.lastModified() == it.modified } - } else { - if (!tmp.renameTo(f)) { f.writeBytes(scrubbed); tmp.delete() } - Scrubbed(scrubbed.size.toLong(), f.lastModified()).takeIf { f.length() == it.length } + return ScrubResult.Deferred + } + val scrubbedLength = tmp.length() + when (sameContents(tmp, f, shouldStop)) { + null -> { + tmp.delete() + ScrubResult.Deferred + } + true -> { + tmp.delete() + before.takeIf { f.length() == it.length && f.lastModified() == it.modified } + ?.let { ScrubResult.Done(it) } ?: ScrubResult.Failed + } + false -> { + if (shouldStop()) { + tmp.delete() + return ScrubResult.Deferred + } + beforeReplace(f) + if (f.length() != before.length || f.lastModified() != before.modified) { + tmp.delete() + return ScrubResult.Failed + } + if (!tmp.renameTo(f)) { + tmp.delete() + return ScrubResult.Failed + } + Scrubbed(scrubbedLength, f.lastModified()).takeIf { f.length() == it.length } + ?.let { ScrubResult.Done(it) } ?: ScrubResult.Failed + } } } catch (e: Exception) { Log.w(TAG, "could not scrub ${f.name}", e) tmp.delete() - null + ScrubResult.Failed + } + } + + internal fun sameContents(a: File, b: File, shouldStop: () -> Boolean = { false }): Boolean? { + if (shouldStop()) return null + if (a.length() != b.length()) return false + fun readChunk(input: java.io.InputStream, buffer: ByteArray): Int? { + var count = 0 + while (count < buffer.size) { + if (shouldStop()) return null + val read = input.read(buffer, count, buffer.size - count) + if (shouldStop()) return null + if (read < 0) break + if (read == 0) continue + count += read + } + return count + } + return a.inputStream().buffered().use { left -> + b.inputStream().buffered().use { right -> + val leftBuffer = ByteArray(64 * 1024) + val rightBuffer = ByteArray(64 * 1024) + while (true) { + val leftCount = readChunk(left, leftBuffer) ?: return null + val rightCount = readChunk(right, rightBuffer) ?: return null + if (leftCount != rightCount) return false + if (leftCount == 0) break + if (shouldStop()) return null + for (i in 0 until leftCount) if (leftBuffer[i] != rightBuffer[i]) return false + } + true + } } } @@ -183,10 +270,44 @@ object SessionArtifacts { }.toSet() } - internal fun scrubAndMark(dir: File): Boolean = markScrubbed(scrubTree(Record(dir))) + internal fun scrubAndMark( + dir: File, + stopWhenSessionStarts: Boolean = false, + beforeReplace: (File) -> Unit = {}, + listFiles: (File) -> Array? = { it.listFiles() }, + sessionStarted: () -> Boolean = { SessionState.running }, + ): Boolean { + val shouldStop = { stopWhenSessionStarts && sessionStarted() } + val record = scrubTree( + Record(dir), + listFiles = listFiles, + beforeReplace = beforeReplace, + shouldStop = shouldStop, + ) + if (shouldStop()) { + record.failed = true + record.deferred = true + } + return markScrubbed(record) + } - private fun scrubTree(record: Record): Record { - record.dir.walkTopDown().filter { it.isDirectory }.forEach { scrubFolder(it, record) } + private fun scrubTree( + record: Record, + listFiles: (File) -> Array? = { it.listFiles() }, + beforeReplace: (File) -> Unit = {}, + shouldStop: () -> Boolean = { false }, + ): Record { + for (dir in record.dir.walkTopDown().filter { it.isDirectory }) { + if (shouldStop() || !scrubFolder(dir, record, shouldStop, beforeReplace, listFiles)) { + record.failed = true + record.deferred = true + break + } + } + if (shouldStop()) { + record.failed = true + record.deferred = true + } return record } @@ -205,6 +326,7 @@ object SessionArtifacts { private const val HEAD = 4096L private class Mark(val size: Long, val head: String) + private class CopyResult(val files: List, val failed: Boolean, val deferred: Boolean) fun markSteamLogs(dir: File, logs: File) { val lines = logs.listFiles { f -> f.isFile }?.mapNotNull { f -> @@ -240,23 +362,54 @@ object SessionArtifacts { .firstOrNull { m -> heads.getOrPut(minOf(m.size, HEAD)) { head(src, m.size) } == m.head }?.size ?: 0L } - private fun copySteamLogs(context: Context, dir: File, record: Record, steamArch: String? = null) { + private fun copySteamLogs( + context: Context, + dir: File, + record: Record, + steamArch: String? = null, + stopWhenSessionStarts: Boolean = false, + ) { val logs = File(steamArch?.let { SessionPrefs.steamRoot(context, it) } ?: SessionPrefs.activeSteamRoot(context), "logs") if (!logs.isDirectory) return val out = File(dir, "steam").apply { mkdirs() } - copySessionLogs(logs, dir, out).forEach { dst -> record.files[dst] = Scrubbed(dst.length(), dst.lastModified()) } + val result = copySessionLogsResult(logs, dir, out) { stopWhenSessionStarts && SessionState.running } + result.files.forEach { dst -> record.files[dst] = Scrubbed(dst.length(), dst.lastModified()) } + record.failed = record.failed || result.failed + record.deferred = record.deferred || result.deferred Log.i(TAG, "collected ${out.listFiles()?.size ?: 0} Steam log(s), scrubbed, into $out") } - internal fun copySessionLogs(logs: File, dir: File, out: File): List { + internal fun copySessionLogs( + logs: File, + dir: File, + out: File, + openWriter: (File) -> Writer = { it.bufferedWriter() }, + ): List = copySessionLogsResult(logs, dir, out, openWriter) { false }.files + + private fun copySessionLogsResult( + logs: File, + dir: File, + out: File, + openWriter: (File) -> Writer = { it.bufferedWriter() }, + shouldStop: () -> Boolean, + ): CopyResult { val marks = steamLogMarks(dir) val copied = ArrayList() - logs.listFiles { f -> f.isFile }?.forEach { src -> + var failed = false + var deferred = false + val sources = logs.listFiles { f -> f.isFile } ?: return CopyResult(copied, true, false) + for (src in sources) { + if (shouldStop()) { + failed = true + deferred = true + break + } val size = src.length() val from = marks?.let { startOf(src, size, it) } ?: 0L - if (marks != null && from == size || size - from >= MAX_STEAM_LOG) return@forEach + if (marks != null && from == size || size - from >= MAX_STEAM_LOG) continue + val dst = File(out, src.name) + val staging = File(out, ".${src.name}.copy") try { - val dst = File(out, src.name) src.inputStream().buffered().use { input -> var left = if (from > 0) from - 1 else 0L while (left > 0) { @@ -270,49 +423,183 @@ object SessionArtifacts { if (c < 0 || c == '\n'.code) break } } - dst.bufferedWriter().use { w -> - input.bufferedReader().forEachLine { line -> w.write(LogRedactor.redact(line)); w.newLine() } + val complete = openWriter(staging).use { w -> scrubSteamLog(input, w, shouldStop) } + if (!complete) { + staging.delete() + failed = true + deferred = true } } - copied.add(dst) + if (deferred) break + Files.move( + staging.toPath(), + dst.toPath(), + StandardCopyOption.ATOMIC_MOVE, + StandardCopyOption.REPLACE_EXISTING, + ) + copied += dst } catch (e: Exception) { + staging.delete() Log.w(TAG, "could not scrub ${src.name}", e) + failed = true } } - return copied + return CopyResult(copied, failed, deferred) + } + + private fun scrubSteamLog( + input: java.io.InputStream, + out: java.io.Writer, + shouldStop: () -> Boolean, + ): Boolean { + input.reader().use { reader -> + val chunk = CharArray(8192) + val line = StringBuilder(4096) + var oversized = false + var pendingContent = false + var pendingCarriageReturn = false + + fun emit() { + out.write(if (oversized) LogRedactor.OVERSIZED_LINE else LogRedactor.redact(line.toString())) + out.write("\n") + line.setLength(0) + oversized = false + pendingContent = false + } + + while (true) { + if (shouldStop()) return false + val count = reader.read(chunk) + if (count < 0) break + if (shouldStop()) return false + for (i in 0 until count) { + if (shouldStop()) return false + val char = chunk[i] + if (pendingCarriageReturn) { + emit() + pendingCarriageReturn = false + if (char == '\n') continue + } + when (char) { + '\r' -> pendingCarriageReturn = true + '\n' -> emit() + else -> { + pendingContent = true + if (!oversized) { + if (line.length < LogRedactor.MAX_LINE_LENGTH) line.append(char) + else { + line.setLength(0) + oversized = true + } + } + } + } + } + } + if (pendingCarriageReturn || pendingContent) { + if (shouldStop()) return false + emit() + } + } + return true } @Synchronized - fun finishAbandoned(context: Context) { + fun finishAbandoned(context: Context, beforeGuestStart: Boolean = false) { + val stopWhenSessionStarts = !beforeGuestStart val parent = LinuxRuntime.logDir(context) val abandoned = parent.listFiles { f -> SessionPaths.isSessionFolder(f) && !File(f, COMPLETE_MARKER).exists() && !inFlight(f) }?.sortedWith(SessionPaths.chronological) ?: return if (abandoned.isEmpty()) return val current = SessionPaths.current() + val latestPreviousSession = SessionPaths.sessionFolders(context).lastOrNull { it != current } LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context)) - abandoned.forEachIndexed { i, dir -> - if (dir == current) return@forEachIndexed - val newest = i == abandoned.lastIndex + for (dir in abandoned) { + if (stopWhenSessionStarts && SessionState.running) break + if (dir == current) continue + if (beforeGuestStart && dir != latestPreviousSession) continue + val newest = dir == latestPreviousSession try { - File(dir, "ended-without-teardown.txt").writeText( - "This session's process ended without running its own teardown - killed by\n" + - "Android, a native crash, or the device going down - so the files below were\n" + - "gathered when the app next started, at ${now()}.\n" + - "The logs written during the session (session.log, app.log, wayland.log,\n" + - "audio.log, device.txt) were on disk already and are as they were left.\n" + - (if (newest) "" else "Steam's logs are not included: a later session has overwritten them.\n") + - "crash.log holds Android's crash buffer as of the next app start - if this\n" + - "session died of a crash, the entry is in there unless the device rebooted.\n" - ) + val recoveryNote = File(dir, "ended-without-teardown.txt") + val runtimeCaptured = File(dir, RECOVERY_RUNTIME_CAPTURED_MARKER) + val runtimeExpired = File(dir, RECOVERY_RUNTIME_EXPIRED_MARKER) + val recoveryPreviouslyAttempted = recoveryNote.exists() + val recoveryAttempted = recoveryPreviouslyAttempted && + (runtimeCaptured.exists() || runtimeExpired.exists() || !beforeGuestStart) + if (!recoveryAttempted) { + recoveryNote.writeText( + "This session's process ended without running its own teardown - killed by\n" + + "Android, a native crash, or the device going down - so the files below were\n" + + "gathered when the app next started, at ${now()}.\n" + + "The logs written during the session (session.log, app.log, wayland.log,\n" + + "audio.log, device.txt) were on disk already and are as they were left.\n" + + (if (newest) "" else "Steam's logs are not included: a later session has overwritten them.\n") + + "crash.log holds Android's crash buffer as of the next app start - if this\n" + + "session died of a crash, the entry is in there unless the device rebooted.\n" + ) + } + if (recoveryPreviouslyAttempted && !runtimeCaptured.exists() && + (runtimeExpired.exists() || !beforeGuestStart) && + !recoveryNote.readText().contains("runtime capture did not finish")) { + recoveryNote.appendText( + "Steam's logs and VAC evidence are not included: runtime capture did not finish " + + "before its evidence expired.\n" + ) + } + if (recoveryPreviouslyAttempted && !runtimeCaptured.exists() && !beforeGuestStart) { + runtimeExpired.writeText("runtime evidence no longer belongs to this session, at ${now()}\n") + } val record = Record(dir) - if (newest) { - copySteamLogs(context, dir, record, recordedClient(dir)) - VacDiagnostics.collect(context, dir) + if (newest && !recoveryAttempted) { + copySteamLogs( + context, + dir, + record, + steamArch = recordedClient(dir), + stopWhenSessionStarts = stopWhenSessionStarts, + ) + if (!record.deferred && (!stopWhenSessionStarts || !SessionState.running)) { + if (!record.failed && VacDiagnostics.collect(context, dir)) { + try { + runtimeCaptured.writeText("collected at ${now()}\n") + } catch (e: Exception) { + record.failed = true + if (beforeGuestStart) { + runtimeExpired.writeText("runtime capture marker failed, at ${now()}\n") + } + Log.w(TAG, "could not mark runtime capture for $dir", e) + } + } else { + record.failed = true + if (beforeGuestStart) { + runtimeExpired.writeText("runtime capture failed, at ${now()}\n") + } + } + } + } + if (record.deferred || stopWhenSessionStarts && SessionState.running) { + record.failed = true + record.deferred = true + markScrubbed(record) + break + } + val crashLog = File(dir, "crash.log") + if (!crashLog.exists()) { + SessionLogCapture.dumpCrashBuffer(crashLog) + } + if (stopWhenSessionStarts && SessionState.running) { + record.failed = true + record.deferred = true + markScrubbed(record) + break } - SessionLogCapture.dumpCrashBuffer(File(dir, "crash.log")) SessionEvents.record("session.artifacts_recovered", mapOf("newest" to newest), dir) - markScrubbed(scrubTree(record)) + if (beforeGuestStart) return + val scrubbed = scrubTree(record) { stopWhenSessionStarts && SessionState.running } + val marked = markScrubbed(scrubbed) + if (scrubbed.deferred) break + if (!marked) continue File(dir, COMPLETE_MARKER).writeText("collected: late, at next app start, ${now()}\n") Log.i(TAG, "finished the abandoned session folder $dir") } catch (e: Exception) { diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionLaunchFailure.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionLaunchFailure.kt new file mode 100644 index 0000000000..22d8b952cd --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionLaunchFailure.kt @@ -0,0 +1,42 @@ +package com.droiddeck.launcher.session + +enum class SessionLaunchFailure { + STEAM_ILLEGAL_INSTRUCTION, + VULKAN_DEVICE_MISSING; + + companion object { + private val ANSI = Regex("\u001b\\[[0-?]*[ -/]*[@-~]") + private val STEAM_EXIT = Regex("== steam exited rc=(\\d+)") + + fun find(lines: Sequence): SessionLaunchFailure? { + var steamStarted = false + var illegalInstruction = false + var missingDevice = false + lines.forEach { raw -> + val line = ANSI.replace(raw, "").trim() + when { + line.startsWith("== droiddeck-session ") -> { + steamStarted = false + illegalInstruction = false + missingDevice = false + } + line.startsWith("== STEP ") && line.contains("starting the Steam client") -> { + steamStarted = true + illegalInstruction = false + } + STEAM_EXIT.matches(line) && steamStarted -> + illegalInstruction = STEAM_EXIT.matchEntire(line)?.groupValues?.get(1) == "132" + line.startsWith("[gamescope]") && line.contains("vulkan:") -> when { + line.contains("failed to find physical device") -> missingDevice = true + line.contains("selecting physical device") -> missingDevice = false + } + } + } + return when { + illegalInstruction -> STEAM_ILLEGAL_INSTRUCTION + missingDevice -> VULKAN_DEVICE_MISSING + else -> null + } + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionPaths.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionPaths.kt index e67092c1d0..f73609f442 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPaths.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPaths.kt @@ -44,6 +44,10 @@ object SessionPaths { fun current(): File? = dir + /** Whether the current session folder will survive teardown. No session means the next one can retain logs. */ + fun currentSessionLogsRetained(context: Context): Boolean = + dir?.let { it.parentFile == SessionFiles.logDirectory(context) } ?: true + fun lastEnded(): File? = ended?.takeIf { it.isDirectory } @Synchronized diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt index 592bf42cf9..a98dabcead 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -602,6 +602,8 @@ object SessionPrefs { } fun mangoapp(context: Context): Boolean = prefs(context).getBoolean("mangoapp", true) + fun vsyncThread(context: Context): Boolean = prefs(context).getBoolean("vsyncThread", true) + fun renderOnCommit(context: Context): Boolean = prefs(context).getBoolean("renderOnCommit", true) fun setMangoapp(context: Context, on: Boolean) { prefs(context).edit().putBoolean("mangoapp", on).apply() } fun zinkLazy(context: Context): Boolean = prefs(context).getBoolean("zinkLazy", true) @@ -629,8 +631,74 @@ object SessionPrefs { fun logsEnabled(context: Context): Boolean = prefs(context).getBoolean("logs", true) - fun setLogsEnabled(context: Context, on: Boolean) { - prefs(context).edit().putBoolean("logs", on).apply() + fun setLogsEnabled(context: Context, on: Boolean): Boolean = synchronized(GameEnvironmentStore) { + setLogPreference( + context, + key = "logs", + oldValue = logsEnabled(context), + newValue = on, + newEffective = on && gameDebugLogsEnabled(context) && SessionPaths.currentSessionLogsRetained(context), + ) + } + + /** Extra Proton, Wine and graphics diagnostics for the next game launch; off unless chosen. */ + fun gameDebugLogsEnabled(context: Context): Boolean = + prefs(context).getBoolean("gameDebugLogsEnabled", false) + + fun setGameDebugLogsEnabled(context: Context, on: Boolean): Boolean = synchronized(GameEnvironmentStore) { + setLogPreference( + context, + key = "gameDebugLogsEnabled", + oldValue = gameDebugLogsEnabled(context), + newValue = on, + newEffective = logsEnabled(context) && on && SessionPaths.currentSessionLogsRetained(context), + ) + } + + private fun setLogPreference( + context: Context, + key: String, + oldValue: Boolean, + newValue: Boolean, + newEffective: Boolean, + ): Boolean { + if (oldValue == newValue) return true + val saved = prefs(context) + val oldEffective = logsEnabled(context) && gameDebugLogsEnabled(context) && + SessionPaths.currentSessionLogsRetained(context) + fun publish(value: Boolean) = GameEnvironmentStore.publish(context, gameDebugLogsOverride = value) + if (oldEffective == newEffective) { + if (saved.edit().putBoolean(key, newValue).commit()) return true + saved.edit().putBoolean(key, oldValue).commit() + return false + } + if (oldEffective && !newEffective) { + try { + publish(false) + } catch (e: Exception) { + android.util.Log.e("GameEnvironment", "Could not disable game diagnostics", e) + return false + } + if (saved.edit().putBoolean(key, newValue).commit()) return true + saved.edit().putBoolean(key, oldValue).commit() + runCatching { publish(oldEffective) } + .onFailure { android.util.Log.e("GameEnvironment", "Could not restore game diagnostics", it) } + return false + } + if (!saved.edit().putBoolean(key, newValue).commit()) { + saved.edit().putBoolean(key, oldValue).commit() + return false + } + return try { + publish(newEffective) + true + } catch (e: Exception) { + saved.edit().putBoolean(key, oldValue).commit() + runCatching { publish(oldEffective) } + .onFailure { android.util.Log.e("GameEnvironment", "Could not restore game diagnostics", it) } + android.util.Log.e("GameEnvironment", "Could not update game diagnostics", e) + false + } } fun battleNetNoSteamSet(context: Context): Boolean = prefs(context).getBoolean("battleNetNoSteamSet", false) diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt index 025332da3b..101fb82a15 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt @@ -91,6 +91,7 @@ class SessionService : Service() { private var screenOn = true private var sessionDisplayId = Display.DEFAULT_DISPLAY private var manualPauseRequested = false + private var manualHold = false private var steamSleepToken: String? = null private var nativeSleepToken: String? = null private var nativeSleepReady = false @@ -274,7 +275,11 @@ class SessionService : Service() { val hold = intent?.getBooleanExtra(EXTRA_HOLD, false) == true if (hold == signInHold) return START_NOT_STICKY signInHold = hold - if (hold) manualPauseRequested = false + if (hold) { + manualPauseRequested = false + manualHold = false + SessionState.manualPause = false + } suspendAttemptFailed = false updateSuspendPolicy() return START_NOT_STICKY @@ -304,6 +309,14 @@ class SessionService : Service() { updateSuspendPolicy() return START_NOT_STICKY } + ACTION_PAUSE_NOW -> { + if (!SessionState.running || SessionState.suspended || signInHold) return START_NOT_STICKY + manualHold = true + SessionState.manualPause = true + suspendAttemptFailed = false + updateSuspendPolicy() + return START_NOT_STICKY + } ACTION_RESUME -> { resumeSession() return START_NOT_STICKY @@ -346,6 +359,8 @@ class SessionService : Service() { SessionState.resumeRequested = false SessionState.resuming = false SessionState.resumeFailed = false + manualHold = false + SessionState.manualPause = false SessionState.pipActive = false pipTask = false SessionState.program = intent?.getStringExtra(EXTRA_PROGRAM) @@ -385,10 +400,10 @@ class SessionService : Service() { } private fun collectSessionArtifacts(dir: File, steamArch: String?) { + SessionLogCapture.stopFor(dir) try { SessionArtifacts.collect(this, dir, "session stopped", steamArch) } finally { - SessionLogCapture.stopFor(dir) SessionPaths.release(this, dir) } } @@ -461,13 +476,20 @@ class SessionService : Service() { SessionFiles.stage(this, root, startsSession = true) // Earlier sessions' reports still read the Steam logs and VAC marker this session replaces. SessionArtifacts.awaitCollections() - SessionArtifacts.finishAbandoned(this) + SessionArtifacts.finishAbandoned(this, beforeGuestStart = true) VacDiagnostics.arm(this) com.droiddeck.launcher.agent.AgentGuest.reset(this) com.droiddeck.launcher.stores.gog.GogComet.begin() com.droiddeck.launcher.stores.StoreLaunchRequests.start(this) val sessionDir = openSessionFolder() + try { + GameEnvironmentStore.publish(this) + } catch (e: Exception) { + Log.e(TAG, "could not publish the game environment", e) + stopSession(-1) + return + } val sessionLog = File(sessionDir, "session.log") val prootLine = "== proot: ${LinuxRuntime.prootBinary(this).path} (${LinuxRuntime.prootSource(this)})" Log.i(TAG, prootLine) @@ -1332,6 +1354,8 @@ class SessionService : Service() { if (panelVisible) activityVisible = true screenOn = readScreenOn() manualPauseRequested = false + manualHold = false + SessionState.manualPause = false suspendDownloadNow = false if (steamSleepToken == null && (nativeSleepToken == null || nativeSleepFallback || nativeSleepIdle)) requestSteamWake() completeNativeSleep() @@ -1539,12 +1563,12 @@ class SessionService : Service() { manualPauseRequested = false } val controller = suspendController ?: return - if (downloadsBlockingSuspend) acquireLocks() - val steamPause = SessionState.mode == MODE_STEAM && !downloadsBlockingSuspend && when (suspendPolicy) { + if (downloadsBlockingSuspend && !manualHold) acquireLocks() + val steamPause = SessionState.mode == MODE_STEAM && (manualHold || !downloadsBlockingSuspend && when (suspendPolicy) { SessionPrefs.SUSPEND_AUTO, SessionPrefs.SUSPEND_NATIVE -> hidden SessionPrefs.SUSPEND_MANUAL -> manualPauseRequested else -> false - } + }) if (!steamPause) { completeNativeSleep() } else if (nativeSleepToken == null && steamSleepToken == null && @@ -1552,12 +1576,15 @@ class SessionService : Service() { prepareNativeSleep() } val prepared = SessionState.mode != MODE_STEAM || nativeSleepReady - val shouldSuspend = steamSleepToken != null || when (suspendPolicy) { + val shouldSuspend = steamSleepToken != null || (manualHold && prepared) || when (suspendPolicy) { SessionPrefs.SUSPEND_AUTO -> hidden && prepared && !downloadsBlockingSuspend SessionPrefs.SUSPEND_NATIVE -> hidden && nativeSleepReady && !downloadsBlockingSuspend SessionPrefs.SUSPEND_MANUAL -> manualPauseRequested && prepared && !downloadsBlockingSuspend else -> false } + // A frozen game never sends the stop for a held rumble, so the keepalive would run on. + val quietRumble = !screenOn || shouldSuspend || SessionState.suspended + components.forEach { (it as? RumbleComponent)?.quiet(quietRumble) } if (freezePending && !shouldSuspend && !freezeCancelled) { freezeCancelled = true controller.cancelFreeze() @@ -1597,6 +1624,8 @@ class SessionService : Service() { SessionEvents.record("session.suspend_cancelled") } else { suspendAttemptFailed = true + manualHold = false + SessionState.manualPause = false Log.w(TAG, "could not confirm that the session stopped") } } @@ -1645,7 +1674,7 @@ class SessionService : Service() { } private fun resumeSteamSleepOnReturn() { - if (suspendPolicy in setOf(SessionPrefs.SUSPEND_AUTO, SessionPrefs.SUSPEND_NATIVE) && hasVisibleSurface) { + if (!manualHold && suspendPolicy in setOf(SessionPrefs.SUSPEND_AUTO, SessionPrefs.SUSPEND_NATIVE) && hasVisibleSurface) { if (steamSleepToken == null && (nativeSleepToken == null || nativeSleepFallback || nativeSleepIdle)) requestSteamWake() completeNativeSleep() completeSteamSleep() @@ -1703,42 +1732,48 @@ class SessionService : Service() { }.onFailure { Log.w(TAG, "could not request Steam wake", it) } } - private fun finishSessionStop(status: Int, stoppedGen: Int) { + private fun finishSessionStop(status: Int, stoppedGen: Int, afterStopped: () -> Unit = {}) { mainHandler.post { - if (stoppedGen != sessionGen || SessionState.running) { - Log.i(TAG, "session $stoppedGen finished stopping after a new one started") - return@post + try { + if (stoppedGen != sessionGen || SessionState.running) { + Log.i(TAG, "session $stoppedGen finished stopping after a new one started") + return@post + } + SessionState.suspended = false + SessionState.resumeRequested = false + SessionState.resuming = false + SessionState.resumeFailed = false + manualHold = false + SessionState.manualPause = false + SessionState.pipActive = false + pipTask = false + SessionState.guestPid = -1 + com.droiddeck.launcher.agent.AgentGuest.stop() + com.droiddeck.launcher.stores.StoreLaunchRequests.stop() + Thread({ com.droiddeck.launcher.stores.CloudSaves.uploadAllDirty(applicationContext, "session-end", running = false) }, "cloud-session-end").start() + runCatching { com.droiddeck.launcher.agent.AgentEnv.endSession(this) } + .onFailure { Log.w(TAG, "clearing the agent's session environment", it) } + releaseLocks() + MemoryLog.stop() + com.droiddeck.launcher.core.BackgroundAppLimit.restoreAsync(applicationContext) + if (status == 0) { + SessionEvents.transition(SessionPhase.IDLE, "session.stopped", mapOf("status" to status)) + } else { + val code = SessionState.failureCode ?: "GUEST_EXIT" + val message = SessionState.failureMessage ?: "Session guest exited with status $status" + val failureStatus = SessionState.failureStatus ?: status + SessionEvents.fail(code, message, failureStatus) + } + SessionState.steamVr = false + com.droiddeck.launcher.glasses.Glasses.cancelSteamVrStart() + com.droiddeck.launcher.glasses.Glasses.setVrActive(false) + com.droiddeck.launcher.glasses.Glasses.set3dForVr(false) + SessionState.notifyEnded(status) + stopForeground(STOP_FOREGROUND_REMOVE) + stopSelf() + } finally { + afterStopped() } - SessionState.suspended = false - SessionState.resumeRequested = false - SessionState.resuming = false - SessionState.resumeFailed = false - SessionState.pipActive = false - pipTask = false - SessionState.guestPid = -1 - com.droiddeck.launcher.agent.AgentGuest.stop() - com.droiddeck.launcher.stores.StoreLaunchRequests.stop() - Thread({ com.droiddeck.launcher.stores.CloudSaves.uploadAllDirty(applicationContext, "session-end", running = false) }, "cloud-session-end").start() - runCatching { com.droiddeck.launcher.agent.AgentEnv.endSession(this) } - .onFailure { Log.w(TAG, "clearing the agent's session environment", it) } - releaseLocks() - MemoryLog.stop() - com.droiddeck.launcher.core.BackgroundAppLimit.restoreAsync(applicationContext) - if (status == 0) { - SessionEvents.transition(SessionPhase.IDLE, "session.stopped", mapOf("status" to status)) - } else { - val code = SessionState.failureCode ?: "GUEST_EXIT" - val message = SessionState.failureMessage ?: "Session guest exited with status $status" - val failureStatus = SessionState.failureStatus ?: status - SessionEvents.fail(code, message, failureStatus) - } - SessionState.steamVr = false - com.droiddeck.launcher.glasses.Glasses.cancelSteamVrStart() - com.droiddeck.launcher.glasses.Glasses.setVrActive(false) - com.droiddeck.launcher.glasses.Glasses.set3dForVr(false) - SessionState.notifyEnded(status) - stopForeground(STOP_FOREGROUND_REMOVE) - stopSelf() } } @@ -1769,7 +1804,9 @@ class SessionService : Service() { SessionEvents.record("guest.exited", mapOf("status" to status)) SessionEvents.transition(SessionPhase.STOPPING, "session.stopping", mapOf("status" to status)) SessionState.running = false - SessionPaths.take() to SessionState.steamClientArch + val ended = SessionPaths.take() + if (ended != null) SessionArtifacts.collectionStarted(ended) + ended to SessionState.steamClientArch } SessionState.micAvailable = false SessionState.micEnabled = false @@ -1798,8 +1835,6 @@ class SessionService : Service() { suspendController = null if (ended != null) { VacDiagnostics.snapshot(this, ended) - SessionArtifacts.collectionStarted(ended) - Thread({ collectSessionArtifacts(ended, endedArch) }, "session-collect").start() } components.reversed().forEach { try { @@ -1809,6 +1844,9 @@ class SessionService : Service() { } } components.clear() + val collectEnded = { + if (ended != null) Thread({ collectSessionArtifacts(ended, endedArch) }, "session-collect").start() + } FakeInputWriter.releaseAllRingSlots() com.droiddeck.launcher.input.SteamTouchDevice.release() val steamClientMayRun = SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP @@ -1820,13 +1858,13 @@ class SessionService : Service() { auxiliary.forEach { (pid, started) -> teardown(pid, started) } if (prootPid > 1) teardown(prootPid) killGuestLeftovers() - finishSessionStop(status, stoppedGen) + finishSessionStop(status, stoppedGen, collectEnded) if (launcherEnded) importLauncherGames() }, "session-teardown").start() } else { Thread({ com.droiddeck.launcher.stores.gog.GogComet.end(stoppedSession) - finishSessionStop(status, stoppedGen) + finishSessionStop(status, stoppedGen, collectEnded) if (launcherEnded) importLauncherGames() }, "gog-session-stop").start() } @@ -2065,6 +2103,7 @@ class SessionService : Service() { const val ACTION_STOP = "com.droiddeck.launcher.STOP_SESSION" const val ACTION_RESUME = "com.droiddeck.launcher.RESUME_SESSION" const val ACTION_SUSPEND_NOW = "com.droiddeck.launcher.SUSPEND_NOW" + private const val ACTION_PAUSE_NOW = "com.droiddeck.launcher.PAUSE_NOW" private const val ACTION_PIP_BEGIN = "com.droiddeck.launcher.PIP_BEGIN" const val ACTION_LAUNCH_GAME = "com.droiddeck.launcher.LAUNCH_STEAM_GAME" const val ACTION_HOME_GUIDE = "com.droiddeck.launcher.HOME_GUIDE" @@ -2184,6 +2223,10 @@ class SessionService : Service() { context.startService(Intent(context, SessionService::class.java).setAction(ACTION_SIGN_IN_HOLD).putExtra(EXTRA_HOLD, hold)) } + fun pause(context: Context) { + context.startService(Intent(context, SessionService::class.java).setAction(ACTION_PAUSE_NOW)) + } + fun resume(context: Context) { if (!SessionState.running) return if (SessionState.suspended) SessionState.resumeRequested = true diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt index 52544f2fc0..5f3ae0154a 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt @@ -53,6 +53,7 @@ object SessionState { var resuming by mutableStateOf(false) var resumeFailures by mutableIntStateOf(0) var resumeFailed by mutableStateOf(false) + var manualPause by mutableStateOf(false) @Volatile var pipActive = false @Volatile var program: String? = null diff --git a/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt b/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt index e67f1c08ee..0c5620d9ea 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt @@ -22,7 +22,7 @@ object SettingsReset { "tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "ramCapMb", "vramCapMb", "zramClient", "directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus", "noXalia", "fastSync", "fsyncFirst", "syncFallback", "prootNoSeccomp", "prootFastPath", "cursorComposite", - "guestHostname", "fexPreset", "forceSsbs", "logs", "storageDiagnostics", + "guestHostname", "fexPreset", "forceSsbs", "logs", "gameDebugLogsEnabled", "storageDiagnostics", "upscaler", "upscaleSharpness", "screenEffects", "textureAnisotropy", "textureLodBias", "steamDownloadsInBackground", "steam_offline", "bootMovie", "bootMovieSound", "bootMovieVolume", "bootMovieSeconds", "bootMovieApplyNext", "bootMovieSteamSeen", @@ -38,6 +38,7 @@ object SettingsReset { internal fun isSessionSetting(key: String) = key in SESSION_KEYS || SESSION_PREFIXES.any { key.startsWith(it) } fun resetAll(context: Context, gameProfiles: Boolean, gameScopes: Collection = emptyList()): Boolean { + if (!SessionPrefs.setGameDebugLogsEnabled(context, false)) return false var ok = true val session = context.getSharedPreferences("session", Context.MODE_PRIVATE) session.edit().apply { session.all.keys.filter { isSessionSetting(it) }.forEach { remove(it) } }.commit() diff --git a/app/src/main/java/com/droiddeck/launcher/session/VacDiagnostics.kt b/app/src/main/java/com/droiddeck/launcher/session/VacDiagnostics.kt index 5681882097..2f0d03c280 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/VacDiagnostics.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/VacDiagnostics.kt @@ -68,13 +68,13 @@ object VacDiagnostics { } } - fun collect(context: Context, dir: File) { + fun collect(context: Context, dir: File): Boolean { val root = LinuxRuntime.rootDir(context) val kept = File(dir, SNAPSHOT_MARKER).takeIf { it.isFile } val marker = kept ?: File(root, MARKER) val launchList = if (kept != null) File(dir, SNAPSHOT_LAUNCHES) else File(root, LAUNCHES) - if (!marker.isFile) return - try { + if (!marker.isFile) return true + return try { val armed = marker.readLines().map { it.trim() } val since = (armed.getOrNull(0)?.toLongOrNull() ?: 0L) * 1000 - 5_000 val arch = armed.getOrNull(1)?.takeIf { it.isNotEmpty() } ?: SessionPrefs.steamClientArch(context) @@ -125,8 +125,10 @@ object VacDiagnostics { File(dir, SNAPSHOT_MARKER).delete() File(dir, SNAPSHOT_LAUNCHES).delete() Log.i(TAG, "VAC diagnostics: ${consoles.size} console log(s), ${steamHits.size} client VAC line(s), into $dir") + true } catch (e: Exception) { Log.w(TAG, "collecting VAC diagnostics", e) + false } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AndroidAppsPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/AndroidAppsPage.kt new file mode 100644 index 0000000000..fdd0fdd8cb --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/AndroidAppsPage.kt @@ -0,0 +1,959 @@ +package com.droiddeck.launcher.ui + +import android.app.Activity +import android.content.Context +import android.content.ContextWrapper +import android.view.KeyEvent +import androidx.activity.compose.BackHandler +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.core.Spring +import androidx.compose.animation.core.animateFloatAsState +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.animation.scaleIn +import androidx.compose.animation.scaleOut +import androidx.compose.foundation.ExperimentalFoundationApi +import androidx.compose.foundation.Image +import androidx.compose.foundation.LocalIndication +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.combinedClickable +import androidx.compose.foundation.focusable +import androidx.compose.foundation.gestures.awaitEachGesture +import androidx.compose.foundation.gestures.awaitFirstDown +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.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.aspectRatio +import androidx.compose.foundation.layout.fillMaxHeight +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.imePadding +import androidx.compose.foundation.layout.offset +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.lazy.grid.GridCells +import androidx.compose.foundation.lazy.grid.GridItemSpan +import androidx.compose.foundation.lazy.grid.LazyGridState +import androidx.compose.foundation.lazy.grid.LazyVerticalGrid +import androidx.compose.foundation.lazy.grid.items +import androidx.compose.foundation.lazy.grid.rememberLazyGridState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.Edit +import androidx.compose.material.icons.filled.FilterAlt +import androidx.compose.material.icons.filled.Sort +import androidx.compose.material.icons.filled.Widgets +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.derivedStateOf +import androidx.compose.runtime.getValue +import androidx.compose.runtime.key +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +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.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.asImageBitmap +import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.input.key.onPreviewKeyEvent +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.layout.boundsInRoot +import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.IntOffset +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.compose.ui.viewinterop.AndroidView +import androidx.compose.ui.zIndex +import com.droiddeck.launcher.HomeApp +import com.droiddeck.launcher.HomeFolders +import com.droiddeck.launcher.HomeHidden +import com.droiddeck.launcher.HomePins +import android.content.pm.ShortcutInfo +import android.graphics.Bitmap +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import com.droiddeck.launcher.HomeWidgets +import com.droiddeck.launcher.R +import kotlinx.coroutines.launch +import kotlin.math.roundToInt + +private sealed interface AppEntry : AppEntryKey { + val key: String + + class App(val app: HomeApp.LaunchableApp) : AppEntry { + override val label get() = app.label + override val key get() = "app:" + app.key + override val installedAt get() = app.installedAt + override val updatedAt get() = app.updatedAt + } + + class Folder(val folder: HomeFolders.Folder, val apps: List) : AppEntry { + override val label get() = folder.name + override val key get() = "folder:" + folder.id + override val installedAt get() = apps.maxOf { it.installedAt } + override val updatedAt get() = apps.maxOf { it.updatedAt } + } + + class Shortcut(val pinned: HomePins.Pinned) : AppEntry { + override val label get() = pinned.label + override val key get() = pinned.key + override val installedAt get() = 0L + override val updatedAt get() = 0L + } +} + +private fun indexLetter(label: String): String { + val c = label.trim().firstOrNull()?.uppercaseChar() ?: return "#" + return if (c in 'A'..'Z') c.toString() else if (c.isLetter()) c.toString() else "#" +} + +private fun searchRank(label: String, q: String): Int? { + if (label.startsWith(q, ignoreCase = true)) return 0 + if (label.split(' ', '-', '_', '.').any { it.startsWith(q, ignoreCase = true) }) return 1 + if (label.contains(q, ignoreCase = true)) return 2 + return null +} + +internal fun Context.findActivity(): Activity? { + var c: Context? = this + while (c is ContextWrapper) { + if (c is Activity) return c + c = c.baseContext + } + return null +} + +private fun Modifier.menuKey(onMenu: () -> Unit): Modifier = onPreviewKeyEvent { event -> + val k = event.nativeKeyEvent + if (k.keyCode != KeyEvent.KEYCODE_BUTTON_Y && k.keyCode != KeyEvent.KEYCODE_MENU) false + else { + if (k.action == KeyEvent.ACTION_DOWN && k.repeatCount == 0) onMenu() + true + } +} + +internal object AppsView { + const val ALL = "all" + const val GAMES = "games" + const val DOWNLOADED = "downloaded" + const val SYSTEM = "system" + const val HIDDEN = "hidden" + val FILTERS = listOf(ALL, GAMES, DOWNLOADED, SYSTEM, HIDDEN) + const val NAME_ASC = "nameAsc" + const val NAME_DESC = "nameDesc" + const val INSTALLED = "installed" + const val UPDATED = "updated" + val SORTS = listOf(NAME_ASC, NAME_DESC, INSTALLED, UPDATED) + + var filter by mutableStateOf(ALL) + var sort by mutableStateOf(NAME_ASC) + private var loaded = false + + private fun prefs(context: Context) = context.getSharedPreferences("home_launcher", Context.MODE_PRIVATE) + + fun load(context: Context) { + if (loaded) return + loaded = true + val p = prefs(context) + filter = p.getString("filter", ALL)?.takeIf { it in FILTERS } ?: ALL + sort = p.getString("sort", NAME_ASC)?.takeIf { it in SORTS } ?: NAME_ASC + } + + fun setFilter(context: Context, value: String) { + filter = value + prefs(context).edit().putString("filter", value).apply() + } + + fun setSort(context: Context, value: String) { + sort = value + prefs(context).edit().putString("sort", value).apply() + } + + fun keeps(app: HomeApp.LaunchableApp): Boolean { + val hidden = app.key in HomeHidden.keys + return when (filter) { + HIDDEN -> hidden + GAMES -> !hidden && app.game + DOWNLOADED -> !hidden && !app.system + SYSTEM -> !hidden && app.system + else -> !hidden + } + } + + fun comparator(): Comparator = when (sort) { + NAME_DESC -> compareBy(String.CASE_INSENSITIVE_ORDER) { it.label }.reversed() + INSTALLED -> compareByDescending { it.installedAt }.thenBy(String.CASE_INSENSITIVE_ORDER) { it.label } + UPDATED -> compareByDescending { it.updatedAt }.thenBy(String.CASE_INSENSITIVE_ORDER) { it.label } + else -> compareBy(String.CASE_INSENSITIVE_ORDER) { it.label } + } +} + +internal interface AppEntryKey { + val label: String + val installedAt: Long + val updatedAt: Long +} + +@OptIn(ExperimentalLayoutApi::class) +@Composable +internal fun AndroidAppsPage(s: FrontEndState, modifier: Modifier, onLaunch: (HomeApp.LaunchableApp) -> Unit) { + val ctx = LocalContext.current + remember { HomeFolders.load(ctx); HomeWidgets.load(ctx); HomeHidden.load(ctx); AppsView.load(ctx); true } + val colors = MaterialTheme.colorScheme + val narrow = LocalNarrowPane.current + val padH = if (narrow) 16.dp else 22.dp + var query by rememberSaveable { mutableStateOf("") } + var openFolder by rememberSaveable { mutableStateOf(null) } + var renameOnOpen by rememberSaveable { mutableStateOf(false) } + var picking by rememberSaveable { mutableStateOf(false) } + val folders = HomeFolders.folders + val byKey = remember(s.androidApps) { s.androidApps.associateBy { it.key } } + val byPkg = remember(s.androidApps) { s.androidApps.filterNot { it.work }.groupBy { it.packageName }.mapNotNull { (pkg, apps) -> apps.singleOrNull()?.let { pkg to it } }.toMap() } + LaunchedEffect(byPkg) { if (byPkg.isNotEmpty()) HomeFolders.migrateMembers(ctx) { byPkg[it]?.key } } + val member: (String) -> HomeApp.LaunchableApp? = { byKey[it] ?: byPkg[it] } + val pins = HomePins.pinned + val hidden = HomeHidden.keys + val q = query.trim() + val filter = AppsView.filter + val sort = AppsView.sort + val entries: List = remember(s.androidApps, folders, q, filter, sort, pins, hidden) { + val kept = s.androidApps.filter { AppsView.keeps(it) } + val shortcuts = if (filter == AppsView.ALL) pins.map { AppEntry.Shortcut(it) } else emptyList() + if (q.isNotEmpty()) { + (kept.map { AppEntry.App(it) } + shortcuts).mapNotNull { e -> searchRank(e.label, q)?.let { it to e } } + .sortedWith(compareBy> { it.first }.thenBy(String.CASE_INSENSITIVE_ORDER) { it.second.label }) + .map { it.second } + } else if (filter != AppsView.ALL) { + kept.map { AppEntry.App(it) }.sortedWith(AppsView.comparator()) + } else { + val folderEntries = folders.mapNotNull { f -> + val apps = f.apps.mapNotNull(member).filter { it.key !in hidden }.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.label }) + if (apps.isEmpty()) null else AppEntry.Folder(f, apps) + } + val grouped = folderEntries.flatMap { f -> f.apps.map { it.key } }.toSet() + (folderEntries + kept.filter { it.key !in grouped }.map { AppEntry.App(it) } + shortcuts).sortedWith(AppsView.comparator()) + } + } + val grid = rememberLazyGridState() + LaunchedEffect(q, filter, sort) { grid.scrollToItem(0) } + val widgetsShown = q.isEmpty() && filter == AppsView.ALL && HomeWidgets.widgets.isNotEmpty() + val leadItems = if (widgetsShown) 1 else 0 + val byName = sort == AppsView.NAME_ASC || sort == AppsView.NAME_DESC + val newFolder: (HomeApp.LaunchableApp) -> Unit = { app -> + val f = HomeFolders.create(ctx, ctx.getString(R.string.apps_folder_default), app.key) + renameOnOpen = true + openFolder = f.id + } + + Box(modifier) { + Column(Modifier.fillMaxSize().imePadding()) { + Box(Modifier.fillMaxWidth().padding(start = padH, end = padH, top = if (narrow) 8.dp else 12.dp)) { + ModeHeader( + stringResource(R.string.content_android_apps), query, { query = it }, + placeholder = stringResource(R.string.apps_search_hint), + clearSearchFocus = openFolder != null || picking, + lead = { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.padding(start = 2.dp, end = 4.dp)) { + Text(stringResource(R.string.content_android_apps), fontSize = if (narrow) 20.sp else 24.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1) + val shownCount = s.androidApps.count { AppsView.keeps(it) } + if (filter == AppsView.ALL) pins.size else 0 + Text(androidx.compose.ui.res.pluralStringResource(R.plurals.apps_count, shownCount, shownCount), fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1) + } + }, + ) { + AppsFilterButton() + AppsSortButton() + HeaderIconButton(stringResource(R.string.apps_add_widget), Icons.Filled.Widgets, "add-widget") { + HomeWidgets.loadProviders(ctx) + picking = true + } + } + } + Box(Modifier.weight(1f).fillMaxWidth()) { + val scroller = q.isEmpty() && byName && entries.size > 16 + LazyVerticalGrid( + columns = GridCells.Adaptive(if (narrow) 84.dp else 96.dp), + state = grid, + horizontalArrangement = Arrangement.spacedBy(10.dp), + verticalArrangement = Arrangement.spacedBy(10.dp), + contentPadding = PaddingValues(start = padH, end = if (scroller) padH + 22.dp else padH, top = 12.dp, bottom = 16.dp), + modifier = Modifier.fillMaxSize(), + ) { + if (widgetsShown) item(key = "widgets", span = { GridItemSpan(maxLineSpan) }) { + BoxWithConstraints(Modifier.fillMaxWidth()) { + val maxW = maxWidth + FlowRow( + horizontalArrangement = Arrangement.spacedBy(10.dp), + verticalArrangement = Arrangement.spacedBy(10.dp), + modifier = Modifier.fillMaxWidth().padding(bottom = 6.dp), + ) { + for (w in HomeWidgets.widgets) key(w.id) { WidgetCard(w, maxW.value.toInt()) } + } + } + } + if (entries.isEmpty()) item(key = "empty", span = { GridItemSpan(maxLineSpan) }) { + Note( + when { + q.isNotEmpty() -> stringResource(R.string.apps_no_match, q) + filter == AppsView.HIDDEN -> stringResource(R.string.apps_hidden_none) + else -> stringResource(R.string.content_no_android_apps) + }, + ) + } + items(entries, key = { it.key }) { entry -> + when (entry) { + is AppEntry.App -> AppTile( + entry.app, folderId = null, onLaunch = onLaunch, onNewFolder = newFolder, + first = entry === entries.first(), + ) + is AppEntry.Shortcut -> PinnedTile(entry.pinned, first = entry === entries.first()) + is AppEntry.Folder -> FolderTile(entry, first = entry === entries.first(), onOpen = { renameOnOpen = false; openFolder = entry.folder.id }) { + renameOnOpen = true + openFolder = entry.folder.id + } + } + } + } + if (scroller) AlphabetScroller(entries, grid, leadItems, Modifier.align(Alignment.CenterEnd).fillMaxHeight().padding(end = 4.dp, top = 8.dp, bottom = 8.dp)) + } + } + + val folder = folders.firstOrNull { it.id == openFolder } + LaunchedEffect(folder == null, openFolder) { if (folder == null && openFolder != null) openFolder = null } + AnimatedVisibility( + folder != null, enter = fadeIn(Motion.tw(180)), exit = fadeOut(Motion.tw(160)), + modifier = Modifier.fillMaxSize().zIndex(2f), + ) { + var last by remember { mutableStateOf(folder) } + if (folder != null) last = folder + last?.let { f -> + FolderSheet(f, f.apps.mapNotNull(member).filter { it.key !in hidden }.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.label }), renameOnOpen, onLaunch, newFolder) { + openFolder = null + renameOnOpen = false + } + } + } + AnimatedVisibility( + picking, enter = fadeIn(Motion.tw(180)), exit = fadeOut(Motion.tw(160)), + modifier = Modifier.fillMaxSize().zIndex(3f), + ) { WidgetPicker(padH) { picking = false } } + } +} + +@Composable +private fun SwipeLock() { + DisposableEffect(Unit) { + PageSwipe.locks++ + onDispose { PageSwipe.locks-- } + } +} + +@Composable +private fun appsFilterLabel(filter: String): String = stringResource( + when (filter) { + AppsView.GAMES -> R.string.apps_filter_games + AppsView.DOWNLOADED -> R.string.apps_filter_downloaded + AppsView.SYSTEM -> R.string.apps_filter_system + AppsView.HIDDEN -> R.string.apps_filter_hidden + else -> R.string.apps_filter_all + }, +) + +@Composable +private fun appsSortLabel(sort: String): String = stringResource( + when (sort) { + AppsView.NAME_DESC -> R.string.apps_sort_name_desc + AppsView.INSTALLED -> R.string.apps_sort_installed + AppsView.UPDATED -> R.string.apps_sort_updated + else -> R.string.apps_sort_name_asc + }, +) + +@Composable +private fun AppsFilterButton() = HeaderChoiceButton( + stringResource(R.string.apps_filter), Icons.Filled.FilterAlt, "apps-filter", + AppsView.FILTERS, AppsView.filter, { appsFilterLabel(it) }, AppsView::setFilter, +) + +@Composable +private fun AppsSortButton() = HeaderChoiceButton( + stringResource(R.string.stores_sort), Icons.Filled.Sort, "apps-sort", + AppsView.SORTS, AppsView.sort, { appsSortLabel(it) }, AppsView::setSort, +) + +@Composable +private fun HeaderChoiceButton( + title: String, icon: androidx.compose.ui.graphics.vector.ImageVector, key: String, + options: List, current: String, label: @Composable (String) -> String, onPick: (Context, String) -> Unit, +) { + val pal = LocalPalette.current + val ctx = LocalContext.current + var at by remember { mutableStateOf(null) } + Box(Modifier.onGloballyPositioned { at = it.boundsInRoot() }) { + HeaderIconButton("$title · ${label(current)}", icon, key) { + val from = at ?: return@HeaderIconButton + Steps.ask(StepAsk( + anchor = from, side = StepSide.Left, accent = pal.signal, pillCorner = 8.dp, items = options.size, + handle = { Icon(icon, null, tint = pal.signal, modifier = Modifier.size(18.dp)) }, + ) { + StepTitle(title) + StepList { + options.forEachIndexed { i, option -> + StepChoice( + label(option), selected = option == current, enabled = open, + modifier = Modifier.fillMaxWidth().stepItem(i).then(if (option == current) Modifier.focusRequester(first) else Modifier), + ) { + onPick(ctx, option) + Steps.fold() + } + } + } + }) + } + } +} + +@Composable +private fun AlphabetScroller(entries: List, grid: LazyGridState, leadItems: Int, modifier: Modifier) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val scope = rememberCoroutineScope() + val firstAt = remember(entries) { + val map = LinkedHashMap() + entries.forEachIndexed { i, e -> map.putIfAbsent(indexLetter(e.label), i) } + map + } + val letters = remember(firstAt) { firstAt.keys.toList() } + var dragging by remember { mutableStateOf(null) } + val current by remember(entries, leadItems) { + derivedStateOf { + val i = (grid.firstVisibleItemIndex - leadItems).coerceIn(0, (entries.size - 1).coerceAtLeast(0)) + entries.getOrNull(i)?.let { indexLetter(it.label) } + } + } + var height by remember { mutableIntStateOf(1) } + val jump: (Float) -> Unit = { y -> + val i = ((y / height) * letters.size).toInt().coerceIn(0, letters.size - 1) + val letter = letters[i] + if (letter != dragging) { + dragging = letter + val at = firstAt[letter] ?: 0 + scope.launch { grid.scrollToItem(if (at == 0) 0 else leadItems + at) } + } + } + Box(modifier.width(22.dp)) { + Column( + verticalArrangement = Arrangement.SpaceEvenly, horizontalAlignment = Alignment.CenterHorizontally, + modifier = Modifier.fillMaxSize() + .clip(RoundedCornerShape(11.dp)) + .background(if (dragging != null) colors.surface.copy(alpha = 0.85f) else Color.Transparent) + .onSizeChanged { height = it.height.coerceAtLeast(1) } + .pointerInput(letters) { + awaitEachGesture { + val down = awaitFirstDown() + down.consume() + jump(down.position.y) + while (true) { + val event = awaitPointerEvent() + val c = event.changes.firstOrNull { it.id == down.id } ?: break + if (!c.pressed) break + c.consume() + jump(c.position.y) + } + dragging = null + } + }, + ) { + for (l in letters) { + val on = l == (dragging ?: current) + Text( + l, fontSize = 10.sp, lineHeight = 11.sp, fontWeight = if (on) FontWeight.Bold else FontWeight.Medium, + color = if (on) pal.signal else colors.onSurfaceVariant, textAlign = TextAlign.Center, + ) + } + } + dragging?.let { l -> + Box( + contentAlignment = Alignment.Center, + modifier = Modifier.align(Alignment.Center).offset { IntOffset(-64.dp.roundToPx(), 0) }.size(56.dp) + .clip(CircleShape).background(pal.signal), + ) { Text(l, fontSize = 26.sp, fontWeight = FontWeight.Bold, color = pal.onPrimary) } + } + } +} + +@OptIn(ExperimentalFoundationApi::class) +@Composable +private fun TileFrame( + id: String, first: Boolean, onClick: () -> Unit, onMenu: () -> Unit, + content: @Composable (hot: Boolean) -> 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.55f, Spring.StiffnessMedium), label = "appScale") + Column( + horizontalAlignment = Alignment.CenterHorizontally, + modifier = Modifier.fillMaxWidth() + .paneItem("tile:$id").then(if (first) Modifier.firstTile().paneEntry() else Modifier) + .graphicsLayer { scaleX = scale; scaleY = scale } + .clip(Shape12) + .background(if (hot) colors.surface else colors.surface.copy(alpha = 0.55f)) + .glideBorder(hot, Shape12, pal.signal, hotWidth = 2.5.dp) + .hoverable(src) + .combinedClickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onLongClick = onMenu, onClick = onClick) + .controllerConfirm(onClick = onClick) + .menuKey(onMenu) + .padding(horizontal = 6.dp, vertical = 10.dp), + ) { content(hot) } +} + +@Composable +private fun TileLabel(text: String) = Text( + text, fontSize = 12.sp, lineHeight = 15.sp, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground, + maxLines = 1, overflow = TextOverflow.Ellipsis, textAlign = TextAlign.Center, + modifier = Modifier.fillMaxWidth().padding(top = 8.dp), +) + +@Composable +private fun AppIcon(app: HomeApp.LaunchableApp, size: androidx.compose.ui.unit.Dp) { + val icon = app.icon + if (icon != null) Image(icon.asImageBitmap(), null, contentScale = ContentScale.Fit, modifier = Modifier.size(size)) + else Box(Modifier.size(size).clip(CircleShape).background(artBrush(hueOf(app.label)))) +} + +@Composable +private fun AppTile( + app: HomeApp.LaunchableApp, folderId: String?, first: Boolean, + onLaunch: (HomeApp.LaunchableApp) -> Unit, onNewFolder: (HomeApp.LaunchableApp) -> Unit, +) { + var menu by remember { mutableStateOf(false) } + Box { + TileFrame(app.key, first, onClick = { onLaunch(app) }, onMenu = { menu = true }) { + AppIcon(app, 52.dp) + TileLabel(app.label) + } + AppMenu(app, folderId, menu, onDismiss = { menu = false }, onNewFolder = onNewFolder) + } +} + +@Composable +private fun AppMenu( + app: HomeApp.LaunchableApp, folderId: String?, open: Boolean, + onDismiss: () -> Unit, onNewFolder: (HomeApp.LaunchableApp) -> Unit, +) { + val ctx = LocalContext.current + var choosing by remember { mutableStateOf(false) } + var shortcuts by remember { mutableStateOf>>(emptyList()) } + LaunchedEffect(open) { + if (!open) { + choosing = false + return@LaunchedEffect + } + shortcuts = withContext(Dispatchers.IO) { + HomeApp.shortcuts(ctx, app).map { it to HomeApp.shortcutIcon(ctx, it, 64) } + } + } + val isHidden = app.key in HomeHidden.keys + AnchoredMenu(open, onDismiss = onDismiss, title = app.label, compact = true, minWidth = 200.dp) { first -> + if (choosing) { + val others = HomeFolders.folders.filter { it.id != folderId } + var firstUsed = false + for (f in others) key(f.id) { + MenuItem(f.name, checked = false, focusRequester = if (!firstUsed) first.also { firstUsed = true } else null) { + HomeFolders.add(ctx, f.id, app.key) + onDismiss() + } + } + MenuItem(stringResource(R.string.apps_new_folder), checked = false, focusRequester = if (others.isEmpty()) first else null) { + onDismiss() + onNewFolder(app) + } + } else { + shortcuts.forEachIndexed { i, (info, icon) -> + key(info.id) { + MenuItem( + info.shortLabel?.toString().orEmpty(), checked = false, + focusRequester = if (i == 0) first else null, + leading = { MenuIcon(icon) }, + ) { + onDismiss() + runCatching { HomeApp.startShortcut(ctx, info) } + } + } + } + if (shortcuts.isNotEmpty()) Box(Modifier.fillMaxWidth().padding(vertical = 4.dp).height(1.dp).background(LocalPalette.current.line)) + if (!isHidden) MenuItem(stringResource(R.string.apps_add_to_folder), checked = false, focusRequester = if (shortcuts.isEmpty()) first else null) { choosing = true } + if (folderId != null) MenuItem(stringResource(R.string.apps_remove_from_folder), checked = false) { + HomeFolders.remove(ctx, app.key) + onDismiss() + } + MenuItem(stringResource(if (isHidden) R.string.apps_unhide else R.string.apps_hide), checked = false, + focusRequester = if (isHidden && shortcuts.isEmpty()) first else null) { + onDismiss() + HomeHidden.set(ctx, app.key, !isHidden) + } + MenuItem(stringResource(R.string.apps_app_info), checked = false) { + onDismiss() + runCatching { HomeApp.openAppInfo(ctx, app) } + } + if (HomeApp.canUninstall(app)) MenuItem(stringResource(R.string.apps_uninstall), checked = false) { + onDismiss() + runCatching { HomeApp.uninstall(ctx, app) } + } + } + } +} + +@Composable +private fun MenuIcon(icon: Bitmap?) { + if (icon != null) Image(icon.asImageBitmap(), null, modifier = Modifier.size(20.dp)) + else Spacer(Modifier.size(20.dp)) +} + +@Composable +private fun PinnedTile(pinned: HomePins.Pinned, first: Boolean) { + val ctx = LocalContext.current + var menu by remember { mutableStateOf(false) } + Box { + TileFrame(pinned.key, first, onClick = { runCatching { HomeApp.startShortcut(ctx, pinned.info) } }, onMenu = { menu = true }) { + Box { + val icon = pinned.icon + if (icon != null) Image(icon.asImageBitmap(), null, contentScale = ContentScale.Fit, modifier = Modifier.size(52.dp)) + else Box(Modifier.size(52.dp).clip(CircleShape).background(artBrush(hueOf(pinned.label)))) + } + TileLabel(pinned.label) + } + AnchoredMenu(menu, onDismiss = { menu = false }, title = pinned.label, compact = true, minWidth = 180.dp) { firstItem -> + MenuItem(stringResource(R.string.apps_shortcut_remove), checked = false, detail = pinned.appLabel, focusRequester = firstItem) { + menu = false + HomePins.unpin(ctx, pinned) + } + } + } +} + +@Composable +private fun FolderIcon(apps: List, size: androidx.compose.ui.unit.Dp) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val cell = (size - 14.dp) / 2 + Box( + Modifier.size(size).clip(RoundedCornerShape(size / 3.5f)).background(colors.surfaceVariant) + .glideBorder(false, RoundedCornerShape(size / 3.5f), pal.signal, pal.line2) + .padding(5.dp), + ) { + Column(verticalArrangement = Arrangement.spacedBy(4.dp)) { + for (row in apps.take(4).chunked(2)) Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) { + for (a in row) AppIcon(a, cell) + } + } + } +} + +@Composable +private fun FolderTile(entry: AppEntry.Folder, first: Boolean, onOpen: () -> Unit, onRename: () -> Unit) { + val ctx = LocalContext.current + var menu by remember { mutableStateOf(false) } + Box { + TileFrame(entry.key, first, onClick = onOpen, onMenu = { menu = true }) { + FolderIcon(entry.apps, 52.dp) + TileLabel(entry.folder.name) + } + AnchoredMenu(menu, onDismiss = { menu = false }, title = entry.folder.name, compact = true, minWidth = 160.dp) { firstItem -> + MenuItem(stringResource(R.string.apps_folder_rename), checked = false, focusRequester = firstItem) { + menu = false + onRename() + } + MenuItem(stringResource(R.string.apps_folder_ungroup), checked = false) { + menu = false + HomeFolders.delete(ctx, entry.folder.id) + } + } + } +} + +@Composable +private fun FolderSheet( + folder: HomeFolders.Folder, apps: List, renameFirst: Boolean, + onLaunch: (HomeApp.LaunchableApp) -> Unit, onNewFolder: (HomeApp.LaunchableApp) -> Unit, onClose: () -> Unit, +) { + SwipeLock() + val ctx = LocalContext.current + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + var renaming by remember(folder.id) { mutableStateOf(renameFirst) } + var name by remember(folder.id) { mutableStateOf(if (renameFirst) "" else folder.name) } + val commit = { + val n = name.trim() + if (n.isNotEmpty() && n != folder.name) HomeFolders.rename(ctx, folder.id, n) + renaming = false + } + val close = { if (renaming) commit(); onClose() } + BackHandler { close() } + Box( + contentAlignment = Alignment.Center, + modifier = Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.55f)) + .pointerInput(Unit) { awaitEachGesture { val d = awaitFirstDown(); d.consume(); close() } }, + ) { + val shown = remember { androidx.compose.animation.core.MutableTransitionState(false) }.apply { targetState = true } + AnimatedVisibility(shown, enter = scaleIn(Motion.sp(0.75f), initialScale = 0.92f) + fadeIn(Motion.tw(160)), exit = scaleOut(Motion.tw(140)) + fadeOut(Motion.tw(140))) { + Column( + modifier = Modifier.widthIn(max = 620.dp).fillMaxWidth(0.9f).heightIn(max = 520.dp) + .clip(Shape16).background(pal.surfaceVariant.copy(alpha = 0.97f)) + .glideBorder(false, Shape16, pal.signal, pal.signal.copy(alpha = 0.22f)) + .pointerInput(Unit) { awaitEachGesture { awaitFirstDown(requireUnconsumed = false).consume() } } + .controllerBack(close) + .padding(16.dp), + ) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().padding(bottom = 10.dp)) { + if (renaming) Box(Modifier.weight(1f)) { + AdbTextField( + value = name, onValueChange = { name = it.take(40) }, label = stringResource(R.string.apps_folder_name), + keyboardType = KeyboardType.Text, imeAction = ImeAction.Done, compact = true, showLabel = false, + placeholder = folder.name, focusOnShow = true, onDone = { commit() }, + ) + } else { + Text(folder.name, fontSize = 20.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false)) + SmallIconButton(Icons.Filled.Edit, stringResource(R.string.apps_folder_rename), tint = colors.onSurfaceVariant) { renaming = true } + Spacer(Modifier.weight(1f)) + } + SmallIconButton(Icons.Filled.Close, stringResource(R.string.common_close), tint = colors.onSurfaceVariant) { close() } + } + LazyVerticalGrid( + columns = GridCells.Adaptive(92.dp), + horizontalArrangement = Arrangement.spacedBy(10.dp), + verticalArrangement = Arrangement.spacedBy(10.dp), + ) { + items(apps, key = { it.key }) { app -> + AppTile(app, folderId = folder.id, first = false, onLaunch = { onClose(); onLaunch(it) }, onNewFolder = onNewFolder) + } + } + } + } + } +} + +@Composable +private fun WidgetCard(w: HomeWidgets.Placed, maxWidthDp: Int) { + val ctx = LocalContext.current + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + var menu by remember { mutableStateOf(false) } + val src = remember { MutableInteractionSource() } + val hot = rememberHot(src) + val width = w.widthDp.coerceAtMost(maxWidthDp) + val activity = remember(ctx) { ctx.findActivity() } + Box { + Box( + Modifier.size(width.dp, w.heightDp.dp) + .clip(Shape16) + .background(colors.surface.copy(alpha = 0.35f)) + .glideBorder(hot || menu, Shape16, pal.signal) + .hoverable(src).focusable(interactionSource = src) + .controllerConfirm { menu = true } + .menuKey { menu = true }, + ) { + AndroidView( + factory = { c -> + (HomeWidgets.createView(c, w.id) ?: android.view.View(c)).apply { + val radius = 16 * c.resources.displayMetrics.density + outlineProvider = object : android.view.ViewOutlineProvider() { + override fun getOutline(view: android.view.View, outline: android.graphics.Outline) = + outline.setRoundRect(0, 0, view.width, view.height, radius) + } + clipToOutline = true + } + }, + update = { v -> + if (v is HomeWidgets.HomeWidgetView) { + v.onLongPress = { menu = true } + HomeWidgets.applySize(v, width, w.heightDp) + } + }, + modifier = Modifier.fillMaxSize(), + ) + } + val (minW, minH) = remember(w.id) { HomeWidgets.minSize(ctx, w.id) } + val index = HomeWidgets.widgets.indexOfFirst { it.id == w.id } + val label = remember(w.id) { HomeWidgets.info(ctx, w.id)?.loadLabel(ctx.packageManager) ?: "" } + AnchoredMenu(menu, onDismiss = { menu = false }, title = label, compact = true, minWidth = 180.dp) { first -> + val step = 48 + MenuItem(stringResource(R.string.apps_widget_wider), checked = false, enabled = width < maxWidthDp, focusRequester = first) { + HomeWidgets.resize(ctx, w.id, (width + step).coerceAtMost(maxWidthDp), w.heightDp) + } + MenuItem(stringResource(R.string.apps_widget_narrower), checked = false, enabled = width > minW) { + HomeWidgets.resize(ctx, w.id, (width - step).coerceAtLeast(minW), w.heightDp) + } + MenuItem(stringResource(R.string.apps_widget_taller), checked = false, enabled = w.heightDp < 480) { + HomeWidgets.resize(ctx, w.id, width, (w.heightDp + step).coerceAtMost(480)) + } + MenuItem(stringResource(R.string.apps_widget_shorter), checked = false, enabled = w.heightDp > minH) { + HomeWidgets.resize(ctx, w.id, width, (w.heightDp - step).coerceAtLeast(minH)) + } + if (index > 0) MenuItem(stringResource(R.string.apps_widget_move_earlier), checked = false) { HomeWidgets.move(ctx, w.id, -1) } + if (index in 0 until HomeWidgets.widgets.size - 1) MenuItem(stringResource(R.string.apps_widget_move_later), checked = false) { HomeWidgets.move(ctx, w.id, 1) } + if (activity != null && HomeWidgets.canReconfigure(ctx, w.id)) MenuItem(stringResource(R.string.apps_widget_configure), checked = false) { + menu = false + HomeWidgets.reconfigure(activity, w.id) + } + MenuItem(stringResource(R.string.apps_widget_remove), checked = false) { + menu = false + HomeWidgets.remove(ctx, w.id) + } + } + } +} + +@Composable +private fun WidgetPicker(padH: androidx.compose.ui.unit.Dp, onClose: () -> Unit) { + SwipeLock() + val ctx = LocalContext.current + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val activity = remember(ctx) { ctx.findActivity() } + BackHandler { onClose() } + val providers = HomeWidgets.providers + Column(Modifier.fillMaxSize().background(colors.background).pointerInput(Unit) { awaitEachGesture { awaitFirstDown(requireUnconsumed = false) } }) { + LazyVerticalGrid( + columns = GridCells.Adaptive(150.dp), + horizontalArrangement = Arrangement.spacedBy(10.dp), + verticalArrangement = Arrangement.spacedBy(10.dp), + contentPadding = PaddingValues(horizontal = padH, vertical = 14.dp), + modifier = Modifier.fillMaxSize(), + ) { + item(key = "back", span = { GridItemSpan(maxLineSpan) }) { + Column { + Box(Modifier.padding(bottom = 10.dp)) { BackLink(stringResource(R.string.rail_apps), compact = true, onClick = onClose) } + PageHeader(stringResource(R.string.apps_add_widget)) { + if (providers != null) Chip(providers.size.toString(), ok = false) + } + } + } + when { + providers == null -> item(key = "loading", span = { GridItemSpan(maxLineSpan) }) { Note(stringResource(R.string.apps_widgets_loading)) } + providers.isEmpty() -> item(key = "none", span = { GridItemSpan(maxLineSpan) }) { Note(stringResource(R.string.apps_widgets_none)) } + else -> items(providers, key = { it.info.provider.flattenToString() }) { p -> + ProviderCard(p, first = p === providers.first()) { + onClose() + if (activity != null) HomeWidgets.add(activity, p) + } + } + } + } + } +} + +@Composable +private fun ProviderCard(p: HomeWidgets.Provider, first: Boolean, onClick: () -> Unit) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val src = remember { MutableInteractionSource() } + val hot = rememberHot(src) + Column( + modifier = Modifier.fillMaxWidth().paneItem("widget:" + p.info.provider.flattenToString()).then(if (first) Modifier.firstTile() else Modifier) + .clip(Shape12).background(colors.surface) + .glideBorder(hot, Shape12, pal.signal, hotWidth = 2.5.dp) + .hoverable(src) + .clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onClick) + .controllerConfirm(onClick = onClick), + ) { + Box( + contentAlignment = Alignment.Center, + modifier = Modifier.fillMaxWidth().aspectRatio(1.6f).background(colors.surfaceVariant).padding(10.dp), + ) { + val preview = p.preview + if (preview != null) Image(preview.asImageBitmap(), null, contentScale = ContentScale.Fit, modifier = Modifier.fillMaxSize()) + } + Column(Modifier.padding(horizontal = 10.dp, vertical = 8.dp)) { + Text(p.label, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis) + val cells = "${(p.widthDp / 80f).roundToInt().coerceAtLeast(1)} × ${(p.heightDp / 80f).roundToInt().coerceAtLeast(1)}" + Text(if (p.appLabel == p.label) cells else "${p.appLabel} · $cells", fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis) + } + } +} + +@Composable +fun PinRequestPrompt(label: String, appLabel: String, icon: Bitmap?, wide: Boolean, onAdd: () -> Unit, onCancel: () -> Unit) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + BackHandler { onCancel() } + Box( + contentAlignment = Alignment.Center, + modifier = Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.55f)) + .pointerInput(Unit) { awaitEachGesture { awaitFirstDown().consume(); onCancel() } }, + ) { + val shown = remember { androidx.compose.animation.core.MutableTransitionState(false) }.apply { targetState = true } + AnimatedVisibility(shown, enter = scaleIn(Motion.sp(0.75f), initialScale = 0.92f) + fadeIn(Motion.tw(160))) { + Column( + verticalArrangement = Arrangement.spacedBy(14.dp), + modifier = Modifier.widthIn(min = 280.dp, max = 420.dp) + .clip(Shape16).background(pal.surfaceVariant.copy(alpha = 0.97f)) + .glideBorder(false, Shape16, pal.signal, pal.signal.copy(alpha = 0.22f)) + .pointerInput(Unit) { awaitEachGesture { awaitFirstDown(requireUnconsumed = false).consume() } } + .controllerBack(onCancel) + .padding(18.dp), + ) { + Text( + stringResource(R.string.apps_pin_title).uppercase(), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, + letterSpacing = 1.5.sp, color = colors.onSurfaceVariant, + ) + if (wide && icon != null) Box( + contentAlignment = Alignment.Center, + modifier = Modifier.fillMaxWidth().heightIn(max = 180.dp).clip(Shape12).background(MaterialTheme.colorScheme.surface).padding(10.dp), + ) { Image(icon.asImageBitmap(), null, contentScale = ContentScale.Fit, modifier = Modifier.fillMaxWidth()) } + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(14.dp)) { + if (!wide) { + if (icon != null) Image(icon.asImageBitmap(), null, contentScale = ContentScale.Fit, modifier = Modifier.size(52.dp)) + else Box(Modifier.size(52.dp).clip(CircleShape).background(artBrush(hueOf(label)))) + } + Column(Modifier.weight(1f)) { + Text(label, fontSize = 17.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 2, overflow = TextOverflow.Ellipsis) + Text(appLabel, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis) + } + } + Row(horizontalArrangement = Arrangement.spacedBy(10.dp, Alignment.End), modifier = Modifier.fillMaxWidth()) { + SecondaryButton(stringResource(R.string.common_cancel), onClick = onCancel) + PrimaryButton(stringResource(R.string.apps_pin_add), onClick = onAdd) + } + } + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ComponentsPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/ComponentsPage.kt index 364650b90b..a934d39cfa 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ComponentsPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ComponentsPage.kt @@ -699,7 +699,7 @@ fun ComponentsPage( Box(Modifier.fillMaxSize().onGloballyPositioned { pageAt = it.positionInRoot() }.onFocusChanged { pageFocused = it.hasFocus }) { Column( - Modifier.fillMaxSize().padding(horizontal = if (narrow) 16.dp else 22.dp, vertical = if (narrow) 12.dp else 18.dp) + Modifier.fillMaxSize().padding(horizontal = if (narrow) 16.dp else 22.dp).padding(top = if (narrow) 12.dp else 18.dp) .then(if (selectedGame == null) Modifier.bumpers( onPrevious = { pick(layerStep(layer, -1)) }, onNext = { pick(layerStep(layer, 1)) }, @@ -972,7 +972,7 @@ private fun Stack( onFocus = { onFocus(l) }, onClick = { onOpen(l) }, ) } - Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(3.dp)) { + Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState()).padding(bottom = 16.dp), verticalArrangement = Arrangement.spacedBy(3.dp)) { StackHeading(stringResource(R.string.comp_this_device)) card(GPU_TAB) Spacer(Modifier.height(6.dp)) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndContent.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndContent.kt index b70f9bb5e3..62c6a862e5 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndContent.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndContent.kt @@ -10,6 +10,8 @@ import androidx.compose.animation.core.animateFloat import androidx.compose.animation.core.snap import androidx.compose.animation.core.tween import androidx.compose.animation.scaleIn +import androidx.compose.animation.slideInHorizontally +import androidx.compose.animation.slideOutHorizontally import androidx.compose.animation.scaleOut import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.rememberUpdatedState @@ -105,7 +107,7 @@ import java.io.File internal fun Pane( s: FrontEndState, selected: String, a: FrontEndActions, page: (@Composable () -> Unit)?, modifier: Modifier, onSelect: (String) -> Unit, onAndroidAppClick: (HomeApp.LaunchableApp) -> Unit, - onOpenDeveloperOptions: () -> Unit, onRequestWirelessAdb: (Boolean) -> Unit, + onOpenDeveloperOptions: () -> Unit, onRequestWirelessAdb: (Boolean) -> Unit, onPairWirelessDebugging: () -> Unit, ) { BoxWithConstraints(modifier = modifier) { CompositionLocalProvider(LocalNarrowPane provides (maxWidth < NarrowPaneWidth)) { @@ -138,12 +140,19 @@ internal fun Pane( before[0] = target val targetNow by rememberUpdatedState(target) val leave = if (Hops.linking) PageLeave.Link else PageLeave.Ordinary - LaunchedEffect(target) { Hops.linking = false } + LaunchedEffect(target) { + Hops.linking = false + PageSwipe.direction = 0 + } AnimatedContent( targetState = target, modifier = Modifier.onGloballyPositioned { paneAt[0] = it.positionInRoot() }, transitionSpec = { + val swipe = PageSwipe.direction when { + swipe != 0 -> (fadeIn(Motion.tw(260, 40)) + slideInHorizontally(Motion.tw(360)) { it * swipe / 8 }) + .togetherWith(fadeOut(Motion.tw(160)) + slideOutHorizontally(Motion.tw(220)) { -it * swipe / 8 }) + .apply { targetContentZIndex = 1f } targetState in origins -> (fadeIn(Motion.tw(120))) .togetherWith(fadeOut(Motion.tw(320, 80)) + scaleOut(Motion.tw(480), targetScale = 0.95f)) .apply { targetContentZIndex = 1f } @@ -162,7 +171,7 @@ internal fun Pane( label = "pane", ) { key -> val drawn = (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) } + ?: { Content(s, if (key == "games") gameShown[0] else key, a, Modifier.fillMaxSize(), onSelect, onAndroidAppClick, onOpenDeveloperOptions, onRequestWirelessAdb, onPairWirelessDebugging) } val hopSink by androidx.compose.animation.core.animateFloatAsState( if (Hops.sinking == key) 1f else 0f, Motion.tw(260), label = "hopSink", ) @@ -223,7 +232,7 @@ private fun romFor(s: FrontEndState, selected: String): Pair Unit, onAndroidAppClick: (HomeApp.LaunchableApp) -> Unit, - onOpenDeveloperOptions: () -> Unit, onRequestWirelessAdb: (Boolean) -> Unit, + onOpenDeveloperOptions: () -> Unit, onRequestWirelessAdb: (Boolean) -> Unit, onPairWirelessDebugging: () -> Unit, ) { val colors = MaterialTheme.colorScheme val detailPosterWidth = if (LocalConfiguration.current.screenHeightDp < 600) 72.dp else 120.dp @@ -232,13 +241,13 @@ private fun Content( val padH = if (narrow) 16.dp else 22.dp val padV = if (narrow) 12.dp else 18.dp if (selected == "setup") { - Column(modifier = modifier.padding(horizontal = padH, vertical = padV)) { - SetupPanel(s, a, onOpenDeveloperOptions, onRequestWirelessAdb) + Column(modifier = modifier.padding(horizontal = padH).padding(top = padV)) { + SetupPanel(s, a, onOpenDeveloperOptions, onRequestWirelessAdb, onPairWirelessDebugging) } return } if (selected == "updates") { - UpdatesPage(s, a, modifier.padding(horizontal = padH, vertical = padV)) + UpdatesPage(s, a, modifier.padding(horizontal = padH).padding(top = padV)) return } if (selected == "steam") { @@ -261,24 +270,12 @@ private fun Content( DesktopPage(s, a, modifier, onSelect) return } + if (selected == "android-apps" && s.isHomeApp) { + AndroidAppsPage(s, modifier, onAndroidAppClick) + return + } Column(modifier = modifier.verticalScroll(rememberScrollState()).padding(horizontal = padH, vertical = padV)) { when { - selected == "android-apps" && s.isHomeApp -> { - Rise(0) { PageHeader(stringResource(R.string.content_android_apps)) { Chip(stringResource(R.string.content_apps_count, s.androidApps.size), ok = false) } } - if (s.androidApps.isEmpty()) Rise(3) { Note(stringResource(R.string.content_no_android_apps)) } - else Rise(3, Modifier.fillMaxWidth()) { - ArtGrid(s.androidApps.map { app -> - Tile( - app.label, - null, - null, - "android:${app.packageName}", - onClick = { onAndroidAppClick(app) }, - iconBitmap = app.icon, - ) - }) - } - } selected.startsWith("user:") -> { 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) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt index 78e6bd49bf..b7ac8ee43a 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt @@ -84,7 +84,9 @@ import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.compose.ui.layout.boundsInParent import androidx.compose.ui.layout.boundsInRoot +import androidx.compose.ui.layout.LayoutCoordinates import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.ui.layout.onPlaced import com.droiddeck.launcher.core.PhantomProcessLimit @@ -99,15 +101,15 @@ internal fun BottomBar( val keys = navigationKeys(s) val bounds = remember { androidx.compose.runtime.mutableStateMapOf() } val tint = androidx.compose.runtime.rememberUpdatedState(LocalPalette.current.signal) - var barAt by remember { mutableStateOf(androidx.compose.ui.geometry.Offset.Zero) } + val content = remember { arrayOfNulls(1) } Row(modifier.fillMaxWidth().background(MaterialTheme.colorScheme.surface), verticalAlignment = Alignment.CenterVertically) { BoxWithConstraints(Modifier.weight(1f)) { val itemWidth = (maxWidth / keys.size).coerceIn(56.dp, 88.dp) - Box(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).onGloballyPositioned { barAt = it.boundsInRoot().topLeft }) { - if (shown in keys) ChipGlide(keys.indexOf(shown), bounds[shown]?.translate(-barAt), tint, GlideAxis.Horizontal, corner = 14.dp, fill = 0.14f, outline = 0f) + Box(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).onPlaced { content[0] = it }) { + if (shown in keys) ChipGlide(keys.indexOf(shown), bounds[shown], tint, GlideAxis.Horizontal, corner = 14.dp, fill = 0.14f, outline = 0f) Row(Modifier.selectableGroup().padding(vertical = 4.dp), horizontalArrangement = Arrangement.Center) { NavigationItems(s, shown, compact = true, iconOnly = false, height = 56.dp, width = itemWidth, - place = { key -> Modifier.onGloballyPositioned { bounds[key] = it.boundsInRoot(); Hops.railBounds[key] = it.boundsInRoot() } }, + place = { key -> Modifier.onGloballyPositioned { item -> content[0]?.let { bounds[key] = it.localBoundingBoxOf(item) }; Hops.railBounds[key] = item.boundsInRoot() } }, onSelect = onSelect, onFocusSelect = onFocusSelect) } } @@ -116,7 +118,7 @@ internal fun BottomBar( } } -private fun navigationKeys(s: FrontEndState) = buildList { +internal fun navigationKeys(s: FrontEndState) = buildList { add("steam"); add("games") if (s.gameStoresEnabled) add("stores") add("desktop"); add("components") @@ -143,18 +145,18 @@ internal fun SideRail( val keys = navigationKeys(s) val bounds = remember { androidx.compose.runtime.mutableStateMapOf() } 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 }) { - if (shown in keys) ChipGlide(keys.indexOf(shown), bounds[shown]?.translate(-railAt), tint, GlideAxis.Vertical, corner = 14.dp, fill = 0.14f, outline = 0f) + val content = remember { arrayOfNulls(1) } + Box(Modifier.fillMaxSize().verticalScroll(rememberScrollState()).onPlaced { content[0] = it }) { + if (shown in keys) ChipGlide(keys.indexOf(shown), bounds[shown], tint, GlideAxis.Vertical, corner = 14.dp, fill = 0.14f, outline = 0f) Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(4.dp), modifier = Modifier.fillMaxWidth().selectableGroup(), ) { val place: (String) -> Modifier = { key -> - Modifier.onGloballyPositioned { - bounds[key] = it.boundsInRoot() - Hops.railBounds[key] = it.boundsInRoot() + Modifier.onGloballyPositioned { item -> + content[0]?.let { bounds[key] = it.localBoundingBoxOf(item) } + Hops.railBounds[key] = item.boundsInRoot() } } NavigationItems(s, shown, compact, iconOnly, fit, if (iconOnly) 52.dp else 80.dp, place, onSelect, onFocusSelect) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt index e75994776a..48315b0fe1 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt @@ -99,6 +99,8 @@ class FrontEndState( val frameGenLabel: String, val romsDir: String?, val logsEnabled: Boolean, + val gameDebugLogsEnabled: Boolean = false, + val gameDebugLogsNeedsRestart: Boolean = false, val vacDiagnostics: Boolean = false, val agentCommands: Boolean = false, val clearCachedApps: Boolean = false, @@ -208,6 +210,7 @@ class FrontEndActions( val onFiles: () -> Unit, val onBrowseFiles: (File) -> Unit = {}, val onLogs: () -> Unit, + val onGameDebugLogs: () -> Unit = {}, val onVacDiagnostics: () -> Unit = {}, val onAgentCommands: () -> Unit = {}, val onClearCachedApps: (Boolean) -> Unit = {}, @@ -255,6 +258,8 @@ class FrontEndActions( val onCopyPhantomCommand: (Boolean) -> Unit = {}, val onDismissPhantomGate: () -> Unit = {}, val onStartWirelessAdbPairing: () -> Unit = {}, + val onStartPairingGuide: (Int?) -> Boolean = { false }, + val onShowPhantomGate: () -> Unit = {}, val onOpenNotificationSettings: () -> Unit = {}, val controller: ControllerActions? = null, val updates: UpdatesActions = UpdatesActions(), @@ -425,6 +430,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com } var showWirelessAdbFix by rememberSaveable { mutableStateOf(false) } var showDeveloperDisplayChoice by rememberSaveable { mutableStateOf(false) } + var developerChoiceGuided by rememberSaveable { mutableStateOf(false) } var wirelessAdbDesiredEnabled by rememberSaveable { mutableStateOf(false) } var appToChooseDisplay by remember { mutableStateOf(null) } val colors = MaterialTheme.colorScheme @@ -433,9 +439,36 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com val phantomGateVisible = s.showPhantomGate && PhantomProcessLimit.blocksSteam(s.phantomProcessStatus) val processSettingsPageVisible = phantomGateVisible || showWirelessAdbFix || showDeveloperDisplayChoice val requestDeveloperOptions = { + developerChoiceGuided = false if (s.secondScreenDisplays.isEmpty()) a.onOpenDeveloperOptions(null) else showDeveloperDisplayChoice = true } + val openDeveloperOptionsOn: (Int?) -> Unit = { displayId -> + if (developerChoiceGuided) a.onStartWirelessAdbPairing() + if (!developerChoiceGuided || !a.onStartPairingGuide(displayId)) a.onOpenDeveloperOptions(displayId) + developerChoiceGuided = false + } + val startGuidedPairing = { + if (!com.droiddeck.launcher.core.WirelessAdbPairingService.notificationsEnabled(ctx)) { + wirelessAdbDesiredEnabled = false + showWirelessAdbFix = true + } else { + developerChoiceGuided = true + if (s.secondScreenDisplays.isEmpty()) openDeveloperOptionsOn(null) + else showDeveloperDisplayChoice = true + } + } + var applyingSavedPairing by remember { mutableStateOf(false) } + val fixPhantomLimit = { + if (!s.adbPaired || !com.droiddeck.launcher.core.GlobalSettings.wirelessDebuggingOn(ctx)) startGuidedPairing() + else if (!applyingSavedPairing) { + applyingSavedPairing = true + a.onSetPhantomProcessLimit(false) { error -> + applyingSavedPairing = false + if (error != null) startGuidedPairing() + } + } + } val requestWirelessAdbFix: (Boolean) -> Unit = { enabled -> wirelessAdbDesiredEnabled = enabled showWirelessAdbFix = true @@ -477,6 +510,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com selected.startsWith("emu:") || selected.startsWith("rom:") || selected.startsWith("user:") || selected == "store" -> "desktop" else -> s.pageKey ?: selected } + val railSelectionNow = androidx.compose.runtime.rememberUpdatedState(railSelection) var railPicks by remember { mutableStateOf(0) } val showRailPage: (String, Boolean) -> Unit = { key, focusContent -> if (key == "components") a.onComponents(focusContent) @@ -579,13 +613,23 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com }, ) { Pane( - s, selected, a, page, Modifier.fillMaxSize().then(paneFocus), { selected = it }, + s, selected, a, page, + Modifier.fillMaxSize().then(paneFocus).pageSwipe({ !processSettingsPageVisible && appToChooseDisplay == null }) { dir -> + val keys = navigationKeys(s) + val at = keys.indexOf(railSelectionNow.value) + if (at >= 0) keys.getOrNull(at + dir)?.let { key -> + PageSwipe.direction = dir + showRailPage(key, false) + } + }, + { selected = it }, onAndroidAppClick = { app -> if (s.secondScreenDisplays.isEmpty()) a.onAndroidApp(app, null) else appToChooseDisplay = app }, onOpenDeveloperOptions = requestDeveloperOptions, onRequestWirelessAdb = requestWirelessAdbFix, + onPairWirelessDebugging = startGuidedPairing, ) } @@ -619,10 +663,8 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com status = s.phantomProcessStatus, onDismiss = a.onDismissPhantomGate, onOpenDeveloperOptions = requestDeveloperOptions, - onFixWithWirelessDebugging = { - a.onStartWirelessAdbPairing() - requestDeveloperOptions() - }, + applyingSavedPairing = applyingSavedPairing, + onFixWithWirelessDebugging = fixPhantomLimit, onEnterAddressManually = { requestWirelessAdbFix(false) }, onCopyCommand = { a.onCopyPhantomCommand(false) }, onOpenNotificationSettings = a.onOpenNotificationSettings, @@ -648,13 +690,16 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com }, onMainScreen = { showDeveloperDisplayChoice = false - a.onOpenDeveloperOptions(null) + openDeveloperOptionsOn(null) }, onSecondaryScreen = { displayId -> showDeveloperDisplayChoice = false - a.onOpenDeveloperOptions(displayId) + openDeveloperOptionsOn(displayId) + }, + onDismiss = { + showDeveloperDisplayChoice = false + developerChoiceGuided = false }, - onDismiss = { showDeveloperDisplayChoice = false }, ) } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt index d5932762f7..db955683bb 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt @@ -141,6 +141,7 @@ internal fun SetupPanel( a: FrontEndActions, onOpenDeveloperOptions: () -> Unit, onRequestWirelessAdb: (Boolean) -> Unit, + onPairWirelessDebugging: () -> Unit, ) { val host = rememberMenuHost() val ctx = LocalContext.current @@ -203,6 +204,12 @@ internal fun SetupPanel( tab = STORAGE_TAB } } + LaunchedEffect(Unit) { + while (true) { + kotlinx.coroutines.delay(2_000) + a.onRefreshPhantomStatus() + } + } LaunchedEffect(tab) { if (tabTurned && inputModeManager.inputMode == InputMode.Keyboard) { androidx.compose.runtime.withFrameNanos { } @@ -279,7 +286,7 @@ internal fun SetupPanel( }, divider = divider && !showLimitDetails, ) { - if (limitBlocks) PrimaryButton(if (showLimitDetails) stringResource(R.string.common_hide) else stringResource(R.string.setup_fix_it), compact = true) { showLimitDetails = !showLimitDetails } + if (limitBlocks) PrimaryButton(stringResource(R.string.setup_fix_it), compact = true, onClick = a.onShowPhantomGate) else if (s.phantomProcessStatus != PhantomProcessStatus.NOT_APPLICABLE) { SecondaryButton(if (showLimitDetails) stringResource(R.string.common_hide) else stringResource(R.string.setup_details), compact = true) { showLimitDetails = !showLimitDetails } } @@ -292,11 +299,7 @@ internal fun SetupPanel( fontSize = 14.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(vertical = 4.dp), ) Actions { - if (limitBlocks) { - PrimaryButton(stringResource(R.string.setup_dev_options), compact = true, onClick = onOpenDeveloperOptions) - SecondaryButton(stringResource(R.string.setup_use_wireless), compact = true, enabled = !processLimitBusy) { setProcessLimit(false) } - SecondaryButton(stringResource(R.string.setup_check_again), compact = true, onClick = a.onRefreshPhantomStatus) - } else if (s.phantomProcessStatus == PhantomProcessStatus.DISABLED) { + if (s.phantomProcessStatus == PhantomProcessStatus.DISABLED) { SecondaryButton(stringResource(R.string.setup_limit_turn_on), compact = true, enabled = !processLimitBusy) { setProcessLimit(true) } } } @@ -472,6 +475,12 @@ internal fun SetupPanel( 4 -> { SettingsGroup(stringResource(R.string.setup_tab_diagnostics)) { ToggleRow(host, "logs", stringResource(R.string.setup_logs), stringResource(R.string.setup_logs_hint), s.logsEnabled) { a.onLogs() } + ToggleRow( + host, "game-debug-logs", stringResource(R.string.setup_game_debug_logs), + stringResource(if (s.gameDebugLogsNeedsRestart) R.string.setup_game_debug_logs_restart else R.string.setup_game_debug_logs_hint), + s.gameDebugLogsEnabled, + enabled = s.logsEnabled, + ) { a.onGameDebugLogs() } ToggleRow(host, "vacdiag", stringResource(R.string.setup_vac_diag), stringResource(R.string.setup_vac_diag_hint), s.vacDiagnostics) { a.onVacDiagnostics() } ToggleRow(host, "agent-commands", stringResource(R.string.setup_agent_commands), null, s.agentCommands) { a.onAgentCommands() } ActionRow(stringResource(R.string.setup_latest_logs), stringResource(R.string.drawer_logs_hint), stringResource(R.string.drawer_share_logs), a.onShareLogs, @@ -509,7 +518,7 @@ internal fun SetupPanel( ) if (!s.adbPaired) ActionRow( stringResource(R.string.setup_adb_pair), stringResource(R.string.setup_adb_pair_hint), - stringResource(R.string.setup_adb_pair_button), { onRequestWirelessAdb(false) }, + stringResource(R.string.setup_adb_pair_button), onPairWirelessDebugging, ) } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt index 4a3b24ce67..29c2e8c99e 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt @@ -304,12 +304,12 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String, open, detailScroll, gridScrolled = { grid.firstVisibleItemIndex > 0 || grid.firstVisibleItemScrollOffset > 0 }, onDetailFocus = { detailFocused = it }, - modifier = modifier.padding(horizontal = if (narrow) 14.dp else 22.dp, vertical = if (narrow) 10.dp else 14.dp), + modifier = modifier.padding(horizontal = if (narrow) 14.dp else 22.dp).padding(top = if (narrow) 10.dp else 14.dp), wrap = { key, content -> StoreTheme(GameRef.parse(key).let { r -> r.store ?: r.game(s.steamGames)?.source?.let { Store.byId(it) } }) { content() } }, grid = { LibraryGrid( s, a, grid, visible, split, visible.size, sources, source, sizesPending, syncing, - showUninstalled = listUninstalled.takeIf { stores }, onShowUninstalled = setShowUninstalled, + showUninstalled = listUninstalled.takeIf { !s.shortcutPicker },onShowUninstalled = setShowUninstalled, hiddenUninstalled = hiddenUninstalled, onSource = { LibraryView.source = it }, onCycle = { step -> @@ -638,7 +638,7 @@ private fun LibraryRow(e: LibraryEntry, first: Boolean, navigation: Modifier, ch } @Composable -private fun HeaderIconButton(description: String, icon: androidx.compose.ui.graphics.vector.ImageVector, key: String, onClick: () -> Unit) { +internal fun HeaderIconButton(description: String, icon: androidx.compose.ui.graphics.vector.ImageVector, key: String, onClick: () -> Unit) { val colors = MaterialTheme.colorScheme val pal = LocalPalette.current val src = remember { MutableInteractionSource() } @@ -655,7 +655,7 @@ private fun HeaderIconButton(description: String, icon: androidx.compose.ui.grap /** Choosing Library in the rail lands on the first game, as Play Steam does on the Steam page. */ @Composable -private fun Modifier.paneEntry(): Modifier { +internal fun Modifier.paneEntry(): Modifier { val ff = LocalFrontFocus.current ?: return this androidx.compose.runtime.DisposableEffect(ff) { ff.primaryAttached++ diff --git a/app/src/main/java/com/droiddeck/launcher/ui/PageSwipe.kt b/app/src/main/java/com/droiddeck/launcher/ui/PageSwipe.kt new file mode 100644 index 0000000000..94c7a8cf3c --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/PageSwipe.kt @@ -0,0 +1,60 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.foundation.gestures.awaitEachGesture +import androidx.compose.foundation.gestures.awaitFirstDown +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.input.pointer.PointerEventPass +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.input.pointer.util.VelocityTracker +import androidx.compose.ui.input.pointer.util.addPointerInputChange +import androidx.compose.ui.unit.dp +import kotlin.math.abs + +internal object PageSwipe { + var locks by mutableIntStateOf(0) + var direction by mutableIntStateOf(0) +} + +// Runs on the Final pass so carousels, sliders, scrollers and widgets that consumed the drag keep it. +@Composable +internal fun Modifier.pageSwipe(enabled: () -> Boolean, onSwipe: (Int) -> Unit): Modifier { + val enabledNow by rememberUpdatedState(enabled) + val onSwipeNow by rememberUpdatedState(onSwipe) + return pointerInput(Unit) { + val distance = 72.dp.toPx() + val flingDistance = 32.dp.toPx() + val flingVelocity = 900.dp.toPx() + val slop = viewConfiguration.touchSlop + awaitEachGesture { + val down = awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Final) + if (!enabledNow() || PageSwipe.locks > 0) return@awaitEachGesture + val tracker = VelocityTracker() + tracker.addPointerInputChange(down) + var total = Offset.Zero + var mine = false + while (true) { + val event = awaitPointerEvent(PointerEventPass.Final) + if (event.changes.size > 1) return@awaitEachGesture + val change = event.changes.firstOrNull { it.id == down.id } ?: return@awaitEachGesture + if (!change.pressed) break + if (!mine && change.isConsumed) return@awaitEachGesture + total += change.position - change.previousPosition + tracker.addPointerInputChange(change) + if (!mine && abs(total.x) > slop && abs(total.x) > abs(total.y) * 2f) mine = true + if (mine) change.consume() + } + if (!mine || PageSwipe.locks > 0) return@awaitEachGesture + val vx = tracker.calculateVelocity().x + val horizontal = abs(total.x) > abs(total.y) * 1.5f + val far = abs(total.x) > distance + val flung = abs(total.x) > flingDistance && abs(vx) > flingVelocity && (vx > 0) == (total.x > 0) + if (horizontal && (far || flung)) onSwipeNow(if (total.x < 0) 1 else -1) + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/PhantomProcessGatePage.kt b/app/src/main/java/com/droiddeck/launcher/ui/PhantomProcessGatePage.kt index 517309ec03..60b4223f0a 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/PhantomProcessGatePage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/PhantomProcessGatePage.kt @@ -45,6 +45,7 @@ import com.droiddeck.launcher.core.WirelessAdbPairingService.Stage @Composable fun PhantomProcessGatePage( status: PhantomProcessStatus, + applyingSavedPairing: Boolean, onDismiss: () -> Unit, onOpenDeveloperOptions: () -> Unit, onFixWithWirelessDebugging: () -> Unit, @@ -77,7 +78,7 @@ fun PhantomProcessGatePage( BoxWithConstraints(Modifier.fillMaxWidth()) { val wide = maxWidth >= 620.dp val fix: @Composable ColumnScope.() -> Unit = { - FixGroup(hasToggle, stage, environment, compact, onOpenDeveloperOptions, onFixWithWirelessDebugging, + FixGroup(hasToggle, stage, environment, compact, applyingSavedPairing, onOpenDeveloperOptions, onFixWithWirelessDebugging, onOpenNotificationSettings, onCancel = { WirelessAdbPairingService.cancel(context) }) } val side: @Composable ColumnScope.() -> Unit = { @@ -119,6 +120,7 @@ private fun FixGroup( stage: Stage, environment: GateEnvironment, compact: Boolean, + applyingSavedPairing: Boolean, onOpenDeveloperOptions: () -> Unit, onFixWithWirelessDebugging: () -> Unit, onOpenNotificationSettings: () -> Unit, @@ -131,6 +133,10 @@ private fun FixGroup( verticalArrangement = Arrangement.spacedBy(8.dp), ) { when { + applyingSavedPairing -> Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) { + CircularProgressIndicator(Modifier.size(18.dp), strokeWidth = 2.dp) + Body(stringResource(R.string.adbpair_applying)) + } pairing -> PairingProgress(stage, onCancel) hasToggle -> { Body(stringResource(R.string.gate_toggle_steps)) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt index e643cd79a3..c814242715 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt @@ -38,6 +38,7 @@ import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.material.icons.outlined.DesktopWindows import androidx.compose.material.icons.outlined.Layers import androidx.compose.material.icons.outlined.ScreenShare +import androidx.compose.material.icons.outlined.Pause import androidx.compose.material.icons.outlined.PictureInPictureAlt import androidx.compose.material.icons.automirrored.outlined.ExitToApp import androidx.compose.material.icons.outlined.Settings @@ -286,6 +287,7 @@ class DrawerActions( val pipSupported: Boolean = false, val pipAutoEnter: Boolean = false, val onPip: () -> Unit = {}, + val onPause: () -> Unit = {}, val onPipAutoEnter: (Boolean) -> Unit = {}, val unfoldedControls: Boolean? = null, val onUnfoldedControls: (Boolean) -> Unit = {}, @@ -428,17 +430,15 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont } .padding(12.dp), ) { - val title = a.title ?: if (a.steam) stringResource(R.string.drawer_steam) else stringResource(R.string.drawer_desktop) - if (narrow) Text(title, fontSize = 18.sp, fontWeight = FontWeight.Bold, - color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis, - modifier = Modifier.fillMaxWidth().padding(bottom = 6.dp)) Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().heightIn(min = 44.dp), ) { - if (narrow) Spacer(Modifier.weight(1f)) else Text(title, fontSize = 18.sp, fontWeight = FontWeight.Bold, - color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f)) + Spacer(Modifier.weight(1f)) + SteamActionPill( + stringResource(R.string.stores_dl_pause), Icons.Outlined.Pause, focus.track(page, "pause"), + ) { host.open = null; a.onPause() } if (a.pipSupported) SteamActionPill( stringResource(R.string.pip_title), Icons.Outlined.PictureInPictureAlt, focus.track(page, "pip"), ) { host.open = null; a.onPip() } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SessionPausedOverlay.kt b/app/src/main/java/com/droiddeck/launcher/ui/SessionPausedOverlay.kt index afe9f0ba4c..2b91273065 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionPausedOverlay.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionPausedOverlay.kt @@ -77,6 +77,7 @@ class PausedFrame(val image: ImageBitmap, val bounds: android.graphics.Rect) private const val CARD_SCALE = 0.82f private const val FRAME_WAIT_MS = 600L +private val PopEasing = CubicBezierEasing(0.3f, 1.5f, 0.4f, 1f) private fun tone(saturation: Float, brightness: Float): ColorMatrix = ColorMatrix().apply { @@ -90,6 +91,7 @@ fun SessionPausedOverlay( engaged: Boolean, failures: Int, frame: PausedFrame?, + animateIn: Boolean, title: String, onResume: () -> Unit, onFrameNeeded: () -> Unit, @@ -106,6 +108,18 @@ fun SessionPausedOverlay( LaunchedEffect(suspended, engaged) { when { suspended && !engaged -> { + if (!shown && animateIn) { + if (currentFrame == null) { + onFrameNeeded() + withTimeoutOrNull(FRAME_WAIT_MS) { snapshotFlow { currentFrame }.first { it != null } } + } + shown = true + launch { press.animateTo(1f, Motion.sp(0.5f, Spring.StiffnessMedium)) } + launch { ring.animateTo(0f, Motion.tw(200)) } + launch { lift.animateTo(1f, Motion.tw(520)) } + orb.animateTo(1f, Motion.tw(380, delay = if (orb.value < 0.5f) 260 else 0, easing = PopEasing)) + return@LaunchedEffect + } if (!shown) { if (currentFrame == null) { onFrameNeeded() diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StorePage.kt b/app/src/main/java/com/droiddeck/launcher/ui/StorePage.kt index cd3a905c78..e3724dd83d 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StorePage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StorePage.kt @@ -157,7 +157,7 @@ private fun FlathubHero(s: FrontEndState, ring: Int) { StoreState.sections.values.flatten().mapNotNull { it.icon }.distinct().take(48).takeIf { it.size >= 8 }.orEmpty() } val busy = StoreState.busy == "setup" - BoxWithConstraints(Modifier.fillMaxSize().padding(horizontal = if (narrow) 14.dp else 22.dp, vertical = if (narrow) 10.dp else 14.dp)) { + BoxWithConstraints(Modifier.fillMaxSize().padding(horizontal = if (narrow) 14.dp else 22.dp).padding(top = if (narrow) 10.dp else 14.dp)) { val shape = RoundedCornerShape(20.dp) Box(Modifier.fillMaxWidth().height(maxHeight.coerceAtLeast(320.dp)).clip(shape).background(colors.background).border(1.dp, pal.line, shape)) { androidx.compose.animation.Crossfade(icons, animationSpec = Motion.tw(600), label = "flathubWall") { tiles -> @@ -316,7 +316,7 @@ internal fun Storefront(s: FrontEndState, a: FrontEndActions) { } Column( - Modifier.fillMaxSize().padding(horizontal = padH, vertical = if (narrow) 10.dp else 14.dp) + Modifier.fillMaxSize().padding(horizontal = padH).padding(top = if (narrow) 10.dp else 14.dp) .bumpers( onPrevious = { if (openApp == null) mode = modes[(modes.indexOf(mode) + modes.size - 1) % modes.size] }, onNext = { if (openApp == null) mode = modes[(modes.indexOf(mode) + 1) % modes.size] }, diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt index 916e44e43f..92b118d54b 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt @@ -311,7 +311,7 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier val backLabel = stringResource(R.string.common_back) Box(modifier.onGloballyPositioned { hostAt = it.positionInRoot() }) { Column( - modifier = Modifier.fillMaxSize().padding(horizontal = padH, vertical = if (narrow) 10.dp else 14.dp) + modifier = Modifier.fillMaxSize().padding(horizontal = padH).padding(top = if (narrow) 10.dp else 14.dp) .then(if (openGame != null && !arranging) Modifier else Modifier.bumpers( onPrevious = { val picked = Store.byId(focusedChip) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/UpdatesPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/UpdatesPage.kt index 927a2c470d..dd73939a7d 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/UpdatesPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/UpdatesPage.kt @@ -115,7 +115,7 @@ internal fun UpdatesPage(s: FrontEndState, a: FrontEndActions, modifier: Modifie } BoxWithConstraints(Modifier.weight(1f).fillMaxWidth()) { val stacked = LocalNarrowPane.current || maxWidth < 600.dp - Column(modifier = Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(bottom = 8.dp)) { + Column(modifier = Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(bottom = 16.dp)) { if (stacked) { StatusPanel(s, u, ua, me) Box(Modifier.height(18.dp)) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/WirelessAdbFixPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/WirelessAdbFixPage.kt index 5c719ca90d..7e67b352bf 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/WirelessAdbFixPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/WirelessAdbFixPage.kt @@ -360,6 +360,7 @@ internal fun AdbTextField( onNext: (() -> Unit)? = null, onDone: (() -> Unit)? = null, focusOnShow: Boolean = false, + showLabel: Boolean = true, ) { val context = LocalContext.current val focusAsked = remember { booleanArrayOf(false) } @@ -374,7 +375,7 @@ internal fun AdbTextField( val colors = MaterialTheme.colorScheme Column(modifier = modifier.fillMaxWidth()) { - Text( + if (showLabel) Text( label, style = MaterialTheme.typography.labelSmall, fontWeight = FontWeight.Medium, diff --git a/app/src/main/java/com/droiddeck/launcher/update/AppUpdates.kt b/app/src/main/java/com/droiddeck/launcher/update/AppUpdates.kt index 222d308590..3a86e28af3 100644 --- a/app/src/main/java/com/droiddeck/launcher/update/AppUpdates.kt +++ b/app/src/main/java/com/droiddeck/launcher/update/AppUpdates.kt @@ -200,18 +200,31 @@ object AppUpdates { fun message(context: Context): String = context.getString(text, *args) } - fun follow(context: Context, catalog: Catalog?): Follow { + fun follow(context: Context, catalog: Catalog?): Follow = follow(context, catalog, installed()) + + internal fun follow(context: Context, catalog: Catalog?, me: Installed): Follow { stored(context)?.let { return it } - val me = installed() - val inferred = when { - me.pr != 0 -> Follow(Channel.TEST, me.pr) - catalog == null -> return Follow(Channel.STABLE) - catalog.stable != null && isRunning(catalog.stable, me) -> Follow(Channel.STABLE) - me.updatable -> Follow(Channel.NIGHTLY) - else -> Follow(Channel.STABLE) - } - setFollow(context, inferred) - return inferred + val guess = guessFollow(catalog, me) + if (guess.certain) setFollow(context, guess.follow) + return guess.follow + } + + internal class Guess(val follow: Follow, val certain: Boolean) + + /** + * Stable and Preview builds of one commit are the same APK. Preview history can include older Stable releases, + * so an overlapping older-build guess keeps the Stable default for this run without persisting it. + */ + internal fun guessFollow(catalog: Catalog?, me: Installed): Guess { + if (me.pr != 0) return Guess(Follow(Channel.TEST, me.pr), true) + val stable = catalog?.stable + if (stable != null && isRunning(stable, me)) return Guess(Follow(Channel.STABLE), true) + val publishedPreview = catalog != null && me.updatable && ( + catalog.preview?.let { isRunning(it, me) } == true || + catalog.recentPreviews.any { matchesInstalledCommit(it.commit, me.commit) } + ) + if (stable?.version?.let { compareVersions(me.version, it) < 0 } == true) return Guess(Follow(Channel.STABLE), !publishedPreview) + return Guess(Follow(if (publishedPreview) Channel.NIGHTLY else Channel.STABLE), false) } fun setFollow(context: Context, follow: Follow) { diff --git a/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt b/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt index 348e8ff1fb..ea06879faf 100644 --- a/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt +++ b/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt @@ -1,7 +1,11 @@ package com.droiddeck.launcher.wayland +import android.os.Handler +import android.os.HandlerThread +import android.os.Process import android.view.Choreographer import android.view.Surface +import com.droiddeck.launcher.session.SessionPrefs import com.droiddeck.launcher.session.SessionState object CompositorHost { @@ -14,8 +18,22 @@ object CompositorHost { @Volatile private var vsyncRunning = false - private val vsync = object : Choreographer.FrameCallback { + @Volatile + private var ownVsyncThread = true + + // The screen tick gets its own thread so a busy main thread cannot delay the compositor's frames. + private val vsyncThread: HandlerThread by lazy { + HandlerThread("droiddeck-vsync", Process.THREAD_PRIORITY_DISPLAY).apply { start() } + } + private val vsyncHandler: Handler by lazy { Handler(vsyncThread.looper) } + + @Volatile + private var vsyncGeneration = 0 + + // Each resume gets a new callback; one left queued from an earlier resume, on either thread, stops itself. + private fun vsyncCallback(generation: Int) = object : Choreographer.FrameCallback { override fun doFrame(frameTimeNanos: Long) { + if (generation != vsyncGeneration) return WaylandCompositor.nativeVsync(frameTimeNanos) if (vsyncRunning) Choreographer.getInstance().postFrameCallback(this) } @@ -34,6 +52,8 @@ object CompositorHost { refreshHz: Float, fpsLimit: Int, ): Boolean { + ownVsyncThread = SessionPrefs.vsyncThread(context) + WaylandCompositor.nativeSetRenderOnCommit(SessionPrefs.renderOnCommit(context)) pace(refreshHz, fpsLimit) if (!SessionState.running) WaylandCompositor.nativeSetOutputSize(outputWidth, outputHeight) if (started) { @@ -103,8 +123,14 @@ object CompositorHost { private fun resumeVsync() { if (vsyncRunning) return + val callback = vsyncCallback(++vsyncGeneration) vsyncRunning = true - Choreographer.getInstance().postFrameCallback(vsync) + WaylandCompositor.nativeLog("screen", if (ownVsyncThread) "screen tick runs on its own display-priority thread" else "screen tick runs on the main thread") + if (!ownVsyncThread) { + Choreographer.getInstance().postFrameCallback(callback) + return + } + vsyncHandler.post { Choreographer.getInstance().postFrameCallback(callback) } } private fun pauseVsync() { diff --git a/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java b/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java index 206b182805..7aefad5738 100644 --- a/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java +++ b/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java @@ -284,6 +284,8 @@ public final class WaylandCompositor { public static native void nativeSetFpsLimit(int fps); + public static native void nativeSetRenderOnCommit(boolean on); + public static native void nativeSetGpuTurbo(boolean on); public static native int nativeRaisePriority(int tid, int nice); diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index f78cf3014d..e07f0faded 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -3221,4 +3221,50 @@ المجموعات سحابية إعدادات السحابة + البحث في التطبيقات + لا توجد تطبيقات تطابق ”%1$s“. + إضافة أداة + جارٍ تحميل الأدوات… + لا توجد تطبيقات على هذا الجهاز توفّر أدوات. + أعرض + أضيق + أطول + أقصر + نقل إلى الأمام + نقل إلى الخلف + إعدادات الأداة + إزالة الأداة + إضافة إلى مجلد + مجلد جديد + إزالة من المجلد + معلومات التطبيق + إلغاء التثبيت + إعادة التسمية + فك التجميع + مجلد + اسم المجلد + عرض + كل التطبيقات + الألعاب + المنزّلة + النظام + المخفية + إخفاء + إظهار في التطبيقات + إزالة الاختصار + إضافة إلى التطبيقات + إضافة + لا توجد تطبيقات مخفية. + الاسم أ–ي + الاسم ي–أ + المثبّتة مؤخرًا + المحدّثة مؤخرًا + + %d تطبيق + تطبيق واحد + تطبيقان + %d تطبيقات + %d تطبيقًا + %d تطبيق + diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index 09e76582e9..0861e3525f 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -3071,4 +3071,47 @@ Colecciones Nube Configuración de nube + Buscar apps + Ninguna app coincide con «%1$s». + Agregar widget + Cargando widgets… + Ninguna app de este dispositivo ofrece widgets. + Más ancho + Más angosto + Más alto + Más bajo + Mover antes + Mover después + Configuración del widget + Quitar widget + Agregar a carpeta + Carpeta nueva + Quitar de la carpeta + Información de la app + Desinstalar + Cambiar nombre + Desagrupar + Carpeta + Nombre de la carpeta + Mostrar + Todas las apps + Juegos + Descargadas + Sistema + Ocultas + Ocultar + Mostrar en apps + Quitar acceso directo + Agregar a Apps + Agregar + No hay apps ocultas. + Nombre A–Z + Nombre Z–A + Instaladas recientemente + Actualizadas recientemente + + %d app + %d apps + %d apps + diff --git a/app/src/main/res/values-bg/strings.xml b/app/src/main/res/values-bg/strings.xml index 314b01f305..fecfd3a044 100644 --- a/app/src/main/res/values-bg/strings.xml +++ b/app/src/main/res/values-bg/strings.xml @@ -3085,4 +3085,46 @@ Колекции Облак Настройки на облака + Търсене на приложения + Няма приложения, отговарящи на „%1$s“. + Добавяне на приспособление + Приспособленията се зареждат… + Няма приложения с приспособления на това устройство. + По-широко + По-тясно + По-високо + По-ниско + Преместване по-рано + Преместване по-късно + Настройки на приспособлението + Премахване на приспособлението + Добавяне в папка + Нова папка + Премахване от папката + Информация за приложението + Деинсталиране + Преименуване + Разгрупиране + Папка + Име на папката + Показване + Всички приложения + Игри + Изтеглени + Системни + Скрити + Скриване + Показване в приложенията + Премахване на прекия път + Добавяне към приложенията + Добавяне + Няма скрити приложения. + Име А–Я + Име Я–А + Наскоро инсталирани + Наскоро актуализирани + + %d приложение + %d приложения + diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index e0278767d6..b9694894ef 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -3153,4 +3153,48 @@ Kolekce Cloud Nastavení cloudu + Hledat aplikace + Výrazu „%1$s“ neodpovídá žádná aplikace. + Přidat widget + Načítání widgetů… + Žádná aplikace v zařízení nenabízí widgety. + Širší + Užší + Vyšší + Nižší + Posunout dříve + Posunout později + Nastavení widgetu + Odebrat widget + Přidat do složky + Nová složka + Odebrat ze složky + Informace o aplikaci + Odinstalovat + Přejmenovat + Zrušit složku + Složka + Název složky + Zobrazit + Všechny aplikace + Hry + Stažené + Systémové + Skryté + Skrýt + Zobrazit v aplikacích + Odebrat zkratku + Přidat do aplikací + Přidat + Žádné skryté aplikace. + Název A–Z + Název Z–A + Nedávno nainstalované + Nedávno aktualizované + + %d aplikace + %d aplikace + %d aplikace + %d aplikací + diff --git a/app/src/main/res/values-da/strings.xml b/app/src/main/res/values-da/strings.xml index 789cbc762d..af13b452d1 100644 --- a/app/src/main/res/values-da/strings.xml +++ b/app/src/main/res/values-da/strings.xml @@ -3085,4 +3085,46 @@ Samlinger Sky Skyindstillinger + Søg i apps + Ingen apps matcher “%1$s”. + Tilføj widget + Indlæser widgets… + Ingen apps på enheden tilbyder widgets. + Bredere + Smallere + Højere + Lavere + Flyt tidligere + Flyt senere + Widgetindstillinger + Fjern widget + Føj til mappe + Ny mappe + Fjern fra mappe + Appinfo + Afinstaller + Omdøb + Opløs + Mappe + Mappenavn + Vis + Alle apps + Spil + Downloadet + System + Skjulte + Skjul + Vis i apps + Fjern genvej + Føj til Apps + Tilføj + Ingen skjulte apps. + Navn A–Å + Navn Å–A + Senest installeret + Senest opdateret + + %d app + %d apps + diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 1ddc2655d3..9ffcfe1fd0 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -3085,4 +3085,46 @@ Sammlungen Cloud Cloud-Einstellungen + Apps durchsuchen + Keine Apps passen zu „%1$s“. + Widget hinzufügen + Widgets werden geladen… + Keine App auf diesem Gerät bietet Widgets an. + Breiter + Schmaler + Höher + Niedriger + Nach vorne + Nach hinten + Widget-Einstellungen + Widget entfernen + Zu Ordner hinzufügen + Neuer Ordner + Aus Ordner entfernen + App-Info + Deinstallieren + Umbenennen + Auflösen + Ordner + Ordnername + Anzeigen + Alle Apps + Spiele + Heruntergeladen + System + Ausgeblendet + Ausblenden + In Apps anzeigen + Verknüpfung entfernen + Zu Apps hinzufügen + Hinzufügen + Keine ausgeblendeten Apps. + Name A–Z + Name Z–A + Zuletzt installiert + Zuletzt aktualisiert + + %d App + %d Apps + diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 85e3befcd8..c8588ac9c2 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -3085,4 +3085,46 @@ Συλλογές Cloud Ρυθμίσεις cloud + Αναζήτηση εφαρμογών + Καμία εφαρμογή δεν ταιριάζει με «%1$s». + Προσθήκη γραφικού στοιχείου + Φόρτωση γραφικών στοιχείων… + Καμία εφαρμογή στη συσκευή δεν προσφέρει γραφικά στοιχεία. + Πλατύτερο + Στενότερο + Ψηλότερο + Χαμηλότερο + Μετακίνηση νωρίτερα + Μετακίνηση αργότερα + Ρυθμίσεις γραφικού στοιχείου + Αφαίρεση γραφικού στοιχείου + Προσθήκη σε φάκελο + Νέος φάκελος + Αφαίρεση από φάκελο + Πληροφορίες εφαρμογής + Απεγκατάσταση + Μετονομασία + Κατάργηση ομάδας + Φάκελος + Όνομα φακέλου + Εμφάνιση + Όλες οι εφαρμογές + Παιχνίδια + Ληφθείσες + Συστήματος + Κρυφές + Απόκρυψη + Εμφάνιση στις εφαρμογές + Αφαίρεση συντόμευσης + Προσθήκη στις Εφαρμογές + Προσθήκη + Δεν υπάρχουν κρυφές εφαρμογές. + Όνομα Α–Ω + Όνομα Ω–Α + Πρόσφατα εγκατεστημένες + Πρόσφατα ενημερωμένες + + %d εφαρμογή + %d εφαρμογές + diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index f6d49f6f92..82af913320 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -3121,4 +3121,47 @@ Colecciones Nube Ajustes de nube + Buscar aplicaciones + Ninguna aplicación coincide con «%1$s». + Añadir widget + Cargando widgets… + Ninguna aplicación de este dispositivo ofrece widgets. + Más ancho + Más estrecho + Más alto + Más bajo + Mover antes + Mover después + Ajustes del widget + Quitar widget + Añadir a carpeta + Carpeta nueva + Quitar de la carpeta + Información de la aplicación + Desinstalar + Cambiar nombre + Desagrupar + Carpeta + Nombre de la carpeta + Mostrar + Todas las aplicaciones + Juegos + Descargadas + Sistema + Ocultas + Ocultar + Mostrar en aplicaciones + Quitar acceso directo + Añadir a Aplicaciones + Añadir + No hay aplicaciones ocultas. + Nombre A–Z + Nombre Z–A + Instaladas recientemente + Actualizadas recientemente + + %d aplicación + %d aplicaciones + %d aplicaciones + diff --git a/app/src/main/res/values-fi/strings.xml b/app/src/main/res/values-fi/strings.xml index 79737e2e0f..3ad1e92476 100644 --- a/app/src/main/res/values-fi/strings.xml +++ b/app/src/main/res/values-fi/strings.xml @@ -3085,4 +3085,46 @@ Kokoelmat Pilvi Pilviasetukset + Hae sovelluksia + Mikään sovellus ei vastaa hakua ”%1$s”. + Lisää widget + Ladataan widgettejä… + Mikään tämän laitteen sovellus ei tarjoa widgettejä. + Leveämpi + Kapeampi + Korkeampi + Matalampi + Siirrä aiemmaksi + Siirrä myöhemmäksi + Widgetin asetukset + Poista widget + Lisää kansioon + Uusi kansio + Poista kansiosta + Sovelluksen tiedot + Poista asennus + Nimeä uudelleen + Pura kansio + Kansio + Kansion nimi + Näytä + Kaikki sovellukset + Pelit + Ladatut + Järjestelmä + Piilotetut + Piilota + Näytä sovelluksissa + Poista pikakuvake + Lisää sovelluksiin + Lisää + Ei piilotettuja sovelluksia. + Nimi A–Ö + Nimi Ö–A + Äskettäin asennetut + Äskettäin päivitetyt + + %d sovellus + %d sovellusta + diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 97cb78aa59..ef4fdb8f56 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -3121,4 +3121,47 @@ Collections Cloud Paramètres cloud + Rechercher des applications + Aucune application ne correspond à « %1$s ». + Ajouter un widget + Chargement des widgets… + Aucune application de cet appareil ne propose de widgets. + Plus large + Plus étroit + Plus haut + Moins haut + Avancer + Reculer + Paramètres du widget + Retirer le widget + Ajouter à un dossier + Nouveau dossier + Retirer du dossier + Infos sur l’application + Désinstaller + Renommer + Dégrouper + Dossier + Nom du dossier + Afficher + Toutes les applications + Jeux + Téléchargées + Système + Masquées + Masquer + Afficher dans les applications + Retirer le raccourci + Ajouter aux applications + Ajouter + Aucune application masquée. + Nom A–Z + Nom Z–A + Installées récemment + Mises à jour récemment + + %d application + %d applications + %d applications + diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml index a1edf261e0..ea458fa238 100644 --- a/app/src/main/res/values-hi/strings.xml +++ b/app/src/main/res/values-hi/strings.xml @@ -3085,4 +3085,46 @@ संग्रह क्लाउड क्लाउड सेटिंग्स + ऐप खोजें + “%1$s” से कोई ऐप मेल नहीं खाता। + विजेट जोड़ें + विजेट लोड हो रहे हैं… + इस डिवाइस पर कोई ऐप विजेट नहीं देता। + चौड़ा + पतला + लंबा + छोटा + पहले ले जाएँ + बाद में ले जाएँ + विजेट सेटिंग + विजेट हटाएँ + फ़ोल्डर में जोड़ें + नया फ़ोल्डर + फ़ोल्डर से हटाएँ + ऐप की जानकारी + अनइंस्टॉल करें + नाम बदलें + समूह तोड़ें + फ़ोल्डर + फ़ोल्डर का नाम + दिखाएँ + सभी ऐप + गेम + डाउनलोड किए गए + सिस्टम + छिपे हुए + छिपाएँ + ऐप में दिखाएँ + शॉर्टकट हटाएँ + ऐप में जोड़ें + जोड़ें + कोई छिपा हुआ ऐप नहीं। + नाम A–Z + नाम Z–A + हाल ही में इंस्टॉल किए गए + हाल ही में अपडेट किए गए + + %d ऐप + %d ऐप + diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index 747b7ed5c1..8d8f2774de 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -3085,4 +3085,46 @@ Gyűjtemények Felhő Felhőbeállítások + Alkalmazások keresése + Egy alkalmazás sem felel meg ennek: „%1$s”. + Modul hozzáadása + Modulok betöltése… + Az eszközön egyik alkalmazás sem kínál modult. + Szélesebb + Keskenyebb + Magasabb + Alacsonyabb + Előrébb + Hátrébb + Modulbeállítások + Modul eltávolítása + Hozzáadás mappához + Új mappa + Eltávolítás a mappából + Alkalmazásinformáció + Eltávolítás + Átnevezés + Szétbontás + Mappa + Mappa neve + Megjelenítés + Összes alkalmazás + Játékok + Letöltött + Rendszer + Rejtett + Elrejtés + Megjelenítés az alkalmazások között + Parancsikon eltávolítása + Hozzáadás az alkalmazásokhoz + Hozzáadás + Nincsenek rejtett alkalmazások. + Név A–Z + Név Z–A + Nemrég telepített + Nemrég frissített + + %d alkalmazás + %d alkalmazás + diff --git a/app/src/main/res/values-in/strings.xml b/app/src/main/res/values-in/strings.xml index 79291d8e70..c0c4fa21fe 100644 --- a/app/src/main/res/values-in/strings.xml +++ b/app/src/main/res/values-in/strings.xml @@ -3075,4 +3075,45 @@ Koleksi Cloud Pengaturan cloud + Cari aplikasi + Tidak ada aplikasi yang cocok dengan “%1$s”. + Tambahkan widget + Memuat widget… + Tidak ada aplikasi di perangkat ini yang menyediakan widget. + Lebih lebar + Lebih sempit + Lebih tinggi + Lebih pendek + Pindahkan ke depan + Pindahkan ke belakang + Setelan widget + Hapus widget + Tambahkan ke folder + Folder baru + Keluarkan dari folder + Info aplikasi + Uninstal + Ganti nama + Pisahkan + Folder + Nama folder + Tampilkan + Semua aplikasi + Game + Didownload + Sistem + Tersembunyi + Sembunyikan + Tampilkan di aplikasi + Hapus pintasan + Tambahkan ke Aplikasi + Tambahkan + Tidak ada aplikasi tersembunyi. + Nama A–Z + Nama Z–A + Baru diinstal + Baru diperbarui + + %d aplikasi + diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index bbe5351461..c20bdc1513 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -3119,4 +3119,47 @@ Raccolte Cloud Impostazioni cloud + Cerca app + Nessuna app corrisponde a «%1$s». + Aggiungi widget + Caricamento widget… + Nessuna app su questo dispositivo offre widget. + Più largo + Più stretto + Più alto + Più basso + Sposta prima + Sposta dopo + Impostazioni widget + Rimuovi widget + Aggiungi a cartella + Nuova cartella + Rimuovi dalla cartella + Info app + Disinstalla + Rinomina + Separa + Cartella + Nome cartella + Mostra + Tutte le app + Giochi + Scaricate + Sistema + Nascoste + Nascondi + Mostra nelle app + Rimuovi scorciatoia + Aggiungi ad App + Aggiungi + Nessuna app nascosta. + Nome A–Z + Nome Z–A + Installate di recente + Aggiornate di recente + + %d app + %d app + %d app + diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index 19f6dbfaee..87a910caef 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -3062,4 +3062,45 @@ コレクション クラウド クラウド設定 + アプリを検索 + 「%1$s」に一致するアプリはありません。 + ウィジェットを追加 + ウィジェットを読み込み中… + このデバイスにはウィジェットを提供するアプリがありません。 + 幅を広く + 幅を狭く + 高く + 低く + 前へ移動 + 後ろへ移動 + ウィジェットの設定 + ウィジェットを削除 + フォルダに追加 + 新しいフォルダ + フォルダから削除 + アプリ情報 + アンインストール + 名前を変更 + グループを解除 + フォルダ + フォルダ名 + 表示 + すべてのアプリ + ゲーム + ダウンロード済み + システム + 非表示 + 非表示にする + アプリに表示 + ショートカットを削除 + アプリに追加 + 追加 + 非表示のアプリはありません。 + 名前 A–Z + 名前 Z–A + 最近インストール + 最近更新 + + %d 個のアプリ + diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index 9163a3a7d7..10d6fd46dc 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -3062,4 +3062,45 @@ 컬렉션 클라우드 클라우드 설정 + 앱 검색 + ‘%1$s’와(과) 일치하는 앱이 없습니다. + 위젯 추가 + 위젯 불러오는 중… + 이 기기에 위젯을 제공하는 앱이 없습니다. + 더 넓게 + 더 좁게 + 더 높게 + 더 낮게 + 앞으로 이동 + 뒤로 이동 + 위젯 설정 + 위젯 삭제 + 폴더에 추가 + 새 폴더 + 폴더에서 제거 + 앱 정보 + 제거 + 이름 변경 + 그룹 해제 + 폴더 + 폴더 이름 + 표시 + 모든 앱 + 게임 + 다운로드됨 + 시스템 + 숨김 + 숨기기 + 앱에 표시 + 바로가기 삭제 + 앱에 추가 + 추가 + 숨긴 앱이 없습니다. + 이름 A–Z + 이름 Z–A + 최근 설치 + 최근 업데이트 + + 앱 %d개 + diff --git a/app/src/main/res/values-ms/strings.xml b/app/src/main/res/values-ms/strings.xml index eb41beb9b0..098f2429a2 100644 --- a/app/src/main/res/values-ms/strings.xml +++ b/app/src/main/res/values-ms/strings.xml @@ -3060,4 +3060,45 @@ Koleksi Awan Tetapan awan + Cari apl + Tiada apl sepadan dengan “%1$s”. + Tambah widget + Memuatkan widget… + Tiada apl pada peranti ini yang menawarkan widget. + Lebih lebar + Lebih sempit + Lebih tinggi + Lebih rendah + Alih ke depan + Alih ke belakang + Tetapan widget + Alih keluar widget + Tambah pada folder + Folder baharu + Alih keluar daripada folder + Maklumat apl + Nyahpasang + Namakan semula + Leraikan + Folder + Nama folder + Tunjukkan + Semua apl + Permainan + Dimuat turun + Sistem + Tersembunyi + Sembunyikan + Tunjukkan dalam apl + Alih keluar pintasan + Tambah pada Apl + Tambah + Tiada apl tersembunyi. + Nama A–Z + Nama Z–A + Dipasang baru-baru ini + Dikemas kini baru-baru ini + + %d apl + diff --git a/app/src/main/res/values-nb/strings.xml b/app/src/main/res/values-nb/strings.xml index 75653c225f..e95a57c22b 100644 --- a/app/src/main/res/values-nb/strings.xml +++ b/app/src/main/res/values-nb/strings.xml @@ -3085,4 +3085,46 @@ Samlinger Sky Skyinnstillinger + Søk i apper + Ingen apper samsvarer med «%1$s». + Legg til modul + Laster inn moduler… + Ingen apper på enheten tilbyr moduler. + Bredere + Smalere + Høyere + Lavere + Flytt tidligere + Flytt senere + Modulinnstillinger + Fjern modul + Legg til i mappe + Ny mappe + Fjern fra mappe + Appinfo + Avinstaller + Gi nytt navn + Løs opp + Mappe + Mappenavn + Vis + Alle apper + Spill + Nedlastet + System + Skjult + Skjul + Vis i apper + Fjern snarvei + Legg til i Apper + Legg til + Ingen skjulte apper. + Navn A–Å + Navn Å–A + Nylig installert + Nylig oppdatert + + %d app + %d apper + diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 53748c36ab..5cd7fdf36d 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -3085,4 +3085,46 @@ Collecties Cloud Cloudinstellingen + Apps zoeken + Geen apps gevonden voor ‘%1$s’. + Widget toevoegen + Widgets laden… + Geen enkele app op dit apparaat biedt widgets. + Breder + Smaller + Hoger + Lager + Naar voren + Naar achteren + Widgetinstellingen + Widget verwijderen + Toevoegen aan map + Nieuwe map + Uit map verwijderen + App-info + Verwijderen + Naam wijzigen + Opheffen + Map + Mapnaam + Tonen + Alle apps + Games + Gedownload + Systeem + Verborgen + Verbergen + Tonen in apps + Snelkoppeling verwijderen + Toevoegen aan Apps + Toevoegen + Geen verborgen apps. + Naam A–Z + Naam Z–A + Recent geïnstalleerd + Recent bijgewerkt + + %d app + %d apps + diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 37619c513a..4e87191fe1 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -3156,4 +3156,48 @@ Kolekcje Chmura Ustawienia chmury + Szukaj aplikacji + Żadna aplikacja nie pasuje do „%1$s”. + Dodaj widżet + Wczytywanie widżetów… + Żadna aplikacja na tym urządzeniu nie oferuje widżetów. + Szerszy + Węższy + Wyższy + Niższy + Przesuń wcześniej + Przesuń później + Ustawienia widżetu + Usuń widżet + Dodaj do folderu + Nowy folder + Usuń z folderu + Informacje o aplikacji + Odinstaluj + Zmień nazwę + Rozgrupuj + Folder + Nazwa folderu + Pokaż + Wszystkie aplikacje + Gry + Pobrane + Systemowe + Ukryte + Ukryj + Pokaż w aplikacjach + Usuń skrót + Dodaj do aplikacji + Dodaj + Brak ukrytych aplikacji. + Nazwa A–Z + Nazwa Z–A + Ostatnio zainstalowane + Ostatnio zaktualizowane + + %d aplikacja + %d aplikacje + %d aplikacji + %d aplikacji + diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml index 177799c1a2..ceac1c5343 100644 --- a/app/src/main/res/values-pt-rPT/strings.xml +++ b/app/src/main/res/values-pt-rPT/strings.xml @@ -3119,4 +3119,47 @@ Coleções Nuvem Definições da nuvem + Pesquisar aplicações + Nenhuma aplicação corresponde a “%1$s”. + Adicionar widget + A carregar widgets… + Nenhuma aplicação neste dispositivo oferece widgets. + Mais largo + Mais estreito + Mais alto + Mais baixo + Mover para antes + Mover para depois + Definições do widget + Remover widget + Adicionar a pasta + Nova pasta + Remover da pasta + Informações da aplicação + Desinstalar + Mudar o nome + Desagrupar + Pasta + Nome da pasta + Mostrar + Todas as aplicações + Jogos + Transferidas + Sistema + Ocultas + Ocultar + Mostrar nas aplicações + Remover atalho + Adicionar às Aplicações + Adicionar + Nenhuma aplicação oculta. + Nome A–Z + Nome Z–A + Instaladas recentemente + Atualizadas recentemente + + %d aplicação + %d aplicações + %d aplicações + diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 2bdda9aacd..825ef7b95d 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -3119,4 +3119,47 @@ Coleções Nuvem Configurações da nuvem + Pesquisar apps + Nenhum app corresponde a “%1$s”. + Adicionar widget + Carregando widgets… + Nenhum app neste dispositivo oferece widgets. + Mais largo + Mais estreito + Mais alto + Mais baixo + Mover para antes + Mover para depois + Configurações do widget + Remover widget + Adicionar à pasta + Nova pasta + Remover da pasta + Informações do app + Desinstalar + Renomear + Desagrupar + Pasta + Nome da pasta + Mostrar + Todos os apps + Jogos + Baixados + Sistema + Ocultos + Ocultar + Mostrar nos apps + Remover atalho + Adicionar aos Apps + Adicionar + Nenhum app oculto. + Nome A–Z + Nome Z–A + Instalados recentemente + Atualizados recentemente + + %d app + %d apps + %d apps + diff --git a/app/src/main/res/values-ro/strings.xml b/app/src/main/res/values-ro/strings.xml index 49a0503c69..b95ef48573 100644 --- a/app/src/main/res/values-ro/strings.xml +++ b/app/src/main/res/values-ro/strings.xml @@ -3119,4 +3119,47 @@ Colecții Cloud Setări cloud + Caută aplicații + Nicio aplicație nu se potrivește cu „%1$s”. + Adaugă widget + Se încarcă widgeturile… + Nicio aplicație de pe acest dispozitiv nu oferă widgeturi. + Mai lat + Mai îngust + Mai înalt + Mai scund + Mută mai devreme + Mută mai târziu + Setări widget + Elimină widgetul + Adaugă în dosar + Dosar nou + Elimină din dosar + Informații despre aplicație + Dezinstalează + Redenumește + Degrupează + Dosar + Numele dosarului + Afișează + Toate aplicațiile + Jocuri + Descărcate + Sistem + Ascunse + Ascunde + Afișează în aplicații + Elimină comanda rapidă + Adaugă în Aplicații + Adaugă + Nicio aplicație ascunsă. + Nume A–Z + Nume Z–A + Instalate recent + Actualizate recent + + %d aplicație + %d aplicații + %d de aplicații + diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index b4d440f2c9..483d86ab5a 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -3155,4 +3155,48 @@ Коллекции Облако Настройки облака + Поиск приложений + Нет приложений по запросу «%1$s». + Добавить виджет + Загрузка виджетов… + На этом устройстве нет приложений с виджетами. + Шире + Уже + Выше + Ниже + Переместить раньше + Переместить позже + Настройки виджета + Удалить виджет + Добавить в папку + Новая папка + Убрать из папки + О приложении + Удалить + Переименовать + Разгруппировать + Папка + Название папки + Показать + Все приложения + Игры + Загруженные + Системные + Скрытые + Скрыть + Показывать в приложениях + Удалить ярлык + Добавить в приложения + Добавить + Скрытых приложений нет. + Название А–Я + Название Я–А + Недавно установленные + Недавно обновлённые + + %d приложение + %d приложения + %d приложений + %d приложения + diff --git a/app/src/main/res/values-sv/strings.xml b/app/src/main/res/values-sv/strings.xml index 35c26e8f21..72c27705b9 100644 --- a/app/src/main/res/values-sv/strings.xml +++ b/app/src/main/res/values-sv/strings.xml @@ -3085,4 +3085,46 @@ Samlingar Moln Molninställningar + Sök appar + Inga appar matchar ”%1$s”. + Lägg till widget + Läser in widgetar… + Inga appar på enheten erbjuder widgetar. + Bredare + Smalare + Högre + Lägre + Flytta tidigare + Flytta senare + Widgetinställningar + Ta bort widget + Lägg till i mapp + Ny mapp + Ta bort från mapp + Appinfo + Avinstallera + Byt namn + Dela upp + Mapp + Mappnamn + Visa + Alla appar + Spel + Nedladdade + System + Dolda + Dölj + Visa i appar + Ta bort genväg + Lägg till i Appar + Lägg till + Inga dolda appar. + Namn A–Ö + Namn Ö–A + Senast installerade + Senast uppdaterade + + %d app + %d appar + diff --git a/app/src/main/res/values-th/strings.xml b/app/src/main/res/values-th/strings.xml index 348740686b..9cdb0a55b3 100644 --- a/app/src/main/res/values-th/strings.xml +++ b/app/src/main/res/values-th/strings.xml @@ -3060,4 +3060,45 @@ คอลเลกชัน คลาวด์ การตั้งค่าคลาวด์ + ค้นหาแอป + ไม่มีแอปที่ตรงกับ “%1$s” + เพิ่มวิดเจ็ต + กำลังโหลดวิดเจ็ต… + ไม่มีแอปในอุปกรณ์นี้ที่มีวิดเจ็ต + กว้างขึ้น + แคบลง + สูงขึ้น + เตี้ยลง + ย้ายไปก่อน + ย้ายไปหลัง + การตั้งค่าวิดเจ็ต + นำวิดเจ็ตออก + เพิ่มลงในโฟลเดอร์ + โฟลเดอร์ใหม่ + นำออกจากโฟลเดอร์ + ข้อมูลแอป + ถอนการติดตั้ง + เปลี่ยนชื่อ + ยกเลิกกลุ่ม + โฟลเดอร์ + ชื่อโฟลเดอร์ + แสดง + แอปทั้งหมด + เกม + ที่ดาวน์โหลด + ระบบ + ที่ซ่อนไว้ + ซ่อน + แสดงในแอป + นำทางลัดออก + เพิ่มลงในแอป + เพิ่ม + ไม่มีแอปที่ซ่อนไว้ + ชื่อ A–Z + ชื่อ Z–A + ติดตั้งล่าสุด + อัปเดตล่าสุด + + %d แอป + diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index 78cdc1f700..3dea1e5bc6 100644 --- a/app/src/main/res/values-tr/strings.xml +++ b/app/src/main/res/values-tr/strings.xml @@ -3087,4 +3087,46 @@ Koleksiyonlar Bulut Bulut ayarları + Uygulama ara + “%1$s” ile eşleşen uygulama yok. + Widget ekle + Widget’lar yükleniyor… + Bu cihazdaki hiçbir uygulama widget sunmuyor. + Daha geniş + Daha dar + Daha uzun + Daha kısa + Öne taşı + Arkaya taşı + Widget ayarları + Widget’ı kaldır + Klasöre ekle + Yeni klasör + Klasörden çıkar + Uygulama bilgileri + Kaldır + Yeniden adlandır + Grubu çöz + Klasör + Klasör adı + Göster + Tüm uygulamalar + Oyunlar + İndirilenler + Sistem + Gizli + Gizle + Uygulamalarda göster + Kısayolu kaldır + Uygulamalara ekle + Ekle + Gizli uygulama yok. + Ad A–Z + Ad Z–A + Son yüklenenler + Son güncellenenler + + %d uygulama + %d uygulama + diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml index 050fd0fdcf..3084c36ba8 100644 --- a/app/src/main/res/values-uk/strings.xml +++ b/app/src/main/res/values-uk/strings.xml @@ -3153,4 +3153,48 @@ Колекції Хмара Налаштування хмари + Пошук застосунків + Немає застосунків за запитом «%1$s». + Додати віджет + Завантаження віджетів… + На цьому пристрої немає застосунків із віджетами. + Ширше + Вужче + Вище + Нижче + Перемістити раніше + Перемістити пізніше + Налаштування віджета + Вилучити віджет + Додати до папки + Нова папка + Вилучити з папки + Про застосунок + Видалити + Перейменувати + Розгрупувати + Папка + Назва папки + Показати + Усі застосунки + Ігри + Завантажені + Системні + Приховані + Приховати + Показувати в застосунках + Вилучити ярлик + Додати до застосунків + Додати + Прихованих застосунків немає. + Назва А–Я + Назва Я–А + Нещодавно встановлені + Нещодавно оновлені + + %d застосунок + %d застосунки + %d застосунків + %d застосунку + diff --git a/app/src/main/res/values-vi/strings.xml b/app/src/main/res/values-vi/strings.xml index 9c75292d7f..0cfe20866d 100644 --- a/app/src/main/res/values-vi/strings.xml +++ b/app/src/main/res/values-vi/strings.xml @@ -3060,4 +3060,45 @@ Bộ sưu tập Đám mây Cài đặt đám mây + Tìm ứng dụng + Không có ứng dụng nào khớp với “%1$s”. + Thêm tiện ích + Đang tải tiện ích… + Không có ứng dụng nào trên thiết bị này cung cấp tiện ích. + Rộng hơn + Hẹp hơn + Cao hơn + Thấp hơn + Chuyển lên trước + Chuyển ra sau + Cài đặt tiện ích + Xóa tiện ích + Thêm vào thư mục + Thư mục mới + Xóa khỏi thư mục + Thông tin ứng dụng + Gỡ cài đặt + Đổi tên + Bỏ nhóm + Thư mục + Tên thư mục + Hiển thị + Tất cả ứng dụng + Trò chơi + Đã tải xuống + Hệ thống + Đã ẩn + Ẩn + Hiện trong ứng dụng + Xóa lối tắt + Thêm vào Ứng dụng + Thêm + Không có ứng dụng nào bị ẩn. + Tên A–Z + Tên Z–A + Mới cài đặt + Mới cập nhật + + %d ứng dụng + diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index ade2de5de3..b14b5663ad 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -3010,6 +3010,10 @@ 6DoF 虚拟屏幕 在光线充足的房间内缓慢环顾四周。\n不要遮挡追踪摄像头,并面向家具等有明显细节的物体。 DroidDeck ChArUco 30 mm + Steam 因非法指令(SIGILL)停止。这可能是 CPU 指令兼容问题,也可能是客户端崩溃。请分享日志并附上设备信息。 + 可尝试“Steam 设置 → Steam 客户端 → x86-64(实验)”。此选项需要额外下载,运行速度也可能更慢。 + Linux 图形驱动未找到可用的 Vulkan 设备。请确认所选 Linux GPU 驱动支持这颗 GPU。 + 当前配置缺少兼容这颗 GPU 的 Linux Vulkan 驱动,会话无法启动。Adreno Turnip 驱动不能为联发科/Mali GPU 增加支持。 内存 会话前关闭缓存的应用 会话开始时关闭 Android 留在后台的应用,让游戏有更多内存可用。需要开启无线调试。 @@ -3064,4 +3068,45 @@ 收藏集 云 云设置 + 搜索应用 + 没有与“%1$s”匹配的应用。 + 添加微件 + 正在加载微件… + 此设备上没有提供微件的应用。 + 加宽 + 缩窄 + 加高 + 降低 + 前移 + 后移 + 微件设置 + 移除微件 + 添加到文件夹 + 新建文件夹 + 从文件夹中移除 + 应用信息 + 卸载 + 重命名 + 取消分组 + 文件夹 + 文件夹名称 + 显示 + 所有应用 + 游戏 + 已下载 + 系统 + 已隐藏 + 隐藏 + 在应用中显示 + 移除快捷方式 + 添加到应用 + 添加 + 没有隐藏的应用。 + 名称 A–Z + 名称 Z–A + 最近安装 + 最近更新 + + %d 个应用 + diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml index 94ed816a9f..4a9c6ee963 100644 --- a/app/src/main/res/values-zh-rHK/strings.xml +++ b/app/src/main/res/values-zh-rHK/strings.xml @@ -3009,6 +3009,10 @@ 6DoF 虛擬螢幕 在光線充足的房間內緩慢環顧四周。\n不要遮擋追蹤攝影機,並面向家具等有明顯細節的物體。 DroidDeck ChArUco 30 mm + Steam 因非法指令(SIGILL)停止。這可能是 CPU 指令兼容問題,也可能是客戶端崩潰。請分享記錄並附上裝置資訊。 + 可嘗試「Steam 設定 → Steam 客戶端 → x86-64(實驗)」。此選項需要額外下載,執行速度也可能更慢。 + Linux 圖形驅動程式未找到可用的 Vulkan 裝置。請確認所選 Linux GPU 驅動程式支援這顆 GPU。 + 目前設定缺少兼容這顆 GPU 的 Linux Vulkan 驅動程式,工作階段無法啟動。Adreno Turnip 驅動程式無法為聯發科/Mali GPU 增加支援。 記憶體 工作階段前關閉快取的應用程式 工作階段開始時關閉 Android 留在背景的應用程式,讓遊戲有更多記憶體可用。需要開啟無線偵錯。 @@ -3063,4 +3067,45 @@ 收藏集 雲端 雲端設定 + 搜尋應用程式 + 沒有符合「%1$s」的應用程式。 + 新增小工具 + 正在載入小工具… + 此裝置上沒有提供小工具的應用程式。 + 加闊 + 收窄 + 加高 + 降低 + 向前移 + 向後移 + 小工具設定 + 移除小工具 + 加入資料夾 + 新資料夾 + 從資料夾移除 + 應用程式資料 + 解除安裝 + 重新命名 + 取消組合 + 資料夾 + 資料夾名稱 + 顯示 + 所有應用程式 + 遊戲 + 已下載 + 系統 + 已隱藏 + 隱藏 + 在應用程式中顯示 + 移除捷徑 + 加入應用程式 + 新增 + 沒有隱藏的應用程式。 + 名稱 A–Z + 名稱 Z–A + 最近安裝 + 最近更新 + + %d 個應用程式 + diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index 0c3257ead8..9d5adf6aee 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -3009,6 +3009,10 @@ 6DoF 虛擬螢幕 在光線充足的房間內緩慢環顧四周。\n不要遮擋追蹤攝影機,並面向家具等有明顯細節的物體。 DroidDeck ChArUco 30 mm + Steam 因非法指令(SIGILL)停止。這可能是 CPU 指令相容問題,也可能是用戶端當機。請分享記錄並附上裝置資訊。 + 可嘗試「Steam 設定 → Steam 用戶端 → x86-64(實驗)」。此選項需要額外下載,執行速度也可能更慢。 + Linux 圖形驅動程式未找到可用的 Vulkan 裝置。請確認所選 Linux GPU 驅動程式支援這顆 GPU。 + 目前設定缺少相容這顆 GPU 的 Linux Vulkan 驅動程式,工作階段無法啟動。Adreno Turnip 驅動程式無法為聯發科/Mali GPU 增加支援。 記憶體 工作階段前關閉快取的應用程式 工作階段開始時關閉 Android 留在背景的應用程式,讓遊戲有更多記憶體可用。需要開啟無線偵錯。 @@ -3063,4 +3067,45 @@ 收藏集 雲端 雲端設定 + 搜尋應用程式 + 沒有符合「%1$s」的應用程式。 + 新增小工具 + 正在載入小工具… + 這部裝置上沒有提供小工具的應用程式。 + 加寬 + 縮窄 + 加高 + 降低 + 往前移 + 往後移 + 小工具設定 + 移除小工具 + 新增至資料夾 + 新資料夾 + 從資料夾移除 + 應用程式資訊 + 解除安裝 + 重新命名 + 取消群組 + 資料夾 + 資料夾名稱 + 顯示 + 所有應用程式 + 遊戲 + 已下載 + 系統 + 已隱藏 + 隱藏 + 在應用程式中顯示 + 移除捷徑 + 新增至應用程式 + 新增 + 沒有隱藏的應用程式。 + 名稱 A–Z + 名稱 Z–A + 最近安裝 + 最近更新 + + %d 個應用程式 + diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index fc6649cc86..ad44ccba46 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -800,6 +800,10 @@ Session Session logs Saved after each session + Game debug logs + Include Proton, Wine and graphics diagnostics on the next game launch. Can reduce performance and use more storage. + Restart this session to save game debug logs + Couldn\'t update logging. Check the switch and try again. Debugging tools Latest session logs Saved session logs @@ -990,6 +994,12 @@ Open Settings → Developer options → Wireless debugging and turn it on Tap “Pair device with pairing code” Type the code into the DroidDeck notification + In About phone, tap Build number 7 times + Turn on Wireless debugging + Open Wireless debugging, then tap “Pair device with pairing code” + Build number + Wireless debugging + Pair device with pairing code Waiting for the pairing pop-up… Pop-up found. Enter its code in the notification. Status @@ -1075,6 +1085,48 @@ Android apps %1$d apps No launchable Android apps found. + Search apps + No apps match “%1$s”. + Add widget + Loading widgets… + No apps on this device offer widgets. + Wider + Narrower + Taller + Shorter + Move earlier + Move later + Widget settings + Remove widget + Add to folder + New folder + Remove from folder + App info + Uninstall + Rename + Ungroup + Folder + Folder name + Show + All apps + Games + Downloaded + System + Hidden + Hide + Show in apps + Remove shortcut + Add to Apps + Add + No hidden apps. + + %d app + %d apps + + Name A–Z + Name Z–A + Recently installed + Recently updated ● Desktop installed Installs on first open Available to install @@ -1849,6 +1901,7 @@ Applying the setting… Wireless debugging command failed Wireless debugging setup + Wireless debugging setup progress Asks for the Wireless debugging pairing code while Settings is open Pair Wireless debugging Turn on Wireless debugging, then tap “Pair device with pairing code”. @@ -3166,6 +3219,10 @@ Saved views can be recalculated. Start a new calibration to capture in the current tracking frame. Hand model checksum mismatch OpenCV could not load + Steam stopped with an illegal instruction (SIGILL). This can be a CPU instruction compatibility problem or a client crash. Share the logs with your device details. + You can try Steam settings → Steam client → x86-64 (experimental). It needs an additional download and may run more slowly. + The Linux graphics driver could not find a usable Vulkan device. Check that the selected Linux GPU driver supports this GPU. + This session cannot start because this GPU has no compatible Linux Vulkan driver in the current setup. Adreno Turnip drivers cannot enable support for MediaTek/Mali GPUs. Memory Clear cached apps before a session When a session starts, DroidDeck closes the apps Android keeps parked in the background, so the game has more memory. Wireless debugging must be on. diff --git a/app/src/test/java/com/droiddeck/launcher/core/DeviceReportCpuTest.kt b/app/src/test/java/com/droiddeck/launcher/core/DeviceReportCpuTest.kt new file mode 100644 index 0000000000..88520b21c6 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/core/DeviceReportCpuTest.kt @@ -0,0 +1,20 @@ +package com.droiddeck.launcher.core + +import org.junit.Assert.assertEquals +import org.junit.Test + +class DeviceReportCpuTest { + @Test fun onlyFeatureListsAreReportedAndDifferentCoreCapabilitiesAreKept() { + val cpuInfo = """ + processor : 0 + Features : fp asimd aes + Serial : private-device-id + processor : 1 + Features : fp asimd aes atomics + processor : 2 + Features : fp asimd aes + """.trimIndent() + assertEquals("fp asimd aes | fp asimd aes atomics", DeviceReport.cpuFeaturesSummary(cpuInfo)) + assertEquals("not reported", DeviceReport.cpuFeaturesSummary("processor : 0\n")) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/core/LogRedactorTest.kt b/app/src/test/java/com/droiddeck/launcher/core/LogRedactorTest.kt index 38849c41a8..b93c439bf2 100644 --- a/app/src/test/java/com/droiddeck/launcher/core/LogRedactorTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/core/LogRedactorTest.kt @@ -3,9 +3,14 @@ package com.droiddeck.launcher.core import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue +import org.junit.Rule import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.StringWriter class LogRedactorTest { + @get:Rule val tmp = TemporaryFolder() + @Test fun labelledJwtIsRedacted() { val out = LogRedactor.redact("Using JWT 25484942796017334") assertFalse(out.contains("25484942796017334")) @@ -226,6 +231,103 @@ class LogRedactorTest { assertEquals(once, LogRedactor.redactForShare(once)) } + @Test fun anOversizedDirectInputIsWithheldBeforeRegex() { + val secret = "sessionid=abcdef123456" + val line = "x".repeat(LogRedactor.MAX_LINE_LENGTH) + secret + assertEquals(LogRedactor.OVERSIZED_LINE, LogRedactor.redact(line)) + assertEquals(LogRedactor.OVERSIZED_LINE, LogRedactor.redactForShare(line)) + } + + @Test fun streamWithholdsAnOversizedLogicalLineWholeAndContinues() { + val secret = "sessionid=abcdef123456" + val src = tmp.newFile("oversized.log") + src.writeText( + "before\r" + + "x".repeat(LogRedactor.MAX_LINE_LENGTH - 3) + secret + "\r\n" + + "after $secret" + ) + val out = StringWriter() + + LogRedactor.scrubTo(src, out) + + assertEquals( + "before\n${LogRedactor.OVERSIZED_LINE}\nafter sessionid=\n", + out.toString(), + ) + assertFalse(out.toString().contains("abcdef123456")) + } + + @Test fun sharedStreamDistinguishesOversizedAndUnsupportedLines() { + val src = tmp.newFile("shared-lines.log") + src.writeText( + "x".repeat(LogRedactor.MAX_LINE_LENGTH + 1) + "\n" + + "private-prefix\u0000private-suffix\n" + + "after sessionid=abcdef123456\n" + ) + val out = StringWriter() + + assertTrue(LogRedactor.scrubForShare(src, out)) + + assertEquals( + "${LogRedactor.OVERSIZED_LINE}\n" + + "\n" + + "after sessionid=\n", + out.toString(), + ) + } + + @Test fun aMaximumLengthLineBeforeCrLfIsStillScrubbed() { + val src = tmp.newFile("maximum.log") + val line = "x ".repeat(LogRedactor.MAX_LINE_LENGTH / 2) + src.writeText(line + "\r\n") + val out = StringWriter() + + LogRedactor.scrubTo(src, out) + + assertEquals(line + "\n", out.toString()) + assertFalse(out.toString().contains(LogRedactor.OVERSIZED_LINE)) + } + + @Test fun streamingScrubStopsBetweenInputChunks() { + val src = tmp.newFile("cancelled.log") + src.writeText("first safe line\n" + "x".repeat(20_000) + " sessionid=abcdef123456\n") + val out = StringWriter() + var checks = 0 + + val complete = LogRedactor.scrubTo(src, out) { ++checks >= 4 } + + assertFalse(complete) + assertFalse(out.toString().contains("abcdef123456")) + assertTrue(checks >= 4) + } + + @Test fun manyLearnedAccountsKeepBoundariesAndLiteralNames() { + val users = tmp.newFile("loginusers.vdf") + users.writeText((0 until 40).joinToString("\n") { + "\"AccountName\" \"probe_account_$it\"" + } + "\n\"PersonaName\" \"Player.+[40]\"\n") + try { + LogRedactor.learnAccounts(users) + assertEquals("owner= persona=", + LogRedactor.redact("owner=probe_account_39 persona=Player.+[40]")) + assertEquals("owner=probe_account_390", LogRedactor.redact("owner=probe_account_390")) + } finally { + LogRedactor.learnAccounts(tmp.root.resolve("missing-users")) + } + } + + @Test fun manyLearnedAddressesKeepOtherAddresses() { + val link = tmp.newFile("droiddeck-net") + link.writeText((1..40).joinToString("\n") { "addr 203.0.113.$it 24" }) + try { + LogRedactor.learnOwnAddresses(link) + assertEquals("local= server=203.0.113.200", + LogRedactor.redact("local=203.0.113.40 server=203.0.113.200")) + } finally { + LogRedactor.learnOwnAddresses(tmp.root.resolve("missing-network")) + } + } + @Test fun learnedAccountsComeFromBothClients() { val root = java.nio.file.Files.createTempDirectory("redactor").toFile() try { diff --git a/app/src/test/java/com/droiddeck/launcher/gpu/TurnipDriverAutoTest.kt b/app/src/test/java/com/droiddeck/launcher/gpu/TurnipDriverAutoTest.kt index 95713589ea..123fcee195 100644 --- a/app/src/test/java/com/droiddeck/launcher/gpu/TurnipDriverAutoTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/gpu/TurnipDriverAutoTest.kt @@ -1,6 +1,11 @@ package com.droiddeck.launcher.gpu +import android.os.Environment +import android.os.Build import com.droiddeck.launcher.session.QuestExperimental +import com.droiddeck.launcher.session.SessionPrefs +import java.io.File +import org.junit.After import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test @@ -9,6 +14,7 @@ import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment import org.robolectric.annotation.Config import org.robolectric.shadows.ShadowBuild +import org.robolectric.util.ReflectionHelpers @RunWith(RobolectricTestRunner::class) @Config(sdk = [28], manifest = Config.NONE) @@ -16,10 +22,23 @@ class TurnipDriverAutoTest { @Before fun reset() { ShadowBuild.setModel("Phone") ShadowBuild.setDevice("phone") + overrideFile().delete() } + @After fun cleanUp() { + overrideFile().delete() + SessionPrefs.setAndroidDriver(RuntimeEnvironment.getApplication(), TurnipDriver.AUTO) + File(RuntimeEnvironment.getApplication().filesDir, "graphics_driver/test-pinned").deleteRecursively() + } + + private fun overrideFile() = File(Environment.getExternalStorageDirectory(), "Download/droiddeck-driver") + + private fun gpu(model: Int, adreno: Boolean = true) = GpuInfo( + "test GPU", model, GpuInfo.familyOf(adreno, model), "", false, + ) + @Test fun questModelsUseTheirPatchedDriverAsTheFallback() { - val driver = TurnipDriver(RuntimeEnvironment.getApplication()) + val driver = TurnipDriver(RuntimeEnvironment.getApplication()) { error("Quest must not use generic GPU detection") } for (model in listOf("Quest 3", "Quest 3S", "Quest 2")) { ShadowBuild.setModel(model) assertEquals(if (model == "Quest 2") QuestExperimental.DRIVER_A6XX else QuestExperimental.DRIVER, @@ -27,8 +46,54 @@ class TurnipDriverAutoTest { } } - @Test fun otherDevicesRetainTheGenericFallback() { - assertEquals("turnip25.1.0", TurnipDriver(RuntimeEnvironment.getApplication()).autoId()) + @Test fun aNonAdrenoDeviceDoesNotAutomaticallyLoadTurnip() { + assertEquals(GpuInfo.Family.NOT_ADRENO, GpuInfo.detect().family) + assertEquals("system", TurnipDriver(RuntimeEnvironment.getApplication()).autoId()) + } + + @Test fun autoSelectionUsesTheDetectedFamilyAndModel() { + val context = RuntimeEnvironment.getApplication() + for ((detected, expected) in listOf( + gpu(0, adreno = false) to "system", + gpu(0) to "turnip25.1.0", + gpu(650) to "turnip26.3.0-a6xx", + gpu(730) to "turnip25.1.0", + gpu(850) to "turnip-sdk36", + )) { + var calls = 0 + assertEquals(expected, TurnipDriver(context) { calls++; detected }.autoId()) + assertEquals(1, calls) + } + } + + @Test fun nonAdrenoDoesNotUseTheAndroid16TurnipFallback() { + val context = RuntimeEnvironment.getApplication() + val sdk = Build.VERSION.SDK_INT + try { + ReflectionHelpers.setStaticField(Build.VERSION::class.java, "SDK_INT", 36) + assertEquals("system", TurnipDriver(context) { gpu(0, adreno = false) }.autoId()) + assertEquals("turnip-sdk36", TurnipDriver(context) { gpu(0) }.autoId()) + } finally { + ReflectionHelpers.setStaticField(Build.VERSION::class.java, "SDK_INT", sdk) + } + } + + @Test fun externalOverrideStillTakesPriorityOverDetection() { + val driver = TurnipDriver(RuntimeEnvironment.getApplication()) { error("override must precede detection") } + overrideFile().parentFile!!.mkdirs() + overrideFile().writeText("system") + assertEquals("system", driver.autoId()) + overrideFile().writeText("a8") + assertEquals("turnip-sdk36", driver.autoId()) + } + + @Test fun aManuallySelectedImportedDriverStillTakesPriorityOverDetection() { + val context = RuntimeEnvironment.getApplication() + val dir = File(context.filesDir, "graphics_driver/test-pinned").apply { mkdirs() } + File(dir, "meta.json").writeText("""{"libraryName":"test.so"}""") + File(dir, "test.so").writeText("") + SessionPrefs.setAndroidDriver(context, "test-pinned") + assertEquals("test-pinned", TurnipDriver(context) { error("manual choice must precede detection") }.install()) } @Test fun normalizedGpuModelsSelectExistingGenerationDrivers() { diff --git a/app/src/test/java/com/droiddeck/launcher/input/HomeGuideInputTest.kt b/app/src/test/java/com/droiddeck/launcher/input/HomeGuideInputTest.kt index ccef31215d..3d2a2863ee 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/HomeGuideInputTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/HomeGuideInputTest.kt @@ -27,6 +27,14 @@ class HomeGuideInputTest { assertEquals(listOf(true, false), states) } + @Test fun genericLayoutMoveHomeHoldsGuideLikeHome() { + val down = KeyEvent(10, 110, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MOVE_HOME, 0, 0, 10, 102) + val up = KeyEvent(10, 200, KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MOVE_HOME, 0, 0, 10, 102) + assertTrue(input.onKeyEvent(down, true)) + assertTrue(input.onKeyEvent(up, true)) + assertEquals(listOf(true, false), states) + } + @Test fun anUnownedHomePressKeepsAndroidBehaviorEvenIfSessionBecomesEligibleBeforeRelease() { assertFalse(input.onKeyEvent(home(KeyEvent.ACTION_DOWN), false)) assertFalse(input.onKeyEvent(home(KeyEvent.ACTION_UP), true)) diff --git a/app/src/test/java/com/droiddeck/launcher/input/PadBridgeQamTest.kt b/app/src/test/java/com/droiddeck/launcher/input/PadBridgeQamTest.kt index ab3ea6f2fc..3e3c78ee17 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/PadBridgeQamTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/PadBridgeQamTest.kt @@ -343,6 +343,102 @@ class PadBridgeQamTest { assertFalse(pad().isDown(PadState.X)) } + @Test fun homeGuideHoldsOnThePrimaryPlayerWithoutABuiltinPad() { + PadBridge.setFirstSlot(1) + try { + bridge.setBuiltinPad(false) + bridge.setHomeGuidePressed(true) + assertTrue(requireNotNull(JoyConPadTest.RecordingWriter.pads[1]).isDown(PadState.GUIDE)) + bridge.setHomeGuidePressed(false) + assertFalse(requireNotNull(JoyConPadTest.RecordingWriter.pads[1]).isDown(PadState.GUIDE)) + } finally { + PadBridge.setFirstSlot(0) + } + } + + @Test fun homeGuideAndControllerGuideReleaseIndependentlyOnThePrimaryPlayer() { + PadBridge.setFirstSlot(1) + try { + bridge.setBuiltinPad(false) + val device = controller() + bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_MODE)) + bridge.setHomeGuidePressed(true) + bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_MODE, KeyEvent.ACTION_UP)) + assertTrue(requireNotNull(JoyConPadTest.RecordingWriter.pads[1]).isDown(PadState.GUIDE)) + bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_MODE)) + bridge.setHomeGuidePressed(false) + assertTrue(requireNotNull(JoyConPadTest.RecordingWriter.pads[1]).isDown(PadState.GUIDE)) + bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_MODE, KeyEvent.ACTION_UP)) + assertFalse(requireNotNull(JoyConPadTest.RecordingWriter.pads[1]).isDown(PadState.GUIDE)) + } finally { + PadBridge.setFirstSlot(0) + } + } + + @Test fun playerSlotHomeGuidePreservesRemappedInputAndTheEnableGate() { + PadBridge.setFirstSlot(1) + try { + bridge.setBuiltinPad(false) + routed(InputProfile.defaults(InputProfile.GAME) + .withBinding(InputRole.PHYSICAL, InputControl.A, InputAction.Native(InputControl.B)) + .withBinding(InputRole.PHYSICAL, InputControl.LS, InputAction.Native(InputControl.RS))) + val device = controller() + bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_A)) + motion(device, MotionEvent.AXIS_X, .6f) + bridge.setHomeGuidePressed(true) + val held = requireNotNull(JoyConPadTest.RecordingWriter.pads[1]) + assertTrue(held.isDown(PadState.GUIDE)) + assertTrue(held.isDown(PadState.B)) + assertFalse(held.isDown(PadState.A)) + assertEquals(0f, held.leftX) + assertEquals(.6f, held.rightX) + bridge.setInputEnabled(false) + val disabled = requireNotNull(JoyConPadTest.RecordingWriter.pads[1]) + assertTrue(disabled.isDown(PadState.GUIDE)) + assertFalse(disabled.isDown(PadState.A)) + assertFalse(disabled.isDown(PadState.B)) + assertEquals(0f, disabled.leftX) + assertEquals(0f, disabled.rightX) + bridge.cancelHomeGuide() + assertFalse(requireNotNull(JoyConPadTest.RecordingWriter.pads[1]).isDown(PadState.GUIDE)) + } finally { + PadBridge.setFirstSlot(0) + } + } + + @Test fun removingThePrimaryPlayerForgetsItsHomeGuide() { + PadBridge.setFirstSlot(1) + try { + bridge.setBuiltinPad(false) + val device = controller() + bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_A, KeyEvent.ACTION_UP)) + bridge.setHomeGuidePressed(true) + bridge.onDeviceRemoved(device.id) + JoyConPadTest.RecordingWriter.pads.remove(1) + bridge.cancelHomeGuide() + bridge.setHomeGuidePressed(false) + assertNull(JoyConPadTest.RecordingWriter.pads[1]) + } finally { + PadBridge.setFirstSlot(0) + } + } + + @Test fun cancellingHomeGuideOnAPlayerSlotKeepsItsHeldControls() { + PadBridge.setFirstSlot(1) + try { + bridge.setBuiltinPad(false) + val device = controller() + bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_A)) + bridge.setHomeGuidePressed(true) + bridge.cancelHomeGuide() + val pad = requireNotNull(JoyConPadTest.RecordingWriter.pads[1]) + assertFalse(pad.isDown(PadState.GUIDE)) + assertTrue(pad.isDown(PadState.A)) + } finally { + PadBridge.setFirstSlot(0) + } + } + @Test fun cancellingHomeDiscardsQueuedPartnersAndReleasesGuideImmediately() { bridge.setHomeGuidePressed(true) bridge.applyExternal({ it.press(PadState.LB, true); it.leftY = -1f }, true) diff --git a/app/src/test/java/com/droiddeck/launcher/input/SteamVolumeKeysTest.kt b/app/src/test/java/com/droiddeck/launcher/input/SteamVolumeKeysTest.kt new file mode 100644 index 0000000000..cce0daa3cc --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/input/SteamVolumeKeysTest.kt @@ -0,0 +1,46 @@ +package com.droiddeck.launcher.input + +import android.media.AudioManager +import android.view.KeyEvent +import org.junit.Assert.* +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28, 33]) +class SteamVolumeKeysTest { + private val adjustments = mutableListOf() + + private fun key(code: Int, action: Int = KeyEvent.ACTION_DOWN, repeat: Int = 0) = + KeyEvent(0L, 0L, action, code, repeat) + + private fun dispatch(code: Int, enabled: Boolean = true, action: Int = KeyEvent.ACTION_DOWN, repeat: Int = 0) = + SteamVolumeKeys.dispatch(key(code, action, repeat), enabled, adjustments::add) + + @Test fun enabledKeysAdjustOncePerDownAndConsumeRelease() { + assertTrue(dispatch(KeyEvent.KEYCODE_VOLUME_UP)) + assertTrue(dispatch(KeyEvent.KEYCODE_VOLUME_UP, repeat = 1)) + assertTrue(dispatch(KeyEvent.KEYCODE_VOLUME_UP, action = KeyEvent.ACTION_UP)) + assertTrue(dispatch(KeyEvent.KEYCODE_VOLUME_DOWN)) + assertTrue(dispatch(KeyEvent.KEYCODE_VOLUME_DOWN, action = KeyEvent.ACTION_UP)) + assertEquals(listOf(AudioManager.ADJUST_RAISE, AudioManager.ADJUST_RAISE, AudioManager.ADJUST_LOWER), adjustments) + } + + @Test fun muteTogglesOnlyOnInitialPress() { + assertTrue(dispatch(KeyEvent.KEYCODE_VOLUME_MUTE)) + assertTrue(dispatch(KeyEvent.KEYCODE_VOLUME_MUTE, repeat = 1)) + assertTrue(dispatch(KeyEvent.KEYCODE_VOLUME_MUTE, action = KeyEvent.ACTION_UP)) + assertEquals(listOf(AudioManager.ADJUST_TOGGLE_MUTE), adjustments) + } + + @Test fun disabledAndNonVolumeKeysFallThrough() { + for (code in listOf(KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE)) { + assertFalse(dispatch(code, enabled = false)) + assertFalse(dispatch(code, enabled = false, action = KeyEvent.ACTION_UP)) + } + assertFalse(dispatch(KeyEvent.KEYCODE_BUTTON_A)) + assertTrue(adjustments.isEmpty()) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/DeviceControlsComponentTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/DeviceControlsComponentTest.kt index db035a656a..fb9a834fad 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/DeviceControlsComponentTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/DeviceControlsComponentTest.kt @@ -66,6 +66,15 @@ class DeviceControlsComponentTest { assertEquals(3, audio.getStreamVolume(AudioManager.STREAM_MUSIC)) } + @Test fun everyVolumeStepIsPublishedWithoutWaitingForThePoll() { + for (level in 2..5) { + audio.setStreamVolume(AudioManager.STREAM_MUSIC, level, 0) + context.sendBroadcast(android.content.Intent("android.media.VOLUME_CHANGED_ACTION")) + shadowOf(Looper.getMainLooper()).idle() + assertEquals(level.toString(), File(directory, "volume.state").readText().split(" ").first()) + } + } + @Test fun deniedBrightnessDoesNotOpenSettingsOrReplayAnOldSliderValueAfterPermission() { WriteSettingsShadow.writable = false request("brightness", "0.75") diff --git a/app/src/test/java/com/droiddeck/launcher/session/GameEnvironmentStoreTest.kt b/app/src/test/java/com/droiddeck/launcher/session/GameEnvironmentStoreTest.kt index 6645c6ee17..197512e5be 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/GameEnvironmentStoreTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/GameEnvironmentStoreTest.kt @@ -4,6 +4,7 @@ import android.content.Context import com.droiddeck.launcher.core.GameEnvironment import com.droiddeck.launcher.runtime.LinuxRuntime import org.json.JSONObject +import org.junit.After import org.junit.Assert.* import org.junit.Before import org.junit.Test @@ -12,6 +13,8 @@ import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment import org.robolectric.annotation.Config import java.io.File +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit @RunWith(RobolectricTestRunner::class) @Config(sdk = [28], manifest = Config.NONE) @@ -21,10 +24,137 @@ class GameEnvironmentStoreTest { @Before fun setUp() { context = RuntimeEnvironment.getApplication() + context.getSharedPreferences("session", Context.MODE_PRIVATE).edit() + .remove("logs") + .remove("gameDebugLogsEnabled") + .commit() guest = File(LinuxRuntime.rootDir(context), "root/.config/droiddeck/game-environment.json") File(context.filesDir, "game-environment.json").delete() } + @After fun tearDown() { + context.getSharedPreferences("session", Context.MODE_PRIVATE).edit() + .remove("logs") + .remove("gameDebugLogsEnabled") + .commit() + } + + @Test fun gameDebugLogsAreOffByDefault() { + assertFalse(SessionPrefs.gameDebugLogsEnabled(context)) + + GameEnvironmentStore.save(context, GameEnvironment.Config()) + + assertFalse(JSONObject(guest.readText()).getBoolean(GameEnvironmentStore.GAME_DEBUG_LOGS)) + } + + @Test fun gameDebugLogsRequireSessionLogsAndPreserveCustomDiagnostics() { + val config = GameEnvironment.Config(shared = mapOf("PROTON_LOG" to "0", "WINEDEBUG" to "+warn")) + GameEnvironmentStore.save(context, config) + + SessionPrefs.setGameDebugLogsEnabled(context, true) + var published = JSONObject(guest.readText()) + assertTrue(published.getBoolean(GameEnvironmentStore.GAME_DEBUG_LOGS)) + assertEquals("0", published.getJSONObject("shared").getString("PROTON_LOG")) + assertEquals("+warn", published.getJSONObject("shared").getString("WINEDEBUG")) + assertEquals(config, GameEnvironmentStore.read(context)) + + SessionPrefs.setLogsEnabled(context, false) + published = JSONObject(guest.readText()) + assertFalse(published.getBoolean(GameEnvironmentStore.GAME_DEBUG_LOGS)) + assertTrue(SessionPrefs.gameDebugLogsEnabled(context)) + + SessionPrefs.setLogsEnabled(context, true) + assertTrue(JSONObject(guest.readText()).getBoolean(GameEnvironmentStore.GAME_DEBUG_LOGS)) + } + + @Test fun failedGameDebugOptOutLeavesTheEnabledPreferenceVisible() { + assertTrue(SessionPrefs.setGameDebugLogsEnabled(context, true)) + assertTrue(SessionPrefs.gameDebugLogsEnabled(context)) + val guestDirectory = guest.parentFile!! + guestDirectory.deleteRecursively() + guestDirectory.parentFile!!.mkdirs() + guestDirectory.writeText("blocks the guest configuration directory\n") + try { + assertFalse(SessionPrefs.setGameDebugLogsEnabled(context, false)) + assertTrue(SessionPrefs.gameDebugLogsEnabled(context)) + } finally { + guestDirectory.delete() + guestDirectory.mkdirs() + GameEnvironmentStore.publish(context) + } + assertTrue(JSONObject(guest.readText()).getBoolean(GameEnvironmentStore.GAME_DEBUG_LOGS)) + } + + @Test fun unchangedEffectiveDiagnosticsDoNotRequireGuestPublication() { + assertFalse(SessionPrefs.gameDebugLogsEnabled(context)) + val guestDirectory = guest.parentFile!! + guestDirectory.deleteRecursively() + guestDirectory.parentFile!!.mkdirs() + guestDirectory.writeText("blocks the guest configuration directory\n") + try { + assertTrue(SessionPrefs.setLogsEnabled(context, false)) + assertFalse(SessionPrefs.logsEnabled(context)) + } finally { + guestDirectory.delete() + guestDirectory.mkdirs() + SessionPrefs.setLogsEnabled(context, true) + GameEnvironmentStore.publish(context) + } + } + + @Test fun logPreferenceUpdatesUseThePublisherLock() { + GameEnvironmentStore.publish(context) + val entered = CountDownLatch(1) + val finished = CountDownLatch(1) + lateinit var thread: Thread + synchronized(GameEnvironmentStore) { + thread = Thread { + entered.countDown() + SessionPrefs.setGameDebugLogsEnabled(context, true) + finished.countDown() + } + thread.start() + assertTrue(entered.await(5, TimeUnit.SECONDS)) + assertFalse(finished.await(100, TimeUnit.MILLISECONDS)) + assertFalse(SessionPrefs.gameDebugLogsEnabled(context)) + assertFalse(JSONObject(guest.readText()).getBoolean(GameEnvironmentStore.GAME_DEBUG_LOGS)) + } + assertTrue(finished.await(5, TimeUnit.SECONDS)) + thread.join() + assertTrue(SessionPrefs.gameDebugLogsEnabled(context)) + assertTrue(JSONObject(guest.readText()).getBoolean(GameEnvironmentStore.GAME_DEBUG_LOGS)) + } + + @Test fun gameDebugLogsWaitForARetainedSessionFolder() { + assertNull(SessionPaths.current()) + assertTrue(SessionPaths.currentSessionLogsRetained(context)) + GameEnvironmentStore.publish(context) + SessionPrefs.setLogsEnabled(context, false) + val cacheSession = SessionPaths.beginOrCurrent(context, "game-debug-logs") + try { + assertFalse(SessionPaths.currentSessionLogsRetained(context)) + + SessionPrefs.setLogsEnabled(context, true) + SessionPrefs.setGameDebugLogsEnabled(context, true) + assertTrue(SessionPrefs.gameDebugLogsEnabled(context)) + assertFalse(JSONObject(guest.readText()).getBoolean(GameEnvironmentStore.GAME_DEBUG_LOGS)) + + assertEquals(cacheSession, SessionPaths.take()) + SessionPaths.release(context, cacheSession) + val retainedSession = SessionPaths.beginOrCurrent(context, "game-debug-logs") + assertTrue(SessionPaths.currentSessionLogsRetained(context)) + + GameEnvironmentStore.publish(context) + assertTrue(JSONObject(guest.readText()).getBoolean(GameEnvironmentStore.GAME_DEBUG_LOGS)) + assertEquals(retainedSession, SessionPaths.current()) + } finally { + SessionPaths.take()?.let { ended -> + SessionPaths.release(context, ended) + ended.deleteRecursively() + } + } + } + @Test fun savedSettingsAndPublishedSettingsPreserveUnsetsAndLiteralValues() { val config = GameEnvironment.Config( shared = mapOf("LITERAL" to "a=b 'quoted' $(echo test)", "EMPTY" to ""), diff --git a/app/src/test/java/com/droiddeck/launcher/session/RumbleComponentTest.kt b/app/src/test/java/com/droiddeck/launcher/session/RumbleComponentTest.kt index 8c5361aec1..78741888d3 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/RumbleComponentTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/RumbleComponentTest.kt @@ -115,6 +115,22 @@ class RumbleComponentTest { assertFalse(pad.vibrating) } + @Test fun quietingStopsAHeldEffectAndDropsEffectsUntilLifted() { + val pad = FakeMotors() + rumble.controllerMotors = { pad } + activeController(PAD_ID) + effect(strong = 40000, weak = 20000, ms = RumbleComponent.HOLD_MS) + rumble.quiet(true) + assertFalse(pad.vibrating) + idle(RumbleComponent.KEEPALIVE_MS * 4 + 100) + assertEquals("the keepalive restarted the motors while quiet", 1, pad.played.size) + effect(strong = 40000, weak = 20000) + assertFalse("an effect played while quiet", pad.vibrating) + rumble.quiet(false) + effect(strong = 40000, weak = 20000) + assertTrue(pad.vibrating) + } + @Test fun aHeldEffectFollowsTheGamesNewStrength() { val pad = FakeMotors() rumble.controllerMotors = { pad } diff --git a/app/src/test/java/com/droiddeck/launcher/session/SessionEndHintTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SessionEndHintTest.kt new file mode 100644 index 0000000000..c5f75297ea --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/SessionEndHintTest.kt @@ -0,0 +1,121 @@ +package com.droiddeck.launcher.session + +import android.app.Application +import com.droiddeck.launcher.R +import com.droiddeck.launcher.SessionActivity +import com.droiddeck.launcher.gpu.GpuInfo +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.junit.runner.RunWith +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import org.robolectric.annotation.Implementation +import org.robolectric.annotation.Implements +import org.robolectric.util.ReflectionHelpers +import java.io.File + +@RunWith(RobolectricTestRunner::class) +@Config( + sdk = [33], application = Application::class, qualifiers = "en-rUS", + instrumentedPackages = ["com.droiddeck.launcher.gpu.GpuInfo"], + shadows = [SessionEndHintTest.DetectedGpu::class], +) +class SessionEndHintTest { + @get:Rule val temporary = TemporaryFolder() + private lateinit var activity: SessionActivity + private var previousArchitecture: String? = null + + @Before + fun setUp() { + previousArchitecture = SessionState.steamClientArch + DetectedGpu.family = GpuInfo.Family.NOT_ADRENO + activity = Robolectric.buildActivity(SessionActivity::class.java).get() + SessionState.steamClientArch = "arm64" + } + + @After + fun tearDown() { + SessionState.steamClientArch = previousArchitecture + DetectedGpu.family = GpuInfo.Family.NOT_ADRENO + } + + @Test + fun sigillOnArm64IncludesTheExperimentalX64Fallback() { + SessionState.steamClientArch = "arm64" + + assertEquals( + activity.getString(R.string.session_end_steam_sigill) + "\n" + activity.getString(R.string.session_end_steam_try_x64), + hintText(sigillLog()), + ) + } + + @Test + fun sigillOnX86_64DoesNotSuggestSwitchingToItself() { + SessionState.steamClientArch = "x86_64" + + assertEquals(activity.getString(R.string.session_end_steam_sigill), hintText(sigillLog())) + } + + @Test + fun sigillWithUnknownArchitectureDoesNotAssumeArm64() { + SessionState.steamClientArch = null + + assertEquals(activity.getString(R.string.session_end_steam_sigill), hintText(sigillLog())) + } + + @Test + fun vulkanFailureOnAdrenoSelectsTheDriverHint() { + for (family in listOf(GpuInfo.Family.A6XX, GpuInfo.Family.ADRENO_UNKNOWN)) { + DetectedGpu.family = family + + assertEquals(family.name, activity.getString(R.string.session_end_vulkan_device), hintText(vulkanLog())) + } + } + + @Test + fun vulkanFailureOnNonAdrenoExplainsTheMissingLinuxDriver() { + DetectedGpu.family = GpuInfo.Family.NOT_ADRENO + + assertEquals(activity.getString(R.string.session_end_gpu_unsupported), hintText(vulkanLog())) + } + + @Test + fun missingEmptyAndUnrelatedLogsHaveNoHint() { + assertNull(hint(null)) + assertNull(hint(File(temporary.root, "missing.log"))) + assertNull(hint(log(""))) + assertNull(hint(log("game: Illegal instruction\n== steam exited rc=132"))) + } + + private fun sigillLog() = log("== STEP 12:00:00 starting the Steam client\n== steam exited rc=132\n") + + private fun vulkanLog() = log("[gamescope] [Error] vulkan: failed to find physical device\n") + + private fun log(text: String): File = temporary.newFile().apply { writeText(text) } + + private fun hint(log: File?): Any? = SessionActivity::class.java + .getDeclaredMethod("sessionEndHint", File::class.java).apply { isAccessible = true }.invoke(activity, log) + + private fun hintText(log: File): String { + val result = hint(log) + assertNotNull(result) + return ReflectionHelpers.getField(result, "text") + } + + @Implements(value = GpuInfo.Companion::class, isInAndroidSdk = false) + class DetectedGpu { + @Implementation + fun detect(): GpuInfo = GpuInfo("test GPU", if (family == GpuInfo.Family.A6XX) 610 else 0, family, "", false) + + companion object { + var family = GpuInfo.Family.NOT_ADRENO + } + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/SessionLaunchFailureTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SessionLaunchFailureTest.kt new file mode 100644 index 0000000000..e36f237509 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/SessionLaunchFailureTest.kt @@ -0,0 +1,54 @@ +package com.droiddeck.launcher.session + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class SessionLaunchFailureTest { + private fun find(vararg lines: String) = SessionLaunchFailure.find(lines.asSequence()) + + @Test fun installedSteamThatExitsWithSigillHasACpuFailureHint() { + assertEquals(SessionLaunchFailure.STEAM_ILLEGAL_INSTRUCTION, find( + "== STEP 06:35:36.987 Steam client ready", + "== STEP 06:35:41.058 starting the Steam client", + "/usr/local/bin/droiddeck-session: line 309: 1192 Illegal instruction steam", + "== steam exited rc=132", + "(EE) failed to read Wayland events: Broken pipe", + )) + } + + @Test fun gamescopeWithoutAPhysicalDeviceHasAGraphicsFailureHint() { + assertEquals(SessionLaunchFailure.VULKAN_DEVICE_MISSING, find( + "[gamescope] [\u001b[0;31mError\u001b[0m] \u001b[0;37mvulkan:\u001b[0m failed to find physical device", + "SDL_Vulkan_CreateSurface failed: VK_KHR_wayland_surface extension is not enabled in the Vulkan instance.Failed to create backend.", + )) + } + + @Test fun unrelatedIllegalInstructionsAndExitCodesAreNotBlamedOnSteam() { + assertNull(find("game: Illegal instruction", "== steam exited rc=132")) + assertNull(find("== STEP 12:00:00 starting the Steam client", "== steam exited rc=139")) + assertNull(find("== STEP 12:00:00 starting the Steam client", "== steam exited rc=1320")) + assertNull(find("== STEP 12:00:00 starting the Steam client", "== steam exited rc=0")) + } + + @Test fun onlyTheLatestClientAttemptCounts() { + assertNull(find( + "== STEP 12:00:00 starting the Steam client", "== steam exited rc=132", + "== STEP 12:01:00 starting the Steam client", "== steam exited rc=0", + )) + } + + @Test fun aLaterSuccessfulDeviceSelectionClearsTheGraphicsFailure() { + assertNull(find( + "[gamescope] [Error] vulkan: failed to find physical device", + "[gamescope] [Info] vulkan: selecting physical device 'Turnip Adreno (TM) 610': queue family 0", + )) + } + + @Test fun aNewSessionDoesNotReuseAnOldFailure() { + assertNull(find( + "== STEP 12:00:00 starting the Steam client", "== steam exited rc=132", + "== droiddeck-session Fri Oct 23 12:01:00 mode=steam", + )) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/SessionLogShareTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SessionLogShareTest.kt index bc1718bffb..2e00e83c69 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SessionLogShareTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SessionLogShareTest.kt @@ -1,8 +1,10 @@ package com.droiddeck.launcher.session import com.droiddeck.launcher.core.LogRedactor +import org.junit.Assert.assertArrayEquals import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Rule import org.junit.Test @@ -12,6 +14,9 @@ import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment import org.robolectric.annotation.Config import java.io.File +import java.text.SimpleDateFormat +import java.util.Date +import java.util.Locale import java.util.zip.ZipFile @RunWith(RobolectricTestRunner::class) @@ -147,6 +152,41 @@ class SessionLogShareTest { assertTrue(zip(folder).values.none { it.contains(leaked) }) } + @Test fun aDirectoryListingFailureLeavesTheTreeUnrecordedButDoesNotStopSiblingScrubbing() { + val folder = tmp.newFolder("2026-10-06-06-listing") + val unavailable = File(folder, "unavailable").apply { mkdirs() } + val unavailableLog = File(unavailable, "session.log").apply { writeText("$secret\n") } + val availableLog = File(folder, "available/session.log").apply { + parentFile!!.mkdirs() + writeText("$secret\n") + } + + assertFalse(SessionArtifacts.scrubAndMark(folder, listFiles = { + if (it == unavailable) null else it.listFiles() + })) + + assertTrue(unavailableLog.readText().contains(leaked)) + assertFalse(availableLog.readText().contains(leaked)) + assertFalse(File(folder, ".scrubbed-r${LogRedactor.RULES_VERSION}").exists()) + assertFalse(File(folder, SessionArtifacts.SCRUBBED_TREE_MARKER).exists()) + } + + @Test fun aFailedScrubStillRecordsTheCollectionEventWithoutCompletingTheFolder() { + val context: android.content.Context = RuntimeEnvironment.getApplication() + val folder = tmp.newFolder("2026-10-06-06-collect") + File(folder, "wayland.log").writeText("test compositor log\n") + File(folder, SessionArtifacts.SCRUBBED_TREE_MARKER).apply { + mkdirs() + resolve("blocker").writeText("force marker write failure\n") + } + + SessionArtifacts.collect(context, folder, "test") + + assertTrue(File(folder, "events.jsonl").readText().contains("session.artifacts_collected")) + assertFalse(File(folder, SessionArtifacts.COMPLETE_MARKER).exists()) + assertFalse(File(folder, ".scrubbed-r${LogRedactor.RULES_VERSION}").exists()) + } + @Test fun steamLogsPastTheSizeLimitStayOut() { val folder = tmp.newFolder("2026-10-06-07-steam") File(folder, "session.log").writeText("ok\n") @@ -160,4 +200,322 @@ class SessionLogShareTest { assertTrue("steam/console_log.txt" in names) assertFalse("steam/cef_log.previous.txt" in names) } + + @Test fun streamingComparisonPreservesUnchangedFileAndReplacesChangedFile() { + val folder = tmp.newFolder("2026-10-06-08-steam") + val unchanged = File(folder, "unchanged.log") + unchanged.bufferedWriter().use { out -> repeat(5000) { out.write("safe diagnostic $it\n") } } + val originalModified = 1_600_000_000_000L + assertTrue(unchanged.setLastModified(originalModified)) + val changed = File(folder, "changed.log") + changed.bufferedWriter().use { out -> + repeat(5000) { out.write("safe diagnostic $it\n") } + out.write("$secret\n") + } + + assertTrue(SessionArtifacts.scrubAndMark(folder)) + + assertEquals(originalModified, unchanged.lastModified()) + assertFalse(changed.readText().contains(leaked)) + assertTrue(changed.readText().contains("sessionid=")) + } + + @Test fun historicalScrubDefersWithoutLeavingMarkersAndResumes() { + val folder = tmp.newFolder("2026-10-06-09-steam") + val log = File(folder, "session.log").apply { writeText("$secret\n") } + val rulesMarker = File(folder, ".scrubbed-r${LogRedactor.RULES_VERSION}").apply { writeText("stale\n") } + val treeMarker = File(folder, SessionArtifacts.SCRUBBED_TREE_MARKER).apply { writeText("rules ${LogRedactor.RULES_VERSION}\n") } + + SessionState.running = true + try { + assertFalse(SessionArtifacts.scrubAndMark(folder, stopWhenSessionStarts = true)) + } finally { + SessionState.running = false + } + assertFalse(rulesMarker.exists()) + assertFalse(treeMarker.exists()) + assertTrue(log.readText().contains(leaked)) + + assertTrue(SessionArtifacts.scrubAndMark(folder, stopWhenSessionStarts = true)) + assertFalse(log.readText().contains(leaked)) + assertTrue(File(folder, ".scrubbed-r${LogRedactor.RULES_VERSION}").isFile) + } + + @Test fun historicalScrubCancellationDuringStreamingPreservesTheOriginal() { + val folder = tmp.newFolder("2026-10-06-10-steam") + val original = "first safe line\n" + "x".repeat(20_000) + " $secret\n" + val log = File(folder, "session.log").apply { writeText(original) } + var checks = 0 + + assertFalse(SessionArtifacts.scrubAndMark(folder, stopWhenSessionStarts = true) { ++checks >= 4 }) + + assertEquals(original, log.readText()) + assertFalse(File(folder, ".session.log.scrub").exists()) + assertFalse(File(folder, SessionArtifacts.SCRUBBED_TREE_MARKER).exists()) + } + + @Test fun historicalScrubCancellationBeforeComparisonPreservesTheOriginal() { + val folder = tmp.newFolder("2026-10-06-11-steam") + val original = "safe diagnostic\n" + val log = File(folder, "session.log").apply { writeText(original) } + val temporary = File(folder, ".session.log.scrub") + + assertFalse(SessionArtifacts.scrubAndMark(folder, stopWhenSessionStarts = true) { temporary.length() > 0 }) + + assertEquals(original, log.readText()) + assertFalse(temporary.exists()) + assertFalse(File(folder, SessionArtifacts.SCRUBBED_TREE_MARKER).exists()) + } + + @Test fun historicalScrubDoesNotReplaceALogThatChangedBeforeCommit() { + val folder = tmp.newFolder("2026-10-06-12-steam") + val original = "sessionid=$leaked\n" + val appended = "writer finished after collection started\n" + val log = File(folder, "session.log").apply { writeText(original) } + + assertFalse(SessionArtifacts.scrubAndMark(folder, beforeReplace = { it.appendText(appended) })) + + assertEquals(original + appended, log.readText()) + assertFalse(File(folder, ".session.log.scrub").exists()) + assertFalse(File(folder, ".scrubbed-r${LogRedactor.RULES_VERSION}").exists()) + assertFalse(File(folder, SessionArtifacts.SCRUBBED_TREE_MARKER).exists()) + } + + @Test fun comparisonCancellationWinsOverAnImmediateLengthMismatch() { + val left = tmp.newFile("left.log").apply { writeText("short\n") } + val right = tmp.newFile("right.log").apply { writeText("a different length\n") } + + assertNull(SessionArtifacts.sameContents(left, right) { true }) + } + + @Test fun recoveryRetryKeepsItsSteamLogsWhenALaterSessionLeftNoFolder() { + val context: android.content.Context = RuntimeEnvironment.getApplication() + val folder = File(com.droiddeck.launcher.runtime.LinuxRuntime.logDir(context), "2026-10-08-01-steam").apply { mkdirs() } + val saved = File(folder, "steam/console_log.txt").apply { + parentFile!!.mkdirs() + writeText("session A\n") + } + File(folder, "ended-without-teardown.txt").writeText("recovery attempted before session B\n") + val runtime = File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context), "root/.local/share/Steam/logs/console_log.txt").apply { + parentFile!!.mkdirs() + writeText("session B\n") + } + + SessionArtifacts.finishAbandoned(context) + + assertEquals("session A\n", saved.readText()) + assertEquals("session B\n", runtime.readText()) + assertTrue(File(folder, "ended-without-teardown.txt").readText().contains("runtime capture did not finish")) + assertTrue(File(folder, SessionArtifacts.COMPLETE_MARKER).isFile) + } + + @Test fun abandonedRecoveryDoesNotCopyLogsFromANewerCompletedSession() { + val context: android.content.Context = RuntimeEnvironment.getApplication() + val logs = com.droiddeck.launcher.runtime.LinuxRuntime.logDir(context) + val folder = File(logs, "2026-10-08-02-steam").apply { mkdirs() } + val saved = File(folder, "steam/console_log.txt").apply { + parentFile!!.mkdirs() + writeText("session A\n") + } + File(logs, "2026-10-08-03-steam").apply { mkdirs() } + .resolve(SessionArtifacts.COMPLETE_MARKER).writeText("finished session B\n") + File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context), "root/.local/share/Steam/logs/console_log.txt").apply { + parentFile!!.mkdirs() + writeText("session B\n") + } + + SessionArtifacts.finishAbandoned(context) + + assertEquals("session A\n", saved.readText()) + assertTrue(File(folder, SessionArtifacts.COMPLETE_MARKER).isFile) + } + + @Test fun startupRecoveryRunsBeforeVacMarkerArmWhileOrdinaryCleanupDefers() { + val context: android.content.Context = RuntimeEnvironment.getApplication() + val root = com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context) + val folder = File(com.droiddeck.launcher.runtime.LinuxRuntime.logDir(context), "2999-12-31-99-startup-recovery") + val marker = File(root, "root/.droiddeck-vac-diagnostics") + val launches = File(root, "root/.droiddeck-vac-launches") + val runtimeSteamLog = File(SessionPrefs.steamRoot(context, "arm64"), "logs/startup-recovery-vac.log") + val sessionLog = File(folder, "session.log") + val crashLog = File(folder, "crash.log") + val previousRunning = SessionState.running + val previousPhase = SessionState.phase + try { + folder.deleteRecursively() + folder.mkdirs() + SessionArtifacts.recordClient(folder, "arm64") + sessionLog.writeText("$secret\n") + marker.apply { parentFile!!.mkdirs(); writeText("0\narm64\n") } + launches.writeText("startup VAC evidence\n") + runtimeSteamLog.apply { parentFile!!.mkdirs(); writeText("startup VAC evidence\n") } + SessionState.running = true + SessionState.phase = SessionPhase.STARTING_GUEST + + SessionArtifacts.finishAbandoned(context) + + assertFalse(File(folder, "ended-without-teardown.txt").exists()) + assertFalse(File(folder, SessionArtifacts.COMPLETE_MARKER).exists()) + + SessionArtifacts.finishAbandoned(context, beforeGuestStart = true) + + assertEquals("startup VAC evidence\n", File(folder, "steam/startup-recovery-vac.log").readText()) + assertTrue(File(folder, "vac.txt").readText().contains("startup VAC evidence")) + assertTrue(File(folder, ".recovery-runtime-captured").isFile) + assertTrue(crashLog.isFile && crashLog.length() > 0L) + assertTrue(sessionLog.readText().contains(leaked)) + assertFalse(File(folder, SessionArtifacts.COMPLETE_MARKER).exists()) + + SessionState.running = false + SessionArtifacts.finishAbandoned(context) + + assertFalse(sessionLog.readText().contains(leaked)) + assertTrue(File(folder, SessionArtifacts.COMPLETE_MARKER).isFile) + } finally { + SessionState.running = previousRunning + SessionState.phase = previousPhase + folder.deleteRecursively() + runtimeSteamLog.delete() + marker.delete() + launches.delete() + } + } + + @Test fun startupRecoveryExcludesCurrentFolderAndCapturesDeferredRuntime() { + val context: android.content.Context = RuntimeEnvironment.getApplication() + val root = com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context) + val logs = com.droiddeck.launcher.runtime.LinuxRuntime.logDir(context) + val day = SimpleDateFormat("yyyy-MM-dd", Locale.US).format(Date()) + val olderFolder = File(logs, "$day-8999-older-recovery") + val folder = File(logs, "$day-9000-deferred-recovery") + val marker = File(root, "root/.droiddeck-vac-diagnostics") + val launches = File(root, "root/.droiddeck-vac-launches") + val runtimeSteamLog = File(SessionPrefs.steamRoot(context, "arm64"), "logs/deferred-recovery-vac.log") + val previousRunning = SessionState.running + val previousPhase = SessionState.phase + val previousLogsEnabled = SessionPrefs.logsEnabled(context) + var currentFolder: File? = null + try { + olderFolder.deleteRecursively() + olderFolder.mkdirs() + folder.deleteRecursively() + folder.mkdirs() + SessionArtifacts.recordClient(folder, "arm64") + File(folder, "ended-without-teardown.txt").writeText("recovery began before session start\n") + marker.apply { parentFile!!.mkdirs(); writeText("0\narm64\n") } + launches.writeText("deferred VAC evidence\n") + runtimeSteamLog.apply { parentFile!!.mkdirs(); writeText("deferred VAC evidence\n") } + SessionState.running = true + SessionState.phase = SessionPhase.STARTING_GUEST + SessionPrefs.setLogsEnabled(context, true) + currentFolder = SessionPaths.beginOrCurrent(context, "current-session") + + SessionArtifacts.finishAbandoned(context, beforeGuestStart = true) + + assertEquals("deferred VAC evidence\n", File(folder, "steam/deferred-recovery-vac.log").readText()) + assertTrue(File(folder, "vac.txt").readText().contains("deferred VAC evidence")) + assertTrue(File(folder, ".recovery-runtime-captured").isFile) + assertFalse(File(folder, SessionArtifacts.COMPLETE_MARKER).exists()) + assertFalse(File(olderFolder, "ended-without-teardown.txt").exists()) + assertFalse(File(olderFolder, SessionArtifacts.COMPLETE_MARKER).exists()) + assertFalse(File(currentFolder, "ended-without-teardown.txt").exists()) + assertFalse(File(currentFolder, SessionArtifacts.COMPLETE_MARKER).exists()) + + SessionState.running = false + SessionArtifacts.finishAbandoned(context) + + assertTrue(File(folder, SessionArtifacts.COMPLETE_MARKER).isFile) + assertTrue(File(olderFolder, SessionArtifacts.COMPLETE_MARKER).isFile) + assertFalse(File(currentFolder, SessionArtifacts.COMPLETE_MARKER).exists()) + } finally { + SessionState.running = previousRunning + SessionState.phase = previousPhase + SessionPaths.take()?.let { SessionPaths.release(context, it) } + currentFolder?.deleteRecursively() + SessionPrefs.setLogsEnabled(context, previousLogsEnabled) + olderFolder.deleteRecursively() + folder.deleteRecursively() + runtimeSteamLog.delete() + marker.delete() + launches.delete() + } + } + + @Test fun failedPreGuestRuntimeCaptureWritesNeitherCaptureNorCompleteMarker() { + val context: android.content.Context = RuntimeEnvironment.getApplication() + val root = com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context) + val folder = File(com.droiddeck.launcher.runtime.LinuxRuntime.logDir(context), "9999-12-31-01-vac-failure") + val marker = File(root, "root/.droiddeck-vac-diagnostics") + val launches = File(root, "root/.droiddeck-vac-launches") + val runtimeSteamLog = File(SessionPrefs.steamRoot(context, "arm64"), "logs/expired-recovery.log") + val crashLog = File(folder, "crash.log") + val previousRunning = SessionState.running + try { + folder.deleteRecursively() + folder.mkdirs() + SessionArtifacts.recordClient(folder, "arm64") + File(folder, "ended-without-teardown.txt").writeText("recovery began before session start\n") + val firstCrashSnapshot = "first crash snapshot\n".toByteArray() + crashLog.writeBytes(firstCrashSnapshot) + File(folder, "vac.txt").mkdirs() + marker.apply { parentFile!!.mkdirs(); writeText("0\narm64\n") } + launches.writeText("VAC evidence that cannot be reported\n") + runtimeSteamLog.apply { parentFile!!.mkdirs(); writeText("session A\n") } + SessionState.running = true + + SessionArtifacts.finishAbandoned(context, beforeGuestStart = true) + + assertFalse(File(folder, ".recovery-runtime-captured").exists()) + assertTrue(File(folder, ".recovery-runtime-expired").isFile) + assertFalse(File(folder, SessionArtifacts.COMPLETE_MARKER).exists()) + assertArrayEquals(firstCrashSnapshot, crashLog.readBytes()) + + File(folder, "vac.txt").deleteRecursively() + runtimeSteamLog.writeText("session B\n") + SessionArtifacts.finishAbandoned(context, beforeGuestStart = true) + + assertEquals("session A\n", File(folder, "steam/expired-recovery.log").readText()) + assertArrayEquals(firstCrashSnapshot, crashLog.readBytes()) + assertTrue(File(folder, "ended-without-teardown.txt").readText().contains("runtime capture did not finish")) + assertFalse(File(folder, SessionArtifacts.COMPLETE_MARKER).exists()) + + SessionState.running = false + SessionArtifacts.finishAbandoned(context) + + assertArrayEquals(firstCrashSnapshot, crashLog.readBytes()) + assertTrue(File(folder, SessionArtifacts.COMPLETE_MARKER).isFile) + } finally { + SessionState.running = previousRunning + folder.deleteRecursively() + runtimeSteamLog.delete() + marker.delete() + launches.delete() + } + } + + @Test fun emptyCrashSnapshotIsPreservedAcrossRecovery() { + val context: android.content.Context = RuntimeEnvironment.getApplication() + val folder = File(com.droiddeck.launcher.runtime.LinuxRuntime.logDir(context), "9999-12-31-02-empty-crash") + val crashLog = File(folder, "crash.log") + val previousRunning = SessionState.running + try { + folder.deleteRecursively() + folder.mkdirs() + crashLog.writeBytes(ByteArray(0)) + SessionState.running = true + + SessionArtifacts.finishAbandoned(context, beforeGuestStart = true) + assertTrue(crashLog.isFile) + assertEquals(0L, crashLog.length()) + + SessionState.running = false + SessionArtifacts.finishAbandoned(context) + assertTrue(crashLog.isFile) + assertEquals(0L, crashLog.length()) + assertTrue(File(folder, SessionArtifacts.COMPLETE_MARKER).isFile) + } finally { + SessionState.running = previousRunning + folder.deleteRecursively() + } + } } diff --git a/app/src/test/java/com/droiddeck/launcher/session/SessionLogShareZipTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SessionLogShareZipTest.kt index 012d2a916d..674f6211e8 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SessionLogShareZipTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SessionLogShareZipTest.kt @@ -2,6 +2,7 @@ package com.droiddeck.launcher.session import com.droiddeck.launcher.runtime.LinuxRuntime import java.io.File +import java.nio.charset.StandardCharsets import java.text.SimpleDateFormat import java.util.Date import java.util.Locale @@ -20,6 +21,49 @@ import org.robolectric.annotation.Config class SessionLogShareZipTest { private val app get() = RuntimeEnvironment.getApplication() + @Test fun aLargeSteamLogIsRedactedInTheSharedArchive() { + val session = File(LinuxRuntime.logDir(app), "2026-10-08-02-steam").apply { mkdirs() } + val raw = File(session, "steam-42.log") + val earlySecret = "early-sessionid-abcdef123456" + val trailingSecret = "late-refresh-token-abcdef123456" + try { + // One long line exercises the streaming limit; the final ordinary line must still be redacted. + raw.bufferedWriter().use { out -> + out.write("sessionid=$earlySecret") + val chunk = "x".repeat(8192) + repeat(8192) { out.write(chunk) } + out.write("\nrefresh_token=$trailingSecret\n") + } + assertTrue(raw.length() > 64L * 1024 * 1024) + + val zip = SessionLogShare.zipFolder(app, session)!! + ZipFile(zip).use { archive -> + val entry = archive.getEntry("${session.name}/steam-42.log")!! + archive.getInputStream(entry).use { input -> + // Only inspect the bounded scrubbed prefix: the pre-fix raw archive is over 64 MiB. + val expected = "${com.droiddeck.launcher.core.LogRedactor.OVERSIZED_LINE}\n" + val prefix = ByteArray(expected.toByteArray(StandardCharsets.UTF_8).size) + var offset = 0 + while (offset < prefix.size) { + val count = input.read(prefix, offset, prefix.size - offset) + assertTrue("zip entry ended before its scrubbed prefix", count > 0) + offset += count + } + assertEquals(expected, String(prefix, StandardCharsets.UTF_8)) + input.bufferedReader().use { reader -> + val trailing = requireNotNull(reader.readLine()) + assertFalse("trailing secret survived", trailing.contains(trailingSecret)) + assertEquals("refresh_token=", trailing) + assertEquals(null, reader.readLine()) + } + } + } + } finally { + SessionLogShare.clear(app) + session.deleteRecursively() + } + } + @Test fun everyTextFileInTheZipIsScrubbedAndTheStoresAndToolsLogsComeAlong() { val logs = LinuxRuntime.logDir(app) val session = File(logs, "2026-10-08-01-steam").apply { mkdirs() } diff --git a/app/src/test/java/com/droiddeck/launcher/session/SessionSteamLogsTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SessionSteamLogsTest.kt index 60c57ecfd5..3b996ae3d2 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SessionSteamLogsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SessionSteamLogsTest.kt @@ -2,10 +2,13 @@ package com.droiddeck.launcher.session import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder import java.io.File +import java.io.IOException +import java.io.Writer class SessionSteamLogsTest { @get:Rule val tmp = TemporaryFolder() @@ -59,4 +62,37 @@ class SessionSteamLogsTest { assertEquals(listOf("web.txt"), names(copied)) assertFalse(File(out, "web.txt").readText().contains("abcdef123456")) } + + @Test fun aCopyFailurePreservesThePreviousSnapshotAndRemovesPartialStaging() { + val logs = tmp.newFolder("logs") + val session = tmp.newFolder("session") + val out = tmp.newFolder("out") + File(logs, "console_log.txt").writeText("new complete line\n") + val snapshot = File(out, "console_log.txt").apply { writeText("previous valid snapshot\n") } + lateinit var staging: File + + val copied = SessionArtifacts.copySessionLogs(logs, session, out) { target -> + staging = target + val delegate = target.bufferedWriter() + object : Writer() { + private var failed = false + + override fun write(buffer: CharArray, offset: Int, length: Int) { + if (!failed) { + delegate.write(buffer, offset, minOf(length, 4)) + delegate.flush() + failed = true + } + throw IOException("injected writer failure") + } + + override fun flush() = delegate.flush() + override fun close() = delegate.close() + } + } + + assertTrue(copied.isEmpty()) + assertEquals("previous valid snapshot\n", snapshot.readText()) + assertFalse(staging.exists()) + } } diff --git a/app/src/test/java/com/droiddeck/launcher/session/SettingsResetTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SettingsResetTest.kt index 3845a62d91..637f4d1163 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SettingsResetTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SettingsResetTest.kt @@ -40,6 +40,7 @@ class SettingsResetTest { SessionPrefs.setHdr(app, SessionService.MODE_DESKTOP, true) SessionPrefs.setResolutionChoice(app, SessionService.MODE_STEAM, "1280x800") SessionPrefs.setGuestHostname(app, "MyDeck") + assertTrue(SessionPrefs.setGameDebugLogsEnabled(app, true)) SessionPrefs.setHudShowFps(app, false) SessionPrefs.setHudShowBattery(app, false) SessionPrefs.setHudShowGraph(app, false) @@ -60,6 +61,10 @@ class SettingsResetTest { assertFalse(SessionPrefs.hdr(app, SessionService.MODE_DESKTOP)) assertFalse(SessionPrefs.resolutionChosen(app, SessionService.MODE_STEAM)) assertEquals(SessionPrefs.DEFAULT_GUEST_HOSTNAME, SessionPrefs.guestHostname(app)) + assertFalse(SessionPrefs.gameDebugLogsEnabled(app)) + val guest = java.io.File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(app), + "root/.config/droiddeck/game-environment.json") + assertFalse(org.json.JSONObject(guest.readText()).getBoolean(GameEnvironmentStore.GAME_DEBUG_LOGS)) assertTrue(SessionPrefs.hudShowFps(app)) assertTrue(SessionPrefs.hudShowBattery(app)) assertTrue(SessionPrefs.hudShowGraph(app)) @@ -73,6 +78,22 @@ class SettingsResetTest { assertFalse(prefs("steam_touch").contains("gyro")) } + @Test fun aFailedDebugOptOutDoesNotHideTheEnabledPreference() { + assertTrue(SessionPrefs.setGameDebugLogsEnabled(app, true)) + val directory = java.io.File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(app), + "root/.config/droiddeck") + directory.deleteRecursively() + directory.writeText("blocks configuration publication") + try { + assertFalse(SettingsReset.resetAll(app, gameProfiles = false)) + assertTrue(SessionPrefs.gameDebugLogsEnabled(app)) + } finally { + directory.delete() + directory.mkdirs() + GameEnvironmentStore.publish(app) + } + } + @Test fun libraryAndRecordsAreKept() { val folder = "/storage/emulated/0/Games/Foo" SessionPrefs.setAddedGameName(app, folder, "Foo") diff --git a/app/src/test/java/com/droiddeck/launcher/stores/StoreAccountsCipherTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/StoreAccountsCipherTest.kt index 0aeb49bb35..cd14c66602 100644 --- a/app/src/test/java/com/droiddeck/launcher/stores/StoreAccountsCipherTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/stores/StoreAccountsCipherTest.kt @@ -1,5 +1,6 @@ package com.droiddeck.launcher.stores +import android.app.Application import org.json.JSONObject import org.junit.After import org.junit.Assert.assertEquals @@ -18,7 +19,7 @@ import javax.crypto.SecretKey import javax.crypto.spec.SecretKeySpec @RunWith(RobolectricTestRunner::class) -@Config(sdk = [33]) +@Config(sdk = [33], application = Application::class) class StoreAccountsCipherTest { private val app get() = RuntimeEnvironment.getApplication() private fun newKey(): SecretKey = SecretKeySpec(ByteArray(32).also { SecureRandom().nextBytes(it) }, "AES") diff --git a/app/src/test/java/com/droiddeck/launcher/ui/GlobalGlassesSettingsTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/GlobalGlassesSettingsTest.kt index b64986a1e4..62c90ce94a 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/GlobalGlassesSettingsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/GlobalGlassesSettingsTest.kt @@ -144,7 +144,7 @@ class GlobalGlassesSettingsTest { onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> }, onSetPhantomProcessLimit = { _, _ -> }, - ), onOpenDeveloperOptions = {}, onRequestWirelessAdb = {}) + ), onOpenDeveloperOptions = {}, onRequestWirelessAdb = {}, onPairWirelessDebugging = {}) } } } diff --git a/app/src/test/java/com/droiddeck/launcher/update/AppUpdatesTest.kt b/app/src/test/java/com/droiddeck/launcher/update/AppUpdatesTest.kt index ada2ff3bef..5bb78ff9cc 100644 --- a/app/src/test/java/com/droiddeck/launcher/update/AppUpdatesTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/update/AppUpdatesTest.kt @@ -8,6 +8,7 @@ import com.droiddeck.launcher.update.AppUpdates.Offer import com.droiddeck.launcher.update.AppUpdates.PreviewChange import com.droiddeck.launcher.update.AppUpdates.PreviewHistoryKind import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse import org.junit.Assert.assertNotNull import org.junit.Assert.assertNull import org.json.JSONArray @@ -285,4 +286,69 @@ class AppUpdatesTest { } catch (_: IOException) { } } + + @Test fun anOlderStableIsGuessedStableAndSaved() { + val g = AppUpdates.guessFollow(catalog, me("eeeeeee999", version = "0.1.9")) + assertEquals(AppUpdates.Channel.STABLE, g.follow.channel) + assertTrue(g.certain) + } + + @Test fun anOlderBuildInPreviewHistoryKeepsStableAsAnUncertainGuess() { + val withHistory = AppUpdates.Catalog(stable, release("1111111"), emptyList(), 0L, recentPreview) + val g = AppUpdates.guessFollow(withHistory, me("2".repeat(40), version = "0.1.0")) + assertEquals(Channel.STABLE, g.follow.channel) + assertFalse(g.certain) + } + + @Test fun anOlderCataloguedBuildDoesNotPersistAGuessAndExplicitChoicesStillWin() { + val context = org.robolectric.RuntimeEnvironment.getApplication() + val preferences = context.getSharedPreferences("app_updates", android.content.Context.MODE_PRIVATE) + preferences.edit().clear().commit() + try { + val installed = me("2".repeat(40), version = "0.1.0") + val newerStable = release("0".repeat(40), version = "9999.0.0") + val currentPreview = release(installed.commit) + val newerCatalog = AppUpdates.Catalog(newerStable, currentPreview, emptyList(), 0L) + assertEquals(Channel.STABLE, AppUpdates.follow(context, newerCatalog, installed).channel) + assertNull(preferences.getString("channel", null)) + assertEquals(Channel.STABLE, AppUpdates.follow(context, null, installed).channel) + assertNull(preferences.getString("channel", null)) + for (choice in listOf(Follow(Channel.STABLE), Follow(Channel.NIGHTLY), Follow(Channel.TEST, 93))) { + AppUpdates.setFollow(context, choice) + val actual = AppUpdates.follow(context, newerCatalog, installed) + assertEquals(choice.channel, actual.channel) + assertEquals(choice.pr, actual.pr) + } + } finally { + preferences.edit().clear().commit() + } + } + + @Test fun runningTheCatalogStableIsCertainStable() { + val g = AppUpdates.guessFollow(catalog, me(stable.commit)) + assertEquals(AppUpdates.Channel.STABLE, g.follow.channel) + assertTrue(g.certain) + } + + @Test fun aPublishedPreviewPastStableIsGuessedNightlyWithoutSaving() { + val withHistory = AppUpdates.Catalog(stable, release("1111111"), emptyList(), 0L, recentPreview) + val g = AppUpdates.guessFollow(withHistory, me("2".repeat(40), version = "0.3.0")) + assertEquals(AppUpdates.Channel.NIGHTLY, g.follow.channel) + assertFalse(g.certain) + } + + @Test fun anUncataloguedNewerBuildStaysStableForNow() { + val g = AppUpdates.guessFollow(catalog, me("9".repeat(40), version = "0.3.0")) + assertEquals(AppUpdates.Channel.STABLE, g.follow.channel) + assertFalse(g.certain) + val offline = AppUpdates.guessFollow(null, me("9".repeat(40), version = "0.3.0")) + assertEquals(AppUpdates.Channel.STABLE, offline.follow.channel) + assertFalse(offline.certain) + } + + @Test fun aPullRequestBuildIsCertainTest() { + val g = AppUpdates.guessFollow(catalog, me("ccccccc2222222222222222222222222222222", pr = 93)) + assertEquals(AppUpdates.Channel.TEST, g.follow.channel) + assertTrue(g.certain) + } } diff --git a/docs/development/game-environment.md b/docs/development/game-environment.md index bebd67ce66..57c88bd92a 100644 --- a/docs/development/game-environment.md +++ b/docs/development/game-environment.md @@ -52,6 +52,44 @@ environment entries and is intentionally narrower than **Reset game profile**. Values are literal strings, with no shell expansion; quotes are only needed when the consuming program expects them. +## Game debug logs + +Under **Setup > Diagnostics**, enable **Session logs** and **Game debug logs** +before reproducing a Windows game problem. Game debug logs is off by default and +is available when Session logs is enabled. It applies to the next game launch through DroidDeck's +Valve or third-party Proton wrapper, including added games and store shortcuts. +A running game must be restarted. If the current session began with Session logs +disabled, restart that session first: its existing log folder is disposable, and +the UI shows a restart reminder instead of enabling logs that would be discarded. + +| Generated setting | Effective value while enabled | +| --- | --- | +| `PROTON_LOG` | `1` | +| `PROTON_LOG_DIR`, `PROTON_CRASH_REPORT_DIR`, `DXVK_LOG_PATH` | The actual session log directory | +| `DXVK_LOG_LEVEL` | `debug` | +| `VKD3D_DEBUG` | `info` | +| `WINEDEBUG` | Valid custom channels plus Proton's standard diagnostic channels | + +Diagnostics take precedence over conflicting inherited, shared, or per-game log +settings while the switch is on. Wine channel selectors are normalized and +deduplicated with the last selector winning; required exception, module, and +timestamp channels are applied last, including when a profile contains `-all`. +Custom channels from `PROTON_LOG` are retained when valid. Malformed channel tokens +are omitted; an oversized list falls back to the standard diagnostic channels. + +Saved profiles and Steam launch options are unchanged. The launcher merges a +process-environment map, so every variable has one value and paths containing +spaces, quotes, or shell characters stay literal. Existing arguments and +`%command%` are not reconstructed. Disabling the switch restores the user's normal +settings on the next launch. It does not change Steam probes or native Linux +programs, whose ordinary output remains in the session log. + +After reproducing once, stop the session and use **Latest session logs > Share +logs**. The archive includes the generated Wine/Proton and graphics logs. Debug +logging can reduce performance and consume storage; disable it after collecting +the report. If the session log directory is unavailable, the launcher reports +that diagnostics were skipped instead of writing uncollected files elsewhere. + A Unity game under FEX (`UnityPlayer.dll` for Windows builds under Proton, `UnityPlayer.so` or `GameAssembly.so` for native Linux builds started by **Linux x86 (FEX)**) keeps FEX's TSO on when the Default profile's FEX preset diff --git a/docs/development/steam-launch-hardware.md b/docs/development/steam-launch-hardware.md new file mode 100644 index 0000000000..234dedeac9 --- /dev/null +++ b/docs/development/steam-launch-hardware.md @@ -0,0 +1,61 @@ +# Steam startup failures on older CPUs and non-Adreno GPUs + +These are different failures, even when neither reaches the Steam interface. + +## Steam exits with SIGILL (#1376) + +The [Redmi Note 8 report](https://github.com/Droid-Deck/DroidDeck/issues/1376) +shows gamescope selecting Adreno 610 successfully, all 17 client parts being +downloaded, and the native Steam executable immediately exiting with status +132 (`Illegal instruction`). The failure occurs after installation, not during +the runtime download. The supplied logs do not identify the faulting program +counter or CPU feature flags, so they cannot establish the exact instruction. + +The official ARM64 Steam client and web helper inspected during this +investigation contain LSE atomic instructions. This is a compatibility concern +for CPUs without LSE, not proof that LSE caused this particular crash. Device +reports now include only the kernel's CPU `Features` lists, without unrelated +`/proc/cpuinfo` fields such as serial numbers. + +After SIGILL, the failure screen explains the signal and, for an ARM64 client, +points to **Steam settings → Steam client → x86-64 (experimental)**. This is an +explicit user choice with an additional download and emulation overhead. It +does not establish that the device can run every component or game. + +The x86-64 client normally reuses a matching-build native ARM web helper. +When CPU feature flags explicitly lack `atomics`, it now retains the existing +x86 web helper instead. Otherwise the fallback could re-enter native code +containing the same instruction class. All reported core feature lists must +include that exact flag; absent or unreadable feature data retains the prior +behavior. Explicit x86-helper selection and the client-build matching rule +remain unchanged. + +## gamescope cannot find a Vulkan device (#1368) + +The [MT6993 report](https://github.com/Droid-Deck/DroidDeck/issues/1368) shows a +non-Adreno device starting with an Adreno Turnip display driver, followed by +gamescope failing to find a physical device through the Linux freedreno ICD. +Steam has not been started in that trace. + +Automatic Android display-driver selection now leaves non-Adreno GPUs on the +system driver rather than choosing Turnip from the Android SDK version. An +Adreno GPU with an unknown model still uses the existing SDK fallback; Quest, +external overrides and manual selections retain their priority. The failure +screen distinguishes an unavailable Linux Vulkan device from a failed Steam +download. + +This does not implement MT6993/Mali graphics support. The Linux session needs +a driver for that GPU and kernel, and the Android compositor also has Vulkan +requirements. The system Android driver alone does not provide the Linux +driver; the desktop's software rendering does not replace the outer +compositor. Removing the unsupported-device notice or importing Adreno +Turnip cannot supply these missing components. + +## Verification boundary + +Regression tests cover actual automatic driver selection, log classification +and the x86 client's web-helper selection. The supplied session logs can be +replayed through the classifier. No target phone was available, and the +specific ARM64 instruction fault has not been reproduced under a debugger. +Neither report should be treated as verified fixed on hardware based on these +tests alone. diff --git a/docs/development/unified-input-validation.md b/docs/development/unified-input-validation.md index f49d57c73f..98256e353f 100644 --- a/docs/development/unified-input-validation.md +++ b/docs/development/unified-input-validation.md @@ -172,6 +172,20 @@ complete `:app:testDebugUnitTest` run passes **2,636 tests across 385 suites, ze failures/errors/skips**, with the same Java/SDK/NDK settings and `-PskipRust=true`. These fixes have not been tested or benchmarked on Thor. +### Upstream Home/player-slot integration (2026-10-28) + +Merged upstream `213c2da5` without rewriting the published branch. Home/Guide now +follows upstream's primary-player slot selection when the built-in pad is off, +while its report retains routed buttons and axes. The input-settings overlay +continues to gate Home shortcuts and now also gates upstream's Steam volume-key +handling. + +A new regression combines Home on player slot 1 with button/stick remapping and +disabled routing. The complete `:app:testDebugUnitTest` run passes **2,707 tests +across 389 suites, zero failures/errors/skips**, using the same Java/SDK/NDK +settings and `-PskipRust=true`. A new APK build, Thor validation and latency +measurement were not performed for this merge. + ## Manual AYN Thor results The user performed the following checks in the installed candidate. The desktop diff --git a/tools/aaudio-sink/android-volume.h b/tools/aaudio-sink/android-volume.h index 6a31befeb1..0e71caf65b 100644 --- a/tools/aaudio-sink/android-volume.h +++ b/tools/aaudio-sink/android-volume.h @@ -3,10 +3,15 @@ #include #include +#define ANDROID_VOLUME_IDLE_MS 100 +#define ANDROID_VOLUME_ACTIVE_MS 16 +#define ANDROID_VOLUME_ACTIVE_TICKS 40 + struct android_volume { pa_sink *sink; char *directory; pa_time_event *timer; + unsigned active_ticks; }; static bool android_volume_read(const char *directory, unsigned *level, unsigned *maximum, unsigned *muted) { @@ -57,22 +62,39 @@ static void android_volume_refresh(pa_mainloop_api *api, pa_time_event *event, c char *processing = pa_sprintf_malloc("%s.processing", request); char *mute_processing = pa_sprintf_malloc("%s.processing", mute_request); if (access(request, F_OK) != 0 && access(mute_request, F_OK) != 0 && - access(processing, F_OK) != 0 && access(mute_processing, F_OK) != 0 && - android_volume_read(bridge->directory, &level, &maximum, &muted)) { - pa_cvolume volume; - if (bridge->sink->n_volume_steps != maximum + 1) { - bridge->sink->n_volume_steps = maximum + 1; - pa_subscription_post(bridge->sink->core, PA_SUBSCRIPTION_EVENT_SINK | PA_SUBSCRIPTION_EVENT_CHANGE, bridge->sink->index); + access(processing, F_OK) != 0 && access(mute_processing, F_OK) != 0) { + if (android_volume_read(bridge->directory, &level, &maximum, &muted)) { + pa_cvolume volume; + bool changed = false; + if (bridge->sink->n_volume_steps != maximum + 1) { + bridge->sink->n_volume_steps = maximum + 1; + pa_subscription_post(bridge->sink->core, PA_SUBSCRIPTION_EVENT_SINK | PA_SUBSCRIPTION_EVENT_CHANGE, bridge->sink->index); + } + pa_cvolume_set(&volume, bridge->sink->sample_spec.channels, (uint64_t)level * PA_VOLUME_NORM / maximum); + if (!pa_cvolume_equal(&volume, &bridge->sink->real_volume)) { + pa_sink_volume_changed(bridge->sink, &volume); + changed = true; + } + if (bridge->sink->muted != !!muted) { + pa_sink_mute_changed(bridge->sink, !!muted); + changed = true; + } + if (changed) bridge->active_ticks = ANDROID_VOLUME_ACTIVE_TICKS; } - pa_cvolume_set(&volume, bridge->sink->sample_spec.channels, (uint64_t)level * PA_VOLUME_NORM / maximum); - if (!pa_cvolume_equal(&volume, &bridge->sink->real_volume)) pa_sink_volume_changed(bridge->sink, &volume); - if (bridge->sink->muted != !!muted) pa_sink_mute_changed(bridge->sink, !!muted); + } else { + bridge->active_ticks = ANDROID_VOLUME_ACTIVE_TICKS; } pa_xfree(request); pa_xfree(mute_request); pa_xfree(processing); pa_xfree(mute_processing); - pa_core_rttime_restart(bridge->sink->core, event, pa_rtclock_now() + 100 * PA_USEC_PER_MSEC); + /* A held volume key steps Android every ~50 ms; sampling at 100 ms hands Steam uneven multi-step jumps. */ + unsigned delay_ms = ANDROID_VOLUME_IDLE_MS; + if (bridge->active_ticks) { + bridge->active_ticks--; + delay_ms = ANDROID_VOLUME_ACTIVE_MS; + } + pa_core_rttime_restart(bridge->sink->core, event, pa_rtclock_now() + delay_ms * PA_USEC_PER_MSEC); } static struct android_volume *android_volume_new(pa_sink *sink, const char *directory) { @@ -90,7 +112,7 @@ static struct android_volume *android_volume_new(pa_sink *sink, const char *dire pa_cvolume_reset(&sink->soft_volume, sink->sample_spec.channels); pa_sink_set_set_volume_callback(sink, android_volume_set); pa_sink_set_set_mute_callback(sink, android_volume_mute); - bridge->timer = pa_core_rttime_new(sink->core, pa_rtclock_now() + 100 * PA_USEC_PER_MSEC, + bridge->timer = pa_core_rttime_new(sink->core, pa_rtclock_now() + ANDROID_VOLUME_IDLE_MS * PA_USEC_PER_MSEC, android_volume_refresh, bridge); return bridge; } diff --git a/tools/gamescope/PATCHES.md b/tools/gamescope/PATCHES.md index a72ab6be13..a57c3bc82b 100644 --- a/tools/gamescope/PATCHES.md +++ b/tools/gamescope/PATCHES.md @@ -156,3 +156,46 @@ A host mode switch can report a passing rate for a few frames (72 Hz between 144 120 Hz on the AYANEO Pocket FIT), so with following on a new rate is taken once it has been reported for 300 ms. Without the variable the reported rate is taken at once, as upstream does. + +The rate comes from the feedback of a frame gamescope presents, so with nothing moving +on screen no feedback arrived and the old rate stayed. With following on, gamescope +presents once when the host's `wl_output` mode changes (DroidDeck's compositor sends +the new mode) and keeps presenting while a new rate is pending (since p16). + +## 0121 Xwayland: skip the X tree walk for a repeated window override + +The WSI layer sends `override_window_content` on every present of an X11 swapchain. +gamescope first walked from that window to its top-level window with `XQueryTree`, one +blocking X round trip per level under the wlserver lock, and only then noticed that the +same swapchain already overrides that window. At thousands of frames per second that is +thousands of round trips to Xwayland every second. + +The override now remembers the window it was asked for. When the same swapchain and +surface ask for the same window again within 100 ms, the request returns at once; after +100 ms the walk runs again, so a window that moved to another top level is still found. + +## 0122 Wayland: wake steamcompmgr after reading host events + +Backport of upstream commit 2962992 by Matthew Schwartz (ValveSoftware/gamescope). +The nested Wayland backend's input thread reads the host display, but steamcompmgr +does not watch that file descriptor, so buffer releases and presentation feedback +queued by that read could wait up to one refresh for steamcompmgr's next poll. The +input thread now wakes steamcompmgr after each read. + +## 0123 commit: fence lifetime fixes from upstream + +Backport of upstream commits 0efe47c and 666c52b by Matthew Schwartz (ValveSoftware/gamescope). +Pending commits share ownership of their completion list with the Xwayland context, so a late +fence signal can no longer append to a list freed with the context; and a commit being destroyed +no longer hands the image waiter a new reference to itself. Both touch the code 0124 changes. + +## 0124 commit: mark a finished frame done at import + +Every game frame took two passes of steamcompmgr's loop: the import duplicated the buffer's +fence and handed the commit to the image waiter (epoll add), then the waiter thread saw the fence +signalled, removed and closed it and woke steamcompmgr again to handle the finished commit. +`update_wayland_res` now polls the fence without waiting first. A frame that is already finished +is marked done at once - no duplicate fence, no epoll add or delete, no waiter wake - and the main +loop handles it in the same pass, after the import (FIFO commits still wait for a vblank). The +`commit_ready_check` convar (default on, `gamescopectl commit_ready_check 0`) turns it off; the +`xwm` log counts fences ready at import and waited for, every 10 s. diff --git a/tools/gamescope/patches/0121-override-content-skip-toplevel-walk.patch b/tools/gamescope/patches/0121-override-content-skip-toplevel-walk.patch new file mode 100644 index 0000000000..016ae5af37 --- /dev/null +++ b/tools/gamescope/patches/0121-override-content-skip-toplevel-walk.patch @@ -0,0 +1,55 @@ +diff --git a/src/wlserver.cpp b/src/wlserver.cpp +index 9a027a2..e6d8e31 100644 +--- a/src/wlserver.cpp ++++ b/src/wlserver.cpp +@@ -98,6 +98,8 @@ struct wlserver_content_override { + uint32_t x11_window; + struct wl_listener surface_destroy_listener; + struct wl_resource *gamescope_swapchain; ++ uint32_t requested_window; ++ uint64_t ulCheckedNs; + }; + + std::mutex g_wlserver_xdg_shell_windows_lock; +@@ -800,6 +802,20 @@ static void gamescope_swapchain_destroy_co( struct wl_resource *resource ); + + void gamescope_xwayland_server_t::handle_override_window_content( struct wl_client *client, struct wl_resource *gamescope_swapchain_resource, struct wlr_surface *surface, uint32_t x11_window ) + { ++ // The WSI layer sends this on every present. Finding the top level walks the X tree with a ++ // round trip per level, so a swapchain repeating the same window skips it for 100 ms. ++ const uint64_t ulNow = get_time_in_nanos(); ++ if ( gamescope_swapchain_resource ) ++ { ++ for ( const auto &[ window, existing ] : content_overrides ) ++ { ++ if ( existing->gamescope_swapchain == gamescope_swapchain_resource && existing->surface == surface && ++ existing->requested_window == x11_window && ulNow - existing->ulCheckedNs < 100'000'000ul ) ++ return; ++ } ++ } ++ ++ const uint32_t requested_window = x11_window; + x11_window = x11_find_toplevel_for_xid( this->ctx->dpy, x11_window ); + + wlserver_x11_surface_info *x11_surface = lookup_x11_surface_info_from_xid( this, x11_window ); +@@ -813,7 +829,11 @@ void gamescope_xwayland_server_t::handle_override_window_content( struct wl_clie + + if ( content_overrides.count( x11_window ) ) { + if ( content_overrides[x11_window]->gamescope_swapchain == gamescope_swapchain_resource ) ++ { ++ content_overrides[x11_window]->requested_window = requested_window; ++ content_overrides[x11_window]->ulCheckedNs = ulNow; + return; ++ } + #ifdef GAMESCOPE_SWAPCHAIN_DEBUG + wl_log.infof( "handle_override_window_content: (2) DESTROYING x11_window: 0x%x old_swapchain: %p new_swapchain: %p", x11_window, content_overrides[x11_window]->gamescope_swapchain, gamescope_swapchain_resource ); + #endif +@@ -830,6 +850,8 @@ void gamescope_xwayland_server_t::handle_override_window_content( struct wl_clie + co->surface = surface; + co->x11_window = x11_window; + co->gamescope_swapchain = gamescope_swapchain_resource; ++ co->requested_window = requested_window; ++ co->ulCheckedNs = ulNow; + co->surface_destroy_listener.notify = content_override_handle_surface_destroy; + wl_signal_add( &surface->events.destroy, &co->surface_destroy_listener ); + content_overrides[ x11_window ] = co; diff --git a/tools/gamescope/patches/0122-wayland-wake-after-host-events.patch b/tools/gamescope/patches/0122-wayland-wake-after-host-events.patch new file mode 100644 index 0000000000..0be39bf16c --- /dev/null +++ b/tools/gamescope/patches/0122-wayland-wake-after-host-events.patch @@ -0,0 +1,14 @@ +diff --git a/src/Backends/WaylandBackend.cpp b/src/Backends/WaylandBackend.cpp +index 1b85e63..370661d 100644 +--- a/src/Backends/WaylandBackend.cpp ++++ b/src/Backends/WaylandBackend.cpp +@@ -2977,6 +2977,9 @@ namespace gamescope + LogDisplayError( "Failed to read events on input thread", m_pBackend->GetDisplay() ); + abort(); + } ++ ++ // Reading also queues releases and presentation feedback for steamcompmgr. ++ nudge_steamcompmgr(); + } + } + diff --git a/tools/gamescope/patches/0123-commit-fence-lifetime-upstream.patch b/tools/gamescope/patches/0123-commit-fence-lifetime-upstream.patch new file mode 100644 index 0000000000..75e93b68a0 --- /dev/null +++ b/tools/gamescope/patches/0123-commit-fence-lifetime-upstream.patch @@ -0,0 +1,157 @@ +diff --git a/src/commit.cpp b/src/commit.cpp +index c9d0001..f2e0f0c 100644 +--- a/src/commit.cpp ++++ b/src/commit.cpp +@@ -105,14 +105,15 @@ bool commit_t::CloseFenceInternal() + if ( m_nCommitFence < 0 ) + return false; + +- // Will automatically remove from epoll! +- g_ImageWaiter.RemoveWaitable( this ); ++ // Do not recreate an Rc after deletion has started. ++ if ( HasLiveReferences() ) ++ g_ImageWaiter.RemoveWaitable( this ); + close( m_nCommitFence ); + m_nCommitFence = -1; + return true; + } + +-void commit_t::SetFence( int nFence, bool bMangoNudge, uint32_t uMangoMsgType, CommitDoneList_t *pDoneCommits ) ++void commit_t::SetFence( int nFence, bool bMangoNudge, uint32_t uMangoMsgType, const std::shared_ptr &pDoneCommits ) + { + std::unique_lock lock( m_WaitableCommitStateMutex ); + CloseFenceInternal(); +diff --git a/src/commit.h b/src/commit.h +index 20f881d..8603a9a 100644 +--- a/src/commit.h ++++ b/src/commit.h +@@ -1,6 +1,7 @@ + #include "steamcompmgr_shared.hpp" + #include "Utils/NonCopyable.h" + ++#include + #include + #include "main.hpp" + #include "rendervulkan.hpp" +@@ -34,7 +35,7 @@ struct commit_t final : public gamescope::RcObject, public gamescope::IWaitable, + + // Returns true if we had a fence that was closed. + bool CloseFenceInternal(); +- void SetFence( int nFence, bool bMangoNudge, uint32_t uMangoMsgType, CommitDoneList_t *pDoneCommits ); ++ void SetFence( int nFence, bool bMangoNudge, uint32_t uMangoMsgType, const std::shared_ptr &pDoneCommits ); + + bool ShouldPreemptivelyUpscale( GamescopeUpscaleFilter eFilter, GamescopeUpscaleScaler eScaler ); + +@@ -81,5 +82,5 @@ struct commit_t final : public gamescope::RcObject, public gamescope::IWaitable, + bool m_bMangoNudge = false; + // Typed mangoapp stream to nudge, 0 for none, never the legacy type. + uint32_t m_uMangoMsgType = 0; +- CommitDoneList_t *m_pDoneCommits = nullptr; // I hate this +-}; +\ No newline at end of file ++ std::shared_ptr m_pDoneCommits; // I hate this ++}; +diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp +index 5fb9086..22aa907 100644 +--- a/src/steamcompmgr.cpp ++++ b/src/steamcompmgr.cpp +@@ -932,7 +932,7 @@ constexpr const T& clamp( const T& x, const T& min, const T& max ) + + extern bool g_bForceRelativeMouse; + +-CommitDoneList_t g_steamcompmgr_xdg_done_commits; ++std::shared_ptr g_steamcompmgr_xdg_done_commits = std::make_shared(); + + + static std::mutex s_KeysToCloseMutex; +@@ -8073,7 +8073,7 @@ bool handle_done_commit( steamcompmgr_win_t *w, xwayland_ctx_t *ctx, uint64_t co + // TODO: Merge these two functions. + void handle_done_commits_xwayland( xwayland_ctx_t *ctx, bool vblank, uint64_t vblank_idx ) + { +- std::lock_guard lock( ctx->doneCommits.listCommitsDoneLock ); ++ std::lock_guard lock( ctx->doneCommits->listCommitsDoneLock ); + + uint64_t next_refresh_time = g_SteamCompMgrVBlankTime.schedule.ulTargetVBlank; + +@@ -8090,7 +8090,7 @@ void handle_done_commits_xwayland( xwayland_ctx_t *ctx, bool vblank, uint64_t vb + uint64_t now = get_time_in_nanos(); + + // very fast loop yes +- for ( auto& entry : ctx->doneCommits.listCommitsDone ) ++ for ( auto& entry : ctx->doneCommits->listCommitsDone ) + { + steamcompmgr_win_t *entry_win = nullptr; + for ( steamcompmgr_win_t *w = ctx->list; w; w = w->xwayland().next ) +@@ -8130,12 +8130,12 @@ void handle_done_commits_xwayland( xwayland_ctx_t *ctx, bool vblank, uint64_t vb + } + } + +- ctx->doneCommits.listCommitsDone.swap( commits_before_their_time ); ++ ctx->doneCommits->listCommitsDone.swap( commits_before_their_time ); + } + + void handle_done_commits_xdg( bool vblank, uint64_t vblank_idx ) + { +- std::lock_guard lock( g_steamcompmgr_xdg_done_commits.listCommitsDoneLock ); ++ std::lock_guard lock( g_steamcompmgr_xdg_done_commits->listCommitsDoneLock ); + + uint64_t next_refresh_time = g_SteamCompMgrVBlankTime.schedule.ulTargetVBlank; + +@@ -8152,7 +8152,7 @@ void handle_done_commits_xdg( bool vblank, uint64_t vblank_idx ) + uint64_t now = get_time_in_nanos(); + + // very fast loop yes +- for ( auto& entry : g_steamcompmgr_xdg_done_commits.listCommitsDone ) ++ for ( auto& entry : g_steamcompmgr_xdg_done_commits->listCommitsDone ) + { + steamcompmgr_win_t *entry_win = nullptr; + for (const auto& xdg_win : g_steamcompmgr_xdg_wins) +@@ -8192,7 +8192,7 @@ void handle_done_commits_xdg( bool vblank, uint64_t vblank_idx ) + } + } + +- g_steamcompmgr_xdg_done_commits.listCommitsDone.swap( commits_before_their_time ); ++ g_steamcompmgr_xdg_done_commits->listCommitsDone.swap( commits_before_their_time ); + } + + gamescope::ConVar cv_mangoapp_use_output_timing{ "mangoapp_use_output_timing", true }; +@@ -8359,7 +8359,7 @@ static TempUpscaleImage_t *GetTempUpscaleImage( global_focus_t *pFocus, uint32_t + + gamescope::ConVar cv_surface_update_force_only_current_surface( "surface_update_force_only_current_surface", false, "Force updates to apply only to the current surface, ignoring commits for other surfaces." ); + +-void update_wayland_res(CommitDoneList_t *doneCommits, steamcompmgr_win_t *w, ResListEntry_t& reslistentry) ++void update_wayland_res(const std::shared_ptr &doneCommits, steamcompmgr_win_t *w, ResListEntry_t& reslistentry) + { + struct wlr_buffer *buf = reslistentry.buf; + +@@ -8632,7 +8632,7 @@ void check_new_xwayland_res(xwayland_ctx_t *ctx) + for ( uint32_t i = 0; i < tmp_queue.size(); i++ ) + { + steamcompmgr_win_t *w = find_win( ctx, tmp_queue[ i ].surf ); +- update_wayland_res( &ctx->doneCommits, w, tmp_queue[ i ]); ++ update_wayland_res( ctx->doneCommits, w, tmp_queue[ i ]); + } + } + +@@ -8645,7 +8645,7 @@ void check_new_xdg_res() + { + if ( xdg_win->xdg().surface.main_surface == tmp_queue[ i ].surf ) + { +- update_wayland_res( &g_steamcompmgr_xdg_done_commits, xdg_win.get(), tmp_queue[ i ] ); ++ update_wayland_res( g_steamcompmgr_xdg_done_commits, xdg_win.get(), tmp_queue[ i ] ); + break; + } + } +diff --git a/src/xwayland_ctx.hpp b/src/xwayland_ctx.hpp +index 81910a1..3a75650 100644 +--- a/src/xwayland_ctx.hpp ++++ b/src/xwayland_ctx.hpp +@@ -92,7 +92,7 @@ struct xwayland_ctx_t final : public gamescope::IWaitable + + std::unique_ptr cursor; + +- CommitDoneList_t doneCommits; ++ std::shared_ptr doneCommits = std::make_shared(); + + double accum_x = 0.0; + double accum_y = 0.0; diff --git a/tools/gamescope/patches/0124-commit-done-at-import.patch b/tools/gamescope/patches/0124-commit-done-at-import.patch new file mode 100644 index 0000000000..9ac818e4eb --- /dev/null +++ b/tools/gamescope/patches/0124-commit-done-at-import.patch @@ -0,0 +1,103 @@ +diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp +index 22aa907..0aef598 100644 +--- a/src/steamcompmgr.cpp ++++ b/src/steamcompmgr.cpp +@@ -8359,6 +8359,33 @@ static TempUpscaleImage_t *GetTempUpscaleImage( global_focus_t *pFocus, uint32_t + + gamescope::ConVar cv_surface_update_force_only_current_surface( "surface_update_force_only_current_surface", false, "Force updates to apply only to the current surface, ignoring commits for other surfaces." ); + ++gamescope::ConVar cv_commit_ready_check( "commit_ready_check", true, "Check a new commit's fence at import; a finished frame is marked done in the same pass instead of through the image waiter." ); ++ ++// Set when update_wayland_res marks a commit done itself, so the main loop handles it in the same pass. ++static bool s_bXwaylandCommitsDoneAtImport = false; ++static bool s_bXdgCommitsDoneAtImport = false; ++ ++static bool commit_fence_ready_now( int nFd ) ++{ ++ struct pollfd pfd = { .fd = nFd, .events = POLLIN, .revents = 0 }; ++ return poll( &pfd, 1, 0 ) == 1 && ( pfd.revents & POLLIN ); ++} ++ ++static void note_commit_fence( bool bReadyAtImport ) ++{ ++ static uint64_t s_ulReady = 0, s_ulWaited = 0, s_ulLastLog = 0; ++ ( bReadyAtImport ? s_ulReady : s_ulWaited )++; ++ uint64_t now = get_time_in_nanos(); ++ if ( !s_ulLastLog ) ++ s_ulLastLog = now; ++ if ( now - s_ulLastLog >= 10'000'000'000ul ) ++ { ++ xwm_log.infof( "commit fences, last 10 s: %lu ready at import, %lu waited for", s_ulReady, s_ulWaited ); ++ s_ulReady = s_ulWaited = 0; ++ s_ulLastLog = now; ++ } ++} ++ + void update_wayland_res(const std::shared_ptr &doneCommits, steamcompmgr_win_t *w, ResListEntry_t& reslistentry) + { + struct wlr_buffer *buf = reslistentry.buf; +@@ -8602,7 +8629,11 @@ void update_wayland_res(const std::shared_ptr &doneCommits, st + struct wlr_dmabuf_attributes dmabuf = {0}; + if ( wlr_buffer_get_dmabuf( buf, &dmabuf ) ) + { +- fence = dup( dmabuf.fd[0] ); ++ // A finished buffer needs no fence of its own. ++ if ( cv_commit_ready_check && commit_fence_ready_now( dmabuf.fd[0] ) ) ++ bKnownReady = true; ++ else ++ fence = dup( dmabuf.fd[0] ); + } + else + { +@@ -8610,11 +8641,22 @@ void update_wayland_res(const std::shared_ptr &doneCommits, st + } + } + ++ if ( cv_commit_ready_check ) ++ { ++ if ( !bKnownReady && fence >= 0 && commit_fence_ready_now( fence ) ) ++ bKnownReady = true; ++ note_commit_fence( bKnownReady ); ++ } ++ + gpuvis_trace_printf( "pushing wait for commit %lu win %lx", newCommit->commitID, w->type == steamcompmgr_win_type_t::XWAYLAND ? w->xwayland().id : 0 ); + { + newCommit->SetFence( fence, mango_nudge, uMangoMsgType, doneCommits ); + if ( bKnownReady ) ++ { + newCommit->Signal(); ++ if ( cv_commit_ready_check ) ++ ( w->type == steamcompmgr_win_type_t::XWAYLAND ? s_bXwaylandCommitsDoneAtImport : s_bXdgCommitsDoneAtImport ) = true; ++ } + else + g_ImageWaiter.AddWaitable( newCommit.get() ); + } +@@ -9400,6 +9442,13 @@ void steamcompmgr_check_xdg(bool vblank, uint64_t vblank_idx) + } + + check_new_xdg_res(); ++ ++ // Commits marked done at import: handle them now rather than on the next wake. FIFO commits still wait for a vblank. ++ if ( s_bXdgCommitsDoneAtImport ) ++ { ++ s_bXdgCommitsDoneAtImport = false; ++ handle_done_commits_xdg( false, vblank_idx ); ++ } + } + + void update_edid_prop() +@@ -10512,6 +10561,14 @@ steamcompmgr_main(int argc, char **argv) + gamescope_xwayland_server_t *server = NULL; + for (size_t i = 0; (server = wlserver_get_xwayland_server(i)); i++) + check_new_xwayland_res(server->ctx.get()); ++ ++ // Commits marked done at import: handle them now rather than on the next wake. FIFO commits still wait for a vblank. ++ if ( s_bXwaylandCommitsDoneAtImport ) ++ { ++ s_bXwaylandCommitsDoneAtImport = false; ++ for (size_t i = 0; (server = wlserver_get_xwayland_server(i)); i++) ++ handle_done_commits_xwayland(server->ctx.get(), false, vblank_idx); ++ } + } + + diff --git a/tools/gamescope/release.env b/tools/gamescope/release.env index 676a020370..996f24a812 100644 --- a/tools/gamescope/release.env +++ b/tools/gamescope/release.env @@ -1,3 +1,3 @@ GAMESCOPE_REPO=Droid-Deck/DroidDeck-Components -GAMESCOPE_TAG=gamescope-3.16.29-p16 -GAMESCOPE_SHA256=8ae783d730d910de9a44ddb98dd567643e9cf7987f16ef261fe08cd2c4a7ba5c +GAMESCOPE_TAG=gamescope-3.16.29-p18 +GAMESCOPE_SHA256=a79d8acc5628973c807a43524638c20e7d5c101a4fc3bcb8b5068631e6f6fe55 diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env b/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env index 288c8d57c2..025d84d26b 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env @@ -357,21 +357,76 @@ def game_cores(env): print("droiddeck-game-env: could not use game cores %r (%s)" % (text, error), file=sys.stderr) -def cpu_topology(env): +def core_speeds(cores, root="/sys/devices/system/cpu"): + """Each core's capacity, else its top clock; None when some core reports neither.""" + for name in ("cpu_capacity", "cpufreq/cpuinfo_max_freq"): + speeds = {} + for core in cores: + try: + with open("%s/cpu%d/%s" % (root, core, name)) as f: + speeds[core] = int(f.read().strip()) + except (OSError, ValueError): + break + else: + return speeds + return None + + +def fastest_first(cores): + """The cores, fastest first; cores of equal or unknown speed keep their numeric order.""" + cores = sorted(cores) + speeds = core_speeds(cores) + return sorted(cores, key=lambda core: -speeds[core]) if speeds else cores + + +def proton_cpu_limit(command, env): + """This game's entry in Proton's own default_cpu_limit list: a core count, another value such as "P" as text, or None.""" + app_id = env.get("SteamGameId", "") + if not command or not app_id.isdigit(): + return None + try: + if os.path.getsize(command[0]) > 4 * 1024 * 1024: + return None + with open(command[0], encoding="utf-8", errors="replace") as f: + text = f.read() + except OSError: + return None + table = re.search(r"^default_cpu_limit = \{(.*?)^\}", text, re.M | re.S) + match = table and re.search(r'^\s*"%s"\s*:\s*"?(\w+)' % app_id, table.group(1), re.M) + if not match: + return None + value = match.group(1) + return int(value) if value.isdigit() else value + + +def cpu_topology(env, command=()): + """Windows sees the game's cores fastest first, so a thread a game pins to CPU 0 runs on the fastest core.""" if "PROTON_CPU_TOPOLOGY" in env: return if "WINE_CPU_TOPOLOGY" in env: if env["WINE_CPU_TOPOLOGY"]: env["PROTON_CPU_TOPOLOGY"] = env["WINE_CPU_TOPOLOGY"] return - if not (env.get("DROIDDECK_GAME_CORES", "").strip() or env.get("BL_GAME_CPUS", "").strip()): + picked = bool(env.get("DROIDDECK_GAME_CORES", "").strip() or env.get("BL_GAME_CPUS", "").strip()) + fastest = env.get("DROIDDECK_FASTEST_CORES", "").strip() != "0" and game_id(env) is not None + if not (picked or fastest): return try: cores = sorted(os.sched_getaffinity(0)) except OSError: return online = online_cores() - if not cores or set(cores) >= online or cores[-1] >= len(online): + if not cores or cores[-1] >= len(online): + return + picked = picked and not set(cores) >= online + if fastest: + limit = None if picked else proton_cpu_limit(command, env) + if isinstance(limit, str): + return + cores = fastest_first(cores)[:limit or None] + elif set(cores) >= online: + return + if cores == sorted(online): return env["WINE_CPU_TOPOLOGY"] = env["PROTON_CPU_TOPOLOGY"] = "%d:%s" % (len(cores), ",".join(map(str, cores))) print("droiddeck-game-env: Windows sees %d cores (%s)" % (len(cores), env["WINE_CPU_TOPOLOGY"]), file=sys.stderr) @@ -409,6 +464,59 @@ def apply_config(env, config, app_id, fixes=None): return result +GAME_DEBUG_CHANNELS = ( + "timestamp", "pid", "tid", "seh", "unwind", "threadname", "debugstr", "loaddll", "mscoree", +) +WINE_DEBUG_SELECTOR = re.compile(r"(?:(trace|warn|err|fixme))?([+-])([A-Za-z_][A-Za-z0-9_]*)") + + +def game_debug_channels(*values): + """Normalize Wine selectors, retaining custom channels before required diagnostics.""" + selectors = {} + for value in values: + if not isinstance(value, str) or "\0" in value or len(value) > 8192: + continue + for part in value.split(","): + part = part.strip() + match = WINE_DEBUG_SELECTOR.fullmatch(part) + if match is None: + continue + key = (match[1] or "", match[3]) + # Move the last value to the end: global +/-all and per-class selectors + # have ordered semantics, so replacing a value in its old position is wrong. + selectors.pop(key, None) + selectors[key] = part + for channel in GAME_DEBUG_CHANNELS: + key = ("", channel) + selectors.pop(key, None) + selectors[key] = "+" + channel + formatted = ",".join(selectors.values()) + if len(formatted) > 8192: + formatted = ",".join("+" + channel for channel in GAME_DEBUG_CHANNELS) + return formatted + + +def apply_game_debug_logs(env, config, debug_dir): + """Apply app-owned diagnostics to a real game, without editing its launch command.""" + if not isinstance(config, dict) or config.get("version") != 1 or config.get("gameDebugLogs") is not True: + return env + if (not isinstance(debug_dir, str) or "\0" in debug_dir or len(debug_dir) > 8192 + or not os.path.isabs(debug_dir) or not os.path.isdir(debug_dir)): + print("droiddeck-game-env: game debug logs skipped; session log directory unavailable", file=sys.stderr) + return env + result = dict(env) + result.update({ + "PROTON_LOG": "1", + "PROTON_LOG_DIR": debug_dir, + "PROTON_CRASH_REPORT_DIR": debug_dir, + "DXVK_LOG_PATH": debug_dir, + "DXVK_LOG_LEVEL": "debug", + "VKD3D_DEBUG": "info", + "WINEDEBUG": game_debug_channels(env.get("WINEDEBUG"), env.get("PROTON_LOG")), + }) + return result + + def sync_config(config, app_id): games = config.get("games", {}) return { @@ -610,6 +718,7 @@ def main(): return 2 env = game_gpu(os.environ.copy()) mic_enabled = env.get("BL_MIC_ENABLED") + debug_dir = env.get("BL_DEBUG_DIR", "") scripts = mark_install_scripts(command, env) if scripts and install_scripts_done(scripts, env): print("droiddeck-game-env: install scripts already run in this prefix; evaluator skipped", file=sys.stderr) @@ -634,6 +743,7 @@ def main(): own = fixes.get("WINEDLLOVERRIDES") fixes["WINEDLLOVERRIDES"] = components + ";" + own if own else components path = Path.home() / ".config/droiddeck/game-environment.json" + config = {} try: with path.open(encoding="utf-8") as source: config = json.load(source) @@ -646,6 +756,11 @@ def main(): env = apply_config(env, {"version": 1}, app_id, fixes) except (OSError, ValueError, TypeError, AttributeError): print("droiddeck-game-env: invalid configuration; using inherited environment", file=sys.stderr) + if waiting: + before_debug = env + env = apply_game_debug_logs(env, config, debug_dir) + if env is not before_debug: + print("droiddeck-game-env: game debug logs enabled for this launch", file=sys.stderr) if app_id and len(command) > 1 and command[1] == "waitforexitandrun": command = offline_without_anticheat(command, env) if mic_enabled == "0": @@ -653,7 +768,7 @@ def main(): env = vram_cap(env) env = force_ssbs(command, env) game_cores(env) - cpu_topology(env) + cpu_topology(env, command) try: xbox = runpy.run_path(str(Path(__file__).with_name("droiddeck-xbox"))) except Exception as error: diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-x64 b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-x64 index 17d4490f17..f6d7d1d92d 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-x64 +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-x64 @@ -799,13 +799,25 @@ x64_gpu_watch() { x64_gpu_probe } +x64_arm_webhelper_cpu_supported() { + local status=0 + # Valve's native ARM web helper contains LSE atomics; missing CPU data cannot establish incompatibility. + awk -F: ' + $1 ~ /^[[:space:]]*Features[[:space:]]*$/ { + if ($2 !~ /(^|[[:space:]])atomics([[:space:]]|$)/) unsupported = 1 + } + END { exit unsupported ? 1 : 0 } + ' /proc/cpuinfo 2>/dev/null || status=$? + [ "$status" != 1 ] +} + x64_exec() { x64_env cd "$STEAM_X64" # The client checksums its files at start and reinstalls over edited ones, so the session shim (preload/net.c) # swaps the web helper at exec. The arm64 helper only comes up against a client of the same build. if [ "${BL_X64_X86_WEBHELPER:-0}" != 1 ] && [ -x /usr/local/bin/droiddeck-x64-arm-webhelper ] && - [ -x "$ARM_STEAM/steamrtarm64/steamwebhelper" ]; then + [ -x "$ARM_STEAM/steamrtarm64/steamwebhelper" ] && x64_arm_webhelper_cpu_supported; then local chan x86_build arm_build chan=$(cat "$STEAM_X64/package/beta" 2>/dev/null || echo "$X64_CHANNEL") x86_build=$(awk -F'"' '$2 == "version" { print $4; exit }' "$STEAM_X64/package/steam_client_${chan}_steamrt64.manifest" 2>/dev/null || true) @@ -1049,4 +1061,4 @@ for attempt in 1 2 3 4 5; do ( x64_exec -clientbeta "$X64_CHANNEL" -no-cef-sandbox "${cef[@]}" "$@" ) >>"$LOG" 2>&1 || rc=$? step "client exited rc=$rc" [ "$rc" = 42 ] || break -done \ No newline at end of file +done diff --git a/tools/linuxfs/overlay/usr/local/bin/steam-compatibility b/tools/linuxfs/overlay/usr/local/bin/steam-compatibility index b1864dfadf..47c83fbd9a 100755 --- a/tools/linuxfs/overlay/usr/local/bin/steam-compatibility +++ b/tools/linuxfs/overlay/usr/local/bin/steam-compatibility @@ -276,6 +276,18 @@ bl_vacdiag() { } """ +# Steam's shader pre-caching runs its D3D driver query through every Proton tool at each start, as +# "run /bin/d3ddriverquery64.exe" in compatdata/0. Here it has never succeeded (exit 1 every time), and each +# run started Wine in compatdata/0, where the two Protons upgrade the prefix back and forth for many seconds while the +# game starts. Steam gets the same failure without starting Wine; other verbs and prefixes are left alone. +BL_DRIVER_QUERY_SKIP = """ +case "$verb:${1##*/}:${STEAM_COMPAT_DATA_PATH%/}" in + run:d3ddriverquery64.exe:*/compatdata/0 | run:d3ddriverquery.exe:*/compatdata/0) + echo "droiddeck-proton: Steam's D3D driver query is not run (it fails here and would start Wine in compatdata/0)" >&2 + exit 1 ;; +esac +""" + BL_DIRECTAUDIO_SETUP = """ bl_is_steam_installscript_target() { local target=${1:-} @@ -408,7 +420,7 @@ LAUNCHER_TEMPLATE = LAUNCHER_SH def launcher_sh(sources=SOURCES): return (LAUNCHER_TEMPLATE % " ".join('"%s"' % n for n in sources)).replace( - "verb=$1; shift", "verb=$1; shift\n" + BL_DESKTOP_GPU_SETUP + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP + "verb=$1; shift", "verb=$1; shift\n" + BL_DRIVER_QUERY_SKIP + BL_DESKTOP_GPU_SETUP + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP + BL_VACDIAG_SETUP + BL_COMPONENTS_SETUP + BL_LIBPATH_SETUP + BL_STORE_SETUP, 1) @@ -455,6 +467,15 @@ bl_store_launch "$@" BL_STORE_ARGS=("$@") bl_run ${BL_TASKSET:-} /usr/local/bin/droiddeck-game-env "$BL_STORE_PROTON" "$verb" "$@" "${BL_EXTRA_ARGS[@]}" """ + + +def extra_wrapper_sh(entry_point): + return (EXTRA_WRAPPER_SH % entry_point).replace( + 'here=$(dirname "$0")', + 'here=$(dirname "$0")\n' + BL_DRIVER_QUERY_SKIP + BL_DESKTOP_GPU_SETUP + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + + BL_IDTECH3_SETUP + BL_VACDIAG_SETUP + BL_COMPONENTS_SETUP + BL_LIBPATH_SETUP + BL_STORE_SETUP, 1) + + EXTRA_COMPAT_TOOL_VDF = """"compatibilitytools" { "compat_tools" @@ -678,11 +699,7 @@ def adopt_extras(tools): name = first_key(compat_vdf, ["compatibilitytools", "compat_tools"]) or entry wrapper = os.path.join(tool_dir, EXTRA_WRAPPER) try: - body = (EXTRA_WRAPPER_SH % entry_point).replace( - 'here=$(dirname "$0")', - 'here=$(dirname "$0")\n' + BL_DESKTOP_GPU_SETUP + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP - + BL_VACDIAG_SETUP + BL_COMPONENTS_SETUP + BL_LIBPATH_SETUP + BL_STORE_SETUP, 1) - write_changed(wrapper, body, 0o755) + write_changed(wrapper, extra_wrapper_sh(entry_point), 0o755) write_changed(manifest, EXTRA_MANIFEST_VDF) write_changed(compat_vdf, EXTRA_COMPAT_TOOL_VDF % (name, display_name(entry))) legacy_wrapper = os.path.join(tool_dir, LEGACY_EXTRA_WRAPPER) diff --git a/tools/release/sign-apk.sh b/tools/release/sign-apk.sh index 2cf46c551e..c0fd0ace68 100755 --- a/tools/release/sign-apk.sh +++ b/tools/release/sign-apk.sh @@ -27,6 +27,7 @@ if [ "$pkg" = "$P" ]; then else python3 "$here/axml_rename.py" "$in" "$work/renamed.apk" \ "$P=$pkg" "$P.androidx-startup=$pkg.androidx-startup" "$P.logs=$pkg.logs" \ + "$P.pairingguide=$pkg.pairingguide" "$P.pin=$pkg.pin" \ "$P.documents=$pkg.documents" "$P.home=$pkg.home" "$P.agent=$pkg.agent" \ "$P.vr_recovery=$pkg.vr_recovery" \ "$P.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION=$pkg.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION" diff --git a/tools/tests/test_android_volume.py b/tools/tests/test_android_volume.py index 8246f34fe1..44d34f9b45 100644 --- a/tools/tests/test_android_volume.py +++ b/tools/tests/test_android_volume.py @@ -44,6 +44,7 @@ typedef struct pa_sink { struct android_volume; struct userdata { struct android_volume *android_volume; }; static int restarts, frees; +static uint64_t last_delay; static char *pa_sprintf_malloc(const char *format, ...) { va_list ap; va_start(ap,format); char *result; assert(vasprintf(&result,format,ap)>=0); va_end(ap); return result; } @@ -57,7 +58,7 @@ static void pa_sink_set_set_volume_callback(pa_sink *sink, void (*callback)(pa_s static void pa_sink_set_set_mute_callback(pa_sink *sink, void (*callback)(pa_sink*)) { sink->set_mute=callback; } static void pa_subscription_post(pa_core *core, int event, unsigned index) {} static uint64_t pa_rtclock_now(void) { return 0; } -static void pa_core_rttime_restart(pa_core *core, pa_time_event *event, uint64_t time) { restarts++; } +static void pa_core_rttime_restart(pa_core *core, pa_time_event *event, uint64_t time) { restarts++; last_delay=time; } static pa_time_event *pa_core_rttime_new(pa_core *core, uint64_t time, void (*callback)(pa_mainloop_api*,pa_time_event*,const struct timeval*,void*), void *userdata) { return calloc(1,sizeof(pa_time_event)); @@ -76,11 +77,18 @@ int main(int argc, char **argv) { assert(userdata.android_volume && userdata.android_volume->timer && sink.set_volume && sink.set_mute); state(argv[1],"invalid\n"); android_volume_refresh(&api,userdata.android_volume->timer,NULL,userdata.android_volume); - assert(sink.real_volume.value==PA_VOLUME_NORM && restarts==1); + assert(sink.real_volume.value==PA_VOLUME_NORM && restarts==1 && last_delay==100*PA_USEC_PER_MSEC); state(argv[1],"3 15 1\n"); android_volume_refresh(&api,userdata.android_volume->timer,NULL,userdata.android_volume); assert(sink.real_volume.value==3*PA_VOLUME_NORM/15 && sink.muted && sink.n_volume_steps==16); assert(sink.soft_volume.value==PA_VOLUME_NORM && restarts==2); + assert(last_delay==16*PA_USEC_PER_MSEC); + state(argv[1],"4 15 1\n"); + android_volume_refresh(&api,userdata.android_volume->timer,NULL,userdata.android_volume); + assert(sink.real_volume.value==4*PA_VOLUME_NORM/15 && last_delay==16*PA_USEC_PER_MSEC); + for (int i = 0; i < ANDROID_VOLUME_ACTIVE_TICKS + 1; i++) + android_volume_refresh(&api,userdata.android_volume->timer,NULL,userdata.android_volume); + assert(last_delay==100*PA_USEC_PER_MSEC); sink.real_volume.value=2*PA_VOLUME_NORM/3; sink.set_volume(&sink); char *request=pa_sprintf_malloc("%s/volume.request",argv[1]); FILE *f=fopen(request,"r"); unsigned level; assert(f && fscanf(f,"%u",&level)==1 && level==10); fclose(f); free(request); diff --git a/tools/tests/test_game_environment.py b/tools/tests/test_game_environment.py index 0b1bee1753..ebb6110368 100644 --- a/tools/tests/test_game_environment.py +++ b/tools/tests/test_game_environment.py @@ -28,6 +28,121 @@ def config_text(entries): return '"InstallConfigStore" { "Software" { "Valve" { "Steam" { "CompatToolMapping" { %s } } } } }' % mapping +class GameDebugLoggingTest(unittest.TestCase): + def test_real_game_launch_without_config_file_keeps_the_base_environment(self): + with tempfile.TemporaryDirectory() as tmp: + home = Path(tmp) + probe = home / "proton" + probe.write_text("#!" + sys.executable + "\nimport os\nprint(os.environ['PROTON_LOG'])\n") + probe.chmod(0o755) + result = subprocess.run( + [sys.executable, str(BIN / "droiddeck-game-env"), str(probe), "waitforexitandrun"], + env={**os.environ, "HOME": tmp, "STEAM_COMPAT_DATA_PATH": str(home / "compatdata/42"), + "BL_DEBUG_DIR": tmp, "PROTON_LOG": "0"}, + text=True, capture_output=True, check=True, + ) + self.assertEqual(result.stdout.strip(), "0") + + def test_game_debug_logs_override_only_diagnostic_values_and_keep_raw_settings(self): + with tempfile.TemporaryDirectory(prefix="game logs '") as debug_dir: + inherited = {"BL_DEBUG_DIR": debug_dir, "PROTON_LOG": "0", "WINEDEBUG": "-all,+relay", + "PROTON_LOG_DIR": "/old", "PROTON_CRASH_REPORT_DIR": "/old-crashes", + "DXVK_LOG_PATH": "/old-dxvk", "DXVK_LOG_LEVEL": "none", "VKD3D_DEBUG": "none", + "CUSTOM": "$(touch never); 'quoted' = literal", "DXVK_CONFIG": "dxvk.tearFree = True"} + config = {"version": 1, "gameDebugLogs": True, + "shared": {"PROTON_LOG": "0", "BL_DEBUG_DIR": "/profile-redirect"}, + "games": {"42": {"PROTON_LOG_DIR": None, "DXVK_LOG_PATH": "/game-redirect"}}} + normal = MODULE["apply_config"](inherited, config, "42") + debug = MODULE["apply_game_debug_logs"](normal, config, inherited["BL_DEBUG_DIR"]) + self.assertEqual(debug["PROTON_LOG"], "1") + for key in ("PROTON_LOG_DIR", "PROTON_CRASH_REPORT_DIR", "DXVK_LOG_PATH"): + self.assertEqual(debug[key], debug_dir) + self.assertEqual(debug["DXVK_LOG_LEVEL"], "debug") + self.assertEqual(debug["VKD3D_DEBUG"], "info") + self.assertIn("+relay", debug["WINEDEBUG"].split(",")) + self.assertTrue(debug["WINEDEBUG"].endswith("+loaddll,+mscoree")) + for key in ("CUSTOM", "DXVK_CONFIG", "BL_DEBUG_DIR"): + self.assertEqual(debug[key], normal[key]) + self.assertEqual(normal["PROTON_LOG"], "0") + self.assertEqual(inherited["PROTON_LOG_DIR"], "/old") + self.assertIs(MODULE["apply_game_debug_logs"](normal, {**config, "gameDebugLogs": False}, debug_dir), normal) + self.assertEqual(MODULE["apply_game_debug_logs"](debug, config, debug_dir), debug) + + def test_wine_debug_channels_are_formatted_deduplicated_and_diagnostics_win(self): + formatted = MODULE["game_debug_channels"]( + " +relay, trace-vulkan, -all, -seh, +relay, trace+vulkan, garbage, $(touch never) ", + "+seh,warn-foo,warn+foo,+relay", + ) + self.assertEqual(formatted, "-all,trace+vulkan,warn+foo,+relay," + + "+timestamp,+pid,+tid,+seh,+unwind,+threadname,+debugstr,+loaddll,+mscoree") + self.assertEqual(MODULE["game_debug_channels"](formatted, "1"), formatted) + self.assertNotIn("-seh", formatted) + for value in ("x\0,+relay", "+" + "x" * 8192, 1, None): + self.assertEqual(MODULE["game_debug_channels"](value), MODULE["game_debug_channels"]()) + oversized = ",".join("+channel_" + str(i) for i in range(550)) + other = ",".join("+other_" + str(i) for i in range(550)) + self.assertLessEqual(len(MODULE["game_debug_channels"](oversized, other)), 8192) + self.assertTrue(MODULE["game_debug_channels"](oversized, other).endswith("+loaddll,+mscoree")) + + def test_game_debug_logs_require_opt_in_and_a_real_session_log_directory(self): + env = {"PROTON_LOG": "user", "CUSTOM": "keep"} + for config in ({}, {"version": 1}, {"version": 1, "gameDebugLogs": False}, + {"version": 1, "gameDebugLogs": "true"}, {"version": 2, "gameDebugLogs": True}): + self.assertIs(MODULE["apply_game_debug_logs"](env, config, "/"), env) + with tempfile.TemporaryDirectory() as tmp: + not_a_directory = Path(tmp) / "file" + not_a_directory.write_text("file") + for path in (None, "", "relative", "bad\0path", str(not_a_directory), str(Path(tmp) / "missing")): + with self.subTest(path=path): + self.assertIs(MODULE["apply_game_debug_logs"](env, {"version": 1, "gameDebugLogs": True}, path), env) + + def test_game_debug_toggle_is_live_preserves_command_and_excludes_probes(self): + with tempfile.TemporaryDirectory() as tmp: + home = Path(tmp) + config_path = home / ".config/droiddeck/game-environment.json" + config_path.parent.mkdir(parents=True) + debug_dir = home / "session logs '$literal; directory'" + debug_dir.mkdir() + probe = home / "fake proton" + probe.write_text("#!" + sys.executable + "\nimport json, os, sys\n" + "print(json.dumps({'env': dict(os.environ), 'argv': sys.argv[1:]}))\n") + probe.chmod(0o755) + literal = "$(touch " + str(home / "never-created") + "); 'literal'=value" + config = {"version": 1, "gameDebugLogs": True, + "shared": {"PROTON_LOG": "0", "WINEDEBUG": "-all,+relay", "CUSTOM": literal, + "BL_DEBUG_DIR": "/profile-must-not-redirect"}} + env = {**os.environ, "HOME": tmp, "STEAM_COMPAT_DATA_PATH": str(home / "compatdata/42"), + "BL_DEBUG_DIR": str(debug_dir), "PROTON_LOG": "0", "WINEDEBUG": "-all"} + command = [str(probe), "waitforexitandrun", "game 'with quotes'.exe", "argument with spaces", "$(literal)", "%command%"] + + def launch(arguments, environment): + result = subprocess.run([sys.executable, str(BIN / "droiddeck-game-env"), *arguments], + env=environment, text=True, capture_output=True, check=True) + return json.loads(result.stdout) + + for enabled in (True, False, True): + config_path.write_text(json.dumps({**config, "gameDebugLogs": enabled})) + result = launch(command, env) + self.assertEqual(result["argv"], command[1:]) + self.assertEqual(result["env"]["CUSTOM"], literal) + self.assertEqual(result["env"]["PROTON_LOG"], "1" if enabled else "0") + if enabled: + self.assertEqual(result["env"]["PROTON_LOG_DIR"], str(debug_dir)) + self.assertIn("+relay", result["env"]["WINEDEBUG"].split(",")) + self.assertIn("+seh", result["env"]["WINEDEBUG"].split(",")) + else: + self.assertEqual(result["env"]["WINEDEBUG"], "-all,+relay") + for verb, prefix in (("run", "42"), ("waitforexitandrun", "0"), ("waitforexitandrun", "not-a-game")): + result = launch([str(probe), verb], {**env, "STEAM_COMPAT_DATA_PATH": str(home / "compatdata" / prefix)}) + self.assertEqual(result["env"]["PROTON_LOG"], "0") + self.assertEqual(result["env"]["WINEDEBUG"], "-all") + # Non-Steam shortcuts use the same normalized unsigned compatdata identity. + result = launch(command, {**env, "STEAM_COMPAT_DATA_PATH": str(home / "compatdata/-1")}) + self.assertEqual(result["env"]["PROTON_LOG"], "1") + self.assertFalse((home / "never-created").exists()) + self.assertEqual(json.loads(config_path.read_text())["shared"], config["shared"]) + + class ReadConfigMappingTest(unittest.TestCase): def test_missing_parent_or_unbalanced_vdf_is_not_treated_as_absent_choices(self): with tempfile.TemporaryDirectory() as tmp: @@ -464,12 +579,78 @@ class GameEnvironmentTest(unittest.TestCase): ({"BL_GAME_CPUS": "9"}, {9}, None, None), ] for env, affinity, expected, proton in cases: + env["DROIDDECK_FASTEST_CORES"] = "0" with mock.patch.dict(MODULE["cpu_topology"].__globals__, online), \ mock.patch.object(os_mod, "sched_getaffinity", return_value=affinity, create=True): MODULE["cpu_topology"](env) self.assertEqual(env.get("WINE_CPU_TOPOLOGY"), expected, env) self.assertEqual(env.get("PROTON_CPU_TOPOLOGY"), proton, env) + def test_windows_cpu_0_is_the_fastest_core(self): + os_mod = MODULE["os"] + pocket_fit = {0: 379, 1: 379, 2: 923, 3: 923, 4: 923, 5: 867, 6: 867, 7: 1024} + every = set(range(8)) + with tempfile.TemporaryDirectory() as tmp: + proton = Path(tmp) / "proton" + proton.write_text('default_cpu_limit = {\n "19900" : "16", # Far Cry 2\n' + ' "2229830" : "1", # Command & Conquer\n "11440" : "4", # DiRT\n' + ' "1038250" : "P", # DIRT 5\n "618970" : 4, # Outcast, written as Proton 10 does\n' + '}\n\nother = {\n "620" : "2",\n}\n') + command = [str(proton), "waitforexitandrun", "/game/game.exe"] + cases = [ + ({}, every, pocket_fit, "8:7,2,3,4,5,6,0,1", "8:7,2,3,4,5,6,0,1"), + ({"BL_GAME_CPUS": "6,7"}, {6, 7}, pocket_fit, "2:7,6", "2:7,6"), + ({"DROIDDECK_GAME_CORES": "0-2"}, {0, 1, 2}, pocket_fit, "3:2,0,1", "3:2,0,1"), + ({"BL_GAME_CPUS": "0-7"}, every, pocket_fit, "8:7,2,3,4,5,6,0,1", "8:7,2,3,4,5,6,0,1"), + ({"WINE_CPU_TOPOLOGY": "2:0,1"}, every, pocket_fit, "2:0,1", "2:0,1"), + ({"WINE_CPU_TOPOLOGY": ""}, every, pocket_fit, "", None), + ({"PROTON_CPU_TOPOLOGY": "1:0"}, every, pocket_fit, None, "1:0"), + ({"DROIDDECK_FASTEST_CORES": "0"}, every, pocket_fit, None, None), + ({"SteamGameId": "2229830"}, every, pocket_fit, "1:7", "1:7"), + ({"SteamGameId": "11440"}, every, pocket_fit, "4:7,2,3,4", "4:7,2,3,4"), + ({"SteamGameId": "19900"}, every, pocket_fit, "8:7,2,3,4,5,6,0,1", "8:7,2,3,4,5,6,0,1"), + ({"SteamGameId": "1038250"}, every, pocket_fit, None, None), + ({"SteamGameId": "618970"}, every, pocket_fit, "4:7,2,3,4", "4:7,2,3,4"), + ({"SteamGameId": "620"}, every, pocket_fit, "8:7,2,3,4,5,6,0,1", "8:7,2,3,4,5,6,0,1"), + ({"SteamGameId": "2229830", "BL_GAME_CPUS": "0,1"}, {0, 1}, pocket_fit, "2:0,1", "2:0,1"), + ({"SteamGameId": "2229830", "DROIDDECK_GAME_CORES": "12-13"}, every, pocket_fit, "1:7", "1:7"), + ({"SteamGameId": "11440", "BL_GAME_CPUS": "0-7"}, every, pocket_fit, "4:7,2,3,4", "4:7,2,3,4"), + ({}, every, {core: 100 for core in every}, None, None), + ({}, every, None, None, None), + ({"SteamGameId": "11440"}, every, None, "4:0,1,2,3", "4:0,1,2,3"), + ({"BL_GAME_CPUS": "9"}, {9}, pocket_fit, None, None), + ] + cases += [ + ({"STEAM_COMPAT_DATA_PATH": "/steam/compatdata/0"}, every, pocket_fit, None, None), + ({"STEAM_COMPAT_DATA_PATH": ""}, every, pocket_fit, None, None), + ({"STEAM_COMPAT_DATA_PATH": "/steam/compatdata/0", "BL_GAME_CPUS": "6,7"}, {6, 7}, pocket_fit, "2:6,7", "2:6,7"), + ] + for env, affinity, speeds, expected, proton_topology in cases: + env.setdefault("STEAM_COMPAT_DATA_PATH", "/steam/compatdata/3608888694") + with mock.patch.dict(MODULE["cpu_topology"].__globals__, {"online_cores": lambda: every}), \ + mock.patch.dict(MODULE["fastest_first"].__globals__, {"core_speeds": lambda cores, speeds=speeds: speeds}), \ + mock.patch.object(os_mod, "sched_getaffinity", return_value=affinity, create=True): + MODULE["cpu_topology"](env, command) + self.assertEqual(env.get("WINE_CPU_TOPOLOGY"), expected, env) + self.assertEqual(env.get("PROTON_CPU_TOPOLOGY"), proton_topology, env) + self.assertIsNone(MODULE["proton_cpu_limit"](["/missing/proton"], {"SteamGameId": "11440"})) + self.assertIsNone(MODULE["proton_cpu_limit"](command, {})) + self.assertEqual(MODULE["proton_cpu_limit"](command, {"SteamGameId": "1038250"}), "P") + self.assertEqual(MODULE["proton_cpu_limit"](command, {"SteamGameId": "618970"}), 4) + + def test_core_speeds_read_capacity_then_top_clock(self): + with tempfile.TemporaryDirectory() as tmp: + for core, capacity, clock in ((0, "379", "2265600"), (1, None, "3302400")): + folder = Path(tmp) / ("cpu%d" % core) / "cpufreq" + folder.mkdir(parents=True) + (folder / "cpuinfo_max_freq").write_text(clock + "\n") + if capacity: + (folder.parent / "cpu_capacity").write_text(capacity + "\n") + speeds = MODULE["core_speeds"] + self.assertEqual(speeds([0], tmp), {0: 379}) + self.assertEqual(speeds([0, 1], tmp), {0: 2265600, 1: 3302400}) + self.assertIsNone(speeds([0, 2], tmp)) + def test_reskate_runs_at_feature_level_12_1(self): with tempfile.TemporaryDirectory() as tmp: reskate = Path(tmp) / "ReSkate" @@ -790,6 +971,36 @@ class GameEnvironmentTest(unittest.TestCase): subprocess.run(["bash", "-n"], input=script, text=True, check=True) self.assertIn('bl_run ${BL_TASKSET:-} /usr/local/bin/droiddeck-game-env', script) + def test_both_proton_wrappers_answer_steams_driver_query_without_wine(self): + scripts = (COMPAT["launcher_sh"](), COMPAT["extra_wrapper_sh"]("proton")) + query = "/root/.local/share/Steam/steamrtarm64/../bin/d3ddriverquery64.exe" + probe = "/root/.local/share/Steam/steamapps/compatdata/0" + for script in scripts: + subprocess.run(["bash", "-n"], input=script, text=True, check=True) + self.assertLess(script.index('case "$verb:${1##*/}:'), script.index("bl_components ")) + for args, prefix in (([query, "-d3d12"], probe), ([query], probe + "/"), + ([query.replace("64.exe", ".exe")], probe)): + result = subprocess.run(["bash", "-s", "run"] + args, input=script, text=True, capture_output=True, + env={"PATH": os.defpath, "HOME": "/nonexistent", "STEAM_COMPAT_DATA_PATH": prefix}, + timeout=10) + self.assertEqual(result.returncode, 1, result.stderr) + self.assertEqual(result.stdout, "") + self.assertIn("D3D driver query is not run", result.stderr) + skip = COMPAT["BL_DRIVER_QUERY_SKIP"] + for verb, args, prefix in ( + ("getcompatpath", [query], probe), + ("run", [query], "/root/.local/share/Steam/steamapps/compatdata/2276548447"), + ("run", [query], None), + ("waitforexitandrun", ["/games/AIO/AIO-Graphics-Test-64bit.exe", "--cube", "dx11"], probe), + ("run", ["/games/Tool/tool.exe", query], probe), + ("run", ["/games/d3ddriverquery64.exe.bak"], probe)): + env = {"PATH": os.defpath} + if prefix is not None: + env["STEAM_COMPAT_DATA_PATH"] = prefix + out = subprocess.run(["bash", "-c", "verb=" + verb + "\n" + skip + "echo continued", "_"] + args, + env=env, capture_output=True, text=True, check=True).stdout + self.assertEqual(out, "continued\n", (verb, args, prefix)) + def test_wrappers_preload_the_session_library_before_the_input_shim(self): overlay = "/root/.local/share/Steam/ubuntu12_64/gameoverlayrenderer.so" with tempfile.TemporaryDirectory() as tmp: diff --git a/tools/tests/test_render_on_commit.py b/tools/tests/test_render_on_commit.py new file mode 100644 index 0000000000..d27c7646e1 --- /dev/null +++ b/tools/tests/test_render_on_commit.py @@ -0,0 +1,223 @@ +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +import unittest + +from test_output_refresh import SOURCE, extract_function + + +PREAMBLE = r''' +#include +#include +#include +#include + +struct wl_event_source { int armed; }; +static struct wl_event_source idle_source, timer_source; +static void (*idle_func)(void *); +static int idles_added, timers_armed, renders, window_requests, effects_changes, pose_changes; +static int64_t clock_ns; +static int g_display_storage; +static void *g_display = &g_display_storage; +static struct wl_event_source *g_render_idle, *g_fallback_timer; +static int g_fallback_armed, g_dirty, g_hud_fresh, framegen; +static void *g_hud_surface; +static int64_t g_dirty_since_ns, g_last_vsync_ns, g_tick_vsync_ns, g_hud_last_ns, g_rendered_tick_ns; +static int g_tick_held; +static int64_t g_hold_missed_ns; +#define HOLD_RETRY_NS 1000000000LL +static int64_t g_refresh_ns = 16666667; +volatile int g_render_on_commit = 1; +volatile int g_release_unpaced = 1; +static atomic_int g_stream_on; +static struct { unsigned ticks, ticks_late_2ms, commit_renders; int64_t tick_late_ns, tick_late_max_ns; } g_pace; +static struct { unsigned ticks; } g_perf; +static int64_t now_ns(void) { return clock_ns; } +static void *wl_display_get_event_loop(void *display) { return display; } +static struct wl_event_source *wl_event_loop_add_idle(void *loop, void (*func)(void *), void *data) { + idles_added++; idle_func = func; return &idle_source; +} +static struct wl_event_source *wl_event_loop_add_timer(void *loop, int (*func)(void *), void *data) { return &timer_source; } +static int wl_event_source_timer_update(struct wl_event_source *source, int ms) { timers_armed++; return 0; } +static int vkp_framegen_active(void) { return framegen; } +static int vkp_apply_window_request(void) { return window_requests; } +static int vkp_effects_sync(void) { return effects_changes; } +static int vkp_cardboard_pose_changed(void) { return pose_changes; } +static void render_scene(void) { renders++; g_dirty = 0; g_dirty_since_ns = 0; g_rendered_tick_ns = g_tick_vsync_ns; g_tick_held = 0; } +static int on_fallback_timer(void *data) { return 0; } +static void on_commit_idle(void *data); +''' + +CHECKS = r''' +static void run_idle(void) { + void (*func)(void *) = idle_func; + idle_func = NULL; + if (func) func(NULL); +} + +static void tick(int64_t t) { clock_ns = t; on_vsync(t); } + +static void arrive(int64_t after_ns) { clock_ns += after_ns; schedule_render(); } + +int main(void) { + const int64_t refresh = 6944444, ms = 1000000; + int64_t t = 1000000000LL; + int r0; + unsigned c0; + g_refresh_ns = refresh; + tick(t); + assert(renders == 0); + + /* a new frame is drawn when it arrives */ + arrive(2 * ms); + assert(idles_added == 1 && renders == 0); + run_idle(); + assert(renders == 1 && g_pace.commit_renders == 1 && g_render_idle == NULL); + + /* a second frame in the same refresh is left for the next arrival, which is drawn when it arrives */ + arrive(1 * ms); + assert(idles_added == 1); + tick(t += refresh); + assert(renders == 1 && g_tick_held == 1); + arrive(2 * ms); + assert(idles_added == 2); + run_idle(); + assert(renders == 2 && g_pace.commit_renders == 2 && g_tick_held == 0); + + /* a frame no other frame follows is drawn at the tick after next */ + arrive(1 * ms); + tick(t += refresh); + assert(renders == 2); + tick(t += refresh); + assert(renders == 3 && g_pace.commit_renders == 2); + + /* after that, the tick draws every frame for a second, then holds one again */ + arrive(1 * ms); + tick(t += refresh); + assert(renders == 4 && g_tick_held == 0); + t += HOLD_RETRY_NS; + tick(t); + arrive(1 * ms); + run_idle(); + arrive(1 * ms); + tick(t += refresh); + assert(renders == 5 && g_tick_held == 1); + arrive(2 * ms); + run_idle(); + assert(renders == 6 && g_pace.commit_renders == 4); + + /* one frame per refresh, starting right after a tick draw, settles on drawing every frame when it arrives */ + window_requests = 1; + tick(t += refresh); + window_requests = 0; + arrive(2 * ms); + r0 = renders; c0 = g_pace.commit_renders; + for (int i = 0; i < 10; i++) { + tick(t += refresh); + arrive(2 * ms); + run_idle(); + } + assert(renders - r0 == 10 && g_pace.commit_renders - c0 == 10); + + /* a client that draws again only after its frame callback (sent when the scene is drawn) keeps one frame + per refresh: two held frames in 200 refreshes, about 1.4 s */ + r0 = renders; c0 = g_pace.commit_renders; + { + int seen = renders - 1; + for (int i = 0; i < 200; i++) { + if (renders != seen) { seen = renders; arrive(1 * ms); run_idle(); } + tick(t += refresh); + } + } + assert(renders - r0 == 198 && g_pace.commit_renders == c0); + + /* a window, effect or headset change at the tick draws the waiting frame now */ + t += HOLD_RETRY_NS; + tick(t); + arrive(1 * ms); + run_idle(); + r0 = renders; + arrive(1 * ms); + window_requests = 1; + tick(t += refresh); + window_requests = 0; + assert(renders - r0 == 1 && g_tick_held == 0); + + /* a draw queued before the tick still draws the frame once */ + tick(t += refresh); + r0 = renders; c0 = g_pace.commit_renders; + arrive(1 * ms); + tick(t += refresh); + assert(renders == r0); + run_idle(); + assert(renders - r0 == 1 && g_pace.commit_renders - c0 == 1); + tick(t += refresh); + assert(renders - r0 == 1); + + /* streaming switched on after the draw was queued leaves the frame for the tick */ + tick(t += refresh); + r0 = renders; c0 = g_pace.commit_renders; + arrive(1 * ms); + atomic_store(&g_stream_on, 1); + run_idle(); + assert(renders == r0); + tick(t += refresh); + atomic_store(&g_stream_on, 0); + assert(renders - r0 == 1 && g_pace.commit_renders == c0); + + /* paced output, frame generation, the switch off and streaming keep drawing on the tick */ + const int idles = idles_added; + r0 = renders; + for (int c = 0; c < 4; c++) { + tick(t += refresh); + if (c == 0) g_release_unpaced = 0; + if (c == 1) framegen = 1; + if (c == 2) g_render_on_commit = 0; + if (c == 3) atomic_store(&g_stream_on, 1); + arrive(1 * ms); + assert(idles_added == idles); + tick(t += refresh); + g_release_unpaced = 1; framegen = 0; g_render_on_commit = 1; atomic_store(&g_stream_on, 0); + assert(renders - r0 == c + 1); + } + + /* without screen ticks the fallback timer still draws */ + clock_ns += 200000000LL; + schedule_render(); + assert(idles_added == idles && g_fallback_armed == 1 && timers_armed == 1); + puts("PASS"); + return 0; +} +''' + + +@unittest.skipUnless(sys.platform.startswith('linux'), 'needs a Linux host compiler') +class RenderOnCommitTest(unittest.TestCase): + def test_a_new_frame_is_drawn_on_arrival_at_most_once_per_refresh(self): + compiler = shutil.which(os.environ.get('CC', 'cc')) + if compiler is None: + self.skipTest('A host C compiler is required') + source = SOURCE.read_text() + render = extract_function(source, 'render_scene') + self.assertIn('g_rendered_tick_ns = g_tick_vsync_ns;', render) + self.assertIn('g_tick_held = 0;', render) + functions = ('commit_renders_on', 'render_on_commit', 'schedule_render', 'scene_waits_for_game', 'on_commit_idle', 'on_vsync') + harness = PREAMBLE + '\n'.join(extract_function(source, name) for name in functions) + CHECKS + with tempfile.TemporaryDirectory(prefix='droiddeck-render-on-commit-') as folder: + path = Path(folder) + (path / 'commit.c').write_text(harness) + binary = path / 'commit-test' + build = subprocess.run([compiler, '-std=c11', '-Wall', '-Wextra', '-Werror', + '-Wno-unused-parameter', '-Wno-unused-function', '-O2', + str(path / 'commit.c'), '-o', str(binary)], capture_output=True, text=True) + self.assertEqual(0, build.returncode, build.stderr) + result = subprocess.run([str(binary)], capture_output=True, text=True, timeout=10) + self.assertEqual(0, result.returncode, result.stderr) + self.assertEqual('PASS', result.stdout.strip()) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/tests/test_steam_x64_cpu.py b/tools/tests/test_steam_x64_cpu.py new file mode 100644 index 0000000000..ad8e2dc271 --- /dev/null +++ b/tools/tests/test_steam_x64_cpu.py @@ -0,0 +1,79 @@ +import os +from pathlib import Path +import subprocess +import tempfile +import unittest + +SCRIPT = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-steam-x64' + + +class SteamX64CpuTest(unittest.TestCase): + def selection(self, features, *, forced=False, same_build=True, unreadable=False): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + arm = root / 'arm' + x64 = root / 'x64' + for base in (arm, x64): + (base / 'package').mkdir(parents=True) + (arm / 'steamrtarm64').mkdir() + (arm / 'steamrtarm64/steamwebhelper').touch(mode=0o700) + shim = root / 'arm-shim' + shim.touch(mode=0o700) + (x64 / 'package/beta').write_text('publicbeta\n') + for base, arch, version in ((x64, 'steamrt64', '123'), (arm, 'linuxarm64', '123' if same_build else '122')): + (base / f'package/steam_client_publicbeta_{arch}.manifest').write_text(f'"version" "{version}"\n') + cpuinfo = root / 'cpuinfo' + if not unreadable: + cpuinfo.write_text(features) + text = SCRIPT.read_text() + start = text.find('x64_arm_webhelper_cpu_supported() {') + helper = text[start:text.index('x64_exec() {')] if start >= 0 else '' + selection = text.split('x64_exec() {', 1)[1].split(' mkdir -p "$STEAM_X64/logs"', 1)[0] + shell = helper + '\nx64_env() { :; }\nx64_webhelper_gpu() { return 1; }\nselect_helper() {' + selection + '\nprintf "%s|%s\\n" "${BL_X64_ARM_WEBHELPER:-x86}" "${BL_WEBHELPER_ARGS:-}";\n}\nselect_helper\n' + shell = shell.replace('/proc/cpuinfo', str(cpuinfo)).replace('/usr/local/bin/droiddeck-x64-arm-webhelper', str(shim)) + env = dict(os.environ, STEAM_X64=str(x64), ARM_STEAM=str(arm), X64_CHANNEL='publicbeta', BL_X64_X86_WEBHELPER='1' if forced else '0') + env.pop('BL_X64_ARM_WEBHELPER', None) + env.pop('BL_WEBHELPER_ARGS', None) + result = subprocess.run(['bash', '-eu', '-c', shell], env=env, capture_output=True, text=True) + self.assertEqual(result.returncode, 0, result.stderr) + return result.stdout.strip(), str(shim) + + def test_missing_atomics_keeps_x86_helper(self): + result, _ = self.selection('Features : fp asimd aes crc32\n') + self.assertEqual(result, 'x86|stock') + + def test_atomics_keeps_same_build_arm_helper(self): + result, arm = self.selection('Features : fp asimd atomics aes\n') + self.assertEqual(result, arm + '|') + + def test_exact_token_required(self): + result, _ = self.selection('Features : fp noatomics atomics_extra\n') + self.assertEqual(result, 'x86|stock') + + def test_any_explicit_core_without_atomics_keeps_x86_helper(self): + result, _ = self.selection('processor : 0\nFeatures : fp atomics\nprocessor : 1\nFeatures : fp aes\n') + self.assertEqual(result, 'x86|stock') + + def test_empty_features_is_explicitly_unsupported(self): + result, _ = self.selection('Features : \n') + self.assertEqual(result, 'x86|stock') + + def test_absent_features_preserves_existing_behavior(self): + result, arm = self.selection('processor : 0\n') + self.assertEqual(result, arm + '|') + + def test_unreadable_cpuinfo_preserves_existing_behavior(self): + result, arm = self.selection('', unreadable=True) + self.assertEqual(result, arm + '|') + + def test_forced_x86_still_wins(self): + result, _ = self.selection('Features : atomics\n', forced=True) + self.assertEqual(result, 'x86|stock') + + def test_supported_cpu_still_requires_same_build(self): + result, _ = self.selection('Features : atomics\n', same_build=False) + self.assertEqual(result, 'x86|stock') + + +if __name__ == '__main__': + unittest.main()