mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-21 05:46:03 +00:00
Unify controller and screen input profiles for game and desktop sessions (#1439)
## Problem and intent Desktop sessions need configurable mouse, keyboard and application actions from a controller. On dual-screen devices, a lower-screen trackpad may already handle the pointer, leaving the physical controls available for other assignments. This PR gives physical controllers and local touch controls a shared profile/action model instead of separate configuration paths. This follows the centralization direction discussed in [#1202](https://github.com/Droid-Deck/DroidDeck/pull/1202#issuecomment-6299647180) and addresses the controller-input portion of #860 and #1356. Those discussions are context, **not prior maintainer approval** of this implementation. I would appreciate architectural feedback and guidance on splitting or coordinating this work if that would make review easier. ## Profiles and configuration - Controller stays within the existing Setup tabs. Game and Desktop each have a default-profile selector, followed by one profile list and device settings. - Named profiles reference three independently reusable parts: Physical controller, Main screen and Second screen. Layout geometry and action bindings are stored separately. Profiles can share physical controls while assigning different touch actions. - The session menu selects a complete profile, or expands to mix the three parts. A mixed selection can be saved as a new profile; Game and Desktop retain separate selections. - Both screens use the same full-size editor, with add, move, resize, snapping, undo and shared properties. The main-screen editor has movable, collapsible tools and is transparent above a running session. When editing the secondary display, its entire area is the canvas and the main display hosts tools/properties. - The old fixed gamepad, fixed Deck controls and separate Screen keys editor are replaced with editable presets and the shared renderer. Existing positions, bindings, shapes, symbols, imported images and toggle behavior migrate; legacy Screen keys become additional profiles without replacing the user's selected profile. Migration retains a backup before removing old preferences. - Saved layouts have thumbnails and screen targeting. Actions include compatible native output/remapping, keys/combinations, mouse buttons, pointer movement, vertical/horizontal scrolling, directional keys, existing menu/keyboard commands, and disabled. Buttons can use symbols, shapes and toggle behavior. ## Architecture and latency ```mermaid flowchart LR Library[Profiles + reusable layouts and bindings] --> Router[InputRouter] Physical[Physical controller adapters] --> Router Touch[Main + secondary InputSurfaceView] --> Sources[Owned pad / Deck sources] Sources --> Router BLE[Steam Controller BLE adapter] --> Router Router --> Native[Existing controller publication] Native --> Steam[Steam Input / guest controller] Router --> Held[Shared key and mouse ownership] Held --> Guest[Existing guest input outputs] Router --> UI[Existing menu / keyboard hosts] ``` Bindings resolve when the profile changes, outside event dispatch. Native forwarding has no additional frame/timer queue; identity routes reuse existing state/reports. Only synthesized continuous stick pointer/scroll motion uses a frame callback. One source releasing a key/button does not release another source's hold. Menu, profile, suspension and removal transitions release old outputs and gate held controls until neutral. Steam continues to own game-specific mappings and action sets. Steam Mobile Touch and VR retain their specialized paths. Raw device adapters remain responsible for transport/calibration and must join routing before publishing consumed controls; this does not claim that every adapter has been unified. Historical Thor measurements on the native Game path found kernel-event-to-guest-observer upper-bound medians of **3.061 ms baseline versus 2.999–3.403 ms candidate**, with a subsequent installed-APK check at **3.039 ms / 300 matched edges**. These are relative software-path measurements, not button-to-photon latency. Some tails increased, simultaneous BLE contention remains unmeasured, and **this UI revision has not had a new latency measurement**. The previous cursor fix changed visual update intervals from roughly 33.3 ms to 16.7 ms without changing sensitivity or adding smoothing. [Full design, migration and boundaries](https://github.com/Delete228/DroidDeck/blob/codex/unified-controller-input/docs/development/unified-input-proposal.md). ## Validation Updated through upstream 542bbf89c; current PR head08526f828. The latest CodeRabbit review generated no actionable comments. - **1,017 tests passed in 133 suites after the latest upstream merge**, with no failures, errors or skips: all input/UI tests, global reset, component updates, PiP policy, runtime auto-update and Proton menu auto-selection. The pre-merge review-fix run passed **967 input/UI/global-reset tests**. The subsequent second-screen refresh fix passed **35 focused surface/presentation tests**, including three new state-preservation regressions. - Full local run before the final review follow-ups: **3,598 tests, 3,573 passed, 25 failed**. The 25 are unchanged upstream macOS limitations: log-export tests requiring SecureDirectoryStream (24) and a case-sensitive WoW add-on test (1). The global-reset regression also passes. Earlier disk-exhausted attempts were discarded; the completed run bounded temporary resources with one worker and JVM recycling, without excluding tests or changing repository test configuration. - APK build, runtime/session assets, native dependencies, alignment and v1/v2/v3 signatures passed. Installed over the separate Input Test app on **AYN Thor** with its environment retained. Local packaging omits Rust store engines; the [full Build APK workflow for08526f828passed](https://github.com/Droid-Deck/DroidDeck/actions/runs/42295403480), including Android/JVM, Python/native, Rust store-engine and Xbox checks. - Review follow-ups keep migration IDs stable, preserve unreadable supported-version libraries before recovery, retain forward-version protection, release keyboard owners on focus loss, handle unavailable presentation displays, and allow controller confirmation/cancellation after key capture. Deck router cleanup checks ownership; BLE teardown synchronously blocks late routing/publication, and shared Triton slot ownership protects a replacement controller from stale instances. Legacy Select-to-Steam migrates to Desktop without replacing saved bindings; mouse backend transitions are serialized with publication. Profile refresh now updates custom controls in place, preserving terminal/dashboard state, the field keyboard and WoW chat. No physical BLE-controller test or new latency measurement was performed. - The latest08526f828APK is installed on Thor. Profile preferences stayed byte-for-byte identical and the retained Steam environment reached READY at 1280×720 / 60 Hz. The earlier capture-dialog fix was also exercised on Thor. APK SHA-256: `ed6ef888648468b4ebeb94e8f1ae74a195bb1f0a3f27e4fb3646d5462a4beb6b`. - Upstream integration preserves the new WoW chat panel, platform-pointer and PiP fixes. The fast-double-tap stick-click rule and its six regressions were adapted to the shared renderer; WoW field selection also preserves Ctrl held by a profile. - Latest Thor UI pass: existing Setup navigation, profile/layout previews, action persistence, centered element creation, main-screen editing over Steam, secondary canvas with primary tools/properties, and X returning from the docked menu to controls. - Across the documented device sessions, the user tested native physical buttons/sticks/triggers, Deck pads/grips, desktop pointer/clicks/scrolling/arrows, Android keyboard with physical input, Ctrl+F and Ctrl+A/X/V/S, simultaneous physical/touch holds, menu release and Home/resume. These historical checks are distinguished from the latest UI-only pass. [Revision-specific results, APK hashes and limitations](https://github.com/Delete228/DroidDeck/blob/codex/unified-controller-input/docs/development/unified-input-validation.md). ## Coordination and remaining work - #1202 (jmarti326): shortcut capture/device identity and the shared-assignment discussion informed this work. - #1305 (kingokksa): shared PC-key definitions were adapted from that PR; this does not absorb its entire feature set. - #1414, #581, #1226 and #1150 remain relevant for external-device input, calibration, keyboard routing and DualSense integration. The DualSense coordination discussion in this PR describes adapter boundaries and duplicate-stream suppression. Import/export, automatic per-app selection, macros, multi-button activation chords and automatic text-field keyboard detection remain out of scope. A single binding emitting a key combination is implemented. The configuration UI is now implemented and exercised on Thor. I am happy to continue UX/accessibility/localization refinements here before merge, or in follow-up PRs, according to maintainer feedback. The main review questions remain the shared model, source ownership/lifecycle contract, migration policy and integration with other input work. ## UI walkthrough on AYN Thor Actual captures from the installed Input Test build. In paired images, the main display is above the second display. The test application name and local build badge are not production branding changes. <details> <summary>Controller settings: separate defaults for Desktop and Game, followed by the profile library.</summary> <img width="960" alt="Controller settings: separate defaults for Desktop and Game, followed by the profile library." src="https://github.com/user-attachments/assets/a4c156d6-9ded-43df-b0f8-e5f34028806d" /> </details> <details> <summary>Physical controller: bindings grouped by control type, with each current action visible.</summary> <img width="960" alt="Physical controller: bindings grouped by control type, with each current action visible." src="https://github.com/user-attachments/assets/a8a840e3-19ac-473f-9f55-b06ae9c637b5" /> </details> <details> <summary>Reusable layouts: bounded previews and separate screen targets.</summary> <img width="960" alt="Reusable layouts: bounded previews and separate screen targets." src="https://github.com/user-attachments/assets/cf0cf7d1-42f3-46cd-b50b-f01e1fa8ed41" /> </details> <details> <summary>Main-screen editor over the live Steam UI, with the movable tools expanded. The background is Steam artwork, not a running game.</summary> <img width="960" alt="Main-screen editor over the live Steam UI, with the movable tools expanded. The background is Steam artwork, not a running game." src="https://github.com/user-attachments/assets/0781f7c8-fd10-47e5-8a23-817f945a6289" /> </details> <details> <summary>Dual-screen editor: tools and selection on the main display, full-size placement canvas on the second display.</summary> <img width="720" alt="Dual-screen editor: tools and selection on the main display, full-size placement canvas on the second display." src="https://github.com/user-attachments/assets/f13d4ef6-be6d-4d95-9d42-e047e0a63b8a" /> </details> <details> <summary>The selected lower-screen trackpad stays visible while its properties open on the main display.</summary> <img width="720" alt="The selected lower-screen trackpad stays visible while its properties open on the main display." src="https://github.com/user-attachments/assets/26baf597-f037-419e-9601-e48f086c0d4f" /> </details> <details> <summary>Session menu: expand Profile to select the physical, main-screen and second-screen parts independently.</summary> <img width="720" alt="Session menu: expand Profile to select the physical, main-screen and second-screen parts independently." src="https://github.com/user-attachments/assets/27ac4d9c-68b3-4257-8353-23104e2343de" /> </details>
This commit is contained in:
98 files changed
+10181
-4879
No files matched your search
@@ -1,111 +1,20 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import com.droiddeck.launcher.R
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.layout.ColumnScope
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import com.droiddeck.launcher.input.ControllerPrefs
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
|
||||
class ControllerActions(
|
||||
val onOsc: (String) -> Unit,
|
||||
val onTint: (Int) -> Unit,
|
||||
val onOpacity: (Int) -> Unit,
|
||||
val onSize: (Int) -> Unit,
|
||||
val onStickClick: (Boolean) -> Unit,
|
||||
val onAdaptiveSticks: (Boolean) -> Unit,
|
||||
val onRumble: (Boolean) -> Unit,
|
||||
val onDeadZone: (Int) -> Unit,
|
||||
val onSteamButton: (Boolean) -> Unit,
|
||||
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,
|
||||
val onResetAll: () -> Unit,
|
||||
)
|
||||
class ControllerActions(val onMapping: () -> Unit)
|
||||
|
||||
@Composable
|
||||
private fun Swatch(color: Int) {
|
||||
Box(Modifier.size(14.dp).background(Color(color), CircleShape).border(1.dp, Color.White.copy(alpha = 0.35f), CircleShape))
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun ColumnScope.ControllerRows(host: MenuHost, oscMode: String, c: ControllerPrefs.Settings, a: ControllerActions) {
|
||||
ChoiceRow(
|
||||
host, "controller-osc", stringResource(R.string.mode_osc), stringResource(R.string.ctrl_osc_hint),
|
||||
listOf(SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto), SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always), SessionPrefs.OSC_STEAM_TOUCH to stringResource(R.string.osc_steam_touch), SessionPrefs.OSC_STEAM_QAM to stringResource(R.string.mode_osc_qam), SessionPrefs.OSC_NEVER to stringResource(R.string.common_never)),
|
||||
oscMode, note = stringResource(R.string.mode_osc_note), onPick = a.onOsc,
|
||||
)
|
||||
val tintOpen = host.open == "controller-tint"
|
||||
SettingsRow(stringResource(R.string.ctrl_color), stringResource(R.string.ctrl_color_hint), highlighted = tintOpen) {
|
||||
Box {
|
||||
ValueChip(ControllerPrefs.tints.firstOrNull { it.first == c.tint }?.second?.let { stringResource(it) } ?: stringResource(R.string.ctrl_custom), tintOpen) {
|
||||
host.open = if (tintOpen) null else "controller-tint"
|
||||
}
|
||||
AnchoredMenu(tintOpen, onDismiss = { if (host.open == "controller-tint") host.open = null }, title = stringResource(R.string.ctrl_color)) { firstItemFocus ->
|
||||
ControllerPrefs.tints.forEachIndexed { index, (color, name) ->
|
||||
MenuItem(stringResource(name), checked = c.tint == color, leading = { Swatch(color) }, focusRequester = if (index == 0) firstItemFocus else null) {
|
||||
a.onTint(color)
|
||||
host.open = null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ChoiceRow(host, "controller-opacity", stringResource(R.string.ctrl_opacity), null, ControllerPrefs.opacities.map { it to stringResource(R.string.ctrl_percent, it) }, c.opacity, onPick = a.onOpacity)
|
||||
ChoiceRow(host, "controller-size", stringResource(R.string.ctrl_size), stringResource(R.string.ctrl_size_hint), ControllerPrefs.sizes.map { it to stringResource(R.string.ctrl_percent, it) }, c.size, onPick = a.onSize)
|
||||
ToggleRow(host, "controller-stick-click", stringResource(R.string.ctrl_stick_click), stringResource(R.string.ctrl_stick_click_hint), c.stickClick, onChange = a.onStickClick)
|
||||
ToggleRow(host, "controller-adaptive", stringResource(R.string.ctrl_adaptive), stringResource(R.string.ctrl_adaptive_hint), c.adaptiveSticks, onChange = a.onAdaptiveSticks)
|
||||
ToggleRow(host, "controller-rumble", stringResource(R.string.ctrl_rumble), null, c.rumble, onChange = a.onRumble)
|
||||
ChoiceRow(host, "controller-dead-zone", stringResource(R.string.ctrl_dead_zone), null, ControllerPrefs.deadZones.map { it to stringResource(R.string.ctrl_percent, it) }, c.deadZone, onPick = a.onDeadZone)
|
||||
ToggleRow(host, "controller-steam", stringResource(R.string.ctrl_steam_button), null, c.steamButton, onChange = a.onSteamButton)
|
||||
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() }
|
||||
SecondaryButton(stringResource(R.string.ctrl_reset), enabled = c.customLayout) { a.onResetLayout() }
|
||||
}
|
||||
}
|
||||
val remapped = c.mapping.count { (id, target) -> id != target }
|
||||
ActionRow(stringResource(R.string.ctrl_mapping), if (remapped == 0) stringResource(R.string.ctrl_mapping_default) else stringResource(R.string.ctrl_mapping_count, remapped, c.mapping.size), stringResource(R.string.ctrl_configure), a.onMapping)
|
||||
ActionRow(stringResource(R.string.ctrl_reset_all), stringResource(R.string.ctrl_reset_all_hint), stringResource(R.string.ctrl_reset), a.onResetAll)
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun ControllerMappingPage(mapping: Map<String, String>, onPick: (String, String) -> Unit, onReset: () -> Unit, onBack: () -> Unit) {
|
||||
val host = rememberMenuHost()
|
||||
SettingsPage(
|
||||
host, title = stringResource(R.string.ctrl_mapping), eyebrow = stringResource(R.string.setup_controller),
|
||||
lede = stringResource(R.string.ctrl_mapping_lede),
|
||||
onBack = onBack,
|
||||
) {
|
||||
SettingsGroup(stringResource(R.string.shortcuts_title)) {
|
||||
PhysicalShortcutRows()
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.ctrl_onscreen_buttons)) {
|
||||
val targets = ControllerPrefs.targets.map { (id, label) -> id to stringResource(label) }
|
||||
for ((id, name) in ControllerPrefs.mappable) {
|
||||
ChoiceRow(host, "map-$id", stringResource(name), null, targets, mapping[id] ?: id) { onPick(id, it) }
|
||||
}
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.ctrl_defaults)) {
|
||||
ActionRow(stringResource(R.string.ctrl_reset_mapping), stringResource(R.string.ctrl_mapping_default), stringResource(R.string.ctrl_reset), onReset)
|
||||
}
|
||||
internal fun rememberControllerSettings(): ControllerPrefs.Settings {
|
||||
val context = LocalContext.current
|
||||
var settings by remember { mutableStateOf(ControllerPrefs.read(context)) }
|
||||
DisposableEffect(context) {
|
||||
val prefs = ControllerPrefs.prefs(context)
|
||||
val listener = android.content.SharedPreferences.OnSharedPreferenceChangeListener { _, _ -> settings = ControllerPrefs.read(context) }
|
||||
prefs.registerOnSharedPreferenceChangeListener(listener)
|
||||
onDispose { prefs.unregisterOnSharedPreferenceChangeListener(listener) }
|
||||
}
|
||||
return settings
|
||||
}
|
||||
@@ -1,720 +0,0 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import com.droiddeck.launcher.R
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Color
|
||||
import android.graphics.Paint
|
||||
import android.graphics.RadialGradient
|
||||
import android.graphics.RectF
|
||||
import android.graphics.Shader
|
||||
import android.graphics.Typeface
|
||||
import android.graphics.drawable.GradientDrawable
|
||||
import android.view.Gravity
|
||||
import android.view.HapticFeedbackConstants
|
||||
import android.view.MotionEvent
|
||||
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.DeckControls
|
||||
import com.droiddeck.launcher.input.PadBridge
|
||||
import com.droiddeck.launcher.input.PadState
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import kotlin.math.atan2
|
||||
import kotlin.math.hypot
|
||||
import kotlin.math.min
|
||||
|
||||
@SuppressLint("ViewConstructor")
|
||||
class DeckControlsPanel(
|
||||
context: Context,
|
||||
private val onClose: () -> Unit,
|
||||
private val onSteamMenu: () -> Unit,
|
||||
private val onQam: () -> Unit,
|
||||
private val pad: PadBridge? = null,
|
||||
private val portraitDock: Boolean = false,
|
||||
private val onMenu: (() -> Unit)? = null,
|
||||
private val onSwap: (() -> Unit)? = null,
|
||||
) : LinearLayout(context) {
|
||||
private enum class Tab(val label: Int) { GAMEPAD(R.string.deck_tab_gamepad), GRIPS(R.string.deck_tab_grips), LEFT(R.string.deck_tab_left), RIGHT(R.string.deck_tab_right), BOTH(R.string.deck_tab_both) }
|
||||
|
||||
private val content = FrameLayout(context)
|
||||
val deckControls = pad == null || SessionState.deckPad
|
||||
private val tabViews = HashMap<Tab, TextView>()
|
||||
private val topBar: View by lazy { tabsRow() }
|
||||
|
||||
init {
|
||||
orientation = VERTICAL
|
||||
setBackgroundColor(Color.BLACK)
|
||||
val title = context.getString(if (deckControls) R.string.second_mode_deck_controls else R.string.deck_tab_gamepad)
|
||||
val extras = listOfNotNull(onSwap?.let { BarExtra(context.getString(R.string.swap_screens), icon = R.drawable.ic_bottom_swap, onClick = it) })
|
||||
addView(bottomScreenBarView(context) { sessionBarModel(title, onClose, onMenu, onSteamMenu, onQam, extras) },
|
||||
LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT))
|
||||
addView(topBar, LayoutParams(LayoutParams.MATCH_PARENT, dp(52)))
|
||||
addView(content, LayoutParams(LayoutParams.MATCH_PARENT, 0, 1f))
|
||||
select(if (pad != null && !deckControls) Tab.GAMEPAD else if (pad != null) selectedWithPad else selected)
|
||||
}
|
||||
|
||||
override fun onDetachedFromWindow() {
|
||||
DeckControls.releaseAll()
|
||||
super.onDetachedFromWindow()
|
||||
}
|
||||
|
||||
private fun tabsRow(): View = LinearLayout(context).apply {
|
||||
orientation = HORIZONTAL
|
||||
gravity = Gravity.CENTER
|
||||
setPadding(dp(12), 0, dp(12), dp(8))
|
||||
val tabs = LinearLayout(context).apply {
|
||||
orientation = HORIZONTAL
|
||||
background = outline(CORNER_PILL, SURFACE)
|
||||
setPadding(dp(4), dp(4), dp(4), dp(4))
|
||||
for (tab in Tab.values()) {
|
||||
if (!deckControls && tab != Tab.GAMEPAD) continue
|
||||
if (tab == Tab.GAMEPAD && pad == null) continue
|
||||
val view = TextView(context).apply {
|
||||
text = context.getString(tab.label)
|
||||
textSize = 14f
|
||||
typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
|
||||
gravity = Gravity.CENTER
|
||||
isSingleLine = true
|
||||
setPadding(dp(14), 0, dp(14), 0)
|
||||
setOnClickListener { select(tab) }
|
||||
}
|
||||
tabViews[tab] = view
|
||||
addView(view, LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT))
|
||||
}
|
||||
}
|
||||
val centre = HorizontalScrollView(context).apply {
|
||||
isHorizontalScrollBarEnabled = false
|
||||
overScrollMode = View.OVER_SCROLL_NEVER
|
||||
addView(tabs, FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, dp(44)))
|
||||
}
|
||||
addView(centre, LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT))
|
||||
}
|
||||
|
||||
private fun select(tab: Tab) {
|
||||
if (pad != null) selectedWithPad = tab else selected = tab
|
||||
DeckControls.releaseAll()
|
||||
for ((each, view) in tabViews) {
|
||||
val on = each == tab
|
||||
view.background = if (on) filled(CORNER_PILL, ACCENT) else null
|
||||
view.setTextColor(if (on) ON_ACCENT else TEXT_DIM)
|
||||
}
|
||||
tabViews[tab]?.let { selectedView ->
|
||||
(selectedView.parent?.parent as? HorizontalScrollView)?.post {
|
||||
val left = selectedView.left
|
||||
val right = selectedView.right
|
||||
val scroll = selectedView.parent?.parent as? HorizontalScrollView ?: return@post
|
||||
when {
|
||||
left < scroll.scrollX -> scroll.smoothScrollTo(left, 0)
|
||||
right > scroll.scrollX + scroll.width -> scroll.smoothScrollTo(right - scroll.width, 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
content.removeAllViews()
|
||||
topBar.visibility = if (tab == Tab.GAMEPAD || tabViews.size < 2) View.GONE else View.VISIBLE
|
||||
content.addView(
|
||||
when (tab) {
|
||||
Tab.GRIPS -> gripsGrid()
|
||||
Tab.LEFT -> singlePad(right = false)
|
||||
Tab.RIGHT -> singlePad(right = true)
|
||||
Tab.BOTH -> bothPads()
|
||||
Tab.GAMEPAD -> gamepad(pad ?: return)
|
||||
},
|
||||
FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT),
|
||||
)
|
||||
}
|
||||
|
||||
private fun gripsGrid(): View = LinearLayout(context).apply {
|
||||
orientation = HORIZONTAL
|
||||
setPadding(dp(12), dp(6), dp(12), dp(12))
|
||||
fun column(upper: View, lower: View) = LinearLayout(context).apply {
|
||||
orientation = VERTICAL
|
||||
addView(upper, LayoutParams(LayoutParams.MATCH_PARENT, 0, 1f).apply { bottomMargin = dp(6) })
|
||||
addView(lower, LayoutParams(LayoutParams.MATCH_PARENT, 0, 1f).apply { topMargin = dp(6) })
|
||||
}
|
||||
addView(column(GripButton(context, "L4", context.getString(R.string.deck_left_upper), DeckControls.L4), GripButton(context, "L5", context.getString(R.string.deck_left_lower), DeckControls.L5)),
|
||||
LayoutParams(0, LayoutParams.MATCH_PARENT, 1f).apply { rightMargin = dp(6) })
|
||||
addView(column(GripButton(context, "R4", context.getString(R.string.deck_right_upper), DeckControls.R4), GripButton(context, "R5", context.getString(R.string.deck_right_lower), DeckControls.R5)),
|
||||
LayoutParams(0, LayoutParams.MATCH_PARENT, 1f).apply { leftMargin = dp(6) })
|
||||
}
|
||||
|
||||
private fun singlePad(right: Boolean): View = LinearLayout(context).apply {
|
||||
orientation = VERTICAL
|
||||
setPadding(dp(12), dp(6), dp(12), dp(12))
|
||||
addView(TrackpadView(context, right), LayoutParams(LayoutParams.MATCH_PARENT, 0, 1f).apply { bottomMargin = dp(12) })
|
||||
addView(ClickBar(context, right), LayoutParams(LayoutParams.MATCH_PARENT, dp(76)))
|
||||
}
|
||||
|
||||
private fun bothPads(): View = LinearLayout(context).apply {
|
||||
orientation = VERTICAL
|
||||
setPadding(dp(12), dp(6), dp(12), dp(12))
|
||||
val pads = LinearLayout(context).apply {
|
||||
orientation = HORIZONTAL
|
||||
addView(TrackpadView(context, right = false), LayoutParams(0, LayoutParams.MATCH_PARENT, 1f).apply { rightMargin = dp(6) })
|
||||
addView(TrackpadView(context, right = true), LayoutParams(0, LayoutParams.MATCH_PARENT, 1f).apply { leftMargin = dp(6) })
|
||||
}
|
||||
addView(pads, LayoutParams(LayoutParams.MATCH_PARENT, 0, 1f).apply { bottomMargin = dp(12) })
|
||||
val grips = LinearLayout(context).apply {
|
||||
orientation = HORIZONTAL
|
||||
val row = listOf("L4" to DeckControls.L4, "L5" to DeckControls.L5, "R5" to DeckControls.R5, "R4" to DeckControls.R4)
|
||||
row.forEachIndexed { index, (label, bit) ->
|
||||
addView(GripButton(context, label, null, bit), LayoutParams(0, LayoutParams.MATCH_PARENT, 1f).apply {
|
||||
if (index > 0) leftMargin = dp(6)
|
||||
if (index < row.size - 1) rightMargin = dp(6)
|
||||
})
|
||||
}
|
||||
}
|
||||
addView(grips, LayoutParams(LayoutParams.MATCH_PARENT, dp(84)))
|
||||
}
|
||||
|
||||
private fun gamepad(pad: PadBridge): View = GamepadLayout(context, portraitDock).apply {
|
||||
fun pill(label: String, write: (PadState, Boolean) -> Unit) = PadButton(context, pad, label, write)
|
||||
place(surfaceSlot(pad, right = false), GamepadGeometry.Slot.LEFT_MAIN)
|
||||
place(DirectionPad(context, pad), GamepadGeometry.Slot.LEFT_SECOND)
|
||||
place(surfaceSlot(pad, right = true), GamepadGeometry.Slot.RIGHT_MAIN)
|
||||
place(FaceButtons(context, pad), GamepadGeometry.Slot.RIGHT_SECOND)
|
||||
place(pill("LT") { st, d -> st.leftTrigger = if (d) 1f else 0f }, GamepadGeometry.Slot.LEFT_OUTER_SHOULDER)
|
||||
place(pill("LB") { st, d -> st.press(PadState.LB, d) }, GamepadGeometry.Slot.LEFT_INNER_SHOULDER)
|
||||
place(pill("RB") { st, d -> st.press(PadState.RB, d) }, GamepadGeometry.Slot.RIGHT_INNER_SHOULDER)
|
||||
place(pill("RT") { st, d -> st.rightTrigger = if (d) 1f else 0f }, GamepadGeometry.Slot.RIGHT_OUTER_SHOULDER)
|
||||
place(pill("VIEW") { st, d -> st.press(PadState.SELECT, d) }, GamepadGeometry.Slot.VIEW)
|
||||
place(pill("MENU") { st, d -> st.press(PadState.START, d) }, GamepadGeometry.Slot.MENU)
|
||||
if (deckControls) place(centreTap("\u25a6 " + context.getString(R.string.deck_panels), context.getString(R.string.deck_more_controls)) { select(Tab.BOTH) },
|
||||
GamepadGeometry.Slot.PANELS)
|
||||
if (portraitDock && deckControls) {
|
||||
place(GripButton(context, "L4", null, DeckControls.L4), GamepadGeometry.Slot.L4)
|
||||
place(GripButton(context, "L5", null, DeckControls.L5), GamepadGeometry.Slot.L5)
|
||||
place(GripButton(context, "R5", null, DeckControls.R5), GamepadGeometry.Slot.R5)
|
||||
place(GripButton(context, "R4", null, DeckControls.R4), GamepadGeometry.Slot.R4)
|
||||
}
|
||||
}
|
||||
|
||||
private fun centreTap(label: String, description: String, onClick: () -> Unit) = TextView(context).apply {
|
||||
text = label
|
||||
contentDescription = description
|
||||
textSize = 13f
|
||||
maxLines = 1
|
||||
setAutoSizeTextTypeUniformWithConfiguration(9, 13, 1, android.util.TypedValue.COMPLEX_UNIT_SP)
|
||||
typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
|
||||
letterSpacing = 0.08f
|
||||
gravity = Gravity.CENTER
|
||||
setTextColor(TEXT)
|
||||
background = outline(CORNER_PILL, SURFACE)
|
||||
setOnClickListener {
|
||||
performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
|
||||
onClick()
|
||||
}
|
||||
}
|
||||
|
||||
private fun surfaceSlot(pad: PadBridge, right: Boolean): View = FrameLayout(context).apply {
|
||||
if (!deckControls) {
|
||||
addView(StickView(context, pad, right),
|
||||
FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT))
|
||||
return@apply
|
||||
}
|
||||
val slot = this
|
||||
fun show() {
|
||||
slot.removeAllViews()
|
||||
val stick = SessionPrefs.gamepadSurface(context, right) == SessionPrefs.SURFACE_STICK
|
||||
slot.addView(if (stick) StickView(context, pad, right) else TrackpadView(context, right, captioned = false),
|
||||
FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT))
|
||||
val chip = TextView(context).apply {
|
||||
text = "\u21c4"
|
||||
contentDescription = context.getString(R.string.deck_surface_switch)
|
||||
textSize = 14f
|
||||
typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
|
||||
gravity = Gravity.CENTER
|
||||
setTextColor(TEXT_DIM)
|
||||
background = outline(CORNER_PILL, SURFACE)
|
||||
setOnClickListener {
|
||||
performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
|
||||
SessionPrefs.setGamepadSurface(context, right,
|
||||
if (stick) SessionPrefs.SURFACE_TRACKPAD else SessionPrefs.SURFACE_STICK)
|
||||
show()
|
||||
}
|
||||
}
|
||||
slot.addView(chip, FrameLayout.LayoutParams(dp(30), dp(30),
|
||||
(if (right) Gravity.START else Gravity.END) or Gravity.TOP).apply { setMargins(dp(6), dp(6), dp(6), dp(6)) })
|
||||
}
|
||||
show()
|
||||
}
|
||||
|
||||
fun takesTouchAt(x: Float, y: Float): Boolean = controlUnder(this, x, y)
|
||||
|
||||
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 FaceButtons ||
|
||||
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 outline(radius: Float, fill: Int) = outline(context, radius, fill)
|
||||
|
||||
private fun filled(radius: Float, fill: Int) = GradientDrawable().apply {
|
||||
cornerRadius = radius * resources.displayMetrics.density
|
||||
setColor(fill)
|
||||
}
|
||||
|
||||
private fun dp(value: Int): Int = dp(context, value)
|
||||
|
||||
|
||||
private abstract class Surface(context: Context) : View(context) {
|
||||
protected val density = resources.displayMetrics.density
|
||||
protected val rect = RectF()
|
||||
private val fill = Paint(Paint.ANTI_ALIAS_FLAG)
|
||||
private val stroke = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE }
|
||||
protected val labelPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
textAlign = Paint.Align.CENTER
|
||||
typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
|
||||
}
|
||||
protected val captionPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
textAlign = Paint.Align.CENTER
|
||||
color = TEXT_DIM
|
||||
}
|
||||
|
||||
protected fun drawSurface(canvas: Canvas, lit: Boolean) {
|
||||
val inset = density
|
||||
rect.set(inset, inset, width - inset, height - inset)
|
||||
val radius = CORNER * density
|
||||
fill.color = if (lit) ACCENT_WASH else SURFACE
|
||||
canvas.drawRoundRect(rect, radius, radius, fill)
|
||||
stroke.color = if (lit) ACCENT else LINE
|
||||
stroke.strokeWidth = (if (lit) 2f else 1f) * density
|
||||
canvas.drawRoundRect(rect, radius, radius, stroke)
|
||||
}
|
||||
}
|
||||
|
||||
private open class HoldButton(
|
||||
context: Context,
|
||||
private val label: String,
|
||||
private val caption: String?,
|
||||
private val onChange: (Boolean) -> Unit,
|
||||
) : Surface(context) {
|
||||
private var down = false
|
||||
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
drawSurface(canvas, down)
|
||||
val cx = width / 2f
|
||||
labelPaint.textSize = min(height * 0.3f, 30 * density)
|
||||
labelPaint.color = if (down) ACCENT else TEXT
|
||||
val labelY = height / 2f + labelPaint.textSize * (if (caption == null) 0.35f else 0.1f)
|
||||
canvas.drawText(label, cx, labelY, labelPaint)
|
||||
if (caption != null) {
|
||||
captionPaint.textSize = 12 * density
|
||||
canvas.drawText(caption, cx, labelY + 22 * density, captionPaint)
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("ClickableViewAccessibility")
|
||||
override fun onTouchEvent(event: MotionEvent): Boolean {
|
||||
when (event.actionMasked) {
|
||||
MotionEvent.ACTION_DOWN -> set(true)
|
||||
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> set(false)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
private fun set(pressed: Boolean) {
|
||||
if (down == pressed) return
|
||||
down = pressed
|
||||
if (pressed) performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
|
||||
onChange(pressed)
|
||||
invalidate()
|
||||
}
|
||||
}
|
||||
|
||||
private class GripButton(context: Context, label: String, caption: String?, bit: Int) :
|
||||
HoldButton(context, label, caption, { DeckControls.setGrip(bit, it) })
|
||||
|
||||
private class ClickBar(context: Context, right: Boolean) :
|
||||
HoldButton(context, context.getString(R.string.deck_click), if (right) context.getString(R.string.deck_right_trackpad) else context.getString(R.string.deck_left_trackpad), { DeckControls.setClick(right, it) })
|
||||
|
||||
private class TrackpadView(context: Context, private val right: Boolean, private val captioned: Boolean = true) : Surface(context) {
|
||||
private var touching = false
|
||||
private var clicked = false
|
||||
private var fingerX = 0f
|
||||
private var fingerY = 0f
|
||||
private val guide = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE; color = GUIDE }
|
||||
private val dot = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = ACCENT }
|
||||
private val glow = Paint(Paint.ANTI_ALIAS_FLAG)
|
||||
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
drawSurface(canvas, clicked)
|
||||
val cx = width / 2f
|
||||
val cy = height / 2f
|
||||
guide.strokeWidth = density
|
||||
val reach = min(width, height) / 2f - 24 * density
|
||||
canvas.drawCircle(cx, cy, reach, guide)
|
||||
canvas.drawCircle(cx, cy, reach / 2f, guide)
|
||||
canvas.drawLine(cx - reach, cy, cx + reach, cy, guide)
|
||||
canvas.drawLine(cx, cy - reach, cx, cy + reach, guide)
|
||||
captionPaint.textSize = 12 * density
|
||||
captionPaint.color = if (touching) ACCENT else TEXT_DIM
|
||||
if (captioned) canvas.drawText((if (right) context.getString(R.string.deck_right_trackpad) else context.getString(R.string.deck_left_trackpad)).uppercase(), cx, 28 * density, captionPaint)
|
||||
if (touching) {
|
||||
val radius = 56 * density
|
||||
glow.shader = RadialGradient(fingerX, fingerY, radius, ACCENT_GLOW, Color.TRANSPARENT, Shader.TileMode.CLAMP)
|
||||
canvas.drawCircle(fingerX, fingerY, radius, glow)
|
||||
canvas.drawCircle(fingerX, fingerY, (if (clicked) 16 else 12) * density, dot)
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("ClickableViewAccessibility")
|
||||
override fun onTouchEvent(event: MotionEvent): Boolean {
|
||||
when (event.actionMasked) {
|
||||
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_MOVE -> {
|
||||
touch(event.getX(0), event.getY(0))
|
||||
click(event.pointerCount > 1)
|
||||
}
|
||||
MotionEvent.ACTION_POINTER_DOWN -> click(true)
|
||||
MotionEvent.ACTION_POINTER_UP -> {
|
||||
val stays = if (event.actionIndex == 0) 1 else 0
|
||||
touch(event.getX(stays), event.getY(stays))
|
||||
click(event.pointerCount - 1 > 1)
|
||||
}
|
||||
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
|
||||
click(false)
|
||||
touching = false
|
||||
DeckControls.setPad(right, touching = false)
|
||||
invalidate()
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
private fun touch(x: Float, y: Float) {
|
||||
fingerX = x.coerceIn(0f, width.toFloat())
|
||||
fingerY = y.coerceIn(0f, height.toFloat())
|
||||
touching = true
|
||||
DeckControls.setPad(right, true, (fingerX - width / 2f) / (width / 2f), -(fingerY - height / 2f) / (height / 2f))
|
||||
invalidate()
|
||||
}
|
||||
|
||||
private fun click(down: Boolean) {
|
||||
if (clicked == down) return
|
||||
clicked = down
|
||||
if (down) performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
|
||||
DeckControls.setClick(right, down)
|
||||
invalidate()
|
||||
}
|
||||
}
|
||||
|
||||
private class PadButton(
|
||||
context: Context,
|
||||
private val pad: PadBridge,
|
||||
label: String,
|
||||
private val write: (PadState, Boolean) -> Unit,
|
||||
) : HoldButton(context, label, null, { down -> pad.applyTouch { write(it, down) } }) {
|
||||
override fun onDetachedFromWindow() {
|
||||
pad.applyTouch { write(it, false) }
|
||||
super.onDetachedFromWindow()
|
||||
}
|
||||
}
|
||||
|
||||
private class StickView(context: Context, private val pad: PadBridge, private val right: Boolean) : Surface(context) {
|
||||
private var touching = false
|
||||
private var clicking = false
|
||||
private var lastUp = 0L
|
||||
private var originX = 0f
|
||||
private var originY = 0f
|
||||
private var knobX = 0f
|
||||
private var knobY = 0f
|
||||
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
|
||||
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
drawSurface(canvas, clicking)
|
||||
val cx = if (touching) originX else width / 2f
|
||||
val cy = if (touching) originY else height / 2f
|
||||
ring.strokeWidth = 2 * density
|
||||
ring.color = if (touching) ACCENT else LINE
|
||||
canvas.drawCircle(cx, cy, reach(), ring)
|
||||
knob.color = if (touching) ACCENT else KNOB
|
||||
canvas.drawCircle(cx + knobX, cy + knobY, reach() * 0.45f, knob)
|
||||
}
|
||||
|
||||
@SuppressLint("ClickableViewAccessibility")
|
||||
override fun onTouchEvent(event: MotionEvent): Boolean {
|
||||
val r = reach().coerceAtLeast(1f)
|
||||
when (event.actionMasked) {
|
||||
MotionEvent.ACTION_DOWN -> {
|
||||
originX = event.x.coerceIn(r, (width - r).coerceAtLeast(r))
|
||||
originY = event.y.coerceIn(r, (height - r).coerceAtLeast(r))
|
||||
touching = true
|
||||
performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
|
||||
if (event.eventTime - lastUp < CLICK_MS) setClick(true)
|
||||
follow(event.x, event.y, r)
|
||||
}
|
||||
MotionEvent.ACTION_MOVE -> follow(event.getX(0), event.getY(0), r)
|
||||
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
|
||||
touching = false
|
||||
lastUp = event.eventTime
|
||||
setClick(false)
|
||||
move(0f, 0f, 1f)
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
private fun follow(x: Float, y: Float, r: Float) {
|
||||
var dx = x - originX
|
||||
var dy = y - originY
|
||||
val length = hypot(dx, dy)
|
||||
if (length > r) { dx *= r / length; dy *= r / length }
|
||||
move(dx, dy, r)
|
||||
}
|
||||
|
||||
private fun move(dx: Float, dy: Float, r: Float) {
|
||||
knobX = dx
|
||||
knobY = dy
|
||||
pad.applyTouch(if (right) PadBridge.RIGHT_STICK else PadBridge.LEFT_STICK) { s ->
|
||||
if (right) { s.rightX = dx / r; s.rightY = dy / r } else { s.leftX = dx / r; s.leftY = dy / r }
|
||||
}
|
||||
invalidate()
|
||||
}
|
||||
|
||||
private fun setClick(down: Boolean) {
|
||||
if (clicking == down) return
|
||||
clicking = down
|
||||
if (down) performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
|
||||
pad.applyTouch { s -> s.press(if (right) PadState.R3 else PadState.L3, down) }
|
||||
}
|
||||
|
||||
override fun onDetachedFromWindow() {
|
||||
setClick(false)
|
||||
if (knobX != 0f || knobY != 0f) move(0f, 0f, 1f)
|
||||
super.onDetachedFromWindow()
|
||||
}
|
||||
}
|
||||
|
||||
private class DirectionPad(context: Context, private val pad: PadBridge) : View(context) {
|
||||
private val density = resources.displayMetrics.density
|
||||
private var held = 0
|
||||
private val arm = Paint(Paint.ANTI_ALIAS_FLAG)
|
||||
private val rect = RectF()
|
||||
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
val size = min(width, height) * 0.86f
|
||||
val cx = width / 2f
|
||||
val cy = height / 2f
|
||||
val half = size / 2f
|
||||
val thick = size / 3f / 2f
|
||||
fun armRect(bit: Int, l: Float, t: Float, r: Float, b: Float) {
|
||||
arm.color = if (held and bit != 0) ACCENT else KNOB
|
||||
rect.set(l, t, r, b)
|
||||
canvas.drawRoundRect(rect, 8 * density, 8 * density, arm)
|
||||
}
|
||||
armRect(1, cx - thick, cy - half, cx + thick, cy - thick)
|
||||
armRect(4, cx - thick, cy + thick, cx + thick, cy + half)
|
||||
armRect(8, cx - half, cy - thick, cx - thick, cy + thick)
|
||||
armRect(2, cx + thick, cy - thick, cx + half, cy + thick)
|
||||
arm.color = KNOB
|
||||
canvas.drawRect(cx - thick, cy - thick, cx + thick, cy + thick, arm)
|
||||
}
|
||||
|
||||
@SuppressLint("ClickableViewAccessibility")
|
||||
override fun onTouchEvent(event: MotionEvent): Boolean {
|
||||
val bits = when (event.actionMasked) {
|
||||
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_MOVE -> {
|
||||
val dx = event.getX(0) - width / 2f
|
||||
val dy = event.getY(0) - height / 2f
|
||||
if (hypot(dx, dy) < min(width, height) * 0.08f) 0 else {
|
||||
val sector = ((Math.toDegrees(atan2(dy.toDouble(), dx.toDouble())) + 360 + 22.5) % 360 / 45).toInt()
|
||||
intArrayOf(2, 2 or 4, 4, 4 or 8, 8, 8 or 1, 1, 1 or 2)[sector]
|
||||
}
|
||||
}
|
||||
else -> 0
|
||||
}
|
||||
set(bits)
|
||||
return true
|
||||
}
|
||||
|
||||
private fun set(bits: Int) {
|
||||
if (bits == held) return
|
||||
if (bits and held.inv() != 0) performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
|
||||
held = bits
|
||||
pad.applyTouch { s ->
|
||||
s.up = bits and 1 != 0; s.right = bits and 2 != 0; s.down = bits and 4 != 0; s.left = bits and 8 != 0
|
||||
}
|
||||
invalidate()
|
||||
}
|
||||
|
||||
override fun onDetachedFromWindow() {
|
||||
set(0)
|
||||
super.onDetachedFromWindow()
|
||||
}
|
||||
}
|
||||
|
||||
private class FaceButtons(context: Context, private val pad: PadBridge) : View(context) {
|
||||
private val buttons = listOf(PadState.Y to "Y", PadState.B to "B", PadState.A to "A", PadState.X to "X")
|
||||
private var held = emptySet<Int>()
|
||||
private val fill = Paint(Paint.ANTI_ALIAS_FLAG)
|
||||
private val text = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
textAlign = Paint.Align.CENTER
|
||||
typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
|
||||
}
|
||||
|
||||
private fun layout(): Pair<List<Pair<Float, Float>>, Float> {
|
||||
val cx = width / 2f
|
||||
val cy = height / 2f
|
||||
val spread = min(width, height) * 0.30f
|
||||
val radius = min(width, height) * 0.16f
|
||||
return listOf(cx to cy - spread, cx + spread to cy, cx to cy + spread, cx - spread to cy) to radius
|
||||
}
|
||||
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
val (centres, radius) = layout()
|
||||
text.textSize = radius * 0.9f
|
||||
buttons.forEachIndexed { i, (button, label) ->
|
||||
val (x, y) = centres[i]
|
||||
val down = button in held
|
||||
fill.color = if (down) ACCENT else KNOB
|
||||
canvas.drawCircle(x, y, radius, fill)
|
||||
text.color = if (down) ON_ACCENT else TEXT
|
||||
canvas.drawText(label, x, y + text.textSize * 0.35f, text)
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("ClickableViewAccessibility")
|
||||
override fun onTouchEvent(event: MotionEvent): Boolean {
|
||||
val (centres, radius) = layout()
|
||||
val now = HashSet<Int>()
|
||||
val ending = event.actionMasked == MotionEvent.ACTION_UP || event.actionMasked == MotionEvent.ACTION_CANCEL
|
||||
if (!ending) for (p in 0 until event.pointerCount) {
|
||||
if (event.actionMasked == MotionEvent.ACTION_POINTER_UP && p == event.actionIndex) continue
|
||||
val x = event.getX(p)
|
||||
val y = event.getY(p)
|
||||
val nearest = centres.indices.minByOrNull { hypot(centres[it].first - x, centres[it].second - y) } ?: continue
|
||||
if (hypot(centres[nearest].first - x, centres[nearest].second - y) <= radius * 1.6f) now.add(buttons[nearest].first)
|
||||
}
|
||||
set(now)
|
||||
return true
|
||||
}
|
||||
|
||||
private fun set(now: Set<Int>) {
|
||||
if (now == held) return
|
||||
if ((now - held).isNotEmpty()) performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
|
||||
val before = held
|
||||
held = now
|
||||
pad.applyTouch { s -> for (b in before + now) s.press(b, b in now) }
|
||||
invalidate()
|
||||
}
|
||||
|
||||
override fun onDetachedFromWindow() {
|
||||
set(emptySet())
|
||||
super.onDetachedFromWindow()
|
||||
}
|
||||
}
|
||||
|
||||
private class GamepadLayout(context: Context, private val portraitDock: Boolean) : ViewGroup(context) {
|
||||
private val slots = LinkedHashMap<View, GamepadGeometry.Slot>()
|
||||
|
||||
fun place(view: View, slot: GamepadGeometry.Slot) {
|
||||
slots[view] = slot
|
||||
addView(view)
|
||||
}
|
||||
|
||||
private fun boxes(w: Int, h: Int) = GamepadGeometry.layout(w.toFloat(), h.toFloat(), resources.displayMetrics.density, portraitDock)
|
||||
|
||||
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
|
||||
val w = MeasureSpec.getSize(widthMeasureSpec)
|
||||
val h = MeasureSpec.getSize(heightMeasureSpec)
|
||||
setMeasuredDimension(w, h)
|
||||
val boxes = boxes(w, h)
|
||||
for ((view, slot) in slots) {
|
||||
val box = boxes[slot]
|
||||
view.visibility = if (box == null) View.GONE else View.VISIBLE
|
||||
if (box == null) continue
|
||||
view.measure(MeasureSpec.makeMeasureSpec(box.width.toInt().coerceAtLeast(1), MeasureSpec.EXACTLY),
|
||||
MeasureSpec.makeMeasureSpec(box.height.toInt().coerceAtLeast(1), MeasureSpec.EXACTLY))
|
||||
}
|
||||
}
|
||||
|
||||
override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
|
||||
val boxes = boxes(r - l, b - t)
|
||||
for ((view, slot) in slots) {
|
||||
val box = boxes[slot] ?: continue
|
||||
val left = box.left.toInt()
|
||||
val top = box.top.toInt()
|
||||
view.layout(left, top, left + box.width.toInt().coerceAtLeast(1), top + box.height.toInt().coerceAtLeast(1))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val CLICK_MS = 300L
|
||||
|
||||
private var selected = Tab.BOTH
|
||||
private var selectedWithPad = Tab.BOTH
|
||||
|
||||
private const val CORNER = 20f
|
||||
private const val CORNER_PILL = 22f
|
||||
private val ACCENT = Color.rgb(0x1A, 0x9F, 0xFF)
|
||||
private val ACCENT_WASH = Color.argb(0x2E, 0x1A, 0x9F, 0xFF)
|
||||
private val ACCENT_GLOW = Color.argb(0x66, 0x1A, 0x9F, 0xFF)
|
||||
private val ON_ACCENT = Color.rgb(0x03, 0x11, 0x1F)
|
||||
private val SURFACE = Color.rgb(0x0A, 0x0B, 0x0D)
|
||||
private val LINE = Color.rgb(0x26, 0x29, 0x2E)
|
||||
private val GUIDE = Color.rgb(0x16, 0x18, 0x1B)
|
||||
private val TEXT = Color.rgb(0xF2, 0xF4, 0xF7)
|
||||
private val TEXT_DIM = Color.rgb(0x7A, 0x80, 0x8A)
|
||||
private val KNOB = Color.rgb(0x2A, 0x2D, 0x33)
|
||||
|
||||
internal fun dp(context: Context, value: Int): Int = (value * context.resources.displayMetrics.density + 0.5f).toInt()
|
||||
|
||||
internal fun outline(context: Context, radius: Float, fill: Int) = GradientDrawable().apply {
|
||||
cornerRadius = radius * context.resources.displayMetrics.density
|
||||
setColor(fill)
|
||||
setStroke(dp(context, 1), LINE)
|
||||
}
|
||||
|
||||
internal fun roundButton(context: Context, label: String, description: String, onClick: () -> Unit, wide: Boolean = false) =
|
||||
TextView(context).apply {
|
||||
text = label
|
||||
contentDescription = description
|
||||
textSize = if (wide) 13f else 20f
|
||||
typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
|
||||
letterSpacing = if (wide) 0.08f else 0f
|
||||
gravity = Gravity.CENTER
|
||||
setTextColor(TEXT)
|
||||
background = outline(context, CORNER_PILL, SURFACE)
|
||||
setPadding(if (wide) dp(context, 16) else 0, 0, if (wide) dp(context, 16) else 0, 0)
|
||||
minWidth = dp(context, 44)
|
||||
layoutParams = LinearLayout.LayoutParams(if (wide) LinearLayout.LayoutParams.WRAP_CONTENT else dp(context, 44), dp(context, 44))
|
||||
setOnClickListener {
|
||||
performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
|
||||
onClick()
|
||||
}
|
||||
}
|
||||
|
||||
internal fun menuButton(context: Context, onClick: () -> Unit) =
|
||||
iconButton(context, R.drawable.ic_stat_session, context.getString(R.string.touch_droiddeck_menu), onClick)
|
||||
|
||||
internal fun iconButton(context: Context, icon: Int, description: String, onClick: () -> Unit) = android.widget.ImageView(context).apply {
|
||||
setImageResource(icon)
|
||||
setColorFilter(TEXT)
|
||||
contentDescription = description
|
||||
scaleType = android.widget.ImageView.ScaleType.CENTER_INSIDE
|
||||
val pad = dp(context, 11)
|
||||
setPadding(pad, pad, pad, pad)
|
||||
background = outline(context, CORNER_PILL, SURFACE)
|
||||
layoutParams = LinearLayout.LayoutParams(dp(context, 44), dp(context, 44))
|
||||
setOnClickListener {
|
||||
performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
|
||||
onClick()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -245,7 +245,7 @@ internal fun SetupPanel(
|
||||
PageHeader(stringResource(R.string.setup_title)) {
|
||||
Box(Modifier.weight(1f)) { SheetChips(tabs, tab, chipFocus, onPick = pick) }
|
||||
}
|
||||
Column(modifier = Modifier.weight(1f).fillMaxWidth().verticalScroll(rememberScrollState()).padding(bottom = 24.dp)) {
|
||||
Column(modifier = Modifier.weight(1f).fillMaxWidth().then(if (tab == 1) Modifier else Modifier.verticalScroll(rememberScrollState())).padding(bottom = if (tab == 1) 0.dp else 24.dp)) {
|
||||
when (tab) {
|
||||
0 -> {
|
||||
// Setup's "Safe mode" row, under the GPU row while the bridge is on and can be used here.
|
||||
@@ -413,9 +413,7 @@ internal fun SetupPanel(
|
||||
}
|
||||
1 -> {
|
||||
val controller = s.controller
|
||||
if (controller != null && a.controller != null) SettingsGroup(stringResource(R.string.setup_controller)) {
|
||||
ControllerRows(host, s.oscMode, controller, a.controller)
|
||||
}
|
||||
if (controller != null && a.controller != null) InputSettingsPage(onBack = { pick(0) }, embedded = true)
|
||||
if (s.controller == null || a.controller == null) Note(stringResource(R.string.setup_controller_unavailable))
|
||||
}
|
||||
2 -> {
|
||||
|
||||
@@ -1,129 +0,0 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import kotlin.math.min
|
||||
|
||||
object GamepadGeometry {
|
||||
enum class Slot {
|
||||
LEFT_MAIN, LEFT_SECOND, RIGHT_MAIN, RIGHT_SECOND,
|
||||
LEFT_OUTER_SHOULDER, LEFT_INNER_SHOULDER, RIGHT_INNER_SHOULDER, RIGHT_OUTER_SHOULDER,
|
||||
VIEW, STEAM, QAM, MENU,
|
||||
PANELS,
|
||||
L4, L5, R5, R4,
|
||||
}
|
||||
|
||||
data class Box(val cx: Float, val cy: Float, val width: Float, val height: Float) {
|
||||
val left get() = cx - width / 2f
|
||||
val top get() = cy - height / 2f
|
||||
val right get() = cx + width / 2f
|
||||
val bottom get() = cy + height / 2f
|
||||
|
||||
fun overlaps(other: Box): Boolean =
|
||||
left < other.right && other.left < right && top < other.bottom && other.top < bottom
|
||||
}
|
||||
|
||||
private val middle = listOf(Slot.VIEW, Slot.STEAM, Slot.QAM, Slot.MENU)
|
||||
private val twoByTwo = mapOf(Slot.VIEW to 0, Slot.MENU to 1, Slot.STEAM to 2, Slot.QAM to 3)
|
||||
|
||||
fun tall(w: Float, h: Float): Boolean = h >= w * 0.45f
|
||||
|
||||
fun layout(w: Float, h: Float, density: Float, portraitDock: Boolean = false): Map<Slot, Box> {
|
||||
if (w <= 0f || h <= 0f) return emptyMap()
|
||||
if (portraitDock && h >= w * 0.9f && w >= 300 * density && h >= 360 * density) {
|
||||
return portraitLayout(w, h, density)
|
||||
}
|
||||
val pad = 8 * density
|
||||
val buttonH = 40 * density
|
||||
val rowButton = 64 * density
|
||||
val gridButton = 48 * density
|
||||
val gutter = 8 * density
|
||||
val boxes = LinkedHashMap<Slot, Box>()
|
||||
fun mirror(x: Float, right: Boolean) = if (right) w - x else x
|
||||
fun pair(left: Slot, right: Slot, x: Float, cy: Float, bw: Float, bh: Float) {
|
||||
boxes[left] = Box(mirror(x, false), cy, bw, bh)
|
||||
boxes[right] = Box(mirror(x, true), cy, bw, bh)
|
||||
}
|
||||
fun middleGrid(columns: Int, span: Float, top: Float) {
|
||||
val each = (span / columns).coerceAtMost(110 * density)
|
||||
for ((order, slot) in middle.withIndex()) {
|
||||
val index = if (columns == 2) twoByTwo.getValue(slot) else order
|
||||
val x = w / 2f + (index % columns - (columns - 1) / 2f) * each
|
||||
boxes[slot] = Box(x, top + buttonH / 2f + (index / columns) * (buttonH + 10 * density), each - gutter, buttonH)
|
||||
}
|
||||
}
|
||||
if (!tall(w, h)) {
|
||||
val reach = min(h - pad, w * 0.33f)
|
||||
val main = reach * 0.66f
|
||||
val second = reach * 0.54f
|
||||
val mainTop = h - reach * 0.40f - main / 2f
|
||||
val shoulderW = reach * 0.36f
|
||||
val shoulderH = (reach * 0.16f).coerceAtLeast(buttonH)
|
||||
val shoulderY = min(h - reach * 0.94f + shoulderH / 2f, mainTop - gutter - shoulderH / 2f)
|
||||
.coerceAtLeast(pad + shoulderH / 2f)
|
||||
pair(Slot.LEFT_MAIN, Slot.RIGHT_MAIN, reach * 0.40f, h - reach * 0.40f, main, main)
|
||||
pair(Slot.LEFT_SECOND, Slot.RIGHT_SECOND, reach * 1.03f, h - reach * 0.30f, second, second)
|
||||
pair(Slot.LEFT_OUTER_SHOULDER, Slot.RIGHT_OUTER_SHOULDER, reach * 0.22f, shoulderY, shoulderW, shoulderH)
|
||||
pair(Slot.LEFT_INNER_SHOULDER, Slot.RIGHT_INNER_SHOULDER, reach * 0.62f, shoulderY, shoulderW, shoulderH)
|
||||
val gap = w - 2 * reach * 1.32f
|
||||
val columns = when {
|
||||
gap >= middle.size * rowButton -> middle.size
|
||||
gap >= 2 * gridButton -> 2
|
||||
else -> 1
|
||||
}
|
||||
middleGrid(columns, gap - 2 * gutter, shoulderY - buttonH / 2f)
|
||||
} else {
|
||||
val side = min(min(w * 0.5f, h * 0.70f), (w - 2 * gridButton - 2 * gutter) / 1.42f)
|
||||
val main = side * 0.62f
|
||||
val second = side * 0.46f
|
||||
val secondCy = h - side * 0.97f
|
||||
val shoulderW = side * 0.34f
|
||||
val shoulderH = (side * 0.13f).coerceAtLeast(buttonH)
|
||||
val shoulderY = (secondCy - second / 2f - gutter - shoulderH / 2f).coerceAtLeast(pad + shoulderH / 2f)
|
||||
pair(Slot.LEFT_MAIN, Slot.RIGHT_MAIN, side * 0.40f, h - side * 0.40f, main, main)
|
||||
pair(Slot.LEFT_SECOND, Slot.RIGHT_SECOND, side * 0.74f, secondCy, second, second)
|
||||
pair(Slot.LEFT_OUTER_SHOULDER, Slot.RIGHT_OUTER_SHOULDER, side * 0.20f, shoulderY, shoulderW, shoulderH)
|
||||
pair(Slot.LEFT_INNER_SHOULDER, Slot.RIGHT_INNER_SHOULDER, side * 0.57f, shoulderY, shoulderW, shoulderH)
|
||||
val gap = w - 2 * (side * 0.40f + main / 2f)
|
||||
val columns = if (gap >= 2 * gridButton) 2 else 1
|
||||
val rows = (middle.size + columns - 1) / columns
|
||||
middleGrid(columns, gap - 2 * gutter, h - pad - rows * buttonH - (rows - 1) * 10 * density)
|
||||
val panelsW = min(112 * density, w - 2 * (side * 0.57f + shoulderW / 2f) - 2 * gutter)
|
||||
if (panelsW >= buttonH) boxes[Slot.PANELS] = Box(w / 2f, shoulderY, panelsW, buttonH)
|
||||
}
|
||||
return boxes
|
||||
}
|
||||
|
||||
private fun portraitLayout(w: Float, h: Float, density: Float): Map<Slot, Box> {
|
||||
val pad = 8 * density
|
||||
val gap = 8 * density
|
||||
val buttonH = 44 * density
|
||||
val scale = min(1f, (h - 2 * pad - 4 * gap - 3 * buttonH) / (w * 0.7f))
|
||||
val main = w * 0.4f * scale
|
||||
val second = w * 0.3f * scale
|
||||
val mainY = h - pad - main / 2f
|
||||
val secondY = mainY - main / 2f - gap - second / 2f
|
||||
val shoulderY = secondY - second / 2f - gap - buttonH / 2f
|
||||
val boxes = linkedMapOf(
|
||||
Slot.LEFT_MAIN to Box(w * 0.25f, mainY, main, main),
|
||||
Slot.RIGHT_MAIN to Box(w * 0.75f, mainY, main, main),
|
||||
Slot.LEFT_SECOND to Box(w * 0.25f, secondY, second, second),
|
||||
Slot.RIGHT_SECOND to Box(w * 0.75f, secondY, second, second),
|
||||
)
|
||||
val utilityW = (w - 2 * pad - 3 * gap) / 4f
|
||||
for ((i, slot) in middle.withIndex()) {
|
||||
boxes[slot] = Box(pad + utilityW / 2f + i * (utilityW + gap), pad + buttonH / 2f, utilityW, buttonH)
|
||||
}
|
||||
val gripTop = pad + buttonH + gap
|
||||
val gripH = min(64 * density, shoulderY - buttonH / 2f - gap - gripTop)
|
||||
for ((i, slot) in listOf(Slot.L4, Slot.L5, Slot.R5, Slot.R4).withIndex()) {
|
||||
boxes[slot] = Box(pad + utilityW / 2f + i * (utilityW + gap), gripTop + gripH / 2f, utilityW, gripH)
|
||||
}
|
||||
val panelsW = min(112 * density, w * 0.22f)
|
||||
val shoulderW = (w - 2 * pad - 4 * gap - panelsW) / 4f
|
||||
boxes[Slot.PANELS] = Box(w / 2f, shoulderY, panelsW, buttonH)
|
||||
boxes[Slot.LEFT_OUTER_SHOULDER] = Box(pad + shoulderW / 2f, shoulderY, shoulderW, buttonH)
|
||||
boxes[Slot.LEFT_INNER_SHOULDER] = Box(pad + shoulderW * 1.5f + gap, shoulderY, shoulderW, buttonH)
|
||||
boxes[Slot.RIGHT_INNER_SHOULDER] = Box(w - pad - shoulderW * 1.5f - gap, shoulderY, shoulderW, buttonH)
|
||||
boxes[Slot.RIGHT_OUTER_SHOULDER] = Box(w - pad - shoulderW / 2f, shoulderY, shoulderW, buttonH)
|
||||
return boxes
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.input.*
|
||||
|
||||
@Composable
|
||||
internal fun InputActionEditor(
|
||||
control: InputControl, current: InputAction, title: String, onBack: () -> Unit, onSave: (InputAction) -> Unit,
|
||||
element: InputSurfaceElement? = null, nativeTargets: Boolean = true, detail: String? = null,
|
||||
properties: (@Composable ColumnScope.() -> Unit)? = null,
|
||||
click: Boolean = false,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val host = rememberMenuHost()
|
||||
var draft by remember(current, title) { mutableStateOf(current) }
|
||||
val drafts = remember(current, title) { mutableMapOf<String, InputAction>() }
|
||||
fun typeOf(action: InputAction): String = when (action) {
|
||||
is InputAction.Native -> "native"; InputAction.Disabled -> "disabled"
|
||||
is InputAction.MouseButton -> "mouse"; is InputAction.Command -> "command"
|
||||
is InputAction.Pointer -> "pointer"; is InputAction.Scroll -> "scroll"
|
||||
is InputAction.Directions -> "directions"; is InputAction.Keys -> "keys"
|
||||
}
|
||||
var localType by remember(current, title) { mutableStateOf(typeOf(current).takeUnless { it == "native" || it == "disabled" } ?: "keys") }
|
||||
fun switch(type: String, initial: () -> InputAction) {
|
||||
drafts[typeOf(draft)] = draft
|
||||
draft = drafts[type] ?: initial()
|
||||
if (type != "native" && type != "disabled") localType = type
|
||||
}
|
||||
var keys by remember { mutableStateOf(false) }
|
||||
var direction by remember { mutableStateOf<Int?>(null) }
|
||||
fun valid(action: InputAction) = if (click) action.validForClick() else if (element != null) action.validFor(element) else action.validFor(control)
|
||||
val nativeOptions = remember(control, element, nativeTargets, click) {
|
||||
(listOf(InputAction.Native()) + if (nativeTargets) InputControl.entries.map { InputAction.Native(it) } else emptyList()).filter(::valid)
|
||||
}
|
||||
val route = when (draft) { is InputAction.Native -> 0; InputAction.Disabled -> 2; else -> 1 }
|
||||
BackHandler(onBack = onBack)
|
||||
SettingsPage(host, title, onBack, eyebrow = stringResource(R.string.input_properties), lede = detail,
|
||||
action = { PrimaryButton(stringResource(R.string.gesture_save_changes), enabled = valid(draft),
|
||||
modifier = Modifier.testTag("input-action-save")) { onSave(draft) } }) {
|
||||
properties?.invoke(this)
|
||||
Spacer(Modifier.height(12.dp))
|
||||
SheetChips(listOf(stringResource(R.string.input_route_controller), stringResource(R.string.input_route_local), stringResource(R.string.input_disabled)), route) {
|
||||
when (it) {
|
||||
0 -> switch("native") { nativeOptions.firstOrNull() ?: InputAction.Disabled }
|
||||
2 -> switch("disabled") { InputAction.Disabled }
|
||||
else -> switch(localType) { InputAction.Keys(listOf(28)) }
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(16.dp))
|
||||
when (route) {
|
||||
0 -> SettingsGroup(stringResource(R.string.input_route_controller)) {
|
||||
ChoiceRow(host, "native-target", stringResource(R.string.input_remap_native), stringResource(R.string.input_controller_route_hint),
|
||||
nativeOptions.map { it to (it.target?.label ?: stringResource(if (nativeTargets) R.string.input_native else R.string.input_normal_binding)) },
|
||||
draft as InputAction.Native) { draft = it }
|
||||
}
|
||||
2 -> Text(stringResource(R.string.input_disabled_hint), Modifier.padding(16.dp))
|
||||
else -> {
|
||||
val types = listOf("keys" to stringResource(R.string.input_keys), "mouse" to stringResource(R.string.input_mouse_click),
|
||||
"command" to stringResource(R.string.input_command)) + if (control.dimensions == 2) listOf(
|
||||
"pointer" to stringResource(R.string.input_pointer), "scroll" to stringResource(R.string.input_scroll),
|
||||
"directions" to stringResource(R.string.input_direction_keys)) else emptyList()
|
||||
val type = when (draft) { is InputAction.MouseButton -> "mouse"; is InputAction.Command -> "command";
|
||||
is InputAction.Pointer -> "pointer"; is InputAction.Scroll -> "scroll"; is InputAction.Directions -> "directions"; else -> "keys" }
|
||||
SettingsGroup(stringResource(R.string.input_action)) {
|
||||
ChoiceRow(host, "action-type", stringResource(R.string.input_action), null, types, type) {
|
||||
switch(it) { when (it) { "mouse" -> InputAction.MouseButton(272); "command" -> InputAction.Command(InputCommand.MENU);
|
||||
"pointer" -> InputAction.Pointer(); "scroll" -> InputAction.Scroll();
|
||||
"directions" -> InputAction.Directions(103, 106, 108, 105); else -> InputAction.Keys(listOf(28)) } }
|
||||
}
|
||||
if (!click && draft !is InputAction.Pointer && draft !is InputAction.Scroll && draft !is InputAction.Directions) {
|
||||
val hint = when {
|
||||
control.isTrackpad -> R.string.input_contact_action_hint
|
||||
control.dimensions == 2 -> R.string.input_axis_action_hint
|
||||
control == InputControl.LT || control == InputControl.RT -> R.string.input_trigger_action_hint
|
||||
else -> null
|
||||
}
|
||||
hint?.let { Text(stringResource(it), Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) }
|
||||
}
|
||||
when (val action = draft) {
|
||||
is InputAction.Keys -> ActionRow(stringResource(R.string.input_keys), actionLabel(action), stringResource(R.string.ctrl_edit), { keys = true })
|
||||
is InputAction.MouseButton -> ChoiceRow(host, "mouse-button", stringResource(R.string.input_mouse_click), null,
|
||||
(272..274).map { it to actionLabel(InputAction.MouseButton(it)) }, action.code) { draft = InputAction.MouseButton(it) }
|
||||
is InputAction.Command -> ChoiceRow(host, "command", stringResource(R.string.input_command), null,
|
||||
InputCommand.entries.map { it to commandLabel(it) }, action.command) { draft = InputAction.Command(it) }
|
||||
is InputAction.Pointer -> {
|
||||
Text(stringResource(R.string.input_pointer_speed, action.speed.toInt()), Modifier.padding(horizontal = 16.dp, vertical = 8.dp), color = MaterialTheme.colorScheme.onSurface)
|
||||
Slider(action.speed, { draft = action.copy(speed = it) }, valueRange = 100f..3000f, modifier = Modifier.padding(horizontal = 16.dp))
|
||||
}
|
||||
is InputAction.Scroll -> {
|
||||
ChoiceRow(host, "scroll-axis", stringResource(R.string.input_scroll_axis), null,
|
||||
listOf(false to stringResource(R.string.input_vertical), true to stringResource(R.string.input_horizontal)), action.horizontal) {
|
||||
draft = action.copy(horizontal = it)
|
||||
}
|
||||
Text(stringResource(R.string.input_scroll_speed, action.speed.toInt()), Modifier.padding(horizontal = 16.dp, vertical = 8.dp), color = MaterialTheme.colorScheme.onSurface)
|
||||
Slider(action.speed, { draft = action.copy(speed = it) }, valueRange = 1f..60f, modifier = Modifier.padding(horizontal = 16.dp))
|
||||
}
|
||||
is InputAction.Directions -> {
|
||||
ToggleRow(host, "direction-diagonals", stringResource(R.string.input_diagonal_keys), stringResource(R.string.input_diagonal_keys_hint), action.diagonals != null) {
|
||||
draft = action.copy(diagonals = if (it) action.diagonals ?: listOf(0, 0, 0, 0) else null)
|
||||
}
|
||||
val codes = listOf(action.up, action.right, action.down, action.left) + action.diagonals.orEmpty()
|
||||
val arrows = listOf("↑", "→", "↓", "←", "↗", "↘", "↙", "↖")
|
||||
codes.forEachIndexed { i, code ->
|
||||
ActionRow(arrows[i], if (code == 0) stringResource(if (i < 4) R.string.input_disabled else R.string.input_diagonal_neighbors) else pcKeyLabel(context, code), stringResource(R.string.ctrl_edit), { direction = i })
|
||||
}
|
||||
}
|
||||
else -> Unit
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (keys) KeyCombinationPicker(onDismiss = { keys = false }, initial = (draft as? InputAction.Keys)?.codes.orEmpty(),
|
||||
sequence = true, sequenceLimit = 8, title = stringResource(R.string.input_keys), confirm = stringResource(R.string.gesture_save_changes), onAdd = {
|
||||
draft = InputAction.Keys(it.sortedBy { code -> if (code in PC_MODIFIERS) 0 else 1 }); keys = false
|
||||
})
|
||||
direction?.let { at ->
|
||||
val action = draft as? InputAction.Directions ?: return@let
|
||||
val codes = listOf(action.up, action.right, action.down, action.left) + action.diagonals.orEmpty()
|
||||
KeyCombinationPicker(onDismiss = { direction = null }, initial = listOf(codes[at]).filter { it != 0 }, sequence = true, sequenceLimit = 1, allowEmpty = true,
|
||||
title = stringResource(R.string.input_direction_keys), confirm = stringResource(R.string.gesture_save_changes), onAdd = {
|
||||
val next = codes.toMutableList().also { values -> values[at] = it.firstOrNull() ?: 0 }
|
||||
draft = InputAction.Directions(next[0], next[1], next[2], next[3], if (action.diagonals != null) next.drop(4) else null); direction = null
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.input.*
|
||||
|
||||
@Composable
|
||||
internal fun actionLabel(action: InputAction): String {
|
||||
val context = LocalContext.current
|
||||
return when (action) {
|
||||
is InputAction.Native -> action.target?.let { stringResource(R.string.input_native_target, it.label) } ?: stringResource(R.string.input_native)
|
||||
InputAction.Disabled -> stringResource(R.string.input_disabled)
|
||||
is InputAction.Keys -> action.codes.joinToString(" + ") { pcKeyLabel(context, it) }
|
||||
is InputAction.MouseButton -> stringResource(when (action.code) { 272 -> R.string.input_mouse_left; 273 -> R.string.input_mouse_right; else -> R.string.input_mouse_middle })
|
||||
is InputAction.Command -> commandLabel(action.command)
|
||||
is InputAction.Directions -> listOf(action.up, action.right, action.down, action.left).joinToString(" / ") { pcKeyLabel(context, it) }
|
||||
is InputAction.Pointer -> stringResource(R.string.input_pointer)
|
||||
is InputAction.Scroll -> stringResource(if (action.horizontal) R.string.input_scroll_horizontal else R.string.input_scroll_vertical)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun commandLabel(command: InputCommand) = stringResource(when (command) {
|
||||
InputCommand.MENU -> R.string.input_command_menu
|
||||
InputCommand.KEYBOARD -> R.string.input_command_keyboard
|
||||
InputCommand.STEAM -> R.string.input_command_steam
|
||||
InputCommand.QUICK_ACCESS -> R.string.input_command_qam
|
||||
})
|
||||
|
||||
@Composable
|
||||
internal fun InputCaptureDialog(onDismiss: () -> Unit, onPick: (PhysicalInputKey) -> Unit) {
|
||||
val confirmFocus = remember { FocusRequester() }
|
||||
var captured by remember { mutableStateOf<PhysicalInputKey?>(null) }
|
||||
var capturedDevice by remember { mutableIntStateOf(-1) }
|
||||
var ready by remember { mutableStateOf(false) }
|
||||
AlertDialog(onDismissRequest = onDismiss, title = { Text(stringResource(R.string.input_capture)) },
|
||||
properties = DialogProperties(dismissOnBackPress = ready),
|
||||
text = {
|
||||
CaptureShortcutKeys { event ->
|
||||
if (ready) {
|
||||
if (event.keyCode == android.view.KeyEvent.KEYCODE_BACK || event.keyCode == android.view.KeyEvent.KEYCODE_BUTTON_B) {
|
||||
if (event.action == android.view.KeyEvent.ACTION_DOWN && event.repeatCount == 0) onDismiss()
|
||||
true
|
||||
} else false
|
||||
} else {
|
||||
val key = PhysicalInputKey.capture(event)
|
||||
if (key == null) false else {
|
||||
if (captured == null && event.action == android.view.KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
|
||||
captured = key
|
||||
capturedDevice = event.deviceId
|
||||
} else if (captured == key && capturedDevice == event.deviceId && event.action == android.view.KeyEvent.ACTION_UP) ready = true
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
Column {
|
||||
Text(captured?.label ?: stringResource(R.string.input_capture_hint))
|
||||
if (captured != null) Text(stringResource(R.string.input_capture_confirm))
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(enabled = ready, modifier = Modifier.focusRequester(confirmFocus)
|
||||
.controllerConfirm(ready) { captured?.let(onPick) }, onClick = { captured?.let(onPick) }) { Text(stringResource(R.string.ctrl_edit)) }
|
||||
LaunchedEffect(ready) { if (ready) confirmFocus.requestFocus() }
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(modifier = Modifier.controllerConfirm { onDismiss() }, onClick = onDismiss) { Text(stringResource(R.string.gesture_cancel)) }
|
||||
if (ready) TextButton(modifier = Modifier.controllerConfirm { captured = null; ready = false },
|
||||
onClick = { captured = null; ready = false }) { Text(stringResource(R.string.input_capture_retry)) }
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.app.Presentation
|
||||
import android.graphics.Color
|
||||
import android.graphics.drawable.ColorDrawable
|
||||
import android.os.Bundle
|
||||
import android.view.Display
|
||||
import android.view.WindowManager
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.setViewTreeOnBackPressedDispatcherOwner
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.platform.ComposeView
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleEventObserver
|
||||
import androidx.lifecycle.setViewTreeLifecycleOwner
|
||||
import androidx.lifecycle.setViewTreeViewModelStoreOwner
|
||||
import androidx.savedstate.setViewTreeSavedStateRegistryOwner
|
||||
|
||||
internal val LocalInputActivity = staticCompositionLocalOf<ComponentActivity?> { null }
|
||||
|
||||
@Composable
|
||||
internal fun InputDisplayContent(host: ComponentActivity, display: Display, onDismiss: () -> Unit, content: @Composable () -> Unit) {
|
||||
val parent = rememberCompositionContext()
|
||||
val currentContent by rememberUpdatedState(content)
|
||||
val dismiss by rememberUpdatedState(onDismiss)
|
||||
DisposableEffect(host, display.displayId) {
|
||||
val presentation = object : Presentation(host, display) {
|
||||
var compose: ComposeView? = null
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
window?.apply {
|
||||
setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
|
||||
clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
|
||||
prepareInputEditor()
|
||||
decorView.setViewTreeLifecycleOwner(host)
|
||||
decorView.setViewTreeViewModelStoreOwner(host)
|
||||
decorView.setViewTreeSavedStateRegistryOwner(host)
|
||||
decorView.setViewTreeOnBackPressedDispatcherOwner(host)
|
||||
}
|
||||
// Presentation contexts cannot host TYPE_APPLICATION dialogs on Android 12+.
|
||||
compose = ComposeView(host).also {
|
||||
it.setParentCompositionContext(parent)
|
||||
it.setContent { CompositionLocalProvider(LocalInputActivity provides host) { currentContent() } }
|
||||
setContentView(it)
|
||||
}
|
||||
}
|
||||
override fun dismiss() { compose?.disposeComposition(); compose = null; super.dismiss() }
|
||||
}
|
||||
presentation.setOnCancelListener { dismiss() }
|
||||
fun showPresentation() {
|
||||
if (!display.isValid) { dismiss(); return }
|
||||
try {
|
||||
presentation.show()
|
||||
} catch (_: WindowManager.InvalidDisplayException) {
|
||||
presentation.dismiss()
|
||||
dismiss()
|
||||
}
|
||||
}
|
||||
showPresentation()
|
||||
val observer = LifecycleEventObserver { _, event ->
|
||||
if (event == Lifecycle.Event.ON_STOP) presentation.hide()
|
||||
if (event == Lifecycle.Event.ON_START) showPresentation()
|
||||
}
|
||||
host.lifecycle.addObserver(observer)
|
||||
onDispose { host.lifecycle.removeObserver(observer); presentation.dismiss() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
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 com.droiddeck.launcher.R
|
||||
|
||||
@Composable
|
||||
internal fun InputElementProperties(element: InputSurfaceElement, onChange: (InputSurfaceElement) -> Unit) {
|
||||
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
|
||||
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 }) },
|
||||
element.buttonShape) { onChange(element.copy(buttonShape = it)) }
|
||||
val open = host.open == "element-icon"
|
||||
SettingsRow(stringResource(R.string.input_button_symbol), null, highlighted = open) {
|
||||
Box {
|
||||
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 }
|
||||
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) }
|
||||
val paint = remember { android.graphics.Paint(android.graphics.Paint.ANTI_ALIAS_FLAG) }
|
||||
Canvas(Modifier.size(22.dp)) {
|
||||
paint.color = android.graphics.Color.argb((color.alpha * 255).toInt(), (color.red * 255).toInt(), (color.green * 255).toInt(), (color.blue * 255).toInt())
|
||||
InputButtonIcons.draw(drawContext.canvas.nativeCanvas, code, size.width / 2, size.height / 2, size.minDimension, paint, symbol)
|
||||
}
|
||||
}) { onChange(element.copy(icon = code, image = "")); host.open = null }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (element.kind == InputElementKind.TRACKPAD) {
|
||||
ToggleRow(rememberMenuHost(), "element-mouse-gestures", stringResource(R.string.input_mouse_gestures), stringResource(R.string.input_mouse_gestures_hint), element.mouseGestures) { onChange(element.copy(mouseGestures = it)) }
|
||||
}
|
||||
if (element.kind == InputElementKind.STICK) {
|
||||
val host = rememberMenuHost()
|
||||
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)) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Canvas
|
||||
import android.view.View
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.input.*
|
||||
|
||||
@Composable
|
||||
internal fun InputLayoutRow(layout: SavedInputLayout, role: InputRole, detail: String?, onManage: () -> Unit, onPick: () -> Unit) {
|
||||
Row(Modifier.fillMaxWidth().clickable(onClick = onPick).padding(12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
InputLayoutThumbnail(layout, role)
|
||||
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
Text(layout.name, style = MaterialTheme.typography.titleMedium)
|
||||
Text(detail ?: stringResource(R.string.input_layout_count, layout.elements.size),
|
||||
style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
TextButton(onClick = onManage, modifier = Modifier.testTag("layout-manage-${layout.id}")) { Text("⋮", style = MaterialTheme.typography.titleLarge) }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun InputLayoutThumbnail(layout: SavedInputLayout, role: InputRole) {
|
||||
AndroidView(factory = { InputLayoutPreviewView(it) }, modifier = Modifier.width(112.dp).height(76.dp).testTag("layout-preview-${layout.id}"),
|
||||
update = { it.update(layout, role) })
|
||||
}
|
||||
|
||||
internal class InputLayoutPreviewView(context: Context) : View(context) {
|
||||
private val renderer = InputSurfaceView(context)
|
||||
private var sourceHeight = 563
|
||||
fun update(layout: SavedInputLayout, role: InputRole) {
|
||||
sourceHeight = if (role == InputRole.PRIMARY) 563 else 870
|
||||
renderer.updateCustomLayout(layout.elements)
|
||||
renderer.updateStyle(layout.style.copy(opacity = 100))
|
||||
renderer.measure(MeasureSpec.makeMeasureSpec(1000, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(sourceHeight, MeasureSpec.EXACTLY))
|
||||
renderer.layout(0, 0, 1000, sourceHeight)
|
||||
contentDescription = layout.name
|
||||
invalidate()
|
||||
}
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
canvas.save()
|
||||
canvas.clipRect(0, 0, width, height)
|
||||
canvas.drawColor(android.graphics.Color.rgb(10, 11, 13))
|
||||
val scale = minOf(width / 1000f, height / sourceHeight.toFloat())
|
||||
canvas.translate((width - 1000 * scale) / 2, (height - sourceHeight * scale) / 2)
|
||||
canvas.scale(scale, scale)
|
||||
renderer.draw(canvas)
|
||||
canvas.restore()
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun InputColorRow(host: MenuHost, value: Int, onPick: (Int) -> Unit) {
|
||||
val open = host.open == "layout-color"
|
||||
SettingsRow(stringResource(R.string.ctrl_color), null, highlighted = open) {
|
||||
Box {
|
||||
ValueChip(ControllerPrefs.tints.firstOrNull { it.first == value }?.second?.let { stringResource(it) }
|
||||
?: stringResource(R.string.ctrl_custom), open, modifier = Modifier.testTag("setting-layout-color")) {
|
||||
host.open = if (open) null else "layout-color"
|
||||
}
|
||||
AnchoredMenu(open, onDismiss = { if (host.open == "layout-color") host.open = null }, title = stringResource(R.string.ctrl_color)) { firstItemFocus ->
|
||||
ControllerPrefs.tints.forEachIndexed { index, (color, name) ->
|
||||
MenuItem(stringResource(name), checked = value == color, leading = {
|
||||
Box(Modifier.size(14.dp).background(Color(color), CircleShape).border(1.dp, Color.White.copy(alpha = .35f), CircleShape))
|
||||
}, focusRequester = if (index == 0) firstItemFocus else null) {
|
||||
onPick(color)
|
||||
host.open = null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.content.Context
|
||||
import android.content.SharedPreferences
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.input.*
|
||||
|
||||
@Composable
|
||||
internal fun InputQuickSettings(host: MenuHost, desktop: Boolean, onChanged: (InputRole?) -> Unit = {}, onEdit: () -> Unit = {}, track: (String) -> Modifier = { Modifier }) {
|
||||
val context = LocalContext.current
|
||||
var library by remember { mutableStateOf(InputLibraries.read(context)) }
|
||||
var expanded by remember { mutableStateOf(false) }
|
||||
var naming by remember { mutableStateOf(false) }
|
||||
var failure by remember { mutableStateOf<String?>(null) }
|
||||
DisposableEffect(context) {
|
||||
val preferences = context.getSharedPreferences("input-profiles", Context.MODE_PRIVATE)
|
||||
val listener = SharedPreferences.OnSharedPreferenceChangeListener { _, key -> if (key == "library") library = InputLibraries.read(context) }
|
||||
preferences.registerOnSharedPreferenceChangeListener(listener)
|
||||
onDispose { preferences.unregisterOnSharedPreferenceChangeListener(listener) }
|
||||
}
|
||||
fun update(role: InputRole?, change: (InputLibrary) -> InputLibrary) {
|
||||
runCatching { InputLibraries.update(context, change) }.onSuccess { library = it; onChanged(role) }
|
||||
.onFailure { failure = it.message ?: context.getString(R.string.input_save_failed) }
|
||||
}
|
||||
val selection = library.selection(desktop)
|
||||
val mixed = selection.parts.isNotEmpty()
|
||||
val active = library.profile(library.activeId(desktop))
|
||||
val profiles = listOf(InputProfiles.AUTO to stringResource(R.string.input_quick_auto, if (desktop) library.profile(library.desktop).name else library.profile(library.steam).name)) +
|
||||
library.profiles.map { it.id to it.name } + if (mixed) listOf("mixed" to stringResource(R.string.input_quick_mixed, active.name)) else emptyList()
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Row(Modifier.weight(1f).clickable { expanded = !expanded }.padding(14.dp).testTag("input-profile-expand"),
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
Text(if (expanded) "▾" else "▸", color = MaterialTheme.colorScheme.onSurface)
|
||||
Text(stringResource(R.string.input_profile), style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.onSurface)
|
||||
}
|
||||
Box(Modifier.padding(end = 14.dp).widthIn(max = 280.dp)) {
|
||||
ChoiceChip(host, "input-profile", stringResource(R.string.input_profile), profiles, if (mixed) "mixed" else selection.profile,
|
||||
modifier = track("input-profile")) { id -> if (id != "mixed") update(null) { it.selectProfile(desktop, id) } }
|
||||
}
|
||||
}
|
||||
if (expanded) Surface(
|
||||
modifier = Modifier.fillMaxWidth().padding(start = 18.dp, end = 12.dp, bottom = 14.dp).testTag("input-profile-parts"),
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
color = MaterialTheme.colorScheme.primary.copy(alpha = .08f),
|
||||
border = BorderStroke(1.dp, MaterialTheme.colorScheme.primary.copy(alpha = .35f)),
|
||||
) {
|
||||
Column(Modifier.padding(vertical = 6.dp)) {
|
||||
for (role in InputRole.entries) {
|
||||
val options = library.bindings.filter { binding ->
|
||||
if (role == InputRole.PHYSICAL) binding.physical
|
||||
else !binding.physical && library.layouts.any { it.id == binding.layoutId && it.supports(role) }
|
||||
}.map { it.id to it.name }
|
||||
ChoiceRow(host, "input-part-${role.name}", roleLabel(role), null, options, library.activePart(desktop, role).bindings,
|
||||
chipModifier = track("input-part-${role.name}")) { id -> update(role) { it.selectPart(desktop, role, id) } }
|
||||
}
|
||||
if (mixed) SecondaryButton(stringResource(R.string.input_save_combination)) { naming = true }
|
||||
ActionRow(stringResource(R.string.input_settings), null, stringResource(R.string.ctrl_edit), onEdit,
|
||||
modifier = track("input-settings").testTag("input-profile-edit"))
|
||||
}
|
||||
}
|
||||
if (naming) {
|
||||
var name by remember { mutableStateOf("") }
|
||||
AlertDialog(onDismissRequest = { naming = false }, title = { Text(stringResource(R.string.input_save_combination)) },
|
||||
text = { OutlinedTextField(name, { name = it.take(80) }, singleLine = true, label = { Text(stringResource(R.string.input_name)) }) },
|
||||
confirmButton = { TextButton(enabled = name.isNotBlank(), onClick = { update(null) { it.saveSelection(desktop, name) }; naming = false }) { Text(stringResource(R.string.gesture_save_changes)) } },
|
||||
dismissButton = { TextButton(onClick = { naming = false }) { Text(stringResource(R.string.common_cancel)) } })
|
||||
}
|
||||
failure?.let { message -> AlertDialog(onDismissRequest = { failure = null }, title = { Text(stringResource(R.string.input_save_failed)) },
|
||||
text = { Text(message) }, confirmButton = { TextButton(onClick = { failure = null }) { Text(stringResource(R.string.common_ok)) } }) }
|
||||
}
|
||||
@@ -0,0 +1,411 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.input.*
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
|
||||
@Composable
|
||||
fun InputSettingsDialog(onBack: () -> Unit, onChanged: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val activity = context.findActivity() as? com.droiddeck.launcher.SessionActivity
|
||||
val target = activity?.inputEditorDisplay(InputRole.SECONDARY)
|
||||
if (activity != null && target != null && target.displayId != activity.window.decorView.display?.displayId) {
|
||||
InputDisplayContent(activity, target, onBack) { InputSettingsPane(onBack, onChanged) }
|
||||
} else InputSettingsWindow(onBack, onChanged)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun InputSettingsWindow(onBack: () -> Unit, onChanged: () -> Unit) {
|
||||
Dialog(onDismissRequest = onBack, properties = DialogProperties(usePlatformDefaultWidth = false)) {
|
||||
InputSettingsPane(onBack, onChanged)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun InputSettingsPane(onBack: () -> Unit, onChanged: () -> Unit) {
|
||||
var editingSurface by remember { mutableStateOf(false) }
|
||||
val window = (androidx.compose.ui.platform.LocalView.current.parent as? androidx.compose.ui.window.DialogWindowProvider)?.window
|
||||
DisposableEffect(window, editingSurface) {
|
||||
window?.setDimAmount(if (editingSurface) 0f else .32f)
|
||||
onDispose { }
|
||||
}
|
||||
BoxWithConstraints(Modifier.fillMaxSize().systemBarsPadding().padding(8.dp)) {
|
||||
CompositionLocalProvider(LocalNarrowPane provides (maxWidth < NarrowPaneWidth)) {
|
||||
Surface(Modifier.fillMaxSize(), color = if (editingSurface) androidx.compose.ui.graphics.Color.Transparent else MaterialTheme.colorScheme.surface) {
|
||||
InputSettingsPage(onBack, onChanged, onSurfaceEditing = { editingSurface = it })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private enum class InputPage { HOME, PROFILE, SOURCE, LAYOUTS, REUSE }
|
||||
private data class InputBindingEdit(val preset: String, val control: InputControl, val element: InputSurfaceElement? = null, val key: PhysicalInputKey? = null, val click: Boolean = false)
|
||||
private data class InputNameRequest(val title: Int, val initial: String, val sources: List<Pair<String, String>> = emptyList(),
|
||||
val source: String = "", val offerSharing: Boolean = false, val save: (String, String, Boolean) -> Unit)
|
||||
private data class InputConfirmation(val title: String, val detail: String, val action: () -> Unit)
|
||||
private data class InputReuseRequest(val name: String, val layoutOnly: Boolean, val apply: (Boolean) -> Unit)
|
||||
|
||||
@Composable
|
||||
fun InputSettingsPage(onBack: () -> Unit, onChanged: () -> Unit = {}, embedded: Boolean = false, onSurfaceEditing: (Boolean) -> Unit = {}) {
|
||||
CompositionLocalProvider(LocalContentColor provides MaterialTheme.colorScheme.onBackground) {
|
||||
InputSettingsContent(onBack, onChanged, embedded, onSurfaceEditing)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embedded: Boolean, onSurfaceEditing: (Boolean) -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val host = rememberMenuHost()
|
||||
var library by remember { mutableStateOf(InputLibraries.read(context)) }
|
||||
var page by remember { mutableStateOf(InputPage.HOME) }
|
||||
var bindingsTab by remember { mutableIntStateOf(0) }
|
||||
var profileId by remember { mutableStateOf(InputProfile.GAME) }
|
||||
var role by remember { mutableStateOf(InputRole.PHYSICAL) }
|
||||
var edit by remember { mutableStateOf<InputBindingEdit?>(null) }
|
||||
var naming by remember { mutableStateOf<InputNameRequest?>(null) }
|
||||
var confirmation by remember { mutableStateOf<InputConfirmation?>(null) }
|
||||
var reuse by remember { mutableStateOf<InputReuseRequest?>(null) }
|
||||
var capture by remember { mutableStateOf(false) }
|
||||
var surface by remember { mutableStateOf(false) }
|
||||
LaunchedEffect(surface) { onSurfaceEditing(surface) }
|
||||
DisposableEffect(Unit) { onDispose { onSurfaceEditing(false) } }
|
||||
var managingLayout by remember { mutableStateOf<SavedInputLayout?>(null) }
|
||||
var error by remember { mutableStateOf<String?>(null) }
|
||||
val controller = rememberControllerSettings()
|
||||
var oscMode by remember { mutableStateOf(SessionPrefs.oscMode(context)) }
|
||||
fun update(change: (InputLibrary) -> InputLibrary): Boolean = runCatching { InputLibraries.update(context, change) }
|
||||
.onSuccess { library = it; onChanged() }.onFailure { error = it.message ?: context.getString(R.string.input_save_failed) }.isSuccess
|
||||
fun go(next: InputPage) { page = next; host.open = null }
|
||||
fun back() {
|
||||
when {
|
||||
edit != null -> edit = null
|
||||
page == InputPage.HOME -> onBack()
|
||||
page == InputPage.PROFILE -> go(InputPage.HOME)
|
||||
page == InputPage.SOURCE -> go(InputPage.PROFILE)
|
||||
else -> go(InputPage.SOURCE)
|
||||
}
|
||||
}
|
||||
BackHandler(enabled = !embedded || page != InputPage.HOME || edit != null, onBack = ::back)
|
||||
val profile = library.profile(profileId)
|
||||
val preset = library.preset(profile.binding(role))
|
||||
val layout = library.layout(profileId, role)
|
||||
fun rename(title: Int, name: String, save: (String) -> Unit) {
|
||||
naming = InputNameRequest(title, name) { value, _, _ -> save(value) }
|
||||
}
|
||||
fun newProfile(copy: Boolean) {
|
||||
naming = InputNameRequest(if (copy) R.string.input_copy_profile else R.string.input_new_profile,
|
||||
if (copy) profile.name else "", library.profiles.map { it.id to it.name }, profileId, offerSharing = true) { name, source, shared ->
|
||||
val id = newInputId()
|
||||
if (update { it.duplicateProfile(source, name, id, sharePhysical = shared) }) { profileId = id; go(InputPage.PROFILE) }
|
||||
}
|
||||
}
|
||||
fun editPart(nextRole: InputRole) { role = nextRole; bindingsTab = 0; go(InputPage.SOURCE) }
|
||||
val editing = edit
|
||||
if (editing != null) {
|
||||
val b = library.preset(editing.preset)
|
||||
var elementProperties by remember(editing) { mutableStateOf(editing.element) }
|
||||
val current = editing.element?.let { if (editing.click) b.clickAction(it) else b.action(it) }
|
||||
?: editing.key?.let { k -> b.keys.firstOrNull { it.key == k }?.action ?: InputAction.Disabled }
|
||||
?: b.controls[editing.control] ?: InputAction.Native()
|
||||
InputActionEditor(editing.control, current, if (editing.click) stringResource(R.string.input_click_name, editing.element!!.name)
|
||||
else editing.element?.name ?: editing.key?.label ?: editing.control.label,
|
||||
properties = { if (!editing.click) elementProperties?.let { e -> InputElementProperties(e) { elementProperties = it } } },
|
||||
onBack = { edit = null }, element = editing.element, nativeTargets = editing.key == null, click = editing.click,
|
||||
detail = if (library.usersOfBindings(b.id).size > 1) stringResource(R.string.input_shared_detail, b.name, library.usersOfBindings(b.id).size)
|
||||
else "${profile.name} · ${roleLabel(role)}", onSave = { action ->
|
||||
if (update { l ->
|
||||
val geometry = if (!editing.click && elementProperties != null && layout != null) l.withLayout(layout.copy(elements = layout.elements.map {
|
||||
if (it.id == elementProperties!!.id) elementProperties!!.copy(name = elementProperties!!.name.trim().ifBlank { it.name }) else it
|
||||
})) else l
|
||||
geometry.withPreset(when {
|
||||
editing.element != null && editing.click -> b.copy(clicks = b.clicks + (editing.element.id to action))
|
||||
editing.element != null -> b.copy(elements = b.elements + (editing.element.id to action))
|
||||
editing.key != null -> b.copy(keys = b.keys.filterNot { it.key == editing.key } + PhysicalInputBinding(editing.key, action))
|
||||
else -> b.copy(controls = b.controls + (editing.control to action))
|
||||
}) }) edit = null
|
||||
})
|
||||
} else if (!surface) key(page, profileId, role) {
|
||||
SettingsPage(host, title = when (page) {
|
||||
InputPage.HOME -> if (embedded) null else stringResource(R.string.setup_controller)
|
||||
InputPage.PROFILE -> profile.name
|
||||
InputPage.SOURCE -> roleLabel(role)
|
||||
InputPage.LAYOUTS -> stringResource(R.string.input_saved_layouts)
|
||||
InputPage.REUSE -> stringResource(R.string.input_use_settings_from)
|
||||
}, eyebrow = when (page) {
|
||||
InputPage.SOURCE -> profile.name
|
||||
InputPage.LAYOUTS, InputPage.REUSE -> "${profile.name} · ${roleLabel(role)}"
|
||||
else -> null
|
||||
},
|
||||
onBack = ::back, showBack = !(embedded && page == InputPage.HOME), compactLayout = true) {
|
||||
when (page) {
|
||||
InputPage.HOME -> {
|
||||
SettingsGroup(stringResource(R.string.input_default_profiles)) {
|
||||
ChoiceRow(host, "auto-desktop", stringResource(R.string.input_desktop_mode), null,
|
||||
library.profiles.map { it.id to it.name }, library.desktop) { id -> update { it.copy(desktop = id) } }
|
||||
ChoiceRow(host, "auto-game", stringResource(R.string.input_game_mode), null,
|
||||
library.profiles.map { it.id to it.name }, library.steam) { id -> update { it.copy(steam = id) } }
|
||||
for (desktop in listOf(true, false)) {
|
||||
val selection = library.selection(desktop)
|
||||
if (selection.profile != InputProfiles.AUTO || selection.parts.isNotEmpty()) InputHint(stringResource(R.string.input_quick_override_hint,
|
||||
stringResource(if (desktop) R.string.input_desktop_mode else R.string.input_game_mode)))
|
||||
}
|
||||
}
|
||||
if (InputLibraries.hasPendingScreenKeyMigration(context)) InputHint(stringResource(R.string.input_import_failed))
|
||||
if (InputLibraries.hasLibraryRecovery(context)) InputHint(stringResource(R.string.input_library_recovered))
|
||||
if (library.profiles.any { it.id.startsWith("migrated.screenkeys.") }) Text(stringResource(R.string.input_imported_keys_hint),
|
||||
Modifier.padding(16.dp), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
SettingsGroup(stringResource(R.string.input_profiles)) {
|
||||
for (p in library.profiles) InputNavigationRow(p.name, when {
|
||||
p.id == library.steam && p.id == library.desktop -> stringResource(R.string.input_default_both)
|
||||
p.id == library.steam -> stringResource(R.string.input_default_game)
|
||||
p.id == library.desktop -> stringResource(R.string.input_default_desktop)
|
||||
else -> null
|
||||
}, Modifier.testTag("input-profile-${p.id}")) { profileId = p.id; go(InputPage.PROFILE) }
|
||||
TextButton(onClick = { newProfile(false) }, modifier = Modifier.padding(8.dp)) { Text(stringResource(R.string.input_new_profile)) }
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.input_device_settings)) {
|
||||
ToggleRow(host, "controller-rumble", stringResource(R.string.ctrl_rumble), null, controller.rumble) { ControllerPrefs.setRumble(context, it); onChanged() }
|
||||
ChoiceRow(host, "controller-dead-zone", stringResource(R.string.ctrl_dead_zone), null, ControllerPrefs.deadZones.map { it to stringResource(R.string.ctrl_percent, it) }, controller.deadZone) { ControllerPrefs.setDeadZone(context, it); onChanged() }
|
||||
ToggleRow(host, "controller-joycon-vr", stringResource(R.string.ctrl_joycon_vr), stringResource(R.string.ctrl_joycon_vr_hint), controller.joyConVr) { ControllerPrefs.setJoyConVr(context, it); onChanged() }
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.shortcuts_title)) { PhysicalShortcutRows() }
|
||||
SettingsGroup(stringResource(R.string.input_latency)) {
|
||||
var measuring by remember { mutableStateOf(InputTiming.enabled) }
|
||||
var timing by remember { mutableStateOf(InputTiming.report()) }
|
||||
InputHint(stringResource(R.string.input_latency_hint))
|
||||
ToggleRow(host, "input-measure", stringResource(R.string.input_measure), null, measuring) { measuring = it; InputTiming.enabled = it; if (it) InputTiming.reset() }
|
||||
var reading by remember { mutableStateOf(false) }
|
||||
ActionRow(stringResource(R.string.input_measurements), stringResource(R.string.input_measure_instructions),
|
||||
stringResource(R.string.input_read_timing), { timing = InputTiming.report(); reading = true })
|
||||
if (reading) AlertDialog(onDismissRequest = { reading = false }, title = { Text(stringResource(R.string.input_measurements)) },
|
||||
text = { Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Text(timing)
|
||||
Text(stringResource(R.string.input_measure_instructions), style = MaterialTheme.typography.bodySmall)
|
||||
} }, confirmButton = { TextButton(onClick = { reading = false }) { Text(stringResource(R.string.common_close)) } })
|
||||
}
|
||||
}
|
||||
InputPage.PROFILE -> {
|
||||
SettingsGroup(stringResource(R.string.input_profile_controls)) {
|
||||
for (r in InputRole.entries) InputNavigationRow(roleLabel(r),
|
||||
if (r == InputRole.PHYSICAL) stringResource(R.string.input_physical_hint) else library.layout(profileId, r)?.name,
|
||||
Modifier.testTag("input-part-${r.name.lowercase()}"), leading = {
|
||||
library.layout(profileId, r)?.let { InputLayoutThumbnail(it, r) }
|
||||
}) { editPart(r) }
|
||||
}
|
||||
Spacer(Modifier.height(16.dp))
|
||||
Actions {
|
||||
SecondaryButton(stringResource(R.string.input_rename)) { rename(R.string.input_rename, profile.name) { name -> update { it.withProfile(profile.copy(name = name)) } } }
|
||||
SecondaryButton(stringResource(R.string.input_copy_profile)) { newProfile(true) }
|
||||
SecondaryButton(stringResource(R.string.input_reset_actions)) {
|
||||
confirmation = InputConfirmation(context.getString(R.string.input_reset_actions), context.getString(R.string.input_reset_profile_detail, profile.name)) { update { it.resetProfile(profileId) } }
|
||||
}
|
||||
if (profileId !in listOf(InputProfile.GAME, InputProfile.DESKTOP)) SecondaryButton(stringResource(R.string.input_delete)) {
|
||||
confirmation = InputConfirmation(context.getString(R.string.input_delete), context.getString(R.string.input_delete_profile_detail, profile.name)) {
|
||||
if (update { it.removeProfile(profileId) }) { profileId = InputProfile.GAME; go(InputPage.HOME) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
InputPage.SOURCE -> {
|
||||
if (role == InputRole.PRIMARY) SettingsGroup(stringResource(R.string.input_screen_visibility)) {
|
||||
ChoiceRow(host, "controller-osc", stringResource(R.string.mode_osc), stringResource(R.string.input_visibility_shared),
|
||||
listOf(SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto), SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always),
|
||||
SessionPrefs.OSC_STEAM_TOUCH to stringResource(R.string.osc_steam_touch), SessionPrefs.OSC_STEAM_QAM to stringResource(R.string.mode_osc_qam), SessionPrefs.OSC_NEVER to stringResource(R.string.common_never)),
|
||||
oscMode) { SessionPrefs.setOscMode(context, it); oscMode = it; onChanged() }
|
||||
}
|
||||
if (layout != null) SettingsGroup(stringResource(R.string.ctrl_layout)) {
|
||||
if (layout.editable) InputNavigationRow(stringResource(R.string.input_edit_layout), layout.name, Modifier.testTag("input-surface-${role.name.lowercase()}")) { surface = true }
|
||||
else InputHint(layout.name)
|
||||
InputNavigationRow(stringResource(R.string.input_saved_layouts), stringResource(R.string.input_saved_layouts_hint)) { go(InputPage.LAYOUTS) }
|
||||
if (layout.editable) {
|
||||
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))) } }
|
||||
}
|
||||
if (role == InputRole.SECONDARY) InputHint(stringResource(R.string.input_second_screen_enable))
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.input_assign_actions)) {
|
||||
val users = library.usersOfBindings(preset.id)
|
||||
if (users.size > 1) InputHint(stringResource(R.string.input_shared_with, users.filterNot { it.id == profileId }.joinToString { it.name }))
|
||||
val elements = layout?.takeIf { it.editable }?.elements
|
||||
if (elements != null) {
|
||||
if (elements.isEmpty()) InputHint(stringResource(R.string.input_empty_elements))
|
||||
for (e in elements) {
|
||||
InputNavigationRow(e.name, actionLabel(preset.action(e)), Modifier.testTag("input-element-${e.id}")) { edit = InputBindingEdit(preset.id, e.control, e) }
|
||||
if (e.hasClick) InputNavigationRow(stringResource(R.string.input_click_name, e.name), actionLabel(preset.clickAction(e)), Modifier.testTag("input-click-${e.id}")) { edit = InputBindingEdit(preset.id, InputControl.A, e, click = true) }
|
||||
}
|
||||
} else {
|
||||
Box(Modifier.padding(horizontal = 12.dp, vertical = 12.dp)) {
|
||||
SheetChips(listOf(stringResource(R.string.input_buttons), stringResource(R.string.input_axes)) +
|
||||
if (preset.physical) listOf(stringResource(R.string.input_extra_keys)) else emptyList(), bindingsTab) { bindingsTab = it }
|
||||
}
|
||||
val controls = InputControl.padControls.asList()
|
||||
if (bindingsTab != 2) InputControlGrid(preset, controls, bindingsTab == 1) { edit = InputBindingEdit(preset.id, it) }
|
||||
else {
|
||||
for (b in preset.keys) {
|
||||
InputNavigationRow(b.key.label, actionLabel(b.action)) { edit = InputBindingEdit(preset.id, InputControl.A, key = b.key) }
|
||||
TextButton(onClick = { update { it.withPreset(preset.copy(keys = preset.keys - b)) } }) { Text(stringResource(R.string.input_remove_binding)) }
|
||||
}
|
||||
InputNavigationRow(stringResource(R.string.input_capture), stringResource(R.string.input_capture_hint)) { capture = true }
|
||||
}
|
||||
}
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.input_reuse)) {
|
||||
InputNavigationRow(stringResource(R.string.input_use_settings_from), stringResource(R.string.input_reuse_hint)) { go(InputPage.REUSE) }
|
||||
if (library.usersOfBindings(preset.id).size > 1 || layout?.let { it.editable && library.usersOfLayout(it.id).size > 1 } == true)
|
||||
InputNavigationRow(stringResource(R.string.input_make_independent), stringResource(R.string.input_independent_hint), Modifier.testTag("input-make-independent")) {
|
||||
update { it.usePart(profileId, role, profileId, shared = false) }
|
||||
}
|
||||
}
|
||||
}
|
||||
InputPage.LAYOUTS -> {
|
||||
InputHint(stringResource(R.string.input_layout_geometry_hint))
|
||||
SettingsGroup(stringResource(R.string.input_saved_layouts)) {
|
||||
var showOther by remember { mutableStateOf(false) }
|
||||
val available = library.layouts.filter { it.supports(role) }
|
||||
val other = available.filter { saved -> !saved.id.startsWith("builtin.") && saved.id != layout?.id &&
|
||||
library.usersOfLayout(saved.id).isEmpty() && library.bindings.none { it.layoutId == saved.id && library.selectedBindings(it.id) } }
|
||||
for (saved in available.filter { showOther || it !in other }) {
|
||||
InputLayoutRow(saved, role, if (saved.id == layout?.id) stringResource(R.string.input_current_layout) else null,
|
||||
onManage = { managingLayout = saved }) {
|
||||
reuse = InputReuseRequest(saved.name, layoutOnly = true) { shared -> if (update { it.useLayout(profileId, role, saved.id, shared) }) go(InputPage.SOURCE) }
|
||||
}
|
||||
}
|
||||
if (other.isNotEmpty()) TextButton(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))
|
||||
}
|
||||
TextButton(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)) }
|
||||
}
|
||||
|
||||
}
|
||||
InputPage.REUSE -> {
|
||||
InputHint(stringResource(R.string.input_reuse_explanation, roleLabel(role)))
|
||||
SettingsGroup(stringResource(R.string.input_profiles)) {
|
||||
for (p in library.profiles.filterNot { it.id == profileId }) InputNavigationRow(p.name, library.layout(p.id, role)?.name) {
|
||||
reuse = InputReuseRequest(p.name, layoutOnly = false) { shared -> if (update { it.usePart(profileId, role, p.id, shared) }) go(InputPage.SOURCE) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
managingLayout?.let { saved -> AlertDialog(onDismissRequest = { managingLayout = null }, title = { Text(saved.name) },
|
||||
text = { Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Text(stringResource(R.string.input_layout_count, saved.elements.size))
|
||||
SecondaryButton(stringResource(R.string.input_rename)) {
|
||||
managingLayout = null
|
||||
rename(R.string.input_rename_layout, saved.name) { name -> update { it.withLayout(saved.copy(name = name)) } }
|
||||
}
|
||||
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
|
||||
confirmation = InputConfirmation(context.getString(R.string.input_delete), context.getString(R.string.input_delete_layout_detail, saved.name)) { update { it.removeLayout(saved.id) } }
|
||||
}
|
||||
} }, confirmButton = { TextButton(onClick = { managingLayout = null }) { Text(stringResource(R.string.common_close)) } }) }
|
||||
if (capture) InputCaptureDialog(onDismiss = { capture = false }) { capture = false; edit = InputBindingEdit(preset.id, InputControl.A, key = it) }
|
||||
if (surface) InputSurfaceDialog(profileId, onDismiss = { surface = false; library = InputLibraries.read(context) }, onChanged = {
|
||||
library = InputLibraries.read(context); onChanged()
|
||||
}, role = role, layoutId = layout?.id, bindingsId = preset.id)
|
||||
naming?.let { request -> key(request) { InputNameDialog(request) { naming = null } } }
|
||||
reuse?.let { request -> key(request) { InputReuseDialog(request) { reuse = null } } }
|
||||
confirmation?.let { request -> AlertDialog(onDismissRequest = { confirmation = null }, title = { Text(request.title) },
|
||||
text = { Text(request.detail) }, confirmButton = { TextButton(onClick = { confirmation = null; request.action() }) { Text(stringResource(R.string.common_ok)) } },
|
||||
dismissButton = { TextButton(onClick = { confirmation = null }) { Text(stringResource(R.string.common_cancel)) } }) }
|
||||
error?.let { message -> AlertDialog(onDismissRequest = { error = null }, title = { Text(stringResource(R.string.input_save_failed)) },
|
||||
text = { Text(message) }, confirmButton = { TextButton(onClick = { error = null }) { Text(stringResource(R.string.common_ok)) } }) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun InputNameDialog(request: InputNameRequest, onDismiss: () -> Unit) {
|
||||
var name by remember { mutableStateOf(request.initial) }
|
||||
var source by remember { mutableStateOf(request.source) }
|
||||
var shared by remember { mutableStateOf(false) }
|
||||
val host = rememberMenuHost()
|
||||
AlertDialog(onDismissRequest = onDismiss, title = { Text(stringResource(request.title)) }, text = { Column(Modifier.verticalScroll(rememberScrollState())) {
|
||||
OutlinedTextField(name, { name = it.take(80) }, label = { Text(stringResource(R.string.input_name)) }, singleLine = true, modifier = Modifier.testTag("input-name"))
|
||||
if (request.sources.isNotEmpty()) ChoiceRow(host, "input-copy-source", stringResource(R.string.input_start_from), null, request.sources, source) { source = it }
|
||||
if (request.offerSharing) {
|
||||
Row(Modifier.fillMaxWidth().clickable { shared = !shared }, verticalAlignment = Alignment.CenterVertically) {
|
||||
Checkbox(shared, { shared = it }, Modifier.testTag("input-share-physical"))
|
||||
Text(stringResource(R.string.input_share_physical))
|
||||
}
|
||||
Text(stringResource(R.string.input_new_independent_hint), style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
} }, confirmButton = { TextButton(enabled = name.isNotBlank(), onClick = { request.save(name.trim(), source, shared); onDismiss() }) { Text(stringResource(R.string.gesture_save_changes)) } },
|
||||
dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.common_cancel)) } })
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun InputReuseDialog(request: InputReuseRequest, onDismiss: () -> Unit) {
|
||||
var shared by remember { mutableStateOf(false) }
|
||||
AlertDialog(onDismissRequest = onDismiss, title = { Text(request.name) }, text = { Column(Modifier.verticalScroll(rememberScrollState())) {
|
||||
Text(stringResource(if (request.layoutOnly) R.string.input_reuse_layout_detail else R.string.input_reuse_part_detail))
|
||||
for (link in listOf(false, true)) Row(Modifier.fillMaxWidth().clickable { shared = link }, verticalAlignment = Alignment.CenterVertically) {
|
||||
RadioButton(shared == link, { shared = link })
|
||||
Text(stringResource(if (link) R.string.input_keep_shared else R.string.input_independent_copy))
|
||||
}
|
||||
} }, confirmButton = { TextButton(onClick = { request.apply(shared); onDismiss() }) { Text(stringResource(R.string.common_ok)) } },
|
||||
dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.common_cancel)) } })
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun InputControlGrid(preset: SavedInputBindings, available: List<InputControl>, axes: Boolean, onPick: (InputControl) -> Unit) {
|
||||
val controls = available.filter { (it.dimensions == 2 || it == InputControl.LT || it == InputControl.RT) == axes }
|
||||
BoxWithConstraints(Modifier.fillMaxWidth().padding(12.dp)) {
|
||||
val columns = if (maxWidth < 480.dp) 2 else 4
|
||||
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
for (row in controls.chunked(columns)) Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
for (control in row) OutlinedCard(onClick = { onPick(control) }, modifier = Modifier.weight(1f).testTag("input-binding-${control.id}")) {
|
||||
Column(Modifier.padding(12.dp).heightIn(min = 48.dp)) {
|
||||
Text(control.label, style = MaterialTheme.typography.titleMedium)
|
||||
Text(actionLabel(preset.controls[control] ?: InputAction.Native()), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
repeat(columns - row.size) { Spacer(Modifier.weight(1f)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun InputNavigationRow(title: String, detail: String?, modifier: Modifier = Modifier, leading: (@Composable () -> Unit)? = null, onClick: () -> Unit) {
|
||||
Row(modifier.fillMaxWidth().clickable(role = Role.Button, onClick = onClick).heightIn(min = 64.dp).padding(14.dp),
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
leading?.invoke()
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(title, style = MaterialTheme.typography.titleMedium)
|
||||
if (detail != null) Text(detail, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
Text("›", style = MaterialTheme.typography.headlineSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
|
||||
@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
|
||||
})
|
||||
|
||||
@Composable
|
||||
private fun InputHint(text: String) {
|
||||
Text(text, Modifier.padding(14.dp), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.app.Presentation
|
||||
import android.hardware.display.DisplayManager
|
||||
import android.os.Bundle
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.view.Display
|
||||
import android.view.View
|
||||
import android.view.Window
|
||||
import android.view.WindowManager
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.activity.setViewTreeOnBackPressedDispatcherOwner
|
||||
import androidx.compose.animation.core.animateDpAsState
|
||||
import androidx.compose.ui.draw.clipToBounds
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.expandVertically
|
||||
import androidx.compose.animation.shrinkVertically
|
||||
import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.gestures.detectDragGestures
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.layout.onSizeChanged
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.unit.IntOffset
|
||||
import androidx.compose.ui.unit.IntSize
|
||||
import kotlin.math.roundToInt
|
||||
import androidx.compose.ui.platform.ComposeView
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalView
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import androidx.compose.ui.window.DialogWindowProvider
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleEventObserver
|
||||
import androidx.lifecycle.setViewTreeLifecycleOwner
|
||||
import androidx.lifecycle.setViewTreeViewModelStoreOwner
|
||||
import androidx.savedstate.setViewTreeSavedStateRegistryOwner
|
||||
import com.droiddeck.launcher.R
|
||||
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) {
|
||||
var elements by mutableStateOf(layout.elements)
|
||||
var actions by mutableStateOf(preset.elements)
|
||||
var clicks by mutableStateOf(preset.clicks)
|
||||
var selected by mutableStateOf<String?>(null)
|
||||
var toolsExpanded by mutableStateOf(false)
|
||||
var toolsX by mutableFloatStateOf(.02f)
|
||||
var toolsY by mutableFloatStateOf(.02f)
|
||||
var snap by mutableStateOf(true)
|
||||
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())
|
||||
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) } }
|
||||
fun action(e: InputSurfaceElement) = preset.copy(elements = actions).action(e)
|
||||
fun clickAction(e: InputSurfaceElement) = preset.copy(elements = actions, clicks = clicks).clickAction(e)
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () -> Unit,
|
||||
role: InputRole = InputRole.SECONDARY, layoutId: String? = null, bindingsId: String? = null) {
|
||||
val context = LocalContext.current
|
||||
val host = LocalInputActivity.current ?: context.findActivity() as? ComponentActivity
|
||||
val library = remember { InputLibraries.read(context) }
|
||||
val savedLayout = remember { library.layouts.first { it.id == (layoutId ?: library.profile(profile).parts.getValue(role).layout) } }
|
||||
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 manager = remember { context.getSystemService(DisplayManager::class.java) }
|
||||
var revision by remember { mutableIntStateOf(0) }
|
||||
var discard by remember { mutableStateOf(false) }
|
||||
var failure by remember { mutableStateOf<String?>(null) }
|
||||
val target = remember(revision, role) {
|
||||
if (host is SessionActivity) host.inputEditorDisplay(role)
|
||||
else if (role == InputRole.PRIMARY) host?.window?.decorView?.display
|
||||
else {
|
||||
val displays = SecondScreenDisplays.available(manager, host?.window?.decorView?.display?.displayId ?: Display.DEFAULT_DISPLAY)
|
||||
manager.getDisplay(displays.firstOrNull { it.id == SessionState.secondScreenDisplay }?.id ?: displays.firstOrNull()?.id ?: -1)
|
||||
}
|
||||
}
|
||||
val remote = target != null && target.displayId != host?.window?.decorView?.display?.displayId
|
||||
fun leave() { if (draft.dirty) discard = true else onDismiss() }
|
||||
fun save() {
|
||||
runCatching {
|
||||
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 } },
|
||||
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) }
|
||||
}
|
||||
DisposableEffect(manager) {
|
||||
val listener = object : DisplayManager.DisplayListener {
|
||||
override fun onDisplayAdded(id: Int) { revision++ }
|
||||
override fun onDisplayRemoved(id: Int) { revision++ }
|
||||
override fun onDisplayChanged(id: Int) { revision++ }
|
||||
}
|
||||
manager.registerDisplayListener(listener, Handler(Looper.getMainLooper()))
|
||||
onDispose { manager.unregisterDisplayListener(listener) }
|
||||
}
|
||||
if (remote && host != null) DisposableEffect(target!!.displayId, host) {
|
||||
val presentation = SurfaceEditorPresentation(host, target, transparent = host is SessionActivity && role == InputRole.PRIMARY) {
|
||||
SurfaceCanvas(draft, transparent = host is SessionActivity && role == InputRole.PRIMARY)
|
||||
}
|
||||
runCatching { presentation.show() }.onFailure { failure = it.message }
|
||||
val observer = LifecycleEventObserver { _, event ->
|
||||
if (event == Lifecycle.Event.ON_STOP) presentation.hide()
|
||||
if (event == Lifecycle.Event.ON_START) runCatching { presentation.show() }
|
||||
}
|
||||
host.lifecycle.addObserver(observer)
|
||||
onDispose { host.lifecycle.removeObserver(observer); presentation.dismiss() }
|
||||
}
|
||||
// Compose 1.6 custom dialog sizing subtracts system bars even when they are hidden.
|
||||
Dialog(onDismissRequest = ::leave, properties = DialogProperties(usePlatformDefaultWidth = true, decorFitsSystemWindows = false)) {
|
||||
val editorWindow = (LocalView.current.parent as? DialogWindowProvider)?.window
|
||||
DisposableEffect(editorWindow) {
|
||||
editorWindow?.prepareInputEditor()
|
||||
if (host is SessionActivity && role == InputRole.PRIMARY) editorWindow?.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
|
||||
onDispose { }
|
||||
}
|
||||
Surface(Modifier.fillMaxSize(), color = if (host is SessionActivity && role == InputRole.PRIMARY && !draft.properties && !remote)
|
||||
androidx.compose.ui.graphics.Color.Transparent else MaterialTheme.colorScheme.surface) {
|
||||
val element = draft.element
|
||||
BackHandler { if (draft.properties) draft.properties = false else leave() }
|
||||
when {
|
||||
draft.properties && element != null -> {
|
||||
var properties by remember(element.id) { mutableStateOf(element) }
|
||||
InputActionEditor(if (draft.clickProperties) InputControl.A else element.control,
|
||||
if (draft.clickProperties) draft.clickAction(element) else draft.action(element),
|
||||
if (draft.clickProperties) stringResource(R.string.input_click_name, element.name) else element.name,
|
||||
onBack = { draft.properties = false }, element = element, click = draft.clickProperties,
|
||||
properties = {
|
||||
if (!draft.clickProperties) InputElementProperties(properties) { properties = it }
|
||||
if (layoutUsers > 1) Text(stringResource(R.string.input_editor_shared, layoutUsers),
|
||||
style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(bottom = 12.dp))
|
||||
}, detail = if (bindingUsers > 1) stringResource(R.string.input_shared_detail, savedBindings.name, bindingUsers)
|
||||
else "${library.profile(profile).name} · ${roleLabel(role)}", onSave = { action ->
|
||||
draft.checkpoint()
|
||||
if (draft.clickProperties) draft.clicks = draft.clicks + (element.id to action) else draft.actions = draft.actions + (element.id to action)
|
||||
draft.elements = draft.elements.map { if (it.id == element.id) properties.copy(name = properties.name.trim().ifBlank { element.name }) else it }
|
||||
draft.properties = false
|
||||
})
|
||||
}
|
||||
target == null -> SettingsPage(rememberMenuHost(), savedLayout.name, ::leave) {
|
||||
Text(stringResource(R.string.input_display_unavailable))
|
||||
PrimaryButton(stringResource(R.string.input_editor_done)) { save() }
|
||||
}
|
||||
remote -> SettingsPage(rememberMenuHost(), stringResource(R.string.input_editor_remote), ::leave,
|
||||
lede = if (layoutUsers > 1) stringResource(R.string.input_editor_shared, layoutUsers) else savedLayout.name) {
|
||||
SurfaceToolbar(draft, ::save, ::leave)
|
||||
SurfaceSelection(draft)
|
||||
}
|
||||
else -> Box(Modifier.fillMaxSize()) {
|
||||
SurfaceCanvas(draft, transparent = host is SessionActivity && role == InputRole.PRIMARY)
|
||||
FloatingSurfaceTools(draft, ::save, ::leave)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (draft.adding) AlertDialog(onDismissRequest = { draft.adding = false }, title = { Text(stringResource(R.string.input_add_element)) }, confirmButton = {}, text = { Column {
|
||||
for (kind in InputElementKind.entries) TextButton(onClick = { draft.checkpoint()
|
||||
val w = if (kind.control.dimensions == 2) .4f else .2f
|
||||
val h = .3f
|
||||
val name = context.getString(kind.label()) + " " + (draft.elements.count { it.kind == kind } + 1)
|
||||
val element = InputSurfaceElement(kind.control, (1f - w) / 2, (1f - h) / 2, w, h, newInputId(), kind, name)
|
||||
draft.elements = draft.elements + element; draft.selected = element.id
|
||||
draft.adding = false; draft.toolsExpanded = false }) { Text(stringResource(kind.label())) }
|
||||
} })
|
||||
if (discard) AlertDialog(onDismissRequest = { discard = false }, title = { Text(stringResource(R.string.input_editor_discard)) },
|
||||
confirmButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.common_ok)) } },
|
||||
dismissButton = { TextButton(onClick = { discard = false }) { Text(stringResource(R.string.common_cancel)) } })
|
||||
failure?.let { AlertDialog(onDismissRequest = { failure = null }, title = { Text(stringResource(R.string.input_save_failed)) }, text = { Text(it) },
|
||||
confirmButton = { TextButton(onClick = { failure = null }) { Text(stringResource(R.string.common_ok)) } }) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
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.isEnabled = !draft.properties && !draft.adding
|
||||
view.onSelect = { if (!draft.properties) draft.selected = it }
|
||||
view.onBeginEdit = draft::checkpoint
|
||||
view.onChange = { e -> if (!draft.properties) draft.elements = draft.elements.map { if (it.id == e.id) e else it } }
|
||||
|
||||
})
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun FloatingSurfaceTools(draft: SurfaceDraft, onSave: () -> Unit, onLeave: () -> Unit) {
|
||||
BoxWithConstraints(Modifier.fillMaxSize()) {
|
||||
val density = LocalDensity.current
|
||||
val screenWidth = with(density) { maxWidth.toPx() }
|
||||
val screenHeight = with(density) { maxHeight.toPx() }
|
||||
val margin = with(density) { 8.dp.toPx() }
|
||||
var panelSize by remember { mutableStateOf(IntSize.Zero) }
|
||||
val x = (draft.toolsX * screenWidth).coerceIn(margin, (screenWidth - panelSize.width - margin).coerceAtLeast(margin))
|
||||
val y = (draft.toolsY * screenHeight).coerceIn(margin, (screenHeight - panelSize.height - margin).coerceAtLeast(margin))
|
||||
val position by rememberUpdatedState(Offset(x, y))
|
||||
val expandedWidth = minOf(420.dp, maxWidth - 16.dp)
|
||||
val panelWidth by animateDpAsState(if (draft.toolsExpanded) expandedWidth else 152.dp, label = "input-tools-width")
|
||||
Surface(Modifier.offset { IntOffset(x.roundToInt(), y.roundToInt()) }
|
||||
.width(panelWidth).clipToBounds()
|
||||
.heightIn(max = maxHeight - 16.dp).onSizeChanged { panelSize = it },
|
||||
shape = RoundedCornerShape(18.dp), color = MaterialTheme.colorScheme.surface,
|
||||
tonalElevation = 6.dp, shadowElevation = 10.dp) {
|
||||
Column {
|
||||
Row(Modifier.fillMaxWidth().heightIn(min = 52.dp).testTag("input-editor-tools")
|
||||
.pointerInput(screenWidth, screenHeight, panelSize) {
|
||||
var dragPosition = Offset.Zero
|
||||
detectDragGestures(onDragStart = { dragPosition = position }) { change, delta ->
|
||||
change.consume()
|
||||
dragPosition = Offset((dragPosition.x + delta.x).coerceIn(margin, (screenWidth - panelSize.width - margin).coerceAtLeast(margin)),
|
||||
(dragPosition.y + delta.y).coerceIn(margin, (screenHeight - panelSize.height - margin).coerceAtLeast(margin)))
|
||||
draft.toolsX = dragPosition.x / screenWidth
|
||||
draft.toolsY = dragPosition.y / screenHeight
|
||||
}
|
||||
}
|
||||
.clickable { draft.toolsExpanded = !draft.toolsExpanded }.padding(horizontal = 16.dp),
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Text("⠿", color = MaterialTheme.colorScheme.primary)
|
||||
Text(stringResource(if (draft.toolsExpanded) R.string.input_hide_tools else R.string.input_tools), style = MaterialTheme.typography.titleSmall, maxLines = 1)
|
||||
}
|
||||
AnimatedVisibility(draft.toolsExpanded, enter = expandVertically(expandFrom = Alignment.Top) + fadeIn(),
|
||||
exit = shrinkVertically(shrinkTowards = Alignment.Top) + fadeOut()) {
|
||||
Column(Modifier.requiredWidth(expandedWidth).verticalScroll(rememberScrollState())) {
|
||||
HorizontalDivider()
|
||||
SurfaceToolbar(draft, onSave, onLeave)
|
||||
HorizontalDivider()
|
||||
SurfaceSelection(draft)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
private fun SurfaceToolbar(draft: SurfaceDraft, onSave: () -> Unit, onLeave: () -> Unit) {
|
||||
FlowRow(Modifier.fillMaxWidth().padding(8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
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() }
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
private fun SurfaceSelection(draft: SurfaceDraft) {
|
||||
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
draft.element?.let { e ->
|
||||
Text(e.name, style = MaterialTheme.typography.titleMedium)
|
||||
FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
PrimaryButton(stringResource(R.string.input_properties), compact = true) { draft.clickProperties = false; draft.properties = true }
|
||||
if (e.hasClick) SecondaryButton(stringResource(R.string.input_click_properties), compact = true) { draft.clickProperties = true; draft.properties = true }
|
||||
SecondaryButton(stringResource(R.string.input_remove_element), compact = true) {
|
||||
draft.checkpoint(); draft.elements = draft.elements.filterNot { it.id == e.id }; draft.actions = draft.actions - e.id; draft.clicks = draft.clicks - e.id; draft.selected = null
|
||||
}
|
||||
}
|
||||
} ?: Text(stringResource(R.string.input_editor_hint))
|
||||
}
|
||||
}
|
||||
|
||||
private fun InputElementKind.label() = when (this) {
|
||||
InputElementKind.BUTTON -> R.string.input_element_button
|
||||
InputElementKind.STICK -> R.string.input_element_stick
|
||||
InputElementKind.TRACKPAD -> R.string.input_element_trackpad
|
||||
InputElementKind.DPAD -> R.string.input_element_dpad
|
||||
InputElementKind.TRIGGER -> R.string.input_element_trigger
|
||||
}
|
||||
|
||||
private class SurfaceEditorPresentation(private val host: ComponentActivity, display: Display, private val transparent: Boolean, private val content: @Composable () -> Unit) : Presentation(host, display) {
|
||||
private var view: ComposeView? = null
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
setCancelable(false)
|
||||
window?.addFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE)
|
||||
window?.prepareInputEditor()
|
||||
window?.decorView?.let {
|
||||
it.setViewTreeLifecycleOwner(host); it.setViewTreeViewModelStoreOwner(host)
|
||||
it.setViewTreeSavedStateRegistryOwner(host); it.setViewTreeOnBackPressedDispatcherOwner(host)
|
||||
}
|
||||
window?.setBackgroundDrawable(android.graphics.drawable.ColorDrawable(android.graphics.Color.TRANSPARENT))
|
||||
view = ComposeView(context).also { it.setContent { DroidDeckTheme {
|
||||
Surface(Modifier.fillMaxSize(), color = if (transparent) androidx.compose.ui.graphics.Color.Transparent else MaterialTheme.colorScheme.surface) { content() }
|
||||
} }; setContentView(it) }
|
||||
}
|
||||
override fun dismiss() { view?.disposeComposition(); view = null; super.dismiss() }
|
||||
}
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
internal fun Window.prepareInputEditor() {
|
||||
addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON or WindowManager.LayoutParams.FLAG_FULLSCREEN)
|
||||
setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT)
|
||||
decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
|
||||
View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Color
|
||||
import android.graphics.Paint
|
||||
import android.view.HapticFeedbackConstants
|
||||
import android.view.MotionEvent
|
||||
import android.view.ViewConfiguration
|
||||
import android.widget.FrameLayout
|
||||
import com.droiddeck.launcher.input.InputSurfaceElement
|
||||
import com.droiddeck.launcher.input.InputSurfaceStyle
|
||||
import com.droiddeck.launcher.input.snapSurfaceElement
|
||||
import kotlin.math.abs
|
||||
|
||||
internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) {
|
||||
var elements: List<InputSurfaceElement> = emptyList()
|
||||
set(value) { field = value; preview.updateCustomLayout(value); invalidate() }
|
||||
var style = InputSurfaceStyle()
|
||||
set(value) { field = value; preview.updateStyle(value) }
|
||||
var snap = true
|
||||
set(value) { field = value; if (!value) clearGuides() }
|
||||
private var guideX: Float? = null
|
||||
private var guideY: Float? = null
|
||||
var selected: String? = null
|
||||
set(value) { field = value; invalidate() }
|
||||
var onSelect: (String?) -> Unit = {}
|
||||
var onBeginEdit: () -> Unit = {}
|
||||
var onChange: (InputSurfaceElement) -> Unit = {}
|
||||
private val preview = InputSurfaceView(context)
|
||||
private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = Color.rgb(26, 159, 255); strokeWidth = 2 * resources.displayMetrics.density }
|
||||
private val radius = 14 * resources.displayMetrics.density
|
||||
private var original: InputSurfaceElement? = null
|
||||
private var downX = 0f
|
||||
private var downY = 0f
|
||||
private var corner = 0
|
||||
private var dragging = false
|
||||
|
||||
init {
|
||||
setBackgroundColor(Color.rgb(10, 11, 13))
|
||||
addView(preview, LayoutParams(-1, -1))
|
||||
}
|
||||
|
||||
override fun dispatchDraw(canvas: Canvas) {
|
||||
super.dispatchDraw(canvas)
|
||||
paint.style = Paint.Style.STROKE
|
||||
guideX?.let { canvas.drawLine(width * it, 0f, width * it, height.toFloat(), paint) }
|
||||
guideY?.let { canvas.drawLine(0f, height * it, width.toFloat(), height * it, paint) }
|
||||
val e = elements.firstOrNull { it.id == selected } ?: return
|
||||
val l = width * e.x; val t = height * e.y; val r = l + width * e.width; val b = t + height * e.height
|
||||
paint.style = Paint.Style.STROKE; canvas.drawRect(l, t, r, b, paint)
|
||||
paint.style = Paint.Style.FILL
|
||||
for (x in listOf(l, r)) for (y in listOf(t, b)) canvas.drawCircle(x, y, radius / 3, paint)
|
||||
}
|
||||
|
||||
private fun clearGuides() { guideX = null; guideY = null; invalidate() }
|
||||
|
||||
override fun onInterceptTouchEvent(event: MotionEvent) = true
|
||||
|
||||
@SuppressLint("ClickableViewAccessibility")
|
||||
override fun onTouchEvent(event: MotionEvent): Boolean {
|
||||
if (!isEnabled || width == 0 || height == 0) return true
|
||||
when (event.actionMasked) {
|
||||
MotionEvent.ACTION_DOWN -> {
|
||||
clearGuides()
|
||||
downX = event.x; downY = event.y; dragging = false; corner = 0
|
||||
val current = elements.firstOrNull { it.id == selected }
|
||||
if (current != null) {
|
||||
val left = width * current.x; val top = height * current.y
|
||||
val right = left + width * current.width; val bottom = top + height * current.height
|
||||
val horizontal = if (abs(downX - left) < radius) 1 else if (abs(downX - right) < radius) 2 else 0
|
||||
val vertical = if (abs(downY - top) < radius) 4 else if (abs(downY - bottom) < radius) 8 else 0
|
||||
if (horizontal != 0 && vertical != 0) corner = horizontal or vertical
|
||||
}
|
||||
original = if (corner != 0) current else elements.asReversed().firstOrNull {
|
||||
downX / width in it.x..(it.x + it.width) && downY / height in it.y..(it.y + it.height)
|
||||
}
|
||||
selected = original?.id; onSelect(selected)
|
||||
}
|
||||
MotionEvent.ACTION_MOVE -> {
|
||||
val e = original ?: return true
|
||||
if (!dragging && abs(event.x - downX) + abs(event.y - downY) > ViewConfiguration.get(context).scaledTouchSlop) {
|
||||
dragging = true; onBeginEdit()
|
||||
}
|
||||
if (!dragging) return true
|
||||
val dx = (event.x - downX) / width; val dy = (event.y - downY) / height
|
||||
val next = if (corner == 0) e.copy(x = (e.x + dx).coerceIn(0f, 1f - e.width), y = (e.y + dy).coerceIn(0f, 1f - e.height))
|
||||
else {
|
||||
val left = if (corner and 1 != 0) (e.x + dx).coerceIn(0f, e.x + e.width - .03f) else e.x
|
||||
val top = if (corner and 4 != 0) (e.y + dy).coerceIn(0f, e.y + e.height - .03f) else e.y
|
||||
val right = if (corner and 2 != 0) (e.x + e.width + dx).coerceIn(left + .03f, 1f) else e.x + e.width
|
||||
val bottom = if (corner and 8 != 0) (e.y + e.height + dy).coerceIn(top + .03f, 1f) else e.y + e.height
|
||||
e.copy(x = left, y = top, width = right - left, height = bottom - top).bounded()
|
||||
}
|
||||
val aligned = if (snap) snapSurfaceElement(next, elements.filter { it.id != e.id }, 9 * resources.displayMetrics.density / width,
|
||||
9 * resources.displayMetrics.density / height, corner) else null
|
||||
if (aligned != null && (aligned.x != null && aligned.x != guideX || aligned.y != null && aligned.y != guideY)) performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
|
||||
guideX = aligned?.x; guideY = aligned?.y
|
||||
onChange(aligned?.element ?: next)
|
||||
invalidate()
|
||||
}
|
||||
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { original = null; dragging = false; clearGuides() }
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,546 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import com.droiddeck.launcher.R
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import android.graphics.BitmapFactory
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Color
|
||||
import android.graphics.Paint
|
||||
import android.graphics.RadialGradient
|
||||
import android.graphics.RectF
|
||||
import android.graphics.Shader
|
||||
import android.graphics.Typeface
|
||||
import android.graphics.drawable.GradientDrawable
|
||||
import android.view.Gravity
|
||||
import android.view.HapticFeedbackConstants
|
||||
import android.view.ViewConfiguration
|
||||
import android.view.MotionEvent
|
||||
import com.droiddeck.launcher.input.TouchpadGestures
|
||||
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
|
||||
import com.droiddeck.launcher.input.InputControl
|
||||
import com.droiddeck.launcher.input.InputSurfaceElement
|
||||
import com.droiddeck.launcher.input.InputSurfaceStyle
|
||||
import com.droiddeck.launcher.input.pointerSubset
|
||||
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.PadBridge
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import kotlin.math.atan2
|
||||
import kotlin.math.hypot
|
||||
import kotlin.math.min
|
||||
|
||||
@SuppressLint("ViewConstructor")
|
||||
class InputSurfaceView(
|
||||
context: Context,
|
||||
private val pad: PadBridge? = null,
|
||||
private var customLayout: List<InputSurfaceElement> = emptyList(),
|
||||
private val inputRole: InputRole = InputRole.SECONDARY,
|
||||
private var surfaceStyle: InputSurfaceStyle = InputSurfaceStyle(),
|
||||
) : 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) }
|
||||
|
||||
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 || 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 (forwardedPointers == 0) return super.dispatchTouchEvent(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() }
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
fun updateStyle(style: InputSurfaceStyle) {
|
||||
if (surfaceStyle == style) return
|
||||
surfaceStyle = style
|
||||
customCanvas?.let { canvas -> for (i in 0 until canvas.childCount) styleElement(canvas.getChildAt(i)) }
|
||||
}
|
||||
|
||||
private fun styleElement(view: View) {
|
||||
view.alpha = surfaceStyle.opacity / 100f * ((view.tag as? InputSurfaceElement)?.opacity ?: 1f)
|
||||
(view as? Surface)?.tint = surfaceStyle.tint
|
||||
view.invalidate()
|
||||
}
|
||||
|
||||
fun updateCustomLayout(layout: List<InputSurfaceElement>) {
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
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() }
|
||||
forwardedPointers = 0
|
||||
elementSources.forEach { it.release() }
|
||||
}
|
||||
|
||||
private fun renderCustom(pad: PadBridge?) {
|
||||
val canvas = object : ViewGroup(context) {
|
||||
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
|
||||
val layout = customLayout
|
||||
val w = MeasureSpec.getSize(widthMeasureSpec)
|
||||
val h = MeasureSpec.getSize(heightMeasureSpec)
|
||||
setMeasuredDimension(w, h)
|
||||
for (i in layout.indices) getChildAt(i).measure(MeasureSpec.makeMeasureSpec((w * layout[i].width).toInt(), MeasureSpec.EXACTLY),
|
||||
MeasureSpec.makeMeasureSpec((h * layout[i].height).toInt(), MeasureSpec.EXACTLY))
|
||||
}
|
||||
override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
|
||||
val layout = customLayout
|
||||
for (i in layout.indices) {
|
||||
val e = layout[i]
|
||||
val child = getChildAt(i)
|
||||
val x = (width * e.x).toInt(); val y = (height * e.y).toInt()
|
||||
child.layout(x, y, x + child.measuredWidth, y + child.measuredHeight)
|
||||
}
|
||||
}
|
||||
}
|
||||
for (element in customLayout) {
|
||||
val source = pad?.let { InputSurfaceSource(it, inputRole, element).also { s -> elementSources += s } }
|
||||
canvas.addView(when (element.kind) {
|
||||
InputElementKind.STICK -> StickView(context, source, element.floating, element.hideWhenIdle && pad != null)
|
||||
InputElementKind.TRACKPAD -> TrackpadView(context, element.control == InputControl.RIGHT_PAD, source = source)
|
||||
InputElementKind.DPAD -> DirectionPad(context, source)
|
||||
else -> HoldButton(context, element, source)
|
||||
}.apply { tag = element; contentDescription = element.name; styleElement(this); source?.onStateChanged = { postInvalidate() } })
|
||||
}
|
||||
content.addView(canvas, FrameLayout.LayoutParams(-1, -1))
|
||||
customCanvas = canvas
|
||||
}
|
||||
|
||||
override fun onAttachedToWindow() {
|
||||
super.onAttachedToWindow()
|
||||
if (pad != null && elementSources.isEmpty()) {
|
||||
content.removeAllViews()
|
||||
renderCustom(pad)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onDetachedFromWindow() {
|
||||
elementSources.forEach { it.close() }
|
||||
elementSources.clear()
|
||||
super.onDetachedFromWindow()
|
||||
}
|
||||
|
||||
fun takesTouchAt(x: Float, y: Float): Boolean = controlUnder(this, x, y)
|
||||
|
||||
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 abstract class Surface(context: Context) : View(context) {
|
||||
var tint: Int? = null
|
||||
protected val density = resources.displayMetrics.density
|
||||
protected val rect = RectF()
|
||||
private val fill = Paint(Paint.ANTI_ALIAS_FLAG)
|
||||
private val stroke = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE }
|
||||
protected val labelPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
textAlign = Paint.Align.CENTER
|
||||
typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
|
||||
}
|
||||
protected val captionPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
textAlign = Paint.Align.CENTER
|
||||
color = TEXT_DIM
|
||||
}
|
||||
|
||||
protected fun drawSurface(canvas: Canvas, lit: Boolean, shape: InputButtonShape = InputButtonShape.ROUNDED) {
|
||||
val inset = density
|
||||
rect.set(inset, inset, width - inset, height - inset)
|
||||
val radius = when (shape) { InputButtonShape.CIRCLE, InputButtonShape.PILL -> min(width, height) / 2f; InputButtonShape.RECTANGLE -> 2 * density; else -> CORNER * density }
|
||||
fill.color = tint?.let { color -> (color and 0x00ffffff) or ((if (lit) 140 else 48) shl 24) } ?: if (lit) ACCENT_WASH else SURFACE
|
||||
canvas.drawRoundRect(rect, radius, radius, fill)
|
||||
stroke.color = tint?.let { color -> (color and 0x00ffffff) or ((if (lit) 255 else 160) shl 24) } ?: if (lit) ACCENT else LINE
|
||||
stroke.strokeWidth = (if (lit) 2f else 1f) * density
|
||||
canvas.drawRoundRect(rect, radius, radius, stroke)
|
||||
}
|
||||
}
|
||||
|
||||
private class HoldButton(context: Context, private val element: InputSurfaceElement, private val source: InputSurfaceSource?) : Surface(context) {
|
||||
private var down = false
|
||||
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)
|
||||
val size = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
BitmapFactory.decodeFile(file.path, size)
|
||||
val options = BitmapFactory.Options().apply {
|
||||
while (size.outWidth / inSampleSize.coerceAtLeast(1) > 512 || size.outHeight / inSampleSize.coerceAtLeast(1) > 512)
|
||||
inSampleSize = inSampleSize.coerceAtLeast(1) * 2
|
||||
}
|
||||
if (file.isFile) BitmapFactory.decodeFile(file.path, options) else null
|
||||
}
|
||||
private val imageRect = RectF()
|
||||
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
val lit = if (element.toggle) source?.latched == true else down
|
||||
drawSurface(canvas, lit, element.buttonShape)
|
||||
val cx = width / 2f
|
||||
labelPaint.color = if (lit) ACCENT else TEXT
|
||||
bitmap?.let {
|
||||
val scale = min(width * .84f / it.width, height * .84f / it.height)
|
||||
imageRect.set(cx - it.width * scale / 2, (height - it.height * scale) / 2,
|
||||
cx + it.width * scale / 2, (height + it.height * scale) / 2)
|
||||
canvas.drawBitmap(it, null, imageRect, labelPaint)
|
||||
return
|
||||
}
|
||||
if (element.icon != 0 && InputButtonIcons.draw(canvas, element.icon, cx, height / 2f, min(width, height) * .68f, labelPaint, symbol)) return
|
||||
if (!element.showLabel) return
|
||||
labelPaint.textSize = min(height * .3f, 30 * density)
|
||||
val labelWidth = labelPaint.measureText(element.name)
|
||||
if (labelWidth > width * .84f) labelPaint.textSize *= width * .84f / labelWidth
|
||||
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
|
||||
}
|
||||
|
||||
override fun onDetachedFromWindow() { set(false); source?.release(); super.onDetachedFromWindow() }
|
||||
|
||||
private fun set(pressed: Boolean) {
|
||||
if (down == pressed) return
|
||||
down = pressed
|
||||
if (pressed) performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
|
||||
source?.update(if (pressed) 1f else 0f)
|
||||
invalidate()
|
||||
}
|
||||
}
|
||||
|
||||
private inner class TrackpadView(context: Context, private val right: Boolean, private val captioned: Boolean = true,
|
||||
private val source: InputSurfaceSource? = null) : Surface(context) {
|
||||
private var gestureX = 0f
|
||||
private var gestureY = 0f
|
||||
private val mouse = TouchpadGestures(ViewConfiguration.get(context).scaledTouchSlop.toFloat(), object : PointerGestures.Listener {
|
||||
override fun onMove(x: Float, y: Float) {
|
||||
source?.pointerDelta(2 * (x - gestureX) / width.coerceAtLeast(1), 2 * (y - gestureY) / height.coerceAtLeast(1))
|
||||
gestureX = x; gestureY = y
|
||||
}
|
||||
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) }
|
||||
}).apply { bounds = RectF(-1e9f, -1e9f, 1e9f, 1e9f) }
|
||||
|
||||
private var touching = false
|
||||
private var clicked = false
|
||||
private var fingerX = 0f
|
||||
private var fingerY = 0f
|
||||
private val guide = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE; color = GUIDE }
|
||||
private val dot = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = ACCENT }
|
||||
private val glow = Paint(Paint.ANTI_ALIAS_FLAG)
|
||||
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
drawSurface(canvas, clicked)
|
||||
val cx = width / 2f
|
||||
val cy = height / 2f
|
||||
guide.strokeWidth = density
|
||||
val reach = min(width, height) / 2f - 24 * density
|
||||
canvas.drawCircle(cx, cy, reach, guide)
|
||||
canvas.drawCircle(cx, cy, reach / 2f, guide)
|
||||
canvas.drawLine(cx - reach, cy, cx + reach, cy, guide)
|
||||
canvas.drawLine(cx, cy - reach, cx, cy + reach, guide)
|
||||
captionPaint.textSize = 12 * density
|
||||
captionPaint.color = if (touching) ACCENT else TEXT_DIM
|
||||
if (captioned) canvas.drawText((contentDescription?.toString() ?: if (right) context.getString(R.string.deck_right_trackpad) else context.getString(R.string.deck_left_trackpad)).uppercase(), cx, 28 * density, captionPaint)
|
||||
if (touching) {
|
||||
val radius = 56 * density
|
||||
glow.shader = RadialGradient(fingerX, fingerY, radius, ACCENT_GLOW, Color.TRANSPARENT, Shader.TileMode.CLAMP)
|
||||
canvas.drawCircle(fingerX, fingerY, radius, glow)
|
||||
canvas.drawCircle(fingerX, fingerY, (if (clicked) 16 else 12) * density, dot)
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("ClickableViewAccessibility")
|
||||
override fun onTouchEvent(event: MotionEvent): Boolean {
|
||||
if (source?.mouseGestures == true) {
|
||||
if (event.actionMasked == MotionEvent.ACTION_DOWN) {
|
||||
gestureX = 0f; gestureY = 0f; mouse.place(0f, 0f)
|
||||
source.gestureContact(true)
|
||||
}
|
||||
touching = event.actionMasked != MotionEvent.ACTION_UP && event.actionMasked != MotionEvent.ACTION_CANCEL
|
||||
fingerX = event.x; fingerY = event.y
|
||||
mouse.onTouch(event)
|
||||
if (!touching) source.gestureContact(false)
|
||||
invalidate()
|
||||
return true
|
||||
}
|
||||
when (event.actionMasked) {
|
||||
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_MOVE -> {
|
||||
touch(event.getX(0), event.getY(0))
|
||||
click(event.pointerCount > 1)
|
||||
}
|
||||
MotionEvent.ACTION_POINTER_DOWN -> click(true)
|
||||
MotionEvent.ACTION_POINTER_UP -> {
|
||||
val stays = if (event.actionIndex == 0) 1 else 0
|
||||
touch(event.getX(stays), event.getY(stays))
|
||||
click(event.pointerCount - 1 > 1)
|
||||
}
|
||||
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
|
||||
click(false)
|
||||
touching = false
|
||||
source?.update(0f, 0f, false)
|
||||
invalidate()
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
override fun onDetachedFromWindow() { mouse.cancel(); source?.release(); super.onDetachedFromWindow() }
|
||||
|
||||
private fun touch(x: Float, y: Float) {
|
||||
fingerX = x.coerceIn(0f, width.toFloat())
|
||||
fingerY = y.coerceIn(0f, height.toFloat())
|
||||
touching = true
|
||||
val xAxis = (fingerX - width / 2f) / (width / 2f).coerceAtLeast(1f)
|
||||
val yAxis = -(fingerY - height / 2f) / (height / 2f).coerceAtLeast(1f)
|
||||
source?.update(xAxis, yAxis, true)
|
||||
invalidate()
|
||||
}
|
||||
|
||||
private fun click(down: Boolean) {
|
||||
if (clicked == down) return
|
||||
clicked = down
|
||||
if (down) performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
|
||||
source?.click(down)
|
||||
invalidate()
|
||||
}
|
||||
}
|
||||
|
||||
private inner class StickView(context: Context, private val source: InputSurfaceSource? = null, private val floating: Boolean = true, private val hideWhenIdle: Boolean = false) : Surface(context) {
|
||||
private var touching = false
|
||||
private var clicking = false
|
||||
private var lastUp = 0L
|
||||
private var downAt = 0L
|
||||
private var downX = 0f
|
||||
private var downY = 0f
|
||||
private var travel = 0f
|
||||
private val tapSlop = ViewConfiguration.get(context).scaledTouchSlop.toFloat()
|
||||
private var originX = 0f
|
||||
private var originY = 0f
|
||||
private var knobX = 0f
|
||||
private var knobY = 0f
|
||||
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
|
||||
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
if (hideWhenIdle && !touching) return
|
||||
drawSurface(canvas, clicking)
|
||||
val cx = if (touching) originX else width / 2f
|
||||
val cy = if (touching) originY else height / 2f
|
||||
ring.strokeWidth = 2 * density
|
||||
ring.color = if (touching) ACCENT else LINE
|
||||
canvas.drawCircle(cx, cy, reach(), ring)
|
||||
knob.color = if (touching) ACCENT else KNOB
|
||||
canvas.drawCircle(cx + knobX, cy + knobY, reach() * 0.45f, knob)
|
||||
}
|
||||
|
||||
@SuppressLint("ClickableViewAccessibility")
|
||||
override fun onTouchEvent(event: MotionEvent): Boolean {
|
||||
val r = reach().coerceAtLeast(1f)
|
||||
when (event.actionMasked) {
|
||||
MotionEvent.ACTION_DOWN -> {
|
||||
downAt = event.eventTime
|
||||
downX = event.x
|
||||
downY = event.y
|
||||
travel = 0f
|
||||
originX = if (floating) event.x else width / 2f
|
||||
originY = if (floating) event.y else height / 2f
|
||||
touching = true
|
||||
performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
|
||||
if (lastUp != 0L && event.eventTime - lastUp < CLICK_MS) setClick(true)
|
||||
follow(event.x, event.y, r, force = true)
|
||||
}
|
||||
MotionEvent.ACTION_MOVE -> follow(event.getX(0), event.getY(0), r)
|
||||
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
|
||||
touching = false
|
||||
val cancelled = event.actionMasked == MotionEvent.ACTION_CANCEL || event.flags and MotionEvent.FLAG_CANCELED != 0
|
||||
travel = maxOf(travel, hypot(event.x - downX, event.y - downY))
|
||||
lastUp = if (!clicking && !cancelled && event.eventTime - downAt <= STICK_TAP_MS && travel <= tapSlop) event.eventTime else 0L
|
||||
setClick(false)
|
||||
move(0f, 0f, 1f)
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
private fun follow(x: Float, y: Float, r: Float, force: Boolean = false) {
|
||||
travel = maxOf(travel, hypot(x - downX, y - downY))
|
||||
var dx = x - originX
|
||||
var dy = y - originY
|
||||
val length = hypot(dx, dy)
|
||||
if (length > r) { dx *= r / length; dy *= r / length }
|
||||
if (force || dx != knobX || dy != knobY) move(dx, dy, r)
|
||||
}
|
||||
|
||||
private fun move(dx: Float, dy: Float, r: Float) {
|
||||
knobX = dx
|
||||
knobY = dy
|
||||
source?.update(dx / r, dy / r)
|
||||
invalidate()
|
||||
}
|
||||
|
||||
private fun setClick(down: Boolean) {
|
||||
if (clicking == down) return
|
||||
clicking = down
|
||||
if (down) performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
|
||||
source?.click(down)
|
||||
}
|
||||
|
||||
override fun onDetachedFromWindow() {
|
||||
setClick(false)
|
||||
if (knobX != 0f || knobY != 0f) move(0f, 0f, 1f)
|
||||
super.onDetachedFromWindow()
|
||||
}
|
||||
}
|
||||
|
||||
private inner class DirectionPad(context: Context, private val source: InputSurfaceSource? = null) : View(context) {
|
||||
private val density = resources.displayMetrics.density
|
||||
private var held = 0
|
||||
private val arm = Paint(Paint.ANTI_ALIAS_FLAG)
|
||||
private val rect = RectF()
|
||||
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
val size = min(width, height) * 0.86f
|
||||
val cx = width / 2f
|
||||
val cy = height / 2f
|
||||
val half = size / 2f
|
||||
val thick = size / 3f / 2f
|
||||
fun armRect(bit: Int, l: Float, t: Float, r: Float, b: Float) {
|
||||
arm.color = if (held and bit != 0) ACCENT else KNOB
|
||||
rect.set(l, t, r, b)
|
||||
canvas.drawRoundRect(rect, 8 * density, 8 * density, arm)
|
||||
}
|
||||
armRect(1, cx - thick, cy - half, cx + thick, cy - thick)
|
||||
armRect(4, cx - thick, cy + thick, cx + thick, cy + half)
|
||||
armRect(8, cx - half, cy - thick, cx - thick, cy + thick)
|
||||
armRect(2, cx + thick, cy - thick, cx + half, cy + thick)
|
||||
arm.color = KNOB
|
||||
canvas.drawRect(cx - thick, cy - thick, cx + thick, cy + thick, arm)
|
||||
}
|
||||
|
||||
@SuppressLint("ClickableViewAccessibility")
|
||||
override fun onTouchEvent(event: MotionEvent): Boolean {
|
||||
val bits = when (event.actionMasked) {
|
||||
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_MOVE -> {
|
||||
val dx = event.getX(0) - width / 2f
|
||||
val dy = event.getY(0) - height / 2f
|
||||
if (hypot(dx, dy) < min(width, height) * 0.08f) 0 else {
|
||||
val sector = ((Math.toDegrees(atan2(dy.toDouble(), dx.toDouble())) + 360 + 22.5) % 360 / 45).toInt()
|
||||
intArrayOf(2, 2 or 4, 4, 4 or 8, 8, 8 or 1, 1, 1 or 2)[sector]
|
||||
}
|
||||
}
|
||||
else -> 0
|
||||
}
|
||||
set(bits)
|
||||
return true
|
||||
}
|
||||
|
||||
private fun set(bits: Int) {
|
||||
if (bits == held) return
|
||||
if (bits and held.inv() != 0) performHapticFeedback(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))
|
||||
|
||||
invalidate()
|
||||
}
|
||||
|
||||
override fun onDetachedFromWindow() {
|
||||
set(0)
|
||||
super.onDetachedFromWindow()
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val CLICK_MS = 300L
|
||||
private const val STICK_TAP_MS = 200L
|
||||
|
||||
|
||||
private const val CORNER = 20f
|
||||
private const val CORNER_PILL = 22f
|
||||
private val ACCENT = Color.rgb(0x1A, 0x9F, 0xFF)
|
||||
private val ACCENT_WASH = Color.argb(0x2E, 0x1A, 0x9F, 0xFF)
|
||||
private val ACCENT_GLOW = Color.argb(0x66, 0x1A, 0x9F, 0xFF)
|
||||
private val ON_ACCENT = Color.rgb(0x03, 0x11, 0x1F)
|
||||
private val SURFACE = Color.rgb(0x0A, 0x0B, 0x0D)
|
||||
private val LINE = Color.rgb(0x26, 0x29, 0x2E)
|
||||
private val GUIDE = Color.rgb(0x16, 0x18, 0x1B)
|
||||
private val TEXT = Color.rgb(0xF2, 0xF4, 0xF7)
|
||||
private val TEXT_DIM = Color.rgb(0x7A, 0x80, 0x8A)
|
||||
private val KNOB = Color.rgb(0x2A, 0x2D, 0x33)
|
||||
|
||||
internal fun dp(context: Context, value: Int): Int = (value * context.resources.displayMetrics.density + 0.5f).toInt()
|
||||
|
||||
internal fun outline(context: Context, radius: Float, fill: Int) = GradientDrawable().apply {
|
||||
cornerRadius = radius * context.resources.displayMetrics.density
|
||||
setColor(fill)
|
||||
setStroke(dp(context, 1), LINE)
|
||||
}
|
||||
|
||||
internal fun roundButton(context: Context, label: String, description: String, onClick: () -> Unit, wide: Boolean = false) =
|
||||
TextView(context).apply {
|
||||
text = label
|
||||
contentDescription = description
|
||||
textSize = if (wide) 13f else 20f
|
||||
typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
|
||||
letterSpacing = if (wide) 0.08f else 0f
|
||||
gravity = Gravity.CENTER
|
||||
setTextColor(TEXT)
|
||||
background = outline(context, CORNER_PILL, SURFACE)
|
||||
setPadding(if (wide) dp(context, 16) else 0, 0, if (wide) dp(context, 16) else 0, 0)
|
||||
minWidth = dp(context, 44)
|
||||
layoutParams = LinearLayout.LayoutParams(if (wide) LinearLayout.LayoutParams.WRAP_CONTENT else dp(context, 44), dp(context, 44))
|
||||
setOnClickListener {
|
||||
performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
|
||||
onClick()
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
+7
-4
@@ -52,13 +52,16 @@ import com.droiddeck.launcher.input.PcKey
|
||||
import com.droiddeck.launcher.input.pcKeyLabel
|
||||
|
||||
@Composable
|
||||
fun ScreenKeyPicker(
|
||||
fun KeyCombinationPicker(
|
||||
onDismiss: () -> Unit,
|
||||
onAdd: (List<Int>) -> Unit,
|
||||
initial: List<Int> = emptyList(),
|
||||
sequence: Boolean = false,
|
||||
sequenceLimit: Int = 4,
|
||||
allowEmpty: Boolean = false,
|
||||
slots: List<String> = emptyList(),
|
||||
title: String = stringResource(R.string.input_keys),
|
||||
confirm: String = stringResource(R.string.gesture_save_changes),
|
||||
) {
|
||||
var picked by remember { mutableStateOf(initial) }
|
||||
val p = LocalPalette.current
|
||||
@@ -86,7 +89,7 @@ fun ScreenKeyPicker(
|
||||
) {
|
||||
Column {
|
||||
Row(Modifier.fillMaxWidth().padding(start = 16.dp, end = 6.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(stringResource(R.string.screen_keys_add), Modifier.weight(1f), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
|
||||
Text(title, Modifier.weight(1f), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
|
||||
IconButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Icon(Icons.Default.Close, null) }
|
||||
}
|
||||
Row(
|
||||
@@ -136,10 +139,10 @@ fun ScreenKeyPicker(
|
||||
Row(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Button(
|
||||
onClick = { onAdd(picked) },
|
||||
enabled = picked.isNotEmpty(),
|
||||
enabled = allowEmpty || picked.isNotEmpty(),
|
||||
modifier = Modifier.weight(1f).focusGlide(CircleShape),
|
||||
) {
|
||||
Text(stringResource(R.string.screen_keys_add))
|
||||
Text(confirm)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -120,6 +120,7 @@ class ModeSettingsActions(
|
||||
val onSteamDownloadsInBackground: (Boolean) -> Unit = {},
|
||||
val onPipAutoEnter: (Boolean) -> Unit = {},
|
||||
val onOsc: (String) -> Unit,
|
||||
val onInputSettings: () -> Unit,
|
||||
val onBackHold: (Boolean) -> Unit = {},
|
||||
val onBackActionsInverted: (Boolean) -> Unit = {},
|
||||
val onDirectAudio: (Boolean) -> Unit,
|
||||
@@ -259,6 +260,7 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
|
||||
extras.drivers(s.gpuDrivers)
|
||||
}
|
||||
if (tab == SheetTab.CONTROLS) {
|
||||
InputQuickSettings(host, desktop = s.mode == SessionService.MODE_DESKTOP, onEdit = a.onInputSettings)
|
||||
SettingsGroup(if (steam) stringResource(R.string.mode_touch_controls) else stringResource(R.string.mode_touch)) {
|
||||
ChoiceRow(
|
||||
host, "touch", stringResource(R.string.mode_touch), null,
|
||||
|
||||
@@ -36,6 +36,7 @@ import androidx.compose.ui.window.DialogProperties
|
||||
import androidx.compose.ui.window.DialogWindowProvider
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.input.PhysicalShortcuts
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
|
||||
@Composable
|
||||
internal fun PhysicalShortcutRows(
|
||||
@@ -48,14 +49,22 @@ internal fun PhysicalShortcutRows(
|
||||
Column {
|
||||
for (action in PhysicalShortcuts.Action.entries) {
|
||||
val assigned = bindings.filter { it.action == action }
|
||||
val inverted = SessionPrefs.backActionsInverted(context)
|
||||
val default = stringResource(when (action) {
|
||||
PhysicalShortcuts.Action.STEAM -> R.string.input_shortcut_guide
|
||||
PhysicalShortcuts.Action.QAM -> if (inverted) R.string.input_shortcut_back_once else R.string.input_shortcut_back_twice
|
||||
PhysicalShortcuts.Action.DROIDDECK -> if (inverted) R.string.input_shortcut_back_modes else R.string.input_shortcut_back_once
|
||||
})
|
||||
SettingsRow(
|
||||
stringResource(action.label),
|
||||
assigned.joinToString { "${it.button.label} · ${it.button.name}" }.ifEmpty { null },
|
||||
assigned.joinToString { "${it.button.label} · ${it.button.name}" }.ifEmpty {
|
||||
if (action == PhysicalShortcuts.Action.QAM && SessionPrefs.backHold(context)) context.getString(R.string.input_shortcut_hold_hint) else null
|
||||
},
|
||||
) {
|
||||
SecondaryButton(
|
||||
stringResource(if (assigned.isEmpty()) R.string.game_settings_default else R.string.ctrl_custom),
|
||||
if (assigned.isEmpty()) default else assigned.map { it.button.label }.distinct().joinToString(" / "),
|
||||
compact = true,
|
||||
modifier = modifierFor(action).width(LocalChipMinWidth.current)
|
||||
modifier = modifierFor(action).widthIn(min = LocalChipMinWidth.current, max = 240.dp)
|
||||
.testTag("shortcuts-assign-${action.name}"),
|
||||
) { editing = action }
|
||||
}
|
||||
@@ -165,6 +174,12 @@ internal fun PhysicalShortcutsDialog(
|
||||
modifier = Modifier.testTag("shortcuts-remove"),
|
||||
)
|
||||
}
|
||||
SecondaryButton(stringResource(R.string.input_restore_shortcut), enabled = bindings.any { it.action == action },
|
||||
modifier = Modifier.testTag("shortcuts-restore-default")) {
|
||||
PhysicalShortcuts.restoreDefault(context, action)
|
||||
onChanged()
|
||||
onDismiss()
|
||||
}
|
||||
SecondaryButton(stringResource(R.string.common_close), modifier = Modifier.testTag("shortcuts-cancel"),
|
||||
onClick = onDismiss)
|
||||
}
|
||||
@@ -174,7 +189,7 @@ internal fun PhysicalShortcutsDialog(
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CaptureShortcutKeys(onKey: (KeyEvent) -> Boolean) {
|
||||
internal fun CaptureShortcutKeys(onKey: (KeyEvent) -> Boolean) {
|
||||
val currentOnKey by rememberUpdatedState(onKey)
|
||||
val window = (LocalView.current.parent as DialogWindowProvider).window
|
||||
DisposableEffect(window) {
|
||||
|
||||
@@ -1,368 +0,0 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import android.net.Uri
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.gestures.detectDragGestures
|
||||
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.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.offset
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.systemBarsPadding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.BasicTextField
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.Delete
|
||||
import androidx.compose.material.icons.filled.DragIndicator
|
||||
import androidx.compose.material.icons.filled.Image
|
||||
import androidx.compose.material.icons.filled.Keyboard
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Slider
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.focus.onFocusChanged
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.platform.LocalConfiguration
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.IntOffset
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.input.SCREEN_KEY_CIRCLE
|
||||
import com.droiddeck.launcher.input.SCREEN_KEY_DPAD
|
||||
import com.droiddeck.launcher.input.SCREEN_KEY_PILL
|
||||
import com.droiddeck.launcher.input.SCREEN_KEY_RECT
|
||||
import com.droiddeck.launcher.input.SCREEN_KEY_ROUND
|
||||
import com.droiddeck.launcher.input.SCREEN_KEY_STICK
|
||||
import com.droiddeck.launcher.input.SCREEN_KEY_TRIGGER
|
||||
import com.droiddeck.launcher.input.ScreenKeys
|
||||
import com.droiddeck.launcher.input.pcKeyLabel
|
||||
import com.droiddeck.launcher.input.screenKeyDirections
|
||||
import java.io.File
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
private val PANEL_WIDTH = 600.dp
|
||||
private val CHIP_PADDING = androidx.compose.foundation.layout.PaddingValues(horizontal = 6.dp, vertical = 2.dp)
|
||||
|
||||
@Composable
|
||||
fun ScreenKeyEditor(
|
||||
codes: List<Int>,
|
||||
keyY: Float,
|
||||
size: Int,
|
||||
opacity: Float,
|
||||
shape: Int,
|
||||
toggle: Boolean,
|
||||
labels: Boolean,
|
||||
text: String,
|
||||
hasImage: Boolean,
|
||||
onResize: (Int) -> Unit,
|
||||
onOpacity: (Float) -> Unit,
|
||||
onShape: (Int) -> Unit,
|
||||
onToggle: (Boolean) -> Unit,
|
||||
onLabels: (Boolean) -> Unit,
|
||||
onText: (String) -> Unit,
|
||||
onImage: (String) -> Unit,
|
||||
onClearImage: () -> Unit,
|
||||
onBind: () -> Unit,
|
||||
onTextFocus: () -> Unit,
|
||||
onTextBlur: () -> Unit,
|
||||
onDirection: (Int) -> Unit,
|
||||
onRemove: () -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
val p = LocalPalette.current
|
||||
val context = LocalContext.current
|
||||
var offset by remember(codes) { mutableStateOf(Offset.Zero) }
|
||||
val density = LocalDensity.current
|
||||
val screen = LocalConfiguration.current
|
||||
val panelWidthPx = with(density) { PANEL_WIDTH.toPx() }
|
||||
val screenWidthPx = screen.screenWidthDp * density.density
|
||||
val screenHeightPx = screen.screenHeightDp * density.density
|
||||
val atTop = keyY > 0.45f
|
||||
val button = shape <= SCREEN_KEY_RECT
|
||||
val directions = screenKeyDirections(shape)
|
||||
val pickImage = rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) { uri ->
|
||||
if (uri != null) importImage(context, uri, codes)?.let(onImage)
|
||||
}
|
||||
Box(
|
||||
Modifier.fillMaxSize().systemBarsPadding().padding(horizontal = 10.dp, vertical = 6.dp),
|
||||
contentAlignment = if (atTop) Alignment.TopCenter else Alignment.BottomCenter,
|
||||
) {
|
||||
Surface(
|
||||
Modifier.widthIn(max = PANEL_WIDTH).fillMaxWidth()
|
||||
.offset { IntOffset(offset.x.roundToInt(), offset.y.roundToInt()) },
|
||||
shape = RoundedCornerShape(18.dp),
|
||||
color = p.background, contentColor = p.onBackground, border = BorderStroke(1.dp, p.line2),
|
||||
) {
|
||||
Column(Modifier.padding(start = 10.dp, end = 6.dp, top = 2.dp, bottom = 6.dp)) {
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(
|
||||
Icons.Default.DragIndicator, null,
|
||||
tint = p.onBackground.copy(alpha = 0.45f),
|
||||
modifier = Modifier.pointerInput(panelWidthPx, screenWidthPx, screenHeightPx) {
|
||||
detectDragGestures { change, drag ->
|
||||
change.consume()
|
||||
offset = Offset(
|
||||
(offset.x + drag.x).coerceIn(
|
||||
-(screenWidthPx - panelWidthPx) / 2f + 8f,
|
||||
(screenWidthPx - panelWidthPx) / 2f - 8f,
|
||||
),
|
||||
(offset.y + drag.y).coerceIn(
|
||||
-screenHeightPx * if (atTop) 0f else 0.75f,
|
||||
screenHeightPx * if (atTop) 0.75f else 0f,
|
||||
),
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
Box(
|
||||
Modifier.weight(1f).height(36.dp)
|
||||
.background(p.line2.copy(alpha = 0.24f), RoundedCornerShape(9.dp))
|
||||
.padding(horizontal = 10.dp),
|
||||
contentAlignment = Alignment.CenterStart,
|
||||
) {
|
||||
BasicTextField(
|
||||
value = text,
|
||||
onValueChange = { onText(it.take(24)) },
|
||||
singleLine = true,
|
||||
textStyle = TextStyle(
|
||||
color = p.onBackground, fontSize = 13.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
),
|
||||
cursorBrush = androidx.compose.ui.graphics.SolidColor(p.primary),
|
||||
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
|
||||
modifier = Modifier.fillMaxWidth().onFocusChanged {
|
||||
if (it.isFocused) onTextFocus() else onTextBlur()
|
||||
}.focusGlide(),
|
||||
)
|
||||
if (text.isEmpty()) {
|
||||
Text(
|
||||
stringResource(R.string.screen_key_text),
|
||||
color = p.onBackground.copy(alpha = 0.4f),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
}
|
||||
}
|
||||
if (button) {
|
||||
IconButton(onClick = onBind, modifier = Modifier.width(38.dp).focusGlide(CircleShape)) {
|
||||
Icon(
|
||||
Icons.Default.Keyboard, stringResource(R.string.screen_key_bind),
|
||||
tint = p.onBackground.copy(alpha = 0.8f),
|
||||
)
|
||||
}
|
||||
}
|
||||
IconButton(onClick = { pickImage.launch("image/*") }, modifier = Modifier.width(38.dp).focusGlide(CircleShape)) {
|
||||
Icon(
|
||||
Icons.Default.Image, stringResource(R.string.screen_key_image),
|
||||
tint = p.onBackground.copy(alpha = 0.8f),
|
||||
)
|
||||
}
|
||||
if (hasImage) IconButton(onClick = onClearImage, modifier = Modifier.width(34.dp).focusGlide(CircleShape)) {
|
||||
Icon(Icons.Default.Close, stringResource(R.string.screen_key_image_clear), tint = p.error)
|
||||
}
|
||||
IconButton(onClick = onRemove, modifier = Modifier.width(38.dp).focusGlide(CircleShape)) {
|
||||
Icon(Icons.Default.Delete, stringResource(R.string.common_delete), tint = p.error)
|
||||
}
|
||||
IconButton(onClick = onDismiss, modifier = Modifier.width(34.dp).focusGlide(CircleShape)) {
|
||||
Icon(Icons.Default.Close, null, tint = p.onBackground)
|
||||
}
|
||||
}
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(vertical = 2.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
listOf<Pair<Int?, Int>>(
|
||||
(if (button) SCREEN_KEY_PILL else null) to R.string.screen_key_type_button,
|
||||
SCREEN_KEY_TRIGGER to R.string.screen_key_shape_trigger,
|
||||
SCREEN_KEY_DPAD to R.string.touch_dpad,
|
||||
SCREEN_KEY_STICK to R.string.deck_surface_stick,
|
||||
).forEach { (value, label) ->
|
||||
val selected = if (value == null) button else shape == value
|
||||
Chip(stringResource(label), selected, Modifier.weight(1f)) {
|
||||
onShape(if (value == null) (if (button) shape else SCREEN_KEY_PILL) else value)
|
||||
}
|
||||
}
|
||||
Box(Modifier.width(1.dp).height(20.dp).background(p.line2))
|
||||
listOf(
|
||||
SCREEN_KEY_PILL to R.string.screen_key_shape_pill,
|
||||
SCREEN_KEY_ROUND to R.string.screen_key_shape_round,
|
||||
SCREEN_KEY_CIRCLE to R.string.screen_key_shape_circle,
|
||||
SCREEN_KEY_RECT to R.string.screen_key_shape_rect,
|
||||
).forEach { (value, label) ->
|
||||
Chip(
|
||||
stringResource(label), button && shape == value, Modifier.weight(1f), enabled = button,
|
||||
) { onShape(value) }
|
||||
}
|
||||
Box(Modifier.width(1.dp).height(20.dp).background(p.line2))
|
||||
Text(
|
||||
stringResource(R.string.screen_key_toggle), Modifier.padding(start = 6.dp, end = 2.dp),
|
||||
style = MaterialTheme.typography.bodySmall, maxLines = 1,
|
||||
)
|
||||
Switch(checked = toggle, onCheckedChange = onToggle, modifier = Modifier.height(30.dp).focusGlide())
|
||||
}
|
||||
if (directions.isNotEmpty()) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(vertical = 2.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
directions.forEachIndexed { index, arrow ->
|
||||
val code = codes.getOrNull(index) ?: 0
|
||||
Chip(
|
||||
if (code == 0) arrow else "$arrow ${pcKeyLabel(context, code)}",
|
||||
code != 0, Modifier.weight(1f),
|
||||
) { onDirection(index) }
|
||||
}
|
||||
Text(
|
||||
stringResource(R.string.screen_key_text), Modifier.padding(start = 6.dp, end = 2.dp),
|
||||
style = MaterialTheme.typography.bodySmall, maxLines = 1,
|
||||
)
|
||||
Switch(checked = labels, onCheckedChange = onLabels, modifier = Modifier.height(30.dp).focusGlide())
|
||||
}
|
||||
}
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(top = 2.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
KeySlider(
|
||||
label = stringResource(R.string.screen_key_size),
|
||||
value = "$size",
|
||||
current = size.toFloat(),
|
||||
min = ScreenKeys.MIN_SIZE.toFloat(),
|
||||
max = ScreenKeys.MAX_SIZE.toFloat(),
|
||||
modifier = Modifier.weight(1f),
|
||||
) { onResize(it.roundToInt()) }
|
||||
KeySlider(
|
||||
label = stringResource(R.string.screen_key_opacity),
|
||||
value = "${(opacity * 100).roundToInt()}%",
|
||||
current = opacity,
|
||||
min = 0.2f,
|
||||
max = 1f,
|
||||
modifier = Modifier.weight(1f),
|
||||
onChange = onOpacity,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun KeySlider(
|
||||
label: String,
|
||||
value: String,
|
||||
current: Float,
|
||||
min: Float,
|
||||
max: Float,
|
||||
modifier: Modifier,
|
||||
onChange: (Float) -> Unit,
|
||||
) {
|
||||
Row(modifier, verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(label, style = MaterialTheme.typography.bodySmall, maxLines = 1)
|
||||
Slider(current, onChange, Modifier.weight(1f).height(28.dp).focusGlide(), valueRange = min..max)
|
||||
Text(
|
||||
value, Modifier.width(32.dp), style = MaterialTheme.typography.bodySmall,
|
||||
fontWeight = FontWeight.SemiBold, maxLines = 1,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Chip(
|
||||
label: String,
|
||||
selected: Boolean,
|
||||
modifier: Modifier = Modifier,
|
||||
enabled: Boolean = true,
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
val p = LocalPalette.current
|
||||
Box(
|
||||
modifier
|
||||
.background(
|
||||
if (selected) p.primary.copy(alpha = 0.18f) else p.line2.copy(alpha = 0.28f),
|
||||
CircleShape,
|
||||
)
|
||||
.focusGlide(RoundedCornerShape(8.dp)).clickable(enabled = enabled, onClick = onClick)
|
||||
.padding(vertical = 6.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(
|
||||
label, style = MaterialTheme.typography.labelSmall, maxLines = 1, overflow = TextOverflow.Ellipsis,
|
||||
color = when {
|
||||
!enabled -> p.onBackground.copy(alpha = 0.28f)
|
||||
selected -> p.primary
|
||||
else -> p.onBackground.copy(alpha = 0.7f)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun importImage(context: Context, uri: Uri, codes: List<Int>): String? {
|
||||
val dir = File(context.filesDir, ScreenKeys.IMAGE_DIR).apply { mkdirs() }
|
||||
val name = "key_" + codes.joinToString("_") + "_" + System.currentTimeMillis() + ".png"
|
||||
val longest = (ScreenKeys.MAX_SIZE * context.resources.displayMetrics.density).toInt()
|
||||
return runCatching {
|
||||
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
context.contentResolver.openInputStream(uri)?.use { BitmapFactory.decodeStream(it, null, bounds) }
|
||||
val source = maxOf(bounds.outWidth, bounds.outHeight)
|
||||
if (source <= 0) return@runCatching null
|
||||
var sample = 1
|
||||
while (source / (sample * 2) >= longest) sample *= 2
|
||||
val bitmap = context.contentResolver.openInputStream(uri)?.use {
|
||||
BitmapFactory.decodeStream(it, null, BitmapFactory.Options().apply { inSampleSize = sample })
|
||||
} ?: return@runCatching null
|
||||
val scale = longest.toFloat() / maxOf(bitmap.width, bitmap.height)
|
||||
val scaled = if (scale < 1f) {
|
||||
Bitmap.createScaledBitmap(
|
||||
bitmap,
|
||||
(bitmap.width * scale).toInt().coerceAtLeast(1),
|
||||
(bitmap.height * scale).toInt().coerceAtLeast(1),
|
||||
true,
|
||||
)
|
||||
} else {
|
||||
bitmap
|
||||
}
|
||||
try {
|
||||
val saved = File(dir, name).outputStream().use { scaled.compress(Bitmap.CompressFormat.PNG, 100, it) }
|
||||
if (saved) name else null
|
||||
} finally {
|
||||
if (scaled !== bitmap) bitmap.recycle()
|
||||
scaled.recycle()
|
||||
}
|
||||
}.getOrNull().also { if (it == null) File(dir, name).delete() }
|
||||
}
|
||||
@@ -1,139 +0,0 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.clickable
|
||||
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.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.systemBarsPadding
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.droiddeck.launcher.ui.GlideDialog as Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import com.droiddeck.launcher.R
|
||||
|
||||
@Composable
|
||||
fun ScreenLayoutPanel(
|
||||
layouts: List<String>,
|
||||
onSave: (String) -> Unit,
|
||||
onLoad: (String) -> Unit,
|
||||
onDelete: (String) -> Unit,
|
||||
onImport: (String) -> Unit,
|
||||
exportText: () -> String,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
val p = LocalPalette.current
|
||||
val context = LocalContext.current
|
||||
var naming by remember { mutableStateOf(false) }
|
||||
var name by remember { mutableStateOf("") }
|
||||
|
||||
val importer = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
|
||||
if (uri == null) return@rememberLauncherForActivityResult
|
||||
val text = runCatching {
|
||||
context.contentResolver.openInputStream(uri)?.use { it.readBytes().toString(Charsets.UTF_8) }
|
||||
}.getOrNull()
|
||||
if (text != null) onImport(text)
|
||||
}
|
||||
val exporter = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("application/json")) { uri ->
|
||||
if (uri == null) return@rememberLauncherForActivityResult
|
||||
runCatching { context.contentResolver.openOutputStream(uri)?.use { it.write(exportText().toByteArray()) } }
|
||||
}
|
||||
|
||||
Dialog(onDismissRequest = onDismiss, properties = DialogProperties(usePlatformDefaultWidth = false)) {
|
||||
Box(Modifier.fillMaxSize().systemBarsPadding().padding(16.dp), contentAlignment = Alignment.Center) {
|
||||
Surface(
|
||||
Modifier.widthIn(max = 520.dp).fillMaxWidth(), shape = RoundedCornerShape(22.dp),
|
||||
color = p.background, contentColor = p.onBackground, border = BorderStroke(1.dp, p.line2),
|
||||
) {
|
||||
Column(Modifier.padding(start = 20.dp, end = 8.dp, top = 6.dp, bottom = 12.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
stringResource(R.string.screen_key_layout), Modifier.weight(1f),
|
||||
style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold,
|
||||
)
|
||||
IconButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Icon(Icons.Default.Close, null) }
|
||||
}
|
||||
Row(Modifier.fillMaxWidth().padding(end = 12.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
TextButton(onClick = { naming = true }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.screen_key_layout_save)) }
|
||||
TextButton(onClick = { importer.launch(arrayOf("application/json", "text/plain", "*/*")) }, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Text(stringResource(R.string.boot_movie_import))
|
||||
}
|
||||
TextButton(onClick = { exporter.launch("droiddeck-layout.icp") }, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Text(stringResource(R.string.screen_key_layout_export))
|
||||
}
|
||||
}
|
||||
Column(Modifier.padding(end = 12.dp).heightIn(max = 320.dp).verticalScroll(rememberScrollState())) {
|
||||
layouts.forEach { layout ->
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
layout, Modifier.weight(1f).clickable { onLoad(layout) }.padding(vertical = 14.dp),
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
)
|
||||
TextButton(onClick = { onDelete(layout) }, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Text(stringResource(R.string.common_delete), color = p.error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (naming) {
|
||||
Dialog(onDismissRequest = { naming = false }, properties = DialogProperties(usePlatformDefaultWidth = false)) {
|
||||
Box(Modifier.fillMaxSize().systemBarsPadding().padding(16.dp), contentAlignment = Alignment.Center) {
|
||||
Surface(
|
||||
Modifier.widthIn(max = 520.dp).fillMaxWidth(), shape = RoundedCornerShape(22.dp),
|
||||
color = p.background, contentColor = p.onBackground, border = BorderStroke(1.dp, p.line2),
|
||||
) {
|
||||
Column(Modifier.padding(20.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
OutlinedTextField(
|
||||
name, { name = it.take(24) }, Modifier.fillMaxWidth().focusGlide(), singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
|
||||
)
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
|
||||
TextButton(onClick = { naming = false }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) }
|
||||
Button(onClick = { onSave(name.trim()); naming = false }, enabled = name.isNotBlank(), modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Text(stringResource(R.string.screen_key_layout_save))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -29,9 +29,6 @@ import com.droiddeck.launcher.session.SessionState
|
||||
class SecondScreenPresentation(
|
||||
private val sessionActivity: SessionActivity,
|
||||
display: Display,
|
||||
private val sendPointer: (x: Float, y: Float, width: Float, height: Float) -> Unit,
|
||||
private val sendButton: (button: Int, pressed: Boolean) -> Unit,
|
||||
private val sendWheel: (steps: Int) -> Unit,
|
||||
private val onSteamMenu: () -> Unit,
|
||||
private val onQam: () -> Unit,
|
||||
private val onClose: () -> Unit,
|
||||
@@ -62,6 +59,7 @@ class SecondScreenPresentation(
|
||||
private var imeSeen = false
|
||||
private var fieldKeyboard = false
|
||||
private var terminalPanel: SessionTerminalPanel? = null
|
||||
private var controlsView: InputSurfaceView? = null
|
||||
private var created = false
|
||||
|
||||
init {
|
||||
@@ -121,8 +119,9 @@ class SecondScreenPresentation(
|
||||
}
|
||||
|
||||
fun showMode(mode: SecondScreenMode) {
|
||||
if (currentMode == mode && isShowing) return
|
||||
currentMode = mode
|
||||
val next = if (mode == SecondScreenMode.KEYBOARD_TRACKPAD || mode == SecondScreenMode.DECK_CONTROLS) SecondScreenMode.CUSTOM_CONTROLS else mode
|
||||
if (currentMode == next && isShowing) return
|
||||
currentMode = next
|
||||
if (created) renderMode()
|
||||
}
|
||||
|
||||
@@ -161,7 +160,7 @@ class SecondScreenPresentation(
|
||||
view.disposeComposition()
|
||||
}
|
||||
|
||||
val showsKeyboard: Boolean get() = isShowing && !menuShown && currentMode == SecondScreenMode.KEYBOARD_TRACKPAD
|
||||
val showsKeyboard: Boolean get() = isShowing && !menuShown && currentMode == SecondScreenMode.CUSTOM_CONTROLS
|
||||
|
||||
val showsControls: Boolean get() = isShowing && currentMode != SecondScreenMode.NONE
|
||||
|
||||
@@ -214,6 +213,7 @@ class SecondScreenPresentation(
|
||||
dropChat()
|
||||
keyboardHost?.hide()
|
||||
keyboardHost = null
|
||||
controlsView = null
|
||||
dismiss()
|
||||
}
|
||||
|
||||
@@ -236,6 +236,22 @@ class SecondScreenPresentation(
|
||||
return super.dispatchGenericMotionEvent(event)
|
||||
}
|
||||
|
||||
fun refreshControls() {
|
||||
if (!created || currentMode != SecondScreenMode.CUSTOM_CONTROLS) return
|
||||
val controls = controlsView ?: return
|
||||
val layout = com.droiddeck.launcher.input.InputLibraries.read(context)
|
||||
.activeLayout(SessionState.mode == SessionService.MODE_DESKTOP, com.droiddeck.launcher.input.InputRole.SECONDARY)
|
||||
controls.updateCustomLayout(layout?.elements.orEmpty())
|
||||
controls.updateStyle(layout?.style ?: com.droiddeck.launcher.input.InputSurfaceStyle())
|
||||
}
|
||||
|
||||
fun showKeyboard(): Boolean {
|
||||
val host = keyboardHost ?: return false
|
||||
host.toggle()
|
||||
keyboardShown.value = host.shown
|
||||
return true
|
||||
}
|
||||
|
||||
override fun onWindowFocusChanged(hasFocus: Boolean) {
|
||||
super.onWindowFocusChanged(hasFocus)
|
||||
if (hasFocus) {
|
||||
@@ -256,19 +272,28 @@ class SecondScreenPresentation(
|
||||
closeTerminal()
|
||||
closeDashboard()
|
||||
root.removeAllViews()
|
||||
controlsView = null
|
||||
ownComposeViews()
|
||||
val library = com.droiddeck.launcher.input.InputLibraries.read(context)
|
||||
val profileLayout = library.activeLayout(SessionState.mode == SessionService.MODE_DESKTOP, com.droiddeck.launcher.input.InputRole.SECONDARY)
|
||||
val requested = currentMode
|
||||
val mode = when {
|
||||
currentMode == SecondScreenMode.DECK_CONTROLS && !SessionState.deckPad -> SecondScreenMode.NONE
|
||||
currentMode == SecondScreenMode.DASHBOARD && dashboard == null -> SecondScreenMode.NONE
|
||||
currentMode == SecondScreenMode.DESKTOP && !BottomDesktop.available() -> SecondScreenMode.NONE
|
||||
else -> currentMode
|
||||
requested == SecondScreenMode.DASHBOARD && dashboard == null -> SecondScreenMode.NONE
|
||||
requested == SecondScreenMode.DESKTOP && !BottomDesktop.available() -> SecondScreenMode.NONE
|
||||
else -> requested
|
||||
}
|
||||
if (mode == SecondScreenMode.NONE) return
|
||||
|
||||
when (mode) {
|
||||
SecondScreenMode.KEYBOARD_TRACKPAD -> renderKeyboardAndTrackpad()
|
||||
SecondScreenMode.TERMINAL -> renderTerminal()
|
||||
SecondScreenMode.DECK_CONTROLS -> root.addView(DeckControlsPanel(context, onClose, onSteamMenu, onQam, pad, onMenu = onMenu, onSwap = onSwap), weightParams())
|
||||
SecondScreenMode.CUSTOM_CONTROLS -> {
|
||||
val controls = InputSurfaceView(context, pad, profileLayout?.elements.orEmpty(),
|
||||
surfaceStyle = profileLayout?.style ?: com.droiddeck.launcher.input.InputSurfaceStyle())
|
||||
controlsView = controls
|
||||
root.addView(controls, weightParams())
|
||||
attachKeyboard()
|
||||
}
|
||||
SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.DECK_CONTROLS -> Unit
|
||||
SecondScreenMode.DASHBOARD -> renderDashboard()
|
||||
SecondScreenMode.DESKTOP -> {
|
||||
root.addView(BottomDesktopPanel(context, onClose, onMenu,
|
||||
@@ -299,17 +324,7 @@ class SecondScreenPresentation(
|
||||
dashboardView = null
|
||||
}
|
||||
|
||||
private fun renderKeyboardAndTrackpad() {
|
||||
bar(SecondScreenMode.KEYBOARD_TRACKPAD) {
|
||||
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") {
|
||||
keyboardHost?.let { host ->
|
||||
host.toggle()
|
||||
keyboardShown.value = host.shown
|
||||
}
|
||||
})
|
||||
}
|
||||
root.addView(trackpadView(), weightParams())
|
||||
private fun attachKeyboard() {
|
||||
val host = KeyboardHost(context) { event ->
|
||||
val handled = sessionActivity.dispatchKeyEvent(event)
|
||||
if (fieldKeyboard && event.action == KeyEvent.ACTION_UP &&
|
||||
@@ -321,8 +336,6 @@ class SecondScreenPresentation(
|
||||
root.addView(host, ViewGroup.LayoutParams(1, 1))
|
||||
}
|
||||
|
||||
private fun trackpadView(): View = SessionTrackpadView(context, sendPointer, sendButton, sendWheel)
|
||||
|
||||
private fun renderTerminal() {
|
||||
bar(SecondScreenMode.TERMINAL) {
|
||||
listOf(BarExtra(context.getString(R.string.drawer_keyboard), icon = R.drawable.ic_bottom_keyboard, tag = "bottom-keyboard") {
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
internal enum class SessionDrawerPage(val firstControl: String) {
|
||||
CONTROLLER("touch"),
|
||||
CONTROLLER("input-profile"),
|
||||
GLASSES("glasses-game"),
|
||||
SECOND_SCREEN("second-screen:keyboard-trackpad"),
|
||||
SECOND_SCREEN("second-screen:custom-controls"),
|
||||
DISPLAY("fg"),
|
||||
HUD("hud"),
|
||||
EFFECTS("look"),
|
||||
|
||||
@@ -209,6 +209,7 @@ private class DrawerFocus {
|
||||
|
||||
class DrawerActions(
|
||||
val steam: Boolean,
|
||||
val desktop: Boolean,
|
||||
val direct: Boolean = false,
|
||||
val title: String? = null,
|
||||
val isHomeApp: Boolean,
|
||||
@@ -275,9 +276,6 @@ class DrawerActions(
|
||||
val onEditSteamTouch: (() -> Unit)? = null,
|
||||
val controller: com.droiddeck.launcher.input.ControllerPrefs.Settings? = null,
|
||||
val onRumble: (Boolean) -> Unit = {},
|
||||
val onSteamButton: (Boolean) -> Unit = {},
|
||||
val onQamButton: (Boolean) -> Unit = {},
|
||||
val onKeyboardButton: (Boolean) -> Unit = {},
|
||||
val onSuspendPolicy: (String) -> Unit,
|
||||
val onSteamDownloadsInBackground: (Boolean) -> Unit = {},
|
||||
val onBackActionsInverted: (Boolean) -> Unit,
|
||||
@@ -290,14 +288,12 @@ class DrawerActions(
|
||||
val directCursor: Boolean = false,
|
||||
val onDirectCursor: (Boolean) -> Unit = {},
|
||||
val onTouch: (String) -> Unit,
|
||||
val onInputSettings: () -> Unit = {},
|
||||
val onInputSelection: (com.droiddeck.launcher.input.InputRole?) -> Unit = {},
|
||||
val onGestureSettings: () -> Unit = {},
|
||||
val touchActive: String = "",
|
||||
val directHoldBehavior: String = MOUSE_BEHAVIOR_CLICK,
|
||||
val onDirectHoldBehavior: (String) -> Unit = {},
|
||||
val onScreenKeys: (() -> Unit)? = null,
|
||||
val onScreenLayouts: (() -> Unit)? = null,
|
||||
val screenKeysShown: Boolean = true,
|
||||
val onScreenKeysShown: (Boolean) -> Unit = {},
|
||||
val onFexPreset: (String) -> Unit,
|
||||
val onUpscaler: (Int) -> Unit = {},
|
||||
val onUpscaleSharpness: (Int) -> Unit = {},
|
||||
@@ -325,7 +321,6 @@ class DrawerActions(
|
||||
val onStop: () -> Unit,
|
||||
val onStopFrom: ((androidx.compose.ui.geometry.Rect?) -> Unit)? = null,
|
||||
val onClose: () -> Unit,
|
||||
val onDismissScreen: (() -> Unit)? = null,
|
||||
val components: ComponentsManager.Snapshot? = null,
|
||||
val systemPowerVr: Boolean = false,
|
||||
val onComponentsRefresh: () -> Unit = {},
|
||||
@@ -431,7 +426,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
page == SessionDrawerPage.GLASSES -> "glasses-tab-$glassesTab"
|
||||
page == SessionDrawerPage.SESSION && a.isHomeApp -> "apps"
|
||||
page == SessionDrawerPage.SECOND_SCREEN -> "second-screen:" +
|
||||
(if (a.secondScreenMode == SecondScreenMode.NONE && !a.secondScreenNone) SecondScreenMode.KEYBOARD_TRACKPAD else a.secondScreenMode).id
|
||||
(if (a.secondScreenMode == SecondScreenMode.NONE && !a.secondScreenNone) SecondScreenMode.CUSTOM_CONTROLS else a.secondScreenMode).id
|
||||
else -> page.firstControl
|
||||
}
|
||||
if (turned) focus.forget(page)
|
||||
@@ -489,7 +484,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
) {
|
||||
SteamActionPill(
|
||||
stringResource(R.string.common_close), Icons.Outlined.Close, focus.track(page, "close"),
|
||||
) { host.open = null; (a.onDismissScreen ?: a.onClose)() }
|
||||
) { host.open = null; a.onClose() }
|
||||
if (roomyHeader) Spacer(Modifier.weight(1f))
|
||||
SteamActionPill(
|
||||
stringResource(R.string.stores_dl_pause), Icons.Outlined.Pause, focus.track(page, "pause"),
|
||||
@@ -595,8 +590,11 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
}
|
||||
SessionDrawerPage.CONTROLLER -> {
|
||||
SettingsGroup(stringResource(R.string.drawer_page_controller)) {
|
||||
InputQuickSettings(host, desktop = a.desktop, onChanged = a.onInputSelection, onEdit = a.onInputSettings) { key -> focus.track(page, key) }
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.input_device_settings)) {
|
||||
a.padType?.let { type ->
|
||||
ChoiceRow(host, "pad-type", stringResource(R.string.mode_controller), null,
|
||||
ChoiceRow(host, "pad-type", stringResource(R.string.input_virtual_controller), stringResource(R.string.input_virtual_controller_hint),
|
||||
listOf(SessionPrefs.CONTROLLER_DECK to stringResource(R.string.mode_controller_deck),
|
||||
SessionPrefs.CONTROLLER_STEAM to stringResource(R.string.mode_controller_steam),
|
||||
SessionPrefs.CONTROLLER_DS4 to stringResource(R.string.mode_controller_ds4),
|
||||
@@ -604,43 +602,35 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
SessionPrefs.CONTROLLER_XBOX360 to stringResource(R.string.mode_controller_x360)),
|
||||
type, chipModifier = focus.track(page, "pad-type"), onPick = a.onPadType)
|
||||
}
|
||||
ChoiceRow(host, "touch", stringResource(R.string.mode_touch), null,
|
||||
a.controller?.let { c ->
|
||||
ToggleRow(host, "rumble", stringResource(R.string.ctrl_rumble), null, c.rumble,
|
||||
chipModifier = focus.track(page, "rumble"), onChange = a.onRumble)
|
||||
|
||||
}
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.input_touchscreen)) {
|
||||
ChoiceRow(host, "touch", stringResource(R.string.input_touchscreen), stringResource(R.string.input_touchscreen_hint),
|
||||
listOf(SessionPrefs.TOUCH_AUTO to stringResource(R.string.drawer_touch_auto, a.touchAuto), SessionPrefs.TOUCH_PAD to stringResource(R.string.mode_touch_touchpad), SessionPrefs.TOUCH_DIRECT to stringResource(R.string.mode_touch_direct), SessionPrefs.TOUCH_GESTURES to stringResource(R.string.mode_touch_gestures), SessionPrefs.TOUCH_OFF to stringResource(R.string.widgets_off)),
|
||||
a.touchMode, chipModifier = focus.track(page, "touch"), onPick = a.onTouch)
|
||||
if (a.touchActive == SessionPrefs.TOUCH_PAD)
|
||||
RelativeMouseRow(host, a, focus.track(page, "relative-mouse"))
|
||||
if (a.touchActive == SessionPrefs.TOUCH_DIRECT)
|
||||
ToggleRow(host, "direct-cursor", stringResource(R.string.drawer_direct_cursor),
|
||||
null, a.directCursor,
|
||||
ToggleRow(host, "direct-cursor", stringResource(R.string.input_touch_cursor),
|
||||
stringResource(R.string.input_touch_cursor_hint), a.directCursor,
|
||||
chipModifier = focus.track(page, "direct-cursor"), onChange = a.onDirectCursor)
|
||||
when (a.touchActive) {
|
||||
SessionPrefs.TOUCH_GESTURES -> ActionRow(stringResource(R.string.gesture_settings), null,
|
||||
stringResource(R.string.ctrl_edit), a.onGestureSettings,
|
||||
modifier = focus.track(page, "gesture-settings"))
|
||||
SessionPrefs.TOUCH_DIRECT -> ChoiceRow(host, "long-press", stringResource(R.string.gesture_long_press), null,
|
||||
SessionPrefs.TOUCH_DIRECT -> ChoiceRow(host, "long-press", stringResource(R.string.input_touch_hold), stringResource(R.string.input_touch_hold_hint),
|
||||
listOf(MOUSE_BEHAVIOR_NONE to stringResource(R.string.gesture_hold_left),
|
||||
MOUSE_BEHAVIOR_CLICK to stringResource(R.string.gesture_right_click),
|
||||
MOUSE_BEHAVIOR_HOLD to stringResource(R.string.gesture_hold_right)),
|
||||
a.directHoldBehavior, chipModifier = focus.track(page, "long-press"),
|
||||
onPick = a.onDirectHoldBehavior)
|
||||
}
|
||||
if (a.onScreenKeys != null) {
|
||||
SettingsRow(stringResource(R.string.screen_keys), null, stacked = narrow) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
SecondaryButton(stringResource(R.string.ctrl_edit), enabled = a.screenKeysShown,
|
||||
modifier = focus.track(page, "screen-keys"), onClick = a.onScreenKeys)
|
||||
a.onScreenLayouts?.let { open ->
|
||||
SecondaryButton(stringResource(R.string.screen_key_layout),
|
||||
modifier = focus.track(page, "screen-key-layouts"), onClick = open)
|
||||
}
|
||||
ToggleSwitch(a.screenKeysShown, true,
|
||||
modifier = focus.track(page, "screen-keys-shown"), onChange = a.onScreenKeysShown)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.input_screen_visibility)) {
|
||||
ChoiceRow(host, "osc", stringResource(R.string.mode_osc), null,
|
||||
if (a.steam) listOf(SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto), SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always), SessionPrefs.OSC_STEAM_TOUCH to stringResource(R.string.osc_steam_touch), SessionPrefs.OSC_STEAM_QAM to stringResource(R.string.mode_osc_qam), SessionPrefs.OSC_NEVER to stringResource(R.string.common_never))
|
||||
else listOf(SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto), SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always), SessionPrefs.OSC_NEVER to stringResource(R.string.common_never)),
|
||||
@@ -649,30 +639,6 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
a.onEditSteamTouch?.let { edit ->
|
||||
ActionRow(stringResource(R.string.osc_steam_layout), stringResource(R.string.osc_steam_layout_hint), stringResource(R.string.ctrl_edit), edit)
|
||||
}
|
||||
a.controller?.let { c ->
|
||||
ToggleRow(host, "rumble", stringResource(R.string.ctrl_rumble), null, c.rumble,
|
||||
chipModifier = focus.track(page, "rumble"), onChange = a.onRumble)
|
||||
if (a.onScreenButtonsVisible) {
|
||||
if (a.steam) {
|
||||
ToggleRow(host, "steam-button", stringResource(R.string.ctrl_steam_button), null, c.steamButton,
|
||||
chipModifier = focus.track(page, "steam-button"), onChange = a.onSteamButton)
|
||||
ToggleRow(host, "qam-button", stringResource(R.string.ctrl_qam_button), null, c.qamButton,
|
||||
chipModifier = focus.track(page, "qam-button"), onChange = a.onQamButton)
|
||||
}
|
||||
ToggleRow(host, "keyboard-button", stringResource(R.string.ctrl_keyboard_button), null, c.keyboardButton,
|
||||
chipModifier = focus.track(page, "keyboard-button"), onChange = a.onKeyboardButton)
|
||||
}
|
||||
}
|
||||
if (a.steam) ToggleRow(host, "back-hold", stringResource(R.string.back_hold),
|
||||
stringResource(R.string.back_hold_hint), a.backHold,
|
||||
chipModifier = focus.track(page, "back-hold"), onChange = a.onBackHold)
|
||||
if (a.steam) ChoiceRow(host, "back-actions", stringResource(R.string.mode_back), null,
|
||||
listOf(false to stringResource(SessionPrefs.BACK_MENU_THEN_QAM), true to stringResource(SessionPrefs.BACK_QAM_THEN_MENU)),
|
||||
a.backActionsInverted, chipModifier = focus.track(page, "back-actions"), onPick = a.onBackActionsInverted)
|
||||
if (a.steam) ChoiceRow(host, "back-double-tap", stringResource(R.string.back_double_tap_window), null,
|
||||
SessionPrefs.BACK_DOUBLE_TAP_MS_OPTIONS.map { it to stringResource(R.string.back_tap_ms, it) },
|
||||
a.backDoubleTapMs, chipModifier = focus.track(page, "back-double-tap"), onPick = a.onBackDoubleTapMs)
|
||||
PhysicalShortcutRows(modifierFor = { focus.track(page, "physical-shortcut-${it.name}") })
|
||||
if (a.steam && a.unfoldedControls != null) ToggleRow(host, "unfolded-controls", stringResource(R.string.unfolded_controls),
|
||||
stringResource(R.string.unfolded_controls_hint), a.unfoldedControls,
|
||||
chipModifier = focus.track(page, "unfolded-controls"), onChange = a.onUnfoldedControls)
|
||||
@@ -682,6 +648,18 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
chipModifier = focus.track(page, "unfolded-controls-with-controller"),
|
||||
onChange = a.onUnfoldedControlsWithController)
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.shortcuts_title)) {
|
||||
if (a.steam) ToggleRow(host, "back-hold", stringResource(R.string.back_hold),
|
||||
stringResource(R.string.back_hold_hint), a.backHold,
|
||||
chipModifier = focus.track(page, "back-hold"), onChange = a.onBackHold)
|
||||
if (a.steam) ChoiceRow(host, "back-actions", stringResource(R.string.input_back_taps), stringResource(R.string.input_back_taps_hint),
|
||||
listOf(false to stringResource(SessionPrefs.BACK_MENU_THEN_QAM), true to stringResource(SessionPrefs.BACK_QAM_THEN_MENU)),
|
||||
a.backActionsInverted, chipModifier = focus.track(page, "back-actions"), onPick = a.onBackActionsInverted)
|
||||
if (a.steam) ChoiceRow(host, "back-double-tap", stringResource(R.string.back_double_tap_window), null,
|
||||
SessionPrefs.BACK_DOUBLE_TAP_MS_OPTIONS.map { it to stringResource(R.string.back_tap_ms, it) },
|
||||
a.backDoubleTapMs, chipModifier = focus.track(page, "back-double-tap"), onPick = a.onBackDoubleTapMs)
|
||||
PhysicalShortcutRows(modifierFor = { focus.track(page, "physical-shortcut-${it.name}") })
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.drawer_latency)) {
|
||||
ToggleRow(host, "low-latency", stringResource(R.string.drawer_low_latency),
|
||||
stringResource(R.string.drawer_low_latency_hint), a.lowLatency,
|
||||
@@ -1174,8 +1152,7 @@ private fun SteamVrRow(a: DrawerActions) {
|
||||
}
|
||||
|
||||
internal fun secondScreenModes(none: Boolean, deckPad: Boolean, dashboard: Boolean, desktop: Boolean): List<SecondScreenMode> =
|
||||
(if (none) listOf(SecondScreenMode.NONE) else emptyList()) + listOf(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.TERMINAL) +
|
||||
(if (deckPad) listOf(SecondScreenMode.DECK_CONTROLS) else emptyList()) +
|
||||
(if (none) listOf(SecondScreenMode.NONE) else emptyList()) + listOf(SecondScreenMode.CUSTOM_CONTROLS, SecondScreenMode.TERMINAL) +
|
||||
(if (dashboard) listOf(SecondScreenMode.DASHBOARD) else emptyList()) +
|
||||
(if (desktop) listOf(SecondScreenMode.DESKTOP) else emptyList())
|
||||
|
||||
@@ -1185,6 +1162,8 @@ private fun SecondScreenGroup(host: MenuHost, a: DrawerActions, track: (String)
|
||||
val pal = LocalPalette.current
|
||||
val modes = secondScreenModes(a.secondScreenNone, com.droiddeck.launcher.session.SessionState.deckPad, a.dashboardAvailable, a.desktopAvailable)
|
||||
SettingsGroup(stringResource(R.string.drawer_second_screen_mode)) {
|
||||
Text(stringResource(R.string.input_second_mode_hint), Modifier.padding(14.dp),
|
||||
style = MaterialTheme.typography.bodySmall, color = colors.onSurfaceVariant)
|
||||
Column(Modifier.fillMaxWidth().selectableGroup()) {
|
||||
modes.forEach { mode ->
|
||||
val selected = a.secondScreenMode == mode
|
||||
|
||||
@@ -2,21 +2,17 @@ package com.droiddeck.launcher.ui
|
||||
|
||||
import android.content.ClipboardManager
|
||||
import android.content.Context
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Color
|
||||
import android.util.Log
|
||||
import android.view.Gravity
|
||||
import android.view.KeyEvent
|
||||
import android.view.MotionEvent
|
||||
import android.view.View
|
||||
import android.view.ViewConfiguration
|
||||
import android.view.inputmethod.InputMethodManager
|
||||
import android.widget.HorizontalScrollView
|
||||
import android.widget.LinearLayout
|
||||
import android.widget.TextView
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.input.PointerGestures
|
||||
import com.droiddeck.launcher.input.TouchpadGestures
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
import com.droiddeck.launcher.session.SessionTerminal
|
||||
import com.termux.terminal.TerminalEmulator
|
||||
@@ -25,65 +21,6 @@ import com.termux.terminal.TerminalSessionClient
|
||||
import com.termux.view.TerminalView
|
||||
import com.termux.view.TerminalViewClient
|
||||
|
||||
class SessionTrackpadView(
|
||||
context: Context,
|
||||
private val sendPointer: (x: Float, y: Float, width: Float, height: Float) -> Unit,
|
||||
private val sendButton: (button: Int, pressed: Boolean) -> Unit,
|
||||
private val sendWheel: (steps: Int) -> Unit,
|
||||
) : View(context) {
|
||||
private fun dp(value: Int): Int = (value * resources.displayMetrics.density + 0.5f).toInt()
|
||||
|
||||
private val gestures = TouchpadGestures(ViewConfiguration.get(context).scaledTouchSlop.toFloat(),
|
||||
object : PointerGestures.Listener {
|
||||
override fun onMove(x: Float, y: Float) {
|
||||
sendPointer(x, y, width.toFloat(), height.toFloat())
|
||||
invalidate()
|
||||
}
|
||||
|
||||
override fun onButton(button: Int, pressed: Boolean, x: Float, y: Float) {
|
||||
sendPointer(x, y, width.toFloat(), height.toFloat())
|
||||
sendButton(button, pressed)
|
||||
}
|
||||
|
||||
override fun onWheel(steps: Int) = sendWheel(steps)
|
||||
override fun onLongPress() { performHapticFeedback(android.view.HapticFeedbackConstants.LONG_PRESS) }
|
||||
})
|
||||
|
||||
init {
|
||||
isFocusable = true
|
||||
setBackgroundColor(Color.BLACK)
|
||||
}
|
||||
|
||||
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
|
||||
gestures.bounds = android.graphics.RectF(0f, 0f, w.toFloat(), h.toFloat())
|
||||
if (oldw == 0 || oldh == 0) gestures.place(w / 2f, h / 2f)
|
||||
}
|
||||
|
||||
private val surface = android.graphics.RectF()
|
||||
private val fill = android.graphics.Paint(android.graphics.Paint.ANTI_ALIAS_FLAG).apply { color = Color.rgb(0x0A, 0x0B, 0x0D) }
|
||||
private val edge = android.graphics.Paint(android.graphics.Paint.ANTI_ALIAS_FLAG).apply {
|
||||
style = android.graphics.Paint.Style.STROKE
|
||||
color = Color.rgb(0x26, 0x29, 0x2E)
|
||||
strokeWidth = resources.displayMetrics.density
|
||||
}
|
||||
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
val inset = dp(12).toFloat()
|
||||
surface.set(inset, 0f, width - inset, height - inset)
|
||||
if (surface.height() <= inset) return
|
||||
val radius = dp(20).toFloat()
|
||||
canvas.drawRoundRect(surface, radius, radius, fill)
|
||||
canvas.drawRoundRect(surface, radius, radius, edge)
|
||||
}
|
||||
|
||||
override fun onTouchEvent(event: MotionEvent): Boolean = gestures.onTouch(event)
|
||||
|
||||
override fun onDetachedFromWindow() {
|
||||
gestures.cancel()
|
||||
super.onDetachedFromWindow()
|
||||
}
|
||||
}
|
||||
|
||||
class SessionTerminalPanel(context: Context) : LinearLayout(context) {
|
||||
private var terminalSession: TerminalSession? = null
|
||||
private var terminalView: TerminalView? = null
|
||||
@@ -123,7 +60,7 @@ class SessionTerminalPanel(context: Context) : LinearLayout(context) {
|
||||
val keys = LinearLayout(context).apply { orientation = HORIZONTAL; setPadding(dp(12), 0, dp(12), dp(8)) }
|
||||
fun key(label: String, input: String, onClick: ((TextView) -> Unit)? = null) {
|
||||
lateinit var button: TextView
|
||||
button = DeckControlsPanel.roundButton(context, label, label, { if (onClick != null) onClick(button) else session.write(input) }, wide = true)
|
||||
button = InputSurfaceView.roundButton(context, label, label, { if (onClick != null) onClick(button) else session.write(input) }, wide = true)
|
||||
if (keys.childCount > 0) keys.addView(View(context), LinearLayout.LayoutParams(dp(8), 1))
|
||||
keys.addView(button)
|
||||
}
|
||||
|
||||
@@ -509,16 +509,23 @@ fun <T> ChoiceRow(
|
||||
stacked: Boolean = false,
|
||||
onPick: (T) -> Unit,
|
||||
) {
|
||||
SettingsRow(label, hint, highlighted = host.open == key, hintLines = hintLines, stacked = stacked) {
|
||||
ChoiceChip(host, key, label, options, selected, enabled, note, chipModifier, onPick)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun <T> ChoiceChip(host: MenuHost, key: String, label: String, options: List<Pair<T, String>>, selected: T,
|
||||
enabled: Boolean = true, note: String? = null, modifier: Modifier = Modifier, onPick: (T) -> Unit) {
|
||||
val open = host.open == key
|
||||
SettingsRow(label, hint, highlighted = open, hintLines = hintLines, stacked = stacked) {
|
||||
Box {
|
||||
ValueChip(options.firstOrNull { it.first == selected }?.second ?: "-", open, enabled, modifier = chipModifier.testTag("setting-$key")) { host.open = if (open) null else key }
|
||||
AnchoredMenu(open, onDismiss = { if (host.open == key) host.open = null }, title = label, note = note) { firstItemFocus ->
|
||||
options.forEachIndexed { index, (value, text) ->
|
||||
MenuItem(text, checked = value == selected, focusRequester = if (index == 0) firstItemFocus else null) {
|
||||
onPick(value)
|
||||
host.open = null
|
||||
}
|
||||
Box {
|
||||
ValueChip(options.firstOrNull { it.first == selected }?.second ?: "-", open, enabled,
|
||||
modifier = modifier.testTag("setting-$key")) { host.open = if (open) null else key }
|
||||
AnchoredMenu(open, onDismiss = { if (host.open == key) host.open = null }, title = label, note = note) { firstItemFocus ->
|
||||
options.forEachIndexed { index, (value, text) ->
|
||||
MenuItem(text, checked = value == selected, focusRequester = if (index == 0) firstItemFocus else null) {
|
||||
onPick(value)
|
||||
host.open = null
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -714,6 +721,7 @@ fun SettingsPage(
|
||||
scroll: androidx.compose.foundation.ScrollState? = null,
|
||||
scrollContent: Boolean = true,
|
||||
compactLayout: Boolean = false,
|
||||
showBack: Boolean = true,
|
||||
header: (@Composable () -> Unit)? = null,
|
||||
modifier: Modifier = Modifier,
|
||||
content: @Composable ColumnScope.() -> Unit,
|
||||
@@ -736,7 +744,7 @@ fun SettingsPage(
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
BackLink(stringResource(R.string.mode_back), compact = true, onClick = onBack)
|
||||
if (showBack) BackLink(stringResource(R.string.mode_back), compact = true, onClick = onBack)
|
||||
if (header != null) Box(Modifier.weight(1f)) { header() }
|
||||
}
|
||||
}
|
||||
@@ -746,7 +754,7 @@ fun SettingsPage(
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
modifier = Modifier.padding(bottom = 6.dp),
|
||||
) {
|
||||
BackLink(stringResource(R.string.mode_back), compact = true, onClick = onBack)
|
||||
if (showBack) BackLink(stringResource(R.string.mode_back), compact = true, onClick = onBack)
|
||||
Text(
|
||||
title, fontSize = 20.sp, fontWeight = FontWeight.Bold, color = colors.onBackground,
|
||||
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f),
|
||||
@@ -758,7 +766,7 @@ fun SettingsPage(
|
||||
} else {
|
||||
Rise(0) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
BackLink(stringResource(R.string.mode_back), compact = compactLayout, onClick = onBack)
|
||||
if (showBack) BackLink(stringResource(R.string.mode_back), compact = compactLayout, onClick = onBack)
|
||||
if (eyebrow != null) {
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Eyebrow(eyebrow)
|
||||
|
||||
Reference in new issue
Block a user