Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3554907164 | ||
|
|
e7054202a1 | ||
|
|
34e02314fd | ||
|
|
95f638a373 | ||
|
|
7a4d300220 | ||
|
|
eae878db09 | ||
|
|
c5587e9418 | ||
|
|
438f06bce2 | ||
|
|
21b39cbc80 | ||
|
|
05d4936c90 | ||
|
|
8a40e86d73 | ||
|
|
ef5af5c395 | ||
|
|
0d0daf8a45 | ||
|
|
6ed42e0bf3 | ||
|
|
cac575ed26 |
@@ -1,27 +0,0 @@
|
|||||||
---
|
|
||||||
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 / F-Droid
|
|
||||||
- Device and Android version:
|
|
||||||
- Mode: vs AI / puzzles / openings / Bluetooth / LAN
|
|
||||||
|
|
||||||
**Screenshots or logs** (optional)
|
|
||||||
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
---
|
|
||||||
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
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
---
|
|
||||||
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:
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
---
|
|
||||||
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:
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
## 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
|
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
ko_fi: skysparkle
|
||||||
@@ -19,7 +19,7 @@ title: "[Bug] "
|
|||||||
**Environment**
|
**Environment**
|
||||||
|
|
||||||
- App version:
|
- App version:
|
||||||
- Installed from: Gitea / GitHub / F-Droid / Google Play
|
- Installed from: GitHub / F-Droid / Google Play
|
||||||
- Device and Android version:
|
- Device and Android version:
|
||||||
- Mode: vs AI / puzzles / openings / Bluetooth / LAN
|
- Mode: vs AI / puzzles / openings / Bluetooth / LAN
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
blank_issues_enabled: true
|
blank_issues_enabled: true
|
||||||
contact_links:
|
contact_links:
|
||||||
- name: Main repository on git.skysparkle.cc
|
- name: Support the project on Ko-fi
|
||||||
url: https://git.skysparkle.cc/kalarina/Matewave
|
url: https://ko-fi.com/skysparkle
|
||||||
about: This GitHub repository is a mirror. Issues are welcome here and on Gitea.
|
about: Donations keep the apps and the Skysparkle server running.
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
# Builds unsigned release APK and AAB. Download them from the run's "Artifacts" and sign locally.
|
||||||
|
name: Build unsigned release
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
tags: ["v*"]
|
||||||
|
paths-ignore: ["**.md", "fastlane/**", ".github/ISSUE_TEMPLATE/**"]
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: build-${{ github.ref }}
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
env:
|
||||||
|
NAME: Matewave
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- uses: actions/setup-java@v4
|
||||||
|
with:
|
||||||
|
distribution: temurin
|
||||||
|
java-version: 21
|
||||||
|
|
||||||
|
- uses: gradle/actions/setup-gradle@v4
|
||||||
|
|
||||||
|
- name: Build
|
||||||
|
run: |
|
||||||
|
chmod +x gradlew
|
||||||
|
./gradlew --no-daemon clean assembleRelease bundleRelease
|
||||||
|
|
||||||
|
- name: Collect files
|
||||||
|
run: |
|
||||||
|
ver=$(grep -oP 'versionName = "\K[^"]+' app/build.gradle.kts)
|
||||||
|
mkdir out
|
||||||
|
cp app/build/outputs/apk/release/app-release-unsigned.apk "out/$NAME-v$ver-unsigned.apk"
|
||||||
|
cp app/build/outputs/bundle/release/app-release.aab "out/$NAME-v$ver-unsigned.aab"
|
||||||
|
cp app/build/outputs/mapping/release/mapping.txt "out/$NAME-v$ver-mapping.txt"
|
||||||
|
git log -1 --format="Commit %h, %ci: %s" > out/BUILD-INFO.txt
|
||||||
|
echo "VER=$ver" >> "$GITHUB_ENV"
|
||||||
|
|
||||||
|
- uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: ${{ env.NAME }}-v${{ env.VER }}-unsigned
|
||||||
|
path: out/
|
||||||
|
retention-days: 30
|
||||||
@@ -4,7 +4,7 @@ Thanks for wanting to help! This guide explains where to contribute, what fits t
|
|||||||
|
|
||||||
## Where to contribute
|
## 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
|
## Ways to help
|
||||||
|
|
||||||
|
|||||||
@@ -9,8 +9,12 @@
|
|||||||
Play against the AI, solve puzzles, learn openings, or play friends nearby over Bluetooth and Wi-Fi/LAN.
|
Play against the AI, solve puzzles, learn openings, or play friends nearby over Bluetooth and Wi-Fi/LAN.
|
||||||
</p>
|
</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]
|
> [!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 [Gitea](https://git.skysparkle.cc/kalarina/Matewave/issues) or [GitHub](https://github.com/kalarina-bit/Matewave/issues), or an email to [cuken107@proton.me](mailto:cuken107@proton.me).
|
> **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]
|
> [!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).
|
> **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).
|
||||||
@@ -21,9 +25,8 @@
|
|||||||
|
|
||||||
<p align="center">
|
<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://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://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>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
@@ -50,8 +53,8 @@
|
|||||||
## <img src="assets/icon-install.png" width="32" alt=""> Installation
|
## <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.
|
- **[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.
|
- **[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](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.
|
- **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
|
## <img src="assets/icon-verify.png" width="32" alt=""> Verifying a download
|
||||||
|
|
||||||
@@ -82,7 +85,13 @@ Nearby multiplayer needs two physical devices — the emulator has no real Bluet
|
|||||||
|
|
||||||
## 🤝 Contributing
|
## 🤝 Contributing
|
||||||
|
|
||||||
Bug reports, puzzle and opening fixes, translation fixes and pull requests are welcome in the [issue tracker](https://git.skysparkle.cc/kalarina/Matewave/issues). Please read [CONTRIBUTING.md](CONTRIBUTING.md) first — it explains what fits the project and how to send changes. To open an issue or a pull request, [create an account](https://git.skysparkle.cc/user/sign_up) on this Gitea.
|
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
|
## 📄 License
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
plugins {
|
plugins {
|
||||||
id("com.android.application")
|
alias(libs.plugins.android.application)
|
||||||
|
alias(libs.plugins.kotlin.compose)
|
||||||
id("org.jetbrains.kotlin.plugin.compose")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
android {
|
android {
|
||||||
@@ -13,8 +12,8 @@ android {
|
|||||||
applicationId = "cc.skysparkle.matewave"
|
applicationId = "cc.skysparkle.matewave"
|
||||||
minSdk = 26
|
minSdk = 26
|
||||||
targetSdk = 36
|
targetSdk = 36
|
||||||
versionCode = 10
|
versionCode = 12
|
||||||
versionName = "1.0.50"
|
versionName = "1.0.52"
|
||||||
}
|
}
|
||||||
|
|
||||||
buildTypes {
|
buildTypes {
|
||||||
@@ -86,20 +85,20 @@ androidComponents {
|
|||||||
}
|
}
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
implementation(platform("androidx.compose:compose-bom:2026.09.00"))
|
implementation(platform(libs.androidx.compose.bom))
|
||||||
implementation("androidx.compose.material3:material3")
|
implementation(libs.androidx.compose.material3)
|
||||||
implementation("androidx.compose.ui:ui")
|
implementation(libs.androidx.compose.ui)
|
||||||
implementation("androidx.activity:activity-compose:1.13.0")
|
implementation(libs.androidx.activity.compose)
|
||||||
|
|
||||||
implementation("androidx.core:core-ktx:1.18.0")
|
implementation(libs.androidx.core.ktx)
|
||||||
implementation("androidx.navigation:navigation-compose:2.9.7")
|
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(libs.junit)
|
||||||
testImplementation("org.json:json:20240303")
|
testImplementation(libs.org.json)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,3 +2,9 @@
|
|||||||
# reflection. Only keep line numbers so release crash reports stay readable.
|
# reflection. Only keep line numbers so release crash reports stay readable.
|
||||||
-keepattributes SourceFile,LineNumberTable
|
-keepattributes SourceFile,LineNumberTable
|
||||||
-renamesourcefileattribute SourceFile
|
-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(...);
|
||||||
|
}
|
||||||
|
|||||||
@@ -36,6 +36,7 @@
|
|||||||
android:icon="@mipmap/ic_launcher"
|
android:icon="@mipmap/ic_launcher"
|
||||||
android:roundIcon="@mipmap/ic_launcher_round"
|
android:roundIcon="@mipmap/ic_launcher_round"
|
||||||
android:label="@string/app_title"
|
android:label="@string/app_title"
|
||||||
|
android:localeConfig="@xml/locales_config"
|
||||||
android:networkSecurityConfig="@xml/network_security_config"
|
android:networkSecurityConfig="@xml/network_security_config"
|
||||||
android:theme="@android:style/Theme.Material.NoActionBar"
|
android:theme="@android:style/Theme.Material.NoActionBar"
|
||||||
android:supportsRtl="true">
|
android:supportsRtl="true">
|
||||||
@@ -44,7 +45,7 @@
|
|||||||
android:name=".MainActivity"
|
android:name=".MainActivity"
|
||||||
android:exported="true"
|
android:exported="true"
|
||||||
android:launchMode="singleTop"
|
android:launchMode="singleTop"
|
||||||
android:screenOrientation="portrait">
|
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboardHidden">
|
||||||
<intent-filter>
|
<intent-filter>
|
||||||
<action android:name="android.intent.action.MAIN" />
|
<action android:name="android.intent.action.MAIN" />
|
||||||
<category android:name="android.intent.category.LAUNCHER" />
|
<category android:name="android.intent.category.LAUNCHER" />
|
||||||
|
|||||||
@@ -66,6 +66,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
SoundManager.init(this)
|
SoundManager.init(this)
|
||||||
|
|
||||||
val appContext = applicationContext
|
val appContext = applicationContext
|
||||||
|
cc.skysparkle.matewave.settings.PieceSetState.load(this)
|
||||||
kotlin.concurrent.thread(name = "warmup", isDaemon = true) {
|
kotlin.concurrent.thread(name = "warmup", isDaemon = true) {
|
||||||
runCatching { cc.skysparkle.matewave.data.FriendsStore.preload() }
|
runCatching { cc.skysparkle.matewave.data.FriendsStore.preload() }
|
||||||
// Decoded here, the pieces are ready before the first board is shown.
|
// Decoded here, the pieces are ready before the first board is shown.
|
||||||
@@ -121,9 +122,12 @@ private fun AppNavHost() {
|
|||||||
onDispose { PresenceHub.release(context) }
|
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(
|
NavHost(
|
||||||
navController = navController,
|
navController = navController,
|
||||||
startDestination = "menu",
|
startDestination = startRoute,
|
||||||
enterTransition = {
|
enterTransition = {
|
||||||
if (isTabSwitch(initialState.destination.route, targetState.destination.route)) fadeThroughIn()
|
if (isTabSwitch(initialState.destination.route, targetState.destination.route)) fadeThroughIn()
|
||||||
else sharedAxisIn(forward = true)
|
else sharedAxisIn(forward = true)
|
||||||
@@ -141,6 +145,22 @@ private fun AppNavHost() {
|
|||||||
else sharedAxisOut(forward = false)
|
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") {
|
composable("menu") {
|
||||||
MainMenuScreen(
|
MainMenuScreen(
|
||||||
viewModel = viewModel,
|
viewModel = viewModel,
|
||||||
@@ -194,7 +214,8 @@ private fun AppNavHost() {
|
|||||||
onOpenPermissions = { navController.navigate("permissions") },
|
onOpenPermissions = { navController.navigate("permissions") },
|
||||||
onOpenAppearance = { navController.navigate("appearance") },
|
onOpenAppearance = { navController.navigate("appearance") },
|
||||||
onOpenLicenses = { navController.navigate("licenses") },
|
onOpenLicenses = { navController.navigate("licenses") },
|
||||||
onOpenShare = { navController.navigate("shareApk") }
|
onOpenShare = { navController.navigate("shareApk") },
|
||||||
|
onOpenGuide = { navController.navigate("guide") }
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -333,9 +354,12 @@ private fun AppNavHost() {
|
|||||||
viewModel.startVsPlayerNetwork(transport, PieceColor.WHITE, timeControl, isHost = true)
|
viewModel.startVsPlayerNetwork(transport, PieceColor.WHITE, timeControl, isHost = true)
|
||||||
navController.navigate("game")
|
navController.navigate("game")
|
||||||
},
|
},
|
||||||
onJoin = { type, timeControl, targetId ->
|
onJoin = { type, timeControl, targetId, expectedUserId ->
|
||||||
val transport = if (type == TransportType.BLUETOOTH) bleTransport else lanTransport
|
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")
|
navController.navigate("game")
|
||||||
},
|
},
|
||||||
onBack = { navController.popBackStack() }
|
onBack = { navController.popBackStack() }
|
||||||
|
|||||||
@@ -98,6 +98,12 @@ class GameClock(private val timeControl: TimeControl, private val scope: Corouti
|
|||||||
publish()
|
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) {
|
fun restore(whiteMillis: Long, blackMillis: Long) {
|
||||||
if (unlimited) return
|
if (unlimited) return
|
||||||
account()
|
account()
|
||||||
|
|||||||
@@ -2,8 +2,12 @@ package cc.skysparkle.matewave.data
|
|||||||
|
|
||||||
import cc.skysparkle.matewave.ai.AiDifficulty
|
import cc.skysparkle.matewave.ai.AiDifficulty
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
|
import cc.skysparkle.matewave.network.PeerLimits
|
||||||
|
import cc.skysparkle.matewave.security.toHex
|
||||||
import org.json.JSONArray
|
import org.json.JSONArray
|
||||||
import org.json.JSONObject
|
import org.json.JSONObject
|
||||||
|
import java.io.File
|
||||||
|
import java.security.MessageDigest
|
||||||
import kotlin.math.pow
|
import kotlin.math.pow
|
||||||
import kotlin.math.roundToInt
|
import kotlin.math.roundToInt
|
||||||
|
|
||||||
@@ -111,6 +115,7 @@ object FriendsStore {
|
|||||||
private const val PREFS = "chess_friends_prefs"
|
private const val PREFS = "chess_friends_prefs"
|
||||||
private const val KEY_LIST = "friends_json"
|
private const val KEY_LIST = "friends_json"
|
||||||
private const val MAX_FRIENDS = 30
|
private const val MAX_FRIENDS = 30
|
||||||
|
private const val IMAGE_DIR = "friend_images"
|
||||||
|
|
||||||
private var appContext: Context? = null
|
private var appContext: Context? = null
|
||||||
|
|
||||||
@@ -125,6 +130,36 @@ object FriendsStore {
|
|||||||
|
|
||||||
private fun prefs() = appContext?.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
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() }
|
fun list(): List<FriendEntry> = synchronized(lock) { readAll() }
|
||||||
|
|
||||||
private fun readAll(): List<FriendEntry> {
|
private fun readAll(): List<FriendEntry> {
|
||||||
@@ -136,15 +171,21 @@ object FriendsStore {
|
|||||||
return emptyList()
|
return emptyList()
|
||||||
}
|
}
|
||||||
val result = ArrayList<FriendEntry>()
|
val result = ArrayList<FriendEntry>()
|
||||||
|
var hasInlineImages = false
|
||||||
for (i in 0 until arr.length()) {
|
for (i in 0 until arr.length()) {
|
||||||
try {
|
try {
|
||||||
val o = arr.getJSONObject(i)
|
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(
|
result.add(
|
||||||
FriendEntry(
|
FriendEntry(
|
||||||
userId = o.optString("uid", "").ifBlank { o.getString("name") },
|
userId = userId,
|
||||||
name = o.getString("name"),
|
name = o.getString("name"),
|
||||||
avatarBase64 = if (o.has("avatar")) o.getString("avatar") else null,
|
avatarBase64 = inlineAvatar ?: if (o.optBoolean("a")) readImage(userId, "a") else null,
|
||||||
backgroundBase64 = if (o.has("background")) o.getString("background") else null,
|
backgroundBase64 = inlineBackground ?: if (o.optBoolean("b")) readImage(userId, "b") else null,
|
||||||
elo = o.optInt("elo", 1200),
|
elo = o.optInt("elo", 1200),
|
||||||
lastPlayedMs = o.optLong("t", 0),
|
lastPlayedMs = o.optLong("t", 0),
|
||||||
favorite = o.optBoolean("fav", false),
|
favorite = o.optBoolean("fav", false),
|
||||||
@@ -156,24 +197,35 @@ object FriendsStore {
|
|||||||
}
|
}
|
||||||
val sorted = result.sortedByDescending { it.lastPlayedMs }
|
val sorted = result.sortedByDescending { it.lastPlayedMs }
|
||||||
cached = sorted
|
cached = sorted
|
||||||
|
if (hasInlineImages) writeAll(sorted, previous = emptyList())
|
||||||
return sorted
|
return sorted
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun writeAll(entries: List<FriendEntry>) {
|
private fun writeAll(entries: List<FriendEntry>, previous: List<FriendEntry> = readAll()) {
|
||||||
val p = prefs() ?: return
|
val p = prefs() ?: return
|
||||||
|
val before = previous.associateBy { it.userId }
|
||||||
val arr = JSONArray()
|
val arr = JSONArray()
|
||||||
entries.forEach { f ->
|
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()
|
val o = JSONObject()
|
||||||
o.put("uid", f.userId)
|
o.put("uid", f.userId)
|
||||||
o.put("name", f.name)
|
o.put("name", f.name)
|
||||||
if (f.avatarBase64 != null) o.put("avatar", f.avatarBase64)
|
if (f.avatarBase64 != null) o.put("a", true)
|
||||||
if (f.backgroundBase64 != null) o.put("background", f.backgroundBase64)
|
if (f.backgroundBase64 != null) o.put("b", true)
|
||||||
o.put("elo", f.elo)
|
o.put("elo", f.elo)
|
||||||
o.put("t", f.lastPlayedMs)
|
o.put("t", f.lastPlayedMs)
|
||||||
if (f.favorite) o.put("fav", true)
|
if (f.favorite) o.put("fav", true)
|
||||||
if (f.lastSeenMs > 0) o.put("s", f.lastSeenMs)
|
if (f.lastSeenMs > 0) o.put("s", f.lastSeenMs)
|
||||||
arr.put(o)
|
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()
|
p.edit().putString(KEY_LIST, arr.toString()).apply()
|
||||||
cached = entries.sortedByDescending { it.lastPlayedMs }
|
cached = entries.sortedByDescending { it.lastPlayedMs }
|
||||||
}
|
}
|
||||||
@@ -182,6 +234,11 @@ object FriendsStore {
|
|||||||
synchronized(lock) { readAll() }
|
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(
|
fun updateProfile(
|
||||||
userId: String,
|
userId: String,
|
||||||
name: String,
|
name: String,
|
||||||
@@ -192,8 +249,8 @@ object FriendsStore {
|
|||||||
synchronized(lock) {
|
synchronized(lock) {
|
||||||
val existing = readAll().firstOrNull { it.userId == userId } ?: return
|
val existing = readAll().firstOrNull { it.userId == userId } ?: return
|
||||||
val updated = existing.copy(
|
val updated = existing.copy(
|
||||||
name = name.ifBlank { existing.name },
|
name = cleanName(name).ifBlank { existing.name },
|
||||||
elo = if (elo > 0) elo else existing.elo,
|
elo = if (elo > 0) cleanElo(elo) else existing.elo,
|
||||||
avatarBase64 = avatarBase64 ?: existing.avatarBase64,
|
avatarBase64 = avatarBase64 ?: existing.avatarBase64,
|
||||||
backgroundBase64 = backgroundBase64 ?: existing.backgroundBase64
|
backgroundBase64 = backgroundBase64 ?: existing.backgroundBase64
|
||||||
)
|
)
|
||||||
@@ -217,12 +274,13 @@ object FriendsStore {
|
|||||||
backgroundBase64: String? = null
|
backgroundBase64: String? = null
|
||||||
): FriendEntry = synchronized(lock) {
|
): FriendEntry = synchronized(lock) {
|
||||||
val existing = readAll().firstOrNull { it.userId == userId }
|
val existing = readAll().firstOrNull { it.userId == userId }
|
||||||
|
val clean = cleanName(name)
|
||||||
val merged = FriendEntry(
|
val merged = FriendEntry(
|
||||||
userId = userId,
|
userId = userId,
|
||||||
name = name.ifBlank { existing?.name ?: name },
|
name = clean.ifBlank { existing?.name ?: clean },
|
||||||
avatarBase64 = avatarBase64 ?: existing?.avatarBase64,
|
avatarBase64 = avatarBase64 ?: existing?.avatarBase64,
|
||||||
backgroundBase64 = backgroundBase64 ?: existing?.backgroundBase64,
|
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(),
|
lastPlayedMs = System.currentTimeMillis(),
|
||||||
favorite = existing?.favorite ?: false,
|
favorite = existing?.favorite ?: false,
|
||||||
lastSeenMs = existing?.lastSeenMs ?: 0
|
lastSeenMs = existing?.lastSeenMs ?: 0
|
||||||
|
|||||||
@@ -7,44 +7,6 @@ enum class PieceType(val symbol: Char) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
data class Piece(val type: PieceType, val color: PieceColor) {
|
data class Piece(val type: PieceType, val color: PieceColor) {
|
||||||
fun drawableRes(): Int = when (color) {
|
|
||||||
PieceColor.WHITE -> when (type) {
|
|
||||||
PieceType.PAWN -> cc.skysparkle.matewave.R.drawable.piece_white_pawn
|
|
||||||
PieceType.KNIGHT -> cc.skysparkle.matewave.R.drawable.piece_white_knight
|
|
||||||
PieceType.BISHOP -> cc.skysparkle.matewave.R.drawable.piece_white_bishop
|
|
||||||
PieceType.ROOK -> cc.skysparkle.matewave.R.drawable.piece_white_rook
|
|
||||||
PieceType.QUEEN -> cc.skysparkle.matewave.R.drawable.piece_white_queen
|
|
||||||
PieceType.KING -> cc.skysparkle.matewave.R.drawable.piece_white_king
|
|
||||||
}
|
|
||||||
PieceColor.BLACK -> when (type) {
|
|
||||||
PieceType.PAWN -> cc.skysparkle.matewave.R.drawable.piece_black_pawn
|
|
||||||
PieceType.KNIGHT -> cc.skysparkle.matewave.R.drawable.piece_black_knight
|
|
||||||
PieceType.BISHOP -> cc.skysparkle.matewave.R.drawable.piece_black_bishop
|
|
||||||
PieceType.ROOK -> cc.skysparkle.matewave.R.drawable.piece_black_rook
|
|
||||||
PieceType.QUEEN -> cc.skysparkle.matewave.R.drawable.piece_black_queen
|
|
||||||
PieceType.KING -> cc.skysparkle.matewave.R.drawable.piece_black_king
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun unicode(): String = when (color) {
|
|
||||||
PieceColor.WHITE -> when (type) {
|
|
||||||
PieceType.PAWN -> "\u2659"
|
|
||||||
PieceType.KNIGHT -> "\u2658"
|
|
||||||
PieceType.BISHOP -> "\u2657"
|
|
||||||
PieceType.ROOK -> "\u2656"
|
|
||||||
PieceType.QUEEN -> "\u2655"
|
|
||||||
PieceType.KING -> "\u2654"
|
|
||||||
}
|
|
||||||
PieceColor.BLACK -> when (type) {
|
|
||||||
PieceType.PAWN -> "\u265F"
|
|
||||||
PieceType.KNIGHT -> "\u265E"
|
|
||||||
PieceType.BISHOP -> "\u265D"
|
|
||||||
PieceType.ROOK -> "\u265C"
|
|
||||||
PieceType.QUEEN -> "\u265B"
|
|
||||||
PieceType.KING -> "\u265A"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun fenChar(): Char =
|
fun fenChar(): Char =
|
||||||
if (color == PieceColor.WHITE) type.symbol else type.symbol.lowercaseChar()
|
if (color == PieceColor.WHITE) type.symbol else type.symbol.lowercaseChar()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -73,6 +73,9 @@ class BleTransport(
|
|||||||
|
|
||||||
private const val INCOMPLETE_TTL_MS = 30_000L
|
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_TOTAL_MARKER = 0
|
||||||
private const val CTRL_ACK = 1
|
private const val CTRL_ACK = 1
|
||||||
private const val CTRL_NACK = 2
|
private const val CTRL_NACK = 2
|
||||||
@@ -232,6 +235,8 @@ class BleTransport(
|
|||||||
role = Role.PERIPHERAL
|
role = Role.PERIPHERAL
|
||||||
hosting = true
|
hosting = true
|
||||||
|
|
||||||
|
// Presence may already be advertising in the low-power mode; restart it for hosting.
|
||||||
|
if (advertisingActive || advertiseCallback != null) startAdvertising()
|
||||||
startPresence()
|
startPresence()
|
||||||
_connectionState.value = ConnectionState.CONNECTING
|
_connectionState.value = ConnectionState.CONNECTING
|
||||||
}
|
}
|
||||||
@@ -300,10 +305,14 @@ class BleTransport(
|
|||||||
}
|
}
|
||||||
// One advertisement at a time: a second start would leak the first one.
|
// One advertisement at a time: a second start would leak the first one.
|
||||||
if (advertiseCallback != null) stopAdvertising()
|
if (advertiseCallback != null) stopAdvertising()
|
||||||
|
// A hosted game should be found at once; plain presence can save the battery.
|
||||||
val settings = AdvertiseSettings.Builder()
|
val settings = AdvertiseSettings.Builder()
|
||||||
|
.setAdvertiseMode(
|
||||||
.setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY)
|
if (hosting) AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY else AdvertiseSettings.ADVERTISE_MODE_BALANCED
|
||||||
.setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_HIGH)
|
)
|
||||||
|
.setTxPowerLevel(
|
||||||
|
if (hosting) AdvertiseSettings.ADVERTISE_TX_POWER_HIGH else AdvertiseSettings.ADVERTISE_TX_POWER_MEDIUM
|
||||||
|
)
|
||||||
.setConnectable(true)
|
.setConnectable(true)
|
||||||
.build()
|
.build()
|
||||||
|
|
||||||
@@ -790,6 +799,11 @@ class BleTransport(
|
|||||||
val now = System.currentTimeMillis()
|
val now = System.currentTimeMillis()
|
||||||
incoming.entries.removeAll { now - it.value.startedAt > INCOMPLETE_TTL_MS }
|
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) }
|
val entry = incoming.getOrPut(messageId) { PartialMessage(total, now) }
|
||||||
if (entry.total != total) {
|
if (entry.total != total) {
|
||||||
incoming[messageId] = PartialMessage(total, now).also { it.parts[index] = payload }
|
incoming[messageId] = PartialMessage(total, now).also { it.parts[index] = payload }
|
||||||
|
|||||||
@@ -29,6 +29,8 @@ data class LanPeer(
|
|||||||
val fingerprint: String = "",
|
val fingerprint: String = "",
|
||||||
|
|
||||||
val signature: 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. */
|
/** 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. */
|
/** Tag of the LAN game the peer plays, empty when not in one. */
|
||||||
@@ -59,8 +61,22 @@ class LanTransport(
|
|||||||
|
|
||||||
const val RESOLVE_RETRY_MS = 400L
|
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
|
override val type = TransportType.LAN
|
||||||
@@ -72,7 +88,8 @@ class LanTransport(
|
|||||||
context.getSystemService(Context.NSD_SERVICE) as? NsdManager
|
context.getSystemService(Context.NSD_SERVICE) as? NsdManager
|
||||||
|
|
||||||
private var serverSocket: ServerSocket? = null
|
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()
|
private val socketLock = Any()
|
||||||
|
|
||||||
@@ -82,7 +99,7 @@ class LanTransport(
|
|||||||
socket = candidate
|
socket = candidate
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
private var output: OutputStream? = null
|
@Volatile private var output: OutputStream? = null
|
||||||
private val dispatcher = MessageDispatcher()
|
private val dispatcher = MessageDispatcher()
|
||||||
|
|
||||||
@Volatile private var hosting = false
|
@Volatile private var hosting = false
|
||||||
@@ -91,6 +108,9 @@ class LanTransport(
|
|||||||
|
|
||||||
private var registeredServiceName: String? = null
|
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 {
|
private val ownServiceName: String by lazy {
|
||||||
val fingerprint = cc.skysparkle.matewave.security.DeviceKeys.publicKeyFingerprint(context)
|
val fingerprint = cc.skysparkle.matewave.security.DeviceKeys.publicKeyFingerprint(context)
|
||||||
?: cc.skysparkle.matewave.data.DeviceIdentity.deviceId(context).take(12)
|
?: cc.skysparkle.matewave.data.DeviceIdentity.deviceId(context).take(12)
|
||||||
@@ -211,13 +231,15 @@ class LanTransport(
|
|||||||
val profile = cc.skysparkle.matewave.data.ProfileStore.get()
|
val profile = cc.skysparkle.matewave.data.ProfileStore.get()
|
||||||
runCatching {
|
runCatching {
|
||||||
val shownName = profile.name.take(40)
|
val shownName = profile.name.take(40)
|
||||||
|
val signedAt = System.currentTimeMillis() / 1000L
|
||||||
setAttribute("id", profile.userId)
|
setAttribute("id", profile.userId)
|
||||||
setAttribute("name", shownName)
|
setAttribute("name", shownName)
|
||||||
setAttribute("elo", profile.elo.toString())
|
setAttribute("elo", profile.elo.toString())
|
||||||
setAttribute("fp", cc.skysparkle.matewave.security.DeviceKeys.publicKeyFingerprint(context) ?: "")
|
setAttribute("fp", cc.skysparkle.matewave.security.DeviceKeys.publicKeyFingerprint(context) ?: "")
|
||||||
|
setAttribute("ts", signedAt.toString())
|
||||||
|
|
||||||
cc.skysparkle.matewave.security.DeviceKeys.sign(
|
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) }
|
)?.let { setAttribute("sig", it) }
|
||||||
cc.skysparkle.matewave.spectate.SpectatorAdvert.attributes().forEach { (key, value) -> setAttribute(key, value) }
|
cc.skysparkle.matewave.spectate.SpectatorAdvert.attributes().forEach { (key, value) -> setAttribute(key, value) }
|
||||||
}
|
}
|
||||||
@@ -240,9 +262,15 @@ class LanTransport(
|
|||||||
nsd.registerService(info, NsdManager.PROTOCOL_DNS_SD, listener)
|
nsd.registerService(info, NsdManager.PROTOCOL_DNS_SD, listener)
|
||||||
} catch (_: Exception) {
|
} catch (_: Exception) {
|
||||||
}
|
}
|
||||||
|
resignJob = scope.launch {
|
||||||
|
kotlinx.coroutines.delay(PRESENCE_RESIGN_MS)
|
||||||
|
republishProfile()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun unregisterService() {
|
private fun unregisterService() {
|
||||||
|
resignJob?.cancel()
|
||||||
|
resignJob = null
|
||||||
val nsd = nsdManager ?: return
|
val nsd = nsdManager ?: return
|
||||||
registrationListener?.let {
|
registrationListener?.let {
|
||||||
try { nsd.unregisterService(it) } catch (_: Exception) {}
|
try { nsd.unregisterService(it) } catch (_: Exception) {}
|
||||||
@@ -362,6 +390,7 @@ class LanTransport(
|
|||||||
|
|
||||||
fingerprint = attr("fp").ifEmpty { fingerprintFromServiceName(info.serviceName ?: "") ?: "" },
|
fingerprint = attr("fp").ifEmpty { fingerprintFromServiceName(info.serviceName ?: "") ?: "" },
|
||||||
signature = attr("sig"),
|
signature = attr("sig"),
|
||||||
|
signedAtSeconds = attr("ts").toLongOrNull() ?: 0,
|
||||||
serviceName = info.serviceName ?: "",
|
serviceName = info.serviceName ?: "",
|
||||||
gameTag = game.gameTag,
|
gameTag = game.gameTag,
|
||||||
spectatePort = game.spectatePort
|
spectatePort = game.spectatePort
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
package cc.skysparkle.matewave.network
|
package cc.skysparkle.matewave.network
|
||||||
|
|
||||||
|
import android.util.Log
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
import kotlinx.coroutines.flow.update
|
|
||||||
|
|
||||||
enum class DisconnectReason(val userText: String, val textRes: Int) {
|
enum class DisconnectReason(val userText: String, val textRes: Int) {
|
||||||
NONE("—", cc.skysparkle.matewave.R.string.reason_unknown),
|
NONE("—", cc.skysparkle.matewave.R.string.reason_unknown),
|
||||||
@@ -18,23 +18,13 @@ enum class DisconnectReason(val userText: String, val textRes: Int) {
|
|||||||
PORT_BUSY("Could not open port", cc.skysparkle.matewave.R.string.reason_port_busy)
|
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
|
|
||||||
)
|
|
||||||
|
|
||||||
object NetworkLog {
|
object NetworkLog {
|
||||||
private const val CAPACITY = 60
|
|
||||||
|
|
||||||
private val _events = MutableStateFlow<List<NetworkEvent>>(emptyList())
|
|
||||||
|
|
||||||
private val _lastReason = MutableStateFlow(DisconnectReason.NONE)
|
private val _lastReason = MutableStateFlow(DisconnectReason.NONE)
|
||||||
val lastReason: StateFlow<DisconnectReason> = _lastReason
|
val lastReason: StateFlow<DisconnectReason> = _lastReason
|
||||||
|
|
||||||
|
/** Debug output only: release builds strip Log.d (see proguard-rules.pro). */
|
||||||
fun log(transport: String, text: String) {
|
fun log(transport: String, text: String) {
|
||||||
val event = NetworkEvent(System.currentTimeMillis(), transport, text)
|
Log.d("Matewave/$transport", text)
|
||||||
_events.update { (it + event).takeLast(CAPACITY) }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fun reason(transport: String, reason: DisconnectReason, detail: String? = null) {
|
fun reason(transport: String, reason: DisconnectReason, detail: String? = null) {
|
||||||
|
|||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -141,13 +141,19 @@ class LocalPresence(
|
|||||||
|
|
||||||
val knownKey = knownPeers.publicKeyOf(id)
|
val knownKey = knownPeers.publicKeyOf(id)
|
||||||
if (knownKey != null) {
|
if (knownKey != null) {
|
||||||
val authentic = peer.signature.isNotEmpty() && DeviceKeys.verify(
|
// A known friend must send a fresh announcement signed with their key: an old one
|
||||||
knownKey,
|
// recorded and replayed by someone else is not accepted.
|
||||||
cc.skysparkle.matewave.network.LanTransport.presencePayload(peer.playerId, peer.displayName, peer.elo),
|
val authentic = peer.signature.isNotEmpty() &&
|
||||||
peer.signature
|
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) {
|
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
|
return@forEach
|
||||||
}
|
}
|
||||||
FriendsStore.updateProfile(
|
FriendsStore.updateProfile(
|
||||||
|
|||||||
@@ -6,8 +6,9 @@ import android.net.Uri
|
|||||||
|
|
||||||
/** External links of the app, kept in one place. */
|
/** External links of the app, kept in one place. */
|
||||||
object AppLinks {
|
object AppLinks {
|
||||||
const val REPOSITORY = "https://git.skysparkle.cc/kalarina/Matewave"
|
const val REPOSITORY = "https://github.com/kalarina-bit/Matewave"
|
||||||
const val REPOSITORY_LABEL = "git.skysparkle.cc/kalarina/Matewave"
|
const val REPOSITORY_LABEL = "github.com/kalarina-bit/Matewave"
|
||||||
|
const val DONATE = "https://ko-fi.com/skysparkle"
|
||||||
const val PRIVACY_POLICY = "https://skysparkle.cc/privacy?lang=en"
|
const val PRIVACY_POLICY = "https://skysparkle.cc/privacy?lang=en"
|
||||||
|
|
||||||
/** Opens a link in the browser; does nothing if no app can open it. */
|
/** Opens a link in the browser; does nothing if no app can open it. */
|
||||||
|
|||||||
@@ -22,10 +22,6 @@ class BoardAppearance(context: Context) {
|
|||||||
get() = prefs.getBoolean(KEY_COORDS, true)
|
get() = prefs.getBoolean(KEY_COORDS, true)
|
||||||
set(value) { prefs.edit().putBoolean(KEY_COORDS, value).apply() }
|
set(value) { prefs.edit().putBoolean(KEY_COORDS, value).apply() }
|
||||||
|
|
||||||
var useImagePieces: Boolean
|
|
||||||
get() = prefs.getBoolean(KEY_IMAGES, true)
|
|
||||||
set(value) { prefs.edit().putBoolean(KEY_IMAGES, value).apply() }
|
|
||||||
|
|
||||||
var showLastMove: Boolean
|
var showLastMove: Boolean
|
||||||
get() = prefs.getBoolean(KEY_LAST_MOVE, true)
|
get() = prefs.getBoolean(KEY_LAST_MOVE, true)
|
||||||
set(value) { prefs.edit().putBoolean(KEY_LAST_MOVE, value).apply() }
|
set(value) { prefs.edit().putBoolean(KEY_LAST_MOVE, value).apply() }
|
||||||
@@ -45,6 +41,5 @@ class BoardAppearance(context: Context) {
|
|||||||
const val PREFS = "board_appearance"
|
const val PREFS = "board_appearance"
|
||||||
const val KEY_THEME = "theme"
|
const val KEY_THEME = "theme"
|
||||||
const val KEY_COORDS = "coords"
|
const val KEY_COORDS = "coords"
|
||||||
const val KEY_IMAGES = "images"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,94 @@
|
|||||||
|
package cc.skysparkle.matewave.settings
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import cc.skysparkle.matewave.R
|
||||||
|
import cc.skysparkle.matewave.engine.PieceColor
|
||||||
|
import cc.skysparkle.matewave.engine.PieceType
|
||||||
|
|
||||||
|
/** Piece pictures, white and black, in PieceType order: pawn, knight, bishop, rook, queen, king. */
|
||||||
|
enum class PieceSet(val titleRes: Int, private val white: IntArray, private val black: IntArray) {
|
||||||
|
CLASSIC(
|
||||||
|
R.string.piece_set_classic,
|
||||||
|
intArrayOf(
|
||||||
|
R.drawable.piece_classic_white_pawn, R.drawable.piece_classic_white_knight, R.drawable.piece_classic_white_bishop,
|
||||||
|
R.drawable.piece_classic_white_rook, R.drawable.piece_classic_white_queen, R.drawable.piece_classic_white_king
|
||||||
|
),
|
||||||
|
intArrayOf(
|
||||||
|
R.drawable.piece_classic_black_pawn, R.drawable.piece_classic_black_knight, R.drawable.piece_classic_black_bishop,
|
||||||
|
R.drawable.piece_classic_black_rook, R.drawable.piece_classic_black_queen, R.drawable.piece_classic_black_king
|
||||||
|
)
|
||||||
|
),
|
||||||
|
OUTLINE(
|
||||||
|
R.string.piece_set_outline,
|
||||||
|
intArrayOf(
|
||||||
|
R.drawable.piece_outline_white_pawn, R.drawable.piece_outline_white_knight, R.drawable.piece_outline_white_bishop,
|
||||||
|
R.drawable.piece_outline_white_rook, R.drawable.piece_outline_white_queen, R.drawable.piece_outline_white_king
|
||||||
|
),
|
||||||
|
intArrayOf(
|
||||||
|
R.drawable.piece_outline_black_pawn, R.drawable.piece_outline_black_knight, R.drawable.piece_outline_black_bishop,
|
||||||
|
R.drawable.piece_outline_black_rook, R.drawable.piece_outline_black_queen, R.drawable.piece_outline_black_king
|
||||||
|
)
|
||||||
|
),
|
||||||
|
PASTEL(
|
||||||
|
R.string.piece_set_pastel,
|
||||||
|
intArrayOf(
|
||||||
|
R.drawable.piece_pastel_white_pawn, R.drawable.piece_pastel_white_knight, R.drawable.piece_pastel_white_bishop,
|
||||||
|
R.drawable.piece_pastel_white_rook, R.drawable.piece_pastel_white_queen, R.drawable.piece_pastel_white_king
|
||||||
|
),
|
||||||
|
intArrayOf(
|
||||||
|
R.drawable.piece_pastel_black_pawn, R.drawable.piece_pastel_black_knight, R.drawable.piece_pastel_black_bishop,
|
||||||
|
R.drawable.piece_pastel_black_rook, R.drawable.piece_pastel_black_queen, R.drawable.piece_pastel_black_king
|
||||||
|
)
|
||||||
|
),
|
||||||
|
WOOD(
|
||||||
|
R.string.piece_set_wood,
|
||||||
|
intArrayOf(
|
||||||
|
R.drawable.piece_wood_white_pawn, R.drawable.piece_wood_white_knight, R.drawable.piece_wood_white_bishop,
|
||||||
|
R.drawable.piece_wood_white_rook, R.drawable.piece_wood_white_queen, R.drawable.piece_wood_white_king
|
||||||
|
),
|
||||||
|
intArrayOf(
|
||||||
|
R.drawable.piece_wood_black_pawn, R.drawable.piece_wood_black_knight, R.drawable.piece_wood_black_bishop,
|
||||||
|
R.drawable.piece_wood_black_rook, R.drawable.piece_wood_black_queen, R.drawable.piece_wood_black_king
|
||||||
|
)
|
||||||
|
),
|
||||||
|
FLAT(
|
||||||
|
R.string.piece_set_flat,
|
||||||
|
intArrayOf(
|
||||||
|
R.drawable.piece_flat_white_pawn, R.drawable.piece_flat_white_knight, R.drawable.piece_flat_white_bishop,
|
||||||
|
R.drawable.piece_flat_white_rook, R.drawable.piece_flat_white_queen, R.drawable.piece_flat_white_king
|
||||||
|
),
|
||||||
|
intArrayOf(
|
||||||
|
R.drawable.piece_flat_black_pawn, R.drawable.piece_flat_black_knight, R.drawable.piece_flat_black_bishop,
|
||||||
|
R.drawable.piece_flat_black_rook, R.drawable.piece_flat_black_queen, R.drawable.piece_flat_black_king
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
fun res(type: PieceType, color: PieceColor): Int =
|
||||||
|
(if (color == PieceColor.WHITE) white else black)[type.ordinal]
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The chosen piece set; every board and piece picture follows it at once. */
|
||||||
|
object PieceSetState {
|
||||||
|
private const val PREFS = "board_appearance"
|
||||||
|
private const val KEY = "piece_set"
|
||||||
|
|
||||||
|
var current by mutableStateOf(PieceSet.CLASSIC)
|
||||||
|
private set
|
||||||
|
|
||||||
|
/** Reads the saved set; call once before the first frame. */
|
||||||
|
fun load(context: Context) {
|
||||||
|
val saved = prefs(context).getString(KEY, null)
|
||||||
|
current = PieceSet.entries.firstOrNull { it.name == saved } ?: PieceSet.CLASSIC
|
||||||
|
}
|
||||||
|
|
||||||
|
fun select(context: Context, set: PieceSet) {
|
||||||
|
prefs(context).edit().putString(KEY, set.name).apply()
|
||||||
|
current = set
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun prefs(context: Context) =
|
||||||
|
context.applicationContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||||
|
}
|
||||||
@@ -5,10 +5,12 @@ import java.io.File
|
|||||||
import java.io.IOException
|
import java.io.IOException
|
||||||
import java.io.OutputStream
|
import java.io.OutputStream
|
||||||
import java.net.Inet4Address
|
import java.net.Inet4Address
|
||||||
|
import java.net.InetSocketAddress
|
||||||
import java.net.NetworkInterface
|
import java.net.NetworkInterface
|
||||||
import java.net.ServerSocket
|
import java.net.ServerSocket
|
||||||
import java.net.Socket
|
import java.net.Socket
|
||||||
import java.util.Locale
|
import java.util.Locale
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger
|
||||||
import kotlin.concurrent.thread
|
import kotlin.concurrent.thread
|
||||||
|
|
||||||
class ApkShareServer(private val apk: File, private val appName: String) {
|
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
|
@Volatile
|
||||||
private var server: ServerSocket? = null
|
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 {
|
fun start(): Int {
|
||||||
val socket = ServerSocket(0)
|
val socket = ServerSocket()
|
||||||
|
socket.reuseAddress = true
|
||||||
|
socket.bind(InetSocketAddress(LocalNetwork.wifiInet4(), 0))
|
||||||
server = socket
|
server = socket
|
||||||
thread(name = "apk-share-accept", isDaemon = true) {
|
thread(name = "apk-share-accept", isDaemon = true) {
|
||||||
while (!socket.isClosed) {
|
while (!socket.isClosed) {
|
||||||
@@ -27,7 +34,19 @@ class ApkShareServer(private val apk: File, private val appName: String) {
|
|||||||
} catch (e: IOException) {
|
} catch (e: IOException) {
|
||||||
break
|
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
|
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) {
|
private fun sendText(out: OutputStream, code: Int, reason: String, text: String, withBody: Boolean) {
|
||||||
val body = text.toByteArray(Charsets.UTF_8)
|
val body = text.toByteArray(Charsets.UTF_8)
|
||||||
writeHeader(out, code, reason, "text/plain; charset=utf-8", body.size.toLong())
|
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 {
|
object LocalNetwork {
|
||||||
private val WIFI_PREFIXES = listOf("wlan", "swlan", "ap", "softap", "eth")
|
private val WIFI_PREFIXES = listOf("wlan", "swlan", "ap", "softap", "eth")
|
||||||
|
|
||||||
fun wifiIpv4(): String? = runCatching {
|
fun wifiInet4(): Inet4Address? = runCatching {
|
||||||
NetworkInterface.getNetworkInterfaces()?.toList().orEmpty()
|
NetworkInterface.getNetworkInterfaces()?.toList().orEmpty()
|
||||||
.filter { nif -> nif.isUp && !nif.isLoopback && WIFI_PREFIXES.any { nif.name.startsWith(it) } }
|
.filter { nif -> nif.isUp && !nif.isLoopback && WIFI_PREFIXES.any { nif.name.startsWith(it) } }
|
||||||
.flatMap { nif -> nif.inetAddresses.toList() }
|
.flatMap { nif -> nif.inetAddresses.toList() }
|
||||||
.filterIsInstance<Inet4Address>()
|
.filterIsInstance<Inet4Address>()
|
||||||
.firstOrNull { it.isSiteLocalAddress }
|
.firstOrNull { it.isSiteLocalAddress }
|
||||||
?.hostAddress
|
|
||||||
}.getOrNull()
|
}.getOrNull()
|
||||||
|
|
||||||
|
fun wifiIpv4(): String? = wifiInet4()?.hostAddress
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -86,21 +86,46 @@ private object DecodedImageCache {
|
|||||||
fun put(key: String, bitmap: Bitmap) { cache.put(key, bitmap) }
|
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? {
|
fun decodeChatImage(base64: String, maxDimension: Int = 0): Bitmap? {
|
||||||
return try {
|
return try {
|
||||||
val bytes = Base64.decode(base64, Base64.NO_WRAP)
|
val bytes = Base64.decode(base64, Base64.NO_WRAP)
|
||||||
if (maxDimension <= 0) {
|
// The size is always checked first: the image may come from another device.
|
||||||
BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
|
val (width, height) = imageBounds(bytes) ?: return null
|
||||||
} else {
|
if (width > MAX_INCOMING_IMAGE_PX || height > MAX_INCOMING_IMAGE_PX) return null
|
||||||
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
val target = if (maxDimension > 0) maxDimension else DEFAULT_DECODE_PX
|
||||||
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)
|
var sample = 1
|
||||||
var sample = 1
|
while (maxOf(width, height) / (sample * 2) >= target) sample *= 2
|
||||||
while (maxOf(bounds.outWidth, bounds.outHeight) / (sample * 2) >= maxDimension) sample *= 2
|
val options = BitmapFactory.Options().apply { inSampleSize = sample }
|
||||||
val options = BitmapFactory.Options().apply { inSampleSize = sample }
|
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options)
|
||||||
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options)
|
|
||||||
}
|
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
null
|
null
|
||||||
|
} catch (e: OutOfMemoryError) {
|
||||||
|
null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -33,10 +33,11 @@ import androidx.compose.ui.unit.IntOffset
|
|||||||
import androidx.compose.ui.unit.IntSize
|
import androidx.compose.ui.unit.IntSize
|
||||||
import cc.skysparkle.matewave.engine.Board
|
import cc.skysparkle.matewave.engine.Board
|
||||||
import cc.skysparkle.matewave.engine.Move
|
import cc.skysparkle.matewave.engine.Move
|
||||||
import cc.skysparkle.matewave.engine.Piece
|
|
||||||
import cc.skysparkle.matewave.engine.PieceColor
|
import cc.skysparkle.matewave.engine.PieceColor
|
||||||
import cc.skysparkle.matewave.engine.PieceType
|
import cc.skysparkle.matewave.engine.PieceType
|
||||||
import cc.skysparkle.matewave.settings.BoardAppearance
|
import cc.skysparkle.matewave.settings.BoardAppearance
|
||||||
|
import cc.skysparkle.matewave.settings.PieceSet
|
||||||
|
import cc.skysparkle.matewave.settings.PieceSetState
|
||||||
import cc.skysparkle.matewave.ui.theme.HighlightCheck
|
import cc.skysparkle.matewave.ui.theme.HighlightCheck
|
||||||
import cc.skysparkle.matewave.ui.theme.HighlightHint
|
import cc.skysparkle.matewave.ui.theme.HighlightHint
|
||||||
import cc.skysparkle.matewave.ui.theme.HighlightLastMove
|
import cc.skysparkle.matewave.ui.theme.HighlightLastMove
|
||||||
@@ -44,21 +45,22 @@ import cc.skysparkle.matewave.ui.theme.HighlightMove
|
|||||||
import kotlin.math.floor
|
import kotlin.math.floor
|
||||||
import kotlin.math.roundToInt
|
import kotlin.math.roundToInt
|
||||||
|
|
||||||
/** The twelve piece pictures, decoded once and shared by the board and the other piece views. */
|
/** The twelve pictures of the chosen piece set, decoded once and shared by the board and the other piece views. */
|
||||||
internal object PieceImages {
|
internal object PieceImages {
|
||||||
@Volatile private var cache: Array<ImageBitmap>? = null
|
@Volatile private var cache: Pair<PieceSet, Array<ImageBitmap>>? = null
|
||||||
|
|
||||||
fun get(context: Context): Array<ImageBitmap> {
|
fun get(context: Context, set: PieceSet = PieceSetState.current): Array<ImageBitmap> {
|
||||||
cache?.let { return it }
|
cache?.let { if (it.first == set) return it.second }
|
||||||
synchronized(this) {
|
synchronized(this) {
|
||||||
cache?.let { return it }
|
cache?.let { if (it.first == set) return it.second }
|
||||||
val options = BitmapFactory.Options().apply { inScaled = false }
|
val options = BitmapFactory.Options().apply { inScaled = false }
|
||||||
val types = PieceType.entries
|
val types = PieceType.entries
|
||||||
val loaded = Array(PieceColor.entries.size * types.size) { i ->
|
val loaded = Array(PieceColor.entries.size * types.size) { i ->
|
||||||
val piece = Piece(types[i % types.size], PieceColor.entries[i / types.size])
|
val res = set.res(types[i % types.size], PieceColor.entries[i / types.size])
|
||||||
BitmapFactory.decodeResource(context.resources, piece.drawableRes(), options).asImageBitmap()
|
BitmapFactory.decodeResource(context.resources, res, options).asImageBitmap()
|
||||||
}
|
}
|
||||||
cache = loaded
|
// Only the set in use stays in memory.
|
||||||
|
cache = set to loaded
|
||||||
return loaded
|
return loaded
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -91,12 +93,12 @@ fun ChessBoardView(
|
|||||||
val appearance = remember { BoardAppearance(context) }
|
val appearance = remember { BoardAppearance(context) }
|
||||||
val theme = remember { appearance.theme }
|
val theme = remember { appearance.theme }
|
||||||
val showCoords = remember { appearance.showCoordinates }
|
val showCoords = remember { appearance.showCoordinates }
|
||||||
val imagePieces = remember { appearance.useImagePieces }
|
|
||||||
val lastMoveSetting = remember { appearance.showLastMove }
|
val lastMoveSetting = remember { appearance.showLastMove }
|
||||||
val showLastMove = highlightLastMove ?: lastMoveSetting
|
val showLastMove = highlightLastMove ?: lastMoveSetting
|
||||||
val showCheck = remember { appearance.showCheckHighlight }
|
val showCheck = remember { appearance.showCheckHighlight }
|
||||||
|
|
||||||
val pieceImages = if (imagePieces) remember(context) { PieceImages.get(context) } else null
|
val pieceSet = PieceSetState.current
|
||||||
|
val pieceImages = remember(pieceSet) { PieceImages.get(context, pieceSet) }
|
||||||
|
|
||||||
val targetMask = remember(legalTargets) {
|
val targetMask = remember(legalTargets) {
|
||||||
var mask = 0L
|
var mask = 0L
|
||||||
@@ -107,9 +109,6 @@ fun ChessBoardView(
|
|||||||
val coordPaint = remember {
|
val coordPaint = remember {
|
||||||
Paint().apply { isAntiAlias = true; typeface = Typeface.DEFAULT_BOLD }
|
Paint().apply { isAntiAlias = true; typeface = Typeface.DEFAULT_BOLD }
|
||||||
}
|
}
|
||||||
val glyphPaint = remember {
|
|
||||||
Paint().apply { isAntiAlias = true; textAlign = Paint.Align.CENTER }
|
|
||||||
}
|
|
||||||
|
|
||||||
val currentOnSquareClick by rememberUpdatedState(onSquareClick)
|
val currentOnSquareClick by rememberUpdatedState(onSquareClick)
|
||||||
val currentBoard by rememberUpdatedState(board)
|
val currentBoard by rememberUpdatedState(board)
|
||||||
@@ -184,13 +183,6 @@ fun ChessBoardView(
|
|||||||
val liftedSize = pieceSize * LIFT_SCALE
|
val liftedSize = pieceSize * LIFT_SCALE
|
||||||
val liftedDst = IntSize(liftedSize.roundToInt(), liftedSize.roundToInt())
|
val liftedDst = IntSize(liftedSize.roundToInt(), liftedSize.roundToInt())
|
||||||
val hoverStroke = Stroke(width = cell * 0.07f)
|
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 {
|
onDrawBehind {
|
||||||
val lastFrom = if (showLastMove) (lastMove?.from ?: -1) else -1
|
val lastFrom = if (showLastMove) (lastMove?.from ?: -1) else -1
|
||||||
val lastTo = if (showLastMove) (lastMove?.to ?: -1) else -1
|
val lastTo = if (showLastMove) (lastMove?.to ?: -1) else -1
|
||||||
@@ -251,10 +243,6 @@ fun ChessBoardView(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (pieceImages == null) {
|
|
||||||
glyphPaint.textSize = glyphSize
|
|
||||||
glyphPaint.color = GLYPH_COLOR
|
|
||||||
}
|
|
||||||
for (row in 0 until 8) {
|
for (row in 0 until 8) {
|
||||||
for (col in 0 until 8) {
|
for (col in 0 until 8) {
|
||||||
val displayRank = if (flipped) row else 7 - row
|
val displayRank = if (flipped) row else 7 - row
|
||||||
@@ -262,24 +250,15 @@ fun ChessBoardView(
|
|||||||
val pieceSq = displayRank * 8 + displayFile
|
val pieceSq = displayRank * 8 + displayFile
|
||||||
if (pieceSq == liftedSq) continue
|
if (pieceSq == liftedSq) continue
|
||||||
val piece = board.pieceAt(pieceSq) ?: continue
|
val piece = board.pieceAt(pieceSq) ?: continue
|
||||||
if (pieceImages != null) {
|
drawImage(
|
||||||
drawImage(
|
image = pieceImages[PieceImages.indexOf(piece.type, piece.color)],
|
||||||
image = pieceImages[PieceImages.indexOf(piece.type, piece.color)],
|
dstOffset = IntOffset(
|
||||||
dstOffset = IntOffset(
|
(col * cell + inset).roundToInt(),
|
||||||
(col * cell + inset).roundToInt(),
|
(row * cell + inset).roundToInt()
|
||||||
(row * cell + inset).roundToInt()
|
),
|
||||||
),
|
dstSize = pieceDst,
|
||||||
dstSize = pieceDst,
|
filterQuality = FilterQuality.Medium
|
||||||
filterQuality = FilterQuality.Medium
|
)
|
||||||
)
|
|
||||||
} else {
|
|
||||||
drawContext.canvas.nativeCanvas.drawText(
|
|
||||||
piece.unicode(),
|
|
||||||
col * cell + cell / 2f,
|
|
||||||
row * cell + cell / 2f - glyphShift,
|
|
||||||
glyphPaint
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -306,25 +285,15 @@ fun ChessBoardView(
|
|||||||
topLeft = Offset(liftedAt.x - liftedSize * 0.36f, liftedAt.y + cell * 0.05f),
|
topLeft = Offset(liftedAt.x - liftedSize * 0.36f, liftedAt.y + cell * 0.05f),
|
||||||
size = Size(liftedSize * 0.72f, liftedSize * 0.28f)
|
size = Size(liftedSize * 0.72f, liftedSize * 0.28f)
|
||||||
)
|
)
|
||||||
if (pieceImages != null) {
|
drawImage(
|
||||||
drawImage(
|
image = pieceImages[PieceImages.indexOf(liftedPiece.type, liftedPiece.color)],
|
||||||
image = pieceImages[PieceImages.indexOf(liftedPiece.type, liftedPiece.color)],
|
dstOffset = IntOffset(
|
||||||
dstOffset = IntOffset(
|
(cx - liftedSize / 2f).roundToInt(),
|
||||||
(cx - liftedSize / 2f).roundToInt(),
|
(cy - liftedSize / 2f).roundToInt()
|
||||||
(cy - liftedSize / 2f).roundToInt()
|
),
|
||||||
),
|
dstSize = liftedDst,
|
||||||
dstSize = liftedDst,
|
filterQuality = FilterQuality.Medium
|
||||||
filterQuality = FilterQuality.Medium
|
)
|
||||||
)
|
|
||||||
} else {
|
|
||||||
glyphPaint.textSize = glyphSize * LIFT_SCALE
|
|
||||||
drawContext.canvas.nativeCanvas.drawText(
|
|
||||||
liftedPiece.unicode(),
|
|
||||||
cx,
|
|
||||||
cy - liftedGlyphShift,
|
|
||||||
glyphPaint
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -344,8 +313,6 @@ private fun squareAt(x: Float, y: Float, boardPx: Float, flipped: Boolean): Int
|
|||||||
return displayRank * 8 + displayFile
|
return displayRank * 8 + displayFile
|
||||||
}
|
}
|
||||||
|
|
||||||
private val GLYPH_COLOR = Color(0xFF1B1B1B).toArgb()
|
|
||||||
|
|
||||||
private val FILE_LABELS = Array(8) { ('a' + it).toString() }
|
private val FILE_LABELS = Array(8) { ('a' + it).toString() }
|
||||||
private val RANK_LABELS = Array(8) { (it + 1).toString() }
|
private val RANK_LABELS = Array(8) { (it + 1).toString() }
|
||||||
|
|
||||||
|
|||||||
@@ -53,6 +53,72 @@ import cc.skysparkle.matewave.ui.theme.GlassShape
|
|||||||
import cc.skysparkle.matewave.ui.theme.PanelBorder
|
import cc.skysparkle.matewave.ui.theme.PanelBorder
|
||||||
import cc.skysparkle.matewave.ui.theme.TabletMaxContentWidth
|
import cc.skysparkle.matewave.ui.theme.TabletMaxContentWidth
|
||||||
import cc.skysparkle.matewave.ui.theme.glass
|
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
|
||||||
|
|
||||||
|
/** 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
|
@Composable
|
||||||
fun GlassScaffold(
|
fun GlassScaffold(
|
||||||
@@ -64,38 +130,9 @@ fun GlassScaffold(
|
|||||||
titleContent: (@Composable RowScope.() -> Unit)? = null,
|
titleContent: (@Composable RowScope.() -> Unit)? = null,
|
||||||
content: @Composable ColumnScope.() -> Unit
|
content: @Composable ColumnScope.() -> Unit
|
||||||
) {
|
) {
|
||||||
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.TopCenter) {
|
Box(modifier = Modifier.fillMaxSize().horizontalSafePadding(), contentAlignment = Alignment.TopCenter) {
|
||||||
Column(modifier = Modifier.fillMaxSize().widthIn(max = TabletMaxContentWidth)) {
|
Column(modifier = Modifier.fillMaxSize().widthIn(max = TabletMaxContentWidth)) {
|
||||||
Row(
|
ScaffoldTopBar(title, onBack, actions, titleContent)
|
||||||
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()
|
|
||||||
}
|
|
||||||
|
|
||||||
val scrollState = rememberScrollState()
|
val scrollState = rememberScrollState()
|
||||||
|
|
||||||
@@ -120,6 +157,65 @@ fun GlassScaffold(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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)
|
||||||
|
.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 = Modifier
|
||||||
|
.weight(1f)
|
||||||
|
.fillMaxHeight()
|
||||||
|
.verticalScroll(rememberScrollState()),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(14.dp)
|
||||||
|
) {
|
||||||
|
above()
|
||||||
|
below()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
private fun Modifier.pressScale(interactionSource: MutableInteractionSource): Modifier {
|
private fun Modifier.pressScale(interactionSource: MutableInteractionSource): Modifier {
|
||||||
val pressed by interactionSource.collectIsPressedAsState()
|
val pressed by interactionSource.collectIsPressedAsState()
|
||||||
|
|||||||
@@ -40,6 +40,10 @@ import androidx.compose.foundation.Image
|
|||||||
import cc.skysparkle.matewave.R
|
import cc.skysparkle.matewave.R
|
||||||
import cc.skysparkle.matewave.settings.BoardAppearance
|
import cc.skysparkle.matewave.settings.BoardAppearance
|
||||||
import cc.skysparkle.matewave.settings.BoardTheme
|
import cc.skysparkle.matewave.settings.BoardTheme
|
||||||
|
import cc.skysparkle.matewave.settings.PieceSet
|
||||||
|
import cc.skysparkle.matewave.settings.PieceSetState
|
||||||
|
import cc.skysparkle.matewave.engine.PieceColor
|
||||||
|
import cc.skysparkle.matewave.engine.PieceType
|
||||||
import cc.skysparkle.matewave.ui.components.GlassCard
|
import cc.skysparkle.matewave.ui.components.GlassCard
|
||||||
import cc.skysparkle.matewave.ui.components.GlassScaffold
|
import cc.skysparkle.matewave.ui.components.GlassScaffold
|
||||||
import cc.skysparkle.matewave.ui.theme.PanelBorder
|
import cc.skysparkle.matewave.ui.theme.PanelBorder
|
||||||
@@ -51,7 +55,6 @@ fun AppearanceScreen(onBack: () -> Unit) {
|
|||||||
|
|
||||||
var theme by remember { mutableStateOf(appearance.theme) }
|
var theme by remember { mutableStateOf(appearance.theme) }
|
||||||
var coords by remember { mutableStateOf(appearance.showCoordinates) }
|
var coords by remember { mutableStateOf(appearance.showCoordinates) }
|
||||||
var images by remember { mutableStateOf(appearance.useImagePieces) }
|
|
||||||
var lastMove by remember { mutableStateOf(appearance.showLastMove) }
|
var lastMove by remember { mutableStateOf(appearance.showLastMove) }
|
||||||
var checkGlow by remember { mutableStateOf(appearance.showCheckHighlight) }
|
var checkGlow by remember { mutableStateOf(appearance.showCheckHighlight) }
|
||||||
var openingBar by remember { mutableStateOf(appearance.showOpening) }
|
var openingBar by remember { mutableStateOf(appearance.showOpening) }
|
||||||
@@ -81,7 +84,7 @@ fun AppearanceScreen(onBack: () -> Unit) {
|
|||||||
}
|
}
|
||||||
) {
|
) {
|
||||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||||
ThemePreview(candidate, showPieces = images)
|
ThemePreview(candidate)
|
||||||
Text(
|
Text(
|
||||||
stringResource(candidate.titleRes),
|
stringResource(candidate.titleRes),
|
||||||
color = ink,
|
color = ink,
|
||||||
@@ -97,6 +100,43 @@ fun AppearanceScreen(onBack: () -> Unit) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Text(
|
||||||
|
stringResource(R.string.appearance_pieces),
|
||||||
|
color = ink,
|
||||||
|
style = MaterialTheme.typography.titleMedium
|
||||||
|
)
|
||||||
|
|
||||||
|
PieceSet.entries.forEach { candidate ->
|
||||||
|
GlassCard(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(vertical = 4.dp)
|
||||||
|
.clickable {
|
||||||
|
PieceSetState.select(context, candidate)
|
||||||
|
// Decode the pictures now, so the next board opens without a pause.
|
||||||
|
val appContext = context.applicationContext
|
||||||
|
kotlin.concurrent.thread(isDaemon = true) {
|
||||||
|
runCatching { cc.skysparkle.matewave.ui.components.PieceImages.get(appContext, candidate) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
) {
|
||||||
|
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||||
|
PieceSetPreview(candidate, theme)
|
||||||
|
Text(
|
||||||
|
stringResource(candidate.titleRes),
|
||||||
|
color = ink,
|
||||||
|
style = MaterialTheme.typography.bodyLarge,
|
||||||
|
modifier = Modifier.weight(1f)
|
||||||
|
)
|
||||||
|
if (candidate == PieceSetState.current) {
|
||||||
|
cc.skysparkle.matewave.ui.components.AppIcon(
|
||||||
|
R.drawable.ic_check_box, size = 20.dp, tint = cc.skysparkle.matewave.ui.theme.ChessGreen
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
AppearanceToggle(
|
AppearanceToggle(
|
||||||
icon = R.drawable.ic_coordinates,
|
icon = R.drawable.ic_coordinates,
|
||||||
title = stringResource(R.string.appearance_coordinates),
|
title = stringResource(R.string.appearance_coordinates),
|
||||||
@@ -104,13 +144,6 @@ fun AppearanceScreen(onBack: () -> Unit) {
|
|||||||
checked = coords
|
checked = coords
|
||||||
) { coords = it; appearance.showCoordinates = it }
|
) { 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(
|
AppearanceToggle(
|
||||||
icon = R.drawable.ic_last_move,
|
icon = R.drawable.ic_last_move,
|
||||||
title = stringResource(R.string.appearance_last_move),
|
title = stringResource(R.string.appearance_last_move),
|
||||||
@@ -220,7 +253,8 @@ private fun StyleSwatch(
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
private fun ThemePreview(theme: BoardTheme, showPieces: Boolean) {
|
private fun ThemePreview(theme: BoardTheme) {
|
||||||
|
val set = PieceSetState.current
|
||||||
val shape = RoundedCornerShape(6.dp)
|
val shape = RoundedCornerShape(6.dp)
|
||||||
Column(modifier = Modifier.size(56.dp).clip(shape).border(1.dp, PanelBorder, shape)) {
|
Column(modifier = Modifier.size(56.dp).clip(shape).border(1.dp, PanelBorder, shape)) {
|
||||||
repeat(2) { row ->
|
repeat(2) { row ->
|
||||||
@@ -234,16 +268,16 @@ private fun ThemePreview(theme: BoardTheme, showPieces: Boolean) {
|
|||||||
.background(if (light) theme.light else theme.dark),
|
.background(if (light) theme.light else theme.dark),
|
||||||
contentAlignment = Alignment.Center
|
contentAlignment = Alignment.Center
|
||||||
) {
|
) {
|
||||||
if (showPieces && row == 0 && col == 0) {
|
if (row == 0 && col == 0) {
|
||||||
Image(
|
Image(
|
||||||
painter = painterResource(R.drawable.piece_white_king),
|
painter = painterResource(set.res(PieceType.KING, PieceColor.WHITE)),
|
||||||
contentDescription = null,
|
contentDescription = null,
|
||||||
modifier = Modifier.size(22.dp)
|
modifier = Modifier.size(22.dp)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
if (showPieces && row == 1 && col == 1) {
|
if (row == 1 && col == 1) {
|
||||||
Image(
|
Image(
|
||||||
painter = painterResource(R.drawable.piece_black_knight),
|
painter = painterResource(set.res(PieceType.KNIGHT, PieceColor.BLACK)),
|
||||||
contentDescription = null,
|
contentDescription = null,
|
||||||
modifier = Modifier.size(22.dp)
|
modifier = Modifier.size(22.dp)
|
||||||
)
|
)
|
||||||
@@ -255,6 +289,34 @@ private fun ThemePreview(theme: BoardTheme, showPieces: Boolean) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Four pieces of the set on squares of the chosen board. */
|
||||||
|
@Composable
|
||||||
|
private fun PieceSetPreview(set: PieceSet, theme: BoardTheme) {
|
||||||
|
val shape = RoundedCornerShape(6.dp)
|
||||||
|
val pieces = listOf(
|
||||||
|
PieceType.KING to PieceColor.WHITE,
|
||||||
|
PieceType.QUEEN to PieceColor.BLACK,
|
||||||
|
PieceType.KNIGHT to PieceColor.WHITE,
|
||||||
|
PieceType.PAWN to PieceColor.BLACK
|
||||||
|
)
|
||||||
|
Row(modifier = Modifier.clip(shape).border(1.dp, PanelBorder, shape)) {
|
||||||
|
pieces.forEachIndexed { i, (type, color) ->
|
||||||
|
Box(
|
||||||
|
modifier = Modifier
|
||||||
|
.size(36.dp)
|
||||||
|
.background(if (i % 2 == 0) theme.light else theme.dark),
|
||||||
|
contentAlignment = Alignment.Center
|
||||||
|
) {
|
||||||
|
Image(
|
||||||
|
painter = painterResource(set.res(type, color)),
|
||||||
|
contentDescription = null,
|
||||||
|
modifier = Modifier.size(32.dp)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
private fun AppearanceToggle(
|
private fun AppearanceToggle(
|
||||||
icon: Int,
|
icon: Int,
|
||||||
|
|||||||
@@ -77,14 +77,16 @@ private data class NearbyEntry(
|
|||||||
val elo: Int?,
|
val elo: Int?,
|
||||||
val type: TransportType,
|
val type: TransportType,
|
||||||
val address: String,
|
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
|
@Composable
|
||||||
fun ConnectionScreen(
|
fun ConnectionScreen(
|
||||||
presence: LocalPresence,
|
presence: LocalPresence,
|
||||||
onStartHost: (TimeControl) -> Unit,
|
onStartHost: (TimeControl) -> Unit,
|
||||||
onJoin: (TransportType, TimeControl, targetId: String) -> Unit,
|
onJoin: (TransportType, TimeControl, targetId: String, expectedUserId: String?) -> Unit,
|
||||||
onBack: () -> Unit
|
onBack: () -> Unit
|
||||||
) {
|
) {
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
@@ -146,7 +148,8 @@ fun ConnectionScreen(
|
|||||||
elo = peer.elo,
|
elo = peer.elo,
|
||||||
type = TransportType.LAN,
|
type = TransportType.LAN,
|
||||||
address = peer.address,
|
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() }
|
val lanFingerprints = peers.values.map { it.fingerprint }.filter { it.isNotEmpty() }
|
||||||
@@ -263,7 +266,7 @@ fun ConnectionScreen(
|
|||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.clip(RoundedCornerShape(50))
|
.clip(RoundedCornerShape(50))
|
||||||
.background(Lime)
|
.background(Lime)
|
||||||
.clickable { onJoin(entry.type, timeControl, entry.address) }
|
.clickable { onJoin(entry.type, timeControl, entry.address, entry.playerId) }
|
||||||
.padding(horizontal = 14.dp, vertical = 6.dp)
|
.padding(horizontal = 14.dp, vertical = 6.dp)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -102,7 +102,14 @@ fun GameScreen(viewModel: GameViewModel, onExit: () -> Unit) {
|
|||||||
else -> null
|
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 = "",
|
title = "",
|
||||||
onBack = requestExit,
|
onBack = requestExit,
|
||||||
actions = {
|
actions = {
|
||||||
@@ -112,32 +119,29 @@ fun GameScreen(viewModel: GameViewModel, onExit: () -> Unit) {
|
|||||||
},
|
},
|
||||||
titleContent = if (showOpening && opening != null) {
|
titleContent = if (showOpening && opening != null) {
|
||||||
{ OpeningTitle("${opening.eco} · ${opening.name}", bookStatus, inBook) }
|
{ 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 = remember(state.board) { ChessEngine.checkedKingSquare(state.board) }
|
|
||||||
|
|
||||||
PlayerRow(state, topColor, isMe = false, material = material, clock = viewModel.clockState)
|
|
||||||
|
|
||||||
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, clock = viewModel.clockState)
|
PlayerRow(state, bottomColor, isMe = true, material = material, clock = viewModel.clockState)
|
||||||
|
|
||||||
// The move ribbon: only moves here, the opening name lives in the top bar.
|
// The move ribbon: only moves here, the opening name lives in the top bar.
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import androidx.compose.foundation.layout.Row
|
|||||||
import androidx.compose.foundation.layout.Spacer
|
import androidx.compose.foundation.layout.Spacer
|
||||||
import androidx.compose.foundation.layout.fillMaxHeight
|
import androidx.compose.foundation.layout.fillMaxHeight
|
||||||
import androidx.compose.foundation.layout.fillMaxSize
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import cc.skysparkle.matewave.ui.components.horizontalSafePadding
|
||||||
import androidx.compose.foundation.layout.fillMaxWidth
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
import androidx.compose.foundation.layout.height
|
import androidx.compose.foundation.layout.height
|
||||||
import androidx.compose.foundation.layout.navigationBarsPadding
|
import androidx.compose.foundation.layout.navigationBarsPadding
|
||||||
@@ -50,6 +51,9 @@ 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 androidx.compose.ui.unit.sp
|
||||||
import cc.skysparkle.matewave.R
|
import cc.skysparkle.matewave.R
|
||||||
|
import cc.skysparkle.matewave.engine.PieceColor
|
||||||
|
import cc.skysparkle.matewave.engine.PieceType
|
||||||
|
import cc.skysparkle.matewave.settings.PieceSetState
|
||||||
import cc.skysparkle.matewave.stats.Stats
|
import cc.skysparkle.matewave.stats.Stats
|
||||||
import cc.skysparkle.matewave.ui.components.AppBottomBar
|
import cc.skysparkle.matewave.ui.components.AppBottomBar
|
||||||
import cc.skysparkle.matewave.ui.components.AppDialog
|
import cc.skysparkle.matewave.ui.components.AppDialog
|
||||||
@@ -98,7 +102,7 @@ fun MainMenuScreen(
|
|||||||
var showRatingGate by remember { mutableStateOf(false) }
|
var showRatingGate by remember { mutableStateOf(false) }
|
||||||
var showStats 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)) {
|
Column(modifier = Modifier.fillMaxSize().widthIn(max = TabletMaxContentWidth)) {
|
||||||
Row(
|
Row(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
@@ -258,7 +262,7 @@ private fun Hero() {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
Image(
|
Image(
|
||||||
painter = painterResource(R.drawable.piece_white_knight),
|
painter = painterResource(PieceSetState.current.res(PieceType.KNIGHT, PieceColor.WHITE)),
|
||||||
contentDescription = null,
|
contentDescription = null,
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.align(Alignment.CenterEnd)
|
.align(Alignment.CenterEnd)
|
||||||
@@ -279,7 +283,7 @@ private fun AiCard(subtitle: String, modifier: Modifier = Modifier, onClick: ()
|
|||||||
.clickable(onClick = onClick)
|
.clickable(onClick = onClick)
|
||||||
) {
|
) {
|
||||||
Image(
|
Image(
|
||||||
painter = painterResource(R.drawable.piece_black_king),
|
painter = painterResource(PieceSetState.current.res(PieceType.KING, PieceColor.BLACK)),
|
||||||
contentDescription = null,
|
contentDescription = null,
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.align(Alignment.TopEnd)
|
.align(Alignment.TopEnd)
|
||||||
|
|||||||
@@ -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))
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -43,45 +43,52 @@ fun OpeningTrainerScreen(viewModel: OpeningStudyViewModel, onBack: () -> Unit) {
|
|||||||
val sans = state.sans
|
val sans = state.sans
|
||||||
val opening = remember(sans) { OpeningBook.openingName(sans) }
|
val opening = remember(sans) { OpeningBook.openingName(sans) }
|
||||||
|
|
||||||
GlassScaffold(title = course.name, onBack = onBack) {
|
// Landscape: the board on the left, progress, moves and the task on the right
|
||||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
cc.skysparkle.matewave.ui.components.BoardScaffold(
|
||||||
Text(
|
title = course.name,
|
||||||
stringResource(
|
onBack = onBack,
|
||||||
when (state.mode) {
|
above = {
|
||||||
SessionMode.LEARN -> R.string.study_mode_learn
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
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(
|
Text(
|
||||||
stringResource(R.string.study_progress, minOf(state.answered + 1, asked), asked),
|
stringResource(
|
||||||
color = ink.copy(alpha = 0.7f),
|
when (state.mode) {
|
||||||
style = MaterialTheme.typography.bodySmall
|
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, 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) {
|
when (state.phase) {
|
||||||
TrainerPhase.YOUR_MOVE -> Text(
|
TrainerPhase.YOUR_MOVE -> Text(
|
||||||
stringResource(if (state.mode == SessionMode.LEARN) R.string.study_learn_prompt else R.string.study_recall_prompt),
|
stringResource(if (state.mode == SessionMode.LEARN) R.string.study_learn_prompt else R.string.study_recall_prompt),
|
||||||
|
|||||||
@@ -71,7 +71,8 @@ fun PuzzleSolveScreen(viewModel: GameViewModel, onBack: () -> Unit, onNextPuzzle
|
|||||||
}
|
}
|
||||||
val redSquare = if (state.puzzleFailedAttempt && state.puzzleAutoMoving) state.lastMove?.to else null
|
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),
|
title = puzzle?.let { stringResource(R.string.puzzle_title_rating, it.rating) } ?: stringResource(R.string.puzzle_title_fallback),
|
||||||
onBack = onBack,
|
onBack = onBack,
|
||||||
actions = {
|
actions = {
|
||||||
@@ -88,24 +89,25 @@ fun PuzzleSolveScreen(viewModel: GameViewModel, onBack: () -> Unit, onNextPuzzle
|
|||||||
.padding(horizontal = 6.dp, vertical = 2.dp)
|
.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 = remember(state.board) { ChessEngine.checkedKingSquare(state.board) },
|
|
||||||
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.
|
// The task, in the same format as the status in a game: a dot in the side's colour.
|
||||||
val (text, color) = when {
|
val (text, color) = when {
|
||||||
state.puzzleSolved -> stringResource(R.string.puzzle_solved) to ChessGreen
|
state.puzzleSolved -> stringResource(R.string.puzzle_solved) to ChessGreen
|
||||||
|
|||||||
@@ -57,7 +57,8 @@ fun SettingsScreen(
|
|||||||
onOpenPermissions: () -> Unit,
|
onOpenPermissions: () -> Unit,
|
||||||
onOpenAppearance: () -> Unit,
|
onOpenAppearance: () -> Unit,
|
||||||
onOpenLicenses: () -> Unit,
|
onOpenLicenses: () -> Unit,
|
||||||
onOpenShare: () -> Unit
|
onOpenShare: () -> Unit,
|
||||||
|
onOpenGuide: () -> Unit
|
||||||
) {
|
) {
|
||||||
var musicOn by remember { mutableStateOf(SoundManager.musicEnabled) }
|
var musicOn by remember { mutableStateOf(SoundManager.musicEnabled) }
|
||||||
var sfxOn by remember { mutableStateOf(SoundManager.sfxEnabled) }
|
var sfxOn by remember { mutableStateOf(SoundManager.sfxEnabled) }
|
||||||
@@ -170,6 +171,14 @@ fun SettingsScreen(
|
|||||||
onClick = { cc.skysparkle.matewave.settings.AppLinks.open(context, cc.skysparkle.matewave.settings.AppLinks.PRIVACY_POLICY) }
|
onClick = { cc.skysparkle.matewave.settings.AppLinks.open(context, cc.skysparkle.matewave.settings.AppLinks.PRIVACY_POLICY) }
|
||||||
)
|
)
|
||||||
ListDivider()
|
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(
|
ListRow(
|
||||||
title = stringResource(R.string.about_section),
|
title = stringResource(R.string.about_section),
|
||||||
icon = R.drawable.ic_info,
|
icon = R.drawable.ic_info,
|
||||||
@@ -178,6 +187,19 @@ fun SettingsScreen(
|
|||||||
onClick = { showAbout = true }
|
onClick = { showAbout = true }
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Donation plaque, last on the screen so it never gets in the way. A heart rather than the
|
||||||
|
// app icon: the logo already appears in the About dialog
|
||||||
|
ListGroup {
|
||||||
|
ListRow(
|
||||||
|
title = stringResource(R.string.support_title),
|
||||||
|
subtitle = stringResource(R.string.support_text),
|
||||||
|
icon = R.drawable.ic_heart,
|
||||||
|
iconTint = DonateRed,
|
||||||
|
chevron = true,
|
||||||
|
onClick = { cc.skysparkle.matewave.settings.AppLinks.open(context, cc.skysparkle.matewave.settings.AppLinks.DONATE) }
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (showAbout) {
|
if (showAbout) {
|
||||||
@@ -242,6 +264,8 @@ fun SettingsScreen(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private val DonateRed = Color(0xFFFF6B8A)
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
private fun AboutRow(iconRes: Int, title: String, subtitle: String, onClick: () -> Unit) {
|
private fun AboutRow(iconRes: Int, title: String, subtitle: String, onClick: () -> Unit) {
|
||||||
val rowShape = RoundedCornerShape(12.dp)
|
val rowShape = RoundedCornerShape(12.dp)
|
||||||
|
|||||||
@@ -88,35 +88,40 @@ fun SpectatorScreen(target: SpectateTarget, onBackToFriends: () -> Unit) {
|
|||||||
val view = state.view
|
val view = state.view
|
||||||
var resultHidden by remember(view?.gameId, state.phase) { mutableStateOf(false) }
|
var resultHidden by remember(view?.gameId, state.phase) { mutableStateOf(false) }
|
||||||
|
|
||||||
GlassScaffold(
|
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),
|
title = stringResource(R.string.spectate_title),
|
||||||
onBack = backToFriends,
|
onBack = backToFriends,
|
||||||
actions = { if (view != null) SpectatorBadge(state.spectators, state.max) }
|
actions = { if (view != null) SpectatorBadge(state.spectators, state.max) },
|
||||||
) {
|
above = {
|
||||||
if (state.phase == SpectatePhase.CONNECTING) {
|
if (state.phase == SpectatePhase.CONNECTING) {
|
||||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
CircularProgressIndicator(color = ink, strokeWidth = 2.dp, modifier = Modifier.size(16.dp))
|
CircularProgressIndicator(color = ink, strokeWidth = 2.dp, modifier = Modifier.size(16.dp))
|
||||||
Text(stringResource(R.string.spectate_joining), color = ink, style = MaterialTheme.typography.bodyMedium)
|
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) return@GlassScaffold
|
) {
|
||||||
|
if (view == null || material == null) return@BoardScaffold
|
||||||
val bottom = if (state.flipped) PieceColor.BLACK else PieceColor.WHITE
|
|
||||||
val material = remember(view.board) { Material.balance(view.board) }
|
|
||||||
val checkSquare = remember(view.board) { ChessEngine.checkedKingSquare(view.board) }
|
|
||||||
|
|
||||||
SpectatorPlayerRow(view, bottom.opposite(), state, material)
|
|
||||||
ChessBoardView(
|
|
||||||
board = view.board,
|
|
||||||
selectedSquare = null,
|
|
||||||
legalTargets = emptyList(),
|
|
||||||
kingInCheckSquare = checkSquare,
|
|
||||||
flipped = state.flipped,
|
|
||||||
onSquareClick = {},
|
|
||||||
lastMove = view.lastMove,
|
|
||||||
interactionEnabled = false,
|
|
||||||
highlightLastMove = true
|
|
||||||
)
|
|
||||||
SpectatorPlayerRow(view, bottom, state, material)
|
SpectatorPlayerRow(view, bottom, state, material)
|
||||||
|
|
||||||
val bookPlies = remember(view.moveSans) { OpeningBook.bookDepth(view.moveSans) }
|
val bookPlies = remember(view.moveSans) { OpeningBook.bookDepth(view.moveSans) }
|
||||||
|
|||||||
@@ -44,6 +44,10 @@ import cc.skysparkle.matewave.R
|
|||||||
import cc.skysparkle.matewave.ai.AiDifficulty
|
import cc.skysparkle.matewave.ai.AiDifficulty
|
||||||
import cc.skysparkle.matewave.clock.TimeControl
|
import cc.skysparkle.matewave.clock.TimeControl
|
||||||
import cc.skysparkle.matewave.engine.PieceColor
|
import cc.skysparkle.matewave.engine.PieceColor
|
||||||
|
import cc.skysparkle.matewave.engine.PieceType
|
||||||
|
import cc.skysparkle.matewave.settings.PieceSetState
|
||||||
|
import androidx.compose.ui.draw.drawWithContent
|
||||||
|
import androidx.compose.ui.graphics.drawscope.clipRect
|
||||||
import cc.skysparkle.matewave.ui.components.GlassButton
|
import cc.skysparkle.matewave.ui.components.GlassButton
|
||||||
import cc.skysparkle.matewave.ui.components.GlassScaffold
|
import cc.skysparkle.matewave.ui.components.GlassScaffold
|
||||||
|
|
||||||
@@ -126,9 +130,9 @@ fun VsAiSetupScreen(
|
|||||||
|
|
||||||
SectionCaption(stringResource(R.string.your_color))
|
SectionCaption(stringResource(R.string.your_color))
|
||||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
ColorChip(R.drawable.piece_white_king, stringResource(R.string.color_white), color == PieceColor.WHITE) { color = PieceColor.WHITE }
|
ColorChip(listOf(PieceColor.WHITE), 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(listOf(PieceColor.BLACK), 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 }
|
ColorChip(listOf(PieceColor.WHITE, PieceColor.BLACK), stringResource(R.string.color_random), color == null) { color = null }
|
||||||
}
|
}
|
||||||
|
|
||||||
SectionCaption(stringResource(R.string.time_control_label))
|
SectionCaption(stringResource(R.string.time_control_label))
|
||||||
@@ -144,7 +148,7 @@ private fun aiDescription(d: AiDifficulty): Int = when (d) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
private fun ColorChip(iconRes: Int, text: String, selected: Boolean, onClick: () -> Unit) {
|
private fun ColorChip(kings: List<PieceColor>, text: String, selected: Boolean, onClick: () -> Unit) {
|
||||||
val shape = RoundedCornerShape(50)
|
val shape = RoundedCornerShape(50)
|
||||||
Row(
|
Row(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
@@ -164,12 +168,26 @@ private fun ColorChip(iconRes: Int, text: String, selected: Boolean, onClick: ()
|
|||||||
.background(Color(0xFF9AA0A8)),
|
.background(Color(0xFF9AA0A8)),
|
||||||
contentAlignment = Alignment.Center
|
contentAlignment = Alignment.Center
|
||||||
) {
|
) {
|
||||||
Image(
|
val set = PieceSetState.current
|
||||||
painter = painterResource(iconRes),
|
kings.forEachIndexed { i, king ->
|
||||||
contentDescription = null,
|
Image(
|
||||||
modifier = Modifier.size(20.dp)
|
painter = painterResource(set.res(PieceType.KING, king)),
|
||||||
)
|
contentDescription = null,
|
||||||
|
modifier = Modifier
|
||||||
|
.size(20.dp)
|
||||||
|
.then(if (kings.size > 1) Modifier.halfOf(left = i == 0) else Modifier)
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Text(text, color = ink, style = MaterialTheme.typography.bodySmall)
|
Text(text, color = ink, style = MaterialTheme.typography.bodySmall)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Draws only the left or the right half, for the half-white, half-black king. */
|
||||||
|
private fun Modifier.halfOf(left: Boolean): Modifier = drawWithContent {
|
||||||
|
val mid = size.width / 2f
|
||||||
|
clipRect(left = if (left) 0f else mid, right = if (left) mid else size.width) {
|
||||||
|
this@drawWithContent.drawContent()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -15,6 +15,8 @@ val UiCornerRadius = 22.dp
|
|||||||
val GlassShape: Shape = RoundedCornerShape(UiCornerRadius)
|
val GlassShape: Shape = RoundedCornerShape(UiCornerRadius)
|
||||||
|
|
||||||
val TabletMaxContentWidth = 600.dp
|
val TabletMaxContentWidth = 600.dp
|
||||||
|
/** Landscape board screens: board and side panel together. */
|
||||||
|
val LandscapeMaxContentWidth = 1200.dp
|
||||||
|
|
||||||
fun Modifier.glass(): Modifier = this
|
fun Modifier.glass(): Modifier = this
|
||||||
.clip(GlassShape)
|
.clip(GlassShape)
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ import cc.skysparkle.matewave.network.ConnectionTransport
|
|||||||
import cc.skysparkle.matewave.network.GameMessage
|
import cc.skysparkle.matewave.network.GameMessage
|
||||||
import cc.skysparkle.matewave.network.NetworkLog
|
import cc.skysparkle.matewave.network.NetworkLog
|
||||||
import cc.skysparkle.matewave.network.NetworkMetrics
|
import cc.skysparkle.matewave.network.NetworkMetrics
|
||||||
|
import cc.skysparkle.matewave.network.PeerLimits
|
||||||
import cc.skysparkle.matewave.network.TransportType
|
import cc.skysparkle.matewave.network.TransportType
|
||||||
import cc.skysparkle.matewave.puzzles.Puzzle
|
import cc.skysparkle.matewave.puzzles.Puzzle
|
||||||
import cc.skysparkle.matewave.security.DeviceKeys
|
import cc.skysparkle.matewave.security.DeviceKeys
|
||||||
@@ -43,6 +44,7 @@ import cc.skysparkle.matewave.spectate.SpectatorResult
|
|||||||
import cc.skysparkle.matewave.spectate.SpectatorResults
|
import cc.skysparkle.matewave.spectate.SpectatorResults
|
||||||
import cc.skysparkle.matewave.spectate.SpectatorSnapshot
|
import cc.skysparkle.matewave.spectate.SpectatorSnapshot
|
||||||
import cc.skysparkle.matewave.stats.Stats
|
import cc.skysparkle.matewave.stats.Stats
|
||||||
|
import cc.skysparkle.matewave.ui.components.isAcceptableIncomingImage
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.Job
|
import kotlinx.coroutines.Job
|
||||||
import kotlinx.coroutines.delay
|
import kotlinx.coroutines.delay
|
||||||
@@ -185,8 +187,10 @@ class GameViewModel : ViewModel() {
|
|||||||
private var sessionGeneration = 0
|
private var sessionGeneration = 0
|
||||||
private var networkGameId: String = ""
|
private var networkGameId: String = ""
|
||||||
private var pendingOpponentImages: Pair<String?, String?>? = null
|
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 currentPly: Int = 0
|
||||||
private var lastOpponentRemaining: Long = Long.MAX_VALUE
|
|
||||||
|
|
||||||
// Spectating: the host serves spectators, both players announce the game's tag.
|
// Spectating: the host serves spectators, both players announce the game's tag.
|
||||||
private var spectators: SpectatorBroadcaster? = null
|
private var spectators: SpectatorBroadcaster? = null
|
||||||
@@ -711,7 +715,8 @@ class GameViewModel : ViewModel() {
|
|||||||
myColor: PieceColor,
|
myColor: PieceColor,
|
||||||
timeControl: TimeControl,
|
timeControl: TimeControl,
|
||||||
isHost: Boolean,
|
isHost: Boolean,
|
||||||
targetId: String? = null
|
targetId: String? = null,
|
||||||
|
expectedUserId: String? = null
|
||||||
) {
|
) {
|
||||||
pendingLeave?.let { (job, oldTransport) ->
|
pendingLeave?.let { (job, oldTransport) ->
|
||||||
job.cancel()
|
job.cancel()
|
||||||
@@ -730,6 +735,7 @@ class GameViewModel : ViewModel() {
|
|||||||
this.transport = transport
|
this.transport = transport
|
||||||
lastNetworkTimeControl = timeControl
|
lastNetworkTimeControl = timeControl
|
||||||
isNetworkHost = isHost
|
isNetworkHost = isHost
|
||||||
|
expectedOpponentUserId = expectedUserId?.takeIf { it.isNotBlank() }
|
||||||
|
|
||||||
ephemeralKeys = DeviceKeys.generateEphemeral()
|
ephemeralKeys = DeviceKeys.generateEphemeral()
|
||||||
|
|
||||||
@@ -739,7 +745,6 @@ class GameViewModel : ViewModel() {
|
|||||||
opponentFlagJob = null
|
opponentFlagJob = null
|
||||||
networkGameId = if (isHost) java.util.UUID.randomUUID().toString() else ""
|
networkGameId = if (isHost) java.util.UUID.randomUUID().toString() else ""
|
||||||
currentPly = 0
|
currentPly = 0
|
||||||
lastOpponentRemaining = Long.MAX_VALUE
|
|
||||||
|
|
||||||
_clockState.value = null
|
_clockState.value = null
|
||||||
_uiState.value = GameUiState(
|
_uiState.value = GameUiState(
|
||||||
@@ -848,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 =
|
private fun belongsToCurrentGame(gameId: String): Boolean =
|
||||||
gameId.isEmpty() || networkGameId.isEmpty() || gameId == networkGameId
|
gameId.isEmpty() || networkGameId.isEmpty() || gameId == networkGameId
|
||||||
|
|
||||||
@@ -901,9 +913,14 @@ class GameViewModel : ViewModel() {
|
|||||||
NetworkLog.log("GAME", "Oversized chat message rejected")
|
NetworkLog.log("GAME", "Oversized chat message rejected")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if (msg.imageBase64 != null && !isAcceptableIncomingImage(msg.imageBase64)) {
|
||||||
|
NetworkLog.log("GAME", "Unreadable or oversized chat image rejected")
|
||||||
|
return
|
||||||
|
}
|
||||||
val state = _uiState.value
|
val state = _uiState.value
|
||||||
_uiState.value = state.copy(
|
_uiState.value = state.copy(
|
||||||
chatMessages = state.chatMessages + ChatEntry(msg.text, msg.imageBase64, fromMe = false),
|
chatMessages = (state.chatMessages + ChatEntry(msg.text, msg.imageBase64, fromMe = false))
|
||||||
|
.takeLast(MAX_CHAT_ENTRIES),
|
||||||
unreadChatCount = state.unreadChatCount + 1
|
unreadChatCount = state.unreadChatCount + 1
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -976,8 +993,8 @@ class GameViewModel : ViewModel() {
|
|||||||
}
|
}
|
||||||
is GameMessage.ProfileImagesMsg -> {
|
is GameMessage.ProfileImagesMsg -> {
|
||||||
if (!belongsToCurrentGame(msg.gameId)) return
|
if (!belongsToCurrentGame(msg.gameId)) return
|
||||||
val avatar = msg.avatarBase64?.takeIf { it.length <= MAX_CHAT_IMAGE_CHARS }
|
val avatar = msg.avatarBase64?.let(::acceptedIncomingImage)
|
||||||
val background = msg.backgroundBase64?.takeIf { it.length <= MAX_CHAT_IMAGE_CHARS }
|
val background = msg.backgroundBase64?.let(::acceptedIncomingImage)
|
||||||
if (avatar == null && background == null) return
|
if (avatar == null && background == null) return
|
||||||
val current = _uiState.value.opponentProfile
|
val current = _uiState.value.opponentProfile
|
||||||
if (current == null) {
|
if (current == null) {
|
||||||
@@ -1051,17 +1068,17 @@ class GameViewModel : ViewModel() {
|
|||||||
|
|
||||||
val limit = lastNetworkTimeControl?.let { it.initialSeconds * 1000L + 60_000L }
|
val limit = lastNetworkTimeControl?.let { it.initialSeconds * 1000L + 60_000L }
|
||||||
val increment = lastNetworkTimeControl?.let { it.incrementSeconds * 1000L } ?: 0L
|
val increment = lastNetworkTimeControl?.let { it.incrementSeconds * 1000L } ?: 0L
|
||||||
val allowedMax = if (lastOpponentRemaining == Long.MAX_VALUE) {
|
// Our own clock has been running the opponent's time while they thought, so their claim
|
||||||
limit ?: Long.MAX_VALUE
|
// may not exceed it by more than the increment and network slack.
|
||||||
} else {
|
val allowedMax = clock?.remainingMillis(opponentColor)
|
||||||
lastOpponentRemaining + increment + CLOCK_TOLERANCE_MS
|
?.let { PeerLimits.maxOpponentClockAfterMove(it, increment, CLOCK_TOLERANCE_MS) }
|
||||||
}
|
?: limit ?: Long.MAX_VALUE
|
||||||
if (msg.remainingMillisSelf >= 0 &&
|
if (msg.remainingMillisSelf >= 0 &&
|
||||||
(limit == null || msg.remainingMillisSelf <= limit) &&
|
(limit == null || msg.remainingMillisSelf <= limit) &&
|
||||||
msg.remainingMillisSelf <= allowedMax
|
msg.remainingMillisSelf <= allowedMax
|
||||||
) {
|
) {
|
||||||
lastOpponentRemaining = msg.remainingMillisSelf
|
// The reported time already includes the increment; makeMove below adds it again.
|
||||||
clock?.applyRemoteTime(opponentColor, msg.remainingMillisSelf)
|
clock?.applyRemoteTime(opponentColor, (msg.remainingMillisSelf - increment).coerceAtLeast(0))
|
||||||
} else if (msg.remainingMillisSelf > 0) {
|
} else if (msg.remainingMillisSelf > 0) {
|
||||||
NetworkLog.log("GAME", "Invalid clock value from opponent rejected: ${msg.remainingMillisSelf}")
|
NetworkLog.log("GAME", "Invalid clock value from opponent rejected: ${msg.remainingMillisSelf}")
|
||||||
}
|
}
|
||||||
@@ -1077,6 +1094,12 @@ class GameViewModel : ViewModel() {
|
|||||||
NetworkLog.log("GAME", "Repeated profile in current session ignored")
|
NetworkLog.log("GAME", "Repeated profile in current session ignored")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
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
|
val peers = knownPeers
|
||||||
if (peers == null) {
|
if (peers == null) {
|
||||||
NetworkLog.log("GAME", "Key store not ready, profile rejected")
|
NetworkLog.log("GAME", "Key store not ready, profile rejected")
|
||||||
@@ -1125,7 +1148,11 @@ class GameViewModel : ViewModel() {
|
|||||||
}
|
}
|
||||||
markReadyIfPossible()
|
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
|
val pending = pendingOpponentImages
|
||||||
pendingOpponentImages = null
|
pendingOpponentImages = null
|
||||||
@@ -1133,8 +1160,8 @@ class GameViewModel : ViewModel() {
|
|||||||
userId = msg.userId,
|
userId = msg.userId,
|
||||||
name = msg.name,
|
name = msg.name,
|
||||||
elo = msg.elo,
|
elo = msg.elo,
|
||||||
avatarBase64 = msg.avatarBase64 ?: pending?.first,
|
avatarBase64 = msg.avatarBase64?.let(::acceptedIncomingImage) ?: pending?.first,
|
||||||
backgroundBase64 = msg.backgroundBase64 ?: pending?.second
|
backgroundBase64 = msg.backgroundBase64?.let(::acceptedIncomingImage) ?: pending?.second
|
||||||
)
|
)
|
||||||
_uiState.value = _uiState.value.copy(
|
_uiState.value = _uiState.value.copy(
|
||||||
opponentProfile = Profile(
|
opponentProfile = Profile(
|
||||||
@@ -1240,7 +1267,6 @@ class GameViewModel : ViewModel() {
|
|||||||
opponentFlagJob?.cancel()
|
opponentFlagJob?.cancel()
|
||||||
opponentFlagJob = null
|
opponentFlagJob = null
|
||||||
currentPly = 0
|
currentPly = 0
|
||||||
lastOpponentRemaining = Long.MAX_VALUE
|
|
||||||
val start = Board.startPosition()
|
val start = Board.startPosition()
|
||||||
resetHistory(start)
|
resetHistory(start)
|
||||||
|
|
||||||
@@ -1349,7 +1375,8 @@ class GameViewModel : ViewModel() {
|
|||||||
val trimmed = text.trim().take(MAX_CHAT_TEXT_CHARS)
|
val trimmed = text.trim().take(MAX_CHAT_TEXT_CHARS)
|
||||||
if (!sendGameMessage(GameMessage.ChatMsg(text = trimmed, gameId = networkGameId))) return
|
if (!sendGameMessage(GameMessage.ChatMsg(text = trimmed, gameId = networkGameId))) return
|
||||||
_uiState.value = _uiState.value.copy(
|
_uiState.value = _uiState.value.copy(
|
||||||
chatMessages = _uiState.value.chatMessages + ChatEntry(trimmed, null, fromMe = true)
|
chatMessages = (_uiState.value.chatMessages + ChatEntry(trimmed, null, fromMe = true))
|
||||||
|
.takeLast(MAX_CHAT_ENTRIES)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1362,7 +1389,8 @@ class GameViewModel : ViewModel() {
|
|||||||
}
|
}
|
||||||
if (!sendGameMessage(GameMessage.ChatMsg(imageBase64 = base64, gameId = networkGameId))) return
|
if (!sendGameMessage(GameMessage.ChatMsg(imageBase64 = base64, gameId = networkGameId))) return
|
||||||
_uiState.value = _uiState.value.copy(
|
_uiState.value = _uiState.value.copy(
|
||||||
chatMessages = _uiState.value.chatMessages + ChatEntry(null, base64, fromMe = true)
|
chatMessages = (_uiState.value.chatMessages + ChatEntry(null, base64, fromMe = true))
|
||||||
|
.takeLast(MAX_CHAT_ENTRIES)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1400,7 +1428,10 @@ class GameViewModel : ViewModel() {
|
|||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
var serving = false
|
var serving = false
|
||||||
try {
|
try {
|
||||||
val port = withContext(Dispatchers.IO) { runCatching { hub.start() }.getOrNull() }
|
// 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")
|
if (port == null) NetworkLog.log("SPECTATE", "Could not open the spectator port")
|
||||||
// The game may have ended while the port was opening.
|
// The game may have ended while the port was opening.
|
||||||
if (port == null || generation != sessionGeneration || !spectatingDecided || spectateTag.isEmpty()) return@launch
|
if (port == null || generation != sessionGeneration || !spectatingDecided || spectateTag.isEmpty()) return@launch
|
||||||
@@ -1589,6 +1620,7 @@ class GameViewModel : ViewModel() {
|
|||||||
const val MAX_CHAT_TEXT_CHARS = 8_000
|
const val MAX_CHAT_TEXT_CHARS = 8_000
|
||||||
const val MAX_CHAT_IMAGE_CHARS = 400_000
|
const val MAX_CHAT_IMAGE_CHARS = 400_000
|
||||||
const val CLOCK_TOLERANCE_MS = 2_000L
|
const val CLOCK_TOLERANCE_MS = 2_000L
|
||||||
|
const val MAX_CHAT_ENTRIES = 200
|
||||||
const val HANDSHAKE_TIMEOUT_MS = 20_000L
|
const val HANDSHAKE_TIMEOUT_MS = 20_000L
|
||||||
const val OPPONENT_FLAG_GRACE_MS = 4_000L
|
const val OPPONENT_FLAG_GRACE_MS = 4_000L
|
||||||
const val LEAVE_FLUSH_MS = 700L
|
const val LEAVE_FLUSH_MS = 700L
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 5.4 KiB |
|
Before Width: | Height: | Size: 3.8 KiB After Width: | Height: | Size: 3.8 KiB |
|
Before Width: | Height: | Size: 3.1 KiB After Width: | Height: | Size: 3.1 KiB |
|
Before Width: | Height: | Size: 3.6 KiB After Width: | Height: | Size: 3.6 KiB |
|
Before Width: | Height: | Size: 2.3 KiB After Width: | Height: | Size: 2.3 KiB |
|
Before Width: | Height: | Size: 3.6 KiB After Width: | Height: | Size: 3.6 KiB |
|
Before Width: | Height: | Size: 1.9 KiB After Width: | Height: | Size: 1.9 KiB |
|
Before Width: | Height: | Size: 3.8 KiB After Width: | Height: | Size: 3.8 KiB |
|
Before Width: | Height: | Size: 3.0 KiB After Width: | Height: | Size: 3.0 KiB |
|
Before Width: | Height: | Size: 3.6 KiB After Width: | Height: | Size: 3.6 KiB |
|
Before Width: | Height: | Size: 2.3 KiB After Width: | Height: | Size: 2.3 KiB |
|
Before Width: | Height: | Size: 3.6 KiB After Width: | Height: | Size: 3.6 KiB |
|
Before Width: | Height: | Size: 1.9 KiB After Width: | Height: | Size: 1.9 KiB |
|
After Width: | Height: | Size: 6.5 KiB |
|
After Width: | Height: | Size: 6.4 KiB |
|
After Width: | Height: | Size: 6.3 KiB |
|
After Width: | Height: | Size: 5.5 KiB |
|
After Width: | Height: | Size: 6.7 KiB |
|
After Width: | Height: | Size: 5.4 KiB |
|
After Width: | Height: | Size: 6.7 KiB |
|
After Width: | Height: | Size: 7.0 KiB |
|
After Width: | Height: | Size: 6.6 KiB |
|
After Width: | Height: | Size: 5.6 KiB |
|
After Width: | Height: | Size: 7.1 KiB |
|
After Width: | Height: | Size: 5.6 KiB |
|
After Width: | Height: | Size: 7.9 KiB |
|
After Width: | Height: | Size: 7.8 KiB |
|
After Width: | Height: | Size: 9.2 KiB |
|
After Width: | Height: | Size: 6.7 KiB |
|
After Width: | Height: | Size: 8.3 KiB |
|
After Width: | Height: | Size: 7.1 KiB |
|
After Width: | Height: | Size: 8.2 KiB |
|
After Width: | Height: | Size: 8.1 KiB |
|
After Width: | Height: | Size: 9.9 KiB |
|
After Width: | Height: | Size: 7.2 KiB |
|
After Width: | Height: | Size: 8.9 KiB |
|
After Width: | Height: | Size: 7.5 KiB |
|
After Width: | Height: | Size: 7.7 KiB |
|
After Width: | Height: | Size: 8.0 KiB |
|
After Width: | Height: | Size: 9.3 KiB |
|
After Width: | Height: | Size: 7.0 KiB |
|
After Width: | Height: | Size: 8.8 KiB |
|
After Width: | Height: | Size: 8.5 KiB |
|
After Width: | Height: | Size: 8.6 KiB |
|
After Width: | Height: | Size: 9.1 KiB |
|
After Width: | Height: | Size: 10 KiB |
|
After Width: | Height: | Size: 7.3 KiB |
|
After Width: | Height: | Size: 9.5 KiB |
|
After Width: | Height: | Size: 8.5 KiB |
|
After Width: | Height: | Size: 8.4 KiB |
|
After Width: | Height: | Size: 8.5 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 6.9 KiB |
|
After Width: | Height: | Size: 8.4 KiB |
|
After Width: | Height: | Size: 7.3 KiB |
|
After Width: | Height: | Size: 8.9 KiB |
|
After Width: | Height: | Size: 9.5 KiB |
|
After Width: | Height: | Size: 11 KiB |