fix(input): restore the controls, panels and settings #1439 removed (#2238)

* fix(input): restore on-screen touch behaviour: slide between buttons, mouse pass-through, keyboard on release, overlay haptics, stick reach and hit areas

* fix(dual-screen): restore second-screen bars, swapped Terminal and Deck panel tabs

* fix(input): fit on-screen layouts to the real view size, cutout, Steam + QAM mode and unfolded strip

* fix(input): unfolded strip keeps press haptics

* fix(input): restore layout import/export, element editor rows and layout tools

Bring back .icp layout import and export on the saved layouts page, the
per-element image, opacity and label controls, a uniform size slider and
reset positions in the layout editor, and non-destructive Steam, QAM and
keyboard button toggles stored on the layout style. Remove strings left
unused by the input profile unification.

* fix(input): keep hit slack to gamepad-shaped buttons and fit touch tests to saved layout geometry

* fix(input): button size regenerates the gamepad and scales spacing

A generated gamepad now stores its button size and is regenerated at that
size, so spacing follows the radius and the layout keeps regenerating on
rotation. Edited layouts scale positions from their anchor edge or centre
so gaps grow and shrink with the controls.

* fix(input): button size rescales moved gamepads around the generator

Gamepad layouts that no longer match the generated positions exactly were
scaled element by element from screen thirds, which split the face buttons
and D-pad across anchors. Gamepad controls now take the generator's
positions at the new size plus each control's own offset from the
generated position, so groups keep their shape and spacing.
This commit is contained in:
MaxsTechReview authored and GitHub committed 2026-11-07 16:36:23 -05:00
1 parent a33954b8bd
commit 8fa30b99f9
70 files changed
+2383 -1789

No files matched your search

