diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 490103c..a3dc375 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -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 { @@ -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) } diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro index ffb2e7a..eb31172 100644 --- a/app/proguard-rules.pro +++ b/app/proguard-rules.pro @@ -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(...); +} diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 44380ff..e2ed4bf 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -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"> diff --git a/app/src/main/java/cc/skysparkle/matewave/network/BleTransport.kt b/app/src/main/java/cc/skysparkle/matewave/network/BleTransport.kt index 0e2be96..e47e5dc 100644 --- a/app/src/main/java/cc/skysparkle/matewave/network/BleTransport.kt +++ b/app/src/main/java/cc/skysparkle/matewave/network/BleTransport.kt @@ -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 } diff --git a/app/src/main/java/cc/skysparkle/matewave/network/LanTransport.kt b/app/src/main/java/cc/skysparkle/matewave/network/LanTransport.kt index 9664d42..a4425fa 100644 --- a/app/src/main/java/cc/skysparkle/matewave/network/LanTransport.kt +++ b/app/src/main/java/cc/skysparkle/matewave/network/LanTransport.kt @@ -72,7 +72,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 +83,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 diff --git a/app/src/main/java/cc/skysparkle/matewave/network/NetworkLog.kt b/app/src/main/java/cc/skysparkle/matewave/network/NetworkLog.kt index af79232..1e219e3 100644 --- a/app/src/main/java/cc/skysparkle/matewave/network/NetworkLog.kt +++ b/app/src/main/java/cc/skysparkle/matewave/network/NetworkLog.kt @@ -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>(emptyList()) - private val _lastReason = MutableStateFlow(DisconnectReason.NONE) val lastReason: StateFlow = _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) { diff --git a/app/src/main/java/cc/skysparkle/matewave/share/ApkShareServer.kt b/app/src/main/java/cc/skysparkle/matewave/share/ApkShareServer.kt index 82021fa..3d8f1ed 100644 --- a/app/src/main/java/cc/skysparkle/matewave/share/ApkShareServer.kt +++ b/app/src/main/java/cc/skysparkle/matewave/share/ApkShareServer.kt @@ -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() .firstOrNull { it.isSiteLocalAddress } - ?.hostAddress }.getOrNull() + + fun wifiIpv4(): String? = wifiInet4()?.hostAddress } diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 2691bda..507afaf 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -7,13 +7,11 @@ Gute Nacht Partie fortsetzen Schnelles Spiel - Wie beim letzten Mal: %1$s · %2$s Gegen die KI Schwierigkeit wählen Mit einem Freund Per Bluetooth oder WLAN in der Nähe Schachaufgaben - Aufgaben passend zu deiner Wertung Statistik %1$d Siege · %2$d%% · Serie: %3$d Min.: %1$d @@ -136,7 +134,6 @@ 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. Vergessen Abbrechen - Bereit für eine neue Partie? Werden beim ersten Treffen mit einem neuen Spieler automatisch gespeichert Eindeutiger Fingerabdruck des Schlüssels dieses Geräts. Dein Gegner kann ihn beim ersten Treffen mit deinem vergleichen. Online @@ -331,7 +328,6 @@ System Alles bereit Aktion nötig - Wertung %1$d · Partien: %2$d Fortschritt Wertung Geräteschlüssel diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index c5de98d..3ddc9fa 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -7,13 +7,11 @@ おやすみなさい 対局を続ける クイックゲーム - 前回と同じ:%1$s・%2$s AIと対戦 難易度を選択 友達と対戦 近くでBluetoothまたはWi-Fiで チェスパズル - あなたのレーティングに合った問題 成績 %1$d勝 · %2$d%% · 連勝: %3$d 最小: %1$d @@ -136,7 +134,6 @@ 再び会うまで、知っている相手とその名前を名乗る人を区別できなくなります。相手がアプリを再インストールした場合に必要です。 忘れる キャンセル - 新しい対局の準備はできましたか? 新しいプレイヤーと初めて会ったときに自動で保存されます この端末の鍵の固有のフィンガープリントです。初めて会ったとき、相手があなたのものと照合できます。 オンライン @@ -330,7 +327,6 @@ システム 準備完了 要対応 - レーティング %1$d · 対局: %2$d 進捗 レーティング 端末の鍵 diff --git a/app/src/main/res/values-lt/strings.xml b/app/src/main/res/values-lt/strings.xml index 236adc3..7562636 100644 --- a/app/src/main/res/values-lt/strings.xml +++ b/app/src/main/res/values-lt/strings.xml @@ -7,13 +7,11 @@ Labos nakties Tęsti partiją Greitas žaidimas - Kaip praėjusį kartą: %1$s · %2$s Prieš DI Pasirinkite sudėtingumą Su draugu Per „Bluetooth“ arba „Wi-Fi“ netoliese Šachmatų galvosūkiai - Užduotys pagal jūsų reitingą Statistika %1$d pergalių · %2$d%% · serija: %3$d Min.: %1$d @@ -136,7 +134,6 @@ 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ą. Pamiršti Atšaukti - Pasiruošę naujai partijai? Išsaugomi automatiškai pirmą kartą sutikus naują žaidėją Unikalus šio įrenginio rakto kontrolinis kodas. Pirmą kartą susitikęs varžovas gali jį palyginti su jūsų. Prisijungęs @@ -333,7 +330,6 @@ Sistema Viskas paruošta Reikia veiksmo - Reitingas %1$d · Partijų: %2$d Pažanga Reitingas Įrenginio raktas diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 56a67f5..e06ed08 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -9,14 +9,12 @@ Продолжить партию Быстрая игра - Как в прошлый раз: %1$s · %2$s Против ИИ Выберите сложность С другом По Bluetooth или Wi-Fi рядом Шахматные задачи - Задачи под ваш рейтинг Статистика %1$d побед · %2$d%% · серия: %3$d Мин: %1$d @@ -141,7 +139,6 @@ Вы перестанете отличать знакомого соперника от того, кто назвался его именем, пока не встретитесь с ним заново. Нужно, если соперник переустановил приложение. Забыть Отмена - Готовы к новой партии? Запоминаются автоматически при первой встрече с новым игроком Уникальный отпечаток ключа этого устройства. Соперник может сверить его с вашим при первой встрече. В сети @@ -339,7 +336,6 @@ Система Всё готово Нужно действие - Рейтинг %1$d · Партий: %2$d Прогресс Рейтинг Ключ устройства diff --git a/app/src/main/res/values-zh/strings.xml b/app/src/main/res/values-zh/strings.xml index 67062ec..36a0a63 100644 --- a/app/src/main/res/values-zh/strings.xml +++ b/app/src/main/res/values-zh/strings.xml @@ -7,13 +7,11 @@ 晚安 继续对局 快速对局 - 与上次相同:%1$s · %2$s 对战 AI 选择难度 好友对战 通过蓝牙或附近的 Wi-Fi 国际象棋谜题 - 按你的等级分挑选的谜题 统计 %1$d 胜 · %2$d%% · 连胜:%3$d 最低:%1$d @@ -136,7 +134,6 @@ 在再次见面之前,你将无法区分熟悉的对手和冒用其名字的人。如果对手重装了应用,则需要这样做。 忘记 取消 - 准备好开始新对局了吗? 首次遇到新玩家时自动保存 此设备密钥的唯一指纹。首次见面时,对手可以将其与你的核对。 在线 @@ -330,7 +327,6 @@ 系统 已就绪 需要处理 - 等级分 %1$d · 对局:%2$d 进度 等级分 设备密钥 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 803999f..95cbdcb 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -7,13 +7,11 @@ Good night Continue game Quick game - Same as last time: %1$s · %2$s Vs AI Choose difficulty Vs a friend Over Bluetooth or Wi-Fi nearby Chess puzzles - Puzzles picked for your rating Statistics %1$d wins · %2$d%% · streak: %3$d Min: %1$d @@ -136,7 +134,6 @@ 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. Forget Cancel - Ready for a new game? Saved automatically the first time you meet a new player The unique fingerprint of this device\'s key. Your opponent can compare it with yours when you first meet. Online @@ -331,7 +328,6 @@ System All set Action needed - Rating %1$d · Games: %2$d Progress Rating Device key diff --git a/app/src/main/res/xml/locales_config.xml b/app/src/main/res/xml/locales_config.xml new file mode 100644 index 0000000..61b019d --- /dev/null +++ b/app/src/main/res/xml/locales_config.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/build.gradle.kts b/build.gradle.kts index 19bda35..020183f 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -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 } diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml new file mode 100644 index 0000000..15d5808 --- /dev/null +++ b/gradle/libs.versions.toml @@ -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" } diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index c56b367..aa29bbc 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -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