Add VITURE XR controls, head tracking, and SteamVR (#732)

* Add VITURE glasses support: hardware control, 3D, head tracking

Glasses get their own controller over the MCU (permission, 120 Hz default, brightness, volume, sunblock, 2D/3D) and the game moves onto them when plugged in. The IMU drives Cardboard head tracking and the SteamVR driver. 3D falls back to one eye's view on phones that can't send the 3840x1080 signal. Options open from a glasses button in game and on the Steam page.

* Drop the glasses settings like Steam's: Play-style button, Settings lip, tabs

* Hang the glasses Settings lip over the top of the button

* Space glasses MCU commands so the IMU rate sticks, fit fixed resolutions to the glasses

* Keep Steam alive with SteamVR registered, run SteamVR at the glasses' rate, keep the glasses lip on top

* Fit VR games on the glasses: full view, seated origin at the head, pad hands reach with the d-pad

* Let the pad hands reach a metre out so buttons with deep colliders press

* Show every VR frame in order at 120 fps: wait for SteamVR's GPU work, present only finished copies, skip the grace on idle shared counters

* Glasses: SteamVR starts and stops with them, closer view with a field of view setting, Recenter on the pad

* Glasses: SteamVR field of view defaults to 90°

* VR pad hands: sticks move and aim the hands, left stick click switches the sticks to the game, d-pad pulls a held hand

* Glasses: Play SteamVR beside the glasses button instead of starting SteamVR with them, pad hands drawn as Index controllers and off while other VR controllers are connected, glasses sheet tabs sized like Steam's

* Track glasses mode, refresh-aware glasses window, align Play SteamVR with Play Steam

* Fix 3D on the glasses: full-res SteamVR presenter, revert VR 3D at session end, coalesce vsync ticks, no session restart after end

* Address review: glasses output after installs and session end, VR revert retry, display fallback, presenter swapchain retry, agent hex checks, drawer bumpers, glasses translations, docs

* Harden VITURE stereo negotiation and output refresh tracking

* Localize stereo recovery feedback and record Astra reconnect tests

* Improve test failure diagnostics and refresh Astra firmware findings

* Handle VITURE docks separately and reject truncated USB frames

* Glasses: remember a 3D fallback per model, docks as display only, VR timing fixes

- A 3D attempt that ends at the 640x480 fallback is remembered for that glasses
  model, so Play SteamVR no longer blacks out the glasses after every restart;
  Retry clears it and "3D for VR games" stays reachable
- A VITURE Mobile Dock on its own no longer counts as glasses; through a dock
  Play SteamVR is hidden and the sheet shows the output and why there is no control
- HDR is probed on the glasses when the session starts there
- Glasses frames with a mismatched checksum are marked in the status frame log
- SteamVR layer and driver vblank counters stay monotonic across refresh changes;
  one-eye render scale applies from activation and on mono/3D switches
- Compositor binds announce the refresh clients were last told; the presenter
  retries a failed first swapchain
- Dead strings and helpers removed; docs updated

* Glasses: drop USB frames with a bad checksum

* Glasses: count frames dropped for a bad checksum

* Feat/viture xr (#907)

* Add RayNeo Air and GT support to the XR glasses pipeline

* Add RayNeo Air and GT support to the XR glasses pipeline

* Checkpoint glasses tracking, calibration, and SteamVR launch integration

* Checkpoint glasses tracking, calibration, and SteamVR launch integration

* Add XREAL 1S support and correct GT and Pro 2 tracking

* Add XREAL 1S support and correct GT and Pro 2 tracking

* Fix mirrored glasses tracking and recover SteamVR after device loss

* Fix mirrored glasses tracking and recover SteamVR after device loss

* Document confirmed XREAL 1S brightness control

* Document confirmed XREAL 1S brightness control

* Fix SteamVR glasses defaults and rendering controls

* Fix SteamVR glasses defaults and rendering controls

* chore: keep only the 3 newest session log folders (#852)

* chore: add agent comment rules (#748)

Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>

* Fix SteamVR polling, VITURE checksums, and fence tracking

Keep manual SteamVR launches polled, discard corrupt VITURE packets, and retire Vulkan fences out of order without blocking submissions at a fixed capacity. Preserve the contiguous completion watermark used by the presenter.

Fix optional Windows launcher configuration and audited helper staging. Add Android, Windows, and native tracker regression coverage.

* Fix SteamVR polling, VITURE checksums, and fence tracking

Keep manual SteamVR launches polled, discard corrupt VITURE packets, and retire Vulkan fences out of order without blocking submissions at a fixed capacity. Preserve the contiguous completion watermark used by the presenter.

Fix optional Windows launcher configuration and audited helper staging. Add Android, Windows, and native tracker regression coverage.

* fix: wireless ADB page names the child-process switch the way Android shows it (#848)

* l10n: refresh stale and untranslated strings in es, fr, ko, ru (#850)

* l10n: refresh stale and untranslated strings in es, fr, ko, ru

- mode_added_art_hint: now mentions Steam then SteamGridDB (all four locales).
- wincomp_needs_installer / wincomp_installers_note: es and ko still described
  the old "coming soon" behaviour; align with the current English text.
- summary_remove_game: was still English in all four locales.

Machine-assisted translation; native-speaker review is welcome.

* l10n(es): say registro, not grabación, for the missing installer record

---------

Co-authored-by: ovurrsl <ovurrsl@users.noreply.github.com>

* fix: a failed cloud save recovery no longer ends the app (#846)

The cloud-recovery thread started at every app start had nothing to
catch an error, so one went to CrashHandler, which halts the process
with status 2. In unit tests the thread can outlive the test that
started it, fail on the torn-down preferences, and take the whole test
run down. The error is now logged and the thread ends.

Co-authored-by: Kirk <12691869+KirkPatrickJunsay@users.noreply.github.com>

* fix: an interrupted Linux runtime download resumes instead of starting again (#847)

* fix: an interrupted Linux runtime download resumes instead of starting again

installOnce() asked the downloader to resume but always deleted the archive in its finally block, so the next attempt began at zero. The archive is now named after the release version and checksum, a failed download keeps what it fetched, and archives of other releases (and the old fixed name) are removed. A checksum or extraction failure still deletes the file.

* test: Downloader resumes a cut-off download from the bytes it kept

Starts a socket server that promises the whole file, hangs up part way and then answers a Range request, and checks that the second downloadFile call resumes with the right offset and ends with identical bytes.

* fix: a resumed download discards a 206 that does not start where the kept bytes end

Downloader appended every 206 response to the partial file without
looking at Content-Range. A server or proxy that answers a Range request
with a different offset would leave a corrupt file. Check that the range
starts at the kept length; otherwise delete the partial file and start
again without a Range header.

Adds a test with a server that answers the Range request from offset 0.

---------

Co-authored-by: ovurrsl <ovurrsl@users.noreply.github.com>

* l10n: German, French, Spanish, Italian, Portuguese and Russian for the zRAM, reset-settings and store free-space strings (#849)

* l10n: German, French, Spanish, Italian, Portuguese and Russian for the zRAM, reset-settings and store free-space strings

Adds the strings values-de, values-it and values-pt were missing (14 each) and the six that values-fr, values-es and values-ru were missing. Machine-assisted drafts that follow each file's existing register and terms; native review is welcome.

* l10n: correct missing active swap translations

---------

Co-authored-by: ovurrsl <ovurrsl@users.noreply.github.com>
Co-authored-by: xXJsonDeruloXx <danielhimebauch@gmail.com>

* fix: droiddeckctl reaches variant-package builds (recover #842) (#854)

fix: droiddeckctl reaches builds shipped under a variant package

The provider authority and the start Activity's component were fixed to
com.droiddeck.launcher, so droiddeckctl could not talk to the antutu,
ludashi or pubg builds from tools/release/variants.txt. DROIDDECK_PACKAGE
now picks the package; the Activity's class name stays the same in every
variant.

Co-authored-by: angelrenefm <17342133+angelrenefm@users.noreply.github.com>

* feat: droiddeckctl reports on-screen pacing (recover #843) (#855)

feat: droiddeckctl pacing reports the frames that reached the screen

Reads SurfaceFlinger's timestats for the game's layer (or the session's
SurfaceView) over a capture: frames on screen, fps on screen, the
present-to-present histogram and how many intervals were off the usual
cadence. Records split by a refresh-rate change are summed. A game's own fps
counter counts frames handed over, so it can't show dropped or doubled frames.

Co-authored-by: angelrenefm <17342133+angelrenefm@users.noreply.github.com>

* fix: Steam can restart more than twice in a session (#754)

* fix: Steam can restart more than twice in a session

Every exit 42 counted toward the cap that stops an update which will
not install, and the count was never cleared, so the third restart of
a session ended it however far apart they were. A client that ran for
a minute before asking is not that loop: the count starts again.

* fix: measure the client's run time as it exits

The time spent collecting logs and checking FEX after the client exits
counted toward its run, so a slow cleanup could make a quick exit 42
look like a long one and clear the count.

---------

Co-authored-by: Kirk <12691869+KirkPatrickJunsay@users.noreply.github.com>
Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>

* fix: the front end keeps its page when the Fold is folded or unfolded (#832)

* fix: the front end keeps its page when the Fold is folded or unfolded

MainActivity, FileManagerActivity, FilePickerActivity and StoreLoginActivity did not declare the screen-size configuration changes, so folding or unfolding a foldable recreated them and dropped their in-memory state. They now handle orientation, screenSize, screenLayout, smallestScreenSize and density themselves, like SessionActivity already does. uiMode is left out on purpose.

* fix: store login keeps rebuilding its toolbar when the display density changes

StoreLoginActivity builds its toolbar in code with dp-to-pixel values taken at creation time and has no onConfigurationChanged. It no longer declares density in configChanges, so a density change recreates it as before this PR. Size and layout changes are still handled in place.

---------

Co-authored-by: ovurrsl <ovurrsl@users.noreply.github.com>

* Release pointer buttons without replaying stale motion (#803)

* Fix cursor warping on native touch down

* Preserve input cleanup without replaying stale pointer motion

---------

Co-authored-by: siyuan.qsy <siyuan.qsy@alibaba-inc.com>

* l10n: translate the strings added since #284 into zh-CN, zh-HK, zh-TW and ja (#539)

* l10n: translate the 184 strings added since #284 (zh-CN/HK/TW, ja)

The stores, cloud saves, Windows components, Steam touch, desktop
removal and background-downloads strings landed after #284's
translation snapshot, so every one of them fell back to English.
Translate all 184 into Simplified Chinese, Traditional Chinese
(Taiwan and Hong Kong) and Japanese, keeping each locale file's own
vocabulary (工作階段/會話, 解除安裝/卸載, 元件/組件, 設定).

Also fix four Hong Kong strings that kept the simplified 着色器.

* l10n(zh): fix stale and ambiguous strings found in review

Severe: summary_remove_game was untranslated English in all three
files; mode_added_art_hint, wincomp_installers_note and
wincomp_needs_installer still described the pre-#480/#492 English.

Also: distinguish the Setup wizard from Android system settings in
zh-HK/zh-TW (初始設定 / 系統設定 / Android 設定), unify library as
收藏庫, component as 組件 in zh-HK, session as 會話 in zh-HK, account
as 帳戶 in zh-HK, Trending as 趋势/趨勢, Forget as 清除, reword the
re-applied-at-launch, action-failed and already-in-Games strings, and
play as 執行/開啟遊戲 in zh-TW/zh-HK.

* l10n(ja): fix stale and ambiguous strings found in review

---------

Co-authored-by: Dantalian <Dantalian-dev@users.noreply.github.com>
Co-authored-by: xXJsonDeruloXx <danielhimebauch@gmail.com>

* Rebuild and verify Windows VR runtime components

* Rebuild and verify Windows VR runtime components

* Add top, bottom, and centered picture positions for Steam sessions (#871)

* fix: dependency scan ignores folders above the game folder (#859)

* DroidDeck-Proton: get releases from the Droid-Deck org repo

DroidDeck-Proton is now built and released on Droid-Deck/DroidDeck-Proton
(11-9.1 is Latest there), so the Components page, the update check and the
guest installer read releases from the org repo instead of The412Banner's.

* feat: low-latency controller and touch toggles in the session drawer (#808)

* fix: SteamGridDB lookups no longer stick as "no match" after a failure; add a search to the art chooser (#876)

* feat: Steam home wall fills from the signed-in library instead of store picks (#878)

* test: cover GPU family and support classification (#880)

* Fix local builds on Linux failing after the first Comet build (#866)

* feat: sort the store library and installed tabs, and switch between card and list views (#798)

* feat: three-finger tap toggles Steam's on-screen keyboard in game mode (#782)

* fix: keep Quest-patched Turnip as the auto default (#853)

* Fix deploy_local.sh and droiddeckctl not finding a phone connected over wireless debugging (#864)

* fix: keep proot sessions alive when the kernel loses fork events (#457)

* fix(quest): correct desktop and Steam display corruption across sessions (#733)

fix(quest): stabilize desktop and Steam layer presentation

Keep Quest SDR scenes and the black backdrop off the Android Vulkan swapchain regardless of session order or HDR preferences. Only report the first frame after client content is submitted.

Add backdrop lifecycle and first-frame regression coverage. Record the user's successful Quest 3 Test 2 result.

Co-authored-by: xXJsonDeruloXx <danielhimebauch@gmail.com>

* fix: keep SteamVR syscall hooks and report Steam crashes (#905)

* fix: preserve SteamVR syscall hooks

* fix: report Steam crashes through gamescope

* fix: honor glasses pacing and resolution in SteamVR launches

---------

Co-authored-by: connor g <connorsspam1992@gmail.com>
Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
Co-authored-by: Yassine Gherbi <y.gherbi.dev@gmail.com>
Co-authored-by: Resul Övür <92828257+ovurrsl@users.noreply.github.com>
Co-authored-by: ovurrsl <ovurrsl@users.noreply.github.com>
Co-authored-by: Kirk <kirtoy.junsay@gmail.com>
Co-authored-by: Kirk <12691869+KirkPatrickJunsay@users.noreply.github.com>
Co-authored-by: xXJsonDeruloXx <danielhimebauch@gmail.com>
Co-authored-by: angelrenefm <17342133+angelrenefm@users.noreply.github.com>
Co-authored-by: asdf17128 <asdf17128@gmail.com>
Co-authored-by: siyuan.qsy <siyuan.qsy@alibaba-inc.com>
Co-authored-by: Dantalian <wsu091227@qq.com>
Co-authored-by: Dantalian <Dantalian-dev@users.noreply.github.com>
Co-authored-by: The412Banner <the412banner@users.noreply.github.com>
Co-authored-by: The412Banner <205237651+The412Banner@users.noreply.github.com>
Co-authored-by: FX1922 <120828496+FX192@users.noreply.github.com>
Co-authored-by: Muaz Kadan <32595066+muazkadan@users.noreply.github.com>
Co-authored-by: kingokksa <47888451+kingokksa@users.noreply.github.com>
Co-authored-by: Jamie Schenker <jam1esch3nk3r@gmail.com>
Co-authored-by: Jagger15 <jagger2333@live.com>

* Glasses: keep a pending 2D restore and the SteamVR recovery offer, show Play SteamVR only with a picture

* Translate the glasses calibration, XREAL and SteamVR recovery strings

* SteamVR recovery: give a finished teardown time to collect logs before restarting

* Credit the projects the XR glasses support builds on

* Joy-Cons: SteamVR hands from their gyro while SteamVR runs, one combined pad otherwise

* Headsets: settings badge on Play SteamVR instead of a top-right button, both shown only once connected

* Hand tracking: camera-tracked Joy-Cons and bare hands in SteamVR, drawn as white gloves

- Joy-Con movement from the accelerometer (report reordering, per-Joy-Con calibration, zero-velocity updates)
- MediaPipe pose and hand landmarks from the device camera, placement check, per-hand Kalman filter with the Joy-Con
- No controller connected: bare camera hands with Quest-style gestures, 1€ filtered, rendered as a white glove model built from a distance field
- SteamVR safe mode cleared before each start so one crash no longer blocks the driver

---------

Co-authored-by: MaxsTechReview <6025299+maxjivi05@users.noreply.github.com>
Co-authored-by: informalTechCode <informaltechyt@gmail.com>
Co-authored-by: connor g <connorsspam1992@gmail.com>
Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
Co-authored-by: Yassine Gherbi <y.gherbi.dev@gmail.com>
Co-authored-by: Resul Övür <92828257+ovurrsl@users.noreply.github.com>
Co-authored-by: ovurrsl <ovurrsl@users.noreply.github.com>
Co-authored-by: Kirk <kirtoy.junsay@gmail.com>
Co-authored-by: Kirk <12691869+KirkPatrickJunsay@users.noreply.github.com>
Co-authored-by: xXJsonDeruloXx <danielhimebauch@gmail.com>
Co-authored-by: angelrenefm <17342133+angelrenefm@users.noreply.github.com>
Co-authored-by: asdf17128 <asdf17128@gmail.com>
Co-authored-by: siyuan.qsy <siyuan.qsy@alibaba-inc.com>
Co-authored-by: Dantalian <wsu091227@qq.com>
Co-authored-by: Dantalian <Dantalian-dev@users.noreply.github.com>
Co-authored-by: The412Banner <the412banner@users.noreply.github.com>
Co-authored-by: The412Banner <205237651+The412Banner@users.noreply.github.com>
Co-authored-by: FX1922 <120828496+FX192@users.noreply.github.com>
Co-authored-by: Muaz Kadan <32595066+muazkadan@users.noreply.github.com>
Co-authored-by: kingokksa <47888451+kingokksa@users.noreply.github.com>
Co-authored-by: Jamie Schenker <jam1esch3nk3r@gmail.com>
Co-authored-by: Jagger15 <jagger2333@live.com>
This commit is contained in:
221 files changed
+24369 -491

No files matched your search

@@ -29,6 +29,7 @@ class ControllerActions(
val onQamButton: (Boolean) -> Unit,
val onKeyboardButton: (Boolean) -> Unit,
val onSelectSteam: (Boolean) -> Unit,
val onJoyConVr: (Boolean) -> Unit,
val onEditLayout: () -> Unit,
val onResetLayout: () -> Unit,
val onMapping: () -> Unit,
@@ -72,6 +73,7 @@ fun ColumnScope.ControllerRows(host: MenuHost, oscMode: String, c: ControllerPre
ToggleRow(host, "controller-qam", stringResource(R.string.ctrl_qam_button), null, c.qamButton, onChange = a.onQamButton)
ToggleRow(host, "controller-keyboard", stringResource(R.string.ctrl_keyboard_button), null, c.keyboardButton, onChange = a.onKeyboardButton)
ToggleRow(host, "controller-select-steam", stringResource(R.string.ctrl_select_steam), stringResource(R.string.ctrl_select_steam_hint), c.selectSteam, onChange = a.onSelectSteam)
ToggleRow(host, "controller-joycon-vr", stringResource(R.string.ctrl_joycon_vr), stringResource(R.string.ctrl_joycon_vr_hint), c.joyConVr, onChange = a.onJoyConVr)
SettingsRow(stringResource(R.string.ctrl_layout), if (c.customLayout) stringResource(R.string.ctrl_layout_custom) else stringResource(R.string.ctrl_layout_default)) {
Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
SecondaryButton(stringResource(R.string.ctrl_edit)) { a.onEditLayout() }
@@ -0,0 +1,484 @@
package com.droiddeck.launcher.ui
import android.view.KeyEvent
import androidx.activity.compose.BackHandler
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInHorizontally
import androidx.compose.animation.slideOutHorizontally
import androidx.compose.animation.togetherWith
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.focusGroup
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraintsScope
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.compose.runtime.withFrameNanos
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusDirection
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.graphics.lerp
import androidx.compose.ui.input.InputMode
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
import androidx.compose.ui.input.nestedscroll.NestedScrollSource
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.boundsInParent
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalInputModeManager
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.unit.IntOffset
import androidx.compose.ui.unit.Velocity
import androidx.compose.ui.unit.dp
import androidx.compose.ui.util.lerp
import androidx.compose.ui.zIndex
import com.droiddeck.launcher.R
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.math.roundToInt
private const val DROP_PIECES = 12
internal class DropSheetState(private val scope: CoroutineScope) {
var open by mutableStateOf(false)
var shown by mutableStateOf(false)
var lipBack by mutableStateOf(false)
var tab by mutableStateOf(0)
var travel by mutableStateOf(1)
var settledByDrag = false
var engaged = false
private set
val pull = Animatable(0f)
val lift = Animatable(0f)
val ride = Animatable(0f)
val sink = Animatable(0f)
val hot = Animatable(1f)
val lipShow = Animatable(0f)
val lipGone = Animatable(0f)
val pieces = List(DROP_PIECES) { Animatable(0f) }
var travelPx = 1f
private var from = 0f
var progress = 0f
private set
private var dragJob: Job? = null
fun cancelDrag() {
dragJob?.cancel()
dragJob = null
}
fun reset() {
cancelDrag()
engaged = false
settledByDrag = false
open = false
shown = false
lipBack = false
scope.launch {
listOf(pull, lift, ride, sink, lipGone).forEach { it.snapTo(0f) }
pieces.forEach { it.snapTo(0f) }
hot.snapTo(1f)
}
}
fun beginDrag() {
cancelDrag()
settledByDrag = false
engaged = true
from = if (open) 1f else 0f
progress = from
if (!open) shown = true
}
fun drag(dy: Float) = follow((progress + dy / travelPx).coerceIn(0f, 1.04f))
fun follow(p: Float) {
progress = p
scope.launch {
lift.snapTo(p); ride.snapTo(p); sink.snapTo(p.coerceIn(0f, 1f)); hot.snapTo(0f)
lipGone.snapTo(1f)
pieces.forEach { it.snapTo(p.coerceIn(0f, 1f)) }
}
}
fun settle(v: Float, flick: Float) {
engaged = false
val opens = when {
v > flick -> true
v < -flick -> false
from > 0.5f -> progress > 0.7f
else -> progress > 0.3f
}
settledByDrag = true
cancelDrag()
dragJob = scope.launch {
val to = if (opens) 1f else 0f
coroutineScope {
launch { lift.animateTo(to, Motion.sp(if (opens) 0.7f else 1f, 380f)) }
launch { ride.animateTo(to, Motion.sp(if (opens) 0.7f else 0.55f, if (opens) 380f else 300f)) }
launch { sink.animateTo(to, Motion.tw(220)) }
pieces.forEachIndexed { i, piece -> launch { if (opens) delay(Motion.ms(i * 35).toLong()); piece.animateTo(to, Motion.tw(if (opens) 200 else 90)) } }
}
if (!opens) { shown = false; lipGone.snapTo(0f); hot.snapTo(1f); lipBack = false }
}
if (open != opens) open = opens else settledByDrag = false
}
}
@Composable
internal fun rememberDropSheetState(): DropSheetState {
val scope = rememberCoroutineScope()
return remember { DropSheetState(scope) }
}
@OptIn(ExperimentalComposeUiApi::class, androidx.compose.animation.ExperimentalAnimationApi::class)
@Composable
internal fun BoxWithConstraintsScope.DropSheet(
state: DropSheetState,
tabs: List<Pair<String, String>>,
covered: () -> Float = { 0f },
button: @Composable (enabled: Boolean) -> Unit,
rows: @Composable (tab: String) -> Unit,
) {
val density = LocalDensity.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val inputMode = LocalInputModeManager.current
val narrow = LocalNarrowPane.current
val chipFocus = remember(tabs.size) { List(tabs.size) { FocusRequester() } }
val buttonFocus = remember { FocusRequester() }
val leftForButton = remember { booleanArrayOf(false) }
var rest by remember { mutableStateOf<Rect?>(null) }
val openState = rememberUpdatedState(state.open)
if (state.tab > tabs.lastIndex) state.tab = 0
fun focusButton() { if (inputMode.inputMode == InputMode.Keyboard) runCatching { buttonFocus.requestFocus() } }
fun close() {
if (!state.open) return
state.open = false
focusButton()
}
val lifecycle = androidx.compose.ui.platform.LocalLifecycleOwner.current.lifecycle
DisposableEffect(lifecycle) {
val obs = androidx.lifecycle.LifecycleEventObserver { _, e ->
if (e == androidx.lifecycle.Lifecycle.Event.ON_STOP && (state.open || state.shown || state.engaged)) state.reset()
}
lifecycle.addObserver(obs)
onDispose { lifecycle.removeObserver(obs) }
}
LaunchedEffect(state.open) {
if (state.settledByDrag) {
state.settledByDrag = false
if (state.open) {
if (inputMode.inputMode == InputMode.Keyboard) { withFrameNanos { }; runCatching { chipFocus[state.tab].requestFocus() } }
} else focusButton()
return@LaunchedEffect
}
if (state.engaged) return@LaunchedEffect
state.cancelDrag()
if (state.open) {
state.lipBack = false
state.shown = true
coroutineScope {
launch { state.pull.animateTo(24f, Motion.sp(0.7f, 380f)) }
launch { state.sink.animateTo(1f, Motion.tw(260)) }
launch {
delay(Motion.ms(120).toLong())
launch { state.lipGone.animateTo(1f, Motion.tw(140)) }
launch { state.pull.animateTo(0f, Motion.sp(1f, 500f)) }
launch { state.lift.animateTo(1f, Motion.sp(0.7f, 380f)) }
launch { state.ride.animateTo(1f, Motion.sp(0.7f, 380f)) }
launch { state.hot.snapTo(1f); delay(Motion.ms(100).toLong()); state.hot.animateTo(0f, Motion.tw(200)) }
}
state.pieces.forEachIndexed { i, p -> launch { delay(Motion.ms(120 + 260 + i * 55).toLong()); p.animateTo(1f, Motion.tw(220)) } }
if (inputMode.inputMode == InputMode.Keyboard) launch {
delay(Motion.ms(300).toLong())
withFrameNanos { }
runCatching { chipFocus[state.tab].requestFocus() }
}
}
} else if (state.shown) {
coroutineScope {
state.pieces.forEach { launch { it.animateTo(0f, Motion.tw(90)) } }
launch { delay(Motion.ms(60).toLong()); state.lift.animateTo(0f, Motion.sp(1f, 380f)) }
launch { delay(Motion.ms(100).toLong()); state.ride.animateTo(0f, Motion.sp(0.55f, 300f)) }
launch { state.sink.animateTo(0f, Motion.tw(300)) }
launch { delay(Motion.ms(420).toLong()); state.lipGone.snapTo(0f); state.lipBack = true }
}
state.shown = false
state.lipBack = false
state.lipGone.snapTo(0f)
state.hot.snapTo(1f)
} else {
listOf(state.pull, state.sink, state.lift, state.ride, state.lipGone).forEach { it.snapTo(0f) }
state.pieces.forEach { it.snapTo(0f) }
state.hot.snapTo(1f)
}
}
BackHandler(enabled = state.open) { close() }
if (state.ride.isRunning || (state.shown && !state.open)) VeilRing()
val lipWanted = !state.open && (!state.shown || state.lipBack) && covered() < 0.5f
LaunchedEffect(lipWanted) {
if (lipWanted) {
if (!state.lipBack) delay(Motion.ms(160).toLong())
state.lipShow.animateTo(1f, Motion.tw(220))
} else {
delay(Motion.ms(140).toLong())
state.lipShow.animateTo(0f, Motion.tw(220))
}
}
val flick = with(density) { 600.dp.toPx() }
val rowsPush = remember(state) {
object : NestedScrollConnection {
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
if (!state.engaged || available.y <= 0f) return Offset.Zero
val before = state.progress
state.follow((before + available.y / state.travelPx).coerceAtMost(1f))
return Offset(0f, (state.progress - before) * state.travelPx)
}
override fun onPostScroll(consumed: Offset, available: Offset, source: NestedScrollSource): Offset {
if (available.y >= 0f || source != NestedScrollSource.Drag || !openState.value) return Offset.Zero
if (!state.engaged) state.beginDrag()
state.follow((state.progress + available.y / state.travelPx).coerceIn(0f, 1f))
return available
}
override suspend fun onPreFling(available: Velocity): Velocity {
if (!state.engaged) return Velocity.Zero
state.settle(available.y, flick)
return available
}
}
}
val w = constraints.maxWidth.toFloat()
val h = constraints.maxHeight.toFloat()
val inset = with(density) { 12.dp.toPx() }
val edge = with(density) { 3.dp.toPx() }
val buttonH = rest?.height ?: with(density) { 56.dp.toPx() }
val openBottom = h - sheetTop(h, buttonH, with(density) { 16.dp.toPx() }, edge)
val lower = rest?.let { (openBottom - edge - buttonH / 2f) - it.top } ?: 0f
state.travelPx = openBottom.coerceAtLeast(1f)
if (state.shown || state.open) Box(
Modifier.fillMaxSize()
.graphicsLayer { alpha = state.sink.value }.background(Color.Black.copy(alpha = 0.42f))
.focusProperties { canFocus = false }
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null, enabled = state.open) { close() },
)
if (state.shown) {
val bottom = lerp(0f, openBottom, state.lift.value)
val sheetLeft = inset
val sheetRight = w - inset
val corner = with(density) { 18.dp.toPx() }
val rim = with(density) { 1.4.dp.toPx() }
val path = remember { Path() }
val rimPath = remember { Path() }
Canvas(Modifier.fillMaxSize()) {
val t = -corner
rimPath.reset()
rimPath.moveTo(sheetLeft, t)
rimPath.lineTo(sheetLeft, bottom - corner)
rimPath.arcTo(Rect(sheetLeft, bottom - 2 * corner, sheetLeft + 2 * corner, bottom), 180f, -90f, false)
rimPath.lineTo(sheetRight - corner, bottom)
rimPath.arcTo(Rect(sheetRight - 2 * corner, bottom - 2 * corner, sheetRight, bottom), 90f, -90f, false)
rimPath.lineTo(sheetRight, t)
path.reset()
path.addPath(rimPath)
path.close()
drawPath(path, lerp(colors.surface, pal.signal, 0.22f * state.hot.value))
drawPath(rimPath, pal.signal.copy(alpha = lerp(0.55f, 0.9f, state.hot.value)), style = Stroke(rim))
}
val pill = rest?.translate(0f, lower)
val sheetW = sheetRight - sheetLeft
val chipsH = with(density) { 44.dp.toPx() }
val closeW = with(density) { 64.dp.toPx() }
val chipsBottom = with(density) {
if (narrow && pill != null) pill.top - 10.dp.toPx() else openBottom - 14.dp.toPx()
}
val chipsTop = chipsBottom - chipsH
val chipsLeft = with(density) {
if (narrow || pill == null) 16.dp.toPx() else pill.right - sheetLeft + 20.dp.toPx()
}
val chipsRight = sheetW - closeW
val rowsBottom = chipsTop - with(density) { 8.dp.toPx() }
Box(
Modifier
.offset { IntOffset(sheetLeft.roundToInt(), (bottom - openBottom).roundToInt()) }
.size(with(density) { sheetW.toDp() }, with(density) { openBottom.toDp() })
.pointerInput(Unit) { detectTapGestures { } }
.controllerBack { close() }
.bumpers(
onPrevious = { if (state.tab > 0) { state.travel = -1; state.tab--; runCatching { chipFocus[state.tab].requestFocus() } } },
onNext = { if (state.tab < tabs.lastIndex) { state.travel = 1; state.tab++; runCatching { chipFocus[state.tab].requestFocus() } } },
)
.focusProperties {
exit = { dir ->
if (!openState.value) FocusRequester.Default
else if (dir == FocusDirection.Left) { leftForButton[0] = true; buttonFocus }
else FocusRequester.Cancel
}
}
.focusGroup(),
) {
Box(
Modifier
.nestedScroll(rowsPush)
.fillMaxWidth()
.height(with(density) { rowsBottom.coerceAtLeast(0f).toDp() }),
) {
AnimatedContent(
targetState = state.tab.coerceIn(0, tabs.lastIndex.coerceAtLeast(0)),
transitionSpec = {
val d = state.travel
val shift = with(density) { 24.dp.roundToPx() }
(slideInHorizontally(Motion.tw(240)) { shift * d } + fadeIn(Motion.tw(240)))
.togetherWith(slideOutHorizontally(Motion.tw(240)) { -shift * d } + fadeOut(Motion.tw(240)))
},
label = "dropTab",
) { t ->
val leaving = transition.targetState == androidx.compose.animation.EnterExitState.PostExit
val leavingNow = rememberUpdatedState(leaving)
CompositionLocalProvider(LocalSheetBeat provides remember { SheetBeat(state.pieces) }) {
Column(
Modifier.fillMaxSize()
.focusProperties { enter = { if (leavingNow.value) FocusRequester.Cancel else FocusRequester.Default } }
.focusGroup()
.verticalScroll(rememberScrollState())
.padding(start = 16.dp, end = 16.dp, top = 8.dp, bottom = 8.dp),
) { tabs.getOrNull(t)?.let { rows(it.first) } }
}
}
}
Box(
Modifier
.offset { IntOffset(chipsLeft.roundToInt(), chipsTop.roundToInt()) }
.zIndex(1f)
.width(with(density) { (chipsRight - chipsLeft).coerceAtLeast(0f).toDp() })
.graphicsLayer { val v = state.pieces[0].value; alpha = v; translationY = (1f - v) * -6.dp.toPx() }
.onPreviewKeyEvent { e ->
val k = e.nativeKeyEvent
if (k.keyCode == KeyEvent.KEYCODE_DPAD_DOWN) { if (k.action == KeyEvent.ACTION_DOWN) close(); true } else false
},
) {
SheetChips(tabs.map { it.second }, state.tab, chipFocus, width = LocalSheetChipWidth.current) { i -> state.travel = if (i > state.tab) 1 else -1; state.tab = i }
}
val closeSource = remember { MutableInteractionSource() }
val closeHot = rememberHot(closeSource)
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.offset { IntOffset((sheetW - 52.dp.toPx()).roundToInt(), chipsTop.roundToInt()) }
.zIndex(1f).size(44.dp).testTag("drop-close")
.clip(CircleShape).glideBorder(closeHot, CircleShape, pal.signal)
.hoverable(closeSource)
.clickable(interactionSource = closeSource, indication = LocalIndication.current, enabled = state.open, role = Role.Button) { close() }
.controllerConfirm(enabled = state.open) { close() },
) { Icon(Icons.Filled.Close, stringResource(R.string.common_close), tint = colors.onSurfaceVariant, modifier = Modifier.size(20.dp)) }
}
}
val enabled = covered() < 0.5f
val sideInset = if (narrow) 20.dp else 44.dp
val play = LocalPlayRect.current
Box(
Modifier
.offset { IntOffset(play?.left?.roundToInt() ?: sideInset.roundToPx(), sideInset.roundToPx()) }
.then(if (play != null) Modifier.width(with(density) { play.width.toDp() }) else Modifier)
.onGloballyPositioned { rest = it.boundsInParent() }
.graphicsLayer { translationY = lower * state.ride.value; alpha = 1f - covered() }
.zIndex(2f)
.focusRequester(buttonFocus)
.focusProperties { canFocus = enabled }
.onFocusChanged {
if (it.hasFocus && leftForButton[0]) { leftForButton[0] = false; if (openState.value) close() }
}
.onPreviewKeyEvent { e ->
val k = e.nativeKeyEvent
if (k.keyCode != KeyEvent.KEYCODE_DPAD_UP && !(state.open && k.keyCode == KeyEvent.KEYCODE_DPAD_RIGHT)) false
else {
if (k.action == KeyEvent.ACTION_DOWN && k.repeatCount == 0) {
if (state.open) runCatching { chipFocus[state.tab].requestFocus() } else if (enabled) state.open = true
}
true
}
},
) { button(enabled) }
val r0 = rest
if (r0 != null && (state.lipShow.value > 0.01f || state.pull.value > 0.5f)) {
var handleSize by remember { mutableStateOf(androidx.compose.ui.unit.IntSize.Zero) }
val lipH = 32.dp + state.pull.value.dp
val drop = { if (!state.open && enabled) state.open = true }
val settingsLabel = stringResource(R.string.drawer_page_settings)
Box(
contentAlignment = Alignment.BottomCenter,
modifier = Modifier
.offset { IntOffset((r0.center.x - handleSize.width / 2f).roundToInt(), (r0.top + lower * state.ride.value - handleSize.height + (1f - state.lipShow.value) * 8.dp.toPx()).roundToInt()) }
.onSizeChanged { handleSize = it }
.graphicsLayer { alpha = state.lipShow.value * (1f - state.lipGone.value) * (1f - covered()) }
.zIndex(2f)
.heightIn(min = 44.dp).testTag("drop-open")
.semantics { contentDescription = settingsLabel }
.focusProperties { canFocus = false }
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null, role = Role.Button, onClick = drop),
) {
Handle(lipH, above = true)
}
}
}
@@ -151,6 +151,7 @@ class FrontEndState(
class FrontEndActions(
val onPlay: () -> Unit,
val onPlaySteamVr: () -> Unit = {},
val onPlayDesktopUi: () -> Unit,
val onSteamUrl: (String) -> Unit = {},
val onSteamGame: (Library.SteamGame) -> Unit,
@@ -206,7 +206,7 @@ internal fun SetupPanel(
),
) {
PageHeader(stringResource(R.string.setup_title)) {
Box(Modifier.weight(1f)) { SheetChips(tabs, tab, chipFocus, pick) }
Box(Modifier.weight(1f)) { SheetChips(tabs, tab, chipFocus, onPick = pick) }
}
Column(modifier = Modifier.weight(1f).fillMaxWidth().verticalScroll(rememberScrollState()).padding(bottom = 24.dp)) {
when (tab) {
@@ -22,6 +22,7 @@ import androidx.compose.foundation.interaction.collectIsHoveredAsState
import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
@@ -38,6 +39,7 @@ import androidx.compose.material.icons.filled.ChevronLeft
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.LocalTextStyle
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
@@ -57,6 +59,8 @@ import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.rememberTextMeasurer
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
@@ -148,6 +152,7 @@ internal fun PrimaryButton(
modifier: Modifier = Modifier,
large: Boolean = false,
icon: ImageVector? = null,
fill: Boolean = false,
onClick: () -> Unit,
) {
val colors = MaterialTheme.colorScheme
@@ -165,7 +170,8 @@ internal fun PrimaryButton(
val lift by animateFloatAsState(if (hot) 14f else 6f, Motion.tw(300), label = "btnLift")
val placed = remember { arrayOfNulls<androidx.compose.ui.layout.LayoutCoordinates>(1) }
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = if (fill) Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally) else Arrangement.spacedBy(8.dp),
modifier = modifier.then(track)
.onGloballyPositioned { placed[0] = it }
.heightIn(min = if (compact) 44.dp else 48.dp)
@@ -181,18 +187,34 @@ internal fun PrimaryButton(
onClick()
}
.padding(
start = if (large) 20.dp else if (compact) 10.dp else if (icon != null) 14.dp else 18.dp,
end = if (large) 26.dp else if (compact) 10.dp else 18.dp,
start = if (fill) 12.dp else if (large) 20.dp else if (compact) 10.dp else if (icon != null) 14.dp else 18.dp,
end = if (fill) 12.dp else if (large) 26.dp else if (compact) 10.dp else 18.dp,
top = if (large) 16.dp else if (compact) 7.dp else 11.dp,
bottom = if (large) 16.dp else if (compact) 7.dp else 11.dp,
),
) {
val fg = if (enabled) colors.onPrimary else colors.onSurfaceVariant
if (icon != null) Icon(icon, contentDescription = null, tint = fg, modifier = Modifier.size(if (large) 20.dp else 17.dp))
Text(
text, fontSize = if (large) 17.sp else if (compact) 12.sp else 15.sp,
fontWeight = if (large) FontWeight.Bold else FontWeight.SemiBold, letterSpacing = 0.5.sp, color = fg, maxLines = 1,
)
val style = LocalTextStyle.current.merge(TextStyle(
fontSize = if (large) 17.sp else if (compact) 12.sp else 15.sp,
fontWeight = if (large) FontWeight.Bold else FontWeight.SemiBold, letterSpacing = 0.5.sp, color = fg,
))
if (fill) FittedLabel(text, style, Modifier.weight(1f, fill = false))
else Text(text, style = style, maxLines = 1)
}
}
@Composable
private fun FittedLabel(text: String, style: TextStyle, modifier: Modifier = Modifier) {
BoxWithConstraints(modifier) {
val measurer = rememberTextMeasurer()
val max = constraints.maxWidth
val size = remember(text, style, max) {
var size = style.fontSize
while (size.value > 10f && measurer.measure(text, style.copy(fontSize = size), maxLines = 1, softWrap = false).size.width > max) size = (size.value - 0.5f).sp
size
}
Text(text, style = style.copy(fontSize = size), maxLines = 1, softWrap = false)
}
}
@@ -0,0 +1,64 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.*
import androidx.compose.ui.res.stringResource
import com.droiddeck.launcher.R
import com.droiddeck.launcher.glasses.CalibrationPhase
import com.droiddeck.launcher.glasses.GlassesCalibrationState
@Composable
internal fun GlassesCalibrationControls(
state: GlassesCalibrationState,
onStart: () -> Unit,
onCancel: () -> Unit,
onReset: () -> Unit,
onDone: () -> Unit,
) {
var shown by remember { mutableStateOf(false) }
var reset by remember { mutableStateOf(false) }
val cancel by rememberUpdatedState(onCancel)
DisposableEffect(Unit) { onDispose { cancel() } }
ActionRow(stringResource(R.string.glasses_calibration),
stringResource(if (state.saved) R.string.glasses_calibration_saved_hint else R.string.glasses_calibration_hint),
stringResource(R.string.glasses_calibration_open), { onCancel(); shown = true })
if (state.saved && !state.running) ActionRow(stringResource(R.string.glasses_calibration_reset), null,
stringResource(R.string.glasses_calibration_reset_button), { reset = true })
if (reset) AlertDialog(
onDismissRequest = { reset = false },
title = { Text(stringResource(R.string.glasses_calibration_reset)) },
text = { Text(stringResource(R.string.glasses_calibration_reset_hint)) },
confirmButton = { TextButton(onClick = { onReset(); reset = false }) { Text(stringResource(R.string.glasses_calibration_reset_button)) } },
dismissButton = { TextButton(onClick = { reset = false }) { Text(stringResource(R.string.common_cancel)) } },
)
if (shown) AlertDialog(
onDismissRequest = { onCancel(); shown = false },
title = { Text(stringResource(R.string.glasses_calibration)) },
text = { Column {
Text(stringResource(when (state.phase) {
CalibrationPhase.IDLE -> R.string.glasses_calibration_instructions
CalibrationPhase.SETTLING -> R.string.glasses_calibration_settling
CalibrationPhase.COLLECTING -> R.string.glasses_calibration_collecting
CalibrationPhase.MOVING -> R.string.glasses_calibration_moving
CalibrationPhase.TURN_OVER -> R.string.glasses_calibration_turn_over
CalibrationPhase.SAVED -> R.string.glasses_calibration_complete
CalibrationPhase.FAILED -> R.string.glasses_calibration_failed
}))
if (state.running) {
LinearProgressIndicator(progress = { state.progress / 100f })
Text("${state.progress}%")
}
} },
confirmButton = {
if (!state.running) TextButton(onClick = {
if (state.phase == CalibrationPhase.SAVED) { onDone(); onCancel(); shown = false }
else onStart()
}) { Text(stringResource(if (state.phase == CalibrationPhase.SAVED) R.string.glasses_calibration_done else R.string.glasses_calibration_start)) }
},
dismissButton = { TextButton(onClick = { onCancel(); shown = false }) { Text(stringResource(R.string.common_cancel)) } },
)
}
@@ -0,0 +1,268 @@
package com.droiddeck.launcher.ui
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.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.displayCutout
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.foundation.shape.CircleShape
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.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.sp
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.compose.runtime.collectAsState
import com.droiddeck.launcher.R
import com.droiddeck.launcher.glasses.Glasses
import com.droiddeck.launcher.glasses.GlassesRendering
import com.droiddeck.launcher.glasses.GlassesSettings
import com.droiddeck.launcher.glasses.GlassesState
import com.droiddeck.launcher.handtracking.HandTracking
import java.util.Locale
internal val GlassesIcon: ImageVector by lazy {
ImageVector.Builder("Glasses", 24.dp, 24.dp, 24f, 24f).apply {
path(fill = null, stroke = SolidColor(Color.Black), strokeLineWidth = 1.8f, strokeLineCap = StrokeCap.Round, strokeLineJoin = StrokeJoin.Round) {
moveTo(2.5f, 10f); lineTo(21.5f, 10f)
moveTo(3.2f, 10f); lineTo(3.8f, 15.2f); quadTo(4f, 17f, 6f, 17f); lineTo(8.6f, 17f); quadTo(10.2f, 17f, 10.6f, 15.4f); lineTo(11.2f, 12.6f)
quadTo(12f, 11.6f, 12.8f, 12.6f); lineTo(13.4f, 15.4f); quadTo(13.8f, 17f, 15.4f, 17f); lineTo(18f, 17f); quadTo(20f, 17f, 20.2f, 15.2f); lineTo(20.8f, 10f)
moveTo(2.5f, 10f); lineTo(1.8f, 7.6f)
moveTo(21.5f, 10f); lineTo(22.2f, 7.6f)
}
}.build()
}
@Composable
internal fun rememberGlasses(): Pair<GlassesState, GlassesSettings> {
val g by Glasses.state.collectAsState()
val s by Glasses.settings.collectAsState()
return g to s
}
internal object GlassesTab {
const val DISPLAY = "display"
const val HARDWARE = "hardware"
const val TRACKING = "tracking"
}
@Composable
internal fun glassesTabs(g: GlassesState): List<Pair<String, String>> = buildList {
add(GlassesTab.DISPLAY to stringResource(R.string.glasses_display))
if (g.canControl) {
if (g.hardwareControls) add(GlassesTab.HARDWARE to stringResource(R.string.glasses_hardware))
add(GlassesTab.TRACKING to stringResource(R.string.glasses_tracking))
}
}
@Composable
internal fun GlassesGroups(
host: MenuHost,
g: GlassesState,
s: GlassesSettings,
track: (String) -> Modifier = { Modifier },
onRecenter: (() -> Unit)? = null,
inSession: Boolean = true,
outputActive: Boolean = inSession,
steamVrRunning: Boolean = false,
tab: String? = null,
steamVr: @Composable () -> Unit = {},
) {
val display = tab == null || tab == GlassesTab.DISPLAY
val picture = GlassesRendering.picture(s, g.sbs, steamVrRunning)
val usesGlasses = GlassesRendering.usesGlasses(g, outputActive, steamVrRunning)
val virtualScreen = usesGlasses && picture == GlassesRendering.Picture.VIRTUAL_SCREEN
val directView = usesGlasses && picture == GlassesRendering.Picture.STEREO
if (display) SettingsGroup(g.model) {
if (g.experimental) SettingsRow(stringResource(R.string.glasses_control), stringResource(R.string.glasses_xreal_experimental)) {}
val status = if (g.hasDisplay) stringResource(R.string.glasses_status, g.width, g.height, kotlin.math.round(g.hz).toInt(),
stringResource(if (g.sbs) R.string.glasses_mode_3d else R.string.glasses_mode_2d)) else null
when {
g.noSignal -> SettingsRow(stringResource(R.string.glasses_output), stringResource(R.string.glasses_no_signal)) {}
!g.controllable -> {
if (status != null) SettingsRow(stringResource(R.string.glasses_output), status) {}
SettingsRow(stringResource(R.string.glasses_control), g.controlError ?: stringResource(R.string.glasses_no_control)) {}
}
g.permission == Glasses.Permission.ASKING ->
SettingsRow(stringResource(R.string.glasses_control), stringResource(R.string.glasses_asking)) {}
!g.connected -> ActionRow(stringResource(R.string.glasses_control),
g.controlError ?: stringResource(if (g.permission == Glasses.Permission.DENIED) R.string.glasses_denied else R.string.glasses_allow_hint),
stringResource(R.string.glasses_allow), { Glasses.requestControl() })
status != null -> SettingsRow(stringResource(R.string.glasses_output), status) {}
}
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 (display && (g.canControl || g.hasDisplay)) SettingsGroup(stringResource(R.string.glasses_display)) {
if (g.canControl) {
if (!g.sbs) ChoiceRow(host, "glasses-hz", stringResource(R.string.glasses_refresh), null,
listOf(60, 90, 120).map { it to "$it Hz" }, s.refreshHz, chipModifier = track("glasses-hz")) { Glasses.setRefreshHz(it) }
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) })
} else {
if (inSession || g.sbs) ToggleRow(host, "glasses-3d", stringResource(R.string.glasses_3d), stringResource(R.string.glasses_3d_hint),
g.sbs, chipModifier = track("glasses-3d")) { Glasses.set3d(it) }
if (g.sbs) {
if (g.sbs90) ChoiceRow(host, "glasses-3d-hz", stringResource(R.string.glasses_3d_refresh), null,
listOf(60, 90).map { it to "$it Hz" }, s.sbsHz, chipModifier = track("glasses-3d-hz")) { Glasses.setSbsHz(it) }
else SettingsRow(stringResource(R.string.glasses_3d_refresh), "60 Hz") {}
}
}
}
ToggleRow(host, "glasses-auto3d", stringResource(R.string.glasses_auto3d), stringResource(R.string.glasses_auto3d_hint),
s.auto3d, chipModifier = track("glasses-auto3d")) { Glasses.setAuto3d(it) }
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),
GlassesSettings.PICTURE_SCREEN to stringResource(R.string.glasses_picture_screen),
GlassesSettings.PICTURE_SBS to stringResource(R.string.glasses_picture_sbs),
), s.picture3d, chipModifier = track("glasses-picture"), hintLines = 2) { Glasses.setPicture3d(it) }
when {
!inSession -> SettingsRow(stringResource(R.string.glasses_picture_screen), stringResource(R.string.glasses_screen_next_session)) {}
!usesGlasses -> SettingsRow(stringResource(R.string.glasses_picture_screen), stringResource(R.string.glasses_screen_no_output)) {}
picture == GlassesRendering.Picture.FLAT -> ActionRow(
stringResource(R.string.glasses_picture_screen), stringResource(R.string.glasses_screen_flat_hint),
stringResource(R.string.glasses_screen_use), { Glasses.setPicture3d(GlassesSettings.PICTURE_SCREEN) })
directView -> SettingsRow(stringResource(R.string.glasses_picture_screen),
stringResource(if (steamVrRunning) R.string.glasses_screen_direct_hint else R.string.glasses_screen_sbs_hint)) {}
}
if (virtualScreen || (!inSession && s.picture3d != GlassesSettings.PICTURE_SBS)) {
SliderRow(stringResource(R.string.glasses_screen_size), null, s.screenWidthDm, 5..60, step = 1,
format = { String.format(Locale.US, "%.1f m", it / 10f) }, modifier = track("glasses-width")) { Glasses.setScreenWidthDm(it) }
SliderRow(stringResource(R.string.glasses_screen_distance), null, s.screenDistanceDm, 5..100, step = 1,
format = { String.format(Locale.US, "%.1f m", it / 10f) }, modifier = track("glasses-distance")) { Glasses.setScreenDistanceDm(it) }
}
steamVr()
if ((directView && steamVrRunning) || !inSession) SliderRow(stringResource(R.string.glasses_vr_fov), stringResource(R.string.glasses_vr_fov_hint), s.vrFovDeg,
GlassesSettings.VR_FOV_MIN..GlassesSettings.VR_FOV_MAX, step = 1,
format = { "$it°" }, modifier = track("glasses-vr-fov")) { Glasses.setVrFovDeg(it) }
}
if ((tab == null || tab == GlassesTab.HARDWARE) && g.canControl && g.hardwareControls) SettingsGroup(stringResource(R.string.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,
modifier = track("glasses-volume")) { Glasses.setVolume(it) }
if (g.hasSunblock) ToggleRow(host, "glasses-sunblock", stringResource(R.string.glasses_sunblock), stringResource(R.string.glasses_sunblock_hint),
g.sunblock, chipModifier = track("glasses-sunblock")) { Glasses.setSunblock(it) }
}
if ((tab == null || tab == GlassesTab.TRACKING) && g.canControl) SettingsGroup(stringResource(R.string.glasses_tracking)) {
val trackingHint = when {
inSession && !usesGlasses -> R.string.glasses_screen_no_output
inSession && picture == GlassesRendering.Picture.FLAT -> R.string.glasses_tracking_flat_hint
inSession && directView && !steamVrRunning -> R.string.glasses_tracking_sbs_hint
else -> R.string.glasses_head_tracking_hint
}
ToggleRow(host, "glasses-tracking", stringResource(R.string.glasses_head_tracking), stringResource(trackingHint),
s.headTracking, chipModifier = track("glasses-tracking")) { Glasses.setHeadTracking(it) }
if (onRecenter != null && s.headTracking && (virtualScreen || (directView && steamVrRunning))) ActionRow(stringResource(R.string.glasses_recenter), null,
stringResource(R.string.cardboard_recenter_button), onRecenter)
val calibration by Glasses.calibration.collectAsState()
if (calibration.supported) GlassesCalibrationControls(calibration,
onStart = Glasses::startCalibration, onCancel = Glasses::cancelCalibration,
onReset = Glasses::resetCalibration, onDone = { onRecenter?.invoke() })
}
val context = androidx.compose.ui.platform.LocalContext.current
val hands by HandTracking.settings.collectAsState()
androidx.compose.runtime.LaunchedEffect(Unit) { HandTracking.load(context) }
if ((tab == null || tab == GlassesTab.TRACKING) && g.canControl && hands.usable) SettingsGroup(stringResource(R.string.hand_camera_group)) {
HandCameraRows(host, track, inSession)
}
}
private fun padButtonColors(tint: Int, opacity: Int, pressed: Boolean): Pair<Color, Color> {
val base = Color(tint)
val alpha = opacity.coerceIn(0, 100) / 100f
fun light(a: Int, f: Float) = Color(base.red + (1 - base.red) * f, base.green + (1 - base.green) * f, base.blue + (1 - base.blue) * f, a * alpha / 255f)
return Color(base.red * 0.12f, base.green * 0.12f, base.blue * 0.12f, 190 / 255f) to (if (pressed) light(230, 0.7f) else light(150, 0.25f))
}
@Composable
internal fun GlassesCornerButton(slot: Int, tint: Int, opacity: Int, onClick: () -> Unit) {
val density = androidx.compose.ui.platform.LocalDensity.current
androidx.compose.foundation.layout.BoxWithConstraints(
Modifier.fillMaxSize().windowInsetsPadding(WindowInsets.displayCutout),
) {
val x = if (slot < 0) maxWidth / 2 + 56.dp else 34.dp + 56.dp * slot
val bottom = if (slot < 0) 44.dp else 34.dp
val source = remember { MutableInteractionSource() }
val pressed by source.collectIsPressedAsState()
val (fill, line) = padButtonColors(tint, opacity, pressed)
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.offset { with(density) { IntOffset((x - 18.dp).roundToPx(), (maxHeight - bottom - 18.dp).roundToPx()) } }
.size(36.dp)
.clip(CircleShape)
.background(fill)
.border(1.5.dp, line, CircleShape)
.clickable(interactionSource = source, indication = null, role = Role.Button, onClick = onClick)
.testTag("glasses-button"),
) {
Icon(GlassesIcon, stringResource(R.string.glasses_open), tint = line, modifier = Modifier.size(22.dp))
}
}
}
@Composable
internal fun GlassesRecenterButton(tint: Int, opacity: Int, onClick: () -> Unit) {
val source = remember { MutableInteractionSource() }
val pressed by source.collectIsPressedAsState()
val (fill, line) = padButtonColors(tint, opacity, pressed)
val shape = RoundedCornerShape(50)
Box(
Modifier.fillMaxSize().windowInsetsPadding(WindowInsets.displayCutout).padding(top = 12.dp),
contentAlignment = Alignment.TopCenter,
) {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.height(36.dp)
.clip(shape)
.background(fill)
.border(1.5.dp, line, shape)
.clickable(interactionSource = source, indication = null, role = Role.Button, onClick = onClick)
.padding(horizontal = 18.dp)
.testTag("glasses-recenter"),
) {
Text(stringResource(R.string.glasses_recenter_button), color = line, fontSize = 14.sp)
}
}
}
@Composable
internal fun GlassesPlayingHint(model: String) {
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Icon(GlassesIcon, null, tint = Color.White.copy(alpha = 0.35f), modifier = Modifier.size(56.dp))
Spacer(Modifier.height(10.dp))
Text(stringResource(R.string.glasses_playing, model), color = Color.White.copy(alpha = 0.45f), fontSize = 15.sp)
}
}
}
@@ -0,0 +1,345 @@
package com.droiddeck.launcher.ui
import android.Manifest
import android.content.Intent
import android.net.Uri
import android.provider.Settings
import android.speech.tts.TextToSpeech
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.RadioButton
import androidx.compose.material3.RadioButtonDefaults
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
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
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import com.droiddeck.launcher.R
import com.droiddeck.launcher.handtracking.Advice
import com.droiddeck.launcher.handtracking.BodyPose
import com.droiddeck.launcher.handtracking.HandCamera
import com.droiddeck.launcher.handtracking.HandTracking
import com.droiddeck.launcher.handtracking.Landmark
import com.droiddeck.launcher.handtracking.TrackingCameras
import kotlinx.coroutines.delay
import java.util.Locale
@Composable
internal fun HandCameraHost(check: Boolean?, onAskPermission: () -> Unit, onPlay: () -> Unit, onClose: () -> Unit) {
if (!HandTracking.supported) return
val context = LocalContext.current
val (glasses, _) = rememberGlasses()
val settings by HandTracking.settings.collectAsState()
LaunchedEffect(Unit) { HandTracking.load(context) }
var prompted by rememberSaveable { mutableStateOf(false) }
if (!prompted && HandTracking.shouldAsk(settings, glasses.present && glasses.canControl)) {
HandCameraPrompt(settings.sides,
onAllow = { side ->
prompted = true
HandTracking.allow(context, side)
if (!HandTracking.permitted(context)) onAskPermission()
},
onNotNow = {
prompted = true
HandTracking.decline(context)
})
}
val requests by HandTracking.checkRequests.collectAsState()
var handled by remember { mutableStateOf(requests) }
val fromSettings = requests != handled
if (check != null || fromSettings) {
PlacementCheck(settings, play = check == true && !fromSettings,
onPlay = { handled = requests; onPlay() },
onClose = { handled = requests; onClose() })
}
}
@Composable
internal fun HandCameraPrompt(sides: Set<String>, onAllow: (String?) -> Unit, onNotNow: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val choose = sides.size > 1
var side by remember { mutableStateOf(TrackingCameras.REAR) }
AlertDialog(
onDismissRequest = onNotNow,
modifier = Modifier.testTag("hand-camera-prompt"),
title = { Text(stringResource(R.string.hand_camera_prompt_title)) },
text = {
Column(Modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(10.dp)) {
Text(stringResource(R.string.hand_camera_prompt_body), fontSize = 14.sp)
if (choose) listOf(
Triple(TrackingCameras.REAR, R.string.hand_camera_rear, R.string.hand_camera_rear_hint),
Triple(TrackingCameras.FRONT, R.string.hand_camera_front, R.string.hand_camera_front_hint),
).forEach { (id, label, hint) ->
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp))
.selectable(side == id, role = Role.RadioButton) { side = id }
.testTag("hand-camera-$id")
.padding(vertical = 4.dp),
) {
RadioButton(side == id, onClick = null,
colors = RadioButtonDefaults.colors(selectedColor = pal.signal, unselectedColor = colors.onSurfaceVariant))
Column(Modifier.padding(start = 10.dp)) {
Text(stringResource(label), fontSize = 15.sp, color = colors.onBackground)
Text(stringResource(hint), fontSize = 13.sp, color = colors.onSurfaceVariant)
}
}
}
}
},
confirmButton = {
TextButton(onClick = { onAllow(if (choose) side else null) }, modifier = Modifier.testTag("hand-camera-allow")) {
Text(stringResource(R.string.hand_camera_allow))
}
},
dismissButton = {
TextButton(onClick = onNotNow, modifier = Modifier.testTag("hand-camera-not-now")) { Text(stringResource(R.string.hand_camera_not_now)) }
},
)
}
@Composable
internal fun HandCameraRows(host: MenuHost, track: (String) -> Modifier, inSession: Boolean) {
if (!HandTracking.supported) return
val context = LocalContext.current
val lifecycle = LocalLifecycleOwner.current.lifecycle
DisposableEffect(lifecycle) {
HandTracking.load(context)
val watch = LifecycleEventObserver { _, event -> if (event == Lifecycle.Event.ON_RESUME) HandTracking.refreshPermission(context) }
lifecycle.addObserver(watch)
onDispose { lifecycle.removeObserver(watch) }
}
val s by HandTracking.settings.collectAsState()
if (!s.usable) return
var denied by remember { mutableStateOf(false) }
val ask = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
HandTracking.refreshPermission(context)
denied = !granted
}
ToggleRow(host, "hand-camera", stringResource(R.string.hand_camera_setting), stringResource(R.string.hand_camera_setting_hint),
s.enabled, chipModifier = track("hand-camera")) { on ->
HandTracking.setEnabled(context, on)
if (on && !s.permitted) ask.launch(Manifest.permission.CAMERA)
}
if (!s.enabled) return
if (s.sides.size > 1) ChoiceRow(host, "hand-camera-side", stringResource(R.string.hand_camera_choice), null,
listOf(TrackingCameras.REAR to stringResource(R.string.hand_camera_rear), TrackingCameras.FRONT to stringResource(R.string.hand_camera_front)),
s.side ?: TrackingCameras.REAR, chipModifier = track("hand-camera-side")) { HandTracking.setSide(context, it) }
when {
!s.permitted && denied -> ActionRow(stringResource(R.string.hand_camera_access), stringResource(R.string.hand_camera_access_denied),
stringResource(R.string.hand_camera_open_settings), {
context.startActivity(Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.fromParts("package", context.packageName, null))
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
})
!s.permitted -> ActionRow(stringResource(R.string.hand_camera_access), stringResource(R.string.hand_camera_access_hint),
stringResource(R.string.hand_camera_allow_button), { ask.launch(Manifest.permission.CAMERA) })
!inSession -> ActionRow(stringResource(R.string.hand_camera_placement), stringResource(R.string.hand_camera_placement_hint),
stringResource(R.string.hand_camera_check), { HandTracking.requestCheck() })
}
}
@Composable
private fun PlacementCheck(settings: HandTracking.Settings, play: Boolean, onPlay: () -> Unit, onClose: () -> Unit) {
val context = LocalContext.current
val side = settings.side
val camera = remember(side) { HandCamera(context, null, preview = true) }
DisposableEffect(camera) {
camera.start(side)
onDispose { camera.stop() }
}
val view by camera.view.collectAsState()
val failed by camera.failed.collectAsState()
val front = view?.front ?: (TrackingCameras.pick(HandTracking.cameras(context), side)?.front == true)
val advice = when {
failed -> null
else -> view?.advice ?: Advice.STARTING
}
val adviceText = stringResource(advice?.let(::adviceLabel) ?: R.string.hand_camera_failed)
val start by rememberUpdatedState(onPlay)
if (play) LaunchedEffect(advice == Advice.GOOD) {
if (advice == Advice.GOOD) {
delay(GOOD_HOLD_MS)
start()
}
}
if (!front) SpokenAdvice(advice, adviceText)
Dialog(onDismissRequest = onClose, properties = DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false)) {
PlacementCheckContent(view, front, advice, adviceText, play, switchable = settings.sides.size > 1,
onSwitch = { HandTracking.setSide(context, if (front) TrackingCameras.REAR else TrackingCameras.FRONT) },
onPlay = onPlay, onClose = onClose)
}
}
@Composable
internal fun PlacementCheckContent(
view: HandCamera.View?,
front: Boolean,
advice: Advice?,
adviceText: String,
play: Boolean,
switchable: Boolean,
onSwitch: () -> Unit,
onPlay: () -> Unit,
onClose: () -> Unit,
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Row(
horizontalArrangement = Arrangement.spacedBy(24.dp),
modifier = Modifier.fillMaxSize().background(pal.background).padding(24.dp).testTag("hand-camera-check"),
) {
Box(Modifier.weight(1.3f).fillMaxHeight(), contentAlignment = Alignment.Center) { CameraPreview(view) }
Column(Modifier.weight(1f).fillMaxHeight().verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(14.dp)) {
Text(stringResource(R.string.hand_camera_check_title), fontSize = 22.sp, fontWeight = FontWeight.Bold, color = colors.onBackground)
Text(stringResource(if (front) R.string.hand_camera_how_front else R.string.hand_camera_how_rear), fontSize = 15.sp, color = colors.onSurfaceVariant)
Text(adviceText, fontSize = 19.sp, fontWeight = FontWeight.SemiBold,
color = if (advice == Advice.GOOD) pal.good else colors.onBackground, modifier = Modifier.testTag("hand-camera-advice"))
Spacer(Modifier.heightIn(min = 8.dp))
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
if (switchable) SecondaryButton(stringResource(R.string.hand_camera_switch), compact = true, onClick = onSwitch)
if (play) {
SecondaryButton(stringResource(R.string.hand_camera_skip), compact = true, modifier = Modifier.testTag("hand-camera-skip"), onClick = onPlay)
SecondaryButton(stringResource(R.string.common_cancel), compact = true, onClick = onClose)
} else {
SecondaryButton(stringResource(R.string.hand_camera_done), compact = true, modifier = Modifier.testTag("hand-camera-done"), onClick = onClose)
}
}
}
}
}
@Composable
private fun CameraPreview(view: HandCamera.View?) {
val pal = LocalPalette.current
val shape = RoundedCornerShape(16.dp)
if (view == null) {
Box(Modifier.fillMaxWidth().aspectRatio(4f / 3f).clip(shape).background(pal.surface), contentAlignment = Alignment.Center) {
CircularProgressIndicator(color = pal.signal, modifier = Modifier.size(36.dp))
}
return
}
val image = remember(view) { view.image.asImageBitmap() }
Box(Modifier.aspectRatio(view.image.width.toFloat() / view.image.height).clip(shape)) {
Image(image, null, contentScale = ContentScale.FillBounds,
modifier = Modifier.fillMaxSize().graphicsLayer { if (view.front) scaleX = -1f })
Canvas(Modifier.fillMaxSize()) { drawSkeleton(view.landmarks, view.front, pal.signal, pal.good) }
}
}
private fun DrawScope.drawSkeleton(marks: List<Landmark>?, mirrored: Boolean, line: Color, hand: Color) {
if (marks == null || marks.size <= BodyPose.RIGHT_HIP) return
fun at(i: Int) = Offset((if (mirrored) 1f - marks[i].x else marks[i].x) * size.width, marks[i].y * size.height)
fun seen(i: Int) = marks[i].visibility >= BodyPose.MIN_VISIBILITY
val width = size.minDimension / 120f
for ((a, b) in BONES) if (seen(a) && seen(b)) drawLine(line, at(a), at(b), strokeWidth = width, cap = StrokeCap.Round)
for (i in JOINTS) if (seen(i)) drawCircle(line, width * 1.2f, at(i))
for (wrist in listOf(BodyPose.LEFT_WRIST, BodyPose.RIGHT_WRIST)) {
if (!seen(wrist)) continue
val grip = (at(wrist) + at(wrist + 2) + at(wrist + 4)) / 3f
drawCircle(hand.copy(alpha = 0.35f), width * 5f, grip)
drawCircle(hand, width * 2.2f, grip)
}
}
@Composable
private fun SpokenAdvice(advice: Advice?, text: String) {
val context = LocalContext.current
var ready by remember { mutableStateOf(false) }
val speech = remember {
var engine: TextToSpeech? = null
engine = TextToSpeech(context.applicationContext) { status ->
if (status == TextToSpeech.SUCCESS) {
engine?.language = Locale.getDefault()
ready = true
}
}
engine
}
DisposableEffect(speech) { onDispose { speech.shutdown() } }
LaunchedEffect(advice, ready) {
if (!ready || advice == null || advice == Advice.STARTING) return@LaunchedEffect
delay(SPEAK_AFTER_MS)
while (true) {
speech.speak(text, TextToSpeech.QUEUE_FLUSH, null, "hand-camera")
if (advice == Advice.GOOD) break
delay(SPEAK_AGAIN_MS)
}
}
}
private fun adviceLabel(advice: Advice): Int = when (advice) {
Advice.STARTING -> R.string.hand_camera_starting
Advice.STAND_UP -> R.string.hand_camera_stand_up
Advice.UPRIGHT -> R.string.hand_camera_upright
Advice.NOT_SEEN -> R.string.hand_camera_not_seen
Advice.MOVE_BACK -> R.string.hand_camera_move_back
Advice.MOVE_CLOSER -> R.string.hand_camera_move_closer
Advice.SHOW_HANDS -> R.string.hand_camera_show_hands
Advice.GOOD -> R.string.hand_camera_good
}
private val BONES = listOf(
BodyPose.LEFT_SHOULDER to BodyPose.RIGHT_SHOULDER,
BodyPose.LEFT_SHOULDER to BodyPose.LEFT_ELBOW, BodyPose.LEFT_ELBOW to BodyPose.LEFT_WRIST,
BodyPose.RIGHT_SHOULDER to BodyPose.RIGHT_ELBOW, BodyPose.RIGHT_ELBOW to BodyPose.RIGHT_WRIST,
BodyPose.LEFT_SHOULDER to BodyPose.LEFT_HIP, BodyPose.RIGHT_SHOULDER to BodyPose.RIGHT_HIP, BodyPose.LEFT_HIP to BodyPose.RIGHT_HIP,
BodyPose.NOSE to BodyPose.LEFT_EYE, BodyPose.NOSE to BodyPose.RIGHT_EYE,
BodyPose.LEFT_EYE to BodyPose.LEFT_EAR, BodyPose.RIGHT_EYE to BodyPose.RIGHT_EAR,
)
private val JOINTS = listOf(BodyPose.NOSE, BodyPose.LEFT_SHOULDER, BodyPose.RIGHT_SHOULDER, BodyPose.LEFT_ELBOW, BodyPose.RIGHT_ELBOW,
BodyPose.LEFT_HIP, BodyPose.RIGHT_HIP)
private const val GOOD_HOLD_MS = 1200L
private const val SPEAK_AFTER_MS = 1200L
private const val SPEAK_AGAIN_MS = 6000L
@@ -23,6 +23,7 @@ import androidx.compose.foundation.interaction.collectIsHoveredAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.BoxWithConstraintsScope
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
@@ -42,6 +43,7 @@ import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.ui.platform.testTag
import kotlinx.coroutines.Job
@@ -52,6 +54,7 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.compositionLocalOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
@@ -81,6 +84,7 @@ import androidx.compose.ui.geometry.RoundRect
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.drawscope.scale
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.graphics.lerp
import androidx.compose.ui.input.InputMode
@@ -102,6 +106,7 @@ import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.isSpecified
import androidx.compose.ui.unit.sp
import androidx.compose.ui.util.lerp
import com.droiddeck.launcher.R
@@ -138,6 +143,15 @@ internal class SheetBeat(private val pieces: List<Animatable<Float, AnimationVec
internal val LocalSheetBeat = staticCompositionLocalOf<SheetBeat?> { null }
internal val LocalSheetChipWidth = compositionLocalOf { Dp.Unspecified }
internal val LocalPlayRect = compositionLocalOf<Rect?> { null }
private val ChipGap = 6.dp
internal fun sheetChipWidth(row: Dp, count: Int): Dp =
if (count > 0 && row / count >= 96.dp) (row - ChipGap * (count - 1)) / count else 0.dp
@Composable
internal fun Modifier.sheetPiece(): Modifier {
val beat = LocalSheetBeat.current ?: return this
@@ -173,6 +187,8 @@ internal fun LiftHero(
onOpenChange: (Boolean) -> Unit = {},
start: Dp = 44.dp,
bottom: Dp = 44.dp,
drop: DropSheetState? = null,
overlay: @Composable BoxWithConstraintsScope.(lifted: () -> Float) -> Unit = {},
) {
val density = LocalDensity.current
val inputMode = LocalInputModeManager.current
@@ -306,7 +322,7 @@ internal fun LiftHero(
val lipFocus = remember { FocusRequester() }
val settingsLabel = stringResource(R.string.drawer_page_settings)
var lipFocused by remember { mutableStateOf(false) }
val lipWanted = !open && (!shown || lipBack) && (playFocused || playHovered || touchOnly || lipFocused)
val lipWanted = !open && (!shown || lipBack) && (playFocused || playHovered || touchOnly || lipFocused) && drop?.let { it.open || it.shown } != true
LaunchedEffect(lipWanted) {
if (lipWanted) {
if (!lipBack) delay(Motion.ms(160).toLong())
@@ -385,18 +401,35 @@ internal fun LiftHero(
}
BoxWithConstraints(
modifier.fillMaxSize().onGloballyPositioned { heroAt = it.boundsInRoot().topLeft }
.pointerInput(Unit) {
.pointerInput(drop) {
val tracker = androidx.compose.ui.input.pointer.util.VelocityTracker()
var decided = false
val dropFlick = 600.dp.toPx()
detectVerticalDragGestures(
onDragStart = { tracker.resetTracking(); decided = false; drag.engaged = false },
onDragEnd = { if (drag.engaged) settleDrag(tracker.calculateVelocity().y) },
onDragCancel = { if (drag.engaged) settleDrag(0f) },
onDragEnd = {
if (drag.engaged) settleDrag(tracker.calculateVelocity().y)
else if (drop?.engaged == true) drop.settle(tracker.calculateVelocity().y, dropFlick)
},
onDragCancel = {
if (drag.engaged) settleDrag(0f)
else if (drop?.engaged == true) drop.settle(0f, dropFlick)
},
) { change, amount ->
if (launching) return@detectVerticalDragGestures
if (!decided) {
decided = true
if (if (open) amount > 0f else amount < 0f) beginDrag()
when {
drop != null && (drop.open || drop.shown) -> if (drop.open && amount < 0f) drop.beginDrag()
open || shown || amount < 0f -> if (if (open) amount > 0f else amount < 0f) beginDrag()
drop != null && amount > 0f -> drop.beginDrag()
}
}
if (drop?.engaged == true) {
change.consume()
tracker.addPosition(change.uptimeMillis, change.position)
drop.drag(amount)
return@detectVerticalDragGestures
}
if (!drag.engaged) return@detectVerticalDragGestures
change.consume()
@@ -413,9 +446,15 @@ internal fun LiftHero(
val openTop = sheetTop(h, buttonH, with(density) { 16.dp.toPx() }, with(density) { 3.dp.toPx() })
val raise = restRect?.let { (openTop + with(density) { 3.dp.toPx() } - buttonH / 2f) - it.top } ?: 0f
travelPx[0] = (h - openTop).coerceAtLeast(1f)
val pill = restRect?.translate(0f, raise)
val chipsX = with(density) {
if (narrow || pill == null) 16.dp.toPx() else pill.right + 20.dp.toPx() - inset
}
val chipWidth = with(density) { sheetChipWidth((w - 2 * inset - chipsX - 64.dp.toPx()).coerceAtLeast(0f).toDp(), tabs.size) }
val foot = h
Box(Modifier.fillMaxSize().clipToBounds().graphicsLayer { val k = 1f - 0.05f * sink.value; scaleX = k; scaleY = k }) { background() }
val wallSink = { maxOf(sink.value, drop?.sink?.value ?: 0f) }
Box(Modifier.fillMaxSize().clipToBounds().graphicsLayer { val k = 1f - 0.05f * wallSink(); scaleX = k; scaleY = k }) { background() }
scrim { sink.value }
if (shown || open) Box(
Modifier.fillMaxSize()
@@ -432,7 +471,6 @@ internal fun LiftHero(
val rimPath = remember { Path() }
val corner = with(density) { SheetCorner.toPx() }
val rim = with(density) { 1.4.dp.toPx() }
val pill = restRect?.translate(0f, raise)
Canvas(Modifier.fillMaxSize()) {
val f = fold.value
val ft = foldTop.value
@@ -459,9 +497,6 @@ internal fun LiftHero(
drawPath(rimPath, rimColor, style = Stroke(rim))
}
}
val chipsX = with(density) {
if (narrow || pill == null) 16.dp.toPx() else pill.right + 20.dp.toPx() - sheetLeft
}
val chipsY = with(density) { if (narrow && pill != null) (pill.bottom - openTop) + 10.dp.toPx() else ChipsTop.toPx() }
val rowsY = with(density) { maxOf(RowsTop.toPx(), chipsY + 52.dp.toPx()) }
val sheetW = sheetRight - sheetLeft
@@ -537,13 +572,13 @@ internal fun LiftHero(
}
Column(Modifier.align(Alignment.BottomStart).padding(start = start, bottom = bottom, end = 20.dp)) {
Box(Modifier.graphicsLayer { alpha = 1f - sink.value }) { words() }
Box(Modifier.graphicsLayer { alpha = 1f - wallSink() }) { words() }
Spacer(Modifier.height(18.dp))
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
Box(
Modifier
.onGloballyPositioned { rest = it.boundsInRoot() }
.graphicsLayer { translationY = raise * ride.value }
.graphicsLayer { translationY = raise * ride.value; alpha = 1f - (drop?.sink?.value ?: 0f) }
.onFocusChanged {
if (it.hasFocus && leftForPlay[0]) { leftForPlay[0] = false; if (openState.value && !launchingState.value) close() }
playFocused = it.hasFocus
@@ -570,7 +605,7 @@ internal fun LiftHero(
val besideShown = !(open || shown)
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp),
modifier = Modifier.graphicsLayer { alpha = 1f - sink.value }
modifier = Modifier.graphicsLayer { alpha = 1f - wallSink() }
.focusProperties { canFocus = besideShown },
) { if (besideShown || sink.value < 0.99f) beside() }
}
@@ -585,7 +620,7 @@ internal fun LiftHero(
Modifier
.offset { IntOffset((r0.center.x - handleW / 2f).roundToInt(), (r0.bottom + raise * ride.value + (lipShow.value - 1f) * 8.dp.toPx()).roundToInt()) }
.onSizeChanged { handleW = it.width.toFloat() }
.graphicsLayer { alpha = lipShow.value * (1f - lipGone.value) }
.graphicsLayer { alpha = lipShow.value * (1f - lipGone.value) * (1f - (drop?.sink?.value ?: 0f)) }
.heightIn(min = 44.dp).testTag("sheet-open")
.semantics { contentDescription = settingsLabel }
.then(
@@ -599,14 +634,15 @@ internal fun LiftHero(
}
}
}
CompositionLocalProvider(LocalSheetChipWidth provides chipWidth, LocalPlayRect provides restRect) { overlay { sink.value } }
}
}
@Composable
private fun Handle(height: Dp) {
internal fun Handle(height: Dp, above: Boolean = false) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val shape = RoundedCornerShape(bottomStart = 12.dp, bottomEnd = 12.dp)
val shape = if (above) RoundedCornerShape(topStart = 12.dp, topEnd = 12.dp) else RoundedCornerShape(bottomStart = 12.dp, bottomEnd = 12.dp)
val still = Motion.scale == 0f
val bob = androidx.compose.animation.core.rememberInfiniteTransition(label = "handle")
val lift by bob.animateFloat(
@@ -625,18 +661,18 @@ private fun Handle(height: Dp) {
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp),
modifier = Modifier.height(height).clip(shape).background(colors.surface)
.drawBorderSidesAndFoot(pal.line, 12.dp)
.drawBorderSidesAndFoot(pal.line, 12.dp, flip = above)
.padding(start = 14.dp, end = 10.dp),
) {
Text(stringResource(R.string.drawer_page_settings), fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onSurfaceVariant, maxLines = 1)
Icon(
Icons.Filled.KeyboardArrowUp, null, tint = colors.onSurfaceVariant,
modifier = Modifier.size(16.dp).graphicsLayer { translationY = if (still) 0f else -3.dp.toPx() * lift },
if (above) Icons.Filled.KeyboardArrowDown else Icons.Filled.KeyboardArrowUp, null, tint = colors.onSurfaceVariant,
modifier = Modifier.size(16.dp).graphicsLayer { translationY = if (still) 0f else (if (above) 3.dp else -3.dp).toPx() * lift },
)
}
}
private fun Modifier.drawBorderSidesAndFoot(color: Color, corner: Dp): Modifier =
private fun Modifier.drawBorderSidesAndFoot(color: Color, corner: Dp, flip: Boolean = false): Modifier =
this.drawWithContent {
drawContent()
val c = corner.toPx()
@@ -649,30 +685,40 @@ private fun Modifier.drawBorderSidesAndFoot(color: Color, corner: Dp): Modifier
arcTo(Rect(size.width - 2 * c, size.height - 2 * c + sw / 2, size.width - sw / 2, size.height - sw / 2), 90f, -90f, false)
lineTo(size.width - sw / 2, 0f)
}
drawPath(p, color, style = Stroke(sw))
if (flip) scale(1f, -1f) { drawPath(p, color, style = Stroke(sw)) } else drawPath(p, color, style = Stroke(sw))
}
@OptIn(ExperimentalComposeUiApi::class)
@Composable
internal fun SheetChips(labels: List<String>, selected: Int, focus: List<FocusRequester>? = null, onPick: (Int) -> Unit) {
internal fun SheetChips(
labels: List<String>,
selected: Int,
focus: List<FocusRequester>? = null,
width: Dp = Dp.Unspecified,
onPick: (Int) -> Unit,
) {
val pal = LocalPalette.current
val bounds = remember { mutableStateMapOf<Int, Rect>() }
val tint = rememberUpdatedState(pal.signal)
val chips = focus ?: remember(labels.size) { List(labels.size) { FocusRequester() } }
var within by remember { mutableStateOf(false) }
LaunchedEffect(selected) { if (within) runCatching { chips[selected].requestFocus() } }
BoxWithConstraints(Modifier.fillMaxWidth().onFocusChanged { within = it.hasFocus }) {
val equal = maxWidth / labels.size.coerceAtLeast(1) >= 96.dp
BoxWithConstraints(
Modifier.fillMaxWidth().onFocusChanged { within = it.hasFocus },
contentAlignment = Alignment.CenterStart,
) {
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()
Box(if (equal) Modifier.fillMaxWidth() else Modifier.edgeFade(scroll).horizontalScroll(scroll).padding(3.dp)) {
Row(
horizontalArrangement = Arrangement.spacedBy(6.dp),
horizontalArrangement = Arrangement.spacedBy(ChipGap),
modifier = (if (equal) Modifier.fillMaxWidth() else Modifier)
.focusProperties { enter = { chips.getOrNull(selected) ?: FocusRequester.Default } }
.focusGroup(),
) {
labels.forEachIndexed { i, label ->
val m = (if (equal) Modifier.weight(1f) else Modifier.widthIn(min = 64.dp))
val m = (if (equal) Modifier.weight(1f) else Modifier.widthIn(min = least))
.onGloballyPositioned { bounds[i] = it.boundsInParent() }
.focusRequester(chips[i])
SheetChip(label, i == selected, m.onFocusChanged { if (it.isFocused && i != selected) onPick(i) }) { onPick(i) }
@@ -2,6 +2,7 @@ package com.droiddeck.launcher.ui
internal enum class SessionDrawerPage(val firstControl: String) {
CONTROLLER("touch"),
GLASSES("glasses-game"),
SECOND_SCREEN("second-screen:none"),
DISPLAY("hud"),
EFFECTS("look"),
@@ -10,8 +11,10 @@ internal enum class SessionDrawerPage(val firstControl: String) {
SESSION("suspend"),
}
internal fun sessionDrawerPages(hasSecondScreen: Boolean): List<SessionDrawerPage> =
SessionDrawerPage.entries.filter { hasSecondScreen || it != SessionDrawerPage.SECOND_SCREEN }
internal fun sessionDrawerPages(hasSecondScreen: Boolean, hasGlasses: Boolean = false): List<SessionDrawerPage> =
SessionDrawerPage.entries.filter {
(hasSecondScreen || it != SessionDrawerPage.SECOND_SCREEN) && (hasGlasses || it != SessionDrawerPage.GLASSES)
}
internal fun List<SessionDrawerPage>.step(current: SessionDrawerPage, direction: Int): SessionDrawerPage {
val index = indexOf(current).coerceAtLeast(0)
@@ -149,6 +149,7 @@ import java.util.Locale
private val SessionDrawerPage.title: Int get() = when (this) {
SessionDrawerPage.CONTROLLER -> R.string.drawer_page_controller
SessionDrawerPage.GLASSES -> R.string.drawer_page_glasses
SessionDrawerPage.SECOND_SCREEN -> R.string.drawer_second_screen
SessionDrawerPage.DISPLAY -> R.string.drawer_page_display
SessionDrawerPage.VR -> R.string.vr_title
@@ -159,6 +160,7 @@ private val SessionDrawerPage.title: Int get() = when (this) {
private val SessionDrawerPage.icon get() = when (this) {
SessionDrawerPage.CONTROLLER -> Icons.Outlined.SportsEsports
SessionDrawerPage.GLASSES -> GlassesIcon
SessionDrawerPage.SECOND_SCREEN -> Icons.Outlined.ScreenShare
SessionDrawerPage.DISPLAY -> Icons.Outlined.DesktopWindows
SessionDrawerPage.VR -> VrHeadsetIcon
@@ -211,6 +213,8 @@ class DrawerActions(
val cardboard: Cardboard = Cardboard.OFF,
val cardboardSensor: Boolean = false,
val steamVr: SteamVr.Status? = null,
val glassesPresent: Boolean = false,
val glassesOutput: Boolean = false,
val immersiveSteamVr: Boolean = false,
val textureAnisotropy: Int? = 0,
val textureLodBias: String? = TextureFiltering.LOD_BIAS_OFF,
@@ -247,6 +251,7 @@ class DrawerActions(
val onEffects: (ScreenEffects) -> Unit = {},
val onCardboard: (Cardboard) -> Unit = {},
val onCardboardRecenter: () -> Unit = {},
val onGlassesRecenter: () -> Unit = {},
val onSteamVr: (String) -> Unit = {},
val onTextureAnisotropy: (Int?) -> Unit = {},
val onTextureLodBias: (String?) -> Unit = {},
@@ -295,7 +300,7 @@ class DrawerActions(
@OptIn(ExperimentalComposeUiApi::class)
@Composable
internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, controllerActive: Boolean, onPageChange: (SessionDrawerPage) -> Unit, a: DrawerActions) {
val pages = sessionDrawerPages(a.steam && a.secondScreenDisplays.isNotEmpty())
val pages = sessionDrawerPages(a.steam && a.secondScreenDisplays.isNotEmpty(), a.glassesPresent)
val page = requestedPage.takeIf { it in pages } ?: SessionDrawerPage.CONTROLLER
LaunchedEffect(requestedPage, pages) { if (page != requestedPage) onPageChange(page) }
val colors = MaterialTheme.colorScheme
@@ -465,7 +470,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
}
SessionDrawerPage.VR -> {
SteamVrGroup(a) { key -> focus.track(page, key) }
CardboardGroup(host, a) { key -> focus.track(page, key) }
if (!a.glassesOutput) CardboardGroup(host, a) { key -> focus.track(page, key) }
}
SessionDrawerPage.CONTROLLER -> {
SettingsGroup(stringResource(R.string.drawer_page_controller)) {
@@ -532,6 +537,12 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
SessionDrawerPage.SECOND_SCREEN -> {
SecondScreenGroup(host, a) { key -> focus.track(page, key) }
}
SessionDrawerPage.GLASSES -> {
val (g, s) = rememberGlasses()
GlassesGroups(host, g, s, { key -> focus.track(page, key) }, onRecenter = a.onGlassesRecenter,
outputActive = a.glassesOutput, steamVrRunning = a.steamVr == SteamVr.Status.RUNNING,
steamVr = { SteamVrRow(a) })
}
SessionDrawerPage.GAMES -> {
if (a.steam) SelectedGameProfileGroup(host, a) { key -> focus.track(page, key) }
Text(stringResource(R.string.fex_next_launch), fontSize = 12.sp,
@@ -954,6 +965,19 @@ private fun SteamVrGroup(a: DrawerActions, track: (String) -> Modifier) {
}
}
@Composable
private fun SteamVrRow(a: DrawerActions) {
val vrLabel = stringResource(R.string.cardboard_steamvr)
when (a.steamVr) {
SteamVr.Status.NOT_INSTALLED -> ActionRow(vrLabel, null, stringResource(R.string.cardboard_steamvr_install), { a.onSteamVr("install") })
SteamVr.Status.INSTALLING -> SettingsRow(vrLabel, stringResource(R.string.cardboard_steamvr_installing)) {}
SteamVr.Status.READY -> ActionRow(vrLabel, null, stringResource(R.string.cardboard_steamvr_start), { a.onSteamVr("start") })
SteamVr.Status.RUNNING -> ActionRow(vrLabel, null, stringResource(R.string.cardboard_steamvr_stop), { a.onSteamVr("stop") })
SteamVr.Status.UNAVAILABLE -> SettingsRow(vrLabel, stringResource(R.string.cardboard_steamvr_unavailable)) {}
null -> {}
}
}
@Composable
private fun SecondScreenGroup(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) {
val colors = MaterialTheme.colorScheme
@@ -1,6 +1,7 @@
package com.droiddeck.launcher.ui
import androidx.compose.ui.platform.testTag
import androidx.compose.foundation.layout.fillMaxWidth
import com.droiddeck.launcher.R
import androidx.compose.ui.res.stringResource
import androidx.compose.animation.core.FastOutSlowInEasing
@@ -104,8 +105,24 @@ internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier)
}
},
)
val (glasses, glassesSettings) = rememberGlasses()
val headset = glasses.present && glasses.canControl
val drop = rememberDropSheetState()
LaunchedEffect(headset) { if (!headset && (drop.open || drop.shown)) drop.reset() }
LiftHero(
key = "steam", tabs = tabs,
drop = drop.takeIf { headset },
overlay = { lifted ->
if (headset) DropSheet(
drop, glassesTabs(glasses), covered = lifted,
button = { enabled ->
PrimaryButton(stringResource(R.string.games_play_steamvr), enabled = !s.busy && glasses.usable, large = true, icon = Icons.Filled.PlayArrow, fill = true,
modifier = Modifier.fillMaxWidth().testTag("play-steamvr")) { if (enabled) { drop.open = false; a.onPlaySteamVr() } }
},
) { tab ->
GlassesGroups(rememberMenuHost(), glasses, glassesSettings, inSession = false, tab = tab)
}
},
onOpen = a.onSteamSettings, onPrimary = a.onPlay,
modifier = modifier.clipToBounds(),
start = if (narrow) 20.dp else 44.dp, bottom = if (narrow) 20.dp else 44.dp,