mirror of
https://github.com/kalarina-bit/Matewave.git
synced 2026-11-22 08:06:09 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6137923ca1 | ||
|
|
f59e461405 | ||
|
|
fb58dfb4ae | ||
|
|
2d0e605dfa | ||
|
|
0eb407ead5 | ||
|
|
c6be0cac7a | ||
|
|
e4a6e05cf3 | ||
|
|
a3ec1501e4 | ||
|
|
071430865f | ||
|
|
849e735ed0 | ||
|
|
ae1344d2ec | ||
|
|
c08272fb4a | ||
|
|
5c0f80247f |
@@ -1,54 +1,55 @@
|
||||
<p align="center">
|
||||
<img src="assets/icon-rounded.png" width="128" alt="Matewave icon">
|
||||
<img src="assets/icon-rounded.png" width="112" alt="Matewave icon">
|
||||
</p>
|
||||
|
||||
<h1 align="center">Matewave</h1>
|
||||
|
||||
<p align="center"><b>A beautiful, open-source chess app for Android.</b></p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://git.skysparkle.cc/kalarina/Matewave/releases"><img src="assets/get-it-on-gitea.png" height="60" alt="Get it on Gitea"></a>
|
||||
<b>A beautiful, open-source chess app for Android.</b><br>
|
||||
Play against the AI, solve puzzles, learn openings, or play friends nearby over Bluetooth and Wi-Fi/LAN.
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<img src="https://img.shields.io/badge/Android-8.0%2B-2e7d32?logo=android&logoColor=white&labelColor=1b1b1b" alt="Android 8.0+">
|
||||
<img src="https://img.shields.io/badge/License-GPL--3.0--or--later-2e7d32?labelColor=1b1b1b" alt="GPL-3.0-or-later">
|
||||
<a href="https://github.com/kalarina-bit/Matewave/releases/latest"><img src="https://img.shields.io/github/v/release/kalarina-bit/Matewave?style=for-the-badge&label=release&labelColor=1b1b1b&color=2e7d32" alt="Latest release"></a>
|
||||
</p>
|
||||
|
||||
Play against the AI, solve puzzles, learn openings, or play friends nearby over Bluetooth and Wi-Fi/LAN.
|
||||
<p align="center">
|
||||
<a href="https://f-droid.org/packages/cc.skysparkle.matewave/"><img src="assets/get-it-on%20(1).png" height="56" alt="Get it on F-Droid"></a>
|
||||
<a href="https://apps.obtainium.imranr.dev/redirect?r=obtainium://add/https://git.skysparkle.cc/kalarina/Matewave"><img src="assets/badge_obtainium.png" height="56" alt="Get it on Obtainium"></a>
|
||||
<a href="https://github.com/kalarina-bit/Matewave/releases/latest"><img src="assets/get-it-on-github.png" height="56" alt="Get it on GitHub"></a>
|
||||
<a href="https://git.skysparkle.cc/kalarina/Matewave/releases"><img src="assets/get-it-on-gitea.png" height="56" alt="Get it on Gitea"></a>
|
||||
</p>
|
||||
|
||||
## Features
|
||||
<p align="center">
|
||||
<img src="assets/screenshots/5-move-count.png" width="160" alt="Make your next move count">
|
||||
<img src="assets/screenshots/4-home.png" width="160" alt="Home screen">
|
||||
<img src="assets/screenshots/1-friendly-matches.png" width="160" alt="From solo games to friendly matches">
|
||||
<img src="assets/screenshots/3-play-together.png" width="160" alt="Play together">
|
||||
<img src="assets/screenshots/2-keep-growing.png" width="160" alt="Keep growing">
|
||||
</p>
|
||||
|
||||
> [!TIP]
|
||||
> If you find Matewave useful, please consider giving it a ⭐ — it helps others discover the project.
|
||||
|
||||
## ✨ Features
|
||||
|
||||
- 🤖 **AI opponent** with adjustable difficulty
|
||||
- 🧩 **Puzzles** and tactical training
|
||||
- 📖 **Opening trainer** — learn and practice opening lines and their variations
|
||||
- 📶 **Local multiplayer** over Bluetooth or Wi-Fi/LAN, with nearby player discovery
|
||||
- 👀 **Watch friends play** — up to 20 spectators on the same Wi-Fi can follow a live LAN game
|
||||
- 📲 **Share the app** with a nearby friend via QR code over the local network
|
||||
- 🎷 **Optional jazz radio**
|
||||
- 🌙 **Dark theme**
|
||||
- 🌍 **Six languages** — English, Russian, German, Japanese, Lithuanian and Chinese
|
||||
|
||||
## Screenshots
|
||||
## <img src="assets/icon-install.png" width="32" alt=""> Installation
|
||||
|
||||
<p align="center">
|
||||
<img src="assets/screenshots/5-move-count.png" width="200" alt="Make your next move count">
|
||||
<img src="assets/screenshots/4-home.png" width="200" alt="Home screen">
|
||||
<img src="assets/screenshots/1-friendly-matches.png" width="200" alt="From solo games to friendly matches">
|
||||
<img src="assets/screenshots/3-play-together.png" width="200" alt="Play together">
|
||||
<img src="assets/screenshots/2-keep-growing.png" width="200" alt="Keep growing">
|
||||
</p>
|
||||
- **[F-Droid](https://f-droid.org/packages/cc.skysparkle.matewave/)** — install and update through the F-Droid client.
|
||||
- **[Obtainium](https://apps.obtainium.imranr.dev/redirect?r=obtainium://add/https://git.skysparkle.cc/kalarina/Matewave)** — installs the APK straight from Gitea releases and keeps it up to date.
|
||||
- **Manually** — download the latest APK from [GitHub](https://github.com/kalarina-bit/Matewave/releases/latest) or [Gitea](https://git.skysparkle.cc/kalarina/Matewave/releases), allow installs from unknown sources for the app you open it with (Settings → Apps → Special access → Install unknown apps), then open the `.apk` and confirm.
|
||||
|
||||
## Installation
|
||||
|
||||
<img src="assets/icon-install.png" width="36" align="left">
|
||||
|
||||
1. Download the latest APK from the [Releases page](https://git.skysparkle.cc/kalarina/Matewave/releases).
|
||||
2. Allow installs from unknown sources for the app you open it with (Settings → Apps → Special access → Install unknown apps).
|
||||
3. Open the `.apk` file and confirm the install.
|
||||
|
||||
## Verifying a download
|
||||
|
||||
<img src="assets/icon-verify.png" width="36" align="left">
|
||||
## <img src="assets/icon-verify.png" width="32" alt=""> Verifying a download
|
||||
|
||||
Every official APK is signed with the same key. Check it before installing:
|
||||
|
||||
@@ -64,7 +65,7 @@ The SHA-256 fingerprint of the signing certificate must be:
|
||||
|
||||
`apksigner` prints the same value in lowercase without colons. On Android you can check it with [AppVerifier](https://github.com/soupslurpr/AppVerifier) (app ID `cc.skysparkle.matewave`).
|
||||
|
||||
## Building from source
|
||||
## <img src="assets/icon-structure.png" width="32" alt=""> Building from source
|
||||
|
||||
Requires JDK 17+ and Android Studio with AGP 9.2 support.
|
||||
|
||||
@@ -75,10 +76,10 @@ Requires JDK 17+ and Android Studio with AGP 9.2 support.
|
||||
|
||||
Nearby multiplayer needs two physical devices — the emulator has no real Bluetooth, and mDNS discovery is often blocked on emulator networks.
|
||||
|
||||
## Contributing
|
||||
## 🤝 Contributing
|
||||
|
||||
Bug reports, puzzle and opening fixes, translation fixes and pull requests are welcome in the [issue tracker](https://git.skysparkle.cc/kalarina/Matewave/issues). Please read [CONTRIBUTING.md](CONTRIBUTING.md) first — it explains what fits the project and how to send changes. To open an issue or a pull request, [create an account](https://git.skysparkle.cc/user/sign_up) on this Gitea.
|
||||
|
||||
## License
|
||||
## 📄 License
|
||||
|
||||
[GNU General Public License v3.0 or later](LICENSE).
|
||||
|
||||
@@ -13,8 +13,8 @@ android {
|
||||
applicationId = "cc.skysparkle.matewave"
|
||||
minSdk = 26
|
||||
targetSdk = 36
|
||||
versionCode = 2
|
||||
versionName = "1.0.44"
|
||||
versionCode = 4
|
||||
versionName = "1.0.46"
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
|
||||
@@ -12,7 +12,9 @@ import androidx.activity.compose.setContent
|
||||
import cc.skysparkle.matewave.audio.SoundManager
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import androidx.navigation.compose.NavHost
|
||||
import androidx.navigation.compose.composable
|
||||
@@ -110,6 +112,10 @@ private fun AppNavHost() {
|
||||
|
||||
// Presence is shared with the background service, so the lists stay the same in both.
|
||||
val presence = remember { PresenceHub.get(context) }
|
||||
|
||||
var spectateTarget by androidx.compose.runtime.saveable.rememberSaveable(saver = SpectateTargetSaver) {
|
||||
androidx.compose.runtime.mutableStateOf<cc.skysparkle.matewave.spectate.SpectateTarget?>(null)
|
||||
}
|
||||
androidx.compose.runtime.DisposableEffect(Unit) {
|
||||
if (cc.skysparkle.matewave.presence.PresenceSettings(context).backgroundEnabled) {
|
||||
cc.skysparkle.matewave.presence.PresenceService.start(context)
|
||||
@@ -231,6 +237,10 @@ private fun AppNavHost() {
|
||||
FriendsScreen(
|
||||
presence = presence,
|
||||
onPlay = { navController.navigate("connectionNearby") },
|
||||
onWatch = { target ->
|
||||
spectateTarget = target
|
||||
navController.navigate("spectate")
|
||||
},
|
||||
onHomeClick = { navController.popBackStack("menu", inclusive = false) },
|
||||
onSettingsClick = {
|
||||
navController.popBackStack("menu", inclusive = false)
|
||||
@@ -243,6 +253,19 @@ private fun AppNavHost() {
|
||||
)
|
||||
}
|
||||
|
||||
composable("spectate") {
|
||||
val target = spectateTarget
|
||||
val backToFriends: () -> Unit = {
|
||||
if (!navController.popBackStack("friends", inclusive = false)) navController.popBackStack()
|
||||
}
|
||||
if (target == null) {
|
||||
LaunchedEffect(Unit) { backToFriends() }
|
||||
} else {
|
||||
PlayScreenMusic()
|
||||
cc.skysparkle.matewave.ui.screens.SpectatorScreen(target = target, onBackToFriends = backToFriends)
|
||||
}
|
||||
}
|
||||
|
||||
composable("vsAiSetup") {
|
||||
VsAiSetupScreen(
|
||||
onBack = { navController.popBackStack() },
|
||||
@@ -260,6 +283,7 @@ private fun AppNavHost() {
|
||||
}
|
||||
|
||||
composable("game") {
|
||||
PlayScreenMusic()
|
||||
GameScreen(
|
||||
viewModel = viewModel,
|
||||
onExit = { navController.popBackStack("menu", inclusive = false) }
|
||||
@@ -267,6 +291,7 @@ private fun AppNavHost() {
|
||||
}
|
||||
|
||||
composable("openingStudy") {
|
||||
PlayScreenMusic()
|
||||
cc.skysparkle.matewave.ui.screens.OpeningStudyScreen(
|
||||
viewModel = studyViewModel,
|
||||
onBack = { navController.popBackStack() },
|
||||
@@ -275,6 +300,7 @@ private fun AppNavHost() {
|
||||
}
|
||||
|
||||
composable("openingTrainer") {
|
||||
PlayScreenMusic()
|
||||
cc.skysparkle.matewave.ui.screens.OpeningTrainerScreen(
|
||||
viewModel = studyViewModel,
|
||||
onBack = { navController.popBackStack() }
|
||||
@@ -282,6 +308,7 @@ private fun AppNavHost() {
|
||||
}
|
||||
|
||||
composable("puzzleSolve") {
|
||||
PlayScreenMusic()
|
||||
PuzzleSolveScreen(
|
||||
viewModel = viewModel,
|
||||
onBack = { navController.popBackStack("menu", inclusive = false) },
|
||||
@@ -320,6 +347,18 @@ private fun AppNavHost() {
|
||||
}
|
||||
}
|
||||
|
||||
private val SpectateTargetSaver = androidx.compose.runtime.saveable.Saver<
|
||||
androidx.compose.runtime.MutableState<cc.skysparkle.matewave.spectate.SpectateTarget?>, List<Any>
|
||||
>(
|
||||
save = { state -> state.value?.let { arrayListOf<Any>(it.host, it.port, it.gameTag) } },
|
||||
restore = { saved ->
|
||||
val target = if (saved.size == 3) {
|
||||
cc.skysparkle.matewave.spectate.SpectateTarget(saved[0] as String, saved[1] as Int, saved[2] as String)
|
||||
} else null
|
||||
androidx.compose.runtime.mutableStateOf(target)
|
||||
}
|
||||
)
|
||||
|
||||
private val TAB_ROUTES = setOf("menu", "friends", "settings", "account")
|
||||
|
||||
private fun isTabSwitch(from: String?, to: String?): Boolean =
|
||||
@@ -355,3 +394,12 @@ private fun sharedAxisOut(forward: Boolean): androidx.compose.animation.ExitTran
|
||||
androidx.compose.animation.fadeOut(
|
||||
androidx.compose.animation.core.tween(durationMillis = 120, easing = androidx.compose.animation.core.LinearEasing)
|
||||
)
|
||||
|
||||
// Offline music switches to the game track while a game, puzzle or opening study is open
|
||||
@Composable
|
||||
private fun PlayScreenMusic() {
|
||||
androidx.compose.runtime.DisposableEffect(Unit) {
|
||||
SoundManager.enterPlayScreen()
|
||||
onDispose { SoundManager.leavePlayScreen() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,9 @@ import android.media.AudioFocusRequest
|
||||
import android.media.AudioManager
|
||||
import android.media.MediaPlayer
|
||||
import android.media.SoundPool
|
||||
import android.net.ConnectivityManager
|
||||
import android.net.Network
|
||||
import android.net.NetworkCapabilities
|
||||
import android.os.Build
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
@@ -25,11 +28,13 @@ object SoundManager {
|
||||
"https://stream.srg-ssr.ch/srgssr/rsj/aac/96"
|
||||
)
|
||||
|
||||
// Played instead of the radio when it can't be reached
|
||||
private const val MENU_TRACK = "music/midnight_grove_conversations.ogg"
|
||||
private const val PLAY_TRACK = "music/raindrops_and_pawns.ogg"
|
||||
|
||||
private const val PREFS = "chess_sound_prefs"
|
||||
private const val KEY_MUSIC = "music_enabled"
|
||||
private const val KEY_SFX = "sfx_enabled"
|
||||
private const val KEY_MENU_MUSIC = "menu_music_enabled"
|
||||
private const val MENU_MUSIC_DIR = "music"
|
||||
private const val TAG = "SoundManager"
|
||||
|
||||
private const val RADIO_START_DELAY_MS = 1_500L
|
||||
@@ -47,45 +52,46 @@ object SoundManager {
|
||||
private var sourceIndex = 0
|
||||
private var connectTimeoutRunnable: Runnable? = null
|
||||
private var audioManager: AudioManager? = null
|
||||
private var connectivity: ConnectivityManager? = null
|
||||
private var networkCallbackRegistered = false
|
||||
private var focusRequest: AudioFocusRequest? = null
|
||||
private var focusGranted = false
|
||||
private var noisyReceiverRegistered = false
|
||||
private val mainHandler = Handler(Looper.getMainLooper())
|
||||
|
||||
private var offlinePlayer: MediaPlayer? = null
|
||||
private var offlinePrepared = false
|
||||
private var offlineTrack: String? = null
|
||||
private var playScreens = 0
|
||||
private var appInForeground = false
|
||||
|
||||
/** Jazz radio. Off until the user turns it on, so nothing connects on start. */
|
||||
var musicEnabled: Boolean = false
|
||||
private set
|
||||
/** Bundled tracks on the main screen, used while the radio is off. */
|
||||
var menuMusicEnabled: Boolean = true
|
||||
private set
|
||||
var sfxEnabled: Boolean = true
|
||||
private set
|
||||
|
||||
private val _radioState = MutableStateFlow(RadioState.IDLE)
|
||||
val radioState: StateFlow<RadioState> = _radioState
|
||||
|
||||
private var menuPlayer: MediaPlayer? = null
|
||||
private var menuPrepared = false
|
||||
private var menuTracks: List<String> = emptyList()
|
||||
private var menuTrackIndex = 0
|
||||
private var menuVisible = false
|
||||
private var appInForeground = false
|
||||
|
||||
private fun pauseRadio() {
|
||||
val player = musicPlayer ?: return
|
||||
if (playerPrepared) runCatching { if (player.isPlaying) player.pause() }
|
||||
private fun setRadioState(state: RadioState) {
|
||||
_radioState.value = state
|
||||
updateOfflineMusic()
|
||||
}
|
||||
|
||||
private fun pauseMenuMusic() {
|
||||
val player = menuPlayer ?: return
|
||||
if (menuPrepared) runCatching { if (player.isPlaying) player.pause() }
|
||||
private fun pauseAll() {
|
||||
musicPlayer?.let { player -> if (playerPrepared) runCatching { if (player.isPlaying) player.pause() } }
|
||||
offlinePlayer?.let { player -> if (offlinePrepared) runCatching { if (player.isPlaying) player.pause() } }
|
||||
}
|
||||
|
||||
private fun setVolumeAll(volume: Float) {
|
||||
runCatching { musicPlayer?.setVolume(volume, volume) }
|
||||
runCatching { offlinePlayer?.setVolume(volume, volume) }
|
||||
}
|
||||
|
||||
private val noisyReceiver = object : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
if (intent.action == AudioManager.ACTION_AUDIO_BECOMING_NOISY) {
|
||||
pauseRadio()
|
||||
pauseMenuMusic()
|
||||
}
|
||||
if (intent.action == AudioManager.ACTION_AUDIO_BECOMING_NOISY) pauseAll()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -93,27 +99,33 @@ object SoundManager {
|
||||
when (change) {
|
||||
AudioManager.AUDIOFOCUS_LOSS -> {
|
||||
stopRadioInternal()
|
||||
releaseMenuPlayer()
|
||||
releaseOfflinePlayer()
|
||||
abandonAudioFocus()
|
||||
}
|
||||
AudioManager.AUDIOFOCUS_LOSS_TRANSIENT -> {
|
||||
pauseRadio()
|
||||
pauseMenuMusic()
|
||||
}
|
||||
AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -> {
|
||||
runCatching { musicPlayer?.setVolume(BASE_VOLUME * 0.3f, BASE_VOLUME * 0.3f) }
|
||||
runCatching { menuPlayer?.setVolume(BASE_VOLUME * 0.3f, BASE_VOLUME * 0.3f) }
|
||||
focusGranted = false
|
||||
pauseAll()
|
||||
}
|
||||
AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -> setVolumeAll(BASE_VOLUME * 0.3f)
|
||||
AudioManager.AUDIOFOCUS_GAIN -> {
|
||||
focusGranted = true
|
||||
setVolumeAll(BASE_VOLUME)
|
||||
val player = musicPlayer
|
||||
if (player != null && playerPrepared) runCatching {
|
||||
player.setVolume(BASE_VOLUME, BASE_VOLUME)
|
||||
if (!player.isPlaying) player.start()
|
||||
if (player != null && playerPrepared) runCatching { if (!player.isPlaying) player.start() }
|
||||
val offline = offlinePlayer
|
||||
if (offline != null && offlinePrepared && shouldPlayOffline()) {
|
||||
runCatching { if (!offline.isPlaying) offline.start() }
|
||||
}
|
||||
val menu = menuPlayer
|
||||
if (menu != null && menuPrepared && menuVisible) runCatching {
|
||||
menu.setVolume(BASE_VOLUME, BASE_VOLUME)
|
||||
if (!menu.isPlaying) menu.start()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Brings the radio back once the device is online again
|
||||
private val networkCallback = object : ConnectivityManager.NetworkCallback() {
|
||||
override fun onAvailable(network: Network) {
|
||||
mainHandler.post {
|
||||
if (musicEnabled && appInForeground && musicPlayer == null && _radioState.value == RadioState.ERROR) {
|
||||
startRadio()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -125,14 +137,11 @@ object SoundManager {
|
||||
val ctx = context.applicationContext
|
||||
appContext = ctx
|
||||
audioManager = ctx.getSystemService(Context.AUDIO_SERVICE) as? AudioManager
|
||||
connectivity = ctx.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
|
||||
|
||||
val prefs = ctx.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||
musicEnabled = prefs.getBoolean(KEY_MUSIC, false)
|
||||
sfxEnabled = prefs.getBoolean(KEY_SFX, true)
|
||||
menuMusicEnabled = prefs.getBoolean(KEY_MENU_MUSIC, true)
|
||||
menuTracks = runCatching {
|
||||
ctx.assets.list(MENU_MUSIC_DIR)?.filter { it.endsWith(".ogg") || it.endsWith(".mp3") }?.sorted()
|
||||
}.getOrNull().orEmpty()
|
||||
|
||||
ensureSoundPool(ctx)
|
||||
|
||||
@@ -143,23 +152,27 @@ object SoundManager {
|
||||
|
||||
private fun requestAudioFocus(): Boolean {
|
||||
val am = audioManager ?: return false
|
||||
if (focusRequest != null) return true
|
||||
val attrs = AudioAttributes.Builder()
|
||||
if (focusGranted) return true
|
||||
// Asked again after a denial or a transient loss, e.g. during a phone call
|
||||
val request = focusRequest ?: AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
|
||||
.setAudioAttributes(
|
||||
AudioAttributes.Builder()
|
||||
.setUsage(AudioAttributes.USAGE_MEDIA)
|
||||
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
|
||||
.build()
|
||||
val request = AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
|
||||
.setAudioAttributes(attrs)
|
||||
)
|
||||
.setOnAudioFocusChangeListener(focusChangeListener, mainHandler)
|
||||
.build()
|
||||
focusRequest = request
|
||||
return am.requestAudioFocus(request) == AudioManager.AUDIOFOCUS_REQUEST_GRANTED
|
||||
.also { focusRequest = it }
|
||||
focusGranted = am.requestAudioFocus(request) == AudioManager.AUDIOFOCUS_REQUEST_GRANTED
|
||||
return focusGranted
|
||||
}
|
||||
|
||||
private fun abandonAudioFocus() {
|
||||
val am = audioManager ?: return
|
||||
focusRequest?.let { am.abandonAudioFocusRequest(it) }
|
||||
focusRequest = null
|
||||
focusGranted = false
|
||||
}
|
||||
|
||||
private fun registerNoisyReceiver() {
|
||||
@@ -182,22 +195,47 @@ object SoundManager {
|
||||
noisyReceiverRegistered = false
|
||||
}
|
||||
|
||||
private fun registerNetworkCallback() {
|
||||
val cm = connectivity ?: return
|
||||
if (networkCallbackRegistered) return
|
||||
runCatching { cm.registerDefaultNetworkCallback(networkCallback) }
|
||||
.onSuccess { networkCallbackRegistered = true }
|
||||
}
|
||||
|
||||
private fun unregisterNetworkCallback() {
|
||||
val cm = connectivity ?: return
|
||||
if (!networkCallbackRegistered) return
|
||||
runCatching { cm.unregisterNetworkCallback(networkCallback) }
|
||||
networkCallbackRegistered = false
|
||||
}
|
||||
|
||||
private fun isOnline(): Boolean {
|
||||
val cm = connectivity ?: return true
|
||||
val caps = cm.getNetworkCapabilities(cm.activeNetwork) ?: return false
|
||||
return caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
|
||||
}
|
||||
|
||||
private fun startRadio() {
|
||||
val ctx = appContext ?: return
|
||||
if (musicPlayer != null) return
|
||||
releaseMenuPlayer()
|
||||
if (!requestAudioFocus()) {
|
||||
Log.w(TAG, "Audio focus denied, radio not started")
|
||||
_radioState.value = RadioState.ERROR
|
||||
setRadioState(RadioState.ERROR)
|
||||
return
|
||||
}
|
||||
registerNoisyReceiver()
|
||||
registerNetworkCallback()
|
||||
retryCount = 0
|
||||
if (!isOnline()) {
|
||||
// No point waiting for timeouts: play offline music until the network is back
|
||||
setRadioState(RadioState.ERROR)
|
||||
return
|
||||
}
|
||||
connect(ctx)
|
||||
}
|
||||
|
||||
private fun connect(ctx: Context) {
|
||||
_radioState.value = RadioState.CONNECTING
|
||||
setRadioState(RadioState.CONNECTING)
|
||||
val url = RADIO_SOURCES[sourceIndex % RADIO_SOURCES.size]
|
||||
try {
|
||||
val player = MediaPlayer()
|
||||
@@ -214,9 +252,9 @@ object SoundManager {
|
||||
player.setOnPreparedListener {
|
||||
cancelConnectTimeout()
|
||||
playerPrepared = true
|
||||
it.start()
|
||||
retryCount = 0
|
||||
_radioState.value = RadioState.PLAYING
|
||||
if (appInForeground) it.start()
|
||||
setRadioState(RadioState.PLAYING)
|
||||
}
|
||||
player.setOnErrorListener { mp, _, _ ->
|
||||
cancelConnectTimeout()
|
||||
@@ -272,18 +310,18 @@ object SoundManager {
|
||||
private fun scheduleRetry(ctx: Context) {
|
||||
cancelConnectTimeout()
|
||||
if (!musicEnabled) {
|
||||
_radioState.value = RadioState.IDLE
|
||||
setRadioState(RadioState.IDLE)
|
||||
return
|
||||
}
|
||||
if (retryCount >= MAX_RETRIES) {
|
||||
_radioState.value = RadioState.ERROR
|
||||
Log.w(TAG, "Could not connect to the radio after $MAX_RETRIES attempts")
|
||||
if (retryCount >= MAX_RETRIES || !isOnline()) {
|
||||
if (retryCount >= MAX_RETRIES) Log.w(TAG, "Could not connect to the radio after $MAX_RETRIES attempts")
|
||||
setRadioState(RadioState.ERROR)
|
||||
return
|
||||
}
|
||||
sourceIndex++
|
||||
val delay = RETRY_DELAYS_MS.getOrElse(retryCount) { RETRY_DELAYS_MS.last() }
|
||||
retryCount++
|
||||
_radioState.value = RadioState.CONNECTING
|
||||
setRadioState(RadioState.CONNECTING)
|
||||
mainHandler.postDelayed({
|
||||
if (musicEnabled && musicPlayer == null) connect(ctx)
|
||||
}, delay)
|
||||
@@ -295,22 +333,22 @@ object SoundManager {
|
||||
musicPlayer = null
|
||||
playerPrepared = false
|
||||
unregisterNoisyReceiver()
|
||||
unregisterNetworkCallback()
|
||||
abandonAudioFocus()
|
||||
mainHandler.removeCallbacksAndMessages(null)
|
||||
_radioState.value = RadioState.IDLE
|
||||
setRadioState(RadioState.IDLE)
|
||||
}
|
||||
|
||||
fun onAppResumed() {
|
||||
appInForeground = true
|
||||
if (musicEnabled && musicPlayer == null) startRadio()
|
||||
updateMenuMusic()
|
||||
updateOfflineMusic()
|
||||
}
|
||||
|
||||
fun onAppPaused() {
|
||||
appInForeground = false
|
||||
releaseOfflinePlayer()
|
||||
stopRadioInternal()
|
||||
releaseMenuPlayer()
|
||||
abandonAudioFocus()
|
||||
}
|
||||
|
||||
fun setMusicEnabled(enabled: Boolean) {
|
||||
@@ -320,97 +358,86 @@ object SoundManager {
|
||||
if (enabled) {
|
||||
startRadio()
|
||||
} else {
|
||||
releaseOfflinePlayer()
|
||||
stopRadioInternal()
|
||||
updateMenuMusic()
|
||||
}
|
||||
}
|
||||
|
||||
fun setMenuMusicEnabled(enabled: Boolean) {
|
||||
menuMusicEnabled = enabled
|
||||
appContext?.getSharedPreferences(PREFS, Context.MODE_PRIVATE)?.edit()
|
||||
?.putBoolean(KEY_MENU_MUSIC, enabled)?.apply()
|
||||
updateMenuMusic()
|
||||
/** Games, puzzles and opening study call this while they are on screen. */
|
||||
fun enterPlayScreen() {
|
||||
playScreens++
|
||||
updateOfflineMusic()
|
||||
}
|
||||
|
||||
/** Called by the main screen when it appears and disappears. */
|
||||
fun setMenuVisible(visible: Boolean) {
|
||||
menuVisible = visible
|
||||
updateMenuMusic()
|
||||
fun leavePlayScreen() {
|
||||
playScreens = maxOf(0, playScreens - 1)
|
||||
updateOfflineMusic()
|
||||
}
|
||||
|
||||
private fun updateMenuMusic() {
|
||||
val shouldPlay = menuMusicEnabled && !musicEnabled && menuVisible && appInForeground
|
||||
if (shouldPlay) startMenuMusic() else pauseMenuMusicAndFocus()
|
||||
// The radio is on but can't be reached: no network, or the first attempt already failed
|
||||
private fun radioUnavailable(): Boolean = when (_radioState.value) {
|
||||
RadioState.ERROR -> true
|
||||
RadioState.CONNECTING -> retryCount > 0
|
||||
else -> false
|
||||
}
|
||||
|
||||
private fun pauseMenuMusicAndFocus() {
|
||||
pauseMenuMusic()
|
||||
if (!musicEnabled) abandonAudioFocus()
|
||||
}
|
||||
private fun shouldPlayOffline() = musicEnabled && appInForeground && radioUnavailable()
|
||||
|
||||
private fun startMenuMusic() {
|
||||
if (menuTracks.isEmpty()) return
|
||||
val player = menuPlayer
|
||||
if (player != null) {
|
||||
if (menuPrepared && !player.isPlaying && requestAudioFocus()) {
|
||||
registerNoisyReceiver()
|
||||
runCatching { player.setVolume(BASE_VOLUME, BASE_VOLUME); player.start() }
|
||||
}
|
||||
private fun updateOfflineMusic() {
|
||||
if (!shouldPlayOffline()) {
|
||||
releaseOfflinePlayer()
|
||||
return
|
||||
}
|
||||
// Never cut off music another app is already playing.
|
||||
if (audioManager?.isMusicActive == true) return
|
||||
val track = if (playScreens > 0) PLAY_TRACK else MENU_TRACK
|
||||
val player = offlinePlayer
|
||||
if (player != null && offlineTrack == track) {
|
||||
if (offlinePrepared && !player.isPlaying && requestAudioFocus()) runCatching { player.start() }
|
||||
return
|
||||
}
|
||||
releaseOfflinePlayer()
|
||||
if (!requestAudioFocus()) return
|
||||
registerNoisyReceiver()
|
||||
playMenuTrack(menuTrackIndex)
|
||||
playOfflineTrack(track)
|
||||
}
|
||||
|
||||
private fun playMenuTrack(index: Int) {
|
||||
private fun playOfflineTrack(track: String) {
|
||||
val ctx = appContext ?: return
|
||||
if (menuTracks.isEmpty()) return
|
||||
val name = menuTracks[index % menuTracks.size]
|
||||
try {
|
||||
val player = MediaPlayer()
|
||||
menuPlayer = player
|
||||
menuPrepared = false
|
||||
offlinePlayer = player
|
||||
offlineTrack = track
|
||||
offlinePrepared = false
|
||||
player.setAudioAttributes(
|
||||
AudioAttributes.Builder()
|
||||
.setUsage(AudioAttributes.USAGE_MEDIA)
|
||||
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
|
||||
.build()
|
||||
)
|
||||
ctx.assets.openFd("$MENU_MUSIC_DIR/$name").use { fd ->
|
||||
ctx.assets.openFd(track).use { fd ->
|
||||
player.setDataSource(fd.fileDescriptor, fd.startOffset, fd.length)
|
||||
}
|
||||
player.isLooping = true
|
||||
player.setVolume(BASE_VOLUME, BASE_VOLUME)
|
||||
player.setOnPreparedListener {
|
||||
menuPrepared = true
|
||||
if (menuVisible && appInForeground && menuMusicEnabled && !musicEnabled) it.start()
|
||||
}
|
||||
player.setOnCompletionListener { mp ->
|
||||
if (menuPlayer === mp) {
|
||||
releaseMenuPlayer()
|
||||
menuTrackIndex = (menuTrackIndex + 1) % menuTracks.size
|
||||
if (menuVisible && appInForeground && menuMusicEnabled && !musicEnabled) {
|
||||
playMenuTrack(menuTrackIndex)
|
||||
}
|
||||
}
|
||||
offlinePrepared = true
|
||||
if (shouldPlayOffline() && focusGranted) it.start()
|
||||
}
|
||||
player.setOnErrorListener { mp, _, _ ->
|
||||
if (menuPlayer === mp) releaseMenuPlayer()
|
||||
if (offlinePlayer === mp) releaseOfflinePlayer()
|
||||
true
|
||||
}
|
||||
player.prepareAsync()
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Menu music error ($name): ${e.message}")
|
||||
releaseMenuPlayer()
|
||||
Log.w(TAG, "Offline music error ($track): ${e.message}")
|
||||
releaseOfflinePlayer()
|
||||
}
|
||||
}
|
||||
|
||||
private fun releaseMenuPlayer() {
|
||||
try { menuPlayer?.release() } catch (_: Exception) {}
|
||||
menuPlayer = null
|
||||
menuPrepared = false
|
||||
private fun releaseOfflinePlayer() {
|
||||
try { offlinePlayer?.release() } catch (_: Exception) {}
|
||||
offlinePlayer = null
|
||||
offlineTrack = null
|
||||
offlinePrepared = false
|
||||
}
|
||||
|
||||
fun setSfxEnabled(enabled: Boolean) {
|
||||
|
||||
@@ -67,6 +67,9 @@ sealed class GameMessage {
|
||||
val newGameId: String = ""
|
||||
) : GameMessage()
|
||||
|
||||
/** Host to guest: how many spectators watch. Older versions skip it as an unknown type. */
|
||||
data class SpectatorCountMsg(val count: Int, val gameId: String = "") : GameMessage()
|
||||
|
||||
fun toJson(): String {
|
||||
val o = JSONObject()
|
||||
when (this) {
|
||||
@@ -99,6 +102,7 @@ sealed class GameMessage {
|
||||
o.put("type", "rematch"); o.put("action", action); o.put("gameId", gameId)
|
||||
if (newGameId.isNotEmpty()) o.put("newGameId", newGameId)
|
||||
}
|
||||
is SpectatorCountMsg -> { o.put("type", "spectators"); o.put("n", count); o.put("gameId", gameId) }
|
||||
is ProfileMsg -> {
|
||||
o.put("type", "profile")
|
||||
o.put("userId", userId)
|
||||
@@ -154,6 +158,7 @@ sealed class GameMessage {
|
||||
o.optString("gameId", ""),
|
||||
o.optString("newGameId", "")
|
||||
)
|
||||
"spectators" -> SpectatorCountMsg(o.getInt("n"), o.optString("gameId", ""))
|
||||
"profile" -> ProfileMsg(
|
||||
|
||||
userId = o.optString("userId", "").ifBlank { o.getString("name") },
|
||||
|
||||
@@ -30,7 +30,11 @@ data class LanPeer(
|
||||
|
||||
val signature: String = "",
|
||||
/** Raw NSD service name, used to remove the peer when the service is lost. */
|
||||
val serviceName: String = ""
|
||||
val serviceName: String = "",
|
||||
/** Tag of the LAN game the peer plays, empty when not in one. */
|
||||
val gameTag: String = "",
|
||||
/** Spectator port when the peer hosts a watchable game, otherwise 0. */
|
||||
val spectatePort: Int = 0
|
||||
) {
|
||||
val id: String get() = "$host:$port"
|
||||
}
|
||||
@@ -224,6 +228,7 @@ class LanTransport(
|
||||
cc.skysparkle.matewave.security.DeviceKeys.sign(
|
||||
context, presencePayload(profile.userId, shownName, profile.elo)
|
||||
)?.let { setAttribute("sig", it) }
|
||||
cc.skysparkle.matewave.spectate.SpectatorAdvert.attributes().forEach { (key, value) -> setAttribute(key, value) }
|
||||
}
|
||||
}
|
||||
val listener = object : NsdManager.RegistrationListener {
|
||||
@@ -353,6 +358,7 @@ class LanTransport(
|
||||
fun attr(key: String): String = runCatching {
|
||||
info.attributes[key]?.toString(Charsets.UTF_8) ?: ""
|
||||
}.getOrDefault("")
|
||||
val game = cc.skysparkle.matewave.spectate.SpectatorAdvert.parse(::attr)
|
||||
return LanPeer(
|
||||
name = displayNameOf(info.serviceName),
|
||||
host = host,
|
||||
@@ -363,7 +369,9 @@ class LanTransport(
|
||||
|
||||
fingerprint = attr("fp").ifEmpty { fingerprintFromServiceName(info.serviceName ?: "") ?: "" },
|
||||
signature = attr("sig"),
|
||||
serviceName = info.serviceName ?: ""
|
||||
serviceName = info.serviceName ?: "",
|
||||
gameTag = game.gameTag,
|
||||
spectatePort = game.spectatePort
|
||||
)
|
||||
}
|
||||
|
||||
@@ -517,7 +525,7 @@ class LanTransport(
|
||||
try {
|
||||
val reader = BufferedReader(InputStreamReader(sock.getInputStream(), Charsets.UTF_8))
|
||||
while (true) {
|
||||
val read = readBoundedLine(reader)
|
||||
val read = readBoundedLine(reader, MAX_MESSAGE_CHARS)
|
||||
if (read is LineResult.EndOfStream) break
|
||||
if (sock !== socket) break
|
||||
if (read is LineResult.TooLong) {
|
||||
@@ -577,27 +585,6 @@ class LanTransport(
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class LineResult {
|
||||
data class Line(val text: String) : LineResult()
|
||||
object TooLong : LineResult()
|
||||
object EndOfStream : LineResult()
|
||||
}
|
||||
|
||||
private fun readBoundedLine(reader: BufferedReader): LineResult {
|
||||
val builder = StringBuilder()
|
||||
while (true) {
|
||||
val ch = reader.read()
|
||||
if (ch == -1) {
|
||||
return if (builder.isEmpty()) LineResult.EndOfStream
|
||||
else LineResult.Line(builder.toString())
|
||||
}
|
||||
if (ch == '\n'.code) return LineResult.Line(builder.toString())
|
||||
if (ch == '\r'.code) continue
|
||||
if (builder.length >= MAX_MESSAGE_CHARS) return LineResult.TooLong
|
||||
builder.append(ch.toChar())
|
||||
}
|
||||
}
|
||||
|
||||
override fun send(message: GameMessage) {
|
||||
val json = message.toJson()
|
||||
val size = json.length
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
package cc.skysparkle.matewave.network
|
||||
|
||||
import java.io.Reader
|
||||
|
||||
/** Result of reading one newline-delimited message from a socket. */
|
||||
sealed class LineResult {
|
||||
data class Line(val text: String) : LineResult()
|
||||
object TooLong : LineResult()
|
||||
object EndOfStream : LineResult()
|
||||
}
|
||||
|
||||
/** Reads one line of at most [maxChars] characters; longer lines are reported, not buffered. */
|
||||
fun readBoundedLine(reader: Reader, maxChars: Int): LineResult {
|
||||
val builder = StringBuilder()
|
||||
while (true) {
|
||||
val ch = reader.read()
|
||||
if (ch == -1) {
|
||||
return if (builder.isEmpty()) LineResult.EndOfStream
|
||||
else LineResult.Line(builder.toString())
|
||||
}
|
||||
if (ch == '\n'.code) return LineResult.Line(builder.toString())
|
||||
if (ch == '\r'.code) continue
|
||||
if (builder.length >= maxChars) return LineResult.TooLong
|
||||
builder.append(ch.toChar())
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,10 @@ data class DiscoveredPeer(
|
||||
val elo: Int,
|
||||
val fingerprint: String,
|
||||
|
||||
val address: String
|
||||
val address: String,
|
||||
val host: String = "",
|
||||
val gameTag: String = "",
|
||||
val spectatePort: Int = 0
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -159,7 +162,10 @@ class LocalPresence(
|
||||
name = peer.displayName.ifEmpty { peer.name },
|
||||
elo = peer.elo,
|
||||
fingerprint = peer.fingerprint,
|
||||
address = peer.id
|
||||
address = peer.id,
|
||||
host = peer.host,
|
||||
gameTag = peer.gameTag,
|
||||
spectatePort = peer.spectatePort
|
||||
)
|
||||
}
|
||||
_peers.value = result
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
package cc.skysparkle.matewave.spectate
|
||||
|
||||
enum class PresenceStatus { ONLINE, IN_GAME, OFFLINE }
|
||||
|
||||
/** Where to watch a game: the host's address and spectator port. */
|
||||
data class SpectateTarget(val host: String, val port: Int, val gameTag: String)
|
||||
|
||||
/** A player seen on the network, reduced to what spectating needs. */
|
||||
data class NearbyPlayerGame(
|
||||
val playerId: String,
|
||||
val host: String,
|
||||
val gameTag: String,
|
||||
val spectatePort: Int
|
||||
)
|
||||
|
||||
data class FriendGameStatus(
|
||||
val status: PresenceStatus,
|
||||
val target: SpectateTarget? = null,
|
||||
/** Live count from the host, null until it has answered. */
|
||||
val spectators: Int? = null,
|
||||
val max: Int = MAX_SPECTATORS
|
||||
) {
|
||||
val full: Boolean get() = spectators != null && spectators >= max
|
||||
}
|
||||
|
||||
/**
|
||||
* Online, In game or Offline for one player, and where to watch. Both players of a game announce
|
||||
* the same tag, but only the host serves spectators, so the guest's game is watched through the
|
||||
* host. A host that says its game has ended overrides an announcement that is not updated yet.
|
||||
*/
|
||||
object FriendStatusResolver {
|
||||
fun resolve(
|
||||
playerId: String,
|
||||
nearby: Map<String, NearbyPlayerGame>,
|
||||
probes: Map<SpectateTarget, SpectatorMessage.Status>
|
||||
): FriendGameStatus {
|
||||
val player = nearby[playerId] ?: return FriendGameStatus(PresenceStatus.OFFLINE)
|
||||
if (player.gameTag.isEmpty()) return FriendGameStatus(PresenceStatus.ONLINE)
|
||||
val host = hostOf(player, nearby) ?: return FriendGameStatus(PresenceStatus.IN_GAME)
|
||||
val target = SpectateTarget(host.host, host.spectatePort, host.gameTag)
|
||||
val probe = probes[target]
|
||||
if (probe != null && !probe.inGame) return FriendGameStatus(PresenceStatus.ONLINE)
|
||||
return FriendGameStatus(PresenceStatus.IN_GAME, target, probe?.count, probe?.max ?: MAX_SPECTATORS)
|
||||
}
|
||||
|
||||
/** Every host worth asking for a live spectator count. */
|
||||
fun targets(nearby: Collection<NearbyPlayerGame>): Set<SpectateTarget> =
|
||||
nearby.filter { it.gameTag.isNotEmpty() && it.spectatePort > 0 && it.host.isNotEmpty() }
|
||||
.map { SpectateTarget(it.host, it.spectatePort, it.gameTag) }
|
||||
.toSet()
|
||||
|
||||
private fun hostOf(player: NearbyPlayerGame, nearby: Map<String, NearbyPlayerGame>): NearbyPlayerGame? {
|
||||
if (player.spectatePort > 0 && player.host.isNotEmpty()) return player
|
||||
return nearby.values.firstOrNull {
|
||||
it.playerId != player.playerId && it.gameTag == player.gameTag && it.spectatePort > 0 && it.host.isNotEmpty()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package cc.skysparkle.matewave.spectate
|
||||
|
||||
/**
|
||||
* What this device adds to its network announcement while it plays a watchable LAN game: a short
|
||||
* tag shared by both players of the game, and, on the host, the spectator port. Older app versions
|
||||
* ignore these attributes.
|
||||
*/
|
||||
object SpectatorAdvert {
|
||||
const val KEY_GAME = "g"
|
||||
const val KEY_PORT = "sp"
|
||||
|
||||
data class State(val gameTag: String = "", val spectatePort: Int = 0)
|
||||
|
||||
@Volatile var current = State()
|
||||
private set
|
||||
|
||||
/** Returns true when the announcement has to be published again. */
|
||||
@Synchronized
|
||||
fun update(state: State): Boolean {
|
||||
if (state == current) return false
|
||||
current = state
|
||||
return true
|
||||
}
|
||||
|
||||
fun clear(): Boolean = update(State())
|
||||
|
||||
fun attributes(state: State = current): Map<String, String> = buildMap {
|
||||
if (state.gameTag.isNotEmpty()) put(KEY_GAME, state.gameTag)
|
||||
if (state.gameTag.isNotEmpty() && state.spectatePort > 0) put(KEY_PORT, state.spectatePort.toString())
|
||||
}
|
||||
|
||||
/** Reads the attributes of a discovered player; anything malformed counts as absent. */
|
||||
fun parse(attribute: (String) -> String): State {
|
||||
val tag = attribute(KEY_GAME).takeIf { TAG_PATTERN.matches(it) } ?: return State()
|
||||
val port = attribute(KEY_PORT).toIntOrNull()?.takeIf { it in 1..65_535 } ?: 0
|
||||
return State(tag, port)
|
||||
}
|
||||
|
||||
/** Short tag of a game id, so the game id itself is not announced. */
|
||||
fun tagOf(gameId: String): String {
|
||||
if (gameId.isEmpty()) return ""
|
||||
val digest = java.security.MessageDigest.getInstance("SHA-256").digest(gameId.toByteArray(Charsets.UTF_8))
|
||||
return digest.take(4).joinToString("") { "%02x".format(it) }
|
||||
}
|
||||
|
||||
private val TAG_PATTERN = Regex("^[0-9a-f]{8}$")
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
package cc.skysparkle.matewave.spectate
|
||||
|
||||
import cc.skysparkle.matewave.network.LineResult
|
||||
import cc.skysparkle.matewave.network.readBoundedLine
|
||||
import java.io.BufferedReader
|
||||
import java.io.BufferedWriter
|
||||
import java.io.IOException
|
||||
import java.io.InputStreamReader
|
||||
import java.io.OutputStreamWriter
|
||||
import java.net.InetSocketAddress
|
||||
import java.net.Socket
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.concurrent.RejectedExecutionException
|
||||
|
||||
/**
|
||||
* One spectator's connection to a hosted game. Events arrive on a background thread, in order.
|
||||
* Silence longer than [Timing.silenceTimeoutMs] (the host pings every few seconds) means the host
|
||||
* is gone, which also covers Wi-Fi switching off on either side.
|
||||
*/
|
||||
class SpectatorClient(
|
||||
private val host: String,
|
||||
private val port: Int,
|
||||
private val onEvent: (Event) -> Unit,
|
||||
private val timing: Timing = Timing(),
|
||||
private val version: Int = SpectatorProtocol.VERSION,
|
||||
private val minVersion: Int = SpectatorProtocol.MIN_COMPATIBLE_VERSION
|
||||
) {
|
||||
data class Timing(val connectTimeoutMs: Int = 5_000, val silenceTimeoutMs: Int = 15_000)
|
||||
|
||||
enum class Failure { UNREACHABLE, FULL, NO_GAME, UPDATE_THIS_APP, UPDATE_HOST_APP }
|
||||
|
||||
sealed class Event {
|
||||
data class Joined(val welcome: SpectatorMessage.Welcome) : Event()
|
||||
data class Received(val message: SpectatorMessage) : Event()
|
||||
data class JoinFailed(val failure: Failure) : Event()
|
||||
|
||||
/** The connection ended after joining; [hostClosed] is true when the host said goodbye. */
|
||||
data class Disconnected(val hostClosed: Boolean) : Event()
|
||||
}
|
||||
|
||||
@Volatile private var socket: Socket? = null
|
||||
@Volatile private var output: BufferedWriter? = null
|
||||
@Volatile private var stopped = false
|
||||
private val writer = Executors.newSingleThreadExecutor { r ->
|
||||
Thread(r, "spectator-send").apply { isDaemon = true }
|
||||
}
|
||||
|
||||
fun start() {
|
||||
Thread({ run() }, "spectator-receive").apply { isDaemon = true }.start()
|
||||
}
|
||||
|
||||
fun requestResync() = send(SpectatorMessage.Resync)
|
||||
|
||||
fun stop() {
|
||||
if (stopped) return
|
||||
stopped = true
|
||||
try {
|
||||
writer.execute {
|
||||
writeLine(SpectatorMessage.Leave)
|
||||
closeSocket()
|
||||
}
|
||||
} catch (e: RejectedExecutionException) {
|
||||
closeSocket()
|
||||
}
|
||||
writer.shutdown()
|
||||
// A send stuck on a dead connection must not keep the socket open.
|
||||
Thread({
|
||||
try { Thread.sleep(STOP_GRACE_MS) } catch (_: InterruptedException) {}
|
||||
closeSocket()
|
||||
}, "spectator-stop").apply { isDaemon = true }.start()
|
||||
}
|
||||
|
||||
private fun run() {
|
||||
val s = Socket()
|
||||
socket = s
|
||||
val reader: BufferedReader
|
||||
try {
|
||||
if (stopped) throw IOException("Stopped")
|
||||
s.tcpNoDelay = true
|
||||
s.connect(InetSocketAddress(host, port), timing.connectTimeoutMs)
|
||||
s.soTimeout = timing.silenceTimeoutMs
|
||||
output = BufferedWriter(OutputStreamWriter(s.getOutputStream(), Charsets.UTF_8))
|
||||
reader = BufferedReader(InputStreamReader(s.getInputStream(), Charsets.UTF_8))
|
||||
} catch (e: IOException) {
|
||||
closeSocket()
|
||||
emit(Event.JoinFailed(Failure.UNREACHABLE))
|
||||
return
|
||||
}
|
||||
send(SpectatorMessage.Hello(minVersion))
|
||||
|
||||
var joined = false
|
||||
var hostClosed = false
|
||||
try {
|
||||
while (!stopped) {
|
||||
val read = readBoundedLine(reader, SpectatorProtocol.MAX_HOST_LINE_CHARS)
|
||||
if (read !is LineResult.Line) break
|
||||
val envelope = SpectatorProtocol.decode(read.text) ?: continue
|
||||
val message = envelope.message
|
||||
if (!joined) {
|
||||
// reject keeps its shape across versions, so read it before the version gate.
|
||||
if (message is SpectatorMessage.Reject) {
|
||||
emit(Event.JoinFailed(failureOf(message)))
|
||||
return
|
||||
}
|
||||
if (envelope.version < minVersion) {
|
||||
emit(Event.JoinFailed(Failure.UPDATE_HOST_APP))
|
||||
return
|
||||
}
|
||||
if (message is SpectatorMessage.Welcome) {
|
||||
joined = true
|
||||
emit(Event.Joined(message))
|
||||
}
|
||||
continue
|
||||
}
|
||||
when (message) {
|
||||
null -> Unit
|
||||
SpectatorMessage.Closing -> hostClosed = true
|
||||
is SpectatorMessage.Ping -> {
|
||||
send(SpectatorMessage.Pong)
|
||||
emit(Event.Received(message))
|
||||
}
|
||||
else -> emit(Event.Received(message))
|
||||
}
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
// Silence timeout or connection reset.
|
||||
} finally {
|
||||
closeSocket()
|
||||
}
|
||||
if (joined) emit(Event.Disconnected(hostClosed)) else emit(Event.JoinFailed(Failure.UNREACHABLE))
|
||||
}
|
||||
|
||||
private fun failureOf(reject: SpectatorMessage.Reject): Failure = when (reject.reason) {
|
||||
RejectReason.FULL -> Failure.FULL
|
||||
RejectReason.NO_GAME -> Failure.NO_GAME
|
||||
RejectReason.UPDATE_REQUIRED ->
|
||||
if (version < reject.minVersion) Failure.UPDATE_THIS_APP else Failure.UPDATE_HOST_APP
|
||||
RejectReason.OTHER -> Failure.UNREACHABLE
|
||||
}
|
||||
|
||||
private fun emit(event: Event) {
|
||||
if (!stopped) onEvent(event)
|
||||
}
|
||||
|
||||
private fun send(message: SpectatorMessage) {
|
||||
try {
|
||||
writer.execute { writeLine(message) }
|
||||
} catch (e: RejectedExecutionException) {
|
||||
// Stopped.
|
||||
}
|
||||
}
|
||||
|
||||
private fun writeLine(message: SpectatorMessage) {
|
||||
val out = output ?: return
|
||||
try {
|
||||
out.write(SpectatorProtocol.encode(message, version))
|
||||
out.write("\n")
|
||||
out.flush()
|
||||
} catch (e: IOException) {
|
||||
closeSocket()
|
||||
}
|
||||
}
|
||||
|
||||
private fun closeSocket() {
|
||||
try { socket?.close() } catch (_: IOException) {}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val STOP_GRACE_MS = 500L
|
||||
}
|
||||
}
|
||||
|
||||
/** One-shot status query, used to show live spectator counts in the Friends list. */
|
||||
object SpectatorProbe {
|
||||
fun query(host: String, port: Int, timeoutMs: Int = 2_000): SpectatorMessage.Status? = try {
|
||||
Socket().use { s ->
|
||||
s.connect(InetSocketAddress(host, port), timeoutMs)
|
||||
s.soTimeout = timeoutMs
|
||||
val out = s.getOutputStream()
|
||||
out.write((SpectatorProtocol.encode(SpectatorMessage.StatusQuery) + "\n").toByteArray(Charsets.UTF_8))
|
||||
out.flush()
|
||||
val reader = BufferedReader(InputStreamReader(s.getInputStream(), Charsets.UTF_8))
|
||||
val read = readBoundedLine(reader, SpectatorProtocol.MAX_HOST_LINE_CHARS)
|
||||
(read as? LineResult.Line)?.let { SpectatorProtocol.decode(it.text)?.message as? SpectatorMessage.Status }
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
package cc.skysparkle.matewave.spectate
|
||||
|
||||
import cc.skysparkle.matewave.engine.Board
|
||||
import cc.skysparkle.matewave.engine.ChessEngine
|
||||
import cc.skysparkle.matewave.engine.GameStatus
|
||||
import cc.skysparkle.matewave.engine.Move
|
||||
import cc.skysparkle.matewave.engine.Notation
|
||||
import cc.skysparkle.matewave.engine.PieceColor
|
||||
import cc.skysparkle.matewave.engine.opposite
|
||||
|
||||
/** What a spectator sees of a game. */
|
||||
data class SpectatorView(
|
||||
val gameId: String,
|
||||
val white: SpectatorPlayer,
|
||||
val black: SpectatorPlayer,
|
||||
val startBoard: Board,
|
||||
val board: Board,
|
||||
val movesUci: List<String>,
|
||||
val moveSans: List<String>,
|
||||
val lastMove: Move?,
|
||||
val initialSeconds: Int,
|
||||
val incrementSeconds: Int,
|
||||
val clock: SpectatorClock?,
|
||||
val result: SpectatorResult?
|
||||
) {
|
||||
val ply: Int get() = movesUci.size
|
||||
}
|
||||
|
||||
/**
|
||||
* The spectator's copy of the game, rebuilt from a snapshot and moved forward by live moves. Moves
|
||||
* are checked against the rules; anything that does not follow on asks for a fresh snapshot.
|
||||
*/
|
||||
class SpectatorGame {
|
||||
enum class Applied { APPLIED, IGNORED, NEEDS_RESYNC }
|
||||
|
||||
var view: SpectatorView? = null
|
||||
private set
|
||||
|
||||
fun load(snapshot: SpectatorSnapshot): Boolean {
|
||||
val start = Board.startPosition()
|
||||
var board = start
|
||||
val sans = ArrayList<String>(snapshot.movesUci.size)
|
||||
var last: Move? = null
|
||||
for (uci in snapshot.movesUci) {
|
||||
val move = resolve(board, uci) ?: return false
|
||||
sans.add(Notation.toSan(board, move))
|
||||
board = ChessEngine.applyMove(board, move)
|
||||
last = move
|
||||
}
|
||||
view = SpectatorView(
|
||||
gameId = snapshot.gameId,
|
||||
white = snapshot.white,
|
||||
black = snapshot.black,
|
||||
startBoard = start,
|
||||
board = board,
|
||||
movesUci = snapshot.movesUci,
|
||||
moveSans = sans,
|
||||
lastMove = last,
|
||||
initialSeconds = snapshot.initialSeconds,
|
||||
incrementSeconds = snapshot.incrementSeconds,
|
||||
clock = snapshot.clock,
|
||||
result = snapshot.result
|
||||
)
|
||||
return true
|
||||
}
|
||||
|
||||
fun onMove(message: SpectatorMessage.MovePlayed): Applied {
|
||||
val current = view ?: return Applied.NEEDS_RESYNC
|
||||
if (message.gameId != current.gameId) return Applied.NEEDS_RESYNC
|
||||
if (current.result != null || message.ply <= current.ply) return Applied.IGNORED
|
||||
if (message.ply != current.ply + 1) return Applied.NEEDS_RESYNC
|
||||
val move = resolve(current.board, message.uci) ?: return Applied.NEEDS_RESYNC
|
||||
view = current.copy(
|
||||
board = ChessEngine.applyMove(current.board, move),
|
||||
movesUci = current.movesUci + move.toUci(),
|
||||
moveSans = current.moveSans + Notation.toSan(current.board, move),
|
||||
lastMove = move,
|
||||
clock = message.clock ?: current.clock
|
||||
)
|
||||
return Applied.APPLIED
|
||||
}
|
||||
|
||||
fun onGameOver(message: SpectatorMessage.GameOver): Applied {
|
||||
val current = view ?: return Applied.NEEDS_RESYNC
|
||||
if (message.gameId != current.gameId) return Applied.NEEDS_RESYNC
|
||||
view = current.copy(
|
||||
result = message.result,
|
||||
clock = (message.clock ?: current.clock)?.copy(running = null)
|
||||
)
|
||||
return Applied.APPLIED
|
||||
}
|
||||
|
||||
fun onClock(clock: SpectatorClock?) {
|
||||
val current = view ?: return
|
||||
if (clock == null || current.result != null) return
|
||||
view = current.copy(clock = clock)
|
||||
}
|
||||
|
||||
private fun resolve(board: Board, uci: String): Move? {
|
||||
if (uci.length !in 4..5) return null
|
||||
val candidate = runCatching { Move.fromUci(uci) }.getOrNull() ?: return null
|
||||
if (candidate.from !in 0..63 || candidate.to !in 0..63) return null
|
||||
val matches = ChessEngine.legalMoves(board).filter { it.from == candidate.from && it.to == candidate.to }
|
||||
return matches.firstOrNull { it.promotion == candidate.promotion } ?: matches.firstOrNull()
|
||||
}
|
||||
}
|
||||
|
||||
/** Turns successive host snapshots into the messages spectators need to follow along. */
|
||||
object SpectatorDiff {
|
||||
fun between(old: SpectatorSnapshot?, new: SpectatorSnapshot): List<SpectatorMessage> {
|
||||
if (old == null) return emptyList()
|
||||
if (old.gameId != new.gameId || old.white != new.white || old.black != new.black) {
|
||||
return listOf(SpectatorMessage.NewGame(new))
|
||||
}
|
||||
val events = ArrayList<SpectatorMessage>()
|
||||
val before = old.movesUci
|
||||
val after = new.movesUci
|
||||
if (after != before) {
|
||||
if (after.size <= before.size || after.subList(0, before.size) != before) {
|
||||
return listOf(SpectatorMessage.NewGame(new))
|
||||
}
|
||||
for (i in before.size until after.size) {
|
||||
val isLast = i == after.lastIndex
|
||||
events += SpectatorMessage.MovePlayed(new.gameId, i + 1, after[i], if (isLast) new.clock else null)
|
||||
}
|
||||
}
|
||||
when {
|
||||
old.result == null && new.result != null -> events += SpectatorMessage.GameOver(new.gameId, new.result, new.clock)
|
||||
old.result != null && new.result != old.result -> return listOf(SpectatorMessage.NewGame(new))
|
||||
}
|
||||
return events
|
||||
}
|
||||
}
|
||||
|
||||
/** Result of a finished game as spectators are told it. */
|
||||
object SpectatorResults {
|
||||
fun of(
|
||||
status: GameStatus,
|
||||
sideToMove: PieceColor,
|
||||
timedOutSide: PieceColor?,
|
||||
resignedSide: PieceColor?,
|
||||
leftMidGame: Boolean
|
||||
): SpectatorResult? = when (status) {
|
||||
GameStatus.ONGOING -> null
|
||||
GameStatus.CHECKMATE -> SpectatorResult(SpectatorOutcome.CHECKMATE, sideToMove.opposite())
|
||||
GameStatus.STALEMATE -> SpectatorResult(SpectatorOutcome.STALEMATE, null)
|
||||
GameStatus.DRAW_50_MOVES -> SpectatorResult(SpectatorOutcome.FIFTY_MOVES, null)
|
||||
GameStatus.DRAW_REPETITION -> SpectatorResult(SpectatorOutcome.REPETITION, null)
|
||||
GameStatus.DRAW_MATERIAL -> SpectatorResult(SpectatorOutcome.INSUFFICIENT_MATERIAL, null)
|
||||
GameStatus.TIMEOUT -> SpectatorResult(SpectatorOutcome.TIMEOUT, timedOutSide?.opposite())
|
||||
GameStatus.TIMEOUT_DRAW -> SpectatorResult(SpectatorOutcome.TIMEOUT_DRAW, null)
|
||||
GameStatus.RESIGNATION -> SpectatorResult(
|
||||
if (leftMidGame) SpectatorOutcome.LEFT else SpectatorOutcome.RESIGNATION,
|
||||
resignedSide?.opposite()
|
||||
)
|
||||
GameStatus.DRAW_AGREEMENT -> SpectatorResult(SpectatorOutcome.AGREEMENT, null)
|
||||
}
|
||||
|
||||
fun leftBy(side: PieceColor) = SpectatorResult(SpectatorOutcome.LEFT, side.opposite())
|
||||
|
||||
val interrupted = SpectatorResult(SpectatorOutcome.INTERRUPTED, null)
|
||||
}
|
||||
@@ -0,0 +1,364 @@
|
||||
package cc.skysparkle.matewave.spectate
|
||||
|
||||
import cc.skysparkle.matewave.network.LineResult
|
||||
import cc.skysparkle.matewave.network.readBoundedLine
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import java.io.BufferedReader
|
||||
import java.io.BufferedWriter
|
||||
import java.io.Closeable
|
||||
import java.io.IOException
|
||||
import java.io.InputStreamReader
|
||||
import java.io.OutputStreamWriter
|
||||
import java.net.InetAddress
|
||||
import java.net.InetSocketAddress
|
||||
import java.net.ServerSocket
|
||||
import java.net.Socket
|
||||
import java.net.SocketTimeoutException
|
||||
import java.util.concurrent.ArrayBlockingQueue
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.concurrent.RejectedExecutionException
|
||||
import java.util.concurrent.ThreadFactory
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
|
||||
/**
|
||||
* Runs on the host player's device and streams the game to up to [maxSpectators] spectators on
|
||||
* its own listening socket; the players' connection is never touched. Each spectator gets its own
|
||||
* bounded queue and writer thread, so a slow or vanished spectator is dropped without delaying
|
||||
* the game or anyone else. Spectators can only listen: anything they send besides keepalives and
|
||||
* resync requests is ignored.
|
||||
*/
|
||||
class SpectatorHub(
|
||||
private val maxSpectators: Int = MAX_SPECTATORS,
|
||||
private val timing: Timing = Timing(),
|
||||
private val log: (String) -> Unit = {}
|
||||
) {
|
||||
data class Timing(
|
||||
val helloTimeoutMs: Int = 5_000,
|
||||
val pingIntervalMs: Long = 5_000,
|
||||
/** A spectator that answers no ping for this long is gone (e.g. its Wi-Fi went off). */
|
||||
val silenceTimeoutMs: Int = 20_000,
|
||||
val queueCapacity: Int = 512
|
||||
)
|
||||
|
||||
private val lock = Any()
|
||||
private val spectators = LinkedHashSet<Spectator>()
|
||||
private var latest: SpectatorSnapshot? = null
|
||||
private var latestAtNanos = 0L
|
||||
private var closed = false
|
||||
private var server: ServerSocket? = null
|
||||
private val handshaking = AtomicInteger()
|
||||
|
||||
private val threads = Executors.newCachedThreadPool(daemonThreads("spectator"))
|
||||
private val ticker = Executors.newSingleThreadScheduledExecutor(daemonThreads("spectator-ping"))
|
||||
|
||||
private val _count = MutableStateFlow(0)
|
||||
val count: StateFlow<Int> = _count
|
||||
|
||||
val port: Int get() = server?.localPort ?: 0
|
||||
|
||||
/** Opens the spectator socket on [bindAddress] (all interfaces by default) and returns its port. */
|
||||
fun start(bindAddress: InetAddress? = null): Int {
|
||||
val socket = synchronized(lock) {
|
||||
check(!closed) { "Hub is closed" }
|
||||
server?.let { return it.localPort }
|
||||
ServerSocket().also {
|
||||
it.reuseAddress = true
|
||||
it.bind(InetSocketAddress(bindAddress, 0))
|
||||
server = it
|
||||
}
|
||||
}
|
||||
threads.execute { acceptLoop(socket) }
|
||||
ticker.scheduleAtFixedRate(
|
||||
{ runCatching { sendPings() } },
|
||||
timing.pingIntervalMs, timing.pingIntervalMs, TimeUnit.MILLISECONDS
|
||||
)
|
||||
return socket.localPort
|
||||
}
|
||||
|
||||
/** Replaces the current game state and sends [events] to every spectator, atomically. */
|
||||
fun publish(snapshot: SpectatorSnapshot, events: List<SpectatorMessage> = emptyList()) {
|
||||
synchronized(lock) {
|
||||
if (closed) return
|
||||
latest = snapshot
|
||||
latestAtNanos = System.nanoTime()
|
||||
if (events.isEmpty() || spectators.isEmpty()) return
|
||||
val targets = spectators.toList()
|
||||
events.forEach { deliver(targets, SpectatorProtocol.encode(it)) }
|
||||
}
|
||||
}
|
||||
|
||||
/** Sends [finalEvents] and a goodbye to everyone, then stops accepting and closes. */
|
||||
fun close(finalEvents: List<SpectatorMessage> = emptyList()) {
|
||||
val targets = synchronized(lock) {
|
||||
if (closed) return
|
||||
closed = true
|
||||
spectators.toList().also { spectators.clear() }
|
||||
}
|
||||
_count.value = 0
|
||||
val lines = finalEvents.map { SpectatorProtocol.encode(it) } + SpectatorProtocol.encode(SpectatorMessage.Closing)
|
||||
targets.forEach { spectator ->
|
||||
lines.forEach { spectator.offer(it) }
|
||||
spectator.finish()
|
||||
}
|
||||
closeQuietly(server)
|
||||
ticker.shutdownNow()
|
||||
threads.shutdown()
|
||||
}
|
||||
|
||||
private fun acceptLoop(socket: ServerSocket) {
|
||||
while (!socket.isClosed) {
|
||||
val client = try {
|
||||
socket.accept()
|
||||
} catch (e: IOException) {
|
||||
if (socket.isClosed) return
|
||||
log("Spectator accept failed: ${e.message}")
|
||||
continue
|
||||
}
|
||||
if (handshaking.incrementAndGet() > MAX_HANDSHAKING) {
|
||||
handshaking.decrementAndGet()
|
||||
closeQuietly(client)
|
||||
continue
|
||||
}
|
||||
try {
|
||||
threads.execute { serve(client) }
|
||||
} catch (e: RejectedExecutionException) {
|
||||
handshaking.decrementAndGet()
|
||||
closeQuietly(client)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun serve(client: Socket) {
|
||||
var spectator: Spectator? = null
|
||||
var reader: BufferedReader? = null
|
||||
try {
|
||||
client.tcpNoDelay = true
|
||||
client.soTimeout = timing.helloTimeoutMs
|
||||
reader = BufferedReader(InputStreamReader(client.getInputStream(), Charsets.UTF_8))
|
||||
val first = readBoundedLine(reader, SpectatorProtocol.MAX_CLIENT_LINE_CHARS)
|
||||
val envelope = (first as? LineResult.Line)?.let { SpectatorProtocol.decode(it.text) }
|
||||
when (envelope?.message) {
|
||||
SpectatorMessage.StatusQuery -> reply(client, status())
|
||||
is SpectatorMessage.Hello -> {
|
||||
if (envelope.version < SpectatorProtocol.MIN_COMPATIBLE_VERSION) {
|
||||
log("Spectator with protocol ${envelope.version} told to update")
|
||||
reply(client, SpectatorMessage.Reject(RejectReason.UPDATE_REQUIRED, SpectatorProtocol.MIN_COMPATIBLE_VERSION))
|
||||
} else {
|
||||
spectator = admit(client)
|
||||
}
|
||||
}
|
||||
else -> Unit
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
// Timed out or closed before saying hello.
|
||||
} finally {
|
||||
handshaking.decrementAndGet()
|
||||
if (spectator == null) closeQuietly(client)
|
||||
}
|
||||
val admitted = spectator ?: return
|
||||
listen(admitted, reader ?: return)
|
||||
}
|
||||
|
||||
private fun admit(client: Socket): Spectator? {
|
||||
var reject: RejectReason? = null
|
||||
var spectator: Spectator? = null
|
||||
synchronized(lock) {
|
||||
val game = latest
|
||||
when {
|
||||
closed || game == null -> reject = RejectReason.NO_GAME
|
||||
spectators.size >= maxSpectators -> reject = RejectReason.FULL
|
||||
else -> {
|
||||
val joined = Spectator(client, timing.queueCapacity)
|
||||
val others = spectators.toList()
|
||||
spectators.add(joined)
|
||||
val n = spectators.size
|
||||
_count.value = n
|
||||
joined.offer(SpectatorProtocol.encode(SpectatorMessage.Welcome(n, maxSpectators, liveSnapshot(game))))
|
||||
deliver(others, SpectatorProtocol.encode(SpectatorMessage.Count(n, maxSpectators)))
|
||||
spectator = joined
|
||||
}
|
||||
}
|
||||
}
|
||||
reject?.let {
|
||||
reply(client, SpectatorMessage.Reject(it, SpectatorProtocol.MIN_COMPATIBLE_VERSION))
|
||||
return null
|
||||
}
|
||||
val joined = spectator ?: return null
|
||||
try {
|
||||
threads.execute { write(joined) }
|
||||
} catch (e: RejectedExecutionException) {
|
||||
drop(joined)
|
||||
return null
|
||||
}
|
||||
return joined
|
||||
}
|
||||
|
||||
private fun listen(spectator: Spectator, reader: BufferedReader) {
|
||||
try {
|
||||
spectator.socket.soTimeout = timing.silenceTimeoutMs
|
||||
while (true) {
|
||||
val read = readBoundedLine(reader, SpectatorProtocol.MAX_CLIENT_LINE_CHARS)
|
||||
if (read !is LineResult.Line) break
|
||||
when (SpectatorProtocol.decode(read.text)?.message) {
|
||||
SpectatorMessage.Resync -> synchronized(lock) {
|
||||
val game = latest
|
||||
if (game != null && !closed) {
|
||||
deliver(listOf(spectator), SpectatorProtocol.encode(SpectatorMessage.NewGame(liveSnapshot(game))))
|
||||
}
|
||||
}
|
||||
SpectatorMessage.Leave -> break
|
||||
else -> Unit
|
||||
}
|
||||
}
|
||||
} catch (e: SocketTimeoutException) {
|
||||
log("Spectator silent for ${timing.silenceTimeoutMs / 1000} s, dropped")
|
||||
} catch (e: IOException) {
|
||||
// Connection reset.
|
||||
} finally {
|
||||
drop(spectator)
|
||||
}
|
||||
}
|
||||
|
||||
private fun write(spectator: Spectator) {
|
||||
try {
|
||||
val out = BufferedWriter(OutputStreamWriter(spectator.socket.getOutputStream(), Charsets.UTF_8))
|
||||
while (true) {
|
||||
val item = spectator.queue.take()
|
||||
if (item === POISON) break
|
||||
out.write(item as String)
|
||||
out.write("\n")
|
||||
if (spectator.queue.isEmpty()) out.flush()
|
||||
}
|
||||
out.flush()
|
||||
} catch (e: IOException) {
|
||||
// Spectator went away.
|
||||
} catch (e: InterruptedException) {
|
||||
Thread.currentThread().interrupt()
|
||||
} finally {
|
||||
drop(spectator)
|
||||
closeQuietly(spectator.socket)
|
||||
}
|
||||
}
|
||||
|
||||
private fun sendPings() {
|
||||
val line: String
|
||||
val targets: List<Spectator>
|
||||
synchronized(lock) {
|
||||
if (closed || spectators.isEmpty()) return
|
||||
line = SpectatorProtocol.encode(SpectatorMessage.Ping(liveClock()))
|
||||
targets = spectators.toList()
|
||||
}
|
||||
deliver(targets, line)
|
||||
}
|
||||
|
||||
private fun deliver(targets: List<Spectator>, line: String) {
|
||||
for (spectator in targets) {
|
||||
if (!spectator.offer(line)) {
|
||||
log("Spectator too slow, dropped")
|
||||
drop(spectator)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun drop(spectator: Spectator) {
|
||||
val others: List<Spectator>
|
||||
val remaining: Int
|
||||
synchronized(lock) {
|
||||
// Already dropped, or the hub is closing and its writer is flushing the goodbye.
|
||||
if (!spectators.remove(spectator)) return
|
||||
remaining = spectators.size
|
||||
_count.value = remaining
|
||||
others = spectators.toList()
|
||||
}
|
||||
spectator.shutdown()
|
||||
if (!closed) deliver(others, SpectatorProtocol.encode(SpectatorMessage.Count(remaining, maxSpectators)))
|
||||
}
|
||||
|
||||
private fun status(): SpectatorMessage.Status = synchronized(lock) {
|
||||
val game = latest
|
||||
SpectatorMessage.Status(
|
||||
inGame = !closed && game != null && game.result == null,
|
||||
count = spectators.size,
|
||||
max = maxSpectators,
|
||||
minVersion = SpectatorProtocol.MIN_COMPATIBLE_VERSION
|
||||
)
|
||||
}
|
||||
|
||||
private fun elapsedMs(): Long = (System.nanoTime() - latestAtNanos) / 1_000_000L
|
||||
|
||||
private fun liveClock(): SpectatorClock? = latest?.clock?.advancedBy(elapsedMs())
|
||||
|
||||
private fun liveSnapshot(game: SpectatorSnapshot): SpectatorSnapshot =
|
||||
if (game.clock == null) game else game.copy(clock = game.clock.advancedBy(elapsedMs()))
|
||||
|
||||
private fun reply(client: Socket, message: SpectatorMessage) {
|
||||
try {
|
||||
val out = client.getOutputStream()
|
||||
out.write((SpectatorProtocol.encode(message) + "\n").toByteArray(Charsets.UTF_8))
|
||||
out.flush()
|
||||
} catch (e: IOException) {
|
||||
// Nothing more to tell a peer that is gone.
|
||||
}
|
||||
}
|
||||
|
||||
/** One spectator's outgoing queue; one slot is kept free for the end marker. */
|
||||
private class Spectator(val socket: Socket, private val capacity: Int) {
|
||||
val queue = ArrayBlockingQueue<Any>(capacity + 1)
|
||||
private var open = true
|
||||
|
||||
@Synchronized
|
||||
fun offer(line: String): Boolean = open && queue.size < capacity && queue.offer(line)
|
||||
|
||||
/** Lets the writer send what is queued, then close. */
|
||||
@Synchronized
|
||||
fun finish() {
|
||||
if (!open) return
|
||||
open = false
|
||||
queue.offer(POISON)
|
||||
}
|
||||
|
||||
/** Stops at once, discarding anything unsent. */
|
||||
@Synchronized
|
||||
fun shutdown() {
|
||||
open = false
|
||||
queue.clear()
|
||||
queue.offer(POISON)
|
||||
closeQuietly(socket)
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
val POISON = Any()
|
||||
|
||||
/** Connections allowed to sit in the hello phase at once. */
|
||||
const val MAX_HANDSHAKING = 32
|
||||
|
||||
fun closeQuietly(c: Closeable?) {
|
||||
try { c?.close() } catch (_: IOException) {}
|
||||
}
|
||||
|
||||
fun daemonThreads(name: String): ThreadFactory {
|
||||
val n = AtomicInteger()
|
||||
return ThreadFactory { r -> Thread(r, "$name-${n.incrementAndGet()}").apply { isDaemon = true } }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Feeds a hub from the host's game: each new snapshot becomes the messages spectators need. */
|
||||
class SpectatorBroadcaster(val hub: SpectatorHub) {
|
||||
private var last: SpectatorSnapshot? = null
|
||||
|
||||
fun update(snapshot: SpectatorSnapshot) {
|
||||
val events = SpectatorDiff.between(last, snapshot)
|
||||
last = snapshot
|
||||
hub.publish(snapshot, events)
|
||||
}
|
||||
|
||||
/** Stops spectating; [final] is the last state, e.g. the result of a game left midway. */
|
||||
fun close(final: SpectatorSnapshot? = null) {
|
||||
val events = if (final != null) SpectatorDiff.between(last, final) else emptyList()
|
||||
hub.close(events)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
package cc.skysparkle.matewave.spectate
|
||||
|
||||
import cc.skysparkle.matewave.engine.PieceColor
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
|
||||
/** Most spectators one hosted game accepts at the same time. */
|
||||
const val MAX_SPECTATORS = 20
|
||||
|
||||
data class SpectatorPlayer(val id: String, val name: String, val elo: Int)
|
||||
|
||||
data class SpectatorClock(val whiteMs: Long, val blackMs: Long, val running: PieceColor?) {
|
||||
/** The same clock [elapsedMs] later. */
|
||||
fun advancedBy(elapsedMs: Long): SpectatorClock {
|
||||
if (elapsedMs <= 0) return this
|
||||
return when (running) {
|
||||
PieceColor.WHITE -> copy(whiteMs = (whiteMs - elapsedMs).coerceAtLeast(0))
|
||||
PieceColor.BLACK -> copy(blackMs = (blackMs - elapsedMs).coerceAtLeast(0))
|
||||
null -> this
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum class SpectatorOutcome(val wire: String) {
|
||||
CHECKMATE("checkmate"),
|
||||
STALEMATE("stalemate"),
|
||||
FIFTY_MOVES("fifty"),
|
||||
REPETITION("repetition"),
|
||||
INSUFFICIENT_MATERIAL("material"),
|
||||
TIMEOUT("timeout"),
|
||||
TIMEOUT_DRAW("timeout_draw"),
|
||||
RESIGNATION("resign"),
|
||||
AGREEMENT("agreement"),
|
||||
LEFT("left"),
|
||||
INTERRUPTED("interrupted"),
|
||||
UNKNOWN("unknown");
|
||||
|
||||
companion object {
|
||||
fun fromWire(value: String): SpectatorOutcome = entries.firstOrNull { it.wire == value } ?: UNKNOWN
|
||||
}
|
||||
}
|
||||
|
||||
/** How a game ended; [winner] is null for draws and interrupted games. */
|
||||
data class SpectatorResult(val outcome: SpectatorOutcome, val winner: PieceColor?)
|
||||
|
||||
/** Everything a spectator needs to show a game from any point: players, moves, clocks, result. */
|
||||
data class SpectatorSnapshot(
|
||||
val gameId: String,
|
||||
val white: SpectatorPlayer,
|
||||
val black: SpectatorPlayer,
|
||||
val movesUci: List<String>,
|
||||
val initialSeconds: Int,
|
||||
val incrementSeconds: Int,
|
||||
val clock: SpectatorClock?,
|
||||
val result: SpectatorResult? = null
|
||||
)
|
||||
|
||||
enum class RejectReason(val wire: String) {
|
||||
FULL("full"),
|
||||
UPDATE_REQUIRED("update"),
|
||||
NO_GAME("no_game"),
|
||||
OTHER("other");
|
||||
|
||||
companion object {
|
||||
fun fromWire(value: String): RejectReason = entries.firstOrNull { it.wire == value } ?: OTHER
|
||||
}
|
||||
}
|
||||
|
||||
sealed class SpectatorMessage {
|
||||
// Spectator to host.
|
||||
data class Hello(val minVersion: Int = SpectatorProtocol.MIN_COMPATIBLE_VERSION) : SpectatorMessage()
|
||||
data object StatusQuery : SpectatorMessage()
|
||||
data object Pong : SpectatorMessage()
|
||||
data object Resync : SpectatorMessage()
|
||||
data object Leave : SpectatorMessage()
|
||||
|
||||
// Host to spectator.
|
||||
data class Welcome(val count: Int, val max: Int, val game: SpectatorSnapshot) : SpectatorMessage()
|
||||
data class Status(val inGame: Boolean, val count: Int, val max: Int, val minVersion: Int) : SpectatorMessage()
|
||||
data class Reject(val reason: RejectReason, val minVersion: Int) : SpectatorMessage()
|
||||
data class MovePlayed(val gameId: String, val ply: Int, val uci: String, val clock: SpectatorClock?) : SpectatorMessage()
|
||||
data class GameOver(val gameId: String, val result: SpectatorResult, val clock: SpectatorClock?) : SpectatorMessage()
|
||||
data class NewGame(val game: SpectatorSnapshot) : SpectatorMessage()
|
||||
data class Count(val count: Int, val max: Int) : SpectatorMessage()
|
||||
data class Ping(val clock: SpectatorClock?) : SpectatorMessage()
|
||||
data object Closing : SpectatorMessage()
|
||||
}
|
||||
|
||||
/** One decoded line: the sender's protocol version and the message, or null for an unknown type. */
|
||||
data class SpectatorEnvelope(val version: Int, val message: SpectatorMessage?)
|
||||
|
||||
/**
|
||||
* Wire format between a hosted game and its spectators: one JSON object per line, each carrying
|
||||
* the sender's protocol version in "sv". Unknown types are skipped, never fatal.
|
||||
*/
|
||||
object SpectatorProtocol {
|
||||
/**
|
||||
* Bump on incompatible changes and raise [MIN_COMPATIBLE_VERSION] to the oldest version still
|
||||
* understood. hello, status and reject keep their shape so any two versions can still tell
|
||||
* each other that an update is required.
|
||||
*/
|
||||
const val VERSION = 1
|
||||
const val MIN_COMPATIBLE_VERSION = 1
|
||||
|
||||
const val MAX_HOST_LINE_CHARS = 64_000
|
||||
const val MAX_CLIENT_LINE_CHARS = 1_024
|
||||
|
||||
private const val MAX_NAME_CHARS = 40
|
||||
private const val MAX_PLIES = 2_000
|
||||
|
||||
fun encode(message: SpectatorMessage, version: Int = VERSION): String {
|
||||
val o = JSONObject()
|
||||
o.put("sv", version)
|
||||
when (message) {
|
||||
is SpectatorMessage.Hello -> { o.put("type", "hello"); o.put("min", message.minVersion) }
|
||||
SpectatorMessage.StatusQuery -> o.put("type", "query")
|
||||
SpectatorMessage.Pong -> o.put("type", "pong")
|
||||
SpectatorMessage.Resync -> o.put("type", "resync")
|
||||
SpectatorMessage.Leave -> o.put("type", "leave")
|
||||
is SpectatorMessage.Welcome -> {
|
||||
o.put("type", "welcome"); o.put("n", message.count); o.put("max", message.max)
|
||||
o.put("game", snapshotJson(message.game))
|
||||
}
|
||||
is SpectatorMessage.Status -> {
|
||||
o.put("type", "status"); o.put("live", message.inGame)
|
||||
o.put("n", message.count); o.put("max", message.max); o.put("min", message.minVersion)
|
||||
}
|
||||
is SpectatorMessage.Reject -> {
|
||||
o.put("type", "reject"); o.put("reason", message.reason.wire); o.put("min", message.minVersion)
|
||||
}
|
||||
is SpectatorMessage.MovePlayed -> {
|
||||
o.put("type", "move"); o.put("gid", message.gameId); o.put("ply", message.ply); o.put("uci", message.uci)
|
||||
message.clock?.let { o.put("clock", clockJson(it)) }
|
||||
}
|
||||
is SpectatorMessage.GameOver -> {
|
||||
o.put("type", "end"); o.put("gid", message.gameId); o.put("result", resultJson(message.result))
|
||||
message.clock?.let { o.put("clock", clockJson(it)) }
|
||||
}
|
||||
is SpectatorMessage.NewGame -> { o.put("type", "game"); o.put("game", snapshotJson(message.game)) }
|
||||
is SpectatorMessage.Count -> { o.put("type", "count"); o.put("n", message.count); o.put("max", message.max) }
|
||||
is SpectatorMessage.Ping -> {
|
||||
o.put("type", "ping")
|
||||
message.clock?.let { o.put("clock", clockJson(it)) }
|
||||
}
|
||||
SpectatorMessage.Closing -> o.put("type", "closing")
|
||||
}
|
||||
return o.toString()
|
||||
}
|
||||
|
||||
/** Null when the line is not a protocol message at all. */
|
||||
fun decode(line: String): SpectatorEnvelope? {
|
||||
val o = runCatching { JSONObject(line) }.getOrNull() ?: return null
|
||||
val type = o.optString("type", "")
|
||||
if (type.isEmpty()) return null
|
||||
val version = o.optInt("sv", 0)
|
||||
val message = runCatching { decodeMessage(type, o) }.getOrNull()
|
||||
return SpectatorEnvelope(version, message)
|
||||
}
|
||||
|
||||
private fun decodeMessage(type: String, o: JSONObject): SpectatorMessage? = when (type) {
|
||||
"hello" -> SpectatorMessage.Hello(o.optInt("min", o.optInt("sv", 0)))
|
||||
"query" -> SpectatorMessage.StatusQuery
|
||||
"pong" -> SpectatorMessage.Pong
|
||||
"resync" -> SpectatorMessage.Resync
|
||||
"leave" -> SpectatorMessage.Leave
|
||||
"welcome" -> SpectatorMessage.Welcome(o.getInt("n"), o.getInt("max"), parseSnapshot(o.getJSONObject("game")))
|
||||
"status" -> SpectatorMessage.Status(o.getBoolean("live"), o.getInt("n"), o.getInt("max"), o.optInt("min", 0))
|
||||
"reject" -> SpectatorMessage.Reject(RejectReason.fromWire(o.getString("reason")), o.optInt("min", 0))
|
||||
"move" -> SpectatorMessage.MovePlayed(
|
||||
o.getString("gid"), o.getInt("ply"), o.getString("uci"), o.optJSONObject("clock")?.let(::parseClock)
|
||||
)
|
||||
"end" -> SpectatorMessage.GameOver(
|
||||
o.getString("gid"), parseResult(o.getJSONObject("result")), o.optJSONObject("clock")?.let(::parseClock)
|
||||
)
|
||||
"game" -> SpectatorMessage.NewGame(parseSnapshot(o.getJSONObject("game")))
|
||||
"count" -> SpectatorMessage.Count(o.getInt("n"), o.getInt("max"))
|
||||
"ping" -> SpectatorMessage.Ping(o.optJSONObject("clock")?.let(::parseClock))
|
||||
"closing" -> SpectatorMessage.Closing
|
||||
else -> null
|
||||
}
|
||||
|
||||
private fun sideWire(side: PieceColor?): String = when (side) {
|
||||
PieceColor.WHITE -> "w"
|
||||
PieceColor.BLACK -> "b"
|
||||
null -> ""
|
||||
}
|
||||
|
||||
private fun sideOf(wire: String): PieceColor? = when (wire) {
|
||||
"w" -> PieceColor.WHITE
|
||||
"b" -> PieceColor.BLACK
|
||||
else -> null
|
||||
}
|
||||
|
||||
private fun clockJson(c: SpectatorClock) = JSONObject().apply {
|
||||
put("w", c.whiteMs); put("b", c.blackMs)
|
||||
if (c.running != null) put("r", sideWire(c.running))
|
||||
}
|
||||
|
||||
private fun parseClock(o: JSONObject) = SpectatorClock(
|
||||
whiteMs = o.getLong("w").coerceAtLeast(0),
|
||||
blackMs = o.getLong("b").coerceAtLeast(0),
|
||||
running = sideOf(o.optString("r", ""))
|
||||
)
|
||||
|
||||
private fun resultJson(r: SpectatorResult) = JSONObject().apply {
|
||||
put("o", r.outcome.wire)
|
||||
if (r.winner != null) put("w", sideWire(r.winner))
|
||||
}
|
||||
|
||||
private fun parseResult(o: JSONObject) = SpectatorResult(
|
||||
outcome = SpectatorOutcome.fromWire(o.getString("o")),
|
||||
winner = sideOf(o.optString("w", ""))
|
||||
)
|
||||
|
||||
private fun playerJson(p: SpectatorPlayer) = JSONObject().apply {
|
||||
put("id", p.id); put("name", p.name); put("elo", p.elo)
|
||||
}
|
||||
|
||||
private fun parsePlayer(o: JSONObject) = SpectatorPlayer(
|
||||
id = o.optString("id", "").take(64),
|
||||
name = o.optString("name", "").take(MAX_NAME_CHARS),
|
||||
elo = o.optInt("elo", 0)
|
||||
)
|
||||
|
||||
private fun snapshotJson(s: SpectatorSnapshot) = JSONObject().apply {
|
||||
put("gid", s.gameId)
|
||||
put("wp", playerJson(s.white))
|
||||
put("bp", playerJson(s.black))
|
||||
put("moves", JSONArray().also { array -> s.movesUci.forEach { array.put(it) } })
|
||||
put("ti", s.initialSeconds)
|
||||
put("tx", s.incrementSeconds)
|
||||
s.clock?.let { put("clock", clockJson(it)) }
|
||||
s.result?.let { put("result", resultJson(it)) }
|
||||
}
|
||||
|
||||
private fun parseSnapshot(o: JSONObject): SpectatorSnapshot {
|
||||
val array = o.getJSONArray("moves")
|
||||
require(array.length() <= MAX_PLIES)
|
||||
return SpectatorSnapshot(
|
||||
gameId = o.getString("gid"),
|
||||
white = parsePlayer(o.getJSONObject("wp")),
|
||||
black = parsePlayer(o.getJSONObject("bp")),
|
||||
movesUci = List(array.length()) { array.getString(it) },
|
||||
initialSeconds = o.optInt("ti", 0),
|
||||
incrementSeconds = o.optInt("tx", 0),
|
||||
clock = o.optJSONObject("clock")?.let(::parseClock),
|
||||
result = o.optJSONObject("result")?.let(::parseResult)
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -78,14 +78,16 @@ fun ChessBoardView(
|
||||
interactionEnabled: Boolean = true,
|
||||
/** A square briefly tinted to confirm or reject a move (puzzles). */
|
||||
flashSquare: Int? = null,
|
||||
flashColor: Color = Color.Transparent
|
||||
flashColor: Color = Color.Transparent,
|
||||
/** Overrides the last-move setting; null follows it. */
|
||||
highlightLastMove: Boolean? = null
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val appearance = remember { BoardAppearance(context) }
|
||||
val theme = appearance.theme
|
||||
val showCoords = appearance.showCoordinates
|
||||
val imagePieces = appearance.useImagePieces
|
||||
val showLastMove = appearance.showLastMove
|
||||
val showLastMove = highlightLastMove ?: appearance.showLastMove
|
||||
val showCheck = appearance.showCheckHighlight
|
||||
|
||||
val pieceImages = if (imagePieces) remember(context) { PieceImages.get(context) } else null
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
package cc.skysparkle.matewave.ui.components
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.clearAndSetSemantics
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.unit.dp
|
||||
import cc.skysparkle.matewave.R
|
||||
import cc.skysparkle.matewave.ui.theme.ink
|
||||
|
||||
/** Small, quiet spectator counter for the top bar: an eye and "7" or "7/20". */
|
||||
@Composable
|
||||
fun SpectatorBadge(count: Int, max: Int? = null, modifier: Modifier = Modifier) {
|
||||
val description = stringResource(R.string.spectators_description, count)
|
||||
Row(
|
||||
modifier = modifier
|
||||
.padding(end = 12.dp)
|
||||
.clip(RoundedCornerShape(50))
|
||||
.background(ink.copy(alpha = 0.10f))
|
||||
.padding(horizontal = 10.dp, vertical = 4.dp)
|
||||
.clearAndSetSemantics { contentDescription = description },
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(6.dp)
|
||||
) {
|
||||
AppIcon(R.drawable.ic_spectators, size = 16.dp, tint = ink.copy(alpha = 0.7f))
|
||||
Text(
|
||||
if (max != null) "$count/$max" else count.toString(),
|
||||
color = ink.copy(alpha = 0.8f),
|
||||
style = MaterialTheme.typography.labelMedium
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -46,6 +46,15 @@ import cc.skysparkle.matewave.ui.components.AppIcon
|
||||
import cc.skysparkle.matewave.ui.components.BottomTab
|
||||
import cc.skysparkle.matewave.ui.components.GlassScaffold
|
||||
import cc.skysparkle.matewave.ui.theme.ChessGreen
|
||||
import cc.skysparkle.matewave.spectate.FriendGameStatus
|
||||
import cc.skysparkle.matewave.spectate.FriendStatusResolver
|
||||
import cc.skysparkle.matewave.spectate.NearbyPlayerGame
|
||||
import cc.skysparkle.matewave.spectate.PresenceStatus
|
||||
import cc.skysparkle.matewave.spectate.SpectateTarget
|
||||
import cc.skysparkle.matewave.spectate.SpectatorMessage
|
||||
import cc.skysparkle.matewave.spectate.SpectatorProbe
|
||||
import kotlinx.coroutines.async
|
||||
import kotlinx.coroutines.awaitAll
|
||||
|
||||
@Composable
|
||||
fun FriendsScreen(
|
||||
@@ -53,7 +62,8 @@ fun FriendsScreen(
|
||||
onHomeClick: () -> Unit,
|
||||
onSettingsClick: () -> Unit,
|
||||
onAccountClick: () -> Unit,
|
||||
onPlay: () -> Unit = {}
|
||||
onPlay: () -> Unit = {},
|
||||
onWatch: (SpectateTarget) -> Unit = {}
|
||||
) {
|
||||
var onlineOnly by remember { mutableStateOf(false) }
|
||||
var version by remember { mutableStateOf(0) }
|
||||
@@ -64,6 +74,28 @@ fun FriendsScreen(
|
||||
val peers by presence.peers.collectAsState()
|
||||
val friends = remember(peers, version) { FriendsStore.list() }
|
||||
|
||||
// Who plays a LAN game, and live spectator counts from each host while the list is open.
|
||||
val nearbyGames = remember(peers) {
|
||||
peers.values.associate { it.playerId to NearbyPlayerGame(it.playerId, it.host, it.gameTag, it.spectatePort) }
|
||||
}
|
||||
val hosts = remember(nearbyGames) { FriendStatusResolver.targets(nearbyGames.values) }
|
||||
var probes by remember { mutableStateOf<Map<SpectateTarget, SpectatorMessage.Status>>(emptyMap()) }
|
||||
androidx.compose.runtime.LaunchedEffect(hosts) {
|
||||
if (hosts.isEmpty()) {
|
||||
probes = emptyMap()
|
||||
return@LaunchedEffect
|
||||
}
|
||||
while (true) {
|
||||
probes = kotlinx.coroutines.coroutineScope {
|
||||
hosts.map { host ->
|
||||
async(kotlinx.coroutines.Dispatchers.IO) { SpectatorProbe.query(host.host, host.port)?.let { host to it } }
|
||||
}.awaitAll().filterNotNull().toMap()
|
||||
}
|
||||
kotlinx.coroutines.delay(PROBE_INTERVAL_MS)
|
||||
}
|
||||
}
|
||||
val statusOf: (String) -> FriendGameStatus = { id -> FriendStatusResolver.resolve(id, nearbyGames, probes) }
|
||||
|
||||
// Fresh search on opening, then refresh "5 min ago" labels while the screen is visible.
|
||||
androidx.compose.runtime.LaunchedEffect(Unit) {
|
||||
presence.refresh()
|
||||
@@ -115,18 +147,20 @@ fun FriendsScreen(
|
||||
FriendGroup(
|
||||
title = stringResource(R.string.friends_group_favorites),
|
||||
list = favorites,
|
||||
isOnline = presence::isOnline,
|
||||
statusOf = statusOf,
|
||||
onOpen = { opened = it },
|
||||
onToggleFavorite = { FriendsStore.toggleFavorite(it.userId); version++ },
|
||||
onPlay = onPlay
|
||||
onPlay = onPlay,
|
||||
onWatch = onWatch
|
||||
)
|
||||
FriendGroup(
|
||||
title = if (favorites.isNotEmpty()) stringResource(R.string.friends_group_others) else null,
|
||||
list = others,
|
||||
isOnline = presence::isOnline,
|
||||
statusOf = statusOf,
|
||||
onOpen = { opened = it },
|
||||
onToggleFavorite = { FriendsStore.toggleFavorite(it.userId); version++ },
|
||||
onPlay = onPlay
|
||||
onPlay = onPlay,
|
||||
onWatch = onWatch
|
||||
)
|
||||
|
||||
if (strangers.isNotEmpty()) {
|
||||
@@ -134,11 +168,13 @@ fun FriendsScreen(
|
||||
ListGroup {
|
||||
strangers.sortedBy { it.name }.forEachIndexed { index, peer ->
|
||||
if (index > 0) ListDivider(inset = 68)
|
||||
val status = statusOf(peer.playerId)
|
||||
ListRow(
|
||||
title = displayName(peer.name, peer.playerId),
|
||||
subtitle = stringResource(R.string.friends_rating, peer.elo),
|
||||
subtitle = stringResource(R.string.friends_rating, peer.elo) + " · " + statusText(status.status, 0),
|
||||
subtitleColor = statusColor(status.status),
|
||||
leading = { AvatarCircle(base64 = null, size = 40.dp) },
|
||||
trailing = { PlayChip(onPlay) }
|
||||
trailing = { StatusAction(status, onPlay, onWatch) }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -149,7 +185,7 @@ fun FriendsScreen(
|
||||
}
|
||||
|
||||
opened?.let { friend ->
|
||||
FriendCard(friend = friend, online = presence.isOnline(friend.userId), onDismiss = { opened = null })
|
||||
FriendCard(friend = friend, status = statusOf(friend.userId).status, onDismiss = { opened = null })
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -158,10 +194,11 @@ fun FriendsScreen(
|
||||
private fun FriendGroup(
|
||||
title: String?,
|
||||
list: List<FriendEntry>,
|
||||
isOnline: (String) -> Boolean,
|
||||
statusOf: (String) -> FriendGameStatus,
|
||||
onOpen: (FriendEntry) -> Unit,
|
||||
onToggleFavorite: (FriendEntry) -> Unit,
|
||||
onPlay: () -> Unit
|
||||
onPlay: () -> Unit,
|
||||
onWatch: (SpectateTarget) -> Unit
|
||||
) {
|
||||
if (list.isEmpty()) return
|
||||
if (title != null) SectionCaption(title)
|
||||
@@ -170,10 +207,11 @@ private fun FriendGroup(
|
||||
if (index > 0) ListDivider(inset = 68)
|
||||
FriendRow(
|
||||
friend = friend,
|
||||
online = isOnline(friend.userId),
|
||||
status = statusOf(friend.userId),
|
||||
onOpen = { onOpen(friend) },
|
||||
onToggleFavorite = { onToggleFavorite(friend) },
|
||||
onPlay = onPlay
|
||||
onPlay = onPlay,
|
||||
onWatch = onWatch
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -205,7 +243,7 @@ private fun PlayChip(onClick: () -> Unit) {
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun FriendCard(friend: FriendEntry, online: Boolean, onDismiss: () -> Unit) {
|
||||
private fun FriendCard(friend: FriendEntry, status: PresenceStatus, onDismiss: () -> Unit) {
|
||||
Dialog(onDismissRequest = onDismiss) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
@@ -257,9 +295,12 @@ private fun FriendCard(friend: FriendEntry, online: Boolean, onDismiss: () -> Un
|
||||
}
|
||||
Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
Text(
|
||||
if (online) stringResource(R.string.friends_online)
|
||||
else lastSeenText(maxOf(friend.lastPlayedMs, friend.lastSeenMs)),
|
||||
color = if (online) Color(0xFF7BE495) else ink.copy(alpha = 0.6f),
|
||||
statusText(status, maxOf(friend.lastPlayedMs, friend.lastSeenMs)),
|
||||
color = when (status) {
|
||||
PresenceStatus.ONLINE -> Color(0xFF7BE495)
|
||||
PresenceStatus.IN_GAME -> InGameColor
|
||||
PresenceStatus.OFFLINE -> ink.copy(alpha = 0.6f)
|
||||
},
|
||||
style = MaterialTheme.typography.bodyMedium
|
||||
)
|
||||
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
|
||||
@@ -276,32 +317,33 @@ private fun FriendCard(friend: FriendEntry, online: Boolean, onDismiss: () -> Un
|
||||
@Composable
|
||||
private fun FriendRow(
|
||||
friend: FriendEntry,
|
||||
online: Boolean,
|
||||
status: FriendGameStatus,
|
||||
onOpen: () -> Unit,
|
||||
onToggleFavorite: () -> Unit,
|
||||
onPlay: () -> Unit
|
||||
onPlay: () -> Unit,
|
||||
onWatch: (SpectateTarget) -> Unit
|
||||
) {
|
||||
ListRow(
|
||||
title = displayName(friend.name, friend.userId),
|
||||
subtitle = stringResource(R.string.friends_rating, friend.elo) + " · " +
|
||||
(if (online) stringResource(R.string.friends_online) else lastSeenText(maxOf(friend.lastPlayedMs, friend.lastSeenMs))),
|
||||
subtitleColor = if (online) ChessGreen else ink.copy(alpha = 0.55f),
|
||||
statusText(status.status, maxOf(friend.lastPlayedMs, friend.lastSeenMs)),
|
||||
subtitleColor = statusColor(status.status),
|
||||
leading = {
|
||||
Box {
|
||||
AvatarCircle(base64 = friend.avatarBase64, size = 40.dp)
|
||||
if (online) {
|
||||
if (status.status != PresenceStatus.OFFLINE) {
|
||||
Box(
|
||||
Modifier
|
||||
.align(Alignment.BottomEnd)
|
||||
.size(11.dp)
|
||||
.clip(CircleShape)
|
||||
.background(ChessGreen)
|
||||
.background(if (status.status == PresenceStatus.IN_GAME) InGameColor else ChessGreen)
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
trailing = {
|
||||
if (online) PlayChip(onPlay)
|
||||
StatusAction(status, onPlay, onWatch)
|
||||
AppIcon(
|
||||
R.drawable.ic_star,
|
||||
size = 20.dp,
|
||||
@@ -317,6 +359,58 @@ private fun FriendRow(
|
||||
)
|
||||
}
|
||||
|
||||
private val InGameColor = Color(0xFFFFB86B)
|
||||
|
||||
private const val PROBE_INTERVAL_MS = 3_000L
|
||||
|
||||
/** Play for someone who is free, Watch (with the live count) for someone in a LAN game. */
|
||||
@Composable
|
||||
private fun StatusAction(status: FriendGameStatus, onPlay: () -> Unit, onWatch: (SpectateTarget) -> Unit) {
|
||||
when (status.status) {
|
||||
PresenceStatus.ONLINE -> PlayChip(onPlay)
|
||||
PresenceStatus.IN_GAME -> status.target?.let { target -> WatchChip(status) { onWatch(target) } }
|
||||
PresenceStatus.OFFLINE -> Unit
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun WatchChip(status: FriendGameStatus, onClick: () -> Unit) {
|
||||
val enabled = !status.full
|
||||
val spectators = status.spectators
|
||||
val label = when {
|
||||
status.full -> stringResource(R.string.friends_watch_full)
|
||||
spectators != null -> stringResource(R.string.friends_watch_count, spectators, status.max)
|
||||
else -> stringResource(R.string.friends_watch)
|
||||
}
|
||||
Text(
|
||||
label,
|
||||
color = if (enabled) Color.White else ink.copy(alpha = 0.5f),
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
maxLines = 1,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(50))
|
||||
.background(if (enabled) ChessGreen else ink.copy(alpha = 0.12f))
|
||||
.then(if (enabled) Modifier.clickable(onClick = onClick) else Modifier)
|
||||
.padding(horizontal = 14.dp, vertical = 6.dp)
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun statusText(status: PresenceStatus, lastSeenMs: Long): String = when (status) {
|
||||
PresenceStatus.ONLINE -> stringResource(R.string.friends_online)
|
||||
PresenceStatus.IN_GAME -> stringResource(R.string.friends_in_game)
|
||||
PresenceStatus.OFFLINE ->
|
||||
if (lastSeenMs <= 0) stringResource(R.string.friends_offline)
|
||||
else stringResource(R.string.friends_offline) + " · " + lastSeenText(lastSeenMs)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun statusColor(status: PresenceStatus): Color = when (status) {
|
||||
PresenceStatus.ONLINE -> ChessGreen
|
||||
PresenceStatus.IN_GAME -> InGameColor
|
||||
PresenceStatus.OFFLINE -> ink.copy(alpha = 0.55f)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun lastSeenText(lastSeenMs: Long): String {
|
||||
if (lastSeenMs <= 0) return stringResource(R.string.friends_offline)
|
||||
|
||||
@@ -101,6 +101,11 @@ fun GameScreen(viewModel: GameViewModel, onExit: () -> Unit) {
|
||||
GlassScaffold(
|
||||
title = "",
|
||||
onBack = requestExit,
|
||||
actions = {
|
||||
if (state.mode == GameMode.VS_PLAYER_NETWORK && state.spectatorCount > 0) {
|
||||
cc.skysparkle.matewave.ui.components.SpectatorBadge(state.spectatorCount)
|
||||
}
|
||||
},
|
||||
titleContent = if (showOpening && opening != null) {
|
||||
{ OpeningTitle("${opening.eco} · ${opening.name}", bookStatus, inBook) }
|
||||
} else null
|
||||
@@ -490,7 +495,7 @@ private fun PlayerRow(
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun BigClock(millis: Long, active: Boolean) {
|
||||
internal fun BigClock(millis: Long, active: Boolean) {
|
||||
val totalSeconds = millis / 1000
|
||||
val low = active && totalSeconds < 20
|
||||
val color = when {
|
||||
|
||||
@@ -84,10 +84,6 @@ fun MainMenuScreen(
|
||||
onFriendsClick: () -> Unit
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
androidx.compose.runtime.DisposableEffect(Unit) {
|
||||
cc.skysparkle.matewave.audio.SoundManager.setMenuVisible(true)
|
||||
onDispose { cc.skysparkle.matewave.audio.SoundManager.setMenuVisible(false) }
|
||||
}
|
||||
val resumable by viewModel.resumable.collectAsState()
|
||||
val ongoing = resumable
|
||||
val hasOngoingGame = ongoing != null
|
||||
|
||||
@@ -60,7 +60,6 @@ fun SettingsScreen(
|
||||
onOpenShare: () -> Unit
|
||||
) {
|
||||
var musicOn by remember { mutableStateOf(SoundManager.musicEnabled) }
|
||||
var menuMusicOn by remember { mutableStateOf(SoundManager.menuMusicEnabled) }
|
||||
var sfxOn by remember { mutableStateOf(SoundManager.sfxEnabled) }
|
||||
val context = LocalContext.current
|
||||
|
||||
@@ -83,6 +82,11 @@ fun SettingsScreen(
|
||||
val status = remember(statusTick) {
|
||||
cc.skysparkle.matewave.network.NetworkRequirements.check(context)
|
||||
}
|
||||
// Wi-Fi alone used to count as "All set" even with the nearby permission denied
|
||||
val permissionsMissing = remember(statusTick) {
|
||||
!status.permissionsGranted ||
|
||||
(cc.skysparkle.matewave.presence.PresenceSettings(context).backgroundEnabled && !status.notificationsGranted)
|
||||
}
|
||||
LaunchedEffect(Unit) {
|
||||
while (true) { kotlinx.coroutines.delay(3_000); statusTick++ }
|
||||
}
|
||||
@@ -107,13 +111,6 @@ fun SettingsScreen(
|
||||
) {
|
||||
SectionCaption(stringResource(R.string.settings_section_sound))
|
||||
ListGroup {
|
||||
ListRow(
|
||||
title = stringResource(R.string.settings_menu_music),
|
||||
subtitle = stringResource(R.string.settings_menu_music_subtitle),
|
||||
icon = R.drawable.ic_music,
|
||||
trailing = { SettingSwitch(menuMusicOn) { menuMusicOn = it; SoundManager.setMenuMusicEnabled(it) } }
|
||||
)
|
||||
ListDivider()
|
||||
ListRow(
|
||||
title = stringResource(R.string.settings_radio),
|
||||
subtitle = stringResource(R.string.settings_radio_subtitle),
|
||||
@@ -157,10 +154,10 @@ fun SettingsScreen(
|
||||
ListGroup {
|
||||
ListRow(
|
||||
title = stringResource(R.string.permissions_card_title),
|
||||
icon = if (status.onlineBlocked) R.drawable.ic_permissions else R.drawable.ic_check_permission,
|
||||
iconTint = if (status.onlineBlocked) Color(0xFFFF6B6B) else ChessGreen,
|
||||
value = stringResource(if (status.onlineBlocked) R.string.permissions_card_blocked_short else R.string.permissions_card_ok_short),
|
||||
valueColor = if (status.onlineBlocked) Color(0xFFFF6B6B) else ink.copy(alpha = 0.55f),
|
||||
icon = if (permissionsMissing) R.drawable.ic_permissions else R.drawable.ic_check_permission,
|
||||
iconTint = if (permissionsMissing) Color(0xFFFF6B6B) else ChessGreen,
|
||||
value = stringResource(if (permissionsMissing) R.string.permissions_card_blocked_short else R.string.permissions_card_ok_short),
|
||||
valueColor = if (permissionsMissing) Color(0xFFFF6B6B) else ink.copy(alpha = 0.55f),
|
||||
chevron = true,
|
||||
onClick = onOpenPermissions
|
||||
)
|
||||
|
||||
@@ -0,0 +1,269 @@
|
||||
package cc.skysparkle.matewave.ui.screens
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import cc.skysparkle.matewave.R
|
||||
import cc.skysparkle.matewave.data.FriendsStore
|
||||
import cc.skysparkle.matewave.engine.ChessEngine
|
||||
import cc.skysparkle.matewave.engine.Material
|
||||
import cc.skysparkle.matewave.engine.PieceColor
|
||||
import cc.skysparkle.matewave.engine.opposite
|
||||
import cc.skysparkle.matewave.network.NetworkRequirements
|
||||
import cc.skysparkle.matewave.openings.OpeningBook
|
||||
import cc.skysparkle.matewave.spectate.SpectateTarget
|
||||
import cc.skysparkle.matewave.spectate.SpectatorClient
|
||||
import cc.skysparkle.matewave.spectate.SpectatorOutcome
|
||||
import cc.skysparkle.matewave.spectate.SpectatorResult
|
||||
import cc.skysparkle.matewave.spectate.SpectatorView
|
||||
import cc.skysparkle.matewave.ui.components.AppDialog
|
||||
import cc.skysparkle.matewave.ui.components.ButtonIcon
|
||||
import cc.skysparkle.matewave.ui.components.CapturedPiecesRow
|
||||
import cc.skysparkle.matewave.ui.components.ChessBoardView
|
||||
import cc.skysparkle.matewave.ui.components.DialogAction
|
||||
import cc.skysparkle.matewave.ui.components.DialogText
|
||||
import cc.skysparkle.matewave.ui.components.GlassOutlinedButton
|
||||
import cc.skysparkle.matewave.ui.components.GlassScaffold
|
||||
import cc.skysparkle.matewave.ui.components.MovesBar
|
||||
import cc.skysparkle.matewave.ui.components.SpectatorBadge
|
||||
import cc.skysparkle.matewave.ui.theme.ChessGreen
|
||||
import cc.skysparkle.matewave.ui.theme.ink
|
||||
import cc.skysparkle.matewave.viewmodel.SpectatePhase
|
||||
import cc.skysparkle.matewave.viewmodel.SpectateUiState
|
||||
import cc.skysparkle.matewave.viewmodel.SpectatorViewModel
|
||||
import kotlinx.coroutines.delay
|
||||
|
||||
/** Read-only view of a friend's LAN game. */
|
||||
@Composable
|
||||
fun SpectatorScreen(target: SpectateTarget, onBackToFriends: () -> Unit) {
|
||||
val viewModel: SpectatorViewModel = viewModel()
|
||||
LaunchedEffect(target) { viewModel.start(target) }
|
||||
val state by viewModel.uiState.collectAsState()
|
||||
val context = LocalContext.current
|
||||
|
||||
var left by remember { mutableStateOf(false) }
|
||||
val backToFriends: () -> Unit = {
|
||||
if (!left) {
|
||||
left = true
|
||||
onBackToFriends()
|
||||
}
|
||||
}
|
||||
androidx.activity.compose.BackHandler(onBack = backToFriends)
|
||||
|
||||
// Wi-Fi switched off here: say so at once instead of waiting for the connection to time out.
|
||||
LaunchedEffect(Unit) {
|
||||
while (true) {
|
||||
delay(WIFI_CHECK_MS)
|
||||
if (!NetworkRequirements.check(context).wifiConnected) viewModel.onNetworkLost()
|
||||
}
|
||||
}
|
||||
|
||||
val view = state.view
|
||||
var resultHidden by remember(view?.gameId, state.phase) { mutableStateOf(false) }
|
||||
|
||||
GlassScaffold(
|
||||
title = stringResource(R.string.spectate_title),
|
||||
onBack = backToFriends,
|
||||
actions = { if (view != null) SpectatorBadge(state.spectators, state.max) }
|
||||
) {
|
||||
if (state.phase == SpectatePhase.CONNECTING) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
CircularProgressIndicator(color = ink, strokeWidth = 2.dp, modifier = Modifier.size(16.dp))
|
||||
Text(stringResource(R.string.spectate_joining), color = ink, style = MaterialTheme.typography.bodyMedium)
|
||||
}
|
||||
}
|
||||
if (view == null) return@GlassScaffold
|
||||
|
||||
val bottom = if (state.flipped) PieceColor.BLACK else PieceColor.WHITE
|
||||
val material = remember(view.board) { Material.balance(view.board) }
|
||||
val checkSquare = if (ChessEngine.isInCheck(view.board, view.board.sideToMove)) {
|
||||
view.board.kingSquare(view.board.sideToMove)
|
||||
} else null
|
||||
|
||||
SpectatorPlayerRow(view, bottom.opposite(), state, material)
|
||||
ChessBoardView(
|
||||
board = view.board,
|
||||
selectedSquare = null,
|
||||
legalTargets = emptyList(),
|
||||
kingInCheckSquare = checkSquare,
|
||||
flipped = state.flipped,
|
||||
onSquareClick = {},
|
||||
lastMove = view.lastMove,
|
||||
interactionEnabled = false,
|
||||
highlightLastMove = true
|
||||
)
|
||||
SpectatorPlayerRow(view, bottom, state, material)
|
||||
|
||||
val bookPlies = remember(view.moveSans) { OpeningBook.bookDepth(view.moveSans) }
|
||||
MovesBar(
|
||||
sans = view.moveSans,
|
||||
startBoard = view.startBoard,
|
||||
currentIndex = view.moveSans.size,
|
||||
opening = null,
|
||||
bookPlies = bookPlies
|
||||
)
|
||||
|
||||
GlassOutlinedButton(onClick = viewModel::flip, modifier = Modifier.fillMaxWidth()) {
|
||||
ButtonIcon(R.drawable.ic_board_view)
|
||||
Text(stringResource(R.string.spectate_flip), color = ink, maxLines = 1)
|
||||
}
|
||||
|
||||
if (state.phase == SpectatePhase.ENDED && resultHidden) {
|
||||
GlassOutlinedButton(onClick = { resultHidden = false }, modifier = Modifier.fillMaxWidth()) {
|
||||
Text(stringResource(R.string.game_over_title), color = ink, maxLines = 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
when (state.phase) {
|
||||
SpectatePhase.ENDED -> {
|
||||
val result = view?.result
|
||||
if (result != null && !resultHidden) {
|
||||
AppDialog(
|
||||
onDismissRequest = { resultHidden = true },
|
||||
title = stringResource(R.string.game_over_title),
|
||||
actions = { DialogAction(stringResource(R.string.spectate_back_to_friends), backToFriends) }
|
||||
) {
|
||||
DialogText(resultText(result))
|
||||
}
|
||||
}
|
||||
}
|
||||
SpectatePhase.LOST -> {
|
||||
LaunchedEffect(Unit) {
|
||||
delay(LOST_RETURN_MS)
|
||||
backToFriends()
|
||||
}
|
||||
AppDialog(
|
||||
onDismissRequest = backToFriends,
|
||||
title = stringResource(R.string.connection_lost),
|
||||
actions = { DialogAction(stringResource(R.string.spectate_back_to_friends), backToFriends) }
|
||||
) {
|
||||
DialogText(stringResource(R.string.spectate_lost_text))
|
||||
}
|
||||
}
|
||||
SpectatePhase.FAILED -> {
|
||||
val (title, text) = failureTexts(state.failure, state.max)
|
||||
AppDialog(
|
||||
onDismissRequest = backToFriends,
|
||||
title = title,
|
||||
actions = { DialogAction(stringResource(R.string.spectate_back_to_friends), backToFriends) }
|
||||
) {
|
||||
DialogText(text)
|
||||
}
|
||||
}
|
||||
else -> Unit
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun failureTexts(failure: SpectatorClient.Failure?, max: Int): Pair<String, String> = when (failure) {
|
||||
SpectatorClient.Failure.FULL ->
|
||||
stringResource(R.string.spectate_full_title) to stringResource(R.string.spectate_full_text, max)
|
||||
SpectatorClient.Failure.UPDATE_THIS_APP ->
|
||||
stringResource(R.string.spectate_update_title) to stringResource(R.string.spectate_update_this)
|
||||
SpectatorClient.Failure.UPDATE_HOST_APP ->
|
||||
stringResource(R.string.spectate_update_title) to stringResource(R.string.spectate_update_host)
|
||||
SpectatorClient.Failure.NO_GAME ->
|
||||
stringResource(R.string.spectate_failed_title) to stringResource(R.string.spectate_no_game)
|
||||
SpectatorClient.Failure.UNREACHABLE, null ->
|
||||
stringResource(R.string.spectate_failed_title) to stringResource(R.string.spectate_unreachable)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun resultText(result: SpectatorResult): String {
|
||||
val white = stringResource(R.string.color_white)
|
||||
val black = stringResource(R.string.color_black)
|
||||
val winner = result.winner
|
||||
fun name(side: PieceColor) = if (side == PieceColor.WHITE) white else black
|
||||
return when (result.outcome) {
|
||||
SpectatorOutcome.CHECKMATE -> winner?.let { stringResource(R.string.checkmate_winner, name(it)) }
|
||||
SpectatorOutcome.TIMEOUT -> winner?.let { stringResource(R.string.timeout_winner, name(it)) }
|
||||
SpectatorOutcome.RESIGNATION -> winner?.let { stringResource(R.string.resignation_winner, name(it)) }
|
||||
SpectatorOutcome.LEFT -> winner?.let { stringResource(R.string.spectate_left_win, name(it.opposite()), name(it)) }
|
||||
SpectatorOutcome.STALEMATE -> stringResource(R.string.stalemate)
|
||||
SpectatorOutcome.FIFTY_MOVES -> stringResource(R.string.draw_50_moves)
|
||||
SpectatorOutcome.REPETITION -> stringResource(R.string.draw_repetition)
|
||||
SpectatorOutcome.INSUFFICIENT_MATERIAL -> stringResource(R.string.draw_material)
|
||||
SpectatorOutcome.TIMEOUT_DRAW -> stringResource(R.string.timeout_draw)
|
||||
SpectatorOutcome.AGREEMENT -> stringResource(R.string.draw_agreement)
|
||||
SpectatorOutcome.INTERRUPTED -> stringResource(R.string.spectate_interrupted)
|
||||
SpectatorOutcome.UNKNOWN -> null
|
||||
} ?: stringResource(R.string.game_over_title)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SpectatorPlayerRow(
|
||||
view: SpectatorView,
|
||||
side: PieceColor,
|
||||
state: SpectateUiState,
|
||||
material: cc.skysparkle.matewave.engine.MaterialBalance
|
||||
) {
|
||||
val player = if (side == PieceColor.WHITE) view.white else view.black
|
||||
val active = view.result == null && view.board.sideToMove == side
|
||||
// Known friends get their saved avatar; nothing large travels to spectators.
|
||||
val avatar = remember(player.id) {
|
||||
if (player.id.isEmpty()) null else FriendsStore.list().firstOrNull { it.userId == player.id }?.avatarBase64
|
||||
}
|
||||
Row(modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.size(8.dp)
|
||||
.clip(CircleShape)
|
||||
.background(if (active) ChessGreen else ink.copy(alpha = 0.15f))
|
||||
)
|
||||
Spacer(Modifier.width(10.dp))
|
||||
AvatarCircle(base64 = avatar, size = 34.dp)
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
player.name.ifBlank { stringResource(R.string.player_default_name) },
|
||||
color = if (active) ink else ink.copy(alpha = 0.75f),
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
)
|
||||
if (player.elo > 0) {
|
||||
Text(
|
||||
stringResource(R.string.friends_elo_value, player.elo),
|
||||
color = ink.copy(alpha = 0.55f),
|
||||
style = MaterialTheme.typography.labelSmall
|
||||
)
|
||||
}
|
||||
CapturedPiecesRow(
|
||||
captured = if (side == PieceColor.WHITE) material.capturedByWhite else material.capturedByBlack,
|
||||
capturedColor = side.opposite(),
|
||||
advantage = if (side == PieceColor.WHITE) material.advantage else -material.advantage
|
||||
)
|
||||
}
|
||||
val millis = if (side == PieceColor.WHITE) state.whiteMs else state.blackMs
|
||||
if (millis != null) BigClock(millis, active)
|
||||
}
|
||||
}
|
||||
|
||||
private const val WIFI_CHECK_MS = 2_000L
|
||||
private const val LOST_RETURN_MS = 4_000L
|
||||
@@ -33,6 +33,15 @@ import cc.skysparkle.matewave.security.KnownPeers
|
||||
import cc.skysparkle.matewave.security.SessionAuth
|
||||
import cc.skysparkle.matewave.security.TrustResult
|
||||
import cc.skysparkle.matewave.settings.Haptics
|
||||
import cc.skysparkle.matewave.spectate.MAX_SPECTATORS
|
||||
import cc.skysparkle.matewave.spectate.SpectatorAdvert
|
||||
import cc.skysparkle.matewave.spectate.SpectatorBroadcaster
|
||||
import cc.skysparkle.matewave.spectate.SpectatorClock
|
||||
import cc.skysparkle.matewave.spectate.SpectatorHub
|
||||
import cc.skysparkle.matewave.spectate.SpectatorPlayer
|
||||
import cc.skysparkle.matewave.spectate.SpectatorResult
|
||||
import cc.skysparkle.matewave.spectate.SpectatorResults
|
||||
import cc.skysparkle.matewave.spectate.SpectatorSnapshot
|
||||
import cc.skysparkle.matewave.stats.Stats
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
@@ -95,7 +104,10 @@ data class GameUiState(
|
||||
val opponentLeftMidGame: Boolean = false,
|
||||
val rematchOfferFromOpponent: Boolean = false,
|
||||
|
||||
val activeTransport: TransportType? = null
|
||||
val activeTransport: TransportType? = null,
|
||||
|
||||
/** Spectators watching this LAN game, shown to both players. */
|
||||
val spectatorCount: Int = 0
|
||||
)
|
||||
|
||||
data class PendingPromotion(val from: Int, val to: Int)
|
||||
@@ -172,6 +184,16 @@ class GameViewModel : ViewModel() {
|
||||
private var currentPly: Int = 0
|
||||
private var lastOpponentRemaining: Long = Long.MAX_VALUE
|
||||
|
||||
// Spectating: the host serves spectators, both players announce the game's tag.
|
||||
private var spectators: SpectatorBroadcaster? = null
|
||||
private var spectatorWatcher: Job? = null
|
||||
private var spectatorCountJob: Job? = null
|
||||
private var spectatingDecided = false
|
||||
private var spectateTag: String = ""
|
||||
private var spectatorPlayers: Pair<SpectatorPlayer, SpectatorPlayer>? = null
|
||||
private var spectatorPlayersKey: String = ""
|
||||
private var lastSentSpectatorCount = 0
|
||||
|
||||
init {
|
||||
GameSaveStore.load()?.let { saved -> restoreSaved(saved) }
|
||||
}
|
||||
@@ -689,6 +711,7 @@ class GameViewModel : ViewModel() {
|
||||
pendingLeave = null
|
||||
handshakeTimeoutJob?.cancel()
|
||||
handshakeTimeoutJob = null
|
||||
stopSpectating()
|
||||
cancelAi()
|
||||
// A paused game against the AI stays saved and can be continued later.
|
||||
persistIfResumable()
|
||||
@@ -729,6 +752,8 @@ class GameViewModel : ViewModel() {
|
||||
heartbeat?.stop()
|
||||
heartbeat = cc.skysparkle.matewave.network.Heartbeat(viewModelScope, transport).also { it.start() }
|
||||
|
||||
spectatorWatcher = viewModelScope.launch { _uiState.collect { onStateForSpectators(it) } }
|
||||
|
||||
var profileSent = false
|
||||
var connectedOnce = false
|
||||
val connectStartedAt = System.currentTimeMillis()
|
||||
@@ -965,6 +990,10 @@ class GameViewModel : ViewModel() {
|
||||
)
|
||||
}
|
||||
is GameMessage.PingMsg -> Unit
|
||||
is GameMessage.SpectatorCountMsg -> {
|
||||
if (isNetworkHost) return
|
||||
_uiState.value = _uiState.value.copy(spectatorCount = msg.count.coerceIn(0, MAX_SPECTATORS))
|
||||
}
|
||||
is GameMessage.TimeoutMsg -> {
|
||||
if (!belongsToCurrentGame(msg.gameId)) return
|
||||
val state = _uiState.value
|
||||
@@ -1113,6 +1142,9 @@ class GameViewModel : ViewModel() {
|
||||
}
|
||||
|
||||
private fun endNetworkSession() {
|
||||
val state = _uiState.value
|
||||
// The players lost each other: spectators see the game end as interrupted.
|
||||
stopSpectating(if (state.status == GameStatus.ONGOING) SpectatorResults.interrupted else null)
|
||||
opponentFlagJob?.cancel()
|
||||
opponentFlagJob = null
|
||||
clock?.stop()
|
||||
@@ -1137,7 +1169,9 @@ class GameViewModel : ViewModel() {
|
||||
return
|
||||
}
|
||||
|
||||
if (state.status == GameStatus.ONGOING && state.handshake == HandshakeState.PLAYING) {
|
||||
val leftMidGame = state.status == GameStatus.ONGOING && state.handshake == HandshakeState.PLAYING
|
||||
stopSpectating(if (leftMidGame) SpectatorResults.leftBy(state.myColor) else null)
|
||||
if (leftMidGame) {
|
||||
applyNetworkResultElo(0.0)
|
||||
}
|
||||
opponentFlagJob?.cancel()
|
||||
@@ -1218,7 +1252,8 @@ class GameViewModel : ViewModel() {
|
||||
handshake = state.handshake,
|
||||
activeTransport = state.activeTransport,
|
||||
opponentUnverified = state.opponentUnverified,
|
||||
chatMessages = state.chatMessages
|
||||
chatMessages = state.chatMessages,
|
||||
spectatorCount = state.spectatorCount
|
||||
)
|
||||
setupClock(timeControl)
|
||||
}
|
||||
@@ -1333,6 +1368,119 @@ class GameViewModel : ViewModel() {
|
||||
|
||||
// endregion
|
||||
|
||||
// region Spectators
|
||||
|
||||
/**
|
||||
* Once a LAN game is under way, the host opens its spectator socket and both players announce
|
||||
* the game's tag; players who chose not to be visible on the network are not watchable.
|
||||
*/
|
||||
private fun onStateForSpectators(state: GameUiState) {
|
||||
if (state.mode != GameMode.VS_PLAYER_NETWORK) return
|
||||
spectators?.update(spectatorSnapshot(state))
|
||||
if (spectatingDecided) return
|
||||
val live = state.handshake == HandshakeState.PLAYING &&
|
||||
state.connectionState == ConnectionState.CONNECTED &&
|
||||
state.activeTransport == TransportType.LAN
|
||||
if (!live) return
|
||||
val ctx = appContext ?: return
|
||||
spectatingDecided = true
|
||||
if (!cc.skysparkle.matewave.presence.PresenceSettings(ctx).announceEnabled) return
|
||||
spectateTag = SpectatorAdvert.tagOf(networkGameId)
|
||||
if (spectateTag.isEmpty()) return
|
||||
if (isNetworkHost) startSpectatorHub(ctx) else advertiseGame(ctx, SpectatorAdvert.State(spectateTag, 0))
|
||||
}
|
||||
|
||||
private fun startSpectatorHub(ctx: android.content.Context) {
|
||||
val generation = sessionGeneration
|
||||
val hub = SpectatorHub(log = { NetworkLog.log("SPECTATE", it) })
|
||||
viewModelScope.launch {
|
||||
var serving = false
|
||||
try {
|
||||
val port = withContext(Dispatchers.IO) { runCatching { hub.start() }.getOrNull() }
|
||||
if (port == null) NetworkLog.log("SPECTATE", "Could not open the spectator port")
|
||||
// The game may have ended while the port was opening.
|
||||
if (port == null || generation != sessionGeneration || !spectatingDecided || spectateTag.isEmpty()) return@launch
|
||||
val broadcaster = SpectatorBroadcaster(hub)
|
||||
broadcaster.update(spectatorSnapshot(_uiState.value))
|
||||
spectators = broadcaster
|
||||
serving = true
|
||||
spectatorCountJob = viewModelScope.launch { hub.count.collect { onSpectatorCount(it) } }
|
||||
advertiseGame(ctx, SpectatorAdvert.State(spectateTag, port))
|
||||
NetworkLog.log("SPECTATE", "Spectators can join on port $port")
|
||||
} finally {
|
||||
if (!serving) hub.close()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun onSpectatorCount(count: Int) {
|
||||
if (_uiState.value.spectatorCount != count) {
|
||||
_uiState.value = _uiState.value.copy(spectatorCount = count)
|
||||
}
|
||||
if (count != lastSentSpectatorCount && canSendGameMessages() &&
|
||||
sendGameMessage(GameMessage.SpectatorCountMsg(count, networkGameId))
|
||||
) {
|
||||
lastSentSpectatorCount = count
|
||||
}
|
||||
}
|
||||
|
||||
private fun advertiseGame(ctx: android.content.Context, state: SpectatorAdvert.State) {
|
||||
if (SpectatorAdvert.update(state)) cc.skysparkle.matewave.network.Transports.lan(ctx).republishProfile()
|
||||
}
|
||||
|
||||
/** Ends spectating for this session; [final] tells spectators how a game cut short ended. */
|
||||
private fun stopSpectating(final: SpectatorResult? = null) {
|
||||
spectatorWatcher?.cancel()
|
||||
spectatorWatcher = null
|
||||
spectatorCountJob?.cancel()
|
||||
spectatorCountJob = null
|
||||
spectators?.let { broadcaster ->
|
||||
val last = final?.let { spectatorSnapshot(_uiState.value).copy(result = it) }
|
||||
broadcaster.close(last)
|
||||
}
|
||||
spectators = null
|
||||
spectatingDecided = false
|
||||
spectateTag = ""
|
||||
spectatorPlayers = null
|
||||
spectatorPlayersKey = ""
|
||||
lastSentSpectatorCount = 0
|
||||
appContext?.let { ctx ->
|
||||
if (SpectatorAdvert.clear()) cc.skysparkle.matewave.network.Transports.lan(ctx).republishProfile()
|
||||
}
|
||||
if (_uiState.value.spectatorCount != 0) {
|
||||
_uiState.value = _uiState.value.copy(spectatorCount = 0)
|
||||
}
|
||||
}
|
||||
|
||||
private fun spectatorSnapshot(state: GameUiState): SpectatorSnapshot {
|
||||
val opponent = state.opponentProfile
|
||||
val key = networkGameId + "|" + (opponent?.userId ?: "")
|
||||
val players = spectatorPlayers?.takeIf { spectatorPlayersKey == key } ?: run {
|
||||
val me = ProfileStore.get()
|
||||
val mine = SpectatorPlayer(me.userId, me.name, me.elo)
|
||||
val theirs = SpectatorPlayer(opponent?.userId ?: "", opponent?.name ?: "", opponent?.elo ?: 0)
|
||||
(if (state.myColor == PieceColor.WHITE) mine to theirs else theirs to mine).also {
|
||||
spectatorPlayers = it
|
||||
spectatorPlayersKey = key
|
||||
}
|
||||
}
|
||||
val timeControl = lastNetworkTimeControl
|
||||
return SpectatorSnapshot(
|
||||
gameId = networkGameId,
|
||||
white = players.first,
|
||||
black = players.second,
|
||||
movesUci = moveLog.toList(),
|
||||
initialSeconds = timeControl?.initialSeconds ?: 0,
|
||||
incrementSeconds = timeControl?.incrementSeconds ?: 0,
|
||||
clock = clock?.state?.value?.let { SpectatorClock(it.whiteMillis, it.blackMillis, it.running) },
|
||||
result = SpectatorResults.of(
|
||||
state.status, state.board.sideToMove, state.timedOutSide, state.resignedSide, state.opponentLeftMidGame
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
// endregion
|
||||
|
||||
// region Clock
|
||||
|
||||
private fun disposeClock() {
|
||||
@@ -1418,6 +1566,7 @@ class GameViewModel : ViewModel() {
|
||||
pendingLeave?.first?.cancel()
|
||||
pendingLeave?.second?.disconnect()
|
||||
pendingLeave = null
|
||||
stopSpectating()
|
||||
persistIfResumable()
|
||||
clock?.stop()
|
||||
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
package cc.skysparkle.matewave.viewmodel
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import cc.skysparkle.matewave.network.NetworkLog
|
||||
import cc.skysparkle.matewave.spectate.MAX_SPECTATORS
|
||||
import cc.skysparkle.matewave.spectate.SpectateTarget
|
||||
import cc.skysparkle.matewave.spectate.SpectatorClient
|
||||
import cc.skysparkle.matewave.spectate.SpectatorGame
|
||||
import cc.skysparkle.matewave.spectate.SpectatorMessage
|
||||
import cc.skysparkle.matewave.spectate.SpectatorSnapshot
|
||||
import cc.skysparkle.matewave.spectate.SpectatorView
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.channels.Channel
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.isActive
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
enum class SpectatePhase { CONNECTING, WATCHING, ENDED, LOST, FAILED }
|
||||
|
||||
data class SpectateUiState(
|
||||
val phase: SpectatePhase = SpectatePhase.CONNECTING,
|
||||
val failure: SpectatorClient.Failure? = null,
|
||||
val view: SpectatorView? = null,
|
||||
val whiteMs: Long? = null,
|
||||
val blackMs: Long? = null,
|
||||
val spectators: Int = 0,
|
||||
val max: Int = MAX_SPECTATORS,
|
||||
/** Board turned for this spectator only. */
|
||||
val flipped: Boolean = false
|
||||
)
|
||||
|
||||
/** Watches one LAN game read-only. Nothing here can reach the players. */
|
||||
class SpectatorViewModel : ViewModel() {
|
||||
private val _uiState = MutableStateFlow(SpectateUiState())
|
||||
val uiState: StateFlow<SpectateUiState> = _uiState
|
||||
|
||||
private val game = SpectatorGame()
|
||||
private val events = Channel<SpectatorClient.Event>(Channel.UNLIMITED)
|
||||
private var client: SpectatorClient? = null
|
||||
private var target: SpectateTarget? = null
|
||||
private var clockAtNanos = 0L
|
||||
private var ticker: Job? = null
|
||||
|
||||
init {
|
||||
viewModelScope.launch { for (event in events) handle(event) }
|
||||
}
|
||||
|
||||
fun start(target: SpectateTarget) {
|
||||
if (this.target == target) return
|
||||
this.target = target
|
||||
client?.stop()
|
||||
_uiState.value = SpectateUiState(flipped = _uiState.value.flipped)
|
||||
client = SpectatorClient(target.host, target.port, { events.trySend(it) }).also { it.start() }
|
||||
}
|
||||
|
||||
fun flip() {
|
||||
_uiState.update { it.copy(flipped = !it.flipped) }
|
||||
}
|
||||
|
||||
/** Wi-Fi went away on this device: no need to wait for the connection to time out. */
|
||||
fun onNetworkLost() {
|
||||
when (_uiState.value.phase) {
|
||||
SpectatePhase.CONNECTING -> fail(SpectatorClient.Failure.UNREACHABLE)
|
||||
SpectatePhase.WATCHING -> lose()
|
||||
else -> Unit
|
||||
}
|
||||
}
|
||||
|
||||
private fun handle(event: SpectatorClient.Event) {
|
||||
when (event) {
|
||||
is SpectatorClient.Event.Joined -> {
|
||||
_uiState.update { it.copy(spectators = event.welcome.count, max = event.welcome.max) }
|
||||
load(event.welcome.game)
|
||||
}
|
||||
is SpectatorClient.Event.Received -> onMessage(event.message)
|
||||
is SpectatorClient.Event.JoinFailed -> fail(event.failure)
|
||||
is SpectatorClient.Event.Disconnected -> {
|
||||
// After the result the host may leave; the result stays on screen.
|
||||
if (_uiState.value.phase != SpectatePhase.ENDED) lose()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun onMessage(message: SpectatorMessage) {
|
||||
val phase = _uiState.value.phase
|
||||
if (phase == SpectatePhase.LOST || phase == SpectatePhase.FAILED) return
|
||||
when (message) {
|
||||
is SpectatorMessage.MovePlayed -> applied(game.onMove(message))
|
||||
is SpectatorMessage.GameOver -> applied(game.onGameOver(message))
|
||||
is SpectatorMessage.NewGame -> load(message.game)
|
||||
is SpectatorMessage.Count -> _uiState.update { it.copy(spectators = message.count, max = message.max) }
|
||||
is SpectatorMessage.Ping -> {
|
||||
game.onClock(message.clock)
|
||||
publish(clockUpdated = message.clock != null)
|
||||
}
|
||||
else -> Unit
|
||||
}
|
||||
}
|
||||
|
||||
private fun applied(result: SpectatorGame.Applied) {
|
||||
when (result) {
|
||||
SpectatorGame.Applied.APPLIED -> publish(clockUpdated = true)
|
||||
SpectatorGame.Applied.NEEDS_RESYNC -> client?.requestResync()
|
||||
SpectatorGame.Applied.IGNORED -> Unit
|
||||
}
|
||||
}
|
||||
|
||||
private fun load(snapshot: SpectatorSnapshot) {
|
||||
if (game.load(snapshot)) {
|
||||
publish(clockUpdated = true)
|
||||
} else {
|
||||
NetworkLog.log("SPECTATE", "Received game could not be replayed")
|
||||
lose()
|
||||
}
|
||||
}
|
||||
|
||||
private fun publish(clockUpdated: Boolean) {
|
||||
val view = game.view ?: return
|
||||
if (clockUpdated) clockAtNanos = System.nanoTime()
|
||||
_uiState.update {
|
||||
it.copy(
|
||||
phase = if (view.result != null) SpectatePhase.ENDED else SpectatePhase.WATCHING,
|
||||
failure = null,
|
||||
view = view
|
||||
)
|
||||
}
|
||||
showClocks()
|
||||
if (ticker?.isActive != true) {
|
||||
ticker = viewModelScope.launch {
|
||||
while (isActive) {
|
||||
delay(TICK_MS)
|
||||
if (_uiState.value.phase == SpectatePhase.WATCHING) showClocks()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Clocks count down locally between the host's updates. */
|
||||
private fun showClocks() {
|
||||
val view = game.view ?: return
|
||||
val clock = view.clock
|
||||
if (clock == null) {
|
||||
_uiState.update { it.copy(whiteMs = null, blackMs = null) }
|
||||
return
|
||||
}
|
||||
val shown = if (view.result == null) clock.advancedBy((System.nanoTime() - clockAtNanos) / 1_000_000L) else clock
|
||||
_uiState.update { it.copy(whiteMs = shown.whiteMs, blackMs = shown.blackMs) }
|
||||
}
|
||||
|
||||
private fun lose() {
|
||||
client?.stop()
|
||||
_uiState.update { it.copy(phase = SpectatePhase.LOST) }
|
||||
}
|
||||
|
||||
private fun fail(failure: SpectatorClient.Failure) {
|
||||
client?.stop()
|
||||
_uiState.update { it.copy(phase = SpectatePhase.FAILED, failure = failure) }
|
||||
}
|
||||
|
||||
override fun onCleared() {
|
||||
client?.stop()
|
||||
client = null
|
||||
events.close()
|
||||
super.onCleared()
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val TICK_MS = 250L
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="24dp"
|
||||
android:height="24dp"
|
||||
android:viewportWidth="24"
|
||||
android:viewportHeight="24">
|
||||
<path
|
||||
android:pathData="M2,12C4.5,7.5 8,5.5 12,5.5C16,5.5 19.5,7.5 22,12C19.5,16.5 16,18.5 12,18.5C8,18.5 4.5,16.5 2,12Z"
|
||||
android:strokeWidth="2"
|
||||
android:strokeColor="#FFFFFFFF"
|
||||
android:strokeLineJoin="round"
|
||||
android:fillColor="#00000000" />
|
||||
<path
|
||||
android:pathData="M8.8,12a3.2,3.2 0,1 0,6.4 0a3.2,3.2 0,1 0,-6.4 0Z"
|
||||
android:fillColor="#FFFFFFFF" />
|
||||
</vector>
|
||||
@@ -25,9 +25,9 @@
|
||||
<string name="settings_version">Version %1$s</string>
|
||||
<string name="settings_repo_title">Quellcode</string>
|
||||
<string name="settings_radio">Jazzradio</string>
|
||||
<string name="settings_radio_subtitle">Internetradio im Hintergrund statt Stille</string>
|
||||
<string name="settings_radio_subtitle">Radio Swiss Jazz. Ohne Verbindung läuft eingebaute Musik</string>
|
||||
<string name="settings_radio_connecting">Verbinde...</string>
|
||||
<string name="settings_radio_error">Verbindung fehlgeschlagen</string>
|
||||
<string name="settings_radio_error">Keine Verbindung, eingebaute Musik</string>
|
||||
<string name="settings_sfx">Soundeffekte</string>
|
||||
<string name="settings_sfx_subtitle">Figur wählen, ziehen, schlagen</string>
|
||||
<string name="back">Zurück</string>
|
||||
@@ -354,10 +354,30 @@
|
||||
<string name="nearby_bt_off_hint">Schalte es ein, um Spieler per Bluetooth zu finden</string>
|
||||
<string name="nearby_wifi_hint">Spieler im selben WLAN werden erst gefunden, wenn du verbunden bist</string>
|
||||
<string name="permission_open_settings">Einstellungen öffnen</string>
|
||||
<string name="settings_menu_music">Menümusik</string>
|
||||
<string name="settings_menu_music_subtitle">Ruhige Musik auf dem Startbildschirm, solange das Radio aus ist</string>
|
||||
<string name="piece_queen">Dame</string>
|
||||
<string name="piece_rook">Turm</string>
|
||||
<string name="piece_bishop">Läufer</string>
|
||||
<string name="piece_knight">Springer</string>
|
||||
|
||||
<!-- Spectators -->
|
||||
<string name="friends_in_game">Im Spiel</string>
|
||||
<string name="friends_watch">Zuschauen</string>
|
||||
<string name="friends_watch_count">Zuschauen · %1$d/%2$d</string>
|
||||
<string name="friends_watch_full">Voll</string>
|
||||
<string name="spectators_description">Zuschauer: %1$d</string>
|
||||
<string name="spectate_title">Zuschauen</string>
|
||||
<string name="spectate_joining">Verbinde mit der Partie…</string>
|
||||
<string name="spectate_flip">Brett drehen</string>
|
||||
<string name="spectate_back_to_friends">Zurück zu Freunden</string>
|
||||
<string name="spectate_lost_text">Das Gerät, auf dem die Partie läuft, ist nicht mehr erreichbar.</string>
|
||||
<string name="spectate_full_title">Partie ist voll</string>
|
||||
<string name="spectate_full_text">Diese Partie hat bereits die maximale Zahl von %1$d Zuschauern. Versuch es später noch einmal.</string>
|
||||
<string name="spectate_update_title">Update erforderlich</string>
|
||||
<string name="spectate_update_this">Aktualisiere Matewave, um diese Partie anzusehen.</string>
|
||||
<string name="spectate_update_host">Der Spieler, der diese Partie ausrichtet, muss Matewave aktualisieren, bevor man zuschauen kann.</string>
|
||||
<string name="spectate_failed_title">Zuschauen nicht möglich</string>
|
||||
<string name="spectate_no_game">Diese Partie ist nicht mehr verfügbar.</string>
|
||||
<string name="spectate_unreachable">Das Gerät, auf dem die Partie läuft, ist nicht erreichbar. Achte darauf, dass du im selben WLAN bist.</string>
|
||||
<string name="spectate_left_win">%1$s hat die Partie verlassen. %2$s gewinnt.</string>
|
||||
<string name="spectate_interrupted">Partie unterbrochen: Die Spieler haben die Verbindung verloren.</string>
|
||||
</resources>
|
||||
|
||||
@@ -25,9 +25,9 @@
|
||||
<string name="settings_version">バージョン %1$s</string>
|
||||
<string name="settings_repo_title">ソースコード</string>
|
||||
<string name="settings_radio">ジャズラジオ</string>
|
||||
<string name="settings_radio_subtitle">無音のかわりにインターネットラジオをバックグラウンドで再生</string>
|
||||
<string name="settings_radio_subtitle">Radio Swiss Jazz。接続がないときは内蔵の音楽を再生</string>
|
||||
<string name="settings_radio_connecting">接続中...</string>
|
||||
<string name="settings_radio_error">接続できませんでした</string>
|
||||
<string name="settings_radio_error">接続なし・内蔵の音楽</string>
|
||||
<string name="settings_sfx">効果音</string>
|
||||
<string name="settings_sfx_subtitle">駒の選択、移動、取る音</string>
|
||||
<string name="back">戻る</string>
|
||||
@@ -353,10 +353,30 @@
|
||||
<string name="nearby_bt_off_hint">オンにすると、Bluetoothでプレイヤーを探せます</string>
|
||||
<string name="nearby_wifi_hint">接続するまで、同じWi-Fiのプレイヤーは見つかりません</string>
|
||||
<string name="permission_open_settings">設定を開く</string>
|
||||
<string name="settings_menu_music">メニューの音楽</string>
|
||||
<string name="settings_menu_music_subtitle">ラジオがオフのとき、ホーム画面で穏やかな音楽を流します</string>
|
||||
<string name="piece_queen">クイーン</string>
|
||||
<string name="piece_rook">ルーク</string>
|
||||
<string name="piece_bishop">ビショップ</string>
|
||||
<string name="piece_knight">ナイト</string>
|
||||
|
||||
<!-- Spectators -->
|
||||
<string name="friends_in_game">対局中</string>
|
||||
<string name="friends_watch">観戦</string>
|
||||
<string name="friends_watch_count">観戦 · %1$d/%2$d</string>
|
||||
<string name="friends_watch_full">満員</string>
|
||||
<string name="spectators_description">観戦者: %1$d人</string>
|
||||
<string name="spectate_title">観戦</string>
|
||||
<string name="spectate_joining">対局に接続中…</string>
|
||||
<string name="spectate_flip">盤を反転</string>
|
||||
<string name="spectate_back_to_friends">フレンドに戻る</string>
|
||||
<string name="spectate_lost_text">対局をホストしている端末に接続できなくなりました。</string>
|
||||
<string name="spectate_full_title">満員です</string>
|
||||
<string name="spectate_full_text">この対局の観戦者はすでに上限の%1$d人です。しばらくしてからもう一度お試しください。</string>
|
||||
<string name="spectate_update_title">アップデートが必要です</string>
|
||||
<string name="spectate_update_this">この対局を観戦するには Matewave をアップデートしてください。</string>
|
||||
<string name="spectate_update_host">この対局を観戦するには、対局をホストしているプレイヤーが Matewave をアップデートする必要があります。</string>
|
||||
<string name="spectate_failed_title">観戦できません</string>
|
||||
<string name="spectate_no_game">この対局はもう観戦できません。</string>
|
||||
<string name="spectate_unreachable">対局をホストしている端末に接続できません。同じWi-Fiネットワークに接続しているか確認してください。</string>
|
||||
<string name="spectate_left_win">%1$sが対局から退出しました。%2$sの勝ち</string>
|
||||
<string name="spectate_interrupted">対局が中断されました。プレイヤー間の接続が切れました。</string>
|
||||
</resources>
|
||||
|
||||
@@ -25,9 +25,9 @@
|
||||
<string name="settings_version">Versija %1$s</string>
|
||||
<string name="settings_repo_title">Šaltinio kodas</string>
|
||||
<string name="settings_radio">Džiazo radijas</string>
|
||||
<string name="settings_radio_subtitle">Interneto radijas fone vietoj tylos</string>
|
||||
<string name="settings_radio_subtitle">Radio Swiss Jazz. Be ryšio groja įdiegta muzika</string>
|
||||
<string name="settings_radio_connecting">Jungiamasi...</string>
|
||||
<string name="settings_radio_error">Nepavyko prisijungti</string>
|
||||
<string name="settings_radio_error">Nėra ryšio, įdiegta muzika</string>
|
||||
<string name="settings_sfx">Garso efektai</string>
|
||||
<string name="settings_sfx_subtitle">Figūros pasirinkimas, ėjimas, paėmimas</string>
|
||||
<string name="back">Atgal</string>
|
||||
@@ -356,10 +356,30 @@
|
||||
<string name="nearby_bt_off_hint">Įjunkite, kad rastumėte žaidėjus per „Bluetooth“</string>
|
||||
<string name="nearby_wifi_hint">Žaidėjų tame pačiame „Wi-Fi“ tinkle nerasite, kol neprisijungsite</string>
|
||||
<string name="permission_open_settings">Atidaryti nustatymus</string>
|
||||
<string name="settings_menu_music">Meniu muzika</string>
|
||||
<string name="settings_menu_music_subtitle">Rami muzika pagrindiniame ekrane, kol radijas išjungtas</string>
|
||||
<string name="piece_queen">Valdovė</string>
|
||||
<string name="piece_rook">Bokštas</string>
|
||||
<string name="piece_bishop">Rikis</string>
|
||||
<string name="piece_knight">Žirgas</string>
|
||||
|
||||
<!-- Spectators -->
|
||||
<string name="friends_in_game">Žaidžia</string>
|
||||
<string name="friends_watch">Stebėti</string>
|
||||
<string name="friends_watch_count">Stebėti · %1$d/%2$d</string>
|
||||
<string name="friends_watch_full">Pilna</string>
|
||||
<string name="spectators_description">Žiūrovų: %1$d</string>
|
||||
<string name="spectate_title">Partijos stebėjimas</string>
|
||||
<string name="spectate_joining">Jungiamasi prie partijos…</string>
|
||||
<string name="spectate_flip">Apversti lentą</string>
|
||||
<string name="spectate_back_to_friends">Atgal į draugus</string>
|
||||
<string name="spectate_lost_text">Įrenginio, kuriame vyksta partija, nebepavyksta pasiekti.</string>
|
||||
<string name="spectate_full_title">Vietų nebėra</string>
|
||||
<string name="spectate_full_text">Šią partiją jau stebi didžiausias leidžiamas žiūrovų skaičius (%1$d). Pabandykite vėliau.</string>
|
||||
<string name="spectate_update_title">Reikia atnaujinti</string>
|
||||
<string name="spectate_update_this">Atnaujinkite Matewave, kad galėtumėte stebėti šią partiją.</string>
|
||||
<string name="spectate_update_host">Partiją rengiantis žaidėjas turi atnaujinti Matewave, kad ją būtų galima stebėti.</string>
|
||||
<string name="spectate_failed_title">Šios partijos stebėti negalima</string>
|
||||
<string name="spectate_no_game">Ši partija nebepasiekiama.</string>
|
||||
<string name="spectate_unreachable">Nepavyksta pasiekti įrenginio, kuriame vyksta partija. Įsitikinkite, kad esate prisijungę prie to paties „Wi-Fi“ tinklo.</string>
|
||||
<string name="spectate_left_win">%1$s paliko partiją. Laimėjo %2$s.</string>
|
||||
<string name="spectate_interrupted">Partija nutraukta: žaidėjų ryšys nutrūko.</string>
|
||||
</resources>
|
||||
|
||||
@@ -30,9 +30,9 @@
|
||||
<string name="settings_version">Версия %1$s</string>
|
||||
<string name="settings_repo_title">Исходный код</string>
|
||||
<string name="settings_radio">Джаз-радио</string>
|
||||
<string name="settings_radio_subtitle">Фоновый интернет-эфир вместо тишины</string>
|
||||
<string name="settings_radio_subtitle">Radio Swiss Jazz. Без связи играет встроенная музыка</string>
|
||||
<string name="settings_radio_connecting">Подключение...</string>
|
||||
<string name="settings_radio_error">Не удалось подключиться</string>
|
||||
<string name="settings_radio_error">Нет связи, встроенная музыка</string>
|
||||
<string name="settings_sfx">Звуковые эффекты</string>
|
||||
<string name="settings_sfx_subtitle">Выбор фигуры, ход, взятие</string>
|
||||
<string name="back">Назад</string>
|
||||
@@ -362,10 +362,30 @@
|
||||
<string name="nearby_bt_off_hint">Включите, чтобы находить игроков по Bluetooth</string>
|
||||
<string name="nearby_wifi_hint">Игроков в той же сети Wi-Fi не найти, пока вы не подключитесь</string>
|
||||
<string name="permission_open_settings">Открыть настройки</string>
|
||||
<string name="settings_menu_music">Музыка в меню</string>
|
||||
<string name="settings_menu_music_subtitle">Спокойная музыка на главном экране, пока радио выключено</string>
|
||||
<string name="piece_queen">Ферзь</string>
|
||||
<string name="piece_rook">Ладья</string>
|
||||
<string name="piece_bishop">Слон</string>
|
||||
<string name="piece_knight">Конь</string>
|
||||
|
||||
<!-- Spectators -->
|
||||
<string name="friends_in_game">В игре</string>
|
||||
<string name="friends_watch">Смотреть</string>
|
||||
<string name="friends_watch_count">Смотреть · %1$d/%2$d</string>
|
||||
<string name="friends_watch_full">Мест нет</string>
|
||||
<string name="spectators_description">Зрителей: %1$d</string>
|
||||
<string name="spectate_title">Просмотр партии</string>
|
||||
<string name="spectate_joining">Подключение к партии…</string>
|
||||
<string name="spectate_flip">Перевернуть доску</string>
|
||||
<string name="spectate_back_to_friends">Назад к друзьям</string>
|
||||
<string name="spectate_lost_text">Устройство, на котором идёт партия, больше недоступно.</string>
|
||||
<string name="spectate_full_title">Мест нет</string>
|
||||
<string name="spectate_full_text">У этой партии уже максимум зрителей (%1$d). Попробуйте позже.</string>
|
||||
<string name="spectate_update_title">Требуется обновление</string>
|
||||
<string name="spectate_update_this">Обновите Matewave, чтобы смотреть эту партию.</string>
|
||||
<string name="spectate_update_host">Игроку, который проводит эту партию, нужно обновить Matewave, чтобы её можно было смотреть.</string>
|
||||
<string name="spectate_failed_title">Не удаётся посмотреть партию</string>
|
||||
<string name="spectate_no_game">Эта партия больше недоступна.</string>
|
||||
<string name="spectate_unreachable">Устройство, на котором идёт партия, недоступно. Убедитесь, что вы подключены к той же сети Wi-Fi.</string>
|
||||
<string name="spectate_left_win">%1$s покинули партию. Победили %2$s.</string>
|
||||
<string name="spectate_interrupted">Партия прервана: игроки потеряли связь.</string>
|
||||
</resources>
|
||||
|
||||
@@ -25,9 +25,9 @@
|
||||
<string name="settings_version">版本 %1$s</string>
|
||||
<string name="settings_repo_title">源代码</string>
|
||||
<string name="settings_radio">爵士电台</string>
|
||||
<string name="settings_radio_subtitle">在后台播放网络电台,告别寂静</string>
|
||||
<string name="settings_radio_subtitle">Radio Swiss Jazz。无网络时播放内置音乐</string>
|
||||
<string name="settings_radio_connecting">正在连接...</string>
|
||||
<string name="settings_radio_error">无法连接</string>
|
||||
<string name="settings_radio_error">无连接,播放内置音乐</string>
|
||||
<string name="settings_sfx">音效</string>
|
||||
<string name="settings_sfx_subtitle">选子、走子、吃子</string>
|
||||
<string name="back">返回</string>
|
||||
@@ -353,10 +353,30 @@
|
||||
<string name="nearby_bt_off_hint">开启后即可通过蓝牙查找玩家</string>
|
||||
<string name="nearby_wifi_hint">连接 Wi-Fi 后才能找到同一网络中的玩家</string>
|
||||
<string name="permission_open_settings">打开设置</string>
|
||||
<string name="settings_menu_music">菜单音乐</string>
|
||||
<string name="settings_menu_music_subtitle">电台关闭时,在主屏幕播放舒缓的音乐</string>
|
||||
<string name="piece_queen">后</string>
|
||||
<string name="piece_rook">车</string>
|
||||
<string name="piece_bishop">象</string>
|
||||
<string name="piece_knight">马</string>
|
||||
|
||||
<!-- Spectators -->
|
||||
<string name="friends_in_game">对局中</string>
|
||||
<string name="friends_watch">观战</string>
|
||||
<string name="friends_watch_count">观战 · %1$d/%2$d</string>
|
||||
<string name="friends_watch_full">已满</string>
|
||||
<string name="spectators_description">观战人数:%1$d</string>
|
||||
<string name="spectate_title">观战</string>
|
||||
<string name="spectate_joining">正在加入对局…</string>
|
||||
<string name="spectate_flip">翻转棋盘</string>
|
||||
<string name="spectate_back_to_friends">返回好友</string>
|
||||
<string name="spectate_lost_text">无法再连接到主持对局的设备。</string>
|
||||
<string name="spectate_full_title">观战人数已满</string>
|
||||
<string name="spectate_full_text">此对局的观战人数已达上限(%1$d 人),请稍后再试。</string>
|
||||
<string name="spectate_update_title">需要更新</string>
|
||||
<string name="spectate_update_this">请更新 Matewave 以观看此对局。</string>
|
||||
<string name="spectate_update_host">主持此对局的玩家需要更新 Matewave 后才能观战。</string>
|
||||
<string name="spectate_failed_title">无法观看此对局</string>
|
||||
<string name="spectate_no_game">此对局已不可观看。</string>
|
||||
<string name="spectate_unreachable">无法连接到主持对局的设备。请确认你们连接的是同一个 Wi-Fi 网络。</string>
|
||||
<string name="spectate_left_win">%1$s离开了对局,%2$s获胜。</string>
|
||||
<string name="spectate_interrupted">对局中断:玩家之间的连接已断开。</string>
|
||||
</resources>
|
||||
|
||||
@@ -25,9 +25,9 @@
|
||||
<string name="settings_version">Version %1$s</string>
|
||||
<string name="settings_repo_title">Source code</string>
|
||||
<string name="settings_radio">Jazz radio</string>
|
||||
<string name="settings_radio_subtitle">Background internet radio instead of silence</string>
|
||||
<string name="settings_radio_subtitle">Radio Swiss Jazz. Without a connection, built-in music plays</string>
|
||||
<string name="settings_radio_connecting">Connecting...</string>
|
||||
<string name="settings_radio_error">Couldn\'t connect</string>
|
||||
<string name="settings_radio_error">No connection, built-in music</string>
|
||||
<string name="settings_sfx">Sound effects</string>
|
||||
<string name="settings_sfx_subtitle">Selecting a piece, moving, capturing</string>
|
||||
<string name="back">Back</string>
|
||||
@@ -354,10 +354,30 @@
|
||||
<string name="nearby_bt_off_hint">Turn it on to find players over Bluetooth</string>
|
||||
<string name="nearby_wifi_hint">Players on the same Wi-Fi network can\'t be found until you connect</string>
|
||||
<string name="permission_open_settings">Open settings</string>
|
||||
<string name="settings_menu_music">Menu music</string>
|
||||
<string name="settings_menu_music_subtitle">Calm music on the main screen while the radio is off</string>
|
||||
<string name="piece_queen">Queen</string>
|
||||
<string name="piece_rook">Rook</string>
|
||||
<string name="piece_bishop">Bishop</string>
|
||||
<string name="piece_knight">Knight</string>
|
||||
|
||||
<!-- Spectators -->
|
||||
<string name="friends_in_game">In game</string>
|
||||
<string name="friends_watch">Watch</string>
|
||||
<string name="friends_watch_count">Watch · %1$d/%2$d</string>
|
||||
<string name="friends_watch_full">Full</string>
|
||||
<string name="spectators_description">Spectators: %1$d</string>
|
||||
<string name="spectate_title">Watching</string>
|
||||
<string name="spectate_joining">Joining the game…</string>
|
||||
<string name="spectate_flip">Flip board</string>
|
||||
<string name="spectate_back_to_friends">Back to Friends</string>
|
||||
<string name="spectate_lost_text">The host\'s device can no longer be reached.</string>
|
||||
<string name="spectate_full_title">Game is full</string>
|
||||
<string name="spectate_full_text">This game already has the maximum of %1$d spectators. Try again later.</string>
|
||||
<string name="spectate_update_title">Update required</string>
|
||||
<string name="spectate_update_this">Update Matewave to watch this game.</string>
|
||||
<string name="spectate_update_host">The player hosting this game needs to update Matewave before it can be watched.</string>
|
||||
<string name="spectate_failed_title">Can\'t watch this game</string>
|
||||
<string name="spectate_no_game">This game is no longer available.</string>
|
||||
<string name="spectate_unreachable">The host\'s device can\'t be reached. Make sure you\'re on the same Wi-Fi network.</string>
|
||||
<string name="spectate_left_win">%1$s left the game. %2$s wins.</string>
|
||||
<string name="spectate_interrupted">Game interrupted: the players lost their connection.</string>
|
||||
</resources>
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
package cc.skysparkle.matewave
|
||||
|
||||
import cc.skysparkle.matewave.spectate.FriendStatusResolver
|
||||
import cc.skysparkle.matewave.spectate.MAX_SPECTATORS
|
||||
import cc.skysparkle.matewave.spectate.NearbyPlayerGame
|
||||
import cc.skysparkle.matewave.spectate.PresenceStatus
|
||||
import cc.skysparkle.matewave.spectate.SpectateTarget
|
||||
import cc.skysparkle.matewave.spectate.SpectatorAdvert
|
||||
import cc.skysparkle.matewave.spectate.SpectatorMessage
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class FriendStatusTest {
|
||||
private val tag = SpectatorAdvert.tagOf("game-1")
|
||||
private val host = NearbyPlayerGame("host", "192.168.1.10", tag, 40_123)
|
||||
private val guest = NearbyPlayerGame("guest", "192.168.1.11", tag, 0)
|
||||
private val idle = NearbyPlayerGame("idle", "192.168.1.12", "", 0)
|
||||
private val nearby = listOf(host, guest, idle).associateBy { it.playerId }
|
||||
private val target = SpectateTarget("192.168.1.10", 40_123, tag)
|
||||
|
||||
private fun status(count: Int, live: Boolean = true) = SpectatorMessage.Status(live, count, MAX_SPECTATORS, 1)
|
||||
|
||||
@Test
|
||||
fun notVisibleIsOffline() {
|
||||
assertEquals(PresenceStatus.OFFLINE, FriendStatusResolver.resolve("nobody", nearby, emptyMap()).status)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun visibleWithoutAGameIsOnline() {
|
||||
val s = FriendStatusResolver.resolve("idle", nearby, emptyMap())
|
||||
assertEquals(PresenceStatus.ONLINE, s.status)
|
||||
assertNull(s.target)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun hostInGameCanBeWatchedWithTheLiveCount() {
|
||||
val s = FriendStatusResolver.resolve("host", nearby, mapOf(target to status(7)))
|
||||
assertEquals(PresenceStatus.IN_GAME, s.status)
|
||||
assertEquals(target, s.target)
|
||||
assertEquals(7, s.spectators)
|
||||
assertFalse(s.full)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun guestIsWatchedThroughTheHost() {
|
||||
val s = FriendStatusResolver.resolve("guest", nearby, mapOf(target to status(3)))
|
||||
assertEquals(PresenceStatus.IN_GAME, s.status)
|
||||
assertEquals(target, s.target)
|
||||
assertEquals(3, s.spectators)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun fullGameIsReportedAsFull() {
|
||||
assertTrue(FriendStatusResolver.resolve("host", nearby, mapOf(target to status(MAX_SPECTATORS))).full)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun countIsUnknownUntilTheHostAnswers() {
|
||||
val s = FriendStatusResolver.resolve("host", nearby, emptyMap())
|
||||
assertEquals(PresenceStatus.IN_GAME, s.status)
|
||||
assertNull(s.spectators)
|
||||
assertFalse(s.full)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun hostSayingTheGameEndedWinsOverAStaleAnnouncement() {
|
||||
val ended = mapOf(target to status(0, live = false))
|
||||
assertEquals(PresenceStatus.ONLINE, FriendStatusResolver.resolve("host", nearby, ended).status)
|
||||
assertEquals(PresenceStatus.ONLINE, FriendStatusResolver.resolve("guest", nearby, ended).status)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun guestWhoseHostIsHiddenIsInGameWithoutWatch() {
|
||||
val s = FriendStatusResolver.resolve("guest", mapOf("guest" to guest), emptyMap())
|
||||
assertEquals(PresenceStatus.IN_GAME, s.status)
|
||||
assertNull(s.target)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun onlyHostsAreProbed() {
|
||||
assertEquals(setOf(target), FriendStatusResolver.targets(nearby.values))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun advertRoundTripsAndRejectsJunk() {
|
||||
val state = SpectatorAdvert.State(tag, 40_123)
|
||||
val attrs = SpectatorAdvert.attributes(state)
|
||||
assertEquals(state, SpectatorAdvert.parse { attrs[it] ?: "" })
|
||||
assertEquals(SpectatorAdvert.State(), SpectatorAdvert.parse { "" })
|
||||
assertEquals(SpectatorAdvert.State(), SpectatorAdvert.parse { if (it == "g") "not-a-tag" else "1" })
|
||||
assertEquals(SpectatorAdvert.State(tag, 0), SpectatorAdvert.parse { if (it == "g") tag else "99999" })
|
||||
assertEquals(emptyMap<String, String>(), SpectatorAdvert.attributes(SpectatorAdvert.State()))
|
||||
assertEquals(8, tag.length)
|
||||
assertEquals("", SpectatorAdvert.tagOf(""))
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ class GameMessageTest {
|
||||
@Test fun signed() = roundTrip(GameMessage.SignedMsg("abc", "tag", 7))
|
||||
@Test fun rematch() = roundTrip(GameMessage.RematchMsg("accept", "g1", "g2"))
|
||||
@Test fun images() = roundTrip(GameMessage.ProfileImagesMsg("a", null, "g1"))
|
||||
@Test fun spectatorCount() = roundTrip(GameMessage.SpectatorCountMsg(7, "g1"))
|
||||
|
||||
@Test
|
||||
fun profileCarriesGameIdAndVersion() {
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
package cc.skysparkle.matewave
|
||||
|
||||
import cc.skysparkle.matewave.engine.GameStatus
|
||||
import cc.skysparkle.matewave.engine.PieceColor
|
||||
import cc.skysparkle.matewave.engine.PieceType
|
||||
import cc.skysparkle.matewave.spectate.SpectatorClock
|
||||
import cc.skysparkle.matewave.spectate.SpectatorDiff
|
||||
import cc.skysparkle.matewave.spectate.SpectatorGame
|
||||
import cc.skysparkle.matewave.spectate.SpectatorGame.Applied
|
||||
import cc.skysparkle.matewave.spectate.SpectatorMessage
|
||||
import cc.skysparkle.matewave.spectate.SpectatorOutcome
|
||||
import cc.skysparkle.matewave.spectate.SpectatorPlayer
|
||||
import cc.skysparkle.matewave.spectate.SpectatorResult
|
||||
import cc.skysparkle.matewave.spectate.SpectatorResults
|
||||
import cc.skysparkle.matewave.spectate.SpectatorSnapshot
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class SpectatorGameTest {
|
||||
private fun snapshot(moves: List<String>, gameId: String = "g1", result: SpectatorResult? = null) = SpectatorSnapshot(
|
||||
gameId = gameId,
|
||||
white = SpectatorPlayer("u1", "Alice", 1500),
|
||||
black = SpectatorPlayer("u2", "Bob", 1400),
|
||||
movesUci = moves,
|
||||
initialSeconds = 180,
|
||||
incrementSeconds = 2,
|
||||
clock = SpectatorClock(170_000, 175_000, if (moves.size % 2 == 0) PieceColor.WHITE else PieceColor.BLACK),
|
||||
result = result
|
||||
)
|
||||
|
||||
private fun move(ply: Int, uci: String, gameId: String = "g1") = SpectatorMessage.MovePlayed(gameId, ply, uci, null)
|
||||
|
||||
@Test
|
||||
fun loadReplaysTheMoveListWithTurnAndLastMove() {
|
||||
val game = SpectatorGame()
|
||||
assertTrue(game.load(snapshot(listOf("e2e4", "e7e5", "e1e2"))))
|
||||
val view = game.view!!
|
||||
assertEquals(listOf("e4", "e5", "Ke2"), view.moveSans)
|
||||
assertEquals(PieceColor.BLACK, view.board.sideToMove)
|
||||
assertEquals("e1e2", view.lastMove!!.toUci())
|
||||
assertEquals(3, view.ply)
|
||||
assertEquals(180, view.initialSeconds)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun illegalHistoryIsRefused() {
|
||||
assertFalse(SpectatorGame().load(snapshot(listOf("e2e5"))))
|
||||
assertFalse(SpectatorGame().load(snapshot(listOf("zz99"))))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun liveMovesFollowOnAndDuplicatesAreIgnored() {
|
||||
val game = SpectatorGame()
|
||||
game.load(snapshot(listOf("d2d4")))
|
||||
assertEquals(Applied.APPLIED, game.onMove(move(2, "d7d5")))
|
||||
assertEquals(Applied.IGNORED, game.onMove(move(2, "d7d5")))
|
||||
assertEquals(Applied.IGNORED, game.onMove(move(1, "d2d4")))
|
||||
assertEquals(listOf("d4", "d5"), game.view!!.moveSans)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun gapsIllegalMovesAndForeignGamesAskForResync() {
|
||||
val game = SpectatorGame()
|
||||
game.load(snapshot(listOf("d2d4")))
|
||||
assertEquals(Applied.NEEDS_RESYNC, game.onMove(move(3, "c2c4")))
|
||||
assertEquals(Applied.NEEDS_RESYNC, game.onMove(move(2, "d4d5")))
|
||||
assertEquals(Applied.NEEDS_RESYNC, game.onMove(move(2, "d7d5", gameId = "other")))
|
||||
assertEquals(Applied.NEEDS_RESYNC, SpectatorGame().onMove(move(1, "e2e4")))
|
||||
assertEquals(1, game.view!!.ply)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun promotionIsKept() {
|
||||
val game = SpectatorGame()
|
||||
val moves = listOf("h2h4", "g7g5", "h4g5", "h7h6", "g5h6", "g8f6", "h6h7", "f6g8")
|
||||
assertTrue(game.load(snapshot(moves)))
|
||||
assertEquals(Applied.APPLIED, game.onMove(move(9, "h7g8n")))
|
||||
assertEquals(PieceType.KNIGHT, game.view!!.lastMove!!.promotion)
|
||||
assertEquals("hxg8=N", game.view!!.moveSans.last())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun gameOverStopsTheClockAndLaterMovesAreIgnored() {
|
||||
val game = SpectatorGame()
|
||||
game.load(snapshot(listOf("f2f3", "e7e5", "g2g4", "d8h4")))
|
||||
val result = SpectatorResult(SpectatorOutcome.CHECKMATE, PieceColor.BLACK)
|
||||
assertEquals(Applied.APPLIED, game.onGameOver(SpectatorMessage.GameOver("g1", result, null)))
|
||||
assertEquals(result, game.view!!.result)
|
||||
assertNull(game.view!!.clock!!.running)
|
||||
assertEquals(Applied.IGNORED, game.onMove(move(5, "a2a3")))
|
||||
game.onClock(SpectatorClock(1, 1, PieceColor.WHITE))
|
||||
assertNull(game.view!!.clock!!.running)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun diffTurnsNewMovesIntoLiveMessagesWithTheLatestClock() {
|
||||
val before = snapshot(listOf("e2e4"))
|
||||
val after = snapshot(listOf("e2e4", "e7e5", "g1f3"))
|
||||
val events = SpectatorDiff.between(before, after)
|
||||
assertEquals(2, events.size)
|
||||
val first = events[0] as SpectatorMessage.MovePlayed
|
||||
val second = events[1] as SpectatorMessage.MovePlayed
|
||||
assertEquals(2 to "e7e5", first.ply to first.uci)
|
||||
assertNull(first.clock)
|
||||
assertEquals(3 to "g1f3", second.ply to second.uci)
|
||||
assertEquals(after.clock, second.clock)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun diffReportsTheEndOnceAndRestartsOnANewGame() {
|
||||
val playing = snapshot(listOf("e2e4"))
|
||||
val over = playing.copy(result = SpectatorResult(SpectatorOutcome.RESIGNATION, PieceColor.WHITE))
|
||||
assertEquals(listOf(SpectatorMessage.GameOver("g1", over.result!!, over.clock)), SpectatorDiff.between(playing, over))
|
||||
assertEquals(emptyList<SpectatorMessage>(), SpectatorDiff.between(over, over))
|
||||
val rematch = snapshot(emptyList(), gameId = "g2")
|
||||
assertEquals(listOf(SpectatorMessage.NewGame(rematch)), SpectatorDiff.between(over, rematch))
|
||||
assertEquals(emptyList<SpectatorMessage>(), SpectatorDiff.between(null, rematch))
|
||||
// Clock ticks alone are carried by pings, not extra messages.
|
||||
assertEquals(emptyList<SpectatorMessage>(), SpectatorDiff.between(playing, playing.copy(clock = SpectatorClock(1, 2, null))))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun diffFallsBackToAFullSnapshotWhenHistoryChanges() {
|
||||
val a = snapshot(listOf("e2e4", "e7e5"))
|
||||
val b = snapshot(listOf("d2d4"))
|
||||
assertEquals(listOf(SpectatorMessage.NewGame(b)), SpectatorDiff.between(a, b))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun resultsMapEveryWayAGameCanEnd() {
|
||||
fun of(status: GameStatus, timedOut: PieceColor? = null, resigned: PieceColor? = null, left: Boolean = false) =
|
||||
SpectatorResults.of(status, PieceColor.WHITE, timedOut, resigned, left)
|
||||
assertNull(of(GameStatus.ONGOING))
|
||||
assertEquals(SpectatorResult(SpectatorOutcome.CHECKMATE, PieceColor.BLACK), of(GameStatus.CHECKMATE))
|
||||
assertEquals(SpectatorResult(SpectatorOutcome.TIMEOUT, PieceColor.WHITE), of(GameStatus.TIMEOUT, timedOut = PieceColor.BLACK))
|
||||
assertEquals(SpectatorResult(SpectatorOutcome.RESIGNATION, PieceColor.BLACK), of(GameStatus.RESIGNATION, resigned = PieceColor.WHITE))
|
||||
assertEquals(SpectatorResult(SpectatorOutcome.LEFT, PieceColor.WHITE), of(GameStatus.RESIGNATION, resigned = PieceColor.BLACK, left = true))
|
||||
assertEquals(SpectatorResult(SpectatorOutcome.STALEMATE, null), of(GameStatus.STALEMATE))
|
||||
assertEquals(SpectatorResult(SpectatorOutcome.FIFTY_MOVES, null), of(GameStatus.DRAW_50_MOVES))
|
||||
assertEquals(SpectatorResult(SpectatorOutcome.REPETITION, null), of(GameStatus.DRAW_REPETITION))
|
||||
assertEquals(SpectatorResult(SpectatorOutcome.INSUFFICIENT_MATERIAL, null), of(GameStatus.DRAW_MATERIAL))
|
||||
assertEquals(SpectatorResult(SpectatorOutcome.TIMEOUT_DRAW, null), of(GameStatus.TIMEOUT_DRAW))
|
||||
assertEquals(SpectatorResult(SpectatorOutcome.AGREEMENT, null), of(GameStatus.DRAW_AGREEMENT))
|
||||
assertEquals(SpectatorResult(SpectatorOutcome.LEFT, PieceColor.BLACK), SpectatorResults.leftBy(PieceColor.WHITE))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,460 @@
|
||||
package cc.skysparkle.matewave
|
||||
|
||||
import cc.skysparkle.matewave.engine.PieceColor
|
||||
import cc.skysparkle.matewave.spectate.MAX_SPECTATORS
|
||||
import cc.skysparkle.matewave.spectate.RejectReason
|
||||
import cc.skysparkle.matewave.spectate.SpectatorBroadcaster
|
||||
import cc.skysparkle.matewave.spectate.SpectatorClient
|
||||
import cc.skysparkle.matewave.spectate.SpectatorClient.Event
|
||||
import cc.skysparkle.matewave.spectate.SpectatorClient.Failure
|
||||
import cc.skysparkle.matewave.spectate.SpectatorClock
|
||||
import cc.skysparkle.matewave.spectate.SpectatorGame
|
||||
import cc.skysparkle.matewave.spectate.SpectatorHub
|
||||
import cc.skysparkle.matewave.spectate.SpectatorMessage
|
||||
import cc.skysparkle.matewave.spectate.SpectatorOutcome
|
||||
import cc.skysparkle.matewave.spectate.SpectatorPlayer
|
||||
import cc.skysparkle.matewave.spectate.SpectatorProbe
|
||||
import cc.skysparkle.matewave.spectate.SpectatorProtocol
|
||||
import cc.skysparkle.matewave.spectate.SpectatorResults
|
||||
import cc.skysparkle.matewave.spectate.SpectatorSnapshot
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assert.fail
|
||||
import org.junit.Test
|
||||
import java.io.BufferedReader
|
||||
import java.io.Closeable
|
||||
import java.io.IOException
|
||||
import java.io.InputStreamReader
|
||||
import java.net.InetAddress
|
||||
import java.net.ServerSocket
|
||||
import java.net.Socket
|
||||
import java.util.concurrent.CopyOnWriteArrayList
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.LinkedBlockingQueue
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
class SpectatorHubTest {
|
||||
private val loopback: InetAddress = InetAddress.getLoopbackAddress()
|
||||
private val hubTiming = SpectatorHub.Timing(helloTimeoutMs = 1_000, pingIntervalMs = 150, silenceTimeoutMs = 900)
|
||||
private val clientTiming = SpectatorClient.Timing(connectTimeoutMs = 2_000, silenceTimeoutMs = 900)
|
||||
|
||||
private val hubs = CopyOnWriteArrayList<SpectatorHub>()
|
||||
private val clients = CopyOnWriteArrayList<SpectatorClient>()
|
||||
private val closeables = CopyOnWriteArrayList<Closeable>()
|
||||
|
||||
@After
|
||||
fun tearDown() {
|
||||
clients.forEach { it.stop() }
|
||||
hubs.forEach { it.close() }
|
||||
closeables.forEach { runCatching { it.close() } }
|
||||
}
|
||||
|
||||
private fun snapshot(
|
||||
moves: List<String> = emptyList(),
|
||||
clock: SpectatorClock? = SpectatorClock(300_000, 300_000, PieceColor.WHITE),
|
||||
gameId: String = "g1"
|
||||
) = SpectatorSnapshot(
|
||||
gameId = gameId,
|
||||
white = SpectatorPlayer("u1", "Alice", 1500),
|
||||
black = SpectatorPlayer("u2", "Bob", 1400),
|
||||
movesUci = moves,
|
||||
initialSeconds = 300,
|
||||
incrementSeconds = 0,
|
||||
clock = clock
|
||||
)
|
||||
|
||||
private fun hub(initial: SpectatorSnapshot? = snapshot()): SpectatorHub {
|
||||
val hub = SpectatorHub(timing = hubTiming)
|
||||
hubs += hub
|
||||
hub.start(loopback)
|
||||
if (initial != null) hub.publish(initial)
|
||||
return hub
|
||||
}
|
||||
|
||||
private class Recorder {
|
||||
val events = LinkedBlockingQueue<Event>()
|
||||
|
||||
fun next(timeoutMs: Long = 3_000): Event =
|
||||
events.poll(timeoutMs, TimeUnit.MILLISECONDS) ?: throw AssertionError("No event within $timeoutMs ms")
|
||||
|
||||
/** Skips pings and counts until an event matching [predicate]. */
|
||||
fun awaitEvent(timeoutMs: Long = 3_000, predicate: (Event) -> Boolean): Event {
|
||||
val deadline = System.currentTimeMillis() + timeoutMs
|
||||
while (true) {
|
||||
val left = deadline - System.currentTimeMillis()
|
||||
if (left <= 0) throw AssertionError("Expected event did not arrive")
|
||||
val event = events.poll(left, TimeUnit.MILLISECONDS) ?: continue
|
||||
if (predicate(event)) return event
|
||||
}
|
||||
}
|
||||
|
||||
fun awaitMessage(timeoutMs: Long = 3_000, predicate: (SpectatorMessage) -> Boolean): SpectatorMessage =
|
||||
(awaitEvent(timeoutMs) { it is Event.Received && predicate(it.message) } as Event.Received).message
|
||||
}
|
||||
|
||||
private fun watch(
|
||||
port: Int,
|
||||
recorder: Recorder = Recorder(),
|
||||
version: Int = SpectatorProtocol.VERSION,
|
||||
minVersion: Int = SpectatorProtocol.MIN_COMPATIBLE_VERSION
|
||||
): Pair<SpectatorClient, Recorder> {
|
||||
val client = SpectatorClient("127.0.0.1", port, { recorder.events.add(it) }, clientTiming, version, minVersion)
|
||||
clients += client
|
||||
client.start()
|
||||
return client to recorder
|
||||
}
|
||||
|
||||
private fun awaitCount(hub: SpectatorHub, expected: Int, timeoutMs: Long = 3_000) {
|
||||
val deadline = System.currentTimeMillis() + timeoutMs
|
||||
while (hub.count.value != expected) {
|
||||
if (System.currentTimeMillis() > deadline) fail("Spectator count ${hub.count.value}, expected $expected")
|
||||
Thread.sleep(10)
|
||||
}
|
||||
}
|
||||
|
||||
private fun joined(recorder: Recorder): SpectatorMessage.Welcome {
|
||||
val event = recorder.next()
|
||||
assertTrue("Expected to join, got $event", event is Event.Joined)
|
||||
return (event as Event.Joined).welcome
|
||||
}
|
||||
|
||||
@Test
|
||||
fun twentySpectatorsJoinAndTheTwentyFirstIsRefused() {
|
||||
val hub = hub()
|
||||
val watchers = List(MAX_SPECTATORS) { watch(hub.port).second }
|
||||
watchers.forEach { joined(it) }
|
||||
awaitCount(hub, MAX_SPECTATORS)
|
||||
|
||||
val (_, late) = watch(hub.port)
|
||||
assertEquals(Event.JoinFailed(Failure.FULL), late.next())
|
||||
assertEquals(MAX_SPECTATORS, hub.count.value)
|
||||
|
||||
// Everyone already watching still gets the game.
|
||||
hub.publish(snapshot(listOf("e2e4")), listOf(SpectatorMessage.MovePlayed("g1", 1, "e2e4", null)))
|
||||
watchers.forEach { recorder ->
|
||||
val move = recorder.awaitMessage { it is SpectatorMessage.MovePlayed } as SpectatorMessage.MovePlayed
|
||||
assertEquals("e2e4", move.uci)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun simultaneousJoinsNeverExceedTheLimit() {
|
||||
val hub = hub()
|
||||
val start = CountDownLatch(1)
|
||||
val recorders = List(MAX_SPECTATORS + 10) { Recorder() }
|
||||
val threads = recorders.map { r -> Thread { start.await(); watch(hub.port, r) }.apply { start() } }
|
||||
start.countDown()
|
||||
threads.forEach { it.join() }
|
||||
|
||||
val outcomes = recorders.map { it.next(5_000) }
|
||||
assertEquals(MAX_SPECTATORS, outcomes.count { it is Event.Joined })
|
||||
assertEquals(10, outcomes.count { it == Event.JoinFailed(Failure.FULL) })
|
||||
assertEquals(MAX_SPECTATORS, hub.count.value)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun joiningMidGameGetsFullStateThenFollowsLive() {
|
||||
val hub = hub()
|
||||
val broadcaster = SpectatorBroadcaster(hub)
|
||||
val opening = listOf("e2e4", "e7e5", "g1f3")
|
||||
broadcaster.update(snapshot())
|
||||
broadcaster.update(snapshot(opening, SpectatorClock(290_000, 295_000, PieceColor.BLACK)))
|
||||
|
||||
val (_, recorder) = watch(hub.port)
|
||||
val welcome = joined(recorder)
|
||||
assertEquals(1, welcome.count)
|
||||
assertEquals(opening, welcome.game.movesUci)
|
||||
assertEquals("Alice", welcome.game.white.name)
|
||||
assertEquals(300, welcome.game.initialSeconds)
|
||||
val clock = welcome.game.clock!!
|
||||
assertEquals(PieceColor.BLACK, clock.running)
|
||||
assertEquals(290_000, clock.whiteMs)
|
||||
assertTrue(clock.blackMs in 290_000..295_000)
|
||||
|
||||
val game = SpectatorGame()
|
||||
assertTrue(game.load(welcome.game))
|
||||
assertEquals(PieceColor.BLACK, game.view!!.board.sideToMove)
|
||||
assertEquals(listOf("e4", "e5", "Nf3"), game.view!!.moveSans)
|
||||
|
||||
broadcaster.update(snapshot(opening + "b8c6", SpectatorClock(290_000, 293_000, PieceColor.WHITE)))
|
||||
val move = recorder.awaitMessage { it is SpectatorMessage.MovePlayed } as SpectatorMessage.MovePlayed
|
||||
assertEquals(4, move.ply)
|
||||
assertEquals(SpectatorGame.Applied.APPLIED, game.onMove(move))
|
||||
assertEquals(PieceColor.WHITE, game.view!!.board.sideToMove)
|
||||
assertEquals("Nc6", game.view!!.moveSans.last())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun hostLeavingMidGameShowsTheResultThenSaysGoodbye() {
|
||||
val hub = hub()
|
||||
val broadcaster = SpectatorBroadcaster(hub)
|
||||
val playing = snapshot(listOf("e2e4"))
|
||||
broadcaster.update(playing)
|
||||
val (_, recorder) = watch(hub.port)
|
||||
joined(recorder)
|
||||
|
||||
broadcaster.close(playing.copy(result = SpectatorResults.leftBy(PieceColor.WHITE)))
|
||||
val end = recorder.awaitMessage { it is SpectatorMessage.GameOver } as SpectatorMessage.GameOver
|
||||
assertEquals(SpectatorOutcome.LEFT, end.result.outcome)
|
||||
assertEquals(PieceColor.BLACK, end.result.winner)
|
||||
assertEquals(Event.Disconnected(hostClosed = true), recorder.awaitEvent { it is Event.Disconnected })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun hostDroppingOffIsSeenAsConnectionLost() {
|
||||
val hub = hub()
|
||||
val link = FlakyLink(hub.port)
|
||||
val (_, recorder) = watch(link.port)
|
||||
joined(recorder)
|
||||
|
||||
link.cut()
|
||||
assertEquals(Event.Disconnected(hostClosed = false), recorder.awaitEvent { it is Event.Disconnected })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun wifiSwitchingOffIsDetectedOnBothSides() {
|
||||
val hub = hub()
|
||||
val link = FlakyLink(hub.port)
|
||||
val (_, cutOff) = watch(link.port)
|
||||
val (_, direct) = watch(hub.port)
|
||||
joined(cutOff)
|
||||
joined(direct)
|
||||
awaitCount(hub, 2)
|
||||
|
||||
// No more packets either way, but no connection reset: what a dead Wi-Fi link looks like.
|
||||
link.silent = true
|
||||
|
||||
assertEquals(Event.Disconnected(hostClosed = false), cutOff.awaitEvent { it is Event.Disconnected })
|
||||
awaitCount(hub, 1)
|
||||
// The remaining spectator's counter follows.
|
||||
assertNotNull(direct.awaitMessage { it is SpectatorMessage.Count && it.count == 1 })
|
||||
|
||||
// The spectator who still has a connection keeps watching.
|
||||
hub.publish(snapshot(listOf("d2d4")), listOf(SpectatorMessage.MovePlayed("g1", 1, "d2d4", null)))
|
||||
assertNotNull(direct.awaitMessage { it is SpectatorMessage.MovePlayed })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun spectatorsLeavingFreeTheirSlotsWhileOthersKeepWatching() {
|
||||
val hub = hub()
|
||||
val watchers = List(MAX_SPECTATORS) { watch(hub.port) }
|
||||
watchers.forEach { joined(it.second) }
|
||||
awaitCount(hub, MAX_SPECTATORS)
|
||||
|
||||
watchers.take(5).forEach { it.first.stop() }
|
||||
awaitCount(hub, MAX_SPECTATORS - 5)
|
||||
|
||||
val (_, newcomer) = watch(hub.port)
|
||||
assertEquals(MAX_SPECTATORS - 4, joined(newcomer).count)
|
||||
|
||||
hub.publish(snapshot(listOf("c2c4")), listOf(SpectatorMessage.MovePlayed("g1", 1, "c2c4", null)))
|
||||
(watchers.drop(5).map { it.second } + newcomer).forEach {
|
||||
assertNotNull(it.awaitMessage { m -> m is SpectatorMessage.MovePlayed })
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun stalledSpectatorsNeverSlowDownTheHost() {
|
||||
val hub = hub()
|
||||
val link = FlakyLink(hub.port)
|
||||
repeat(5) { joined(watch(link.port).second) }
|
||||
link.silent = true
|
||||
|
||||
val started = System.nanoTime()
|
||||
repeat(2_000) { i ->
|
||||
hub.publish(snapshot(), listOf(SpectatorMessage.Count(i, MAX_SPECTATORS)))
|
||||
}
|
||||
val elapsedMs = (System.nanoTime() - started) / 1_000_000
|
||||
assertTrue("publish took $elapsedMs ms", elapsedMs < 1_000)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun outdatedSpectatorIsToldToUpdate() {
|
||||
val hub = hub()
|
||||
val (_, recorder) = watch(hub.port, version = 0, minVersion = 0)
|
||||
assertEquals(Event.JoinFailed(Failure.UPDATE_THIS_APP), recorder.next())
|
||||
assertEquals(0, hub.count.value)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun outdatedHostIsReported() {
|
||||
val hub = hub()
|
||||
val newer = SpectatorProtocol.VERSION + 1
|
||||
val (_, recorder) = watch(hub.port, version = newer, minVersion = newer)
|
||||
assertEquals(Event.JoinFailed(Failure.UPDATE_HOST_APP), recorder.next())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun rawOldClientGetsAClearRejectInsteadOfACrash() {
|
||||
val hub = hub()
|
||||
Socket(loopback, hub.port).use { s ->
|
||||
s.soTimeout = 2_000
|
||||
s.getOutputStream().write("{\"type\":\"hello\",\"sv\":0}\n".toByteArray())
|
||||
val reply = BufferedReader(InputStreamReader(s.getInputStream())).readLine()
|
||||
val reject = SpectatorProtocol.decode(reply)!!.message as SpectatorMessage.Reject
|
||||
assertEquals(RejectReason.UPDATE_REQUIRED, reject.reason)
|
||||
assertEquals(SpectatorProtocol.MIN_COMPATIBLE_VERSION, reject.minVersion)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun garbageAndOversizedInputCloseOnlyThatConnection() {
|
||||
val hub = hub()
|
||||
val (_, watcher) = watch(hub.port)
|
||||
joined(watcher)
|
||||
|
||||
for (payload in listOf("hello?\n", "x".repeat(SpectatorProtocol.MAX_CLIENT_LINE_CHARS + 10) + "\n")) {
|
||||
Socket(loopback, hub.port).use { s ->
|
||||
s.soTimeout = 2_000
|
||||
s.getOutputStream().write(payload.toByteArray())
|
||||
// Closed with unread input the host may answer with a reset instead of a clean close.
|
||||
val read = try { s.getInputStream().read() } catch (e: IOException) { -1 }
|
||||
assertEquals(-1, read)
|
||||
}
|
||||
}
|
||||
assertEquals(1, hub.count.value)
|
||||
hub.publish(snapshot(listOf("e2e4")), listOf(SpectatorMessage.MovePlayed("g1", 1, "e2e4", null)))
|
||||
assertNotNull(watcher.awaitMessage { it is SpectatorMessage.MovePlayed })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun silentConnectionThatNeverSaysHelloIsClosed() {
|
||||
val hub = hub()
|
||||
Socket(loopback, hub.port).use { s ->
|
||||
s.soTimeout = 3_000
|
||||
assertEquals(-1, s.getInputStream().read())
|
||||
}
|
||||
assertEquals(0, hub.count.value)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun noGameYetIsRefused() {
|
||||
val hub = hub(initial = null)
|
||||
val (_, recorder) = watch(hub.port)
|
||||
assertEquals(Event.JoinFailed(Failure.NO_GAME), recorder.next())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun statusProbeReportsLiveCountWithoutTakingASlot() {
|
||||
val hub = hub()
|
||||
repeat(3) { joined(watch(hub.port).second) }
|
||||
awaitCount(hub, 3)
|
||||
val status = SpectatorProbe.query("127.0.0.1", hub.port)!!
|
||||
assertTrue(status.inGame)
|
||||
assertEquals(3, status.count)
|
||||
assertEquals(MAX_SPECTATORS, status.max)
|
||||
assertEquals(3, hub.count.value)
|
||||
|
||||
hub.publish(snapshot().copy(result = SpectatorResults.interrupted))
|
||||
assertFalse(SpectatorProbe.query("127.0.0.1", hub.port)!!.inGame)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun probeOfAClosedHostIsNull() {
|
||||
val hub = hub()
|
||||
val port = hub.port
|
||||
hub.close()
|
||||
assertEquals(null, SpectatorProbe.query("127.0.0.1", port, timeoutMs = 500))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun resyncSendsAFreshSnapshot() {
|
||||
val hub = hub(snapshot(listOf("e2e4", "c7c5")))
|
||||
val (client, recorder) = watch(hub.port)
|
||||
joined(recorder)
|
||||
client.requestResync()
|
||||
val fresh = recorder.awaitMessage { it is SpectatorMessage.NewGame } as SpectatorMessage.NewGame
|
||||
assertEquals(listOf("e2e4", "c7c5"), fresh.game.movesUci)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun rematchReachesSpectatorsAsANewGame() {
|
||||
val hub = hub()
|
||||
val broadcaster = SpectatorBroadcaster(hub)
|
||||
val first = snapshot(listOf("f2f3", "e7e5", "g2g4", "d8h4"))
|
||||
broadcaster.update(first)
|
||||
val (_, recorder) = watch(hub.port)
|
||||
joined(recorder)
|
||||
broadcaster.update(first.copy(result = SpectatorResults.of(
|
||||
cc.skysparkle.matewave.engine.GameStatus.CHECKMATE, PieceColor.WHITE, null, null, false
|
||||
)))
|
||||
val end = recorder.awaitMessage { it is SpectatorMessage.GameOver } as SpectatorMessage.GameOver
|
||||
assertEquals(PieceColor.BLACK, end.result.winner)
|
||||
|
||||
broadcaster.update(snapshot(gameId = "g2"))
|
||||
val next = recorder.awaitMessage { it is SpectatorMessage.NewGame } as SpectatorMessage.NewGame
|
||||
assertEquals("g2", next.game.gameId)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun clocksKeepRunningBetweenHostUpdates() {
|
||||
val hub = hub(snapshot(clock = SpectatorClock(60_000, 60_000, PieceColor.WHITE)))
|
||||
Thread.sleep(400)
|
||||
val (_, recorder) = watch(hub.port)
|
||||
val clock = joined(recorder).game.clock!!
|
||||
assertTrue("white ${clock.whiteMs}", clock.whiteMs in 50_000..59_700)
|
||||
assertEquals(60_000, clock.blackMs)
|
||||
val ping = recorder.awaitMessage { it is SpectatorMessage.Ping } as SpectatorMessage.Ping
|
||||
assertTrue(ping.clock!!.whiteMs <= clock.whiteMs)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun closingTheHubEndsEveryoneAndRefusesNewcomers() {
|
||||
val hub = hub()
|
||||
val recorders = List(3) { watch(hub.port).second }
|
||||
recorders.forEach { joined(it) }
|
||||
val port = hub.port
|
||||
hub.close()
|
||||
recorders.forEach { assertEquals(Event.Disconnected(hostClosed = true), it.awaitEvent { e -> e is Event.Disconnected }) }
|
||||
assertEquals(0, hub.count.value)
|
||||
val (_, late) = watch(port)
|
||||
assertEquals(Event.JoinFailed(Failure.UNREACHABLE), late.next())
|
||||
}
|
||||
|
||||
/** A TCP relay that can go silent (dead Wi-Fi) or drop every connection (host gone). */
|
||||
private inner class FlakyLink(target: Int) : Closeable {
|
||||
private val server = ServerSocket(0, 50, loopback)
|
||||
private val sockets = CopyOnWriteArrayList<Socket>()
|
||||
@Volatile var silent = false
|
||||
val port: Int get() = server.localPort
|
||||
|
||||
init {
|
||||
closeables += this
|
||||
Thread {
|
||||
while (!server.isClosed) {
|
||||
val inbound = try { server.accept() } catch (e: IOException) { break }
|
||||
val outbound = Socket(loopback, target)
|
||||
sockets += inbound
|
||||
sockets += outbound
|
||||
pump(inbound, outbound)
|
||||
pump(outbound, inbound)
|
||||
}
|
||||
}.apply { isDaemon = true }.start()
|
||||
}
|
||||
|
||||
private fun pump(from: Socket, to: Socket) = Thread {
|
||||
val buffer = ByteArray(8_192)
|
||||
try {
|
||||
while (true) {
|
||||
val n = from.getInputStream().read(buffer)
|
||||
if (n < 0) break
|
||||
if (!silent) to.getOutputStream().write(buffer, 0, n)
|
||||
}
|
||||
} catch (_: IOException) {
|
||||
} finally {
|
||||
runCatching { from.close() }
|
||||
runCatching { to.close() }
|
||||
}
|
||||
}.apply { isDaemon = true }.start()
|
||||
|
||||
fun cut() = sockets.forEach { runCatching { it.close() } }
|
||||
|
||||
override fun close() {
|
||||
runCatching { server.close() }
|
||||
cut()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package cc.skysparkle.matewave
|
||||
|
||||
import cc.skysparkle.matewave.engine.PieceColor
|
||||
import cc.skysparkle.matewave.spectate.MAX_SPECTATORS
|
||||
import cc.skysparkle.matewave.spectate.RejectReason
|
||||
import cc.skysparkle.matewave.spectate.SpectatorClock
|
||||
import cc.skysparkle.matewave.spectate.SpectatorMessage
|
||||
import cc.skysparkle.matewave.spectate.SpectatorOutcome
|
||||
import cc.skysparkle.matewave.spectate.SpectatorPlayer
|
||||
import cc.skysparkle.matewave.spectate.SpectatorProtocol
|
||||
import cc.skysparkle.matewave.spectate.SpectatorResult
|
||||
import cc.skysparkle.matewave.spectate.SpectatorSnapshot
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class SpectatorProtocolTest {
|
||||
private val clock = SpectatorClock(295_000, 300_000, PieceColor.BLACK)
|
||||
private val snapshot = SpectatorSnapshot(
|
||||
gameId = "g1",
|
||||
white = SpectatorPlayer("u1", "Владимир", 1350),
|
||||
black = SpectatorPlayer("u2", "Bob", 1200),
|
||||
movesUci = listOf("e2e4", "e7e5", "g1f3"),
|
||||
initialSeconds = 300,
|
||||
incrementSeconds = 2,
|
||||
clock = clock
|
||||
)
|
||||
|
||||
private fun roundTrip(message: SpectatorMessage) {
|
||||
val envelope = SpectatorProtocol.decode(SpectatorProtocol.encode(message))
|
||||
assertNotNull(envelope)
|
||||
assertEquals(SpectatorProtocol.VERSION, envelope!!.version)
|
||||
assertEquals(message, envelope.message)
|
||||
}
|
||||
|
||||
@Test fun hello() = roundTrip(SpectatorMessage.Hello(1))
|
||||
@Test fun query() = roundTrip(SpectatorMessage.StatusQuery)
|
||||
@Test fun pong() = roundTrip(SpectatorMessage.Pong)
|
||||
@Test fun resync() = roundTrip(SpectatorMessage.Resync)
|
||||
@Test fun leave() = roundTrip(SpectatorMessage.Leave)
|
||||
@Test fun welcome() = roundTrip(SpectatorMessage.Welcome(7, MAX_SPECTATORS, snapshot))
|
||||
@Test fun status() = roundTrip(SpectatorMessage.Status(true, 7, MAX_SPECTATORS, 1))
|
||||
@Test fun reject() = roundTrip(SpectatorMessage.Reject(RejectReason.FULL, 1))
|
||||
@Test fun move() = roundTrip(SpectatorMessage.MovePlayed("g1", 4, "b8c6", clock))
|
||||
@Test fun moveWithoutClock() = roundTrip(SpectatorMessage.MovePlayed("g1", 4, "e7e8q", null))
|
||||
@Test fun count() = roundTrip(SpectatorMessage.Count(3, MAX_SPECTATORS))
|
||||
@Test fun ping() = roundTrip(SpectatorMessage.Ping(clock))
|
||||
@Test fun closing() = roundTrip(SpectatorMessage.Closing)
|
||||
@Test fun newGame() = roundTrip(SpectatorMessage.NewGame(snapshot.copy(movesUci = emptyList(), clock = null)))
|
||||
|
||||
@Test
|
||||
fun gameOverKeepsWinnerAndDraws() {
|
||||
roundTrip(SpectatorMessage.GameOver("g1", SpectatorResult(SpectatorOutcome.CHECKMATE, PieceColor.WHITE), clock.copy(running = null)))
|
||||
roundTrip(SpectatorMessage.GameOver("g1", SpectatorResult(SpectatorOutcome.AGREEMENT, null), null))
|
||||
roundTrip(SpectatorMessage.GameOver("g1", SpectatorResult(SpectatorOutcome.INTERRUPTED, null), null))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun everyMessageCarriesTheSenderVersion() {
|
||||
val line = SpectatorProtocol.encode(SpectatorMessage.Pong, version = 7)
|
||||
assertEquals(7, SpectatorProtocol.decode(line)!!.version)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun unknownTypeFromANewerVersionIsSkippedNotFatal() {
|
||||
val envelope = SpectatorProtocol.decode("""{"type":"emote","sv":9,"what":"wave"}""")
|
||||
assertNotNull(envelope)
|
||||
assertEquals(9, envelope!!.version)
|
||||
assertNull(envelope.message)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun unknownOutcomeAndRejectReasonDegradeGracefully() {
|
||||
val end = SpectatorProtocol.decode("""{"type":"end","sv":2,"gid":"g1","result":{"o":"abandoned"}}""")!!.message
|
||||
assertEquals(SpectatorOutcome.UNKNOWN, (end as SpectatorMessage.GameOver).result.outcome)
|
||||
val reject = SpectatorProtocol.decode("""{"type":"reject","sv":2,"reason":"banned","min":2}""")!!.message
|
||||
assertEquals(RejectReason.OTHER, (reject as SpectatorMessage.Reject).reason)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun malformedInputNeverThrows() {
|
||||
assertNull(SpectatorProtocol.decode("not json"))
|
||||
assertNull(SpectatorProtocol.decode("{}"))
|
||||
assertNull(SpectatorProtocol.decode(""))
|
||||
// Known type with missing fields: skipped like an unknown one.
|
||||
assertNull(SpectatorProtocol.decode("""{"type":"move","sv":1}""")!!.message)
|
||||
assertNull(SpectatorProtocol.decode("""{"type":"welcome","sv":1,"n":1}""")!!.message)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun oldHelloWithoutMinimumStillParses() {
|
||||
val hello = SpectatorProtocol.decode("""{"type":"hello","sv":1}""")!!.message
|
||||
assertEquals(SpectatorMessage.Hello(1), hello)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun clockAdvancesOnlyForTheRunningSide() {
|
||||
val later = clock.advancedBy(1_500)
|
||||
assertEquals(295_000, later.whiteMs)
|
||||
assertEquals(298_500, later.blackMs)
|
||||
assertEquals(0, SpectatorClock(1_000, 5_000, PieceColor.WHITE).advancedBy(9_000).whiteMs)
|
||||
assertEquals(clock.copy(running = null), clock.copy(running = null).advancedBy(5_000))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun hugeMoveListIsRejected() {
|
||||
val moves = (1..2_001).joinToString(",") { "\"e2e4\"" }
|
||||
val line = """{"type":"game","sv":1,"game":{"gid":"g","wp":{},"bp":{},"moves":[$moves]}}"""
|
||||
assertNull(SpectatorProtocol.decode(line)!!.message)
|
||||
assertTrue(SpectatorProtocol.MAX_CLIENT_LINE_CHARS < SpectatorProtocol.MAX_HOST_LINE_CHARS)
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 23 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 14 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 6.3 KiB |
@@ -0,0 +1,3 @@
|
||||
• Eingebaute Musik, wenn das Jazzradio keine Verbindung hat, mit eigenem Stück für Partien und Aufgaben. Sie ersetzt die bisherige Menümusik
|
||||
• Musik spielt nicht mehr, während ein Anruf oder eine andere App den Ton nutzt
|
||||
• Die Einstellungen zeigen „Aktion nötig“, solange Berechtigungen fehlen
|
||||
@@ -0,0 +1 @@
|
||||
• Partien von Freunden ansehen: bis zu 20 Zuschauer im selben WLAN können eine laufende LAN-Partie im Bereich „Freunde“ verfolgen
|
||||
@@ -0,0 +1,3 @@
|
||||
• Built-in music when the jazz radio has no connection, with its own track for games and puzzles. It replaces the separate menu music
|
||||
• Music no longer plays while a call or another app is using the sound
|
||||
• Settings show "Action needed" while permissions are missing
|
||||
@@ -0,0 +1 @@
|
||||
• Watch friends' games: up to 20 spectators on the same Wi-Fi can follow a live LAN game from the Friends section
|
||||
@@ -0,0 +1,3 @@
|
||||
• ジャズラジオに接続できないときは内蔵の音楽を再生。対局とパズルには専用の曲。メニュー音楽はこれに置き換わりました
|
||||
• 通話や他のアプリが音声を使っている間は音楽を再生しません
|
||||
• 権限が足りない間、設定に「要対応」と表示されます
|
||||
@@ -0,0 +1 @@
|
||||
• 友達の対局を観戦:同じWi-Fiにいる最大20人が「フレンド」から進行中のLAN対局を見られます
|
||||
@@ -0,0 +1,3 @@
|
||||
• Įdiegta muzika, kai džiazo radijas neturi ryšio, su atskiru kūriniu partijoms ir uždaviniams. Ji pakeitė atskirą meniu muziką
|
||||
• Muzika nebegroja, kol garsą naudoja skambutis ar kita programėlė
|
||||
• Nustatymuose rodoma „Reikia veiksmo“, kol trūksta leidimų
|
||||
@@ -0,0 +1 @@
|
||||
• Draugų partijų stebėjimas: iki 20 žiūrovų tame pačiame Wi-Fi tinkle gali sekti vykstančią LAN partiją skiltyje „Draugai“
|
||||
@@ -0,0 +1,3 @@
|
||||
• Встроенная музыка, когда у джаз-радио нет связи, со своим треком для партий и задач. Она заменила отдельную музыку в меню
|
||||
• Музыка больше не играет, пока звук занят звонком или другим приложением
|
||||
• В настройках показывается «Нужно действие», пока не хватает разрешений
|
||||
@@ -0,0 +1 @@
|
||||
• Просмотр партий друзей: до 20 зрителей в той же Wi-Fi сети могут следить за идущей LAN-партией в разделе «Друзья»
|
||||
@@ -0,0 +1,3 @@
|
||||
• 爵士电台无法连接时播放内置音乐,对局和谜题有专属曲目,取代了原来的菜单音乐
|
||||
• 通话或其他应用占用声音时不再播放音乐
|
||||
• 缺少权限时,设置中会显示“需要处理”
|
||||
@@ -0,0 +1 @@
|
||||
• 观看好友对局:同一 Wi-Fi 下最多 20 名观众可在“好友”中观看正在进行的局域网对局
|
||||
Reference in New Issue
Block a user