@@ -12,6 +12,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.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
@@ -47,6 +48,7 @@ import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.input.DeckPanel
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
@@ -59,6 +61,8 @@ internal class BarExtra(
val onClick: () -> Unit,
)
internal class BarTabs(val labels: List<String>, val selected: Int, val onSelect: (Int) -> Unit)
internal class BottomBarModel(
val title: String?,
val onClose: (() -> Unit)?,
@@ -67,10 +71,22 @@ internal class BottomBarModel(
val onQam: (() -> Unit)?,
val extras: List<BarExtra> = emptyList(),
val menuActive: Boolean = false,
val tabs: BarTabs? = null,
)
@Composable
internal fun BottomScreenBar(model: BottomBarModel, modifier: Modifier = Modifier) {
val tabs = model.tabs
if (tabs == null) BarRow(model, modifier) else Column(modifier.fillMaxWidth().blockTouches()) {
BarRow(model)
Box(Modifier.fillMaxWidth().padding(start = BAR_PAD, end = BAR_PAD, bottom = 8.dp), contentAlignment = Alignment.Center) {
TabStrip(tabs.labels, tabs.selected, tabs.onSelect, Modifier.testTag("bottom-bar-tabs"), bumpers = false)
}
}
}
@Composable
private fun BarRow(model: BottomBarModel, modifier: Modifier = Modifier) {
val colors = MaterialTheme.colorScheme
BoxWithConstraints(modifier.fillMaxWidth().height(BAR_HEIGHT).blockTouches()) {
val buttons = listOfNotNull(model.onClose, model.onMenu, model.onQam).size + model.extras.size
@@ -195,11 +211,15 @@ internal fun sessionBarModel(
onSteam: () -> Unit,
onQam: () -> Unit,
extras: List<BarExtra> = emptyList(),
tabs: BarTabs? = null,
): BottomBarModel {
val steam = SessionState.mode == SessionService.MODE_STEAM
return BottomBarModel(title, onClose, onMenu, onSteam.takeIf { steam }, onQam.takeIf { steam }, extras)
return BottomBarModel(title, onClose, onMenu, onSteam.takeIf { steam }, onQam.takeIf { steam }, extras, tabs = tabs)
}
internal fun deckPanelTabs(context: Context, selected: DeckPanel, onSelect: (DeckPanel) -> Unit) =
BarTabs(DeckPanel.entries.map { context.getString(it.label) }, selected.ordinal) { onSelect(DeckPanel.entries[it]) }
internal fun bottomScreenBarView(context: Context, model: () -> BottomBarModel): ComposeView = ComposeView(context).apply {
setContent { DroidDeckTheme { BottomScreenBar(model()) } }
}
@@ -6,20 +6,38 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.foundation.Canvas
import androidx.compose.ui.graphics.nativeCanvas
import com.droiddeck.launcher.input.*
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.rememberUpdatedState
import com.droiddeck.launcher.R
import kotlin.math.roundToInt
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
@Composable
internal fun InputElementProperties(element: InputSurfaceElement, onChange: (InputSurfaceElement) -> Unit) {
val current by rememberUpdatedState(element)
val change by rememberUpdatedState(onChange)
OutlinedTextField(element.name, { onChange(element.copy(name = it.take(80))) }, label = { Text(stringResource(R.string.input_name)) },
singleLine = true, modifier = Modifier.fillMaxWidth().padding(bottom = 16.dp))
if (element.kind == InputElementKind.BUTTON || element.kind == InputElementKind.TRIGGER) {
val host = rememberMenuHost()
val context = LocalContext.current
val scope = rememberCoroutineScope()
val pickImage = rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) { uri ->
if (uri != null) scope.launch {
withContext(Dispatchers.IO) { InputButtonImages.import(context.applicationContext, uri) }?.let { change(current.copy(icon = 0, image = it)) }
}
}
ToggleRow(host, "element-toggle", stringResource(R.string.input_toggle_button), stringResource(R.string.input_toggle_button_hint), element.toggle) { onChange(element.copy(toggle = it)) }
ChoiceRow(host, "element-shape", stringResource(R.string.input_button_shape), null,
InputButtonShape.entries.map { it to stringResource(when (it) { InputButtonShape.ROUNDED -> R.string.input_shape_rounded; InputButtonShape.PILL -> R.string.input_shape_pill; InputButtonShape.CIRCLE -> R.string.input_shape_circle; InputButtonShape.RECTANGLE -> R.string.input_shape_rectangle }) },
@@ -30,6 +48,7 @@ internal fun InputElementProperties(element: InputSurfaceElement, onChange: (Inp
ValueChip(if (element.image.isNotEmpty()) stringResource(R.string.input_imported_image) else if (element.icon == 0) stringResource(R.string.input_button_text) else InputButtonIcons.label(context, element.icon), open) { host.open = if (open) null else "element-icon" }
AnchoredMenu(open, onDismiss = { host.open = null }, title = stringResource(R.string.input_button_symbol)) { firstItemFocus ->
MenuItem(stringResource(R.string.input_button_text), element.icon == 0 && element.image.isEmpty(), focusRequester = firstItemFocus) { onChange(element.copy(icon = 0, image = "")); host.open = null }
MenuItem(stringResource(R.string.screen_key_image), element.image.isNotEmpty()) { host.open = null; pickImage.launch("image/*") }
for (code in InputButtonIcons.codes) MenuItem(InputButtonIcons.label(context, code), element.icon == code && element.image.isEmpty(), leading = {
val color = MaterialTheme.colorScheme.onSurface
val symbol = remember(context, code) { InputButtonIcons.drawable(context, code) }
@@ -51,4 +70,10 @@ internal fun InputElementProperties(element: InputSurfaceElement, onChange: (Inp
ToggleRow(host, "element-floating", stringResource(R.string.input_floating_stick), null, element.floating) { onChange(element.copy(floating = it)) }
ToggleRow(host, "element-hide-idle", stringResource(R.string.input_hide_idle), null, element.hideWhenIdle) { onChange(element.copy(hideWhenIdle = it)) }
}
val host = rememberMenuHost()
if ((element.kind == InputElementKind.BUTTON || element.kind == InputElementKind.TRIGGER) && element.icon == 0 && element.image.isEmpty() ||
element.kind == InputElementKind.STICK && element.id.startsWith("legacy:"))
ToggleRow(host, "element-label", stringResource(R.string.input_show_label), null, element.showLabel) { onChange(element.copy(showLabel = it)) }
SliderRow(stringResource(R.string.ctrl_opacity), null, (element.opacity * 100).roundToInt().coerceIn(20, 100), 20..100, step = 5,
format = { "$it%" }, modifier = Modifier.testTag("setting-element-opacity")) { onChange(element.copy(opacity = it / 100f)) }
}
@@ -1,6 +1,12 @@
package com.droiddeck.launcher.ui
import android.content.Context
import android.net.Uri
import android.provider.OpenableColumns
import android.util.DisplayMetrics
import androidx.activity.compose.BackHandler
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.focusGroup
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.ui.focus.focusRequester
@@ -21,6 +27,9 @@ import androidx.compose.ui.window.DialogProperties
import com.droiddeck.launcher.R
import com.droiddeck.launcher.input.*
import com.droiddeck.launcher.session.SessionPrefs
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
@Composable
fun InputSettingsDialog(onBack: () -> Unit, onChanged: () -> Unit) {
@@ -88,7 +97,9 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
LaunchedEffect(surface) { onSurfaceEditing(surface) }
DisposableEffect(Unit) { onDispose { onSurfaceEditing(false) } }
var managingLayout by remember { mutableStateOf<SavedInputLayout?>(null) }
var exporting by remember { mutableStateOf<String?>(null) }
var error by remember { mutableStateOf<String?>(null) }
val scope = rememberCoroutineScope()
val controller = rememberControllerSettings()
var oscMode by remember { mutableStateOf(SessionPrefs.oscMode(context)) }
fun update(change: (InputLibrary) -> InputLibrary): Boolean = runCatching { InputLibraries.update(context, change) }
@@ -107,6 +118,27 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
val profile = library.profile(profileId)
val preset = library.preset(profile.binding(role))
val layout = library.layout(profileId, role)
val importer = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
if (uri == null) return@rememberLauncherForActivityResult
val target = role
scope.launch {
val raw = withContext(Dispatchers.IO) { readLayoutFile(context, uri) }
val metrics = inputDisplayMetrics(context, target)
val imported = raw?.let { InputLayoutFile.import(context, it, layoutFileName(context, uri) ?: context.getString(R.string.ctrl_layout),
if (target == InputRole.PRIMARY) InputLayoutScreen.MAIN else InputLayoutScreen.SECONDARY, layout?.style ?: InputSurfaceStyle(),
metrics.widthPixels, metrics.heightPixels, metrics.density) }
if (imported == null) error = context.getString(R.string.input_layout_import_failed)
else if (update { it.withLayout(imported.first).withPreset(imported.second).chooseLayout(profileId, target, imported.first.id) }) go(InputPage.SOURCE)
}
}
val exporter = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("application/json")) { uri ->
val text = exporting
exporting = null
if (uri != null && text != null) scope.launch {
val saved = withContext(Dispatchers.IO) { runCatching { context.contentResolver.openOutputStream(uri, "wt")?.use { it.write(text.toByteArray()) } != null }.getOrDefault(false) }
if (!saved) error = context.getString(R.string.input_save_failed)
}
}
fun rename(title: Int, name: String, save: (String) -> Unit) {
naming = InputNameRequest(title, name) { value, _, _ -> save(value) }
}
@@ -249,6 +281,8 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
InputColorRow(host, layout.style.tint) { color -> update { it.withLayout(layout.copy(style = layout.style.copy(tint = color))) } }
SliderRow(stringResource(R.string.ctrl_opacity), null, layout.style.opacity, 1..100, step = 1,
format = { "$it%" }) { opacity -> update { it.withLayout(layout.copy(style = layout.style.copy(opacity = opacity))) } }
for (button in layout.quickButtons) ToggleRow(host, "quick-${button.name.lowercase()}", stringResource(quickButtonLabel(button)), null,
button !in layout.style.hidden) { on -> update { it.withLayout(layout.withQuickButton(button, on)) } }
}
if (role == InputRole.SECONDARY) InputHint(stringResource(R.string.input_second_screen_enable))
}
@@ -302,10 +336,14 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
if (other.isNotEmpty()) PadTextButton(onClick = { showOther = !showOther }, modifier = Modifier.padding(8.dp)) {
Text(stringResource(if (showOther) R.string.input_hide_other_layouts else R.string.input_other_layouts, other.size))
}
PadTextButton(onClick = { naming = InputNameRequest(R.string.input_new_layout, "") { name, _, _ ->
val created = SavedInputLayout(newInputId(), name, screen = if (role == InputRole.PRIMARY) InputLayoutScreen.MAIN else InputLayoutScreen.SECONDARY)
if (update { it.withLayout(created).useLayout(profileId, role, created.id, shared = true) }) { go(InputPage.SOURCE); surface = true }
} }, modifier = Modifier.padding(8.dp)) { Text(stringResource(R.string.input_new_layout)) }
Row {
PadTextButton(onClick = { naming = InputNameRequest(R.string.input_new_layout, "") { name, _, _ ->
val created = SavedInputLayout(newInputId(), name, screen = if (role == InputRole.PRIMARY) InputLayoutScreen.MAIN else InputLayoutScreen.SECONDARY)
if (update { it.withLayout(created).useLayout(profileId, role, created.id, shared = true) }) { go(InputPage.SOURCE); surface = true }
} }, modifier = Modifier.padding(8.dp)) { Text(stringResource(R.string.input_new_layout)) }
PadTextButton(onClick = { importer.launch(arrayOf("application/json", "text/plain", "application/octet-stream", "*/*")) },
modifier = Modifier.padding(8.dp).testTag("input-layout-import")) { Text(stringResource(R.string.boot_movie_import)) }
}
}
}
@@ -329,6 +367,16 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
managingLayout = null
rename(R.string.input_rename_layout, saved.name) { name -> update { it.withLayout(saved.copy(name = name)) } }
}
val exported = remember(saved, library) {
val metrics = inputDisplayMetrics(context, if (saved.screen == InputLayoutScreen.SECONDARY) InputRole.SECONDARY else InputRole.PRIMARY)
InputLayoutFile.export(saved, library.bindings.firstOrNull { it.id == preset.id && it.layoutId == saved.id }
?: library.bindings.firstOrNull { it.layoutId == saved.id }, metrics.widthPixels, metrics.heightPixels)
}
if (exported != null) SecondaryButton(stringResource(R.string.screen_key_layout_export)) {
managingLayout = null
exporting = exported
exporter.launch(InputLayoutFile.fileName(saved))
}
val used = library.usersOfLayout(saved.id).isNotEmpty() || library.bindings.any { it.layoutId == saved.id && library.selectedBindings(it.id) }
if (!used && saved.editable) SecondaryButton(stringResource(R.string.input_delete)) {
managingLayout = null
@@ -413,6 +461,38 @@ private fun InputNavigationRow(title: String, detail: String?, modifier: Modifie
}
}
internal fun quickButtonLabel(button: InputCommand) = when (button) {
InputCommand.STEAM -> R.string.ctrl_steam_button
InputCommand.QUICK_ACCESS -> R.string.ctrl_qam_button
else -> R.string.ctrl_keyboard_button
}
@Suppress("DEPRECATION")
internal fun inputDisplayMetrics(context: Context, role: InputRole): DisplayMetrics = DisplayMetrics().also { metrics ->
(context.findActivity() as? com.droiddeck.launcher.SessionActivity)?.inputEditorDisplay(role)?.getRealMetrics(metrics)
?: metrics.setTo(context.resources.displayMetrics)
}
private fun readLayoutFile(context: Context, uri: Uri): String? = runCatching {
context.contentResolver.openInputStream(uri)?.use { input ->
val out = java.io.ByteArrayOutputStream()
val buffer = ByteArray(8192)
while (true) {
val read = input.read(buffer)
if (read < 0) break
out.write(buffer, 0, read)
if (out.size() > 1_000_000) return@use null
}
out.toString(Charsets.UTF_8.name())
}
}.getOrNull()
private fun layoutFileName(context: Context, uri: Uri): String? = runCatching {
context.contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { cursor ->
if (cursor.moveToFirst()) cursor.getString(0)?.substringBeforeLast('.')?.trim()?.takeIf { it.isNotEmpty() } else null
}
}.getOrNull()
@Composable
internal fun roleLabel(role: InputRole) = stringResource(when (role) {
InputRole.PHYSICAL -> R.string.input_physical; InputRole.PRIMARY -> R.string.input_primary; InputRole.SECONDARY -> R.string.input_secondary
@@ -58,7 +58,18 @@ import com.droiddeck.launcher.SessionActivity
import com.droiddeck.launcher.input.*
import com.droiddeck.launcher.session.SessionState
private class SurfaceDraft(val layout: SavedInputLayout, val preset: SavedInputBindings) {
private data class SurfaceSnapshot(val elements: List<InputSurfaceElement>, val actions: Map<String, InputAction>,
val clicks: Map<String, InputAction>, val scale: Float)
private class GamepadScaler(private val context: android.content.Context, private val width: Int, private val height: Int) {
private fun generator(scale: Float) = LegacyGamepadLayout(context, width, height, scale = scale)
val ids = generator(1f).elements().map { it.id }.toSet()
fun rescale(stored: List<InputSurfaceElement>, from: Float, to: Float) = generator(to).rescale(stored, generator(from))
fun reset(stored: List<InputSurfaceElement>) = generator(1f).regenerate(stored).associateBy { it.id }.let { placed -> stored.map { placed[it.id] ?: it } }
}
private class SurfaceDraft(val layout: SavedInputLayout, val preset: SavedInputBindings, val defaults: List<InputSurfaceElement>? = null,
private val gamepad: GamepadScaler? = null) {
var elements by mutableStateOf(layout.elements)
var actions by mutableStateOf(preset.elements)
var clicks by mutableStateOf(preset.clicks)
@@ -70,15 +81,41 @@ private class SurfaceDraft(val layout: SavedInputLayout, val preset: SavedInputB
var adding by mutableStateOf(false)
var properties by mutableStateOf(false)
var clickProperties by mutableStateOf(false)
var history by mutableStateOf<List<Triple<List<InputSurfaceElement>, Map<String, InputAction>, Map<String, InputAction>>>>(emptyList())
var history by mutableStateOf<List<SurfaceSnapshot>>(emptyList())
var layoutScale by mutableFloatStateOf(layout.scale)
private var scaleBase by mutableStateOf<Triple<List<InputSurfaceElement>, List<InputSurfaceElement>, Float>?>(null)
private var scaleValue by mutableIntStateOf(100)
private val rescales get() = gamepad != null && elements.any { it.id in gamepad.ids }
val scale get() = when {
scaleBase?.second == elements -> scaleValue
rescales -> (layoutScale * 100).roundToInt()
else -> 100
}
val positioned get() = (if (rescales) gamepad!!.reset(elements) else defaults?.let { elements.withPositionsOf(it) })
?.takeIf { it != elements || rescales && layoutScale != 1f }
val element get() = elements.firstOrNull { it.id == selected }
val dirty get() = elements != layout.elements || actions != preset.elements || clicks != preset.clicks
fun checkpoint() { history = (history + Triple(elements, actions, clicks)).takeLast(40) }
fun undo() { history.lastOrNull()?.let { elements = it.first; actions = it.second; clicks = it.third; history = history.dropLast(1) } }
val dirty get() = elements != layout.elements || actions != preset.elements || clicks != preset.clicks || layoutScale != layout.scale
fun checkpoint() { history = (history + SurfaceSnapshot(elements, actions, clicks, layoutScale)).takeLast(40) }
fun undo() { history.lastOrNull()?.let { elements = it.elements; actions = it.actions; clicks = it.clicks; layoutScale = it.scale; history = history.dropLast(1) } }
fun scaleAll(percent: Int) {
val base = scaleBase?.takeIf { it.second == elements } ?: Triple(elements, elements, if (rescales) layoutScale else 0f).also { checkpoint() }
val factor = percent / 100f
elements = if (base.third > 0f && gamepad != null) {
layoutScale = factor
val others = base.first.filterNot { it.id in gamepad.ids }.scaled(factor / base.third).associateBy { it.id }
gamepad.rescale(base.first, base.third, factor).map { others[it.id] ?: it }
} else base.first.scaled(factor)
scaleValue = percent; scaleBase = Triple(base.first, elements, base.third)
}
fun resetPositions() { positioned?.let { checkpoint(); elements = it; if (rescales) layoutScale = 1f } }
fun action(e: InputSurfaceElement) = preset.copy(elements = actions).action(e)
fun clickAction(e: InputSurfaceElement) = preset.copy(elements = actions, clicks = clicks).clickAction(e)
}
@Suppress("DEPRECATION")
private fun displayAspect(display: Display): Float? = android.util.DisplayMetrics().also(display::getRealMetrics)
.takeIf { it.widthPixels > 0 && it.heightPixels > 0 }?.let { (it.widthPixels.toFloat() / it.heightPixels).coerceIn(.05f, 20f) }
@Composable
fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () -> Unit,
role: InputRole = InputRole.SECONDARY, layoutId: String? = null, bindingsId: String? = null) {
@@ -89,7 +126,14 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () ->
val savedBindings = remember { library.preset(bindingsId ?: library.profile(profile).binding(role)) }
val layoutUsers = library.usersOfLayout(savedLayout.id).size
val bindingUsers = library.usersOfBindings(savedBindings.id).size
val draft = remember { SurfaceDraft(savedLayout, savedBindings) }
val draft = remember {
val (display, metrics) = InputLibraries.primaryDisplay(context)
val gamepad = savedLayout.elements.takeIf { e -> e.any { it.id.startsWith("legacy:") } }?.let {
val (w, h) = OnScreenLayout.generatedSize(context, savedLayout, metrics.widthPixels, metrics.heightPixels) ?: (metrics.widthPixels to metrics.heightPixels)
GamepadScaler(display, w, h)
}
SurfaceDraft(savedLayout, savedBindings, InputLibraries.defaultPositions(context, library, savedLayout), gamepad)
}
val manager = remember { context.getSystemService(DisplayManager::class.java) }
var revision by remember { mutableIntStateOf(0) }
var discard by remember { mutableStateOf(false) }
@@ -109,7 +153,7 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () ->
InputLibraries.update(context) { latest ->
val l = latest.layouts.first { it.id == savedLayout.id }
val p = latest.preset(savedBindings.id)
latest.withLayout(l.copy(elements = draft.elements)).withPreset(p.copy(elements = draft.actions.filterKeys { id -> draft.elements.any { it.id == id } },
latest.withLayout(l.copy(elements = draft.elements, aspect = target?.let(::displayAspect) ?: l.aspect, scale = draft.layoutScale)).withPreset(p.copy(elements = draft.actions.filterKeys { id -> draft.elements.any { it.id == id } },
clicks = draft.clicks.filterKeys { id -> draft.elements.any { it.id == id && it.hasClick } }))
}
}.onSuccess { onChanged(); onDismiss() }.onFailure { failure = it.message ?: context.getString(R.string.input_save_failed) }
@@ -204,7 +248,7 @@ private fun SurfaceCanvas(draft: SurfaceDraft, transparent: Boolean = false) {
AndroidView(factory = { InputSurfaceEditorView(it) }, modifier = Modifier.fillMaxSize().testTag("input-layout-canvas"),
update = { view ->
view.setBackgroundColor(if (transparent) android.graphics.Color.TRANSPARENT else android.graphics.Color.rgb(10, 11, 13))
view.style = draft.layout.style; view.elements = draft.elements; view.selected = draft.selected; view.snap = draft.snap
view.style = draft.layout.style.copy(hidden = emptySet()); view.elements = draft.elements; view.selected = draft.selected; view.snap = draft.snap
view.isEnabled = !draft.properties && !draft.adding
view.onSelect = { if (!draft.properties) draft.selected = it }
view.onBeginEdit = draft::checkpoint
@@ -269,12 +313,15 @@ private fun SurfaceToolbar(draft: SurfaceDraft, onSave: () -> Unit, onLeave: ()
SecondaryButton(stringResource(R.string.common_cancel), compact = true, onClick = onLeave)
SecondaryButton(stringResource(R.string.input_editor_add), enabled = draft.elements.size < 64, compact = true) { draft.adding = true }
SecondaryButton(stringResource(R.string.input_editor_undo), enabled = draft.history.isNotEmpty(), compact = true) { draft.undo() }
if (draft.defaults != null) SecondaryButton(stringResource(R.string.input_reset_positions), enabled = draft.positioned != null, compact = true) { draft.resetPositions() }
Row(verticalAlignment = Alignment.CenterVertically) {
Checkbox(draft.snap, { draft.snap = it })
Text(stringResource(R.string.ctrl_editor_snap))
}
PrimaryButton(stringResource(R.string.input_editor_done), compact = true, onClick = onSave)
}
if (draft.elements.isNotEmpty()) SliderRow(stringResource(R.string.ctrl_size), null, draft.scale, 80..125, step = 5,
format = { "$it%" }, modifier = Modifier.testTag("input-editor-scale")) { draft.scaleAll(it) }
}
@OptIn(ExperimentalLayoutApi::class)
@@ -23,7 +23,6 @@ import com.droiddeck.launcher.input.PointerGestures
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.HorizontalScrollView
import android.widget.LinearLayout
import android.widget.TextView
import com.droiddeck.launcher.input.InputRole
@@ -35,7 +34,7 @@ import com.droiddeck.launcher.input.InputSurfaceSource
import com.droiddeck.launcher.input.InputElementKind
import com.droiddeck.launcher.input.InputButtonIcons
import com.droiddeck.launcher.input.InputButtonShape
import java.io.File
import com.droiddeck.launcher.input.InputButtonImages
import com.droiddeck.launcher.input.PadBridge
import com.droiddeck.launcher.session.SessionPrefs
import kotlin.math.atan2
@@ -49,40 +48,94 @@ class InputSurfaceView(
private var customLayout: List<InputSurfaceElement> = emptyList(),
private val inputRole: InputRole = InputRole.SECONDARY,
private var surfaceStyle: InputSurfaceStyle = InputSurfaceStyle(),
private val haptics: Boolean = inputRole != InputRole.PRIMARY,
) : FrameLayout(context) {
private val content = FrameLayout(context)
private val elementSources = ArrayList<InputSurfaceSource>()
private var customCanvas: ViewGroup? = null
init { addView(content, LayoutParams(-1, -1)); renderCustom(pad) }
private val owners = HashMap<Int, View>()
private var requestedLayout = customLayout
init { customLayout = surfaceStyle.shown(customLayout); addView(content, LayoutParams(-1, -1)); renderCustom(pad) }
var onTouchMiss: ((MotionEvent) -> Unit)? = null
private var forwardedPointers = 0
override fun dispatchTouchEvent(event: MotionEvent): Boolean {
if (event.actionMasked == MotionEvent.ACTION_DOWN) forwardedPointers = 0
if (onTouchMiss == null) return super.dispatchTouchEvent(event)
if (event.actionMasked == MotionEvent.ACTION_DOWN) { forwardedPointers = 0; cancelOwners(event) }
if (event.actionMasked == MotionEvent.ACTION_DOWN || event.actionMasked == MotionEvent.ACTION_POINTER_DOWN) {
val index = event.actionIndex
if (!takesTouchAt(event.getX(index), event.getY(index))) forwardedPointers = forwardedPointers or (1 shl event.getPointerId(index))
else if (SessionPrefs.lowLatency(context)) requestUnbufferedDispatch(event)
if (event.getToolType(index) == MotionEvent.TOOL_TYPE_MOUSE || !takesTouchAt(event.getX(index), event.getY(index)))
forwardedPointers = forwardedPointers or (1 shl event.getPointerId(index))
else if (onTouchMiss != null && SessionPrefs.lowLatency(context)) requestUnbufferedDispatch(event)
}
if (forwardedPointers == 0) return super.dispatchTouchEvent(event)
if (forwardedPointers == 0) return route(event)
var all = 0
for (index in 0 until event.pointerCount) all = all or (1 shl event.getPointerId(index))
event.pointerSubset(all and forwardedPointers.inv())?.let { split ->
try { super.dispatchTouchEvent(split) } finally { split.recycle() }
}
val routed = event.pointerSubset(all and forwardedPointers.inv())?.let { split ->
try { route(split) } finally { split.recycle() }
} ?: false
event.pointerSubset(all and forwardedPointers)?.let { split ->
try { onTouchMiss?.invoke(split) } finally { split.recycle() }
}
if (event.actionMasked == MotionEvent.ACTION_POINTER_UP) forwardedPointers = forwardedPointers and (1 shl event.getPointerId(event.actionIndex)).inv()
if (event.actionMasked == MotionEvent.ACTION_UP || event.actionMasked == MotionEvent.ACTION_CANCEL) forwardedPointers = 0
return true
return onTouchMiss != null || routed
}
private fun route(event: MotionEvent): Boolean {
val action = event.actionMasked
if (action == MotionEvent.ACTION_CANCEL) { cancelOwners(event); return true }
val index = event.actionIndex
val pointer = event.getPointerId(index)
var taken = true
if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_POINTER_DOWN) {
val target = elementAt(event.getX(index), event.getY(index))
taken = target != null
when {
target is HoldButton -> { owners[pointer] = target; target.press(pointer, true) }
target != null && !(target is StickView && target in owners.values) -> owners[pointer] = target
}
}
if (action == MotionEvent.ACTION_MOVE) for (i in 0 until event.pointerCount) slide(event.getPointerId(i), event.getX(i), event.getY(i))
for (view in owners.values.distinct()) {
if (view is HoldButton) continue
var bits = 0
for ((id, owner) in owners) if (owner === view) bits = bits or (1 shl id)
event.pointerSubset(bits)?.let { split ->
try { split.offsetLocation(-originX(view), -originY(view)); view.dispatchTouchEvent(split) } finally { split.recycle() }
}
}
if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_POINTER_UP) {
(owners.remove(pointer) as? HoldButton)?.press(pointer, false, event.flags and MotionEvent.FLAG_CANCELED != 0)
}
return taken
}
private fun slide(pointer: Int, x: Float, y: Float) {
val owner = owners[pointer]
if (owner != null && owner !is HoldButton) return
val over = elementAt(x, y) as? HoldButton
if (over === owner) return
(owner as? HoldButton)?.press(pointer, false, cancelled = true)
if (over == null) owners.remove(pointer) else { owners[pointer] = over; over.press(pointer, true) }
}
private fun cancelOwners(event: MotionEvent) {
if (owners.isEmpty()) return
val views = owners.values.distinct()
owners.clear()
for (view in views) {
if (view is HoldButton) { view.cancel(); continue }
val cancel = MotionEvent.obtain(event.downTime, event.eventTime, MotionEvent.ACTION_CANCEL, 0f, 0f, 0)
try { view.dispatchTouchEvent(cancel) } finally { cancel.recycle() }
}
}
fun updateStyle(style: InputSurfaceStyle) {
if (surfaceStyle == style) return
val relayout = surfaceStyle.hidden != style.hidden
surfaceStyle = style
if (relayout) updateCustomLayout(requestedLayout)
customCanvas?.let { canvas -> for (i in 0 until canvas.childCount) styleElement(canvas.getChildAt(i)) }
}
@@ -92,23 +145,30 @@ class InputSurfaceView(
view.invalidate()
}
fun updateCustomLayout(layout: List<InputSurfaceElement>) {
fun updateCustomLayout(requested: List<InputSurfaceElement>) {
requestedLayout = requested
val layout = surfaceStyle.shown(requested)
val sameElements = customLayout.map { it.copy(x = 0f, y = 0f, width = 1f, height = 1f) } == layout.map { it.copy(x = 0f, y = 0f, width = 1f, height = 1f) }
customLayout = layout
if (sameElements) customCanvas?.requestLayout() else {
elementSources.forEach { it.close() }; elementSources.clear()
content.removeAllViews(); renderCustom(pad)
owners.clear(); content.removeAllViews(); renderCustom(pad)
}
}
fun releaseInputs() {
val now = android.os.SystemClock.uptimeMillis()
val cancel = MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0f, 0f, 0)
try { super.dispatchTouchEvent(cancel) } finally { cancel.recycle() }
try { cancelOwners(cancel) } finally { cancel.recycle() }
forwardedPointers = 0
elementSources.forEach { it.release() }
}
override fun onVisibilityChanged(changedView: View, visibility: Int) {
super.onVisibilityChanged(changedView, visibility)
if (visibility != VISIBLE) releaseInputs()
}
private fun renderCustom(pad: PadBridge?) {
val canvas = object : ViewGroup(context) {
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
@@ -129,7 +189,7 @@ class InputSurfaceView(
}
}
}
canvas.clipChildren = customLayout.none { it.kind == InputElementKind.STICK && classic(it) }
canvas.clipChildren = customLayout.none { it.kind == InputElementKind.STICK && (classic(it) || adaptive(it)) }
for (element in customLayout) {
val source = pad?.let { InputSurfaceSource(it, inputRole, element).also { s -> elementSources += s } }
canvas.addView(when (element.kind) {
@@ -146,7 +206,7 @@ class InputSurfaceView(
override fun onAttachedToWindow() {
super.onAttachedToWindow()
if (pad != null && elementSources.isEmpty()) {
content.removeAllViews()
owners.clear(); content.removeAllViews()
renderCustom(pad)
}
}
@@ -157,19 +217,52 @@ class InputSurfaceView(
super.onDetachedFromWindow()
}
fun takesTouchAt(x: Float, y: Float): Boolean = controlUnder(this, x, y)
fun takesTouchAt(x: Float, y: Float): Boolean = elementAt(x, y) != null
private fun controlUnder(view: View, x: Float, y: Float): Boolean {
if (view.visibility != VISIBLE || x < 0f || y < 0f || x >= view.width || y >= view.height) return false
if (view.isClickable || view is HorizontalScrollView || view is Surface || view is DirectionPad ||
view is androidx.compose.ui.platform.ComposeView) return true
val group = view as? ViewGroup ?: return false
return (group.childCount - 1 downTo 0).any { i ->
val child = group.getChildAt(i)
controlUnder(child, x + group.scrollX - child.x, y + group.scrollY - child.y)
}
private fun elementAt(x: Float, y: Float): View? {
val canvas = customCanvas ?: return null
if (visibility != VISIBLE || x < 0f || y < 0f || x >= width || y >= height) return null
val views = (canvas.childCount - 1 downTo 0).map(canvas::getChildAt).filter { it.visibility == VISIBLE }
views.firstOrNull { !(it is StickView && it.adaptive) && hits(it, x, y, 0f) }?.let { return it }
views.filter { it is HoldButton && hits(it, x, y, slack(it)) }.minByOrNull { distance(it, x, y) }?.let { return it }
if (views.any { it is HoldButton && hits(it, x, y, slack(it) + ADAPTIVE_CLEARANCE_PX) }) return null
return views.filter { it is StickView && it.adaptive && it !in owners.values && (hits(it, x, y, 0f) || it.captures(x - originX(it), y - originY(it))) }
.minByOrNull { distance(it, x, y) }
}
private fun hits(view: View, x: Float, y: Float, slack: Float): Boolean {
val left = originX(view)
val top = originY(view)
if ((view as? HoldButton)?.round == true && slack > 0f) {
val reach = min(view.width, view.height) / 2f + slack
return hypot(x - left - view.width / 2f, y - top - view.height / 2f) <= reach
}
return x >= left - slack && x < left + view.width + slack && y >= top - slack && y < top + view.height + slack
}
private fun slack(view: View) = if ((view as? HoldButton)?.gamepad == true) min(view.width, view.height) / 2f * HIT_SLACK else 0f
private fun distance(view: View, x: Float, y: Float): Float {
val cx = originX(view) + ((view as? StickView)?.centreX() ?: (view.width / 2f))
return hypot(x - cx, y - originY(view) - view.height / 2f)
}
private fun originX(view: View): Float {
var x = 0f
var at: View = view
while (at !== this) { x += at.left - ((at.parent as? View)?.scrollX ?: 0); at = at.parent as? View ?: break }
return x
}
private fun originY(view: View): Float {
var y = 0f
var at: View = view
while (at !== this) { y += at.top - ((at.parent as? View)?.scrollY ?: 0); at = at.parent as? View ?: break }
return y
}
private fun feedback(view: View, type: Int) { if (haptics) view.performHapticFeedback(type) }
private abstract class Surface(context: Context) : View(context) {
var tint: Int? = null
protected val density = resources.displayMetrics.density
@@ -231,11 +324,13 @@ class InputSurfaceView(
protected fun textColor(lit: Boolean) = if (lit) Color.WHITE else tint?.let { light(it, 210, 0.75f) } ?: TEXT
}
private class HoldButton(context: Context, private val element: InputSurfaceElement, private val source: InputSurfaceSource?) : Surface(context) {
private inner class HoldButton(context: Context, private val element: InputSurfaceElement, private val source: InputSurfaceSource?) : Surface(context) {
private var down = false
private val pointers = HashSet<Int>()
val round get() = element.buttonShape == InputButtonShape.CIRCLE
val gamepad get() = round || element.buttonShape == InputButtonShape.PILL
private val symbol = InputButtonIcons.drawable(context, element.icon)
private val bitmap = element.image.takeIf { it.matches(Regex("[A-Za-z0-9_.-]{1,128}")) && it != "." && it != ".." }?.let { name ->
val file = File(File(context.filesDir, "screenkeys"), name)
private val bitmap = InputButtonImages.file(context, element.image)?.let { file ->
val size = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeFile(file.path, size)
val options = BitmapFactory.Options().apply {
@@ -282,23 +377,20 @@ class InputSurfaceView(
canvas.drawText(element.name, cx, height / 2f + labelPaint.textSize * .35f, labelPaint)
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent): Boolean {
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> set(true)
MotionEvent.ACTION_UP -> set(false)
MotionEvent.ACTION_CANCEL -> { set(false); source?.release() }
}
return true
fun press(pointer: Int, pressed: Boolean, cancelled: Boolean = false) {
if (pressed) pointers.add(pointer) else pointers.remove(pointer)
set(pointers.isNotEmpty(), cancelled)
}
override fun onDetachedFromWindow() { set(false); source?.release(); super.onDetachedFromWindow() }
fun cancel() { pointers.clear(); set(false, cancelled = true); source?.release() }
private fun set(pressed: Boolean) {
override fun onDetachedFromWindow() { cancel(); super.onDetachedFromWindow() }
private fun set(pressed: Boolean, cancelled: Boolean = false) {
if (down == pressed) return
down = pressed
if (pressed) performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
source?.update(if (pressed) 1f else 0f)
if (pressed) feedback(this, HapticFeedbackConstants.VIRTUAL_KEY)
if (!pressed && cancelled) source?.cancel() else source?.update(if (pressed) 1f else 0f)
invalidate()
}
}
@@ -314,7 +406,7 @@ class InputSurfaceView(
}
override fun onButton(button: Int, pressed: Boolean, x: Float, y: Float) { source?.gestureButton(button, pressed) }
override fun onWheel(steps: Int) { source?.gestureWheel(steps) }
override fun onLongPress() { performHapticFeedback(HapticFeedbackConstants.LONG_PRESS) }
override fun onLongPress() { feedback(this@TrackpadView, HapticFeedbackConstants.LONG_PRESS) }
}).apply { bounds = RectF(-1e9f, -1e9f, 1e9f, 1e9f) }
private var touching = false
@@ -396,7 +488,7 @@ class InputSurfaceView(
private fun click(down: Boolean) {
if (clicked == down) return
clicked = down
if (down) performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
if (down) feedback(this, HapticFeedbackConstants.VIRTUAL_KEY)
source?.click(down)
invalidate()
}
@@ -418,9 +510,18 @@ class InputSurfaceView(
private val ring = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE }
private val knob = Paint(Paint.ANTI_ALIAS_FLAG)
private fun reach() = min(width, height) * 0.30f
val adaptive get() = adaptive(element)
private fun centreX() = when {
fun reach() = min(width, height) * if (classic(element)) CLASSIC_REACH else PANEL_REACH
fun captures(x: Float, y: Float): Boolean {
val cx = centreX()
val dx = if (element.control == InputControl.LS) maxOf(0f, x - cx) else x - cx
val limit = reach() * ADAPTIVE_REACH
return dx * dx + (y - height / 2f) * (y - height / 2f) <= limit * limit
}
fun centreX() = when {
!classic(element) || width <= height -> width / 2f
element.control == InputControl.LS -> width - height / 2f
else -> height / 2f
@@ -465,7 +566,7 @@ class InputSurfaceView(
originX = if (floating) event.x else centreX()
originY = if (floating) event.y else height / 2f
touching = true
performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
feedback(this, HapticFeedbackConstants.VIRTUAL_KEY)
if (lastUp != 0L && event.eventTime - lastUp < CLICK_MS) setClick(true)
follow(event.x, event.y, r, force = true)
}
@@ -501,7 +602,7 @@ class InputSurfaceView(
private fun setClick(down: Boolean) {
if (clicking == down) return
clicking = down
if (down) performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
if (down) feedback(this, HapticFeedbackConstants.VIRTUAL_KEY)
source?.click(down)
}
@@ -556,7 +657,7 @@ class InputSurfaceView(
private fun set(bits: Int) {
if (bits == held) return
if (bits and held.inv() != 0) performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
if (bits and held.inv() != 0) feedback(this, HapticFeedbackConstants.VIRTUAL_KEY)
held = bits
source?.update((if (bits and 2 != 0) 1f else 0f) - (if (bits and 8 != 0) 1f else 0f),
(if (bits and 4 != 0) 1f else 0f) - (if (bits and 1 != 0) 1f else 0f))
@@ -573,6 +674,11 @@ class InputSurfaceView(
companion object {
private const val CLICK_MS = 300L
private const val STICK_TAP_MS = 200L
private const val CLASSIC_REACH = 0.5f
private const val PANEL_REACH = 0.30f
private const val HIT_SLACK = 0.25f
private const val ADAPTIVE_CLEARANCE_PX = 5f
private val ADAPTIVE_REACH = 1.4f * kotlin.math.sqrt(1.5f)
private const val CORNER = 20f
@@ -588,6 +694,8 @@ class InputSurfaceView(
private val TEXT_DIM = Color.rgb(0x7A, 0x80, 0x8A)
private val KNOB = Color.rgb(0x2A, 0x2D, 0x33)
private fun adaptive(element: InputSurfaceElement) = element.kind == InputElementKind.STICK && element.floating && element.hideWhenIdle
private fun classic(element: InputSurfaceElement) = (element.id == "legacy:${element.control.id}" || element.id == "builtin:keyboard") &&
(element.buttonShape == InputButtonShape.CIRCLE || element.buttonShape == InputButtonShape.PILL)
@@ -18,11 +18,13 @@ import androidx.activity.setViewTreeOnBackPressedDispatcherOwner
import androidx.lifecycle.setViewTreeLifecycleOwner
import androidx.lifecycle.setViewTreeViewModelStoreOwner
import androidx.savedstate.setViewTreeSavedStateRegistryOwner
import com.droiddeck.launcher.input.DeckPanel
import com.droiddeck.launcher.input.KeyboardHost
import com.droiddeck.launcher.input.PadBridge
import com.droiddeck.launcher.input.SecondScreenMode
import com.droiddeck.launcher.SessionActivity
import com.droiddeck.launcher.session.BottomDesktop
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
@@ -39,6 +41,7 @@ class SecondScreenPresentation(
private val dashboard: (@androidx.compose.runtime.Composable () -> Unit)? = null,
private val onSwap: (() -> Unit)? = null,
private val onMenuTouched: () -> Unit = {},
private val onDeckPanel: (DeckPanel) -> Unit = { SessionPrefs.setDeckPanel(sessionActivity, it) },
) : Presentation(sessionActivity, display) {
private val frame = FrameLayout(context)
private var menuView: androidx.compose.ui.platform.ComposeView? = null
@@ -55,6 +58,7 @@ class SecondScreenPresentation(
private var currentMode = SecondScreenMode.NONE
private var keyboardHost: KeyboardHost? = null
private val keyboardShown = androidx.compose.runtime.mutableStateOf(false)
private val deckPanel = androidx.compose.runtime.mutableStateOf(DeckPanel.BOTH)
private var keyboardPending = false
private var imeSeen = false
private var fieldKeyboard = false
@@ -284,6 +288,8 @@ class SecondScreenPresentation(
when (mode) {
SecondScreenMode.TERMINAL -> renderTerminal()
SecondScreenMode.CUSTOM_CONTROLS, SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.DECK_CONTROLS -> {
if (mode == SecondScreenMode.DECK_CONTROLS) deckPanel.value = SessionPrefs.deckPanel(context)
bar(mode)
val layout = panelLayout(mode)
val controls = InputSurfaceView(context, pad, layout?.elements.orEmpty(),
surfaceStyle = layout?.style ?: com.droiddeck.launcher.input.InputSurfaceStyle())
@@ -301,19 +307,39 @@ class SecondScreenPresentation(
}
private fun panelLayout(mode: SecondScreenMode) = com.droiddeck.launcher.input.InputLibraries.read(context)
.panelLayout(SessionState.mode == SessionService.MODE_DESKTOP, mode.bindings)
.panelLayout(SessionState.mode == SessionService.MODE_DESKTOP, mode.panel(context))
private fun bar(mode: SecondScreenMode, extras: () -> List<BarExtra> = { emptyList() }) {
root.addView(bottomScreenBarView(context) {
sessionBarModel(context.getString(mode.label), onClose, onMenu, onSteamMenu, onQam, extras())
}, LinearLayout.LayoutParams(-1, -2))
private fun bar(mode: SecondScreenMode) {
val first = barModel(mode) ?: return
root.addView(bottomScreenBarView(context) { barModel(mode) ?: first }, LinearLayout.LayoutParams(-1, -2))
}
internal fun barModel(mode: SecondScreenMode): BottomBarModel? {
val swap = listOfNotNull(onSwap?.let { BarExtra(context.getString(R.string.swap_screens), icon = R.drawable.ic_bottom_swap, tag = "bottom-swap", onClick = it) })
fun model(extras: List<BarExtra>, tabs: BarTabs? = null) =
sessionBarModel(context.getString(mode.label), onClose, onMenu, onSteamMenu, onQam, extras, tabs)
return when (mode) {
SecondScreenMode.KEYBOARD_TRACKPAD -> model(listOf(BarExtra(
context.getString(if (keyboardShown.value) R.string.second_hide_keyboard else R.string.second_show_keyboard),
icon = R.drawable.ic_bottom_keyboard, active = keyboardShown.value, tag = "bottom-keyboard") { showKeyboard() }))
SecondScreenMode.DECK_CONTROLS -> model(swap, deckPanelTabs(context, deckPanel.value, ::selectDeckPanel))
SecondScreenMode.DASHBOARD -> model(swap)
SecondScreenMode.TERMINAL -> model(listOf(BarExtra(context.getString(R.string.drawer_keyboard), icon = R.drawable.ic_bottom_keyboard,
tag = "bottom-keyboard") { terminalPanel?.showKeyboard() }))
else -> null
}
}
private fun selectDeckPanel(panel: DeckPanel) {
if (deckPanel.value == panel) return
deckPanel.value = panel
onDeckPanel(panel)
refreshControls()
}
private fun renderDashboard() {
val content = dashboard ?: return
bar(SecondScreenMode.DASHBOARD) {
listOfNotNull(onSwap?.let { BarExtra(context.getString(R.string.swap_screens), icon = R.drawable.ic_bottom_swap, tag = "bottom-swap", onClick = it) })
}
bar(SecondScreenMode.DASHBOARD)
val view = androidx.compose.ui.platform.ComposeView(context).apply { setContent { content() } }
dashboardView = view
root.addView(view, weightParams())
@@ -337,11 +363,7 @@ class SecondScreenPresentation(
}
private fun renderTerminal() {
bar(SecondScreenMode.TERMINAL) {
listOf(BarExtra(context.getString(R.string.drawer_keyboard), icon = R.drawable.ic_bottom_keyboard, tag = "bottom-keyboard") {
terminalPanel?.showKeyboard()
})
}
bar(SecondScreenMode.TERMINAL)
val panel = SessionTerminalPanel(context)
terminalPanel = panel
root.addView(panel, weightParams())
@@ -316,6 +316,8 @@ class DrawerActions(
val unfoldedControls: Boolean? = null,
val adaptiveSticks: Boolean? = null,
val onAdaptiveSticks: (Boolean) -> Unit = {},
val quickButtons: Map<com.droiddeck.launcher.input.InputCommand, Boolean> = emptyMap(),
val onQuickButton: (com.droiddeck.launcher.input.InputCommand, Boolean) -> Unit = { _, _ -> },
val onUnfoldedControls: (Boolean) -> Unit = {},
val unfoldedControlsWithController: Boolean = false,
val onUnfoldedControlsWithController: (Boolean) -> Unit = {},
@@ -642,6 +644,11 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
ToggleRow(host, "adaptive-sticks", stringResource(R.string.ctrl_adaptive), null, on,
chipModifier = focus.track(page, "adaptive-sticks"), onChange = a.onAdaptiveSticks)
}
for ((button, shown) in a.quickButtons) {
val key = "quick-${button.name.lowercase()}"
ToggleRow(host, key, stringResource(quickButtonLabel(button)), null, shown,
chipModifier = focus.track(page, key)) { a.onQuickButton(button, it) }
}
a.onEditSteamTouch?.let { edit ->
ActionRow(stringResource(R.string.osc_steam_layout), stringResource(R.string.osc_steam_layout_hint), stringResource(R.string.ctrl_edit), edit)
}