Merge main into feat/neural-upscaler

Conflicts: drawer pages moved into functions on main (upscaler group now in
DrawerGamePage), launch.sh WSI bypass line, recipes.json/runtime_inputs.py
lists (main's IME entries + the upscale layer), game-environment tests (both
classes kept).
This commit is contained in:
The412Banner committed 2026-12-04 07:50:50 -05:00
commit 94bcfca5c0
449 files changed
+34769 -2967

No files matched your search

@@ -20,6 +20,10 @@ class App : Application() {
override fun onCreate() {
super.onCreate()
if (android.os.Build.VERSION.SDK_INT >= 28 &&
com.droiddeck.launcher.runtime.GuestWorker.isWorkerProcess(this, Application.getProcessName())) return
if (android.os.Build.VERSION.SDK_INT >= 28 && Application.getProcessName() == packageName)
com.droiddeck.launcher.runtime.GuestWorkers.attach(this)
com.droiddeck.launcher.runtime.NativeGuest.init(this)
com.droiddeck.launcher.session.Onboarding.attach(this)
Thread({ runCatching { EnhancedSessionLogShare.cleanupAbandonedStages(this) } }, "diagnostic-stage-cleanup").start()
@@ -25,6 +25,7 @@ import android.widget.EditText
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
@@ -192,13 +193,15 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private var prootNoSeccomp by mutableStateOf(false)
private var prootFastPath by mutableStateOf(true)
private var nativeUserland by mutableStateOf(true)
private var desktopAsUser by mutableStateOf(false)
private var cursorComposite by mutableStateOf(true)
private var guestHostname by mutableStateOf(SessionPrefs.DEFAULT_GUEST_HOSTNAME)
private var phantomWarning by mutableStateOf<String?>(null)
private var phantomProcessStatus by mutableStateOf(PhantomProcessStatus.NOT_APPLICABLE)
private var showPhantomGate by mutableStateOf(false)
private var directAudio by mutableStateOf(false)
private var picturePosition by mutableStateOf("center")
private var picturePositionLandscape by mutableStateOf("center")
private var picturePositionPortrait by mutableStateOf("top")
private var integerScaling by mutableStateOf(false)
private var stretch16x9 by mutableStateOf(false)
private var avoidNotch by mutableStateOf(false)
@@ -206,6 +209,12 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private var launcherOrientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER)
private var homePage by mutableStateOf(com.droiddeck.launcher.core.AppUiPrefs.HOME_PAGE_STEAM)
private var launcherFullscreen by mutableStateOf(true)
private var launcherFrost by mutableStateOf(false)
private var frostWallpaper by mutableStateOf(true)
private var frostCards by mutableStateOf(true)
private var frostTransparency by mutableStateOf(com.droiddeck.launcher.ui.FROST_WALLPAPER_DEFAULT)
private var frostCardTransparency by mutableStateOf(com.droiddeck.launcher.ui.FROST_DEFAULT)
private val frost = com.droiddeck.launcher.ui.LauncherFrost(this)
private var controllerHaptics by mutableStateOf(true)
private var downloadSource by mutableStateOf(DownloadSource.MODE_AUTO)
private var downloadMirror by mutableStateOf("")
@@ -296,9 +305,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
protons.installExperimental { progress -> com.droiddeck.launcher.session.ExperimentalProtons.installFromFile(this, zip, progress) }
}
}
private val pickLossless = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let { importLossless(it) }
}
private val pickSaveZip = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
val then = onSavePicked.also { onSavePicked = null } ?: return@registerForActivityResult
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let(then)
@@ -509,17 +515,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
bootMovieCustomName = com.droiddeck.launcher.session.BootMovie.customName(this)
}
private fun importLossless(dll: File) {
Thread({
val message = Lossless.message(this, Lossless.import(this, dll))
val state = Lossless.state(this)
ui.post {
lossless = state
android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_LONG).show()
}
}, "lossless-import").start()
}
private fun importSaves(name: String, game: () -> GameSaves.Game) {
if (SessionState.running) {
android.widget.Toast.makeText(this, R.string.main_saves_close_session, android.widget.Toast.LENGTH_LONG).show()
@@ -617,6 +612,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private var appScale by mutableStateOf(com.droiddeck.launcher.core.AppUiPrefs.DEFAULT_SCALE)
private var hdrOn by mutableStateOf(false)
private var zeroCopyOn by mutableStateOf(true)
private var producerAcquireFences by mutableStateOf(false)
private var upscaler by mutableStateOf(0)
private var upscaleSharpness by mutableStateOf(75)
private var hdrReason by mutableStateOf<String?>(null)
@@ -1092,6 +1088,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
} else {
putExtra(SessionService.EXTRA_STEAM_URL,
com.droiddeck.launcher.frontend.GameLaunchLink.steamUrl(game.gameIdString))
putExtra(SessionService.EXTRA_FRONTEND_STEAM_GAME, true)
}
}
.playing(game), steamSession = true)
@@ -1371,6 +1368,14 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
requestedOrientation = launcherOrientation
homePage = com.droiddeck.launcher.core.AppUiPrefs.homePage(this)
launcherFullscreen = SessionPrefs.launcherFullscreen(this)
launcherFrost = SessionPrefs.launcherFrost(this)
frostWallpaper = SessionPrefs.frostWallpaper(this)
frostCards = SessionPrefs.frostCards(this)
frostTransparency = SessionPrefs.frostTransparency(this)
frostCardTransparency = SessionPrefs.frostCardTransparency(this)
frost.start()
frost.prepare(launcherFrost && frostWallpaper)
frost.show(frostShown())
controllerHaptics = SessionPrefs.controllerHaptics(this)
downloadSource = DownloadSource.mode(this)
downloadMirror = DownloadSource.mirror(this)
@@ -1395,8 +1400,14 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
val appsTabShown = "android-apps" !in com.droiddeck.launcher.ui.NavTabs.hidden
androidx.compose.runtime.LaunchedEffect(appsTabShown) { if (appsTabShown && androidApps.isEmpty()) refreshAndroidApps() }
DroidDeckTheme(theme, appScale = appScale) {
com.droiddeck.launcher.ui.FocusGlideHost(androidx.compose.ui.Modifier.fillMaxSize().exposeTestTags()) {
val frostShown = frostShown()
androidx.compose.runtime.LaunchedEffect(frostShown) { frost.show(frostShown) }
val frostChoice = if (frostShown) com.droiddeck.launcher.ui.FrostChoice(frostTransparency, frostCards, frostCardTransparency) else null
DroidDeckTheme(theme, appScale = appScale, frost = frostChoice) {
val palette = com.droiddeck.launcher.ui.LocalPalette.current
val veil = com.droiddeck.launcher.ui.LocalFrost.current
val ground = if (frost.prepared) androidx.compose.ui.Modifier.background(veil ?: palette.background) else androidx.compose.ui.Modifier
com.droiddeck.launcher.ui.FocusGlideHost(androidx.compose.ui.Modifier.fillMaxSize().then(ground).exposeTestTags()) {
if (decky.deckyPendingZip != null) com.droiddeck.launcher.ui.DeckyZipWarningDialog(
onConfirm = { decky.confirmPluginZip() }, onCancel = { decky.cancelPluginZip() },
)
@@ -1472,6 +1483,12 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
launcherOrientation = launcherOrientation,
homePage = homePage,
launcherFullscreen = launcherFullscreen,
launcherFrost = launcherFrost,
frostWallpaper = frostWallpaper,
frostCards = frostCards,
frostTransparency = frostTransparency,
frostCardTransparency = frostCardTransparency,
frostSupported = frost.supported,
controllerHaptics = controllerHaptics,
downloadSource = downloadSource,
downloadMirror = downloadMirror,
@@ -1630,9 +1647,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
FrameGen.set(this, mode)
frameGenLabel = FrameGen.label(this)
},
onImportLossless = {
pickLossless.launch(InAppFilePicker.buildIntent(this, listOf("dll"), getString(R.string.lsfg_pick_title)))
},
onProtons = { openProtons() },
onComponents = { focusContent -> openComponents(focusContent) },
onGameComponents = { game -> openComponents(gameKey = game.profileKey) },
@@ -1807,6 +1821,28 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
launcherFullscreen = on
applyLauncherFullscreen()
},
onLauncherFrost = { on ->
SessionPrefs.setLauncherFrost(this, on)
launcherFrost = on
if (on && frostWallpaper && !frost.prepared) restartLauncher()
},
onFrostWallpaper = { on ->
SessionPrefs.setFrostWallpaper(this, on)
frostWallpaper = on
if (on && !frost.prepared) restartLauncher()
},
onFrostCards = { on ->
SessionPrefs.setFrostCards(this, on)
frostCards = on
},
onFrostTransparency = { percent ->
SessionPrefs.setFrostTransparency(this, percent)
frostTransparency = SessionPrefs.frostTransparency(this)
},
onFrostCardTransparency = { percent ->
SessionPrefs.setFrostCardTransparency(this, percent)
frostCardTransparency = SessionPrefs.frostCardTransparency(this)
},
onGameStoresSpeedTier = { tier -> SessionPrefs.setGameStoresSpeedTier(this, tier); gameStoresSpeedTier = tier },
onNavigated = { navRequest = null },
onStoresShowMature = { show -> SessionPrefs.setStoresShowMature(this, show); storesShowMature = show },
@@ -2113,6 +2149,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
}
private fun frostShown(): Boolean =
launcherFrost && frostWallpaper && frost.prepared && frost.available && theme != com.droiddeck.launcher.ui.Themes.TRUE_BLACK
private fun applyLauncherFullscreen() {
@Suppress("DEPRECATION")
window.decorView.systemUiVisibility = if (launcherFullscreen) {
@@ -2194,7 +2233,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
return true
}
return try {
super.dispatchKeyEvent(event)
super.dispatchKeyEvent(event) || com.droiddeck.launcher.ui.PageBumpers.handle(event)
} catch (e: IllegalStateException) {
if (e.message?.contains("active focus target") != true) throw e
android.util.Log.w("MainActivity", "key ${event.keyCode} dropped: ${e.message}")
@@ -2203,6 +2242,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
private val triggerKeys = com.droiddeck.launcher.input.TriggerKeys { dispatchKeyEvent(it) }
internal fun onMenuMotion(event: MotionEvent) = triggerKeys.onMotion(event)
private val rightStickLayouts = HashMap<Int, Boolean>()
private val rightStickScrollHandler = android.os.Handler(android.os.Looper.getMainLooper())
private var rightStickScrollDeviceId = -1
@@ -2264,7 +2306,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
!com.droiddeck.launcher.input.PadBridge.isControllerMotionEvent(event)) return
val device = event.device ?: return
val rxRy = com.droiddeck.launcher.input.PadBridge.rightStickUsesRxRy(event, device, rightStickLayouts)
?: return
?: run {
if (rightStickScrollDeviceId == event.deviceId) stopRightStickScroll()
return
}
val axis = if (rxRy) android.view.MotionEvent.AXIS_RY else android.view.MotionEvent.AXIS_RZ
val value = event.getAxisValue(axis)
if (kotlin.math.abs(value) < 0.55f) {
@@ -2321,7 +2366,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
refreshHomeAppState()
}
if (settingsMode == SessionService.MODE_STEAM) refreshFoundSteamLibraries()
settingsMode?.let { hdrOn = SessionPrefs.hdr(this, it) }
settingsMode?.let { mode ->
hdrOn = SessionPrefs.hdr(this, mode)
if (mode == SessionService.MODE_STEAM) loadPicturePositions()
}
compatLaunchVisible = true
com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false)
com.droiddeck.launcher.ui.DualScreenPanel.ownerPaused(taskId, false)
@@ -2457,6 +2505,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
launchCoordinator.cancelAll()
cancelCompatLaunch()
updates.unregister()
frost.stop()
runCatching { unregisterReceiver(shortcutsInstallStatus) }
super.onDestroy()
}
@@ -2861,6 +2910,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
mode = mode, resolution = resolution, resolutionPortrait = resolutionPortrait,
panelSize = com.droiddeck.launcher.session.SessionDisplay.panelSize(this),
hdr = hdrOn, hdrReason = hdrReason, hdrDisplay = hdrDisplay, zeroCopy = zeroCopyOn,
producerAcquireFences = producerAcquireFences.takeIf {
mode == SessionService.MODE_STEAM &&
com.droiddeck.launcher.runtime.FrameAcquireWorkerProbe.available(this)
},
upscaler = upscaler, upscaleSharpness = upscaleSharpness,
gpuDrivers = drivers.summary(),
touchMode = touchMode,
@@ -2875,7 +2928,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
backHold = backHold,
backActionsInverted = backActionsInverted,
directAudio = if (mode == SessionService.MODE_STEAM) directAudio else null,
picturePosition = if (mode == SessionService.MODE_STEAM) picturePosition else null,
picturePositionLandscape = picturePositionLandscape.takeIf { mode == SessionService.MODE_STEAM },
picturePositionPortrait = picturePositionPortrait.takeIf { mode == SessionService.MODE_STEAM },
integerScaling = if (mode == SessionService.MODE_STEAM) integerScaling else null,
stretch16x9 = if (mode == SessionService.MODE_STEAM) stretch16x9 else null,
avoidNotch = if (mode == SessionService.MODE_STEAM) avoidNotch else null,
@@ -2925,6 +2979,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
SessionPrefs.prefMode(SessionState.mode) == SessionPrefs.prefMode(mode))
com.droiddeck.launcher.wayland.WaylandCompositor.nativeSetZeroCopy(on)
},
onProducerAcquireFences = {
SessionPrefs.setProducerAcquireFences(this, it)
producerAcquireFences = it
},
onGpuDrivers = { openComponents(focusContent = true, tab = com.droiddeck.launcher.ui.GPU_TAB) },
onUpscaler = { m -> SessionPrefs.setUpscaler(this, m); upscaler = m },
onUpscaleSharpness = { pct -> SessionPrefs.setUpscaleSharpness(this, pct); upscaleSharpness = pct },
@@ -2948,7 +3006,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
backActionsInverted = inverted
},
onDirectAudio = { on -> SessionPrefs.setDirectAudio(this, on); directAudio = on },
onPicturePosition = { value -> SessionPrefs.setPicturePosition(this, value); picturePosition = value },
onPicturePosition = { portrait, value ->
SessionPrefs.setPicturePosition(this, portrait, value)
if (portrait) picturePositionPortrait = value else picturePositionLandscape = value
},
onIntegerScaling = { on -> SessionPrefs.setIntegerScaling(this, on); integerScaling = on },
onStretch16x9 = { on -> SessionPrefs.setStretch16x9(this, on); stretch16x9 = on },
onAvoidNotch = { on -> SessionPrefs.setAvoidNotch(this, on); avoidNotch = on },
@@ -3046,7 +3107,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
fsyncFirst = fsyncFirst,
gamescopeRealtime = gamescopeRealtime,
gpuClockPin = gpuClockPin,
prootNoSeccomp = prootNoSeccomp, prootFastPath = prootFastPath, nativeUserland = nativeUserland, cursorComposite = cursorComposite,
prootNoSeccomp = prootNoSeccomp, prootFastPath = prootFastPath, nativeUserland = nativeUserland, desktopAsUser = desktopAsUser, cursorComposite = cursorComposite,
guestHostname = guestHostname, phantomWarning = phantomWarning,
onClientOverride = { on -> SessionPrefs.setClientCpusOverride(this, on); clientOverride = on },
onPaceCores = { on -> SessionPrefs.setPaceCores(this, on); paceCores = on },
@@ -3063,6 +3124,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
onProotNoSeccomp = { on -> SessionPrefs.setProotNoSeccomp(this, on); prootNoSeccomp = on },
onProotFastPath = { on -> SessionPrefs.setProotFastPath(this, on); prootFastPath = on },
onNativeUserland = { on -> SessionPrefs.setNativeUserland(this, on); nativeUserland = on },
onDesktopAsUser = { on -> SessionPrefs.setDesktopAsUser(this, on); desktopAsUser = on },
onCursorComposite = { on -> SessionPrefs.setCursorComposite(this, on); cursorComposite = on },
onGuestHostname = { name -> SessionPrefs.setGuestHostname(this, name) },
onClientCore = { core, on ->
@@ -3264,6 +3326,11 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
resolutionPortrait = SessionPrefs.resolutionStored(this, mode, panel, true)
}
private fun loadPicturePositions() {
picturePositionLandscape = SessionPrefs.picturePosition(this, portrait = false)
picturePositionPortrait = SessionPrefs.picturePosition(this, portrait = true)
}
private fun loadModeSettings(mode: String) {
pipAutoEnter = SessionPrefs.pipAutoEnter(this)
unfoldedControls = SessionPrefs.unfoldedControls(this)
@@ -3285,6 +3352,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
loadBootMovie()
hdrOn = SessionPrefs.hdr(this, mode)
zeroCopyOn = SessionPrefs.zeroCopy(this, mode)
producerAcquireFences = SessionPrefs.producerAcquireFences(this)
upscaler = SessionPrefs.upscaler(this)
upscaleSharpness = SessionPrefs.upscaleSharpness(this)
hdrReason = com.droiddeck.launcher.wayland.HdrSupport.blocked(this)
@@ -3298,7 +3366,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
backHold = SessionPrefs.backHold(this)
backActionsInverted = SessionPrefs.backActionsInverted(this)
directAudio = SessionPrefs.directAudio(this)
picturePosition = SessionPrefs.picturePosition(this)
loadPicturePositions()
integerScaling = SessionPrefs.integerScaling(this)
stretch16x9 = SessionPrefs.stretch16x9(this)
avoidNotch = SessionPrefs.avoidNotch(this)
@@ -3381,6 +3449,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
prootNoSeccomp = SessionPrefs.prootNoSeccomp(this)
prootFastPath = SessionPrefs.prootFastPath(this)
nativeUserland = SessionPrefs.nativeUserland(this)
desktopAsUser = SessionPrefs.desktopAsUser(this)
cursorComposite = SessionPrefs.cursorComposite(this)
guestHostname = SessionPrefs.guestHostname(this)
refreshPhantomStatus()
@@ -4,25 +4,32 @@ import android.app.NativeActivity
import android.os.Bundle
import android.os.SystemClock
import android.util.Log
import android.view.Surface
import android.widget.Toast
import com.droiddeck.launcher.gpu.SteamVr
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.session.xr.XrLayerSource
import com.droiddeck.launcher.session.xr.XrPanels
import com.droiddeck.launcher.wayland.CompositorHost
import com.droiddeck.launcher.wayland.WaylandCompositor
class QuestXrActivity : NativeActivity() {
class QuestXrActivity : NativeActivity(), XrLayerSource {
private var steamVrStarted = false
@Volatile private var closing = false
@Volatile private var steamVrStatus = SteamVr.Status.UNAVAILABLE
private var sessionId: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
// NativeActivity opens the library itself, but the layer host's JNI methods resolve only
// through a System.loadLibrary.
System.loadLibrary("droiddeckxr")
sessionId = SessionState.sessionId
SessionService.setXrActivityVisible(this, true)
super.onCreate(savedInstanceState)
}
fun onXrActive(active: Boolean) {
XrPanels.setDrawing(active)
if (active) {
check(CompositorHost.isStarted) { "DroidDeck compositor is not running" }
SessionService.resume(this)
@@ -100,8 +107,30 @@ class QuestXrActivity : NativeActivity() {
fun onXrStatus(): Int = steamVrStatus.ordinal
fun onXrHostBuffers(state: java.nio.ByteBuffer, control: java.nio.ByteBuffer) {
runOnUiThread { if (!closing) XrPanels.attach(this, state, control) }
}
fun onXrHostFrame() = XrPanels.frame()
override val context: android.content.Context get() = this
override fun createLayer(width: Int, height: Int) = nativeCreateLayer(width, height)
override fun layerSurface(id: Int) = nativeLayerSurface(id)
override fun destroyLayer(id: Int) = nativeDestroyLayer(id)
override fun setOrbImage(image: android.graphics.Bitmap) = nativeSetOrbImage(image)
override fun leave() {
closing = true
finish()
}
private external fun nativeCreateLayer(width: Int, height: Int): Int
private external fun nativeLayerSurface(id: Int): Surface?
private external fun nativeDestroyLayer(id: Int)
private external fun nativeSetOrbImage(image: android.graphics.Bitmap)
override fun onDestroy() {
closing = true
XrPanels.detach()
SessionService.setXrActivityVisible(this, false)
super.onDestroy()
}
@@ -76,6 +76,7 @@ import com.droiddeck.launcher.input.InputSpace
import com.droiddeck.launcher.input.KeyboardHost
import com.droiddeck.launcher.input.ControllerPrefs
import com.droiddeck.launcher.input.SessionClipboard
import com.droiddeck.launcher.input.SessionTextInput
import com.droiddeck.launcher.input.OnScreenControls
import com.droiddeck.launcher.input.OnScreenLayout
import com.droiddeck.launcher.input.InputRouter
@@ -162,7 +163,8 @@ import kotlin.math.abs
private const val SCREEN_EFFECTS_TARGET_AUTO = "auto"
private const val SCREEN_EFFECTS_TARGET_GLOBAL = "global"
class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droiddeck.launcher.ui.AgentPetHost {
class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droiddeck.launcher.ui.AgentPetHost,
com.droiddeck.launcher.session.xr.XrMenuHost {
override fun attachBaseContext(newBase: android.content.Context) {
super.attachBaseContext(newBase)
com.droiddeck.launcher.core.AppLanguage.applyTo(this, newBase)
@@ -178,6 +180,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private var adaptiveSticks by mutableStateOf<Boolean?>(null)
private var quickButtons by mutableStateOf<Map<InputCommand, Boolean>>(emptyMap())
private var picturePosition by mutableStateOf("center")
private fun picturePortrait(config: android.content.res.Configuration = resources.configuration): Boolean =
config.orientation == android.content.res.Configuration.ORIENTATION_PORTRAIT
private var integerScaling by mutableStateOf(false)
private var gameZoom by mutableStateOf(SessionState.gameZoom)
private var avoidNotch = false
@@ -228,6 +233,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
private var unfoldedPanel by mutableStateOf<OnScreenControls?>(null)
private var unfoldedColumn: android.widget.LinearLayout? = null
private var unfoldedKeys: View? = null
private var unfoldedDeckSurface: com.droiddeck.launcher.ui.InputSurfaceView? = null
private var swappedInputSurface: com.droiddeck.launcher.ui.InputSurfaceView? = null
private var unfoldedDeckPanel by mutableStateOf<com.droiddeck.launcher.input.DeckPanel?>(null)
@@ -348,6 +354,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
window.decorView.hasWindowFocus() || secondScreenPresentation?.window?.decorView?.hasWindowFocus() == true
}
}
private val sessionTextInput by lazy {
SessionTextInput(this) {
window.decorView.hasWindowFocus() || secondScreenPresentation?.window?.decorView?.hasWindowFocus() == true
}
}
private var watching = true
private lateinit var touchpad: TouchpadGestures
private lateinit var directTouchHold: DirectTouchHold
@@ -546,6 +557,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private var drawerOpenState by mutableStateOf(false)
private var typingReturnMode: SecondScreenMode? = null
private var drawerDocked by mutableStateOf(false)
/** The menu is open as a floating panel in the immersive Quest view instead of over this window. */
private var drawerXr by mutableStateOf(false)
private var drawerPinned by mutableStateOf(false)
private var drawerLayerOpen = false
private var drawerBackRequests by mutableIntStateOf(0)
@@ -563,9 +576,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
drawerPinned = false
if (value) {
releaseHeldKeys()
drawerDocked = dockDrawer() && openDockedMenu()
drawerXr = com.droiddeck.launcher.session.xr.XrPanels.showMenu()
drawerDocked = !drawerXr && dockDrawer() && openDockedMenu()
}
drawerOpenState = value
if (!value && drawerXr) {
drawerXr = false
com.droiddeck.launcher.session.xr.XrPanels.hideMenu()
}
if (!value && drawerDocked) closeDockedMenu()
}
private val dockedMenuIdle: Boolean get() = com.droiddeck.launcher.input.DualScreen.menuIdleOnBottom(drawerOpen, drawerDocked, drawerPinned, dockedMenuController)
@@ -703,9 +721,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private var drawerTextureAnisotropy by mutableStateOf<Int?>(null)
private var drawerTextureLodBias by mutableStateOf<String?>(null)
private var lossless by mutableStateOf(Lossless.State.NONE)
private val pickLossless = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let { importLossless(it) }
}
private var frameGen by mutableStateOf(FrameGen.Mode.OFF)
private var frameGenActiveGameId by mutableStateOf<Long?>(null)
private var frameGenActiveGameName by mutableStateOf<String?>(null)
@@ -807,6 +822,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
private var isHomeApp by mutableStateOf(false)
private var androidApps by mutableStateOf<List<HomeApp.LaunchableApp>>(emptyList())
private var padConnected by mutableStateOf(false)
private val deviceListener = object : InputManager.InputDeviceListener {
override fun onInputDeviceAdded(deviceId: Int) {
@@ -849,6 +865,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
com.droiddeck.launcher.session.xr.XrPanels.setMenuHost(this)
AgentGuest.readyListener = agentReadyListener
com.droiddeck.launcher.agent.AgentAttachments.gameFrame = gameFrame
if (com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.isRemoving() ||
@@ -979,6 +996,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
openDeckRing("activity created")
bridge.setOnPlayerInput(::onPadInput)
onScreenControls = OnScreenControls(this, bridge).also { controls ->
controls.alpha = onScreenOpacityAlpha()
controls.updateLayout(primaryInputLayout)
controls.onTouchMiss = miss@{ event ->
if (!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.ON_SCREEN_CONTROLS, event)) return@miss
@@ -987,7 +1005,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
root.addView(controls)
}
keyboard = KeyboardHost(this).also { host ->
keyboard = KeyboardHost(this, sendKeyEvent = ::dispatchImeKeyEvent, sendText = WaylandCompositor::textInputCommit).also { host ->
host.onImeChanged = ::onPrimaryImeChanged
root.addView(host)
}
@@ -1192,7 +1210,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
val cursorHidden = cursorHiddenByUi()
androidx.compose.runtime.SideEffect {
com.droiddeck.launcher.glasses.GlassesMenuMirror.setSessionMenuVisible(this@SessionActivity,
(drawerOpen || achievementsOpen || pcKeyboardOpen) && !pipUi && steamVrStatus != SteamVr.Status.RUNNING)
(drawerOpen || achievementsOpen || pcKeyboardOpen) && !pipUi && !drawerXr && steamVrStatus != SteamVr.Status.RUNNING)
}
androidx.compose.runtime.SideEffect { applyPlatformPointer(uiPointer) }
androidx.compose.runtime.DisposableEffect(Unit) {
@@ -1262,14 +1280,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
glasses.usesSpatialControllers(glassesSettings) && glassesSettings.joyConTracking)
joyConVr?.let { { it.recenter() } } else null,
) { headTracker?.recenter() }
if (!phonePanel && glasses.present && !drawerOpen && !pcKeyboardOpen && !loading.visible) com.droiddeck.launcher.ui.GlassesCornerButton(glassesSlot,
val showGlassesShortcut = com.droiddeck.launcher.ui.rememberShowGlassesShortcut()
if (!phonePanel && glasses.present && showGlassesShortcut && !drawerOpen && !pcKeyboardOpen && !loading.visible) com.droiddeck.launcher.ui.GlassesCornerButton(glassesSlot,
controllerSettings?.tint ?: android.graphics.Color.rgb(90, 160, 255), controllerSettings?.opacity ?: 100) {
drawerPage = com.droiddeck.launcher.ui.SessionDrawerPage.GLASSES
drawerPage = com.droiddeck.launcher.ui.SessionDrawerPage.VR
drawerOpen = true
}
if (!drawerOpen && !pcKeyboardOpen && !loading.visible) {
com.droiddeck.launcher.ui.DrawerEntryHint(SessionState.mode == SessionService.MODE_STEAM, backActionsInverted) { drawerOpen = true }
if (cornerTap) com.droiddeck.launcher.ui.DrawerCornerTap { drawerOpen = true }
if (com.droiddeck.launcher.session.QuestExperimental.isSupported())
com.droiddeck.launcher.ui.DrawerEdgeSwipe { onBackPressedDispatcher.onBackPressed() }
}
if (loading.visible) LoadingOverlay(
loading.step, loading.percent, loading.elapsed, loading.hint, loading.ended,
@@ -1451,7 +1472,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
}
LaunchedEffect(drawerOpen, achievementsOpen, AgentGuest.focusRevision, StoreAchievements.revision) {
if (!drawerOpen && !achievementsOpen) return@LaunchedEffect
if (!drawerOpen && !achievementsOpen) {
achievementsInFront = null
return@LaunchedEffect
}
val found = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
runCatching { resolveAchievementsInFront() }
.onFailure { Log.w(TAG, "achievements in front: ${it.javaClass.simpleName}") }.getOrNull()
@@ -1470,11 +1494,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
onAndroidKeyboard = { pcKeyboardOpen = false; togglePrimaryKeyboard() },
onClose = { pcKeyboardOpen = false },
)
if (!drawerDocked) SessionMenu(
if (!drawerDocked && !drawerXr) SessionMenu(
docked = false,
effectsEditorProfileId = effectsEditorProfileId,
effectsEditorTarget = effectsEditorTarget,
)
if (drawerOpen && !drawerDocked && !drawerXr && com.droiddeck.launcher.session.QuestExperimental.isSupported())
com.droiddeck.launcher.ui.DrawerEdgeSwipe { onBackPressedDispatcher.onBackPressed() }
LaunchedEffect(achievementsOpen) {
if (achievementsOpen) {
releasePads()
@@ -1523,6 +1549,74 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
}
@androidx.compose.runtime.Composable
override fun XrMenuContent() {
val activeEffectsProfileId = currentScreenEffectsProfileId()
val effectsEditorTarget = if (drawerOpen) screenEffectsTarget else null
val effectsEditorProfileId = activeEffectsProfileId.takeIf { effectsEditorTarget == SCREEN_EFFECTS_TARGET_AUTO }
androidx.compose.runtime.LaunchedEffect(effectsEditorTarget, effectsEditorProfileId) {
when (effectsEditorTarget) {
SCREEN_EFFECTS_TARGET_AUTO -> syncActiveScreenEffectsProfile()
null -> Unit
else -> syncScreenEffectsTarget(effectsEditorTarget)
}
}
SessionMenu(docked = true, effectsEditorProfileId = effectsEditorProfileId, effectsEditorTarget = effectsEditorTarget)
}
override fun xrSetMenuOpen(open: Boolean) {
if (open != drawerOpen) drawerOpen = open
}
/**
* In the immersive Quest view, Stop takes the user back to this window with the session still
* running, and Stop SteamVR leaves at once instead of after the stop is noticed.
*/
private fun leaveXrMenu() {
if (!drawerXr) return
drawerOpen = false
com.droiddeck.launcher.session.xr.XrPanels.leaveImmersive()
}
override fun xrMenuBack() {
if (drawerLayerOpen) drawerBackRequests++ else drawerOpen = false
}
override fun xrSendKey(code: Int, down: Boolean) {
if (CompositorHost.isStarted) sendGuestKey(code, down, 32)
}
override fun xrTypeText(text: String) = xrKeys.type(text)
override fun xrImmersiveChanged(active: Boolean) {
if (active) {
if (immersiveFlatSize == null) immersiveFlatSize = SessionState.outputSize
resizeOutputForWindow(surfaceW, surfaceH)
return
}
val flat = immersiveFlatSize
immersiveFlatSize = null
if (windowOutputSize(surfaceW, surfaceH) == null && flat != null) applyOutputSize(flat)
else resizeOutputForWindow(surfaceW, surfaceH)
}
/** The output's size when the immersive view opened; this window may have no surface while it is up. */
private var immersiveFlatSize: Pair<Int, Int>? = null
override fun xrTapKey(keyCode: Int) = xrKeys.tap(keyCode)
/** The VR keyboard's keys go straight to the game, past the menu and pad handling a real key passes through. */
private val xrKeys by lazy {
KeyboardHost(
this,
sendKeyEvent = { event ->
CompositorHost.isStarted && (event.action != KeyEvent.ACTION_DOWN || event.repeatCount == 0) &&
com.droiddeck.launcher.input.GuestKeys.send(event) { code, pressed -> sendGuestKey(code, pressed, 16) }
},
sendText = { text -> if (CompositorHost.isStarted) WaylandCompositor.textInputCommit(text) },
)
}
@androidx.compose.runtime.Composable
private fun SessionMenu(
docked: Boolean,
@@ -1626,6 +1720,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
SessionState.gameZoom = gameZoom
runCatching { WaylandCompositor.nativeSetZoom(gameZoom) }
},
picturePosition = picturePosition,
onPicturePosition = { position ->
SessionPrefs.setPicturePosition(this@SessionActivity, picturePortrait(), position)
picturePosition = position
},
integerScaling = integerScaling,
onIntegerScaling = { enabled ->
SessionPrefs.setIntegerScaling(this@SessionActivity, enabled)
@@ -1787,7 +1886,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
onBlackFrameInsertion = { on ->
SessionPrefs.setBlackFrameInsertion(this@SessionActivity, on)
blackFrameInsertion = on
CompositorHost.setBlackFrameInsertion(on, refreshHz(), outputFpsLimit())
CompositorHost.setBlackFrameInsertion(on, refreshHz(), compositorFpsLimit())
},
hdr = hdrWanted,
hdrAvailable = hdrAvailable,
@@ -1810,10 +1909,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
readPrefs()
applyFrameGen(force = true)
},
onImportLossless = {
pickLossless.launch(InAppFilePicker.buildIntent(
this@SessionActivity, listOf("dll"), getString(R.string.lsfg_pick_title)))
},
onKeyboard = { drawerOpen = false; pcKeyboardOpen = false; togglePrimaryKeyboard() },
onHardwareKeyboard = ::togglePcKeyboard,
wowChatShown = com.droiddeck.launcher.ui.WowChat.isWow(AgentGuest.gameProgram),
@@ -1821,10 +1916,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
onWowChat = wowChat::choose,
controller = controllerSettings,
onControllerSize = { percent -> updateControllerPrefs { ControllerPrefs.setSize(this@SessionActivity, percent) } },
onControllerOpacity = { percent ->
ControllerPrefs.setOnScreenOpacity(this@SessionActivity, percent)
controllerSettings = ControllerPrefs.read(this@SessionActivity)
applyOnScreenOpacity()
},
onRumble = { on -> updateControllerPrefs { ControllerPrefs.setRumble(this@SessionActivity, on) } },
onSteamMenu = if (SessionState.mode == SessionService.MODE_STEAM) ({ sendSteamGuide() }) else null,
onQam = if (SessionState.mode == SessionService.MODE_STEAM) ({ triggerSteamQam() }) else null,
onAchievements = achievementsInFront?.let { { drawerOpen = false; achievementsOpen = true } },
controllerConnected = padConnected,
achievementsGame = achievementsInFront?.game,
achievementsTitle = achievementsInFront?.title,
achievementsProgress = achievementsInFront?.progress,
padType = if (SessionState.mode == SessionService.MODE_STEAM && SessionState.deckPad) padType else null,
onPadType = { id ->
@@ -1899,9 +2001,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
SessionService.suspendPolicyChanged(this@SessionActivity)
},
onTouch = { v -> SessionPrefs.setTouchMode(this@SessionActivity, v); readPrefs() },
onInputSettings = { releasePads(); drawerOpen = false; inputSettingsOpen = true },
onInputSettings = { leaveImmersiveForDialog(); releasePads(); drawerOpen = false; inputSettingsOpen = true },
onInputSelection = { releasePads(); refreshInputProfile() },
onGestureSettings = { drawerOpen = false; gestureSettingsOpen = true },
onGestureSettings = { leaveImmersiveForDialog(); drawerOpen = false; gestureSettingsOpen = true },
touchActive = drawerTouchMode(),
directHoldBehavior = directHoldBehavior,
onDirectHoldBehavior = { value ->
@@ -1945,7 +2047,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
onResume = { SessionService.resume(this@SessionActivity) },
orientation = sessionOrientation,
onOrientation = { value ->
SessionPrefs.setOrientation(this@SessionActivity, value)
when (SessionState.mode) {
SessionService.MODE_STEAM, SessionService.MODE_RUN ->
SessionPrefs.setOrientation(this@SessionActivity, "steam", value)
SessionService.MODE_DESKTOP ->
SessionPrefs.setOrientation(this@SessionActivity, "desktop", value)
else -> SessionPrefs.setOrientation(this@SessionActivity, value)
}
sessionOrientation = value
applyFollowOrientation(resources.configuration)
},
@@ -1956,6 +2064,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
},
unfoldedControls = unfoldedControls,
onUnfoldedControls = ::chooseUnfoldedControls,
deckPanel = unfoldedDeckPanel,
onDeckPanel = ::selectDeckPanel,
adaptiveSticks = adaptiveSticks.takeIf {
unfoldedPanel != null || oscMode != SessionPrefs.OSC_NEVER && oscMode != SessionPrefs.OSC_STEAM_QAM && !steamTouchInUse
},
@@ -1992,18 +2102,26 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
onUnfoldedControlsWithController = ::chooseUnfoldedControlsWithController,
onBackground = { drawerOpen = false; pip.background(); moveTaskToBack(true) },
onShareLogs = { drawerOpen = false; shareCurrentSessionLogs() },
onStop = { drawerOpen = false; SessionService.stop(this@SessionActivity); finish() },
onStop = {
if (drawerXr) leaveXrMenu() else {
drawerOpen = false
SessionService.stop(this@SessionActivity)
finish()
}
},
onStopFrom = { onScreen ->
drawerOpen = false
if (onScreen == null || com.droiddeck.launcher.ui.Motion.scale == 0f || quitFrom != null) {
if (quitFrom == null) { SessionService.stop(this@SessionActivity); finish() }
} else {
val at = IntArray(2).also { sessionOverlay.getLocationOnScreen(it) }
quitFrom = onScreen.translate(-at[0].toFloat(), -at[1].toFloat())
if (drawerXr) leaveXrMenu() else {
drawerOpen = false
if (onScreen == null || com.droiddeck.launcher.ui.Motion.scale == 0f || quitFrom != null) {
if (quitFrom == null) { SessionService.stop(this@SessionActivity); finish() }
} else {
val at = IntArray(2).also { sessionOverlay.getLocationOnScreen(it) }
quitFrom = onScreen.translate(-at[0].toFloat(), -at[1].toFloat())
}
}
},
onClose = { drawerOpen = false },
onDismissScreen = if (docked) ({ selectSecondScreenMode(SecondScreenMode.NONE) }) else null,
onDismissScreen = if (docked && !drawerXr) ({ selectSecondScreenMode(SecondScreenMode.NONE) }) else null,
components = drawerComponents,
onComponentsRefresh = {
refreshDrawerComponents()
@@ -2081,7 +2199,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}) else null,
onKeyboard = { togglePrimaryKeyboard() },
onSessionMenu = { drawerOpen = true },
onStopSteamVr = if (vr) ({ steamVrAction("stop") }) else null,
onStopSteamVr = if (vr) ({ leaveXrMenu(); steamVrAction("stop") }) else null,
brightness = glasses.brightness,
brightnessMax = glasses.brightnessMax,
onBrightness = if (glasses.canControl && glasses.hardwareControls) Glasses::setBrightness else null,
@@ -2120,6 +2238,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun togglePcKeyboard() {
drawerOpen = false
if (com.droiddeck.launcher.session.xr.XrPanels.toggleGameKeyboard(pc = true)) return
hidePrimaryKeyboard()
onScreenControls?.releaseAll()
bottomInputControls?.releaseAll()
@@ -2129,12 +2248,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun showPrimaryKeyboard() {
pendingFieldKeyboard = false
fieldKeyboardOnPrimary = false
if (com.droiddeck.launcher.session.xr.XrPanels.showGameKeyboard(pc = false)) return
keyboard?.show()
}
private fun togglePrimaryKeyboard() {
pendingFieldKeyboard = false
fieldKeyboardOnPrimary = false
if (com.droiddeck.launcher.session.xr.XrPanels.toggleGameKeyboard(pc = false)) return
keyboard?.toggle()
}
@@ -2158,6 +2279,18 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (fieldKeyboardOnPrimary) hidePrimaryKeyboard()
}
private fun onScreenOpacityAlpha() = ControllerPrefs.onScreenOpacity(this) / 100f
private fun applyOnScreenOpacity() {
val alpha = onScreenOpacityAlpha()
onScreenControls?.alpha = alpha
bottomInputControls?.alpha = alpha
unfoldedColumn?.alpha = alpha
swappedInputSurface?.alpha = alpha
secondScreenPresentation?.controlsView?.alpha = alpha
steamTouchControls?.let { it.alpha = if (it.isEditing) 1f else alpha }
}
private fun updateControllerPrefs(change: () -> Unit) {
change()
controllerSettings = ControllerPrefs.read(this)
@@ -2668,7 +2801,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
pipAutoEnter = SessionPrefs.pipAutoEnter(this)
unfoldedControls = SessionPrefs.unfoldedControls(this)
unfoldedControlsWithController = SessionPrefs.unfoldedControlsWithController(this)
picturePosition = SessionPrefs.picturePosition(this)
picturePosition = SessionPrefs.picturePosition(this, picturePortrait())
integerScaling = SessionPrefs.integerScaling(this)
avoidNotch = SessionPrefs.avoidNotch(this)
applyNotchInset()
@@ -2724,7 +2857,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
oscTrackpads = SessionPrefs.oscTrackpads(this)
backHold = SessionPrefs.backHold(this)
dockedMenuController = SessionPrefs.dockedMenuController(this)
sessionOrientation = SessionPrefs.orientation(this)
sessionOrientation = SessionPrefs.orientation(this, SessionState.mode)
dualScreenSessionMode = SessionPrefs.dualScreenSessionMode(this)
backActionsInverted = SessionPrefs.backActionsInverted(this)
physicalShortcuts.bindings = PhysicalShortcuts.read(this)
@@ -2990,7 +3123,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
CompositorHost.startOrAttach(
this, holder.surface, runtimeDir.path,
driverId?.let { turnip.driverPath(it) }, driverId?.let { turnip.libraryName(it) },
applicationInfo.nativeLibraryDir, size.first, size.second, refreshHz(holder), outputFpsLimit(),
applicationInfo.nativeLibraryDir, size.first, size.second, refreshHz(holder), compositorFpsLimit(),
)
onOutputAttached(holder)
if (SessionState.running && size != previous) {
@@ -3008,6 +3141,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
intent.getStringArrayExtra(SessionService.EXTRA_PROGRAM_ARGS),
intent.getStringExtra(SessionService.EXTRA_GAME_ID),
sessionActivityDisplayId,
frontendSteamGame = intent.getBooleanExtra(SessionService.EXTRA_FRONTEND_STEAM_GAME, false),
)
intent.getStringExtra(EXTRA_PLAYED_GAME)?.let { com.droiddeck.launcher.frontend.Library.recordPlayed(this, it) }
}
@@ -3032,6 +3166,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
private fun windowOutputSize(width: Int, height: Int): Pair<Int, Int>? {
if (com.droiddeck.launcher.session.xr.XrPanels.immersiveActive) {
val flat = immersiveFlatSize ?: SessionState.outputSize
return if (steamScreenShown()) vrOutputSize(flat) else flat
}
if (width <= 0 || height <= 0 || isInPictureInPictureMode) return null
if (bottomGame != null) return when {
SessionState.followScreen ->
@@ -3045,9 +3183,38 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
else if (glassesScreen == null) outputSize() else null
}
/** These editors draw in this window, which the immersive view hides, so they open after leaving it. */
private fun leaveImmersiveForDialog() {
if (com.droiddeck.launcher.session.xr.XrPanels.immersiveActive) com.droiddeck.launcher.session.xr.XrPanels.leaveImmersive()
}
/** Steam's own screen is up with no game holding a window; with no focus report, a game may be running. */
private fun steamScreenShown(): Boolean {
if (SessionState.mode != SessionService.MODE_STEAM) return false
val focus = com.droiddeck.launcher.agent.AgentGuest.focus(this) ?: return false
return com.droiddeck.launcher.session.xr.XrSteamScreen.shown(
focus.takeUnless { it.isNull("focusedApp") }?.optLong("focusedApp"),
focus.optJSONArray("focusableApps")?.let { list -> (0 until list.length()).map { list.optLong(it) } },
)
}
/**
* SteamVR shows Steam's own screen as its floating Steam window, so in the headset that screen is drawn
* tall enough for the window to stay sharp. A flat game keeps the flat size, so the output keeps it
* while one is running.
*/
private fun vrOutputSize(flat: Pair<Int, Int>): Pair<Int, Int> {
if (flat.second >= VR_OUTPUT_HEIGHT) return flat
val width = (flat.first.toLong() * VR_OUTPUT_HEIGHT / flat.second.coerceAtLeast(1)).toInt() and 1.inv()
return width to VR_OUTPUT_HEIGHT
}
private fun resizeOutputForWindow(width: Int, height: Int) {
applyOutputSize(windowOutputSize(width, height) ?: return)
}
private fun applyOutputSize(size: Pair<Int, Int>) {
if (!CompositorHost.isStarted) return
val size = windowOutputSize(width, height) ?: return
if (size == SessionState.outputSize) return
Log.i(TAG, "output resized: ${SessionState.outputSize.first}x${SessionState.outputSize.second} -> ${size.first}x${size.second}")
SessionState.outputSize = size
@@ -3056,7 +3223,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
WaylandCompositor.nativeResizeOutput(size.first, size.second)
}
private fun followPortrait(): Boolean = glassesScreen == null && SessionPrefs.portrait(this)
private fun followPortrait(): Boolean = glassesScreen == null && SessionPrefs.portrait(this, SessionState.mode)
private fun applyFollowChoice() {
val scale = SessionState.followScales.let { if (followPortrait()) it.second else it.first }
@@ -3065,12 +3232,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
private fun applyFollowOrientation(config: android.content.res.Configuration) {
val wanted = SessionPrefs.windowOrientation(this, SessionState.followScreen, config.smallestScreenWidthDp)
val wanted = SessionPrefs.windowOrientation(this, SessionState.followScreen, config.smallestScreenWidthDp, SessionState.mode)
if (requestedOrientation != wanted) requestedOrientation = wanted
}
override fun onConfigurationChanged(newConfig: android.content.res.Configuration) {
super.onConfigurationChanged(newConfig)
picturePosition = SessionPrefs.picturePosition(this, picturePortrait(newConfig))
if (refreshActivityDisplayId() && started) {
SessionService.setActivityDisplay(this, sessionActivityDisplayId)
}
@@ -3128,13 +3296,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun displayMode(): String = SessionPrefs.displayMode(this,
intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM, intent.getStringExtra(SessionService.EXTRA_PROGRAM))
private fun portraitOutput(): Boolean = SessionPrefs.portrait(this) && !controlsBelowWanted()
private fun portraitOutput(): Boolean = SessionPrefs.portrait(this, SessionState.mode) && !controlsBelowWanted()
private fun outputSize(): Pair<Int, Int> =
com.droiddeck.launcher.session.SessionDisplay.resolveChoice(com.droiddeck.launcher.session.SessionDisplay.panelSize(this),
resolutionChoice(), portraitOutput())
private fun resolutionChoice(portrait: Boolean = SessionPrefs.portrait(this)): String {
private fun resolutionChoice(portrait: Boolean = SessionPrefs.portrait(this, SessionState.mode)): String {
val mode = displayMode()
val program = intent.getStringExtra(SessionService.EXTRA_PROGRAM)
return if (intent.getStringExtra(SessionService.EXTRA_MODE) == SessionService.MODE_RUN &&
@@ -3181,6 +3349,18 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun outputFpsLimit(): Int = outputFpsLimit(pipUi)
// Android holds the window to the Game Mode override while the panel runs faster; the guest paces to the panel,
// so without this cap every frame past the override is drawn and dropped.
private fun hostFrameCap(): Int {
if (glassesScreen != null || bottomOutputActive) return 0
val display = (if (Build.VERSION.SDK_INT >= 30) display else @Suppress("DEPRECATION") windowManager.defaultDisplay) ?: return 0
return SessionPrefs.hostFrameCap(display.refreshRate, display.mode.refreshRate)
}
private fun compositorFpsLimit(): Int = SessionPrefs.compositorFpsLimit(
mirrorRefreshLimit(), if (noSteamSession()) SessionState.fpsLimit else 0, pipUi, hostFrameCap(),
)
private fun outputFpsLimit(pip: Boolean): Int =
SessionPrefs.compositorFpsLimit(mirrorRefreshLimit(), if (noSteamSession()) SessionState.fpsLimit else 0, pip)
@@ -3218,7 +3398,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
)
val hz = refreshHz()
val changed = kotlin.math.abs(SessionState.refreshHz - hz) > 0.1f
CompositorHost.updatePacing(hz, outputFpsLimit())
CompositorHost.updatePacing(hz, compositorFpsLimit())
pushCardboard(activeCardboard)
if (changed && ::surfaceView.isInitialized) applyFrameGen()
}
@@ -3431,19 +3611,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}, "lossless-sync").start()
}
private fun importLossless(dll: File) {
Thread({
val result = Lossless.import(this, dll)
val message = Lossless.message(this, result)
val state = Lossless.state(this)
runOnUiThread {
lossless = state
Toast.makeText(this, message, Toast.LENGTH_LONG).show()
applyFrameGen(force = result == Lossless.ImportResult.UPDATED)
}
}, "lossless-import").start()
}
private fun watchSession() {
val handler = Handler(Looper.getMainLooper())
@@ -3655,16 +3822,20 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
internal fun dispatchImeKeyEvent(event: KeyEvent): Boolean = dispatchKeyEvent(event, orderedImeKey = true)
override fun dispatchKeyEvent(event: KeyEvent): Boolean = dispatchKeyEvent(event, orderedImeKey = false)
private fun dispatchKeyEvent(event: KeyEvent, orderedImeKey: Boolean): Boolean {
val normalized = com.droiddeck.launcher.input.GuestKeys.normalizeKeyboardEscape(event)
if (normalized === event) return dispatchSessionKeyEvent(event)
if (normalized === event) return dispatchSessionKeyEvent(event, orderedImeKey)
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
Log.i(TAG, "hardware Esc normalized from Back device=${event.deviceId} scan=${event.scanCode}")
}
return dispatchSessionKeyEvent(normalized)
return dispatchSessionKeyEvent(normalized, orderedImeKey)
}
private fun dispatchSessionKeyEvent(event: KeyEvent): Boolean {
private fun dispatchSessionKeyEvent(event: KeyEvent, orderedImeKey: Boolean): Boolean {
if (com.droiddeck.launcher.ui.AgentPet.handleBack(this, event)) return true
when (event.keyCode) {
KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE -> {
@@ -3747,7 +3918,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
return true
}
val pad = com.droiddeck.launcher.input.JoyCon.normalize(event)
if (pad !== event) return dispatchKeyEvent(pad)
if (pad !== event) return dispatchKeyEvent(pad, orderedImeKey)
val fromController = PadBridge.isControllerKeyEvent(event)
if (fromController && (menuOwnsController || pcKeyboardOpen || achievementsOpen || inputSettingsOpen || gestureSettingsOpen || SessionState.suspended)) {
padBridge?.setInputEnabled(false)
@@ -3789,7 +3960,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (fromController && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) {
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
// The bumpers walk the tabs on the strip; a page kept inside More counts as the More tab.
val pages = sessionDrawerPages(glasses.present)
val pages = sessionDrawerPages(achievementsInFront != null)
drawerPage = pages.strip().step(pages.tabFor(drawerPage), if (event.keyCode == KeyEvent.KEYCODE_BUTTON_R1) 1 else -1)
releaseDrawerDirection()
}
@@ -3830,7 +4001,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
val down = event.action == KeyEvent.ACTION_DOWN
if (down && event.repeatCount > 0) return true
val owner = if (event.deviceId <= 0) 16 else 8
if (com.droiddeck.launcher.input.GuestKeys.send(event) { code, pressed -> sendGuestKey(code, pressed, owner) }) return true
if (com.droiddeck.launcher.input.GuestKeys.send(event) { code, pressed -> sendGuestKey(code, pressed, owner, orderedImeKey) }) return true
}
return super.dispatchKeyEvent(event)
}
@@ -3917,7 +4088,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
steamTouchControls?.let { takes(it, it::takesTouchAt) } == true ||
unfoldedPanel?.let { takes(it, it::takesTouchAt) } == true ||
unfoldedDeckSurface?.let { takes(it, it::takesTouchAt) } == true ||
unfoldedColumn?.getChildAt(0)?.let { takes(it) { _, _ -> true } } == true
unfoldedKeys?.let { takes(it) { _, _ -> true } } == true
}
override fun dispatchTouchEvent(event: MotionEvent): Boolean {
@@ -4945,6 +5116,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
private fun refreshControls() {
padConnected = controllerConnected()
applyUnfoldedControls()
updateOnScreenControls()
}
@@ -4960,12 +5132,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
val width = rootContentWidth()
val height = rootContentHeight()
val wanted = controlsBelowWanted()
val tabRow = unfoldedColumn?.getChildAt(0)?.height?.let {
it - (com.droiddeck.launcher.ui.BAR_HEIGHT.value * resources.displayMetrics.density + 0.5f).toInt()
} ?: 0
val outputAspect = if (!wanted || SessionState.followScreen) 0f
else outputSize().let { it.first.toFloat() / it.second.coerceAtLeast(1) }
val gameHeight = if (wanted) com.droiddeck.launcher.session.SessionDisplay.unfoldedGameHeight(width, height, tabRow, outputAspect)
val gameHeight = if (wanted) com.droiddeck.launcher.session.SessionDisplay.unfoldedGameHeight(width, height, aspect = outputAspect)
else FrameLayout.LayoutParams.MATCH_PARENT
val params = surfaceView.layoutParams as FrameLayout.LayoutParams
if (params.height != gameHeight) {
@@ -4982,6 +5151,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (panel != null && (!wanted || panel.dock != dock)) {
sessionRoot.removeView(unfoldedColumn)
unfoldedColumn = null
unfoldedKeys = null
unfoldedDeckSurface = null
unfoldedDeckPanel = null
unfoldedPanel = null
@@ -4992,14 +5162,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (panel == null) {
panel = OnScreenControls(this, padBridge, dock).also { it.updateLayout(primaryInputLayout) }
val column = android.widget.LinearLayout(this).apply {
alpha = onScreenOpacityAlpha()
orientation = android.widget.LinearLayout.VERTICAL
addView(unfoldedBar().apply {
addOnLayoutChangeListener { _, _, top, _, bottom, _, oldTop, _, oldBottom ->
if (bottom - top != oldBottom - oldTop) post { applyUnfoldedControls() }
}
}, android.widget.LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.MATCH_PARENT,
android.widget.LinearLayout.LayoutParams.WRAP_CONTENT))
addView(panel, android.widget.LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f))
unfoldedKeys = com.droiddeck.launcher.ui.padKeysView(
this@SessionActivity, SessionState.mode == SessionService.MODE_STEAM,
{ releasePads(); drawerOpen = true }, ::tapSteamButton, ::tapQam,
).also {
addView(it, android.widget.LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.MATCH_PARENT,
android.widget.LinearLayout.LayoutParams.WRAP_CONTENT))
}
}
sessionRoot.addView(column, sessionRoot.indexOfChild(surfaceView) + 1)
unfoldedColumn = column
@@ -5010,13 +5182,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
unfoldedColumn?.layoutParams = FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, height - gameHeight, Gravity.BOTTOM)
}
private fun unfoldedBar(): View = com.droiddeck.launcher.ui.bottomScreenBarView(this) {
val deck = unfoldedDeckPanel
com.droiddeck.launcher.ui.sessionBarModel(getString(if (deck != null) R.string.second_mode_deck_controls else R.string.deck_tab_gamepad),
{ chooseUnfoldedControls(false) }, { drawerOpen = true }, ::tapSteamButton, ::tapQam,
tabs = deck?.let { com.droiddeck.launcher.ui.deckPanelTabs(this, it, ::selectDeckPanel) })
}
private fun showUnfoldedDeckPanel() {
val column = unfoldedColumn
val panel = unfoldedPanel
@@ -5032,7 +5197,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
panel.visibility = View.GONE
unfoldedDeckSurface = com.droiddeck.launcher.ui.InputSurfaceView(this, padBridge, layout.elements, InputRole.PRIMARY, layout.style, haptics = true).also {
it.tag = layout
column.addView(it, android.widget.LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f))
column.addView(it, column.indexOfChild(panel) + 1, android.widget.LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f))
}
}
@@ -5123,27 +5288,19 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
} else {
endGameField()
}
host.type(text)
host.tap(KeyEvent.KEYCODE_ENTER)
if (text.isEmpty()) host.tap(KeyEvent.KEYCODE_ENTER)
else WaylandCompositor.textInputCommitAndSubmit(text)
uiHandler.postDelayed({
if (AgentGuest.gameTextField && com.droiddeck.launcher.ui.WowChat.isWow(AgentGuest.gameProgram)) endGameField()
}, FIELD_SETTLE_MS)
}
private fun endGameField() {
WaylandCompositor.nativeSendKey(KEY_END, 1)
WaylandCompositor.nativeSendKey(KEY_END, 0)
orderedImeKeySender(KEY_END, true)
orderedImeKeySender(KEY_END, false)
}
private fun selectGameField(vararg then: Int) {
heldKeys.set(256, KEY_LEFTCTRL, true)
try {
for (key in intArrayOf(KEY_A) + then) {
heldKeys.set(256, key, true)
heldKeys.set(256, key, false)
}
} finally { heldKeys.release(256) }
}
private fun selectGameField(copy: Boolean = false) { WaylandCompositor.nativeSelectGameField(copy) }
private fun readGameField(done: (String?) -> Unit) {
val opened = wowChat.request
@@ -5152,7 +5309,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (text != null && stillOpen()) endGameField()
done(text)
}
selectGameField(KEY_C)
selectGameField(copy = true)
}
private fun cancelWowChat() {
@@ -5851,7 +6008,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
val view = com.droiddeck.launcher.input.SteamTouchControls(this, device,
onMenu = { drawerOpen = true }, onKeyboard = ::togglePcKeyboard)
view.visibility = View.GONE
view.onEditingChanged = { touchEditorChanged() }
view.alpha = onScreenOpacityAlpha()
view.onEditingChanged = { editing ->
view.alpha = if (editing) 1f else onScreenOpacityAlpha()
touchEditorChanged()
}
view.onOptions = { options ->
steamTouchOptions = options
applyTouchRouting()
@@ -5956,6 +6117,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (bottom?.parent !== bottomRoot) {
(bottom?.parent as? android.view.ViewGroup)?.removeView(bottom)
bottom = OnScreenControls(bottomRoot.context, padBridge).also { view ->
view.alpha = onScreenOpacityAlpha()
view.onTouchMiss = { event -> onBottomGameTouch(event) }
bottomRoot.addView(view, android.view.ViewGroup.LayoutParams(-1, -1))
}
@@ -6055,11 +6217,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
releaseHeldKeys()
}
private fun sendGuestKey(key: Int, down: Boolean, owner: Int = 1) {
private fun sendGuestKey(key: Int, down: Boolean, owner: Int = 1, orderedImeKey: Boolean = false) {
if (down && pipUi) return
val code = if (key == KEY_RIGHTCTRL && SessionState.mode == SessionService.MODE_DESKTOP) KEY_LEFTCTRL else key
if (owner == 1) { if (down) guestKeysDown.add(code) else guestKeysDown.remove(code) }
heldKeys.set(owner, code, down)
val orderedSender = if (orderedImeKey) orderedImeKeySender else null
heldKeys.set(owner, code, down, orderedSender)
}
private val orderedImeKeySender: (Int, Boolean) -> Unit = { code, down ->
WaylandCompositor.nativeSendKeyOrdered(code, if (down) 1 else 0)
}
private fun capturePausedFrame(manual: Boolean = false, onDone: () -> Unit = {}) {
@@ -6127,7 +6294,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
val back = {
if (restore.compareAndSet(false, true)) {
pauseCaptures--
if (!isDestroyed) WaylandCompositor.nativeSetZeroCopy(composedOutputFree())
if (!isDestroyed && zeroCopyActive()) WaylandCompositor.nativeSetZeroCopy(composedOutputFree())
}
}
uiHandler.postDelayed({ capturePausedFrame(manual = true, onDone = back) }, ZERO_COPY_SETTLE_MS)
@@ -6242,6 +6409,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
heldButtons.clear()
hidePrimaryKeyboard()
sessionClipboard.stop()
sessionTextInput.stop()
padMotion?.stop()
cursorVisible = false
closeSecondScreen(reset = false)
@@ -6257,7 +6425,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
} else if (!isFinishing && !isDestroyed) {
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
updateOnScreenControls()
if (resumed) { sessionClipboard.start(); updatePadMotion() }
if (resumed) { sessionClipboard.start(); sessionTextInput.start(); updatePadMotion() }
if (started) {
settleDualScreenControls()
refreshSecondScreenDisplays()
@@ -6328,6 +6496,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
com.droiddeck.launcher.input.DualScreen.unwatchTaken(bottomScreenListener)
contentResolver.unregisterContentObserver(refreshSettingObserver)
if (!screenIsOff()) closeSecondScreen(reset = false)
sessionTextInput.stop()
startedScreens = (startedScreens - 1).coerceAtLeast(0)
updateGlassesScreen()
updateBottomGame()
@@ -6385,12 +6554,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
(getSystemService(INPUT_SERVICE) as? InputManager)
?.registerInputDeviceListener(deviceListener, Handler(Looper.getMainLooper()))
padConnected = controllerConnected()
padBridge?.setStickDeadZone(ControllerPrefs.deadZone(this))
refreshSecondScreenDisplays()
if (SessionState.guestPid > 1) padBridge?.syncConnectedControllers()
joyConVr?.refresh()
onScreenControls?.reload()
controllerSettings = ControllerPrefs.read(this)
applyOnScreenOpacity()
resumed = true
boostGpuClock(panelOverGame)
updateKeyboardRoute()
@@ -6406,7 +6577,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
onCancel = { padBridge?.cancelHomeGuide() },
)
updatePointerCapture()
if (!pipUi) sessionClipboard.start()
if (!pipUi) { sessionClipboard.start(); sessionTextInput.start() }
updatePadMotion()
ControllerPrefs.prefs(this).registerOnSharedPreferenceChangeListener(shortcutPrefListener)
SessionPrefs.sessionPrefs(this).registerOnSharedPreferenceChangeListener(screenEffectsProfilePrefListener)
@@ -6899,7 +7070,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
androidx.compose.runtime.key(profileLayout) {
androidx.compose.ui.viewinterop.AndroidView(
factory = { context -> com.droiddeck.launcher.ui.InputSurfaceView(context, padBridge, profileLayout?.elements.orEmpty(),
surfaceStyle = profileLayout?.style ?: com.droiddeck.launcher.input.InputSurfaceStyle()).also { swappedInputSurface = it } },
surfaceStyle = profileLayout?.style ?: com.droiddeck.launcher.input.InputSurfaceStyle()).also {
it.alpha = onScreenOpacityAlpha()
swappedInputSurface = it
} },
modifier = Modifier.fillMaxWidth().weight(1f),
onRelease = { if (swappedInputSurface === it) swappedInputSurface = null },
)
@@ -7123,6 +7297,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
override fun onDestroy() {
com.droiddeck.launcher.session.xr.XrPanels.clearMenuHost(this)
if (drawerXr) com.droiddeck.launcher.session.xr.XrPanels.hideMenu()
uiHandler.removeCallbacks(panelHeldCheck)
uiHandler.removeCallbacks(panelHeldRetry)
synchronized(frameGenGlobalLock) {
@@ -7135,6 +7311,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
gamescopeConvarRequests.shutdownNow()
backQamInput.cancel()
steamVrRecovery.close()
sessionTextInput.stop()
uiHandler.removeCallbacks(steamTouchRetry)
uiHandler.removeCallbacks(cursorResync)
uiHandler.removeCallbacks(usbMouseFallback)
@@ -7247,6 +7424,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
const val EXTRA_RETURN_HOME = "returnHome"
private const val BLUETOOTH_CONNECT = "android.permission.BLUETOOTH_CONNECT"
private const val REQUEST_BLUETOOTH = 31
private const val VR_OUTPUT_HEIGHT = 1080
const val EXTRA_LINK_TASK = "linkTask"
const val EXTRA_STEAMVR = "steamVr"
const val EXTRA_PLAYED_GAME = "com.droiddeck.launcher.PLAYED_GAME"
@@ -0,0 +1,48 @@
package com.droiddeck.launcher.agent
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.droiddeck.launcher.core.AppUiPrefs
import com.droiddeck.launcher.ui.AgentPage
import com.droiddeck.launcher.ui.DroidDeckTheme
/**
* The agent's chat in a window of its own, for Quest's flat mode: opened in its own task, it is a
* separate Horizon panel the user can move, resize and close like any other.
*/
class AgentChatActivity : ComponentActivity() {
override fun attachBaseContext(newBase: Context) {
super.attachBaseContext(newBase)
com.droiddeck.launcher.core.AppLanguage.applyTo(this, newBase)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
DroidDeckTheme(appScale = AppUiPrefs.scale(this)) {
AgentPage(
Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background).padding(horizontal = 12.dp, vertical = 6.dp),
visible = true, startTyping = AgentHost.entries.isEmpty(),
)
}
}
}
companion object {
fun open(context: Context) {
context.startActivity(
Intent(context, AgentChatActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT),
)
}
}
}
@@ -19,7 +19,7 @@ import java.util.UUID
object AgentGuest {
private val main by lazy { Handler(Looper.getMainLooper()) }
var focusRevision by mutableIntStateOf(0)
private set
@androidx.annotation.VisibleForTesting internal set
var steamKeyboard by mutableStateOf(false)
private set
var desktopTextField by mutableStateOf(false)
@@ -75,7 +75,9 @@ object AgentHost {
"Never kill by a command-line pattern (pkill -f, pgrep -f piped to kill): your own command line holds the user's message, so the pattern matches you. " +
"Files the user attaches are listed at the end of their message, under /root/.cache/droiddeck/attachments. " +
"To have the user pick between options, end your reply with a fenced code block whose language is choices, one short option per line, " +
"and end your turn: DroidDeck shows them as buttons and sends the one picked as the next message."
"and end your turn: DroidDeck shows them as buttons and sends the one picked as the next message. " +
"To show the user an image (a screenshot, a mockup, a chart), put ![what it shows](/absolute/path.png) on a line of its own: " +
"DroidDeck draws the file in the chat."
val entries = mutableStateListOf<Entry>()
val queue = mutableStateListOf<Queued>()
@@ -8,8 +8,11 @@ import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.R
import com.droiddeck.launcher.core.WirelessAdbFix
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.OrphanReaper
import com.droiddeck.launcher.session.QuestExperimental
import java.io.File
import java.util.concurrent.TimeUnit
@@ -88,6 +91,8 @@ object AgentSetup {
private fun completedKey(harness: AgentHarness) = "setup_completed_${harness.id}"
private val main = Handler(Looper.getMainLooper())
/** Advanced by every Allow, so a connection check started before it cannot overwrite what it found. */
private var connectionGeneration = 0
private const val REPO = "https://github.com/Droid-Deck/DroidDeck.git"
private const val CHECKOUT = "/root/DroidDeck"
private val HELPERS = listOf("android-open", "dd-gh-login", "droiddeckctl", "droiddeck-scenario")
@@ -104,6 +109,7 @@ object AgentSetup {
val harness = AgentHost.harness
keys = harness.keys(LinuxRuntime.rootDir(app))
val probes = mutableListOf<Pair<Step, List<String>>>()
val generation = connectionGeneration
for (step in Step.entries) if (status[step] != Status.WORKING) {
when (step) {
Step.INSTALL -> set(step, if (harness.files.all { AgentHost.guestFileExists(app, it) }) Status.DONE else Status.TODO)
@@ -114,7 +120,9 @@ object AgentSetup {
detail.remove(step)
Thread({
val live = com.droiddeck.launcher.core.WirelessAdbFix.liveConnectAddress(app) != null
set(step, if (live) Status.DONE else Status.TODO)
main.post {
if (generation == connectionGeneration && status[step] != Status.WORKING) status[step] = if (live) Status.DONE else Status.TODO
}
}, "agent-connection").start()
} else probes += step to listOf("sh", "-c",
"for i in 1 2 3; do adb connect \"\$ADB_SERIAL\" >/dev/null 2>&1; " +
@@ -123,7 +131,7 @@ object AgentSetup {
Step.GITHUB -> probes += step to listOf("gh", "auth", "status")
}
}
Thread({ for ((step, command) in probes) probe(app, harness, step, command) }, "agent-checks").start()
Thread({ for ((step, command) in probes) probe(app, harness, step, command, generation) }, "agent-checks").start()
}
/** The last failed refresh ends the script: the installs after it would run from stale indexes and could report success. */
@@ -141,6 +149,22 @@ object AgentSetup {
/** Runs [step]'s action. [CONNECTION] is the app's own pairing flow, so the caller opens it. */
fun run(context: Context, step: Step) = run(context, step, null)
/** The [Step.CONNECTION] action on a Quest, which has no pairing screen; see [WirelessAdbFix.trustOnDevice]. */
fun trustOnDevice(context: Context) {
val app = context.applicationContext
connectionGeneration++
status[Step.CONNECTION] = Status.WORKING
detail[Step.CONNECTION] = app.getString(R.string.agent_connection_quest_waiting)
Thread({
val ok = runCatching { WirelessAdbFix.trustOnDevice(app) }.isSuccess
main.post {
status[Step.CONNECTION] = if (ok) Status.DONE else Status.FAILED
if (ok) detail.remove(Step.CONNECTION) else detail[Step.CONNECTION] = app.getString(R.string.agent_connection_quest_failed)
if (ok) check(app)
}
}, "agent-quest-trust").start()
}
/** Opens the page where a provider's key is made, as the sign-in of a harness that takes pasted keys. */
fun openKeyPage(context: Context, page: String) = run(context, Step.SIGN_IN, listOf("/root/.local/bin/android-open", page))
@@ -202,7 +226,18 @@ object AgentSetup {
/** The whole output of a step's last run; the card shows only its last line. */
fun logFile(app: Context, step: Step) = File(app.filesDir, "agent/setup-${step.name.lowercase()}.log")
fun buildToolsInstalled(app: Context) = AgentHost.guestFileExists(app, "/root/aapt2/aapt2") && AgentHost.guestFileExists(app, "$CHECKOUT/.git")
/**
* An install set up before setup wrote the Gradle init script gets the step again, but only
* once the checkout's setup writes it: the step runs that script, and an older one never would.
*/
fun buildToolsInstalled(app: Context) = AgentHost.guestFileExists(app, "/root/aapt2/aapt2") && AgentHost.guestFileExists(app, "$CHECKOUT/.git") &&
(AgentHost.guestFileExists(app, GRADLE_INIT) || !setupWritesGradleInit(app))
private const val GRADLE_INIT = "/root/.gradle/init.d/droiddeck-device.gradle"
private fun setupWritesGradleInit(app: Context) = runCatching {
File(LinuxRuntime.rootDir(app), "$CHECKOUT/tools/agent/setup".removePrefix("/")).readText().contains(GRADLE_INIT.substringAfterLast('/'))
}.getOrDefault(false)
/** dd-lab-build compiled this install's commit, so a Lab build compiles only what changed. */
private fun prepared(app: Context) = runCatching {
@@ -216,7 +251,7 @@ object AgentSetup {
detail.clear()
}
private fun probe(app: Context, harness: AgentHarness, step: Step, command: List<String>) {
private fun probe(app: Context, harness: AgentHarness, step: Step, command: List<String>, generation: Int) {
var output = ""
val ok = runCatching {
val child = AgentHost.guest(app, command, connectAdb = step == Step.CONNECTION).start()
@@ -232,11 +267,14 @@ object AgentSetup {
}.onFailure { output = it.message.orEmpty() }.getOrDefault(false)
main.post {
if (AgentHost.harness != harness) return@post
// A running or newer Allow owns the row, including the instructions it shows while it waits.
if (step == Step.CONNECTION && (generation != connectionGeneration || status[step] == Status.WORKING)) return@post
if (status[step] != Status.WORKING) status[step] = if (ok) Status.DONE else Status.TODO
val last = output.lines().lastOrNull { it.isNotBlank() && !noise(it.trim()) }?.trim()?.take(160)
when {
ok -> detail.remove(step)
step == Step.CONNECTION -> detail[step] = app.getString(com.droiddeck.launcher.R.string.agent_connection_off)
step == Step.CONNECTION -> detail[step] = app.getString(
if (QuestExperimental.isSupported()) R.string.agent_connection_quest_off else R.string.agent_connection_off)
step.required && last != null -> detail[step] = last
}
if (ready) AgentHost.prefs(app).edit().putBoolean(completedKey(harness), true).apply()
@@ -89,7 +89,7 @@ public class DirectAudioRelayComponent extends SessionPart {
}
}
final java.io.PrintWriter log = out;
pid = HostProcess.start(command.toString(), env.toArray(new String[0]),
pid = HostProcess.startUncounted(command.toString(), env.toArray(new String[0]),
app().getFilesDir(), null,
line -> {
Log.i(TAG, line);
@@ -12,6 +12,7 @@ import com.droiddeck.launcher.core.TarZst;
import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.AtomicMoveNotSupportedException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
@@ -36,9 +37,15 @@ public class PulseAudioComponent extends SessionPart {
private final HostLifecycle host = new HostLifecycle(Process::killProcess);
static final class HostLifecycle {
static final int MAX_STARTUP_CRASH_RESTARTS = 4;
private static final long[] STARTUP_RESTART_DELAYS_MS = {250L, 1000L, 2000L, 4000L};
volatile int pid = -1;
private long generation;
private long launches;
private boolean preferStandardPerformanceMode;
private boolean sinkReady;
private int startupCrashRestarts;
private final IntConsumer terminate;
final ReentrantReadWriteLock commands = new ReentrantReadWriteLock();
@@ -48,6 +55,9 @@ public class PulseAudioComponent extends SessionPart {
synchronized long begin() {
stop();
preferStandardPerformanceMode = false;
sinkReady = false;
startupCrashRestarts = 0;
return generation;
}
@@ -55,6 +65,7 @@ public class PulseAudioComponent extends SessionPart {
generation++;
if (pid > 1) terminate.accept(pid);
pid = -1;
sinkReady = false;
}
boolean launch(long expected, IntSupplier launch) {
@@ -63,6 +74,7 @@ public class PulseAudioComponent extends SessionPart {
synchronized (this) {
if (expected != generation) return false;
launches++;
sinkReady = false;
pid = launch.getAsInt();
return true;
}
@@ -93,11 +105,45 @@ public class PulseAudioComponent extends SessionPart {
return token == launches && pid > 1;
}
synchronized boolean preferStandardPerformanceMode() {
return preferStandardPerformanceMode;
}
synchronized void markLowLatencyFailed(long token) {
if (token == launches && pid > 1) preferStandardPerformanceMode = true;
}
synchronized void markSinkReady(long token) {
if (token == launches && pid > 1) {
sinkReady = true;
startupCrashRestarts = 0;
}
}
synchronized boolean exited(long expected) {
if (expected != generation || pid <= 1) return false;
pid = -1;
return true;
}
/**
* Decides whether a dead host should be restarted and after how many milliseconds.
* Returns 0 for immediate recovery of a host that had a working sink, a positive backoff
* while falling back to standard AAudio mode after a startup crash, or -1 to stop retrying.
*/
synchronized long nextRestartDelayMs(long expected) {
if (expected != generation) return -1L;
if (sinkReady) {
sinkReady = false;
startupCrashRestarts = 0;
return 0L;
}
preferStandardPerformanceMode = true;
if (startupCrashRestarts >= MAX_STARTUP_CRASH_RESTARTS) return -1L;
long delay = STARTUP_RESTART_DELAYS_MS[Math.min(startupCrashRestarts, STARTUP_RESTART_DELAYS_MS.length - 1)];
startupCrashRestarts++;
return delay;
}
}
public PulseAudioComponent(Context context) {
@@ -167,11 +213,14 @@ public class PulseAudioComponent extends SessionPart {
if (micFifoPath != null && !micFifoPath.isEmpty()) {
new File(micFifoPath).delete();
}
boolean standardMode = host.preferStandardPerformanceMode();
String initialPerformanceMode = standardMode ? "0" : "1";
ArrayList<String> config = new ArrayList<>();
config.add("load-module module-native-protocol-unix auth-anonymous=1 auth-cookie-enabled=0 socket=\""
+ socket().getAbsolutePath() + "\"");
config.add(".nofail");
config.add("load-module module-directaudio-native-sink sink_name=DirectAudio performance_mode=1 adaptive=1 decay=0 limiter=1 watchdog=1 volume=1.0 control_dir=" + deviceControls);
config.add("load-module module-directaudio-native-sink sink_name=DirectAudio performance_mode="
+ initialPerformanceMode + " adaptive=1 decay=0 limiter=1 watchdog=1 volume=1.0 control_dir=" + deviceControls);
config.add("set-default-sink DirectAudio");
config.add(".fail");
if (micFifoPath != null && !micFifoPath.isEmpty()) {
@@ -186,15 +235,36 @@ public class PulseAudioComponent extends SessionPart {
env.add("LD_LIBRARY_PATH=/system/lib64:" + modules + ":" + workingDir.getAbsolutePath());
env.add("HOME=" + workingDir);
env.add("TMPDIR=" + workingDir);
// The daemon closes every fd at start but this one; in a worker process it is the binder
// fd whose closing Android takes for the process's death.
env.add("PULSE_PASSED_FD=" + com.droiddeck.launcher.runtime.GuestWorker.BINDER_FD_TOKEN);
String command = String.join(" ", HostProcess.dataExecutable(workingDir.getAbsolutePath() + "/libpulseaudio.so"))
+ " --system=false --disable-shm=true --fail=false"
+ " -n --file=default.pa --daemonize=false --use-pid-file=false --exit-idle-time=-1"
+ " --log-level=info";
final java.io.PrintWriter out = openLog();
if (!host.launch(generation, () -> HostProcess.start(command, env.toArray(new String[0]), workingDir, status -> {
if (!host.launch(generation, () -> HostProcess.startUncounted(command, env.toArray(new String[0]), workingDir, status -> {
if (host.exited(generation)) {
Log.w(TAG, "audio host exited with status " + status + "; restarting");
long delayMs = host.nextRestartDelayMs(generation);
if (delayMs < 0) {
String msg = "audio host exited with status " + status
+ " before a client sink came up too many times; not restarting again in this session";
Log.w(TAG, msg);
note(out, msg);
return;
}
Log.w(TAG, "audio host exited with status " + status + "; restarting"
+ (host.preferStandardPerformanceMode() ? " with standard AAudio mode" : "")
+ (delayMs > 0 ? " in " + delayMs + " ms" : ""));
if (delayMs > 0) {
try {
Thread.sleep(delayMs);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
start(generation);
}
},
@@ -208,6 +278,24 @@ public class PulseAudioComponent extends SessionPart {
guard.start();
}
private boolean loadDirectAudioSink(long token, String performanceMode) {
if ("0".equals(performanceMode)) pactlOk(token, "unload-module", "module-directaudio-native-sink");
String loaded = pactlFor(token, "load-module", "module-directaudio-native-sink", "sink_name=DirectAudio",
"performance_mode=" + performanceMode,
"adaptive=1", "decay=0", "limiter=1", "watchdog=1", "volume=1.0", "control_dir=" + deviceControls);
if (loaded == null) return false;
if (pactlOk(token, "set-default-sink", "DirectAudio")) return true;
String moduleId = loaded.trim();
pactlOk(token, "unload-module", moduleId.matches("\\d+") ? moduleId : "module-directaudio-native-sink");
return false;
}
private boolean loadPlainAAudioSink(long token, String performanceMode) {
return pactlOk(token, "load-module", "module-aaudio-sink", "sink_name=AAudioSink",
"performance_mode=" + performanceMode, "adaptive=1", "volume=1.0", "control_dir=" + deviceControls)
&& pactlOk(token, "set-default-sink", "AAudioSink");
}
private void ensureClientSink(java.io.PrintWriter out, long token) {
try {
// Nothing that may block (a sink whose AAudio open hangs: a Galaxy S24 FE (US) hung the
@@ -229,27 +317,42 @@ public class PulseAudioComponent extends SessionPart {
if (sinks == null) {
line = "== client sink: the daemon did not answer in 30 s; no fallback attempted";
} else if (sinks.contains("\tDirectAudio\t") || sinks.startsWith("DirectAudio\t") || sinks.contains("\tDirectAudio\n") || sinks.matches("(?s).*\\bDirectAudio\\b.*")) {
line = "== client sink: DirectAudio (module-directaudio-native-sink)";
host.markSinkReady(token);
line = "== client sink: DirectAudio (module-directaudio-native-sink"
+ (host.preferStandardPerformanceMode() ? ", standard mode" : "") + ")";
} else {
// AAudio can refuse the first open with AAUDIO_ERROR_DISCONNECTED while Android is
// still switching the output route as the session starts (seen on a Galaxy S24 FE):
// try DirectAudio again, then the plain sink, a few times over ten seconds.
// still switching the output route (Galaxy S24 FE) or when low-latency MMAP output
// is rejected by the HAL (Samsung One UI). Retry low-latency once if it hasn't been
// disqualified yet, then fall back to performance_mode=0 (non-MMAP) on DirectAudio
// before trying the plain AAudio sink.
String loadedAs = null;
for (int attempt = 1; attempt <= 5 && loadedAs == null && host.live(token); attempt++) {
try { Thread.sleep(2000L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; }
if (pactlOk(token, "load-module", "module-directaudio-native-sink", "sink_name=DirectAudio", "performance_mode=1",
"adaptive=1", "decay=0", "limiter=1", "watchdog=1", "volume=1.0", "control_dir=" + deviceControls)
&& pactlOk(token, "set-default-sink", "DirectAudio")) {
loadedAs = "DirectAudio on attempt " + attempt;
} else if (pactlOk(token, "load-module", "module-aaudio-sink", "sink_name=AAudioSink",
"performance_mode=" + (attempt == 1 ? "1" : "0"), "adaptive=1", "volume=1.0", "control_dir=" + deviceControls)
&& pactlOk(token, "set-default-sink", "AAudioSink")) {
loadedAs = "the plain AAudio sink (AAudioSink) on attempt " + attempt;
if (!host.live(token)) break;
if (attempt == 1 && !host.preferStandardPerformanceMode()) {
if (loadDirectAudioSink(token, "1")) {
loadedAs = "DirectAudio on attempt " + attempt;
break;
}
if (!host.live(token)) break;
host.markLowLatencyFailed(token);
}
if (loadDirectAudioSink(token, "0")) {
loadedAs = "DirectAudio (standard mode) on attempt " + attempt;
} else if (host.live(token) && loadPlainAAudioSink(token, "0")) {
loadedAs = "the plain AAudio sink (AAudioSink, standard mode) on attempt " + attempt;
}
}
line = loadedAs != null ? "== client sink: DirectAudio did not come up at start; retried and got " + loadedAs
: "== client sink: DirectAudio did not come up and the AAudio fallback failed too after 5 retries - no client sound."
+ " If audio.log shows AAUDIO_ERROR_DISCONNECTED, Android refused the audio output: rebooting the phone usually fixes this";
if (loadedAs != null) {
host.markSinkReady(token);
line = "== client sink: DirectAudio did not come up at start; retried and got " + loadedAs;
} else if (!host.live(token)) {
line = "== client sink: audio host exited during sink recovery";
} else {
line = "== client sink: DirectAudio did not come up and the AAudio fallback failed too after 5 retries - no client sound."
+ " If audio.log shows AAUDIO_ERROR_DISCONNECTED, Android refused the audio output: rebooting the phone usually fixes this";
}
Log.w(TAG, line);
}
Log.i(TAG, line);
@@ -404,11 +507,22 @@ public class PulseAudioComponent extends SessionPart {
continue;
}
File destination = new File(workingDir, lib);
File temp = null;
try (InputStream in = resource.openStream()) {
Files.copy(in, destination.toPath(), StandardCopyOption.REPLACE_EXISTING);
FileUtils.chmod(destination, 0771);
temp = File.createTempFile(lib + ".", ".tmp", workingDir);
Files.copy(in, temp.toPath(), StandardCopyOption.REPLACE_EXISTING);
FileUtils.chmod(temp, 0771);
try {
Files.move(temp.toPath(), destination.toPath(),
StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
} catch (AtomicMoveNotSupportedException e) {
Files.move(temp.toPath(), destination.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
temp = null;
} catch (Exception e) {
Log.w(TAG, "copy " + lib, e);
} finally {
if (temp != null) temp.delete();
}
}
}
@@ -61,7 +61,19 @@ object GameEnvironment {
}
fun effective(config: Config, preset: String, scope: String, forceSsbs: Boolean = false): Map<String, String?> =
defaults(preset, forceSsbs) + config.shared + if (scope.isEmpty()) emptyMap() else config.games[scope].orEmpty()
defaults(preset, forceSsbs) + config.shared + if (scope.isEmpty()) emptyMap() else knownGames[scope].orEmpty() + config.games[scope].orEmpty()
/**
* What some Steam games need here whatever the shared settings say; the game's own settings still win.
* GTA III dies at 0042A703 when a new game starts with FEX's reduced x87 precision, as the Rockstar store copy does.
*/
val knownGames: Map<String, Map<String, String?>> = mapOf(
"12100" to mapOf("FEX_X87REDUCEDPRECISION" to "0"),
)
/** [config] with [knownGames] folded under each game's own settings, for the guest to read. */
fun withKnownGames(config: Config): Config =
config.copy(games = config.games + knownGames.mapValues { (scope, known) -> known + config.games[scope].orEmpty() })
fun hasOverride(config: Config, scope: String, name: String): Boolean =
scope.isNotEmpty() && config.entries(scope).containsKey(name)
@@ -78,7 +90,7 @@ object GameEnvironment {
val entries = config.games[scope].orEmpty()
if (FexPreset.environmentKeys.none(entries::containsKey)) return null
return FexPreset.all.firstOrNull { preset ->
val expected = FexPreset.environment(preset.id)
val expected = presetFor(scope, preset.id)
FexPreset.environmentKeys.all { key -> entries.containsKey(key) && entries[key] == expected[key] }
}?.id ?: CUSTOM_FEX_PRESET
}
@@ -88,12 +100,16 @@ object GameEnvironment {
require(preset == null || FexPreset.all.any { it.id == preset })
val entries = config.entries(scope).filterKeys { it !in FexPreset.environmentKeys }.toMutableMap()
if (preset != null) {
val values = FexPreset.environment(preset)
val values = presetFor(scope, preset)
FexPreset.environmentKeys.forEach { key -> entries[key] = values[key] }
}
return config.withEntries(scope, entries)
}
/** A FEX preset as a game gets it: picking one never undoes a fix the game is known to need. */
private fun presetFor(scope: String, preset: String): Map<String, String?> =
FexPreset.environment(preset) + knownGames[scope].orEmpty().filterKeys { it in FexPreset.environmentKeys }
const val CUSTOM_FEX_PRESET = "__custom__"
val syncBackends = listOf(SessionPrefs.SYNC_NTSYNC, SessionPrefs.SYNC_FSYNC, SessionPrefs.SYNC_ESYNC, SessionPrefs.SYNC_WINESERVER)
@@ -1,6 +1,7 @@
package com.droiddeck.launcher.core
import android.content.Context
import android.content.pm.PackageManager
import android.net.Uri
import android.provider.Settings
@@ -19,4 +20,14 @@ object GlobalSettings {
fun developerOptionsOn(context: Context): Boolean = isOn(context, Settings.Global.DEVELOPMENT_SETTINGS_ENABLED)
fun wirelessDebuggingOn(context: Context): Boolean = isOn(context, "adb_wifi_enabled")
/**
* True when it was off and is now on. Quest only, where Settings has no switch for it; it needs
* WRITE_SECURE_SETTINGS granted over adb.
*/
fun turnOnWirelessDebugging(context: Context): Boolean {
if (!com.droiddeck.launcher.session.QuestExperimental.isSupported() || wirelessDebuggingOn(context)) return false
if (context.checkSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS) != PackageManager.PERMISSION_GRANTED) return false
return runCatching { Settings.Global.putInt(context.contentResolver, "adb_wifi_enabled", 1) }.getOrDefault(false)
}
}
@@ -1,5 +1,6 @@
package com.droiddeck.launcher.core
import android.os.ParcelFileDescriptor
import android.util.Log
import java.io.File
import java.util.function.Consumer
@@ -7,6 +8,9 @@ import java.util.function.Consumer
object HostProcess {
private const val TAG = "HostProcess"
private const val LINKER = "/system/bin/linker64"
// sh -c WORKER_CD sh DIR NAME=VALUE... -- PROGRAM ARGS...
private const val WORKER_CD = "cd \"\$1\" || exit 126; shift; " +
"while [ \$# -gt 0 ] && [ \"\$1\" != -- ]; do export \"\$1\"; shift; done; shift; exec \"\$@\""
/** Android 10+ refuses to execute app data files for targetSdk 29+; its linker still loads them. */
@JvmStatic
@@ -65,6 +69,77 @@ object HostProcess {
}
}
/**
* As [start], but the program runs as the main process of one of the app's worker processes,
* which Android does not count against the app's child processes (docs/phantom-processes.md).
* Falls back to [start] when no worker is available. The exit status is the program's exit
* code, or 128 plus the signal that ended it, as Process.waitFor() reports it.
*/
@JvmStatic
@JvmOverloads
fun startUncounted(command: String, env: Array<String>?, dir: File?, onExit: Consumer<Int>?, onLine: Consumer<String>?,
outputFile: File? = null, onOutputComplete: Runnable? = null): Int {
val context = com.droiddeck.launcher.runtime.GuestWorkers.context
val argv = split(command)
// A missing working directory fails the launch (start() returns -1 for it), not the program
if (context == null || argv.isEmpty() || !com.droiddeck.launcher.runtime.GuestWorkers.enabled(context) ||
(dir != null && !dir.isDirectory)) {
return start(command, env, dir, onExit, onLine, outputFile, onOutputComplete)
}
val environment = LinkedHashMap(System.getenv())
env?.forEach { line ->
val eq = line.indexOf('=')
if (eq > 0) environment[line.substring(0, eq)] = line.substring(eq + 1)
}
val assignments = environment.map { (k, v) -> "$k=$v" }
// A worker cannot chdir before its exec, so Android's shell does it. The shell starts with an
// environment of its own (the program's LD_PRELOAD of glibc libraries would stop it loading)
// and exports the program's before the exec.
val launch = if (dir != null) {
listOf("/system/bin/sh", "-c", WORKER_CD, "sh", dir.path) + assignments + listOf("--") + argv
} else argv
val workerEnv = if (dir != null) listOf("PATH=/system/bin") else assignments
var input: ParcelFileDescriptor? = null
var reader: ParcelFileDescriptor? = null
var output: ParcelFileDescriptor? = null
val pid = try {
input = ParcelFileDescriptor.open(File("/dev/null"), ParcelFileDescriptor.MODE_READ_ONLY)
output = when {
onLine != null -> ParcelFileDescriptor.createPipe().let { reader = it[0]; it[1] }
outputFile != null -> ParcelFileDescriptor.open(outputFile,
ParcelFileDescriptor.MODE_WRITE_ONLY or ParcelFileDescriptor.MODE_CREATE or ParcelFileDescriptor.MODE_APPEND)
else -> ParcelFileDescriptor.open(File("/dev/null"), ParcelFileDescriptor.MODE_WRITE_ONLY)
}
com.droiddeck.launcher.runtime.GuestWorkers.start(context, launch, workerEnv, listOf(input, output, output)) { status ->
onExit?.accept(if (status < 0) -1 else if (status and 0x7f == 0) (status shr 8) and 0xff else 128 + (status and 0x7f))
}
} catch (e: Exception) {
Log.w(TAG, "no worker for ${argv.first()}", e)
-1
} finally {
runCatching { input?.close() }
runCatching { output?.close() }
}
if (pid <= 0) {
reader?.close()
return start(command, env, dir, onExit, onLine, outputFile, onOutputComplete)
}
Log.i(TAG, "started pid $pid outside the child-process count: ${argv.first()} (${argv.size - 1} arguments)")
reader?.let { pipe ->
Thread({
try {
ParcelFileDescriptor.AutoCloseInputStream(pipe).bufferedReader().useLines { lines ->
lines.forEach { onLine?.accept(it) }
}
} catch (e: Exception) {
} finally {
onOutputComplete?.run()
}
}, "proc-out-$pid").apply { priority = Thread.NORM_PRIORITY - 1; isDaemon = true; start() }
}
return pid
}
@JvmStatic
fun pidOf(process: Process): Int = try {
val field = process.javaClass.getDeclaredField("pid")
@@ -7,6 +7,8 @@ import com.droiddeck.launcher.R
enum class PhantomProcessStatus {
NOT_APPLICABLE,
/** The limit is on, but the session keeps its programs out of Android's count (GuestWorkers). */
UNCOUNTED,
DISABLED,
ENABLED,
UNSET,
@@ -57,6 +59,12 @@ object PhantomProcessLimit {
fun read(context: Context, sdk: Int = Build.VERSION.SDK_INT): PhantomProcessStatus {
if (sdk < Build.VERSION_CODES.S) return PhantomProcessStatus.NOT_APPLICABLE
val status = readSetting(context, sdk)
return if (status != PhantomProcessStatus.DISABLED && com.droiddeck.launcher.runtime.GuestWorkers.limitHandled(context))
PhantomProcessStatus.UNCOUNTED else status
}
private fun readSetting(context: Context, sdk: Int): PhantomProcessStatus {
if (usesDeviceConfig(sdk)) {
val off = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getBoolean(PREF_ANDROID_12_OFF, false)
val global = try {
@@ -101,7 +109,8 @@ object PhantomProcessLimit {
fun hasDeveloperToggle(sdk: Int = Build.VERSION.SDK_INT): Boolean = sdk >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE
fun blocksSteam(status: PhantomProcessStatus): Boolean =
status != PhantomProcessStatus.NOT_APPLICABLE && status != PhantomProcessStatus.DISABLED
status != PhantomProcessStatus.NOT_APPLICABLE && status != PhantomProcessStatus.DISABLED &&
status != PhantomProcessStatus.UNCOUNTED
fun title(context: Context, status: PhantomProcessStatus): String = context.getString(when (status) {
PhantomProcessStatus.ENABLED -> R.string.phantom_title_on
@@ -109,6 +118,7 @@ object PhantomProcessLimit {
PhantomProcessStatus.UNREADABLE -> R.string.phantom_title_unreadable
PhantomProcessStatus.DISABLED -> R.string.phantom_title_off
PhantomProcessStatus.NOT_APPLICABLE -> R.string.phantom_title_not_required
PhantomProcessStatus.UNCOUNTED -> R.string.phantom_title_uncounted
})
fun instructions(context: Context, status: PhantomProcessStatus): String = when (status) {
@@ -116,6 +126,7 @@ object PhantomProcessLimit {
context.getString(R.string.phantom_instructions_fix, fixSentence(context))
PhantomProcessStatus.DISABLED -> context.getString(R.string.phantom_instructions_off)
PhantomProcessStatus.NOT_APPLICABLE -> context.getString(R.string.phantom_instructions_not_applicable)
PhantomProcessStatus.UNCOUNTED -> context.getString(R.string.phantom_instructions_uncounted)
}
fun gateInstructions(context: Context, status: PhantomProcessStatus): String = when (status) {
@@ -132,5 +143,6 @@ object PhantomProcessLimit {
PhantomProcessStatus.UNSET -> "not set (ROM default applies; DroidDeck requires an explicit disabled value)"
PhantomProcessStatus.UNREADABLE -> "unreadable (DroidDeck could not verify the setting)"
PhantomProcessStatus.NOT_APPLICABLE -> "not applicable before Android 12"
PhantomProcessStatus.UNCOUNTED -> "on, not needed (most of the session's programs run in uncounted worker processes)"
}
}
@@ -28,17 +28,18 @@ object SessionLogCapture {
out.flush()
writer = out
this.target = target
pid = HostProcess.start(
pid = HostProcess.startUncounted(
command(Process.myPid(), sinceMillis),
null, target.parentFile, null,
) { line ->
synchronized(this) {
try {
writer?.apply { write(line); newLine(); flush() }
} catch (e: Exception) {
onLine = { line ->
synchronized(this) {
try {
writer?.apply { write(line); newLine(); flush() }
} catch (e: Exception) {
}
}
}
}
},
)
if (pid == -1) {
out.write("logcat could not be started; this ROM may not hand an app its own entries.\n")
out.flush()
@@ -22,6 +22,9 @@ object WirelessAdbFix {
private const val HOST_FILE = "wireless-adb-host.txt"
private const val CONNECTION_FILE = "wireless-adb-connection.txt"
const val LOOPBACK = "127.0.0.1"
private const val TCP_PORT = 5555
private const val WIRELESS_START_MS = 2_000L
private const val NETWORK_PROMPT_MS = 30_000L
private data class SavedConnection(val host: String, val port: Int?)
@@ -55,6 +58,23 @@ object WirelessAdbFix {
writeAtomically(context, File(context.noBackupFilesDir, CONNECTION_FILE), ByteArray(0))
}
/**
* Quest has no pairing screen. adbd in TCP mode (`adb tcpip 5555`) asks "Allow debugging?" for an
* unknown key, and Wireless debugging accepts a key allowed there, so this stands in for pairing.
* Blocks until the prompt is answered or times out.
*/
fun trustOnDevice(context: Context) {
val app = context.applicationContext
// Already trusted, as after a reboot: Wireless debugging takes the key, and port 5555 is closed by then.
val live = if (savedConnection(app) != null) liveConnectAddress(app) else null
if (live != null && acceptsKey(app, live.substringBeforeLast(':').trim('[', ']'), live.substringAfterLast(':').toInt())) return
GlobalSettings.turnOnWirelessDebugging(app)
loadOrCreateIdentity(app)
Kadb.create(LOOPBACK, TCP_PORT, 2_000, 120_000).use { check(it.shell("true").exitCode == 0) }
writeAtomically(app, File(app.noBackupFilesDir, HOST_FILE), LOOPBACK.toByteArray())
writeAtomically(app, File(app.noBackupFilesDir, CONNECTION_FILE), ByteArray(0))
}
private fun savedConnection(context: Context): SavedConnection? {
val directory = context.applicationContext.noBackupFilesDir
if (!File(directory, CERT_FILE).isFile || !File(directory, KEY_FILE).isFile) return null
@@ -78,10 +98,17 @@ object WirelessAdbFix {
fun liveConnectAddress(context: Context): String? {
val app = context.applicationContext
val saved = savedConnection(app) ?: return null
val turnedOn = GlobalSettings.turnOnWirelessDebugging(app)
val host = if (':' in saved.host) "[${saved.host}]" else saved.host
saved.port?.takeIf { answers(saved.host, it) }?.let { return "$host:$it" }
if (!turnedOn) saved.port?.takeIf { answers(saved.host, it) }?.let { return "$host:$it" }
val loopback = runCatching { InetAddress.getByName(saved.host).isLoopbackAddress }.getOrDefault(false)
val port = if (loopback) loopbackAdbPort(app) else findConnectPort(app, saved.host, accept = { answers(saved.host, it) })
// Turning it on can first ask "Allow wireless debugging on this network?", so keep looking while that is answered.
val deadline = android.os.SystemClock.elapsedRealtime() + if (turnedOn) NETWORK_PROMPT_MS else 0L
var port: Int?
do {
if (turnedOn) Thread.sleep(WIRELESS_START_MS)
port = if (loopback) loopbackAdbPort(app) else findConnectPort(app, saved.host, accept = { answers(saved.host, it) })
} while (port == null && android.os.SystemClock.elapsedRealtime() < deadline)
port ?: return null
saveConnection(app, saved.host, port)
return "$host:$port"
@@ -105,10 +132,12 @@ object WirelessAdbFix {
}
}.apply { start() }
}.forEach { it.join() }
return open.sorted().firstOrNull { port -> acceptsKey(app, LOOPBACK, port) }
}
private fun acceptsKey(app: Context, host: String, port: Int): Boolean {
loadOrCreateIdentity(app)
return open.sorted().firstOrNull { port ->
runCatching { Kadb.create(LOOPBACK, port, 1_000, 3_000).use { it.shell("true").exitCode == 0 } }.getOrDefault(false)
}
return runCatching { Kadb.create(host, port, 1_000, 3_000).use { it.shell("true").exitCode == 0 } }.getOrDefault(false)
}
private val EPHEMERAL_PORTS = 32768..60999
@@ -10,11 +10,13 @@ object FrameGen {
const val ENGINE_DDFG = "ddfg"
private const val LEGACY_ENGINE_WINFG = "winfg"
const val ENGINE_LSFG = "lsfg"
const val ENGINE_ZEROFG = "zerofg"
private const val DDFG_PERF_PRESET = 2
private const val DDFG_MODEL = 4
private const val FLOW_SCALE_DDFG = 0.60f
private const val FLOW_SCALE_LSFG = 0.80f
private const val FLOW_SCALE_ZEROFG = 1.0f
val ADAPTIVE_TARGETS = listOf(120, 90, 60)
@@ -69,6 +71,14 @@ object FrameGen {
.putString("engine", mode.engine).putInt("multiplier", mode.multiplier).putInt("target", mode.target).apply()
}
fun pacerEnabled(context: Context): Boolean =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getBoolean("pacer", false)
fun setPacer(context: Context, enabled: Boolean) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putBoolean("pacer", enabled).apply()
WaylandCompositor.nativeSetFrameGenPacer(enabled)
}
fun clearGlobal(context: Context) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.remove("engine").remove("multiplier").remove("target").apply()
@@ -80,6 +90,7 @@ object FrameGen {
mode.engine == ENGINE_DDFG -> context.getString(R.string.frame_gen_ddfg, mode.multiplier)
mode.engine == ENGINE_LSFG && mode.target > 0 -> context.getString(R.string.frame_gen_lsfg_adaptive, mode.target)
mode.engine == ENGINE_LSFG -> context.getString(R.string.frame_gen_lsfg, mode.multiplier)
mode.engine == ENGINE_ZEROFG -> context.getString(R.string.frame_gen_zerofg, mode.multiplier)
else -> context.getString(R.string.frame_gen_off)
}
@@ -104,6 +115,7 @@ object FrameGen {
fun applyPrepared(context: Context, prepared: PreparedApply, refreshHz: Float): String? {
val mode = prepared.mode
WaylandCompositor.nativeSetFrameGenPacer(pacerEnabled(context))
when (mode.engine) {
ENGINE_LSFG -> {
val status = prepared.lsfgStatus ?: LsfgNative.STATUS_NOT_INSTALLED
@@ -111,7 +123,7 @@ object FrameGen {
if (status != LsfgNative.STATUS_OK || cachePath == null) {
WaylandCompositor.nativeSetFrameGenArmed(false, 0, 0)
val problem = context.getString(
if (status == LsfgNative.STATUS_NOT_INSTALLED) R.string.lsfg_problem_missing else R.string.lsfg_problem_failed,
if (status == LsfgNative.STATUS_NOT_INSTALLED) R.string.lsfg_needs_steam else R.string.lsfg_problem_failed,
)
Log.w(TAG, "$problem (status $status)")
return problem
@@ -127,6 +139,11 @@ object FrameGen {
WaylandCompositor.nativeSetFrameGenTuning(FLOW_SCALE_DDFG, refreshHz)
WaylandCompositor.nativeSetFrameGenArmed(true, mode.multiplier, 0)
}
ENGINE_ZEROFG -> {
WaylandCompositor.nativeSetFrameGenEngine(WaylandCompositor.FG_ENGINE_ZEROFG)
WaylandCompositor.nativeSetFrameGenTuning(FLOW_SCALE_ZEROFG, refreshHz)
WaylandCompositor.nativeSetFrameGenArmed(true, mode.multiplier, 0)
}
else -> WaylandCompositor.nativeSetFrameGenArmed(false, 0, 0)
}
Log.i(TAG, "frame generation: $mode at ${refreshHz}Hz")
@@ -2,22 +2,16 @@ package com.droiddeck.launcher.gpu
import android.content.Context
import android.util.Log
import com.droiddeck.launcher.R
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.GameStorage
import com.droiddeck.launcher.session.SessionPrefs
import java.io.File
import java.security.DigestOutputStream
import java.security.MessageDigest
object Lossless {
enum class Source { NONE, STEAM, IMPORT }
enum class ImportResult { UPDATED, UNCHANGED, NOT_OWNED, INVALID, FAILED }
data class State(val owned: Boolean, val ready: Boolean, val source: Source) {
data class State(val owned: Boolean, val ready: Boolean) {
companion object {
val NONE = State(owned = false, ready = false, source = Source.NONE)
val NONE = State(owned = false, ready = false)
}
}
@@ -26,15 +20,13 @@ object Lossless {
private const val KEY_OWNED = "owned"
private const val KEY_ID = "id"
private const val KEY_SOURCE = "source"
private const val SOURCE_STEAM = "STEAM"
private const val KEY_STEAM_STAMP = "steamStamp"
private const val STEAM_MANIFEST = "steamapps/appmanifest_993090.acf"
private const val STEAM_DLL = "steamapps/common/Lossless Scaling/Lossless.dll"
private const val UNCHANGED = -1
fun state(context: Context): State {
val source = prefs(context).getString(KEY_SOURCE, null)
?.let { name -> Source.entries.firstOrNull { it.name == name } } ?: Source.NONE
return State(owned(context), cacheFile(context)?.isFile == true, source)
}
fun state(context: Context) = State(owned(context), cacheFile(context)?.isFile == true)
fun owned(context: Context): Boolean {
if (prefs(context).getBoolean(KEY_OWNED, false)) return true
@@ -43,61 +35,46 @@ object Lossless {
return true
}
fun cacheFile(context: Context): File? = prefs(context).getString(KEY_ID, null)?.let { cacheFor(context, it) }
fun cacheFile(context: Context): File? = steamCacheId(context)?.let { cacheFor(context, it) }
private fun steamCacheId(context: Context): String? = prefs(context).let {
if (it.getString(KEY_SOURCE, null) == SOURCE_STEAM) it.getString(KEY_ID, null) else null
}
@Synchronized
fun sync(context: Context): Int {
val settings = prefs(context)
if (steamCacheId(context) == null && settings.contains(KEY_ID)) {
settings.edit().remove(KEY_ID).remove(KEY_SOURCE).remove(KEY_STEAM_STAMP).apply()
}
val steam = steamDll(context)
if (steam != null) {
markOwned(context)
val stamp = "${steam.length()}:${steam.lastModified()}"
if (stamp != prefs(context).getString(KEY_STEAM_STAMP, null)) {
val status = adopt(context, steam, Source.STEAM)
if (stamp != settings.getString(KEY_STEAM_STAMP, null)) {
val status = adoptSteamDll(context, steam)
if (status != LsfgNative.STATUS_OK && status != UNCHANGED) {
Log.w(TAG, "Steam copy $steam not taken: ${statusName(status)}")
}
prefs(context).edit().putString(KEY_STEAM_STAMP, stamp).apply()
settings.edit().putString(KEY_STEAM_STAMP, stamp).apply()
}
}
return ensureBuilt(context)
}
@Synchronized
fun import(context: Context, dll: File): ImportResult {
if (!owned(context)) return ImportResult.NOT_OWNED
return when (adopt(context, dll, Source.IMPORT)) {
UNCHANGED -> ImportResult.UNCHANGED
LsfgNative.STATUS_OK -> ImportResult.UPDATED
LsfgNative.STATUS_UNREADABLE_FILE, LsfgNative.STATUS_NOT_PORTABLE_EXECUTABLE,
LsfgNative.STATUS_MISSING_SHADERS -> ImportResult.INVALID
else -> ImportResult.FAILED
}
}
fun message(context: Context, result: ImportResult): String = context.getString(
when (result) {
ImportResult.UPDATED -> R.string.lsfg_imported
ImportResult.UNCHANGED -> R.string.lsfg_import_unchanged
ImportResult.NOT_OWNED -> R.string.lsfg_import_not_owned
ImportResult.INVALID -> R.string.lsfg_import_invalid
ImportResult.FAILED -> R.string.lsfg_import_failed
},
)
private fun ensureBuilt(context: Context): Int {
val id = prefs(context).getString(KEY_ID, null) ?: return LsfgNative.STATUS_NOT_INSTALLED
val cache = cacheFor(context, id)
val cache = cacheFile(context) ?: return LsfgNative.STATUS_NOT_INSTALLED
if (usable(cache)) return LsfgNative.STATUS_OK
val dll = storedDll(context)
if (!dll.isFile) return LsfgNative.STATUS_NOT_INSTALLED
return build(dll, cache)
}
private fun adopt(context: Context, source: File, from: Source): Int {
private fun adoptSteamDll(context: Context, source: File): Int {
val staged = File(dir(context).apply { mkdirs() }, "Lossless.dll.staged")
try {
val id = copyHashing(source, staged)
if (id == prefs(context).getString(KEY_ID, null) && usable(cacheFor(context, id))) return UNCHANGED
if (id == steamCacheId(context) && usable(cacheFor(context, id))) return UNCHANGED
val cache = cacheFor(context, id)
var status = LsfgNative.nativeValidateDll(staged.path)
if (status == LsfgNative.STATUS_OK) status = build(staged, cache)
@@ -109,9 +86,9 @@ object Lossless {
cache.delete()
return LsfgNative.STATUS_CACHE_UNUSABLE
}
prefs(context).edit().putString(KEY_ID, id).putString(KEY_SOURCE, from.name).apply()
prefs(context).edit().putString(KEY_ID, id).putString(KEY_SOURCE, SOURCE_STEAM).apply()
removeStale(context, id)
Log.i(TAG, "Lossless.dll from $source ($from) ready as $id")
Log.i(TAG, "Steam Lossless.dll from $source ready as $id")
return LsfgNative.STATUS_OK
} catch (e: java.io.IOException) {
Log.w(TAG, "could not copy $source", e)
@@ -158,9 +135,13 @@ object Lossless {
GameStorage.effective(context)?.path?.let(::File),
GameStorage.x64CardLibrary(context),
) + com.droiddeck.launcher.frontend.AddedGames.roots(context).map { it.host }
return libraries.map { File(it, STEAM_DLL) }.filter { it.isFile }.maxByOrNull { it.lastModified() }
return installedSteamDll(libraries)
}
internal fun installedSteamDll(libraries: List<File>): File? =
libraries.asSequence().filter { File(it, STEAM_MANIFEST).isFile }
.map { File(it, STEAM_DLL) }.filter { it.isFile }.maxByOrNull { it.lastModified() }
private fun markOwned(context: Context) {
if (!prefs(context).getBoolean(KEY_OWNED, false)) prefs(context).edit().putBoolean(KEY_OWNED, true).apply()
}
@@ -11,7 +11,7 @@ internal object DroidDeckHudConfig {
"showPerCore" to "1", "showTemp" to "1", "showBatteryTemp" to "1", "showGpuTemp" to "0",
"showVram" to "1", "showRAM" to "1", "showSwap" to "1", "showBattery" to "0", "showBatteryTime" to "0", "showPower" to "1",
"showFPS" to "1", "showFPSGraph" to "1", "fpsDecimal" to "1",
"showLatency" to "1", "showAvg" to "1", "showLow1" to "1", "showLow01" to "1", "showLow001" to "1",
"showLatency" to "1", "showAvg" to "1", "showLow1" to "1", "showLow01" to "0", "showLow001" to "0",
"showEngine" to "1", "showRenderer" to "1",
"showDisplay" to "1", "showHdr" to "1", "showNet" to "1", "showResolution" to "1",
"showProton" to "1", "showUpscale" to "1", "showSession" to "1", "showClock" to "1", "hudOrder" to "",
@@ -92,8 +92,8 @@ class DroidDeckHudView(context: Context) : View(context) {
private var showBatteryTemp = false
private var showGraph = false
private var showLow1 = true
private var showLow01 = true
private var showLow001 = true
private var showLow01 = false
private var showLow001 = false
private var fpsDecimal = true
private var showClockTime = true
private var showLatency = true
@@ -188,6 +188,12 @@ class DroidDeckHudView(context: Context) : View(context) {
private var graphRect: RectF? = null
private var contentW = 0f
private var contentH = 0f
private var viewportW = Float.POSITIVE_INFINITY
private var viewportH = Float.POSITIVE_INFINITY
private val panelFit: Float
get() = if (dPanel == null || contentW <= 0f || contentH <= 0f) 1f
else minOf(1f, viewportW / contentW, viewportH / contentH)
private var onMovedListener: BiConsumer<Float, Float>? = null
private var onSizeCycledListener: Consumer<String>? = null
@@ -998,13 +1004,20 @@ class DroidDeckHudView(context: Context) : View(context) {
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
viewportW = viewportLimit(widthMeasureSpec)
viewportH = viewportLimit(heightMeasureSpec)
if (stripRect != null) { setMeasuredDimension(contentW.roundToInt(), resolveSize(contentH.roundToInt(), heightMeasureSpec)); return }
val fit = panelFit
setMeasuredDimension(
resolveSize(contentW.roundToInt(), widthMeasureSpec),
resolveSize(contentH.roundToInt(), heightMeasureSpec),
resolveSize((contentW * fit).roundToInt(), widthMeasureSpec),
resolveSize((contentH * fit).roundToInt(), heightMeasureSpec),
)
}
private fun viewportLimit(spec: Int): Float =
if (MeasureSpec.getMode(spec) == MeasureSpec.UNSPECIFIED) Float.POSITIVE_INFINITY
else MeasureSpec.getSize(spec).toFloat()
override fun onDraw(canvas: Canvas) {
if (contentW <= 0f || contentH <= 0f) { lockController.drawBadge(canvas); return }
val blend = if (dock == DroidDeckHudDock.NONE && previewEdge != DroidDeckHudDock.NONE) previewBlend else 0f
@@ -1039,8 +1052,10 @@ class DroidDeckHudView(context: Context) : View(context) {
}
private fun drawContent(canvas: Canvas) {
dPanel?.let { panel -> panelFrame(panel)?.let { canvas.drawBitmap(it, 0f, 0f, null) } }
val fit = panelFit
dPanel?.let { panel -> panelFrame(panel, fit)?.let { canvas.drawBitmap(it, 0f, 0f, null) } }
val saved = canvas.save()
if (fit != 1f) canvas.scale(fit, fit)
if (tileRects.isNotEmpty()) {
tilePaint.color = Color.argb((14 * bgOpacity).roundToInt().coerceIn(8, 40), 255, 255, 255)
@@ -1070,6 +1085,7 @@ class DroidDeckHudView(context: Context) : View(context) {
if (stripRect != null && layerType != LAYER_TYPE_SOFTWARE) drawCachedGraph(canvas, it) else drawGraph(canvas, it)
}
canvas.restoreToCount(saved)
lockController.drawBadge(canvas)
}
@@ -1182,13 +1198,14 @@ class DroidDeckHudView(context: Context) : View(context) {
return if (dy <= 0f) p.right - stroke else if (dy >= r) cx else cx + sqrt(r * r - dy * dy)
}
private fun panelFrame(panel: RectF): Bitmap? {
private fun panelFrame(panel: RectF, fit: Float): Bitmap? {
if (width <= 0 || height <= 0) return null
val stroke = outlineWidth()
val key = "$width,$height,$panel,$dRadius,$dDividerTop,$stroke,$accent,$surfaceRgb,$bgOpacity,${outlineColor()}"
val key = "$width,$height,$fit,$panel,$dRadius,$dDividerTop,$stroke,$accent,$surfaceRgb,$bgOpacity,${outlineColor()}"
if (key == dFrameKey) dFrame?.let { return it }
val bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
val c = Canvas(bmp)
c.scale(fit, fit)
val corner = sp(6f)
val body = dShape(panel.left, panel.top, panel.right, panel.bottom, dRadius, corner)
bgPaint.color = panelColor()
@@ -1261,8 +1278,8 @@ class DroidDeckHudView(context: Context) : View(context) {
internal val isStrip: Boolean get() = stripRect != null
internal val contentWidth: Float get() = contentW
internal val contentHeight: Float get() = contentH
internal val contentWidth: Float get() = contentW * panelFit
internal val contentHeight: Float get() = contentH * panelFit
internal val isDragging: Boolean get() = lockController.isDragging() || tabDragging
@@ -46,7 +46,14 @@ internal class ControllerPortraitGeometry(
}
row(shoulders, top + pad + buttonHeight / 2f, buttonHeight, 4f * unit)
var bodyTop = top + pad + buttonHeight + gap
if (presented.any { it.control in REAR && isStock(it) }) {
if (presented.any { it.control in REAR && isStock(it) } && docked) {
val chipHeight = 36f * unit
val cell = (w - 2f * pad - 5f * gap) / 6f
listOf(0, 1, 4, 5).zip(REAR).forEach { (index, control) ->
put(control, Box(safe.left + pad + cell / 2f + index * (cell + gap), bodyTop + chipHeight / 2f, cell, chipHeight))
}
bodyTop += chipHeight + gap
} else if (presented.any { it.control in REAR && isStock(it) }) {
val rearHeight = min(56f * unit, (panel - bodyTop + top) * .12f).coerceAtLeast(buttonHeight)
row(REAR, bodyTop + rearHeight / 2f, rearHeight, gap)
bodyTop += rearHeight + gap
@@ -19,6 +19,7 @@ object ControllerPrefs {
)
val opacities = listOf(40, 60, 80, 100)
val onScreenOpacityRange = 10..100
val sizes = listOf(80, 85, 90, 95, 100, 105, 110, 115, 120, 125)
@@ -45,6 +46,7 @@ object ControllerPrefs {
val size: Int,
val stickClick: Boolean,
val adaptiveSticks: Boolean,
val onScreenOpacity: Int,
val rumble: Boolean,
val steamButton: Boolean,
val qamButton: Boolean,
@@ -66,7 +68,8 @@ object ControllerPrefs {
opacity = p.getInt("opacity", 100).takeIf { it in opacities } ?: 100,
size = p.getInt("size", 100).takeIf { it in sizes } ?: 100,
stickClick = p.getBoolean("stickClick", true),
adaptiveSticks = p.getBoolean("adaptiveSticks", true),
adaptiveSticks = p.getBoolean("adaptiveSticks", false),
onScreenOpacity = onScreenOpacity(context),
rumble = rumbleEnabled(context),
steamButton = p.getBoolean("steamButton", true),
qamButton = p.getBoolean("qamButton", true),
@@ -103,6 +106,13 @@ object ControllerPrefs {
prefs(context).edit().putBoolean("stickClick", on).apply()
}
fun onScreenOpacity(context: Context): Int =
prefs(context).getInt("onScreenOpacity", 100).coerceIn(onScreenOpacityRange)
fun setOnScreenOpacity(context: Context, percent: Int) {
prefs(context).edit().putInt("onScreenOpacity", percent.coerceIn(onScreenOpacityRange)).apply()
}
fun setAdaptiveSticks(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("adaptiveSticks", on).apply()
}
@@ -2,14 +2,24 @@ package com.droiddeck.launcher.input
class HeldInput(private val emit: (Int, Boolean) -> Unit) {
private val owners = IntArray(768)
private val ordered = arrayOfNulls<(Int, Boolean) -> Unit>(768)
@Synchronized
fun set(source: Int, code: Int, down: Boolean) {
fun set(source: Int, code: Int, down: Boolean, orderedEmit: ((Int, Boolean) -> Unit)? = null) {
if (code !in owners.indices) return
val before = owners[code]
val after = if (down) before or source else before and source.inv()
owners[code] = after
if ((before == 0) != (after == 0)) emit(code, after != 0)
if ((before == 0) != (after == 0)) {
if (after != 0) {
ordered[code] = orderedEmit
orderedEmit?.invoke(code, true) ?: emit(code, true)
} else {
val fn = ordered[code]
ordered[code] = null
fn?.invoke(code, false) ?: emit(code, false)
}
}
}
@Synchronized
@@ -21,7 +31,9 @@ class HeldInput(private val emit: (Int, Boolean) -> Unit) {
fun clear() {
for (code in owners.indices) if (owners[code] != 0) {
owners[code] = 0
emit(code, false)
val fn = ordered[code]
ordered[code] = null
fn?.invoke(code, false) ?: emit(code, false)
}
}
}
@@ -4,7 +4,6 @@ import android.app.Activity
import android.content.Context
import android.os.Build
import android.text.InputType
import android.view.KeyCharacterMap
import android.view.KeyEvent
import android.view.View
import android.view.WindowInsets
@@ -12,15 +11,17 @@ import android.view.inputmethod.BaseInputConnection
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputConnection
import android.view.inputmethod.InputMethodManager
import com.droiddeck.launcher.wayland.WaylandCompositor
class KeyboardHost(
context: Context,
private val sendKeyEvent: (KeyEvent) -> Boolean,
private val sendText: (String) -> Unit,
) : View(context) {
constructor(activity: Activity) : this(activity, { activity.dispatchKeyEvent(it) })
constructor(activity: Activity) :
this(activity, { activity.dispatchKeyEvent(it) }, { WaylandCompositor.textInputCommit(it) })
private val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
private val map: KeyCharacterMap = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD)
var shown = false
private set
var imeShowing = false
@@ -40,8 +41,7 @@ class KeyboardHost(
override fun onCreateInputConnection(outAttrs: EditorInfo): InputConnection? {
if (!shown) return null
outAttrs.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS or
InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
outAttrs.inputType = InputType.TYPE_CLASS_TEXT
outAttrs.imeOptions = EditorInfo.IME_ACTION_NONE or EditorInfo.IME_FLAG_NO_FULLSCREEN or
EditorInfo.IME_FLAG_NO_EXTRACT_UI
return KeyConnection()
@@ -93,45 +93,153 @@ class KeyboardHost(
fun type(text: CharSequence?) {
if (text.isNullOrEmpty()) return
val events = map.getEvents(text.toString().toCharArray())
if (events != null) {
for (event in events) sendKeyEvent(event)
} else {
for (ch in text) {
val t = System.currentTimeMillis()
val down = KeyEvent(t, t, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_UNKNOWN, 0, 0,
KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 0, 0)
sendKeyEvent(CharKeyEvent(down, ch))
sendKeyEvent(CharKeyEvent(KeyEvent.changeAction(down, KeyEvent.ACTION_UP), ch))
}
}
// Text and soft editing actions share this queue to preserve IME ordering.
sendText(text.toString())
}
fun tap(keyCode: Int) {
val control = softControl(keyCode)
if (control != null) {
sendText(control.toString())
return
}
val t = System.currentTimeMillis()
sendKeyEvent(KeyEvent(t, t, KeyEvent.ACTION_DOWN, keyCode, 0))
sendKeyEvent(KeyEvent(t, t, KeyEvent.ACTION_UP, keyCode, 0))
}
private inner class KeyConnection : BaseInputConnection(this, false) {
// A press keeps the route chosen on its first down across repeats and the matching up.
private val controlRoutes = HashMap<Int, Boolean>()
private var composingText = ""
private var composingCursor = 0
override fun commitText(text: CharSequence?, newCursorPosition: Int): Boolean {
composingText = ""
composingCursor = 0
type(text)
return true
}
override fun setComposingText(text: CharSequence?, newCursorPosition: Int): Boolean = true
override fun finishComposingText(): Boolean = true
override fun deleteSurroundingText(beforeLength: Int, afterLength: Int): Boolean {
repeat(beforeLength) { tap(KeyEvent.KEYCODE_DEL) }
repeat(afterLength) { tap(KeyEvent.KEYCODE_FORWARD_DEL) }
override fun setComposingText(text: CharSequence?, newCursorPosition: Int): Boolean {
composingText = text?.toString().orEmpty()
val rawCursor = if (newCursorPosition > 0) {
composingText.length.toLong() + newCursorPosition - 1L
} else {
newCursorPosition.toLong()
}
composingCursor = rawCursor.coerceIn(0L, composingText.length.toLong()).toInt()
return true
}
override fun sendKeyEvent(event: KeyEvent): Boolean = this@KeyboardHost.sendKeyEvent(event)
override fun finishComposingText(): Boolean {
val text = composingText
composingText = ""
composingCursor = 0
type(text)
return true
}
override fun deleteSurroundingText(beforeLength: Int, afterLength: Int): Boolean {
val before = beforeLength.coerceAtLeast(0)
val after = afterLength.coerceAtLeast(0)
if (before == 0 && after == 0) return true
val consumedBefore = minOf(before, composingCursor)
val consumedAfter = minOf(after, composingText.length - composingCursor)
val guestBefore = before - consumedBefore
val guestAfter = after - consumedAfter
if (guestBefore > 1 || guestAfter > 1) return false
return applyDeletion(
composingCursor - consumedBefore,
composingCursor + consumedAfter,
guestBefore,
guestAfter,
)
}
override fun deleteSurroundingTextInCodePoints(beforeLength: Int, afterLength: Int): Boolean {
val before = beforeLength.coerceAtLeast(0)
val after = afterLength.coerceAtLeast(0)
if (before == 0 && after == 0) return true
if (splitsPair(composingCursor)) return false
val text = composingText
val beforePoints = Character.codePointCount(text, 0, composingCursor)
val afterPoints = Character.codePointCount(text, composingCursor, text.length)
val consumedBefore = minOf(before, beforePoints)
val consumedAfter = minOf(after, afterPoints)
val start = Character.offsetByCodePoints(text, composingCursor, -consumedBefore)
val end = Character.offsetByCodePoints(text, composingCursor, consumedAfter)
if (hasUnpairedSurrogate(text, start, end)) return false
return applyDeletion(
start,
end,
before - consumedBefore,
after - consumedAfter,
)
}
private fun applyDeletion(start: Int, end: Int, guestBefore: Int, guestAfter: Int): Boolean {
if (guestBefore > 64 || guestAfter > 64) return false
if (splitsPair(start) || splitsPair(end)) return false
if (start < end) {
composingText = composingText.removeRange(start, end)
composingCursor = start
}
val controls = StringBuilder()
repeat(guestBefore) { controls.append(BACKSPACE) }
repeat(guestAfter) { controls.append(FORWARD_DELETE) }
if (controls.isNotEmpty()) sendText(controls.toString())
return true
}
private fun splitsPair(index: Int): Boolean =
index > 0 && index < composingText.length &&
composingText[index - 1].isHighSurrogate() && composingText[index].isLowSurrogate()
private fun hasUnpairedSurrogate(text: CharSequence, start: Int, end: Int): Boolean {
var i = start
while (i < end) {
val c = text[i]
if (c.isHighSurrogate()) {
if (i + 1 >= end || !text[i + 1].isLowSurrogate()) return true
i += 2
} else if (c.isLowSurrogate()) {
return true
} else {
i++
}
}
return false
}
override fun sendKeyEvent(event: KeyEvent): Boolean {
val control = softControl(event.keyCode)
if (control == null) return this@KeyboardHost.sendKeyEvent(event)
if (event.action == KeyEvent.ACTION_DOWN) {
val soft = if (event.repeatCount == 0) {
val route = !event.isModified()
controlRoutes[event.keyCode] = route
route
} else {
controlRoutes[event.keyCode] ?: !event.isModified()
}
if (!soft) return this@KeyboardHost.sendKeyEvent(event)
if (control == ENTER) finishComposingText()
sendText(control.toString())
return true
}
if (event.action == KeyEvent.ACTION_UP) {
val soft = controlRoutes.remove(event.keyCode) ?: !event.isModified()
if (soft) return true
return this@KeyboardHost.sendKeyEvent(event)
}
return this@KeyboardHost.sendKeyEvent(event)
}
override fun performEditorAction(actionCode: Int): Boolean {
tap(KeyEvent.KEYCODE_ENTER)
finishComposingText()
sendText(ENTER.toString())
return true
}
@@ -140,8 +248,22 @@ class KeyboardHost(
override fun getSelectedText(flags: Int): CharSequence? = null
}
private class CharKeyEvent(origin: KeyEvent, private val ch: Char) : KeyEvent(origin) {
override fun getUnicodeChar(): Int = ch.code
override fun getUnicodeChar(metaState: Int): Int = ch.code
private fun softControl(keyCode: Int): Char? = when (keyCode) {
KeyEvent.KEYCODE_DEL -> BACKSPACE
KeyEvent.KEYCODE_FORWARD_DEL -> FORWARD_DELETE
KeyEvent.KEYCODE_ENTER -> ENTER
KeyEvent.KEYCODE_TAB -> TAB
else -> null
}
private fun KeyEvent.isModified(): Boolean =
isCtrlPressed || isShiftPressed || isAltPressed || isMetaPressed
private companion object {
// Control characters represent editing keys on the guest text channel.
const val ENTER = '\r'
const val BACKSPACE = '\b'
const val FORWARD_DELETE = '\u007f'
const val TAB = '\t'
}
}
@@ -36,6 +36,13 @@ object OnScreenLayout {
fun elements(context: Context, saved: SavedInputLayout?, width: Int, height: Int, safe: Rect,
buttonsOnly: Boolean = false, dock: Dock? = null, rearButtons: Boolean? = null,
trackpads: Boolean? = null): List<InputSurfaceElement> {
val placed = placeElements(context, saved, width, height, safe, buttonsOnly, dock, rearButtons, trackpads)
// Below the game a stick covers nothing, so it keeps its base in view instead of appearing only under the thumb.
return if (dock == null) placed else placed.map { if (it.kind == InputElementKind.STICK) it.copy(hideWhenIdle = false) else it }
}
private fun placeElements(context: Context, saved: SavedInputLayout?, width: Int, height: Int, safe: Rect,
buttonsOnly: Boolean, dock: Dock?, rearButtons: Boolean?, trackpads: Boolean?): List<InputSurfaceElement> {
if (saved == null) return emptyList()
if (width <= 0 || height <= 0) return saved.elements
val layout = oriented(saved, dock?.portrait ?: (height > width))
@@ -0,0 +1,327 @@
package com.droiddeck.launcher.input
import android.content.Context
import android.net.LocalSocket
import android.net.LocalSocketAddress
import android.os.Handler
import android.os.Looper
import android.util.Log
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.wayland.WaylandCompositor
import java.io.File
import java.io.IOException
import java.util.concurrent.RejectedExecutionException
import java.util.concurrent.ScheduledThreadPoolExecutor
import java.util.concurrent.TimeUnit
private enum class TextDelivery(val result: Int) {
NOT_DELIVERED(WaylandCompositor.TEXT_NOT_DELIVERED),
DELIVERED(WaylandCompositor.TEXT_DELIVERED),
UNRESOLVED(WaylandCompositor.TEXT_UNRESOLVED),
}
class SessionTextInput(context: Context, private val hasFocus: () -> Boolean) {
private val delivery = deliveryFor(context)
private val owner = Any()
fun start() = delivery.start(owner, hasFocus)
fun stop() = delivery.stop(owner)
private companion object {
private var instance: SessionTextDelivery? = null
@Synchronized private fun deliveryFor(context: Context): SessionTextDelivery =
instance ?: SessionTextDelivery(context.applicationContext).also { instance = it }
}
}
private class SessionTextDelivery(private val appContext: Context) {
private val handler = Handler(Looper.getMainLooper())
private val lock = Any()
private var generation = 0L
@Volatile private var active = false
private var owner: Any? = null
private var focusCheck: (() -> Boolean)? = null
private var executor: ScheduledThreadPoolExecutor? = null
private var socket: LocalSocket? = null
private var pendingToken = 0
private var runningToken = 0
private var failedToken = 0
private val guestListener = object : WaylandCompositor.TextInputFallbackListener {
override fun onTextInputFallback(text: String, token: Int): Boolean {
synchronized(lock) {
if (!active || pendingToken != 0 || failedToken != 0 || token <= 0) return false
val received = generation
pendingToken = token
val posted = try {
handler.post { enqueue(text, received, token) }
} catch (e: RuntimeException) {
false
}
if (!posted) pendingToken = 0
return posted
}
}
}
fun start(nextOwner: Any, hasFocus: () -> Boolean) {
val previous = synchronized(lock) {
if (owner === nextOwner) return
owner
}
if (previous != null) stop(previous)
val queue = ScheduledThreadPoolExecutor(1) { runnable ->
Thread(runnable, "session-text-input").apply { isDaemon = true }
}
queue.executeExistingDelayedTasksAfterShutdownPolicy = false
synchronized(lock) {
this.owner = nextOwner
focusCheck = hasFocus
active = true
executor = queue
if (failedToken != 0) scheduleRetryLocked(failedToken, INITIAL_DELAY_MS)
}
WaylandCompositor.setTextInputFallbackListener(guestListener)
}
fun stop(oldOwner: Any) {
val detached = synchronized(lock) {
if (owner !== oldOwner) return
owner = null
focusCheck = null
active = false
generation += 1
val queue = executor
val open = socket
val token = if (runningToken == 0 && failedToken == 0) pendingToken else 0
executor = null
socket = null
Triple(queue, open, token)
}
WaylandCompositor.clearTextInputFallbackListener(guestListener)
handler.removeCallbacksAndMessages(null)
detached.second?.let { requestCancel(it) }
detached.first?.shutdown()
if (detached.third != 0) complete(detached.third)
}
private fun enqueue(text: String, received: Long, token: Int) {
val currentFocus = synchronized(lock) { if (active && generation == received) focusCheck else null }
if (currentFocus == null || !currentFocus() || !WaylandCompositor.isTextInputFallbackListener(guestListener)) {
Log.d(TAG, "guest text fallback skipped outside the active focused session")
complete(token)
return
}
val bytes = text.toByteArray(Charsets.UTF_8)
if (bytes.isEmpty() || bytes.size > MAX_BYTES) {
complete(token)
return
}
val queue = synchronized(lock) {
if (active && generation == received) executor else null
}
if (queue == null) {
complete(token)
return
}
try {
queue.execute {
try {
val delivery = send(bytes, received, token)
if (delivery == TextDelivery.UNRESOLVED) recover(token)
else complete(token, delivery)
} finally {
releaseRunning(token)
}
}
} catch (e: RejectedExecutionException) {
complete(token)
}
}
private fun recover(token: Int) {
if (probe()) {
complete(token)
return
}
val marked = synchronized(lock) {
if (pendingToken == token && failedToken == 0) {
failedToken = token
WaylandCompositor.completeTextInputFallback(token, TextDelivery.UNRESOLVED.result)
scheduleRetryLocked(token, INITIAL_DELAY_MS)
true
} else {
false
}
}
if (marked) Log.w(TAG, "text injection could not be confirmed")
}
private fun scheduleRetryLocked(token: Int, delayMs: Long) {
if (!active || failedToken != token || pendingToken != token) return
val queue = executor ?: return
val current = generation
try {
queue.schedule({ retryProbe(current, token, delayMs) }, delayMs, TimeUnit.MILLISECONDS)
} catch (e: RejectedExecutionException) {
}
}
private fun retryProbe(received: Long, token: Int, delayMs: Long) {
val ready = synchronized(lock) {
active && generation == received && failedToken == token && pendingToken == token
}
if (!ready) return
val proven = probe()
val owned = synchronized(lock) {
if (proven) {
if (active && generation == received && failedToken == token && pendingToken == token) {
pendingToken = 0
runningToken = 0
failedToken = 0
true
} else {
false
}
} else {
if (active && generation == received && failedToken == token && pendingToken == token) {
val next = (delayMs * 2).coerceAtMost(MAX_DELAY_MS)
scheduleRetryLocked(token, next)
}
false
}
}
if (owned) WaylandCompositor.completeTextInputFallback(token, TextDelivery.NOT_DELIVERED.result)
}
private fun probe(): Boolean {
val live = LocalSocket()
return try {
live.connect(LocalSocketAddress(endpoint().path, LocalSocketAddress.Namespace.FILESYSTEM))
live.soTimeout = TIMEOUT_MS
val out = live.outputStream
out.write(lengthPrefix(0))
out.flush()
live.inputStream.read() == 0
} catch (e: IOException) {
Log.w(TAG, "could not probe guest text input state", e)
false
} finally {
close(live)
}
}
private fun complete(token: Int, delivery: TextDelivery = TextDelivery.NOT_DELIVERED) {
val owned = synchronized(lock) {
if (pendingToken == token) {
pendingToken = 0
runningToken = 0
failedToken = 0
true
} else {
false
}
}
if (owned) WaylandCompositor.completeTextInputFallback(token, delivery.result)
}
private fun releaseRunning(token: Int) {
synchronized(lock) {
if (runningToken == token) runningToken = 0
}
}
private fun send(bytes: ByteArray, received: Long, token: Int): TextDelivery {
val live = LocalSocket()
if (!claim(live, received, token)) {
close(live)
return TextDelivery.NOT_DELIVERED
}
var requested = false
try {
live.connect(LocalSocketAddress(endpoint().path, LocalSocketAddress.Namespace.FILESYSTEM))
live.soTimeout = TIMEOUT_MS
if (!isCurrent(received)) return TextDelivery.NOT_DELIVERED
val out = live.outputStream
out.write(lengthPrefix(bytes.size))
requested = true
out.write(bytes)
out.flush()
val input = live.inputStream
val ack = try {
input.read()
} catch (e: IOException) {
// Android may report a socket read timeout as a plain IOException.
requestCancel(live)
input.read()
}
if (ack == 0) Log.d(TAG, "guest did not complete text delivery")
if (ack != 0 && ack != 1 && isCurrent(received)) Log.w(TAG, "guest did not acknowledge text delivery")
return when (ack) {
1 -> TextDelivery.DELIVERED
0 -> TextDelivery.NOT_DELIVERED
else -> TextDelivery.UNRESOLVED
}
} catch (e: IOException) {
if (isCurrent(received)) Log.w(TAG, "could not hand text to the guest", e)
if (!requested) return TextDelivery.NOT_DELIVERED
return TextDelivery.UNRESOLVED
} finally {
release(live)
close(live)
}
}
private fun requestCancel(live: LocalSocket) {
try {
live.shutdownOutput()
} catch (e: IOException) {
Log.w(TAG, "could not request guest text input cancellation", e)
}
}
private fun isCurrent(received: Long) = synchronized(lock) { active && generation == received }
private fun claim(live: LocalSocket, received: Long, token: Int) = synchronized(lock) {
if (!active || generation != received || pendingToken != token || runningToken != 0 || failedToken != 0) {
false
} else {
runningToken = token
socket = live
true
}
}
private fun release(live: LocalSocket) {
synchronized(lock) {
if (socket === live) socket = null
}
}
private fun endpoint(): File = File(LinuxRuntime.sessionRoot(appContext), "text-input.sock")
private fun lengthPrefix(size: Int): ByteArray {
val flagged = if (size == 0) size else size or Int.MIN_VALUE
return byteArrayOf(
(flagged ushr 24).toByte(),
(flagged ushr 16).toByte(),
(flagged ushr 8).toByte(),
flagged.toByte(),
)
}
private fun close(sock: LocalSocket) {
try {
sock.close()
} catch (e: IOException) {
}
}
private companion object {
const val TAG = "SessionTextInput"
const val MAX_BYTES = 65536
const val TIMEOUT_MS = 3000
const val INITIAL_DELAY_MS = 500L
const val MAX_DELAY_MS = 5000L
}
}
@@ -38,6 +38,11 @@ object ElfSeccompPatch {
val end = minOf(data.size, buffer.getLong(at + 8).toInt() + buffer.getLong(at + 32).toInt()) and 3.inv()
var pos = start
while (pos + 4 <= end) {
if (patchTermiosRequest(buffer, pos, end)) {
patched++
pos += 4
continue
}
val replacement = when (buffer.getInt(pos)) {
MOV_X8_SET_ROBUST_LIST -> NOP
MOV_X8_CLONE3, MOV_X8_RSEQ -> MOV_X0_ENOSYS
@@ -65,6 +70,40 @@ object ElfSeccompPatch {
return patched
}
/**
* glibc 2.42 and later read and set a terminal with TCGETS2 and TCSETS2/W2/F2, which Android's
* SELinux policy refuses on an app's pseudo-terminal slaves (EACCES): isatty() was false in every
* Konsole, ssh and tmux session, so bash had no prompt or job control and stdout was not line
* buffered. TCGETS and TCSETS* carry the same struct without its two speed fields, which glibc
* then takes from c_cflag. A site is `movz xN, #lo` then `movk xN, #hi, lsl #16`; the movz gets
* the old request and the movk becomes a no-op.
*/
private fun patchTermiosRequest(buffer: ByteBuffer, pos: Int, end: Int): Boolean {
val movz = buffer.getInt(pos)
if ((movz and 0x7fe00000) != 0x52800000) return false
val low = (movz ushr 5) and 0xffff
if (low !in 0x542a..0x542d) return false
val register = movz and 0x1f
var next = pos + 4
while (next < minOf(end, pos + 4 + 4 * 4)) {
val movk = buffer.getInt(next)
if ((movk and 0x7fe00000) == 0x72a00000 && (movk and 0x1f) == register) {
val request = when ((movk ushr 5) and 0xffff) {
0x802c -> if (low == 0x542a) 0x5401 else return false
0x402c -> if (low != 0x542a) 0x5402 + (low - 0x542b) else return false
else -> return false
}
buffer.putInt(pos, (movz and 0x1f.inv() and (0xffff shl 5).inv()) or (request shl 5) or register)
buffer.putInt(next, NOP)
return true
}
// Anything between that might read or write the register would see the old low half
if (intArrayOf(0, 5, 10, 16).any { (movk ushr it) and 0x1f == register }) return false
next += 4
}
return false
}
/** Patches the file behind [path] (symlinks followed) if it still has unpatched call sites. */
fun patchFile(path: File): Int {
val target = path.canonicalFile
@@ -0,0 +1,271 @@
package com.droiddeck.launcher.runtime
import android.content.Context
import android.os.SystemClock
import android.system.Os
import android.system.OsConstants
import android.util.Log
import com.droiddeck.launcher.wayland.WaylandCompositor
import java.io.File
import java.io.InputStream
import java.nio.file.Files
import java.nio.file.LinkOption.NOFOLLOW_LINKS
import java.security.MessageDigest
/** One app-issued Steam session and one attested Gamescope worker. This is not an
* isolation boundary against arbitrary code already running as the Android app UID. */
internal object FrameAcquireWorkerProbe {
private const val SESSION_SCRIPT = "/usr/local/bin/droiddeck-session"
private const val PATH = "/usr/local/bin/gamescope"
private const val CAPABILITY = "linuxfs/usr/local/share/droiddeck/gamescope-producer-acquire-v1"
internal const val GAMESCOPE_ENABLE = "GAMESCOPE_DROIDDECK_PRODUCER_ACQUIRE=1"
internal const val GAME_ENABLE = "DROIDDECK_GAME_DROIDDECK_GAME_FRAME_ACQUIRE=1"
private const val MAX_BINARY_BYTES = 32L * 1024L * 1024L
internal const val RECEIPT_TAG = 0x44445046
internal const val RECEIPT_BYTES = Int.SIZE_BYTES + Long.SIZE_BYTES
private const val TTL_MS = 90_000L
internal data class Ticket(
val owner: Int, val root: File, val configuredRoot: File, val binary: File,
val expected: ByteArray, val expires: Long, val steamGameUrl: String?,
)
internal data class Qualified(val ticket: Ticket, val dev: Long, val ino: Long, val mtime: Long, val ctime: Long)
private var intent: Ticket? = null
private var nativeOwner = 0
private var nativePid = 0
private enum class Stage { ARM, MATCH, PUBLISH }
private enum class Reason {
ENABLED, MATCH_ACK, MATCH_OWNER, MATCH_EXPIRED, MATCH_PATH, MATCH_ROOT,
MATCH_ARGV, MATCH_FILE, MATCH_DIGEST, QUALIFIED, PUBLISH_TICKET, PUBLISH_RESTAT,
PUBLISH_NATIVE, PUBLISH_RECEIPT, RESERVED
}
private val reported = mutableSetOf<Stage>()
@Synchronized private fun breadcrumb(stage: Stage, reason: Reason) {
if (reported.add(stage)) Log.i("FrameAcquireWorkerProbe", "worker_admission=" + reason.name)
}
internal fun validEnvironment(agentEnvironment: List<String>, customEnvironment: List<String>): Boolean {
// AgentEnv supplies a replacement PATH whenever any executable override is staged.
// Custom env is user-editable, including names not known to this build; it is not a trust root.
return agentEnvironment.isEmpty() && customEnvironment.isEmpty()
}
fun available(context: Context): Boolean =
android.os.Build.VERSION.SDK_INT >= 30 && com.droiddeck.launcher.core.DeviceSupport.adreno() &&
runCatching { context.assets.open(CAPABILITY).use { it.readBytes().decodeToString() } }
.getOrNull() == "droiddeck-producer-acquire-v1\n"
private fun digest(input: InputStream, maxBytes: Long): ByteArray {
val out = MessageDigest.getInstance("SHA-256")
val buffer = ByteArray(64 * 1024)
var size = 0L
while (true) {
val n = input.read(buffer)
if (n == -1) break
require(n > 0)
size += n
require(size <= maxBytes)
out.update(buffer, 0, n)
}
require(size > 0)
return out.digest()
}
// Compute asset identity outside SessionService's stop lock and before a worker
// exists. The resulting ticket still has to be assigned to that exact owner.
private const val STEAM_RUN_PREFIX = "steam://rungameid/"
internal fun permittedLaunch(url: String?, frontendGame: Boolean): Boolean =
if (url == null) !frontendGame else frontendGame && url.startsWith(STEAM_RUN_PREFIX) &&
com.droiddeck.launcher.frontend.GameLaunchLink.validId(url.removePrefix(STEAM_RUN_PREFIX))
internal fun prepare(context: Context, steamGameUrl: String?, frontendGame: Boolean): Ticket? {
if (!permittedLaunch(steamGameUrl, frontendGame) ||
!available(context) || !WaylandCompositor.frameWorkerProbeEnabled()) return null
return runCatching {
val configuredRoot = LinuxRuntime.rootDir(context).absoluteFile
val root = configuredRoot.canonicalFile
val file = File(root.path + PATH)
require(file.canonicalFile == file && Files.isRegularFile(file.toPath(), NOFOLLOW_LINKS))
val script = File(root.path + SESSION_SCRIPT)
require(exactSteamScript(SESSION_SCRIPT, root, configuredRoot))
val stagedScript = script.inputStream().use { digest(it, 1024L * 1024L) }
val signedScript = context.assets.open("linuxfs" + SESSION_SCRIPT).use { digest(it, 1024L * 1024L) }
require(MessageDigest.isEqual(stagedScript, signedScript))
val expected = context.assets.open("linuxfs" + PATH).use { digest(it, MAX_BINARY_BYTES) }
Ticket(0, root, configuredRoot, file, expected, SystemClock.elapsedRealtime() + TTL_MS, steamGameUrl)
}.getOrNull()
}
@Synchronized fun arm(owner: Int, prepared: Ticket): Boolean {
if (owner <= 0 || SystemClock.elapsedRealtime() >= prepared.expires) return false
reported.clear()
intent = prepared.copy(owner = owner)
breadcrumb(Stage.ARM, Reason.ENABLED)
return true
}
/** Native shebang handling can give Bash the staged host filename as its $0. */
internal fun exactSteamScript(token: String, root: File, configuredRoot: File): Boolean {
if (token != SESSION_SCRIPT && token != root.path + SESSION_SCRIPT &&
token != configuredRoot.path + SESSION_SCRIPT) return false
return runCatching {
val expected = File(root.path + SESSION_SCRIPT)
val supplied = if (token == SESSION_SCRIPT) expected else File(token)
// Reject symlinks within the authorized root, including a symlink replacing the script.
// Android's configured root itself may be an alias of its app-issued canonical root.
require(configuredRoot.canonicalFile == root && expected.canonicalFile == expected &&
supplied.canonicalFile == expected &&
Files.isRegularFile(expected.toPath(), NOFOLLOW_LINKS) &&
Files.isRegularFile(supplied.toPath(), NOFOLLOW_LINKS))
Files.isSameFile(supplied.toPath(), expected.toPath())
}.getOrDefault(false)
}
internal fun exactGamescopeArgs(
argv: List<String>, steamGameUrl: String? = null, script: (String) -> Boolean,
): Boolean {
if (argv.firstOrNull() !in listOf("gamescope", PATH)) return false
val delimiter = argv.indexOf("--")
val tailSize = if (steamGameUrl == null) 3 else 4
if (delimiter < 4 || argv.size != delimiter + tailSize || argv[delimiter + 2] != "steam" ||
!script(argv[delimiter + 1]) ||
(steamGameUrl != null && (!permittedLaunch(steamGameUrl, true) || argv.last() != steamGameUrl))) return false
val opts = argv.subList(1, delimiter)
if (opts.take(4) != listOf("--backend", "wayland", "--expose-wayland", "-f")) return false
val dimensions = setOf("-W", "-H", "-w", "-h")
val seen = mutableSetOf<String>()
var i = 4
while (i < opts.size) {
val option = opts[i++]
if (!seen.add(option)) return false
when (option) {
"-e", "--hdr-enabled", "--mangoapp" -> Unit
"-S" -> if (opts.getOrNull(i++) != "stretch") return false
"--default-touch-mode" -> if (opts.getOrNull(i++) != "4") return false
"-W", "-H", "-w", "-h", "-r", "--xwayland-count" -> {
val value = opts.getOrNull(i++) ?: return false
if (value.length !in 1..6 || value.any { it !in '0'..'9' } ||
value.toIntOrNull()?.let { it > 0 } != true) return false
}
else -> return false
}
}
return seen.containsAll(dimensions)
}
fun match(owner: Int, root: File, file: String, argv: List<String>, ack: Boolean): Qualified? {
val t = synchronized(this) { intent } ?: return null
// Startup's --version worker and unrelated workers must not consume the one diagnostic.
val candidate = "--version" !in argv && (file.substringAfterLast('/') == "gamescope" ||
argv.firstOrNull()?.substringAfterLast('/') == "gamescope")
val rejection = when {
!ack -> Reason.MATCH_ACK
t.owner != owner -> Reason.MATCH_OWNER
SystemClock.elapsedRealtime() >= t.expires -> Reason.MATCH_EXPIRED
file != PATH -> Reason.MATCH_PATH
runCatching { root.canonicalFile }.getOrNull() != t.root -> Reason.MATCH_ROOT
!exactGamescopeArgs(argv, t.steamGameUrl) { exactSteamScript(it, t.root, t.configuredRoot) } -> Reason.MATCH_ARGV
else -> null
}
if (rejection != null) {
if (candidate) breadcrumb(Stage.MATCH, rejection)
return null
}
// Hash an actual descriptor rather than two pathname opens. Check both the
// descriptor and pathname identity; a race or substituted executable denies the grant.
val qualified = runCatching {
require(t.binary.canonicalFile == t.binary)
val before = Os.lstat(t.binary.path)
require(OsConstants.S_ISREG(before.st_mode) && before.st_size in 1..MAX_BINARY_BYTES)
val fd = Os.open(t.binary.path, OsConstants.O_RDONLY or OsConstants.O_NOFOLLOW or OsConstants.O_CLOEXEC, 0)
val sum = try {
require(stillSame(before, Os.fstat(fd)))
android.os.ParcelFileDescriptor.AutoCloseInputStream(android.os.ParcelFileDescriptor.dup(fd)).use {
digest(it, MAX_BINARY_BYTES)
}.also { require(stillSame(before, Os.fstat(fd))) }
} finally {
Os.close(fd)
}
val after = Os.lstat(t.binary.path)
require(stillSame(before, after))
if (!MessageDigest.isEqual(sum, t.expected)) {
breadcrumb(Stage.MATCH, Reason.MATCH_DIGEST)
return null
}
Qualified(t, after.st_dev, after.st_ino, after.st_mtime, after.st_ctime)
}.getOrNull()
breadcrumb(Stage.MATCH, if (qualified == null) Reason.MATCH_FILE else Reason.QUALIFIED)
return qualified
}
private fun stillSame(a: android.system.StructStat, b: android.system.StructStat): Boolean =
a.st_dev == b.st_dev && a.st_ino == b.st_ino && a.st_size == b.st_size &&
a.st_mtime == b.st_mtime && a.st_ctime == b.st_ctime &&
OsConstants.S_ISREG(b.st_mode)
internal fun validReceipt(pid: Int, workerPid: Int, ticks: Long, bytes: Int): Long =
if (pid > 1 && pid == workerPid && ticks > 0 && bytes == RECEIPT_BYTES) ticks else 0L
internal fun parseSelfStat(stat: String, pid: Int): Long {
if (pid <= 1 || !stat.startsWith("$pid (")) return 0L
val comm = stat.lastIndexOf(')')
if (comm < 3 || stat.getOrNull(comm + 1) != ' ') return 0L
val fields = stat.substring(comm + 2).split(' ').filter { it.isNotEmpty() }
if (fields.firstOrNull()?.length != 1 || fields.size < 21) return 0L
val value = fields[19] // field 22 from field 3 (the single-character task state).
return value.takeIf { it.isNotEmpty() && it.all { ch -> ch in '0'..'9' } }
?.toLongOrNull()?.takeIf { it > 0 } ?: 0L
}
internal fun selfStartTicks(pid: Int): Long = runCatching {
File("/proc/self/stat").inputStream().use { input ->
val bytes = ByteArray(4096)
var used = 0
while (used < bytes.size) {
val n = input.read(bytes, used, bytes.size - used)
if (n < 0) break
if (n == 0) return@runCatching 0L
used += n
}
if (used == bytes.size || used == 0 || bytes[used-1] != '\n'.code.toByte()) 0L
else parseSelfStat(String(bytes, 0, used, Charsets.US_ASCII), pid)
}
}.getOrDefault(0L)
/** Runs just before the final GO byte. Failure never changes ordinary launch. */
@Synchronized fun publish(q: Qualified, pid: Int, startTicks: Long) {
val t = q.ticket
if (intent !== t || pid <= 1 || SystemClock.elapsedRealtime() >= t.expires) {
if (intent === t) breadcrumb(Stage.PUBLISH, Reason.PUBLISH_TICKET)
return
}
intent = null // At most one candidate per explicitly armed session.
if (startTicks <= 0L) {
breadcrumb(Stage.PUBLISH, Reason.PUBLISH_RECEIPT)
return
}
val status = runCatching {
val st = Os.lstat(t.binary.path)
require(OsConstants.S_ISREG(st.st_mode) && st.st_dev == q.dev && st.st_ino == q.ino &&
st.st_mtime == q.mtime && st.st_ctime == q.ctime)
if (WaylandCompositor.frameWorkerProbeGrant(t.owner, pid, t.expires, t.binary.path, st.st_dev, st.st_ino, startTicks)) {
nativeOwner = t.owner
nativePid = pid
Reason.RESERVED
} else Reason.PUBLISH_NATIVE
}.getOrDefault(Reason.PUBLISH_RESTAT)
breadcrumb(Stage.PUBLISH, status)
}
@Synchronized fun revoke(owner: Int, pid: Int = 0) {
if (owner <= 0) return
if (pid == 0 && intent?.owner == owner) intent = null
if (nativeOwner == owner && (pid == 0 || pid == nativePid)) {
WaylandCompositor.frameWorkerProbeRevoke(owner, pid)
nativeOwner = 0
nativePid = 0
}
}
}
File diff suppressed because it is too large. Load diff
@@ -35,9 +35,40 @@ object LegacyNames {
@Synchronized
fun migrateEtc(root: File) {
for ((old, new) in LINKED_DIRS) moveAndLink(File(root, old), File(root, new))
File(root, "etc/droiddeck/empty").mkdirs()
clearEmptyStandIn(root)
File(root, NO_THERMAL).mkdirs()
}
/**
* It stands in for /sys/bus/pci/devices, and libpci exits the whole process on an entry it cannot
* parse; older builds let thermal bind mount points leak into it. The guest can write here, so a
* link is never followed: one in place of the folder is removed, and one above it stops the cleanup.
*/
private fun clearEmptyStandIn(root: File) {
val linkedAbove = listOf("etc", "etc/droiddeck").firstOrNull { Files.isSymbolicLink(File(root, it).toPath()) }
if (linkedAbove != null) {
Log.w(TAG, "not clearing the empty stand-in: $linkedAbove is a link")
return
}
val empty = File(root, "etc/droiddeck/empty")
if (Files.isSymbolicLink(empty.toPath())) runCatching { Files.delete(empty.toPath()) }
.onFailure { Log.w(TAG, "could not remove the link at $empty", it); return }
empty.mkdirs()
empty.listFiles()?.forEach { entry ->
runCatching { deleteWithoutFollowing(entry.toPath()) }.onFailure { Log.w(TAG, "could not clear $entry", it) }
}
}
private fun deleteWithoutFollowing(path: java.nio.file.Path) {
if (Files.isDirectory(path, java.nio.file.LinkOption.NOFOLLOW_LINKS)) {
Files.newDirectoryStream(path).use { entries -> entries.forEach(::deleteWithoutFollowing) }
}
Files.deleteIfExists(path)
}
/** Stands in for a /sys/class/thermal the kernel won't list; proot adds the bound zones' mount points to it. */
const val NO_THERMAL = "etc/droiddeck/no-thermal"
@Synchronized
fun migrateRootfs(root: File) {
migrateEtc(root)
@@ -248,7 +248,7 @@ public final class LinuxRuntime {
// A kernel that refuses to list /sys/class/thermal (Pixel 10, Android 17) made mangoapp abort
// at start ("filesystem_error ... Permission denied: '/sys/class/thermal/'") until its
// wrapper gave up: it lists the directory for CPU temperatures. Empty there instead.
if (new File("/sys/class/thermal").list() == null) bind(cmd, new File(root, "etc/droiddeck/empty").getPath() + ":/sys/class/thermal");
if (new File("/sys/class/thermal").list() == null) bind(cmd, new File(root, LegacyNames.NO_THERMAL).getPath() + ":/sys/class/thermal");
bind(cmd, context.getFilesDir().getPath());
bind(cmd, context.getCacheDir().getPath());
bind(cmd, liveDir(context).getPath());
@@ -24,6 +24,16 @@ object NativeGuest {
fun enabled(context: Context): Boolean =
SessionPrefs.nativeUserland(context) && available(LinuxRuntime.rootDir(context))
/**
* Whether the next session will start natively. The session stages the hook from the APK before
* it starts, so only the setting and the rootfs's loader decide, and a runtime still to be
* installed will have one.
*/
fun nextSession(context: Context): Boolean =
SessionPrefs.nativeUserland(context) && willRun(LinuxRuntime.rootDir(context), LinuxRuntime.isInstalled(context))
internal fun willRun(root: File, installed: Boolean): Boolean = !installed || loader(root) != null
/** The mode the running session started in; null between sessions. */
@Volatile var sessionMode: Boolean? = null
@@ -219,6 +219,19 @@ object BottomDesktop {
fun sendText(text: String) {
val target = service ?: return
if (text.isNotEmpty() && text.all { it == '\r' || it == '\n' || it == '\b' || it == '\u007f' || it == '\t' }) {
for (c in text) {
val evdev = when (c) {
'\r', '\n' -> 28
'\b' -> 14
'\u007f' -> 111
else -> 15
}
sendKey(evdev, true)
sendKey(evdev, false)
}
return
}
send(target, Message.obtain(null, Comp.MSG_TEXT).apply { data = Bundle().apply { putString(Comp.KEY_TEXT, text) } })
}
@@ -30,6 +30,8 @@ object ComponentsManager {
private const val DD_COMPONENTS = "Droid-Deck/DroidDeck-Components"
internal const val DD_NIGHTLY = "linux-nightly"
internal const val DD_BIONIC = "bionic-stable"
/** FEX for original Xbox games on DroidDeck-Bionic: kept apart from [DD_BIONIC] so automatic FEX updates never pick it. */
internal const val DD_XBOX = "bionic-xbox"
private val RELEASES = linkedMapOf(
"FexCore-Linux" to "fex",
"Dxvk-Linux" to "dxvk",
@@ -38,7 +40,8 @@ object ComponentsManager {
"Vkd3d-proton-Linux" to "vkd3d",
)
private val NIGHTLY_PREFIXES = linkedMapOf("DD-dxvk-" to "dxvk", "DD-vkd3d-proton-" to "vkd3d", "DD-FEXCore-" to "fex")
private val SOURCES = RELEASES.keys.map { NIGHTLIES to it } + (DD_COMPONENTS to DD_NIGHTLY) + (DD_COMPONENTS to DD_BIONIC)
private val SOURCES = RELEASES.keys.map { NIGHTLIES to it } + (DD_COMPONENTS to DD_NIGHTLY) + (DD_COMPONENTS to DD_BIONIC) +
(DD_COMPONENTS to DD_XBOX)
private val DOWNLOAD_REPOS = listOf(NIGHTLIES, DD_COMPONENTS)
private val TYPES = mapOf("FEXCore-Linux" to "fex", "FEXCore-Bionic" to "fex", "DXVK-Linux" to "dxvk", "VKD3D-Linux" to "vkd3d")
private val TYPE_OF = mapOf("fex" to "FEXCore-Linux", "dxvk" to "DXVK-Linux", "vkd3d" to "VKD3D-Linux")
@@ -253,6 +256,28 @@ object ComponentsManager {
saveState(context, state)
}
internal enum class Assigned { SET, NOT_LISTED, CHANGED }
/**
* Sets a game's component to a listed package, fetching it first when it is not stored. [expected] is the component
* the caller read when it decided: if the game's component is something else once the package is ready (the player
* chose one during the download), nothing is written. [onSet] runs under the same lock as the write.
*/
internal fun assignGameComponent(context: Context, scope: String, comp: String, file: String, release: String,
expected: String?, onSet: () -> Unit = {}): Assigned {
val wcp = File(packagesDir(context), safeName(file))
if (!wcp.isFile || runCatching { packageInfo(context, wcp) }.isFailure) {
wcp.delete()
download(context, catalogItem(context, file, release) ?: return Assigned.NOT_LISTED) {}
}
synchronized(lock) {
if (gameComponents(context, scope)[comp] != expected) return Assigned.CHANGED
setGameComponent(context, scope, comp, file) { runtimeManaged(context, it) }
onSet()
}
return Assigned.SET
}
fun clearGameComponents(context: Context, scope: String) = synchronized(lock) {
require(GameEnvironment.validScope(scope))
val state = loadState(context)
@@ -1124,7 +1149,7 @@ object ComponentsManager {
internal fun assetComp(release: String, name: String): String? = RELEASES[release] ?: when (release) {
DD_NIGHTLY -> NIGHTLY_PREFIXES.entries.firstOrNull { name.startsWith(it.key) }?.value
DD_BIONIC -> "fex"
DD_BIONIC, DD_XBOX -> "fex"
else -> null
}
@@ -121,7 +121,7 @@ object GameEnvironmentStore {
) {
publishGameCores(context)
val stored = config ?: read(context)
val resolved = stored.copy(shared = GameEnvironment.defaults(SessionPrefs.fexPreset(context), SessionPrefs.forceSsbs(context)) + stored.shared)
val resolved = GameEnvironment.withKnownGames(stored).copy(shared = GameEnvironment.defaults(SessionPrefs.fexPreset(context), SessionPrefs.forceSsbs(context)) + stored.shared)
val json = encode(resolved)
val dxvk = TextureFiltering.dxvkOptions(
SessionPrefs.textureAnisotropy(context), SessionPrefs.textureLodBias(context),
@@ -59,13 +59,18 @@ object GameStorage {
return when {
pref == SessionPrefs.GAME_STORAGE_OFF -> null
pref.isEmpty() -> options(context).firstOrNull()?.let { Option(it.name, it.path) }
else -> Option(SessionPrefs.gameStorageLabel(context), pref).takeIf { attached(File(pref)) }
else -> reachable(pref).let { path -> Option(SessionPrefs.gameStorageLabel(context), path).takeIf { attached(File(path)) } }
}
}
fun disconnected(context: Context): Boolean {
val pref = SessionPrefs.gameStorage(context)
return pref.isNotEmpty() && pref != SessionPrefs.GAME_STORAGE_OFF && !attached(File(pref))
return pref.isNotEmpty() && pref != SessionPrefs.GAME_STORAGE_OFF && !attached(File(reachable(pref)))
}
internal fun reachable(path: String, usable: (File) -> Boolean = { it.isDirectory && it.canWrite() }): String {
val alias = UsbLink.storagePath(path)
return if (alias != path && !usable(File(path)) && usable(File(alias))) alias else path
}
internal fun attached(
@@ -0,0 +1,70 @@
package com.droiddeck.launcher.session
import android.util.Log
import java.io.File
internal object PageCacheTrim {
private const val TAG = "PageCacheTrim"
private const val MIN_FILE_BYTES = 8L shl 20
private const val POLL_MS = 3000L
private const val RESCAN_MS = 120_000L
data class Mem(val freeKb: Long, val fileKb: Long)
fun parse(meminfo: String): Mem? {
fun field(name: String) = Regex("""(?m)^$name:\s+(\d+) kB""").find(meminfo)?.groupValues?.get(1)?.toLongOrNull()
val free = field("MemFree") ?: return null
val file = (field("Active\\(file\\)") ?: return null) + (field("Inactive\\(file\\)") ?: return null)
return Mem(free, file)
}
fun shouldTrim(mem: Mem, baselineFileKb: Long): Boolean {
val built = mem.fileKb - baselineFileKb
return (mem.freeKb < 2560 * 1024 && built >= 768 * 1024) ||
(mem.freeKb < 1024 * 1024 && built >= 128 * 1024)
}
fun start(roots: () -> List<File>, alive: () -> Boolean) {
Thread({
var baseline = 0L
var files = emptyList<File>()
var scanned = 0L
var trims = 0
var failureLogged = false
while (alive()) {
runCatching {
val mem = parse(File("/proc/meminfo").readText())
if (mem != null && shouldTrim(mem, baseline)) {
val now = System.currentTimeMillis()
if (now - scanned > RESCAN_MS) {
files = roots().flatMap { root -> root.walkTopDown().onEnter { !java.nio.file.Files.isSymbolicLink(it.toPath()) }.filter { it.isFile && it.length() >= MIN_FILE_BYTES }.toList() }
scanned = now
}
val began = System.nanoTime()
files.forEach(::drop)
val after = parse(File("/proc/meminfo").readText())
baseline = after?.fileKb ?: mem.fileKb
trims++
Log.i(TAG, "trim #$trims: free ${mem.freeKb / 1024} -> ${after?.freeKb?.div(1024)} MB, file cache ${mem.fileKb / 1024} -> ${after?.fileKb?.div(1024)} MB, ${files.size} files, ${(System.nanoTime() - began) / 1_000_000} ms")
}
}.onFailure {
if (!failureLogged) Log.w(TAG, "trim failed: $it")
failureLogged = true
}
Thread.sleep(POLL_MS)
}
}, "page-cache-trim").apply { isDaemon = true }.start()
}
private fun drop(file: File) {
PageCacheNative.fadviseDontNeed(file.path)
}
}
internal object PageCacheNative {
init {
System.loadLibrary("sdnative")
}
@JvmStatic external fun fadviseDontNeed(path: String): Int
}
@@ -46,7 +46,16 @@ object SecondaryLibrary {
}
fun privateRoot(files: File, library: File): File {
val digest = MessageDigest.getInstance("SHA-256").digest(library.canonicalPath.toByteArray())
val own = privateDir(files, library.canonicalPath)
if (own.exists()) return own
val raw = UsbLink.rawPath(library.absolutePath)
val alias = if (raw != library.absolutePath) raw else UsbLink.storagePath(library.absolutePath)
if (alias == library.absolutePath) return own
return privateDir(files, runCatching { File(alias).canonicalPath }.getOrDefault(alias)).takeIf { it.exists() } ?: own
}
private fun privateDir(files: File, path: String): File {
val digest = MessageDigest.getInstance("SHA-256").digest(path.toByteArray())
.joinToString("") { "%02x".format(it.toInt() and 255) }
return File(files, "steam-libraries/$digest")
}
@@ -16,6 +16,7 @@ object SessionDisplay {
const val LINK_PORTRAIT = "link/portrait"
const val DEFAULT_RESOLUTION = "720p"
const val DEFAULT_STEAM_PORTRAIT_RESOLUTION = "1280x800"
private val PRESET_HEIGHTS = listOf(720, 900, 1080)
fun presetHeight(choice: String): Int? =
@@ -11,6 +11,7 @@ import com.droiddeck.launcher.runtime.DesktopCatalog
import com.droiddeck.launcher.runtime.LegacyNames
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.runtime.ProotFastPath
import org.json.JSONObject
import java.io.File
object SessionFiles {
@@ -21,6 +22,8 @@ object SessionFiles {
private const val NO_PAD_SWITCH = "Download/droiddeck-no-pad"
const val DIRECTAUDIO_DIR = "usr/local/lib/directaudio"
private const val STAGED_LEDGER = "usr/local/.droiddeck-staged"
private const val IME_MANIFEST = "usr/local/share/droiddeck/ime-files.json"
private const val IME_DEFAULT_MODE = 420
val DIRECTAUDIO_SETS = arrayOf("linux-wine11", "linux-wine11-systhread")
internal val DESKTOP_FILES = arrayOf(
@@ -35,6 +38,7 @@ object SessionFiles {
"usr/local/bin/kwin_wayland_wrapper" to "usr/local/bin/kwin_wayland_wrapper",
"usr/lib/firefox/defaults/pref/droiddeck.js" to "usr/lib/firefox/defaults/pref/droiddeck.js",
"etc/xdg/autostart/droiddeck-clipboard.desktop" to "etc/xdg/autostart/droiddeck-clipboard.desktop",
"usr/share/applications/droiddeck-return-gaming.desktop" to "usr/share/applications/droiddeck-return-gaming.desktop",
"etc/xdg/fastfetch/config.jsonc" to "etc/xdg/fastfetch/config.jsonc",
)
@@ -129,7 +133,11 @@ object SessionFiles {
"usr/local/bin/droiddeck-agent" to "usr/local/bin/droiddeck-agent",
"usr/local/bin/steam-compatibility" to "usr/local/bin/steam-compatibility",
"usr/local/bin/droiddeck-clipboard" to "usr/local/bin/droiddeck-clipboard",
"usr/local/bin/droiddeck-spawn" to "usr/local/bin/droiddeck-spawn",
"usr/local/bin/droiddeck-log-writer" to "usr/local/bin/droiddeck-log-writer",
"usr/local/bin/droiddeck-desktop-clipboard" to "usr/local/bin/droiddeck-desktop-clipboard",
"usr/local/bin/droiddeck-text-input" to "usr/local/bin/droiddeck-text-input",
"usr/local/bin/droiddeck-steam-ime" to "usr/local/bin/droiddeck-steam-ime",
"usr/local/bin/droiddeck-gpu-window" to "usr/local/bin/droiddeck-gpu-window",
"usr/local/bin/droiddeck-steam-install" to "usr/local/bin/droiddeck-steam-install",
"usr/local/bin/droiddeck-steam-preapply" to "usr/local/bin/droiddeck-steam-preapply",
@@ -153,6 +161,7 @@ object SessionFiles {
"usr/local/bin/droiddeck-desktop-bookmarks" to "usr/local/bin/droiddeck-desktop-bookmarks",
"usr/local/bin/droiddeck-downloads" to "usr/local/bin/droiddeck-downloads",
"usr/local/bin/droiddeck-root" to "usr/local/bin/droiddeck-root",
"usr/local/bin/droiddeck-user" to "usr/local/bin/droiddeck-user",
"usr/local/bin/droiddeck-text" to "usr/local/bin/droiddeck-text",
"usr/local/bin/droiddeck-snapd" to "usr/local/bin/droiddeck-snapd",
"usr/local/bin/droiddeck-emulators" to "usr/local/bin/droiddeck-emulators",
@@ -336,6 +345,7 @@ object SessionFiles {
if (installed) ledger.staged(key, target) else Log.e(TAG, "DirectAudio $set/$relative NOT staged")
}
for (pack in SERVICE_PACKS.keys) stageStoreService(context, root, pack, ledger)
stageImeFiles(context, root, ledger)
ledger.save()
for (old in arrayOf("aarch64-unix", "aarch64-windows", "i386-windows")) File(root, "$DIRECTAUDIO_DIR/lib/wine/$old").deleteRecursively()
val preload = StringBuilder("/usr/local/lib/libddsession.so\n")
@@ -362,6 +372,7 @@ object SessionFiles {
Log.e(TAG, "could not write steam-compatibility-label")
}
writeCjkFontConfig(root, etc)
writeSessionBusPolicy(etc)
writeDesktopStrings(context, File(etc, "droiddeck").apply { mkdirs() })
val droiddeckEtc = File(etc, "droiddeck").apply { mkdirs() }
val stagedSocket = File(droiddeckEtc, "bwrap-socket.staged")
@@ -421,6 +432,42 @@ object SessionFiles {
seen?.let { SessionPrefs.setBootMovieSteamSeen(context, it) }
}
private fun stageImeFiles(context: Context, root: File, ledger: StageLedger) {
val entries = LinkedHashMap<String, Int>()
try {
val text = context.assets.open("linuxfs/$IME_MANIFEST").bufferedReader().use { it.readText() }
val files = JSONObject(text).getJSONObject("files")
for (name in files.keys()) {
entries[name] = files.optJSONObject(name)?.optString("mode").orEmpty().toIntOrNull(8) ?: IME_DEFAULT_MODE
}
entries[IME_MANIFEST] = IME_DEFAULT_MODE
} catch (e: Exception) {
Log.w(TAG, "the Chinese input payload is not bundled; Steam sessions start without it", e)
return
}
for ((relative, mode) in entries) {
val target = File(root, relative)
if (ledger.current(relative, target)) continue
val staged = File(target.parentFile, target.name + ".staged")
var installed = false
try {
target.parentFile?.mkdirs()
context.assets.open("linuxfs/$relative").use { input ->
staged.outputStream().use { output -> FileUtils.copy(input, output) }
}
installed = staged.setReadable(true, false) &&
staged.setWritable((mode and 0x80) != 0, true) &&
staged.setExecutable((mode and 0x49) != 0, false) &&
staged.renameTo(target)
} catch (e: Exception) {
Log.w(TAG, "could not stage $relative", e)
} finally {
if (!installed) staged.delete()
}
if (installed) ledger.staged(relative, target) else Log.e(TAG, "$relative NOT staged")
}
}
internal fun resetMissingStartupMovie(config: File, force: Boolean): Boolean {
synchronized(STEAM_CONFIG) {
if (!config.isFile) return true
@@ -884,6 +931,24 @@ object SessionFiles {
}
}
/**
* A session bus admits only its owner, and with droiddeck-user (the native hook's ordinary
* user) a root process and a user's share the bus while the kernel sees one Android uid.
*/
private fun writeSessionBusPolicy(etc: File) {
val xml = """<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN"
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
<busconfig>
<policy context="default">
<allow user="*"/>
</policy>
</busconfig>
"""
val conf = File(etc, "dbus-1/session.d/droiddeck-users.conf")
conf.parentFile?.mkdirs()
if (!FileUtils.writeString(conf, xml)) Log.e(TAG, "could not write the session bus policy")
}
private fun writeCjkFontConfig(root: File, etc: File) {
try {
val confDir = File(etc, "fonts/conf.d").apply { mkdirs() }
@@ -63,6 +63,24 @@ object SessionPrefs {
.takeIf { value -> orientationOptions.any { it.first == value } }
?: ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
fun orientation(context: Context, mode: String?): Int {
val key = when (mode) {
"steam", SessionService.MODE_STEAM, SessionService.MODE_RUN -> "orientation.steam"
"desktop", SessionService.MODE_DESKTOP -> "orientation.desktop"
else -> null
} ?: return orientation(context)
val stored = prefs(context).getInt(key, Int.MIN_VALUE)
return if (stored == Int.MIN_VALUE) orientation(context)
else stored.takeIf { value -> orientationOptions.any { it.first == value } } ?: orientation(context)
}
fun setOrientation(context: Context, mode: String, orientation: Int) {
require(mode == "steam" || mode == "desktop")
require(orientationOptions.any { it.first == orientation })
val key = if (mode == "steam") "orientation.steam" else "orientation.desktop"
prefs(context).edit().putInt(key, orientation).apply()
}
/** The session menu's width in dp the user dragged it to; null keeps the default. */
fun drawerWidthDp(context: Context): Int? = prefs(context).getInt("drawerWidthDp", 0).takeIf { it > 0 }
@@ -75,11 +93,19 @@ object SessionPrefs {
prefs(context).edit().putInt("orientation", orientation).apply()
}
fun windowOrientation(context: Context, followScreen: Boolean, smallestWidthDp: Int): Int =
if (followScreen && smallestWidthDp >= SessionDisplay.UNFOLDED_MIN_DP && !prefs(context).contains("orientation"))
fun windowOrientation(context: Context, followScreen: Boolean, smallestWidthDp: Int, mode: String? = null): Int {
val modeKey = when (mode) {
"steam", SessionService.MODE_STEAM, SessionService.MODE_RUN -> "orientation.steam"
"desktop", SessionService.MODE_DESKTOP -> "orientation.desktop"
else -> null
}
val preferences = prefs(context)
if (modeKey != null && preferences.contains(modeKey)) return orientation(context, mode)
return if (followScreen && smallestWidthDp >= SessionDisplay.UNFOLDED_MIN_DP && !preferences.contains("orientation"))
ActivityInfo.SCREEN_ORIENTATION_USER else orientation(context)
}
fun portrait(context: Context): Boolean = when (orientation(context)) {
fun portrait(context: Context, mode: String? = null): Boolean = when (orientation(context, mode)) {
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT -> true
ActivityInfo.SCREEN_ORIENTATION_USER ->
context.resources.configuration.orientation == android.content.res.Configuration.ORIENTATION_PORTRAIT
@@ -92,6 +118,39 @@ object SessionPrefs {
prefs(context).edit().putBoolean("launcherFullscreen", on).apply()
}
fun launcherFrost(context: Context): Boolean = prefs(context).getBoolean("launcherFrost", false)
fun setLauncherFrost(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("launcherFrost", on).apply()
}
fun frostWallpaper(context: Context): Boolean = prefs(context).getBoolean("frostWallpaper", true)
fun setFrostWallpaper(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("frostWallpaper", on).apply()
}
fun frostCards(context: Context): Boolean = prefs(context).getBoolean("frostCards", true)
fun setFrostCards(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("frostCards", on).apply()
}
fun frostTransparency(context: Context): Int = frostPercent(context, "frostTransparency", com.droiddeck.launcher.ui.FROST_WALLPAPER_DEFAULT)
fun setFrostTransparency(context: Context, percent: Int) = setFrostPercent(context, "frostTransparency", percent)
fun frostCardTransparency(context: Context): Int = frostPercent(context, "frostCardTransparency", com.droiddeck.launcher.ui.FROST_DEFAULT)
fun setFrostCardTransparency(context: Context, percent: Int) = setFrostPercent(context, "frostCardTransparency", percent)
private fun frostPercent(context: Context, key: String, default: Int): Int =
prefs(context).getInt(key, default).coerceIn(0, com.droiddeck.launcher.ui.FROST_MAX)
private fun setFrostPercent(context: Context, key: String, percent: Int) {
prefs(context).edit().putInt(key, percent.coerceIn(0, com.droiddeck.launcher.ui.FROST_MAX)).apply()
}
fun controllerHaptics(context: Context): Boolean = prefs(context).getBoolean("controllerHaptics", true)
fun setControllerHaptics(context: Context, on: Boolean) {
@@ -305,13 +364,13 @@ object SessionPrefs {
prefs(context).edit().putInt("libraryCardLevel", level).apply()
}
fun libraryShowTitle(context: Context): Boolean = prefs(context).getBoolean("libraryShowTitle", true)
fun libraryShowTitle(context: Context): Boolean = prefs(context).getBoolean("libraryShowTitle", false)
fun setLibraryShowTitle(context: Context, show: Boolean) {
prefs(context).edit().putBoolean("libraryShowTitle", show).apply()
}
fun libraryShowSize(context: Context): Boolean = prefs(context).getBoolean("libraryShowSize", true)
fun libraryShowSize(context: Context): Boolean = prefs(context).getBoolean("libraryShowSize", false)
fun setLibraryShowSize(context: Context, show: Boolean) {
prefs(context).edit().putBoolean("libraryShowSize", show).apply()
@@ -493,6 +552,17 @@ object SessionPrefs {
prefs(context).edit().putString("drawerPageHidden", keys.joinToString(",")).apply()
}
fun drawerSections(context: Context): Map<String, Boolean> =
idList(prefs(context).getString("drawerSections", null)).mapNotNull { entry ->
val at = entry.lastIndexOf('=').takeIf { it > 0 } ?: return@mapNotNull null
entry.substring(0, at) to (entry.substring(at + 1) == "1")
}.toMap()
fun setDrawerSections(context: Context, sections: Map<String, Boolean>) {
prefs(context).edit().putString("drawerSections", sections.entries.filter { ',' !in it.key }
.joinToString(",") { "${it.key}=${if (it.value) 1 else 0}" }).apply()
}
fun setNavTabHidden(context: Context, keys: Set<String>) {
prefs(context).edit().putString("navTabHidden", keys.joinToString(",")).apply()
}
@@ -876,13 +946,21 @@ object SessionPrefs {
}
fun picturePosition(context: Context): String =
prefs(context).getString("picturePosition", "center")
?.takeIf { it in listOf("top", "bottom", "left", "right", "center") } ?: "center"
private val picturePositions = setOf("center", "top", "bottom", "left", "right")
fun setPicturePosition(context: Context, position: String) {
prefs(context).edit().putString("picturePosition",
position.takeIf { it in listOf("top", "bottom", "left", "right", "center") } ?: "center").apply()
private fun picturePositionKey(portrait: Boolean) =
if (portrait) "picturePosition.portrait" else "picturePosition.landscape"
fun picturePosition(context: Context, portrait: Boolean): String {
val preferences = prefs(context)
return preferences.getString(picturePositionKey(portrait), null)?.takeIf { it in picturePositions }
?: preferences.getString("picturePosition", null)?.takeIf { it in picturePositions }
?: if (portrait) "top" else "center"
}
fun setPicturePosition(context: Context, portrait: Boolean, position: String) {
require(position in picturePositions)
prefs(context).edit().putString(picturePositionKey(portrait), position).apply()
}
fun integerScaling(context: Context): Boolean =
@@ -1100,10 +1178,20 @@ object SessionPrefs {
fun nativeUserland(context: Context): Boolean = prefs(context).getBoolean("nativeUserland", true)
/** The session's long-lived programs run in worker processes Android does not count (GuestWorkers). */
fun childProcessHandoff(context: Context): Boolean = prefs(context).getBoolean("childProcessHandoff", true)
fun setNativeUserland(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("nativeUserland", on).apply()
}
/** Whether the Plasma desktop, and so its apps and shells, runs as an ordinary user instead of root (native userland only). */
fun desktopAsUser(context: Context): Boolean = prefs(context).getBoolean("desktopAsUser", false)
fun setDesktopAsUser(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("desktopAsUser", on).apply()
}
fun prootFastPath(context: Context): Boolean = prefs(context).getBoolean("prootFastPath", true)
fun setProotFastPath(context: Context, on: Boolean) {
@@ -1433,10 +1521,12 @@ object SessionPrefs {
fun resolutionStored(context: Context, mode: String, panel: Pair<Int, Int>, portrait: Boolean): String {
if (!portrait) return landscapeResolutionStored(context, mode, panel)
val value = prefs(context).getString("displayResolution.portrait.$mode", null) ?: return SessionDisplay.LINK_LANDSCAPE
val fallback = if (mode == SessionService.MODE_STEAM) SessionDisplay.DEFAULT_STEAM_PORTRAIT_RESOLUTION
else SessionDisplay.LINK_LANDSCAPE
val value = prefs(context).getString("displayResolution.portrait.$mode", null) ?: return fallback
if (value == SessionDisplay.LINK_LANDSCAPE || value == SessionDisplay.MATCH_SCREEN || SessionDisplay.isFollow(value) ||
SessionDisplay.presetHeight(value) != null) return value
return parseOrientedResolution(value)?.let { "${it.first}x${it.second}" } ?: SessionDisplay.LINK_LANDSCAPE
return parseOrientedResolution(value)?.let { "${it.first}x${it.second}" } ?: fallback
}
fun parseOrientedResolution(text: String): Pair<Int, Int>? =
@@ -1698,6 +1788,9 @@ object SessionPrefs {
name.removeSuffix(from) + to to moved
}
fun storedAddedGameAppId(context: Context, folderPath: String): Long? =
prefs(context).getLong("addedAppId:$folderPath", 0L).takeIf { it != 0L }
fun addedGameAppId(context: Context, folderPath: String, first: Long): Long = synchronized(addedGameLock) {
val p = prefs(context)
p.getLong("addedAppId:$folderPath", 0L).takeIf { it != 0L }
@@ -1794,10 +1887,17 @@ object SessionPrefs {
prefs(context).edit().putBoolean(hdrKey(mode), on).apply()
}
fun zeroCopy(context: Context, mode: String): Boolean = prefs(context).getBoolean("zeroCopy.$mode", true)
/** Restart-scoped opt-in; not inferred from Zero-copy (which defaults on). */
fun producerAcquireFences(context: Context): Boolean = prefs(context).getBoolean("producerAcquireFences", false)
fun setProducerAcquireFences(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("producerAcquireFences", on).apply()
}
fun zeroCopy(context: Context, mode: String): Boolean = prefs(context).getBoolean("zeroCopy.${prefMode(mode)}", true)
fun setZeroCopy(context: Context, mode: String, on: Boolean) {
prefs(context).edit().putBoolean("zeroCopy.$mode", on).apply()
prefs(context).edit().putBoolean("zeroCopy.${prefMode(mode)}", on).apply()
}
const val FPS_UNPACED = -1
@@ -1807,16 +1907,15 @@ object SessionPrefs {
const val PIP_FPS = 30
fun compositorFpsLimit(mirrorRefreshLimit: Int, sessionLimit: Int = 0, pip: Boolean = false): Int {
val limit = when {
mirrorRefreshLimit <= 0 && sessionLimit <= 0 -> FPS_UNPACED
mirrorRefreshLimit <= 0 -> sessionLimit
sessionLimit <= 0 -> mirrorRefreshLimit
else -> minOf(mirrorRefreshLimit, sessionLimit)
}
fun compositorFpsLimit(mirrorRefreshLimit: Int, sessionLimit: Int = 0, pip: Boolean = false, hostCap: Int = 0): Int {
val limit = listOf(mirrorRefreshLimit, sessionLimit, hostCap).filter { it > 0 }.minOrNull() ?: FPS_UNPACED
return if (pip && mirrorRefreshLimit <= 0 && (limit <= 0 || limit > PIP_FPS)) PIP_FPS else limit
}
/** The per-app rate Android holds this window to (Game Mode's FPS override), or 0 when the panel's rate applies. */
fun hostFrameCap(overrideHz: Float, panelHz: Float): Int =
if (overrideHz > 1f && panelHz - overrideHz > 1f) Math.round(overrideHz) else 0
val upscalerChoices = listOf(
2 to "Nearest", 0 to "Linear", 4 to "AMD FSR 1", 3 to "Snapdragon GSR",
8 to "Snapdragon GSR (quality)", 7 to "NVIDIA NIS", 6 to "Sharpen only",
@@ -2117,6 +2216,12 @@ object SessionPrefs {
(resolutionChosen(context, SessionService.MODE_DESKTOP) || resolutionChosen(context, SessionService.MODE_DESKTOP, true))) SessionService.MODE_DESKTOP
else prefMode(mode)
fun showGlassesShortcut(context: Context): Boolean = prefs(context).getBoolean("showGlassesShortcut", true)
fun setShowGlassesShortcut(context: Context, show: Boolean) {
prefs(context).edit().putBoolean("showGlassesShortcut", show).apply()
}
fun pipAutoEnter(context: Context): Boolean = prefs(context).getBoolean("pipAutoEnter", true)
fun setPipAutoEnter(context: Context, enabled: Boolean) {
@@ -394,8 +394,10 @@ class SessionService : Service() {
SessionState.program = intent?.getStringExtra(EXTRA_PROGRAM)
SessionState.programArgs = intent?.getStringArrayExtra(EXTRA_PROGRAM_ARGS)?.toList().orEmpty()
SessionState.steamUi = intent?.getStringExtra(EXTRA_STEAM_UI)
SessionState.steamUrl = intent?.getStringExtra(EXTRA_STEAM_URL)
val steamUrlGameId = SessionState.steamUrl
val launchSteamUrl = intent?.getStringExtra(EXTRA_STEAM_URL)
val frontendSteamGame = intent?.getBooleanExtra(EXTRA_FRONTEND_STEAM_GAME, false) == true
SessionState.steamUrl = launchSteamUrl
val steamUrlGameId = launchSteamUrl
?.let { url ->
when {
url.startsWith(GAME_URL_PREFIX) ->
@@ -426,6 +428,11 @@ class SessionService : Service() {
++sessionGen
}
}
val trimGen = gen
PageCacheTrim.start(
roots = { listOfNotNull(File(filesDir, "linuxfs"), GameStorage.effective(applicationContext)?.let { File(it.path) }).filter(File::isDirectory) },
alive = { SessionState.running && sessionGen == trimGen },
)
if (SessionState.stopRequested) {
stopSession(0)
return START_NOT_STICKY
@@ -447,7 +454,7 @@ class SessionService : Service() {
Thread({
OrphanReaper.reap("session starting")
ProtonExtras.awaitReplacement(120_000)
runSession(gen)
runSession(gen, launchSteamUrl, frontendSteamGame)
}, "session-start").start()
return START_NOT_STICKY
}
@@ -500,7 +507,7 @@ class SessionService : Service() {
}
private fun runSession(gen: Int) {
private fun runSession(gen: Int, launchSteamUrl: String?, frontendSteamGame: Boolean) {
SessionPrefs.ensurePowerVrAutoDriversAfterGpuQuery(this)
if (!com.droiddeck.launcher.core.DeviceSupport.adreno()) {
com.droiddeck.launcher.gpu.VulkanInfo.query()["api"]?.let { SessionPrefs.setHostVulkanApi(this, it) }
@@ -555,9 +562,10 @@ class SessionService : Service() {
return
}
}
val agentEnvironment = runCatching { com.droiddeck.launcher.agent.AgentEnv.beginSession(this) }
val nextAgentEnvironment = runCatching { com.droiddeck.launcher.agent.AgentEnv.beginSession(this) }
.onFailure { Log.w(TAG, "agent environment skipped", it) }
.getOrDefault(emptyList())
val agentEnvironment = nextAgentEnvironment.getOrDefault(emptyList())
val customEnvironment = extraEnv()
try {
if (systemVulkan) {
SystemVulkanDriver.prepare(this)
@@ -614,6 +622,9 @@ class SessionService : Service() {
val size = SessionState.outputSize
val guest = ArrayList<String>()
val steamHere = SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP
runCatching { SessionEvents.step("components-xbox") { XboxBackCompatComponents.ensure(this) } }
.onSuccess { if (it != null) Log.i(TAG, it) }
.onFailure { Log.w(TAG, "original Xbox components", it) }
runCatching { SessionEvents.step("components-republish") { ComponentsManager.republish(this) } }
.onSuccess { if (it) Log.i(TAG, "component selections published for the installed Proton builds") }
.onFailure { Log.w(TAG, "component selections", it) }
@@ -623,7 +634,7 @@ class SessionService : Service() {
.onFailure { Log.w(TAG, "forced components", it) }
}
try {
SessionEvents.step("client-environment") { addClientEnvironment(guest, steamHere, agentEnvironment) }
SessionEvents.step("client-environment") { addClientEnvironment(guest, steamHere, agentEnvironment, customEnvironment) }
} catch (e: IllegalStateException) {
Log.e(TAG, "Could not resolve the selected Linux Vulkan driver", e)
failSession(gen, "VULKAN_DRIVER_UNAVAILABLE", e.message ?: "Selected Linux Vulkan driver is unavailable", -1)
@@ -661,7 +672,7 @@ class SessionService : Service() {
Log.i(TAG, "game resolution: ${w}x$h on a ${size.first}x${size.second} output")
}
if (SessionState.followScreen || size.first < size.second ||
SessionPrefs.orientation(this) == android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER)
SessionPrefs.orientation(this, SessionState.mode) == android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER)
guest.add("DD_FOLLOW_OUTPUT=1")
if (SessionState.hdr) {
guest.add("DD_HDR=1")
@@ -705,10 +716,38 @@ class SessionService : Service() {
if (com.droiddeck.launcher.gpu.Lossless.owned(this)) guest.add("DD_LOSSLESS_OWNED=1")
}
guest.add("DD_LAUNCH_DIR=" + sessionRoot.path)
// this session's worker number: the shared field may be a newer session's by the time it is used
var ownWorkers = 0
if (com.droiddeck.launcher.runtime.GuestWorkers.enabled(this)) {
val fenceWorker = com.droiddeck.launcher.runtime.FrameAcquireWorkerProbe
val preparedFence = if (steamHere && !systemVulkan && !VenusComponent.wanted(this) &&
SessionPrefs.zeroCopy(this, MODE_STEAM) && SessionPrefs.producerAcquireFences(this) &&
nextAgentEnvironment.isSuccess && fenceWorker.validEnvironment(agentEnvironment, customEnvironment)
) fenceWorker.prepare(this, launchSteamUrl, frontendSteamGame) else null
var fenceArmed = false
// Under the lock a stop takes its number with: a stop either comes first (and this session
// starts no workers) or owns them
ownWorkers = synchronized(stopLock) {
if (gen != sessionGen || !SessionState.running) 0
else com.droiddeck.launcher.runtime.GuestWorkers.serve(this).also {
guestWorkerSession = it
if (preparedFence != null) fenceArmed = fenceWorker.arm(it, preparedFence)
}
}
if (ownWorkers > 0) {
guest.add("DD_SPAWN=" + com.droiddeck.launcher.runtime.GuestWorkers.socketName(this))
guest.add("DD_SPAWN_SESSION=$ownWorkers")
if (fenceArmed) {
guest.add(fenceWorker.GAMESCOPE_ENABLE)
guest.add(fenceWorker.GAME_ENABLE)
}
}
}
// Proton builds up to 11.12 report X11 text fields under this name.
guest.add("BL_LAUNCH_DIR=" + sessionRoot.path)
GameStorage.effective(this)?.let { guest.add("DD_LIBRARY_LABEL=" + it.label.replace('"', ' ')) }
if (SessionState.mode == MODE_STEAM && SessionState.steamUi == "desktop") guest.add("DD_STEAM_UI=desktop")
if (SessionPrefs.desktopAsUser(this)) guest.add("DD_DESKTOP_USER=1")
// Detailed graphics logs: per-game logs and the guest's Vulkan summary (a GPU that is not
// an Adreno, or Setup's switch), and graphics-report.txt for every session.
if (GraphicsReport.detailed(this)) guest.add("DD_GAME_LOGS=1")
@@ -723,7 +762,7 @@ class SessionService : Service() {
val desktopGuest = ArrayList(guest)
guest.add(LinuxRuntime.SESSION_SCRIPT)
guest.add(SessionState.mode)
if (SessionState.mode == MODE_STEAM) SessionState.steamUrl?.takeIf { it.startsWith("steam://") }?.let {
if (SessionState.mode == MODE_STEAM) launchSteamUrl?.takeIf { it.startsWith("steam://") }?.let {
guest.add(it)
Log.i(TAG, "steam: handing the client $it")
}
@@ -863,10 +902,10 @@ class SessionService : Service() {
watchLaunchRequests(sessionRoot)
watchSyncWanted(root)
EsyncPacks.fetchInBackground(this, root)
val pid = SessionEvents.step("guest-launch") { HostProcess.start(line, hostEnv.asArray(), root, { status ->
val pid = SessionEvents.step("guest-launch") { HostProcess.startUncounted(line, hostEnv.asArray(), root, { status ->
if (gen != sessionGen) {
Log.i(TAG, "an earlier session's process ended ($status); the current one carries on")
return@start
return@startUncounted
}
val program = programStatus(sessionRoot)
Log.i(TAG, "session ended: $status" + if (program != null) " (program $program)" else "")
@@ -882,10 +921,19 @@ class SessionService : Service() {
syncWatcher = null
}
abandonStart(gen, sessionDir, started)
if (pid > 1) Thread({ teardown(pid) }, "session-teardown").start()
val workers = ownWorkers
if (pid > 1) Thread({ teardown(pid, workerSession = workers) }, "session-teardown").start()
else com.droiddeck.launcher.runtime.GuestWorkers.stopGuests(workers)
return
}
sessionPid = pid
// Under the lock Stop clears it with, and only while this session still runs: a Stop since the
// check above has cleared it already, and this would set it again for no running session.
val uncounted = com.droiddeck.launcher.runtime.GuestWorkers.runsInWorker(pid)
synchronized(stopLock) {
if (gen == sessionGen && SessionState.running)
com.droiddeck.launcher.runtime.GuestWorkers.sessionRootUncounted = uncounted
}
if (pid > 1) {
raiseTracer(pid, gen)
SessionEvents.guestStarted(pid)
@@ -993,7 +1041,8 @@ class SessionService : Service() {
return com.droiddeck.launcher.input.GesturePrefs.read(this, game).relativeMouseMode
}
private fun addClientEnvironment(guest: MutableList<String>, steamHere: Boolean, agentEnvironment: List<String>) {
private fun addClientEnvironment(guest: MutableList<String>, steamHere: Boolean,
agentEnvironment: List<String>, customEnvironment: List<String>) {
guest.add("/usr/bin/env")
guest.add("-i")
guest.add("DROIDDECK_BWRAP_SOCKET=" + com.droiddeck.launcher.runtime.BwrapSpawner.socket(this))
@@ -1113,7 +1162,7 @@ class SessionService : Service() {
guest.add("DD_ZRAM=1")
}
guest.add("AUDIO_DIRECT_DECAY=0")
val extra = extraEnv() + agentEnvironment
val extra = customEnvironment + agentEnvironment
guest.addAll(TurnipEnvironment.gameEnvironment(tuOverride, tuDriver, SessionPrefs.tuSysmem(this), extra))
if (extra.none { it.startsWith("MESA_NO_ERROR=") }) guest.add("${GAME_PREFIX}MESA_NO_ERROR=")
extra.forEach { guest.add(it) }
@@ -1537,10 +1586,15 @@ class SessionService : Service() {
return binds
}
private fun teardown(prootPid: Int, expectedStartTime: Long? = null) {
// The workers' session number of the session running now (GuestWorkers.serve)
@Volatile private var guestWorkerSession = 0
private fun teardown(prootPid: Int, expectedStartTime: Long? = null, workerSession: Int = guestWorkerSession) {
fun stillSameProcess(): Boolean = expectedStartTime == null || readStat(prootPid)?.second == expectedStartTime
if (!stillSameProcess()) return
val tree = descendants(prootPid)
// The session's programs that run in worker processes are not descendants of its root.
val workers = if (expectedStartTime == null) com.droiddeck.launcher.runtime.GuestWorkers.guestPids(workerSession) else emptyList()
val tree = descendants(prootPid) + workers.flatMap { pid -> listOfNotNull(readStat(pid)?.let { Pair(pid, it.second) }) + descendants(pid) }
if (!stillSameProcess()) return
saveWineRegistries(tree)
android.os.Process.sendSignal(prootPid, 15)
@@ -1557,6 +1611,7 @@ class SessionService : Service() {
killed++
}
if (killed > 0) Log.i(TAG, "swept $killed process(es) proot left behind")
if (expectedStartTime == null) com.droiddeck.launcher.runtime.GuestWorkers.stopGuests(workerSession)
}
private fun clearCachedApps() {
@@ -1731,6 +1786,7 @@ class SessionService : Service() {
SessionEvents.record("steam.game_launch_requested", mapOf("gameId" to gameId, "generation" to gen))
watchGameExit(gameId, gen, exitWatchToken, pendingSteamPreviousGameId)
Log.i(TAG, "queued Steam game $gameId for the running client")
com.droiddeck.launcher.runtime.GuestWorkers.expectLaunch(this)
}
private fun watchGameExit(
@@ -2327,12 +2383,16 @@ class SessionService : Service() {
return
}
completeNativeSleep()
var workers = 0
val (ended, endedArch) = synchronized(stopLock) {
if (gen != null && gen != sessionGen) return
// as it is when running is cleared: startup registers its workers under this lock too
workers = guestWorkerSession
cancelQueuedSteamGame()
gameExitWatchToken++
// also when startup stopped before the guest ran
com.droiddeck.launcher.runtime.NativeGuest.sessionMode = null
com.droiddeck.launcher.runtime.GuestWorkers.sessionRootUncounted = null
if (!SessionState.running) return
if (relaunch) SessionState.confirmRelaunchStop()
SessionEvents.record("guest.exited", mapOf("status" to status))
@@ -2393,7 +2453,8 @@ class SessionService : Service() {
if (prootPid > 1 && steamClientMayRun) askSteamToExit(prootPid)
com.droiddeck.launcher.stores.gog.GogComet.end(stoppedSession)
auxiliary.forEach { (pid, started) -> teardown(pid, started) }
if (prootPid > 1) teardown(prootPid)
if (prootPid > 1) teardown(prootPid, workerSession = workers)
else com.droiddeck.launcher.runtime.GuestWorkers.stopGuests(workers)
killGuestLeftovers(ended)
pruneSystemVulkanRuntime()
finishSessionStop(status, stoppedGen, collectEnded)
@@ -2402,6 +2463,7 @@ class SessionService : Service() {
} else {
Thread({ pruneSystemVulkanRuntime() }, "system-vulkan-prune").start()
Thread({
com.droiddeck.launcher.runtime.GuestWorkers.stopGuests(workers)
com.droiddeck.launcher.stores.gog.GogComet.end(stoppedSession)
finishSessionStop(status, stoppedGen, collectEnded)
if (launcherEnded) importLauncherGames()
@@ -2720,6 +2782,9 @@ class SessionService : Service() {
const val EXTRA_PROGRAM_ARGS = "programArgs"
const val EXTRA_STEAM_UI = "steamUi"
const val EXTRA_STEAM_URL = "steamUrl"
// Set by the first-party Library play action on the private SessionActivity/Service path.
// Never copied from an exported intent or Agent command.
internal const val EXTRA_FRONTEND_STEAM_GAME = "com.droiddeck.launcher.FRONTEND_STEAM_GAME"
const val EXTRA_GAME_ID = "gameId"
fun start(
@@ -2727,6 +2792,7 @@ class SessionService : Service() {
steamUi: String? = null, steamUrl: String? = null, programArgs: Array<String>? = null,
gameId: String? = null,
displayId: Int = Display.DEFAULT_DISPLAY,
frontendSteamGame: Boolean = false,
) {
SteamClientPrefetch.cancel()
SessionState.activityDisplayId = displayId
@@ -2737,6 +2803,7 @@ class SessionService : Service() {
if (programArgs != null) intent.putExtra(EXTRA_PROGRAM_ARGS, programArgs)
if (steamUi != null) intent.putExtra(EXTRA_STEAM_UI, steamUi)
if (steamUrl != null) intent.putExtra(EXTRA_STEAM_URL, steamUrl)
if (frontendSteamGame) intent.putExtra(EXTRA_FRONTEND_STEAM_GAME, true)
if (gameId != null) intent.putExtra(EXTRA_GAME_ID, gameId)
if (Build.VERSION.SDK_INT >= 26) context.startForegroundService(intent)
else context.startService(intent)
@@ -12,15 +12,15 @@ object SettingsReset {
private const val TAG = "SettingsReset"
internal val SESSION_KEYS = setOf(
"orientation", "launcherFullscreen", "controllerHaptics", "animations", "lowStorageWarning", "theme", "runSteamAtStartup", "startupSession", "addedGamesArt",
"orientation", "launcherFullscreen", "launcherFrost", "frostWallpaper", "frostCards", "frostTransparency", "frostCardTransparency", "controllerHaptics", "animations", "lowStorageWarning", "theme", "runSteamAtStartup", "startupSession", "addedGamesArt",
"drawerWidthDp", "dualScreenMode", "dualScreenSessionMode", "dualScreenLauncher", "dualScreenSessionControls", "androidTextFieldKeyboard",
"soundtracksIngame", "gameStoresSpeedTier", "gameStoresParallel", "storesOpenTab", "storesShowMature",
"storesInstallLanguage",
"hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "__KEEP_droidDeckHud__", "__KEEP_droidDeckHudPos__", "backHold", "dockedMenuController", "backActionsInverted", "backDoubleTapMs", "touch", "pen", "penButton", "osc", "shape", "steamController",
"gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "unfoldedControlsWithController",
"stretch16x9", "avoidNotch", "picturePosition", "integerScaling", "railLabels", "developerTools", "navTabOrder", "navTabShelved", "navTabHidden", "drawerPageOrder", "drawerPageHidden", "pcKeyboardSize", "pcKeyboardOpacity", "pcKeyboardHiddenKeys",
"stretch16x9", "avoidNotch", "picturePosition", "picturePosition.portrait", "picturePosition.landscape", "integerScaling", "railLabels", "developerTools", "navTabOrder", "navTabShelved", "navTabHidden", "drawerPageOrder", "drawerPageHidden", "drawerSections", "pcKeyboardSize", "pcKeyboardOpacity", "pcKeyboardHiddenKeys",
"gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop",
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "paceCores",
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "producerAcquireFences", "paceCores",
"directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus",
"noXalia", "fastSync", "fsyncFirst", "syncFallback", "prootNoSeccomp", "prootFastPath", "nativeUserland", "cursorComposite", "mountSharedStorage",
"guestHostname", "fexPreset", "forceSsbs", "logs", "gameDebugLogsEnabled", "enhancedDiagnosticsNext", "storageDiagnostics", "buildWatermark",
@@ -10,9 +10,23 @@ import java.io.File
// browser view placed outside the Big Picture window, composition capped at "notification" so gamescope keeps the game
// focused, and gamepad focus on the main UI. The hold is a lease the app renews, so Steam recovers if the app goes away.
object SteamQam {
data class Target(val port: Int, val path: String)
/** [mainPath] is Steam's main menu page, shown beside the quick access menu in the split layout. */
data class Target(val port: Int, val path: String, val mainPath: String? = null)
const val MAIN_MENU = 1
const val QUICK_ACCESS = 2
/** Height in CSS pixels both menus are laid out at in the split layout, so they show at one scale. */
const val SPLIT_CSS_HEIGHT = 480
/** Steam's own width for the main menu; quick access takes the rest of the panel. */
const val MAIN_CSS_WIDTH = 240
/** Holds the parked main menu in place and spreads its item rows (not dividers) over the full height, at most 80 px each. */
private const val MAIN_PARKED_CSS =
".BasicUI > .Panel { transform: none !important; width: 100% !important; height: 100% !important; margin: 0 !important; } " +
".BasicUI > .Panel > :has(> .Focusable) { flex: 1 1 0 !important; height: auto !important; max-height: 80px; } " +
".BasicUI > .Panel > :has(> .Focusable) > .Panel { height: 100% !important; }"
const val LEASE_MS = 5_000
private const val TAG = "SteamQam"
private const val EVAL_MS = 6_000L
@@ -26,21 +40,54 @@ object SteamQam {
* Takes or renews the lease for [owner], or releases it. A live lease held by a newer panel is never taken back by an
* older one, so a late request from a panel being torn down cannot end its replacement's lease or change its layout.
*/
internal fun leaseScript(on: Boolean, owner: Long, aspect: Float = 0f): String =
internal fun leaseScript(on: Boolean, owner: Long, aspect: Float = 0f, split: Boolean = false): String =
if (on) "if (!(g.__ddQamUntil > Date.now()) || !(g.__ddQamOwner > $owner)) { g.__ddQamOwner = $owner; g.__ddQamUntil = Date.now() + $LEASE_MS;" +
(if (aspect > 0f) " g.__ddQamAspect = $aspect;" else "") + " }"
(if (aspect > 0f) " g.__ddQamAspect = $aspect;" else "") + " g.__ddQamSplit = $split; }"
else "if (g.__ddQamOwner === $owner) g.__ddQamUntil = 0;"
/** [aspect] is the panel's width over height: the menu is laid out at that shape so every tab shows at one scale. */
internal fun script(on: Boolean, aspect: Float = 0f, owner: Long = 0): String = """(() => {
const g = globalThis, QAM = 2;
/**
* [aspect] is the panel's width over height: the menu is laid out at that shape so every tab shows at one scale. With
* [split], Steam's main menu is kept rendered at its own width beside the quick access menu, which gets the rest.
*/
internal fun script(on: Boolean, aspect: Float = 0f, owner: Long = 0, split: Boolean = false): String = """(() => {
const g = globalThis, QAM = 2, MAIN = 1;
const W = SteamUIStore.WindowStore.SteamUIWindows[0];
const m = W.MenuStore, c = W.m_CompositionStateStore;
const nav = W.m_FocusNavContext;
const popup = g_PopupManager.GetExistingPopup("SP BPM_uid0");
const held = () => g.__ddQamUntil > Date.now();
const ours = () => held() && m.m_eOpenSideMenu === QAM && !g.__ddQamTop;
const split = () => held() && g.__ddQamSplit === true;
// Steam's views carry no names: the main menu's is the one Steam focuses while the main menu is open. Until Steam
// has shown it, the main menu is opened once with its view parked like the quick access menu's.
const probing = () => g.__ddMainProbe > Date.now();
const ours = () => held() && !g.__ddQamTop && (m.m_eOpenSideMenu === QAM || (probing() && m.m_eOpenSideMenu === MAIN));
const width = (h) => g.__ddQamAspect > 0 ? Math.round(h * g.__ddQamAspect) : 0;
const parkX = () => popup.m_popup.innerWidth + 64;
const mainSize = () => [$MAIN_CSS_WIDTH, $SPLIT_CSS_HEIGHT];
const qamSplitSize = () => [Math.max(Math.round($SPLIT_CSS_HEIGHT * (g.__ddQamAspect > 0 ? g.__ddQamAspect : 1)) - $MAIN_CSS_WIDTH, 320), $SPLIT_CSS_HEIGHT];
const size = (w, h) => split() ? qamSplitSize() : [width(h) || w, h];
const mainView = () => views().find(v => v.__ddMain);
// Only the quick access view is parked: the one Steam focuses while quick access is open. Before Steam has
// focused it, any view but the main menu's and the header's web page (Store and other pages) may be it.
const headerView = () => W.m_HeaderStore?.m_currentBrowserAndBackstack?.m_browserView;
const isQam = (v) => !v.__ddMain && v !== headerView() &&
(!!v.__ddQamView || !views().some(o => o.__ddQamView) || (probing() && m.m_eOpenSideMenu === MAIN));
const mainParked = () => split() && (m.m_eOpenSideMenu !== MAIN || probing());
const mainDoc = () => {
for (const s of SteamUIStore.m_GamepadNavigationManager?.m_rgGamepadInputSources || []) {
try { const d = s.m_targetWindow?.document; if (d?.title?.startsWith("MainMenu")) return d; } catch (e) {}
}
return null;
};
// Steam slides the main menu out whenever it is not the open side menu; parked, it stays in place and fills its view.
const mainStyle = (on) => {
const d = mainDoc();
let s = d?.getElementById("dd-main-split");
if (!on) { s?.remove(); return; }
if (!d?.head) return;
if (!s) { s = d.createElement("style"); s.id = "dd-main-split"; d.head.appendChild(s); }
if (s.textContent !== "$MAIN_PARKED_CSS") s.textContent = "$MAIN_PARKED_CSS";
};
if (!c.__ddQam) {
c.__ddQam = c.ComputeOverallMinimumRequestedComposition;
m.__ddQam = m.OnMenuDeactivated;
@@ -59,6 +106,18 @@ object SteamQam {
return without >= 2 ? v : 1;
};
}
// Steam frosts its Store page while a side menu is open; a parked menu is not over it.
const inst = m.m_Instance;
if (inst?.SetStoreBrowserGlass && !inst.__ddQamGlass) {
inst.__ddQamGlass = inst.SetStoreBrowserGlass;
inst.SetStoreBrowserGlass = function (e) { return inst.__ddQamGlass.call(this, ours() ? 0 : e); };
}
const glass = () => {
const on = !ours() && m.m_eOpenSideMenu !== 0;
if (g.__ddQamGlassOn === on) return;
g.__ddQamGlassOn = on;
inst?.SetStoreBrowserGlass?.(m.m_eOpenSideMenu);
};
const views = () => popup?.m_rgChildBrowserViews || [];
const backdrop = (hide) => {
const doc = popup?.m_popup?.document;
@@ -75,16 +134,61 @@ object SteamQam {
};
const keep = () => {
for (const v of views()) {
if (v.__ddQam) continue;
v.__ddQam = v.SetBounds;
if (!v.__ddQam) v.__ddQam = v.SetBounds;
if (v.__ddQamW === 4) continue;
v.__ddQamW = 4;
v.__ddQamVis = v.__ddQamVis || v.SetVisible;
v.__ddQamFocus = v.__ddQamFocus || v.SetFocus;
v.SetBounds = function (x, y, w, h, ...r) {
if (v.__ddMain && mainParked()) {
if (w > 0) v.__ddMainAsked = [x, y, w, h];
[w, h] = mainSize();
v.__ddMainOn = true; v.__ddMainW = w; v.__ddMainH = h;
return v.__ddQam.call(this, parkX(), 0, w, h, ...r);
}
if (v.__ddMain && w > 0) mainStyle(false);
v.__ddAsked = [x, y, w, h];
if (w > 0 && ours()) { x = popup.m_popup.innerWidth + 64; w = width(h) || w; }
if (w > 0 && ours() && isQam(v)) { x = parkX(); [w, h] = size(w, h); }
v.__ddAt = x;
v.__ddW = w;
v.__ddH = h;
return v.__ddQam.call(this, x, y, w, h, ...r);
};
v.SetVisible = function (on, ...r) {
return v.__ddQamVis.call(this, on || (!!v.__ddMain && mainParked()), ...r);
};
v.SetFocus = function (on, ...r) {
if (on && m.m_eOpenSideMenu === MAIN && v !== headerView()) {
for (const o of views()) if (o !== v) delete o.__ddMain;
v.__ddMain = true;
delete v.__ddQamView;
}
if (on && m.m_eOpenSideMenu === QAM && !v.__ddMain && v !== headerView()) {
for (const o of views()) if (o !== v) delete o.__ddQamView;
v.__ddQamView = true;
}
return v.__ddQamFocus.call(this, on, ...r);
};
}
if (g.__ddMainProbe && !probing()) { g.__ddMainProbe = 0; g.__ddMainProbed = true; }
if (probing() && mainView()) { g.__ddMainProbe = 0; g.__ddMainProbed = true; }
const mv = mainView();
if (mv && !probing()) {
if (mainParked()) {
const [w, h] = mainSize();
if (!mv.__ddMainOn || mv.__ddMainW !== w || mv.__ddMainH !== h) {
mv.__ddQam.call(mv, parkX(), 0, w, h);
mv.__ddQamVis.call(mv, true);
mv.__ddMainOn = true; mv.__ddMainW = w; mv.__ddMainH = h;
}
} else if (mv.__ddMainOn) {
mv.__ddMainOn = false;
if (m.m_eOpenSideMenu !== MAIN) { mv.__ddQamVis.call(mv, false); mv.__ddQam.call(mv, 0, 0, 0, 0); }
else if (mv.__ddMainAsked) mv.__ddQam.call(mv, ...mv.__ddMainAsked);
}
}
mainStyle(!!mv && mainParked() && !probing());
glass();
if (!held()) {
const parked = !g.__ddQamTop;
g.__ddQamTop = false;
@@ -124,6 +228,25 @@ object SteamQam {
}
g.__ddQamTop = false;
}
// Each Split activation gets a fresh probe budget, and a spent one refills after a backoff, so a Steam that was
// still loading does not leave the main menu undiscovered for good.
if (split() !== !!g.__ddQamSplitOn) { g.__ddQamSplitOn = split(); if (split()) g.__ddMainProbes = 0; }
if (split() && !mv) {
if (probing()) return;
if ((g.__ddMainProbes || 0) >= 3 && Date.now() - (g.__ddMainProbeLast || 0) > 30000) g.__ddMainProbes = 0;
if ((g.__ddMainProbes || 0) < 3 && m.m_eOpenSideMenu !== MAIN) {
g.__ddMainProbes = (g.__ddMainProbes || 0) + 1;
g.__ddMainProbeLast = Date.now();
g.__ddMainProbe = Date.now() + 1500;
m.OpenMainMenu();
c.EnsureCorrectComposition?.();
return;
}
}
if (g.__ddMainProbed) {
g.__ddMainProbed = false;
if (m.m_eOpenSideMenu === MAIN) m.OpenQuickAccessMenu(g.__ddQamTab ?? undefined);
}
const decky = !!g.DeckyPluginLoader?.tabsHook?.qamBrowserViewPatch;
// Decky hooks the menu after Steam starts; the menu has to unmount for its tab to appear, so reopen on the next tick.
if (m.m_eOpenSideMenu === QAM && decky && !g.__ddQamDecky) { g.__ddQamDecky = true; m.CloseSideMenus(); return; }
@@ -136,18 +259,26 @@ object SteamQam {
if (m.m_eQuickAccessTab != null) g.__ddQamTab = m.m_eQuickAccessTab;
if (!g.__ddQamOn) { g.__ddQamOn = true; c.EnsureCorrectComposition?.(); }
for (const v of views()) {
if (v.__ddMain) continue;
if (!isQam(v)) {
// A view parked before the quick access view was known goes back where Steam asked for it.
const a = v.__ddAsked;
if (a?.[2] > 0 && v.__ddAt >= popup.m_popup.innerWidth) { v.__ddQam.call(v, ...a); v.__ddAt = a[0]; v.__ddW = a[2]; v.__ddH = a[3]; }
continue;
}
if (!v.__ddAsked) {
const b = v.GetBounds?.();
if (b && b.width > 0) { v.__ddAsked = [b.x, b.y, b.width, b.height]; v.__ddAt = b.x; v.__ddW = b.width; }
if (b && b.width > 0) { v.__ddAsked = [b.x, b.y, b.width, b.height]; v.__ddAt = b.x; v.__ddW = b.width; v.__ddH = b.height; }
}
const a = v.__ddAsked;
if (a?.[2] > 0 && (v.__ddAt < popup.m_popup.innerWidth || (width(a[3]) && v.__ddW !== width(a[3])))) v.SetBounds(...a);
const [w, h] = a?.[2] > 0 ? size(a[2], a[3]) : [0, 0];
if (a?.[2] > 0 && (v.__ddAt < popup.m_popup.innerWidth || v.__ddW !== w || v.__ddH !== h)) v.SetBounds(...a);
}
const main = nav?.m_rgGamepadNavigationTrees?.find(t => t.m_ID === "GamepadUI_Full_Root");
if (main && nav.m_LastActiveNavTree?.m_ID?.startsWith("QuickAccess")) nav.SetActiveNavTree(main);
if (main && /^(QuickAccess|MainMenu)/.test(nav.m_LastActiveNavTree?.m_ID ?? "")) nav.SetActiveNavTree(main);
backdrop(true);
};
${leaseScript(on, owner, aspect)}
${leaseScript(on, owner, aspect, split)}
keep();
if (held() && !g.__ddQamTimer) {
g.__ddQamTimer = setInterval(() => {
@@ -161,7 +292,8 @@ object SteamQam {
/** [open] is Steam's open side menu; [top] is true while the menu is shown on the top screen. */
data class Hold(val open: Int, val top: Boolean)
fun hold(context: Context, aspect: Float, owner: Long): Hold? = eval(context, script(true, aspect, owner))?.let(::parseHold)
fun hold(context: Context, aspect: Float, owner: Long, split: Boolean = false): Hold? =
eval(context, script(true, aspect, owner, split))?.let(::parseHold)
internal fun parseHold(text: String): Hold? = runCatching {
val a = JSONArray(text)
@@ -181,7 +313,9 @@ object SteamQam {
fun target(context: Context): Target? = runCatching {
val devtools = File(AgentGuest.dir(context), "cdp-port").readText().trim().toInt()
val (relay, secret) = parseRelay(helper(context, "start", devtools.toString())) ?: return null
val found = runCatching { parseTarget(relay, get(relay, "/$secret/json"))?.let { it.copy(path = "/$secret${it.path}") } }
val found = runCatching {
parseTarget(relay, get(relay, "/$secret/json"))?.let { t -> t.copy(path = "/$secret${t.path}", mainPath = t.mainPath?.let { "/$secret$it" }) }
}
if (found.getOrNull() == null) helper(context, "stop", relay.toString())
found.getOrThrow()
}.onFailure { android.util.Log.e(TAG, "no quick access target: $it") }.getOrNull()
@@ -232,14 +366,16 @@ object SteamQam {
internal fun parseTarget(port: Int, json: String): Target? {
val list = JSONArray(json)
for (i in 0 until list.length()) {
val t = list.optJSONObject(i) ?: continue
if (!t.optString("title").startsWith("QuickAccess")) continue
val ws = t.optString("webSocketDebuggerUrl")
val path = Regex("^ws://[^/]+(/devtools/page/[A-Za-z0-9-]+)$").find(ws)?.groupValues?.get(1) ?: continue
return Target(port, path)
fun page(prefix: String): String? {
for (i in 0 until list.length()) {
val t = list.optJSONObject(i) ?: continue
if (!t.optString("title").startsWith(prefix)) continue
val ws = t.optString("webSocketDebuggerUrl")
Regex("^ws://[^/]+(/devtools/page/[A-Za-z0-9-]+)$").find(ws)?.groupValues?.get(1)?.let { return it }
}
return null
}
return null
return page("QuickAccess")?.let { Target(port, it, page("MainMenu")) }
}
private fun eval(context: Context, expression: String): String? = runCatching {
@@ -0,0 +1,78 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.util.Log
import com.droiddeck.launcher.gpu.GpuInfo
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreGameSidecar
import com.droiddeck.launcher.stores.StoreInstallRoot
import com.droiddeck.launcher.stores.xbox.XboxManifest
/**
* Microsoft's original Xbox releases for PC run its emulator, which needs FEX and VKD3D-Proton builds with fixes of
* their own (each off unless droiddeck-game-env turns it on for these games) and a newer DXVK than some Protons carry.
* Each installed one gets them as its game components. A component the player chose for the game is never replaced;
* one set here follows this list, so a newer build replaces it, and one the player cleared stays cleared.
*/
internal object XboxBackCompatComponents {
private const val TAG = "XboxBackCompat"
private const val PREFS = "xbox-backcompat-components"
internal data class Wanted(val comp: String, val file: String, val release: String)
internal fun wanted(family: GpuInfo.Family?): List<Wanted> = listOf(
Wanted("fex", "FEXCore-2611.1-xbox-bionic.wcp", ComponentsManager.DD_XBOX),
Wanted("vkd3d", "vkd3d-proton-arm64ec-3.1-xbox-linux.wcp", "Vkd3d-proton-Linux"),
Wanted("dxvk", if (family == GpuInfo.Family.A6XX) "dxvk-gplasync-3.2-a6xx-1-linux.wcp" else "dxvk-gplasync-3.2-1-linux.wcp",
"Dxvk-gplasync-Linux"),
)
/** The file to set for one component of a game, or null to leave it as it is. */
internal fun decide(current: String?, assigned: String?, wanted: String): String? = when {
current == null && assigned == null -> wanted
current != null && current == assigned && current != wanted -> wanted
else -> null
}
internal class Game(val scope: String, val title: String)
internal fun installed(context: Context): List<Game> = StoreInstallRoot.gameFolders(context).mapNotNull { folder ->
val sidecar = StoreGameSidecar.read(folder)?.takeIf { it.store == Store.XBOX && it.isInstalled } ?: return@mapNotNull null
if (!XboxManifest.backCompat(folder)) return@mapNotNull null
val appId = SessionPrefs.storedAddedGameAppId(context, folder.path) ?: return@mapNotNull null
Game(appId.toString(), sidecar.title)
}
fun ensure(context: Context): String? {
val games = installed(context)
if (games.isEmpty()) return null
val marks = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
val wanted = wanted(runCatching { GpuInfo.detect().family }.getOrNull())
val lines = mutableListOf<String>()
for (game in games) {
val current = ComponentsManager.gameComponents(context, game.scope)
for (w in wanted) {
val key = "${game.scope}/${w.comp}"
val file = decide(current[w.comp], marks.getString(key, null), w.file) ?: continue
val label = ComponentsManager.LABEL[w.comp]
runCatching {
ComponentsManager.assignGameComponent(context, game.scope, w.comp, file, w.release, expected = current[w.comp]) {
marks.edit().putString(key, file).apply()
}
}
.onSuccess { result ->
lines += when (result) {
ComponentsManager.Assigned.SET -> "${game.title}: $label ${file.removeSuffix(".wcp")}"
ComponentsManager.Assigned.NOT_LISTED -> "${game.title}: $file is not listed; $label unchanged"
ComponentsManager.Assigned.CHANGED -> "${game.title}: $label was chosen during the download; kept"
}
}
.onFailure { e ->
Log.w(TAG, "${game.title}: $file", e)
lines += "${game.title}: $label unchanged (${e.message ?: e.javaClass.simpleName})"
}
}
}
return lines.joinToString("; ").ifEmpty { null }
}
}
@@ -0,0 +1,68 @@
package com.droiddeck.launcher.session.xr
/**
* The menu gesture: both controllers held together. It arms when the two aim points come within
* [ARM_METRES], cancels once they part beyond [CANCEL_METRES], and fires after [HOLD_MS] held.
* It needs both controllers apart again before it can arm a second time.
*/
internal class XrGesture {
enum class Phase { IDLE, ARMING, FIRED }
var phase = Phase.IDLE
private set
var progress = 0f
private set
var midpoint = Vec3.ZERO
private set
private var startedMs = 0L
private var needsRelease = false
/** Returns true on the frame the gesture completes. */
fun update(left: XrHand, right: XrHand, nowMs: Long): Boolean {
if (!left.active || !right.active) {
reset(release = false)
return false
}
val a = left.aim.position
val b = right.aim.position
val distance = (a - b).length
midpoint = Vec3.lerp(a, b, 0.5f)
if (needsRelease) {
if (distance > CANCEL_METRES) needsRelease = false
phase = Phase.IDLE
progress = 0f
return false
}
when (phase) {
Phase.IDLE, Phase.FIRED -> if (distance < ARM_METRES) {
phase = Phase.ARMING
startedMs = nowMs
progress = 0f
}
Phase.ARMING -> if (distance > CANCEL_METRES) {
phase = Phase.IDLE
progress = 0f
} else {
progress = ((nowMs - startedMs).toFloat() / HOLD_MS).coerceIn(0f, 1f)
if (progress >= 1f) {
phase = Phase.FIRED
needsRelease = true
return true
}
}
}
return false
}
fun reset(release: Boolean) {
phase = Phase.IDLE
progress = 0f
if (release) needsRelease = true
}
companion object {
const val ARM_METRES = 0.09f
const val CANCEL_METRES = 0.14f
const val HOLD_MS = 1500L
}
}
@@ -0,0 +1,160 @@
package com.droiddeck.launcher.session.xr
import java.nio.ByteBuffer
import java.nio.ByteOrder
/**
* Typed access to the two buffers quest_xr.cpp shares each frame (app/src/main/cpp/questxr/xr_host.h).
* The offsets here must match that header.
*/
internal object XrHostLayout {
const val VERSION = 1
const val LAYERS = 6
const val STATE_SIZE = 288
const val CONTROL_SIZE = 552
const val POSE_SIZE = 32
const val HAND_SIZE = 96
const val STATE_HEAD = 32
const val STATE_HANDS = 64
const val HAND_GRIP = 0
const val HAND_AIM = 32
const val HAND_TRIGGER = 64
const val HAND_SQUEEZE = 68
const val HAND_STICK = 72
const val HAND_BUTTONS = 80
const val HAND_ACTIVE = 84
const val CONTROL_HANDS = 8
const val HAND_CONTROL_SIZE = 40
const val HAND_CONTROL_MASK = 0
const val HAND_CONTROL_LASER = 4
const val HAND_CONTROL_HAPTIC = 8
const val CONTROL_ORB = 88
const val CONTROL_LAYERS = 136
const val LAYER_SIZE = 64
const val FLAG_SURFACE_SWAPCHAIN = 1
const val FLAG_FOCUSED = 2
const val MASK_INPUT = 1
const val LAYER_ALPHA = 1
const val LAYER_HEAD_LOCKED = 2
const val SECONDARY_CLICK = 1 shl 2
}
internal class XrHand(
val grip: Pose,
val aim: Pose,
val trigger: Float,
val squeeze: Float,
val stickX: Float,
val stickY: Float,
val buttons: Int,
val active: Boolean,
) {
val secondary: Boolean get() = buttons and XrHostLayout.SECONDARY_CLICK != 0
companion object {
val IDLE = XrHand(Pose(), Pose(), 0f, 0f, 0f, 0f, 0, false)
}
}
internal class XrFrame(val flags: Int, val frame: Long, val displayTimeNs: Long, val head: Pose, val hands: List<XrHand>) {
val focused: Boolean get() = flags and XrHostLayout.FLAG_FOCUSED != 0
val surfaces: Boolean get() = flags and XrHostLayout.FLAG_SURFACE_SWAPCHAIN != 0
}
internal class XrHaptic(val durationMs: Int, val amplitude: Float, val frequency: Float = 0f)
internal class XrLayerOut(
val id: Int,
val pose: Pose,
val width: Float,
val height: Float,
val order: Int,
val alpha: Boolean = true,
)
internal class XrControlOut {
val masks = BooleanArray(2)
val lasers = FloatArray(2)
val haptics = arrayOfNulls<XrHaptic>(2)
var orb: Orb? = null
val layers = mutableListOf<XrLayerOut>()
class Orb(val position: Vec3, val radius: Float, val progress: Float, val burst: Float)
}
internal class XrHost(state: ByteBuffer, control: ByteBuffer) {
private val state = state.order(ByteOrder.nativeOrder())
private val control = control.order(ByteOrder.nativeOrder())
private val hapticIds = LongArray(2)
init {
require(state.capacity() >= XrHostLayout.STATE_SIZE && control.capacity() >= XrHostLayout.CONTROL_SIZE) { "XR host buffers too small" }
}
fun read(): XrFrame = readFrame(state)
fun write(out: XrControlOut) = writeControl(control, out, hapticIds)
companion object {
fun readPose(b: ByteBuffer, at: Int) = Pose(
Quat(b.getFloat(at), b.getFloat(at + 4), b.getFloat(at + 8), b.getFloat(at + 12)),
Vec3(b.getFloat(at + 16), b.getFloat(at + 20), b.getFloat(at + 24)),
)
fun writePose(b: ByteBuffer, at: Int, pose: Pose) {
b.putFloat(at, pose.orientation.x); b.putFloat(at + 4, pose.orientation.y)
b.putFloat(at + 8, pose.orientation.z); b.putFloat(at + 12, pose.orientation.w)
b.putFloat(at + 16, pose.position.x); b.putFloat(at + 20, pose.position.y); b.putFloat(at + 24, pose.position.z)
b.putInt(at + 28, 0)
}
fun readFrame(b: ByteBuffer): XrFrame {
val hands = (0 until 2).map { hand ->
val at = XrHostLayout.STATE_HANDS + hand * XrHostLayout.HAND_SIZE
XrHand(
readPose(b, at + XrHostLayout.HAND_GRIP), readPose(b, at + XrHostLayout.HAND_AIM),
b.getFloat(at + XrHostLayout.HAND_TRIGGER), b.getFloat(at + XrHostLayout.HAND_SQUEEZE),
b.getFloat(at + XrHostLayout.HAND_STICK), b.getFloat(at + XrHostLayout.HAND_STICK + 4),
b.getInt(at + XrHostLayout.HAND_BUTTONS), b.getInt(at + XrHostLayout.HAND_ACTIVE) != 0,
)
}
return XrFrame(b.getInt(8), b.getLong(16), b.getLong(24), readPose(b, XrHostLayout.STATE_HEAD), hands)
}
fun writeControl(b: ByteBuffer, out: XrControlOut, hapticIds: LongArray) {
for (i in 0 until XrHostLayout.CONTROL_SIZE step 4) b.putInt(i, 0)
b.putInt(0, XrHostLayout.VERSION)
for (hand in 0 until 2) {
val at = XrHostLayout.CONTROL_HANDS + hand * XrHostLayout.HAND_CONTROL_SIZE
b.putInt(at + XrHostLayout.HAND_CONTROL_MASK, if (out.masks[hand]) XrHostLayout.MASK_INPUT else 0)
b.putFloat(at + XrHostLayout.HAND_CONTROL_LASER, out.lasers[hand])
out.haptics[hand]?.let { hapticIds[hand]++ }
val haptic = at + XrHostLayout.HAND_CONTROL_HAPTIC
b.putLong(haptic, hapticIds[hand])
out.haptics[hand]?.let {
b.putLong(haptic + 8, it.durationMs * 1_000_000L)
b.putFloat(haptic + 16, it.amplitude)
b.putFloat(haptic + 20, it.frequency)
}
}
out.orb?.let { orb ->
val at = XrHostLayout.CONTROL_ORB
b.putInt(at, 1)
b.putFloat(at + 4, orb.progress); b.putFloat(at + 8, orb.burst); b.putFloat(at + 12, orb.radius)
writePose(b, at + 16, Pose(position = orb.position))
}
out.layers.take(XrHostLayout.LAYERS).forEachIndexed { index, layer ->
val at = XrHostLayout.CONTROL_LAYERS + index * XrHostLayout.LAYER_SIZE
b.putInt(at, layer.id)
b.putInt(at + 4, 1)
b.putInt(at + 8, if (layer.alpha) XrHostLayout.LAYER_ALPHA else 0)
b.putInt(at + 12, layer.order)
writePose(b, at + 16, layer.pose)
b.putFloat(at + 48, layer.width); b.putFloat(at + 52, layer.height)
}
for (index in out.layers.size until XrHostLayout.LAYERS) b.putInt(XrHostLayout.CONTROL_LAYERS + index * XrHostLayout.LAYER_SIZE, -1)
}
}
}
@@ -0,0 +1,303 @@
package com.droiddeck.launcher.session.xr
import kotlin.math.PI
import kotlin.math.abs
/**
* [barButton]: the grab bar has a button at its left end; the menu has its own close button instead.
* [tilt]: how far the panel leans back from upright, in radians, as a keyboard lies on a desk.
*/
internal enum class XrPanelKind(
val key: String, val resizable: Boolean, val chrome: Boolean, val barButton: Boolean = false, val tilt: Float = 0f,
) {
MENU("menu", resizable = true, chrome = true),
PET_HEAD("pet_head", resizable = false, chrome = false),
PET_CHAT("pet_chat", resizable = true, chrome = true, barButton = true),
KEYBOARD("keyboard_desk", resizable = true, chrome = true, barButton = true, tilt = (PI / 4).toFloat());
/** Turned towards [head] about the vertical axis, then leant back by [tilt]. */
fun orient(position: Vec3, head: Vec3): Quat = facing(position, head) * Quat.pitch(-tilt)
}
/** Where a panel is and how big, in metres; [pixelWidth] and [pixelHeight] are its surface's size. */
internal class XrPanelState(val kind: XrPanelKind, var pose: Pose, var width: Float, var height: Float) {
var pixelWidth = XrUnits.pixels(width)
var pixelHeight = XrUnits.pixels(height)
/** 0 while it opens or closes from [animationFrom], 1 when it is in place and takes input. */
var scale = 1f
var animationFrom: Vec3? = null
val shownPose: Pose get() = animationFrom?.let { Pose(pose.orientation, Vec3.lerp(it, pose.position, scale)) } ?: pose
val interactive: Boolean get() = scale >= 1f
fun hit(ray: Pose): XrHit? = hitPlane(ray, bounded = true)
/** Where [ray] meets this panel's plane; [bounded] limits it to the panel itself. */
fun hitPlane(ray: Pose, bounded: Boolean, plane: Pose = pose, w: Float = width, h: Float = height): XrHit? {
val normal = plane.orientation.rotate(Vec3(0f, 0f, 1f))
val direction = ray.forward
val denominator = direction dot normal
if (denominator > -1e-4f) return null
val distance = ((plane.position - ray.position) dot normal) / denominator
if (distance <= 0f) return null
val local = plane.toLocal(ray.position + direction * distance)
if (bounded && (abs(local.x) > w / 2f || abs(local.y) > h / 2f)) return null
return XrHit(this, local.x, local.y, distance)
}
fun u(localX: Float) = (localX / width + 0.5f).coerceIn(0f, 1f)
fun v(localY: Float) = (0.5f - localY / height).coerceIn(0f, 1f)
fun pixelX(localX: Float) = u(localX) * pixelWidth
fun pixelY(localY: Float) = v(localY) * pixelHeight
/** The grab bar runs along the bottom, as under Quest's own windows, with its button at the left end. */
fun inBar(hit: XrHit) = kind.chrome && hit.y + 0.5f * height <= XrUnits.BAR_METRES
fun inBarButtons(hit: XrHit) = kind.barButton && inBar(hit) && hit.x + 0.5f * width <= XrUnits.BAR_BUTTONS_METRES
fun inResizeGrip(hit: XrHit) = kind.resizable &&
0.5f * width - hit.x <= XrUnits.GRIP_METRES && hit.y + 0.5f * height <= XrUnits.GRIP_METRES
}
internal class XrHit(val panel: XrPanelState, val x: Float, val y: Float, val distance: Float)
internal object XrUnits {
const val DP_PER_METRE = 900f
const val DENSITY = 2f
const val DPI = 320
const val BAR_METRES = 52f / DP_PER_METRE
const val BAR_BUTTONS_DP = 150f
const val BAR_BUTTONS_METRES = BAR_BUTTONS_DP / DP_PER_METRE
const val GRIP_METRES = 0.05f
const val MIN_METRES = 0.3f
const val MAX_METRES = 1.6f
const val MIN_DISTANCE = 0.4f
const val MAX_DISTANCE = 3f
fun pixels(metres: Float) = (metres * DP_PER_METRE * DENSITY).toInt().coerceAtLeast(16)
}
internal sealed class XrPointerEvent(val panel: XrPanelState) {
class Down(panel: XrPanelState, val x: Float, val y: Float, val hand: Int = 0) : XrPointerEvent(panel)
class Move(panel: XrPanelState, val x: Float, val y: Float, val hand: Int = 0) : XrPointerEvent(panel)
class Up(panel: XrPanelState, val x: Float, val y: Float, val hand: Int = 0) : XrPointerEvent(panel)
class Cancel(panel: XrPanelState, val hand: Int = 0) : XrPointerEvent(panel)
class Scroll(panel: XrPanelState, val x: Float, val y: Float, val amount: Float) : XrPointerEvent(panel)
class Back(panel: XrPanelState) : XrPointerEvent(panel)
class Click(panel: XrPanelState) : XrPointerEvent(panel)
class Resized(panel: XrPanelState) : XrPointerEvent(panel)
class Moved(panel: XrPanelState) : XrPointerEvent(panel)
}
internal class XrInteractionOut {
val events = mutableListOf<XrPointerEvent>()
val masks = BooleanArray(2)
val lasers = FloatArray(2)
val ticks = BooleanArray(2)
/** Where each controller points on each panel, in its pixels, left hand first; panels with no entry show none. */
val cursors = mutableMapOf<XrPanelState, MutableList<Pair<Float, Float>>>()
fun point(panel: XrPanelState, x: Float, y: Float) {
cursors.getOrPut(panel) { mutableListOf() } += x to y
}
}
/**
* What the two controllers do to the panels each frame. A controller acts on a panel only while it
* points at one, or while it holds one it picked up, pressed or is resizing; only then is its input
* taken from the game.
*/
internal class XrInteraction {
private sealed class Hold {
object None : Hold()
class Press(val panel: XrPanelState, var x: Float, var y: Float) : Hold()
class Move(val panel: XrPanelState, var offset: Vec3, val byGrip: Boolean) : Hold()
class Resize(val panel: XrPanelState, val plane: Pose, val width: Float, val height: Float, val startX: Float, val startY: Float) : Hold()
class HeadPress(val panel: XrPanelState, val startX: Float, val startY: Float, val offset: Vec3) : Hold()
}
private val holds = arrayOf<Hold>(Hold.None, Hold.None)
private val trigger = BooleanArray(2)
private val grip = BooleanArray(2)
private val secondary = BooleanArray(2)
fun holding(panel: XrPanelState) = holds.any { held(it) === panel }
private fun held(hold: Hold): XrPanelState? = when (hold) {
is Hold.Press -> hold.panel
is Hold.Move -> hold.panel
is Hold.Resize -> hold.panel
is Hold.HeadPress -> hold.panel
Hold.None -> null
}
/** Lets go of everything, as when the immersive view goes. A button still held counts only once let go and pressed again. */
fun reset() {
holds.fill(Hold.None)
trigger.fill(true)
grip.fill(true)
secondary.fill(true)
}
/** Cancels a press and ends a move or resize where it is, as when the headset loses focus; then [reset]. */
fun cancel(out: XrInteractionOut) {
for ((hand, hold) in holds.withIndex()) when (hold) {
is Hold.Press -> out.events += XrPointerEvent.Cancel(hold.panel, hand)
is Hold.Move -> out.events += XrPointerEvent.Moved(hold.panel)
is Hold.Resize -> out.events += XrPointerEvent.Resized(hold.panel)
else -> Unit
}
reset()
}
/** Lets go of [panel], as when it closes. */
fun release(panel: XrPanelState, out: XrInteractionOut) {
for (hand in 0..1) if (held(holds[hand]) === panel) {
if (holds[hand] is Hold.Press) out.events += XrPointerEvent.Cancel(panel, hand)
holds[hand] = Hold.None
}
}
fun update(head: Pose, hands: List<XrHand>, panels: List<XrPanelState>, dtSeconds: Float): XrInteractionOut {
val out = XrInteractionOut()
for (hand in 0..1) handFrame(hand, head, hands[hand], panels.filter { it.interactive }, dtSeconds, out)
return out
}
private fun handFrame(index: Int, head: Pose, hand: XrHand, panels: List<XrPanelState>, dt: Float, out: XrInteractionOut) {
val wasTrigger = trigger[index]
val wasGrip = grip[index]
val wasSecondary = secondary[index]
trigger[index] = if (wasTrigger) hand.trigger > 0.4f else hand.trigger > 0.6f
grip[index] = if (wasGrip) hand.squeeze > 0.5f else hand.squeeze > 0.7f
secondary[index] = hand.secondary
val triggerDown = trigger[index] && !wasTrigger
val triggerUp = !trigger[index] && wasTrigger
val gripDown = grip[index] && !wasGrip
val secondaryDown = secondary[index] && !wasSecondary
val hold = holds[index]
if (!hand.active) {
if (hold is Hold.Press) out.events += XrPointerEvent.Cancel(hold.panel, index)
if (hold is Hold.Move) out.events += XrPointerEvent.Moved(hold.panel)
if (hold is Hold.Resize) out.events += XrPointerEvent.Resized(hold.panel)
holds[index] = Hold.None
return
}
val ray = hand.aim
when (hold) {
is Hold.Move -> {
val panel = hold.panel
if (abs(hand.stickY) > 0.2f) {
val length = hold.offset.length
val wanted = (length * (1f + hand.stickY * 1.2f * dt)).coerceIn(XrUnits.MIN_DISTANCE, XrUnits.MAX_DISTANCE)
hold.offset = hold.offset.normalized() * wanted
}
val position = ray.toWorld(hold.offset)
panel.pose = Pose(panel.kind.orient(position, head.position), position)
out.masks[index] = true
out.lasers[index] = hold.offset.length
val released = if (hold.byGrip) !grip[index] else !trigger[index]
if (released) {
holds[index] = Hold.None
out.events += XrPointerEvent.Moved(panel)
}
return
}
is Hold.Resize -> {
val panel = hold.panel
out.masks[index] = true
hold.panel.hitPlane(ray, bounded = false, plane = hold.plane, w = hold.width, h = hold.height)?.let { hit ->
val left = -hold.width / 2f
val top = hold.height / 2f
val width = (hold.width + hit.x - hold.startX).coerceIn(XrUnits.MIN_METRES, XrUnits.MAX_METRES)
val height = (hold.height + hold.startY - hit.y).coerceIn(XrUnits.MIN_METRES, XrUnits.MAX_METRES)
panel.width = width
panel.height = height
panel.pose = Pose(hold.plane.orientation, hold.plane.toWorld(Vec3(left + width / 2f, top - height / 2f, 0f)))
out.lasers[index] = hit.distance
}
if (!trigger[index]) {
holds[index] = Hold.None
out.events += XrPointerEvent.Resized(panel)
}
return
}
is Hold.Press -> {
val panel = hold.panel
out.masks[index] = true
val hit = panel.hitPlane(ray, bounded = false)
if (hit != null) {
val x = panel.pixelX(hit.x)
val y = panel.pixelY(hit.y)
if (x != hold.x || y != hold.y) out.events += XrPointerEvent.Move(panel, x, y, index)
hold.x = x; hold.y = y
out.lasers[index] = hit.distance
out.point(panel, x, y)
}
if (secondaryDown) out.events += XrPointerEvent.Back(panel)
if (triggerUp || !trigger[index]) {
out.events += if (hit != null) XrPointerEvent.Up(panel, hold.x, hold.y, index) else XrPointerEvent.Cancel(panel, index)
holds[index] = Hold.None
}
return
}
is Hold.HeadPress -> {
val panel = hold.panel
out.masks[index] = true
val hit = panel.hitPlane(ray, bounded = false)
if (hit != null) {
out.lasers[index] = hit.distance
val moved = Vec3(hit.x - hold.startX, hit.y - hold.startY, 0f).length
if (moved > HEAD_DRAG_METRES) {
holds[index] = Hold.Move(panel, hold.offset, byGrip = false)
val position = ray.toWorld(hold.offset)
panel.pose = Pose(panel.kind.orient(position, head.position), position)
return
}
}
if (!trigger[index]) {
holds[index] = Hold.None
if (panel.hit(ray) != null) out.events += XrPointerEvent.Click(panel)
}
return
}
Hold.None -> Unit
}
val hit = panels.mapNotNull { it.hit(ray) }.minByOrNull { it.distance } ?: return
val panel = hit.panel
out.masks[index] = true
out.lasers[index] = hit.distance
val x = panel.pixelX(hit.x)
val y = panel.pixelY(hit.y)
out.point(panel, x, y)
val other = holds[1 - index]
val heldByOther = held(other) === panel && other !is Hold.Press
when {
heldByOther -> Unit
gripDown -> {
holds[index] = Hold.Move(panel, ray.toLocal(panel.pose.position), byGrip = true)
out.ticks[index] = true
}
triggerDown && panel.kind == XrPanelKind.PET_HEAD ->
holds[index] = Hold.HeadPress(panel, hit.x, hit.y, ray.toLocal(panel.pose.position))
triggerDown && panel.inResizeGrip(hit) -> {
holds[index] = Hold.Resize(panel, panel.pose, panel.width, panel.height, hit.x, hit.y)
out.ticks[index] = true
}
triggerDown && panel.inBar(hit) && !panel.inBarButtons(hit) -> {
holds[index] = Hold.Move(panel, ray.toLocal(panel.pose.position), byGrip = false)
out.ticks[index] = true
}
triggerDown -> {
holds[index] = Hold.Press(panel, x, y)
out.events += XrPointerEvent.Down(panel, x, y, index)
}
}
if (holds[index] === Hold.None) {
if (abs(hand.stickY) > 0.25f) out.events += XrPointerEvent.Scroll(panel, x, y, hand.stickY * SCROLL_PER_SECOND * dt)
if (secondaryDown) out.events += XrPointerEvent.Back(panel)
}
}
companion object {
const val HEAD_DRAG_METRES = 0.02f
const val SCROLL_PER_SECOND = 12f
}
}
@@ -0,0 +1,283 @@
package com.droiddeck.launcher.session.xr
import android.view.KeyEvent
import androidx.compose.ui.res.stringResource
import com.droiddeck.launcher.R
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.outlined.Backspace
import androidx.compose.material.icons.automirrored.outlined.KeyboardReturn
import androidx.compose.material.icons.outlined.KeyboardArrowUp
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.compositeOver
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.input.EditCommand
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.ImeOptions
import androidx.compose.ui.text.input.PlatformTextInputService
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.input.PC_KEY_ROWS
import kotlinx.coroutines.delay
import com.droiddeck.launcher.ui.TypingRequest
/** Sends text fields in the floating panels to [XrKeyboard], since the system keyboard cannot show in the immersive view. */
internal class XrTextInput : PlatformTextInputService {
private var request: TypingRequest? = null
override fun startInput(
value: TextFieldValue, imeOptions: ImeOptions,
onEditCommand: (List<EditCommand>) -> Unit, onImeActionPerformed: (ImeAction) -> Unit,
) {
val next = TypingRequest(value, imeOptions, { onEditCommand(TypingRequest.editsFor(it)) }, onImeActionPerformed)
request = next
XrPanels.startTyping(next)
}
override fun stopInput() {
request?.let { XrPanels.stopTyping(it) }
request = null
}
override fun showSoftwareKeyboard() {
request?.let { XrPanels.startTyping(it) }
}
override fun hideSoftwareKeyboard() {
request?.let { XrPanels.stopTyping(it) }
}
override fun updateState(oldValue: TextFieldValue?, newValue: TextFieldValue) {
request?.value = newValue
}
}
internal object XrKeys {
private val letters = listOf("qwertyuiop", "asdfghjkl", "zxcvbnm")
private val symbols = listOf("1234567890", "@#&*-+=()", "!?:;'\"/,")
fun rows(numbers: Boolean, shift: Boolean): List<String> =
(if (numbers) symbols else letters).map { if (shift && !numbers) it.uppercase() else it }
fun insert(value: TextFieldValue, text: String): TextFieldValue {
val start = minOf(value.selection.start, value.selection.end)
val end = maxOf(value.selection.start, value.selection.end)
val next = value.text.substring(0, start) + text + value.text.substring(end)
return TextFieldValue(next, TextRange(start + text.length))
}
fun backspace(value: TextFieldValue): TextFieldValue {
val start = minOf(value.selection.start, value.selection.end)
val end = maxOf(value.selection.start, value.selection.end)
if (start != end) return TextFieldValue(value.text.substring(0, start) + value.text.substring(end), TextRange(start))
if (start == 0) return value
val cut = value.text.offsetByCodePoints(start, -1)
return TextFieldValue(value.text.substring(0, cut) + value.text.substring(start), TextRange(cut))
}
const val REPEAT_DELAY_MS = 450L
const val REPEAT_MS = 50L
/** Return sends when the field asks for an action, and starts a new line otherwise. */
fun returnSends(options: ImeOptions) = options.imeAction != ImeAction.Default && options.imeAction != ImeAction.None &&
options.singleLine
}
/** Where the laser keyboard's keys go: a text field in a panel, or the game. */
internal interface XrKeyTarget {
fun type(text: String)
fun backspace()
fun enter()
}
internal class XrFieldTarget(private val request: TypingRequest) : XrKeyTarget {
override fun type(text: String) = request.send(XrKeys.insert(request.value, text))
override fun backspace() = request.send(XrKeys.backspace(request.value))
override fun enter() = if (XrKeys.returnSends(request.imeOptions)) request.action() else type("\n")
}
internal class XrGameTarget(private val host: XrMenuHost) : XrKeyTarget {
override fun type(text: String) = host.xrTypeText(text)
override fun backspace() = host.xrTapKey(KeyEvent.KEYCODE_DEL)
override fun enter() = host.xrTapKey(KeyEvent.KEYCODE_ENTER)
}
/**
* DroidDeck's PC keyboard typing into a panel's text field: the keys that make a character type it,
* Backspace, Enter and Space edit, and Shift and Caps Lock pick the case. The rest have nothing to do there.
*/
internal class XrPcText(private val target: XrKeyTarget, private val timer: XrTimer = XrTimer.Main) {
private val keys = PC_KEY_ROWS.flatten()
.filter { it.labelRes == 0 && it.label.length == 1 && it.code !in ARROWS }
.associateBy { it.code }
private val shifts = mutableSetOf<Int>()
private var caps = false
private var stopRepeat: (() -> Unit)? = null
fun key(code: Int, down: Boolean) {
if (code == LEFT_SHIFT || code == RIGHT_SHIFT) {
if (down) shifts += code else shifts -= code
return
}
if (!down && code != BACKSPACE) return
stopRepeat?.invoke()
stopRepeat = null
if (!down) return
val shifted = shifts.isNotEmpty()
when (code) {
BACKSPACE -> {
target.backspace()
stopRepeat = timer.after(XrKeys.REPEAT_DELAY_MS, ::repeatBackspace)
}
ENTER -> target.enter()
SPACE -> target.type(" ")
CAPS -> caps = !caps
else -> keys[code]?.let { key ->
target.type(when {
shifted && key.shifted != null -> key.shifted
key.label[0].isLetter() && (shifted xor caps) -> key.label.uppercase()
else -> key.label
})
}
}
}
private fun repeatBackspace() {
target.backspace()
stopRepeat = timer.after(XrKeys.REPEAT_MS, ::repeatBackspace)
}
private companion object {
const val LEFT_SHIFT = 42
const val RIGHT_SHIFT = 54
const val BACKSPACE = 14
const val ENTER = 28
const val SPACE = 57
const val CAPS = 58
val ARROWS = setOf(103, 105, 106, 108)
}
}
/** Runs an action later on the main thread; the function it returns cancels it. */
internal fun interface XrTimer {
fun after(ms: Long, action: () -> Unit): () -> Unit
companion object {
private val handler by lazy { android.os.Handler(android.os.Looper.getMainLooper()) }
val Main = XrTimer { ms, action ->
val runnable = Runnable(action)
handler.postDelayed(runnable, ms)
({ handler.removeCallbacks(runnable) })
}
}
}
/** The Android-style text keyboard. */
@Composable
internal fun XrKeyboard(target: XrKeyTarget) {
var shift by remember { mutableStateOf(false) }
var numbers by remember { mutableStateOf(false) }
fun type(text: String) {
target.type(text)
if (shift) shift = false
}
Column(Modifier.fillMaxSize().padding(8.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
XrKeys.rows(numbers, shift).forEachIndexed { index, row ->
Row(Modifier.fillMaxWidth().weight(1f), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
if (index == 2) KeyIcon(Icons.Outlined.KeyboardArrowUp, stringResource(R.string.pckb_key_shift), active = shift, weight = 1.5f) { shift = !shift }
row.forEach { key -> Key(key.toString()) { type(key.toString()) } }
if (index == 2) KeyIcon(Icons.AutoMirrored.Outlined.Backspace, stringResource(R.string.pckb_key_backspace), weight = 1.5f, repeats = true) { target.backspace() }
}
}
Row(Modifier.fillMaxWidth().weight(1f), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
Key(if (numbers) "abc" else "?123", weight = 1.5f) { numbers = !numbers }
Key(",") { type(",") }
Key(" ", weight = 5f) { type(" ") }
Key(".") { type(".") }
KeyIcon(Icons.AutoMirrored.Outlined.KeyboardReturn, stringResource(R.string.pckb_key_enter), weight = 1.5f) { target.enter() }
}
}
}
/** A key that lights while the laser is over it and dips while it is pressed; [repeats] keeps acting while held. */
@Composable
private fun RowScope.KeyBox(
weight: Float, active: Boolean, onClick: () -> Unit, repeats: Boolean = false, content: @Composable (Color) -> Unit,
) {
val colors = MaterialTheme.colorScheme
val source = remember { MutableInteractionSource() }
val (pointedAt, pointed) = rememberXrPointed()
val hovered = pointed.value
val pressed by source.collectIsPressedAsState()
val action by rememberUpdatedState(onClick)
var repeated by remember { mutableStateOf(false) }
if (repeats) LaunchedEffect(pressed) {
if (!pressed) return@LaunchedEffect
repeated = false
delay(XrKeys.REPEAT_DELAY_MS)
repeated = true
while (true) {
action()
delay(XrKeys.REPEAT_MS)
}
}
val fill by animateColorAsState(
when {
pressed -> colors.primary
active -> colors.primary.copy(alpha = 0.8f)
hovered -> colors.onSurface.copy(alpha = 0.22f).compositeOver(colors.surfaceVariant)
else -> colors.surfaceVariant
}, tween(if (pressed) 40 else 140), label = "keyFill",
)
val scale by animateFloatAsState(if (pressed) 0.9f else if (hovered) 1.05f else 1f, tween(if (pressed) 40 else 140), label = "keyScale")
Box(
Modifier.weight(weight).fillMaxHeight()
.then(pointedAt)
.graphicsLayer { scaleX = 1f + (scale - 1f) * size.height / size.width; scaleY = scale }
.clip(RoundedCornerShape(8.dp)).background(fill)
.border(if (hovered) 2.dp else 0.dp, if (hovered) colors.primary else Color.Transparent, RoundedCornerShape(8.dp))
.clickable(interactionSource = source, indication = null) { if (repeated) repeated = false else onClick() },
contentAlignment = Alignment.Center,
) { content(if (pressed || active) colors.onPrimary else colors.onSurface) }
}
@Composable
private fun RowScope.Key(label: String, weight: Float = 1f, onClick: () -> Unit) =
KeyBox(weight, active = false, onClick) { tint -> Text(label, color = tint, fontSize = 22.sp, maxLines = 1) }
@Composable
private fun RowScope.KeyIcon(icon: ImageVector, label: String, active: Boolean = false, weight: Float = 1f, repeats: Boolean = false, onClick: () -> Unit) =
KeyBox(weight, active, onClick, repeats) { tint -> Icon(icon, label, tint = tint) }
@@ -0,0 +1,61 @@
package com.droiddeck.launcher.session.xr
import kotlin.math.atan2
import kotlin.math.cos
import kotlin.math.sin
import kotlin.math.sqrt
internal data class Vec3(val x: Float, val y: Float, val z: Float) {
operator fun plus(o: Vec3) = Vec3(x + o.x, y + o.y, z + o.z)
operator fun minus(o: Vec3) = Vec3(x - o.x, y - o.y, z - o.z)
operator fun times(s: Float) = Vec3(x * s, y * s, z * s)
infix fun dot(o: Vec3) = x * o.x + y * o.y + z * o.z
infix fun cross(o: Vec3) = Vec3(y * o.z - z * o.y, z * o.x - x * o.z, x * o.y - y * o.x)
val length: Float get() = sqrt(this dot this)
fun normalized(): Vec3 = length.let { if (it > 1e-6f) this * (1f / it) else ZERO }
companion object {
val ZERO = Vec3(0f, 0f, 0f)
val FORWARD = Vec3(0f, 0f, -1f)
val UP = Vec3(0f, 1f, 0f)
fun lerp(a: Vec3, b: Vec3, t: Float) = a + (b - a) * t
}
}
internal data class Quat(val x: Float, val y: Float, val z: Float, val w: Float) {
fun rotate(v: Vec3): Vec3 {
val u = Vec3(x, y, z)
return u * (2f * (u dot v)) + v * (w * w - (u dot u)) + (u cross v) * (2f * w)
}
fun conjugate() = Quat(-x, -y, -z, w)
operator fun times(o: Quat) = Quat(
w * o.x + x * o.w + y * o.z - z * o.y,
w * o.y - x * o.z + y * o.w + z * o.x,
w * o.z + x * o.y - y * o.x + z * o.w,
w * o.w - x * o.x - y * o.y - z * o.z,
)
companion object {
val IDENTITY = Quat(0f, 0f, 0f, 1f)
fun yaw(radians: Float) = Quat(0f, sin(radians / 2f), 0f, cos(radians / 2f))
fun pitch(radians: Float) = Quat(sin(radians / 2f), 0f, 0f, cos(radians / 2f))
}
}
internal data class Pose(val orientation: Quat = Quat.IDENTITY, val position: Vec3 = Vec3.ZERO) {
val forward: Vec3 get() = orientation.rotate(Vec3.FORWARD)
fun toLocal(world: Vec3): Vec3 = orientation.conjugate().rotate(world - position)
fun toWorld(local: Vec3): Vec3 = position + orientation.rotate(local)
}
/** Yaw of a direction in the horizontal plane, 0 along -Z, matching [Quat.yaw] applied to -Z. */
internal fun yawOf(direction: Vec3): Float = atan2(-direction.x, -direction.z)
/** An orientation that turns +Z, the side of a quad that shows, from [position] towards [target] about the vertical axis only. */
internal fun facing(position: Vec3, target: Vec3): Quat {
val d = target - position
if (d.x * d.x + d.z * d.z < 1e-8f) return Quat.IDENTITY
return Quat.yaw(atan2(d.x, d.z))
}
@@ -0,0 +1,126 @@
package com.droiddeck.launcher.session.xr
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Remove
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.State
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.boundsInWindow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
/**
* The frame of a floating panel: the content, a bar under it to grab it by with up to two buttons at
* its left end, a corner grip to resize it, and the dot where a controller points. Its sizes match [XrUnits].
*/
@Composable
internal fun XrPanelChrome(
cursor: State<List<Pair<Float, Float>>>,
buttons: List<XrPanelButton>,
resizable: Boolean,
content: @Composable () -> Unit,
) {
val colors = MaterialTheme.colorScheme
val shape = RoundedCornerShape(18.dp)
Box(Modifier.fillMaxSize().clip(shape).background(colors.background).border(1.dp, Color(0x33FFFFFF), shape)) {
Column(Modifier.fillMaxSize()) {
Box(Modifier.weight(1f).fillMaxWidth().padding(start = 10.dp, top = 10.dp, end = 10.dp)) {
CompositionLocalProvider(LocalXrPointers provides cursor) { content() }
}
Box(
Modifier.fillMaxWidth().height(52.dp).background(colors.surfaceVariant.copy(alpha = 0.6f)),
contentAlignment = Alignment.Center,
) {
Box(Modifier.width(72.dp).height(6.dp).clip(CircleShape).background(colors.onSurface.copy(alpha = 0.35f)))
if (buttons.isNotEmpty()) Row(
Modifier.align(Alignment.CenterStart).width(XrUnits.BAR_BUTTONS_DP.dp).padding(start = 8.dp),
horizontalArrangement = Arrangement.spacedBy(4.dp),
verticalAlignment = Alignment.CenterVertically,
) {
buttons.take(2).forEach { button ->
if (button.icon != null) IconButton(onClick = button.onClick, modifier = Modifier.size(44.dp)) {
Icon(button.icon, button.label, tint = colors.onSurface)
} else TextButton(onClick = button.onClick, modifier = Modifier.height(40.dp), contentPadding = PaddingValues(horizontal = 10.dp)) {
Text(button.label, color = colors.onSurface, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, maxLines = 1)
}
}
}
}
}
if (resizable) Canvas(Modifier.align(Alignment.BottomEnd).padding(6.dp).size(28.dp)) {
val stroke = Stroke(width = 3.dp.toPx())
for (step in 1..3) {
val inset = size.width * step / 4f
drawLine(Color(0x99FFFFFF), Offset(size.width, inset), Offset(inset, size.height), stroke.width)
}
}
val density = LocalDensity.current
Canvas(Modifier.fillMaxSize()) {
val radius = with(density) { 7.dp.toPx() }
for ((x, y) in cursor.value) {
drawCircle(Color(0xCC1E9EFF), radius, Offset(x, y))
drawCircle(Color.White, radius, Offset(x, y), style = Stroke(with(density) { 2.dp.toPx() }))
}
}
}
}
/** Where each laser meets the panel, in the panel's pixels; null off a floating panel. */
internal val LocalXrPointers = staticCompositionLocalOf<State<List<Pair<Float, Float>>>?> { null }
/**
* Whether a laser rests on the element the returned [Modifier] is put on, for both controllers at
* once, where a mouse hover has room for one. False off a floating panel.
*/
@Composable
internal fun rememberXrPointed(): Pair<Modifier, State<Boolean>> {
val pointers = LocalXrPointers.current
var bounds by remember { mutableStateOf(Rect.Zero) }
val pointed = remember(pointers) {
derivedStateOf { pointers != null && pointers.value.any { (x, y) -> bounds.contains(Offset(x, y)) } }
}
return Modifier.onGloballyPositioned { bounds = it.boundsInWindow() } to pointed
}
/** With no [icon] the button shows [label] itself, for a short word such as a keyboard mode. */
internal class XrPanelButton(val icon: ImageVector?, val label: String, val onClick: () -> Unit)
internal val XrCollapseIcon get() = Icons.Outlined.Remove
@@ -0,0 +1,271 @@
package com.droiddeck.launcher.session.xr
import android.app.Presentation
import android.content.Context
import android.hardware.display.DisplayManager
import android.hardware.display.VirtualDisplay
import android.os.Bundle
import android.os.SystemClock
import android.view.InputDevice
import android.view.MotionEvent
import android.view.Surface
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.view.inspector.WindowInspector
import android.widget.FrameLayout
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.platform.LocalTextInputService
import androidx.compose.ui.text.input.TextInputService
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
import androidx.activity.OnBackPressedDispatcher
import androidx.activity.OnBackPressedDispatcherOwner
import androidx.activity.setViewTreeOnBackPressedDispatcherOwner
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.ViewModelStoreOwner
import androidx.lifecycle.setViewTreeLifecycleOwner
import androidx.lifecycle.setViewTreeViewModelStoreOwner
import androidx.savedstate.SavedStateRegistry
import androidx.savedstate.SavedStateRegistryController
import androidx.savedstate.SavedStateRegistryOwner
import androidx.savedstate.setViewTreeSavedStateRegistryOwner
import com.droiddeck.launcher.ui.LocalPresentationWindow
/** Keeps a panel's Compose content running while the activity that made it is stopped behind the XR view. */
private class PanelOwner : LifecycleOwner, SavedStateRegistryOwner, ViewModelStoreOwner, OnBackPressedDispatcherOwner {
private val registry = LifecycleRegistry(this)
private val saved = SavedStateRegistryController.create(this)
override val lifecycle: Lifecycle get() = registry
override val savedStateRegistry: SavedStateRegistry get() = saved.savedStateRegistry
override val viewModelStore = ViewModelStore()
override val onBackPressedDispatcher = OnBackPressedDispatcher()
fun own(view: View) {
view.setViewTreeLifecycleOwner(this)
view.setViewTreeSavedStateRegistryOwner(this)
view.setViewTreeViewModelStoreOwner(this)
view.setViewTreeOnBackPressedDispatcherOwner(this)
}
init {
saved.performRestore(null)
registry.currentState = Lifecycle.State.RESUMED
}
fun destroy() {
registry.currentState = Lifecycle.State.DESTROYED
viewModelStore.clear()
}
}
/**
* One floating panel's Android side: a private virtual display drawing into the panel's OpenXR
* surface, and a presentation on it holding the Compose content. Main thread only.
*/
internal class XrPanelWindow(
private val context: Context,
private var surface: Surface,
width: Int,
height: Int,
startPaused: Boolean,
private val content: @Composable () -> Unit,
) {
private var paused = startPaused
private val owner = PanelOwner()
private val textInput = TextInputService(XrTextInput())
private val display: VirtualDisplay = context.getSystemService(DisplayManager::class.java).createVirtualDisplay(
"DroidDeck XR panel", width, height, XrUnits.DPI, surface.takeUnless { paused }, DisplayManager.VIRTUAL_DISPLAY_FLAG_OWN_CONTENT_ONLY,
)
private val presentation = PanelPresentation(context, display.display)
private var downTime = 0L
private var target: View? = null
/** The controllers pressing the panel, by hand, as fingers of one touch. */
private val touches = linkedMapOf<Int, Pair<Float, Float>>()
private var hovering: View? = null
private var hoverAt = 0f to 0f
private var cursor: Pair<Float, Float>? = null
init {
try {
presentation.show()
} catch (failure: RuntimeException) {
release()
throw failure
}
}
val displayId: Int get() = display.display.displayId
fun resize(surface: Surface, width: Int, height: Int) {
this.surface = surface
if (!paused) display.surface = surface
display.resize(width, height, XrUnits.DPI)
}
/** Stops drawing into the panel's layer, or starts again. */
fun pause(pause: Boolean) {
if (pause == paused) return
paused = pause
display.surface = if (pause) null else surface
}
fun release() {
runCatching { presentation.dismiss() }
owner.destroy()
display.release()
}
private inner class PanelPresentation(outer: Context, display: android.view.Display) : Presentation(outer, display) {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
window?.setBackgroundDrawableResource(android.R.color.transparent)
window?.addFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED)
val compose = ComposeView(context).apply {
owner.own(this)
setContent {
CompositionLocalProvider(
LocalPresentationWindow provides true,
LocalTextInputService provides textInput,
) { content() }
}
}
val frame = FrameLayout(context).apply {
addView(compose, FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
}
setContentView(frame)
window?.decorView?.let(owner::own)
}
}
/**
* The topmost window on this panel's display under the point, so popups and dialogs get the input.
* A focusable popup or dialog on top takes a press outside it too, as on a touchscreen, where it
* dismisses itself rather than letting the press act on what is behind it.
*/
private fun rootAt(x: Float, y: Float): View? {
val roots = WindowInspector.getGlobalWindowViews().filter { it.isAttachedToWindow && it.display?.displayId == displayId && it.isShown }
val location = IntArray(2)
fun contains(root: View): Boolean {
root.getLocationOnScreen(location)
return x >= location[0] && y >= location[1] && x < location[0] + root.width && y < location[1] + root.height
}
val top = roots.lastOrNull() ?: return null
val focusable = (top.layoutParams as? WindowManager.LayoutParams)
?.let { it.flags and WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE == 0 } ?: false
if (roots.size > 1 && focusable && !contains(top)) return top
return roots.lastOrNull(::contains) ?: top
}
/** Sends every finger in [touches] to [target]; [action] is already shifted by its pointer index where it needs one. */
private fun sendTouches(action: Int, time: Long) {
val view = target ?: return
val location = IntArray(2)
view.getLocationOnScreen(location)
val properties = touches.keys.map { hand ->
MotionEvent.PointerProperties().apply { id = hand; toolType = MotionEvent.TOOL_TYPE_FINGER }
}.toTypedArray()
val coords = touches.values.map { (x, y) ->
MotionEvent.PointerCoords().apply { this.x = x - location[0]; this.y = y - location[1]; pressure = 1f; size = 1f }
}.toTypedArray()
val event = MotionEvent.obtain(downTime, time, action, touches.size, properties, coords, 0, 0, 1f, 1f, 0, 0,
InputDevice.SOURCE_TOUCHSCREEN, 0)
try {
view.dispatchTouchEvent(event)
} finally {
event.recycle()
}
}
private fun indexed(action: Int, hand: Int) =
action or (touches.keys.indexOf(hand) shl MotionEvent.ACTION_POINTER_INDEX_SHIFT)
private fun send(view: View, action: Int, x: Float, y: Float, time: Long, generic: Boolean, scroll: Float = 0f): Boolean {
val location = IntArray(2)
view.getLocationOnScreen(location)
val properties = arrayOf(MotionEvent.PointerProperties().apply {
id = 0
toolType = if (generic) MotionEvent.TOOL_TYPE_MOUSE else MotionEvent.TOOL_TYPE_FINGER
})
val coords = arrayOf(MotionEvent.PointerCoords().apply {
this.x = x - location[0]
this.y = y - location[1]
pressure = 1f
size = 1f
if (scroll != 0f) setAxisValue(MotionEvent.AXIS_VSCROLL, scroll)
})
val source = if (generic) InputDevice.SOURCE_MOUSE else InputDevice.SOURCE_TOUCHSCREEN
val event = MotionEvent.obtain(if (generic) time else downTime, time, action, 1, properties, coords, 0, 0, 1f, 1f, 0, 0, source, 0)
return try {
if (generic) view.dispatchGenericMotionEvent(event) else view.dispatchTouchEvent(event)
} finally {
event.recycle()
}
}
/** The laser resting on the panel, as a mouse hovering, so keys and buttons light under it. Null: it left. */
fun hover(at: Pair<Float, Float>?) {
cursor = at
if (target != null) return
val now = SystemClock.uptimeMillis()
val root = at?.let { (x, y) -> rootAt(x, y) }
if (root !== hovering) endHover(now)
if (root == null || at == null) return
if (hovering == null) send(root, MotionEvent.ACTION_HOVER_ENTER, at.first, at.second, now, generic = true)
send(root, MotionEvent.ACTION_HOVER_MOVE, at.first, at.second, now, generic = true)
hovering = root
hoverAt = at
}
private fun endHover(now: Long) {
hovering?.let { send(it, MotionEvent.ACTION_HOVER_EXIT, hoverAt.first, hoverAt.second, now, generic = true) }
hovering = null
}
fun pointer(event: XrPointerEvent) {
val now = SystemClock.uptimeMillis()
when (event) {
is XrPointerEvent.Down -> {
if (event.hand in touches) return
touches[event.hand] = event.x to event.y
if (touches.size == 1) {
endHover(now)
downTime = now
target = rootAt(event.x, event.y)
sendTouches(MotionEvent.ACTION_DOWN, now)
} else sendTouches(indexed(MotionEvent.ACTION_POINTER_DOWN, event.hand), now)
}
is XrPointerEvent.Move -> {
if (event.hand !in touches) return
touches[event.hand] = event.x to event.y
sendTouches(MotionEvent.ACTION_MOVE, now)
}
is XrPointerEvent.Up -> {
if (event.hand !in touches) return
touches[event.hand] = event.x to event.y
if (touches.size > 1) {
sendTouches(indexed(MotionEvent.ACTION_POINTER_UP, event.hand), now)
touches -= event.hand
} else {
sendTouches(MotionEvent.ACTION_UP, now)
touches.clear()
target = null
hover(cursor)
}
}
is XrPointerEvent.Cancel -> {
if (event.hand !in touches) return
sendTouches(MotionEvent.ACTION_CANCEL, now)
touches.clear()
target = null
}
is XrPointerEvent.Scroll -> rootAt(event.x, event.y)?.let {
send(it, MotionEvent.ACTION_SCROLL, event.x, event.y, now, generic = true, scroll = event.amount)
}
else -> Unit
}
}
}
@@ -0,0 +1,611 @@
package com.droiddeck.launcher.session.xr
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import android.util.Log
import android.view.Surface
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.KeyboardHide
import androidx.compose.runtime.Composable
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.agent.AgentHost
import com.droiddeck.launcher.session.QuestExperimental
import com.droiddeck.launcher.ui.AgentPage
import com.droiddeck.launcher.ui.AgentPet
import com.droiddeck.launcher.ui.DroidDeckTheme
import com.droiddeck.launcher.ui.PcKeyboard
import com.droiddeck.launcher.ui.PetFigure
import com.droiddeck.launcher.ui.TypingRequest
import com.droiddeck.launcher.ui.petStateNow
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import java.lang.ref.WeakReference
import java.nio.ByteBuffer
import java.util.concurrent.ConcurrentLinkedQueue
import kotlin.math.PI
/** The 2D session window, which hands its menu to the immersive view while that is open. */
internal interface XrMenuHost {
@Composable
fun XrMenuContent()
fun xrSetMenuOpen(open: Boolean)
fun xrMenuBack()
/** A key of DroidDeck's PC keyboard, by Linux key code, to the game. */
fun xrSendKey(code: Int, down: Boolean)
/** Text from the laser keyboard to the game, as the Android keyboard sends it. */
fun xrTypeText(text: String)
fun xrTapKey(keyCode: Int)
/** The immersive view opened or closed; Steam's screen, which SteamVR mirrors as its Steam window, sizes for it. */
fun xrImmersiveChanged(active: Boolean)
}
/** What the immersive view's native loop offers: surface-backed layers it composites in front of the game. */
internal interface XrLayerSource {
val context: Context
fun createLayer(width: Int, height: Int): Int
fun layerSurface(id: Int): Surface?
fun destroyLayer(id: Int)
fun setOrbImage(image: android.graphics.Bitmap)
fun leave()
}
/**
* DroidDeck's own windows inside the immersive Quest view: the session menu, opened by holding the
* controllers together, and the agent pet with its chat. Quest only. [frame] runs on the XR thread
* each frame; the rest runs on the main thread.
*/
internal object XrPanels {
private const val TAG = "XrPanels"
private const val OPEN_MS = 350f
private const val CLOSE_MS = 250f
private const val BURST_MS = 400f
/** The immersive view is up, so the menu and pet belong in it. Always false off Quest. */
@Volatile
var immersiveActive = false
/** Counts attachments, so work posted from one immersive view is dropped once a later one, or none, is up. */
@Volatile
private var attachment = 0
private set
private val main = Handler(Looper.getMainLooper())
/** Whether the headset shows the session; panels draw into their layers only then. */
@Volatile
private var drawing = false
private val lock = Any()
private val ops = ConcurrentLinkedQueue<() -> Unit>()
private var source: XrLayerSource? = null
private var host: XrHost? = null
private var menuHost: WeakReference<XrMenuHost>? = null
private var scope: CoroutineScope? = null
private class Panel(val state: XrPanelState, val content: @Composable (State<List<Pair<Float, Float>>>) -> Unit) {
val cursorState = mutableStateOf<List<Pair<Float, Float>>>(emptyList())
var layerId = -1
var window: XrPanelWindow? = null
var openedMs = 0L
var closingMs = 0L
var resizing = false
var cursor: List<Pair<Float, Float>> = emptyList()
}
private val panels = mutableListOf<Panel>()
private val gesture = XrGesture()
private val interaction = XrInteraction()
private var lastFrameMs = 0L
private var orbImageSent = false
private var lastHead = Pose()
private var burstMs = 0L
private var burstAt = Vec3.ZERO
private var lastTick = 0
private var menuFrom: Vec3? = null
private val typing = mutableStateOf<TypingRequest?>(null)
/** The keyboard was opened for the game, from the session menu; a panel's text field takes it over while it types. */
private val gameKeyboard = mutableStateOf(false)
private val pcKeyboard = mutableStateOf(false)
fun gateOpen(model: String, device: String, manufacturer: String, immersive: Boolean) =
immersive && QuestExperimental.supported(model, device, manufacturer)
fun setMenuHost(menu: XrMenuHost?) {
menuHost = menu?.let { WeakReference(it) }
if (immersiveActive) menu?.xrImmersiveChanged(true)
}
fun clearMenuHost(menu: XrMenuHost) {
if (menuHost?.get() === menu) menuHost = null
}
/** Main thread: the immersive view handed over its buffers. */
fun attach(layers: XrLayerSource, state: ByteBuffer, control: ByteBuffer) {
if (!QuestExperimental.isSupported()) return
synchronized(lock) {
source = layers
host = XrHost(state, control)
orbImageSent = false
}
attachment++
immersiveActive = true
menuHost?.get()?.xrImmersiveChanged(true)
scope?.cancel()
scope = MainScope().also { scope ->
scope.launch {
snapshotFlow { com.droiddeck.launcher.agent.AgentGuest.focusRevision }.collect {
menuHost?.get()?.xrImmersiveChanged(true)
}
}
scope.launch {
snapshotFlow { AgentPet.enabled && AgentHost.installed }.collect { on ->
if (on) { if (!shown(XrPanelKind.PET_CHAT)) open(XrPanelKind.PET_HEAD) }
else { close(XrPanelKind.PET_HEAD); close(XrPanelKind.PET_CHAT) }
}
}
}
}
/**
* XR thread, as the session becomes visible or stops being so. OpenXR allows writing into a surface
* swapchain only while the session is visible or focused, and requires the writes to have stopped
* before xrEndSession, so this returns once the panels have stopped or started drawing.
*/
fun setDrawing(visible: Boolean) {
val done = java.util.concurrent.CountDownLatch(1)
val apply = Runnable {
try {
drawing = visible
synchronized(lock) { panels.mapNotNull { it.window } }.forEach { it.pause(!visible) }
} finally {
done.countDown()
}
}
if (Looper.myLooper() == Looper.getMainLooper()) apply.run()
else if (main.post(apply) && !done.await(1, java.util.concurrent.TimeUnit.SECONDS))
Log.w(TAG, "panels did not ${if (visible) "start" else "stop"} drawing within a second")
}
/** Main thread: the immersive view is going; every panel goes with it. */
fun detach() {
if (!immersiveActive) return
immersiveActive = false
scope?.cancel()
scope = null
val windows = synchronized(lock) {
source = null
host = null
ops.clear()
interaction.reset()
panels.mapNotNull { it.window }.also { panels.clear() }
}
windows.forEach { it.release() }
typing.value = null
gameKeyboard.value = false
gesture.reset(release = false)
menuHost?.get()?.xrSetMenuOpen(false)
menuHost?.get()?.xrImmersiveChanged(false)
}
/** Main thread, from the session window's menu state. */
fun showMenu(): Boolean {
if (!immersiveActive) return false
open(XrPanelKind.MENU, menuFrom)
menuFrom = null
return true
}
fun hideMenu() = close(XrPanelKind.MENU)
/** Main thread: closes the immersive view, as a stop chosen in its menu asks. */
fun leaveImmersive() {
synchronized(lock) { source }?.leave()
}
/** Main thread: a text field in a panel wants typing, so the laser keyboard opens. */
fun startTyping(request: TypingRequest) {
if (!immersiveActive) return
typing.value = request
open(XrPanelKind.KEYBOARD)
}
fun stopTyping(request: TypingRequest) {
if (typing.value !== request) return
typing.value = null
if (!gameKeyboard.value) close(XrPanelKind.KEYBOARD)
}
/**
* Main thread: the session menu's keyboards. [pc] picks DroidDeck's PC keyboard over the Android-style one;
* asking again for the one already open closes it. False off the immersive view, where the 2D keyboards stay.
*/
fun toggleGameKeyboard(pc: Boolean): Boolean {
if (!immersiveActive) return false
if (gameKeyboard.value && pcKeyboard.value == pc && shown(XrPanelKind.KEYBOARD)) hideKeyboard()
else showGameKeyboard(pc)
return true
}
fun showGameKeyboard(pc: Boolean): Boolean {
if (!immersiveActive) return false
gameKeyboard.value = true
pcKeyboard.value = pc
open(XrPanelKind.KEYBOARD)
return true
}
private fun hideKeyboard() {
typing.value = null
gameKeyboard.value = false
close(XrPanelKind.KEYBOARD)
}
private fun shown(kind: XrPanelKind) = synchronized(lock) { panels.any { it.state.kind == kind && it.closingMs == 0L } }
private fun open(kind: XrPanelKind, from: Vec3? = null) {
ops += { create(kind, from) }
}
private fun close(kind: XrPanelKind) {
ops += {
panels.filter { it.state.kind == kind && it.closingMs == 0L }.forEach { panel ->
panel.closingMs = SystemClock.uptimeMillis()
val out = XrInteractionOut()
interaction.release(panel.state, out)
dispatch(out)
}
}
}
/** XR thread. */
private fun create(kind: XrPanelKind, from: Vec3?) {
val layers = source ?: return
panels.firstOrNull { it.state.kind == kind }?.let { existing ->
if (existing.closingMs != 0L) {
existing.closingMs = 0L
val elapsed = 1f - Math.cbrt((1.0 - existing.state.scale).coerceIn(0.0, 1.0)).toFloat()
existing.openedMs = SystemClock.uptimeMillis() - (elapsed * OPEN_MS).toLong()
}
return
}
val placed = XrPlacement.load(layers.context, kind, lastHead)
val state = XrPanelState(kind, placed.pose, placed.width, placed.height)
state.scale = 0f
state.animationFrom = from ?: placed.pose.position
val id = layers.createLayer(state.pixelWidth, state.pixelHeight)
val surface = if (id >= 0) layers.layerSurface(id) else null
if (surface == null) {
Log.w(TAG, "no layer for the ${kind.key} panel")
if (id >= 0) layers.destroyLayer(id)
if (kind == XrPanelKind.MENU) main.post { menuHost?.get()?.xrSetMenuOpen(false) }
return
}
val panel = Panel(state, contentFor(kind))
panel.layerId = id
panel.openedMs = SystemClock.uptimeMillis()
panels += panel
val context = layers.context
main.post {
synchronized(lock) {
if (panel !in panels) return@post
panel.window = runCatching {
XrPanelWindow(context, surface, state.pixelWidth, state.pixelHeight, startPaused = !drawing) {
panel.content(panel.cursorState)
}
}.onFailure {
Log.w(TAG, "could not show the ${kind.key} panel", it)
panels -= panel
ops += { if (source === layers) layers.destroyLayer(id) }
if (kind == XrPanelKind.MENU) menuHost?.get()?.xrSetMenuOpen(false)
}.getOrNull()
}
}
}
private fun contentFor(kind: XrPanelKind): @Composable (State<List<Pair<Float, Float>>>) -> Unit = when (kind) {
XrPanelKind.MENU -> { cursor ->
DroidDeckTheme {
XrPanelChrome(cursor, buttons = emptyList(), resizable = true) {
menuHost?.get()?.XrMenuContent()
}
}
}
XrPanelKind.PET_HEAD -> { _ ->
DroidDeckTheme { Box(Modifier.fillMaxSize()) { PetFigure(petStateNow(), Modifier.fillMaxSize()) } }
}
XrPanelKind.KEYBOARD -> { cursor ->
DroidDeckTheme {
val buttons = listOf(
XrPanelButton(Icons.Outlined.KeyboardHide, stringResource(R.string.pckb_hide), ::hideKeyboard),
XrPanelButton(null, if (pcKeyboard.value) "Android" else "PC") { pcKeyboard.value = !pcKeyboard.value },
)
XrPanelChrome(cursor, buttons, resizable = true) { KeyboardContent() }
}
}
XrPanelKind.PET_CHAT -> { cursor ->
DroidDeckTheme {
XrPanelChrome(cursor, listOf(XrPanelButton(XrCollapseIcon, stringResource(R.string.bottom_chat_close), ::collapseChat)), resizable = true) {
AgentPage(Modifier.fillMaxSize().padding(horizontal = 12.dp), visible = true, startTyping = false, hidesPet = false)
}
}
}
}
/** A panel's text field takes the keyboard while it types; otherwise its keys go to the game. */
@Composable
private fun KeyboardContent() {
val request = typing.value
val host = menuHost?.get()?.takeIf { gameKeyboard.value }
val target = request?.let(::XrFieldTarget) ?: host?.let(::XrGameTarget) ?: return
if (pcKeyboard.value) {
val pcText = remember(request) { request?.let { XrPcText(XrFieldTarget(it)) } }
PcKeyboard(
sendKey = { code, down -> pcText?.key(code, down) ?: host?.xrSendKey(code, down) },
onAndroidKeyboard = { pcKeyboard.value = false },
onClose = ::hideKeyboard,
heightFraction = 1f,
showButtons = false,
hoverFeedback = true,
)
} else XrKeyboard(target)
}
private fun collapseChat() {
close(XrPanelKind.PET_CHAT)
open(XrPanelKind.PET_HEAD)
}
private fun expandChat(from: Vec3) {
close(XrPanelKind.PET_HEAD)
open(XrPanelKind.PET_CHAT, from)
}
/** XR thread, once per frame, from QuestXrActivity.onXrHostFrame. */
fun frame() = synchronized(lock) {
val host = host ?: return
val layers = source ?: return
val frame = host.read()
lastHead = frame.head
while (true) (ops.poll() ?: break).invoke()
if (!orbImageSent) {
orbImageSent = true
runCatching {
android.graphics.BitmapFactory.decodeResource(layers.context.resources, R.drawable.logo)
}.getOrNull()?.let { layers.setOrbImage(it); it.recycle() }
}
val now = SystemClock.uptimeMillis()
val dt = if (lastFrameMs == 0L) 0f else ((now - lastFrameMs) / 1000f).coerceIn(0f, 0.1f)
lastFrameMs = now
val control = XrControlOut()
animate(now, layers)
val active = panels.filter { it.closingMs == 0L && it.window != null }
if (frame.focused) {
if (gesture.update(frame.hands[0], frame.hands[1], now)) {
burstMs = now
burstAt = gesture.midpoint
lastTick = 0
for (hand in 0..1) control.haptics[hand] = XrHaptic(60, 0.9f)
val from = gesture.midpoint
val posted = attachment
main.post { if (immersiveActive && posted == attachment) toggleMenu(from) }
} else if (gesture.phase == XrGesture.Phase.ARMING) {
val step = (gesture.progress * 4).toInt()
if (step > lastTick) for (hand in 0..1) control.haptics[hand] = XrHaptic(18, 0.2f + 0.15f * step)
lastTick = step
} else lastTick = 0
val out = interaction.update(frame.head, frame.hands, active.map { it.state }, dt)
for (hand in 0..1) {
control.masks[hand] = out.masks[hand]
control.lasers[hand] = out.lasers[hand]
if (out.ticks[hand] && control.haptics[hand] == null) control.haptics[hand] = XrHaptic(12, 0.35f)
}
dispatch(out)
} else {
gesture.reset(release = false)
val out = XrInteractionOut()
interaction.cancel(out)
dispatch(out)
}
control.orb = orb(now)
panels.forEachIndexed { index, panel ->
if (panel.layerId < 0 || panel.window == null) return@forEachIndexed
val state = panel.state
control.layers += XrLayerOut(panel.layerId, state.shownPose, state.width * state.scale, state.height * state.scale,
order = if (state.kind == XrPanelKind.PET_HEAD) 100 else index)
}
host.write(control)
}
private fun orb(now: Long): XrControlOut.Orb? {
if (gesture.phase == XrGesture.Phase.ARMING)
return XrControlOut.Orb(gesture.midpoint, 0.02f + 0.01f * gesture.progress, gesture.progress, 0f)
val burst = (now - burstMs) / BURST_MS
if (burstMs != 0L && burst < 1f) return XrControlOut.Orb(burstAt, 0.03f, 1f, burst.coerceAtLeast(0.01f))
return null
}
private fun animate(now: Long, layers: XrLayerSource) {
val gone = mutableListOf<Panel>()
for (panel in panels) {
val state = panel.state
if (panel.closingMs != 0L) {
val t = ((now - panel.closingMs) / CLOSE_MS).coerceIn(0f, 1f)
state.scale = minOf(state.scale, 1f - easeOut(t))
if (state.animationFrom == null) state.animationFrom = state.pose.position
if (t >= 1f) gone += panel
} else if (state.scale < 1f) {
state.scale = easeOut(((now - panel.openedMs) / OPEN_MS).coerceIn(0f, 1f))
if (state.scale >= 1f) state.animationFrom = null
}
}
for (panel in gone) {
panels -= panel
if (panel.layerId >= 0) layers.destroyLayer(panel.layerId)
val window = panel.window
val context = layers.context
val state = panel.state
val head = lastHead
main.post {
window?.release()
XrPlacement.save(context, state.kind, head, state.pose, state.width, state.height)
}
}
}
private fun easeOut(t: Float) = 1f - (1f - t) * (1f - t) * (1f - t)
/** XR thread: hands each panel its input on the main thread and follows up on moves and resizes. */
private fun dispatch(out: XrInteractionOut) {
val layers = source ?: return
for (panel in panels) {
val cursor = out.cursors[panel.state]?.toList().orEmpty()
if (cursor != panel.cursor) {
panel.cursor = cursor
val target = panel.cursorState
val window = panel.window
main.post {
target.value = cursor
window?.hover(cursor.firstOrNull())
}
}
}
for (event in out.events) {
val panel = panels.firstOrNull { it.state === event.panel } ?: continue
when (event) {
is XrPointerEvent.Back -> main.post { back(panel.state.kind) }
is XrPointerEvent.Click -> {
val from = panel.state.pose.position
main.post { expandChat(from) }
}
is XrPointerEvent.Resized -> {
savePlacement(panel, layers)
resize(panel, layers)
}
is XrPointerEvent.Moved -> savePlacement(panel, layers)
else -> {
val window = panel.window
main.post { window?.pointer(event) }
}
}
}
}
/** XR thread: the place a move or resize ended at, read together now and saved on the main thread. */
private fun savePlacement(panel: Panel, layers: XrLayerSource) {
val state = panel.state
val kind = state.kind
val head = lastHead
val pose = state.pose
val width = state.width
val height = state.height
val context = layers.context
main.post { XrPlacement.save(context, kind, head, pose, width, height) }
}
/** XR thread: gives a resized panel a surface of its new size once its content has moved over to it. */
private fun resize(panel: Panel, layers: XrLayerSource) {
val state = panel.state
val width = XrUnits.pixels(state.width)
val height = XrUnits.pixels(state.height)
if (width == state.pixelWidth && height == state.pixelHeight) return
val id = layers.createLayer(width, height)
val surface = if (id >= 0) layers.layerSurface(id) else null
if (surface == null) {
if (id >= 0) layers.destroyLayer(id)
return
}
val window = panel.window
main.post {
window?.resize(surface, width, height)
ops += {
if (panel in panels) {
val old = panel.layerId
panel.layerId = id
state.pixelWidth = width
state.pixelHeight = height
if (old >= 0) layers.destroyLayer(old)
} else if (source === layers) layers.destroyLayer(id)
}
}
}
/** Main thread. */
private fun toggleMenu(from: Vec3) {
val menu = menuHost?.get() ?: return
if (shown(XrPanelKind.MENU)) menu.xrSetMenuOpen(false)
else {
menuFrom = from
menu.xrSetMenuOpen(true)
}
}
/** Main thread: B on a panel goes back a step, as Back does in the 2D window. */
private fun back(kind: XrPanelKind) {
when (kind) {
XrPanelKind.MENU -> menuHost?.get()?.xrMenuBack()
XrPanelKind.PET_CHAT -> collapseChat()
XrPanelKind.PET_HEAD -> Unit
XrPanelKind.KEYBOARD -> hideKeyboard()
}
}
}
/** Where each panel kind was left, relative to where the user faced, so it comes back there. */
internal object XrPlacement {
class Placed(val pose: Pose, val width: Float, val height: Float)
private class Default(val yaw: Float, val distance: Float, val dy: Float, val width: Float, val height: Float)
private val defaults = mapOf(
XrPanelKind.MENU to Default(0f, 0.95f, -0.12f, 0.9f, 0.6f),
XrPanelKind.PET_CHAT to Default(0.6f, 0.95f, -0.12f, 0.6f, 0.7f),
XrPanelKind.PET_HEAD to Default(0.7f, 0.75f, -0.45f, 0.12f, 0.12f),
XrPanelKind.KEYBOARD to Default(0f, 0.5f, -0.5f, 0.8f, 0.36f),
)
private fun prefs(context: Context) = context.getSharedPreferences("quest_xr_panels", Context.MODE_PRIVATE)
fun place(kind: XrPanelKind, head: Pose, yaw: Float, distance: Float, dy: Float): Pose {
val angle = yawOf(head.forward) + yaw
val direction = Quat.yaw(angle).rotate(Vec3.FORWARD)
val position = head.position + direction * distance + Vec3(0f, dy, 0f)
return Pose(kind.orient(position, head.position), position)
}
fun relative(head: Pose, position: Vec3): Triple<Float, Float, Float> {
val offset = position - head.position
val distance = Vec3(offset.x, 0f, offset.z).length
var yaw = yawOf(offset) - yawOf(head.forward)
while (yaw > PI) yaw -= (2 * PI).toFloat()
while (yaw < -PI) yaw += (2 * PI).toFloat()
return Triple(yaw, distance, offset.y)
}
fun load(context: Context, kind: XrPanelKind, head: Pose): Placed {
val fallback = defaults.getValue(kind)
val saved = prefs(context).getString(kind.key, null)?.split(',')?.mapNotNull { it.toFloatOrNull() }
val values = saved?.takeIf { it.size == 5 } ?: listOf(fallback.yaw, fallback.distance, fallback.dy, fallback.width, fallback.height)
val distance = values[1].coerceIn(XrUnits.MIN_DISTANCE, XrUnits.MAX_DISTANCE)
val width = if (kind.resizable) values[3].coerceIn(XrUnits.MIN_METRES, XrUnits.MAX_METRES) else fallback.width
val height = if (kind.resizable) values[4].coerceIn(XrUnits.MIN_METRES, XrUnits.MAX_METRES) else fallback.height
return Placed(place(kind, head, values[0], distance, values[2].coerceIn(-1.5f, 1.5f)), width, height)
}
fun save(context: Context, kind: XrPanelKind, head: Pose, pose: Pose, width: Float, height: Float) {
val (yaw, distance, dy) = relative(head, pose.position)
prefs(context).edit().putString(kind.key, listOf(yaw, distance, dy, width, height).joinToString(",")).apply()
}
}
@@ -0,0 +1,16 @@
package com.droiddeck.launcher.session.xr
/** Whether the guest's focus report shows Steam's own screen, with no game holding a window. */
internal object XrSteamScreen {
/** Steam's own UI and SteamVR, which have windows of their own but are not games. */
private val STEAM_APPS = setOf(769L, 250820L)
/**
* Gamescope lists Steam itself while its screen is up, so a report naming no app at all, as the guest
* writes when it could not collect focus or gamescope has not published it, says nothing.
*/
fun shown(focusedApp: Long?, focusableApps: List<Long>?): Boolean {
val apps = (listOfNotNull(focusedApp) + focusableApps.orEmpty()).filter { it > 0 }
return apps.isNotEmpty() && apps.all { it in STEAM_APPS }
}
}
@@ -121,6 +121,8 @@ object StoresState {
var unfinished by mutableStateOf<List<StoreInstallRoot.Unfinished>>(emptyList())
internal set
var steamPicking by mutableStateOf<CatalogItem?>(null)
fun isUnfinished(item: CatalogItem): Boolean = unfinished.any {
it.store == item.store && (it.id == item.id || (it.id == null && it.folder.name == StoreInstallRoot.folderName(item.title, item.id)))
}
@@ -14,9 +14,14 @@ internal object WebCookies {
}
}
fun scopes(url: String, paths: List<String>): List<String> {
val segments = runCatching { java.net.URI(url).path }.getOrNull().orEmpty().split('/').filter { it.isNotEmpty() }
return (paths + segments.indices.map { i -> "/" + segments.take(i + 1).joinToString("/") }).distinct()
}
fun expire(urls: List<String>, domain: String, paths: List<String>, done: (Int) -> Unit) {
val cookies = CookieManager.getInstance()
val lines = urls.flatMap { url -> expired(cookies.getCookie(url), domain, paths, Uri.parse(url).host).map { url to it } }
val lines = urls.flatMap { url -> expired(cookies.getCookie(url), domain, scopes(url, paths), Uri.parse(url).host).map { url to it } }
if (lines.isEmpty()) {
done(0)
return
@@ -7,6 +7,7 @@ import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.AddedGames
import com.droiddeck.launcher.runtime.BattleNet
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.GameStorage
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.InstalledStoreGame
import com.droiddeck.launcher.stores.Store
@@ -130,13 +131,13 @@ object BattleNetClient {
StoresState.post { opener?.invoke(args) }
}
fun library(context: Context, root: File = preferred(context)): List<String> =
AddedGames.guestPath(context, StoreInstallRoot.storeDir(root, Store.BATTLENET))?.let { listOf("--library", it) }.orEmpty()
fun library(context: Context, root: File? = preferred(context)): List<String> =
root?.let { AddedGames.guestPath(context, StoreInstallRoot.storeDir(it, Store.BATTLENET)) }?.let { listOf("--library", it) }.orEmpty()
internal fun preferred(context: Context): File {
internal fun preferred(context: Context): File? {
val second = StoreInstallRoot.libraryRoot(context)?.absolutePath
return StoreInstallRoot.targets(context).firstOrNull { it.root.absolutePath == second && (it.root.isDirectory || it.root.mkdirs()) }?.root
?: StoreInstallRoot.internalRoot(context)
?: StoreInstallRoot.internalRoot(context).takeIf { second == null && !GameStorage.disconnected(context) }
}
fun installGame(context: Context, uid: String, root: File) {
@@ -44,7 +44,7 @@ object EaBackend : StoreBackend {
signOuts.incrementAndGet()
StoresState.post { StoresState.shelves.remove(store) }
EaUpdates.available.clear()
runCatching { WebCookies.expire(EaLogin.SIGN_IN_URLS, ".ea.com", listOf("/")) {} }
EaLogin.forget {}
}
override fun syncLibrary(context: Context, force: Boolean) {
@@ -100,9 +100,7 @@ internal class EaLogin(private val pending: EaAuth.Pending, override val userAge
override fun isRedirect(url: String): Boolean = url.startsWith("qrc:", ignoreCase = true)
override fun forgetSignIn(done: () -> Unit) {
runCatching { WebCookies.expire(SIGN_IN_URLS, ".ea.com", listOf("/")) { done() } }.onFailure { done() }
}
override fun forgetSignIn(done: () -> Unit) = forget(done)
override fun finish(activity: StoreLoginActivity, view: WebView, url: String): String? {
val code = EaAuth.redirectValue(url, "code") ?: return activity.getString(R.string.stores_login_error_verification)
@@ -116,7 +114,11 @@ internal class EaLogin(private val pending: EaAuth.Pending, override val userAge
}
companion object {
val SIGN_IN_URLS = listOf("https://accounts.ea.com", "https://signin.ea.com", "https://www.ea.com")
val SIGN_IN_URLS = listOf(EaAuth.AUTH_URL, "https://signin.ea.com/p/juno/login", "https://www.ea.com")
fun forget(done: () -> Unit) {
runCatching { WebCookies.expire(SIGN_IN_URLS, ".ea.com", listOf("/")) { done() } }.onFailure { done() }
}
}
}
@@ -67,7 +67,7 @@ object EaLsx {
}
@Volatile var game: Game? = null
@Volatile private var account: Account? = null
@Volatile internal var account: Account? = null
/** The one session of the current launch that may act for the account. */
/** Bumped whenever the launch changes; a connection accepted under an older one is not admitted. */
@Volatile internal var generation = 0
@@ -333,10 +333,11 @@ object EaLsx {
private fun now() = LocalDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"))
private fun answer(session: Session, m: Message): String? {
internal fun answer(session: Session, m: Message): String? {
val g = game
val who = account
val person = who?.takeIf { session.trusted }
val profile = who?.takeIf { session.trusted || session.claimed }
val locale = g?.locale ?: "en_US"
return when (m.name) {
"ChallengeResponse" -> {
@@ -355,15 +356,16 @@ object EaLsx {
"GetConfig" -> tag("GetConfigResponse", body = SERVICES.joinToString("") { tag("Service", "Name" to it.first, "Facility" to it.second) })
"GetProfile" -> tag(
"GetProfileResponse",
"Persona" to person?.persona.orEmpty(), "SubscriberLevel" to 0, "CommerceCurrency" to "USD", "IsTrialSubscriber" to false,
"Country" to "US", "UserId" to person?.userId.orEmpty(), "GeoCountry" to "US", "AvatarId" to "", "IsSubscriber" to false,
"IsSteamSubscriber" to false, "PersonaId" to person?.personaId.orEmpty(), "IsUnderAge" to false, "UserIndex" to 0,
"Persona" to profile?.persona.orEmpty(), "SubscriberLevel" to 0, "CommerceCurrency" to "USD", "IsTrialSubscriber" to false,
"Country" to "US", "UserId" to profile?.userId.orEmpty(), "GeoCountry" to "US", "AvatarId" to "", "IsSubscriber" to false,
"IsSteamSubscriber" to false, "PersonaId" to profile?.personaId.orEmpty(), "IsUnderAge" to false, "UserIndex" to 0,
)
"GetSetting" -> tag("GetSettingResponse", "Setting" to when (m.attrs["SettingId"]) {
"ENVIRONMENT" -> "production"
"LANGUAGE" -> locale
else -> "false"
})
"GetSettings" -> tag("GetSettingsResponse", "IsIGOAvailable" to false, "IsIGOEnabled" to false, "IsTelemetryEnabled" to false, "IsManualOffline" to false)
"GetGameInfo" -> tag("GetGameInfoResponse", "GameInfo" to when (m.attrs["GameInfoId"]) {
"FREETRIAL" -> "false"
"LANGUAGES" -> LANGUAGES
@@ -403,7 +405,7 @@ object EaLsx {
)
})
}
"GetPresence" -> tag("GetPresenceResponse", "UserId" to person?.userId.orEmpty(), "Presence" to "INGAME")
"GetPresence" -> tag("GetPresenceResponse", "UserId" to profile?.userId.orEmpty(), "Presence" to "INGAME")
"QueryPresence" -> tag("QueryPresenceResponse", body = "")
"QueryFriends" -> tag("QueryFriendsResponse", body = "")
"GetBlockList" -> tag("GetBlockListResponse", "Return" to "Success", body = "")
@@ -6,9 +6,6 @@ import android.net.Uri
import android.util.Log
import android.widget.Toast
import androidx.annotation.StringRes
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.session.SessionService
@@ -46,8 +43,6 @@ internal object SteamStore {
/** InvalidPassword, AccessDenied, AccountNotFound, Revoked, Expired, AccountLogonDenied. */
private val REFUSALS = setOf(5, 15, 18, 26, 27, 63)
var picking by mutableStateOf<CatalogItem?>(null)
class Plan(val installDir: String, val downloadBytes: Long, val installBytes: Long, val buildId: String, val linuxBuild: Boolean) {
companion object {
fun of(json: JSONObject): Plan? {
@@ -222,7 +217,7 @@ internal object SteamStore {
toast(context, R.string.steam_store_close_steam)
return
}
picking = item
StoresState.steamPicking = item
}
fun install(context: Context, item: CatalogItem, target: SteamClient.Target) {
@@ -8,6 +8,9 @@ import org.json.JSONObject
import java.time.Instant
internal object XboxCatalog {
/** Package identity prefix of Microsoft's original Xbox releases for PC. */
internal const val BACK_COMPAT_IDENTITY = "Xbox360BackwardCompatibil"
private val productId = Regex("[A-Z0-9]{12}")
private val plans = setOf("CFQ7TTC0KGQ8", "CFQ7TTC0KHS0", "CFQ7TTC0P85B", "CFQ7TTC0K5DJ", "CFQ7TTC0K6L8", "CFQ7TTC10QFD")
private val pcPlans = mapOf(
@@ -148,6 +151,13 @@ internal object XboxCatalog {
.flatMap { objects(it.optJSONArray("Packages")) }
val pc = packages.filter { pkg -> objects(pkg.optJSONArray("PlatformDependencies")).any { it.optString("PlatformName") == "Windows.Desktop" } }
val installable = pc.any { installableFormat(it.optString("PackageFormat")) }
// An original Xbox game: its PC package is only Microsoft's emulator and an
// index; the game data comes from the console package, so that is its size.
val backCompat = pc.any { it.optString("PackageFamilyName").startsWith(BACK_COMPAT_IDENTITY, ignoreCase = true) }
val console = packages.filter { pkg ->
pkg.optString("PackageFormat").equals("XVC", true) ||
objects(pkg.optJSONArray("PlatformDependencies")).any { it.optString("PlatformName") == "Windows.Xbox" }
}
// The installer needs the format, not just the fact that one exists: a
// legacy container takes a different subcommand from a streamed package.
val format = pc.firstOrNull { installableFormat(it.optString("PackageFormat")) }?.optString("PackageFormat").orEmpty()
@@ -172,7 +182,8 @@ internal object XboxCatalog {
storeUrl = "https://www.xbox.com/games/store/$id",
publisher = localized.optString("PublisherName"), developer = localized.optString("DeveloperName"),
description = localized.optString("ProductDescription"),
sizeBytes = if (installable) pc.maxOfOrNull { it.optLong("MaxDownloadSizeInBytes") } ?: 0L else 0L,
sizeBytes = if (!installable) 0L else (if (backCompat) console.maxOfOrNull { it.optLong("MaxDownloadSizeInBytes") } else null)
?.takeIf { it > 0 } ?: pc.maxOfOrNull { it.optLong("MaxDownloadSizeInBytes") } ?: 0L,
extra = mapOf("market" to Xodus.market(), "access" to kind.orEmpty(), "pc" to flag(installable),
"cloud" to flag(streams), "format" to format),
)
@@ -106,7 +106,7 @@ private fun PanelContent(
onChange(settings.copy(frameGen = it))
}
Text("Native engine (experimental): Google's WebRTC and DroidDeck's own compositor, so DroidDeck frame generation " +
"(DDFG) or LSFG can add frames. LSFG uses the Lossless.dll DroidDeck already uses for games. Screen effects " +
"(DDFG) or LSFG can add frames. LSFG requires Lossless Scaling installed through Steam. Screen effects " +
"apply to the web engine.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(start = 8.dp, bottom = 6.dp))
}
@@ -80,6 +80,10 @@ internal object XboxManifest {
dependencies.singleOrNull().orEmpty(), ids, entries, entry.singleOrNull().orEmpty(), behavior.singleOrNull().orEmpty())
}
/** Microsoft's original Xbox releases for PC, which run its emulator. */
fun backCompat(folder: File): Boolean =
runCatching { read(folder).name.startsWith(XboxCatalog.BACK_COMPAT_IDENTITY, ignoreCase = true) }.getOrDefault(false)
/**
* A full trust package starts its executable directly. Anything else is activated
* through the Windows app model, which this runtime has no host for, so starting
@@ -623,11 +623,11 @@ class XboxNativePlayerActivity : ComponentActivity() {
XboxMenuEntry((if (current.frameGen == mode) "✓ " else "") + fgName(mode), when (mode) {
XboxNativeVideo.FG_DDFG -> "DroidDeck's own frame generation (DDFG); doubles the shown frame rate"
XboxNativeVideo.FG_LSFG, XboxNativeVideo.FG_LSFG3, XboxNativeVideo.FG_LSFG4 ->
"Lossless Scaling frame generation (the Lossless.dll DroidDeck uses for games); the frame-rate target caps the output"
"Lossless Scaling frame generation from the Steam installation; the frame-rate target caps the output"
else -> "Show the stream's own frames only"
}, choices[i]) { current = current.copy(frameGen = mode); setFrameGen(mode) }
}
if (!lsfg) androidx.compose.material3.Text("LSFG appears here once DroidDeck has the Lossless.dll (frame generation settings).",
if (!lsfg) androidx.compose.material3.Text("LSFG appears here once Lossless Scaling is installed through Steam.",
style = androidx.compose.material3.MaterialTheme.typography.bodySmall, color = cs.onSurfaceVariant,
modifier = androidx.compose.ui.Modifier.padding(horizontal = 16.dp, vertical = 8.dp))
if (current.zeroCopy) androidx.compose.material3.Text(
@@ -78,7 +78,7 @@ internal fun AgentEntry(
is Entry.Said -> {
val reply = remember(entry.text) { choices(entry.text) }
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
if (reply.text.isNotBlank()) SelectionContainer { AgentMarkdown(reply.text, Modifier.widthIn(max = 760.dp).padding(horizontal = 4.dp)) }
if (reply.text.isNotBlank()) SelectionContainer { AgentReply(reply.text, Modifier.widthIn(max = 760.dp).padding(horizontal = 4.dp)) }
if (reply.options.isNotEmpty()) AgentChoices(reply.options, answerable, onSent)
}
}
@@ -377,10 +377,11 @@ private fun CodeBox(label: String, text: String, color: Color) {
internal fun AttachmentChip(path: String, onRemove: (() -> Unit)?) {
val context = LocalContext.current
val pal = LocalPalette.current
var viewing by remember(path) { mutableStateOf(false) }
Box {
if (AgentAttachments.isImage(path)) AsyncImage(
model = AgentAttachments.host(context, path), contentDescription = path.substringAfterLast('/'), contentScale = ContentScale.Crop,
modifier = Modifier.size(72.dp).clip(Shape12).background(pal.surfaceVariant),
modifier = Modifier.size(72.dp).clip(Shape12).background(pal.surfaceVariant).clickable { viewing = true },
) else Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.heightIn(min = 40.dp).clip(Shape12).background(pal.surfaceVariant).padding(horizontal = 10.dp, vertical = 8.dp),
@@ -396,4 +397,5 @@ internal fun AttachmentChip(path: String, onRemove: (() -> Unit)?) {
Icon(Icons.Outlined.Close, stringResource(R.string.agent_remove_attachment), tint = pal.onSurfaceVariant, modifier = Modifier.size(14.dp))
}
}
if (viewing) PictureViewer(AgentAttachments.host(context, path), path.substringAfterLast('/')) { viewing = false }
}
@@ -37,6 +37,106 @@ import org.commonmark.ext.gfm.tables.TableRow
import org.commonmark.node.AbstractVisitor
import org.commonmark.node.CustomNode
import org.commonmark.node.Node
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.widthIn
import androidx.compose.material3.Text
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
/** Part of an agent's reply: Markdown text, or an image the agent named on a line of its own. */
internal sealed interface ReplyPart {
data class Prose(val text: String) : ReplyPart
data class Picture(val alt: String, val path: String) : ReplyPart
}
private val PICTURE_LINE = Regex("""^\s*!\[([^\]]*)]\(\s*(?:<(?:file://)?(/[^>]*)>|(?:file://)?(/[^)<>]*?))\s*\)\s*$""")
private val FENCE = Regex("""^ {0,3}(`{3,}|~{3,})(.*)$""")
/** Splits [text] at lines that hold only an image of a local absolute path, outside code fences. */
internal fun replyParts(text: String): List<ReplyPart> {
val parts = mutableListOf<ReplyPart>()
val prose = StringBuilder()
fun flush() {
if (prose.isNotBlank()) parts += ReplyPart.Prose(prose.toString().trimEnd('\n'))
prose.clear()
}
var fence: String? = null
for (line in text.lines()) {
val marker = FENCE.matchEntire(line)
val picture = if (fence == null) PICTURE_LINE.matchEntire(line) else null
val open = fence
when {
picture != null -> {
flush()
val path = picture.groupValues[2].ifEmpty { picture.groupValues[3] }
parts += ReplyPart.Picture(picture.groupValues[1].trim(), path.trim())
continue
}
marker == null -> Unit
open == null -> fence = marker.groupValues[1]
marker.groupValues[1].let { it[0] == open[0] && it.length >= open.length } && marker.groupValues[2].isBlank() -> fence = null
}
prose.append(line).append('\n')
}
flush()
return parts
}
/**
* Where the app reads a file the agent named by its guest path: the app's own folders and shared
* storage are bound at the same paths in the guest, everything else lives in the rootfs.
*/
internal fun agentHostFile(context: Context, guestPath: String): File {
val app = context.applicationContext
val same = listOfNotNull(app.filesDir.path, app.cacheDir.path, LinuxRuntime.sharedStorage(app)?.path)
return if (same.any { guestPath == it || guestPath.startsWith("$it/") }) File(guestPath)
else File(LinuxRuntime.rootDir(app), guestPath.removePrefix("/"))
}
/** An agent's reply, with the images it names shown in place. */
@Composable
internal fun AgentReply(text: String, modifier: Modifier) {
val parts = remember(text) { replyParts(text) }
if (parts.size == 1 && parts[0] is ReplyPart.Prose) {
AgentMarkdown(text, modifier)
return
}
Column(modifier, verticalArrangement = Arrangement.spacedBy(8.dp)) {
parts.forEach { part ->
when (part) {
is ReplyPart.Prose -> AgentMarkdown(part.text, Modifier)
is ReplyPart.Picture -> AgentPicture(part)
}
}
}
}
@Composable
private fun AgentPicture(picture: ReplyPart.Picture) {
val context = LocalContext.current
val file = remember(picture.path) { agentHostFile(context, picture.path) }
var viewing by remember(picture.path) { mutableStateOf(false) }
if (!file.isFile) {
Text(stringResource(R.string.agent_image_missing, picture.alt.ifBlank { picture.path }), color = MaterialTheme.colorScheme.onSurfaceVariant)
return
}
AsyncImage(
model = file, contentDescription = picture.alt.ifBlank { file.name }, contentScale = ContentScale.Fit,
modifier = Modifier.widthIn(max = 560.dp).heightIn(max = 420.dp).clip(Shape12).clickable { viewing = true },
)
if (viewing) PictureViewer(file, picture.alt.ifBlank { file.name }) { viewing = false }
}
@Composable
internal fun AgentMarkdown(text: String, modifier: Modifier) {
@@ -532,7 +532,7 @@ private fun AgentLive() {
val pal = LocalPalette.current
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
if (AgentHost.liveThinking.isNotBlank()) AgentThought(AgentHost.liveThinking, live = true)
if (AgentHost.live.isNotBlank()) AgentMarkdown(AgentHost.live, Modifier.widthIn(max = 760.dp).padding(horizontal = 4.dp))
if (AgentHost.live.isNotBlank()) AgentReply(AgentHost.live, Modifier.widthIn(max = 760.dp).padding(horizontal = 4.dp))
val running = AgentHost.running()
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.padding(4.dp)) {
CircularProgressIndicator(Modifier.size(14.dp), strokeWidth = 2.dp, color = pal.primary)
@@ -88,7 +88,14 @@ internal object AgentPet {
private set
/** The floating windows could not be made, so the pet stays in DroidDeck's own windows instead. */
private var floatFailed by mutableStateOf(false)
val floating get() = enabled && allowed && !floatFailed
val floating get() = enabled && allowed && !floatFailed && usesOverlayWindows(onQuest)
/** Quest's shell turns overlay windows into system panels that take input from the VR view. */
private val onQuest = com.droiddeck.launcher.session.QuestExperimental.isSupported()
internal fun usesOverlayWindows(quest: Boolean) = !quest
/** On Quest the chat opens as its own panel window, which Horizon moves, resizes and closes. */
internal fun chatInOwnWindow(quest: Boolean = onQuest) = quest
/** How to close the chat open inside each DroidDeck window that has one. */
private val closeInWindow = java.util.WeakHashMap<AgentPetHost, () -> Unit>()
@@ -118,7 +125,7 @@ internal object AgentPet {
AgentHost.prefs(context).edit().putBoolean(KEY, on).apply()
if (on) {
allowed = PetWindows.allowed(context)
if (!allowed) requestFloating(context)
if (!allowed && usesOverlayWindows(onQuest)) requestFloating(context)
}
}
@@ -251,9 +258,12 @@ private fun PetLayer(host: AgentPetHost) {
val density = LocalDensity.current
val openLabel = androidx.compose.ui.res.stringResource(com.droiddeck.launcher.R.string.agent_pet_open)
val openChat = {
motion.dock()
chatShown = true
chatOpen = true
if (AgentPet.chatInOwnWindow()) com.droiddeck.launcher.agent.AgentChatActivity.open(context)
else {
motion.dock()
chatShown = true
chatOpen = true
}
}
val closeChat = {
chatOpen = false
@@ -21,6 +21,7 @@ import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
@@ -495,7 +496,13 @@ internal class PetWindows(private val context: Context) {
* under it. Its contents are built while it is closed, so opening only animates.
*/
@Composable
internal fun PetChat(open: Boolean, motion: PetMotion, onClose: () -> Unit, onClosed: () -> Unit) {
internal fun PetChat(
open: Boolean, motion: PetMotion, onClose: () -> Unit,
page: @Composable ColumnScope.(AgentMenuSlot) -> Unit = { slot ->
AgentPage(Modifier.weight(1f).fillMaxWidth(), visible = open, startTyping = AgentHost.entries.isEmpty(), hidesPet = false, menuSlot = slot)
},
onClosed: () -> Unit,
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val density = androidx.compose.ui.platform.LocalDensity.current
@@ -552,14 +559,16 @@ internal fun PetChat(open: Boolean, motion: PetMotion, onClose: () -> Unit, onCl
alpha = fade.value
}
.clip(Shape16).background(colors.background).border(1.dp, pal.line, Shape16)
.clickable(remember { MutableInteractionSource() }, null, enabled = open) {}
// Never disabled: a disabled clickable leaves the focus tree, and the one it puts back on reopening
// sits unfocused above the still-focused editor, where key events then find no focus target.
.clickable(remember { MutableInteractionSource() }, null) {}
.padding(start = 12.dp, end = 12.dp, top = 6.dp),
) {
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(bottom = 2.dp)) {
Box(Modifier.weight(1f)) { menuSlot.content?.invoke() }
HeaderAction(Icons.Outlined.Close, stringResource(R.string.agent_close), size = 34.dp, tag = "agent-pet-close", onClick = onClose)
}
AgentPage(Modifier.weight(1f).fillMaxWidth(), visible = open, startTyping = AgentHost.entries.isEmpty(), hidesPet = false, menuSlot = menuSlot)
page(menuSlot)
}
}
}
@@ -0,0 +1,113 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.gestures.calculatePan
import androidx.compose.foundation.gestures.calculateZoom
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Close
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.input.pointer.positionChanged
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Popup
import androidx.compose.ui.window.PopupProperties
import coil.compose.AsyncImage
import com.droiddeck.launcher.R
import kotlin.math.abs
private const val MAX_ZOOM = 5f
private const val TAP_ZOOM = 2.5f
/**
* A picture over the whole window: pinch or double-tap to zoom, drag to pan. A tap, a swipe down,
* Back or B close it. It is a popup, not a dialog, because the pet's chat lives in an overlay window,
* which has no activity token to show a dialog with.
*/
@Composable
internal fun PictureViewer(model: Any, description: String?, onDismiss: () -> Unit) {
Popup(
alignment = Alignment.Center, onDismissRequest = onDismiss,
properties = PopupProperties(focusable = true, dismissOnBackPress = true, dismissOnClickOutside = false),
) {
var size by remember { mutableStateOf(IntSize.Zero) }
var scale by remember { mutableFloatStateOf(1f) }
var offset by remember { mutableStateOf(Offset.Zero) }
fun clamp(o: Offset, s: Float): Offset {
val x = size.width * (s - 1f) / 2f
val y = size.height * (s - 1f) / 2f
return Offset(o.x.coerceIn(-x, x), o.y.coerceIn(-y, y))
}
val fade = if (scale == 1f && size.height > 0) (1f - abs(offset.y) / size.height * 2f).coerceIn(0.3f, 1f) else 1f
Box(
Modifier.fillMaxSize().onSizeChanged { size = it }.background(Color.Black.copy(alpha = 0.94f * fade))
.pointerInput(Unit) {
detectTapGestures(
onDoubleTap = { at ->
if (scale > 1f) { scale = 1f; offset = Offset.Zero } else {
scale = TAP_ZOOM
offset = clamp((Offset(size.width / 2f, size.height / 2f) - at) * (TAP_ZOOM - 1f), TAP_ZOOM)
}
},
onTap = { if (scale == 1f) onDismiss() },
)
}
.pointerInput(Unit) {
awaitEachGesture {
awaitFirstDown(requireUnconsumed = false)
do {
val event = awaitPointerEvent()
val zoom = event.calculateZoom()
val pan = event.calculatePan()
if (zoom != 1f || pan != Offset.Zero) {
val next = (scale * zoom).coerceIn(1f, MAX_ZOOM)
offset = if (next > 1f) clamp(offset * (next / scale) + pan, next) else Offset(0f, offset.y + pan.y)
scale = next
event.changes.forEach { if (it.positionChanged()) it.consume() }
}
} while (event.changes.any { it.pressed })
if (scale == 1f) {
if (abs(offset.y) > size.height / 6f) onDismiss() else offset = Offset.Zero
}
}
},
) {
AsyncImage(
model = model, contentDescription = description, contentScale = ContentScale.Fit,
modifier = Modifier.fillMaxSize().graphicsLayer {
scaleX = scale; scaleY = scale; translationX = offset.x; translationY = offset.y
},
)
IconButton(
onClick = onDismiss,
modifier = Modifier.align(Alignment.TopEnd).padding(12.dp).size(44.dp).clip(CircleShape).background(Color.Black.copy(alpha = 0.5f)),
) {
Icon(Icons.Outlined.Close, stringResource(R.string.common_close), tint = Color.White)
}
}
}
}
@@ -46,6 +46,7 @@ import androidx.compose.ui.platform.testTag
import com.droiddeck.launcher.agent.AgentSetup.Status
import com.droiddeck.launcher.agent.AgentSetup.Step
import com.droiddeck.launcher.core.WirelessAdbPairingService
import com.droiddeck.launcher.session.QuestExperimental
@Composable
internal fun AgentSetupView(modifier: Modifier, firstControl: Modifier = Modifier, onDone: () -> Unit = {}) {
@@ -104,11 +105,16 @@ internal fun AgentSetupView(modifier: Modifier, firstControl: Modifier = Modifie
var keyOpen by rememberSaveable(harness.id) { mutableStateOf(false) }
val (title, hint) = labels(step, harness.name, keyed)
val lab = AgentHost.lab?.takeIf { it.prepare && it.running }
val questConnection = step == Step.CONNECTION && status != Status.DONE && QuestExperimental.isSupported()
val detail = when {
step == Step.PREPARE && lab != null ->
stringResource(R.string.agent_prepare_progress, lab.permille / 10, clock(lab.etaSeconds.toLong().coerceAtLeast(0)))
keyed && status == Status.DONE && AgentSetup.detail[step] == null ->
harness.providers.filter { it.id in AgentSetup.keys }.joinToString(" · ") { it.name }.ifEmpty { stringResource(R.string.agent_step_free_models) }
// The Quest hint holds the one-time commands, so it stays under the status until the step passes.
questConnection -> AgentSetup.detail[step]?.let { "$it\n$hint" } ?: hint
// The Quest hint is setup instructions; once connected, the row says what it is for.
step == Step.CONNECTION && QuestExperimental.isSupported() -> AgentSetup.detail[step] ?: stringResource(R.string.agent_step_connection_hint)
else -> AgentSetup.detail[step] ?: hint
}
// Shown while the sign-in is pending, so it is still there after a trip to the browser for the key.
@@ -121,6 +127,7 @@ internal fun AgentSetupView(modifier: Modifier, firstControl: Modifier = Modifie
Status.TODO, Status.FAILED -> CheckState.WARN
},
title, detail, divider = index < steps.lastIndex && !showKey,
detailLines = if (questConnection) Int.MAX_VALUE else 2,
) {
val blocked = (step in setOf(Step.SIGN_IN, Step.GITHUB, Step.BUILD_TOOLS) && AgentSetup.status[Step.INSTALL] != Status.DONE) ||
(step == Step.PREPARE && AgentSetup.status[Step.BUILD_TOOLS] != Status.DONE)
@@ -258,7 +265,9 @@ internal fun agentStorageWarning(item: AgentStorage.Item) = when (item) {
@Composable
private fun labels(step: Step, harness: String, keyed: Boolean = false): Pair<String, String> = when (step) {
Step.CONNECTION -> stringResource(R.string.agent_step_connection) to stringResource(R.string.agent_step_connection_hint)
Step.CONNECTION -> stringResource(R.string.agent_step_connection) to
if (QuestExperimental.isSupported()) stringResource(R.string.agent_step_connection_quest_hint, LocalContext.current.packageName)
else stringResource(R.string.agent_step_connection_hint)
Step.INSTALL -> stringResource(R.string.agent_step_install, harness) to stringResource(R.string.agent_step_install_hint)
Step.SIGN_IN -> stringResource(R.string.agent_step_sign_in, harness) to stringResource(if (keyed) R.string.agent_step_sign_in_key_hint else R.string.agent_step_sign_in_hint)
Step.GITHUB -> stringResource(R.string.agent_step_github) to stringResource(R.string.agent_step_github_hint)
@@ -267,7 +276,7 @@ private fun labels(step: Step, harness: String, keyed: Boolean = false): Pair<St
}
private fun action(step: Step): Int = when (step) {
Step.CONNECTION -> R.string.agent_action_pair
Step.CONNECTION -> if (QuestExperimental.isSupported()) R.string.agent_action_allow else R.string.agent_action_pair
Step.INSTALL -> R.string.agent_action_install
Step.SIGN_IN, Step.GITHUB -> R.string.agent_action_sign_in
Step.BUILD_TOOLS -> R.string.agent_action_install
@@ -276,6 +285,7 @@ private fun action(step: Step): Int = when (step) {
/** The pairing DroidDeck already uses for the phantom process fix; the agent reuses its key. */
private fun pair(context: android.content.Context) {
if (QuestExperimental.isSupported()) return AgentSetup.trustOnDevice(context)
if (!WirelessAdbPairingService.notificationsEnabled(context)) {
context.startActivity(android.content.Intent(android.provider.Settings.ACTION_APP_NOTIFICATION_SETTINGS)
.putExtra(android.provider.Settings.EXTRA_APP_PACKAGE, context.packageName)
@@ -46,7 +46,11 @@ class BottomDesktopPanel(
private val status = ComposeView(context).apply {
setContent { DroidDeckTheme { BottomDesktopStatus(state.value, ::startAgain) } }
}
private val keyboardHost = KeyboardHost(context) { event -> sendKey(event) }
private val keyboardHost = KeyboardHost(
context,
sendKeyEvent = { event -> sendKey(event) },
sendText = BottomDesktop::sendText,
)
private var directTouch = SessionPrefs.bottomDesktopDirectTouch(context)
private val touchMode = mutableStateOf(directTouch)
private val trackpad = TouchpadGestures(ViewConfiguration.get(context).scaledTouchSlop.toFloat(), TrackpadInput()).apply {
@@ -338,6 +338,24 @@ internal fun sessionBarModel(
internal fun deckPanelTabs(context: Context, selected: DeckPanel, onSelect: (DeckPanel) -> Unit) =
BarTabs(DeckPanel.entries.map { context.getString(it.label) }, selected.ordinal) { onSelect(DeckPanel.entries[it]) }
internal fun padKeysView(
context: Context, steam: Boolean, onMenu: () -> Unit, onSteam: () -> Unit, onQam: () -> Unit,
): ComposeView = ComposeView(context).apply {
setContent { DroidDeckTheme { PadKeys(steam, onMenu, onSteam, onQam) } }
}
@Composable
internal fun PadKeys(steam: Boolean, onMenu: () -> Unit, onSteam: () -> Unit, onQam: () -> Unit) {
Row(
Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp),
horizontalArrangement = if (steam) Arrangement.SpaceBetween else Arrangement.Center,
) {
if (steam) BarActions(null, false, onSteam, null)
BarActions(onMenu, false, null, null)
if (steam) BarActions(null, false, null, onQam)
}
}
internal fun bottomScreenBarView(context: Context, model: () -> BottomBarModel): ComposeView = ComposeView(context).apply {
setContent { DroidDeckTheme { BottomScreenBar(model()) } }
}
@@ -8,11 +8,14 @@ import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.AlignHorizontalCenter
import androidx.compose.material.icons.outlined.AlignHorizontalLeft
import androidx.compose.material.icons.outlined.AlignHorizontalRight
import androidx.compose.material.icons.outlined.VerticalSplit
import androidx.compose.material.icons.outlined.WidthFull
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
@@ -72,7 +75,8 @@ internal enum class QamFit(val id: String, @StringRes val label: Int, val icon:
FULL("full", R.string.bottom_qam_layout_full, Icons.Outlined.WidthFull, 0),
LEFT("left", R.string.bottom_qam_layout_left, Icons.Outlined.AlignHorizontalLeft, -1),
CENTER("center", R.string.bottom_qam_layout_center, Icons.Outlined.AlignHorizontalCenter, 0),
RIGHT("right", R.string.bottom_qam_layout_right, Icons.Outlined.AlignHorizontalRight, 1);
RIGHT("right", R.string.bottom_qam_layout_right, Icons.Outlined.AlignHorizontalRight, 1),
SPLIT("split", R.string.bottom_qam_layout_split, Icons.Outlined.VerticalSplit, 0);
val next: QamFit get() = entries[(ordinal + 1) % entries.size]
@@ -92,6 +96,7 @@ internal enum class QamFit(val id: String, @StringRes val label: Int, val icon:
internal object QamLayout {
private const val WIDE_CSS = "div.BasicUI { width: 100% !important; } div[class*=\\\"tab_\\\"] { max-width: none !important; }"
private const val PARKED_CSS = " #Footer { display: none !important; }"
/** Scale and left edge of the menu in a box; [align] -1, 0 or 1 places a narrower menu left, centred or right. */
fun fit(boxWidth: Float, boxHeight: Float, contentRight: Float, cssHeight: Float, align: Int = 0): Pair<Float, Float> {
@@ -102,10 +107,13 @@ internal object QamLayout {
fun toCss(x: Float, y: Float, scale: Float, left: Float): Pair<Float, Float> = (x - left) / scale to y / scale
/** Makes the menu follow the panel-shaped view (Steam sizes it once, on open) and lifts each tab's 300 px cap, then measures where the content ends. */
/** [wide] is false while the menu is shown on the top screen, where it keeps Steam's own layout. */
fun contentScript(wide: Boolean): String = "(() => { let s = document.getElementById('dd-qam-wide'); " +
/**
* [wide] is false while the menu is shown on the top screen, where it keeps Steam's own layout. [parked] hides the
* button-hint footer Steam draws in a game, which stays an empty black strip while the controller is not on the menu.
*/
fun contentScript(wide: Boolean, parked: Boolean = wide): String = "(() => { let s = document.getElementById('dd-qam-wide'); " +
"if (!s) { s = document.createElement('style'); s.id = 'dd-qam-wide'; document.head.appendChild(s); } " +
"const css = '${if (wide) WIDE_CSS else ""}'; " +
"const css = '${(if (wide) WIDE_CSS else "") + (if (parked) PARKED_CSS else "")}'; " +
"if (s.textContent !== css) s.textContent = css; if (document.scrollingElement.scrollLeft) document.scrollingElement.scrollLeft = 0; " +
"const w = innerWidth; let right = 0; for (const e of document.body.querySelectorAll('*')) { " +
"const r = e.getBoundingClientRect(); const tab = /(^| )tab_/.test(String(e.className)); " +
@@ -117,17 +125,90 @@ private const val TICK_MS = 1_000L
private const val FAST_TICK_MS = 150L
private const val MAX_RETRY_MS = 4_000L
/** The last frame shown, so returning to the panel shows the menu at once while the live stream reconnects. */
/** One of Steam's menu pages streamed to the panel; the last frame is kept so returning to the panel shows it at once. */
internal class MenuStream {
@Volatile var page: CdpPage? = null
val live = java.util.concurrent.atomic.AtomicBoolean(false)
val image = mutableStateOf<ImageBitmap?>(null)
val shape = mutableStateOf<FloatArray?>(null)
fun show(frame: ImageBitmap) {
image.value = frame
live.set(true)
}
/** Connects to [path] and starts its screencast; false when the page cannot be reached. */
fun connect(port: Int, path: String): Boolean {
page?.close()
page = null
live.set(false)
val p = runCatching {
CdpPage(port, path) { method, params ->
if (method == "Page.screencastFrame") {
page?.send("Page.screencastFrameAck", JSONObject().put("sessionId", params.optInt("sessionId")))
decodeFrame(params.optString("data"))?.let(::show)
}
}
}.onFailure { android.util.Log.w("SteamQam", "devtools connect: $it") }.getOrNull() ?: return false
page = p
p.send("Page.enable")
val started = p.call("Page.startScreencast", JSONObject().put("format", "jpeg").put("quality", 85)
.put("maxWidth", 1920).put("maxHeight", 1440))
if (started == null || started.has("error") || !started.has("result")) {
p.close()
page = null
return false
}
return true
}
/** Runs [script], which returns the page's [width, height, pixel ratio, content right], and refreshes a still page. */
fun refresh(script: String) {
val p = page ?: return
// The screencast sends frames only when the menu repaints, so a still menu needs one screenshot.
if (!live.get()) {
p.call("Page.captureScreenshot", JSONObject().put("format", "jpeg").put("quality", 85))
?.optJSONObject("result")?.optString("data")?.let(::decodeFrame)?.let(::show)
}
(p.evaluate(script) as? String)?.let { text ->
runCatching {
val a = JSONArray(text)
val layout = FloatArray(4) { a.getDouble(it).toFloat() }
if (!layout.contentEquals(shape.value)) shape.value = layout
}
}
}
/** Stops the stream and runs [restore] on the page, which outlives this connection. */
fun stop(restore: String) {
val p = page ?: return
page = null
runCatching { p.send("Page.stopScreencast") }
runCatching { p.evaluate(restore) }
p.close()
}
fun frame(): QamFrame? {
val img = image.value
val l = shape.value
return if (img != null && l != null && l[0] > 0f) QamFrame(img, l[0], l[1], l[3].coerceIn(l[0] * 0.25f, l[0])) else null
}
}
/** Steam's main menu beside the quick access menu; Steam's side of the hold keeps it in place and filling its view. */
internal object MainMenuLayout {
const val CONTENT_SCRIPT = "JSON.stringify([innerWidth, innerHeight, devicePixelRatio, innerWidth])"
}
/** Panel streams kept across visits to the panel. */
private object QamCache {
@Volatile var image: ImageBitmap? = null
@Volatile var shape: FloatArray? = null
val qam = MenuStream()
val main = MenuStream()
}
@Composable
internal fun SteamQamPanel() {
val context = LocalContext.current.applicationContext
var image by remember { mutableStateOf(QamCache.image) }
var shape by remember { mutableStateOf(QamCache.shape) }
var failed by remember { mutableStateOf(false) }
var slow by remember { mutableStateOf(false) }
LaunchedEffect(Unit) {
@@ -135,78 +216,67 @@ internal fun SteamQamPanel() {
slow = true
}
val fit = QamFit.current(context)
val holder = remember { arrayOfNulls<CdpPage>(1) }
val qam = QamCache.qam
val mainMenu = QamCache.main
val owner = remember { SteamQam.newOwner() }
val relay = remember { intArrayOf(0) }
val live = remember { java.util.concurrent.atomic.AtomicBoolean(false) }
val mainPath = remember { arrayOfNulls<String>(1) }
val aspect = remember { floatArrayOf(0f) }
val measure = Modifier.fillMaxSize().onSizeChanged { if (it.height > 0) aspect[0] = it.width.toFloat() / it.height }
val show = { frame: ImageBitmap -> image = frame; QamCache.image = frame; live.set(true) }
LaunchedEffect(Unit) {
withContext(Dispatchers.IO) {
var misses = 0
// The main menu page backs off on its own, so Quick Access stays available while its neighbour cannot connect.
var mainMisses = 0
var mainRetryAt = 0L
fun split() = QamFit.current(context) == QamFit.SPLIT
// The lease is renewed on its own, so slow discovery or a retry backoff never lets the held menu lapse.
val renew = launch {
while (isActive) {
if (SessionState.phase == SessionPhase.READY && aspect[0] > 0f) SteamQam.hold(context, aspect[0], owner)
if (SessionState.phase == SessionPhase.READY && aspect[0] > 0f) SteamQam.hold(context, aspect[0], owner, split())
delay(TICK_MS)
}
}
try {
while (isActive) {
// Holding the menu before Steam's first frame keeps gamescope from presenting it.
if (SessionState.phase != SessionPhase.READY) {
if (SessionState.phase != SessionPhase.READY || aspect[0] == 0f) {
delay(FAST_TICK_MS)
continue
}
if (aspect[0] == 0f) {
delay(FAST_TICK_MS)
continue
}
val held = SteamQam.hold(context, aspect[0], owner)
val split = split()
val held = SteamQam.hold(context, aspect[0], owner, split)
ensureActive()
var reached = held != null
if (held?.open == SteamQam.QUICK_ACCESS) {
var page = holder[0]
if (page == null || page.closed) {
page?.close()
live.set(false)
page = SteamQam.target(context)?.let { t ->
if (qam.page?.closed != false) {
val t = SteamQam.target(context)
if (t != null) {
if (relay[0] != 0 && relay[0] != t.port) SteamQam.stopRelay(context, relay[0])
relay[0] = t.port
runCatching {
CdpPage(t.port, t.path) { method, params ->
if (method == "Page.screencastFrame") {
holder[0]?.send("Page.screencastFrameAck", JSONObject().put("sessionId", params.optInt("sessionId")))
decodeFrame(params.optString("data"))?.let(show)
}
}
}.onFailure { android.util.Log.w("SteamQam", "devtools connect: $it") }.getOrNull()
mainPath[0] = t.mainPath
qam.connect(t.port, t.path)
mainMenu.stop(MainMenuLayout.CONTENT_SCRIPT)
}
holder[0] = page
ensureActive()
page?.send("Page.enable")
val started = page?.call("Page.startScreencast", JSONObject().put("format", "jpeg").put("quality", 85)
.put("maxWidth", 1920).put("maxHeight", 1440))
if (page != null && (started == null || started.has("error") || !started.has("result"))) {
page.close()
page = null
holder[0] = null
}
}
// The screencast sends frames only when the menu repaints, so a still menu needs one screenshot.
if (!live.get()) {
page?.call("Page.captureScreenshot", JSONObject().put("format", "jpeg").put("quality", 85))
?.optJSONObject("result")?.optString("data")?.let(::decodeFrame)?.let(show)
}
reached = page != null
val wide = !held.top && QamFit.current(context) == QamFit.FULL
(page?.evaluate(QamLayout.contentScript(wide)) as? String)?.let { text ->
runCatching {
val a = JSONArray(text)
val layout = floatArrayOf(a.getDouble(0).toFloat(), a.getDouble(1).toFloat(), a.getDouble(2).toFloat(), a.getDouble(3).toFloat())
if (!layout.contentEquals(shape)) { shape = layout; QamCache.shape = layout }
reached = qam.page?.closed == false
val wide = !held.top && (QamFit.current(context) == QamFit.FULL || split)
qam.refresh(QamLayout.contentScript(wide, parked = !held.top))
val path = mainPath[0]
if (split && path != null) {
val now = android.os.SystemClock.elapsedRealtime()
if (mainMenu.page?.closed != false && now >= mainRetryAt) {
if (mainMenu.connect(relay[0], path)) {
mainMisses = 0
} else {
mainMisses++
mainRetryAt = now + minOf(TICK_MS shl minOf(mainMisses - 1, 2), MAX_RETRY_MS)
}
}
mainMenu.refresh(MainMenuLayout.CONTENT_SCRIPT)
} else if (!split) {
mainMenu.stop(MainMenuLayout.CONTENT_SCRIPT)
}
}
failed = !reached
@@ -214,7 +284,7 @@ internal fun SteamQamPanel() {
misses = if (reached) 0 else misses + 1
val wait = when {
!reached -> minOf(TICK_MS shl minOf(misses - 1, 2), MAX_RETRY_MS)
live.get() -> TICK_MS
qam.live.get() && (!split || mainMenu.live.get() || mainMenu.page?.closed != false) -> TICK_MS
else -> FAST_TICK_MS
}
val used = QamFit.current(context)
@@ -225,35 +295,46 @@ internal fun SteamQamPanel() {
} finally {
withContext(NonCancellable) {
renew.cancelAndJoin()
val page = holder[0]
holder[0] = null
runCatching { page?.send("Page.stopScreencast") }
// The page outlives this connection, so the widened layout would otherwise stay on the top screen.
runCatching { page?.evaluate(QamLayout.contentScript(wide = false)) }
page?.close()
// The pages outlive these connections, so the widened layouts would otherwise stay on the top screen.
qam.stop(QamLayout.contentScript(wide = false))
mainMenu.stop(MainMenuLayout.CONTENT_SCRIPT)
SteamQam.release(context, relay[0], owner)
}
}
}
}
val img = image
val l = shape
val f = remember(img, l) {
if (img != null && l != null && l[0] > 0f) QamFrame(img, l[0], l[1], l[3].coerceIn(l[0] * 0.25f, l[0])) else null
}
if (f == null) {
val qamFrame = qam.frame()
if (qamFrame == null) {
Box(measure) {
if (slow) PanelNote(stringResource(if (failed) R.string.bottom_qam_unavailable else R.string.achievements_reading))
}
return
}
BoxWithConstraints(measure.background(f.fill)) {
if (fit != QamFit.SPLIT) {
MenuCanvas(qamFrame, fit.align, measure) { qam.page }
return
}
// Each side is as wide as its menu at the shared scale, so neither is shrunk nor padded with empty space.
val mainFrame = mainMenu.frame()
val mainWidth = mainFrame?.cssWidth ?: SteamQam.MAIN_CSS_WIDTH.toFloat()
Row(measure) {
val left = Modifier.weight(mainWidth).fillMaxHeight()
if (mainFrame != null) MenuCanvas(mainFrame, -1, left) { mainMenu.page }
else Box(left.background(qamFrame.fill))
MenuCanvas(qamFrame, -1, Modifier.weight(qamFrame.cssWidth).fillMaxHeight()) { qam.page }
}
}
/** Draws [f] scaled into the box, placed by [align], and forwards touches on it to [page]. */
@Composable
private fun MenuCanvas(f: QamFrame, align: Int, modifier: Modifier, page: () -> CdpPage?) {
BoxWithConstraints(modifier.background(f.fill)) {
val density = LocalDensity.current
val boxW = with(density) { maxWidth.toPx() }
val boxH = with(density) { maxHeight.toPx() }
val (scale, left) = QamLayout.fit(boxW, boxH, f.contentRight, f.cssHeight, fit.align)
val (scale, left) = QamLayout.fit(boxW, boxH, f.contentRight, f.cssHeight, align)
Canvas(
Modifier.fillMaxSize().pointerInput(f.cssWidth, f.contentRight, boxW, boxH, fit) {
Modifier.fillMaxSize().pointerInput(f.cssWidth, f.contentRight, boxW, boxH, align) {
var touching = false
var target: CdpPage? = null
try {
@@ -268,7 +349,7 @@ internal fun SteamQamPanel() {
PointerEventType.Release -> "touchEnd"
else -> null
}?.takeIf { it == "touchStart" || touching } ?: continue
if (type == "touchStart") target = holder[0]
if (type == "touchStart") target = page()
touching = type != "touchEnd"
val points = if (type == "touchEnd") JSONArray()
else JSONArray().put(JSONObject().put("x", x.toDouble()).put("y", y.toDouble()))
@@ -199,7 +199,6 @@ internal fun SessionDrawerPreview(secondScreens: List<SecondScreenDisplay>) {
secondScreenDisplays = secondScreens,
selectedSecondScreenDisplay = secondScreens.firstOrNull()?.id ?: -1,
onSecondScreenDisplay = {},
onImportLossless = {},
onKeyboard = {}, onHardwareKeyboard = {},
onSteamMenu = if (steam) ({}) else null,
onQam = if (steam) ({}) else null,
@@ -7,13 +7,16 @@ import androidx.compose.animation.slideInHorizontally
import androidx.compose.animation.slideOutHorizontally
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectHorizontalDragGestures
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.displayCutout
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.widthIn
@@ -35,6 +38,7 @@ import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
@@ -90,6 +94,29 @@ internal fun DrawerEntryHint(steam: Boolean, inverted: Boolean, onOpen: () -> Un
}
}
/** A Quest has no system Back gesture, so a laser drag in from the right edge stands in for it. */
@Composable
internal fun DrawerEdgeSwipe(onBack: () -> Unit) {
val density = LocalDensity.current
val threshold = with(density) { 48.dp.toPx() }
val strip = with(density) { 12.toDp() }
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.CenterEnd) {
Box(
Modifier.fillMaxHeight().width(strip).testTag("drawer-edge")
.pointerInput(Unit) {
var travelled = 0f
detectHorizontalDragGestures(
onDragStart = { travelled = 0f },
onDragEnd = { if (travelled <= -threshold) onBack() },
) { change, amount ->
change.consume()
travelled += amount
}
},
)
}
}
@Composable
internal fun DrawerCornerTap(onOpen: () -> Unit) {
Box(Modifier.fillMaxSize().windowInsetsPadding(WindowInsets.displayCutout), contentAlignment = Alignment.TopEnd) {
@@ -0,0 +1,142 @@
package com.droiddeck.launcher.ui
import android.content.Context
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsFocusedAsState
import androidx.compose.foundation.interaction.collectIsHoveredAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.ExpandMore
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.compositionLocalOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.stateDescription
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.session.SessionPrefs
/**
* Inside the session menu every top-level settings group folds to its header and a summary of its values.
* Groups start folded; a group the player opens or folds stays that way across sessions.
*/
internal object DrawerSectionState {
private val chosen = mutableStateMapOf<String, Boolean>()
fun load(context: Context) {
if (DevPreview.drawer != null) return
chosen.clear()
chosen.putAll(SessionPrefs.drawerSections(context))
}
fun isOpen(key: String) = chosen[key] ?: false
fun toggle(context: Context, key: String) {
chosen[key] = !isOpen(key)
if (DevPreview.drawer == null) SessionPrefs.setDrawerSections(context, chosen.toMap())
}
}
internal class DrawerSections(val context: Context, val track: (String) -> Modifier)
internal val LocalDrawerSections = compositionLocalOf<DrawerSections?> { null }
@Composable
internal fun DrawerSection(
sections: DrawerSections, key: String, title: String, summary: String?, tag: String?,
content: @Composable ColumnScope.() -> Unit,
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val open = DrawerSectionState.isOpen(key)
val source = remember { MutableInteractionSource() }
val hot = source.collectIsFocusedAsState().value || source.collectIsHoveredAsState().value
val rotation by animateFloatAsState(if (open) 180f else 0f, Motion.tw(180), label = "sectionArrow")
val state = stringResource(if (open) R.string.widgets_expanded else R.string.widgets_collapsed)
val toggle = { DrawerSectionState.toggle(sections.context, key) }
val shape = RoundedCornerShape(14.dp)
Column(
Modifier.fillMaxWidth().padding(top = 6.dp).clip(shape)
.background(colors.surface).border(1.dp, if (open) pal.line2 else pal.line, shape),
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp)
.then(sections.track("section-$key"))
.testTag("drawer-section-$key")
.background(if (hot) pal.signal.copy(alpha = 0.12f) else androidx.compose.ui.graphics.Color.Transparent)
.glideBorder(hot, shape, pal.signal)
.hoverable(source)
.clickable(interactionSource = source, indication = LocalIndication.current, role = Role.Button, onClick = toggle)
.controllerConfirm(onClick = toggle)
.semantics { contentDescription = title; stateDescription = state }
.padding(start = 12.dp, end = 8.dp, top = 6.dp, bottom = 6.dp),
) {
Column(Modifier.weight(1f)) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
Text(title.uppercase(), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.2.sp,
color = if (open) colors.onBackground else colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f, fill = false))
if (tag != null) Text(
tag, fontSize = 10.sp, fontWeight = FontWeight.SemiBold, color = pal.signal, maxLines = 1,
modifier = Modifier.clip(RoundedCornerShape(6.dp)).background(pal.signal.copy(alpha = 0.14f))
.padding(horizontal = 6.dp, vertical = 2.dp),
)
}
if (!open && !summary.isNullOrEmpty()) Text(
summary, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
modifier = Modifier.padding(top = 2.dp),
)
}
Icon(Icons.Outlined.ExpandMore, contentDescription = null, tint = colors.onSurfaceVariant,
modifier = Modifier.size(22.dp).rotate(rotation))
}
AnimatedVisibility(open, enter = expandVertically(Motion.tw(200)) + fadeIn(Motion.tw(160)),
exit = shrinkVertically(Motion.tw(160)) + fadeOut(Motion.tw(120))) {
Column(Modifier.fillMaxWidth()) {
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
// Only top-level groups fold; groups and dialogs opened from inside one draw normally.
CompositionLocalProvider(LocalDrawerSections provides null) { content() }
}
}
}
}
@@ -26,7 +26,8 @@ internal fun DroidDeckHudSettings(host: MenuHost, a: DrawerActions, track: (Stri
fun on(key: String) = cfg[key] == "1"
fun int(key: String, fallback: Int) = cfg[key]?.toIntOrNull() ?: fallback
SettingsGroup(stringResource(R.string.drawer_hud)) {
SettingsGroup(stringResource(R.string.drawer_hud), key = "performance-hud",
detail = stringResource(if (a.hudOn) R.string.widgets_on else R.string.widgets_off)) {
ToggleRow(host, "hud", stringResource(R.string.drawer_hud), null, a.hudOn, chipModifier = track("hud"), onChange = a.onHud)
if (a.hudOn) ToggleRow(
host, "hud-only-during-game", stringResource(R.string.hud_only_during_game),
@@ -62,7 +63,7 @@ internal fun DroidDeckHudSettings(host: MenuHost, a: DrawerActions, track: (Stri
if (a.dashboardAvailable && a.secondScreenDisplays.isNotEmpty()) BottomStripSettings(host, track)
if (!a.hudOn) return
SettingsGroup(stringResource(R.string.hud_group_look)) {
SettingsGroup(stringResource(R.string.hud_group_look), key = "performance-hud-look") {
SliderRow(stringResource(R.string.hud_scale), null, int("hudScale", 100), 50..150, step = 5, format = { "$it%" },
modifier = track("hud-scale")) { a.onHudSetting("hudScale", it.toString()) }
SliderRow(stringResource(R.string.drawer_hud_opacity), null, int("hudOpacity", 80), 0..100, step = 5, format = { "$it%" },
@@ -85,7 +86,7 @@ internal fun DroidDeckHudSettings(host: MenuHost, a: DrawerActions, track: (Stri
}
var editing by remember { mutableStateOf(false) }
SettingsGroup(stringResource(R.string.hud_group_metrics)) {
SettingsGroup(stringResource(R.string.hud_group_metrics), key = "performance-hud-metrics") {
ActionRow(stringResource(R.string.hud_group_metrics), null, stringResource(R.string.common_edit),
onClick = { editing = true }, modifier = track("hud-readings"))
val rows = DroidDeckHudSize.rowsFor(DroidDeckHudSize.from(cfg["hudSize"]), cfg)
@@ -103,7 +104,7 @@ internal fun DroidDeckHudSettings(host: MenuHost, a: DrawerActions, track: (Stri
)
}
if (on("showTemp") || on("showGpuTemp") || on("showBatteryTemp")) SettingsGroup(stringResource(R.string.hud_group_temps)) {
if (on("showTemp") || on("showGpuTemp") || on("showBatteryTemp")) SettingsGroup(stringResource(R.string.hud_group_temps), key = "performance-hud-temps") {
ChoiceRow(host, "hud-temp-unit", stringResource(R.string.hud_temp_unit), null,
listOf("c" to "°C", "f" to "°F"), if (cfg["tempUnit"].equals("f", true)) "f" else "c",
chipModifier = track("hud-temp-unit")) { a.onHudSetting("tempUnit", it) }
@@ -129,7 +130,7 @@ internal fun DroidDeckHudSettings(host: MenuHost, a: DrawerActions, track: (Stri
}
}
SettingsGroup(stringResource(R.string.hud_group_more)) {
SettingsGroup(stringResource(R.string.hud_group_more), key = "performance-hud-more") {
ActionRow(stringResource(R.string.hud_export), stringResource(R.string.hud_export_hint),
stringResource(R.string.hud_export_button), onClick = a.onHudExport, modifier = track("hud-export"))
ActionRow(stringResource(R.string.hud_reset), null, stringResource(R.string.hud_reset_button),
@@ -145,7 +146,7 @@ private fun BottomStripSettings(host: MenuHost, track: (String) -> Modifier) {
var hudOn by remember { mutableStateOf(SessionPrefs.bottomHud(context)) }
var onTabs by remember { mutableStateOf(SessionPrefs.bottomStripOnTabs(context)) }
var shown by remember { mutableStateOf(SessionPrefs.bottomStripMetrics(context)) }
SettingsGroup(stringResource(R.string.bottom_hud_group)) {
SettingsGroup(stringResource(R.string.bottom_hud_group), key = "performance-bottom-hud") {
ToggleRow(host, "bottom-hud", stringResource(R.string.bottom_hud_group), null, hudOn,
chipModifier = track("bottom-hud")) { on ->
hudOn = on
@@ -1,52 +1,371 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.withFrameNanos
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.input.InputMode
import androidx.compose.ui.platform.LocalInputModeManager
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.stateDescription
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.gpu.FrameGen
import com.droiddeck.launcher.gpu.Lossless
@Composable
internal fun FrameGenMenu(
host: MenuHost, mode: FrameGen.Mode, lossless: Lossless.State,
mode: FrameGen.Mode,
lossless: Lossless.State,
onPick: (FrameGen.Mode) -> Unit,
onImportLossless: () -> Unit,
gameProfileId: String? = null,
hasGameOverride: Boolean = false,
onResetGame: () -> Unit = {},
focusModifier: Modifier = Modifier,
legacyButtons: Boolean = false,
listLayout: Boolean = false,
sessionHost: MenuHost? = null,
) {
val sessionEngineAnchor = remember { FocusRequester() }
val need = stringResource(R.string.lsfg_needs_steam)
val selectedEngine = mode.engine.takeIf { it != FrameGen.ENGINE_OFF }
val offLabel = FrameGen.label(LocalContext.current, FrameGen.Mode.OFF)
val colors = MaterialTheme.colorScheme
val context = LocalContext.current
AnchoredMenu(host.open == "fg", onDismiss = { if (host.open == "fg") host.open = null }, title = stringResource(R.string.frame_gen_title)) { firstItemFocus ->
val need = when {
lossless.ready -> null
lossless.owned -> stringResource(R.string.lsfg_needs_install)
else -> stringResource(R.string.lsfg_needs_steam)
var pacerEnabled by remember { mutableStateOf(FrameGen.pacerEnabled(context)) }
val engines = listOf(FrameGen.ENGINE_LSFG to "LSFG", FrameGen.ENGINE_DDFG to "DDFG", FrameGen.ENGINE_ZEROFG to "ZeroFG")
if (legacyButtons) {
val context = LocalContext.current
val options = buildList {
add(FrameGen.Mode.OFF.copy(multiplier = mode.multiplier))
(2..4).forEach { add(FrameGen.Mode(FrameGen.ENGINE_DDFG, it)) }
(2..4).forEach { add(FrameGen.Mode(FrameGen.ENGINE_ZEROFG, it)) }
(2..4).forEach { add(FrameGen.Mode(FrameGen.ENGINE_LSFG, it)) }
FrameGen.ADAPTIVE_TARGETS.forEach { add(FrameGen.Mode(FrameGen.ENGINE_LSFG, target = it)) }
}
@Composable
fun item(m: FrameGen.Mode, enabled: Boolean = true, detail: String? = null, focus: FocusRequester? = null) =
MenuItem(FrameGen.label(context, m), checked = mode == m, enabled = enabled, detail = detail, focusRequester = focus) {
onPick(m); host.open = null
Column(Modifier.fillMaxWidth().padding(start = 10.dp, end = 10.dp, bottom = 8.dp)) {
options.forEachIndexed { index, option ->
val selected = mode == option ||
(option.engine == FrameGen.ENGINE_OFF && selectedEngine == null)
val enabled = option.engine != FrameGen.ENGINE_LSFG || lossless.ready || selected
val pick = { onPick(option) }
OutlinedButton(
onClick = pick,
enabled = enabled,
modifier = (if (index == 0) focusModifier else Modifier).fillMaxWidth()
.padding(top = if (index == 0) 0.dp else 6.dp)
.controllerConfirm(enabled = enabled, onClick = pick),
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
colors = ButtonDefaults.outlinedButtonColors(
containerColor = if (selected) colors.primary.copy(alpha = 0.16f) else colors.surface,
contentColor = if (selected) colors.primary else colors.onSurface,
),
) { Text(FrameGen.label(context, option)) }
}
item(FrameGen.Mode.OFF, focus = firstItemFocus)
if (gameProfileId != null) {
MenuItem(stringResource(R.string.comp_game_use_general), checked = !hasGameOverride) {
if (selectedEngine == FrameGen.ENGINE_LSFG && !lossless.ready) {
Text(
need,
color = colors.onSurfaceVariant,
style = MaterialTheme.typography.bodySmall,
modifier = Modifier.padding(top = 6.dp),
)
}
if (gameProfileId != null) {
val resetGame = onResetGame
OutlinedButton(
onClick = resetGame,
modifier = Modifier.fillMaxWidth().padding(top = 6.dp)
.controllerConfirm(onClick = resetGame),
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
) {
Text(stringResource(R.string.comp_game_use_general) + if (hasGameOverride) "" else " ✓")
}
}
}
return
}
Column(Modifier.fillMaxWidth().padding(start = 10.dp, end = 10.dp, top = 0.dp, bottom = 8.dp)) {
if (sessionHost != null) {
SessionFrameGenEngine(
sessionHost, mode, listOf(FrameGen.ENGINE_OFF to offLabel) + engines,
lossless.ready, need, focusModifier, sessionEngineAnchor, onPick,
)
} else {
OutlinedButton(
onClick = { onPick(FrameGen.Mode.OFF.copy(multiplier = mode.multiplier)) },
modifier = Modifier.fillMaxWidth().controllerConfirm(
onClick = { onPick(FrameGen.Mode.OFF.copy(multiplier = mode.multiplier)) },
),
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
colors = ButtonDefaults.outlinedButtonColors(
containerColor = if (selectedEngine == null) colors.primary.copy(alpha = 0.16f) else colors.surface,
contentColor = if (selectedEngine == null) colors.primary else colors.onSurface,
),
) { Text(offLabel) }
if (listLayout) {
Column(Modifier.fillMaxWidth().padding(top = 8.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
engines.forEach { (engine, label) ->
val selected = selectedEngine == engine
val enabled = selected || engine != FrameGen.ENGINE_LSFG || lossless.ready
val pick = {
onPick(if (selected) FrameGen.Mode.OFF.copy(multiplier = mode.multiplier) else FrameGen.Mode(engine, mode.multiplier.coerceIn(2, 4)))
}
OutlinedButton(
onClick = pick,
enabled = enabled,
modifier = Modifier.fillMaxWidth().controllerConfirm(enabled = enabled, onClick = pick),
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
colors = ButtonDefaults.outlinedButtonColors(
containerColor = if (selected) colors.primary.copy(alpha = 0.16f) else colors.surface,
contentColor = if (selected) colors.primary else colors.onSurface,
),
) { Text(label) }
}
}
} else {
Row(Modifier.fillMaxWidth().padding(top = 8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
val focusIndex = engines.indexOfFirst { (engine, _) ->
selectedEngine == engine || engine != FrameGen.ENGINE_LSFG || lossless.ready
}
engines.forEachIndexed { index, (engine, label) ->
val selected = selectedEngine == engine
val enabled = selected || engine != FrameGen.ENGINE_LSFG || lossless.ready
val pick = {
onPick(if (selected) FrameGen.Mode.OFF.copy(multiplier = mode.multiplier) else FrameGen.Mode(engine, mode.multiplier.coerceIn(2, 4)))
}
OutlinedButton(
onClick = pick,
enabled = enabled,
modifier = (if (index == focusIndex) focusModifier else Modifier)
.weight(1f).controllerConfirm(enabled = enabled, onClick = pick),
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
colors = ButtonDefaults.outlinedButtonColors(
containerColor = if (selected) colors.primary.copy(alpha = 0.16f) else colors.surface,
contentColor = if (selected) colors.primary else colors.onSurface,
),
) { Text(label) }
}
}
}
}
val multiplierEnabled = mode.engine != FrameGen.ENGINE_LSFG || lossless.ready
if (listLayout) {
Column(
Modifier.fillMaxWidth().padding(top = 8.dp),
verticalArrangement = Arrangement.spacedBy(6.dp),
) {
(2..4).forEach { multiplier ->
val selected = mode.multiplier == multiplier && mode.target == 0
val pickMultiplier = { onPick(mode.copy(multiplier = multiplier, target = 0)) }
OutlinedButton(
onClick = pickMultiplier,
enabled = multiplierEnabled,
modifier = Modifier.fillMaxWidth().controllerConfirm(enabled = multiplierEnabled, onClick = pickMultiplier)
.frameGenFocus(sessionHost),
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
colors = ButtonDefaults.outlinedButtonColors(
containerColor = if (selected) colors.secondary.copy(alpha = 0.18f) else colors.surface,
contentColor = if (selected) colors.secondary else colors.onSurface,
),
) { Text("${multiplier}×") }
}
}
} else {
Row(
Modifier.fillMaxWidth().padding(top = 8.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
(2..4).forEach { multiplier ->
val selected = mode.multiplier == multiplier && mode.target == 0
val pickMultiplier = { onPick(mode.copy(multiplier = multiplier, target = 0)) }
OutlinedButton(
onClick = pickMultiplier,
enabled = multiplierEnabled,
modifier = Modifier.weight(1f).controllerConfirm(enabled = multiplierEnabled, onClick = pickMultiplier)
.frameGenFocus(sessionHost),
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
colors = ButtonDefaults.outlinedButtonColors(
containerColor = if (selected) colors.secondary.copy(alpha = 0.18f) else colors.surface,
contentColor = if (selected) colors.secondary else colors.onSurface,
),
) { Text("${multiplier}×") }
}
}
}
val togglePacer = {
val enabled = !pacerEnabled
FrameGen.setPacer(context, enabled)
pacerEnabled = enabled
}
OutlinedButton(
onClick = togglePacer,
modifier = Modifier.fillMaxWidth().padding(top = 8.dp)
.controllerConfirm(onClick = togglePacer).frameGenFocus(sessionHost),
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
colors = ButtonDefaults.outlinedButtonColors(
containerColor = if (pacerEnabled) colors.primary.copy(alpha = 0.16f) else colors.surface,
contentColor = if (pacerEnabled) colors.primary else colors.onSurface,
),
) {
Text("ZeroPacer" + if (pacerEnabled) " ✓" else "")
}
if (selectedEngine == FrameGen.ENGINE_LSFG) {
Row(
Modifier.fillMaxWidth().padding(top = 8.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
FrameGen.ADAPTIVE_TARGETS.forEach { target ->
val adaptiveMode = FrameGen.Mode(FrameGen.ENGINE_LSFG, target = target)
val selected = mode.target == target
val pickTarget = { onPick(adaptiveMode) }
OutlinedButton(
onClick = pickTarget,
enabled = lossless.ready,
modifier = Modifier.weight(1f).controllerConfirm(
enabled = lossless.ready,
onClick = pickTarget,
).frameGenFocus(sessionHost),
contentPadding = PaddingValues(horizontal = 8.dp, vertical = 8.dp),
colors = ButtonDefaults.outlinedButtonColors(
containerColor = if (selected) colors.secondary.copy(alpha = 0.18f) else colors.surface,
contentColor = if (selected) colors.secondary else colors.onSurface,
),
) {
Text(FrameGen.label(LocalContext.current, adaptiveMode))
}
}
}
}
if (sessionHost == null && selectedEngine == FrameGen.ENGINE_LSFG && !lossless.ready) {
Text(need, color = colors.onSurfaceVariant,
style = MaterialTheme.typography.bodySmall,
modifier = Modifier.padding(top = 6.dp))
}
if (gameProfileId != null && (sessionHost == null || hasGameOverride)) {
val input = LocalInputModeManager.current
val resetGame = {
if (sessionHost != null && input.inputMode == InputMode.Keyboard) {
sessionEngineAnchor.requestFocus()
}
onResetGame()
host.open = null
}
OutlinedButton(
onClick = resetGame,
modifier = Modifier.fillMaxWidth().padding(top = 8.dp)
.testTag("framegen-use-global").controllerConfirm(onClick = resetGame)
.frameGenFocus(sessionHost),
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
) {
Text(if (sessionHost != null) stringResource(R.string.frame_gen_use_global)
else stringResource(R.string.comp_game_use_general) + if (hasGameOverride) "" else " ✓")
}
}
for (m in 2..4) item(FrameGen.Mode(FrameGen.ENGINE_DDFG, m))
val lsfg = (2..4).map { FrameGen.Mode(FrameGen.ENGINE_LSFG, it) } +
FrameGen.ADAPTIVE_TARGETS.map { FrameGen.Mode(FrameGen.ENGINE_LSFG, target = it) }
lsfg.forEachIndexed { i, m -> item(m, enabled = lossless.ready, detail = need.takeIf { i == 0 }) }
if (lossless.owned) {
val using = when (lossless.source) {
Lossless.Source.STEAM -> stringResource(R.string.lsfg_using_steam)
Lossless.Source.IMPORT -> stringResource(R.string.lsfg_using_import)
Lossless.Source.NONE -> null
}
}
@Composable
private fun Modifier.frameGenFocus(sessionHost: MenuHost?): Modifier =
if (sessionHost != null) focusGlide(RoundedCornerShape(percent = 50)) else this
@Composable
private fun SessionFrameGenEngine(
host: MenuHost,
mode: FrameGen.Mode,
options: List<Pair<String, String>>,
losslessReady: Boolean,
losslessNote: String,
focusModifier: Modifier,
anchor: FocusRequester,
onPick: (FrameGen.Mode) -> Unit,
) {
val label = stringResource(R.string.frame_gen_engine)
val selectedLabel = options.firstOrNull { (engine, _) -> engine == mode.engine }?.second
?: options.first().second
val key = "frame-generation-engine"
val open = host.open == key
val input = LocalInputModeManager.current
var anchorFocused by remember { mutableStateOf(false) }
val selectedOption = remember { FocusRequester() }
var keyboardOpened by remember { mutableStateOf(false) }
val initial = options.firstOrNull { (engine, _) -> engine == mode.engine }?.first
?: FrameGen.ENGINE_OFF
val close = { if (host.open == key) host.open = null }
// Keep the options in the drawer's focus tree. A separate popup window can
// steal focus from the controller before Compose can focus the selected row.
LaunchedEffect(open) {
if (!keyboardOpened || (!open && host.open != null)) return@LaunchedEffect
val target = if (open) selectedOption else anchor
withFrameNanos { }
target.requestFocus()
if (!open) keyboardOpened = false
}
val blockedSelection = !losslessReady && mode.engine == FrameGen.ENGINE_LSFG
SettingsRow(label, losslessNote.takeIf { blockedSelection && !open }, highlighted = open) {
ValueChip(
selectedLabel, open,
modifier = focusModifier.focusRequester(anchor).onFocusChanged { anchorFocused = it.isFocused }
.heightIn(min = 48.dp).testTag("setting-$key")
.semantics { contentDescription = label; stateDescription = selectedLabel },
) {
if (open) close()
else {
keyboardOpened = anchorFocused || input.inputMode == InputMode.Keyboard
host.open = key
}
}
}
if (open) {
Column(Modifier.fillMaxWidth().padding(horizontal = 8.dp).controllerBack(close)) {
options.forEach { (engine, text) ->
val selected = engine == mode.engine
val enabled = selected || engine != FrameGen.ENGINE_LSFG || losslessReady
MenuItem(
label = text, checked = selected, enabled = enabled,
detail = losslessNote.takeIf { engine == FrameGen.ENGINE_LSFG && !losslessReady },
focusRequester = selectedOption.takeIf { engine == initial },
modifier = Modifier.heightIn(min = 48.dp).testTag("framegen-engine:$engine"),
) {
close()
if (!selected) {
onPick(if (engine == FrameGen.ENGINE_OFF) FrameGen.Mode.OFF.copy(multiplier = mode.multiplier)
else FrameGen.Mode(engine, mode.multiplier.coerceIn(2, 4)))
}
}
}
MenuItem(stringResource(R.string.lsfg_import), checked = false, detail = using) { host.open = null; onImportLossless() }
}
}
}
@@ -177,6 +177,12 @@ class FrontEndState(
val launcherOrientation: Int = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER,
val homePage: String = com.droiddeck.launcher.core.AppUiPrefs.HOME_PAGE_STEAM,
val launcherFullscreen: Boolean = true,
val launcherFrost: Boolean = false,
val frostWallpaper: Boolean = true,
val frostCards: Boolean = true,
val frostTransparency: Int = FROST_WALLPAPER_DEFAULT,
val frostCardTransparency: Int = FROST_DEFAULT,
val frostSupported: Boolean = false,
val controllerHaptics: Boolean = true,
val downloadSource: String = DownloadSource.MODE_AUTO,
val downloadMirror: String = "",
@@ -240,7 +246,6 @@ class FrontEndActions(
val onVkBridgeSafe: (Boolean) -> Unit = {},
val onBridgeProtonDxvk: (Boolean) -> Unit = {},
val onFrameGenPick: (FrameGen.Mode) -> Unit,
val onImportLossless: () -> Unit,
val onProtons: () -> Unit,
val onComponents: (focusContent: Boolean) -> Unit,
val onGameComponents: (Library.SteamGame) -> Unit = { onComponents(true) },
@@ -284,6 +289,11 @@ class FrontEndActions(
val onLauncherOrientation: (Int) -> Unit = {},
val onHomePage: (String) -> Unit = {},
val onLauncherFullscreen: (Boolean) -> Unit = {},
val onLauncherFrost: (Boolean) -> Unit = {},
val onFrostWallpaper: (Boolean) -> Unit = {},
val onFrostCards: (Boolean) -> Unit = {},
val onFrostTransparency: (Int) -> Unit = {},
val onFrostCardTransparency: (Int) -> Unit = {},
val onControllerHaptics: (Boolean) -> Unit = {},
val onAnimationsEnabled: (Boolean) -> Unit = {},
val onLowStorageWarning: (Boolean) -> Unit = {},
@@ -446,6 +456,15 @@ internal suspend fun focusWithinFrames(done: () -> Boolean, target: () -> FocusR
}
}
internal suspend fun holdFocus(held: () -> Boolean, target: () -> FocusRequester?) {
val since = MainTabSteps.otherKeys
repeat(RAIL_HOLD_FRAMES) { frame ->
androidx.compose.runtime.withFrameNanos { }
if (MainTabSteps.otherKeys != since) return
if (frame == 0 || !held()) runCatching { target()?.requestFocus() }
}
}
internal suspend fun focusSoon(target: () -> FocusRequester) {
repeat(30) {
androidx.compose.runtime.withFrameNanos { }
@@ -693,7 +712,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
}
}
androidx.compose.foundation.layout.BoxWithConstraints(
modifier = Modifier.fillMaxSize().background(colors.background)
modifier = Modifier.fillMaxSize().background(if (LocalFrost.current != null) Color.Transparent else colors.background)
.windowInsetsPadding(if (s.launcherFullscreen) WindowInsets.displayCutout else WindowInsets.systemBars)
.onFocusChanged { anyFocused = it.hasFocus },
) {
@@ -775,10 +794,13 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
val stepScope = androidx.compose.runtime.rememberCoroutineScope()
val pageKeyNow = androidx.compose.runtime.rememberUpdatedState(s.pageKey)
var railHold by remember { mutableStateOf<kotlinx.coroutines.Job?>(null) }
val stepView = androidx.compose.ui.platform.LocalView.current
val tabStep = androidx.compose.runtime.rememberUpdatedState { step: Int ->
if (!processSettingsPageVisible) {
val keys = navigationKeys(s)
keys.getOrNull(keys.indexOf(railSelectionNow.value) + step)?.let { key ->
releaseFocusedTextField(stepView)
OpenMenus.leaveAll(withPage = true)
PageSwipe.direction = step
if (s.dualScreen) { onRailSelect(key); return@let }
showRailPage(key, false)
@@ -847,7 +869,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
com.droiddeck.launcher.stores.StoresState.pendingInstall?.let { item -> StoreTheme(item.store) { InstallWhere(item) } }
com.droiddeck.launcher.stores.StoresState.itchPicking?.let { item -> StoreTheme(item.store) { ItchBuildPicker(item) { com.droiddeck.launcher.stores.StoresState.itchPicking = null } } }
com.droiddeck.launcher.stores.StoresState.gameJoltPicking?.let { item -> StoreTheme(item.store) { GameJoltBuildPicker(item) { com.droiddeck.launcher.stores.StoresState.gameJoltPicking = null } } }
com.droiddeck.launcher.stores.steam.SteamStore.picking?.let { item -> StoreTheme(item.store) { SteamInstallWhereDialog(item) { com.droiddeck.launcher.stores.steam.SteamStore.picking = null } } }
com.droiddeck.launcher.stores.StoresState.steamPicking?.let { item -> StoreTheme(item.store) { SteamInstallWhereDialog(item) { com.droiddeck.launcher.stores.StoresState.steamPicking = null } } }
StepsLayer(screenAt)
UiZooSheet()
SessionDrawerPreview(s.secondScreenDisplays)
@@ -1,6 +1,9 @@
package com.droiddeck.launcher.ui
import androidx.compose.ui.platform.LocalContext
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.FocusRequester
import android.os.Build
@@ -50,6 +53,7 @@ import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
@@ -103,7 +107,7 @@ internal object SetupTabs {
}
@Composable
internal fun CheckRow(state: CheckState, title: String, detail: String?, divider: Boolean = true, action: (@Composable () -> Unit)? = null) {
internal fun CheckRow(state: CheckState, title: String, detail: String?, divider: Boolean = true, detailLines: Int = 2, action: (@Composable () -> Unit)? = null) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val tint = when (state) {
@@ -135,7 +139,7 @@ internal fun CheckRow(state: CheckState, title: String, detail: String?, divider
}
Column(modifier = Modifier.weight(1f)) {
Text(title, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
if (detail != null) Text(detail, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 2, overflow = TextOverflow.Ellipsis)
if (detail != null) Text(detail, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = detailLines, overflow = TextOverflow.Ellipsis)
}
if (action != null) action()
}
@@ -152,6 +156,20 @@ internal fun SetupPanel(
) {
val host = rememberMenuHost()
val ctx = LocalContext.current
val frostRow = s.frostSupported && s.theme != Themes.TRUE_BLACK
var steamOrientation by remember { mutableStateOf(SessionPrefs.orientation(ctx, "steam")) }
var desktopOrientation by remember { mutableStateOf(SessionPrefs.orientation(ctx, "desktop")) }
val lifecycleOwner = LocalLifecycleOwner.current
DisposableEffect(lifecycleOwner, ctx) {
val observer = LifecycleEventObserver { _, event ->
if (event == Lifecycle.Event.ON_RESUME) {
steamOrientation = SessionPrefs.orientation(ctx, "steam")
desktopOrientation = SessionPrefs.orientation(ctx, "desktop")
}
}
lifecycleOwner.lifecycle.addObserver(observer)
onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
}
var hideHomeFromRecents by remember { mutableStateOf(com.droiddeck.launcher.core.AppUiPrefs.hideHomeFromRecents(ctx)) }
var processLimitBusy by remember { mutableStateOf(false) }
var processLimitMessage by remember { mutableStateOf<String?>(null) }
@@ -251,7 +269,7 @@ internal fun SetupPanel(
val listing = searching && query.isNotBlank()
val fixed = tab == CONTROLLER_TAB && !listing
Column(modifier = Modifier.weight(1f).fillMaxWidth().then(if (fixed) Modifier else Modifier.verticalScroll(rememberScrollState())).padding(bottom = if (fixed) 0.dp else 24.dp)) {
if (listing) SettingsSearchResults(query) { section -> pick(section.ordinal) }
if (listing) SettingsSearchResults(query, frostRow) { section -> pick(section.ordinal) }
else when (tab) {
OVERVIEW_TAB -> {
OnboardingCard(limitBlocks, a.onShowPhantomGate)
@@ -398,7 +416,8 @@ internal fun SetupPanel(
listOfNotNull(
gpu.displayName(ctx),
s.installed?.let { stringResource(R.string.setup_ready_runtime, it) },
stringResource(R.string.setup_ready_limit_off).takeIf { !limitBlocks },
stringResource(R.string.setup_ready_limit_off)
.takeIf { !limitBlocks && s.phantomProcessStatus != PhantomProcessStatus.UNCOUNTED },
s.offlineAccount?.takeIf { it.isNotEmpty() }?.let { stringResource(R.string.setup_ready_signed_in, it) },
).joinToString(" · "),
open = showChecks, onDetails = { showChecks = !showChecks },
@@ -447,6 +466,35 @@ internal fun SetupPanel(
if (s.theme == Themes.GRADIENT) GradientColorRows()
if (s.theme == Themes.CUSTOM) CustomColorRows()
if (s.theme == Themes.TRUE_BLACK) HighlightColorRow()
if (frostRow) {
ToggleRow(
host, "launcher-frost", stringResource(R.string.setup_frosted_background),
stringResource(R.string.setup_frosted_background_hint), s.launcherFrost, onChange = a.onLauncherFrost,
)
if (s.launcherFrost) {
val ctx = androidx.compose.ui.platform.LocalContext.current
val percent: (Int) -> String = { ctx.getString(R.string.ctrl_percent, it) }
ToggleRow(
host, "launcher-frost-wallpaper", stringResource(R.string.setup_frosted_wallpaper), null,
s.frostWallpaper, onChange = a.onFrostWallpaper,
)
SliderRow(
stringResource(R.string.setup_frost_transparency), stringResource(R.string.setup_frost_transparency_hint),
s.frostTransparency, 0..FROST_MAX, step = FROST_STEP, enabled = s.frostWallpaper, format = percent,
onChange = a.onFrostTransparency,
)
ToggleRow(
host, "launcher-frost-cards", stringResource(R.string.setup_frosted_cards),
stringResource(if (s.frostWallpaper) R.string.setup_frosted_cards_hint else R.string.setup_frosted_cards_needs_wallpaper),
s.frostCards, enabled = s.frostWallpaper, onChange = a.onFrostCards,
)
SliderRow(
stringResource(R.string.setup_frost_card_transparency), stringResource(R.string.setup_frost_card_transparency_hint),
s.frostCardTransparency, 0..FROST_MAX, step = FROST_STEP, enabled = s.frostWallpaper && s.frostCards, format = percent,
onChange = a.onFrostCardTransparency,
)
}
}
ChoiceRow(
host, "app-scale", stringResource(R.string.setup_app_scale), stringResource(R.string.setup_app_scale_hint),
com.droiddeck.launcher.core.AppUiPrefs.scales.map { percent ->
@@ -516,7 +564,27 @@ internal fun SetupPanel(
ChoiceRow(
host, "orientation", stringResource(R.string.setup_session_orientation), stringResource(R.string.setup_session_orientation_hint),
SessionPrefs.orientationOptions.map { (value, label) -> value to stringResource(label) },
s.orientation, onPick = a.onOrientation,
s.orientation, onPick = { value ->
a.onOrientation(value)
steamOrientation = SessionPrefs.orientation(ctx, "steam")
desktopOrientation = SessionPrefs.orientation(ctx, "desktop")
},
)
ChoiceRow(
host, "orientation-steam", stringResource(R.string.setup_session_orientation) + " (Steam)", stringResource(R.string.setup_session_orientation_hint),
SessionPrefs.orientationOptions.map { (value, label) -> value to stringResource(label) },
steamOrientation, onPick = { value ->
steamOrientation = value
SessionPrefs.setOrientation(ctx, "steam", value)
},
)
ChoiceRow(
host, "orientation-desktop", stringResource(R.string.setup_session_orientation) + " (Desktop)", stringResource(R.string.setup_session_orientation_hint),
SessionPrefs.orientationOptions.map { (value, label) -> value to stringResource(label) },
desktopOrientation, onPick = { value ->
desktopOrientation = value
SessionPrefs.setOrientation(ctx, "desktop", value)
},
)
ToggleRow(
host, "launcher-fullscreen", stringResource(R.string.setup_fullscreen),
@@ -643,7 +711,7 @@ internal fun SetupPanel(
ToggleRow(host, "agent-pet", stringResource(R.string.setup_agent_pet), stringResource(R.string.setup_agent_pet_hint), AgentPet.enabled) {
AgentPet.set(agentContext, it)
}
if (AgentPet.enabled && !AgentPet.allowed) ActionRow(
if (AgentPet.enabled && !AgentPet.allowed && AgentPet.usesOverlayWindows(com.droiddeck.launcher.session.QuestExperimental.isSupported())) ActionRow(
stringResource(R.string.setup_agent_pet_float), stringResource(R.string.setup_agent_pet_float_hint),
stringResource(R.string.setup_agent_pet_allow), onClick = { AgentPet.requestFloating(agentContext) },
)
@@ -792,7 +860,7 @@ internal fun ReadinessCard(
@Composable
private fun FrameGenMenu(s: FrontEndState, a: FrontEndActions, host: MenuHost) {
FrameGenMenu(host, s.frameGen, s.lossless, a.onFrameGenPick, a.onImportLossless)
FrameGenMenu(s.frameGen, s.lossless, a.onFrameGenPick, legacyButtons = true)
}
@Composable
@@ -819,6 +887,33 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
val steamCard: (@Composable (Modifier) -> Unit)? = if (game != null && steamScope != null) { m ->
Box(m) { GameSettingsCard(host, game, steamScope) }
} else null
val frameGenMenuContent: @Composable () -> Unit = {
FrameGenMenu(
mode = if (frameGenProfileKey != null) gameFrameGenMode else s.frameGen,
lossless = s.lossless,
onPick = { mode ->
val key = frameGenProfileKey
if (key == null) {
a.onFrameGenPick(mode)
} else {
com.droiddeck.launcher.gpu.FrameGen.setForGame(context, key, mode)
gameFrameGenMode = mode
gameFrameGenOverride = true
}
},
legacyButtons = true,
gameProfileId = frameGenProfileKey,
hasGameOverride = gameFrameGenOverride,
onResetGame = {
val key = frameGenProfileKey
if (key != null) {
com.droiddeck.launcher.gpu.FrameGen.clearGame(context, key)
gameFrameGenMode = com.droiddeck.launcher.gpu.FrameGen.mode(context)
gameFrameGenOverride = false
}
},
)
}
val cards = if (game?.library == com.droiddeck.launcher.frontend.Library.EPIC_LAUNCHER) listOfNotNull(steamCard) else buildList<@Composable (Modifier) -> Unit> {
add { m ->
val back = stringResource(R.string.hop_from_games)
@@ -840,33 +935,7 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
) {
host.open = if (host.open == "fg") null else "fg"
}
FrameGenMenu(
host = host,
mode = if (frameGenProfileKey != null) gameFrameGenMode else s.frameGen,
lossless = s.lossless,
onPick = { mode ->
val key = frameGenProfileKey
if (key == null) {
a.onFrameGenPick(mode)
} else {
com.droiddeck.launcher.gpu.FrameGen.setForGame(context, key, mode)
gameFrameGenMode = mode
gameFrameGenOverride = true
}
},
onImportLossless = a.onImportLossless,
gameProfileId = frameGenProfileKey,
hasGameOverride = gameFrameGenOverride,
onResetGame = {
val key = frameGenProfileKey
if (key != null) {
com.droiddeck.launcher.gpu.FrameGen.clearGame(context, key)
gameFrameGenMode =
com.droiddeck.launcher.gpu.FrameGen.mode(context)
gameFrameGenOverride = false
}
}
)
}
}
if (controller != null) add { m -> SettingCard(stringResource(R.string.setup_card_controls), stringResource(R.string.setup_card_controls_hint), "card:controls", m, controller.onMapping) }
@@ -898,6 +967,11 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
repeat(columns - row.size) { Spacer(Modifier.weight(1f)) }
}
}
if (host.open == "fg") {
Box(Modifier.fillMaxWidth().padding(top = 4.dp)) {
frameGenMenuContent()
}
}
}
}
@@ -235,7 +235,7 @@ internal fun GameDetail(
steppedTo = null
return@LaunchedEffect
}
focusSoon { tabFocus.getValue(t) }
holdFocus({ onStrip }) { tabFocus.getValue(t) }
steppedTo = null
}
fun cycle(step: Int) {
@@ -243,7 +243,7 @@ internal fun GameDetail(
val at = tabs.indexOf(tab).coerceAtLeast(0)
val next = tabs[(at + step + tabs.size) % tabs.size]
picked = next
if (inPage) steppedTo = next
steppedTo = next
}
val art: Any? = game?.hero ?: item?.imageUrl ?: installed?.sidecar?.hero ?: installed?.sidecar?.cover
val artModel: Any? = if (art is String) cardArtRequest(art, item?.tallImageUrl) else art
@@ -396,7 +396,7 @@ private fun GameCapsule(scores: GameScores?, actions: @Composable () -> Unit) {
}
@Composable
private fun GameTabBar(
internal fun GameTabBar(
tabs: List<String>, selected: Int, onSelect: (Int) -> Unit,
modifier: Modifier = Modifier, focusRequesters: List<FocusRequester>? = null,
bumpers: Boolean = true, compact: Boolean = false,
@@ -23,6 +23,9 @@ import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.draw.clip
@@ -31,6 +34,7 @@ import androidx.compose.ui.semantics.Role
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.sp
import androidx.compose.runtime.getValue
import com.droiddeck.launcher.session.SessionPrefs
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
@@ -67,6 +71,21 @@ internal val GlassesIcon: ImageVector by lazy {
}.build()
}
@Composable
internal fun rememberShowGlassesShortcut(): Boolean {
val context = LocalContext.current
var show by remember(context) { mutableStateOf(SessionPrefs.showGlassesShortcut(context)) }
DisposableEffect(context) {
val preferences = context.getSharedPreferences("session", android.content.Context.MODE_PRIVATE)
val listener = android.content.SharedPreferences.OnSharedPreferenceChangeListener { _, key ->
if (key == "showGlassesShortcut") show = SessionPrefs.showGlassesShortcut(context)
}
preferences.registerOnSharedPreferenceChangeListener(listener)
onDispose { preferences.unregisterOnSharedPreferenceChangeListener(listener) }
}
return show
}
@Composable
internal fun rememberGlasses(): Pair<GlassesState, GlassesSettings> {
val g by Glasses.state.collectAsState()
@@ -88,7 +107,7 @@ internal fun VrControllerGroups(host: MenuHost, track: (String) -> Modifier = {
androidx.compose.runtime.LaunchedEffect(Unit) { com.droiddeck.launcher.input.VrControllers.load(context) }
val c by com.droiddeck.launcher.input.VrControllers.settings.collectAsState()
val emulate = com.droiddeck.launcher.input.VrControllers.Emulate.entries
SettingsGroup(stringResource(R.string.vr_controllers_group)) {
SettingsGroup(stringResource(R.string.vr_controllers_group), key = "vr-controllers") {
ChoiceRow(host, "vr-emulate", stringResource(R.string.vr_controllers_emulate), stringResource(R.string.vr_controllers_emulate_hint),
emulate.map { it to stringResource(when (it) {
com.droiddeck.launcher.input.VrControllers.Emulate.OFF -> R.string.vr_controllers_off
@@ -133,6 +152,7 @@ internal fun GlassesGroups(
) {
val display = tab == null || tab == GlassesTab.DISPLAY
val vr = tab == null || tab == GlassesTab.VR
val showShortcut = rememberShowGlassesShortcut()
val picture = GlassesRendering.picture(s, g.sbs, steamVrRunning)
val usesGlasses = GlassesRendering.usesGlasses(g, outputActive, steamVrRunning)
val spatialTracking = g.spatialConnected && s.positionalTracking
@@ -142,13 +162,13 @@ internal fun GlassesGroups(
val directView = usesGlasses && picture == GlassesRendering.Picture.STEREO
val menuScreen = !inSession && g.usable && s.gameOnGlasses && s.screen3dof
if (g.canControl && onRecenter != null && s.headTracking && (virtualScreen || menuScreen || (directView && steamVrRunning))) {
SettingsGroup(stringResource(R.string.glasses_quick_actions), compact = true) {
SettingsGroup(stringResource(R.string.glasses_quick_actions), compact = true, key = "vr-glasses-quick") {
ActionRow(stringResource(R.string.glasses_recenter),
if (virtualScreen || menuScreen) stringResource(R.string.glasses_recenter_screen_hint) else null,
stringResource(R.string.cardboard_recenter_button), onRecenter)
}
}
if (display) SettingsGroup(g.model) {
if (display) SettingsGroup(g.model, key = "vr-glasses") {
if (g.experimental) SettingsRow(stringResource(R.string.glasses_control), stringResource(
if (g.supportsDisplayModeControl) R.string.glasses_xreal_experimental else R.string.glasses_pro2_experimental)) {}
val status = if (g.hasDisplay) stringResource(R.string.glasses_status, g.width, g.height, kotlin.math.round(g.hz).toInt(),
@@ -168,9 +188,15 @@ internal fun GlassesGroups(
}
ToggleRow(host, "glasses-game", stringResource(R.string.glasses_game_on), stringResource(R.string.glasses_game_on_hint),
s.gameOnGlasses, chipModifier = track("glasses-game")) { Glasses.setGameOnGlasses(it) }
if (inSession) {
val context = androidx.compose.ui.platform.LocalContext.current
ToggleRow(host, "glasses-shortcut", stringResource(R.string.glasses_show_shortcut),
stringResource(R.string.glasses_show_shortcut_hint), showShortcut,
chipModifier = track("glasses-shortcut")) { SessionPrefs.setShowGlassesShortcut(context, it) }
}
}
if (display && g.canControl && g.supportsDisplayModeControl && (inSession || g.sbs || g.sbsSupport == GlassesState.SBS_FAILS)) {
SettingsGroup(stringResource(R.string.glasses_display_mode)) {
SettingsGroup(stringResource(R.string.glasses_display_mode), key = "vr-glasses-mode") {
if (g.sbsSupport == GlassesState.SBS_FAILS && !g.sbs) {
ActionRow(stringResource(R.string.glasses_3d), stringResource(R.string.glasses_3d_failed),
stringResource(R.string.stores_dl_retry), { Glasses.set3d(true) })
@@ -182,12 +208,12 @@ internal fun GlassesGroups(
val profiles = if (inSession) listOf(GlassesDisplayModes.profile(g.sbs, false))
else listOf(GlassesDisplayProfile.TWO_D, GlassesDisplayProfile.THREE_D)
for (profile in profiles) SettingsGroup(stringResource(if (profile == GlassesDisplayProfile.TWO_D)
R.string.glasses_output_2d else R.string.glasses_output_3d)) {
R.string.glasses_output_2d else R.string.glasses_output_3d), key = "vr-glasses-output-${profile.name.lowercase()}") {
GlassesResolutionRow(host, g, s, profile, track)
if ((profile == GlassesDisplayProfile.THREE_D) == g.sbs) GlassesRefreshRow(host, g, s, track)
}
}
if (display && (g.canControl || g.hasDisplay)) SettingsGroup(stringResource(R.string.glasses_picture_group)) {
if (display && (g.canControl || g.hasDisplay)) SettingsGroup(stringResource(R.string.glasses_picture_group), key = "vr-glasses-picture") {
ChoiceRow(host, "glasses-picture", stringResource(R.string.glasses_picture), stringResource(R.string.glasses_picture_hint),
listOf(
GlassesSettings.PICTURE_AUTO to stringResource(R.string.glasses_picture_auto),
@@ -213,7 +239,7 @@ internal fun GlassesGroups(
format = { SpatialMeasurements.distance(it / 10f) }, modifier = track("glasses-distance")) { Glasses.setScreenDistanceDm(it) }
}
}
if (vr && (g.canControl || g.hasDisplay)) SettingsGroup(stringResource(R.string.cardboard_steamvr)) {
if (vr && (g.canControl || g.hasDisplay)) SettingsGroup(stringResource(R.string.cardboard_steamvr), key = "vr-glasses-steamvr") {
steamVr()
if (g.supportsDisplayModeControl) ToggleRow(host, "glasses-auto3d", stringResource(R.string.glasses_auto3d),
stringResource(R.string.glasses_auto3d_hint), s.auto3d, chipModifier = track("glasses-auto3d")) { Glasses.setAuto3d(it) }
@@ -226,7 +252,7 @@ internal fun GlassesGroups(
format = { "$it°" }, modifier = track("glasses-vr-fov")) { Glasses.setVrFovDeg(it) }
}
if ((tab == null || tab == GlassesTab.TRACKING) && g.canControl) {
SettingsGroup(stringResource(R.string.glasses_head_tracking)) {
SettingsGroup(stringResource(R.string.glasses_head_tracking), key = "vr-glasses-tracking") {
val trackingHint = when {
inSession && !usesGlasses -> R.string.glasses_screen_no_output
spatialVr -> R.string.glasses_head_tracking_spatial_vr_hint
@@ -240,13 +266,13 @@ internal fun GlassesGroups(
chipModifier = track("glasses-tracking")) { Glasses.setHeadTracking(it) }
}
val calibration by Glasses.calibration.collectAsState()
if (calibration.supported) SettingsGroup(stringResource(R.string.glasses_calibration)) {
if (calibration.supported) SettingsGroup(stringResource(R.string.glasses_calibration), key = "vr-glasses-calibration") {
GlassesCalibrationControls(calibration,
onStart = Glasses::startCalibration, onCancel = Glasses::cancelCalibration,
onReset = Glasses::resetCalibration, onDone = { onRecenter?.invoke() })
}
}
if ((tab == null || tab == GlassesTab.HARDWARE) && g.canControl && g.hardwareControls) SettingsGroup(stringResource(R.string.glasses_hardware)) {
if ((tab == null || tab == GlassesTab.HARDWARE) && g.canControl && g.hardwareControls) SettingsGroup(stringResource(R.string.glasses_hardware), key = "vr-glasses-hardware") {
if (g.brightnessMax > 0) SliderRow(stringResource(R.string.glasses_brightness), null, g.brightness.coerceAtLeast(0), 0..g.brightnessMax, step = 1,
modifier = track("glasses-brightness")) { Glasses.setBrightness(it) }
if (g.volumeMax > 0) SliderRow(stringResource(R.string.glasses_volume), null, g.volume.coerceAtLeast(0), 0..g.volumeMax, step = 1,
@@ -259,7 +285,7 @@ internal fun GlassesGroups(
androidx.compose.runtime.LaunchedEffect(Unit) { HandTracking.load(context) }
if ((tab == null || tab == GlassesTab.TRACKING) && g.canControl) {
if (g.spatialConnected) {
SettingsGroup(stringResource(R.string.glasses_experimental)) {
SettingsGroup(stringResource(R.string.glasses_experimental), key = "vr-glasses-experimental") {
val spatial by SpatialTracking.status.collectAsState()
ToggleRow(host, "glasses-position", stringResource(R.string.glasses_position), stringResource(R.string.glasses_position_hint),
s.positionalTracking, chipModifier = track("glasses-position")) { Glasses.setPositionalTracking(it) }
@@ -282,7 +308,7 @@ internal fun GlassesGroups(
s.joyConTracking, enabled = s.positionalTracking, chipModifier = track("glasses-joycons")) { Glasses.setJoyConTracking(it) }
}
}
if (hands.usable) SettingsGroup(stringResource(R.string.phone_camera_tracking_group)) {
if (hands.usable) SettingsGroup(stringResource(R.string.phone_camera_tracking_group), key = "vr-hand-camera") {
HandCameraRows(host, track, inSession)
}
}
@@ -21,12 +21,20 @@ internal fun GlassesSetupPanel() {
val (glasses, settings) = rememberGlasses()
val host = rememberMenuHost()
val tabs = glassesTabs(glasses)
val context = androidx.compose.ui.platform.LocalContext.current
val showShortcut = rememberShowGlassesShortcut()
var selectedTab by rememberSaveable { mutableStateOf(GlassesTab.DISPLAY) }
val tab = selectedTab.takeIf { selected -> tabs.any { it.first == selected } } ?: GlassesTab.DISPLAY
LaunchedEffect(tab, glasses.present, glasses.canControl, glasses.model) { host.open = null }
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(12.dp)) {
Note(stringResource(R.string.setup_glasses_scope))
SettingsGroup(stringResource(R.string.glasses_shortcut_group), key = "glasses-shortcut") {
ToggleRow(host, "glasses-shortcut", stringResource(R.string.glasses_show_shortcut),
stringResource(R.string.glasses_show_shortcut_hint), showShortcut) {
com.droiddeck.launcher.session.SessionPrefs.setShowGlassesShortcut(context, it)
}
}
if (!glasses.present && !glasses.hasDisplay && !glasses.canControl) {
Note(stringResource(R.string.setup_glasses_connect))
} else {
@@ -76,7 +76,7 @@ internal fun WindowDialog(
content: @Composable () -> Unit,
) {
if (!LocalPresentationWindow.current) {
Dialog(onDismissRequest, properties, content)
Dialog(onDismissRequest, properties) { SolidSurfaces(content) }
return
}
Popup(
@@ -87,7 +87,7 @@ internal fun WindowDialog(
Modifier.fillMaxSize().background(androidx.compose.ui.graphics.Color.Black.copy(alpha = 0.6f))
.tapOutside { if (properties.dismissOnClickOutside) onDismissRequest() },
contentAlignment = Alignment.Center,
) { content() }
) { SolidSurfaces(content) }
}
}
@@ -150,7 +150,7 @@ internal fun GlidePopup(
) {
Popup(popupPositionProvider, onDismissRequest, properties) {
if (properties.focusable) TrackKeyWindow()
FocusGlideHost(content = content)
SolidSurfaces { FocusGlideHost(content = content) }
}
}
@@ -174,14 +174,15 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
detail = if (library.usersOfBindings(b.id).size > 1) stringResource(R.string.input_shared_detail, b.name, library.usersOfBindings(b.id).size)
else "${profile.name} · ${roleLabel(role)}", onSave = { action ->
if (update { l ->
val currentPreset = l.preset(editing.preset)
val geometry = if (!editing.click && elementProperties != null && layout != null) l.withLayout(layout.copy(elements = layout.elements.map {
if (it.id == elementProperties!!.id) elementProperties!!.copy(name = elementProperties!!.name.trim().ifBlank { it.name }) else it
})) else l
geometry.withPreset(when {
editing.element != null && editing.click -> b.copy(clicks = b.clicks + (editing.element.id to action))
editing.element != null -> b.copy(elements = b.elements + (editing.element.id to action))
editing.key != null -> b.copy(keys = b.keys.filterNot { it.key == editing.key } + PhysicalInputBinding(editing.key, action))
else -> b.copy(controls = b.controls + (editing.control to action))
editing.element != null && editing.click -> currentPreset.copy(clicks = currentPreset.clicks + (editing.element.id to action))
editing.element != null -> currentPreset.copy(elements = currentPreset.elements + (editing.element.id to action))
editing.key != null -> currentPreset.copy(keys = currentPreset.keys.filterNot { it.key == editing.key } + PhysicalInputBinding(editing.key, action))
else -> currentPreset.copy(controls = currentPreset.controls + (editing.control to action))
}) }) edit = null
})
} else if (!surface) key(page, profileId, role) {
@@ -44,6 +44,7 @@ import com.droiddeck.launcher.session.SessionPrefs
import kotlin.math.abs
import kotlin.math.atan2
import kotlin.math.hypot
import kotlin.math.max
import kotlin.math.min
@SuppressLint("ViewConstructor")
@@ -63,6 +64,7 @@ class InputSurfaceView(
private val art by lazy(LazyThreadSafetyMode.NONE) { PadArt(context) }
private var artworkDpad = emptyList<HoldButton>()
private val artworkDpadBounds = RectF()
private var crossDpads = emptyList<Pair<List<HoldButton>, RectF>>()
private var requestedLayout = customLayout
init { customLayout = surfaceStyle.shown(customLayout); addView(content, LayoutParams(-1, -1)); renderCustom(pad) }
@@ -185,6 +187,7 @@ class InputSurfaceView(
private fun renderCustom(pad: PadBridge?) {
artworkDpad = emptyList()
crossDpads = emptyList()
val canvas = object : ViewGroup(context) {
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val layout = customLayout
@@ -203,6 +206,7 @@ class InputSurfaceView(
child.layout(x, y, x + child.measuredWidth, y + child.measuredHeight)
}
updateArtworkDpad(this)
updateCrossDpad(this)
}
override fun dispatchDraw(canvas: Canvas) {
@@ -244,11 +248,39 @@ class InputSurfaceView(
canvas.getChildAt(index) as? HoldButton
}
val previous = artworkDpad
artworkDpad = if (crossed(buttons)) buttons else emptyList()
artworkDpad = if (crossed(buttons, artworkDpadBounds)) buttons else emptyList()
if (artworkDpad != previous) (previous + artworkDpad).forEach { it.invalidate() }
}
private fun crossed(buttons: List<HoldButton>): Boolean {
private fun updateCrossDpad(canvas: ViewGroup) {
val buttons = (0 until canvas.childCount).map(canvas::getChildAt).filterIsInstance<HoldButton>()
val (ups, rights, downs, lefts) = DIRECTIONS.map { direction -> buttons.filter { (it.tag as? InputSurfaceElement)?.control == direction } }
crossDpads = ups.flatMap { up -> rights.flatMap { right -> downs.flatMap { down ->
lefts.mapNotNull { left -> listOf(up, right, down, left).let { arms -> hole(arms)?.let { arms to it } } } } } }
}
private fun hole(buttons: List<HoldButton>): RectF? {
val (up, right, down, left) = buttons
val hole = RectF(left.right.toFloat(), up.bottom.toFloat(), right.left.toFloat(), down.top.toFloat())
val across = max(up.left, down.left) to min(up.right, down.right)
val along = max(left.top, right.top) to min(left.bottom, right.bottom)
return hole.takeIf {
!it.isEmpty && across.first < across.second && along.first < along.second &&
across.first < it.right && across.second > it.left && along.first < it.bottom && along.second > it.top
}
}
private fun crossTarget(x: Float, y: Float): HoldButton? {
val first = crossDpads.firstOrNull()?.first?.first() ?: return null
val hx = x - (originX(first) - first.left)
val hy = y - (originY(first) - first.top)
return crossDpads.filter { (arms, hole) -> arms.all { it.visibility == VISIBLE } && hole.contains(hx, hy) }
.flatMap { it.first }.distinct().minByOrNull { arm ->
hypot(max(max(arm.left - hx, hx - arm.right), 0f), max(max(arm.top - hy, hy - arm.bottom), 0f))
}
}
private fun crossed(buttons: List<HoldButton>, bounds: RectF): Boolean {
if (buttons.size != DIRECTIONS.size) return false
val (up, right, down, left) = buttons
val centerX = (left.left + right.right) / 2f
@@ -258,7 +290,7 @@ class InputSurfaceView(
kotlin.math.abs((left.top + left.bottom) / 2f - centerY) > 2f ||
kotlin.math.abs((right.top + right.bottom) / 2f - centerY) > 2f ||
up.bottom >= down.top || left.right >= right.left) return false
artworkDpadBounds.set(left.left.toFloat(), up.top.toFloat(), right.right.toFloat(), down.bottom.toFloat())
bounds.set(left.left.toFloat(), up.top.toFloat(), right.right.toFloat(), down.bottom.toFloat())
return true
}
@@ -284,6 +316,7 @@ class InputSurfaceView(
val views = (canvas.childCount - 1 downTo 0).map(canvas::getChildAt).filter { it.visibility == VISIBLE }
views.firstOrNull { !(it is StickView && it.adaptive) && hits(it, x, y, 0f) }?.let { return it }
views.filter { it is HoldButton && hits(it, x, y, slack(it)) }.minByOrNull { distance(it, x, y) }?.let { return it }
crossTarget(x, y)?.let { return it }
if (views.any { it is HoldButton && hits(it, x, y, slack(it) + ADAPTIVE_CLEARANCE_PX) }) return null
return views.filter { it is StickView && it.adaptive && it !in owners.values && (hits(it, x, y, 0f) || it.captures(x - originX(it), y - originY(it))) }
.minByOrNull { distance(it, x, y) }
@@ -0,0 +1,130 @@
package com.droiddeck.launcher.ui
import android.app.Activity
import android.graphics.drawable.ColorDrawable
import android.os.Build
import android.os.PowerManager
import android.view.WindowManager
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.compositeOver
import androidx.compose.ui.graphics.lerp
import androidx.compose.ui.graphics.luminance
import java.util.function.Consumer
internal val LocalFrost = staticCompositionLocalOf<Color?> { null }
internal const val FROST_MAX = 100
internal const val FROST_STEP = 10
internal const val FROST_DEFAULT = 50
internal const val FROST_WALLPAPER_DEFAULT = 80
private const val FROST_TEXT_LIFT = 0.5f
private const val FROST_LIFT_STEPS = 5
private const val FROST_TINT_MAX = 0.9f
private const val FROST_SEARCH_STEPS = 12
private const val FROST_BLUR_DP = 28
private class FrostScale(val solid: Float, val default: Float, val clear: Float) {
fun at(percent: Int): Float {
val t = percent.coerceIn(0, FROST_MAX) / FROST_DEFAULT.toFloat()
return if (t <= 1f) solid + (default - solid) * t else default + (clear - default) * (t - 1f)
}
}
private val TINT_DARK = FrostScale(0.9f, 0.58f, 0.32f)
private val TINT_LIGHT = FrostScale(0.94f, 0.7f, 0.48f)
private val CARD_DARK = FrostScale(1f, 0.6f, 0.3f)
private val CARD_LIGHT = FrostScale(1f, 0.74f, 0.45f)
private val TEXT_LIFT_MAX = FrostScale(FROST_TEXT_LIFT, FROST_TEXT_LIFT, 1f)
class FrostChoice(
val transparency: Int = FROST_WALLPAPER_DEFAULT,
val cards: Boolean = false,
val cardTransparency: Int = FROST_DEFAULT,
)
internal class FrostLook(val veil: Color, val lift: Float, val cardAlpha: Float)
internal fun frostLook(palette: Palette, choice: FrostChoice): FrostLook {
val light = palette.background.luminance() > 0.5f
val cardAlpha = if (!choice.cards) 1f else (if (light) CARD_LIGHT else CARD_DARK).at(choice.cardTransparency)
val maxLift = maxOf(TEXT_LIFT_MAX.at(choice.transparency), if (choice.cards) TEXT_LIFT_MAX.at(choice.cardTransparency) else 0f)
// Android reports only the wallpaper's main colours, and any part of it can sit behind text.
fun readable(alpha: Float, lift: Float): Boolean = listOf(Color.Black, Color.White).all { behind ->
val page = palette.background.copy(alpha = alpha).compositeOver(behind)
val card = palette.surface.copy(alpha = cardAlpha).compositeOver(page)
val hint = lerp(palette.onSurfaceVariant, palette.onBackground, lift)
minOf(ThemeColors.contrast(hint, page), ThemeColors.contrast(hint, card)) >= ThemeColors.MIN_CONTRAST
}
var low = 0f
var high = FROST_TINT_MAX
if (readable(low, maxLift)) high = low
else if (!readable(high, maxLift)) high = 1f
else repeat(FROST_SEARCH_STEPS) {
val mid = (low + high) / 2
if (readable(mid, maxLift)) high = mid else low = mid
}
val lifts = (0..FROST_LIFT_STEPS).map { FROST_TEXT_LIFT + (maxLift - FROST_TEXT_LIFT) * it / FROST_LIFT_STEPS }
val tint = maxOf((if (light) TINT_LIGHT else TINT_DARK).at(choice.transparency), kotlin.math.ceil(high * 255f) / 255f)
val alpha = if (lifts.any { readable(tint, it) }) tint else 1f
val lift = lifts.firstOrNull { readable(alpha, it) } ?: maxLift
return FrostLook(palette.background.copy(alpha = alpha), lift, cardAlpha)
}
internal fun Palette.frosted(look: FrostLook): Palette = Palette(
id, label, detail,
background = background,
surface = if (look.cardAlpha < 1f) surface.copy(alpha = look.cardAlpha) else surface,
surfaceVariant = if (look.cardAlpha < 1f) surfaceVariant.copy(alpha = look.cardAlpha) else surfaceVariant,
line = line, line2 = line2,
onBackground = onBackground, onSurfaceVariant = lerp(onSurfaceVariant, onBackground, look.lift),
primary = primary, primary2 = primary2, onPrimary = onPrimary, signal = signal,
good = good, error = error, warning = warning,
)
internal class LauncherFrost(private val activity: Activity) {
var available by mutableStateOf(false)
private set
var prepared = false
private set
private var stopListening: (() -> Unit)? = null
val supported: Boolean
get() = Build.VERSION.SDK_INT >= 31 &&
(available || activity.getSystemService(PowerManager::class.java)?.isPowerSaveMode == true)
fun start() {
if (Build.VERSION.SDK_INT < 31 || stopListening != null) return
val windows = activity.windowManager
val blur = Consumer<Boolean> { available = it }
available = windows.isCrossWindowBlurEnabled
windows.addCrossWindowBlurEnabledListener(blur)
stopListening = { windows.removeCrossWindowBlurEnabledListener(blur) }
}
fun stop() {
stopListening?.invoke()
stopListening = null
}
// A window made see-through after its first frame keeps drawing over its old frames, so this runs before setContent.
fun prepare(on: Boolean) {
prepared = on && Build.VERSION.SDK_INT >= 31
if (prepared) activity.window.setBackgroundDrawable(ColorDrawable(android.graphics.Color.TRANSPARENT))
}
fun show(on: Boolean) {
if (!prepared || Build.VERSION.SDK_INT < 31) return
val window = activity.window
val flags = WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER or WindowManager.LayoutParams.FLAG_BLUR_BEHIND
if (on) window.addFlags(flags) else window.clearFlags(flags)
window.attributes = window.attributes.apply {
blurBehindRadius = if (on) (FROST_BLUR_DP * activity.resources.displayMetrics.density).toInt() else 0
}
}
}
@@ -17,6 +17,7 @@ import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
@@ -204,9 +205,9 @@ internal object LibraryDisplay {
val scales = listOf(0.75f, 0.875f, 1f, 1.2f, 1.45f)
var level by mutableIntStateOf(DEFAULT_LEVEL)
private set
var title by mutableStateOf(true)
var title by mutableStateOf(false)
private set
var size by mutableStateOf(true)
var size by mutableStateOf(false)
private set
fun load(context: android.content.Context) {
@@ -531,13 +532,11 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
val grid = remember { LazyGridState() }
val detailScroll = rememberScrollState()
var cycled by remember { mutableIntStateOf(0) }
var gridFocused by remember { mutableStateOf(false) }
LaunchedEffect(source, sort) { grid.scrollToItem(0) }
LaunchedEffect(cycled) {
if (cycled == 0 || ff == null || inputMode.inputMode != androidx.compose.ui.input.InputMode.Keyboard) return@LaunchedEffect
focusWithinFrames({ gridFocused }) {
if (ff.firstTileAttached > 0) ff.firstTile else ff.items["libchip:$source"] ?: FocusRequester.Default
}
val chip = "libchip:$source"
holdFocus({ ff.last == chip }) { ff.items[chip] }
}
CardDetailHost(
open, detailScroll,
@@ -563,7 +562,7 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
else { focusManager.clearFocus(force = true); onSelect(it) }
},
searchCleared = open != null,
onFocus = { gridFocused = it },
onFocus = {},
soundMode = soundMode,
wallArt = { wallTiles(all.filterNot(concealed).mapNotNull { entryArt(it, tall = true) }) },
emptyText = when {
@@ -753,20 +752,23 @@ private fun LibraryGrid(
}
}
}
val manage = !soundMode && !s.shortcutPicker
LazyVerticalGrid(
columns = if (listMode) GridCells.Fixed(1) else remember(baseWidth, level) { LevelCells(baseWidth, level) }, state = grid,
modifier = Modifier.fillMaxSize().onFocusChanged { onFocus(it.hasFocus) }.focusGroup().bumpers(onPrevious = { onCycle(-1) }, onNext = { onCycle(1) }).onSizeChanged {
val gap = with(density) { 10.dp.roundToPx() }
columns = if (listMode) 1 else libraryColumns(it.width, with(density) { baseWidth.roundToPx() }, gap, level)
gridH = it.height
},
modifier = Modifier.fillMaxSize().onFocusChanged { onFocus(it.hasFocus) }.focusGroup()
.then(if (sourceChipsShown(sources, manage)) Modifier.bumpers(onPrevious = { onCycle(-1) }, onNext = { onCycle(1) }) else Modifier)
.onSizeChanged {
val gap = with(density) { 10.dp.roundToPx() }
columns = if (listMode) 1 else libraryColumns(it.width, with(density) { baseWidth.roundToPx() }, gap, level)
gridH = it.height
},
horizontalArrangement = Arrangement.spacedBy(10.dp), verticalArrangement = Arrangement.spacedBy(10.dp),
contentPadding = PaddingValues(top = 4.dp, bottom = 16.dp),
) {
val header: @Composable () -> Unit = {
LibraryHeader(s, a, if (soundMode) total else visible.size + hiddenUninstalled, searchCleared, source == Store.XBOX.id, showUninstalled, onShowUninstalled, collections = Store.byId(source)?.takeIf { it == Store.ITCH || it == Store.GAMEJOLT }, soundMode = soundMode, onAddSoundtrack = onAddSoundtrack, onCollections = onCollections, source = source)
}
val filters: @Composable () -> Unit = { LibraryFilters(sources, source, onSource, manage = !soundMode && !s.shortcutPicker) }
val filters: @Composable () -> Unit = { LibraryFilters(sources, source, onSource, manage) }
item(key = if (soundMode) "header" else "filters", span = { GridItemSpan(maxLineSpan) }) {
Box(Modifier.onSizeChanged { chipsH = it.height }) { Rise(0) { if (soundMode) header() else filters() } }
}
@@ -908,10 +910,13 @@ private fun LibraryHeader(
if (s.steamGamesX64 && narrow) Box(Modifier.padding(top = 4.dp)) { ClientTag() }
}
private fun sourceChipsShown(sources: List<String>, manage: Boolean): Boolean =
(manage && sources.isNotEmpty()) || sources.size >= 2 || sources.singleOrNull() == LIBRARY_HIDDEN
@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
@Composable
private fun LibraryFilters(sources: List<String>, source: String, onSource: (String) -> Unit, manage: Boolean) {
val chips = (manage && sources.isNotEmpty()) || sources.size >= 2 || sources.singleOrNull() == LIBRARY_HIDDEN
internal fun LibraryFilters(sources: List<String>, source: String, onSource: (String) -> Unit, manage: Boolean) {
val chips = sourceChipsShown(sources, manage)
if (!chips && !manage) return
val pal = LocalPalette.current
val keys = if (chips) listOf(LIBRARY_ALL) + sources else emptyList()
@@ -927,42 +932,54 @@ private fun LibraryFilters(sources: List<String>, source: String, onSource: (Str
horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().padding(top = 4.dp, bottom = 2.dp),
) {
Box(Modifier.weight(1f).edgeFade(scroll).horizontalScroll(scroll)) {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.focusGroup()) {
for (id in keys) {
val store = Store.byId(id)
val dot = sourceDot(id)
val label = when (id) {
LIBRARY_ALL -> stringResource(R.string.stores_tab_all)
Library.ADDED -> stringResource(R.string.library_custom_games)
LIBRARY_FAVORITES -> stringResource(R.string.soundtracks_favorites)
LIBRARY_HIDDEN -> stringResource(R.string.apps_filter_hidden)
else -> store?.shortLabel ?: sourceLabel(id)
}
androidx.compose.runtime.key(id) {
val reveal = remember { BringIntoViewRequester() }
LaunchedEffect(source) { if (source == id) reveal.bringIntoView() }
StoreChip(
label = label, on = source == id, under = fillShown && highlighted == id, key = id, mark = dot ?: pal.signal,
modifier = Modifier.bringIntoViewRequester(reveal).testTag("library-source-$id")
.onGloballyPositioned { bounds[id] = it.boundsInParent() },
lead = {
if (dot != null) Box(Modifier.size(9.dp).background(dot, CircleShape))
else Icon(Icons.Filled.GridView, null, modifier = Modifier.size(14.dp))
},
onFocused = { focused = it },
paneKey = "libchip:$id",
) { onSource(id) }
BoxWithConstraints(Modifier.weight(1f)) {
if (sourceTabsAsMenu(maxWidth, keys.size)) {
TabMenu(
keys.map { librarySourceChipLabel(it) }, keys.indexOf(source), { onSource(keys[it]) },
chipModifier = Modifier.paneItem("libchip:$source"),
leading = { i, _ -> LibrarySourceMark(sourceDot(keys[i])) },
)
} else Box(Modifier.edgeFade(scroll).horizontalScroll(scroll)) {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.focusGroup()) {
for (id in keys) {
val dot = sourceDot(id)
androidx.compose.runtime.key(id) {
val reveal = remember { BringIntoViewRequester() }
LaunchedEffect(source) { if (source == id) reveal.bringIntoView() }
StoreChip(
label = librarySourceChipLabel(id), on = source == id, under = fillShown && highlighted == id, key = id, mark = dot ?: pal.signal,
modifier = Modifier.bringIntoViewRequester(reveal).testTag("library-source-$id")
.onGloballyPositioned { bounds[id] = it.boundsInParent() },
lead = { LibrarySourceMark(dot) },
onFocused = { focused = it },
paneKey = "libchip:$id",
) { onSource(id) }
}
}
}
if (highlighted in keys) ChipGlide(keys.indexOf(highlighted), bounds[highlighted], tint, visible = fillShown)
}
if (highlighted in keys) ChipGlide(keys.indexOf(highlighted), bounds[highlighted], tint, visible = fillShown)
}
if (manage) ManageStoresChip()
}
}
}
@Composable
private fun librarySourceChipLabel(id: String): String = when (id) {
LIBRARY_ALL -> stringResource(R.string.stores_tab_all)
Library.ADDED -> stringResource(R.string.library_custom_games)
LIBRARY_FAVORITES -> stringResource(R.string.soundtracks_favorites)
LIBRARY_HIDDEN -> stringResource(R.string.apps_filter_hidden)
else -> Store.byId(id)?.shortLabel ?: sourceLabel(id)
}
@Composable
private fun LibrarySourceMark(dot: Color?) {
if (dot != null) Box(Modifier.size(9.dp).background(dot, CircleShape))
else Icon(Icons.Filled.GridView, null, modifier = Modifier.size(14.dp))
}
@Composable
private fun sourceTitle(src: String): String = when (src) {
LIBRARY_ALL -> stringResource(R.string.library_all_games)
@@ -711,6 +711,10 @@ internal fun SheetChips(
Modifier.fillMaxWidth().onFocusChanged { within = it.hasFocus },
contentAlignment = Alignment.CenterStart,
) {
if (tabsAsMenu(maxWidth, labels.size)) {
TabMenu(labels, selected, onPick, focus = chips)
return@BoxWithConstraints
}
val equal = !width.isSpecified && maxWidth / labels.size.coerceAtLeast(1) >= 96.dp
val least = if (width.isSpecified) maxOf(width, 64.dp) else 64.dp
val scroll = rememberScrollState()
@@ -62,6 +62,7 @@ class ModeSettings(
val hdrReason: String?,
val hdrDisplay: Boolean = true,
val zeroCopy: Boolean = true,
val producerAcquireFences: Boolean? = null,
val gpuDrivers: String? = null,
val upscaler: Int = 0,
val upscaleSharpness: Int = 75,
@@ -86,7 +87,8 @@ class ModeSettings(
val fexPreset: String? = null,
val forceSsbs: Boolean = false,
val syncBackend: String? = null,
val picturePosition: String? = null,
val picturePositionLandscape: String? = null,
val picturePositionPortrait: String? = null,
val integerScaling: Boolean? = null,
val stretch16x9: Boolean? = null,
val avoidNotch: Boolean? = null,
@@ -125,6 +127,7 @@ class ModeSettingsActions(
val onResolutionPortrait: (String) -> Unit = {},
val onHdr: (Boolean) -> Unit,
val onZeroCopy: (Boolean) -> Unit = {},
val onProducerAcquireFences: (Boolean) -> Unit = {},
val onGpuDrivers: () -> Unit = {},
val onUpscaler: (Int) -> Unit = {},
val onUpscaleSharpness: (Int) -> Unit = {},
@@ -150,7 +153,7 @@ class ModeSettingsActions(
val onFexPreset: (String) -> Unit = {},
val onForceSsbs: (Boolean) -> Unit = {},
val onSyncBackend: (String) -> Unit = {},
val onPicturePosition: (String) -> Unit = {},
val onPicturePosition: (Boolean, String) -> Unit = { _, _ -> },
val onIntegerScaling: (Boolean) -> Unit = {},
val onStretch16x9: (Boolean) -> Unit = {},
val onAvoidNotch: (Boolean) -> Unit = {},
@@ -260,15 +263,16 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
ResolutionRow(host, "resolution-portrait", stringResource(R.string.display_resolution_portrait), s.resolutionPortrait, portraitChoice,
com.droiddeck.launcher.session.SessionDisplay.LINK_LANDSCAPE,
if (sessionDisplay.isLink(s.resolution)) portraitChoice else sessionDisplay.orientCustom(s.resolution, true),
s.panelSize, a.onResolutionPortrait, portrait = true)
s.picturePosition?.let { position ->
ChoiceRow(host, "picture-position", stringResource(R.string.display_picture_position), null,
listOf("top" to stringResource(R.string.display_position_top),
"bottom" to stringResource(R.string.display_position_bottom),
"left" to stringResource(R.string.display_position_left),
"right" to stringResource(R.string.display_position_right),
"center" to stringResource(R.string.display_position_center)),
position, onPick = a.onPicturePosition)
s.panelSize, a.onResolutionPortrait, portrait = true,
defaultChoice = if (s.mode == SessionService.MODE_STEAM) sessionDisplay.DEFAULT_STEAM_PORTRAIT_RESOLUTION
else sessionDisplay.DEFAULT_RESOLUTION)
s.picturePositionLandscape?.let { position ->
PicturePositionRow(host, position, key = "picture-position-landscape",
labelRes = R.string.display_picture_position_landscape) { a.onPicturePosition(false, it) }
}
s.picturePositionPortrait?.let { position ->
PicturePositionRow(host, position, key = "picture-position-portrait",
labelRes = R.string.display_picture_position_portrait) { a.onPicturePosition(true, it) }
}
if (s.stretch16x9 != null && (com.droiddeck.launcher.session.SessionDisplay.canStretch16x9(s.panelSize) ||
com.droiddeck.launcher.session.SessionDisplay.canStretch16x9(displaySize))) {
@@ -284,6 +288,11 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
stringResource(R.string.display_avoid_notch_hint), checked = enabled, onChange = a.onAvoidNotch)
}
ToggleRow(host, "zero-copy", stringResource(R.string.display_zero_copy), null, checked = s.zeroCopy, onChange = a.onZeroCopy)
s.producerAcquireFences?.let { enabled ->
ToggleRow(host, "producer-acquire-fences", stringResource(R.string.producer_acquire_fences),
stringResource(R.string.producer_acquire_fences_summary), checked = enabled,
onChange = a.onProducerAcquireFences)
}
}
SettingsGroup(stringResource(R.string.display_image_scaling)) {
s.integerScaling?.let { enabled ->
@@ -735,3 +744,22 @@ internal fun CustomFollowScaleDialog(initial: Float?, onSave: (Float) -> Unit, o
dismissButton = { androidx.compose.material3.TextButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
)
}
@Composable
internal fun PicturePositionRow(
host: MenuHost, position: String,
chipModifier: Modifier = Modifier,
key: String = "picture-position",
@androidx.annotation.StringRes labelRes: Int = R.string.display_picture_position,
onPick: (String) -> Unit,
) {
ChoiceRow(host, key, stringResource(labelRes), null,
listOf(
"center" to stringResource(R.string.display_position_center),
"top" to stringResource(R.string.display_position_top),
"bottom" to stringResource(R.string.display_position_bottom),
"left" to stringResource(R.string.display_position_left),
"right" to stringResource(R.string.display_position_right),
),
position, chipModifier = chipModifier, onPick = onPick)
}
@@ -116,10 +116,7 @@ internal object NavTabs {
fun more(s: FrontEndState) = listed(s).filter { place(s, it) == TabPlace.MORE }
fun bar(s: FrontEndState): List<String> {
val shown = listed(s).filter { place(s, it) == TabPlace.BAR }
return if (more(s).isEmpty()) shown else shown + MORE
}
fun bar(s: FrontEndState): List<String> = listed(s).filter { place(s, it) == TabPlace.BAR } + MORE
fun setHidden(context: Context, key: String, hide: Boolean) {
hidden = if (hide && hideable(key)) hidden + key else hidden - key
@@ -8,6 +8,9 @@ import com.droiddeck.launcher.input.PcKey
import androidx.compose.ui.res.stringResource
import android.view.KeyEvent
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.collectIsHoveredAsState
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
@@ -69,6 +72,9 @@ fun PcKeyboard(
sendKey: (Int, Boolean) -> Unit,
onAndroidKeyboard: () -> Unit,
onClose: () -> Unit,
heightFraction: Float? = null,
showButtons: Boolean = true,
hoverFeedback: Boolean = false,
) {
val pal = LocalPalette.current
val colors = MaterialTheme.colorScheme
@@ -76,31 +82,40 @@ fun PcKeyboard(
var capsOn by remember { mutableStateOf(false) }
val firstKey = remember { FocusRequester() }
val shifted = (mods[42] ?: MOD_OFF) != MOD_OFF || (mods[54] ?: MOD_OFF) != MOD_OFF
// Keys go to wherever sendKey points now, but a held key is let go where it went down.
val currentSend by androidx.compose.runtime.rememberUpdatedState(sendKey)
val heldAt = remember { mutableMapOf<Int, (Int, Boolean) -> Unit>() }
fun down(code: Int) {
val send = currentSend
heldAt[code] = send
send(code, true)
}
fun up(code: Int) = (heldAt.remove(code) ?: currentSend)(code, false)
fun releaseOnceModifiers() {
for ((code, state) in mods.toMap()) if (state == MOD_ONCE) { sendKey(code, false); mods[code] = MOD_OFF }
for ((code, state) in mods.toMap()) if (state == MOD_ONCE) { up(code); mods[code] = MOD_OFF }
}
fun press(key: PcKey) {
if (key.code in PC_MODIFIERS) {
when (mods[key.code] ?: MOD_OFF) {
MOD_OFF -> { sendKey(key.code, true); mods[key.code] = MOD_ONCE }
MOD_OFF -> { down(key.code); mods[key.code] = MOD_ONCE }
MOD_ONCE -> mods[key.code] = MOD_LOCKED
else -> { sendKey(key.code, false); mods[key.code] = MOD_OFF }
else -> { up(key.code); mods[key.code] = MOD_OFF }
}
return
}
sendKey(key.code, true)
down(key.code)
}
fun release(key: PcKey) {
if (key.code in PC_MODIFIERS) return
sendKey(key.code, false)
up(key.code)
if (key.code == 58) capsOn = !capsOn
releaseOnceModifiers()
}
androidx.compose.runtime.DisposableEffect(Unit) {
onDispose { for ((code, state) in mods.toMap()) if (state != MOD_OFF) sendKey(code, false) }
onDispose { for (code in heldAt.keys.toList()) up(code) }
}
LaunchedEffect(Unit) { runCatching { firstKey.requestFocus() } }
LaunchedEffect(Unit) { if (!hoverFeedback) runCatching { firstKey.requestFocus() } }
val prefsContext = LocalContext.current
remember { PcKeyboardPrefs.load(prefsContext) }
@@ -108,7 +123,7 @@ fun PcKeyboard(
val rows = PC_KEY_ROWS.map { row -> row.filter { it.code !in hiddenCodes } }.filter { it.isNotEmpty() }
BoxWithConstraints(Modifier.fillMaxSize(), contentAlignment = Alignment.BottomCenter) {
val rowHeight = ((maxHeight * (PcKeyboardPrefs.size / 100f) - 24.dp - 3.dp * rows.size - 10.dp) / rows.size)
val rowHeight = ((maxHeight * (heightFraction ?: (PcKeyboardPrefs.size / 100f)) - 24.dp - 3.dp * rows.size - 10.dp) / rows.size)
.coerceIn(20.dp, 56.dp)
Box(
Modifier.fillMaxWidth()
@@ -122,9 +137,11 @@ fun PcKeyboard(
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().height(24.dp)) {
Text(stringResource(R.string.drawer_pc_keyboard), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = colors.onSurfaceVariant)
Spacer(Modifier.weight(1f))
HeaderButton(stringResource(R.string.pckb_android), onAndroidKeyboard)
Spacer(Modifier.width(8.dp))
HeaderButton(stringResource(R.string.pckb_hide), onClose)
if (showButtons) {
HeaderButton(stringResource(R.string.pckb_android), onAndroidKeyboard)
Spacer(Modifier.width(8.dp))
HeaderButton(stringResource(R.string.pckb_hide), onClose)
}
}
rows.forEachIndexed { r, row ->
Row(horizontalArrangement = Arrangement.spacedBy(3.dp), modifier = Modifier.fillMaxWidth().height(rowHeight)) {
@@ -139,7 +156,7 @@ fun PcKeyboard(
}
key(key.code) {
KeyCap(
label, key.weight, lit, locked = state == MOD_LOCKED,
label, key.weight, lit, locked = state == MOD_LOCKED, hoverFeedback = hoverFeedback,
modifier = if (r == 0 && i == 0) Modifier.focusRequester(firstKey) else Modifier,
onDown = { press(key) }, onUp = { release(key) },
)
@@ -154,25 +171,35 @@ fun PcKeyboard(
@Composable
private fun RowScope.KeyCap(
label: String, weight: Float, lit: Boolean, locked: Boolean,
label: String, weight: Float, lit: Boolean, locked: Boolean, hoverFeedback: Boolean,
modifier: Modifier, onDown: () -> Unit, onUp: () -> Unit,
) {
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val focused by src.collectIsFocusedAsState()
val hovered by src.collectIsHoveredAsState()
val (pointedAt, laser) = com.droiddeck.launcher.session.xr.rememberXrPointed()
val pointed = hoverFeedback && (hovered || laser.value)
var down by remember { mutableStateOf(false) }
val fill by animateColorAsState(
when {
down -> pal.signal.copy(alpha = 0.55f)
lit -> pal.signal.copy(alpha = if (locked) 0.45f else 0.28f)
pointed -> Color.White.copy(alpha = 0.2f)
else -> Color.White.copy(alpha = 0.07f)
}, Motion.tw(160), label = "keyFill",
}, Motion.tw(if (down) 40 else 160), label = "keyFill",
)
val scale by animateFloatAsState(
if (!hoverFeedback) 1f else if (down) 0.9f else if (pointed) 1.06f else 1f, Motion.tw(if (down) 40 else 140), label = "keyScale",
)
Box(
contentAlignment = Alignment.Center,
modifier = modifier.weight(weight).fillMaxHeight()
.then(pointedAt)
.graphicsLayer { scaleX = 1f + (scale - 1f) * size.height / size.width; scaleY = scale }
.background(fill, RoundedCornerShape(7.dp))
.glideBorder(focused, RoundedCornerShape(7.dp), pal.signal, if (lit) pal.signal.copy(alpha = 0.7f) else Color.White.copy(alpha = 0.12f))
.glideBorder(if (hoverFeedback) pointed || down else focused, RoundedCornerShape(7.dp), pal.signal, if (lit) pal.signal.copy(alpha = 0.7f) else Color.White.copy(alpha = 0.12f))
.then(if (hoverFeedback) Modifier.hoverable(src) else Modifier)
.pointerInput(Unit) {
awaitEachGesture {
awaitFirstDown().consume()
@@ -11,7 +11,7 @@ internal fun PenSettingsGroup(
host: MenuHost, pen: SessionPrefs.Pen, track: (String) -> Modifier = { Modifier },
onPick: (key: String, value: String) -> Unit,
) {
SettingsGroup(stringResource(R.string.mode_pen)) {
SettingsGroup(stringResource(R.string.mode_pen), key = "controller-pen") {
ChoiceRow(host, "pen", stringResource(R.string.mode_pen), null,
listOf(SessionPrefs.PEN_MOUSE to stringResource(R.string.mode_pen_mouse),
SessionPrefs.PEN_TOUCH to stringResource(R.string.mode_pen_touch)),
@@ -49,6 +49,7 @@ fun PerformancePage(
prootNoSeccomp: Boolean,
prootFastPath: Boolean,
nativeUserland: Boolean,
desktopAsUser: Boolean,
cursorComposite: Boolean,
guestHostname: String,
phantomWarning: String?,
@@ -67,6 +68,7 @@ fun PerformancePage(
onProotNoSeccomp: (Boolean) -> Unit,
onProotFastPath: (Boolean) -> Unit,
onNativeUserland: (Boolean) -> Unit,
onDesktopAsUser: (Boolean) -> Unit,
onCursorComposite: (Boolean) -> Unit,
onGuestHostname: (String) -> Unit,
onClientCore: (Int, Boolean) -> Unit,
@@ -194,6 +196,12 @@ fun PerformancePage(
modifier = Modifier.width(220.dp).focusGlide(),
)
}
ToggleRow(
host, "desktopasuser", stringResource(R.string.perf_desktop_as_user),
stringResource(if (nativeUserland) R.string.perf_desktop_as_user_hint else R.string.perf_desktop_as_user_needs_native),
desktopAsUser && nativeUserland, enabled = nativeUserland,
onChange = onDesktopAsUser,
)
}
if (phantomWarning != null) {
Spacer(Modifier.height(16.dp))
@@ -218,7 +226,7 @@ fun PerformancePage(
@Composable
internal fun GpuClockGroup(host: MenuHost, on: Boolean, chipModifier: Modifier = Modifier, onChange: (Boolean) -> Unit) {
SettingsGroup(stringResource(R.string.perf_gpu)) {
SettingsGroup(stringResource(R.string.perf_gpu), key = "performance-gpu") {
ToggleRow(
host, "gpuclock", stringResource(R.string.perf_gpuclock),
null,
@@ -16,12 +16,14 @@ fun ResolutionRow(
panel: Pair<Int, Int>, onPick: (String) -> Unit,
chipModifier: Modifier = Modifier,
portrait: Boolean = false,
defaultChoice: String = SessionDisplay.DEFAULT_RESOLUTION,
) {
val custom = "custom"
val linked = stored == link
val size = SessionDisplay.resolveChoice(panel, choice, portrait)
val screen = SessionDisplay.resolveChoice(panel, SessionDisplay.MATCH_SCREEN, portrait)
val choices = SessionDisplay.resolutionOptions(panel)
val presets = SessionDisplay.resolutionOptions(panel)
val choices = if (defaultChoice == SessionDisplay.DEFAULT_RESOLUTION) presets else listOf(defaultChoice) + presets
val customFollow = !linked && SessionDisplay.isFollow(choice) && choice !in choices
val selected = if (linked) link else if (SessionDisplay.isFollow(choice)) choice
else if (size == screen) SessionDisplay.MATCH_SCREEN else choice
@@ -36,7 +38,7 @@ fun ResolutionRow(
else if (value == SessionDisplay.FOLLOW_SCREEN) stringResource(R.string.display_follow_screen)
else if (SessionDisplay.isFollow(value)) stringResource(R.string.display_follow_screen_scaled,
SessionDisplay.formatScale(SessionDisplay.followScale(value) ?: 1f)) + " (${dimensions.first}×${dimensions.second})"
else if (value == SessionDisplay.DEFAULT_RESOLUTION) stringResource(R.string.mode_res_default, "${dimensions.first}×${dimensions.second}")
else if (value == defaultChoice) stringResource(R.string.mode_res_default, "${dimensions.first}×${dimensions.second}")
else "${dimensions.first}×${dimensions.second}"
} + listOf(SessionDisplay.FOLLOW_CUSTOM to stringResource(R.string.display_follow_screen_scaled,
if (customFollow) SessionDisplay.formatScale(SessionDisplay.followScale(choice) ?: 1f) else "…"
@@ -1,6 +1,7 @@
package com.droiddeck.launcher.ui
import android.content.Context
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.compose.foundation.gestures.awaitEachGesture
@@ -48,10 +49,18 @@ internal fun releaseTextField(field: EditText, origin: IntArray, x: Float, y: Fl
val insideX = x >= origin[0] - margin && x <= origin[0] + field.width + margin
val insideY = y >= origin[1] - margin && y <= origin[1] + field.height + margin
if (insideX && insideY) return
releaseTextField(field)
}
internal fun releaseTextField(field: EditText) {
field.clearFocus()
(field.context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager)?.hideSoftInputFromWindow(field.windowToken, 0)
}
internal fun releaseFocusedTextField(view: View) {
(view.rootView.findFocus() as? EditText)?.let(::releaseTextField)
}
/** A dialog's touches never reach the activity, so a dialog holding a search field counts its taps and releases the field itself. */
internal fun Modifier.releaseTextFieldOnTap(): Modifier = composed {
val view = LocalView.current
@@ -22,9 +22,11 @@ import androidx.compose.material.icons.outlined.Tune
import androidx.lifecycle.setViewTreeLifecycleOwner
import androidx.lifecycle.setViewTreeViewModelStoreOwner
import androidx.savedstate.setViewTreeSavedStateRegistryOwner
import com.droiddeck.launcher.input.ControllerPrefs
import com.droiddeck.launcher.input.DeckPanel
import com.droiddeck.launcher.input.KeyboardHost
import com.droiddeck.launcher.input.PadBridge
import com.droiddeck.launcher.wayland.WaylandCompositor
import com.droiddeck.launcher.input.SecondScreenMode
import com.droiddeck.launcher.SessionActivity
import com.droiddeck.launcher.session.BottomDesktop
@@ -396,6 +398,7 @@ class SecondScreenPresentation(
val layout = panelLayout(mode)
val controls = InputSurfaceView(context, pad, layout?.elements.orEmpty(),
surfaceStyle = layout?.style ?: com.droiddeck.launcher.input.InputSurfaceStyle())
controls.alpha = ControllerPrefs.onScreenOpacity(context) / 100f
controlsView = controls
root.addView(controls, weightParams())
attachKeyboard()
@@ -490,12 +493,19 @@ class SecondScreenPresentation(
}
private fun attachKeyboard() {
val host = KeyboardHost(context) { event ->
val handled = sessionActivity.dispatchKeyEvent(event)
if (fieldKeyboard && event.action == KeyEvent.ACTION_UP &&
(event.keyCode == KeyEvent.KEYCODE_ENTER || event.keyCode == KeyEvent.KEYCODE_NUMPAD_ENTER)) root.post { closeFieldKeyboard() }
handled
}
val host = KeyboardHost(
context,
sendKeyEvent = { event ->
val handled = sessionActivity.dispatchImeKeyEvent(event)
if (fieldKeyboard && event.action == KeyEvent.ACTION_UP &&
(event.keyCode == KeyEvent.KEYCODE_ENTER || event.keyCode == KeyEvent.KEYCODE_NUMPAD_ENTER)) root.post { closeFieldKeyboard() }
handled
},
sendText = { text ->
WaylandCompositor.textInputCommit(text)
if (fieldKeyboard && text == "\r") root.post { closeFieldKeyboard() }
},
)
host.onImeChanged = { visible -> if (!visible && keyboardShown.value) keyboardClosed() }
keyboardHost = host
root.addView(host, ViewGroup.LayoutParams(1, 1))
@@ -6,21 +6,28 @@ import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.session.SessionPrefs
/** HUD holds the Performance page and GAMES the Game page; the names stay because saved page orders use them. */
internal enum class SessionDrawerPage(val firstControl: String) {
CONTROLLER("input-profile"),
GLASSES("glasses-game"),
DISPLAY("fg"),
HUD("hud"),
EFFECTS("look"),
GAMES("anisotropy"),
AGENT("agent-input"),
SESSION("suspend"),
CONTROLLER("section-controller-input"),
HUD("section-performance-pacing"),
FRAMEGEN("fg"),
DISPLAY("section-display"),
EFFECTS("section-effects-look"),
GAMES("section-game-profile"),
VR("section-vr-steamvr"),
SESSION("pause"),
MORE("more-edit"),
VR("steamvr"),
ACHIEVEMENTS("achievements"),
AGENT("agent-input"),
}
internal object DrawerPages {
var order by mutableStateOf(SessionDrawerPage.entries.toList())
private val defaultOrder = SessionDrawerPage.entries.toMutableList().apply {
remove(SessionDrawerPage.VR)
add(indexOf(SessionDrawerPage.MORE) + 1, SessionDrawerPage.VR)
}.toList()
var order by mutableStateOf(defaultOrder)
private set
var hidden by mutableStateOf(emptySet<SessionDrawerPage>())
private set
@@ -37,6 +44,7 @@ internal object DrawerPages {
}
fun arrange(saved: List<String>): List<SessionDrawerPage> {
if (saved.isEmpty()) return defaultOrder
val all = SessionDrawerPage.entries
val out = saved.mapNotNull { name -> all.firstOrNull { it.name == name } }.distinct().toMutableList()
for (page in all.filterNot { it in out }) {
@@ -60,27 +68,27 @@ internal object DrawerPages {
}
fun reset(context: Context) {
order = SessionDrawerPage.entries.toList()
order = defaultOrder
hidden = emptySet()
if (DevPreview.drawer != null) return
SessionPrefs.setDrawerPageOrder(context, order.map { it.name })
SessionPrefs.setDrawerPageHidden(context, emptySet())
}
fun isDefault() = order == SessionDrawerPage.entries.toList() && hidden.isEmpty()
fun isDefault() = order == defaultOrder && hidden.isEmpty()
}
internal fun offeredDrawerPages(
hasGlasses: Boolean = false, hasAgent: Boolean = com.droiddeck.launcher.agent.AgentTab.shown,
hasAchievements: Boolean = false, hasAgent: Boolean = com.droiddeck.launcher.agent.AgentTab.shown,
): List<SessionDrawerPage> =
DrawerPages.order.filter {
(hasGlasses || it != SessionDrawerPage.GLASSES) &&
(hasAchievements || it != SessionDrawerPage.ACHIEVEMENTS) &&
(hasAgent || it != SessionDrawerPage.AGENT)
}
internal fun sessionDrawerPages(
hasGlasses: Boolean = false, hasAgent: Boolean = com.droiddeck.launcher.agent.AgentTab.shown,
): List<SessionDrawerPage> = offeredDrawerPages(hasGlasses, hasAgent).filter { it !in DrawerPages.hidden }
hasAchievements: Boolean = false, hasAgent: Boolean = com.droiddeck.launcher.agent.AgentTab.shown,
): List<SessionDrawerPage> = offeredDrawerPages(hasAchievements, hasAgent).filter { it !in DrawerPages.hidden }
/** The pages shown as tabs: everything up to and including the More tab. */
internal fun List<SessionDrawerPage>.strip(): List<SessionDrawerPage> {
File diff suppressed because it is too large. Load diff
Loaded 100 of 449 files, more files were not shown because too many files have changed in this diff. Show more