mirror of
https://github.com/kalarina-bit/Matewave.git
synced 2026-11-22 16:16:10 +00:00
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ef5af5c395 | ||
|
|
0d0daf8a45 | ||
|
|
6ed42e0bf3 | ||
|
|
cac575ed26 | ||
|
|
77c438ff66 |
+15
-16
@@ -1,7 +1,6 @@
|
||||
plugins {
|
||||
id("com.android.application")
|
||||
|
||||
id("org.jetbrains.kotlin.plugin.compose")
|
||||
alias(libs.plugins.android.application)
|
||||
alias(libs.plugins.kotlin.compose)
|
||||
}
|
||||
|
||||
android {
|
||||
@@ -13,8 +12,8 @@ android {
|
||||
applicationId = "cc.skysparkle.matewave"
|
||||
minSdk = 26
|
||||
targetSdk = 36
|
||||
versionCode = 9
|
||||
versionName = "1.0.49"
|
||||
versionCode = 11
|
||||
versionName = "1.0.51"
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
@@ -86,20 +85,20 @@ androidComponents {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(platform("androidx.compose:compose-bom:2026.09.00"))
|
||||
implementation("androidx.compose.material3:material3")
|
||||
implementation("androidx.compose.ui:ui")
|
||||
implementation("androidx.activity:activity-compose:1.13.0")
|
||||
implementation(platform(libs.androidx.compose.bom))
|
||||
implementation(libs.androidx.compose.material3)
|
||||
implementation(libs.androidx.compose.ui)
|
||||
implementation(libs.androidx.activity.compose)
|
||||
|
||||
implementation("androidx.core:core-ktx:1.18.0")
|
||||
implementation("androidx.navigation:navigation-compose:2.9.7")
|
||||
implementation(libs.androidx.core.ktx)
|
||||
implementation(libs.androidx.navigation.compose)
|
||||
|
||||
implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.11.0")
|
||||
implementation(libs.androidx.lifecycle.viewmodel.compose)
|
||||
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.11.0")
|
||||
implementation(libs.kotlinx.coroutines.android)
|
||||
|
||||
implementation("com.google.zxing:core:3.5.4")
|
||||
implementation(libs.zxing.core)
|
||||
|
||||
testImplementation("junit:junit:4.13.2")
|
||||
testImplementation("org.json:json:20240303")
|
||||
testImplementation(libs.junit)
|
||||
testImplementation(libs.org.json)
|
||||
}
|
||||
|
||||
Vendored
+6
@@ -2,3 +2,9 @@
|
||||
# reflection. Only keep line numbers so release crash reports stay readable.
|
||||
-keepattributes SourceFile,LineNumberTable
|
||||
-renamesourcefileattribute SourceFile
|
||||
|
||||
# Debug and verbose logging (NetworkLog included) is stripped from release builds.
|
||||
-assumenosideeffects class android.util.Log {
|
||||
public static int d(...);
|
||||
public static int v(...);
|
||||
}
|
||||
|
||||
@@ -36,6 +36,7 @@
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:roundIcon="@mipmap/ic_launcher_round"
|
||||
android:label="@string/app_title"
|
||||
android:localeConfig="@xml/locales_config"
|
||||
android:networkSecurityConfig="@xml/network_security_config"
|
||||
android:theme="@android:style/Theme.Material.NoActionBar"
|
||||
android:supportsRtl="true">
|
||||
|
||||
@@ -73,6 +73,7 @@ class MainActivity : ComponentActivity() {
|
||||
runCatching { cc.skysparkle.matewave.puzzles.PuzzleRepository.load(appContext) }
|
||||
}
|
||||
|
||||
cc.skysparkle.matewave.ui.theme.AppThemeState.load(this)
|
||||
setContent {
|
||||
MatewaveTheme {
|
||||
androidx.compose.foundation.layout.Box(
|
||||
@@ -332,9 +333,12 @@ private fun AppNavHost() {
|
||||
viewModel.startVsPlayerNetwork(transport, PieceColor.WHITE, timeControl, isHost = true)
|
||||
navController.navigate("game")
|
||||
},
|
||||
onJoin = { type, timeControl, targetId ->
|
||||
onJoin = { type, timeControl, targetId, expectedUserId ->
|
||||
val transport = if (type == TransportType.BLUETOOTH) bleTransport else lanTransport
|
||||
viewModel.startVsPlayerNetwork(transport, PieceColor.BLACK, timeControl, isHost = false, targetId = targetId)
|
||||
viewModel.startVsPlayerNetwork(
|
||||
transport, PieceColor.BLACK, timeControl, isHost = false,
|
||||
targetId = targetId, expectedUserId = expectedUserId
|
||||
)
|
||||
navController.navigate("game")
|
||||
},
|
||||
onBack = { navController.popBackStack() }
|
||||
|
||||
@@ -98,6 +98,12 @@ class GameClock(private val timeControl: TimeControl, private val scope: Corouti
|
||||
publish()
|
||||
}
|
||||
|
||||
/** Time left for [side] right now, including the part of the current second already used. */
|
||||
fun remainingMillis(side: PieceColor): Long {
|
||||
account()
|
||||
return if (side == PieceColor.WHITE) whiteLeft else blackLeft
|
||||
}
|
||||
|
||||
fun restore(whiteMillis: Long, blackMillis: Long) {
|
||||
if (unlimited) return
|
||||
account()
|
||||
|
||||
@@ -2,8 +2,12 @@ package cc.skysparkle.matewave.data
|
||||
|
||||
import cc.skysparkle.matewave.ai.AiDifficulty
|
||||
import android.content.Context
|
||||
import cc.skysparkle.matewave.network.PeerLimits
|
||||
import cc.skysparkle.matewave.security.toHex
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.security.MessageDigest
|
||||
import kotlin.math.pow
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
@@ -111,6 +115,7 @@ object FriendsStore {
|
||||
private const val PREFS = "chess_friends_prefs"
|
||||
private const val KEY_LIST = "friends_json"
|
||||
private const val MAX_FRIENDS = 30
|
||||
private const val IMAGE_DIR = "friend_images"
|
||||
|
||||
private var appContext: Context? = null
|
||||
|
||||
@@ -125,6 +130,36 @@ object FriendsStore {
|
||||
|
||||
private fun prefs() = appContext?.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||
|
||||
// Avatars and backgrounds live in files, one per image: in the settings XML they made a file
|
||||
// of up to tens of megabytes that was read at start and rewritten on every change.
|
||||
private fun imageDir(): File? = appContext?.let { File(it.filesDir, IMAGE_DIR) }
|
||||
|
||||
private fun imageFile(userId: String, kind: String): File? {
|
||||
val dir = imageDir() ?: return null
|
||||
val digest = MessageDigest.getInstance("SHA-256").digest(userId.toByteArray(Charsets.UTF_8))
|
||||
return File(dir, "${digest.toHex(16)}_$kind")
|
||||
}
|
||||
|
||||
private fun readImage(userId: String, kind: String): String? =
|
||||
imageFile(userId, kind)?.takeIf { it.isFile }?.let { runCatching { it.readText() }.getOrNull() }
|
||||
|
||||
private fun writeImage(userId: String, kind: String, base64: String?) {
|
||||
val file = imageFile(userId, kind) ?: return
|
||||
if (base64 == null) {
|
||||
file.delete()
|
||||
return
|
||||
}
|
||||
runCatching {
|
||||
file.parentFile?.mkdirs()
|
||||
val tmp = File(file.parentFile, file.name + ".tmp")
|
||||
tmp.writeText(base64)
|
||||
if (!tmp.renameTo(file)) {
|
||||
file.delete()
|
||||
tmp.renameTo(file)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun list(): List<FriendEntry> = synchronized(lock) { readAll() }
|
||||
|
||||
private fun readAll(): List<FriendEntry> {
|
||||
@@ -136,15 +171,21 @@ object FriendsStore {
|
||||
return emptyList()
|
||||
}
|
||||
val result = ArrayList<FriendEntry>()
|
||||
var hasInlineImages = false
|
||||
for (i in 0 until arr.length()) {
|
||||
try {
|
||||
val o = arr.getJSONObject(i)
|
||||
val userId = o.optString("uid", "").ifBlank { o.getString("name") }
|
||||
// Older versions kept the images inline; they move to files on the next write.
|
||||
val inlineAvatar = if (o.has("avatar")) o.getString("avatar") else null
|
||||
val inlineBackground = if (o.has("background")) o.getString("background") else null
|
||||
if (inlineAvatar != null || inlineBackground != null) hasInlineImages = true
|
||||
result.add(
|
||||
FriendEntry(
|
||||
userId = o.optString("uid", "").ifBlank { o.getString("name") },
|
||||
userId = userId,
|
||||
name = o.getString("name"),
|
||||
avatarBase64 = if (o.has("avatar")) o.getString("avatar") else null,
|
||||
backgroundBase64 = if (o.has("background")) o.getString("background") else null,
|
||||
avatarBase64 = inlineAvatar ?: if (o.optBoolean("a")) readImage(userId, "a") else null,
|
||||
backgroundBase64 = inlineBackground ?: if (o.optBoolean("b")) readImage(userId, "b") else null,
|
||||
elo = o.optInt("elo", 1200),
|
||||
lastPlayedMs = o.optLong("t", 0),
|
||||
favorite = o.optBoolean("fav", false),
|
||||
@@ -156,24 +197,35 @@ object FriendsStore {
|
||||
}
|
||||
val sorted = result.sortedByDescending { it.lastPlayedMs }
|
||||
cached = sorted
|
||||
if (hasInlineImages) writeAll(sorted, previous = emptyList())
|
||||
return sorted
|
||||
}
|
||||
|
||||
private fun writeAll(entries: List<FriendEntry>) {
|
||||
private fun writeAll(entries: List<FriendEntry>, previous: List<FriendEntry> = readAll()) {
|
||||
val p = prefs() ?: return
|
||||
val before = previous.associateBy { it.userId }
|
||||
val arr = JSONArray()
|
||||
entries.forEach { f ->
|
||||
val old = before[f.userId]
|
||||
// Image files are touched only when the image itself changed.
|
||||
if (old == null || old.avatarBase64 != f.avatarBase64) writeImage(f.userId, "a", f.avatarBase64)
|
||||
if (old == null || old.backgroundBase64 != f.backgroundBase64) writeImage(f.userId, "b", f.backgroundBase64)
|
||||
val o = JSONObject()
|
||||
o.put("uid", f.userId)
|
||||
o.put("name", f.name)
|
||||
if (f.avatarBase64 != null) o.put("avatar", f.avatarBase64)
|
||||
if (f.backgroundBase64 != null) o.put("background", f.backgroundBase64)
|
||||
if (f.avatarBase64 != null) o.put("a", true)
|
||||
if (f.backgroundBase64 != null) o.put("b", true)
|
||||
o.put("elo", f.elo)
|
||||
o.put("t", f.lastPlayedMs)
|
||||
if (f.favorite) o.put("fav", true)
|
||||
if (f.lastSeenMs > 0) o.put("s", f.lastSeenMs)
|
||||
arr.put(o)
|
||||
}
|
||||
val kept = entries.mapTo(HashSet()) { it.userId }
|
||||
previous.filter { it.userId !in kept }.forEach { gone ->
|
||||
writeImage(gone.userId, "a", null)
|
||||
writeImage(gone.userId, "b", null)
|
||||
}
|
||||
p.edit().putString(KEY_LIST, arr.toString()).apply()
|
||||
cached = entries.sortedByDescending { it.lastPlayedMs }
|
||||
}
|
||||
@@ -182,6 +234,11 @@ object FriendsStore {
|
||||
synchronized(lock) { readAll() }
|
||||
}
|
||||
|
||||
// Names and ratings also arrive from presence announcements, so they are bounded here too.
|
||||
private fun cleanName(name: String): String = name.filterNot { it.isISOControl() }.take(PeerLimits.MAX_NAME_CHARS)
|
||||
|
||||
private fun cleanElo(elo: Int): Int = elo.coerceIn(PeerLimits.MIN_ELO, PeerLimits.MAX_ELO)
|
||||
|
||||
fun updateProfile(
|
||||
userId: String,
|
||||
name: String,
|
||||
@@ -192,8 +249,8 @@ object FriendsStore {
|
||||
synchronized(lock) {
|
||||
val existing = readAll().firstOrNull { it.userId == userId } ?: return
|
||||
val updated = existing.copy(
|
||||
name = name.ifBlank { existing.name },
|
||||
elo = if (elo > 0) elo else existing.elo,
|
||||
name = cleanName(name).ifBlank { existing.name },
|
||||
elo = if (elo > 0) cleanElo(elo) else existing.elo,
|
||||
avatarBase64 = avatarBase64 ?: existing.avatarBase64,
|
||||
backgroundBase64 = backgroundBase64 ?: existing.backgroundBase64
|
||||
)
|
||||
@@ -217,12 +274,13 @@ object FriendsStore {
|
||||
backgroundBase64: String? = null
|
||||
): FriendEntry = synchronized(lock) {
|
||||
val existing = readAll().firstOrNull { it.userId == userId }
|
||||
val clean = cleanName(name)
|
||||
val merged = FriendEntry(
|
||||
userId = userId,
|
||||
name = name.ifBlank { existing?.name ?: name },
|
||||
name = clean.ifBlank { existing?.name ?: clean },
|
||||
avatarBase64 = avatarBase64 ?: existing?.avatarBase64,
|
||||
backgroundBase64 = backgroundBase64 ?: existing?.backgroundBase64,
|
||||
elo = if (elo > 0) elo else (existing?.elo ?: 1200),
|
||||
elo = if (elo > 0) cleanElo(elo) else (existing?.elo ?: 1200),
|
||||
lastPlayedMs = System.currentTimeMillis(),
|
||||
favorite = existing?.favorite ?: false,
|
||||
lastSeenMs = existing?.lastSeenMs ?: 0
|
||||
|
||||
@@ -73,6 +73,9 @@ class BleTransport(
|
||||
|
||||
private const val INCOMPLETE_TTL_MS = 30_000L
|
||||
|
||||
/** Messages being reassembled at once; each may grow to [MAX_MESSAGE_BYTES]. */
|
||||
private const val MAX_PARTIAL_MESSAGES = 4
|
||||
|
||||
private const val CTRL_TOTAL_MARKER = 0
|
||||
private const val CTRL_ACK = 1
|
||||
private const val CTRL_NACK = 2
|
||||
@@ -232,6 +235,8 @@ class BleTransport(
|
||||
role = Role.PERIPHERAL
|
||||
hosting = true
|
||||
|
||||
// Presence may already be advertising in the low-power mode; restart it for hosting.
|
||||
if (advertisingActive || advertiseCallback != null) startAdvertising()
|
||||
startPresence()
|
||||
_connectionState.value = ConnectionState.CONNECTING
|
||||
}
|
||||
@@ -300,10 +305,14 @@ class BleTransport(
|
||||
}
|
||||
// One advertisement at a time: a second start would leak the first one.
|
||||
if (advertiseCallback != null) stopAdvertising()
|
||||
// A hosted game should be found at once; plain presence can save the battery.
|
||||
val settings = AdvertiseSettings.Builder()
|
||||
|
||||
.setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY)
|
||||
.setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_HIGH)
|
||||
.setAdvertiseMode(
|
||||
if (hosting) AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY else AdvertiseSettings.ADVERTISE_MODE_BALANCED
|
||||
)
|
||||
.setTxPowerLevel(
|
||||
if (hosting) AdvertiseSettings.ADVERTISE_TX_POWER_HIGH else AdvertiseSettings.ADVERTISE_TX_POWER_MEDIUM
|
||||
)
|
||||
.setConnectable(true)
|
||||
.build()
|
||||
|
||||
@@ -790,6 +799,11 @@ class BleTransport(
|
||||
val now = System.currentTimeMillis()
|
||||
incoming.entries.removeAll { now - it.value.startedAt > INCOMPLETE_TTL_MS }
|
||||
|
||||
if (messageId !in incoming && incoming.size >= MAX_PARTIAL_MESSAGES) {
|
||||
// A peer that starts many messages and never finishes them would fill the memory.
|
||||
incoming.minByOrNull { it.value.startedAt }?.let { incoming.remove(it.key) }
|
||||
NetworkLog.log("BLE", "Too many unfinished messages, oldest dropped")
|
||||
}
|
||||
val entry = incoming.getOrPut(messageId) { PartialMessage(total, now) }
|
||||
if (entry.total != total) {
|
||||
incoming[messageId] = PartialMessage(total, now).also { it.parts[index] = payload }
|
||||
|
||||
@@ -29,6 +29,8 @@ data class LanPeer(
|
||||
val fingerprint: String = "",
|
||||
|
||||
val signature: String = "",
|
||||
/** When the announcement was signed, in epoch seconds; 0 if the peer sent none. */
|
||||
val signedAtSeconds: Long = 0,
|
||||
/** Raw NSD service name, used to remove the peer when the service is lost. */
|
||||
val serviceName: String = "",
|
||||
/** 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
|
||||
|
||||
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
|
||||
@@ -72,7 +88,8 @@ class LanTransport(
|
||||
context.getSystemService(Context.NSD_SERVICE) as? NsdManager
|
||||
|
||||
private var serverSocket: ServerSocket? = null
|
||||
private var socket: Socket? = null
|
||||
// Written by the connect and accept paths, read by the writer coroutine.
|
||||
@Volatile private var socket: Socket? = null
|
||||
|
||||
private val socketLock = Any()
|
||||
|
||||
@@ -82,7 +99,7 @@ class LanTransport(
|
||||
socket = candidate
|
||||
true
|
||||
}
|
||||
private var output: OutputStream? = null
|
||||
@Volatile private var output: OutputStream? = null
|
||||
private val dispatcher = MessageDispatcher()
|
||||
|
||||
@Volatile private var hosting = false
|
||||
@@ -91,6 +108,9 @@ class LanTransport(
|
||||
|
||||
private var registeredServiceName: String? = null
|
||||
|
||||
// Re-signs the announcement before it gets too old to be accepted.
|
||||
private var resignJob: kotlinx.coroutines.Job? = null
|
||||
|
||||
private val ownServiceName: String by lazy {
|
||||
val fingerprint = cc.skysparkle.matewave.security.DeviceKeys.publicKeyFingerprint(context)
|
||||
?: cc.skysparkle.matewave.data.DeviceIdentity.deviceId(context).take(12)
|
||||
@@ -211,13 +231,15 @@ class LanTransport(
|
||||
val profile = cc.skysparkle.matewave.data.ProfileStore.get()
|
||||
runCatching {
|
||||
val shownName = profile.name.take(40)
|
||||
val signedAt = System.currentTimeMillis() / 1000L
|
||||
setAttribute("id", profile.userId)
|
||||
setAttribute("name", shownName)
|
||||
setAttribute("elo", profile.elo.toString())
|
||||
setAttribute("fp", cc.skysparkle.matewave.security.DeviceKeys.publicKeyFingerprint(context) ?: "")
|
||||
setAttribute("ts", signedAt.toString())
|
||||
|
||||
cc.skysparkle.matewave.security.DeviceKeys.sign(
|
||||
context, presencePayload(profile.userId, shownName, profile.elo)
|
||||
context, presencePayload(profile.userId, shownName, profile.elo, signedAt)
|
||||
)?.let { setAttribute("sig", it) }
|
||||
cc.skysparkle.matewave.spectate.SpectatorAdvert.attributes().forEach { (key, value) -> setAttribute(key, value) }
|
||||
}
|
||||
@@ -240,9 +262,15 @@ class LanTransport(
|
||||
nsd.registerService(info, NsdManager.PROTOCOL_DNS_SD, listener)
|
||||
} catch (_: Exception) {
|
||||
}
|
||||
resignJob = scope.launch {
|
||||
kotlinx.coroutines.delay(PRESENCE_RESIGN_MS)
|
||||
republishProfile()
|
||||
}
|
||||
}
|
||||
|
||||
private fun unregisterService() {
|
||||
resignJob?.cancel()
|
||||
resignJob = null
|
||||
val nsd = nsdManager ?: return
|
||||
registrationListener?.let {
|
||||
try { nsd.unregisterService(it) } catch (_: Exception) {}
|
||||
@@ -362,6 +390,7 @@ class LanTransport(
|
||||
|
||||
fingerprint = attr("fp").ifEmpty { fingerprintFromServiceName(info.serviceName ?: "") ?: "" },
|
||||
signature = attr("sig"),
|
||||
signedAtSeconds = attr("ts").toLongOrNull() ?: 0,
|
||||
serviceName = info.serviceName ?: "",
|
||||
gameTag = game.gameTag,
|
||||
spectatePort = game.spectatePort
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
package cc.skysparkle.matewave.network
|
||||
|
||||
import android.util.Log
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
|
||||
enum class DisconnectReason(val userText: String, val textRes: Int) {
|
||||
NONE("—", cc.skysparkle.matewave.R.string.reason_unknown),
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
data class NetworkEvent(
|
||||
val at: Long,
|
||||
val transport: String,
|
||||
val text: String
|
||||
)
|
||||
|
||||
object NetworkLog {
|
||||
private const val CAPACITY = 60
|
||||
|
||||
private val _events = MutableStateFlow<List<NetworkEvent>>(emptyList())
|
||||
|
||||
private val _lastReason = MutableStateFlow(DisconnectReason.NONE)
|
||||
val lastReason: StateFlow<DisconnectReason> = _lastReason
|
||||
|
||||
/** Debug output only: release builds strip Log.d (see proguard-rules.pro). */
|
||||
fun log(transport: String, text: String) {
|
||||
val event = NetworkEvent(System.currentTimeMillis(), transport, text)
|
||||
_events.update { (it + event).takeLast(CAPACITY) }
|
||||
Log.d("Matewave/$transport", text)
|
||||
}
|
||||
|
||||
fun reason(transport: String, reason: DisconnectReason, detail: String? = null) {
|
||||
|
||||
@@ -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)
|
||||
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
|
||||
// recorded and replayed by someone else is not accepted.
|
||||
val authentic = peer.signature.isNotEmpty() &&
|
||||
cc.skysparkle.matewave.network.LanTransport.isFreshPresence(peer.signedAtSeconds, lastResultAt) &&
|
||||
DeviceKeys.verify(
|
||||
knownKey,
|
||||
cc.skysparkle.matewave.network.LanTransport.presencePayload(peer.playerId, peer.displayName, peer.elo),
|
||||
cc.skysparkle.matewave.network.LanTransport.presencePayload(
|
||||
peer.playerId, peer.displayName, peer.elo, peer.signedAtSeconds
|
||||
),
|
||||
peer.signature
|
||||
)
|
||||
if (!authentic) {
|
||||
NetworkLog.log("PRESENCE", "Announcement for $id failed signature check, hidden")
|
||||
NetworkLog.log("PRESENCE", "Announcement for $id is stale or failed signature check, hidden")
|
||||
return@forEach
|
||||
}
|
||||
FriendsStore.updateProfile(
|
||||
|
||||
@@ -5,10 +5,12 @@ import java.io.File
|
||||
import java.io.IOException
|
||||
import java.io.OutputStream
|
||||
import java.net.Inet4Address
|
||||
import java.net.InetSocketAddress
|
||||
import java.net.NetworkInterface
|
||||
import java.net.ServerSocket
|
||||
import java.net.Socket
|
||||
import java.util.Locale
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
import kotlin.concurrent.thread
|
||||
|
||||
class ApkShareServer(private val apk: File, private val appName: String) {
|
||||
@@ -17,8 +19,13 @@ class ApkShareServer(private val apk: File, private val appName: String) {
|
||||
@Volatile
|
||||
private var server: ServerSocket? = null
|
||||
|
||||
private val activeClients = AtomicInteger()
|
||||
|
||||
/** Listens on the Wi-Fi address only (all interfaces if none is found), so the APK is not served elsewhere. */
|
||||
fun start(): Int {
|
||||
val socket = ServerSocket(0)
|
||||
val socket = ServerSocket()
|
||||
socket.reuseAddress = true
|
||||
socket.bind(InetSocketAddress(LocalNetwork.wifiInet4(), 0))
|
||||
server = socket
|
||||
thread(name = "apk-share-accept", isDaemon = true) {
|
||||
while (!socket.isClosed) {
|
||||
@@ -27,7 +34,19 @@ class ApkShareServer(private val apk: File, private val appName: String) {
|
||||
} catch (e: IOException) {
|
||||
break
|
||||
}
|
||||
thread(name = "apk-share-client", isDaemon = true) { serve(client) }
|
||||
// A handful of downloads at a time is plenty; more connections are refused.
|
||||
if (activeClients.incrementAndGet() > MAX_CLIENTS) {
|
||||
activeClients.decrementAndGet()
|
||||
runCatching { client.close() }
|
||||
continue
|
||||
}
|
||||
thread(name = "apk-share-client", isDaemon = true) {
|
||||
try {
|
||||
serve(client)
|
||||
} finally {
|
||||
activeClients.decrementAndGet()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return socket.localPort
|
||||
@@ -78,6 +97,10 @@ class ApkShareServer(private val apk: File, private val appName: String) {
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val MAX_CLIENTS = 4
|
||||
}
|
||||
|
||||
private fun sendText(out: OutputStream, code: Int, reason: String, text: String, withBody: Boolean) {
|
||||
val body = text.toByteArray(Charsets.UTF_8)
|
||||
writeHeader(out, code, reason, "text/plain; charset=utf-8", body.size.toLong())
|
||||
@@ -117,12 +140,13 @@ class ApkShareServer(private val apk: File, private val appName: String) {
|
||||
object LocalNetwork {
|
||||
private val WIFI_PREFIXES = listOf("wlan", "swlan", "ap", "softap", "eth")
|
||||
|
||||
fun wifiIpv4(): String? = runCatching {
|
||||
fun wifiInet4(): Inet4Address? = runCatching {
|
||||
NetworkInterface.getNetworkInterfaces()?.toList().orEmpty()
|
||||
.filter { nif -> nif.isUp && !nif.isLoopback && WIFI_PREFIXES.any { nif.name.startsWith(it) } }
|
||||
.flatMap { nif -> nif.inetAddresses.toList() }
|
||||
.filterIsInstance<Inet4Address>()
|
||||
.firstOrNull { it.isSiteLocalAddress }
|
||||
?.hostAddress
|
||||
}.getOrNull()
|
||||
|
||||
fun wifiIpv4(): String? = wifiInet4()?.hostAddress
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@ import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import cc.skysparkle.matewave.R
|
||||
import cc.skysparkle.matewave.ui.theme.AppBackground
|
||||
import cc.skysparkle.matewave.ui.theme.AppThemeState
|
||||
import cc.skysparkle.matewave.ui.theme.ChessGreen
|
||||
import cc.skysparkle.matewave.ui.theme.Lime
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
@@ -73,6 +74,9 @@ private val ForestTint = ColorFilter.colorMatrix(
|
||||
)
|
||||
)
|
||||
|
||||
/** For the other styles the forest turns almost grey, so it never fights their colours. */
|
||||
private val NeutralForestTint = ColorFilter.colorMatrix(ColorMatrix().apply { setToSaturation(0.12f) })
|
||||
|
||||
/**
|
||||
* The misty forest artwork, deeply darkened so it reads as texture: the mist stays
|
||||
* visible behind the headings at the top and fades into near-black lower down.
|
||||
@@ -95,7 +99,7 @@ fun AppBackdrop() {
|
||||
contentDescription = null,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentScale = ContentScale.Crop,
|
||||
colorFilter = ForestTint
|
||||
colorFilter = if (AppThemeState.palette.greenBackdrop) ForestTint else NeutralForestTint
|
||||
)
|
||||
}
|
||||
Box(
|
||||
|
||||
@@ -50,8 +50,8 @@ import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
|
||||
val DialogSurface = cc.skysparkle.matewave.ui.theme.Surface1
|
||||
val DialogAccent = cc.skysparkle.matewave.ui.theme.ChessGreen
|
||||
val DialogSurface: Color get() = cc.skysparkle.matewave.ui.theme.Surface1
|
||||
val DialogAccent: Color get() = cc.skysparkle.matewave.ui.theme.ChessGreen
|
||||
val DialogShape = RoundedCornerShape(28.dp)
|
||||
|
||||
@Composable
|
||||
|
||||
@@ -86,21 +86,46 @@ private object DecodedImageCache {
|
||||
fun put(key: String, bitmap: Bitmap) { cache.put(key, bitmap) }
|
||||
}
|
||||
|
||||
/** Larger images (from the opponent) are refused; ours never exceed [MAX_DIMENSION_PX]. */
|
||||
const val MAX_INCOMING_IMAGE_PX = 4096
|
||||
|
||||
/** Upper bound for the decoded size when the caller does not ask for a smaller one. */
|
||||
private const val DEFAULT_DECODE_PX = 1280
|
||||
|
||||
/** Width and height of an encoded image, or null if it is not a readable image. */
|
||||
private fun imageBounds(bytes: ByteArray): Pair<Int, Int>? {
|
||||
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)
|
||||
return if (bounds.outWidth > 0 && bounds.outHeight > 0) bounds.outWidth to bounds.outHeight else null
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks an image received from another device before it is shown or stored: it must be a
|
||||
* readable image no larger than [MAX_INCOMING_IMAGE_PX] on either side. A small file can
|
||||
* declare a huge resolution, and decoding it at full size would run out of memory.
|
||||
*/
|
||||
fun isAcceptableIncomingImage(base64: String): Boolean = try {
|
||||
val size = imageBounds(Base64.decode(base64, Base64.NO_WRAP))
|
||||
size != null && size.first <= MAX_INCOMING_IMAGE_PX && size.second <= MAX_INCOMING_IMAGE_PX
|
||||
} catch (e: Exception) {
|
||||
false
|
||||
}
|
||||
|
||||
fun decodeChatImage(base64: String, maxDimension: Int = 0): Bitmap? {
|
||||
return try {
|
||||
val bytes = Base64.decode(base64, Base64.NO_WRAP)
|
||||
if (maxDimension <= 0) {
|
||||
BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
|
||||
} else {
|
||||
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)
|
||||
// The size is always checked first: the image may come from another device.
|
||||
val (width, height) = imageBounds(bytes) ?: return null
|
||||
if (width > MAX_INCOMING_IMAGE_PX || height > MAX_INCOMING_IMAGE_PX) return null
|
||||
val target = if (maxDimension > 0) maxDimension else DEFAULT_DECODE_PX
|
||||
var sample = 1
|
||||
while (maxOf(bounds.outWidth, bounds.outHeight) / (sample * 2) >= maxDimension) sample *= 2
|
||||
while (maxOf(width, height) / (sample * 2) >= target) sample *= 2
|
||||
val options = BitmapFactory.Options().apply { inSampleSize = sample }
|
||||
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
null
|
||||
} catch (e: OutOfMemoryError) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -156,7 +156,7 @@ fun GlassButton(
|
||||
onClick = onClick
|
||||
) else Modifier
|
||||
)
|
||||
.padding(horizontal = 22.dp, vertical = 15.dp),
|
||||
.padding(horizontal = 16.dp, vertical = 15.dp),
|
||||
horizontalArrangement = Arrangement.Center,
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
content = content
|
||||
@@ -186,7 +186,7 @@ fun GlassOutlinedButton(
|
||||
onClick = onClick
|
||||
) else Modifier
|
||||
)
|
||||
.padding(horizontal = 22.dp, vertical = 15.dp),
|
||||
.padding(horizontal = 16.dp, vertical = 15.dp),
|
||||
horizontalArrangement = Arrangement.Center,
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
content = content
|
||||
|
||||
@@ -12,6 +12,13 @@ import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import cc.skysparkle.matewave.ui.theme.AppPalette
|
||||
import cc.skysparkle.matewave.ui.theme.AppStyle
|
||||
import cc.skysparkle.matewave.ui.theme.AppThemeState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Switch
|
||||
@@ -25,7 +32,6 @@ import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.res.stringResource
|
||||
@@ -51,6 +57,13 @@ fun AppearanceScreen(onBack: () -> Unit) {
|
||||
var openingBar by remember { mutableStateOf(appearance.showOpening) }
|
||||
|
||||
GlassScaffold(title = stringResource(R.string.appearance_title), onBack = onBack) {
|
||||
Text(
|
||||
stringResource(R.string.app_style_title),
|
||||
color = ink,
|
||||
style = MaterialTheme.typography.titleMedium
|
||||
)
|
||||
StylePicker()
|
||||
|
||||
Text(
|
||||
stringResource(R.string.appearance_board_theme),
|
||||
color = ink,
|
||||
@@ -77,7 +90,7 @@ fun AppearanceScreen(onBack: () -> Unit) {
|
||||
)
|
||||
if (candidate == theme) {
|
||||
cc.skysparkle.matewave.ui.components.AppIcon(
|
||||
R.drawable.ic_check_box, size = 20.dp, tint = Color(0xFF7BE495)
|
||||
R.drawable.ic_check_box, size = 20.dp, tint = cc.skysparkle.matewave.ui.theme.ChessGreen
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -127,6 +140,85 @@ fun AppearanceScreen(onBack: () -> Unit) {
|
||||
}
|
||||
}
|
||||
|
||||
/** App colour styles as swatches, three per row; the device style follows the wallpaper. */
|
||||
@Composable
|
||||
private fun StylePicker() {
|
||||
val context = LocalContext.current
|
||||
val selected = AppThemeState.style
|
||||
val styles = remember { AppStyle.available }
|
||||
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
styles.chunked(3).forEach { row ->
|
||||
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
row.forEach { style ->
|
||||
StyleSwatch(
|
||||
style = style,
|
||||
palette = remember(style) { AppThemeState.paletteFor(context, style) },
|
||||
selected = style == selected,
|
||||
modifier = Modifier.weight(1f),
|
||||
onClick = { AppThemeState.select(context, style) }
|
||||
)
|
||||
}
|
||||
repeat(3 - row.size) { Spacer(Modifier.weight(1f)) }
|
||||
}
|
||||
}
|
||||
if (selected == AppStyle.DEVICE) {
|
||||
Text(
|
||||
stringResource(R.string.app_style_device_hint),
|
||||
color = ink.copy(alpha = 0.6f),
|
||||
style = MaterialTheme.typography.bodySmall
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StyleSwatch(
|
||||
style: AppStyle,
|
||||
palette: AppPalette,
|
||||
selected: Boolean,
|
||||
modifier: Modifier = Modifier,
|
||||
onClick: () -> Unit
|
||||
) {
|
||||
val shape = RoundedCornerShape(18.dp)
|
||||
Column(
|
||||
modifier = modifier
|
||||
.clip(shape)
|
||||
.background(palette.surface1)
|
||||
.border(if (selected) 2.dp else 1.dp, if (selected) palette.accent else PanelBorder, shape)
|
||||
.clickable(onClick = onClick)
|
||||
.padding(vertical = 12.dp, horizontal = 6.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally
|
||||
) {
|
||||
Box(contentAlignment = Alignment.BottomEnd) {
|
||||
Box(
|
||||
modifier = Modifier.size(44.dp).clip(CircleShape).background(palette.accent),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
if (selected) {
|
||||
cc.skysparkle.matewave.ui.components.AppIcon(
|
||||
R.drawable.ic_check_box, size = 20.dp, tint = palette.onAccent
|
||||
)
|
||||
}
|
||||
}
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.size(20.dp)
|
||||
.clip(CircleShape)
|
||||
.background(palette.action)
|
||||
.border(2.dp, palette.surface1, CircleShape)
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text(
|
||||
stringResource(style.titleRes),
|
||||
color = ink,
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ThemePreview(theme: BoardTheme, showPieces: Boolean) {
|
||||
val shape = RoundedCornerShape(6.dp)
|
||||
|
||||
@@ -77,14 +77,16 @@ private data class NearbyEntry(
|
||||
val elo: Int?,
|
||||
val type: TransportType,
|
||||
val address: String,
|
||||
val avatar: String?
|
||||
val avatar: String?,
|
||||
/** Player id from the signed Wi-Fi announcement; checked against the profile after connecting. */
|
||||
val playerId: String? = null
|
||||
)
|
||||
|
||||
@Composable
|
||||
fun ConnectionScreen(
|
||||
presence: LocalPresence,
|
||||
onStartHost: (TimeControl) -> Unit,
|
||||
onJoin: (TransportType, TimeControl, targetId: String) -> Unit,
|
||||
onJoin: (TransportType, TimeControl, targetId: String, expectedUserId: String?) -> Unit,
|
||||
onBack: () -> Unit
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
@@ -146,7 +148,8 @@ fun ConnectionScreen(
|
||||
elo = peer.elo,
|
||||
type = TransportType.LAN,
|
||||
address = peer.address,
|
||||
avatar = friends.firstOrNull { it.userId == peer.playerId }?.avatarBase64
|
||||
avatar = friends.firstOrNull { it.userId == peer.playerId }?.avatarBase64,
|
||||
playerId = peer.playerId
|
||||
)
|
||||
}
|
||||
val lanFingerprints = peers.values.map { it.fingerprint }.filter { it.isNotEmpty() }
|
||||
@@ -263,7 +266,7 @@ fun ConnectionScreen(
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(50))
|
||||
.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)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -179,12 +179,14 @@ fun GameScreen(viewModel: GameViewModel, onExit: () -> Unit) {
|
||||
Text(
|
||||
if (state.drawOfferSentByMe) stringResource(R.string.draw_offer_waiting) else stringResource(R.string.offer_draw),
|
||||
color = ink,
|
||||
maxLines = 1
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
maxLines = 1,
|
||||
overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis
|
||||
)
|
||||
}
|
||||
GlassOutlinedButton(onClick = { confirmResign = true }, modifier = Modifier.weight(1f)) {
|
||||
ButtonIcon(R.drawable.ic_flag)
|
||||
Text(stringResource(R.string.resign), color = ink, maxLines = 1)
|
||||
Text(stringResource(R.string.resign), color = ink, style = MaterialTheme.typography.labelLarge, maxLines = 1)
|
||||
}
|
||||
}
|
||||
ChatButton(
|
||||
|
||||
@@ -130,7 +130,6 @@ fun MainMenuScreen(
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(50))
|
||||
.background(Surface2)
|
||||
.clickable { showStats = true }
|
||||
.padding(start = 10.dp, end = 14.dp, top = 8.dp, bottom = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
package cc.skysparkle.matewave.ui.theme
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import androidx.compose.material3.dynamicDarkColorScheme
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import cc.skysparkle.matewave.R
|
||||
|
||||
/** The colours every screen is drawn with. The app stays dark in every style. */
|
||||
data class AppPalette(
|
||||
/** Highlights, selected states, progress. */
|
||||
val accent: Color,
|
||||
/** The one main action on a screen. */
|
||||
val action: Color,
|
||||
/** Text and icons on top of [accent] or [action]. */
|
||||
val onAccent: Color,
|
||||
val background: Color,
|
||||
val surface1: Color,
|
||||
val surface2: Color,
|
||||
/** The forest backdrop keeps its green cast only with the original colours. */
|
||||
val greenBackdrop: Boolean = false
|
||||
)
|
||||
|
||||
enum class AppStyle(val titleRes: Int) {
|
||||
MATEWAVE(R.string.app_style_matewave),
|
||||
LAVENDER(R.string.app_style_lavender),
|
||||
PEACH(R.string.app_style_peach),
|
||||
MINT(R.string.app_style_mint),
|
||||
SKY(R.string.app_style_sky),
|
||||
DEVICE(R.string.app_style_device);
|
||||
|
||||
companion object {
|
||||
/** Wallpaper colours exist from Android 12. */
|
||||
val deviceSupported: Boolean get() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S
|
||||
|
||||
val available: List<AppStyle> get() = entries.filter { it != DEVICE || deviceSupported }
|
||||
}
|
||||
}
|
||||
|
||||
private val MatewavePalette = AppPalette(
|
||||
accent = Color(0xFF35E07E),
|
||||
action = Color(0xFFE3F84B),
|
||||
onAccent = Color(0xFF0B1610),
|
||||
background = Color(0xFF0C0F0E),
|
||||
surface1 = Color(0xFF161B19),
|
||||
surface2 = Color(0xFF1F2623),
|
||||
greenBackdrop = true
|
||||
)
|
||||
|
||||
private val LavenderPalette = AppPalette(
|
||||
accent = Color(0xFFC8B6FF),
|
||||
action = Color(0xFFFFC6E5),
|
||||
onAccent = Color(0xFF1E1630),
|
||||
background = Color(0xFF0F0E14),
|
||||
surface1 = Color(0xFF1A1822),
|
||||
surface2 = Color(0xFF25222F)
|
||||
)
|
||||
|
||||
private val PeachPalette = AppPalette(
|
||||
accent = Color(0xFFFFB59E),
|
||||
action = Color(0xFFFFE08A),
|
||||
onAccent = Color(0xFF2A1710),
|
||||
background = Color(0xFF12100E),
|
||||
surface1 = Color(0xFF1D1A17),
|
||||
surface2 = Color(0xFF28231F)
|
||||
)
|
||||
|
||||
private val MintPalette = AppPalette(
|
||||
accent = Color(0xFF9EE7C8),
|
||||
action = Color(0xFFD8F5A8),
|
||||
onAccent = Color(0xFF0F231B),
|
||||
background = Color(0xFF0D110F),
|
||||
surface1 = Color(0xFF171C1A),
|
||||
surface2 = Color(0xFF202724)
|
||||
)
|
||||
|
||||
private val SkyPalette = AppPalette(
|
||||
accent = Color(0xFFA5CBFF),
|
||||
action = Color(0xFFB8F1EE),
|
||||
onAccent = Color(0xFF0F1A2A),
|
||||
background = Color(0xFF0D1014),
|
||||
surface1 = Color(0xFF171B21),
|
||||
surface2 = Color(0xFF20252D)
|
||||
)
|
||||
|
||||
/** The selected style, kept in compose state so every screen recolours at once. */
|
||||
object AppThemeState {
|
||||
private const val PREFS = "app_theme"
|
||||
private const val KEY_STYLE = "style"
|
||||
|
||||
var style by mutableStateOf(AppStyle.MATEWAVE)
|
||||
private set
|
||||
|
||||
var palette by mutableStateOf(MatewavePalette)
|
||||
private set
|
||||
|
||||
/** Reads the saved style; call once before the first frame. */
|
||||
fun load(context: Context) {
|
||||
val saved = context.applicationContext
|
||||
.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||
.getString(KEY_STYLE, null)
|
||||
val style = AppStyle.entries.firstOrNull { it.name == saved } ?: AppStyle.MATEWAVE
|
||||
applyStyle(context, style)
|
||||
}
|
||||
|
||||
fun select(context: Context, style: AppStyle) {
|
||||
context.applicationContext
|
||||
.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||
.edit().putString(KEY_STYLE, style.name).apply()
|
||||
applyStyle(context, style)
|
||||
}
|
||||
|
||||
private fun applyStyle(context: Context, requested: AppStyle) {
|
||||
val style = if (requested == AppStyle.DEVICE && !AppStyle.deviceSupported) AppStyle.MATEWAVE else requested
|
||||
this.style = style
|
||||
palette = paletteFor(context, style)
|
||||
}
|
||||
|
||||
/** Preview colours for the style picker. */
|
||||
fun paletteFor(context: Context, style: AppStyle): AppPalette = when (style) {
|
||||
AppStyle.MATEWAVE -> MatewavePalette
|
||||
AppStyle.LAVENDER -> LavenderPalette
|
||||
AppStyle.PEACH -> PeachPalette
|
||||
AppStyle.MINT -> MintPalette
|
||||
AppStyle.SKY -> SkyPalette
|
||||
AppStyle.DEVICE -> devicePalette(context)
|
||||
}
|
||||
|
||||
private fun devicePalette(context: Context): AppPalette {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) return MatewavePalette
|
||||
val scheme = dynamicDarkColorScheme(context)
|
||||
return AppPalette(
|
||||
accent = scheme.primary,
|
||||
action = scheme.tertiary,
|
||||
onAccent = scheme.onPrimary,
|
||||
background = scheme.background,
|
||||
surface1 = scheme.surfaceContainer,
|
||||
surface2 = scheme.surfaceContainerHigh
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,7 @@ import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.Shape
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
val PanelFill = Surface1
|
||||
val PanelFill: Color get() = Surface1
|
||||
val PanelBorder = Color.White.copy(alpha = 0.06f)
|
||||
|
||||
val UiCornerRadius = 22.dp
|
||||
@@ -22,4 +22,4 @@ fun Modifier.glass(): Modifier = this
|
||||
|
||||
val DialogScrimColor = Color.Black.copy(alpha = 0.70f)
|
||||
|
||||
val FloatingBarFill = Surface2
|
||||
val FloatingBarFill: Color get() = Surface2
|
||||
|
||||
@@ -15,35 +15,27 @@ import androidx.compose.ui.text.font.FontWeight
|
||||
import cc.skysparkle.matewave.R
|
||||
import androidx.compose.ui.unit.sp
|
||||
|
||||
/** Neon green: the brand accent for highlights, selected states and progress. */
|
||||
val ChessGreen = Color(0xFF35E07E)
|
||||
val ChessGreenDark = Color(0xFF123D25)
|
||||
// The interface colours follow the selected style (see AppPalette); reading them in
|
||||
// composition subscribes the screen, so a new style recolours everything at once.
|
||||
|
||||
/** Lime: the one colour for the main action on a screen. */
|
||||
val Lime = Color(0xFFE3F84B)
|
||||
/** Accent: highlights, selected states and progress. Neon green in the original style. */
|
||||
val ChessGreen: Color get() = AppThemeState.palette.accent
|
||||
|
||||
/** The one colour for the main action on a screen. Lime in the original style. */
|
||||
val Lime: Color get() = AppThemeState.palette.action
|
||||
|
||||
/** Text and icons on top of [ChessGreen] or [Lime]. */
|
||||
val OnAccent = Color(0xFF0B1610)
|
||||
val OnAccent: Color get() = AppThemeState.palette.onAccent
|
||||
|
||||
val AppBackground = Color(0xFF0C0F0E)
|
||||
val Surface1 = Color(0xFF161B19)
|
||||
val Surface2 = Color(0xFF1F2623)
|
||||
val AppBackground: Color get() = AppThemeState.palette.background
|
||||
val Surface1: Color get() = AppThemeState.palette.surface1
|
||||
val Surface2: Color get() = AppThemeState.palette.surface2
|
||||
|
||||
val HighlightMove = Color(0x8858A6FF)
|
||||
val HighlightCheck = Color(0x88E53935)
|
||||
val HighlightLastMove = Color(0x664FC3F7)
|
||||
val HighlightHint = Color(0x88FFC107)
|
||||
|
||||
private val DarkScheme = darkColorScheme(
|
||||
primary = ChessGreen,
|
||||
onPrimary = OnAccent,
|
||||
secondary = Lime,
|
||||
onSecondary = OnAccent,
|
||||
background = AppBackground,
|
||||
surface = Surface1,
|
||||
surfaceVariant = Surface2
|
||||
)
|
||||
|
||||
/** Wide display face for the big headings: the brand voice of the app. */
|
||||
val DisplayFont = FontFamily(
|
||||
Font(R.font.unbounded_semibold, FontWeight.SemiBold),
|
||||
@@ -95,7 +87,16 @@ val HeroTextStyle = TextStyle(
|
||||
/** The app has a single dark theme; system bars are set up in MainActivity. */
|
||||
@Composable
|
||||
fun MatewaveTheme(content: @Composable () -> Unit) {
|
||||
MaterialTheme(colorScheme = DarkScheme, typography = AppTypography) {
|
||||
val scheme = darkColorScheme(
|
||||
primary = ChessGreen,
|
||||
onPrimary = OnAccent,
|
||||
secondary = Lime,
|
||||
onSecondary = OnAccent,
|
||||
background = AppBackground,
|
||||
surface = Surface1,
|
||||
surfaceVariant = Surface2
|
||||
)
|
||||
MaterialTheme(colorScheme = scheme, typography = AppTypography) {
|
||||
// Text and icons without their own colour are light, so nothing turns black on the dark background
|
||||
CompositionLocalProvider(LocalContentColor provides Color.White, content = content)
|
||||
}
|
||||
|
||||
@@ -26,6 +26,7 @@ import cc.skysparkle.matewave.network.ConnectionTransport
|
||||
import cc.skysparkle.matewave.network.GameMessage
|
||||
import cc.skysparkle.matewave.network.NetworkLog
|
||||
import cc.skysparkle.matewave.network.NetworkMetrics
|
||||
import cc.skysparkle.matewave.network.PeerLimits
|
||||
import cc.skysparkle.matewave.network.TransportType
|
||||
import cc.skysparkle.matewave.puzzles.Puzzle
|
||||
import cc.skysparkle.matewave.security.DeviceKeys
|
||||
@@ -43,6 +44,7 @@ import cc.skysparkle.matewave.spectate.SpectatorResult
|
||||
import cc.skysparkle.matewave.spectate.SpectatorResults
|
||||
import cc.skysparkle.matewave.spectate.SpectatorSnapshot
|
||||
import cc.skysparkle.matewave.stats.Stats
|
||||
import cc.skysparkle.matewave.ui.components.isAcceptableIncomingImage
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
@@ -185,8 +187,10 @@ class GameViewModel : ViewModel() {
|
||||
private var sessionGeneration = 0
|
||||
private var networkGameId: String = ""
|
||||
private var pendingOpponentImages: Pair<String?, String?>? = null
|
||||
|
||||
// The player picked in the nearby list; whoever answers must be that player.
|
||||
private var expectedOpponentUserId: String? = null
|
||||
private var currentPly: Int = 0
|
||||
private var lastOpponentRemaining: Long = Long.MAX_VALUE
|
||||
|
||||
// Spectating: the host serves spectators, both players announce the game's tag.
|
||||
private var spectators: SpectatorBroadcaster? = null
|
||||
@@ -711,7 +715,8 @@ class GameViewModel : ViewModel() {
|
||||
myColor: PieceColor,
|
||||
timeControl: TimeControl,
|
||||
isHost: Boolean,
|
||||
targetId: String? = null
|
||||
targetId: String? = null,
|
||||
expectedUserId: String? = null
|
||||
) {
|
||||
pendingLeave?.let { (job, oldTransport) ->
|
||||
job.cancel()
|
||||
@@ -730,6 +735,7 @@ class GameViewModel : ViewModel() {
|
||||
this.transport = transport
|
||||
lastNetworkTimeControl = timeControl
|
||||
isNetworkHost = isHost
|
||||
expectedOpponentUserId = expectedUserId?.takeIf { it.isNotBlank() }
|
||||
|
||||
ephemeralKeys = DeviceKeys.generateEphemeral()
|
||||
|
||||
@@ -739,7 +745,6 @@ class GameViewModel : ViewModel() {
|
||||
opponentFlagJob = null
|
||||
networkGameId = if (isHost) java.util.UUID.randomUUID().toString() else ""
|
||||
currentPly = 0
|
||||
lastOpponentRemaining = Long.MAX_VALUE
|
||||
|
||||
_clockState.value = null
|
||||
_uiState.value = GameUiState(
|
||||
@@ -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 =
|
||||
gameId.isEmpty() || networkGameId.isEmpty() || gameId == networkGameId
|
||||
|
||||
@@ -901,9 +913,14 @@ class GameViewModel : ViewModel() {
|
||||
NetworkLog.log("GAME", "Oversized chat message rejected")
|
||||
return
|
||||
}
|
||||
if (msg.imageBase64 != null && !isAcceptableIncomingImage(msg.imageBase64)) {
|
||||
NetworkLog.log("GAME", "Unreadable or oversized chat image rejected")
|
||||
return
|
||||
}
|
||||
val state = _uiState.value
|
||||
_uiState.value = state.copy(
|
||||
chatMessages = state.chatMessages + ChatEntry(msg.text, msg.imageBase64, fromMe = false),
|
||||
chatMessages = (state.chatMessages + ChatEntry(msg.text, msg.imageBase64, fromMe = false))
|
||||
.takeLast(MAX_CHAT_ENTRIES),
|
||||
unreadChatCount = state.unreadChatCount + 1
|
||||
)
|
||||
}
|
||||
@@ -976,8 +993,8 @@ class GameViewModel : ViewModel() {
|
||||
}
|
||||
is GameMessage.ProfileImagesMsg -> {
|
||||
if (!belongsToCurrentGame(msg.gameId)) return
|
||||
val avatar = msg.avatarBase64?.takeIf { it.length <= MAX_CHAT_IMAGE_CHARS }
|
||||
val background = msg.backgroundBase64?.takeIf { it.length <= MAX_CHAT_IMAGE_CHARS }
|
||||
val avatar = msg.avatarBase64?.let(::acceptedIncomingImage)
|
||||
val background = msg.backgroundBase64?.let(::acceptedIncomingImage)
|
||||
if (avatar == null && background == null) return
|
||||
val current = _uiState.value.opponentProfile
|
||||
if (current == null) {
|
||||
@@ -1051,17 +1068,17 @@ class GameViewModel : ViewModel() {
|
||||
|
||||
val limit = lastNetworkTimeControl?.let { it.initialSeconds * 1000L + 60_000L }
|
||||
val increment = lastNetworkTimeControl?.let { it.incrementSeconds * 1000L } ?: 0L
|
||||
val allowedMax = if (lastOpponentRemaining == Long.MAX_VALUE) {
|
||||
limit ?: Long.MAX_VALUE
|
||||
} else {
|
||||
lastOpponentRemaining + increment + CLOCK_TOLERANCE_MS
|
||||
}
|
||||
// Our own clock has been running the opponent's time while they thought, so their claim
|
||||
// may not exceed it by more than the increment and network slack.
|
||||
val allowedMax = clock?.remainingMillis(opponentColor)
|
||||
?.let { PeerLimits.maxOpponentClockAfterMove(it, increment, CLOCK_TOLERANCE_MS) }
|
||||
?: limit ?: Long.MAX_VALUE
|
||||
if (msg.remainingMillisSelf >= 0 &&
|
||||
(limit == null || msg.remainingMillisSelf <= limit) &&
|
||||
msg.remainingMillisSelf <= allowedMax
|
||||
) {
|
||||
lastOpponentRemaining = msg.remainingMillisSelf
|
||||
clock?.applyRemoteTime(opponentColor, msg.remainingMillisSelf)
|
||||
// The reported time already includes the increment; makeMove below adds it again.
|
||||
clock?.applyRemoteTime(opponentColor, (msg.remainingMillisSelf - increment).coerceAtLeast(0))
|
||||
} else if (msg.remainingMillisSelf > 0) {
|
||||
NetworkLog.log("GAME", "Invalid clock value from opponent rejected: ${msg.remainingMillisSelf}")
|
||||
}
|
||||
@@ -1077,6 +1094,12 @@ class GameViewModel : ViewModel() {
|
||||
NetworkLog.log("GAME", "Repeated profile in current session ignored")
|
||||
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
|
||||
if (peers == null) {
|
||||
NetworkLog.log("GAME", "Key store not ready, profile rejected")
|
||||
@@ -1125,7 +1148,11 @@ class GameViewModel : ViewModel() {
|
||||
}
|
||||
markReadyIfPossible()
|
||||
|
||||
_uiState.value = _uiState.value.copy(opponentUnverified = trust == TrustResult.UNSIGNED)
|
||||
val unexpected = expectedOpponentUserId?.let { it != msg.userId } == true
|
||||
if (unexpected) {
|
||||
NetworkLog.log("GAME", "Opponent is not the player picked in the nearby list")
|
||||
}
|
||||
_uiState.value = _uiState.value.copy(opponentUnverified = trust == TrustResult.UNSIGNED || unexpected)
|
||||
|
||||
val pending = pendingOpponentImages
|
||||
pendingOpponentImages = null
|
||||
@@ -1133,8 +1160,8 @@ class GameViewModel : ViewModel() {
|
||||
userId = msg.userId,
|
||||
name = msg.name,
|
||||
elo = msg.elo,
|
||||
avatarBase64 = msg.avatarBase64 ?: pending?.first,
|
||||
backgroundBase64 = msg.backgroundBase64 ?: pending?.second
|
||||
avatarBase64 = msg.avatarBase64?.let(::acceptedIncomingImage) ?: pending?.first,
|
||||
backgroundBase64 = msg.backgroundBase64?.let(::acceptedIncomingImage) ?: pending?.second
|
||||
)
|
||||
_uiState.value = _uiState.value.copy(
|
||||
opponentProfile = Profile(
|
||||
@@ -1240,7 +1267,6 @@ class GameViewModel : ViewModel() {
|
||||
opponentFlagJob?.cancel()
|
||||
opponentFlagJob = null
|
||||
currentPly = 0
|
||||
lastOpponentRemaining = Long.MAX_VALUE
|
||||
val start = Board.startPosition()
|
||||
resetHistory(start)
|
||||
|
||||
@@ -1349,7 +1375,8 @@ class GameViewModel : ViewModel() {
|
||||
val trimmed = text.trim().take(MAX_CHAT_TEXT_CHARS)
|
||||
if (!sendGameMessage(GameMessage.ChatMsg(text = trimmed, gameId = networkGameId))) return
|
||||
_uiState.value = _uiState.value.copy(
|
||||
chatMessages = _uiState.value.chatMessages + ChatEntry(trimmed, null, fromMe = true)
|
||||
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
|
||||
_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 {
|
||||
var serving = false
|
||||
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")
|
||||
// The game may have ended while the port was opening.
|
||||
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_IMAGE_CHARS = 400_000
|
||||
const val CLOCK_TOLERANCE_MS = 2_000L
|
||||
const val MAX_CHAT_ENTRIES = 200
|
||||
const val HANDSHAKE_TIMEOUT_MS = 20_000L
|
||||
const val OPPONENT_FLAG_GRACE_MS = 4_000L
|
||||
const val LEAVE_FLUSH_MS = 700L
|
||||
|
||||
@@ -7,13 +7,11 @@
|
||||
<string name="greeting_night">Gute Nacht</string>
|
||||
<string name="continue_game_title">Partie fortsetzen</string>
|
||||
<string name="quick_game_title">Schnelles Spiel</string>
|
||||
<string name="quick_game_subtitle">Wie beim letzten Mal: %1$s · %2$s</string>
|
||||
<string name="mode_ai_title">Gegen die KI</string>
|
||||
<string name="mode_ai_subtitle">Schwierigkeit wählen</string>
|
||||
<string name="mode_online_title">Mit einem Freund</string>
|
||||
<string name="mode_online_subtitle">Per Bluetooth oder WLAN in der Nähe</string>
|
||||
<string name="puzzles_title">Schachaufgaben</string>
|
||||
<string name="puzzles_subtitle">Aufgaben passend zu deiner Wertung</string>
|
||||
<string name="stats_dialog_title">Statistik</string>
|
||||
<string name="stats_dialog_summary">%1$d Siege · %2$d%% · Serie: %3$d</string>
|
||||
<string name="stats_min">Min.: %1$d</string>
|
||||
@@ -113,8 +111,16 @@
|
||||
<string name="rating_gate_text">Die Wertung wird gebraucht, um einen passenden Gegner zu wählen und dich anderen Spielern zu zeigen. Es dauert nur ein paar Sekunden.</string>
|
||||
<string name="rating_gate_open">Niveau angeben</string>
|
||||
<string name="about_section">Über die App</string>
|
||||
<string name="appearance_title">Aussehen des Bretts</string>
|
||||
<string name="appearance_subtitle">Brettfarben, Koordinaten, Figurenstil</string>
|
||||
<string name="appearance_title">Darstellung</string>
|
||||
<string name="appearance_subtitle">App-Farben, Brett, Figuren</string>
|
||||
<string name="app_style_title">App-Farben</string>
|
||||
<string name="app_style_matewave">Matewave</string>
|
||||
<string name="app_style_lavender">Lavendel</string>
|
||||
<string name="app_style_peach">Pfirsich</string>
|
||||
<string name="app_style_mint">Minze</string>
|
||||
<string name="app_style_sky">Himmel</string>
|
||||
<string name="app_style_device">Gerät</string>
|
||||
<string name="app_style_device_hint">Die Farben kommen aus deinem Hintergrundbild (Material You) und ändern sich mit ihm.</string>
|
||||
<string name="appearance_board_theme">Brettfarben</string>
|
||||
<string name="appearance_coordinates">Buchstaben und Zahlen auf dem Brett</string>
|
||||
<string name="appearance_coordinates_hint">Feldbeschriftung an den Rändern: a–h und 1–8</string>
|
||||
@@ -128,7 +134,6 @@
|
||||
<string name="account_forget_keys_confirm">Du kannst einen bekannten Gegner dann nicht mehr von jemandem unterscheiden, der seinen Namen benutzt, bis ihr euch erneut trefft. Nötig, wenn der Gegner die App neu installiert hat.</string>
|
||||
<string name="account_confirm">Vergessen</string>
|
||||
<string name="account_cancel">Abbrechen</string>
|
||||
<string name="greeting_ready">Bereit für eine neue Partie?</string>
|
||||
<string name="account_trusted_keys_hint">Werden beim ersten Treffen mit einem neuen Spieler automatisch gespeichert</string>
|
||||
<string name="account_fingerprint_explain">Eindeutiger Fingerabdruck des Schlüssels dieses Geräts. Dein Gegner kann ihn beim ersten Treffen mit deinem vergleichen.</string>
|
||||
<string name="friends_online">Online</string>
|
||||
@@ -323,7 +328,6 @@
|
||||
<string name="settings_section_system">System</string>
|
||||
<string name="permissions_card_ok_short">Alles bereit</string>
|
||||
<string name="permissions_card_blocked_short">Aktion nötig</string>
|
||||
<string name="account_header_summary">Wertung %1$d · Partien: %2$d</string>
|
||||
<string name="account_progress">Fortschritt</string>
|
||||
<string name="account_rating_row">Wertung</string>
|
||||
<string name="account_device_key">Geräteschlüssel</string>
|
||||
|
||||
@@ -7,13 +7,11 @@
|
||||
<string name="greeting_night">おやすみなさい</string>
|
||||
<string name="continue_game_title">対局を続ける</string>
|
||||
<string name="quick_game_title">クイックゲーム</string>
|
||||
<string name="quick_game_subtitle">前回と同じ:%1$s・%2$s</string>
|
||||
<string name="mode_ai_title">AIと対戦</string>
|
||||
<string name="mode_ai_subtitle">難易度を選択</string>
|
||||
<string name="mode_online_title">友達と対戦</string>
|
||||
<string name="mode_online_subtitle">近くでBluetoothまたはWi-Fiで</string>
|
||||
<string name="puzzles_title">チェスパズル</string>
|
||||
<string name="puzzles_subtitle">あなたのレーティングに合った問題</string>
|
||||
<string name="stats_dialog_title">成績</string>
|
||||
<string name="stats_dialog_summary">%1$d勝 · %2$d%% · 連勝: %3$d</string>
|
||||
<string name="stats_min">最小: %1$d</string>
|
||||
@@ -113,8 +111,16 @@
|
||||
<string name="rating_gate_text">レーティングは、適切な相手の選択と他のプレイヤーへの表示に必要です。数秒で完了します。</string>
|
||||
<string name="rating_gate_open">レベルを指定</string>
|
||||
<string name="about_section">このアプリについて</string>
|
||||
<string name="appearance_title">盤の見た目</string>
|
||||
<string name="appearance_subtitle">盤の色、座標、駒のスタイル</string>
|
||||
<string name="appearance_title">外観</string>
|
||||
<string name="appearance_subtitle">アプリの色、盤、駒</string>
|
||||
<string name="app_style_title">アプリの色</string>
|
||||
<string name="app_style_matewave">Matewave</string>
|
||||
<string name="app_style_lavender">ラベンダー</string>
|
||||
<string name="app_style_peach">ピーチ</string>
|
||||
<string name="app_style_mint">ミント</string>
|
||||
<string name="app_style_sky">スカイ</string>
|
||||
<string name="app_style_device">端末</string>
|
||||
<string name="app_style_device_hint">色は壁紙から取得され(Material You)、壁紙に合わせて変わります。</string>
|
||||
<string name="appearance_board_theme">盤の色</string>
|
||||
<string name="appearance_coordinates">盤上の文字と数字</string>
|
||||
<string name="appearance_coordinates_hint">盤の端のマス目ラベル: a〜h と 1〜8</string>
|
||||
@@ -128,7 +134,6 @@
|
||||
<string name="account_forget_keys_confirm">再び会うまで、知っている相手とその名前を名乗る人を区別できなくなります。相手がアプリを再インストールした場合に必要です。</string>
|
||||
<string name="account_confirm">忘れる</string>
|
||||
<string name="account_cancel">キャンセル</string>
|
||||
<string name="greeting_ready">新しい対局の準備はできましたか?</string>
|
||||
<string name="account_trusted_keys_hint">新しいプレイヤーと初めて会ったときに自動で保存されます</string>
|
||||
<string name="account_fingerprint_explain">この端末の鍵の固有のフィンガープリントです。初めて会ったとき、相手があなたのものと照合できます。</string>
|
||||
<string name="friends_online">オンライン</string>
|
||||
@@ -322,7 +327,6 @@
|
||||
<string name="settings_section_system">システム</string>
|
||||
<string name="permissions_card_ok_short">準備完了</string>
|
||||
<string name="permissions_card_blocked_short">要対応</string>
|
||||
<string name="account_header_summary">レーティング %1$d · 対局: %2$d</string>
|
||||
<string name="account_progress">進捗</string>
|
||||
<string name="account_rating_row">レーティング</string>
|
||||
<string name="account_device_key">端末の鍵</string>
|
||||
|
||||
@@ -7,13 +7,11 @@
|
||||
<string name="greeting_night">Labos nakties</string>
|
||||
<string name="continue_game_title">Tęsti partiją</string>
|
||||
<string name="quick_game_title">Greitas žaidimas</string>
|
||||
<string name="quick_game_subtitle">Kaip praėjusį kartą: %1$s · %2$s</string>
|
||||
<string name="mode_ai_title">Prieš DI</string>
|
||||
<string name="mode_ai_subtitle">Pasirinkite sudėtingumą</string>
|
||||
<string name="mode_online_title">Su draugu</string>
|
||||
<string name="mode_online_subtitle">Per „Bluetooth“ arba „Wi-Fi“ netoliese</string>
|
||||
<string name="puzzles_title">Šachmatų galvosūkiai</string>
|
||||
<string name="puzzles_subtitle">Užduotys pagal jūsų reitingą</string>
|
||||
<string name="stats_dialog_title">Statistika</string>
|
||||
<string name="stats_dialog_summary">%1$d pergalių · %2$d%% · serija: %3$d</string>
|
||||
<string name="stats_min">Min.: %1$d</string>
|
||||
@@ -113,8 +111,16 @@
|
||||
<string name="rating_gate_text">Reitingas reikalingas tinkamam varžovui parinkti ir kitiems žaidėjams jus parodyti. Tai užtrunka porą sekundžių.</string>
|
||||
<string name="rating_gate_open">Nurodyti lygį</string>
|
||||
<string name="about_section">Apie programą</string>
|
||||
<string name="appearance_title">Lentos išvaizda</string>
|
||||
<string name="appearance_subtitle">Lentos spalvos, koordinatės, figūrų stilius</string>
|
||||
<string name="appearance_title">Išvaizda</string>
|
||||
<string name="appearance_subtitle">Programėlės spalvos, lenta, figūros</string>
|
||||
<string name="app_style_title">Programėlės spalvos</string>
|
||||
<string name="app_style_matewave">Matewave</string>
|
||||
<string name="app_style_lavender">Levanda</string>
|
||||
<string name="app_style_peach">Persikas</string>
|
||||
<string name="app_style_mint">Mėta</string>
|
||||
<string name="app_style_sky">Dangus</string>
|
||||
<string name="app_style_device">Įrenginys</string>
|
||||
<string name="app_style_device_hint">Spalvos paimamos iš ekrano fono („Material You“) ir keičiasi kartu su juo.</string>
|
||||
<string name="appearance_board_theme">Lentos spalvos</string>
|
||||
<string name="appearance_coordinates">Raidės ir skaičiai ant lentos</string>
|
||||
<string name="appearance_coordinates_hint">Langelių žymos pakraščiuose: a–h ir 1–8</string>
|
||||
@@ -128,7 +134,6 @@
|
||||
<string name="account_forget_keys_confirm">Nebegalėsite atskirti pažįstamo varžovo nuo to, kas naudoja jo vardą, kol vėl nesusitiksite. Reikia, jei varžovas iš naujo įdiegė programą.</string>
|
||||
<string name="account_confirm">Pamiršti</string>
|
||||
<string name="account_cancel">Atšaukti</string>
|
||||
<string name="greeting_ready">Pasiruošę naujai partijai?</string>
|
||||
<string name="account_trusted_keys_hint">Išsaugomi automatiškai pirmą kartą sutikus naują žaidėją</string>
|
||||
<string name="account_fingerprint_explain">Unikalus šio įrenginio rakto kontrolinis kodas. Pirmą kartą susitikęs varžovas gali jį palyginti su jūsų.</string>
|
||||
<string name="friends_online">Prisijungęs</string>
|
||||
@@ -325,7 +330,6 @@
|
||||
<string name="settings_section_system">Sistema</string>
|
||||
<string name="permissions_card_ok_short">Viskas paruošta</string>
|
||||
<string name="permissions_card_blocked_short">Reikia veiksmo</string>
|
||||
<string name="account_header_summary">Reitingas %1$d · Partijų: %2$d</string>
|
||||
<string name="account_progress">Pažanga</string>
|
||||
<string name="account_rating_row">Reitingas</string>
|
||||
<string name="account_device_key">Įrenginio raktas</string>
|
||||
|
||||
@@ -9,14 +9,12 @@
|
||||
|
||||
<string name="continue_game_title">Продолжить партию</string>
|
||||
<string name="quick_game_title">Быстрая игра</string>
|
||||
<string name="quick_game_subtitle">Как в прошлый раз: %1$s · %2$s</string>
|
||||
<string name="mode_ai_title">Против ИИ</string>
|
||||
<string name="mode_ai_subtitle">Выберите сложность</string>
|
||||
<string name="mode_online_title">С другом</string>
|
||||
<string name="mode_online_subtitle">По Bluetooth или Wi-Fi рядом</string>
|
||||
|
||||
<string name="puzzles_title">Шахматные задачи</string>
|
||||
<string name="puzzles_subtitle">Задачи под ваш рейтинг</string>
|
||||
<string name="stats_dialog_title">Статистика</string>
|
||||
<string name="stats_dialog_summary">%1$d побед · %2$d%% · серия: %3$d</string>
|
||||
<string name="stats_min">Мин: %1$d</string>
|
||||
@@ -118,8 +116,16 @@
|
||||
<string name="rating_gate_text">Рейтинг нужен, чтобы подобрать сложность соперника и показать вас другим игрокам. Это займёт пару секунд.</string>
|
||||
<string name="rating_gate_open">Указать уровень</string>
|
||||
<string name="about_section">О программе</string>
|
||||
<string name="appearance_title">Внешний вид доски</string>
|
||||
<string name="appearance_subtitle">Цвета доски, координаты, вид фигур</string>
|
||||
<string name="appearance_title">Оформление</string>
|
||||
<string name="appearance_subtitle">Цвета приложения, доска, фигуры</string>
|
||||
<string name="app_style_title">Цвета приложения</string>
|
||||
<string name="app_style_matewave">Matewave</string>
|
||||
<string name="app_style_lavender">Лаванда</string>
|
||||
<string name="app_style_peach">Персик</string>
|
||||
<string name="app_style_mint">Мята</string>
|
||||
<string name="app_style_sky">Небо</string>
|
||||
<string name="app_style_device">Устройство</string>
|
||||
<string name="app_style_device_hint">Цвета берутся из обоев (Material You) и меняются вместе с ними.</string>
|
||||
<string name="appearance_board_theme">Цвета доски</string>
|
||||
<string name="appearance_coordinates">Буквы и цифры на доске</string>
|
||||
<string name="appearance_coordinates_hint">Подписи полей по краям: a–h и 1–8</string>
|
||||
@@ -133,7 +139,6 @@
|
||||
<string name="account_forget_keys_confirm">Вы перестанете отличать знакомого соперника от того, кто назвался его именем, пока не встретитесь с ним заново. Нужно, если соперник переустановил приложение.</string>
|
||||
<string name="account_confirm">Забыть</string>
|
||||
<string name="account_cancel">Отмена</string>
|
||||
<string name="greeting_ready">Готовы к новой партии?</string>
|
||||
<string name="account_trusted_keys_hint">Запоминаются автоматически при первой встрече с новым игроком</string>
|
||||
<string name="account_fingerprint_explain">Уникальный отпечаток ключа этого устройства. Соперник может сверить его с вашим при первой встрече.</string>
|
||||
<string name="friends_online">В сети</string>
|
||||
@@ -331,7 +336,6 @@
|
||||
<string name="settings_section_system">Система</string>
|
||||
<string name="permissions_card_ok_short">Всё готово</string>
|
||||
<string name="permissions_card_blocked_short">Нужно действие</string>
|
||||
<string name="account_header_summary">Рейтинг %1$d · Партий: %2$d</string>
|
||||
<string name="account_progress">Прогресс</string>
|
||||
<string name="account_rating_row">Рейтинг</string>
|
||||
<string name="account_device_key">Ключ устройства</string>
|
||||
|
||||
@@ -7,13 +7,11 @@
|
||||
<string name="greeting_night">晚安</string>
|
||||
<string name="continue_game_title">继续对局</string>
|
||||
<string name="quick_game_title">快速对局</string>
|
||||
<string name="quick_game_subtitle">与上次相同:%1$s · %2$s</string>
|
||||
<string name="mode_ai_title">对战 AI</string>
|
||||
<string name="mode_ai_subtitle">选择难度</string>
|
||||
<string name="mode_online_title">好友对战</string>
|
||||
<string name="mode_online_subtitle">通过蓝牙或附近的 Wi-Fi</string>
|
||||
<string name="puzzles_title">国际象棋谜题</string>
|
||||
<string name="puzzles_subtitle">按你的等级分挑选的谜题</string>
|
||||
<string name="stats_dialog_title">统计</string>
|
||||
<string name="stats_dialog_summary">%1$d 胜 · %2$d%% · 连胜:%3$d</string>
|
||||
<string name="stats_min">最低:%1$d</string>
|
||||
@@ -113,8 +111,16 @@
|
||||
<string name="rating_gate_text">需要等级分来匹配合适的对手,并向其他玩家展示你。只需几秒钟。</string>
|
||||
<string name="rating_gate_open">设置水平</string>
|
||||
<string name="about_section">关于</string>
|
||||
<string name="appearance_title">棋盘外观</string>
|
||||
<string name="appearance_subtitle">棋盘颜色、坐标、棋子样式</string>
|
||||
<string name="appearance_title">外观</string>
|
||||
<string name="appearance_subtitle">应用配色、棋盘、棋子</string>
|
||||
<string name="app_style_title">应用配色</string>
|
||||
<string name="app_style_matewave">Matewave</string>
|
||||
<string name="app_style_lavender">薰衣草</string>
|
||||
<string name="app_style_peach">蜜桃</string>
|
||||
<string name="app_style_mint">薄荷</string>
|
||||
<string name="app_style_sky">天空</string>
|
||||
<string name="app_style_device">设备</string>
|
||||
<string name="app_style_device_hint">颜色取自壁纸(Material You),并随壁纸变化。</string>
|
||||
<string name="appearance_board_theme">棋盘颜色</string>
|
||||
<string name="appearance_coordinates">棋盘上的字母和数字</string>
|
||||
<string name="appearance_coordinates_hint">边缘的格子标注:a–h 和 1–8</string>
|
||||
@@ -128,7 +134,6 @@
|
||||
<string name="account_forget_keys_confirm">在再次见面之前,你将无法区分熟悉的对手和冒用其名字的人。如果对手重装了应用,则需要这样做。</string>
|
||||
<string name="account_confirm">忘记</string>
|
||||
<string name="account_cancel">取消</string>
|
||||
<string name="greeting_ready">准备好开始新对局了吗?</string>
|
||||
<string name="account_trusted_keys_hint">首次遇到新玩家时自动保存</string>
|
||||
<string name="account_fingerprint_explain">此设备密钥的唯一指纹。首次见面时,对手可以将其与你的核对。</string>
|
||||
<string name="friends_online">在线</string>
|
||||
@@ -322,7 +327,6 @@
|
||||
<string name="settings_section_system">系统</string>
|
||||
<string name="permissions_card_ok_short">已就绪</string>
|
||||
<string name="permissions_card_blocked_short">需要处理</string>
|
||||
<string name="account_header_summary">等级分 %1$d · 对局:%2$d</string>
|
||||
<string name="account_progress">进度</string>
|
||||
<string name="account_rating_row">等级分</string>
|
||||
<string name="account_device_key">设备密钥</string>
|
||||
|
||||
@@ -7,13 +7,11 @@
|
||||
<string name="greeting_night">Good night</string>
|
||||
<string name="continue_game_title">Continue game</string>
|
||||
<string name="quick_game_title">Quick game</string>
|
||||
<string name="quick_game_subtitle">Same as last time: %1$s · %2$s</string>
|
||||
<string name="mode_ai_title">Vs AI</string>
|
||||
<string name="mode_ai_subtitle">Choose difficulty</string>
|
||||
<string name="mode_online_title">Vs a friend</string>
|
||||
<string name="mode_online_subtitle">Over Bluetooth or Wi-Fi nearby</string>
|
||||
<string name="puzzles_title">Chess puzzles</string>
|
||||
<string name="puzzles_subtitle">Puzzles picked for your rating</string>
|
||||
<string name="stats_dialog_title">Statistics</string>
|
||||
<string name="stats_dialog_summary">%1$d wins · %2$d%% · streak: %3$d</string>
|
||||
<string name="stats_min">Min: %1$d</string>
|
||||
@@ -113,8 +111,16 @@
|
||||
<string name="rating_gate_text">Your rating is needed to pick a suitable opponent and to show you to other players. It takes a couple of seconds.</string>
|
||||
<string name="rating_gate_open">Set level</string>
|
||||
<string name="about_section">About</string>
|
||||
<string name="appearance_title">Board appearance</string>
|
||||
<string name="appearance_subtitle">Board colors, coordinates, piece style</string>
|
||||
<string name="appearance_title">Appearance</string>
|
||||
<string name="appearance_subtitle">App colors, board, pieces</string>
|
||||
<string name="app_style_title">App colors</string>
|
||||
<string name="app_style_matewave">Matewave</string>
|
||||
<string name="app_style_lavender">Lavender</string>
|
||||
<string name="app_style_peach">Peach</string>
|
||||
<string name="app_style_mint">Mint</string>
|
||||
<string name="app_style_sky">Sky</string>
|
||||
<string name="app_style_device">Device</string>
|
||||
<string name="app_style_device_hint">Colors are taken from your wallpaper (Material You) and change with it.</string>
|
||||
<string name="appearance_board_theme">Board colors</string>
|
||||
<string name="appearance_coordinates">Letters and numbers on the board</string>
|
||||
<string name="appearance_coordinates_hint">Square labels along the edges: a–h and 1–8</string>
|
||||
@@ -128,7 +134,6 @@
|
||||
<string name="account_forget_keys_confirm">You will no longer be able to tell a familiar opponent from someone using their name until you meet again. Needed if the opponent reinstalled the app.</string>
|
||||
<string name="account_confirm">Forget</string>
|
||||
<string name="account_cancel">Cancel</string>
|
||||
<string name="greeting_ready">Ready for a new game?</string>
|
||||
<string name="account_trusted_keys_hint">Saved automatically the first time you meet a new player</string>
|
||||
<string name="account_fingerprint_explain">The unique fingerprint of this device\'s key. Your opponent can compare it with yours when you first meet.</string>
|
||||
<string name="friends_online">Online</string>
|
||||
@@ -323,7 +328,6 @@
|
||||
<string name="settings_section_system">System</string>
|
||||
<string name="permissions_card_ok_short">All set</string>
|
||||
<string name="permissions_card_blocked_short">Action needed</string>
|
||||
<string name="account_header_summary">Rating %1$d · Games: %2$d</string>
|
||||
<string name="account_progress">Progress</string>
|
||||
<string name="account_rating_row">Rating</string>
|
||||
<string name="account_device_key">Device key</string>
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<locale-config xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<locale android:name="en" />
|
||||
<locale android:name="de" />
|
||||
<locale android:name="ja" />
|
||||
<locale android:name="lt" />
|
||||
<locale android:name="ru" />
|
||||
<locale android:name="zh" />
|
||||
</locale-config>
|
||||
@@ -0,0 +1,55 @@
|
||||
package cc.skysparkle.matewave
|
||||
|
||||
import cc.skysparkle.matewave.network.GameMessage
|
||||
import cc.skysparkle.matewave.network.PeerLimits
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class PeerLimitsTest {
|
||||
private fun profile(
|
||||
userId: String = "6f1c2a9e-0b3d-4c5e-8f70-1a2b3c4d5e6f",
|
||||
name: String = "Vladimir",
|
||||
elo: Int = 1350,
|
||||
initialSeconds: Int = 300,
|
||||
incrementSeconds: Int = 3
|
||||
) = GameMessage.ProfileMsg(
|
||||
userId = userId, name = name, avatarBase64 = null, backgroundBase64 = null, elo = elo,
|
||||
initialSeconds = initialSeconds, incrementSeconds = incrementSeconds
|
||||
)
|
||||
|
||||
@Test fun ordinaryProfileIsAccepted() = assertTrue(PeerLimits.isPlausibleProfile(profile()))
|
||||
|
||||
@Test fun joiningPlayerWithoutTimeControlIsAccepted() =
|
||||
assertTrue(PeerLimits.isPlausibleProfile(profile(initialSeconds = 0, incrementSeconds = 0)))
|
||||
|
||||
@Test fun unlimitedGameIsAccepted() =
|
||||
assertTrue(PeerLimits.isPlausibleProfile(profile(initialSeconds = Int.MAX_VALUE, incrementSeconds = 0)))
|
||||
|
||||
@Test
|
||||
fun oversizedOrEmptyFieldsAreRefused() {
|
||||
assertFalse(PeerLimits.isPlausibleProfile(profile(name = "x".repeat(PeerLimits.MAX_NAME_CHARS + 1))))
|
||||
assertFalse(PeerLimits.isPlausibleProfile(profile(name = " ")))
|
||||
assertFalse(PeerLimits.isPlausibleProfile(profile(name = "a\u0000b")))
|
||||
assertFalse(PeerLimits.isPlausibleProfile(profile(userId = "u".repeat(PeerLimits.MAX_USER_ID_CHARS + 1))))
|
||||
assertFalse(PeerLimits.isPlausibleProfile(profile(userId = "")))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun ratingAndTimeControlMustBeInRange() {
|
||||
assertFalse(PeerLimits.isPlausibleProfile(profile(elo = 99)))
|
||||
assertFalse(PeerLimits.isPlausibleProfile(profile(elo = 3001)))
|
||||
assertFalse(PeerLimits.isPlausibleProfile(profile(initialSeconds = -1)))
|
||||
assertFalse(PeerLimits.isPlausibleProfile(profile(initialSeconds = PeerLimits.MAX_INITIAL_SECONDS + 1)))
|
||||
assertFalse(PeerLimits.isPlausibleProfile(profile(incrementSeconds = PeerLimits.MAX_INCREMENT_SECONDS + 1)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun opponentClockMayNotGrowBeyondIncrementAndSlack() {
|
||||
assertEquals(47_000L, PeerLimits.maxOpponentClockAfterMove(42_000, 3_000, 2_000))
|
||||
// A flagged opponent (0 ms locally) may still have had a little time on their side.
|
||||
assertEquals(5_000L, PeerLimits.maxOpponentClockAfterMove(0, 3_000, 2_000))
|
||||
assertEquals(2_000L, PeerLimits.maxOpponentClockAfterMove(-50, 0, 2_000))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package cc.skysparkle.matewave
|
||||
|
||||
import cc.skysparkle.matewave.network.LanTransport
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNotEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class PresenceSignatureTest {
|
||||
private val now = 1_800_000_000_000L
|
||||
private val nowSeconds = now / 1000
|
||||
|
||||
@Test fun recentAnnouncementIsFresh() =
|
||||
assertTrue(LanTransport.isFreshPresence(nowSeconds - 4 * 60, now))
|
||||
|
||||
@Test fun slightlyFastClockIsTolerated() =
|
||||
assertTrue(LanTransport.isFreshPresence(nowSeconds + 5 * 60, now))
|
||||
|
||||
@Test
|
||||
fun oldMissingOrFarFutureAnnouncementsAreRejected() {
|
||||
assertFalse(LanTransport.isFreshPresence(nowSeconds - 16 * 60, now))
|
||||
assertFalse(LanTransport.isFreshPresence(nowSeconds + 16 * 60, now))
|
||||
assertFalse(LanTransport.isFreshPresence(0, now))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun signingTimeIsPartOfTheSignedText() = assertNotEquals(
|
||||
LanTransport.presencePayload("u1", "Vladimir", 1350, nowSeconds),
|
||||
LanTransport.presencePayload("u1", "Vladimir", 1350, nowSeconds - 60)
|
||||
)
|
||||
}
|
||||
+2
-2
@@ -1,4 +1,4 @@
|
||||
plugins {
|
||||
id("com.android.application") version "9.2.0" apply false
|
||||
id("org.jetbrains.kotlin.plugin.compose") version "2.4.20" apply false
|
||||
alias(libs.plugins.android.application) apply false
|
||||
alias(libs.plugins.kotlin.compose) apply false
|
||||
}
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
• Darstellung: App-Farben wählbar — Matewave, die Pastelltöne Lavendel, Pfirsich, Minze und Himmel oder Gerätefarben aus dem Hintergrundbild (Material You, Android 12+)
|
||||
• Die Wertung auf dem Startbildschirm öffnet keine Statistik mehr
|
||||
• Die Beschriftungen von Remis- und Aufgabe-Schaltfläche werden nicht mehr abgeschnitten
|
||||
@@ -0,0 +1,6 @@
|
||||
• Bilder des Gegners werden geprüft: zu große Avatare, Hintergründe oder Chatbilder bringen die App nicht mehr zum Absturz
|
||||
• Der Gegner kann verbrauchte Zeit nicht verbergen; sein Inkrement zählt nicht mehr doppelt
|
||||
• Warnung, wenn nicht der gewählte Spieler in der Nähe antwortet
|
||||
• App-Sprache in den Android-Einstellungen wählbar (Android 13+)
|
||||
• Schnellerer Start mit vielen Freunden, weniger Akku für Bluetooth
|
||||
• WLAN-Präsenz ist nicht mit 1.0.50 kompatibel: beide Handys aktualisieren
|
||||
@@ -0,0 +1,3 @@
|
||||
• Appearance: choose the app colors — Matewave, pastel Lavender, Peach, Mint and Sky, or Device colors from your wallpaper (Material You, Android 12+)
|
||||
• The rating on the home screen no longer opens statistics
|
||||
• Labels on the draw and resign buttons are no longer cut off
|
||||
@@ -0,0 +1,6 @@
|
||||
• Pictures from the opponent are checked first: an oversized avatar, background or chat image no longer crashes the app
|
||||
• The opponent's clock can't hide time spent; their increment is no longer counted twice
|
||||
• A warning if someone other than the chosen nearby player answers
|
||||
• App language can be set in Android settings (Android 13+)
|
||||
• Faster start with many friends, less battery for Bluetooth presence
|
||||
• Wi-Fi presence is not compatible with 1.0.50: update both phones
|
||||
@@ -0,0 +1,3 @@
|
||||
• 外観:アプリの色を選択可能に — Matewave、パステルのラベンダー・ピーチ・ミント・スカイ、または壁紙から取得する端末の色(Material You、Android 12 以降)
|
||||
• ホーム画面のレーティングをタップしても統計が開かなくなりました
|
||||
• 引き分け・投了ボタンの文字が切れにくくなりました
|
||||
@@ -0,0 +1,6 @@
|
||||
• 相手の画像を事前に確認:巨大なアバター、背景、チャット画像でアプリが落ちなくなりました
|
||||
• 相手が消費時間を隠せなくなり、相手の加算時間が二重に数えられなくなりました
|
||||
• 近くで選んだ相手以外が応答したときに警告
|
||||
• Android の設定でアプリの言語を選択可能に(Android 13 以降)
|
||||
• 友達が多くても起動が速く、Bluetooth の電池消費も減少
|
||||
• Wi-Fi の在席表示は 1.0.50 と互換性がありません:両方の端末を更新してください
|
||||
@@ -0,0 +1,3 @@
|
||||
• Išvaizda: galima pasirinkti programėlės spalvas — Matewave, pastelines Levandą, Persiką, Mėtą ir Dangų arba įrenginio spalvas iš ekrano fono („Material You“, Android 12+)
|
||||
• Reitingas pagrindiniame ekrane nebeatidaro statistikos
|
||||
• Lygiųjų ir pasidavimo mygtukų užrašai nebenukerpami
|
||||
@@ -0,0 +1,6 @@
|
||||
• Varžovo paveikslėliai tikrinami: per didelis avataras, fonas ar pokalbio paveikslėlis nebeužlaužia programėlės
|
||||
• Varžovas negali nuslėpti sunaudoto laiko; jo priedas nebeskaičiuojamas dukart
|
||||
• Įspėjimas, jei atsiliepė ne tas netoliese pasirinktas žaidėjas
|
||||
• Programėlės kalbą galima pasirinkti Android nustatymuose (13+)
|
||||
• Greitesnis paleidimas su daug draugų, mažiau baterijos per Bluetooth
|
||||
• Buvimas per Wi-Fi nesuderinamas su 1.0.50: atnaujinkite abu telefonus
|
||||
@@ -0,0 +1,3 @@
|
||||
• Оформление: выбор цветов приложения — Matewave, пастельные Лаванда, Персик, Мята и Небо или цвета устройства из обоев (Material You, Android 12+)
|
||||
• Рейтинг на главном экране больше не открывает статистику
|
||||
• Подписи на кнопках ничьей и сдачи больше не обрезаются
|
||||
@@ -0,0 +1,6 @@
|
||||
• Картинки соперника проверяются: огромный аватар, фон или картинка в чате больше не роняют приложение
|
||||
• Соперник не может скрыть потраченное время; его инкремент больше не учитывается дважды
|
||||
• Предупреждение, если ответил не тот игрок, которого вы выбрали рядом
|
||||
• Язык приложения можно выбрать в настройках Android (13+)
|
||||
• Быстрее запуск со многими друзьями, меньше расход батареи по Bluetooth
|
||||
• Присутствие по Wi-Fi несовместимо с 1.0.50: обновите оба телефона
|
||||
@@ -0,0 +1,3 @@
|
||||
• 外观:可选择应用配色 — Matewave、柔和的薰衣草、蜜桃、薄荷和天空,或取自壁纸的设备颜色(Material You,Android 12 及以上)
|
||||
• 点击主页上的等级分不再打开统计
|
||||
• 提议和棋与认输按钮的文字不再被截断
|
||||
@@ -0,0 +1,6 @@
|
||||
• 先检查对手发来的图片:过大的头像、背景或聊天图片不再导致应用崩溃
|
||||
• 对手无法隐瞒已用时间;对手的加秒不再被重复计算
|
||||
• 应答者不是附近列表中所选玩家时会发出警告
|
||||
• 可在 Android 设置中选择应用语言(Android 13 及以上)
|
||||
• 好友多时启动更快,蓝牙在线显示更省电
|
||||
• Wi-Fi 在线显示与 1.0.50 不兼容:请更新双方手机
|
||||
@@ -0,0 +1,29 @@
|
||||
[versions]
|
||||
agp = "9.2.0"
|
||||
kotlin = "2.4.20"
|
||||
composeBom = "2026.09.00"
|
||||
activityCompose = "1.13.0"
|
||||
coreKtx = "1.18.0"
|
||||
navigationCompose = "2.9.7"
|
||||
lifecycleViewmodelCompose = "2.11.0"
|
||||
kotlinxCoroutines = "1.11.0"
|
||||
zxing = "3.5.4"
|
||||
junit = "4.13.2"
|
||||
orgJson = "20240303"
|
||||
|
||||
[libraries]
|
||||
androidx-compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "composeBom" }
|
||||
androidx-compose-material3 = { group = "androidx.compose.material3", name = "material3" }
|
||||
androidx-compose-ui = { group = "androidx.compose.ui", name = "ui" }
|
||||
androidx-activity-compose = { group = "androidx.activity", name = "activity-compose", version.ref = "activityCompose" }
|
||||
androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
|
||||
androidx-navigation-compose = { group = "androidx.navigation", name = "navigation-compose", version.ref = "navigationCompose" }
|
||||
androidx-lifecycle-viewmodel-compose = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-compose", version.ref = "lifecycleViewmodelCompose" }
|
||||
kotlinx-coroutines-android = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-android", version.ref = "kotlinxCoroutines" }
|
||||
zxing-core = { group = "com.google.zxing", name = "core", version.ref = "zxing" }
|
||||
junit = { group = "junit", name = "junit", version.ref = "junit" }
|
||||
org-json = { group = "org.json", name = "json", version.ref = "orgJson" }
|
||||
|
||||
[plugins]
|
||||
android-application = { id = "com.android.application", version.ref = "agp" }
|
||||
kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
|
||||
+1
@@ -1,5 +1,6 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionSha256Sum=acd53f1edaf02f1a8ff99879f8a34b302661a057d9b063ae9e35b552f804d20a
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-9.7.1-bin.zip
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
|
||||
Reference in New Issue
Block a user