mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-18 12:28:40 +00:00
chore: remove source comments and unused code, translate every missing string (#1965)
* chore(i18n): translate every missing string in all locales Adds the 87 strings the bottom-screen Dashboard and in-game stats pages introduced to all 32 locales, plus the 51 older settings strings Japanese and the 50 Chinese locales were still missing. Every locale now has all 3456 translatable strings with the same placeholders as English. Also translates 36 entries that were still English where the language does not use the English word, and makes es-419 touch_app_id use the same %1$s placeholder as English. * chore(patches): drop comments from the lines downstream patches add Removes comment lines and trailing comments from lines our patches add, with hunk headers recounted. Lines that a later patch uses as context and the upstream backport 0123 are left as they are. The gamescope, FEX, proot and xodus series still apply to their pinned sources, and the patched trees differ only in those comments. test_hud_frames now finds the HUD writer by its first declaration. * docs: credit Greenlight, Better xCloud, viture-v2, GameNative and DiRTTelemetryErrorFix These were credited only in source headers and NOTICE files. * chore: remove source comments and unused functions Removes explanatory comments from first-party Kotlin, Java, C, C++, Rust, TypeScript, Python, shell, Gradle, CMake and workflow files. License and attribution headers stay, and vendored third-party trees, generated files and license files are untouched. A shellcheck directive is kept, and udevmon's fallthrough comments became fallthrough attributes. Syntax trees and token streams match the previous sources apart from the comments and Python docstrings. Module docstrings that argparse prints are kept, and device-smoke.sh prints the same --help text from a heredoc. Also removes 37 functions and 4 fields that nothing referenced. * chore: remove comments from the Syncthing integration and the latest main sources * docs: credit Syncthing and the syncthing-android fork * chore(i18n): translate the Syncthing strings in all locales The 107 strings the Syncthing integration added are now in all 32 locales. sync_web_path_locked names the Syncthing tab by its label. * docs: credit @xXJSONDeruloXx for the HUD metric readers The CPU, GPU load, thermal and battery readers come from their PerformanceHudView pull requests #777, #877, #991, #1406 and #1573. The FusionHUD credit line is unchanged. * docs: credit the HUD metric readers to @xXJSONDeruloXx's work
This commit is contained in:
1 parent
d730f0fa8b
commit
c5577478ca
511 files changed
+6813
-4068
No files matched your search
@@ -19,7 +19,6 @@ class App : Application() {
|
||||
com.droiddeck.launcher.ui.Themes.loadGradient(this)
|
||||
com.droiddeck.launcher.ui.BuildWatermark.install(this)
|
||||
HomeApp.trackRecents(this)
|
||||
// Helper processes must not initialize the main USB provider or guest graphics context.
|
||||
val process = if (android.os.Build.VERSION.SDK_INT >= 28) Application.getProcessName()
|
||||
else (getSystemService(ACTIVITY_SERVICE) as android.app.ActivityManager)
|
||||
.runningAppProcesses?.firstOrNull { it.pid == android.os.Process.myPid() }?.processName
|
||||
@@ -32,7 +31,6 @@ class App : Application() {
|
||||
return
|
||||
}
|
||||
if (process == "$packageName:xcloudnative") {
|
||||
// The native cloud player: the stores log and nothing that touches the Linux session.
|
||||
com.droiddeck.launcher.stores.StoresState.init(this)
|
||||
return
|
||||
}
|
||||
@@ -62,7 +60,6 @@ class App : Application() {
|
||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.battlenet.BattleNetBackend)
|
||||
}
|
||||
|
||||
/** Fetches the packs an existing setup already relies on, so the first use after an update does not wait. */
|
||||
private fun prefetchAddonPacks() {
|
||||
val app = this
|
||||
Thread({
|
||||
|
||||
@@ -717,7 +717,6 @@ class FrontEndActivity : ComponentActivity() {
|
||||
LauncherIcon.set(this, style)
|
||||
launcherIcon = LauncherIcon.current(this)
|
||||
if (launcherIcon == before) return false
|
||||
// Android finishes activities started through the alias that was just disabled.
|
||||
startActivity(Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER)
|
||||
.setComponent(LauncherIcon.activity(this))
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_MULTIPLE_TASK)
|
||||
@@ -1797,7 +1796,6 @@ class FrontEndActivity : ComponentActivity() {
|
||||
|
||||
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".
|
||||
val ownDisplayId = if (android.os.Build.VERSION.SDK_INT >= 30) display?.displayId ?: android.view.Display.DEFAULT_DISPLAY else @Suppress("DEPRECATION") windowManager.defaultDisplay.displayId
|
||||
dualScreenMode = SessionPrefs.dualScreenMode(this)
|
||||
secondScreenDisplays = SecondScreenDisplays.available(displayManager, ownDisplayId)
|
||||
@@ -2491,7 +2489,6 @@ class FrontEndActivity : ComponentActivity() {
|
||||
!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"
|
||||
if (listX64 != steamGamesX64) {
|
||||
steamGamesX64 = listX64
|
||||
|
||||
@@ -12,7 +12,6 @@ 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 ""
|
||||
|
||||
@@ -197,7 +197,6 @@ object HomeWidgets {
|
||||
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
|
||||
|
||||
@@ -20,7 +20,6 @@ internal class ProtonMenu(
|
||||
private val ui: Handler,
|
||||
private val idle: () -> Boolean = { true },
|
||||
) {
|
||||
// Install workers and their results outlive the activity that starts them.
|
||||
private object Operation {
|
||||
val rows = mutableStateOf<List<ProtonRow>>(emptyList())
|
||||
val busyId = mutableStateOf<String?>(null)
|
||||
|
||||
@@ -71,7 +71,6 @@ class QuestXrActivity : NativeActivity() {
|
||||
}
|
||||
} finally {
|
||||
synchronized(steamVrLock) {
|
||||
// A retiring activity must not stop a replacement's SteamVR session.
|
||||
if (steamVrOwner === this) {
|
||||
if (sessionAlive()) SteamVr.run(this, "stop")
|
||||
steamVrOwner = null
|
||||
|
||||
@@ -265,7 +265,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
if (locked) openEvdevMouse() else closeEvdevMouse()
|
||||
padMouseCheckedAt = 0L
|
||||
if (::padMouse.isInitialized) padMouseMode()
|
||||
// Touchpad deltas are measured from the middle while locked (moveLockedPointer).
|
||||
if (locked && ::touchpad.isInitialized) {
|
||||
drawnRect()?.let { touchpad.place(it.centerX(), it.centerY()) }
|
||||
cursorVisible = false
|
||||
@@ -513,8 +512,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
}
|
||||
|
||||
// A higher refresh rate allowed in Android's settings does not change the display while this window
|
||||
// still asks for a lower mode, so the mode is chosen again when the setting changes.
|
||||
private val refreshSettingObserver = object : ContentObserver(Handler(Looper.getMainLooper())) {
|
||||
override fun onChange(selfChange: Boolean) {
|
||||
applyOutputPacing()
|
||||
@@ -571,7 +568,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
finish()
|
||||
return
|
||||
}
|
||||
// A cancelled install keeps its thread until the download stops; a new launch would reuse its stop flag and close itself.
|
||||
if (savedInstanceState == null && SessionState.installing != null && !SessionState.running) {
|
||||
runtimeRemovalBlocked = true
|
||||
android.widget.Toast.makeText(this, R.string.main_wait_desktop_install, android.widget.Toast.LENGTH_SHORT).show()
|
||||
@@ -582,7 +578,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
val mode = intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM
|
||||
SessionState.programArgs = intent.getStringArrayExtra(SessionService.EXTRA_PROGRAM_ARGS)?.toList().orEmpty()
|
||||
SessionEvents.begin(this, mode, SessionPaths.label(mode, intent.getStringExtra(SessionService.EXTRA_PROGRAM)))
|
||||
// begin() moves the phase on, so the block below never runs for a new session; reset per-session flags here.
|
||||
SessionState.secondScreenAutoOpened = false
|
||||
SessionState.secondScreenProvisional = false
|
||||
}
|
||||
@@ -718,8 +713,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
ViewConfiguration.get(this).scaledTouchSlop.toFloat(), gestureOutput,
|
||||
)
|
||||
refreshGestureConfig()
|
||||
// A real touch target lets FrameLayout split fingers between the
|
||||
// game surface and on-screen buttons, in either finger-down order.
|
||||
root.isMotionEventSplittingEnabled = true
|
||||
surfaceView.setOnTouchListener { _, event ->
|
||||
if (!event.isFromSource(InputDevice.SOURCE_TOUCHSCREEN)) {
|
||||
@@ -925,7 +918,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
window.setBackgroundDrawable(android.graphics.drawable.ColorDrawable(android.graphics.Color.BLACK))
|
||||
},
|
||||
)
|
||||
// Also runs when a second screen appears, so Automatic applies then with the running game known.
|
||||
LaunchedEffect(AgentGuest.focusRevision, secondScreenDisplays.isNotEmpty()) {
|
||||
val nextGame = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
|
||||
if (SessionState.mode == SessionService.MODE_RUN) SessionState.program?.let { "program:$it" }
|
||||
@@ -1119,7 +1111,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
SessionAchievements(inFront.game, inFront.title, onClose = ::closeAchievements)
|
||||
}
|
||||
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
|
||||
@@ -1480,7 +1471,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
))
|
||||
}
|
||||
|
||||
/** The SteamVR driver switches pad sticks between hands and game on both stick clicks together. */
|
||||
private fun switchVrSticks() {
|
||||
val chord = { down: Boolean -> padBridge?.applyTouch { state ->
|
||||
state.press(com.droiddeck.launcher.input.PadState.L3, down)
|
||||
@@ -2215,8 +2205,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
|
||||
override fun surfaceDestroyed(holder: SurfaceHolder) {
|
||||
// Hiding the phone surface after a handoff delivers a late destruction
|
||||
// callback. It must not reset the new output's size or attachment.
|
||||
if (holder !== outputHolder()) return
|
||||
cancelTouchGestures()
|
||||
surfaceW = 0
|
||||
@@ -2637,10 +2625,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
if (PadBridge.isControllerMotionEvent(event) && padMouseMode() && padMouse.onMotion(event)) return true
|
||||
if (padBridge?.onMotionEvent(event) == true) return true
|
||||
if (event.isFromSource(android.view.InputDevice.SOURCE_MOUSE) && !drawerOpen) {
|
||||
/* The app's own controls get the pointer first. With the picture on the glasses the
|
||||
* phone shows its panel, and hovering or clicking a control there must reach it
|
||||
* instead of moving and clicking the guest pointer on the glasses. Whatever the UI
|
||||
* leaves alone — the rest of the screen — still drives the guest pointer. */
|
||||
if (appUiOwnsPointer()) {
|
||||
if (super.dispatchGenericMotionEvent(event)) return true
|
||||
if (onMouse(event)) return true
|
||||
@@ -2654,7 +2638,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
override fun dispatchTrackballEvent(event: MotionEvent): Boolean =
|
||||
onCapturedPointer(event) || super.dispatchTrackballEvent(event)
|
||||
|
||||
/** Whether one of the on-screen control layers takes a finger going down at this screen point. */
|
||||
private fun controlTakesTouchAt(rawX: Float, rawY: Float): Boolean {
|
||||
val at = IntArray(2)
|
||||
fun takes(view: View, hit: (Float, Float) -> Boolean): Boolean {
|
||||
@@ -2832,9 +2815,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
override fun prepareRelativePan() {
|
||||
if (pointerLocked) return
|
||||
val rect = drawnRect() ?: return
|
||||
// Gamescope retains the last absolute position while a game can warp
|
||||
// its own cursor to the center. Its first unlocked motion must start
|
||||
// from that same origin, before the game switches to pointer lock.
|
||||
moveTo(rect.centerX(), rect.centerY())
|
||||
}
|
||||
override fun key(code: Int, down: Boolean) {
|
||||
@@ -3156,7 +3136,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}),
|
||||
)
|
||||
|
||||
/** Pages for the bottom-screen dashboard; the dashboard is offered only while at least one exists. */
|
||||
private fun bottomPages(): List<BottomPage> = sessionBottomPages(BottomPageActions(
|
||||
takeScreenshot = ::captureScreenshot,
|
||||
fps = { if (::hud.isInitialized) hud.liveFps else null },
|
||||
@@ -3164,9 +3143,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
runningGame = { gestureGame },
|
||||
))
|
||||
|
||||
// A settings page opened on the bottom screen sits under the dashboard window, so the dashboard hides
|
||||
// until the setting is on, or for at most SETTINGS_WATCH_CHECKS seconds when it is left off (another
|
||||
// app's page closing cannot be seen); choosing Dashboard in the menu again shows it sooner.
|
||||
private fun openSettingsBelow(intent: android.content.Intent, done: () -> Boolean) {
|
||||
val presentation = secondScreenPresentation ?: return
|
||||
val options = android.app.ActivityOptions.makeBasic().setLaunchDisplayId(presentation.display.displayId)
|
||||
@@ -3178,7 +3154,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
if (!opened) return
|
||||
presentation.hide()
|
||||
var checks = 0
|
||||
// Show throws if the display went away while the settings page was open, as in showSecondScreen.
|
||||
fun showAgain() {
|
||||
try {
|
||||
presentation.show()
|
||||
@@ -3199,9 +3174,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}, SETTINGS_WATCH_MS)
|
||||
}
|
||||
|
||||
/** Copies the game frame (no overlay) at the size it is shown and saves it to Pictures/DroidDeck. */
|
||||
private fun captureScreenshot(onDone: (Boolean) -> Unit) {
|
||||
// With the glasses as the output the game is drawn on their surface; the phone's surface is hidden then.
|
||||
val source = if (glassesOutputActive) glassesScreen?.surfaceView else if (::surfaceView.isInitialized) surfaceView else null
|
||||
val width = source?.width ?: 0
|
||||
val height = source?.height ?: 0
|
||||
@@ -3643,23 +3616,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
if (want) view.requestPointerCapture() else view.releasePointerCapture()
|
||||
}
|
||||
|
||||
/** Null until the first application, so the initial state is applied rather than skipped. */
|
||||
private var platformPointerShown: Boolean? = null
|
||||
|
||||
/**
|
||||
* The app's own UI is what the mouse is over, so it needs a pointer of its own: the drawer,
|
||||
* keyboard, achievements and PiP controls, and — once the glasses own the picture — the whole
|
||||
* phone, which then shows [GlassesPhonePanel] instead of the game.
|
||||
*/
|
||||
private fun appUiOwnsPointer(): Boolean =
|
||||
drawerOpen || pcKeyboardOpen || achievementsOpen || pipUi || glassesOutputActive
|
||||
|
||||
/**
|
||||
* Over the game neither this app nor Android draws a pointer: the compositor's cursor is the
|
||||
* only one (Compose's on the phone, inside the picture on the glasses). Over the app's own UI
|
||||
* the game gets no pointer events at all, so without this nothing visible follows the mouse
|
||||
* while buttons still highlight and click.
|
||||
*/
|
||||
private fun applyPlatformPointer(shown: Boolean) {
|
||||
if (!::sessionRoot.isInitialized || !::surfaceView.isInitialized) return
|
||||
if (shown == platformPointerShown) return
|
||||
@@ -3880,7 +3841,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
if (down || code !in gestureKeysDown) WaylandCompositor.nativeSendKey(code, if (down) 1 else 0)
|
||||
}
|
||||
|
||||
// The frozen game cannot draw again, so the paused overlay shows a copy taken while the surface still holds its frame.
|
||||
private fun capturePausedFrame(manual: Boolean = false) {
|
||||
if (!SessionState.running || pipUi || isInPictureInPictureMode || glassesOutputActive) return
|
||||
if (SessionState.suspended && pausedFrame != null) return
|
||||
@@ -3925,8 +3885,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
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() {
|
||||
if (pausedFrame != null) return
|
||||
pausedFrameWanted = true
|
||||
@@ -4163,8 +4121,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
Glasses.cancelSteamVrStart()
|
||||
}
|
||||
if (glasses.present) {
|
||||
// Optional stereo starts only after RUNNING is observed. READY can
|
||||
// arrive repeatedly while the launch worker is still starting VR.
|
||||
if (action == "install") steamVrStatus = SteamVr.Status.INSTALLING
|
||||
runSteamVrAction(action, ::currentRequest) {
|
||||
val ok = SteamVr.run(this, action)
|
||||
@@ -4357,8 +4313,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
if (holder !== outputHolder()) return
|
||||
glassesOutputActive = glassesScreen?.holder === holder
|
||||
if (CompositorHost.isStarted) WaylandCompositor.nativeSetCursorComposite(glassesOutputActive)
|
||||
// Keep the phone's layout for touch/controller coordinates, but remove
|
||||
// its SurfaceView so it cannot retain the last game frame under the hint.
|
||||
surfaceView.visibility = if (glassesOutputActive) View.INVISIBLE else View.VISIBLE
|
||||
Log.i(TAG, "compositor output attached: " +
|
||||
if (glassesOutputActive) "glasses display ${glassesScreen?.display?.displayId}" else "phone")
|
||||
@@ -4437,8 +4391,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
if (target != null) {
|
||||
val screen = GlassesScreen(this, target, Glasses.outputHz(), this, Glasses.outputResolution())
|
||||
// show() can create the surface synchronously. Select its holder
|
||||
// first, otherwise surfaceCreated() rejects the glasses callback.
|
||||
glassesScreen = screen
|
||||
applyOutputPacing()
|
||||
surfaceW = 0
|
||||
|
||||
@@ -118,7 +118,6 @@ public class DirectAudioRelayComponent extends SessionPart {
|
||||
}
|
||||
}
|
||||
|
||||
// Android keeps the input stream's wake lock while a frozen helper still has it started.
|
||||
public boolean awaitMicReleased(long timeoutMs) {
|
||||
long deadline = System.currentTimeMillis() + timeoutMs;
|
||||
synchronized (micLock) {
|
||||
|
||||
@@ -13,12 +13,6 @@ import kotlinx.coroutines.launch
|
||||
import java.io.File
|
||||
import java.io.FileInputStream
|
||||
|
||||
/**
|
||||
* A pack built by CI alongside this APK (tools/packs). Main and release builds publish it to
|
||||
* DroidDeck-Components under a content-addressed tag; a PR test build attaches packs that are not there
|
||||
* yet to its pr-N release on DroidDeck-CI. The APK pins the pack's SHA-256, so only the bytes this build
|
||||
* was made with install, whichever host serves them.
|
||||
*/
|
||||
internal class AddonPack(
|
||||
val name: String, private val sha256: String, val size: Long, private val required: List<String>,
|
||||
private val reuseDeviceCopy: Boolean = sha256.isEmpty() && !BuildConfig.CI_BUILD,
|
||||
@@ -43,13 +37,11 @@ internal class AddonPack(
|
||||
)
|
||||
|
||||
private fun root(context: Context) = File(context.filesDir, "addons/$name")
|
||||
/** App-private and written only after the archive matched the pinned digest. */
|
||||
fun dir(context: Context) = File(root(context), version(context))
|
||||
fun file(context: Context, relative: String) = File(dir(context), relative)
|
||||
|
||||
fun installed(context: Context): Boolean = version(context).isNotEmpty() && File(dir(context), COMPLETE).isFile
|
||||
|
||||
// A build made outside CI pins no packs, so it runs the newest one a CI build already verified and installed.
|
||||
private fun version(context: Context): String = if (!reuseDeviceCopy) sha256 else deviceCopy(context).orEmpty()
|
||||
|
||||
private fun deviceCopy(context: Context): String? = root(context).listFiles().orEmpty()
|
||||
@@ -66,7 +58,6 @@ internal class AddonPack(
|
||||
.also { mutableState.value = it }
|
||||
}
|
||||
|
||||
/** Starts the download in the background unless the pack is already present or on its way. */
|
||||
fun ensure(context: Context, onReady: (Context) -> Unit = {}) {
|
||||
val app = context.applicationContext
|
||||
synchronized(lock) {
|
||||
@@ -81,7 +72,6 @@ internal class AddonPack(
|
||||
}
|
||||
}
|
||||
|
||||
/** Blocks a worker thread until the pack is installed, starting the download if needed. */
|
||||
@JvmOverloads
|
||||
fun await(context: Context, running: () -> Boolean = { true }, onState: (State) -> Unit = {}): Boolean {
|
||||
if (installed(context)) return true
|
||||
@@ -127,7 +117,6 @@ internal class AddonPack(
|
||||
return true
|
||||
}
|
||||
|
||||
// A local build pins the packs it compiled, which no release hosts, so it ships them as assets.
|
||||
internal fun bundled(context: Context, archive: File): Boolean {
|
||||
val copied = runCatching {
|
||||
bundle(context).use { input -> archive.outputStream().use { input.copyTo(it) } }
|
||||
|
||||
@@ -42,7 +42,6 @@ object DeviceReport {
|
||||
}
|
||||
}
|
||||
|
||||
/** Name of an ApplicationExitInfo reason code, so a report says "LOW_MEMORY" instead of "3". */
|
||||
internal fun exitReasonName(reason: Int): String = when (reason) {
|
||||
0 -> "UNKNOWN"
|
||||
1 -> "EXIT_SELF"
|
||||
|
||||
@@ -126,11 +126,9 @@ object DownloadSource {
|
||||
|
||||
fun isGithub(url: String): Boolean = GITHUB_HOSTS.any { url.startsWith("https://$it/") }
|
||||
|
||||
/** Catalogs carry the digests everything else is checked against, so a mirror must never supply one. */
|
||||
fun isCatalog(url: String): Boolean = CATALOGS.any { url.startsWith(it) }
|
||||
|
||||
fun candidates(target: String): List<String> {
|
||||
// GitHub API metadata carries executable URLs and digests; never proxy it.
|
||||
if (isCatalog(target) || target.startsWith("https://api.github.com/")) return listOf(target)
|
||||
val prefs = prefs() ?: return listOf(target)
|
||||
if (!isGithub(target)) return listOf(target)
|
||||
@@ -184,7 +182,6 @@ object DownloadSource {
|
||||
prefs(context)?.edit()?.putString(KEY_PROXY, normalizeProxy(value))?.apply()
|
||||
}
|
||||
|
||||
/** An HTTP proxy every Downloader connection uses, or null when none is configured. */
|
||||
fun httpProxy(): Proxy? = proxyOf(prefs()?.getString(KEY_PROXY, "") ?: "")
|
||||
|
||||
internal fun proxyOf(value: String): Proxy? {
|
||||
|
||||
@@ -91,7 +91,6 @@ public final class Downloader {
|
||||
if (isCancelled(cancelled)) return null;
|
||||
if (i > 0) Log.i(TAG, "retrying " + url + " via " + sources.get(i));
|
||||
Fetch fetch = fetch(sources.get(i), cancelled);
|
||||
// A cancelled fetch says nothing about the source, so it must not count as a failure.
|
||||
if (isCancelled(cancelled)) return null;
|
||||
if (fetch.body != null) {
|
||||
DownloadSource.INSTANCE.succeeded(sources.get(i));
|
||||
@@ -103,7 +102,6 @@ public final class Downloader {
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Fetches without the mirror list, for a URL whose body is a digest the payload is checked against. */
|
||||
public static String downloadDirect(String url) {
|
||||
return fetch(url).body;
|
||||
}
|
||||
@@ -113,13 +111,11 @@ public final class Downloader {
|
||||
return downloadFile(url, destination, resume, null, progress);
|
||||
}
|
||||
|
||||
/** Verify each candidate before accepting it, so a bad mirror can fall back. */
|
||||
public static boolean downloadFile(String url, File destination, boolean resume, String expectedSha256,
|
||||
java.util.function.Consumer<Float> progress) {
|
||||
return downloadFile(url, destination, resume, expectedSha256, null, progress);
|
||||
}
|
||||
|
||||
/** {@code cancelled} is polled while bytes arrive; a cancel stops at once and leaves the partial file for the caller. */
|
||||
public static boolean downloadFile(String url, File destination, boolean resume, String expectedSha256,
|
||||
java.util.function.BooleanSupplier cancelled,
|
||||
java.util.function.Consumer<Float> progress) {
|
||||
@@ -128,13 +124,11 @@ public final class Downloader {
|
||||
return downloadCandidates(url, sources(url, expectedSha256), destination, resume, expectedSha256, cancelled, progress);
|
||||
}
|
||||
|
||||
/** A third-party mirror may only serve bytes that can be checked against a digest from a direct source. */
|
||||
static List<String> sources(String url, String expectedSha256) {
|
||||
return expectedSha256 == null ? java.util.Collections.singletonList(url) : DownloadSource.INSTANCE.candidates(url);
|
||||
|
||||
}
|
||||
|
||||
// Package-private for the local multi-source HTTP test.
|
||||
static boolean downloadCandidates(String original, List<String> sources, File destination, boolean resume,
|
||||
String expectedSha256, java.util.function.Consumer<Float> progress) {
|
||||
return downloadCandidates(original, sources, destination, resume, expectedSha256, null, progress);
|
||||
@@ -149,7 +143,6 @@ public final class Downloader {
|
||||
if (isCancelled(cancelled)) return false;
|
||||
if (i > 0) Log.i(TAG, "retrying " + original + " via " + source);
|
||||
Outcome outcome = attempt(source, destination, resume, identity, expectedSha256, cancelled, progress);
|
||||
// A cancel is not a source failure: no other mirror, and no DownloadSource.failed().
|
||||
if (outcome == Outcome.CANCELLED) return false;
|
||||
if (outcome == Outcome.DONE) {
|
||||
if (expectedSha256 != null) {
|
||||
@@ -192,7 +185,6 @@ public final class Downloader {
|
||||
return value != null && !value.isEmpty() && !value.startsWith("W/");
|
||||
}
|
||||
|
||||
/** Only reuse saved bytes when we persisted a strong validator and their source. */
|
||||
private static Identity loadIdentity(File dest, boolean resume, String expectedSha256) {
|
||||
Identity identity = new Identity();
|
||||
File marker = resumeFile(dest);
|
||||
@@ -213,7 +205,6 @@ public final class Downloader {
|
||||
return identity;
|
||||
}
|
||||
} catch (IOException e) {
|
||||
// Legacy partials or interrupted metadata writes have no trustworthy identity.
|
||||
}
|
||||
if (!discardPartial(dest, identity)) Log.w(TAG, "could not discard unidentified partial " + dest);
|
||||
return identity;
|
||||
@@ -239,7 +230,7 @@ public final class Downloader {
|
||||
try (FileOutputStream out = new FileOutputStream(marker)) {
|
||||
p.store(out, "DroidDeck partial download validator");
|
||||
} catch (IOException e) {
|
||||
marker.delete(); // No valid metadata means no future resume.
|
||||
marker.delete();
|
||||
Log.w(TAG, "cannot persist download validator", e);
|
||||
}
|
||||
}
|
||||
@@ -252,7 +243,6 @@ public final class Downloader {
|
||||
long have = resume && destination.isFile() ? destination.length() : 0;
|
||||
try {
|
||||
if (have > 0 && (!url.equals(identity.source) || !strongETag(identity.etag))) {
|
||||
// A new source or unvalidated bytes must restart from byte zero.
|
||||
if (!discardPartial(destination, identity)) return Outcome.RETRY;
|
||||
have = 0;
|
||||
}
|
||||
@@ -286,7 +276,6 @@ public final class Downloader {
|
||||
return attempt(url, destination, false, identity, expectedSha256, cancelled, progress);
|
||||
}
|
||||
if (!appending && have > 0) {
|
||||
// If-Range may legitimately return full 200 when representation changed.
|
||||
if (!discardPartial(destination, identity)) return Outcome.RETRY;
|
||||
have = 0;
|
||||
}
|
||||
@@ -333,14 +322,12 @@ public final class Downloader {
|
||||
}
|
||||
}
|
||||
|
||||
/** True when a `Content-Range: bytes START-END/TOTAL` header starts exactly at {@code start}. */
|
||||
static boolean rangeStartsAt(String contentRange, long start) {
|
||||
if (contentRange == null) return false;
|
||||
java.util.regex.Matcher m = java.util.regex.Pattern.compile("^\\s*bytes\\s+(\\d+)-\\d+/(?:\\d+|\\*)\\s*$").matcher(contentRange);
|
||||
return m.matches() && Long.parseLong(m.group(1)) == start;
|
||||
}
|
||||
|
||||
/** The complete length in a `Content-Range` header, or -1 when the header leaves it unknown. */
|
||||
static long rangeTotal(String contentRange) {
|
||||
if (contentRange == null) return -1;
|
||||
java.util.regex.Matcher m = java.util.regex.Pattern.compile("^\\s*bytes\\s+\\d+-\\d+/(\\d+)\\s*$").matcher(contentRange);
|
||||
@@ -390,7 +377,6 @@ public final class Downloader {
|
||||
}
|
||||
|
||||
private static HttpURLConnection open(String url, int readTimeoutMs) throws java.io.IOException {
|
||||
// An explicit Proxy routes the connection through the app setting instead of the system-wide proxy.
|
||||
Proxy proxy = DownloadSource.INSTANCE.httpProxy();
|
||||
HttpURLConnection connection = (HttpURLConnection) (proxy != null
|
||||
? new URL(url).openConnection(proxy) : new URL(url).openConnection());
|
||||
|
||||
@@ -5,7 +5,6 @@ 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 ->
|
||||
@@ -19,6 +18,5 @@ object GlobalSettings {
|
||||
|
||||
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")
|
||||
}
|
||||
@@ -11,7 +11,6 @@ object LogRedactor {
|
||||
size > 32
|
||||
}
|
||||
|
||||
// Android matchers own native state, so reuse them instead of creating one for every log line.
|
||||
private val matchers = object : ThreadLocal<MatcherCache>() {
|
||||
override fun initialValue(): MatcherCache = MatcherCache()
|
||||
}
|
||||
@@ -145,7 +144,6 @@ object LogRedactor {
|
||||
val needs = name.lowercase().takeIf { name.all { it.code < 0x80 } }
|
||||
Learned(Regex("(?i)(?<![A-Za-z0-9_])" + Regex.escape(name) + "(?![A-Za-z0-9_])"), needs)
|
||||
}
|
||||
// A file that could not be read keeps the names learned from it before.
|
||||
accounts = if (unread) (accounts + learned).distinctBy { it.regex.pattern } else learned
|
||||
}
|
||||
|
||||
@@ -228,7 +226,6 @@ object LogRedactor {
|
||||
return out
|
||||
}
|
||||
|
||||
/** The at-rest rewrite reads a file into memory twice; larger logs are only scrubbed on the way out. */
|
||||
const val IN_MEMORY_SCRUB_MAX = 64L * 1024 * 1024
|
||||
|
||||
fun isBinary(file: java.io.File): Boolean = try {
|
||||
@@ -241,8 +238,6 @@ object LogRedactor {
|
||||
true
|
||||
}
|
||||
|
||||
fun isText(file: java.io.File): Boolean = file.isFile && file.length() < IN_MEMORY_SCRUB_MAX && !isBinary(file)
|
||||
|
||||
const val RULES_VERSION = 3
|
||||
|
||||
private val LAN_IPV4 = Regex(
|
||||
|
||||
@@ -52,8 +52,6 @@ object SessionLogCapture {
|
||||
if (t.parentFile?.absolutePath == dir.absolutePath) stop()
|
||||
}
|
||||
|
||||
/** flush() only reaches the page cache, and a hard reset on f2fs lost the last minutes of every
|
||||
* log. Every 2 s the session folder's files (ours and the native parts') are synced to storage. */
|
||||
private fun startSyncing(dir: File): Thread = Thread({
|
||||
while (true) {
|
||||
try { Thread.sleep(2000) } catch (e: InterruptedException) { break }
|
||||
|
||||
@@ -45,8 +45,6 @@ object SteamIntegration {
|
||||
suggested = !SessionPrefs.sessionPrefs(context).getBoolean("steam_integration_seen", false),
|
||||
)
|
||||
|
||||
// Android 13+ blocks accessibility services for sideloaded APKs until the user allows restricted settings in App info.
|
||||
// MODE_DEFAULT is inconclusive on Android 15, so only an explicit denial counts here.
|
||||
private fun restrictedSettings(context: Context): Boolean {
|
||||
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.TIRAMISU) return false
|
||||
val mode = runCatching {
|
||||
@@ -90,7 +88,6 @@ object SteamIntegration {
|
||||
fun brightnessSettings(context: Context) = Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS,
|
||||
Uri.parse("package:${context.packageName}"))
|
||||
|
||||
// ACCESSIBILITY_DETAILS_SETTINGS is restricted to system apps; the fragment args key highlights our entry in the list.
|
||||
fun shortcutSettings(context: Context): Intent {
|
||||
val service = ComponentName(context, HomeButtonService::class.java).flattenToString()
|
||||
return Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
|
||||
|
||||
@@ -311,87 +311,3 @@ fun CollapsibleRail(
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun RailTopTabs(
|
||||
items: List<RailItem>,
|
||||
modifier: Modifier = Modifier,
|
||||
links: List<RailLink> = emptyList(),
|
||||
) {
|
||||
Column(modifier = modifier.fillMaxWidth()) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 2.dp, vertical = 2.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
items.forEach { item ->
|
||||
TopTabCell(
|
||||
icon = item.icon,
|
||||
label = item.label,
|
||||
selected = item.selected,
|
||||
onClick = item.onClick,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
if (links.isNotEmpty()) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.padding(horizontal = 2.dp)
|
||||
.width(1.dp)
|
||||
.height(30.dp)
|
||||
.background(MaterialTheme.colorScheme.outline.copy(alpha = 0.4f)),
|
||||
)
|
||||
links.forEach { link ->
|
||||
TopTabCell(link.icon, link.label, selected = false, onClick = link.onClick, isTab = false, modifier = Modifier.weight(1f))
|
||||
}
|
||||
}
|
||||
}
|
||||
HorizontalDivider()
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TopTabCell(
|
||||
icon: ImageVector,
|
||||
label: String,
|
||||
selected: Boolean,
|
||||
onClick: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
isTab: Boolean = true,
|
||||
) {
|
||||
val tint = if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
modifier = modifier
|
||||
.clip(RoundedCornerShape(9.dp))
|
||||
.background(if (selected) MaterialTheme.colorScheme.primary.copy(alpha = 0.14f) else Color.Transparent)
|
||||
.focusGlide(RoundedCornerShape(9.dp))
|
||||
.then(
|
||||
if (isTab) {
|
||||
Modifier.selectable(selected = selected, role = androidx.compose.ui.semantics.Role.Tab, onClick = onClick)
|
||||
} else {
|
||||
Modifier.clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = onClick)
|
||||
},
|
||||
)
|
||||
.padding(vertical = 6.dp, horizontal = 1.dp),
|
||||
) {
|
||||
Icon(icon, contentDescription = label, tint = tint, modifier = Modifier.size(20.dp))
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Text(
|
||||
label,
|
||||
color = tint,
|
||||
fontSize = 8.5.sp,
|
||||
fontWeight = FontWeight.Bold,
|
||||
letterSpacing = 0.2.sp,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.height(2.dp)
|
||||
.width(if (selected) 16.dp else 0.dp)
|
||||
.clip(RoundedCornerShape(3.dp))
|
||||
.background(if (selected) MaterialTheme.colorScheme.primary else Color.Transparent),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -57,7 +57,6 @@ object FileOps {
|
||||
return true
|
||||
}
|
||||
if (!copyWithProgress(src, dst, progress, isCancelled)) return false
|
||||
// Once the destination is committed, finish deleting the source.
|
||||
return delete(src)
|
||||
}
|
||||
|
||||
|
||||
@@ -63,7 +63,6 @@ object StorageRoots {
|
||||
}
|
||||
return true
|
||||
}
|
||||
// vold-managed locations only hold removable volumes, whatever the fstype is.
|
||||
return path.startsWith("/storage/") || path.startsWith("/mnt/media_rw/")
|
||||
}
|
||||
|
||||
@@ -92,8 +91,6 @@ object StorageRoots {
|
||||
.forEachIndexed { index, volume ->
|
||||
val uuid = volume.uuid?.takeIf { it.isNotBlank() }
|
||||
val dirName = volume.directory?.name?.takeIf { it.isNotBlank() }
|
||||
// Unmounted volumes often report neither uuid nor directory; never drop the
|
||||
// volume or a plugged-in drive stays invisible with no explanation.
|
||||
val descSlug = volume.getDescription(context)?.trim()
|
||||
?.takeIf { it.isNotBlank() && !it.equals("android", ignoreCase = true) }
|
||||
?.replace(Regex("[^A-Za-z0-9._-]+"), "-")
|
||||
@@ -108,8 +105,6 @@ object StorageRoots {
|
||||
if (name != null) {
|
||||
entry.candidates += File("/storage/$name")
|
||||
entry.candidates += File("/mnt/media_rw/$name")
|
||||
// Only strict uuid matches own an app directory; a loose match would
|
||||
// attach another volume's folder to this entry.
|
||||
if (uuid != null) appDirs.filter { belongsTo(storageManager!!, it, volume) }
|
||||
.forEach { entry.seeds += it }
|
||||
}
|
||||
@@ -122,8 +117,6 @@ object StorageRoots {
|
||||
File("/mnt/media_rw").listFiles().orEmpty().forEach { child ->
|
||||
if (child.isDirectory) volumeOf(child.name).candidates += child
|
||||
}
|
||||
// USB OTG drives do not always appear as storage volumes or under /storage for
|
||||
// third-party apps, but their kernel mounts are still visible in /proc/mounts.
|
||||
for (mount in externalMounts()) {
|
||||
val entry = volumeOf(mount.name)
|
||||
if (entry.label == null) entry.label = mount.name
|
||||
|
||||
@@ -180,7 +180,6 @@ object AddedGames {
|
||||
|
||||
private fun entryFolders(context: Context): Set<String> = AddedExes.list(context).map { it.folder }.toSet()
|
||||
|
||||
/** The card's Steam libraries: the arm64 client's steamapps and the x86-64 client's own folder beside it. */
|
||||
internal fun isSteamLibraryFolder(name: String): Boolean =
|
||||
name.equals("steamapps", ignoreCase = true) || name == com.droiddeck.launcher.session.GameStorage.X64_CARD_DIR
|
||||
|
||||
@@ -315,7 +314,6 @@ object AddedGames {
|
||||
|
||||
fun addFolder(context: Context, dir: File, onGame: (Game) -> Unit = {}, onChecking: (String?) -> Unit = {}, showHidden: Boolean = false): FolderResult {
|
||||
val app = context.applicationContext
|
||||
// Binds are mounted at session start, so a new one reaches the session from the next start.
|
||||
if (guestPath(app, dir) == null) bindFolder(app, dir)
|
||||
val removed = SessionPrefs.removedAddedGames(app).toSet()
|
||||
val listed = listedFolders(app, removed)
|
||||
|
||||
@@ -54,21 +54,6 @@ object DependencyDetector {
|
||||
"d3dx9", "d3dx11", "xact", "xact_x64", "xna31", "xna40", "physx", "oalinst", "XLiveRedist",
|
||||
)
|
||||
|
||||
fun detectForExe(exeFile: File): List<Recommendation> {
|
||||
val start = exeFile.absoluteFile.parentFile ?: return emptyList()
|
||||
var d: File? = start
|
||||
var depth = 0
|
||||
while (d != null && depth < 4) {
|
||||
val hasRedistContainer = try {
|
||||
d.listFiles()?.any { it.isDirectory && REDIST_DIR_RE.matches(it.name.lowercase(Locale.US)) } == true
|
||||
} catch (_: Throwable) { false }
|
||||
if (hasRedistContainer) return detect(d)
|
||||
d = d.parentFile
|
||||
depth++
|
||||
}
|
||||
return detect(start)
|
||||
}
|
||||
|
||||
fun detect(gameDir: File): List<Recommendation> {
|
||||
if (!gameDir.isDirectory) return emptyList()
|
||||
val hits = LinkedHashMap<String, Recommendation>()
|
||||
|
||||
@@ -87,7 +87,6 @@ object Library {
|
||||
|
||||
internal fun steamLibraries(context: Context, arch: String = SessionPrefs.activeSteamClientArch(context)): List<Pair<File, String>> {
|
||||
val root = SessionPrefs.steamRoot(context, arch)
|
||||
// The session gives the x86-64 client only its card folder; the games folders stay the arm64 client's.
|
||||
val card = GameStorage.effective(context)
|
||||
if (arch == "x86_64") return listOfNotNull(root to "internal", card?.let { File(it.path, GameStorage.X64_CARD_DIR) to it.label })
|
||||
return listOfNotNull(
|
||||
@@ -106,7 +105,6 @@ object Library {
|
||||
.firstOrNull { it.isDirectory }
|
||||
}
|
||||
|
||||
/** Every steamapps/compatdata folder, in the libraries [protonPrefix] searches. */
|
||||
fun compatdataDirs(context: Context, libraries: List<File> = steamLibraries(context).map { it.first }): List<File> =
|
||||
prefixRoots(context, libraries).map { File(it, "steamapps/compatdata") }.filter { it.isDirectory }
|
||||
|
||||
@@ -179,7 +177,6 @@ object Library {
|
||||
}
|
||||
}
|
||||
|
||||
/** Apps the user hid (the "hidden" collection) or marked private in Steam. */
|
||||
internal fun concealedSteamApps(root: File): Set<Long> {
|
||||
val config = AddedGames.accountConfig(root) ?: return emptySet()
|
||||
val hidden = runCatching {
|
||||
@@ -220,7 +217,6 @@ object Library {
|
||||
return (steam + own.map { g -> addedGame(context, g, roots, played[g.appId] ?: 0L) }).distinctBy { it.gameId }
|
||||
}
|
||||
|
||||
/** Steam's LastPlayTime for each non-Steam shortcut, by its unsigned shortcut app id. */
|
||||
internal fun shortcutsLastPlayed(root: File): Map<Long, Long> = runCatching {
|
||||
val config = AddedGames.accountConfig(root) ?: return emptyMap()
|
||||
val bytes = File(config, "shortcuts.vdf").takeIf { it.isFile }?.readBytes() ?: return emptyMap()
|
||||
|
||||
@@ -10,7 +10,6 @@ object LibraryCache {
|
||||
private const val TAG = "LibraryCache"
|
||||
private fun file(context: Context) = File(context.filesDir, "library-cache.json")
|
||||
|
||||
/** The cached games and whether they are the x86-64 client's; a cache written as a bare list is arm64's. */
|
||||
@Synchronized
|
||||
fun snapshot(context: Context): Pair<List<Library.SteamGame>, Boolean> = runCatching {
|
||||
val f = file(context)
|
||||
@@ -36,7 +35,6 @@ object LibraryCache {
|
||||
|
||||
fun listedX64(context: Context): Boolean = snapshot(context).second
|
||||
|
||||
/** Without [x64] the list keeps the client already recorded. */
|
||||
@Synchronized
|
||||
fun save(context: Context, games: List<Library.SteamGame>, x64: Boolean? = null) {
|
||||
runCatching {
|
||||
|
||||
@@ -2,7 +2,6 @@ package com.droiddeck.launcher.frontend
|
||||
|
||||
import org.json.JSONObject
|
||||
|
||||
/** Where Steam pins a game's logo on its hero image and how big it draws it; the same JSON Steam keeps in `<appid>.json`. */
|
||||
object LogoPosition {
|
||||
enum class Pin(val steam: String) {
|
||||
UPPER_LEFT("UpperLeft"), UPPER_CENTER("UpperCenter"), CENTER("CenterCenter"), BOTTOM_LEFT("BottomLeft"), BOTTOM_CENTER("BottomCenter");
|
||||
@@ -17,7 +16,6 @@ object LogoPosition {
|
||||
const val MIN_PCT = 10
|
||||
const val MAX_PCT = 100
|
||||
|
||||
/** What Steam draws when a game has no custom position. */
|
||||
val DEFAULT = Value(Pin.BOTTOM_LEFT, 50, 50)
|
||||
|
||||
private const val VERSION = 1
|
||||
@@ -25,7 +23,6 @@ object LogoPosition {
|
||||
|
||||
fun sized(pin: Pin, size: Int): Value = size.coerceIn(MIN_PCT, MAX_PCT).let { Value(pin, it, it) }
|
||||
|
||||
/** `{"nVersion":1,"logoPosition":{...}}`, with whatever else [into] already held kept as it was. */
|
||||
fun toJson(value: Value, into: JSONObject = JSONObject()): JSONObject = into
|
||||
.put("nVersion", VERSION)
|
||||
.put(KEY, JSONObject().put("pinnedPosition", value.pin.steam).put("nWidthPct", value.widthPct).put("nHeightPct", value.heightPct))
|
||||
@@ -39,7 +36,6 @@ object LogoPosition {
|
||||
return Value(pin, inner.optInt("nWidthPct").coerceIn(MIN_PCT, MAX_PCT), inner.optInt("nHeightPct").coerceIn(MIN_PCT, MAX_PCT))
|
||||
}
|
||||
|
||||
/** [existing] without the logo position; null when nothing but the version number would be left. */
|
||||
fun without(existing: JSONObject): JSONObject? {
|
||||
existing.remove(KEY)
|
||||
val rest = existing.keys().asSequence().filter { it != "nVersion" }.toList()
|
||||
|
||||
@@ -7,11 +7,9 @@ import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.util.UUID
|
||||
|
||||
/** Steam keeps a game's custom art in `userdata/<account>/config/grid`; this is where DroidDeck's choices and Steam's meet. */
|
||||
object SteamGrid {
|
||||
private const val TAG = "SteamGrid"
|
||||
|
||||
/** Every change to a game's art, here or in a scan, takes this first so two of them never interleave. */
|
||||
internal val lock = Any()
|
||||
private const val MANIFEST = ".droiddeck-art.json"
|
||||
private val SUFFIX = mapOf(AddedGameArt.Slot.COVER to "p", AddedGameArt.Slot.WIDE to "", AddedGameArt.Slot.BACKGROUND to "_hero", AddedGameArt.Slot.LOGO to "_logo")
|
||||
@@ -36,7 +34,6 @@ object SteamGrid {
|
||||
|
||||
private fun signature(file: File?) = if (file == null) "" else "${file.length()}:${file.lastModified()}"
|
||||
|
||||
/** Each Steam client has its own grid folder, so what was last seen there is kept per client. */
|
||||
private fun sigName(context: Context, key: String) =
|
||||
if (SessionPrefs.activeSteamClientArch(context) == "x86_64") "grid-x86_64-$key" else "grid-$key"
|
||||
|
||||
@@ -45,10 +42,6 @@ object SteamGrid {
|
||||
private const val GRID_ID = ".droiddeck-grid"
|
||||
private const val UNKNOWN_GRID = "?"
|
||||
|
||||
/**
|
||||
* A random id kept in the grid folder, so a record made against another account's folder, or one wiped with the
|
||||
* runtime, reads as "not seen yet" instead of "removed in Steam". "?" never matches, so nothing is dropped.
|
||||
*/
|
||||
private fun gridId(grid: File): String = runCatching {
|
||||
val f = File(grid, GRID_ID)
|
||||
f.takeIf { it.isFile }?.readText()?.trim()?.takeIf { it.isNotEmpty() } ?: UUID.randomUUID().toString().also { id ->
|
||||
@@ -83,7 +76,6 @@ object SteamGrid {
|
||||
manifest.keys().asSequence().filter { name -> File(grid, name).let { it.isFile && it.length() == manifest.optLong(name, -1L) } }.toSet()
|
||||
}.getOrDefault(emptySet())
|
||||
|
||||
/** Puts a choice (or, with null, the lack of one) where Steam reads it, whether or not Steam is running. */
|
||||
fun write(context: Context, target: Target, slot: AddedGameArt.Slot, file: File?): Boolean = synchronized(lock) { place(context, target, slot, file) }
|
||||
|
||||
private fun place(context: Context, target: Target, slot: AddedGameArt.Slot, file: File?): Boolean {
|
||||
@@ -116,7 +108,6 @@ object SteamGrid {
|
||||
|
||||
private fun positionIn(file: File): LogoPosition.Value? = file.takeIf { it.isFile }?.let { runCatching { it.readText() }.getOrNull() }?.let(LogoPosition::parse)
|
||||
|
||||
/** The logo position chosen here (or taken over from Steam) for a game; null when Steam's own default applies. */
|
||||
fun position(target: Target): LogoPosition.Value? = positionIn(File(target.artDir, POSITION))
|
||||
|
||||
private fun positionRecorded(context: Context, grid: File, target: Target): String? =
|
||||
@@ -132,12 +123,10 @@ object SteamGrid {
|
||||
return runCatching { file.writeText(LogoPosition.toJson(value).toString()) }.isSuccess
|
||||
}
|
||||
|
||||
/** Sets (or with null, clears) a game's logo position here and in the client's grid folder, whether or not Steam is running. */
|
||||
fun writePosition(context: Context, target: Target, value: LogoPosition.Value?): Boolean = synchronized(lock) {
|
||||
placePosition(context, target, value) && storePosition(target, value)
|
||||
}
|
||||
|
||||
/** Steam keeps the position in `<id>.json`; anything else that file holds is left as it was. */
|
||||
private fun placePosition(context: Context, target: Target, value: LogoPosition.Value?): Boolean {
|
||||
val grid = dir(context) ?: return true
|
||||
val file = positionFile(grid, target.id)
|
||||
@@ -160,7 +149,6 @@ object SteamGrid {
|
||||
return true
|
||||
}
|
||||
|
||||
/** A `logoPosition` this version cannot read (a pin it does not know, say) is left alone rather than read as "removed". */
|
||||
private fun hasUnknownPosition(file: File): Boolean {
|
||||
val json = runCatching { JSONObject(file.readText()) }.getOrNull() ?: return false
|
||||
return json.has("logoPosition") && LogoPosition.parse(json) == null
|
||||
@@ -176,7 +164,6 @@ object SteamGrid {
|
||||
when {
|
||||
before == null && own != null && theirs == null -> placePosition(context, target, own)
|
||||
before == null || now != before -> {
|
||||
// Recorded only once the local side agrees, so a failed take-over is tried again on the next scan.
|
||||
if (theirs != null) {
|
||||
if (own == theirs || storePosition(target, theirs)) recordPosition(context, grid, target, now)
|
||||
} else {
|
||||
@@ -187,7 +174,6 @@ object SteamGrid {
|
||||
}
|
||||
}
|
||||
|
||||
/** Takes over what changed in Steam since the last look; returns true when a choice was added, replaced or dropped. */
|
||||
fun sync(context: Context, targets: List<Target>): Boolean = synchronized(lock) { reconcile(context, targets) }
|
||||
|
||||
private fun reconcile(context: Context, targets: List<Target>): Boolean {
|
||||
|
||||
@@ -15,7 +15,6 @@ object SteamRedists {
|
||||
"228989" to ("vcredist2022_dll" to "VC++ 2022"),
|
||||
"228990" to ("d3dx9" to "DirectX (June 2010)"),
|
||||
)
|
||||
/** Redists a game's own install script runs on Windows that its shared depots don't name. */
|
||||
val SCRIPTED = mapOf(
|
||||
72850 to listOf("xact" to "DirectX XACT audio"),
|
||||
489830 to listOf("xact_x64" to "DirectX XACT audio (64-bit)"),
|
||||
@@ -28,7 +27,6 @@ object SteamRedists {
|
||||
return File(steamapps, "appmanifest_$appId.acf").takeIf { it.isFile }
|
||||
}
|
||||
|
||||
/** Redists the game's own install script has Steam run on Windows, from its "Run Process" entries. */
|
||||
fun installScript(gameDir: File?): List<Pair<String, String>> =
|
||||
gameDir?.listFiles { f ->
|
||||
f.isFile && f.length() < 1L shl 20 && f.name.lowercase().let { it.startsWith("installscript") && it.endsWith(".vdf") }
|
||||
|
||||
@@ -51,10 +51,8 @@ object WinCompSources {
|
||||
fun installer(path: String): List<String> = if (UE_PREREQ.containsMatchIn(path)) listOf("vcredist2022", "d3dx9") else DependencyDetector.componentsFor(path)
|
||||
|
||||
private val XBOX_KNOWN = Regex("""<KnownDependency\s+Name="([A-Za-z0-9_.-]{1,40})"""")
|
||||
// VC14 also registers the ARM64 runtime: launchers running as ARM64EC look for it and stop when it is missing.
|
||||
private val XBOX_COMPONENTS = mapOf("VC14" to listOf("vcredist2022", WinComponents.VCREDIST_ARM64))
|
||||
|
||||
/** Microsoft installs a PC Game Pass game's declared runtimes with it; VC14 is wanted by nearly all and is always added. */
|
||||
fun xbox(folder: File?): List<Pair<String, String>> {
|
||||
val config = folder?.listFiles().orEmpty().firstOrNull { it.isFile && it.name.equals("MicrosoftGame.config", ignoreCase = true) && it.length() < 1L shl 20 }
|
||||
val declared = config?.let { file -> runCatching { XBOX_KNOWN.findAll(file.readText()).map { it.groupValues[1] }.toList() }.getOrNull() }.orEmpty()
|
||||
|
||||
@@ -563,7 +563,6 @@ object Glasses {
|
||||
val device = selected?.first
|
||||
val m = selected?.second
|
||||
val controllable = m?.let(::canOpenModel) == true
|
||||
// XREAL uses Android's Ethernet sockets, without opening or claiming USB interfaces.
|
||||
val permitted = controllable && device != null && (m === XrealModel || usb.hasPermission(device))
|
||||
val identity = device?.let {
|
||||
GlassesModeState.Device(it.productId, if (permitted) runCatching { it.serialNumber }.getOrNull() else null)
|
||||
@@ -677,8 +676,6 @@ object Glasses {
|
||||
internal fun selectGlassesDisplay(displays: List<Display>, usbPresent: Boolean): Display? {
|
||||
val candidates = displays
|
||||
.filter { it.displayId != Display.DEFAULT_DISPLAY && it.flags and Display.FLAG_PRESENTATION != 0 }
|
||||
// Android can expose the glasses name on either the logical display or
|
||||
// its product metadata. A generic label on one must not hide the other.
|
||||
return candidates.firstOrNull { display ->
|
||||
isGlassesDisplayName(display.name) ||
|
||||
(Build.VERSION.SDK_INT >= 31 && display.deviceProductInfo?.let { product ->
|
||||
@@ -728,7 +725,6 @@ object Glasses {
|
||||
if (device.productId == VitureProtocol.PRO2_PRODUCT_ID) {
|
||||
VitureV2Link.open(usb, device, v2Listener(generation))
|
||||
} else if ((model as? VitureProtocol.Model)?.needsSdk == true) {
|
||||
// Android can evict cacheDir while the SDK is running.
|
||||
Log.i(TAG, "opening VITURE SDK pid=0x%04X spatial=%s".format(device.productId, spatial))
|
||||
VitureSdkLink.open(usb, device, File(app.noBackupFilesDir, "viture"), sdkListener(generation),
|
||||
(model as? VitureProtocol.Model)?.family, spatial)
|
||||
@@ -854,7 +850,6 @@ object Glasses {
|
||||
if (generation != linkGeneration) return@post
|
||||
closeLink()
|
||||
publish { it.copy(controlError = app.getString(R.string.glasses_connection_failed)) }
|
||||
// Let a reconnect or explicit Allow retry restart the SDK, not an endless failure loop.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -974,7 +969,6 @@ object Glasses {
|
||||
}
|
||||
if (!s.usable || s.sbs || modeState.pendingStereo) return
|
||||
val hz = _settings.value.refreshHz
|
||||
// Native 30 Hz is selected by the Android presentation, without a vendor mode command.
|
||||
if (hz == 30 && GlassesRendering.native30HzAvailable(_settings.value, s)) return
|
||||
if (glassesMode == m.mode(hz, false, outputResolution())) return
|
||||
if (!force) {
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package com.droiddeck.launcher.glasses
|
||||
|
||||
/** Hardware properties; display refresh is selected from Android's advertised modes. */
|
||||
interface GlassesModel {
|
||||
val name: String
|
||||
val controllable: Boolean
|
||||
@@ -18,9 +17,6 @@ interface GlassesModel {
|
||||
fun modeForStep(step: Int): Int?
|
||||
}
|
||||
|
||||
/** The command IDs here are the existing glasses controller's internal vocabulary.
|
||||
* Each transport translates them to its own wire protocol; unsupported controls return false.
|
||||
*/
|
||||
internal interface GlassesLink {
|
||||
val hasImu: Boolean
|
||||
val badFrames: Long get() = 0L
|
||||
|
||||
@@ -63,7 +63,6 @@ class GlassesMenuSurface(
|
||||
override fun onDetachedFromWindow() {
|
||||
close()
|
||||
super.onDetachedFromWindow()
|
||||
// GLSurfaceView may exit its GL thread before queued cleanup is consumed.
|
||||
releaseInput()
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,6 @@ package com.droiddeck.launcher.glasses
|
||||
|
||||
import com.droiddeck.launcher.gpu.Cardboard
|
||||
|
||||
/** Share the actual picture mode with settings so controls match the rendered view. */
|
||||
internal object GlassesRendering {
|
||||
enum class Picture { FLAT, DUPLICATED, VIRTUAL_SCREEN, STEREO }
|
||||
|
||||
@@ -51,11 +50,7 @@ internal object GlassesRendering {
|
||||
outputActive: Boolean,
|
||||
steamVrRunning: Boolean,
|
||||
): Cardboard {
|
||||
// Mirror output still uses the glasses' picture and sensors during VR.
|
||||
if (!usesGlasses(state, outputActive, steamVrRunning)) {
|
||||
// SteamVR uses the renderer's enabled flag as headset proximity.
|
||||
// A flat phone preview still needs an active HMD and one SBS eye;
|
||||
// otherwise SteamVR enters standby and leaves a frozen frame.
|
||||
return if (steamVrRunning && !base.enabled) base.copy(
|
||||
enabled = true,
|
||||
source = Cardboard.SOURCE_SBS,
|
||||
|
||||
@@ -36,7 +36,6 @@ class GlassesScreen(context: Context, display: Display, refreshHz: Int, private
|
||||
fun prefer(hz: Int, resolution: GlassesResolution? = null) {
|
||||
wantHz = hz
|
||||
wantResolution = resolution
|
||||
// A 2D/SBS transition can replace the active mode without changing Hz.
|
||||
applyMode()
|
||||
}
|
||||
|
||||
|
||||
@@ -51,7 +51,6 @@ internal class HandImageBuffer {
|
||||
pixels.clear()
|
||||
pixels.put(rgb)
|
||||
pixels.rewind()
|
||||
// MediaPipe applies the model metadata's float normalization to these RGB bytes.
|
||||
return ByteBufferImageBuilder(pixels, width, height, MPImage.IMAGE_FORMAT_RGB).build()
|
||||
}
|
||||
}
|
||||
@@ -150,7 +150,6 @@ class LumaRgbCaptureService : Service() {
|
||||
intent?.getIntExtra("durationMs",5000) ?: 5000) }
|
||||
finally {
|
||||
stopSelf()
|
||||
// SDK 2.4.0 can crash while cancelling failed USB transfers; isolate each diagnostic.
|
||||
android.os.Process.killProcess(android.os.Process.myPid())
|
||||
}
|
||||
}, "luma-rgb-diagnostic").start()
|
||||
|
||||
@@ -40,12 +40,9 @@ internal data class RayNeoCalibration(val gyroBiasDps: Vec3, val level: Quaterni
|
||||
|
||||
internal class RayNeoCalibrationStore(private val prefs: SharedPreferences) {
|
||||
companion object {
|
||||
// GT and GT Max can share USB identity fields. Keep the non-Max mounting
|
||||
// correction separate from existing Max profiles and their legacy keys.
|
||||
fun profileKey(base: String, gtUsb: Boolean, boardId: Int): String =
|
||||
if (gtUsb && boardId == RayNeoProtocol.BOARD_GT) "$base:gt-standard-v1" else base
|
||||
}
|
||||
// A serial isolates physical units. Devices without one share their model profile.
|
||||
fun key(vid: Int, pid: Int, serial: String?, modelName: String = ""): String =
|
||||
"rayneo-cal-v1:$vid:$pid:${serial?.takeIf { it.isNotBlank() } ?: "model:$modelName"}"
|
||||
fun load(key: String): RayNeoCalibration? = RayNeoCalibration.decode(prefs.getString(key, null))
|
||||
@@ -55,7 +52,6 @@ internal class RayNeoCalibrationStore(private val prefs: SharedPreferences) {
|
||||
}
|
||||
}
|
||||
|
||||
/** One upside-down stationary pose estimates gyro bias and tilt, never yaw or accelerometer scale. */
|
||||
internal class RayNeoCalibrationCollector(private val axes: RayNeoSensorAxes, private val beganMs: Long) {
|
||||
var phase = CalibrationPhase.SETTLING; private set
|
||||
var progress = 0; private set
|
||||
|
||||
@@ -6,7 +6,6 @@ import android.hardware.usb.UsbManager
|
||||
import android.os.SystemClock
|
||||
import android.util.Log
|
||||
|
||||
/** RayNeo command/response and IMU share one endpoint. Keep reads on a single worker. */
|
||||
internal class RayNeoLink private constructor(
|
||||
private val connection: UsbDeviceConnection,
|
||||
private val endpoints: RayNeoEndpointSelection,
|
||||
@@ -52,7 +51,6 @@ internal class RayNeoLink private constructor(
|
||||
ready && (mode == RayNeoProtocol.CMD_SWITCH_TO_3D || mode == RayNeoProtocol.CMD_SWITCH_TO_2D) &&
|
||||
command(mode)
|
||||
}
|
||||
// No VITURE brightness, volume, film, rate or raw command is sent to RayNeo.
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
@@ -159,7 +157,6 @@ internal class RayNeoLink private constructor(
|
||||
}
|
||||
val wxyz = filter.update(packet.sample)
|
||||
if (wantImu && collector == null && lastSensor >= warmupUntil) {
|
||||
// Normalize basis and component order at the hardware boundary.
|
||||
listener.onPose(raw, RayNeoOrientationFilter.glassesPose(wxyz),
|
||||
SystemClock.elapsedRealtimeNanos())
|
||||
}
|
||||
@@ -176,7 +173,6 @@ internal class RayNeoLink private constructor(
|
||||
override fun close() {
|
||||
synchronized(writeLock) {
|
||||
if (!running) return
|
||||
// Best effort: stop the sensor before releasing the claimed interface.
|
||||
if (ready) runCatching { command(RayNeoProtocol.CMD_CLOSE_IMU) }
|
||||
running = false
|
||||
}
|
||||
|
||||
@@ -8,8 +8,6 @@ object RayNeoModel {
|
||||
|
||||
fun model(vid: Int, pid: Int, name: String?): GlassesModel? {
|
||||
if (!isVendor(vid)) return null
|
||||
// GT's identity is confirmed by verncat's SDK; do not claim other products
|
||||
// from that vendor just because their name resembles a supported model.
|
||||
val gt = RayNeoProtocol.isGt(vid, pid)
|
||||
if (vid == RayNeoProtocol.GT_VENDOR_ID && !gt) return null
|
||||
if (!(vid == RayNeoProtocol.VENDOR_ID && pid == RayNeoProtocol.PRODUCT_ID) &&
|
||||
@@ -23,8 +21,6 @@ object RayNeoModel {
|
||||
name.contains("rayneo", ignoreCase = true) || name.contains("ray neo", ignoreCase = true) ||
|
||||
modelName.containsMatchIn(name)
|
||||
|
||||
// Observed on GT Max: Android exposes an unbranded EDID monitor name.
|
||||
// Match its product metadata, not every display called SmartGlasses/TCL.
|
||||
fun isDisplayProduct(name: String?, manufacturer: String?, productId: String?): Boolean =
|
||||
name?.trim().equals("SmartGlasses", ignoreCase = true) &&
|
||||
manufacturer.equals("TCL", ignoreCase = true) && productId == "980"
|
||||
@@ -33,7 +29,7 @@ object RayNeoModel {
|
||||
override val controllable = true
|
||||
override val brightnessMax = 0
|
||||
override val volumeMax = 0
|
||||
override val diagonalFovDeg = 46f // Conservative existing default, not a calibrated model profile.
|
||||
override val diagonalFovDeg = 46f
|
||||
override val sbs90 = false
|
||||
override fun mode(hz: Int, sbs: Boolean) =
|
||||
if (sbs) RayNeoProtocol.CMD_SWITCH_TO_3D else RayNeoProtocol.CMD_SWITCH_TO_2D
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
// Adapted from informalTechCode/RayNeo-Air-Series-3DoF-Scaffold (Apache-2.0).
|
||||
// See docs/third-party/rayneo/. Returns scaffold quaternions in (w, x, y, z) order.
|
||||
// Adapted from informalTechCode/RayNeo-Air-Series-3DoF-Scaffold (Apache-2.0); see docs/third-party/rayneo/ for license and attribution.
|
||||
package com.droiddeck.launcher.glasses
|
||||
|
||||
import kotlin.math.cos
|
||||
@@ -123,10 +122,6 @@ internal class RayNeoOrientationFilter(
|
||||
private var lastRealtimeNs: Long = 0L
|
||||
|
||||
companion object {
|
||||
/** Scaffold: right +X, up +Y, back +Z. VITURE: right -Y, up +Z, back -X.
|
||||
* Conjugate by HeadPose.GLASSES_AXES before entering the unchanged VITURE pose path.
|
||||
* This is a basis conversion, not a projection or seated-origin adjustment.
|
||||
*/
|
||||
fun glassesPose(wxyz: FloatArray): FloatArray =
|
||||
floatArrayOf(-wxyz[3], -wxyz[1], wxyz[2], wxyz[0])
|
||||
}
|
||||
@@ -168,8 +163,6 @@ internal class RayNeoOrientationFilter(
|
||||
if (accelNorm > 1e-3f) {
|
||||
val measuredUp = accel.normalized()
|
||||
if (!gravityInitialized) {
|
||||
// Align gravity before publishing the first pose. Starting at
|
||||
// identity and settling after recenter can rotate the horizon.
|
||||
val axis = measuredUp.cross(worldUp)
|
||||
q = if (measuredUp.y < -0.9999f) {
|
||||
Quaternion.fromAxisAngle(Vec3(1f, 0f, 0f), Math.PI.toFloat())
|
||||
@@ -179,7 +172,6 @@ internal class RayNeoOrientationFilter(
|
||||
gravityInitialized = true
|
||||
}
|
||||
val predictedUp = q.conjugate().rotate(worldUp).normalized()
|
||||
// q maps body to world: measured x predicted reduces gravity error.
|
||||
val correction = measuredUp.cross(predictedUp)
|
||||
gyro += correction * accelGain
|
||||
}
|
||||
|
||||
@@ -40,14 +40,13 @@ data class RayNeoEndpointSelection(
|
||||
object RayNeoProtocol {
|
||||
const val VENDOR_ID = 0x1BBB
|
||||
const val PRODUCT_ID = 0xAF50
|
||||
// verncat/RayNeo-Air-3S-Pro-OpenVR PR #3 (MIT), tested on GT hardware.
|
||||
const val GT_VENDOR_ID = 0x3941
|
||||
private const val GT_CONTROL_INTERFACE = 5
|
||||
|
||||
fun isGt(vid: Int, pid: Int) = vid == GT_VENDOR_ID && pid == PRODUCT_ID
|
||||
|
||||
const val BOARD_AIR_4_PRO = 0x3A
|
||||
const val BOARD_GT = 0x40 // Observed on the user's non-Max GT.
|
||||
const val BOARD_GT = 0x40
|
||||
|
||||
const val PKT_MAGIC = 0x99
|
||||
const val PKT_SENSOR = 0x65
|
||||
@@ -131,7 +130,6 @@ object RayNeoProtocol {
|
||||
endpoint.type != UsbConstants.USB_ENDPOINT_XFER_BULK) {
|
||||
continue
|
||||
}
|
||||
// Exclude small button reports from GT's protocol transport.
|
||||
if (gt && endpoint.maxPacketSize < 64) continue
|
||||
|
||||
if (endpoint.direction == UsbConstants.USB_DIR_IN && inEndpoint == null) {
|
||||
@@ -159,8 +157,6 @@ object RayNeoProtocol {
|
||||
}
|
||||
}
|
||||
|
||||
// Interface numbers can change with firmware. Use a unique protocol-sized
|
||||
// pair when interface 5 is absent, never an arbitrary composite interface.
|
||||
return if (gt) gtCandidates.singleOrNull() else fallback
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,6 @@ import android.hardware.usb.UsbManager
|
||||
import android.os.SystemClock
|
||||
import android.util.Log
|
||||
|
||||
/** Controls are vendor control transfers; the HID interrupt endpoint streams IMU reports unprompted. */
|
||||
internal class RokidLink private constructor(
|
||||
private val connection: UsbDeviceConnection,
|
||||
private val usbInterface: UsbInterface,
|
||||
@@ -44,7 +43,7 @@ internal class RokidLink private constructor(
|
||||
?.let { listener.onValue(VitureProtocol.MSG_BRIGHTNESS, RokidModel.brightnessStep(it)) } != null
|
||||
VitureProtocol.MSG_BRIGHTNESS -> value in 0..RokidModel.BRIGHTNESS_STEPS &&
|
||||
control(RokidModel.REQUEST_SET_BRIGHTNESS, RokidModel.brightnessRaw(value), RokidModel.INDEX_BRIGHTNESS)
|
||||
else -> false // Volume is the glasses' USB audio device; there is no film or IMU-rate control.
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,7 +53,6 @@ internal class RokidLink private constructor(
|
||||
if (!running) return null
|
||||
val buffer = ByteArray(64)
|
||||
val count = connection.controlTransfer(VENDOR_IN, request, 0, index, buffer, buffer.size, TIMEOUT_MS)
|
||||
// Display mode is reported in the second byte, brightness in the first.
|
||||
val offset = if (request == RokidModel.REQUEST_GET_DISPLAY) 1 else 0
|
||||
if (count > offset) buffer[offset].toInt() and 0xff else null
|
||||
}
|
||||
@@ -90,7 +88,6 @@ internal class RokidLink private constructor(
|
||||
if (enabled && !wasTracking) fusion = ImuFusion()
|
||||
wasTracking = enabled
|
||||
if (!enabled) continue
|
||||
// Max captures: already right/up/back; level gravity +Y, turn left +gyroY, look up +gyroX, roll right -gyroZ.
|
||||
fusion.update(sample.timeNs, sample.accel, sample.gyro)?.let {
|
||||
if (running && tracking) listener.onPose(buffer.copyOf(count), it, SystemClock.elapsedRealtimeNanos())
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ package com.droiddeck.launcher.glasses
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
|
||||
/** Rokid Air/Max share one USB identity; Max 2 has a separate product ID. */
|
||||
internal class RokidModel private constructor(override val name: String, private val max: Boolean) : GlassesModel {
|
||||
override val controllable = true
|
||||
override val brightnessMax = BRIGHTNESS_STEPS
|
||||
@@ -36,7 +35,6 @@ internal class RokidModel private constructor(override val name: String, private
|
||||
const val MAX2_PRODUCT_ID = 0x2002
|
||||
const val BRIGHTNESS_STEPS = 10
|
||||
|
||||
// Vendor control requests, device recipient.
|
||||
const val REQUEST_SET_DISPLAY = 0x01
|
||||
const val REQUEST_GET_DISPLAY = 0x81
|
||||
const val REQUEST_SET_BRIGHTNESS = 0x02
|
||||
@@ -51,7 +49,6 @@ internal class RokidModel private constructor(override val name: String, private
|
||||
const val MODE_SBS_1200_60 = 5
|
||||
val MODES = setOf(MODE_2D_60, MODE_SBS_1080_60, MODE_2D_120, MODE_SBS_1200_90, MODE_SBS_1200_60)
|
||||
|
||||
// 0x04d2 is a shared vendor ID, so the Rokid product string is required too.
|
||||
fun model(vid: Int, pid: Int, name: String?): GlassesModel? {
|
||||
if (vid != VENDOR_ID || (pid != PRODUCT_ID && pid != MAX2_PRODUCT_ID)) return null
|
||||
val product = name?.trim()?.takeIf { it.startsWith("Rokid", ignoreCase = true) } ?: return null
|
||||
@@ -60,7 +57,6 @@ internal class RokidModel private constructor(override val name: String, private
|
||||
|
||||
fun isDisplay(name: String) = name.contains("Rokid", ignoreCase = true)
|
||||
|
||||
/** Device brightness is 0..100; the shared slider uses ten steps. */
|
||||
fun brightnessStep(raw: Int): Int = ((raw.coerceIn(0, 100) + 5) / 10).coerceIn(0, BRIGHTNESS_STEPS)
|
||||
fun brightnessRaw(step: Int): Int = step.coerceIn(0, BRIGHTNESS_STEPS) * 10
|
||||
}
|
||||
@@ -74,7 +70,6 @@ internal object RokidProtocol {
|
||||
private const val SENSOR_ACCEL = 1
|
||||
private const val SENSOR_GYRO = 2
|
||||
|
||||
/** Max sends one combined report; Air sends accel and gyro reports that share a timestamp. */
|
||||
class Parser {
|
||||
private var accel: Vec3? = null
|
||||
private var accelTime = -1L
|
||||
@@ -87,7 +82,7 @@ internal object RokidProtocol {
|
||||
return when (packet[0].toInt() and 0xff) {
|
||||
COMBINED -> Sample(b.getLong(1), vec(b, 9), vec(b, 21), packet[59].toInt() and 0xff)
|
||||
SEPARATE -> {
|
||||
val time = b.getLong(9) * 1000 // Air reports microseconds; Max reports nanoseconds.
|
||||
val time = b.getLong(9) * 1000
|
||||
when (packet[1].toInt() and 0xff) {
|
||||
SENSOR_ACCEL -> { accel = vec(b, 21); accelTime = time }
|
||||
SENSOR_GYRO -> { gyro = vec(b, 21); gyroTime = time }
|
||||
|
||||
@@ -26,7 +26,6 @@ internal class StereoCalibration(val identity: String, val width: Int, val heigh
|
||||
val source get() = if (bundledBase && !verified) "luma-ultra-base" else "device"
|
||||
private val p1 = Mat.zeros(3, 4, CvType.CV_64F)
|
||||
private val p2 = Mat.zeros(3, 4, CvType.CV_64F)
|
||||
private val undistortionMaps = Array(2) { arrayOf(Mat(),Mat()) }
|
||||
init {
|
||||
val a = Mat.eye(3, 4, CvType.CV_64F)
|
||||
val b = Mat.zeros(3, 4, CvType.CV_64F)
|
||||
@@ -35,18 +34,6 @@ internal class StereoCalibration(val identity: String, val width: Int, val heigh
|
||||
Core.gemm(k1, a, 1.0, empty, 0.0, p1); Core.gemm(k2, b, 1.0, empty, 0.0, p2)
|
||||
a.release(); b.release(); empty.release()
|
||||
}
|
||||
fun undistort(src: Mat, dst: Mat, right: Boolean) {
|
||||
val k = if (right) k2 else k1; val d = if (right) d2 else d1
|
||||
val maps=undistortionMaps[if(right) 1 else 0]
|
||||
if(maps[0].empty()) {
|
||||
val identity=Mat.eye(3,3,CvType.CV_64F)
|
||||
try {
|
||||
if(fisheye) Calib3d.fisheye_initUndistortRectifyMap(k,d,identity,k,src.size(),CvType.CV_16SC2,maps[0],maps[1])
|
||||
else Calib3d.initUndistortRectifyMap(k,d,identity,k,src.size(),CvType.CV_16SC2,maps[0],maps[1])
|
||||
} finally { identity.release() }
|
||||
}
|
||||
Imgproc.remap(src,dst,maps[0],maps[1],Imgproc.INTER_LINEAR)
|
||||
}
|
||||
fun triangulateRaw(left: List<Point>, right: List<Point>): List<SpatialVector>? {
|
||||
val points = triangulateLandmarksRaw(left,right) ?: return null
|
||||
return if(points.any { it == null }) null else points.filterNotNull()
|
||||
@@ -74,10 +61,6 @@ internal class StereoCalibration(val identity: String, val width: Int, val heigh
|
||||
return triangulatePoints(l.toList(),r.toList())
|
||||
} finally { l.release(); r.release(); identity.release() }
|
||||
}
|
||||
fun triangulate(left: List<Point>, right: List<Point>): List<SpatialVector>? {
|
||||
val points = triangulatePoints(left,right) ?: return null
|
||||
return if(points.any { it == null }) null else points.filterNotNull()
|
||||
}
|
||||
private fun triangulatePoints(left: List<Point>, right: List<Point>): List<SpatialVector?>? {
|
||||
if (left.size != right.size || left.isEmpty()) return null
|
||||
val a = Mat(2, left.size, CvType.CV_64F); val b = Mat(2, right.size, CvType.CV_64F); val out = Mat()
|
||||
@@ -105,7 +88,7 @@ internal class StereoCalibration(val identity: String, val width: Int, val heigh
|
||||
val tmp = File(file.parentFile,file.name+".tmp"); tmp.writeText(j.toString())
|
||||
java.nio.file.Files.move(tmp.toPath(),file.toPath(),java.nio.file.StandardCopyOption.REPLACE_EXISTING)
|
||||
}
|
||||
override fun close() { (listOf(k1,d1,k2,d2,r,t,p1,p2)+undistortionMaps.flatMap { it.toList() }).forEach { it.release() } }
|
||||
override fun close() { listOf(k1,d1,k2,d2,r,t,p1,p2).forEach { it.release() } }
|
||||
companion object {
|
||||
fun load(file: File, identity: String, width: Int, height: Int): StereoCalibration? =
|
||||
runCatching { StereoCalibrationProfile.parse(file.readText(), identity, width, height)?.let(::fromProfile) }.getOrNull()
|
||||
@@ -286,7 +269,6 @@ internal class StereoCalibrator(private val context: Context) : AutoCloseable {
|
||||
Mat().also { output -> corrected.add(output); Calib3d.fisheye_undistortPoints(pixels,output,k,d,identity,k) }
|
||||
}
|
||||
try {
|
||||
// OpenCV 4.13 fisheye stereo fitting assumes equal corner counts in every view.
|
||||
Calib3d.stereoCalibrate(objects,images(left,k1,d1),images(right,k2,d2),k1,if(fish)zero else d1,k2,if(fish)zero else d2,
|
||||
size,r,t,e,f,Calib3d.CALIB_FIX_INTRINSIC)
|
||||
} finally { (corrected+listOf(e,f,identity,zero)).forEach(Mat::release) }
|
||||
|
||||
@@ -383,7 +383,6 @@ internal class StereoHandEngine(private val context: Context, private val token:
|
||||
message=context.getString(R.string.spatial_frame_changed)
|
||||
calibrationProgress = calibrationProgress.copy(collecting = false, capturing = false, captureMessage = message)
|
||||
}
|
||||
// The callback pose's basis is undocumented; use canonical GL pose history.
|
||||
val observation=HandObservation(time,generation,trackingFrame)
|
||||
var captureHead=observation.headPose(SpatialTracking.session,metadata[6]>0)
|
||||
val w=metadata[0].toInt();val h=metadata[1].toInt()
|
||||
@@ -499,7 +498,6 @@ internal class StereoHandEngine(private val context: Context, private val token:
|
||||
dl=pair.first.hands;dr=pair.second.hands
|
||||
if(scheduled) inferenceSchedule.observe(stamp,dl.map { it.side },dr.map { it.side },pair.first.rawCount,pair.second.rawCount)
|
||||
val inferenceMs=(System.nanoTime()-inferenceStart)/1e6f
|
||||
// VIO callbacks can arrive during inference; verify this exact camera stamp before publishing.
|
||||
captureHead=observation.headPose(SpatialTracking.session,
|
||||
metadata[6]>0 || VitureSdk.nativeCameraSynchronized(token,metadata[2]))
|
||||
val hands=Array(2) { SpatialHand() }
|
||||
@@ -631,7 +629,7 @@ internal class StereoHandEngine(private val context: Context, private val token:
|
||||
SpatialTracking.publish(System.nanoTime())
|
||||
}
|
||||
}
|
||||
} catch(e: InterruptedException) { /* Shutdown interrupts the idle wait. */ }
|
||||
} catch(e: InterruptedException) { }
|
||||
catch(e: Throwable) {
|
||||
message=context.getString(R.string.spatial_hand_error, e.message.orEmpty())
|
||||
val unavailable=HandObservationDiagnostic(HandObservationOutcome.INFERENCE_UNAVAILABLE)
|
||||
|
||||
@@ -31,7 +31,6 @@ internal class StereoInferenceRunner : AutoCloseable {
|
||||
catch (e: ExecutionException) { throw e.cause ?: e }
|
||||
}
|
||||
} finally {
|
||||
// Native inference must finish before either camera's pixels or detector can be reused.
|
||||
if (interrupted) Thread.currentThread().interrupt()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,8 +12,6 @@ internal object UvcRgbDiagnostic {
|
||||
internal data class UvcStreamHealth(val observationMs: Double, val observedFps: Double,
|
||||
val maximumGapMs: Double, val healthy: Boolean) {
|
||||
companion object {
|
||||
// Health requires the full requested window, 80% of requested FPS, and no gap
|
||||
// (including the final silent interval) above max(250 ms, three frame periods).
|
||||
fun assess(metadata: LongArray, requestedFps: Int, durationMs: Int): UvcStreamHealth {
|
||||
require(metadata.size == 14 && requestedFps > 0 && durationMs > 0)
|
||||
val first = metadata[7]
|
||||
|
||||
@@ -81,7 +81,6 @@ object VitureProtocol {
|
||||
}
|
||||
}
|
||||
|
||||
/** SDK validates the PID before returning this market name. Never guess a new PID. */
|
||||
fun sdkModel(marketName: String): Model? {
|
||||
val family = when (marketName) {
|
||||
"One", "Lite" -> Family.ONE
|
||||
|
||||
@@ -3,7 +3,6 @@ package com.droiddeck.launcher.glasses
|
||||
import android.util.Log
|
||||
import kotlin.math.sqrt
|
||||
|
||||
/** JNI adapter to VITURE's Android C SDK. The vendor binary is a local build input. */
|
||||
internal object VitureSdk {
|
||||
val available: Boolean by lazy {
|
||||
runCatching {
|
||||
@@ -27,7 +26,6 @@ internal object VitureSdk {
|
||||
external fun nativeSpatialDiagnostics(token: Long): DoubleArray?
|
||||
external fun nativeTracking(token: Long, enabled: Boolean): Int
|
||||
external fun nativeCommand(token: Long, command: Int, value: Int): Int
|
||||
/** Returns CLOCK_BOOTTIME receipt time, zero for no new pose, or a negative SDK error. */
|
||||
external fun nativePose(token: Long, wxyz: FloatArray): Long
|
||||
external fun nativeNextState(token: Long, event: IntArray): Int
|
||||
external fun nativeClose(token: Long)
|
||||
@@ -48,12 +46,9 @@ internal object VitureSpatialIdentity {
|
||||
}
|
||||
|
||||
internal object VitureSdkPose {
|
||||
// Pro 2 hardware captures use OpenGL axes despite the generic Gen2 callback's
|
||||
// NWU documentation. Keep that model-specific exception out of other Gen2 devices.
|
||||
fun usesOpenGlAxes(carina: Boolean, family: VitureProtocol.Family?) =
|
||||
carina || family == VitureProtocol.Family.PRO2
|
||||
|
||||
/** SDK quaternions are wxyz; normalize their coordinate basis at the boundary. */
|
||||
fun toGlasses(wxyz: FloatArray, openGlAxes: Boolean): FloatArray? {
|
||||
if (wxyz.size != 4 || wxyz.any { !it.isFinite() }) return null
|
||||
val length = sqrt(wxyz.sumOf { it.toDouble() * it }.toFloat())
|
||||
|
||||
@@ -7,7 +7,6 @@ import android.os.SystemClock
|
||||
import android.util.Log
|
||||
import java.io.File
|
||||
|
||||
/** SDK owns interface selection (including Ultra bulk endpoints) and all USB I/O. */
|
||||
internal class VitureSdkLink private constructor(
|
||||
private val connection: UsbDeviceConnection,
|
||||
private val token: Long,
|
||||
@@ -47,7 +46,6 @@ internal class VitureSdkLink private constructor(
|
||||
if (rc == 0 || !wanted) tracking = wanted
|
||||
return result("tracking", rc)
|
||||
}
|
||||
// Frequency is negotiated against SDK capabilities, including Pro 2's pose limit.
|
||||
VitureProtocol.MSG_IMU_RATE -> return tracking
|
||||
VitureProtocol.MSG_GET_IMU -> return true
|
||||
}
|
||||
@@ -89,7 +87,6 @@ internal class VitureSdkLink private constructor(
|
||||
if (VitureSdk.nativeNextState(token, event) == 1) when (event[0]) {
|
||||
0 -> listener.onValue(VitureProtocol.MSG_GET_BRIGHTNESS, event[1])
|
||||
1 -> listener.onValue(VitureProtocol.MSG_GET_VOLUME, event[1])
|
||||
// A device event can use a different display-mode namespace.
|
||||
2 -> send(VitureProtocol.MSG_GET_DISPLAY)
|
||||
3 -> listener.onValue(VitureProtocol.MSG_FILM, event[1])
|
||||
}
|
||||
@@ -122,7 +119,6 @@ internal class VitureSdkLink private constructor(
|
||||
if (!running) return
|
||||
running = false
|
||||
VitureSdk.nativeClose(token)
|
||||
// Keep Java's descriptor alive until the SDK and its worker threads have stopped.
|
||||
connection.close()
|
||||
}
|
||||
if (Thread.currentThread() !== worker) worker.join(1000)
|
||||
|
||||
@@ -69,7 +69,6 @@ internal class VitureV2Link internal constructor(
|
||||
return true
|
||||
}
|
||||
if (msgId == VitureProtocol.MSG_GET_IMU) return true
|
||||
// Keep the measured 120 Hz mode; the generic controller requests 240 Hz.
|
||||
if (msgId == VitureProtocol.MSG_IMU_RATE) return false
|
||||
val query = when (msgId) {
|
||||
VitureProtocol.MSG_GET_BRIGHTNESS -> VitureV2Protocol.MSG_GET_BRIGHTNESS
|
||||
@@ -146,9 +145,7 @@ internal class VitureV2Link internal constructor(
|
||||
tracking(true)
|
||||
if (becameReady) listener.onReady()
|
||||
val q = pose.quaternion
|
||||
// Upstream right/up/back pose converted to the shared VITURE legacy basis.
|
||||
val shared = floatArrayOf(-q[2], -q[0], q[1], q[3])
|
||||
// Upstream does not establish device tick units; use host monotonic receipt time.
|
||||
if (running && wanted && streamOn) listener.onPose(received.bytes, shared, received.timeNs)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
// Adapted from elasticjava/viture-v2, MIT, Copyright (c) 2026 Holger Bartnick.
|
||||
// Source: ece8c30485f7d357fefa362ae74f3eabac9b3899; see docs/third-party/viture-v2/.
|
||||
// Adapted from elasticjava/viture-v2, MIT, Copyright (c) 2026 Holger Bartnick. Source: ece8c30485f7d357fefa362ae74f3eabac9b3899; see docs/third-party/viture-v2/.
|
||||
package com.droiddeck.launcher.glasses
|
||||
|
||||
import kotlin.math.sqrt
|
||||
@@ -37,7 +36,6 @@ object VitureV2Protocol {
|
||||
val success: Boolean get() = status == 0
|
||||
}
|
||||
|
||||
// Device ticks have no established time unit; quaternion is xyzw with no axis remapping.
|
||||
class Pose internal constructor(
|
||||
val deviceTick: Long,
|
||||
val quaternion: FloatArray,
|
||||
@@ -64,7 +62,6 @@ object VitureV2Protocol {
|
||||
}
|
||||
|
||||
fun imuControl(streams: Int, rate: Rate = Rate.HZ_120): ByteArray {
|
||||
// Upstream measured that stream mask 3 ACKs but produces no events on Pro 2.
|
||||
require(streams == STREAM_OFF || streams == STREAM_POSE || streams == STREAM_RAW)
|
||||
require(streams != STREAM_POSE || rate.hz <= 240)
|
||||
val wireRate = if (streams == STREAM_OFF) 0 else rate.wireValue
|
||||
|
||||
@@ -24,7 +24,6 @@ internal interface XrealConnector : Closeable {
|
||||
|
||||
internal class XrealNetworkMissing : IOException("XREAL USB Ethernet network is not available")
|
||||
|
||||
/** Bind individual sockets, never the process: Steam must retain its Internet network. */
|
||||
internal class AndroidXrealConnector(context: Context) : XrealConnector {
|
||||
private val manager = context.getSystemService(ConnectivityManager::class.java)
|
||||
private val address = InetAddress.getByName(XrealProtocol.HOST)
|
||||
|
||||
@@ -7,7 +7,6 @@ import java.util.concurrent.ArrayBlockingQueue
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicReference
|
||||
|
||||
/** One connection owns two TCP channels. All control requests are serialized off the UI thread. */
|
||||
internal class XrealLink internal constructor(
|
||||
private val connector: XrealConnector,
|
||||
private val listener: Listener,
|
||||
@@ -47,7 +46,7 @@ internal class XrealLink internal constructor(
|
||||
VitureProtocol.MSG_DISPLAY -> value in 2..5 || value == XrealModel.NATIVE_60HZ
|
||||
VitureProtocol.MSG_BRIGHTNESS -> value in 0..9
|
||||
VitureProtocol.MSG_FILM -> value in 0..1
|
||||
else -> false // No guessed volume, sensor-rate, or VITURE wire commands.
|
||||
else -> false
|
||||
}
|
||||
return valid && commands.offer(Command(msgId, value))
|
||||
}
|
||||
@@ -88,7 +87,7 @@ internal class XrealLink internal constructor(
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
failure.set(e)
|
||||
current.close() // Wake a control read immediately.
|
||||
current.close()
|
||||
}
|
||||
}, "xreal-reports").apply { isDaemon = true; start() }
|
||||
ready = true
|
||||
@@ -145,12 +144,11 @@ internal class XrealLink internal constructor(
|
||||
tracking = false
|
||||
commands.clear()
|
||||
connection.getAndSet(null)?.close()
|
||||
connector.close() // Includes sockets still inside connect().
|
||||
connector.close()
|
||||
worker.interrupt()
|
||||
}
|
||||
}
|
||||
|
||||
/** Kept independent of Android so the real framing/acknowledgement path is testable. */
|
||||
internal class XrealControl(private val channels: XrealChannels, private val settleDelayMs: Long = 150) {
|
||||
private var transaction = 0
|
||||
private fun exchange(command: Int, value: Int? = null): ByteArray {
|
||||
@@ -158,7 +156,7 @@ internal class XrealControl(private val channels: XrealChannels, private val set
|
||||
channels.controlOutput.write(XrealProtocol.request(command, transaction, value))
|
||||
channels.controlOutput.flush()
|
||||
val deadline = System.nanoTime() + 3_000_000_000L
|
||||
repeat(32) { // Bound unsolicited button/status packets and stale responses.
|
||||
repeat(32) {
|
||||
if (System.nanoTime() > deadline) throw IOException("XREAL control timed out")
|
||||
XrealProtocol.response(XrealProtocol.read(channels.controlInput), command, transaction)?.let { return it }
|
||||
}
|
||||
@@ -172,9 +170,6 @@ internal class XrealControl(private val channels: XrealChannels, private val set
|
||||
fun changeDisplay(mode: Int): Int {
|
||||
val stereo = mode == 5
|
||||
set(XrealProtocol.SET_INPUT, if (stereo) 1 else 0)
|
||||
// On 1S, SET_INPUT itself changes EDID. Sending SET_DISPLAY immediately
|
||||
// receives error 5001 while that change is pending. GET_DISPLAY returns
|
||||
// an empty property during the transition; wait for a real mode report.
|
||||
val current = awaitDisplay { (it == 5) == stereo }
|
||||
if (current == mode) return current
|
||||
set(XrealProtocol.SET_DISPLAY, mode)
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
package com.droiddeck.launcher.glasses
|
||||
|
||||
/** First One-family target. Recovery and Air USB products must not use this transport. */
|
||||
object XrealModel : GlassesModel {
|
||||
const val VENDOR_ID = 0x3318
|
||||
const val PRODUCT_1S = 0x043e
|
||||
const val NATIVE_60HZ = 29 // Captured on 1S: 1920 x 1200 at 60 Hz.
|
||||
const val NATIVE_60HZ = 29
|
||||
override val name = "XREAL 1S"
|
||||
override val controllable = true
|
||||
override val brightnessMax = 9
|
||||
@@ -16,7 +15,6 @@ object XrealModel : GlassesModel {
|
||||
fun matches(vid: Int, pid: Int) = vid == VENDOR_ID && pid == PRODUCT_1S
|
||||
fun isDisplay(name: String) = name.contains("XREAL", ignoreCase = true)
|
||||
|
||||
// One-family EDID configuration values, not VITURE's display mode IDs.
|
||||
override fun mode(hz: Int, sbs: Boolean) = when {
|
||||
sbs -> 5
|
||||
hz >= 120 -> 4
|
||||
|
||||
@@ -2,19 +2,14 @@ package com.droiddeck.launcher.glasses
|
||||
|
||||
import kotlin.math.abs
|
||||
|
||||
/** 1S radians/sec and device nanoseconds, mapped using directed hardware captures. */
|
||||
internal class XrealOrientationFilter {
|
||||
private val fusion = ImuFusion()
|
||||
|
||||
// 1S reports right/down/forward. Rotate 180 degrees about X into the
|
||||
// shared right/up/back basis before either gravity alignment or fusion.
|
||||
// Captures: level gravity -Y; looking left -gyroY; up +gyroX; right tilt +gyroZ.
|
||||
fun update(sample: XrealProtocol.Sample): FloatArray? = fusion.update(sample.timeNs,
|
||||
Vec3(sample.accel.x, -sample.accel.y, -sample.accel.z),
|
||||
Vec3(sample.gyro.x, -sample.gyro.y, -sample.gyro.z))
|
||||
}
|
||||
|
||||
/** Gyro integration with gravity correction in the shared right/up/back basis, rad/s and device ns. */
|
||||
internal class ImuFusion {
|
||||
private var previous = 0L
|
||||
private var rotation = Quaternion.IDENTITY
|
||||
@@ -27,7 +22,7 @@ internal class ImuFusion {
|
||||
previous = timeNs
|
||||
val norm = accel.length()
|
||||
val gravityValid = abs(norm - 9.81f) < 1.5f
|
||||
if (dt > 0.25f) initialized = false // Never integrate a reconnect/stall as motion.
|
||||
if (dt > 0.25f) initialized = false
|
||||
if (!initialized) {
|
||||
if (!gravityValid) return null
|
||||
val up = accel.normalized()
|
||||
@@ -47,7 +42,6 @@ internal class ImuFusion {
|
||||
}
|
||||
rotation = rotation.integrateBodyRate(rate, dt).normalized()
|
||||
}
|
||||
// Same right/up/back -> shared glasses basis used by the RayNeo adapter.
|
||||
return RayNeoOrientationFilter.glassesPose(floatArrayOf(rotation.w, rotation.x, rotation.y, rotation.z))
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,6 @@ import java.io.InputStream
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
|
||||
/** Independent implementation of the One-family wire format; see xreal-investigation.md. */
|
||||
internal object XrealProtocol {
|
||||
const val HOST = "169.254.2.1"
|
||||
const val REPORT_PORT = 52998
|
||||
@@ -46,7 +45,7 @@ internal object XrealProtocol {
|
||||
fun sample(frame: Frame): Sample? {
|
||||
if (frame.command != REPORT || frame.body.size != 128) return null
|
||||
val b = ByteBuffer.wrap(frame.body).order(ByteOrder.LITTLE_ENDIAN)
|
||||
if (b.getInt(24) != 11) return null // Magnetometer reports are a different type.
|
||||
if (b.getInt(24) != 11) return null
|
||||
val time = b.getLong(8)
|
||||
val gyro = Vec3(b.getFloat(28), b.getFloat(32), b.getFloat(36))
|
||||
val accel = Vec3(b.getFloat(40), b.getFloat(44), b.getFloat(48))
|
||||
@@ -64,7 +63,6 @@ internal object XrealProtocol {
|
||||
.putInt(4 + payload.size).putInt(transaction or Int.MIN_VALUE).put(payload).array()
|
||||
}
|
||||
|
||||
/** No acknowledgement is inferred from a write; match both command and transaction. */
|
||||
fun response(frame: Frame, command: Int, transaction: Int): ByteArray? {
|
||||
if (frame.command != command || frame.body.size < 4 ||
|
||||
ByteBuffer.wrap(frame.body).int != transaction) return null
|
||||
|
||||
@@ -48,10 +48,6 @@ object AutoDriverTrial {
|
||||
|
||||
fun bad(context: Context): Set<String> = prefs(context).getStringSet("bad", emptySet()).orEmpty()
|
||||
|
||||
/**
|
||||
* Counted before the compositor loads the trial display driver, so a driver that kills the process during
|
||||
* Vulkan init still counts towards a rollback; sessionStarting runs too late for that.
|
||||
*/
|
||||
fun displayStarting(context: Context, display: String) {
|
||||
val p = prefs(context)
|
||||
if (p.getString("release", null) == null || p.getString("display", "") != display) return
|
||||
|
||||
@@ -52,7 +52,6 @@ object FrameGen {
|
||||
|
||||
fun apply(context: Context, refreshHz: Float): String? = apply(context, mode(context), refreshHz)
|
||||
|
||||
/** Arms [mode] in this process's compositor; the cloud player passes its own mode and frame-rate cap. */
|
||||
fun apply(context: Context, mode: Mode, refreshHz: Float): String? {
|
||||
when (mode.engine) {
|
||||
ENGINE_LSFG -> {
|
||||
|
||||
@@ -25,14 +25,6 @@ public final class LinuxVulkanDriver {
|
||||
return values;
|
||||
}
|
||||
|
||||
public static String optionLabel(Context context, String value) {
|
||||
if (value == null || value.isEmpty()) return "Runtime default (built into the runtime)";
|
||||
LinuxVulkanDriverManager m = new LinuxVulkanDriverManager(context);
|
||||
if (!m.isInstalled(value)) return value + " (imported, missing - uses the runtime default)";
|
||||
String ver = m.getDriverVersion(value);
|
||||
return m.getDriverName(value) + (ver.isEmpty() ? "" : " " + ver) + " (imported)";
|
||||
}
|
||||
|
||||
public static String resolveIcdPath(Context context, String value) {
|
||||
if (value == null || value.isEmpty()) return null;
|
||||
LinuxVulkanDriverManager m = new LinuxVulkanDriverManager(context);
|
||||
|
||||
@@ -6,7 +6,6 @@ import java.io.RandomAccessFile
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.attribute.BasicFileAttributes
|
||||
|
||||
/** Only new compositor output is evidence of a fault in the current session. */
|
||||
internal class SteamVrDeviceLossLog(private val file: File) {
|
||||
private var identity: Any? = identity()
|
||||
private var position = file.length()
|
||||
@@ -34,7 +33,6 @@ internal class SteamVrDeviceLossLog(private val file: File) {
|
||||
}
|
||||
identity = current
|
||||
prefix = head
|
||||
// Fault loops can produce megabytes per second. Bound work and keep the newest output.
|
||||
if (input.length() - position > MAX_READ) {
|
||||
position = input.length() - MAX_READ
|
||||
partial = ""
|
||||
|
||||
@@ -11,7 +11,6 @@ import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.session.SessionEvents
|
||||
import java.io.File
|
||||
|
||||
/** Process-wide cursor survives Activity recreation; a new session ignores older log errors. */
|
||||
internal object SteamVrHealth {
|
||||
private var session: String? = null
|
||||
private var log: SteamVrDeviceLossLog? = null
|
||||
@@ -49,7 +48,6 @@ internal class SteamVrRecovery(private val activity: Activity, private val foreg
|
||||
.create()
|
||||
prompt.setOnDismissListener { countdown?.let(handler::removeCallbacks); countdown = null; dialog = null }
|
||||
dialog = prompt
|
||||
// A touch meant for the game must not silently dismiss the recovery controls.
|
||||
prompt.setCanceledOnTouchOutside(false)
|
||||
prompt.show()
|
||||
if (automatic) {
|
||||
@@ -66,7 +64,6 @@ internal class SteamVrRecovery(private val activity: Activity, private val foreg
|
||||
|
||||
private fun restart() {
|
||||
if (!foreground()) return
|
||||
// Commit before crossing processes so a repeated fault cannot create a restart loop.
|
||||
if (!activity.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
|
||||
.putLong(LAST_ATTEMPT, System.currentTimeMillis()).commit()) return
|
||||
SessionEvents.record("steamvr.recovery_requested")
|
||||
|
||||
@@ -5,13 +5,11 @@ import org.json.JSONObject
|
||||
import java.io.File
|
||||
|
||||
internal object SteamVrRecoverySettings {
|
||||
/** After a graphics crash SteamVR can quarantine our HMD, leaving a server with no VR output. */
|
||||
fun unblockHeadset(file: File): Boolean {
|
||||
if (!file.isFile) return false
|
||||
val settings = JSONObject(file.readText())
|
||||
val driver = settings.optJSONObject("driver_droiddeck") ?: return false
|
||||
if (!driver.optBoolean("blocked_by_safe_mode")) return false
|
||||
// Preserve every other setting, including safe mode and blocks on other drivers.
|
||||
driver.put("blocked_by_safe_mode", false)
|
||||
val atomic = AtomicFile(file)
|
||||
val output = atomic.startWrite()
|
||||
|
||||
@@ -14,7 +14,6 @@ import com.droiddeck.launcher.SessionActivity
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
import org.json.JSONObject
|
||||
|
||||
/** A visible, private process survives destruction of the app's native graphics context. */
|
||||
class SteamVrRestartActivity : Activity() {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
@@ -41,7 +40,6 @@ class SteamVrRestartActivity : Activity() {
|
||||
}, SystemClock::elapsedRealtime, SystemClock::sleep)
|
||||
if (shutdown != SteamVrRecoveryPolicy.Shutdown.COMPLETE)
|
||||
android.util.Log.w("SteamVrRecovery", "Restarting before the session finished stopping: $shutdown")
|
||||
// Only the verified main process, never a caller-supplied PID or an external app.
|
||||
Process.killProcess(main.pid)
|
||||
val exited = SystemClock.elapsedRealtime() + 5000
|
||||
while (java.io.File("/proc/${main.pid}").exists() && SystemClock.elapsedRealtime() < exited) SystemClock.sleep(50)
|
||||
|
||||
@@ -13,9 +13,6 @@ object TpUbwcHint {
|
||||
@Volatile var activeMode: String? = null
|
||||
private set
|
||||
|
||||
// On Adreno 740, TPL1_DBG_ECO_CNTL1.TP_UBWC_FLAG_HINT is shared by every driver on the GPU and must
|
||||
// match the system driver. A mismatch corrupts Android UI.
|
||||
// Samsung's One UI firmware sets it whatever blob version it reports.
|
||||
internal fun features(model: Int, systemDriverVersion: String?, samsung: Boolean = false,
|
||||
mode: String = SessionPrefs.TP_UBWC_AUTO): String? {
|
||||
if (model != 740) return null
|
||||
|
||||
@@ -8,7 +8,6 @@ import java.io.FileInputStream
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.channels.FileChannel
|
||||
|
||||
/** Hand-tracking models and the OpenCV/MediaPipe native libraries, downloaded on first use. */
|
||||
internal object TrackingPack {
|
||||
const val HAND = "hand_landmarker.task"
|
||||
const val HAND_LITE = "hand_landmarker_lite.task"
|
||||
@@ -32,10 +31,6 @@ internal object TrackingPack {
|
||||
fun model(context: Context, name: String): ByteBuffer =
|
||||
FileInputStream(file(context, name)).use { it.channel.map(FileChannel.MapMode.READ_ONLY, 0, it.channel.size()) }
|
||||
|
||||
/**
|
||||
* Loads OpenCV and MediaPipe from the pack. MediaPipe's own System.loadLibrary then resolves to the
|
||||
* already-loaded library by soname, so this must run before any MediaPipe task class initializes.
|
||||
*/
|
||||
fun loadNative(context: Context): Boolean {
|
||||
if (nativeLoaded) return true
|
||||
synchronized(lock) {
|
||||
@@ -50,7 +45,6 @@ internal object TrackingPack {
|
||||
}
|
||||
}
|
||||
|
||||
/** Blocks the calling worker thread until the pack is usable, starting the download if needed. */
|
||||
fun awaitNative(context: Context, running: () -> Boolean, onState: (AddonPack.State) -> Unit): Boolean =
|
||||
pack.await(context, running, onState) && loadNative(context)
|
||||
}
|
||||
@@ -3,12 +3,7 @@ package com.droiddeck.launcher.hud
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
|
||||
/** DroidDeck HUD's settings as one "key=value,…" string (DroidDeckHudView.applyConfig), stored in SessionPrefs. */
|
||||
internal object DroidDeckHudConfig {
|
||||
/**
|
||||
* Bannerlator's defaults (DeckOverlaySettings), with the FPS graph from the old DroidDeck HUD. The HUD starts
|
||||
* locked, so like the old HUD it lets touches through until it is unlocked to move it.
|
||||
*/
|
||||
val DEFAULTS: Map<String, String> = linkedMapOf(
|
||||
"hudSize" to "minimal", "hudLocked" to "1", "hudSnap" to "1", "hudScale" to "100", "hudDock" to "none", "hudOpacity" to "80", "hudColor" to "mid",
|
||||
"hudOutline" to "40", "hudOutlineAccent" to "1",
|
||||
@@ -20,7 +15,6 @@ internal object DroidDeckHudConfig {
|
||||
"tempUnit" to "c", "tempBands" to "1", "tempAuto" to "1", "tempRedCpu" to "90", "tempRedGpu" to "90", "tempRedBat" to "48",
|
||||
)
|
||||
|
||||
/** Switches Bannerlator sets together (DeckOverlaySettings twins). */
|
||||
private val TWINS = mapOf("showCPUUsage" to "showCPULoad", "showTemp" to "showBatteryTemp", "showEngine" to "showRenderer")
|
||||
|
||||
fun load(context: Context): MutableMap<String, String> {
|
||||
|
||||
@@ -19,10 +19,6 @@ import com.droiddeck.launcher.wayland.WaylandCompositor
|
||||
import java.io.File
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
/**
|
||||
* DroidDeck HUD on the session screen, in place of the old text HUD: the view, the frame feed from gamescope
|
||||
* (MangoHud's frame times) and MangoHud's readings, started with the session's first frame.
|
||||
*/
|
||||
class DroidDeckHudHost(context: Context) {
|
||||
private val context = context.applicationContext
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
@@ -36,8 +32,6 @@ class DroidDeckHudHost(context: Context) {
|
||||
private var polling = false
|
||||
private var wantX = Float.NaN
|
||||
private var wantY = Float.NaN
|
||||
// With snapping on, the side the HUD keeps to (0 = left, 1 = right), so it stays against that side when its
|
||||
// size changes. NaN = not snapped.
|
||||
private var anchorX = Float.NaN
|
||||
private var snaps = true
|
||||
private var snapping = false
|
||||
@@ -51,13 +45,10 @@ class DroidDeckHudHost(context: Context) {
|
||||
|
||||
var onPresentingWindowChanged: (() -> Unit)? = null
|
||||
|
||||
/** The frame rate the HUD shows; null while the HUD is off and not counting frames. */
|
||||
val liveFps: Float? get() = if (polling) feed.stats.fps else null
|
||||
|
||||
/** The HUD itself changed a setting: a tap cycles the size, a long press locks it. */
|
||||
var onConfigChanged: (() -> Unit)? = null
|
||||
|
||||
/** Screen point → whether an on-screen control takes a touch there; a locked HUD lets those through. */
|
||||
var passesTouchAt: ((rawX: Float, rawY: Float) -> Boolean)? = null
|
||||
|
||||
private val listener = object : WaylandCompositor.GameListener {
|
||||
@@ -86,7 +77,6 @@ class DroidDeckHudHost(context: Context) {
|
||||
get() = SessionPrefs.hudEnabled(context) &&
|
||||
!File(Environment.getExternalStorageDirectory(), "Download/droiddeck-no-hud").exists()
|
||||
|
||||
/** Adds the HUD to [root] at [index] (above the game surface, under the session overlay). */
|
||||
fun attach(root: FrameLayout, index: Int) {
|
||||
if (view != null) return
|
||||
val hud = DroidDeckHudView(root.context)
|
||||
@@ -171,13 +161,11 @@ class DroidDeckHudHost(context: Context) {
|
||||
view?.visibility = View.GONE
|
||||
}
|
||||
|
||||
/** Picture-in-picture and similar: keep running, draw nothing. */
|
||||
fun setHidden(hide: Boolean) {
|
||||
hidden = hide
|
||||
applyShown()
|
||||
}
|
||||
|
||||
/** The session screen is stopped (another app in front): draw nothing and stop reading sensors. */
|
||||
fun setBackgrounded(stopped: Boolean) {
|
||||
backgrounded = stopped
|
||||
applyShown()
|
||||
@@ -188,7 +176,6 @@ class DroidDeckHudHost(context: Context) {
|
||||
val show = !hidden && !backgrounded
|
||||
view?.visibility = if (show) View.VISIBLE else View.GONE
|
||||
showing = show
|
||||
// Frames are read once per display frame only while the HUD is drawn.
|
||||
if (show != polling) {
|
||||
polling = show
|
||||
if (show) Choreographer.getInstance().postFrameCallback(frameCallback)
|
||||
@@ -196,14 +183,11 @@ class DroidDeckHudHost(context: Context) {
|
||||
}
|
||||
}
|
||||
|
||||
/** A sensor report (DroidDeck HUD's diagnostics) in Downloads/DroidDeck; null when it can't be written. */
|
||||
fun exportDiagnostics(): File? = runCatching {
|
||||
val dir = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "DroidDeck")
|
||||
dir.mkdirs()
|
||||
val stamp = java.text.SimpleDateFormat("yyyyMMdd-HHmmss", java.util.Locale.US).format(java.util.Date())
|
||||
val file = File(dir, "HUD-diagnostics-$stamp.txt")
|
||||
// Its own reader: the HUD's CPU load is the change since its previous sample, which an export must
|
||||
// not move. Two samples half a second apart, MangoHud's sampling period.
|
||||
val metrics = HudMetrics(context)
|
||||
metrics.setMangoReadings(MangoReadings(File(context.filesDir, "session"), LinuxRuntime.rootDir(context)))
|
||||
metrics.snapshot()
|
||||
@@ -243,17 +227,14 @@ class DroidDeckHudHost(context: Context) {
|
||||
return if (stats.size > 3 && stats[3] > 1f) stats[3] else 0f
|
||||
}
|
||||
|
||||
/** The edge the HUD was dropped over, once a good part of it hangs past that edge; null when it stays. */
|
||||
private fun dockEdgeFor(v: View): DroidDeckHudDock? {
|
||||
val over = overhang(v) ?: return null
|
||||
return over.key.takeIf { over.value >= DOCK_OVERHANG }
|
||||
}
|
||||
|
||||
/** The edge the HUD hangs furthest past, with how much of it does, as a share of its own size. */
|
||||
private fun overhang(v: View): Map.Entry<DroidDeckHudDock, Float>? {
|
||||
val p = v.parent as? View ?: return null
|
||||
if (p.width <= 0 || p.height <= 0 || v.width <= 0 || v.height <= 0) return null
|
||||
// The Strip spans the screen and is short: measure its pull in a set distance rather than its own size.
|
||||
val strip = (v as? DroidDeckHudView)?.isStrip == true
|
||||
val density = v.resources.displayMetrics.density
|
||||
val w = if (strip) minOf(v.width.toFloat(), STRIP_PULL_ACROSS_DP * density) else v.width.toFloat()
|
||||
@@ -266,7 +247,6 @@ class DroidDeckHudHost(context: Context) {
|
||||
).maxByOrNull { it.value }
|
||||
}
|
||||
|
||||
/** The tab follows the finger along its edge and away from it, staying on screen. */
|
||||
private fun dragTab(hud: DroidDeckHudView, x: Float, y: Float) {
|
||||
val p = hud.parent as? View ?: return
|
||||
stopMotion(hud)
|
||||
@@ -275,7 +255,6 @@ class DroidDeckHudHost(context: Context) {
|
||||
hud.y = y.coerceIn(0f, (p.height - hud.height).toFloat().coerceAtLeast(0f))
|
||||
}
|
||||
|
||||
/** A tab pulled out by more than its own size comes out as the HUD there; a shorter pull slides it back onto its edge. */
|
||||
private fun dropTab(hud: DroidDeckHudView) {
|
||||
val p = hud.parent as? View ?: return
|
||||
val maxX = (p.width - hud.width).toFloat().coerceAtLeast(0f)
|
||||
@@ -298,13 +277,11 @@ class DroidDeckHudHost(context: Context) {
|
||||
.withEndAction { snapping = false }.start()
|
||||
}
|
||||
|
||||
/** Stops the HUD's running move, and the per-frame listener a dock animation hangs on it, which outlives a cancel. */
|
||||
private fun stopMotion(hud: DroidDeckHudView) {
|
||||
hud.animate().setUpdateListener(null)
|
||||
hud.animate().cancel()
|
||||
}
|
||||
|
||||
/** Glides the HUD from (fromX, fromY) to where it now is, back at full size. */
|
||||
private fun glideFrom(hud: DroidDeckHudView, fromX: Float, fromY: Float) {
|
||||
if (Motion.scale == 0f || (fromX == hud.x && fromY == hud.y && hud.scaleX == 1f && hud.scaleY == 1f)) {
|
||||
hud.scaleX = 1f; hud.scaleY = 1f
|
||||
@@ -317,7 +294,6 @@ class DroidDeckHudHost(context: Context) {
|
||||
.withEndAction { snapping = false; keepOnScreen(hud) }.start()
|
||||
}
|
||||
|
||||
/** A drop short of docking fades the tab preview back out. */
|
||||
private fun fadeDockPreview(hud: DroidDeckHudView) {
|
||||
val from = hud.dockPreviewBlend
|
||||
if (from <= 0f) return
|
||||
@@ -331,10 +307,6 @@ class DroidDeckHudHost(context: Context) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Dropped, the HUD glides to the nearer side of the screen at the height it was let go, as a picture-in-picture
|
||||
* window does, carried to the side a fling throws it toward.
|
||||
*/
|
||||
private fun snapToAnchor(hud: DroidDeckHudView, vx: Float) {
|
||||
val p = hud.parent as? View ?: return
|
||||
val maxX = (p.width - hud.width).toFloat().coerceAtLeast(0f)
|
||||
@@ -354,10 +326,6 @@ class DroidDeckHudHost(context: Context) {
|
||||
.withEndAction { snapping = false; keepOnScreen(hud) }.start()
|
||||
}
|
||||
|
||||
/**
|
||||
* Dragged past an edge, the HUD shrinks around the finger toward the tab it docks as, reaching the tab's
|
||||
* size where a drop would dock it, so the drop finishes a contraction the drag already started.
|
||||
*/
|
||||
private fun shrinkPastEdge(hud: DroidDeckHudView, rawX: Float, rawY: Float) {
|
||||
if (hud.dock != DroidDeckHudDock.NONE) return
|
||||
val p = hud.parent as? View ?: return
|
||||
@@ -372,7 +340,6 @@ class DroidDeckHudHost(context: Context) {
|
||||
hud.pivotX = rawX - at[0] - hud.x
|
||||
hud.pivotY = rawY - at[1] - hud.y
|
||||
if (hud.isStrip) {
|
||||
// The bar draws in sideways toward the tab's width; scaled evenly it would thin to a line.
|
||||
hud.scaleX = 1f + (tabW / hud.width - 1f) * e
|
||||
hud.scaleY = 1f
|
||||
return
|
||||
@@ -382,7 +349,6 @@ class DroidDeckHudHost(context: Context) {
|
||||
hud.scaleX = s; hud.scaleY = s
|
||||
}
|
||||
|
||||
/** Tucks the HUD against [edge] as its FPS tab, or with [DroidDeckHudDock.NONE] brings it back out from where it was docked. */
|
||||
private fun setDock(hud: DroidDeckHudView, edge: DroidDeckHudDock) {
|
||||
if (edge == hud.dock) return
|
||||
animateDock(hud, edge) { commitDock(hud, edge) }
|
||||
@@ -405,10 +371,6 @@ class DroidDeckHudHost(context: Context) {
|
||||
onConfigChanged?.invoke()
|
||||
}
|
||||
|
||||
/**
|
||||
* Where the HUD comes out of its tab, decided before it expands so it grows straight there: where the tab is
|
||||
* (against its edge, or wherever it was pulled to), and with snapping on, against the nearer side.
|
||||
*/
|
||||
private fun settleOutOfTab(hud: DroidDeckHudView, tabX: Float, tabY: Float) {
|
||||
val p = hud.parent as? View
|
||||
val maxX = if (p == null) Float.MAX_VALUE else (p.width - hud.contentWidth).coerceAtLeast(0f)
|
||||
@@ -419,11 +381,6 @@ class DroidDeckHudHost(context: Context) {
|
||||
SessionPrefs.setDroidDeckHudPosition(context, wantX, wantY)
|
||||
}
|
||||
|
||||
/**
|
||||
* One shape contracts into the tab, and the tab expands back out to the HUD: the view is scaled onto the
|
||||
* tab's exact rectangle, and the layouts swap at that same size and place. Timing and curve are the
|
||||
* launcher's own ([Motion]), and off when animations are off.
|
||||
*/
|
||||
private fun animateDock(hud: DroidDeckHudView, edge: DroidDeckHudDock, commit: () -> Unit) {
|
||||
stopMotion(hud)
|
||||
previewFade?.cancel(); previewFade = null
|
||||
@@ -436,7 +393,6 @@ class DroidDeckHudHost(context: Context) {
|
||||
commit(); return
|
||||
}
|
||||
if (edge != DroidDeckHudDock.NONE) {
|
||||
// Continue from what the drag left on screen: the shrunk HUD, and the tab where it is along the edge.
|
||||
val left = hud.x + hud.pivotX * (1f - hud.scaleX); val top = hud.y + hud.pivotY * (1f - hud.scaleY)
|
||||
val shownW = hud.width * hud.scaleX; val shownH = hud.height * hud.scaleY
|
||||
hud.pivotX = 0f; hud.pivotY = 0f
|
||||
@@ -480,11 +436,9 @@ class DroidDeckHudHost(context: Context) {
|
||||
}
|
||||
}
|
||||
|
||||
/** The pivot, in parent coordinates, that scaling by [scale] takes a span starting at [from] onto one starting at [to]. */
|
||||
private fun pivotFor(from: Float, to: Float, scale: Float): Float =
|
||||
if (scale > 0.999f) from else (to - from * scale) / (1f - scale)
|
||||
|
||||
/** Where a [w] x [h] HUD or tab sits once [keepOnScreen] has settled it against [dock]. */
|
||||
private fun settled(p: View, dock: DroidDeckHudDock, w: Float, h: Float): Pair<Float, Float> {
|
||||
val maxX = (p.width - w).coerceAtLeast(0f); val maxY = (p.height - h).coerceAtLeast(0f)
|
||||
var x = wantX.coerceIn(0f, maxX); var y = wantY.coerceIn(0f, maxY)
|
||||
@@ -498,9 +452,6 @@ class DroidDeckHudHost(context: Context) {
|
||||
return Pair(x, y)
|
||||
}
|
||||
|
||||
// The HUD is clamped from where the user left it (wantX/wantY, set on a drop or restore), not from where
|
||||
// it is drawn: a window that shrinks and grows back (picture-in-picture, a fold) must not leave it in the
|
||||
// corner the small window pushed it to.
|
||||
private fun keepOnScreen(v: View) {
|
||||
if (snapping) return
|
||||
val p = v.parent as? View ?: return
|
||||
@@ -528,27 +479,19 @@ class DroidDeckHudHost(context: Context) {
|
||||
}
|
||||
|
||||
companion object {
|
||||
/** How much of the HUD, as a share of its own size, must hang past a screen edge for it to dock there. */
|
||||
private const val DOCK_OVERHANG = 0.4f
|
||||
/** How far ahead a fling carries the HUD when picking the spot it snaps to, as seconds of its speed. */
|
||||
private const val FLING_REACH_S = 0.18f
|
||||
/** How far toward docking a drag goes, as a share of the way, before the tab starts to fade in over the HUD. */
|
||||
private const val PREVIEW_FROM = 0.55f
|
||||
/** How far the Strip is pulled sideways, or off its edge, for its overhang to count as its whole size. */
|
||||
private const val STRIP_PULL_ACROSS_DP = 600f
|
||||
private const val STRIP_PULL_OFF_DP = 150f
|
||||
/** The share of the expand animation over which the tab fades out to the HUD. */
|
||||
private const val EXPAND_FADE = 0.5f
|
||||
private val EASE = PathInterpolator(0.2f, 0.8f, 0.2f, 1f)
|
||||
|
||||
/** True while the HUD is on screen; DroidDeck keeps sampling VRAM for it (GpuMemComponent). */
|
||||
@Volatile @JvmStatic var showing = false
|
||||
private set
|
||||
|
||||
/** "Adreno (TM) 750" as the driver names it, "Adreno 750" as DroidDeck does elsewhere. */
|
||||
internal fun cleanGpuName(name: String): String = name.replace("(TM)", "").replace(Regex("\\s+"), " ").trim()
|
||||
|
||||
/** The Proton build of a game process: the first STEAM_COMPAT_TOOL_PATHS entry's folder. */
|
||||
internal fun protonName(pid: Int): String? = runCatching {
|
||||
val environ = File("/proc/$pid/environ").readBytes().toString(Charsets.UTF_8).split('\u0000')
|
||||
val paths = environ.firstOrNull { it.startsWith("STEAM_COMPAT_TOOL_PATHS=") }?.substringAfter('=') ?: return null
|
||||
|
||||
@@ -8,16 +8,11 @@
|
||||
* link to https://github.com/The412Banner/FusionHUD in the project documentation
|
||||
* AND in the in-app credits/about screen.
|
||||
*
|
||||
* Ported to DroidDeck from FusionHUD (Bannerlator's HUD); DroidDeck changes are marked in the code.
|
||||
* Ported to DroidDeck from FusionHUD (Bannerlator's HUD) and modified for DroidDeck.
|
||||
*/
|
||||
|
||||
package com.droiddeck.launcher.hud
|
||||
|
||||
/**
|
||||
* Size modes for the DroidDeck HUD (the 4th selectable in-game overlay style). One shared color-coded
|
||||
* visual language, four amounts of detail — see the approved mockup. The config value is the lower-case
|
||||
* token stored under the `hudSize` key; the label is the user-facing string.
|
||||
*/
|
||||
enum class DroidDeckHudSize(val token: String, val label: String) {
|
||||
FULL("full", "Full"),
|
||||
TILES("tiles", "Tiles"),
|
||||
@@ -26,18 +21,11 @@ enum class DroidDeckHudSize(val token: String, val label: String) {
|
||||
MEGA("mega", "Mega"),
|
||||
STRIP("strip", "Strip");
|
||||
|
||||
/** Next size in the tap-cycle: Full → Tiles → Pill → Minimal → Mega → Strip → Full. */
|
||||
fun next(): DroidDeckHudSize {
|
||||
val all = values()
|
||||
return all[(ordinal + 1) % all.size]
|
||||
}
|
||||
|
||||
/**
|
||||
* The metric toggle chips this size actually renders — the SINGLE source of truth queried by BOTH
|
||||
* config surfaces ({@code FpsCounterConfigDialog} + in-game {@code XServerDrawer} HudContent) so the
|
||||
* chip list can't drift from what the view draws. Chip ids are the chip LABELS used in the UI.
|
||||
* (Hiding a chip is purely UI; buildConfig() still emits every key — strip-invariant.)
|
||||
*/
|
||||
fun supportedChips(): Set<String> = when (this) {
|
||||
MINIMAL -> MINIMAL_CHIPS
|
||||
PILL -> PILL_CHIPS
|
||||
@@ -49,11 +37,6 @@ enum class DroidDeckHudSize(val token: String, val label: String) {
|
||||
fun from(token: String?): DroidDeckHudSize =
|
||||
values().firstOrNull { it.token.equals(token, ignoreCase = true) } ?: FULL
|
||||
|
||||
// Chip-label ids (must match the labels the config UIs build). "Clock" is a small subtle
|
||||
// corner readout available in EVERY size, so it's in all sets.
|
||||
// The API/engine label ("Engine" chip) shows on the FPS row in EVERY size, so it's in all sets.
|
||||
// "Wrapper" and "DX ver" are Mega-only: the wrapper appears solely below Mega's frametime graph,
|
||||
// and "DX ver" gates the DX-version suffix on Mega's FPS-row engine label.
|
||||
val MINIMAL_CHIPS = setOf("FPS", "FPS graph", "0.01% low", "FPS .1", "Engine", "Clock")
|
||||
val PILL_CHIPS = setOf("FPS", "FPS graph", "GPU", "CPU", "VRAM", "RAM", "Battery", "GPU model", "FPS .1", "Engine", "Clock")
|
||||
val STANDARD_CHIPS = setOf(
|
||||
@@ -67,7 +50,6 @@ enum class DroidDeckHudSize(val token: String, val label: String) {
|
||||
}
|
||||
}
|
||||
|
||||
/** The screen edge the HUD is tucked against, where only its FPS tab shows ([NONE] = floating free). */
|
||||
enum class DroidDeckHudDock(val token: String) {
|
||||
NONE("none"), LEFT("left"), RIGHT("right"), TOP("top"), BOTTOM("bottom");
|
||||
|
||||
@@ -76,21 +58,12 @@ enum class DroidDeckHudDock(val token: String) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The Wayland HDR state the DroidDeck HUD shows on its own line, directly under the latency · display-server
|
||||
* line (the host sets it with [DroidDeckHudView.setHdrState]). [NONE] = no line at all: every session whose
|
||||
* HDR gate is closed (X11, SDR screens, HDR off) keeps the HUD exactly as it was.
|
||||
*/
|
||||
object DroidDeckHudHdr {
|
||||
const val NONE = 0
|
||||
const val ON = 1 // HDR frames on screen with HDR headroom
|
||||
const val NO_HEADROOM = 2 // HDR frames on screen, but the display gives them no headroom (5 s+)
|
||||
const val OFF = 3 // the drawer's HDR output switch is off (tone-mapped to SDR)
|
||||
const val READY = 4 // HDR open for the session, no HDR frames on screen right now
|
||||
const val TONEMAPPED = 5 // HDR output on, but the frames are shown tone-mapped (frame generation
|
||||
// on a screen that offers no HDR10 swapchain)
|
||||
const val NOT_ON_THIS_SCREEN = 6 // HDR open for the session, but the screen the game is on NOW
|
||||
// reports no HDR10 (the TV was unplugged mid-game). The offer to the
|
||||
// game cannot be withdrawn once made, so the gate stays open for the
|
||||
// session — but "ready" would be a lie on a panel that cannot show it.
|
||||
const val ON = 1
|
||||
const val NO_HEADROOM = 2
|
||||
const val OFF = 3
|
||||
const val READY = 4
|
||||
const val TONEMAPPED = 5
|
||||
const val NOT_ON_THIS_SCREEN = 6
|
||||
}
|
||||
@@ -8,7 +8,7 @@
|
||||
* link to https://github.com/The412Banner/FusionHUD in the project documentation
|
||||
* AND in the in-app credits/about screen.
|
||||
*
|
||||
* Ported to DroidDeck from FusionHUD (Bannerlator's HUD); DroidDeck changes are marked in the code.
|
||||
* Ported to DroidDeck from FusionHUD (Bannerlator's HUD) and modified for DroidDeck.
|
||||
*/
|
||||
|
||||
package com.droiddeck.launcher.hud
|
||||
@@ -53,28 +53,12 @@ import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
|
||||
/**
|
||||
* DroidDeck HUD — the 4th selectable in-game overlay. One color-coded visual language rendered at four
|
||||
* SIZE modes (Full / Tiles / Pill / Minimal / Mega), all driven by [FrameStats] (gamescope's frame times
|
||||
* read by MangoHud's rules) + a single cached [HudMetrics.Snapshot]. Pure Canvas drawing.
|
||||
*
|
||||
* DroidDeck: the readouts refresh every 500 ms (MangoHud's sampling period) on a Main-dispatcher
|
||||
* coroutine, collecting the snapshot on Dispatchers.IO; the frame graph is redrawn whenever new frames
|
||||
* arrive ([onFrames]), as MangoHud draws it.
|
||||
*
|
||||
* Gestures go through [HudLockController]: long-press toggles the position lock (with a lock/unlock
|
||||
* badge fade), a tap cycles the size (Full→Tiles→Pill→Minimal→Full), and a drag repositions — tap +
|
||||
* drag are frozen while locked. A locked HUD lets a touch through where an on-screen control under it
|
||||
* takes it ([passesTouchAt]); everywhere else it keeps the touch, so a long press there unlocks it.
|
||||
*/
|
||||
class DroidDeckHudView(context: Context) : View(context) {
|
||||
|
||||
private var frames: FrameStats? = null
|
||||
internal fun setFrameStats(stats: FrameStats?) { frames = stats }
|
||||
internal fun setMangoReadings(readings: MangoReadings?) { metrics.setMangoReadings(readings) }
|
||||
|
||||
// Frames per second actually reaching the panel while DroidDeck's frame generation adds frames the
|
||||
// game never made; 0 = nothing is adding frames, and the readout is the game's rate alone.
|
||||
private var presentedFps = 0f
|
||||
fun setPresentedFps(fps: Float) { presentedFps = fps }
|
||||
|
||||
@@ -85,7 +69,6 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
|
||||
private val density = resources.displayMetrics.density
|
||||
|
||||
// ---- Config -----------------------------------------------------------
|
||||
private var size = DroidDeckHudSize.FULL
|
||||
private var scale = 1f
|
||||
private var bgOpacity = 0.8f
|
||||
@@ -109,8 +92,7 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
private var showGraph = false
|
||||
private var showLow001 = true
|
||||
private var fpsDecimal = true
|
||||
private var showClockTime = true // subtle corner/footer clock, available in EVERY size
|
||||
// Mega-only rows
|
||||
private var showClockTime = true
|
||||
private var showPerCore = true
|
||||
private var showSwap = true
|
||||
private var showNet = true
|
||||
@@ -121,21 +103,15 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
private var showSession = true
|
||||
|
||||
private var engineLabel = ""
|
||||
private var displayServer = "" // "X11" / "Wayland": which display server the game runs on
|
||||
private var hdrState = DroidDeckHudHdr.NONE // Wayland HDR, on its own line under latency · display server
|
||||
private var displayServer = ""
|
||||
private var hdrState = DroidDeckHudHdr.NONE
|
||||
private var gpuModel = ""
|
||||
// The GPU name a Wayland session reports to games instead of the real adapter ("" = none). It has
|
||||
// to travel separately from gpuModel: Wayland hands the spoof to DXVK and leaves the Vulkan device
|
||||
// alone, so everything the host reads back is still the real chip. On X11 the driver wrapper renames
|
||||
// the device itself, so there gpuModel already IS the spoofed name and this stays empty.
|
||||
private var gpuSpoofName = ""
|
||||
// Stack-layer version strings (Mega bottom band + DX version on the engine row); fed by the host.
|
||||
private var wineVersion = "" // "Proton 10.0-4"
|
||||
private var graphicsWrapper = "" // graphics-driver wrapper package, e.g. "GameNative", "bcn_layer 20260719"
|
||||
private var dxvkVersion = "" // DXVK version, appended to a DXVK engine row
|
||||
private var vkd3dVersion = "" // VKD3D version, appended to a VKD3D engine row
|
||||
private var wineVersion = ""
|
||||
private var graphicsWrapper = ""
|
||||
private var dxvkVersion = ""
|
||||
private var vkd3dVersion = ""
|
||||
|
||||
// ---- Live data (updated on the refresh coroutine, read on draw) --------
|
||||
private var snap: HudMetrics.Snapshot? = null
|
||||
private var fpsNow = 0f
|
||||
private var fpsAvg = 0f
|
||||
@@ -146,25 +122,17 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
private val graphPath = Path()
|
||||
private var resolution = ""
|
||||
|
||||
// DroidDeck look: the theme's main colour for the FPS label, graph and accent outline, the theme's
|
||||
// surface behind the readouts, a DroidDeck header (wordmark) on Full/Tiles/Minimal/Mega and the logo
|
||||
// chip on the Pill.
|
||||
private var accent = 0xFF1A9FFF.toInt()
|
||||
private var surfaceRgb = 0x121417
|
||||
private var headerMark: RectF? = null
|
||||
private var chipRect: RectF? = null
|
||||
|
||||
// Pushed past a screen edge, the HUD shrinks to a tab with the FPS that stays at that edge.
|
||||
var dock = DroidDeckHudDock.NONE
|
||||
private set
|
||||
private var tabRect: RectF? = null
|
||||
// The Strip is a bar across the whole screen, kept against the top or bottom edge.
|
||||
private var stripRect: RectF? = null
|
||||
private val tabPath = Path()
|
||||
|
||||
// Every size sits in the DroidDeck mark's D: a straight left side, round on the
|
||||
// right. Its fixed layers (fill, header band, watermark, glowing outline) go into a bitmap, because
|
||||
// Android before 9 skips glow on shapes drawn with hardware acceleration.
|
||||
private var dPanel: RectF? = null
|
||||
private var dRadius = 0f
|
||||
private var dDividerTop = -1f
|
||||
@@ -172,7 +140,6 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
private var dFrameKey = ""
|
||||
private val glowPaint = Paint(Paint.ANTI_ALIAS_FLAG)
|
||||
|
||||
// ---- Colors (mockup) --------------------------------------------------
|
||||
private val colGpu = 0xFF5EE08A.toInt()
|
||||
private val colCpu = 0xFF58A6FF.toInt()
|
||||
private val colVram = 0xFFC98BFF.toInt()
|
||||
@@ -183,10 +150,9 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
private val colValue = 0xFFF2F5F9.toInt()
|
||||
private val colDim = 0xFF9AA4B2.toInt()
|
||||
private val colLo = 0xFFE4E8EE.toInt()
|
||||
private val colDisp = 0xFF4DD0E1.toInt() // display server (X11 / Wayland)
|
||||
private val colHdr = 0xFFFFD54F.toInt() // HDR on screen
|
||||
private val colDisp = 0xFF4DD0E1.toInt()
|
||||
private val colHdr = 0xFFFFD54F.toInt()
|
||||
|
||||
// ---- Paints -----------------------------------------------------------
|
||||
private val measurePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
typeface = Typeface.create(Typeface.MONOSPACE, Typeface.BOLD)
|
||||
}
|
||||
@@ -205,16 +171,10 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
typeface = Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD)
|
||||
}
|
||||
|
||||
// ---- Built geometry ---------------------------------------------------
|
||||
private class Glyph(val x: Float, val baseline: Float, val text: String, val color: Int, val sizePx: Float, val sans: Boolean = false, val glow: Boolean = false) {
|
||||
fun moved(dx: Float, dy: Float) = Glyph(x + dx, baseline + dy, text, color, sizePx, sans, glow)
|
||||
}
|
||||
private class Span(val text: String, val color: Int, val sizePx: Float, val glow: Boolean = false)
|
||||
/**
|
||||
* A "label + value-run" row for the aligned grid sizes (Full / Mega). When [inline] is true the row
|
||||
* opts OUT of the shared label column — its value run is placed directly after the label — so a long
|
||||
* label (the graphics-wrapper on the FPS row) can't widen the column and shove every value right.
|
||||
*/
|
||||
private class HudRow(val label: Span, val vals: List<Span>, val inline: Boolean = false)
|
||||
private val glyphs = ArrayList<Glyph>()
|
||||
private val tileRects = ArrayList<RectF>()
|
||||
@@ -222,7 +182,6 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
private var contentW = 0f
|
||||
private var contentH = 0f
|
||||
|
||||
// ---- Listeners --------------------------------------------------------
|
||||
private var onMovedListener: BiConsumer<Float, Float>? = null
|
||||
private var onSizeCycledListener: Consumer<String>? = null
|
||||
private var onLockChangedListener: Consumer<Boolean>? = null
|
||||
@@ -232,13 +191,10 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
private var onDockChangedListener: Consumer<String>? = null
|
||||
private var onScaledListener: IntConsumer? = null
|
||||
private var onDraggedListener: BiConsumer<Float, Float>? = null
|
||||
/** The HUD moved under the finger, at that screen point. */
|
||||
fun setOnDraggedListener(l: BiConsumer<Float, Float>?) { onDraggedListener = l }
|
||||
private var onFlungListener: BiConsumer<Float, Float>? = null
|
||||
/** A drag ended in a fling, at this velocity (pixels per second), just before the move is reported. */
|
||||
fun setOnFlungListener(l: BiConsumer<Float, Float>?) { onFlungListener = l }
|
||||
fun setOnDockChangedListener(l: Consumer<String>?) { onDockChangedListener = l }
|
||||
/** A pinch settled on this size, in percent. */
|
||||
fun setOnScaledListener(l: IntConsumer?) { onScaledListener = l }
|
||||
|
||||
private val lockController = HudLockController(context, this, object : HudLockController.Callbacks {
|
||||
@@ -256,7 +212,6 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
override fun onPinchEnd() { onScaledListener?.accept((scale * 100f).roundToInt()) }
|
||||
})
|
||||
|
||||
// A docked tab always takes touches, locked or not: a tap brings the HUD back, a drag moves the tab.
|
||||
private val touchSlop = ViewConfiguration.get(context).scaledTouchSlop
|
||||
private var tabDownRawX = 0f
|
||||
private var tabDownRawY = 0f
|
||||
@@ -266,10 +221,8 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
private var onTabDraggedListener: BiConsumer<Float, Float>? = null
|
||||
private var onTabDroppedListener: Runnable? = null
|
||||
private var onTabDragCancelledListener: Runnable? = null
|
||||
/** The docked tab is dragged: where the finger would put it (x, y in the parent). */
|
||||
fun setOnTabDraggedListener(l: BiConsumer<Float, Float>?) { onTabDraggedListener = l }
|
||||
fun setOnTabDroppedListener(l: Runnable?) { onTabDroppedListener = l }
|
||||
/** The system took the tab's drag away: the tab goes back to where it was docked. */
|
||||
fun setOnTabDragCancelledListener(l: Runnable?) { onTabDragCancelledListener = l }
|
||||
|
||||
private fun onTabTouch(event: MotionEvent): Boolean {
|
||||
@@ -296,7 +249,6 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
return true
|
||||
}
|
||||
|
||||
// On the way into the tab or out of it, the tab fades in over the HUD at the tab's true size on screen.
|
||||
private var previewEdge = DroidDeckHudDock.NONE
|
||||
private var previewBlend = 0f
|
||||
internal fun setDockPreview(edge: DroidDeckHudDock, blend: Float) {
|
||||
@@ -307,32 +259,15 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
}
|
||||
internal val dockPreviewBlend: Float get() = previewBlend
|
||||
|
||||
// ---- Public surface (symmetric with the other overlays) ---------------
|
||||
fun setEngineLabel(s: String?) { if ((s ?: "") != engineLabel) { engineLabel = s ?: ""; post { rebuildAndInvalidate() } } }
|
||||
fun setGpuModel(s: String?) { if ((s ?: "") != gpuModel) { gpuModel = s ?: ""; post { rebuildAndInvalidate() } } }
|
||||
/** This session's Wayland GPU-name spoof (null / empty = none, the default): the GPU row names it
|
||||
* in place of the real model, marked so it can't be read as the chip that is really rendering. */
|
||||
fun setGpuSpoofName(s: String?) { gpuSpoofName = s ?: ""; post { rebuildAndInvalidate() } }
|
||||
fun setDisplayServer(s: String?) { displayServer = s ?: ""; post { rebuildAndInvalidate() } }
|
||||
/** [DroidDeckHudHdr] code; [DroidDeckHudHdr.NONE] (the default) draws no HDR line anywhere. Any thread. */
|
||||
fun setHdrState(state: Int) {
|
||||
val v = if (state in DroidDeckHudHdr.ON..DroidDeckHudHdr.NOT_ON_THIS_SCREEN) state else DroidDeckHudHdr.NONE
|
||||
post { if (v != hdrState) { hdrState = v; rebuildAndInvalidate() } }
|
||||
}
|
||||
fun setWineVersion(s: String?) { if ((s ?: "") != wineVersion) { wineVersion = s ?: ""; post { rebuildAndInvalidate() } } }
|
||||
fun setGraphicsWrapper(s: String?) { graphicsWrapper = s ?: ""; post { rebuildAndInvalidate() } }
|
||||
fun setDxWrapper(dxvk: String?, vkd3d: String?) {
|
||||
dxvkVersion = dxvk ?: ""; vkd3dVersion = vkd3d ?: ""; post { rebuildAndInvalidate() }
|
||||
}
|
||||
|
||||
/** The game's output from gamescope ("1280x720 @ 144Hz"), as MangoHud shows it; "" = this display. */
|
||||
fun setResolution(s: String?) { resolution = s ?: "" }
|
||||
|
||||
private val periodDone = Channel<Unit>(Channel.CONFLATED)
|
||||
private var seenFpsUpdates = 0L
|
||||
|
||||
/** New frames arrived: redraw the graph (MangoHud redraws it every frame), and the readouts when a
|
||||
* sampling period completed, at the moment MangoHud redraws its own. */
|
||||
fun onFrames() {
|
||||
val updates = frames?.fpsUpdates ?: 0L
|
||||
if (updates != seenFpsUpdates) {
|
||||
@@ -342,10 +277,6 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
if (graphRect != null) invalidate()
|
||||
}
|
||||
|
||||
/** The HUD has no orientation (tap cycles size instead); kept for a symmetric host surface. */
|
||||
fun setVertical(vertical: Boolean) { /* no-op */ }
|
||||
fun isVertical(): Boolean = false
|
||||
|
||||
private fun cycleSize() {
|
||||
size = size.next()
|
||||
onSizeCycledListener?.accept(size.token)
|
||||
@@ -372,7 +303,7 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
showGraph = cfg.get("showFPSGraph", "0") == "1"
|
||||
showLow001 = cfg.get("showLow001", "1") == "1"
|
||||
fpsDecimal = cfg.get("fpsDecimal", "1") == "1"
|
||||
showClockTime = cfg.get("showClock", "1") == "1" // the clock defaults ON
|
||||
showClockTime = cfg.get("showClock", "1") == "1"
|
||||
showPerCore = cfg.get("showPerCore", "1") == "1"
|
||||
showSwap = cfg.get("showSwap", "1") == "1"
|
||||
showNet = cfg.get("showNet", "1") == "1"
|
||||
@@ -397,7 +328,6 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
rebuildAndInvalidate()
|
||||
}
|
||||
|
||||
// ---- Lifecycle: self-refresh ------------------------------------------
|
||||
override fun onAttachedToWindow() {
|
||||
super.onAttachedToWindow()
|
||||
if (isShown) startUpdates()
|
||||
@@ -408,8 +338,6 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
super.onDetachedFromWindow()
|
||||
}
|
||||
|
||||
// The host hides the HUD with GONE (HUD off, picture-in-picture) and keeps it attached: read the
|
||||
// sensors only while it shows.
|
||||
override fun onVisibilityChanged(changedView: View, visibility: Int) {
|
||||
super.onVisibilityChanged(changedView, visibility)
|
||||
if (isAttachedToWindow && isShown) startUpdates() else stopUpdates()
|
||||
@@ -438,13 +366,11 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
graphMaxMs = stats?.graphMaxMs() ?: 0f
|
||||
onRefresh?.run()
|
||||
rebuildAndInvalidate()
|
||||
// Without frames (a still screen) MangoHud redraws nothing; the HUD keeps refreshing.
|
||||
withTimeoutOrNull(REFRESH_MS) { periodDone.receive() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Runs on the main thread just before each readout refresh, for the host's labels. */
|
||||
var onRefresh: Runnable? = null
|
||||
|
||||
private fun applyTheme() {
|
||||
@@ -459,10 +385,6 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
colGraph = lighten(accent, 0.3f)
|
||||
}
|
||||
|
||||
/**
|
||||
* Inner Gamer turns the colour wheel inside the app's Compose UI, which is not running while the drawer is
|
||||
* closed, so the HUD turns it here and shares the hue so the drawer picks up where the HUD is.
|
||||
*/
|
||||
private fun startHueCycle() {
|
||||
if (hueJob?.isActive == true) return
|
||||
if (SessionPrefs.theme(context) != Themes.INNER_GAMER) return
|
||||
@@ -504,7 +426,6 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
invalidate()
|
||||
}
|
||||
|
||||
// ---- Text helpers -----------------------------------------------------
|
||||
private fun blend(color: Int): Int {
|
||||
val i = colorIntensity.coerceIn(0f, 1f)
|
||||
if (i >= 0.999f) return color
|
||||
@@ -537,27 +458,19 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
private fun one(v: Float): String =
|
||||
if (fpsDecimal) String.format(Locale.US, "%.1f", v) else v.roundToInt().toString()
|
||||
|
||||
// Shows "30->118" while something downstream of the game is adding frames.
|
||||
// The game's own rate stays visible next to the panel rate, because the gap
|
||||
// between the two is precisely what frame generation is doing.
|
||||
private fun fpsText(v: Float): String =
|
||||
if (differs(v)) "${one(v)}\u2192${one(presentedFps)}" else one(v)
|
||||
|
||||
// Either direction: up = frames added (LSFG Native), down = frames lost
|
||||
// between the guest and the panel, which is the failure win-fg can hit
|
||||
// and which a single number hides completely.
|
||||
private fun differs(v: Float): Boolean =
|
||||
presentedFps > 0f && kotlin.math.abs(presentedFps - v) > maxOf(1f, v * 0.10f)
|
||||
|
||||
private fun fmt1(v: Float): String = String.format(Locale.US, "%.1f", v)
|
||||
private fun lowText(v: Float): String? = if (v <= 0f) null else fmt1(v)
|
||||
|
||||
// number (white, or "—" muted when null) + unit (muted, smaller)
|
||||
private fun numUnit(num: String?, unit: String, numPx: Float, unitPx: Float): List<Span> =
|
||||
if (num == null) listOf(Span("—", colDim, numPx), Span(unit, colDim, unitPx))
|
||||
else listOf(Span(num, colValue, numPx), Span(unit, colDim, unitPx))
|
||||
|
||||
// "0.2GiB"/"75%"/"1938MHz" → white number + muted suffix
|
||||
private fun valueUnit(text: String, numPx: Float, unitPx: Float): List<Span> {
|
||||
val i = text.indexOfFirst { !(it.isDigit() || it == '.' || it == '-') }
|
||||
return if (i <= 0) listOf(Span(text, colValue, numPx))
|
||||
@@ -566,7 +479,7 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
|
||||
private fun tempSpans(c: Int?, sensor: HudMetrics.TempSensor, numPx: Float, unitPx: Float): List<Span> {
|
||||
if (c == null) return emptyList()
|
||||
val txt = HudMetrics.formatTemp(c.toFloat(), tempDisplay, false) // "81°C"
|
||||
val txt = HudMetrics.formatTemp(c.toFloat(), tempDisplay, false)
|
||||
val col = HudMetrics.tempColor(
|
||||
c.toFloat(), metrics.resolveThresholds(sensor, tempDisplay), tempDisplay, colValue)
|
||||
val i = txt.indexOf('°')
|
||||
@@ -576,13 +489,9 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
|
||||
private fun gap(unitPx: Float) = Span(" ", colDim, unitPx)
|
||||
|
||||
/** The frame-rate number in neon, as on Minimal. */
|
||||
private fun glowing(spans: List<Span>): List<Span> =
|
||||
spans.mapIndexed { i, s -> if (i == 0) Span(s.text, s.color, s.sizePx, glow = true) else s }
|
||||
|
||||
// ---- Wayland HDR state (one line of its own; nothing at all for DroidDeckHudHdr.NONE) ----
|
||||
/** The state as a full line: "HDR", "HDR (no headroom)", "HDR off", "HDR ready", "HDR tone-mapped",
|
||||
* "HDR not on this screen". */
|
||||
private fun hdrLine(px: Float): List<Span> = when (hdrState) {
|
||||
DroidDeckHudHdr.ON -> listOf(Span("HDR", colHdr, px))
|
||||
DroidDeckHudHdr.NO_HEADROOM -> listOf(Span("HDR", colHdr, px), Span(" (no headroom)", colBat, px))
|
||||
@@ -592,8 +501,6 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
DroidDeckHudHdr.NOT_ON_THIS_SCREEN -> listOf(Span("HDR", colDim, px), Span(" not on this screen", colBat, px))
|
||||
else -> emptyList()
|
||||
}
|
||||
/** The value after an "HDR" label (Full / Mega): "on", "no headroom", "off", "ready", "tone-mapped",
|
||||
* "not on this screen". */
|
||||
private fun hdrValue(px: Float): List<Span> = when (hdrState) {
|
||||
DroidDeckHudHdr.ON -> listOf(Span("on", colHdr, px))
|
||||
DroidDeckHudHdr.NO_HEADROOM -> listOf(Span("no headroom", colBat, px))
|
||||
@@ -605,12 +512,7 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
}
|
||||
private fun hdrText(): String = hdrLine(1f).joinToString("") { it.text }
|
||||
|
||||
// ---- GPU model (with the Wayland GPU-name spoof) ----
|
||||
/** What the GPU row names: the spoofed GPU when this session reports one, else the real model. */
|
||||
private fun gpuNameText(): String = gpuSpoofName.ifBlank { gpuModel }
|
||||
/** The GPU row's value run. A spoofed name carries a marker in the same warning colour the HDR line
|
||||
* qualifies its state with, so the row can't be read as the chip that is really rendering:
|
||||
* "GeForce GTX 1080 (spoof)", and where the line is tightest (the pill) "GeForce GTX 1080 spoof". */
|
||||
private fun gpuModelSpans(px: Float, color: Int, compact: Boolean = false): List<Span> {
|
||||
val name = Span(gpuNameText(), color, px)
|
||||
if (gpuSpoofName.isBlank()) return listOf(name)
|
||||
@@ -619,7 +521,6 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
|
||||
private val inkRect = android.graphics.Rect()
|
||||
|
||||
// ---- Layout builders --------------------------------------------------
|
||||
private fun rebuild() {
|
||||
glyphs.clear(); tileRects.clear(); graphRect = null
|
||||
headerMark = null; chipRect = null; dPanel = null; dDividerTop = -1f; tabRect = null; stripRect = null
|
||||
@@ -636,7 +537,6 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
}
|
||||
}
|
||||
|
||||
/** The docked tab: the FPS alone, in a box square on the edge it sits against. */
|
||||
private fun buildDockTab() {
|
||||
val numPx = sp(20f)
|
||||
val spans = tabSpans()
|
||||
@@ -649,7 +549,6 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
|
||||
private fun tabSpans() = listOf(Span(one(fpsNow), colValue, sp(20f)), Span("fps", colDim, sp(8.5f)))
|
||||
|
||||
/** The size the docked tab has, so the HUD can contract to exactly that shape before the tab replaces it. */
|
||||
internal fun dockTabSize(): Pair<Float, Float> =
|
||||
Pair(runWidth(tabSpans()) + 2f * sp(9f), capHeight(sp(20f)) + 2f * sp(7f))
|
||||
|
||||
@@ -675,18 +574,14 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
canvas.drawPath(tabPath, strokePaint)
|
||||
}
|
||||
|
||||
// ---- DroidDeck panel, header and chip -----------------------------------
|
||||
/** The clock sits in the header on every size but the Pill, which keeps it under the FPS. */
|
||||
private fun footerClock(): Boolean = showClockTime && size == DroidDeckHudSize.PILL
|
||||
|
||||
private fun measureSans(text: String, sizePx: Float): Float { wordmarkPaint.textSize = sizePx; return wordmarkPaint.measureText(text) }
|
||||
|
||||
private fun panelInset() = sp(8f) // room for the glow around the panel
|
||||
private fun panelLeft() = sp(13f) // the outline's glow sticks out of the left side
|
||||
private fun panelInset() = sp(8f)
|
||||
private fun panelLeft() = sp(13f)
|
||||
private fun contentLeft() = panelLeft() + sp(16f)
|
||||
|
||||
/** The DroidDeck mark, "DroidDeck" and the clock across the top, starting on [left], with the same
|
||||
* space above and below the mark. Returns the header's bottom edge and its right end. */
|
||||
private fun addPanelHeader(left: Float, inner: Float): Pair<Float, Float> {
|
||||
val wordPx = sp(10f); val clockPx = sp(9.5f); val gapH = sp(7f)
|
||||
wordmarkPaint.textSize = wordPx
|
||||
@@ -714,11 +609,6 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
return Pair(dDividerTop + max(1f, density), x)
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves a size's content, laid out from [pad] at the origin, into the panel: under the header, or after
|
||||
* the logo chip on the Pill. Lines that start on the content's left edge are lined up by their ink, so
|
||||
* the logo, labels and numbers share one edge.
|
||||
*/
|
||||
private fun intoPanel(pad: Float, header: Boolean) {
|
||||
if (contentW <= 0f || contentH <= 0f) return
|
||||
for (i in glyphs.indices) {
|
||||
@@ -748,8 +638,6 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
finishPanel(panel, halfRound = !header)
|
||||
}
|
||||
|
||||
/** Closes the panel around everything placed so far, widened until no line, tile or graph reaches the
|
||||
* round side: a half circle on the short sizes (Pill, Minimal), large round corners on the tall ones. */
|
||||
private fun finishPanel(panel: RectF, halfRound: Boolean) {
|
||||
val r = if (halfRound) panel.height() / 2f else min(panel.height() / 2f, sp(56f))
|
||||
val margin = outlineWidth() + sp(4f)
|
||||
@@ -773,7 +661,6 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
contentH = panel.bottom + panelInset()
|
||||
}
|
||||
|
||||
// ---- Shared small-info helpers ----------------------------------------
|
||||
private fun clockTimeString(): String = DateFormat.getTimeFormat(context).format(Date())
|
||||
|
||||
private fun elapsedString(): String {
|
||||
@@ -783,31 +670,21 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
else String.format(Locale.US, "%02d:%02d", m, s)
|
||||
}
|
||||
|
||||
/**
|
||||
* The FPS row's API/engine label — the DX→Vulkan translator ([engineLabel]: "DXVK"/"VKD3D"/"Zink"),
|
||||
* gated by the "Engine" chip. This is short and shows in EVERY size. Falls back to a bare "FPS" when
|
||||
* the toggle is off or no engine label is set. (The graphics WRAPPER is separate — Mega-only, drawn
|
||||
* below the frametime graph — not on the FPS row.)
|
||||
*/
|
||||
private fun apiLabel(): String =
|
||||
if (showEngine && engineLabel.isNotBlank()) engineLabel else "FPS"
|
||||
|
||||
/** The DX-wrapper version WITH its engine name (e.g. "DXVK 2.4.1", "VKD3D 2.14"), or "" if none.
|
||||
* Used for the Mega stack line below the graph. */
|
||||
private fun dxVersionLabeled(): String = when {
|
||||
engineLabel.contains("VKD3D", true) && vkd3dVersion.isNotBlank() -> "VKD3D $vkd3dVersion"
|
||||
engineLabel.contains("DXVK", true) && dxvkVersion.isNotBlank() -> "DXVK $dxvkVersion"
|
||||
else -> ""
|
||||
}
|
||||
|
||||
/** The DX-wrapper version for the current engine, or "" (used for the Tiles "API" tile sub-line). */
|
||||
private fun dxVersion(): String = when {
|
||||
engineLabel.contains("VKD3D", true) -> vkd3dVersion
|
||||
engineLabel.contains("DXVK", true) -> dxvkVersion
|
||||
else -> ""
|
||||
}
|
||||
|
||||
/** Resolution + refresh, e.g. "1280x720 @ 120Hz". Read from the current display (Main thread). */
|
||||
private fun resolutionString(): String {
|
||||
if (resolution.isNotBlank()) return resolution
|
||||
val dm = resources.displayMetrics
|
||||
@@ -816,15 +693,13 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
return if (hz >= 1f) "$base @ ${hz.roundToInt()}Hz" else base
|
||||
}
|
||||
|
||||
/** A subtle, low-emphasis time-of-day tucked into the bottom-right of any size. Grows contentH slightly. */
|
||||
private fun addSubtleClock(pad: Float, leftAligned: Boolean = false) {
|
||||
if (!footerClock()) return
|
||||
val px = sp(9.5f)
|
||||
val t = clockTimeString()
|
||||
val w = measure(t, px)
|
||||
val footerTop = contentH - pad // reuse the bottom padding band as the footer line
|
||||
val footerTop = contentH - pad
|
||||
val baseline = footerTop - ascent(px)
|
||||
// Right-aligned footer; on the Pill it sits on the left edge, under the FPS.
|
||||
val x = if (leftAligned) pad else (contentW - pad - w).coerceAtLeast(pad)
|
||||
glyphs.add(Glyph(x, baseline, t, blend(colDim), px))
|
||||
contentH = footerTop + lineH(px) + pad * 0.5f
|
||||
@@ -878,7 +753,6 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
val v = ArrayList<Span>()
|
||||
v += glowing(numUnit(fpsText(fpsNow), "FPS", rowPx, unitPx))
|
||||
v += gap(unitPx); v += numUnit(fmt1(1000f / max(fpsNow, 1f)), "ms", rowPx, unitPx)
|
||||
// Short API/engine label ("DXVK"/"VKD3D"/"Zink", else "FPS") — a normal aligned row.
|
||||
rows.add(HudRow(Span(apiLabel(), colFps, rowPx), v))
|
||||
rows.add(HudRow(Span("AVG", colLo, rowPx), numUnit(fmt1(fpsAvg), "FPS", rowPx, unitPx)))
|
||||
rows.add(HudRow(Span("1%", colLo, rowPx), numUnit(lowText(lows.low1Fps), "FPS", rowPx, unitPx)))
|
||||
@@ -902,9 +776,6 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
}
|
||||
|
||||
if (showFPS && showGraph) {
|
||||
// Frametime min/max line + green graph. "Frametime" is far wider than the short-label grid
|
||||
// column, so place the stat AFTER the ACTUAL label width (not labelCol) — otherwise the two
|
||||
// overlap and render as "Frametimemin:.. max:..".
|
||||
val ftPx = unitPx * 1.15f
|
||||
val baseline = y - asc
|
||||
placeRun(pad, baseline, listOf(Span("Frametime", colFps, ftPx)))
|
||||
@@ -945,8 +816,6 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
if (showVram && s.vramText() != null) tiles.add(Tile("VRAM", colVram, valueUnit(s.vramText()!!, valPx, unitPx), null, false))
|
||||
if (showRAM) tiles.add(Tile("RAM", colRam, numUnit(s.ramPercent.roundToInt().toString(), "%", valPx, unitPx),
|
||||
"${s.ramUsedText()} / ${s.ramTotalText()}", false))
|
||||
// API/engine tile — short translator name (DXVK/VKD3D/Zink) with the DX version on the sub-line;
|
||||
// a normal half-width tile that naturally fills the empty slot beside RAM. Gated by "Engine".
|
||||
if (showEngine && engineLabel.isNotBlank())
|
||||
tiles.add(Tile("API", colFps, listOf(Span(engineLabel, colValue, valPx)),
|
||||
dxVersion().ifBlank { null }, false))
|
||||
@@ -970,7 +839,7 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
var normalW = 0f
|
||||
for (t in tiles) if (!t.wide) normalW = max(normalW, tileW(t))
|
||||
if (normalW == 0f) for (t in tiles) normalW = max(normalW, tileW(t) / 2f)
|
||||
val tileH = innerPad * 2 + keyH + lineGap + valH + lineGap + subH // uniform (room for a sub line)
|
||||
val tileH = innerPad * 2 + keyH + lineGap + valH + lineGap + subH
|
||||
val fullW = normalW * 2 + tileGap
|
||||
|
||||
var x = pad; var y = pad; var col = 0
|
||||
@@ -1011,20 +880,12 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
val pad = sp(10f); val midGap = sp(12f); val stkLineGap = sp(3f)
|
||||
|
||||
val left = ArrayList<Span>()
|
||||
// "30->118" is roughly three times the width of "30", and the pill's
|
||||
// number is set at 30sp precisely because it is the one big thing on a
|
||||
// small overlay. Shrink it while it carries both figures so the pill
|
||||
// does not balloon across the screen; it is still the largest element.
|
||||
val generating = differs(fpsNow)
|
||||
val fpsPx = if (generating) bigPx * 0.55f else bigPx
|
||||
left += Span(fpsText(fpsNow), colValue, fpsPx, glow = true)
|
||||
left += Span("fps", colDim, if (generating) bigUnitPx * 0.8f else bigUnitPx)
|
||||
|
||||
val stack = ArrayList<List<Span>>()
|
||||
// The GPU name normally heads the stack. A name wider than every stat under it (a Wayland spoof
|
||||
// such as "Radeon RX 6800/6800 XT / 6900 XT spoof") would set the stack's width and stretch the
|
||||
// whole capsule around empty space, so that name gets its own line across the top of the pill
|
||||
// instead, starting over the API caption (see nameOnTop below).
|
||||
val gpuName = if (showGpuModel && gpuNameText().isNotBlank()) gpuModelSpans(stkPx, colDim, compact = true) else null
|
||||
run {
|
||||
val l = ArrayList<Span>()
|
||||
@@ -1032,11 +893,7 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
if (showCPU) { if (l.isNotEmpty()) l += Span(" · ", colDim, stkPx); l += Span("CPU ${s.cpuPercent ?: "—"}%", colCpu, stkPx) }
|
||||
if (l.isNotEmpty()) stack.add(l)
|
||||
}
|
||||
// RAM % (system-wide) takes the slot the latency row used to occupy, matching the GPU/CPU idiom
|
||||
// on the row above it. colRam keeps RAM's identity colour consistent with the Full/Tiles sizes.
|
||||
if (showRAM) stack.add(listOf(Span("RAM ${s.ramPercent.roundToInt()}%", colRam, stkPx)))
|
||||
// One battery row, as on the other sizes: each part shows on its own switch, so the battery
|
||||
// temperature no longer goes with the RAM switch and watts show without the battery level.
|
||||
if (showBattery || showPower || showBatteryTemp) {
|
||||
val l = ArrayList<Span>()
|
||||
fun part(spans: List<Span>) {
|
||||
@@ -1049,9 +906,6 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
if (showPower && s.battery.watts > 0f) part(listOf(Span("${fmt1(s.battery.watts)}W", colDim, stkPx)))
|
||||
if (l.isNotEmpty()) stack.add(l)
|
||||
}
|
||||
// Latency (+ the display server, + optional VRAM) drops to the bottom of the stack, under the
|
||||
// battery row. The display server sits here, not on the GPU-model line: that line is the
|
||||
// pill's widest and ran into the capsule's rounded edge.
|
||||
run {
|
||||
val l = ArrayList<Span>()
|
||||
l += Span("${fmt1(1000f / max(fpsNow, 1f))}ms", colDim, stkPx)
|
||||
@@ -1059,8 +913,6 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
if (showVram && s.vramText() != null) { l += Span(" · ", colDim, stkPx); l += Span("${s.vramText()} vram", colDim, stkPx) }
|
||||
stack.add(l)
|
||||
}
|
||||
// Wayland HDR state on its OWN line directly under the latency · display-server line (it ran off
|
||||
// the capsule's right edge as "40.3ms · Wayland · HDR (no headroom)"). Only in HDR sessions.
|
||||
if (hdrState != DroidDeckHudHdr.NONE) stack.add(hdrLine(stkPx))
|
||||
|
||||
var statsW = 0f
|
||||
@@ -1068,8 +920,6 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
val nameOnTop = gpuName != null && runWidth(gpuName) > statsW
|
||||
if (gpuName != null && !nameOnTop) stack.add(0, gpuName)
|
||||
|
||||
// Left column: a small API/engine caption (DXVK/VKD3D/Zink) above the big FPS and the clock below
|
||||
// it, all on the left edge, so the left reads API · FPS · clock top-to-bottom.
|
||||
val apiStr = apiLabel()
|
||||
val hasApi = apiStr != "FPS"
|
||||
val apiH = if (hasApi) lineH(stkPx) else 0f
|
||||
@@ -1088,14 +938,12 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
contentW = pad + leftBlockW + midGap + stackW + pad
|
||||
contentH = pad + topLineH + innerH + pad
|
||||
|
||||
// left column (API caption + big FPS), vertically centered as a block
|
||||
var ly = pad + topLineH + (innerH - leftColH) / 2f
|
||||
if (hasApi) {
|
||||
placeRun(pad, ly - ascent(stkPx), listOf(Span(apiStr, colFps, stkPx)))
|
||||
ly += apiH + apiGap
|
||||
}
|
||||
placeRun(pad, ly - ascent(bigPx), left)
|
||||
// stack, vertically centered
|
||||
var sy = pad + topLineH + (innerH - stackTotalH) / 2f
|
||||
for (l in stack) {
|
||||
placeRun(pad + leftBlockW + midGap, sy - ascent(stkPx), l)
|
||||
@@ -1103,22 +951,17 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
}
|
||||
addSubtleClock(pad, leftAligned = true)
|
||||
if (nameOnTop && gpuName != null) {
|
||||
// Left-aligned over the API caption; the pill only widens if the name is wider than the
|
||||
// API/FPS column + stats.
|
||||
val end = placeRun(pad, pad - ascent(stkPx), gpuName)
|
||||
contentW = max(contentW, end + pad)
|
||||
}
|
||||
}
|
||||
|
||||
// One column as wide as the widest row: the logo, FPS, lows, graph and engine line start on its left
|
||||
// edge (ink, not advance), and the header keeps the same space above and below the logo.
|
||||
private fun buildMinimal(s: HudMetrics.Snapshot) {
|
||||
val bigPx = sp(34f); val bigUnitPx = bigPx * 0.32f; val subPx = sp(11.5f); val footPx = sp(9.5f)
|
||||
val stroke = outlineWidth()
|
||||
val left = contentLeft()
|
||||
val inner = panelInset() + stroke
|
||||
|
||||
// Same reasoning as the pill: 34sp is sized for one number, not two.
|
||||
val minGenerating = differs(fpsNow)
|
||||
val big = listOf(
|
||||
Span(fpsText(fpsNow), colValue, if (minGenerating) bigPx * 0.55f else bigPx),
|
||||
@@ -1164,11 +1007,6 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
finishPanel(panel, halfRound = true)
|
||||
}
|
||||
|
||||
/**
|
||||
* Full's readouts on one line across the screen: the mark, the FPS, the graph, the lows, then GPU, CPU,
|
||||
* memory, battery, display server and GPU model, with the clock on the right end. Groups that no longer
|
||||
* fit before the clock are left off, from the end.
|
||||
*/
|
||||
private fun buildStrip(s: HudMetrics.Snapshot) {
|
||||
val rowPx = sp(11.5f); val unitPx = rowPx * 0.8f; val fpsPx = sp(15f)
|
||||
val padX = sp(10f); val groupGap = sp(13f)
|
||||
@@ -1265,8 +1103,6 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
return inkRect.left.toFloat()
|
||||
}
|
||||
|
||||
/** Places a column of "label + value" rows; returns (bottomY, rightX). Appends glyphs. Rows flagged
|
||||
* [HudRow.inline] opt out of the shared label column (value follows the label directly). */
|
||||
private fun layoutColumn(rows: List<HudRow>, x: Float, y0: Float,
|
||||
rowPx: Float, lineGap: Float, lvGap: Float): Pair<Float, Float> {
|
||||
if (rows.isEmpty()) return Pair(y0, x)
|
||||
@@ -1286,7 +1122,6 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
return Pair(y - lineGap, right)
|
||||
}
|
||||
|
||||
/** Places wrapping " · "-separated info fragments within maxWidth; returns (bottomY, rightX). */
|
||||
private fun layoutWrap(fragments: List<List<Span>>, x: Float, y0: Float, maxWidth: Float,
|
||||
px: Float, lineGap: Float): Pair<Float, Float> {
|
||||
if (fragments.isEmpty()) return Pair(y0, x)
|
||||
@@ -1307,7 +1142,6 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
val rowPx = sp(11.5f); val unitPx = rowPx * 0.62f; val bandPx = sp(9.5f)
|
||||
val pad = sp(10f); val lineGap = sp(3.5f); val lvGap = sp(7f); val gutter = sp(16f)
|
||||
|
||||
// ---- LEFT column: GPU, aggregate CPU, then per-core rows ----
|
||||
val left = ArrayList<HudRow>()
|
||||
if (showGpuModel && gpuNameText().isNotBlank())
|
||||
left.add(HudRow(Span("GPU", colGpu, rowPx), gpuModelSpans(rowPx, colValue)))
|
||||
@@ -1339,7 +1173,6 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
}
|
||||
}
|
||||
|
||||
// ---- RIGHT column: VRAM, RAM, SWP, NET, BAT, engine, lows ----
|
||||
val right = ArrayList<HudRow>()
|
||||
if (showVram && s.vramText() != null)
|
||||
right.add(HudRow(Span("VRAM", colVram, rowPx), valueUnit(s.vramText()!!, rowPx, unitPx)))
|
||||
@@ -1377,8 +1210,6 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
val v = ArrayList<Span>()
|
||||
v += glowing(numUnit(fpsText(fpsNow), "FPS", rowPx, unitPx))
|
||||
v += gap(unitPx); v += numUnit(fmt1(1000f / max(fpsNow, 1f)), "ms", rowPx, unitPx)
|
||||
// FPS/engine row: just the short API label. The DX version moved to the stack lines
|
||||
// below the frametime graph (see below), so this row stays compact.
|
||||
right.add(HudRow(Span(apiLabel(), colFps, rowPx), v))
|
||||
right.add(HudRow(Span("AVG", colLo, rowPx), numUnit(fmt1(fpsAvg), "FPS", rowPx, unitPx)))
|
||||
right.add(HudRow(Span("1%", colLo, rowPx), numUnit(lowText(lows.low1Fps), "FPS", rowPx, unitPx)))
|
||||
@@ -1387,15 +1218,12 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
right.add(HudRow(Span("0.01%", colLo, rowPx), numUnit(lowText(lows.low001Fps), "FPS", rowPx, unitPx)))
|
||||
}
|
||||
|
||||
// ---- Two columns side by side (each reflows independently) ----
|
||||
val (leftBottom, leftRight) = layoutColumn(left, pad, pad, rowPx, lineGap, lvGap)
|
||||
val rightX = (if (left.isEmpty()) pad else leftRight + gutter)
|
||||
val (rightBottom, rightRight) = layoutColumn(right, rightX, pad, rowPx, lineGap, lvGap)
|
||||
var y = max(leftBottom, rightBottom)
|
||||
var maxRight = max(leftRight, rightRight)
|
||||
|
||||
// ---- Bottom band spanning both columns: res · Proton · elapsed ----
|
||||
// (The graphics wrapper moved to the FPS-row label above, so it's no longer in this band.)
|
||||
val band = ArrayList<List<Span>>()
|
||||
if (showResolution) band.add(listOf(Span("RES ", colDim, bandPx), Span(resolutionString(), colValue, bandPx)))
|
||||
if (displayServer.isNotBlank()) band.add(listOf(Span("DISP ", colDim, bandPx), Span(displayServer, colDisp, bandPx)))
|
||||
@@ -1408,7 +1236,6 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
y = bBottom; maxRight = max(maxRight, bRight)
|
||||
}
|
||||
|
||||
// ---- Full-width frametime graph ----
|
||||
if (showGraph) {
|
||||
y += sp(3f)
|
||||
val gh = sp(22f)
|
||||
@@ -1418,9 +1245,6 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
y += gh
|
||||
}
|
||||
|
||||
// ---- Stack-layer lines BELOW the frametime graph, subtle (same size/style as the bottom
|
||||
// band): the DX-wrapper version first (e.g. "DXVK 2.4.1-…", gated by "DX ver"), then the
|
||||
// graphics wrapper beneath it (e.g. "Original", gated by "Wrapper"). ----
|
||||
val dxLine = dxVersionLabeled()
|
||||
val hasDx = showDxVer && dxLine.isNotBlank()
|
||||
if (hasDx) {
|
||||
@@ -1436,12 +1260,10 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
|
||||
contentW = maxRight + pad
|
||||
contentH = y + pad
|
||||
addSubtleClock(pad) // subtle time-of-day, consistent with the other sizes
|
||||
addSubtleClock(pad)
|
||||
}
|
||||
|
||||
// ---- Measure / draw ---------------------------------------------------
|
||||
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
|
||||
// The Strip spans the parent, past the side margin the floating sizes keep.
|
||||
if (stripRect != null) { setMeasuredDimension(contentW.roundToInt(), resolveSize(contentH.roundToInt(), heightMeasureSpec)); return }
|
||||
setMeasuredDimension(
|
||||
resolveSize(contentW.roundToInt(), widthMeasureSpec),
|
||||
@@ -1461,7 +1283,6 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
drawTabPreview(canvas, blend)
|
||||
}
|
||||
|
||||
/** The docked tab drawn at its own size in the middle of the view, undoing the view's scale. */
|
||||
private fun drawTabPreview(canvas: Canvas, blend: Float) {
|
||||
val (w, h) = dockTabSize()
|
||||
if (scaleX <= 0f || scaleY <= 0f) return
|
||||
@@ -1487,7 +1308,6 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
|
||||
dPanel?.let { panel -> panelFrame(panel)?.let { canvas.drawBitmap(it, 0f, 0f, null) } }
|
||||
|
||||
// Tile backings
|
||||
if (tileRects.isNotEmpty()) {
|
||||
tilePaint.color = Color.argb((14 * bgOpacity).roundToInt().coerceIn(8, 40), 255, 255, 255)
|
||||
val tr = sp(6f)
|
||||
@@ -1498,7 +1318,6 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
tabRect?.let { drawTab(canvas, it) }
|
||||
stripRect?.let { drawStrip(canvas, it) }
|
||||
|
||||
// Text
|
||||
for (g in glyphs) {
|
||||
val paint = if (g.sans) wordmarkPaint else drawPaint
|
||||
paint.textSize = g.sizePx
|
||||
@@ -1509,14 +1328,11 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
}
|
||||
headerMark?.let { DroidDeckMark.draw(canvas, it.left, it.top, it.height(), blend(colValue), accent) }
|
||||
|
||||
// Frametime graph
|
||||
graphRect?.let { drawGraph(canvas, it) }
|
||||
|
||||
lockController.drawBadge(canvas)
|
||||
}
|
||||
|
||||
// MangoHud's frametime graph: the last 200 frames on a fixed 0-50 ms scale, longer frames clipped
|
||||
// to 49.9 ms (hud_elements.cpp TransformForward_Custom).
|
||||
private fun drawGraph(canvas: Canvas, rect: RectF) {
|
||||
val stats = frames ?: return
|
||||
stats.graph(graphBuf)
|
||||
@@ -1528,7 +1344,6 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
if (i == 0) graphPath.moveTo(px, py) else graphPath.lineTo(px, py)
|
||||
}
|
||||
if (dPanel != null) {
|
||||
// Neon without a blur: a blur would be redrawn with every frame.
|
||||
graphPaint.strokeWidth = sp(4.5f)
|
||||
graphPaint.color = withAlpha(blend(colGraph), 56)
|
||||
canvas.drawPath(graphPath, graphPaint)
|
||||
@@ -1538,7 +1353,6 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
canvas.drawPath(graphPath, graphPaint)
|
||||
}
|
||||
|
||||
/** The bar, with the accent line on the side that faces the game (under it at the top, over it at the bottom). */
|
||||
private fun drawStrip(canvas: Canvas, rect: RectF) {
|
||||
headerPaint.shader = null
|
||||
headerPaint.color = panelColor()
|
||||
@@ -1560,8 +1374,6 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
private fun withAlpha(color: Int, alpha: Int): Int =
|
||||
Color.argb(alpha, Color.red(color), Color.green(color), Color.blue(color))
|
||||
|
||||
/** The D: straight left side with small corners, round on the right with radius [rad] (a half circle
|
||||
* when it is half the height). */
|
||||
private fun dShape(l: Float, t: Float, r: Float, b: Float, rad: Float, corner: Float): Path {
|
||||
return Path().apply {
|
||||
moveTo(l, t + corner)
|
||||
@@ -1575,7 +1387,6 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
}
|
||||
}
|
||||
|
||||
/** Where the inside of the outline's round side is at height [y]. */
|
||||
private fun roundEdgeX(p: RectF, y: Float, stroke: Float): Float {
|
||||
val r = dRadius - stroke
|
||||
val cx = p.right - dRadius
|
||||
@@ -1605,7 +1416,6 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
headerPaint.color = withAlpha(accent, 90)
|
||||
c.drawRect(panel.left, dDividerTop, roundEdgeX(panel, dDividerTop, stroke), dividerBottom, headerPaint)
|
||||
}
|
||||
// The watermark fills the half circle on the short sizes and sits on the right of the tall ones.
|
||||
val halfRound = dRadius >= panel.height() / 2f - 0.5f
|
||||
val wmH = if (halfRound) panel.height() * 0.92f else min(panel.height(), panel.width()) * 0.55f
|
||||
DroidDeckMark.draw(c, panel.right - DroidDeckMark.widthFor(wmH) - (if (halfRound) panel.height() * 0.02f else sp(10f)),
|
||||
@@ -1616,7 +1426,6 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
val outline = dShape(panel.left + h, panel.top + h, panel.right - h, panel.bottom - h, dRadius - h, corner)
|
||||
val blur = BlurMaskFilter((sp(3.2f) - 0.5f).coerceAtLeast(0.5f) / 0.57735f, BlurMaskFilter.Blur.NORMAL)
|
||||
glowPaint.strokeWidth = stroke
|
||||
// Two blurred passes under the sharp one, as the 4-in-1 preview's neon.
|
||||
for (pass in 0..2) {
|
||||
glowPaint.maskFilter = if (pass < 2) blur else null
|
||||
glowPaint.style = Paint.Style.STROKE; glowPaint.color = outlineColor()
|
||||
@@ -1657,10 +1466,8 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
DroidDeckMark.draw(canvas, rect.centerX() - markW / 2f, rect.centerY() - markH / 2f, markH, blend(colValue), accent)
|
||||
}
|
||||
|
||||
/** Screen point → whether an on-screen control under the HUD takes a touch there. */
|
||||
internal var passesTouchAt: ((rawX: Float, rawY: Float) -> Boolean)? = null
|
||||
|
||||
// Declining the down event hands the whole gesture to the views under the HUD.
|
||||
override fun onTouchEvent(event: MotionEvent): Boolean {
|
||||
if (dock != DroidDeckHudDock.NONE) return onTabTouch(event)
|
||||
if (event.actionMasked == MotionEvent.ACTION_DOWN && lockController.isLocked() &&
|
||||
|
||||
@@ -5,7 +5,6 @@ import android.graphics.Matrix
|
||||
import android.graphics.Paint
|
||||
import android.graphics.Path
|
||||
|
||||
/** artwork/droiddeck-mark.svg: the split D with its circular cut-out and the blue orb. */
|
||||
internal object DroidDeckMark {
|
||||
private const val VIEW_X = -55.98f
|
||||
const val VIEW_W = 239.92f
|
||||
@@ -36,7 +35,6 @@ internal object DroidDeckMark {
|
||||
|
||||
fun widthFor(height: Float): Float = height * VIEW_W / VIEW_H
|
||||
|
||||
/** Where the drawn mark starts and ends inside [widthFor]: the artwork has empty space on both sides. */
|
||||
fun inkLeftFor(height: Float): Float = (-31.98f - VIEW_X) * height / VIEW_H
|
||||
fun inkRightFor(height: Float): Float = (175.93f - VIEW_X) * height / VIEW_H
|
||||
|
||||
|
||||
@@ -3,13 +3,6 @@ package com.droiddeck.launcher.hud
|
||||
import java.io.File
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
/**
|
||||
* Frame statistics by MangoHud's rules, so the HUD and Steam's performance overlay agree: MangoHud
|
||||
* overlay.cpp update_hud_info_with_frametime and hud_elements.cpp fps() / frame_timing(). The FPS is the
|
||||
* frames counted over a sampling period of at least 500 ms, the frame time next to it is 1000 / FPS, and
|
||||
* the graph holds the last 200 frame times (zeros until filled) on a fixed 0-50 ms scale, min and max
|
||||
* taken over those 200. Average and lows are DroidDeck HUD's own readouts.
|
||||
*/
|
||||
internal class FrameStats {
|
||||
private val graph = FloatArray(GRAPH_FRAMES)
|
||||
private var graphHead = 0
|
||||
@@ -29,11 +22,9 @@ internal class FrameStats {
|
||||
@Volatile var fps = 0f
|
||||
private set
|
||||
|
||||
/** Completed sampling periods; MangoHud redraws its readouts when one completes. */
|
||||
@Volatile var fpsUpdates = 0L
|
||||
private set
|
||||
|
||||
/** Frames added so far; the HUD redraws its graph when this moves. */
|
||||
@Volatile var count = 0L
|
||||
private set
|
||||
|
||||
@@ -81,10 +72,8 @@ internal class FrameStats {
|
||||
count++
|
||||
}
|
||||
|
||||
/** MangoHud's frame time readout: 1000 / FPS. */
|
||||
fun frametimeMs(): Float = 1000f / maxOf(fps, 1f)
|
||||
|
||||
/** The graph, oldest first, into [out] (GRAPH_FRAMES long). */
|
||||
@Synchronized
|
||||
fun graph(out: FloatArray) {
|
||||
for (i in 0 until GRAPH_FRAMES) out[i] = graph[(graphHead + i) % GRAPH_FRAMES]
|
||||
@@ -96,7 +85,6 @@ internal class FrameStats {
|
||||
@Synchronized
|
||||
fun graphMaxMs(): Float = graph.max()
|
||||
|
||||
/** Average over the frames this session, from the first frame to [nowNs]'s last frame. */
|
||||
@Synchronized
|
||||
fun averageFps(): Float {
|
||||
if (sessionFrames < 2 || lastPresentNs <= sessionStartNs) return 0f
|
||||
@@ -112,7 +100,6 @@ internal class FrameStats {
|
||||
}
|
||||
}
|
||||
|
||||
/** FPS at the 99th, 99.9th and 99.99th percentile frame time of the last LOWS_FRAMES frames. */
|
||||
fun lows(nowNs: Long): Lows {
|
||||
val copy: LongArray
|
||||
synchronized(this) {
|
||||
@@ -145,11 +132,6 @@ internal class FrameStats {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Feeds [stats] with the frame times gamescope shares (the ones MangoHud shows). Sessions without the
|
||||
* shared file, or where gamescope stopped sending, fall back to the frames DroidDeck's compositor shows,
|
||||
* which stop at the screen's refresh rate.
|
||||
*/
|
||||
internal class GameFrameFeed(private val file: File, val stats: FrameStats = FrameStats()) {
|
||||
private var handle = 0L
|
||||
private var nextOpenNs = 0L
|
||||
@@ -160,7 +142,7 @@ internal class GameFrameFeed(private val file: File, val stats: FrameStats = Fra
|
||||
private val info = IntArray(5)
|
||||
@Volatile private var fromGamescope = false
|
||||
private var lastCompositorNs = 0L
|
||||
@Volatile private var compositorFrames = 0L // written by the compositor thread only
|
||||
@Volatile private var compositorFrames = 0L
|
||||
private var seenCompositorFrames = 0L
|
||||
|
||||
@Volatile var engine = ""
|
||||
@@ -176,7 +158,6 @@ internal class GameFrameFeed(private val file: File, val stats: FrameStats = Fra
|
||||
@Volatile var refreshMilliHz = 0
|
||||
private set
|
||||
|
||||
/** Main thread, once per display frame. True when new frames arrived. */
|
||||
fun poll(nowNs: Long): Boolean {
|
||||
val compositorAdded = compositorFrames != seenCompositorFrames
|
||||
seenCompositorFrames = compositorFrames
|
||||
@@ -185,7 +166,6 @@ internal class GameFrameFeed(private val file: File, val stats: FrameStats = Fra
|
||||
nextOpenNs = nowNs + REOPEN_NS
|
||||
handle = runCatching { HudFrames.nativeOpen(file.path) }.getOrDefault(0L)
|
||||
if (handle == 0L) return compositorAdded
|
||||
// Frames already in the file were written before this reader started.
|
||||
HudFrames.nativePoll(handle, frametimes, times)
|
||||
}
|
||||
val n = HudFrames.nativePoll(handle, frametimes, times)
|
||||
@@ -199,7 +179,6 @@ internal class GameFrameFeed(private val file: File, val stats: FrameStats = Fra
|
||||
} else if (lastRingFrameNs != 0L && nowNs - lastRingFrameNs > LIVE_NS) {
|
||||
fromGamescope = false
|
||||
}
|
||||
// A new session writes the file again from the start; reopen when gamescope has gone quiet.
|
||||
if (n <= 0 && nowNs - maxOf(lastRingFrameNs, nextOpenNs - REOPEN_NS) > STALE_NS) close()
|
||||
if (nowNs - lastInfoNs >= INFO_NS) {
|
||||
lastInfoNs = nowNs
|
||||
@@ -208,7 +187,6 @@ internal class GameFrameFeed(private val file: File, val stats: FrameStats = Fra
|
||||
return n > 0 || compositorAdded
|
||||
}
|
||||
|
||||
/** Compositor thread: one frame shown on the panel. */
|
||||
fun onCompositorFrame(nowNs: Long) {
|
||||
if (fromGamescope) {
|
||||
lastCompositorNs = 0L
|
||||
@@ -247,8 +225,6 @@ internal class GameFrameFeed(private val file: File, val stats: FrameStats = Fra
|
||||
private const val STALE_NS = 5_000_000_000L
|
||||
private const val INFO_NS = 500_000_000L
|
||||
|
||||
/** DroidDeck's mangoapp's names for gamescope's engine field (Valve's 20260902.1 build, app/main.cpp
|
||||
* engine_type_from_str and overlay.h engines); gamescope sends "gamescope" when it knows none. */
|
||||
fun engineLabel(name: String): String = when (name) {
|
||||
"DXVK" -> "DXVK"
|
||||
"vkd3d" -> "VKD3D"
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
package com.droiddeck.launcher.hud
|
||||
|
||||
/** Reader for the frame-times file gamescope patch 0125 writes (hudframes.c). */
|
||||
internal object HudFrames {
|
||||
init {
|
||||
System.loadLibrary("droiddeckwayland")
|
||||
}
|
||||
|
||||
/** Under the Linux root: the session exports /run/droiddeck-hud/frames to gamescope. */
|
||||
const val PATH = "run/droiddeck-hud/frames"
|
||||
const val CAPACITY = 1024
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
* link to https://github.com/The412Banner/FusionHUD in the project documentation
|
||||
* AND in the in-app credits/about screen.
|
||||
*
|
||||
* Ported to DroidDeck from FusionHUD (Bannerlator's HUD); DroidDeck changes are marked in the code.
|
||||
* Ported to DroidDeck from FusionHUD (Bannerlator's HUD) and modified for DroidDeck.
|
||||
*/
|
||||
|
||||
package com.droiddeck.launcher.hud;
|
||||
@@ -28,48 +28,18 @@ import android.view.View;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/**
|
||||
* Shared touch + lock behaviour for every in-game performance HUD (classic FrameRating(+Horizontal),
|
||||
* GameHub PerfHudView, GameNative PerformanceHudView, and the DroidDeck HUD). One place so the four
|
||||
* overlays can't drift:
|
||||
*
|
||||
* <ul>
|
||||
* <li><b>tap</b> → {@link Callbacks#onTap()} (orientation-toggle for the first three; size-cycle for
|
||||
* the DroidDeck HUD) — a no-op that only re-flashes the lock badge while locked.</li>
|
||||
* <li><b>drag</b> → moves the host view and, on release, {@link Callbacks#onMoved} to persist the
|
||||
* position — disabled (frozen) while locked.</li>
|
||||
* <li><b>long-press</b> → toggles {@code hudLocked}, persisted via {@link Callbacks#onLockChanged}
|
||||
* and kept in sync with the "Lock in place" menu chip. Works locked or unlocked (so a long-press
|
||||
* always unlocks); a locked {@code DroidDeckHudView} passes touches on only over on-screen controls.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>On every lock/unlock (and on a blocked gesture while locked) a small padlock badge fades in →
|
||||
* holds → fades out in a corner of the panel. The fade is driven by a self-reposting Runnable that
|
||||
* invalidates only while visible — nothing runs on the present path, nothing animates at rest.
|
||||
*
|
||||
* <p>All methods are Main-thread only (touch + draw), matching the epoll-thread rule: the views feed
|
||||
* this from {@code onTouchEvent}/{@code dispatchDraw}, never from a present tick.
|
||||
*/
|
||||
public class HudLockController {
|
||||
|
||||
public interface Callbacks {
|
||||
/** Unlocked single tap: orientation-toggle (classic/gamehub/gamenative) or size-cycle (DroidDeck HUD). */
|
||||
void onTap();
|
||||
/** Drag released (unlocked): persist the new (x, y). */
|
||||
void onMoved(float x, float y);
|
||||
/** The view moved under a drag (unlocked), with the finger at screen point (rawX, rawY). */
|
||||
default void onDragged(float rawX, float rawY) {}
|
||||
/** The drag ended in a fling (unlocked), in pixels per second; comes just before {@link #onMoved}. */
|
||||
default void onFlung(float velocityX, float velocityY) {}
|
||||
/** Lock toggled by long-press: persist {@code hudLocked} + sync the menu chip. */
|
||||
void onLockChanged(boolean locked);
|
||||
/** Two-finger pinch (unlocked): the change since the previous event, above 1 when the fingers spread. */
|
||||
default void onPinch(float factor) {}
|
||||
/** The fingers came off a pinch: persist the new size. */
|
||||
default void onPinchEnd() {}
|
||||
}
|
||||
|
||||
// Fade timing (ms): in → hold → out. Lock/unlock hold ~1.5 s; a blocked-gesture re-flash is shorter.
|
||||
private static final long FADE_IN_MS = 160;
|
||||
private static final long HOLD_TOGGLE_MS = 1500;
|
||||
private static final long HOLD_REFLASH_MS = 750;
|
||||
@@ -83,13 +53,10 @@ public class HudLockController {
|
||||
|
||||
private boolean locked = false;
|
||||
|
||||
// Drag state
|
||||
private float downRawX, downRawY, startX, startY;
|
||||
private boolean dragging = false;
|
||||
// A pinch ends the gesture's drag and tap: the finger left down after it must not move the HUD.
|
||||
private boolean pinched = false;
|
||||
|
||||
// Fade state
|
||||
private long fadeStart = 0;
|
||||
private long holdMs = HOLD_TOGGLE_MS;
|
||||
private boolean fadeShowLocked = false;
|
||||
@@ -110,14 +77,12 @@ public class HudLockController {
|
||||
iconStroke.setStrokeJoin(Paint.Join.ROUND);
|
||||
}
|
||||
|
||||
/** Set lock state from config (applyConfig) WITHOUT firing the persist callback. */
|
||||
public void setLocked(boolean locked) { this.locked = locked; }
|
||||
|
||||
public boolean isLocked() { return locked; }
|
||||
|
||||
public boolean isDragging() { return dragging; }
|
||||
|
||||
/** Feed from the host view's onTouchEvent. Always consumes (mirrors the legacy manual handlers). */
|
||||
public boolean onTouchEvent(MotionEvent event) {
|
||||
scaleDetector.onTouchEvent(event);
|
||||
detector.onTouchEvent(event);
|
||||
@@ -143,7 +108,6 @@ public class HudLockController {
|
||||
|
||||
@Override
|
||||
public void onLongPress(MotionEvent e) {
|
||||
// Long-press always toggles — this is the only gesture that still works while locked.
|
||||
locked = !locked;
|
||||
cb.onLockChanged(locked);
|
||||
flash(locked, HOLD_TOGGLE_MS);
|
||||
@@ -153,7 +117,7 @@ public class HudLockController {
|
||||
public boolean onSingleTapUp(MotionEvent e) {
|
||||
if (pinched) return true;
|
||||
if (locked) {
|
||||
flash(true, HOLD_REFLASH_MS); // intentionally locked — remind the user
|
||||
flash(true, HOLD_REFLASH_MS);
|
||||
} else {
|
||||
cb.onTap();
|
||||
}
|
||||
@@ -171,7 +135,7 @@ public class HudLockController {
|
||||
if (pinched) return true;
|
||||
if (locked) {
|
||||
if (!dragging) flash(true, HOLD_REFLASH_MS);
|
||||
dragging = true; // mark so the blocked drag doesn't fall through to a tap
|
||||
dragging = true;
|
||||
return true;
|
||||
}
|
||||
view.setX(startX + (e2.getRawX() - downRawX));
|
||||
@@ -203,7 +167,6 @@ public class HudLockController {
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Fade badge -------------------------------------------------------
|
||||
private void flash(boolean showLocked, long hold) {
|
||||
fadeShowLocked = showLocked;
|
||||
holdMs = hold;
|
||||
@@ -236,14 +199,6 @@ public class HudLockController {
|
||||
return Color.argb(Math.round(255 * a), Color.red(color), Color.green(color), Color.blue(color));
|
||||
}
|
||||
|
||||
/**
|
||||
* Draw the padlock badge in the top-right of the panel if a fade is in progress. Call from the
|
||||
* host's onDraw (plain View) or dispatchDraw (ViewGroup), after the content.
|
||||
*
|
||||
* <p>No background box: the glyph is drawn twice — a slightly expanded, thicker semi-transparent
|
||||
* black "halo" pass for legibility on any game frame, then the white glyph on top — so it reads as
|
||||
* a floating icon, not an opaque tile.
|
||||
*/
|
||||
public void drawBadge(Canvas canvas) {
|
||||
float a = currentAlpha();
|
||||
if (a <= 0f) return;
|
||||
@@ -262,14 +217,12 @@ public class HudLockController {
|
||||
float r = size * 0.2f;
|
||||
float shackleTop = top + size * 0.08f;
|
||||
|
||||
// Pass 1: dark halo (expanded body, thicker shackle) for contrast; Pass 2: white glyph.
|
||||
drawLock(canvas, cx, bodyTop, bodyLeft, bodyRight, bottom, r, shackleTop, d,
|
||||
Color.argb(Math.round(150 * a), 0, 0, 0), 3.0f * d, 0.9f * d, false);
|
||||
drawLock(canvas, cx, bodyTop, bodyLeft, bodyRight, bottom, r, shackleTop, d,
|
||||
withAlpha(0xFFFFFFFF, a), 1.7f * d, 0f, true);
|
||||
}
|
||||
|
||||
/** One padlock pass. {@code halo} inflates the body/shackle in dark; the white pass punches the keyhole. */
|
||||
private void drawLock(Canvas canvas, float cx, float bodyTop, float bodyLeft, float bodyRight,
|
||||
float bottom, float r, float shackleTop, float d,
|
||||
int color, float strokeW, float expand, boolean punchKeyhole) {
|
||||
@@ -277,7 +230,6 @@ public class HudLockController {
|
||||
iconStroke.setColor(color);
|
||||
iconStroke.setStrokeWidth(strokeW);
|
||||
|
||||
// Body
|
||||
canvas.drawRoundRect(bodyLeft - expand, bodyTop - expand, bodyRight + expand, bottom + expand,
|
||||
2.4f * d, 2.4f * d, iconFill);
|
||||
if (punchKeyhole) {
|
||||
@@ -289,19 +241,16 @@ public class HudLockController {
|
||||
|
||||
RectF arc = new RectF(cx - r, shackleTop, cx + r, shackleTop + 2f * r);
|
||||
if (fadeShowLocked) {
|
||||
// Closed: both legs run straight down into the body.
|
||||
Path p = new Path();
|
||||
p.addArc(arc, 180f, 180f);
|
||||
p.moveTo(cx - r, shackleTop + r); p.lineTo(cx - r, bodyTop);
|
||||
p.moveTo(cx + r, shackleTop + r); p.lineTo(cx + r, bodyTop);
|
||||
canvas.drawPath(p, iconStroke);
|
||||
} else {
|
||||
// Open, clearly to the LEFT: the RIGHT leg stays seated in the body; the arc + LEFT leg
|
||||
// hinge up-and-left off the right attachment so the left leg lifts well clear of the body.
|
||||
canvas.drawLine(cx + r, shackleTop + r, cx + r, bodyTop, iconStroke); // fixed right leg
|
||||
canvas.drawLine(cx + r, shackleTop + r, cx + r, bodyTop, iconStroke);
|
||||
Path p = new Path();
|
||||
p.addArc(arc, 180f, 180f);
|
||||
p.moveTo(cx - r, shackleTop + r); p.lineTo(cx - r, bodyTop); // full-length left leg
|
||||
p.moveTo(cx - r, shackleTop + r); p.lineTo(cx - r, bodyTop);
|
||||
canvas.save();
|
||||
canvas.rotate(-42f, cx + r, shackleTop + r);
|
||||
canvas.drawPath(p, iconStroke);
|
||||
|
||||
@@ -8,7 +8,8 @@
|
||||
* link to https://github.com/The412Banner/FusionHUD in the project documentation
|
||||
* AND in the in-app credits/about screen.
|
||||
*
|
||||
* Ported to DroidDeck from FusionHUD (Bannerlator's HUD); DroidDeck changes are marked in the code.
|
||||
* Ported to DroidDeck from FusionHUD (Bannerlator's HUD) and modified for DroidDeck.
|
||||
* Metric readers from @xXJSONDeruloXx's work.
|
||||
*/
|
||||
|
||||
package com.droiddeck.launcher.hud;
|
||||
@@ -32,50 +33,17 @@ import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* Shared live-metric collector for every performance HUD overlay. This is the single, device-complete
|
||||
* implementation of the sysfs / Android readers — no overlay should re-read sysfs itself, so the GPU
|
||||
* discovery / thermal / battery logic never diverges.
|
||||
*
|
||||
* <p>Ported and hardened from GameNative's {@code PerformanceHudView} readers, which are far more
|
||||
* device-complete than the two-fixed-path versions previously inlined in the classic overlays:
|
||||
* <ul>
|
||||
* <li>GPU load — ~10 static candidates plus a dynamic {@code /sys/class/devfreq} +
|
||||
* {@code /sys/devices/virtual/devfreq} walk for gpu/mali/g3d/kgsl nodes; handles gpubusy
|
||||
* (busy/total), Mali gpuinfo (delta-ms/wall-ms, needs state between calls) and generic percent
|
||||
* nodes. Discovery cached.</li>
|
||||
* <li>CPU usage — {@code /proc/stat} aggregate delta with a scaling-frequency fallback for devices
|
||||
* where {@code /proc/stat} is restricted.</li>
|
||||
* <li>Thermal — prioritized CPU zone discovery (cpu-silicon > cpu-0 > cpu > soc >
|
||||
* s5p-tmu > cputop > tsens > cluster > big/little) and a separate prioritized GPU zone
|
||||
* discovery plus kgsl/mali direct paths. milli-°C normalization + 1..150 sanity clamp.</li>
|
||||
* <li>Battery — % capacity, power W, runtime-left estimate (charge_counter / current_now, smoothed),
|
||||
* battery temperature, plus the dual-battery current-sum for the classic overlays.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>Every getter is null / absent-safe: nullable getters return {@code null} when a metric cannot be
|
||||
* read (the overlay hides that row, matching GameNative behavior); the legacy non-null getters return
|
||||
* 0 in that case. Not thread-safe; call from a single refresh thread per instance.
|
||||
*/
|
||||
public class HudMetrics {
|
||||
private final Context context;
|
||||
|
||||
public HudMetrics(Context context) { this.context = context; }
|
||||
|
||||
// DroidDeck: the readings Steam's performance overlay shows come from MangoReadings, so both agree.
|
||||
private MangoReadings mango;
|
||||
public void setMangoReadings(MangoReadings readings) { mango = readings; }
|
||||
|
||||
// =======================================================================
|
||||
// CPU usage
|
||||
// =======================================================================
|
||||
private Long lastCpuTotal = null;
|
||||
private Long lastCpuIdle = null;
|
||||
|
||||
/**
|
||||
* Overall device CPU usage 0..100 computed from the /proc/stat delta since the last call, with a
|
||||
* scaling-frequency fallback. Returns null only when neither source is readable.
|
||||
*/
|
||||
public Integer getCpuUsagePercent() {
|
||||
String line = readFirstLine("/proc/stat");
|
||||
if (line != null) {
|
||||
@@ -104,8 +72,6 @@ public class HudMetrics {
|
||||
return clampPercent((int) usage);
|
||||
}
|
||||
}
|
||||
// First sample seeds the delta — fall through to the frequency estimate so the
|
||||
// very first read still returns something.
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -127,20 +93,10 @@ public class HudMetrics {
|
||||
return clampPercent((int) ((currentTotal * 100L) / maxTotal));
|
||||
}
|
||||
|
||||
/** Legacy non-null accessor (0 when unavailable). Kept for {@code PerfHudView}. */
|
||||
public float getCPUUsage() {
|
||||
Integer p = getCpuUsagePercent();
|
||||
return p == null ? 0f : p;
|
||||
}
|
||||
|
||||
// =======================================================================
|
||||
// GPU load
|
||||
// =======================================================================
|
||||
private List<String> gpuUsagePathsCache = null;
|
||||
private Long lastMaliGpuInfoMs = null;
|
||||
private long lastMaliGpuInfoWallMs = 0L;
|
||||
|
||||
/** GPU utilisation 0..100, or null when no readable source is found on this device. */
|
||||
public Integer getGpuUsagePercent() {
|
||||
for (String path : discoverGpuUsagePaths()) {
|
||||
Integer p = readGpuUsageSample(path);
|
||||
@@ -149,12 +105,6 @@ public class HudMetrics {
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Legacy non-null accessor (0 when unavailable). Kept for {@code PerfHudView}. */
|
||||
public int getGPULoad() {
|
||||
Integer p = getGpuUsagePercent();
|
||||
return p == null ? 0 : p;
|
||||
}
|
||||
|
||||
private List<String> discoverGpuUsagePaths() {
|
||||
if (gpuUsagePathsCache != null) return gpuUsagePathsCache;
|
||||
LinkedHashSet<String> candidates = new LinkedHashSet<>();
|
||||
@@ -163,8 +113,6 @@ public class HudMetrics {
|
||||
if (new File(p).canRead()) candidates.add(p);
|
||||
}
|
||||
|
||||
// Vendor platform nodes with hashed/addressed names we can't hard-code (e.g.
|
||||
// /sys/devices/platform/13000000.mali/utilisation, .../gpusysfs/gpu_busy, panfrost, sgpu).
|
||||
File platformDir = new File("/sys/devices/platform");
|
||||
File[] platformNodes = platformDir.listFiles(File::isDirectory);
|
||||
if (platformNodes != null) {
|
||||
@@ -211,9 +159,6 @@ public class HudMetrics {
|
||||
return gpuUsagePathsCache;
|
||||
}
|
||||
|
||||
// Ordered, world-readable-when-present GPU utilisation nodes across the vendors we've seen:
|
||||
// Adreno KGSL, Mali (misc + Exynos vendor), PowerVR, and amdgpu-style sysfs (Samsung Xclipse /
|
||||
// "sgpu", AMD-on-Exynos). readGpuUsageSample() knows how to parse each filename shape.
|
||||
private static final String[] GPU_USAGE_STATIC_PATHS = {
|
||||
"/sys/class/kgsl/kgsl-3d0/gpubusy",
|
||||
"/sys/class/kgsl/kgsl-3d0/gpu_busy_percentage",
|
||||
@@ -223,23 +168,19 @@ public class HudMetrics {
|
||||
"/sys/class/misc/mali0/device/gpuinfo",
|
||||
"/sys/devices/platform/mali/utilization",
|
||||
"/sys/kernel/gpu/gpu_busy",
|
||||
"/sys/devices/platform/gpusysfs/gpu_busy", // Exynos Mali vendor node
|
||||
"/sys/devices/platform/gpusysfs/gpu_busy",
|
||||
"/sys/class/misc/pvrsrvkm/device/utilisation",
|
||||
"/sys/class/pvr/utilisation", // PowerVR (Rogue) sysfs
|
||||
"/sys/class/pvr/utilisation",
|
||||
"/sys/class/pvr/gpu_utilisation",
|
||||
"/sys/class/drm/card0/device/gpu_busy_percent", // amdgpu / Xclipse (sgpu), 0..100
|
||||
"/sys/class/drm/card0/device/gpu_busy_percent",
|
||||
"/sys/class/devfreq/gpu/load",
|
||||
// ── Additive cross-vendor fallbacks (appended LAST: tried only after every path above
|
||||
// misses, so a device that already resolves — e.g. Adreno kgsl — never reaches these). ──
|
||||
"/sys/kernel/ged/hal/gpu_utilization", // MediaTek GED: "<loading> <block> <idle>" → loading%
|
||||
"/sys/module/ged/parameters/gpu_loading", // MediaTek GED module param, plain percent
|
||||
"/sys/kernel/ged/hal/gpu_utilization",
|
||||
"/sys/module/ged/parameters/gpu_loading",
|
||||
};
|
||||
// Percent-bearing filenames scanned under each devfreq / platform GPU node.
|
||||
private static final String[] GPU_USAGE_FILES = {
|
||||
"gpu_busy_percentage", "gpu_busy_percent", "gpu_load", "utilisation", "utilization",
|
||||
"load", "gpu_busy", "gpuinfo",
|
||||
};
|
||||
// Substrings that mark a devfreq / platform node as the GPU, across vendors.
|
||||
private static final String[] GPU_NODE_TOKENS = {
|
||||
"gpu", "mali", "g3d", "kgsl", "panfrost", "pvr", "powervr", "xclipse", "sgpu",
|
||||
};
|
||||
@@ -258,8 +199,6 @@ public class HudMetrics {
|
||||
return clampPercent((int) ((busy * 100L) / total));
|
||||
}
|
||||
case "gpuinfo": {
|
||||
// Mali multi-line node: the GPU busy time (ms) is the last token of line 1. Utilisation
|
||||
// is the delta over wall-clock delta between two reads, so it needs state.
|
||||
String line = readNthLine(path, 1);
|
||||
if (line == null) return null;
|
||||
String[] toks = line.trim().split("\\s+");
|
||||
@@ -294,46 +233,12 @@ public class HudMetrics {
|
||||
return null;
|
||||
}
|
||||
|
||||
// =======================================================================
|
||||
// RAM
|
||||
// =======================================================================
|
||||
public float getRAMPercent() {
|
||||
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
|
||||
ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
|
||||
am.getMemoryInfo(mi);
|
||||
if (mi.totalMem <= 0) return 0;
|
||||
return (mi.totalMem - mi.availMem) * 100f / mi.totalMem;
|
||||
}
|
||||
private List<String[]> thermalZonesCache = null;
|
||||
|
||||
/** Used RAM as "x.xGB" (or "yMB" below 1 GB), matching GameNative's HUD text. */
|
||||
public String getUsedRamText() {
|
||||
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
|
||||
if (am == null) return "—";
|
||||
ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
|
||||
am.getMemoryInfo(mi);
|
||||
long usedBytes = Math.max(0L, mi.totalMem - mi.availMem);
|
||||
double usedGb = usedBytes / (1024.0 * 1024.0 * 1024.0);
|
||||
if (usedGb >= 1.0) return String.format(Locale.US, "%.1fGB", usedGb);
|
||||
return (usedBytes / (1024L * 1024L)) + "MB";
|
||||
}
|
||||
|
||||
// =======================================================================
|
||||
// Temperature
|
||||
// =======================================================================
|
||||
private List<String[]> thermalZonesCache = null; // each entry: {type, tempPath}
|
||||
|
||||
/** Legacy non-null CPU-temperature accessor in °C (0 when unavailable). Kept for {@code PerfHudView}. */
|
||||
public float getTemperature() {
|
||||
Integer t = getCpuTempC();
|
||||
return t == null ? 0f : t;
|
||||
}
|
||||
|
||||
/** Hottest representative CPU temperature in °C, or null when no CPU zone is readable. */
|
||||
public Integer getCpuTempC() {
|
||||
return readTemperatureC(discoverPrioritizedCpuTempPaths());
|
||||
}
|
||||
|
||||
/** GPU temperature in °C, or null when no GPU sensor is readable. */
|
||||
public Integer getGpuTempC() {
|
||||
ArrayList<String> paths = new ArrayList<>();
|
||||
paths.add("/sys/class/kgsl/kgsl-3d0/temp");
|
||||
@@ -346,16 +251,16 @@ public class HudMetrics {
|
||||
|
||||
private List<String> discoverPrioritizedCpuTempPaths() {
|
||||
return prioritizePaths(type -> {
|
||||
if (type.contains("gpu")) return null; // never mistake a GPU zone for CPU
|
||||
if (type.contains("gpu")) return null;
|
||||
if (type.contains("cpu-silicon")) return 0;
|
||||
if (type.contains("cpu-0")) return 1;
|
||||
if (type.contains("cpuss")) return 2; // Qualcomm cpuss composite
|
||||
if (type.contains("mtktscpu")) return 2; // MediaTek CPU thermal
|
||||
if (type.contains("cpu")) return 2; // cpu, cpu-*-usr, cpu_thermal, cpu_center
|
||||
if (type.contains("s5p-tmu")) return 3; // Exynos TMU
|
||||
if (type.contains("cpuss")) return 2;
|
||||
if (type.contains("mtktscpu")) return 2;
|
||||
if (type.contains("cpu")) return 2;
|
||||
if (type.contains("s5p-tmu")) return 3;
|
||||
if (type.contains("soc")) return 4;
|
||||
if (type.contains("cputop")) return 5;
|
||||
if (type.contains("tsens")) return 6; // Qualcomm tsens aggregate
|
||||
if (type.contains("tsens")) return 6;
|
||||
if (type.contains("cluster")) return 7;
|
||||
if (type.contains("big") || type.contains("little")) return 8;
|
||||
return null;
|
||||
@@ -365,11 +270,11 @@ public class HudMetrics {
|
||||
private List<String> discoverPrioritizedGpuTempPaths() {
|
||||
return prioritizePaths(type -> {
|
||||
if (type.contains("gpu-silicon")) return 0;
|
||||
if (type.contains("gpuss")) return 1; // Qualcomm gpuss
|
||||
if (type.contains("mtktsgpu")) return 1; // MediaTek GPU thermal
|
||||
if (type.contains("gpuss")) return 1;
|
||||
if (type.contains("mtktsgpu")) return 1;
|
||||
if (type.contains("gpu-virt")) return 2;
|
||||
if (type.contains("gpu")) return 2;
|
||||
if (type.contains("g3d")) return 3; // Exynos Mali (g3d)
|
||||
if (type.contains("g3d")) return 3;
|
||||
if (type.contains("kgsl")) return 4;
|
||||
if (type.contains("mali")) return 5;
|
||||
if (type.contains("xclipse") || type.contains("sgpu")) return 6;
|
||||
@@ -381,12 +286,11 @@ public class HudMetrics {
|
||||
|
||||
private List<String> prioritizePaths(Ranker ranker) {
|
||||
List<String[]> zones = discoverAllThermalZones();
|
||||
ArrayList<int[]> order = new ArrayList<>(); // {index, rank}
|
||||
ArrayList<int[]> order = new ArrayList<>();
|
||||
for (int i = 0; i < zones.size(); i++) {
|
||||
Integer r = ranker.rank(zones.get(i)[0]);
|
||||
if (r != null) order.add(new int[]{i, r});
|
||||
}
|
||||
// Sort by rank, then by path for determinism.
|
||||
order.sort((a, b) -> {
|
||||
if (a[1] != b[1]) return Integer.compare(a[1], b[1]);
|
||||
return zones.get(a[0])[1].compareTo(zones.get(b[0])[1]);
|
||||
@@ -426,14 +330,12 @@ public class HudMetrics {
|
||||
if (!seen.add(path)) continue;
|
||||
Integer raw = readIntFromLine(path);
|
||||
if (raw == null) continue;
|
||||
// Round to nearest degree for milli-°C sources; sanity-clamp to reject offline sensors.
|
||||
int celsius = raw > 1000 ? (raw + 500) / 1000 : raw;
|
||||
if (celsius >= 1 && celsius <= 150) return celsius;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The first path in {@code paths} that yields a plausible reading, or null. */
|
||||
private String resolveTempPath(List<String> paths) {
|
||||
LinkedHashSet<String> seen = new LinkedHashSet<>();
|
||||
for (String path : paths) {
|
||||
@@ -446,13 +348,8 @@ public class HudMetrics {
|
||||
return null;
|
||||
}
|
||||
|
||||
// =======================================================================
|
||||
// Temperature danger bands (green / amber / red)
|
||||
// =======================================================================
|
||||
|
||||
public enum TempSensor { CPU, GPU, BATTERY }
|
||||
|
||||
/** Amber and red onset in °C. Always °C internally — conversion happens at format time only. */
|
||||
public static final class Thresholds {
|
||||
public final int amberC;
|
||||
public final int redC;
|
||||
@@ -463,19 +360,14 @@ public class HudMetrics {
|
||||
public static final int TEMP_COLOR_AMBER = 0xFFFFB74D;
|
||||
public static final int TEMP_COLOR_RED = 0xFFEF5350;
|
||||
|
||||
// Tier-2 fallbacks, used when the device declares no usable trip points. Battery is the only one
|
||||
// with a well-grounded number (Li-ion); CPU/GPU vary enough between parts that these are a
|
||||
// deliberately conservative guess — which is exactly why trip points are preferred.
|
||||
private static final int DEFAULT_RED_CPU = 90;
|
||||
private static final int DEFAULT_RED_GPU = 90;
|
||||
private static final int DEFAULT_RED_BAT = 48;
|
||||
|
||||
/** Amber sits a proportional step below red, which scales sensibly across both CPU/GPU and battery ranges. */
|
||||
public static int amberForRed(int redC) {
|
||||
return Math.round(redC * 0.88f);
|
||||
}
|
||||
|
||||
/** Parsed temperature display options, shared by every overlay so they can't disagree. */
|
||||
public static final class TempDisplay {
|
||||
public final boolean fahrenheit;
|
||||
public final boolean colorBands;
|
||||
@@ -518,17 +410,11 @@ public class HudMetrics {
|
||||
}
|
||||
}
|
||||
|
||||
// Trip points are a device constant — resolve once per sensor and keep it.
|
||||
private final java.util.EnumMap<TempSensor, Thresholds> autoThresholdCache =
|
||||
new java.util.EnumMap<>(TempSensor.class);
|
||||
private final java.util.EnumSet<TempSensor> autoThresholdResolved =
|
||||
java.util.EnumSet.noneOf(TempSensor.class);
|
||||
|
||||
/**
|
||||
* Bands for a sensor. Manual mode uses the user's red point; Auto prefers the device's OWN
|
||||
* declared thermal trip points (per-device truth — a handheld with active cooling and a phone on
|
||||
* the same SoC throttle at very different points) and falls back to {@link #DEFAULT_RED_CPU} etc.
|
||||
*/
|
||||
public Thresholds resolveThresholds(TempSensor sensor, TempDisplay display) {
|
||||
if (display != null && !display.auto) {
|
||||
int red = display.manualRedFor(sensor);
|
||||
@@ -547,15 +433,6 @@ public class HudMetrics {
|
||||
return new Thresholds(amberForRed(red), red);
|
||||
}
|
||||
|
||||
/**
|
||||
* Bands from the kernel's declared trip points for the zone we actually read this sensor from:
|
||||
* amber ← the lowest sane {@code passive} trip, red ← the lowest sane {@code hot}/{@code critical}.
|
||||
*
|
||||
* <p>Returns null unless a usable red point is found. Two real traps this guards against: some
|
||||
* zones aren't temperature sensors at all (a Snapdragon's {@code pm8550-bcl-lvl0} battery-current
|
||||
* limiter reports {@code trip_point_0_temp = 1} with type {@code passive}), and the GPU is often
|
||||
* read from a non-thermal_zone node ({@code /sys/class/kgsl/...}) that has no trip points.
|
||||
*/
|
||||
private Thresholds readTripPointThresholds(TempSensor sensor) {
|
||||
String tempPath;
|
||||
switch (sensor) {
|
||||
@@ -563,7 +440,7 @@ public class HudMetrics {
|
||||
tempPath = resolveTempPath(discoverPrioritizedGpuTempPaths());
|
||||
break;
|
||||
case BATTERY:
|
||||
return null; // battery temp comes from BatteryManager, not a thermal zone
|
||||
return null;
|
||||
default:
|
||||
tempPath = resolveTempPath(discoverPrioritizedCpuTempPaths());
|
||||
}
|
||||
@@ -580,8 +457,6 @@ public class HudMetrics {
|
||||
Integer raw = readIntFromLine(tripTemp.getPath());
|
||||
if (raw == null) continue;
|
||||
int celsius = raw > 1000 ? (raw + 500) / 1000 : raw;
|
||||
// Reject anything that isn't plausibly a thermal trip — this is what filters out the
|
||||
// battery-current-limiter zones whose "trip point" is a level index, not a temperature.
|
||||
if (celsius < 20 || celsius > 120) continue;
|
||||
|
||||
String typePath = tripTemp.getPath().replaceAll("_temp$", "_type");
|
||||
@@ -600,7 +475,6 @@ public class HudMetrics {
|
||||
return new Thresholds(amber, red);
|
||||
}
|
||||
|
||||
/** Band colour for a reading, or {@code fallbackColor} when banding is off or the value is unusable. */
|
||||
public static int tempColor(Float celsius, Thresholds t, TempDisplay display, int fallbackColor) {
|
||||
if (celsius == null || t == null || display == null || !display.colorBands) return fallbackColor;
|
||||
if (celsius >= t.redC) return TEMP_COLOR_RED;
|
||||
@@ -608,7 +482,6 @@ public class HudMetrics {
|
||||
return TEMP_COLOR_OK;
|
||||
}
|
||||
|
||||
/** Formats a °C reading in the user's unit. Thresholds stay °C; only display converts. */
|
||||
public static String formatTemp(float celsius, TempDisplay display, boolean oneDecimal) {
|
||||
boolean f = display != null && display.fahrenheit;
|
||||
float value = f ? celsius * 9f / 5f + 32f : celsius;
|
||||
@@ -618,15 +491,12 @@ public class HudMetrics {
|
||||
: String.format(Locale.ENGLISH, "%d%s", Math.round(value), unit);
|
||||
}
|
||||
|
||||
// =======================================================================
|
||||
// Battery
|
||||
// =======================================================================
|
||||
public static final class Battery {
|
||||
public final float watts;
|
||||
public final boolean charging;
|
||||
public final Integer percent; // 0..100 or null
|
||||
public final Integer tempC; // rounded °C or null
|
||||
public final String runtimeText; // "LEFT 2h 5m" / "LEFT CHG" / null
|
||||
public final Integer percent;
|
||||
public final Integer tempC;
|
||||
public final String runtimeText;
|
||||
|
||||
Battery(float watts, boolean charging) {
|
||||
this(watts, charging, null, null, null);
|
||||
@@ -640,29 +510,23 @@ public class HudMetrics {
|
||||
}
|
||||
}
|
||||
|
||||
/** power_supply current_now channels (µA) for the dual-battery sum. */
|
||||
private static final String[] CURRENT_CHANNELS = {
|
||||
"/sys/class/power_supply/battery/current_now",
|
||||
"/sys/class/power_supply/bms/current_now",
|
||||
"/sys/class/power_supply/main/current_now",
|
||||
};
|
||||
|
||||
/** power_supply voltage_now channels (µV) — fallback when {@code EXTRA_VOLTAGE} reads 0 on some
|
||||
* OEM firmwares (e.g. HONOR Magic), which otherwise leaves wattage stuck at 0.0W. */
|
||||
private static final String[] VOLTAGE_CHANNELS = {
|
||||
"/sys/class/power_supply/battery/voltage_now",
|
||||
"/sys/class/power_supply/bms/voltage_now",
|
||||
"/sys/class/power_supply/main/voltage_now",
|
||||
};
|
||||
/** power_supply power_now channels (µW) — last-resort direct power reading when neither the
|
||||
* BatteryManager voltage nor {@code voltage_now} is available. */
|
||||
private static final String[] POWER_CHANNELS = {
|
||||
"/sys/class/power_supply/battery/power_now",
|
||||
"/sys/class/power_supply/bms/power_now",
|
||||
"/sys/class/power_supply/main/power_now",
|
||||
};
|
||||
|
||||
/** First readable long across a channel list, or null. */
|
||||
private static Long readLongFromChannels(String[] paths) {
|
||||
for (String p : paths) {
|
||||
Long v = readLongFromLine(p);
|
||||
@@ -671,15 +535,6 @@ public class HudMetrics {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* ADDITIVE charging fallback from {@code /sys/class/power_supply/*}, consulted ONLY when the
|
||||
* framework gave no usable charge state ({@code EXTRA_STATUS == UNKNOWN} or a null battery intent).
|
||||
* A charger/input supply reporting {@code online == 1} — or the battery's own {@code status} reading
|
||||
* "Charging"/"Full" — means charging. Returns TRUE when charging is positively detected, FALSE when a
|
||||
* status/online node is readable but not charging, or null when nothing usable exists (so the caller
|
||||
* keeps its own default). Never reached on devices whose BatteryManager reports a real status
|
||||
* (e.g. Adreno phones/handhelds), so it cannot change their reading.
|
||||
*/
|
||||
private static Boolean readChargingFromPowerSupply() {
|
||||
File[] supplies = new File("/sys/class/power_supply").listFiles();
|
||||
if (supplies == null || supplies.length == 0) return null;
|
||||
@@ -690,14 +545,12 @@ public class HudMetrics {
|
||||
type = type == null ? "" : type.trim().toLowerCase(Locale.US);
|
||||
boolean isBattery = type.equals("battery") || name.equals("battery") || name.equals("bms");
|
||||
if (isBattery) {
|
||||
// The battery's own status string is the most direct charge-state signal.
|
||||
String st = readFirstLine(new File(supply, "status").getPath());
|
||||
if (st == null) continue;
|
||||
st = st.trim().toLowerCase(Locale.US);
|
||||
sawSignal = Boolean.FALSE; // "discharging"/"not charging" both land here
|
||||
sawSignal = Boolean.FALSE;
|
||||
if (st.equals("charging") || st.equals("full")) return Boolean.TRUE;
|
||||
} else {
|
||||
// A charger / power-input supply (ac/usb/wireless/mains/dc): online==1 → external power in.
|
||||
Long online = readLongFromLine(new File(supply, "online").getPath());
|
||||
if (online == null) continue;
|
||||
sawSignal = Boolean.FALSE;
|
||||
@@ -712,55 +565,6 @@ public class HudMetrics {
|
||||
private static final double RUNTIME_SMOOTHING_OLD_WEIGHT = 0.65;
|
||||
private static final double RUNTIME_SMOOTHING_NEW_WEIGHT = 0.35;
|
||||
|
||||
/**
|
||||
* Legacy discharge-only power reading used by the classic overlays + {@code PerfHudView}:
|
||||
* watts are reported only while discharging (0 when charging). When {@code dualBattery} is set the
|
||||
* per-cell current channels are summed to correct devices that report only one cell's current.
|
||||
*/
|
||||
public Battery getBattery(boolean dualBattery) {
|
||||
Intent status = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
|
||||
boolean charging = false;
|
||||
int voltageMv = 0;
|
||||
if (status != null) {
|
||||
charging = status.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0) != 0;
|
||||
voltageMv = status.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0);
|
||||
} else {
|
||||
// ADDITIVE: no battery intent → best-effort power_supply charge probe (default stays false).
|
||||
// Never reached on devices that deliver ACTION_BATTERY_CHANGED (e.g. Adreno).
|
||||
Boolean sysCharging = readChargingFromPowerSupply();
|
||||
if (sysCharging != null) charging = sysCharging;
|
||||
}
|
||||
long microAmps;
|
||||
if (dualBattery) {
|
||||
long sum = 0; int n = 0;
|
||||
for (String path : CURRENT_CHANNELS) {
|
||||
Long v = readLongFromLine(path);
|
||||
if (v != null) { sum += Math.abs(v); n++; }
|
||||
}
|
||||
microAmps = n > 0 ? -sum : readCurrentNowFallback();
|
||||
} else {
|
||||
microAmps = readCurrentNowFallback();
|
||||
}
|
||||
// current_now's SIGN convention is device-dependent — many OEMs (Xiaomi/Poco especially)
|
||||
// report discharge as POSITIVE, the opposite of the AOSP convention. Gating wattage on the
|
||||
// sign therefore reads 0W on battery on those devices (and only shows a value while charging).
|
||||
// Use the magnitude for the power figure; the reliable charge DIRECTION is EXTRA_PLUGGED (the
|
||||
// `charging` flag), which the HUD already uses for the PWR/CHG label.
|
||||
// EXTRA_VOLTAGE reads 0 on some OEM firmwares even though current is fine — fall back to the
|
||||
// power_supply voltage_now (µV → mV) so wattage isn't stuck at 0.
|
||||
if (voltageMv <= 0) {
|
||||
Long uv = readLongFromChannels(VOLTAGE_CHANNELS);
|
||||
if (uv != null && uv > 0) voltageMv = (int) (Math.abs(uv) / 1000L);
|
||||
}
|
||||
// current unit auto-detected (mA vs µA) — see currentRawToAmps.
|
||||
float watts = (voltageMv / 1000f) * currentRawToAmps(microAmps);
|
||||
return new Battery(watts, charging);
|
||||
}
|
||||
|
||||
/**
|
||||
* Full GameNative-parity battery snapshot for the GameNative-style HUD: %, power W (magnitude,
|
||||
* regardless of charge/discharge), smoothed runtime-left estimate, and temperature.
|
||||
*/
|
||||
public Battery collectBattery() {
|
||||
BatteryManager bm = (BatteryManager) context.getSystemService(Context.BATTERY_SERVICE);
|
||||
if (bm == null) return new Battery(0f, false);
|
||||
@@ -771,15 +575,12 @@ public class HudMetrics {
|
||||
|
||||
Intent status = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
|
||||
if (status == null) {
|
||||
// No battery intent at all → additive power_supply charge probe (default stays false).
|
||||
Boolean sysCharging = readChargingFromPowerSupply();
|
||||
return new Battery(0f, sysCharging != null && sysCharging, percent, null, null);
|
||||
}
|
||||
|
||||
int st = status.getIntExtra(BatteryManager.EXTRA_STATUS, BatteryManager.BATTERY_STATUS_UNKNOWN);
|
||||
boolean charging = st == BatteryManager.BATTERY_STATUS_CHARGING || st == BatteryManager.BATTERY_STATUS_FULL;
|
||||
// ADDITIVE: only when the framework reports no usable charge state do we consult power_supply.
|
||||
// A device that reports CHARGING/DISCHARGING/FULL/NOT_CHARGING (e.g. Adreno) never enters this.
|
||||
if (st == BatteryManager.BATTERY_STATUS_UNKNOWN) {
|
||||
Boolean sysCharging = readChargingFromPowerSupply();
|
||||
if (sysCharging != null) charging = sysCharging;
|
||||
@@ -792,23 +593,16 @@ public class HudMetrics {
|
||||
int rawTemp = status.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0);
|
||||
if (rawTemp > 0) tempC = Math.round(rawTemp / 10f);
|
||||
|
||||
// EXTRA_VOLTAGE reads 0 on some OEM firmwares (e.g. HONOR Magic) even though capacity, temp
|
||||
// and current all work — which left wattage stuck at 0.0W. Fall back to the power_supply
|
||||
// voltage_now (µV → mV); if voltage is still unavailable, use power_now (µW) directly.
|
||||
if (voltageMv <= 0) {
|
||||
Long uv = readLongFromChannels(VOLTAGE_CHANNELS);
|
||||
if (uv != null && uv > 0) voltageMv = (int) (Math.abs(uv) / 1000L);
|
||||
}
|
||||
// Wattage = current × voltage, with current UNIT auto-detected (CURRENT_NOW is nominally µA but
|
||||
// many OEMs — e.g. this HONOR — report mA; see batteryCurrentAmps). currentMicroAmps above stays
|
||||
// as-is for the runtime estimate (a ratio, so unit-independent). If neither current nor voltage
|
||||
// resolves, fall back to power_now (µW) directly.
|
||||
float amps = batteryCurrentAmps(bm);
|
||||
float watts = 0f;
|
||||
if (amps > 0f && voltageMv > 0) {
|
||||
watts = (voltageMv / 1000f) * amps;
|
||||
} else {
|
||||
Long uw = readLongFromChannels(POWER_CHANNELS); // µW
|
||||
Long uw = readLongFromChannels(POWER_CHANNELS);
|
||||
if (uw != null && uw != 0L) watts = (float) (Math.abs(uw) / 1_000_000.0);
|
||||
}
|
||||
|
||||
@@ -842,24 +636,12 @@ public class HudMetrics {
|
||||
return minutes + "m";
|
||||
}
|
||||
|
||||
private long readCurrentNowFallback() {
|
||||
BatteryManager bm = (BatteryManager) context.getSystemService(Context.BATTERY_SERVICE);
|
||||
return bm.getLongProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW);
|
||||
}
|
||||
|
||||
/** Raw battery current reading → AMPS, with unit AUTO-DETECT. {@code BATTERY_PROPERTY_CURRENT_NOW}
|
||||
* (and {@code current_now}) are nominally µA, but many OEMs report mA — a small number, whereas a
|
||||
* real µA reading is always huge. So a magnitude < 20000 means the device gave mA. Without this,
|
||||
* wattage on mA-reporting devices came out ~1000× too small → 0.0W even though current & voltage are
|
||||
* fine. Sentinel/zero → 0. (Heuristic mirrors Ludashi-plus WinlatorHUD.getBatteryCurrentAmps().) */
|
||||
private static float currentRawToAmps(long raw) {
|
||||
if (raw == 0L || raw == Long.MIN_VALUE) return 0f;
|
||||
long a = Math.abs(raw);
|
||||
return a < 20000L ? a / 1000f : a / 1_000_000f; // mA → A, else µA → A
|
||||
return a < 20000L ? a / 1000f : a / 1_000_000f;
|
||||
}
|
||||
|
||||
/** Battery current in AMPS for the wattage calc: framework property first, then power_supply
|
||||
* {@code current_now} sysfs (battery/bms/main) when it's unsupported ({@code Long.MIN_VALUE}) or 0. */
|
||||
private float batteryCurrentAmps(BatteryManager bm) {
|
||||
long raw = (bm != null) ? bm.getLongProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW) : 0L;
|
||||
if (raw == 0L || raw == Long.MIN_VALUE) {
|
||||
@@ -869,11 +651,6 @@ public class HudMetrics {
|
||||
return currentRawToAmps(raw);
|
||||
}
|
||||
|
||||
// =======================================================================
|
||||
// Clock frequencies (best-effort, nullable)
|
||||
// =======================================================================
|
||||
|
||||
/** Peak CPU core clock in MHz (max scaling_cur_freq across cores), or null when unreadable. */
|
||||
public Integer getCpuClockMhz() {
|
||||
int cores = Runtime.getRuntime().availableProcessors();
|
||||
long maxKhz = 0;
|
||||
@@ -882,29 +659,26 @@ public class HudMetrics {
|
||||
if (cur != null && cur > maxKhz) maxKhz = cur;
|
||||
}
|
||||
if (maxKhz <= 0) return null;
|
||||
return (int) (maxKhz / 1000L); // kHz → MHz
|
||||
return (int) (maxKhz / 1000L);
|
||||
}
|
||||
|
||||
private List<String> gpuClockPathsCache = null;
|
||||
private static final String[] GPU_CLOCK_PATHS = {
|
||||
"/sys/class/kgsl/kgsl-3d0/gpuclk", // Adreno, Hz
|
||||
"/sys/class/kgsl/kgsl-3d0/devfreq/cur_freq", // Adreno devfreq, Hz
|
||||
"/sys/class/kgsl/kgsl-3d0/clock_mhz", // some kernels, already MHz
|
||||
"/sys/kernel/gpu/gpu_clock", // Mali vendor node, MHz
|
||||
"/sys/devices/platform/gpusysfs/gpu_clock", // Exynos Mali vendor node, MHz
|
||||
"/sys/class/misc/mali0/device/clock", // Mali, kHz/MHz
|
||||
"/sys/class/devfreq/gpu/cur_freq", // generic devfreq gpu, Hz
|
||||
// ── Additive cross-vendor fallbacks (appended LAST: only reached when every node above
|
||||
// is unreadable, so Adreno/Mali devices that already resolve are unaffected). ──
|
||||
"/sys/kernel/ged/hal/current_freqency", // MediaTek GED (vendor's spelling), kHz
|
||||
"/sys/kernel/ged/hal/gpu_clock", // MediaTek GED alt, MHz
|
||||
"/sys/class/kgsl/kgsl-3d0/gpuclk",
|
||||
"/sys/class/kgsl/kgsl-3d0/devfreq/cur_freq",
|
||||
"/sys/class/kgsl/kgsl-3d0/clock_mhz",
|
||||
"/sys/kernel/gpu/gpu_clock",
|
||||
"/sys/devices/platform/gpusysfs/gpu_clock",
|
||||
"/sys/class/misc/mali0/device/clock",
|
||||
"/sys/class/devfreq/gpu/cur_freq",
|
||||
"/sys/kernel/ged/hal/current_freqency",
|
||||
"/sys/kernel/ged/hal/gpu_clock",
|
||||
};
|
||||
|
||||
private List<String> discoverGpuClockPaths() {
|
||||
if (gpuClockPathsCache != null) return gpuClockPathsCache;
|
||||
LinkedHashSet<String> found = new LinkedHashSet<>();
|
||||
for (String p : GPU_CLOCK_PATHS) if (new File(p).canRead()) found.add(p);
|
||||
// Vendor-agnostic devfreq walk: any gpu/mali/panfrost/xclipse/sgpu node's cur_freq (Hz).
|
||||
File[] devfreqRoots = {
|
||||
new File("/sys/class/devfreq"),
|
||||
new File("/sys/devices/virtual/devfreq"),
|
||||
@@ -928,49 +702,31 @@ public class HudMetrics {
|
||||
return gpuClockPathsCache;
|
||||
}
|
||||
|
||||
/** GPU clock in MHz (Adreno KGSL / devfreq / Mali nodes), or null when no source reports it. */
|
||||
public Integer getGpuClockMhz() {
|
||||
for (String p : discoverGpuClockPaths()) {
|
||||
Long raw = readLongFromLine(p);
|
||||
if (raw == null || raw <= 0) continue;
|
||||
long mhz;
|
||||
if (raw >= 1_000_000L) mhz = raw / 1_000_000L; // Hz
|
||||
else if (raw >= 10_000L) mhz = raw / 1_000L; // kHz (defensive)
|
||||
else mhz = raw; // already MHz
|
||||
if (raw >= 1_000_000L) mhz = raw / 1_000_000L;
|
||||
else if (raw >= 10_000L) mhz = raw / 1_000L;
|
||||
else mhz = raw;
|
||||
if (mhz >= 1 && mhz <= 3000) return (int) mhz;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// =======================================================================
|
||||
// VRAM (best-effort, Java-only sysfs — no native rebuild)
|
||||
// =======================================================================
|
||||
// Covered here in pure Java: Adreno KGSL (bytes mapped/allocated) and amdgpu-style drm nodes
|
||||
// (Samsung Xclipse / "sgpu", AMD-on-Exynos), which expose mem_info_vram_used/_total directly.
|
||||
// TODO(native): VK_EXT_memory_budget as a vendor-agnostic fallback for Mali/PowerVR, which expose
|
||||
// no world-readable VRAM node. FEASIBILITY (checked 2026-07): the compositor's Vulkan layer
|
||||
// (app/src/main/cpp/winlator/vulkan.c) creates an EPHEMERAL VkInstance/VkPhysicalDevice inside
|
||||
// getRenderer() and destroys it every call — it holds no reusable device and loads only the
|
||||
// properties/extension entrypoints, not vkGetPhysicalDeviceMemoryProperties2. Wiring the budget
|
||||
// query therefore means a new JNI method + enabling VK_KHR_get_physical_device_properties2 /
|
||||
// VK_EXT_memory_budget at instance create + an NDK rebuild — out of scope for a source-only pass.
|
||||
// CAVEAT to document if/when added: this HUD is an app-side overlay, NOT in the game's Vulkan
|
||||
// device, so an app-created instance reports the DEVICE-WIDE heap budget (a GPU-memory-pressure
|
||||
// proxy), not the game's per-process VRAM. Devices with no readable node return null → HUD hides VRAM.
|
||||
private List<String> vramUsedPathsCache = null;
|
||||
private static final String[] VRAM_USED_PATHS = {
|
||||
"/sys/class/kgsl/kgsl-3d0/gpumem_mapped", // bytes currently mapped to the GPU
|
||||
"/sys/class/kgsl/kgsl-3d0/page_alloc", // bytes allocated to the KGSL page pool
|
||||
"/sys/class/kgsl/kgsl-3d0/mapped", // alt name on some kernels
|
||||
"/sys/class/drm/card0/device/mem_info_vram_used",// amdgpu / Xclipse (sgpu), bytes
|
||||
"/sys/class/kgsl/kgsl-3d0/page_alloc_max", // high-water fallback
|
||||
"/sys/class/kgsl/kgsl-3d0/gpumem_mapped",
|
||||
"/sys/class/kgsl/kgsl-3d0/page_alloc",
|
||||
"/sys/class/kgsl/kgsl-3d0/mapped",
|
||||
"/sys/class/drm/card0/device/mem_info_vram_used",
|
||||
"/sys/class/kgsl/kgsl-3d0/page_alloc_max",
|
||||
};
|
||||
// Total-VRAM companions (amdgpu exposes one; used only by the diagnostics report).
|
||||
private static final String[] VRAM_TOTAL_PATHS = {
|
||||
"/sys/class/drm/card0/device/mem_info_vram_total",
|
||||
};
|
||||
|
||||
/** Used GPU memory in bytes from Adreno KGSL sysfs, or null when this device exposes nothing readable. */
|
||||
public Long getVramUsedBytes() {
|
||||
if (vramUsedPathsCache == null) {
|
||||
ArrayList<String> found = new ArrayList<>();
|
||||
@@ -986,50 +742,33 @@ public class HudMetrics {
|
||||
|
||||
private static Long sanitizeVramBytes(Long v) {
|
||||
if (v == null) return null;
|
||||
if (v < (1L << 20)) return null; // < 1 MiB → idle-zero / not a byte count
|
||||
if (v > 64L * (1L << 30)) return null; // > 64 GiB → not bytes
|
||||
if (v < (1L << 20)) return null;
|
||||
if (v > 64L * (1L << 30)) return null;
|
||||
return v;
|
||||
}
|
||||
|
||||
/** Used GPU memory as "x.xGiB" (or "yMiB"), or null when no VRAM source is readable. */
|
||||
public String getVramUsedText() {
|
||||
Long b = getVramUsedBytes();
|
||||
return b == null ? null : formatGiB(b);
|
||||
}
|
||||
|
||||
private static String formatGiB(long bytes) {
|
||||
return String.format(Locale.US, "%.1fGiB", bytes / (1024.0 * 1024.0 * 1024.0));
|
||||
}
|
||||
|
||||
// =======================================================================
|
||||
// Single cached snapshot — read EVERYTHING once per HUD refresh
|
||||
// =======================================================================
|
||||
|
||||
/**
|
||||
* Immutable point-in-time reading of every metric the DroidDeck HUD draws. Collected in one pass by
|
||||
* {@link #snapshot()} so the view never touches sysfs / BatteryManager during draw (the user's
|
||||
* explicit ask: one collection pass, cached, so gameplay isn't strained). All numeric fields are
|
||||
* raw (nullable when unreadable); the view formats + colours them.
|
||||
*/
|
||||
public static final class Snapshot {
|
||||
public final Integer cpuPercent; // 0..100 or null
|
||||
public final Integer gpuPercent; // 0..100 or null
|
||||
public final Integer cpuClockMhz; // MHz or null
|
||||
public final Integer gpuClockMhz; // MHz or null
|
||||
public final Integer cpuTempC; // °C or null
|
||||
public final Integer gpuTempC; // °C or null
|
||||
public final Integer cpuPercent;
|
||||
public final Integer gpuPercent;
|
||||
public final Integer cpuClockMhz;
|
||||
public final Integer gpuClockMhz;
|
||||
public final Integer cpuTempC;
|
||||
public final Integer gpuTempC;
|
||||
public final long ramUsedBytes;
|
||||
public final long ramTotalBytes;
|
||||
public final float ramPercent; // 0..100
|
||||
public final Long vramUsedBytes; // bytes or null
|
||||
public final Battery battery; // never null
|
||||
// ---- Mega-only extras ----
|
||||
public final int[] perCorePercent; // per-core 0..100, -1 unknown (never null; may be empty)
|
||||
public final int[] perCoreClockMhz; // per-core MHz, 0 unknown (never null; may be empty)
|
||||
public final Long swapUsedBytes; // bytes or null (no swap)
|
||||
public final Long swapTotalBytes; // bytes or null
|
||||
public final Long netDownBps; // bytes/sec down, or null (first sample / unreadable)
|
||||
public final Long netUpBps; // bytes/sec up, or null
|
||||
public final float ramPercent;
|
||||
public final Long vramUsedBytes;
|
||||
public final Battery battery;
|
||||
public final int[] perCorePercent;
|
||||
public final int[] perCoreClockMhz;
|
||||
public final Long swapUsedBytes;
|
||||
public final Long swapTotalBytes;
|
||||
public final Long netDownBps;
|
||||
public final Long netUpBps;
|
||||
|
||||
Snapshot(Integer cpuPercent, Integer gpuPercent, Integer cpuClockMhz, Integer gpuClockMhz,
|
||||
Integer cpuTempC, Integer gpuTempC, long ramUsedBytes, long ramTotalBytes,
|
||||
@@ -1066,7 +805,6 @@ public class HudMetrics {
|
||||
}
|
||||
}
|
||||
|
||||
/** One collection pass over every metric. Call from the HUD's own ~1 s refresh thread, never draw. */
|
||||
public Snapshot snapshot() {
|
||||
if (mango != null) return mangoSnapshot(mango);
|
||||
Integer cpu = getCpuUsagePercent();
|
||||
@@ -1102,7 +840,6 @@ public class HudMetrics {
|
||||
net == null ? null : net[0], net == null ? null : net[1]);
|
||||
}
|
||||
|
||||
// DroidDeck: the same snapshot with MangoHud's sources and rounding (see MangoReadings).
|
||||
private Snapshot mangoSnapshot(MangoReadings m) {
|
||||
MangoReadings.Cpu cpu = m.cpu();
|
||||
MangoReadings.Memory mem = m.memory();
|
||||
@@ -1121,11 +858,6 @@ public class HudMetrics {
|
||||
net == null ? null : net[0], net == null ? null : net[1]);
|
||||
}
|
||||
|
||||
// =======================================================================
|
||||
// Mega-view extras: per-core CPU, swap, network (best-effort, nullable)
|
||||
// =======================================================================
|
||||
|
||||
/** Per-core clock in MHz (each core's {@code scaling_cur_freq}); 0 for a core that can't be read. */
|
||||
public int[] getPerCoreClockMhz() {
|
||||
int cores = Runtime.getRuntime().availableProcessors();
|
||||
int[] out = new int[Math.max(0, cores)];
|
||||
@@ -1136,11 +868,9 @@ public class HudMetrics {
|
||||
return out;
|
||||
}
|
||||
|
||||
// Per-core /proc/stat deltas — one prev sample per core, seeded on the first read.
|
||||
private long[] lastCoreTotal = null;
|
||||
private long[] lastCoreIdle = null;
|
||||
|
||||
/** Per-core CPU usage 0..100 from the {@code cpuN} /proc/stat deltas; -1 for a core not yet sampled. */
|
||||
public int[] readPerCorePercent() {
|
||||
int cores = Runtime.getRuntime().availableProcessors();
|
||||
int[] out = new int[Math.max(0, cores)];
|
||||
@@ -1153,8 +883,8 @@ public class HudMetrics {
|
||||
try (BufferedReader r = new BufferedReader(new FileReader("/proc/stat"))) {
|
||||
String line;
|
||||
while ((line = r.readLine()) != null) {
|
||||
if (!line.startsWith("cpu")) break; // cpu lines are first; stop at the block end
|
||||
if (line.length() < 4 || !Character.isDigit(line.charAt(3))) continue; // skip aggregate "cpu "
|
||||
if (!line.startsWith("cpu")) break;
|
||||
if (line.length() < 4 || !Character.isDigit(line.charAt(3))) continue;
|
||||
String[] parts = line.trim().split("\\s+");
|
||||
int core;
|
||||
try { core = Integer.parseInt(parts[0].substring(3)); } catch (Exception e) { continue; }
|
||||
@@ -1165,8 +895,8 @@ public class HudMetrics {
|
||||
try {
|
||||
long v = Long.parseLong(parts[i]);
|
||||
total += v;
|
||||
if (i == 4) idle = v; // idle
|
||||
else if (i == 5) idle += v; // + iowait
|
||||
if (i == 4) idle = v;
|
||||
else if (i == 5) idle += v;
|
||||
} catch (NumberFormatException e) { ok = false; break; }
|
||||
}
|
||||
if (!ok) continue;
|
||||
@@ -1179,10 +909,6 @@ public class HudMetrics {
|
||||
}
|
||||
}
|
||||
} catch (Exception ignored) {}
|
||||
// Frequency fallback for any core /proc/stat couldn't give us — restricted on some firmwares
|
||||
// (e.g. HONOR / Android 16), which is also why the aggregate getCpuUsagePercent() falls back.
|
||||
// scaling_cur_freq / cpuinfo_max_freq is a load proxy (per-core clocks ARE readable there), and
|
||||
// it also seeds the very first sample. Cores with a real /proc/stat delta keep it (no regression).
|
||||
for (int i = 0; i < out.length; i++) {
|
||||
if (out[i] >= 0) continue;
|
||||
Long cur = readLongFromLine("/sys/devices/system/cpu/cpu" + i + "/cpufreq/scaling_cur_freq");
|
||||
@@ -1193,7 +919,6 @@ public class HudMetrics {
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Swap {used, total} in bytes from /proc/meminfo, or null when there is no swap. */
|
||||
public long[] getSwapBytes() {
|
||||
long totalKb = -1, freeKb = -1;
|
||||
try (BufferedReader r = new BufferedReader(new FileReader("/proc/meminfo"))) {
|
||||
@@ -1215,10 +940,8 @@ public class HudMetrics {
|
||||
return v == null ? -1 : v;
|
||||
}
|
||||
|
||||
// Net rate: cumulative rx/tx bytes + the wall-clock of the previous read → bytes/sec.
|
||||
private long lastNetRx = -1, lastNetTx = -1, lastNetWallMs = 0;
|
||||
|
||||
/** Network {down, up} in bytes/sec (all interfaces except loopback), or null on the first/failed read. */
|
||||
public long[] readNetRateBps() {
|
||||
long rx = 0, tx = 0;
|
||||
boolean any = false;
|
||||
@@ -1241,7 +964,7 @@ public class HudMetrics {
|
||||
long now = SystemClock.elapsedRealtime();
|
||||
long prevRx = lastNetRx, prevTx = lastNetTx, prevWall = lastNetWallMs;
|
||||
lastNetRx = rx; lastNetTx = tx; lastNetWallMs = now;
|
||||
if (prevRx < 0 || prevWall <= 0) return null; // seed
|
||||
if (prevRx < 0 || prevWall <= 0) return null;
|
||||
long dt = now - prevWall;
|
||||
if (dt <= 0) return null;
|
||||
long down = Math.max(0L, (rx - prevRx) * 1000L / dt);
|
||||
@@ -1249,20 +972,8 @@ public class HudMetrics {
|
||||
return new long[]{down, up};
|
||||
}
|
||||
|
||||
// =======================================================================
|
||||
// Diagnostics report (invoked ONLY on user tap — never on the HUD refresh path)
|
||||
// =======================================================================
|
||||
|
||||
/**
|
||||
* One-tap plain-text device report for the "Export HUD diagnostics" action: for every metric it
|
||||
* lists the resolved source path/API + current value, or MISS + the exact candidates it tried,
|
||||
* followed by an "exists on this device" dump (thermal zone types, devfreq/kgsl/mali nodes) so a
|
||||
* device owner can send back the real path for anything that missed. Does a short prime+sample so
|
||||
* delta-based readers (CPU%/GPU%/net) report a live value. Run OFF the main thread.
|
||||
*/
|
||||
public String buildDiagnosticsReport(Context ctxIn) {
|
||||
final Context ctx = ctxIn != null ? ctxIn : this.context;
|
||||
// Prime the delta-based readers, wait, then take a live sample.
|
||||
snapshot();
|
||||
try { Thread.sleep(350L); } catch (InterruptedException ignored) { Thread.currentThread().interrupt(); }
|
||||
Snapshot s = snapshot();
|
||||
@@ -1281,7 +992,6 @@ public class HudMetrics {
|
||||
|
||||
sb.append("\n== Metrics ==\n");
|
||||
|
||||
// ---- CPU ----
|
||||
boolean procStat = new File("/proc/stat").canRead();
|
||||
if (s.cpuPercent != null) {
|
||||
metricHit(sb, "CPU %", s.cpuPercent + "%",
|
||||
@@ -1292,7 +1002,6 @@ public class HudMetrics {
|
||||
"/sys/devices/system/cpu/cpu*/cpufreq/scaling_cur_freq");
|
||||
}
|
||||
|
||||
// Per-core %
|
||||
StringBuilder cores = new StringBuilder();
|
||||
for (int i = 0; i < s.perCorePercent.length; i++) {
|
||||
if (i > 0) cores.append(' ');
|
||||
@@ -1304,7 +1013,6 @@ public class HudMetrics {
|
||||
else
|
||||
metricMiss(sb, "Per-core %", "/proc/stat");
|
||||
|
||||
// Per-core clock
|
||||
StringBuilder coreClk = new StringBuilder();
|
||||
for (int i = 0; i < s.perCoreClockMhz.length; i++) {
|
||||
if (i > 0) coreClk.append(' ');
|
||||
@@ -1317,7 +1025,6 @@ public class HudMetrics {
|
||||
else
|
||||
metricMiss(sb, "CPU clock", "/sys/devices/system/cpu/cpu*/cpufreq/scaling_cur_freq");
|
||||
|
||||
// CPU temp
|
||||
String cpuTempPath = resolveTempPath(discoverPrioritizedCpuTempPaths());
|
||||
if (s.cpuTempC != null && cpuTempPath != null)
|
||||
metricHit(sb, "CPU temp", s.cpuTempC + "°C", cpuTempPath);
|
||||
@@ -1325,7 +1032,6 @@ public class HudMetrics {
|
||||
metricMiss(sb, "CPU temp",
|
||||
"/sys/class/thermal/thermal_zone*/temp (types: cpu*/cpuss/tsens/mtktscpu/s5p-tmu/soc)");
|
||||
|
||||
// ---- GPU ----
|
||||
String gpuUsagePath = firstReadableGpuUsagePath();
|
||||
if (s.gpuPercent != null && gpuUsagePath != null)
|
||||
metricHit(sb, "GPU %", s.gpuPercent + "%", gpuUsagePath);
|
||||
@@ -1347,7 +1053,6 @@ public class HudMetrics {
|
||||
"/sys/class/kgsl/kgsl-3d0/temp", "/sys/class/misc/mali0/device/temp",
|
||||
"/sys/class/thermal/thermal_zone*/temp (types: gpu*/gpuss/g3d/kgsl/mali/mtktsgpu)");
|
||||
|
||||
// ---- Memory ----
|
||||
metricHit(sb, "RAM", s.ramUsedText() + " / " + s.ramTotalText()
|
||||
+ " (" + Math.round(s.ramPercent) + "%)", "ActivityManager.MemoryInfo");
|
||||
if (s.swapUsedBytes != null)
|
||||
@@ -1355,7 +1060,6 @@ public class HudMetrics {
|
||||
else
|
||||
metricMiss(sb, "SWAP", "/proc/meminfo (SwapTotal=0 or unreadable)");
|
||||
|
||||
// VRAM
|
||||
String vramPath = firstReadableVramUsedPath();
|
||||
if (s.vramUsedBytes != null && vramPath != null) {
|
||||
Long total = readFirstReadableLong(VRAM_TOTAL_PATHS);
|
||||
@@ -1366,14 +1070,12 @@ public class HudMetrics {
|
||||
new ArrayList<>(), VRAM_USED_PATHS);
|
||||
}
|
||||
|
||||
// ---- Net ----
|
||||
if (s.netDownBps != null)
|
||||
metricHit(sb, "NET", formatRate(s.netDownBps) + " down / " + formatRate(s.netUpBps) + " up",
|
||||
"/proc/net/dev");
|
||||
else
|
||||
metricMiss(sb, "NET", "/proc/net/dev (first sample or unreadable)");
|
||||
|
||||
// ---- Battery ----
|
||||
Battery b = s.battery;
|
||||
StringBuilder bat = new StringBuilder();
|
||||
bat.append(b.percent != null ? b.percent + "%" : "?%")
|
||||
@@ -1383,7 +1085,6 @@ public class HudMetrics {
|
||||
.append(b.runtimeText != null ? ", " + b.runtimeText : "");
|
||||
metricHit(sb, "Battery", bat.toString(), "BatteryManager + /sys/class/power_supply");
|
||||
|
||||
// ---- Exists-on-device dump ----
|
||||
appendExistsDump(sb);
|
||||
return sb.toString();
|
||||
}
|
||||
@@ -1415,7 +1116,7 @@ public class HudMetrics {
|
||||
}
|
||||
|
||||
private String firstReadableVramUsedPath() {
|
||||
if (vramUsedPathsCache == null) getVramUsedBytes(); // builds the cache
|
||||
if (vramUsedPathsCache == null) getVramUsedBytes();
|
||||
if (vramUsedPathsCache == null) return null;
|
||||
for (String p : vramUsedPathsCache) if (sanitizeVramBytes(readLongFromLine(p)) != null) return p;
|
||||
return null;
|
||||
@@ -1479,12 +1180,6 @@ public class HudMetrics {
|
||||
appendGpuNoRootProbes(sb);
|
||||
}
|
||||
|
||||
/** Probes for a ROOT-FREE GPU-load path on locked-sysfs Adreno devices (SM8750/HONOR etc.):
|
||||
* (1) can the app open the KGSL device node? The sysfs mirror (/sys/class/kgsl) is SELinux-blocked
|
||||
* (vendor_sysfs_kgsl), but /dev/kgsl-3d0 is labeled gpu_device and is normally app-openable —
|
||||
* that's the door for reading GPU busy via ioctl perf-counters instead of sysfs.
|
||||
* (2) is there an app-readable devfreq node under /sys/devices/platform that bypasses the blocked
|
||||
* /sys/class/kgsl symlink (a free win for at least the clock). */
|
||||
private void appendGpuNoRootProbes(StringBuilder sb) {
|
||||
sb.append("-- GPU no-root reachability probes --\n");
|
||||
sb.append(" /dev/kgsl-3d0 open O_RDWR: ")
|
||||
@@ -1516,8 +1211,6 @@ public class HudMetrics {
|
||||
if (!found) sb.append(" devfreq (platform kgsl): (no app-readable node found)\n");
|
||||
}
|
||||
|
||||
/** open()+close() a path with the given flags, reporting OK or the errno class — used to test
|
||||
* whether the app's sandbox can reach a device node without root. */
|
||||
private static String probeOpen(String path, int flags) {
|
||||
java.io.FileDescriptor fd = null;
|
||||
try {
|
||||
@@ -1530,8 +1223,6 @@ public class HudMetrics {
|
||||
}
|
||||
}
|
||||
|
||||
/** Battery-wattage inputs: which power_supply nodes this app can actually READ, and their raw
|
||||
* values. Confirms the voltage_now / power_now fallback for devices where EXTRA_VOLTAGE is 0. */
|
||||
private void appendPowerSupplyDump(StringBuilder sb) {
|
||||
sb.append("-- /sys/class/power_supply (battery watts inputs) --\n");
|
||||
File[] nodes = new File("/sys/class/power_supply").listFiles();
|
||||
@@ -1582,9 +1273,6 @@ public class HudMetrics {
|
||||
return names.length() == 0 ? "(no readable files)" : names.toString();
|
||||
}
|
||||
|
||||
// =======================================================================
|
||||
// Low-level helpers
|
||||
// =======================================================================
|
||||
private static int clampPercent(int v) { return v < 0 ? 0 : (v > 100 ? 100 : v); }
|
||||
|
||||
private static String readFirstLine(String path) {
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
* link to https://github.com/The412Banner/FusionHUD in the project documentation
|
||||
* AND in the in-app credits/about screen.
|
||||
*
|
||||
* Ported to DroidDeck from FusionHUD (Bannerlator's HUD); DroidDeck changes are marked in the code.
|
||||
* Ported to DroidDeck from FusionHUD (Bannerlator's HUD) and modified for DroidDeck.
|
||||
*/
|
||||
|
||||
package com.droiddeck.launcher.hud;
|
||||
@@ -20,17 +20,14 @@ import java.util.Iterator;
|
||||
public class KeyValueSet implements Iterable<String[]> {
|
||||
private String data = "";
|
||||
|
||||
// Default constructor for an empty KeyValueSet
|
||||
public KeyValueSet() {
|
||||
this.data = "";
|
||||
}
|
||||
|
||||
// Constructor to initialize with a string representation of key-value pairs
|
||||
public KeyValueSet(String data) {
|
||||
this.data = data != null && !data.isEmpty() ? data : "";
|
||||
}
|
||||
|
||||
// Helper method to find the start and end indices of a key in the data string
|
||||
private int[] indexOfKey(String key) {
|
||||
int start = 0;
|
||||
int end = data.indexOf(",");
|
||||
@@ -48,37 +45,31 @@ public class KeyValueSet implements Iterable<String[]> {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Method to get the value associated with a key, or an empty string if the key is not present
|
||||
public String get(String key) {
|
||||
for (String[] keyValue : this) if (keyValue[0].equals(key)) return keyValue[1];
|
||||
return "";
|
||||
}
|
||||
|
||||
// Method to get the value associated with a key, or a fallback value if the key is not present
|
||||
public String get(String key, String fallback) {
|
||||
for (String[] keyValue : this) if (keyValue[0].equals(key)) return keyValue[1];
|
||||
return fallback;
|
||||
}
|
||||
|
||||
// Method to get a boolean value associated with a key, or a fallback value if the key is not present
|
||||
public boolean getBoolean(String key, boolean fallback) {
|
||||
String value = get(key);
|
||||
if (value.isEmpty()) return fallback;
|
||||
return value.equals("1") || value.equals("t") || value.equalsIgnoreCase("true");
|
||||
}
|
||||
|
||||
// Method to get a float value associated with a key, or a fallback value if the key is not present
|
||||
public float getFloat(String key, float fallback) {
|
||||
String value = get(key);
|
||||
try {
|
||||
if (!value.isEmpty()) return Float.parseFloat(value);
|
||||
} catch (NumberFormatException e) {
|
||||
// Ignore exception and return fallback
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
// Method to set a value for a key in the key-value data
|
||||
public void put(String key, Object value) {
|
||||
int[] range = indexOfKey(key);
|
||||
if (range != null) {
|
||||
@@ -88,21 +79,15 @@ public class KeyValueSet implements Iterable<String[]> {
|
||||
}
|
||||
}
|
||||
|
||||
// Method to set a float value for a key in the key-value data
|
||||
public void put(String key, float value) {
|
||||
put(key, String.valueOf(value));
|
||||
}
|
||||
|
||||
// Iterator implementation for key-value pairs in the format [key, value]
|
||||
@NonNull
|
||||
@Override
|
||||
public Iterator<String[]> iterator() {
|
||||
final int[] start = {0};
|
||||
final int[] end = {data.indexOf(",")};
|
||||
// A single-item config (no comma) gives indexOf == -1, making hasNext() (start < end)
|
||||
// immediately false so the sole pair was never iterated (get() then returned the
|
||||
// fallback). Guard it exactly as next() already does. An empty string still yields
|
||||
// end == 0 → no iteration, which is correct.
|
||||
if (end[0] == -1) end[0] = data.length();
|
||||
final String[] item = new String[2];
|
||||
return new Iterator<String[]>() {
|
||||
|
||||
@@ -3,12 +3,6 @@ package com.droiddeck.launcher.hud
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* The readings Steam's performance overlay shows in a DroidDeck session (Valve's mangohud 20260902.1,
|
||||
* tools/mangoapp), taken from the files the session hands it and computed the same way, so the two
|
||||
* overlays agree. Sources and formulas follow that build: cpu.cpp calculateCPUData, deckard_temp.cpp,
|
||||
* msm.cpp getQcomGpuInfo, memory.cpp update_meminfo and battery.cpp getPercent / getPower.
|
||||
*/
|
||||
internal class MangoReadings(private val sessionDir: File, private val rootDir: File) {
|
||||
class Cpu(val percent: Int, val perCore: IntArray)
|
||||
class Memory(val usedBytes: Long, val totalBytes: Long, val swapUsedBytes: Long, val swapTotalBytes: Long)
|
||||
@@ -17,7 +11,6 @@ internal class MangoReadings(private val sessionDir: File, private val rootDir:
|
||||
private val cpuTimes = HashMap<String, LongArray>()
|
||||
private val cpuPercents = HashMap<String, Int>()
|
||||
|
||||
/** Total and per-core load from the session's /proc/stat (DroidDeck's stand-in when the app can't read it). */
|
||||
@JvmOverloads
|
||||
fun cpu(stat: File = statFile()): Cpu? {
|
||||
val lines = runCatching { stat.readLines() }.getOrNull() ?: return null
|
||||
@@ -38,7 +31,6 @@ internal class MangoReadings(private val sessionDir: File, private val rootDir:
|
||||
File(sessionDir, "proc-stat").takeIf { !File("/proc/stat").canRead() && it.isFile } ?: File("/proc/stat")
|
||||
|
||||
private fun cpuPercent(key: String, v: LongArray): Int {
|
||||
// user nice system idle iowait irq softirq steal guest guest_nice; guest time is already in user.
|
||||
val user = v[0] - v[8]
|
||||
val nice = v[1] - v[9]
|
||||
val systemAll = v[2] + v[5] + v[6]
|
||||
@@ -55,7 +47,6 @@ internal class MangoReadings(private val sessionDir: File, private val rootDir:
|
||||
return busy.coerceIn(0f, 100f).toInt().also { cpuPercents[key] = it }
|
||||
}
|
||||
|
||||
/** Average of the zones the session types cpuN-thermal, truncated. */
|
||||
fun cpuTempC(): Int? {
|
||||
var sum = 0f
|
||||
var count = 0
|
||||
@@ -85,7 +76,6 @@ internal class MangoReadings(private val sessionDir: File, private val rootDir:
|
||||
return (milli / 1000.0).toInt()
|
||||
}
|
||||
|
||||
/** MemTotal - MemAvailable and SwapTotal - SwapFree from /proc/meminfo. */
|
||||
fun memory(): Memory? {
|
||||
val kb = HashMap<String, Long>()
|
||||
runCatching {
|
||||
@@ -102,10 +92,8 @@ internal class MangoReadings(private val sessionDir: File, private val rootDir:
|
||||
return Memory((total - available) * 1024, total * 1024, (swapTotal - swapFree) * 1024, swapTotal * 1024)
|
||||
}
|
||||
|
||||
/** The KGSL total DroidDeck shares with the session (GpuMemComponent). */
|
||||
fun vramBytes(): Long? = fresh(File(rootDir, VRAM_FILE), VRAM_FRESH_MS)?.let(::readLong)
|
||||
|
||||
/** BAT* under the session's power_supply (BatteryComponent): no watts while charging, full or unknown. */
|
||||
fun battery(): Battery? {
|
||||
val dirs = File(sessionDir, "sys/power_supply").listFiles { f -> f.name.contains("BAT") }?.sortedBy { it.name }
|
||||
if (dirs.isNullOrEmpty()) return null
|
||||
@@ -149,7 +137,6 @@ internal class MangoReadings(private val sessionDir: File, private val rootDir:
|
||||
private fun readLong(file: File): Long? = runCatching { file.readText().trim().toLong() }.getOrNull()
|
||||
private fun readFloat(file: File): Float? = runCatching { file.readLines().first().trim().toFloat() }.getOrNull()
|
||||
|
||||
/** std::stod on the first line: the leading number, "6 %" -> 6. */
|
||||
fun leadingNumber(file: File): Double? = runCatching {
|
||||
Regex("^\\s*-?\\d+(\\.\\d+)?").find(file.readLines().first())?.value?.trim()?.toDouble()
|
||||
}.getOrNull()
|
||||
|
||||
@@ -612,7 +612,6 @@ public class FakeInputWriter {
|
||||
for (int i = 0; i < length; i++) output[9 + i] = ring.get(TRITON_OUTPUT_OFFSET + i);
|
||||
nativeStoreFence();
|
||||
if (seq != ring.getLong(TRITON_OUTPUT_SEQ_OFFSET)) return null;
|
||||
// Acknowledge the exact report sequence taken so a concurrent timeout overwrite cannot lose its length.
|
||||
ring.putInt(TRITON_OUTPUT_ACK_OFFSET, (int) seq);
|
||||
nativeStoreFence();
|
||||
return output;
|
||||
|
||||
@@ -2,7 +2,6 @@ package com.droiddeck.launcher.input
|
||||
|
||||
import android.content.Context
|
||||
|
||||
/** Global defaults with optional overrides for the currently focused game. */
|
||||
object GesturePrefs {
|
||||
private fun prefs(context: Context) = context.getSharedPreferences("touch_gestures", Context.MODE_PRIVATE)
|
||||
|
||||
|
||||
@@ -2,7 +2,6 @@ package com.droiddeck.launcher.input
|
||||
|
||||
import android.view.MotionEvent
|
||||
|
||||
/** Keeps split Android touch targets from restarting one shared gesture recognizer. */
|
||||
internal class GestureTouchStreamGate {
|
||||
enum class Source { SURFACE, SCREEN_KEYS, ON_SCREEN_CONTROLS }
|
||||
|
||||
|
||||
@@ -37,7 +37,6 @@ 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 (!HomeGuideInput.isHome(event.keyCode) || !PadBridge.isControllerKeyEvent(event)) return false
|
||||
return input.onKeyEvent(event, enabled() && HomeApp.isDefault(context))
|
||||
}
|
||||
|
||||
@@ -46,7 +46,6 @@ class HomeGuideInput(private val setPressed: (Boolean) -> Unit, private val onCa
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
private const val DUO_QUICK_MENU_SCAN_CODE = 194
|
||||
|
||||
@@ -672,7 +672,6 @@ class OnScreenControls(
|
||||
private fun closestSnap(position: Float, targets: List<Float>): Float? =
|
||||
targets.minByOrNull { abs(position - it) }?.takeIf { abs(position - it) <= dp(SNAP_DP) }
|
||||
|
||||
/** Whether a finger going down at ([x], [y]) lands on something here, as [onTouchEvent] decides it. */
|
||||
fun takesTouchAt(x: Float, y: Float): Boolean =
|
||||
editing || keyboardContains(x, y) || (!buttonsOnly && quickContains(x, y)) ||
|
||||
(!quickHidden && (controlAt(x, y) ?: adaptiveStickAt(x, y)) != null)
|
||||
|
||||
@@ -250,11 +250,6 @@ public final class PadBridge {
|
||||
|| device.supportsSource(InputDevice.SOURCE_JOYSTICK));
|
||||
}
|
||||
|
||||
public static boolean isControllerKey(KeyEvent event) {
|
||||
return isFromController(event.getDevice())
|
||||
&& isPadKey(event.getKeyCode(), event.getDevice().getKeyboardType());
|
||||
}
|
||||
|
||||
public static boolean isPadKey(int keyCode, int keyboardType) {
|
||||
if ((keyCode >= KeyEvent.KEYCODE_BUTTON_A && keyCode <= KeyEvent.KEYCODE_BUTTON_MODE)
|
||||
|| (keyCode >= KeyEvent.KEYCODE_BUTTON_1 && keyCode <= KeyEvent.KEYCODE_BUTTON_16)) return true;
|
||||
@@ -616,7 +611,6 @@ public final class PadBridge {
|
||||
private void writePad(PadState report) {
|
||||
if (backQamAxesBlocked && !hasAxes(state)) backQamAxesBlocked = false;
|
||||
long at = android.os.SystemClock.uptimeMillis();
|
||||
// Steam must see the modifier before a partner; preserve quick press/release pairs in order.
|
||||
if (backQamPressed || homeGuidePressed || !backQamWrites.isEmpty()) at += backQamDelayMs;
|
||||
writeBackQamReport(report, at);
|
||||
}
|
||||
|
||||
@@ -36,12 +36,6 @@ fun screenKeyDirections(shape: Int): List<String> = when (shape) {
|
||||
else -> emptyList()
|
||||
}
|
||||
|
||||
val SCREEN_KEY_SHAPES =
|
||||
listOf(
|
||||
SCREEN_KEY_PILL, SCREEN_KEY_ROUND, SCREEN_KEY_CIRCLE, SCREEN_KEY_RECT,
|
||||
SCREEN_KEY_TRIGGER, SCREEN_KEY_DPAD, SCREEN_KEY_STICK,
|
||||
)
|
||||
|
||||
data class ScreenKey(
|
||||
val codes: List<Int>,
|
||||
val x: Float,
|
||||
@@ -55,9 +49,4 @@ data class ScreenKey(
|
||||
val toggle: Boolean = false,
|
||||
val labels: Boolean = true,
|
||||
) {
|
||||
fun shownLabel(context: Context): String = when {
|
||||
text.isNotEmpty() -> text
|
||||
glyph.isNotEmpty() -> glyph
|
||||
else -> screenKeyLabel(context, codes)
|
||||
}
|
||||
}
|
||||
@@ -609,7 +609,6 @@ class ScreenKeys(context: Context, private val sendKey: (Int, Boolean) -> Unit)
|
||||
else -> entry.halfH
|
||||
}
|
||||
|
||||
/** Whether a finger going down at ([x], [y]) lands on something here, as [onTouchEvent] decides it. */
|
||||
fun takesTouchAt(x: Float, y: Float): Boolean = editing || entryAt(x, y) != null
|
||||
|
||||
private fun entryAt(x: Float, y: Float): Entry? = entries.lastOrNull { entry ->
|
||||
|
||||
@@ -19,7 +19,6 @@ enum class SecondScreenMode(val id: String, @StringRes val label: Int) {
|
||||
it != NONE && it.id == remembered && (it != DECK_CONTROLS || deckPad) && (it != DASHBOARD || dashboard) &&
|
||||
(it != DESKTOP || desktop)
|
||||
}?.let { return it }
|
||||
// No pick yet: the dashboard. A pick that can't open right now keeps the old fallback.
|
||||
val picked = entries.any { it != NONE && it.id == remembered }
|
||||
return when {
|
||||
dashboard && !picked -> DASHBOARD
|
||||
|
||||
@@ -112,7 +112,6 @@ class SteamTouchControls(
|
||||
private var selected = -1
|
||||
private var dragOffset = 0f to 0f
|
||||
private var pinchStart = 0f
|
||||
private var pinchScale = 1f
|
||||
private var saving = false
|
||||
private val pendingBindings = HashMap<SteamTouchBindings.Ref, SteamTouchBindings.Binding>()
|
||||
private var pendingColor: FloatArray? = null
|
||||
@@ -244,7 +243,6 @@ class SteamTouchControls(
|
||||
private fun hit(list: List<Element>, x: Float, y: Float): Element? =
|
||||
list.filter { reach(it, x, y) <= 1.15f }.minByOrNull { reach(it, x, y) }
|
||||
|
||||
/** Whether a finger going down at ([x], [y]) lands on something here, as [onTouchEvent] decides it. */
|
||||
fun takesTouchAt(x: Float, y: Float): Boolean = editing || menuOpen || hit(live(), x, y) != null
|
||||
|
||||
private fun live(): List<Element> =
|
||||
@@ -350,17 +348,6 @@ class SteamTouchControls(
|
||||
canvas.restore()
|
||||
}
|
||||
|
||||
private fun drawSteamMark(canvas: Canvas, x: Float, y: Float, r: Float, color: Int) {
|
||||
val p = Paint(Paint.ANTI_ALIAS_FLAG).apply { this.color = color; style = Paint.Style.STROKE; strokeCap = Paint.Cap.ROUND }
|
||||
p.strokeWidth = r * 0.16f
|
||||
canvas.drawCircle(x + r * 0.28f, y - r * 0.18f, r * 0.27f, p)
|
||||
canvas.drawCircle(x + r * 0.28f, y - r * 0.18f, r * 0.1f, Paint(p).apply { style = Paint.Style.FILL })
|
||||
canvas.drawCircle(x - r * 0.3f, y + r * 0.3f, r * 0.17f, p)
|
||||
p.strokeWidth = r * 0.2f
|
||||
canvas.drawLine(x + r * 0.1f, y - r * 0.02f, x - r * 0.2f, y + r * 0.22f, p)
|
||||
canvas.drawLine(x - r * 0.45f, y + r * 0.28f, x - r * 0.95f, y + r * 0.1f, p)
|
||||
}
|
||||
|
||||
private fun drawFace(canvas: Canvas, type: Int, binding: SteamTouchBindings.Binding?, x: Float, y: Float, r: Float,
|
||||
alpha: Int, pressed: Boolean) {
|
||||
val square = isSquare(type)
|
||||
@@ -855,19 +842,6 @@ class SteamTouchControls(
|
||||
invalidate()
|
||||
}
|
||||
|
||||
private fun controlName(type: Int) = when (type) {
|
||||
SteamTouchConfig.DPAD -> context.getString(R.string.touch_dpad)
|
||||
SteamTouchConfig.JOYSTICK_LEFT -> context.getString(R.string.touch_left_stick)
|
||||
SteamTouchConfig.JOYSTICK_RIGHT -> context.getString(R.string.touch_right_stick)
|
||||
SteamTouchConfig.TRACKPAD_LEFT -> context.getString(R.string.deck_left_trackpad)
|
||||
SteamTouchConfig.TRACKPAD_RIGHT -> context.getString(R.string.deck_right_trackpad)
|
||||
SteamTouchConfig.TRACKPAD_CENTER -> context.getString(R.string.deck_surface_trackpad)
|
||||
SteamTouchConfig.STEAM -> "Steam"
|
||||
SteamTouchConfig.THUMB -> context.getString(R.string.touch_menu)
|
||||
SteamTouchConfig.KEYBOARD -> context.getString(R.string.touch_keyboard)
|
||||
else -> label(type)
|
||||
}
|
||||
|
||||
private fun moreMenu() {
|
||||
val host = parent as? android.view.ViewGroup ?: return
|
||||
val density = resources.displayMetrics.density
|
||||
|
||||
@@ -74,8 +74,6 @@ class SteamTouchDevice private constructor(private val buffer: ByteBuffer) {
|
||||
Log.i(TAG, "steam touch: " + if (value) "plugged in" else "unplugged")
|
||||
}
|
||||
|
||||
fun setBattery(percent: Int) = buffer.putInt(OFF_BATTERY, percent.coerceIn(0, 100))
|
||||
|
||||
fun state(): State {
|
||||
repeat(8) {
|
||||
val seq = buffer.getLong(OFF_STATE_SEQ)
|
||||
|
||||
@@ -3,7 +3,6 @@ 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) {
|
||||
|
||||
@@ -28,7 +28,6 @@ public final class TouchscreenGestures {
|
||||
void key(int code, boolean down);
|
||||
void wheel(int steps);
|
||||
void showKeyboard();
|
||||
/** Establish the pointer origin before a relative middle-mouse pan begins. */
|
||||
default void prepareRelativePan() {}
|
||||
default void gesture(Gesture gesture) {}
|
||||
}
|
||||
@@ -97,12 +96,10 @@ public final class TouchscreenGestures {
|
||||
final int code;
|
||||
MouseButton(int code) { this.code = code; }
|
||||
}
|
||||
// Long-press detection
|
||||
private Runnable longPressRunnable;
|
||||
private boolean longPressTriggered;
|
||||
private boolean longPressActionHeld, twoFingerHoldActionHeld, threeFingerHoldActionHeld;
|
||||
|
||||
// Double-tap detection
|
||||
private long lastTapTime;
|
||||
private float lastTapX;
|
||||
private float lastTapY;
|
||||
@@ -110,76 +107,54 @@ public final class TouchscreenGestures {
|
||||
private float doubleTapAnchorX, doubleTapAnchorY;
|
||||
private long singleFingerDownTime;
|
||||
|
||||
// Drag tracking (box selection)
|
||||
private boolean isDragging;
|
||||
private boolean dragButtonPressed;
|
||||
|
||||
// Two-finger tracking
|
||||
private boolean twoFingerDragging;
|
||||
private float twoFingerLastX0, twoFingerLastY0;
|
||||
private float twoFingerLastX1, twoFingerLastY1;
|
||||
private boolean twoFingerMiddleButtonDown;
|
||||
// Pinch tracking
|
||||
private float pinchLastDistance;
|
||||
private float pinchZoomRemainder;
|
||||
private float keyPanRemainderX, keyPanRemainderY;
|
||||
private static final float PINCH_STEP_PX = 10f;
|
||||
// Two-finger tap detection
|
||||
private boolean twoFingerTapPossible;
|
||||
private boolean twoFingerTapFired;
|
||||
// Track which WASD/arrow keys are currently held
|
||||
private boolean panKeyUp, panKeyDown, panKeyLeft, panKeyRight;
|
||||
// True when finger has moved beyond tap tolerance (prevents spurious tap on lift)
|
||||
private boolean movedBeyondTapThreshold;
|
||||
// True after a multi-finger gesture has been active — prevents the remaining
|
||||
// finger from starting a spurious single-finger drag on lift sequence.
|
||||
private boolean multiFingerGestureUsed;
|
||||
// Remember which keycodes were actually pressed so releasePanKeys releases only those
|
||||
private Integer panLeftKey, panRightKey, panUpKey, panDownKey;
|
||||
// Long-press movement tolerance (pixels of raw finger movement before cancelling long-press)
|
||||
private static final float LONG_PRESS_MOVE_TOLERANCE = 50f;
|
||||
// Raw touch-down coordinates for measuring finger travel
|
||||
private float touchDownRawX, touchDownRawY;
|
||||
// Last raw coordinates for single-finger drag delta
|
||||
private float singleFingerLastRawX, singleFingerLastRawY;
|
||||
// Two-finger gesture mutual exclusion (only pan OR pinch, not both)
|
||||
private static final int TWO_FINGER_GESTURE_NONE = 0;
|
||||
private static final int TWO_FINGER_GESTURE_PAN = 1;
|
||||
private static final int TWO_FINGER_GESTURE_ZOOM = 2;
|
||||
private int twoFingerGestureMode = TWO_FINGER_GESTURE_NONE;
|
||||
// Accumulated deltas for deciding which two-finger gesture to lock into
|
||||
private float accumulatedPinchDelta, accumulatedPanDelta;
|
||||
|
||||
// Settle window: ignore movement for first N ms after second finger lands (#1)
|
||||
// Also serves as a grace period for a third finger to arrive before 2F locks in
|
||||
private static final long TWO_FINGER_SETTLE_MS = 120;
|
||||
private static final long THREE_FINGER_SETTLE_MS = 50;
|
||||
private long twoFingerDownTime;
|
||||
private long threeFingerDownTime;
|
||||
|
||||
// Velocity gating for two-finger hold vs drag (#2)
|
||||
private long twoFingerLastMoveTime;
|
||||
private static final float MIN_DRAG_VELOCITY = 0.3f; // px/ms to commit to drag
|
||||
private static final float MIN_DRAG_VELOCITY = 0.3f;
|
||||
|
||||
// Pinch vs drag ratio: pinch delta must exceed pan by this factor to classify as pinch (#4)
|
||||
private static final float PINCH_RATIO_THRESHOLD = 1.5f;
|
||||
|
||||
// Cancel-and-reclassify: allow reclassification within this window after lock-in (#5)
|
||||
private static final long RECLASSIFY_WINDOW_MS = 100;
|
||||
private long twoFingerLockTime;
|
||||
private float reclassifyPinchDelta, reclassifyPanDelta;
|
||||
// Gesture pointer ownership tracking (prevents d-pad/button pointer conflicts)
|
||||
private int gestureFingerCount = 0;
|
||||
private final ArrayList<Integer> gestureOwnedPointerIds = new ArrayList<>();
|
||||
private final int[] multiFingerStartIds = new int[3];
|
||||
private final float[] multiFingerStartX = new float[3], multiFingerStartY = new float[3];
|
||||
private int multiFingerStartCount;
|
||||
|
||||
// Two-finger hold detection
|
||||
private Runnable twoFingerHoldRunnable;
|
||||
private boolean twoFingerHoldTriggered;
|
||||
|
||||
// Three-finger tracking
|
||||
private boolean threeFingerTapPossible;
|
||||
private boolean threeFingerTapFired;
|
||||
private boolean threeFingerDragging;
|
||||
@@ -199,9 +174,7 @@ public final class TouchscreenGestures {
|
||||
|
||||
switch (action) {
|
||||
case MotionEvent.ACTION_DOWN:
|
||||
// A new touch must not shorten or discard an already recognized click.
|
||||
handleTsCancel(true);
|
||||
// First pointer overall — gesture system claims it
|
||||
gestureOwnedPointerIds.clear();
|
||||
gestureOwnedPointerIds.add(pointerId);
|
||||
gestureFingerCount = 1;
|
||||
@@ -209,13 +182,11 @@ public final class TouchscreenGestures {
|
||||
break;
|
||||
|
||||
case MotionEvent.ACTION_POINTER_DOWN:
|
||||
// New pointer arrived — gesture system claims it
|
||||
if (!gestureOwnedPointerIds.contains(pointerId)) {
|
||||
gestureOwnedPointerIds.add(pointerId);
|
||||
gestureFingerCount++;
|
||||
}
|
||||
if (gestureFingerCount == 1) {
|
||||
// First gesture finger (controls own earlier pointers)
|
||||
handleTsDown(event, actionIndex);
|
||||
} else if (gestureFingerCount == 2) {
|
||||
handleTsPointerDown(event);
|
||||
@@ -242,15 +213,12 @@ public final class TouchscreenGestures {
|
||||
gestureOwnedPointerIds.remove(Integer.valueOf(pointerId));
|
||||
gestureFingerCount = Math.max(0, gestureFingerCount - 1);
|
||||
if (prevCount == 3 && gestureFingerCount == 2) {
|
||||
// Three-finger gesture ending
|
||||
handleTsThreeFingerUp(event);
|
||||
} else if (prevCount == 2 && gestureFingerCount == 1) {
|
||||
// Two-finger gesture ending (2→1)
|
||||
handleTsPointerUp(event);
|
||||
} else if (prevCount >= 4) {
|
||||
if (removedIndex < 3) rebaseThreeFingerMovement(event);
|
||||
} else if (prevCount >= 1 && gestureFingerCount == 0) {
|
||||
// Last gesture finger lifted while controls still hold pointers
|
||||
handleTsUp(event, actionIndex);
|
||||
}
|
||||
}
|
||||
@@ -261,9 +229,6 @@ public final class TouchscreenGestures {
|
||||
int prevCount = gestureFingerCount;
|
||||
gestureOwnedPointerIds.remove(Integer.valueOf(pointerId));
|
||||
gestureFingerCount = Math.max(0, gestureFingerCount - 1);
|
||||
// Clean up multi-finger state if needed, routing by previous
|
||||
// gesture mode so a 3-finger gesture isn't ended via the
|
||||
// two-finger cleanup path.
|
||||
if (prevCount >= 3) {
|
||||
handleTsThreeFingerUp(event);
|
||||
} else if (prevCount == 2) {
|
||||
@@ -271,7 +236,6 @@ public final class TouchscreenGestures {
|
||||
}
|
||||
handleTsUp(event, actionIndex);
|
||||
}
|
||||
// ACTION_UP = last pointer overall — full cleanup
|
||||
gestureOwnedPointerIds.clear();
|
||||
gestureFingerCount = 0;
|
||||
break;
|
||||
@@ -309,15 +273,12 @@ public final class TouchscreenGestures {
|
||||
threeFingerHoldTriggered = false;
|
||||
accumulatedThreeFingerDelta = 0;
|
||||
|
||||
// Store raw touch coordinates for long-press movement tolerance
|
||||
touchDownRawX = event.getX(actionIndex);
|
||||
touchDownRawY = event.getY(actionIndex);
|
||||
singleFingerDownTime = SystemClock.uptimeMillis();
|
||||
singleFingerLastRawX = touchDownRawX;
|
||||
singleFingerLastRawY = touchDownRawY;
|
||||
|
||||
// Keep a nearby re-tap undecided until UP: it can still become a drag,
|
||||
// long press, or multi-finger gesture instead of a double click.
|
||||
if (isDoubleTap(event, actionIndex)) {
|
||||
secondTapCandidate = true;
|
||||
doubleTapAnchorX = lastTapX;
|
||||
@@ -327,7 +288,6 @@ public final class TouchscreenGestures {
|
||||
|
||||
if (!secondTapCandidate && delayedPress == null && pendingTapPress == null) moveCursorTo(x, y);
|
||||
|
||||
// Schedule long-press
|
||||
if (gestureConfig.getLongPressEnabled()) {
|
||||
longPressRunnable = () -> {
|
||||
secondTapCandidate = false;
|
||||
@@ -342,7 +302,6 @@ public final class TouchscreenGestures {
|
||||
postDelayed(longPressRunnable, gestureConfig.getLongPressDelay());
|
||||
}
|
||||
|
||||
// Tap: immediate cursor move (press is deferred to UP for click, or MOVE for drag)
|
||||
}
|
||||
|
||||
private void handleTsPointerDown(MotionEvent event) {
|
||||
@@ -351,11 +310,6 @@ public final class TouchscreenGestures {
|
||||
flushPendingTapRelease();
|
||||
lastTapTime = 0;
|
||||
flushPendingHoldClickRelease();
|
||||
// Cancel any single-finger long-press. cancelLongPressTimer only
|
||||
// clears the pending runnable; if the long-press has already fired
|
||||
// we must also release the held action before we transition into a
|
||||
// multi-finger gesture, otherwise the long-press button/key stays
|
||||
// down for the rest of the touch sequence.
|
||||
if (longPressTriggered) {
|
||||
longPressActionHeld = releaseHoldAction(longPressActionHeld, gestureConfig.getLongPressAction());
|
||||
longPressTriggered = false;
|
||||
@@ -388,7 +342,6 @@ public final class TouchscreenGestures {
|
||||
event.getY(idx0) - event.getY(idx1));
|
||||
recordMultiFingerOrigins(event, 2);
|
||||
}
|
||||
// Schedule two-finger hold
|
||||
if (gestureConfig.getTwoFingerHoldEnabled()) {
|
||||
twoFingerHoldRunnable = () -> {
|
||||
twoFingerHoldTriggered = true;
|
||||
@@ -404,33 +357,26 @@ public final class TouchscreenGestures {
|
||||
}
|
||||
|
||||
private void handleTsMove(MotionEvent event, int pointerIndex) {
|
||||
// After a multi-finger gesture, ignore single-finger movement until all fingers lift
|
||||
if (multiFingerGestureUsed) return;
|
||||
|
||||
int x = (int) event.getX(pointerIndex);
|
||||
int y = (int) event.getY(pointerIndex);
|
||||
|
||||
// If long press already triggered, ignore movement (right-click already sent)
|
||||
if (longPressTriggered) return;
|
||||
|
||||
// Measure raw finger travel from initial touch point
|
||||
float rawTravel = maxFingerTravel(event, pointerIndex, touchDownRawX, touchDownRawY);
|
||||
if (secondTapCandidate && (rawTravel > doubleTapSlop
|
||||
|| maxFingerTravel(event, pointerIndex, doubleTapAnchorX, doubleTapAnchorY) >= doubleTapSlop)) {
|
||||
secondTapCandidate = false;
|
||||
}
|
||||
|
||||
// The threshold decides when a drag starts. An active drag must keep
|
||||
// following the finger even when it returns through the touch origin.
|
||||
if (!isDragging && rawTravel <= LONG_PRESS_MOVE_TOLERANCE) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Beyond tolerance — cancel long press
|
||||
cancelLongPressTimer();
|
||||
movedBeyondTapThreshold = true;
|
||||
|
||||
// Detect drag start
|
||||
if (!isDragging && gestureConfig.getDragEnabled()) {
|
||||
flushPendingTapRelease();
|
||||
String dragAction = gestureConfig.getDragAction();
|
||||
@@ -438,14 +384,7 @@ public final class TouchscreenGestures {
|
||||
dragButtonPressed = true;
|
||||
singleFingerLastRawX = event.getX(pointerIndex);
|
||||
singleFingerLastRawY = event.getY(pointerIndex);
|
||||
// Send the configured drag press immediately so that a short
|
||||
// move followed straight by UP still produces a press+release
|
||||
// pair. A zero-delta performPanAction just presses the button
|
||||
// (or is a no-op for the key-pan variants, which press per
|
||||
// direction on their next move frame).
|
||||
if (isClickDragAction(dragAction)) {
|
||||
// The candidate's cursor stayed at the previous click. Start
|
||||
// a drag at this touch's own origin before pressing its button.
|
||||
moveCursorTo((int) touchDownRawX, (int) touchDownRawY);
|
||||
if (useRelativeMouseDragMovement()) {
|
||||
pressClickDragAction(dragAction);
|
||||
@@ -456,7 +395,6 @@ public final class TouchscreenGestures {
|
||||
performPanAction(0f, 0f, dragAction);
|
||||
}
|
||||
notifyGesture(Gesture.DRAG);
|
||||
// Non-click pan actions continue with real deltas on the next frame.
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -481,14 +419,11 @@ public final class TouchscreenGestures {
|
||||
return;
|
||||
}
|
||||
|
||||
// Move cursor
|
||||
moveCursorTo(x, y);
|
||||
}
|
||||
|
||||
private void handleTsTwoFingerMove(MotionEvent event) {
|
||||
if (multiFingerGestureUsed) return;
|
||||
// If a two-finger hold has already fired, ignore subsequent jitter so
|
||||
// it can't lock into a pan/zoom gesture mid-hold.
|
||||
if (twoFingerHoldTriggered) return;
|
||||
if (gestureFingerCount < 2 || gestureOwnedPointerIds.size() < 2) return;
|
||||
|
||||
@@ -496,20 +431,15 @@ public final class TouchscreenGestures {
|
||||
int idx1 = event.findPointerIndex(gestureOwnedPointerIds.get(1));
|
||||
if (idx0 < 0 || idx1 < 0) return;
|
||||
|
||||
// Settling delays recognition, not movement tracking. A swipe or pinch
|
||||
// must stop being a tap/hold even when it finishes inside that delay.
|
||||
if (multiFingerMovementExceeded(event)) {
|
||||
twoFingerTapPossible = false;
|
||||
cancelTwoFingerHoldTimer();
|
||||
}
|
||||
// Slow deliberate travel can cross touch slop before reaching the
|
||||
// pan/zoom threshold. It must not turn into a stationary hold first.
|
||||
if (multiFingerMovementExceeded(event, true)) cancelTwoFingerHoldTimer();
|
||||
|
||||
float x0 = event.getX(idx0), y0 = event.getY(idx0);
|
||||
float x1 = event.getX(idx1), y1 = event.getY(idx1);
|
||||
|
||||
// Compute per-frame pan and pinch deltas
|
||||
float currDist = (float) Math.hypot(x0 - x1, y0 - y1);
|
||||
float framePinchDelta = Math.abs(currDist - pinchLastDistance);
|
||||
|
||||
@@ -523,7 +453,6 @@ public final class TouchscreenGestures {
|
||||
|
||||
long now = SystemClock.uptimeMillis();
|
||||
if (now - twoFingerDownTime < TWO_FINGER_SETTLE_MS) {
|
||||
// Still settling — update stored positions but don't accumulate deltas
|
||||
twoFingerLastX0 = x0; twoFingerLastY0 = y0;
|
||||
twoFingerLastX1 = x1; twoFingerLastY1 = y1;
|
||||
pinchLastDistance = currDist;
|
||||
@@ -531,14 +460,12 @@ public final class TouchscreenGestures {
|
||||
}
|
||||
long frameTime = now - twoFingerLastMoveTime;
|
||||
twoFingerLastMoveTime = now;
|
||||
float velocity = (frameTime > 0) ? framePanDelta / frameTime : 0; // px/ms
|
||||
float velocity = (frameTime > 0) ? framePanDelta / frameTime : 0;
|
||||
|
||||
// Accumulate deltas until we have enough movement to decide gesture type
|
||||
if (twoFingerGestureMode == TWO_FINGER_GESTURE_NONE) {
|
||||
accumulatedPinchDelta += framePinchDelta;
|
||||
accumulatedPanDelta += framePanDelta;
|
||||
if (accumulatedPinchDelta + accumulatedPanDelta > (float) gestureConfig.getGestureThreshold()) {
|
||||
// Enough movement to lock into a gesture — no longer a tap or hold
|
||||
twoFingerTapPossible = false;
|
||||
cancelTwoFingerHoldTimer();
|
||||
if (accumulatedPinchDelta > accumulatedPanDelta * PINCH_RATIO_THRESHOLD
|
||||
@@ -551,7 +478,6 @@ public final class TouchscreenGestures {
|
||||
twoFingerLockTime = now;
|
||||
notifyGesture(Gesture.TWO_FINGER_DRAG);
|
||||
} else if (accumulatedPanDelta >= accumulatedPinchDelta && gestureConfig.getTwoFingerDragEnabled()) {
|
||||
// Fallback: pan is dominant but velocity was too low — still drag
|
||||
twoFingerGestureMode = TWO_FINGER_GESTURE_PAN;
|
||||
twoFingerLockTime = now;
|
||||
notifyGesture(Gesture.TWO_FINGER_DRAG);
|
||||
@@ -571,7 +497,7 @@ public final class TouchscreenGestures {
|
||||
reclassifyPinchDelta += framePinchDelta;
|
||||
reclassifyPanDelta += framePanDelta;
|
||||
float reclassifyTotal = reclassifyPinchDelta + reclassifyPanDelta;
|
||||
if (reclassifyTotal > 20f) { // enough post-lock data to reclassify
|
||||
if (reclassifyTotal > 20f) {
|
||||
boolean shouldBeZoom = reclassifyPinchDelta > reclassifyPanDelta * PINCH_RATIO_THRESHOLD;
|
||||
if (shouldBeZoom && twoFingerGestureMode == TWO_FINGER_GESTURE_PAN
|
||||
&& gestureConfig.getPinchEnabled()) {
|
||||
@@ -585,7 +511,7 @@ public final class TouchscreenGestures {
|
||||
resetSmallMovement();
|
||||
notifyGesture(Gesture.TWO_FINGER_DRAG);
|
||||
}
|
||||
twoFingerLockTime = 0; // done reclassifying
|
||||
twoFingerLockTime = 0;
|
||||
reclassifyPinchDelta = 0;
|
||||
reclassifyPanDelta = 0;
|
||||
}
|
||||
@@ -595,12 +521,10 @@ public final class TouchscreenGestures {
|
||||
pinchZoomRemainder = accumulateSignedMovement(pinchZoomRemainder, delta);
|
||||
if (Math.abs(pinchZoomRemainder) >= PINCH_STEP_PX) {
|
||||
performZoomAction(pinchZoomRemainder > 0);
|
||||
// Keep the fractional travel, without queuing a burst of old
|
||||
// zoom actions after a large move or a direction reversal.
|
||||
pinchZoomRemainder %= PINCH_STEP_PX;
|
||||
}
|
||||
}
|
||||
pinchLastDistance = currDist; // Always update baseline to avoid stale deltas
|
||||
pinchLastDistance = currDist;
|
||||
if (twoFingerGestureMode == TWO_FINGER_GESTURE_PAN) {
|
||||
String twoFingerDragAction = gestureConfig.getTwoFingerDragAction();
|
||||
if (isClickDragAction(twoFingerDragAction)) {
|
||||
@@ -627,14 +551,11 @@ public final class TouchscreenGestures {
|
||||
private void handleTsPointerUp(MotionEvent event) {
|
||||
cancelTwoFingerHoldTimer();
|
||||
if (multiFingerMovementExceeded(event)) twoFingerTapPossible = false;
|
||||
// Two-finger hold release
|
||||
if (twoFingerHoldTriggered) {
|
||||
twoFingerHoldActionHeld = releaseHoldAction(twoFingerHoldActionHeld, gestureConfig.getTwoFingerHoldAction());
|
||||
twoFingerHoldTriggered = false;
|
||||
}
|
||||
// Two-finger tap detection
|
||||
else if (twoFingerTapPossible && !twoFingerDragging && gestureConfig.getTwoFingerTapEnabled()) {
|
||||
// Move cursor to midpoint between the two fingers
|
||||
float midX = (twoFingerLastX0 + twoFingerLastX1) / 2f;
|
||||
float midY = (twoFingerLastY0 + twoFingerLastY1) / 2f;
|
||||
queueTapClick(gestureConfig.getTwoFingerTapAction(), midX, midY);
|
||||
@@ -652,7 +573,6 @@ public final class TouchscreenGestures {
|
||||
reclassifyPinchDelta = 0;
|
||||
reclassifyPanDelta = 0;
|
||||
twoFingerLockTime = 0;
|
||||
// Suppress single-finger tap/drag when last finger lifts after any 2F gesture
|
||||
movedBeyondTapThreshold = true;
|
||||
multiFingerGestureUsed = true;
|
||||
}
|
||||
@@ -661,7 +581,6 @@ public final class TouchscreenGestures {
|
||||
cancelLongPressTimer();
|
||||
|
||||
if (longPressTriggered) {
|
||||
// Release the long-press action
|
||||
longPressActionHeld = releaseHoldAction(longPressActionHeld, gestureConfig.getLongPressAction());
|
||||
longPressTriggered = false;
|
||||
return;
|
||||
@@ -671,7 +590,6 @@ public final class TouchscreenGestures {
|
||||
float y = event.getY(actionIndex);
|
||||
|
||||
if (isDragging && dragButtonPressed) {
|
||||
// End drag (release any held drag buttons/keys)
|
||||
releaseDragInput();
|
||||
dragButtonPressed = false;
|
||||
isDragging = false;
|
||||
@@ -685,8 +603,6 @@ public final class TouchscreenGestures {
|
||||
? gestureConfig.getLongPressDelay() : ViewConfiguration.getLongPressTimeout();
|
||||
if (SystemClock.uptimeMillis() - singleFingerDownTime < tapLimit
|
||||
&& Math.hypot(x - doubleTapAnchorX, y - doubleTapAnchorY) < doubleTapSlop) {
|
||||
// A normal left tap already supplied the first click. Other
|
||||
// single-tap mappings need a complete synthesized double click.
|
||||
boolean firstTapClicked = gestureConfig.getTapEnabled()
|
||||
&& TouchGestureConfig.ACTION_LEFT_CLICK.equals(gestureConfig.getTapAction());
|
||||
int clicks = firstTapClicked ? 1 : 2;
|
||||
@@ -697,26 +613,21 @@ public final class TouchscreenGestures {
|
||||
}
|
||||
}
|
||||
|
||||
// Two-finger tap already sent its click on POINTER_UP — skip the tap on UP
|
||||
if (twoFingerTapFired) {
|
||||
twoFingerTapFired = false;
|
||||
return;
|
||||
}
|
||||
|
||||
// Three-finger tap already sent its click — skip the tap on UP
|
||||
if (threeFingerTapFired) {
|
||||
threeFingerTapFired = false;
|
||||
return;
|
||||
}
|
||||
|
||||
// Simple tap — only if finger stayed within tap tolerance
|
||||
if (gestureConfig.getTapEnabled() && !movedBeyondTapThreshold) {
|
||||
queueTapClick(gestureConfig.getTapAction(), x, y);
|
||||
notifyGesture(Gesture.TAP);
|
||||
}
|
||||
|
||||
// Record for double-tap detection (even if tap itself is disabled,
|
||||
// so double-tap can still prime from single touch-ups)
|
||||
if (!movedBeyondTapThreshold && (gestureConfig.getTapEnabled() || gestureConfig.getDoubleTapEnabled())) {
|
||||
lastTapTime = SystemClock.uptimeMillis();
|
||||
lastTapX = x;
|
||||
@@ -776,13 +687,10 @@ public final class TouchscreenGestures {
|
||||
cancelLongPressTimer();
|
||||
cancelDrag();
|
||||
cancelTwoFingerHoldTimer();
|
||||
// If a two-finger hold already injected its action, release it before
|
||||
// transitioning so the held button/key doesn't stay down.
|
||||
if (twoFingerHoldTriggered) {
|
||||
twoFingerHoldActionHeld = releaseHoldAction(twoFingerHoldActionHeld, gestureConfig.getTwoFingerHoldAction());
|
||||
twoFingerHoldTriggered = false;
|
||||
}
|
||||
// Clean up two-finger state
|
||||
releaseDragInput();
|
||||
resetSmallMovement();
|
||||
twoFingerDragging = false;
|
||||
@@ -797,7 +705,6 @@ public final class TouchscreenGestures {
|
||||
threeFingerDragOffsetX = threeFingerDragOffsetY = 0f;
|
||||
threeFingerDownTime = SystemClock.uptimeMillis();
|
||||
|
||||
// Compute midpoint of three gesture fingers
|
||||
if (gestureOwnedPointerIds.size() >= 3) {
|
||||
float sumX = 0, sumY = 0;
|
||||
int validCount = 0;
|
||||
@@ -809,13 +716,12 @@ public final class TouchscreenGestures {
|
||||
validCount++;
|
||||
}
|
||||
}
|
||||
if (validCount < 3) return; // Can't proceed without all 3 pointers
|
||||
if (validCount < 3) return;
|
||||
threeFingerLastMidX = sumX / 3f;
|
||||
threeFingerLastMidY = sumY / 3f;
|
||||
recordMultiFingerOrigins(event, 3);
|
||||
}
|
||||
|
||||
// Schedule three-finger hold
|
||||
if (gestureConfig.getThreeFingerHoldEnabled()) {
|
||||
threeFingerHoldRunnable = () -> {
|
||||
threeFingerHoldTriggered = true;
|
||||
@@ -831,8 +737,6 @@ public final class TouchscreenGestures {
|
||||
|
||||
private void handleTsThreeFingerMove(MotionEvent event) {
|
||||
if (gestureFingerCount < 3 || gestureOwnedPointerIds.size() < 3) return;
|
||||
// If a three-finger hold has already fired, ignore subsequent jitter so
|
||||
// it can't lock into a pan gesture mid-hold.
|
||||
if (threeFingerHoldTriggered) return;
|
||||
if (multiFingerMovementExceeded(event)) {
|
||||
threeFingerTapPossible = false;
|
||||
@@ -877,8 +781,6 @@ public final class TouchscreenGestures {
|
||||
}
|
||||
|
||||
if (threeFingerGestureMode == THREE_FINGER_GESTURE_PAN) {
|
||||
// Once recognized, retain small mouse movements. Keyboard panning
|
||||
// accumulates its own direction threshold in performKeyPan.
|
||||
String threeFingerDragAction = gestureConfig.getThreeFingerDragAction();
|
||||
if (isClickDragAction(threeFingerDragAction)) {
|
||||
if (useRelativeMouseDragMovement()) {
|
||||
@@ -919,7 +821,6 @@ public final class TouchscreenGestures {
|
||||
multiFingerStartCount = 0;
|
||||
resetSmallMovement();
|
||||
threeFingerGestureMode = THREE_FINGER_GESTURE_NONE;
|
||||
// Suppress single-finger tap/drag when last finger lifts after any 3F gesture
|
||||
movedBeyondTapThreshold = true;
|
||||
multiFingerGestureUsed = true;
|
||||
}
|
||||
@@ -966,7 +867,6 @@ public final class TouchscreenGestures {
|
||||
}
|
||||
x /= 3f;
|
||||
y /= 3f;
|
||||
// Replacing a tracked finger changes the centroid without moving the cursor.
|
||||
if (threeFingerDragging) {
|
||||
threeFingerDragOffsetX += threeFingerLastMidX - x;
|
||||
threeFingerDragOffsetY += threeFingerLastMidY - y;
|
||||
@@ -1030,9 +930,6 @@ public final class TouchscreenGestures {
|
||||
private void startPendingTapClick() {
|
||||
if (delayedPress != null || pendingTapPress != null || pendingTapClicks.isEmpty()) return;
|
||||
TapClick click = pendingTapClicks.peekFirst();
|
||||
// Games that poll button state need an observable UP interval too.
|
||||
// Reuse the first tap's location: normal finger drift must not turn
|
||||
// this into two clicks on different targets or a tiny drag.
|
||||
long delay = Math.max(0, CLICK_DELAYED_TIME - (SystemClock.uptimeMillis() - lastInputReleaseTime));
|
||||
pendingTapPress = () -> {
|
||||
pendingTapPress = null;
|
||||
@@ -1224,9 +1121,6 @@ public final class TouchscreenGestures {
|
||||
pressButton(MouseButton.BUTTON_MIDDLE);
|
||||
twoFingerMiddleButtonDown = true;
|
||||
}
|
||||
// Pan from the client's current pointer. Games can recenter the mouse
|
||||
// when the middle button goes down; replaying our old absolute touch
|
||||
// anchor after that warp causes a large, unintended camera movement.
|
||||
moveCursorByRelativeDelta(dx, dy);
|
||||
}
|
||||
|
||||
@@ -1287,10 +1181,6 @@ public final class TouchscreenGestures {
|
||||
}
|
||||
|
||||
private void performKeyPan(float dx, float dy, Integer leftKey, Integer rightKey, Integer upKey, Integer downKey) {
|
||||
// When fingers are actively moving, update key states to match the
|
||||
// swipe direction. When fingers stop moving but stay on screen,
|
||||
// keep the current keys held — movement continues until finger-up
|
||||
// calls releasePanKeys().
|
||||
|
||||
keyPanRemainderX = accumulateSignedMovement(keyPanRemainderX, dx);
|
||||
keyPanRemainderY = accumulateSignedMovement(keyPanRemainderY, dy);
|
||||
@@ -1300,9 +1190,6 @@ public final class TouchscreenGestures {
|
||||
dy = keyPanRemainderY;
|
||||
keyPanRemainderX = keyPanRemainderY = 0f;
|
||||
|
||||
// --- Significant movement detected: update each axis ---
|
||||
|
||||
// Horizontal: determine desired state from this frame's delta
|
||||
boolean wantLeft = dx < -3f;
|
||||
boolean wantRight = dx > 3f;
|
||||
|
||||
@@ -1311,7 +1198,6 @@ public final class TouchscreenGestures {
|
||||
if (wantLeft && !panKeyLeft) { pressKey(leftKey); panKeyLeft = true; panLeftKey = leftKey; }
|
||||
if (wantRight && !panKeyRight) { pressKey(rightKey); panKeyRight = true; panRightKey = rightKey; }
|
||||
|
||||
// Vertical: determine desired state from this frame's delta
|
||||
boolean wantUp = dy < -3f;
|
||||
boolean wantDown = dy > 3f;
|
||||
|
||||
|
||||
@@ -6,7 +6,6 @@ import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import java.io.File
|
||||
|
||||
/** What SteamVR sees for the game pad. The driver reads the file once, when SteamVR starts. */
|
||||
object VrControllers {
|
||||
enum class Emulate(val key: String) { OFF("off"), INDEX("index"), TOUCH("touch"), VIVE("vive") }
|
||||
|
||||
@@ -46,7 +45,6 @@ object VrControllers {
|
||||
fun encode(settings: Settings): String =
|
||||
"emulate=${settings.emulate.key}\nsticks=${if (settings.sticksMoveHands) "hands" else "game"}\n"
|
||||
|
||||
/** Writes into the session's runtime dir, which the guest sees as /run/droiddeck. */
|
||||
fun publish(context: Context) {
|
||||
runCatching {
|
||||
val dir = File(context.filesDir, ".wayland-rt").apply { mkdirs() }
|
||||
|
||||
@@ -23,7 +23,6 @@ object DeckyManager {
|
||||
private const val PATH = "root/homebrew/services/PluginLoader"
|
||||
private const val VERSION = "root/homebrew/services/.droiddeck-decky-version"
|
||||
private const val SETTINGS = "root/homebrew/settings/loader.json"
|
||||
// droiddeck-session reads the marker from the root of the client it runs.
|
||||
private val CEF_REMOTE_DEBUG_MARKERS = listOf(
|
||||
"root/.local/share/Steam/.cef-enable-remote-debugging",
|
||||
"root/.droiddeck-x64/.local/share/Steam/.cef-enable-remote-debugging",
|
||||
@@ -58,7 +57,6 @@ object DeckyManager {
|
||||
check(staged.renameTo(file)) { "cannot write ${file.path}" }
|
||||
}
|
||||
|
||||
// Mirrors Decky's updater: Stable takes the newest non-prerelease tag, Prerelease the newest tag of either kind.
|
||||
fun latest(channels: ReleaseChannels, branch: Int): Release? =
|
||||
if (branch == BRANCH_STABLE) channels.stable.firstOrNull() else channels.all.firstOrNull()
|
||||
|
||||
|
||||
@@ -51,7 +51,6 @@ object DesktopCatalog {
|
||||
|
||||
private fun journal(root: File, id: String) = File(root, ".droiddeck-pkg-$id$JOURNAL_SUFFIX")
|
||||
|
||||
/** Packages whose extraction over the runtime started and never finished. */
|
||||
fun interrupted(context: Context): List<Entry> = interrupted(LinuxRuntime.rootDir(context))
|
||||
|
||||
fun interrupted(root: File): List<Entry> =
|
||||
@@ -63,7 +62,6 @@ object DesktopCatalog {
|
||||
|
||||
private fun downloadFile(context: Context, entry: Entry) = File(context.cacheDir, "pkg-${entry.id}-${entry.sha256.take(12)}.download")
|
||||
|
||||
/** Drops downloads kept for installs that no longer need finishing, such as after the runtime was reinstalled. */
|
||||
fun pruneDownloads(context: Context) = synchronized(installLock) {
|
||||
val keep = interrupted(context).map { downloadFile(context, it).name }.toSet()
|
||||
context.cacheDir.listFiles { f -> f.name.startsWith("pkg-") && f.name.removeSuffix(".resume.properties").endsWith(".download") }
|
||||
@@ -102,7 +100,6 @@ object DesktopCatalog {
|
||||
o.optString("icon", "applications-games"), o.optString("category", "Game"),
|
||||
)
|
||||
|
||||
/** A finished download is kept until its extraction completes, so resuming does not fetch it again. */
|
||||
private fun downloaded(file: File, entry: Entry): Boolean =
|
||||
file.isFile && file.length() > 0 && !File(file.path + ".resume.properties").exists() &&
|
||||
(entry.size <= 0 || file.length() == entry.size) && entry.sha256.equals(Hashes.sha256(file), ignoreCase = true)
|
||||
|
||||
@@ -189,7 +189,6 @@ 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"
|
||||
|
||||
@@ -39,7 +39,6 @@ object GuestCommand {
|
||||
if (linkDir != null) cmd.add(1, "--link2symlink")
|
||||
val binds = LinuxRuntime.binds(context, null, runtimeDir, Environment.getExternalStorageDirectory(), extraBinds)
|
||||
binds.forEach { cmd.add("-b"); cmd.add(it) }
|
||||
// Fake root and link2symlink are emulated by proot, so their syscalls must stay on the traced path.
|
||||
val fastPathKey = if (fastPath && !fakeRoot && linkDir == null && ProotFastPath.enabled(context)) ProotFastPath.key(root, binds) else null
|
||||
cmd += listOf(
|
||||
"/usr/bin/env", "-i", "HOME=/root", "USER=root", "LANG=C.UTF-8",
|
||||
@@ -48,8 +47,6 @@ object GuestCommand {
|
||||
"DROIDDECK_BWRAP_SOCKET=${BwrapSpawner.socket(context)}",
|
||||
"XDG_DATA_DIRS=/root/.local/share/flatpak/exports/share:/usr/local/share:/usr/share",
|
||||
)
|
||||
// The Steam client installer and the package tools inside the guest fetch over plain curl,
|
||||
// so the app proxy has to reach them through the environment proot starts them with.
|
||||
DownloadSource.proxyHostPort(context).takeIf { it.isNotEmpty() }?.let { hostPort ->
|
||||
cmd += listOf(
|
||||
"http_proxy=http://$hostPort", "https_proxy=http://$hostPort",
|
||||
@@ -77,7 +74,6 @@ object GuestCommand {
|
||||
try {
|
||||
while (process.isAlive && !flag.get()) Thread.sleep(200)
|
||||
if (flag.get()) {
|
||||
// PRoot ignores SIGTERM; SIGQUIT makes it kill its tracees and exit cleanly.
|
||||
if (pid > 0) {
|
||||
runCatching { android.system.Os.kill(pid, android.system.OsConstants.SIGQUIT) }
|
||||
} else {
|
||||
|
||||
@@ -50,7 +50,6 @@ public final class LinuxRuntime {
|
||||
}
|
||||
|
||||
public static File liveDir(Context context) {
|
||||
// Android may evict cache files even while guest processes are using them.
|
||||
File dir = new File(context.getNoBackupFilesDir(), "guest-runtime");
|
||||
dir.mkdirs();
|
||||
return dir;
|
||||
@@ -63,9 +62,7 @@ public final class LinuxRuntime {
|
||||
}
|
||||
|
||||
private static final String HOST_DIR = "opt/android-host";
|
||||
/** The downloaded add-on pack. The APK does not ship this binary. */
|
||||
public static final String PROOT_PACK = "add-on pack";
|
||||
/** Termux's unpatched proot inside the rootfs. Developer switch only. */
|
||||
public static final String PROOT_ROOTFS = "rootfs fallback";
|
||||
public static final String PROOT_MISSING = "missing";
|
||||
|
||||
@@ -81,7 +78,6 @@ public final class LinuxRuntime {
|
||||
return rootfsProot(context).isFile() && rootfsLoader(context).isFile();
|
||||
}
|
||||
|
||||
/** Patched proot is the add-on pack. The rootfs copy is not that binary. */
|
||||
public static boolean patchedProot(Context context) {
|
||||
return AddonPack.PROOT.installed(context);
|
||||
}
|
||||
@@ -98,7 +94,6 @@ public final class LinuxRuntime {
|
||||
return AddonPack.PROOT.file(context, "libproot-loader.so");
|
||||
}
|
||||
|
||||
/** Where {@link #prootBinary} came from: {@link #PROOT_PACK}, {@link #PROOT_ROOTFS} or {@link #PROOT_MISSING}. */
|
||||
public static String prootSource(Context context) {
|
||||
File bin = prootBinary(context);
|
||||
if (!bin.isFile()) return PROOT_MISSING;
|
||||
@@ -116,7 +111,6 @@ public final class LinuxRuntime {
|
||||
return hasRootfs(context) && (patchedProot(context) || rootfsProotReady(context));
|
||||
}
|
||||
|
||||
/** The rootfs alone: enough to read the game library, while the proot pack can still be downloading. */
|
||||
public static boolean hasRootfs(Context context) {
|
||||
if (LinuxRuntimeInstaller.isRemoving() || LinuxRuntimeInstaller.hasRemovalPending(context)) return false;
|
||||
File root = rootDir(context);
|
||||
@@ -392,9 +386,6 @@ public final class LinuxRuntime {
|
||||
return thermalZone("ddr");
|
||||
}
|
||||
|
||||
// MangoHud reads the GPU and DDR temperatures from these zone numbers (bindAdrenoStats). On phones
|
||||
// where they are CPU zones, their type follows the temperature put there, so they stay out of the
|
||||
// CPU average.
|
||||
private static java.util.Map<String, String> replacedZoneTypes() {
|
||||
java.util.Map<String, String> replaced = new java.util.HashMap<>();
|
||||
if (gpuTempSource() != null) {
|
||||
@@ -405,7 +396,6 @@ public final class LinuxRuntime {
|
||||
return replaced;
|
||||
}
|
||||
|
||||
/** The zones the session's MangoHud averages for the CPU temperature (all typed cpuN-thermal there). */
|
||||
public static List<File> cpuTempZones() {
|
||||
java.util.Map<String, String> replaced = replacedZoneTypes();
|
||||
List<File> zones = new ArrayList<>();
|
||||
|
||||
@@ -244,10 +244,6 @@ public final class LinuxRuntimeInstaller {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The download is named after the release, so a partial file is only ever resumed for the same
|
||||
* version and checksum, never for a different runtime that happens to share a fixed name.
|
||||
*/
|
||||
static String archiveName(Release release) {
|
||||
String version = release.version.replaceAll("[^A-Za-z0-9._-]", "_");
|
||||
String sum = release.sha256.replaceAll("[^A-Za-z0-9]", "");
|
||||
@@ -255,7 +251,6 @@ public final class LinuxRuntimeInstaller {
|
||||
return "linuxfs-" + version + "-" + sum + ".tar.zst";
|
||||
}
|
||||
|
||||
/** Removes archives left by other releases and by builds that used the fixed name. */
|
||||
private static void deleteOtherArchives(File dir, String keep) {
|
||||
File[] files = dir.listFiles((d, name) -> name.startsWith("linuxfs") && name.endsWith(".tar.zst") && !name.equals(keep));
|
||||
if (files == null) return;
|
||||
@@ -264,8 +259,6 @@ public final class LinuxRuntimeInstaller {
|
||||
|
||||
private static boolean installOnce(Context context, Release release, ProgressListener listener) {
|
||||
File archive = new File(context.getCacheDir(), archiveName(release));
|
||||
// A failed download keeps what it fetched so the next attempt resumes it; anything that
|
||||
// reached verification and failed is not trusted and is removed.
|
||||
boolean keepPartial = false;
|
||||
try {
|
||||
deleteOtherArchives(context.getCacheDir(), archive.getName());
|
||||
@@ -526,8 +519,6 @@ public final class LinuxRuntimeInstaller {
|
||||
}
|
||||
}
|
||||
|
||||
// Packages extract over the live runtime and their archives list a link before the file it
|
||||
// names, so a kill mid-way must leave neither a truncated file nor a link to a missing one.
|
||||
public static boolean extract(Context context, File archive, File destination, ProgressListener listener) {
|
||||
return extract(context, archive, destination, destination, listener);
|
||||
}
|
||||
|
||||
@@ -12,10 +12,6 @@ object ProotFastPath {
|
||||
const val LIBRARY = "/usr/local/lib/libblfastpath.so"
|
||||
const val MAX_BINDS = 256
|
||||
|
||||
/**
|
||||
* The fast path's trampoline is let through only by the proot built with patches/0014.
|
||||
* The rootfs copy (Termux's stock proot) is not that binary, so the library stays out.
|
||||
*/
|
||||
fun allows(preference: Boolean, noSeccomp: Boolean, source: String): Boolean =
|
||||
preference && !noSeccomp && source == LinuxRuntime.PROOT_PACK
|
||||
|
||||
|
||||
@@ -74,11 +74,6 @@ public final class RuntimeFileTree {
|
||||
throw new IOException("Cannot make directory removable: " + dir);
|
||||
}
|
||||
|
||||
/**
|
||||
* Paths in a runtime tree that belong to the user: the home folder, imported AppImages and script apps, and catalog
|
||||
* AppImages with their menu entries and markers. Tar-kind catalog packages (the desktop) unpack over /usr and cannot
|
||||
* be carried.
|
||||
*/
|
||||
static java.util.List<String> userPaths(File tree) throws IOException {
|
||||
java.util.List<String> paths = new java.util.ArrayList<>(java.util.Arrays.asList("root", "opt/appimages/user", "opt/droiddeck-apps", "opt/droiddeck/wincomponents"));
|
||||
for (String n : children(new File(tree, "usr/local/share/applications"))) {
|
||||
@@ -168,13 +163,6 @@ public final class RuntimeFileTree {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves each user path that exists in {@code from} into {@code to}, replacing what {@code to} ships there. With
|
||||
* {@code onlyMissing}, a path already present in {@code to} is left alone. On failure the paths already moved go back
|
||||
* before the exception is thrown. Rollback failures are suppressed on that exception; callers must retain the source
|
||||
* of any incomplete rollback.
|
||||
* Returns the moved paths.
|
||||
*/
|
||||
static java.util.List<String> carryUserData(File from, File to, boolean onlyMissing) throws IOException {
|
||||
return carryUserData(from, to, onlyMissing, new java.util.ArrayList<>(userPaths(from, to)));
|
||||
}
|
||||
@@ -200,7 +188,6 @@ public final class RuntimeFileTree {
|
||||
return moved;
|
||||
}
|
||||
|
||||
/** Puts the given paths back from {@code from} into {@code to}; failures are collected, not stopped on. */
|
||||
static void carryBack(File from, File to, java.util.List<String> paths) throws IOException {
|
||||
IOException failed = null;
|
||||
for (int i = paths.size() - 1; i >= 0; i--) {
|
||||
|
||||
@@ -10,7 +10,6 @@ object RuntimeHealth {
|
||||
|
||||
fun brokenLibraryLinks(context: Context): List<String> = brokenLibraryLinks(LinuxRuntime.rootDir(context))
|
||||
|
||||
/** A complete runtime has no library link in usr/lib whose target is missing. */
|
||||
fun brokenLibraryLinks(root: File): List<String> =
|
||||
listOf("usr/lib", "usr/lib/aarch64-linux-gnu").flatMap { dir ->
|
||||
val lib = File(root, dir)
|
||||
|
||||
@@ -117,7 +117,6 @@ class RuntimeInstallService : Service() {
|
||||
if (Build.VERSION.SDK_INT >= 26) context.startForegroundService(intent) else context.startService(intent)
|
||||
}
|
||||
|
||||
/** Keeps the process in the foreground until the returned release runs, so closing the app does not stop the install. */
|
||||
fun holdForPackage(context: Context, title: String): () -> Unit {
|
||||
packageTitle = title
|
||||
packageStage = title
|
||||
|
||||
Loaded 100 of 511 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user