Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c5587e9418 | ||
|
|
438f06bce2 | ||
|
|
21b39cbc80 | ||
|
|
05d4936c90 | ||
|
|
8a40e86d73 | ||
|
|
ef5af5c395 | ||
|
|
0d0daf8a45 | ||
|
|
6ed42e0bf3 | ||
|
|
cac575ed26 | ||
|
|
77c438ff66 | ||
|
|
c2ee9f2c02 | ||
|
|
9b7e694a81 | ||
|
|
d3ea4d36c3 | ||
|
|
58f2766c57 | ||
|
|
50cc40ddaf | ||
|
|
b28fd42bfa | ||
|
|
570754fabe | ||
|
|
86921dc35c | ||
|
|
792f1d127f | ||
|
|
6d62019d3b | ||
|
|
f1995cceaa | ||
|
|
7e8ca1ec48 | ||
|
|
2751461fa0 | ||
|
|
f8fce1675f | ||
|
|
74ae8458d1 | ||
|
|
8891e2a081 | ||
|
|
06e02da33a | ||
|
|
52b0cb43c6 | ||
|
|
6137923ca1 | ||
|
|
f59e461405 | ||
|
|
fb58dfb4ae | ||
|
|
2d0e605dfa | ||
|
|
0eb407ead5 |
@@ -0,0 +1 @@
|
||||
ko_fi: skysparkle
|
||||
@@ -0,0 +1,27 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Something doesn't work as expected
|
||||
title: "[Bug] "
|
||||
---
|
||||
|
||||
**What happened**
|
||||
|
||||
|
||||
**Steps to reproduce**
|
||||
|
||||
1.
|
||||
2.
|
||||
3.
|
||||
|
||||
**What you expected**
|
||||
|
||||
|
||||
**Environment**
|
||||
|
||||
- App version:
|
||||
- Installed from: Gitea / GitHub / F-Droid / Google Play
|
||||
- Device and Android version:
|
||||
- Mode: vs AI / puzzles / openings / Bluetooth / LAN
|
||||
|
||||
**Screenshots or logs** (optional)
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
blank_issues_enabled: true
|
||||
contact_links:
|
||||
- name: Support the project on Ko-fi
|
||||
url: https://ko-fi.com/skysparkle
|
||||
about: Donations keep the apps and the Skysparkle server running.
|
||||
@@ -0,0 +1,18 @@
|
||||
---
|
||||
name: Feature request
|
||||
about: Suggest an idea that fits the app
|
||||
title: "[Feature] "
|
||||
---
|
||||
|
||||
<!-- Please check the "Out of scope" list in CONTRIBUTING.md before opening this. -->
|
||||
|
||||
**What problem does this solve**
|
||||
|
||||
|
||||
**Proposed solution**
|
||||
|
||||
|
||||
**Alternatives you considered**
|
||||
|
||||
|
||||
- [ ] I'd like to implement this myself
|
||||
@@ -0,0 +1,10 @@
|
||||
---
|
||||
name: Puzzle or opening issue
|
||||
about: Report a wrong puzzle solution or opening line
|
||||
title: "[Content] "
|
||||
---
|
||||
|
||||
- Puzzle or opening name:
|
||||
- Position (describe or attach a screenshot):
|
||||
- What the app expects:
|
||||
- What you think is correct, and why:
|
||||
@@ -0,0 +1,12 @@
|
||||
---
|
||||
name: Translation fix
|
||||
about: Report a wrong or awkward translation
|
||||
title: "[Translation] "
|
||||
---
|
||||
|
||||
<!-- Supported languages: English, Russian, German, Japanese, Lithuanian, Chinese. New languages are not accepted. -->
|
||||
|
||||
- Language:
|
||||
- Screen or place in the app:
|
||||
- Current text:
|
||||
- Suggested text:
|
||||
@@ -0,0 +1,17 @@
|
||||
## What does this change
|
||||
|
||||
|
||||
## Related issue
|
||||
|
||||
Closes #
|
||||
|
||||
## Checklist
|
||||
|
||||
- [ ] Discussed in an issue first (not needed for small fixes)
|
||||
- [ ] `./gradlew assembleDebug` and `./gradlew testDebugUnitTest` pass
|
||||
- [ ] Tested on a device or emulator (Android version: )
|
||||
- [ ] Multiplayer changes tested on two physical devices
|
||||
- [ ] No ads, analytics, trackers or Google Play Services / Firebase dependencies
|
||||
- [ ] New strings added to `values/strings.xml` (missing translations noted below)
|
||||
- [ ] Screenshots added for UI changes
|
||||
- [ ] I agree that my contribution is licensed under GPL-3.0-or-later
|
||||
@@ -4,7 +4,7 @@ Thanks for wanting to help! This guide explains where to contribute, what fits t
|
||||
|
||||
## Where to contribute
|
||||
|
||||
Issues and pull requests go to the repository on [Gitea](https://git.skysparkle.cc/kalarina/Matewave).
|
||||
Issues and pull requests go to the repository on [GitHub](https://github.com/kalarina-bit/Matewave).
|
||||
|
||||
## Ways to help
|
||||
|
||||
|
||||
@@ -9,31 +9,42 @@
|
||||
Play against the AI, solve puzzles, learn openings, or play friends nearby over Bluetooth and Wi-Fi/LAN.
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://ko-fi.com/skysparkle"><img src="https://ko-fi.com/img/githubbutton_sm.svg" alt="Support me on Ko-fi"></a>
|
||||
</p>
|
||||
|
||||
> [!IMPORTANT]
|
||||
> **Matewave is coming to Google Play!** The app is now in closed testing there ahead of the public release. Ideas, wishes and suggestions for improvement are very welcome — send them wherever is easiest for you: an [issue on GitHub](https://github.com/kalarina-bit/Matewave/issues), or an email to [cuken107@proton.me](mailto:cuken107@proton.me).
|
||||
|
||||
> [!NOTE]
|
||||
> **Looking for designers!** Matewave is looking for volunteer designers to help with icons, logos, animations, cover art (store graphics) and UI design. This is unpaid help for an open-source project. If you're interested, write to [cuken107@proton.me](mailto:cuken107@proton.me).
|
||||
|
||||
<p align="center">
|
||||
<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>
|
||||
|
||||
<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://apps.obtainium.imranr.dev/redirect?r=obtainium://add/https://github.com/kalarina-bit/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>
|
||||
|
||||
<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">
|
||||
<img src="assets/screenshots/1-play-learn-solve-left.png" width="160" alt="Play, learn, solve"><img src="assets/screenshots/2-play-learn-solve-right.png" width="160" alt="Home screen">
|
||||
<img src="assets/screenshots/3-play-ai-or-a-friend.png" width="160" alt="Play AI or a friend">
|
||||
<img src="assets/screenshots/4-puzzles.png" width="160" alt="Puzzles for your rating">
|
||||
</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**
|
||||
@@ -42,8 +53,8 @@
|
||||
## <img src="assets/icon-install.png" width="32" alt=""> Installation
|
||||
|
||||
- **[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.
|
||||
- **[Obtainium](https://apps.obtainium.imranr.dev/redirect?r=obtainium://add/https://github.com/kalarina-bit/Matewave)** — installs the APK straight from GitHub releases and keeps it up to date.
|
||||
- **Manually** — download the latest APK from [GitHub Releases](https://github.com/kalarina-bit/Matewave/releases/latest), 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.
|
||||
|
||||
## <img src="assets/icon-verify.png" width="32" alt=""> Verifying a download
|
||||
|
||||
@@ -74,7 +85,13 @@ Nearby multiplayer needs two physical devices — the emulator has no real Bluet
|
||||
|
||||
## 🤝 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.
|
||||
Bug reports, puzzle and opening fixes, translation fixes and pull requests are welcome in the [issue tracker](https://github.com/kalarina-bit/Matewave/issues). Please read [CONTRIBUTING.md](CONTRIBUTING.md) first — it explains what fits the project and how to send changes.
|
||||
|
||||
## ☕ Support
|
||||
|
||||
Matewave is free, open source and has no ads. If it is useful to you, you can support the project on [Ko-fi](https://ko-fi.com/skysparkle) — donations pay for the Skysparkle server and the time spent on the apps.
|
||||
|
||||
<a href="https://ko-fi.com/skysparkle"><img src="https://ko-fi.com/img/githubbutton_sm.svg" alt="Support me on Ko-fi"></a>
|
||||
|
||||
## 📄 License
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
plugins {
|
||||
id("com.android.application")
|
||||
|
||||
id("org.jetbrains.kotlin.plugin.compose")
|
||||
alias(libs.plugins.android.application)
|
||||
alias(libs.plugins.kotlin.compose)
|
||||
}
|
||||
|
||||
android {
|
||||
@@ -13,8 +12,8 @@ android {
|
||||
applicationId = "cc.skysparkle.matewave"
|
||||
minSdk = 26
|
||||
targetSdk = 36
|
||||
versionCode = 3
|
||||
versionName = "1.0.45"
|
||||
versionCode = 12
|
||||
versionName = "1.0.52"
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
@@ -34,6 +33,15 @@ android {
|
||||
compose = true
|
||||
}
|
||||
|
||||
androidResources {
|
||||
// The app's languages, plus the regional variants libraries ship for them.
|
||||
localeFilters += listOf(
|
||||
"en", "en-rAU", "en-rCA", "en-rGB", "en-rIN",
|
||||
"ru", "de", "ja", "lt",
|
||||
"zh", "zh-rCN", "zh-rHK", "zh-rTW"
|
||||
)
|
||||
}
|
||||
|
||||
testOptions {
|
||||
unitTests.isReturnDefaultValues = true
|
||||
}
|
||||
@@ -62,21 +70,35 @@ android {
|
||||
}
|
||||
}
|
||||
|
||||
androidComponents {
|
||||
// Release APKs leave out files only build and debug tools read: library version markers,
|
||||
// Kotlin reflection metadata and the coroutines debug agent.
|
||||
onVariants(selector().withBuildType("release")) { variant ->
|
||||
variant.packaging.resources.excludes.addAll(
|
||||
"/META-INF/*.version",
|
||||
"/META-INF/*.kotlin_module",
|
||||
"/kotlin/**",
|
||||
"/kotlin-tooling-metadata.json",
|
||||
"/DebugProbesKt.bin"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(platform("androidx.compose:compose-bom:2026.09.00"))
|
||||
implementation("androidx.compose.material3:material3")
|
||||
implementation("androidx.compose.ui:ui")
|
||||
implementation("androidx.activity:activity-compose:1.13.0")
|
||||
implementation(platform(libs.androidx.compose.bom))
|
||||
implementation(libs.androidx.compose.material3)
|
||||
implementation(libs.androidx.compose.ui)
|
||||
implementation(libs.androidx.activity.compose)
|
||||
|
||||
implementation("androidx.core:core-ktx:1.18.0")
|
||||
implementation("androidx.navigation:navigation-compose:2.9.7")
|
||||
implementation(libs.androidx.core.ktx)
|
||||
implementation(libs.androidx.navigation.compose)
|
||||
|
||||
implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.11.0")
|
||||
implementation(libs.androidx.lifecycle.viewmodel.compose)
|
||||
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.11.0")
|
||||
implementation(libs.kotlinx.coroutines.android)
|
||||
|
||||
implementation("com.google.zxing:core:3.5.4")
|
||||
implementation(libs.zxing.core)
|
||||
|
||||
testImplementation("junit:junit:4.13.2")
|
||||
testImplementation("org.json:json:20240303")
|
||||
testImplementation(libs.junit)
|
||||
testImplementation(libs.org.json)
|
||||
}
|
||||
|
||||
@@ -2,3 +2,9 @@
|
||||
# reflection. Only keep line numbers so release crash reports stay readable.
|
||||
-keepattributes SourceFile,LineNumberTable
|
||||
-renamesourcefileattribute SourceFile
|
||||
|
||||
# Debug and verbose logging (NetworkLog included) is stripped from release builds.
|
||||
-assumenosideeffects class android.util.Log {
|
||||
public static int d(...);
|
||||
public static int v(...);
|
||||
}
|
||||
|
||||
@@ -25,7 +25,6 @@
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE" />
|
||||
|
||||
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
|
||||
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
|
||||
|
||||
<uses-feature android:name="android.hardware.bluetooth" android:required="false" />
|
||||
<uses-feature android:name="android.hardware.bluetooth_le" android:required="false" />
|
||||
@@ -37,6 +36,7 @@
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:roundIcon="@mipmap/ic_launcher_round"
|
||||
android:label="@string/app_title"
|
||||
android:localeConfig="@xml/locales_config"
|
||||
android:networkSecurityConfig="@xml/network_security_config"
|
||||
android:theme="@android:style/Theme.Material.NoActionBar"
|
||||
android:supportsRtl="true">
|
||||
@@ -45,7 +45,7 @@
|
||||
android:name=".MainActivity"
|
||||
android:exported="true"
|
||||
android:launchMode="singleTop"
|
||||
android:screenOrientation="portrait">
|
||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboardHidden">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package cc.skysparkle.matewave
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
|
||||
import android.os.Build
|
||||
@@ -12,7 +11,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
|
||||
@@ -55,7 +56,7 @@ class MainActivity : ComponentActivity() {
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
// The app has one dark look: light system bar icons over the background photo.
|
||||
// The app has one dark look: light system bar icons over the dark backdrop.
|
||||
enableEdgeToEdge(
|
||||
statusBarStyle = SystemBarStyle.dark(android.graphics.Color.TRANSPARENT),
|
||||
navigationBarStyle = SystemBarStyle.dark(android.graphics.Color.TRANSPARENT)
|
||||
@@ -67,20 +68,18 @@ class MainActivity : ComponentActivity() {
|
||||
val appContext = applicationContext
|
||||
kotlin.concurrent.thread(name = "warmup", isDaemon = true) {
|
||||
runCatching { cc.skysparkle.matewave.data.FriendsStore.preload() }
|
||||
// Decoded here, the pieces are ready before the first board is shown.
|
||||
runCatching { cc.skysparkle.matewave.ui.components.PieceImages.get(appContext) }
|
||||
runCatching { cc.skysparkle.matewave.puzzles.PuzzleRepository.load(appContext) }
|
||||
}
|
||||
|
||||
cc.skysparkle.matewave.ui.theme.AppThemeState.load(this)
|
||||
setContent {
|
||||
MatewaveTheme {
|
||||
androidx.compose.foundation.layout.Box(
|
||||
modifier = androidx.compose.ui.Modifier.fillMaxSize()
|
||||
) {
|
||||
cc.skysparkle.matewave.ui.components.AppBackgroundImage()
|
||||
androidx.compose.foundation.layout.Box(
|
||||
modifier = androidx.compose.ui.Modifier
|
||||
.fillMaxSize()
|
||||
.background(cc.skysparkle.matewave.ui.theme.PhotoScrim)
|
||||
)
|
||||
cc.skysparkle.matewave.ui.components.AppBackdrop()
|
||||
AppNavHost()
|
||||
}
|
||||
}
|
||||
@@ -110,6 +109,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)
|
||||
@@ -118,9 +121,12 @@ private fun AppNavHost() {
|
||||
onDispose { PresenceHub.release(context) }
|
||||
}
|
||||
|
||||
// New players start with the guide; everyone else goes straight to the menu
|
||||
val startRoute = remember { if (cc.skysparkle.matewave.ui.screens.Onboarding.needed(context)) "onboarding" else "menu" }
|
||||
|
||||
NavHost(
|
||||
navController = navController,
|
||||
startDestination = "menu",
|
||||
startDestination = startRoute,
|
||||
enterTransition = {
|
||||
if (isTabSwitch(initialState.destination.route, targetState.destination.route)) fadeThroughIn()
|
||||
else sharedAxisIn(forward = true)
|
||||
@@ -138,6 +144,22 @@ private fun AppNavHost() {
|
||||
else sharedAxisOut(forward = false)
|
||||
}
|
||||
) {
|
||||
composable("onboarding") {
|
||||
cc.skysparkle.matewave.ui.screens.OnboardingScreen(
|
||||
replay = false,
|
||||
onDone = {
|
||||
navController.navigate("menu") { popUpTo("onboarding") { inclusive = true } }
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
composable("guide") {
|
||||
cc.skysparkle.matewave.ui.screens.OnboardingScreen(
|
||||
replay = true,
|
||||
onDone = { navController.popBackStack() }
|
||||
)
|
||||
}
|
||||
|
||||
composable("menu") {
|
||||
MainMenuScreen(
|
||||
viewModel = viewModel,
|
||||
@@ -191,7 +213,8 @@ private fun AppNavHost() {
|
||||
onOpenPermissions = { navController.navigate("permissions") },
|
||||
onOpenAppearance = { navController.navigate("appearance") },
|
||||
onOpenLicenses = { navController.navigate("licenses") },
|
||||
onOpenShare = { navController.navigate("shareApk") }
|
||||
onOpenShare = { navController.navigate("shareApk") },
|
||||
onOpenGuide = { navController.navigate("guide") }
|
||||
)
|
||||
}
|
||||
|
||||
@@ -231,6 +254,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 +270,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() },
|
||||
@@ -313,9 +353,12 @@ private fun AppNavHost() {
|
||||
viewModel.startVsPlayerNetwork(transport, PieceColor.WHITE, timeControl, isHost = true)
|
||||
navController.navigate("game")
|
||||
},
|
||||
onJoin = { type, timeControl, targetId ->
|
||||
onJoin = { type, timeControl, targetId, expectedUserId ->
|
||||
val transport = if (type == TransportType.BLUETOOTH) bleTransport else lanTransport
|
||||
viewModel.startVsPlayerNetwork(transport, PieceColor.BLACK, timeControl, isHost = false, targetId = targetId)
|
||||
viewModel.startVsPlayerNetwork(
|
||||
transport, PieceColor.BLACK, timeControl, isHost = false,
|
||||
targetId = targetId, expectedUserId = expectedUserId
|
||||
)
|
||||
navController.navigate("game")
|
||||
},
|
||||
onBack = { navController.popBackStack() }
|
||||
@@ -324,6 +367,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 =
|
||||
|
||||
@@ -19,5 +19,18 @@ class MatewaveApp : Application() {
|
||||
Stats.init(this)
|
||||
GameSaveStore.init(this)
|
||||
Haptics.init(this)
|
||||
|
||||
// Settings files load on a background thread from first use; start them now, so the
|
||||
// first screen finds them in memory instead of waiting for the disk.
|
||||
for (name in EARLY_PREFS) getSharedPreferences(name, MODE_PRIVATE)
|
||||
GameSaveStore.preload()
|
||||
}
|
||||
|
||||
private companion object {
|
||||
/** Settings the home screen and its view models read while starting. */
|
||||
val EARLY_PREFS = arrayOf(
|
||||
"chess_profile_prefs", "chess_friends_prefs", "chess_stats_prefs", "chess_sound_prefs",
|
||||
"last_game_setup", "presence_settings", "opening_srs"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ import cc.skysparkle.matewave.engine.ChessEngine
|
||||
import cc.skysparkle.matewave.engine.Move
|
||||
import cc.skysparkle.matewave.engine.Notation
|
||||
import cc.skysparkle.matewave.engine.PieceColor
|
||||
import cc.skysparkle.matewave.engine.PieceType
|
||||
import cc.skysparkle.matewave.engine.Position
|
||||
|
||||
enum class AiDifficulty(val maxDepth: Int, val timeBudgetMs: Long, val noiseCp: Int) {
|
||||
EASY(2, 400, 150),
|
||||
@@ -19,16 +19,13 @@ enum class AiDifficulty(val maxDepth: Int, val timeBudgetMs: Long, val noiseCp:
|
||||
* quiescence search over captures. The time budget per move is derived from the
|
||||
* remaining clock, and lower difficulty levels add Gaussian noise at the root so the
|
||||
* AI does not play the same game every time (mates are never randomized away).
|
||||
*
|
||||
* The search makes and takes back moves on one [Position] and keeps moves in reused int
|
||||
* buffers, so it allocates nothing per node.
|
||||
*/
|
||||
object ChessAI {
|
||||
private fun valueOf(type: PieceType): Int = when (type) {
|
||||
PieceType.PAWN -> 100
|
||||
PieceType.KNIGHT -> 320
|
||||
PieceType.BISHOP -> 330
|
||||
PieceType.ROOK -> 500
|
||||
PieceType.QUEEN -> 900
|
||||
PieceType.KING -> 20000
|
||||
}
|
||||
/** Piece values by [Position] piece type: pawn, knight, bishop, rook, queen, king. */
|
||||
private val VALUE = intArrayOf(0, 100, 320, 330, 500, 900, 20000)
|
||||
|
||||
private const val MATE = 100_000
|
||||
|
||||
@@ -109,139 +106,225 @@ object ChessAI {
|
||||
-50, -40, -30, -20, -20, -30, -40, -50
|
||||
)
|
||||
|
||||
internal fun evaluate(board: Board): Int {
|
||||
var nonPawnMaterial = 0
|
||||
for (sq in 0 until 64) {
|
||||
val p = board.squares[sq] ?: continue
|
||||
if (p.type != PieceType.PAWN && p.type != PieceType.KING) nonPawnMaterial += valueOf(p.type)
|
||||
}
|
||||
val endgame = nonPawnMaterial <= 1_300
|
||||
// Material plus table bonus per piece code and square, signed from White's side. Kings are
|
||||
// kept apart because their table depends on the phase.
|
||||
private val PIECE_SQUARE = IntArray(16 * 64)
|
||||
private val KING_MIDDLE = IntArray(16 * 64)
|
||||
private val KING_END = IntArray(16 * 64)
|
||||
private val NON_PAWN_VALUE = IntArray(16)
|
||||
|
||||
var score = 0
|
||||
for (sq in 0 until 64) {
|
||||
val piece = board.squares[sq] ?: continue
|
||||
val white = piece.color == PieceColor.WHITE
|
||||
val idx = if (white) sq else sq xor 56
|
||||
val positional = when (piece.type) {
|
||||
PieceType.PAWN -> pawnTable[idx]
|
||||
PieceType.KNIGHT -> knightTable[idx]
|
||||
PieceType.BISHOP -> bishopTable[idx]
|
||||
PieceType.ROOK -> rookTable[idx]
|
||||
PieceType.QUEEN -> queenTable[idx]
|
||||
PieceType.KING -> if (endgame) kingEndTable[idx] else kingMiddleTable[idx]
|
||||
init {
|
||||
for (color in Position.WHITE..Position.BLACK) for (type in Position.PAWN..Position.KING) {
|
||||
val code = Position.code(type, color)
|
||||
val sign = if (color == Position.WHITE) 1 else -1
|
||||
if (type != Position.PAWN && type != Position.KING) NON_PAWN_VALUE[code] = VALUE[type]
|
||||
for (sq in 0 until 64) {
|
||||
val idx = if (color == Position.WHITE) sq else sq xor 56
|
||||
val i = code * 64 + sq
|
||||
when (type) {
|
||||
Position.PAWN -> PIECE_SQUARE[i] = sign * (VALUE[type] + pawnTable[idx])
|
||||
Position.KNIGHT -> PIECE_SQUARE[i] = sign * (VALUE[type] + knightTable[idx])
|
||||
Position.BISHOP -> PIECE_SQUARE[i] = sign * (VALUE[type] + bishopTable[idx])
|
||||
Position.ROOK -> PIECE_SQUARE[i] = sign * (VALUE[type] + rookTable[idx])
|
||||
Position.QUEEN -> PIECE_SQUARE[i] = sign * (VALUE[type] + queenTable[idx])
|
||||
else -> {
|
||||
KING_MIDDLE[i] = sign * (VALUE[type] + kingMiddleTable[idx])
|
||||
KING_END[i] = sign * (VALUE[type] + kingEndTable[idx])
|
||||
}
|
||||
}
|
||||
}
|
||||
val value = valueOf(piece.type) + positional
|
||||
score += if (white) value else -value
|
||||
}
|
||||
return score
|
||||
}
|
||||
|
||||
private fun moveScore(board: Board, m: Move): Int {
|
||||
/** Score from White's side; the endgame king table applies with little non-pawn material. */
|
||||
private fun evaluate(position: Position): Int {
|
||||
val squares = position.squares
|
||||
var score = 0
|
||||
val victim = board.squares[m.to]
|
||||
if (victim != null) {
|
||||
val attacker = board.squares[m.from]
|
||||
score = valueOf(victim.type) * 16 - (if (attacker != null) valueOf(attacker.type) / 100 else 0)
|
||||
} else if (m.isEnPassant) {
|
||||
score = valueOf(PieceType.PAWN) * 16
|
||||
var nonPawnMaterial = 0
|
||||
var kingMiddle = 0
|
||||
var kingEnd = 0
|
||||
for (sq in 0 until 64) {
|
||||
val code = squares[sq]
|
||||
if (code == 0) continue
|
||||
val i = code * 64 + sq
|
||||
if (Position.typeOf(code) == Position.KING) {
|
||||
kingMiddle += KING_MIDDLE[i]
|
||||
kingEnd += KING_END[i]
|
||||
} else {
|
||||
score += PIECE_SQUARE[i]
|
||||
nonPawnMaterial += NON_PAWN_VALUE[code]
|
||||
}
|
||||
}
|
||||
if (m.promotion == PieceType.QUEEN) score += 800
|
||||
return score + if (nonPawnMaterial <= 1_300) kingEnd else kingMiddle
|
||||
}
|
||||
|
||||
private fun moveScore(squares: IntArray, move: Int): Int {
|
||||
var score = 0
|
||||
val victim = squares[Position.moveTo(move)]
|
||||
if (victim != 0) {
|
||||
val attacker = squares[Position.moveFrom(move)]
|
||||
score = VALUE[Position.typeOf(victim)] * 16 -
|
||||
(if (attacker != 0) VALUE[Position.typeOf(attacker)] / 100 else 0)
|
||||
} else if (Position.isEnPassant(move)) {
|
||||
score = VALUE[Position.PAWN] * 16
|
||||
}
|
||||
if (Position.promotionOf(move) == Position.QUEEN) score += 800
|
||||
return score
|
||||
}
|
||||
|
||||
internal fun orderMoves(board: Board, moves: List<Move>): List<Move> =
|
||||
moves.sortedByDescending { m -> moveScore(board, m) }
|
||||
|
||||
internal fun isTactical(board: Board, m: Move): Boolean =
|
||||
board.squares[m.to] != null || m.isEnPassant || m.promotion != null
|
||||
|
||||
private class Search(private val deadline: Long, val history: Set<String>) {
|
||||
private class Search(
|
||||
private val position: Position,
|
||||
private val deadline: Long,
|
||||
private val history: Set<String>,
|
||||
/** Sorted [Position.keyHash] values of [history]. */
|
||||
private val historyHashes: LongArray,
|
||||
private val isCancelled: () -> Boolean
|
||||
) {
|
||||
private var nodes = 0
|
||||
var timedOut = false
|
||||
private set
|
||||
|
||||
fun timeUp(): Boolean {
|
||||
// Move stack: each node uses the slots from [top] on and frees them when it returns.
|
||||
private var moves = IntArray(Position.MAX_MOVES * 16)
|
||||
private var scores = IntArray(Position.MAX_MOVES * 16)
|
||||
private var top = 0
|
||||
|
||||
private fun timeUp(): Boolean {
|
||||
if (timedOut) return true
|
||||
nodes++
|
||||
if ((nodes and 1023) == 0 && System.currentTimeMillis() >= deadline) timedOut = true
|
||||
if ((nodes and 1023) == 0 && (System.currentTimeMillis() >= deadline || isCancelled())) timedOut = true
|
||||
return timedOut
|
||||
}
|
||||
}
|
||||
|
||||
private fun quiesce(
|
||||
board: Board, alphaIn: Int, betaIn: Int, maximizing: Boolean, qDepth: Int, search: Search
|
||||
): Int {
|
||||
val standPat = evaluate(board)
|
||||
if (search.timeUp() || qDepth == 0) return standPat
|
||||
var alpha = alphaIn
|
||||
var beta = betaIn
|
||||
if (maximizing) {
|
||||
if (standPat >= beta) return standPat
|
||||
if (standPat > alpha) alpha = standPat
|
||||
} else {
|
||||
if (standPat <= alpha) return standPat
|
||||
if (standPat < beta) beta = standPat
|
||||
/**
|
||||
* Generates the moves from [start] and orders them by [moveScore], best first and stable,
|
||||
* as sorting the list of legal moves would.
|
||||
*/
|
||||
private fun generateOrdered(start: Int, tacticalOnly: Boolean): Int {
|
||||
if (start + Position.MAX_MOVES > moves.size) {
|
||||
moves = moves.copyOf(moves.size * 2)
|
||||
scores = scores.copyOf(scores.size * 2)
|
||||
}
|
||||
val moves = moves
|
||||
val scores = scores
|
||||
val end = position.generate(moves, start, tacticalOnly)
|
||||
for (i in start until end) scores[i] = moveScore(position.squares, moves[i])
|
||||
for (i in start + 1 until end) {
|
||||
val move = moves[i]
|
||||
val score = scores[i]
|
||||
var j = i - 1
|
||||
while (j >= start && scores[j] < score) {
|
||||
moves[j + 1] = moves[j]
|
||||
scores[j + 1] = scores[j]
|
||||
j--
|
||||
}
|
||||
moves[j + 1] = move
|
||||
scores[j + 1] = score
|
||||
}
|
||||
return end
|
||||
}
|
||||
val captures = ChessEngine.legalMoves(board).filter { isTactical(board, it) }
|
||||
if (captures.isEmpty()) return standPat
|
||||
var best = standPat
|
||||
for (m in orderMoves(board, captures)) {
|
||||
val value = quiesce(ChessEngine.applyMove(board, m), alpha, beta, !maximizing, qDepth - 1, search)
|
||||
|
||||
/** Whether the position occurred in the game before the search started. */
|
||||
private fun isRepetition(): Boolean {
|
||||
if (historyHashes.isEmpty() || historyHashes.binarySearch(position.keyHash()) < 0) return false
|
||||
return Notation.positionKey(position.toBoard()) in history
|
||||
}
|
||||
|
||||
private fun quiesce(alphaIn: Int, betaIn: Int, maximizing: Boolean, qDepth: Int): Int {
|
||||
val standPat = evaluate(position)
|
||||
if (timeUp() || qDepth == 0) return standPat
|
||||
var alpha = alphaIn
|
||||
var beta = betaIn
|
||||
if (maximizing) {
|
||||
if (value > best) best = value
|
||||
if (value > alpha) alpha = value
|
||||
if (standPat >= beta) return standPat
|
||||
if (standPat > alpha) alpha = standPat
|
||||
} else {
|
||||
if (value < best) best = value
|
||||
if (value < beta) beta = value
|
||||
if (standPat <= alpha) return standPat
|
||||
if (standPat < beta) beta = standPat
|
||||
}
|
||||
if (beta <= alpha || search.timedOut) break
|
||||
val start = top
|
||||
val end = generateOrdered(start, tacticalOnly = true)
|
||||
top = end
|
||||
var best = standPat
|
||||
for (i in start until end) {
|
||||
val move = moves[i]
|
||||
position.make(move)
|
||||
if (!position.moverKingSafe()) {
|
||||
position.unmake(move)
|
||||
continue
|
||||
}
|
||||
val value = quiesce(alpha, beta, !maximizing, qDepth - 1)
|
||||
position.unmake(move)
|
||||
if (maximizing) {
|
||||
if (value > best) best = value
|
||||
if (value > alpha) alpha = value
|
||||
} else {
|
||||
if (value < best) best = value
|
||||
if (value < beta) beta = value
|
||||
}
|
||||
if (beta <= alpha || timedOut) break
|
||||
}
|
||||
top = start
|
||||
return best
|
||||
}
|
||||
|
||||
fun minimax(depth: Int, alphaIn: Int, betaIn: Int, maximizing: Boolean, ply: Int): Int {
|
||||
if (timeUp()) return evaluate(position)
|
||||
var alpha = alphaIn
|
||||
var beta = betaIn
|
||||
|
||||
if (ply in 1..2 && isRepetition()) return 0
|
||||
|
||||
if (position.halfmove >= 100 || position.isDeadPosition()) return 0
|
||||
|
||||
val inCheck = position.inCheck()
|
||||
if (depth <= 0 && !inCheck) return quiesce(alpha, beta, maximizing, QUIESCENCE_DEPTH)
|
||||
|
||||
val nextDepth = if (depth <= 0) 0 else depth - 1
|
||||
|
||||
val start = top
|
||||
val end = generateOrdered(start, tacticalOnly = false)
|
||||
top = end
|
||||
var legal = 0
|
||||
var best = if (maximizing) Int.MIN_VALUE else Int.MAX_VALUE
|
||||
for (i in start until end) {
|
||||
val move = moves[i]
|
||||
position.make(move)
|
||||
if (!position.moverKingSafe()) {
|
||||
position.unmake(move)
|
||||
continue
|
||||
}
|
||||
legal++
|
||||
val value = minimax(nextDepth, alpha, beta, !maximizing, ply + 1)
|
||||
position.unmake(move)
|
||||
if (maximizing) {
|
||||
best = maxOf(best, value)
|
||||
alpha = maxOf(alpha, value)
|
||||
} else {
|
||||
best = minOf(best, value)
|
||||
beta = minOf(beta, value)
|
||||
}
|
||||
if (beta <= alpha || timedOut) break
|
||||
}
|
||||
top = start
|
||||
|
||||
if (legal == 0) {
|
||||
return if (inCheck) {
|
||||
if (maximizing) -MATE + ply else MATE - ply
|
||||
} else 0
|
||||
}
|
||||
return best
|
||||
}
|
||||
return best
|
||||
}
|
||||
|
||||
private fun minimax(
|
||||
board: Board, depth: Int, alphaIn: Int, betaIn: Int, maximizing: Boolean, ply: Int, search: Search
|
||||
): Int {
|
||||
if (search.timeUp()) return evaluate(board)
|
||||
var alpha = alphaIn
|
||||
var beta = betaIn
|
||||
|
||||
if (ply in 1..2 && Notation.positionKey(board) in search.history) return 0
|
||||
|
||||
if (board.halfmoveClock >= 100 || ChessEngine.isDeadPosition(board)) return 0
|
||||
|
||||
val inCheck = ChessEngine.isInCheck(board, board.sideToMove)
|
||||
if (depth <= 0 && !inCheck) return quiesce(board, alpha, beta, maximizing, QUIESCENCE_DEPTH, search)
|
||||
|
||||
val moves = ChessEngine.legalMoves(board)
|
||||
if (moves.isEmpty()) {
|
||||
return if (inCheck) {
|
||||
if (maximizing) -MATE + ply else MATE - ply
|
||||
} else 0
|
||||
}
|
||||
|
||||
val nextDepth = if (depth <= 0) 0 else depth - 1
|
||||
|
||||
val ordered = orderMoves(board, moves)
|
||||
if (maximizing) {
|
||||
var best = Int.MIN_VALUE
|
||||
for (m in ordered) {
|
||||
val value = minimax(ChessEngine.applyMove(board, m), nextDepth, alpha, beta, false, ply + 1, search)
|
||||
best = maxOf(best, value)
|
||||
alpha = maxOf(alpha, value)
|
||||
if (beta <= alpha || search.timedOut) break
|
||||
}
|
||||
return best
|
||||
} else {
|
||||
var best = Int.MAX_VALUE
|
||||
for (m in ordered) {
|
||||
val value = minimax(ChessEngine.applyMove(board, m), nextDepth, alpha, beta, true, ply + 1, search)
|
||||
best = minOf(best, value)
|
||||
beta = minOf(beta, value)
|
||||
if (beta <= alpha || search.timedOut) break
|
||||
}
|
||||
return best
|
||||
private fun hashesOf(history: Set<String>): LongArray {
|
||||
val hashes = LongArray(history.size)
|
||||
var n = 0
|
||||
for (key in history) {
|
||||
val board = runCatching { Board.fromFen(key) }.getOrNull() ?: continue
|
||||
hashes[n++] = Position(board).keyHash()
|
||||
}
|
||||
return hashes.copyOf(n).also { it.sort() }
|
||||
}
|
||||
|
||||
fun bestMove(
|
||||
@@ -250,7 +333,9 @@ object ChessAI {
|
||||
history: Set<String> = emptySet(),
|
||||
clockMillis: Long? = null,
|
||||
incrementMillis: Long = 0L,
|
||||
random: java.util.Random = java.util.Random()
|
||||
random: java.util.Random = java.util.Random(),
|
||||
/** Polled during the search; returning true stops it early. */
|
||||
isCancelled: () -> Boolean = { false }
|
||||
): Move? {
|
||||
val rootMoves = ChessEngine.legalMoves(board)
|
||||
if (rootMoves.isEmpty()) return null
|
||||
@@ -263,9 +348,10 @@ object ChessAI {
|
||||
}
|
||||
|
||||
val maximizing = board.sideToMove == PieceColor.WHITE
|
||||
val search = Search(System.currentTimeMillis() + budget, history)
|
||||
val position = Position(board)
|
||||
val search = Search(position, System.currentTimeMillis() + budget, history, hashesOf(history), isCancelled)
|
||||
|
||||
var order = orderMoves(board, rootMoves)
|
||||
var order = rootMoves.sortedByDescending { moveScore(position.squares, Position.encode(it)) }
|
||||
var lastScored: List<Pair<Move, Int>> = emptyList()
|
||||
|
||||
var depth = 1
|
||||
@@ -278,11 +364,13 @@ object ChessAI {
|
||||
var completed = true
|
||||
|
||||
for (m in order) {
|
||||
val next = ChessEngine.applyMove(board, m)
|
||||
val move = Position.encode(m)
|
||||
position.make(move)
|
||||
|
||||
val a = if (difficulty.noiseCp > 0) Int.MIN_VALUE else alpha
|
||||
val b = if (difficulty.noiseCp > 0) Int.MAX_VALUE else beta
|
||||
val value = minimax(next, depth - 1, a, b, !maximizing, 1, search)
|
||||
val value = search.minimax(depth - 1, a, b, !maximizing, 1)
|
||||
position.unmake(move)
|
||||
|
||||
if (search.timedOut) { completed = false; break }
|
||||
scored.add(m to value)
|
||||
|
||||
@@ -143,7 +143,8 @@ object SoundManager {
|
||||
musicEnabled = prefs.getBoolean(KEY_MUSIC, false)
|
||||
sfxEnabled = prefs.getBoolean(KEY_SFX, true)
|
||||
|
||||
ensureSoundPool(ctx)
|
||||
// Building the pool and opening the sounds takes a while: do it off the main thread.
|
||||
kotlin.concurrent.thread(name = "sound-pool", isDaemon = true) { soundPool = createSoundPool(ctx) }
|
||||
|
||||
if (musicEnabled) {
|
||||
mainHandler.postDelayed({ if (musicEnabled) startRadio() }, RADIO_START_DELAY_MS)
|
||||
@@ -446,12 +447,12 @@ object SoundManager {
|
||||
?.putBoolean(KEY_SFX, enabled)?.apply()
|
||||
}
|
||||
|
||||
private var soundPool: SoundPool? = null
|
||||
/** Set once, after [sfxSoundIds] is filled. */
|
||||
@Volatile private var soundPool: SoundPool? = null
|
||||
private val sfxSoundIds = HashMap<Int, Int>()
|
||||
private val sfxLoaded = HashSet<Int>()
|
||||
|
||||
private fun ensureSoundPool(ctx: Context): SoundPool {
|
||||
soundPool?.let { return it }
|
||||
private fun createSoundPool(ctx: Context): SoundPool {
|
||||
val attributes = AudioAttributes.Builder()
|
||||
.setUsage(AudioAttributes.USAGE_GAME)
|
||||
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
|
||||
@@ -467,14 +468,13 @@ object SoundManager {
|
||||
)) {
|
||||
sfxSoundIds[resId] = pool.load(ctx, resId, 1)
|
||||
}
|
||||
soundPool = pool
|
||||
return pool
|
||||
}
|
||||
|
||||
private fun playSfx(resId: Int) {
|
||||
if (!sfxEnabled) return
|
||||
val ctx = appContext ?: return
|
||||
val pool = ensureSoundPool(ctx)
|
||||
// Like a sound still decoding, one asked for before the pool exists is skipped.
|
||||
val pool = soundPool ?: return
|
||||
val soundId = sfxSoundIds[resId] ?: return
|
||||
val ready = synchronized(sfxLoaded) { soundId in sfxLoaded }
|
||||
if (ready) pool.play(soundId, 1f, 1f, 1, 0, 1f)
|
||||
|
||||
@@ -98,6 +98,12 @@ class GameClock(private val timeControl: TimeControl, private val scope: Corouti
|
||||
publish()
|
||||
}
|
||||
|
||||
/** Time left for [side] right now, including the part of the current second already used. */
|
||||
fun remainingMillis(side: PieceColor): Long {
|
||||
account()
|
||||
return if (side == PieceColor.WHITE) whiteLeft else blackLeft
|
||||
}
|
||||
|
||||
fun restore(whiteMillis: Long, blackMillis: Long) {
|
||||
if (unlimited) return
|
||||
account()
|
||||
@@ -106,13 +112,6 @@ class GameClock(private val timeControl: TimeControl, private val scope: Corouti
|
||||
publish()
|
||||
}
|
||||
|
||||
fun pause() {
|
||||
tickJob?.cancel()
|
||||
account()
|
||||
running = null
|
||||
publish()
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
tickJob?.cancel()
|
||||
account()
|
||||
|
||||
@@ -4,6 +4,9 @@ import android.content.ContentValues
|
||||
import android.content.Context
|
||||
import android.database.sqlite.SQLiteDatabase
|
||||
import android.database.sqlite.SQLiteOpenHelper
|
||||
import java.util.concurrent.LinkedBlockingQueue
|
||||
import java.util.concurrent.ThreadPoolExecutor
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
data class SavedGame(
|
||||
val fen: String,
|
||||
@@ -13,11 +16,15 @@ data class SavedGame(
|
||||
val incrementSeconds: Int,
|
||||
val whiteMillis: Long = -1,
|
||||
val blackMillis: Long = -1,
|
||||
/** Moves from the standard start in UCI, space separated; empty for saves made before version 3. */
|
||||
/** Moves from the standard start in UCI, space separated; empty for a game that started elsewhere. */
|
||||
val movesUci: String = ""
|
||||
)
|
||||
|
||||
/** Persists the unfinished game against the AI: moves, position and remaining clock time. */
|
||||
/**
|
||||
* Persists the unfinished game against the AI: moves, position and remaining clock time.
|
||||
* The game is kept in memory once read or saved; the database is written in the background,
|
||||
* in order, so moves never wait for the disk.
|
||||
*/
|
||||
object GameSaveStore {
|
||||
private const val DB_NAME = "chess_save.db"
|
||||
private const val DB_VERSION = 3
|
||||
@@ -25,12 +32,30 @@ object GameSaveStore {
|
||||
|
||||
@Volatile private var helper: DbHelper? = null
|
||||
|
||||
/** One thread at most, so writes keep their order; it ends when idle. */
|
||||
private val io = ThreadPoolExecutor(0, 1, 10, TimeUnit.SECONDS, LinkedBlockingQueue()) { task ->
|
||||
Thread(task, "game-save").apply { isDaemon = true }
|
||||
}
|
||||
|
||||
private val lock = Any()
|
||||
/** Whether [current] matches what is (or is about to be) on disk. */
|
||||
private var known = false
|
||||
private var current: SavedGame? = null
|
||||
|
||||
fun init(context: Context) {
|
||||
if (helper == null) synchronized(this) {
|
||||
if (helper == null) helper = DbHelper(context.applicationContext)
|
||||
}
|
||||
}
|
||||
|
||||
/** Reads the save in the background, so the first screen finds it in memory. */
|
||||
fun preload() {
|
||||
io.execute { load() }
|
||||
}
|
||||
|
||||
/** Whether [load] would return without reading the database. */
|
||||
fun isLoaded(): Boolean = synchronized(lock) { known }
|
||||
|
||||
private class DbHelper(context: Context) : SQLiteOpenHelper(context, DB_NAME, null, DB_VERSION) {
|
||||
override fun onCreate(db: SQLiteDatabase) {
|
||||
db.execSQL(
|
||||
@@ -50,18 +75,19 @@ object GameSaveStore {
|
||||
)
|
||||
}
|
||||
|
||||
// Saves from older versions are not carried over.
|
||||
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
|
||||
if (oldVersion < 2) {
|
||||
db.execSQL("ALTER TABLE $TABLE ADD COLUMN white_ms INTEGER NOT NULL DEFAULT -1")
|
||||
db.execSQL("ALTER TABLE $TABLE ADD COLUMN black_ms INTEGER NOT NULL DEFAULT -1")
|
||||
}
|
||||
if (oldVersion < 3) {
|
||||
db.execSQL("ALTER TABLE $TABLE ADD COLUMN moves TEXT NOT NULL DEFAULT ''")
|
||||
}
|
||||
db.execSQL("DROP TABLE IF EXISTS $TABLE")
|
||||
onCreate(db)
|
||||
}
|
||||
}
|
||||
|
||||
fun save(game: SavedGame) {
|
||||
synchronized(lock) { current = game; known = true }
|
||||
io.execute { write(game) }
|
||||
}
|
||||
|
||||
private fun write(game: SavedGame) {
|
||||
val db = runCatching { helper?.writableDatabase }.getOrNull() ?: return
|
||||
val values = ContentValues().apply {
|
||||
put("id", 1)
|
||||
@@ -77,7 +103,21 @@ object GameSaveStore {
|
||||
runCatching { db.insertWithOnConflict(TABLE, null, values, SQLiteDatabase.CONFLICT_REPLACE) }
|
||||
}
|
||||
|
||||
/** The saved game; the first call reads the database, so make it off the main thread. */
|
||||
fun load(): SavedGame? {
|
||||
synchronized(lock) { if (known) return current }
|
||||
val read = read()
|
||||
synchronized(lock) {
|
||||
// A save or clear made while reading is newer than what was read.
|
||||
if (!known) {
|
||||
current = read
|
||||
known = true
|
||||
}
|
||||
return current
|
||||
}
|
||||
}
|
||||
|
||||
private fun read(): SavedGame? {
|
||||
val db = runCatching { helper?.readableDatabase }.getOrNull() ?: return null
|
||||
return runCatching {
|
||||
db.query(TABLE, null, "id = 1", null, null, null, null).use { cursor ->
|
||||
@@ -97,6 +137,7 @@ object GameSaveStore {
|
||||
}
|
||||
|
||||
fun clear() {
|
||||
runCatching { helper?.writableDatabase?.delete(TABLE, "id = 1", null) }
|
||||
synchronized(lock) { current = null; known = true }
|
||||
io.execute { runCatching { helper?.writableDatabase?.delete(TABLE, "id = 1", null) } }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,8 +2,12 @@ package cc.skysparkle.matewave.data
|
||||
|
||||
import cc.skysparkle.matewave.ai.AiDifficulty
|
||||
import android.content.Context
|
||||
import cc.skysparkle.matewave.network.PeerLimits
|
||||
import cc.skysparkle.matewave.security.toHex
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.security.MessageDigest
|
||||
import kotlin.math.pow
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
@@ -66,8 +70,6 @@ object ProfileStore {
|
||||
prefs()?.edit()?.putString(KEY_AVATAR, base64)?.apply()
|
||||
}
|
||||
|
||||
fun resetAvatarToDefault() = setAvatar(null)
|
||||
|
||||
fun setBackground(base64: String?) {
|
||||
prefs()?.edit()?.putString(KEY_BACKGROUND, base64)?.apply()
|
||||
}
|
||||
@@ -113,6 +115,7 @@ object FriendsStore {
|
||||
private const val PREFS = "chess_friends_prefs"
|
||||
private const val KEY_LIST = "friends_json"
|
||||
private const val MAX_FRIENDS = 30
|
||||
private const val IMAGE_DIR = "friend_images"
|
||||
|
||||
private var appContext: Context? = null
|
||||
|
||||
@@ -127,6 +130,36 @@ object FriendsStore {
|
||||
|
||||
private fun prefs() = appContext?.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||
|
||||
// Avatars and backgrounds live in files, one per image: in the settings XML they made a file
|
||||
// of up to tens of megabytes that was read at start and rewritten on every change.
|
||||
private fun imageDir(): File? = appContext?.let { File(it.filesDir, IMAGE_DIR) }
|
||||
|
||||
private fun imageFile(userId: String, kind: String): File? {
|
||||
val dir = imageDir() ?: return null
|
||||
val digest = MessageDigest.getInstance("SHA-256").digest(userId.toByteArray(Charsets.UTF_8))
|
||||
return File(dir, "${digest.toHex(16)}_$kind")
|
||||
}
|
||||
|
||||
private fun readImage(userId: String, kind: String): String? =
|
||||
imageFile(userId, kind)?.takeIf { it.isFile }?.let { runCatching { it.readText() }.getOrNull() }
|
||||
|
||||
private fun writeImage(userId: String, kind: String, base64: String?) {
|
||||
val file = imageFile(userId, kind) ?: return
|
||||
if (base64 == null) {
|
||||
file.delete()
|
||||
return
|
||||
}
|
||||
runCatching {
|
||||
file.parentFile?.mkdirs()
|
||||
val tmp = File(file.parentFile, file.name + ".tmp")
|
||||
tmp.writeText(base64)
|
||||
if (!tmp.renameTo(file)) {
|
||||
file.delete()
|
||||
tmp.renameTo(file)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun list(): List<FriendEntry> = synchronized(lock) { readAll() }
|
||||
|
||||
private fun readAll(): List<FriendEntry> {
|
||||
@@ -138,15 +171,21 @@ object FriendsStore {
|
||||
return emptyList()
|
||||
}
|
||||
val result = ArrayList<FriendEntry>()
|
||||
var hasInlineImages = false
|
||||
for (i in 0 until arr.length()) {
|
||||
try {
|
||||
val o = arr.getJSONObject(i)
|
||||
val userId = o.optString("uid", "").ifBlank { o.getString("name") }
|
||||
// Older versions kept the images inline; they move to files on the next write.
|
||||
val inlineAvatar = if (o.has("avatar")) o.getString("avatar") else null
|
||||
val inlineBackground = if (o.has("background")) o.getString("background") else null
|
||||
if (inlineAvatar != null || inlineBackground != null) hasInlineImages = true
|
||||
result.add(
|
||||
FriendEntry(
|
||||
userId = o.optString("uid", "").ifBlank { o.getString("name") },
|
||||
userId = userId,
|
||||
name = o.getString("name"),
|
||||
avatarBase64 = if (o.has("avatar")) o.getString("avatar") else null,
|
||||
backgroundBase64 = if (o.has("background")) o.getString("background") else null,
|
||||
avatarBase64 = inlineAvatar ?: if (o.optBoolean("a")) readImage(userId, "a") else null,
|
||||
backgroundBase64 = inlineBackground ?: if (o.optBoolean("b")) readImage(userId, "b") else null,
|
||||
elo = o.optInt("elo", 1200),
|
||||
lastPlayedMs = o.optLong("t", 0),
|
||||
favorite = o.optBoolean("fav", false),
|
||||
@@ -158,24 +197,35 @@ object FriendsStore {
|
||||
}
|
||||
val sorted = result.sortedByDescending { it.lastPlayedMs }
|
||||
cached = sorted
|
||||
if (hasInlineImages) writeAll(sorted, previous = emptyList())
|
||||
return sorted
|
||||
}
|
||||
|
||||
private fun writeAll(entries: List<FriendEntry>) {
|
||||
private fun writeAll(entries: List<FriendEntry>, previous: List<FriendEntry> = readAll()) {
|
||||
val p = prefs() ?: return
|
||||
val before = previous.associateBy { it.userId }
|
||||
val arr = JSONArray()
|
||||
entries.forEach { f ->
|
||||
val old = before[f.userId]
|
||||
// Image files are touched only when the image itself changed.
|
||||
if (old == null || old.avatarBase64 != f.avatarBase64) writeImage(f.userId, "a", f.avatarBase64)
|
||||
if (old == null || old.backgroundBase64 != f.backgroundBase64) writeImage(f.userId, "b", f.backgroundBase64)
|
||||
val o = JSONObject()
|
||||
o.put("uid", f.userId)
|
||||
o.put("name", f.name)
|
||||
if (f.avatarBase64 != null) o.put("avatar", f.avatarBase64)
|
||||
if (f.backgroundBase64 != null) o.put("background", f.backgroundBase64)
|
||||
if (f.avatarBase64 != null) o.put("a", true)
|
||||
if (f.backgroundBase64 != null) o.put("b", true)
|
||||
o.put("elo", f.elo)
|
||||
o.put("t", f.lastPlayedMs)
|
||||
if (f.favorite) o.put("fav", true)
|
||||
if (f.lastSeenMs > 0) o.put("s", f.lastSeenMs)
|
||||
arr.put(o)
|
||||
}
|
||||
val kept = entries.mapTo(HashSet()) { it.userId }
|
||||
previous.filter { it.userId !in kept }.forEach { gone ->
|
||||
writeImage(gone.userId, "a", null)
|
||||
writeImage(gone.userId, "b", null)
|
||||
}
|
||||
p.edit().putString(KEY_LIST, arr.toString()).apply()
|
||||
cached = entries.sortedByDescending { it.lastPlayedMs }
|
||||
}
|
||||
@@ -184,6 +234,11 @@ object FriendsStore {
|
||||
synchronized(lock) { readAll() }
|
||||
}
|
||||
|
||||
// Names and ratings also arrive from presence announcements, so they are bounded here too.
|
||||
private fun cleanName(name: String): String = name.filterNot { it.isISOControl() }.take(PeerLimits.MAX_NAME_CHARS)
|
||||
|
||||
private fun cleanElo(elo: Int): Int = elo.coerceIn(PeerLimits.MIN_ELO, PeerLimits.MAX_ELO)
|
||||
|
||||
fun updateProfile(
|
||||
userId: String,
|
||||
name: String,
|
||||
@@ -194,8 +249,8 @@ object FriendsStore {
|
||||
synchronized(lock) {
|
||||
val existing = readAll().firstOrNull { it.userId == userId } ?: return
|
||||
val updated = existing.copy(
|
||||
name = name.ifBlank { existing.name },
|
||||
elo = if (elo > 0) elo else existing.elo,
|
||||
name = cleanName(name).ifBlank { existing.name },
|
||||
elo = if (elo > 0) cleanElo(elo) else existing.elo,
|
||||
avatarBase64 = avatarBase64 ?: existing.avatarBase64,
|
||||
backgroundBase64 = backgroundBase64 ?: existing.backgroundBase64
|
||||
)
|
||||
@@ -219,12 +274,13 @@ object FriendsStore {
|
||||
backgroundBase64: String? = null
|
||||
): FriendEntry = synchronized(lock) {
|
||||
val existing = readAll().firstOrNull { it.userId == userId }
|
||||
val clean = cleanName(name)
|
||||
val merged = FriendEntry(
|
||||
userId = userId,
|
||||
name = name.ifBlank { existing?.name ?: name },
|
||||
name = clean.ifBlank { existing?.name ?: clean },
|
||||
avatarBase64 = avatarBase64 ?: existing?.avatarBase64,
|
||||
backgroundBase64 = backgroundBase64 ?: existing?.backgroundBase64,
|
||||
elo = if (elo > 0) elo else (existing?.elo ?: 1200),
|
||||
elo = if (elo > 0) cleanElo(elo) else (existing?.elo ?: 1200),
|
||||
lastPlayedMs = System.currentTimeMillis(),
|
||||
favorite = existing?.favorite ?: false,
|
||||
lastSeenMs = existing?.lastSeenMs ?: 0
|
||||
|
||||
@@ -13,8 +13,6 @@ data class Board(
|
||||
) {
|
||||
fun pieceAt(sq: Int): Piece? = squares[sq]
|
||||
|
||||
fun deepCopySquares(): Array<Piece?> = squares.copyOf()
|
||||
|
||||
fun kingSquare(color: PieceColor): Int {
|
||||
for (i in 0 until 64) {
|
||||
val p = squares[i]
|
||||
|
||||
@@ -13,198 +13,8 @@ enum class GameStatus {
|
||||
* repetition, insufficient material).
|
||||
*/
|
||||
object ChessEngine {
|
||||
private fun file(sq: Int) = sq % 8
|
||||
private fun rank(sq: Int) = sq / 8
|
||||
private fun inBounds(f: Int, r: Int) = f in 0..7 && r in 0..7
|
||||
private fun sq(f: Int, r: Int) = r * 8 + f
|
||||
|
||||
private val KNIGHT_DF = intArrayOf(1, 2, 2, 1, -1, -2, -2, -1)
|
||||
private val KNIGHT_DR = intArrayOf(2, 1, -1, -2, -2, -1, 1, 2)
|
||||
private val DIAG_DF = intArrayOf(1, 1, -1, -1)
|
||||
private val DIAG_DR = intArrayOf(1, -1, 1, -1)
|
||||
private val ORTHO_DF = intArrayOf(1, -1, 0, 0)
|
||||
private val ORTHO_DR = intArrayOf(0, 0, 1, -1)
|
||||
private val ALL_DF = intArrayOf(1, -1, 0, 0, 1, 1, -1, -1)
|
||||
private val ALL_DR = intArrayOf(0, 0, 1, -1, 1, -1, 1, -1)
|
||||
private val PAWN_DF = intArrayOf(-1, 1)
|
||||
|
||||
private fun pseudoLegalMoves(board: Board): List<Move> {
|
||||
val moves = ArrayList<Move>(48)
|
||||
for (from in 0 until 64) {
|
||||
val piece = board.squares[from] ?: continue
|
||||
if (piece.color != board.sideToMove) continue
|
||||
when (piece.type) {
|
||||
PieceType.PAWN -> generatePawnMoves(board, from, piece, moves)
|
||||
PieceType.KNIGHT -> generateKnightMoves(board, from, piece, moves)
|
||||
PieceType.BISHOP -> generateSlidingMoves(board, from, piece, moves, DIAG_DF, DIAG_DR)
|
||||
PieceType.ROOK -> generateSlidingMoves(board, from, piece, moves, ORTHO_DF, ORTHO_DR)
|
||||
PieceType.QUEEN -> generateSlidingMoves(board, from, piece, moves, ALL_DF, ALL_DR)
|
||||
PieceType.KING -> generateKingMoves(board, from, piece, moves)
|
||||
}
|
||||
}
|
||||
return moves
|
||||
}
|
||||
|
||||
private fun generatePawnMoves(board: Board, from: Int, piece: Piece, out: MutableList<Move>) {
|
||||
val dir = if (piece.color == PieceColor.WHITE) 1 else -1
|
||||
val startRank = if (piece.color == PieceColor.WHITE) 1 else 6
|
||||
val promoRank = if (piece.color == PieceColor.WHITE) 7 else 0
|
||||
val f = file(from); val r = rank(from)
|
||||
|
||||
val oneR = r + dir
|
||||
if (inBounds(f, oneR) && board.squares[sq(f, oneR)] == null) {
|
||||
addPawnMoveOrPromotion(from, sq(f, oneR), oneR, promoRank, out)
|
||||
val twoR = r + 2 * dir
|
||||
if (r == startRank && board.squares[sq(f, twoR)] == null) {
|
||||
out.add(Move(from, sq(f, twoR)))
|
||||
}
|
||||
}
|
||||
for (df in PAWN_DF) {
|
||||
val nf = f + df; val nr = r + dir
|
||||
if (!inBounds(nf, nr)) continue
|
||||
val target = sq(nf, nr)
|
||||
val targetPiece = board.squares[target]
|
||||
if (targetPiece != null && targetPiece.color != piece.color) {
|
||||
addPawnMoveOrPromotion(from, target, nr, promoRank, out)
|
||||
} else if (target == board.enPassantTarget) {
|
||||
out.add(Move(from, target, isEnPassant = true))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun addPawnMoveOrPromotion(from: Int, to: Int, toRank: Int, promoRank: Int, out: MutableList<Move>) {
|
||||
if (toRank == promoRank) {
|
||||
out.add(Move(from, to, promotion = PieceType.QUEEN))
|
||||
out.add(Move(from, to, promotion = PieceType.ROOK))
|
||||
out.add(Move(from, to, promotion = PieceType.BISHOP))
|
||||
out.add(Move(from, to, promotion = PieceType.KNIGHT))
|
||||
} else {
|
||||
out.add(Move(from, to))
|
||||
}
|
||||
}
|
||||
|
||||
private fun generateKnightMoves(board: Board, from: Int, piece: Piece, out: MutableList<Move>) {
|
||||
val f = file(from); val r = rank(from)
|
||||
for (i in 0 until 8) {
|
||||
val nf = f + KNIGHT_DF[i]; val nr = r + KNIGHT_DR[i]
|
||||
if (!inBounds(nf, nr)) continue
|
||||
val target = sq(nf, nr)
|
||||
val targetPiece = board.squares[target]
|
||||
if (targetPiece == null || targetPiece.color != piece.color) out.add(Move(from, target))
|
||||
}
|
||||
}
|
||||
|
||||
private fun generateSlidingMoves(
|
||||
board: Board, from: Int, piece: Piece, out: MutableList<Move>, dfs: IntArray, drs: IntArray
|
||||
) {
|
||||
val f = file(from); val r = rank(from)
|
||||
for (i in dfs.indices) {
|
||||
val df = dfs[i]; val dr = drs[i]
|
||||
var nf = f + df; var nr = r + dr
|
||||
while (inBounds(nf, nr)) {
|
||||
val target = sq(nf, nr)
|
||||
val targetPiece = board.squares[target]
|
||||
if (targetPiece == null) {
|
||||
out.add(Move(from, target))
|
||||
} else {
|
||||
if (targetPiece.color != piece.color) out.add(Move(from, target))
|
||||
break
|
||||
}
|
||||
nf += df; nr += dr
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun generateKingMoves(board: Board, from: Int, piece: Piece, out: MutableList<Move>) {
|
||||
val f = file(from); val r = rank(from)
|
||||
for (df in -1..1) for (dr in -1..1) {
|
||||
if (df == 0 && dr == 0) continue
|
||||
val nf = f + df; val nr = r + dr
|
||||
if (!inBounds(nf, nr)) continue
|
||||
val target = sq(nf, nr)
|
||||
val targetPiece = board.squares[target]
|
||||
if (targetPiece == null || targetPiece.color != piece.color) out.add(Move(from, target))
|
||||
}
|
||||
val backRank = if (piece.color == PieceColor.WHITE) 0 else 7
|
||||
if (from == sq(4, backRank)) {
|
||||
val ownRook = Piece(PieceType.ROOK, piece.color)
|
||||
val kingSide = (if (piece.color == PieceColor.WHITE) board.whiteKingSideCastle else board.blackKingSideCastle) &&
|
||||
board.squares[sq(7, backRank)] == ownRook
|
||||
val queenSide = (if (piece.color == PieceColor.WHITE) board.whiteQueenSideCastle else board.blackQueenSideCastle) &&
|
||||
board.squares[sq(0, backRank)] == ownRook
|
||||
val enemy = piece.color.opposite()
|
||||
if (kingSide &&
|
||||
board.squares[sq(5, backRank)] == null && board.squares[sq(6, backRank)] == null &&
|
||||
!isSquareAttacked(board, sq(4, backRank), enemy) &&
|
||||
!isSquareAttacked(board, sq(5, backRank), enemy) &&
|
||||
!isSquareAttacked(board, sq(6, backRank), enemy)
|
||||
) {
|
||||
out.add(Move(from, sq(6, backRank), isCastleKingSide = true))
|
||||
}
|
||||
if (queenSide &&
|
||||
board.squares[sq(3, backRank)] == null && board.squares[sq(2, backRank)] == null && board.squares[sq(1, backRank)] == null &&
|
||||
!isSquareAttacked(board, sq(4, backRank), enemy) &&
|
||||
!isSquareAttacked(board, sq(3, backRank), enemy) &&
|
||||
!isSquareAttacked(board, sq(2, backRank), enemy)
|
||||
) {
|
||||
out.add(Move(from, sq(2, backRank), isCastleQueenSide = true))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun isSquareAttacked(board: Board, target: Int, byColor: PieceColor): Boolean =
|
||||
attacked(board.squares, target, byColor)
|
||||
|
||||
private fun attacked(squares: Array<Piece?>, target: Int, byColor: PieceColor): Boolean {
|
||||
val tf = file(target); val tr = rank(target)
|
||||
val pawnDir = if (byColor == PieceColor.WHITE) -1 else 1
|
||||
for (df in PAWN_DF) {
|
||||
val f = tf + df; val r = tr + pawnDir
|
||||
if (inBounds(f, r)) {
|
||||
val p = squares[sq(f, r)]
|
||||
if (p != null && p.color == byColor && p.type == PieceType.PAWN) return true
|
||||
}
|
||||
}
|
||||
for (i in 0 until 8) {
|
||||
val f = tf + KNIGHT_DF[i]; val r = tr + KNIGHT_DR[i]
|
||||
if (inBounds(f, r)) {
|
||||
val p = squares[sq(f, r)]
|
||||
if (p != null && p.color == byColor && p.type == PieceType.KNIGHT) return true
|
||||
}
|
||||
}
|
||||
for (i in 0 until 8) {
|
||||
val f = tf + ALL_DF[i]; val r = tr + ALL_DR[i]
|
||||
if (inBounds(f, r)) {
|
||||
val p = squares[sq(f, r)]
|
||||
if (p != null && p.color == byColor && p.type == PieceType.KING) return true
|
||||
}
|
||||
}
|
||||
for (i in 0 until 4) {
|
||||
val df = DIAG_DF[i]; val dr = DIAG_DR[i]
|
||||
var f = tf + df; var r = tr + dr
|
||||
while (inBounds(f, r)) {
|
||||
val p = squares[sq(f, r)]
|
||||
if (p != null) {
|
||||
if (p.color == byColor && (p.type == PieceType.BISHOP || p.type == PieceType.QUEEN)) return true
|
||||
break
|
||||
}
|
||||
f += df; r += dr
|
||||
}
|
||||
}
|
||||
for (i in 0 until 4) {
|
||||
val df = ORTHO_DF[i]; val dr = ORTHO_DR[i]
|
||||
var f = tf + df; var r = tr + dr
|
||||
while (inBounds(f, r)) {
|
||||
val p = squares[sq(f, r)]
|
||||
if (p != null) {
|
||||
if (p.color == byColor && (p.type == PieceType.ROOK || p.type == PieceType.QUEEN)) return true
|
||||
break
|
||||
}
|
||||
f += df; r += dr
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
Position(board).isAttacked(target, byColor.ordinal)
|
||||
|
||||
fun isInCheck(board: Board, color: PieceColor): Boolean {
|
||||
val kingSq = board.kingSquare(color)
|
||||
@@ -212,54 +22,17 @@ object ChessEngine {
|
||||
return isSquareAttacked(board, kingSq, color.opposite())
|
||||
}
|
||||
|
||||
/** Square of the side to move's king while it is in check, for highlighting. */
|
||||
fun checkedKingSquare(board: Board): Int? =
|
||||
if (isInCheck(board, board.sideToMove)) board.kingSquare(board.sideToMove) else null
|
||||
|
||||
fun legalMoves(board: Board): List<Move> {
|
||||
val pseudo = pseudoLegalMoves(board)
|
||||
val side = board.sideToMove
|
||||
val enemy = side.opposite()
|
||||
val work = board.squares.copyOf()
|
||||
val ownKing = board.kingSquare(side)
|
||||
val result = ArrayList<Move>(pseudo.size)
|
||||
for (m in pseudo) {
|
||||
val moving = work[m.from] ?: continue
|
||||
val captured = work[m.to]
|
||||
|
||||
var epIdx = -1
|
||||
var epPiece: Piece? = null
|
||||
if (m.isEnPassant) {
|
||||
val capturedRank = if (moving.color == PieceColor.WHITE) rank(m.to) - 1 else rank(m.to) + 1
|
||||
epIdx = sq(file(m.to), capturedRank)
|
||||
epPiece = work[epIdx]
|
||||
work[epIdx] = null
|
||||
}
|
||||
work[m.to] = if (m.promotion != null) Piece(m.promotion, moving.color) else moving
|
||||
work[m.from] = null
|
||||
|
||||
var rookFrom = -1
|
||||
var rookTo = -1
|
||||
var rook: Piece? = null
|
||||
if (m.isCastleKingSide) {
|
||||
val backRank = rank(m.from); rookFrom = sq(7, backRank); rookTo = sq(5, backRank)
|
||||
} else if (m.isCastleQueenSide) {
|
||||
val backRank = rank(m.from); rookFrom = sq(0, backRank); rookTo = sq(3, backRank)
|
||||
}
|
||||
if (rookFrom >= 0) {
|
||||
rook = work[rookFrom]
|
||||
work[rookTo] = rook
|
||||
work[rookFrom] = null
|
||||
}
|
||||
|
||||
val kingSq = if (moving.type == PieceType.KING) m.to else ownKing
|
||||
val safe = kingSq == -1 || !attacked(work, kingSq, enemy)
|
||||
|
||||
if (rookFrom >= 0) {
|
||||
work[rookFrom] = rook
|
||||
work[rookTo] = null
|
||||
}
|
||||
work[m.from] = moving
|
||||
work[m.to] = captured
|
||||
if (epIdx >= 0) work[epIdx] = epPiece
|
||||
|
||||
if (safe) result.add(m)
|
||||
val position = Position(board)
|
||||
val moves = IntArray(Position.MAX_MOVES)
|
||||
val end = position.generate(moves, 0, tacticalOnly = false)
|
||||
val result = ArrayList<Move>(end)
|
||||
for (i in 0 until end) {
|
||||
if (position.isLegal(moves[i])) result.add(Position.toMove(moves[i]))
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -267,60 +40,10 @@ object ChessEngine {
|
||||
fun legalMovesFrom(board: Board, from: Int): List<Move> = legalMoves(board).filter { it.from == from }
|
||||
|
||||
fun applyMove(board: Board, move: Move): Board {
|
||||
val squares = board.deepCopySquares()
|
||||
val moving = squares[move.from] ?: return board
|
||||
val isPawn = moving.type == PieceType.PAWN
|
||||
val isCapture = squares[move.to] != null
|
||||
|
||||
if (move.isEnPassant) {
|
||||
val capturedRank = if (moving.color == PieceColor.WHITE) rank(move.to) - 1 else rank(move.to) + 1
|
||||
squares[sq(file(move.to), capturedRank)] = null
|
||||
}
|
||||
|
||||
squares[move.to] = if (move.promotion != null) Piece(move.promotion, moving.color) else moving
|
||||
squares[move.from] = null
|
||||
|
||||
if (move.isCastleKingSide) {
|
||||
val backRank = rank(move.from)
|
||||
squares[sq(5, backRank)] = squares[sq(7, backRank)]
|
||||
squares[sq(7, backRank)] = null
|
||||
}
|
||||
if (move.isCastleQueenSide) {
|
||||
val backRank = rank(move.from)
|
||||
squares[sq(3, backRank)] = squares[sq(0, backRank)]
|
||||
squares[sq(0, backRank)] = null
|
||||
}
|
||||
|
||||
var wk = board.whiteKingSideCastle
|
||||
var wq = board.whiteQueenSideCastle
|
||||
var bk = board.blackKingSideCastle
|
||||
var bq = board.blackQueenSideCastle
|
||||
if (moving.type == PieceType.KING) {
|
||||
if (moving.color == PieceColor.WHITE) { wk = false; wq = false } else { bk = false; bq = false }
|
||||
}
|
||||
if (move.from == sq(0, 0) || move.to == sq(0, 0)) wq = false
|
||||
if (move.from == sq(7, 0) || move.to == sq(7, 0)) wk = false
|
||||
if (move.from == sq(0, 7) || move.to == sq(0, 7)) bq = false
|
||||
if (move.from == sq(7, 7) || move.to == sq(7, 7)) bk = false
|
||||
|
||||
val newEnPassant = if (isPawn && kotlin.math.abs(rank(move.to) - rank(move.from)) == 2) {
|
||||
sq(file(move.from), (rank(move.from) + rank(move.to)) / 2)
|
||||
} else null
|
||||
|
||||
val newHalfmove = if (isPawn || isCapture) 0 else board.halfmoveClock + 1
|
||||
val newFullmove = if (board.sideToMove == PieceColor.BLACK) board.fullmoveNumber + 1 else board.fullmoveNumber
|
||||
|
||||
return Board(
|
||||
squares = squares,
|
||||
sideToMove = board.sideToMove.opposite(),
|
||||
whiteKingSideCastle = wk,
|
||||
whiteQueenSideCastle = wq,
|
||||
blackKingSideCastle = bk,
|
||||
blackQueenSideCastle = bq,
|
||||
enPassantTarget = newEnPassant,
|
||||
halfmoveClock = newHalfmove,
|
||||
fullmoveNumber = newFullmove
|
||||
)
|
||||
if (board.squares[move.from] == null) return board
|
||||
val position = Position(board)
|
||||
position.make(Position.encode(move))
|
||||
return position.toBoard()
|
||||
}
|
||||
|
||||
fun gameStatus(board: Board, positionHistory: List<String> = emptyList()): GameStatus {
|
||||
@@ -339,21 +62,7 @@ object ChessEngine {
|
||||
* Neither side can ever mate: kings alone, a single minor piece, or only bishops that all
|
||||
* stand on squares of one colour.
|
||||
*/
|
||||
fun isDeadPosition(board: Board): Boolean {
|
||||
val minors = ArrayList<Int>(4)
|
||||
for (i in 0 until 64) {
|
||||
val p = board.squares[i] ?: continue
|
||||
when (p.type) {
|
||||
PieceType.KING -> Unit
|
||||
PieceType.BISHOP, PieceType.KNIGHT -> minors.add(i)
|
||||
else -> return false
|
||||
}
|
||||
}
|
||||
if (minors.size <= 1) return true
|
||||
if (minors.any { board.squares[it]?.type != PieceType.BISHOP }) return false
|
||||
val shade = (file(minors[0]) + rank(minors[0])) % 2
|
||||
return minors.all { (file(it) + rank(it)) % 2 == shade }
|
||||
}
|
||||
fun isDeadPosition(board: Board): Boolean = Position(board).isDeadPosition()
|
||||
|
||||
/**
|
||||
* Whether [color] has enough material to mate at all. A player whose flag falls loses only if
|
||||
|
||||
@@ -5,6 +5,7 @@ package cc.skysparkle.matewave.engine
|
||||
* (e.g. "Nbd7", "exd6", "e8=Q", "O-O"), which is the key format of the opening data.
|
||||
*/
|
||||
object Notation {
|
||||
private val LOOSE_SAN = Regex("^([KQRBN])?([a-h])?([1-8])?x?([a-h][1-8])([QRBN])?$")
|
||||
|
||||
fun isCastle(board: Board, move: Move): Boolean {
|
||||
if (move.isCastleKingSide || move.isCastleQueenSide) return true
|
||||
@@ -69,7 +70,7 @@ object Notation {
|
||||
legal.firstOrNull { normalizeSan(toSan(board, it, legal)) == wanted }?.let { return it }
|
||||
|
||||
// Over-disambiguated or loosely written SAN, e.g. "Ngf3" or "e8Q".
|
||||
val m = Regex("^([KQRBN])?([a-h])?([1-8])?x?([a-h][1-8])([QRBN])?$").find(wanted) ?: return null
|
||||
val m = LOOSE_SAN.find(wanted) ?: return null
|
||||
val type = when (m.groupValues[1]) {
|
||||
"K" -> PieceType.KING; "Q" -> PieceType.QUEEN; "R" -> PieceType.ROOK
|
||||
"B" -> PieceType.BISHOP; "N" -> PieceType.KNIGHT; else -> PieceType.PAWN
|
||||
@@ -88,6 +89,15 @@ object Notation {
|
||||
}.singleOrNull()
|
||||
}
|
||||
|
||||
/** The legal move written as [uci]; without a valid promotion letter the first match is taken. */
|
||||
fun fromUci(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()
|
||||
}
|
||||
|
||||
/** Position part of a FEN without move counters, used to compare positions. */
|
||||
fun positionKey(board: Board): String =
|
||||
board.toFen().substringBeforeLast(' ').substringBeforeLast(' ')
|
||||
|
||||
@@ -0,0 +1,485 @@
|
||||
package cc.skysparkle.matewave.engine
|
||||
|
||||
/**
|
||||
* Mutable position for move generation and search: pieces are int codes, moves are ints, and
|
||||
* [make]/[unmake] change one position in place instead of copying boards. [ChessEngine] wraps it
|
||||
* for the immutable [Board] API, so the rules exist once.
|
||||
*
|
||||
* Piece code: type (1 pawn .. 6 king) plus 8 for black, 0 for an empty square. Move: from in bits
|
||||
* 0-5, to in bits 6-11, promotion type in bits 12-14, then the castling and en passant flags.
|
||||
*/
|
||||
internal class Position(board: Board) {
|
||||
val squares = IntArray(64)
|
||||
var side = WHITE
|
||||
private set
|
||||
private var castling = 0
|
||||
private var enPassant = -1
|
||||
var halfmove = 0
|
||||
private set
|
||||
private var fullmove = 1
|
||||
|
||||
/** King square per colour, -1 without a king. */
|
||||
private val kings = intArrayOf(-1, -1)
|
||||
|
||||
private var undo = IntArray(UNDO_FIELDS * 16)
|
||||
private var undoDepth = 0
|
||||
|
||||
init {
|
||||
for (sq in 0 until 64) {
|
||||
val piece = board.squares[sq] ?: continue
|
||||
val code = code(piece.type.ordinal + 1, piece.color.ordinal)
|
||||
squares[sq] = code
|
||||
if (piece.type == PieceType.KING && kings[piece.color.ordinal] == -1) kings[piece.color.ordinal] = sq
|
||||
}
|
||||
side = board.sideToMove.ordinal
|
||||
if (board.whiteKingSideCastle) castling = castling or CASTLE_WK
|
||||
if (board.whiteQueenSideCastle) castling = castling or CASTLE_WQ
|
||||
if (board.blackKingSideCastle) castling = castling or CASTLE_BK
|
||||
if (board.blackQueenSideCastle) castling = castling or CASTLE_BQ
|
||||
enPassant = board.enPassantTarget ?: -1
|
||||
halfmove = board.halfmoveClock
|
||||
fullmove = board.fullmoveNumber
|
||||
}
|
||||
|
||||
fun toBoard(): Board {
|
||||
val pieces = arrayOfNulls<Piece>(64)
|
||||
for (sq in 0 until 64) {
|
||||
val code = squares[sq]
|
||||
if (code != 0) pieces[sq] = PIECES[code]
|
||||
}
|
||||
return Board(
|
||||
squares = pieces,
|
||||
sideToMove = if (side == WHITE) PieceColor.WHITE else PieceColor.BLACK,
|
||||
whiteKingSideCastle = (castling and CASTLE_WK) != 0,
|
||||
whiteQueenSideCastle = (castling and CASTLE_WQ) != 0,
|
||||
blackKingSideCastle = (castling and CASTLE_BK) != 0,
|
||||
blackQueenSideCastle = (castling and CASTLE_BQ) != 0,
|
||||
enPassantTarget = if (enPassant == -1) null else enPassant,
|
||||
halfmoveClock = halfmove,
|
||||
fullmoveNumber = fullmove
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the pseudo-legal moves of the side to move into [out] from [start] and returns the end
|
||||
* index; [out] needs room for [MAX_MOVES]. With [tacticalOnly] only captures, en passant and
|
||||
* promotions are written, in the same relative order.
|
||||
*/
|
||||
fun generate(out: IntArray, start: Int, tacticalOnly: Boolean): Int {
|
||||
var n = start
|
||||
val us = side
|
||||
for (from in 0 until 64) {
|
||||
val piece = squares[from]
|
||||
if (piece == 0 || colorOf(piece) != us) continue
|
||||
n = when (typeOf(piece)) {
|
||||
PAWN -> pawnMoves(from, us, out, n, tacticalOnly)
|
||||
KNIGHT -> stepMoves(from, us, KNIGHT_TARGETS[from], out, n, tacticalOnly)
|
||||
BISHOP -> slidingMoves(from, us, 4, 8, out, n, tacticalOnly)
|
||||
ROOK -> slidingMoves(from, us, 0, 4, out, n, tacticalOnly)
|
||||
QUEEN -> slidingMoves(from, us, 0, 8, out, n, tacticalOnly)
|
||||
else -> kingMoves(from, us, out, n, tacticalOnly)
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
private fun pawnMoves(from: Int, us: Int, out: IntArray, start: Int, tacticalOnly: Boolean): Int {
|
||||
var n = start
|
||||
val file = from and 7
|
||||
val rank = from shr 3
|
||||
val toRank = if (us == WHITE) rank + 1 else rank - 1
|
||||
if (toRank !in 0..7) return n
|
||||
val promotes = toRank == (if (us == WHITE) 7 else 0)
|
||||
val one = toRank * 8 + file
|
||||
if (squares[one] == 0) {
|
||||
if (promotes) {
|
||||
n = promotions(from, one, out, n)
|
||||
} else if (!tacticalOnly) {
|
||||
out[n++] = moveCode(from, one)
|
||||
if (rank == (if (us == WHITE) 1 else 6)) {
|
||||
val two = if (us == WHITE) one + 8 else one - 8
|
||||
if (squares[two] == 0) out[n++] = moveCode(from, two)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (file > 0) n = pawnCapture(from, one - 1, promotes, us, out, n)
|
||||
if (file < 7) n = pawnCapture(from, one + 1, promotes, us, out, n)
|
||||
return n
|
||||
}
|
||||
|
||||
private fun pawnCapture(from: Int, to: Int, promotes: Boolean, us: Int, out: IntArray, start: Int): Int {
|
||||
var n = start
|
||||
val target = squares[to]
|
||||
if (target != 0 && colorOf(target) != us) {
|
||||
if (promotes) n = promotions(from, to, out, n) else out[n++] = moveCode(from, to)
|
||||
} else if (to == enPassant) {
|
||||
out[n++] = moveCode(from, to) or FLAG_EN_PASSANT
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
private fun promotions(from: Int, to: Int, out: IntArray, start: Int): Int {
|
||||
var n = start
|
||||
val base = moveCode(from, to)
|
||||
out[n++] = base or (QUEEN shl 12)
|
||||
out[n++] = base or (ROOK shl 12)
|
||||
out[n++] = base or (BISHOP shl 12)
|
||||
out[n++] = base or (KNIGHT shl 12)
|
||||
return n
|
||||
}
|
||||
|
||||
private fun stepMoves(from: Int, us: Int, targets: IntArray, out: IntArray, start: Int, tacticalOnly: Boolean): Int {
|
||||
var n = start
|
||||
for (to in targets) {
|
||||
val target = squares[to]
|
||||
if (target == 0) {
|
||||
if (!tacticalOnly) out[n++] = moveCode(from, to)
|
||||
} else if (colorOf(target) != us) {
|
||||
out[n++] = moveCode(from, to)
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
private fun slidingMoves(
|
||||
from: Int, us: Int, firstDir: Int, endDir: Int, out: IntArray, start: Int, tacticalOnly: Boolean
|
||||
): Int {
|
||||
var n = start
|
||||
for (dir in firstDir until endDir) {
|
||||
val ray = dir * 64 + from
|
||||
val base = ray * 7
|
||||
for (i in 0 until RAY_LENGTH[ray]) {
|
||||
val to = RAYS[base + i]
|
||||
val target = squares[to]
|
||||
if (target == 0) {
|
||||
if (!tacticalOnly) out[n++] = moveCode(from, to)
|
||||
} else {
|
||||
if (colorOf(target) != us) out[n++] = moveCode(from, to)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
private fun kingMoves(from: Int, us: Int, out: IntArray, start: Int, tacticalOnly: Boolean): Int {
|
||||
var n = stepMoves(from, us, KING_TARGETS[from], out, start, tacticalOnly)
|
||||
if (tacticalOnly) return n
|
||||
val e = if (us == WHITE) 4 else 60
|
||||
if (from != e) return n
|
||||
val rook = code(ROOK, us)
|
||||
val them = us xor 1
|
||||
val kingSide = (castling and (if (us == WHITE) CASTLE_WK else CASTLE_BK)) != 0 && squares[e + 3] == rook
|
||||
val queenSide = (castling and (if (us == WHITE) CASTLE_WQ else CASTLE_BQ)) != 0 && squares[e - 4] == rook
|
||||
if (kingSide && squares[e + 1] == 0 && squares[e + 2] == 0 &&
|
||||
!isAttacked(e, them) && !isAttacked(e + 1, them) && !isAttacked(e + 2, them)
|
||||
) {
|
||||
out[n++] = moveCode(from, e + 2) or FLAG_CASTLE_KING
|
||||
}
|
||||
if (queenSide && squares[e - 1] == 0 && squares[e - 2] == 0 && squares[e - 3] == 0 &&
|
||||
!isAttacked(e, them) && !isAttacked(e - 1, them) && !isAttacked(e - 2, them)
|
||||
) {
|
||||
out[n++] = moveCode(from, e - 2) or FLAG_CASTLE_QUEEN
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
/** Whether a piece of colour [by] attacks [target]. */
|
||||
fun isAttacked(target: Int, by: Int): Boolean {
|
||||
val file = target and 7
|
||||
// Pawns of [by] capture towards the target from one rank behind it.
|
||||
val pawnRank = (target shr 3) + (if (by == WHITE) -1 else 1)
|
||||
if (pawnRank in 0..7) {
|
||||
val pawn = code(PAWN, by)
|
||||
if (file > 0 && squares[pawnRank * 8 + file - 1] == pawn) return true
|
||||
if (file < 7 && squares[pawnRank * 8 + file + 1] == pawn) return true
|
||||
}
|
||||
val knight = code(KNIGHT, by)
|
||||
for (sq in KNIGHT_TARGETS[target]) if (squares[sq] == knight) return true
|
||||
val king = code(KING, by)
|
||||
for (sq in KING_TARGETS[target]) if (squares[sq] == king) return true
|
||||
val queen = code(QUEEN, by)
|
||||
val rook = code(ROOK, by)
|
||||
val bishop = code(BISHOP, by)
|
||||
for (dir in 0 until 8) {
|
||||
val slider = if (dir < 4) rook else bishop
|
||||
val ray = dir * 64 + target
|
||||
val base = ray * 7
|
||||
for (i in 0 until RAY_LENGTH[ray]) {
|
||||
val piece = squares[RAYS[base + i]]
|
||||
if (piece != 0) {
|
||||
if (piece == queen || piece == slider) return true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/** Whether the king of the side to move is attacked. */
|
||||
fun inCheck(): Boolean {
|
||||
val king = kings[side]
|
||||
return king != -1 && isAttacked(king, side xor 1)
|
||||
}
|
||||
|
||||
/** After [make]: whether the side that moved kept its king out of check. */
|
||||
fun moverKingSafe(): Boolean {
|
||||
val king = kings[side xor 1]
|
||||
return king == -1 || !isAttacked(king, side)
|
||||
}
|
||||
|
||||
fun isLegal(move: Int): Boolean {
|
||||
make(move)
|
||||
val safe = moverKingSafe()
|
||||
unmake(move)
|
||||
return safe
|
||||
}
|
||||
|
||||
/** Plays [move] for the piece on its from-square, which must not be empty. */
|
||||
fun make(move: Int) {
|
||||
val from = move and 63
|
||||
val to = (move shr 6) and 63
|
||||
val promotion = (move shr 12) and 7
|
||||
val moving = squares[from]
|
||||
val color = colorOf(moving)
|
||||
val captured = squares[to]
|
||||
|
||||
if ((undoDepth + 1) * UNDO_FIELDS > undo.size) undo = undo.copyOf(undo.size * 2)
|
||||
val u = undoDepth * UNDO_FIELDS
|
||||
undoDepth++
|
||||
undo[u] = moving
|
||||
undo[u + 1] = captured
|
||||
undo[u + 2] = 0
|
||||
undo[u + 3] = castling
|
||||
undo[u + 4] = enPassant
|
||||
undo[u + 5] = halfmove
|
||||
undo[u + 6] = fullmove
|
||||
undo[u + 7] = kings[WHITE]
|
||||
undo[u + 8] = kings[BLACK]
|
||||
|
||||
if ((move and FLAG_EN_PASSANT) != 0) {
|
||||
val victim = if (color == WHITE) to - 8 else to + 8
|
||||
undo[u + 2] = squares[victim]
|
||||
squares[victim] = 0
|
||||
}
|
||||
squares[to] = if (promotion != 0) code(promotion, color) else moving
|
||||
squares[from] = 0
|
||||
val backRank = from and 56
|
||||
if ((move and FLAG_CASTLE_KING) != 0) {
|
||||
squares[backRank + 5] = squares[backRank + 7]
|
||||
squares[backRank + 7] = 0
|
||||
}
|
||||
if ((move and FLAG_CASTLE_QUEEN) != 0) {
|
||||
squares[backRank + 3] = squares[backRank]
|
||||
squares[backRank] = 0
|
||||
}
|
||||
|
||||
val type = typeOf(moving)
|
||||
if (type == KING) {
|
||||
val rights = if (color == WHITE) CASTLE_WK or CASTLE_WQ else CASTLE_BK or CASTLE_BQ
|
||||
castling = castling and rights.inv()
|
||||
kings[color] = to
|
||||
}
|
||||
if (captured != 0 && typeOf(captured) == KING) kings[colorOf(captured)] = -1
|
||||
if (from == 0 || to == 0) castling = castling and CASTLE_WQ.inv()
|
||||
if (from == 7 || to == 7) castling = castling and CASTLE_WK.inv()
|
||||
if (from == 56 || to == 56) castling = castling and CASTLE_BQ.inv()
|
||||
if (from == 63 || to == 63) castling = castling and CASTLE_BK.inv()
|
||||
|
||||
val fromRank = from shr 3
|
||||
val toRank = to shr 3
|
||||
enPassant = if (type == PAWN && (toRank - fromRank == 2 || fromRank - toRank == 2)) {
|
||||
(fromRank + toRank) / 2 * 8 + (from and 7)
|
||||
} else -1
|
||||
halfmove = if (type == PAWN || captured != 0) 0 else halfmove + 1
|
||||
if (side == BLACK) fullmove++
|
||||
side = side xor 1
|
||||
}
|
||||
|
||||
/** Takes back [move], which must be the last one made and a move from [generate]. */
|
||||
fun unmake(move: Int) {
|
||||
undoDepth--
|
||||
val u = undoDepth * UNDO_FIELDS
|
||||
val from = move and 63
|
||||
val to = (move shr 6) and 63
|
||||
side = side xor 1
|
||||
squares[from] = undo[u]
|
||||
squares[to] = undo[u + 1]
|
||||
if ((move and FLAG_EN_PASSANT) != 0) squares[if (side == WHITE) to - 8 else to + 8] = undo[u + 2]
|
||||
val backRank = from and 56
|
||||
if ((move and FLAG_CASTLE_KING) != 0) {
|
||||
squares[backRank + 7] = squares[backRank + 5]
|
||||
squares[backRank + 5] = 0
|
||||
}
|
||||
if ((move and FLAG_CASTLE_QUEEN) != 0) {
|
||||
squares[backRank] = squares[backRank + 3]
|
||||
squares[backRank + 3] = 0
|
||||
}
|
||||
castling = undo[u + 3]
|
||||
enPassant = undo[u + 4]
|
||||
halfmove = undo[u + 5]
|
||||
fullmove = undo[u + 6]
|
||||
kings[WHITE] = undo[u + 7]
|
||||
kings[BLACK] = undo[u + 8]
|
||||
}
|
||||
|
||||
/** See [ChessEngine.isDeadPosition]. */
|
||||
fun isDeadPosition(): Boolean {
|
||||
var minors = 0
|
||||
var knights = false
|
||||
var shade = -1
|
||||
var oneShade = true
|
||||
for (sq in 0 until 64) {
|
||||
val code = squares[sq]
|
||||
if (code == 0) continue
|
||||
when (typeOf(code)) {
|
||||
KING -> Unit
|
||||
KNIGHT -> { minors++; knights = true }
|
||||
BISHOP -> {
|
||||
minors++
|
||||
val s = ((sq and 7) + (sq shr 3)) and 1
|
||||
if (shade == -1) shade = s else if (s != shade) oneShade = false
|
||||
}
|
||||
else -> return false
|
||||
}
|
||||
}
|
||||
return minors <= 1 || (!knights && oneShade)
|
||||
}
|
||||
|
||||
/**
|
||||
* Hash of what [Notation.positionKey] covers: pieces, side to move, castling rights and the
|
||||
* en passant square. Equal keys give equal hashes; different keys can still collide.
|
||||
*/
|
||||
fun keyHash(): Long {
|
||||
var h = if (side == BLACK) ZOBRIST_BLACK else 0L
|
||||
for (sq in 0 until 64) {
|
||||
val code = squares[sq]
|
||||
if (code != 0) h = h xor ZOBRIST[code * 64 + sq]
|
||||
}
|
||||
h = h xor ZOBRIST[CASTLING_KEYS + castling]
|
||||
if (enPassant in 0..63) h = h xor ZOBRIST[EN_PASSANT_KEYS + enPassant]
|
||||
return h
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val WHITE = 0
|
||||
const val BLACK = 1
|
||||
|
||||
const val PAWN = 1
|
||||
const val KNIGHT = 2
|
||||
const val BISHOP = 3
|
||||
const val ROOK = 4
|
||||
const val QUEEN = 5
|
||||
const val KING = 6
|
||||
|
||||
/** More pseudo-legal moves than any position can have. */
|
||||
const val MAX_MOVES = 512
|
||||
|
||||
private const val FLAG_CASTLE_KING = 1 shl 15
|
||||
private const val FLAG_CASTLE_QUEEN = 1 shl 16
|
||||
private const val FLAG_EN_PASSANT = 1 shl 17
|
||||
|
||||
private const val CASTLE_WK = 1
|
||||
private const val CASTLE_WQ = 2
|
||||
private const val CASTLE_BK = 4
|
||||
private const val CASTLE_BQ = 8
|
||||
|
||||
private const val UNDO_FIELDS = 9
|
||||
|
||||
fun code(type: Int, color: Int): Int = type or (color shl 3)
|
||||
fun typeOf(code: Int): Int = code and 7
|
||||
fun colorOf(code: Int): Int = code shr 3
|
||||
|
||||
fun moveFrom(move: Int): Int = move and 63
|
||||
fun moveTo(move: Int): Int = (move shr 6) and 63
|
||||
fun promotionOf(move: Int): Int = (move shr 12) and 7
|
||||
fun isEnPassant(move: Int): Boolean = (move and FLAG_EN_PASSANT) != 0
|
||||
|
||||
private fun moveCode(from: Int, to: Int): Int = from or (to shl 6)
|
||||
|
||||
private val TYPES = PieceType.entries.toTypedArray()
|
||||
|
||||
/** Shared [Piece] per code; pieces are immutable values. */
|
||||
private val PIECES = arrayOfNulls<Piece>(16).also {
|
||||
for (type in TYPES) for (color in PieceColor.entries) {
|
||||
it[code(type.ordinal + 1, color.ordinal)] = Piece(type, color)
|
||||
}
|
||||
}
|
||||
|
||||
fun encode(move: Move): Int {
|
||||
var m = moveCode(move.from, move.to)
|
||||
if (move.promotion != null) m = m or ((move.promotion.ordinal + 1) shl 12)
|
||||
if (move.isCastleKingSide) m = m or FLAG_CASTLE_KING
|
||||
if (move.isCastleQueenSide) m = m or FLAG_CASTLE_QUEEN
|
||||
if (move.isEnPassant) m = m or FLAG_EN_PASSANT
|
||||
return m
|
||||
}
|
||||
|
||||
fun toMove(move: Int): Move {
|
||||
val promotion = promotionOf(move)
|
||||
return Move(
|
||||
from = moveFrom(move),
|
||||
to = moveTo(move),
|
||||
promotion = if (promotion == 0) null else TYPES[promotion - 1],
|
||||
isCastleKingSide = (move and FLAG_CASTLE_KING) != 0,
|
||||
isCastleQueenSide = (move and FLAG_CASTLE_QUEEN) != 0,
|
||||
isEnPassant = (move and FLAG_EN_PASSANT) != 0
|
||||
)
|
||||
}
|
||||
|
||||
/** Knight targets per square, in the order moves are generated. */
|
||||
private val KNIGHT_TARGETS = targets(intArrayOf(1, 2, 2, 1, -1, -2, -2, -1), intArrayOf(2, 1, -1, -2, -2, -1, 1, 2))
|
||||
|
||||
/** King targets per square, file offset first, then rank offset. */
|
||||
private val KING_TARGETS = targets(intArrayOf(-1, -1, -1, 0, 0, 1, 1, 1), intArrayOf(-1, 0, 1, -1, 1, -1, 0, 1))
|
||||
|
||||
private fun targets(df: IntArray, dr: IntArray): Array<IntArray> = Array(64) { sq ->
|
||||
val list = ArrayList<Int>(8)
|
||||
for (i in df.indices) {
|
||||
val f = (sq and 7) + df[i]
|
||||
val r = (sq shr 3) + dr[i]
|
||||
if (f in 0..7 && r in 0..7) list.add(r * 8 + f)
|
||||
}
|
||||
list.toIntArray()
|
||||
}
|
||||
|
||||
/** Directions 0-3 are orthogonal, 4-7 diagonal, in the order moves are generated. */
|
||||
private val DIR_FILE = intArrayOf(1, -1, 0, 0, 1, 1, -1, -1)
|
||||
private val DIR_RANK = intArrayOf(0, 0, 1, -1, 1, -1, 1, -1)
|
||||
|
||||
/** Squares along each direction from each square: 7 slots per ray (direction * 64 + square). */
|
||||
private val RAYS = IntArray(8 * 64 * 7)
|
||||
private val RAY_LENGTH = IntArray(8 * 64)
|
||||
|
||||
init {
|
||||
for (dir in 0 until 8) for (sq in 0 until 64) {
|
||||
val ray = dir * 64 + sq
|
||||
var f = (sq and 7) + DIR_FILE[dir]
|
||||
var r = (sq shr 3) + DIR_RANK[dir]
|
||||
var length = 0
|
||||
while (f in 0..7 && r in 0..7) {
|
||||
RAYS[ray * 7 + length++] = r * 8 + f
|
||||
f += DIR_FILE[dir]
|
||||
r += DIR_RANK[dir]
|
||||
}
|
||||
RAY_LENGTH[ray] = length
|
||||
}
|
||||
}
|
||||
|
||||
private const val CASTLING_KEYS = 16 * 64
|
||||
private const val EN_PASSANT_KEYS = CASTLING_KEYS + 16
|
||||
|
||||
/** Fixed pseudo-random keys (splitmix64): piece and square, castling rights, en passant. */
|
||||
private val ZOBRIST = LongArray(EN_PASSANT_KEYS + 64).also {
|
||||
var state = 0x2545F4914F6CDD1DL
|
||||
for (i in it.indices) {
|
||||
state += -0x61c8864680b583ebL
|
||||
var z = state
|
||||
z = (z xor (z ushr 30)) * -0x40a7b892e31b1a47L
|
||||
z = (z xor (z ushr 27)) * -0x6b2fb644ecceee15L
|
||||
it[i] = z xor (z ushr 31)
|
||||
}
|
||||
}
|
||||
private val ZOBRIST_BLACK = ZOBRIST[0]
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,7 @@ import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.os.ParcelUuid
|
||||
import androidx.core.content.ContextCompat
|
||||
import cc.skysparkle.matewave.security.toHex
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.channels.Channel
|
||||
@@ -52,6 +53,7 @@ class BleTransport(
|
||||
) : ConnectionTransport {
|
||||
companion object {
|
||||
val SERVICE_UUID: UUID = UUID.fromString("6b1e7f10-2c3d-4a5b-8e9f-0a1b2c3d4e5f")
|
||||
private val SERVICE_PARCEL_UUID = ParcelUuid(SERVICE_UUID)
|
||||
|
||||
val CHAR_WRITE_UUID: UUID = UUID.fromString("6b1e7f11-2c3d-4a5b-8e9f-0a1b2c3d4e5f")
|
||||
|
||||
@@ -71,6 +73,9 @@ class BleTransport(
|
||||
|
||||
private const val INCOMPLETE_TTL_MS = 30_000L
|
||||
|
||||
/** Messages being reassembled at once; each may grow to [MAX_MESSAGE_BYTES]. */
|
||||
private const val MAX_PARTIAL_MESSAGES = 4
|
||||
|
||||
private const val CTRL_TOTAL_MARKER = 0
|
||||
private const val CTRL_ACK = 1
|
||||
private const val CTRL_NACK = 2
|
||||
@@ -94,11 +99,6 @@ class BleTransport(
|
||||
private const val NAME_BYTES_LIMIT = 6
|
||||
|
||||
const val MAX_MESSAGE_BYTES = 1_000_000
|
||||
|
||||
fun fingerprintOf(publicKeyOrId: String): String =
|
||||
java.security.MessageDigest.getInstance("SHA-256")
|
||||
.digest(publicKeyOrId.toByteArray(Charsets.UTF_8))
|
||||
.take(FINGERPRINT_BYTES).joinToString("") { "%02x".format(it) }
|
||||
}
|
||||
|
||||
override val type = TransportType.BLUETOOTH
|
||||
@@ -110,8 +110,6 @@ class BleTransport(
|
||||
private val adapter: BluetoothAdapter? = manager?.adapter
|
||||
|
||||
private val dispatcher = MessageDispatcher()
|
||||
var lastError: String? = null
|
||||
private set
|
||||
|
||||
private enum class Role { NONE, PERIPHERAL, CENTRAL }
|
||||
private var role = Role.NONE
|
||||
@@ -119,8 +117,6 @@ class BleTransport(
|
||||
private var gattServerActive = false
|
||||
private var advertisingActive = false
|
||||
|
||||
private var shuttingDown = false
|
||||
|
||||
private var gattServer: BluetoothGattServer? = null
|
||||
private var notifyCharacteristic: BluetoothGattCharacteristic? = null
|
||||
private var connectedCentral: BluetoothDevice? = null
|
||||
@@ -143,8 +139,10 @@ class BleTransport(
|
||||
|
||||
private var outgoingMessageId = 0
|
||||
|
||||
private var sendGeneration = 0
|
||||
private var partialWatcherStarted = false
|
||||
@Volatile private var sendGeneration = 0
|
||||
|
||||
/** Guarded by [incoming]. */
|
||||
private var partialWatcherRunning = false
|
||||
|
||||
private val pendingAcks = HashMap<Int, kotlinx.coroutines.CompletableDeferred<Set<Int>>>()
|
||||
|
||||
@@ -211,25 +209,17 @@ class BleTransport(
|
||||
|
||||
@SuppressLint("MissingPermission")
|
||||
fun startPresence() {
|
||||
shuttingDown = false
|
||||
val ad = adapter
|
||||
if (ad == null || !ad.isEnabled) {
|
||||
lastError = "Bluetooth is off"
|
||||
return
|
||||
}
|
||||
if (ad == null || !ad.isEnabled) return
|
||||
try {
|
||||
val serverWasReady = gattServerActive
|
||||
if (!gattServerActive) {
|
||||
if (!startGattServer()) {
|
||||
lastError = "Could not start the Bluetooth service"
|
||||
return
|
||||
}
|
||||
if (!startGattServer()) return
|
||||
gattServerActive = true
|
||||
}
|
||||
|
||||
if (serverWasReady && !advertisingActive) startAdvertising()
|
||||
} catch (e: SecurityException) {
|
||||
lastError = "No Bluetooth permission"
|
||||
} catch (_: SecurityException) {
|
||||
NetworkLog.reason("BLE", DisconnectReason.PERMISSION_DENIED)
|
||||
}
|
||||
}
|
||||
@@ -238,15 +228,15 @@ class BleTransport(
|
||||
override fun startHosting() {
|
||||
val ad = adapter
|
||||
if (ad == null || !ad.isEnabled) {
|
||||
lastError = "Bluetooth is off"
|
||||
NetworkLog.reason("BLE", DisconnectReason.BLUETOOTH_OFF)
|
||||
_connectionState.value = ConnectionState.FAILED
|
||||
return
|
||||
}
|
||||
lastError = null
|
||||
role = Role.PERIPHERAL
|
||||
hosting = true
|
||||
|
||||
// Presence may already be advertising in the low-power mode; restart it for hosting.
|
||||
if (advertisingActive || advertiseCallback != null) startAdvertising()
|
||||
startPresence()
|
||||
_connectionState.value = ConnectionState.CONNECTING
|
||||
}
|
||||
@@ -310,27 +300,30 @@ class BleTransport(
|
||||
if (!announceAllowed()) return
|
||||
val advertiser = adapter?.bluetoothLeAdvertiser
|
||||
if (advertiser == null) {
|
||||
lastError = "This device does not support Bluetooth advertising"
|
||||
if (hosting) _connectionState.value = ConnectionState.FAILED
|
||||
return
|
||||
}
|
||||
// One advertisement at a time: a second start would leak the first one.
|
||||
if (advertiseCallback != null) stopAdvertising()
|
||||
// A hosted game should be found at once; plain presence can save the battery.
|
||||
val settings = AdvertiseSettings.Builder()
|
||||
|
||||
.setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY)
|
||||
.setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_HIGH)
|
||||
.setAdvertiseMode(
|
||||
if (hosting) AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY else AdvertiseSettings.ADVERTISE_MODE_BALANCED
|
||||
)
|
||||
.setTxPowerLevel(
|
||||
if (hosting) AdvertiseSettings.ADVERTISE_TX_POWER_HIGH else AdvertiseSettings.ADVERTISE_TX_POWER_MEDIUM
|
||||
)
|
||||
.setConnectable(true)
|
||||
.build()
|
||||
|
||||
val data = AdvertiseData.Builder()
|
||||
.setIncludeDeviceName(false)
|
||||
.addServiceUuid(ParcelUuid(SERVICE_UUID))
|
||||
.addServiceUuid(SERVICE_PARCEL_UUID)
|
||||
.build()
|
||||
|
||||
val scanResponse = AdvertiseData.Builder()
|
||||
.setIncludeDeviceName(false)
|
||||
.addServiceData(ParcelUuid(SERVICE_UUID), buildIdentityPayload())
|
||||
.addServiceData(SERVICE_PARCEL_UUID, buildIdentityPayload())
|
||||
.build()
|
||||
|
||||
val cb = object : AdvertiseCallback() {
|
||||
@@ -345,7 +338,6 @@ class BleTransport(
|
||||
}
|
||||
advertisingActive = false
|
||||
if (advertiseCallback === this) advertiseCallback = null
|
||||
lastError = "Advertising failed (code $errorCode)"
|
||||
NetworkLog.log("BLE", "Advertising failed, code $errorCode")
|
||||
// Without advertising nobody can find a hosted game; plain presence just goes quiet.
|
||||
if (hosting && connectedCentral == null) _connectionState.value = ConnectionState.FAILED
|
||||
@@ -354,9 +346,8 @@ class BleTransport(
|
||||
advertiseCallback = cb
|
||||
try {
|
||||
advertiser.startAdvertising(settings, data, scanResponse, cb)
|
||||
} catch (e: Exception) {
|
||||
} catch (_: Exception) {
|
||||
advertiseCallback = null
|
||||
lastError = "Advertising failed: ${e.message}"
|
||||
if (hosting) _connectionState.value = ConnectionState.FAILED
|
||||
}
|
||||
}
|
||||
@@ -380,7 +371,7 @@ class BleTransport(
|
||||
|
||||
private fun parseIdentityPayload(data: ByteArray?): Pair<String?, String?> {
|
||||
if (data == null || data.size < FINGERPRINT_BYTES) return null to null
|
||||
val fingerprint = data.take(FINGERPRINT_BYTES).joinToString("") { "%02x".format(it) }
|
||||
val fingerprint = data.toHex(FINGERPRINT_BYTES)
|
||||
val name = if (data.size > FINGERPRINT_BYTES) {
|
||||
String(data, FINGERPRINT_BYTES, data.size - FINGERPRINT_BYTES, Charsets.UTF_8)
|
||||
.trim().ifBlank { null }
|
||||
@@ -392,12 +383,11 @@ class BleTransport(
|
||||
@SuppressLint("MissingPermission")
|
||||
override fun onServiceAdded(status: Int, service: BluetoothGattService?) {
|
||||
if (status != BluetoothGatt.GATT_SUCCESS) {
|
||||
lastError = "Could not start the Bluetooth service (code $status)"
|
||||
NetworkLog.log("BLE", "Service not added, code $status")
|
||||
gattServerActive = false
|
||||
return
|
||||
}
|
||||
if (!advertisingActive && !shuttingDown) startAdvertising()
|
||||
if (!advertisingActive) startAdvertising()
|
||||
}
|
||||
|
||||
@SuppressLint("MissingPermission")
|
||||
@@ -420,7 +410,6 @@ class BleTransport(
|
||||
role = Role.PERIPHERAL
|
||||
// A new peer starts at the default MTU until it negotiates a larger one.
|
||||
chunkSize = SAFE_CHUNK
|
||||
startWriterIfNeeded()
|
||||
|
||||
_connectionState.value = ConnectionState.CONNECTING
|
||||
stopAdvertising()
|
||||
@@ -462,7 +451,7 @@ class BleTransport(
|
||||
if (enabled) {
|
||||
subscribeWatchJob?.cancel()
|
||||
subscribeWatchJob = null
|
||||
_connectionState.value = ConnectionState.CONNECTED
|
||||
markReady()
|
||||
} else {
|
||||
NetworkLog.log("BLE", "Opponent disabled notifications")
|
||||
dropPeripheralPeer(device)
|
||||
@@ -539,7 +528,22 @@ class BleTransport(
|
||||
|
||||
val lastSeen = HashMap<String, Long>()
|
||||
|
||||
val filter = ScanFilter.Builder().setServiceUuid(ParcelUuid(SERVICE_UUID)).build()
|
||||
// Drops players not seen for a while; true if any were dropped.
|
||||
fun dropExpired(now: Long): Boolean {
|
||||
var dropped = false
|
||||
val entries = lastSeen.entries.iterator()
|
||||
while (entries.hasNext()) {
|
||||
val entry = entries.next()
|
||||
if (now - entry.value > NEARBY_TTL_MS) {
|
||||
found.remove(entry.key)
|
||||
entries.remove()
|
||||
dropped = true
|
||||
}
|
||||
}
|
||||
return dropped
|
||||
}
|
||||
|
||||
val filter = ScanFilter.Builder().setServiceUuid(SERVICE_PARCEL_UUID).build()
|
||||
val settings = ScanSettings.Builder()
|
||||
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
|
||||
|
||||
@@ -552,7 +556,7 @@ class BleTransport(
|
||||
if (myGeneration != scanGeneration) return
|
||||
val device = result.device ?: return
|
||||
|
||||
val payload = result.scanRecord?.getServiceData(ParcelUuid(SERVICE_UUID))
|
||||
val payload = result.scanRecord?.getServiceData(SERVICE_PARCEL_UUID)
|
||||
val (fingerprint, advertisedName) = parseIdentityPayload(payload)
|
||||
|
||||
val bondedName = try { device.name } catch (e: SecurityException) { null }
|
||||
@@ -566,25 +570,20 @@ class BleTransport(
|
||||
val previous = found.put(player.address, player)
|
||||
lastSeen[player.address] = now
|
||||
|
||||
val expired = lastSeen.filterValues { now - it > NEARBY_TTL_MS }.keys
|
||||
expired.forEach { found.remove(it); lastSeen.remove(it) }
|
||||
val expired = dropExpired(now)
|
||||
|
||||
if (previous == null || previous.name != player.name || expired.isNotEmpty()) {
|
||||
if (previous == null || previous.name != player.name || expired) {
|
||||
val snapshot = found.values.toList()
|
||||
scope.launch(Dispatchers.Main) { onFound(snapshot) }
|
||||
}
|
||||
}
|
||||
|
||||
override fun onScanFailed(errorCode: Int) {
|
||||
if (myGeneration != scanGeneration) return
|
||||
lastError = "Nearby scan failed to start (code $errorCode)"
|
||||
}
|
||||
override fun onScanFailed(errorCode: Int) {}
|
||||
}
|
||||
scanCallback = cb
|
||||
try {
|
||||
scanner.startScan(listOf(filter), settings, cb)
|
||||
} catch (e: SecurityException) {
|
||||
lastError = "No permission to scan for devices"
|
||||
} catch (_: SecurityException) {
|
||||
}
|
||||
|
||||
// Scan results arrive on the main thread, so the expiry check runs there too.
|
||||
@@ -592,12 +591,7 @@ class BleTransport(
|
||||
while (true) {
|
||||
kotlinx.coroutines.delay(NEARBY_TTL_MS / 3)
|
||||
if (myGeneration != scanGeneration) return@launch
|
||||
val now = System.currentTimeMillis()
|
||||
val expired = lastSeen.filterValues { now - it > NEARBY_TTL_MS }.keys.toList()
|
||||
if (expired.isNotEmpty()) {
|
||||
expired.forEach { found.remove(it); lastSeen.remove(it) }
|
||||
onFound(found.values.toList())
|
||||
}
|
||||
if (dropExpired(System.currentTimeMillis())) onFound(found.values.toList())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -617,18 +611,15 @@ class BleTransport(
|
||||
override fun startDiscoveryAndConnect(targetId: String?) {
|
||||
val ad = adapter
|
||||
if (ad == null || !ad.isEnabled || targetId.isNullOrBlank()) {
|
||||
lastError = "Bluetooth is off or no opponent selected"
|
||||
_connectionState.value = ConnectionState.FAILED
|
||||
return
|
||||
}
|
||||
|
||||
if (role == Role.PERIPHERAL && connectedCentral != null) {
|
||||
lastError = "A connection is already active, close it first"
|
||||
_connectionState.value = ConnectionState.FAILED
|
||||
return
|
||||
}
|
||||
_connectionState.value = ConnectionState.CONNECTING
|
||||
lastError = null
|
||||
stopDiscovery()
|
||||
// A previous attempt must release its client: Android allows only a few at a time.
|
||||
gattClient?.let { old ->
|
||||
@@ -646,8 +637,7 @@ class BleTransport(
|
||||
context, false, clientCallback(myGeneration), BluetoothDevice.TRANSPORT_LE
|
||||
)
|
||||
gattClient = gatt
|
||||
} catch (e: Exception) {
|
||||
lastError = "Connection failed: ${e.message}"
|
||||
} catch (_: Exception) {
|
||||
_connectionState.value = ConnectionState.FAILED
|
||||
}
|
||||
}
|
||||
@@ -700,7 +690,6 @@ class BleTransport(
|
||||
if (!isCurrent()) return
|
||||
val service = if (status == BluetoothGatt.GATT_SUCCESS) gatt.getService(SERVICE_UUID) else null
|
||||
if (service == null) {
|
||||
lastError = "Peer does not expose this app's service"
|
||||
NetworkLog.reason("BLE", DisconnectReason.SERVICE_NOT_FOUND, "status $status")
|
||||
_connectionState.value = ConnectionState.FAILED
|
||||
closeClient()
|
||||
@@ -708,7 +697,6 @@ class BleTransport(
|
||||
}
|
||||
writeCharacteristic = service.getCharacteristic(CHAR_WRITE_UUID)
|
||||
if (writeCharacteristic == null) {
|
||||
lastError = "Peer does not support move exchange"
|
||||
NetworkLog.reason("BLE", DisconnectReason.SERVICE_NOT_FOUND, "no write characteristic")
|
||||
_connectionState.value = ConnectionState.FAILED
|
||||
closeClient()
|
||||
@@ -717,7 +705,12 @@ class BleTransport(
|
||||
|
||||
val notifyChar = service.getCharacteristic(CHAR_NOTIFY_UUID)
|
||||
if (notifyChar != null) {
|
||||
gatt.setCharacteristicNotification(notifyChar, true)
|
||||
if (!gatt.setCharacteristicNotification(notifyChar, true)) {
|
||||
NetworkLog.reason("BLE", DisconnectReason.SUBSCRIBE_FAILED, "local notification registration failed")
|
||||
_connectionState.value = ConnectionState.FAILED
|
||||
closeClient()
|
||||
return
|
||||
}
|
||||
val cccd = notifyChar.getDescriptor(CCCD_UUID)
|
||||
if (cccd != null) {
|
||||
@Suppress("DEPRECATION")
|
||||
@@ -728,7 +721,6 @@ class BleTransport(
|
||||
}
|
||||
|
||||
if (notifyChar == null || notifyChar.getDescriptor(CCCD_UUID) == null) {
|
||||
lastError = "Peer does not support the Bluetooth return channel"
|
||||
NetworkLog.reason("BLE", DisconnectReason.SERVICE_NOT_FOUND, "no notify characteristic")
|
||||
_connectionState.value = ConnectionState.FAILED
|
||||
closeClient()
|
||||
@@ -739,7 +731,6 @@ class BleTransport(
|
||||
kotlinx.coroutines.delay(SUBSCRIBE_TIMEOUT_MS)
|
||||
if (!isCurrent()) return@launch
|
||||
if (_connectionState.value != ConnectionState.CONNECTED) {
|
||||
lastError = "Peer did not confirm readiness"
|
||||
NetworkLog.reason("BLE", DisconnectReason.SUBSCRIBE_FAILED)
|
||||
_connectionState.value = ConnectionState.FAILED
|
||||
closeClient()
|
||||
@@ -762,7 +753,6 @@ class BleTransport(
|
||||
if (status == BluetoothGatt.GATT_SUCCESS) {
|
||||
markReady()
|
||||
} else {
|
||||
lastError = "Could not enable Bluetooth notifications (code $status)"
|
||||
NetworkLog.reason("BLE", DisconnectReason.SUBSCRIBE_FAILED, "code $status")
|
||||
_connectionState.value = ConnectionState.FAILED
|
||||
closeClient()
|
||||
@@ -809,9 +799,15 @@ class BleTransport(
|
||||
val now = System.currentTimeMillis()
|
||||
incoming.entries.removeAll { now - it.value.startedAt > INCOMPLETE_TTL_MS }
|
||||
|
||||
if (messageId !in incoming && incoming.size >= MAX_PARTIAL_MESSAGES) {
|
||||
// A peer that starts many messages and never finishes them would fill the memory.
|
||||
incoming.minByOrNull { it.value.startedAt }?.let { incoming.remove(it.key) }
|
||||
NetworkLog.log("BLE", "Too many unfinished messages, oldest dropped")
|
||||
}
|
||||
val entry = incoming.getOrPut(messageId) { PartialMessage(total, now) }
|
||||
if (entry.total != total) {
|
||||
incoming[messageId] = PartialMessage(total, now).also { it.parts[index] = payload }
|
||||
startPartialWatcher()
|
||||
return
|
||||
}
|
||||
if (entry.receivedBytes + payload.size > MAX_MESSAGE_BYTES) {
|
||||
@@ -833,6 +829,8 @@ class BleTransport(
|
||||
}
|
||||
}
|
||||
incoming.remove(messageId)
|
||||
} else {
|
||||
startPartialWatcher()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -945,14 +943,22 @@ class BleTransport(
|
||||
var lastChunkAt: Long = startedAt
|
||||
}
|
||||
|
||||
/**
|
||||
* Asks again for the missing chunks of stalled messages. Runs only while some message is
|
||||
* incomplete; call with [incoming] locked.
|
||||
*/
|
||||
private fun startPartialWatcher() {
|
||||
if (partialWatcherStarted) return
|
||||
partialWatcherStarted = true
|
||||
if (partialWatcherRunning) return
|
||||
partialWatcherRunning = true
|
||||
scope.launch {
|
||||
while (true) {
|
||||
kotlinx.coroutines.delay(STALLED_PARTIAL_MS)
|
||||
val requests = ArrayList<Pair<Int, List<Int>>>()
|
||||
synchronized(incoming) {
|
||||
if (incoming.isEmpty()) {
|
||||
partialWatcherRunning = false
|
||||
return@launch
|
||||
}
|
||||
val now = System.currentTimeMillis()
|
||||
for ((messageId, entry) in incoming) {
|
||||
if (now - entry.lastChunkAt < STALLED_PARTIAL_MS) continue
|
||||
@@ -971,7 +977,6 @@ class BleTransport(
|
||||
private fun startWriterIfNeeded() {
|
||||
if (writerStarted) return
|
||||
writerStarted = true
|
||||
startPartialWatcher()
|
||||
scope.launch(Dispatchers.IO) {
|
||||
while (true) {
|
||||
var handled = false
|
||||
@@ -1064,9 +1069,12 @@ class BleTransport(
|
||||
}
|
||||
|
||||
val answer = kotlinx.coroutines.withTimeoutOrNull(ACK_TIMEOUT_MS) {
|
||||
// Control frames keep going out while we wait for the answer.
|
||||
while (!waiter.isCompleted) {
|
||||
val control = controlOutbox.tryReceive().getOrNull()
|
||||
if (control != null) writeRaw(control) else kotlinx.coroutines.delay(20)
|
||||
kotlinx.coroutines.selects.select<Unit> {
|
||||
waiter.onAwait {}
|
||||
controlOutbox.onReceive { writeRaw(it) }
|
||||
}
|
||||
}
|
||||
waiter.await()
|
||||
}
|
||||
@@ -1117,6 +1125,9 @@ class BleTransport(
|
||||
synchronized(nackAccumulator) { nackAccumulator.clear() }
|
||||
synchronized(incoming) { incoming.clear() }
|
||||
synchronized(recentlyCompleted) { recentlyCompleted.clear() }
|
||||
while (outbox.tryReceive().isSuccess) { }
|
||||
while (bulkOutbox.tryReceive().isSuccess) { }
|
||||
while (controlOutbox.tryReceive().isSuccess) { }
|
||||
}
|
||||
|
||||
@SuppressLint("MissingPermission")
|
||||
@@ -1125,12 +1136,17 @@ class BleTransport(
|
||||
val central = connectedCentral
|
||||
if (role == Role.PERIPHERAL && central != null) {
|
||||
val ch = notifyCharacteristic ?: return false
|
||||
@Suppress("DEPRECATION")
|
||||
ch.value = chunk
|
||||
val waiter = kotlinx.coroutines.CompletableDeferred<Boolean>()
|
||||
notificationSent = waiter
|
||||
@Suppress("DEPRECATION")
|
||||
val queued = gattServer?.notifyCharacteristicChanged(central, ch, false) ?: false
|
||||
val queued = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) {
|
||||
gattServer?.notifyCharacteristicChanged(central, ch, false, chunk) ==
|
||||
android.bluetooth.BluetoothStatusCodes.SUCCESS
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
ch.value = chunk
|
||||
@Suppress("DEPRECATION")
|
||||
gattServer?.notifyCharacteristicChanged(central, ch, false) ?: false
|
||||
}
|
||||
if (!queued) {
|
||||
notificationSent = null
|
||||
return false
|
||||
@@ -1141,14 +1157,19 @@ class BleTransport(
|
||||
sent == true
|
||||
} else {
|
||||
val ch = writeCharacteristic ?: return false
|
||||
@Suppress("DEPRECATION")
|
||||
ch.value = chunk
|
||||
|
||||
ch.writeType = BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT
|
||||
val waiter = kotlinx.coroutines.CompletableDeferred<Boolean>()
|
||||
characteristicWritten = waiter
|
||||
@Suppress("DEPRECATION")
|
||||
val queued = gattClient?.writeCharacteristic(ch) ?: false
|
||||
val queued = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) {
|
||||
gattClient?.writeCharacteristic(
|
||||
ch, chunk, BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT
|
||||
) == android.bluetooth.BluetoothStatusCodes.SUCCESS
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
ch.value = chunk
|
||||
ch.writeType = BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT
|
||||
@Suppress("DEPRECATION")
|
||||
gattClient?.writeCharacteristic(ch) ?: false
|
||||
}
|
||||
if (!queued) {
|
||||
characteristicWritten = null
|
||||
return false
|
||||
@@ -1173,6 +1194,11 @@ class BleTransport(
|
||||
}
|
||||
|
||||
override fun send(message: GameMessage) {
|
||||
if (_connectionState.value != ConnectionState.CONNECTED) {
|
||||
NetworkMetrics.messageDropped()
|
||||
NetworkLog.log("BLE", "Message not queued: GATT session is not ready")
|
||||
return
|
||||
}
|
||||
val json = message.toJson()
|
||||
|
||||
if (json.toByteArray(Charsets.UTF_8).size > currentMaxMessageBytes()) {
|
||||
@@ -1226,18 +1252,4 @@ class BleTransport(
|
||||
while (controlOutbox.tryReceive().isSuccess) { }
|
||||
_connectionState.value = ConnectionState.DISCONNECTED
|
||||
}
|
||||
|
||||
@SuppressLint("MissingPermission")
|
||||
fun shutdown() {
|
||||
shuttingDown = true
|
||||
stopDiscovery()
|
||||
stopAdvertising()
|
||||
disconnect()
|
||||
try { gattServer?.close() } catch (_: Exception) {}
|
||||
gattServer = null
|
||||
notifyCharacteristic = null
|
||||
gattServerActive = false
|
||||
advertisingActive = false
|
||||
shuttingDown = false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,8 +9,8 @@ enum class ConnectionState { DISCONNECTED, CONNECTING, CONNECTED, FAILED }
|
||||
/**
|
||||
* Wire protocol shared by all transports: one JSON object per message.
|
||||
* Game messages travel inside [SignedMsg] once the handshake is done; only
|
||||
* [ProfileMsg] and [PingMsg] are sent in the clear. Bump [PROTOCOL_VERSION] on any
|
||||
* incompatible change: peers with an older version are rejected during the handshake.
|
||||
* [ProfileMsg] and [PingMsg] are sent in the clear. [PROTOCOL_VERSION] is sent in the
|
||||
* profile for information only; peers are not rejected by version.
|
||||
*/
|
||||
sealed class GameMessage {
|
||||
data class MoveMsg(
|
||||
@@ -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") },
|
||||
|
||||
@@ -3,6 +3,7 @@ package cc.skysparkle.matewave.network
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.collectLatest
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/** Periodic ping that detects a silently dropped connection. */
|
||||
@@ -35,38 +36,31 @@ class Heartbeat(
|
||||
}
|
||||
}
|
||||
|
||||
// Sleeps while disconnected; every new connection starts with fresh timestamps.
|
||||
job = scope.launch {
|
||||
var wasConnected = false
|
||||
while (true) {
|
||||
delay(INTERVAL_MS)
|
||||
val connected = transport.connectionState.value == ConnectionState.CONNECTED
|
||||
if (!connected) {
|
||||
wasConnected = false
|
||||
continue
|
||||
}
|
||||
if (!wasConnected) {
|
||||
transport.connectionState.collectLatest { state ->
|
||||
if (state != ConnectionState.CONNECTED) return@collectLatest
|
||||
lastReplyAt = System.currentTimeMillis()
|
||||
lastTrafficAt = lastReplyAt
|
||||
while (true) {
|
||||
val now = System.currentTimeMillis()
|
||||
lastReplyAt = now
|
||||
lastTrafficAt = now
|
||||
wasConnected = true
|
||||
}
|
||||
val now = System.currentTimeMillis()
|
||||
val silence = now - lastReplyAt
|
||||
val silence = now - lastReplyAt
|
||||
|
||||
if (silence > TIMEOUT_MS && now - lastTrafficAt > TIMEOUT_MS) {
|
||||
NetworkLog.reason(
|
||||
transport.type.name,
|
||||
DisconnectReason.REMOTE_DISCONNECTED,
|
||||
"no reply for ${silence / 1000} s"
|
||||
)
|
||||
transport.disconnect()
|
||||
continue
|
||||
if (silence > TIMEOUT_MS && now - lastTrafficAt > TIMEOUT_MS) {
|
||||
NetworkLog.reason(
|
||||
transport.type.name,
|
||||
DisconnectReason.REMOTE_DISCONNECTED,
|
||||
"no reply for ${silence / 1000} s"
|
||||
)
|
||||
transport.disconnect()
|
||||
} else {
|
||||
if (silence > TIMEOUT_MS) {
|
||||
NetworkLog.log(transport.type.name, "No heartbeat reply for ${silence / 1000} s, but data is flowing")
|
||||
}
|
||||
transport.send(GameMessage.PingMsg(reply = false, sessionId = sessionId))
|
||||
}
|
||||
delay(INTERVAL_MS)
|
||||
}
|
||||
|
||||
if (silence > TIMEOUT_MS) {
|
||||
NetworkLog.log(transport.type.name, "No heartbeat reply for ${silence / 1000} s, but data is flowing")
|
||||
}
|
||||
transport.send(GameMessage.PingMsg(reply = false, sessionId = sessionId))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,8 +29,14 @@ data class LanPeer(
|
||||
val fingerprint: String = "",
|
||||
|
||||
val signature: String = "",
|
||||
/** When the announcement was signed, in epoch seconds; 0 if the peer sent none. */
|
||||
val signedAtSeconds: Long = 0,
|
||||
/** 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"
|
||||
}
|
||||
@@ -53,12 +59,24 @@ class LanTransport(
|
||||
|
||||
const val MAX_MESSAGE_CHARS = 1_400_000
|
||||
|
||||
const val ACCEPT_POLL_MS = 1_000
|
||||
|
||||
const val RESOLVE_RETRY_MS = 400L
|
||||
|
||||
fun presencePayload(playerId: String, name: String, elo: Int): String =
|
||||
"presence|$playerId|$name|$elo"
|
||||
/**
|
||||
* Signed presence announcement. The signing time is part of it, so a recorded
|
||||
* announcement stops being accepted after [PRESENCE_MAX_AGE_MS]; older versions, which
|
||||
* signed without it, are no longer accepted at all.
|
||||
*/
|
||||
fun presencePayload(playerId: String, name: String, elo: Int, signedAtSeconds: Long): String =
|
||||
"presence2|$playerId|$name|$elo|$signedAtSeconds"
|
||||
|
||||
/** How old (or how far ahead, for a clock set wrong) a signed announcement may be. */
|
||||
const val PRESENCE_MAX_AGE_MS = 15 * 60_000L
|
||||
|
||||
/** The announcement is signed anew this often, well within [PRESENCE_MAX_AGE_MS]. */
|
||||
const val PRESENCE_RESIGN_MS = 5 * 60_000L
|
||||
|
||||
fun isFreshPresence(signedAtSeconds: Long, nowMs: Long): Boolean =
|
||||
signedAtSeconds > 0 && kotlin.math.abs(nowMs - signedAtSeconds * 1000L) <= PRESENCE_MAX_AGE_MS
|
||||
}
|
||||
|
||||
override val type = TransportType.LAN
|
||||
@@ -70,7 +88,8 @@ class LanTransport(
|
||||
context.getSystemService(Context.NSD_SERVICE) as? NsdManager
|
||||
|
||||
private var serverSocket: ServerSocket? = null
|
||||
private var socket: Socket? = null
|
||||
// Written by the connect and accept paths, read by the writer coroutine.
|
||||
@Volatile private var socket: Socket? = null
|
||||
|
||||
private val socketLock = Any()
|
||||
|
||||
@@ -80,7 +99,7 @@ class LanTransport(
|
||||
socket = candidate
|
||||
true
|
||||
}
|
||||
private var output: OutputStream? = null
|
||||
@Volatile private var output: OutputStream? = null
|
||||
private val dispatcher = MessageDispatcher()
|
||||
|
||||
@Volatile private var hosting = false
|
||||
@@ -89,6 +108,9 @@ class LanTransport(
|
||||
|
||||
private var registeredServiceName: String? = null
|
||||
|
||||
// Re-signs the announcement before it gets too old to be accepted.
|
||||
private var resignJob: kotlinx.coroutines.Job? = null
|
||||
|
||||
private val ownServiceName: String by lazy {
|
||||
val fingerprint = cc.skysparkle.matewave.security.DeviceKeys.publicKeyFingerprint(context)
|
||||
?: cc.skysparkle.matewave.data.DeviceIdentity.deviceId(context).take(12)
|
||||
@@ -104,9 +126,6 @@ class LanTransport(
|
||||
private val resolveQueue = java.util.ArrayDeque<Pair<Int, NsdServiceInfo>>()
|
||||
private var resolving = false
|
||||
|
||||
var lastError: String? = null
|
||||
private set
|
||||
|
||||
private val outbox = Channel<String>(capacity = Channel.UNLIMITED)
|
||||
private var writerStarted = false
|
||||
|
||||
@@ -150,13 +169,12 @@ class LanTransport(
|
||||
|
||||
server.bind(InetSocketAddress(0))
|
||||
|
||||
server.soTimeout = ACCEPT_POLL_MS
|
||||
// accept() blocks until a peer connects; shutdown() closes the socket to end it.
|
||||
synchronized(presenceLock) { serverSocket = server; presenceStarting = false }
|
||||
if (announceAllowed()) registerService(server.localPort)
|
||||
acceptLoop(server)
|
||||
} catch (e: IOException) {
|
||||
synchronized(presenceLock) { presenceStarting = false }
|
||||
lastError = "Could not open port: ${e.message}"
|
||||
NetworkLog.reason("LAN", DisconnectReason.PORT_BUSY, e.message)
|
||||
}
|
||||
}
|
||||
@@ -182,8 +200,6 @@ class LanTransport(
|
||||
continue
|
||||
}
|
||||
onConnected(client)
|
||||
} catch (e: java.net.SocketTimeoutException) {
|
||||
continue
|
||||
} catch (e: IOException) {
|
||||
if (server.isClosed) return
|
||||
NetworkLog.log("LAN", "Accept failed: ${e.message}")
|
||||
@@ -195,7 +211,6 @@ class LanTransport(
|
||||
override fun startHosting() {
|
||||
hosting = true
|
||||
_connectionState.value = ConnectionState.CONNECTING
|
||||
lastError = null
|
||||
|
||||
val port = serverSocket?.localPort
|
||||
if (port != null) registerService(port) else startPresence()
|
||||
@@ -216,14 +231,17 @@ class LanTransport(
|
||||
val profile = cc.skysparkle.matewave.data.ProfileStore.get()
|
||||
runCatching {
|
||||
val shownName = profile.name.take(40)
|
||||
val signedAt = System.currentTimeMillis() / 1000L
|
||||
setAttribute("id", profile.userId)
|
||||
setAttribute("name", shownName)
|
||||
setAttribute("elo", profile.elo.toString())
|
||||
setAttribute("fp", cc.skysparkle.matewave.security.DeviceKeys.publicKeyFingerprint(context) ?: "")
|
||||
setAttribute("ts", signedAt.toString())
|
||||
|
||||
cc.skysparkle.matewave.security.DeviceKeys.sign(
|
||||
context, presencePayload(profile.userId, shownName, profile.elo)
|
||||
context, presencePayload(profile.userId, shownName, profile.elo, signedAt)
|
||||
)?.let { setAttribute("sig", it) }
|
||||
cc.skysparkle.matewave.spectate.SpectatorAdvert.attributes().forEach { (key, value) -> setAttribute(key, value) }
|
||||
}
|
||||
}
|
||||
val listener = object : NsdManager.RegistrationListener {
|
||||
@@ -231,20 +249,28 @@ class LanTransport(
|
||||
registeredServiceName = info?.serviceName
|
||||
}
|
||||
override fun onRegistrationFailed(info: NsdServiceInfo?, errorCode: Int) {
|
||||
lastError = "Network service registration failed (code $errorCode). Connect by address manually."
|
||||
NetworkLog.log("LAN", "Service registration failed, code $errorCode")
|
||||
if (registrationListener === this) registrationListener = null
|
||||
}
|
||||
override fun onServiceUnregistered(info: NsdServiceInfo?) {}
|
||||
override fun onUnregistrationFailed(info: NsdServiceInfo?, errorCode: Int) {}
|
||||
override fun onUnregistrationFailed(info: NsdServiceInfo?, errorCode: Int) {
|
||||
NetworkLog.log("LAN", "Service unregistration failed, code $errorCode")
|
||||
}
|
||||
}
|
||||
registrationListener = listener
|
||||
try {
|
||||
nsd.registerService(info, NsdManager.PROTOCOL_DNS_SD, listener)
|
||||
} catch (e: Exception) {
|
||||
lastError = "Service registration: ${e.message}"
|
||||
} catch (_: Exception) {
|
||||
}
|
||||
resignJob = scope.launch {
|
||||
kotlinx.coroutines.delay(PRESENCE_RESIGN_MS)
|
||||
republishProfile()
|
||||
}
|
||||
}
|
||||
|
||||
private fun unregisterService() {
|
||||
resignJob?.cancel()
|
||||
resignJob = null
|
||||
val nsd = nsdManager ?: return
|
||||
registrationListener?.let {
|
||||
try { nsd.unregisterService(it) } catch (_: Exception) {}
|
||||
@@ -285,8 +311,8 @@ class LanTransport(
|
||||
|
||||
override fun onDiscoveryStopped(serviceType: String?) {}
|
||||
override fun onStartDiscoveryFailed(serviceType: String?, errorCode: Int) {
|
||||
lastError = "Network discovery failed (code $errorCode). Enter the address manually."
|
||||
NetworkLog.log("LAN", "Network discovery failed to start, code $errorCode")
|
||||
if (discoveryListener === this) discoveryListener = null
|
||||
}
|
||||
override fun onStopDiscoveryFailed(serviceType: String?, errorCode: Int) {}
|
||||
}
|
||||
@@ -294,8 +320,8 @@ class LanTransport(
|
||||
try {
|
||||
nsd.discoverServices(SERVICE_TYPE, NsdManager.PROTOCOL_DNS_SD, listener)
|
||||
} catch (e: Exception) {
|
||||
lastError = "Network discovery: ${e.message}"
|
||||
NetworkLog.log("LAN", "Network discovery: ${e.message}")
|
||||
discoveryListener = null
|
||||
}
|
||||
}
|
||||
|
||||
@@ -353,6 +379,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 +390,10 @@ class LanTransport(
|
||||
|
||||
fingerprint = attr("fp").ifEmpty { fingerprintFromServiceName(info.serviceName ?: "") ?: "" },
|
||||
signature = attr("sig"),
|
||||
serviceName = info.serviceName ?: ""
|
||||
signedAtSeconds = attr("ts").toLongOrNull() ?: 0,
|
||||
serviceName = info.serviceName ?: "",
|
||||
gameTag = game.gameTag,
|
||||
spectatePort = game.spectatePort
|
||||
)
|
||||
}
|
||||
|
||||
@@ -378,9 +408,12 @@ class LanTransport(
|
||||
|
||||
if (serviceName == ownServiceName) return true
|
||||
|
||||
return Regex("^${Regex.escape(ownServiceName)} \\(\\d+\\)$").matches(serviceName)
|
||||
return renamedOwnService.matches(serviceName)
|
||||
}
|
||||
|
||||
/** Our own service after NSD renamed it on a clash, e.g. "ChessApp-ab12 (2)". */
|
||||
private val renamedOwnService: Regex by lazy { Regex("^${Regex.escape(ownServiceName)} \\(\\d+\\)$") }
|
||||
|
||||
private fun isSelfEndpoint(host: String, port: Int): Boolean {
|
||||
val ourPort = serverSocket?.localPort ?: return false
|
||||
if (port != ourPort) return false
|
||||
@@ -476,14 +509,12 @@ class LanTransport(
|
||||
val host = targetId.substringBeforeLast(':', targetId).trim()
|
||||
|
||||
val port = targetId.substringAfterLast(':', "").toIntOrNull() ?: run {
|
||||
lastError = "Address must look like 192.168.1.5:port"
|
||||
NetworkLog.reason("LAN", DisconnectReason.PEER_NOT_FOUND)
|
||||
_connectionState.value = ConnectionState.FAILED
|
||||
return
|
||||
}
|
||||
|
||||
_connectionState.value = ConnectionState.CONNECTING
|
||||
lastError = null
|
||||
scope.launch(Dispatchers.IO) {
|
||||
try {
|
||||
val s = Socket()
|
||||
@@ -500,8 +531,7 @@ class LanTransport(
|
||||
return@launch
|
||||
}
|
||||
onConnected(s)
|
||||
} catch (e: IOException) {
|
||||
lastError = "Could not connect to $host:$port: ${e.message}"
|
||||
} catch (_: IOException) {
|
||||
NetworkLog.reason("LAN", DisconnectReason.CONNECT_TIMEOUT, "$host:$port")
|
||||
_connectionState.value = ConnectionState.FAILED
|
||||
}
|
||||
@@ -517,7 +547,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) {
|
||||
@@ -552,6 +582,12 @@ class LanTransport(
|
||||
if (wasCurrent) {
|
||||
hosting = false
|
||||
onHostingEnded()
|
||||
var dropped = 0
|
||||
while (outbox.tryReceive().isSuccess) dropped++
|
||||
if (dropped > 0) {
|
||||
repeat(dropped) { NetworkMetrics.messageDropped() }
|
||||
NetworkLog.log("LAN", "Dropped unsent messages after disconnect: $dropped")
|
||||
}
|
||||
_connectionState.value = ConnectionState.DISCONNECTED
|
||||
}
|
||||
}
|
||||
@@ -577,28 +613,12 @@ 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) {
|
||||
if (_connectionState.value != ConnectionState.CONNECTED) {
|
||||
NetworkMetrics.messageDropped()
|
||||
NetworkLog.log("LAN", "Message not queued: TCP session is not connected")
|
||||
return
|
||||
}
|
||||
val json = message.toJson()
|
||||
val size = json.length
|
||||
if (size > MAX_MESSAGE_CHARS) {
|
||||
|
||||
@@ -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())
|
||||
}
|
||||
}
|
||||
@@ -18,8 +18,4 @@ class MessageDispatcher {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun clear() {
|
||||
listeners.clear()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
package cc.skysparkle.matewave.network
|
||||
|
||||
import android.util.Log
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
|
||||
enum class DisconnectReason(val userText: String, val textRes: Int) {
|
||||
NONE("—", cc.skysparkle.matewave.R.string.reason_unknown),
|
||||
PERMISSION_DENIED("No nearby devices permission", cc.skysparkle.matewave.R.string.reason_permission_denied),
|
||||
BLUETOOTH_OFF("Bluetooth is off", cc.skysparkle.matewave.R.string.reason_bluetooth_off),
|
||||
WIFI_UNAVAILABLE("Phone is not connected to Wi-Fi", cc.skysparkle.matewave.R.string.reason_wifi_unavailable),
|
||||
PEER_NOT_FOUND("Opponent not found", cc.skysparkle.matewave.R.string.reason_peer_not_found),
|
||||
CONNECT_TIMEOUT("Opponent did not respond in time", cc.skysparkle.matewave.R.string.reason_connect_timeout),
|
||||
SERVICE_NOT_FOUND("The other device does not have this app", cc.skysparkle.matewave.R.string.reason_service_not_found),
|
||||
@@ -16,38 +15,20 @@ enum class DisconnectReason(val userText: String, val textRes: Int) {
|
||||
WRITE_FAILED("Could not send data", cc.skysparkle.matewave.R.string.reason_write_failed),
|
||||
MESSAGE_TOO_LARGE("Received message is too large", cc.skysparkle.matewave.R.string.reason_message_too_large),
|
||||
REMOTE_DISCONNECTED("Opponent disconnected", cc.skysparkle.matewave.R.string.reason_remote_disconnected),
|
||||
PORT_BUSY("Could not open port", cc.skysparkle.matewave.R.string.reason_port_busy),
|
||||
UNKNOWN("Unknown connection error", cc.skysparkle.matewave.R.string.reason_unknown)
|
||||
PORT_BUSY("Could not open port", cc.skysparkle.matewave.R.string.reason_port_busy)
|
||||
}
|
||||
|
||||
data class NetworkEvent(
|
||||
val at: Long,
|
||||
val transport: String,
|
||||
val text: String
|
||||
)
|
||||
|
||||
/** In-memory connection log, copied into the diagnostics report from Settings. */
|
||||
object NetworkLog {
|
||||
private const val CAPACITY = 60
|
||||
|
||||
private val _events = MutableStateFlow<List<NetworkEvent>>(emptyList())
|
||||
|
||||
private val _lastReason = MutableStateFlow(DisconnectReason.NONE)
|
||||
val lastReason: StateFlow<DisconnectReason> = _lastReason
|
||||
|
||||
/** Debug output only: release builds strip Log.d (see proguard-rules.pro). */
|
||||
fun log(transport: String, text: String) {
|
||||
val event = NetworkEvent(System.currentTimeMillis(), transport, text)
|
||||
_events.update { (it + event).takeLast(CAPACITY) }
|
||||
Log.d("Matewave/$transport", text)
|
||||
}
|
||||
|
||||
fun reason(transport: String, reason: DisconnectReason, detail: String? = null) {
|
||||
_lastReason.value = reason
|
||||
log(transport, reason.userText + (detail?.let { ": $it" } ?: ""))
|
||||
}
|
||||
|
||||
fun asText(): String = _events.value.joinToString("\n") { e ->
|
||||
val time = java.text.SimpleDateFormat("HH:mm:ss", java.util.Locale.getDefault())
|
||||
.format(java.util.Date(e.at))
|
||||
"$time [${e.transport}] ${e.text}"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,22 +37,4 @@ object NetworkMetrics {
|
||||
fun duplicateChunk() { duplicateChunks.incrementAndGet() }
|
||||
fun messageCorrupted() { corruptedMessages.incrementAndGet(); touch() }
|
||||
fun messageDropped() { messagesDropped.incrementAndGet(); touch() }
|
||||
|
||||
private fun retryPercent(): Int {
|
||||
val sent = chunksSent.get()
|
||||
if (sent == 0L) return 0
|
||||
return ((chunkRetries.get() * 100) / sent).toInt()
|
||||
}
|
||||
|
||||
fun asText(res: android.content.res.Resources): String = buildString {
|
||||
appendLine(res.getString(cc.skysparkle.matewave.R.string.metrics_connect_attempts,
|
||||
connectAttempts.get(), connectSuccesses.get()))
|
||||
val last = lastConnectMillis.get()
|
||||
if (last > 0) appendLine(res.getString(cc.skysparkle.matewave.R.string.metrics_last_connect, last))
|
||||
appendLine(res.getString(cc.skysparkle.matewave.R.string.metrics_chunks,
|
||||
chunksSent.get(), chunkRetries.get(), retryPercent()))
|
||||
appendLine(res.getString(cc.skysparkle.matewave.R.string.metrics_duplicates, duplicateChunks.get()))
|
||||
appendLine(res.getString(cc.skysparkle.matewave.R.string.metrics_corrupted, corruptedMessages.get()))
|
||||
appendLine(res.getString(cc.skysparkle.matewave.R.string.metrics_dropped, messagesDropped.get()))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,16 +14,7 @@ data class NetworkStatus(
|
||||
val wifiConnected: Boolean,
|
||||
val permissionsGranted: Boolean,
|
||||
val notificationsGranted: Boolean
|
||||
) {
|
||||
val bluetoothReady: Boolean
|
||||
get() = bluetoothSupported && bluetoothOn && permissionsGranted
|
||||
|
||||
val lanReady: Boolean get() = wifiConnected
|
||||
|
||||
val anyChannelReady: Boolean get() = bluetoothReady || lanReady
|
||||
|
||||
val onlineBlocked: Boolean get() = !anyChannelReady
|
||||
}
|
||||
)
|
||||
|
||||
object NetworkRequirements {
|
||||
fun check(context: Context): NetworkStatus {
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
package cc.skysparkle.matewave.network
|
||||
|
||||
/** Bounds for what another device may send us; anything outside them is not stored or used. */
|
||||
object PeerLimits {
|
||||
const val MAX_NAME_CHARS = 40
|
||||
const val MAX_USER_ID_CHARS = 64
|
||||
const val MIN_ELO = 100
|
||||
const val MAX_ELO = 3000
|
||||
const val MAX_INITIAL_SECONDS = 3 * 60 * 60
|
||||
const val MAX_INCREMENT_SECONDS = 180
|
||||
|
||||
/** "No time limit" is sent as Int.MAX_VALUE; 0 means the peer sent no time control. */
|
||||
private fun isTimeControl(initialSeconds: Int, incrementSeconds: Int): Boolean =
|
||||
(initialSeconds == 0 || initialSeconds == Int.MAX_VALUE || initialSeconds in 1..MAX_INITIAL_SECONDS) &&
|
||||
incrementSeconds in 0..MAX_INCREMENT_SECONDS
|
||||
|
||||
fun isPlausibleName(name: String): Boolean =
|
||||
name.isNotBlank() && name.length <= MAX_NAME_CHARS && name.none { it.isISOControl() }
|
||||
|
||||
fun isPlausibleUserId(userId: String): Boolean =
|
||||
userId.isNotBlank() && userId.length <= MAX_USER_ID_CHARS && userId.none { it.isISOControl() }
|
||||
|
||||
/**
|
||||
* Checked before the profile is trusted or stored. The fields are signed as they are, so an
|
||||
* out-of-range profile is refused rather than trimmed.
|
||||
*/
|
||||
fun isPlausibleProfile(msg: GameMessage.ProfileMsg): Boolean =
|
||||
isPlausibleUserId(msg.userId) &&
|
||||
isPlausibleName(msg.name) &&
|
||||
msg.elo in MIN_ELO..MAX_ELO &&
|
||||
isTimeControl(msg.initialSeconds, msg.incrementSeconds)
|
||||
|
||||
/**
|
||||
* The most the opponent's clock may show after their move: what our clock gives them, plus
|
||||
* the increment and some slack for network delay. A higher claim would mean time not spent.
|
||||
*/
|
||||
fun maxOpponentClockAfterMove(localRemainingMs: Long, incrementMs: Long, toleranceMs: Long): Long =
|
||||
localRemainingMs.coerceAtLeast(0) + incrementMs + toleranceMs
|
||||
}
|
||||
@@ -9,9 +9,8 @@ data class OpeningName(val eco: String, val name: String)
|
||||
* deviations, and opening names from lichess-org/chess-openings (CC0). Both are keyed by SAN move
|
||||
* sequences from the standard starting position, so no position hashing is needed at runtime.
|
||||
*
|
||||
* explorer.txt: header "#games N", then one node per line "parentId san white draws black";
|
||||
* node ids are line numbers (the root is 0) and parents always come before children. Only the
|
||||
* tree shape is used here.
|
||||
* explorer.txt: header "#games N", then one node per line "parentId san"; node ids are line
|
||||
* numbers (the root is 0) and parents always come before children.
|
||||
*/
|
||||
object OpeningBook {
|
||||
|
||||
|
||||
@@ -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
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -138,13 +141,19 @@ class LocalPresence(
|
||||
|
||||
val knownKey = knownPeers.publicKeyOf(id)
|
||||
if (knownKey != null) {
|
||||
val authentic = peer.signature.isNotEmpty() && DeviceKeys.verify(
|
||||
knownKey,
|
||||
cc.skysparkle.matewave.network.LanTransport.presencePayload(peer.playerId, peer.displayName, peer.elo),
|
||||
peer.signature
|
||||
)
|
||||
// A known friend must send a fresh announcement signed with their key: an old one
|
||||
// recorded and replayed by someone else is not accepted.
|
||||
val authentic = peer.signature.isNotEmpty() &&
|
||||
cc.skysparkle.matewave.network.LanTransport.isFreshPresence(peer.signedAtSeconds, lastResultAt) &&
|
||||
DeviceKeys.verify(
|
||||
knownKey,
|
||||
cc.skysparkle.matewave.network.LanTransport.presencePayload(
|
||||
peer.playerId, peer.displayName, peer.elo, peer.signedAtSeconds
|
||||
),
|
||||
peer.signature
|
||||
)
|
||||
if (!authentic) {
|
||||
NetworkLog.log("PRESENCE", "Announcement for $id failed signature check, hidden")
|
||||
NetworkLog.log("PRESENCE", "Announcement for $id is stale or failed signature check, hidden")
|
||||
return@forEach
|
||||
}
|
||||
FriendsStore.updateProfile(
|
||||
@@ -159,7 +168,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
|
||||
|
||||
@@ -9,8 +9,7 @@ data class Puzzle(
|
||||
val theme: String,
|
||||
val fen: String,
|
||||
val solutionUci: List<String>,
|
||||
val rating: Int,
|
||||
val themes: List<String> = emptyList()
|
||||
val rating: Int
|
||||
)
|
||||
|
||||
/** Localized name of the puzzle theme, shown as the screen title. */
|
||||
@@ -59,16 +58,13 @@ object PuzzleRepository {
|
||||
val o = arr.getJSONObject(i)
|
||||
val solutionArr = o.getJSONArray("solution")
|
||||
val solution = (0 until solutionArr.length()).map { solutionArr.getString(it) }
|
||||
val themesArr = o.optJSONArray("themes")
|
||||
val themes = themesArr?.let { t -> (0 until t.length()).map { t.getString(it) } } ?: emptyList()
|
||||
result.add(
|
||||
Puzzle(
|
||||
id = o.getInt("id"),
|
||||
theme = o.optString("theme", "tactic"),
|
||||
fen = o.getString("fen"),
|
||||
solutionUci = solution,
|
||||
rating = o.getInt("rating"),
|
||||
themes = themes
|
||||
rating = o.getInt("rating")
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -108,7 +108,7 @@ object DeviceKeys {
|
||||
fun fingerprintOf(publicKey: String): String =
|
||||
MessageDigest.getInstance("SHA-256")
|
||||
.digest(publicKey.toByteArray(Charsets.UTF_8))
|
||||
.take(16).joinToString("") { "%02x".format(it) }
|
||||
.toHex(16)
|
||||
|
||||
fun sign(context: Context, data: String): String? {
|
||||
val privateKey: PrivateKey = keyPair(context)?.private ?: return null
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
package cc.skysparkle.matewave.security
|
||||
|
||||
private const val HEX_DIGITS = "0123456789abcdef"
|
||||
|
||||
/** Lowercase hex of the first [count] bytes. */
|
||||
internal fun ByteArray.toHex(count: Int = size): String {
|
||||
val n = minOf(count, size)
|
||||
val out = CharArray(n * 2)
|
||||
for (i in 0 until n) {
|
||||
val v = this[i].toInt() and 0xFF
|
||||
out[i * 2] = HEX_DIGITS[v ushr 4]
|
||||
out[i * 2 + 1] = HEX_DIGITS[v and 0x0F]
|
||||
}
|
||||
return String(out)
|
||||
}
|
||||
@@ -79,7 +79,7 @@ class KnownPeers(context: Context) {
|
||||
if (value.isNullOrEmpty()) return ""
|
||||
return java.security.MessageDigest.getInstance("SHA-256")
|
||||
.digest(value.toByteArray(Charsets.UTF_8))
|
||||
.take(8).joinToString("") { "%02x".format(it) }
|
||||
.toHex(8)
|
||||
}
|
||||
|
||||
/** Forgets every pinned key, e.g. after opponents reinstalled the app. */
|
||||
|
||||
@@ -6,8 +6,10 @@ import android.net.Uri
|
||||
|
||||
/** External links of the app, kept in one place. */
|
||||
object AppLinks {
|
||||
const val REPOSITORY = "https://git.skysparkle.cc/kalarina/Matewave"
|
||||
const val REPOSITORY_LABEL = "git.skysparkle.cc/kalarina/Matewave"
|
||||
const val REPOSITORY = "https://github.com/kalarina-bit/Matewave"
|
||||
const val REPOSITORY_LABEL = "github.com/kalarina-bit/Matewave"
|
||||
const val DONATE = "https://ko-fi.com/skysparkle"
|
||||
const val DONATE_LABEL = "ko-fi.com/skysparkle"
|
||||
const val PRIVACY_POLICY = "https://skysparkle.cc/privacy?lang=en"
|
||||
|
||||
/** Opens a link in the browser; does nothing if no app can open it. */
|
||||
|
||||
@@ -25,21 +25,21 @@ object Haptics {
|
||||
}
|
||||
}
|
||||
|
||||
fun select() = play(Build.VERSION_CODES.Q, predefined = VibrationEffect.EFFECT_TICK, fallbackMs = 8)
|
||||
fun select() = play(VibrationEffect.EFFECT_TICK, fallbackMs = 8)
|
||||
|
||||
fun move() = play(Build.VERSION_CODES.Q, predefined = VibrationEffect.EFFECT_CLICK, fallbackMs = 15)
|
||||
fun move() = play(VibrationEffect.EFFECT_CLICK, fallbackMs = 15)
|
||||
|
||||
fun capture() = play(Build.VERSION_CODES.Q, predefined = VibrationEffect.EFFECT_HEAVY_CLICK, fallbackMs = 25)
|
||||
fun capture() = play(VibrationEffect.EFFECT_HEAVY_CLICK, fallbackMs = 25)
|
||||
|
||||
fun alert() = play(Build.VERSION_CODES.Q, predefined = VibrationEffect.EFFECT_DOUBLE_CLICK, fallbackMs = 40)
|
||||
fun alert() = play(VibrationEffect.EFFECT_DOUBLE_CLICK, fallbackMs = 40)
|
||||
|
||||
private fun play(minApiForPredefined: Int, predefined: Int, fallbackMs: Long) {
|
||||
private fun play(predefined: Int, fallbackMs: Long) {
|
||||
val context = appContext ?: return
|
||||
val v = vibrator ?: return
|
||||
if (!v.hasVibrator()) return
|
||||
if (!FeedbackSettings(context).vibrationEnabled) return
|
||||
runCatching {
|
||||
val effect = if (Build.VERSION.SDK_INT >= minApiForPredefined) {
|
||||
val effect = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
VibrationEffect.createPredefined(predefined)
|
||||
} else {
|
||||
VibrationEffect.createOneShot(fallbackMs, VibrationEffect.DEFAULT_AMPLITUDE)
|
||||
|
||||
@@ -5,10 +5,12 @@ import java.io.File
|
||||
import java.io.IOException
|
||||
import java.io.OutputStream
|
||||
import java.net.Inet4Address
|
||||
import java.net.InetSocketAddress
|
||||
import java.net.NetworkInterface
|
||||
import java.net.ServerSocket
|
||||
import java.net.Socket
|
||||
import java.util.Locale
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
import kotlin.concurrent.thread
|
||||
|
||||
class ApkShareServer(private val apk: File, private val appName: String) {
|
||||
@@ -17,8 +19,13 @@ class ApkShareServer(private val apk: File, private val appName: String) {
|
||||
@Volatile
|
||||
private var server: ServerSocket? = null
|
||||
|
||||
private val activeClients = AtomicInteger()
|
||||
|
||||
/** Listens on the Wi-Fi address only (all interfaces if none is found), so the APK is not served elsewhere. */
|
||||
fun start(): Int {
|
||||
val socket = ServerSocket(0)
|
||||
val socket = ServerSocket()
|
||||
socket.reuseAddress = true
|
||||
socket.bind(InetSocketAddress(LocalNetwork.wifiInet4(), 0))
|
||||
server = socket
|
||||
thread(name = "apk-share-accept", isDaemon = true) {
|
||||
while (!socket.isClosed) {
|
||||
@@ -27,7 +34,19 @@ class ApkShareServer(private val apk: File, private val appName: String) {
|
||||
} catch (e: IOException) {
|
||||
break
|
||||
}
|
||||
thread(name = "apk-share-client", isDaemon = true) { serve(client) }
|
||||
// A handful of downloads at a time is plenty; more connections are refused.
|
||||
if (activeClients.incrementAndGet() > MAX_CLIENTS) {
|
||||
activeClients.decrementAndGet()
|
||||
runCatching { client.close() }
|
||||
continue
|
||||
}
|
||||
thread(name = "apk-share-client", isDaemon = true) {
|
||||
try {
|
||||
serve(client)
|
||||
} finally {
|
||||
activeClients.decrementAndGet()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return socket.localPort
|
||||
@@ -78,6 +97,10 @@ class ApkShareServer(private val apk: File, private val appName: String) {
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val MAX_CLIENTS = 4
|
||||
}
|
||||
|
||||
private fun sendText(out: OutputStream, code: Int, reason: String, text: String, withBody: Boolean) {
|
||||
val body = text.toByteArray(Charsets.UTF_8)
|
||||
writeHeader(out, code, reason, "text/plain; charset=utf-8", body.size.toLong())
|
||||
@@ -117,12 +140,13 @@ class ApkShareServer(private val apk: File, private val appName: String) {
|
||||
object LocalNetwork {
|
||||
private val WIFI_PREFIXES = listOf("wlan", "swlan", "ap", "softap", "eth")
|
||||
|
||||
fun wifiIpv4(): String? = runCatching {
|
||||
fun wifiInet4(): Inet4Address? = runCatching {
|
||||
NetworkInterface.getNetworkInterfaces()?.toList().orEmpty()
|
||||
.filter { nif -> nif.isUp && !nif.isLoopback && WIFI_PREFIXES.any { nif.name.startsWith(it) } }
|
||||
.flatMap { nif -> nif.inetAddresses.toList() }
|
||||
.filterIsInstance<Inet4Address>()
|
||||
.firstOrNull { it.isSiteLocalAddress }
|
||||
?.hostAddress
|
||||
}.getOrNull()
|
||||
|
||||
fun wifiIpv4(): String? = wifiInet4()?.hostAddress
|
||||
}
|
||||
|
||||
@@ -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,49 @@
|
||||
package cc.skysparkle.matewave.spectate
|
||||
|
||||
import cc.skysparkle.matewave.security.toHex
|
||||
|
||||
/**
|
||||
* 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.toHex(4)
|
||||
}
|
||||
|
||||
private val TAG_PATTERN = Regex("^[0-9a-f]{8}$")
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
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 }
|
||||
|
||||
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) {
|
||||
if (message is SpectatorMessage.Reject) {
|
||||
emit(Event.JoinFailed(failureOf(message)))
|
||||
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.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,154 @@
|
||||
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 = Notation.fromUci(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 = Notation.fromUci(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)
|
||||
}
|
||||
}
|
||||
|
||||
/** 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,357 @@
|
||||
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 -> { 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,245 @@
|
||||
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"),
|
||||
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 {
|
||||
/** Sent with every message for information only; no version is ever refused. */
|
||||
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)
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,6 @@ package cc.skysparkle.matewave.ui.components
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.BitmapFactory
|
||||
import android.util.DisplayMetrics
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Box
|
||||
@@ -14,12 +13,20 @@ import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.draw.drawWithCache
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.graphics.Brush
|
||||
import androidx.compose.ui.graphics.ColorFilter
|
||||
import androidx.compose.ui.graphics.ColorMatrix
|
||||
import androidx.compose.ui.graphics.ImageBitmap
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import cc.skysparkle.matewave.R
|
||||
import cc.skysparkle.matewave.ui.theme.AppBackground
|
||||
import cc.skysparkle.matewave.ui.theme.AppThemeState
|
||||
import cc.skysparkle.matewave.ui.theme.ChessGreen
|
||||
import cc.skysparkle.matewave.ui.theme.Lime
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
@@ -32,7 +39,7 @@ private object BackgroundAssetCache {
|
||||
bitmap?.let { return it }
|
||||
synchronized(this) {
|
||||
bitmap?.let { return it }
|
||||
val metrics: DisplayMetrics = context.resources.displayMetrics
|
||||
val metrics = context.resources.displayMetrics
|
||||
val target = maxOf(metrics.widthPixels, metrics.heightPixels).coerceAtLeast(1)
|
||||
|
||||
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
@@ -55,10 +62,28 @@ private object BackgroundAssetCache {
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun AppBackgroundImage(modifier: Modifier = Modifier.fillMaxSize()) {
|
||||
val context = LocalContext.current
|
||||
/** Slight green cast so the grey mist matches the accent colours. */
|
||||
private val ForestTint = ColorFilter.colorMatrix(
|
||||
ColorMatrix(
|
||||
floatArrayOf(
|
||||
0.80f, 0f, 0f, 0f, 0f,
|
||||
0f, 0.95f, 0f, 0f, 6f,
|
||||
0f, 0f, 0.85f, 0f, 2f,
|
||||
0f, 0f, 0f, 1f, 0f
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
/** For the other styles the forest turns almost grey, so it never fights their colours. */
|
||||
private val NeutralForestTint = ColorFilter.colorMatrix(ColorMatrix().apply { setToSaturation(0.12f) })
|
||||
|
||||
/**
|
||||
* The misty forest artwork, deeply darkened so it reads as texture: the mist stays
|
||||
* visible behind the headings at the top and fades into near-black lower down.
|
||||
*/
|
||||
@Composable
|
||||
fun AppBackdrop() {
|
||||
val context = LocalContext.current
|
||||
var bitmap by remember { mutableStateOf(BackgroundAssetCache.cached()) }
|
||||
|
||||
LaunchedEffect(Unit) {
|
||||
@@ -67,15 +92,42 @@ fun AppBackgroundImage(modifier: Modifier = Modifier.fillMaxSize()) {
|
||||
}
|
||||
}
|
||||
|
||||
val image = bitmap
|
||||
if (image != null) {
|
||||
Image(
|
||||
bitmap = image,
|
||||
contentDescription = null,
|
||||
modifier = modifier,
|
||||
contentScale = ContentScale.Crop
|
||||
Box(modifier = Modifier.fillMaxSize().background(AppBackground)) {
|
||||
bitmap?.let { image ->
|
||||
Image(
|
||||
bitmap = image,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentScale = ContentScale.Crop,
|
||||
colorFilter = if (AppThemeState.palette.greenBackdrop) ForestTint else NeutralForestTint
|
||||
)
|
||||
}
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.drawWithCache {
|
||||
val shade = Brush.verticalGradient(
|
||||
0.00f to AppBackground.copy(alpha = 0.72f),
|
||||
0.30f to AppBackground.copy(alpha = 0.80f),
|
||||
0.60f to AppBackground.copy(alpha = 0.90f),
|
||||
1.00f to AppBackground.copy(alpha = 0.96f)
|
||||
)
|
||||
val glow = Brush.radialGradient(
|
||||
colors = listOf(ChessGreen.copy(alpha = 0.14f), ChessGreen.copy(alpha = 0f)),
|
||||
center = Offset(size.width * 0.9f, 0f),
|
||||
radius = size.maxDimension * 0.5f
|
||||
)
|
||||
val lime = Brush.radialGradient(
|
||||
colors = listOf(Lime.copy(alpha = 0.05f), Lime.copy(alpha = 0f)),
|
||||
center = Offset(0f, size.height),
|
||||
radius = size.maxDimension * 0.45f
|
||||
)
|
||||
onDrawBehind {
|
||||
drawRect(shade)
|
||||
drawRect(glow)
|
||||
drawRect(lime)
|
||||
}
|
||||
}
|
||||
)
|
||||
} else {
|
||||
Box(modifier = modifier.background(Color(0xFF101413)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,39 +3,44 @@ package cc.skysparkle.matewave.ui.components
|
||||
import cc.skysparkle.matewave.ui.theme.ink
|
||||
|
||||
import androidx.compose.animation.animateColorAsState
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.RowScope
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.ColorFilter
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.selected
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.unit.dp
|
||||
import cc.skysparkle.matewave.R
|
||||
import cc.skysparkle.matewave.ui.theme.UiCornerRadius
|
||||
import cc.skysparkle.matewave.ui.theme.FloatingBarFill
|
||||
import cc.skysparkle.matewave.ui.theme.Lime
|
||||
import cc.skysparkle.matewave.ui.theme.OnAccent
|
||||
import cc.skysparkle.matewave.ui.theme.PanelBorder
|
||||
|
||||
enum class BottomTab { HOME, FRIENDS, SETTINGS, ACCOUNT }
|
||||
|
||||
/** Floating pill; the active tab is a lime circle, the others are plain icons. */
|
||||
@Composable
|
||||
fun AppBottomBar(
|
||||
current: BottomTab,
|
||||
@@ -46,108 +51,76 @@ fun AppBottomBar(
|
||||
|
||||
accountAvatarBase64: String? = null
|
||||
) {
|
||||
val shape = RoundedCornerShape(50)
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 24.dp, vertical = 4.dp)
|
||||
.background(cc.skysparkle.matewave.ui.theme.FloatingBarFill, RoundedCornerShape(UiCornerRadius))
|
||||
.padding(vertical = 6.dp),
|
||||
horizontalArrangement = Arrangement.SpaceEvenly
|
||||
) {
|
||||
NavItem(iconRes = R.drawable.ic_home, label = stringResource(R.string.nav_home), active = current == BottomTab.HOME, onClick = onHomeClick)
|
||||
|
||||
NavItem(iconRes = R.drawable.ic_friends, label = stringResource(R.string.nav_friends), active = current == BottomTab.FRIENDS, onClick = onFriendsClick)
|
||||
NavItem(iconRes = R.drawable.ic_settings, label = stringResource(R.string.nav_settings), active = current == BottomTab.SETTINGS, onClick = onSettingsClick)
|
||||
|
||||
AccountNavItem(
|
||||
avatarBase64 = accountAvatarBase64,
|
||||
active = current == BottomTab.ACCOUNT,
|
||||
onClick = onAccountClick
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun RowScope.NavItem(iconRes: Int, label: String, active: Boolean, onClick: () -> Unit) {
|
||||
val shape = RoundedCornerShape(UiCornerRadius)
|
||||
|
||||
val highlight by animateColorAsState(
|
||||
if (active) ink.copy(alpha = 0.14f) else ink.copy(alpha = 0f),
|
||||
animationSpec = tween(220),
|
||||
label = "navHighlight"
|
||||
)
|
||||
val itemColor by animateColorAsState(
|
||||
if (active) ink else ink.copy(alpha = 0.7f),
|
||||
animationSpec = tween(220),
|
||||
label = "navColor"
|
||||
)
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.weight(1f)
|
||||
.padding(horizontal = 24.dp, vertical = 8.dp)
|
||||
.clip(shape)
|
||||
.background(highlight, shape)
|
||||
.clickable(onClick = onClick)
|
||||
.padding(vertical = 8.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally
|
||||
.background(FloatingBarFill)
|
||||
.border(1.dp, PanelBorder, shape)
|
||||
.padding(horizontal = 8.dp, vertical = 8.dp)
|
||||
.height(52.dp),
|
||||
horizontalArrangement = Arrangement.SpaceEvenly,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Image(
|
||||
painter = painterResource(iconRes),
|
||||
contentDescription = null,
|
||||
colorFilter = ColorFilter.tint(itemColor),
|
||||
modifier = Modifier.size(24.dp)
|
||||
)
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
label,
|
||||
color = if (active) itemColor else Color.Transparent,
|
||||
style = MaterialTheme.typography.labelMedium
|
||||
)
|
||||
NavItem(stringResource(R.string.nav_home), current == BottomTab.HOME, onHomeClick) { tint ->
|
||||
AppIcon(R.drawable.ic_home, size = 24.dp, tint = tint)
|
||||
}
|
||||
NavItem(stringResource(R.string.nav_friends), current == BottomTab.FRIENDS, onFriendsClick) { tint ->
|
||||
AppIcon(R.drawable.ic_friends, size = 24.dp, tint = tint)
|
||||
}
|
||||
NavItem(stringResource(R.string.nav_settings), current == BottomTab.SETTINGS, onSettingsClick) { tint ->
|
||||
AppIcon(R.drawable.ic_settings, size = 24.dp, tint = tint)
|
||||
}
|
||||
NavItem(stringResource(R.string.account_title), current == BottomTab.ACCOUNT, onAccountClick) { tint ->
|
||||
val bitmap = rememberChatImage(accountAvatarBase64, AVATAR_MAX_DIMENSION_PX)
|
||||
if (bitmap != null) {
|
||||
Image(
|
||||
bitmap = bitmap,
|
||||
contentDescription = null,
|
||||
contentScale = ContentScale.Crop,
|
||||
modifier = Modifier.size(28.dp).clip(CircleShape)
|
||||
)
|
||||
} else {
|
||||
AppIcon(R.drawable.ic_default_avatar, size = 24.dp, tint = tint)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Every screen has its own bar, so a tab never changes between active and inactive while shown. */
|
||||
@Composable
|
||||
private fun RowScope.AccountNavItem(avatarBase64: String?, active: Boolean, onClick: () -> Unit) {
|
||||
val shape = RoundedCornerShape(UiCornerRadius)
|
||||
val bitmap = rememberChatImage(avatarBase64, AVATAR_MAX_DIMENSION_PX)
|
||||
val highlight by animateColorAsState(
|
||||
if (active) ink.copy(alpha = 0.14f) else ink.copy(alpha = 0f),
|
||||
animationSpec = tween(220),
|
||||
label = "navHighlight"
|
||||
)
|
||||
val itemColor by animateColorAsState(
|
||||
if (active) ink else ink.copy(alpha = 0.7f),
|
||||
animationSpec = tween(220),
|
||||
label = "navColor"
|
||||
)
|
||||
Column(
|
||||
private fun RowScope.NavItem(
|
||||
label: String,
|
||||
active: Boolean,
|
||||
onClick: () -> Unit,
|
||||
icon: @Composable (tint: Color) -> Unit
|
||||
) {
|
||||
val fill by animateColorAsState(if (active) Lime else Lime.copy(alpha = 0f), label = "navFill")
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.weight(1f)
|
||||
.clip(shape)
|
||||
.background(highlight, shape)
|
||||
.clickable(onClick = onClick)
|
||||
.padding(vertical = 8.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally
|
||||
.semantics {
|
||||
contentDescription = label
|
||||
selected = active
|
||||
}
|
||||
.clickable(
|
||||
interactionSource = remember { MutableInteractionSource() },
|
||||
indication = null,
|
||||
role = Role.Tab,
|
||||
onClick = onClick
|
||||
),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
if (bitmap != null) {
|
||||
Image(
|
||||
bitmap = bitmap,
|
||||
contentDescription = null,
|
||||
contentScale = ContentScale.Crop,
|
||||
modifier = Modifier.size(24.dp).clip(CircleShape)
|
||||
)
|
||||
} else {
|
||||
Image(
|
||||
painter = painterResource(R.drawable.ic_default_avatar),
|
||||
contentDescription = null,
|
||||
colorFilter = ColorFilter.tint(itemColor),
|
||||
modifier = Modifier.size(24.dp)
|
||||
)
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.size(52.dp)
|
||||
.clip(CircleShape)
|
||||
.background(fill),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
icon(if (active) OnAccent else ink.copy(alpha = 0.6f))
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
stringResource(R.string.account_title),
|
||||
color = if (active) itemColor else Color.Transparent,
|
||||
style = MaterialTheme.typography.labelMedium
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,6 +22,7 @@ import androidx.compose.ui.window.DialogWindowProvider
|
||||
import cc.skysparkle.matewave.ui.theme.DialogScrimColor
|
||||
import cc.skysparkle.matewave.ui.theme.ink
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
@@ -49,8 +50,8 @@ import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
|
||||
val DialogSurface = Color(0xFF262B29)
|
||||
val DialogAccent = Color(0xFF93DBA3)
|
||||
val DialogSurface: Color get() = cc.skysparkle.matewave.ui.theme.Surface1
|
||||
val DialogAccent: Color get() = cc.skysparkle.matewave.ui.theme.ChessGreen
|
||||
val DialogShape = RoundedCornerShape(28.dp)
|
||||
|
||||
@Composable
|
||||
@@ -115,7 +116,7 @@ fun AppDialog(
|
||||
}
|
||||
.clip(DialogShape)
|
||||
.background(DialogSurface)
|
||||
|
||||
.border(1.dp, cc.skysparkle.matewave.ui.theme.PanelBorder, DialogShape)
|
||||
.clickable(
|
||||
interactionSource = remember { MutableInteractionSource() },
|
||||
indication = null
|
||||
@@ -156,12 +157,11 @@ fun AppDialog(
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun DialogText(text: String, modifier: Modifier = Modifier) {
|
||||
fun DialogText(text: String) {
|
||||
Text(
|
||||
text,
|
||||
color = ink.copy(alpha = 0.78f),
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
modifier = modifier
|
||||
style = MaterialTheme.typography.bodyLarge
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
package cc.skysparkle.matewave.ui.components
|
||||
|
||||
import cc.skysparkle.matewave.ui.theme.ink
|
||||
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.material3.LocalContentColor
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
@@ -17,7 +16,7 @@ import androidx.compose.ui.unit.dp
|
||||
fun AppIcon(
|
||||
resId: Int,
|
||||
size: Dp = 20.dp,
|
||||
tint: Color = ink,
|
||||
tint: Color = LocalContentColor.current,
|
||||
modifier: Modifier = Modifier,
|
||||
contentDescription: String? = null
|
||||
) {
|
||||
@@ -30,6 +29,6 @@ fun AppIcon(
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun ButtonIcon(resId: Int, tint: Color = ink, size: Dp = 18.dp) {
|
||||
fun ButtonIcon(resId: Int, tint: Color = LocalContentColor.current, size: Dp = 18.dp) {
|
||||
AppIcon(resId, size = size, tint = tint, modifier = Modifier.padding(end = 8.dp))
|
||||
}
|
||||
|
||||
@@ -15,9 +15,8 @@ import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.unit.dp
|
||||
import cc.skysparkle.matewave.engine.Piece
|
||||
import cc.skysparkle.matewave.engine.PieceColor
|
||||
import cc.skysparkle.matewave.engine.PieceType
|
||||
|
||||
@@ -25,11 +24,11 @@ import cc.skysparkle.matewave.engine.PieceType
|
||||
fun CapturedPiecesRow(
|
||||
captured: List<PieceType>,
|
||||
capturedColor: PieceColor,
|
||||
advantage: Int,
|
||||
modifier: Modifier = Modifier
|
||||
advantage: Int
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
Row(
|
||||
modifier = modifier.fillMaxWidth().height(22.dp),
|
||||
modifier = Modifier.fillMaxWidth().height(22.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(3.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
@@ -37,7 +36,7 @@ fun CapturedPiecesRow(
|
||||
Row(horizontalArrangement = Arrangement.spacedBy((-10).dp)) {
|
||||
repeat(group.size) {
|
||||
Image(
|
||||
painter = painterResource(Piece(type, capturedColor).drawableRes()),
|
||||
bitmap = PieceImages.of(context, type, capturedColor),
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(20.dp)
|
||||
)
|
||||
|
||||
@@ -109,7 +109,7 @@ fun ChatDialog(
|
||||
},
|
||||
enabled = text.isNotBlank()
|
||||
) {
|
||||
AppIcon(R.drawable.ic_arrow_forward, size = 20.dp)
|
||||
AppIcon(R.drawable.ic_send, size = 20.dp)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,21 +86,46 @@ private object DecodedImageCache {
|
||||
fun put(key: String, bitmap: Bitmap) { cache.put(key, bitmap) }
|
||||
}
|
||||
|
||||
/** Larger images (from the opponent) are refused; ours never exceed [MAX_DIMENSION_PX]. */
|
||||
const val MAX_INCOMING_IMAGE_PX = 4096
|
||||
|
||||
/** Upper bound for the decoded size when the caller does not ask for a smaller one. */
|
||||
private const val DEFAULT_DECODE_PX = 1280
|
||||
|
||||
/** Width and height of an encoded image, or null if it is not a readable image. */
|
||||
private fun imageBounds(bytes: ByteArray): Pair<Int, Int>? {
|
||||
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)
|
||||
return if (bounds.outWidth > 0 && bounds.outHeight > 0) bounds.outWidth to bounds.outHeight else null
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks an image received from another device before it is shown or stored: it must be a
|
||||
* readable image no larger than [MAX_INCOMING_IMAGE_PX] on either side. A small file can
|
||||
* declare a huge resolution, and decoding it at full size would run out of memory.
|
||||
*/
|
||||
fun isAcceptableIncomingImage(base64: String): Boolean = try {
|
||||
val size = imageBounds(Base64.decode(base64, Base64.NO_WRAP))
|
||||
size != null && size.first <= MAX_INCOMING_IMAGE_PX && size.second <= MAX_INCOMING_IMAGE_PX
|
||||
} catch (e: Exception) {
|
||||
false
|
||||
}
|
||||
|
||||
fun decodeChatImage(base64: String, maxDimension: Int = 0): Bitmap? {
|
||||
return try {
|
||||
val bytes = Base64.decode(base64, Base64.NO_WRAP)
|
||||
if (maxDimension <= 0) {
|
||||
BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
|
||||
} else {
|
||||
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)
|
||||
var sample = 1
|
||||
while (maxOf(bounds.outWidth, bounds.outHeight) / (sample * 2) >= maxDimension) sample *= 2
|
||||
val options = BitmapFactory.Options().apply { inSampleSize = sample }
|
||||
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options)
|
||||
}
|
||||
// The size is always checked first: the image may come from another device.
|
||||
val (width, height) = imageBounds(bytes) ?: return null
|
||||
if (width > MAX_INCOMING_IMAGE_PX || height > MAX_INCOMING_IMAGE_PX) return null
|
||||
val target = if (maxDimension > 0) maxDimension else DEFAULT_DECODE_PX
|
||||
var sample = 1
|
||||
while (maxOf(width, height) / (sample * 2) >= target) sample *= 2
|
||||
val options = BitmapFactory.Options().apply { inSampleSize = sample }
|
||||
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options)
|
||||
} catch (e: Exception) {
|
||||
null
|
||||
} catch (e: OutOfMemoryError) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,9 +4,9 @@ import android.content.Context
|
||||
import android.graphics.BitmapFactory
|
||||
import android.graphics.Paint
|
||||
import android.graphics.Typeface
|
||||
import androidx.compose.foundation.Canvas
|
||||
import androidx.compose.foundation.gestures.detectDragGesturesAfterLongPress
|
||||
import androidx.compose.foundation.gestures.detectTapGestures
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.aspectRatio
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.runtime.Composable
|
||||
@@ -16,6 +16,7 @@ import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberUpdatedState
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.drawWithCache
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.geometry.Size
|
||||
import androidx.compose.ui.graphics.Color
|
||||
@@ -43,7 +44,8 @@ import cc.skysparkle.matewave.ui.theme.HighlightMove
|
||||
import kotlin.math.floor
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
private object PieceImages {
|
||||
/** The twelve piece pictures, decoded once and shared by the board and the other piece views. */
|
||||
internal object PieceImages {
|
||||
@Volatile private var cache: Array<ImageBitmap>? = null
|
||||
|
||||
fun get(context: Context): Array<ImageBitmap> {
|
||||
@@ -51,9 +53,9 @@ private object PieceImages {
|
||||
synchronized(this) {
|
||||
cache?.let { return it }
|
||||
val options = BitmapFactory.Options().apply { inScaled = false }
|
||||
val types = PieceType.values()
|
||||
val loaded = Array(PieceColor.values().size * types.size) { i ->
|
||||
val piece = Piece(types[i % types.size], PieceColor.values()[i / types.size])
|
||||
val types = PieceType.entries
|
||||
val loaded = Array(PieceColor.entries.size * types.size) { i ->
|
||||
val piece = Piece(types[i % types.size], PieceColor.entries[i / types.size])
|
||||
BitmapFactory.decodeResource(context.resources, piece.drawableRes(), options).asImageBitmap()
|
||||
}
|
||||
cache = loaded
|
||||
@@ -61,7 +63,9 @@ private object PieceImages {
|
||||
}
|
||||
}
|
||||
|
||||
fun indexOf(piece: Piece): Int = piece.color.ordinal * PieceType.values().size + piece.type.ordinal
|
||||
fun of(context: Context, type: PieceType, color: PieceColor): ImageBitmap = get(context)[indexOf(type, color)]
|
||||
|
||||
fun indexOf(type: PieceType, color: PieceColor): Int = color.ordinal * PieceType.entries.size + type.ordinal
|
||||
}
|
||||
|
||||
@Composable
|
||||
@@ -78,15 +82,19 @@ 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
|
||||
// Read once: the appearance changes only in settings, while no board is on screen.
|
||||
val appearance = remember { BoardAppearance(context) }
|
||||
val theme = appearance.theme
|
||||
val showCoords = appearance.showCoordinates
|
||||
val imagePieces = appearance.useImagePieces
|
||||
val showLastMove = appearance.showLastMove
|
||||
val showCheck = appearance.showCheckHighlight
|
||||
val theme = remember { appearance.theme }
|
||||
val showCoords = remember { appearance.showCoordinates }
|
||||
val imagePieces = remember { appearance.useImagePieces }
|
||||
val lastMoveSetting = remember { appearance.showLastMove }
|
||||
val showLastMove = highlightLastMove ?: lastMoveSetting
|
||||
val showCheck = remember { appearance.showCheckHighlight }
|
||||
|
||||
val pieceImages = if (imagePieces) remember(context) { PieceImages.get(context) } else null
|
||||
|
||||
@@ -111,7 +119,7 @@ fun ChessBoardView(
|
||||
var dragSquare by remember { mutableStateOf<Int?>(null) }
|
||||
var dragPos by remember { mutableStateOf<Offset?>(null) }
|
||||
|
||||
Canvas(
|
||||
Spacer(
|
||||
modifier = modifier
|
||||
.fillMaxWidth()
|
||||
.aspectRatio(1f)
|
||||
@@ -167,151 +175,161 @@ fun ChessBoardView(
|
||||
)
|
||||
}
|
||||
}
|
||||
) {
|
||||
val cell = size.width / 8f
|
||||
val lastFrom = if (showLastMove) (lastMove?.from ?: -1) else -1
|
||||
val lastTo = if (showLastMove) (lastMove?.to ?: -1) else -1
|
||||
val selected = selectedSquare ?: -1
|
||||
val checkSquare = if (showCheck) (kingInCheckSquare ?: -1) else -1
|
||||
val hint = hintSquare ?: -1
|
||||
val flash = flashSquare ?: -1
|
||||
|
||||
val dSq = dragSquare
|
||||
val dPos = dragPos
|
||||
val liftedSq = if (dSq != null && dPos != null && selected == dSq) dSq else -1
|
||||
val liftedAt: Offset? = if (liftedSq >= 0) dPos else null
|
||||
|
||||
for (row in 0 until 8) {
|
||||
for (col in 0 until 8) {
|
||||
val displayRank = if (flipped) row else 7 - row
|
||||
val displayFile = if (flipped) 7 - col else col
|
||||
val sqIndex = displayRank * 8 + displayFile
|
||||
val isLight = (displayRank + displayFile) % 2 == 1
|
||||
var color = if (isLight) theme.light else theme.dark
|
||||
if (sqIndex == lastFrom || sqIndex == lastTo) color = HighlightLastMove
|
||||
if (sqIndex == hint) color = HighlightHint
|
||||
if (sqIndex == selected) color = HighlightMove
|
||||
if (sqIndex == checkSquare) color = HighlightCheck
|
||||
drawRect(
|
||||
color = color,
|
||||
topLeft = Offset(col * cell, row * cell),
|
||||
size = Size(cell, cell)
|
||||
)
|
||||
if (sqIndex == flash) {
|
||||
drawRect(color = flashColor, topLeft = Offset(col * cell, row * cell), size = Size(cell, cell))
|
||||
}
|
||||
|
||||
if (showCoords) {
|
||||
val labelColor = if (isLight) theme.dark else theme.light
|
||||
if (row == 7) {
|
||||
drawCoordinate(
|
||||
('a' + displayFile).toString(),
|
||||
Offset(col * cell + cell * 0.78f, row * cell + cell * 0.80f),
|
||||
cell, labelColor, coordPaint
|
||||
)
|
||||
}
|
||||
if (col == 0) {
|
||||
drawCoordinate(
|
||||
(displayRank + 1).toString(),
|
||||
Offset(col * cell + cell * 0.10f, row * cell + cell * 0.22f),
|
||||
cell, labelColor, coordPaint
|
||||
)
|
||||
}
|
||||
}
|
||||
if ((targetMask shr sqIndex) and 1L != 0L) {
|
||||
drawCircle(
|
||||
color = HighlightMove,
|
||||
radius = cell * 0.14f,
|
||||
center = Offset(col * cell + cell / 2, row * cell + cell / 2)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val pieceSize = cell * 0.86f
|
||||
val inset = (cell - pieceSize) / 2f
|
||||
val pieceDst = IntSize(pieceSize.roundToInt(), pieceSize.roundToInt())
|
||||
if (pieceImages == null) {
|
||||
glyphPaint.textSize = cell * 0.62f
|
||||
glyphPaint.color = GLYPH_COLOR
|
||||
}
|
||||
for (row in 0 until 8) {
|
||||
for (col in 0 until 8) {
|
||||
val displayRank = if (flipped) row else 7 - row
|
||||
val displayFile = if (flipped) 7 - col else col
|
||||
val pieceSq = displayRank * 8 + displayFile
|
||||
if (pieceSq == liftedSq) continue
|
||||
val piece = board.pieceAt(pieceSq) ?: continue
|
||||
if (pieceImages != null) {
|
||||
drawImage(
|
||||
image = pieceImages[PieceImages.indexOf(piece)],
|
||||
dstOffset = IntOffset(
|
||||
(col * cell + inset).roundToInt(),
|
||||
(row * cell + inset).roundToInt()
|
||||
),
|
||||
dstSize = pieceDst,
|
||||
filterQuality = FilterQuality.Medium
|
||||
)
|
||||
} else {
|
||||
val metrics = glyphPaint.fontMetrics
|
||||
drawContext.canvas.nativeCanvas.drawText(
|
||||
piece.unicode(),
|
||||
col * cell + cell / 2f,
|
||||
row * cell + cell / 2f - (metrics.ascent + metrics.descent) / 2f,
|
||||
glyphPaint
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (liftedAt != null) {
|
||||
val liftedPiece = board.pieceAt(liftedSq)
|
||||
if (liftedPiece != null) {
|
||||
val hover = squareAt(liftedAt.x, liftedAt.y, size.width, flipped)
|
||||
if (hover >= 0 && ((targetMask shr hover) and 1L) != 0L) {
|
||||
val hRank = hover / 8
|
||||
val hFile = hover % 8
|
||||
val hRow = if (flipped) hRank else 7 - hRank
|
||||
val hCol = if (flipped) 7 - hFile else hFile
|
||||
drawRect(
|
||||
color = Color.White.copy(alpha = 0.75f),
|
||||
topLeft = Offset(hCol * cell, hRow * cell),
|
||||
size = Size(cell, cell),
|
||||
style = Stroke(width = cell * 0.07f)
|
||||
)
|
||||
}
|
||||
.drawWithCache {
|
||||
// Sizes and text metrics change only with the board size.
|
||||
val cell = size.width / 8f
|
||||
val pieceSize = cell * 0.86f
|
||||
val inset = (cell - pieceSize) / 2f
|
||||
val pieceDst = IntSize(pieceSize.roundToInt(), pieceSize.roundToInt())
|
||||
val liftedSize = pieceSize * LIFT_SCALE
|
||||
val cx = liftedAt.x
|
||||
val cy = liftedAt.y - cell * 0.55f
|
||||
drawOval(
|
||||
color = Color.Black.copy(alpha = 0.30f),
|
||||
topLeft = Offset(liftedAt.x - liftedSize * 0.36f, liftedAt.y + cell * 0.05f),
|
||||
size = Size(liftedSize * 0.72f, liftedSize * 0.28f)
|
||||
)
|
||||
if (pieceImages != null) {
|
||||
val liftedDst = IntSize(liftedSize.roundToInt(), liftedSize.roundToInt())
|
||||
drawImage(
|
||||
image = pieceImages[PieceImages.indexOf(liftedPiece)],
|
||||
dstOffset = IntOffset(
|
||||
(cx - liftedSize / 2f).roundToInt(),
|
||||
(cy - liftedSize / 2f).roundToInt()
|
||||
),
|
||||
dstSize = liftedDst,
|
||||
filterQuality = FilterQuality.Medium
|
||||
)
|
||||
} else {
|
||||
glyphPaint.textSize = cell * 0.62f * LIFT_SCALE
|
||||
val metrics = glyphPaint.fontMetrics
|
||||
drawContext.canvas.nativeCanvas.drawText(
|
||||
liftedPiece.unicode(),
|
||||
cx,
|
||||
cy - (metrics.ascent + metrics.descent) / 2f,
|
||||
glyphPaint
|
||||
)
|
||||
val liftedDst = IntSize(liftedSize.roundToInt(), liftedSize.roundToInt())
|
||||
val hoverStroke = Stroke(width = cell * 0.07f)
|
||||
val glyphSize = cell * 0.62f
|
||||
glyphPaint.textSize = glyphSize
|
||||
val glyphMetrics = glyphPaint.fontMetrics
|
||||
val glyphShift = (glyphMetrics.ascent + glyphMetrics.descent) / 2f
|
||||
glyphPaint.textSize = glyphSize * LIFT_SCALE
|
||||
val liftedMetrics = glyphPaint.fontMetrics
|
||||
val liftedGlyphShift = (liftedMetrics.ascent + liftedMetrics.descent) / 2f
|
||||
onDrawBehind {
|
||||
val lastFrom = if (showLastMove) (lastMove?.from ?: -1) else -1
|
||||
val lastTo = if (showLastMove) (lastMove?.to ?: -1) else -1
|
||||
val selected = selectedSquare ?: -1
|
||||
val checkSquare = if (showCheck) (kingInCheckSquare ?: -1) else -1
|
||||
val hint = hintSquare ?: -1
|
||||
val flash = flashSquare ?: -1
|
||||
|
||||
val dSq = dragSquare
|
||||
val dPos = dragPos
|
||||
val liftedSq = if (dSq != null && dPos != null && selected == dSq) dSq else -1
|
||||
val liftedAt: Offset? = if (liftedSq >= 0) dPos else null
|
||||
|
||||
for (row in 0 until 8) {
|
||||
for (col in 0 until 8) {
|
||||
val displayRank = if (flipped) row else 7 - row
|
||||
val displayFile = if (flipped) 7 - col else col
|
||||
val sqIndex = displayRank * 8 + displayFile
|
||||
val isLight = (displayRank + displayFile) % 2 == 1
|
||||
var color = if (isLight) theme.light else theme.dark
|
||||
if (sqIndex == lastFrom || sqIndex == lastTo) color = HighlightLastMove
|
||||
if (sqIndex == hint) color = HighlightHint
|
||||
if (sqIndex == selected) color = HighlightMove
|
||||
if (sqIndex == checkSquare) color = HighlightCheck
|
||||
drawRect(
|
||||
color = color,
|
||||
topLeft = Offset(col * cell, row * cell),
|
||||
size = Size(cell, cell)
|
||||
)
|
||||
if (sqIndex == flash) {
|
||||
drawRect(color = flashColor, topLeft = Offset(col * cell, row * cell), size = Size(cell, cell))
|
||||
}
|
||||
|
||||
if (showCoords) {
|
||||
val labelColor = if (isLight) theme.dark else theme.light
|
||||
if (row == 7) {
|
||||
drawCoordinate(
|
||||
FILE_LABELS[displayFile],
|
||||
Offset(col * cell + cell * 0.78f, row * cell + cell * 0.80f),
|
||||
cell, labelColor, coordPaint
|
||||
)
|
||||
}
|
||||
if (col == 0) {
|
||||
drawCoordinate(
|
||||
RANK_LABELS[displayRank],
|
||||
Offset(col * cell + cell * 0.10f, row * cell + cell * 0.22f),
|
||||
cell, labelColor, coordPaint
|
||||
)
|
||||
}
|
||||
}
|
||||
if ((targetMask shr sqIndex) and 1L != 0L) {
|
||||
drawCircle(
|
||||
color = HighlightMove,
|
||||
radius = cell * 0.14f,
|
||||
center = Offset(col * cell + cell / 2, row * cell + cell / 2)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (pieceImages == null) {
|
||||
glyphPaint.textSize = glyphSize
|
||||
glyphPaint.color = GLYPH_COLOR
|
||||
}
|
||||
for (row in 0 until 8) {
|
||||
for (col in 0 until 8) {
|
||||
val displayRank = if (flipped) row else 7 - row
|
||||
val displayFile = if (flipped) 7 - col else col
|
||||
val pieceSq = displayRank * 8 + displayFile
|
||||
if (pieceSq == liftedSq) continue
|
||||
val piece = board.pieceAt(pieceSq) ?: continue
|
||||
if (pieceImages != null) {
|
||||
drawImage(
|
||||
image = pieceImages[PieceImages.indexOf(piece.type, piece.color)],
|
||||
dstOffset = IntOffset(
|
||||
(col * cell + inset).roundToInt(),
|
||||
(row * cell + inset).roundToInt()
|
||||
),
|
||||
dstSize = pieceDst,
|
||||
filterQuality = FilterQuality.Medium
|
||||
)
|
||||
} else {
|
||||
drawContext.canvas.nativeCanvas.drawText(
|
||||
piece.unicode(),
|
||||
col * cell + cell / 2f,
|
||||
row * cell + cell / 2f - glyphShift,
|
||||
glyphPaint
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (liftedAt != null) {
|
||||
val liftedPiece = board.pieceAt(liftedSq)
|
||||
if (liftedPiece != null) {
|
||||
val hover = squareAt(liftedAt.x, liftedAt.y, size.width, flipped)
|
||||
if (hover >= 0 && ((targetMask shr hover) and 1L) != 0L) {
|
||||
val hRank = hover / 8
|
||||
val hFile = hover % 8
|
||||
val hRow = if (flipped) hRank else 7 - hRank
|
||||
val hCol = if (flipped) 7 - hFile else hFile
|
||||
drawRect(
|
||||
color = Color.White.copy(alpha = 0.75f),
|
||||
topLeft = Offset(hCol * cell, hRow * cell),
|
||||
size = Size(cell, cell),
|
||||
style = hoverStroke
|
||||
)
|
||||
}
|
||||
val cx = liftedAt.x
|
||||
val cy = liftedAt.y - cell * 0.55f
|
||||
drawOval(
|
||||
color = Color.Black.copy(alpha = 0.30f),
|
||||
topLeft = Offset(liftedAt.x - liftedSize * 0.36f, liftedAt.y + cell * 0.05f),
|
||||
size = Size(liftedSize * 0.72f, liftedSize * 0.28f)
|
||||
)
|
||||
if (pieceImages != null) {
|
||||
drawImage(
|
||||
image = pieceImages[PieceImages.indexOf(liftedPiece.type, liftedPiece.color)],
|
||||
dstOffset = IntOffset(
|
||||
(cx - liftedSize / 2f).roundToInt(),
|
||||
(cy - liftedSize / 2f).roundToInt()
|
||||
),
|
||||
dstSize = liftedDst,
|
||||
filterQuality = FilterQuality.Medium
|
||||
)
|
||||
} else {
|
||||
glyphPaint.textSize = glyphSize * LIFT_SCALE
|
||||
drawContext.canvas.nativeCanvas.drawText(
|
||||
liftedPiece.unicode(),
|
||||
cx,
|
||||
cy - liftedGlyphShift,
|
||||
glyphPaint
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
private const val LIFT_SCALE = 1.6f
|
||||
@@ -328,6 +346,9 @@ private fun squareAt(x: Float, y: Float, boardPx: Float, flipped: Boolean): Int
|
||||
|
||||
private val GLYPH_COLOR = Color(0xFF1B1B1B).toArgb()
|
||||
|
||||
private val FILE_LABELS = Array(8) { ('a' + it).toString() }
|
||||
private val RANK_LABELS = Array(8) { (it + 1).toString() }
|
||||
|
||||
private fun DrawScope.drawCoordinate(
|
||||
text: String,
|
||||
position: Offset,
|
||||
|
||||
@@ -7,11 +7,9 @@ import androidx.compose.animation.core.spring
|
||||
import androidx.compose.foundation.LocalIndication
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.interaction.collectIsPressedAsState
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.graphics.graphicsLayer
|
||||
import cc.skysparkle.matewave.ui.theme.LocalInk
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
@@ -30,7 +28,6 @@ import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.IconButton
|
||||
@@ -41,81 +38,178 @@ import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.alpha
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.Shape
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import cc.skysparkle.matewave.R
|
||||
import cc.skysparkle.matewave.ui.theme.ChessGreen
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.LocalContentColor
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import cc.skysparkle.matewave.ui.theme.Lime
|
||||
import cc.skysparkle.matewave.ui.theme.OnAccent
|
||||
import cc.skysparkle.matewave.ui.theme.Surface2
|
||||
import cc.skysparkle.matewave.ui.theme.GlassShape
|
||||
import cc.skysparkle.matewave.ui.theme.PanelBorder
|
||||
import cc.skysparkle.matewave.ui.theme.PanelFill
|
||||
import cc.skysparkle.matewave.ui.theme.TabletMaxContentWidth
|
||||
import cc.skysparkle.matewave.ui.theme.UiCornerRadius
|
||||
import cc.skysparkle.matewave.ui.theme.glass
|
||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
import androidx.compose.foundation.layout.WindowInsets
|
||||
import androidx.compose.foundation.layout.WindowInsetsSides
|
||||
import androidx.compose.foundation.layout.displayCutout
|
||||
import androidx.compose.foundation.layout.fillMaxHeight
|
||||
import androidx.compose.foundation.layout.navigationBars
|
||||
import androidx.compose.foundation.layout.only
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.union
|
||||
import androidx.compose.foundation.layout.windowInsetsPadding
|
||||
import androidx.compose.runtime.ReadOnlyComposable
|
||||
import androidx.compose.ui.platform.LocalConfiguration
|
||||
import androidx.compose.ui.unit.min
|
||||
import cc.skysparkle.matewave.ui.theme.LandscapeMaxContentWidth
|
||||
|
||||
private val UiShape: Shape = RoundedCornerShape(UiCornerRadius)
|
||||
/** Landscape: a phone on its side or a tablet held wide. Board screens then put the board on the left. */
|
||||
@Composable
|
||||
@ReadOnlyComposable
|
||||
fun isLandscape(): Boolean {
|
||||
val config = LocalConfiguration.current
|
||||
return config.screenWidthDp > config.screenHeightDp
|
||||
}
|
||||
|
||||
/** Side insets in landscape: the camera cutout and a 3-button navigation bar sit on the left or right. */
|
||||
@Composable
|
||||
fun Modifier.horizontalSafePadding(): Modifier =
|
||||
windowInsetsPadding(WindowInsets.displayCutout.union(WindowInsets.navigationBars).only(WindowInsetsSides.Horizontal))
|
||||
|
||||
@Composable
|
||||
private fun ScaffoldTopBar(
|
||||
title: String,
|
||||
onBack: (() -> Unit)?,
|
||||
actions: @Composable RowScope.() -> Unit,
|
||||
titleContent: (@Composable RowScope.() -> Unit)?
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().statusBarsPadding().padding(start = 4.dp, end = 4.dp, top = 8.dp, bottom = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
if (onBack != null) {
|
||||
IconButton(onClick = onBack) {
|
||||
AppIcon(
|
||||
R.drawable.ic_arrow_back,
|
||||
size = 24.dp,
|
||||
tint = ChessGreen,
|
||||
contentDescription = stringResource(R.string.back)
|
||||
)
|
||||
}
|
||||
} else {
|
||||
Spacer(Modifier.width(16.dp))
|
||||
}
|
||||
if (titleContent != null) {
|
||||
Row(modifier = Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically, content = titleContent)
|
||||
} else {
|
||||
Text(
|
||||
title,
|
||||
color = ink,
|
||||
style = MaterialTheme.typography.headlineSmall,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f)
|
||||
)
|
||||
}
|
||||
actions()
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun GlassScaffold(
|
||||
title: String,
|
||||
onBack: (() -> Unit)? = null,
|
||||
actions: @Composable RowScope.() -> Unit = {},
|
||||
scrollable: Boolean = true,
|
||||
|
||||
bottomBar: (@Composable () -> Unit)? = null,
|
||||
/** Replaces the plain title, e.g. with the opening name and its status badge. */
|
||||
titleContent: (@Composable RowScope.() -> Unit)? = null,
|
||||
content: @Composable ColumnScope.() -> Unit
|
||||
) {
|
||||
Box(modifier = Modifier.fillMaxSize()) {
|
||||
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.TopCenter) {
|
||||
Column(modifier = Modifier.fillMaxSize().widthIn(max = TabletMaxContentWidth)) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().statusBarsPadding().padding(horizontal = 4.dp, vertical = 4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
if (onBack != null) {
|
||||
IconButton(onClick = onBack) {
|
||||
AppIcon(
|
||||
R.drawable.ic_arrow_back,
|
||||
size = 24.dp,
|
||||
contentDescription = stringResource(R.string.back)
|
||||
)
|
||||
}
|
||||
} else {
|
||||
Spacer(Modifier.width(48.dp))
|
||||
}
|
||||
if (titleContent != null) {
|
||||
Row(modifier = Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically, content = titleContent)
|
||||
} else {
|
||||
Text(
|
||||
title,
|
||||
color = ink,
|
||||
style = MaterialTheme.typography.titleLarge,
|
||||
modifier = Modifier.weight(1f)
|
||||
)
|
||||
}
|
||||
actions()
|
||||
}
|
||||
Box(modifier = Modifier.fillMaxSize().horizontalSafePadding(), contentAlignment = Alignment.TopCenter) {
|
||||
Column(modifier = Modifier.fillMaxSize().widthIn(max = TabletMaxContentWidth)) {
|
||||
ScaffoldTopBar(title, onBack, actions, titleContent)
|
||||
|
||||
val scrollState = rememberScrollState()
|
||||
val scrollState = rememberScrollState()
|
||||
|
||||
val contentModifier = Modifier
|
||||
val contentModifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.weight(1f)
|
||||
.padding(horizontal = 16.dp)
|
||||
.verticalScroll(scrollState)
|
||||
.then(if (bottomBar == null) Modifier.navigationBarsPadding() else Modifier)
|
||||
.padding(bottom = 16.dp)
|
||||
|
||||
Column(
|
||||
modifier = contentModifier,
|
||||
verticalArrangement = Arrangement.spacedBy(14.dp),
|
||||
content = content
|
||||
)
|
||||
|
||||
if (bottomBar != null) {
|
||||
Box(modifier = Modifier.navigationBarsPadding()) { bottomBar() }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A screen with a chess board. Portrait: [above], the board and [below] in one scrolling column,
|
||||
* as before. Landscape: the board on the left as large as the height allows, [above] and [below]
|
||||
* in a scrolling column on the right. [board] gets the modifier that sizes it.
|
||||
*/
|
||||
@Composable
|
||||
fun BoardScaffold(
|
||||
title: String,
|
||||
onBack: (() -> Unit)? = null,
|
||||
actions: @Composable RowScope.() -> Unit = {},
|
||||
titleContent: (@Composable RowScope.() -> Unit)? = null,
|
||||
above: @Composable ColumnScope.() -> Unit = {},
|
||||
board: (@Composable (Modifier) -> Unit)?,
|
||||
below: @Composable ColumnScope.() -> Unit = {}
|
||||
) {
|
||||
if (!isLandscape()) {
|
||||
GlassScaffold(title = title, onBack = onBack, actions = actions, titleContent = titleContent) {
|
||||
above()
|
||||
if (board != null) {
|
||||
Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.TopCenter) { board(Modifier) }
|
||||
}
|
||||
below()
|
||||
}
|
||||
return
|
||||
}
|
||||
Box(modifier = Modifier.fillMaxSize().horizontalSafePadding(), contentAlignment = Alignment.TopCenter) {
|
||||
Column(modifier = Modifier.fillMaxSize().widthIn(max = LandscapeMaxContentWidth)) {
|
||||
ScaffoldTopBar(title, onBack, actions, titleContent)
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.weight(1f)
|
||||
.padding(horizontal = 16.dp)
|
||||
.then(if (scrollable) Modifier.verticalScroll(scrollState) else Modifier)
|
||||
.then(if (bottomBar == null) Modifier.navigationBarsPadding() else Modifier)
|
||||
.padding(bottom = 16.dp)
|
||||
|
||||
.navigationBarsPadding()
|
||||
.padding(start = 16.dp, end = 16.dp, bottom = 12.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(20.dp)
|
||||
) {
|
||||
if (board != null) {
|
||||
BoxWithConstraints(
|
||||
modifier = Modifier.weight(1f).fillMaxHeight(),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
board(Modifier.size(min(maxWidth, maxHeight)))
|
||||
}
|
||||
}
|
||||
Column(
|
||||
modifier = contentModifier,
|
||||
verticalArrangement = Arrangement.spacedBy(14.dp),
|
||||
content = content
|
||||
)
|
||||
|
||||
if (bottomBar != null) {
|
||||
Box(modifier = Modifier.navigationBarsPadding()) { bottomBar() }
|
||||
modifier = Modifier
|
||||
.weight(1f)
|
||||
.fillMaxHeight()
|
||||
.verticalScroll(rememberScrollState()),
|
||||
verticalArrangement = Arrangement.spacedBy(14.dp)
|
||||
) {
|
||||
above()
|
||||
below()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -133,6 +227,9 @@ private fun Modifier.pressScale(interactionSource: MutableInteractionSource): Mo
|
||||
return this.graphicsLayer { scaleX = scale; scaleY = scale }
|
||||
}
|
||||
|
||||
private val PillShape = RoundedCornerShape(50)
|
||||
|
||||
/** The main action: a lime pill with dark text and icons. */
|
||||
@Composable
|
||||
fun GlassButton(
|
||||
onClick: () -> Unit,
|
||||
@@ -141,14 +238,13 @@ fun GlassButton(
|
||||
content: @Composable RowScope.() -> Unit
|
||||
) {
|
||||
val interaction = remember { MutableInteractionSource() }
|
||||
|
||||
CompositionLocalProvider(LocalInk provides Color.White) {
|
||||
CompositionLocalProvider(LocalContentColor provides OnAccent) {
|
||||
Row(
|
||||
modifier = modifier
|
||||
.pressScale(interaction)
|
||||
.alpha(if (enabled) 1f else 0.4f)
|
||||
.clip(UiShape)
|
||||
.background(ChessGreen)
|
||||
.clip(PillShape)
|
||||
.background(Lime)
|
||||
.then(
|
||||
if (enabled) Modifier.clickable(
|
||||
interactionSource = interaction,
|
||||
@@ -156,7 +252,7 @@ fun GlassButton(
|
||||
onClick = onClick
|
||||
) else Modifier
|
||||
)
|
||||
.padding(horizontal = 20.dp, vertical = 14.dp),
|
||||
.padding(horizontal = 16.dp, vertical = 15.dp),
|
||||
horizontalArrangement = Arrangement.Center,
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
content = content
|
||||
@@ -176,9 +272,9 @@ fun GlassOutlinedButton(
|
||||
modifier = modifier
|
||||
.pressScale(interaction)
|
||||
.alpha(if (enabled) 1f else 0.4f)
|
||||
.clip(UiShape)
|
||||
.background(PanelFill)
|
||||
.border(1.dp, PanelBorder, UiShape)
|
||||
.clip(PillShape)
|
||||
.background(Surface2)
|
||||
.border(1.dp, PanelBorder, PillShape)
|
||||
.then(
|
||||
if (enabled) Modifier.clickable(
|
||||
interactionSource = interaction,
|
||||
@@ -186,7 +282,7 @@ fun GlassOutlinedButton(
|
||||
onClick = onClick
|
||||
) else Modifier
|
||||
)
|
||||
.padding(horizontal = 20.dp, vertical = 14.dp),
|
||||
.padding(horizontal = 16.dp, vertical = 15.dp),
|
||||
horizontalArrangement = Arrangement.Center,
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
content = content
|
||||
@@ -194,12 +290,12 @@ fun GlassOutlinedButton(
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun GlassCard(modifier: Modifier = Modifier, shape: Shape = UiShape, content: @Composable ColumnScope.() -> Unit) {
|
||||
fun GlassCard(modifier: Modifier = Modifier, content: @Composable ColumnScope.() -> Unit) {
|
||||
Column(
|
||||
modifier = modifier
|
||||
.glass(shape)
|
||||
.border(1.dp, PanelBorder, shape)
|
||||
.padding(14.dp),
|
||||
.glass()
|
||||
.border(1.dp, PanelBorder, GlassShape)
|
||||
.padding(16.dp),
|
||||
content = content
|
||||
)
|
||||
}
|
||||
@@ -207,7 +303,7 @@ fun GlassCard(modifier: Modifier = Modifier, shape: Shape = UiShape, content: @C
|
||||
@Composable
|
||||
fun GlassProgress(text: String) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
CircularProgressIndicator(color = ink, modifier = Modifier.padding(2.dp))
|
||||
CircularProgressIndicator(color = ChessGreen, modifier = Modifier.padding(2.dp))
|
||||
Text(text, color = ink, style = MaterialTheme.typography.bodyMedium)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,7 +12,6 @@ import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
@@ -22,28 +21,22 @@ import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import cc.skysparkle.matewave.R
|
||||
import cc.skysparkle.matewave.ui.theme.UiCornerRadius
|
||||
import cc.skysparkle.matewave.ui.theme.glass
|
||||
import cc.skysparkle.matewave.ui.theme.ink
|
||||
|
||||
/** Small uppercase caption above a group. */
|
||||
@Composable
|
||||
fun SectionCaption(text: String, modifier: Modifier = Modifier) {
|
||||
Text(
|
||||
text.uppercase(),
|
||||
color = ink.copy(alpha = 0.5f),
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
modifier = modifier.padding(start = 4.dp, top = 6.dp)
|
||||
)
|
||||
fun SectionCaption(text: String) {
|
||||
SetupSectionLabel(text, Modifier.padding(start = 4.dp, top = 6.dp))
|
||||
}
|
||||
|
||||
/** Rows of one kind in a single block, instead of a card per row. Separate rows with [ListDivider]. */
|
||||
@Composable
|
||||
fun ListGroup(modifier: Modifier = Modifier, content: @Composable ColumnScope.() -> Unit) {
|
||||
fun ListGroup(content: @Composable ColumnScope.() -> Unit) {
|
||||
Column(
|
||||
modifier = modifier
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.glass(RoundedCornerShape(UiCornerRadius))
|
||||
.glass()
|
||||
.padding(vertical = 2.dp),
|
||||
content = content
|
||||
)
|
||||
@@ -67,11 +60,9 @@ fun ListDivider(inset: Int = 52) {
|
||||
@Composable
|
||||
fun ListRow(
|
||||
title: String,
|
||||
modifier: Modifier = Modifier,
|
||||
subtitle: String? = null,
|
||||
icon: Int? = null,
|
||||
iconTint: Color = ink,
|
||||
titleColor: Color = ink,
|
||||
subtitleColor: Color = ink.copy(alpha = 0.6f),
|
||||
value: String? = null,
|
||||
valueColor: Color = ink.copy(alpha = 0.55f),
|
||||
@@ -81,7 +72,7 @@ fun ListRow(
|
||||
onClick: (() -> Unit)? = null
|
||||
) {
|
||||
Row(
|
||||
modifier = modifier
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.then(if (onClick != null) Modifier.clickable(onClick = onClick) else Modifier)
|
||||
.padding(horizontal = 16.dp, vertical = 12.dp),
|
||||
@@ -92,7 +83,7 @@ fun ListRow(
|
||||
icon != null -> { AppIcon(icon, size = 22.dp, tint = iconTint); Spacer(Modifier.width(14.dp)) }
|
||||
}
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(title, color = titleColor, style = MaterialTheme.typography.bodyLarge, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
||||
Text(title, color = ink, style = MaterialTheme.typography.bodyLarge, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
||||
if (subtitle != null) {
|
||||
Text(subtitle, color = subtitleColor, style = MaterialTheme.typography.bodySmall, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
@@ -107,7 +98,7 @@ fun ListRow(
|
||||
}
|
||||
if (chevron) {
|
||||
Spacer(Modifier.width(8.dp))
|
||||
AppIcon(R.drawable.ic_arrow_forward, size = 16.dp, tint = ink.copy(alpha = 0.5f))
|
||||
AppIcon(R.drawable.ic_arrow_forward, size = 20.dp, tint = ink.copy(alpha = 0.7f))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package cc.skysparkle.matewave.ui.components
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
@@ -10,7 +9,7 @@ import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyRow
|
||||
import androidx.compose.foundation.lazy.itemsIndexed
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
@@ -34,25 +33,15 @@ import cc.skysparkle.matewave.ui.theme.ink
|
||||
private data class MoveToken(val text: String, val moveIndex: Int?)
|
||||
|
||||
private val BookTint = androidx.compose.ui.graphics.Color(0xFF93DBA3)
|
||||
private val OutOfBookTint = androidx.compose.ui.graphics.Color(0xFFFFB86B)
|
||||
|
||||
/**
|
||||
* Compact move list that scrolls to the current move, with the opening name underneath.
|
||||
* [currentIndex] is the number of moves played to reach the shown position.
|
||||
*/
|
||||
/** Compact move list that scrolls to the last move, with the opening name underneath. */
|
||||
@Composable
|
||||
fun MovesBar(
|
||||
sans: List<String>,
|
||||
startBoard: Board,
|
||||
currentIndex: Int,
|
||||
opening: OpeningName?,
|
||||
modifier: Modifier = Modifier,
|
||||
/** Leading moves that are opening theory; they are tinted in the list. */
|
||||
bookPlies: Int = 0,
|
||||
/** "Theory" or "Out of book from move N"; null hides the status. */
|
||||
bookStatus: String? = null,
|
||||
inBook: Boolean = true,
|
||||
onMoveClick: ((Int) -> Unit)? = null
|
||||
bookPlies: Int = 0
|
||||
) {
|
||||
if (sans.isEmpty() && opening == null) return
|
||||
val tokens = remember(sans, startBoard) {
|
||||
@@ -67,15 +56,15 @@ fun MovesBar(
|
||||
}
|
||||
}
|
||||
val listState = rememberLazyListState()
|
||||
LaunchedEffect(currentIndex, tokens.size) {
|
||||
val target = tokens.indexOfFirst { it.moveIndex == currentIndex - 1 }
|
||||
LaunchedEffect(sans.size, tokens.size) {
|
||||
val target = tokens.indexOfFirst { it.moveIndex == sans.size - 1 }
|
||||
if (target >= 0) listState.animateScrollToItem(maxOf(0, target - 3))
|
||||
}
|
||||
|
||||
Column(modifier = modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
Column(modifier = Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
if (sans.isNotEmpty()) {
|
||||
LazyRow(state = listState, horizontalArrangement = Arrangement.spacedBy(2.dp)) {
|
||||
itemsIndexed(tokens) { _, token ->
|
||||
items(tokens) { token ->
|
||||
val index = token.moveIndex
|
||||
if (index == null) {
|
||||
Text(
|
||||
@@ -85,7 +74,7 @@ fun MovesBar(
|
||||
modifier = Modifier.padding(start = 6.dp, top = 4.dp, bottom = 4.dp)
|
||||
)
|
||||
} else {
|
||||
val current = index == currentIndex - 1
|
||||
val current = index == sans.size - 1
|
||||
Text(
|
||||
token.text,
|
||||
color = if (index < bookPlies) BookTint else ink,
|
||||
@@ -94,38 +83,24 @@ fun MovesBar(
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.then(if (current) Modifier.background(ChessGreen.copy(alpha = 0.45f)) else Modifier)
|
||||
.then(if (onMoveClick != null) Modifier.clickable { onMoveClick(index + 1) } else Modifier)
|
||||
.padding(horizontal = 6.dp, vertical = 4.dp)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (opening != null || bookStatus != null) {
|
||||
if (opening != null) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
AppIcon(R.drawable.ic_book, size = 14.dp, tint = if (inBook) BookTint else ink.copy(alpha = 0.5f))
|
||||
AppIcon(R.drawable.ic_book, size = 16.dp, tint = BookTint)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(
|
||||
opening?.let { "${it.eco} · ${it.name}" } ?: "",
|
||||
"${opening.eco} · ${opening.name}",
|
||||
color = ink.copy(alpha = 0.85f),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f, fill = false)
|
||||
)
|
||||
if (bookStatus != null) {
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(
|
||||
bookStatus,
|
||||
color = if (inBook) BookTint else OutOfBookTint,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
maxLines = 1,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(6.dp))
|
||||
.background((if (inBook) BookTint else OutOfBookTint).copy(alpha = 0.15f))
|
||||
.padding(horizontal = 6.dp, vertical = 2.dp)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,14 +15,13 @@ 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.painterResource
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.unit.dp
|
||||
import cc.skysparkle.matewave.R
|
||||
import cc.skysparkle.matewave.engine.Piece
|
||||
import cc.skysparkle.matewave.engine.PieceColor
|
||||
import cc.skysparkle.matewave.engine.PieceType
|
||||
import cc.skysparkle.matewave.ui.theme.PanelBorder
|
||||
@@ -32,6 +31,7 @@ import cc.skysparkle.matewave.ui.theme.ink
|
||||
/** The four promotion pieces, drawn with the same images as the board. */
|
||||
@Composable
|
||||
fun PromotionDialog(color: PieceColor, onChoose: (PieceType) -> Unit, onDismiss: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
AppDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = stringResource(R.string.promotion_title),
|
||||
@@ -63,7 +63,7 @@ fun PromotionDialog(color: PieceColor, onChoose: (PieceType) -> Unit, onDismiss:
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
Image(
|
||||
painter = painterResource(Piece(type, color).drawableRes()),
|
||||
bitmap = PieceImages.of(context, type, color),
|
||||
contentDescription = null,
|
||||
modifier = Modifier.fillMaxWidth().aspectRatio(1f)
|
||||
)
|
||||
|
||||
@@ -19,6 +19,8 @@ import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.unit.dp
|
||||
import cc.skysparkle.matewave.ui.theme.ChessGreen
|
||||
import cc.skysparkle.matewave.ui.theme.OnAccent
|
||||
import cc.skysparkle.matewave.ui.theme.Surface1
|
||||
|
||||
@Composable
|
||||
fun SetupSectionLabel(text: String, modifier: Modifier = Modifier) {
|
||||
@@ -36,7 +38,7 @@ fun SetupSegmented(options: List<String>, selectedIndex: Int, onSelect: (Int) ->
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(50))
|
||||
.background(ink.copy(alpha = 0.08f))
|
||||
.background(Surface1)
|
||||
.padding(4.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(4.dp)
|
||||
) {
|
||||
@@ -46,12 +48,16 @@ fun SetupSegmented(options: List<String>, selectedIndex: Int, onSelect: (Int) ->
|
||||
modifier = Modifier
|
||||
.weight(1f)
|
||||
.clip(RoundedCornerShape(50))
|
||||
.background(if (selected) ChessGreen.copy(alpha = 0.35f) else Color.Transparent)
|
||||
.background(if (selected) ChessGreen else Color.Transparent)
|
||||
.clickable { onSelect(index) }
|
||||
.padding(vertical = 10.dp),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
Text(label, color = ink, style = MaterialTheme.typography.bodyMedium)
|
||||
Text(
|
||||
label,
|
||||
color = if (selected) OnAccent else ink.copy(alpha = 0.8f),
|
||||
style = MaterialTheme.typography.labelLarge
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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) {
|
||||
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
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package cc.skysparkle.matewave.ui.components
|
||||
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.drawWithCache
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.Path
|
||||
import androidx.compose.ui.graphics.StrokeCap
|
||||
import androidx.compose.ui.graphics.drawscope.Stroke
|
||||
import androidx.compose.ui.unit.dp
|
||||
import kotlin.math.PI
|
||||
import kotlin.math.sin
|
||||
|
||||
/**
|
||||
* The Matewave signature: thin parallel waves drawn behind the content,
|
||||
* fading towards the bottom of the surface.
|
||||
*/
|
||||
fun Modifier.wavePattern(color: Color, lines: Int = 7): Modifier = drawWithCache {
|
||||
val stroke = Stroke(width = 1.5.dp.toPx(), cap = StrokeCap.Round)
|
||||
val amplitude = 9.dp.toPx()
|
||||
val wavelength = size.width * 0.9f
|
||||
val gap = size.height * 0.55f / lines
|
||||
val step = 4.dp.toPx()
|
||||
val paths = List(lines) { i ->
|
||||
val baseY = gap * (i + 1)
|
||||
val phase = i * 0.55f
|
||||
Path().apply {
|
||||
var x = 0f
|
||||
moveTo(x, baseY + amplitude * sin(phase))
|
||||
while (x <= size.width) {
|
||||
x += step
|
||||
lineTo(x, baseY + amplitude * sin(2f * PI.toFloat() * x / wavelength + phase))
|
||||
}
|
||||
}
|
||||
}
|
||||
onDrawBehind {
|
||||
paths.forEachIndexed { i, path ->
|
||||
drawPath(path, color = color.copy(alpha = color.alpha * (1f - i.toFloat() / lines)), style = stroke)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
package cc.skysparkle.matewave.ui.screens
|
||||
|
||||
import cc.skysparkle.matewave.ui.components.ListDivider
|
||||
import cc.skysparkle.matewave.ui.components.ListGroup
|
||||
import cc.skysparkle.matewave.ui.components.ListRow
|
||||
import cc.skysparkle.matewave.ui.components.SectionCaption
|
||||
@@ -45,12 +44,10 @@ import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import cc.skysparkle.matewave.R
|
||||
import cc.skysparkle.matewave.ui.components.DialogText
|
||||
import cc.skysparkle.matewave.ui.components.DialogAction
|
||||
@@ -59,12 +56,20 @@ import cc.skysparkle.matewave.ui.components.AppBottomBar
|
||||
import cc.skysparkle.matewave.ui.components.BottomTab
|
||||
import cc.skysparkle.matewave.data.ProfileStore
|
||||
import cc.skysparkle.matewave.ui.components.AppIcon
|
||||
import cc.skysparkle.matewave.ui.components.GlassOutlinedButton
|
||||
import cc.skysparkle.matewave.ui.components.ButtonIcon
|
||||
import cc.skysparkle.matewave.ui.components.GlassButton
|
||||
import cc.skysparkle.matewave.ui.components.GlassScaffold
|
||||
import cc.skysparkle.matewave.ui.components.rememberChatImage
|
||||
import cc.skysparkle.matewave.ui.components.wavePattern
|
||||
import cc.skysparkle.matewave.ui.components.encodeImageForChat
|
||||
import cc.skysparkle.matewave.ui.theme.ChessGreen
|
||||
import cc.skysparkle.matewave.ui.theme.PanelBorder
|
||||
import cc.skysparkle.matewave.ui.theme.GlassShape
|
||||
import cc.skysparkle.matewave.ui.theme.Lime
|
||||
import cc.skysparkle.matewave.ui.theme.OnAccent
|
||||
import cc.skysparkle.matewave.ui.theme.Surface1
|
||||
import cc.skysparkle.matewave.ui.theme.Surface2
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import cc.skysparkle.matewave.ui.theme.whiteOutlinedTextFieldColors
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
@@ -136,160 +141,77 @@ fun AccountScreen(
|
||||
)
|
||||
}
|
||||
) {
|
||||
androidx.compose.runtime.CompositionLocalProvider(cc.skysparkle.matewave.ui.theme.LocalInk provides Color.White) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.height(168.dp)
|
||||
.clip(RoundedCornerShape(20.dp))
|
||||
.clickable { backgroundPicker.launch("image/*") }
|
||||
) {
|
||||
val bgBitmap = rememberChatImage(profile.backgroundBase64)
|
||||
if (bgBitmap != null) {
|
||||
Image(
|
||||
bitmap = bgBitmap,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.fillMaxWidth().height(168.dp),
|
||||
contentScale = ContentScale.Crop
|
||||
)
|
||||
} else {
|
||||
Image(
|
||||
painter = painterResource(R.drawable.bg_profile_default),
|
||||
contentDescription = null,
|
||||
modifier = Modifier.fillMaxWidth().height(168.dp),
|
||||
contentScale = ContentScale.Crop
|
||||
)
|
||||
}
|
||||
ProfileHero(
|
||||
profile = profile,
|
||||
onPickBackground = { backgroundPicker.launch("image/*") },
|
||||
onPickAvatar = { avatarPicker.launch("image/*") },
|
||||
onEditName = { editingName = true }
|
||||
)
|
||||
|
||||
Box(
|
||||
modifier = Modifier.fillMaxWidth().height(168.dp).background(
|
||||
Brush.verticalGradient(
|
||||
0.0f to Color.Black.copy(alpha = 0.30f),
|
||||
0.55f to Color.Black.copy(alpha = 0.45f),
|
||||
1.0f to Color.Black.copy(alpha = 0.72f)
|
||||
)
|
||||
)
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
AppIcon(R.drawable.ic_rating, size = 20.dp, tint = Lime)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(
|
||||
stringResource(R.string.friends_rating, profile.elo),
|
||||
color = ink,
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
modifier = Modifier.weight(1f)
|
||||
)
|
||||
|
||||
Box(
|
||||
Text(
|
||||
stringResource(R.string.stats_dialog_title),
|
||||
color = ChessGreen,
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
modifier = Modifier
|
||||
.align(Alignment.TopEnd)
|
||||
.padding(10.dp)
|
||||
.size(36.dp)
|
||||
.clip(CircleShape)
|
||||
.background(Color.Black.copy(alpha = 0.45f))
|
||||
.clickable { backgroundPicker.launch("image/*") },
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
AppIcon(R.drawable.ic_add_photo, size = 20.dp)
|
||||
}
|
||||
.clip(RoundedCornerShape(50))
|
||||
.border(1.dp, ChessGreen.copy(alpha = 0.6f), RoundedCornerShape(50))
|
||||
.clickable { showStats = true }
|
||||
.padding(horizontal = 14.dp, vertical = 6.dp)
|
||||
)
|
||||
}
|
||||
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.align(Alignment.BottomStart)
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 18.dp, vertical = 16.dp)
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(16.dp)) {
|
||||
Box {
|
||||
AvatarCircle(
|
||||
base64 = profile.avatarBase64,
|
||||
size = 76.dp,
|
||||
modifier = Modifier.clickable { avatarPicker.launch("image/*") }
|
||||
)
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.align(Alignment.BottomEnd)
|
||||
.size(28.dp)
|
||||
.clip(CircleShape)
|
||||
.background(ChessGreen)
|
||||
.clickable { avatarPicker.launch("image/*") },
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
AppIcon(R.drawable.ic_edit, size = 14.dp)
|
||||
}
|
||||
}
|
||||
Column {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp)
|
||||
) {
|
||||
Text(
|
||||
profile.name,
|
||||
color = ink,
|
||||
fontSize = 23.sp,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
)
|
||||
|
||||
AppIcon(
|
||||
R.drawable.ic_edit,
|
||||
size = 18.dp,
|
||||
tint = ink.copy(alpha = 0.75f),
|
||||
modifier = Modifier.clickable { editingName = true }
|
||||
)
|
||||
}
|
||||
Text(
|
||||
stringResource(R.string.account_header_summary, profile.elo, cc.skysparkle.matewave.stats.Stats.gamesPlayed()),
|
||||
color = ink.copy(alpha = 0.72f),
|
||||
style = MaterialTheme.typography.bodyMedium
|
||||
)
|
||||
}
|
||||
}
|
||||
if (!profile.levelChosen) {
|
||||
GlassButton(onClick = { showLevelPicker = true }, modifier = Modifier.fillMaxWidth()) {
|
||||
ButtonIcon(R.drawable.ic_speed)
|
||||
Text(stringResource(R.string.account_choose_level), style = MaterialTheme.typography.titleMedium)
|
||||
}
|
||||
}
|
||||
|
||||
StatTiles()
|
||||
|
||||
// Progress: the reason to open a profile.
|
||||
SectionCaption(stringResource(R.string.account_progress))
|
||||
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
HighlightCard(
|
||||
iconRes = R.drawable.ic_study,
|
||||
title = stringResource(R.string.study_title),
|
||||
value = "${study.learnedCount}/${study.courses.size} · ★${study.masteredCount}",
|
||||
modifier = Modifier.weight(1f),
|
||||
onClick = onStudyClick
|
||||
)
|
||||
HighlightCard(
|
||||
iconRes = R.drawable.ic_puzzle,
|
||||
title = stringResource(R.string.puzzles_title),
|
||||
value = "${cc.skysparkle.matewave.stats.Stats.solvedPuzzles().size}",
|
||||
modifier = Modifier.weight(1f),
|
||||
onClick = null
|
||||
)
|
||||
}
|
||||
|
||||
RatingHistoryCard(elo = profile.elo, onClick = { showStats = true })
|
||||
|
||||
if (profile.avatarBase64 != null || profile.backgroundBase64 != null) {
|
||||
Text(
|
||||
stringResource(R.string.account_reset_avatar),
|
||||
color = ink.copy(alpha = 0.55f),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
modifier = Modifier.clickable {
|
||||
ProfileStore.resetAvatarToDefault()
|
||||
ProfileStore.setAvatar(null)
|
||||
ProfileStore.setBackground(null)
|
||||
profile = ProfileStore.get()
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
if (!profile.levelChosen) {
|
||||
GlassOutlinedButton(onClick = { showLevelPicker = true }, modifier = Modifier.fillMaxWidth()) {
|
||||
Text(stringResource(R.string.account_choose_level), color = ink)
|
||||
}
|
||||
}
|
||||
|
||||
// Progress: the reason to open a profile. The rating is shown here once, with its trend.
|
||||
SectionCaption(stringResource(R.string.account_progress))
|
||||
ListGroup {
|
||||
val curve = remember(profile.elo) { cc.skysparkle.matewave.stats.Stats.ratingCurve(profile.elo) }
|
||||
ListRow(
|
||||
title = stringResource(R.string.account_rating_row),
|
||||
icon = R.drawable.ic_license,
|
||||
iconTint = ChessGreen,
|
||||
value = "${profile.elo}",
|
||||
valueColor = ink,
|
||||
trailing = { MiniRatingGraph(points = curve, modifier = Modifier.width(64.dp).height(24.dp)) },
|
||||
chevron = true,
|
||||
onClick = { showStats = true }
|
||||
)
|
||||
ListDivider()
|
||||
ListRow(
|
||||
title = stringResource(R.string.study_title),
|
||||
icon = R.drawable.ic_crown,
|
||||
value = "${study.learnedCount}/${study.courses.size} · ★${study.masteredCount}",
|
||||
chevron = true,
|
||||
onClick = onStudyClick
|
||||
)
|
||||
ListDivider()
|
||||
ListRow(
|
||||
title = stringResource(R.string.puzzles_title),
|
||||
icon = R.drawable.ic_puzzle,
|
||||
value = stringResource(R.string.puzzle_solved_count, cc.skysparkle.matewave.stats.Stats.solvedPuzzles().size)
|
||||
)
|
||||
}
|
||||
|
||||
// Security folded into one row; the details live in a dialog.
|
||||
if (myFingerprint != null) {
|
||||
SectionCaption(stringResource(R.string.account_section_security))
|
||||
@@ -393,6 +315,176 @@ fun AccountScreen(
|
||||
}
|
||||
}
|
||||
|
||||
/** Big name over a dimmed cover, with a large avatar in a neon ring, as in the mockup. */
|
||||
@Composable
|
||||
private fun ProfileHero(
|
||||
profile: cc.skysparkle.matewave.data.Profile,
|
||||
onPickBackground: () -> Unit,
|
||||
onPickAvatar: () -> Unit,
|
||||
onEditName: () -> Unit
|
||||
) {
|
||||
val heroHeight = 236.dp
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.height(heroHeight)
|
||||
.clip(GlassShape)
|
||||
.background(Surface1)
|
||||
) {
|
||||
val bgBitmap = rememberChatImage(profile.backgroundBase64)
|
||||
if (bgBitmap != null) {
|
||||
Image(
|
||||
bitmap = bgBitmap,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.fillMaxWidth().height(heroHeight),
|
||||
contentScale = ContentScale.Crop,
|
||||
alpha = 0.45f
|
||||
)
|
||||
} else {
|
||||
Image(
|
||||
painter = painterResource(R.drawable.bg_profile_default),
|
||||
contentDescription = null,
|
||||
modifier = Modifier.fillMaxWidth().height(heroHeight),
|
||||
contentScale = ContentScale.Crop,
|
||||
alpha = 0.45f
|
||||
)
|
||||
}
|
||||
Box(
|
||||
modifier = Modifier.fillMaxWidth().height(heroHeight).background(
|
||||
Brush.verticalGradient(
|
||||
0.0f to Surface1.copy(alpha = 0.2f),
|
||||
0.6f to Surface1.copy(alpha = 0.6f),
|
||||
1.0f to Surface1.copy(alpha = 0.95f)
|
||||
)
|
||||
).wavePattern(ChessGreen.copy(alpha = 0.12f))
|
||||
)
|
||||
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.align(Alignment.TopStart)
|
||||
.padding(12.dp)
|
||||
.size(36.dp)
|
||||
.clip(CircleShape)
|
||||
.background(Color.Black.copy(alpha = 0.45f))
|
||||
.clickable(onClick = onPickBackground),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
AppIcon(R.drawable.ic_add_photo, size = 20.dp)
|
||||
}
|
||||
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.align(Alignment.TopEnd)
|
||||
.padding(top = 16.dp, end = 16.dp)
|
||||
) {
|
||||
Box(
|
||||
modifier = Modifier.size(148.dp).clip(CircleShape).background(ChessGreen),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
AvatarCircle(
|
||||
base64 = profile.avatarBase64,
|
||||
size = 136.dp,
|
||||
modifier = Modifier.clickable(onClick = onPickAvatar)
|
||||
)
|
||||
}
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.align(Alignment.BottomStart)
|
||||
.padding(start = 8.dp, bottom = 8.dp)
|
||||
.size(34.dp)
|
||||
.clip(CircleShape)
|
||||
.background(Lime)
|
||||
.clickable(onClick = onPickAvatar),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
AppIcon(R.drawable.ic_edit, size = 16.dp, tint = OnAccent)
|
||||
}
|
||||
}
|
||||
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.align(Alignment.BottomStart)
|
||||
.fillMaxWidth()
|
||||
.clickable(onClick = onEditName)
|
||||
.padding(start = 18.dp, end = 18.dp, bottom = 16.dp),
|
||||
verticalAlignment = Alignment.Bottom
|
||||
) {
|
||||
Text(
|
||||
profile.name,
|
||||
color = ink,
|
||||
style = MaterialTheme.typography.headlineLarge,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f, fill = false)
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
AppIcon(
|
||||
R.drawable.ic_edit,
|
||||
size = 18.dp,
|
||||
tint = ink.copy(alpha = 0.7f),
|
||||
modifier = Modifier.padding(bottom = 8.dp)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun HighlightCard(
|
||||
iconRes: Int,
|
||||
title: String,
|
||||
value: String,
|
||||
modifier: Modifier = Modifier,
|
||||
onClick: (() -> Unit)?
|
||||
) {
|
||||
Row(
|
||||
modifier = modifier
|
||||
.clip(GlassShape)
|
||||
.background(Surface1)
|
||||
.border(1.dp, PanelBorder, GlassShape)
|
||||
.then(if (onClick != null) Modifier.clickable(onClick = onClick) else Modifier)
|
||||
.padding(14.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Box(
|
||||
modifier = Modifier.size(40.dp).clip(RoundedCornerShape(14.dp)).background(Surface2),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
AppIcon(iconRes, size = 22.dp, tint = ChessGreen)
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(title, color = ink.copy(alpha = 0.6f), style = MaterialTheme.typography.labelSmall, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
||||
Text(value, color = ink, style = MaterialTheme.typography.titleMedium, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun RatingHistoryCard(elo: Int, onClick: () -> Unit) {
|
||||
val curve = remember(elo) { cc.skysparkle.matewave.stats.Stats.ratingCurve(elo) }
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(GlassShape)
|
||||
.background(Surface1)
|
||||
.border(1.dp, PanelBorder, GlassShape)
|
||||
.clickable(onClick = onClick)
|
||||
.padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp)
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
stringResource(R.string.account_rating_row),
|
||||
color = ink,
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
modifier = Modifier.weight(1f)
|
||||
)
|
||||
AppIcon(R.drawable.ic_arrow_forward, size = 20.dp, tint = ink.copy(alpha = 0.6f))
|
||||
}
|
||||
MiniRatingGraph(points = curve, modifier = Modifier.fillMaxWidth().height(96.dp), showDots = false)
|
||||
}
|
||||
}
|
||||
|
||||
private const val MAX_NAME_LENGTH = 20
|
||||
|
||||
@Composable
|
||||
@@ -463,12 +555,12 @@ private fun LevelPickerDialog(onChoose: (Int) -> Unit, onDismiss: () -> Unit) {
|
||||
}
|
||||
) {
|
||||
SKILL_LEVELS.forEach { level ->
|
||||
val rowShape = RoundedCornerShape(12.dp)
|
||||
val rowShape = RoundedCornerShape(16.dp)
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(rowShape)
|
||||
.background(ink.copy(alpha = 0.07f))
|
||||
.background(Surface2)
|
||||
.clickable { onChoose(level.elo) }
|
||||
.padding(horizontal = 16.dp, vertical = 14.dp),
|
||||
horizontalArrangement = Arrangement.SpaceBetween
|
||||
@@ -487,7 +579,7 @@ fun AvatarCircle(base64: String?, size: Dp, modifier: Modifier = Modifier) {
|
||||
modifier = modifier
|
||||
.size(size)
|
||||
.clip(CircleShape)
|
||||
.background(ChessGreen.copy(alpha = 0.6f))
|
||||
.background(Surface2)
|
||||
.border(2.dp, PanelBorder, CircleShape),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
@@ -502,7 +594,7 @@ fun AvatarCircle(base64: String?, size: Dp, modifier: Modifier = Modifier) {
|
||||
Image(
|
||||
painter = painterResource(R.drawable.ic_default_avatar),
|
||||
contentDescription = null,
|
||||
colorFilter = ColorFilter.tint(ink),
|
||||
colorFilter = ColorFilter.tint(ink.copy(alpha = 0.8f)),
|
||||
modifier = Modifier.size(size * 0.8f)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -12,6 +12,13 @@ import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import cc.skysparkle.matewave.ui.theme.AppPalette
|
||||
import cc.skysparkle.matewave.ui.theme.AppStyle
|
||||
import cc.skysparkle.matewave.ui.theme.AppThemeState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Switch
|
||||
@@ -25,7 +32,6 @@ 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.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.res.stringResource
|
||||
@@ -36,7 +42,7 @@ import cc.skysparkle.matewave.settings.BoardAppearance
|
||||
import cc.skysparkle.matewave.settings.BoardTheme
|
||||
import cc.skysparkle.matewave.ui.components.GlassCard
|
||||
import cc.skysparkle.matewave.ui.components.GlassScaffold
|
||||
import cc.skysparkle.matewave.ui.theme.GlassBorder
|
||||
import cc.skysparkle.matewave.ui.theme.PanelBorder
|
||||
|
||||
@Composable
|
||||
fun AppearanceScreen(onBack: () -> Unit) {
|
||||
@@ -51,6 +57,13 @@ fun AppearanceScreen(onBack: () -> Unit) {
|
||||
var openingBar by remember { mutableStateOf(appearance.showOpening) }
|
||||
|
||||
GlassScaffold(title = stringResource(R.string.appearance_title), onBack = onBack) {
|
||||
Text(
|
||||
stringResource(R.string.app_style_title),
|
||||
color = ink,
|
||||
style = MaterialTheme.typography.titleMedium
|
||||
)
|
||||
StylePicker()
|
||||
|
||||
Text(
|
||||
stringResource(R.string.appearance_board_theme),
|
||||
color = ink,
|
||||
@@ -77,7 +90,7 @@ fun AppearanceScreen(onBack: () -> Unit) {
|
||||
)
|
||||
if (candidate == theme) {
|
||||
cc.skysparkle.matewave.ui.components.AppIcon(
|
||||
R.drawable.ic_check_box, size = 20.dp, tint = Color(0xFF7BE495)
|
||||
R.drawable.ic_check_box, size = 20.dp, tint = cc.skysparkle.matewave.ui.theme.ChessGreen
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -85,30 +98,35 @@ fun AppearanceScreen(onBack: () -> Unit) {
|
||||
}
|
||||
|
||||
AppearanceToggle(
|
||||
icon = R.drawable.ic_coordinates,
|
||||
title = stringResource(R.string.appearance_coordinates),
|
||||
subtitle = stringResource(R.string.appearance_coordinates_hint),
|
||||
checked = coords
|
||||
) { coords = it; appearance.showCoordinates = it }
|
||||
|
||||
AppearanceToggle(
|
||||
icon = R.drawable.ic_image_pieces,
|
||||
title = stringResource(R.string.appearance_image_pieces),
|
||||
subtitle = stringResource(R.string.appearance_image_pieces_hint),
|
||||
checked = images
|
||||
) { images = it; appearance.useImagePieces = it }
|
||||
|
||||
AppearanceToggle(
|
||||
icon = R.drawable.ic_last_move,
|
||||
title = stringResource(R.string.appearance_last_move),
|
||||
subtitle = stringResource(R.string.appearance_last_move_hint),
|
||||
checked = lastMove
|
||||
) { lastMove = it; appearance.showLastMove = it }
|
||||
|
||||
AppearanceToggle(
|
||||
icon = R.drawable.ic_check_alert,
|
||||
title = stringResource(R.string.appearance_check),
|
||||
subtitle = stringResource(R.string.appearance_check_hint),
|
||||
checked = checkGlow
|
||||
) { checkGlow = it; appearance.showCheckHighlight = it }
|
||||
|
||||
AppearanceToggle(
|
||||
icon = R.drawable.ic_move_list,
|
||||
title = stringResource(R.string.appearance_opening_in_game),
|
||||
subtitle = stringResource(R.string.appearance_opening_in_game_hint),
|
||||
checked = openingBar
|
||||
@@ -122,10 +140,89 @@ fun AppearanceScreen(onBack: () -> Unit) {
|
||||
}
|
||||
}
|
||||
|
||||
/** App colour styles as swatches, three per row; the device style follows the wallpaper. */
|
||||
@Composable
|
||||
private fun StylePicker() {
|
||||
val context = LocalContext.current
|
||||
val selected = AppThemeState.style
|
||||
val styles = remember { AppStyle.available }
|
||||
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
styles.chunked(3).forEach { row ->
|
||||
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
row.forEach { style ->
|
||||
StyleSwatch(
|
||||
style = style,
|
||||
palette = remember(style) { AppThemeState.paletteFor(context, style) },
|
||||
selected = style == selected,
|
||||
modifier = Modifier.weight(1f),
|
||||
onClick = { AppThemeState.select(context, style) }
|
||||
)
|
||||
}
|
||||
repeat(3 - row.size) { Spacer(Modifier.weight(1f)) }
|
||||
}
|
||||
}
|
||||
if (selected == AppStyle.DEVICE) {
|
||||
Text(
|
||||
stringResource(R.string.app_style_device_hint),
|
||||
color = ink.copy(alpha = 0.6f),
|
||||
style = MaterialTheme.typography.bodySmall
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StyleSwatch(
|
||||
style: AppStyle,
|
||||
palette: AppPalette,
|
||||
selected: Boolean,
|
||||
modifier: Modifier = Modifier,
|
||||
onClick: () -> Unit
|
||||
) {
|
||||
val shape = RoundedCornerShape(18.dp)
|
||||
Column(
|
||||
modifier = modifier
|
||||
.clip(shape)
|
||||
.background(palette.surface1)
|
||||
.border(if (selected) 2.dp else 1.dp, if (selected) palette.accent else PanelBorder, shape)
|
||||
.clickable(onClick = onClick)
|
||||
.padding(vertical = 12.dp, horizontal = 6.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally
|
||||
) {
|
||||
Box(contentAlignment = Alignment.BottomEnd) {
|
||||
Box(
|
||||
modifier = Modifier.size(44.dp).clip(CircleShape).background(palette.accent),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
if (selected) {
|
||||
cc.skysparkle.matewave.ui.components.AppIcon(
|
||||
R.drawable.ic_check_box, size = 20.dp, tint = palette.onAccent
|
||||
)
|
||||
}
|
||||
}
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.size(20.dp)
|
||||
.clip(CircleShape)
|
||||
.background(palette.action)
|
||||
.border(2.dp, palette.surface1, CircleShape)
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text(
|
||||
stringResource(style.titleRes),
|
||||
color = ink,
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ThemePreview(theme: BoardTheme, showPieces: Boolean) {
|
||||
val shape = RoundedCornerShape(6.dp)
|
||||
Column(modifier = Modifier.size(56.dp).clip(shape).border(1.dp, GlassBorder, shape)) {
|
||||
Column(modifier = Modifier.size(56.dp).clip(shape).border(1.dp, PanelBorder, shape)) {
|
||||
repeat(2) { row ->
|
||||
Row(modifier = Modifier.weight(1f)) {
|
||||
repeat(2) { col ->
|
||||
@@ -160,6 +257,7 @@ private fun ThemePreview(theme: BoardTheme, showPieces: Boolean) {
|
||||
|
||||
@Composable
|
||||
private fun AppearanceToggle(
|
||||
icon: Int,
|
||||
title: String,
|
||||
subtitle: String,
|
||||
checked: Boolean,
|
||||
@@ -167,6 +265,7 @@ private fun AppearanceToggle(
|
||||
) {
|
||||
GlassCard(modifier = Modifier.fillMaxWidth()) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
cc.skysparkle.matewave.ui.components.ButtonIcon(icon, size = 24.dp)
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(title, color = ink, style = MaterialTheme.typography.titleMedium)
|
||||
Text(subtitle, color = ink.copy(alpha = 0.7f), style = MaterialTheme.typography.bodySmall)
|
||||
@@ -175,8 +274,8 @@ private fun AppearanceToggle(
|
||||
checked = checked,
|
||||
onCheckedChange = onCheckedChange,
|
||||
colors = SwitchDefaults.colors(
|
||||
checkedThumbColor = Color.White,
|
||||
checkedTrackColor = Color(0xFF4F8A5B)
|
||||
checkedThumbColor = cc.skysparkle.matewave.ui.theme.OnAccent,
|
||||
checkedTrackColor = cc.skysparkle.matewave.ui.theme.ChessGreen
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -37,6 +37,7 @@ 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.drawWithCache
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
@@ -63,6 +64,8 @@ import cc.skysparkle.matewave.ui.components.GlassButton
|
||||
import cc.skysparkle.matewave.ui.components.GlassScaffold
|
||||
import cc.skysparkle.matewave.ui.components.rememberPermissionRequester
|
||||
import cc.skysparkle.matewave.ui.theme.ChessGreen
|
||||
import cc.skysparkle.matewave.ui.theme.Lime
|
||||
import cc.skysparkle.matewave.ui.theme.OnAccent
|
||||
|
||||
private enum class Hint { BLUETOOTH_PERMISSION, BLUETOOTH_OFF, WIFI_OFF }
|
||||
|
||||
@@ -74,14 +77,16 @@ private data class NearbyEntry(
|
||||
val elo: Int?,
|
||||
val type: TransportType,
|
||||
val address: String,
|
||||
val avatar: String?
|
||||
val avatar: String?,
|
||||
/** Player id from the signed Wi-Fi announcement; checked against the profile after connecting. */
|
||||
val playerId: String? = null
|
||||
)
|
||||
|
||||
@Composable
|
||||
fun ConnectionScreen(
|
||||
presence: LocalPresence,
|
||||
onStartHost: (TimeControl) -> Unit,
|
||||
onJoin: (TransportType, TimeControl, targetId: String) -> Unit,
|
||||
onJoin: (TransportType, TimeControl, targetId: String, expectedUserId: String?) -> Unit,
|
||||
onBack: () -> Unit
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
@@ -143,7 +148,8 @@ fun ConnectionScreen(
|
||||
elo = peer.elo,
|
||||
type = TransportType.LAN,
|
||||
address = peer.address,
|
||||
avatar = friends.firstOrNull { it.userId == peer.playerId }?.avatarBase64
|
||||
avatar = friends.firstOrNull { it.userId == peer.playerId }?.avatarBase64,
|
||||
playerId = peer.playerId
|
||||
)
|
||||
}
|
||||
val lanFingerprints = peers.values.map { it.fingerprint }.filter { it.isNotEmpty() }
|
||||
@@ -172,10 +178,11 @@ fun ConnectionScreen(
|
||||
modifier = Modifier.weight(1f)
|
||||
) {
|
||||
ButtonIcon(R.drawable.ic_add, size = 20.dp)
|
||||
Text(stringResource(R.string.nearby_create), color = ink, style = MaterialTheme.typography.titleMedium, maxLines = 1)
|
||||
Text(stringResource(R.string.nearby_create), style = MaterialTheme.typography.titleMedium, maxLines = 1)
|
||||
}
|
||||
GlassOutlinedButton(onClick = { pickTime = true }) {
|
||||
Text(timeControl.shortLabel() + " ▾", color = ink, maxLines = 1)
|
||||
Text(timeControl.shortLabel(), color = ink, maxLines = 1)
|
||||
AppIcon(R.drawable.ic_expand, size = 20.dp)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -254,12 +261,12 @@ fun ConnectionScreen(
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(
|
||||
stringResource(R.string.players_play),
|
||||
color = Color.White,
|
||||
color = OnAccent,
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(50))
|
||||
.background(ChessGreen)
|
||||
.clickable { onJoin(entry.type, timeControl, entry.address) }
|
||||
.background(Lime)
|
||||
.clickable { onJoin(entry.type, timeControl, entry.address, entry.playerId) }
|
||||
.padding(horizontal = 14.dp, vertical = 6.dp)
|
||||
)
|
||||
}
|
||||
@@ -294,18 +301,26 @@ private fun SearchPulse() {
|
||||
)
|
||||
Column(modifier = Modifier.fillMaxWidth().padding(top = 8.dp), horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Box(modifier = Modifier.size(120.dp), contentAlignment = Alignment.Center) {
|
||||
androidx.compose.foundation.Canvas(modifier = Modifier.size(120.dp)) {
|
||||
for (k in 0 until 3) {
|
||||
val p = (phase + k / 3f) % 1f
|
||||
drawCircle(
|
||||
color = ChessGreen.copy(alpha = (1f - p) * 0.45f),
|
||||
radius = size.minDimension / 2f * (0.3f + 0.7f * p),
|
||||
style = androidx.compose.ui.graphics.drawscope.Stroke(width = 2.dp.toPx())
|
||||
)
|
||||
Spacer(
|
||||
modifier = Modifier.size(120.dp).drawWithCache {
|
||||
val ring = androidx.compose.ui.graphics.drawscope.Stroke(width = 2.dp.toPx())
|
||||
// The phase is read while drawing: the pulse redraws without recomposing.
|
||||
onDrawBehind {
|
||||
for (k in 0 until 3) {
|
||||
val p = (phase + k / 3f) % 1f
|
||||
drawCircle(
|
||||
color = ChessGreen.copy(alpha = (1f - p) * 0.45f),
|
||||
radius = size.minDimension / 2f * (0.3f + 0.7f * p),
|
||||
style = ring
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
androidx.compose.foundation.Image(
|
||||
painter = androidx.compose.ui.res.painterResource(R.drawable.piece_white_knight),
|
||||
bitmap = cc.skysparkle.matewave.ui.components.PieceImages.of(
|
||||
LocalContext.current, cc.skysparkle.matewave.engine.PieceType.KNIGHT, cc.skysparkle.matewave.engine.PieceColor.WHITE
|
||||
),
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(40.dp)
|
||||
)
|
||||
|
||||
@@ -43,9 +43,21 @@ import cc.skysparkle.matewave.data.FriendsStore
|
||||
import cc.skysparkle.matewave.presence.LocalPresence
|
||||
import cc.skysparkle.matewave.ui.components.AppBottomBar
|
||||
import cc.skysparkle.matewave.ui.components.AppIcon
|
||||
import cc.skysparkle.matewave.ui.components.ButtonIcon
|
||||
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.ui.theme.Lime
|
||||
import cc.skysparkle.matewave.ui.theme.OnAccent
|
||||
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 +65,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 +77,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()
|
||||
@@ -96,7 +131,8 @@ fun FriendsScreen(
|
||||
Text(stringResource(R.string.friends_nobody_title), color = ink, style = MaterialTheme.typography.titleMedium)
|
||||
Text(stringResource(R.string.friends_nobody_hint), color = ink.copy(alpha = 0.65f), style = MaterialTheme.typography.bodyMedium)
|
||||
GlassButton(onClick = onPlay, modifier = Modifier.fillMaxWidth()) {
|
||||
Text(stringResource(R.string.friends_play_nearby), color = ink)
|
||||
ButtonIcon(R.drawable.ic_play)
|
||||
Text(stringResource(R.string.friends_play_nearby), style = MaterialTheme.typography.titleMedium)
|
||||
}
|
||||
return@GlassScaffold
|
||||
}
|
||||
@@ -115,18 +151,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 +172,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 +189,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 +198,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 +211,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
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -194,25 +236,24 @@ private fun displayName(name: String, id: String): String {
|
||||
private fun PlayChip(onClick: () -> Unit) {
|
||||
Text(
|
||||
stringResource(R.string.friends_play),
|
||||
color = Color.White,
|
||||
color = OnAccent,
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(50))
|
||||
.background(ChessGreen)
|
||||
.background(Lime)
|
||||
.clickable(onClick = onClick)
|
||||
.padding(horizontal = 14.dp, vertical = 6.dp)
|
||||
)
|
||||
}
|
||||
|
||||
@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
|
||||
.clip(cc.skysparkle.matewave.ui.components.DialogShape)
|
||||
.background(cc.skysparkle.matewave.ui.components.DialogSurface)
|
||||
) {
|
||||
androidx.compose.runtime.CompositionLocalProvider(cc.skysparkle.matewave.ui.theme.LocalInk provides Color.White) {
|
||||
Box(modifier = Modifier.fillMaxWidth().height(150.dp)) {
|
||||
val bg = cc.skysparkle.matewave.ui.components.rememberChatImage(friend.backgroundBase64)
|
||||
if (bg != null) {
|
||||
@@ -254,12 +295,14 @@ 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 +319,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 +361,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) OnAccent else ink.copy(alpha = 0.5f),
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
maxLines = 1,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(50))
|
||||
.background(if (enabled) Lime 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)
|
||||
|
||||
@@ -9,6 +9,7 @@ import androidx.compose.foundation.layout.padding
|
||||
import cc.skysparkle.matewave.ui.theme.ink
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
@@ -33,6 +34,7 @@ import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import cc.skysparkle.matewave.R
|
||||
import cc.skysparkle.matewave.clock.ClockState
|
||||
import cc.skysparkle.matewave.ui.components.DialogText
|
||||
import cc.skysparkle.matewave.ui.components.DialogAction
|
||||
import cc.skysparkle.matewave.ui.components.AppDialog
|
||||
@@ -48,9 +50,11 @@ import cc.skysparkle.matewave.ui.components.GlassOutlinedButton
|
||||
import cc.skysparkle.matewave.ui.components.GlassScaffold
|
||||
import cc.skysparkle.matewave.ui.components.PromotionDialog
|
||||
import cc.skysparkle.matewave.ui.theme.ChessGreen
|
||||
import cc.skysparkle.matewave.ui.theme.OnAccent
|
||||
import cc.skysparkle.matewave.viewmodel.GameMode
|
||||
import cc.skysparkle.matewave.viewmodel.GameUiState
|
||||
import cc.skysparkle.matewave.viewmodel.GameViewModel
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
|
||||
@Composable
|
||||
fun GameScreen(viewModel: GameViewModel, onExit: () -> Unit) {
|
||||
@@ -98,47 +102,53 @@ fun GameScreen(viewModel: GameViewModel, onExit: () -> Unit) {
|
||||
else -> null
|
||||
}
|
||||
|
||||
GlassScaffold(
|
||||
val material = remember(state.board) { cc.skysparkle.matewave.engine.Material.balance(state.board) }
|
||||
val bottomColor = state.myColor
|
||||
val topColor = if (bottomColor == PieceColor.WHITE) PieceColor.BLACK else PieceColor.WHITE
|
||||
val kingInCheckSquare = remember(state.board) { ChessEngine.checkedKingSquare(state.board) }
|
||||
|
||||
// Portrait: opponent, board, you and the controls one under another.
|
||||
// Landscape: the board on the left, players and controls on the right.
|
||||
cc.skysparkle.matewave.ui.components.BoardScaffold(
|
||||
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
|
||||
} else null,
|
||||
above = {
|
||||
if (state.mode == GameMode.VS_PLAYER_NETWORK) ConnectionBanner(state)
|
||||
TrustBanners(state)
|
||||
PlayerRow(state, topColor, isMe = false, material = material, clock = viewModel.clockState)
|
||||
},
|
||||
board = { boardModifier ->
|
||||
ChessBoardView(
|
||||
modifier = boardModifier,
|
||||
board = state.board,
|
||||
selectedSquare = state.selectedSquare,
|
||||
legalTargets = state.legalTargetsFromSelected,
|
||||
kingInCheckSquare = kingInCheckSquare,
|
||||
flipped = state.myColor == PieceColor.BLACK,
|
||||
onSquareClick = viewModel::onSquareClicked,
|
||||
lastMove = state.lastMove,
|
||||
interactionEnabled = state.status == GameStatus.ONGOING && state.pendingPromotion == null &&
|
||||
(state.mode != GameMode.VS_PLAYER_NETWORK ||
|
||||
(state.connectionState == ConnectionState.CONNECTED &&
|
||||
state.handshake == cc.skysparkle.matewave.viewmodel.HandshakeState.PLAYING))
|
||||
)
|
||||
}
|
||||
) {
|
||||
if (state.mode == GameMode.VS_PLAYER_NETWORK) ConnectionBanner(state)
|
||||
TrustBanners(state)
|
||||
|
||||
val material = remember(state.board) { cc.skysparkle.matewave.engine.Material.balance(state.board) }
|
||||
val bottomColor = state.myColor
|
||||
val topColor = if (bottomColor == PieceColor.WHITE) PieceColor.BLACK else PieceColor.WHITE
|
||||
val kingInCheckSquare = if (ChessEngine.isInCheck(state.board, state.board.sideToMove)) {
|
||||
state.board.kingSquare(state.board.sideToMove)
|
||||
} else null
|
||||
|
||||
PlayerRow(state, topColor, isMe = false, material = material)
|
||||
|
||||
ChessBoardView(
|
||||
board = state.board,
|
||||
selectedSquare = state.selectedSquare,
|
||||
legalTargets = state.legalTargetsFromSelected,
|
||||
kingInCheckSquare = kingInCheckSquare,
|
||||
flipped = state.myColor == PieceColor.BLACK,
|
||||
onSquareClick = viewModel::onSquareClicked,
|
||||
lastMove = state.lastMove,
|
||||
interactionEnabled = state.status == GameStatus.ONGOING && state.pendingPromotion == null &&
|
||||
(state.mode != GameMode.VS_PLAYER_NETWORK ||
|
||||
(state.connectionState == ConnectionState.CONNECTED &&
|
||||
state.handshake == cc.skysparkle.matewave.viewmodel.HandshakeState.PLAYING))
|
||||
)
|
||||
|
||||
PlayerRow(state, bottomColor, isMe = true, material = material)
|
||||
PlayerRow(state, bottomColor, isMe = true, material = material, clock = viewModel.clockState)
|
||||
|
||||
// The move ribbon: only moves here, the opening name lives in the top bar.
|
||||
if (showOpening) {
|
||||
cc.skysparkle.matewave.ui.components.MovesBar(
|
||||
sans = sans,
|
||||
startBoard = start,
|
||||
currentIndex = sans.size,
|
||||
opening = null,
|
||||
bookPlies = bookPlies
|
||||
)
|
||||
@@ -169,14 +179,18 @@ fun GameScreen(viewModel: GameViewModel, onExit: () -> Unit) {
|
||||
modifier = Modifier.weight(1f),
|
||||
enabled = !state.drawOfferSentByMe
|
||||
) {
|
||||
ButtonIcon(R.drawable.ic_draw)
|
||||
Text(
|
||||
if (state.drawOfferSentByMe) stringResource(R.string.draw_offer_waiting) else stringResource(R.string.offer_draw),
|
||||
color = ink,
|
||||
maxLines = 1
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
maxLines = 1,
|
||||
overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis
|
||||
)
|
||||
}
|
||||
GlassOutlinedButton(onClick = { confirmResign = true }, modifier = Modifier.weight(1f)) {
|
||||
Text(stringResource(R.string.resign), color = ink, maxLines = 1)
|
||||
ButtonIcon(R.drawable.ic_flag)
|
||||
Text(stringResource(R.string.resign), color = ink, style = MaterialTheme.typography.labelLarge, maxLines = 1)
|
||||
}
|
||||
}
|
||||
ChatButton(
|
||||
@@ -188,6 +202,7 @@ fun GameScreen(viewModel: GameViewModel, onExit: () -> Unit) {
|
||||
// The result dialog was closed to look at the board: one tap brings it back.
|
||||
if (state.status != GameStatus.ONGOING && gameOverHidden) {
|
||||
GlassOutlinedButton(onClick = { gameOverHidden = false }, modifier = Modifier.fillMaxWidth()) {
|
||||
ButtonIcon(R.drawable.ic_trophy)
|
||||
Text(stringResource(R.string.game_over_title), color = ink, maxLines = 1)
|
||||
}
|
||||
}
|
||||
@@ -293,7 +308,7 @@ private fun ChatButton(unreadCount: Int, onClick: () -> Unit) {
|
||||
.background(ChessGreen),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
Text(unreadCount.toString(), color = Color.White, fontSize = 11.sp)
|
||||
Text(unreadCount.toString(), color = OnAccent, fontSize = 11.sp)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -434,7 +449,8 @@ private fun PlayerRow(
|
||||
state: GameUiState,
|
||||
side: PieceColor,
|
||||
isMe: Boolean,
|
||||
material: cc.skysparkle.matewave.engine.MaterialBalance
|
||||
material: cc.skysparkle.matewave.engine.MaterialBalance,
|
||||
clock: StateFlow<ClockState?>
|
||||
) {
|
||||
val active = state.status == GameStatus.ONGOING && state.board.sideToMove == side
|
||||
// Re-read after the game: the rating changes when it ends.
|
||||
@@ -452,15 +468,26 @@ private fun PlayerRow(
|
||||
state.opponentProfile?.avatarBase64
|
||||
)
|
||||
}
|
||||
Row(modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
// A card per player; the side to move gets a neon outline and ring.
|
||||
val cardShape = RoundedCornerShape(18.dp)
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(cardShape)
|
||||
.background(cc.skysparkle.matewave.ui.theme.Surface1)
|
||||
.border(1.dp, if (active) ChessGreen.copy(alpha = 0.7f) else cc.skysparkle.matewave.ui.theme.PanelBorder, cardShape)
|
||||
.padding(horizontal = 10.dp, vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.size(8.dp)
|
||||
.size(40.dp)
|
||||
.clip(CircleShape)
|
||||
.background(if (active) ChessGreen else ink.copy(alpha = 0.15f))
|
||||
)
|
||||
Spacer(Modifier.width(10.dp))
|
||||
AvatarCircle(base64 = avatar, size = 34.dp)
|
||||
.background(if (active) ChessGreen else Color.Transparent),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
AvatarCircle(base64 = avatar, size = 36.dp)
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
@@ -483,14 +510,21 @@ private fun PlayerRow(
|
||||
}
|
||||
SideCaptured(material, side)
|
||||
}
|
||||
state.clockState?.let { cs ->
|
||||
BigClock(if (side == PieceColor.WHITE) cs.whiteMillis else cs.blackMillis, active)
|
||||
}
|
||||
PlayerClock(clock, side, active)
|
||||
}
|
||||
}
|
||||
|
||||
/** Collects the clock here, so its ticks recompose only the clock. */
|
||||
@Composable
|
||||
private fun PlayerClock(clock: StateFlow<ClockState?>, side: PieceColor, active: Boolean) {
|
||||
val clockState by clock.collectAsState()
|
||||
clockState?.let { cs ->
|
||||
BigClock(if (side == PieceColor.WHITE) cs.whiteMillis else cs.blackMillis, active)
|
||||
}
|
||||
}
|
||||
|
||||
@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 {
|
||||
@@ -498,21 +532,27 @@ private fun BigClock(millis: Long, active: Boolean) {
|
||||
active -> ink
|
||||
else -> ink.copy(alpha = 0.45f)
|
||||
}
|
||||
// The running clock is a lime pill, like the main action; a low clock turns red.
|
||||
val fill = when {
|
||||
low -> Color(0xFFFF6B6B)
|
||||
active -> cc.skysparkle.matewave.ui.theme.Lime
|
||||
else -> ink.copy(alpha = 0.06f)
|
||||
}
|
||||
val textColor = if (active) cc.skysparkle.matewave.ui.theme.OnAccent else color
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(if (active) ink.copy(alpha = 0.12f) else Color.Transparent)
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp),
|
||||
.clip(RoundedCornerShape(50))
|
||||
.background(fill)
|
||||
.padding(horizontal = 14.dp, vertical = 6.dp),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
if (totalSeconds >= NO_LIMIT_THRESHOLD_SECONDS) {
|
||||
AppIcon(R.drawable.ic_infinity, size = 28.dp, tint = color)
|
||||
AppIcon(R.drawable.ic_infinity, size = 26.dp, tint = textColor)
|
||||
} else {
|
||||
Text(
|
||||
"%d:%02d".format(totalSeconds / 60, totalSeconds % 60),
|
||||
color = color,
|
||||
style = MaterialTheme.typography.headlineSmall,
|
||||
fontWeight = androidx.compose.ui.text.font.FontWeight.SemiBold
|
||||
color = textColor,
|
||||
style = MaterialTheme.typography.titleLarge.copy(fontFeatureSettings = "tnum")
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -543,7 +583,6 @@ private fun ConnectionBanner(state: GameUiState) {
|
||||
private fun TrustBanners(state: GameUiState) {
|
||||
val (icon, text, color) = when {
|
||||
state.opponentUntrusted -> Triple(R.drawable.ic_no_encryption, stringResource(R.string.trust_impersonation), Color(0xFFFF6B6B))
|
||||
state.opponentOutdated -> Triple(R.drawable.ic_error, stringResource(R.string.trust_outdated), Color(0xFFFF6B6B))
|
||||
state.opponentUnverified -> Triple(R.drawable.ic_no_encryption, stringResource(R.string.trust_unverified), Color(0xFFFFC46B))
|
||||
else -> Triple(0, null, Color.Unspecified)
|
||||
}
|
||||
|
||||
@@ -45,6 +45,7 @@ private data class LicenseEntry(
|
||||
)
|
||||
|
||||
private const val APACHE = "Apache License 2.0"
|
||||
private const val OFL = "SIL Open Font License 1.1"
|
||||
private const val AOSP = "The Android Open Source Project"
|
||||
|
||||
private val LIBRARIES = listOf(
|
||||
@@ -109,6 +110,14 @@ private val ASSETS = listOf(
|
||||
LicenseEntry(
|
||||
"Vector Chess Pieces", "RhosGFX", null, "CC0 1.0",
|
||||
"https://rhosgfx.itch.io/vector-chess-pieces", R.string.licenses_note_pieces
|
||||
),
|
||||
LicenseEntry(
|
||||
"Unbounded", "The Unbounded Project Authors", null, OFL,
|
||||
"https://github.com/googlefonts/unbounded", R.string.licenses_note_fonts
|
||||
),
|
||||
LicenseEntry(
|
||||
"Manrope", "The Manrope Project Authors", null, OFL,
|
||||
"https://github.com/googlefonts/manrope", R.string.licenses_note_fonts
|
||||
)
|
||||
)
|
||||
|
||||
@@ -123,6 +132,7 @@ private val RADIO = listOf(
|
||||
fun LicensesScreen(onBack: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
var showApache by remember { mutableStateOf(false) }
|
||||
var showOfl by remember { mutableStateOf(false) }
|
||||
|
||||
GlassScaffold(title = stringResource(R.string.licenses_title), onBack = onBack) {
|
||||
Text(
|
||||
@@ -143,6 +153,10 @@ fun LicensesScreen(onBack: () -> Unit) {
|
||||
|
||||
SetupSectionLabel(stringResource(R.string.licenses_group_assets))
|
||||
ASSETS.forEach { entry -> LicenseCard(entry) { openUrl(context, entry.url) } }
|
||||
GlassOutlinedButton(onClick = { showOfl = true }, modifier = Modifier.fillMaxWidth()) {
|
||||
ButtonIcon(R.drawable.ic_copyright)
|
||||
Text(stringResource(R.string.licenses_ofl_full), color = ink)
|
||||
}
|
||||
|
||||
SetupSectionLabel(stringResource(R.string.licenses_group_radio))
|
||||
Text(
|
||||
@@ -154,7 +168,10 @@ fun LicensesScreen(onBack: () -> Unit) {
|
||||
}
|
||||
|
||||
if (showApache) {
|
||||
ApacheLicenseDialog(onDismiss = { showApache = false })
|
||||
LicenseTextDialog(APACHE, R.raw.license_apache_2_0, "https://www.apache.org/licenses/LICENSE-2.0") { showApache = false }
|
||||
}
|
||||
if (showOfl) {
|
||||
LicenseTextDialog(OFL, R.raw.license_ofl_1_1, "https://openfontlicense.org") { showOfl = false }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -179,26 +196,26 @@ private fun LicenseCard(entry: LicenseEntry, onClick: () -> Unit) {
|
||||
)
|
||||
}
|
||||
}
|
||||
AppIcon(R.drawable.ic_arrow_forward, size = 16.dp, tint = ink.copy(alpha = 0.6f))
|
||||
AppIcon(R.drawable.ic_arrow_forward, size = 20.dp, tint = ink.copy(alpha = 0.7f))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ApacheLicenseDialog(onDismiss: () -> Unit) {
|
||||
private fun LicenseTextDialog(title: String, rawRes: Int, fallbackUrl: String, onDismiss: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val text = remember {
|
||||
val text = remember(rawRes) {
|
||||
runCatching {
|
||||
context.resources.openRawResource(R.raw.license_apache_2_0)
|
||||
context.resources.openRawResource(rawRes)
|
||||
.bufferedReader().use { it.readText() }
|
||||
}.getOrDefault("https://www.apache.org/licenses/LICENSE-2.0")
|
||||
}.getOrDefault(fallbackUrl)
|
||||
.trim()
|
||||
.split(Regex("\n\\s*\n"))
|
||||
.joinToString("\n\n") { paragraph -> paragraph.lines().joinToString(" ") { it.trim() } }
|
||||
}
|
||||
AppDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = APACHE,
|
||||
title = title,
|
||||
actions = { DialogAction(stringResource(R.string.chat_close), onDismiss) }
|
||||
) {
|
||||
Column(modifier = Modifier.fillMaxWidth().heightIn(max = 380.dp).verticalScroll(rememberScrollState())) {
|
||||
|
||||
@@ -1,18 +1,6 @@
|
||||
package cc.skysparkle.matewave.ui.screens
|
||||
|
||||
import androidx.compose.foundation.layout.statusBarsPadding
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import cc.skysparkle.matewave.ui.components.ListDivider
|
||||
import cc.skysparkle.matewave.ui.components.ListGroup
|
||||
import cc.skysparkle.matewave.ui.components.ListRow
|
||||
import cc.skysparkle.matewave.ui.components.SectionCaption
|
||||
|
||||
import cc.skysparkle.matewave.ui.theme.ink
|
||||
|
||||
import androidx.compose.foundation.Canvas
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
@@ -21,20 +9,25 @@ 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.fillMaxHeight
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import cc.skysparkle.matewave.ui.components.horizontalSafePadding
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.navigationBarsPadding
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.statusBarsPadding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
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
|
||||
@@ -42,32 +35,44 @@ 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.draw.drawWithCache
|
||||
import androidx.compose.ui.draw.rotate
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.graphics.Brush
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.ColorFilter
|
||||
import androidx.compose.ui.graphics.Path
|
||||
import androidx.compose.ui.graphics.StrokeCap
|
||||
import androidx.compose.ui.graphics.drawscope.Stroke
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.foundation.Image
|
||||
import cc.skysparkle.matewave.R
|
||||
import cc.skysparkle.matewave.ui.components.DialogText
|
||||
import cc.skysparkle.matewave.ui.components.DialogAction
|
||||
import cc.skysparkle.matewave.ui.components.AppDialog
|
||||
import cc.skysparkle.matewave.stats.Stats
|
||||
import cc.skysparkle.matewave.ui.components.AppBottomBar
|
||||
import cc.skysparkle.matewave.ui.components.AppDialog
|
||||
import cc.skysparkle.matewave.ui.components.AppIcon
|
||||
import cc.skysparkle.matewave.ui.components.BottomTab
|
||||
import cc.skysparkle.matewave.ui.components.DialogAction
|
||||
import cc.skysparkle.matewave.ui.components.DialogText
|
||||
import cc.skysparkle.matewave.ui.components.SectionCaption
|
||||
import cc.skysparkle.matewave.ui.components.displayName
|
||||
import cc.skysparkle.matewave.ui.components.wavePattern
|
||||
import cc.skysparkle.matewave.ui.theme.ChessGreen
|
||||
import cc.skysparkle.matewave.ui.theme.GlassShape
|
||||
import cc.skysparkle.matewave.ui.theme.HeroTextStyle
|
||||
import cc.skysparkle.matewave.ui.theme.Lime
|
||||
import cc.skysparkle.matewave.ui.theme.OnAccent
|
||||
import cc.skysparkle.matewave.ui.theme.PanelBorder
|
||||
import cc.skysparkle.matewave.ui.theme.Surface1
|
||||
import cc.skysparkle.matewave.ui.theme.Surface2
|
||||
import cc.skysparkle.matewave.ui.theme.TabletMaxContentWidth
|
||||
import cc.skysparkle.matewave.ui.theme.UiCornerRadius
|
||||
import cc.skysparkle.matewave.ui.theme.glass
|
||||
import cc.skysparkle.matewave.ui.theme.ink
|
||||
import cc.skysparkle.matewave.viewmodel.GameViewModel
|
||||
import cc.skysparkle.matewave.viewmodel.ResumeInfo
|
||||
import cc.skysparkle.matewave.ui.components.displayName
|
||||
|
||||
@Composable
|
||||
fun MainMenuScreen(
|
||||
@@ -86,40 +91,53 @@ fun MainMenuScreen(
|
||||
val context = LocalContext.current
|
||||
val resumable by viewModel.resumable.collectAsState()
|
||||
val ongoing = resumable
|
||||
val hasOngoingGame = ongoing != null
|
||||
val profile = remember { cc.skysparkle.matewave.data.ProfileStore.get() }
|
||||
val lastSetup = remember { cc.skysparkle.matewave.settings.LastGameSetup(context) }
|
||||
LaunchedEffect(Unit) { studyViewModel.init(context) }
|
||||
val study by studyViewModel.overview.collectAsState()
|
||||
|
||||
var showRatingGate by remember { mutableStateOf(false) }
|
||||
var showStats by remember { mutableStateOf(false) }
|
||||
|
||||
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.TopCenter) {
|
||||
Box(modifier = Modifier.fillMaxSize().horizontalSafePadding(), contentAlignment = Alignment.TopCenter) {
|
||||
Column(modifier = Modifier.fillMaxSize().widthIn(max = TabletMaxContentWidth)) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.statusBarsPadding()
|
||||
.padding(top = 16.dp, start = 20.dp, end = 20.dp, bottom = 10.dp),
|
||||
.padding(top = 12.dp, start = 20.dp, end = 20.dp, bottom = 4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Image(
|
||||
painter = painterResource(R.drawable.logo_knight),
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(width = 30.dp, height = 44.dp)
|
||||
)
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Greeting(modifier = Modifier.weight(1f))
|
||||
// The rating is always in sight.
|
||||
Box(
|
||||
modifier = Modifier.size(44.dp).clip(CircleShape).background(ChessGreen),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
Image(
|
||||
painter = painterResource(R.drawable.logo_knight),
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(width = 20.dp, height = 29.dp)
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Text(
|
||||
"${profile.elo}",
|
||||
"matewave",
|
||||
color = ink,
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
style = MaterialTheme.typography.headlineSmall.copy(fontSize = 17.sp, letterSpacing = (-0.3).sp),
|
||||
maxLines = 1
|
||||
)
|
||||
Spacer(Modifier.weight(1f))
|
||||
// The rating is always in sight.
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(50))
|
||||
.background(ink.copy(alpha = 0.10f))
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp)
|
||||
)
|
||||
.background(Surface2)
|
||||
.padding(start = 10.dp, end = 14.dp, top = 8.dp, bottom = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
AppIcon(R.drawable.ic_rating, size = 18.dp, tint = Lime)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text("${profile.elo}", color = ink, style = MaterialTheme.typography.titleSmall)
|
||||
}
|
||||
}
|
||||
|
||||
Column(
|
||||
@@ -130,70 +148,71 @@ fun MainMenuScreen(
|
||||
.verticalScroll(rememberScrollState()),
|
||||
verticalArrangement = Arrangement.spacedBy(14.dp)
|
||||
) {
|
||||
// The most urgent thing first: an unfinished game.
|
||||
if (ongoing != null) ContinueCard(ongoing, onContinueGame)
|
||||
Hero()
|
||||
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(12.dp), modifier = Modifier.fillMaxWidth()) {
|
||||
ModeTile(
|
||||
iconRes = R.drawable.ic_ai_app,
|
||||
title = stringResource(R.string.mode_ai_title),
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().height(268.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp)
|
||||
) {
|
||||
AiCard(
|
||||
subtitle = stringResource(R.string.mode_ai_subtitle),
|
||||
modifier = Modifier.weight(1f),
|
||||
modifier = Modifier.weight(1f).fillMaxHeight(),
|
||||
onClick = { if (profile.levelChosen) onVsAiClick() else showRatingGate = true }
|
||||
)
|
||||
ModeTile(
|
||||
iconRes = R.drawable.ic_profile_photo,
|
||||
title = stringResource(R.string.mode_online_title),
|
||||
subtitle = stringResource(R.string.mode_online_subtitle),
|
||||
modifier = Modifier.weight(1f),
|
||||
onClick = { if (profile.levelChosen) onVsPlayerClick() else showRatingGate = true }
|
||||
)
|
||||
Column(
|
||||
modifier = Modifier.weight(1f).fillMaxHeight(),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp)
|
||||
) {
|
||||
SmallModeCard(
|
||||
iconRes = R.drawable.ic_versus,
|
||||
title = stringResource(R.string.mode_online_title),
|
||||
subtitle = stringResource(R.string.mode_online_subtitle),
|
||||
modifier = Modifier.weight(1f).fillMaxWidth(),
|
||||
onClick = { if (profile.levelChosen) onVsPlayerClick() else showRatingGate = true }
|
||||
)
|
||||
// The most urgent thing takes this slot: an unfinished game, otherwise a quick rematch.
|
||||
if (ongoing != null) {
|
||||
ContinueCard(ongoing, Modifier.weight(1f).fillMaxWidth(), onContinueGame)
|
||||
} else {
|
||||
SmallModeCard(
|
||||
iconRes = R.drawable.ic_quick_game,
|
||||
title = stringResource(R.string.quick_game_title),
|
||||
subtitle = stringResource(difficultyName(lastSetup.aiDifficulty)) +
|
||||
" · " + lastSetup.aiTime.displayName(),
|
||||
modifier = Modifier.weight(1f).fillMaxWidth(),
|
||||
onClick = { if (profile.levelChosen) onQuickGame() else showRatingGate = true }
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SectionCaption(stringResource(R.string.home_today))
|
||||
ListGroup {
|
||||
if (!hasOngoingGame) {
|
||||
ListRow(
|
||||
title = stringResource(R.string.quick_game_title),
|
||||
subtitle = stringResource(
|
||||
R.string.quick_game_subtitle,
|
||||
stringResource(difficultyName(lastSetup.aiDifficulty)),
|
||||
lastSetup.aiTime.displayName()
|
||||
),
|
||||
icon = R.drawable.ic_quick_game,
|
||||
iconTint = ChessGreen,
|
||||
chevron = true,
|
||||
onClick = { if (profile.levelChosen) onQuickGame() else showRatingGate = true }
|
||||
)
|
||||
ListDivider()
|
||||
}
|
||||
if (study.dueCards > 0) {
|
||||
ListRow(
|
||||
title = stringResource(R.string.study_review_title),
|
||||
subtitle = stringResource(R.string.study_review_summary, study.dueCards, study.dueCourses),
|
||||
icon = R.drawable.ic_review,
|
||||
iconTint = cc.skysparkle.matewave.ui.screens.StarGold,
|
||||
chevron = true,
|
||||
onClick = onStudyClick
|
||||
)
|
||||
} else {
|
||||
ListRow(
|
||||
title = stringResource(R.string.study_title),
|
||||
subtitle = stringResource(R.string.study_menu_subtitle),
|
||||
icon = R.drawable.ic_crown,
|
||||
chevron = true,
|
||||
onClick = onStudyClick
|
||||
)
|
||||
}
|
||||
ListDivider()
|
||||
ListRow(
|
||||
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
val due = study.dueCards > 0
|
||||
LearnCard(
|
||||
iconRes = if (due) R.drawable.ic_review else R.drawable.ic_study,
|
||||
title = stringResource(if (due) R.string.study_review_title else R.string.study_title),
|
||||
subtitle = if (due) {
|
||||
stringResource(R.string.study_review_summary, study.dueCards, study.dueCourses)
|
||||
} else {
|
||||
stringResource(R.string.study_menu_subtitle)
|
||||
},
|
||||
highlighted = due,
|
||||
modifier = Modifier.weight(1f),
|
||||
onClick = onStudyClick
|
||||
)
|
||||
LearnCard(
|
||||
iconRes = R.drawable.ic_puzzle,
|
||||
title = stringResource(R.string.puzzles_title),
|
||||
subtitle = stringResource(R.string.puzzles_subtitle),
|
||||
icon = R.drawable.ic_puzzle,
|
||||
chevron = true,
|
||||
subtitle = stringResource(R.string.puzzle_solved_count, Stats.solvedPuzzles().size),
|
||||
highlighted = false,
|
||||
modifier = Modifier.weight(1f),
|
||||
onClick = onPuzzlesClick
|
||||
)
|
||||
}
|
||||
|
||||
ProgressPanel(elo = profile.elo, onClick = { showStats = true })
|
||||
Spacer(Modifier.height(4.dp))
|
||||
}
|
||||
|
||||
Box(modifier = Modifier.navigationBarsPadding()) {
|
||||
@@ -215,10 +234,11 @@ fun MainMenuScreen(
|
||||
onDismiss = { showRatingGate = false }
|
||||
)
|
||||
}
|
||||
if (showStats) StatsDialog(onDismiss = { showStats = false })
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Greeting(modifier: Modifier = Modifier) {
|
||||
private fun Hero() {
|
||||
val hour = remember { java.util.Calendar.getInstance().get(java.util.Calendar.HOUR_OF_DAY) }
|
||||
val greeting = when (hour) {
|
||||
in 5..11 -> stringResource(R.string.greeting_morning)
|
||||
@@ -226,65 +246,236 @@ private fun Greeting(modifier: Modifier = Modifier) {
|
||||
in 18..22 -> stringResource(R.string.greeting_evening)
|
||||
else -> stringResource(R.string.greeting_night)
|
||||
}
|
||||
Column(modifier = modifier) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(greeting, color = ink, style = MaterialTheme.typography.headlineSmall)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text("👋", fontSize = 20.sp)
|
||||
Box(modifier = Modifier.fillMaxWidth().padding(top = 8.dp)) {
|
||||
Column(modifier = Modifier.padding(end = 76.dp)) {
|
||||
Text("$greeting 👋", color = ink.copy(alpha = 0.6f), style = MaterialTheme.typography.bodyLarge)
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Text(
|
||||
stringResource(R.string.home_hero),
|
||||
color = ink,
|
||||
style = HeroTextStyle,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
)
|
||||
}
|
||||
Text(stringResource(R.string.greeting_ready), color = ink.copy(alpha = 0.7f), style = MaterialTheme.typography.bodyMedium)
|
||||
Image(
|
||||
painter = painterResource(R.drawable.piece_white_knight),
|
||||
contentDescription = null,
|
||||
modifier = Modifier
|
||||
.align(Alignment.CenterEnd)
|
||||
.size(88.dp)
|
||||
.rotate(-14f)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** The main mode: a tall neon card with a big piece, like the hero tile of the mockup. */
|
||||
@Composable
|
||||
private fun AiCard(subtitle: String, modifier: Modifier = Modifier, onClick: () -> Unit) {
|
||||
Box(
|
||||
modifier = modifier
|
||||
.clip(GlassShape)
|
||||
.background(ChessGreen)
|
||||
.wavePattern(OnAccent.copy(alpha = 0.16f))
|
||||
.clickable(onClick = onClick)
|
||||
) {
|
||||
Image(
|
||||
painter = painterResource(R.drawable.piece_black_king),
|
||||
contentDescription = null,
|
||||
modifier = Modifier
|
||||
.align(Alignment.TopEnd)
|
||||
.padding(top = 10.dp, end = 4.dp)
|
||||
.size(108.dp)
|
||||
.rotate(10f)
|
||||
)
|
||||
Column(
|
||||
modifier = Modifier.align(Alignment.BottomStart).fillMaxWidth().padding(16.dp)
|
||||
) {
|
||||
Text(
|
||||
stringResource(R.string.mode_ai_title),
|
||||
color = OnAccent,
|
||||
style = MaterialTheme.typography.headlineSmall.copy(fontSize = 19.sp, lineHeight = 24.sp),
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
)
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
subtitle,
|
||||
color = OnAccent.copy(alpha = 0.7f),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SmallModeCard(
|
||||
iconRes: Int,
|
||||
title: String,
|
||||
subtitle: String,
|
||||
modifier: Modifier = Modifier,
|
||||
onClick: () -> Unit
|
||||
) {
|
||||
Column(
|
||||
modifier = modifier
|
||||
.clip(GlassShape)
|
||||
.background(Surface1)
|
||||
.border(1.dp, PanelBorder, GlassShape)
|
||||
.clickable(onClick = onClick)
|
||||
.padding(14.dp)
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Box(
|
||||
modifier = Modifier.size(34.dp).clip(CircleShape).background(ChessGreen.copy(alpha = 0.14f)),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
AppIcon(iconRes, size = 18.dp, tint = ChessGreen)
|
||||
}
|
||||
Spacer(Modifier.weight(1f))
|
||||
ArrowBubble(fill = Surface2, tint = ink)
|
||||
}
|
||||
Spacer(Modifier.weight(1f))
|
||||
Text(title, color = ink, style = MaterialTheme.typography.titleMedium, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
||||
Text(subtitle, color = ink.copy(alpha = 0.55f), style = MaterialTheme.typography.bodySmall, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
|
||||
/** An unfinished game against the AI: move number, whose turn and the clock, one tap to resume. */
|
||||
@Composable
|
||||
private fun ContinueCard(info: ResumeInfo, onClick: () -> Unit) {
|
||||
private fun ContinueCard(info: ResumeInfo, modifier: Modifier = Modifier, onClick: () -> Unit) {
|
||||
val turn = stringResource(if (info.myTurn) R.string.home_your_move else R.string.home_ai_move)
|
||||
val clock = info.myMillis?.let { ms ->
|
||||
val s = ms.coerceAtLeast(0) / 1000
|
||||
"%d:%02d".format(s / 60, s % 60)
|
||||
}
|
||||
val details = stringResource(R.string.home_continue_details, info.moveNumber, turn) + (clock?.let { " · $it" } ?: "")
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.glass(RoundedCornerShape(UiCornerRadius))
|
||||
.border(1.dp, ChessGreen.copy(alpha = 0.6f), RoundedCornerShape(UiCornerRadius))
|
||||
Column(
|
||||
modifier = modifier
|
||||
.clip(GlassShape)
|
||||
.background(Lime)
|
||||
.clickable(onClick = onClick)
|
||||
.padding(16.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
.padding(14.dp)
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(stringResource(R.string.continue_game_title), color = ink, style = MaterialTheme.typography.titleMedium)
|
||||
Text(details, color = ink.copy(alpha = 0.7f), style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
Box(
|
||||
modifier = Modifier.size(44.dp).clip(CircleShape).background(ChessGreen),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
cc.skysparkle.matewave.ui.components.AppIcon(R.drawable.ic_arrow_forward, size = 20.dp, tint = Color.White)
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Box(
|
||||
modifier = Modifier.size(34.dp).clip(CircleShape).background(OnAccent.copy(alpha = 0.1f)),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
AppIcon(R.drawable.ic_play, size = 18.dp, tint = OnAccent)
|
||||
}
|
||||
Spacer(Modifier.weight(1f))
|
||||
ArrowBubble(fill = OnAccent, tint = Lime)
|
||||
}
|
||||
Spacer(Modifier.weight(1f))
|
||||
Text(
|
||||
stringResource(R.string.continue_game_title),
|
||||
color = OnAccent,
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
)
|
||||
Text(details, color = OnAccent.copy(alpha = 0.7f), style = MaterialTheme.typography.bodySmall, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
|
||||
/** One of the two equal ways to start a game. */
|
||||
@Composable
|
||||
private fun ModeTile(iconRes: Int, title: String, subtitle: String, modifier: Modifier = Modifier, onClick: () -> Unit) {
|
||||
private fun ArrowBubble(fill: Color, tint: Color) {
|
||||
Box(
|
||||
modifier = Modifier.size(30.dp).clip(CircleShape).background(fill),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
AppIcon(R.drawable.ic_arrow_forward, size = 16.dp, tint = tint)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun LearnCard(
|
||||
iconRes: Int,
|
||||
title: String,
|
||||
subtitle: String,
|
||||
highlighted: Boolean,
|
||||
modifier: Modifier = Modifier,
|
||||
onClick: () -> Unit
|
||||
) {
|
||||
Column(
|
||||
modifier = modifier
|
||||
.glass(RoundedCornerShape(UiCornerRadius))
|
||||
.height(148.dp)
|
||||
.clip(GlassShape)
|
||||
.background(Surface1)
|
||||
.border(1.dp, if (highlighted) ChessGreen.copy(alpha = 0.7f) else PanelBorder, GlassShape)
|
||||
.clickable(onClick = onClick)
|
||||
.padding(14.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(4.dp)
|
||||
.padding(14.dp)
|
||||
) {
|
||||
Image(
|
||||
painter = painterResource(iconRes),
|
||||
contentDescription = null,
|
||||
colorFilter = ColorFilter.tint(ink),
|
||||
modifier = Modifier.size(24.dp)
|
||||
)
|
||||
Text(title, color = ink, style = MaterialTheme.typography.titleMedium)
|
||||
Text(subtitle, color = ink.copy(alpha = 0.65f), style = MaterialTheme.typography.bodySmall)
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.size(40.dp)
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(if (highlighted) ChessGreen else Surface2),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
AppIcon(iconRes, size = 22.dp, tint = if (highlighted) OnAccent else ChessGreen)
|
||||
}
|
||||
Spacer(Modifier.weight(1f))
|
||||
Text(title, color = ink, style = MaterialTheme.typography.titleSmall, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Text(subtitle, color = ink.copy(alpha = 0.55f), style = MaterialTheme.typography.bodySmall, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
|
||||
/** Rating with its trend and the three numbers players look at; opens the statistics. */
|
||||
@Composable
|
||||
private fun ProgressPanel(elo: Int, onClick: () -> Unit) {
|
||||
val curve = remember(elo) { Stats.ratingCurve(elo) }
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(GlassShape)
|
||||
.background(Surface1)
|
||||
.border(1.dp, PanelBorder, GlassShape)
|
||||
.clickable(onClick = onClick)
|
||||
.padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp)
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
stringResource(R.string.account_progress).uppercase(),
|
||||
color = ink.copy(alpha = 0.5f),
|
||||
style = MaterialTheme.typography.labelMedium
|
||||
)
|
||||
Text("$elo", color = ink, style = MaterialTheme.typography.headlineMedium)
|
||||
}
|
||||
MiniRatingGraph(points = curve, modifier = Modifier.width(132.dp).height(44.dp), showDots = false, showGrid = false)
|
||||
}
|
||||
StatTiles()
|
||||
}
|
||||
}
|
||||
|
||||
/** Games, wins and streak, as three equal tiles. */
|
||||
@Composable
|
||||
internal fun StatTiles() {
|
||||
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
StatTile(R.drawable.ic_play, stringResource(R.string.stat_games), "${Stats.gamesPlayed()}", Modifier.weight(1f))
|
||||
StatTile(R.drawable.ic_trophy, stringResource(R.string.stat_wins), "${Stats.wins()}", Modifier.weight(1f))
|
||||
StatTile(R.drawable.ic_speed, stringResource(R.string.stat_streak), "${Stats.streak()}", Modifier.weight(1f))
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StatTile(iconRes: Int, label: String, value: String, modifier: Modifier = Modifier) {
|
||||
Column(
|
||||
modifier = modifier
|
||||
.clip(RoundedCornerShape(16.dp))
|
||||
.background(Surface2)
|
||||
.padding(vertical = 12.dp, horizontal = 8.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally
|
||||
) {
|
||||
AppIcon(iconRes, size = 18.dp, tint = ChessGreen)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(label, color = ink.copy(alpha = 0.6f), style = MaterialTheme.typography.labelSmall, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(value, color = ink, style = MaterialTheme.typography.titleMedium, maxLines = 1)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -326,46 +517,58 @@ internal fun StatsDialog(onDismiss: () -> Unit) {
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun MiniRatingGraph(points: List<Int>, modifier: Modifier = Modifier) {
|
||||
internal fun MiniRatingGraph(points: List<Int>, modifier: Modifier = Modifier, showDots: Boolean = true, showGrid: Boolean = true) {
|
||||
val lineInk = ink
|
||||
Canvas(modifier = modifier) {
|
||||
if (points.size < 2) return@Canvas
|
||||
val minV = points.min().toFloat()
|
||||
val maxV = points.max().toFloat()
|
||||
val range = (maxV - minV).coerceAtLeast(1f)
|
||||
val stepX = size.width / (points.size - 1)
|
||||
// Paths, gradient and stroke are built once per size and reused by every redraw.
|
||||
Spacer(
|
||||
modifier = modifier.drawWithCache {
|
||||
if (points.size < 2) return@drawWithCache onDrawBehind {}
|
||||
val minV = points.min().toFloat()
|
||||
val maxV = points.max().toFloat()
|
||||
val range = (maxV - minV).coerceAtLeast(1f)
|
||||
val stepX = size.width / (points.size - 1)
|
||||
|
||||
fun yOf(v: Int) = size.height - ((v - minV) / range) * size.height
|
||||
fun yOf(v: Int) = size.height - ((v - minV) / range) * size.height
|
||||
|
||||
val gridLines = 4
|
||||
for (i in 0..gridLines) {
|
||||
val y = size.height / gridLines * i
|
||||
drawLine(lineInk.copy(alpha = 0.08f), Offset(0f, y), Offset(size.width, y), strokeWidth = 1f)
|
||||
}
|
||||
// Reference line: the rating at the start of the shown history.
|
||||
val zeroY = yOf(points.first())
|
||||
drawLine(lineInk.copy(alpha = 0.3f), Offset(0f, zeroY), Offset(size.width, zeroY), strokeWidth = 1.5f)
|
||||
// Reference line: the rating at the start of the shown history.
|
||||
val zeroY = yOf(points.first())
|
||||
val line = Path().apply {
|
||||
moveTo(0f, yOf(points[0]))
|
||||
points.forEachIndexed { i, v -> if (i > 0) lineTo(i * stepX, yOf(v)) }
|
||||
}
|
||||
val fill = Path().apply {
|
||||
addPath(line)
|
||||
lineTo(size.width, size.height)
|
||||
lineTo(0f, size.height)
|
||||
close()
|
||||
}
|
||||
val fillBrush = Brush.verticalGradient(listOf(ChessGreen.copy(alpha = 0.35f), ChessGreen.copy(alpha = 0f)))
|
||||
val lineBrush = Brush.horizontalGradient(listOf(ChessGreen, Lime))
|
||||
val lineStroke = Stroke(width = 2.5.dp.toPx(), cap = StrokeCap.Round)
|
||||
|
||||
val line = Path().apply {
|
||||
moveTo(0f, yOf(points[0]))
|
||||
points.forEachIndexed { i, v -> if (i > 0) lineTo(i * stepX, yOf(v)) }
|
||||
}
|
||||
val fill = Path().apply {
|
||||
addPath(line)
|
||||
lineTo(size.width, size.height)
|
||||
lineTo(0f, size.height)
|
||||
close()
|
||||
}
|
||||
drawPath(
|
||||
fill,
|
||||
brush = Brush.verticalGradient(listOf(ChessGreen.copy(alpha = 0.35f), ChessGreen.copy(alpha = 0f)))
|
||||
)
|
||||
drawPath(line, color = ChessGreen, style = Stroke(width = 4f, cap = StrokeCap.Round))
|
||||
onDrawBehind {
|
||||
if (showGrid) {
|
||||
val gridLines = 4
|
||||
for (i in 0..gridLines) {
|
||||
val y = size.height / gridLines * i
|
||||
drawLine(lineInk.copy(alpha = 0.06f), Offset(0f, y), Offset(size.width, y), strokeWidth = 1f)
|
||||
}
|
||||
drawLine(lineInk.copy(alpha = 0.25f), Offset(0f, zeroY), Offset(size.width, zeroY), strokeWidth = 1.5f)
|
||||
}
|
||||
|
||||
points.forEachIndexed { i, v ->
|
||||
val center = Offset(i * stepX, yOf(v))
|
||||
drawCircle(color = lineInk, radius = 5f, center = center)
|
||||
drawCircle(color = ChessGreen, radius = 3f, center = center)
|
||||
drawPath(fill, brush = fillBrush)
|
||||
drawPath(line, brush = lineBrush, style = lineStroke)
|
||||
|
||||
if (showDots) {
|
||||
points.forEachIndexed { i, v ->
|
||||
val center = Offset(i * stepX, yOf(v))
|
||||
drawCircle(color = Surface1, radius = 5f, center = center)
|
||||
drawCircle(color = ChessGreen, radius = 3f, center = center)
|
||||
}
|
||||
} else {
|
||||
drawCircle(color = Lime, radius = 4.dp.toPx(), center = Offset(size.width, yOf(points.last())))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,365 @@
|
||||
package cc.skysparkle.matewave.ui.screens
|
||||
|
||||
import android.content.Context
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.annotation.DrawableRes
|
||||
import androidx.annotation.StringRes
|
||||
import androidx.compose.animation.core.animateDpAsState
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.imePadding
|
||||
import androidx.compose.foundation.layout.navigationBarsPadding
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.statusBarsPadding
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.pager.HorizontalPager
|
||||
import androidx.compose.foundation.pager.rememberPagerState
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import cc.skysparkle.matewave.R
|
||||
import cc.skysparkle.matewave.data.ProfileStore
|
||||
import cc.skysparkle.matewave.network.Transports
|
||||
import cc.skysparkle.matewave.ui.components.AppIcon
|
||||
import cc.skysparkle.matewave.ui.components.GlassButton
|
||||
import cc.skysparkle.matewave.ui.components.horizontalSafePadding
|
||||
import cc.skysparkle.matewave.ui.theme.ChessGreen
|
||||
import cc.skysparkle.matewave.ui.theme.PanelBorder
|
||||
import cc.skysparkle.matewave.ui.theme.Surface2
|
||||
import cc.skysparkle.matewave.ui.theme.TabletMaxContentWidth
|
||||
import cc.skysparkle.matewave.ui.theme.ink
|
||||
import cc.skysparkle.matewave.ui.theme.whiteOutlinedTextFieldColors
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/**
|
||||
* First-launch guide. New players see it once; Settings → «Show the guide» opens it again.
|
||||
* Anyone who already played before this version (a name, a chosen level or games against the
|
||||
* AI on record) is treated as having seen it.
|
||||
*/
|
||||
object Onboarding {
|
||||
private const val PREFS = "onboarding_prefs"
|
||||
private const val KEY_DONE = "done"
|
||||
|
||||
fun needed(context: Context): Boolean {
|
||||
val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||
if (prefs.getBoolean(KEY_DONE, false)) return false
|
||||
val profile = context.getSharedPreferences("chess_profile_prefs", Context.MODE_PRIVATE)
|
||||
val stats = context.getSharedPreferences("chess_stats_prefs", Context.MODE_PRIVATE)
|
||||
val playedBefore = profile.contains("name") || profile.getBoolean("level_chosen", false) || stats.all.isNotEmpty()
|
||||
if (playedBefore) {
|
||||
markDone(context)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
fun markDone(context: Context) {
|
||||
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putBoolean(KEY_DONE, true).apply()
|
||||
}
|
||||
}
|
||||
|
||||
private data class GuidePage(
|
||||
@param:DrawableRes val iconRes: Int,
|
||||
@param:StringRes val titleRes: Int,
|
||||
@param:StringRes val textRes: Int
|
||||
)
|
||||
|
||||
private val PAGES = listOf(
|
||||
GuidePage(R.drawable.ic_launcher_card, R.string.guide_welcome_title, R.string.guide_welcome_text),
|
||||
GuidePage(R.drawable.ic_puzzle, R.string.guide_play_title, R.string.guide_play_text),
|
||||
GuidePage(R.drawable.ic_bluetooth, R.string.guide_nearby_title, R.string.guide_nearby_text),
|
||||
// the last page asks for a name and a level
|
||||
GuidePage(R.drawable.ic_default_avatar, R.string.guide_you_title, R.string.guide_you_text)
|
||||
)
|
||||
|
||||
private data class GuideLevel(@param:StringRes val labelRes: Int, val elo: Int)
|
||||
|
||||
// The same levels as in the account screen
|
||||
private val LEVELS = listOf(
|
||||
GuideLevel(R.string.skill_novice, 800),
|
||||
GuideLevel(R.string.skill_amateur, 1200),
|
||||
GuideLevel(R.string.skill_pro, 1800),
|
||||
GuideLevel(R.string.skill_master, 2200)
|
||||
)
|
||||
|
||||
private const val MAX_NAME_LENGTH = 20
|
||||
|
||||
/**
|
||||
* @param replay opened from Settings: back on the first page closes it, and the level is not
|
||||
* asked again once chosen.
|
||||
*/
|
||||
@Composable
|
||||
fun OnboardingScreen(replay: Boolean, onDone: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
val pager = rememberPagerState(pageCount = { PAGES.size })
|
||||
val last = pager.currentPage == PAGES.lastIndex
|
||||
|
||||
val profile = remember { ProfileStore.get() }
|
||||
val defaultName = stringResource(R.string.player_default_name)
|
||||
var name by rememberSaveable { mutableStateOf(if (profile.name == defaultName) "" else profile.name) }
|
||||
var level by rememberSaveable { mutableStateOf<Int?>(null) }
|
||||
val askLevel = !profile.levelChosen
|
||||
|
||||
val finish = {
|
||||
val trimmed = name.trim()
|
||||
var changed = false
|
||||
if (trimmed.isNotEmpty() && trimmed != profile.name) {
|
||||
ProfileStore.setName(trimmed)
|
||||
changed = true
|
||||
}
|
||||
val elo = level
|
||||
if (askLevel && elo != null) {
|
||||
ProfileStore.setStartingElo(elo)
|
||||
changed = true
|
||||
}
|
||||
// Nearby players see the new name and rating right away
|
||||
if (changed) {
|
||||
Transports.lan(context).republishProfile()
|
||||
Transports.ble(context).republishProfile()
|
||||
}
|
||||
Onboarding.markDone(context)
|
||||
onDone()
|
||||
}
|
||||
|
||||
BackHandler(enabled = pager.currentPage > 0 || replay) {
|
||||
if (pager.currentPage > 0) scope.launch { pager.animateScrollToPage(pager.currentPage - 1) } else onDone()
|
||||
}
|
||||
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.horizontalSafePadding()
|
||||
.testTag("onboarding"),
|
||||
contentAlignment = Alignment.TopCenter
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.widthIn(max = TabletMaxContentWidth)
|
||||
.statusBarsPadding()
|
||||
.navigationBarsPadding()
|
||||
.imePadding()
|
||||
) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.height(56.dp)
|
||||
.padding(horizontal = 12.dp),
|
||||
contentAlignment = Alignment.CenterEnd
|
||||
) {
|
||||
if (!last) {
|
||||
Text(
|
||||
text = stringResource(R.string.guide_skip),
|
||||
color = ink.copy(alpha = 0.7f),
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
modifier = Modifier
|
||||
.clip(CircleShape)
|
||||
// Skipping still lands on the last page: the name and level are asked there
|
||||
.clickable(role = Role.Button) { scope.launch { pager.animateScrollToPage(PAGES.lastIndex) } }
|
||||
.padding(horizontal = 14.dp, vertical = 10.dp)
|
||||
.testTag("onboarding_skip")
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
HorizontalPager(
|
||||
state = pager,
|
||||
modifier = Modifier
|
||||
.weight(1f)
|
||||
.fillMaxWidth()
|
||||
) { index ->
|
||||
val page = PAGES[index]
|
||||
PageColumn {
|
||||
PageIcon(page, isLogo = index == 0)
|
||||
Spacer(Modifier.height(32.dp))
|
||||
Text(
|
||||
text = stringResource(page.titleRes),
|
||||
color = ink,
|
||||
style = MaterialTheme.typography.headlineSmall.copy(fontWeight = FontWeight.Bold),
|
||||
textAlign = TextAlign.Center
|
||||
)
|
||||
Spacer(Modifier.height(12.dp))
|
||||
Text(
|
||||
text = stringResource(page.textRes),
|
||||
color = ink.copy(alpha = 0.7f),
|
||||
style = MaterialTheme.typography.bodyLarge.copy(lineHeight = 24.sp),
|
||||
textAlign = TextAlign.Center
|
||||
)
|
||||
if (index == PAGES.lastIndex) {
|
||||
Spacer(Modifier.height(24.dp))
|
||||
AboutYou(
|
||||
name = name,
|
||||
onName = { if (it.length <= MAX_NAME_LENGTH) name = it },
|
||||
askLevel = askLevel,
|
||||
level = level,
|
||||
onLevel = { level = it }
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Dots(count = PAGES.size, current = pager.currentPage)
|
||||
|
||||
GlassButton(
|
||||
onClick = { if (last) finish() else scope.launch { pager.animateScrollToPage(pager.currentPage + 1) } },
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 24.dp, vertical = 20.dp)
|
||||
.testTag("onboarding_next")
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(if (last) R.string.guide_start else R.string.guide_next),
|
||||
style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PageColumn(content: @Composable () -> Unit) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.verticalScroll(rememberScrollState())
|
||||
.padding(horizontal = 28.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.Center
|
||||
) {
|
||||
content()
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PageIcon(page: GuidePage, isLogo: Boolean) {
|
||||
if (isLogo) {
|
||||
// The app icon picture, not a glyph
|
||||
Image(
|
||||
painter = painterResource(page.iconRes),
|
||||
contentDescription = null,
|
||||
contentScale = ContentScale.Crop,
|
||||
modifier = Modifier
|
||||
.size(120.dp)
|
||||
.clip(RoundedCornerShape(32.dp))
|
||||
.border(1.dp, PanelBorder, RoundedCornerShape(32.dp))
|
||||
)
|
||||
} else {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.size(120.dp)
|
||||
.clip(CircleShape)
|
||||
.background(Surface2)
|
||||
.border(1.dp, PanelBorder, CircleShape),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
AppIcon(page.iconRes, size = 52.dp, tint = ChessGreen)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AboutYou(
|
||||
name: String,
|
||||
onName: (String) -> Unit,
|
||||
askLevel: Boolean,
|
||||
level: Int?,
|
||||
onLevel: (Int) -> Unit
|
||||
) {
|
||||
Column(modifier = Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
Text(stringResource(R.string.account_name), color = ink.copy(alpha = 0.7f), style = MaterialTheme.typography.labelLarge)
|
||||
OutlinedTextField(
|
||||
value = name,
|
||||
onValueChange = onName,
|
||||
singleLine = true,
|
||||
placeholder = { Text(stringResource(R.string.player_default_name), color = ink.copy(alpha = 0.4f)) },
|
||||
colors = whiteOutlinedTextFieldColors(),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.testTag("onboarding_name")
|
||||
)
|
||||
if (askLevel) {
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(stringResource(R.string.account_level_dialog_title), color = ink.copy(alpha = 0.7f), style = MaterialTheme.typography.labelLarge)
|
||||
LEVELS.forEach { option ->
|
||||
val selected = option.elo == level
|
||||
val shape = RoundedCornerShape(16.dp)
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(shape)
|
||||
.background(Surface2)
|
||||
.border(if (selected) 2.dp else 1.dp, if (selected) ChessGreen else PanelBorder, shape)
|
||||
.clickable(role = Role.RadioButton) { onLevel(option.elo) }
|
||||
.padding(horizontal = 16.dp, vertical = 14.dp),
|
||||
horizontalArrangement = Arrangement.SpaceBetween
|
||||
) {
|
||||
Text(stringResource(option.labelRes), color = ink, style = MaterialTheme.typography.titleMedium)
|
||||
Text("~${option.elo}", color = if (selected) ChessGreen else ink.copy(alpha = 0.7f), style = MaterialTheme.typography.titleMedium)
|
||||
}
|
||||
}
|
||||
Text(stringResource(R.string.guide_level_hint), color = ink.copy(alpha = 0.5f), style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Dots(count: Int, current: Int) {
|
||||
val label = stringResource(R.string.guide_page_of, current + 1, count)
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.semantics { contentDescription = label },
|
||||
horizontalArrangement = Arrangement.Center,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
repeat(count) { i ->
|
||||
val selected = i == current
|
||||
val width by animateDpAsState(if (selected) 22.dp else 8.dp, label = "guide_dot")
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.padding(horizontal = 4.dp)
|
||||
.size(width = width, height = 8.dp)
|
||||
.clip(CircleShape)
|
||||
.background(if (selected) ChessGreen else ink.copy(alpha = 0.2f))
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -47,6 +47,7 @@ import cc.skysparkle.matewave.openings.CourseInfo
|
||||
import cc.skysparkle.matewave.openings.CourseStatus
|
||||
import cc.skysparkle.matewave.openings.artRes
|
||||
import cc.skysparkle.matewave.ui.components.AppIcon
|
||||
import cc.skysparkle.matewave.ui.components.ButtonIcon
|
||||
import cc.skysparkle.matewave.ui.components.GlassButton
|
||||
import cc.skysparkle.matewave.ui.components.GlassScaffold
|
||||
import cc.skysparkle.matewave.ui.components.SetupSegmented
|
||||
@@ -148,7 +149,7 @@ private fun NextAction(overview: StudyOverview, viewModel: OpeningStudyViewModel
|
||||
button = stringResource(R.string.study_start_button)
|
||||
) { if (viewModel.open(firstNew.course)) onOpenTrainer() }
|
||||
nextDueAt != null -> Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
AppIcon(R.drawable.ic_review, size = 16.dp, tint = ink.copy(alpha = 0.55f))
|
||||
AppIcon(R.drawable.ic_review, size = 16.dp, tint = ink.copy(alpha = 0.7f))
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(stringResource(R.string.study_next_review, formatDueIn(nextDueAt)), color = ink.copy(alpha = 0.65f), style = MaterialTheme.typography.bodyMedium)
|
||||
}
|
||||
@@ -160,7 +161,7 @@ private fun ActionCard(icon: Int, title: String, subtitle: String?, button: Stri
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.glass(RoundedCornerShape(UiCornerRadius))
|
||||
.glass()
|
||||
.padding(horizontal = 14.dp, vertical = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
@@ -177,7 +178,10 @@ private fun ActionCard(icon: Int, title: String, subtitle: String?, button: Stri
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.width(12.dp))
|
||||
GlassButton(onClick = onClick) { Text(button, color = ink, maxLines = 1) }
|
||||
GlassButton(onClick = onClick) {
|
||||
ButtonIcon(R.drawable.ic_play)
|
||||
Text(button, maxLines = 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -230,7 +234,7 @@ private fun CourseCard(info: CourseInfo, modifier: Modifier, onClick: () -> Unit
|
||||
)
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
AppIcon(R.drawable.ic_timer, size = 12.dp, tint = ink.copy(alpha = 0.55f))
|
||||
AppIcon(R.drawable.ic_timer, size = 14.dp, tint = ink.copy(alpha = 0.7f))
|
||||
Spacer(Modifier.width(4.dp))
|
||||
Text(
|
||||
LocalContext.current.resources.getQuantityString(R.plurals.study_moves_count, info.total, info.total),
|
||||
@@ -266,7 +270,7 @@ private fun CourseCard(info: CourseInfo, modifier: Modifier, onClick: () -> Unit
|
||||
fun Stars(count: Int, size: androidx.compose.ui.unit.Dp = 16.dp) {
|
||||
Row {
|
||||
repeat(3) { i ->
|
||||
AppIcon(R.drawable.ic_star, size = size, tint = if (i < count) StarGold else ink.copy(alpha = 0.2f))
|
||||
AppIcon(R.drawable.ic_star, size = size, tint = if (i < count) StarGold else ink.copy(alpha = 0.3f))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -43,45 +43,52 @@ fun OpeningTrainerScreen(viewModel: OpeningStudyViewModel, onBack: () -> Unit) {
|
||||
val sans = state.sans
|
||||
val opening = remember(sans) { OpeningBook.openingName(sans) }
|
||||
|
||||
GlassScaffold(title = course.name, onBack = onBack) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
stringResource(
|
||||
when (state.mode) {
|
||||
SessionMode.LEARN -> R.string.study_mode_learn
|
||||
SessionMode.REVIEW -> R.string.study_mode_review
|
||||
SessionMode.PRACTICE -> R.string.study_mode_practice
|
||||
}
|
||||
),
|
||||
color = ChessGreen,
|
||||
style = MaterialTheme.typography.labelLarge
|
||||
)
|
||||
Spacer(Modifier.weight(1f))
|
||||
val asked = state.asked.size
|
||||
if (asked > 0 && state.phase != TrainerPhase.COMPLETE) {
|
||||
// Landscape: the board on the left, progress, moves and the task on the right
|
||||
cc.skysparkle.matewave.ui.components.BoardScaffold(
|
||||
title = course.name,
|
||||
onBack = onBack,
|
||||
above = {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
stringResource(R.string.study_progress, minOf(state.answered + 1, asked), asked),
|
||||
color = ink.copy(alpha = 0.7f),
|
||||
style = MaterialTheme.typography.bodySmall
|
||||
stringResource(
|
||||
when (state.mode) {
|
||||
SessionMode.LEARN -> R.string.study_mode_learn
|
||||
SessionMode.REVIEW -> R.string.study_mode_review
|
||||
SessionMode.PRACTICE -> R.string.study_mode_practice
|
||||
}
|
||||
),
|
||||
color = ChessGreen,
|
||||
style = MaterialTheme.typography.labelLarge
|
||||
)
|
||||
Spacer(Modifier.weight(1f))
|
||||
val asked = state.asked.size
|
||||
if (asked > 0 && state.phase != TrainerPhase.COMPLETE) {
|
||||
Text(
|
||||
stringResource(R.string.study_progress, minOf(state.answered + 1, asked), asked),
|
||||
color = ink.copy(alpha = 0.7f),
|
||||
style = MaterialTheme.typography.bodySmall
|
||||
)
|
||||
}
|
||||
}
|
||||
ProgressBar(state.answered.toFloat() / state.asked.size.coerceAtLeast(1))
|
||||
|
||||
MovesBar(sans = sans, startBoard = startBoard, opening = opening)
|
||||
},
|
||||
board = { boardModifier ->
|
||||
ChessBoardView(
|
||||
modifier = boardModifier,
|
||||
board = state.board,
|
||||
selectedSquare = state.selectedSquare,
|
||||
legalTargets = state.legalTargets,
|
||||
kingInCheckSquare = null,
|
||||
flipped = course.side == PieceColor.BLACK,
|
||||
onSquareClick = { viewModel.onSquareClick(it) },
|
||||
lastMove = state.lastMove,
|
||||
hintSquare = state.hintSquare,
|
||||
interactionEnabled = state.phase == TrainerPhase.YOUR_MOVE || state.phase == TrainerPhase.WRONG
|
||||
)
|
||||
}
|
||||
ProgressBar(state.answered.toFloat() / state.asked.size.coerceAtLeast(1))
|
||||
|
||||
MovesBar(sans = sans, startBoard = startBoard, currentIndex = sans.size, opening = opening)
|
||||
|
||||
ChessBoardView(
|
||||
board = state.board,
|
||||
selectedSquare = state.selectedSquare,
|
||||
legalTargets = state.legalTargets,
|
||||
kingInCheckSquare = null,
|
||||
flipped = course.side == PieceColor.BLACK,
|
||||
onSquareClick = { viewModel.onSquareClick(it) },
|
||||
lastMove = state.lastMove,
|
||||
hintSquare = state.hintSquare,
|
||||
interactionEnabled = state.phase == TrainerPhase.YOUR_MOVE || state.phase == TrainerPhase.WRONG
|
||||
)
|
||||
|
||||
) {
|
||||
when (state.phase) {
|
||||
TrainerPhase.YOUR_MOVE -> Text(
|
||||
stringResource(if (state.mode == SessionMode.LEARN) R.string.study_learn_prompt else R.string.study_recall_prompt),
|
||||
@@ -142,10 +149,12 @@ fun OpeningTrainerScreen(viewModel: OpeningStudyViewModel, onBack: () -> Unit) {
|
||||
}
|
||||
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
GlassOutlinedButton(onClick = { viewModel.practiceAgain() }, modifier = Modifier.weight(1f)) {
|
||||
ButtonIcon(R.drawable.ic_replay)
|
||||
Text(stringResource(R.string.study_again), color = ink, maxLines = 1)
|
||||
}
|
||||
GlassButton(onClick = { if (!viewModel.continueStudy()) onBack() }, modifier = Modifier.weight(1f)) {
|
||||
Text(stringResource(R.string.study_next), color = ink, maxLines = 1)
|
||||
ButtonIcon(R.drawable.ic_next)
|
||||
Text(stringResource(R.string.study_next), maxLines = 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -166,6 +175,7 @@ fun OpeningTrainerScreen(viewModel: OpeningStudyViewModel, onBack: () -> Unit) {
|
||||
// A review is not restarted: it would only replay the moves still due.
|
||||
if (state.mode != SessionMode.REVIEW) {
|
||||
GlassOutlinedButton(onClick = { viewModel.restart() }, modifier = Modifier.weight(1f)) {
|
||||
ButtonIcon(R.drawable.ic_restart)
|
||||
Text(stringResource(R.string.study_restart), color = ink, maxLines = 1)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,7 +12,6 @@ import androidx.compose.material3.SwitchDefaults
|
||||
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
|
||||
@@ -26,10 +25,7 @@ import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.height
|
||||
import cc.skysparkle.matewave.R
|
||||
import cc.skysparkle.matewave.settings.FeedbackSettings
|
||||
import cc.skysparkle.matewave.network.AppPermissions
|
||||
import cc.skysparkle.matewave.network.DisconnectReason
|
||||
import cc.skysparkle.matewave.network.NetworkLog
|
||||
import cc.skysparkle.matewave.network.NetworkRequirements
|
||||
import cc.skysparkle.matewave.ui.components.GlassCard
|
||||
import cc.skysparkle.matewave.ui.components.GlassOutlinedButton
|
||||
@@ -88,39 +84,8 @@ fun PermissionsScreen(onBack: () -> Unit) {
|
||||
cc.skysparkle.matewave.network.Transports.applyAnnounceSetting()
|
||||
},
|
||||
colors = SwitchDefaults.colors(
|
||||
checkedThumbColor = Color.White,
|
||||
checkedTrackColor = Color(0xFF4F8A5B)
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
val feedbackSettings = remember { FeedbackSettings(context) }
|
||||
var vibration by remember { mutableStateOf(feedbackSettings.vibrationEnabled) }
|
||||
GlassCard(modifier = Modifier.fillMaxWidth()) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
cc.skysparkle.matewave.ui.components.ButtonIcon(R.drawable.ic_vibration, size = 24.dp)
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
stringResource(R.string.perm_vibration_title),
|
||||
color = ink,
|
||||
style = MaterialTheme.typography.titleMedium
|
||||
)
|
||||
Text(
|
||||
stringResource(R.string.perm_vibration_text),
|
||||
color = ink.copy(alpha = 0.7f),
|
||||
style = MaterialTheme.typography.bodySmall
|
||||
)
|
||||
}
|
||||
Switch(
|
||||
checked = vibration,
|
||||
onCheckedChange = {
|
||||
vibration = it
|
||||
feedbackSettings.vibrationEnabled = it
|
||||
},
|
||||
colors = SwitchDefaults.colors(
|
||||
checkedThumbColor = Color.White,
|
||||
checkedTrackColor = Color(0xFF4F8A5B)
|
||||
checkedThumbColor = cc.skysparkle.matewave.ui.theme.OnAccent,
|
||||
checkedTrackColor = cc.skysparkle.matewave.ui.theme.ChessGreen
|
||||
)
|
||||
)
|
||||
}
|
||||
@@ -177,8 +142,8 @@ fun PermissionsScreen(onBack: () -> Unit) {
|
||||
}
|
||||
},
|
||||
colors = SwitchDefaults.colors(
|
||||
checkedThumbColor = Color.White,
|
||||
checkedTrackColor = Color(0xFF4F8A5B)
|
||||
checkedThumbColor = cc.skysparkle.matewave.ui.theme.OnAccent,
|
||||
checkedTrackColor = cc.skysparkle.matewave.ui.theme.ChessGreen
|
||||
)
|
||||
)
|
||||
}
|
||||
@@ -214,53 +179,6 @@ fun PermissionsScreen(onBack: () -> Unit) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val lastReason by NetworkLog.lastReason.collectAsState()
|
||||
if (lastReason != DisconnectReason.NONE) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
cc.skysparkle.matewave.ui.components.ButtonIcon(
|
||||
R.drawable.ic_error, tint = Color(0xFFFFC46B), size = 16.dp
|
||||
)
|
||||
Text(
|
||||
stringResource(R.string.diag_last_reason, stringResource(lastReason.textRes)),
|
||||
color = Color(0xFFFFC46B),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
modifier = Modifier.weight(1f)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
val metricsTick by cc.skysparkle.matewave.network.NetworkMetrics.updated.collectAsState()
|
||||
val metricsText = remember(metricsTick) {
|
||||
cc.skysparkle.matewave.network.NetworkMetrics.asText(context.resources)
|
||||
}
|
||||
Text(
|
||||
metricsText.trim(),
|
||||
color = ink.copy(alpha = 0.7f),
|
||||
style = MaterialTheme.typography.bodySmall
|
||||
)
|
||||
|
||||
GlassOutlinedButton(
|
||||
onClick = {
|
||||
val clipboard = context.getSystemService(android.content.Context.CLIPBOARD_SERVICE)
|
||||
as android.content.ClipboardManager
|
||||
|
||||
val report = buildString {
|
||||
appendLine(context.getString(R.string.diag_report_counters))
|
||||
append(cc.skysparkle.matewave.network.NetworkMetrics.asText(context.resources))
|
||||
appendLine()
|
||||
appendLine(context.getString(R.string.diag_report_events))
|
||||
append(NetworkLog.asText().ifBlank { context.getString(R.string.diag_log_empty) })
|
||||
}
|
||||
clipboard.setPrimaryClip(
|
||||
android.content.ClipData.newPlainText("network report", report)
|
||||
)
|
||||
},
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) {
|
||||
cc.skysparkle.matewave.ui.components.ButtonIcon(R.drawable.ic_copy)
|
||||
Text(stringResource(R.string.diag_copy_log), color = ink)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -287,6 +205,7 @@ private fun PermissionItem(
|
||||
Text(subtitle, color = ink.copy(alpha = 0.75f), style = MaterialTheme.typography.bodySmall)
|
||||
if (!granted) {
|
||||
GlassOutlinedButton(onClick = onGrant, modifier = Modifier.fillMaxWidth()) {
|
||||
cc.skysparkle.matewave.ui.components.ButtonIcon(R.drawable.ic_approve)
|
||||
Text(stringResource(R.string.perm_grant), color = ink)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,6 +40,7 @@ import cc.skysparkle.matewave.puzzles.PuzzleRepository
|
||||
import cc.skysparkle.matewave.puzzles.themeTitleRes
|
||||
import cc.skysparkle.matewave.stats.Stats
|
||||
import cc.skysparkle.matewave.ui.components.ButtonIcon
|
||||
import cc.skysparkle.matewave.ui.components.AppIcon
|
||||
import cc.skysparkle.matewave.ui.components.ChessBoardView
|
||||
import cc.skysparkle.matewave.ui.components.GlassButton
|
||||
import cc.skysparkle.matewave.ui.components.GlassOutlinedButton
|
||||
@@ -70,7 +71,8 @@ fun PuzzleSolveScreen(viewModel: GameViewModel, onBack: () -> Unit, onNextPuzzle
|
||||
}
|
||||
val redSquare = if (state.puzzleFailedAttempt && state.puzzleAutoMoving) state.lastMove?.to else null
|
||||
|
||||
GlassScaffold(
|
||||
// Landscape: the board on the left, the task and buttons on the right
|
||||
cc.skysparkle.matewave.ui.components.BoardScaffold(
|
||||
title = puzzle?.let { stringResource(R.string.puzzle_title_rating, it.rating) } ?: stringResource(R.string.puzzle_title_fallback),
|
||||
onBack = onBack,
|
||||
actions = {
|
||||
@@ -87,42 +89,51 @@ fun PuzzleSolveScreen(viewModel: GameViewModel, onBack: () -> Unit, onNextPuzzle
|
||||
.padding(horizontal = 6.dp, vertical = 2.dp)
|
||||
)
|
||||
}
|
||||
},
|
||||
board = { boardModifier ->
|
||||
// On tablets the board is capped and centred, so the task and buttons fit without scrolling.
|
||||
ChessBoardView(
|
||||
board = state.board,
|
||||
selectedSquare = state.selectedSquare,
|
||||
legalTargets = state.legalTargetsFromSelected,
|
||||
kingInCheckSquare = remember(state.board) { ChessEngine.checkedKingSquare(state.board) },
|
||||
flipped = state.myColor == PieceColor.BLACK,
|
||||
onSquareClick = viewModel::onSquareClicked,
|
||||
modifier = boardModifier.widthIn(max = 560.dp),
|
||||
lastMove = state.lastMove,
|
||||
hintSquare = state.puzzleHintFrom,
|
||||
interactionEnabled = state.puzzleStarted && !state.puzzleAutoMoving && !state.puzzleSolved && state.pendingPromotion == null,
|
||||
flashSquare = redSquare ?: greenFlash,
|
||||
flashColor = if (redSquare != null) WrongRed.copy(alpha = 0.55f) else ChessGreen.copy(alpha = 0.55f)
|
||||
)
|
||||
}
|
||||
) {
|
||||
// On tablets the board is capped and centred, so the task and buttons fit without scrolling.
|
||||
ChessBoardView(
|
||||
board = state.board,
|
||||
selectedSquare = state.selectedSquare,
|
||||
legalTargets = state.legalTargetsFromSelected,
|
||||
kingInCheckSquare = if (ChessEngine.isInCheck(state.board, state.board.sideToMove)) {
|
||||
state.board.kingSquare(state.board.sideToMove)
|
||||
} else null,
|
||||
flipped = state.myColor == PieceColor.BLACK,
|
||||
onSquareClick = viewModel::onSquareClicked,
|
||||
modifier = Modifier.align(Alignment.CenterHorizontally).widthIn(max = 560.dp),
|
||||
lastMove = state.lastMove,
|
||||
hintSquare = state.puzzleHintFrom,
|
||||
interactionEnabled = state.puzzleStarted && !state.puzzleAutoMoving && !state.puzzleSolved && state.pendingPromotion == null,
|
||||
flashSquare = redSquare ?: greenFlash,
|
||||
flashColor = if (redSquare != null) WrongRed.copy(alpha = 0.55f) else ChessGreen.copy(alpha = 0.55f)
|
||||
)
|
||||
|
||||
// The task, in the same format as the status in a game: a dot in the side's colour.
|
||||
val (text, color) = when {
|
||||
state.puzzleSolved -> "✓ " + stringResource(R.string.puzzle_solved) to ChessGreen
|
||||
state.puzzleFailedAttempt -> "✗ " + stringResource(R.string.puzzle_wrong_move) to WrongRed
|
||||
state.puzzleSolved -> stringResource(R.string.puzzle_solved) to ChessGreen
|
||||
state.puzzleFailedAttempt -> stringResource(R.string.puzzle_wrong_move) to WrongRed
|
||||
state.puzzleAutoMoving -> stringResource(R.string.opponent_turn) to ink.copy(alpha = 0.7f)
|
||||
state.myColor == PieceColor.WHITE -> stringResource(R.string.puzzle_find_best_white) to ink
|
||||
else -> stringResource(R.string.puzzle_find_best_black) to ink
|
||||
}
|
||||
// Solved and wrong show a mark instead of the dot
|
||||
val mark = when {
|
||||
state.puzzleSolved -> R.drawable.ic_approve
|
||||
state.puzzleFailedAttempt -> R.drawable.ic_cancel
|
||||
else -> null
|
||||
}
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Box(
|
||||
Modifier
|
||||
.size(10.dp)
|
||||
.clip(CircleShape)
|
||||
.background(if (state.myColor == PieceColor.WHITE) Color(0xFFF0F0F0) else Color(0xFF222222))
|
||||
.border(1.dp, ink.copy(alpha = 0.5f), CircleShape)
|
||||
)
|
||||
if (mark != null) {
|
||||
AppIcon(mark, size = 20.dp, tint = color)
|
||||
} else {
|
||||
Box(
|
||||
Modifier
|
||||
.size(10.dp)
|
||||
.clip(CircleShape)
|
||||
.background(if (state.myColor == PieceColor.WHITE) Color(0xFFF0F0F0) else Color(0xFF222222))
|
||||
.border(1.dp, ink.copy(alpha = 0.5f), CircleShape)
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Text(text, color = color, style = MaterialTheme.typography.titleMedium)
|
||||
}
|
||||
@@ -174,7 +185,8 @@ fun PuzzleSolveScreen(viewModel: GameViewModel, onBack: () -> Unit, onNextPuzzle
|
||||
}
|
||||
if (next != null) {
|
||||
GlassButton(onClick = { onNextPuzzle(next) }, modifier = Modifier.fillMaxWidth()) {
|
||||
Text(stringResource(R.string.puzzle_next), color = ink, style = MaterialTheme.typography.titleMedium)
|
||||
ButtonIcon(R.drawable.ic_next)
|
||||
Text(stringResource(R.string.puzzle_next), style = MaterialTheme.typography.titleMedium)
|
||||
}
|
||||
}
|
||||
Text(
|
||||
|
||||
@@ -57,7 +57,8 @@ fun SettingsScreen(
|
||||
onOpenPermissions: () -> Unit,
|
||||
onOpenAppearance: () -> Unit,
|
||||
onOpenLicenses: () -> Unit,
|
||||
onOpenShare: () -> Unit
|
||||
onOpenShare: () -> Unit,
|
||||
onOpenGuide: () -> Unit
|
||||
) {
|
||||
var musicOn by remember { mutableStateOf(SoundManager.musicEnabled) }
|
||||
var sfxOn by remember { mutableStateOf(SoundManager.sfxEnabled) }
|
||||
@@ -133,7 +134,8 @@ fun SettingsScreen(
|
||||
)
|
||||
ListDivider()
|
||||
ListRow(
|
||||
title = stringResource(R.string.perm_vibration_title),
|
||||
title = stringResource(R.string.settings_vibration),
|
||||
subtitle = stringResource(R.string.settings_vibration_subtitle),
|
||||
icon = R.drawable.ic_vibration,
|
||||
trailing = { SettingSwitch(vibrationOn) { vibrationOn = it; feedback.vibrationEnabled = it } }
|
||||
)
|
||||
@@ -144,7 +146,7 @@ fun SettingsScreen(
|
||||
ListRow(
|
||||
title = stringResource(R.string.appearance_title),
|
||||
subtitle = stringResource(R.string.appearance_subtitle),
|
||||
icon = R.drawable.ic_board_view,
|
||||
icon = R.drawable.ic_palette,
|
||||
chevron = true,
|
||||
onClick = onOpenAppearance
|
||||
)
|
||||
@@ -169,6 +171,14 @@ fun SettingsScreen(
|
||||
onClick = { cc.skysparkle.matewave.settings.AppLinks.open(context, cc.skysparkle.matewave.settings.AppLinks.PRIVACY_POLICY) }
|
||||
)
|
||||
ListDivider()
|
||||
ListRow(
|
||||
title = stringResource(R.string.guide_show),
|
||||
subtitle = stringResource(R.string.guide_show_subtitle),
|
||||
icon = R.drawable.ic_hint,
|
||||
chevron = true,
|
||||
onClick = onOpenGuide
|
||||
)
|
||||
ListDivider()
|
||||
ListRow(
|
||||
title = stringResource(R.string.about_section),
|
||||
icon = R.drawable.ic_info,
|
||||
@@ -177,6 +187,23 @@ fun SettingsScreen(
|
||||
onClick = { showAbout = true }
|
||||
)
|
||||
}
|
||||
|
||||
// Donation plaque with the app icon, last on the screen so it never gets in the way
|
||||
ListGroup {
|
||||
ListRow(
|
||||
title = stringResource(R.string.support_title),
|
||||
subtitle = stringResource(R.string.support_text),
|
||||
leading = {
|
||||
Image(
|
||||
painter = painterResource(R.drawable.ic_launcher_card),
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(36.dp).clip(RoundedCornerShape(10.dp))
|
||||
)
|
||||
},
|
||||
trailing = { cc.skysparkle.matewave.ui.components.AppIcon(R.drawable.ic_heart, size = 22.dp, tint = DonateRed) },
|
||||
onClick = { cc.skysparkle.matewave.settings.AppLinks.open(context, cc.skysparkle.matewave.settings.AppLinks.DONATE) }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (showAbout) {
|
||||
@@ -231,6 +258,12 @@ fun SettingsScreen(
|
||||
onOpenLicenses()
|
||||
}
|
||||
)
|
||||
AboutRow(
|
||||
iconRes = R.drawable.ic_heart,
|
||||
title = stringResource(R.string.support_button),
|
||||
subtitle = cc.skysparkle.matewave.settings.AppLinks.DONATE_LABEL,
|
||||
onClick = { cc.skysparkle.matewave.settings.AppLinks.open(context, cc.skysparkle.matewave.settings.AppLinks.DONATE) }
|
||||
)
|
||||
AboutRow(
|
||||
iconRes = R.drawable.ic_repo,
|
||||
title = stringResource(R.string.settings_repo_title),
|
||||
@@ -241,6 +274,8 @@ fun SettingsScreen(
|
||||
}
|
||||
}
|
||||
|
||||
private val DonateRed = Color(0xFFFF6B8A)
|
||||
|
||||
@Composable
|
||||
private fun AboutRow(iconRes: Int, title: String, subtitle: String, onClick: () -> Unit) {
|
||||
val rowShape = RoundedCornerShape(12.dp)
|
||||
@@ -260,7 +295,7 @@ private fun AboutRow(iconRes: Int, title: String, subtitle: String, onClick: ()
|
||||
Text(subtitle, color = ink.copy(alpha = 0.65f), style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
cc.skysparkle.matewave.ui.components.AppIcon(
|
||||
R.drawable.ic_arrow_forward, size = 16.dp, tint = ink.copy(alpha = 0.6f)
|
||||
R.drawable.ic_arrow_forward, size = 20.dp, tint = ink.copy(alpha = 0.7f)
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -272,7 +307,7 @@ private fun SettingSwitch(checked: Boolean, onCheckedChange: (Boolean) -> Unit)
|
||||
onCheckedChange = onCheckedChange,
|
||||
colors = SwitchDefaults.colors(
|
||||
checkedTrackColor = ChessGreen,
|
||||
checkedThumbColor = Color.White,
|
||||
checkedThumbColor = cc.skysparkle.matewave.ui.theme.OnAccent,
|
||||
uncheckedTrackColor = ink.copy(alpha = 0.15f),
|
||||
uncheckedThumbColor = Color.White.copy(alpha = 0.7f)
|
||||
)
|
||||
|
||||
@@ -0,0 +1,280 @@
|
||||
package cc.skysparkle.matewave.ui.screens
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.layout.padding
|
||||
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) }
|
||||
|
||||
val bottom = if (state.flipped) PieceColor.BLACK else PieceColor.WHITE
|
||||
val material = remember(view?.board) { view?.let { Material.balance(it.board) } }
|
||||
val checkSquare = remember(view?.board) { view?.let { ChessEngine.checkedKingSquare(it.board) } }
|
||||
|
||||
// Landscape: the board on the left, players, moves and buttons on the right
|
||||
cc.skysparkle.matewave.ui.components.BoardScaffold(
|
||||
title = stringResource(R.string.spectate_title),
|
||||
onBack = backToFriends,
|
||||
actions = { if (view != null) SpectatorBadge(state.spectators, state.max) },
|
||||
above = {
|
||||
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 && material != null) SpectatorPlayerRow(view, bottom.opposite(), state, material)
|
||||
},
|
||||
board = { boardModifier ->
|
||||
if (view != null) ChessBoardView(
|
||||
modifier = boardModifier,
|
||||
board = view.board,
|
||||
selectedSquare = null,
|
||||
legalTargets = emptyList(),
|
||||
kingInCheckSquare = checkSquare,
|
||||
flipped = state.flipped,
|
||||
onSquareClick = {},
|
||||
lastMove = view.lastMove,
|
||||
interactionEnabled = false,
|
||||
highlightLastMove = true
|
||||
)
|
||||
}
|
||||
) {
|
||||
if (view == null || material == null) return@BoardScaffold
|
||||
SpectatorPlayerRow(view, bottom, state, material)
|
||||
|
||||
val bookPlies = remember(view.moveSans) { OpeningBook.bookDepth(view.moveSans) }
|
||||
MovesBar(
|
||||
sans = view.moveSans,
|
||||
startBoard = view.startBoard,
|
||||
opening = null,
|
||||
bookPlies = bookPlies
|
||||
)
|
||||
|
||||
GlassOutlinedButton(onClick = viewModel::flip, modifier = Modifier.fillMaxWidth()) {
|
||||
ButtonIcon(R.drawable.ic_flip)
|
||||
Text(stringResource(R.string.spectate_flip), color = ink, maxLines = 1)
|
||||
}
|
||||
|
||||
if (state.phase == SpectatePhase.ENDED && resultHidden) {
|
||||
GlassOutlinedButton(onClick = { resultHidden = false }, modifier = Modifier.fillMaxWidth()) {
|
||||
ButtonIcon(R.drawable.ic_trophy)
|
||||
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.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
|
||||
}
|
||||
val cardShape = androidx.compose.foundation.shape.RoundedCornerShape(18.dp)
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(cardShape)
|
||||
.background(cc.skysparkle.matewave.ui.theme.Surface1)
|
||||
.border(1.dp, if (active) ChessGreen.copy(alpha = 0.7f) else cc.skysparkle.matewave.ui.theme.PanelBorder, cardShape)
|
||||
.padding(horizontal = 10.dp, vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.size(40.dp)
|
||||
.clip(CircleShape)
|
||||
.background(if (active) ChessGreen else androidx.compose.ui.graphics.Color.Transparent),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
AvatarCircle(base64 = avatar, size = 36.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
|
||||
@@ -6,6 +6,7 @@ import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import cc.skysparkle.matewave.ui.components.AppIcon
|
||||
import cc.skysparkle.matewave.ui.components.ButtonIcon
|
||||
import cc.skysparkle.matewave.ui.components.SectionCaption
|
||||
import cc.skysparkle.matewave.ui.components.TimeControlGrid
|
||||
import cc.skysparkle.matewave.ui.components.displayName
|
||||
@@ -35,6 +36,7 @@ import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import cc.skysparkle.matewave.ui.components.SetupSegmented
|
||||
import cc.skysparkle.matewave.ui.theme.ChessGreen
|
||||
import cc.skysparkle.matewave.ui.theme.PanelBorder
|
||||
@@ -75,9 +77,9 @@ fun VsAiSetupScreen(
|
||||
},
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) {
|
||||
ButtonIcon(R.drawable.ic_play)
|
||||
Text(
|
||||
stringResource(R.string.vsai_play_summary, difficultyLabel(difficulty), timeControl.displayName()),
|
||||
color = ink,
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
maxLines = 1
|
||||
)
|
||||
@@ -124,8 +126,8 @@ fun VsAiSetupScreen(
|
||||
|
||||
SectionCaption(stringResource(R.string.your_color))
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
ColorChip(R.drawable.ic_white_colour, stringResource(R.string.color_white), color == PieceColor.WHITE) { color = PieceColor.WHITE }
|
||||
ColorChip(R.drawable.ic_black_colour, stringResource(R.string.color_black), color == PieceColor.BLACK) { color = PieceColor.BLACK }
|
||||
ColorChip(R.drawable.piece_white_king, stringResource(R.string.color_white), color == PieceColor.WHITE) { color = PieceColor.WHITE }
|
||||
ColorChip(R.drawable.piece_black_king, stringResource(R.string.color_black), color == PieceColor.BLACK) { color = PieceColor.BLACK }
|
||||
ColorChip(R.drawable.ic_random_colour, stringResource(R.string.color_random), color == null) { color = null }
|
||||
}
|
||||
|
||||
@@ -154,11 +156,20 @@ private fun ColorChip(iconRes: Int, text: String, selected: Boolean, onClick: ()
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp)
|
||||
) {
|
||||
Image(
|
||||
painter = painterResource(iconRes),
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(16.dp)
|
||||
)
|
||||
// The king from the board's own piece set; random is half white, half black
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.size(26.dp)
|
||||
.clip(CircleShape)
|
||||
.background(Color(0xFF9AA0A8)),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
Image(
|
||||
painter = painterResource(iconRes),
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(20.dp)
|
||||
)
|
||||
}
|
||||
Text(text, color = ink, style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
package cc.skysparkle.matewave.ui.theme
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import androidx.compose.material3.dynamicDarkColorScheme
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import cc.skysparkle.matewave.R
|
||||
|
||||
/** The colours every screen is drawn with. The app stays dark in every style. */
|
||||
data class AppPalette(
|
||||
/** Highlights, selected states, progress. */
|
||||
val accent: Color,
|
||||
/** The one main action on a screen. */
|
||||
val action: Color,
|
||||
/** Text and icons on top of [accent] or [action]. */
|
||||
val onAccent: Color,
|
||||
val background: Color,
|
||||
val surface1: Color,
|
||||
val surface2: Color,
|
||||
/** The forest backdrop keeps its green cast only with the original colours. */
|
||||
val greenBackdrop: Boolean = false
|
||||
)
|
||||
|
||||
enum class AppStyle(val titleRes: Int) {
|
||||
MATEWAVE(R.string.app_style_matewave),
|
||||
LAVENDER(R.string.app_style_lavender),
|
||||
PEACH(R.string.app_style_peach),
|
||||
MINT(R.string.app_style_mint),
|
||||
SKY(R.string.app_style_sky),
|
||||
DEVICE(R.string.app_style_device);
|
||||
|
||||
companion object {
|
||||
/** Wallpaper colours exist from Android 12. */
|
||||
val deviceSupported: Boolean get() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S
|
||||
|
||||
val available: List<AppStyle> get() = entries.filter { it != DEVICE || deviceSupported }
|
||||
}
|
||||
}
|
||||
|
||||
private val MatewavePalette = AppPalette(
|
||||
accent = Color(0xFF35E07E),
|
||||
action = Color(0xFFE3F84B),
|
||||
onAccent = Color(0xFF0B1610),
|
||||
background = Color(0xFF0C0F0E),
|
||||
surface1 = Color(0xFF161B19),
|
||||
surface2 = Color(0xFF1F2623),
|
||||
greenBackdrop = true
|
||||
)
|
||||
|
||||
private val LavenderPalette = AppPalette(
|
||||
accent = Color(0xFFC8B6FF),
|
||||
action = Color(0xFFFFC6E5),
|
||||
onAccent = Color(0xFF1E1630),
|
||||
background = Color(0xFF0F0E14),
|
||||
surface1 = Color(0xFF1A1822),
|
||||
surface2 = Color(0xFF25222F)
|
||||
)
|
||||
|
||||
private val PeachPalette = AppPalette(
|
||||
accent = Color(0xFFFFB59E),
|
||||
action = Color(0xFFFFE08A),
|
||||
onAccent = Color(0xFF2A1710),
|
||||
background = Color(0xFF12100E),
|
||||
surface1 = Color(0xFF1D1A17),
|
||||
surface2 = Color(0xFF28231F)
|
||||
)
|
||||
|
||||
private val MintPalette = AppPalette(
|
||||
accent = Color(0xFF9EE7C8),
|
||||
action = Color(0xFFD8F5A8),
|
||||
onAccent = Color(0xFF0F231B),
|
||||
background = Color(0xFF0D110F),
|
||||
surface1 = Color(0xFF171C1A),
|
||||
surface2 = Color(0xFF202724)
|
||||
)
|
||||
|
||||
private val SkyPalette = AppPalette(
|
||||
accent = Color(0xFFA5CBFF),
|
||||
action = Color(0xFFB8F1EE),
|
||||
onAccent = Color(0xFF0F1A2A),
|
||||
background = Color(0xFF0D1014),
|
||||
surface1 = Color(0xFF171B21),
|
||||
surface2 = Color(0xFF20252D)
|
||||
)
|
||||
|
||||
/** The selected style, kept in compose state so every screen recolours at once. */
|
||||
object AppThemeState {
|
||||
private const val PREFS = "app_theme"
|
||||
private const val KEY_STYLE = "style"
|
||||
|
||||
var style by mutableStateOf(AppStyle.MATEWAVE)
|
||||
private set
|
||||
|
||||
var palette by mutableStateOf(MatewavePalette)
|
||||
private set
|
||||
|
||||
/** Reads the saved style; call once before the first frame. */
|
||||
fun load(context: Context) {
|
||||
val saved = context.applicationContext
|
||||
.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||
.getString(KEY_STYLE, null)
|
||||
val style = AppStyle.entries.firstOrNull { it.name == saved } ?: AppStyle.MATEWAVE
|
||||
applyStyle(context, style)
|
||||
}
|
||||
|
||||
fun select(context: Context, style: AppStyle) {
|
||||
context.applicationContext
|
||||
.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||
.edit().putString(KEY_STYLE, style.name).apply()
|
||||
applyStyle(context, style)
|
||||
}
|
||||
|
||||
private fun applyStyle(context: Context, requested: AppStyle) {
|
||||
val style = if (requested == AppStyle.DEVICE && !AppStyle.deviceSupported) AppStyle.MATEWAVE else requested
|
||||
this.style = style
|
||||
palette = paletteFor(context, style)
|
||||
}
|
||||
|
||||
/** Preview colours for the style picker. */
|
||||
fun paletteFor(context: Context, style: AppStyle): AppPalette = when (style) {
|
||||
AppStyle.MATEWAVE -> MatewavePalette
|
||||
AppStyle.LAVENDER -> LavenderPalette
|
||||
AppStyle.PEACH -> PeachPalette
|
||||
AppStyle.MINT -> MintPalette
|
||||
AppStyle.SKY -> SkyPalette
|
||||
AppStyle.DEVICE -> devicePalette(context)
|
||||
}
|
||||
|
||||
private fun devicePalette(context: Context): AppPalette {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) return MatewavePalette
|
||||
val scheme = dynamicDarkColorScheme(context)
|
||||
return AppPalette(
|
||||
accent = scheme.primary,
|
||||
action = scheme.tertiary,
|
||||
onAccent = scheme.onPrimary,
|
||||
background = scheme.background,
|
||||
surface1 = scheme.surfaceContainer,
|
||||
surface2 = scheme.surfaceContainerHigh
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -4,36 +4,24 @@ import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Brush
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.Shape
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
val PanelFill = Color(0xFF14171C).copy(alpha = 0.86f)
|
||||
val PanelBorder = Color.White.copy(alpha = 0.10f)
|
||||
val PanelFill: Color get() = Surface1
|
||||
val PanelBorder = Color.White.copy(alpha = 0.06f)
|
||||
|
||||
val UiCornerRadius = 8.dp
|
||||
val UiCornerRadius = 22.dp
|
||||
val GlassShape: Shape = RoundedCornerShape(UiCornerRadius)
|
||||
|
||||
val TabletMaxContentWidth = 600.dp
|
||||
/** Landscape board screens: board and side panel together. */
|
||||
val LandscapeMaxContentWidth = 1200.dp
|
||||
|
||||
fun Modifier.glass(shape: Shape = GlassShape): Modifier = this
|
||||
.clip(shape)
|
||||
fun Modifier.glass(): Modifier = this
|
||||
.clip(GlassShape)
|
||||
.background(PanelFill)
|
||||
|
||||
val GlassBorder = PanelBorder
|
||||
val DialogScrimColor = Color.Black.copy(alpha = 0.70f)
|
||||
|
||||
val PhotoScrim = Brush.verticalGradient(
|
||||
0.00f to Color.Black.copy(alpha = 0.84f),
|
||||
0.10f to Color.Black.copy(alpha = 0.72f),
|
||||
0.22f to Color.Black.copy(alpha = 0.58f),
|
||||
0.38f to Color.Black.copy(alpha = 0.48f),
|
||||
0.55f to Color.Black.copy(alpha = 0.47f),
|
||||
0.72f to Color.Black.copy(alpha = 0.55f),
|
||||
0.88f to Color.Black.copy(alpha = 0.68f),
|
||||
1.00f to Color.Black.copy(alpha = 0.80f)
|
||||
)
|
||||
|
||||
val DialogScrimColor = Color.Black.copy(alpha = 0.62f)
|
||||
|
||||
val FloatingBarFill = Color.Black.copy(alpha = 0.25f)
|
||||
val FloatingBarFill: Color get() = Surface2
|
||||
|
||||
@@ -1,13 +1,6 @@
|
||||
package cc.skysparkle.matewave.ui.theme
|
||||
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.ReadOnlyComposable
|
||||
import androidx.compose.runtime.compositionLocalOf
|
||||
import androidx.compose.ui.graphics.Color
|
||||
|
||||
val LocalInk = compositionLocalOf { Color.White }
|
||||
|
||||
val ink: Color
|
||||
@Composable
|
||||
@ReadOnlyComposable
|
||||
get() = LocalInk.current
|
||||
/** Colour of text and icons on the app's dark background. */
|
||||
val ink = Color.White
|
||||
|
||||
@@ -1,31 +1,104 @@
|
||||
package cc.skysparkle.matewave.ui.theme
|
||||
|
||||
import androidx.compose.material3.LocalContentColor
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextFieldDefaults
|
||||
import androidx.compose.material3.Typography
|
||||
import androidx.compose.material3.darkColorScheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.font.Font
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import cc.skysparkle.matewave.R
|
||||
import androidx.compose.ui.unit.sp
|
||||
|
||||
// The interface colours follow the selected style (see AppPalette); reading them in
|
||||
// composition subscribes the screen, so a new style recolours everything at once.
|
||||
|
||||
/** Accent: highlights, selected states and progress. Neon green in the original style. */
|
||||
val ChessGreen: Color get() = AppThemeState.palette.accent
|
||||
|
||||
/** The one colour for the main action on a screen. Lime in the original style. */
|
||||
val Lime: Color get() = AppThemeState.palette.action
|
||||
|
||||
/** Text and icons on top of [ChessGreen] or [Lime]. */
|
||||
val OnAccent: Color get() = AppThemeState.palette.onAccent
|
||||
|
||||
val AppBackground: Color get() = AppThemeState.palette.background
|
||||
val Surface1: Color get() = AppThemeState.palette.surface1
|
||||
val Surface2: Color get() = AppThemeState.palette.surface2
|
||||
|
||||
val ChessGreen = Color(0xFF3E7C4A)
|
||||
val ChessGreenDark = Color(0xFF1B4D2E)
|
||||
val HighlightMove = Color(0x8858A6FF)
|
||||
val HighlightCheck = Color(0x88E53935)
|
||||
val HighlightLastMove = Color(0x664FC3F7)
|
||||
val HighlightHint = Color(0x88FFC107)
|
||||
|
||||
private val DarkScheme = darkColorScheme(
|
||||
primary = ChessGreen,
|
||||
secondary = ChessGreenDark,
|
||||
background = Color(0xFF121212),
|
||||
surface = Color(0xFF1E1E1E)
|
||||
/** Wide display face for the big headings: the brand voice of the app. */
|
||||
val DisplayFont = FontFamily(
|
||||
Font(R.font.unbounded_semibold, FontWeight.SemiBold),
|
||||
Font(R.font.unbounded_extrabold, FontWeight.ExtraBold)
|
||||
)
|
||||
|
||||
/** Text face for everything else. Characters it lacks (CJK, symbols) fall back to the system font. */
|
||||
val TextFont = FontFamily(
|
||||
Font(R.font.manrope_regular, FontWeight.Normal),
|
||||
Font(R.font.manrope_medium, FontWeight.Medium),
|
||||
Font(R.font.manrope_semibold, FontWeight.SemiBold),
|
||||
Font(R.font.manrope_bold, FontWeight.Bold)
|
||||
)
|
||||
|
||||
private val base = Typography()
|
||||
|
||||
private fun TextStyle.display(weight: FontWeight, tracking: Double) =
|
||||
copy(fontFamily = DisplayFont, fontWeight = weight, letterSpacing = tracking.sp)
|
||||
|
||||
private fun TextStyle.text(weight: FontWeight) = copy(fontFamily = TextFont, fontWeight = weight)
|
||||
|
||||
private val AppTypography = Typography(
|
||||
displayLarge = base.displayLarge.display(FontWeight.ExtraBold, -1.5),
|
||||
displayMedium = base.displayMedium.display(FontWeight.ExtraBold, -1.2),
|
||||
displaySmall = base.displaySmall.display(FontWeight.ExtraBold, -0.8),
|
||||
headlineLarge = base.headlineLarge.display(FontWeight.ExtraBold, -0.8),
|
||||
headlineMedium = base.headlineMedium.display(FontWeight.ExtraBold, -0.6),
|
||||
headlineSmall = base.headlineSmall.copy(fontSize = 21.sp, lineHeight = 28.sp).display(FontWeight.SemiBold, -0.4),
|
||||
titleLarge = base.titleLarge.text(FontWeight.Bold),
|
||||
titleMedium = base.titleMedium.text(FontWeight.Bold),
|
||||
titleSmall = base.titleSmall.text(FontWeight.Bold),
|
||||
bodyLarge = base.bodyLarge.text(FontWeight.Medium),
|
||||
bodyMedium = base.bodyMedium.text(FontWeight.Medium),
|
||||
bodySmall = base.bodySmall.text(FontWeight.Medium),
|
||||
labelLarge = base.labelLarge.text(FontWeight.Bold),
|
||||
labelMedium = base.labelMedium.text(FontWeight.Bold).copy(letterSpacing = 1.sp),
|
||||
labelSmall = base.labelSmall.text(FontWeight.SemiBold)
|
||||
)
|
||||
|
||||
/** Large hero heading on the home screen. */
|
||||
val HeroTextStyle = TextStyle(
|
||||
fontFamily = DisplayFont,
|
||||
fontSize = 46.sp,
|
||||
lineHeight = 50.sp,
|
||||
fontWeight = FontWeight.ExtraBold,
|
||||
letterSpacing = (-1.5).sp
|
||||
)
|
||||
|
||||
/** The app has a single dark theme; system bars are set up in MainActivity. */
|
||||
@Composable
|
||||
fun MatewaveTheme(content: @Composable () -> Unit) {
|
||||
MaterialTheme(colorScheme = DarkScheme) {
|
||||
CompositionLocalProvider(LocalInk provides Color.White, content = content)
|
||||
val scheme = darkColorScheme(
|
||||
primary = ChessGreen,
|
||||
onPrimary = OnAccent,
|
||||
secondary = Lime,
|
||||
onSecondary = OnAccent,
|
||||
background = AppBackground,
|
||||
surface = Surface1,
|
||||
surfaceVariant = Surface2
|
||||
)
|
||||
MaterialTheme(colorScheme = scheme, typography = AppTypography) {
|
||||
// Text and icons without their own colour are light, so nothing turns black on the dark background
|
||||
CompositionLocalProvider(LocalContentColor provides Color.White, content = content)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,9 +106,9 @@ fun MatewaveTheme(content: @Composable () -> Unit) {
|
||||
fun whiteOutlinedTextFieldColors() = OutlinedTextFieldDefaults.colors(
|
||||
focusedTextColor = ink,
|
||||
unfocusedTextColor = ink,
|
||||
focusedBorderColor = ink.copy(alpha = 0.6f),
|
||||
unfocusedBorderColor = ink.copy(alpha = 0.3f),
|
||||
focusedLabelColor = ink.copy(alpha = 0.8f),
|
||||
focusedBorderColor = ChessGreen,
|
||||
unfocusedBorderColor = ink.copy(alpha = 0.2f),
|
||||
focusedLabelColor = ChessGreen,
|
||||
unfocusedLabelColor = ink.copy(alpha = 0.6f),
|
||||
cursorColor = ink
|
||||
cursorColor = ChessGreen
|
||||
)
|
||||
|
||||
@@ -26,6 +26,7 @@ import cc.skysparkle.matewave.network.ConnectionTransport
|
||||
import cc.skysparkle.matewave.network.GameMessage
|
||||
import cc.skysparkle.matewave.network.NetworkLog
|
||||
import cc.skysparkle.matewave.network.NetworkMetrics
|
||||
import cc.skysparkle.matewave.network.PeerLimits
|
||||
import cc.skysparkle.matewave.network.TransportType
|
||||
import cc.skysparkle.matewave.puzzles.Puzzle
|
||||
import cc.skysparkle.matewave.security.DeviceKeys
|
||||
@@ -33,12 +34,23 @@ 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 cc.skysparkle.matewave.ui.components.isAcceptableIncomingImage
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.isActive
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
@@ -60,7 +72,6 @@ data class GameUiState(
|
||||
|
||||
val gameStarted: Boolean = false,
|
||||
val aiDifficulty: AiDifficulty = AiDifficulty.MEDIUM,
|
||||
val aiThinking: Boolean = false,
|
||||
val puzzle: Puzzle? = null,
|
||||
val puzzleMoveIndex: Int = 0,
|
||||
val puzzleSolved: Boolean = false,
|
||||
@@ -69,14 +80,12 @@ data class GameUiState(
|
||||
val puzzleAutoMoving: Boolean = false,
|
||||
val puzzleHintFrom: Int? = null,
|
||||
val puzzleSolutionRevealed: Boolean = false,
|
||||
val clockState: ClockState? = null,
|
||||
val timedOutSide: PieceColor? = null,
|
||||
val resignedSide: PieceColor? = null,
|
||||
val connectionState: ConnectionState = ConnectionState.DISCONNECTED,
|
||||
|
||||
val opponentUntrusted: Boolean = false,
|
||||
val opponentUnverified: Boolean = false,
|
||||
val opponentOutdated: Boolean = false,
|
||||
val handshake: HandshakeState = HandshakeState.DISCONNECTED,
|
||||
val newPeerFingerprint: String? = null,
|
||||
|
||||
@@ -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)
|
||||
@@ -103,8 +115,7 @@ data class PendingPromotion(val from: Int, val to: Int)
|
||||
data class ChatEntry(
|
||||
val text: String?,
|
||||
val imageBase64: String?,
|
||||
val fromMe: Boolean,
|
||||
val timestampMs: Long
|
||||
val fromMe: Boolean
|
||||
)
|
||||
|
||||
enum class OpponentNotice { DRAW_DECLINED, REMATCH_DECLINED }
|
||||
@@ -136,6 +147,13 @@ class GameViewModel : ViewModel() {
|
||||
private val _uiState = MutableStateFlow(GameUiState())
|
||||
val uiState: StateFlow<GameUiState> = _uiState
|
||||
|
||||
/**
|
||||
* The game's clock, kept out of [uiState] so its ticks redraw only the clocks. Cleared with
|
||||
* every new game state; a new clock shows itself once set up.
|
||||
*/
|
||||
private val _clockState = MutableStateFlow<ClockState?>(null)
|
||||
val clockState: StateFlow<ClockState?> = _clockState
|
||||
|
||||
private val _resumable = MutableStateFlow<ResumeInfo?>(null)
|
||||
|
||||
/** The game against the AI that is saved and can be continued, or null. */
|
||||
@@ -169,11 +187,32 @@ class GameViewModel : ViewModel() {
|
||||
private var sessionGeneration = 0
|
||||
private var networkGameId: String = ""
|
||||
private var pendingOpponentImages: Pair<String?, String?>? = null
|
||||
|
||||
// The player picked in the nearby list; whoever answers must be that player.
|
||||
private var expectedOpponentUserId: String? = null
|
||||
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) }
|
||||
if (GameSaveStore.isLoaded()) {
|
||||
GameSaveStore.load()?.let { saved -> restoreSaved(saved) }
|
||||
} else {
|
||||
// Not read yet: read it in the background instead of making the first screen wait.
|
||||
val untouched = _uiState.value
|
||||
viewModelScope.launch {
|
||||
val saved = withContext(Dispatchers.IO) { GameSaveStore.load() } ?: return@launch
|
||||
if (_uiState.value === untouched) restoreSaved(saved)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// region History
|
||||
@@ -203,7 +242,7 @@ class GameViewModel : ViewModel() {
|
||||
var replayed = saved.movesUci.isNotBlank()
|
||||
if (replayed) {
|
||||
for (uci in saved.movesUci.trim().split(' ')) {
|
||||
val move = resolveUciAgainstLegalMoves(board, uci)
|
||||
val move = Notation.fromUci(board, uci)
|
||||
if (move == null) { replayed = false; break }
|
||||
sans.add(Notation.toSan(board, move))
|
||||
board = ChessEngine.applyMove(board, move)
|
||||
@@ -226,6 +265,7 @@ class GameViewModel : ViewModel() {
|
||||
fenHistory.clear(); fenHistory.addAll(keys)
|
||||
moveLog.clear(); moveLog.addAll(ucis)
|
||||
lastVsAiSettings = Triple(difficulty, myColor, timeControl)
|
||||
_clockState.value = null
|
||||
_uiState.value = GameUiState(
|
||||
board = board,
|
||||
startBoard = start,
|
||||
@@ -242,14 +282,14 @@ class GameViewModel : ViewModel() {
|
||||
restoreWhiteMillis = saved.whiteMillis,
|
||||
restoreBlackMillis = saved.blackMillis
|
||||
)
|
||||
clock?.pause()
|
||||
clock?.stop()
|
||||
_resumable.value = resumeInfoOf(_uiState.value)
|
||||
return true
|
||||
}
|
||||
|
||||
private fun resumeInfoOf(state: GameUiState): ResumeInfo {
|
||||
val unlimited = lastVsAiSettings?.third?.initialSeconds == Int.MAX_VALUE
|
||||
val millis = if (unlimited) null else (clock?.state?.value ?: state.clockState)?.let {
|
||||
val millis = if (unlimited) null else (clock?.state?.value ?: _clockState.value)?.let {
|
||||
if (state.myColor == PieceColor.WHITE) it.whiteMillis else it.blackMillis
|
||||
}
|
||||
return ResumeInfo(state.board.fullmoveNumber, state.board.sideToMove == state.myColor, millis)
|
||||
@@ -257,7 +297,8 @@ class GameViewModel : ViewModel() {
|
||||
|
||||
private fun persistIfResumable() {
|
||||
val state = _uiState.value
|
||||
if (state.mode != GameMode.VS_AI || state.status != GameStatus.ONGOING) return
|
||||
// The untouched initial state is no game: saving it would offer a game nobody started.
|
||||
if (state.mode != GameMode.VS_AI || state.status != GameStatus.ONGOING || !state.gameStarted) return
|
||||
val clockState = clock?.state?.value
|
||||
GameSaveStore.save(
|
||||
SavedGame(
|
||||
@@ -412,12 +453,6 @@ class GameViewModel : ViewModel() {
|
||||
ProfileStore.applyEloDelta(ProfileStore.aiNominalElo(difficulty), result)
|
||||
}
|
||||
|
||||
private fun resolveUciAgainstLegalMoves(board: Board, uci: String): Move? {
|
||||
val candidate = runCatching { Move.fromUci(uci) }.getOrNull() ?: 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()
|
||||
}
|
||||
|
||||
// endregion
|
||||
|
||||
// region Against the AI
|
||||
@@ -434,6 +469,7 @@ class GameViewModel : ViewModel() {
|
||||
val start = Board.startPosition()
|
||||
resetHistory(start)
|
||||
lastVsAiSettings = Triple(difficulty, myColor, timeControl)
|
||||
_clockState.value = null
|
||||
_uiState.value = GameUiState(
|
||||
board = start,
|
||||
startBoard = start,
|
||||
@@ -471,7 +507,6 @@ class GameViewModel : ViewModel() {
|
||||
private fun cancelAi() {
|
||||
aiJob?.cancel()
|
||||
aiJob = null
|
||||
if (_uiState.value.aiThinking) _uiState.value = _uiState.value.copy(aiThinking = false)
|
||||
}
|
||||
|
||||
private fun triggerAiMoveIfNeeded() {
|
||||
@@ -479,7 +514,6 @@ class GameViewModel : ViewModel() {
|
||||
if (state.mode != GameMode.VS_AI || state.status != GameStatus.ONGOING) return
|
||||
if (state.board.sideToMove == state.myColor) return
|
||||
if (aiJob?.isActive == true) return
|
||||
_uiState.value = state.copy(aiThinking = true)
|
||||
val boardAtStart = state.board
|
||||
val history = fenHistory.toSet()
|
||||
val aiColor = boardAtStart.sideToMove
|
||||
@@ -489,14 +523,14 @@ class GameViewModel : ViewModel() {
|
||||
val incrementMillis = (lastVsAiSettings?.third?.incrementSeconds ?: 0) * 1000L
|
||||
aiJob = viewModelScope.launch {
|
||||
val move = withContext(Dispatchers.Default) {
|
||||
ChessAI.bestMove(boardAtStart, state.aiDifficulty, history, clockMillis, incrementMillis)
|
||||
// Stops thinking as soon as the game is left or the move is no longer wanted.
|
||||
ChessAI.bestMove(
|
||||
boardAtStart, state.aiDifficulty, history, clockMillis, incrementMillis,
|
||||
isCancelled = { !isActive }
|
||||
)
|
||||
}
|
||||
val now = _uiState.value
|
||||
if (now.board !== boardAtStart || now.mode != GameMode.VS_AI || now.status != GameStatus.ONGOING) {
|
||||
if (now.aiThinking) _uiState.value = now.copy(aiThinking = false)
|
||||
return@launch
|
||||
}
|
||||
_uiState.value = now.copy(aiThinking = false)
|
||||
if (now.board !== boardAtStart || now.mode != GameMode.VS_AI || now.status != GameStatus.ONGOING) return@launch
|
||||
if (move != null) makeMove(move)
|
||||
}
|
||||
}
|
||||
@@ -510,6 +544,7 @@ class GameViewModel : ViewModel() {
|
||||
disposeClock()
|
||||
val board = runCatching { Board.fromFen(puzzle.fen) }.getOrNull() ?: return
|
||||
resetHistory(board)
|
||||
_clockState.value = null
|
||||
_uiState.value = GameUiState(
|
||||
board = board,
|
||||
startBoard = board,
|
||||
@@ -565,7 +600,7 @@ class GameViewModel : ViewModel() {
|
||||
return
|
||||
}
|
||||
|
||||
val replyMove = resolveUciAgainstLegalMoves(_uiState.value.board, puzzle.solutionUci[nextIndex])
|
||||
val replyMove = Notation.fromUci(_uiState.value.board, puzzle.solutionUci[nextIndex])
|
||||
_uiState.value = _uiState.value.copy(
|
||||
puzzleMoveIndex = nextIndex + 1,
|
||||
puzzleFailedAttempt = false,
|
||||
@@ -680,7 +715,8 @@ class GameViewModel : ViewModel() {
|
||||
myColor: PieceColor,
|
||||
timeControl: TimeControl,
|
||||
isHost: Boolean,
|
||||
targetId: String? = null
|
||||
targetId: String? = null,
|
||||
expectedUserId: String? = null
|
||||
) {
|
||||
pendingLeave?.let { (job, oldTransport) ->
|
||||
job.cancel()
|
||||
@@ -689,6 +725,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()
|
||||
@@ -698,6 +735,7 @@ class GameViewModel : ViewModel() {
|
||||
this.transport = transport
|
||||
lastNetworkTimeControl = timeControl
|
||||
isNetworkHost = isHost
|
||||
expectedOpponentUserId = expectedUserId?.takeIf { it.isNotBlank() }
|
||||
|
||||
ephemeralKeys = DeviceKeys.generateEphemeral()
|
||||
|
||||
@@ -707,8 +745,8 @@ class GameViewModel : ViewModel() {
|
||||
opponentFlagJob = null
|
||||
networkGameId = if (isHost) java.util.UUID.randomUUID().toString() else ""
|
||||
currentPly = 0
|
||||
lastOpponentRemaining = Long.MAX_VALUE
|
||||
|
||||
_clockState.value = null
|
||||
_uiState.value = GameUiState(
|
||||
board = start,
|
||||
startBoard = start,
|
||||
@@ -729,6 +767,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()
|
||||
@@ -813,6 +853,13 @@ class GameViewModel : ViewModel() {
|
||||
)
|
||||
}
|
||||
|
||||
/** The image if it may be shown and stored, otherwise null (and a log line). */
|
||||
private fun acceptedIncomingImage(base64: String): String? {
|
||||
if (base64.length <= MAX_CHAT_IMAGE_CHARS && isAcceptableIncomingImage(base64)) return base64
|
||||
NetworkLog.log("GAME", "Unreadable or oversized profile image rejected")
|
||||
return null
|
||||
}
|
||||
|
||||
private fun belongsToCurrentGame(gameId: String): Boolean =
|
||||
gameId.isEmpty() || networkGameId.isEmpty() || gameId == networkGameId
|
||||
|
||||
@@ -866,9 +913,14 @@ class GameViewModel : ViewModel() {
|
||||
NetworkLog.log("GAME", "Oversized chat message rejected")
|
||||
return
|
||||
}
|
||||
if (msg.imageBase64 != null && !isAcceptableIncomingImage(msg.imageBase64)) {
|
||||
NetworkLog.log("GAME", "Unreadable or oversized chat image rejected")
|
||||
return
|
||||
}
|
||||
val state = _uiState.value
|
||||
_uiState.value = state.copy(
|
||||
chatMessages = state.chatMessages + ChatEntry(msg.text, msg.imageBase64, fromMe = false, System.currentTimeMillis()),
|
||||
chatMessages = (state.chatMessages + ChatEntry(msg.text, msg.imageBase64, fromMe = false))
|
||||
.takeLast(MAX_CHAT_ENTRIES),
|
||||
unreadChatCount = state.unreadChatCount + 1
|
||||
)
|
||||
}
|
||||
@@ -941,8 +993,8 @@ class GameViewModel : ViewModel() {
|
||||
}
|
||||
is GameMessage.ProfileImagesMsg -> {
|
||||
if (!belongsToCurrentGame(msg.gameId)) return
|
||||
val avatar = msg.avatarBase64?.takeIf { it.length <= MAX_CHAT_IMAGE_CHARS }
|
||||
val background = msg.backgroundBase64?.takeIf { it.length <= MAX_CHAT_IMAGE_CHARS }
|
||||
val avatar = msg.avatarBase64?.let(::acceptedIncomingImage)
|
||||
val background = msg.backgroundBase64?.let(::acceptedIncomingImage)
|
||||
if (avatar == null && background == null) return
|
||||
val current = _uiState.value.opponentProfile
|
||||
if (current == null) {
|
||||
@@ -965,6 +1017,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
|
||||
@@ -1007,22 +1063,22 @@ class GameViewModel : ViewModel() {
|
||||
val opponentColor = state.myColor.opposite()
|
||||
if (state.board.sideToMove != opponentColor) return
|
||||
|
||||
val move = resolveUciAgainstLegalMoves(state.board, msg.uci) ?: return
|
||||
val move = Notation.fromUci(state.board, msg.uci) ?: return
|
||||
currentPly = if (msg.ply > 0) msg.ply else currentPly + 1
|
||||
|
||||
val limit = lastNetworkTimeControl?.let { it.initialSeconds * 1000L + 60_000L }
|
||||
val increment = lastNetworkTimeControl?.let { it.incrementSeconds * 1000L } ?: 0L
|
||||
val allowedMax = if (lastOpponentRemaining == Long.MAX_VALUE) {
|
||||
limit ?: Long.MAX_VALUE
|
||||
} else {
|
||||
lastOpponentRemaining + increment + CLOCK_TOLERANCE_MS
|
||||
}
|
||||
// Our own clock has been running the opponent's time while they thought, so their claim
|
||||
// may not exceed it by more than the increment and network slack.
|
||||
val allowedMax = clock?.remainingMillis(opponentColor)
|
||||
?.let { PeerLimits.maxOpponentClockAfterMove(it, increment, CLOCK_TOLERANCE_MS) }
|
||||
?: limit ?: Long.MAX_VALUE
|
||||
if (msg.remainingMillisSelf >= 0 &&
|
||||
(limit == null || msg.remainingMillisSelf <= limit) &&
|
||||
msg.remainingMillisSelf <= allowedMax
|
||||
) {
|
||||
lastOpponentRemaining = msg.remainingMillisSelf
|
||||
clock?.applyRemoteTime(opponentColor, msg.remainingMillisSelf)
|
||||
// The reported time already includes the increment; makeMove below adds it again.
|
||||
clock?.applyRemoteTime(opponentColor, (msg.remainingMillisSelf - increment).coerceAtLeast(0))
|
||||
} else if (msg.remainingMillisSelf > 0) {
|
||||
NetworkLog.log("GAME", "Invalid clock value from opponent rejected: ${msg.remainingMillisSelf}")
|
||||
}
|
||||
@@ -1038,11 +1094,10 @@ class GameViewModel : ViewModel() {
|
||||
NetworkLog.log("GAME", "Repeated profile in current session ignored")
|
||||
return
|
||||
}
|
||||
if (msg.protocolVersion < GameMessage.PROTOCOL_VERSION) {
|
||||
NetworkLog.log(
|
||||
"GAME", "Opponent protocol version ${msg.protocolVersion} < ${GameMessage.PROTOCOL_VERSION}, incompatible"
|
||||
)
|
||||
_uiState.value = _uiState.value.copy(opponentOutdated = true)
|
||||
if (!PeerLimits.isPlausibleProfile(msg)) {
|
||||
// Nothing of it is stored: no key, no friend entry. The connection is closed.
|
||||
NetworkLog.log("GAME", "Profile with out-of-range fields rejected, disconnecting")
|
||||
transport?.disconnect()
|
||||
return
|
||||
}
|
||||
val peers = knownPeers
|
||||
@@ -1093,7 +1148,11 @@ class GameViewModel : ViewModel() {
|
||||
}
|
||||
markReadyIfPossible()
|
||||
|
||||
_uiState.value = _uiState.value.copy(opponentUnverified = trust == TrustResult.UNSIGNED)
|
||||
val unexpected = expectedOpponentUserId?.let { it != msg.userId } == true
|
||||
if (unexpected) {
|
||||
NetworkLog.log("GAME", "Opponent is not the player picked in the nearby list")
|
||||
}
|
||||
_uiState.value = _uiState.value.copy(opponentUnverified = trust == TrustResult.UNSIGNED || unexpected)
|
||||
|
||||
val pending = pendingOpponentImages
|
||||
pendingOpponentImages = null
|
||||
@@ -1101,8 +1160,8 @@ class GameViewModel : ViewModel() {
|
||||
userId = msg.userId,
|
||||
name = msg.name,
|
||||
elo = msg.elo,
|
||||
avatarBase64 = msg.avatarBase64 ?: pending?.first,
|
||||
backgroundBase64 = msg.backgroundBase64 ?: pending?.second
|
||||
avatarBase64 = msg.avatarBase64?.let(::acceptedIncomingImage) ?: pending?.first,
|
||||
backgroundBase64 = msg.backgroundBase64?.let(::acceptedIncomingImage) ?: pending?.second
|
||||
)
|
||||
_uiState.value = _uiState.value.copy(
|
||||
opponentProfile = Profile(
|
||||
@@ -1113,6 +1172,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()
|
||||
@@ -1132,12 +1194,14 @@ class GameViewModel : ViewModel() {
|
||||
|
||||
if (state.mode != GameMode.VS_PLAYER_NETWORK) {
|
||||
cancelAi()
|
||||
clock?.pause()
|
||||
clock?.stop()
|
||||
persistIfResumable()
|
||||
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()
|
||||
@@ -1203,10 +1267,10 @@ class GameViewModel : ViewModel() {
|
||||
opponentFlagJob?.cancel()
|
||||
opponentFlagJob = null
|
||||
currentPly = 0
|
||||
lastOpponentRemaining = Long.MAX_VALUE
|
||||
val start = Board.startPosition()
|
||||
resetHistory(start)
|
||||
|
||||
_clockState.value = null
|
||||
_uiState.value = GameUiState(
|
||||
board = start,
|
||||
startBoard = start,
|
||||
@@ -1218,7 +1282,8 @@ class GameViewModel : ViewModel() {
|
||||
handshake = state.handshake,
|
||||
activeTransport = state.activeTransport,
|
||||
opponentUnverified = state.opponentUnverified,
|
||||
chatMessages = state.chatMessages
|
||||
chatMessages = state.chatMessages,
|
||||
spectatorCount = state.spectatorCount
|
||||
)
|
||||
setupClock(timeControl)
|
||||
}
|
||||
@@ -1310,7 +1375,8 @@ class GameViewModel : ViewModel() {
|
||||
val trimmed = text.trim().take(MAX_CHAT_TEXT_CHARS)
|
||||
if (!sendGameMessage(GameMessage.ChatMsg(text = trimmed, gameId = networkGameId))) return
|
||||
_uiState.value = _uiState.value.copy(
|
||||
chatMessages = _uiState.value.chatMessages + ChatEntry(trimmed, null, fromMe = true, System.currentTimeMillis())
|
||||
chatMessages = (_uiState.value.chatMessages + ChatEntry(trimmed, null, fromMe = true))
|
||||
.takeLast(MAX_CHAT_ENTRIES)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1323,7 +1389,8 @@ class GameViewModel : ViewModel() {
|
||||
}
|
||||
if (!sendGameMessage(GameMessage.ChatMsg(imageBase64 = base64, gameId = networkGameId))) return
|
||||
_uiState.value = _uiState.value.copy(
|
||||
chatMessages = _uiState.value.chatMessages + ChatEntry(null, base64, fromMe = true, System.currentTimeMillis())
|
||||
chatMessages = (_uiState.value.chatMessages + ChatEntry(null, base64, fromMe = true))
|
||||
.takeLast(MAX_CHAT_ENTRIES)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1333,6 +1400,122 @@ 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 {
|
||||
// Spectators come over Wi-Fi; other interfaces (mobile data) are not listened on.
|
||||
val port = withContext(Dispatchers.IO) {
|
||||
runCatching { hub.start(cc.skysparkle.matewave.share.LocalNetwork.wifiInet4()) }.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() {
|
||||
@@ -1363,15 +1546,14 @@ class GameViewModel : ViewModel() {
|
||||
}
|
||||
|
||||
private fun onClockTick(cs: ClockState) {
|
||||
_clockState.value = cs
|
||||
val current = _uiState.value
|
||||
// Spectators get the clock as before, when it was part of the game state.
|
||||
if (spectatorWatcher?.isActive == true) onStateForSpectators(current)
|
||||
val flag = cs.flagged
|
||||
if (flag == null || current.status != GameStatus.ONGOING) {
|
||||
_uiState.value = current.copy(clockState = cs)
|
||||
return
|
||||
}
|
||||
if (flag == null || current.status != GameStatus.ONGOING) return
|
||||
when (current.mode) {
|
||||
GameMode.VS_PLAYER_NETWORK -> {
|
||||
_uiState.value = current.copy(clockState = cs)
|
||||
if (flag == current.myColor) {
|
||||
declareNetworkTimeout(flag, sendClaim = true)
|
||||
} else if (opponentFlagJob?.isActive != true) {
|
||||
@@ -1400,12 +1582,11 @@ class GameViewModel : ViewModel() {
|
||||
recordAiResult(current.aiDifficulty, result)
|
||||
clearSavedGame()
|
||||
_uiState.value = current.copy(
|
||||
clockState = cs,
|
||||
status = if (draw) GameStatus.TIMEOUT_DRAW else GameStatus.TIMEOUT,
|
||||
timedOutSide = flag
|
||||
)
|
||||
}
|
||||
GameMode.PUZZLE -> _uiState.value = current.copy(clockState = cs)
|
||||
GameMode.PUZZLE -> Unit
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1418,6 +1599,7 @@ class GameViewModel : ViewModel() {
|
||||
pendingLeave?.first?.cancel()
|
||||
pendingLeave?.second?.disconnect()
|
||||
pendingLeave = null
|
||||
stopSpectating()
|
||||
persistIfResumable()
|
||||
clock?.stop()
|
||||
|
||||
@@ -1438,6 +1620,7 @@ class GameViewModel : ViewModel() {
|
||||
const val MAX_CHAT_TEXT_CHARS = 8_000
|
||||
const val MAX_CHAT_IMAGE_CHARS = 400_000
|
||||
const val CLOCK_TOLERANCE_MS = 2_000L
|
||||
const val MAX_CHAT_ENTRIES = 200
|
||||
const val HANDSHAKE_TIMEOUT_MS = 20_000L
|
||||
const val OPPONENT_FLAG_GRACE_MS = 4_000L
|
||||
const val LEAVE_FLUSH_MS = 700L
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
package cc.skysparkle.matewave.viewmodel
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import cc.skysparkle.matewave.engine.PieceColor
|
||||
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.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 (clockUpdated || ticker?.isActive != true) {
|
||||
ticker?.cancel()
|
||||
ticker = viewModelScope.launch {
|
||||
while (true) {
|
||||
delay(untilShownSecondChanges() ?: break)
|
||||
if (_uiState.value.phase != SpectatePhase.WATCHING) break
|
||||
showClocks()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Milliseconds until the running clock shows the next second; null while nothing counts down. */
|
||||
private fun untilShownSecondChanges(): Long? {
|
||||
if (_uiState.value.phase != SpectatePhase.WATCHING) return null
|
||||
val view = game.view ?: return null
|
||||
val clock = view.clock ?: return null
|
||||
if (view.result != null) return null
|
||||
val shown = clock.advancedBy((System.nanoTime() - clockAtNanos) / 1_000_000L)
|
||||
val left = when (clock.running) {
|
||||
PieceColor.WHITE -> shown.whiteMs
|
||||
PieceColor.BLACK -> shown.blackMs
|
||||
null -> return null
|
||||
}
|
||||
return if (left > 0) left % 1_000 + 1 else null
|
||||
}
|
||||
|
||||
/** 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()
|
||||
}
|
||||
}
|
||||
|
Before Width: | Height: | Size: 3.0 KiB |
|
Before Width: | Height: | Size: 5.2 KiB |
|
Before Width: | Height: | Size: 4.1 KiB |
|
Before Width: | Height: | Size: 5.0 KiB |
|
Before Width: | Height: | Size: 3.7 KiB |
|
Before Width: | Height: | Size: 3.9 KiB |
|
Before Width: | Height: | Size: 7.7 KiB |
|
Before Width: | Height: | Size: 5.5 KiB |
|
Before Width: | Height: | Size: 5.4 KiB |
|
Before Width: | Height: | Size: 3.6 KiB |
|
Before Width: | Height: | Size: 1.7 KiB |
|
Before Width: | Height: | Size: 7.4 KiB |
|
Before Width: | Height: | Size: 5.1 KiB |
|
Before Width: | Height: | Size: 4.6 KiB |