diff --git a/Cargo.lock b/Cargo.lock index aa1e682..7ec29fa 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2405,6 +2405,7 @@ dependencies = [ "chess-import", "shakmaty", "thiserror 2.0.21", + "uci", "uniffi", ] diff --git a/androidApp/.gitignore b/androidApp/.gitignore new file mode 100644 index 0000000..aa724b7 --- /dev/null +++ b/androidApp/.gitignore @@ -0,0 +1,15 @@ +*.iml +.gradle +/local.properties +/.idea/caches +/.idea/libraries +/.idea/modules.xml +/.idea/workspace.xml +/.idea/navEditor.xml +/.idea/assetWizardSettings.xml +.DS_Store +/build +/captures +.externalNativeBuild +.cxx +local.properties diff --git a/androidApp/app/.gitignore b/androidApp/app/.gitignore new file mode 100644 index 0000000..42afabf --- /dev/null +++ b/androidApp/app/.gitignore @@ -0,0 +1 @@ +/build \ No newline at end of file diff --git a/androidApp/app/build.gradle.kts b/androidApp/app/build.gradle.kts new file mode 100644 index 0000000..1125e3f --- /dev/null +++ b/androidApp/app/build.gradle.kts @@ -0,0 +1,191 @@ +// ChessPenguin for Android (docs/design/android-ui.md, docs/research/android-stack.md): +// the interface in Kotlin + Jetpack Compose, the reading of databases in the Rust core +// of the desktop app (crates/mobile-api), bound with UniFFI. +plugins { + alias(libs.plugins.android.application) + alias(libs.plugins.compose.compiler) + alias(libs.plugins.kotlin.serialization) +} + +/// The repository root: the Rust workspace, the sample games, the piece sets. +val repo: File = rootDir.parentFile +val cargoOut = layout.buildDirectory.dir("rust/ndk") +val rustLibs = layout.buildDirectory.dir("rust/jniLibs") +val bindings = layout.buildDirectory.dir("generated/uniffi") +val bundled = layout.buildDirectory.dir("generated/assets") +val ndkHome = System.getenv("ANDROID_NDK_HOME") + ?: "${System.getenv("ANDROID_HOME") ?: "${System.getProperty("user.home")}/Android/Sdk"}/ndk/30.0.16248370" + +/// The core for the phones (arm64) and the emulator (x86_64). +val cargoBuild = tasks.register("cargoBuild") { + workingDir = repo + environment("ANDROID_NDK_HOME", ndkHome) + commandLine( + "cargo", "ndk", "-t", "arm64-v8a", "-t", "x86_64", "--platform", "31", + "-o", cargoOut.get().asFile.path, "build", "--release", "-p", "mobile-api", + ) + inputs.dir(File(repo, "crates")) + inputs.file(File(repo, "Cargo.lock")) + outputs.dir(cargoOut) +} + +/// Only our library: cargo-ndk also copies the cdylibs of dependencies (sevenz-rust2), +/// which are linked into ours already. +val rustJniLibs = tasks.register("rustJniLibs") { + dependsOn(cargoBuild) + from(cargoOut) { include("*/libmobile_api.so") } + into(rustLibs) +} + +/// The Kotlin side of the bridge, generated from the built library. +val uniffiBindings = tasks.register("uniffiBindings") { + dependsOn(rustJniLibs) + workingDir = repo + commandLine( + "cargo", "run", "-q", "-p", "mobile-api", "--features", "bindgen", "--bin", "uniffi-bindgen", + "--", "generate", "--no-format", "--language", "kotlin", + "--library", rustLibs.get().file("x86_64/libmobile_api.so").asFile.path, + "--out-dir", bindings.get().asFile.path, + ) + inputs.dir(rustLibs) + outputs.dir(bindings) +} + +/// Stockfish for Android (scripts/stockfish.sh): the executable for both builds, its +/// network only inside the "full" one. +val stockfishOut = layout.buildDirectory.dir("stockfish") +val stockfish = tasks.register("stockfish") { + environment("ANDROID_NDK_HOME", ndkHome) + commandLine(File(rootDir, "scripts/stockfish.sh").path, stockfishOut.get().asFile.path) + inputs.file(File(rootDir, "scripts/stockfish.sh")) + outputs.dir(stockfishOut) +} + +/// The sample games of the desktop app and the Merida pieces, as app assets. +val bundleAssets = tasks.register("bundleAssets") { + from(File(repo, "examples")) { + include("*.pgn") + into("examples") + } + from(File(repo, "apps/desktop/assets/pieces/merida")) { + include("*.svg") + into("pieces/merida") + } + from(stockfishOut.map { it.dir("source") }) { + into("licenses/stockfish") + } + dependsOn(stockfish) + into(bundled) +} + +android { + namespace = "io.github.vrubelroman.chesspenguin" + compileSdk = 37 + flavorDimensions += "engine" + productFlavors { + // «Stockfish уже внутри»: the network is in the APK, nothing to download. + create("full") { + dimension = "engine" + buildConfigField("boolean", "NET_BUILT_IN", "true") + } + // «Stockfish скачивается в приложении»: the network is downloaded on request. + create("light") { + dimension = "engine" + buildConfigField("boolean", "NET_BUILT_IN", "false") + } + } + + defaultConfig { + applicationId = "io.github.vrubelroman.chesspenguin" + minSdk = 31 + targetSdk = 36 + versionCode = 1 + versionName = "0.1.0" + ndk { + abiFilters += listOf("arm64-v8a", "x86_64") + } + // The network of Stockfish 19 (scripts/stockfish.sh), checked after download. + buildConfigField("String", "NET_NAME", "\"nn-1a298aa575a0.nnue\"") + buildConfigField("String", "NET_SHA256", "\"1a298aa575a085434d29027978dc36867fe9c5bcea9376654b7a8eba1e52dfc2\"") + buildConfigField("long", "NET_SIZE", "98511183L") + buildConfigField( + "String", + "NET_URL", + "\"https://github.com/official-stockfish/networks/raw/master/nn-1a298aa575a0.nnue\"", + ) + } + + buildTypes { + release { + isMinifyEnabled = false + proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") + } + } + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + buildFeatures { + compose = true + aidl = false + buildConfig = true + shaders = false + } + sourceSets { + getByName("main") { + jniLibs.directories.add(rustLibs.get().asFile.path) + jniLibs.directories.add(stockfishOut.get().dir("jniLibs").asFile.path) + kotlin.directories.add(bindings.get().asFile.path) + assets.directories.add(bundled.get().asFile.path) + } + getByName("full") { + assets.directories.add(stockfishOut.get().dir("net").asFile.path) + } + } + packaging { + // Unpacked at install: Stockfish runs from nativeLibraryDir as its own process. + jniLibs { + useLegacyPackaging = true + } + resources { + excludes += "/META-INF/{AL2.0,LGPL2.1}" + } + } +} + +kotlin { + jvmToolchain(21) +} + +tasks.named("preBuild") { + dependsOn(uniffiBindings, bundleAssets, stockfish) +} + +dependencies { + val composeBom = platform(libs.androidx.compose.bom) + implementation(composeBom) + + implementation(libs.androidx.core.ktx) + implementation(libs.androidx.lifecycle.runtime.ktx) + implementation(libs.androidx.activity.compose) + implementation(libs.androidx.lifecycle.runtime.compose) + implementation(libs.androidx.lifecycle.viewmodel.compose) + + implementation(libs.androidx.compose.ui) + implementation(libs.androidx.compose.ui.tooling.preview) + implementation(libs.androidx.compose.material3) + implementation(libs.androidx.compose.material.icons) + debugImplementation(libs.androidx.compose.ui.tooling) + + implementation(libs.androidx.navigation3.ui) + implementation(libs.androidx.navigation3.runtime) + implementation(libs.androidx.lifecycle.viewmodel.navigation3) + implementation(libs.androidx.datastore.preferences) + implementation(libs.kotlinx.serialization.json) + + // The bridge to the Rust core (UniFFI uses JNA), and the SVG pieces. + implementation("${libs.jna.get()}@aar") + implementation(libs.androidsvg) + + testImplementation(libs.junit) +} diff --git a/androidApp/app/src/light/AndroidManifest.xml b/androidApp/app/src/light/AndroidManifest.xml new file mode 100644 index 0000000..ab9d809 --- /dev/null +++ b/androidApp/app/src/light/AndroidManifest.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/androidApp/app/src/main/AndroidManifest.xml b/androidApp/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..36ad798 --- /dev/null +++ b/androidApp/app/src/main/AndroidManifest.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ChessPenguinApp.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ChessPenguinApp.kt new file mode 100644 index 0000000..e28187a --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ChessPenguinApp.kt @@ -0,0 +1,22 @@ +package io.github.vrubelroman.chesspenguin + +import android.app.Application +import io.github.vrubelroman.chesspenguin.data.EngineFiles +import io.github.vrubelroman.chesspenguin.data.Library +import io.github.vrubelroman.chesspenguin.data.Settings +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob + +/// The app's databases, settings and engine files live as long as the process. +class ChessPenguinApp : Application() { + /// Work that outlives a screen (the download of the engine). + val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + val library by lazy { Library(this) } + val settings by lazy { Settings(this) } + val engineFiles by lazy { EngineFiles(this, scope) } + + /// The games shown on the list of each database (after a search), for paging + /// games from the game screen: database id → game numbers. + val shown = HashMap>() +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/MainActivity.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/MainActivity.kt new file mode 100644 index 0000000..28b566a --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/MainActivity.kt @@ -0,0 +1,34 @@ +package io.github.vrubelroman.chesspenguin + +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.activity.enableEdgeToEdge +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.ui.Modifier +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import io.github.vrubelroman.chesspenguin.data.Theme +import io.github.vrubelroman.chesspenguin.theme.ChessPenguinTheme + +class MainActivity : ComponentActivity() { + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + enableEdgeToEdge() + val settings = (application as ChessPenguinApp).settings + setContent { + val prefs by settings.prefs.collectAsState() + val dark = when (prefs.theme) { + Theme.System -> isSystemInDarkTheme() + Theme.Light -> false + Theme.Dark -> true + } + ChessPenguinTheme(darkTheme = dark) { + Surface(Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) { MainNavigation() } + } + } + } +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/Navigation.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/Navigation.kt new file mode 100644 index 0000000..30ddd00 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/Navigation.kt @@ -0,0 +1,50 @@ +package io.github.vrubelroman.chesspenguin + +import androidx.compose.runtime.Composable +import androidx.navigation3.runtime.NavKey +import androidx.navigation3.runtime.entryProvider +import androidx.navigation3.runtime.rememberNavBackStack +import androidx.navigation3.ui.NavDisplay +import io.github.vrubelroman.chesspenguin.ui.AboutScreen +import io.github.vrubelroman.chesspenguin.ui.DatabasesScreen +import io.github.vrubelroman.chesspenguin.ui.SettingsScreen +import io.github.vrubelroman.chesspenguin.ui.GameScreen +import io.github.vrubelroman.chesspenguin.ui.GamesScreen +import kotlinx.serialization.Serializable + +@Serializable data object Databases : NavKey + +@Serializable data class Games(val db: String) : NavKey + +/// The game at `place` on the list of games shown for the database. +@Serializable data class GameAt(val db: String, val place: Int) : NavKey + +@Serializable data object SettingsKey : NavKey + +@Serializable data object AboutKey : NavKey + +@Composable +fun MainNavigation() { + val backStack = rememberNavBackStack(Databases) + NavDisplay( + backStack = backStack, + onBack = { backStack.removeLastOrNull() }, + entryProvider = entryProvider { + entry { + DatabasesScreen(onOpen = { backStack.add(Games(it)) }, onSettings = { backStack.add(SettingsKey) }) + } + entry { key -> + GamesScreen(key.db, onBack = { backStack.removeLastOrNull() }, onGame = { backStack.add(GameAt(key.db, it)) }) + } + entry { key -> + GameScreen(key.db, key.place, onBack = { backStack.removeLastOrNull() }, onSettings = { backStack.add(SettingsKey) }) + } + entry { + SettingsScreen(onBack = { backStack.removeLastOrNull() }, onAbout = { backStack.add(AboutKey) }) + } + entry { + AboutScreen(onBack = { backStack.removeLastOrNull() }) + } + }, + ) +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/EngineFiles.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/EngineFiles.kt new file mode 100644 index 0000000..d242efa --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/EngineFiles.kt @@ -0,0 +1,189 @@ +package io.github.vrubelroman.chesspenguin.data + +import android.content.Context +import android.net.ConnectivityManager +import android.net.NetworkCapabilities +import io.github.vrubelroman.chesspenguin.BuildConfig +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.ensureActive +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import java.io.File +import java.io.FileOutputStream +import java.io.IOException +import java.io.InputStream +import java.net.HttpURLConnection +import java.net.URL +import java.security.MessageDigest + +/// Why the network of the engine is not there. +enum class NetProblem { NoInternet, Interrupted, NoSpace, Corrupt } + +sealed interface NetState { + data object Missing : NetState + data class Loading(val done: Long, val total: Long) : NetState + data class Failed(val problem: NetProblem) : NetState + data object Ready : NetState +} + +/// Stockfish and its network (android-ui.md §8). The executable is a "library" of the +/// APK; the network is a file in the app's storage: copied from the APK in the "full" +/// build, downloaded on request in the "light" one, checked by its SHA-256 either way. +class EngineFiles(private val context: Context, private val scope: CoroutineScope) { + private val dir = File(context.filesDir, "engine") + val net = File(dir, BuildConfig.NET_NAME) + private val part = File(dir, BuildConfig.NET_NAME + ".part") + + /// The executable, unpacked by the installer (useLegacyPackaging). + val executable: String get() = context.applicationInfo.nativeLibraryDir + "/libstockfish.so" + + private val _state = MutableStateFlow(if (installed()) NetState.Ready else NetState.Missing) + val state: StateFlow = _state.asStateFlow() + private var job: Job? = null + + /// A network checked when it was written: the right size is enough later. + private fun installed() = net.length() == BuildConfig.NET_SIZE + + val builtIn: Boolean get() = BuildConfig.NET_BUILT_IN + + /// True when the phone is on a metered (mobile) connection right now. + fun metered(): Boolean { + val cm = context.getSystemService(ConnectivityManager::class.java) ?: return false + val caps = cm.getNetworkCapabilities(cm.activeNetwork) ?: return false + return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED) + } + + /// Gets the network ready: from the APK, or from the internet. Runs on in the app's + /// scope when the screen that asked goes away. + fun prepare() { + if (_state.value == NetState.Ready || job?.isActive == true) return + job = scope.launch(Dispatchers.IO) { + _state.value = try { + dir.mkdirs() + if (builtIn) copyFromApk() else download() + NetState.Ready + } catch (e: NetFailure) { + NetState.Failed(e.problem) + } catch (e: IOException) { + NetState.Failed(if (dir.usableSpace < BuildConfig.NET_SIZE) NetProblem.NoSpace else NetProblem.Interrupted) + } + } + } + + /// Stops a download; what came is kept for the next one. + fun cancel() { + job?.cancel() + job = null + _state.value = NetState.Missing + } + + /// Removes a downloaded network (Settings → "Delete the engine"). + fun delete() { + cancel() + net.delete() + part.delete() + } + + private class NetFailure(val problem: NetProblem) : Exception() + + private suspend fun copyFromApk() { + part.delete() + context.assets.open(BuildConfig.NET_NAME).use { write(it, append = false, start = 0) } + finish() + } + + private suspend fun download() { + if (!online()) throw NetFailure(NetProblem.NoInternet) + if (dir.usableSpace + part.length() < BuildConfig.NET_SIZE) throw NetFailure(NetProblem.NoSpace) + var have = part.length().takeIf { it < BuildConfig.NET_SIZE } ?: 0L + var url = URL(BuildConfig.NET_URL) + // GitHub answers with a redirect to its file host; follow it by hand to keep + // the Range header (resume after an interruption). + var conn: HttpURLConnection + var hops = 0 + while (true) { + conn = url.openConnection() as HttpURLConnection + conn.instanceFollowRedirects = false + conn.connectTimeout = 15_000 + conn.readTimeout = 30_000 + if (have > 0) conn.setRequestProperty("Range", "bytes=$have-") + val code = try { + conn.responseCode + } catch (e: IOException) { + throw NetFailure(if (online()) NetProblem.Interrupted else NetProblem.NoInternet) + } + if (code in 300..399 && hops++ < 5) { + url = URL(url, conn.getHeaderField("Location")) + conn.disconnect() + continue + } + if (code == 416) { + // The part is already whole (or longer): check it. + conn.disconnect() + finish() + return + } + if (code != 200 && code != 206) throw NetFailure(NetProblem.Interrupted) + if (code == 200) have = 0 + break + } + try { + conn.inputStream.use { write(it, append = have > 0, start = have) } + } catch (e: IOException) { + throw NetFailure(if (dir.usableSpace < 1_000_000) NetProblem.NoSpace else NetProblem.Interrupted) + } finally { + conn.disconnect() + } + finish() + } + + private suspend fun write(input: InputStream, append: Boolean, start: Long) = withContext(Dispatchers.IO) { + val total = BuildConfig.NET_SIZE + var done = start + FileOutputStream(part, append).use { out -> + val buf = ByteArray(256 * 1024) + var last = 0L + while (true) { + ensureActive() + val n = input.read(buf) + if (n < 0) break + out.write(buf, 0, n) + done += n + if (done - last > 512 * 1024) { + last = done + _state.value = NetState.Loading(done, total) + } + } + } + } + + /// Checks the whole file and puts it in place, or throws it away. + private fun finish() { + val digest = MessageDigest.getInstance("SHA-256") + part.inputStream().use { input -> + val buf = ByteArray(1024 * 1024) + while (true) { + val n = input.read(buf) + if (n < 0) break + digest.update(buf, 0, n) + } + } + val sum = digest.digest().joinToString("") { "%02x".format(it) } + if (sum != BuildConfig.NET_SHA256) { + part.delete() + throw NetFailure(NetProblem.Corrupt) + } + if (!part.renameTo(net)) throw IOException("cannot move the network into place") + } + + private fun online(): Boolean { + val cm = context.getSystemService(ConnectivityManager::class.java) ?: return true + val caps = cm.getNetworkCapabilities(cm.activeNetwork) ?: return false + return caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) + } +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/EngineSession.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/EngineSession.kt new file mode 100644 index 0000000..73ef184 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/EngineSession.kt @@ -0,0 +1,158 @@ +package io.github.vrubelroman.chesspenguin.data + +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.isActive +import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withContext +import uniffi.mobile_api.Analysis +import uniffi.mobile_api.Analyzer +import uniffi.mobile_api.GameData + +/// The position for the engine: where the history starts and the moves since then. +data class EnginePosition(val startFen: String, val moves: List) + +/// The history of a node, so the engine sees repetitions; after a training null move +/// ("--") it starts again from the position as a FEN (android-ui.md §8, AGENTS.md). +fun enginePosition(game: GameData, node: Int): EnginePosition { + val path = ArrayList() + var n: Int? = node + while (n != null) { + path.add(n) + n = game.nodes[n].parent?.toInt() + } + path.reverse() + var start = game.nodes[0].fen + val moves = ArrayList() + for (id in path.drop(1)) { + val m = game.nodes[id] + if (m.uci.isEmpty()) { + start = m.fen + moves.clear() + } else { + moves.add(m.uci) + } + } + return EnginePosition(start, moves) +} + +sealed interface EngineStatus { + data object Off : EngineStatus + data object Starting : EngineStatus + /// Thinking about the current position. + data object Thinking : EngineStatus + /// The time per position is over; "Deeper" thinks on. + data object Paused : EngineStatus + /// The engine stopped answering or does not run on this phone. + data class Failed(val notStarting: Boolean) : EngineStatus +} + +/// The engine while a game is on the screen: one Stockfish process, the analysis of the +/// shown position only. A new position clears the lines at once; snapshots of an older +/// search are dropped, so an old evaluation is never shown for a new position. +class EngineSession(private val files: EngineFiles, private val scope: CoroutineScope) { + private val _status = MutableStateFlow(EngineStatus.Off) + val status: StateFlow = _status.asStateFlow() + private val _analysis = MutableStateFlow(null) + val analysis: StateFlow = _analysis.asStateFlow() + + private val lock = Mutex() + private var analyzer: Analyzer? = null + private var loop: Job? = null + private var timer: Job? = null + @Volatile private var search: ULong = 0u + private var position: EnginePosition? = null + private var prefs = Prefs() + + /// Starts the engine (if it is not running) and analyses `pos`. + fun show(pos: EnginePosition, p: Prefs) { + prefs = p + val changed = pos != position + position = pos + scope.launch { + lock.withLock { + val a = analyzer ?: startLocked() ?: return@withLock + // The same position again (the screen redrawn, the time over) stays as it is. + if (changed || _status.value == EngineStatus.Starting) analyzeLocked(a, pos) + } + } + } + + /// Thinks on about the same position after the time ran out. + fun deeper() { + val pos = position ?: return + scope.launch { lock.withLock { analyzer?.let { analyzeLocked(it, pos) } } } + } + + /// Quits the process (the screen went away, the button was turned off). + fun shutdown() { + position = null + _analysis.value = null + _status.value = EngineStatus.Off + val a = analyzer + analyzer = null + loop?.cancel() + timer?.cancel() + if (a != null) scope.launch(Dispatchers.IO) { lock.withLock { a.quit(); a.close() } } + } + + private suspend fun startLocked(): Analyzer? { + _status.value = EngineStatus.Starting + val a = withContext(Dispatchers.IO) { + runCatching { + Analyzer.start(files.executable, files.net.path, prefs.engineThreads.toUInt(), prefs.engineHashMb.toUInt()) + } + }.getOrElse { + _status.value = EngineStatus.Failed(notStarting = true) + return null + } + analyzer = a + loop = scope.launch(Dispatchers.IO) { poll(a) } + return a + } + + private suspend fun analyzeLocked(a: Analyzer, pos: EnginePosition) { + // No snapshot is taken until the new search has its number. + search = 0u + _analysis.value = null + val id = withContext(Dispatchers.IO) { + runCatching { a.analyze(pos.startFen, pos.moves, prefs.engineLines.toUInt()) } + }.getOrElse { + _status.value = EngineStatus.Failed(notStarting = false) + return + } + search = id + _status.value = EngineStatus.Thinking + timer?.cancel() + if (prefs.engineSeconds > 0) { + timer = scope.launch { + delay(prefs.engineSeconds * 1000L) + lock.withLock { + if (search == id && analyzer === a) { + withContext(Dispatchers.IO) { a.stop() } + _status.value = EngineStatus.Paused + } + } + } + } + } + + private suspend fun poll(a: Analyzer) { + while (scope.isActive && analyzer === a) { + val snapshot = try { + a.poll(150u) + } catch (e: Exception) { + if (analyzer === a) _status.value = EngineStatus.Failed(notStarting = false) + return + } + if (snapshot != null && snapshot.search == search && analyzer === a) _analysis.value = snapshot + } + } +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/Library.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/Library.kt new file mode 100644 index 0000000..6ad19a4 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/Library.kt @@ -0,0 +1,172 @@ +package io.github.vrubelroman.chesspenguin.data + +import android.content.Context +import android.content.Intent +import android.net.Uri +import android.provider.OpenableColumns +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withContext +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.Json +import uniffi.mobile_api.ApiException +import uniffi.mobile_api.Database +import uniffi.mobile_api.openBytes +import uniffi.mobile_api.openFile +import java.io.File +import java.util.UUID + +/// Where a database comes from. +@Serializable +enum class Source { + /// One of the sample games of the desktop app, inside the app (assets/examples). + Sample, + + /// A file the user picked; read in place through its persisted permission. + File, +} + +/// A database on the list. The file itself is never changed. +@Serializable +data class DbEntry( + val id: String, + val name: String, + val source: Source, + /// The asset path of a sample, the content URI of a file. + val location: String, + /// The file's name, for its extension (PGN, .zip, .7z, .cbv). + val fileName: String, + val games: Int? = null, + val format: String? = null, + /// A sample keeps the name of the current language until it is renamed. + val renamed: Boolean = false, +) + +/// The databases on the list and the open ones (docs/design/android-ui.md §3). +class Library(private val context: Context) { + private val file = File(context.filesDir, "library.json") + private val json = Json { ignoreUnknownKeys = true } + private val _entries = MutableStateFlow(load()) + val entries: StateFlow> = _entries.asStateFlow() + + /// Open databases by entry id (they are small: phone-sized). + private val open = HashMap() + private val lock = Mutex() + + private fun load(): List { + if (!file.exists()) return samples().also { save(it) } + val list = runCatching { json.decodeFromString>(file.readText()) }.getOrDefault(emptyList()) + val names = samples().associate { it.id to it.name } + return list.map { e -> if (e.source == Source.Sample && !e.renamed) e.copy(name = names[e.id] ?: e.name) else e } + } + + private fun save(list: List) { + val tmp = File(file.path + ".tmp") + tmp.writeText(json.encodeToString(list)) + tmp.renameTo(file) + } + + private fun update(change: (List) -> List) { + val next = change(_entries.value) + _entries.value = next + save(next) + } + + /// The sample games of the desktop app: on the list from the first start. + private fun samples(): List { + val names = listOf( + "classics.pgn" to context.getString(io.github.vrubelroman.chesspenguin.R.string.sample_classics), + "alekhine.pgn" to context.getString(io.github.vrubelroman.chesspenguin.R.string.sample_alekhine), + ) + return names.map { (f, name) -> DbEntry(id = "sample-$f", name = name, source = Source.Sample, location = "examples/$f", fileName = f) } + } + + /// Puts the sample games back on the list (those not on it), at its end. + fun addSamples() = update { list -> list + samples().filter { s -> list.none { it.id == s.id } } } + + fun entry(id: String): DbEntry? = _entries.value.firstOrNull { it.id == id } + + /// Adds a file picked with the system picker; its read permission is kept across + /// restarts. Returns the new entry, or the one already on the list. + fun addFile(uri: Uri): DbEntry { + _entries.value.firstOrNull { it.location == uri.toString() }?.let { return it } + runCatching { + context.contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION) + } + val fileName = displayName(uri) ?: "database.pgn" + val entry = DbEntry( + id = UUID.randomUUID().toString(), + name = fileName.substringBeforeLast('.'), + source = Source.File, + location = uri.toString(), + fileName = fileName, + ) + update { it + entry } + return entry + } + + fun rename(id: String, name: String) = update { list -> list.map { if (it.id == id) it.copy(name = name, renamed = true) else it } } + + /// Takes the database off the list (the file stays where it is). Returns its place, + /// for "Undo". + fun remove(id: String): Pair? { + val list = _entries.value + val i = list.indexOfFirst { it.id == id } + if (i < 0) return null + val e = list[i] + update { it.filterNot { x -> x.id == id } } + open.remove(id)?.close() + if (e.source == Source.File) { + runCatching { + context.contentResolver.releasePersistableUriPermission(Uri.parse(e.location), Intent.FLAG_GRANT_READ_URI_PERMISSION) + } + } + return i to e + } + + fun restore(place: Int, entry: DbEntry) { + if (entry.source == Source.File) { + runCatching { + context.contentResolver.takePersistableUriPermission(Uri.parse(entry.location), Intent.FLAG_GRANT_READ_URI_PERMISSION) + } + } + update { it.toMutableList().apply { add(place.coerceIn(0, size), entry) } } + } + + private fun displayName(uri: Uri): String? = runCatching { + context.contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { c -> + if (c.moveToFirst()) c.getString(0) else null + } + }.getOrNull() + + /// The open database of an entry (opened in the background the first time). + suspend fun database(id: String): Result = lock.withLock { + open[id]?.let { return@withLock Result.success(it) } + val e = entry(id) ?: return@withLock Result.failure(IllegalArgumentException("no database $id")) + val result = withContext(Dispatchers.IO) { + runCatching { + when (e.source) { + Source.Sample -> openBytes(e.fileName, context.assets.open(e.location).use { it.readBytes() }) + Source.File -> { + val pfd = context.contentResolver.openFileDescriptor(Uri.parse(e.location), "r") + ?: throw ApiException.Io(detail = "no access to the file") + openFile(e.fileName, pfd.detachFd()) + } + } + } + } + result.onSuccess { db -> + open[id] = db + val games = db.len().toInt() + val format = db.format() + if (e.games != games || e.format != format) { + update { list -> list.map { if (it.id == id) it.copy(games = games, format = format) else it } } + } + } + result + } +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/Settings.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/Settings.kt new file mode 100644 index 0000000..5c13713 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/Settings.kt @@ -0,0 +1,72 @@ +package io.github.vrubelroman.chesspenguin.data + +import android.content.Context +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow + +enum class Theme { System, Light, Dark } + +/// How moves are written on the screen (PGN keeps K Q R B N). +enum class Notation { Latin, Figurines, Local } + +/// The user's choices (android-ui.md §9), applied at once and kept across starts. +data class Prefs( + val theme: Theme = Theme.System, + val notation: Notation = Notation.Latin, + val vibration: Boolean = true, + val animation: Boolean = true, + val bestArrow: Boolean = true, + /// The engine button: once turned on, it stays on in the next game (§8.3). + val engineOn: Boolean = false, + val engineLines: Int = 2, + /// Seconds of thinking per position; 0 = no limit. + val engineSeconds: Int = 20, + val engineThreads: Int = defaultThreads(), + val engineHashMb: Int = 64, +) + +/// Half the cores, at most 4 (§9). +fun defaultThreads(): Int = (Runtime.getRuntime().availableProcessors() / 2).coerceIn(1, 4) + +class Settings(context: Context) { + private val store = context.getSharedPreferences("settings", Context.MODE_PRIVATE) + private val _prefs = MutableStateFlow(read()) + val prefs: StateFlow = _prefs.asStateFlow() + + private fun read(): Prefs { + val d = Prefs() + return Prefs( + theme = enumValueOrNull(store.getString("theme", null)) ?: d.theme, + notation = enumValueOrNull(store.getString("notation", null)) ?: d.notation, + vibration = store.getBoolean("vibration", d.vibration), + animation = store.getBoolean("animation", d.animation), + bestArrow = store.getBoolean("bestArrow", d.bestArrow), + engineOn = store.getBoolean("engineOn", d.engineOn), + engineLines = store.getInt("engineLines", d.engineLines), + engineSeconds = store.getInt("engineSeconds", d.engineSeconds), + engineThreads = store.getInt("engineThreads", d.engineThreads), + engineHashMb = store.getInt("engineHashMb", d.engineHashMb), + ) + } + + fun update(change: (Prefs) -> Prefs) { + val p = change(_prefs.value) + _prefs.value = p + store.edit() + .putString("theme", p.theme.name) + .putString("notation", p.notation.name) + .putBoolean("vibration", p.vibration) + .putBoolean("animation", p.animation) + .putBoolean("bestArrow", p.bestArrow) + .putBoolean("engineOn", p.engineOn) + .putInt("engineLines", p.engineLines) + .putInt("engineSeconds", p.engineSeconds) + .putInt("engineThreads", p.engineThreads) + .putInt("engineHashMb", p.engineHashMb) + .apply() + } +} + +private inline fun > enumValueOrNull(name: String?): T? = + enumValues().firstOrNull { it.name == name } diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/theme/Color.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/theme/Color.kt new file mode 100644 index 0000000..9fd66ad --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/theme/Color.kt @@ -0,0 +1,66 @@ +package io.github.vrubelroman.chesspenguin.theme + +import androidx.compose.ui.graphics.Color + +// The colors of the desktop app and the website (docs/design/android-ui.md §10.3). + +val LightBackground = Color(0xFFFFFFFF) +val LightContainerLow = Color(0xFFF5F6F7) +val LightContainer = Color(0xFFEEF0F2) +val LightContainerHigh = Color(0xFFE8EAED) +val LightOnSurface = Color(0xFF1C1D1F) +val LightOnSurfaceVariant = Color(0xFF5D636B) +val LightOutline = Color(0xFFC4C8CD) +val LightOutlineVariant = Color(0xFFE1E3E6) +val LightPrimary = Color(0xFF1F6FA8) +val LightPrimaryContainer = Color(0xFFD6E8F6) +val LightOnPrimaryContainer = Color(0xFF1A5F91) +val LightError = Color(0xFFC42B1C) +val LightErrorContainer = Color(0xFFFCE4E1) + +val DarkBackground = Color(0xFF161718) +val DarkContainerLow = Color(0xFF1F2022) +val DarkContainer = Color(0xFF232427) +val DarkContainerHigh = Color(0xFF2A2C2F) +val DarkOnSurface = Color(0xFFE8E8E8) +val DarkOnSurfaceVariant = Color(0xFFA3A7AD) +val DarkOutline = Color(0xFF4A4D52) +val DarkOutlineVariant = Color(0xFF2E3033) +val DarkPrimary = Color(0xFF62AEE6) +val DarkOnPrimary = Color(0xFF0B2A40) +val DarkPrimaryContainer = Color(0xFF1A4566) +val DarkError = Color(0xFFF28B82) +val DarkErrorContainer = Color(0xFF5C1A14) + +/// Colors of the notation and the board that stay ours whatever the theme. +data class ChessColors( + val currentMove: Color, + val comment: Color, + val lightSquare: Color, + val darkSquare: Color, + val lastMove: Color, +) + +val LightChess = ChessColors( + currentMove = Color(0xFF90D1FF), + comment = Color(0xFF2A5B8A), + lightSquare = Color(0xFFFFFFDD), + darkSquare = Color(0xFF86A666), + lastMove = Color(0x699BC700), +) + +val DarkChess = LightChess.copy( + currentMove = Color(0xFF005C80), + comment = Color(0xFF9EC4E0), +) + +/// Move assessments, as on the desktop (Lichess colors), the same in both themes. +fun nagColor(nag: Int): Color? = when (nag) { + 1 -> Color(0xFF629C2E) // ! + 2 -> Color(0xFFE68F00) // ? + 3 -> Color(0xFF22AC9A) // !! + 4 -> Color(0xFFDF5353) // ?? + 5 -> Color(0xFFEA45D8) // !? + 6 -> Color(0xFF56B4E9) // ?! + else -> null +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/theme/Theme.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/theme/Theme.kt new file mode 100644 index 0000000..b0ab13d --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/theme/Theme.kt @@ -0,0 +1,72 @@ +package io.github.vrubelroman.chesspenguin.theme + +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.darkColorScheme +import androidx.compose.material3.lightColorScheme +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.staticCompositionLocalOf +import androidx.compose.ui.graphics.Color + +private val Light = lightColorScheme( + primary = LightPrimary, + onPrimary = Color.White, + primaryContainer = LightPrimaryContainer, + onPrimaryContainer = LightOnPrimaryContainer, + secondary = LightPrimary, + onSecondary = Color.White, + secondaryContainer = LightPrimaryContainer, + onSecondaryContainer = LightOnPrimaryContainer, + tertiary = LightPrimary, + background = LightBackground, + onBackground = LightOnSurface, + surface = LightBackground, + onSurface = LightOnSurface, + onSurfaceVariant = LightOnSurfaceVariant, + surfaceContainerLowest = LightBackground, + surfaceContainerLow = LightContainerLow, + surfaceContainer = LightContainer, + surfaceContainerHigh = LightContainerHigh, + surfaceContainerHighest = LightContainerHigh, + outline = LightOutline, + outlineVariant = LightOutlineVariant, + error = LightError, + errorContainer = LightErrorContainer, +) + +private val Dark = darkColorScheme( + primary = DarkPrimary, + onPrimary = DarkOnPrimary, + primaryContainer = DarkPrimaryContainer, + onPrimaryContainer = LightPrimaryContainer, + secondary = DarkPrimary, + onSecondary = DarkOnPrimary, + secondaryContainer = DarkPrimaryContainer, + onSecondaryContainer = LightPrimaryContainer, + tertiary = DarkPrimary, + background = DarkBackground, + onBackground = DarkOnSurface, + surface = DarkBackground, + onSurface = DarkOnSurface, + onSurfaceVariant = DarkOnSurfaceVariant, + surfaceContainerLowest = DarkBackground, + surfaceContainerLow = DarkContainerLow, + surfaceContainer = DarkContainer, + surfaceContainerHigh = DarkContainerHigh, + surfaceContainerHighest = DarkContainerHigh, + outline = DarkOutline, + outlineVariant = DarkOutlineVariant, + error = DarkError, + errorContainer = DarkErrorContainer, +) + +val LocalChessColors = staticCompositionLocalOf { LightChess } + +/// Our own colors in the light or dark theme of the system (docs/design/android-ui.md §10.3). +@Composable +fun ChessPenguinTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit) { + CompositionLocalProvider(LocalChessColors provides if (darkTheme) DarkChess else LightChess) { + MaterialTheme(colorScheme = if (darkTheme) Dark else Light, typography = Typography, content = content) + } +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/theme/Type.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/theme/Type.kt new file mode 100644 index 0000000..1358853 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/theme/Type.kt @@ -0,0 +1,20 @@ +package io.github.vrubelroman.chesspenguin.theme + +import androidx.compose.material3.Typography +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.sp + +// The system font (Roboto on most phones), the sizes of §10.2. +val Typography = Typography().run { + copy( + titleLarge = titleLarge.copy(fontSize = 22.sp, lineHeight = 28.sp, fontWeight = FontWeight.Normal), + bodyLarge = bodyLarge.copy(fontSize = 16.sp, lineHeight = 24.sp), + bodyMedium = bodyMedium.copy(fontSize = 14.sp, lineHeight = 20.sp), + labelLarge = labelLarge.copy(fontSize = 14.sp, lineHeight = 20.sp, fontWeight = FontWeight.Medium), + labelSmall = labelSmall.copy(fontSize = 12.sp, lineHeight = 16.sp, fontWeight = FontWeight.Medium), + ) +} + +/// Digits that keep their width (results, counters). +val Tabular = TextStyle(fontFeatureSettings = "tnum") diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/AboutScreen.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/AboutScreen.kt new file mode 100644 index 0000000..4a8f8ab --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/AboutScreen.kt @@ -0,0 +1,80 @@ +package io.github.vrubelroman.chesspenguin.ui + +import androidx.compose.foundation.Image +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.rounded.ArrowBack +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalUriHandler +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import io.github.vrubelroman.chesspenguin.BuildConfig +import io.github.vrubelroman.chesspenguin.R + +private const val SITE = "https://chess.vrubel.xyz" + +/// The authors and licenses of what the app is made of (android-ui.md §8.3, §9). +private val NOTICES = listOf( + "ChessPenguin" to "GPL-3.0-or-later · vrubelroman", + "Stockfish 19" to "GPL-3.0 · The Stockfish developers (see AUTHORS) · github.com/official-stockfish/Stockfish", + "Merida pieces" to "GPLv2+ · Armando Hernandez Marroquin (via Lichess)", + "Figurines, Noto Sans Math" to "SIL Open Font License 1.1", + "Jetpack Compose, AndroidX, Kotlin" to "Apache-2.0 · Google, JetBrains", + "UniFFI" to "MPL-2.0 · Mozilla", + "JNA" to "Apache-2.0 / LGPL-2.1", + "AndroidSVG" to "Apache-2.0 · Paul LeBeau", + "shakmaty" to "GPL-3.0-or-later · Niklas Fiekas", +) + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun AboutScreen(onBack: () -> Unit) { + val uri = LocalUriHandler.current + Scaffold( + topBar = { + TopAppBar( + title = { Text(stringResource(R.string.about)) }, + navigationIcon = { + IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Rounded.ArrowBack, stringResource(R.string.back)) } + }, + ) + }, + ) { padding -> + Column(Modifier.fillMaxSize().padding(padding).verticalScroll(rememberScrollState()).padding(horizontal = 16.dp, vertical = 8.dp)) { + Image(painterResource(R.drawable.penguin), null, Modifier.size(72.dp)) + Spacer(Modifier.height(16.dp)) + Text(stringResource(R.string.app_name), style = MaterialTheme.typography.titleLarge) + val build = stringResource(if (BuildConfig.NET_BUILT_IN) R.string.build_full else R.string.build_light) + Text("${BuildConfig.VERSION_NAME} · $build", color = MaterialTheme.colorScheme.onSurfaceVariant) + Spacer(Modifier.height(16.dp)) + Text(stringResource(R.string.about_text), style = MaterialTheme.typography.bodyLarge) + TextButton(onClick = { uri.openUri(SITE) }, contentPadding = androidx.compose.foundation.layout.PaddingValues(0.dp)) { + Text(stringResource(R.string.website)) + } + Spacer(Modifier.height(16.dp)) + Text(stringResource(R.string.licenses), style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.primary) + NOTICES.forEach { (what, license) -> + Spacer(Modifier.height(12.dp)) + Text(what, style = MaterialTheme.typography.bodyLarge) + Text(license, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + } + } +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/Board.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/Board.kt new file mode 100644 index 0000000..b6087d2 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/Board.kt @@ -0,0 +1,244 @@ +package io.github.vrubelroman.chesspenguin.ui + +import android.content.Context +import android.graphics.Bitmap +import android.graphics.Canvas +import androidx.compose.animation.core.Animatable +import androidx.compose.animation.core.FastOutSlowInEasing +import androidx.compose.animation.core.tween +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.layout.aspectRatio +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.Brush +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.ImageBitmap +import androidx.compose.ui.graphics.Path +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.graphics.asImageBitmap +import androidx.compose.ui.graphics.drawscope.DrawScope +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.drawText +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.rememberTextMeasurer +import androidx.compose.ui.unit.IntOffset +import androidx.compose.ui.unit.IntSize +import androidx.compose.ui.unit.sp +import com.caverock.androidsvg.SVG +import io.github.vrubelroman.chesspenguin.theme.LocalChessColors + +/// The 64 squares of a FEN's placement, a8 first: the piece letter or ' '. +fun placement(fen: String): CharArray { + val out = CharArray(64) { ' ' } + var i = 0 + for (c in fen.substringBefore(' ')) { + when { + c == '/' -> {} + c.isDigit() -> i += c - '0' + i < 64 -> out[i++] = c + } + } + return out +} + +/// "e4" → its index in [placement] (a8 = 0). +fun squareIndex(square: String?): Int? { + if (square == null || square.length < 2) return null + val file = square[0] - 'a' + val rank = square[1] - '1' + if (file !in 0..7 || rank !in 0..7) return null + return (7 - rank) * 8 + file +} + +/// The Merida pieces of the desktop app, drawn from their SVG at a size once. +class Pieces(private val context: Context) { + private val svgs = HashMap() + private val bitmaps = HashMap, ImageBitmap>() + + fun bitmap(piece: Char, size: Int): ImageBitmap? { + if (size <= 0) return null + return bitmaps.getOrPut(piece to size) { + val name = (if (piece.isUpperCase()) "w" else "b") + piece.uppercaseChar() + val svg = svgs.getOrPut(piece) { context.assets.open("pieces/merida/$name.svg").use { SVG.getFromInputStream(it) } } + val bmp = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888) + svg.setDocumentWidth(size.toFloat()) + svg.setDocumentHeight(size.toFloat()) + svg.renderToCanvas(Canvas(bmp)) + bmp.asImageBitmap() + } + } +} + +/// An arrow on the board: a comment's `[%cal]` or the engine's best move. +data class BoardArrow(val from: String, val to: String, val color: Color, val weight: Float = 1f) + +/// A marked square of a comment (`[%csl]`), drawn as a ring. +data class BoardMark(val square: String, val color: Color) + +/// The comment colors of the desktop app (game_view.rs `shape_color`). +fun markColor(letter: String): Color = when (letter) { + "R" -> Color(136, 32, 32, 170) + "G" -> Color(21, 120, 27, 170) + "B" -> Color(0, 48, 136, 170) + "Y" -> Color(230, 143, 0, 170) + else -> Color(120, 120, 120, 170) +} + +/// The engine's arrows are blue, as on the desktop. +val EngineArrow = Color(0, 48, 136, 160) + +/// The board: full width, the colors of the green theme, the last move lit, the +/// coordinates inside the edge squares (as on Lichess). It takes no touches in the first +/// version (docs/design/android-ui.md §7.2). A move slides into place (250 ms). +@Composable +fun Board( + fen: String, + flipped: Boolean, + lastFrom: String?, + lastTo: String?, + pieces: Pieces, + description: String, + modifier: Modifier = Modifier, + arrows: List = emptyList(), + marks: List = emptyList(), + check: Boolean = false, + animated: Boolean = true, +) { + val colors = LocalChessColors.current + val measurer = rememberTextMeasurer() + val squares = remember(fen) { placement(fen) } + val from = squareIndex(lastFrom) + val to = squareIndex(lastTo) + // The piece of the last move slides from its square when the position steps on. + val slide = remember { Animatable(1f) } + var previous by remember { mutableStateOf(null) } + var animate by remember { mutableStateOf(false) } + LaunchedEffect(fen) { + animate = animated && previous != null && from != null && to != null && placement(previous!!).let { p -> p[from] != ' ' && p[to] != squares[to] } + previous = fen + if (animate) { + slide.snapTo(0f) + slide.animateTo(1f, tween(250, easing = FastOutSlowInEasing)) + } else { + slide.snapTo(1f) + } + } + val coordStyle = TextStyle(fontSize = 10.sp, fontWeight = FontWeight.Medium) + val density = LocalDensity.current + Canvas( + modifier + .fillMaxWidth() + .aspectRatio(1f) + .semantics { contentDescription = description }, + ) { + val sq = size.width / 8f + val px = sq.toInt() + fun cell(i: Int): Offset { + val row = i / 8 + val col = i % 8 + val (r, c) = if (flipped) (7 - row) to (7 - col) else row to col + return Offset(c * sq, r * sq) + } + for (i in 0 until 64) { + val light = (i / 8 + i % 8) % 2 == 0 + drawRect(if (light) colors.lightSquare else colors.darkSquare, cell(i), Size(sq, sq)) + if (i == from || i == to) drawRect(colors.lastMove, cell(i), Size(sq, sq)) + } + for (m in marks) { + val i = squareIndex(m.square) ?: continue + val c = cell(i) + drawCircle(m.color, radius = sq * 0.45f, center = Offset(c.x + sq / 2, c.y + sq / 2), style = Stroke(width = sq * 0.08f)) + } + if (check) { + // A red glow under the king of the side to move. + val king = if (fen.substringAfter(' ').startsWith("b")) 'k' else 'K' + val i = squares.indexOf(king) + if (i >= 0) { + val c = cell(i) + val center = Offset(c.x + sq / 2, c.y + sq / 2) + drawCircle( + Brush.radialGradient( + 0f to Color(255, 0, 0, 230), + 0.25f to Color(231, 0, 0, 230), + 0.89f to Color(169, 0, 0, 0), + center = center, + radius = sq * 0.6f, + ), + radius = sq * 0.6f, + center = center, + ) + } + } + // Coordinates: files along the bottom edge, ranks along the left edge. + for (k in 0 until 8) { + val fileIndex = if (flipped) 7 - k else k + val rankIndex = if (flipped) k else 7 - k + val bottomLight = (7 + k) % 2 == 0 + val leftLight = k % 2 == 0 + drawCoord(measurer, ('a' + fileIndex).toString(), coordStyle.copy(color = if (bottomLight) colors.darkSquare else colors.lightSquare), + Offset((k + 1) * sq - with(density) { 8.sp.toPx() }, 8 * sq - with(density) { 13.sp.toPx() })) + drawCoord(measurer, ('1' + rankIndex).toString(), coordStyle.copy(color = if (leftLight) colors.darkSquare else colors.lightSquare), + Offset(with(density) { 2.sp.toPx() }, k * sq + with(density) { 1.sp.toPx() })) + } + for (i in 0 until 64) { + val p = squares[i] + if (p == ' ') continue + val bmp = pieces.bitmap(p, px) ?: continue + var at = cell(i) + if (animate && i == to && from != null && slide.value < 1f) { + val start = cell(from) + at = Offset(start.x + (at.x - start.x) * slide.value, start.y + (at.y - start.y) * slide.value) + } + drawImage(bmp, dstOffset = IntOffset(at.x.toInt(), at.y.toInt()), dstSize = IntSize(px, px)) + } + for (a in arrows) { + val f = squareIndex(a.from) ?: continue + val t = squareIndex(a.to) ?: continue + drawArrow(cell(f) + Offset(sq / 2, sq / 2), cell(t) + Offset(sq / 2, sq / 2), sq, a) + } + } +} + +/// An arrow as on the desktop (board.rs `draw_arrow`): a shaft and a head that stops +/// short of the square's center. +private fun DrawScope.drawArrow(from: Offset, to: Offset, sq: Float, a: BoardArrow) { + val d = to - from + val len = d.getDistance() + if (len < 1f) return + val dir = d / len + val width = sq * 0.16f * a.weight + val headLen = sq * 0.42f * kotlin.math.sqrt(a.weight) + val headW = sq * 0.38f * kotlin.math.sqrt(a.weight) + val tip = to - dir * (sq * 0.12f) + val base = tip - dir * headLen + val start = from + dir * (sq * 0.2f) + val normal = Offset(-dir.y, dir.x) + drawLine(a.color, start, base, strokeWidth = width) + val head = Path().apply { + moveTo(tip.x, tip.y) + lineTo(base.x + normal.x * headW, base.y + normal.y * headW) + lineTo(base.x - normal.x * headW, base.y - normal.y * headW) + close() + } + drawPath(head, a.color) +} + +private fun DrawScope.drawCoord( + measurer: androidx.compose.ui.text.TextMeasurer, + text: String, + style: TextStyle, + at: Offset, +) { + drawText(measurer, text, at, style) +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/Common.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/Common.kt new file mode 100644 index 0000000..7894470 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/Common.kt @@ -0,0 +1,130 @@ +package io.github.vrubelroman.chesspenguin.ui + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.unit.dp +import androidx.compose.ui.platform.LocalConfiguration +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.buildAnnotatedString +import androidx.compose.ui.text.font.Font +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.withStyle +import io.github.vrubelroman.chesspenguin.ChessPenguinApp +import io.github.vrubelroman.chesspenguin.R +import io.github.vrubelroman.chesspenguin.data.Notation +import io.github.vrubelroman.chesspenguin.data.DbEntry + +@Composable +fun app(): ChessPenguinApp = LocalContext.current.applicationContext as ChessPenguinApp + +/// 1248 → "1 248": digit groups apart, as on the desktop. +fun groupDigits(n: Int): String = "%,d".format(n).replace(',', ' ').replace(' ', ' ') + +/// The label of a database's format, for its badge (§10.6). +fun badge(e: DbEntry): String { + val ext = e.fileName.substringAfterLast('.', "").lowercase() + return when (ext) { + "zip" -> "ZIP" + "7z" -> "7Z" + "cbv", "cbh", "cbz" -> "CB" + else -> "PGN" + } +} + +@Composable +fun FormatBadge(text: String, error: Boolean = false) { + Box( + Modifier + .size(40.dp) + .clip(RoundedCornerShape(8.dp)) + .background(if (error) MaterialTheme.colorScheme.errorContainer else MaterialTheme.colorScheme.primaryContainer), + contentAlignment = Alignment.Center, + ) { + Text( + text, + style = MaterialTheme.typography.labelSmall, + color = if (error) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onPrimaryContainer, + ) + } +} + +/// "Carlsen, Magnus" → "Carlsen M."; other names stay as in the file (§6.2). +fun shortName(name: String): String { + val n = name.trim() + if (n.isEmpty() || n == "?") return "?" + val comma = n.indexOf(',') + if (comma <= 0) return n + val surname = n.substring(0, comma).trim() + val initials = n.substring(comma + 1).trim().split(' ', '-').filter { it.isNotEmpty() }.joinToString(" ") { "${it.first()}." } + return if (initials.isEmpty()) surname else "$surname $initials" +} + +/// "1/2-1/2" → "½-½". +fun shortResult(result: String): String = when (result) { + "1/2-1/2" -> "½-½" + "" -> "*" + else -> result +} + +/// The year of a PGN date ("1927.??.??" → "1927"), or nothing. +fun year(date: String): String = date.take(4).takeIf { y -> y.length == 4 && y.all { it.isDigit() } } ?: "" + +/// The parts that are known, joined with " · " (empty values and "?" left out). +fun joinKnown(vararg parts: String): String = parts.map { it.trim() }.filter { it.isNotEmpty() && it != "?" }.joinToString(" · ") + +/// The figurines of the desktop app (OFL, apps/desktop/assets/fonts/OFL.txt). +val Figurines = FontFamily(Font(R.font.figurines)) + +/// King, queen, rook, bishop, knight in a language, as on the desktop (san.rs). +private fun localLetters(lang: String): List? = when (lang) { + "ru" -> listOf("Кр", "Ф", "Л", "С", "К") + "de" -> listOf("K", "D", "T", "L", "S") + "fr" -> listOf("R", "D", "T", "F", "C") + "es", "it" -> listOf("R", "D", "T", "A", "C") + else -> null +} + +/// A SAN move as shown: the piece letter at the start and after "=" replaced; the +/// game itself stays in Latin SAN. +fun displaySan(san: String, mode: Notation, lang: String): AnnotatedString { + val local = localLetters(lang) + if (mode == Notation.Latin || (mode == Notation.Local && local == null)) return AnnotatedString(san) + return buildAnnotatedString { + san.forEachIndexed { i, c -> + val k = "KQRBN".indexOf(c) + val piece = k >= 0 && (i == 0 || san[i - 1] == '=') + when { + !piece -> append(c) + mode == Notation.Figurines -> withStyle(SpanStyle(fontFamily = Figurines)) { append("♔♕♖♗♘"[k]) } + else -> append(local!![k]) + } + } + } +} + +/// A line like "14.Nd5 Bxd5 15.exd5": each move shown with [displaySan]. +fun displayLine(text: String, mode: Notation, lang: String): AnnotatedString { + if (mode == Notation.Latin) return AnnotatedString(text) + return buildAnnotatedString { + text.split(' ').forEachIndexed { i, word -> + if (i > 0) append(' ') + val cut = word.indexOfLast { it == '.' || it == '…' } + 1 + append(word.substring(0, cut)) + append(displaySan(word.substring(cut), mode, lang)) + } + } +} + +/// The language of the interface ("ru", "en", …). +@Composable +fun uiLanguage(): String = LocalConfiguration.current.locales[0].language diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/DatabasesScreen.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/DatabasesScreen.kt new file mode 100644 index 0000000..5415868 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/DatabasesScreen.kt @@ -0,0 +1,243 @@ +package io.github.vrubelroman.chesspenguin.ui + +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.ExperimentalFoundationApi +import androidx.compose.foundation.Image +import androidx.compose.foundation.combinedClickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.rounded.Add +import androidx.compose.material.icons.rounded.MoreVert +import androidx.compose.material.icons.rounded.Settings +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.ExtendedFloatingActionButton +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.SnackbarResult +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.derivedStateOf +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.input.nestedscroll.nestedScroll +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.TextRange +import androidx.compose.ui.text.input.TextFieldValue +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import io.github.vrubelroman.chesspenguin.R +import io.github.vrubelroman.chesspenguin.data.DbEntry +import io.github.vrubelroman.chesspenguin.data.Source +import kotlinx.coroutines.launch + +/// The first screen: the databases on the list (android-ui.md §3). +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun DatabasesScreen(onOpen: (String) -> Unit, onSettings: () -> Unit) { + val library = app().library + val entries by library.entries.collectAsState() + val snackbar = remember { SnackbarHostState() } + val scope = rememberCoroutineScope() + val removedText = stringResource(R.string.removed) + val undoText = stringResource(R.string.undo) + val pick = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> + if (uri != null) onOpen(library.addFile(uri).id) + } + val add = { pick.launch(arrayOf("*/*")) } + var renaming by remember { mutableStateOf(null) } + val list = rememberLazyListState() + val expanded by remember { derivedStateOf { list.firstVisibleItemIndex == 0 } } + val scroll = TopAppBarDefaults.pinnedScrollBehavior() + // The samples are small: read them at once, so their rows show the number of games. + LaunchedEffect(Unit) { + library.entries.value.filter { it.source == Source.Sample && it.games == null }.forEach { library.database(it.id) } + } + + Scaffold( + modifier = Modifier.nestedScroll(scroll.nestedScrollConnection), + topBar = { + TopAppBar( + title = { Text(stringResource(R.string.app_name)) }, + actions = { + IconButton(onClick = onSettings) { Icon(Icons.Rounded.Settings, stringResource(R.string.settings)) } + }, + scrollBehavior = scroll, + ) + }, + snackbarHost = { SnackbarHost(snackbar) }, + floatingActionButton = { + if (entries.isNotEmpty()) { + ExtendedFloatingActionButton( + onClick = add, + expanded = expanded, + icon = { Icon(Icons.Rounded.Add, null) }, + text = { Text(stringResource(R.string.add_database)) }, + ) + } + }, + ) { padding -> + if (entries.isEmpty()) { + Empty(Modifier.padding(padding), onAdd = add, onSamples = { + library.addSamples() + library.entries.value.firstOrNull()?.let { onOpen(it.id) } + }) + } else { + LazyColumn( + Modifier.fillMaxSize(), + state = list, + contentPadding = PaddingValues(top = padding.calculateTopPadding(), bottom = padding.calculateBottomPadding() + 88.dp), + ) { + items(entries, key = { it.id }) { e -> + DatabaseRow( + e, + onOpen = { onOpen(e.id) }, + onRename = { renaming = e }, + onRemove = { + val removed = library.remove(e.id) ?: return@DatabaseRow + scope.launch { + snackbar.currentSnackbarData?.dismiss() + val r = snackbar.showSnackbar(removedText, undoText, withDismissAction = false) + if (r == SnackbarResult.ActionPerformed) library.restore(removed.first, removed.second) + } + }, + modifier = Modifier.animateItem(), + ) + } + } + } + } + renaming?.let { e -> + RenameDialog(e.name, onDismiss = { renaming = null }, onSave = { + library.rename(e.id, it) + renaming = null + }) + } +} + +@Composable +private fun Empty(modifier: Modifier, onAdd: () -> Unit, onSamples: () -> Unit) { + Column( + modifier.fillMaxSize().padding(horizontal = 32.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.Center, + ) { + Image(painterResource(R.drawable.penguin), null, Modifier.size(96.dp)) + Spacer(Modifier.height(24.dp)) + Text(stringResource(R.string.empty_title), style = MaterialTheme.typography.titleLarge, textAlign = TextAlign.Center) + Spacer(Modifier.height(12.dp)) + Text( + stringResource(R.string.empty_text), + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = TextAlign.Center, + modifier = Modifier.widthIn(max = 296.dp), + ) + Spacer(Modifier.height(32.dp)) + Button(onClick = onAdd, modifier = Modifier.height(48.dp)) { + Icon(Icons.Rounded.Add, null) + Spacer(Modifier.size(8.dp)) + Text(stringResource(R.string.add_database)) + } + TextButton(onClick = onSamples, modifier = Modifier.height(48.dp)) { Text(stringResource(R.string.open_samples)) } + } +} + +@OptIn(ExperimentalFoundationApi::class) +@Composable +private fun DatabaseRow(e: DbEntry, onOpen: () -> Unit, onRename: () -> Unit, onRemove: () -> Unit, modifier: Modifier) { + var menu by remember { mutableStateOf(false) } + val format = badge(e) + val subtitle = e.games?.let { + stringResource(R.string.games_with_format, pluralStringResource(R.plurals.games_count, it, groupDigits(it)), e.format ?: format) + } ?: stringResource(R.string.not_opened, format) + Row( + modifier + .fillMaxWidth() + .height(72.dp) + .combinedClickable(onClick = onOpen, onLongClick = { menu = true }) + .padding(start = 16.dp, end = 4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + FormatBadge(format) + Column(Modifier.weight(1f).padding(start = 16.dp)) { + Text(e.name, style = MaterialTheme.typography.bodyLarge, maxLines = 1, overflow = TextOverflow.Ellipsis) + Text( + subtitle, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + Box { + IconButton(onClick = { menu = true }) { Icon(Icons.Rounded.MoreVert, stringResource(R.string.menu)) } + DropdownMenu(expanded = menu, onDismissRequest = { menu = false }) { + DropdownMenuItem(text = { Text(stringResource(R.string.rename)) }, onClick = { + menu = false + onRename() + }) + DropdownMenuItem(text = { Text(stringResource(R.string.remove)) }, onClick = { + menu = false + onRemove() + }) + } + } + } +} + +@Composable +private fun RenameDialog(name: String, onDismiss: () -> Unit, onSave: (String) -> Unit) { + var value by remember { mutableStateOf(TextFieldValue(name, TextRange(0, name.length))) } + val trimmed = value.text.trim() + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(stringResource(R.string.rename)) }, + text = { + OutlinedTextField( + value = value, + onValueChange = { value = it }, + singleLine = true, + supportingText = { Text(stringResource(R.string.rename_hint)) }, + ) + }, + confirmButton = { TextButton(onClick = { onSave(trimmed) }, enabled = trimmed.isNotEmpty()) { Text(stringResource(R.string.save)) } }, + dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) } }, + ) +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/EngineViews.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/EngineViews.kt new file mode 100644 index 0000000..cd316e7 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/EngineViews.kt @@ -0,0 +1,290 @@ +package io.github.vrubelroman.chesspenguin.ui + +import androidx.compose.animation.core.animateFloatAsState +import androidx.compose.animation.core.tween +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.rounded.Close +import androidx.compose.material.icons.rounded.ExpandLess +import androidx.compose.material.icons.rounded.ExpandMore +import androidx.compose.material3.Button +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.LinearProgressIndicator +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.ModalBottomSheet +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.luminance +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import io.github.vrubelroman.chesspenguin.BuildConfig +import io.github.vrubelroman.chesspenguin.R +import io.github.vrubelroman.chesspenguin.data.EngineStatus +import io.github.vrubelroman.chesspenguin.data.NetProblem +import io.github.vrubelroman.chesspenguin.data.NetState +import io.github.vrubelroman.chesspenguin.theme.Tabular +import uniffi.mobile_api.Analysis +import uniffi.mobile_api.EngineLine +import kotlin.math.exp + +/// White's share of the bar, as on Lichess: 0.5 is equal, 1 is White winning. +fun whiteShare(line: EngineLine?): Float { + if (line == null) return 0.5f + line.mate?.let { return if (it > 0) 1f else 0f } + val cp = (line.cp ?: 0).coerceIn(-1000, 1000) + return (0.5 + 0.5 * (2 / (1 + exp(-0.00368208 * cp)) - 1)).toFloat() +} + +/// The engine's row between the board and the notation (android-ui.md §8.2): the +/// evaluation, the depth, the best line; ▾ shows more lines. +@Composable +fun EngineStrip( + status: EngineStatus, + analysis: Analysis?, + flipped: Boolean, + lines: Int, + expanded: Boolean, + onExpand: () -> Unit, + onLine: (EngineLine) -> Unit, + onDeeper: () -> Unit, + onRestart: () -> Unit, + notation: (String) -> AnnotatedString, +) { + val best = analysis?.lines?.firstOrNull() + val share by animateFloatAsState(whiteShare(best), tween(300), label = "eval") + Column(Modifier.fillMaxWidth().background(MaterialTheme.colorScheme.surfaceContainerLow)) { + // White's share on the left; on the right when the board is turned. + Row(Modifier.fillMaxWidth().height(3.dp)) { + // The light part must stand out from a light strip too. + val white = if (MaterialTheme.colorScheme.surface.luminance() > 0.5f) Color(0xFFD5D8DC) else Color(0xFFF5F5F0) + val black = Color(0xFF26282B) + val left = if (flipped) 1f - share else share + if (left > 0f) Box(Modifier.weight(left.coerceAtLeast(0.001f)).fillMaxHeight().background(if (flipped) black else white)) + if (left < 1f) Box(Modifier.weight((1f - left).coerceAtLeast(0.001f)).fillMaxHeight().background(if (flipped) white else black)) + } + if (status is EngineStatus.Failed) { + Row(Modifier.fillMaxWidth().height(48.dp).padding(start = 16.dp, end = 8.dp), verticalAlignment = Alignment.CenterVertically) { + Text( + stringResource(if (status.notStarting) R.string.engine_not_starting else R.string.engine_not_answering), + color = MaterialTheme.colorScheme.error, + style = MaterialTheme.typography.bodyMedium, + modifier = Modifier.weight(1f), + ) + if (!status.notStarting) TextButton(onClick = onRestart) { Text(stringResource(R.string.restart)) } + } + return@Column + } + LineRow(best, analysis, status, true, lines > 1, expanded, onExpand, onLine, onDeeper, notation) + if (expanded) { + analysis?.lines?.drop(1)?.take(lines - 1)?.forEach { l -> + LineRow(l, analysis, status, false, false, false, {}, onLine, {}, notation) + } + } + } +} + +@Composable +private fun LineRow( + line: EngineLine?, + analysis: Analysis?, + status: EngineStatus, + first: Boolean, + canExpand: Boolean, + expanded: Boolean, + onExpand: () -> Unit, + onLine: (EngineLine) -> Unit, + onDeeper: () -> Unit, + notation: (String) -> AnnotatedString, +) { + Row( + Modifier + .fillMaxWidth() + .height(if (first) 48.dp else 40.dp) + .then(if (line != null) Modifier.clickable { onLine(line) } else Modifier) + .padding(start = 8.dp, end = if (first) 0.dp else 16.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + EvalPlaque(line) + Spacer(Modifier.width(8.dp)) + if (first) { + val depth = analysis?.depth?.toInt() ?: 0 + val label = when { + line == null || status == EngineStatus.Starting -> stringResource(R.string.thinking) + status == EngineStatus.Paused -> stringResource(R.string.depth, depth) + " · " + stringResource(R.string.paused) + else -> stringResource(R.string.depth, depth) + } + Text( + label, + style = MaterialTheme.typography.bodyMedium.merge(Tabular), + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + ) + Spacer(Modifier.width(8.dp)) + } + Text( + line?.let { notation(it.text) } ?: AnnotatedString(""), + style = MaterialTheme.typography.bodyMedium, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), + ) + if (first && status == EngineStatus.Paused) { + TextButton(onClick = onDeeper) { Text(stringResource(R.string.deeper)) } + } else if (first && canExpand) { + IconButton(onClick = onExpand) { + Icon( + if (expanded) Icons.Rounded.ExpandLess else Icons.Rounded.ExpandMore, + stringResource(if (expanded) R.string.fewer_lines else R.string.more_lines), + ) + } + } + } +} + +/// The evaluation: light when White is better, dark when Black is (§8.2). +@Composable +private fun EvalPlaque(line: EngineLine?) { + val blackBetter = line != null && ((line.mate ?: 0) < 0 || (line.mate == null && (line.cp ?: 0) < 0)) + val bg = if (blackBetter) Color(0xFF26282B) else Color(0xFFF5F5F0) + val fg = if (blackBetter) Color(0xFFE8E8E8) else Color(0xFF1C1D1F) + Box( + Modifier + .width(56.dp) + .height(28.dp) + .clip(RoundedCornerShape(8.dp)) + .background(bg) + .border(1.dp, MaterialTheme.colorScheme.outlineVariant, RoundedCornerShape(8.dp)), + contentAlignment = Alignment.Center, + ) { + Text( + line?.eval?.let(::shortEval) ?: "", + color = fg, + fontSize = 15.sp, + fontWeight = FontWeight.Bold, + style = Tabular, + ) + } +} + +/// One decimal is enough on a phone (§8.2): "+0.45" → "+0.4". +fun shortEval(eval: String): String { + if (eval.contains('#')) return eval + val dot = eval.indexOf('.') + return if (dot >= 0 && eval.length > dot + 2) eval.substring(0, dot + 2) else eval +} + +/// The bar above the notation while an engine line is shown on the board (§8.3). +@Composable +fun PreviewBar(step: Int, total: Int, onClose: () -> Unit) { + Row( + Modifier + .fillMaxWidth() + .height(40.dp) + .background(MaterialTheme.colorScheme.primaryContainer) + .padding(start = 16.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + stringResource(R.string.engine_line_preview, step, total), + style = MaterialTheme.typography.labelLarge, + color = MaterialTheme.colorScheme.onPrimaryContainer, + modifier = Modifier.weight(1f), + ) + IconButton(onClick = onClose) { Icon(Icons.Rounded.Close, stringResource(R.string.close)) } + } +} + +private fun mb(bytes: Long) = (bytes / 1_000_000).toInt() + +/// The sheet that offers the download of the engine (light build, §8.4). +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun EngineSheet(state: NetState, metered: Boolean, onDownload: () -> Unit, onCancel: () -> Unit, onDismiss: () -> Unit) { + val size = mb(BuildConfig.NET_SIZE) + ModalBottomSheet(onDismissRequest = onDismiss) { + Column(Modifier.fillMaxWidth().padding(start = 24.dp, end = 24.dp, bottom = 24.dp)) { + Text(stringResource(R.string.engine_sheet_title), style = MaterialTheme.typography.titleLarge) + Spacer(Modifier.height(16.dp)) + Text(stringResource(R.string.engine_sheet_text), style = MaterialTheme.typography.bodyLarge) + Spacer(Modifier.height(16.dp)) + when (state) { + is NetState.Loading -> { + LinearProgressIndicator( + progress = { state.done.toFloat() / state.total.coerceAtLeast(1) }, + modifier = Modifier.fillMaxWidth(), + ) + Spacer(Modifier.height(8.dp)) + Text( + stringResource(R.string.downloaded_of, mb(state.done), mb(state.total)), + style = MaterialTheme.typography.bodyMedium.merge(Tabular), + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Spacer(Modifier.height(24.dp)) + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) { + TextButton(onClick = onCancel) { Text(stringResource(R.string.cancel_download)) } + } + } + is NetState.Failed -> { + val text = when (state.problem) { + NetProblem.NoInternet -> stringResource(R.string.no_internet) + NetProblem.Interrupted -> stringResource(R.string.interrupted) + NetProblem.NoSpace -> stringResource(R.string.no_space, size) + NetProblem.Corrupt -> stringResource(R.string.corrupt) + } + Text(text, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodyMedium) + Spacer(Modifier.height(24.dp)) + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End)) { + TextButton(onClick = onDismiss) { Text(stringResource(R.string.not_now)) } + when (state.problem) { + NetProblem.NoSpace -> Button(onClick = onDismiss) { Text(stringResource(R.string.ok)) } + NetProblem.NoInternet -> Button(onClick = onDownload) { Text(stringResource(R.string.retry)) } + NetProblem.Interrupted -> Button(onClick = onDownload) { Text(stringResource(R.string.resume)) } + NetProblem.Corrupt -> Button(onClick = onDownload) { Text(stringResource(R.string.download_again)) } + } + } + } + else -> { + Text(stringResource(R.string.engine_size, size), style = MaterialTheme.typography.bodyMedium.merge(Tabular)) + if (metered) { + Spacer(Modifier.height(8.dp)) + Text( + stringResource(R.string.engine_metered), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + Spacer(Modifier.height(24.dp)) + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End)) { + TextButton(onClick = onDismiss) { Text(stringResource(R.string.not_now)) } + Button(onClick = onDownload) { Text(stringResource(R.string.download)) } + } + } + } + } + } +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GameScreen.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GameScreen.kt new file mode 100644 index 0000000..6aab596 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GameScreen.kt @@ -0,0 +1,542 @@ +package io.github.vrubelroman.chesspenguin.ui + +import android.content.Context +import android.view.HapticFeedbackConstants +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.background +import androidx.compose.foundation.gestures.detectTapGestures +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.rememberScrollState +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.rounded.ArrowBack +import androidx.compose.material.icons.automirrored.rounded.ArrowLeft +import androidx.compose.material.icons.automirrored.rounded.ArrowRight +import androidx.compose.material.icons.outlined.Memory +import androidx.compose.material.icons.rounded.ChevronLeft +import androidx.compose.material.icons.rounded.ChevronRight +import androidx.compose.material.icons.rounded.Download +import androidx.compose.material.icons.rounded.FirstPage +import androidx.compose.material.icons.rounded.LastPage +import androidx.compose.material.icons.rounded.Memory +import androidx.compose.material.icons.rounded.Settings +import androidx.compose.material.icons.rounded.SwapVert +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.FilterChip +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.LocalContentColor +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalView +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.disabled +import androidx.compose.ui.semantics.onClick +import androidx.compose.ui.semantics.role +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.semantics.stateDescription +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.LifecycleEventObserver +import androidx.lifecycle.compose.LocalLifecycleOwner +import io.github.vrubelroman.chesspenguin.R +import io.github.vrubelroman.chesspenguin.data.EngineSession +import io.github.vrubelroman.chesspenguin.data.NetState +import io.github.vrubelroman.chesspenguin.data.enginePosition +import io.github.vrubelroman.chesspenguin.theme.Tabular +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import uniffi.mobile_api.EngineLine +import uniffi.mobile_api.GameData +import uniffi.mobile_api.MoveNode + +/// An engine line shown on the board (§8.3): the game itself does not change. +private data class Preview(val line: EngineLine, val step: Int) + +/// One game: the board on top, the notation under it, the move buttons at the bottom +/// under the thumb; ‹ › page the games of the list (android-ui.md §7). +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun GameScreen(db: String, startPlace: Int, onBack: () -> Unit, onSettings: () -> Unit) { + val app = app() + val context = LocalContext.current + val prefs by app.settings.prefs.collectAsState() + var games by remember { mutableStateOf(app.shown[db]) } + var place by rememberSaveable { mutableIntStateOf(startPlace) } + var game by remember { mutableStateOf(null) } + var failed by remember { mutableStateOf(false) } + var current by rememberSaveable(place) { mutableIntStateOf(0) } + var flipped by rememberSaveable { mutableStateOf(false) } + var preview by remember { mutableStateOf(null) } + LaunchedEffect(db, place) { + preview = null + val database = app.library.database(db).getOrNull() + if (database == null) { + failed = true + return@LaunchedEffect + } + // After the process was restarted the list is gone: page all the games. + val list = games ?: withContext(Dispatchers.Default) { database.find("") }.also { + games = it + app.shown[db] = it + } + val index = list.getOrNull(place) ?: return@LaunchedEffect + game = null + val loaded = withContext(Dispatchers.Default) { runCatching { database.game(index) } } + failed = loaded.isFailure + game = loaded.getOrNull() + } + val pieces = remember { Pieces(context) } + val snackbar = remember { SnackbarHostState() } + val scope = rememberCoroutineScope() + val view = LocalView.current + val hint = stringResource(R.string.board_hint) + val readyText = stringResource(R.string.engine_ready) + val cancelledText = stringResource(R.string.download_cancelled) + val total = games?.size ?: 0 + val lang = uiLanguage() + val san = remember(prefs.notation, lang) { { s: String -> displaySan(s, prefs.notation, lang) } } + val line = remember(prefs.notation, lang) { { s: String -> displayLine(s, prefs.notation, lang) } } + + // The engine: one process while this screen is visible and the button is on. + val files = app.engineFiles + val netState by files.state.collectAsState() + val session = remember { EngineSession(files, app.scope) } + val status by session.status.collectAsState() + val analysis by session.analysis.collectAsState() + var visible by remember { mutableStateOf(true) } + var sheet by remember { mutableStateOf(false) } + var wantEngine by remember { mutableStateOf(false) } + var expanded by rememberSaveable { mutableStateOf(false) } + val lifecycle = LocalLifecycleOwner.current.lifecycle + DisposableEffect(lifecycle) { + val observer = LifecycleEventObserver { _, e -> + when (e) { + Lifecycle.Event.ON_START -> visible = true + // The screen went dark or the app went away: the engine quits (§8.3). + Lifecycle.Event.ON_STOP -> { + visible = false + session.shutdown() + } + else -> {} + } + } + lifecycle.addObserver(observer) + onDispose { + lifecycle.removeObserver(observer) + session.shutdown() + } + } + + val g = game + val tag = { name: String -> g?.tags?.firstOrNull { it.name == name }?.value ?: "" } + val white = surname(tag("White")) + val black = surname(tag("Black")) + val resultText = g?.let { resultLine(context, it.result) } ?: "" + val (items, where) = remember(g, resultText) { g?.let { layout(it, resultText) } ?: (emptyList() to emptyMap()) } + val nodes = g?.nodes + val node = nodes?.getOrNull(current) + val notation = rememberLazyListState() + val engineReady = netState == NetState.Ready + val engineOn = prefs.engineOn && engineReady + + LaunchedEffect(g, current, engineOn, visible, prefs.engineLines, prefs.engineSeconds) { + if (g == null || !visible) return@LaunchedEffect + if (engineOn) session.show(enginePosition(g, current), prefs) else session.shutdown() + } + // A download started from the button turns the engine on when it is done. + LaunchedEffect(netState) { + if (netState == NetState.Ready && wantEngine) { + wantEngine = false + sheet = false + app.settings.update { it.copy(engineOn = true) } + if (!files.builtIn) snackbar.showSnackbar(readyText) + } + } + + fun buzz(edge: Boolean) { + if (prefs.vibration) view.performHapticFeedback(if (edge) HapticFeedbackConstants.CONFIRM else HapticFeedbackConstants.CLOCK_TICK) + } + fun go(to: Int) { + preview = null + if (nodes == null || to == current || to !in nodes.indices) return + current = to + buzz(to == 0 || nodes[to].children.isEmpty()) + } + fun stepPreview(by: Int) { + val p = preview ?: return + val next = p.step + by + if (next < 0) { + preview = null + } else if (next < p.line.steps.size) { + preview = p.copy(step = next) + buzz(next == p.line.steps.size - 1) + } + } + val canBack = preview != null || node?.parent != null + val canForward = preview?.let { it.step + 1 < it.line.steps.size } ?: (node?.children?.isNotEmpty() == true) + fun back() { + if (preview != null) stepPreview(-1) else node?.parent?.let { go(it.toInt()) } + } + fun forward() { + if (preview != null) stepPreview(1) else node?.children?.firstOrNull()?.let { go(it.toInt()) } + } + fun end() { + preview?.let { + preview = it.copy(step = it.line.steps.size - 1) + return + } + var n = node ?: return + while (n.children.isNotEmpty()) n = nodes[n.children[0].toInt()] + go(n.id.toInt()) + } + fun toggleEngine() { + when { + prefs.engineOn && engineReady -> app.settings.update { it.copy(engineOn = false) } + engineReady -> app.settings.update { it.copy(engineOn = true) } + files.builtIn -> { + wantEngine = true + files.prepare() + } + else -> sheet = true + } + } + BackHandler(preview != null) { preview = null } + + Scaffold( + topBar = { + TopAppBar( + navigationIcon = { + IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Rounded.ArrowBack, stringResource(R.string.back)) } + }, + title = { + Column { + Text( + when { + g == null -> "" + black == "?" && white != "?" -> white + else -> "$white – $black" + }, + style = MaterialTheme.typography.titleMedium, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + if (total > 0) { + Text( + joinKnown(stringResource(R.string.game_of, place + 1, total), g?.let { shortResult(it.result) } ?: ""), + style = MaterialTheme.typography.bodyMedium.merge(Tabular), + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + }, + actions = { + IconButton(onClick = { place -= 1 }, enabled = place > 0) { + Icon(Icons.Rounded.ChevronLeft, stringResource(R.string.previous_game)) + } + IconButton(onClick = { place += 1 }, enabled = place + 1 < total) { + Icon(Icons.Rounded.ChevronRight, stringResource(R.string.next_game)) + } + IconButton(onClick = onSettings) { Icon(Icons.Rounded.Settings, stringResource(R.string.settings)) } + }, + ) + }, + snackbarHost = { SnackbarHost(snackbar) }, + ) { padding -> + Column(Modifier.fillMaxSize().padding(top = padding.calculateTopPadding())) { + val p = preview + val step = p?.let { it.line.steps[it.step] } + val fen = step?.fen ?: node?.fen ?: START + val description = when { + step != null -> stringResource(R.string.board_description, step.label) + node == null || current == 0 -> stringResource(R.string.board_start) + else -> stringResource(R.string.board_description, (if (node.white) "${node.moveNumber}." else "${node.moveNumber}…") + node.san) + } + val arrows = buildList { + if (p != null) { + p.line.steps.getOrNull(p.step + 1)?.let { add(BoardArrow(it.fromSquare, it.toSquare, EngineArrow)) } + } else { + node?.marks?.forEach { m -> m.to?.let { add(BoardArrow(m.from, it, markColor(m.color), 0.9f)) } } + if (engineOn && prefs.bestArrow) { + analysis?.lines?.take(2)?.forEachIndexed { i, l -> + val f = l.fromSquare + val t = l.toSquare + if (f != null && t != null) { + add(BoardArrow(f, t, EngineArrow.copy(alpha = if (i == 0) 0.63f else 0.35f), if (i == 0) 1f else 0.7f)) + } + } + } + } + } + val marks = if (p == null) node?.marks?.filter { it.to == null }?.map { BoardMark(it.from, markColor(it.color)) }.orEmpty() else emptyList() + val check = (step?.label ?: node?.san ?: "").let { it.endsWith("+") || it.endsWith("#") } + Board( + fen = fen, + flipped = flipped, + lastFrom = step?.fromSquare ?: node?.fromSquare, + lastTo = step?.toSquare ?: node?.toSquare, + pieces = pieces, + description = description, + arrows = arrows, + marks = marks, + check = check, + animated = prefs.animation, + modifier = Modifier.pointerInput(Unit) { + detectTapGestures { + if (firstBoardTouch(context)) scope.launch { snackbar.showSnackbar(hint) } + } + }, + ) + if (engineOn) { + EngineStrip( + status = status, + analysis = analysis, + flipped = flipped, + lines = prefs.engineLines, + expanded = expanded, + onExpand = { expanded = !expanded }, + onLine = { l -> if (l.steps.isNotEmpty()) preview = Preview(l, 0) }, + onDeeper = { session.deeper() }, + onRestart = { + session.shutdown() + g?.let { session.show(enginePosition(it, current), prefs) } + }, + notation = line, + ) + } else if (wantEngine && netState is NetState.Loading) { + Row(Modifier.fillMaxWidth().height(48.dp).padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically) { + CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp) + Text(stringResource(R.string.preparing_engine), Modifier.padding(start = 12.dp), color = MaterialTheme.colorScheme.onSurfaceVariant) + } + } + if (p != null) PreviewBar(p.step + 1, p.line.steps.size, onClose = { preview = null }) + Box(Modifier.weight(1f).fillMaxWidth()) { + when { + g != null -> Notation(g, items, where, current, notation, san, onMove = ::go, modifier = Modifier.fillMaxSize()) + failed -> Text( + stringResource(R.string.game_failed), + color = MaterialTheme.colorScheme.error, + modifier = Modifier.align(Alignment.Center), + ) + else -> CircularProgressIndicator(Modifier.align(Alignment.Center)) + } + } + if (p == null && node != null && nodes != null && node.children.size > 1) { + Forks(node.children.map { nodes[it.toInt()] }, san, onMove = ::go) + } + HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant) + Surface(color = MaterialTheme.colorScheme.surfaceContainer) { + Row( + Modifier.fillMaxWidth().navigationBarsPadding().height(72.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + EngineButton( + on = engineOn, + needsDownload = !engineReady && !files.builtIn, + loading = netState as? NetState.Loading, + modifier = Modifier.weight(1.2f), + onClick = ::toggleEngine, + ) + BarButton(Icons.Rounded.SwapVert, stringResource(R.string.flip), true, Modifier.weight(1f)) { flipped = !flipped } + BarButton(Icons.Rounded.FirstPage, stringResource(R.string.to_start), canBack, Modifier.weight(1f)) { + if (preview != null) preview = null else go(0) + } + BarButton(Icons.AutoMirrored.Rounded.ArrowLeft, stringResource(R.string.move_back), canBack, Modifier.weight(1.5f), 44, repeat = true) { back() } + BarButton(Icons.AutoMirrored.Rounded.ArrowRight, stringResource(R.string.move_forward), canForward, Modifier.weight(1.5f), 44, repeat = true) { forward() } + BarButton(Icons.Rounded.LastPage, stringResource(R.string.to_end), canForward, Modifier.weight(1f)) { end() } + } + } + } + } + if (sheet) { + EngineSheet( + state = netState, + metered = remember(sheet) { !files.builtIn && files.metered() }, + onDownload = { + wantEngine = true + files.prepare() + }, + onCancel = { + files.cancel() + wantEngine = false + sheet = false + scope.launch { snackbar.showSnackbar(cancelledText) } + }, + onDismiss = { sheet = false }, + ) + } +} + +private const val START = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1" + +/// The engine switch of the bottom bar, with its label (§7.4): filled and underlined +/// when on; with a download mark while the light build has no engine yet. +@Composable +private fun EngineButton(on: Boolean, needsDownload: Boolean, loading: NetState.Loading?, modifier: Modifier, onClick: () -> Unit) { + val label = stringResource(R.string.engine) + val action by rememberUpdatedState(onClick) + val color = if (on) MaterialTheme.colorScheme.primary else LocalContentColor.current + Column( + modifier + .fillMaxHeight() + .semantics { + contentDescription = label + role = Role.Switch + stateDescription = if (on) "on" else "off" + onClick { action(); true } + } + .pointerInput(Unit) { detectTapGestures { action() } }, + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.Center, + ) { + Box(Modifier.size(36.dp), contentAlignment = Alignment.Center) { + Icon(if (on) Icons.Rounded.Memory else Icons.Outlined.Memory, null, tint = color) + if (loading != null) { + CircularProgressIndicator( + progress = { loading.done.toFloat() / loading.total.coerceAtLeast(1) }, + modifier = Modifier.size(34.dp), + strokeWidth = 2.dp, + ) + } else if (needsDownload) { + Icon( + Icons.Rounded.Download, + null, + tint = color, + modifier = Modifier.size(14.dp).align(Alignment.BottomEnd).background(MaterialTheme.colorScheme.surfaceContainer), + ) + } + } + Text(label, style = MaterialTheme.typography.labelSmall, color = color) + Box(Modifier.padding(top = 2.dp).width(24.dp).height(2.dp).background(if (on) MaterialTheme.colorScheme.primary else Color.Transparent)) + } +} + +/// The row of continuations at a fork (§7.5): the line's own move first and filled. +@Composable +private fun Forks(moves: List, san: (String) -> AnnotatedString, onMove: (Int) -> Unit) { + Row( + Modifier.fillMaxWidth().height(48.dp).horizontalScroll(rememberScrollState()).padding(horizontal = 16.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + Text(stringResource(R.string.next_moves), style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.onSurfaceVariant) + moves.forEachIndexed { i, m -> + FilterChip( + selected = i == 0, + onClick = { onMove(m.id.toInt()) }, + label = { Text(AnnotatedString(if (m.white) "${m.moveNumber}." else "${m.moveNumber}…") + san(m.san)) }, + ) + } + } +} + +/// A button of the bottom bar. With `repeat`, holding it steps again after 400 ms and +/// then every 120 ms (§7.4). +@Composable +private fun BarButton( + icon: ImageVector, + label: String, + enabled: Boolean, + modifier: Modifier, + iconSize: Int = 24, + repeat: Boolean = false, + onClick: () -> Unit, +) { + val action by rememberUpdatedState(onClick) + val on by rememberUpdatedState(enabled) + val color = if (enabled) LocalContentColor.current else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f) + Box( + modifier + .fillMaxHeight() + .semantics { + contentDescription = label + role = Role.Button + if (!enabled) disabled() + onClick { action(); true } + } + .pointerInput(repeat) { + detectTapGestures(onPress = { + if (!on) return@detectTapGestures + action() + if (!repeat) return@detectTapGestures + coroutineScope { + val job = launch { + delay(400) + while (on) { + action() + delay(120) + } + } + tryAwaitRelease() + job.cancel() + } + }) + }, + contentAlignment = Alignment.Center, + ) { + Icon(icon, null, tint = color, modifier = Modifier.size(iconSize.dp)) + } +} + +/// "Carlsen, Magnus" → "Carlsen"; "Magnus Carlsen" stays as it is. +private fun surname(name: String): String = name.substringBefore(',').trim().ifEmpty { "?" } + +/// "1-0 · White won" for the end of the notation. +private fun resultLine(context: Context, result: String): String = when (result) { + "1-0" -> "1-0 · " + context.getString(R.string.white_won) + "0-1" -> "0-1 · " + context.getString(R.string.black_won) + "1/2-1/2" -> "½-½ · " + context.getString(R.string.draw) + else -> "" +} + +/// True only the very first time the board is touched (then the hint is shown). +private fun firstBoardTouch(context: Context): Boolean { + val prefs = context.getSharedPreferences("hints", Context.MODE_PRIVATE) + if (prefs.getBoolean("board", false)) return false + prefs.edit().putBoolean("board", true).apply() + return true +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GamesScreen.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GamesScreen.kt new file mode 100644 index 0000000..c64b41d --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GamesScreen.kt @@ -0,0 +1,242 @@ +package io.github.vrubelroman.chesspenguin.ui + +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.text.KeyboardActions +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.rounded.ArrowBack +import androidx.compose.material.icons.rounded.Close +import androidx.compose.material.icons.rounded.Search +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Text +import androidx.compose.material3.TextField +import androidx.compose.material3.TextFieldDefaults +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateMapOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.input.nestedscroll.nestedScroll +import androidx.compose.ui.platform.LocalSoftwareKeyboardController +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import io.github.vrubelroman.chesspenguin.R +import io.github.vrubelroman.chesspenguin.theme.Tabular +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay +import kotlinx.coroutines.withContext +import uniffi.mobile_api.Database +import uniffi.mobile_api.GameRow + +private const val CHUNK = 100 + +/// The games of a database, with a search (android-ui.md §6). +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun GamesScreen(db: String, onBack: () -> Unit, onGame: (Int) -> Unit) { + val app = app() + val entries by app.library.entries.collectAsState() + val entry = entries.firstOrNull { it.id == db } + var database by remember { mutableStateOf(null) } + var failed by remember { mutableStateOf(null) } + LaunchedEffect(db) { + app.library.database(db).onSuccess { database = it }.onFailure { failed = it.message ?: "" } + } + var searching by rememberSaveable { mutableStateOf(false) } + var query by rememberSaveable { mutableStateOf("") } + var shown by remember { mutableStateOf?>(null) } + val rows = remember { mutableStateMapOf>() } + LaunchedEffect(database, query) { + val d = database ?: return@LaunchedEffect + if (query.isNotEmpty()) delay(250) + val found = withContext(Dispatchers.Default) { d.find(query) } + rows.clear() + shown = found + app.shown[db] = found + } + val list = rememberLazyListState() + val scroll = TopAppBarDefaults.pinnedScrollBehavior() + val focus = remember { FocusRequester() } + val keyboard = LocalSoftwareKeyboardController.current + BackHandler(searching) { + searching = false + query = "" + } + + Scaffold( + modifier = Modifier.nestedScroll(scroll.nestedScrollConnection), + topBar = { + TopAppBar( + navigationIcon = { + IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Rounded.ArrowBack, stringResource(R.string.back)) } + }, + title = { + if (searching) { + TextField( + value = query, + onValueChange = { query = it }, + placeholder = { Text(stringResource(R.string.search_hint)) }, + singleLine = true, + keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search), + keyboardActions = KeyboardActions(onSearch = { keyboard?.hide() }), + colors = TextFieldDefaults.colors( + focusedContainerColor = Color.Transparent, + unfocusedContainerColor = Color.Transparent, + focusedIndicatorColor = Color.Transparent, + unfocusedIndicatorColor = Color.Transparent, + ), + modifier = Modifier.fillMaxWidth().focusRequester(focus), + ) + LaunchedEffect(Unit) { focus.requestFocus() } + } else { + Column { + Text(entry?.name ?: "", maxLines = 1, overflow = TextOverflow.Ellipsis) + database?.let { d -> + val n = d.len().toInt() + Text( + pluralStringResource(R.plurals.games_count, n, groupDigits(n)), + style = MaterialTheme.typography.bodyMedium.merge(Tabular), + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + } + }, + actions = { + if (searching) { + IconButton(onClick = { + if (query.isEmpty()) searching = false else query = "" + }) { Icon(Icons.Rounded.Close, stringResource(R.string.clear)) } + } else if (database != null) { + IconButton(onClick = { searching = true }) { Icon(Icons.Rounded.Search, stringResource(R.string.search)) } + } + }, + scrollBehavior = scroll, + ) + }, + ) { padding -> + Box(Modifier.fillMaxSize().padding(padding)) { + val games = shown + when { + failed != null -> Message(stringResource(R.string.open_failed), failed!!) + games == null -> Column(Modifier.align(Alignment.Center), horizontalAlignment = Alignment.CenterHorizontally) { + CircularProgressIndicator() + Spacer(Modifier.height(16.dp)) + Text(stringResource(R.string.reading), color = MaterialTheme.colorScheme.onSurfaceVariant) + } + games.isEmpty() -> Message(stringResource(R.string.nothing_found), "") + else -> LazyColumn(Modifier.fillMaxSize(), state = list) { + items(games.size, key = { games[it].toLong() }) { place -> + val chunk = place / CHUNK + val loaded = rows[chunk] + LaunchedEffect(chunk, games) { + if (rows[chunk] == null) { + val d = database ?: return@LaunchedEffect + val part = games.subList(chunk * CHUNK, minOf(games.size, (chunk + 1) * CHUNK)) + rows[chunk] = withContext(Dispatchers.Default) { d.rowsOf(part) } + } + } + GameRowView(loaded?.getOrNull(place % CHUNK)) { onGame(place) } + } + } + } + } + } +} + +@Composable +private fun Message(title: String, detail: String) { + Column(Modifier.fillMaxSize().padding(32.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) { + Text(title, style = MaterialTheme.typography.titleLarge, textAlign = TextAlign.Center) + if (detail.isNotEmpty()) { + Spacer(Modifier.height(8.dp)) + Text(detail, color = MaterialTheme.colorScheme.onSurfaceVariant, textAlign = TextAlign.Center) + } + } +} + +/// One game: "White – Black" and the result, then event · year · ECO (§6.2). +@Composable +private fun GameRowView(row: GameRow?, onClick: () -> Unit) { + Row( + Modifier + .fillMaxWidth() + .height(64.dp) + .clickable(enabled = row != null, onClick = onClick) + .padding(horizontal = 16.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Column(Modifier.weight(1f)) { + if (row == null) return@Column + Row { + Text( + shortName(row.white), + style = MaterialTheme.typography.bodyLarge, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f, fill = false), + ) + // A study or a book position often has a title for White and no Black. + if (shortName(row.black) != "?" || shortName(row.white) == "?") { + Text(" – ", style = MaterialTheme.typography.bodyLarge) + Text( + shortName(row.black), + style = MaterialTheme.typography.bodyLarge, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f, fill = false), + ) + } + } + val details = joinKnown(row.event, year(row.date), row.eco) + if (details.isNotEmpty()) { + Text( + details, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + } + Text( + row?.let { shortResult(it.result) } ?: "", + style = MaterialTheme.typography.bodyLarge.merge(Tabular), + textAlign = TextAlign.End, + modifier = Modifier.width(48.dp).padding(start = 8.dp), + ) + } +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/Notation.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/Notation.kt new file mode 100644 index 0000000..191aac6 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/Notation.kt @@ -0,0 +1,325 @@ +package io.github.vrubelroman.chesspenguin.ui + +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.LazyListState +import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.LinkAnnotation +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.TextLinkStyles +import androidx.compose.ui.text.buildAnnotatedString +import androidx.compose.ui.text.font.FontStyle +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.withLink +import androidx.compose.ui.text.withStyle +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import io.github.vrubelroman.chesspenguin.theme.ChessColors +import io.github.vrubelroman.chesspenguin.theme.LocalChessColors +import io.github.vrubelroman.chesspenguin.theme.nagColor +import uniffi.mobile_api.GameData +import uniffi.mobile_api.MoveNode + +/// A piece of the notation: the main line as a table of moves, comments and variations +/// as full-width blocks between its rows (as on the desktop, android-ui.md §7.3). +sealed interface Item { + data class Comment(val text: String) : Item + data class Moves(val number: Int, val white: Int?, val black: Int?) : Item + data class Variation(val start: Int, val depth: Int) : Item + data class Result(val text: String) : Item +} + +/// The items of a game, and for each node the item that shows it (to keep it in view). +fun layout(game: GameData, resultText: String): Pair, Map> { + val nodes = game.nodes + val items = ArrayList() + val where = HashMap() + fun node(i: Int) = nodes[i] + val root = node(0) + if (root.commentAfter.isNotEmpty()) items += Item.Comment(root.commentAfter) + var row: Item.Moves? = null + fun flush() { + row?.let { r -> + items += r + r.white?.let { where[it] = items.size - 1 } + r.black?.let { where[it] = items.size - 1 } + } + row = null + } + fun markVariation(start: Int, at: Int) { + // Every node of the variation (its whole subtree) is shown by this item. + val stack = ArrayDeque(listOf(start)) + while (stack.isNotEmpty()) { + val n = stack.removeLast() + where[n] = at + node(n).children.forEach { stack.add(it.toInt()) } + } + } + var parent = 0 + while (true) { + val kids = node(parent).children + if (kids.isEmpty()) break + val id = kids[0].toInt() + val n = node(id) + if (n.commentBefore.isNotEmpty()) { + flush() + items += Item.Comment(n.commentBefore) + } + if (n.white) { + flush() + row = Item.Moves(n.moveNumber.toInt(), id, null) + } else { + row = (row ?: Item.Moves(n.moveNumber.toInt(), null, null)).copy(black = id) + } + val variations = kids.drop(1).map { it.toInt() } + val interrupted = n.commentAfter.isNotEmpty() || variations.isNotEmpty() + if (interrupted || !n.white) { + flush() + if (n.commentAfter.isNotEmpty()) items += Item.Comment(n.commentAfter) + for (v in variations) { + items += Item.Variation(v, 1) + markVariation(v, items.size - 1) + } + } + parent = id + } + flush() + if (resultText.isNotEmpty()) items += Item.Result(resultText) + return items to where +} + +private fun label(n: MoveNode, number: Boolean, san: (String) -> AnnotatedString): AnnotatedString = when { + n.white -> AnnotatedString("${n.moveNumber}.") + san(n.san) + number -> AnnotatedString("${n.moveNumber}…") + san(n.san) + else -> san(n.san) +} + +/// A variation as flowing text: its moves (each a link), comments in italics, nested +/// variations in parentheses. +@Composable +private fun variationText( + game: GameData, + start: Int, + current: Int, + chess: ChessColors, + san: (String) -> AnnotatedString, + onMove: (Int) -> Unit, +): AnnotatedString { + val nodes = game.nodes + val comment = chess.comment + val onSurface = MaterialTheme.colorScheme.onSurface + return remember(game, start, current, san) { + buildAnnotatedString { + // A space goes before each word, except right after "(". + var space = false + fun word(write: () -> Unit) { + if (space) append(' ') + write() + space = true + } + fun line(first: Int) { + var id = first + var number = true + while (true) { + val n = nodes[id] + if (n.commentBefore.isNotEmpty()) { + word { withStyle(SpanStyle(color = comment, fontStyle = FontStyle.Italic)) { append(n.commentBefore) } } + number = true + } + val style = if (id == current) { + SpanStyle(background = chess.currentMove, color = onSurface, fontWeight = FontWeight.Medium) + } else { + SpanStyle(color = onSurface) + } + val target = id + word { + withLink(LinkAnnotation.Clickable("m$id", TextLinkStyles(style)) { onMove(target) }) { + append(label(n, number, san)) + } + if (n.nagSymbols.isNotEmpty()) { + val c = n.nags.firstOrNull()?.let { nagColor(it.toInt()) } ?: onSurface + withStyle(SpanStyle(color = c)) { append(n.nagSymbols) } + } + } + number = false + if (n.commentAfter.isNotEmpty()) { + word { withStyle(SpanStyle(color = comment, fontStyle = FontStyle.Italic)) { append(n.commentAfter) } } + number = true + } + // The alternatives to this move (but not to the line's first move: those + // belong to the level above). + if (id != first) { + val parent = n.parent?.toInt() + if (parent != null) { + for (v in nodes[parent].children.drop(1)) { + word { append('(') } + space = false + line(v.toInt()) + append(')') + number = true + } + } + } + val next = n.children.firstOrNull() ?: break + id = next.toInt() + } + } + line(start) + } + } +} + +/// The notation under the board (android-ui.md §7.3): the current move highlighted +/// and kept in view; a tap on a move goes there. +@Composable +fun Notation( + game: GameData, + items: List, + where: Map, + current: Int, + state: LazyListState, + san: (String) -> AnnotatedString, + onMove: (Int) -> Unit, + modifier: Modifier = Modifier, +) { + val chess = LocalChessColors.current + LaunchedEffect(current) { + val at = where[current] ?: if (current == 0) 0 else return@LaunchedEffect + val visible = state.layoutInfo.visibleItemsInfo + if (visible.none { it.index == at } || visible.firstOrNull()?.index == at || visible.lastOrNull()?.index == at) { + // Keep the current move about the middle of what is visible. + state.animateScrollToItem((at - 2).coerceAtLeast(0)) + } + } + LazyColumn(modifier, state = state, contentPadding = PaddingValues(bottom = 8.dp)) { + itemsIndexed(items) { _, item -> + when (item) { + is Item.Comment -> Text( + item.text, + color = chess.comment, + fontSize = 15.sp, + lineHeight = 22.sp, + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 8.dp, vertical = 4.dp) + .clip(RoundedCornerShape(12.dp)) + .background(MaterialTheme.colorScheme.surfaceContainerLow) + .padding(horizontal = 12.dp, vertical = 8.dp), + ) + is Item.Moves -> MovesRow(game, item, current, chess, san, onMove) + is Item.Variation -> Box( + Modifier + .fillMaxWidth() + .padding(start = (8 + 16 * (item.depth - 1)).dp, end = 8.dp, top = 2.dp, bottom = 2.dp), + ) { + Row(Modifier.height(androidx.compose.foundation.layout.IntrinsicSize.Min)) { + Box(Modifier.width(2.dp).fillMaxHeight().background(MaterialTheme.colorScheme.outlineVariant)) + Text( + variationText(game, item.start, current, chess, san, onMove), + fontSize = 15.sp, + lineHeight = 28.sp, + modifier = Modifier.padding(start = 12.dp, end = 4.dp), + ) + } + } + is Item.Result -> Box(Modifier.fillMaxWidth().padding(16.dp), contentAlignment = Alignment.Center) { + Text( + item.text, + style = MaterialTheme.typography.labelLarge, + modifier = Modifier + .clip(RoundedCornerShape(8.dp)) + .background(MaterialTheme.colorScheme.surfaceContainerHigh) + .padding(horizontal = 16.dp, vertical = 8.dp), + ) + } + } + } + } +} + +@Composable +private fun MovesRow( + game: GameData, + row: Item.Moves, + current: Int, + chess: ChessColors, + san: (String) -> AnnotatedString, + onMove: (Int) -> Unit, +) { + Row(Modifier.fillMaxWidth().height(48.dp), verticalAlignment = Alignment.CenterVertically) { + Text( + "${row.number}", + color = MaterialTheme.colorScheme.onSurfaceVariant, + fontSize = 15.sp, + modifier = Modifier.width(40.dp).padding(end = 8.dp), + textAlign = androidx.compose.ui.text.style.TextAlign.End, + ) + MoveCell(game, row.white, current, chess, san, onMove, Modifier.weight(1f)) + MoveCell(game, row.black, current, chess, san, onMove, Modifier.weight(1f)) + } +} + +@Composable +private fun MoveCell( + game: GameData, + id: Int?, + current: Int, + chess: ChessColors, + san: (String) -> AnnotatedString, + onMove: (Int) -> Unit, + modifier: Modifier, +) { + val selected = id != null && id == current + // The whole cell takes the tap; the fill only hugs the move. + Box( + modifier + .fillMaxHeight() + .then(if (id != null) Modifier.clickable { onMove(id) } else Modifier) + .padding(start = 4.dp), + contentAlignment = Alignment.CenterStart, + ) { + if (id == null) { + Text("…", color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 17.sp, modifier = Modifier.padding(horizontal = 8.dp)) + } else { + val n = game.nodes[id] + Row( + Modifier + .clip(RoundedCornerShape(6.dp)) + .background(if (selected) chess.currentMove else Color.Transparent) + .padding(horizontal = 8.dp, vertical = 6.dp), + horizontalArrangement = Arrangement.spacedBy(1.dp), + ) { + Text(san(n.san), fontSize = 17.sp, fontWeight = FontWeight.Medium, color = MaterialTheme.colorScheme.onSurface) + if (n.nagSymbols.isNotEmpty()) { + Text( + n.nagSymbols, + fontSize = 17.sp, + fontWeight = FontWeight.Medium, + color = n.nags.firstOrNull()?.let { nagColor(it.toInt()) } ?: MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + } + } +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/SettingsScreen.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/SettingsScreen.kt new file mode 100644 index 0000000..b6e955a --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/SettingsScreen.kt @@ -0,0 +1,241 @@ +package io.github.vrubelroman.chesspenguin.ui + +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.rounded.ArrowBack +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.RadioButton +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults +import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.input.nestedscroll.nestedScroll +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.unit.dp +import io.github.vrubelroman.chesspenguin.BuildConfig +import io.github.vrubelroman.chesspenguin.R +import io.github.vrubelroman.chesspenguin.data.NetState +import io.github.vrubelroman.chesspenguin.data.Notation +import io.github.vrubelroman.chesspenguin.data.Theme + +/// One screen of groups, changes apply at once (android-ui.md §9). Boards and piece +/// sets are not chosen in the first version (§16). +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun SettingsScreen(onBack: () -> Unit, onAbout: () -> Unit) { + val app = app() + val prefs by app.settings.prefs.collectAsState() + val files = app.engineFiles + val net by files.state.collectAsState() + val set = app.settings::update + var choice by remember { mutableStateOf(null) } + var deleting by remember { mutableStateOf(false) } + val lang = uiLanguage() + val scroll = TopAppBarDefaults.pinnedScrollBehavior() + val size = (BuildConfig.NET_SIZE / 1_000_000).toInt() + + val themeNames = listOf( + Theme.System to stringResource(R.string.theme_system), + Theme.Light to stringResource(R.string.theme_light), + Theme.Dark to stringResource(R.string.theme_dark), + ) + val notationNames = buildList { + add(Notation.Latin to stringResource(R.string.notation_latin)) + add(Notation.Figurines to stringResource(R.string.notation_figurines)) + // English has no letters of its own (move-notation.md §2.1). + if (lang != "en") add(Notation.Local to stringResource(R.string.notation_local)) + } + val secondsNames = listOf( + 10 to stringResource(R.string.seconds, 10), + 20 to stringResource(R.string.seconds, 20), + 60 to stringResource(R.string.one_minute), + 0 to stringResource(R.string.no_limit), + ) + val cores = Runtime.getRuntime().availableProcessors() + + Scaffold( + modifier = Modifier.nestedScroll(scroll.nestedScrollConnection), + topBar = { + TopAppBar( + title = { Text(stringResource(R.string.settings)) }, + navigationIcon = { + IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Rounded.ArrowBack, stringResource(R.string.back)) } + }, + scrollBehavior = scroll, + ) + }, + ) { padding -> + Column(Modifier.fillMaxSize().padding(padding).verticalScroll(rememberScrollState()).padding(bottom = 24.dp)) { + Group(stringResource(R.string.group_look)) + Item(stringResource(R.string.theme), themeNames.first { it.first == prefs.theme }.second) { + choice = Choice(R.string.theme, themeNames.map { it.second }, themeNames.indexOfFirst { it.first == prefs.theme }) { i -> + set { it.copy(theme = themeNames[i].first) } + } + } + val notationNow = notationNames.firstOrNull { it.first == prefs.notation } ?: notationNames.first() + Item(stringResource(R.string.notation), notationNow.second) { + choice = Choice( + R.string.notation, + notationNames.map { it.second }, + notationNames.indexOf(notationNow), + hint = R.string.notation_hint, + ) { i -> set { it.copy(notation = notationNames[i].first) } } + } + + Group(stringResource(R.string.group_board)) + Toggle(stringResource(R.string.animation), prefs.animation) { v -> set { it.copy(animation = v) } } + Toggle(stringResource(R.string.best_arrow), prefs.bestArrow) { v -> set { it.copy(bestArrow = v) } } + Toggle(stringResource(R.string.vibration), prefs.vibration) { v -> set { it.copy(vibration = v) } } + + Group(stringResource(R.string.group_engine)) + when { + files.builtIn -> Item(stringResource(R.string.engine_built_in), null, null) + net == NetState.Ready -> { + Item(stringResource(R.string.engine_downloaded), null, null) + Item(stringResource(R.string.engine_delete, size), null) { deleting = true } + } + net is NetState.Loading -> { + val l = net as NetState.Loading + Item(stringResource(R.string.engine_downloading, (l.done / 1_000_000).toInt(), (l.total / 1_000_000).toInt()), null, null) + } + else -> Item(stringResource(R.string.engine_missing, size), null) { files.prepare() } + } + Item(stringResource(R.string.lines), "${prefs.engineLines}") { + choice = Choice(R.string.lines, listOf("1", "2", "3"), prefs.engineLines - 1) { i -> set { it.copy(engineLines = i + 1) } } + } + Item(stringResource(R.string.time_per_position), secondsNames.firstOrNull { it.first == prefs.engineSeconds }?.second ?: "") { + choice = Choice(R.string.time_per_position, secondsNames.map { it.second }, secondsNames.indexOfFirst { it.first == prefs.engineSeconds }) { i -> + set { it.copy(engineSeconds = secondsNames[i].first) } + } + } + Item(stringResource(R.string.threads), "${prefs.engineThreads}") { + choice = Choice(R.string.threads, (1..cores).map { "$it" }, prefs.engineThreads - 1) { i -> set { it.copy(engineThreads = i + 1) } } + } + val hashes = listOf(16, 32, 64, 128, 256) + val hashNames = hashes.map { stringResource(R.string.megabytes, it) } + Item(stringResource(R.string.memory), stringResource(R.string.megabytes, prefs.engineHashMb)) { + choice = Choice(R.string.memory, hashNames, hashes.indexOf(prefs.engineHashMb)) { i -> set { it.copy(engineHashMb = hashes[i]) } } + } + Text( + stringResource(R.string.engine_battery), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp), + ) + Spacer(Modifier.height(16.dp)) + Item(stringResource(R.string.about), null, onAbout) + } + } + + choice?.let { c -> + AlertDialog( + onDismissRequest = { choice = null }, + title = { Text(stringResource(c.title)) }, + text = { + Column { + c.options.forEachIndexed { i, label -> + Row( + Modifier + .fillMaxWidth() + .heightIn(min = 48.dp) + .selectable(selected = i == c.selected, role = Role.RadioButton) { + c.pick(i) + choice = null + }, + verticalAlignment = Alignment.CenterVertically, + ) { + RadioButton(selected = i == c.selected, onClick = null) + Text(label, Modifier.padding(start = 16.dp), style = MaterialTheme.typography.bodyLarge) + } + } + c.hint?.let { + Spacer(Modifier.height(8.dp)) + Text(stringResource(it), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + } + }, + confirmButton = { TextButton(onClick = { choice = null }) { Text(stringResource(R.string.cancel)) } }, + ) + } + if (deleting) { + AlertDialog( + onDismissRequest = { deleting = false }, + text = { Text(stringResource(R.string.engine_delete_question)) }, + confirmButton = { + TextButton(onClick = { + files.delete() + deleting = false + }) { Text(stringResource(R.string.delete)) } + }, + dismissButton = { TextButton(onClick = { deleting = false }) { Text(stringResource(R.string.cancel)) } }, + ) + } +} + +private class Choice(val title: Int, val options: List, val selected: Int, val hint: Int? = null, val pick: (Int) -> Unit) + +@Composable +private fun Group(title: String) { + Text( + title, + style = MaterialTheme.typography.labelLarge, + color = MaterialTheme.colorScheme.primary, + modifier = Modifier.padding(start = 16.dp, end = 16.dp, top = 24.dp, bottom = 8.dp), + ) +} + +@Composable +private fun Item(title: String, value: String?, onClick: (() -> Unit)?) { + Column( + Modifier + .fillMaxWidth() + .heightIn(min = 56.dp) + .then(if (onClick != null) Modifier.clickable(onClick = onClick) else Modifier) + .padding(horizontal = 16.dp, vertical = 8.dp), + verticalArrangement = androidx.compose.foundation.layout.Arrangement.Center, + ) { + Text(title, style = MaterialTheme.typography.bodyLarge) + if (value != null) Text(value, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + } +} + +@Composable +private fun Toggle(title: String, value: Boolean, onChange: (Boolean) -> Unit) { + Row( + Modifier + .fillMaxWidth() + .heightIn(min = 56.dp) + .selectable(selected = value, role = Role.Switch) { onChange(!value) } + .padding(horizontal = 16.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text(title, style = MaterialTheme.typography.bodyLarge, modifier = Modifier.weight(1f)) + Switch(checked = value, onCheckedChange = null) + } +} diff --git a/androidApp/app/src/main/res/drawable-nodpi/penguin.png b/androidApp/app/src/main/res/drawable-nodpi/penguin.png new file mode 100644 index 0000000..f57a3c8 Binary files /dev/null and b/androidApp/app/src/main/res/drawable-nodpi/penguin.png differ diff --git a/androidApp/app/src/main/res/drawable/ic_launcher_background.xml b/androidApp/app/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 0000000..07d5da9 --- /dev/null +++ b/androidApp/app/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,170 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/androidApp/app/src/main/res/drawable/ic_launcher_foreground.xml b/androidApp/app/src/main/res/drawable/ic_launcher_foreground.xml new file mode 100644 index 0000000..2b068d1 --- /dev/null +++ b/androidApp/app/src/main/res/drawable/ic_launcher_foreground.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/androidApp/app/src/main/res/font/figurines.ttf b/androidApp/app/src/main/res/font/figurines.ttf new file mode 100644 index 0000000..dbc3e1b Binary files /dev/null and b/androidApp/app/src/main/res/font/figurines.ttf differ diff --git a/androidApp/app/src/main/res/font/nag_symbols.ttf b/androidApp/app/src/main/res/font/nag_symbols.ttf new file mode 100644 index 0000000..3134da8 Binary files /dev/null and b/androidApp/app/src/main/res/font/nag_symbols.ttf differ diff --git a/androidApp/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/androidApp/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 0000000..6f3b755 --- /dev/null +++ b/androidApp/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/androidApp/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/androidApp/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100644 index 0000000..6f3b755 --- /dev/null +++ b/androidApp/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/androidApp/app/src/main/res/mipmap-hdpi/ic_launcher.webp b/androidApp/app/src/main/res/mipmap-hdpi/ic_launcher.webp new file mode 100644 index 0000000..c209e78 Binary files /dev/null and b/androidApp/app/src/main/res/mipmap-hdpi/ic_launcher.webp differ diff --git a/androidApp/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp b/androidApp/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp new file mode 100644 index 0000000..b2dfe3d Binary files /dev/null and b/androidApp/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp differ diff --git a/androidApp/app/src/main/res/mipmap-mdpi/ic_launcher.webp b/androidApp/app/src/main/res/mipmap-mdpi/ic_launcher.webp new file mode 100644 index 0000000..4f0f1d6 Binary files /dev/null and b/androidApp/app/src/main/res/mipmap-mdpi/ic_launcher.webp differ diff --git a/androidApp/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp b/androidApp/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp new file mode 100644 index 0000000..62b611d Binary files /dev/null and b/androidApp/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp differ diff --git a/androidApp/app/src/main/res/mipmap-xhdpi/ic_launcher.webp b/androidApp/app/src/main/res/mipmap-xhdpi/ic_launcher.webp new file mode 100644 index 0000000..948a307 Binary files /dev/null and b/androidApp/app/src/main/res/mipmap-xhdpi/ic_launcher.webp differ diff --git a/androidApp/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp b/androidApp/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp new file mode 100644 index 0000000..1b9a695 Binary files /dev/null and b/androidApp/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp differ diff --git a/androidApp/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp b/androidApp/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp new file mode 100644 index 0000000..28d4b77 Binary files /dev/null and b/androidApp/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp differ diff --git a/androidApp/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp b/androidApp/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp new file mode 100644 index 0000000..9287f50 Binary files /dev/null and b/androidApp/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp differ diff --git a/androidApp/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp b/androidApp/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp new file mode 100644 index 0000000..aa7d642 Binary files /dev/null and b/androidApp/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp differ diff --git a/androidApp/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp b/androidApp/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp new file mode 100644 index 0000000..9126ae3 Binary files /dev/null and b/androidApp/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp differ diff --git a/androidApp/app/src/main/res/values-ru/strings.xml b/androidApp/app/src/main/res/values-ru/strings.xml new file mode 100644 index 0000000..8277ff1 --- /dev/null +++ b/androidApp/app/src/main/res/values-ru/strings.xml @@ -0,0 +1,122 @@ + + Классические партии + Алехин + + Здесь будут ваши базы + Добавьте файл PGN или архив .zip/.7z — с телефона или из облака. + Добавить базу + Открыть примеры партий + ещё не открывалась · %1$s + + %1$s партия + %1$s партии + %1$s партий + %1$s партии + + %1$s · %2$s + Меню + Переименовать + Убрать из списка + Название в списке. Файл не меняется. + Отмена + Сохранить + База убрана из списка + Вернуть + Назад + + Читаю… + Не удалось открыть базу + Нет доступа к файлу. Добавьте его заново. + Поиск + Игрок, турнир, год + Ничего не найдено + Очистить + + %1$d из %2$d + Предыдущая партия + Следующая партия + Перевернуть + В начало + Ход назад + Ход вперёд + В конец + Дальше: + Это просмотр партии. Ходы листаются кнопками ◀ ▶ внизу. + Доска, позиция после %1$s + Доска, начальная позиция + Победили белые + Победили чёрные + Ничья + Не удалось прочитать партию + + Движок + Считаю… + гл. %1$d + пауза + Глубже + Больше линий + Меньше линий + Движок не отвечает + Движок не запускается на этом телефоне + Перезапустить + Линия движка · ход %1$d из %2$d + Закрыть + Движок Stockfish + Оценивает позицию и показывает лучшие ходы. Работает без интернета — нужно один раз скачать. + Размер: %1$d МБ + Сейчас нет Wi-Fi: загрузка пойдёт через мобильный интернет. + Не сейчас + Скачать + Скачано %1$d из %2$d МБ + Отменить + Загрузка отменена + Движок готов + Нет интернета. Подключитесь к сети и попробуйте ещё раз. + Загрузка прервалась. Скачанное сохранено. + Не хватает места: нужно %1$d МБ. + Файл движка повреждён при загрузке. Скачайте его ещё раз. + Повторить + Продолжить + Скачать снова + Понятно + Готовлю движок… + + Настройки + Внешний вид + Доска + Движок + Тема + Как в системе + Светлая + Тёмная + Запись ходов + Латинские буквы (K Q R B N) + Фигурки + Русские буквы (Кр Ф Л С К) + Только вид на экране. В PGN всегда K Q R B N. + Анимация фигур + Стрелка лучшего хода + Вибрация + Stockfish 19 · встроен + Stockfish 19 · скачан + Не скачан · Скачать (%1$d МБ) + Скачивается… %1$d из %2$d МБ + Удалить движок (освободит %1$d МБ) + Удалить движок? Его можно скачать снова. + Удалить + Линий + Время на позицию + %1$d с + 1 мин + Без ограничения + Потоки + Память + %1$d МБ + Движок расходует заряд. Он сам останавливается, когда гаснет экран. + О программе + Stockfish внутри + Stockfish скачивается + Просмотр шахматных баз: PGN, ChessBase, архивы. Файлы только читаются и никогда не меняются. + Лицензии + Сайт и исходный код + diff --git a/androidApp/app/src/main/res/values/strings.xml b/androidApp/app/src/main/res/values/strings.xml new file mode 100644 index 0000000..b8e9f6f --- /dev/null +++ b/androidApp/app/src/main/res/values/strings.xml @@ -0,0 +1,121 @@ + + ChessPenguin + Classic games + Alekhine + + Your databases will be here + Add a PGN file or an archive .zip/.7z — from the phone or a cloud. + Add database + Open sample games + not opened yet · %1$s + + %1$s game + %1$s games + + %1$s · %2$s + Menu + Rename + Remove from the list + The name on the list. The file does not change. + Cancel + Save + Database removed from the list + Undo + Back + + Reading… + Could not open the database + No access to the file. Add it again. + Search + Player, event, year + Nothing found + Clear + + %1$d of %2$d + Previous game + Next game + Flip + To the start + Move back + Move forward + To the end + Next: + This is a game viewer. Moves are stepped with the ◀ ▶ buttons below. + Board, position after %1$s + Board, starting position + White won + Black won + Draw + Could not read the game + + Engine + Thinking… + d. %1$d + paused + Deeper + More lines + Fewer lines + The engine is not answering + The engine does not start on this phone + Restart + Engine line · move %1$d of %2$d + Close + Stockfish engine + Evaluates the position and shows the best moves. Works offline — it only has to be downloaded once. + Size: %1$d MB + No Wi-Fi now: the download will go over mobile data. + Not now + Download + Downloaded %1$d of %2$d MB + Cancel + Download cancelled + The engine is ready + No internet. Connect to a network and try again. + The download was interrupted. What came is kept. + Not enough space: %1$d MB needed. + The engine file was damaged in the download. Download it again. + Try again + Continue + Download again + OK + Preparing the engine… + + Settings + Look + Board + Engine + Theme + As in the system + Light + Dark + Move notation + Latin letters (K Q R B N) + Figurines + Letters of the language + Only how moves look on the screen. PGN always keeps K Q R B N. + Piece animation + Best-move arrow + Vibration + Stockfish 19 · built in + Stockfish 19 · downloaded + Not downloaded · Download (%1$d MB) + Downloading… %1$d of %2$d MB + Delete the engine (frees %1$d MB) + Delete the engine? It can be downloaded again. + Delete + Lines + Time per position + %1$d s + 1 min + No limit + Threads + Memory + %1$d MB + The engine uses the battery. It stops by itself when the screen goes dark. + About + Stockfish built in + Stockfish downloaded in the app + A viewer of chess databases: PGN, ChessBase, archives. Files are only read, never changed. + Licenses + Website and source code + diff --git a/androidApp/app/src/main/res/values/themes.xml b/androidApp/app/src/main/res/values/themes.xml new file mode 100644 index 0000000..f2372f3 --- /dev/null +++ b/androidApp/app/src/main/res/values/themes.xml @@ -0,0 +1,5 @@ + + + +