This commit is contained in:
loucass003 committed 2026-07-20 19:52:47 +02:00
1 parent 5c4c64e629
commit 9332ff8e02
25 files changed
+1116 -49

No files matched your search

@@ -17,6 +17,9 @@ import dev.slimevr.desktop.install.executeShellCommand
import dev.slimevr.desktop.install.runInstaller
import dev.slimevr.desktop.ipc.createIpcServers
import dev.slimevr.desktop.ipc.createSolarXRWebsocketServer
import dev.slimevr.desktop.keybind.createDesktopKeybindManager
import dev.slimevr.desktop.keybind.isGnome
import dev.slimevr.desktop.keybind.resolveGnomeAppId
import dev.slimevr.desktop.networkprofile.setupDesktopNetworkProfileChecker
import dev.slimevr.desktop.serial.DesktopFirmwareFlasher
import dev.slimevr.desktop.serial.createDesktopSerialServer
@@ -38,8 +41,12 @@ import dev.slimevr.udp.UdpServer
import dev.slimevr.util.safeLaunch
import dev.slimevr.vmc.VMCManager
import dev.slimevr.vrcosc.VRCOSCManager
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import solarxr_protocol.rpc.KeybindSupport
fun main(args: Array<String>) = runBlocking<Unit> {
contextDebugEnabled = System.getProperty("slimevr.debug.context") == "true" ||
@@ -60,6 +67,20 @@ fun main(args: Array<String>) = runBlocking<Unit> {
}
if (CURRENT_PLATFORM != Platform.LINUX) featureFlags.skipCheckUdev = true
// Windows registers hotkeys itself, and on GNOME we can rewrite the triggers it stores in dconf.
// Other compositors own the bindings, so there the user rebinds from the system settings.
featureFlags.keybindSupport = when (CURRENT_PLATFORM) {
Platform.WINDOWS -> KeybindSupport.APP_MANAGED
Platform.LINUX -> if (isGnome() && resolveGnomeAppId() != null) {
KeybindSupport.APP_MANAGED
} else {
KeybindSupport.SYSTEM_MANAGED
}
else -> KeybindSupport.UNSUPPORTED
}
val isInstallDisabled = System.getenv("SLIME_SERVER_DISABLE_INSTALLER")?.toIntOrNull()
if (featureFlags.steam && isInstallDisabled != 1) runInstaller()
@@ -125,16 +146,27 @@ fun main(args: Array<String>) = runBlocking<Unit> {
tapDetectionManager = tapDetectionManager,
)
// JVM shutdown hooks fire on SIGINT/SIGTERM but coroutine `finally` blocks do not,
// so cancel the root scope on shutdown to let structured concurrency run every cleanup.
val rootJob = coroutineContext[Job]!!
Runtime.getRuntime().addShutdownHook(
Thread {
rootJob.cancel()
runBlocking { rootJob.join() }
},
)
try {
appContext.startObserving()
safeLaunch { createDesktopHIDManager(appContext, this) }
safeLaunch { createDesktopKeybindManager(appContext, this) }
safeLaunch { createSolarXRWebsocketServer(appContext) }
safeLaunch { createIpcServers(appContext) }
safeLaunch { setupDesktopNetworkProfileChecker(this, networkProfileManager) }
awaitCancellation()
} finally {
appContext.dispose()
withContext(NonCancellable) { appContext.dispose() }
}
}
@@ -1,7 +1,12 @@
package dev.slimevr.desktop.ipc
import com.google.flatbuffers.FlatBufferBuilder
import dev.hannah.portals.PortalManager
import dev.slimevr.AppContextProvider
import dev.slimevr.AppLogger
import dev.slimevr.CURRENT_PLATFORM
import dev.slimevr.Platform
import dev.slimevr.SLIMEVR_IDENTIFIER
import dev.slimevr.VRServerActions
import dev.slimevr.desktop.unblockSteamVRDriver
import dev.slimevr.fbscodegen.runtime.JvmFlatBufferReader
@@ -13,10 +18,13 @@ import dev.slimevr.util.safeLaunch
import io.ktor.client.HttpClient
import io.ktor.client.engine.cio.CIO
import io.ktor.util.moveToByteArray
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.withContext
import solarxr_protocol.MessageBundle
import solarxr_protocol.rpc.EnableSteamVRDriverRequest
import solarxr_protocol.rpc.OpenKeybindSettingsRequest
import java.nio.ByteBuffer
class EnableSteamVRDriverBehaviour : SolarXRBridgeBehaviour {
@@ -31,6 +39,21 @@ class EnableSteamVRDriverBehaviour : SolarXRBridgeBehaviour {
}
}
class OpenKeybindSettingsBehaviour : SolarXRBridgeBehaviour {
override fun observe(receiver: SolarXRBridge) {
receiver.rpcDispatcher.on<OpenKeybindSettingsRequest> {
if (CURRENT_PLATFORM != Platform.LINUX) return@on
receiver.context.scope.safeLaunch {
withContext(Dispatchers.IO) {
runCatching {
PortalManager(SLIMEVR_IDENTIFIER).openGlobalShortcutsSettings()
}.onFailure { AppLogger.keybind.error(it, "Failed to open global shortcuts settings") }
}
}
}
}
}
suspend fun handleSolarXRBridge(
appContext: AppContextProvider,
messages: Flow<ByteArray>,
@@ -43,6 +66,7 @@ suspend fun handleSolarXRBridge(
extraBehaviours = { _ ->
buildList {
add(EnableSteamVRDriverBehaviour())
add(OpenKeybindSettingsBehaviour())
}
},
)
@@ -0,0 +1,72 @@
package dev.slimevr.desktop.keybind
import dev.slimevr.AppLogger
import dev.slimevr.config.KeybindConfig
import dev.slimevr.desktop.install.executeShellCommand
import java.io.File
private const val GLOBAL_SHORTCUTS_PATH = "/org/gnome/settings-daemon/global-shortcuts"
private val MODIFIERS = linkedMapOf(
"SHIFT" to "<Shift>",
"CTRL" to "<Control>",
"ALT" to "<Alt>",
"SUPER" to "<Super>",
)
fun isGnome(): Boolean = System.getenv("XDG_CURRENT_DESKTOP")?.uppercase()?.contains("GNOME") == true
fun resolveGnomeAppId(): String? {
val cgroup = runCatching { File("/proc/self/cgroup").readText() }.getOrNull() ?: return null
val scope = cgroup.lineSequence()
.map { line -> line.substringAfterLast('/', "") }
.firstOrNull { it.startsWith("app-") && it.endsWith(".scope") }
?: return null
// app-<id>-<instance>.scope, where instance is the pid that launched it
return scope
.removePrefix("app-")
.removeSuffix(".scope")
.substringBeforeLast('-')
.ifEmpty { null }
}
/** Converts our `CTRL+ALT+SHIFT+Y` form into GTK's `<Shift><Control><Alt>y` form. */
private fun toGnomeAccelerator(binding: String): String? {
val parts = binding.split('+').map { it.trim().uppercase() }.filter { it.isNotEmpty() }
val key = parts.firstOrNull { it !in MODIFIERS } ?: return null
val modifiers = parts.filter { it in MODIFIERS }.toSet()
return MODIFIERS.filterKeys { it in modifiers }.values.joinToString("") + key.lowercase()
}
private fun escapeGVariant(value: String): String = value.replace("\\", "\\\\").replace("'", "\\'")
private fun buildGnomeShortcutsVariant(keybinds: List<KeybindConfig>): String = keybinds
.mapNotNull { keybind ->
val accelerator = toGnomeAccelerator(keybind.binding) ?: return@mapNotNull null
"('${escapeGVariant(keybind.id.name)}', {'shortcuts': <['${escapeGVariant(accelerator)}']>, " +
"'description': <'${escapeGVariant(keybindLabel(keybind.id))}'>})"
}
.joinToString(", ", prefix = "[", postfix = "]")
suspend fun gnomeShortcutsExist(appId: String): Boolean {
val (exitCode, output) = executeShellCommand("dconf", "read", "$GLOBAL_SHORTCUTS_PATH/$appId/shortcuts") ?: return false
return exitCode == 0 && output.isNotBlank()
}
suspend fun writeGnomeShortcuts(appId: String, keybinds: List<KeybindConfig>): Boolean {
val bound = keybinds.filter { toGnomeAccelerator(it.binding) != null }
if (bound.isEmpty()) return false
val variant = buildGnomeShortcutsVariant(bound)
val (exitCode, output) = executeShellCommand("dconf", "write", "$GLOBAL_SHORTCUTS_PATH/$appId/shortcuts", variant)
?: return false
if (exitCode != 0) {
AppLogger.keybind.warn("Failed to write GNOME shortcuts for $appId: ${output.trim()}")
return false
}
return true
}
@@ -0,0 +1,154 @@
package dev.slimevr.desktop.keybind
import com.melloware.jintellitype.JIntellitype
import dev.hannah.portals.PortalManager
import dev.hannah.portals.globalShortcuts.GlobalShortcutsHandler
import dev.hannah.portals.globalShortcuts.Shortcut
import dev.hannah.portals.globalShortcuts.ShortcutTuple
import dev.slimevr.AppContextProvider
import dev.slimevr.AppLogger
import dev.slimevr.CURRENT_PLATFORM
import dev.slimevr.Platform
import dev.slimevr.SLIMEVR_IDENTIFIER
import dev.slimevr.config.KeybindConfig
import dev.slimevr.skeleton.SkeletonActions
import dev.slimevr.util.safeLaunch
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.distinctUntilChangedBy
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onEach
import solarxr_protocol.datatypes.BodyPart
import solarxr_protocol.rpc.KeybindId
import solarxr_protocol.rpc.ResetType
private const val KEYBIND_SOURCE = "Keybind"
private val FEET_BODY_PARTS = listOf(BodyPart.LEFT_FOOT, BodyPart.RIGHT_FOOT)
private fun currentKeybinds(appContext: AppContextProvider): List<KeybindConfig> = appContext.config.settings.context.state.value.data.keybinds
private fun bindingsFlow(appContext: AppContextProvider): Flow<List<KeybindConfig>> = appContext.config.settings.context.state
.map { it.data.keybinds }
.distinctUntilChangedBy { keybinds -> keybinds.map { it.id to it.binding } }
fun keybindLabel(id: KeybindId): String = id.name
.split('_')
.joinToString(" ") { word -> word.lowercase().replaceFirstChar { it.uppercase() } }
private fun toJIntellitypeAccelerator(binding: String): String = binding
.split('+')
.joinToString("+") { if (it == "SUPER") "WIN" else it }
private fun triggerKeybind(appContext: AppContextProvider, scope: CoroutineScope, id: KeybindId) {
val delaySeconds = currentKeybinds(appContext).find { it.id == id }?.delay ?: 0f
scope.safeLaunch {
when (id) {
KeybindId.FULL_RESET ->
appContext.resetsManager.scheduleReset(KEYBIND_SOURCE, ResetType.FULL, delaySeconds)
KeybindId.YAW_RESET ->
appContext.resetsManager.scheduleReset(KEYBIND_SOURCE, ResetType.YAW, delaySeconds)
KeybindId.MOUNTING_RESET ->
appContext.resetsManager.scheduleReset(KEYBIND_SOURCE, ResetType.MOUNTING, delaySeconds)
KeybindId.FEET_MOUNTING_RESET ->
appContext.resetsManager.scheduleReset(KEYBIND_SOURCE, ResetType.MOUNTING, delaySeconds, FEET_BODY_PARTS)
KeybindId.PAUSE_TRACKING -> {
if (delaySeconds > 0f) delay((delaySeconds * 1000).toLong())
val skeleton = appContext.skeleton.context
skeleton.dispatch(SkeletonActions.PauseTracking(!skeleton.state.value.paused))
}
KeybindId.NONE -> Unit
}
}
}
suspend fun createDesktopKeybindManager(appContext: AppContextProvider, scope: CoroutineScope) {
when (CURRENT_PLATFORM) {
Platform.WINDOWS -> setupWindowsKeybinds(appContext, scope)
Platform.LINUX -> setupLinuxKeybinds(appContext, scope)
else -> AppLogger.keybind.info("Keybinds are not supported on $CURRENT_PLATFORM")
}
}
private suspend fun setupWindowsKeybinds(appContext: AppContextProvider, scope: CoroutineScope) {
val instance = try {
JIntellitype.getInstance()
} catch (e: Throwable) {
AppLogger.keybind.error(e, "Failed to initialize JIntellitype, keybinds will be disabled")
return
}
instance.addHotKeyListener { identifier ->
KeybindId.fromValue(identifier.toUByte())?.let { triggerKeybind(appContext, scope, it) }
}
var registered: List<KeybindConfig> = emptyList()
bindingsFlow(appContext).onEach { keybinds ->
registered.forEach { runCatching { instance.unregisterHotKey(it.id.value.toInt()) } }
keybinds.forEach { keybind ->
runCatching { instance.registerHotKey(keybind.id.value.toInt(), toJIntellitypeAccelerator(keybind.binding)) }
.onFailure { AppLogger.keybind.warn("Failed to bind ${keybind.id.name} to ${keybind.binding}") }
}
registered = keybinds
}.launchIn(scope)
}
private suspend fun setupLinuxKeybinds(appContext: AppContextProvider, scope: CoroutineScope) {
var handler: GlobalShortcutsHandler? = null
// Closing a handler disconnects its dbus connection, so every session gets its own manager
suspend fun bind(keybinds: List<KeybindConfig>) {
runCatching { handler?.close() }
val shortcuts = keybinds.map { keybind ->
ShortcutTuple(keybind.id.name, Shortcut(keybindLabel(keybind.id), keybind.binding).shortcut)
}.toMutableList()
handler = runCatching {
PortalManager(SLIMEVR_IDENTIFIER).globalShortcutsRequest(shortcuts).apply {
onShortcutActivated = { shortcutId ->
KeybindId.entries.firstOrNull { it.name == shortcutId }?.let { triggerKeybind(appContext, scope, it) }
}
}
}.onFailure {
AppLogger.keybind.error(it, "Failed to register global shortcuts, keybinds will not work")
}.getOrNull()
}
val gnomeAppId = if (isGnome()) resolveGnomeAppId() else null
if (gnomeAppId == null) {
// The compositor owns the triggers and we have no way to change them, so bind once and
// leave it alone. The user rebinds from their system settings instead.
bind(currentKeybinds(appContext))
} else {
// GNOME keeps the triggers in dconf and only reads them when a session is created, so a
// change means rewriting dconf and starting a new session. Its stored values also win over
// the ones we pass, so push the config on startup too or the gui would disagree with what
// actually fires. The exception is a first run, where the portal seeds them and prompts.
val needsSeeding = !gnomeShortcutsExist(gnomeAppId)
var isInitialBind = true
bindingsFlow(appContext).onEach { keybinds ->
if (!(isInitialBind && needsSeeding)) {
writeGnomeShortcuts(gnomeAppId, keybinds)
}
bind(keybinds)
isInitialBind = false
}.launchIn(scope)
}
scope.safeLaunch {
try {
awaitCancellation()
} finally {
runCatching { handler?.close() }
}
}
}